#!/usr/bin/env python3 """Planted-signal studies with known ground truth under protocol v6 (T2 text cues, T3 depth hazard). scripts/21_m5_synthetic.py run both arms, write outputs/m5/synthetic/ scripts/21_m5_synthetic.py --arm t3 run one arm (the report is rebuilt from every finished run) scripts/21_m5_synthetic.py --arm t2 --shard 0/4 run every fourth T2 planting (independent processes) scripts/21_m5_synthetic.py --arm report rebuild report.json and the tables from finished runs only scripts/21_m5_synthetic.py --arm diagnose post-hoc: why the T2 null check at c = 0 can fail when f > 0 Refuses to run unless configs/protocol_v6.yaml matches its checksum, its parent v5 matches the recorded checksum and the cue lexicon matches inputs_hashed. Every T2 run is checkpointed in outputs/m5/synthetic/t2_runs/, so an interrupted run resumes. The real activity codes and the real T2/T3 labels are never read. """ from __future__ import annotations import argparse import json import time from pathlib import Path import numpy as np import pandas as pd from volve_dia import m34, m5_synthetic as ms ROOT = Path(__file__).resolve().parents[1] PROTOCOL = ROOT / "configs/protocol_v6.yaml" CUES = ROOT / "configs/synth_cues.yaml" BASE_SEED, SEEDS, RESAMPLES, CI_SEED = 20261117, 5, 2000, 20261117 T2_PI, T3_PI = 0.183, 556 / 4894 T2_C = (0.0, 0.1, 0.25, 0.5, 0.75, 1.0) T2_F_PRIMARY, T2_F_SENSITIVITY = 0.02, 0.10 T3_S = (0.0, 0.25, 0.5, 1.0, 2.0) T2_UNIVERSE, T3_UNIVERSE = (23447, 11), (4894, 10) T2_STATED, T3_STATED = 0.461, 0.150 def real_t2_reference(root): rows = json.loads((root / "m34/report.json").read_text())["classification"] match = [r for r in rows if r["task"] == "t2" and r["definition"] == "b" and r["mode"] == "masked" and r["split"] == "well" and r["method"] == "tfidf_logistic" and r["modality"] == "xml" and r["subset"] == "all"] if len(match) != 1: raise ValueError("Expected one masked T2(b) TF-IDF by-well XML row in outputs/m34/report.json") return {"source": "outputs/m34/report.json classification: t2, b, masked, well, tfidf_logistic, xml, all", "ap": match[0]["metrics"]["pr_auc_ap"]["estimate"], "stated_in_protocol": T2_STATED} def real_t3_reference(root): block = json.loads((root / "m5/t5/report.json").read_text())["knn_forecast"]["label_b"]["depth"] return {"source": "outputs/m5/t5/report.json knn_forecast.label_b.depth.ap", "ap": block["ap"], "stated_in_protocol": T3_STATED} def check_universe(frame, expected, name): if (len(frame), frame["well"].nunique()) != expected: raise ValueError(f"{name} universe differs from protocol v6: {len(frame)} rows, " f"{frame['well'].nunique()} wells") def run_t2(root, dest, protocol, spec, digest, shard=(0, 1)): acts = pd.read_parquet(root / "labels/t2_inputs.parquet", columns=ms.T2_COLUMNS) check_universe(acts, T2_UNIVERSE, "T2") phrases = ms.load_cues(CUES) settings, n_splits = spec["classification"], protocol["splits"]["inner"]["n_splits"] wells = acts["well"].to_numpy() runs = dest / "t2_runs" runs.mkdir(parents=True, exist_ok=True) plan = t2_plan() for i, (f, c, seed) in enumerate(plan): if i % shard[1] != shard[0]: continue name = f"f{f:.2f}_c{c:.2f}_s{seed}" meta = runs / f"{name}.json" if meta.is_file() and json.loads(meta.read_text()).get("protocol_sha256") == digest: continue start = time.time() y, cue = ms.plant_t2(len(acts), T2_PI, c, f, len(phrases), ms.planting_rng(seed, c, f)) text = ms.t2_text(ms.apply_cues(acts, cue, phrases)) scores, chosen = ms.t2_oof(ms.t2_inputs(acts, text), y, settings, n_splits) exposure = ms.cue_exposure(text, y, phrases) row = {"arm": "t2", "f": f, "c": c, "seed": seed, **ms.ap_row(y, scores, wells, RESAMPLES, CI_SEED), "cue_rate_planted": float((cue[y] >= 0).mean()), "cue_rate_unplanted": float((cue[~y] >= 0).mean()), "exposure_planted": exposure["planted"], "exposure_unplanted": exposure["unplanted"], "logistic_c": chosen, "seconds": round(time.time() - start, 1), "protocol_sha256": digest} m34.write_parquet(pd.DataFrame({"act_id": acts["act_id"], "well": wells, "planted": y, "cue": cue, "score": scores}), runs / f"{name}.parquet") m34.atomic_write(meta, json.dumps(row, indent=1).encode()) print(f"[{i + 1}/{len(plan)}] t2 {name}: AP {row['ap']:.4f} ({row['seconds']} s)", flush=True) def t2_plan(): return [(f, c, BASE_SEED + k) for f in (T2_F_PRIMARY, T2_F_SENSITIVITY) for c in T2_C for k in range(SEEDS)] def collect_t2(dest, digest): """Every finished T2 planting of the current protocol, in plan order.""" rows = [] for f, c, seed in t2_plan(): meta = dest / "t2_runs" / f"f{f:.2f}_c{c:.2f}_s{seed}.json" if meta.is_file() and (row := json.loads(meta.read_text())).get("protocol_sha256") == digest: rows.append(row) return pd.DataFrame(rows) def run_t3(root, dest): cells = pd.read_parquet(root / "m34/features_t3.parquet", columns=ms.T3_COLUMNS) check_universe(cells, T3_UNIVERSE, "T3") z = ms.zscore(cells["md_top"]) wells = cells["well"].to_numpy() rows, frames = [], [] for s in T3_S: for k in range(SEEDS): seed = BASE_SEED + k a, p, y = ms.plant_t3(z, s, T3_PI, ms.planting_rng(seed, s)) scores = ms.t3_scores(cells, y) oracle = ms.ap_row(y, p, wells, RESAMPLES, CI_SEED) rows.append({"arm": "t3", "s": s, "seed": seed, "intercept": a, "mean_p": float(p.mean()), **ms.ap_row(y, scores, wells, RESAMPLES, CI_SEED), "oracle_ap": oracle["ap"], "oracle_ci_low": oracle["ci_low"], "oracle_ci_high": oracle["ci_high"]}) frames.append(pd.DataFrame({"item": cells["item"], "well": wells, "s": s, "seed": seed, "p": p, "planted": y, "score": scores})) print(f"t3 s={s} seed={seed}: AP {rows[-1]['ap']:.4f}, oracle {oracle['ap']:.4f}", flush=True) m34.write_parquet(pd.concat(frames, ignore_index=True), dest / "t3_scores.parquet") return pd.DataFrame(rows) def diagnose_t2(dest): """Post-hoc (not part of protocol v6): the model AP against the AP of the no-own-cue indicator, per setting.""" rows = [] for path in sorted((dest / "t2_runs").glob("*.parquet")): meta = json.loads(path.with_suffix(".json").read_text()) run = pd.read_parquet(path) y = run["planted"].to_numpy() rows.append({"f": meta["f"], "c": meta["c"], "seed": meta["seed"], "prevalence": float(y.mean()), "model_ap": meta["ap"], "no_cue_indicator_ap": ms.no_cue_indicator_ap(y, run["cue"]), "own_cue_rate_planted": float((run["cue"][y] >= 0).mean()), "own_cue_rate_unplanted": float((run["cue"][~y] >= 0).mean())}) seeds = pd.DataFrame(rows) table = seeds.groupby(["f", "c"], as_index=False).mean(numeric_only=True).drop(columns="seed") table["seeds"] = seeds.groupby(["f", "c"])["seed"].nunique().to_numpy() table["expected_no_cue_ap_at_c0"] = [ms.expected_no_cue_ap(T2_PI, f) if np.isclose(c, 0) else np.nan for f, c in zip(table["f"], table["c"])] return table def t2_block(seeds, reference): block = {"settings": {}, "null_checks": {}} table = ms.summarise(seeds, ["f", "c"], T2_PI) for f, g in table.groupby("f"): block["settings"][f"f={f:.2f}"] = g.drop(columns="f").to_dict(orient="records") null = g[np.isclose(g["c"], 0.0)] if len(null): r = null.iloc[0] block["null_checks"][f"f={f:.2f}"] = ms.null_check(r["ap_mean"], [r["seed0_ci_low"], r["seed0_ci_high"]], T2_PI) | {"seeds": int(r["seeds"])} primary = seeds[np.isclose(seeds["f"], T2_F_PRIMARY)] complete = primary.groupby("c")["seed"].nunique().reindex(T2_C).fillna(0).eq(SEEDS).all() block["effective_cue_rate"] = {"f": T2_F_PRIMARY, "complete_grid": bool(complete)} if complete: block["effective_cue_rate"] |= { "reference_report": ms.interpolate_with_seeds(primary, "c", reference["ap"]), "reference_stated_0.461": ms.interpolate_with_seeds(primary, "c", T2_STATED)} return block, table def t3_block(seeds, reference): table = ms.summarise(seeds, ["s"], T3_PI) null = table[np.isclose(table["s"], 0.0)].iloc[0] oracle_null = ms.null_check(null["oracle_ap_mean"], None, T3_PI) block = {"settings": table.to_dict(orient="records"), "null_checks": {"depth_knn": ms.null_check(null["ap_mean"], [null["seed0_ci_low"], null["seed0_ci_high"]], T3_PI) | {"seeds": int(null["seeds"])}, "oracle_mean_ap_at_s0": oracle_null["mean_ap"]}, "effective_strength": { "reference_report": ms.interpolate_with_seeds(seeds, "s", reference["ap"]), "reference_stated_0.150": ms.interpolate_with_seeds(seeds, "s", T3_STATED)}} return block, table def main(): parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument("--arm", choices=["t2", "t3", "all", "report", "diagnose"], default="all") parser.add_argument("--shard", default="0/1", help="i/n: run the T2 plantings whose index modulo n is i") args = parser.parse_args() shard = tuple(int(v) for v in args.shard.split("/")) try: v6, digest = ms.verify_protocol(PROTOCOL, ROOT) except ValueError as error: raise SystemExit(str(error)) protocol, spec = m34.configuration() root, digests = m34.inputs(protocol) dest = root / "m5/synthetic" dest.mkdir(parents=True, exist_ok=True) if args.arm == "diagnose": table = diagnose_t2(dest) table.to_csv(dest / "null_diagnosis_t2.csv", index=False) print(table.round(4).to_string(index=False)) references = {"t2": real_t2_reference(root), "t3": real_t3_reference(root)} t3_path, t2_path = dest / "seeds_t3.csv", dest / "seeds_t2.csv" if args.arm in ("t3", "all"): run_t3(root, dest).to_csv(t3_path, index=False) if args.arm in ("t2", "all"): run_t2(root, dest, protocol, spec, digest, shard) t2 = collect_t2(dest, digest) if len(t2): t2.drop(columns="logistic_c").assign(logistic_c=t2["logistic_c"].map(json.dumps)).to_csv(t2_path, index=False) report = {"protocol": {"file": str(PROTOCOL.relative_to(ROOT)), "sha256": digest, "version": v6["version"], "cues_sha256": v6["inputs_hashed"]["configs/synth_cues.yaml"]}, "inputs": digests, "references": references, "design": { "seeds": [BASE_SEED + k for k in range(SEEDS)], "rng": "numpy default_rng([seed, round(1000 x " "setting) ...]); T2 settings (c, f), T3 setting s; one planting per seed and setting", "ci": {"resamples": RESAMPLES, "seed": CI_SEED, "cluster": "well", "function": "m5_t5.ap_ci"}, "t2_pi": T2_PI, "t3_pi": T3_PI, "lift": "AP / pi (nominal pi)", "t2_model": "m34_classify.fold_prediction (TF-IDF word 1-2 grams, min_df 2, sublinear tf, " "max_features 60000; logistic C from [0.25, 1, 4] by inner GroupKFold(5) on wells, " "average precision), leave-one-well-out, sequential folds", "t2_inputs": "well + text_xml only: the real T2 frame has no numeric column in the model allowlist " "(m34_classify.numeric_columns), so the baseline is text-only, as in M3-M4", "t2_cue_placement": "phrase appended after the activity comment with one space before the text is " "built; the real text construction (comments, previous, next, sum24Hr, " "forecast24Hr joined by [SEP]) then also carries a cued comment into the " "previous/next fields of adjacent activities of the same report " "(see exposure_* columns)", "t3_model": "m5_t5.knn_scores(features, planted, ['md_top']), k = 10, other wells", "t3_covariate": "z-score of md_top over the 4,894 cells (population sd)"}, "outputs": {}} if t3_path.is_file(): report["t3_hazard"], table = t3_block(pd.read_csv(t3_path), references["t3"]) table.to_csv(dest / "settings_t3.csv", index=False) if t2_path.is_file(): seeds = pd.read_csv(t2_path) report["t2_cues"], table = t2_block(seeds, references["t2"]) table.to_csv(dest / "settings_t2.csv", index=False) report["t2_cues"]["runs"] = int(len(seeds)) report["t2_cues"]["seconds_total"] = float(seeds["seconds"].sum()) if (dest / "null_diagnosis_t2.csv").is_file(): report["t2_cues"]["null_diagnosis_post_hoc"] = { "note": "not part of protocol v6: at c = 0 and f > 0 the absence of an own cue already points to a " "planted row, so the setting is not a null; c = f is", "rows": pd.read_csv(dest / "null_diagnosis_t2.csv").to_dict(orient="records")} report["outputs"] = sorted(p.name for p in dest.iterdir() if p.is_file() and p.name != "report.json") m34.atomic_write(dest / "report.json", json.dumps(report, indent=1, default=_json).encode()) def _json(value): if isinstance(value, (np.integer, np.floating)): return value.item() if isinstance(value, np.bool_): return bool(value) raise TypeError(type(value)) if __name__ == "__main__": main()