From 68222bf4ddb15491a664fdde664d8479afe2d780 Mon Sep 17 00:00:00 2001 From: igerber Date: Sun, 22 Nov 2026 16:10:33 -0500 Subject: [PATCH] fix(survey): dropped replicates cap the design df instead of replacing it (library-wide) Under a replicate-weight design the inference df is the QR rank of the analysis-weight matrix minus 1. When a replicate dropped (an all-zero column, or a failed refit / solve) 13 sites replaced that df with n_valid - 1, which raised the df above the design df on a rank-deficient replicate matrix (t(14) instead of t(4)) and produced t-inference on an undefined design df (t(2) instead of NaN inference). - survey.reduced_replicate_df: strict-reduction override helper next to cap_replicate_df. - Influence-function sites (_se_from_psi and its CS / staggered-DDD / DMLDiD relays, 2x2x2 TripleDifference, EfficientDiD, ContinuousDiD) override the working df only on a strict reduction from >= 2 valid replicates; a statistic with < 2 valid replicates no longer changes another statistic's df. - Refit / OLS sites (DifferenceInDifferences, TwoWayFixedEffects incl. event-study mode, SunAbraham, StackedDiD, ImputationDiD, TwoStageDiD, LinearRegression) cap the shared df; plain DiD now writes the capped df to survey_metadata. - DMLDiD inline rule consolidated onto cap_replicate_df; dCDH docstrings corrected. - REGISTRY replicate-df Note rewritten; TODO row removed. --- TODO.md | 1 - changelog.d/20261122-replicate-df-min-cap.md | 53 ++ diff_diff/chaisemartin_dhaultfoeuille.py | 17 +- diff_diff/continuous_did.py | 20 +- diff_diff/continuous_did_aggregation.py | 12 +- diff_diff/dml_did.py | 35 +- diff_diff/efficient_did_aggregation.py | 43 +- diff_diff/efficient_did_results.py | 26 +- diff_diff/estimators.py | 26 +- diff_diff/imputation.py | 3 +- diff_diff/imputation_aggregation.py | 6 +- diff_diff/linalg.py | 15 +- diff_diff/stacked_did.py | 12 +- diff_diff/staggered_aggregation.py | 24 +- diff_diff/sun_abraham.py | 12 +- diff_diff/survey.py | 26 + diff_diff/triple_diff.py | 13 +- diff_diff/twfe.py | 6 +- diff_diff/two_stage_aggregation.py | 6 +- docs/methodology/REGISTRY.md | 58 +- tests/test_aggregate_contract.py | 19 +- tests/test_replicate_df_cap.py | 901 +++++++++++++++++++ tests/test_survey_dml.py | 25 +- 23 files changed, 1245 insertions(+), 114 deletions(-) create mode 100644 changelog.d/20261122-replicate-df-min-cap.md create mode 100644 tests/test_replicate_df_cap.py diff --git a/TODO.md b/TODO.md index 618997ca1..2852ec1cf 100644 --- a/TODO.md +++ b/TODO.md @@ -36,7 +36,6 @@ Related tracking surfaces: | `EventStudyResults` inference-provenance fields: the container records no `vcov_type`/`cluster_name`/`n_clusters`/`df_convention`/Conley metadata, so a serialized surface cannot distinguish unit auto-clustering from explicit clustering, survey, Conley, or the one-way carve-out (3(a) R9 review). Adding them is a cross-producer M-092 schema amendment (six builders, to_dict/summary rendering, surface-suite pins) - follow the pre-cut amendment convention (optional fields appended last, ledger note same-diff) rather than bolting onto one producer | `diff_diff/results_base.py` | 3(a) R9 | Mid | Low | | Opt-in singleton-group pruning for TwoWayFixedEffects (static + event-study mode; reghdfe parity): singleton units/periods are currently RETAINED class-wide - the within-demeaned row is zero so points are unchanged, but N/G/residual-df count it and CR1/finite-sample SEs shift (~0.41019 -> 0.40962 measured; REGISTRY "Deviation from R" Note, R5 review) - reghdfe iteratively drops singletons by default while fixest retains them (diff-diff matches fixest); an opt-in knob needs iterative unit+period pruning with consistent cluster/survey/replicate/Conley array subsetting and a default-flip decision protocol (moves published SEs) | `diff_diff/twfe.py`, `diff_diff/estimators.py`, `diff_diff/utils.py` | 3(a) R5 | Mid | Low | | Cohort-timing validation input for the simultaneous-adoption event-study family (TWFE `event_study=True`; MultiPeriodDiD through 3.9): an optional `first_treat=`/`cohort=` column so simultaneous adoption becomes checkable under the contract-valid time-invariant `D_i` indicator - today the staggered-adoption advisory derives timing from within-unit 0->1 transitions, so it can only fire on off-contract time-varying `D_it` input, and with valid `D_i` adoption timing is not observable in the inputs at all (REGISTRY "staggered-adoption detection limit" Notes, both sections); design questions: validate-only vs steering error (the M-011 removal shipped in PR 4c-ii, so only the TWFE surface is in play) | `diff_diff/twfe.py`, `diff_diff/estimators.py` | 3(a) R2 | Mid | Medium | -| Replicate effective-df min-cap, library-wide: when a replicate is dropped (`n_valid < R`) the design df is REPLACED by `n_valid - 1` instead of capped at `min(df_survey, n_valid - 1)`, which can RAISE df above the QR-rank design df (anti-conservative; latent - it needs a dropped replicate AND a rank-deficient replicate matrix) and turns an undefined design df (`df_survey=None`, QR rank <= 1) into t-inference at `n_valid - 1`. Replace-style sites: the shared CS-family source `staggered_aggregation.py::_se_from_psi` (feeding the CS overall relay in `staggered.py`, the event-study/group `min(non_none_dfs)` relays, the staggered-DDD overall relay in `_staggered_triple_diff_engine.py`, and the Eq. 4.14 relay in `triple_diff_results.py::_event_time_overall_result`), `efficient_did_aggregation.py`, `continuous_did.py`, `triple_diff.py` (2x2x2), `estimators.py` (x2), `twfe.py`, `sun_abraham.py`, `stacked_did.py` (x2), `imputation_aggregation.py`, `two_stage_aggregation.py`, and `linalg.py` (`LinearRegression._replicate_df`). Roll `survey.cap_replicate_df` (shipped with the per-cell design-SE fix; CS and staggered-DDD per-cell dfs already use it) through all of them, fixing `_se_from_psi` at the source; consolidate DMLDiD's inline rule and reconcile dCDH's `_effective_df_survey` (its docstring wrongly cites EfficientDiD and 2x2x2 TripleDifference as reduce-not-replace precedents); flip `tests/test_survey_dml.py::test_es_df_pins_inherited_replace_convention`; and update the REGISTRY Survey Data Support Notes that state the replace rule ("Survey df uses `n_valid - 1`", "df propagation is not needed") | `diff_diff/survey.py`, `diff_diff/staggered_aggregation.py` | DML replicate PR | Mid | Low | | `balance_e` replay on bootstrapped ImputationDiD/TwoStageDiD fits: the unrestricted ES/group surface is relayed since 4.0 PR 3c (computed at fit, `balance_e=None`; M-021/M-022), but `aggregate('event_study', balance_e=k)` still raises there - a balanced-window replay needs retained per-target psi (ImputationDiD: the panel-backed kit retains everything the psi precompute reads, so a seeded replay is tractable) / retained per-level GMM scores (TwoStageDiD: function-locals today) | `diff_diff/imputation_results.py`, `diff_diff/two_stage_results.py`, `diff_diff/aggregation.py` | 2(b) PR-3b | Mid | Low | | ContinuousDiD post-fit bootstrap-ES REPLAY: since 4.0 PR 3c a bootstrapped fit relays the event-study surface computed at fit (M-025), so the gap is a genuine post-fit replay (fresh draws, no fit-side cost, a route for pre-4.0 pickles); a seeded replay is tractable - the multiplier draws are seeded (`np.random.default_rng(self.seed)`) - but needs the FULL per-cell `_bootstrap_info` (bread/ee_treated/Psi_eval/dPsi_*/beta_pred) the pruned kit deliberately drops, so shipping it means a kit-payload change with its own memory contract | `diff_diff/continuous_did_aggregation.py`, `diff_diff/continuous_did_results.py` | 2(b) PR-3c | Mid | Low | | practitioner `step_name="heterogeneity"` producer-side collisions: three OTHER estimators' advice steps reuse the key with non-heterogeneity labels (`:975` ContinuousDiD dose-response, `:1022` Triple placebo-group, `:1413` LPDiD WAS arrays), so DiagnosticReport's heterogeneity completion silently drops that unrelated advice from `next_steps` via `_filter_steps` - the same latent collision fixed for StackedDiD in M-024 (renamed to `sub_experiment_balance`). Renaming these changes those estimators' report output; audit + rename with per-estimator pins. | `diff_diff/practitioner.py` | 2(b) PR-2 review R9 | Quick | Low | diff --git a/changelog.d/20261122-replicate-df-min-cap.md b/changelog.d/20261122-replicate-df-min-cap.md new file mode 100644 index 000000000..8e91b4102 --- /dev/null +++ b/changelog.d/20261122-replicate-df-min-cap.md @@ -0,0 +1,53 @@ +### Fixed +- **Replicate-weight inference df: a dropped replicate now caps the design df + instead of replacing it** (every estimator with replicate-weight support: + `CallawaySantAnna`, `TripleDifference` (2x2x2 and staggered), `EfficientDiD`, + `ContinuousDiD`, `DifferenceInDifferences`, `TwoWayFixedEffects` including + event-study mode, `SunAbraham`, `StackedDiD`, `ImputationDiD`, `TwoStageDiD`, + `DMLDiD` aggregates, and `LinearRegression`). When a replicate was dropped + (an all-zero replicate column, or a failed replicate refit / solve) the + inference df became `n_valid - 1`, ignoring the design df (QR rank of the + replicate matrix minus 1). It is now `min(df_survey, n_valid - 1)`. Two + outcomes were wrong and are fixed; SEs and point estimates are unchanged: + - **Rank-deficient replicate matrix: df was raised above the design df.** With + 15 usable columns of rank 5 plus one all-zero column, t-stats were referred + to t(14) instead of t(4): on a small staggered panel the `CallawaySantAnna` + overall p-value was 9.1e-09 and is now 2.7e-04, the `TwoWayFixedEffects` + p-value was 7.4e-11 and is now 6.5e-05, and `survey_metadata.df_survey` + read 14 and now reads 4. p-values and confidence intervals on such designs + get wider. + - **Undefined design df (rank <= 1) plus a dropped column gave t-inference.** + Statistics were referred to t(`n_valid - 1`) (e.g. `CallawaySantAnna` + p = 0.013 at t(2)); they now report NaN t-stat, p-value and CI with the SE + still reported, the same as an undefined design with no dropped column. + `survey_metadata.df_survey` stays `None` (it previously read + `n_valid - 1`). + - `LinearRegression.survey_df_` follows the same rule: the capped df, or + `None` on an undefined design df, in which case `get_inference()` emits its + existing "undefined survey d.f." warning and returns NaN inference whether + or not a replicate dropped. + - Plain (no-absorb) `DifferenceInDifferences`: when failed replicate solves + lowered the df, inference used the lower df but `survey_metadata.df_survey` + and `summary()` kept showing the design df. They now report the df used. + - Designs with no dropped replicate, and designs whose surviving replicate + columns are full rank, are unaffected (the two rules coincide). + - See the REGISTRY Survey Data Support replicate-df Note. New helper + `diff_diff.survey.reduced_replicate_df`. + +### Behavioral Changes +- **One statistic with fewer than two valid replicates no longer changes the + inference of the others** (`CallawaySantAnna`, staggered `TripleDifference` + and `DMLDiD` event-study / group aggregates, `EfficientDiD`, + `ContinuousDiD`). Such a statistic has a NaN SE and NaN inference; it used to + also alter the df shared with the rest of the fit: + - `CallawaySantAnna` family aggregates: every event-study horizon or group + row went NaN, and the overall relay could write `0` into + `survey_metadata.df_survey`. Now only the affected row is NaN. + - `EfficientDiD`: every statistic computed afterwards silently switched from + the t reference to the normal reference. Now they keep the design df. + - `ContinuousDiD`: every statistic's inference went NaN. Now only the + affected statistic is NaN. + - This needs a non-finite influence function on a single statistic, so it is + not expected on well-formed fits. `ChaisemartinDHaultfoeuille` is unchanged: + it deliberately takes one global minimum over all its replicate-variance + sites (fail-closed). diff --git a/diff_diff/chaisemartin_dhaultfoeuille.py b/diff_diff/chaisemartin_dhaultfoeuille.py index 9b43f5f14..657658ae1 100644 --- a/diff_diff/chaisemartin_dhaultfoeuille.py +++ b/diff_diff/chaisemartin_dhaultfoeuille.py @@ -1317,9 +1317,9 @@ def fit( # Replicate-weight variance tracker: each _compute_se call under # a replicate design returns n_valid (number of replicate columns # that produced a finite estimate). The effective df_survey is - # min(n_valid) - 1 across all IF sites — matches the precedent in - # `diff_diff/efficient_did.py:1133-1135` and - # `diff_diff/triple_diff.py:676-686`. Under TSL (analytical), + # min(design df, min(n_valid) - 1) across all IF sites - the + # library-wide cap (`survey.cap_replicate_df`), applied here as ONE + # global minimum (see `_effective_df_survey`). Under TSL (analytical), # _compute_se returns None for n_valid and df_survey falls through # to resolved_survey.df_survey (= n_psu - n_strata). _replicate_n_valid_list: List[int] = [] @@ -8140,9 +8140,14 @@ def _effective_df_survey( ``min(resolved_survey.df_survey, min(n_valid) - 1)`` when both are defined. - Matches the precedent in ``diff_diff/efficient_did.py:1133-1135`` - and ``diff_diff/triple_diff.py:676-686`` (both reduce, not - replace). Under TSL (analytical) or non-survey fits, + Same arithmetic as the library-wide rule + :func:`diff_diff.survey.cap_replicate_df` (dropped replicates cap the + design df, never replace it), with two dCDH-specific differences: it + returns ``None`` rather than the ``0`` sentinel when the df is + undefined (``_inference_df`` maps that to the sentinel), and it is ONE + global minimum over every IF site, so a late site with fewer than two + valid replicates turns every surface's inference NaN (fail-closed). + Under TSL (analytical) or non-survey fits, ``replicate_n_valid_list`` is empty and this falls through to the design-level df. Returns ``None`` when either the base df is undefined (rank ≤ 1) or the reduced df would be < 1 — preserving diff --git a/diff_diff/continuous_did.py b/diff_diff/continuous_did.py index 639a308b3..a0bc0d80e 100644 --- a/diff_diff/continuous_did.py +++ b/diff_diff/continuous_did.py @@ -2097,7 +2097,12 @@ def _rep_se(if_vals): nonlocal _rep_n_valid psi_scaled = _w_rep * if_vals v, nv = compute_replicate_if_variance(psi_scaled, unit_resolved) - _rep_n_valid = min(_rep_n_valid, nv) # worst-case valid count + # Worst-case valid count over statistics that HAVE a + # variance. A statistic with fewer than two valid + # replicates has a NaN variance (NaN inference at any df) + # and must not change the df of the other statistics. + if nv >= 2: + _rep_n_valid = min(_rep_n_valid, nv) return float(np.sqrt(max(v, 0.0))) if np.isfinite(v) else np.nan overall_att_se = _rep_se(if_att_glob) @@ -2139,16 +2144,21 @@ def _rep_se(if_vals): acrt_d_se = np.sqrt(np.sum(if_acrt_d**2, axis=0)) # Return unit-level survey df and resolved design for metadata recomputation - # Only override with n_valid-based df when replicates were actually dropped + # Dropped replicates can only LOWER the design df, never replace it + # (survey.reduced_replicate_df): an undefined design df stays None + # (mapped to the NaN-inference sentinel by the caller). if ( resolved_survey is not None and hasattr(resolved_survey, "uses_replicate_variance") and resolved_survey.uses_replicate_variance ): + from diff_diff.survey import reduced_replicate_df + + unit_df_survey = unit_resolved.df_survey if _rep_n_valid < unit_resolved.n_replicates: - unit_df_survey = _rep_n_valid - 1 if _rep_n_valid > 1 else None - else: - unit_df_survey = unit_resolved.df_survey + _reduced_df = reduced_replicate_df(unit_df_survey, _rep_n_valid) + if _reduced_df is not None: + unit_df_survey = _reduced_df else: unit_df_survey = unit_resolved.df_survey if resolved_survey is not None else None diff --git a/diff_diff/continuous_did_aggregation.py b/diff_diff/continuous_did_aggregation.py index d3809305f..6c474f1ab 100644 --- a/diff_diff/continuous_did_aggregation.py +++ b/diff_diff/continuous_did_aggregation.py @@ -192,6 +192,7 @@ def _compute_event_study_inference( if_es[uid] -= w * ee_control[k] / p_0 / n_total_gt # Compute SE: survey-aware TSL or standard sqrt(sum(IF^2)) + es_df: Optional[int] = survey_df if unit_resolved_es is not None: if unit_resolved_es.uses_replicate_variance: from diff_diff.survey import compute_replicate_if_variance @@ -200,6 +201,15 @@ def _compute_event_study_inference( psi_es = unit_resolved_es.weights * if_es variance, _nv = compute_replicate_if_variance(psi_es, unit_resolved_es) es_se = float(np.sqrt(max(variance, 0.0))) if np.isfinite(variance) else np.nan + # Statistic-local df: a dropped replicate can only lower + # the fit's working df for THIS horizon, never raise it + # (survey.reduced_replicate_df; None = keep survey_df). + if _nv < unit_resolved_es.n_replicates: + from diff_diff.survey import reduced_replicate_df + + _reduced_df = reduced_replicate_df(survey_df, _nv) + if _reduced_df is not None: + es_df = _reduced_df else: X_ones_es = np.ones((n_units, 1)) tsl_scale_es = float(unit_resolved_es.weights.sum()) @@ -209,7 +219,7 @@ def _compute_event_study_inference( else: es_se = float(np.sqrt(np.sum(if_es**2))) - t_stat, p_val, ci_es = safe_inference(info_e["effect"], es_se, self.alpha, df=survey_df) + t_stat, p_val, ci_es = safe_inference(info_e["effect"], es_se, self.alpha, df=es_df) info_e["se"] = es_se info_e["t_stat"] = t_stat info_e["p_value"] = p_val diff --git a/diff_diff/dml_did.py b/diff_diff/dml_did.py index 178e7fee8..d1975ff71 100644 --- a/diff_diff/dml_did.py +++ b/diff_diff/dml_did.py @@ -1570,7 +1570,7 @@ def _cell_se_from_payload( se: float with np.errstate(over="ignore", invalid="ignore"): if resolved_survey_unit is not None and resolved_survey_unit.uses_replicate_variance: - from diff_diff.survey import compute_replicate_if_variance + from diff_diff.survey import cap_replicate_df, compute_replicate_if_variance variance, n_valid_rep = compute_replicate_if_variance( inf_full, resolved_survey_unit @@ -1579,16 +1579,12 @@ def _cell_se_from_payload( se = float("nan") else: se = float(np.sqrt(variance)) - # Per-cell df: min(design df, n_valid - 1) — the dCDH - # _effective_df_survey rule, inlined. n_valid is computed - # over the WHOLE replicate columns, so it equals R for every - # cell in practice (defensive; REGISTRY Note). - if df_survey is not None: - df_survey = min(int(df_survey), int(n_valid_rep) - 1) - else: - # Undefined replicate df (QR rank <= 1): df=0 sentinel - # -> NaN inference (CS sentinel parity). - df_survey = 0 + # Per-cell df: the library-wide cap min(design df, + # n_valid - 1), with an undefined design df (QR rank <= 1) + # mapped to the 0 sentinel -> NaN inference. For a finite IF + # the cap never binds (design df <= n_valid - 1; REGISTRY + # Note). + df_survey = cap_replicate_df(df_survey, n_valid_rep) elif ( resolved_survey_unit is not None and getattr(resolved_survey_unit, "psu", None) is not None @@ -2663,7 +2659,7 @@ def _compute_dml_rcs_gt( se: float with np.errstate(over="ignore", invalid="ignore"): if resolved_survey_unit is not None and resolved_survey_unit.uses_replicate_variance: - from diff_diff.survey import compute_replicate_if_variance + from diff_diff.survey import cap_replicate_df, compute_replicate_if_variance variance, n_valid_rep = compute_replicate_if_variance( inf_full, resolved_survey_unit @@ -2672,10 +2668,7 @@ def _compute_dml_rcs_gt( se = float("nan") else: se = float(np.sqrt(variance)) - if df_survey is not None: - df_survey = min(int(df_survey), int(n_valid_rep) - 1) - else: - df_survey = 0 + df_survey = cap_replicate_df(df_survey, n_valid_rep) elif ( resolved_survey_unit is not None and getattr(resolved_survey_unit, "psu", None) is not None @@ -3189,11 +3182,11 @@ def fit( reference_event_times = tuple(sorted(ref_event_times)) # Overall ATT (simple aggregation over post-treatment finite cells). - # overall_effective_df is non-None only when replicate variance - # dropped replicates (n_valid < R). MIN-CAP, not CS's replace: the - # QR-rank design df stays the ceiling (CS's replace convention can - # RAISE df above the design df — anti-conservative; deliberate - # documented divergence, REGISTRY DMLDiD Note + replicate-df min-cap TODO row). + # overall_effective_df is non-None only when dropped replicates + # strictly lower the design df (the shared _se_from_psi contract, + # survey.reduced_replicate_df): the QR-rank design df is the ceiling. + # The min() below is therefore redundant with the shared rule and + # kept as a local guard. overall_att, overall_se, overall_effective_df = self._aggregate_simple( group_time_effects, influence_func_info, df, unit, precomputed ) diff --git a/diff_diff/efficient_did_aggregation.py b/diff_diff/efficient_did_aggregation.py index 617f3eb4d..1af8ae4bd 100644 --- a/diff_diff/efficient_did_aggregation.py +++ b/diff_diff/efficient_did_aggregation.py @@ -103,10 +103,20 @@ class _EfficientAggregationMixin: five attributes declared below — this is the ``_EDiDKitAggregator`` contract (``efficient_did_results.py``): the post-fit path constructs a fresh throwaway host per ``aggregate()`` call, so the ONE mutation these - methods perform (``_compute_survey_eif_se`` writes ``self._survey_df`` - when a degenerate replicate design drops replicates) lands on the + methods perform (``_note_replicate_n_valid`` lowers ``self._survey_df`` + when a replicate-variance call drops replicates) lands on the throwaway, never on the retained kit — preserving the aggregate() immutability contract. + + That mutation is a monotone ``min`` and fires only on a strict reduction + from at least two valid replicates (``survey.reduced_replicate_df``): the + working df is never raised above the design df it was seeded from, an + undefined design df stays the ``0`` sentinel, and a statistic with fewer + than two valid replicates (NaN variance, NaN inference at any df) leaves + the df of every other statistic untouched. On the influence-function path + the design df never exceeds ``n_valid - 1`` for a finite EIF (QR rank <= + number of nonzero replicate columns), so in practice the working df stays + the design df. """ # Typed host-attribute contract (mypy attr-defined; the @@ -120,6 +130,23 @@ class _EfficientAggregationMixin: # -- Survey SE helpers ---------------------------------------------------- + def _note_replicate_n_valid(self, n_valid: int) -> None: + """Lower the working df for a replicate-variance call that dropped replicates. + + The base is the CURRENT working df, which was seeded from the unit-level + design df and is only ever lowered here - equivalent to capping the + design df, without re-reading ``df_survey`` (a QR on every access). + See the class docstring for the contract. + """ + resolved = self._unit_resolved_survey + if resolved is None or n_valid >= resolved.n_replicates: + return + from diff_diff.survey import reduced_replicate_df + + reduced = reduced_replicate_df(self._survey_df, n_valid) + if reduced is not None: + self._survey_df = reduced + def _compute_survey_eif_se(self, eif_vals: np.ndarray) -> float: """Compute SE from EIF scores using Taylor Series Linearization. @@ -139,9 +166,7 @@ def _compute_survey_eif_se(self, eif_vals: np.ndarray) -> float: variance, n_valid = compute_replicate_if_variance( psi_scaled, self._unit_resolved_survey ) - # Update survey df to reflect effective replicate count - if n_valid < self._unit_resolved_survey.n_replicates: - self._survey_df = n_valid - 1 if n_valid > 1 else None + self._note_replicate_n_valid(n_valid) return float(np.sqrt(max(variance, 0.0))) if np.isfinite(variance) else np.nan from diff_diff.survey import compute_survey_vcov @@ -304,7 +329,10 @@ def _aggregate_overall( ): from diff_diff.survey import compute_replicate_if_variance - variance, _ = compute_replicate_if_variance(psi_total, self._unit_resolved_survey) + variance, n_valid = compute_replicate_if_variance( + psi_total, self._unit_resolved_survey + ) + self._note_replicate_n_valid(n_valid) else: from diff_diff.survey import compute_survey_if_variance @@ -444,9 +472,10 @@ def _aggregate_event_study( ): from diff_diff.survey import compute_replicate_if_variance - variance, _ = compute_replicate_if_variance( + variance, n_valid = compute_replicate_if_variance( psi_total, self._unit_resolved_survey ) + self._note_replicate_n_valid(n_valid) else: from diff_diff.survey import compute_survey_if_variance diff --git a/diff_diff/efficient_did_results.py b/diff_diff/efficient_did_results.py index 0c6f96c17..5947200b7 100644 --- a/diff_diff/efficient_did_results.py +++ b/diff_diff/efficient_did_results.py @@ -454,15 +454,16 @@ def _aggregate_compute( # Carrier + shared builder: EDiD is a _from_relative_dict producer, # so the recomputed dict rides the same route as the fit-time # surface. The carrier's survey_metadata is a COPY whose df_survey - # is the kit's post-overall snapshot - _recompute_unit_survey_ - # metadata's is-not-None guard can leave the raw metadata at the - # resolved design's finite value when the governing df degenerated - # to None (n_valid <= 1), and the copy keeps the container honest - # there (in non-degenerate fits the two agree and the copy is - # inert). Copying also keeps the parent's metadata unmutated. + # is the kit's post-overall snapshot, so the container reports the + # df that actually governed the fit's inference (in non-degenerate + # fits it equals the raw metadata value and the copy is inert). + # Copying also keeps the parent's metadata unmutated. meta = self.survey_metadata if meta is not None: - meta = dataclasses.replace(meta, df_survey=bk["df_survey"]) + # The kit df is the 0 sentinel on a replicate design whose df is + # undefined; metadata keeps None for that state (the resolver + # ladder maps None + replicate_method back to the 0.0 sentinel). + meta = dataclasses.replace(meta, df_survey=(bk["df_survey"] or None)) # The carrier's PROVENANCE fields also come from the kit snapshots # (CI review R2): the reference_period property and the container's # alpha/anticipation must reflect the FIT's regime, not a possibly @@ -498,11 +499,12 @@ def _aggregate_simple_result(self, kit: Any) -> AggregationResult: ``df`` is the kit's post-overall ``df_survey`` snapshot - the very value fit passed to ``safe_inference`` for the overall row - NOT - ``resolve_inference_df(self)``: ``survey_metadata.df_survey`` can - diverge from the governing df in the degenerate replicate case - (``n_valid <= 1`` sets the working df to None while the metadata - keeps the resolved design's finite value), and the snapshot is - provenance-exact in every state. None → all-NaN df column; + ``resolve_inference_df(self)``: the snapshot is the value that + governed the fit's inference and is provenance-exact in every + state (a replicate-variance call that drops replicates can only + lower the working df; one with fewer than two valid replicates + leaves it unchanged and NaNs only its own statistic). + None → all-NaN df column; the replicate-undefined 0-sentinel row NaNs out via post_init. Bootstrapped fits relay the stored quintet verbatim (percentile se/p/CI beside the finite ``safe_inference`` t) with a NaN df diff --git a/diff_diff/estimators.py b/diff_diff/estimators.py index 4ca149441..3cdde6073 100644 --- a/diff_diff/estimators.py +++ b/diff_diff/estimators.py @@ -861,7 +861,11 @@ def _refit_did_absorb(w_r): # Replicate-refit path is only reached with a resolved design. assert resolved_survey is not None if _n_valid_rep < resolved_survey.n_replicates: - _df_rep = _n_valid_rep - 1 if _n_valid_rep > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + _df_rep = cap_replicate_df(_df_rep, _n_valid_rep) if survey_metadata is not None: survey_metadata.df_survey = _df_rep if _df_rep > 0 else None t_stat, p_value, conf_int = safe_inference(att, se, alpha=self.alpha, df=_df_rep) @@ -913,6 +917,17 @@ def _refit_did_absorb(w_r): _inference_df_used = ( float(inference.df) if inference.df is not None and inference.df > 0 else None ) + # Replicate design whose failed solves lowered the df below the + # design df: the regression used reg.survey_df_, so metadata (and + # summary()) must report that df, not the design df. + if ( + survey_metadata is not None + and resolved_survey is not None + and getattr(resolved_survey, "uses_replicate_variance", False) + and reg.survey_df_ is not None + and survey_metadata.df_survey != reg.survey_df_ + ): + survey_metadata.df_survey = reg.survey_df_ r_squared = compute_r_squared(y, residuals) @@ -2101,14 +2116,19 @@ def _refit_mp_absorb(w_r): if resolved_survey is not None and resolved_survey.df_survey is not None: df = resolved_survey.df_survey - # Replicate df: rank-deficient → NaN inference; dropped replicates → n_valid-1 + # Replicate df: rank-deficient → NaN inference; dropped replicates cap + # the df at min(df, n_valid - 1) if _uses_replicate_mp: # The flag definition above guarantees this (mypy can't track it). assert resolved_survey is not None if resolved_survey.df_survey is None: df = 0 # rank-deficient replicate → NaN inference if _n_valid_rep_mp is not None and _n_valid_rep_mp < resolved_survey.n_replicates: - df = _n_valid_rep_mp - 1 if _n_valid_rep_mp > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + df = cap_replicate_df(df, _n_valid_rep_mp) if survey_metadata is not None: survey_metadata.df_survey = df if df > 0 else None diff --git a/diff_diff/imputation.py b/diff_diff/imputation.py index f20f0a24e..83cf86060 100644 --- a/diff_diff/imputation.py +++ b/diff_diff/imputation.py @@ -690,7 +690,8 @@ def fit( # Survey degrees of freedom for t-distribution inference _survey_df = resolved_survey.df_survey if resolved_survey is not None else None - # Replicate df: rank-deficient → NaN inference; dropped replicates → n_valid-1 + # Replicate df: rank-deficient → NaN inference (dropped replicates cap + # the df at min(df, n_valid - 1) in the replicate-refit override) if _uses_replicate_imp and _survey_df is None: _survey_df = 0 # rank-deficient replicate → NaN inference diff --git a/diff_diff/imputation_aggregation.py b/diff_diff/imputation_aggregation.py index f9a1eff4d..9472b32d9 100644 --- a/diff_diff/imputation_aggregation.py +++ b/diff_diff/imputation_aggregation.py @@ -1833,7 +1833,11 @@ def _refit_imp(w_r): assert resolved_survey is not None survey_df_final = survey_df_seed if _n_valid_rep_imp < resolved_survey.n_replicates: - survey_df_final = _n_valid_rep_imp - 1 if _n_valid_rep_imp > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + survey_df_final = cap_replicate_df(survey_df_seed, _n_valid_rep_imp) # Override event-study SEs from vcov diagonal for i, e in enumerate(_sorted_rel_times): diff --git a/diff_diff/linalg.py b/diff_diff/linalg.py index 70c291c5e..367c02795 100644 --- a/diff_diff/linalg.py +++ b/diff_diff/linalg.py @@ -4900,11 +4900,18 @@ def fit( _effective_survey_design, weight_type=_fit_weight_type, ) - # Store effective replicate df only when replicates were dropped + # Dropped replicates can only LOWER the rank-based design df + # (survey.reduced_replicate_df); None = use the design df. + # An undefined design df therefore stays None whether or not a + # replicate dropped, and get_inference() takes its + # "undefined survey d.f." warning + NaN branch. + self._replicate_df = None if _n_valid_rep < _effective_survey_design.n_replicates: - self._replicate_df = _n_valid_rep - 1 if _n_valid_rep > 1 else None - else: - self._replicate_df = None # use rank-based df from design + from diff_diff.survey import reduced_replicate_df + + self._replicate_df = reduced_replicate_df( + _effective_survey_design.df_survey, _n_valid_rep + ) else: from diff_diff.survey import compute_survey_vcov diff --git a/diff_diff/stacked_did.py b/diff_diff/stacked_did.py index 61db46ac3..5eb37f397 100644 --- a/diff_diff/stacked_did.py +++ b/diff_diff/stacked_did.py @@ -925,7 +925,11 @@ def _refit_stacked(w_r): # Override df when replicate replicates were dropped if _n_valid_rep_sd is not None and resolved_stacked is not None: if _n_valid_rep_sd < resolved_stacked.n_replicates: - _survey_df = _n_valid_rep_sd - 1 if _n_valid_rep_sd > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + _survey_df = cap_replicate_df(_survey_df, _n_valid_rep_sd) if survey_metadata is not None: survey_metadata.df_survey = _survey_df if _survey_df > 0 else None # Use BM contrast DOF for hc2_bm. Fail-closed: when the @@ -1012,7 +1016,11 @@ def _refit_stacked(w_r): ) if _n_valid_rep_sd is not None and resolved_stacked is not None: if _n_valid_rep_sd < resolved_stacked.n_replicates: - _survey_df_overall = _n_valid_rep_sd - 1 if _n_valid_rep_sd > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + _survey_df_overall = cap_replicate_df(_survey_df_overall, _n_valid_rep_sd) if survey_metadata is not None: survey_metadata.df_survey = ( _survey_df_overall if _survey_df_overall > 0 else None diff --git a/diff_diff/staggered_aggregation.py b/diff_diff/staggered_aggregation.py index 09db17e93..1468e4949 100644 --- a/diff_diff/staggered_aggregation.py +++ b/diff_diff/staggered_aggregation.py @@ -849,8 +849,14 @@ def _se_from_psi( variance estimator the per-event-time and simple-aggregation SE paths use: replicate-weight variance, full survey-design variance, or the simple ``sqrt(sum(psi^2))``. Callers must guard emptiness/finiteness first. - Returns ``(se, effective_df)``; ``effective_df`` is non-None only for - replicate designs that dropped replicates. + Returns ``(se, effective_df)``; ``effective_df`` is non-None only when + a replicate design dropped replicates AND that strictly lowers the + design df (``survey.reduced_replicate_df``). It is never above the + design df, never set on an undefined design df, and never set for a + statistic with fewer than two valid replicates (NaN variance), so the + relays that consume it (``if eff_df is not None: df = eff_df`` and the + event-study / group ``min``) can neither raise the df nor let one + degenerate statistic change another's. """ resolved_survey = ( precomputed.get("resolved_survey_unit") if precomputed is not None else None @@ -860,13 +866,21 @@ def _se_from_psi( and hasattr(resolved_survey, "uses_replicate_variance") and resolved_survey.uses_replicate_variance ): - from diff_diff.survey import compute_replicate_if_variance + from diff_diff.survey import compute_replicate_if_variance, reduced_replicate_df variance, n_valid_rep = compute_replicate_if_variance(psi_total, resolved_survey) - # Compute effective df for this statistic (don't mutate shared state) + # Effective df for this statistic (don't mutate shared state). + # The design df comes from the fit-cached precomputed value: + # ResolvedSurveyDesign.df_survey runs a pivoted QR on the + # replicate matrix on every access, and an all-zero replicate + # column makes n_valid < R for EVERY horizon / group. effective_df = None if n_valid_rep < resolved_survey.n_replicates: - effective_df = n_valid_rep - 1 if n_valid_rep > 1 else 0 + if precomputed is not None and "df_survey" in precomputed: + design_df = precomputed["df_survey"] + else: + design_df = resolved_survey.df_survey + effective_df = reduced_replicate_df(design_df, n_valid_rep) if np.isnan(variance): se = np.nan else: diff --git a/diff_diff/sun_abraham.py b/diff_diff/sun_abraham.py index ac943f8cf..10550b068 100644 --- a/diff_diff/sun_abraham.py +++ b/diff_diff/sun_abraham.py @@ -1207,8 +1207,8 @@ def _refit_sa(w_r): if survey_metadata is not None and survey_metadata.df_survey is not None else None ) - # Replicate df: rank-deficient → NaN inference (dropped-replicate - # override happens after replicate refit below) + # Replicate df: rank-deficient → NaN inference (the dropped-replicate + # cap min(df, n_valid - 1) is applied after the replicate refit below) if _uses_replicate_sa and _sa_survey_df is None: _sa_survey_df = 0 # rank-deficient replicate → NaN inference @@ -1436,7 +1436,11 @@ def _refit_sa(w_r): # Replicate-refit path is only reached with a resolved design. assert resolved_survey is not None if _n_valid_rep_sa < resolved_survey.n_replicates: - _sa_survey_df = _n_valid_rep_sa - 1 if _n_valid_rep_sa > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + _sa_survey_df = cap_replicate_df(_sa_survey_df, _n_valid_rep_sa) if survey_metadata is not None: survey_metadata.df_survey = ( _sa_survey_df if _sa_survey_df and _sa_survey_df > 0 else None @@ -1496,6 +1500,8 @@ def _refit_sa_cohort(w_r): ) return np.array([ce_r.get(k, np.nan) for k in _keys_ordered]) + # n_valid is not consumed here: cohort effects store effect / se / + # weight only (no t-stat, p-value or CI), so no df prices them. _vcov_cohort_rep, _ = compute_replicate_refit_variance( _refit_sa_cohort, _full_cohort_vec, resolved_survey ) diff --git a/diff_diff/survey.py b/diff_diff/survey.py index 8889b1149..5e347d637 100644 --- a/diff_diff/survey.py +++ b/diff_diff/survey.py @@ -2549,6 +2549,32 @@ def cap_replicate_df(base_df: Optional[float], n_valid: int) -> int: return max(min(int(base_df), int(n_valid) - 1), 0) +def reduced_replicate_df(base_df: Optional[float], n_valid: int) -> Optional[int]: + """Strictly reduced replicate df, or ``None`` when no override applies. + + For sites that keep a working df seeded from the design df and only + *override* it for a statistic whose replicates dropped. Returns + ``min(base_df, n_valid - 1)`` only when the design df is defined and + positive, at least two replicates are valid, and the result is strictly + below ``base_df``. Otherwise returns ``None`` ("keep the working df"): + + - an undefined design df (``None`` or the ``0`` sentinel) stays undefined - + it is never replaced by ``n_valid - 1``; + - ``n_valid - 1 >= base_df`` leaves the design df in place (never raised); + - fewer than two valid replicates means that statistic's variance is NaN, + so its inference is NaN at any df and it must not change the df of any + other statistic. + + Same arithmetic as :func:`cap_replicate_df`, which is the form for + statistic-local dfs and for refit paths where one joint vcov prices every + statistic. + """ + if base_df is None or base_df <= 0 or n_valid < 2: + return None + reduced = int(n_valid) - 1 + return reduced if reduced < int(base_df) else None + + def compute_replicate_refit_variance( refit_fn: Callable[[np.ndarray], np.ndarray], full_sample_estimate: np.ndarray, diff --git a/diff_diff/triple_diff.py b/diff_diff/triple_diff.py index 71e25ff20..c8583ec81 100644 --- a/diff_diff/triple_diff.py +++ b/diff_diff/triple_diff.py @@ -677,15 +677,22 @@ def fit( # When survey design is active, use survey df (n_PSU - n_strata) if survey_metadata is not None and survey_metadata.df_survey is not None: df = survey_metadata.df_survey - # Override with effective replicate df only when replicates were dropped + # Dropped replicates can only LOWER the design df (never replace + # it): survey.reduced_replicate_df returns None unless + # min(df, n_valid - 1) is a strict reduction from >= 2 valid + # replicates. if ( hasattr(self, "_replicate_n_valid") and self._replicate_n_valid is not None and resolved_survey is not None and self._replicate_n_valid < resolved_survey.n_replicates ): - df = self._replicate_n_valid - 1 - survey_metadata.df_survey = self._replicate_n_valid - 1 + from diff_diff.survey import reduced_replicate_df + + _reduced_df = reduced_replicate_df(df, self._replicate_n_valid) + if _reduced_df is not None: + df = _reduced_df + survey_metadata.df_survey = _reduced_df # df <= 0 means insufficient rank for t-based inference if df is not None and df <= 0: df = 0 # Forces NaN from t-distribution diff --git a/diff_diff/twfe.py b/diff_diff/twfe.py index 8a070c980..de85307f3 100644 --- a/diff_diff/twfe.py +++ b/diff_diff/twfe.py @@ -884,7 +884,11 @@ def _refit_twfe(w_r): # Replicate-refit path is only reached with a resolved design. assert resolved_survey is not None if _n_valid_rep_twfe < resolved_survey.n_replicates: - _df_rep = _n_valid_rep_twfe - 1 if _n_valid_rep_twfe > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + _df_rep = cap_replicate_df(_df_rep, _n_valid_rep_twfe) if survey_metadata is not None: survey_metadata.df_survey = _df_rep if _df_rep > 0 else None t_stat, p_value, conf_int = _safe_inf(att, se, alpha=self.alpha, df=_df_rep) diff --git a/diff_diff/two_stage_aggregation.py b/diff_diff/two_stage_aggregation.py index d0a31a322..e2f3f56ad 100644 --- a/diff_diff/two_stage_aggregation.py +++ b/diff_diff/two_stage_aggregation.py @@ -1537,7 +1537,11 @@ def _refit_ts(w_r): assert resolved_survey is not None survey_df_final = survey_df_seed if _n_valid_rep_ts < resolved_survey.n_replicates: - survey_df_final = _n_valid_rep_ts - 1 if _n_valid_rep_ts > 1 else 0 + # Dropped replicates CAP the df at min(df, n_valid - 1); they never + # replace it (a rank-deficient replicate matrix has df < n_valid - 1). + from diff_diff.survey import cap_replicate_df + + survey_df_final = cap_replicate_df(survey_df_seed, _n_valid_rep_ts) # Override event-study SEs (only for identified effects) for i, e in enumerate(_sorted_es_periods_ts): diff --git a/docs/methodology/REGISTRY.md b/docs/methodology/REGISTRY.md index 3109e1daf..e8d3bb437 100644 --- a/docs/methodology/REGISTRY.md +++ b/docs/methodology/REGISTRY.md @@ -1964,7 +1964,7 @@ where `q_{g,e} = pi_g / sum_{g' in G_{trt,e}} pi_{g'}`. - **Note:** `vcov_type` is permanently narrow to `{"hc1"}` per the Chen-Sant'Anna-Xie (2025) EIF-based variance achieving the semiparametric efficiency bound. Analytical-sandwich families `{classical, hc2, hc2_bm}` are rejected at `__init__` — the per-unit EIF aggregation has no equivalent single design matrix on which hat-matrix leverage or Bell-McCaffrey Satterthwaite DOF can be defined. `cluster=` invokes Liang-Zeger CR1 on cluster-aggregated EIF (`_compute_se_from_eif` with `cluster_indices`); `survey_design=` invokes TSL on the combined IF (`_compute_survey_eif_se`); both live in `diff_diff/efficient_did_aggregation.py` since the M-023 post-fit aggregate() extraction. `vcov_type='conley'` deferred to the EfficientDiD Conley follow-up row in DEFERRED.md. - **Note:** Default `cluster=None` (no survey design) renders summary label "HC1 heteroskedasticity-robust" because the per-unit EIF SE `sqrt(mean(EIF²)/n)` is methodologically HC1-style (no Liang-Zeger G/(G-1) finite-sample correction). M-080 position (category b; shipped item 7b, 2026-10-29): `cluster=False` is an accepted explicit no-op (bit-identical to the default) on `fit()` and on the `hausman_pretest` classmethod's own `cluster` argument; the shared `str | None | False` contract ([M-155]) applies. `EfficientDiDResults.cluster_name` and `n_clusters` stay None under unclustered fits. This diverges from `ImputationDiD` which auto-clusters at unit per Borusyak-Jaravel-Spiess (2024) Theorem 3 — there the default summary renders the CR1 unit-clustered label. - **Note:** `set_params(vcov_type=bad)` raises immediately on EVERY estimator: since the shared `BaseEstimator` mixin (`diff_diff/_base.py`, v4 2(c)-i), `set_params` validates transactionally by constructor probe re-init, so it enforces exactly `__init__`'s validation, eagerly, library-wide. The former split — EfficientDiD eager vs `ImputationDiD`/`TripleDifference`/`CallawaySantAnna` (and six more: SunAbraham, StackedDiD, the since-removed StaggeredTripleDifference, SpilloverDiD, TROP, PreTrendsPower) accepting constructor-rejected values until `fit()` — is retired; the fit-time re-validation layers remain as a second check against DIRECT attribute mutation (`est.vcov_type = ...`), which no setter can see. -- **Note (post-fit aggregate() - rows M-023/M-120):** `fit(aggregate=, balance_e=)` was deprecated in 3.9 and REMOVED at 4.0 (PR 3b of the cut: `fit()` computes no event-study/group surface, the legacy `event_study_effects`/`group_effects`/`event_study_df` fields are None after EVERY fit, `to_dataframe(level='event_study')` returns `aggregate('event_study').to_dataframe()` - the unified `EVENT_STUDY_SCHEMA` frame - since the 4.0 cut ([M-093] item 8b; bootstrapped fits replay the fit-time bootstrap on every call), while `to_dataframe(level='group')` still raises on fresh fits with the post-fit pointer, and `survey_design`/`store_eif` are positional slots 7/8) in favor of post-fit `EfficientDiDResults.aggregate(type, balance_e=)` - a LAZY RECOMPUTING KIT (the CallawaySantAnna class, not a StackedDiD/dCDH view relay): `fit()` computes nothing extra, the results object retains an `AggregationKit`, and `aggregate('event_study'/'group', balance_e=)` re-runs the extracted `_EfficientAggregationMixin` aggregators on a throwaway host while `aggregate('simple')` relays the stored overall row bit-exact. (a) RETAINED BUFFERS (memory contract; phrased as maxima - optional design fields stay None when unsupplied): the per-(g,t) EIF dict, O(n_units x n_gt), the dominant payload - retained on EVERY fit regardless of `store_eif`, which since 3.9 governs only the public `influence_functions` field; `unit_cohorts` (cohort labels), `unit_level_weights`, factorized cluster codes - O(n_units) each; on ordinary (TSL) survey fits the unit-level `ResolvedSurveyDesign` adds `weights` plus, where supplied, `strata`/`psu`/`fpc` (factorized int codes / float values, never raw labels) - up to four O(n_units) arrays; on replicate designs it adds the O(n_units x n_replicates) replicate matrix plus, where supplied, `replicate_strata`/`replicate_rscales` (O(n_replicates)); per-row dict SNAPSHOTS of `group_time_effects` plus copies of the `groups`/`time_periods` lists and the scalar `pt_assumption`/`n_treated+n_control` provenance (aggregate() recomputes exclusively from these private snapshots, never from the mutable public result fields - a user edit of the public rows cannot mix altered point estimates with the retained EIF variance); scalars `n_units`, `cohort_fractions`, and the POST-OVERALL `df_survey` snapshot (captured after the overall inference and before the ES/group gates: the group pass can degenerate the working df to None on replicate designs with `n_valid <= 1`, and every fit-time aggregation seeds from the post-overall value, so recompute replays the exact seed). The data-minimization guarantee is scoped to unit identifiers - no unit-label container is retained. (b) `balance_e` uses the ANCHOR-HORIZON rule (keep cohorts with a finite effect at the anchor horizon, then retain all their horizons) - the same rule SHAPE CallawaySantAnna uses, with one keying-granularity difference (EDiD anchors on the `int(t - g)` bucket, CS on raw `t - g` - identical on integer-period panels; see the truncation Note below), divergent from ImputationDiD/TwoStageDiD's balanced-window rule; an anchor no cohort reaches warns and yields a legal zero-row container. (c) BOOTSTRAP fits: 'simple' (and 'total') RELAY the stored overall row verbatim (percentile se/p/CI beside the finite safe_inference t) with a NaN df column and never re-warn, while the RECOMPUTE levels (ES/group, balance_e included) REPLAY the fit-time multiplier bootstrap from the kit's `BootstrapReplaySpec` (the fit-captured RNG state + run params BY VALUE - seed=None fits replay; post-fit `set_params`/attribute mutation cannot alter it; pickles carry it): se/CI/t match a fit-time aggregation to BLAS reassociation (~1 ULP, `assert_allclose` - never bit-identity), the percentile p-value is a count statistic (compared at 2/n_bootstrap), and the replay publishes no analytical provenance (percentile overrides via the shared `bootstrap_utils` appliers; group rows' `df_used` cleared exactly as at fit time; EDiD has no sup-t cband). The spec stamps the weight backend at capture ('rust'/'numpy', or 'portable' for backend-independent branches - stratified survey generation, census-FPC zero weights, the single-PSU degenerate early return); a replay under a different backend fails closed naming both, and legacy pickles without the spec fail closed with a refit message. Replays RE-EMIT the fit-time bootstrap warnings for the replayed configuration (low n_bootstrap, single-PSU, empty balance_e anchor, non-finite-draw RuntimeWarnings); the relay levels stay silent. Per-call cost O(n_bootstrap x n_units x n_gt), no memoization. The M-027 rationale - no level publishes analytical-provenance fields beside percentile inference - is honored by the percentile overrides and NaN df channels. (d) CONTAINER ADMISSION into `compute_honest_did`/`compute_pretrends_power` is REJECTED BY DESIGN (both terminal TypeErrors state it): the primary ground is the absent joint event-study covariance (container `vcov=None`; the PER-ROW df column now threads the post-overall `df_survey` snapshot via the results-level `event_study_df` channel on analytical survey fits - M-092 completion; None on non-survey/bootstrapped/no-surface fits and for the replicate-undefined 0 sentinel - beside the scalar `df_survey` channel; see the CS post-fit Note's two-channel contract). Reference semantics are regime-dependent: under `pt_assumption="all"` there is NO reference row (universal first-period baseline; e=-1 is a genuine estimate); under `"post"` the per-cohort baseline cell is materialized as a mechanical zero anchor at `e = -1 - anticipation` whenever it is not the panel's first period, and the MEMBERSHIP-GATED `reference_period` property (the SunAbraham rule - never synthesized when the anchor cell was not estimated) marks it `is_reference` in the container and corrects `plot_event_study`'s inferred reference (previously the `-1` fallback) on PT-Post `anticipation>0` fits. (e) 'simple' relay conventions: `target="att"`, `n = n_treated_units + n_control_units` with `n_kind="units"` (DISJOINT by construction - `last_cohort` trimming reassigns before the counts, so a true total exists, unlike StackedDiD's overlapping sets), `df` = the post-overall snapshot (provenance-exact where `survey_metadata.df_survey` can diverge in the degenerate replicate state); 'group' relay: `n_kind="cells"`, `weight=None` (equal within-cohort weights, no cross-cohort mass), per-row `df_used` array captured at each row's `safe_inference` call (exact by construction; a stated divergence from CS's conservative-min scalar broadcast); 'event_study' rides the shared `_from_relative_dict` builder via a carrier whose `survey_metadata` copy carries the snapshot `df_survey` and whose `event_study_df` threads the same snapshot into the per-row df column (cleared on bootstrap replays and for the 0 sentinel). (f) `aggregate('total')` (3.10): the estimator-owned total incremental outcome - an exact relay `C x overall` CONDITIONAL on the realized aggregation mass, with `C = sum(n_treated)` over the kept post-anticipation FINITE-effect cells of the kit's deep-copied `group_time_effects` snapshot (an exact integer sum; NEVER the routinely-non-integral `n_units x sum(cohort_fractions)` float product). Unweighted fits only: ANY declared `survey_design=` fails closed via the kit's `unit_level_weights`/`resolved_survey_unit` markers (weight-type-agnostic - unweighted psu-only and analytic fweight designs, whose resolved weights stay RAW, gate identically; EDiD never synthesizes an internal design, so the markers are exact declaration provenance and post-fit mutation of the public `survey_metadata` cannot bypass them). No keepers -> NaN mass -> all-NaN row (no re-warn); with finite `C` the relay is verbatim (inherited NaNs pass through; att/n never blanked). Bootstrap fits relay with a NaN df column (M-027); df carrier = the post-overall `df_survey` snapshot; container: single `target='total'` row, `n_kind='obs'`, the per-level n-semantics note in the CS total Note applies. MMM: the container is admitted with NO scale (see the MMM section); the survey/RC totals remainder and its att*dC variance term are the DEFERRED row. +- **Note (post-fit aggregate() - rows M-023/M-120):** `fit(aggregate=, balance_e=)` was deprecated in 3.9 and REMOVED at 4.0 (PR 3b of the cut: `fit()` computes no event-study/group surface, the legacy `event_study_effects`/`group_effects`/`event_study_df` fields are None after EVERY fit, `to_dataframe(level='event_study')` returns `aggregate('event_study').to_dataframe()` - the unified `EVENT_STUDY_SCHEMA` frame - since the 4.0 cut ([M-093] item 8b; bootstrapped fits replay the fit-time bootstrap on every call), while `to_dataframe(level='group')` still raises on fresh fits with the post-fit pointer, and `survey_design`/`store_eif` are positional slots 7/8) in favor of post-fit `EfficientDiDResults.aggregate(type, balance_e=)` - a LAZY RECOMPUTING KIT (the CallawaySantAnna class, not a StackedDiD/dCDH view relay): `fit()` computes nothing extra, the results object retains an `AggregationKit`, and `aggregate('event_study'/'group', balance_e=)` re-runs the extracted `_EfficientAggregationMixin` aggregators on a throwaway host while `aggregate('simple')` relays the stored overall row bit-exact. (a) RETAINED BUFFERS (memory contract; phrased as maxima - optional design fields stay None when unsupplied): the per-(g,t) EIF dict, O(n_units x n_gt), the dominant payload - retained on EVERY fit regardless of `store_eif`, which since 3.9 governs only the public `influence_functions` field; `unit_cohorts` (cohort labels), `unit_level_weights`, factorized cluster codes - O(n_units) each; on ordinary (TSL) survey fits the unit-level `ResolvedSurveyDesign` adds `weights` plus, where supplied, `strata`/`psu`/`fpc` (factorized int codes / float values, never raw labels) - up to four O(n_units) arrays; on replicate designs it adds the O(n_units x n_replicates) replicate matrix plus, where supplied, `replicate_strata`/`replicate_rscales` (O(n_replicates)); per-row dict SNAPSHOTS of `group_time_effects` plus copies of the `groups`/`time_periods` lists and the scalar `pt_assumption`/`n_treated+n_control` provenance (aggregate() recomputes exclusively from these private snapshots, never from the mutable public result fields - a user edit of the public rows cannot mix altered point estimates with the retained EIF variance); scalars `n_units`, `cohort_fractions`, and the POST-OVERALL `df_survey` snapshot (captured after the overall inference and before the ES/group gates: a replicate-variance call that drops replicates can lower the working df - never raise it, and a call with fewer than two valid replicates leaves it unchanged - and every fit-time aggregation seeds from the post-overall value, so recompute replays the exact seed). The data-minimization guarantee is scoped to unit identifiers - no unit-label container is retained. (b) `balance_e` uses the ANCHOR-HORIZON rule (keep cohorts with a finite effect at the anchor horizon, then retain all their horizons) - the same rule SHAPE CallawaySantAnna uses, with one keying-granularity difference (EDiD anchors on the `int(t - g)` bucket, CS on raw `t - g` - identical on integer-period panels; see the truncation Note below), divergent from ImputationDiD/TwoStageDiD's balanced-window rule; an anchor no cohort reaches warns and yields a legal zero-row container. (c) BOOTSTRAP fits: 'simple' (and 'total') RELAY the stored overall row verbatim (percentile se/p/CI beside the finite safe_inference t) with a NaN df column and never re-warn, while the RECOMPUTE levels (ES/group, balance_e included) REPLAY the fit-time multiplier bootstrap from the kit's `BootstrapReplaySpec` (the fit-captured RNG state + run params BY VALUE - seed=None fits replay; post-fit `set_params`/attribute mutation cannot alter it; pickles carry it): se/CI/t match a fit-time aggregation to BLAS reassociation (~1 ULP, `assert_allclose` - never bit-identity), the percentile p-value is a count statistic (compared at 2/n_bootstrap), and the replay publishes no analytical provenance (percentile overrides via the shared `bootstrap_utils` appliers; group rows' `df_used` cleared exactly as at fit time; EDiD has no sup-t cband). The spec stamps the weight backend at capture ('rust'/'numpy', or 'portable' for backend-independent branches - stratified survey generation, census-FPC zero weights, the single-PSU degenerate early return); a replay under a different backend fails closed naming both, and legacy pickles without the spec fail closed with a refit message. Replays RE-EMIT the fit-time bootstrap warnings for the replayed configuration (low n_bootstrap, single-PSU, empty balance_e anchor, non-finite-draw RuntimeWarnings); the relay levels stay silent. Per-call cost O(n_bootstrap x n_units x n_gt), no memoization. The M-027 rationale - no level publishes analytical-provenance fields beside percentile inference - is honored by the percentile overrides and NaN df channels. (d) CONTAINER ADMISSION into `compute_honest_did`/`compute_pretrends_power` is REJECTED BY DESIGN (both terminal TypeErrors state it): the primary ground is the absent joint event-study covariance (container `vcov=None`; the PER-ROW df column now threads the post-overall `df_survey` snapshot via the results-level `event_study_df` channel on analytical survey fits - M-092 completion; None on non-survey/bootstrapped/no-surface fits and for the replicate-undefined 0 sentinel - beside the scalar `df_survey` channel; see the CS post-fit Note's two-channel contract). Reference semantics are regime-dependent: under `pt_assumption="all"` there is NO reference row (universal first-period baseline; e=-1 is a genuine estimate); under `"post"` the per-cohort baseline cell is materialized as a mechanical zero anchor at `e = -1 - anticipation` whenever it is not the panel's first period, and the MEMBERSHIP-GATED `reference_period` property (the SunAbraham rule - never synthesized when the anchor cell was not estimated) marks it `is_reference` in the container and corrects `plot_event_study`'s inferred reference (previously the `-1` fallback) on PT-Post `anticipation>0` fits. (e) 'simple' relay conventions: `target="att"`, `n = n_treated_units + n_control_units` with `n_kind="units"` (DISJOINT by construction - `last_cohort` trimming reassigns before the counts, so a true total exists, unlike StackedDiD's overlapping sets), `df` = the post-overall snapshot (provenance-exact where `survey_metadata.df_survey` can diverge in the degenerate replicate state); 'group' relay: `n_kind="cells"`, `weight=None` (equal within-cohort weights, no cross-cohort mass), per-row `df_used` array captured at each row's `safe_inference` call (exact by construction; a stated divergence from CS's conservative-min scalar broadcast); 'event_study' rides the shared `_from_relative_dict` builder via a carrier whose `survey_metadata` copy carries the snapshot `df_survey` and whose `event_study_df` threads the same snapshot into the per-row df column (cleared on bootstrap replays and for the 0 sentinel). (f) `aggregate('total')` (3.10): the estimator-owned total incremental outcome - an exact relay `C x overall` CONDITIONAL on the realized aggregation mass, with `C = sum(n_treated)` over the kept post-anticipation FINITE-effect cells of the kit's deep-copied `group_time_effects` snapshot (an exact integer sum; NEVER the routinely-non-integral `n_units x sum(cohort_fractions)` float product). Unweighted fits only: ANY declared `survey_design=` fails closed via the kit's `unit_level_weights`/`resolved_survey_unit` markers (weight-type-agnostic - unweighted psu-only and analytic fweight designs, whose resolved weights stay RAW, gate identically; EDiD never synthesizes an internal design, so the markers are exact declaration provenance and post-fit mutation of the public `survey_metadata` cannot bypass them). No keepers -> NaN mass -> all-NaN row (no re-warn); with finite `C` the relay is verbatim (inherited NaNs pass through; att/n never blanked). Bootstrap fits relay with a NaN df column (M-027); df carrier = the post-overall `df_survey` snapshot; container: single `target='total'` row, `n_kind='obs'`, the per-level n-semantics note in the CS total Note applies. MMM: the container is admitted with NO scale (see the MMM section); the survey/RC totals remainder and its att*dC variance term are the DEFERRED row. - **Note (fractional-period truncation bucketing):** the event-study equation defines `ES(e)` at an exact relative time, but the implementation buckets horizons by `int(t - g)` - truncation TOWARD ZERO - on the analytical aggregator, the bootstrap ES prep (all three keying sites, the `balance_e` anchor filter included; aligned 2026-08), and `hausman_pretest`'s internal aggregation. On integer-period panels `int()` is the identity and nothing below applies. On fractional-period panels (accepted by `fit()` without an integrality check): (i) bucket 0 is DOUBLE-WIDTH, spanning `(-1, 1)`, so the pre-treatment horizon e=-0.5 pools into the post-treatment e=0 bucket; e=1.0/1.5 pool into bucket 1 and e=-1.5/-1.0 into bucket -1; (ii) under `pt_assumption="post"` the bucket at `-1 - anticipation` pools genuine estimated fractional pre-treatment horizons (e.g. raw e=-1.5) with the mechanical zero anchor, and the container's reference normalization then publishes the WHOLE pooled row as `att=0.0` with NaN inference (`is_reference=True`) - genuine fractional-horizon estimates are subsumed into the reference row (the fit-time `event_study_effects` dict keeps the pooled effect + percentile inference unrewritten; the rewrite is container-only); (iii) WEIGHTING is CELL-MASS within the bucket - the aggregator appends one `(effect, pi_g)` term per CELL and normalizes, so a cohort contributing k cells to a bucket carries k*pi_g mass, whereas the exact-relative-time equation has one term per cohort - while `n_groups` counts DISTINCT cohorts in the bucket (identity with the cell count on integer panels). Every aggregation that truncation-buckets a fractional horizon emits a UserWarning naming this Note. - **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. @@ -3360,13 +3360,10 @@ the finite-dimensional `p_0` is handled by the variance correction below. scale-invariance tests. Df conventions: design df = QR rank of the analysis-weight matrix − 1; per-cell and overall inference use `min(df_survey, n_valid − 1)` capping (`n_valid` equals R in practice, - so the cap is defensive). The overall MIN-CAP deliberately diverges - from CS's replace convention (`df_survey = overall_effective_df`), - which can RAISE df above the design df — anti-conservative; the CS-side - flip, along with the inherited replace-style event-study/group - aggregation sites in shared code (latent — they fire only when - `n_valid < R`) and the staggered-DDD engine twins, is tracked in the - TODO.md replicate-df min-cap row. `df_survey is None` (rank ≤ 1) → NaN + so the cap is defensive). This is the library-wide replicate-df rule + (Survey Data Support, replicate-df Note): the shared overall / + event-study / group aggregation code DMLDiD inherits from + CallawaySantAnna applies the same cap. `df_survey is None` (rank ≤ 1) → NaN inference (df=0 sentinel local to `safe_inference`; `survey_metadata.df_survey` keeps `None`). PER-CELL replicate SEs use the same IF-reweighting convention as CallawaySantAnna's replicate lane @@ -8015,8 +8012,39 @@ variance from the distribution of replicate estimates. (e.g., `1/R` for BRR, `(R-1)/R` for JK1) uses the original design's `R`, not the valid count — matching R's `survey` package convention where the design structure is fixed and dropped replicates contribute zero to the - sum without changing the scale. Survey df uses `n_valid - 1` for - t-based inference. + sum without changing the scale. Dropped replicates cap the inference df + (next Note). +- **Note:** Replicate inference df. The design df is the QR rank of the + analysis-weight matrix minus 1 (R's `survey::degf()`), undefined when the + rank is <= 1. A dropped replicate (`n_valid < R`: an all-zero replicate + column, or a failed refit / solve) CAPS that df at + `min(df_survey, n_valid - 1)`; it never REPLACES it with `n_valid - 1` + (helpers `survey.cap_replicate_df` and `survey.reduced_replicate_df`). + Consequences, all estimators with replicate support: + - The df is never above the design df. On a rank-deficient replicate + matrix `n_valid - 1` exceeds the design df (15 usable columns of rank 5: + design df 4, `n_valid - 1 = 14`), so replacing would be anti-conservative. + - An undefined design df gives NaN inference (t-stat, p-value, CI) with the + SE still reported and `survey_metadata.df_survey` left `None`; it is never + a `t(n_valid - 1)` or normal reference. `EventStudyResults.df_survey` + carries the `0.0` replicate-undefined sentinel in that case. + - Refit / OLS paths (DifferenceInDifferences, TwoWayFixedEffects incl. + event-study mode, SunAbraham, StackedDiD, ImputationDiD, TwoStageDiD, + `LinearRegression`): one joint replicate vcov prices every statistic, so + `n_valid` is shared and failed refits can lower the df below the design + df; `survey_metadata.df_survey` (and `LinearRegression.survey_df_`) + report the capped value. + - Influence-function paths (CallawaySantAnna, staggered and 2x2x2 + TripleDifference, EfficientDiD, ContinuousDiD, DMLDiD): for a finite + influence function a replicate column is valid exactly when it has a + positive weight, and the QR rank cannot exceed the number of nonzero + columns, so `df_survey <= n_valid - 1` always and the cap never binds - + the inference df is the design df. A statistic whose influence function + is non-finite has fewer than two valid replicates, a NaN SE and NaN + inference at any df; it does not change the df of any other statistic of + the fit. Exception: ChaisemartinDHaultfoeuille takes one global minimum + over all its replicate-variance sites, so a late site with fewer than two + valid replicates turns every surface's inference NaN (fail-closed). - **Note:** Replicate-weight support matrix (13 of 20 public estimators): - **Supported**: CallawaySantAnna (reg/ipw/dr with or without covariates, no bootstrap; IF-based replicate variance is covariate-agnostic, PER-CELL @@ -8049,10 +8077,12 @@ variance from the distribution of replicate estimates. - Estimators with replicate support reject replicate + bootstrap (replicate weights provide analytical variance) - **Note:** When invalid replicates are dropped in `compute_replicate_vcov` - (OLS path), `n_valid` is returned and used for `df_survey = n_valid - 1` - in `LinearRegression.fit()`. For IF-based replicate paths, replicates - essentially never fail (weighted sums cannot be singular), so `n_valid` - equals `R` in practice and df propagation is not needed. + (OLS path), `n_valid` is returned and `LinearRegression.fit()` sets + `survey_df_ = min(df_survey, n_valid - 1)` (the replicate-df Note above; + `survey_df_` stays `None` on an undefined design df, and `get_inference` + then warns and returns NaN inference). For IF-based replicate paths, + replicate sums cannot be singular: a column drops only when it is all + zero, and then the cap never binds. ### DEFF Diagnostics (Phase 6) diff --git a/tests/test_aggregate_contract.py b/tests/test_aggregate_contract.py index d2e113ae7..a14af78f0 100644 --- a/tests/test_aggregate_contract.py +++ b/tests/test_aggregate_contract.py @@ -2326,7 +2326,7 @@ def _efficient_survey_panel(seed=5, replicate=False, degenerate=None): degenerate: None | "dropped" (2 all-zero replicate columns -> n_valid = n_replicates - 2) | "undefined" (all but one column all-zero - -> n_valid <= 1 -> working df None, the load-bearing degenerate state). + -> rank 1, undefined design df: the working df is the 0 sentinel). """ import numpy as np @@ -2558,17 +2558,18 @@ def test_replicate_df_contract_healthy_and_dropped(self): assert _assert_analytic_inference_contract(es, alpha=plain.alpha) > 0 def test_replicate_undefined_df_degenerate(self): - # n_valid <= 1: the working df degenerates to None mid-fit. The - # post-overall snapshot carries that state; the container's scalar - # df_survey resolves to the 0.0 replicate-undefined sentinel (the - # shared resolver ladder), NOT the raw survey_metadata value the - # is-not-None guard leaves finite - this arm is the discriminator - # for the carrier's metadata copy. The per-row df column is NaN - # (the 0 sentinel NaNs the inference triple). + # n_valid <= 1 on a rank-1 replicate matrix: the design df is + # undefined, so the working df is the 0 sentinel from the seed on + # (a dropped replicate never rewrites it - not to None, which + # would be a z-reference, and not to n_valid - 1). The + # post-overall snapshot carries that sentinel; the container's + # scalar df_survey resolves to the 0.0 replicate-undefined + # sentinel and the per-row df column is NaN (the sentinel NaNs + # the inference triple). d, rep_cols = _efficient_survey_panel(replicate=True, degenerate="undefined") sd = _efficient_survey_design(rep_cols) plain = _fit_efficient(d, survey_design=sd) - assert plain._aggregation_kit.bookkeeping["df_survey"] is None + assert plain._aggregation_kit.bookkeeping["df_survey"] == 0 es = plain.aggregate("event_study") assert es.df_survey == 0.0 assert np.all(np.isnan(np.asarray(es.df, dtype=float))) diff --git a/tests/test_replicate_df_cap.py b/tests/test_replicate_df_cap.py new file mode 100644 index 000000000..f0c9be17b --- /dev/null +++ b/tests/test_replicate_df_cap.py @@ -0,0 +1,901 @@ +"""Replicate-weight inference df: dropped replicates cap the design df. + +The design df of a replicate-weight design is the QR rank of the analysis-weight +matrix minus 1 (``None`` when rank <= 1). A replicate is dropped by an all-zero +column or by a failed refit / solve. Every estimator used to REPLACE the design +df with ``n_valid - 1`` in that case, which + +- RAISED the df above the design df on a rank-deficient replicate matrix + (15 usable columns of rank 5: t(14) instead of t(4)), and +- produced t-inference on an UNDEFINED design df (rank 1 plus a dropped column: + t(2) instead of NaN inference). + +Invariant under test: on a replicate design the df given to ``safe_inference`` +is never above the design df and never a t- or z-reference when the design df +is undefined; at the influence-function sites a statistic with fewer than two +valid replicates changes no other statistic's df. +""" + +import warnings + +import numpy as np +import pandas as pd +import pytest + +import diff_diff.survey as survey_mod +from diff_diff import ( + CallawaySantAnna, + ContinuousDiD, + DifferenceInDifferences, + EfficientDiD, + ImputationDiD, + StackedDiD, + SunAbraham, + SurveyDesign, + TripleDifference, + TwoStageDiD, + TwoWayFixedEffects, +) +from diff_diff.linalg import LinearRegression +from diff_diff.prep_dgp import generate_staggered_ddd_data +from diff_diff.survey import ( + cap_replicate_df, + compute_replicate_if_variance, + reduced_replicate_df, +) +from diff_diff.utils import safe_inference + +# --------------------------------------------------------------------------- +# Data and replicate designs +# --------------------------------------------------------------------------- + +DESIGN_DF = 4 # rank 5 in every defined fixture below +KINDS_DEFINED = ("healthy", "dropped_full_rank", "dropped_rank_deficient") +# df the pre-fix code reported on each fixture (n_valid - 1). +REPLACED_DF = {"dropped_rank_deficient": 14, "undefined_dropped": 2} + + +def _panel(seed=3, n_units=60, n_periods=6): + """Staggered panel: cohorts {3, 5, never} interleaved across units.""" + rng = np.random.default_rng(seed) + rows = [] + for u in range(n_units): + ft = 3 if u % 3 == 0 else (5 if u % 3 == 1 else 0) + a, w = rng.normal(), rng.uniform(0.5, 2.0) + dose = rng.uniform(0.5, 2.0) if ft else 0.0 + for t in range(1, n_periods + 1): + y = a + 0.2 * t + (1.5 if ft and t >= ft else 0.0) + rng.normal(0, 0.5) + rows.append((u, t, ft, y, w, dose)) + d = pd.DataFrame(rows, columns=["unit", "time", "first_treat", "outcome", "w", "dose"]) + d["treated"] = (d["first_treat"] > 0).astype(int) + d["post"] = (d["time"] >= 3).astype(int) + return d + + +def _ddd_panel(): + d = generate_staggered_ddd_data( + n_units=240, n_periods=4, cohort_periods=[3, 4], never_enabled_frac=0.4, seed=5 + ) + units = np.sort(d["unit"].unique()) + rng = np.random.default_rng(17) + d["w"] = d["unit"].map(pd.Series(rng.uniform(0.5, 2.0, len(units)), index=units)) + return d + + +def _ddd_cross_section(seed=42, n=240): + rng = np.random.default_rng(seed) + d1 = np.repeat([0, 1], n // 2) + d2 = np.tile([0, 1], n // 2) + post = rng.integers(0, 2, n) + y = 1.0 + 0.5 * d1 + 0.3 * d2 + 2.0 * d1 * d2 * post + rng.normal(0, 0.5, n) + return pd.DataFrame( + { + "row": np.arange(n), + "y": y, + "d1": d1, + "d2": d2, + "post": post, + "w": rng.uniform(0.5, 2.0, n), + } + ) + + +def _add_reps(d, kind, key="unit", seed=9): + """Attach replicate columns of a known rank and return ``(data, design)``. + + Base columns are the full-sample weight times a strictly positive + ``key``-constant factor, so no replicate zeroes out a unit, a cohort or the + comparison group: every refit is estimable and the only dropped replicate + is the explicit all-zero column. Random positive columns are full rank. + """ + rng = np.random.default_rng(seed) + ids = np.sort(d[key].unique()) + w = d["w"].to_numpy() + + def base_col(): + return d[key].map(dict(zip(ids, rng.uniform(0.5, 1.5, len(ids))))).to_numpy() * w + + zero = np.zeros(len(d)) + if kind == "healthy": # R = 5, rank 5, n_valid 5 + cols = [base_col() for _ in range(5)] + elif kind == "dropped_full_rank": # R = 6, rank 5, n_valid 5 + cols = [base_col() for _ in range(5)] + [zero] + elif kind == "dropped_rank_deficient": # R = 16, rank 5, n_valid 15 + cols = [b for b in [base_col() for _ in range(5)] for _ in range(3)] + [zero] + elif kind == "undefined_dropped": # R = 4, rank 1, n_valid 3 + b = base_col() + cols = [b, 2.0 * b, 3.0 * b, zero] + elif kind == "full12": # R = 12, rank 12, n_valid 12 + cols = [base_col() for _ in range(12)] + else: # pragma: no cover + raise ValueError(kind) + names = [f"rw{i}" for i in range(len(cols))] + out = pd.concat([d, pd.DataFrame(dict(zip(names, cols)), index=d.index)], axis=1) + # mse=True centers on the full-sample estimate. The undefined fixture needs + # it for a positive variance: its three usable columns are proportional, and + # a refit is scale-invariant, so mean-centering would give exactly 0. + design = SurveyDesign( + weights="w", + replicate_weights=names, + replicate_method="JK1", + mse=(kind == "undefined_dropped"), + ) + return out, design + + +def test_fixture_ranks(): + """The fixtures have the df / dropped-column structure the tests rely on.""" + expected = { + "healthy": (4, 5), + "dropped_full_rank": (4, 6), + "dropped_rank_deficient": (4, 16), + "undefined_dropped": (None, 4), + "full12": (11, 12), + } + for kind, (df, n_rep) in expected.items(): + d, design = _add_reps(_panel(), kind) + resolved = design.resolve(d) + assert resolved.df_survey == df, kind + assert resolved.n_replicates == n_rep, kind + + +# --------------------------------------------------------------------------- +# Statistic extraction +# --------------------------------------------------------------------------- + + +def _scalar(res, label): + return [ + ( + label, + float(res.att), + float(res.se), + float(res.t_stat), + float(res.p_value), + float(res.conf_int[0]), + float(res.conf_int[1]), + ) + ] + + +def _rows(container, label): + """Estimable, non-reference rows of an aggregate container. + + Reference rows carry SE 0 or NaN by construction and are not statistics. + """ + att = np.asarray(container.att, dtype=float) + se = np.asarray(container.se, dtype=float) + ref = np.asarray(getattr(container, "is_reference", np.zeros(len(att), dtype=bool))) + out = [] + for i in range(len(att)): + if ref[i] or not np.isfinite(att[i]) or not np.isfinite(se[i]) or se[i] <= 0: + continue + out.append( + ( + f"{label}[{i}]", + att[i], + se[i], + float(container.t_stat[i]), + float(container.p_value[i]), + float(container.conf_int_lower[i]), + float(container.conf_int_upper[i]), + ) + ) + return out + + +def _row_dfs(container): + """Per-row df provenance of the estimable, non-reference rows.""" + att = np.asarray(container.att, dtype=float) + se = np.asarray(container.se, dtype=float) + ref = np.asarray(getattr(container, "is_reference", np.zeros(len(att), dtype=bool))) + keep = ~ref & np.isfinite(att) & np.isfinite(se) & (se > 0) + return np.asarray(container.df, dtype=float)[keep] + + +class _Out: + """What one adapter reports for one fit.""" + + def __init__(self): + self.stats = [] # (label, effect, se, t, p, ci_lo, ci_hi) + self.meta_df = "absent" # survey_metadata.df_survey, when the result has one + self.container_dfs = [] # EventStudyResults.df_survey scalars + self.row_dfs = [] # per-row df arrays of aggregate containers + + def add_result(self, res, label): + self.stats += _scalar(res, label) + self.meta_df = res.survey_metadata.df_survey + return self + + def add_container(self, container, label): + self.stats += _rows(container, label) + self.row_dfs.append(_row_dfs(container)) + if hasattr(container, "df_survey"): + self.container_dfs.append(container.df_survey) + return self + + +def _quiet(fn): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + return fn() + + +# --------------------------------------------------------------------------- +# Estimator adapters: (data, design) -> _Out +# --------------------------------------------------------------------------- + + +def _staggered_args(d, design): + return (d, "outcome", "unit", "time", "first_treat"), {"survey_design": design} + + +def _fit_cs(d, design): + a, k = _staggered_args(d, design) + res = CallawaySantAnna(estimation_method="reg").fit(*a, **k) + out = _Out().add_result(res, "cs") + out.add_container(res.aggregate("event_study"), "cs.es") + out.add_container(res.aggregate("group"), "cs.group") + return out + + +def _fit_edid(d, design): + a, k = _staggered_args(d, design) + res = EfficientDiD().fit(*a, **k) + out = _Out().add_result(res, "edid") + out.add_container(res.aggregate("event_study"), "edid.es") + out.add_container(res.aggregate("group"), "edid.group") + return out + + +def _fit_continuous(d, design): + res = ContinuousDiD(n_bootstrap=0, num_knots=2).fit( + d, "outcome", "unit", "time", "first_treat", "dose", survey_design=design + ) + out = _Out().add_result(res, "cont.att") + out.stats.append( + ( + "cont.acrt", + float(res.overall_acrt), + float(res.overall_acrt_se), + float(res.overall_acrt_t_stat), + float(res.overall_acrt_p_value), + float(res.overall_acrt_conf_int[0]), + float(res.overall_acrt_conf_int[1]), + ) + ) + out.add_container(res.aggregate("event_study"), "cont.es") + return out + + +def _fit_did_plain(d, design): + res = DifferenceInDifferences().fit( + d, outcome="outcome", treatment="treated", post="post", survey_design=design + ) + return _Out().add_result(res, "did") + + +def _fit_did_absorb(d, design): + res = DifferenceInDifferences().fit( + d, + outcome="outcome", + treatment="treated", + post="post", + absorb=["unit"], + survey_design=design, + ) + return _Out().add_result(res, "did.absorb") + + +def _fit_twfe(d, design): + res = TwoWayFixedEffects().fit( + d, outcome="outcome", treatment="treated", post="post", unit="unit", survey_design=design + ) + return _Out().add_result(res, "twfe") + + +def _fit_twfe_es(spec): + def fit(d, design): + kw = {"unit": "unit"} if spec == "within" else {} + es = TwoWayFixedEffects().fit( + d, + outcome="outcome", + treatment="treated", + time="time", + event_study=True, + spec=spec, + post_periods=[3, 4, 5, 6], + survey_design=design, + **kw, + ) + # EventStudyResults: no survey_metadata, scalar df_survey instead. + return _Out().add_container(es, f"twfe.es.{spec}") + + return fit + + +def _fit_sun_abraham(d, design): + a, k = _staggered_args(d, design) + res = SunAbraham(n_bootstrap=0).fit(*a, **k) + out = _Out().add_result(res, "sa") + for e, row in sorted(res.event_study_effects.items()): + se = row["se"] + if np.isfinite(row["effect"]) and np.isfinite(se) and se > 0: + out.stats.append( + ( + f"sa.es[{e}]", + row["effect"], + se, + row["t_stat"], + row["p_value"], + row["conf_int"][0], + row["conf_int"][1], + ) + ) + return out + + +def _fit_keyword_staggered(cls, label, levels, **est_kw): + def fit(d, design): + res = cls(**est_kw).fit( + d, + outcome="outcome", + unit="unit", + time="time", + first_treat="first_treat", + survey_design=design, + ) + out = _Out().add_result(res, label) + for level in levels: + out.add_container(res.aggregate(level), f"{label}.{level}") + return out + + return fit + + +def _fit_ddd_staggered(d, design): + res = TripleDifference().fit( + d, + outcome="outcome", + unit="unit", + time="period", + first_treat="first_treat", + partition="eligibility", + survey_design=design, + ) + out = _Out().add_result(res, "ddd.staggered") + out.add_container(res.aggregate("event_study"), "ddd.staggered.es") + return out + + +def _fit_ddd_2x2x2(d, design): + res = TripleDifference(estimation_method="reg").fit( + d, outcome="y", group="d1", partition="d2", post="post", survey_design=design + ) + return _Out().add_result(res, "ddd.2x2x2") + + +# name -> (data builder, replicate key, adapter) +ADAPTERS = { + "cs": (_panel, "unit", _fit_cs), + "efficient_did": (_panel, "unit", _fit_edid), + "continuous_did": (_panel, "unit", _fit_continuous), + "did_plain": (_panel, "unit", _fit_did_plain), + "did_absorb": (_panel, "unit", _fit_did_absorb), + "twfe": (_panel, "unit", _fit_twfe), + "twfe_es_within": (_panel, "unit", _fit_twfe_es("within")), + "twfe_es_pooled": (_panel, "unit", _fit_twfe_es("pooled")), + "sun_abraham": (_panel, "unit", _fit_sun_abraham), + "stacked_did": (_panel, "unit", _fit_keyword_staggered(StackedDiD, "stacked", ["event_study"])), + "imputation_did": ( + _panel, + "unit", + _fit_keyword_staggered(ImputationDiD, "imp", ["event_study", "group"], n_bootstrap=0), + ), + "two_stage_did": ( + _panel, + "unit", + _fit_keyword_staggered(TwoStageDiD, "ts", ["event_study", "group"], n_bootstrap=0), + ), + "ddd_staggered": (_ddd_panel, "unit", _fit_ddd_staggered), + "ddd_2x2x2": (_ddd_cross_section, "row", _fit_ddd_2x2x2), +} + +# Which replicate-variance routine prices each adapter's statistics. +IF_PATH = ("cs", "efficient_did", "continuous_did", "ddd_staggered", "ddd_2x2x2") +REFIT_PATH = ( + "did_absorb", + "twfe", + "twfe_es_within", + "sun_abraham", + "stacked_did", + "imputation_did", + "two_stage_did", +) +OLS_PATH = ("did_plain", "twfe_es_pooled") + +_FIT_CACHE = {} + + +def _run(name, kind): + """Fit ``name`` on fixture ``kind`` (cached: each fit is reused across tests).""" + if (name, kind) not in _FIT_CACHE: + build, key, adapter = ADAPTERS[name] + d, design = _add_reps(build(), kind, key=key) + _FIT_CACHE[(name, kind)] = _quiet(lambda: adapter(d, design)) + return _FIT_CACHE[(name, kind)] + + +def _assert_inference_at_df(out, df): + assert out.stats, "adapter returned no estimable statistics" + for label, effect, se, t, p, lo, hi in out.stats: + exp_t, exp_p, exp_ci = safe_inference(effect, se, alpha=0.05, df=df) + np.testing.assert_allclose(t, exp_t, rtol=1e-10, err_msg=label) + np.testing.assert_allclose(p, exp_p, rtol=1e-8, atol=1e-300, err_msg=label) + np.testing.assert_allclose([lo, hi], exp_ci, rtol=1e-10, err_msg=label) + + +def _assert_df_carriers(out, df): + if out.meta_df != "absent": + assert out.meta_df == df + for value in out.container_dfs: + assert value == float(df) + for arr in out.row_dfs: + assert len(arr) > 0 + np.testing.assert_array_equal(arr, float(df)) + + +# --------------------------------------------------------------------------- +# 1. Estimator matrix on real designs +# --------------------------------------------------------------------------- + + +@pytest.mark.parametrize("name", sorted(ADAPTERS)) +class TestEstimatorMatrix: + @pytest.mark.parametrize("kind", KINDS_DEFINED) + def test_inference_uses_design_df(self, name, kind): + out = _run(name, kind) + _assert_inference_at_df(out, DESIGN_DF) + _assert_df_carriers(out, DESIGN_DF) + + def test_rank_deficient_df_is_not_raised(self, name): + """Guards the matrix against a vacuous pass: t(4) and t(14) differ.""" + out = _run(name, "dropped_rank_deficient") + for label, effect, se, _t, p, _lo, _hi in out.stats: + _, p_replaced, _ = safe_inference( + effect, se, alpha=0.05, df=REPLACED_DF["dropped_rank_deficient"] + ) + assert abs(p - p_replaced) > 1e-12 * max(p, p_replaced), label + assert p > p_replaced, label # t(4) is the heavier tail + + def test_undefined_design_df_gives_nan_inference(self, name): + out = _run(name, "undefined_dropped") + assert out.stats + for label, _effect, se, t, p, lo, hi in out.stats: + # Non-vacuity: the SE is valid, so NaN inference comes from the df. + assert np.isfinite(se) and se > 0, label + assert np.isnan(t) and np.isnan(p) and np.isnan(lo) and np.isnan(hi), label + if out.meta_df != "absent": + assert out.meta_df is None # never 0, never n_valid - 1 + for value in out.container_dfs: + assert value == 0.0 # the replicate-undefined sentinel + for arr in out.row_dfs: + assert np.all(np.isnan(arr)) + + +# --------------------------------------------------------------------------- +# 2. A genuine reduction below the design df is kept +# --------------------------------------------------------------------------- + + +def _report_failed(monkeypatch, fn_name, n_failed=3): + """Make one replicate-variance routine report ``n_failed`` dropped replicates.""" + original = getattr(survey_mod, fn_name) + + def wrapped(*args, **kwargs): + value, n_valid = original(*args, **kwargs) + return value, n_valid - n_failed + + monkeypatch.setattr(survey_mod, fn_name, wrapped) + + +class TestCapBindsBelowDesignDf: + """12 full-rank columns (design df 11), 3 reported failed -> df 8.""" + + @staticmethod + def _fit(name, monkeypatch, fn_name): + build, key, adapter = ADAPTERS[name] + d, design = _add_reps(build(), "full12", key=key) + assert design.resolve(d).df_survey == 11 + _report_failed(monkeypatch, fn_name) + return _quiet(lambda: adapter(d, design)) + + @pytest.mark.parametrize("name", REFIT_PATH) + def test_refit_path(self, name, monkeypatch): + out = self._fit(name, monkeypatch, "compute_replicate_refit_variance") + _assert_inference_at_df(out, 8) + _assert_df_carriers(out, 8) + + @pytest.mark.parametrize("name", OLS_PATH) + def test_ols_path(self, name, monkeypatch): + # did_plain pins the metadata write: inference comes from + # LinearRegression.survey_df_, and metadata must report the same df. + out = self._fit(name, monkeypatch, "compute_replicate_vcov") + _assert_inference_at_df(out, 8) + _assert_df_carriers(out, 8) + + @pytest.mark.parametrize("name", IF_PATH) + def test_if_path(self, name, monkeypatch): + out = self._fit(name, monkeypatch, "compute_replicate_if_variance") + _assert_inference_at_df(out, 8) + _assert_df_carriers(out, 8) + + +# --------------------------------------------------------------------------- +# 3. LinearRegression direct +# --------------------------------------------------------------------------- + + +class TestLinearRegressionDirect: + @staticmethod + def _fit(kind): + d, design = _add_reps(_panel(), kind) + resolved = design.resolve(d) + X = np.column_stack( + [np.ones(len(d)), d["treated"], d["post"], d["treated"] * d["post"]] + ).astype(float) + reg = LinearRegression( + include_intercept=False, + weights=resolved.weights, + weight_type="pweight", + survey_design=resolved, + ) + _quiet(lambda: reg.fit(X, d["outcome"].to_numpy())) + return reg + + @pytest.mark.parametrize("kind", KINDS_DEFINED) + def test_survey_df_is_design_df(self, kind): + reg = self._fit(kind) + assert reg.survey_df_ == DESIGN_DF + inf = reg.get_inference(3) + _, exp_p, exp_ci = safe_inference(inf.coefficient, inf.se, alpha=0.05, df=DESIGN_DF) + np.testing.assert_allclose(inf.p_value, exp_p, rtol=1e-8) + np.testing.assert_allclose(inf.conf_int, exp_ci, rtol=1e-10) + + def test_undefined_design_df_warns_and_nans(self): + reg = self._fit("undefined_dropped") + # None, not 0 and not n_valid - 1: same state as an undefined design + # with no dropped replicate, so the same warning + NaN branch fires. + assert reg.survey_df_ is None + with pytest.warns(UserWarning, match="undefined survey d.f."): + inf = reg.get_inference(3) + assert np.isfinite(inf.se) and inf.se > 0 + assert np.isnan(inf.t_stat) and np.isnan(inf.p_value) + assert np.isnan(inf.conf_int[0]) and np.isnan(inf.conf_int[1]) + + def test_failed_solves_lower_the_df(self, monkeypatch): + d, design = _add_reps(_panel(), "full12") + resolved = design.resolve(d) + _report_failed(monkeypatch, "compute_replicate_vcov") + X = np.column_stack([np.ones(len(d)), d["treated"], d["post"]]).astype(float) + reg = LinearRegression( + include_intercept=False, + weights=resolved.weights, + weight_type="pweight", + survey_design=resolved, + ) + _quiet(lambda: reg.fit(X, d["outcome"].to_numpy())) + assert reg.survey_df_ == 8 + + +# --------------------------------------------------------------------------- +# 4. Per-statistic isolation (influence-function sites) +# --------------------------------------------------------------------------- + + +def _spy_one_call(monkeypatch, call_index): + """Make exactly one ``compute_replicate_if_variance`` call fully degenerate.""" + original = survey_mod.compute_replicate_if_variance + state = {"n": 0} + + def spy(psi, resolved): + i = state["n"] + state["n"] += 1 + if i == call_index: + return float("nan"), 0 + return original(psi, resolved) + + monkeypatch.setattr(survey_mod, "compute_replicate_if_variance", spy) + return state + + +def _assert_only_one_statistic_changed(clean, spied): + """Every statistic but one is identical; the odd one out has NaN inference.""" + assert len(clean) == len(spied) + changed = 0 + for c, s in zip(clean, spied): + if np.isnan(s[2]): # se + changed += 1 + assert np.isnan(s[3]) and np.isnan(s[4]) and np.isnan(s[5]) and np.isnan(s[6]) + continue + np.testing.assert_allclose(s[1:], c[1:], rtol=1e-12, err_msg=c[0]) + assert changed == 1 + + +def _all_rows(container, label): + """Every non-reference row, including ones whose SE went NaN.""" + att = np.asarray(container.att, dtype=float) + ref = np.asarray(getattr(container, "is_reference", np.zeros(len(att), dtype=bool))) + return [ + ( + f"{label}[{i}]", + att[i], + float(container.se[i]), + float(container.t_stat[i]), + float(container.p_value[i]), + float(container.conf_int_lower[i]), + float(container.conf_int_upper[i]), + ) + for i in range(len(att)) + if not ref[i] and np.isfinite(att[i]) + ] + + +class TestPerStatisticIsolation: + """A statistic with < 2 valid replicates must not change another's df. + + Each arm marked "discriminating" fails on the pre-fix tree. + """ + + def test_efficient_did_per_cell(self, monkeypatch): + # Discriminating: the pre-fix sticky df became None, so every later + # cell (and the overall ATT) silently switched to a z-reference. + d, design = _add_reps(_panel(), "healthy") + a, k = _staggered_args(d, design) + + def cells(res): + out = [] + for gt, row in sorted(res.group_time_effects.items()): + out.append( + ( + str(gt), + row["effect"], + row["se"], + row["t_stat"], + row["p_value"], + row["conf_int"][0], + row["conf_int"][1], + ) + ) + return out + + clean = _quiet(lambda: EfficientDiD().fit(*a, **k)) + _spy_one_call(monkeypatch, 0) + spied = _quiet(lambda: EfficientDiD().fit(*a, **k)) + _assert_only_one_statistic_changed(cells(clean), cells(spied)) + np.testing.assert_allclose(spied.p_value, clean.p_value, rtol=1e-12) + np.testing.assert_allclose(spied.conf_int, clean.conf_int, rtol=1e-12) + assert spied.survey_metadata.df_survey == DESIGN_DF + + def test_efficient_did_wif_aggregate(self, monkeypatch): + # Regression guard only: the WIF sites discarded n_valid before the + # fix as well, so this arm passes on both trees. + d, design = _add_reps(_panel(), "healthy") + a, k = _staggered_args(d, design) + res = _quiet(lambda: EfficientDiD().fit(*a, **k)) + clean = _all_rows(_quiet(lambda: res.aggregate("event_study")), "es") + _spy_one_call(monkeypatch, 0) + spied = _all_rows(_quiet(lambda: res.aggregate("event_study")), "es") + _assert_only_one_statistic_changed(clean, spied) + + def test_continuous_did(self, monkeypatch): + # Discriminating: the pre-fix worst-case count fell to 0, which turned + # EVERY statistic's inference NaN. + d, design = _add_reps(_panel(), "healthy") + + def fit(): + return _quiet( + lambda: ContinuousDiD(n_bootstrap=0, num_knots=2).fit( + d, "outcome", "unit", "time", "first_treat", "dose", survey_design=design + ) + ) + + clean = fit() + _spy_one_call(monkeypatch, 1) # the overall ACRT statistic + spied = fit() + assert np.isnan(spied.overall_acrt_se) and np.isnan(spied.overall_acrt_p_value) + np.testing.assert_allclose(spied.se, clean.se, rtol=1e-12) + np.testing.assert_allclose(spied.p_value, clean.p_value, rtol=1e-12) + np.testing.assert_allclose(spied.conf_int, clean.conf_int, rtol=1e-12) + assert spied.survey_metadata.df_survey == DESIGN_DF + + @pytest.mark.parametrize("level", ["event_study", "group"]) + def test_callaway_santanna_aggregates(self, level, monkeypatch): + # Discriminating: the shared _se_from_psi returned the 0 sentinel for + # the degenerate statistic, and the relay's min() over rows then gave + # EVERY horizon / group NaN inference. + d, design = _add_reps(_panel(), "healthy") + a, k = _staggered_args(d, design) + res = _quiet(lambda: CallawaySantAnna(estimation_method="reg").fit(*a, **k)) + clean = _all_rows(_quiet(lambda: res.aggregate(level)), level) + _spy_one_call(monkeypatch, 0) + spied = _all_rows(_quiet(lambda: res.aggregate(level)), level) + _assert_only_one_statistic_changed(clean, spied) + + def test_callaway_santanna_overall_keeps_metadata(self, monkeypatch): + # Discriminating: a degenerate overall statistic used to write the 0 + # sentinel into survey_metadata.df_survey. + d, design = _add_reps(_panel(), "healthy") + a, k = _staggered_args(d, design) + original = survey_mod.compute_replicate_if_variance + + def degenerate(psi, resolved): + _var, _n = original(psi, resolved) + return float("nan"), 0 + + monkeypatch.setattr(survey_mod, "compute_replicate_if_variance", degenerate) + res = _quiet(lambda: CallawaySantAnna(estimation_method="reg").fit(*a, **k)) + assert np.isnan(res.se) and np.isnan(res.p_value) + assert res.survey_metadata.df_survey == DESIGN_DF + + +class TestNoRepeatedDesignRank: + """Post-fit aggregation must not recompute the design rank per statistic. + + ``ResolvedSurveyDesign.df_survey`` runs a pivoted QR on the n x R + replicate matrix on every access, and an all-zero replicate column makes + ``n_valid < R`` for every horizon and group. + """ + + @staticmethod + def _count_df_survey(monkeypatch): + calls = {"n": 0} + original = survey_mod.ResolvedSurveyDesign.df_survey + + def counted(self): + calls["n"] += 1 + return original.fget(self) + + monkeypatch.setattr(survey_mod.ResolvedSurveyDesign, "df_survey", property(counted)) + return calls + + @pytest.mark.parametrize("level", ["event_study", "group"]) + def test_callaway_santanna(self, level, monkeypatch): + d, design = _add_reps(_panel(), "dropped_rank_deficient") + a, k = _staggered_args(d, design) + res = _quiet(lambda: CallawaySantAnna(estimation_method="reg").fit(*a, **k)) + calls = self._count_df_survey(monkeypatch) + agg = _quiet(lambda: res.aggregate(level)) + assert calls["n"] == 0 + np.testing.assert_array_equal(_row_dfs(agg), float(DESIGN_DF)) + + @pytest.mark.parametrize("level", ["event_study", "group"]) + def test_efficient_did(self, level, monkeypatch): + d, design = _add_reps(_panel(), "dropped_rank_deficient") + a, k = _staggered_args(d, design) + res = _quiet(lambda: EfficientDiD().fit(*a, **k)) + calls = self._count_df_survey(monkeypatch) + agg = _quiet(lambda: res.aggregate(level)) + assert calls["n"] == 0 + np.testing.assert_array_equal(_row_dfs(agg), float(DESIGN_DF)) + + +# --------------------------------------------------------------------------- +# 5. EfficientDiD kit df on an undefined design +# --------------------------------------------------------------------------- + + +class TestEfficientDiDKit: + def test_undefined_design_kit_df_is_sentinel(self): + d, design = _add_reps(_panel(), "undefined_dropped") + a, k = _staggered_args(d, design) + res = _quiet(lambda: EfficientDiD().fit(*a, **k)) + # The working df stays the seeded 0 sentinel; it is never None (a + # z-reference) and never n_valid - 1. + assert res._aggregation_kit.bookkeeping["df_survey"] == 0 + assert res.survey_metadata.df_survey is None + es = _quiet(lambda: res.aggregate("event_study")) + assert es.df_survey == 0.0 + assert np.all(np.isnan(np.asarray(es.p_value, dtype=float))) + grp = _quiet(lambda: res.aggregate("group")) + assert np.all(np.isnan(np.asarray(grp.df, dtype=float))) + assert np.all(np.isnan(np.asarray(grp.p_value, dtype=float))) + + +# --------------------------------------------------------------------------- +# 6. Influence-function path: the design df never exceeds n_valid - 1 +# --------------------------------------------------------------------------- + + +class TestNeverBindsProperty: + """QR rank <= number of nonzero replicate columns == n_valid (finite psi). + + This is why the influence-function sites that do not consume ``n_valid`` + cannot report a df above what a cap would give. + """ + + @pytest.mark.parametrize("combined", [True, False]) + @pytest.mark.parametrize("seed", range(12)) + def test_design_df_at_most_n_valid_minus_one(self, seed, combined): + rng = np.random.default_rng(seed) + n = 40 + n_base = int(rng.integers(1, 6)) + base = rng.uniform(0.2, 2.0, (n, n_base)) + picks = rng.integers(0, n_base, int(rng.integers(2, 10))) + cols = [base[:, j] * rng.uniform(0.5, 2.0) for j in picks] + cols += [np.zeros(n) for _ in range(int(rng.integers(0, 3)))] + order = rng.permutation(len(cols)) + names = [f"r{i}" for i in range(len(cols))] + d = pd.DataFrame({"w": rng.uniform(0.5, 2.0, n)}) + for name, j in zip(names, order): + d[name] = cols[j] + resolved = SurveyDesign( + weights="w", + replicate_weights=names, + replicate_method="JK1", + combined_weights=combined, + ).resolve(d) + _var, n_valid = compute_replicate_if_variance(rng.normal(size=n), resolved) + assert n_valid == sum(1 for c in cols if np.any(c > 0)) + df = resolved.df_survey + assert df is None or df <= n_valid - 1 + if df is not None and n_valid >= 2: + assert reduced_replicate_df(df, n_valid) is None + assert cap_replicate_df(df, n_valid) == df + + +# --------------------------------------------------------------------------- +# 7. Helper tables +# --------------------------------------------------------------------------- + + +class TestReducedReplicateDf: + @pytest.mark.parametrize( + "base_df, n_valid, expected", + [ + (None, 7, None), # undefined design df stays undefined + (0, 7, None), # already the sentinel + (19, 0, None), # no variance for this statistic + (19, 1, None), + (19, 20, None), # nothing dropped + (19, 21, None), # never raised + (4, 15, None), # rank-deficient: design df is the ceiling + (19, 8, 7), # strict reduction + (4, 5, None), # equal: no override + (4, 4, 3), + (11.0, 9, 8), # float design df + ], + ) + def test_table(self, base_df, n_valid, expected): + got = reduced_replicate_df(base_df, n_valid) + assert got == expected + assert expected is None or isinstance(got, int) + + @pytest.mark.parametrize("base_df", [None, 0, 1, 4, 19]) + @pytest.mark.parametrize("n_valid", [0, 1, 2, 5, 20, 40]) + def test_consistent_with_cap(self, base_df, n_valid): + """An override, when given, is exactly the cap; and it only lowers.""" + reduced = reduced_replicate_df(base_df, n_valid) + if reduced is not None: + assert reduced == cap_replicate_df(base_df, n_valid) + assert 0 < reduced < base_df diff --git a/tests/test_survey_dml.py b/tests/test_survey_dml.py index d41f6d8cc..cde376a96 100644 --- a/tests/test_survey_dml.py +++ b/tests/test_survey_dml.py @@ -1078,9 +1078,9 @@ def reduce_n_valid(psi, resolved_arg): def test_overall_df_caps_never_replaces(self, panel_replicate_df, monkeypatch): # The CAP-vs-REPLACE discriminator: a rank-deficient-but-usable # design (duplicated replicate columns -> QR rank 5, df_survey = 4) - # plus a spy n_valid with n_valid - 1 = 6 > 4. CS's replace - # convention would report df = 6; DMLDiD's min-cap must keep 4 - # (deliberate documented divergence; REGISTRY DMLDiD Note). + # plus a spy n_valid with n_valid - 1 = 6 > 4. A replace rule + # would report df = 6; the library-wide cap must keep 4 + # (REGISTRY Survey Data Support, replicate-df Note). from scipy import stats as _stats from diff_diff import survey as _survey_mod @@ -1186,15 +1186,12 @@ def test_aggregations_finite_es_vcov_none_total_closed(self, panel_replicate): with pytest.raises(NotImplementedError): panel_replicate.aggregate("total") - def test_es_df_pins_inherited_replace_convention(self, panel_replicate_df, monkeypatch): - # The SHARED event-study aggregation path REPLACES the design df - # with min(non_none effective dfs) (staggered_aggregation.py) — - # the inherited CS convention, NOT the fit-level min-cap. To - # discriminate, the design must be rank-deficient (df_survey = 4) - # with spy n_valid - 1 = 6 > 4: replace reports 6, a cap would - # report 4. Pinned at 6 so the follow-up flip to min-cap (TODO.md - # replicate-df min-cap row: every replace-style relay site) is detectable; - # latent in practice (n_valid == R on well-formed designs). + def test_es_df_caps_never_replaces(self, panel_replicate_df, monkeypatch): + # The SHARED event-study aggregation path (staggered_aggregation.py + # _se_from_psi + the min over horizons) CAPS the design df: a + # dropped replicate can only lower it. To discriminate, the design + # must be rank-deficient (df_survey = 4) with spy n_valid - 1 = 6 + # > 4: the former replace rule reported 6, the cap keeps 4. from diff_diff import survey as _survey_mod df, rep_cols = panel_replicate_df @@ -1211,14 +1208,14 @@ def test_es_df_pins_inherited_replace_convention(self, panel_replicate_df, monke def reduce_n_valid(psi, resolved_arg): var, _n_valid = original(psi, resolved_arg) - return var, 7 # < R = 8 -> effective df 6 at the shared site + return var, 7 # < R = 8; n_valid - 1 = 6 exceeds the design df monkeypatch.setattr(_survey_mod, "compute_replicate_if_variance", reduce_n_valid) es = res.aggregate("event_study") df_vals = np.asarray(es.df, dtype=float) finite = df_vals[np.isfinite(df_vals)] assert finite.size > 0 - assert np.all(finite == 6.0) # inherited replace; a min-cap would give 4 + assert np.all(finite == 4.0) # the design df is the ceiling def test_replicate_fit_keeps_stratified_folds(self, panel_replicate): # Replicate designs have psu None by mutual exclusion -> the