From 03da62a7941be328350857b736826f3dc1c49937 Mon Sep 17 00:00:00 2001 From: igerber Date: Thu, 26 Nov 2026 09:04:08 -0500 Subject: [PATCH 1/3] fix(stacked_did): complete event windows, and equal cohort shares on 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. --- DEFERRED.md | 2 +- METHODOLOGY_REVIEW.md | 28 +- TODO.md | 2 +- benchmarks/R/benchmark_survey_estimators.R | 59 +- benchmarks/R/generate_cbwsdid_golden.R | 20 + benchmarks/data/cbwsdid_golden.json | 7 + benchmarks/data/stacked_did_golden.json | 72 +- .../data/stacked_did_population_panel.csv | 250 ++-- .../data/stacked_did_sample_share_panel.csv | 250 ++-- .../survey_estimator_validation_golden.json | 12 +- .../python_helpers/dump_stacked_did_panel.py | 80 ++ .../20261126-stacked-complete-windows.md | 91 ++ diff_diff/_reporting_helpers.py | 24 +- diff_diff/guides/llms-autonomous.txt | 4 +- diff_diff/guides/llms-full.txt | 6 +- diff_diff/stacked_did.py | 781 +++++++++---- diff_diff/stacked_did_results.py | 13 +- docs/api/stacked_did.rst | 11 +- docs/choosing_estimator.rst | 6 +- docs/methodology/REGISTRY.md | 38 +- docs/tutorials/13_stacked_did.ipynb | 8 +- tests/test_methodology_stacked_did.py | 46 +- tests/test_stacked_did.py | 1008 ++++++++++++++++- tests/test_target_parameter.py | 36 + 24 files changed, 2191 insertions(+), 663 deletions(-) create mode 100644 benchmarks/python_helpers/dump_stacked_did_panel.py create mode 100644 changelog.d/20261126-stacked-complete-windows.md diff --git a/DEFERRED.md b/DEFERRED.md index 9fa72b865..ce35f453e 100644 --- a/DEFERRED.md +++ b/DEFERRED.md @@ -29,7 +29,7 @@ provenance and AI-review deviation-documentation: a row here (or in | TwoStageDiD honest/pretrends container admission DEFERRED (decision revised from "widen" during the 2(b) PR-3b plan review): analytical fits carry the joint Gardner-GMM event-study covariance (M-092), but the pre-period coefficients are stage-1 residual MEANS — the reference horizon is dropped from the no-intercept Stage-2 design and the zero anchor row appended mechanically — not contrasts against a reference period, while HonestDiD's Δ^RM/Δ^SD arithmetic hard-codes the `delta_0 = 0` normalization into its boundary/bridge constraints. Admission needs either a Stage-2 re-estimation with the reference horizon in the design or a derived residual-to-reference normalization mapping (+ its variance transform). Both consumers' TypeErrors state the deferral; see the REGISTRY TwoStageDiD Note (d). | `diff_diff/honest_did.py`, `diff_diff/pretrends.py`, `diff_diff/two_stage_aggregation.py` | 2(b) PR-3b | Low | | RDDensityTest binomial windows test (R rddensity's `bino=` block: exact binomial tests of side counts in shrinking windows around the cutoff): methodology is sourced from Cattaneo, Frandsen & Titiunik (2015, JCI) and Cattaneo, Frandsen & Vazquez-Bare (2017), NOT the reviewed CJM 2020 paper, so implementing it needs its own paper review(s) first (the 2-PR methodology convention). | `diff_diff/rddensity.py` | rddensity PR-B | Low | | RDDensityTest `rdplotdensity` companion (density plots with pointwise/uniform confidence bands): requires an lpdensity port (Cattaneo, Jansson & Ma 2022 JSS) - a separate estimation surface (evaluation grids, CDF/derivative estimation) well beyond the manipulation test. | `diff_diff/rddensity.py` | rddensity PR-B | Low | -| CBWSDID covariate balancing (`StackedDiD(balance="entropy")`) v1 supports only balanced event windows + `weighting="aggregate"`; unbalanced/ragged panels fail closed (unit-count vs observation-count corrector convention unresolved off balanced panels). Matching-based balancing and the repeated `0→1`/`1→0` episode extension are also deferred. Documented in REGISTRY StackedDiD "Covariate balancing (CBWSDID)" Notes. | `stacked_did.py`, `balancing.py`, REGISTRY | follow-up | Low | +| CBWSDID covariate balancing (`StackedDiD(balance="entropy")`) v1 supports only `weighting="aggregate"`. Matching-based balancing and the repeated `0→1`/`1→0` episode extension are also deferred. Documented in REGISTRY StackedDiD "Covariate balancing (CBWSDID)" Notes. | `stacked_did.py`, `balancing.py`, REGISTRY | follow-up | Low | | dCDH: Phase-1 per-period placebo `DID_M^pl` has NaN SE (no IF derivation for the per-period aggregation path). Multi-horizon placebos (`L_max ≥ 1`) have valid SE. | `chaisemartin_dhaultfoeuille.py` | #294 | Low | | dCDH: survey cell-period allocator's post-period attribution is a library convention, not derived from the observation-level survey linearization. MC coverage is empirically close to nominal; a formal derivation (or covariance-aware two-cell alternative) is deferred. Documented in REGISTRY survey IF expansion Note. | `chaisemartin_dhaultfoeuille.py`, REGISTRY | #408 | Medium | | dCDH by_path: survey-aware backward-horizon (`placebo + predict_het + survey_design`) raises `NotImplementedError` (and `_compute_heterogeneity_test` warn-and-skips to forward-horizon-only heterogeneity) — the Binder TSL cell-period allocator's REGISTRY justification is tied to post-period attribution; backward horizons would put ψ_g mass on a pre-period cell. Needs the pre-period cell allocator derived. | `chaisemartin_dhaultfoeuille.py`, REGISTRY | follow-up | Medium | diff --git a/METHODOLOGY_REVIEW.md b/METHODOLOGY_REVIEW.md index 5f822d586..251f73446 100644 --- a/METHODOLOGY_REVIEW.md +++ b/METHODOLOGY_REVIEW.md @@ -517,8 +517,10 @@ and covariate-adjusted specifications.) 2. **Q-weight computation: event-time-specific for aggregate weighting** (`stacked_did.py`, `_compute_q_weights()`): Changed aggregate Q-weights from unit counts per sub-experiment to observation counts per (event_time, sub_exp), matching R reference `compute_weights()`. - For balanced panels, results are unchanged. For unbalanced panels, weights now adjust for - varying observation density. Population/sample_share retain unit-count formulas (paper notation). + For balanced panels, results are unchanged. Since the complete-window rule (item 6) every + sub-experiment holds the same units at every event time, so the observation counts equal the + paper's unit counts on ragged input panels too. The three schemes now share one formula on + unit masses (item 7). 3. **Anticipation parameter: reference period and dummies** (`stacked_did.py`, `fit()`): Reference period now shifts to `e = -1 - anticipation`. Event-time dummies cover the @@ -530,8 +532,26 @@ and covariate-adjusted specifications.) cohort×event-time interactions. Use CallawaySantAnna or ImputationDiD for cohort-level estimates. 5. **n_sub_experiments metadata** (`stacked_did.py`, `fit()`): Now tracks actual built - sub-experiments, not all events in omega_kappa. Warns if any sub-experiments are empty - after data filtering. + sub-experiments, not all events in omega_kappa. An event whose sub-experiment cannot be + built (no treated unit or no clean control observed at every event time of its window) is + dropped with a warning naming the reason and moves from `groups` to `trimmed_groups`. + +6. **Complete event windows** (`stacked_did.py`, `_build_sub_experiment()`): a unit enters a + sub-experiment only if it is observed at every event time of the window, as in the paper's + stack (Section 5.1). Ragged panels previously returned shifted estimates with no warning, + because Equation 3 contrasts event-time cell means. Incomplete units are excluded with a + warning (refused under `survey_design=`); duplicate `(unit, time)` rows, a missing or + non-integer `time` and a non-integer `first_treat` raise. Deviation from the R reference + code, which keeps incomplete units, documented in REGISTRY.md. + +7. **Equal cohort shares on both arms** (`stacked_did.py`, `_cohort_share_weights()`): the + paper's Table 1 weights treated rows too under population and sample-share weighting; the + library set the treated weight to 1 under every scheme, so those two schemes aggregated the + arms with different shares and the untreated trends did not cancel. Under `survey_design=` + the corrective weights used raw unit counts with the same consequence. One formula now gives + both arms the target share `pi_a`, from survey-weighted unit masses when a survey design is + present, recomputed in each replicate refit. Aggregate weighting without survey weights is + bit-identical. **Outstanding Concerns:** - Population/sample_share Q-weights use paper's unit-count formulas (no R reference to validate) diff --git a/TODO.md b/TODO.md index f8dc96161..c547cd5a0 100644 --- a/TODO.md +++ b/TODO.md @@ -56,7 +56,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 | -| `StackedDiD` returns shifted estimates with NO warning on ragged event windows (found by the sibling audit for the SunAbraham reference fix). On a noiseless panel that the balanced fit recovers exactly (`kappa_pre=2, kappa_post=2`, true effect `2 + 0.5 e`): one cohort missing its `e = -1` rows shifts every event-study row by +0.164 (ATT 2.664 for a true 2.5); a cohort with no pre-treatment rows shifts the post rows by -0.164; ONE missing never-treated observation moves them by 0.003. The `balance="entropy"` path already fails closed on ragged windows (REGISTRY StackedDiD); the default path should either handle unit-level missingness inside a sub-experiment (unit fixed effects, or trimming to units observed over the whole window) or fail closed the same way. Establish what Wing, Freedman and Hollingsworth prescribe before choosing. | `diff_diff/stacked_did.py`, `docs/methodology/REGISTRY.md` | SunAbraham reference 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 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 | | 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/benchmarks/R/benchmark_survey_estimators.R b/benchmarks/R/benchmark_survey_estimators.R index f6384f24a..ae83c8382 100644 --- a/benchmarks/R/benchmark_survey_estimators.R +++ b/benchmarks/R/benchmark_survey_estimators.R @@ -323,40 +323,43 @@ rownames(stacked) <- NULL n_stacked <- nrow(stacked) cat(sprintf(" Stacked dataset: %d observations\n", n_stacked)) -# Step 2: Compute Q-weights (sample_share) -# Count distinct units per sub-experiment -N_D <- sapply(sub_experiments, function(df) length(unique(df$unit[df$D_sa == 1]))) -N_C <- sapply(sub_experiments, function(df) length(unique(df$unit[df$D_sa == 0]))) -N_Omega_D <- sum(N_D) -N_Omega_C <- sum(N_C) -N_grand <- N_Omega_D + N_Omega_C - -cat(sprintf(" N_D per sub-exp: %s\n", paste(N_D, collapse = ", "))) -cat(sprintf(" N_C per sub-exp: %s\n", paste(N_C, collapse = ", "))) -cat(sprintf(" N_Omega_D = %d, N_Omega_C = %d, N_grand = %d\n", - N_Omega_D, N_Omega_C, N_grand)) - -q_control <- setNames(numeric(length(cohorts)), as.character(cohorts)) -for (a_str in names(N_D)) { - n_c <- N_C[a_str] - n_d <- N_D[a_str] - if (n_c == 0 || N_Omega_C == 0) { - q_control[a_str] <- 1.0 - } else { - control_share <- n_c / N_Omega_C - sample_share <- (n_d + n_c) / N_grand - q_control[a_str] <- sample_share / control_share - } +# Step 2: Compute corrective Q-weights (sample_share) +# Both arms must aggregate the sub-experiments with the SAME shares, otherwise +# the untreated trends do not cancel (Wing et al. 2024, Section 5.3). Under a +# survey design the shares are formed from survey-weighted unit masses +# (weights are constant within a unit): +# W_a^D = sum of treated units' weights, W_a^C = sum of controls' weights +# pi_a = (W_a^D + W_a^C) / (W^D + W^C) (sample_share target) +# Q = pi_a / (W_a^D / W^D) for treated rows (Table 1 treatment weight) +# Q = pi_a / (W_a^C / W^C) for control rows +unit_mass <- function(df, d) { + u <- df[df$D_sa == d, ] + u <- u[!duplicated(u$unit), ] + sum(u$weight) } +W_D <- sapply(sub_experiments, unit_mass, d = 1) +W_C <- sapply(sub_experiments, unit_mass, d = 0) +W_Omega_D <- sum(W_D) +W_Omega_C <- sum(W_C) + +cat(sprintf(" W_D per sub-exp: %s\n", paste(sprintf("%.6f", W_D), collapse = ", "))) +cat(sprintf(" W_C per sub-exp: %s\n", paste(sprintf("%.6f", W_C), collapse = ", "))) + +target_share <- (W_D + W_C) / (W_Omega_D + W_Omega_C) +q_treated <- target_share / (W_D / W_Omega_D) +q_control <- target_share / (W_C / W_Omega_C) +cat(sprintf(" Q-weights (treated): %s\n", + paste(sprintf("%s=%.6f", names(q_treated), q_treated), collapse = ", "))) cat(sprintf(" Q-weights (control): %s\n", paste(sprintf("%s=%.6f", names(q_control), q_control), collapse = ", "))) -# Assign Q-weights: treated=1, control=q_control[sub_exp] -stacked$Q_weight <- 1.0 +stacked$Q_weight <- NA_real_ for (a_str in names(q_control)) { - mask <- stacked$sub_exp == as.numeric(a_str) & stacked$D_sa == 0 - stacked$Q_weight[mask] <- q_control[a_str] + in_a <- stacked$sub_exp == as.numeric(a_str) + stacked$Q_weight[in_a & stacked$D_sa == 1] <- q_treated[a_str] + stacked$Q_weight[in_a & stacked$D_sa == 0] <- q_control[a_str] } +stopifnot(!anyNA(stacked$Q_weight)) # Step 3: Compose Q x survey weight, normalize stacked$composed_weight <- stacked$Q_weight * stacked$weight diff --git a/benchmarks/R/generate_cbwsdid_golden.R b/benchmarks/R/generate_cbwsdid_golden.R index 49a6c0087..be9a641dc 100644 --- a/benchmarks/R/generate_cbwsdid_golden.R +++ b/benchmarks/R/generate_cbwsdid_golden.R @@ -33,6 +33,19 @@ m <- cbwsdid( ) qoi <- cbwsdid_qoi(m, type = "dynamic") +# Ragged copy of the same panel: units 1-5 (cohort 5) lose their t = 6 row and +# units 55-59 (never-treated) lose their t = 5 row. cbwsdid builds each +# sub-experiment from the units observed across the whole event window, which is +# the complete-window rule StackedDiD applies; this block pins that agreement. +ragged <- df[!((df$unit %in% 1:5 & df$time == 6) | (df$unit %in% 55:59 & df$time == 5)), ] +m_ragged <- cbwsdid( + data = ragged, y = "y", d = "d", id = c("unit", "time"), + kappa = c(-2, 2), design = "absorbing", post_path = "stable", + refinement.method = "weightit", covs.formula = ~x, + refinement.args = list(method = "ebal"), pooled = TRUE +) +qoi_ragged <- cbwsdid_qoi(m_ragged, type = "dynamic") + golden <- list( meta = list( package = "cbwsdid", @@ -47,6 +60,13 @@ golden <- list( std_error = as.numeric(qoi$std.error) ) ) +golden$dynamic_ragged <- list( + dropped_rows = "unit in 1:5 & time == 6; unit in 55:59 & time == 5", + nobs = as.integer(m_ragged$nobs), + event_time = as.integer(qoi_ragged$et), + estimate = as.numeric(qoi_ragged$estimate), + std_error = as.numeric(qoi_ragged$std.error) +) write_json(golden, out_json, auto_unbox = TRUE, digits = 15, pretty = TRUE) cat("wrote", out_json, "\n") print(data.frame(et = qoi$et, estimate = qoi$estimate, se = qoi$std.error)) diff --git a/benchmarks/data/cbwsdid_golden.json b/benchmarks/data/cbwsdid_golden.json index d26dd41b2..05ed997fd 100644 --- a/benchmarks/data/cbwsdid_golden.json +++ b/benchmarks/data/cbwsdid_golden.json @@ -10,5 +10,12 @@ "event_time": [-2, 0, 1, 2], "estimate": [0.008614905402558678, 1.998507474812239, 2.000435324046538, 1.977837212056277], "std_error": [0.05870423491347857, 0.05704878175034945, 0.1113623933607992, 0.1700804801053713] + }, + "dynamic_ragged": { + "dropped_rows": "unit in 1:5 & time == 6; unit in 55:59 & time == 5", + "nobs": 1185, + "event_time": [-2, 0, 1, 2], + "estimate": [0.01244907143498961, 2.003124493838106, 2.004966724053774, 1.982689462926543], + "std_error": [0.06293179799467032, 0.06042498588243073, 0.1177882246009692, 0.1807105370549422] } } diff --git a/benchmarks/data/stacked_did_golden.json b/benchmarks/data/stacked_did_golden.json index 9431fd27a..af4d01e80 100644 --- a/benchmarks/data/stacked_did_golden.json +++ b/benchmarks/data/stacked_did_golden.json @@ -50,28 +50,28 @@ "anticipation": 0 }, "unit": { - "se_cr1_es": [0.2055876355330852, 0.1872478941072777, 0.1804446738410741, 0.2304790296984253], - "se_cr2_es": [0.2059668479962416, 0.1874175980522263, 0.1798116646995264, 0.2305505425313663], - "dof_bm_es": [41.119689028899977, 41.11968902890009, 41.119689028899977, 41.119689028900027], - "dof_bm_overall": 41.119689028899927, - "se_overall_cr1": 0.1617459655611932, - "se_overall_cr2": 0.1617028169620642, + "se_cr1_es": [0.2104330845719489, 0.1875173523523448, 0.1877504429099093, 0.2373560022194896], + "se_cr2_es": [0.2110024147621817, 0.1877457734530312, 0.187457025340696, 0.2377149110781938], + "dof_bm_es": [39.952957869876066, 39.952957869876059, 39.952957869876123, 39.952957869876137], + "dof_bm_overall": 39.952957869876627, + "se_overall_cr1": 0.1656211836347583, + "se_overall_cr2": 0.1657552718024157, "es_coef_names": ["delta_neg2", "delta_0", "delta_1", "delta_2"], - "se_cr1_intercept": 0.5092056342946343, - "se_cr2_intercept": 0.5122813872396925, - "coef_es": [0.1592684537601917, 2.202558541183745, 2.011016359321843, 2.067053388909866] + "se_cr1_intercept": 0.509205634294654, + "se_cr2_intercept": 0.5122813872397097, + "coef_es": [0.1452678115880203, 2.200492036602629, 1.989446189655178, 2.04089147953348] }, "unit_subexp": { - "se_cr1_es": [0.1931159955471998, 0.1868877212425096, 0.1989124404085452, 0.2350017927907321], - "se_cr2_es": [0.1928712028049674, 0.1865877414187149, 0.1983942713018044, 0.234830388099705], - "dof_bm_es": [46.762096192405849, 46.762096192405608, 46.7620961924057, 46.762096192405586], - "dof_bm_overall": 46.762096192407405, - "se_overall_cr1": 0.1676538114692963, - "se_overall_cr2": 0.1674538455644745, + "se_cr1_es": [0.1982426438441615, 0.1871564334354635, 0.2055322318055454, 0.2417189488500172], + "se_cr2_es": [0.1982396969161469, 0.1869173738247701, 0.205348943198997, 0.2418680166174626], + "dof_bm_es": [45.172510861126533, 45.172510861126462, 45.172510861126462, 45.17251086112654], + "dof_bm_overall": 45.172510861127506, + "se_overall_cr1": 0.1713781577139802, + "se_overall_cr2": 0.1713703577377322, "es_coef_names": ["delta_neg2", "delta_0", "delta_1", "delta_2"], - "se_cr1_intercept": 0.3897579339609716, - "se_cr2_intercept": 0.388735182137397, - "coef_es": [0.1592684537601917, 2.202558541183745, 2.011016359321843, 2.067053388909866] + "se_cr1_intercept": 0.3897579339609886, + "se_cr2_intercept": 0.3887351821374126, + "coef_es": [0.1452678115880203, 2.200492036602629, 1.989446189655178, 2.04089147953348] } }, "anticipation1": { @@ -114,28 +114,28 @@ "anticipation": 0 }, "unit": { - "se_cr1_es": [0.1926945586681986, 0.1774065826127712, 0.179551540289758, 0.2122392518497908], - "se_cr2_es": [0.1924916107265304, 0.1771398302930658, 0.1787869223969842, 0.211801063322419], - "dof_bm_es": [43.616923190028679, 43.616923190028658, 43.616923190028672, 43.616923190028579], - "dof_bm_overall": 43.616923190028821, - "se_overall_cr1": 0.1513357911957259, - "se_overall_cr2": 0.1509672871980841, + "se_cr1_es": [0.1859716240824845, 0.1793979736393216, 0.1703911854993988, 0.20246042480147], + "se_cr2_es": [0.1856359202257969, 0.179335212711467, 0.1694664857444232, 0.2018405688706844], + "dof_bm_es": [39.904751083640249, 39.904751083640136, 39.904751083640285, 39.904751083640235], + "dof_bm_overall": 39.904751083640939, + "se_overall_cr1": 0.1466106324105385, + "se_overall_cr2": 0.1462014521192812, "es_coef_names": ["delta_neg2", "delta_0", "delta_1", "delta_2"], - "se_cr1_intercept": 0.4871327984687643, - "se_cr2_intercept": 0.4880622063955147, - "coef_es": [0.1108321656167259, 2.20608363527907, 1.950880164652265, 2.024566452331055] + "se_cr1_intercept": 0.4871327984687699, + "se_cr2_intercept": 0.4880622063955239, + "coef_es": [0.1330775080120084, 2.20936706338209, 1.985152579007225, 2.066134590751882] }, "unit_subexp": { - "se_cr1_es": [0.1793915271522487, 0.1770839950451901, 0.1982000403327432, 0.217155905557332], - "se_cr2_es": [0.17853000329591, 0.1762727793305481, 0.1973992806659578, 0.2163342225610217], - "dof_bm_es": [50.784770788284384, 50.784770788284128, 50.78477078828427, 50.784770788284149], - "dof_bm_overall": 50.78477078828643, - "se_overall_cr1": 0.1576457481577655, - "se_overall_cr2": 0.1570178024670955, + "se_cr1_es": [0.1721845092660676, 0.1790696737269916, 0.1899807430008049, 0.2076545689640564], + "se_cr2_es": [0.1711158576953478, 0.1784788272454798, 0.1889989475574134, 0.2065924022528671], + "dof_bm_es": [45.565297306304544, 45.565297306304181, 45.565297306304529, 45.56529730630443], + "dof_bm_overall": 45.565297306305098, + "se_overall_cr1": 0.1531369877616297, + "se_overall_cr2": 0.1524412447122756, "es_coef_names": ["delta_neg2", "delta_0", "delta_1", "delta_2"], - "se_cr1_intercept": 0.3600565608113597, - "se_cr2_intercept": 0.3569865903344588, - "coef_es": [0.1108321656167259, 2.20608363527907, 1.950880164652265, 2.024566452331055] + "se_cr1_intercept": 0.3600565608113655, + "se_cr2_intercept": 0.3569865903344603, + "coef_es": [0.1330775080120084, 2.20936706338209, 1.985152579007225, 2.066134590751882] } } } diff --git a/benchmarks/data/stacked_did_population_panel.csv b/benchmarks/data/stacked_did_population_panel.csv index 387f252ea..d9f9bf038 100644 --- a/benchmarks/data/stacked_did_population_panel.csv +++ b/benchmarks/data/stacked_did_population_panel.csv @@ -79,56 +79,56 @@ unit,period,outcome,first_treat,treated,treat,true_effect,pop,_sub_exp,_event_ti 15,3,8.564340753151164,7.0,0,1,0.0,35.65147999343277,3.0,0,0,0.6781447450134034,15_3.0 15,4,8.1815349724801,7.0,0,1,0.0,35.65147999343277,3.0,1,0,0.6781447450134034,15_3.0 15,5,9.311637156674976,7.0,0,1,0.0,35.65147999343277,3.0,2,0,0.6781447450134034,15_3.0 -16,1,7.6836207307333035,3.0,0,1,0.0,93.68673941787888,3.0,-2,1,1.0,16_3.0 -16,2,8.357654569597338,3.0,0,1,0.0,93.68673941787888,3.0,-1,1,1.0,16_3.0 -16,3,10.056550820184588,3.0,1,1,2.0,93.68673941787888,3.0,0,1,1.0,16_3.0 -16,4,10.207378999928212,3.0,1,1,2.0,93.68673941787888,3.0,1,1,1.0,16_3.0 -16,5,10.096882823598278,3.0,1,1,2.0,93.68673941787888,3.0,2,1,1.0,16_3.0 -17,1,8.175606640239206,3.0,0,1,0.0,38.41053736783668,3.0,-2,1,1.0,17_3.0 -17,2,8.600350852687033,3.0,0,1,0.0,38.41053736783668,3.0,-1,1,1.0,17_3.0 -17,3,9.60085063995874,3.0,1,1,2.0,38.41053736783668,3.0,0,1,1.0,17_3.0 -17,4,11.265857113284081,3.0,1,1,2.0,38.41053736783668,3.0,1,1,1.0,17_3.0 -17,5,10.805731826455423,3.0,1,1,2.0,38.41053736783668,3.0,2,1,1.0,17_3.0 -19,1,8.287479893276272,3.0,0,1,0.0,5.016156798575755,3.0,-2,1,1.0,19_3.0 -19,2,8.838449778710965,3.0,0,1,0.0,5.016156798575755,3.0,-1,1,1.0,19_3.0 -19,3,10.301088160788524,3.0,1,1,2.0,5.016156798575755,3.0,0,1,1.0,19_3.0 -19,4,10.193467173412117,3.0,1,1,2.0,5.016156798575755,3.0,1,1,1.0,19_3.0 -19,5,10.93570451644154,3.0,1,1,2.0,5.016156798575755,3.0,2,1,1.0,19_3.0 -20,1,6.608825849966525,3.0,0,1,0.0,30.566903992571508,3.0,-2,1,1.0,20_3.0 -20,2,6.192567902449463,3.0,0,1,0.0,30.566903992571508,3.0,-1,1,1.0,20_3.0 -20,3,8.62011884779571,3.0,1,1,2.0,30.566903992571508,3.0,0,1,1.0,20_3.0 -20,4,9.534699361996061,3.0,1,1,2.0,30.566903992571508,3.0,1,1,1.0,20_3.0 -20,5,8.972714344039472,3.0,1,1,2.0,30.566903992571508,3.0,2,1,1.0,20_3.0 +16,1,7.6836207307333035,3.0,0,1,0.0,93.68673941787888,3.0,-2,1,0.8830009700695357,16_3.0 +16,2,8.357654569597338,3.0,0,1,0.0,93.68673941787888,3.0,-1,1,0.8830009700695357,16_3.0 +16,3,10.056550820184588,3.0,1,1,2.0,93.68673941787888,3.0,0,1,0.8830009700695357,16_3.0 +16,4,10.207378999928212,3.0,1,1,2.0,93.68673941787888,3.0,1,1,0.8830009700695357,16_3.0 +16,5,10.096882823598278,3.0,1,1,2.0,93.68673941787888,3.0,2,1,0.8830009700695357,16_3.0 +17,1,8.175606640239206,3.0,0,1,0.0,38.41053736783668,3.0,-2,1,0.8830009700695357,17_3.0 +17,2,8.600350852687033,3.0,0,1,0.0,38.41053736783668,3.0,-1,1,0.8830009700695357,17_3.0 +17,3,9.60085063995874,3.0,1,1,2.0,38.41053736783668,3.0,0,1,0.8830009700695357,17_3.0 +17,4,11.265857113284081,3.0,1,1,2.0,38.41053736783668,3.0,1,1,0.8830009700695357,17_3.0 +17,5,10.805731826455423,3.0,1,1,2.0,38.41053736783668,3.0,2,1,0.8830009700695357,17_3.0 +19,1,8.287479893276272,3.0,0,1,0.0,5.016156798575755,3.0,-2,1,0.8830009700695357,19_3.0 +19,2,8.838449778710965,3.0,0,1,0.0,5.016156798575755,3.0,-1,1,0.8830009700695357,19_3.0 +19,3,10.301088160788524,3.0,1,1,2.0,5.016156798575755,3.0,0,1,0.8830009700695357,19_3.0 +19,4,10.193467173412117,3.0,1,1,2.0,5.016156798575755,3.0,1,1,0.8830009700695357,19_3.0 +19,5,10.93570451644154,3.0,1,1,2.0,5.016156798575755,3.0,2,1,0.8830009700695357,19_3.0 +20,1,6.608825849966525,3.0,0,1,0.0,30.566903992571508,3.0,-2,1,0.8830009700695357,20_3.0 +20,2,6.192567902449463,3.0,0,1,0.0,30.566903992571508,3.0,-1,1,0.8830009700695357,20_3.0 +20,3,8.62011884779571,3.0,1,1,2.0,30.566903992571508,3.0,0,1,0.8830009700695357,20_3.0 +20,4,9.534699361996061,3.0,1,1,2.0,30.566903992571508,3.0,1,1,0.8830009700695357,20_3.0 +20,5,8.972714344039472,3.0,1,1,2.0,30.566903992571508,3.0,2,1,0.8830009700695357,20_3.0 23,1,11.395156619865356,7.0,0,1,0.0,89.09593115974947,3.0,-2,0,0.6781447450134034,23_3.0 23,2,12.292733093551572,7.0,0,1,0.0,89.09593115974947,3.0,-1,0,0.6781447450134034,23_3.0 23,3,10.987337838152467,7.0,0,1,0.0,89.09593115974947,3.0,0,0,0.6781447450134034,23_3.0 23,4,12.858675160893522,7.0,0,1,0.0,89.09593115974947,3.0,1,0,0.6781447450134034,23_3.0 23,5,11.476064698198886,7.0,0,1,0.0,89.09593115974947,3.0,2,0,0.6781447450134034,23_3.0 -26,1,10.668383782601722,3.0,0,1,0.0,58.952591834886505,3.0,-2,1,1.0,26_3.0 -26,2,10.446234601225571,3.0,0,1,0.0,58.952591834886505,3.0,-1,1,1.0,26_3.0 -26,3,13.556242815369252,3.0,1,1,2.0,58.952591834886505,3.0,0,1,1.0,26_3.0 -26,4,13.576729933292084,3.0,1,1,2.0,58.952591834886505,3.0,1,1,1.0,26_3.0 -26,5,13.922175150825803,3.0,1,1,2.0,58.952591834886505,3.0,2,1,1.0,26_3.0 +26,1,10.668383782601722,3.0,0,1,0.0,58.952591834886505,3.0,-2,1,0.8830009700695357,26_3.0 +26,2,10.446234601225571,3.0,0,1,0.0,58.952591834886505,3.0,-1,1,0.8830009700695357,26_3.0 +26,3,13.556242815369252,3.0,1,1,2.0,58.952591834886505,3.0,0,1,0.8830009700695357,26_3.0 +26,4,13.576729933292084,3.0,1,1,2.0,58.952591834886505,3.0,1,1,0.8830009700695357,26_3.0 +26,5,13.922175150825803,3.0,1,1,2.0,58.952591834886505,3.0,2,1,0.8830009700695357,26_3.0 27,1,8.580588297539316,7.0,0,1,0.0,60.3140426816271,3.0,-2,0,0.6781447450134034,27_3.0 27,2,9.053926240501355,7.0,0,1,0.0,60.3140426816271,3.0,-1,0,0.6781447450134034,27_3.0 27,3,8.688974179281848,7.0,0,1,0.0,60.3140426816271,3.0,0,0,0.6781447450134034,27_3.0 27,4,7.928575988525038,7.0,0,1,0.0,60.3140426816271,3.0,1,0,0.6781447450134034,27_3.0 27,5,9.170520905605873,7.0,0,1,0.0,60.3140426816271,3.0,2,0,0.6781447450134034,27_3.0 -28,1,9.371848258038815,3.0,0,1,0.0,65.91287985914114,3.0,-2,1,1.0,28_3.0 -28,2,9.154422149577181,3.0,0,1,0.0,65.91287985914114,3.0,-1,1,1.0,28_3.0 -28,3,11.965196547208972,3.0,1,1,2.0,65.91287985914114,3.0,0,1,1.0,28_3.0 -28,4,11.302065396349953,3.0,1,1,2.0,65.91287985914114,3.0,1,1,1.0,28_3.0 -28,5,11.589704550706,3.0,1,1,2.0,65.91287985914114,3.0,2,1,1.0,28_3.0 -29,1,8.985010266355241,3.0,0,1,0.0,51.616916159081924,3.0,-2,1,1.0,29_3.0 -29,2,8.92226436961385,3.0,0,1,0.0,51.616916159081924,3.0,-1,1,1.0,29_3.0 -29,3,11.587183906367892,3.0,1,1,2.0,51.616916159081924,3.0,0,1,1.0,29_3.0 -29,4,11.061585148973101,3.0,1,1,2.0,51.616916159081924,3.0,1,1,1.0,29_3.0 -29,5,11.32705363934025,3.0,1,1,2.0,51.616916159081924,3.0,2,1,1.0,29_3.0 -30,1,8.376287388505098,3.0,0,1,0.0,20.174295613318602,3.0,-2,1,1.0,30_3.0 -30,2,8.657693030574496,3.0,0,1,0.0,20.174295613318602,3.0,-1,1,1.0,30_3.0 -30,3,10.18781936742593,3.0,1,1,2.0,20.174295613318602,3.0,0,1,1.0,30_3.0 -30,4,11.000739934625502,3.0,1,1,2.0,20.174295613318602,3.0,1,1,1.0,30_3.0 -30,5,10.282065104573295,3.0,1,1,2.0,20.174295613318602,3.0,2,1,1.0,30_3.0 +28,1,9.371848258038815,3.0,0,1,0.0,65.91287985914114,3.0,-2,1,0.8830009700695357,28_3.0 +28,2,9.154422149577181,3.0,0,1,0.0,65.91287985914114,3.0,-1,1,0.8830009700695357,28_3.0 +28,3,11.965196547208972,3.0,1,1,2.0,65.91287985914114,3.0,0,1,0.8830009700695357,28_3.0 +28,4,11.302065396349953,3.0,1,1,2.0,65.91287985914114,3.0,1,1,0.8830009700695357,28_3.0 +28,5,11.589704550706,3.0,1,1,2.0,65.91287985914114,3.0,2,1,0.8830009700695357,28_3.0 +29,1,8.985010266355241,3.0,0,1,0.0,51.616916159081924,3.0,-2,1,0.8830009700695357,29_3.0 +29,2,8.92226436961385,3.0,0,1,0.0,51.616916159081924,3.0,-1,1,0.8830009700695357,29_3.0 +29,3,11.587183906367892,3.0,1,1,2.0,51.616916159081924,3.0,0,1,0.8830009700695357,29_3.0 +29,4,11.061585148973101,3.0,1,1,2.0,51.616916159081924,3.0,1,1,0.8830009700695357,29_3.0 +29,5,11.32705363934025,3.0,1,1,2.0,51.616916159081924,3.0,2,1,0.8830009700695357,29_3.0 +30,1,8.376287388505098,3.0,0,1,0.0,20.174295613318602,3.0,-2,1,0.8830009700695357,30_3.0 +30,2,8.657693030574496,3.0,0,1,0.0,20.174295613318602,3.0,-1,1,0.8830009700695357,30_3.0 +30,3,10.18781936742593,3.0,1,1,2.0,20.174295613318602,3.0,0,1,0.8830009700695357,30_3.0 +30,4,11.000739934625502,3.0,1,1,2.0,20.174295613318602,3.0,1,1,0.8830009700695357,30_3.0 +30,5,10.282065104573295,3.0,1,1,2.0,20.174295613318602,3.0,2,1,0.8830009700695357,30_3.0 33,1,11.57454492762582,7.0,0,1,0.0,10.424090898727023,3.0,-2,0,0.6781447450134034,33_3.0 33,2,11.691765125046665,7.0,0,1,0.0,10.424090898727023,3.0,-1,0,0.6781447450134034,33_3.0 33,3,11.84979372696007,7.0,0,1,0.0,10.424090898727023,3.0,0,0,0.6781447450134034,33_3.0 @@ -139,36 +139,36 @@ unit,period,outcome,first_treat,treated,treat,true_effect,pop,_sub_exp,_event_ti 34,3,12.803090421682993,7.0,0,1,0.0,12.1998072950007,3.0,0,0,0.6781447450134034,34_3.0 34,4,13.544985407250604,7.0,0,1,0.0,12.1998072950007,3.0,1,0,0.6781447450134034,34_3.0 34,5,13.17341536766152,7.0,0,1,0.0,12.1998072950007,3.0,2,0,0.6781447450134034,34_3.0 -35,1,13.198034881842501,3.0,0,1,0.0,28.77799746301179,3.0,-2,1,1.0,35_3.0 -35,2,13.13803314498448,3.0,0,1,0.0,28.77799746301179,3.0,-1,1,1.0,35_3.0 -35,3,14.775491475016876,3.0,1,1,2.0,28.77799746301179,3.0,0,1,1.0,35_3.0 -35,4,14.755631298179171,3.0,1,1,2.0,28.77799746301179,3.0,1,1,1.0,35_3.0 -35,5,15.82726562084955,3.0,1,1,2.0,28.77799746301179,3.0,2,1,1.0,35_3.0 -36,1,7.2152253987939226,3.0,0,1,0.0,59.65911885671169,3.0,-2,1,1.0,36_3.0 -36,2,6.610853150968622,3.0,0,1,0.0,59.65911885671169,3.0,-1,1,1.0,36_3.0 -36,3,8.853563997233643,3.0,1,1,2.0,59.65911885671169,3.0,0,1,1.0,36_3.0 -36,4,9.09329932509169,3.0,1,1,2.0,59.65911885671169,3.0,1,1,1.0,36_3.0 -36,5,9.298377296285087,3.0,1,1,2.0,59.65911885671169,3.0,2,1,1.0,36_3.0 +35,1,13.198034881842501,3.0,0,1,0.0,28.77799746301179,3.0,-2,1,0.8830009700695357,35_3.0 +35,2,13.13803314498448,3.0,0,1,0.0,28.77799746301179,3.0,-1,1,0.8830009700695357,35_3.0 +35,3,14.775491475016876,3.0,1,1,2.0,28.77799746301179,3.0,0,1,0.8830009700695357,35_3.0 +35,4,14.755631298179171,3.0,1,1,2.0,28.77799746301179,3.0,1,1,0.8830009700695357,35_3.0 +35,5,15.82726562084955,3.0,1,1,2.0,28.77799746301179,3.0,2,1,0.8830009700695357,35_3.0 +36,1,7.2152253987939226,3.0,0,1,0.0,59.65911885671169,3.0,-2,1,0.8830009700695357,36_3.0 +36,2,6.610853150968622,3.0,0,1,0.0,59.65911885671169,3.0,-1,1,0.8830009700695357,36_3.0 +36,3,8.853563997233643,3.0,1,1,2.0,59.65911885671169,3.0,0,1,0.8830009700695357,36_3.0 +36,4,9.09329932509169,3.0,1,1,2.0,59.65911885671169,3.0,1,1,0.8830009700695357,36_3.0 +36,5,9.298377296285087,3.0,1,1,2.0,59.65911885671169,3.0,2,1,0.8830009700695357,36_3.0 37,1,10.146958297869952,7.0,0,1,0.0,34.979030166470274,3.0,-2,0,0.6781447450134034,37_3.0 37,2,9.060497069998855,7.0,0,1,0.0,34.979030166470274,3.0,-1,0,0.6781447450134034,37_3.0 37,3,9.318388049432945,7.0,0,1,0.0,34.979030166470274,3.0,0,0,0.6781447450134034,37_3.0 37,4,9.26097646005531,7.0,0,1,0.0,34.979030166470274,3.0,1,0,0.6781447450134034,37_3.0 37,5,8.919210921226544,7.0,0,1,0.0,34.979030166470274,3.0,2,0,0.6781447450134034,37_3.0 -39,1,12.353298527293795,3.0,0,1,0.0,96.57316078735487,3.0,-2,1,1.0,39_3.0 -39,2,12.242756403937744,3.0,0,1,0.0,96.57316078735487,3.0,-1,1,1.0,39_3.0 -39,3,15.149617439612653,3.0,1,1,2.0,96.57316078735487,3.0,0,1,1.0,39_3.0 -39,4,14.088452790656742,3.0,1,1,2.0,96.57316078735487,3.0,1,1,1.0,39_3.0 -39,5,14.060806514376624,3.0,1,1,2.0,96.57316078735487,3.0,2,1,1.0,39_3.0 +39,1,12.353298527293795,3.0,0,1,0.0,96.57316078735487,3.0,-2,1,0.8830009700695357,39_3.0 +39,2,12.242756403937744,3.0,0,1,0.0,96.57316078735487,3.0,-1,1,0.8830009700695357,39_3.0 +39,3,15.149617439612653,3.0,1,1,2.0,96.57316078735487,3.0,0,1,0.8830009700695357,39_3.0 +39,4,14.088452790656742,3.0,1,1,2.0,96.57316078735487,3.0,1,1,0.8830009700695357,39_3.0 +39,5,14.060806514376624,3.0,1,1,2.0,96.57316078735487,3.0,2,1,0.8830009700695357,39_3.0 40,1,7.342148190809627,7.0,0,1,0.0,33.85216111249103,3.0,-2,0,0.6781447450134034,40_3.0 40,2,8.356636279545437,7.0,0,1,0.0,33.85216111249103,3.0,-1,0,0.6781447450134034,40_3.0 40,3,8.853341199215448,7.0,0,1,0.0,33.85216111249103,3.0,0,0,0.6781447450134034,40_3.0 40,4,7.646273376822638,7.0,0,1,0.0,33.85216111249103,3.0,1,0,0.6781447450134034,40_3.0 40,5,7.959815635944495,7.0,0,1,0.0,33.85216111249103,3.0,2,0,0.6781447450134034,40_3.0 -41,1,12.529859573199765,3.0,0,1,0.0,24.392128963266284,3.0,-2,1,1.0,41_3.0 -41,2,12.359862327664574,3.0,0,1,0.0,24.392128963266284,3.0,-1,1,1.0,41_3.0 -41,3,14.594595526225248,3.0,1,1,2.0,24.392128963266284,3.0,0,1,1.0,41_3.0 -41,4,14.627150386514797,3.0,1,1,2.0,24.392128963266284,3.0,1,1,1.0,41_3.0 -41,5,15.438306775111634,3.0,1,1,2.0,24.392128963266284,3.0,2,1,1.0,41_3.0 +41,1,12.529859573199765,3.0,0,1,0.0,24.392128963266284,3.0,-2,1,0.8830009700695357,41_3.0 +41,2,12.359862327664574,3.0,0,1,0.0,24.392128963266284,3.0,-1,1,0.8830009700695357,41_3.0 +41,3,14.594595526225248,3.0,1,1,2.0,24.392128963266284,3.0,0,1,0.8830009700695357,41_3.0 +41,4,14.627150386514797,3.0,1,1,2.0,24.392128963266284,3.0,1,1,0.8830009700695357,41_3.0 +41,5,15.438306775111634,3.0,1,1,2.0,24.392128963266284,3.0,2,1,0.8830009700695357,41_3.0 43,1,11.589875560059742,7.0,0,1,0.0,57.69391670715631,3.0,-2,0,0.6781447450134034,43_3.0 43,2,11.566062741673996,7.0,0,1,0.0,57.69391670715631,3.0,-1,0,0.6781447450134034,43_3.0 43,3,11.081605645195344,7.0,0,1,0.0,57.69391670715631,3.0,0,0,0.6781447450134034,43_3.0 @@ -259,68 +259,68 @@ unit,period,outcome,first_treat,treated,treat,true_effect,pop,_sub_exp,_event_ti 14,5,9.254403864326273,inf,0,0,0.0,27.75690150753168,5.0,0,0,1.5364254249776612,14_5.0 14,6,9.330459677777796,inf,0,0,0.0,27.75690150753168,5.0,1,0,1.5364254249776612,14_5.0 14,7,9.00828730479836,inf,0,0,0.0,27.75690150753168,5.0,2,0,1.5364254249776612,14_5.0 -18,3,8.750153667767103,5.0,0,1,0.0,77.6902716711911,5.0,-2,1,1.0,18_5.0 -18,4,10.369418029568877,5.0,0,1,0.0,77.6902716711911,5.0,-1,1,1.0,18_5.0 -18,5,11.814853522513967,5.0,1,1,2.0,77.6902716711911,5.0,0,1,1.0,18_5.0 -18,6,11.880991600710768,5.0,1,1,2.0,77.6902716711911,5.0,1,1,1.0,18_5.0 -18,7,12.084939640054936,5.0,1,1,2.0,77.6902716711911,5.0,2,1,1.0,18_5.0 -21,3,11.130313135937552,5.0,0,1,0.0,70.55652351914023,5.0,-2,1,1.0,21_5.0 -21,4,11.783557955755562,5.0,0,1,0.0,70.55652351914023,5.0,-1,1,1.0,21_5.0 -21,5,13.932178697330485,5.0,1,1,2.0,70.55652351914023,5.0,0,1,1.0,21_5.0 -21,6,13.311045276660398,5.0,1,1,2.0,70.55652351914023,5.0,1,1,1.0,21_5.0 -21,7,12.672260765381138,5.0,1,1,2.0,70.55652351914023,5.0,2,1,1.0,21_5.0 -22,3,10.370162504733846,5.0,0,1,0.0,45.77300946437004,5.0,-2,1,1.0,22_5.0 -22,4,10.130795877474743,5.0,0,1,0.0,45.77300946437004,5.0,-1,1,1.0,22_5.0 -22,5,13.327665186472212,5.0,1,1,2.0,45.77300946437004,5.0,0,1,1.0,22_5.0 -22,6,14.006133024294815,5.0,1,1,2.0,45.77300946437004,5.0,1,1,1.0,22_5.0 -22,7,11.997025447630525,5.0,1,1,2.0,45.77300946437004,5.0,2,1,1.0,22_5.0 -24,3,12.216528415765985,5.0,0,1,0.0,44.074903125040095,5.0,-2,1,1.0,24_5.0 -24,4,11.844123402747586,5.0,0,1,0.0,44.074903125040095,5.0,-1,1,1.0,24_5.0 -24,5,13.783296021523771,5.0,1,1,2.0,44.074903125040095,5.0,0,1,1.0,24_5.0 -24,6,13.374452489632073,5.0,1,1,2.0,44.074903125040095,5.0,1,1,1.0,24_5.0 -24,7,14.257003341404754,5.0,1,1,2.0,44.074903125040095,5.0,2,1,1.0,24_5.0 -25,3,12.376139740663152,5.0,0,1,0.0,62.73241976658182,5.0,-2,1,1.0,25_5.0 -25,4,12.451932231507831,5.0,0,1,0.0,62.73241976658182,5.0,-1,1,1.0,25_5.0 -25,5,14.40345513916028,5.0,1,1,2.0,62.73241976658182,5.0,0,1,1.0,25_5.0 -25,6,15.399316274400507,5.0,1,1,2.0,62.73241976658182,5.0,1,1,1.0,25_5.0 -25,7,14.121018820768782,5.0,1,1,2.0,62.73241976658182,5.0,2,1,1.0,25_5.0 -31,3,5.699685628062173,5.0,0,1,0.0,7.827770838902669,5.0,-2,1,1.0,31_5.0 -31,4,6.640244849690189,5.0,0,1,0.0,7.827770838902669,5.0,-1,1,1.0,31_5.0 -31,5,8.80287858433971,5.0,1,1,2.0,7.827770838902669,5.0,0,1,1.0,31_5.0 -31,6,7.478011213888342,5.0,1,1,2.0,7.827770838902669,5.0,1,1,1.0,31_5.0 -31,7,7.785449789009849,5.0,1,1,2.0,7.827770838902669,5.0,2,1,1.0,31_5.0 -32,3,13.145351442221973,5.0,0,1,0.0,25.952523503204013,5.0,-2,1,1.0,32_5.0 -32,4,14.213246370804844,5.0,0,1,0.0,25.952523503204013,5.0,-1,1,1.0,32_5.0 -32,5,15.673222444412447,5.0,1,1,2.0,25.952523503204013,5.0,0,1,1.0,32_5.0 -32,6,14.660677350520446,5.0,1,1,2.0,25.952523503204013,5.0,1,1,1.0,32_5.0 -32,7,14.475511437433273,5.0,1,1,2.0,25.952523503204013,5.0,2,1,1.0,32_5.0 -38,3,9.198240092902193,5.0,0,1,0.0,78.00707396817663,5.0,-2,1,1.0,38_5.0 -38,4,8.489100540648527,5.0,0,1,0.0,78.00707396817663,5.0,-1,1,1.0,38_5.0 -38,5,11.45417220010028,5.0,1,1,2.0,78.00707396817663,5.0,0,1,1.0,38_5.0 -38,6,10.634610329560985,5.0,1,1,2.0,78.00707396817663,5.0,1,1,1.0,38_5.0 -38,7,12.158628732093817,5.0,1,1,2.0,78.00707396817663,5.0,2,1,1.0,38_5.0 -42,3,9.165900951128542,5.0,0,1,0.0,69.09529934600081,5.0,-2,1,1.0,42_5.0 -42,4,9.836927314238459,5.0,0,1,0.0,69.09529934600081,5.0,-1,1,1.0,42_5.0 -42,5,11.893273621648287,5.0,1,1,2.0,69.09529934600081,5.0,0,1,1.0,42_5.0 -42,6,10.811622966738568,5.0,1,1,2.0,69.09529934600081,5.0,1,1,1.0,42_5.0 -42,7,12.387788948877349,5.0,1,1,2.0,69.09529934600081,5.0,2,1,1.0,42_5.0 -44,3,13.218744977031886,5.0,0,1,0.0,77.18615844224195,5.0,-2,1,1.0,44_5.0 -44,4,13.584858653200563,5.0,0,1,0.0,77.18615844224195,5.0,-1,1,1.0,44_5.0 -44,5,15.869766671523484,5.0,1,1,2.0,77.18615844224195,5.0,0,1,1.0,44_5.0 -44,6,15.606050081127213,5.0,1,1,2.0,77.18615844224195,5.0,1,1,1.0,44_5.0 -44,7,14.741953786805245,5.0,1,1,2.0,77.18615844224195,5.0,2,1,1.0,44_5.0 -47,3,11.405672205690639,5.0,0,1,0.0,91.1995253876107,5.0,-2,1,1.0,47_5.0 -47,4,10.327840224798175,5.0,0,1,0.0,91.1995253876107,5.0,-1,1,1.0,47_5.0 -47,5,12.972063268138358,5.0,1,1,2.0,91.1995253876107,5.0,0,1,1.0,47_5.0 -47,6,13.3375192672357,5.0,1,1,2.0,91.1995253876107,5.0,1,1,1.0,47_5.0 -47,7,13.949251964590784,5.0,1,1,2.0,91.1995253876107,5.0,2,1,1.0,47_5.0 -48,3,10.036462523941848,5.0,0,1,0.0,57.72070965802602,5.0,-2,1,1.0,48_5.0 -48,4,10.557346448715858,5.0,0,1,0.0,57.72070965802602,5.0,-1,1,1.0,48_5.0 -48,5,11.320126492133841,5.0,1,1,2.0,57.72070965802602,5.0,0,1,1.0,48_5.0 -48,6,12.376923426574146,5.0,1,1,2.0,57.72070965802602,5.0,1,1,1.0,48_5.0 -48,7,12.52530519550149,5.0,1,1,2.0,57.72070965802602,5.0,2,1,1.0,48_5.0 -49,3,9.93003674799368,5.0,0,1,0.0,72.11274206787415,5.0,-2,1,1.0,49_5.0 -49,4,9.728215912860774,5.0,0,1,0.0,72.11274206787415,5.0,-1,1,1.0,49_5.0 -49,5,12.103403154230948,5.0,1,1,2.0,72.11274206787415,5.0,0,1,1.0,49_5.0 -49,6,11.538525743370705,5.0,1,1,2.0,72.11274206787415,5.0,1,1,1.0,49_5.0 -49,7,12.200705227099014,5.0,1,1,2.0,72.11274206787415,5.0,2,1,1.0,49_5.0 +18,3,8.750153667767103,5.0,0,1,0.0,77.6902716711911,5.0,-2,1,1.1079991045511979,18_5.0 +18,4,10.369418029568877,5.0,0,1,0.0,77.6902716711911,5.0,-1,1,1.1079991045511979,18_5.0 +18,5,11.814853522513967,5.0,1,1,2.0,77.6902716711911,5.0,0,1,1.1079991045511979,18_5.0 +18,6,11.880991600710768,5.0,1,1,2.0,77.6902716711911,5.0,1,1,1.1079991045511979,18_5.0 +18,7,12.084939640054936,5.0,1,1,2.0,77.6902716711911,5.0,2,1,1.1079991045511979,18_5.0 +21,3,11.130313135937552,5.0,0,1,0.0,70.55652351914023,5.0,-2,1,1.1079991045511979,21_5.0 +21,4,11.783557955755562,5.0,0,1,0.0,70.55652351914023,5.0,-1,1,1.1079991045511979,21_5.0 +21,5,13.932178697330485,5.0,1,1,2.0,70.55652351914023,5.0,0,1,1.1079991045511979,21_5.0 +21,6,13.311045276660398,5.0,1,1,2.0,70.55652351914023,5.0,1,1,1.1079991045511979,21_5.0 +21,7,12.672260765381138,5.0,1,1,2.0,70.55652351914023,5.0,2,1,1.1079991045511979,21_5.0 +22,3,10.370162504733846,5.0,0,1,0.0,45.77300946437004,5.0,-2,1,1.1079991045511979,22_5.0 +22,4,10.130795877474743,5.0,0,1,0.0,45.77300946437004,5.0,-1,1,1.1079991045511979,22_5.0 +22,5,13.327665186472212,5.0,1,1,2.0,45.77300946437004,5.0,0,1,1.1079991045511979,22_5.0 +22,6,14.006133024294815,5.0,1,1,2.0,45.77300946437004,5.0,1,1,1.1079991045511979,22_5.0 +22,7,11.997025447630525,5.0,1,1,2.0,45.77300946437004,5.0,2,1,1.1079991045511979,22_5.0 +24,3,12.216528415765985,5.0,0,1,0.0,44.074903125040095,5.0,-2,1,1.1079991045511979,24_5.0 +24,4,11.844123402747586,5.0,0,1,0.0,44.074903125040095,5.0,-1,1,1.1079991045511979,24_5.0 +24,5,13.783296021523771,5.0,1,1,2.0,44.074903125040095,5.0,0,1,1.1079991045511979,24_5.0 +24,6,13.374452489632073,5.0,1,1,2.0,44.074903125040095,5.0,1,1,1.1079991045511979,24_5.0 +24,7,14.257003341404754,5.0,1,1,2.0,44.074903125040095,5.0,2,1,1.1079991045511979,24_5.0 +25,3,12.376139740663152,5.0,0,1,0.0,62.73241976658182,5.0,-2,1,1.1079991045511979,25_5.0 +25,4,12.451932231507831,5.0,0,1,0.0,62.73241976658182,5.0,-1,1,1.1079991045511979,25_5.0 +25,5,14.40345513916028,5.0,1,1,2.0,62.73241976658182,5.0,0,1,1.1079991045511979,25_5.0 +25,6,15.399316274400507,5.0,1,1,2.0,62.73241976658182,5.0,1,1,1.1079991045511979,25_5.0 +25,7,14.121018820768782,5.0,1,1,2.0,62.73241976658182,5.0,2,1,1.1079991045511979,25_5.0 +31,3,5.699685628062173,5.0,0,1,0.0,7.827770838902669,5.0,-2,1,1.1079991045511979,31_5.0 +31,4,6.640244849690189,5.0,0,1,0.0,7.827770838902669,5.0,-1,1,1.1079991045511979,31_5.0 +31,5,8.80287858433971,5.0,1,1,2.0,7.827770838902669,5.0,0,1,1.1079991045511979,31_5.0 +31,6,7.478011213888342,5.0,1,1,2.0,7.827770838902669,5.0,1,1,1.1079991045511979,31_5.0 +31,7,7.785449789009849,5.0,1,1,2.0,7.827770838902669,5.0,2,1,1.1079991045511979,31_5.0 +32,3,13.145351442221973,5.0,0,1,0.0,25.952523503204013,5.0,-2,1,1.1079991045511979,32_5.0 +32,4,14.213246370804844,5.0,0,1,0.0,25.952523503204013,5.0,-1,1,1.1079991045511979,32_5.0 +32,5,15.673222444412447,5.0,1,1,2.0,25.952523503204013,5.0,0,1,1.1079991045511979,32_5.0 +32,6,14.660677350520446,5.0,1,1,2.0,25.952523503204013,5.0,1,1,1.1079991045511979,32_5.0 +32,7,14.475511437433273,5.0,1,1,2.0,25.952523503204013,5.0,2,1,1.1079991045511979,32_5.0 +38,3,9.198240092902193,5.0,0,1,0.0,78.00707396817663,5.0,-2,1,1.1079991045511979,38_5.0 +38,4,8.489100540648527,5.0,0,1,0.0,78.00707396817663,5.0,-1,1,1.1079991045511979,38_5.0 +38,5,11.45417220010028,5.0,1,1,2.0,78.00707396817663,5.0,0,1,1.1079991045511979,38_5.0 +38,6,10.634610329560985,5.0,1,1,2.0,78.00707396817663,5.0,1,1,1.1079991045511979,38_5.0 +38,7,12.158628732093817,5.0,1,1,2.0,78.00707396817663,5.0,2,1,1.1079991045511979,38_5.0 +42,3,9.165900951128542,5.0,0,1,0.0,69.09529934600081,5.0,-2,1,1.1079991045511979,42_5.0 +42,4,9.836927314238459,5.0,0,1,0.0,69.09529934600081,5.0,-1,1,1.1079991045511979,42_5.0 +42,5,11.893273621648287,5.0,1,1,2.0,69.09529934600081,5.0,0,1,1.1079991045511979,42_5.0 +42,6,10.811622966738568,5.0,1,1,2.0,69.09529934600081,5.0,1,1,1.1079991045511979,42_5.0 +42,7,12.387788948877349,5.0,1,1,2.0,69.09529934600081,5.0,2,1,1.1079991045511979,42_5.0 +44,3,13.218744977031886,5.0,0,1,0.0,77.18615844224195,5.0,-2,1,1.1079991045511979,44_5.0 +44,4,13.584858653200563,5.0,0,1,0.0,77.18615844224195,5.0,-1,1,1.1079991045511979,44_5.0 +44,5,15.869766671523484,5.0,1,1,2.0,77.18615844224195,5.0,0,1,1.1079991045511979,44_5.0 +44,6,15.606050081127213,5.0,1,1,2.0,77.18615844224195,5.0,1,1,1.1079991045511979,44_5.0 +44,7,14.741953786805245,5.0,1,1,2.0,77.18615844224195,5.0,2,1,1.1079991045511979,44_5.0 +47,3,11.405672205690639,5.0,0,1,0.0,91.1995253876107,5.0,-2,1,1.1079991045511979,47_5.0 +47,4,10.327840224798175,5.0,0,1,0.0,91.1995253876107,5.0,-1,1,1.1079991045511979,47_5.0 +47,5,12.972063268138358,5.0,1,1,2.0,91.1995253876107,5.0,0,1,1.1079991045511979,47_5.0 +47,6,13.3375192672357,5.0,1,1,2.0,91.1995253876107,5.0,1,1,1.1079991045511979,47_5.0 +47,7,13.949251964590784,5.0,1,1,2.0,91.1995253876107,5.0,2,1,1.1079991045511979,47_5.0 +48,3,10.036462523941848,5.0,0,1,0.0,57.72070965802602,5.0,-2,1,1.1079991045511979,48_5.0 +48,4,10.557346448715858,5.0,0,1,0.0,57.72070965802602,5.0,-1,1,1.1079991045511979,48_5.0 +48,5,11.320126492133841,5.0,1,1,2.0,57.72070965802602,5.0,0,1,1.1079991045511979,48_5.0 +48,6,12.376923426574146,5.0,1,1,2.0,57.72070965802602,5.0,1,1,1.1079991045511979,48_5.0 +48,7,12.52530519550149,5.0,1,1,2.0,57.72070965802602,5.0,2,1,1.1079991045511979,48_5.0 +49,3,9.93003674799368,5.0,0,1,0.0,72.11274206787415,5.0,-2,1,1.1079991045511979,49_5.0 +49,4,9.728215912860774,5.0,0,1,0.0,72.11274206787415,5.0,-1,1,1.1079991045511979,49_5.0 +49,5,12.103403154230948,5.0,1,1,2.0,72.11274206787415,5.0,0,1,1.1079991045511979,49_5.0 +49,6,11.538525743370705,5.0,1,1,2.0,72.11274206787415,5.0,1,1,1.1079991045511979,49_5.0 +49,7,12.200705227099014,5.0,1,1,2.0,72.11274206787415,5.0,2,1,1.1079991045511979,49_5.0 diff --git a/benchmarks/data/stacked_did_sample_share_panel.csv b/benchmarks/data/stacked_did_sample_share_panel.csv index 1166ba816..9815ee54c 100644 --- a/benchmarks/data/stacked_did_sample_share_panel.csv +++ b/benchmarks/data/stacked_did_sample_share_panel.csv @@ -79,56 +79,56 @@ unit,period,outcome,first_treat,treated,treat,true_effect,_sub_exp,_event_time,_ 15,3,8.564340753151164,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,15_3.0 15,4,8.1815349724801,7.0,0,1,0.0,3.0,1,0,0.9107692307692308,15_3.0 15,5,9.311637156674976,7.0,0,1,0.0,3.0,2,0,0.9107692307692308,15_3.0 -16,1,7.6836207307333035,3.0,0,1,0.0,3.0,-2,1,1.0,16_3.0 -16,2,8.357654569597338,3.0,0,1,0.0,3.0,-1,1,1.0,16_3.0 -16,3,10.056550820184588,3.0,1,1,2.0,3.0,0,1,1.0,16_3.0 -16,4,10.207378999928212,3.0,1,1,2.0,3.0,1,1,1.0,16_3.0 -16,5,10.096882823598278,3.0,1,1,2.0,3.0,2,1,1.0,16_3.0 -17,1,8.175606640239206,3.0,0,1,0.0,3.0,-2,1,1.0,17_3.0 -17,2,8.600350852687033,3.0,0,1,0.0,3.0,-1,1,1.0,17_3.0 -17,3,9.60085063995874,3.0,1,1,2.0,3.0,0,1,1.0,17_3.0 -17,4,11.265857113284081,3.0,1,1,2.0,3.0,1,1,1.0,17_3.0 -17,5,10.805731826455423,3.0,1,1,2.0,3.0,2,1,1.0,17_3.0 -19,1,8.287479893276272,3.0,0,1,0.0,3.0,-2,1,1.0,19_3.0 -19,2,8.838449778710965,3.0,0,1,0.0,3.0,-1,1,1.0,19_3.0 -19,3,10.301088160788524,3.0,1,1,2.0,3.0,0,1,1.0,19_3.0 -19,4,10.193467173412117,3.0,1,1,2.0,3.0,1,1,1.0,19_3.0 -19,5,10.93570451644154,3.0,1,1,2.0,3.0,2,1,1.0,19_3.0 -20,1,6.608825849966525,3.0,0,1,0.0,3.0,-2,1,1.0,20_3.0 -20,2,6.192567902449463,3.0,0,1,0.0,3.0,-1,1,1.0,20_3.0 -20,3,8.62011884779571,3.0,1,1,2.0,3.0,0,1,1.0,20_3.0 -20,4,9.534699361996061,3.0,1,1,2.0,3.0,1,1,1.0,20_3.0 -20,5,8.972714344039472,3.0,1,1,2.0,3.0,2,1,1.0,20_3.0 +16,1,7.6836207307333035,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,16_3.0 +16,2,8.357654569597338,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,16_3.0 +16,3,10.056550820184588,3.0,1,1,2.0,3.0,0,1,1.185897435897436,16_3.0 +16,4,10.207378999928212,3.0,1,1,2.0,3.0,1,1,1.185897435897436,16_3.0 +16,5,10.096882823598278,3.0,1,1,2.0,3.0,2,1,1.185897435897436,16_3.0 +17,1,8.175606640239206,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,17_3.0 +17,2,8.600350852687033,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,17_3.0 +17,3,9.60085063995874,3.0,1,1,2.0,3.0,0,1,1.185897435897436,17_3.0 +17,4,11.265857113284081,3.0,1,1,2.0,3.0,1,1,1.185897435897436,17_3.0 +17,5,10.805731826455423,3.0,1,1,2.0,3.0,2,1,1.185897435897436,17_3.0 +19,1,8.287479893276272,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,19_3.0 +19,2,8.838449778710965,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,19_3.0 +19,3,10.301088160788524,3.0,1,1,2.0,3.0,0,1,1.185897435897436,19_3.0 +19,4,10.193467173412117,3.0,1,1,2.0,3.0,1,1,1.185897435897436,19_3.0 +19,5,10.93570451644154,3.0,1,1,2.0,3.0,2,1,1.185897435897436,19_3.0 +20,1,6.608825849966525,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,20_3.0 +20,2,6.192567902449463,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,20_3.0 +20,3,8.62011884779571,3.0,1,1,2.0,3.0,0,1,1.185897435897436,20_3.0 +20,4,9.534699361996061,3.0,1,1,2.0,3.0,1,1,1.185897435897436,20_3.0 +20,5,8.972714344039472,3.0,1,1,2.0,3.0,2,1,1.185897435897436,20_3.0 23,1,11.395156619865356,7.0,0,1,0.0,3.0,-2,0,0.9107692307692308,23_3.0 23,2,12.292733093551572,7.0,0,1,0.0,3.0,-1,0,0.9107692307692308,23_3.0 23,3,10.987337838152467,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,23_3.0 23,4,12.858675160893522,7.0,0,1,0.0,3.0,1,0,0.9107692307692308,23_3.0 23,5,11.476064698198886,7.0,0,1,0.0,3.0,2,0,0.9107692307692308,23_3.0 -26,1,10.668383782601722,3.0,0,1,0.0,3.0,-2,1,1.0,26_3.0 -26,2,10.446234601225571,3.0,0,1,0.0,3.0,-1,1,1.0,26_3.0 -26,3,13.556242815369252,3.0,1,1,2.0,3.0,0,1,1.0,26_3.0 -26,4,13.576729933292084,3.0,1,1,2.0,3.0,1,1,1.0,26_3.0 -26,5,13.922175150825803,3.0,1,1,2.0,3.0,2,1,1.0,26_3.0 +26,1,10.668383782601722,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,26_3.0 +26,2,10.446234601225571,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,26_3.0 +26,3,13.556242815369252,3.0,1,1,2.0,3.0,0,1,1.185897435897436,26_3.0 +26,4,13.576729933292084,3.0,1,1,2.0,3.0,1,1,1.185897435897436,26_3.0 +26,5,13.922175150825803,3.0,1,1,2.0,3.0,2,1,1.185897435897436,26_3.0 27,1,8.580588297539316,7.0,0,1,0.0,3.0,-2,0,0.9107692307692308,27_3.0 27,2,9.053926240501355,7.0,0,1,0.0,3.0,-1,0,0.9107692307692308,27_3.0 27,3,8.688974179281848,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,27_3.0 27,4,7.928575988525038,7.0,0,1,0.0,3.0,1,0,0.9107692307692308,27_3.0 27,5,9.170520905605873,7.0,0,1,0.0,3.0,2,0,0.9107692307692308,27_3.0 -28,1,9.371848258038815,3.0,0,1,0.0,3.0,-2,1,1.0,28_3.0 -28,2,9.154422149577181,3.0,0,1,0.0,3.0,-1,1,1.0,28_3.0 -28,3,11.965196547208972,3.0,1,1,2.0,3.0,0,1,1.0,28_3.0 -28,4,11.302065396349953,3.0,1,1,2.0,3.0,1,1,1.0,28_3.0 -28,5,11.589704550706,3.0,1,1,2.0,3.0,2,1,1.0,28_3.0 -29,1,8.985010266355241,3.0,0,1,0.0,3.0,-2,1,1.0,29_3.0 -29,2,8.92226436961385,3.0,0,1,0.0,3.0,-1,1,1.0,29_3.0 -29,3,11.587183906367892,3.0,1,1,2.0,3.0,0,1,1.0,29_3.0 -29,4,11.061585148973101,3.0,1,1,2.0,3.0,1,1,1.0,29_3.0 -29,5,11.32705363934025,3.0,1,1,2.0,3.0,2,1,1.0,29_3.0 -30,1,8.376287388505098,3.0,0,1,0.0,3.0,-2,1,1.0,30_3.0 -30,2,8.657693030574496,3.0,0,1,0.0,3.0,-1,1,1.0,30_3.0 -30,3,10.18781936742593,3.0,1,1,2.0,3.0,0,1,1.0,30_3.0 -30,4,11.000739934625502,3.0,1,1,2.0,3.0,1,1,1.0,30_3.0 -30,5,10.282065104573295,3.0,1,1,2.0,3.0,2,1,1.0,30_3.0 +28,1,9.371848258038815,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,28_3.0 +28,2,9.154422149577181,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,28_3.0 +28,3,11.965196547208972,3.0,1,1,2.0,3.0,0,1,1.185897435897436,28_3.0 +28,4,11.302065396349953,3.0,1,1,2.0,3.0,1,1,1.185897435897436,28_3.0 +28,5,11.589704550706,3.0,1,1,2.0,3.0,2,1,1.185897435897436,28_3.0 +29,1,8.985010266355241,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,29_3.0 +29,2,8.92226436961385,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,29_3.0 +29,3,11.587183906367892,3.0,1,1,2.0,3.0,0,1,1.185897435897436,29_3.0 +29,4,11.061585148973101,3.0,1,1,2.0,3.0,1,1,1.185897435897436,29_3.0 +29,5,11.32705363934025,3.0,1,1,2.0,3.0,2,1,1.185897435897436,29_3.0 +30,1,8.376287388505098,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,30_3.0 +30,2,8.657693030574496,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,30_3.0 +30,3,10.18781936742593,3.0,1,1,2.0,3.0,0,1,1.185897435897436,30_3.0 +30,4,11.000739934625502,3.0,1,1,2.0,3.0,1,1,1.185897435897436,30_3.0 +30,5,10.282065104573295,3.0,1,1,2.0,3.0,2,1,1.185897435897436,30_3.0 33,1,11.57454492762582,7.0,0,1,0.0,3.0,-2,0,0.9107692307692308,33_3.0 33,2,11.691765125046665,7.0,0,1,0.0,3.0,-1,0,0.9107692307692308,33_3.0 33,3,11.84979372696007,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,33_3.0 @@ -139,36 +139,36 @@ unit,period,outcome,first_treat,treated,treat,true_effect,_sub_exp,_event_time,_ 34,3,12.803090421682993,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,34_3.0 34,4,13.544985407250604,7.0,0,1,0.0,3.0,1,0,0.9107692307692308,34_3.0 34,5,13.17341536766152,7.0,0,1,0.0,3.0,2,0,0.9107692307692308,34_3.0 -35,1,13.198034881842501,3.0,0,1,0.0,3.0,-2,1,1.0,35_3.0 -35,2,13.13803314498448,3.0,0,1,0.0,3.0,-1,1,1.0,35_3.0 -35,3,14.775491475016876,3.0,1,1,2.0,3.0,0,1,1.0,35_3.0 -35,4,14.755631298179171,3.0,1,1,2.0,3.0,1,1,1.0,35_3.0 -35,5,15.82726562084955,3.0,1,1,2.0,3.0,2,1,1.0,35_3.0 -36,1,7.2152253987939226,3.0,0,1,0.0,3.0,-2,1,1.0,36_3.0 -36,2,6.610853150968622,3.0,0,1,0.0,3.0,-1,1,1.0,36_3.0 -36,3,8.853563997233643,3.0,1,1,2.0,3.0,0,1,1.0,36_3.0 -36,4,9.09329932509169,3.0,1,1,2.0,3.0,1,1,1.0,36_3.0 -36,5,9.298377296285087,3.0,1,1,2.0,3.0,2,1,1.0,36_3.0 +35,1,13.198034881842501,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,35_3.0 +35,2,13.13803314498448,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,35_3.0 +35,3,14.775491475016876,3.0,1,1,2.0,3.0,0,1,1.185897435897436,35_3.0 +35,4,14.755631298179171,3.0,1,1,2.0,3.0,1,1,1.185897435897436,35_3.0 +35,5,15.82726562084955,3.0,1,1,2.0,3.0,2,1,1.185897435897436,35_3.0 +36,1,7.2152253987939226,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,36_3.0 +36,2,6.610853150968622,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,36_3.0 +36,3,8.853563997233643,3.0,1,1,2.0,3.0,0,1,1.185897435897436,36_3.0 +36,4,9.09329932509169,3.0,1,1,2.0,3.0,1,1,1.185897435897436,36_3.0 +36,5,9.298377296285087,3.0,1,1,2.0,3.0,2,1,1.185897435897436,36_3.0 37,1,10.146958297869952,7.0,0,1,0.0,3.0,-2,0,0.9107692307692308,37_3.0 37,2,9.060497069998855,7.0,0,1,0.0,3.0,-1,0,0.9107692307692308,37_3.0 37,3,9.318388049432945,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,37_3.0 37,4,9.26097646005531,7.0,0,1,0.0,3.0,1,0,0.9107692307692308,37_3.0 37,5,8.919210921226544,7.0,0,1,0.0,3.0,2,0,0.9107692307692308,37_3.0 -39,1,12.353298527293795,3.0,0,1,0.0,3.0,-2,1,1.0,39_3.0 -39,2,12.242756403937744,3.0,0,1,0.0,3.0,-1,1,1.0,39_3.0 -39,3,15.149617439612653,3.0,1,1,2.0,3.0,0,1,1.0,39_3.0 -39,4,14.088452790656742,3.0,1,1,2.0,3.0,1,1,1.0,39_3.0 -39,5,14.060806514376624,3.0,1,1,2.0,3.0,2,1,1.0,39_3.0 +39,1,12.353298527293795,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,39_3.0 +39,2,12.242756403937744,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,39_3.0 +39,3,15.149617439612653,3.0,1,1,2.0,3.0,0,1,1.185897435897436,39_3.0 +39,4,14.088452790656742,3.0,1,1,2.0,3.0,1,1,1.185897435897436,39_3.0 +39,5,14.060806514376624,3.0,1,1,2.0,3.0,2,1,1.185897435897436,39_3.0 40,1,7.342148190809627,7.0,0,1,0.0,3.0,-2,0,0.9107692307692308,40_3.0 40,2,8.356636279545437,7.0,0,1,0.0,3.0,-1,0,0.9107692307692308,40_3.0 40,3,8.853341199215448,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,40_3.0 40,4,7.646273376822638,7.0,0,1,0.0,3.0,1,0,0.9107692307692308,40_3.0 40,5,7.959815635944495,7.0,0,1,0.0,3.0,2,0,0.9107692307692308,40_3.0 -41,1,12.529859573199765,3.0,0,1,0.0,3.0,-2,1,1.0,41_3.0 -41,2,12.359862327664574,3.0,0,1,0.0,3.0,-1,1,1.0,41_3.0 -41,3,14.594595526225248,3.0,1,1,2.0,3.0,0,1,1.0,41_3.0 -41,4,14.627150386514797,3.0,1,1,2.0,3.0,1,1,1.0,41_3.0 -41,5,15.438306775111634,3.0,1,1,2.0,3.0,2,1,1.0,41_3.0 +41,1,12.529859573199765,3.0,0,1,0.0,3.0,-2,1,1.185897435897436,41_3.0 +41,2,12.359862327664574,3.0,0,1,0.0,3.0,-1,1,1.185897435897436,41_3.0 +41,3,14.594595526225248,3.0,1,1,2.0,3.0,0,1,1.185897435897436,41_3.0 +41,4,14.627150386514797,3.0,1,1,2.0,3.0,1,1,1.185897435897436,41_3.0 +41,5,15.438306775111634,3.0,1,1,2.0,3.0,2,1,1.185897435897436,41_3.0 43,1,11.589875560059742,7.0,0,1,0.0,3.0,-2,0,0.9107692307692308,43_3.0 43,2,11.566062741673996,7.0,0,1,0.0,3.0,-1,0,0.9107692307692308,43_3.0 43,3,11.081605645195344,7.0,0,1,0.0,3.0,0,0,0.9107692307692308,43_3.0 @@ -259,68 +259,68 @@ unit,period,outcome,first_treat,treated,treat,true_effect,_sub_exp,_event_time,_ 14,5,9.254403864326273,inf,0,0,0.0,5.0,0,0,1.1487179487179489,14_5.0 14,6,9.330459677777796,inf,0,0,0.0,5.0,1,0,1.1487179487179489,14_5.0 14,7,9.00828730479836,inf,0,0,0.0,5.0,2,0,1.1487179487179489,14_5.0 -18,3,8.750153667767103,5.0,0,1,0.0,5.0,-2,1,1.0,18_5.0 -18,4,10.369418029568877,5.0,0,1,0.0,5.0,-1,1,1.0,18_5.0 -18,5,11.814853522513967,5.0,1,1,2.0,5.0,0,1,1.0,18_5.0 -18,6,11.880991600710768,5.0,1,1,2.0,5.0,1,1,1.0,18_5.0 -18,7,12.084939640054936,5.0,1,1,2.0,5.0,2,1,1.0,18_5.0 -21,3,11.130313135937552,5.0,0,1,0.0,5.0,-2,1,1.0,21_5.0 -21,4,11.783557955755562,5.0,0,1,0.0,5.0,-1,1,1.0,21_5.0 -21,5,13.932178697330485,5.0,1,1,2.0,5.0,0,1,1.0,21_5.0 -21,6,13.311045276660398,5.0,1,1,2.0,5.0,1,1,1.0,21_5.0 -21,7,12.672260765381138,5.0,1,1,2.0,5.0,2,1,1.0,21_5.0 -22,3,10.370162504733846,5.0,0,1,0.0,5.0,-2,1,1.0,22_5.0 -22,4,10.130795877474743,5.0,0,1,0.0,5.0,-1,1,1.0,22_5.0 -22,5,13.327665186472212,5.0,1,1,2.0,5.0,0,1,1.0,22_5.0 -22,6,14.006133024294815,5.0,1,1,2.0,5.0,1,1,1.0,22_5.0 -22,7,11.997025447630525,5.0,1,1,2.0,5.0,2,1,1.0,22_5.0 -24,3,12.216528415765985,5.0,0,1,0.0,5.0,-2,1,1.0,24_5.0 -24,4,11.844123402747586,5.0,0,1,0.0,5.0,-1,1,1.0,24_5.0 -24,5,13.783296021523771,5.0,1,1,2.0,5.0,0,1,1.0,24_5.0 -24,6,13.374452489632073,5.0,1,1,2.0,5.0,1,1,1.0,24_5.0 -24,7,14.257003341404754,5.0,1,1,2.0,5.0,2,1,1.0,24_5.0 -25,3,12.376139740663152,5.0,0,1,0.0,5.0,-2,1,1.0,25_5.0 -25,4,12.451932231507831,5.0,0,1,0.0,5.0,-1,1,1.0,25_5.0 -25,5,14.40345513916028,5.0,1,1,2.0,5.0,0,1,1.0,25_5.0 -25,6,15.399316274400507,5.0,1,1,2.0,5.0,1,1,1.0,25_5.0 -25,7,14.121018820768782,5.0,1,1,2.0,5.0,2,1,1.0,25_5.0 -31,3,5.699685628062173,5.0,0,1,0.0,5.0,-2,1,1.0,31_5.0 -31,4,6.640244849690189,5.0,0,1,0.0,5.0,-1,1,1.0,31_5.0 -31,5,8.80287858433971,5.0,1,1,2.0,5.0,0,1,1.0,31_5.0 -31,6,7.478011213888342,5.0,1,1,2.0,5.0,1,1,1.0,31_5.0 -31,7,7.785449789009849,5.0,1,1,2.0,5.0,2,1,1.0,31_5.0 -32,3,13.145351442221973,5.0,0,1,0.0,5.0,-2,1,1.0,32_5.0 -32,4,14.213246370804844,5.0,0,1,0.0,5.0,-1,1,1.0,32_5.0 -32,5,15.673222444412447,5.0,1,1,2.0,5.0,0,1,1.0,32_5.0 -32,6,14.660677350520446,5.0,1,1,2.0,5.0,1,1,1.0,32_5.0 -32,7,14.475511437433273,5.0,1,1,2.0,5.0,2,1,1.0,32_5.0 -38,3,9.198240092902193,5.0,0,1,0.0,5.0,-2,1,1.0,38_5.0 -38,4,8.489100540648527,5.0,0,1,0.0,5.0,-1,1,1.0,38_5.0 -38,5,11.45417220010028,5.0,1,1,2.0,5.0,0,1,1.0,38_5.0 -38,6,10.634610329560985,5.0,1,1,2.0,5.0,1,1,1.0,38_5.0 -38,7,12.158628732093817,5.0,1,1,2.0,5.0,2,1,1.0,38_5.0 -42,3,9.165900951128542,5.0,0,1,0.0,5.0,-2,1,1.0,42_5.0 -42,4,9.836927314238459,5.0,0,1,0.0,5.0,-1,1,1.0,42_5.0 -42,5,11.893273621648287,5.0,1,1,2.0,5.0,0,1,1.0,42_5.0 -42,6,10.811622966738568,5.0,1,1,2.0,5.0,1,1,1.0,42_5.0 -42,7,12.387788948877349,5.0,1,1,2.0,5.0,2,1,1.0,42_5.0 -44,3,13.218744977031886,5.0,0,1,0.0,5.0,-2,1,1.0,44_5.0 -44,4,13.584858653200563,5.0,0,1,0.0,5.0,-1,1,1.0,44_5.0 -44,5,15.869766671523484,5.0,1,1,2.0,5.0,0,1,1.0,44_5.0 -44,6,15.606050081127213,5.0,1,1,2.0,5.0,1,1,1.0,44_5.0 -44,7,14.741953786805245,5.0,1,1,2.0,5.0,2,1,1.0,44_5.0 -47,3,11.405672205690639,5.0,0,1,0.0,5.0,-2,1,1.0,47_5.0 -47,4,10.327840224798175,5.0,0,1,0.0,5.0,-1,1,1.0,47_5.0 -47,5,12.972063268138358,5.0,1,1,2.0,5.0,0,1,1.0,47_5.0 -47,6,13.3375192672357,5.0,1,1,2.0,5.0,1,1,1.0,47_5.0 -47,7,13.949251964590784,5.0,1,1,2.0,5.0,2,1,1.0,47_5.0 -48,3,10.036462523941848,5.0,0,1,0.0,5.0,-2,1,1.0,48_5.0 -48,4,10.557346448715858,5.0,0,1,0.0,5.0,-1,1,1.0,48_5.0 -48,5,11.320126492133841,5.0,1,1,2.0,5.0,0,1,1.0,48_5.0 -48,6,12.376923426574146,5.0,1,1,2.0,5.0,1,1,1.0,48_5.0 -48,7,12.52530519550149,5.0,1,1,2.0,5.0,2,1,1.0,48_5.0 -49,3,9.93003674799368,5.0,0,1,0.0,5.0,-2,1,1.0,49_5.0 -49,4,9.728215912860774,5.0,0,1,0.0,5.0,-1,1,1.0,49_5.0 -49,5,12.103403154230948,5.0,1,1,2.0,5.0,0,1,1.0,49_5.0 -49,6,11.538525743370705,5.0,1,1,2.0,5.0,1,1,1.0,49_5.0 -49,7,12.200705227099014,5.0,1,1,2.0,5.0,2,1,1.0,49_5.0 +18,3,8.750153667767103,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,18_5.0 +18,4,10.369418029568877,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,18_5.0 +18,5,11.814853522513967,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,18_5.0 +18,6,11.880991600710768,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,18_5.0 +18,7,12.084939640054936,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,18_5.0 +21,3,11.130313135937552,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,21_5.0 +21,4,11.783557955755562,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,21_5.0 +21,5,13.932178697330485,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,21_5.0 +21,6,13.311045276660398,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,21_5.0 +21,7,12.672260765381138,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,21_5.0 +22,3,10.370162504733846,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,22_5.0 +22,4,10.130795877474743,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,22_5.0 +22,5,13.327665186472212,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,22_5.0 +22,6,14.006133024294815,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,22_5.0 +22,7,11.997025447630525,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,22_5.0 +24,3,12.216528415765985,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,24_5.0 +24,4,11.844123402747586,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,24_5.0 +24,5,13.783296021523771,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,24_5.0 +24,6,13.374452489632073,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,24_5.0 +24,7,14.257003341404754,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,24_5.0 +25,3,12.376139740663152,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,25_5.0 +25,4,12.451932231507831,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,25_5.0 +25,5,14.40345513916028,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,25_5.0 +25,6,15.399316274400507,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,25_5.0 +25,7,14.121018820768782,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,25_5.0 +31,3,5.699685628062173,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,31_5.0 +31,4,6.640244849690189,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,31_5.0 +31,5,8.80287858433971,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,31_5.0 +31,6,7.478011213888342,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,31_5.0 +31,7,7.785449789009849,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,31_5.0 +32,3,13.145351442221973,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,32_5.0 +32,4,14.213246370804844,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,32_5.0 +32,5,15.673222444412447,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,32_5.0 +32,6,14.660677350520446,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,32_5.0 +32,7,14.475511437433273,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,32_5.0 +38,3,9.198240092902193,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,38_5.0 +38,4,8.489100540648527,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,38_5.0 +38,5,11.45417220010028,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,38_5.0 +38,6,10.634610329560985,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,38_5.0 +38,7,12.158628732093817,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,38_5.0 +42,3,9.165900951128542,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,42_5.0 +42,4,9.836927314238459,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,42_5.0 +42,5,11.893273621648287,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,42_5.0 +42,6,10.811622966738568,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,42_5.0 +42,7,12.387788948877349,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,42_5.0 +44,3,13.218744977031886,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,44_5.0 +44,4,13.584858653200563,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,44_5.0 +44,5,15.869766671523484,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,44_5.0 +44,6,15.606050081127213,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,44_5.0 +44,7,14.741953786805245,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,44_5.0 +47,3,11.405672205690639,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,47_5.0 +47,4,10.327840224798175,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,47_5.0 +47,5,12.972063268138358,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,47_5.0 +47,6,13.3375192672357,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,47_5.0 +47,7,13.949251964590784,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,47_5.0 +48,3,10.036462523941848,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,48_5.0 +48,4,10.557346448715858,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,48_5.0 +48,5,11.320126492133841,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,48_5.0 +48,6,12.376923426574146,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,48_5.0 +48,7,12.52530519550149,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,48_5.0 +49,3,9.93003674799368,5.0,0,1,0.0,5.0,-2,1,0.8284023668639053,49_5.0 +49,4,9.728215912860774,5.0,0,1,0.0,5.0,-1,1,0.8284023668639053,49_5.0 +49,5,12.103403154230948,5.0,1,1,2.0,5.0,0,1,0.8284023668639053,49_5.0 +49,6,11.538525743370705,5.0,1,1,2.0,5.0,1,1,0.8284023668639053,49_5.0 +49,7,12.200705227099014,5.0,1,1,2.0,5.0,2,1,0.8284023668639053,49_5.0 diff --git a/benchmarks/data/synthetic/survey_estimator_validation_golden.json b/benchmarks/data/synthetic/survey_estimator_validation_golden.json index bf8a6d713..da395c331 100644 --- a/benchmarks/data/synthetic/survey_estimator_validation_golden.json +++ b/benchmarks/data/synthetic/survey_estimator_validation_golden.json @@ -14,18 +14,18 @@ "scenario": "S2", "description": "StackedDiD: stacked WLS with Q-weight x survey weight composition", "estimator": "survey::svyglm", - "att": 5.039606586, - "se": 0.43170156311, + "att": 5.0838104334, + "se": 0.41544433376, "n_stacked": 678, "df": 6, "event_study": { "0": { - "coef": 5.0048694773, - "se": 0.4629603277 + "coef": 5.0230443997, + "se": 0.46964959396 }, "1": { - "coef": 5.0743436947, - "se": 0.56222065855 + "coef": 5.144576467, + "se": 0.53261301956 } } }, diff --git a/benchmarks/python_helpers/dump_stacked_did_panel.py b/benchmarks/python_helpers/dump_stacked_did_panel.py new file mode 100644 index 000000000..bb6cb9d06 --- /dev/null +++ b/benchmarks/python_helpers/dump_stacked_did_panel.py @@ -0,0 +1,80 @@ +"""Dump the pre-stacked StackedDiD panels read by the R golden generator. + +`benchmarks/R/generate_stacked_did_golden.R` fits `lm(weights = Q)` on these +CSVs and records clubSandwich CR1S / CR2 standard errors, so the R side is +independent of the stacking logic but uses the Q-weights computed here. Rerun +this script, then the R script, whenever the stacked sample or the Q-weights +change for a variant: + + python benchmarks/python_helpers/dump_stacked_did_panel.py + Rscript benchmarks/R/generate_stacked_did_golden.R + +The panels mirror the fixtures in `tests/test_methodology_stacked_did.py` +(`panel`, `population_panel`), which is what the parity tests fit. +""" + +from __future__ import annotations + +import os +import warnings + +import numpy as np + +from diff_diff import StackedDiD +from diff_diff.prep_dgp import generate_staggered_data + +_DATA_DIR = os.path.join(os.path.dirname(__file__), "..", "data") + + +def _base_panel(): + return generate_staggered_data( + n_units=50, + n_periods=8, + cohort_periods=[3, 5, 7], + never_treated_frac=0.3, + treatment_effect=2.0, + dynamic_effects=False, + seed=20260521, + ) + + +def _population_panel(): + rng = np.random.default_rng(99) + data = _base_panel() + unit_pops = rng.uniform(1.0, 100.0, size=data["unit"].nunique()) + data = data.copy() + data["pop"] = data["unit"].map(lambda u: unit_pops[int(u)]) + return data + + +# name -> (panel builder, StackedDiD kwargs, fit kwargs) +VARIANTS = { + "test": (_base_panel, {}, {}), + "population": (_population_panel, {"weighting": "population"}, {"population": "pop"}), + "anticipation1": (_base_panel, {"anticipation": 1}, {}), + "sample_share": (_base_panel, {"weighting": "sample_share"}, {}), +} + + +def dump(name: str) -> str: + builder, est_kwargs, fit_kwargs = VARIANTS[name] + with warnings.catch_warnings(): + warnings.simplefilter("ignore", UserWarning) + res = StackedDiD(kappa_pre=2, kappa_post=2, **est_kwargs).fit( + builder(), + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + **fit_kwargs, + ) + stacked = res.stacked_data.copy() + stacked["unit_subexp"] = stacked["unit"].astype(str) + "_" + stacked["_sub_exp"].astype(str) + path = os.path.join(_DATA_DIR, f"stacked_did_{name}_panel.csv") + stacked.to_csv(path, index=False) + return path + + +if __name__ == "__main__": + for variant in VARIANTS: + print("wrote", os.path.relpath(dump(variant))) diff --git a/changelog.d/20261126-stacked-complete-windows.md b/changelog.d/20261126-stacked-complete-windows.md new file mode 100644 index 000000000..1163c762a --- /dev/null +++ b/changelog.d/20261126-stacked-complete-windows.md @@ -0,0 +1,91 @@ +### Fixed +- **`StackedDiD` no longer returns shifted estimates on panels with missing + observations.** The stacked regression contrasts (treated x event-time) and + (control x event-time) cell means, which are within-unit changes only when + the same units sit in every cell of a sub-experiment. The paper's stack is + built that way (Wing, Freedman & Hollingsworth 2024, Section 5.1), but + `fit()` kept every row of an eligible unit, so on a ragged panel level + differences between units leaked into the estimates, with no warning. On a + noiseless panel with a true ATT of 2.5 (90 units, 10 periods, cohorts 4 and + 6, `kappa_pre = kappa_post = 2`): + - one never-treated observation missing: 2.4978; + - 5% of rows missing at random: 2.6020; + - half of one cohort missing its `e = -1` row: 2.2965; the whole cohort + missing it, or having no pre-treatment rows at all: 1.9500; + - never-treated units missing two post-treatment periods: 2.7000; + - a calendar period absent for every unit: 1.7667 or 2.6833, depending on + the period; + - no never-treated rows inside the event windows: NaN with a rank warning. + Each case now returns 2.5 exactly or raises (see Behavioral Changes). The + authors' reference R code returns the same shifted numbers on such panels + (the library matched it to 12 digits), so the corrected behavior is a + documented deviation from it; R `cbwsdid` already builds its stack from + complete units, and `balance="entropy"` now matches it on ragged panels. +- **`StackedDiD` no longer mis-assigns rows it cannot place on the event-time + grid.** Duplicate `(unit, time)` rows were double-counted (2.5411 on the + panel above), rows at a fractional `time` were absorbed into the reference + category (1.3833), rows with a missing `time` were dropped silently, and a + fractional `first_treat` was truncated to the period before it. All four + now raise `ValueError`. +- **`StackedDiD(weighting="population")` and `weighting="sample_share"` now + apply the paper's treatment weight.** Table 1 of Wing, Freedman & + Hollingsworth (2024) weights the treated rows as well as the controls; the + library set the treated weight to 1 under every scheme, so under these two + the treated arm was aggregated by unit shares and the control arm by + population or sample shares, the untreated trends did not 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 0.0023 (`population`) and 0.10 (`sample_share`); both + are now exact. The default `weighting="aggregate"` was correct and is + bit-identical. +- **`StackedDiD` + `survey_design=`: the corrective weights now use + survey-weighted cohort shares.** They were formed from raw unit counts and + then multiplied by the survey weight, which left the treated arm on + survey-weighted shares and the control arm on a mix of both. With + unit-constant weights of 1.5 / 0.5 / 1 across two cohorts and the controls, + a noiseless panel with a true ATT of 2.50 returned 2.46; with half of a + cohort at weight 0 it returned 2.4733. Both are now exact, replicate-weight + refits recompute the corrective weights from each replicate's weights, and + an independent R implementation (`survey::svyglm`) of the same formula + matches to 1e-11. +- **`StackedDiD` + `survey_design=` no longer accepts survey columns that + change within a unit.** A weight that varies 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); it now raises + `ValueError`, as it does for the other panel estimators. +- **`StackedDiDResults.groups` no longer lists an adoption event whose + sub-experiment was not built.** + +### Behavioral Changes +- **`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]`. On a panel with missing + observations the units that are not are excluded from that sub-experiment + and `fit()` warns with the per-event "kept of eligible" counts; the estimand + is the trimmed aggregate ATT over the units observed across their whole + window, and `n_treated_units`, `n_control_units` and `stacked_data` reflect + them. Balanced panels are unchanged. +- **`StackedDiD`: events without complete units are dropped.** An adoption + event left without a treated unit or a clean control observed across its + window, including one whose window contains a calendar period no unit + observes, is dropped with a warning naming the reason and is reported in + `trimmed_groups` instead of `groups`. With no event left `fit()` raises + `ValueError`, naming the gaps in the time grid when there are any (a + biennial or datetime-coded `time` column must be re-indexed to consecutive + integers). Panels that previously raised "would be fabricated" for a + missing reference period now raise this error instead. +- **`StackedDiD` + `survey_design=` refuses a panel that would be trimmed** + (`NotImplementedError`), whether a unit or a whole adoption event would be + dropped: excluding them would remove their PSUs and strata from the variance + and its degrees of freedom. +- **`StackedDiD` estimates change under `weighting="population"`, + `weighting="sample_share"` and `survey_design=`** (see Fixed): under the two + alternative schemes wherever their target shares differ from the treated-unit + shares, and under a survey design wherever the survey weights differ across + cohorts. Replicate-weight standard errors change as well, since each refit + recomputes the corrective weights. A sub-experiment with no treated or + control unit of positive weight, or a zero treated population, now carries + zero weight and is named in a warning; `weighting="population"` requires a + finite, non-negative, unit-constant population for the treated units. +- **`StackedDiD(balance="entropy")` trims ragged windows** like the default + path, where it previously raised `ValueError`. diff --git a/diff_diff/_reporting_helpers.py b/diff_diff/_reporting_helpers.py index ed7606787..f727c5ab2 100644 --- a/diff_diff/_reporting_helpers.py +++ b/diff_diff/_reporting_helpers.py @@ -441,6 +441,20 @@ def describe_target_parameter(results: Any) -> Dict[str, Any]: "treated through the event's post-window " "(``A_s > a + kappa_post``)." ) + # Each scheme aggregates the sub-experiment ATTs with its own cohort + # share (Wing et al. 2024, Table 1); a getattr default keeps results + # stand-ins that predate the field working. + weighting = getattr(results, "weighting", "aggregate") + if weighting == "population": + share_clause = "treated-population-share-weighted" + elif weighting == "sample_share": + share_clause = "sample-share-weighted" + else: + share_clause = "treated-unit-share-weighted" + if getattr(results, "survey_metadata", None) is not None: + mass_clause = "the shares counting those units by their survey weights" + else: + mass_clause = "the shares counting those units" return { "name": "overall ATT (average of post-treatment event-study coefficients)", "definition": ( @@ -448,10 +462,12 @@ def describe_target_parameter(results: Any) -> Dict[str, Any]: "``delta_h`` (h >= -anticipation), estimated from the stacked " "sub-experiment panel with delta-method SE. Each sub-" "experiment aligns a treated cohort with its clean-control " - "set over the event window ``[-kappa_pre, +kappa_post]``; " - "each per-horizon ``delta_h`` is the paper's " - "``theta_kappa^e`` treated-share-weighted cross-event " - "aggregate. The ``att`` headline is the equally-" + "set over the event window ``[-kappa_pre - anticipation, " + "+kappa_post]`` and " + "holds only the units observed at every event time of that " + "window; each per-horizon ``delta_h`` is the paper's " + f"``theta_kappa^e`` {share_clause} cross-event " + f"aggregate, {mass_clause}. The ``att`` headline is the equally-" "weighted average of these per-horizon coefficients, not a " "separate cross-event weighted aggregate at the ATT level. " + control_clause ), diff --git a/diff_diff/guides/llms-autonomous.txt b/diff_diff/guides/llms-autonomous.txt index ef3175644..7209267be 100644 --- a/diff_diff/guides/llms-autonomous.txt +++ b/diff_diff/guides/llms-autonomous.txt @@ -439,7 +439,9 @@ the estimand). If either condition fails, pre-process with `drop_duplicates([unit, time])` pass, or pick a balance-tolerant estimator from the remaining rows (CS/SA/dCDH/Imputation/TwoStage/ Stacked/ETWFE all accept unbalanced input, with some caveats in -their own docs). +their own docs: `StackedDiD`, for one, keeps in each sub-experiment +only the units observed at every event time of its window, warns +with the counts, and rejects duplicate `(unit, time)` rows). For two common reasoning patterns walked through end-to-end (continuous dose checked against the existing `has_never_treated` / diff --git a/diff_diff/guides/llms-full.txt b/diff_diff/guides/llms-full.txt index 9eb95d575..297f30461 100644 --- a/diff_diff/guides/llms-full.txt +++ b/diff_diff/guides/llms-full.txt @@ -1024,6 +1024,10 @@ StackedDiD( **Alias:** none (the pre-4.0 `Stacked` alias was removed in 4.0; use `StackedDiD`) +**Weighting schemes (Wing et al. 2024, Table 1):** each scheme fixes the share `pi_a` with which sub-experiment `a` enters the aggregate `sum_a pi_a ATT(a, a+e)`: the share of treated units (`"aggregate"`), of the treated units' population (`"population"`, needs `fit(population=...)`: finite, non-negative, constant within a unit) or of all units (`"sample_share"`). Treated AND control rows are weighted so that each arm carries `pi_a`; treated rows have weight 1 only under `"aggregate"`. Under `survey_design=` the shares are formed from survey-weighted unit masses (the design-weighted aggregate), survey columns must be constant within a unit, and replicate refits recompute the weights. A sub-experiment with no treated or control unit of positive weight, or a zero treated population, carries zero weight and is named in a `UserWarning`. + +**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`. + **fit() parameters:** ```python @@ -1034,7 +1038,7 @@ stacked.fit( time: str, first_treat: str, population: str = None, # Required when weighting="population" - covariates: list[str] = None, # Columns to balance (requires balance="entropy"); values read at t=a-1-anticipation; balanced windows only + covariates: list[str] = None, # Columns to balance (requires balance="entropy"); values read at t=a-1-anticipation ) -> StackedDiDResults ``` diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 5eb37f397..530af5e1a 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -41,6 +41,115 @@ ] +def _cohort_share_weights( + sub_exp: np.ndarray, + treated: np.ndarray, + unit: np.ndarray, + weighting: str, + row_weights: Optional[np.ndarray] = None, + population: Optional[np.ndarray] = None, +) -> Tuple[np.ndarray, Dict[Any, str]]: + """Corrective Q-weights that give both arms the same cohort shares. + + Wing, Freedman & Hollingsworth (2024, Section 5.3) show the stacked + regression recovers a convex combination of the sub-experiment ATTs only + if the treated arm and the control arm aggregate sub-experiments with the + SAME shares; otherwise the untreated trends do not cancel. With ``w_s`` a + unit's survey weight (1 without a survey design) and the sums taken over + the units of sub-experiment ``a``:: + + W_a^D = sum of w_s over treated units, W_a^C = sum over controls + pi_a = W_a^D / W^D (aggregate) + pi_a = sum of w_s * pop_s over treated / total (population) + pi_a = (W_a^D + W_a^C) / (W^D + W^C) (sample_share) + + Q_sa = pi_a / (W_a^D / W^D) for treated rows + Q_sa = pi_a / (W_a^C / W^C) for control rows + + Without survey weights these are the paper's Table 1 weights (treated + ``Q = 1`` under ``aggregate``). A sub-experiment with no treated mass, + no control mass, or a zero target share gets ``Q = 0`` on every row and + is left out of the totals; its rows stay in the stack. + + Parameters + ---------- + sub_exp, treated, unit : np.ndarray + Per stacked row: sub-experiment label, treated flag (1/0), unit id. + weighting : {"aggregate", "population", "sample_share"} + row_weights : np.ndarray, optional + Per-row survey weight, constant within a unit. ``None`` = all ones. + population : np.ndarray, optional + Per-row population (``weighting="population"`` only); read on + treated rows, constant within a unit. + + Returns + ------- + q : np.ndarray + Q-weight per stacked row. + zero_weight : dict + Sub-experiments that receive zero weight, mapped to the reason. + """ + n = len(sub_exp) + is_treated = np.asarray(treated) == 1 + frame = pd.DataFrame( + { + "a": sub_exp, + "u": unit, + "d": is_treated, + "w": np.ones(n) if row_weights is None else np.asarray(row_weights, dtype=float), + } + ) + if population is not None: + frame["p"] = np.asarray(population, dtype=float) + # One row per (sub-experiment, unit): every stacked unit covers the whole + # window and its weight is constant, so the first row carries its mass. + units = frame.loc[~frame.duplicated(subset=["a", "u"])] + events = list(pd.unique(frame["a"])) + w_d = units.loc[units["d"]].groupby("a")["w"].sum().reindex(events, fill_value=0.0) + w_c = units.loc[~units["d"]].groupby("a")["w"].sum().reindex(events, fill_value=0.0) + + zero_weight: Dict[Any, str] = {} + for a in events: + if not w_d[a] > 0: + zero_weight[a] = "no treated unit with positive weight" + elif not w_c[a] > 0: + zero_weight[a] = "no clean control with positive weight" + effective = [a for a in events if a not in zero_weight] + + q_treated = pd.Series(0.0, index=events) + q_control = pd.Series(0.0, index=events) + if effective: + w_d_total = float(w_d[effective].sum()) + w_c_total = float(w_c[effective].sum()) + if weighting == "aggregate": + target = w_d / w_d_total + elif weighting == "population": + treated_units = units.loc[units["d"]] + pop_mass = ( + (treated_units["w"] * treated_units["p"]) + .groupby(treated_units["a"]) + .sum() + .reindex(events, fill_value=0.0) + ) + pop_total = float(pop_mass[effective].sum()) + target = pop_mass / pop_total if pop_total > 0 else pop_mass * 0.0 + for a in effective: + if not pop_mass[a] > 0: + zero_weight[a] = "zero treated population" + else: # sample_share + target = (w_d + w_c) / (w_d_total + w_c_total) + for a in effective: + if a in zero_weight: + continue + q_treated[a] = target[a] / (w_d[a] / w_d_total) + q_control[a] = target[a] / (w_c[a] / w_c_total) + + q = np.where( + is_treated, frame["a"].map(q_treated).to_numpy(), frame["a"].map(q_control).to_numpy() + ).astype(float) + return q, zero_weight + + class StackedDiD(BaseEstimator): """ Stacked Difference-in-Differences estimator. @@ -58,10 +167,16 @@ class StackedDiD(BaseEstimator): kappa_post : int, default=1 Number of post-treatment event-time periods. weighting : str, default="aggregate" - Target estimand weighting scheme per Table 1 of the paper: - - "aggregate": Equal weight per adoption event (trimmed aggregate ATT) - - "population": Weight by population size of treated cohort - - "sample_share": Weight by sample share of each sub-experiment + Target estimand weighting scheme per Table 1 of the paper. Each sets + the share ``pi_a`` with which sub-experiment ``a`` enters the aggregate + ``sum_a pi_a ATT(a, a+e)``, and both the treated and the control rows + are weighted so that each arm carries that share: + - "aggregate": share of treated units (trimmed aggregate ATT; treated + rows have Q = 1) + - "population": share of the treated units' population + - "sample_share": share of all units (treated plus clean controls) + Under ``survey_design=`` the shares are formed from survey-weighted + 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 @@ -133,9 +248,10 @@ class StackedDiD(BaseEstimator): trimmed-aggregate-ATT estimand (it changes only how untreated trends are estimated, not the treated-cohort weights); at ``b_sa=1`` it reduces to the paper's unit-count weighted stacked DID, equal to - ``weighting="aggregate"`` on balanced event windows. v1 requires - ``weighting="aggregate"`` and **balanced event windows** (ragged windows - raise a ``ValueError``), and does not support ``survey_design=``; + ``weighting="aggregate"``. v1 requires ``weighting="aggregate"`` and does + not support ``survey_design=``; on a ragged panel it runs on the units + observed over their whole event window, like the default path (see + Notes); matching-based balancing and the repeated-treatment extension are out of scope. Default ``"none"`` reproduces plain weighted stacked DID. df_convention : {"residual", "cluster", "normal"}, default "cluster" @@ -187,6 +303,23 @@ class StackedDiD(BaseEstimator): 2. Applying Q-weights to reweight the stacked regression 3. Running a single event-study WLS regression on the weighted stack + **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 are within-unit changes only when the same + units sit in every cell (the paper's stack has each unit observed for + ``kappa_pre + kappa_post + 1`` periods, Section 5.1). On a ragged panel + the units that are not are excluded from that sub-experiment with a + ``UserWarning`` reporting 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 are refused + (``NotImplementedError``). ``time`` must + be integer-valued with at most one row per unit and period. + References ---------- Wing, C., Freedman, S. M., & Hollingsworth, A. (2024). Stacked @@ -323,7 +456,8 @@ def fit( Use 0 or np.inf for never-treated units. population : str, optional Column name for population weights. Required only when - weighting="population". + weighting="population". Read for the treated units in the stack, + where it must be finite, non-negative and constant within a unit. survey_design : SurveyDesign, optional Survey design specification for design-based inference. When provided, uses Taylor Series Linearization for variance @@ -350,7 +484,29 @@ def fit( Raises ------ ValueError - If required columns are missing or data validation fails. + If required columns are missing or data validation fails: 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 + treated unit's population is missing, negative or not constant + within the unit, and under ``survey_design=`` when a survey column + varies within a unit. + NotImplementedError + 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). + + Warns + ----- + UserWarning + When units are excluded from a sub-experiment because they are + not observed at every event time of its window, and when an + adoption event is dropped because no treated unit or no clean + control is. Also when a sub-experiment carries zero weight (no + treated or control unit with positive survey weight, or a zero + treated population under ``weighting="population"``). """ # Fit-time re-check: __init__ and set_params validate eagerly, so # this only catches DIRECT attribute mutation (est.anticipation = ...) @@ -411,11 +567,18 @@ def fit( from diff_diff.survey import ( SurveyDesign, _resolve_survey_for_fit, + _validate_unit_constant_survey, ) resolved_survey, survey_weights, survey_weight_type, survey_metadata = ( _resolve_survey_for_fit(survey_design, data, "analytical") ) + # Survey columns must be constant within a unit: the regression + # contrasts event-time cell means, and a weight that changes over a + # unit's rows changes each cell's weighted composition exactly as a + # missing row does (REGISTRY StackedDiD complete-window Note). + if survey_design is not None and isinstance(survey_design, SurveyDesign): + _validate_unit_constant_survey(data, unit, survey_design) _uses_replicate_sd = resolved_survey is not None and resolved_survey.uses_replicate_variance # Reject fweight and aweight — Q-weight composition is ratio-valued @@ -464,6 +627,7 @@ def fit( df = data.copy() df[time] = pd.to_numeric(df[time]) df[first_treat] = pd.to_numeric(df[first_treat]) + self._validate_panel_grid(df, unit, time, first_treat) # ---- Data setup ---- # Handle never-treated encoding: both 0 and inf -> inf @@ -494,10 +658,33 @@ def fit( omega_kappa, trimmed = self._trim_adoption_events(omega_A, T_min, T_max, unit_info) # ---- 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 + # the window. Equation 3 contrasts (treated x event-time) and + # (control x event-time) cell means, which are within-unit changes + # only when the same units sit in every cell (Wing et al. 2024, + # Section 5.1: "each unit will be observed for kappa_pre + + # kappa_post + 1 time periods"). + win_lo = -self.kappa_pre - self.anticipation + win_hi = self.kappa_post + observed_periods = {int(t) for t in time_periods} sub_experiments = [] - skipped_events = [] + realized_events: List[Any] = [] + unrealized: Dict[Any, str] = {} + coverage: Dict[Any, Dict[str, int]] = {} for a in omega_kappa: - sub_exp = self._build_sub_experiment( + a_int = int(a) + # (i) A window period that NO unit observes: no unit can be + # complete, so the event cannot be realized. + absent = [ + t for t in range(a_int + win_lo, a_int + win_hi + 1) if t not in observed_periods + ] + if absent: + unrealized[a] = ( + f"calendar period(s) {absent} of its window are not observed for any unit" + ) + continue + sub_exp, counts = self._build_sub_experiment( df, unit_info, a, @@ -507,28 +694,150 @@ def fit( outcome, extra_cols=survey_cols, ) - if sub_exp is not None and len(sub_exp) > 0: + coverage[a] = counts + if sub_exp is not None: sub_experiments.append(sub_exp) + realized_events.append(a) else: - skipped_events.append(a) + reasons = [] + if counts["treated_kept"] == 0: + reasons.append( + "no treated unit is observed at every event time " + f"(0 of {counts['treated_eligible']})" + ) + if counts["control_kept"] == 0: + reasons.append( + "no clean control is observed at every event time " + f"(0 of {counts['control_eligible']})" + ) + unrealized[a] = " and ".join(reasons) + + n_dropped_treated = sum( + c["treated_eligible"] - c["treated_kept"] for c in coverage.values() + ) + n_dropped_control = sum( + c["control_eligible"] - c["control_kept"] for c in coverage.values() + ) + + # (ii)/(iii) Under a survey design, removing units for unit-level + # missingness is REFUSED before any estimate is formed: their PSUs + # and strata would leave the Taylor-linearized meat and df_survey, + # which is not domain estimation. An event lost to a period the + # whole panel lacks is refused for the same reason further down, + # after the "nothing left" diagnosis, which takes precedence when + # no event at all can be formed. + if survey_design is not None and (n_dropped_treated + n_dropped_control) > 0: + raise NotImplementedError( + "StackedDiD with survey_design= requires every treated and " + "clean-control unit to be observed at every event time of its " + f"sub-experiment window [{win_lo}, {win_hi}], but " + f"{n_dropped_treated} treated and {n_dropped_control} control " + "unit-by-sub-experiment entries are not (" + + self._format_coverage(coverage) + + "). Without a survey design those units are trimmed; under a " + "survey design removing them would drop their PSUs and strata " + "from the variance and its degrees of freedom, which is not " + "domain estimation. Supply a panel in which every unit is " + "observed at every period, or fit without survey_design=." + ) + + if len(sub_experiments) == 0: + raise ValueError( + "No sub-experiment has both a treated unit and a clean control " + f"observed at every event time of the window [{win_lo}, {win_hi}] " + f"(kappa_pre={self.kappa_pre}, kappa_post={self.kappa_post}, " + f"anticipation={self.anticipation}): " + + "; ".join(f"event {int(a)}: {why}" for a, why in unrealized.items()) + + "." + + self._describe_time_grid_gaps(T_min, T_max, observed_periods) + + " Reduce kappa_pre / kappa_post, or supply the missing observations." + ) - if skipped_events: + if survey_design is not None and unrealized: + raise NotImplementedError( + "StackedDiD with survey_design= cannot drop adoption event(s) " + "that have no sub-experiment of complete units (" + + "; ".join(f"event {int(a)}: {why}" for a, why in unrealized.items()) + + "): the dropped cohorts' PSUs and strata would leave the " + "survey variance and its degrees of freedom, which is not " + "domain estimation. Remove those cohorts from the data " + "yourself (and adjust the design accordingly), narrow the " + "event window, or fit without survey_design=." + ) + + if unrealized: warnings.warn( - f"Sub-experiments for events {skipped_events} were empty " f"after filtering.", + f"{len(unrealized)} adoption event(s) were dropped because no " + "sub-experiment could be formed from units observed at every " + f"event time of the window [{win_lo}, {win_hi}]: " + + "; ".join(f"event {int(a)}: {why}" for a, why in unrealized.items()) + + ". They are reported in trimmed_groups and do not enter the " + "trimmed aggregate ATT.", UserWarning, stacklevel=2, ) + trimmed = sorted(list(trimmed) + list(unrealized)) - if len(sub_experiments) == 0: - raise ValueError( - "All sub-experiments are empty after filtering. " - "Check your data or reduce kappa values." + realized_cov = {a: coverage[a] for a in realized_events} + n_trim_t = sum(c["treated_eligible"] - c["treated_kept"] for c in realized_cov.values()) + n_trim_c = sum(c["control_eligible"] - c["control_kept"] for c in realized_cov.values()) + if n_trim_t + n_trim_c > 0: + warnings.warn( + f"{n_trim_t} treated and {n_trim_c} control unit-by-sub-experiment " + "entries were excluded because the unit is not observed at every " + f"event time of the window [{win_lo}, {win_hi}] (" + + self._format_coverage(realized_cov) + + "). The stacked regression contrasts event-time cell means, " + "which requires the same units at every event time of a " + "sub-experiment (Wing et al. 2024, Section 5.1), so the estimand " + "is the trimmed aggregate ATT over the units observed across " + "their whole window.", + UserWarning, + stacklevel=2, ) stacked_df = pd.concat(sub_experiments, ignore_index=True) # ---- Compute Q-weights ---- - stacked_df = self._compute_q_weights(stacked_df, unit, population) + # Both arms must carry the same cohort shares (helper docstring), so + # the shares are formed from survey-weighted unit masses when a + # survey design supplies weights, and recomputed in every replicate. + _sub_arr = stacked_df["_sub_exp"].to_numpy() + _d_arr = stacked_df["_D_sa"].to_numpy() + _unit_arr = stacked_df[unit].to_numpy() + _survey_w_rows: Optional[np.ndarray] = None + if survey_design is not None and getattr(survey_design, "weights", None) is not None: + _survey_w_rows = stacked_df[survey_design.weights].to_numpy(dtype=np.float64) + _pop_rows: Optional[np.ndarray] = None + if self.weighting == "population": + assert population is not None # validated at the top of fit() + self._validate_treated_population(stacked_df, unit, population) + # Only treated rows are read: control populations are unused and + # may hold anything (missing values, pd.NA in an object column). + _treated_rows = _d_arr == 1 + _pop_rows = np.zeros(len(stacked_df), dtype=np.float64) + _pop_rows[_treated_rows] = pd.to_numeric( + stacked_df.loc[_treated_rows, population] + ).to_numpy(dtype=np.float64) + _q_rows, _zero_weight_events = _cohort_share_weights( + _sub_arr, + _d_arr, + _unit_arr, + self.weighting, + row_weights=_survey_w_rows, + population=_pop_rows, + ) + stacked_df["_Q_weight"] = _q_rows + if _zero_weight_events: + warnings.warn( + f"{len(_zero_weight_events)} sub-experiment(s) carry zero weight " + "and contribute nothing to the estimates: " + + "; ".join(f"event {int(a)}: {why}" for a, why in _zero_weight_events.items()) + + ". Their rows stay in the stack (and in groups, " + "n_sub_experiments and the unit counts).", + UserWarning, + stacklevel=2, + ) # ---- Covariate balancing: design weights b_sa -> effective-mass W_sa ---- # When balancing, this OVERWRITES `_Q_weight` with the CBWSDID final weights @@ -598,8 +907,12 @@ def fit( else np.ones(n_stacked, dtype=np.float64) ) composed_weights = Q_weights * survey_weights_stacked - # Normalize composed weights to sum = n_stacked - composed_weights = composed_weights * (n_stacked / np.sum(composed_weights)) + # Normalize composed weights to sum = n_stacked. A zero total (no + # sub-experiment carries weight) is left as is, so the + # reference-support guard below reports it. + _composed_sum = float(np.sum(composed_weights)) + if _composed_sum > 0: + composed_weights = composed_weights * (n_stacked / _composed_sum) else: composed_weights = Q_weights @@ -611,10 +924,12 @@ def fit( # defined relative to its cells. Equation 3 is a Q-WEIGHTED WLS, # so the check runs on the COMPOSED weights, not raw row # presence: a cell whose rows all carry zero effective weight - # (aggregate Q-weights zero a sub-experiment's controls at any - # event time where that sub-experiment has no treated rows; - # survey pweights can zero a cell outright) is as empty as a - # missing one. An effectively-empty cell makes the design + # (survey pweights can zero a cell outright; population + # weighting zeroes every weight when the treated population is + # zero) is as empty as a missing one, and with kappa_pre = 0 + # the reference lies outside the window altogether. Gapped and + # ragged panels no longer reach this guard: the complete-window + # rule in _build_sub_experiment removes them first. An effectively-empty cell makes the design # rank-deficient and QR pivoting silently re-normalizes against # an arbitrary surviving column - the surface would then certify # a delta_0 = 0 normalization that never happened (and @@ -636,16 +951,11 @@ def fit( "(delta_0 = 0 at the reference) would be fabricated: the " "regression's effective baseline cell is empty and rank " "handling would silently re-normalize against an " - "arbitrary horizon. Causes: a gapped panel where every " - "retained cohort's calendar period a - 1 - anticipation " - "is absent (the IC1 window check only inspects the " - "panel's min/max periods, not interior gaps); ragged " - "panels where the only reference-period control rows sit " - "in sub-experiments without treated reference rows " - "(aggregate Q-weights zero those controls); or survey " - "weights that zero out a reference cell. Fill the gap, " - "adjust anticipation/kappa_pre so the reference falls on " - "an observed period, or drop the affected cohorts." + "arbitrary horizon. Causes: kappa_pre = 0 (the reference " + "period lies outside the event window; use kappa_pre >= " + "1); weighting='population' with zero treated population " + "(every weight is then zero); or survey weights " + "that zero out a reference cell." ) Y = stacked_df[outcome].values @@ -825,10 +1135,23 @@ def fit( # fit() fires before this branch can be reached for any other # vcov_type. def _refit_stacked(w_r): - composed_r = Q_weights * w_r + # The corrective weights depend on the survey weights (they + # equalize the arms' survey-weighted cohort shares), so each + # replicate recomputes them from its own weights. + q_r, _ = _cohort_share_weights( + _sub_arr, + _d_arr, + _unit_arr, + self.weighting, + row_weights=w_r, + population=_pop_rows, + ) + composed_r = q_r * w_r w_sum = np.sum(composed_r) - if w_sum > 0: - composed_r = composed_r * (n_stacked / w_sum) + if not w_sum > 0: + # No sub-experiment has both arms in this replicate. + return np.full(X.shape[1], np.nan) + composed_r = composed_r * (n_stacked / w_sum) coef_r, _, _ = solve_ols( X, Y, @@ -1064,7 +1387,7 @@ def _refit_stacked(w_r): event_study_effects=event_study_effects, group_effects=None, stacked_data=stacked_df, - groups=list(omega_kappa), + groups=list(realized_events), trimmed_groups=list(trimmed), time_periods=time_periods, n_obs=len(data), @@ -1095,6 +1418,100 @@ def _refit_stacked(w_r): self.is_fitted_ = True return self.results_ + # ========================================================================= + # Input validation and coverage messages + # ========================================================================= + + @staticmethod + def _validate_panel_grid(df: pd.DataFrame, unit: str, time: str, first_treat: str) -> None: + """Reject inputs the event-time grid cannot represent. + + Event times are integer offsets ``time - a``, each unit contributes + one row per event time, and the adoption date ``a`` is an integer + period. A missing or fractional ``time``, a duplicated ``(unit, + time)`` row or a fractional ``first_treat`` would otherwise be + silently mis-assigned (dropped, absorbed into the reference + category, double-counted, or shifted by ``int()`` truncation). + """ + t_vals = df[time].to_numpy(dtype=float) + n_bad = int(np.sum(~np.isfinite(t_vals))) + if n_bad: + raise ValueError( + f"Column '{time}' has {n_bad} missing or non-finite value(s). " + "StackedDiD places every row at an integer event time; drop or " + "fill those rows before fitting." + ) + frac = t_vals != np.floor(t_vals) + if np.any(frac): + raise ValueError( + f"Column '{time}' must be integer-valued, but {int(np.sum(frac))} " + f"row(s) are not (e.g. {t_vals[frac][:3].tolist()}). Event times " + "are integer offsets from the adoption period; re-index time to " + "consecutive integers." + ) + dup = df.duplicated(subset=[unit, time], keep=False) + if dup.any(): + example = df.loc[dup, [unit, time]].iloc[0].tolist() + raise ValueError( + f"Found {int(dup.sum())} rows sharing a ({unit}, {time}) pair " + f"(e.g. {example}). StackedDiD requires at most one observation " + "per unit and period; aggregate or drop the duplicates." + ) + ft_vals = df[first_treat].to_numpy(dtype=float) + ft_frac = np.isfinite(ft_vals) & (ft_vals != np.floor(ft_vals)) + if np.any(ft_frac): + raise ValueError( + f"Column '{first_treat}' must hold integer adoption periods (or " + "0 / inf for never-treated units), but found non-integer " + f"value(s) (e.g. {np.unique(ft_vals[ft_frac])[:3].tolist()})." + ) + + @staticmethod + def _format_coverage(coverage: Dict[Any, Dict[str, int]], limit: int = 12) -> str: + """Per-event "kept of eligible" breakdown for the coverage messages.""" + affected = [ + (a, c) + for a, c in coverage.items() + if (c["treated_kept"] < c["treated_eligible"]) + or (c["control_kept"] < c["control_eligible"]) + ] + if not affected: + return "all units kept" + text = "kept " + "; ".join( + f"event {int(a)}: {c['treated_kept']} of {c['treated_eligible']} treated, " + f"{c['control_kept']} of {c['control_eligible']} control" + for a, c in affected[:limit] + ) + if len(affected) > limit: + text += f"; and {len(affected) - limit} more event(s)" + return text + + @staticmethod + def _describe_time_grid_gaps(T_min: int, T_max: int, observed_periods: set) -> str: + """Sentence naming integer periods the whole panel lacks (bounded cost).""" + span = T_max - T_min + 1 + n_obs_periods = len(observed_periods) + if span <= n_obs_periods: + return "" + advice = ( + " StackedDiD's event times are integer offsets of the time column, " + "so re-index time to consecutive integers (for example the rank of " + "each period) or narrow the window." + ) + if span > 10_000: + return ( + f" The time column spans {span} integer values but holds only " + f"{n_obs_periods} distinct periods (a datetime or coded time " + "column?)." + advice + ) + missing = [t for t in range(T_min, T_max + 1) if t not in observed_periods] + shown = missing[:12] + more = f" (first 12 of {len(missing)})" if len(missing) > 12 else "" + return ( + f" The panel's time grid has gaps: period(s) {shown}{more} are not " + "observed for any unit." + advice + ) + # ========================================================================= # Trimming (IC1 + IC2) # ========================================================================= @@ -1200,10 +1617,16 @@ def _build_sub_experiment( first_treat: str, outcome: str, extra_cols: Optional[List[str]] = None, - ) -> Optional[pd.DataFrame]: + ) -> Tuple[Optional[pd.DataFrame], Dict[str, int]]: """ Build a single sub-experiment for adoption event a. + Only units observed at EVERY integer event time of the window + ``[-kappa_pre - anticipation, kappa_post]`` are kept (the + complete-window rule: the paper's stack has each unit observed for + ``kappa_pre + kappa_post + 1`` periods, Section 5.1, and the + regression's cell-mean contrasts are within-unit changes only then). + Parameters ---------- df : pd.DataFrame @@ -1221,8 +1644,14 @@ def _build_sub_experiment( Returns ------- - pd.DataFrame or None - Sub-experiment data with _sub_exp, _event_time, _D_sa columns. + sub_df : pd.DataFrame or None + Sub-experiment data with _sub_exp, _event_time, _D_sa columns, or + None when no treated unit or no clean control is complete. + counts : dict + ``treated_eligible`` / ``control_eligible`` (units eligible by + ``first_treat``, with or without rows in the window) and + ``treated_kept`` / ``control_kept`` (those observed at every + event time). """ a_int = int(a) ft = unit_info["_first_treat"].values @@ -1241,8 +1670,14 @@ def _build_sub_experiment( control_mask = np.isinf(ft) control_units = set(unit_ids[control_mask]) + counts = { + "treated_eligible": len(treated_units), + "control_eligible": len(control_units), + "treated_kept": 0, + "control_kept": 0, + } if len(treated_units) == 0 or len(control_units) == 0: - return None + return None, counts # Time window: [a - kappa_pre - anticipation, a + kappa_post] # Reference period a-1 (event time e=-1) is included when kappa_pre >= 1 @@ -1256,181 +1691,64 @@ def _build_sub_experiment( mask = df[unit].isin(all_units) & (df[time] >= t_start) & (df[time] <= t_end) sub_df = df.loc[mask].copy() - if len(sub_df) == 0: - return None + # Complete-window rule: keep a unit only if it has a row at every + # integer event time of the window. Rows are unique per (unit, time) + # and integer-valued (``_validate_panel_grid``), so a row count equal + # to the window length is exact coverage. ``len(range(...))`` keeps a + # non-integer kappa failing with range()'s TypeError. + n_expected = len(range(t_start, t_end + 1)) + rows_per_unit = sub_df.groupby(unit).size() + complete = set(rows_per_unit.index[rows_per_unit == n_expected]) + counts["treated_kept"] = len(treated_units & complete) + counts["control_kept"] = len(control_units & complete) + if counts["treated_kept"] == 0 or counts["control_kept"] == 0: + return None, counts + if len(complete) < len(rows_per_unit): + sub_df = sub_df.loc[sub_df[unit].isin(complete)].copy() # Add sub-experiment columns sub_df["_sub_exp"] = a sub_df["_event_time"] = sub_df[time] - a_int sub_df["_D_sa"] = sub_df[unit].isin(treated_units).astype(int) - return sub_df + return sub_df, counts # ========================================================================= - # Q-weight computation + # Q-weight inputs # ========================================================================= - def _compute_q_weights( - self, - stacked_df: pd.DataFrame, - unit_col: str, - population_col: Optional[str], - ) -> pd.DataFrame: - """ - Compute Q-weights per Table 1 of Wing et al. (2024). - - Treated observations always get Q = 1. - Control observations get Q based on the weighting scheme. - - For aggregate weighting, Q-weights are computed using observation - counts per (event_time, sub_exp), matching the R reference - ``compute_weights()``. For balanced panels this is equivalent to - unit counts per sub-experiment. For unbalanced panels the weights - adjust for varying observation density per event time. - - Population and sample_share weighting use unit counts per - sub-experiment, following the paper's notation (N_a^D, N_a^C). - - Parameters - ---------- - stacked_df : pd.DataFrame - Stacked dataset with _sub_exp, _event_time, and _D_sa columns. - unit_col : str - Unit column name. - population_col : str, optional - Population column name (for weighting="population"). - - Returns - ------- - pd.DataFrame - stacked_df with _Q_weight column added. + @staticmethod + def _validate_treated_population( + stacked_df: pd.DataFrame, unit_col: str, population_col: str + ) -> None: + """Validate the population of the treated units in the stack. + + ``weighting="population"`` reads it into both arms' weights (the + paper's Table 1), so it must be finite, non-negative and constant + within a unit. Control units, and treated units that never enter the + stack, are not read and not validated. """ - if self.weighting == "aggregate": - return self._compute_q_weights_aggregate(stacked_df) - - # --- Population and sample_share: unit-count-based formulas --- - - # Count distinct units per sub-experiment - sub_exp_stats = ( - stacked_df.groupby(["_sub_exp", "_D_sa"])[unit_col].nunique().unstack(fill_value=0) - ) - - # N_a^D and N_a^C per sub-experiment - N_D = sub_exp_stats.get(1, pd.Series(dtype=float)).to_dict() - N_C = sub_exp_stats.get(0, pd.Series(dtype=float)).to_dict() - - # Totals - N_Omega_C = sum(N_C.values()) - - if self.weighting == "population": - # Pop_a^D: sum of population values for treated units per sub-exp - treated_pop = ( - stacked_df[stacked_df["_D_sa"] == 1] - .drop_duplicates(subset=[unit_col, "_sub_exp"]) - .groupby("_sub_exp")[population_col] - .sum() - .to_dict() + rows = stacked_df.loc[stacked_df["_D_sa"] == 1, [unit_col, population_col]] + values = pd.to_numeric(rows[population_col], errors="coerce").to_numpy(dtype=float) + bad = ~np.isfinite(values) + if np.any(bad): + raise ValueError( + f"Column '{population_col}' has {int(np.sum(bad))} missing or " + "non-finite value(s) on treated units; weighting='population' " + "needs a finite population for every treated unit." + ) + if np.any(values < 0): + raise ValueError( + f"Column '{population_col}' has negative value(s) on treated " + "units; weighting='population' needs non-negative populations." + ) + varying = rows.groupby(unit_col)[population_col].nunique() + if (varying > 1).any(): + raise ValueError( + f"Column '{population_col}' varies within {int((varying > 1).sum())} " + "treated unit(s); weighting='population' needs one population " + "value per unit." ) - Pop_D_total = sum(treated_pop.values()) - - q_control: Dict[Any, float] = {} - for a in N_D: - n_c = N_C.get(a, 0) - if n_c == 0 or N_Omega_C == 0: - q_control[a] = 1.0 - continue - control_share = n_c / N_Omega_C - pop_d = treated_pop.get(a, 0) - pop_share = pop_d / Pop_D_total if Pop_D_total > 0 else 0.0 - q_control[a] = pop_share / control_share if control_share > 0 else 1.0 - - else: # sample_share - N_Omega_D = sum(N_D.values()) - N_total = {a: N_D.get(a, 0) + N_C.get(a, 0) for a in N_D} - N_grand = N_Omega_D + N_Omega_C - - q_control = {} - for a in N_D: - n_c = N_C.get(a, 0) - if n_c == 0 or N_Omega_C == 0: - q_control[a] = 1.0 - continue - control_share = n_c / N_Omega_C - n_total_a = N_total.get(a, 0) - sample_share = n_total_a / N_grand if N_grand > 0 else 0.0 - q_control[a] = sample_share / control_share if control_share > 0 else 1.0 - - # Assign weights: treated=1, control=q_control[sub_exp] - sub_exp_vals = stacked_df["_sub_exp"].values - d_vals = stacked_df["_D_sa"].values - weights = np.ones(len(stacked_df)) - for i in range(len(stacked_df)): - if d_vals[i] == 0: - weights[i] = q_control.get(sub_exp_vals[i], 1.0) - - stacked_df["_Q_weight"] = weights - return stacked_df - - def _compute_q_weights_aggregate(self, stacked_df: pd.DataFrame) -> pd.DataFrame: - """ - Compute aggregate Q-weights using observation counts per (event_time, sub_exp). - - Matches the R reference ``compute_weights()`` which computes shares at the - (event_time, sub_exp) level, not the sub_exp level. For balanced panels the - two approaches are equivalent. For unbalanced panels this adjusts for varying - observation density per event time. - - R reference pattern:: - - stack_treat_n = count(D==1) BY event_time - stack_control_n = count(D==0) BY event_time - sub_treat_n = count(D==1) BY (sub_exp, event_time) - sub_control_n = count(D==0) BY (sub_exp, event_time) - sub_treat_share = sub_treat_n / stack_treat_n - sub_control_share = sub_control_n / stack_control_n - Q = sub_treat_share / sub_control_share (for controls) - Q = 1 (for treated) - """ - # Step 1: Stack-level totals by (event_time, D_sa) - stack_counts = stacked_df.groupby(["_event_time", "_D_sa"]).size().unstack(fill_value=0) - stack_treat_n = stack_counts.get(1, pd.Series(0, index=stack_counts.index)) - stack_control_n = stack_counts.get(0, pd.Series(0, index=stack_counts.index)) - - # Step 2: Sub-experiment-level counts by (event_time, sub_exp, D_sa) - sub_counts = ( - stacked_df.groupby(["_event_time", "_sub_exp", "_D_sa"]).size().unstack(fill_value=0) - ) - sub_treat_n = sub_counts.get(1, pd.Series(0, index=sub_counts.index)) - sub_control_n = sub_counts.get(0, pd.Series(0, index=sub_counts.index)) - - # Step 3: Compute shares and Q per (event_time, sub_exp) - # Q = (sub_treat_n / stack_treat_n) / (sub_control_n / stack_control_n) - q_lookup: Dict[Tuple[Any, Any], float] = {} - for et, sub_exp in sub_counts.index: - s_treat = sub_treat_n.get((et, sub_exp), 0) - s_control = sub_control_n.get((et, sub_exp), 0) - st_treat = stack_treat_n.get(et, 0) - st_control = stack_control_n.get(et, 0) - - if s_control == 0 or st_treat == 0 or st_control == 0: - q_lookup[(et, sub_exp)] = 1.0 - else: - treat_share = s_treat / st_treat - control_share = s_control / st_control - q_lookup[(et, sub_exp)] = treat_share / control_share if control_share > 0 else 1.0 - - # Step 4: Assign weights via vectorized merge - et_vals = stacked_df["_event_time"].values - sub_exp_vals = stacked_df["_sub_exp"].values - d_vals = stacked_df["_D_sa"].values - weights = np.ones(len(stacked_df)) - - for i in range(len(stacked_df)): - if d_vals[i] == 0: - weights[i] = q_lookup.get((et_vals[i], sub_exp_vals[i]), 1.0) - - stacked_df["_Q_weight"] = weights - return stacked_df # ========================================================================= # Covariate balancing (CBWSDID, Ustyuzhanin 2026) @@ -1475,52 +1793,13 @@ def _compute_balancing_weights( Nt_C: Dict[Any, float] = {} diagnostics: Dict[Any, Dict[str, Any]] = {} - # Balanced event windows are required: the paper's unit-count corrective and - # diff-diff's observation-count "aggregate" Q-weights coincide only when every - # unit is observed at every event time. On ragged windows they diverge (the - # count-convention is unresolved — out of scope for v1), so fail closed rather - # than silently producing unit-count estimates that differ from balance="none". - # The check validates exact (unit x event_time) coverage, not just row counts: - # it catches (a) eligible units with zero rows in the window (silently dropped - # by _build_sub_experiment, so invisible to a count), (b) wrong row counts, and - # (c) duplicate (unit, event_time) rows that a count-only check would let pass - # alongside a compensating missing row. - expected_events = list(range(-self.kappa_pre - self.anticipation, self.kappa_post + 1)) - n_expected = len(expected_events) - ft_by_unit = df.drop_duplicates(subset=[unit]).set_index(unit)[first_treat] - - def _expected_units(a_val: Any) -> set: - treated = set(ft_by_unit[ft_by_unit == a_val].index) - if self.control_group == "not_yet_treated": - controls = set(ft_by_unit[ft_by_unit > a_val + self.kappa_post].index) - elif self.control_group == "strict": - controls = set( - ft_by_unit[ft_by_unit > a_val + self.kappa_post + self.kappa_pre].index - ) - else: # never_treated - controls = set(ft_by_unit[np.isinf(ft_by_unit)].index) - return treated | controls - + # Every sub-experiment in the stack is balanced by construction: fit() + # rejects duplicate (unit, time) rows and _build_sub_experiment keeps + # only units observed at every event time of the window. The paper's + # unit-count corrective and the observation-count "aggregate" Q-weights + # therefore coincide here, on ragged input panels too. for a in sub_exps: sub = stacked_df[stacked_df["_sub_exp"] == a] - counts = sub.groupby(unit).size() - present_units = set(counts.index) - missing_eligible = _expected_units(a) - present_units # zero-row eligible units - wrong_count = set(counts[counts != n_expected].index) - dup_mask = sub.duplicated(subset=[unit, "_event_time"], keep=False) - dup_units = set(sub.loc[dup_mask, unit].unique()) - bad = missing_eligible | wrong_count | dup_units - if bad: - raise ValueError( - f"balance='entropy' requires balanced event windows, but cohort a={a} " - f"has {len(bad)} treated/clean-control unit(s) without exact coverage of " - f"the {n_expected} event times {expected_events} (zero-row, missing/extra, " - f"or duplicated (unit, event_time) rows; e.g. {list(bad)[:3]}). Covariate " - "balancing on unbalanced/ragged panels is out of scope for v1 because the " - "paper's unit-count corrective and diff-diff's observation-count " - "'aggregate' Q-weights diverge off balanced panels. Use balance='none', or " - "restrict to a balanced window." - ) treated_units = list(pd.unique(sub.loc[sub["_D_sa"] == 1, unit])) control_units = list(pd.unique(sub.loc[sub["_D_sa"] == 0, unit])) diff --git a/diff_diff/stacked_did_results.py b/diff_diff/stacked_did_results.py index 73834d07b..9d9f56a3d 100644 --- a/diff_diff/stacked_did_results.py +++ b/diff_diff/stacked_did_results.py @@ -63,9 +63,13 @@ class StackedDiDResults(BaseResults, AggregationMixin): Full stacked dataset with _sub_exp, _event_time, _D_sa, _Q_weight columns. Accessible for custom analysis. groups : list - Adoption events in the trimmed set (Omega_kappa). + Adoption events in the trimmed set (Omega_kappa) whose + sub-experiment was built: IC1 and IC2 hold and at least one + treated unit and one clean control are observed at every event + time of the window. trimmed_groups : list - Adoption events excluded by IC1/IC2. + Adoption events excluded by IC1/IC2, or left without a treated + unit or clean control observed at every event time of the window. time_periods : list All time periods in the original data. n_obs : int @@ -75,9 +79,10 @@ class StackedDiDResults(BaseResults, AggregationMixin): n_sub_experiments : int Number of sub-experiments in the stack. n_treated_units : int - Distinct treated units across trimmed set. + Distinct treated units in the stack (units observed at every + event time of their sub-experiment window). n_control_units : int - Distinct control units across trimmed set. + Distinct control units in the stack (same rule). kappa_pre : int Pre-treatment event-time window size. kappa_post : int diff --git a/docs/api/stacked_did.rst b/docs/api/stacked_did.rst index 0009782cb..f6656b131 100644 --- a/docs/api/stacked_did.rst +++ b/docs/api/stacked_did.rst @@ -89,7 +89,12 @@ Accessing the stacked dataset:: stacked = results.stacked_data print(stacked[['unit', 'period', '_sub_exp', '_event_time', '_D_sa', '_Q_weight']].head()) -Different weighting schemes:: +Different weighting schemes. Each fixes the share with which a sub-experiment +enters the aggregate (Wing et al. 2024, Table 1): the share of treated units +(``'aggregate'``, the default), of the treated units' population +(``'population'``) or of all units (``'sample_share'``). Treated and control +rows are both weighted so that each arm carries that share; under +``survey_design=`` the shares are formed from survey-weighted unit masses:: # Population-weighted ATT (requires population column) est = StackedDiD(kappa_pre=2, kappa_post=2, weighting='population') @@ -116,7 +121,7 @@ Comparison with Other Staggered Estimators - Pooled WLS on stacked sub-experiments - Separate group-time regressions * - Compositional balance - - Enforced by IC1/IC2 trimming + - Enforced by IC1/IC2 trimming and by keeping, in each sub-experiment, only the units observed at every event time of its window (excluded units are reported in a warning) - Via balanced event study aggregation * - Target parameter - Trimmed aggregate ATT @@ -125,5 +130,5 @@ Comparison with Other Staggered Estimators - Full stacked dataset accessible - Group-time effects accessible * - Covariates - - Entropy balancing via ``balance="entropy"`` + ``fit(covariates=...)`` (CBWSDID, Ustyuzhanin 2026); requires ``weighting="aggregate"`` + balanced windows, no ``survey_design`` + - Entropy balancing via ``balance="entropy"`` + ``fit(covariates=...)`` (CBWSDID, Ustyuzhanin 2026); requires ``weighting="aggregate"``, no ``survey_design`` - Supported (OR, IPW, DR) diff --git a/docs/choosing_estimator.rst b/docs/choosing_estimator.rst index d95d4b4fc..bce96dc0f 100644 --- a/docs/choosing_estimator.rst +++ b/docs/choosing_estimator.rst @@ -590,7 +590,11 @@ with clean controls and apply Q-weights to reweight the stacked regression. .. note:: The trimmed aggregate ATT may exclude early or late cohorts whose event - windows do not fit in the data. Check ``results.trimmed_groups``. + windows do not fit in the data, and cohorts left without a treated unit or + clean control observed at every event time of the window. Check + ``results.trimmed_groups``. On a panel with missing observations, units not + observed across a sub-experiment's whole window are excluded from it with a + warning. TROP ~~~~ diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index d8a75d215..00f6b7f30 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -2524,10 +2524,14 @@ Estimated via WLS with Q-weights. The delta_h coefficients identify theta_kappa^ *Q-weights (Section 5.3, Table 1):* - Q_sa = 1 if D_sa = 1 (treated) - Q_sa = (N_a^D / N^D) / (N_a^C / N^C) if D_sa = 0 (control, aggregate weighting) - Q_sa = (Pop_a^D / Pop^D) / (N_a^C / N^C) if D_sa = 0 (control, population weighting) - Q_sa = ((N_a + N_a^C)/(N^D+N^C)) / (N_a^C/N^C) if D_sa = 0 (control, sample share weighting) + Q_sa = pi_a / (N_a^D / N^D) if D_sa = 1 (treated) + Q_sa = pi_a / (N_a^C / N^C) if D_sa = 0 (control) + + pi_a = N_a^D / N^D (aggregate weighting: treated Q_sa = 1) + pi_a = Pop_a^D / Pop^D (population weighting) + pi_a = (N_a^D + N_a^C) / (N^D + N^C) (sample share weighting) + +`pi_a` is the share of sub-experiment `a` in the target aggregate `sum_a pi_a ATT(a, a+e)`. Both arms carry it: Section 5.3 shows the untreated trends cancel only if the treated arm and the control arm aggregate the sub-experiments with the same shares. Under a survey design the counts are replaced by survey-weighted unit masses (survey-weights Note below). *Standard errors (Section 5.4):* - Default: Cluster-robust standard errors at the group (unit) level @@ -2565,8 +2569,11 @@ records the resolved df per event time as before. *Edge cases:* - All events trimmed: `len(Omega_kappa) == 0` -> ValueError suggesting reduced kappa - No clean controls for event a: IC2 check fails -> Trim event, warn user +- No treated unit, or no clean control, observed at every event time of event a's window (including a window that contains a calendar period no unit observes): drop the event with a `UserWarning`, report it in `trimmed_groups`; no event left -> `ValueError`; under `survey_design=` -> `NotImplementedError` (complete-window Notes below) +- Unit not observed at every event time of a sub-experiment's window: excluded from that sub-experiment with a `UserWarning` (complete-window Note below); under `survey_design=` -> `NotImplementedError` - Single cohort in trimmed set: Valid — Q-weights simplify -- Duplicate observations: Same (unit, time) appears in multiple sub-experiments -> handled by clustering at unit level +- 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. - Group aggregation: Not supported — pooled stacked regression cannot produce cohort-specific effects. Use CallawaySantAnna or ImputationDiD. @@ -2574,9 +2581,9 @@ records the resolved df per event time as before. *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]) +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 4. Stack all sub-experiments vertically -5. Compute Q-weights: aggregate weighting uses observation counts per (event_time, sub_exp), matching R reference. Population/sample_share use unit counts per sub_exp (paper notation). +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 7. Extract delta_h coefficients as event-study ATTs 8. Compute cluster-robust SEs at unit level @@ -2602,6 +2609,7 @@ The paper text states a stricter bound (T_min + 1) but the R code by the co-auth **Requirements checklist:** - [x] Sub-experiment construction with treated + clean controls + time window - [x] IC1 and IC2 trimming with warnings +- [x] Complete-window rule: units not observed at every event time of a sub-experiment are excluded with a warning; events left without a complete treated unit or clean control are dropped - [x] Q-weight computation for all three weighting schemes (Table 1) - [x] WLS via sqrt(w) transformation - [x] Event study regression (Equation 3) with reference period e=-1 @@ -2609,7 +2617,7 @@ The paper text states a stricter bound (T_min + 1) but the R code by the co-auth - [x] Overall ATT as average of post-treatment delta_h with delta-method SE - [x] Anticipation parameter support - [x] Never-treated encoding (0 and inf) -- [x] Survey design support (Phase 3): Q-weights compose multiplicatively with survey weights; TSL vcov on composed weights; survey design columns propagated through sub-experiments. Replicate weights supported via estimator-level refit with Q-weight composition (see Replicate Weight Variance section). +- [x] Survey design support (Phase 3): Q-weights are formed from survey-weighted unit masses and compose multiplicatively with the survey weights; TSL vcov on composed weights; survey design columns propagated through sub-experiments. Replicate weights supported via estimator-level refit that recomputes the Q-weights from each replicate's weights (see Replicate Weight Variance section). - **Note:** M-080 position (auto-cluster policy, re-scoped 2026-10-18 - category c3 in `docs/methodology/variance-conventions.md` "Default clustering roster"; 7b, 2026-10-29: still rejected, unchanged - StackedDiD keeps its own vocabulary validator @@ -2621,6 +2629,12 @@ The paper text states a stricter bound (T_min + 1) but the R code by the co-auth instance of the general policy" applies to the default resolution only. - **Note (intercept SEs excluded from R parity):** for the base StackedDiD `clubSandwich` parity fixture (not the CBWSDID `cbwsdid` fixture below), stacked event-study *interaction* SEs match R at ~2e-13, but the regression *intercept* SE differs from R by a measured ~0.3% — a nuisance-parameter reference-cell/parameterization gap, not machine-precision lockable. Surfacing `se_cr1_intercept`/`se_cr2_intercept` would add an unasserted, R-divergent public field, so intercept SEs are deliberately not exposed and are excluded from the parity lock (`tests/test_methodology_stacked_did.py`; SE-audit C1/(c) decision, 2026-07-09). - **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 (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`). +- **Deviation from R:** the reference `create_sub_exp()` keeps every row of an eligible unit inside the window and never checks coverage, and the reference `compute_weights()` then uses per-(sub-experiment, event-time) row counts. On a ragged panel that code returns the shifted estimates (verified by execution: on a noisy panel in which half of one cohort misses its `e = -1` row, the reference code gives `delta_{-2} = -0.270` where the complete-window fit gives `0.012`; the library before this rule matched the reference code to 12 digits). diff-diff applies the complete-window rule instead. On a stack trimmed by hand the reference code and diff-diff agree to 1e-10 in coefficients and cluster-robust SEs, and balanced panels are unaffected. ### Covariate balancing (CBWSDID) @@ -2641,14 +2655,14 @@ The pooled estimator is `DID^{CBWSDID}_e = Σ_a (N^D_a/N^D_Ω)(Δ̄^D_{a,e} − - **Note:** Inference is conditional-on-the-estimated-weights cluster-robust (the existing `hc1`/`hc2_bm` path with `W_{sa}` as the WLS weights) — the paper's default. The paper's weight-re-estimating bootstrap is NOT implemented in v1 (deliberate scope; entropy balancing is smooth so the Abadie–Imbens (2008) nonsmooth-matching bootstrap caveat does not apply). `cluster` is orthogonal to `b_{sa}` (weights conditioned-on); default `unit` matches the paper. - **Note:** v1 scope — only `balance="entropy"` with `weighting="aggregate"`. `balance` + `population`/`sample_share` and `balance` + `survey_design=` raise `NotImplementedError`; matching-based balancing and the repeated `0→1/1→0` episode extension are out of scope. - **Note (post-fit aggregate() - row M-024):** `fit(aggregate=)` was deprecated in 3.9 and REMOVED at 4.0 (PR 3b of the cut; its `group`/`all`/unknown ValueErrors died with it - `aggregate('group')` already fails closed in the mixin - and `population`/`survey_design`/`covariates` are positional slots 6/7/8) and the event-study surface is ALWAYS materialized at fit — the pooled regression always included the event-time interactions, so only the extraction and, under `hc2_bm`, the per-event Bell-McCaffrey contrast DOFs were fit-time-gated; both gates are gone (the param had been behaviorally inert since 3.9). `aggregate('event_study')` returns the unified `EventStudyResults` container (a pure view; no recomputation, so every stored inference mode — survey TSL, replicate refit, hc2_bm fail-close — relays faithfully); `aggregate('simple')` relays `att/se/t/p/CI` bit-exactly with `target="att"` (the scalar is the equally-weighted post-period average, NOT the per-event-time trimmed aggregate ATT `θ^e_κ` — `describe_target_parameter` remains the estimand's prose source of truth), `n = n_treated_units` with `n_kind="units"` (TREATED-only scope: under dynamic clean-control definitions a later-treated unit is treated in its own sub-experiment and a clean control in earlier ones, so the treated and control unit sets OVERLAP and no disjoint total exists — cross-container `n` comparisons vs CallawaySantAnna's treated+control convention are out of contract), and `df = inference_df` (the stored overall inference's exact provenance). Consequences of the always-computed surface: plain-fit `summary()` renders the event-study table, `to_dataframe('event_study')` is total on 3.9+ fits, `plot_event_study` renders plain fits, DiagnosticReport's `heterogeneity` (always) and `parallel_trends` (`kappa_pre >= 2`) checks run on plain fits, and the `hc2_bm` overall-ATT contrast now shares the m>1 batch of `_compute_cr2_bm_contrast_dof`, whose degeneracy guard is batch-relative — the noise-floor carve-out on the `Wald_test(test="HTZ")$df_denom` parity claim in the variance-families bullets above widens quantitatively (unchanged behavior when tripped: fail-closed NaN inference plus linalg's loud noise-floor UserWarning; the absolute floor already made this reachable at m=1). -- **Note (container admission - rows M-024/M-093):** `compute_honest_did` and `compute_pretrends_power` admit Stacked-sourced `aggregate('event_study')` containers. Provenance: `base_period` is the class-level constant `"universal"` (every sub-experiment normalizes against the single omitted reference `e = -1 - anticipation`) and `reference_event_times` is the singleton `(-1 - anticipation,)`. Requirements: `kappa_pre >= 2` (the default `kappa_pre=1` grid minus the reference has ZERO estimated pre-periods — both consumers reject), and for HonestDiD a non-singular FULL retained event-study covariance — the validated sub-block spans the retained pre AND post rows (`allow_singular=False` per Rambachan-Roth's eigenvalues-bounded-away-from-zero assumption on the full Σ — keep `kappa_pre` small relative to the cluster count; PreTrendsPower keeps its documented singular support). The container's scalar `df_survey` is None on analytical fits — the generic resolver's fallback reads `df_inference`, a name StackedDiD does not carry (`inference_df` is the overall POST-AVERAGE contrast df, not a design-level cluster df, and misusing it for FLCI critical values would be worse than the asymptotic default) — so honest FLCI critical values are NORMAL-THEORY on analytical Stacked fits, diverging from bare-`cluster=` CS fits (which thread `G-1`); survey fits thread the survey df and replicate-undefined designs the fail-closed `0.0` sentinel (NaN FLCI CIs; the identified-set `lb`/`ub` bounds are df-independent and stay finite). Withheld-inference rows (finite `se`, non-finite `p_value` — the hc2_bm BM-DOF fail-close and replicate-undefined designs both emit this shape) are ADMITTED with a source-scoped warning in BOTH consumers: bounds/power consume only the point estimates and covariance, which remain valid; the warning is shape-descriptive because containers are publicly constructible. A rank-dropped interior event-time column (NaN-se row) fails closed via honest's consecutive-grid ValueError with a Stacked-specific remedy (no `balance_e` — Stacked's aggregate() has no such level). REFERENCE-SUPPORT GUARD: `fit()` raises when either omitted-reference cell (treated / control) carries no POSITIVE COMPOSED WLS WEIGHT — Equation 3 is Q-weighted, so raw row presence is not support: a gapped panel can empty the cell outright (IC1 checks only min/max periods), aggregate Q-weights zero a sub-experiment's controls at any event time where that sub-experiment has no treated rows, and survey pweights can zero a cell — without the guard the design rank-drops and QR pivoting silently re-normalizes against an arbitrary horizon while the surface certifies `delta_0 = 0` at the reference. Partial support (some cohorts' own ref period absent while the POOLED omitted category is populated) still fits: the coefficient-vector normalization is real; the per-cohort baseline raggedness is estimand composition, the documented ragged-window behavior. +- **Note (container admission - rows M-024/M-093):** `compute_honest_did` and `compute_pretrends_power` admit Stacked-sourced `aggregate('event_study')` containers. Provenance: `base_period` is the class-level constant `"universal"` (every sub-experiment normalizes against the single omitted reference `e = -1 - anticipation`) and `reference_event_times` is the singleton `(-1 - anticipation,)`. Requirements: `kappa_pre >= 2` (the default `kappa_pre=1` grid minus the reference has ZERO estimated pre-periods — both consumers reject), and for HonestDiD a non-singular FULL retained event-study covariance — the validated sub-block spans the retained pre AND post rows (`allow_singular=False` per Rambachan-Roth's eigenvalues-bounded-away-from-zero assumption on the full Σ — keep `kappa_pre` small relative to the cluster count; PreTrendsPower keeps its documented singular support). The container's scalar `df_survey` is None on analytical fits — the generic resolver's fallback reads `df_inference`, a name StackedDiD does not carry (`inference_df` is the overall POST-AVERAGE contrast df, not a design-level cluster df, and misusing it for FLCI critical values would be worse than the asymptotic default) — so honest FLCI critical values are NORMAL-THEORY on analytical Stacked fits, diverging from bare-`cluster=` CS fits (which thread `G-1`); survey fits thread the survey df and replicate-undefined designs the fail-closed `0.0` sentinel (NaN FLCI CIs; the identified-set `lb`/`ub` bounds are df-independent and stay finite). Withheld-inference rows (finite `se`, non-finite `p_value` — the hc2_bm BM-DOF fail-close and replicate-undefined designs both emit this shape) are ADMITTED with a source-scoped warning in BOTH consumers: bounds/power consume only the point estimates and covariance, which remain valid; the warning is shape-descriptive because containers are publicly constructible. A rank-dropped interior event-time column (NaN-se row) fails closed via honest's consecutive-grid ValueError with a Stacked-specific remedy (no `balance_e` — Stacked's aggregate() has no such level). REFERENCE-SUPPORT GUARD: `fit()` raises when either omitted-reference cell (treated / control) carries no POSITIVE COMPOSED WLS WEIGHT — Equation 3 is Q-weighted, so raw row presence is not support: `kappa_pre = 0` puts the reference outside the event window, `weighting="population"` with zero treated population zeroes every weight (the treated reference cell is then the one reported empty), and survey pweights can zero a cell (gapped and ragged panels no longer reach the guard: the complete-window rule removes them first) — without the guard the design rank-drops and QR pivoting silently re-normalizes against an arbitrary horizon while the surface certifies `delta_0 = 0` at the reference. A cohort whose own reference period is absent no longer contributes with a ragged baseline: its units are incomplete, so the complete-window rule drops the event (or excludes the incomplete units) and the pooled reference category holds only cohorts observed at their own reference period. - **Note (reference-row marking, 4.0, [M-093] item 8a):** the always-materialized `event_study_effects` reference row (`e = -1 - anticipation`) carries `"is_reference": True` and no `n_obs` key (3.x: the `n_obs == 0` sentinel, retired); `summary()` keys its `[ref: h]` line on the marker; `plot_event_study(results)` and `DiagnosticReport` locate the reference by the key; 3.x pickles are migrated on load (`__setstate__`). Since 8b `to_dataframe(level='event_study')` is the unified `EVENT_STUDY_SCHEMA` frame (`n` NaN on the `is_reference` row). *Covariate-balancing edge cases:* - Infeasible cohort (treated covariate mean outside the clean-control hull → entropy balancing cannot match the moments): **fail-closed** `ValueError` naming the cohort and worst covariate — NOT silently dropped (dropping a cohort would shift the estimand to an overlap-trimmed ATT, Ustyuzhanin 2026 §3.1). - Degenerate design weights (`Ñ^C_a → 0` / highly concentrated weights): low effective sample size → `UserWarning` with the per-cohort diagnostic. -- Missing pre-treatment row, or covariate absent / `balance`↔`covariates` mismatch: `ValueError` at `fit()`. -- **Ragged / unbalanced event windows** (a unit not observed at every event time in a sub-experiment): **fail-closed `ValueError`** — `balance="entropy"` requires balanced windows. The paper assumes balanced event windows; off them the unit-count corrector and the observation-count `aggregate` Q diverge (the count-convention is unresolved, deferred). `balance="none"` continues to support unbalanced panels via observation-count Q. +- Covariate absent / `balance`↔`covariates` mismatch: `ValueError` at `fit()`. A unit missing its pre-treatment reference row is excluded by the complete-window rule whenever the reference period lies inside the window; the reference-row lookup can raise `ValueError` only when it lies outside (`kappa_pre = 0`). +- **Note (ragged / unbalanced event windows):** the complete-window rule of the StackedDiD section applies unchanged under `balance="entropy"`: units not observed at every event time of a sub-experiment are excluded with the same warning, balancing runs on the complete units, and `balance_diagnostics` counts them. This matches R `cbwsdid`, which also builds each sub-experiment from the units observed across the whole window (verified by execution on a ragged copy of the parity panel: 1,185 stacked rows in both, dynamic ATTs within 9e-8; pinned by the `dynamic_ragged` block of `benchmarks/data/cbwsdid_golden.json`). Before this rule `balance="entropy"` raised `ValueError` on any ragged window. - **Note:** `anticipation` is validated at construction (non-negative integer; `bool` rejected) via the shared `utils.validate_anticipation`, and re-checked on the fit path (direct-mutation defense) — see the family-wide adoption note (ledger row [M-144]) in the TripleDifference staggered-mode section. --- @@ -8319,7 +8333,7 @@ variance from the distribution of replicate estimates. estimator-level refit - the removed MultiPeriodDiD's two lanes), TwoWayFixedEffects (estimator-level refit with within-transformation), SunAbraham (estimator-level refit, replaces `vcov_cohort`), - StackedDiD (estimator-level refit with Q-weight composition), + StackedDiD (estimator-level refit; the Q-weights are recomputed from each replicate's weights), ImputationDiD (two-stage refit), TwoStageDiD (two-stage refit), ChaisemartinDHaultfoeuille (closed-form cell-collapse replicate ATT, multi-horizon and placebo paths; replicate + `n_bootstrap > 0` rejected diff --git a/docs/tutorials/13_stacked_did.ipynb b/docs/tutorials/13_stacked_did.ipynb index a24071c4a..3f508c49f 100644 --- a/docs/tutorials/13_stacked_did.ipynb +++ b/docs/tutorials/13_stacked_did.ipynb @@ -177,7 +177,7 @@ " print(f\"{int(sub_exp):>8} {n_treated:>10} {n_controls:>10} {avg_q:>14.3f}\")\n", "\n", "print()\n", - "print(\"Note: Treated units always have Q = 1. Controls get adjusted weights.\")" + "print(\"Note: under the default 'aggregate' weighting treated units have Q = 1 and controls get adjusted weights.\")" ] }, { @@ -256,9 +256,9 @@ "\n", "Wing et al. (2024, Table 1) define three target estimands, each with a different Q-weight formula:\n", "\n", - "- **`\"aggregate\"`** (default): Weight by treated cohort size (N_a^D / N_Ω^D) — the trimmed aggregate ATT. (For unbalanced panels, weights are computed at the observation level per (event_time, sub_exp), which reduces to cohort-size weighting when panels are balanced.)\n", - "- **`\"population\"`**: Weight by population size of treated cohort (requires a `population` column)\n", - "- **`\"sample_share\"`**: Weight by sample share of each sub-experiment\n", + "- **`\"aggregate\"`** (default): Weight by treated cohort size (N_a^D / N_Ω^D) — the trimmed aggregate ATT. (On a panel with missing observations, each sub-experiment keeps only the units observed at every event time of its window and `fit()` warns with the counts, so the cohort sizes count those units.)\n", + "- **`\"population\"`**: Weight by population size of treated cohort (requires a `population` column); treated and control rows are both reweighted\n", + "- **`\"sample_share\"`**: Weight by sample share of each sub-experiment; treated and control rows are both reweighted\n", "\n", "The choice depends on whether you want cohorts weighted by their treated unit count (`aggregate`), by an external population measure (`population`), or by their share of the stacked sample (`sample_share`)." ] diff --git a/tests/test_methodology_stacked_did.py b/tests/test_methodology_stacked_did.py index 5a3e55df6..a8f3a926c 100644 --- a/tests/test_methodology_stacked_did.py +++ b/tests/test_methodology_stacked_did.py @@ -585,8 +585,9 @@ def test_anticipation1_hc2_bm_matches_clubsandwich_cr2(self, goldens, panel): ) def test_sample_share_weighting_hc1_matches_clubsandwich_cr1s(self, goldens, panel): - """weighting='sample_share' uses a distinct Q-weight formula - `Q_sa = ((N^D_a + N^C_a)/(N^D+N^C)) / (N^C_a/N^C)` for controls. + """weighting='sample_share' uses the target share + `pi_a = (N^D_a + N^C_a)/(N^D+N^C)`, with `Q_sa = pi_a / (N^C_a/N^C)` for + controls and `Q_sa = pi_a / (N^D_a/N^D)` for treated rows (Table 1). Pin R parity at atol=1e-10 (per R9 P1).""" if "sample_share" not in goldens: pytest.skip("sample_share variant not in goldens") @@ -1009,3 +1010,44 @@ def test_dynamic_atts_match_r_cbwsdid(self): rtol=0.02, err_msg=f"event {et}: python SE {py_se} vs R cbwsdid SE {r_se}", ) + + def test_ragged_panel_matches_r_cbwsdid(self): + """On a ragged panel R ``cbwsdid`` builds each sub-experiment from the + units observed across the whole event window - the complete-window rule + StackedDiD applies. The ``dynamic_ragged`` golden block (same panel with + ten rows dropped) pins the stack size and the dynamic ATTs.""" + import warnings + + with open(_CBWSDID_GOLDEN) as f: + g = json.load(f) + if "dynamic_ragged" not in g: + pytest.skip("cbwsdid_golden.json has no dynamic_ragged block; regenerate it") + df = pd.read_csv(_CBWSDID_PANEL) + drop = (df["unit"].between(1, 5) & (df["time"] == 6)) | ( + df["unit"].between(55, 59) & (df["time"] == 5) + ) + ragged = df[~drop].reset_index(drop=True) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + res = StackedDiD( + kappa_pre=2, + kappa_post=2, + weighting="aggregate", + control_group="not_yet_treated", + cluster="unit", + balance="entropy", + ).fit( + ragged, + outcome="y", + unit="unit", + time="time", + first_treat="first_treat", + covariates=["x"], + ) + assert any("not observed at every" in str(w.message) for w in caught) + block = g["dynamic_ragged"] + assert res.n_stacked_obs == block["nobs"] + for et, r_est, r_se in zip(block["event_time"], block["estimate"], block["std_error"]): + py = res.event_study_effects[et]["effect"] + assert abs(py - r_est) < 1e-5, f"event {et}: python {py} vs R cbwsdid {r_est}" + np.testing.assert_allclose(res.event_study_effects[et]["se"], r_se, rtol=0.02) diff --git a/tests/test_stacked_did.py b/tests/test_stacked_did.py index 96b65658f..eab83b49a 100644 --- a/tests/test_stacked_did.py +++ b/tests/test_stacked_did.py @@ -289,7 +289,7 @@ class TestQWeights: """Tests for Q-weight computation.""" def test_treated_weight_is_one(self, staggered_data): - """All treated observations should have Q=1.""" + """All treated observations have Q=1 under the default aggregate weighting.""" est = StackedDiD(kappa_pre=2, kappa_post=2) results = est.fit( staggered_data, @@ -588,7 +588,8 @@ def test_anticipation_reference_period(self): assert np.isfinite(results.att) def test_unbalanced_panel(self): - """Works with missing observations within the window.""" + """Missing observations inside a window trim the unit from that + sub-experiment (complete-window rule), with a warning.""" data = generate_staggered_data( n_units=200, n_periods=12, @@ -603,17 +604,39 @@ def test_unbalanced_panel(self): data = data.drop(data.index[drop_idx]).reset_index(drop=True) est = StackedDiD(kappa_pre=2, kappa_post=2) - results = est.fit( - data, - outcome="outcome", - unit="unit", - time="period", - first_treat="first_treat", - ) + with pytest.warns(UserWarning, match="not observed at every"): + results = est.fit( + data, + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + ) sd = results.stacked_data assert np.isfinite(results.att) assert np.all(sd["_Q_weight"] > 0) assert np.all(np.isfinite(sd["_Q_weight"])) + # Every unit left in a sub-experiment covers the whole window. + rows = sd.groupby(["_sub_exp", "unit"])["_event_time"].agg(["size", "nunique"]) + assert (rows["size"] == 5).all() and (rows["nunique"] == 5).all() + assert results.n_stacked_obs < len( + StackedDiD(kappa_pre=2, kappa_post=2) + .fit( + generate_staggered_data( + n_units=200, + n_periods=12, + cohort_periods=[4, 6, 8], + never_treated_frac=0.3, + treatment_effect=5.0, + seed=42, + ), + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + ) + .stacked_data + ) def test_nan_inference(self): """Degenerate case with NaN inference fields.""" @@ -1321,8 +1344,14 @@ def test_replicate_refit_coef_bit_equal_vs_bake_w_baseline(self, baseline_panel) # aggregation, so SE gets atol=1e-10. Both bands match # similar "no methodologically significant drift" tolerances # used elsewhere in the project. + # The ATT is the full-sample fit (w = 1.0, default weighting), whose + # Q-weights are untouched. The SE moved from 0.14697256517699428 when + # the replicate refits began recomputing the corrective weights from + # each replicate's own (non-uniform) weights; the new value is the one + # TestStackedDiDCohortShares::test_replicate_refits_recompute_the_shares + # justifies against independent per-replicate fits. BASELINE_ATT = 2.0807833161293945 - BASELINE_SE = 0.14697256517699428 + BASELINE_SE = 0.1447117933599559 np.testing.assert_allclose(res.att, BASELINE_ATT, atol=1e-13) np.testing.assert_allclose(res.se, BASELINE_SE, atol=1e-10) @@ -1899,41 +1928,56 @@ def test_get_params_includes_balance_and_clone(self): clone = StackedDiD(**est.get_params()) # round-trip assert clone.balance == "entropy" - def test_ragged_event_window_raises(self): - # balance="entropy" requires balanced event windows: on a ragged panel (a unit - # missing a non-reference event-time row) the unit-count corrector and the - # observation-count aggregate Q diverge, so fail closed. balance="none" still - # supports the unbalanced panel. + def test_ragged_event_window_trims(self): + # A treated unit missing one event-time row is trimmed from its + # sub-experiment (complete-window rule), under balance="entropy" exactly + # as under balance="none"; the fit equals the fit without that unit. df = _balance_panel(seed=10, const_x=True) u = int(df.loc[df["first_treat"] == 4, "unit"].iloc[0]) drop = (df["unit"] == u) & (df["time"] == 5) # a post-period row (keeps t=a-1 ref) dfr = df[~drop].reset_index(drop=True) - with pytest.raises(ValueError, match="balanced event windows"): - _cb_fit(dfr, balance="entropy", covariates=["x"]) - assert np.isfinite(_cb_fit(dfr, balance="none").att) - - def test_zero_row_eligible_control_raises(self): + dfu = df[df["unit"] != u].reset_index(drop=True) + for balance, cov in (("entropy", ["x"]), ("none", None)): + with pytest.warns(UserWarning, match="not observed at every"): + ragged = _cb_fit(dfr, balance=balance, covariates=cov) + removed = _cb_fit(dfu, balance=balance, covariates=cov) + np.testing.assert_allclose(ragged.att, removed.att, rtol=1e-12) + np.testing.assert_allclose(ragged.se, removed.se, rtol=1e-12) + assert ragged.n_treated_units == removed.n_treated_units + assert ragged.n_treated_units == df.loc[df["first_treat"] > 0, "unit"].nunique() - 1 + entropy = _cb_fit(dfr, balance="entropy", covariates=["x"]) + assert entropy.balance_diagnostics[4]["n_treated"] == 19 # 20 per cohort, one trimmed + + def test_zero_row_eligible_control_is_trimmed(self): # An eligible (never-treated) control with ZERO rows in a cohort's window is - # silently dropped by _build_sub_experiment — the count-only guard misses it, - # the exact-coverage guard catches it (missing_units). + # not in that sub-experiment; with rows missing in every cohort's window it + # is in none, and the balanced fit equals the fit without the unit. df = _balance_panel(seed=11, const_x=True) u = int(df.loc[df["first_treat"] == 0, "unit"].iloc[0]) # a never-treated unit drop = (df["unit"] == u) & (df["time"].between(2, 6)) # cohort-4 window [2,6] dfz = df[~drop].reset_index(drop=True) - with pytest.raises(ValueError, match="balanced event windows"): - _cb_fit(dfz, balance="entropy", covariates=["x"]) - - def test_duplicate_and_missing_event_time_raises(self): - # A unit with a duplicated event time AND a missing one nets the expected row - # count, bypassing a count-only guard; the exact-coverage guard catches the - # duplicate (unit, event_time). + with pytest.warns(UserWarning, match="not observed at every"): + ragged = _cb_fit(dfz, balance="entropy", covariates=["x"]) + removed = _cb_fit( + df[df["unit"] != u].reset_index(drop=True), balance="entropy", covariates=["x"] + ) + np.testing.assert_allclose(ragged.att, removed.att, rtol=1e-12) + assert u not in set(ragged.stacked_data["unit"]) + for a, diag in ragged.balance_diagnostics.items(): + assert diag["n_control"] == removed.balance_diagnostics[a]["n_control"] + + def test_duplicate_unit_time_rows_raise(self): + # Duplicate (unit, time) rows are rejected at fit(), whatever the balance + # mode: a duplicated event time would be double-counted in its cell mean. df = _balance_panel(seed=12, const_x=True) u = int(df.loc[df["first_treat"] == 4, "unit"].iloc[0]) dupe = df[(df["unit"] == u) & (df["time"] == 3)] # event_time -1 for cohort 4 df2 = df[~((df["unit"] == u) & (df["time"] == 5))] # drop event_time +1 dfd = pd.concat([df2, dupe], ignore_index=True) # same row count, ragged coverage - with pytest.raises(ValueError, match="balanced event windows"): + with pytest.raises(ValueError, match=r"sharing a \(unit, time\) pair"): _cb_fit(dfd, balance="entropy", covariates=["x"]) + with pytest.raises(ValueError, match=r"sharing a \(unit, time\) pair"): + _cb_fit(dfd, balance="none") def test_string_covariate_raises_typeerror(self): df = _balance_panel(seed=13, const_x=True) @@ -2137,13 +2181,14 @@ def _gapped_panel(periods, cohorts, n_units=90, seed=0): return pd.DataFrame(rows) def test_stack_wide_missing_reference_fails_closed(self): - # Calendar period 4 absent; sole cohort a=5 has ref a-1=4 -> the - # reference cell is empty stack-wide. IC1 passes (min/max only), - # so without the guard this rank-drops and re-normalizes against - # an arbitrary horizon while synthesizing a fake e=-1 row. + # Calendar period 4 absent; sole cohort a=5 has ref a-1=4. IC1 passes + # (min/max only), but no unit can cover the window [3, 7], so the + # complete-window rule leaves no sub-experiment and fit() raises, + # naming the gap in the time grid (before the complete-window rule + # the reference-support guard caught this panel). panel = self._gapped_panel([1, 2, 3, 5, 6, 7], [0, 5]) est = StackedDiD(kappa_pre=2, kappa_post=2) - with pytest.raises(ValueError, match="would be fabricated"): + with pytest.raises(ValueError, match=r"No sub-experiment has both.*period\(s\) \[4\]"): est.fit( panel, outcome="y", @@ -2153,13 +2198,11 @@ def test_stack_wide_missing_reference_fails_closed(self): ) def test_partial_reference_support_still_fits(self): - # Cohort 5's own ref period (4) is absent but cohort 7's (6) is - # present, so the POOLED omitted category is populated: the - # coefficient-vector normalization at e=-1 is real (verified by - # execution during the CI-review triage - no rank drop, sane - # surface). Ragged per-cohort baseline support affects estimand - # composition (documented ragged-window behavior), not the - # normalization the container certifies. + # Cohort 5's own ref period (4) is absent for every unit, so its + # window [3, 7] cannot be covered: the event is dropped with a + # warning and listed in trimmed_groups. Cohort 7's window [5, 9] is + # complete, so the fit proceeds on it and the normalization at e=-1 + # is real. panel = self._gapped_panel([1, 2, 3, 5, 6, 7, 8, 9], [0, 5, 7]) est = StackedDiD(kappa_pre=2, kappa_post=2) with warnings.catch_warnings(record=True) as caught: @@ -2172,6 +2215,11 @@ def test_partial_reference_support_still_fits(self): first_treat="first_treat", ) assert not [w for w in caught if "Rank-deficient" in str(w.message)] + dropped = [w for w in caught if "adoption event(s) were dropped" in str(w.message)] + assert len(dropped) == 1 and "[4]" in str(dropped[0].message) + assert [float(g) for g in res.groups] == [7.0] + assert [float(g) for g in res.trimmed_groups] == [5.0] + assert res.n_sub_experiments == 1 assert res.event_study_effects is not None surf = res.aggregate("event_study") assert surf.reference_event_times == (-1,) @@ -2183,13 +2231,13 @@ class TestReferenceSupportGuardEffectiveWeights: means positive COMPOSED weight in both baseline cells - raw row presence is not enough.""" - def test_zero_q_weight_control_reference_cell_fails_closed(self): - # Raw rows exist in both reference cells, but the only control - # rows at e=-1 sit in sub-experiments whose treated rows are - # absent at that event time - aggregate Q-weights zero them, the - # effective control baseline is empty, and (pre-guard, verified - # by execution) the design rank-dropped and re-normalized while - # the container still certified reference_event_times=(-1,). + def test_ragged_reference_cells_leave_no_sub_experiment(self): + # Raw rows exist in both reference cells, but cohort 5's controls + # all lack its reference period (4) and cohort 7's treated units + # all lack theirs (6). Under the complete-window rule neither + # sub-experiment keeps both a treated unit and a clean control, so + # fit() raises (before that rule the aggregate Q-weights zeroed the + # control reference cell and the reference-support guard fired). rng = np.random.default_rng(3) rows = [] for u in range(120): @@ -2212,7 +2260,7 @@ def test_zero_q_weight_control_reference_cell_fails_closed(self): } ) est = StackedDiD(kappa_pre=2, kappa_post=2) - with pytest.raises(ValueError, match="positive weight.*fabricated"): + with pytest.raises(ValueError, match="No sub-experiment has both") as exc: est.fit( pd.DataFrame(rows), outcome="y", @@ -2220,6 +2268,54 @@ def test_zero_q_weight_control_reference_cell_fails_closed(self): time="time", first_treat="first_treat", ) + assert "no clean control is observed at every event time" in str(exc.value) + assert "no treated unit is observed at every event time" in str(exc.value) + + @staticmethod + def _balanced_panel(pop_treated=100.0, seed=3): + rng = np.random.default_rng(seed) + rows = [] + for u in range(90): + g = [0, 5, 7][u % 3] + for t in range(1, 11): + d = 1 if (g and t >= g) else 0 + rows.append( + { + "unit": u, + "time": t, + "y": u * 0.01 + 0.2 * t + 1.5 * d + rng.normal(0, 0.3), + "first_treat": g, + "pop": pop_treated if g else 50.0, + } + ) + return pd.DataFrame(rows) + + def test_kappa_pre_zero_reference_outside_window_fails_closed(self): + # kappa_pre = 0: the window [0, kappa_post] does not contain the + # reference e = -1, so there is no reference cell at all. + with pytest.raises(ValueError, match="positive weight.*fabricated") as exc: + StackedDiD(kappa_pre=0, kappa_post=2).fit( + self._balanced_panel(), + outcome="y", + unit="unit", + time="time", + first_treat="first_treat", + ) + assert "kappa_pre = 0" in str(exc.value) + + def test_zero_treated_population_fails_closed(self): + # weighting="population" with zero treated population zeroes every + # control Q-weight, so the control reference cell has no mass. + with pytest.raises(ValueError, match="positive weight.*fabricated") as exc: + StackedDiD(kappa_pre=2, kappa_post=2, weighting="population").fit( + self._balanced_panel(pop_treated=0.0), + outcome="y", + unit="unit", + time="time", + first_treat="first_treat", + population="pop", + ) + assert "zero treated population" in str(exc.value) def test_survey_zeroed_reference_cell_fails_closed(self): from diff_diff.survey import SurveyDesign @@ -2230,10 +2326,11 @@ def test_survey_zeroed_reference_cell_fails_closed(self): g = [0, 5, 7][u % 3] for t in range(1, 11): d = 1 if (g and t >= g) else 0 - # controls carry zero pweight at both cohorts' reference - # calendar periods -> the control baseline cell has rows - # but no effective WLS mass - w = 0.0 if (g == 0 and t in (4, 6)) else 1.0 + # every control carries zero pweight (unit-constant, as the + # survey columns must be) -> no sub-experiment has control + # mass, every corrective weight is zero, and the guard + # reports the empty treated reference cell + w = 0.0 if g == 0 else 1.0 rows.append( { "unit": u, @@ -2257,6 +2354,809 @@ def test_survey_zeroed_reference_cell_fails_closed(self): ) +# ============================================================================= +# Complete event windows (ragged panels) +# ============================================================================= + +_CW_EFFECTS = {4: (2.0, 0.5), 6: (3.0, 0.25)} # cohort -> (level, slope in event time) + + +def _cw_panel(noise=0.0, seed=0, n=90, n_periods=10, hetero=True): + """Cohorts 4 and 6 plus never-treated; unit levels differ by cohort, and + (with ``hetero``) so do the effects, so the trimmed aggregate ATT depends on + which treated units each sub-experiment holds.""" + rng = np.random.default_rng(seed) + rows = [] + for u in range(n): + g = (0, 4, 6)[u % 3] + level = rng.normal(0, 1) + {0: 0.0, 4: 0.8, 6: -0.5}[g] + for t in range(1, n_periods + 1): + e = t - g + base, slope = _CW_EFFECTS[g] if (g and hetero) else (2.0, 0.5) + tau = (base + slope * e) if (g and e >= 0) else 0.0 + rows.append( + { + "unit": u, + "time": t, + "y": level + 0.3 * t + 0.02 * t * t + tau + rng.normal(0, noise), + "first_treat": g, + # population differs by cohort, so population shares are not + # the unit shares + "pop": 100.0 + 10.0 * (u % 7) + (150.0 if g == 6 else 0.0), + "w": 1.0, + } + ) + return pd.DataFrame(rows) + + +def _cw_ragged(name, d): + """The ragged panels of the complete-window fix, by name.""" + nt = d["first_treat"] == 0 + c6 = d["first_treat"] == 6 + if name == "cohort6_missing_ref": + out = d[~(c6 & (d["time"] == 5))] + elif name == "cohort6_no_pre": + out = d[~(c6 & (d["time"] < 6))] + elif name == "half_cohort6_missing_ref": + out = d[~(c6 & (d["time"] == 5) & (d["unit"] % 2 == 0))] + elif name == "one_nt_obs_missing": + u0 = d.loc[nt, "unit"].iloc[0] + out = d[~((d["unit"] == u0) & (d["time"] == 5))] + elif name == "random_5pct": + out = d.drop(np.random.default_rng(1).choice(len(d), len(d) // 20, replace=False)) + elif name == "period7_absent": + out = d[d["time"] != 7] + elif name == "nt_missing_7_8": + out = d[~(nt & d["time"].between(7, 8))] + elif name == "period5_absent": + out = d[d["time"] != 5] + elif name == "nt_missing_4_8": + out = d[~(nt & d["time"].between(4, 8))] + else: # pragma: no cover + raise KeyError(name) + return out.reset_index(drop=True) + + +def _cw_complete_units(d, a, kappa_pre=2, kappa_post=2, anticipation=0): + """Units with an observation at EVERY period of event a's window, found + independently of the estimator (wide pivot, no missing cell).""" + window = list(range(a - kappa_pre - anticipation, a + kappa_post + 1)) + wide = ( + d[d["time"].isin(window)] + .pivot(index="unit", columns="time", values="y") + .reindex(columns=window) + ) + return set(wide.index[wide.notna().all(axis=1)]) + + +def _cw_cells(d, kappa_pre=2, kappa_post=2, anticipation=0): + """Per realized event: (complete treated units, complete clean controls) + under the default not-yet-treated control rule.""" + ft = d.groupby("unit")["first_treat"].first() + cells = {} + for a in sorted(g for g in ft.unique() if g > 0): + complete = _cw_complete_units(d, a, kappa_pre, kappa_post, anticipation) + treated = complete & set(ft.index[ft == a]) + control = complete & set(ft.index[(ft == 0) | (ft > a + kappa_post)]) + if treated and control: + cells[a] = (treated, control) + return cells + + +def _cw_truth(d, hetero=True, kappa_pre=2, kappa_post=2): + """True trimmed aggregate ATT per event time: sum_a (N_a^D / N^D) tau_a(e), + N_a^D counting the complete treated units of each realized event.""" + cells = _cw_cells(d, kappa_pre, kappa_post) + n_total = sum(len(t) for t, _ in cells.values()) + truth = {} + for e in range(-kappa_pre, kappa_post + 1): + val = 0.0 + for a, (treated, _) in cells.items(): + base, slope = _CW_EFFECTS[a] if hetero else (2.0, 0.5) + val += len(treated) / n_total * ((base + slope * e) if e >= 0 else 0.0) + truth[e] = val + return truth, cells + + +def _cw_fit(d, survey_design=None, population=None, **kw): + kw.setdefault("kappa_pre", 2) + kw.setdefault("kappa_post", 2) + return StackedDiD(**kw).fit( + d, + outcome="y", + unit="unit", + time="time", + first_treat="first_treat", + survey_design=survey_design, + population=population, + ) + + +def _cw_quiet_fit(d, **kw): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return _cw_fit(d, **kw) + + +_CW_RECOVERABLE = [ + "cohort6_missing_ref", + "cohort6_no_pre", + "half_cohort6_missing_ref", + "one_nt_obs_missing", + "random_5pct", + "period7_absent", + "nt_missing_7_8", +] + + +class TestStackedDiDCompleteWindows: + """A unit enters a sub-experiment only if it is observed at every event + time of the window (Wing et al. 2024, Section 5.1). Before this rule a + ragged panel returned shifted estimates with no warning: the regression + contrasts event-time cell means, and unit levels leaked in.""" + + @pytest.mark.parametrize("name", _CW_RECOVERABLE) + def test_exact_recovery_on_ragged_panels(self, name): + d = _cw_ragged(name, _cw_panel()) + truth, cells = _cw_truth(d) + res = _cw_quiet_fit(d) + assert [float(g) for g in res.groups] == [float(a) for a in cells] + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9), (name, e) + assert res.att == pytest.approx(np.mean([truth[e] for e in (0, 1, 2)]), abs=1e-9) + + def test_balanced_panel_recovers_and_warns_nothing(self): + d = _cw_panel() + truth, cells = _cw_truth(d) + assert sorted(cells) == [4, 6] + with warnings.catch_warnings(): + warnings.simplefilter("error") + res = _cw_fit(d) + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9) + assert res.trimmed_groups == [] + + def test_equals_manual_aggregate_of_cohort_contrasts(self): + # Independent oracle (paper Eq. 2 / footnote 5): per-cohort DID + # contrasts from plain means over the complete units, weighted by the + # complete treated-unit shares. No regression, no Q-weights. + d = _cw_ragged("random_5pct", _cw_panel(noise=0.5, seed=4)) + cells = _cw_cells(d) + assert len(cells) == 2 + n_total = sum(len(t) for t, _ in cells.values()) + res = _cw_quiet_fit(d) + for e in (-2, 0, 1, 2): + manual = 0.0 + for a, (treated, control) in cells.items(): + + def _mean(units, t): + rows = d[d["unit"].isin(units) & (d["time"] == t)] + assert len(rows) == len(units) + return rows["y"].mean() + + did = (_mean(treated, a + e) - _mean(treated, a - 1)) - ( + _mean(control, a + e) - _mean(control, a - 1) + ) + manual += len(treated) / n_total * did + np.testing.assert_allclose(res.event_study_effects[e]["effect"], manual, rtol=1e-10) + + def test_equals_the_fit_without_the_incomplete_units(self): + # Each incomplete unit here is incomplete in EVERY sub-experiment it + # enters (a treated unit sits in one; the never-treated unit misses a + # period common to both windows), so removing the units outright must + # give the same fit. + d = _cw_panel(noise=0.5, seed=7) + c6_units = sorted(d.loc[d["first_treat"] == 6, "unit"].unique())[::3] + nt_unit = d.loc[d["first_treat"] == 0, "unit"].iloc[0] + gone = (d["unit"].isin(c6_units) & (d["time"] == 7)) | ( + (d["unit"] == nt_unit) & (d["time"] == 5) + ) + with pytest.warns(UserWarning, match="not observed at every"): + ragged = _cw_fit(d[~gone].reset_index(drop=True)) + removed = _cw_fit(d[~d["unit"].isin(list(c6_units) + [nt_unit])].reset_index(drop=True)) + np.testing.assert_allclose(ragged.att, removed.att, rtol=1e-12) + np.testing.assert_allclose(ragged.se, removed.se, rtol=1e-12) + np.testing.assert_allclose(ragged.event_study_vcov, removed.event_study_vcov, rtol=1e-12) + for e, row in removed.event_study_effects.items(): + np.testing.assert_allclose( + ragged.event_study_effects[e]["effect"], row["effect"], rtol=1e-12 + ) + np.testing.assert_allclose(ragged.event_study_effects[e]["se"], row["se"], rtol=1e-12) + assert ragged.n_treated_units == removed.n_treated_units + assert ragged.n_control_units == removed.n_control_units + assert ragged.n_stacked_obs == removed.n_stacked_obs + + def test_unit_is_trimmed_per_sub_experiment(self): + # Period 2 lies in cohort 4's window [2, 6] only: the unit leaves that + # sub-experiment and stays, with all five rows, in cohort 6's. + d = _cw_panel(noise=0.3) + nt_unit = d.loc[d["first_treat"] == 0, "unit"].iloc[0] + res = _cw_quiet_fit(d[~((d["unit"] == nt_unit) & (d["time"] == 2))].reset_index(drop=True)) + sd = res.stacked_data + assert nt_unit not in set(sd.loc[sd["_sub_exp"] == 4, "unit"]) + kept = sd[(sd["_sub_exp"] == 6) & (sd["unit"] == nt_unit)] + assert sorted(kept["_event_time"]) == [-2, -1, 0, 1, 2] + + def test_q_weights_are_the_unit_count_formula(self): + d = _cw_ragged("random_5pct", _cw_panel(noise=0.3)) + cells = _cw_cells(d) + n_d = sum(len(t) for t, _ in cells.values()) + n_c = sum(len(c) for _, c in cells.values()) + sd = _cw_quiet_fit(d).stacked_data + assert (sd.loc[sd["_D_sa"] == 1, "_Q_weight"] == 1.0).all() + for a, (treated, control) in cells.items(): + q = sd.loc[(sd["_sub_exp"] == a) & (sd["_D_sa"] == 0), "_Q_weight"] + assert len(q) == 5 * len(control) + np.testing.assert_allclose( + q.to_numpy(), (len(treated) / n_d) / (len(control) / n_c), rtol=1e-13 + ) + + def test_trim_warning_reports_the_counts(self): + d = _cw_ragged("half_cohort6_missing_ref", _cw_panel()) + with pytest.warns(UserWarning) as rec: + res = _cw_fit(d) + msgs = [str(w.message) for w in rec] + assert len(msgs) == 1 + assert "15 treated and 0 control unit-by-sub-experiment entries" in msgs[0] + assert "15 of 30 treated, 30 of 30 control" in msgs[0] + assert "trimmed aggregate ATT over the units observed across their whole window" in msgs[0] + assert res.n_treated_units == 45 and res.n_control_units == 30 + + @pytest.mark.parametrize( + "name, reason", + [ + ("cohort6_missing_ref", "no treated unit is observed at every event time (0 of 30)"), + ("nt_missing_7_8", "no clean control is observed at every event time (0 of 30)"), + ("period7_absent", "calendar period(s) [7] of its window are not observed"), + ], + ) + def test_event_without_complete_units_is_dropped(self, name, reason): + d = _cw_ragged(name, _cw_panel(noise=0.3)) + with pytest.warns(UserWarning) as rec: + res = _cw_fit(d) + dropped = [ + str(w.message) for w in rec if "adoption event(s) were dropped" in str(w.message) + ] + assert len(dropped) == 1 and reason in dropped[0] + assert [float(g) for g in res.groups] == [4.0] + assert [float(g) for g in res.trimmed_groups] == [6.0] + assert res.n_sub_experiments == 1 + assert set(res.stacked_data["_sub_exp"]) == {4} + assert np.isfinite(res.att) and np.isfinite(res.se) + + def test_no_event_left_raises(self): + d = _cw_panel() + with pytest.raises(ValueError, match="No sub-experiment has both") as exc: + _cw_fit(_cw_ragged("period5_absent", d)) + assert "period(s) [5] are not observed for any unit" in str(exc.value) + with pytest.raises(ValueError, match="No sub-experiment has both") as exc: + _cw_fit(_cw_ragged("nt_missing_4_8", d)) + assert "no clean control is observed at every event time (0 of 30)" in str(exc.value) + assert "time grid has gaps" not in str(exc.value) + + def test_biennial_grid_raises_naming_the_missing_periods(self): + d = _cw_panel() + with pytest.raises(ValueError, match="No sub-experiment has both") as exc: + _cw_fit(d[d["time"] % 2 == 0].reset_index(drop=True)) + assert "period(s) [3, 5, 7, 9] are not observed for any unit" in str(exc.value) + assert "re-index time to consecutive integers" in str(exc.value) + + def test_datetime_coded_time_reports_the_span(self): + # A datetime column coerces to epoch integers a day apart by ~1e11 + # or more, so every window misses. The message must describe the + # span, not enumerate the missing integers. + d = _cw_panel(n=30) + dates = pd.Series(pd.date_range("2020-01-01", periods=10, freq="D")) + epoch = pd.to_numeric(dates) + d["time"] = d["time"].map(dict(zip(range(1, 11), dates))) + d["first_treat"] = d["first_treat"].map( + {0: 0, 4: int(epoch.iloc[3]), 6: int(epoch.iloc[5])} + ) + with pytest.raises(ValueError, match="No sub-experiment has both") as exc: + _cw_fit(d) + assert "holds only 10 distinct periods" in str(exc.value) + + def test_input_validation(self): + d = _cw_panel(n=30) + dup = pd.concat([d, d.iloc[[5]]], ignore_index=True) + with pytest.raises(ValueError, match=r"sharing a \(unit, time\) pair"): + _cw_fit(dup) + nan_time = d.astype({"time": float}) + nan_time.loc[3, "time"] = np.nan + with pytest.raises(ValueError, match="missing or non-finite"): + _cw_fit(nan_time) + frac = d.astype({"time": float}) + frac.loc[3, "time"] = 4.5 + with pytest.raises(ValueError, match="must be integer-valued"): + _cw_fit(frac) + frac_ft = d.astype({"first_treat": float}) + frac_ft.loc[frac_ft["first_treat"] == 6, "first_treat"] = 5.5 + with pytest.raises(ValueError, match="integer adoption periods"): + _cw_fit(frac_ft) + with pytest.raises(TypeError): + _cw_fit(d, kappa_pre=1.5) + + def test_never_treated_encodings_pass_validation(self): + d = _cw_panel(n=30, noise=0.2) + base = _cw_fit(d) + as_inf = d.astype({"first_treat": float}) + as_inf.loc[as_inf["first_treat"] == 0, "first_treat"] = np.inf + np.testing.assert_allclose(_cw_fit(as_inf).att, base.att, rtol=1e-12) + + @pytest.mark.parametrize( + "kwargs", + [ + {"control_group": "strict"}, + {"control_group": "never_treated"}, + {"vcov_type": "hc2_bm"}, + {"cluster": "unit_subexp"}, + ], + ids=lambda k: "-".join(f"{a}={b}" for a, b in k.items()), + ) + def test_exact_recovery_across_configurations(self, kwargs): + # Homogeneous effects, so the truth is 2 + 0.5 e whatever the controls. + d = _cw_ragged("random_5pct", _cw_panel(hetero=False)) + res = _cw_quiet_fit(d, **kwargs) + assert len(res.groups) == 2 + for e in (-2, 0, 1, 2): + want = (2.0 + 0.5 * e) if e >= 0 else 0.0 + assert res.event_study_effects[e]["effect"] == pytest.approx(want, abs=1e-9) + + def test_exact_recovery_with_anticipation(self): + # anticipation=1 widens the window to [-3, 2] and moves the reference + # to e = -2; the trim uses the widened window. + d = _cw_ragged("random_5pct", _cw_panel(hetero=False)) + res = _cw_quiet_fit(d, anticipation=1) + sd = res.stacked_data + assert (sd.groupby(["_sub_exp", "unit"]).size() == 6).all() + for e in (-3, -1, 0, 1, 2): + want = (2.0 + 0.5 * e) if e >= 0 else 0.0 + assert res.event_study_effects[e]["effect"] == pytest.approx(want, abs=1e-9) + + def test_random_missingness_never_returns_a_wrong_number(self): + n_fit = 0 + for seed in range(30): + rng = np.random.default_rng(100 + seed) + d = _cw_panel(seed=seed) + frac = rng.uniform(0.02, 0.12) + d = d.drop(rng.choice(len(d), int(frac * len(d)), replace=False)).reset_index(drop=True) + truth, cells = _cw_truth(d) + if not cells: + with pytest.raises(ValueError, match="No sub-experiment has both"): + _cw_quiet_fit(d) + continue + res = _cw_quiet_fit(d) + n_fit += 1 + assert [float(g) for g in res.groups] == [float(a) for a in cells], seed + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9), seed + assert n_fit >= 25 + + +class TestStackedDiDCompleteWindowsSurvey: + """Under survey_design= the unit-level trim is refused: removing units + would drop their PSUs and strata from the variance and df_survey.""" + + @staticmethod + def _designs(d): + from diff_diff.survey import SurveyDesign + + d = d.copy() + d["psu"] = d["unit"] + units = sorted(d["unit"].unique()) + cols = [] + n_rep = 10 + for r in range(n_rep): + deleted = set(units[r::n_rep]) + col = f"rep_{r}" + d[col] = np.where(d["unit"].isin(deleted), 0.0, d["w"] * n_rep / (n_rep - 1)) + cols.append(col) + return d, { + "tsl": SurveyDesign(weights="w", psu="psu"), + "replicate": SurveyDesign(weights="w", replicate_weights=cols, replicate_method="JK1"), + } + + @pytest.mark.parametrize("design", ["tsl", "replicate"]) + @pytest.mark.parametrize( + "name", ["half_cohort6_missing_ref", "cohort6_missing_ref", "nt_missing_4_8"] + ) + def test_ragged_panel_is_refused(self, design, name): + d, designs = self._designs(_cw_ragged(name, _cw_panel(noise=0.3))) + with pytest.raises(NotImplementedError, match="survey_design=") as exc: + _cw_fit(d, survey_design=designs[design]) + assert "not domain estimation" in str(exc.value) + + @pytest.mark.parametrize("design", ["tsl", "replicate"]) + def test_balanced_panel_fits(self, design): + d, designs = self._designs(_cw_panel(noise=0.3)) + res = _cw_quiet_fit(d, survey_design=designs[design]) + plain = _cw_fit(_cw_panel(noise=0.3)) + np.testing.assert_allclose(res.att, plain.att, rtol=1e-10) # uniform weights + assert np.isfinite(res.se) and res.se > 0 + assert [float(g) for g in res.groups] == [4.0, 6.0] + + @pytest.mark.parametrize("design", ["tsl", "replicate"]) + def test_dropped_event_is_refused(self, design): + # Period 7 is missing for EVERY unit, so cohort 6 cannot be realized. + # Dropping it would take the cohort's PSUs out of the design (60 of + # 90 PSUs left), so the survey fit refuses instead of proceeding on + # cohort 4 as the unweighted fit does. + d, designs = self._designs(_cw_ragged("period7_absent", _cw_panel(noise=0.3))) + with pytest.raises(NotImplementedError, match="cannot drop adoption event") as exc: + _cw_fit(d, survey_design=designs[design]) + assert "calendar period(s) [7]" in str(exc.value) + assert _cw_quiet_fit(d).n_sub_experiments == 1 # the unweighted fit proceeds + + @pytest.mark.parametrize("col", ["w", "psu"]) + def test_survey_columns_must_be_constant_within_unit(self, col): + # A weight that changes over a unit's rows changes each event-time + # cell's weighted composition just as a missing row does: positive + # time-varying weights returned 2.6174 for a true 2.5 on this panel. + d, designs = self._designs(_cw_panel(hetero=False)) + half = (d["first_treat"] == 6) & (d["unit"] % 2 == 0) + if col == "w": + d.loc[half & (d["time"] < 6), "w"] = 1.5 + d.loc[half & (d["time"] >= 6), "w"] = 0.5 + else: + d.loc[half & (d["time"] >= 6), "psu"] = -1 + with pytest.raises(ValueError, match=f"Survey column '{col}' varies within units"): + _cw_fit(d, survey_design=designs["tsl"]) + + def test_zero_weight_on_one_row_is_rejected(self): + d, designs = self._designs(_cw_panel(hetero=False)) + d.loc[(d["first_treat"] == 6) & (d["time"] == 5), "w"] = 0.0 + with pytest.raises(ValueError, match="varies within units"): + _cw_fit(d, survey_design=designs["tsl"]) + + def test_gapped_grid_diagnosis_takes_precedence(self): + d, designs = self._designs(_cw_panel(noise=0.3)) + with pytest.raises(ValueError, match="No sub-experiment has both"): + _cw_fit(d[d["time"] % 2 == 0].reset_index(drop=True), survey_design=designs["tsl"]) + + +# ============================================================================= +# Cohort shares: both arms aggregate sub-experiments with the same shares +# ============================================================================= + +_CW_SCHEMES = ["aggregate", "population", "sample_share"] + + +def _cw_unequal(d): + """Balanced panel with unequal cohort sizes: every second cohort-6 unit removed.""" + return d[~((d["first_treat"] == 6) & (d["unit"] % 2 == 0))].reset_index(drop=True) + + +def _cw_shares(d, scheme, weight_col=None, kappa_post=2): + """Target cohort shares pi_a of a weighting scheme, computed from the input + panel independently of the estimator, plus each event's complete unit sets + and the unit weights. Events without positive treated and control mass, or + with a zero target, are left out.""" + w = ( + d.groupby("unit")[weight_col].first() + if weight_col + else pd.Series(1.0, index=sorted(d["unit"].unique())) + ) + pop = d.groupby("unit")["pop"].first() + cells = { + a: (sorted(t), sorted(c)) + for a, (t, c) in _cw_cells(d, kappa_post=kappa_post).items() + if w[sorted(t)].sum() > 0 and w[sorted(c)].sum() > 0 + } + if scheme == "aggregate": + raw = {a: w[t].sum() for a, (t, c) in cells.items()} + elif scheme == "population": + raw = {a: (w[t] * pop[t]).sum() for a, (t, c) in cells.items()} + else: + raw = {a: w[t].sum() + w[c].sum() for a, (t, c) in cells.items()} + raw = {a: v for a, v in raw.items() if v > 0} + total = sum(raw.values()) + return {a: v / total for a, v in raw.items()}, cells, w + + +def _cw_share_truth(shares, event_times=(-2, 0, 1, 2)): + return { + e: sum( + share * ((_CW_EFFECTS[a][0] + _CW_EFFECTS[a][1] * e) if e >= 0 else 0.0) + for a, share in shares.items() + ) + for e in event_times + } + + +def _cw_manual_aggregate(d, shares, cells, w, e): + """sum_a pi_a DID_{a,e} from (survey-weighted) cell means: no regression.""" + + def _mean(units, t): + rows = d[d["unit"].isin(units) & (d["time"] == t)].set_index("unit")["y"] + assert len(rows) == len(units) + return float(np.average(rows[units], weights=w[units])) + + total = 0.0 + for a, share in shares.items(): + treated = [u for u in cells[a][0] if w[u] > 0] + control = [u for u in cells[a][1] if w[u] > 0] + did = (_mean(treated, a + e) - _mean(treated, a - 1)) - ( + _mean(control, a + e) - _mean(control, a - 1) + ) + total += share * did + return total + + +def _cw_weighted(d, kind, seed=5): + """Unit-constant survey weights in column ``w``.""" + d = d.copy() + ft = d.groupby("unit")["first_treat"].first() + if kind == "by_cohort": + unit_w = ft.map({4: 1.5, 6: 0.5, 0: 1.0}) + else: # random + rng = np.random.default_rng(seed) + unit_w = pd.Series(rng.uniform(0.2, 3.0, len(ft)), index=ft.index) + d["w"] = d["unit"].map(unit_w) + return d + + +def _cw_survey(): + from diff_diff.survey import SurveyDesign + + return SurveyDesign(weights="w") + + +class TestStackedDiDCohortShares: + """Wing et al. (2024, Section 5.3): the stacked regression recovers a convex + combination of sub-experiment ATTs only if the treated arm and the control + arm aggregate sub-experiments with the SAME shares. Before the weights were + unified, ``population`` and ``sample_share`` set the treated weight to 1 + (the paper's Table 1 has a treatment weight for both), and survey fits used + raw unit counts for the corrective weights; untreated trends then failed to + cancel on every panel with a nonlinear time trend.""" + + @pytest.mark.parametrize("scheme", _CW_SCHEMES) + @pytest.mark.parametrize("panel", ["unequal", "random_5pct"]) + def test_truth_recovery_under_every_scheme(self, scheme, panel): + d = _cw_unequal(_cw_panel()) if panel == "unequal" else _cw_ragged(panel, _cw_panel()) + shares, _, _ = _cw_shares(d, scheme) + assert len(shares) == 2 + truth = _cw_share_truth(shares) + res = _cw_quiet_fit( + d, weighting=scheme, population="pop" if scheme == "population" else None + ) + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9), e + + @pytest.mark.parametrize("scheme", _CW_SCHEMES) + def test_q_weights_are_table_1(self, scheme): + d = _cw_unequal(_cw_panel(noise=0.3)) + shares, cells, _ = _cw_shares(d, scheme) + n_d = sum(len(t) for t, _ in cells.values()) + n_c = sum(len(c) for _, c in cells.values()) + sd = _cw_fit( + d, weighting=scheme, population="pop" if scheme == "population" else None + ).stacked_data + for a, (treated, control) in cells.items(): + in_a = sd["_sub_exp"] == a + np.testing.assert_allclose( + sd.loc[in_a & (sd["_D_sa"] == 1), "_Q_weight"].to_numpy(), + shares[a] / (len(treated) / n_d), + rtol=1e-13, + ) + np.testing.assert_allclose( + sd.loc[in_a & (sd["_D_sa"] == 0), "_Q_weight"].to_numpy(), + shares[a] / (len(control) / n_c), + rtol=1e-13, + ) + if scheme == "aggregate": + assert (sd.loc[sd["_D_sa"] == 1, "_Q_weight"] == 1.0).all() + else: + assert sd.loc[sd["_D_sa"] == 1, "_Q_weight"].nunique() == 2 # not all 1 + + @pytest.mark.parametrize("scheme", _CW_SCHEMES) + def test_equals_manual_aggregate_under_every_scheme(self, scheme): + d = _cw_ragged("random_5pct", _cw_unequal(_cw_panel(noise=0.5, seed=4))) + shares, cells, w = _cw_shares(d, scheme) + res = _cw_quiet_fit( + d, weighting=scheme, population="pop" if scheme == "population" else None + ) + for e in (-2, 0, 1, 2): + np.testing.assert_allclose( + res.event_study_effects[e]["effect"], + _cw_manual_aggregate(d, shares, cells, w, e), + rtol=1e-10, + ) + + @pytest.mark.parametrize("scheme", _CW_SCHEMES) + @pytest.mark.parametrize("kind", ["by_cohort", "random"]) + def test_survey_weighted_truth_recovery(self, scheme, kind): + # Survey-weighted cohort shares on both arms. With raw-count corrective + # weights the by-cohort case returned an ATT of 2.46 for a true 2.50 + # (homogeneous effects) on the balanced panel. + d = _cw_weighted(_cw_panel(), kind) + shares, _, _ = _cw_shares(d, scheme, weight_col="w") + truth = _cw_share_truth(shares) + res = _cw_quiet_fit( + d, + weighting=scheme, + population="pop" if scheme == "population" else None, + survey_design=_cw_survey(), + ) + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9), e + + @pytest.mark.parametrize("scheme", _CW_SCHEMES) + def test_survey_fit_equals_weighted_manual_aggregate(self, scheme): + d = _cw_weighted(_cw_unequal(_cw_panel(noise=0.5, seed=4)), "random") + shares, cells, w = _cw_shares(d, scheme, weight_col="w") + res = _cw_quiet_fit( + d, + weighting=scheme, + population="pop" if scheme == "population" else None, + survey_design=_cw_survey(), + ) + for e in (-2, 0, 1, 2): + np.testing.assert_allclose( + res.event_study_effects[e]["effect"], + _cw_manual_aggregate(d, shares, cells, w, e), + rtol=1e-10, + ) + + def test_survey_weights_are_scale_invariant(self): + d = _cw_weighted(_cw_panel(noise=0.4), "random") + base = _cw_quiet_fit(d, survey_design=_cw_survey()) + scaled = _cw_quiet_fit(d.assign(w=d["w"] * 7.0), survey_design=_cw_survey()) + np.testing.assert_allclose(scaled.att, base.att, rtol=1e-12) + np.testing.assert_allclose(scaled.se, base.se, rtol=1e-12) + + def test_zero_weight_units_define_a_subpopulation(self): + # Half of cohort 6 at weight 0: the estimate is the truth over the + # positive-weight units (raw-count corrective weights returned 2.4733 + # for a true 2.50 on the homogeneous-effects version of this panel). + d = _cw_weighted(_cw_panel(), "random") + d.loc[(d["first_treat"] == 6) & (d["unit"] % 2 == 0), "w"] = 0.0 + shares, _, _ = _cw_shares(d, "aggregate", weight_col="w") + truth = _cw_share_truth(shares) + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + res = _cw_fit(d, survey_design=_cw_survey()) + # Both cohorts still carry mass, so no sub-experiment is reported empty. + assert not [w for w in caught if "carry zero weight" in str(w.message)] + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9) + + def test_cohort_at_zero_weight_contributes_nothing(self): + d = _cw_weighted(_cw_panel(), "by_cohort") + d.loc[d["first_treat"] == 6, "w"] = 0.0 + with pytest.warns(UserWarning, match="carry zero weight") as rec: + res = _cw_fit(d, survey_design=_cw_survey(), control_group="never_treated") + msg = next(str(w.message) for w in rec if "carry zero weight" in str(w.message)) + assert "event 6: no treated unit with positive weight" in msg + truth = _cw_share_truth({4: 1.0}) + for e, val in truth.items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9) + # The rows stay in the stack (the design is unchanged), at zero weight. + sd = res.stacked_data + assert set(sd["_sub_exp"]) == {4, 6} + assert (sd.loc[sd["_sub_exp"] == 6, "_Q_weight"] == 0.0).all() + assert [float(g) for g in res.groups] == [4.0, 6.0] + + def test_event_without_control_mass_is_left_out_of_the_shares(self): + # kappa_post=1: event 6's clean controls are the never-treated units + # only, event 4's also include cohort 6 (not yet treated through 5). + # With every never-treated unit at weight 0, event 6 has no control + # mass; its TREATED mass must not enter the totals event 4 is scaled by. + d = _cw_weighted(_cw_panel(), "random") + d.loc[d["first_treat"] == 0, "w"] = 0.0 + with pytest.warns(UserWarning, match="carry zero weight") as rec: + res = _cw_fit(d, survey_design=_cw_survey(), kappa_post=1) + msg = next(str(w.message) for w in rec if "carry zero weight" in str(w.message)) + assert "event 6: no clean control with positive weight" in msg + for e in (-2, 0, 1): + want = (_CW_EFFECTS[4][0] + _CW_EFFECTS[4][1] * e) if e >= 0 else 0.0 + assert res.event_study_effects[e]["effect"] == pytest.approx(want, abs=1e-9) + sd = res.stacked_data + in_4 = sd["_sub_exp"] == 4 + np.testing.assert_allclose(sd.loc[in_4 & (sd["_D_sa"] == 1), "_Q_weight"], 1.0) + np.testing.assert_allclose(sd.loc[in_4 & (sd["_D_sa"] == 0), "_Q_weight"], 1.0) + + def test_cohort_with_zero_treated_population_warns(self): + d = _cw_panel() + d.loc[d["first_treat"] == 6, "pop"] = 0.0 + with pytest.warns(UserWarning, match="carry zero weight") as rec: + res = _cw_fit(d, weighting="population", population="pop") + msg = next(str(w.message) for w in rec if "carry zero weight" in str(w.message)) + assert "event 6: zero treated population" in msg + for e, val in _cw_share_truth({4: 1.0}).items(): + assert res.event_study_effects[e]["effect"] == pytest.approx(val, abs=1e-9) + + def test_population_input_is_validated_on_treated_units(self): + d = _cw_panel(n=30).astype({"pop": float}) + kw = dict(weighting="population", population="pop") + # A cohort-4 row inside its window [2, 6]: validation reads the stack. + treated_row = d.index[(d["first_treat"] == 4) & (d["time"] == 4)][0] + nan_pop = d.copy() + nan_pop.loc[treated_row, "pop"] = np.nan + with pytest.raises(ValueError, match="missing or non-finite"): + _cw_fit(nan_pop, **kw) + neg_pop = d.copy() + neg_pop.loc[d["first_treat"] == 4, "pop"] = -1.0 + with pytest.raises(ValueError, match="negative value"): + _cw_fit(neg_pop, **kw) + varying = d.copy() + varying.loc[treated_row, "pop"] = varying.loc[treated_row, "pop"] + 5.0 + with pytest.raises(ValueError, match="varies within 1 treated unit"): + _cw_fit(varying, **kw) + # Control units' population, and treated rows outside every window, + # are never read. + unread = d.copy() + unread.loc[d["first_treat"] == 0, "pop"] = np.nan + unread.loc[(d["first_treat"] == 4) & (d["time"] == 10), "pop"] = -3.0 + base = _cw_fit(d, **kw) + np.testing.assert_allclose(_cw_fit(unread, **kw).att, base.att, rtol=1e-12) + # ... whatever they hold: an object column with pd.NA on the controls. + as_object = d.astype({"pop": object}) + as_object.loc[d["first_treat"] == 0, "pop"] = pd.NA + res = _cw_fit(as_object, **kw) + np.testing.assert_allclose(res.att, base.att, rtol=1e-12) + np.testing.assert_allclose(res.se, base.se, rtol=1e-12) + + @staticmethod + def _jk1(d, n_rep=10): + d = d.copy() + units = sorted(d["unit"].unique()) + cols = [] + for r in range(n_rep): + col = f"rep_{r}" + d[col] = np.where( + d["unit"].isin(set(units[r::n_rep])), 0.0, d["w"] * n_rep / (n_rep - 1) + ) + cols.append(col) + return d, cols + + @pytest.mark.parametrize("mse", [False, True]) + def test_replicate_refits_recompute_the_shares(self, mse): + # Each replicate estimate must be the estimate under THAT replicate's + # weights, whose cohort shares differ from the full sample's. The + # oracle is independent of the estimator: weighted cell means under + # each replicate column, aggregated with that replicate's shares. + from diff_diff.survey import SurveyDesign + + d, cols = self._jk1(_cw_weighted(_cw_panel(noise=0.5, seed=4), "by_cohort")) + res = _cw_quiet_fit( + d, + survey_design=SurveyDesign( + weights="w", replicate_weights=cols, replicate_method="JK1", mse=mse + ), + ) + events = (-2, 0, 1, 2) + theta = np.array([res.event_study_effects[e]["effect"] for e in events]) + reps = [] + for col in cols: + shares, cells, w = _cw_shares(d, "aggregate", weight_col=col) + reps.append([_cw_manual_aggregate(d, shares, cells, w, e) for e in events]) + reps = np.array(reps) + centre = theta if mse else reps.mean(axis=0) + n_rep = len(cols) + oracle_var = (n_rep - 1) / n_rep * ((reps - centre) ** 2).sum(axis=0) + reported = np.array([res.event_study_effects[e]["se"] for e in events]) + np.testing.assert_allclose(reported, np.sqrt(oracle_var), rtol=1e-9) + + def test_replicate_without_control_mass_is_dropped(self): + from diff_diff.survey import SurveyDesign + + d = _cw_weighted(_cw_panel(noise=0.5, seed=4), "by_cohort") + d = d[d["first_treat"] != 6].reset_index(drop=True) # one cohort, never-treated controls + d, cols = self._jk1(d) + d.loc[d["first_treat"] == 0, cols[0]] = 0.0 # replicate 0: no control at all + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + res = _cw_fit( + d, + survey_design=SurveyDesign( + weights="w", replicate_weights=cols, replicate_method="JK1" + ), + ) + assert any("replicate" in str(w.message).lower() for w in caught) + assert np.isfinite(res.se) and res.se > 0 + + @pytest.fixture(scope="module") def alpha_fitted(): data = generate_staggered_data( diff --git a/tests/test_target_parameter.py b/tests/test_target_parameter.py index fe20625ac..fd0000826 100644 --- a/tests/test_target_parameter.py +++ b/tests/test_target_parameter.py @@ -393,6 +393,42 @@ def test_stacked_control_group_branches_definition(self, control_group, expected assert tp["aggregation"] == "stacked" assert expected_clause in tp["definition"] + @pytest.mark.parametrize( + "weighting, expected_clause", + [ + ("aggregate", "treated-unit-share-weighted"), + ("population", "treated-population-share-weighted"), + ("sample_share", "sample-share-weighted"), + ], + ) + def test_stacked_weighting_names_its_share(self, weighting, expected_clause): + """Each StackedDiD weighting scheme aggregates the sub-experiment ATTs + with its own cohort share (Wing et al. 2024, Table 1).""" + tp = describe_target_parameter( + _minimal_result( + "StackedDiDResults", control_group="not_yet_treated", weighting=weighting + ) + ) + assert expected_clause in tp["definition"] + assert "survey weights" not in tp["definition"] + + def test_stacked_without_weighting_attribute_reads_as_aggregate(self): + tp = describe_target_parameter( + _minimal_result("StackedDiDResults", control_group="not_yet_treated") + ) + assert "treated-unit-share-weighted" in tp["definition"] + + def test_stacked_survey_fit_says_shares_are_survey_weighted(self): + tp = describe_target_parameter( + _minimal_result( + "StackedDiDResults", + control_group="not_yet_treated", + weighting="aggregate", + survey_metadata=object(), + ) + ) + assert "the shares counting those units by their survey weights" in tp["definition"] + @pytest.mark.parametrize( "pt_assumption, expected_tag", [("all", "pt_all_combined"), ("post", "pt_post_single_baseline")], From 3ff0b437b763c50db04a6645b64388697b1d76ef Mon Sep 17 00:00:00 2001 From: igerber Date: Thu, 26 Nov 2026 10:39:00 -0500 Subject: [PATCH 2/3] test(stacked_did): replicate oracle uses unit-varying weights so cohort 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. --- tests/test_stacked_did.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/test_stacked_did.py b/tests/test_stacked_did.py index eab83b49a..661ea5fb3 100644 --- a/tests/test_stacked_did.py +++ b/tests/test_stacked_did.py @@ -3116,9 +3116,13 @@ def test_replicate_refits_recompute_the_shares(self, mse): # weights, whose cohort shares differ from the full sample's. The # oracle is independent of the estimator: weighted cell means under # each replicate column, aggregated with that replicate's shares. + # The weights vary by unit: with weights constant within a cohort this + # jackknife removes the same mass from every cohort, the shares never + # move, and refits that reused the full-sample corrective weights + # would pass as well. from diff_diff.survey import SurveyDesign - d, cols = self._jk1(_cw_weighted(_cw_panel(noise=0.5, seed=4), "by_cohort")) + d, cols = self._jk1(_cw_weighted(_cw_panel(noise=0.5, seed=4), "random")) res = _cw_quiet_fit( d, survey_design=SurveyDesign( @@ -3127,11 +3131,14 @@ def test_replicate_refits_recompute_the_shares(self, mse): ) events = (-2, 0, 1, 2) theta = np.array([res.event_study_effects[e]["effect"] for e in events]) - reps = [] + reps, rep_shares = [], [] for col in cols: shares, cells, w = _cw_shares(d, "aggregate", weight_col=col) + rep_shares.append(shares[4]) reps.append([_cw_manual_aggregate(d, shares, cells, w, e) for e in events]) reps = np.array(reps) + full_share = _cw_shares(d, "aggregate", weight_col="w")[0][4] + assert max(abs(s - full_share) for s in rep_shares) > 0.01 centre = theta if mse else reps.mean(axis=0) n_rep = len(cols) oracle_var = (n_rep - 1) / n_rep * ((reps - centre) ** 2).sum(axis=0) From 55e31e53312a8bbfdf44f3fcc03f57a805b4e1b4 Mon Sep 17 00:00:00 2001 From: igerber Date: Thu, 26 Nov 2026 13:15:39 -0500 Subject: [PATCH 3/3] docs(stacked_did): blank lines around the weighting bullet list in the 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. --- diff_diff/stacked_did.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 530af5e1a..9603e16b8 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -171,10 +171,12 @@ class StackedDiD(BaseEstimator): the share ``pi_a`` with which sub-experiment ``a`` enters the aggregate ``sum_a pi_a ATT(a, a+e)``, and both the treated and the control rows are weighted so that each arm carries that share: + - "aggregate": share of treated units (trimmed aggregate ATT; treated rows have Q = 1) - "population": share of the treated units' population - "sample_share": share of all units (treated plus clean controls) + Under ``survey_design=`` the shares are formed from survey-weighted unit masses. control_group : str, default="not_yet_treated"