"""P03, as preregistered in prereg/P03.md (bundle 836db4f4…f8413d). Run: ~/.venvs/ots/bin/python analysis/P03.py Writes results/P03.json and results/P03_contrasts.csv.""" import json, os, warnings import numpy as np, pandas as pd, rdata, statsmodels.api as sm from scipy import stats warnings.filterwarnings("ignore") ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DATA = os.path.join(ROOT, "work/batch1/p03_data/coppock_PiP/replication_archive/data") SESOI, MIN_N = 0.05, 30 def rds(name): df = rdata.conversion.convert(rdata.parser.parse_file(f"{DATA}/{name}.rds")) df["pid7"] = pd.to_numeric(df["pid_7"].astype(str), errors="coerce") return df def split(df, by): by = [b for b in by if b in df.columns] if not by: yield {}, df; return for key, g in df.groupby(by, observed=True): key = key if isinstance(key, tuple) else (key,) yield {b: str(k) for b, k in zip(by, key)}, g def contrasts(): """Yield (study, labels, frame with columns y, t (1 treated, 0 control), w, pid7). Exactly the table in prereg section 3.""" def mk(g, tvar, arm, ctrl, y, w): s = g[g[tvar].astype(str).isin([arm, ctrl])] return pd.DataFrame({"y": s[y].astype(float), "t": (s[tvar].astype(str) == arm).astype(float), "w": s[w].astype(float), "pid7": s["pid7"]}) for study, f, tvar, arms, ctrl in [("patriot_act", "patriot_act_stacked", "T1_content", ["Pro", "Con"], "Control"), ("immigration", "immigration_stacked", "Z_brader_pos_neg", ["positive", "negative"], "control"), ("free_trade_valence", "free_trade_stacked", "Z_Hiscox_valence", ["Positive", "Negative"], "Control"), ("free_trade_expert", "free_trade_stacked", "Z_Hiscox_expert", ["Expert treatment"], "Control"), ("expert_economists", "expert_economists_stacked_long", "Z_expert_all", ["Expert Treatment"], "Control"), ("frame_breadth", "frame_breath_topic", "Z", ["1.0"], "0.0"), ("death_penalty", "death_penalty_stacked", "Z", ["1.0"], "0.0")]: df = rds(f) if df[tvar].dtype.kind == "f": df[tvar] = df[tvar].map(lambda v: f"{v:.1f}" if pd.notna(v) else v) for lab, g in split(df, ["sample_label", "topic"]): for arm in arms: yield study, {**lab, "arm": arm}, mk(g, tvar, arm, ctrl, "Y_w1_s", "weights") df = rds("opeds_long"); match = {"amtrak": "amtrak", "climate": "climate", "flat": "paul", "veterans": "veterans", "wallstreet": "wallstreet"} for lab, g in split(df, ["sample_label", "topic"]): arm = match[lab["topic"]] yield "opeds", {**lab, "arm": arm}, mk(g, "Z", arm, "control", "Y_w1_s", "weights") for study, f, tvar, arm, ctrl in [("flavin", "flavin_clean", "Z", "Treatment", "Control"), ("mutz", "mutz_clean", "Z", "Job lost to trade", "Reason not specified"), ("trump_white", "trump_white_clean", "Z", "Treatment", "Control"), ("kreps_wallace", "kreps_wallace_clean", "Z", "Treatment", "Control")]: yield study, {"arm": arm}, mk(rds(f), tvar, arm, ctrl, "Y_s", "weight") df = rds("gash_murakami_clean") for topic in ("Ballot", "Courts", "Legislature"): g = df[df[topic].notna()] yield "gash_murakami", {"topic": topic, "arm": "Treatment"}, mk(g, topic, "Treatment", "Control", "Y_s", "weight") def wdiff(d): a, b = d[d.t == 1], d[d.t == 0] return np.average(a.y, weights=a.w) - np.average(b.y, weights=b.w) def est(d): r = sm.WLS(d.y, sm.add_constant(d.t), weights=d.w).fit(cov_type="HC2") return float(r.params["t"]), float(r.bse["t"]) def reml_hk(y, se): """Random-effects pooling: tau^2 by restricted maximum likelihood, Hartung-Knapp-Sidik-Jonkman 95% CI.""" from scipy.optimize import minimize_scalar y, v = np.asarray(y, float), np.asarray(se, float) ** 2; k = len(y) def nll(tau2): w = 1 / (v + tau2); mu = np.sum(w * y) / w.sum() return 0.5 * (np.sum(np.log(v + tau2)) + np.log(w.sum()) + np.sum(w * (y - mu) ** 2)) tau2 = minimize_scalar(nll, bounds=(0, 10 * np.var(y) + 1e-6), method="bounded", options={"xatol": 1e-10}).x w = 1 / (v + tau2); mu = np.sum(w * y) / w.sum() q = np.sum(w * (y - mu) ** 2) / (k - 1); se_hk = np.sqrt(q / w.sum()) t = stats.t.ppf(0.975, k - 1) return {"D": round(float(mu), 4), "L": round(float(mu - t * se_hk), 4), "U": round(float(mu + t * se_hk), 4), "se_HK": round(float(se_hk), 4), "tau2": round(float(tau2), 5), "k": k} def verdict(p): if p["L"] > -SESOI and p["U"] < SESOI: return "PM-0145 confirmed" if p["L"] > 0 and p["D"] >= SESOI: return "PM-0145 refuted" return "inconclusive" def main(): rows, excluded = [], [] for study, lab, d in contrasts(): d = d.dropna(subset=["y", "t", "w", "pid7"]); d = d[d.w > 0] strong, weak = d[d.pid7.isin([1, 7])], d[d.pid7.between(2, 6)] ns = (int((strong.t == 1).sum()), int((strong.t == 0).sum())) tag = {"study": study, **lab} if min(ns) < MIN_N: excluded.append({**tag, "n_strong_treated_control": ns, "reason": "not fielded in this sample" if len(d) == 0 else f"fewer than {MIN_N} strong partisans in an arm"}); continue s = float(np.sign(wdiff(weak))) dS, seS = est(strong); dW, seW = est(weak); sW_by_strong = float(np.sign(wdiff(strong))) rows.append({**tag, "n_strong": len(strong), "n_nonstrong": len(weak), "s": s, "d_strong": dS, "se_strong": seS, "oriented_strong": s * dS, "d_nonstrong": dW, "se_nonstrong": seW, "oriented_nonstrong_by_strong": sW_by_strong * dW}) t = pd.DataFrame(rows) t.to_csv(os.path.join(ROOT, "results/P03_contrasts.csv"), index=False) prim = reml_hk(t.oriented_strong, t.se_strong) # (a) within study x sample_label inverse-variance averages first t["grp"] = t.study + "|" + (t["sample_label"].fillna("") if "sample_label" in t else "") ga = t.groupby("grp").apply(lambda g: pd.Series({"y": np.average(g.oriented_strong, weights=1 / g.se_strong**2), "se": np.sqrt(1 / np.sum(1 / g.se_strong**2))})) rob_a = reml_hk(ga.y, ga.se) nb = t[~t.study.isin(["expert_economists", "free_trade_expert"])] rob_b = reml_hk(nb.oriented_strong, nb.se_strong) rob_c = reml_hk(t.oriented_nonstrong_by_strong, t.se_nonstrong) # cluster-robust variance for the pooled estimate (contrasts sharing control groups / respondents are not independent) def crve(t, gcol): tau2 = prim["tau2"]; w = 1 / (t.se_strong**2 + tau2); mu = np.sum(w * t.oriented_strong) / w.sum() g = t[gcol].values; G = len(set(g)) num = sum((np.sum((w * (t.oriented_strong - mu))[g == k])) ** 2 for k in set(g)) se = np.sqrt(G / (G - 1) * num) / w.sum(); q = stats.t.ppf(0.975, G - 1) return {"D": round(float(mu), 4), "L": round(float(mu - q * se), 4), "U": round(float(mu + q * se), 4), "G": G} cl_study = crve(t, "study"); cl_grp = crve(t, "grp") argonly = t[~t.study.isin(["death_penalty", "kreps_wallace", "mutz", "gash_murakami"])] rob_d = reml_hk(argonly.oriented_strong, argonly.se_strong) out = {"primary_strong_partisans": prim, "cluster_robust_by_study": cl_study, "cluster_robust_by_study_sample": cl_grp, "robust_d_argument_vs_control_only": rob_d, "verdict": verdict(prim), "robust_a_study_averaged": rob_a, "robust_b_no_expert_cues": rob_b, "robust_c_nonstrong_oriented_by_strong": rob_c, "n_contrasts": len(t), "excluded_contrasts": excluded, "share_strong_contrasts_positive": round(float((t.oriented_strong > 0).mean()), 3), "verdict_holds_under_cluster_robust_CI": bool(cl_study["L"] > 0 and cl_study["D"] >= SESOI), "notes": ["s is the direction in which non-strong respondents moved, not the argument's content direction; in free-trade valence both arms take the same sign in three samples. Non-strong and strong respondents are disjoint, so this orientation cannot bias the strong-partisan estimate upward; noisy signs bias it toward zero.", "Departures from the book's figure 5.16, both written into the preregistration: expert economists and frame breadth are split by topic as well as sample (5 book estimates become 22 contrasts); the preregistration's remark that the book drops 'Both' in free trade is wrong (the book's filter tests lowercase 'both' and removes nothing), while this analysis does exclude the Both arm.", "Some contrasts are not argument versus pure control: death penalty (innocence vs race argument), Kreps & Wallace (violate vs do not violate), Mutz (vignette), Gash & Murakami (institutional-route cue). robust_d drops them.", "Outcomes are the book's standardised variables (divided by the control-group SD, not centred); 0.25 'SD' is in those units, not strong partisans' own spread.", "All data come from one author's collection, which the register already cited as contradicting PM-0145, and the book's code was read before the stamp: this is a re-cut of known evidence, entered to calibrate the ledger, not independent evidence.", "The smallest effect of interest (0.05) does not drive the verdict: the lower bound is about four times larger."]} json.dump(out, open(os.path.join(ROOT, "results/P03.json"), "w"), indent=1) print(json.dumps(out, indent=1)) if __name__ == "__main__": main()