Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_label_marker.py +159 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_main.py +297 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_sensitivity.py +140 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/within_analysis.py +378 -0
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_label_marker.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Independent recompute (verify lens) of the within-3 label/marker check (CPU only; 2026-10-05).
|
| 3 |
+
|
| 4 |
+
Generated side: work/sepsis/fold0/<arm>.npz. T cells: aifi_l1 or aifi_l2 == 'T cell'; label-called proliferating T:
|
| 5 |
+
aifi_l2 == 'Proliferating T cell' within T; cycling: >= 2 of MKI67 TOP2A TYMS CENPF UBE2C BIRC5 with count > 0.
|
| 6 |
+
Observed side: tools/sepsis_states.observed() for the 17 fold-0 donors (read-only loader), binomially thinned per arm
|
| 7 |
+
with that arm's T-parent thin (= the 'ISG-high T' thin: median generated T library / median observed T library),
|
| 8 |
+
seed 20261005; the thinning is also repeated over 50 extra seeds to show its Monte Carlo spread.
|
| 9 |
+
Uncertainty: Wilson 95% intervals per proportion; donor bootstrap (2000 reps, seed 20261005, donors sorted, the same idx
|
| 10 |
+
for both arms) of the matched scratch - pretrained differences.
|
| 11 |
+
Output: verify_recompute_within_label_marker.csv, verify_recompute_within_label_marker_diffs.csv
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import importlib.util
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
|
| 20 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import numpy as np
|
| 26 |
+
import pandas as pd
|
| 27 |
+
from scipy.stats import fisher_exact, norm
|
| 28 |
+
|
| 29 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 30 |
+
W = PLAN / "work/sepsis/fold0"
|
| 31 |
+
V = PLAN / "out/scratch_vs_lora_20261005"
|
| 32 |
+
PFX = "verify_recompute_within_"
|
| 33 |
+
SEED, B = 20261005, 2000
|
| 34 |
+
CYC = ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"]
|
| 35 |
+
ARMS = ["zs__raw", "lora_n5__raw", "scratch_n5__raw", "real_lora__raw", "real_full__raw", "scratch_full__raw",
|
| 36 |
+
"lora_recipe__raw", "scratch_recipe__raw"]
|
| 37 |
+
MAIN = [("5 pairs", "scratch_n5__raw", "lora_n5__raw"),
|
| 38 |
+
("58 pairs vs LoRA", "scratch_full__raw", "real_lora__raw"),
|
| 39 |
+
("58 pairs vs full FT", "scratch_full__raw", "real_full__raw"),
|
| 40 |
+
("recipes", "scratch_recipe__raw", "lora_recipe__raw")]
|
| 41 |
+
|
| 42 |
+
spec = importlib.util.spec_from_file_location("sepsis_states_ro", PLAN / "tools/sepsis_states.py")
|
| 43 |
+
ss = importlib.util.module_from_spec(spec)
|
| 44 |
+
sys.path.insert(0, str(PLAN / "tools"))
|
| 45 |
+
spec.loader.exec_module(ss)
|
| 46 |
+
|
| 47 |
+
states = json.loads((PLAN / "tools/states.json").read_text())
|
| 48 |
+
G = {a: np.load(W / f"{a}.npz", allow_pickle=False) for a in ARMS}
|
| 49 |
+
DONORS = sorted(set(G[ARMS[0]]["donor"].astype(str)))
|
| 50 |
+
assert len(DONORS) == 17
|
| 51 |
+
ob = ss.observed(states, DONORS)
|
| 52 |
+
osyms = list(ob["marker_symbols"])
|
| 53 |
+
ocyc = [osyms.index(g) for g in CYC]
|
| 54 |
+
oT = (ob["lab"].aifi_l1.to_numpy() == "T cell") | (ob["lab"].aifi_l2.to_numpy() == "T cell")
|
| 55 |
+
oPT = oT & (ob["lab"].aifi_l2.to_numpy() == "Proliferating T cell")
|
| 56 |
+
odon = ob["donor"]
|
| 57 |
+
oco = ob["markers"][:, ocyc].astype(np.int64)
|
| 58 |
+
olib = ob["lib"]
|
| 59 |
+
|
| 60 |
+
PD = pd.read_csv(PLAN / "out/sepsis_fold0_per_donor.csv")
|
| 61 |
+
SUMM = pd.read_csv(PLAN / "out/sepsis_fold0_summary.csv")
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def wilson(k: int, n: int) -> tuple[float, float]:
|
| 65 |
+
if n == 0:
|
| 66 |
+
return (np.nan, np.nan)
|
| 67 |
+
z = norm.ppf(0.975)
|
| 68 |
+
p = k / n
|
| 69 |
+
c = (p + z * z / (2 * n)) / (1 + z * z / n)
|
| 70 |
+
h = z * np.sqrt(p * (1 - p) / n + z * z / (4 * n * n)) / (1 + z * z / n)
|
| 71 |
+
return (100 * (c - h), 100 * (c + h))
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def per_donor(don: np.ndarray, T: np.ndarray, PT: np.ndarray, cyc: np.ndarray) -> np.ndarray:
|
| 75 |
+
"""(17, 4): T cells, cycling T cells, PT-label cells, cycling PT-label cells."""
|
| 76 |
+
out = np.zeros((17, 4))
|
| 77 |
+
for i, d in enumerate(DONORS):
|
| 78 |
+
m = don == d
|
| 79 |
+
out[i] = [(T & m).sum(), (T & m & cyc).sum(), (PT & m).sum(), (PT & m & cyc).sum()]
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
rows, PDON = [], {}
|
| 84 |
+
checks = []
|
| 85 |
+
obs_native_cyc = (oco > 0).sum(1) >= 2
|
| 86 |
+
PDON["observed (native)"] = per_donor(odon, oT, oPT, obs_native_cyc)
|
| 87 |
+
for a in ARMS:
|
| 88 |
+
g = G[a]
|
| 89 |
+
syms = list(g["marker_symbols"].astype(str))
|
| 90 |
+
assert syms == osyms, a
|
| 91 |
+
gT = (g["aifi_l1"].astype(str) == "T cell") | (g["aifi_l2"].astype(str) == "T cell")
|
| 92 |
+
gPT = gT & (g["aifi_l2"].astype(str) == "Proliferating T cell")
|
| 93 |
+
gcyc = (g["markers"][:, [syms.index(x) for x in CYC]] > 0).sum(1) >= 2
|
| 94 |
+
gdon = g["donor"].astype(str)
|
| 95 |
+
PDON[a] = per_donor(gdon, gT, gPT, gcyc)
|
| 96 |
+
thin = min(1.0, float(np.median(g["lib_measured"][gT])) / float(np.median(olib[oT])))
|
| 97 |
+
# cross-checks against the per-donor CSV (T parent counts, PT-label counts) and the summary thin of ISG-high T
|
| 98 |
+
pdT = PD[(PD.arm == a) & (PD.state == "ISG-high T")].set_index("donor").loc[DONORS]
|
| 99 |
+
pdPT = PD[(PD.arm == a) & (PD.state == "Proliferating T (label)")].set_index("donor").loc[DONORS]
|
| 100 |
+
checks.append({"arm": a, "gen_T_match": bool((pdT.gen_parent.to_numpy() == PDON[a][:, 0]).all()),
|
| 101 |
+
"obs_T_match": bool((pdT.obs_parent.to_numpy() == PDON["observed (native)"][:, 0]).all()),
|
| 102 |
+
"gen_PT_match": bool((pdPT.gen_state.to_numpy() == PDON[a][:, 2]).all()),
|
| 103 |
+
"obs_PT_match": bool((pdPT.obs_state.to_numpy() == PDON["observed (native)"][:, 2]).all()),
|
| 104 |
+
"thin_recomputed": thin,
|
| 105 |
+
"thin_summary_isgT": float(SUMM[(SUMM.arm == a) & (SUMM.state == "ISG-high T")].thin.iloc[0])})
|
| 106 |
+
tot = PDON[a].sum(0)
|
| 107 |
+
rows.append({"side": "generated", "arm": a, "thin": np.nan, "n_T": int(tot[0]), "n_T_cycling": int(tot[1]),
|
| 108 |
+
"n_PT_label": int(tot[2]), "n_PT_label_cycling": int(tot[3])})
|
| 109 |
+
# observed thinned to this arm's T depth: main seed, then 50 extra seeds for the Monte Carlo spread
|
| 110 |
+
rng = np.random.default_rng(SEED)
|
| 111 |
+
oc = (rng.binomial(oco, thin) > 0).sum(1) >= 2 if thin < 1.0 else obs_native_cyc
|
| 112 |
+
PDON[f"observed thinned for {a}"] = per_donor(odon, oT, oPT, oc)
|
| 113 |
+
tot = PDON[f"observed thinned for {a}"].sum(0)
|
| 114 |
+
mc_pt, mc_t = [], []
|
| 115 |
+
if thin < 1.0:
|
| 116 |
+
for s in range(50):
|
| 117 |
+
r2 = np.random.default_rng(SEED + 1 + s)
|
| 118 |
+
c2 = (r2.binomial(oco[oT], thin) > 0).sum(1) >= 2
|
| 119 |
+
mc_t.append(100 * c2.sum() / oT.sum())
|
| 120 |
+
mc_pt.append(100 * c2[oPT[oT]].sum() / oPT.sum())
|
| 121 |
+
rows.append({"side": "observed thinned", "arm": a, "thin": thin, "n_T": int(tot[0]), "n_T_cycling": int(tot[1]),
|
| 122 |
+
"n_PT_label": int(tot[2]), "n_PT_label_cycling": int(tot[3]),
|
| 123 |
+
"mc50_pct_PT_passing_min": min(mc_pt) if mc_pt else np.nan,
|
| 124 |
+
"mc50_pct_PT_passing_max": max(mc_pt) if mc_pt else np.nan,
|
| 125 |
+
"mc50_pct_T_cycling_min": min(mc_t) if mc_t else np.nan,
|
| 126 |
+
"mc50_pct_T_cycling_max": max(mc_t) if mc_t else np.nan})
|
| 127 |
+
tot = PDON["observed (native)"].sum(0)
|
| 128 |
+
rows.append({"side": "observed native", "arm": "-", "thin": 1.0, "n_T": int(tot[0]), "n_T_cycling": int(tot[1]),
|
| 129 |
+
"n_PT_label": int(tot[2]), "n_PT_label_cycling": int(tot[3])})
|
| 130 |
+
R = pd.DataFrame(rows)
|
| 131 |
+
R["pct_of_PT_label_passing_cycling_rule"] = 100 * R.n_PT_label_cycling / R.n_PT_label
|
| 132 |
+
R["cycling_rule_pct_of_T"] = 100 * R.n_T_cycling / R.n_T
|
| 133 |
+
R[["pt_wilson_lo", "pt_wilson_hi"]] = [wilson(k, n) for k, n in zip(R.n_PT_label_cycling, R.n_PT_label)]
|
| 134 |
+
R[["t_wilson_lo", "t_wilson_hi"]] = [wilson(k, n) for k, n in zip(R.n_T_cycling, R.n_T)]
|
| 135 |
+
R.to_csv(V / f"{PFX}label_marker.csv", index=False)
|
| 136 |
+
C = pd.DataFrame(checks)
|
| 137 |
+
with pd.option_context("display.width", 250, "display.max_columns", 30):
|
| 138 |
+
print(C.to_string(index=False))
|
| 139 |
+
print(R.round(3).to_string(index=False))
|
| 140 |
+
|
| 141 |
+
# matched differences: Fisher exact on pooled counts + donor bootstrap of the pooled-proportion difference
|
| 142 |
+
idx = np.random.default_rng(SEED).integers(0, 17, (B, 17))
|
| 143 |
+
Wm = np.stack([np.bincount(r, minlength=17) for r in idx]).astype(float)
|
| 144 |
+
drows = []
|
| 145 |
+
for name, sa, pa in MAIN:
|
| 146 |
+
for metric, (kk, nn) in (("pct_PT_label_passing", (3, 2)), ("pct_T_cycling", (1, 0))):
|
| 147 |
+
Xs, Xp = PDON[sa], PDON[pa]
|
| 148 |
+
ks, ns, kp, np_ = Xs[:, kk].sum(), Xs[:, nn].sum(), Xp[:, kk].sum(), Xp[:, nn].sum()
|
| 149 |
+
est = 100 * (ks / ns - kp / np_)
|
| 150 |
+
bs = 100 * ((Wm @ Xs[:, kk]) / (Wm @ Xs[:, nn]) - (Wm @ Xp[:, kk]) / (Wm @ Xp[:, nn]))
|
| 151 |
+
lo, hi = np.nanpercentile(bs, [2.5, 97.5])
|
| 152 |
+
p = fisher_exact([[ks, ns - ks], [kp, np_ - kp]]).pvalue
|
| 153 |
+
drows.append({"comparison": name, "metric": metric, "scratch_k_n": f"{int(ks)}/{int(ns)}",
|
| 154 |
+
"pretrained_k_n": f"{int(kp)}/{int(np_)}", "diff_scratch_minus_pretrained_pp": est,
|
| 155 |
+
"donor_boot_lo": lo, "donor_boot_hi": hi, "fisher_p": p})
|
| 156 |
+
D = pd.DataFrame(drows)
|
| 157 |
+
D.to_csv(V / f"{PFX}label_marker_diffs.csv", index=False)
|
| 158 |
+
with pd.option_context("display.width", 250, "display.max_columns", 30):
|
| 159 |
+
print(D.round(4).to_string(index=False))
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_main.py
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Independent recompute (verify lens) of the within-cohort scratch-vs-pretrained claims (CPU only; 2026-10-05).
|
| 3 |
+
|
| 4 |
+
Input: only out/sepsis_fold0_per_donor.csv (plus sepsis_fold0_summary.csv / sepsis_fold0_contrasts.csv as cross-checks
|
| 5 |
+
of the per-donor CSV itself). No analyst file (within_*.csv) is read.
|
| 6 |
+
|
| 7 |
+
Pooled ratio per arm and state: r = ((sum gen_state + pc) / sum gen_parent) / ((sum obsthin_state + pc) / sum obs_parent)
|
| 8 |
+
with pc = 0.5 (fidelity |log2 r|) and pc = 0 (plain ratio = summary gen_over_obs).
|
| 9 |
+
D = |log2 r|(scratch arm) - |log2 r|(pretrained arm): > 0 means the pretrained arm is closer to the observed frequency.
|
| 10 |
+
Donor bootstrap: donors sorted by name, idx = default_rng(20261005).integers(0, 17, (2000, 17)), the same idx for both
|
| 11 |
+
arms, all four sums recomputed on donors[idx[b]]. Percentile CI (2.5 / 97.5) and, as a sensitivity, Efron's
|
| 12 |
+
bias-corrected (BC) percentile CI. Spearman: over donors with both pcts defined; bootstrap Spearman on resampled rows
|
| 13 |
+
(average ranks), undefined replicates reported.
|
| 14 |
+
Outputs (prefix verify_recompute_within_): fidelity.csv, bootstrap.csv, spearman.csv, contrasts.csv, contrast_counts.csv
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 21 |
+
|
| 22 |
+
from pathlib import Path
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
from scipy.stats import norm, rankdata, spearmanr
|
| 27 |
+
|
| 28 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 29 |
+
OUT = PLAN / "out"
|
| 30 |
+
V = OUT / "scratch_vs_lora_20261005"
|
| 31 |
+
PFX = "verify_recompute_within_"
|
| 32 |
+
SEED, B = 20261005, 2000
|
| 33 |
+
|
| 34 |
+
P = pd.read_csv(OUT / "sepsis_fold0_per_donor.csv")
|
| 35 |
+
SUMM = pd.read_csv(OUT / "sepsis_fold0_summary.csv")
|
| 36 |
+
CON = pd.read_csv(OUT / "sepsis_fold0_contrasts.csv")
|
| 37 |
+
|
| 38 |
+
ARMS = list(dict.fromkeys(P.arm))
|
| 39 |
+
STATES = list(dict.fromkeys(P.state))
|
| 40 |
+
CTRL = {"ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"}
|
| 41 |
+
RARE = [s for s in STATES if s not in CTRL]
|
| 42 |
+
DONORS = sorted(P.donor.unique())
|
| 43 |
+
assert len(RARE) == 13 and len(DONORS) == 17 and len(ARMS) == 8, (len(RARE), len(DONORS), len(ARMS))
|
| 44 |
+
TRAINED = [a for a in ARMS if a != "zs__raw"]
|
| 45 |
+
MAIN = [("5 pairs", "scratch_n5__raw", "lora_n5__raw"),
|
| 46 |
+
("58 pairs vs LoRA", "scratch_full__raw", "real_lora__raw"),
|
| 47 |
+
("58 pairs vs full FT", "scratch_full__raw", "real_full__raw"),
|
| 48 |
+
("recipes", "scratch_recipe__raw", "lora_recipe__raw")]
|
| 49 |
+
REFC = [("zs ref: 5 pairs", "scratch_n5__raw", "zs__raw"),
|
| 50 |
+
("zs ref: 58 pairs", "scratch_full__raw", "zs__raw"),
|
| 51 |
+
("zs ref: recipes", "scratch_recipe__raw", "zs__raw")]
|
| 52 |
+
COLS = ["gen_state", "gen_parent", "obsthin_state", "obs_parent"]
|
| 53 |
+
|
| 54 |
+
# ---- per-donor arrays in DONORS order -------------------------------------------------------------------------
|
| 55 |
+
X = {}
|
| 56 |
+
for (a, s), g in P.groupby(["arm", "state"], sort=False):
|
| 57 |
+
assert g.donor.is_unique and len(g) == 17, (a, s)
|
| 58 |
+
X[(a, s)] = g.set_index("donor").loc[DONORS, COLS].to_numpy(float)
|
| 59 |
+
GROUP = P.drop_duplicates("donor").set_index("donor").group
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def ratio(sums: np.ndarray, pc: float) -> np.ndarray:
|
| 63 |
+
gs, gp, os_, op = (sums[..., i] for i in range(4))
|
| 64 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 65 |
+
return ((gs + pc) / gp) / ((os_ + pc) / op)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def fid(sums: np.ndarray, pc: float = 0.5) -> np.ndarray:
|
| 69 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 70 |
+
return np.abs(np.log2(ratio(sums, pc)))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def pct(arr: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 74 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 75 |
+
g = np.where(arr[:, 1] > 0, 100 * arr[:, 0] / arr[:, 1], np.nan)
|
| 76 |
+
o = np.where(arr[:, 3] > 0, 100 * arr[:, 2] / arr[:, 3], np.nan)
|
| 77 |
+
return g, o
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ---- 0. integrity cross-checks of the per-donor CSV ----------------------------------------------------------
|
| 81 |
+
chk = []
|
| 82 |
+
for a in ARMS:
|
| 83 |
+
for s in STATES:
|
| 84 |
+
tot = X[(a, s)].sum(0)
|
| 85 |
+
r0 = float(ratio(tot, 0.0))
|
| 86 |
+
srow = SUMM[(SUMM.arm == a) & (SUMM.state == s)].iloc[0]
|
| 87 |
+
g, o = pct(X[(a, s)])
|
| 88 |
+
m = np.isfinite(g) & np.isfinite(o)
|
| 89 |
+
rho = spearmanr(g[m], o[m]).correlation
|
| 90 |
+
chk.append({"arm": a, "state": s, "ratio_recomputed": r0, "summary_gen_over_obs": srow.gen_over_obs,
|
| 91 |
+
"rho_recomputed": rho, "summary_spearman": srow.spearman_donors,
|
| 92 |
+
"gen_str": f"{int(tot[0]):,} / {int(tot[1]):,}", "summary_gen": srow.gen,
|
| 93 |
+
"obs_str": f"{int(tot[2]):,} / {int(tot[3]):,}", "summary_obs": srow.obs_thinned})
|
| 94 |
+
chk = pd.DataFrame(chk)
|
| 95 |
+
bad_r = (chk.ratio_recomputed - chk.summary_gen_over_obs).abs().max()
|
| 96 |
+
bad_rho = (chk.rho_recomputed - chk.summary_spearman).abs().max()
|
| 97 |
+
bad_str = int(((chk.gen_str != chk.summary_gen) | (chk.obs_str != chk.summary_obs)).sum())
|
| 98 |
+
print(f"[check] max |ratio - summary| = {bad_r:.2e}; max |rho - summary| = {bad_rho:.2e}; count-string mismatches = {bad_str}")
|
| 99 |
+
|
| 100 |
+
# ---- 1. point estimates per arm and state --------------------------------------------------------------------
|
| 101 |
+
rows = []
|
| 102 |
+
for a in ARMS:
|
| 103 |
+
for s in STATES:
|
| 104 |
+
tot = X[(a, s)].sum(0)
|
| 105 |
+
g, o = pct(X[(a, s)])
|
| 106 |
+
m = np.isfinite(g) & np.isfinite(o)
|
| 107 |
+
rows.append({"arm": a, "state": s, "rare": s in RARE, "gen_state": int(tot[0]), "gen_parent": int(tot[1]),
|
| 108 |
+
"obsthin_state": int(tot[2]), "obs_parent": int(tot[3]),
|
| 109 |
+
"ratio_pc0": float(ratio(tot, 0.0)), "ratio_pc05": float(ratio(tot, 0.5)),
|
| 110 |
+
"abs_log2_pc05": float(fid(tot, 0.5)), "abs_log2_pc0": float(fid(tot, 0.0)),
|
| 111 |
+
"spearman": float(spearmanr(g[m], o[m]).correlation), "n_donors_spearman": int(m.sum())})
|
| 112 |
+
F = pd.DataFrame(rows)
|
| 113 |
+
agg = F[F.rare].groupby("arm").agg(mean_abs_log2_pc05=("abs_log2_pc05", "mean"),
|
| 114 |
+
mean_abs_log2_pc0=("abs_log2_pc0", "mean"),
|
| 115 |
+
mean_spearman=("spearman", "mean")).reindex(ARMS)
|
| 116 |
+
print(agg.round(3).to_string())
|
| 117 |
+
F.to_csv(V / f"{PFX}fidelity.csv", index=False)
|
| 118 |
+
|
| 119 |
+
# ---- 2. donor bootstrap ----------------------------------------------------------------------------------------
|
| 120 |
+
idx = np.random.default_rng(SEED).integers(0, 17, (B, 17))
|
| 121 |
+
W = np.stack([np.bincount(r, minlength=17) for r in idx]).astype(float) # (B, 17) donor multiplicities
|
| 122 |
+
BOOT = {k: W @ v for k, v in X.items()} # (B, 4) resampled sums
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def bc_ci(boot: np.ndarray, est: float, ties: bool = False) -> tuple[float, float]:
|
| 126 |
+
b = boot[np.isfinite(boot)]
|
| 127 |
+
if not np.isfinite(est) or len(b) == 0:
|
| 128 |
+
return (np.nan, np.nan)
|
| 129 |
+
p = (np.sum(b < est) + (0.5 * np.sum(b == est) if ties else 0.0)) / len(b)
|
| 130 |
+
if p <= 0 or p >= 1:
|
| 131 |
+
return (np.nan, np.nan)
|
| 132 |
+
z0 = norm.ppf(p)
|
| 133 |
+
lo, hi = norm.cdf(2 * z0 + norm.ppf(0.025)), norm.cdf(2 * z0 + norm.ppf(0.975))
|
| 134 |
+
return tuple(np.percentile(b, [100 * lo, 100 * hi]))
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def verdict(lo: float, hi: float) -> str:
|
| 138 |
+
if not (np.isfinite(lo) and np.isfinite(hi)):
|
| 139 |
+
return "undefined"
|
| 140 |
+
if lo > 0:
|
| 141 |
+
return "pretrained closer"
|
| 142 |
+
if hi < 0:
|
| 143 |
+
return "scratch closer"
|
| 144 |
+
return "n.s."
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
brows = []
|
| 148 |
+
for kind, comps in (("main", MAIN), ("reference", REFC)):
|
| 149 |
+
for name, sa, pa in comps:
|
| 150 |
+
Dst, Dbs = {}, {}
|
| 151 |
+
for s in STATES:
|
| 152 |
+
Dst[s] = float(fid(X[(sa, s)].sum(0)) - fid(X[(pa, s)].sum(0)))
|
| 153 |
+
Dbs[s] = fid(BOOT[(sa, s)]) - fid(BOOT[(pa, s)])
|
| 154 |
+
for s in STATES + ["MEAN13"]:
|
| 155 |
+
if s == "MEAN13":
|
| 156 |
+
est = float(np.mean([Dst[t] for t in RARE]))
|
| 157 |
+
boot = np.mean(np.stack([Dbs[t] for t in RARE], 1), 1)
|
| 158 |
+
fs = float(np.mean([fid(X[(sa, t)].sum(0)) for t in RARE]))
|
| 159 |
+
fp = float(np.mean([fid(X[(pa, t)].sum(0)) for t in RARE]))
|
| 160 |
+
rs = rp = np.nan
|
| 161 |
+
else:
|
| 162 |
+
est, boot = Dst[s], Dbs[s]
|
| 163 |
+
fs, fp = float(fid(X[(sa, s)].sum(0))), float(fid(X[(pa, s)].sum(0)))
|
| 164 |
+
rs, rp = float(ratio(X[(sa, s)].sum(0), 0.0)), float(ratio(X[(pa, s)].sum(0), 0.0))
|
| 165 |
+
fin = np.isfinite(boot)
|
| 166 |
+
lo, hi = np.percentile(boot[fin], [2.5, 97.5])
|
| 167 |
+
blo, bhi = bc_ci(boot, est)
|
| 168 |
+
tlo, thi = bc_ci(boot, est, ties=True)
|
| 169 |
+
brows.append({"kind": kind, "comparison": name, "scratch_arm": sa, "pretrained_arm": pa, "state": s,
|
| 170 |
+
"rare": s in RARE or s == "MEAN13", "ratio_scratch_pc0": rs, "ratio_pretrained_pc0": rp,
|
| 171 |
+
"abs_log2_scratch": fs, "abs_log2_pretrained": fp, "D": est,
|
| 172 |
+
"D_ci_lo": lo, "D_ci_hi": hi, "D_bc_ci_lo": blo, "D_bc_ci_hi": bhi,
|
| 173 |
+
"D_bc_ties_lo": tlo, "D_bc_ties_hi": thi, "boot_mean": float(np.mean(boot[fin])),
|
| 174 |
+
"boot_frac_below_est": float(np.mean(boot[fin] < est)), "n_finite": int(fin.sum()),
|
| 175 |
+
"verdict_pct": verdict(lo, hi), "verdict_bc": verdict(blo, bhi)})
|
| 176 |
+
BT = pd.DataFrame(brows)
|
| 177 |
+
BT.to_csv(V / f"{PFX}bootstrap.csv", index=False)
|
| 178 |
+
with pd.option_context("display.width", 250, "display.max_rows", 500, "display.max_columns", 30):
|
| 179 |
+
show = ["comparison", "state", "ratio_scratch_pc0", "ratio_pretrained_pc0", "abs_log2_scratch",
|
| 180 |
+
"abs_log2_pretrained", "D", "D_ci_lo", "D_ci_hi", "D_bc_ci_lo", "D_bc_ci_hi", "verdict_pct", "verdict_bc"]
|
| 181 |
+
print(BT[show].round(3).to_string(index=False))
|
| 182 |
+
m = BT[(BT.state != "MEAN13") & BT.rare]
|
| 183 |
+
print(m.groupby(["kind", "comparison"], sort=False).verdict_pct.value_counts().unstack(fill_value=0))
|
| 184 |
+
print(m.groupby(["kind", "comparison"], sort=False).verdict_bc.value_counts().unstack(fill_value=0))
|
| 185 |
+
|
| 186 |
+
# ---- 3. Spearman point + bootstrap --------------------------------------------------------------------------------
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def boot_spearman(g: np.ndarray, o: np.ndarray) -> np.ndarray:
|
| 190 |
+
gb, ob = g[idx], o[idx]
|
| 191 |
+
out = np.full(B, np.nan)
|
| 192 |
+
if np.isfinite(g).all() and np.isfinite(o).all():
|
| 193 |
+
rg, ro = rankdata(gb, axis=1), rankdata(ob, axis=1)
|
| 194 |
+
rg -= rg.mean(1, keepdims=True)
|
| 195 |
+
ro -= ro.mean(1, keepdims=True)
|
| 196 |
+
den = np.sqrt((rg ** 2).sum(1) * (ro ** 2).sum(1))
|
| 197 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 198 |
+
out = np.where(den > 0, (rg * ro).sum(1) / den, np.nan)
|
| 199 |
+
return out
|
| 200 |
+
for b in range(B):
|
| 201 |
+
m = np.isfinite(gb[b]) & np.isfinite(ob[b])
|
| 202 |
+
x, y = gb[b][m], ob[b][m]
|
| 203 |
+
if m.sum() > 2 and np.ptp(x) > 0 and np.ptp(y) > 0:
|
| 204 |
+
out[b] = spearmanr(x, y).correlation
|
| 205 |
+
return out
|
| 206 |
+
|
| 207 |
+
|
| 208 |
+
SP = {}
|
| 209 |
+
for a in ARMS:
|
| 210 |
+
for s in STATES:
|
| 211 |
+
g, o = pct(X[(a, s)])
|
| 212 |
+
SP[(a, s)] = boot_spearman(g, o)
|
| 213 |
+
|
| 214 |
+
srows = []
|
| 215 |
+
for kind, comps in (("main", MAIN), ("reference", REFC)):
|
| 216 |
+
for name, sa, pa in comps:
|
| 217 |
+
for s in STATES + ["MEAN13"]:
|
| 218 |
+
if s == "MEAN13":
|
| 219 |
+
rs = float(np.mean([F[(F.arm == sa) & (F.state == t)].spearman.iloc[0] for t in RARE]))
|
| 220 |
+
rp = float(np.mean([F[(F.arm == pa) & (F.state == t)].spearman.iloc[0] for t in RARE]))
|
| 221 |
+
Ms = np.stack([SP[(sa, t)] for t in RARE], 1)
|
| 222 |
+
Mp = np.stack([SP[(pa, t)] for t in RARE], 1)
|
| 223 |
+
d = Mp - Ms
|
| 224 |
+
boot = np.mean(d, 1)
|
| 225 |
+
boot_nan = np.nanmean(d, 1)
|
| 226 |
+
else:
|
| 227 |
+
rs = float(F[(F.arm == sa) & (F.state == s)].spearman.iloc[0])
|
| 228 |
+
rp = float(F[(F.arm == pa) & (F.state == s)].spearman.iloc[0])
|
| 229 |
+
boot = SP[(pa, s)] - SP[(sa, s)]
|
| 230 |
+
boot_nan = boot
|
| 231 |
+
fin = np.isfinite(boot)
|
| 232 |
+
lo, hi = np.percentile(boot[fin], [2.5, 97.5])
|
| 233 |
+
lo2, hi2 = np.percentile(boot_nan[np.isfinite(boot_nan)], [2.5, 97.5])
|
| 234 |
+
srows.append({"kind": kind, "comparison": name, "scratch_arm": sa, "pretrained_arm": pa, "state": s,
|
| 235 |
+
"rare": s in RARE or s == "MEAN13", "rho_scratch": rs, "rho_pretrained": rp,
|
| 236 |
+
"diff_pre_minus_scratch": rp - rs, "ci_lo": lo, "ci_hi": hi, "n_finite": int(fin.sum()),
|
| 237 |
+
"ci_lo_nanmean": lo2, "ci_hi_nanmean": hi2,
|
| 238 |
+
"verdict": ("pretrained tracks better" if lo > 0 else
|
| 239 |
+
"scratch tracks better" if hi < 0 else "n.s.")})
|
| 240 |
+
SPT = pd.DataFrame(srows)
|
| 241 |
+
SPT.to_csv(V / f"{PFX}spearman.csv", index=False)
|
| 242 |
+
with pd.option_context("display.width", 250, "display.max_rows", 500, "display.max_columns", 30):
|
| 243 |
+
print(SPT[["kind", "comparison", "state", "rho_scratch", "rho_pretrained", "diff_pre_minus_scratch", "ci_lo",
|
| 244 |
+
"ci_hi", "n_finite", "ci_lo_nanmean", "ci_hi_nanmean", "verdict"]].round(3).to_string(index=False))
|
| 245 |
+
m = SPT[(SPT.state != "MEAN13") & SPT.rare]
|
| 246 |
+
print(m.groupby(["kind", "comparison"], sort=False).verdict.value_counts().unstack(fill_value=0))
|
| 247 |
+
|
| 248 |
+
# ---- 4. disease contrasts (from the per-donor CSV group column) ----------------------------------------------
|
| 249 |
+
CONTRASTS = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
|
| 250 |
+
("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
|
| 251 |
+
("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
|
| 252 |
+
["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
|
| 253 |
+
gv = GROUP.loc[DONORS].to_numpy()
|
| 254 |
+
print("groups:", pd.Series(gv).value_counts().to_dict())
|
| 255 |
+
crow = []
|
| 256 |
+
for a in ARMS:
|
| 257 |
+
for s in STATES:
|
| 258 |
+
g, o = pct(X[(a, s)])
|
| 259 |
+
for name, A, Bg in CONTRASTS:
|
| 260 |
+
ma, mb = np.isin(gv, A), np.isin(gv, Bg)
|
| 261 |
+
od = np.nanmean(o[ma]) - np.nanmean(o[mb])
|
| 262 |
+
gd = np.nanmean(g[ma]) - np.nanmean(g[mb])
|
| 263 |
+
crow.append({"arm": a, "state": s, "contrast": name, "n_a": int(ma.sum()), "n_b": int(mb.sum()),
|
| 264 |
+
"obs_diff": od, "gen_diff": gd})
|
| 265 |
+
CT = pd.DataFrame(crow)
|
| 266 |
+
mrg = CT.merge(CON[["arm", "state", "contrast", "obs_diff", "gen_diff"]], on=["arm", "state", "contrast"],
|
| 267 |
+
suffixes=("", "_file"))
|
| 268 |
+
print(f"[check] contrasts: max |obs_diff - file| = {(mrg.obs_diff - mrg.obs_diff_file).abs().max():.2e}, "
|
| 269 |
+
f"max |gen_diff - file| = {(mrg.gen_diff - mrg.gen_diff_file).abs().max():.2e}")
|
| 270 |
+
elig = []
|
| 271 |
+
for s in RARE:
|
| 272 |
+
for name, _, _ in CONTRASTS:
|
| 273 |
+
od = CT[(CT.state == s) & (CT.contrast == name) & CT.arm.isin(TRAINED)].obs_diff.to_numpy()
|
| 274 |
+
sg = np.sign(od)
|
| 275 |
+
ok = bool(np.abs(od).min() >= 0.5 and (sg == sg[0]).all() and sg[0] != 0)
|
| 276 |
+
elig.append({"state": s, "contrast": name, "eligible": ok, "min_abs_obs_diff": float(np.abs(od).min()),
|
| 277 |
+
"obs_sign": int(sg[0]) if (sg == sg[0]).all() else 0})
|
| 278 |
+
EL = pd.DataFrame(elig)
|
| 279 |
+
CT = CT.merge(EL, on=["state", "contrast"], how="left")
|
| 280 |
+
CT["kept"] = np.sign(CT.gen_diff) == np.sign(CT.obs_diff)
|
| 281 |
+
CT["loss_type"] = np.where(CT.kept, "kept",
|
| 282 |
+
np.where(~np.isfinite(CT.gen_diff) | (CT.gen_diff == 0), "flat",
|
| 283 |
+
np.where(CT.gen_diff.abs() >= 0.5, "reversed_strong", "reversed_weak")))
|
| 284 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 285 |
+
CT["gen_over_obs_diff"] = CT.gen_diff / CT.obs_diff
|
| 286 |
+
CT.to_csv(V / f"{PFX}contrasts.csv", index=False)
|
| 287 |
+
E = CT[CT.eligible.fillna(False).astype(bool)]
|
| 288 |
+
print("eligible pairs:", int(EL.eligible.sum()))
|
| 289 |
+
cc = E.groupby("arm").loss_type.value_counts().unstack(fill_value=0).reindex(ARMS)
|
| 290 |
+
cc["n"] = cc.sum(1)
|
| 291 |
+
cc.to_csv(V / f"{PFX}contrast_counts.csv")
|
| 292 |
+
print(cc)
|
| 293 |
+
with pd.option_context("display.width", 250, "display.max_rows", 500, "display.max_columns", 30):
|
| 294 |
+
print(E[~E.kept & E.arm.isin(TRAINED)][["arm", "state", "contrast", "obs_diff", "gen_diff", "loss_type",
|
| 295 |
+
"gen_over_obs_diff"]].round(3).sort_values(["arm", "state"]).to_string(index=False))
|
| 296 |
+
att = E[E.arm.isin(ARMS)].assign(abs_ratio=lambda d: (d.gen_diff / d.obs_diff))
|
| 297 |
+
print(att.groupby("arm").abs_ratio.median().reindex(ARMS).round(3))
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_sensitivity.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Adversarial sensitivity checks for the within-cohort claims (verify lens; CPU only; 2026-10-05).
|
| 3 |
+
|
| 4 |
+
From out/sepsis_fold0_per_donor.csv only (same pooled-ratio fidelity, pseudocount 0.5, and the same donor bootstrap
|
| 5 |
+
idx = default_rng(20261005).integers(0, 17, (2000, 17)) over donors sorted by name):
|
| 6 |
+
1. mean D over state subsets: all 13 rare states; 11 marker-defined states (drop the two scANVI-label states);
|
| 7 |
+
10 states (also drop LDG); and per comparison the states that are not a 'double failure'
|
| 8 |
+
(dropping states where both arms are outside [0.5x, 2x]).
|
| 9 |
+
2. Spearman mean difference (pretrained - scratch) with Efron bias-corrected CIs (sensitivity to within-7).
|
| 10 |
+
3. Disease-direction counts: discordant eligible pairs per matched comparison with an exact two-sided sign
|
| 11 |
+
(McNemar) test, ignoring the dependence between pairs (so p-values are optimistic).
|
| 12 |
+
Output: verify_recompute_within_sensitivity.csv, verify_recompute_within_direction_mcnemar.csv
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
|
| 18 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 19 |
+
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
from scipy.stats import binomtest, norm, rankdata
|
| 25 |
+
|
| 26 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 27 |
+
OUT = PLAN / "out"
|
| 28 |
+
V = OUT / "scratch_vs_lora_20261005"
|
| 29 |
+
PFX = "verify_recompute_within_"
|
| 30 |
+
SEED, B = 20261005, 2000
|
| 31 |
+
P = pd.read_csv(OUT / "sepsis_fold0_per_donor.csv")
|
| 32 |
+
STATES = list(dict.fromkeys(P.state))
|
| 33 |
+
CTRL = {"ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"}
|
| 34 |
+
RARE = [s for s in STATES if s not in CTRL]
|
| 35 |
+
LABEL = ["Proliferating T (label)", "Plasmablast (label)"]
|
| 36 |
+
LDG = "Granulocyte-like (LDG)"
|
| 37 |
+
DONORS = sorted(P.donor.unique())
|
| 38 |
+
MAIN = [("5 pairs", "scratch_n5__raw", "lora_n5__raw"),
|
| 39 |
+
("58 pairs vs LoRA", "scratch_full__raw", "real_lora__raw"),
|
| 40 |
+
("58 pairs vs full FT", "scratch_full__raw", "real_full__raw"),
|
| 41 |
+
("recipes", "scratch_recipe__raw", "lora_recipe__raw")]
|
| 42 |
+
REFC = [("zs ref: 5 pairs", "scratch_n5__raw", "zs__raw"),
|
| 43 |
+
("zs ref: 58 pairs", "scratch_full__raw", "zs__raw"),
|
| 44 |
+
("zs ref: recipes", "scratch_recipe__raw", "zs__raw")]
|
| 45 |
+
X = {(a, s): g.set_index("donor").loc[DONORS, ["gen_state", "gen_parent", "obsthin_state", "obs_parent"]]
|
| 46 |
+
.to_numpy(float) for (a, s), g in P.groupby(["arm", "state"])}
|
| 47 |
+
idx = np.random.default_rng(SEED).integers(0, 17, (B, 17))
|
| 48 |
+
Wm = np.stack([np.bincount(r, minlength=17) for r in idx]).astype(float)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def fid(S: np.ndarray) -> np.ndarray:
|
| 52 |
+
return np.abs(np.log2(((S[..., 0] + 0.5) / S[..., 1]) / ((S[..., 2] + 0.5) / S[..., 3])))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def ratio0(S: np.ndarray) -> float:
|
| 56 |
+
return float((S[0] / S[1]) / (S[2] / S[3]))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def bc(boot: np.ndarray, est: float) -> tuple[float, float]:
|
| 60 |
+
b = boot[np.isfinite(boot)]
|
| 61 |
+
p = np.mean(b < est)
|
| 62 |
+
if p <= 0 or p >= 1:
|
| 63 |
+
return (np.nan, np.nan)
|
| 64 |
+
z0 = norm.ppf(p)
|
| 65 |
+
return tuple(np.percentile(b, [100 * norm.cdf(2 * z0 - 1.959964), 100 * norm.cdf(2 * z0 + 1.959964)]))
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
rows = []
|
| 69 |
+
for kind, comps in (("main", MAIN), ("reference", REFC)):
|
| 70 |
+
for name, sa, pa in comps:
|
| 71 |
+
d_est = {s: float(fid(X[(sa, s)].sum(0)) - fid(X[(pa, s)].sum(0))) for s in RARE}
|
| 72 |
+
d_bt = {s: fid(Wm @ X[(sa, s)]) - fid(Wm @ X[(pa, s)]) for s in RARE}
|
| 73 |
+
both_fail = [s for s in RARE if all(not (0.5 <= ratio0(X[(a, s)].sum(0)) <= 2.0) for a in (sa, pa))]
|
| 74 |
+
subsets = {"13 rare states": RARE,
|
| 75 |
+
"11 marker states (drop 2 label states)": [s for s in RARE if s not in LABEL],
|
| 76 |
+
"10 states (drop 2 label states + LDG)": [s for s in RARE if s not in LABEL + [LDG]],
|
| 77 |
+
"drop double failures (both outside 0.5-2x)": [s for s in RARE if s not in both_fail],
|
| 78 |
+
"drop label states + double failures": [s for s in RARE if s not in LABEL + both_fail]}
|
| 79 |
+
for lab, ss in subsets.items():
|
| 80 |
+
est = float(np.mean([d_est[s] for s in ss]))
|
| 81 |
+
boot = np.mean(np.stack([d_bt[s] for s in ss], 1), 1)
|
| 82 |
+
lo, hi = np.percentile(boot, [2.5, 97.5])
|
| 83 |
+
blo, bhi = bc(boot, est)
|
| 84 |
+
rows.append({"analysis": "fidelity mean D", "kind": kind, "comparison": name, "subset": lab,
|
| 85 |
+
"n_states": len(ss), "dropped": "; ".join(s for s in RARE if s not in ss), "D": est,
|
| 86 |
+
"ci_lo": lo, "ci_hi": hi, "bc_lo": blo, "bc_hi": bhi})
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
# ---- Spearman mean difference with BC CI ----
|
| 90 |
+
def pcts(A: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
| 91 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 92 |
+
return (np.where(A[:, 1] > 0, A[:, 0] / A[:, 1], np.nan), np.where(A[:, 3] > 0, A[:, 2] / A[:, 3], np.nan))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def rho(g: np.ndarray, o: np.ndarray) -> float:
|
| 96 |
+
m = np.isfinite(g) & np.isfinite(o)
|
| 97 |
+
if m.sum() < 3:
|
| 98 |
+
return np.nan
|
| 99 |
+
a, b = rankdata(g[m]), rankdata(o[m])
|
| 100 |
+
a, b = a - a.mean(), b - b.mean()
|
| 101 |
+
den = np.sqrt((a * a).sum() * (b * b).sum())
|
| 102 |
+
return float((a * b).sum() / den) if den > 0 else np.nan
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
RB = {}
|
| 106 |
+
for a in {x for _, s_, p_ in MAIN + REFC for x in (s_, p_)}:
|
| 107 |
+
for s in RARE:
|
| 108 |
+
g, o = pcts(X[(a, s)])
|
| 109 |
+
RB[(a, s)] = (rho(g, o), np.array([rho(g[i], o[i]) for i in idx]))
|
| 110 |
+
for kind, comps in (("main", MAIN), ("reference", REFC)):
|
| 111 |
+
for name, sa, pa in comps:
|
| 112 |
+
est = float(np.mean([RB[(pa, s)][0] - RB[(sa, s)][0] for s in RARE]))
|
| 113 |
+
boot = np.nanmean(np.stack([RB[(pa, s)][1] - RB[(sa, s)][1] for s in RARE], 1), 1)
|
| 114 |
+
lo, hi = np.percentile(boot, [2.5, 97.5])
|
| 115 |
+
blo, bhi = bc(boot, est)
|
| 116 |
+
rows.append({"analysis": "Spearman mean diff (pre - scratch)", "kind": kind, "comparison": name,
|
| 117 |
+
"subset": "13 rare states", "n_states": 13, "dropped": "", "D": est, "ci_lo": lo, "ci_hi": hi,
|
| 118 |
+
"bc_lo": blo, "bc_hi": bhi})
|
| 119 |
+
R = pd.DataFrame(rows)
|
| 120 |
+
R.to_csv(V / f"{PFX}sensitivity.csv", index=False)
|
| 121 |
+
with pd.option_context("display.width", 250, "display.max_rows", 200, "display.max_colwidth", 70):
|
| 122 |
+
print(R.drop(columns=["dropped"]).round(3).to_string(index=False))
|
| 123 |
+
print(R[R.subset.str.startswith("drop")][["comparison", "subset", "dropped"]].to_string(index=False))
|
| 124 |
+
|
| 125 |
+
# ---- disease-direction discordance (eligible pairs from the verify contrasts table) ----
|
| 126 |
+
CT = pd.read_csv(V / f"{PFX}contrasts.csv")
|
| 127 |
+
E = CT[CT.eligible.fillna(False).astype(bool)]
|
| 128 |
+
mrows = []
|
| 129 |
+
for name, sa, pa in MAIN + REFC:
|
| 130 |
+
ks = E[E.arm == sa].set_index(["state", "contrast"]).kept
|
| 131 |
+
kp = E[E.arm == pa].set_index(["state", "contrast"]).kept.reindex(ks.index)
|
| 132 |
+
b = int((kp & ~ks).sum()) # pretrained kept, scratch lost
|
| 133 |
+
c = int((~kp & ks).sum()) # scratch kept, pretrained lost
|
| 134 |
+
p = binomtest(b, b + c, 0.5).pvalue if b + c > 0 else np.nan
|
| 135 |
+
mrows.append({"comparison": name, "scratch_arm": sa, "pretrained_arm": pa, "n_eligible": len(ks),
|
| 136 |
+
"kept_scratch": int(ks.sum()), "kept_pretrained": int(kp.sum()), "pre_only": b, "scratch_only": c,
|
| 137 |
+
"exact_sign_p_two_sided": p})
|
| 138 |
+
M = pd.DataFrame(mrows)
|
| 139 |
+
M.to_csv(V / f"{PFX}direction_mcnemar.csv", index=False)
|
| 140 |
+
print(M.round(4).to_string(index=False))
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/within_analysis.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Rare-state fidelity, from-scratch vs pretrained arms, WITHIN-COHORT setting (2026-10-05; CPU only).
|
| 3 |
+
|
| 4 |
+
Setting: Ye 2026 sepsis paired cohort, fold 0, 17 held-out donors (12 sepsis, 5 controls). Inputs (read-only) are
|
| 5 |
+
the fold-0 outputs of tools/sepsis_states.py (--scope fold0 analyze) one directory up:
|
| 6 |
+
../sepsis_fold0_summary.csv, ../sepsis_fold0_contrasts.csv, ../sepsis_fold0_per_donor.csv
|
| 7 |
+
Outputs (new files, this directory, prefix "within_"):
|
| 8 |
+
within_state_table.csv one row per state: gen_over_obs, |log2|, Spearman, cell counts for all 8 arms
|
| 9 |
+
within_arm_fidelity.csv per arm x state: pooled log2 ratio (+0.5) with donor-bootstrap 95 % CI
|
| 10 |
+
within_bootstrap.csv per comparison x state: D = |log2 r_scratch| - |log2 r_pretrained|, CI, verdict
|
| 11 |
+
within_bootstrap_counts.csv per comparison: verdict counts (rare states; controls separately)
|
| 12 |
+
within_contrast_directions.csv per arm x (state, contrast): observed vs generated difference, kept/reversed/flat
|
| 13 |
+
within_contrast_counts.csv per arm: kept / reversed / flat counts on the common eligible set
|
| 14 |
+
within_spearman.csv per comparison x state: Spearman over donors, difference with bootstrap CI
|
| 15 |
+
|
| 16 |
+
Definitions
|
| 17 |
+
- Pooled ratio of an arm and state, as in the summary CSV:
|
| 18 |
+
r = (sum gen_state / sum gen_parent) / (sum obsthin_state / sum obs_parent)
|
| 19 |
+
For log2 work +0.5 is added to both state counts (r_pc). Fidelity = |log2 r_pc| (0 = generated frequency equals the
|
| 20 |
+
observed frequency after thinning to the arm's depth).
|
| 21 |
+
- D = |log2 r_pc(scratch)| - |log2 r_pc(pretrained)|. D > 0: the pretrained arm is closer to the observed frequency.
|
| 22 |
+
- Paired donor bootstrap: one 2000 x 17 index matrix, np.random.default_rng(20261005).integers(0, 17, (2000, 17)) over
|
| 23 |
+
the donors sorted by name, reused for every arm, state and comparison (so arms, states and comparisons are paired).
|
| 24 |
+
95 % percentile intervals. "pretrained closer" if the CI of D lies above 0, "scratch closer" if it lies below 0.
|
| 25 |
+
p_boot = 2 * min(P(D_b <= 0), P(D_b >= 0)) (rough two-sided bootstrap p, not multiplicity-corrected).
|
| 26 |
+
Sensitivity only: bias-corrected percentile interval of D (columns D_bc_*), because |log2| is folded at 0.
|
| 27 |
+
Companion script within_label_marker_check.py (label vs marker definition of proliferating T cells).
|
| 28 |
+
- Informative state: the observed side has >= 30 thinned state cells in total in every arm (minimum over arms).
|
| 29 |
+
- Contrast eligibility (common to all arms): informative non-control state and |obs_diff| >= 0.5 percentage points in
|
| 30 |
+
each of the 7 trained arms with the same observed sign (obs_diff varies slightly by arm through thinning).
|
| 31 |
+
status: kept (sign(gen_diff) == sign(obs_diff)), flat (gen_diff == 0 or undefined), reversed (opposite sign).
|
| 32 |
+
"""
|
| 33 |
+
from __future__ import annotations
|
| 34 |
+
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
import numpy as np
|
| 38 |
+
import pandas as pd
|
| 39 |
+
from scipy.stats import norm, rankdata
|
| 40 |
+
|
| 41 |
+
OUT = Path(__file__).resolve().parent
|
| 42 |
+
SRC = OUT.parent
|
| 43 |
+
SEED, NBOOT, PC = 20261005, 2000, 0.5
|
| 44 |
+
INFORMATIVE_MIN = 30
|
| 45 |
+
CONTRAST_MIN = 0.5
|
| 46 |
+
|
| 47 |
+
ARMS = ["zs__raw", "lora_n5__raw", "scratch_n5__raw", "real_lora__raw", "real_full__raw", "scratch_full__raw",
|
| 48 |
+
"lora_recipe__raw", "scratch_recipe__raw"]
|
| 49 |
+
ARM_INFO = { # init, pairs, training minutes (fold 0; from the task description / benchmark)
|
| 50 |
+
"zs__raw": ("pretrained zero-shot", 0, 0.0),
|
| 51 |
+
"lora_n5__raw": ("pretrained + LoRA", 5, 3.2),
|
| 52 |
+
"scratch_n5__raw": ("scratch", 5, 61.0),
|
| 53 |
+
"real_lora__raw": ("pretrained + LoRA", 58, 5.4),
|
| 54 |
+
"real_full__raw": ("pretrained + full FT", 58, 4.7),
|
| 55 |
+
"scratch_full__raw": ("scratch (100k-step cap)", 58, 79.0),
|
| 56 |
+
"lora_recipe__raw": ("pretrained + LoRA + recipes", 58, 4.5),
|
| 57 |
+
"scratch_recipe__raw": ("scratch + recipes", 58, 86.0),
|
| 58 |
+
}
|
| 59 |
+
TRAINED = [a for a in ARMS if a != "zs__raw"]
|
| 60 |
+
SCRATCH_ARMS = ["scratch_n5__raw", "scratch_full__raw", "scratch_recipe__raw"]
|
| 61 |
+
COMPARISONS = [ # name, scratch arm, pretrained arm, kind
|
| 62 |
+
("5 pairs: scratch vs pretrained LoRA", "scratch_n5__raw", "lora_n5__raw", "main"),
|
| 63 |
+
("58 pairs: scratch vs pretrained LoRA", "scratch_full__raw", "real_lora__raw", "main"),
|
| 64 |
+
("58 pairs: scratch vs pretrained full FT", "scratch_full__raw", "real_full__raw", "main"),
|
| 65 |
+
("58 pairs + recipes: scratch vs pretrained LoRA", "scratch_recipe__raw", "lora_recipe__raw", "main"),
|
| 66 |
+
("reference: scratch 5 pairs vs pretrained zero-shot (no pairs)", "scratch_n5__raw", "zs__raw", "reference"),
|
| 67 |
+
("reference: scratch 58 pairs vs pretrained zero-shot (no pairs)", "scratch_full__raw", "zs__raw", "reference"),
|
| 68 |
+
("reference: scratch 58 + recipes vs pretrained zero-shot (no pairs)", "scratch_recipe__raw", "zs__raw",
|
| 69 |
+
"reference"),
|
| 70 |
+
]
|
| 71 |
+
CONTROLS = {"ISG-high monocyte (positive control)": "positive control",
|
| 72 |
+
"Platelet signal in monocytes (negative control)": "negative control"}
|
| 73 |
+
KEYS = ["gen_state", "gen_parent", "obsthin_state", "obs_parent", "obs_state", "gen_pct", "obsthin_pct"]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def r6(x):
|
| 77 |
+
return None if x is None or (isinstance(x, float) and not np.isfinite(x)) else round(float(x), 6)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def load():
|
| 81 |
+
P = pd.read_csv(SRC / "sepsis_fold0_per_donor.csv")
|
| 82 |
+
S = pd.read_csv(SRC / "sepsis_fold0_summary.csv")
|
| 83 |
+
C = pd.read_csv(SRC / "sepsis_fold0_contrasts.csv")
|
| 84 |
+
assert sorted(P.arm.unique()) == sorted(ARMS), P.arm.unique()
|
| 85 |
+
return P, S, C
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def arrays(P, donors, states):
|
| 89 |
+
A = {}
|
| 90 |
+
for (arm, st), t in P.groupby(["arm", "state"]):
|
| 91 |
+
t = t.set_index("donor").loc[donors]
|
| 92 |
+
A[arm, st] = {k: t[k].to_numpy(float) for k in KEYS}
|
| 93 |
+
assert all((a, s) in A for a in ARMS for s in states)
|
| 94 |
+
return A
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def log2_ratio(x, idx=None):
|
| 98 |
+
"""Pooled log2 ratio (+0.5 on state counts); idx (B, n) -> (B,) bootstrap values."""
|
| 99 |
+
tot = {k: (x[k].sum() if idx is None else x[k][idx].sum(axis=-1))
|
| 100 |
+
for k in ["gen_state", "gen_parent", "obsthin_state", "obs_parent"]}
|
| 101 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 102 |
+
v = np.log2(((tot["gen_state"] + PC) / tot["gen_parent"]) / ((tot["obsthin_state"] + PC) / tot["obs_parent"]))
|
| 103 |
+
return np.where(np.isfinite(v), v, np.nan)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
def spearman(x, y):
|
| 107 |
+
m = np.isfinite(x) & np.isfinite(y)
|
| 108 |
+
if m.sum() < 3:
|
| 109 |
+
return np.nan
|
| 110 |
+
rx, ry = rankdata(x[m]), rankdata(y[m])
|
| 111 |
+
if rx.std() == 0 or ry.std() == 0:
|
| 112 |
+
return np.nan
|
| 113 |
+
return float(np.corrcoef(rx, ry)[0, 1])
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def boot_spearman(x, IDX):
|
| 117 |
+
g, o = x["gen_pct"], x["obsthin_pct"]
|
| 118 |
+
return np.array([spearman(g[i], o[i]) for i in IDX])
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def ci(v):
|
| 122 |
+
v = v[np.isfinite(v)]
|
| 123 |
+
if len(v) == 0:
|
| 124 |
+
return np.nan, np.nan, 0
|
| 125 |
+
lo, hi = np.percentile(v, [2.5, 97.5])
|
| 126 |
+
return lo, hi, len(v)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def p_boot(v):
|
| 130 |
+
v = v[np.isfinite(v)]
|
| 131 |
+
if len(v) == 0:
|
| 132 |
+
return np.nan
|
| 133 |
+
return min(1.0, 2 * min((v <= 0).mean(), (v >= 0).mean()))
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def verdict(lo, hi, pos="pretrained closer", neg="scratch closer"):
|
| 137 |
+
if not (np.isfinite(lo) and np.isfinite(hi)):
|
| 138 |
+
return "undefined"
|
| 139 |
+
return pos if lo > 0 else neg if hi < 0 else "not significant"
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def bc_ci(v, t0):
|
| 143 |
+
"""Bias-corrected percentile interval (sensitivity only). |log2| is folded at 0, so when one arm sits near 1x its
|
| 144 |
+
bootstrap |log2| is pushed above the point estimate and the plain percentile interval of D is shifted; the BC
|
| 145 |
+
interval re-centres on the point estimate (z0 = Phi^-1(P(D_b < D)))."""
|
| 146 |
+
v = v[np.isfinite(v)]
|
| 147 |
+
if len(v) == 0 or not np.isfinite(t0):
|
| 148 |
+
return np.nan, np.nan
|
| 149 |
+
z0 = norm.ppf(np.clip((v < t0).mean() + 0.5 * (v == t0).mean(), 1e-4, 1 - 1e-4))
|
| 150 |
+
q = norm.cdf(2 * z0 + norm.ppf([0.025, 0.975]))
|
| 151 |
+
lo, hi = np.percentile(v, 100 * q)
|
| 152 |
+
return lo, hi
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def main():
|
| 156 |
+
P, S, C = load()
|
| 157 |
+
donors = sorted(P.donor.unique())
|
| 158 |
+
states = list(dict.fromkeys(S.state))
|
| 159 |
+
A = arrays(P, donors, states)
|
| 160 |
+
rng = np.random.default_rng(SEED)
|
| 161 |
+
IDX = rng.integers(0, len(donors), size=(NBOOT, len(donors)))
|
| 162 |
+
groups = P.drop_duplicates("donor").set_index("donor").group
|
| 163 |
+
|
| 164 |
+
# ---------------- 1. state table -----------------------------------------------------------------------------
|
| 165 |
+
Sx = S.set_index(["arm", "state"])
|
| 166 |
+
obsthin_tot = {(a, s): int(A[a, s]["obsthin_state"].sum()) for a in ARMS for s in states}
|
| 167 |
+
informative = {s: min(obsthin_tot[a, s] for a in ARMS) >= INFORMATIVE_MIN for s in states}
|
| 168 |
+
rows = []
|
| 169 |
+
for s in states:
|
| 170 |
+
x0 = A[ARMS[0], s]
|
| 171 |
+
native = x0["obs_state"]
|
| 172 |
+
row = {"state": s, "role": CONTROLS.get(s, "rare state"),
|
| 173 |
+
"obs_parent_cells": int(x0["obs_parent"].sum()), "obs_native_state_cells": int(native.sum()),
|
| 174 |
+
"obs_thinned_state_cells_min": min(obsthin_tot[a, s] for a in ARMS),
|
| 175 |
+
"obs_thinned_state_cells_max": max(obsthin_tot[a, s] for a in ARMS),
|
| 176 |
+
"informative": informative[s],
|
| 177 |
+
"obs_donors_with_state": int((native > 0).sum()),
|
| 178 |
+
"obs_top_donor_share": r6(native.max() / native.sum()) if native.sum() else None,
|
| 179 |
+
"obs_top_donor": donors[int(np.argmax(native))]}
|
| 180 |
+
fid = {}
|
| 181 |
+
for a in ARMS:
|
| 182 |
+
g = Sx.loc[(a, s)]
|
| 183 |
+
ratio = float(g.gen_over_obs)
|
| 184 |
+
row[f"gen_over_obs__{a}"] = r6(ratio)
|
| 185 |
+
row[f"abs_log2__{a}"] = r6(abs(np.log2(ratio))) if ratio > 0 else None
|
| 186 |
+
row[f"spearman__{a}"] = r6(g.spearman_donors)
|
| 187 |
+
row[f"gen_state_cells__{a}"] = int(A[a, s]["gen_state"].sum())
|
| 188 |
+
row[f"gen_parent_cells__{a}"] = int(A[a, s]["gen_parent"].sum())
|
| 189 |
+
row[f"obs_thinned_state_cells__{a}"] = obsthin_tot[a, s]
|
| 190 |
+
row[f"thin__{a}"] = r6(g.thin)
|
| 191 |
+
fid[a] = abs(np.log2(ratio)) if ratio > 0 else np.inf
|
| 192 |
+
best = min(TRAINED, key=lambda a: fid[a])
|
| 193 |
+
row["closest_trained_arm"] = best
|
| 194 |
+
row["closest_scratch_arm"] = min(SCRATCH_ARMS, key=lambda a: fid[a])
|
| 195 |
+
row["closest_pretrained_trained_arm"] = min([a for a in TRAINED if a not in SCRATCH_ARMS], key=lambda a: fid[a])
|
| 196 |
+
rows.append(row)
|
| 197 |
+
ST = pd.DataFrame(rows)
|
| 198 |
+
ST.to_csv(OUT / "within_state_table.csv", index=False)
|
| 199 |
+
|
| 200 |
+
# ---------------- 2. bootstrap of |log2| ---------------------------------------------------------------------
|
| 201 |
+
L0 = {(a, s): float(log2_ratio(A[a, s])) for a in ARMS for s in states}
|
| 202 |
+
LB = {(a, s): log2_ratio(A[a, s], IDX) for a in ARMS for s in states}
|
| 203 |
+
fr = []
|
| 204 |
+
for a in ARMS:
|
| 205 |
+
for s in states:
|
| 206 |
+
lo, hi, n = ci(LB[a, s])
|
| 207 |
+
alo, ahi, _ = ci(np.abs(LB[a, s]))
|
| 208 |
+
fr.append({"arm": a, "init": ARM_INFO[a][0], "pairs": ARM_INFO[a][1], "state": s,
|
| 209 |
+
"role": CONTROLS.get(s, "rare state"), "informative": informative[s],
|
| 210 |
+
"gen_over_obs_summary": r6(Sx.loc[(a, s)].gen_over_obs),
|
| 211 |
+
"ratio_pc": r6(2 ** L0[a, s]), "log2_ratio_pc": r6(L0[a, s]),
|
| 212 |
+
"log2_ci_lo": r6(lo), "log2_ci_hi": r6(hi),
|
| 213 |
+
"ratio_ci_lo": r6(2 ** lo), "ratio_ci_hi": r6(2 ** hi),
|
| 214 |
+
"ratio_ci_includes_1": bool(lo <= 0 <= hi), "abs_log2_pc": r6(abs(L0[a, s])),
|
| 215 |
+
"abs_log2_ci_lo": r6(alo), "abs_log2_ci_hi": r6(ahi), "n_boot_valid": n})
|
| 216 |
+
rare = [s for s in states if s not in CONTROLS and informative[s]]
|
| 217 |
+
for a in ARMS: # mean |log2| over the informative rare states
|
| 218 |
+
m0 = np.mean([abs(L0[a, s]) for s in rare])
|
| 219 |
+
mb = np.mean(np.vstack([np.abs(LB[a, s]) for s in rare]), axis=0)
|
| 220 |
+
lo, hi, n = ci(mb)
|
| 221 |
+
n_in = sum(bool(ci(LB[a, s])[0] <= 0 <= ci(LB[a, s])[1]) for s in rare)
|
| 222 |
+
fr.append({"arm": a, "init": ARM_INFO[a][0], "pairs": ARM_INFO[a][1],
|
| 223 |
+
"state": f"MEAN over {len(rare)} informative rare states", "role": "aggregate",
|
| 224 |
+
"informative": True, "abs_log2_pc": r6(m0), "abs_log2_ci_lo": r6(lo), "abs_log2_ci_hi": r6(hi),
|
| 225 |
+
"n_boot_valid": n, "ratio_ci_includes_1": None,
|
| 226 |
+
"n_rare_states_ratio_ci_includes_1": n_in,
|
| 227 |
+
"n_rare_states_within_2x": sum(abs(L0[a, s]) <= 1 for s in rare),
|
| 228 |
+
"n_rare_states_below_0.25x": sum(L0[a, s] < -2 for s in rare)})
|
| 229 |
+
pd.DataFrame(fr).to_csv(OUT / "within_arm_fidelity.csv", index=False)
|
| 230 |
+
|
| 231 |
+
br = []
|
| 232 |
+
for name, sa, pa, kind in COMPARISONS:
|
| 233 |
+
for s in states:
|
| 234 |
+
d0 = abs(L0[sa, s]) - abs(L0[pa, s])
|
| 235 |
+
db = np.abs(LB[sa, s]) - np.abs(LB[pa, s])
|
| 236 |
+
lo, hi, n = ci(db)
|
| 237 |
+
blo, bhi = bc_ci(db, d0)
|
| 238 |
+
br.append({"comparison": name, "kind": kind, "scratch_arm": sa, "pretrained_arm": pa, "state": s,
|
| 239 |
+
"role": CONTROLS.get(s, "rare state"), "informative": informative[s],
|
| 240 |
+
"obs_thinned_state_cells_min": min(obsthin_tot[a, s] for a in ARMS),
|
| 241 |
+
"ratio_scratch": r6(Sx.loc[(sa, s)].gen_over_obs),
|
| 242 |
+
"ratio_pretrained": r6(Sx.loc[(pa, s)].gen_over_obs),
|
| 243 |
+
"gen_state_scratch": int(A[sa, s]["gen_state"].sum()),
|
| 244 |
+
"gen_state_pretrained": int(A[pa, s]["gen_state"].sum()),
|
| 245 |
+
"abs_log2_scratch": r6(abs(L0[sa, s])), "abs_log2_pretrained": r6(abs(L0[pa, s])),
|
| 246 |
+
"D": r6(d0), "D_ci_lo": r6(lo), "D_ci_hi": r6(hi), "p_boot": r6(p_boot(db)),
|
| 247 |
+
"n_boot_valid": n, "verdict": verdict(lo, hi) if informative[s] else "uninformative",
|
| 248 |
+
"D_bc_ci_lo": r6(blo), "D_bc_ci_hi": r6(bhi),
|
| 249 |
+
"verdict_bc_sensitivity": verdict(blo, bhi) if informative[s] else "uninformative"})
|
| 250 |
+
d0 = np.mean([abs(L0[sa, s]) - abs(L0[pa, s]) for s in rare])
|
| 251 |
+
db = np.mean(np.vstack([np.abs(LB[sa, s]) - np.abs(LB[pa, s]) for s in rare]), axis=0)
|
| 252 |
+
lo, hi, n = ci(db)
|
| 253 |
+
blo, bhi = bc_ci(db, d0)
|
| 254 |
+
br.append({"comparison": name, "kind": kind, "scratch_arm": sa, "pretrained_arm": pa,
|
| 255 |
+
"state": f"MEAN over {len(rare)} informative rare states", "role": "aggregate",
|
| 256 |
+
"informative": True,
|
| 257 |
+
"abs_log2_scratch": r6(np.mean([abs(L0[sa, s]) for s in rare])),
|
| 258 |
+
"abs_log2_pretrained": r6(np.mean([abs(L0[pa, s]) for s in rare])),
|
| 259 |
+
"D": r6(d0), "D_ci_lo": r6(lo), "D_ci_hi": r6(hi), "p_boot": r6(p_boot(db)), "n_boot_valid": n,
|
| 260 |
+
"verdict": verdict(lo, hi), "D_bc_ci_lo": r6(blo), "D_bc_ci_hi": r6(bhi),
|
| 261 |
+
"verdict_bc_sensitivity": verdict(blo, bhi)})
|
| 262 |
+
B = pd.DataFrame(br)
|
| 263 |
+
B.to_csv(OUT / "within_bootstrap.csv", index=False)
|
| 264 |
+
cr = [] # verdict counts per comparison
|
| 265 |
+
for name, sa, pa, kind in COMPARISONS:
|
| 266 |
+
t = B[(B.comparison == name) & (B.role != "aggregate")]
|
| 267 |
+
for label, m in [("rare states", t.role == "rare state"), ("controls", t.role != "rare state")]:
|
| 268 |
+
u = t[m]
|
| 269 |
+
row = {"comparison": name, "kind": kind, "scratch_arm": sa, "pretrained_arm": pa, "states": label,
|
| 270 |
+
"n_states": len(u), "n_uninformative": int((u.verdict == "uninformative").sum())}
|
| 271 |
+
for col, tag in [("verdict", ""), ("verdict_bc_sensitivity", "bc_")]:
|
| 272 |
+
v = u[col]
|
| 273 |
+
row[f"{tag}pretrained_closer"] = int((v == "pretrained closer").sum())
|
| 274 |
+
row[f"{tag}scratch_closer"] = int((v == "scratch closer").sum())
|
| 275 |
+
row[f"{tag}not_significant"] = int((v == "not significant").sum())
|
| 276 |
+
row[f"{tag}pretrained_closer_states"] = "; ".join(u[v == "pretrained closer"].state)
|
| 277 |
+
row[f"{tag}scratch_closer_states"] = "; ".join(u[v == "scratch closer"].state)
|
| 278 |
+
row["point_D_positive"] = int((u.D > 0).sum())
|
| 279 |
+
row["point_D_negative"] = int((u.D < 0).sum())
|
| 280 |
+
cr.append(row)
|
| 281 |
+
pd.DataFrame(cr).to_csv(OUT / "within_bootstrap_counts.csv", index=False)
|
| 282 |
+
|
| 283 |
+
# ---------------- 3. contrast directions ---------------------------------------------------------------------
|
| 284 |
+
C = C.copy()
|
| 285 |
+
C["is_control"] = C.state.isin(list(CONTROLS))
|
| 286 |
+
w = C[C.arm.isin(TRAINED)].groupby(["state", "contrast"]).obs_diff
|
| 287 |
+
elig = pd.DataFrame({"min_abs_obs_diff_trained": w.apply(lambda v: v.abs().min()),
|
| 288 |
+
"obs_sign_consistent_trained": w.apply(lambda v: np.sign(v).nunique() == 1)}).reset_index()
|
| 289 |
+
C = C.merge(elig, on=["state", "contrast"])
|
| 290 |
+
C["informative"] = C.state.map(informative)
|
| 291 |
+
C["eligible_common"] = (C.informative & (C.min_abs_obs_diff_trained >= CONTRAST_MIN)
|
| 292 |
+
& C.obs_sign_consistent_trained)
|
| 293 |
+
C["eligible_own"] = C.informative & (C.obs_diff.abs() >= CONTRAST_MIN)
|
| 294 |
+
C["status"] = np.where(C.same_direction, "kept",
|
| 295 |
+
np.where((C.gen_diff == 0) | C.gen_diff.isna(), "flat", "reversed"))
|
| 296 |
+
# strong reversal: generated difference of >= 0.5 percentage points in the wrong direction; weak: < 0.5 pp
|
| 297 |
+
# (i.e. essentially no generated disease difference rather than an opposite one)
|
| 298 |
+
C["reversal_strength"] = np.where(C.status != "reversed", "",
|
| 299 |
+
np.where(C.gen_diff.abs() >= CONTRAST_MIN, "strong", "weak"))
|
| 300 |
+
C["compression_gen_over_obs_diff"] = C.gen_diff / C.obs_diff
|
| 301 |
+
C["init"] = C.arm.map(lambda a: ARM_INFO[a][0])
|
| 302 |
+
C["pairs"] = C.arm.map(lambda a: ARM_INFO[a][1])
|
| 303 |
+
cols = ["arm", "init", "pairs", "state", "contrast", "is_control", "n_a", "n_b", "obs_a", "obs_b", "gen_a",
|
| 304 |
+
"gen_b", "obs_diff", "gen_diff", "compression_gen_over_obs_diff", "same_direction", "status",
|
| 305 |
+
"reversal_strength", "informative", "min_abs_obs_diff_trained", "eligible_common", "eligible_own"]
|
| 306 |
+
C[cols].to_csv(OUT / "within_contrast_directions.csv", index=False)
|
| 307 |
+
cnt = []
|
| 308 |
+
for a in ARMS:
|
| 309 |
+
for label, m in [("rare, common eligible set", C.eligible_common & ~C.is_control),
|
| 310 |
+
("rare, own eligible set", C.eligible_own & ~C.is_control),
|
| 311 |
+
("controls, own |obs_diff| >= 0.5", C.eligible_own & C.is_control)]:
|
| 312 |
+
t = C[(C.arm == a) & m]
|
| 313 |
+
cnt.append({"arm": a, "init": ARM_INFO[a][0], "pairs": ARM_INFO[a][1], "set": label, "n": len(t),
|
| 314 |
+
"kept": int((t.status == "kept").sum()), "reversed": int((t.status == "reversed").sum()),
|
| 315 |
+
"reversed_strong": int((t.reversal_strength == "strong").sum()),
|
| 316 |
+
"reversed_weak": int((t.reversal_strength == "weak").sum()),
|
| 317 |
+
"flat": int((t.status == "flat").sum()),
|
| 318 |
+
"median_compression_kept": r6(t[t.status == "kept"].compression_gen_over_obs_diff.median())
|
| 319 |
+
if (t.status == "kept").any() else None,
|
| 320 |
+
"not_kept": "; ".join(f"{r.state} | {r.contrast} ({r.status} {r.reversal_strength}: "
|
| 321 |
+
f"gen {r.gen_diff:+.2f} vs obs {r.obs_diff:+.2f} pp)"
|
| 322 |
+
for r in t[t.status != "kept"].itertuples())})
|
| 323 |
+
pd.DataFrame(cnt).to_csv(OUT / "within_contrast_counts.csv", index=False)
|
| 324 |
+
|
| 325 |
+
# ---------------- 4. Spearman over donors --------------------------------------------------------------------
|
| 326 |
+
R0, RB = {}, {}
|
| 327 |
+
for a in ARMS:
|
| 328 |
+
for s in states:
|
| 329 |
+
R0[a, s] = spearman(A[a, s]["gen_pct"], A[a, s]["obsthin_pct"])
|
| 330 |
+
assert abs(R0[a, s] - Sx.loc[(a, s)].spearman_donors) < 1e-9 or (
|
| 331 |
+
np.isnan(R0[a, s]) and np.isnan(Sx.loc[(a, s)].spearman_donors)), (a, s)
|
| 332 |
+
RB[a, s] = boot_spearman(A[a, s], IDX)
|
| 333 |
+
sr = []
|
| 334 |
+
for name, sa, pa, kind in COMPARISONS:
|
| 335 |
+
for s in states:
|
| 336 |
+
diff = RB[pa, s] - RB[sa, s]
|
| 337 |
+
lo, hi, n = ci(diff)
|
| 338 |
+
slo, shi, _ = ci(RB[sa, s])
|
| 339 |
+
plo, phi, _ = ci(RB[pa, s])
|
| 340 |
+
sr.append({"comparison": name, "kind": kind, "scratch_arm": sa, "pretrained_arm": pa, "state": s,
|
| 341 |
+
"role": CONTROLS.get(s, "rare state"), "informative": informative[s],
|
| 342 |
+
"spearman_scratch": r6(R0[sa, s]), "scratch_ci_lo": r6(slo), "scratch_ci_hi": r6(shi),
|
| 343 |
+
"spearman_pretrained": r6(R0[pa, s]), "pretrained_ci_lo": r6(plo),
|
| 344 |
+
"pretrained_ci_hi": r6(phi),
|
| 345 |
+
"diff_pretrained_minus_scratch": r6(R0[pa, s] - R0[sa, s]), "diff_ci_lo": r6(lo),
|
| 346 |
+
"diff_ci_hi": r6(hi), "n_boot_valid": n,
|
| 347 |
+
"verdict": verdict(lo, hi, "pretrained tracks donors better", "scratch tracks donors better")})
|
| 348 |
+
d0 = np.mean([R0[pa, s] - R0[sa, s] for s in rare])
|
| 349 |
+
db = np.nanmean(np.vstack([RB[pa, s] - RB[sa, s] for s in rare]), axis=0)
|
| 350 |
+
lo, hi, n = ci(db)
|
| 351 |
+
sr.append({"comparison": name, "kind": kind, "scratch_arm": sa, "pretrained_arm": pa,
|
| 352 |
+
"state": f"MEAN over {len(rare)} informative rare states", "role": "aggregate",
|
| 353 |
+
"informative": True,
|
| 354 |
+
"spearman_scratch": r6(np.mean([R0[sa, s] for s in rare])),
|
| 355 |
+
"spearman_pretrained": r6(np.mean([R0[pa, s] for s in rare])),
|
| 356 |
+
"diff_pretrained_minus_scratch": r6(d0), "diff_ci_lo": r6(lo), "diff_ci_hi": r6(hi),
|
| 357 |
+
"n_boot_valid": n,
|
| 358 |
+
"verdict": verdict(lo, hi, "pretrained tracks donors better", "scratch tracks donors better")})
|
| 359 |
+
pd.DataFrame(sr).to_csv(OUT / "within_spearman.csv", index=False)
|
| 360 |
+
|
| 361 |
+
# ---------------- console digest -----------------------------------------------------------------------------
|
| 362 |
+
pd.set_option("display.width", 250)
|
| 363 |
+
pd.set_option("display.max_columns", 40)
|
| 364 |
+
pd.set_option("display.max_rows", 500)
|
| 365 |
+
print("donors", len(donors), dict(groups.value_counts()))
|
| 366 |
+
print("informative", informative)
|
| 367 |
+
print(B[["comparison", "state", "ratio_scratch", "ratio_pretrained", "D", "D_ci_lo", "D_ci_hi", "p_boot",
|
| 368 |
+
"verdict", "verdict_bc_sensitivity"]].round(3).to_string(index=False))
|
| 369 |
+
print(pd.read_csv(OUT / "within_bootstrap_counts.csv").drop(
|
| 370 |
+
columns=["scratch_arm", "pretrained_arm", "kind"]).to_string(index=False))
|
| 371 |
+
SR = pd.read_csv(OUT / "within_spearman.csv")
|
| 372 |
+
SR = SR[(SR.role == "rare state") & SR.informative]
|
| 373 |
+
print(SR.groupby("comparison").verdict.value_counts().unstack(fill_value=0).to_string())
|
| 374 |
+
print(SR.assign(pos=SR.diff_pretrained_minus_scratch > 0).groupby("comparison").pos.agg(["sum", "count"]))
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
if __name__ == "__main__":
|
| 378 |
+
main()
|