""" msc_analysis.py -- the Phase 0 analysis driver. `msc_core.py` is used AS-IS. Nothing in it is reimplemented. This module only drives it, and adds four corrections. Each exists because the naive version produces a *plausible number* rather than an obvious error: 1. COMMON MASK. `clean()` masks each run's own irreducible samples, so a pairwise analysis computes ceiling_A, ceiling_B and rho_S(A,B) on three different confidence-selected subsets while disattenuation assumes one population. Measured at tau=0.5: pairwise n ~ 4,500 vs common n = 2,050. 2. COMONOTONE BOUND. MSC takes K distinct values. Spearman between two K-level ordinals is capped BELOW 1 whenever their marginals differ, even under a perfectly monotone relationship (verified: 0.884 at K=5). The bias is one-directional and adverse: the ceiling is measured within-architecture (shared marginals, undepressed) while T is measured across (depressed), so T is biased toward "architecture-specific". 3. JOINT PAIRED BOOTSTRAP. `disattenuated_transfer` bootstraps the numerator against a FIXED denominator, so ceiling uncertainty never reaches the CI. 4. THREE-WAY DELTA R^2. Prediction depth is the same suffix-closure construction as MSC with k-NN probes, so leaving it in the battery suppresses Delta-R^2 definitionally. Plus one standing assertion: the shuffled control runs on EVERY cell and it RAISES. Non-zero shuffled transfer means the pipeline is manufacturing structure from permuted targets -- almost always row misalignment -- and no number from the analysis is usable. """ from __future__ import annotations import json from pathlib import Path from typing import Any, Dict, List, Optional, Sequence import numpy as np import pandas as pd from scipy import stats import msc_core as C import msc_data as D __version__ = "2.0.0" SHUFFLE_TOL = 0.05 BATTERY_FULL = list(D.BATTERY) BATTERY_NO_PD = [c for c in BATTERY_FULL if c != "pred_depth"] # --------------------------------------------------------------------------- # loading + alignment # --------------------------------------------------------------------------- def load_runs(paths: Dict[str, str]) -> Dict[str, pd.DataFrame]: """Load per-sample tables and assert they are row-aligned. The cheapest possible alignment test is that every run reports the same label for the same sample_idx. It catches a swapped mirror, a reordered loader, and drop_last=True -- most of what invariant I1 is about. """ dfs = {k: pd.read_parquet(v) for k, v in paths.items()} names = list(dfs) ref = dfs[names[0]] n = len(ref) for k, df in dfs.items(): if len(df) != n: raise AssertionError(f"{k} has {len(df)} rows, {names[0]} has {n}") D.assert_canonical_index(df["sample_idx"].to_numpy(), n) if not np.array_equal(df["label"].to_numpy(), ref["label"].to_numpy()): bad = int(np.argmax(df["label"].to_numpy() != ref["label"].to_numpy())) raise AssertionError( f"{k}: labels differ from {names[0]} at sample_idx {bad}.\n" f"THE RUNS ARE NOT ROW-ALIGNED. Every downstream number is void.") print(f"[ALIGN] {len(dfs)} runs x {n} rows; labels identical across all") return dfs def check_fingerprints(fps: Dict[str, Dict[str, str]]) -> None: names = list(fps) ref = fps[names[0]] for k in names[1:]: if fps[k] != ref: raise AssertionError( f"dataset fingerprint differs between {names[0]} and {k}. " f"The runs saw different data. Row alignment is void.") print(f"[ALIGN] dataset fingerprint identical across {len(names)} runs") def read_meta(path: str) -> Dict[str, Any]: import pyarrow.parquet as pq md = pq.read_schema(path).metadata or {} out = {} for k, v in md.items(): try: out[k.decode()] = json.loads(v.decode()) except Exception: pass return out # --------------------------------------------------------------------------- # MSC extraction # --------------------------------------------------------------------------- def msc_for(df: pd.DataFrame, axis: str, rho: Sequence[float], tau: float, cols: Sequence[str]) -> C.MSCResult: preds = np.stack([df[f"pred_{c}"].to_numpy() for c in cols], 1) t1 = np.stack([df[f"top1p_{c}"].to_numpy() for c in cols], 1) t2 = np.stack([df[f"top2p_{c}"].to_numpy() for c in cols], 1) return C.compute_msc(preds, t1, t2, rho, tau=tau, axis=axis) # --------------------------------------------------------------------------- # 1. common mask # --------------------------------------------------------------------------- def common_mask(results: Dict[str, C.MSCResult]) -> np.ndarray: m = None for r in results.values(): v = np.isfinite(r.clean()) m = v if m is None else (m & v) return m # --------------------------------------------------------------------------- # 2. comonotone bound # --------------------------------------------------------------------------- def comonotone_max(a: np.ndarray, b: np.ndarray) -> float: """Exact upper bound on Spearman given the two observed marginals. Pairing the sorted vectors is the comonotone coupling, which maximises rank correlation over every coupling preserving those marginals. """ a, b = np.asarray(a, float), np.asarray(b, float) m = np.isfinite(a) & np.isfinite(b) a, b = a[m], b[m] if a.size < 3: return float("nan") return C.spearman(np.sort(a), np.sort(b)) def kendall_tau_b(a: np.ndarray, b: np.ndarray) -> float: a, b = np.asarray(a, float), np.asarray(b, float) m = np.isfinite(a) & np.isfinite(b) a, b = a[m], b[m] if a.size < 3: return float("nan") return float(stats.kendalltau(a, b, variant="b").statistic) def contingency(a: np.ndarray, b: np.ndarray) -> pd.DataFrame: m = np.isfinite(a) & np.isfinite(b) return pd.crosstab(pd.Series(np.asarray(a)[m], name="A"), pd.Series(np.asarray(b)[m], name="B")) # --------------------------------------------------------------------------- # 3. joint paired bootstrap # --------------------------------------------------------------------------- def transfer_joint(a1, a2, b1, b2, mask, n_boot: int = 1000, seed: int = 0) -> Dict[str, Any]: """T and T_adj with a CI that includes ceiling uncertainty. All four vectors are restricted to the SAME common mask, so numerator and denominator describe one population. """ A1, A2, B1, B2 = (np.asarray(v, float)[mask] for v in (a1, a2, b1, b2)) n = A1.size c_a, c_b = C.spearman(A1, A2), C.spearman(B1, B2) raw = C.spearman(A1, B1) denom = np.sqrt(max(c_a, 1e-9) * max(c_b, 1e-9)) rmax = comonotone_max(A1, B1) T = raw / denom if denom > 0 else float("nan") T_adj = (T / rmax if rmax and np.isfinite(rmax) and rmax > 0 else float("nan")) rng = np.random.default_rng(seed) bt, bta = np.empty(n_boot), np.empty(n_boot) for i in range(n_boot): idx = rng.integers(0, n, n) ca = C.spearman(A1[idx], A2[idx]) cb = C.spearman(B1[idx], B2[idx]) rw = C.spearman(A1[idx], B1[idx]) d = np.sqrt(max(ca, 1e-9) * max(cb, 1e-9)) t = rw / d if d > 0 else np.nan bt[i] = t rm = comonotone_max(A1[idx], B1[idx]) bta[i] = t / rm if rm and rm > 0 else np.nan lo, hi = np.nanpercentile(bt, [2.5, 97.5]) alo, ahi = np.nanpercentile(bta, [2.5, 97.5]) return {"n": int(n), "ceiling_A": c_a, "ceiling_B": c_b, "spearman_raw": raw, "rho_max": rmax, "T": T, "T_ci95": (float(lo), float(hi)), "T_adj": T_adj, "T_adj_ci95": (float(alo), float(ahi)), "kendall_tau_b": kendall_tau_b(A1, B1)} # --------------------------------------------------------------------------- # standing shuffled control # --------------------------------------------------------------------------- def shuffled_control(a, b, mask, ceiling_a, ceiling_b, label: str, seed: int = 12345, raise_on_fail: bool = True) -> float: A = np.asarray(a, float)[mask] B = np.asarray(b, float)[mask] perm = np.random.default_rng(seed).permutation(B.size) denom = np.sqrt(max(ceiling_a, 1e-9) * max(ceiling_b, 1e-9)) t = C.spearman(A, B[perm]) / denom if denom > 0 else float("nan") if raise_on_fail and np.isfinite(t) and abs(t) >= SHUFFLE_TOL: raise AssertionError( f"SHUFFLED CONTROL FAILED for {label}: T_shuffled = {t:+.4f} " f"(tolerance {SHUFFLE_TOL}).\n" f"The pipeline is producing structure from permuted targets. Almost " f"certainly row misalignment between per-sample tables. NO NUMBER " f"FROM THIS ANALYSIS IS USABLE until it is found.") return float(t) # --------------------------------------------------------------------------- # top-set agreement (NOT a decile at K=5) # --------------------------------------------------------------------------- def top_set_agreement(a, b, mask, q: float = 0.9) -> Dict[str, Any]: A = np.asarray(a, float)[mask] B = np.asarray(b, float)[mask] ta, tb = np.quantile(A, q), np.quantile(B, q) sa, sb = A >= ta, B >= tb inter, union = int((sa & sb).sum()), int((sa | sb).sum()) return {"J_top": inter / union if union else float("nan"), "frac_A": float(sa.mean()), "frac_B": float(sb.mean()), "is_decile": bool(abs(sa.mean() - 0.1) < 0.02)} # --------------------------------------------------------------------------- # 4. three-way irreducibility # --------------------------------------------------------------------------- def irreducibility_three_way(df_source: pd.DataFrame, msc_source, msc_target, mask, n_boot: int = 500, seed: int = 0) -> Dict[str, Any]: out: Dict[str, Any] = {} src = np.asarray(msc_source, float)[mask] tgt = np.asarray(msc_target, float)[mask] variants = {"full_battery": BATTERY_FULL, "no_pred_depth": BATTERY_NO_PD, "pred_depth_only": ["pred_depth"]} for name, cols in variants.items(): have = [c for c in cols if c in df_source.columns] if not have: out[name] = {"error": f"columns absent: {cols}"} continue Dm = df_source.loc[mask, have].reset_index(drop=True) try: out[name] = C.irreducibility(src, tgt, Dm, n_boot=n_boot, seed=seed) out[name]["columns"] = have except Exception as e: out[name] = {"error": f"{type(e).__name__}: {e}"} have = [c for c in BATTERY_NO_PD if c in df_source.columns] if have: Dm = df_source.loc[mask, have].reset_index(drop=True) try: out["no_pred_depth_rank_target"] = C.irreducibility( src, stats.rankdata(tgt) / len(tgt), Dm, n_boot=n_boot, seed=seed) except Exception as e: out["no_pred_depth_rank_target"] = {"error": str(e)} return out # --------------------------------------------------------------------------- # the sweep # --------------------------------------------------------------------------- def run_phase0(dfs: Dict[str, pd.DataFrame], budgets: Dict[str, Any], run_ids: Dict[str, str], taus: Sequence[float] = (0.0, 0.1, 0.2, 0.3, 0.5), axes: Sequence[str] = ("depth", "resolution"), n_boot: int = 1000) -> Dict[str, Any]: """`run_ids` maps slots a1/a2/b1/b2 to run_id strings.""" for slot in ("a1", "a2", "b1", "b2"): if run_ids[slot] not in dfs: raise AssertionError( f"missing run {run_ids[slot]}. The analysis needs all four: the " f"ceiling requires both seeds of both architectures.") arch = {"a": budgets["_arch_a"], "b": budgets["_arch_b"]} rows, detail = [], {} for axis in axes: for tau in taus: res = {} for slot, rid in run_ids.items(): bud = budgets[arch[slot[0]]] if axis == "depth": rho = bud["rho_depth"] cols = D.axis_columns("depth", k_depth=len(rho)) else: rho = bud["rho_resolution"] cols = D.axis_columns(axis, bud["resolutions"]) res[slot] = msc_for(dfs[rid], axis, rho, tau, cols) mask = common_mask(res) n_common = int(mask.sum()) cl = {k: v.clean() for k, v in res.items()} if n_common < 50: rows.append({"axis": axis, "tau": tau, "n_common": n_common, "note": "too few jointly-valid samples"}) continue tr = transfer_joint(cl["a1"], cl["a2"], cl["b1"], cl["b2"], mask, n_boot=n_boot) t_sh = shuffled_control(cl["a1"], cl["b1"], mask, tr["ceiling_A"], tr["ceiling_B"], f"{axis}@tau={tau}") jt = top_set_agreement(cl["a1"], cl["b1"], mask) rows.append({ "axis": axis, "tau": tau, "n_common": n_common, "n_pairwise_A": int((np.isfinite(cl["a1"]) & np.isfinite(cl["a2"])).sum()), "frac_irr_a1": res["a1"].frac_irreducible, "frac_irr_b1": res["b1"].frac_irreducible, "ceiling_A": tr["ceiling_A"], "ceiling_B": tr["ceiling_B"], "ceiling_A_pairwise": C.spearman(cl["a1"], cl["a2"]), "spearman_raw": tr["spearman_raw"], "spearman_raw_pairwise": C.spearman(cl["a1"], cl["b1"]), "rho_max": tr["rho_max"], "T": tr["T"], "T_lo": tr["T_ci95"][0], "T_hi": tr["T_ci95"][1], "T_adj": tr["T_adj"], "T_adj_lo": tr["T_adj_ci95"][0], "T_adj_hi": tr["T_adj_ci95"][1], "kendall_tau_b": tr["kendall_tau_b"], "J_top": jt["J_top"], "J_top_fracA": jt["frac_A"], "T_shuffled": t_sh}) detail[f"{axis}@{tau}"] = { "transfer": tr, "top_set": jt, "contingency": contingency(cl["a1"][mask], cl["b1"][mask]).to_dict()} table = pd.DataFrame(rows) tau_ref = 0.1 if 0.1 in list(taus) else list(taus)[0] ba, bb = budgets[arch["a"]], budgets[arch["b"]] ra = msc_for(dfs[run_ids["a1"]], "depth", ba["rho_depth"], tau_ref, D.axis_columns("depth", k_depth=len(ba["rho_depth"]))) rb = msc_for(dfs[run_ids["b1"]], "depth", bb["rho_depth"], tau_ref, D.axis_columns("depth", k_depth=len(bb["rho_depth"]))) m4 = np.isfinite(ra.clean()) & np.isfinite(rb.clean()) q4 = (irreducibility_three_way(dfs[run_ids["a1"]], ra.clean(), rb.clean(), m4, n_boot=min(500, n_boot)) if m4.sum() >= 200 else {}) try: d_ = ra.clean() r_ = msc_for(dfs[run_ids["a1"]], "resolution", ba["rho_resolution"], tau_ref, D.axis_columns("resolution", ba["resolutions"])).clean() q2 = C.axis_structure({"depth": d_, "resolution": r_}) q2["spearman_matrix"] = q2["spearman_matrix"].to_dict() except Exception as e: q2 = {"error": f"{type(e).__name__}: {e}"} return {"table": table, "detail": detail, "q4": q4, "q2_preview": q2, "tau_ref": tau_ref} # --------------------------------------------------------------------------- # decision # --------------------------------------------------------------------------- def decide(table: pd.DataFrame, q4: Dict[str, Any]) -> Dict[str, Any]: """Apply the pre-committed rules from `01_PHASE0_GO_NOGO.md` §6.1. Written before any number existed, precisely so this function cannot be tuned to the result. """ d = table[(table.axis == "depth") & table["T"].notna()] if d.empty: return {"decision": "NO DATA", "notes": []} def passes(col, thr): hits = d[d[col] >= thr]["tau"].tolist() core = [t for t in hits if t in (0.1, 0.2)] return (len(hits) >= 3 and len(core) >= 1), hits ceil_ok, ceil_taus = passes("ceiling_A", 0.6) ceil_fail = int((d["ceiling_A"] < 0.4).sum()) >= 3 t_ok, t_taus = passes("T", 0.7) t_adj_ok, _ = passes("T_adj", 0.7) notes: List[str] = [] straddle = False for thr in (0.7, 0.5): disagree = int(((d["T"] >= thr) != (d["T_adj"] >= thr)).sum()) if disagree >= 2: straddle = True notes.append( f"RULE 1: T and T_adj fall on opposite sides of {thr} at " f"{disagree} tau values -> MARGINAL, coarsen to K=3. The " f"flattering number is not selected.") dr2_defer = False key = "no_pred_depth" if key in q4 and "delta_r2" in q4[key]: lo, hi = q4[key]["delta_r2_ci95"] if lo < 0.02 < hi: dr2_defer = True notes.append( f"RULE 3: Delta R^2 = {q4[key]['delta_r2']:.4f}, CI " f"[{lo:.4f}, {hi:.4f}] spans 0.02 -> Q4 INCONCLUSIVE at Phase 0 " f"scale, deferred to Phase 1. The reframe row does NOT fire.") ceil_med = float(d["ceiling_A"].median()) t_med = float(d["T"].median()) if ceil_fail: decision = ("FAIL — MSC is noise-dominated. One retry at K=3 on the " "EXISTING checkpoints, then the fallback direction.") elif not ceil_ok and ceil_med < 0.6: decision = ("MARGINAL — coarsen to K=3 well-separated budgets and " "re-run the analysis. No retraining.") elif straddle: decision = "MARGINAL (rule 1) — coarsen to K=3." elif t_ok and t_adj_ok: if dr2_defer: decision = "FULL PROGRAM, with Q4 deferred to Phase 1." elif key in q4 and q4[key].get("delta_r2", 1.0) < 0.02: decision = ("REFRAME — MSC == difficulty. 'Cheap difficulty scores " "suffice for compute routing.' Skip the multi-axis " "oracle.") else: decision = ("FULL PROGRAM — proceed to the Phase 1 atlas and build " "the method.") elif t_med < 0.5: decision = ("PIVOT TO THE STRONG NEGATIVE — 'per-sample compute " "requirements are architecture-specific'. Expand the atlas " "across families instead of building the method. This is a " "better paper than the method paper.") else: decision = "MARGINAL — T in the 0.5-0.7 band. Coarsen to K=3." return {"decision": decision, "ceiling_median": ceil_med, "ceiling_pass_taus": ceil_taus, "T_median": t_med, "T_pass_taus": t_taus, "T_adj_median": float(d["T_adj"].median()), "notes": notes} def write_decision(out_dir, result: Dict[str, Any], dec: Dict[str, Any]) -> Path: out = Path(out_dir) out.mkdir(parents=True, exist_ok=True) result["table"].to_csv(out / "phase0_table.csv", index=False) (out / "phase0_q4.json").write_text( json.dumps(result["q4"], indent=2, default=str)) (out / "phase0_q2_preview.json").write_text( json.dumps(result["q2_preview"], indent=2, default=str)) lines = ["# Phase 0 decision", "", f"Generated: {pd.Timestamp.utcnow().isoformat()}", "", "## Decision", "", f"**{dec['decision']}**", "", "## Supporting numbers", "", f"- seed ceiling (depth), median over tau: " f"**{dec['ceiling_median']:.3f}** " f"(>=0.6 at tau {dec['ceiling_pass_taus']})", f"- T (depth), median over tau: **{dec['T_median']:.3f}** " f"(>=0.7 at tau {dec['T_pass_taus']})", f"- T_adj (depth), median over tau: **{dec['T_adj_median']:.3f}**", ""] if dec["notes"]: lines += ["## Pre-committed rules that fired", ""] lines += [f"- {n}" for n in dec["notes"]] + [""] lines += ["## Full tau curve", "", result["table"].to_markdown(index=False), ""] (out / "phase0_decision.md").write_text("\n".join(lines), encoding="utf-8") print(f"[WRITE] {out/'phase0_decision.md'}") return out / "phase0_decision.md"