junidude14 commited on
Commit
97208e3
·
verified ·
1 Parent(s): d13a731

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/confound_audit.py ADDED
@@ -0,0 +1,720 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Confound audit: scratch vs pretrained rare-state generation, Ye 2026 sepsis held-out donors (CPU only; 2026-10-05).
3
+
4
+ Read-only inputs (nothing existing is modified):
5
+ ../../work/sepsis/{fold0,loco}/<arm>.npz per-cell marker extracts (markers, marker_symbols, lib_measured, donor,
6
+ aifi_l1, aifi_l2)
7
+ ../sepsis_{fold0,loco}_{summary,contrasts,per_donor}.csv
8
+ ../../tools/states.json; rule logic imported from ../../tools/screen.py (call_state, state_cols, parent_mask);
9
+ observed cells from ../../tools/sepsis_states.py observed() (same cells / labels / measured genes as the screen).
10
+ Writes only confound_*.csv next to this script. NaN / undefined -> 'null'.
11
+
12
+ Sections
13
+ (0) reproduction of the screen's per-donor counts (same RNG sequence, seed 20261004) as a check of the inputs.
14
+ (a) generated depth per arm and parent; library ratio vs marker-gene depth ratio; the screen's 'thin' constant.
15
+ (b) generated vs observed composition; parent-pool sizes; parent-fraction vs within-parent decomposition per pair.
16
+ (c) depth-matching sensitivity for all marker states, three common references per setting (seed 20261005):
17
+ V1 'lib' : thin every arm and the observed parent cells to the lowest generated parent median library
18
+ (one constant per arm and state, as the screen does, but a common target for all arms);
19
+ V2 'msum' : effective depth = sum over reference marker genes of the parent mean count, relative to the
20
+ observed native parent (reference genes = the 73 extracted markers minus the state's own rule
21
+ genes, observed parent mean >= 0.1); thin every arm and the observed to the lowest one;
22
+ V3 'mmed' : as V2 with the median over reference genes of the per-gene mean ratio.
23
+ V0 = the screen as published (each arm's own observed thinning). Donor bootstrap (B = 2000, seed 20261005) of
24
+ which arm of each scratch-vs-pretrained pair is closer to gen/obs = 1.
25
+ (d) donor spread / collapse: SD across donors of state %, composition, marker-level between-donor CV (sampling floor
26
+ removed), within-donor excess dispersion, and across-donor tracking of per-donor marker means.
27
+ (e) small-n contrasts: group sizes, generated state cells per group, leave-one-donor-out and donor-bootstrap
28
+ stability of same_direction (V0).
29
+ (f) positive / negative controls across arms and schemes.
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import sys
35
+ import time
36
+ import warnings
37
+ from pathlib import Path
38
+
39
+ import numpy as np
40
+ import pandas as pd
41
+ from scipy.stats import pearsonr, spearmanr
42
+
43
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
44
+ sys.path.insert(0, str(PLAN / "tools"))
45
+ from screen import call_state, parent_mask, state_cols # noqa: E402
46
+ import sepsis_states as ss # noqa: E402
47
+
48
+ OUT = PLAN / "out/scratch_vs_lora_20261005"
49
+ SEED = 20261005
50
+ NBOOT = 2000
51
+ ORIG_THIN_SEED = 20261004
52
+ FOCUS = ["MS1 monocyte (IL1R2+)", "C1Q-high monocyte (reference)", "Cycling monocyte (Ye 2026)",
53
+ "Plasmablast (markers)", "ISG-high T", "DN2 / ABC B"]
54
+ CONTROLS = ["ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"]
55
+ SETTINGS = {"fold0": ("work/sepsis/fold0", "out/sepsis_fold0_"), "loco": ("work/sepsis/loco", "out/sepsis_loco_")}
56
+ ARM_CLASS = {
57
+ "fold0": {"zs__raw": "pretrained zero-shot", "lora_n5__raw": "pretrained LoRA (5 pairs)",
58
+ "scratch_n5__raw": "scratch (5 pairs)", "real_lora__raw": "pretrained LoRA (58 pairs)",
59
+ "real_full__raw": "pretrained full FT (58 pairs)", "scratch_full__raw": "scratch (58 pairs, 100k cap)",
60
+ "lora_recipe__raw": "pretrained LoRA + recipes (58 pairs)",
61
+ "scratch_recipe__raw": "scratch + recipes (58 pairs)"},
62
+ "loco": {"zs__raw": "pretrained zero-shot", "xcalL_K1000": "pretrained zero-shot + cross-cohort calibration",
63
+ "locoL_lora16sat_s26750_K1000": "pretrained LoRA r16 (cross-cohort)",
64
+ "locoL_lora64sat_s59000_K1000": "pretrained LoRA r64 (cross-cohort)",
65
+ "locoL_fullsat_s20000_K1000": "pretrained full FT 20k (cross-cohort)",
66
+ "locoL_fullsat_s108500_K1000": "pretrained full FT 108.5k saturated (cross-cohort)",
67
+ "locoL_scratchsat_s50000_K1000": "scratch 50k (cross-cohort)",
68
+ "locoL_scratchsat_s100000_K1000": "scratch 100k (cross-cohort)",
69
+ "locoL_scratchsat_s150000_K1000": "scratch 150k (cross-cohort)",
70
+ "locoL_scratchsat_s162000_K1000": "scratch 162k final (cross-cohort)",
71
+ "lora_n5__raw": "own-cohort pretrained LoRA (5 pairs, cross-fitted)",
72
+ "real_lora__raw": "own-cohort pretrained LoRA (~58 pairs, cross-fitted)"},
73
+ }
74
+ PAIRS = {
75
+ "fold0": [("n5", "scratch_n5__raw", "lora_n5__raw"),
76
+ ("58 pairs vs LoRA", "scratch_full__raw", "real_lora__raw"),
77
+ ("58 pairs vs full FT", "scratch_full__raw", "real_full__raw"),
78
+ ("58 pairs + recipes", "scratch_recipe__raw", "lora_recipe__raw")],
79
+ "loco": [("final scratch vs LoRA r16", "locoL_scratchsat_s162000_K1000", "locoL_lora16sat_s26750_K1000"),
80
+ ("final scratch vs LoRA r64", "locoL_scratchsat_s162000_K1000", "locoL_lora64sat_s59000_K1000"),
81
+ ("final scratch vs full FT 108.5k", "locoL_scratchsat_s162000_K1000", "locoL_fullsat_s108500_K1000"),
82
+ ("final scratch vs full FT 20k", "locoL_scratchsat_s162000_K1000", "locoL_fullsat_s20000_K1000")],
83
+ }
84
+ L1_TYPES = ["Monocyte", "T cell", "B cell", "NK cell"]
85
+ REP_STATE = {"Monocyte": "MS1 monocyte (IL1R2+)", "T cell": "ISG-high T", "B cell": "DN2 / ABC B",
86
+ "ALL": "Plasmablast (markers)"}
87
+ warnings.filterwarnings("ignore", category=RuntimeWarning)
88
+
89
+
90
+ def is_scratch(arm: str) -> bool:
91
+ return "scratch" in arm
92
+
93
+
94
+ def safe_spearman(x: np.ndarray, y: np.ndarray) -> float:
95
+ if len(x) < 3 or np.nanstd(x) == 0 or np.nanstd(y) == 0:
96
+ return np.nan
97
+ return float(spearmanr(x, y).correlation)
98
+
99
+
100
+ def safe_pearson(x: np.ndarray, y: np.ndarray) -> float:
101
+ if len(x) < 3 or np.nanstd(x) == 0 or np.nanstd(y) == 0:
102
+ return np.nan
103
+ return float(pearsonr(x, y)[0])
104
+
105
+
106
+ def abs_log2(r: float) -> float:
107
+ """|log2 gen/obs|; null for a complete miss (r = 0) or undefined r."""
108
+ return float(abs(np.log2(r))) if (r is not None and np.isfinite(r) and r > 0) else np.nan
109
+
110
+
111
+ def rule_parts(st: dict, syms: list[str]):
112
+ sym2col = {s: i for i, s in enumerate(syms)}
113
+ ident = {s: s for s in syms}
114
+ _, pcols, req, exc = state_cols(st, ident, sym2col)
115
+ cols = pcols + [x for r in req for x in r] + exc
116
+ rule_syms = set(st.get("genes", [])) | {x for g in st.get("require_any", []) for x in g} | set(st.get("exclude", []))
117
+ return cols, len(pcols), req, exc, rule_syms
118
+
119
+
120
+ def write(df: pd.DataFrame, name: str) -> None:
121
+ df = df.replace([np.inf, -np.inf], np.nan)
122
+ df.to_csv(OUT / f"confound_{name}.csv", index=False, na_rep="null", float_format="%.6g")
123
+ print(f"wrote confound_{name}.csv ({len(df)} rows)", flush=True)
124
+
125
+
126
+ # ----------------------------------------------------------------------------------------------------------- load
127
+ t0 = time.time()
128
+ STATES = json.loads((PLAN / "tools/states.json").read_text())
129
+ SBY = {s["name"]: s for s in STATES}
130
+ MARKER_STATES = [s["name"] for s in STATES if s["kind"] == "markers"]
131
+ summ = {k: pd.read_csv(PLAN / f"{v[1]}summary.csv") for k, v in SETTINGS.items()}
132
+ perd = {k: pd.read_csv(PLAN / f"{v[1]}per_donor.csv") for k, v in SETTINGS.items()}
133
+ cons = {k: pd.read_csv(PLAN / f"{v[1]}contrasts.csv") for k, v in SETTINGS.items()}
134
+ ARMS = {k: list(dict.fromkeys(summ[k].arm)) for k in SETTINGS}
135
+ GEN = {k: {a: dict(np.load(PLAN / SETTINGS[k][0] / f"{a}.npz", allow_pickle=False)) for a in ARMS[k]}
136
+ for k in SETTINGS}
137
+ SYMS = list(GEN["loco"]["zs__raw"]["marker_symbols"].astype(str))
138
+ DONORS = {k: sorted(set(GEN[k][ARMS[k][0]]["donor"])) for k in SETTINGS}
139
+ for k in SETTINGS:
140
+ for a in ARMS[k]:
141
+ g = GEN[k][a]
142
+ if list(g["marker_symbols"].astype(str)) != SYMS or sorted(set(g["donor"])) != DONORS[k]:
143
+ raise SystemExit(f"{k}/{a}: marker columns or donors differ")
144
+ ob_all = ss.observed(STATES, DONORS["loco"])
145
+ if list(ob_all["marker_symbols"]) != SYMS:
146
+ raise SystemExit("observed marker columns differ")
147
+ GROUPS = ob_all["groups"]
148
+ OBS = {}
149
+ for k in SETTINGS:
150
+ m = np.isin(ob_all["donor"], DONORS[k])
151
+ OBS[k] = {"markers": ob_all["markers"][m], "lib": ob_all["lib"][m], "donor": ob_all["donor"][m],
152
+ "lab": ob_all["lab"][m].reset_index(drop=True)}
153
+ DIDX = {} # donor index per cell, per setting, for bincount
154
+ for k in SETTINGS:
155
+ pos = {d: i for i, d in enumerate(DONORS[k])}
156
+ DIDX[(k, "OBS")] = np.asarray([pos[d] for d in OBS[k]["donor"]])
157
+ for a in ARMS[k]:
158
+ DIDX[(k, a)] = np.asarray([pos[d] for d in GEN[k][a]["donor"]])
159
+ GRP = {k: np.asarray([GROUPS.get(d) for d in DONORS[k]]) for k in SETTINGS}
160
+ print(f"loaded in {time.time() - t0:.1f}s; observed cells {len(ob_all['lib']):,}", flush=True)
161
+
162
+
163
+ def lab_df(k: str, a: str) -> pd.DataFrame:
164
+ if a == "OBS":
165
+ return OBS[k]["lab"]
166
+ return pd.DataFrame({"aifi_l1": GEN[k][a]["aifi_l1"], "aifi_l2": GEN[k][a]["aifi_l2"]})
167
+
168
+
169
+ def per_donor(k: str, a: str, mask: np.ndarray) -> np.ndarray:
170
+ return np.bincount(DIDX[(k, a)][mask], minlength=len(DONORS[k]))
171
+
172
+
173
+ # ------------------------------------------------------------------------------------ (0) reproduction of the screen
174
+ rows = []
175
+ for k in SETTINGS:
176
+ rng = np.random.default_rng(ORIG_THIN_SEED)
177
+ ob = OBS[k]
178
+ rep = []
179
+ for a in ARMS[k]:
180
+ g = GEN[k][a]
181
+ lg = lab_df(k, a)
182
+ for st in STATES:
183
+ po, pg = parent_mask(ob["lab"], st["parent"]), parent_mask(lg, st["parent"])
184
+ if st["kind"] == "label":
185
+ ho = ob["lab"].aifi_l2.isin(st["labels"]).to_numpy() & po
186
+ hg = lg.aifi_l2.isin(st["labels"]).to_numpy() & pg
187
+ ht = ho
188
+ else:
189
+ cols, npos, req, exc, _ = rule_parts(st, SYMS)
190
+ thin = min(1.0, float(np.median(g["lib_measured"][pg])) / float(np.median(ob["lib"][po])))
191
+ co = ob["markers"][:, cols].astype(np.int64)
192
+ ho = call_state(co, st, npos, req, exc) & po
193
+ ct = rng.binomial(co, thin) if thin < 1.0 else co
194
+ ht = call_state(ct, st, npos, req, exc) & po
195
+ hg = call_state(g["markers"][:, cols], st, npos, req, exc) & pg
196
+ rep.append(pd.DataFrame({"arm": a, "state": st["name"], "donor": DONORS[k],
197
+ "obs_parent": per_donor(k, "OBS", po), "obs_state": per_donor(k, "OBS", ho),
198
+ "obsthin_state": per_donor(k, "OBS", ht), "gen_parent": per_donor(k, a, pg),
199
+ "gen_state": per_donor(k, a, hg)}))
200
+ rep = pd.concat(rep)
201
+ mrg = perd[k].merge(rep, on=["arm", "state", "donor"], suffixes=("", "_re"), how="outer", indicator=True)
202
+ row = {"setting": k, "rows_csv": len(perd[k]), "rows_reproduced": len(rep),
203
+ "rows_unmatched": int((mrg["_merge"] != "both").sum())}
204
+ for c in ["obs_parent", "obs_state", "obsthin_state", "gen_parent", "gen_state"]:
205
+ row[f"mismatch_{c}"] = int((mrg[c] != mrg[f"{c}_re"]).sum())
206
+ rows.append(row)
207
+ VALID = pd.DataFrame(rows)
208
+ write(VALID, "validation")
209
+ print(VALID.to_string(index=False), flush=True)
210
+
211
+ # --------------------------------------------------------------------------------------------------------- (a) depth
212
+ rows = []
213
+ for k in SETTINGS:
214
+ ob = OBS[k]
215
+ for P in ["ALL"] + L1_TYPES:
216
+ po = parent_mask(ob["lab"], [P])
217
+ mo = ob["markers"][po].mean(0)
218
+ ref = mo >= 0.1
219
+ olib = ob["lib"][po]
220
+ base = {"setting": k, "parent": P, "n_ref_genes": int(ref.sum())}
221
+ rows.append({**base, "arm": "OBSERVED (native)", "arm_class": "observed", "n_cells": int(po.sum()),
222
+ "lib_q10": np.quantile(olib, .1), "lib_q25": np.quantile(olib, .25), "lib_median": np.median(olib),
223
+ "lib_q75": np.quantile(olib, .75), "lib_q90": np.quantile(olib, .9),
224
+ "marker_share_median": float(np.median(ob["markers"][po].sum(1) / np.maximum(olib, 1))),
225
+ "lib_ratio_vs_obs": 1.0, "marker_sum_ratio_vs_obs": 1.0, "marker_median_ratio_vs_obs": 1.0})
226
+ for a in ARMS[k]:
227
+ g = GEN[k][a]
228
+ pg = parent_mask(lab_df(k, a), [P])
229
+ glib = g["lib_measured"][pg]
230
+ mg = g["markers"][pg].mean(0)
231
+ r_sum = float(mg[ref].sum() / mo[ref].sum())
232
+ r_med = float(np.median(mg[ref] / mo[ref]))
233
+ thin = np.nan
234
+ if P in REP_STATE:
235
+ s = summ[k][(summ[k].arm == a) & (summ[k].state == REP_STATE[P])]
236
+ thin = float(s.thin.iloc[0])
237
+ rows.append({**base, "arm": a, "arm_class": ARM_CLASS[k][a], "n_cells": int(pg.sum()),
238
+ "lib_q10": np.quantile(glib, .1), "lib_q25": np.quantile(glib, .25),
239
+ "lib_median": np.median(glib), "lib_q75": np.quantile(glib, .75),
240
+ "lib_q90": np.quantile(glib, .9),
241
+ "marker_share_median": float(np.median(g["markers"][pg].sum(1) / np.maximum(glib, 1))),
242
+ "lib_ratio_vs_obs": float(np.median(glib) / np.median(olib)),
243
+ "marker_sum_ratio_vs_obs": r_sum, "marker_median_ratio_vs_obs": r_med,
244
+ "screen_thin": thin,
245
+ # generated marker-gene depth relative to the observed reference the screen compared it with
246
+ "marker_depth_vs_screen_reference": r_sum / thin if np.isfinite(thin) else np.nan})
247
+ DEPTH = pd.DataFrame(rows)
248
+ write(DEPTH, "depth")
249
+
250
+ # ------------------------------------------------------------------------------------------- (b) composition, pools
251
+ rows = []
252
+ for k in SETTINGS:
253
+ for a in ["OBS"] + ARMS[k]:
254
+ lab = lab_df(k, a)
255
+ n_d = per_donor(k, a, np.ones(len(lab), bool)).astype(float)
256
+ cats = {t: (lab.aifi_l1 == t).to_numpy() for t in L1_TYPES}
257
+ cats["Plasma cell (L2)"] = (lab.aifi_l2 == "Plasma cell").to_numpy()
258
+ cats["other L1"] = ~lab.aifi_l1.isin(L1_TYPES).to_numpy()
259
+ for t, msk in cats.items():
260
+ c = per_donor(k, a, msk)
261
+ frac = 100 * c / np.where(n_d > 0, n_d, np.nan)
262
+ rows.append({"setting": k, "arm": "OBSERVED" if a == "OBS" else a,
263
+ "arm_class": "observed" if a == "OBS" else ARM_CLASS[k][a], "cell_type": t,
264
+ "n_cells": int(c.sum()), "pooled_pct": 100 * c.sum() / n_d.sum(),
265
+ "donor_mean_pct": float(np.nanmean(frac)), "donor_sd_pct": float(np.nanstd(frac, ddof=1)),
266
+ "donor_min_n": int(c.min()), "donor_median_n": float(np.median(c)),
267
+ "n_donors_lt20": int((c < 20).sum()), "n_donors_zero": int((c == 0).sum())})
268
+ COMP = pd.DataFrame(rows)
269
+ obs_ref = COMP[COMP.arm == "OBSERVED"].set_index(["setting", "cell_type"])
270
+ COMP["gen_over_obs_pooled"] = [r.pooled_pct / obs_ref.loc[(r.setting, r.cell_type), "pooled_pct"]
271
+ for r in COMP.itertuples()]
272
+ COMP["gen_over_obs_donor_mean"] = [r.donor_mean_pct / obs_ref.loc[(r.setting, r.cell_type), "donor_mean_pct"]
273
+ for r in COMP.itertuples()]
274
+ write(COMP, "composition")
275
+
276
+ # cross-check: observed composition implied by obs_parent of the per-donor CSV equals the label-derived one
277
+ chk = []
278
+ for k in SETTINGS:
279
+ P = perd[k][perd[k].arm == ARMS[k][0]].set_index(["state", "donor"])
280
+ tot = P.loc["Plasmablast (label)"].obs_parent
281
+ for t, st in [("Monocyte", "C1Q-high monocyte (reference)"), ("T cell", "ISG-high T"), ("B cell", "DN2 / ABC B")]:
282
+ v = 100 * P.loc[st].obs_parent.sum() / tot.sum()
283
+ lab_v = obs_ref.loc[(k, t), "pooled_pct"]
284
+ chk.append({"setting": k, "cell_type": t, "pct_from_per_donor_csv": v, "pct_from_labels": lab_v})
285
+ v = 100 * P.loc["Plasmablast (label)"].obs_state.sum() / tot.sum()
286
+ chk.append({"setting": k, "cell_type": "Plasma cell (L2)", "pct_from_per_donor_csv": v,
287
+ "pct_from_labels": obs_ref.loc[(k, "Plasma cell (L2)"), "pooled_pct"]})
288
+ print(pd.DataFrame(chk).round(3).to_string(index=False), flush=True)
289
+
290
+ rows = []
291
+ for k in SETTINGS:
292
+ for (a, s), t in perd[k].groupby(["arm", "state"], sort=False):
293
+ rows.append({"setting": k, "arm": a, "arm_class": ARM_CLASS[k][a], "state": s,
294
+ "parent": "+".join(SBY[s]["parent"]),
295
+ "gen_parent_total": int(t.gen_parent.sum()), "gen_parent_donor_min": int(t.gen_parent.min()),
296
+ "gen_parent_donor_median": float(t.gen_parent.median()),
297
+ "n_donors_gen_parent_lt20": int((t.gen_parent < 20).sum()),
298
+ "n_donors_gen_parent_zero": int((t.gen_parent == 0).sum()),
299
+ "obs_parent_total": int(t.obs_parent.sum()), "obs_parent_donor_min": int(t.obs_parent.min()),
300
+ "obs_parent_donor_median": float(t.obs_parent.median()),
301
+ "gen_parent_pct_of_cells": 100 * t.gen_parent.sum() / (1500 * len(t)),
302
+ "gen_state_total": int(t.gen_state.sum()), "obsthin_state_total": int(t.obsthin_state.sum()),
303
+ "n_donors_gen_state_zero": int((t.gen_state == 0).sum())})
304
+ POOLS = pd.DataFrame(rows)
305
+ tot_obs = {k: perd[k][(perd[k].arm == ARMS[k][0]) & (perd[k].state == "Plasmablast (label)")].obs_parent.sum()
306
+ for k in SETTINGS}
307
+ POOLS["obs_parent_pct_of_cells"] = [100 * r.obs_parent_total / tot_obs[r.setting] for r in POOLS.itertuples()]
308
+ POOLS["parent_gen_over_obs"] = POOLS.gen_parent_pct_of_cells / POOLS.obs_parent_pct_of_cells
309
+ write(POOLS, "parent_pools")
310
+
311
+ S_IDX = {k: summ[k].set_index(["arm", "state"]) for k in SETTINGS}
312
+ rows = []
313
+ for k in SETTINGS:
314
+ for lab_, sa, pa in PAIRS[k]:
315
+ for s in FOCUS + CONTROLS + ["Plasmablast (label)", "Proliferating T (label)", "Cycling T/NK",
316
+ "Granulocyte-like (LDG)", "HSPC"]:
317
+ ts = perd[k][(perd[k].arm == sa) & (perd[k].state == s)]
318
+ tp = perd[k][(perd[k].arm == pa) & (perd[k].state == s)]
319
+ n_s, n_p = 1500 * len(ts), 1500 * len(tp)
320
+ pf_s, pf_p = ts.gen_parent.sum() / n_s, tp.gen_parent.sum() / n_p
321
+ w_s = ts.gen_state.sum() / max(ts.gen_parent.sum(), 1)
322
+ w_p = tp.gen_state.sum() / max(tp.gen_parent.sum(), 1)
323
+ l2 = lambda x, y: float(np.log2(x / y)) if (x > 0 and y > 0) else np.nan # noqa: E731
324
+ rows.append({"setting": k, "pair": lab_, "scratch_arm": sa, "pretrained_arm": pa, "state": s,
325
+ "parent": "+".join(SBY[s]["parent"]),
326
+ "scratch_parent_pct": 100 * pf_s, "pretrained_parent_pct": 100 * pf_p,
327
+ "scratch_within_parent_pct": 100 * w_s, "pretrained_within_parent_pct": 100 * w_p,
328
+ "scratch_state_per_1000_cells": 1000 * ts.gen_state.sum() / n_s,
329
+ "pretrained_state_per_1000_cells": 1000 * tp.gen_state.sum() / n_p,
330
+ "log2_parent_frac_scratch_over_pretrained": l2(pf_s, pf_p),
331
+ "log2_within_parent_scratch_over_pretrained": l2(w_s, w_p),
332
+ "log2_state_per_cell_scratch_over_pretrained": l2(ts.gen_state.sum() / n_s,
333
+ tp.gen_state.sum() / n_p),
334
+ "scratch_gen_over_obs_screen": float(S_IDX[k].loc[(sa, s), "gen_over_obs"]),
335
+ "pretrained_gen_over_obs_screen": float(S_IDX[k].loc[(pa, s), "gen_over_obs"]),
336
+ "scratch_gen_state_total": int(ts.gen_state.sum()),
337
+ "pretrained_gen_state_total": int(tp.gen_state.sum())})
338
+ DECOMP = pd.DataFrame(rows)
339
+ DECOMP["share_of_log2_difference_from_parent_pool"] = (
340
+ DECOMP.log2_parent_frac_scratch_over_pretrained / DECOMP.log2_state_per_cell_scratch_over_pretrained)
341
+ write(DECOMP, "decomposition")
342
+
343
+
344
+ # ---------------------------------------------------------------------------------- (c) depth-matching sensitivity
345
+ def metrics(k: str, gs, gp, os_, op) -> dict:
346
+ rg = 100 * gs.sum() / max(gp.sum(), 1)
347
+ ro = 100 * os_.sum() / max(op.sum(), 1)
348
+ ratio = rg / ro if ro > 0 else np.nan
349
+ gpct = np.where(gp > 0, 100 * gs / np.maximum(gp, 1), np.nan)
350
+ opct = np.where(op > 0, 100 * os_ / np.maximum(op, 1), np.nan)
351
+ ok = ~np.isnan(gpct) & ~np.isnan(opct)
352
+ out = {"gen_state": int(gs.sum()), "gen_parent": int(gp.sum()), "gen_pct": rg,
353
+ "obs_state": int(os_.sum()), "obs_parent": int(op.sum()), "obs_pct": ro, "gen_over_obs": ratio,
354
+ "abs_log2": abs_log2(ratio), "complete_miss": bool(gs.sum() == 0),
355
+ "spearman_donors": safe_spearman(gpct[ok], opct[ok]),
356
+ "gen_over_obs_donor_mean": (np.nanmean(gpct) / np.nanmean(opct)) if np.nanmean(opct) > 0 else np.nan}
357
+ for name, A, Bg in ss.CONTRASTS:
358
+ ia, ib = np.isin(GRP[k], A), np.isin(GRP[k], Bg)
359
+ od = np.nanmean(opct[ia]) - np.nanmean(opct[ib])
360
+ gd = np.nanmean(gpct[ia]) - np.nanmean(gpct[ib])
361
+ key = {"adult sepsis vs adult HC": "adult", "paediatric sepsis vs paediatric HC": "ped",
362
+ "all sepsis vs all controls": "all"}[name]
363
+ out[f"obs_diff_{key}"], out[f"gen_diff_{key}"] = od, gd
364
+ out[f"same_direction_{key}"] = (bool(np.sign(od) == np.sign(gd))
365
+ if np.isfinite(od) and np.isfinite(gd) else None)
366
+ return out
367
+
368
+
369
+ rng_thin = np.random.default_rng(SEED)
370
+ PDON = {} # (setting, scheme, state, arm) -> (gen_state, gen_parent, obs_state, obs_parent) per donor
371
+ rows, trows = [], []
372
+ for k in SETTINGS:
373
+ ob = OBS[k]
374
+ for st in STATES:
375
+ s = st["name"]
376
+ # V0: the screen as published (per-donor CSV; each arm has its own observed thinning)
377
+ for a in ARMS[k]:
378
+ t = perd[k][(perd[k].arm == a) & (perd[k].state == s)].set_index("donor").loc[DONORS[k]]
379
+ v = (t.gen_state.to_numpy(), t.gen_parent.to_numpy(), t.obsthin_state.to_numpy(), t.obs_parent.to_numpy())
380
+ PDON[(k, "V0_screen", s, a)] = v
381
+ rows.append({"setting": k, "scheme": "V0_screen", "state": s, "arm": a, "arm_class": ARM_CLASS[k][a],
382
+ "p_gen": 1.0, "p_obs": float(S_IDX[k].loc[(a, s), "thin"]), **metrics(k, *v)})
383
+ if st["kind"] != "markers":
384
+ continue
385
+ cols, npos, req, exc, rule_syms = rule_parts(st, SYMS)
386
+ po = parent_mask(ob["lab"], st["parent"])
387
+ mo = ob["markers"][po].mean(0)
388
+ ref = np.asarray([(sym not in rule_syms) and mo[j] >= 0.1 for j, sym in enumerate(SYMS)])
389
+ olib_med = float(np.median(ob["lib"][po]))
390
+ pg_ = {a: parent_mask(lab_df(k, a), st["parent"]) for a in ARMS[k]}
391
+ glib_med = {a: float(np.median(GEN[k][a]["lib_measured"][pg_[a]])) for a in ARMS[k]}
392
+ rsum, rmed = {}, {}
393
+ for a in ARMS[k]:
394
+ mg = GEN[k][a]["markers"][pg_[a]].mean(0)
395
+ rsum[a] = float(mg[ref].sum() / mo[ref].sum())
396
+ rmed[a] = float(np.median(mg[ref] / mo[ref]))
397
+ if min(rsum.values()) <= 0 or min(rmed.values()) <= 0 or min(glib_med.values()) <= 0:
398
+ raise SystemExit(f"{k}/{s}: zero effective depth in some arm; schemes undefined")
399
+ targets = {
400
+ "V1_lib": (min(min(glib_med.values()), olib_med),
401
+ {a: min(1.0, min(min(glib_med.values()), olib_med) / glib_med[a]) for a in ARMS[k]},
402
+ min(1.0, min(min(glib_med.values()), olib_med) / olib_med)),
403
+ "V2_msum": (min(1.0, min(rsum.values())), {a: min(1.0, min(1.0, min(rsum.values())) / rsum[a])
404
+ for a in ARMS[k]}, min(1.0, min(rsum.values()))),
405
+ "V3_mmed": (min(1.0, min(rmed.values())), {a: min(1.0, min(1.0, min(rmed.values())) / rmed[a])
406
+ for a in ARMS[k]}, min(1.0, min(rmed.values()))),
407
+ }
408
+ co = ob["markers"][po][:, cols].astype(np.int64)
409
+ for sch, (target, pga, pob) in targets.items():
410
+ trows.append({"setting": k, "state": s, "scheme": sch, "target": target, "p_obs": pob,
411
+ "reference_genes": ";".join(np.asarray(SYMS)[ref]) if sch != "V1_lib" else "",
412
+ "lowest_arm": (min(glib_med, key=glib_med.get) if sch == "V1_lib" else
413
+ min(rsum, key=rsum.get) if sch == "V2_msum" else min(rmed, key=rmed.get)),
414
+ **{f"p_gen[{a}]": pga[a] for a in ARMS[k]}})
415
+ ct = rng_thin.binomial(co, pob) if pob < 1.0 else co
416
+ ho = np.zeros(len(po), bool)
417
+ ho[po] = call_state(ct, st, npos, req, exc)
418
+ os_, op = per_donor(k, "OBS", ho), per_donor(k, "OBS", po)
419
+ for a in ARMS[k]:
420
+ cg = GEN[k][a]["markers"][pg_[a]][:, cols].astype(np.int64)
421
+ cgt = rng_thin.binomial(cg, pga[a]) if pga[a] < 1.0 else cg
422
+ hg = np.zeros(len(pg_[a]), bool)
423
+ hg[pg_[a]] = call_state(cgt, st, npos, req, exc)
424
+ v = (per_donor(k, a, hg), per_donor(k, a, pg_[a]), os_, op)
425
+ PDON[(k, sch, s, a)] = v
426
+ rows.append({"setting": k, "scheme": sch, "state": s, "arm": a, "arm_class": ARM_CLASS[k][a],
427
+ "p_gen": pga[a], "p_obs": pob, **metrics(k, *v)})
428
+ print(f"{k}: depth-matching done ({time.time() - t0:.1f}s)", flush=True)
429
+ DM = pd.DataFrame(rows)
430
+ write(DM, "depthmatch")
431
+ write(pd.DataFrame(trows), "depthmatch_targets")
432
+
433
+ # per-donor counts of the schemes for the focus states and controls (traceability)
434
+ rows = []
435
+ for (k, sch, s, a), (gs, gp, os_, op) in PDON.items():
436
+ if s in FOCUS + CONTROLS and sch != "V0_screen":
437
+ rows.append(pd.DataFrame({"setting": k, "scheme": sch, "state": s, "arm": a, "donor": DONORS[k],
438
+ "group": GRP[k], "gen_state": gs, "gen_parent": gp, "obs_state": os_,
439
+ "obs_parent": op}))
440
+ write(pd.concat(rows), "depthmatch_per_donor")
441
+
442
+ # pairs: which arm is closer to gen/obs = 1, per scheme, with a donor bootstrap
443
+ rng_boot = np.random.default_rng(SEED)
444
+
445
+
446
+ def boot_abslog2(idx, gs, gp, os_, op):
447
+ rg = gs[idx].sum(1) / np.maximum(gp[idx].sum(1), 1)
448
+ ro = os_[idx].sum(1) / np.maximum(op[idx].sum(1), 1)
449
+ r = np.where(ro > 0, rg / np.where(ro > 0, ro, 1), np.nan)
450
+ a = np.where(r > 0, np.abs(np.log2(np.where(r > 0, r, 1))), np.inf) # complete miss -> inf (worst)
451
+ return np.where(np.isnan(r), np.nan, a)
452
+
453
+
454
+ rows = []
455
+ DMI = DM.set_index(["setting", "scheme", "state", "arm"])
456
+ for k in SETTINGS:
457
+ nd = len(DONORS[k])
458
+ for sch in ["V0_screen", "V1_lib", "V2_msum", "V3_mmed"]:
459
+ for s in MARKER_STATES + ["Plasmablast (label)", "Proliferating T (label)"]:
460
+ if (k, sch, s, ARMS[k][0]) not in PDON:
461
+ continue
462
+ for lab_, sa, pa in PAIRS[k]:
463
+ rs, rp = DMI.loc[(k, sch, s, sa)], DMI.loc[(k, sch, s, pa)]
464
+ as_ = rs.abs_log2 if not rs.complete_miss else np.inf
465
+ ap_ = rp.abs_log2 if not rp.complete_miss else np.inf
466
+ closer = ("undefined" if (np.isnan(as_) or np.isnan(ap_)) else
467
+ "scratch" if as_ < ap_ else "pretrained" if ap_ < as_ else "tie")
468
+ idx = rng_boot.integers(0, nd, size=(NBOOT, nd))
469
+ bs = boot_abslog2(idx, *PDON[(k, sch, s, sa)])
470
+ bp = boot_abslog2(idx, *PDON[(k, sch, s, pa)])
471
+ ok = ~np.isnan(bs) & ~np.isnan(bp)
472
+ p_closer = float(np.mean(bs[ok] < bp[ok]) + 0.5 * np.mean(bs[ok] == bp[ok])) if ok.any() else np.nan
473
+ gs_s, gp_s = PDON[(k, sch, s, sa)][:2]
474
+ gs_p, gp_p = PDON[(k, sch, s, pa)][:2]
475
+ rate_s = gs_s[idx].sum(1) / np.maximum(gp_s[idx].sum(1), 1)
476
+ rate_p = gs_p[idx].sum(1) / np.maximum(gp_p[idx].sum(1), 1)
477
+ rows.append({"setting": k, "scheme": sch, "state": s, "pair": lab_, "scratch_arm": sa,
478
+ "pretrained_arm": pa,
479
+ "scratch_gen_over_obs": rs.gen_over_obs, "pretrained_gen_over_obs": rp.gen_over_obs,
480
+ "scratch_abs_log2": rs.abs_log2, "pretrained_abs_log2": rp.abs_log2,
481
+ "scratch_complete_miss": rs.complete_miss, "pretrained_complete_miss": rp.complete_miss,
482
+ "closer_to_1": closer, "boot_p_scratch_closer": p_closer,
483
+ "scratch_gen_pct": rs.gen_pct, "pretrained_gen_pct": rp.gen_pct,
484
+ "boot_p_scratch_gen_pct_higher": float(np.mean(rate_s > rate_p) +
485
+ 0.5 * np.mean(rate_s == rate_p)),
486
+ "scratch_spearman": rs.spearman_donors, "pretrained_spearman": rp.spearman_donors,
487
+ "scratch_gen_state": rs.gen_state, "pretrained_gen_state": rp.gen_state,
488
+ "obs_state_scratch_ref": rs.obs_state, "obs_state_pretrained_ref": rp.obs_state})
489
+ PAIRDF = pd.DataFrame(rows)
490
+ v0 = PAIRDF[PAIRDF.scheme == "V0_screen"].set_index(["setting", "state", "pair"]).closer_to_1
491
+ PAIRDF["closer_to_1_V0"] = [v0.get((r.setting, r.state, r.pair)) for r in PAIRDF.itertuples()]
492
+ PAIRDF["ordering_changed_vs_V0"] = [(r.closer_to_1 != r.closer_to_1_V0) if r.scheme != "V0_screen" else False
493
+ for r in PAIRDF.itertuples()]
494
+ PAIRDF["in_focus"] = PAIRDF.state.isin(FOCUS)
495
+ write(PAIRDF, "depthmatch_pairs")
496
+
497
+ # ------------------------------------------------------------------------------------------- (d) spread / collapse
498
+ rows = []
499
+ for (k, sch, s, a), (gs, gp, os_, op) in PDON.items():
500
+ if sch not in ("V0_screen", "V2_msum"):
501
+ continue
502
+ ok = (gp >= 20) & (op >= 20)
503
+ gpct, opct = 100 * gs[ok] / gp[ok], 100 * os_[ok] / op[ok]
504
+ sdg, sdo = (float(np.std(gpct, ddof=1)), float(np.std(opct, ddof=1))) if ok.sum() > 2 else (np.nan, np.nan)
505
+ rows.append({"setting": k, "scheme": sch, "state": s, "arm": a, "arm_class": ARM_CLASS[k][a],
506
+ "n_donors_parent_ge20": int(ok.sum()), "sd_gen_pct": sdg, "sd_obs_pct": sdo,
507
+ "sd_ratio_gen_over_obs": sdg / sdo if (sdo and np.isfinite(sdo) and sdo > 0) else np.nan,
508
+ "iqr_gen_pct": float(np.subtract(*np.percentile(gpct, [75, 25]))) if ok.sum() > 2 else np.nan,
509
+ "iqr_obs_pct": float(np.subtract(*np.percentile(opct, [75, 25]))) if ok.sum() > 2 else np.nan,
510
+ "mean_gen_pct": float(np.mean(gpct)) if ok.any() else np.nan,
511
+ "mean_obs_pct": float(np.mean(opct)) if ok.any() else np.nan,
512
+ "n_donors_gen_state_zero": int((gs[ok] == 0).sum()),
513
+ "spearman_donors": safe_spearman(gpct, opct)})
514
+ write(pd.DataFrame(rows), "collapse_states")
515
+
516
+ rows = []
517
+ for k in SETTINGS:
518
+ nd = len(DONORS[k])
519
+ lab_o = lab_df(k, "OBS")
520
+ n_o = per_donor(k, "OBS", np.ones(len(lab_o), bool))
521
+ fo = {t: 100 * per_donor(k, "OBS", (lab_o.aifi_l1 == t).to_numpy()) / n_o for t in L1_TYPES}
522
+ fo["Plasma cell (L2)"] = 100 * per_donor(k, "OBS", (lab_o.aifi_l2 == "Plasma cell").to_numpy()) / n_o
523
+ for a in ARMS[k]:
524
+ lab = lab_df(k, a)
525
+ n_g = per_donor(k, a, np.ones(len(lab), bool))
526
+ r_all = []
527
+ for t in L1_TYPES + ["Plasma cell (L2)"]:
528
+ msk = (lab.aifi_l2 == "Plasma cell").to_numpy() if t == "Plasma cell (L2)" else (lab.aifi_l1 == t).to_numpy()
529
+ fg = 100 * per_donor(k, a, msk) / n_g
530
+ sdg, sdo = float(np.std(fg, ddof=1)), float(np.std(fo[t], ddof=1))
531
+ r = safe_pearson(fg, fo[t])
532
+ r_all.append(r)
533
+ rows.append({"setting": k, "arm": a, "arm_class": ARM_CLASS[k][a], "cell_type": t,
534
+ "sd_gen_pct": sdg, "sd_obs_pct": sdo, "sd_ratio_gen_over_obs": sdg / sdo if sdo > 0 else np.nan,
535
+ "pearson_donors": r, "spearman_donors": safe_spearman(fg, fo[t]),
536
+ "mean_gen_pct": float(np.mean(fg)), "mean_obs_pct": float(np.mean(fo[t]))})
537
+ rows.append({"setting": k, "arm": a, "arm_class": ARM_CLASS[k][a], "cell_type": "MEAN over 4 L1 types",
538
+ "pearson_donors": float(np.nanmean(r_all[:4]))})
539
+ write(pd.DataFrame(rows), "collapse_composition")
540
+
541
+
542
+ def gene_stats(M: np.ndarray, didx: np.ndarray, nd: int, min_cells: int = 20):
543
+ """Per donor (>= min_cells parent cells): mean, variance and n of each gene's counts."""
544
+ n = np.bincount(didx, minlength=nd).astype(float)
545
+ s1 = np.stack([np.bincount(didx, weights=M[:, j], minlength=nd) for j in range(M.shape[1])], 1)
546
+ s2 = np.stack([np.bincount(didx, weights=M[:, j].astype(float) ** 2, minlength=nd) for j in range(M.shape[1])], 1)
547
+ keep = n >= min_cells
548
+ nn = np.where(keep, n, np.nan)[:, None]
549
+ mu = s1 / nn
550
+ var = (s2 - nn * mu ** 2) / (nn - 1)
551
+ return mu, var, n, keep
552
+
553
+
554
+ rows, grows = [], []
555
+ for k in SETTINGS:
556
+ nd = len(DONORS[k])
557
+ ob = OBS[k]
558
+ for P in L1_TYPES:
559
+ po = parent_mask(ob["lab"], [P])
560
+ mo_all = ob["markers"][po].mean(0)
561
+ genes = np.flatnonzero(mo_all >= 0.2)
562
+ mu_o, var_o, n_o, keep_o = gene_stats(ob["markers"][po][:, genes].astype(float), DIDX[(k, "OBS")][po], nd)
563
+ for a in ["OBS"] + ARMS[k]:
564
+ if a == "OBS":
565
+ mu, var, n, keep = mu_o, var_o, n_o, keep_o
566
+ else:
567
+ pg = parent_mask(lab_df(k, a), [P])
568
+ mu, var, n, keep = gene_stats(GEN[k][a]["markers"][pg][:, genes].astype(float), DIDX[(k, a)][pg], nd)
569
+ for jj, j in enumerate(genes):
570
+ m, v = mu[keep, jj], var[keep, jj]
571
+ gm = np.mean(m)
572
+ cv2 = np.var(m, ddof=1) / gm ** 2 if gm > 0 and keep.sum() > 2 else np.nan
573
+ floor2 = np.mean(v / n[keep]) / gm ** 2 if gm > 0 else np.nan
574
+ phi = np.median(np.where(m > 0.05, (v - m) / np.where(m > 0.05, m, 1) ** 2, np.nan)[m > 0.05]) \
575
+ if (m > 0.05).any() else np.nan
576
+ both = keep & keep_o
577
+ rho = safe_spearman(mu[both, jj], mu_o[both, jj]) if a != "OBS" else np.nan
578
+ grows.append({"setting": k, "parent": P, "arm": "OBSERVED" if a == "OBS" else a, "gene": SYMS[j],
579
+ "mean_count": gm, "between_donor_cv_raw": np.sqrt(cv2) if np.isfinite(cv2) else np.nan,
580
+ "between_donor_cv_floor_removed": np.sqrt(max(cv2 - floor2, 0))
581
+ if np.isfinite(cv2) and np.isfinite(floor2) else np.nan,
582
+ "within_donor_excess_dispersion": phi, "spearman_donor_means_vs_obs": rho,
583
+ "n_donors": int(keep.sum())})
584
+ print(f"{k}: marker spread done ({time.time() - t0:.1f}s)", flush=True)
585
+ G = pd.DataFrame(grows)
586
+ write(G, "collapse_markers_pergene")
587
+ obs_g = G[G.arm == "OBSERVED"].set_index(["setting", "parent", "gene"])
588
+ for r in G.groupby(["setting", "parent", "arm"], sort=False):
589
+ (k, P, a), t = r
590
+ o = obs_g.loc[[(k, P, gname) for gname in t.gene]]
591
+ cv_ratio = t.between_donor_cv_floor_removed.to_numpy() / o.between_donor_cv_floor_removed.to_numpy()
592
+ rows.append({"setting": k, "parent": P, "arm": a,
593
+ "arm_class": "observed" if a == "OBSERVED" else ARM_CLASS[k][a], "n_genes": len(t),
594
+ "median_between_donor_cv_floor_removed": float(np.nanmedian(t.between_donor_cv_floor_removed)),
595
+ "median_cv_ratio_gen_over_obs": float(np.nanmedian(cv_ratio)),
596
+ "frac_genes_cv_lt_half_obs": float(np.nanmean(cv_ratio < 0.5)),
597
+ "median_within_donor_excess_dispersion": float(np.nanmedian(t.within_donor_excess_dispersion)),
598
+ "median_spearman_donor_means_vs_obs": float(np.nanmedian(t.spearman_donor_means_vs_obs)),
599
+ "min_n_donors": int(t.n_donors.min())})
600
+ write(pd.DataFrame(rows), "collapse_markers")
601
+
602
+ # ----------------------------------------------------------------------------------------------------- (e) small n
603
+ rows = []
604
+ for k in SETTINGS:
605
+ for name, A, Bg in ss.CONTRASTS:
606
+ ia, ib = np.isin(GRP[k], A), np.isin(GRP[k], Bg)
607
+ rows.append({"setting": k, "contrast": name, "n_a": int(ia.sum()), "n_b": int(ib.sum()),
608
+ "groups_a": "+".join(A), "groups_b": "+".join(Bg),
609
+ "small_n_flag_le2": bool(min(ia.sum(), ib.sum()) <= 2)})
610
+ for gname, c in pd.Series(GRP[k]).value_counts().items():
611
+ rows.append({"setting": k, "contrast": f"group size: {gname}", "n_a": int(c)})
612
+ write(pd.DataFrame(rows), "groupsizes")
613
+
614
+ rng_boot2 = np.random.default_rng(SEED)
615
+ rows = []
616
+ for k in SETTINGS:
617
+ for a in ARMS[k]:
618
+ for s in [st["name"] for st in STATES]:
619
+ gs, gp, os_, op = PDON[(k, "V0_screen", s, a)]
620
+ gpct = np.where(gp > 0, 100 * gs / np.maximum(gp, 1), np.nan)
621
+ opct = np.where(op > 0, 100 * os_ / np.maximum(op, 1), np.nan)
622
+ for name, A, Bg in ss.CONTRASTS:
623
+ ia, ib = np.flatnonzero(np.isin(GRP[k], A)), np.flatnonzero(np.isin(GRP[k], Bg))
624
+ od = np.nanmean(opct[ia]) - np.nanmean(opct[ib])
625
+ gd = np.nanmean(gpct[ia]) - np.nanmean(gpct[ib])
626
+ same = bool(np.sign(od) == np.sign(gd)) if (np.isfinite(od) and np.isfinite(gd)) else None
627
+ flips, n_loo = 0, 0
628
+ for d in (np.concatenate([ia, ib]) if same is not None else []):
629
+ ja, jb = ia[ia != d], ib[ib != d]
630
+ if len(ja) == 0 or len(jb) == 0:
631
+ continue
632
+ od2 = np.nanmean(opct[ja]) - np.nanmean(opct[jb])
633
+ gd2 = np.nanmean(gpct[ja]) - np.nanmean(gpct[jb])
634
+ if not (np.isfinite(od2) and np.isfinite(gd2)):
635
+ continue
636
+ n_loo += 1
637
+ flips += int(bool(np.sign(od2) == np.sign(gd2)) != same)
638
+ ba = ia[rng_boot2.integers(0, len(ia), size=(NBOOT, len(ia)))]
639
+ bb = ib[rng_boot2.integers(0, len(ib), size=(NBOOT, len(ib)))]
640
+ odb = np.nanmean(opct[ba], 1) - np.nanmean(opct[bb], 1)
641
+ gdb = np.nanmean(gpct[ba], 1) - np.nanmean(gpct[bb], 1)
642
+ okb = np.isfinite(odb) & np.isfinite(gdb)
643
+ rows.append({"setting": k, "arm": a, "arm_class": ARM_CLASS[k][a], "state": s, "contrast": name,
644
+ "n_a": len(ia), "n_b": len(ib), "small_n_flag_le2": min(len(ia), len(ib)) <= 2,
645
+ "gen_state_a": int(gs[ia].sum()), "gen_state_b": int(gs[ib].sum()),
646
+ "gen_parent_a": int(gp[ia].sum()), "gen_parent_b": int(gp[ib].sum()),
647
+ "obs_state_a": int(os_[ia].sum()), "obs_state_b": int(os_[ib].sum()),
648
+ "low_gen_count_flag_lt10": int(gs[ia].sum() + gs[ib].sum()) < 10,
649
+ "obs_diff": od, "gen_diff": gd, "same_direction": same,
650
+ "loo_n": n_loo, "loo_flips": flips,
651
+ "loo_stable": (flips == 0) if n_loo > 0 else None,
652
+ "boot_p_same_direction": float(np.mean(np.sign(odb[okb]) == np.sign(gdb[okb])))
653
+ if okb.any() else np.nan})
654
+ SMALLN = pd.DataFrame(rows)
655
+ # consistency with the screen's own contrast table
656
+ chk = []
657
+ for k in SETTINGS:
658
+ m = SMALLN[SMALLN.setting == k].merge(cons[k], on=["arm", "state", "contrast"], suffixes=("", "_screen"))
659
+ chk.append({"setting": k, "rows": len(m), "same_direction_mismatch": int((m.same_direction.astype(bool) !=
660
+ m.same_direction_screen).sum())})
661
+ print(pd.DataFrame(chk).to_string(index=False), flush=True)
662
+ write(SMALLN, "smalln")
663
+
664
+ # ------------------------------------------------------------------------------------------------------ (f) controls
665
+ CTRL = DM[DM.state.isin(CONTROLS)].copy()
666
+ write(CTRL, "controls")
667
+
668
+ # ------------------------------------------------------------------------------ ordering verdict (summary of c, f)
669
+ # V1_lib is not a valid depth reference for the cross-cohort scratch arms: their library is ~10x the observed one but
670
+ # the extracted marker genes carry ~0.1 % of it (observed ~1.2 %), so library-ratio thinning removes ~95 % of their
671
+ # marker counts (see confound_depth.csv, marker_share_median). It is reported in depthmatch*.csv but excluded here
672
+ # for loco. Robust = same arm closer to gen/obs = 1 in every valid scheme and donor-bootstrap P >= 0.8 (or <= 0.2).
673
+ rows = []
674
+ for (k, s, pair), t in PAIRDF[PAIRDF.state.isin(FOCUS + CONTROLS)].groupby(["setting", "state", "pair"], sort=False):
675
+ t = t.set_index("scheme")
676
+ valid = ["V0_screen", "V1_lib", "V2_msum", "V3_mmed"] if k == "fold0" else ["V0_screen", "V2_msum", "V3_mmed"]
677
+ cl = [t.loc[v, "closer_to_1"] for v in valid]
678
+ ps = [t.loc[v, "boot_p_scratch_closer"] for v in valid]
679
+ if all(c == "scratch" for c in cl) and min(ps) >= 0.8:
680
+ verdict = "scratch closer, robust"
681
+ elif all(c == "pretrained" for c in cl) and max(ps) <= 0.2:
682
+ verdict = "pretrained closer, robust"
683
+ elif len(set(cl)) == 1:
684
+ verdict = f"{cl[0]} closer in all valid schemes, bootstrap-uncertain"
685
+ else:
686
+ verdict = "scheme-dependent"
687
+ both_low = all(max(t.loc[v, "scratch_gen_over_obs"], t.loc[v, "pretrained_gen_over_obs"]) < 0.25
688
+ for v in ["V0_screen", "V2_msum"])
689
+ # preferred pair of schemes: the screen as published (V0) and the marker-sum depth match (V2); V3 is a stress test
690
+ c02 = [t.loc[v, "closer_to_1"] for v in ("V0_screen", "V2_msum")]
691
+ p02 = [t.loc[v, "boot_p_scratch_closer"] for v in ("V0_screen", "V2_msum")]
692
+ v02 = ("scratch closer, robust" if all(c == "scratch" for c in c02) and min(p02) >= 0.8 else
693
+ "pretrained closer, robust" if all(c == "pretrained" for c in c02) and max(p02) <= 0.2 else
694
+ f"{c02[0]} closer in V0 and V2, bootstrap-uncertain" if c02[0] == c02[1] else "flips between V0 and V2")
695
+ # donor-equal weighting (mean of per-donor %) instead of pooled counts
696
+ dmc = {}
697
+ for v in ("V0_screen", "V2_msum"):
698
+ a_s = abs_log2(DMI.loc[(k, v, s, t.scratch_arm.iloc[0]), "gen_over_obs_donor_mean"])
699
+ a_p = abs_log2(DMI.loc[(k, v, s, t.pretrained_arm.iloc[0]), "gen_over_obs_donor_mean"])
700
+ a_s, a_p = (np.inf if np.isnan(a_s) else a_s), (np.inf if np.isnan(a_p) else a_p)
701
+ dmc[v] = "scratch" if a_s < a_p else "pretrained" if a_p < a_s else "tie"
702
+ rows.append({"setting": k, "state": s, "pair": pair, "scratch_arm": t.scratch_arm.iloc[0],
703
+ "pretrained_arm": t.pretrained_arm.iloc[0], "valid_schemes": ";".join(valid),
704
+ "closer_by_scheme": ";".join(f"{v}={c}" for v, c in zip(valid, cl)),
705
+ "boot_p_scratch_closer_min": float(np.nanmin(ps)), "boot_p_scratch_closer_max": float(np.nanmax(ps)),
706
+ "verdict": verdict, "verdict_V0_V2": v02,
707
+ "boot_p_scratch_closer_V0": p02[0], "boot_p_scratch_closer_V2": p02[1],
708
+ "closer_donor_mean_weighting_V0": dmc["V0_screen"], "closer_donor_mean_weighting_V2": dmc["V2_msum"],
709
+ "both_arms_below_0.25_in_V0_and_V2": both_low,
710
+ "scratch_g_o_V0": t.loc["V0_screen", "scratch_gen_over_obs"],
711
+ "pretrained_g_o_V0": t.loc["V0_screen", "pretrained_gen_over_obs"],
712
+ "scratch_g_o_V2": t.loc["V2_msum", "scratch_gen_over_obs"],
713
+ "pretrained_g_o_V2": t.loc["V2_msum", "pretrained_gen_over_obs"],
714
+ "scratch_g_o_V1": t.loc["V1_lib", "scratch_gen_over_obs"],
715
+ "pretrained_g_o_V1": t.loc["V1_lib", "pretrained_gen_over_obs"],
716
+ "V1_valid": k == "fold0"})
717
+ write(pd.DataFrame(rows), "ordering_verdict")
718
+ print(pd.DataFrame(rows)[["setting", "state", "pair", "verdict", "verdict_V0_V2", "both_arms_below_0.25_in_V0_and_V2",
719
+ "boot_p_scratch_closer_V0", "boot_p_scratch_closer_V2"]].round(2).to_string(index=False))
720
+ print(f"done in {time.time() - t0:.1f}s", flush=True)
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/cross_analysis.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rare states, cross-cohort setting: from scratch vs pretrained (CPU only, 2026-10-05).
3
+
4
+ Setting: plans/paired_crosscohort_20261002 split hoL_ye2026_sepsis. All 82 usable Ye 2026 sepsis donors are held out;
5
+ the models trained on ImMicro + Imperial + Giroux + Liu pairs only. Reads (never writes) the rare-state screen outputs
6
+ out/sepsis_loco_{summary,contrasts,per_donor}.csv, the per-cell extracts work/sepsis/loco/<arm>.npz and the benchmark
7
+ summaries plans/paired_crosscohort_20261002/scores/ye2026_sepsis/<arm>/summary.json. Writes only
8
+ out/scratch_vs_lora_20261005/cross_*.csv.
9
+
10
+ ratio (= gen_over_obs) = [sum gen_state / sum gen_parent] / [sum obsthin_state / sum obs_parent], pooled over donors.
11
+ Fidelity = |log2 ratio| (0 = the observed frequency).
12
+ Bootstrap: donors resampled with replacement, B = 2000, numpy default_rng(20261005).integers(0, 82, (2000, 82)) over the
13
+ donors in sorted order; ONE index matrix shared by every arm, state, reference and comparison (so every comparison is
14
+ paired). 0.5 is added to the pooled state counts (generated and observed) in the point estimate and in every replicate.
15
+ D = |log2 ratio_scratch| - |log2 ratio_comparator|; 95 % percentile CI. D > 0 with CI > 0: comparator closer.
16
+ Reference variants:
17
+ own_ref each arm against its own depth-thinned observed counts (the screen's definition; primary).
18
+ pretrained_depth_ref the scratch arm against the comparator's thinned observed counts (vs xcal and vs scratch arms:
19
+ the LoRA r16 reference). Reason: the scratch model's cells have a ~20,000-UMI median library,
20
+ so the screen did not thin the observed cells for it (thin = 1), but their marker-gene detection
21
+ equals that of the ~1,000-UMI pretrained cross-cohort arms (cross_depth_check.csv).
22
+ Contrasts: recomputed from the per-donor CSV exactly as tools/sepsis_states.py (difference of donor-mean percentages)
23
+ and checked against out/sepsis_loco_contrasts.csv. eligible_own: informative state and |obs_diff| >= 0.5 pp in that
24
+ arm; eligible_common: |obs_diff| >= 0.5 pp with the same observed sign in all 12 arms (one pair set for every arm).
25
+ Outputs: cross_state_table.csv (step 1), cross_bootstrap.csv (step 2, per state), cross_bootstrap_aggregate.csv (mean
26
+ |log2| per arm and mean D per comparison over the 13 informative non-control states), cross_arm_ci.csv (per-arm ratio and
27
+ Spearman CIs), cross_contrasts.csv + cross_contrast_counts.csv (step 3), cross_spearman.csv (step 4),
28
+ cross_depth_check.csv (library vs marker detection per arm and parent), cross_run.log (console).
29
+ usage: PYTHONDONTWRITEBYTECODE=1 CUDA_VISIBLE_DEVICES= python cross_analysis.py | tee cross_run.log
30
+ """
31
+ from __future__ import annotations
32
+
33
+ import json
34
+ import sys
35
+ from pathlib import Path
36
+
37
+ import numpy as np
38
+ import pandas as pd
39
+ from scipy.stats import rankdata
40
+
41
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
42
+ OUTD = PLAN / "out/scratch_vs_lora_20261005"
43
+ SCORES = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_crosscohort_20261002/"
44
+ "scores/ye2026_sepsis")
45
+ sys.dont_write_bytecode = True # never write into tools/
46
+ sys.path.insert(0, str(PLAN / "tools"))
47
+ from screen import parent_mask # noqa: E402
48
+
49
+ SEED, B, PSEUDO, MIN_OBS, MIN_DIFF = 20261005, 2000, 0.5, 30, 0.5
50
+ ARMS = ["zs__raw", "xcalL_K1000", "locoL_lora16sat_s26750_K1000", "locoL_lora64sat_s59000_K1000",
51
+ "locoL_fullsat_s20000_K1000", "locoL_fullsat_s108500_K1000", "locoL_scratchsat_s50000_K1000",
52
+ "locoL_scratchsat_s100000_K1000", "locoL_scratchsat_s150000_K1000", "locoL_scratchsat_s162000_K1000",
53
+ "lora_n5__raw", "real_lora__raw"]
54
+ ZS, XCAL, L16, L64, F20, F108, S50, S100, S150, S162, OWN5, OWN58 = ARMS
55
+ SCRATCH = [S50, S100, S150, S162]
56
+ PRE_LOCO = [L16, L64, F20, F108]
57
+ CONTROLS = ["ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"]
58
+ # (scratch arm, comparator, kind, comparator reference used for the scratch arm in the pretrained_depth_ref variant)
59
+ COMPARISONS = [(S162, L16, "main", L16), (S162, L64, "main", L64), (S162, F108, "main", F108),
60
+ (S162, XCAL, "main", L16),
61
+ (S162, F20, "extra", F20), (S50, L16, "extra", L16),
62
+ (S162, S50, "trajectory", L16), (S162, S100, "trajectory", L16), (S162, S150, "trajectory", L16)]
63
+ CONTRASTS = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
64
+ ("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
65
+ ("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
66
+ ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
67
+
68
+
69
+ def spearman(x: np.ndarray, y: np.ndarray) -> float:
70
+ ok = ~(np.isnan(x) | np.isnan(y))
71
+ x, y = x[ok], y[ok]
72
+ if len(x) < 3:
73
+ return np.nan
74
+ rx, ry = rankdata(x), rankdata(y)
75
+ if rx.std() == 0 or ry.std() == 0:
76
+ return np.nan
77
+ return float(np.corrcoef(rx, ry)[0, 1])
78
+
79
+
80
+ def spearman_rows(X: np.ndarray, Y: np.ndarray) -> np.ndarray:
81
+ """Row-wise Spearman (average ranks, NaN pairs dropped) of (B, m) arrays; equals spearman() row by row."""
82
+ bad = np.isnan(X) | np.isnan(Y)
83
+ X, Y = np.where(bad, np.nan, X), np.where(bad, np.nan, Y)
84
+ R1, R2 = rankdata(X, axis=1, nan_policy="omit"), rankdata(Y, axis=1, nan_policy="omit")
85
+ cnt = (~bad).sum(1)
86
+ with np.errstate(invalid="ignore", divide="ignore"):
87
+ d1 = R1 - np.nanmean(R1, 1, keepdims=True)
88
+ d2 = R2 - np.nanmean(R2, 1, keepdims=True)
89
+ den = np.sqrt(np.nansum(d1 * d1, 1) * np.nansum(d2 * d2, 1))
90
+ rho = np.nansum(d1 * d2, 1) / den
91
+ rho[(cnt < 3) | ~(den > 1e-12)] = np.nan
92
+ return rho
93
+
94
+
95
+ def pct(state: np.ndarray, parent: np.ndarray) -> np.ndarray:
96
+ with np.errstate(invalid="ignore", divide="ignore"):
97
+ return np.where(parent > 0, 100.0 * state / np.where(parent > 0, parent, 1), np.nan)
98
+
99
+
100
+ def main() -> None:
101
+ out = PLAN / "out"
102
+ S = pd.read_csv(out / "sepsis_loco_summary.csv")
103
+ C = pd.read_csv(out / "sepsis_loco_contrasts.csv")
104
+ P = pd.read_csv(out / "sepsis_loco_per_donor.csv")
105
+ assert sorted(S.arm.unique()) == sorted(ARMS), S.arm.unique()
106
+ states = list(S.state.drop_duplicates())
107
+ donors = sorted(P.donor.unique())
108
+ n = len(donors)
109
+ groups = P.drop_duplicates("donor").set_index("donor").group.reindex(donors).to_numpy()
110
+
111
+ # ---- per-donor arrays ---------------------------------------------------------------------------------------
112
+ A = {}
113
+ for (arm, st), t in P.groupby(["arm", "state"], sort=False):
114
+ t = t.set_index("donor").reindex(donors)
115
+ A[arm, st] = {k: t[k].to_numpy(dtype=float) for k in
116
+ ["gen_state", "gen_parent", "obsthin_state", "obs_parent", "obs_state"]}
117
+ # obs_parent is the same for every arm (one observed cell set)
118
+ for st in states:
119
+ for arm in ARMS:
120
+ assert np.array_equal(A[arm, st]["obs_parent"], A[ARMS[0], st]["obs_parent"])
121
+
122
+ # ---- sanity: reproduce the screen's summary from the per-donor table -----------------------------------------
123
+ for _, r in S.iterrows():
124
+ a = A[r.arm, r.state]
125
+ ro = a["obsthin_state"].sum() / max(a["obs_parent"].sum(), 1)
126
+ rg = a["gen_state"].sum() / max(a["gen_parent"].sum(), 1)
127
+ assert np.isclose(rg / ro, r.gen_over_obs, rtol=1e-9), (r.arm, r.state)
128
+ rho = spearman(pct(a["gen_state"], a["gen_parent"]), pct(a["obsthin_state"], a["obs_parent"]))
129
+ assert (np.isnan(rho) and np.isnan(r.spearman_donors)) or np.isclose(rho, r.spearman_donors, atol=1e-9), \
130
+ (r.arm, r.state, rho, r.spearman_donors)
131
+
132
+ # ---- 1. state table ----------------------------------------------------------------------------------------
133
+ rows = []
134
+ for st in states:
135
+ s = S[S.state == st].set_index("arm")
136
+ obsthin = {arm: int(A[arm, st]["obsthin_state"].sum()) for arm in ARMS}
137
+ row = {"state": st, "is_control": st in CONTROLS,
138
+ "obs_native_state_cells": int(A[ARMS[0], st]["obs_state"].sum()),
139
+ "obs_parent_cells": int(A[ARMS[0], st]["obs_parent"].sum()),
140
+ "obs_thinned_state_cells_min": min(obsthin.values()),
141
+ "obs_thinned_state_cells_max": max(obsthin.values()),
142
+ "informative": min(obsthin.values()) >= MIN_OBS}
143
+ for arm in ARMS:
144
+ row[f"gen_over_obs__{arm}"] = s.loc[arm, "gen_over_obs"]
145
+ for arm in ARMS:
146
+ row[f"abs_log2__{arm}"] = abs(np.log2(s.loc[arm, "gen_over_obs"])) if s.loc[arm, "gen_over_obs"] > 0 \
147
+ else np.inf
148
+ for arm in ARMS:
149
+ row[f"spearman_donors__{arm}"] = s.loc[arm, "spearman_donors"]
150
+ for arm in ARMS:
151
+ row[f"obs_thinned_state_cells__{arm}"] = obsthin[arm]
152
+ for arm in ARMS:
153
+ row[f"gen_state_cells__{arm}"] = int(A[arm, st]["gen_state"].sum())
154
+ for arm in ARMS:
155
+ row[f"thin__{arm}"] = s.loc[arm, "thin"]
156
+ rows.append(row)
157
+ ST = pd.DataFrame(rows)
158
+ ST.to_csv(OUTD / "cross_state_table.csv", index=False)
159
+ informative = dict(zip(ST.state, ST.informative))
160
+
161
+ # ---- bootstrap machinery ------------------------------------------------------------------------------------
162
+ rng = np.random.default_rng(SEED)
163
+ idx = rng.integers(0, n, size=(B, n))
164
+ W = np.zeros((B, n))
165
+ for b in range(B):
166
+ W[b] = np.bincount(idx[b], minlength=n)
167
+
168
+ def log2_ratio(gen_arm: str, ref_arm: str, st: str, pseudo: float = PSEUDO) -> tuple[float, np.ndarray]:
169
+ g, o = A[gen_arm, st], A[ref_arm, st]
170
+ with np.errstate(divide="ignore", invalid="ignore"):
171
+ pt = np.log2(((g["gen_state"].sum() + pseudo) / g["gen_parent"].sum())
172
+ / ((o["obsthin_state"].sum() + pseudo) / o["obs_parent"].sum()))
173
+ bs = np.log2(((W @ g["gen_state"] + pseudo) / (W @ g["gen_parent"]))
174
+ / ((W @ o["obsthin_state"] + pseudo) / (W @ o["obs_parent"])))
175
+ return float(pt), bs
176
+
177
+ def raw_ratio(gen_arm: str, ref_arm: str, st: str) -> float:
178
+ g, o = A[gen_arm, st], A[ref_arm, st]
179
+ ro = o["obsthin_state"].sum() / o["obs_parent"].sum()
180
+ return float((g["gen_state"].sum() / g["gen_parent"].sum()) / ro) if ro > 0 else np.nan
181
+
182
+ def spearman_boot(gen_arm: str, ref_arm: str, st: str) -> tuple[float, np.ndarray]:
183
+ g, o = A[gen_arm, st], A[ref_arm, st]
184
+ x, y = pct(g["gen_state"], g["gen_parent"]), pct(o["obsthin_state"], o["obs_parent"])
185
+ return spearman(x, y), spearman_rows(x[idx], y[idx])
186
+
187
+ # sanity: the vectorised Spearman equals the scalar one, incl. a donor with no generated parent cells
188
+ for arm, st in [(F108, "C1Q-high monocyte (reference)"), (S162, "Cycling T/NK"), (L16, "HSPC")]:
189
+ g = A[arm, st]
190
+ x, y = pct(g["gen_state"], g["gen_parent"]), pct(g["obsthin_state"], g["obs_parent"])
191
+ v, s_ = spearman_rows(x[idx[:50]], y[idx[:50]]), np.array([spearman(x[i], y[i]) for i in idx[:50]])
192
+ assert np.allclose(v, s_, equal_nan=True), (arm, st)
193
+
194
+ # ---- per-arm CIs (ratio and Spearman), own reference + scratch arms at pretrained depth ------------------------
195
+ cache_sp = {}
196
+ rows = []
197
+ for st in states:
198
+ for arm in ARMS:
199
+ refs = [("own_ref", arm)] + ([("pretrained_depth_ref:" + r, r) for r in PRE_LOCO] if arm in SCRATCH else [])
200
+ for variant, ref in refs:
201
+ pt, bs = log2_ratio(arm, ref, st)
202
+ sp_pt, sp_bs = spearman_boot(arm, ref, st)
203
+ cache_sp[arm, ref, st] = (sp_pt, sp_bs)
204
+ lo, hi = np.nanpercentile(bs, [2.5, 97.5])
205
+ slo, shi = (np.nanpercentile(sp_bs, [2.5, 97.5]) if np.isfinite(sp_bs).sum() > 0 else (np.nan, np.nan))
206
+ rows.append({"state": st, "is_control": st in CONTROLS, "informative": informative[st], "arm": arm,
207
+ "variant": variant.split(":")[0], "observed_reference_arm": ref,
208
+ "gen_state": int(A[arm, st]["gen_state"].sum()),
209
+ "gen_parent": int(A[arm, st]["gen_parent"].sum()),
210
+ "obsthin_state": int(A[ref, st]["obsthin_state"].sum()),
211
+ "obs_parent": int(A[ref, st]["obs_parent"].sum()),
212
+ "ratio": raw_ratio(arm, ref, st), "ratio_ps": 2 ** pt,
213
+ "ratio_ps_ci_lo": 2 ** lo, "ratio_ps_ci_hi": 2 ** hi,
214
+ "abs_log2_ps": abs(pt), "spearman_donors": sp_pt,
215
+ "spearman_ci_lo": slo, "spearman_ci_hi": shi})
216
+ AC = pd.DataFrame(rows)
217
+ AC.to_csv(OUTD / "cross_arm_ci.csv", index=False)
218
+
219
+ # ---- 2. paired bootstrap of D -------------------------------------------------------------------------------
220
+ rows = []
221
+ for scr, comp, kind, depth_ref in COMPARISONS:
222
+ variants = [("own_ref", scr, comp)]
223
+ if kind != "trajectory":
224
+ variants.append(("pretrained_depth_ref", depth_ref, comp))
225
+ else: # both scratch arms at the LoRA r16 depth
226
+ variants.append(("pretrained_depth_ref", depth_ref, depth_ref))
227
+ for variant, ref_s, ref_c in variants:
228
+ for st in states:
229
+ ps, bs_s = log2_ratio(scr, ref_s, st)
230
+ pc, bs_c = log2_ratio(comp, ref_c, st)
231
+ D, Db = abs(ps) - abs(pc), np.abs(bs_s) - np.abs(bs_c)
232
+ lo, hi = np.nanpercentile(Db, [2.5, 97.5])
233
+ verdict = ("comparator_closer_sig" if lo > 0 else "scratch_closer_sig" if hi < 0 else "not_significant")
234
+ rows.append({"comparison": f"{scr} vs {comp}", "kind": kind, "variant": variant, "state": st,
235
+ "is_control": st in CONTROLS, "informative": informative[st],
236
+ "scratch_arm": scr, "comparator_arm": comp,
237
+ "scratch_reference": ref_s, "comparator_reference": ref_c,
238
+ "ratio_scratch": raw_ratio(scr, ref_s, st), "ratio_comparator": raw_ratio(comp, ref_c, st),
239
+ "ratio_scratch_ps": 2 ** ps, "ratio_comparator_ps": 2 ** pc,
240
+ "abs_log2_scratch": abs(ps), "abs_log2_comparator": abs(pc),
241
+ "D": D, "D_ci_lo": lo, "D_ci_hi": hi, "D_boot_median": float(np.nanmedian(Db)),
242
+ "frac_boot_D_gt0": float(np.mean(Db > 0)), "verdict": verdict,
243
+ "n_boot": B, "seed": SEED, "pseudocount": PSEUDO})
244
+ BT = pd.DataFrame(rows)
245
+ BT.to_csv(OUTD / "cross_bootstrap.csv", index=False)
246
+
247
+ # ---- aggregate over the informative non-control states: mean |log2| per arm, mean D per comparison --------------
248
+ rare = [s for s in states if informative[s] and s not in CONTROLS]
249
+ assert len(rare) == 13, rare
250
+ rows = []
251
+ for arm in ARMS:
252
+ for variant, ref in [("own_ref", arm)] + ([("pretrained_depth_ref", L16)] if arm in SCRATCH else []):
253
+ pts, bss = zip(*[log2_ratio(arm, ref, s) for s in rare])
254
+ a_pt, a_bs = np.abs(np.array(pts)), np.abs(np.vstack(bss))
255
+ raw = np.array([raw_ratio(arm, ref, s) for s in rare])
256
+ lo, hi = np.nanpercentile(a_bs.mean(0), [2.5, 97.5])
257
+ rows.append({"kind": "arm", "arm_or_comparison": arm, "variant": variant, "observed_reference": ref,
258
+ "n_states": len(rare), "mean_abs_log2": a_pt.mean(), "ci_lo": lo, "ci_hi": hi,
259
+ "median_abs_log2": float(np.median(a_pt)),
260
+ "n_states_within_2fold": int(((raw >= 0.5) & (raw <= 2)).sum()),
261
+ "n_states_below_0.25x": int((raw < 0.25).sum()), "n_states_above_2x": int((raw > 2).sum()),
262
+ "states_within_2fold": "; ".join(s for s, r in zip(rare, raw) if 0.5 <= r <= 2)})
263
+ for scr, comp, kind, depth_ref in COMPARISONS:
264
+ for variant, ref_s, ref_c in [("own_ref", scr, comp),
265
+ ("pretrained_depth_ref", depth_ref,
266
+ depth_ref if kind == "trajectory" else comp)]:
267
+ Ds, Dbs = [], []
268
+ for s in rare:
269
+ ps, bs_s = log2_ratio(scr, ref_s, s)
270
+ pc, bs_c = log2_ratio(comp, ref_c, s)
271
+ Ds.append(abs(ps) - abs(pc))
272
+ Dbs.append(np.abs(bs_s) - np.abs(bs_c))
273
+ Db = np.vstack(Dbs).mean(0)
274
+ lo, hi = np.nanpercentile(Db, [2.5, 97.5])
275
+ rows.append({"kind": f"comparison_{kind}", "arm_or_comparison": f"{scr} vs {comp}", "variant": variant,
276
+ "observed_reference": f"{ref_s} | {ref_c}", "n_states": len(rare),
277
+ "mean_D": float(np.mean(Ds)), "ci_lo": lo, "ci_hi": hi, "median_D": float(np.median(Ds)),
278
+ "frac_boot_mean_D_gt0": float(np.mean(Db > 0))})
279
+ pd.DataFrame(rows).to_csv(OUTD / "cross_bootstrap_aggregate.csv", index=False)
280
+
281
+ # ---- 4. Spearman differences ----------------------------------------------------------------------------------
282
+ rows = []
283
+ for scr, comp, kind, depth_ref in COMPARISONS:
284
+ for variant, ref_s, ref_c in [("own_ref", scr, comp)] + (
285
+ [("pretrained_depth_ref", depth_ref, comp)] if kind != "trajectory" else []):
286
+ for st in states:
287
+ if (scr, ref_s, st) not in cache_sp:
288
+ cache_sp[scr, ref_s, st] = spearman_boot(scr, ref_s, st)
289
+ if (comp, ref_c, st) not in cache_sp:
290
+ cache_sp[comp, ref_c, st] = spearman_boot(comp, ref_c, st)
291
+ (a, ab), (c, cb) = cache_sp[scr, ref_s, st], cache_sp[comp, ref_c, st]
292
+ d = ab - cb
293
+ ok = np.isfinite(d)
294
+ lo, hi = (np.percentile(d[ok], [2.5, 97.5]) if ok.sum() > 0 else (np.nan, np.nan))
295
+ rows.append({"comparison": f"{scr} vs {comp}", "kind": kind, "variant": variant, "state": st,
296
+ "is_control": st in CONTROLS, "informative": informative[st],
297
+ "spearman_scratch": a, "spearman_comparator": c, "diff_scratch_minus_comparator": a - c,
298
+ "diff_ci_lo": lo, "diff_ci_hi": hi, "n_boot_finite": int(ok.sum()),
299
+ "verdict": ("scratch_higher_sig" if lo > 0 else
300
+ "comparator_higher_sig" if hi < 0 else "not_significant")})
301
+ SPD = pd.DataFrame(rows)
302
+ SPD.to_csv(OUTD / "cross_spearman.csv", index=False)
303
+
304
+ # ---- 3. contrasts -------------------------------------------------------------------------------------------
305
+ rows = []
306
+ for arm in ARMS:
307
+ refs = [("own_ref", arm)] + ([("pretrained_depth_ref", L16)] if arm in SCRATCH else [])
308
+ for variant, ref in refs:
309
+ for st in states:
310
+ g, o = A[arm, st], A[ref, st]
311
+ gp_, op_ = pct(g["gen_state"], g["gen_parent"]), pct(o["obsthin_state"], o["obs_parent"])
312
+ for name, ga, gb in CONTRASTS:
313
+ ma, mb = np.isin(groups, ga), np.isin(groups, gb)
314
+ od = np.nanmean(op_[ma]) - np.nanmean(op_[mb])
315
+ gd = np.nanmean(gp_[ma]) - np.nanmean(gp_[mb])
316
+ rows.append({"arm": arm, "variant": variant, "observed_reference_arm": ref, "state": st,
317
+ "contrast": name, "is_control": st in CONTROLS, "informative": informative[st],
318
+ "obs_diff": od, "gen_diff": gd,
319
+ "same_direction": bool(np.sign(od) == np.sign(gd)),
320
+ "reversed": bool(np.sign(od) * np.sign(gd) < 0), "flat_generated": bool(gd == 0),
321
+ "gen_over_obs_diff": gd / od if od != 0 else np.nan})
322
+ CT = pd.DataFrame(rows)
323
+ chk = CT[CT.variant == "own_ref"].merge(C, on=["arm", "state", "contrast"], suffixes=("", "_screen"))
324
+ assert len(chk) == len(C)
325
+ assert np.allclose(chk.obs_diff, chk.obs_diff_screen, equal_nan=True)
326
+ assert np.allclose(chk.gen_diff, chk.gen_diff_screen, equal_nan=True)
327
+ assert (chk.same_direction == chk.same_direction_screen).all()
328
+ own = CT[CT.variant == "own_ref"]
329
+ big_all = own.assign(big=own.obs_diff.abs() >= MIN_DIFF, sgn=np.sign(own.obs_diff)).groupby(
330
+ ["state", "contrast"]).agg(big_all=("big", "all"), sign_consistent=("sgn", lambda s: s.nunique() == 1))
331
+ CT = CT.merge(big_all.reset_index(), on=["state", "contrast"], how="left")
332
+ CT["eligible_own"] = CT.informative & (CT.obs_diff.abs() >= MIN_DIFF)
333
+ CT["eligible_common"] = CT.informative & CT.big_all & CT.sign_consistent
334
+ CT.to_csv(OUTD / "cross_contrasts.csv", index=False)
335
+ rows = []
336
+ for (arm, variant), t in CT.groupby(["arm", "variant"], sort=False):
337
+ for scope, ctrl in [("rare_states", False), ("controls", True)]:
338
+ u = t[t.is_control == ctrl]
339
+ for elig in ["eligible_own", "eligible_common"]:
340
+ e = u[u[elig]]
341
+ rows.append({"arm": arm, "variant": variant, "states": scope, "eligibility": elig,
342
+ "n_pairs": len(e), "kept": int(e.same_direction.sum()), "reversed": int(e.reversed.sum()),
343
+ "flat": int(e.flat_generated.sum()),
344
+ "median_gen_over_obs_diff_kept": float(e[e.same_direction].gen_over_obs_diff.median())
345
+ if e.same_direction.any() else np.nan,
346
+ "lost_pairs": "; ".join(f"{r.state} | {r.contrast}" for r in e[~e.same_direction].itertuples())})
347
+ CC = pd.DataFrame(rows)
348
+ CC.to_csv(OUTD / "cross_contrast_counts.csv", index=False)
349
+
350
+ # ---- depth check ----------------------------------------------------------------------------------------------
351
+ st_json = json.loads((PLAN / "tools/states.json").read_text())
352
+ parents = []
353
+ for s in st_json:
354
+ if s["parent"] not in parents:
355
+ parents.append(s["parent"])
356
+ bench_name = {ZS: "zs_K1000"}
357
+ rows = []
358
+ for arm in ARMS:
359
+ d = np.load(PLAN / f"work/sepsis/loco/{arm}.npz", allow_pickle=False)
360
+ lab = pd.DataFrame({"aifi_l1": d["aifi_l1"], "aifi_l2": d["aifi_l2"]})
361
+ M, lib = d["markers"], d["lib_measured"]
362
+ bj = SCORES / bench_name.get(arm, arm) / "summary.json"
363
+ bench = {}
364
+ if bj.exists():
365
+ pa = json.loads(bj.read_text())["per_arm"][bench_name.get(arm, arm)]
366
+ bench = {"bench_median_umi_gen_scoring_genes": pa["median_umi_per_cell_scoring_genes"]["generated_pooled"],
367
+ "bench_median_umi_obs_scoring_genes": pa["median_umi_per_cell_scoring_genes"]["observed_pooled"],
368
+ "bench_detected_genes_median_gen": pa["precision_coverage_depth_matched"]["detected_median_before"]["Q"],
369
+ "bench_detected_genes_median_obs": pa["precision_coverage_depth_matched"]["detected_median_before"]["R1"],
370
+ "bench_precision": pa["precision_coverage"]["precision"],
371
+ "bench_coverage": pa["precision_coverage"]["coverage"]}
372
+ syms = list(d["marker_symbols"].astype(str))
373
+ for p in parents:
374
+ m = parent_mask(lab, p)
375
+ X = M[m]
376
+ nz = X[X > 0]
377
+ thin_state = next(s["name"] for s in st_json if s["parent"] == p and s["kind"] == "markers")
378
+ rows.append({"arm": arm, "parent": "+".join(p), "n_parent_cells": int(m.sum()),
379
+ "median_lib_measured": float(np.median(lib[m])),
380
+ "mean_detected_marker_genes_of_73": float((X > 0).sum(1).mean()),
381
+ "mean_count_per_detected_marker": float(nz.mean()) if nz.size else np.nan,
382
+ "screen_thin_constant": float(S[(S.arm == arm) & (S.state == thin_state)].thin.iloc[0]),
383
+ # detection of broadly expressed (non-state) marker genes: a depth read-out on the marker panel
384
+ **{f"detected_frac__{gname}": float((X[:, syms.index(gname)] > 0).mean())
385
+ for gname in ["HLA-DRA", "HLA-DRB1", "ZEB2", "PLAC8", "CD163", "NKG7", "GZMA", "GNLY",
386
+ "CCR7"] if gname in syms},
387
+ **bench})
388
+ pd.DataFrame(rows).to_csv(OUTD / "cross_depth_check.csv", index=False)
389
+
390
+ # ---- console summary --------------------------------------------------------------------------------------
391
+ pd.set_option("display.width", 250, "display.max_columns", 40, "display.max_rows", 400)
392
+ print("informative:", ST.informative.sum(), "of", len(ST), "| min obs thinned:", ST.obs_thinned_state_cells_min.min())
393
+ for (comp, variant), t in BT.groupby(["comparison", "variant"], sort=False):
394
+ u = t[t.informative & ~t.is_control]
395
+ print(f"{comp} [{variant}]: scratch closer {int((u.verdict == 'scratch_closer_sig').sum())}, comparator closer "
396
+ f"{int((u.verdict == 'comparator_closer_sig').sum())}, n.s. {int((u.verdict == 'not_significant').sum())}")
397
+ print(CC[CC.states == "rare_states"].to_string(index=False))
398
+
399
+
400
+ if __name__ == "__main__":
401
+ main()
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_confound_cross_analysis.py ADDED
@@ -0,0 +1,727 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Adversarial confound check of the CROSS-COHORT scratch-vs-pretrained rare-state claims (CPU only; 2026-10-05).
3
+
4
+ Independent re-implementation (does not import tools/*.py, so nothing is written into tools/__pycache__).
5
+ Read-only inputs:
6
+ out/sepsis_loco_{summary,per_donor,contrasts}.csv, out/sepsis_fold0_summary.csv
7
+ work/sepsis/loco/<arm>.npz (generated per-cell marker extracts)
8
+ paired_finetune_intradataset_20260927/data/ye2026_sepsis/{cells_panel6k.npz, cells_obs.parquet, folds.csv}
9
+ paired_finetune_intradataset_20260927/scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet
10
+ tools/states.json
11
+ Writes only out/scratch_vs_lora_20261005/verify_confound_cross_*.
12
+
13
+ Checks
14
+ R recompute the screen ratio (pooled), plus two re-weighted estimators that remove the donor-weighting /
15
+ parent-pool mismatch between the generated (1,500 cells per donor) and observed (variable) pools:
16
+ gw = sum gen_state / sum_d gen_parent_d * obs_thin_rate_d (generated-weighted expected count)
17
+ dm = mean_d gen_% / mean_d obs_thin_% (donor-balanced)
18
+ LODO range of each ratio and the largest single-donor share of the state counts.
19
+ C scratch (s162000) vs comparators: D = |log2 r_scratch| - |log2 r_comp| for the three estimators, own reference
20
+ and comparator-depth reference; donor bootstrap (seed 20261005, B 2000, shared index); LODO stability of the
21
+ bootstrap verdict (82 leave-one-donor-out re-bootstraps, index rng(20261005).integers(0, 81, (2000, 81))).
22
+ A 13-state aggregate mean D: LODO and leave-one-state-out.
23
+ DEP detection-matched depth: per arm and parent, the binomial thinning constant t at which the observed cells' expected
24
+ detection of reference marker genes (observed native detection >= 10 % in the parent, the state's own rule genes
25
+ excluded) equals the generated detection (per-gene t, median over genes). Observed cells are then thinned at
26
+ that t (seed 20261005) and every marker state re-called -> detection-matched ratio and D.
27
+ LAB label-state validity: cycling / plasma marker support inside the scANVI 'Proliferating T cell' / 'Plasma cell'
28
+ labelled cells, generated vs observed.
29
+ CON contrast robustness: chance level, donor-bootstrap (within group) sign stability, LODO, compression at matched
30
+ depth, paired compression on pairs kept by both arms.
31
+ SP Spearman over donors: zero-inflation, CI width, best arm per state.
32
+ FOLD own-cohort and cross-cohort arms restricted to each within-cohort fold's held-out donors.
33
+ """
34
+ from __future__ import annotations
35
+
36
+ import json
37
+ import sys
38
+ import time
39
+ from pathlib import Path
40
+
41
+ import numpy as np
42
+ import pandas as pd
43
+ import scipy.sparse as sp
44
+ from scipy.stats import binom, rankdata
45
+
46
+ sys.dont_write_bytecode = True
47
+ T0 = time.time()
48
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
49
+ PLAN = M8 / "plans/rare_states_screen_20261004"
50
+ OUT = PLAN / "out/scratch_vs_lora_20261005"
51
+ PFX = "verify_confound_cross_"
52
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
53
+ DATA = FT / "data/ye2026_sepsis"
54
+ OBS_LABELS = FT / "scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet"
55
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
56
+ "canonical_genes.tsv")
57
+ SEED, B, PS = 20261005, 2000, 0.5
58
+
59
+ ARMS = ["zs__raw", "xcalL_K1000", "locoL_lora16sat_s26750_K1000", "locoL_lora64sat_s59000_K1000",
60
+ "locoL_fullsat_s20000_K1000", "locoL_fullsat_s108500_K1000", "locoL_scratchsat_s50000_K1000",
61
+ "locoL_scratchsat_s100000_K1000", "locoL_scratchsat_s150000_K1000", "locoL_scratchsat_s162000_K1000",
62
+ "lora_n5__raw", "real_lora__raw"]
63
+ SHORT = dict(zip(ARMS, ["zs", "xcal", "r16", "r64", "full20k", "full108k", "s50k", "s100k", "s150k", "s162k",
64
+ "own5", "own58"]))
65
+ ZS, XCAL, L16, L64, F20, F108, S50, S100, S150, S162, OWN5, OWN58 = ARMS
66
+ SCRATCH = [S50, S100, S150, S162]
67
+ PRE = [L16, L64, F20, F108]
68
+ CONTROLS = ["ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"]
69
+ CONTRASTS = [("adult", ["adult_sepsis"], ["adult_HC"]),
70
+ ("paediatric", ["ped_sepsis"], ["ped_HC"]),
71
+ ("all", ["adult_sepsis", "ped_sepsis"], ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
72
+ # (scratch arm, comparator, scratch reference arm in the comparator-depth variant)
73
+ COMPS = [(S162, L16, L16), (S162, L64, L64), (S162, F108, F108), (S162, XCAL, L16), (S162, F20, F20),
74
+ (S50, L16, L16), (S162, S50, S162)]
75
+ LOG = []
76
+
77
+
78
+ def log(*a):
79
+ s = " ".join(str(x) for x in a)
80
+ print(s, flush=True)
81
+ LOG.append(s)
82
+
83
+
84
+ def write(df: pd.DataFrame, name: str) -> None:
85
+ df.to_csv(OUT / f"{PFX}{name}.csv", index=False, na_rep="null")
86
+
87
+
88
+ # ------------------------------------------------------------------------------------------------ per-donor table
89
+ P = pd.read_csv(PLAN / "out/sepsis_loco_per_donor.csv")
90
+ S = pd.read_csv(PLAN / "out/sepsis_loco_summary.csv")
91
+ STJ = json.loads((PLAN / "tools/states.json").read_text())
92
+ STATES = [s["name"] for s in STJ]
93
+ RARE = [s for s in STATES if s not in CONTROLS]
94
+ donors = sorted(P.donor.unique())
95
+ n = len(donors)
96
+ groups = P.drop_duplicates("donor").set_index("donor").group.reindex(donors).to_numpy()
97
+ A = {}
98
+ for (arm, st), t in P.groupby(["arm", "state"], sort=False):
99
+ t = t.set_index("donor").reindex(donors)
100
+ A[arm, st] = {k: t[k].to_numpy(float) for k in ["gen_state", "gen_parent", "obsthin_state", "obs_parent",
101
+ "obs_state"]}
102
+ THIN = {(r.arm, r.state): r.thin for r in S.itertuples()}
103
+ assert len(RARE) == 13 and n == 82
104
+
105
+ rng = np.random.default_rng(SEED)
106
+ IDX = rng.integers(0, n, size=(B, n))
107
+ W = np.stack([np.bincount(r, minlength=n) for r in IDX]).astype(float)
108
+ IDX81 = np.random.default_rng(SEED).integers(0, n - 1, size=(B, n - 1))
109
+ W81 = np.stack([np.bincount(r, minlength=n - 1) for r in IDX81]).astype(float)
110
+
111
+
112
+ def vecs(gen_arm, ref_arm, st, obs_override=None):
113
+ g, o = A[gen_arm, st], A[ref_arm, st]
114
+ os_ = o["obsthin_state"] if obs_override is None else obs_override
115
+ return g["gen_state"], g["gen_parent"], os_, o["obs_parent"]
116
+
117
+
118
+ def lr(est, gs, gp, os_, op, w=None):
119
+ """log2 ratio with a 0.5-cell pseudocount on both state counts. w: (B, m) weights or None."""
120
+ with np.errstate(divide="ignore", invalid="ignore"):
121
+ if est == "pool":
122
+ if w is None:
123
+ return np.log2(((gs.sum() + PS) / gp.sum()) / ((os_.sum() + PS) / op.sum()))
124
+ return np.log2(((w @ gs + PS) / (w @ gp)) / ((w @ os_ + PS) / (w @ op)))
125
+ if est == "gw":
126
+ ok = op > 0
127
+ e = np.where(ok, gp * os_ / np.where(ok, op, 1), 0.0)
128
+ g = np.where(ok, gs, 0.0)
129
+ if w is None:
130
+ return np.log2((g.sum() + PS) / (e.sum() + PS))
131
+ return np.log2((w @ g + PS) / (w @ e + PS))
132
+ if est == "dm":
133
+ ok = (gp > 0) & (op > 0)
134
+ gpct = np.where(ok, gs / np.where(gp > 0, gp, 1), 0.0)
135
+ opct = np.where(ok, os_ / np.where(op > 0, op, 1), 0.0)
136
+ eg, eo = PS / gp.sum(), PS / op.sum()
137
+ if w is None:
138
+ return np.log2((gpct[ok].mean() + eg) / (opct[ok].mean() + eo))
139
+ wk = w * ok
140
+ den = wk.sum(1)
141
+ return np.log2(((wk @ gpct) / den + eg) / ((wk @ opct) / den + eo))
142
+ raise ValueError(est)
143
+
144
+
145
+ def raw_ratio(gs, gp, os_, op):
146
+ ro = os_.sum() / op.sum()
147
+ return float((gs.sum() / gp.sum()) / ro) if ro > 0 and gp.sum() > 0 else np.nan
148
+
149
+
150
+ def verdict(lo, hi):
151
+ return "comparator_closer_sig" if lo > 0 else "scratch_closer_sig" if hi < 0 else "not_significant"
152
+
153
+
154
+ # ------------------------------------------------------------------------------------------------ R: ratios
155
+ log("== R: ratios, re-weighted estimators, LODO ==")
156
+ rows = []
157
+ for st in STATES:
158
+ for arm in ARMS:
159
+ refs = [("own_ref", arm)] + ([("r16_depth_ref", L16)] if arm in SCRATCH else [])
160
+ for variant, ref in refs:
161
+ gs, gp, os_, op = vecs(arm, ref, st)
162
+ row = {"state": st, "arm": SHORT[arm], "variant": variant, "gen_state": int(gs.sum()),
163
+ "gen_parent": int(gp.sum()), "obsthin_state": int(os_.sum()), "obs_parent": int(op.sum()),
164
+ "ratio_pool_raw": raw_ratio(gs, gp, os_, op)}
165
+ for est in ["pool", "gw", "dm"]:
166
+ pt = lr(est, gs, gp, os_, op)
167
+ bs = lr(est, gs, gp, os_, op, W)
168
+ lo, hi = np.nanpercentile(bs, [2.5, 97.5])
169
+ row.update({f"ratio_{est}": 2 ** pt, f"ratio_{est}_lo": 2 ** lo, f"ratio_{est}_hi": 2 ** hi})
170
+ # LODO of the pooled ratio (pseudocount version)
171
+ lodo = np.array([lr("pool", np.delete(gs, j), np.delete(gp, j), np.delete(os_, j), np.delete(op, j))
172
+ for j in range(n)])
173
+ row.update({"lodo_ratio_min": 2 ** lodo.min(), "lodo_ratio_max": 2 ** lodo.max(),
174
+ "lodo_most_influential_donor": donors[int(np.argmax(np.abs(lodo - lr("pool", gs, gp, os_, op))))],
175
+ "max_donor_share_gen_state": float(gs.max() / gs.sum()) if gs.sum() > 0 else np.nan,
176
+ "max_donor_share_obsthin_state": float(os_.max() / os_.sum()) if os_.sum() > 0 else np.nan,
177
+ "donors_with_0_gen_state": int((gs == 0).sum()),
178
+ "donors_with_gen_parent": int((gp > 0).sum())})
179
+ rows.append(row)
180
+ R = pd.DataFrame(rows)
181
+ write(R, "ratios")
182
+ key = R[(R.variant == "own_ref") & R.state.isin(["C1Q-high monocyte (reference)", "MS1 monocyte (IL1R2+)",
183
+ "Cycling T/NK", "Cycling monocyte (Ye 2026)",
184
+ "Cycling activated T (CD38/HLA-DR)", "Proliferating T (label)",
185
+ "HSPC", "Cytotoxic CD4 T", "Plasmablast (label)"])]
186
+ with pd.option_context("display.width", 250, "display.max_rows", 300, "display.max_columns", 30):
187
+ log(key[["state", "arm", "ratio_pool_raw", "ratio_pool", "ratio_pool_lo", "ratio_pool_hi", "ratio_gw", "ratio_dm",
188
+ "lodo_ratio_min", "lodo_ratio_max", "max_donor_share_gen_state", "max_donor_share_obsthin_state"]]
189
+ .round(3).to_string(index=False))
190
+
191
+
192
+ # ------------------------------------------------------------------------------------------------ C: comparisons
193
+ log("== C: scratch vs comparators, three estimators, LODO-bootstrap stability ==")
194
+
195
+
196
+ def comp_boot(scr, comp, ref_s, ref_c, st, est, w=None, drop=None):
197
+ gs, gp, os_, op = vecs(scr, ref_s, st)
198
+ cs, cp, co, cop = vecs(comp, ref_c, st)
199
+ if drop is not None:
200
+ gs, gp, os_, op, cs, cp, co, cop = (np.delete(v, drop) for v in (gs, gp, os_, op, cs, cp, co, cop))
201
+ return np.abs(lr(est, gs, gp, os_, op, w)) - np.abs(lr(est, cs, cp, co, cop, w))
202
+
203
+
204
+ rows = []
205
+ for scr, comp, dref in COMPS:
206
+ for variant, ref_s, ref_c in [("own_ref", scr, comp), ("comparator_depth_ref", dref, comp if comp not in SCRATCH else dref)]:
207
+ if comp in SCRATCH and variant == "comparator_depth_ref":
208
+ ref_s = ref_c = L16
209
+ for st in STATES:
210
+ for est in ["pool", "gw", "dm"]:
211
+ D = float(comp_boot(scr, comp, ref_s, ref_c, st, est))
212
+ Db = comp_boot(scr, comp, ref_s, ref_c, st, est, W)
213
+ lo, hi = np.nanpercentile(Db, [2.5, 97.5])
214
+ v = verdict(lo, hi)
215
+ row = {"comparison": f"{SHORT[scr]} vs {SHORT[comp]}", "variant": variant, "state": st,
216
+ "estimator": est, "D": D, "D_lo": lo, "D_hi": hi, "verdict": v}
217
+ if est == "pool":
218
+ # LODO: point D range and bootstrap verdict stability
219
+ pts, same = [], 0
220
+ for j in range(n):
221
+ pts.append(float(comp_boot(scr, comp, ref_s, ref_c, st, est, drop=j)))
222
+ Dj = comp_boot(scr, comp, ref_s, ref_c, st, est, W81, drop=j)
223
+ l2, h2 = np.nanpercentile(Dj, [2.5, 97.5])
224
+ same += verdict(l2, h2) == v
225
+ row.update({"lodo_D_min": min(pts), "lodo_D_max": max(pts),
226
+ "lodo_sign_flips": int(sum(np.sign(p) != np.sign(D) for p in pts)),
227
+ "lodo_verdict_same_frac": same / n})
228
+ rows.append(row)
229
+ C = pd.DataFrame(rows)
230
+ write(C, "comparisons")
231
+ Cp = C.pivot_table(index=["comparison", "variant", "state"], columns="estimator", values="verdict",
232
+ aggfunc="first").reset_index()
233
+ Cp["estimators_agree"] = (Cp["pool"] == Cp["gw"]) & (Cp["pool"] == Cp["dm"])
234
+ dis = Cp[~Cp.estimators_agree & ~Cp.state.isin(CONTROLS)]
235
+ with pd.option_context("display.width", 250, "display.max_rows", 300):
236
+ log("verdict disagreements between estimators (rare states):")
237
+ log(dis.to_string(index=False))
238
+ u = C[(C.estimator == "pool") & (C.verdict != "not_significant") & ~C.state.isin(CONTROLS)]
239
+ log("pooled-estimator significant verdicts with LODO stability:")
240
+ log(u[["comparison", "variant", "state", "D", "D_lo", "D_hi", "verdict", "lodo_D_min", "lodo_D_max",
241
+ "lodo_verdict_same_frac"]].round(3).to_string(index=False))
242
+
243
+ # ------------------------------------------------------------------------------------------------ A: aggregate
244
+ log("== A: 13-state aggregate mean D: LODO and leave-one-state-out ==")
245
+ rows = []
246
+ for scr, comp, dref in COMPS:
247
+ for variant in ["own_ref", "comparator_depth_ref"]:
248
+ if variant == "own_ref":
249
+ ref_s, ref_c = scr, comp
250
+ elif comp in SCRATCH:
251
+ ref_s = ref_c = L16
252
+ else:
253
+ ref_s, ref_c = dref, comp
254
+ for est in ["pool", "gw", "dm"]:
255
+ Ds = np.array([float(comp_boot(scr, comp, ref_s, ref_c, s, est)) for s in RARE])
256
+ Dbs = np.vstack([comp_boot(scr, comp, ref_s, ref_c, s, est, W) for s in RARE])
257
+ lo, hi = np.nanpercentile(Dbs.mean(0), [2.5, 97.5])
258
+ row = {"comparison": f"{SHORT[scr]} vs {SHORT[comp]}", "variant": variant, "estimator": est,
259
+ "mean_D": Ds.mean(), "lo": lo, "hi": hi, "verdict": verdict(lo, hi)}
260
+ # leave one state out
261
+ loso = [(RARE[i], np.delete(Ds, i).mean(), *np.nanpercentile(np.delete(Dbs, i, 0).mean(0), [2.5, 97.5]))
262
+ for i in range(len(RARE))]
263
+ row.update({"loso_mean_D_min": min(x[1] for x in loso), "loso_mean_D_max": max(x[1] for x in loso),
264
+ "loso_verdicts": ";".join(sorted({verdict(x[2], x[3]) for x in loso})),
265
+ "loso_state_flipping_verdict": ";".join(x[0] for x in loso if verdict(x[2], x[3]) !=
266
+ verdict(lo, hi))})
267
+ if est == "pool":
268
+ same, pts = 0, []
269
+ for j in range(n):
270
+ Dj = np.vstack([comp_boot(scr, comp, ref_s, ref_c, s, est, W81, drop=j) for s in RARE]).mean(0)
271
+ pts.append(np.mean([float(comp_boot(scr, comp, ref_s, ref_c, s, est, drop=j)) for s in RARE]))
272
+ l2, h2 = np.nanpercentile(Dj, [2.5, 97.5])
273
+ same += verdict(l2, h2) == verdict(lo, hi)
274
+ row.update({"lodo_mean_D_min": min(pts), "lodo_mean_D_max": max(pts), "lodo_verdict_same_frac": same / n})
275
+ rows.append(row)
276
+ AG = pd.DataFrame(rows)
277
+ write(AG, "aggregate")
278
+ with pd.option_context("display.width", 250, "display.max_rows", 300, "display.max_columns", 30):
279
+ log(AG.round(3).to_string(index=False))
280
+ log(f"[{time.time() - T0:.0f}s]")
281
+
282
+ # ------------------------------------------------------------------------------------------------ observed cells
283
+ log("== loading observed cells (82 donors, 73 marker columns) ==")
284
+ G = {a: np.load(PLAN / f"work/sepsis/loco/{a}.npz", allow_pickle=False) for a in ARMS}
285
+ SYMS = list(G[ZS]["marker_symbols"].astype(str))
286
+ for a in ARMS:
287
+ assert list(G[a]["marker_symbols"].astype(str)) == SYMS
288
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
289
+ panel = d["panel_gene_ids"].astype(str)
290
+ measured = d["panel_measured"].any(0)
291
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
292
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
293
+ pos = {g: i for i, g in enumerate(panel)}
294
+ cols = np.asarray([pos[sym2id[g]] for g in SYMS])
295
+ X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
296
+ obs = pd.read_parquet(DATA / "cells_obs.parquet", columns=["sample_id", "group"])
297
+ lab = pd.read_parquet(OBS_LABELS, columns=["aifi_l1", "aifi_l2", "npz_row"])
298
+ assert len(lab) == X.shape[0] and (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all()
299
+ keep = np.flatnonzero(obs.sample_id.isin(donors).to_numpy())
300
+ LIBO = np.asarray(X @ measured.astype(np.float32)).ravel()[keep]
301
+ MO = X[:, cols][keep].toarray().astype(np.int32)
302
+ del X, d
303
+ DONO = obs.sample_id.to_numpy()[keep].astype(str)
304
+ L1O, L2O = lab.aifi_l1.to_numpy()[keep].astype(str), lab.aifi_l2.to_numpy()[keep].astype(str)
305
+ SYM2COL = {s: i for i, s in enumerate(SYMS)}
306
+ DIDX_O = pd.Index(donors).get_indexer(DONO)
307
+ log(f"observed cells {len(keep):,} [{time.time() - T0:.0f}s]")
308
+
309
+
310
+ def pmask(l1, l2, parent):
311
+ if parent == ["ALL"]:
312
+ return np.ones(len(l1), bool)
313
+ return np.isin(l2, parent) | np.isin(l1, parent)
314
+
315
+
316
+ def rule(st):
317
+ pc = [SYM2COL[g] for g in st["genes"] if g in SYM2COL]
318
+ req = [[SYM2COL[g] for g in grp if g in SYM2COL] for grp in st.get("require_any", [])]
319
+ exc = [SYM2COL[g] for g in st.get("exclude", []) if g in SYM2COL]
320
+ return pc, [r for r in req if r], exc
321
+
322
+
323
+ def call(M, st):
324
+ pc, req, exc = rule(st)
325
+ det = M > 0
326
+ h = det[:, pc].sum(1) >= st["k"]
327
+ for r in req:
328
+ h &= det[:, r].any(1)
329
+ if exc:
330
+ h &= ~det[:, exc].any(1)
331
+ return h
332
+
333
+
334
+ def own_genes(st):
335
+ return set(st.get("genes", [])) | {g for grp in st.get("require_any", []) for g in grp} | set(st.get("exclude", []))
336
+
337
+
338
+ # validate the observed loader against the screen's native per-donor counts
339
+ bad = 0
340
+ for st in STJ:
341
+ po = pmask(L1O, L2O, st["parent"])
342
+ ho = (np.isin(L2O, st["labels"]) & po) if st["kind"] == "label" else (call(MO, st) & po)
343
+ op_ = np.bincount(DIDX_O[po], minlength=n)
344
+ os_ = np.bincount(DIDX_O[ho], minlength=n)
345
+ bad += int((op_ != A[ZS, st["name"]]["obs_parent"]).sum() + (os_ != A[ZS, st["name"]]["obs_state"]).sum())
346
+ log(f"observed loader reproduces screen native per-donor parent/state counts: mismatches = {bad}")
347
+
348
+ # ------------------------------------------------------------------------------------------------ DEP
349
+ log("== DEP: detection-matched depth ==")
350
+ TG = np.linspace(0.0, 1.0, 401)
351
+ PARENTS = []
352
+ for st in STJ:
353
+ if st["kind"] == "markers" and st["parent"] not in PARENTS:
354
+ PARENTS.append(st["parent"])
355
+
356
+
357
+ def det_curve(counts):
358
+ """expected detection fraction of one gene at thinning t (grid) for observed counts."""
359
+ vals, cnt = np.unique(counts, return_counts=True)
360
+ vals, cnt = vals[vals > 0], cnt[vals > 0]
361
+ return ((1 - (1 - TG[:, None]) ** vals[None, :]) * cnt[None, :]).sum(1) / len(counts)
362
+
363
+
364
+ def solve_t(curve, target):
365
+ if target >= curve[-1]:
366
+ return 1.0
367
+ return float(np.interp(target, curve, TG))
368
+
369
+
370
+ obs_curves = {}
371
+ for p in PARENTS:
372
+ po = pmask(L1O, L2O, p)
373
+ obs_curves["+".join(p)] = {g: det_curve(MO[po, SYM2COL[g]]) for g in SYMS}
374
+ rows = []
375
+ TDET = {}
376
+ for st in STJ:
377
+ if st["kind"] != "markers":
378
+ continue
379
+ p = "+".join(st["parent"])
380
+ curves = obs_curves[p]
381
+ ref = [g for g in SYMS if g not in own_genes(st) and curves[g][-1] >= 0.10]
382
+ for arm in ARMS:
383
+ gm = G[arm]
384
+ pg = pmask(gm["aifi_l1"].astype(str), gm["aifi_l2"].astype(str), st["parent"])
385
+ Mg = gm["markers"][pg]
386
+ tg = {g: solve_t(curves[g], float((Mg[:, SYM2COL[g]] > 0).mean())) for g in ref}
387
+ tv = np.array(list(tg.values()))
388
+ # pooled-detection version
389
+ gen_pool = float(np.mean([(Mg[:, SYM2COL[g]] > 0).mean() for g in ref]))
390
+ t_pool = solve_t(np.mean([curves[g] for g in ref], 0), gen_pool)
391
+ TDET[arm, st["name"]] = float(np.median(tv))
392
+ rows.append({"state": st["name"], "parent": p, "arm": SHORT[arm], "n_ref_genes": len(ref),
393
+ "ref_genes": " ".join(ref), "t_det_median_gene": float(np.median(tv)),
394
+ "t_det_q25": float(np.quantile(tv, 0.25)), "t_det_q75": float(np.quantile(tv, 0.75)),
395
+ "t_det_pooled": t_pool, "n_genes_capped_at_1": int((tv >= 1.0).sum()),
396
+ "screen_thin_library": THIN[arm, st["name"]],
397
+ "gen_median_lib": float(np.median(gm["lib_measured"][pg])),
398
+ "gen_mean_detected_of_73": float((Mg > 0).sum(1).mean())})
399
+ DEP = pd.DataFrame(rows)
400
+ write(DEP, "depth_detection")
401
+ with pd.option_context("display.width", 250, "display.max_rows", 300):
402
+ dd = DEP.drop_duplicates(["parent", "arm"])[["parent", "arm", "n_ref_genes", "t_det_median_gene", "t_det_q25",
403
+ "t_det_q75", "t_det_pooled", "n_genes_capped_at_1",
404
+ "screen_thin_library", "gen_median_lib", "gen_mean_detected_of_73"]]
405
+ log(dd.round(3).to_string(index=False))
406
+ log("per-state t_det for scratch s162k vs r16 / r64 / full108k / own library thin:")
407
+ piv = DEP.pivot_table(index="state", columns="arm", values="t_det_median_gene")
408
+ piv2 = DEP.pivot_table(index="state", columns="arm", values="screen_thin_library")
409
+ log(pd.concat([piv[["s50k", "s162k", "r16", "r64", "full108k", "xcal", "own58"]].add_prefix("tdet_"),
410
+ piv2[["r16", "r64", "full108k", "xcal", "own58"]].add_prefix("thinlib_")], axis=1).round(3)
411
+ .to_string())
412
+
413
+ # detection-matched observed state counts per arm (one binomial draw per arm and state at t_det)
414
+ rng_t = np.random.default_rng(SEED)
415
+ DETCNT = {}
416
+ for st in STJ:
417
+ if st["kind"] != "markers":
418
+ continue
419
+ po = pmask(L1O, L2O, st["parent"])
420
+ pc, req, exc = rule(st)
421
+ cset = sorted(set(pc) | {c for r in req for c in r} | set(exc))
422
+ for arm in ARMS:
423
+ t = TDET[arm, st["name"]]
424
+ Mt = MO
425
+ if t < 1:
426
+ Mt = np.zeros_like(MO)
427
+ Mt[:, cset] = rng_t.binomial(MO[:, cset], t)
428
+ h = call(Mt, st) & po
429
+ DETCNT[arm, st["name"]] = np.bincount(DIDX_O[h], minlength=n).astype(float)
430
+ rows = []
431
+ for st in RARE + CONTROLS:
432
+ if (L16, st) not in DETCNT:
433
+ continue
434
+ for arm in ARMS:
435
+ gs, gp, _, op = vecs(arm, arm, st)
436
+ os_ = DETCNT[arm, st]
437
+ pt, bs = lr("pool", gs, gp, os_, op), lr("pool", gs, gp, os_, op, W)
438
+ lo, hi = np.nanpercentile(bs, [2.5, 97.5])
439
+ rows.append({"state": st, "arm": SHORT[arm], "t_det": TDET[arm, st], "thin_library": THIN[arm, st],
440
+ "obs_det_state": int(os_.sum()), "ratio_detmatched": 2 ** pt, "lo": 2 ** lo, "hi": 2 ** hi,
441
+ "ratio_screen": raw_ratio(gs, gp, A[arm, st]["obsthin_state"], op)})
442
+ DR = pd.DataFrame(rows)
443
+ rows = []
444
+ for scr, comp, _ in COMPS:
445
+ for st in RARE + CONTROLS:
446
+ if (L16, st) not in DETCNT:
447
+ continue
448
+ gs, gp, _, op = vecs(scr, scr, st)
449
+ cs, cp, _, cop = vecs(comp, comp, st)
450
+ a, c = DETCNT[scr, st], DETCNT[comp, st]
451
+ D = abs(lr("pool", gs, gp, a, op)) - abs(lr("pool", cs, cp, c, cop))
452
+ Db = np.abs(lr("pool", gs, gp, a, op, W)) - np.abs(lr("pool", cs, cp, c, cop, W))
453
+ lo, hi = np.nanpercentile(Db, [2.5, 97.5])
454
+ rows.append({"comparison": f"{SHORT[scr]} vs {SHORT[comp]}", "state": st, "D_detmatched": D, "lo": lo,
455
+ "hi": hi, "verdict": verdict(lo, hi)})
456
+ DD = pd.DataFrame(rows)
457
+ write(DR, "detmatched_ratios")
458
+ write(DD, "detmatched_comparisons")
459
+ with pd.option_context("display.width", 250, "display.max_rows", 400):
460
+ log(DR.pivot_table(index="state", columns="arm", values="ratio_detmatched")[
461
+ ["s50k", "s162k", "r16", "r64", "full108k", "full20k", "xcal", "own5", "own58"]].round(3).to_string())
462
+ log(DD[~DD.state.isin(CONTROLS)].pivot_table(index="state", columns="comparison", values="verdict",
463
+ aggfunc="first").to_string())
464
+ # aggregate under detection matching (11 marker rare states + 2 label states at their screen values)
465
+ rows = []
466
+ for scr, comp, _ in COMPS:
467
+ Ds, Dbs = [], []
468
+ for st in RARE:
469
+ gs, gp, os_s, op = vecs(scr, scr, st)
470
+ cs, cp, os_c, cop = vecs(comp, comp, st)
471
+ if (L16, st) in DETCNT:
472
+ os_s, os_c = DETCNT[scr, st], DETCNT[comp, st]
473
+ Ds.append(abs(lr("pool", gs, gp, os_s, op)) - abs(lr("pool", cs, cp, os_c, cop)))
474
+ Dbs.append(np.abs(lr("pool", gs, gp, os_s, op, W)) - np.abs(lr("pool", cs, cp, os_c, cop, W)))
475
+ lo, hi = np.nanpercentile(np.vstack(Dbs).mean(0), [2.5, 97.5])
476
+ rows.append({"comparison": f"{SHORT[scr]} vs {SHORT[comp]}", "mean_D_detmatched": float(np.mean(Ds)),
477
+ "lo": lo, "hi": hi, "verdict": verdict(lo, hi),
478
+ "n_comparator_closer": int(sum(1 for x in DD[(DD.comparison == f"{SHORT[scr]} vs {SHORT[comp]}") &
479
+ ~DD.state.isin(CONTROLS)].verdict
480
+ if x == "comparator_closer_sig")),
481
+ "n_scratch_closer_markers_only": int(sum(1 for x in DD[(DD.comparison == f"{SHORT[scr]} vs {SHORT[comp]}") &
482
+ ~DD.state.isin(CONTROLS)].verdict
483
+ if x == "scratch_closer_sig"))})
484
+ DAG = pd.DataFrame(rows)
485
+ write(DAG, "detmatched_aggregate")
486
+ log(DAG.round(3).to_string(index=False))
487
+ log(f"[{time.time() - T0:.0f}s]")
488
+
489
+ # ------------------------------------------------------------------------------------------------ LAB
490
+ log("== LAB: label-state marker support ==")
491
+ cyc = [SYM2COL[g] for g in ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"]]
492
+ pbm = [SYM2COL[g] for g in ["JCHAIN", "MZB1", "TNFRSF17", "TXNDC5", "PRDM1", "IRF4", "IGLL5"]]
493
+ rows = []
494
+
495
+
496
+ def lab_rows(name, l1, l2, M, thin_t=None, rngx=None):
497
+ Mx = M
498
+ if thin_t is not None and thin_t < 1:
499
+ Mx = M.copy()
500
+ Mx[:, cyc + pbm] = rngx.binomial(M[:, cyc + pbm], thin_t)
501
+ T = np.isin(l1, ["T cell"]) | np.isin(l2, ["T cell"])
502
+ pro = np.isin(l2, ["Proliferating T cell"]) & T
503
+ pla = np.isin(l2, ["Plasma cell"])
504
+ ncyc = (Mx[:, cyc] > 0).sum(1)
505
+ npb = (Mx[:, pbm] > 0).sum(1)
506
+ return {"source": name, "T_cells": int(T.sum()), "prolif_T_labelled": int(pro.sum()),
507
+ "prolifT_frac_ge1_cycling_gene": float((ncyc[pro] >= 1).mean()) if pro.any() else np.nan,
508
+ "prolifT_frac_ge2_cycling_genes": float((ncyc[pro] >= 2).mean()) if pro.any() else np.nan,
509
+ "otherT_frac_ge2_cycling_genes": float((ncyc[T & ~pro] >= 2).mean()),
510
+ "frac_of_ge2cycling_T_labelled_prolif": float(pro[T & (ncyc >= 2)].mean()) if (T & (ncyc >= 2)).any() else np.nan,
511
+ "plasma_labelled": int(pla.sum()),
512
+ "plasma_frac_ge3_pb_markers": float((npb[pla] >= 3).mean()) if pla.any() else np.nan,
513
+ "plasma_frac_JCHAIN_or_MZB1": float(((Mx[pla][:, [SYM2COL['JCHAIN'], SYM2COL['MZB1']]] > 0).any(1)).mean())
514
+ if pla.any() else np.nan}
515
+
516
+
517
+ rows.append(lab_rows("observed native", L1O, L2O, MO))
518
+ rr = np.random.default_rng(SEED)
519
+ for tname, tt in [("observed thinned to r16 T depth", THIN[L16, "Cycling T/NK"])]:
520
+ rows.append(lab_rows(tname, L1O, L2O, MO, tt, rr))
521
+ for arm in ARMS:
522
+ gm = G[arm]
523
+ rows.append(lab_rows(SHORT[arm], gm["aifi_l1"].astype(str), gm["aifi_l2"].astype(str), gm["markers"]))
524
+ LAB = pd.DataFrame(rows)
525
+ write(LAB, "label_validity")
526
+ with pd.option_context("display.width", 250):
527
+ log(LAB.round(3).to_string(index=False))
528
+
529
+ # ------------------------------------------------------------------------------------------------ depth stats
530
+ log("== depth readouts from extracts (cross-4) ==")
531
+ rows = []
532
+ for arm in ARMS:
533
+ gm = G[arm]
534
+ l1, l2 = gm["aifi_l1"].astype(str), gm["aifi_l2"].astype(str)
535
+ for pname, par in [("Monocyte", ["Monocyte"]), ("T cell", ["T cell"])]:
536
+ m = pmask(l1, l2, par)
537
+ Mg = gm["markers"][m]
538
+ nz = Mg[Mg > 0]
539
+ rows.append({"arm": SHORT[arm], "parent": pname, "median_lib_all_cells": float(np.median(gm["lib_measured"])),
540
+ "median_lib_parent": float(np.median(gm["lib_measured"][m])),
541
+ "mean_detected_of_73": float((Mg > 0).sum(1).mean()),
542
+ "umi_per_detected_marker": float(nz.mean()),
543
+ **{f"det_{g}": float((Mg[:, SYM2COL[g]] > 0).mean()) for g in ["HLA-DRA", "NKG7", "GZMA", "CCR7"]}})
544
+ for pname, par in [("Monocyte", ["Monocyte"]), ("T cell", ["T cell"])]:
545
+ m = pmask(L1O, L2O, par)
546
+ Mg = MO[m]
547
+ nz = Mg[Mg > 0]
548
+ rows.append({"arm": "observed native", "parent": pname, "median_lib_all_cells": float(np.median(LIBO)),
549
+ "median_lib_parent": float(np.median(LIBO[m])), "mean_detected_of_73": float((Mg > 0).sum(1).mean()),
550
+ "umi_per_detected_marker": float(nz.mean()),
551
+ **{f"det_{g}": float((Mg[:, SYM2COL[g]] > 0).mean()) for g in ["HLA-DRA", "NKG7", "GZMA", "CCR7"]}})
552
+ DS = pd.DataFrame(rows)
553
+ write(DS, "depth_readouts")
554
+ with pd.option_context("display.width", 250):
555
+ log(DS.round(3).to_string(index=False))
556
+
557
+ # ------------------------------------------------------------------------------------------------ CON
558
+ log("== CON: contrasts ==")
559
+
560
+
561
+ def pctv(s, p):
562
+ with np.errstate(invalid="ignore", divide="ignore"):
563
+ return np.where(p > 0, 100 * s / np.where(p > 0, p, 1), np.nan)
564
+
565
+
566
+ rows = []
567
+ gidx = {name: (np.isin(groups, a), np.isin(groups, b)) for name, a, b in CONTRASTS}
568
+ # stratified bootstrap index (within the union of contrast groups, resample donors within each group)
569
+ rngc = np.random.default_rng(SEED)
570
+ grp_members = {g: np.flatnonzero(groups == g) for g in np.unique(groups)}
571
+ SB = np.zeros((B, n))
572
+ for b in range(B):
573
+ for g, mem in grp_members.items():
574
+ pick = rngc.choice(mem, size=len(mem), replace=True)
575
+ SB[b] += np.bincount(pick, minlength=n)
576
+
577
+
578
+ def diff(vals, ma, mb, w=None):
579
+ ok = ~np.isnan(vals)
580
+ v = np.where(ok, vals, 0.0)
581
+ if w is None:
582
+ return v[ma & ok].mean() - v[mb & ok].mean()
583
+ wa, wb = w * (ma & ok), w * (mb & ok)
584
+ return (wa @ v) / wa.sum(1) - (wb @ v) / wb.sum(1)
585
+
586
+
587
+ for arm in ARMS:
588
+ for variant, ref in [("own_ref", arm)] + ([("r16_depth_ref", L16), ("r64_depth_ref", L64),
589
+ ("full108k_depth_ref", F108)] if arm in SCRATCH else []):
590
+ for st in RARE:
591
+ g, o = A[arm, st], A[ref, st]
592
+ gp_, op_ = pctv(g["gen_state"], g["gen_parent"]), pctv(o["obsthin_state"], o["obs_parent"])
593
+ for name, _, _ in CONTRASTS:
594
+ ma, mb = gidx[name]
595
+ od, gd = diff(op_, ma, mb), diff(gp_, ma, mb)
596
+ gdb, odb = diff(gp_, ma, mb, SB), diff(op_, ma, mb, SB)
597
+ lodo_same = 0
598
+ for j in range(n):
599
+ keepj = np.ones(n, bool)
600
+ keepj[j] = False
601
+ gdj = diff(gp_, ma & keepj, mb & keepj)
602
+ lodo_same += np.sign(gdj) == np.sign(od)
603
+ rows.append({"arm": SHORT[arm], "variant": variant, "state": st, "contrast": name,
604
+ "n_a": int(ma.sum()), "n_b": int(mb.sum()), "obs_diff": od, "gen_diff": gd,
605
+ "same_direction": bool(np.sign(od) == np.sign(gd)),
606
+ "gen_over_obs_diff": gd / od if od != 0 else np.nan,
607
+ "boot_P_gen_sign_eq_obs": float(np.mean(np.sign(gdb) == np.sign(od))),
608
+ "boot_P_obs_sign_stable": float(np.mean(np.sign(odb) == np.sign(od))),
609
+ "lodo_same_direction_frac": lodo_same / n,
610
+ "obs_state_cells_group_b": int(o["obsthin_state"][mb].sum()),
611
+ "gen_state_cells_group_a": int(g["gen_state"][ma].sum()),
612
+ "gen_state_cells_group_b": int(g["gen_state"][mb].sum())})
613
+ CT = pd.DataFrame(rows)
614
+ own = CT[CT.variant == "own_ref"]
615
+ elig = own.assign(big=own.obs_diff.abs() >= 0.5, sg=np.sign(own.obs_diff)).groupby(["state", "contrast"]).agg(
616
+ big=("big", "all"), sgn=("sg", lambda s: s.nunique() == 1)).reset_index()
617
+ elig["common"] = elig.big & elig.sgn
618
+ CT = CT.merge(elig[["state", "contrast", "common"]], on=["state", "contrast"], how="left")
619
+ write(CT, "contrasts")
620
+ rows = []
621
+ for (arm, variant), t in CT[CT.common].groupby(["arm", "variant"], sort=False):
622
+ k = int(t.same_direction.sum())
623
+ rows.append({"arm": arm, "variant": variant, "n_pairs": len(t), "kept": k,
624
+ "binom_p_ge_kept_at_0.5": float(binom.sf(k - 1, len(t), 0.5)),
625
+ "robust_kept_boot_P>=0.95": int((t.boot_P_gen_sign_eq_obs >= 0.95).sum()),
626
+ "robust_reversed_boot_P<=0.05": int((t.boot_P_gen_sign_eq_obs <= 0.05).sum()),
627
+ "kept_and_lodo_stable": int((t.same_direction & (t.lodo_same_direction_frac == 1)).sum()),
628
+ "median_ratio_kept": float(t[t.same_direction].gen_over_obs_diff.median()),
629
+ "median_ratio_all21_signed": float(t.gen_over_obs_diff.median()),
630
+ "mean_ratio_all21_signed": float(t.gen_over_obs_diff.mean())})
631
+ CC = pd.DataFrame(rows)
632
+ write(CC, "contrast_counts")
633
+ with pd.option_context("display.width", 250):
634
+ log(CC.round(3).to_string(index=False))
635
+ # paired compression on pairs kept by both (own reference)
636
+ rows = []
637
+ for comp in [L16, L64, F108, F20, XCAL, OWN58]:
638
+ a = CT[(CT.arm == "s162k") & (CT.variant == "own_ref") & CT.common].set_index(["state", "contrast"])
639
+ a16 = CT[(CT.arm == "s162k") & (CT.variant == "r16_depth_ref") & CT.common].set_index(["state", "contrast"])
640
+ c = CT[(CT.arm == SHORT[comp]) & (CT.variant == "own_ref") & CT.common].set_index(["state", "contrast"])
641
+ both = a.same_direction & c.same_direction
642
+ rows.append({"comparator": SHORT[comp], "pairs_kept_by_both": int(both.sum()),
643
+ "scratch_median_ratio_on_both": float(a[both].gen_over_obs_diff.median()),
644
+ "scratch_r16depth_median_ratio_on_both": float(a16[both].gen_over_obs_diff.median()),
645
+ "comparator_median_ratio_on_both": float(c[both].gen_over_obs_diff.median()),
646
+ "pairs_scratch_less_compressed": int((a[both].gen_over_obs_diff > c[both].gen_over_obs_diff).sum())})
647
+ PC = pd.DataFrame(rows)
648
+ write(PC, "contrast_paired_compression")
649
+ log(PC.round(3).to_string(index=False))
650
+ log(f"[{time.time() - T0:.0f}s]")
651
+
652
+ # ------------------------------------------------------------------------------------------------ SP
653
+ log("== SP: Spearman over donors ==")
654
+
655
+
656
+ def spearman(x, y):
657
+ ok = ~(np.isnan(x) | np.isnan(y))
658
+ x, y = x[ok], y[ok]
659
+ if len(x) < 3:
660
+ return np.nan
661
+ rx, ry = rankdata(x), rankdata(y)
662
+ if rx.std() == 0 or ry.std() == 0:
663
+ return np.nan
664
+ return float(np.corrcoef(rx, ry)[0, 1])
665
+
666
+
667
+ def sp_boot(x, y):
668
+ out = np.full(B, np.nan)
669
+ for b in range(B):
670
+ out[b] = spearman(x[IDX[b]], y[IDX[b]])
671
+ return out
672
+
673
+
674
+ rows, SPB = [], {}
675
+ for arm in ARMS:
676
+ for st in RARE:
677
+ g = A[arm, st]
678
+ x, y = pctv(g["gen_state"], g["gen_parent"]), pctv(g["obsthin_state"], g["obs_parent"])
679
+ SPB[arm, st] = sp_boot(x, y)
680
+ rows.append({"arm": SHORT[arm], "state": st, "rho": spearman(x, y),
681
+ "rho_lo": np.nanpercentile(SPB[arm, st], 2.5), "rho_hi": np.nanpercentile(SPB[arm, st], 97.5),
682
+ "frac_donors_gen_state_0": float(np.mean(g["gen_state"] == 0)),
683
+ "frac_donors_obs_state_0": float(np.mean(g["obsthin_state"] == 0))})
684
+ SPT = pd.DataFrame(rows)
685
+ rows = []
686
+ for comp in [L16, L64, F108, XCAL, OWN58]:
687
+ for st in RARE:
688
+ dlt = SPB[S162, st] - SPB[comp, st]
689
+ lo, hi = np.nanpercentile(dlt, [2.5, 97.5])
690
+ rows.append({"comparison": f"s162k vs {SHORT[comp]}", "state": st,
691
+ "diff": SPT[(SPT.arm == "s162k") & (SPT.state == st)].rho.iloc[0]
692
+ - SPT[(SPT.arm == SHORT[comp]) & (SPT.state == st)].rho.iloc[0],
693
+ "lo": lo, "hi": hi, "ci_width": hi - lo,
694
+ "verdict": "scratch_higher_sig" if lo > 0 else "comparator_higher_sig" if hi < 0 else "n.s."})
695
+ SPD = pd.DataFrame(rows)
696
+ write(SPT, "spearman")
697
+ write(SPD, "spearman_diff")
698
+ with pd.option_context("display.width", 250, "display.max_rows", 300):
699
+ pv = SPT.pivot_table(index="state", columns="arm", values="rho")[[SHORT[a] for a in ARMS]]
700
+ log(pv.round(3).to_string())
701
+ log("mean rho over 13 states: " + ", ".join(f"{k} {v:.3f}" for k, v in pv.mean().items()))
702
+ log("best arm per state: " + "; ".join(f"{s[:18]}={pv.loc[s].idxmax()}" for s in pv.index))
703
+ log(SPD.groupby("comparison").agg(n_sig=("verdict", lambda v: int((v != "n.s.").sum())),
704
+ median_ci_width=("ci_width", "median"), mean_diff=("diff", "mean")).round(3)
705
+ .to_string())
706
+ log(SPD[SPD.verdict != "n.s."].round(3).to_string(index=False))
707
+
708
+ # ------------------------------------------------------------------------------------------------ FOLD
709
+ log("== FOLD: own-cohort vs cross-cohort arms on each within-cohort fold's donors ==")
710
+ folds = pd.read_csv(DATA / "folds.csv").set_index("sample_id").fold.reindex(donors).to_numpy()
711
+ rows = []
712
+ for st in ["C1Q-high monocyte (reference)", "MS1 monocyte (IL1R2+)", "Cycling T/NK", "Cycling monocyte (Ye 2026)"]:
713
+ for arm in [OWN5, OWN58, S162, L16, L64, F108, XCAL]:
714
+ for f in sorted(set(folds)):
715
+ m = folds == f
716
+ gs, gp, os_, op = (v[m] for v in vecs(arm, arm, st))
717
+ rows.append({"state": st, "arm": SHORT[arm], "fold": int(f), "n_donors": int(m.sum()),
718
+ "ratio": raw_ratio(gs, gp, os_, op), "gen_state": int(gs.sum()),
719
+ "obsthin_state": int(os_.sum())})
720
+ FO = pd.DataFrame(rows)
721
+ write(FO, "per_fold")
722
+ with pd.option_context("display.width", 250, "display.max_rows", 300):
723
+ log(FO.pivot_table(index=["state", "fold"], columns="arm", values="ratio")[
724
+ ["own5", "own58", "s162k", "r16", "r64", "full108k", "xcal"]].round(3).to_string())
725
+
726
+ (OUT / f"{PFX}run.log").write_text("\n".join(LOG) + "\n")
727
+ log(f"done [{time.time() - T0:.0f}s]")
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_confound_within_analysis.py ADDED
@@ -0,0 +1,965 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Adversarial confound verification of the WITHIN-COHORT scratch-vs-pretrained rare-state claims (within-1..8).
3
+
4
+ CPU only, read-only inputs, 2026-10-05. Run:
5
+ CUDA_VISIBLE_DEVICES='' PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=4 \
6
+ /home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python verify_confound_within_analysis.py
7
+ Writes only verify_confound_within_*.csv next to this script (NaN / undefined -> "null").
8
+
9
+ Inputs (read-only)
10
+ ../sepsis_fold0_{per_donor,summary,contrasts}.csv fold 0, 17 held-out donors, 8 arms
11
+ ../sepsis_per_donor.csv pooled cross-fitted arms (all 82 donors; LoRA n5..n40, all)
12
+ ../../work/sepsis/fold0/<arm>.npz per-cell marker extracts of the generated cells
13
+ tools/sepsis_states.observed() observed cells of the same 17 donors (imported, not run)
14
+ paired_finetune_intradataset_20260927/data/ye2026_sepsis/folds.csv fold assignment
15
+
16
+ Sections (output file suffix)
17
+ repro re-computation of every number used by the claims (pooled ratio, |log2|, D, percentile / BC CI)
18
+ lodo leave-one-donor-out D (point + 16-donor bootstrap verdict) for all comparisons, states, aggregates
19
+ donormean donor-mean weighting (mean per-donor %) instead of pooled cell counts
20
+ concentration observed state cells: donors carrying the state, top-donor share, sepsis share
21
+ depth re-scoring of marker states from the per-cell extracts under alternative depth handling:
22
+ V0_replay exact replay of the screen (seed 20261004) -> validates this pipeline
23
+ V0_reseed screen thinning constants, new binomial draw (seed 20261005)
24
+ V1_lib_trained generated AND observed thinned to one common library target per state
25
+ (lowest parent median among observed + 7 trained arms)
26
+ V1_lib_all same, target includes zero-shot (lowest)
27
+ V2_msum_trained common target on effective marker depth (sum of parent mean counts over the
28
+ extracted markers minus the state's own rule genes, observed mean >= 0.1)
29
+ V2_msum_all same, incl. zero-shot
30
+ composition parent-composition standardisation (rates within AIFI L2 strata re-weighted to observed mix)
31
+ labelcheck proliferating-T label vs cycling-marker rule with donor-bootstrap CIs
32
+ contrasts direction counts, LODO stability, paired discordance, relative reversal strength
33
+ spearman Spearman reproduction, perfect-tracking noise ceiling, within-sepsis-only Spearman
34
+ folds LoRA arms of other folds / other pair counts (pooled cross-fitted CSV) -> generalisation
35
+ """
36
+ from __future__ import annotations
37
+
38
+ import json
39
+ import sys
40
+ import time
41
+ from pathlib import Path
42
+
43
+ import numpy as np
44
+ import pandas as pd
45
+ from scipy.stats import binomtest, norm, rankdata
46
+
47
+ PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
48
+ OUT = PLAN / "out/scratch_vs_lora_20261005"
49
+ SRC = PLAN / "out"
50
+ WORK = PLAN / "work/sepsis/fold0"
51
+ FOLDS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
52
+ "paired_finetune_intradataset_20260927/data/ye2026_sepsis/folds.csv")
53
+ PREFIX = "verify_confound_within_"
54
+ sys.path.insert(0, str(PLAN / "tools"))
55
+ from screen import call_state, parent_mask, state_cols # noqa: E402
56
+ from sepsis_states import observed # noqa: E402
57
+
58
+ SEED, NBOOT, PC = 20261005, 2000, 0.5
59
+ SCREEN_THIN_SEED = 20261004
60
+ ARMS = ["zs__raw", "lora_n5__raw", "scratch_n5__raw", "real_lora__raw", "real_full__raw", "scratch_full__raw",
61
+ "lora_recipe__raw", "scratch_recipe__raw"]
62
+ TRAINED = ARMS[1:]
63
+ MAIN = [("5 pairs: scratch vs LoRA", "scratch_n5__raw", "lora_n5__raw"),
64
+ ("58 pairs: scratch vs LoRA", "scratch_full__raw", "real_lora__raw"),
65
+ ("58 pairs: scratch vs full FT", "scratch_full__raw", "real_full__raw"),
66
+ ("58 pairs + recipes: scratch vs LoRA", "scratch_recipe__raw", "lora_recipe__raw")]
67
+ REFC = [("ref: scratch 5 pairs vs zero-shot", "scratch_n5__raw", "zs__raw"),
68
+ ("ref: scratch 58 pairs vs zero-shot", "scratch_full__raw", "zs__raw"),
69
+ ("ref: scratch 58 + recipes vs zero-shot", "scratch_recipe__raw", "zs__raw")]
70
+ CONTROLS = ["ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"]
71
+ LABEL_STATES = ["Proliferating T (label)", "Plasmablast (label)"]
72
+ KEYS = ["gen_state", "gen_parent", "obsthin_state", "obs_parent", "obs_state", "gen_pct", "obsthin_pct"]
73
+ CYC = ["MKI67", "TOP2A", "TYMS", "CENPF", "UBE2C", "BIRC5"]
74
+ T0 = time.time()
75
+
76
+
77
+ def log(*a):
78
+ print(f"[{time.time() - T0:7.1f}s]", *a, flush=True)
79
+
80
+
81
+ def write(df: pd.DataFrame, name: str) -> None:
82
+ df.to_csv(OUT / f"{PREFIX}{name}.csv", index=False, na_rep="null", float_format="%.6g")
83
+ log("wrote", f"{PREFIX}{name}.csv", df.shape)
84
+
85
+
86
+ # ----------------------------------------------------------------------------------------------- statistics helpers
87
+ def l2r(x: dict, sub=None, idx=None, pc=PC):
88
+ """Pooled log2((gen_state+pc)/gen_parent / ((obsthin_state+pc)/obs_parent)); sub = donor subset (positions),
89
+ idx = bootstrap index matrix into that subset (B, n_sub) -> (B,)."""
90
+ def tot(k):
91
+ v = x[k] if sub is None else x[k][sub]
92
+ return v.sum() if idx is None else v[idx].sum(-1)
93
+ gs, gp, os_, op = tot("gen_state"), tot("gen_parent"), tot("obsthin_state"), tot("obs_parent")
94
+ with np.errstate(divide="ignore", invalid="ignore"):
95
+ v = np.log2(((gs + pc) / gp) / ((os_ + pc) / op))
96
+ return np.where(np.isfinite(v), v, np.nan)
97
+
98
+
99
+ def raw_ratio(x: dict, sub=None):
100
+ s = (lambda k: x[k].sum()) if sub is None else (lambda k: x[k][sub].sum())
101
+ gp, op, os_ = s("gen_parent"), s("obs_parent"), s("obsthin_state")
102
+ if gp == 0 or op == 0 or os_ == 0:
103
+ return np.nan
104
+ return (s("gen_state") / gp) / (os_ / op)
105
+
106
+
107
+ def pci(v):
108
+ v = np.asarray(v, float)
109
+ v = v[np.isfinite(v)]
110
+ if len(v) == 0:
111
+ return np.nan, np.nan
112
+ lo, hi = np.percentile(v, [2.5, 97.5])
113
+ return float(lo), float(hi)
114
+
115
+
116
+ def bc_ci(v, t0):
117
+ v = np.asarray(v, float)
118
+ v = v[np.isfinite(v)]
119
+ if len(v) == 0 or not np.isfinite(t0):
120
+ return np.nan, np.nan
121
+ z0 = norm.ppf(np.clip((v < t0).mean() + 0.5 * (v == t0).mean(), 1e-4, 1 - 1e-4))
122
+ q = norm.cdf(2 * z0 + norm.ppf([0.025, 0.975]))
123
+ lo, hi = np.percentile(v, 100 * q)
124
+ return float(lo), float(hi)
125
+
126
+
127
+ def verdict(lo, hi, pos="pretrained closer", neg="scratch closer"):
128
+ if not (np.isfinite(lo) and np.isfinite(hi)):
129
+ return "undefined"
130
+ return pos if lo > 0 else neg if hi < 0 else "not significant"
131
+
132
+
133
+ def spearman(x, y):
134
+ m = np.isfinite(x) & np.isfinite(y)
135
+ if m.sum() < 3:
136
+ return np.nan
137
+ rx, ry = rankdata(x[m]), rankdata(y[m])
138
+ if rx.std() == 0 or ry.std() == 0:
139
+ return np.nan
140
+ return float(np.corrcoef(rx, ry)[0, 1])
141
+
142
+
143
+ def spearman_rows(G, O):
144
+ """Row-wise Spearman of (B, n) arrays; rows with NaN fall back to the masked scalar version."""
145
+ out = np.full(G.shape[0], np.nan)
146
+ bad = ~(np.isfinite(G).all(1) & np.isfinite(O).all(1))
147
+ ok = ~bad
148
+ if ok.any():
149
+ rg, ro = rankdata(G[ok], axis=1), rankdata(O[ok], axis=1)
150
+ rg = rg - rg.mean(1, keepdims=True)
151
+ ro = ro - ro.mean(1, keepdims=True)
152
+ den = np.sqrt((rg ** 2).sum(1) * (ro ** 2).sum(1))
153
+ with np.errstate(divide="ignore", invalid="ignore"):
154
+ out[ok] = np.where(den > 0, (rg * ro).sum(1) / den, np.nan)
155
+ for i in np.flatnonzero(bad):
156
+ out[i] = spearman(G[i], O[i])
157
+ return out
158
+
159
+
160
+ def absl(v):
161
+ return np.abs(v)
162
+
163
+
164
+ # ----------------------------------------------------------------------------------------------- load
165
+ def load_fold0():
166
+ P = pd.read_csv(SRC / "sepsis_fold0_per_donor.csv")
167
+ S = pd.read_csv(SRC / "sepsis_fold0_summary.csv")
168
+ C = pd.read_csv(SRC / "sepsis_fold0_contrasts.csv")
169
+ donors = sorted(P.donor.unique())
170
+ states = list(dict.fromkeys(S.state))
171
+ A = {}
172
+ for (a, s), t in P.groupby(["arm", "state"]):
173
+ t = t.set_index("donor").loc[donors]
174
+ A[a, s] = {k: t[k].to_numpy(float) for k in KEYS}
175
+ groups = P.drop_duplicates("donor").set_index("donor").group.loc[donors].to_numpy()
176
+ return P, S, C, donors, states, A, groups
177
+
178
+
179
+ def comparison_rows(A, states, rare, comps, IDX, tag, extra=None):
180
+ """D = |log2 r_pc(scratch)| - |log2 r_pc(pretrained)| per state + aggregate over `rare`, donor bootstrap."""
181
+ rows = []
182
+ L0 = {}
183
+ LB = {}
184
+ arms = {a for _, sa, pa in comps for a in (sa, pa)}
185
+ for a in arms:
186
+ for s in states:
187
+ L0[a, s] = float(l2r(A[a, s]))
188
+ LB[a, s] = l2r(A[a, s], idx=IDX)
189
+ for name, sa, pa in comps:
190
+ for s in states + ["AGGREGATE"]:
191
+ if s == "AGGREGATE":
192
+ ss = rare
193
+ d0 = float(np.mean([abs(L0[sa, t]) - abs(L0[pa, t]) for t in ss]))
194
+ db = np.mean(np.vstack([absl(LB[sa, t]) - absl(LB[pa, t]) for t in ss]), axis=0)
195
+ fs = float(np.mean([abs(L0[sa, t]) for t in ss]))
196
+ fp = float(np.mean([abs(L0[pa, t]) for t in ss]))
197
+ rs = rp = np.nan
198
+ else:
199
+ d0 = abs(L0[sa, s]) - abs(L0[pa, s])
200
+ db = absl(LB[sa, s]) - absl(LB[pa, s])
201
+ fs, fp = abs(L0[sa, s]), abs(L0[pa, s])
202
+ rs, rp = raw_ratio(A[sa, s]), raw_ratio(A[pa, s])
203
+ lo, hi = pci(db)
204
+ blo, bhi = bc_ci(db, d0)
205
+ row = {"scheme": tag, "comparison": name, "scratch_arm": sa, "pretrained_arm": pa, "state": s,
206
+ "ratio_scratch": rs, "ratio_pretrained": rp, "abs_log2_scratch": fs, "abs_log2_pretrained": fp,
207
+ "D": d0, "D_ci_lo": lo, "D_ci_hi": hi, "verdict": verdict(lo, hi),
208
+ "D_bc_ci_lo": blo, "D_bc_ci_hi": bhi, "verdict_bc": verdict(blo, bhi)}
209
+ if extra:
210
+ row.update(extra.get((sa, pa, s), {}))
211
+ rows.append(row)
212
+ return pd.DataFrame(rows), L0, LB
213
+
214
+
215
+ # ----------------------------------------------------------------------------------------------- main
216
+ def main():
217
+ P, S, C, donors, states, A, groups = load_fold0()
218
+ n = len(donors)
219
+ rare = [s for s in states if s not in CONTROLS]
220
+ marker_states = [s for s in states if s not in LABEL_STATES]
221
+ IDX = np.random.default_rng(SEED).integers(0, n, (NBOOT, n))
222
+ log("donors", n, dict(pd.Series(groups).value_counts()), "rare states", len(rare))
223
+
224
+ # ===================================================================================== 1. reproduction
225
+ R, L0, LB = comparison_rows(A, states, rare, MAIN + REFC, IDX, "V0_published")
226
+ pub = pd.read_csv(OUT / "within_bootstrap.csv")
227
+ pub["state2"] = np.where(pub.role == "aggregate", "AGGREGATE", pub.state)
228
+ m = R.merge(pub[["scratch_arm", "pretrained_arm", "state2", "D", "D_ci_lo", "D_ci_hi", "D_bc_ci_lo",
229
+ "D_bc_ci_hi"]].rename(columns={"state2": "state"}),
230
+ on=["scratch_arm", "pretrained_arm", "state"], suffixes=("", "_pub"))
231
+ for c in ["D", "D_ci_lo", "D_ci_hi", "D_bc_ci_lo", "D_bc_ci_hi"]:
232
+ m[f"absdiff_{c}"] = (m[c] - m[f"{c}_pub"]).abs()
233
+ R = m
234
+ # arm-level fidelity (signed log2 with CI) and mean |log2| per arm
235
+ af = []
236
+ for a in ARMS:
237
+ for s in states:
238
+ lo, hi = pci(LB.get((a, s), l2r(A[a, s], idx=IDX)))
239
+ af.append({"arm": a, "state": s, "ratio_raw": raw_ratio(A[a, s]), "log2_pc": float(l2r(A[a, s])),
240
+ "log2_ci_lo": lo, "log2_ci_hi": hi, "gen_state": A[a, s]["gen_state"].sum(),
241
+ "gen_parent": A[a, s]["gen_parent"].sum(), "obsthin_state": A[a, s]["obsthin_state"].sum(),
242
+ "obs_parent": A[a, s]["obs_parent"].sum()})
243
+ af.append({"arm": a, "state": "MEAN |log2| over 13 rare states",
244
+ "log2_pc": float(np.mean([abs(float(l2r(A[a, s]))) for s in rare]))})
245
+ AF = pd.DataFrame(af)
246
+ R2 = pd.concat([R.assign(section="comparison"), AF.assign(section="arm")], ignore_index=True)
247
+ write(R2, "repro")
248
+ log("max |diff| vs published:", {c: float(R[f'absdiff_{c}'].max()) for c in ["D", "D_ci_lo", "D_ci_hi",
249
+ "D_bc_ci_lo", "D_bc_ci_hi"]})
250
+ main_rows = R[R.comparison.isin([c[0] for c in MAIN]) & R.state.isin(rare)]
251
+ log("state-level verdict counts (main, 13 rare):", main_rows.verdict.value_counts().to_dict(),
252
+ "BC:", main_rows.verdict_bc.value_counts().to_dict())
253
+
254
+ # state-set sensitivity of the aggregate
255
+ subsets = {
256
+ "13 rare (claim)": rare,
257
+ "11 marker states (no label states)": [s for s in rare if s not in LABEL_STATES],
258
+ "drop states where both arms < 0.25x": None, # per comparison
259
+ "drop LDG + cycling monocyte (dual failures)": [s for s in rare if s not in
260
+ ("Granulocyte-like (LDG)", "Cycling monocyte (Ye 2026)")],
261
+ "non-redundant 9 (drop Cycling activated T, Plasmablast markers, Proliferating T label, HSPC)":
262
+ [s for s in rare if s not in ("Cycling activated T (CD38/HLA-DR)", "Plasmablast (markers)",
263
+ "Proliferating T (label)", "HSPC")],
264
+ "monocyte states (C1Q, MS1, cycling mono)": ["C1Q-high monocyte (reference)", "MS1 monocyte (IL1R2+)",
265
+ "Cycling monocyte (Ye 2026)"],
266
+ "T/NK states (cycling T/NK, cycling act T, prolif T label, ISG-high T, cytotoxic CD4)":
267
+ ["Cycling T/NK", "Cycling activated T (CD38/HLA-DR)", "Proliferating T (label)", "ISG-high T",
268
+ "Cytotoxic CD4 T"],
269
+ }
270
+ ssr = []
271
+ for name, sa, pa in MAIN + REFC:
272
+ for lab, ss in subsets.items():
273
+ if ss is None:
274
+ ss = [s for s in rare if not (raw_ratio(A[sa, s]) < 0.25 and raw_ratio(A[pa, s]) < 0.25)]
275
+ d0 = float(np.mean([abs(L0[sa, t]) - abs(L0[pa, t]) for t in ss]))
276
+ db = np.mean(np.vstack([absl(LB[sa, t]) - absl(LB[pa, t]) for t in ss]), axis=0)
277
+ lo, hi = pci(db)
278
+ blo, bhi = bc_ci(db, d0)
279
+ ssr.append({"comparison": name, "state_set": lab, "n_states": len(ss), "D": d0, "D_ci_lo": lo,
280
+ "D_ci_hi": hi, "verdict": verdict(lo, hi), "D_bc_ci_lo": blo, "D_bc_ci_hi": bhi,
281
+ "verdict_bc": verdict(blo, bhi), "states": "; ".join(ss)})
282
+ write(pd.DataFrame(ssr), "stateset")
283
+
284
+ # ===================================================================================== 2. leave-one-donor-out
285
+ IDX16 = np.random.default_rng(SEED).integers(0, n - 1, (NBOOT, n - 1))
286
+ lodo = []
287
+ full = {(r.comparison, r.state): r for r in R.itertuples()}
288
+ for name, sa, pa in MAIN + REFC:
289
+ per = {s: [] for s in states + ["AGGREGATE"]}
290
+ for j in range(n):
291
+ sub = np.delete(np.arange(n), j)
292
+ sidx = sub[IDX16]
293
+ Ls = {(a, s): float(l2r(A[a, s], sub=sub)) for a in (sa, pa) for s in states}
294
+ Lb = {(a, s): l2r(A[a, s], idx=sidx) for a in (sa, pa) for s in states}
295
+ for s in states + ["AGGREGATE"]:
296
+ if s == "AGGREGATE":
297
+ d0 = float(np.mean([abs(Ls[sa, t]) - abs(Ls[pa, t]) for t in rare]))
298
+ db = np.mean(np.vstack([absl(Lb[sa, t]) - absl(Lb[pa, t]) for t in rare]), axis=0)
299
+ else:
300
+ d0 = abs(Ls[sa, s]) - abs(Ls[pa, s])
301
+ db = absl(Lb[sa, s]) - absl(Lb[pa, s])
302
+ lo, hi = pci(db)
303
+ blo, bhi = bc_ci(db, d0)
304
+ per[s].append((donors[j], d0, verdict(lo, hi), verdict(blo, bhi),
305
+ 2 ** Ls[sa, s] if s != "AGGREGATE" else np.nan,
306
+ 2 ** Ls[pa, s] if s != "AGGREGATE" else np.nan))
307
+ for s, v in per.items():
308
+ f = full[(name, s)]
309
+ ds = np.array([x[1] for x in v])
310
+ vs = [x[2] for x in v]
311
+ vb = [x[3] for x in v]
312
+ infl = int(np.argmax(np.abs(ds - f.D)))
313
+ lodo.append({"comparison": name, "state": s, "D_full": f.D, "verdict_full": f.verdict,
314
+ "verdict_bc_full": f.verdict_bc, "D_lodo_min": ds.min(), "D_lodo_max": ds.max(),
315
+ "n_lodo_sign_flip": int((np.sign(ds) != np.sign(f.D)).sum()),
316
+ "n_lodo_same_verdict": int(sum(x == f.verdict for x in vs)),
317
+ "n_lodo_same_verdict_bc": int(sum(x == f.verdict_bc for x in vb)),
318
+ "lodo_verdicts": "; ".join(f"{k}:{vs.count(k)}" for k in sorted(set(vs))),
319
+ "lodo_verdicts_bc": "; ".join(f"{k}:{vb.count(k)}" for k in sorted(set(vb))),
320
+ "most_influential_donor": v[infl][0], "D_without_it": ds[infl],
321
+ "ratio_scratch_without_it": v[infl][4], "ratio_pretrained_without_it": v[infl][5]})
322
+ LO = pd.DataFrame(lodo)
323
+ write(LO, "lodo")
324
+
325
+ # ===================================================================================== 3. donor-mean weighting
326
+ dm = []
327
+ for name, sa, pa in MAIN + REFC:
328
+ Dsb, Ds0 = [], []
329
+ for s in states:
330
+ xs, xp = A[sa, s], A[pa, s]
331
+ mask = (np.isfinite(xs["gen_pct"]) & np.isfinite(xp["gen_pct"]) & np.isfinite(xs["obsthin_pct"])
332
+ & np.isfinite(xp["obsthin_pct"]))
333
+
334
+ def rdm(x, idx=None):
335
+ w = mask.astype(float) if idx is None else mask[idx].astype(float)
336
+ g = np.nan_to_num(x["gen_pct"]) if idx is None else np.nan_to_num(x["gen_pct"])[idx]
337
+ o = np.nan_to_num(x["obsthin_pct"]) if idx is None else np.nan_to_num(x["obsthin_pct"])[idx]
338
+ with np.errstate(divide="ignore", invalid="ignore"):
339
+ r = (g * w).sum(-1) / (o * w).sum(-1)
340
+ v = np.log2(r)
341
+ return np.where(np.isfinite(v), v, np.nan)
342
+ ls, lp = float(rdm(xs)), float(rdm(xp))
343
+ bs, bp = rdm(xs, IDX), rdm(xp, IDX)
344
+ d0 = abs(ls) - abs(lp) if np.isfinite(ls) and np.isfinite(lp) else np.nan
345
+ db = np.abs(bs) - np.abs(bp)
346
+ lo, hi = pci(db)
347
+ if s in rare:
348
+ Ds0.append(d0)
349
+ Dsb.append(db)
350
+ dm.append({"comparison": name, "state": s, "n_donors": int(mask.sum()),
351
+ "ratio_donor_mean_scratch": 2 ** ls if np.isfinite(ls) else np.nan,
352
+ "ratio_donor_mean_pretrained": 2 ** lp if np.isfinite(lp) else np.nan,
353
+ "ratio_pooled_scratch": raw_ratio(xs), "ratio_pooled_pretrained": raw_ratio(xp),
354
+ "D_donor_mean": d0, "D_ci_lo": lo, "D_ci_hi": hi, "verdict": verdict(lo, hi),
355
+ "D_pooled_pc": full[(name, s)].D, "verdict_pooled": full[(name, s)].verdict})
356
+ d0 = float(np.mean(Ds0)) if np.all(np.isfinite(Ds0)) else np.nan
357
+ db = np.nanmean(np.vstack(Dsb), axis=0)
358
+ lo, hi = pci(db)
359
+ dm.append({"comparison": name, "state": "AGGREGATE", "D_donor_mean": d0, "D_ci_lo": lo, "D_ci_hi": hi,
360
+ "verdict": verdict(lo, hi), "D_pooled_pc": full[(name, 'AGGREGATE')].D,
361
+ "verdict_pooled": full[(name, 'AGGREGATE')].verdict})
362
+ write(pd.DataFrame(dm), "donormean")
363
+
364
+ # ===================================================================================== 4. observed concentration
365
+ con = []
366
+ sepsis = np.isin(groups, ["adult_sepsis", "ped_sepsis"])
367
+ for s in states:
368
+ x = A[ARMS[1], s]
369
+ nat = x["obs_state"]
370
+ th = {a: A[a, s]["obsthin_state"] for a in ARMS}
371
+ order = np.argsort(-nat)
372
+ row = {"state": s, "obs_native_state_cells": nat.sum(), "obs_parent_cells": x["obs_parent"].sum(),
373
+ "donors_with_state": int((nat > 0).sum()), "top_donor": donors[order[0]],
374
+ "top_donor_group": groups[order[0]], "top_donor_share": nat[order[0]] / nat.sum() if nat.sum() else np.nan,
375
+ "top2_share": nat[order[:2]].sum() / nat.sum() if nat.sum() else np.nan,
376
+ "sepsis_share_of_state_cells": nat[sepsis].sum() / nat.sum() if nat.sum() else np.nan,
377
+ "sepsis_share_of_parent_cells": x["obs_parent"][sepsis].sum() / x["obs_parent"].sum(),
378
+ "obsthin_state_min_over_arms": min(v.sum() for v in th.values()),
379
+ "obsthin_state_max_over_arms": max(v.sum() for v in th.values())}
380
+ for a in ARMS:
381
+ g = A[a, s]["gen_state"]
382
+ row[f"gen_state__{a}"] = g.sum()
383
+ row[f"gen_top_donor_share__{a}"] = g.max() / g.sum() if g.sum() else np.nan
384
+ con.append(row)
385
+ write(pd.DataFrame(con), "concentration")
386
+
387
+ # ===================================================================================== 5. depth re-scoring
388
+ st_json = json.loads((PLAN / "tools/states.json").read_text())
389
+ st_by = {st["name"]: st for st in st_json}
390
+ log("loading observed cells via tools/sepsis_states.observed() ...")
391
+ ob = observed(st_json, donors)
392
+ syms = list(ob["marker_symbols"])
393
+ dcode = {d: i for i, d in enumerate(donors)}
394
+ do = np.array([dcode[d] for d in ob["donor"]])
395
+ lab_o = ob["lab"]
396
+ Mo, libo = ob["markers"], ob["lib"]
397
+ log("observed cells", Mo.shape)
398
+ G = {}
399
+ for a in ARMS:
400
+ g = np.load(WORK / f"{a}.npz", allow_pickle=False)
401
+ if list(g["marker_symbols"].astype(str)) != syms:
402
+ raise SystemExit(f"{a}: marker columns differ")
403
+ G[a] = {"M": g["markers"], "lib": g["lib_measured"].astype(float),
404
+ "d": np.array([dcode[x] for x in g["donor"].astype(str)]),
405
+ "lab": pd.DataFrame({"aifi_l1": g["aifi_l1"].astype(str), "aifi_l2": g["aifi_l2"].astype(str)})}
406
+ sym2col = {s: i for i, s in enumerate(syms)}
407
+ ident = {s: s for s in syms}
408
+
409
+ def parts(st):
410
+ _, pcols, req, exc = state_cols(st, ident, sym2col)
411
+ cols = pcols + [x for r in req for x in r] + exc
412
+ rule = set(st.get("genes", [])) | {x for gg in st.get("require_any", []) for x in gg} | set(st.get("exclude", []))
413
+ return cols, len(pcols), req, exc, rule
414
+
415
+ def bc(codes, mask):
416
+ return np.bincount(codes[mask], minlength=n).astype(float)
417
+
418
+ # 5a. exact replay of the screen's RNG sequence (validates every per-donor count of the published CSV)
419
+ rng = np.random.default_rng(SCREEN_THIN_SEED)
420
+ replay_bad = 0
421
+ for a in ARMS:
422
+ for st in st_json:
423
+ po = parent_mask(lab_o, st["parent"])
424
+ pg = parent_mask(G[a]["lab"], st["parent"])
425
+ if st["kind"] == "label":
426
+ hg = G[a]["lab"].aifi_l2.isin(st["labels"]).to_numpy() & pg
427
+ ht = lab_o.aifi_l2.isin(st["labels"]).to_numpy() & po
428
+ else:
429
+ cols, npos, req, exc, _ = parts(st)
430
+ thin = min(1.0, float(np.median(G[a]["lib"][pg])) / float(np.median(libo[po])))
431
+ co = Mo[:, cols].astype(np.int64)
432
+ ct = rng.binomial(co, thin) if thin < 1.0 else co
433
+ ht = call_state(ct, st, npos, req, exc) & po
434
+ hg = call_state(G[a]["M"][:, cols], st, npos, req, exc) & pg
435
+ x = A[a, st["name"]]
436
+ ok = (np.array_equal(bc(do, ht), x["obsthin_state"]) and np.array_equal(bc(G[a]["d"], hg), x["gen_state"])
437
+ and np.array_equal(bc(do, po), x["obs_parent"]) and np.array_equal(bc(G[a]["d"], pg), x["gen_parent"]))
438
+ replay_bad += int(not ok)
439
+ log("V0 replay: per-donor count rows not reproduced (arm x state):", replay_bad, "of", len(ARMS) * len(st_json))
440
+
441
+ # 5b. alternative depth schemes
442
+ def depth_meas(st):
443
+ po = parent_mask(lab_o, st["parent"])
444
+ cols, npos, req, exc, rule = parts(st)
445
+ mo_mean = Mo[po].mean(0)
446
+ ref = [i for i, s_ in enumerate(syms) if s_ not in rule and mo_mean[i] >= 0.1]
447
+ e = {"OBS": (float(np.median(libo[po])), float(mo_mean[ref].sum()))}
448
+ for a in ARMS:
449
+ pg = parent_mask(G[a]["lab"], st["parent"])
450
+ e[a] = (float(np.median(G[a]["lib"][pg])), float(G[a]["M"][pg][:, ref].mean(0).sum()))
451
+ return e, len(ref)
452
+
453
+ schemes = ["V0_reseed", "V1_lib_trained", "V1_lib_all", "V2_msum_trained", "V2_msum_all"]
454
+ Asch = {sc: {} for sc in schemes}
455
+ depth_rows = []
456
+ calls_v0 = {} # (arm, state) -> (obs thinned calls, gen calls) for the composition section
457
+ Sx = S.set_index(["arm", "state"])
458
+ for sc in schemes:
459
+ rng = np.random.default_rng(SEED)
460
+ for st in st_json:
461
+ sname = st["name"]
462
+ if st["kind"] == "label":
463
+ for a in ARMS:
464
+ Asch[sc][a, sname] = A[a, sname]
465
+ continue
466
+ cols, npos, req, exc, _ = parts(st)
467
+ po = parent_mask(lab_o, st["parent"])
468
+ co = Mo[:, cols].astype(np.int64)
469
+ e, nref = depth_meas(st)
470
+ k = 0 if sc.startswith("V1") else 1
471
+ pool = TRAINED if sc.endswith("trained") else ARMS
472
+ if sc != "V0_reseed":
473
+ target = min([e["OBS"][k]] + [e[a][k] for a in pool])
474
+ thin_o = target / e["OBS"][k]
475
+ ct = rng.binomial(co, thin_o) if thin_o < 1 else co
476
+ ht_common = call_state(ct, st, npos, req, exc) & po
477
+ for a in ARMS:
478
+ pg = parent_mask(G[a]["lab"], st["parent"])
479
+ if sc == "V0_reseed":
480
+ thin_o = min(1.0, e[a][0] / e["OBS"][0])
481
+ ct = rng.binomial(co, thin_o) if thin_o < 1 else co
482
+ ht = call_state(ct, st, npos, req, exc) & po
483
+ thin_g = 1.0
484
+ gm = G[a]["M"][:, cols]
485
+ else:
486
+ ht = ht_common
487
+ thin_g = min(1.0, target / e[a][k])
488
+ gm = G[a]["M"][:, cols].astype(np.int64)
489
+ gm = rng.binomial(gm, thin_g) if thin_g < 1 else gm
490
+ hg = call_state(gm, st, npos, req, exc) & pg
491
+ if sc == "V0_reseed":
492
+ calls_v0[a, sname] = (ht, hg)
493
+ op, gp = bc(do, po), bc(G[a]["d"], pg)
494
+ os_, gs = bc(do, ht), bc(G[a]["d"], hg)
495
+ with np.errstate(divide="ignore", invalid="ignore"):
496
+ Asch[sc][a, sname] = {"gen_state": gs, "gen_parent": gp, "obsthin_state": os_, "obs_parent": op,
497
+ "obs_state": A[a, sname]["obs_state"],
498
+ "gen_pct": np.where(gp > 0, 100 * gs / gp, np.nan),
499
+ "obsthin_pct": np.where(op > 0, 100 * os_ / op, np.nan)}
500
+ depth_rows.append({"scheme": sc, "state": sname, "arm": a, "obs_thin": thin_o, "gen_thin": thin_g,
501
+ "depth_matched": bool(sc == "V0_reseed" or a in pool or e[a][k] >= target),
502
+ "obs_lib_median": e["OBS"][0], "gen_lib_median": e[a][0],
503
+ "obs_msum": e["OBS"][1], "gen_msum": e[a][1], "n_ref_genes": nref,
504
+ "msum_over_lib_ratio": (e[a][1] / e["OBS"][1]) / (e[a][0] / e["OBS"][0]),
505
+ "ratio_raw": raw_ratio(Asch[sc][a, sname]),
506
+ "ratio_screen": float(Sx.loc[(a, sname)].gen_over_obs)})
507
+ DR = pd.DataFrame(depth_rows)
508
+ write(DR, "depth_arms")
509
+ dep = []
510
+ for sc in schemes:
511
+ comps = MAIN + (REFC if sc in ("V0_reseed", "V1_lib_all", "V2_msum_all") else [])
512
+ Rd, _, _ = comparison_rows(Asch[sc], states, rare, comps, IDX, sc)
513
+ dep.append(Rd)
514
+ DEP = pd.concat([R[R.comparison.isin([c[0] for c in MAIN + REFC])][list(dep[0].columns)]] + dep,
515
+ ignore_index=True)
516
+ write(DEP, "depth")
517
+ for sc in ["V0_published"] + schemes:
518
+ t = DEP[(DEP.scheme == sc) & DEP.comparison.isin([c[0] for c in MAIN]) & DEP.state.isin(rare)]
519
+ a_ = DEP[(DEP.scheme == sc) & (DEP.state == "AGGREGATE")]
520
+ log(sc, "main state verdicts:", t.verdict.value_counts().to_dict(), "| aggregate:",
521
+ [(r.comparison[:22], round(r.D, 3), round(r.D_ci_lo, 3), round(r.D_ci_hi, 3)) for r in a_.itertuples()])
522
+
523
+ # ===================================================================================== 6. composition
524
+ strata_def = {}
525
+ for st in st_json:
526
+ p = st["parent"]
527
+ strata_def[st["name"]] = "l2"
528
+ if p == ["ALL"] or st["kind"] == "label": # a label state cannot be standardised on its own L2 label
529
+ strata_def[st["name"]] = "l1"
530
+ comp_rows, comp_cmp = [], []
531
+ lab_l2o = lab_o.aifi_l2.to_numpy(str)
532
+ lab_l1o = lab_o.aifi_l1.to_numpy(str)
533
+ CS = {}
534
+ for st in st_json:
535
+ sname = st["name"]
536
+ po = parent_mask(lab_o, st["parent"])
537
+ for level in (["l2", "l1"] if sname == "Cycling T/NK" else [strata_def[sname]]):
538
+ so = (lab_l2o if level == "l2" else lab_l1o)
539
+ strata = sorted(set(so[po]))
540
+ K = len(strata)
541
+ sidx = {s_: i for i, s_ in enumerate(strata)}
542
+ for a in ARMS:
543
+ if st["kind"] == "label":
544
+ ht = lab_o.aifi_l2.isin(st["labels"]).to_numpy() & po
545
+ pg = parent_mask(G[a]["lab"], st["parent"])
546
+ hg = G[a]["lab"].aifi_l2.isin(st["labels"]).to_numpy() & pg
547
+ else:
548
+ ht, hg = calls_v0[a, sname]
549
+ pg = parent_mask(G[a]["lab"], st["parent"])
550
+ sg = G[a]["lab"].aifi_l2.to_numpy(str) if level == "l2" else G[a]["lab"].aifi_l1.to_numpy(str)
551
+ # per donor x stratum tables
552
+ ko = np.array([sidx.get(v, -1) for v in so])
553
+ kg = np.array([sidx.get(v, -1) for v in sg])
554
+ def tab(codes, kk, mask):
555
+ m_ = mask & (kk >= 0)
556
+ return np.bincount(codes[m_] * K + kk[m_], minlength=n * K).reshape(n, K).astype(float)
557
+ OP, OS = tab(do, ko, po), tab(do, ko, ht)
558
+ GP, GS = tab(G[a]["d"], kg, pg), tab(G[a]["d"], kg, hg)
559
+ extra_gen = int((pg & (kg < 0)).sum()) # generated parent cells in strata absent from observed
560
+ CS[a, sname, level] = (OP, OS, GP, GS)
561
+
562
+ def std(OP, OS, GP, GS):
563
+ op, os_, gp, gs = OP.sum(0), OS.sum(0), GP.sum(0), GS.sum(0)
564
+ w = op / op.sum()
565
+ keep = gp > 0
566
+ with np.errstate(divide="ignore", invalid="ignore"):
567
+ rg = np.where(keep, gs / np.where(gp > 0, gp, 1), np.nan)
568
+ ro = os_ / np.where(op > 0, op, 1)
569
+ Rstd = np.nansum(w[keep] * rg[keep]) / w[keep].sum()
570
+ Ro = np.sum(w[keep] * ro[keep]) / w[keep].sum()
571
+ raw = (gs.sum() / gp.sum()) / (os_.sum() / op.sum())
572
+ wg = gp / gp.sum()
573
+ comp_only = np.sum(wg * ro) / (os_.sum() / op.sum())
574
+ return Rstd / Ro, raw, comp_only, 1 - w[keep].sum()
575
+ sr, rr, co_, dropped = std(OP, OS, GP, GS)
576
+ gpk = GP.sum(0)
577
+ top = np.argsort(-GS.sum(0))[:3]
578
+ comp_rows.append({"state": sname, "strata": level, "arm": a, "ratio_raw_v0reseed": rr,
579
+ "ratio_composition_standardised": sr, "composition_only_factor": co_,
580
+ "obs_weight_dropped": dropped, "gen_parent_outside_obs_strata": extra_gen,
581
+ "top_gen_state_strata": "; ".join(f"{strata[i]}:{int(GS.sum(0)[i])}/{int(gpk[i])}"
582
+ for i in top if GS.sum(0)[i] > 0),
583
+ "obs_top_state_strata": "; ".join(
584
+ f"{strata[i]}:{int(OS.sum(0)[i])}/{int(OP.sum(0)[i])}"
585
+ for i in np.argsort(-OS.sum(0))[:3] if OS.sum(0)[i] > 0)})
586
+ # comparisons on the standardised ratio, bootstrap over donors
587
+ for level in (["l2", "l1"] if sname == "Cycling T/NK" else [strata_def[sname]]):
588
+ for name, sa, pa in MAIN + REFC:
589
+ vals = {}
590
+ for a in (sa, pa):
591
+ OP, OS, GP, GS = CS[a, sname, level]
592
+
593
+ def stdb(idx=None):
594
+ if idx is None:
595
+ op, os_, gp, gs = OP.sum(0), OS.sum(0), GP.sum(0), GS.sum(0)
596
+ op, os_, gp, gs = op[None], os_[None], gp[None], gs[None]
597
+ else:
598
+ op, os_, gp, gs = OP[idx].sum(1), OS[idx].sum(1), GP[idx].sum(1), GS[idx].sum(1)
599
+ w = op / op.sum(1, keepdims=True)
600
+ keep = gp > 0
601
+ with np.errstate(divide="ignore", invalid="ignore"):
602
+ rg = np.where(keep, (gs + PC / gs.shape[1]) / np.where(gp > 0, gp, 1), 0.0)
603
+ ro = (os_ + PC / os_.shape[1]) / np.where(op > 0, op, 1)
604
+ wk = np.where(keep, w, 0.0)
605
+ v = np.log2((wk * rg).sum(1) / (wk * ro).sum(1))
606
+ return np.where(np.isfinite(v), v, np.nan)
607
+ vals[a] = (float(stdb()[0]), stdb(IDX))
608
+ d0 = abs(vals[sa][0]) - abs(vals[pa][0])
609
+ db = np.abs(vals[sa][1]) - np.abs(vals[pa][1])
610
+ lo, hi = pci(db)
611
+ blo, bhi = bc_ci(db, d0)
612
+ comp_cmp.append({"state": sname, "strata": level, "comparison": name,
613
+ "std_ratio_scratch": 2 ** vals[sa][0], "std_ratio_pretrained": 2 ** vals[pa][0],
614
+ "D_std": d0, "D_std_ci_lo": lo, "D_std_ci_hi": hi, "verdict_std": verdict(lo, hi),
615
+ "verdict_std_bc": verdict(blo, bhi),
616
+ "D_published": full[(name, sname)].D, "verdict_published": full[(name, sname)].verdict})
617
+ # aggregate over the 13 rare states on the standardised ratio (default strata; Cycling T/NK on L2)
618
+ std_l2 = {}
619
+ for a in ARMS:
620
+ for s in states:
621
+ level = strata_def[s]
622
+ OP, OS, GP, GS = CS[a, s, level]
623
+
624
+ def stdv(idx=None):
625
+ if idx is None:
626
+ op, os_, gp, gs = OP.sum(0)[None], OS.sum(0)[None], GP.sum(0)[None], GS.sum(0)[None]
627
+ else:
628
+ op, os_, gp, gs = OP[idx].sum(1), OS[idx].sum(1), GP[idx].sum(1), GS[idx].sum(1)
629
+ w = op / op.sum(1, keepdims=True)
630
+ keep = gp > 0
631
+ with np.errstate(divide="ignore", invalid="ignore"):
632
+ rg = np.where(keep, (gs + PC / gs.shape[1]) / np.where(gp > 0, gp, 1), 0.0)
633
+ ro = (os_ + PC / os_.shape[1]) / np.where(op > 0, op, 1)
634
+ wk = np.where(keep, w, 0.0)
635
+ v = np.log2((wk * rg).sum(1) / (wk * ro).sum(1))
636
+ return np.where(np.isfinite(v), v, np.nan)
637
+ std_l2[a, s] = (float(stdv()[0]), stdv(IDX))
638
+ for name, sa, pa in MAIN + REFC:
639
+ d0 = float(np.mean([abs(std_l2[sa, s][0]) - abs(std_l2[pa, s][0]) for s in rare]))
640
+ db = np.mean(np.vstack([np.abs(std_l2[sa, s][1]) - np.abs(std_l2[pa, s][1]) for s in rare]), axis=0)
641
+ lo, hi = pci(db)
642
+ blo, bhi = bc_ci(db, d0)
643
+ nv = {"pretrained closer": 0, "scratch closer": 0, "not significant": 0}
644
+ for s in rare:
645
+ l_, h_ = pci(np.abs(std_l2[sa, s][1]) - np.abs(std_l2[pa, s][1]))
646
+ nv[verdict(l_, h_)] = nv.get(verdict(l_, h_), 0) + 1
647
+ comp_cmp.append({"state": "AGGREGATE (13 rare, standardised)", "strata": "default", "comparison": name,
648
+ "std_ratio_scratch": float(np.mean([abs(std_l2[sa, s][0]) for s in rare])),
649
+ "std_ratio_pretrained": float(np.mean([abs(std_l2[pa, s][0]) for s in rare])),
650
+ "D_std": d0, "D_std_ci_lo": lo, "D_std_ci_hi": hi, "verdict_std": verdict(lo, hi),
651
+ "verdict_std_bc": verdict(blo, bhi), "D_published": full[(name, 'AGGREGATE')].D,
652
+ "verdict_published": full[(name, 'AGGREGATE')].verdict,
653
+ "n_states_pretrained_closer": nv["pretrained closer"],
654
+ "n_states_scratch_closer": nv["scratch closer"],
655
+ "n_states_not_significant": nv["not significant"]})
656
+ write(pd.DataFrame(comp_rows), "composition_arms")
657
+ write(pd.DataFrame(comp_cmp), "composition")
658
+ log("composition aggregate:\n" + pd.DataFrame(comp_cmp[-len(MAIN + REFC):])[
659
+ ["comparison", "std_ratio_scratch", "std_ratio_pretrained", "D_std", "D_std_ci_lo", "D_std_ci_hi",
660
+ "verdict_std", "verdict_std_bc", "n_states_pretrained_closer", "n_states_scratch_closer"]].round(3).to_string())
661
+
662
+ # arm-level mean |log2 r_pc| over the 13 rare states under every scheme (is zero-shot still the least faithful?)
663
+ am = []
664
+ for sc, AA in [("V0_published", A)] + [(k, Asch[k]) for k in schemes] + [("composition_std", None)]:
665
+ for a in ARMS:
666
+ if AA is None:
667
+ v = [abs(std_l2[a, s][0]) for s in rare]
668
+ else:
669
+ v = [abs(float(l2r(AA[a, s]))) for s in rare]
670
+ am.append({"scheme": sc, "arm": a, "mean_abs_log2_13_rare": float(np.mean(v)),
671
+ "depth_matched_in_scheme": bool(sc in ("V0_published", "V0_reseed", "composition_std")
672
+ or sc.endswith("_all") or a != "zs__raw")})
673
+ # state-set sensitivity (13 rare vs 11 marker-only vs T/NK states) under every scheme
674
+ sets = {"13 rare": rare, "11 marker states (no label states)": [s for s in rare if s not in LABEL_STATES],
675
+ "T/NK states (5)": ["Cycling T/NK", "Cycling activated T (CD38/HLA-DR)", "Proliferating T (label)",
676
+ "ISG-high T", "Cytotoxic CD4 T"]}
677
+ sbs = []
678
+ for sc in ["V0_published"] + schemes + ["composition_std"]:
679
+ for name, sa, pa in MAIN + REFC:
680
+ for lab, ss in sets.items():
681
+ if sc == "composition_std":
682
+ vs = {(a, s): std_l2[a, s] for a in (sa, pa) for s in ss}
683
+ else:
684
+ AA = A if sc == "V0_published" else Asch[sc]
685
+ vs = {(a, s): (float(l2r(AA[a, s])), l2r(AA[a, s], idx=IDX)) for a in (sa, pa) for s in ss}
686
+ d0 = float(np.mean([abs(vs[sa, s][0]) - abs(vs[pa, s][0]) for s in ss]))
687
+ db = np.mean(np.vstack([np.abs(vs[sa, s][1]) - np.abs(vs[pa, s][1]) for s in ss]), axis=0)
688
+ lo, hi = pci(db)
689
+ blo, bhi = bc_ci(db, d0)
690
+ sbs.append({"scheme": sc, "comparison": name, "state_set": lab, "D": d0, "D_ci_lo": lo,
691
+ "D_ci_hi": hi, "verdict": verdict(lo, hi), "D_bc_ci_lo": blo, "D_bc_ci_hi": bhi,
692
+ "verdict_bc": verdict(blo, bhi)})
693
+ SBS = pd.DataFrame(sbs)
694
+ write(SBS, "stateset_by_scheme")
695
+ log("state-set x scheme (main comparisons):\n" + SBS[SBS.comparison.isin([c[0] for c in MAIN])].assign(
696
+ cell=lambda d: d.apply(lambda r: f"{r.D:+.3f}[{r.D_ci_lo:+.2f},{r.D_ci_hi:+.2f}]"
697
+ f"{'*' if r.verdict != 'not significant' else ''}"
698
+ f"{'b' if r.verdict_bc != 'not significant' else ''}", axis=1)).pivot_table(
699
+ index=["state_set", "comparison"], columns="scheme", values="cell", aggfunc="first").to_string())
700
+ AM = pd.DataFrame(am)
701
+ AM["rank_worst_first"] = AM.groupby("scheme").mean_abs_log2_13_rare.rank(ascending=False).astype(int)
702
+ write(AM, "arm_mean_abslog2")
703
+ log("arm mean |log2| by scheme:\n" + AM.pivot(index="arm", columns="scheme",
704
+ values="mean_abs_log2_13_rare").round(3).to_string())
705
+
706
+ # ===================================================================================== 7. label vs marker CIs
707
+ cyc_cols = [sym2col[g] for g in CYC]
708
+ thin_T = {a: float(Sx.loc[(a, "ISG-high T")].thin) for a in ARMS}
709
+ rng = np.random.default_rng(SEED)
710
+ lab_rows, lab_cnt = [], {}
711
+ To = (lab_o.aifi_l1.to_numpy(str) == "T cell") | (lab_o.aifi_l2.to_numpy(str) == "T cell")
712
+ PTo = To & (lab_o.aifi_l2.to_numpy(str) == "Proliferating T cell")
713
+ for a in ARMS:
714
+ l1 = G[a]["lab"].aifi_l1.to_numpy(str)
715
+ l2 = G[a]["lab"].aifi_l2.to_numpy(str)
716
+ T = (l1 == "T cell") | (l2 == "T cell")
717
+ PT = T & (l2 == "Proliferating T cell")
718
+ cyc = (G[a]["M"][:, cyc_cols] > 0).sum(1) >= 2
719
+ d = G[a]["d"]
720
+ mo = Mo[:, cyc_cols].astype(np.int64)
721
+ mt = rng.binomial(mo, thin_T[a]) if thin_T[a] < 1 else mo
722
+ cyco = (mt > 0).sum(1) >= 2
723
+ lab_cnt[a] = {"gen": {"T": bc(d, T), "PT": bc(d, PT), "PTpass": bc(d, PT & cyc), "cycT": bc(d, cyc & T),
724
+ "nonPT": bc(d, T & ~PT), "nonPTpass": bc(d, T & ~PT & cyc)},
725
+ "obs": {"T": bc(do, To), "PT": bc(do, PTo), "PTpass": bc(do, PTo & cyco),
726
+ "cycT": bc(do, cyco & To), "nonPT": bc(do, To & ~PTo),
727
+ "nonPTpass": bc(do, To & ~PTo & cyco)}}
728
+ def rates(c, idx=None):
729
+ f = (lambda v: v.sum()) if idx is None else (lambda v: v[idx].sum(-1))
730
+ with np.errstate(divide="ignore", invalid="ignore"):
731
+ return {"pass_PT": 100 * f(c["PTpass"]) / f(c["PT"]), "PT_of_T": 100 * f(c["PT"]) / f(c["T"]),
732
+ "cyc_of_T": 100 * f(c["cycT"]) / f(c["T"]), "pass_nonPT": 100 * f(c["nonPTpass"]) / f(c["nonPT"]),
733
+ "share_cyc_in_PT": 100 * f(c["PTpass"]) / f(c["cycT"])}
734
+ for a in ARMS:
735
+ rg, ro = rates(lab_cnt[a]["gen"]), rates(lab_cnt[a]["obs"])
736
+ rgb, rob = rates(lab_cnt[a]["gen"], IDX), rates(lab_cnt[a]["obs"], IDX)
737
+ row = {"arm": a, "obs_thin_T": thin_T[a], "gen_PT_cells": lab_cnt[a]["gen"]["PT"].sum(),
738
+ "gen_PTpass_cells": lab_cnt[a]["gen"]["PTpass"].sum(),
739
+ "gen_cycling_T_cells": lab_cnt[a]["gen"]["cycT"].sum()}
740
+ for k in rg:
741
+ lo, hi = pci(rgb[k])
742
+ row.update({f"gen_{k}": rg[k], f"gen_{k}_ci_lo": lo, f"gen_{k}_ci_hi": hi, f"obs_{k}": ro[k]})
743
+ row["gen_over_obs_PT_of_T"] = rg["PT_of_T"] / ro["PT_of_T"]
744
+ row["gen_over_obs_pass_PT"] = rg["pass_PT"] / ro["pass_PT"]
745
+ row["gen_over_obs_cyc_of_T"] = rg["cyc_of_T"] / ro["cyc_of_T"]
746
+ lab_rows.append(row)
747
+ for name, sa, pa in MAIN:
748
+ rsb, rpb = rates(lab_cnt[sa]["gen"], IDX), rates(lab_cnt[pa]["gen"], IDX)
749
+ rs, rp = rates(lab_cnt[sa]["gen"]), rates(lab_cnt[pa]["gen"])
750
+ row = {"arm": f"DIFF pretrained - scratch | {name}"}
751
+ for k in ["pass_PT", "PT_of_T", "cyc_of_T", "share_cyc_in_PT"]:
752
+ lo, hi = pci(rpb[k] - rsb[k])
753
+ row.update({f"diff_{k}": rp[k] - rs[k], f"diff_{k}_ci_lo": lo, f"diff_{k}_ci_hi": hi})
754
+ lab_rows.append(row)
755
+ write(pd.DataFrame(lab_rows), "labelcheck")
756
+
757
+ # ===================================================================================== 8. contrasts
758
+ CONTR = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
759
+ ("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
760
+ ("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
761
+ ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
762
+
763
+ def contrast(x, keep_mask):
764
+ out = {}
765
+ for cname, ga, gb in CONTR:
766
+ ma = np.isin(groups, ga) & keep_mask
767
+ mb = np.isin(groups, gb) & keep_mask
768
+ if ma.sum() == 0 or mb.sum() == 0:
769
+ out[cname] = (np.nan, np.nan, np.nan)
770
+ continue
771
+ od = np.nanmean(x["obsthin_pct"][ma]) - np.nanmean(x["obsthin_pct"][mb])
772
+ gd = np.nanmean(x["gen_pct"][ma]) - np.nanmean(x["gen_pct"][mb])
773
+ lvl = np.nanmean([np.nanmean(x["gen_pct"][ma]), np.nanmean(x["gen_pct"][mb])])
774
+ out[cname] = (od, gd, lvl)
775
+ return out
776
+ allm = np.ones(n, bool)
777
+ CF = {(a, s): contrast(A[a, s], allm) for a in ARMS for s in states}
778
+ # eligibility exactly as the claim: rare, min over trained arms |obs_diff| >= 0.5 with one sign
779
+ elig = []
780
+ for s in rare:
781
+ for cname, _, _ in CONTR:
782
+ od = np.array([CF[a, s][cname][0] for a in TRAINED])
783
+ if np.all(np.isfinite(od)) and np.abs(od).min() >= 0.5 and len(set(np.sign(od))) == 1:
784
+ elig.append((s, cname))
785
+ log("eligible (state, contrast) pairs:", len(elig))
786
+ crow = []
787
+ status = {}
788
+ for a in ARMS:
789
+ for s, cname in elig:
790
+ od, gd, lvl = CF[a, s][cname]
791
+ st_ = "kept" if np.sign(gd) == np.sign(od) else ("flat" if gd == 0 or not np.isfinite(gd) else "reversed")
792
+ strength = "" if st_ != "reversed" else ("strong" if abs(gd) >= 0.5 else "weak")
793
+ rel = abs(gd) / lvl if lvl and np.isfinite(lvl) and lvl > 0 else np.nan
794
+ strength_rel = "" if st_ != "reversed" else ("strong" if rel >= 0.5 else "weak")
795
+ status[a, s, cname] = st_
796
+ crow.append({"arm": a, "state": s, "contrast": cname, "obs_diff": od, "gen_diff": gd,
797
+ "gen_level_mean_pct": lvl, "rel_gen_diff": rel, "status": st_,
798
+ "reversal_strength_abs_0.5pp": strength, "reversal_strength_rel_0.5": strength_rel})
799
+ CR = pd.DataFrame(crow)
800
+ # LODO
801
+ lodo_c = []
802
+ for j in range(n):
803
+ km = allm.copy()
804
+ km[j] = False
805
+ for a in ARMS:
806
+ kept = undefined = obs_flip = 0
807
+ for s, cname in elig:
808
+ od, gd, _ = contrast(A[a, s], km)[cname]
809
+ od_full = CF[a, s][cname][0]
810
+ if not np.isfinite(od) or not np.isfinite(gd):
811
+ undefined += 1
812
+ continue
813
+ obs_flip += int(np.sign(od) != np.sign(od_full))
814
+ kept += int(np.sign(gd) == np.sign(od))
815
+ lodo_c.append({"left_out": donors[j], "group": groups[j], "arm": a, "kept": kept,
816
+ "undefined": undefined, "obs_direction_flips": obs_flip})
817
+ LC = pd.DataFrame(lodo_c)
818
+ summ = []
819
+ for a in ARMS:
820
+ t = CR[CR.arm == a]
821
+ lc = LC[LC.arm == a]
822
+ summ.append({"arm": a, "n_eligible": len(t), "kept": int((t.status == "kept").sum()),
823
+ "reversed_strong_abs": int((t["reversal_strength_abs_0.5pp"] == "strong").sum()),
824
+ "reversed_weak_abs": int((t["reversal_strength_abs_0.5pp"] == "weak").sum()),
825
+ "flat": int((t.status == "flat").sum()),
826
+ "reversed_strong_rel": int((t["reversal_strength_rel_0.5"] == "strong").sum()),
827
+ "reversed_weak_rel": int((t["reversal_strength_rel_0.5"] == "weak").sum()),
828
+ "kept_lodo_min": int(lc.kept.min()), "kept_lodo_max": int(lc.kept.max()),
829
+ "kept_by_contrast": "; ".join(f"{c}:{int(((t.contrast == c) & (t.status == 'kept')).sum())}/"
830
+ f"{int((t.contrast == c).sum())}" for c, _, _ in CONTR)})
831
+ for name, sa, pa in MAIN + REFC:
832
+ b = sum(status[pa, s, c] == "kept" and status[sa, s, c] != "kept" for s, c in elig)
833
+ c_ = sum(status[sa, s, c] == "kept" and status[pa, s, c] != "kept" for s, c in elig)
834
+ p = binomtest(b, b + c_, 0.5).pvalue if b + c_ > 0 else np.nan
835
+ dl = (LC[LC.arm == pa].set_index("left_out").kept - LC[LC.arm == sa].set_index("left_out").kept)
836
+ summ.append({"arm": f"PAIR {name}", "n_eligible": len(elig),
837
+ "kept_diff_pretrained_minus_scratch": sum(status[pa, s, c] == "kept" for s, c in elig)
838
+ - sum(status[sa, s, c] == "kept" for s, c in elig),
839
+ "discordant_pretrained_only_kept": b, "discordant_scratch_only_kept": c_,
840
+ "exact_sign_test_p": p, "kept_diff_lodo_min": int(dl.min()), "kept_diff_lodo_max": int(dl.max())})
841
+ obs_fragile = LC[LC.arm == TRAINED[0]][["left_out", "group", "obs_direction_flips", "undefined"]]
842
+ write(pd.concat([CR.assign(section="pair"), pd.DataFrame(summ).assign(section="summary"),
843
+ LC.assign(section="lodo")], ignore_index=True), "contrasts")
844
+ log("contrast summary:\n" + pd.DataFrame(summ).to_string(index=False))
845
+ log("observed-direction flips per left-out donor (arm lora_n5):\n" + obs_fragile.to_string(index=False))
846
+
847
+ # ===================================================================================== 9. Spearman
848
+ sp_rows = []
849
+ R0, RB = {}, {}
850
+ for a in ARMS:
851
+ for s in states:
852
+ g, o = A[a, s]["gen_pct"], A[a, s]["obsthin_pct"]
853
+ R0[a, s] = spearman(g, o)
854
+ RB[a, s] = spearman_rows(g[IDX], o[IDX])
855
+ rng = np.random.default_rng(SEED)
856
+ ceil = {}
857
+ for a in ARMS:
858
+ for s in states:
859
+ x = A[a, s]
860
+ c = raw_ratio(x)
861
+ p = np.clip(np.nan_to_num(x["obsthin_pct"]) / 100 * (c if np.isfinite(c) else 1.0), 0, 1)
862
+ sims = []
863
+ for _ in range(500):
864
+ gs = rng.binomial(x["gen_parent"].astype(np.int64), p)
865
+ with np.errstate(divide="ignore", invalid="ignore"):
866
+ gp = np.where(x["gen_parent"] > 0, 100 * gs / x["gen_parent"], np.nan)
867
+ sims.append(spearman(gp, x["obsthin_pct"]))
868
+ sims = np.array(sims, float)
869
+ ceil[a, s] = (np.nanmean(sims), *pci(sims), np.nanstd(sims))
870
+ sep = sepsis & np.isfinite(x["gen_pct"]) & np.isfinite(x["obsthin_pct"])
871
+ sp_rows.append({"arm": a, "state": s, "spearman": R0[a, s], "ceiling_mean": ceil[a, s][0],
872
+ "ceiling_ci_lo": ceil[a, s][1], "ceiling_ci_hi": ceil[a, s][2],
873
+ "ceiling_sd": ceil[a, s][3],
874
+ "spearman_over_ceiling": R0[a, s] / ceil[a, s][0] if ceil[a, s][0] else np.nan,
875
+ "spearman_within_sepsis_only": spearman(x["gen_pct"][sep], x["obsthin_pct"][sep]),
876
+ "median_gen_state_cells_per_donor": float(np.median(x["gen_state"]))})
877
+ for name, sa, pa in MAIN:
878
+ d0 = float(np.mean([R0[pa, s] - R0[sa, s] for s in rare]))
879
+ db = np.nanmean(np.vstack([RB[pa, s] - RB[sa, s] for s in rare]), axis=0)
880
+ lo, hi = pci(db)
881
+ lo90, hi90 = np.percentile(db[np.isfinite(db)], [5, 95])
882
+ cs, cp = np.mean([ceil[sa, s][0] for s in rare]), np.mean([ceil[pa, s][0] for s in rare])
883
+ sep_s = np.nanmean([r["spearman_within_sepsis_only"] for r in sp_rows if r["arm"] == sa and r["state"] in rare])
884
+ sep_p = np.nanmean([r["spearman_within_sepsis_only"] for r in sp_rows if r["arm"] == pa and r["state"] in rare])
885
+ nsig = 0
886
+ npos = 0
887
+ for s in rare:
888
+ l_, h_ = pci(RB[pa, s] - RB[sa, s])
889
+ nsig += int(l_ > 0 or h_ < 0)
890
+ npos += int(R0[pa, s] - R0[sa, s] > 0)
891
+ sp_rows.append({"arm": f"DIFF pretrained - scratch | {name}", "state": "MEAN over 13 rare",
892
+ "spearman": d0, "ceiling_mean": cp - cs, "diff_ci_lo": lo, "diff_ci_hi": hi,
893
+ "diff_ci90_lo": lo90, "diff_ci90_hi": hi90, "mean_spearman_scratch": np.mean([R0[sa, s] for s in rare]),
894
+ "mean_spearman_pretrained": np.mean([R0[pa, s] for s in rare]),
895
+ "mean_ceiling_scratch": cs, "mean_ceiling_pretrained": cp,
896
+ "mean_within_sepsis_scratch": sep_s, "mean_within_sepsis_pretrained": sep_p,
897
+ "n_states_sig": nsig, "n_states_pretrained_higher": npos})
898
+ write(pd.DataFrame(sp_rows), "spearman")
899
+
900
+ # ===================================================================================== 10. folds / LoRA series
901
+ PP = pd.read_csv(SRC / "sepsis_per_donor.csv")
902
+ folds = pd.read_csv(FOLDS).set_index("sample_id").fold
903
+ PP["fold"] = PP.donor.map(folds)
904
+ fr = []
905
+ for (a, f), t in PP.groupby(["arm", "fold"]):
906
+ if f < 0:
907
+ continue
908
+ absl_ = []
909
+ for s in states:
910
+ u = t[t.state == s]
911
+ x = {k: u[k].to_numpy(float) for k in ["gen_state", "gen_parent", "obsthin_state", "obs_parent"]}
912
+ v = float(l2r(x))
913
+ if s in rare:
914
+ absl_.append(abs(v))
915
+ fr.append({"source": "pooled cross-fitted CSV", "arm": a, "fold": int(f), "state": s,
916
+ "n_donors": len(u), "ratio_raw": raw_ratio(x), "log2_pc": v})
917
+ fr.append({"source": "pooled cross-fitted CSV", "arm": a, "fold": int(f),
918
+ "state": "MEAN |log2| over 13 rare", "log2_pc": float(np.mean(absl_))})
919
+ for (s, f), t in PP[PP.arm == "real_lora__raw"].groupby(["state", "fold"]):
920
+ if f < 0:
921
+ continue
922
+ fr.append({"source": "pooled cross-fitted CSV, observed side", "arm": "observed (thinned to real_lora)",
923
+ "fold": int(f), "state": s, "n_donors": len(t), "obsthin_state": int(t.obsthin_state.sum()),
924
+ "obs_parent": int(t.obs_parent.sum()),
925
+ "obs_top_donor_share": float(t.obsthin_state.max() / t.obsthin_state.sum())
926
+ if t.obsthin_state.sum() else np.nan})
927
+ for a in ARMS:
928
+ fr.append({"source": "fold0 CSV", "arm": a, "fold": 0, "state": "MEAN |log2| over 13 rare",
929
+ "log2_pc": float(np.mean([abs(L0.get((a, s), float(l2r(A[a, s])))) for s in rare]))})
930
+ for s in states:
931
+ fr.append({"source": "fold0 CSV", "arm": a, "fold": 0, "state": s, "n_donors": n,
932
+ "ratio_raw": raw_ratio(A[a, s]), "log2_pc": float(l2r(A[a, s]))})
933
+ FR = pd.DataFrame(fr)
934
+ # substitution: scratch arm vs LoRA arms of other pair counts on fold-0 donors (each with its own reference)
935
+ sub_rows = []
936
+ d0f = PP[PP.fold == 0]
937
+ for la in ["lora_n5__raw", "lora_n10__raw", "lora_n20__raw", "lora_n40__raw", "real_lora__raw"]:
938
+ Lx = {}
939
+ for s in states:
940
+ u = d0f[(d0f.arm == la) & (d0f.state == s)].set_index("donor").loc[donors]
941
+ Lx[s] = {k: u[k].to_numpy(float) for k in ["gen_state", "gen_parent", "obsthin_state", "obs_parent"]}
942
+ for sa in ["scratch_n5__raw", "scratch_full__raw", "scratch_recipe__raw"]:
943
+ ds, dbs = [], []
944
+ for s in states:
945
+ ls_, lp_ = float(l2r(A[sa, s])), float(l2r(Lx[s]))
946
+ d = abs(ls_) - abs(lp_)
947
+ db = np.abs(l2r(A[sa, s], idx=IDX)) - np.abs(l2r(Lx[s], idx=IDX))
948
+ lo, hi = pci(db)
949
+ sub_rows.append({"scratch_arm": sa, "lora_arm_pooled_csv": la, "state": s,
950
+ "ratio_scratch": raw_ratio(A[sa, s]), "ratio_lora": raw_ratio(Lx[s]),
951
+ "D": d, "D_ci_lo": lo, "D_ci_hi": hi, "verdict": verdict(lo, hi)})
952
+ if s in rare:
953
+ ds.append(d)
954
+ dbs.append(db)
955
+ db = np.mean(np.vstack(dbs), axis=0)
956
+ lo, hi = pci(db)
957
+ sub_rows.append({"scratch_arm": sa, "lora_arm_pooled_csv": la, "state": "AGGREGATE",
958
+ "D": float(np.mean(ds)), "D_ci_lo": lo, "D_ci_hi": hi, "verdict": verdict(lo, hi)})
959
+ write(pd.concat([FR.assign(section="per fold"), pd.DataFrame(sub_rows).assign(section="lora substitution")],
960
+ ignore_index=True), "folds")
961
+ log("done")
962
+
963
+
964
+ if __name__ == "__main__":
965
+ main()