Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 |
Expand Down
53 changes: 53 additions & 0 deletions changelog.d/20261122-replicate-df-min-cap.md
Original file line number Diff line number Diff line change
@@ -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).
17 changes: 11 additions & 6 deletions diff_diff/chaisemartin_dhaultfoeuille.py
Original file line number Diff line number Diff line change
Expand Up @@ -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] = []
Expand Down Expand Up @@ -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
Expand Down
20 changes: 15 additions & 5 deletions diff_diff/continuous_did.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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

Expand Down
12 changes: 11 additions & 1 deletion diff_diff/continuous_did_aggregation.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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())
Expand All @@ -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
Expand Down
35 changes: 14 additions & 21 deletions diff_diff/dml_did.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
)
Expand Down
Loading
Loading