Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_cross_extra_script.py +154 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_cross_obsdepth_script.py +137 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_cross_script.py +555 -0
- paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_donorweight.py +70 -0
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_cross_extra_script.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Extra adversarial checks for cross-4 and cross-7 (CPU only, 2026-10-05; verifier-written, independent of the analyst).
|
| 3 |
+
|
| 4 |
+
cross-7: is the "kept effects 3-4x more compressed" result a selection effect of comparing medians over different kept
|
| 5 |
+
sets? (a) same-pair comparison: medians of gen_diff/obs_diff over the common pairs kept by BOTH arms;
|
| 6 |
+
(b) donor bootstrap (seed 20261005, 2000 x 82, the shared idx) of the ratio comparator-median / scratch-median
|
| 7 |
+
over each arm's own kept set, and of the same-pair version; scratch at its own and at the r16 depth.
|
| 8 |
+
cross-4: range of the depth-correction factor (scratch ratio at a pretrained arm's depth / own) over all four
|
| 9 |
+
pretrained references and all marker states.
|
| 10 |
+
Inputs: out/sepsis_loco_per_donor.csv, verify_recompute_cross_contrasts.csv (the verifier's own common-set flags) and
|
| 11 |
+
verify_recompute_cross_ratios.csv. Outputs: verify_recompute_cross_extra_*.csv / _report.txt.
|
| 12 |
+
"""
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pandas as pd
|
| 20 |
+
|
| 21 |
+
sys.dont_write_bytecode = True
|
| 22 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 23 |
+
OUT = PLAN / "out"
|
| 24 |
+
DST = OUT / "scratch_vs_lora_20261005"
|
| 25 |
+
PFX = "verify_recompute_cross_extra_"
|
| 26 |
+
SEED, B = 20261005, 2000
|
| 27 |
+
SH = {"zs__raw": "zs", "xcalL_K1000": "xcal", "locoL_lora16sat_s26750_K1000": "r16",
|
| 28 |
+
"locoL_lora64sat_s59000_K1000": "r64", "locoL_fullsat_s20000_K1000": "full20k",
|
| 29 |
+
"locoL_fullsat_s108500_K1000": "full108k", "locoL_scratchsat_s50000_K1000": "s50k",
|
| 30 |
+
"locoL_scratchsat_s100000_K1000": "s100k", "locoL_scratchsat_s150000_K1000": "s150k",
|
| 31 |
+
"locoL_scratchsat_s162000_K1000": "s162k", "lora_n5__raw": "own5", "real_lora__raw": "own58"}
|
| 32 |
+
INV = {v: k for k, v in SH.items()}
|
| 33 |
+
CONTRASTS = {"adult": (["adult_sepsis"], ["adult_HC"]), "paediatric": (["ped_sepsis"], ["ped_HC"]),
|
| 34 |
+
"all": (["adult_sepsis", "ped_sepsis"], ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])}
|
| 35 |
+
LOG: list[str] = []
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def say(*a) -> None:
|
| 39 |
+
s = " ".join(str(x) for x in a)
|
| 40 |
+
print(s)
|
| 41 |
+
LOG.append(s)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
P = pd.read_csv(OUT / "sepsis_loco_per_donor.csv")
|
| 45 |
+
DONORS = sorted(P.donor.unique())
|
| 46 |
+
N = len(DONORS)
|
| 47 |
+
GROUP = P.drop_duplicates("donor").set_index("donor").group.reindex(DONORS).to_numpy()
|
| 48 |
+
IDX = np.random.default_rng(SEED).integers(0, N, (B, N))
|
| 49 |
+
CT = pd.read_csv(DST / "verify_recompute_cross_contrasts.csv")
|
| 50 |
+
COMMON = sorted({(s, c) for s, c in zip(CT[CT.common].state, CT[CT.common].contrast)})
|
| 51 |
+
assert len(COMMON) == 21
|
| 52 |
+
|
| 53 |
+
PCT = {}
|
| 54 |
+
for (a, s), t in P.groupby(["arm", "state"], sort=False):
|
| 55 |
+
t = t.set_index("donor").reindex(DONORS)
|
| 56 |
+
PCT[SH[a], s] = (t.gen_pct.to_numpy(float), t.obsthin_pct.to_numpy(float))
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def diffs(arm: str, ref: str, rows: np.ndarray | None) -> tuple[np.ndarray, np.ndarray]:
|
| 60 |
+
"""gen_diff and obs_diff for the 21 common pairs; rows = donor index matrix (B, N) or None (point estimate)."""
|
| 61 |
+
G, O = [], []
|
| 62 |
+
for s, c in COMMON:
|
| 63 |
+
g = PCT[arm, s][0]
|
| 64 |
+
o = PCT[ref, s][1]
|
| 65 |
+
ga, gb = CONTRASTS[c]
|
| 66 |
+
ma, mb = np.isin(GROUP, ga), np.isin(GROUP, gb)
|
| 67 |
+
if rows is None:
|
| 68 |
+
G.append(np.nanmean(g[ma]) - np.nanmean(g[mb]))
|
| 69 |
+
O.append(np.nanmean(o[ma]) - np.nanmean(o[mb]))
|
| 70 |
+
else:
|
| 71 |
+
# per replicate: nan-aware mean over the resampled donors of each group
|
| 72 |
+
def gm(v: np.ndarray, m: np.ndarray) -> np.ndarray:
|
| 73 |
+
V, M = v[rows], m[rows]
|
| 74 |
+
ok = M & ~np.isnan(V)
|
| 75 |
+
with np.errstate(invalid="ignore", divide="ignore"):
|
| 76 |
+
return np.where(ok, V, 0).sum(1) / ok.sum(1)
|
| 77 |
+
G.append(gm(g, ma) - gm(g, mb))
|
| 78 |
+
O.append(gm(o, ma) - gm(o, mb))
|
| 79 |
+
return np.array(G), np.array(O)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def med_kept(g: np.ndarray, o: np.ndarray, mask: np.ndarray | None = None) -> float:
|
| 83 |
+
keep = (np.sign(g) == np.sign(o)) & np.isfinite(g) & np.isfinite(o) & (o != 0)
|
| 84 |
+
if mask is not None:
|
| 85 |
+
keep &= mask
|
| 86 |
+
return float(np.median(g[keep] / o[keep])) if keep.any() else np.nan
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
say("=== cross-7: medians over each arm's own kept set vs over the pairs kept by both ===")
|
| 90 |
+
rows = []
|
| 91 |
+
for scr_var, scr_ref in [("own", "s162k"), ("depth_r16", "r16")]:
|
| 92 |
+
gs, os_ = diffs("s162k", scr_ref, None)
|
| 93 |
+
ks = np.sign(gs) == np.sign(os_)
|
| 94 |
+
for comp in ["r16", "r64", "full20k", "full108k", "xcal", "zs", "own58"]:
|
| 95 |
+
gc, oc = diffs(comp, comp, None)
|
| 96 |
+
kc = np.sign(gc) == np.sign(oc)
|
| 97 |
+
both = ks & kc
|
| 98 |
+
m_s, m_c = med_kept(gs, os_), med_kept(gc, oc)
|
| 99 |
+
b_s, b_c = med_kept(gs, os_, both), med_kept(gc, oc, both)
|
| 100 |
+
# bootstrap
|
| 101 |
+
Gs, Os = diffs("s162k", scr_ref, IDX)
|
| 102 |
+
Gc, Oc = diffs(comp, comp, IDX)
|
| 103 |
+
rat_own, rat_both = [], []
|
| 104 |
+
for b in range(B):
|
| 105 |
+
gs_b, os_b, gc_b, oc_b = Gs[:, b], Os[:, b], Gc[:, b], Oc[:, b]
|
| 106 |
+
ms, mc = med_kept(gs_b, os_b), med_kept(gc_b, oc_b)
|
| 107 |
+
rat_own.append(mc / ms if ms and np.isfinite(ms) and ms > 0 else np.nan)
|
| 108 |
+
kb = (np.sign(gs_b) == np.sign(os_b)) & (np.sign(gc_b) == np.sign(oc_b))
|
| 109 |
+
ms2, mc2 = med_kept(gs_b, os_b, kb), med_kept(gc_b, oc_b, kb)
|
| 110 |
+
rat_both.append(mc2 / ms2 if ms2 and np.isfinite(ms2) and ms2 > 0 else np.nan)
|
| 111 |
+
rat_own, rat_both = np.array(rat_own), np.array(rat_both)
|
| 112 |
+
f = lambda v: np.percentile(v[np.isfinite(v)], [2.5, 97.5]) if np.isfinite(v).any() else (np.nan, np.nan)
|
| 113 |
+
lo1, hi1 = f(rat_own)
|
| 114 |
+
lo2, hi2 = f(rat_both)
|
| 115 |
+
rows.append({"scratch_variant": scr_var, "comparator": comp, "n_kept_scratch": int(ks.sum()),
|
| 116 |
+
"n_kept_comp": int(kc.sum()), "n_kept_both": int(both.sum()),
|
| 117 |
+
"median_kept_scratch": m_s, "median_kept_comp": m_c, "ratio_comp_over_scratch": m_c / m_s,
|
| 118 |
+
"ratio_ci_lo": lo1, "ratio_ci_hi": hi1, "frac_boot_ratio_gt1": float(np.nanmean(rat_own > 1)),
|
| 119 |
+
"median_bothkept_scratch": b_s, "median_bothkept_comp": b_c,
|
| 120 |
+
"ratio_bothkept_comp_over_scratch": b_c / b_s if b_s > 0 else np.nan,
|
| 121 |
+
"ratio_bothkept_ci_lo": lo2, "ratio_bothkept_ci_hi": hi2,
|
| 122 |
+
"frac_boot_bothkept_ratio_gt1": float(np.nanmean(rat_both > 1)),
|
| 123 |
+
"n_boot_finite": int(np.isfinite(rat_own).sum())})
|
| 124 |
+
X7 = pd.DataFrame(rows)
|
| 125 |
+
X7.to_csv(DST / f"{PFX}contrast_compression.csv", index=False)
|
| 126 |
+
say(X7.round(3).to_string(index=False))
|
| 127 |
+
|
| 128 |
+
# per-pair table for scratch vs r16 / full108k on the pairs kept by both
|
| 129 |
+
gs, os_ = diffs("s162k", "s162k", None)
|
| 130 |
+
tab = pd.DataFrame({"pair": [f"{s}|{c}" for s, c in COMMON], "s162k_frac": gs / os_})
|
| 131 |
+
for comp in ["r16", "r64", "full108k", "full20k", "xcal", "own58"]:
|
| 132 |
+
gc, oc = diffs(comp, comp, None)
|
| 133 |
+
tab[f"{comp}_frac"] = gc / oc
|
| 134 |
+
gs16, os16 = diffs("s162k", "r16", None)
|
| 135 |
+
tab["s162k_at_r16depth_frac"] = gs16 / os16
|
| 136 |
+
tab.to_csv(DST / f"{PFX}contrast_pairs.csv", index=False)
|
| 137 |
+
say(tab.round(3).to_string(index=False))
|
| 138 |
+
|
| 139 |
+
say("\n=== cross-4: depth-correction factor ranges ===")
|
| 140 |
+
R = pd.read_csv(DST / "verify_recompute_cross_ratios.csv")
|
| 141 |
+
s = R[R.arm == "s162k"].pivot(index="state", columns="reference", values="ratio")
|
| 142 |
+
fac = s[["depth_r16", "depth_r64", "depth_full20k", "depth_full108k"]].div(s["own"], axis=0)
|
| 143 |
+
fac["is_label"] = s.index.str.contains(r"\(label\)")
|
| 144 |
+
say(fac.round(3).to_string())
|
| 145 |
+
ctrl = fac.index.str.contains("control")
|
| 146 |
+
mk = ~fac.is_label
|
| 147 |
+
num = fac.drop(columns="is_label")
|
| 148 |
+
say("rare marker states: factor range", round(float(num[mk & ~ctrl].min().min()), 3), "-",
|
| 149 |
+
round(float(num[mk & ~ctrl].max().max()), 3), "| r16 only:", round(float(num[mk & ~ctrl].depth_r16.min()), 3),
|
| 150 |
+
"-", round(float(num[mk & ~ctrl].depth_r16.max()), 3))
|
| 151 |
+
say("controls: factor range", round(float(num[ctrl].min().min()), 3), "-", round(float(num[ctrl].max().max()), 3))
|
| 152 |
+
fac.to_csv(DST / f"{PFX}depth_factors.csv")
|
| 153 |
+
|
| 154 |
+
(DST / f"{PFX}report.txt").write_text("\n".join(LOG) + "\n")
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_cross_obsdepth_script.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""cross-4 adversarial check on the observed side (CPU only, read-only inputs; verifier-written, 2026-10-05).
|
| 3 |
+
|
| 4 |
+
Question: does "the scratch model's marker detection equals the ~1,000-UMI pretrained arms" really mean the scratch
|
| 5 |
+
cells behave like observed cells thinned to the pretrained arms' depth? For observed monocytes and T cells of the 82
|
| 6 |
+
held-out donors, binomially thin the 73 marker-gene counts over a grid of thinning factors (seed 20261005) and record
|
| 7 |
+
marker detection (mean detected markers of 73, HLA-DRA in monocytes, NKG7 / GZMA in T cells). Then find the thinning
|
| 8 |
+
at which observed detection equals each generated arm's detection, and compare it with the screen's library-based
|
| 9 |
+
thin constants. Sanity: the native C1Q-high and MS1 counts must equal the per-donor CSV's obs_state sums.
|
| 10 |
+
Inputs: plans/paired_finetune_intradataset_20260927/data/ye2026_sepsis/{cells_panel6k.npz,cells_obs.parquet},
|
| 11 |
+
scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet, the canonical gene table, work/sepsis/loco/*.npz,
|
| 12 |
+
out/sepsis_loco_{per_donor,summary}.csv. Output: verify_recompute_cross_obsdepth.csv / _report.txt.
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import json
|
| 17 |
+
import sys
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pandas as pd
|
| 22 |
+
|
| 23 |
+
sys.dont_write_bytecode = True
|
| 24 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 25 |
+
PLAN = M8 / "plans/rare_states_screen_20261004"
|
| 26 |
+
DST = PLAN / "out/scratch_vs_lora_20261005"
|
| 27 |
+
FT = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 28 |
+
DATA = FT / "data/ye2026_sepsis"
|
| 29 |
+
CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
|
| 30 |
+
"canonical_genes.tsv")
|
| 31 |
+
LOG: list[str] = []
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def say(*a) -> None:
|
| 35 |
+
s = " ".join(str(x) for x in a)
|
| 36 |
+
print(s, flush=True)
|
| 37 |
+
LOG.append(s)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
P = pd.read_csv(PLAN / "out/sepsis_loco_per_donor.csv")
|
| 41 |
+
SUM = pd.read_csv(PLAN / "out/sepsis_loco_summary.csv")
|
| 42 |
+
donors = sorted(P.donor.unique())
|
| 43 |
+
g0 = np.load(PLAN / "work/sepsis/loco/locoL_scratchsat_s162000_K1000.npz", allow_pickle=False)
|
| 44 |
+
syms = list(g0["marker_symbols"].astype(str))
|
| 45 |
+
|
| 46 |
+
d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
|
| 47 |
+
panel = d["panel_gene_ids"].astype(str)
|
| 48 |
+
measured = d["panel_measured"].any(0)
|
| 49 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 50 |
+
sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
|
| 51 |
+
pos = {g: i for i, g in enumerate(panel)}
|
| 52 |
+
cols = np.array([pos[sym2id[s]] for s in syms])
|
| 53 |
+
assert all(measured[c] for c in cols)
|
| 54 |
+
data, indices, indptr = d["data"], d["indices"], d["indptr"]
|
| 55 |
+
n_rows = len(indptr) - 1
|
| 56 |
+
obs = pd.read_parquet(DATA / "cells_obs.parquet", columns=["sample_id"])
|
| 57 |
+
lab = pd.read_parquet(FT / "scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet")
|
| 58 |
+
assert len(obs) == n_rows == len(lab) and (lab.npz_row.to_numpy() == np.arange(n_rows)).all()
|
| 59 |
+
keep = obs.sample_id.isin(donors).to_numpy()
|
| 60 |
+
say("observed cells of the 82 donors:", int(keep.sum()), "of", n_rows)
|
| 61 |
+
|
| 62 |
+
# library on measured genes, per row
|
| 63 |
+
row_of = np.repeat(np.arange(n_rows, dtype=np.int32), np.diff(indptr))
|
| 64 |
+
lib = np.bincount(row_of, weights=data * measured[indices], minlength=n_rows)
|
| 65 |
+
# dense marker matrix for the kept rows
|
| 66 |
+
colmap = np.full(len(panel), -1, dtype=np.int32)
|
| 67 |
+
colmap[cols] = np.arange(len(cols))
|
| 68 |
+
sel = colmap[indices] >= 0
|
| 69 |
+
M = np.zeros((n_rows, len(cols)), dtype=np.int64)
|
| 70 |
+
M[row_of[sel], colmap[indices[sel]]] = data[sel]
|
| 71 |
+
del row_of, sel
|
| 72 |
+
M, lib = M[keep], lib[keep]
|
| 73 |
+
l1 = lab.aifi_l1.to_numpy().astype(str)[keep]
|
| 74 |
+
l2 = lab.aifi_l2.to_numpy().astype(str)[keep]
|
| 75 |
+
mono = np.isin(l1, ["Monocyte"]) | np.isin(l2, ["Monocyte"])
|
| 76 |
+
tcell = np.isin(l1, ["T cell"]) | np.isin(l2, ["T cell"])
|
| 77 |
+
say("observed monocytes", int(mono.sum()), "T cells", int(tcell.sum()))
|
| 78 |
+
say("observed median library (measured genes): monocytes", float(np.median(lib[mono])), "T cells",
|
| 79 |
+
float(np.median(lib[tcell])), "all", float(np.median(lib)))
|
| 80 |
+
ci = {s: i for i, s in enumerate(syms)}
|
| 81 |
+
|
| 82 |
+
# sanity: native C1Q-high (>=2 of C1QA/B/C) and MS1 counts equal the per-donor CSV
|
| 83 |
+
det = M > 0
|
| 84 |
+
c1q = det[:, [ci["C1QA"], ci["C1QB"], ci["C1QC"]]].sum(1) >= 2
|
| 85 |
+
ms1 = (det[:, [ci[g] for g in ["RETN", "ALOX5AP", "CYP1B1", "MCEMP1", "PLAC8", "CLU", "CD163"]]].sum(1) >= 2) & \
|
| 86 |
+
det[:, ci["IL1R2"]]
|
| 87 |
+
n_c1q = int((c1q & mono).sum())
|
| 88 |
+
n_ms1 = int((ms1 & mono).sum())
|
| 89 |
+
csv_c1q = int(P[(P.arm == "zs__raw") & (P.state == "C1Q-high monocyte (reference)")].obs_state.sum())
|
| 90 |
+
csv_ms1 = int(P[(P.arm == "zs__raw") & (P.state == "MS1 monocyte (IL1R2+)")].obs_state.sum())
|
| 91 |
+
say("sanity native C1Q", n_c1q, "csv", csv_c1q, "| MS1", n_ms1, "csv", csv_ms1)
|
| 92 |
+
assert n_c1q == csv_c1q and n_ms1 == csv_ms1
|
| 93 |
+
|
| 94 |
+
rng = np.random.default_rng(20261005)
|
| 95 |
+
grid = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5, 0.45, 0.4, 0.35, 0.3, 0.25, 0.2, 0.15, 0.1, 0.07, 0.05]
|
| 96 |
+
rows = []
|
| 97 |
+
Mm, Mt = M[mono], M[tcell]
|
| 98 |
+
for t in grid:
|
| 99 |
+
tm = rng.binomial(Mm, t) if t < 1 else Mm
|
| 100 |
+
tt = rng.binomial(Mt, t) if t < 1 else Mt
|
| 101 |
+
dm, dt = tm > 0, tt > 0
|
| 102 |
+
rows.append({"thin": t, "mono_mean_detected_of_73": float(dm.sum(1).mean()),
|
| 103 |
+
"mono_umis_per_detected": float(tm[dm].mean()),
|
| 104 |
+
"mono_HLA-DRA": float(dm[:, ci["HLA-DRA"]].mean()),
|
| 105 |
+
"mono_C1Q_pct": 100 * float((dm[:, [ci["C1QA"], ci["C1QB"], ci["C1QC"]]].sum(1) >= 2).mean()),
|
| 106 |
+
"T_mean_detected_of_73": float(dt.sum(1).mean()),
|
| 107 |
+
"T_NKG7": float(dt[:, ci["NKG7"]].mean()), "T_GZMA": float(dt[:, ci["GZMA"]].mean())})
|
| 108 |
+
OD = pd.DataFrame(rows)
|
| 109 |
+
OD.to_csv(DST / "verify_recompute_cross_obsdepth.csv", index=False)
|
| 110 |
+
pd.set_option("display.width", 250, "display.max_columns", 30)
|
| 111 |
+
say(OD.round(4).to_string(index=False))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def inv(metric: str, value: float) -> float:
|
| 115 |
+
"""thinning at which the observed metric equals value (linear interpolation on the monotone grid)."""
|
| 116 |
+
x = OD.thin.to_numpy()[::-1]
|
| 117 |
+
y = OD[metric].to_numpy()[::-1]
|
| 118 |
+
if value < y.min() or value > y.max():
|
| 119 |
+
return float("nan")
|
| 120 |
+
return float(np.interp(value, y, x))
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
DC = pd.read_csv(DST / "verify_recompute_cross_depth.csv")
|
| 124 |
+
rows = []
|
| 125 |
+
for arm in ["zs", "xcal", "r16", "r64", "full20k", "full108k", "s50k", "s162k", "own58"]:
|
| 126 |
+
m = DC[(DC.arm == arm) & (DC.parent == "Monocyte")].iloc[0]
|
| 127 |
+
t = DC[(DC.arm == arm) & (DC.parent == "T cell")].iloc[0]
|
| 128 |
+
rows.append({"arm": arm, "screen_thin_mono": m.screen_thin, "screen_thin_T": t.screen_thin,
|
| 129 |
+
"detect_matched_thin_mono_markers": inv("mono_mean_detected_of_73", m["mean_detected_markers_of_73"]),
|
| 130 |
+
"detect_matched_thin_HLA-DRA": inv("mono_HLA-DRA", m["det_HLA-DRA"]),
|
| 131 |
+
"detect_matched_thin_T_markers": inv("T_mean_detected_of_73", t["mean_detected_markers_of_73"]),
|
| 132 |
+
"detect_matched_thin_NKG7": inv("T_NKG7", t["det_NKG7"]),
|
| 133 |
+
"detect_matched_thin_GZMA": inv("T_GZMA", t["det_GZMA"])})
|
| 134 |
+
DM = pd.DataFrame(rows)
|
| 135 |
+
DM.to_csv(DST / "verify_recompute_cross_obsdepth_matched.csv", index=False)
|
| 136 |
+
say(DM.round(3).to_string(index=False))
|
| 137 |
+
(DST / "verify_recompute_cross_obsdepth_report.txt").write_text("\n".join(LOG) + "\n")
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_cross_script.py
ADDED
|
@@ -0,0 +1,555 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Independent adversarial recompute of the cross-cohort claims cross-1 .. cross-8 (CPU only, 2026-10-05).
|
| 3 |
+
|
| 4 |
+
Written from scratch by the verifier (does not import or read the analyst's cross_*.csv / cross_analysis.py results).
|
| 5 |
+
Inputs (read-only): out/sepsis_loco_per_donor.csv (all ratio / bootstrap / Spearman / contrast numbers),
|
| 6 |
+
out/sepsis_loco_summary.csv and out/sepsis_loco_contrasts.csv (only to check that the per-donor table reproduces the
|
| 7 |
+
screen, and for the screen's thin constants), work/sepsis/loco/<arm>.npz (library / marker-detection depth check),
|
| 8 |
+
plans/paired_crosscohort_20261002/scores/ye2026_sepsis/<arm>/summary.json (benchmark depth / coverage numbers).
|
| 9 |
+
Outputs: out/scratch_vs_lora_20261005/verify_recompute_cross_*.csv and verify_recompute_cross_report.txt.
|
| 10 |
+
|
| 11 |
+
Definitions (from the claims' how_to_recompute):
|
| 12 |
+
ratio = (sum gen_state / sum gen_parent) / (sum obsthin_state / sum obs_parent) over the 82 donors (no pseudocount)
|
| 13 |
+
ratio_ps = same with +0.5 added to both state sums (used for |log2|, D and every bootstrap replicate)
|
| 14 |
+
bootstrap = donors sorted; idx = default_rng(20261005).integers(0, 82, (2000, 82)); one idx shared by everything
|
| 15 |
+
D = |log2 ratio_ps(scratch)| - |log2 ratio_ps(comparator)|; 95 % percentile CI; D > 0 = comparator closer
|
| 16 |
+
matched depth (pretrained_depth_ref): the scratch arm's obsthin_state replaced by the comparator's (vs xcal: by the
|
| 17 |
+
LoRA r16 one, as in the claims; the xcal-depth alternative is also reported)
|
| 18 |
+
usage: CUDA_VISIBLE_DEVICES= python verify_recompute_cross_script.py
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import json
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
from scipy.stats import rankdata, spearmanr
|
| 29 |
+
|
| 30 |
+
sys.dont_write_bytecode = True
|
| 31 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 32 |
+
OUT = PLAN / "out"
|
| 33 |
+
DST = OUT / "scratch_vs_lora_20261005"
|
| 34 |
+
PFX = "verify_recompute_cross_"
|
| 35 |
+
SCORES = PLAN.parent / "paired_crosscohort_20261002/scores/ye2026_sepsis"
|
| 36 |
+
|
| 37 |
+
SEED, B, PS = 20261005, 2000, 0.5
|
| 38 |
+
ZS, XCAL = "zs__raw", "xcalL_K1000"
|
| 39 |
+
L16, L64 = "locoL_lora16sat_s26750_K1000", "locoL_lora64sat_s59000_K1000"
|
| 40 |
+
F20, F108 = "locoL_fullsat_s20000_K1000", "locoL_fullsat_s108500_K1000"
|
| 41 |
+
S50, S100, S150, S162 = (f"locoL_scratchsat_s{s}_K1000" for s in (50000, 100000, 150000, 162000))
|
| 42 |
+
OWN5, OWN58 = "lora_n5__raw", "real_lora__raw"
|
| 43 |
+
ARMS = [ZS, XCAL, L16, L64, F20, F108, S50, S100, S150, S162, OWN5, OWN58]
|
| 44 |
+
SH = {ZS: "zs", XCAL: "xcal", L16: "r16", L64: "r64", F20: "full20k", F108: "full108k", S50: "s50k", S100: "s100k",
|
| 45 |
+
S150: "s150k", S162: "s162k", OWN5: "own5", OWN58: "own58"}
|
| 46 |
+
SCRATCH = [S50, S100, S150, S162]
|
| 47 |
+
PRE = [L16, L64, F20, F108]
|
| 48 |
+
CONTROLS = ["ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"]
|
| 49 |
+
C1Q, MS1 = "C1Q-high monocyte (reference)", "MS1 monocyte (IL1R2+)"
|
| 50 |
+
CYC_TNK, CYC_ACT, CYC_MONO = "Cycling T/NK", "Cycling activated T (CD38/HLA-DR)", "Cycling monocyte (Ye 2026)"
|
| 51 |
+
PROLIF, PB_LAB, PB_MK = "Proliferating T (label)", "Plasmablast (label)", "Plasmablast (markers)"
|
| 52 |
+
ISG_T, ISG_M, DN2, HSPC = "ISG-high T", "ISG-high monocyte (positive control)", "DN2 / ABC B", "HSPC"
|
| 53 |
+
CYTO4, LDG, PLT = "Cytotoxic CD4 T", "Granulocyte-like (LDG)", "Platelet signal in monocytes (negative control)"
|
| 54 |
+
CONTRASTS = [("adult", ["adult_sepsis"], ["adult_HC"]),
|
| 55 |
+
("paediatric", ["ped_sepsis"], ["ped_HC"]),
|
| 56 |
+
("all", ["adult_sepsis", "ped_sepsis"], ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
|
| 57 |
+
|
| 58 |
+
LOG: list[str] = []
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def say(*a) -> None:
|
| 62 |
+
s = " ".join(str(x) for x in a)
|
| 63 |
+
print(s)
|
| 64 |
+
LOG.append(s)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
# ------------------------------------------------------------------------------------------------------------------
|
| 68 |
+
P = pd.read_csv(OUT / "sepsis_loco_per_donor.csv")
|
| 69 |
+
SUM = pd.read_csv(OUT / "sepsis_loco_summary.csv")
|
| 70 |
+
CON = pd.read_csv(OUT / "sepsis_loco_contrasts.csv")
|
| 71 |
+
assert sorted(P.arm.unique()) == sorted(ARMS)
|
| 72 |
+
DONORS = sorted(P.donor.unique())
|
| 73 |
+
N = len(DONORS)
|
| 74 |
+
assert N == 82
|
| 75 |
+
STATES = list(dict.fromkeys(P.state))
|
| 76 |
+
RARE = [s for s in STATES if s not in CONTROLS]
|
| 77 |
+
assert len(STATES) == 15 and len(RARE) == 13
|
| 78 |
+
GROUP = P.drop_duplicates("donor").set_index("donor").group.reindex(DONORS).to_numpy()
|
| 79 |
+
assert P.groupby("donor").group.nunique().max() == 1
|
| 80 |
+
|
| 81 |
+
X: dict = {}
|
| 82 |
+
for (a, s), t in P.groupby(["arm", "state"], sort=False):
|
| 83 |
+
assert len(t) == N and t.donor.is_unique
|
| 84 |
+
t = t.set_index("donor").reindex(DONORS)
|
| 85 |
+
X[a, s] = {c: t[c].to_numpy(dtype=float) for c in
|
| 86 |
+
["obs_parent", "obs_state", "obsthin_state", "gen_parent", "gen_state", "obsthin_pct", "gen_pct"]}
|
| 87 |
+
for s in STATES:
|
| 88 |
+
for a in ARMS:
|
| 89 |
+
assert np.array_equal(X[a, s]["obs_parent"], X[ZS, s]["obs_parent"]), (a, s)
|
| 90 |
+
assert np.array_equal(X[a, s]["obs_state"], X[ZS, s]["obs_state"]), (a, s)
|
| 91 |
+
|
| 92 |
+
IDX = np.random.default_rng(SEED).integers(0, N, (B, N))
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def pct(st: np.ndarray, par: np.ndarray) -> np.ndarray:
|
| 96 |
+
out = np.full(st.shape, np.nan)
|
| 97 |
+
m = par > 0
|
| 98 |
+
out[m] = 100.0 * st[m] / par[m]
|
| 99 |
+
return out
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
# the per-donor pct columns equal the counts
|
| 103 |
+
for k, v in X.items():
|
| 104 |
+
assert np.allclose(pct(v["gen_state"], v["gen_parent"]), v["gen_pct"], equal_nan=True)
|
| 105 |
+
assert np.allclose(pct(v["obsthin_state"], v["obs_parent"]), v["obsthin_pct"], equal_nan=True)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def raw_ratio(gen_arm: str, ref_arm: str, st: str) -> float:
|
| 109 |
+
g, o = X[gen_arm, st], X[ref_arm, st]
|
| 110 |
+
ro = o["obsthin_state"].sum() / o["obs_parent"].sum()
|
| 111 |
+
rg = g["gen_state"].sum() / g["gen_parent"].sum()
|
| 112 |
+
return float(rg / ro) if ro > 0 else float("nan")
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def log2r(gen_arm: str, ref_arm: str, st: str, ps: float = PS) -> tuple[float, np.ndarray]:
|
| 116 |
+
g, o = X[gen_arm, st], X[ref_arm, st]
|
| 117 |
+
gs, gp, os_, op = g["gen_state"], g["gen_parent"], o["obsthin_state"], o["obs_parent"]
|
| 118 |
+
pt = np.log2(((gs.sum() + ps) / gp.sum()) / ((os_.sum() + ps) / op.sum()))
|
| 119 |
+
bgs, bgp, bos, bop = gs[IDX].sum(1), gp[IDX].sum(1), os_[IDX].sum(1), op[IDX].sum(1)
|
| 120 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 121 |
+
bs = np.log2(((bgs + ps) / bgp) / ((bos + ps) / bop))
|
| 122 |
+
return float(pt), bs
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def ci(v: np.ndarray) -> tuple[float, float]:
|
| 126 |
+
v = v[np.isfinite(v)]
|
| 127 |
+
if v.size == 0:
|
| 128 |
+
return float("nan"), float("nan")
|
| 129 |
+
lo, hi = np.percentile(v, [2.5, 97.5])
|
| 130 |
+
return float(lo), float(hi)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
# sanity: reproduce the screen summary (gen_over_obs, Spearman) from the per-donor table
|
| 134 |
+
for r in SUM.itertuples():
|
| 135 |
+
rr = raw_ratio(r.arm, r.arm, r.state)
|
| 136 |
+
assert np.isclose(rr, r.gen_over_obs, rtol=1e-9), (r.arm, r.state, rr, r.gen_over_obs)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def spear(x: np.ndarray, y: np.ndarray) -> float:
|
| 140 |
+
m = ~(np.isnan(x) | np.isnan(y))
|
| 141 |
+
if m.sum() < 3:
|
| 142 |
+
return float("nan")
|
| 143 |
+
x, y = x[m], y[m]
|
| 144 |
+
if np.all(x == x[0]) or np.all(y == y[0]):
|
| 145 |
+
return float("nan")
|
| 146 |
+
return float(spearmanr(x, y).statistic)
|
| 147 |
+
|
| 148 |
+
|
| 149 |
+
for r in SUM.itertuples():
|
| 150 |
+
v = X[r.arm, r.state]
|
| 151 |
+
rho = spear(v["gen_pct"], v["obsthin_pct"])
|
| 152 |
+
assert (np.isnan(rho) and np.isnan(r.spearman_donors)) or np.isclose(rho, r.spearman_donors, atol=1e-9), \
|
| 153 |
+
(r.arm, r.state, rho, r.spearman_donors)
|
| 154 |
+
say("[sanity] per-donor table reproduces sepsis_loco_summary.csv gen_over_obs and spearman_donors for all",
|
| 155 |
+
len(SUM), "rows")
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def spear_boot(x: np.ndarray, y: np.ndarray) -> np.ndarray:
|
| 159 |
+
"""Spearman (average ranks, NaN pairs dropped) of every bootstrap replicate of donors."""
|
| 160 |
+
XB, YB = x[IDX], y[IDX]
|
| 161 |
+
ok = ~(np.isnan(XB) | np.isnan(YB))
|
| 162 |
+
out = np.full(B, np.nan)
|
| 163 |
+
full = ok.all(1)
|
| 164 |
+
if full.any():
|
| 165 |
+
rx = rankdata(XB[full], axis=1)
|
| 166 |
+
ry = rankdata(YB[full], axis=1)
|
| 167 |
+
rx = rx - rx.mean(1, keepdims=True)
|
| 168 |
+
ry = ry - ry.mean(1, keepdims=True)
|
| 169 |
+
den = np.sqrt((rx * rx).sum(1) * (ry * ry).sum(1))
|
| 170 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 171 |
+
r = (rx * ry).sum(1) / den
|
| 172 |
+
r[~(den > 1e-12)] = np.nan
|
| 173 |
+
out[full] = r
|
| 174 |
+
for b in np.flatnonzero(~full):
|
| 175 |
+
m = ok[b]
|
| 176 |
+
a_, c_ = XB[b][m], YB[b][m]
|
| 177 |
+
if m.sum() < 3 or np.all(a_ == a_[0]) or np.all(c_ == c_[0]):
|
| 178 |
+
continue
|
| 179 |
+
out[b] = np.corrcoef(rankdata(a_), rankdata(c_))[0, 1]
|
| 180 |
+
return out
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
# check the vectorised bootstrap Spearman against scipy on 40 replicates of 3 arm/state pairs (incl. NaN donors)
|
| 184 |
+
for a, s in [(S162, CYC_TNK), (F108, C1Q), (L16, HSPC)]:
|
| 185 |
+
v = X[a, s]
|
| 186 |
+
bb = spear_boot(v["gen_pct"], v["obsthin_pct"])
|
| 187 |
+
for b in range(40):
|
| 188 |
+
xx, yy = v["gen_pct"][IDX[b]], v["obsthin_pct"][IDX[b]]
|
| 189 |
+
assert (np.isnan(bb[b]) and np.isnan(spear(xx, yy))) or np.isclose(bb[b], spear(xx, yy), atol=1e-12)
|
| 190 |
+
say("[sanity] vectorised bootstrap Spearman == scipy.spearmanr on checked replicates")
|
| 191 |
+
|
| 192 |
+
# ------------------------------------------------------------------------------------------------------------------
|
| 193 |
+
# 1. per-arm ratios with CIs (own reference; scratch arms also at each pretrained arm's depth and at xcal's)
|
| 194 |
+
rows = []
|
| 195 |
+
for s in STATES:
|
| 196 |
+
for a in ARMS:
|
| 197 |
+
refs = [("own", a)] + ([(f"depth_{SH[r]}", r) for r in PRE + [XCAL]] if a in SCRATCH else [])
|
| 198 |
+
for var, ref in refs:
|
| 199 |
+
pt, bs = log2r(a, ref, s)
|
| 200 |
+
lo, hi = ci(bs)
|
| 201 |
+
g, o = X[a, s], X[ref, s]
|
| 202 |
+
rows.append({"state": s, "is_control": s in CONTROLS, "arm": SH[a], "reference": var,
|
| 203 |
+
"gen_state": int(g["gen_state"].sum()), "gen_parent": int(g["gen_parent"].sum()),
|
| 204 |
+
"obsthin_state": int(o["obsthin_state"].sum()), "obs_parent": int(o["obs_parent"].sum()),
|
| 205 |
+
"obs_native_state": int(o["obs_state"].sum()),
|
| 206 |
+
"ratio": raw_ratio(a, ref, s), "ratio_ps": 2 ** pt, "ci_lo": 2 ** lo, "ci_hi": 2 ** hi,
|
| 207 |
+
"abs_log2_ps": abs(pt), "n_boot_nonfinite": int((~np.isfinite(bs)).sum())})
|
| 208 |
+
R = pd.DataFrame(rows)
|
| 209 |
+
R.to_csv(DST / f"{PFX}ratios.csv", index=False)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def rat(a: str, s: str, ref: str = "own") -> pd.Series:
|
| 213 |
+
t = R[(R.arm == SH[a]) & (R.state == s) & (R.reference == ref)]
|
| 214 |
+
assert len(t) == 1, (a, s, ref)
|
| 215 |
+
return t.iloc[0]
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# 2. paired D per state
|
| 219 |
+
COMPS = [(S162, L16), (S162, L64), (S162, F108), (S162, XCAL), (S162, F20), (S162, ZS),
|
| 220 |
+
(S50, L16), (S50, L64), (S50, F108), (S50, XCAL),
|
| 221 |
+
(S162, S50), (S162, S100), (S162, S150), (S162, OWN58), (S162, OWN5)]
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def variants(scr: str, comp: str) -> list[tuple[str, str, str]]:
|
| 225 |
+
v = [("own", scr, comp)]
|
| 226 |
+
if comp in PRE or comp == ZS:
|
| 227 |
+
v.append(("matched_depth", comp, comp))
|
| 228 |
+
elif comp == XCAL:
|
| 229 |
+
v += [("matched_depth", L16, XCAL), ("matched_depth_xcalref", XCAL, XCAL)]
|
| 230 |
+
elif comp in SCRATCH:
|
| 231 |
+
v.append(("both_at_r16_depth", L16, L16))
|
| 232 |
+
return v
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
rows, AGG = [], []
|
| 236 |
+
for scr, comp in COMPS:
|
| 237 |
+
for var, ref_s, ref_c in variants(scr, comp):
|
| 238 |
+
Dpt, Dbs = [], []
|
| 239 |
+
for s in STATES:
|
| 240 |
+
ps_, bs_s = log2r(scr, ref_s, s)
|
| 241 |
+
pc_, bs_c = log2r(comp, ref_c, s)
|
| 242 |
+
d, db = abs(ps_) - abs(pc_), np.abs(bs_s) - np.abs(bs_c)
|
| 243 |
+
lo, hi = ci(db)
|
| 244 |
+
# D without the pseudocount in the point estimate (CI unchanged)
|
| 245 |
+
rs, rc = raw_ratio(scr, ref_s, s), raw_ratio(comp, ref_c, s)
|
| 246 |
+
d_raw = (abs(np.log2(rs)) if rs > 0 else np.inf) - (abs(np.log2(rc)) if rc > 0 else np.inf)
|
| 247 |
+
rows.append({"comparison": f"{SH[scr]} vs {SH[comp]}", "variant": var, "state": s,
|
| 248 |
+
"is_control": s in CONTROLS, "scratch_ref": SH[ref_s], "comparator_ref": SH[ref_c],
|
| 249 |
+
"ratio_scratch": rs, "ratio_comparator": rc,
|
| 250 |
+
"ratio_scratch_ps": 2 ** ps_, "ratio_comparator_ps": 2 ** pc_,
|
| 251 |
+
"D": d, "D_ci_lo": lo, "D_ci_hi": hi, "D_rawpoint": d_raw,
|
| 252 |
+
"verdict": "comparator_closer" if lo > 0 else "scratch_closer" if hi < 0 else "ns"})
|
| 253 |
+
if s in RARE:
|
| 254 |
+
Dpt.append(d)
|
| 255 |
+
Dbs.append(db)
|
| 256 |
+
mDb = np.vstack(Dbs).mean(0)
|
| 257 |
+
lo, hi = ci(mDb)
|
| 258 |
+
AGG.append({"kind": "mean_D", "name": f"{SH[scr]} vs {SH[comp]}", "variant": var,
|
| 259 |
+
"value": float(np.mean(Dpt)), "ci_lo": lo, "ci_hi": hi})
|
| 260 |
+
DT = pd.DataFrame(rows)
|
| 261 |
+
DT.to_csv(DST / f"{PFX}D_per_state.csv", index=False)
|
| 262 |
+
|
| 263 |
+
# 3. mean |log2| over the 13 rare states per arm (own reference; scratch also at r16 depth)
|
| 264 |
+
for a in ARMS:
|
| 265 |
+
for var, ref in [("own", a)] + ([("depth_r16", L16)] if a in SCRATCH else []):
|
| 266 |
+
pts, bss = zip(*[log2r(a, ref, s) for s in RARE])
|
| 267 |
+
m = np.abs(np.vstack(bss)).mean(0)
|
| 268 |
+
lo, hi = ci(m)
|
| 269 |
+
raws = np.array([raw_ratio(a, ref, s) for s in RARE])
|
| 270 |
+
AGG.append({"kind": "mean_abs_log2", "name": SH[a], "variant": var, "value": float(np.mean(np.abs(pts))),
|
| 271 |
+
"ci_lo": lo, "ci_hi": hi, "n_within_2fold": int(((raws >= 0.5) & (raws <= 2)).sum()),
|
| 272 |
+
"within_2fold": "; ".join(s for s, r in zip(RARE, raws) if 0.5 <= r <= 2),
|
| 273 |
+
"mean_abs_log2_rawpoint": float(np.mean(np.abs(np.log2(np.where(raws > 0, raws, np.nan)))))
|
| 274 |
+
if (raws > 0).all() else float("nan")})
|
| 275 |
+
AG = pd.DataFrame(AGG)
|
| 276 |
+
AG.to_csv(DST / f"{PFX}aggregate.csv", index=False)
|
| 277 |
+
|
| 278 |
+
# 4. Spearman per arm/state and differences
|
| 279 |
+
SPC: dict = {}
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def sp_get(a: str, ref: str, s: str) -> tuple[float, np.ndarray]:
|
| 283 |
+
if (a, ref, s) not in SPC:
|
| 284 |
+
x, y = X[a, s]["gen_pct"], X[ref, s]["obsthin_pct"]
|
| 285 |
+
SPC[a, ref, s] = (spear(x, y), spear_boot(x, y))
|
| 286 |
+
return SPC[a, ref, s]
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
rows = []
|
| 290 |
+
for a in ARMS:
|
| 291 |
+
for s in STATES:
|
| 292 |
+
rho, bb = sp_get(a, a, s)
|
| 293 |
+
lo, hi = ci(bb)
|
| 294 |
+
rows.append({"arm": SH[a], "state": s, "rho": rho, "ci_lo": lo, "ci_hi": hi})
|
| 295 |
+
SPA = pd.DataFrame(rows)
|
| 296 |
+
rows = []
|
| 297 |
+
for scr, comp in [(S162, L16), (S162, L64), (S162, F108), (S162, XCAL), (S162, F20), (S162, OWN58)]:
|
| 298 |
+
for s in STATES:
|
| 299 |
+
(a_, ab), (c_, cb) = sp_get(scr, scr, s), sp_get(comp, comp, s)
|
| 300 |
+
lo, hi = ci(ab - cb)
|
| 301 |
+
rows.append({"comparison": f"{SH[scr]} vs {SH[comp]}", "state": s, "is_control": s in CONTROLS,
|
| 302 |
+
"rho_scratch": a_, "rho_comparator": c_, "diff": a_ - c_, "ci_lo": lo, "ci_hi": hi,
|
| 303 |
+
"verdict": "scratch_higher" if lo > 0 else "comparator_higher" if hi < 0 else "ns"})
|
| 304 |
+
SPD = pd.DataFrame(rows)
|
| 305 |
+
SPA.to_csv(DST / f"{PFX}spearman_arms.csv", index=False)
|
| 306 |
+
SPD.to_csv(DST / f"{PFX}spearman_diff.csv", index=False)
|
| 307 |
+
|
| 308 |
+
# 5. contrasts
|
| 309 |
+
rows = []
|
| 310 |
+
for a in ARMS:
|
| 311 |
+
for var, ref in [("own", a)] + ([("depth_r16", L16)] if a in SCRATCH else []):
|
| 312 |
+
for s in STATES:
|
| 313 |
+
gp_, op_ = X[a, s]["gen_pct"], X[ref, s]["obsthin_pct"]
|
| 314 |
+
for cname, ga, gb in CONTRASTS:
|
| 315 |
+
ma, mb = np.isin(GROUP, ga), np.isin(GROUP, gb)
|
| 316 |
+
od = np.nanmean(op_[ma]) - np.nanmean(op_[mb])
|
| 317 |
+
gd = np.nanmean(gp_[ma]) - np.nanmean(gp_[mb])
|
| 318 |
+
rows.append({"arm": SH[a], "variant": var, "state": s, "contrast": cname, "is_control": s in CONTROLS,
|
| 319 |
+
"obs_diff": od, "gen_diff": gd, "same_direction": bool(np.sign(od) == np.sign(gd)),
|
| 320 |
+
"reversed": bool(np.sign(od) * np.sign(gd) < 0),
|
| 321 |
+
"gen_over_obs_diff": gd / od if od != 0 else np.nan})
|
| 322 |
+
CT = pd.DataFrame(rows)
|
| 323 |
+
# check against the screen's contrasts file
|
| 324 |
+
cmap = {"adult sepsis vs adult HC": "adult", "paediatric sepsis vs paediatric HC": "paediatric",
|
| 325 |
+
"all sepsis vs all controls": "all"}
|
| 326 |
+
chk = CON.assign(contrast=CON.contrast.map(cmap), arm=CON.arm.map(SH)).merge(
|
| 327 |
+
CT[CT.variant == "own"], on=["arm", "state", "contrast"], suffixes=("_screen", ""))
|
| 328 |
+
assert len(chk) == len(CON) == 12 * 15 * 3
|
| 329 |
+
assert np.allclose(chk.obs_diff, chk.obs_diff_screen) and np.allclose(chk.gen_diff, chk.gen_diff_screen)
|
| 330 |
+
assert (chk.same_direction == chk.same_direction_screen).all()
|
| 331 |
+
say("[sanity] contrasts reproduce sepsis_loco_contrasts.csv (obs_diff, gen_diff, same_direction) for all", len(chk),
|
| 332 |
+
"rows")
|
| 333 |
+
own = CT[(CT.variant == "own") & ~CT.is_control]
|
| 334 |
+
elig = own.groupby(["state", "contrast"]).apply(
|
| 335 |
+
lambda t: bool((t.obs_diff.abs() >= 0.5).all() and np.sign(t.obs_diff).nunique() == 1), include_groups=False)
|
| 336 |
+
COMMON = set(elig[elig].index)
|
| 337 |
+
CT["common"] = [(s, c) in COMMON for s, c in zip(CT.state, CT.contrast)]
|
| 338 |
+
CT.to_csv(DST / f"{PFX}contrasts.csv", index=False)
|
| 339 |
+
|
| 340 |
+
# 6. depth check from the per-cell extracts and the benchmark summaries
|
| 341 |
+
states_json = json.loads((PLAN / "tools/states.json").read_text())
|
| 342 |
+
|
| 343 |
+
|
| 344 |
+
def parent_of(lab1: np.ndarray, lab2: np.ndarray, parent: list[str]) -> np.ndarray:
|
| 345 |
+
if parent == ["ALL"]:
|
| 346 |
+
return np.ones(len(lab1), bool)
|
| 347 |
+
return np.isin(lab2, parent) | np.isin(lab1, parent)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
rows = []
|
| 351 |
+
for a in ARMS:
|
| 352 |
+
d = np.load(PLAN / f"work/sepsis/loco/{a}.npz", allow_pickle=False)
|
| 353 |
+
M, lib, l1, l2 = d["markers"], d["lib_measured"], d["aifi_l1"].astype(str), d["aifi_l2"].astype(str)
|
| 354 |
+
syms = list(d["marker_symbols"].astype(str))
|
| 355 |
+
bname = "zs_K1000" if a == ZS else a
|
| 356 |
+
bj = SCORES / bname / "summary.json"
|
| 357 |
+
bench = {}
|
| 358 |
+
if bj.exists():
|
| 359 |
+
pa = json.loads(bj.read_text())["per_arm"][bname]
|
| 360 |
+
bench = {"bench_umi_gen": pa["median_umi_per_cell_scoring_genes"]["generated_pooled"],
|
| 361 |
+
"bench_umi_obs": pa["median_umi_per_cell_scoring_genes"]["observed_pooled"],
|
| 362 |
+
"bench_detected_gen": pa["precision_coverage_depth_matched"]["detected_median_before"]["Q"],
|
| 363 |
+
"bench_detected_obs": pa["precision_coverage_depth_matched"]["detected_median_before"]["R1"],
|
| 364 |
+
"bench_precision": pa["precision_coverage"]["precision"],
|
| 365 |
+
"bench_coverage": pa["precision_coverage"]["coverage"]}
|
| 366 |
+
seen = []
|
| 367 |
+
for st in states_json:
|
| 368 |
+
if st["parent"] in seen:
|
| 369 |
+
continue
|
| 370 |
+
seen.append(st["parent"])
|
| 371 |
+
m = parent_of(l1, l2, st["parent"])
|
| 372 |
+
Xm = M[m]
|
| 373 |
+
det = Xm > 0
|
| 374 |
+
rec = {"arm": SH[a], "parent": "+".join(st["parent"]), "n_cells_all": int(len(lib)),
|
| 375 |
+
"median_lib_all_cells": float(np.median(lib)), "n_parent": int(m.sum()),
|
| 376 |
+
"median_lib_parent": float(np.median(lib[m])),
|
| 377 |
+
"mean_detected_markers_of_%d" % M.shape[1]: float(det.sum(1).mean()),
|
| 378 |
+
"umis_per_detected_marker": float(Xm[det].mean()) if det.any() else np.nan, **bench}
|
| 379 |
+
for gname in ["HLA-DRA", "NKG7", "GZMA", "CCR7", "CR2", "ZEB2", "PLAC8"]:
|
| 380 |
+
rec[f"det_{gname}"] = float(det[:, syms.index(gname)].mean())
|
| 381 |
+
# screen thin constant of the first marker state on this parent
|
| 382 |
+
mk = [x["name"] for x in states_json if x["parent"] == st["parent"] and x["kind"] == "markers"]
|
| 383 |
+
rec["screen_thin"] = float(SUM[(SUM.arm == a) & (SUM.state == mk[0])].thin.iloc[0]) if mk else np.nan
|
| 384 |
+
rec["implied_obs_median_lib_parent"] = rec["median_lib_parent"] / rec["screen_thin"] \
|
| 385 |
+
if rec["screen_thin"] < 1 else np.nan
|
| 386 |
+
rows.append(rec)
|
| 387 |
+
DC = pd.DataFrame(rows)
|
| 388 |
+
DC.to_csv(DST / f"{PFX}depth.csv", index=False)
|
| 389 |
+
|
| 390 |
+
# ------------------------------------------------------------------------------------------------------------------
|
| 391 |
+
# report
|
| 392 |
+
pd.set_option("display.width", 250, "display.max_columns", 40, "display.max_rows", 500)
|
| 393 |
+
f3 = lambda v: "null" if v is None or (isinstance(v, float) and not np.isfinite(v)) else f"{v:.3f}"
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def rline(a: str, s: str, ref: str = "own") -> str:
|
| 397 |
+
r = rat(a, s, ref)
|
| 398 |
+
return (f"{SH[a]:>9}[{ref}] ratio {f3(r.ratio)} ps {f3(r.ratio_ps)} [{f3(r.ci_lo)},{f3(r.ci_hi)}] "
|
| 399 |
+
f"gen {r.gen_state}/{r.gen_parent} obs {r.obsthin_state}/{r.obs_parent} (native {r.obs_native_state})")
|
| 400 |
+
|
| 401 |
+
|
| 402 |
+
def dline(scr: str, comp: str, s: str, var: str = "own") -> str:
|
| 403 |
+
t = DT[(DT.comparison == f"{SH[scr]} vs {SH[comp]}") & (DT.state == s) & (DT.variant == var)].iloc[0]
|
| 404 |
+
return (f"D {SH[scr]}-{SH[comp]} [{var}] {s}: {t.D:+.3f} [{t.D_ci_lo:+.3f},{t.D_ci_hi:+.3f}] "
|
| 405 |
+
f"(raw-point {t.D_rawpoint:+.3f}) ratios {f3(t.ratio_scratch)} vs {f3(t.ratio_comparator)} -> {t.verdict}")
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def cline(a: str, s: str, c: str, var: str = "own") -> str:
|
| 409 |
+
t = CT[(CT.arm == SH[a]) & (CT.state == s) & (CT.contrast == c) & (CT.variant == var)].iloc[0]
|
| 410 |
+
return (f"{SH[a]:>9}[{var}] {s} | {c}: gen {t.gen_diff:+.2f} obs {t.obs_diff:+.2f} "
|
| 411 |
+
f"frac {t.gen_over_obs_diff:+.3f} same={t.same_direction}")
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
say("\n=== cross-1 ===")
|
| 415 |
+
for s in [C1Q, MS1]:
|
| 416 |
+
for a in [S162, L16, L64, F20, F108, XCAL, ZS, OWN5, OWN58]:
|
| 417 |
+
say(rline(a, s))
|
| 418 |
+
say(rline(S162, s, "depth_r16"))
|
| 419 |
+
for comp in [L16, L64, F108, XCAL]:
|
| 420 |
+
say(dline(S162, comp, s))
|
| 421 |
+
say(dline(S162, comp, s, "matched_depth"))
|
| 422 |
+
for a in [S162, L16, L64, F20, F108, XCAL, ZS, OWN5, OWN58]:
|
| 423 |
+
say(cline(a, MS1, "adult"))
|
| 424 |
+
say(cline(S162, MS1, "adult", "depth_r16"))
|
| 425 |
+
for a in [S162, L16, L64, F20, F108, XCAL, ZS, OWN5, OWN58]:
|
| 426 |
+
for c in ["adult", "paediatric", "all"]:
|
| 427 |
+
say(cline(a, C1Q, c))
|
| 428 |
+
|
| 429 |
+
say("\n=== cross-2 ===")
|
| 430 |
+
for s in [CYC_TNK, CYC_MONO, CYC_ACT, PROLIF]:
|
| 431 |
+
for a in [S162, L16, L64, F20, F108, XCAL, ZS, OWN5, OWN58]:
|
| 432 |
+
say(rline(a, s))
|
| 433 |
+
for ref in ["depth_r16", "depth_r64", "depth_full108k", "depth_full20k", "depth_xcal"]:
|
| 434 |
+
say(rline(S162, s, ref))
|
| 435 |
+
for comp in [L16, L64, F108, XCAL, F20]:
|
| 436 |
+
for var in ["own", "matched_depth"] + (["matched_depth_xcalref"] if comp == XCAL else []):
|
| 437 |
+
say(dline(S162, comp, s, var))
|
| 438 |
+
|
| 439 |
+
say("\n=== cross-3 ===")
|
| 440 |
+
say(AG[AG.kind == "mean_abs_log2"][["name", "variant", "value", "ci_lo", "ci_hi", "n_within_2fold",
|
| 441 |
+
"mean_abs_log2_rawpoint"]].to_string(index=False))
|
| 442 |
+
say(AG[AG.kind == "mean_D"][["name", "variant", "value", "ci_lo", "ci_hi"]].to_string(index=False))
|
| 443 |
+
cnt = (DT[~DT.is_control].groupby(["comparison", "variant"]).verdict.value_counts().unstack(fill_value=0))
|
| 444 |
+
say(cnt.to_string())
|
| 445 |
+
for comp in ["s162k vs r16", "s162k vs r64", "s162k vs full108k", "s162k vs xcal", "s162k vs full20k"]:
|
| 446 |
+
for var in ["own", "matched_depth", "matched_depth_xcalref"]:
|
| 447 |
+
t = DT[(DT.comparison == comp) & (DT.variant == var) & ~DT.is_control]
|
| 448 |
+
if len(t):
|
| 449 |
+
say(f"{comp} [{var}] scratch_closer: {list(t[t.verdict == 'scratch_closer'].state)} | comparator_closer: "
|
| 450 |
+
f"{list(t[t.verdict == 'comparator_closer'].state)}")
|
| 451 |
+
|
| 452 |
+
say("\n=== cross-4 ===")
|
| 453 |
+
say(DC[["arm", "parent", "n_parent", "median_lib_all_cells", "median_lib_parent", "mean_detected_markers_of_73",
|
| 454 |
+
"umis_per_detected_marker", "det_HLA-DRA", "det_NKG7", "det_GZMA", "screen_thin",
|
| 455 |
+
"implied_obs_median_lib_parent"]].round(4).to_string(index=False))
|
| 456 |
+
say(DC.drop_duplicates("arm")[["arm", "median_lib_all_cells", "bench_umi_gen", "bench_umi_obs", "bench_detected_gen",
|
| 457 |
+
"bench_detected_obs", "bench_precision", "bench_coverage"]].to_string(index=False))
|
| 458 |
+
thin_tab = SUM.pivot(index="state", columns="arm", values="thin")
|
| 459 |
+
mk_states = [x["name"] for x in states_json if x["kind"] == "markers"]
|
| 460 |
+
lab_states = [x["name"] for x in states_json if x["kind"] == "label"]
|
| 461 |
+
say("pretrained (r16/r64/full20k/full108k) thin range over marker states:",
|
| 462 |
+
float(thin_tab.loc[mk_states, PRE].min().min()), float(thin_tab.loc[mk_states, PRE].max().max()))
|
| 463 |
+
say("pretrained thin range over monocyte+T parents (C1Q, cycling T/NK, ISG-high T):",
|
| 464 |
+
float(thin_tab.loc[[C1Q, CYC_TNK, ISG_T, CYC_ACT], PRE].min().min()),
|
| 465 |
+
float(thin_tab.loc[[C1Q, CYC_TNK, ISG_T, CYC_ACT], PRE].max().max()))
|
| 466 |
+
say("scratch thin values:", sorted(set(thin_tab.loc[:, SCRATCH].to_numpy().ravel().tolist())))
|
| 467 |
+
for s in mk_states:
|
| 468 |
+
own_r = rat(S162, s).ratio
|
| 469 |
+
deps = {SH[r]: rat(S162, s, f"depth_{SH[r]}").ratio for r in PRE}
|
| 470 |
+
say(f"{s:<50} s162k own {f3(own_r)} | at depth " + " ".join(f"{k} {f3(v)}" for k, v in deps.items())
|
| 471 |
+
+ f" | factor r16/own {f3(deps['r16'] / own_r) if own_r > 0 else 'null'}")
|
| 472 |
+
for s in lab_states:
|
| 473 |
+
vals = {SH[a]: int(X[a, s]["obsthin_state"].sum()) for a in ARMS}
|
| 474 |
+
say(f"label state {s}: obsthin sums across arms {set(vals.values())}; obs_state {int(X[ZS, s]['obs_state'].sum())}")
|
| 475 |
+
|
| 476 |
+
say("\n=== cross-5 ===")
|
| 477 |
+
for s in [HSPC, CYTO4, PB_LAB, ISG_T]:
|
| 478 |
+
say(f"{s}: obsthin_state over 12 arms: min {min(int(X[a, s]['obsthin_state'].sum()) for a in ARMS)} max "
|
| 479 |
+
f"{max(int(X[a, s]['obsthin_state'].sum()) for a in ARMS)}; native {int(X[ZS, s]['obs_state'].sum())}")
|
| 480 |
+
for a in [S162, L16, L64, F20, F108, XCAL, ZS, OWN58]:
|
| 481 |
+
say(rline(a, s))
|
| 482 |
+
say(rline(S162, s, "depth_r16"))
|
| 483 |
+
for comp in [L16, L64, F108, XCAL, F20]:
|
| 484 |
+
for var in ["own", "matched_depth"]:
|
| 485 |
+
say(dline(S162, comp, s, var))
|
| 486 |
+
for comp in ["s162k vs r16", "s162k vs r64", "s162k vs full108k", "s162k vs xcal"]:
|
| 487 |
+
for var in ["own", "matched_depth", "matched_depth_xcalref"]:
|
| 488 |
+
t = DT[(DT.comparison == comp) & (DT.variant == var) & ~DT.is_control & (DT.verdict == "scratch_closer")]
|
| 489 |
+
if var in set(DT[DT.comparison == comp].variant):
|
| 490 |
+
say(f"scratch significantly closer: {comp} [{var}]: " + "; ".join(
|
| 491 |
+
f"{r.state} (scr {f3(r.ratio_scratch)} vs comp {f3(r.ratio_comparator)})" for r in t.itertuples()))
|
| 492 |
+
|
| 493 |
+
say("\n=== cross-6 ===")
|
| 494 |
+
say(SPA.pivot(index="state", columns="arm", values="rho")[[SH[a] for a in ARMS]].round(3).to_string())
|
| 495 |
+
for comp in ["s162k vs r16", "s162k vs r64", "s162k vs full108k", "s162k vs xcal", "s162k vs full20k",
|
| 496 |
+
"s162k vs own58"]:
|
| 497 |
+
t = SPD[(SPD.comparison == comp) & ~SPD.is_control]
|
| 498 |
+
say(f"{comp}: sig {int((t.verdict != 'ns').sum())}/13 ({t[t.verdict != 'ns'][['state', 'rho_scratch', 'rho_comparator', 'diff', 'ci_lo', 'ci_hi', 'verdict']].round(3).to_dict('records')}), "
|
| 499 |
+
f"range {t['diff'].min():+.3f}..{t['diff'].max():+.3f}, mean {t['diff'].mean():+.3f}")
|
| 500 |
+
say(" min:", t.loc[t['diff'].idxmin(), ["state", "rho_scratch", "rho_comparator"]].tolist(),
|
| 501 |
+
"max:", t.loc[t['diff'].idxmax(), ["state", "rho_scratch", "rho_comparator"]].tolist())
|
| 502 |
+
rr = SPA[SPA.state.isin(RARE)].pivot(index="state", columns="arm", values="rho")
|
| 503 |
+
say("mean rho over 13 rare states per arm:", rr.mean().round(3).to_dict())
|
| 504 |
+
say("median rho per arm:", rr.median().round(3).to_dict())
|
| 505 |
+
cross_arms = [SH[a] for a in [ZS, XCAL, L16, L64, F20, F108] + SCRATCH]
|
| 506 |
+
vals = rr[cross_arms].to_numpy().ravel()
|
| 507 |
+
vals = vals[np.isfinite(vals)]
|
| 508 |
+
say(f"cross-cohort arms rho: n {vals.size}, in [0,0.55]: {((vals >= 0) & (vals <= 0.55)).sum()}, <0: "
|
| 509 |
+
f"{(vals < 0).sum()}, >0.55: {(vals > 0.55).sum()}, max {vals.max():.3f}")
|
| 510 |
+
say("per state, arm with max rho:", rr.idxmax(axis=1).to_dict())
|
| 511 |
+
|
| 512 |
+
say("\n=== cross-7 ===")
|
| 513 |
+
say(f"common set size: {len(COMMON)}")
|
| 514 |
+
say(sorted(COMMON))
|
| 515 |
+
rows = []
|
| 516 |
+
for a in ARMS:
|
| 517 |
+
for var in ["own"] + (["depth_r16"] if a in SCRATCH else []):
|
| 518 |
+
t = CT[(CT.arm == SH[a]) & (CT.variant == var) & CT.common]
|
| 519 |
+
k = t[t.same_direction]
|
| 520 |
+
rows.append({"arm": SH[a], "variant": var, "n": len(t), "kept": len(k), "reversed": int(t.reversed.sum()),
|
| 521 |
+
"median_frac_kept": float(k.gen_over_obs_diff.median()) if len(k) else np.nan,
|
| 522 |
+
"median_frac_all_common_signed": float(t.gen_over_obs_diff.median()),
|
| 523 |
+
"mean_frac_all_common_signed": float(t.gen_over_obs_diff.mean()),
|
| 524 |
+
"lost": "; ".join(f"{r.state}|{r.contrast}" for r in t[~t.same_direction].itertuples())})
|
| 525 |
+
CC = pd.DataFrame(rows)
|
| 526 |
+
CC.to_csv(DST / f"{PFX}contrast_counts.csv", index=False)
|
| 527 |
+
say(CC.drop(columns="lost").round(3).to_string(index=False))
|
| 528 |
+
for r in CC.itertuples():
|
| 529 |
+
say(f" lost {r.arm}[{r.variant}]: {r.lost}")
|
| 530 |
+
com = CT[CT.common & (CT.variant == "own")]
|
| 531 |
+
keepers = com.pivot_table(index=["state", "contrast"], columns="arm", values="same_direction", aggfunc="first")
|
| 532 |
+
say(keepers[[SH[a] for a in ARMS]].astype(int).to_string())
|
| 533 |
+
obs_lost = com[com.state.isin([PROLIF, PB_MK])].groupby(["state", "contrast"]).obs_diff.agg(["min", "max"])
|
| 534 |
+
say(obs_lost.to_string())
|
| 535 |
+
for (s, c) in sorted(COMMON):
|
| 536 |
+
if s in (C1Q,):
|
| 537 |
+
say(cline(S162, s, c), "|", cline(L16, s, c))
|
| 538 |
+
|
| 539 |
+
say("\n=== cross-8 ===")
|
| 540 |
+
for s in RARE:
|
| 541 |
+
say(f"{s:<36} " + " -> ".join(f3(rat(a, s).ratio) for a in SCRATCH))
|
| 542 |
+
for a in SCRATCH:
|
| 543 |
+
t = AG[(AG.kind == "mean_abs_log2") & (AG.name == SH[a]) & (AG.variant == "own")].iloc[0]
|
| 544 |
+
say(f"{SH[a]} mean|log2| {t.value:.3f} [{t.ci_lo:.3f},{t.ci_hi:.3f}]")
|
| 545 |
+
for comp in ["s162k vs s50k", "s162k vs s100k", "s162k vs s150k", "s50k vs r16", "s162k vs r16"]:
|
| 546 |
+
say(AG[(AG.kind == "mean_D") & (AG.name == comp)][["name", "variant", "value", "ci_lo", "ci_hi"]].to_string(
|
| 547 |
+
index=False))
|
| 548 |
+
for var in ["own", "both_at_r16_depth"]:
|
| 549 |
+
t = DT[(DT.comparison == "s162k vs s50k") & (DT.variant == var) & ~DT.is_control]
|
| 550 |
+
say(f"s162k vs s50k [{var}] s50k closer (comparator_closer): {list(t[t.verdict == 'comparator_closer'].state)}; "
|
| 551 |
+
f"s162k closer: {list(t[t.verdict == 'scratch_closer'].state)}")
|
| 552 |
+
say(DC.drop_duplicates("arm")[["arm", "median_lib_all_cells", "bench_coverage", "bench_precision"]].to_string(
|
| 553 |
+
index=False))
|
| 554 |
+
|
| 555 |
+
(DST / f"{PFX}report.txt").write_text("\n".join(LOG) + "\n")
|
paper-releases/pbisc-diffusion/updates/20261005T142225Z-rare-states-scratch-vs-pretrained/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/out/scratch_vs_lora_20261005/verify_recompute_within_donorweight.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Weighting sensitivity (verify lens; CPU only; 2026-10-05).
|
| 3 |
+
|
| 4 |
+
The claimed fidelity pools cells: generated % = sum gen_state / sum gen_parent (each donor ~1,500 generated cells) and
|
| 5 |
+
observed % = sum obsthin_state / sum obs_parent (each donor weighted by its observed parent count, which varies
|
| 6 |
+
widely). Here every donor gets equal weight on both sides: ratio_dw = mean_d(gen %) / mean_d(obsthin %), donors with
|
| 7 |
+
an undefined % dropped on that side. Fidelity |log2 ratio_dw| (a 0.5-cell pseudocount per donor-mean is not applied;
|
| 8 |
+
no state has a zero mean). Mean D over the 13 rare states with the same donor bootstrap as the main recompute.
|
| 9 |
+
Output: verify_recompute_within_donorweight.csv
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import os
|
| 14 |
+
|
| 15 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 16 |
+
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pandas as pd
|
| 21 |
+
|
| 22 |
+
PLAN = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/rare_states_screen_20261004")
|
| 23 |
+
OUT = PLAN / "out"
|
| 24 |
+
V = OUT / "scratch_vs_lora_20261005"
|
| 25 |
+
SEED, B = 20261005, 2000
|
| 26 |
+
P = pd.read_csv(OUT / "sepsis_fold0_per_donor.csv")
|
| 27 |
+
STATES = list(dict.fromkeys(P.state))
|
| 28 |
+
CTRL = {"ISG-high monocyte (positive control)", "Platelet signal in monocytes (negative control)"}
|
| 29 |
+
RARE = [s for s in STATES if s not in CTRL]
|
| 30 |
+
DONORS = sorted(P.donor.unique())
|
| 31 |
+
ARMS = list(dict.fromkeys(P.arm))
|
| 32 |
+
MAIN = [("5 pairs", "scratch_n5__raw", "lora_n5__raw"),
|
| 33 |
+
("58 pairs vs LoRA", "scratch_full__raw", "real_lora__raw"),
|
| 34 |
+
("58 pairs vs full FT", "scratch_full__raw", "real_full__raw"),
|
| 35 |
+
("recipes", "scratch_recipe__raw", "lora_recipe__raw"),
|
| 36 |
+
("zs ref: 5 pairs", "scratch_n5__raw", "zs__raw"),
|
| 37 |
+
("zs ref: 58 pairs", "scratch_full__raw", "zs__raw"),
|
| 38 |
+
("zs ref: recipes", "scratch_recipe__raw", "zs__raw")]
|
| 39 |
+
PCT = {(a, s): g.set_index("donor").loc[DONORS, ["gen_pct", "obsthin_pct"]].to_numpy(float)
|
| 40 |
+
for (a, s), g in P.groupby(["arm", "state"])}
|
| 41 |
+
idx = np.random.default_rng(SEED).integers(0, 17, (B, 17))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def fid_dw(M: np.ndarray) -> np.ndarray:
|
| 45 |
+
"""M: (..., n, 2) per-donor pcts -> |log2(mean gen % / mean obs %)| (nan-mean over donors)."""
|
| 46 |
+
with np.errstate(divide="ignore", invalid="ignore"):
|
| 47 |
+
return np.abs(np.log2(np.nanmean(M[..., 0], -1) / np.nanmean(M[..., 1], -1)))
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
rows = []
|
| 51 |
+
for a in ARMS:
|
| 52 |
+
for s in STATES:
|
| 53 |
+
M = PCT[(a, s)]
|
| 54 |
+
rows.append({"what": "ratio", "arm": a, "state": s,
|
| 55 |
+
"ratio_donor_weighted": float(np.nanmean(M[:, 0]) / np.nanmean(M[:, 1]))})
|
| 56 |
+
R = pd.DataFrame(rows)
|
| 57 |
+
piv = R.pivot(index="state", columns="arm", values="ratio_donor_weighted")[ARMS]
|
| 58 |
+
for name, sa, pa in MAIN:
|
| 59 |
+
dst = [float(fid_dw(PCT[(sa, s)]) - fid_dw(PCT[(pa, s)])) for s in RARE]
|
| 60 |
+
boot = np.mean(np.stack([fid_dw(PCT[(sa, s)][idx]) - fid_dw(PCT[(pa, s)][idx]) for s in RARE], 1), 1)
|
| 61 |
+
lo, hi = np.nanpercentile(boot, [2.5, 97.5])
|
| 62 |
+
rows.append({"what": "mean D (13 rare states, donor-weighted)", "arm": f"{sa} - {pa}", "state": name,
|
| 63 |
+
"ratio_donor_weighted": np.nan, "D": float(np.mean(dst)), "ci_lo": lo, "ci_hi": hi,
|
| 64 |
+
"mean_abs_log2_scratch": float(np.mean([fid_dw(PCT[(sa, s)]) for s in RARE])),
|
| 65 |
+
"mean_abs_log2_pretrained": float(np.mean([fid_dw(PCT[(pa, s)]) for s in RARE]))})
|
| 66 |
+
out = pd.DataFrame(rows)
|
| 67 |
+
out.to_csv(V / "verify_recompute_within_donorweight.csv", index=False)
|
| 68 |
+
with pd.option_context("display.width", 250, "display.max_rows", 200, "display.max_columns", 20):
|
| 69 |
+
print(piv.round(3).to_string())
|
| 70 |
+
print(out[out.what != "ratio"].drop(columns=["ratio_donor_weighted"]).round(3).to_string(index=False))
|