"""P06, as preregistered in prereg/P06.md (bundle 836db4f4…f8413d). Needs results/P06_country_days.csv from analysis/p06_fetch.py. Run: ~/.venvs/ots/bin/python analysis/P06.py Writes results/P06.json.""" import json, os, warnings import numpy as np, pandas as pd, statsmodels.api as sm warnings.filterwarnings("ignore") ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MIN_N = 20 def panel(cal, cd, half=2, drop_years=(), drop_country=None): rows = [] for c, kind, name, y, h, win, base in cal: if y in drop_years or c == drop_country: continue hd = pd.Timestamp(h) win = [d for d in win if abs((pd.Timestamp(d) - hd).days) <= half] inst = f"{c}|{name}|{y}" rows += [(inst, c, y, kind, d, 1) for d in win] + [(inst, c, y, kind, d, 0) for d in base] p = pd.DataFrame(rows, columns=["inst", "country", "year", "kind", "day", "in_window"]) p["day"] = p.day.str.replace("-", "") p = p.merge(cd, left_on=["day", "country"], right_on=["day", "country"], how="inner") p = p[p.N >= MIN_N].copy() p["C_win"] = ((p.kind == "C") & (p.in_window == 1)).astype(float) p["K_win"] = ((p.kind == "K") & (p.in_window == 1)).astype(float) p["dow"] = pd.to_datetime(p.day).dt.dayofweek p["cy"] = p.country + "|" + p.year.astype(str) return p def fe(p): return pd.concat([p[["C_win", "K_win"]], pd.get_dummies(p.inst, prefix="i", dtype=float), pd.get_dummies(p.dow, prefix="d", drop_first=True, dtype=float)], axis=1) def ppml(p, y, cluster="cy"): X = fe(p) r = sm.GLM(p[y].astype(float), X, family=sm.families.Poisson(), offset=np.log(p.N.astype(float))).fit( cov_type="cluster", cov_kwds={"groups": pd.factorize(p[cluster])[0]}, maxiter=200) return contrast(r, ratio=True) def ols_tone(p, absolute=False): p = p.copy(); p["tone"] = p.tone_sum / p.N if absolute: # absolute deviation from the instance's own baseline mean bm = p[p.in_window == 0].groupby("inst").tone.mean(); p["tone"] = (p.tone - p.inst.map(bm)).abs() X = fe(p) r = sm.WLS(p.tone, X, weights=p.N.astype(float)).fit(cov_type="cluster", cov_kwds={"groups": pd.factorize(p.cy)[0]}) return contrast(r, ratio=False) def contrast(r, ratio): b = r.params["C_win"] - r.params["K_win"] V = r.cov_params(); se = np.sqrt(V.loc["C_win", "C_win"] + V.loc["K_win", "K_win"] - 2 * V.loc["C_win", "K_win"]) lo, hi = b - 1.96 * se, b + 1.96 * se f = np.exp if ratio else (lambda x: x) out = {"effect": round(float(f(b)), 4), "L": round(float(f(lo)), 4), "U": round(float(f(hi)), 4), "C_lift": round(float(f(r.params["C_win"])), 4), "K_lift": round(float(f(r.params["K_win"])), 4), "n_rows": int(r.nobs)} return out def verdict(e): if e["effect"] >= 1.10 and e["L"] > 1.00: return "confirmed" if e["U"] < 1.10: return "refuted" return "inconclusive" def main(): cal = json.load(open(os.path.join(ROOT, "results/P06_calendar.json"))) cd = pd.read_csv(os.path.join(ROOT, "results/P06_country_days.csv"), dtype={"day": str}) files = pd.read_csv(os.path.join(ROOT, "results/P06_files.csv"), dtype={"day": str}) p = panel(cal, cd) out = {"files_read": int((files.status == "ok").sum()), "files_missing_or_failed": files[files.status != "ok"][["day", "status"]].values.tolist(), "country_days_dropped_N_lt_20": int(len(panel(cal, cd.assign(N=cd.N.clip(lower=MIN_N))))) - len(p), "rows": len(p), "instances": int(p.inst.nunique()), "commemoration_instances": int(p[p.kind == "C"].inst.nunique())} out["Y1_primary_RAD_any_actor"] = ppml(p, "Y1_rad_any"); out["verdict"] = verdict(out["Y1_primary_RAD_any_actor"]) out["Y2_protest"] = ppml(p, "Y2_protest") out["Y3_tone_signed"] = ols_tone(p); out["Y3_tone_absolute_deviation"] = ols_tone(p, absolute=True) out["robust_excl_2020"] = ppml(panel(cal, cd, drop_years=(2020,)), "Y1_rad_any") out["robust_window_pm1"] = ppml(panel(cal, cd, half=1), "Y1_rad_any") out["robust_actor1_only"] = ppml(p, "Y1a_rad_actor1") out["robust_drop_one_country"] = {c: ppml(panel(cal, cd, drop_country=c), "Y1_rad_any") for c in sorted(p.country.unique())} # exclusion chain (prereg section 7) allrows = sum(len(x[5]) + len(x[6]) for x in cal) have = panel(cal, cd.assign(N=cd.N.clip(lower=MIN_N))) out["exclusion_chain"] = {"controls_dropped_by_overlap_rule": 2, "instance_days_in_design": allrows, "lost_to_missing_daily_files": allrows - len(have), "dropped_N_lt_20": len(have) - len(p), "analysed_rows": len(p)} ny = ~(p.inst.str.contains("New Year") & (p.year == 2020)) out["robust_drop_new_year_2020"] = ppml(p[ny], "Y1_rad_any") out["robust_cluster_by_country_11"] = ppml(p, "Y1_rad_any", cluster="country") out["data_defects"] = ["GDELT daily files 2020-01-02 and 2020-01-03 (and most of 2020-01-01) date their events SQLDATE 1920-01-xx instead of 2020-01-xx, so the preregistered SQLDATE anchoring keeps almost none of their rows: those New Year 2020 window days are dropped by the N >= 20 rule or rest on a few events. robust_drop_new_year_2020 removes the New Year 2020 instances.", "Two daily files do not exist upstream (2022-11-10, 2023-03-23)."] out["notes"] = ["EventCode 017 is stored with a leading zero ('017'), checked on three files after the review; the exclusion works.", "The verdict is close to the refutation line: leaving out Australia gives an upper bound below 1.10 (refuted by the rule); clustering by country (11 clusters, not preregistered) also gives an upper bound below 1.10. The preregistered verdict stays inconclusive and is reported with this beside it.", "Per-country lifts differ widely and the US supplies about half the RAD events; no claim about any single country is made.", "Tone (Y3) is secondary and does not count toward the verdict; AvgTone is the tone of the source documents, not of events.", "Baseline country-days shared by two instances of the same country-year appear twice, as the instance-based design implies (252 days); keeping one copy gives R = 0.942 (hostile review)."] json.dump(out, open(os.path.join(ROOT, "results/P06.json"), "w"), indent=1) print(json.dumps({k: out[k] for k in ("rows", "instances", "Y1_primary_RAD_any_actor", "verdict", "Y2_protest", "Y3_tone_signed")}, indent=1)) if __name__ == "__main__": main()