"""P07, as preregistered in prereg/batch2/P07.md (bundle b4ff7c84…dd00). Run: ~/.venvs/ots/bin/python analysis/P07.py Writes results/P07.json and results/P07_country_waves.csv (aggregates only).""" import io, json, os, urllib.request, zipfile import numpy as np, pandas as pd, statsmodels.formula.api as smf ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) FILES = {"WVS": "data/restricted/wvs/F00011930-WVS_Time_Series_1981-2022_Stata_v5_0.zip", "EVS": "data/restricted/evs/ZA7503_v3-0-0.dta.zip"} COLS = ["S003", "S017", "S020", "S024", "E069_01", "F050"] SESOI = 1.0 def load(src): z = zipfile.ZipFile(os.path.join(ROOT, FILES[src])); n = [x for x in z.namelist() if x.endswith(".dta")][0] df = pd.read_stata(io.BytesIO(z.read(n)), columns=COLS, convert_categoricals=False) df["file"] = src return df def worldbank_hash(): import hashlib return hashlib.sha256(open(os.path.join(ROOT, "results/P07_worldbank_IT.NET.USER.ZS.json"), "rb").read()).hexdigest() def worldbank(): url = "https://api.worldbank.org/v2/country/all/indicator/IT.NET.USER.ZS?format=json&per_page=20000&date=1990:2023" raw = urllib.request.urlopen(url, timeout=120).read() open(os.path.join(ROOT, "results/P07_worldbank_IT.NET.USER.ZS.json"), "wb").write(raw) rows = json.loads(raw)[1] wb = pd.DataFrame([(r["countryiso3code"], int(r["date"]), r["value"]) for r in rows if r["value"] is not None and r["countryiso3code"]], columns=["iso3", "year", "internet"]) return wb def iso_num_to_a3(): import pycountry return {int(c.numeric): c.alpha_3 for c in pycountry.countries} def country_waves(df): out, steps = [], {} df = df[df.S020 >= 1990] for (f, cw), g in df.groupby(["file", "S024"]): c = g[g.E069_01.between(1, 4)]; b = g[g.F050.isin([0, 1])] if len(c) < 300 or len(b) < 300: continue w = lambda x: x.S017.clip(lower=0) if w(c).sum() <= 0 or w(b).sum() <= 0: continue out.append({"file": f, "S024": int(cw), "S003": int(g.S003.iloc[0]), "year": int(round(g.S020.median())), "C": 100 * np.average(c.E069_01.isin([1, 2]), weights=w(c)), "B": 100 * np.average(b.F050 == 1, weights=w(b)), "C_mean_rev": np.average(5 - c.E069_01, weights=w(c)), "n_C": len(c), "n_B": len(b)}) return pd.DataFrame(out) def fit(cw, extra=""): long = pd.concat([cw.assign(outcome="C", share=cw.C), cw.assign(outcome="B", share=cw.B)]) long = long.drop(columns=["C", "B"]) # 'C' would shadow patsy's C() long["isC"] = (long.outcome == "C").astype(float); long["I10"] = long.internet / 10 long["period"] = (long.year // 5 * 5).astype(str); long["cty"] = long.iso3 fx = "C(outcome):C(file)" if extra == "file_by_outcome" else "C(file)" f = f"share ~ I10 + I10:isC + C(outcome):C(cty) + C(outcome):C(period) + {fx}" if extra != "linear_year" else f"share ~ I10 + I10:isC + C(outcome):C(cty) + C(outcome):year + {fx}" r = smf.ols(f, data=long).fit(cov_type="cluster", cov_kwds={"groups": pd.factorize(long.cty)[0]}) d = r.params["I10:isC"]; lo, hi = r.conf_int().loc["I10:isC"] bB = r.params["I10"]; bC = bB + d V = r.cov_params(); seC = np.sqrt(V.loc["I10", "I10"] + V.loc["I10:isC", "I10:isC"] + 2 * V.loc["I10", "I10:isC"]) return {"delta": round(float(d), 3), "L": round(float(lo), 3), "U": round(float(hi), 3), "beta_C": round(float(bC), 3), "beta_C_L": round(float(bC - 1.96 * seC), 3), "beta_C_U": round(float(bC + 1.96 * seC), 3), "beta_B": round(float(bB), 3), "beta_B_L": round(float(r.conf_int().loc["I10"][0]), 3), "beta_B_U": round(float(r.conf_int().loc["I10"][1]), 3), "country_waves": int(len(cw)), "countries": int(cw.iso3.nunique())} def verdict(p): if p["delta"] <= -SESOI and p["U"] < 0 and p["beta_C"] < 0: return "confirmed" if p["L"] > -SESOI: return "refuted" return "inconclusive" def main(): import pycountry raw = pd.concat([load("WVS"), load("EVS")]) n_after_1990 = int(raw[raw.S020 >= 1990].groupby(["file", "S024"]).ngroups) cw = country_waves(raw); n0 = len(cw) # the same survey present in both files (identical n and shares) is counted once (the WVS copy is dropped) key = ["S003", "year", "n_C", "n_B"] dup = cw[cw.duplicated(key, keep=False)] same = dup.groupby(key).filter(lambda g: g.C.round(6).nunique() == 1 and g.B.round(6).nunique() == 1 and g.file.nunique() == 2) drop_dup = same[same.file == "WVS"].index; cw = cw.drop(drop_dup) a3 = iso_num_to_a3(); cw["iso3"] = cw.S003.map(a3) unmapped = cw[cw.iso3.isna()][["file", "S024", "S003", "year"]].values.tolist(); cw = cw[cw.iso3.notna()] wb = worldbank() cw = cw.merge(wb, on=["iso3", "year"], how="left") no_wb = cw[cw.internet.isna()][["file", "S024", "iso3", "year"]].values.tolist(); cw = cw[cw.internet.notna()] k = cw.groupby("iso3").size(); single = sorted(k[k < 2].index); cw = cw[cw.iso3.isin(k[k >= 2].index)] cw.round(3).to_csv(os.path.join(ROOT, "results/P07_country_waves.csv"), index=False) prim = fit(cw) out = {"counts": {"country_waves_1990_on": n_after_1990, "passing_300_rule": n0, "failing_300_rule_or_zero_weight": n_after_1990 - n0, "same_survey_in_both_files_dropped": int(len(drop_dup)), "unmapped_country_codes": unmapped, "no_worldbank_value": no_wb, "single_wave_countries_dropped": single, "analysed": int(len(cw)), "countries": sorted(cw.iso3.unique().tolist())}, "worldbank_download_sha256": worldbank_hash(), "primary": prim, "verdict": verdict(prim)} loo = {c: fit(cw[cw.iso3 != c]) for c in sorted(cw.iso3.unique())} flips = {c: v["L"] for c, v in loo.items() if verdict(v) != out["verdict"]} out["leave_one_country_out"] = {"verdict_changes_in": len(flips), "of": len(loo), "lower_bounds_where_it_changes": dict(sorted(flips.items(), key=lambda x: x[1])), "min_L": min(v["L"] for v in loo.values()), "max_L": max(v["L"] for v in loo.values())} # EVS-WVS overlap: pairs in the same country within 2 years; keep one file def overlap_keep(src): other = "EVS" if src == "WVS" else "WVS"; d = cw.copy(); drop = [] for _, r in d[d.file == other].iterrows(): m = d[(d.file == src) & (d.iso3 == r.iso3) & ((d.year - r.year).abs() <= 2)] if len(m): drop.append(_) return fit(d.drop(drop)) out["overlap_keep_WVS"] = overlap_keep("WVS"); out["overlap_keep_EVS"] = overlap_keep("EVS") out["robust_a_WVS_only"] = fit(cw[cw.file == "WVS"]); out["robust_b_EVS_only"] = fit(cw[cw.file == "EVS"]) out["robust_c_linear_year"] = fit(cw, "linear_year") out["robust_d_confidence_mean_reversed"] = fit(cw.assign(C=cw.C_mean_rev)) out["file_effect_by_outcome_first_run"] = fit(cw, "file_by_outcome") out["deviations"] = [ {"id": "D1", "what": "First run replaced non-positive S017 weights (all exactly 0, in 22 EVS waves) with 1; corrected: S017 is used as given, so zero-weight respondents count for nothing.", "why": "Bug found by the hostile review; the preregistration says weighted by S017."}, {"id": "D2", "what": "First run used a file effect per outcome; corrected to the single file indicator the preregistration names. The first-run specification is reported as file_effect_by_outcome_first_run.", "why": "Undeclared departure found by the hostile review."}, {"id": "D3", "what": "One survey present in both files with identical n and shares (Sweden 1999) is counted once.", "why": "Double counting found by the hostile review; the preregistration intended distinct surveys."}] out["notes"] = ["The verdict is fragile: see leave_one_country_out and the overlap sensitivities; a one-year internet lag (exploratory, not preregistered) also moves the lower bound past -1.0.", "The result excludes a gap of 1 pp or more per 10 points of internet use only barely; smaller gaps are not excluded.", "beta_C is not distinguishable from zero while belief in God falls; the result does not show that institutional confidence fell at all.", "WVS wave 5 did not ask F050 (coded not asked), so 2005-2009 is nearly absent; within-country internet variation comes in large steps.", "The prediction says 'followed by'; the test is contemporaneous (survey year). 'Sooner' was not tested.", "robust_d uses the reversed 1-4 confidence mean as preregistered; its units are not comparable to percentage points."] json.dump(out, open(os.path.join(ROOT, "results/P07.json"), "w"), indent=1) print(json.dumps({k: out[k] for k in ("primary", "verdict", "leave_one_country_out", "overlap_keep_WVS", "overlap_keep_EVS")}, indent=1)) print({k: (out["counts"][k] if not isinstance(out["counts"][k], list) else len(out["counts"][k])) for k in out["counts"]}) if __name__ == "__main__": main()