"""P02, as preregistered in prereg/batch2/P02.md (bundle b4ff7c84…dd00). Run: ~/.venvs/ots/bin/python analysis/P02.py Step 1 parses Appendix A7 and writes results/P02_A7_parsed.csv with its SHA-256 before any effect size is computed.""" import hashlib, json, os, re import numpy as np, pandas as pd from scipy import stats from scipy.optimize import minimize_scalar ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DOCX = os.path.join(ROOT, "work/batch2/p02_data/41598_2025_14895_MOESM1_ESM.docx") TRIALS = ["Flowers et al. 2021", "Heller et al., 2022", "Ikemoto et al., 2020", "Kube et al., 2020", "Locher et al., 2017 -", "Locher et al., 2017 +", "Schienle et al., 2022", "Schneider et al., 2006", "Walach et al., 2001"] # Direction of the expected effect, fixed in the preregistration (section 3); keys are lower-case substrings of the Measure text DIRECTION = [("average pain", -1), ("morphine", -1), ("digit span", +1), ("correct target", +1), ("reaction time", -1), ("perceived cognitive", +1), ("basic mobility", -1), ("pain severity", -1), ("subjective disability", -1), ("heat pain tolerance", +1), ("tolerance", +1), ("intensity", -1), ("unpleas", -1), ("lpp", -1), ("anger", -1), ("arousal", -1), ("systolic", +1), ("diastolic", +1), ("heart rate", +1), ("alertness", +1), ("mood", +1), ("calmness", -1), ("basle", +1)] def parse(): import docx d = docx.Document(DOCX); t = [tb for tb in d.tables if len(tb.rows) > 150][0] hdr = [c.text.strip() for c in t.rows[0].cells]; rows = [[c.text.strip() for c in r.cells] for r in t.rows[1:]] df = pd.DataFrame(rows, columns=hdr) def ms(x): m = re.match(r"^\s*(-?[\d.,]+)\s*\(\s*(-?[\d.,]+)\s*\)", str(x).replace("−", "-")) return (float(m.group(1).replace(",", ".")), float(m.group(2).replace(",", "."))) if m else (np.nan, np.nan) num = lambda x: pd.to_numeric(str(x).replace(",", ".").strip(), errors="coerce") out = pd.DataFrame({"study": df["Authors, Year"], "form": df["Form of report"], "measure": df["Measure"], "type": df["Type score"]}) for col, key in [("Mean IGa pre (SD)b", "ig_pre"), ("Mean CGd pre (SD)", "cg_pre"), ("Mean IG post (SD)", "ig_post"), ("Mean CG post (SD)", "cg_post"), ("Change IG provided (SD)", "ig_chg"), ("Change CG provided (SD)", "cg_chg")]: v = df[col].map(ms); out[key + "_m"] = v.map(lambda x: x[0]); out[key + "_sd"] = v.map(lambda x: x[1]) for col, key in [("Nc IG pre", "n_ig_pre"), ("N CG pre", "n_cg_pre"), ("N IGpost", "n_ig_post"), ("N CG post", "n_cg_post"), ("N change IG provided", "n_ig_chg"), ("N change CG provided", "n_cg_chg")]: out[key] = df[col].map(num) p = os.path.join(ROOT, "results/P02_A7_parsed.csv"); out.to_csv(p, index=False) return out, hashlib.sha256(open(p, "rb").read()).hexdigest() def direction(measure): m = measure.lower() for k, s in DIRECTION: if k in m: return s return None def g_of(r): J = lambda n1, n2: 1 - 3 / (4 * (n1 + n2) - 9) if pd.notna(r.ig_chg_m) and pd.notna(r.cg_chg_m) and r.n_ig_chg > 0 and r.n_cg_chg > 0: n1, n2 = r.n_ig_chg, r.n_cg_chg; sp = np.sqrt(((n1 - 1) * r.ig_chg_sd**2 + (n2 - 1) * r.cg_chg_sd**2) / (n1 + n2 - 2)) d = (r.ig_chg_m - r.cg_chg_m) / sp; how = "provided change scores" elif r.type.lower().startswith("change") and pd.notna(r.ig_pre_m) and pd.notna(r.ig_post_m) and pd.notna(r.cg_pre_m) and pd.notna(r.cg_post_m): n1, n2 = r.n_ig_pre, r.n_cg_pre; sp = np.sqrt(((n1 - 1) * r.ig_pre_sd**2 + (n2 - 1) * r.cg_pre_sd**2) / (n1 + n2 - 2)) d = ((r.ig_post_m - r.ig_pre_m) - (r.cg_post_m - r.cg_pre_m)) / sp; how = "Morris pre-post-control (pooled pre SD)" elif pd.notna(r.ig_post_m) and pd.notna(r.cg_post_m): n1, n2 = r.n_ig_post, r.n_cg_post; sp = np.sqrt(((n1 - 1) * r.ig_post_sd**2 + (n2 - 1) * r.cg_post_sd**2) / (n1 + n2 - 2)) d = (r.ig_post_m - r.cg_post_m) / sp; how = "post-only" else: return np.nan, np.nan, "unparseable" g = J(n1, n2) * d return g, (n1 + n2) / (n1 * n2) + g**2 / (2 * (n1 + n2)), how def composite(gs, vs, r): gs, vs = np.asarray(gs), np.asarray(vs); m = len(gs) cov = sum(r * np.sqrt(vs[i] * vs[j]) for i in range(m) for j in range(m) if i != j) return gs.mean(), (vs.sum() + cov) / m**2 def reml_hk(y, v): y, v = np.asarray(y, float), np.asarray(v, float); k = len(y) def nll(t2): w = 1 / (v + t2); mu = np.sum(w * y) / w.sum(); return 0.5 * (np.sum(np.log(v + t2)) + np.log(w.sum()) + np.sum(w * (y - mu) ** 2)) t2 = minimize_scalar(nll, bounds=(0, 10 * np.var(y) + 1e-6), method="bounded").x w = 1 / (v + t2); mu = np.sum(w * y) / w.sum(); q = np.sum(w * (y - mu) ** 2) / (k - 1); se = np.sqrt(q / w.sum()); t = stats.t.ppf(0.975, k - 1) return {"est": round(float(mu), 3), "L": round(float(mu - t * se), 3), "U": round(float(mu + t * se), 3), "tau2": round(float(t2), 4), "k": k} def run(es, r=0.5, drop=(), trials=None): rows = [] for s, g in es[es.study.isin(trials or TRIALS) & ~es.study.isin(drop)].groupby("study"): a, b = g[g.form == "Self-report"], g[g.form == "Objective"] if len(a) == 0 or len(b) == 0: continue gs, vs = composite(a.g, a.v, r); go, vo = composite(b.g, b.v, r) rows.append({"study": s, "g_SR": gs, "v_SR": vs, "g_OBJ": go, "v_OBJ": vo, "delta": gs - go, "v_delta": vs + vo - 2 * r * np.sqrt(vs * vo)}) t = pd.DataFrame(rows) return {"delta": reml_hk(t.delta, t.v_delta), "g_SR": reml_hk(t.g_SR, t.v_SR), "g_OBJ": reml_hk(t.g_OBJ, t.v_OBJ), "per_trial": t.round(3).to_dict("records")} def verdict(p): d, sr, ob = p["delta"], p["g_SR"]["est"], p["g_OBJ"]["est"] if d["L"] > 0 and (ob <= 0 or sr >= 2 * ob): return "confirmed" if (d["L"] > -0.15 and d["U"] < 0.15) or d["U"] < 0: return "refuted" return "inconclusive" def main(): a7, h = parse() a7["direction"] = a7.measure.map(direction) res = a7.apply(g_of, axis=1, result_type="expand"); a7["g_raw"], a7["v"], a7["how"] = res[0], res[1], res[2] # D3: Locher 2017 reports standard errors in A7's SD slots (checked against the 2023 supplement: SD = SE*sqrt(n)) loc = a7.study.str.startswith("Locher et al., 2017") for arm, n in (("ig_chg", "n_ig_chg"), ("cg_chg", "n_cg_chg"), ("ig_post", "n_ig_post"), ("cg_post", "n_cg_post"), ("ig_pre", "n_ig_pre"), ("cg_pre", "n_cg_pre")): a7.loc[loc, arm + "_sd"] = a7.loc[loc, arm + "_sd"] * np.sqrt(a7.loc[loc, n]) res = a7.apply(g_of, axis=1, result_type="expand"); a7["g_raw"], a7["v"], a7["how"] = res[0], res[1], res[2] # D2 labels: values in the 'change provided' columns that are post levels (Heller, Schienle, Locher) lv = a7.study.isin(["Heller et al., 2022", "Schienle et al., 2022"]) | loc a7.loc[lv & (a7.how == "provided change scores"), "how"] = "post-only (values from the change columns)" # Literal preregistered orientation (kept for the record; it double-flips measures Fendel et al. already multiplied by -1) lit = a7.assign(g=a7.g_raw * a7.direction) literal = run(lit[lit.g.notna()]) # D1: A7 means are already oriented so that higher = beneficial (Fendel et al. 2025, Methods; visible as negative pain, reaction-time # and morphine values), so the effect is taken as computed, with no second flip. a7["g"] = a7.g_raw sub = a7[a7.study.isin(TRIALS)] excluded = sub[sub.g.isna()][["study", "measure", "how"]].values.tolist() + sub[sub.direction.isna()][["study", "measure"]].values.tolist() es = a7[a7.g.notna()] prim = run(es) comb = es.copy(); comb.loc[comb.study.str.startswith("Locher et al., 2017"), "study"] = "Locher et al., 2017 (both arms)" TR8 = [t for t in TRIALS if not t.startswith("Locher")] + ["Locher et al., 2017 (both arms)"] locher_one = run(comb, trials=TR8) tug = es.copy(); m = (tug.study == "Ikemoto et al., 2020") & tug.measure.str.lower().str.contains("basic mobility"); tug.loc[m, "g"] = -tug.loc[m, "g"] tug_flip = run(tug) # secondary (preregistered): between-trial comparison over all A7 trials, Fendel orientation, per-trial composites by form allt = [] for (st, fm), g in es.groupby(["study", "form"]): gg, vv = composite(g.g, g.v, 0.5); allt.append((st, fm, gg, vv)) allt = pd.DataFrame(allt, columns=["study", "form", "g", "v"]) between = {fm: reml_hk(allt[allt.form == fm].g, allt[allt.form == fm].v) for fm in ("Self-report", "Objective")} out = {"A7_parsed_sha256": h, "rows_in_nine_trials": int(len(sub)), "excluded_rows": excluded, "outcomes": sub[["study", "form", "measure", "direction", "how", "g", "v"]].round(3).to_dict("records"), "primary": prim, "verdict": verdict(prim), "robust_r_0.2": {k: v for k, v in run(es, r=0.2).items() if k != "per_trial"}, "robust_r_0.8": {k: v for k, v in run(es, r=0.8).items() if k != "per_trial"}, "robust_without_caffeine_trials": {k: v for k, v in run(es, drop=("Schneider et al., 2006", "Walach et al., 2001")).items() if k != "per_trial"}, "robust_without_Heller": {k: v for k, v in run(es, drop=("Heller et al., 2022",)).items() if k != "per_trial"}, "sensitivity_locher_arms_as_one_trial_k8": {k: v for k, v in locher_one.items() if k != "per_trial"}, "sensitivity_ikemoto_TUG_sign_flipped": {k: v for k, v in tug_flip.items() if k != "per_trial"}, "secondary_between_trial_all_A7": between, "prereg_literal_orientation_result": {k: v for k, v in literal.items() if k != "per_trial"}, "prereg_literal_verdict": verdict(literal), "deviations": [{"id": "D1", "what": "The preregistered direction multiplication is dropped; effects use the orientation already applied in the source table (higher = beneficial). The literal result is reported as prereg_literal_orientation_result.", "why": "Fendel et al. 2025 state that 'the means of some studies were multiplied by -1' so that positive means beneficial; Appendix A7 shows this (pain, reaction time and morphine values are negative). Applying the preregistered directions on top flips those outcomes twice. For the caffeine-placebo trials Fendel's orientation follows caffeine's expected effect (e.g. calmness flipped), which is also the preregistered direction. Ikemoto 2020's Timed-Up-and-Go change cannot be settled from A7 (sensitivity reported). D1 was chosen after the literal result was visible; both give the same verdict. Not foreseen: the preregistration assumed raw means."}, {"id": "D3", "what": "Locher et al. 2017: the dispersions in A7 are standard errors (A7 gives 47.99 (0.14) with N 37; the 2023 supplement gives SD 0.85 = 0.14*sqrt(37)); converted to SD = SE*sqrt(n).", "why": "Extraction error in the source table, found by the hostile review; it inflated Locher's g about six-fold."}, {"id": "D2", "what": "Where A7 places values in the 'change provided' columns for outcomes typed Post-only or without pre-test values (Heller 2022, Locher 2017, Schienle 2022), they are used as given; the formula (difference of means over the pooled SD) is the same as the post-only formula.", "why": "A7 column use is inconsistent across trials."}], "notes": ["The ratio condition (g_SR >= 2 x g_OBJ) is nearly vacuous when g_OBJ is about 0; only the CI of the difference decides.", "The positive difference depends on the two caffeine-placebo trials; without them it is near zero. Schneider 2006's objective composite is dominated by heart rate, with a 14 bpm baseline imbalance between arms of 15.", "Locher 2017's two arms share one control group, so their differences are not independent (sensitivity with the arms combined).", "A7 appears to swap systolic and diastolic values for Walach 2001; the composite is unaffected.", "Approximations: the Morris pre-post-control variance omits the 2(1-rho) factor; Flowers 2021 uses baseline Ns; change-SD and pre-SD scalings put some g on different scales."], "non_blind": "A research subagent saw the published pooled results of the 2023 and 2025 OLP meta-analyses before this test was preregistered; calibration entry."} # secondary between-trial comparison: every A7 outcome whose direction is fixed (only the nine trials have fixed directions) json.dump(out, open(os.path.join(ROOT, "results/P02.json"), "w"), indent=1, default=float) print(json.dumps({k: out[k] for k in ("A7_parsed_sha256", "rows_in_nine_trials", "excluded_rows", "verdict")}, indent=1)) print("primary:", {k: prim[k] for k in ("delta", "g_SR", "g_OBJ")}) for k in ("robust_r_0.2", "robust_r_0.8", "robust_without_caffeine_trials", "robust_without_Heller"): print(k, out[k]["delta"], out[k]["g_SR"]["est"], out[k]["g_OBJ"]["est"]) if __name__ == "__main__": main()