"""P26, as preregistered in prereg/P26.md (bundle 836db4f4…f8413d). Run: ~/.venvs/ots/bin/python analysis/P26.py Writes results/P26.json and results/P26.md.""" import json, os, zipfile, io import numpy as np, pandas as pd, statsmodels.api as sm ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ZIP = os.path.join(ROOT, "data/restricted/ess/ESS1-11_FI-NO-SE_datafile-subset_2026-10-02.zip") SESOI = 0.10 COLS = ["cntry", "essround", "idno", "ppltrst", "rlgdgr", "yrbrn", "agea", "anweight", "pspwght", "inwyys", "inwyr", "psu", "mode"] def load(): with zipfile.ZipFile(ZIP) as z: with z.open("Datafile-subset.dta") as f: it = pd.read_stata(io.BytesIO(f.read()), convert_categoricals=False, columns=None, iterator=True) cols = [c for c in COLS if c in it.variable_labels()] df = it.read(columns=cols) for c in COLS: if c not in df.columns: df[c] = np.nan return df def exclusions(df, weight_fallback=False): if weight_fallback: # sensitivity (deviation D2): pspwght where anweight is missing; equivalent after within-round rescaling df = df.assign(anweight=df.anweight.fillna(df.pspwght)) steps = [] def step(name, mask): nonlocal df before = df.groupby("cntry").size(); df = df[mask(df)]; after = df.groupby("cntry").size() steps.append({"step": name, **{c: int(before.get(c, 0) - after.get(c, 0)) for c in ("FI", "NO", "SE")}}) steps.append({"step": "start", **df.groupby("cntry").size().reindex(["FI", "NO", "SE"]).fillna(0).astype(int).to_dict()}) step("country FI/NO/SE and round 1-11", lambda d: d.cntry.isin(["FI", "NO", "SE"]) & d.essround.between(1, 11)) step("agea 18-90", lambda d: d.agea.between(18, 90)) step("yrbrn 1915-2005", lambda d: d.yrbrn.between(1915, 2005)) step("ppltrst valid 0-10", lambda d: d.ppltrst.between(0, 10)) step("anweight > 0", lambda d: d.anweight > 0) iy = df.inwyys.where(df.inwyys.between(2000, 2030), df.inwyr.where(df.inwyr.between(2000, 2030))) df = df.assign(iy=iy) step("yrbrn/agea inconsistent with interview year by > 2", lambda d: ~((d.iy.notna()) & ((d.iy - d.yrbrn - d.agea).abs() > 2))) steps.append({"step": "analysed", **df.groupby("cntry").size().reindex(["FI", "NO", "SE"]).fillna(0).astype(int).to_dict()}) return df, steps def dp_period(rounds, free=()): """Deaton-Paxson: period effects over the rounds in S (all rounds except `free`) sum to zero and are orthogonal to a linear trend in round number. Rounds in `free` (SE round 10, the self-completion file) get their own unconstrained dummy elsewhere, so here all their dp_ columns are zero.""" S = sorted(r for r in rounds.unique() if r not in free); r1, r2 = S[0], S[1] X = {} for r in S[2:]: a = (r - r1) / (r2 - r1); b = 1 - a X[f"dp_{int(r)}"] = (rounds == r).astype(float) - a * (rounds == r2).astype(float) - b * (rounds == r1).astype(float) return pd.DataFrame(X, index=rounds.index) def age_dummies(a): bins = [18, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 91] lab = pd.cut(a, bins, right=False, labels=[f"age{b}" for b in bins[:-1]]) return pd.get_dummies(lab, drop_first=True, dtype=float) ROUND_YEAR = {1: 2002, 2: 2004, 3: 2006, 4: 2008, 5: 2010, 6: 2012, 7: 2014, 8: 2016, 9: 2018, 10: 2021, 11: 2023} # ESS round designation years def design(d, age="dummies", cohort="linear", reading="literal", video=False): """reading: 'literal' = the preregistration as written (Deaton-Paxson over all rounds; for SE also a round-10 self-completion dummy); 'd1' = DP over SE's other ten rounds with a free round-10 level (the reading first used, now a sensitivity); 'free' = unconstrained round dummies (identified only by the age-bin functional form; fragile).""" X = [pd.Series(1.0, index=d.index, name="const")] if cohort == "linear": X.append(((d.yrbrn - 1960) / 10).rename("cohort_per_decade")) else: cb = pd.cut(d.yrbrn, list(range(1915, 2006, 5)) + [2006], right=False) X.append(pd.get_dummies(cb, prefix="coh", drop_first=True, dtype=float)) if age == "dummies": X.append(age_dummies(d.agea)) elif age == "dummies10": X.append(pd.get_dummies(pd.cut(d.agea, [18, 30, 40, 50, 60, 70, 80, 91], right=False), prefix="a10", drop_first=True, dtype=float)) else: a = (d.agea - 50) / 10; X += [a.rename("age"), (a ** 2).rename("age2")] se = d.cntry.iloc[0] == "SE" if reading == "free": X.append(pd.get_dummies(d.essround.astype(int), prefix="round", drop_first=True, dtype=float)) else: X.append(dp_period(d.essround, free=(10,) if (se and reading == "d1") else ())) if se: X.append(((d.essround == 10).astype(float)).rename("se_round10_selfcompletion")) if video: X.append(((d["mode"] == 2).astype(float)).rename("video_interview")) X = pd.concat(X, axis=1) return X.loc[:, X.std() > 0].assign(const=1.0) def fit(d, y, age="dummies", cohort="linear", cluster=False, reading="literal", pi=0.0, video=False): """pi: an assumed true linear period trend in y (points per decade), removed from y before the constrained model is fitted.""" d = d[d[y].notna()] w = d.anweight / d.groupby("essround").anweight.transform("mean") t = d.essround.map(ROUND_YEAR) yv = d[y] - pi * (t - t.mean()) / 10 X = design(d, age, cohort, reading, video) m = sm.WLS(yv, X, weights=w) if cluster: # psu within country-round where present (rounds 9-11 here); each respondent its own cluster elsewhere g = np.where(d.psu.notna(), d.essround.astype(int) * 10**9 + d.psu.fillna(0).astype("int64"), -(np.arange(len(d)) + 1)) r = m.fit(cov_type="cluster", cov_kwds={"groups": pd.factorize(g)[0]}) else: r = m.fit(cov_type="HC1") r.cond = float(np.linalg.cond(X.values)) return r, len(d) def slope(r): b = r.params["cohort_per_decade"]; lo, hi = r.conf_int().loc["cohort_per_decade"] return {"b": round(float(b), 4), "L": round(float(lo), 4), "U": round(float(hi), 4), "se": round(float(r.bse["cohort_per_decade"]), 4)} def classify(s): if s["L"] > -SESOI: return "confirms P26" if s["U"] < 0 and s["b"] < -SESOI: return "refutes P26" return "inconclusive" def main(): raw = load() df, steps = exclusions(raw) out = {"exclusions": steps, "countries": {}, "sensitivity": {}} for c in ("FI", "NO", "SE"): d = df[df.cntry == c].copy() prim, n = fit(d, "ppltrst"); r1, _ = fit(d, "ppltrst", age="quadratic") r3, _ = fit(d, "ppltrst", cluster=True); r2, _ = fit(d, "ppltrst", cohort="dummies") prem, npr = fit(d, "rlgdgr") P, R1, R3, PR = slope(prim), slope(r1), slope(r3), slope(prem) coh = {k: [round(float(r2.params[k]), 3), round(float(r2.conf_int().loc[k][0]), 3), round(float(r2.conf_int().loc[k][1]), 3)] for k in r2.params.index if k.startswith("coh_")} out["countries"][c] = {"N": n, "primary": P, "R1_age_quadratic": R1, "R3_cluster_psu": R3, "R2_cohort_dummies": coh, "premise_rlgdgr": {**PR, "N": npr, "holds": PR["U"] < 0}, "class_primary": classify(P), "class_R1": classify(R1), "design_condition_number": round(prim.cond, 1), "rounds": sorted(int(x) for x in d.essround.unique())} sens = {} for name, kw in {"reading_d1_free_SE_round10": {"reading": "d1"}, "free_period_dummies": {"reading": "free"}, "age_10yr_bins": {"age": "dummies10"}, "video_interview_dummy": {"video": True}}.items(): r, _ = fit(d, "ppltrst", **kw); sl = slope(r); sens[name] = {**sl, "class": classify(sl), "condition_number": round(r.cond, 1)} sens["assumed_period_trend_grid"] = {f"{pi:+.2f}": {**slope(fit(d, "ppltrst", pi=pi)[0])} for pi in (-0.20, -0.10, -0.05, 0.0, 0.02, 0.05, 0.10, 0.20)} for k, v in sens["assumed_period_trend_grid"].items(): v["class"] = classify(v) tw = d.groupby("essround").apply(lambda g: np.average(g.ppltrst, weights=g.anweight)) out["countries"][c]["raw_weighted_mean_by_round"] = {int(k): round(float(v), 3) for k, v in tw.items()} out["sensitivity"][c] = sens C = out["countries"] conf = all(C[c]["class_primary"] == "confirms P26" and C[c]["class_R1"] == "confirms P26" for c in C) and sum(C[c]["premise_rlgdgr"]["holds"] for c in C) >= 2 ref_c = [c for c in C if C[c]["class_primary"] == "refutes P26" and C[c]["class_R1"] == "refutes P26" and C[c]["premise_rlgdgr"]["holds"]] out["verdict"] = "confirmed" if conf else ("refuted" if len(ref_c) >= 2 else "inconclusive") out["verdict_meaning"] = {"confirmed": "drawdown argument refuted for this proxy, conditional on the Deaton-Paxson zero-trend assumption", "refuted": "drawdown argument supported for this proxy, conditional on the Deaton-Paxson zero-trend assumption", "inconclusive": "the preregistered thresholds were not met in all three countries"}[out["verdict"]] bs = np.array([C[c]["primary"]["b"] for c in C]); ses = np.array([C[c]["primary"]["se"] for c in C]); w = 1 / ses**2 pb, pse = float(np.sum(w * bs) / w.sum()), float(np.sqrt(1 / w.sum())) out["pooled_inverse_variance"] = {"b": round(pb, 4), "L": round(pb - 1.96 * pse, 4), "U": round(pb + 1.96 * pse, 4), "note": "fixed-effect average of the three country slopes (primary model); reported, not used for the verdict"} # Sensitivity S1 (deviation D2): rounds 2-3 kept, weighted by pspwght where anweight is missing dfs, steps_s = exclusions(raw, weight_fallback=True) out["S1_with_rounds_2_3"] = {"exclusions": steps_s} for c in ("FI", "NO", "SE"): d = dfs[dfs.cntry == c].copy() a, n = fit(d, "ppltrst"); b, _ = fit(d, "ppltrst", age="quadratic"); pr, _ = fit(d, "rlgdgr") out["S1_with_rounds_2_3"][c] = {"N": n, "primary": slope(a), "R1_age_quadratic": slope(b), "premise_rlgdgr": slope(pr), "class_primary": classify(slope(a)), "class_R1": classify(slope(b)), "rounds": sorted(int(x) for x in d.essround.unique())} # cohort profile plot (R2) import matplotlib; matplotlib.use("Agg"); import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(8, 4.5)) for c, mk in zip(C, "osd"): ks = list(C[c]["R2_cohort_dummies"]); xs = [int(k[5:9]) + 2 for k in ks]; v = np.array([C[c]["R2_cohort_dummies"][k] for k in ks]) ax.errorbar(np.array(xs) + {"FI": -0.6, "NO": 0, "SE": 0.6}[c], v[:, 0], yerr=[v[:, 0] - v[:, 1], v[:, 2] - v[:, 0]], fmt=mk + "-", capsize=2, label=c, lw=1) ax.axhline(0, color="grey", lw=0.6); ax.set_xlabel("birth cohort (5-year, midpoint)"); ax.set_ylabel("ppltrst vs 1915-19 cohort (0-10 scale)") ax.set_title("P26 cohort profile (R2), Deaton-Paxson period constraint, 95% CI"); ax.legend(); fig.tight_layout() fig.savefig(os.path.join(ROOT, "results/P26_cohort_profile.png"), dpi=130) out["deviations"] = [ {"id": "D1", "what": "Withdrawn as the primary. The first run applied the Deaton-Paxson constraint to Sweden's other ten rounds with a free round-10 level and called that the only identified reading. That claim was false (the hostile review found the literal reading has full rank, identified through the 5-year age bins). The primary now follows the preregistration literally; the first reading is reported as sensitivity 'reading_d1_free_SE_round10'. The three readings give Sweden different classifications; this is stated next to the verdict.", "why": "Correcting an error found by the hostile review before publication."}, {"id": "D2", "what": "The rule 'positive anweight' drops rounds 2 and 3 entirely: the downloaded file has no anweight in those rounds for any of the three countries. The verdict follows the rule as written; S1 reports the same models with rounds 2 and 3 weighted by pspwght.", "why": "Not foreseen in the preregistration. Within a country-round pweight is constant, so after the preregistered rescaling to mean 1 within country-round pspwght equals anweight (checked: equal to within 2e-7)."}, {"id": "D3", "what": "R3 clusters by psu within country-round where psu is present (rounds 9-11 only) and treats each respondent as its own cluster elsewhere. In rounds 9-11 every psu holds exactly one respondent in all three countries (simple random samples from population registers), so R3 equals the HC1 primary: it is vacuous.", "why": "psu exists only in rounds 9-11 of this file; the preregistration says 'where psu is available'."}, {"id": "D4", "what": "The Deaton-Paxson constraint is orthogonal to round number, not to calendar year; rounds 10 and 11 were fielded about 2021-2023. Calendar-year spacing changes the slopes by under 0.005 (hostile review).", "why": "Implementation choice not stated in the preregistration."}] out["notes"] = ["The interview-year consistency exclusion cannot bite: agea is calculated by ESS from birth year and interview date, and rounds 10-11 carry neither inwyys nor inwyr. Zero exclusions there is uninformative.", "R1 tests the shape of the age profile, not the identifying assumption; the assumption is tested by the period-trend grid and the free-period model.", "Every cohort slope here is conditional on the assumption that there is no underlying linear period trend in trust over 2002-2023. A society-wide drawdown would show as exactly such a trend, so the test cannot see it; the grid shows how each country's classification changes with an assumed trend.", "For Sweden the literal reading (Deaton-Paxson over all rounds plus a free round-10 self-completion dummy) is numerically identical to the free-period model: the extra dummy releases the period trend, so the assumed-trend grid cannot move Sweden's slope and its identification rests on the age-bin functional form alone (R1 with a quadratic age term is near-collinear and gives an absurd value).", "The pooled estimate is a fixed-effect average of three slopes identified under different conditions (Sweden's essentially unconstrained); it is reported because the preregistration promised it, and should not be read as a Nordic estimate.", "Video interviews are a large share in FI rounds 10-11, NO rounds 10-11 and SE round 11; a video dummy is reported as a sensitivity."] json.dump(out, open(os.path.join(ROOT, "results/P26.json"), "w"), indent=1) print(json.dumps({"verdict": out["verdict"], **{c: (C[c]["primary"], C[c]["class_primary"], C[c]["R1_age_quadratic"]["b"], C[c]["class_R1"]) for c in C}}, indent=1)) if __name__ == "__main__": main()