junidude14 commited on
Commit
ae545b3
·
verified ·
1 Parent(s): 67bdade

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261004T174508Z-sepsis-rare-states/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/tools/sepsis_states.py ADDED
@@ -0,0 +1,231 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Rare states on held-out donors of the Ye 2026 sepsis paired cohort (real bulk, LoRA; CPU only; 2026-10-05).
3
+
4
+ Arms: the pooled, cross-fitted arms of plans/paired_finetune_intradataset_20260927 (generated/ye2026_sepsis/pooled/
5
+ <arm>.npz on spark-0110; every donor's cells come from the fold model that never trained on it; 82 donors x 1,500
6
+ cells; real bulk at K = 1,000). No new generation. The same scANVI labels as the benchmark are reused
7
+ (scores/ye2026_sepsis/pooled/arms/<arm>/labels), so the generated counts must be the benchmark's own Poisson read-out:
8
+ one draw over the whole NPZ (poisson_readout.poisson_integerise, seed 20260916, rows in NPZ order), then the rows of
9
+ generated_cells.parquet. `extract` checks this cell by cell against the benchmark's recorded umi_scoring_genes.
10
+
11
+ extract ARM < NPZ bytes on stdin (ssh spark-0110 cat .../pooled/ARM.npz | sepsis_states.py extract ARM)
12
+ sha256 of the stream must equal the pooled receipt (generated/ye2026_sepsis/pooled/ARM.log, output_sha256).
13
+ Writes work/sepsis/ARM.npz: per labelled cell, counts of every marker gene of tools/states.json, the library on
14
+ the dataset's measured panel genes, donor, AIFI L1/L2. Nothing large is written.
15
+ analyze ARM [ARM ...]
16
+ Observed side: every cell of the scored donors (data/ye2026_sepsis/cells_panel6k.npz, benchmark observed labels).
17
+ States, thinning and counts exactly as tools/screen.py (one thinning constant per arm and marker state: observed
18
+ parent median library -> generated parent median library on the measured panel genes; label states as they
19
+ are). Per arm and state: "X of N" on both sides, generated / observed, Spearman over donors, and contrasts
20
+ (adult sepsis vs adult HC, paediatric sepsis vs paediatric HC, all sepsis vs all controls incl. ICU controls).
21
+ Outputs: out/sepsis_{summary,contrasts,per_donor}.csv
22
+ """
23
+ from __future__ import annotations
24
+
25
+ import hashlib
26
+ import importlib.util
27
+ import io
28
+ import json
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ import numpy as np
33
+ import pandas as pd
34
+ import scipy.sparse as sp
35
+ from scipy.stats import spearmanr
36
+
37
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
38
+ from screen import call_state, parent_mask, state_cols # noqa: E402
39
+
40
+ PLAN = Path(__file__).resolve().parents[1]
41
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
42
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
43
+ DATA = FT / "data/ye2026_sepsis"
44
+ POOLED_GEN = FT / "generated/ye2026_sepsis/pooled"
45
+ POOLED_SCORES = FT / "scores/ye2026_sepsis/pooled/arms"
46
+ REF = FT / "scoring_cache/ye2026_sepsis/reference.npz"
47
+ OBS_LABELS = FT / "scoring_cache/ye2026_sepsis/observed_labels/labels/labels.parquet"
48
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
49
+ "canonical_genes.tsv")
50
+ POISSON_PY = M8 / "plans/aifi_scanvi_rebuild_20260916/poisson_readout.py"
51
+ POISSON_SEED = 20260916
52
+ THIN_SEED = 20261004
53
+ WORK = PLAN / "work/sepsis"
54
+ CONTRASTS = [("adult sepsis vs adult HC", ["adult_sepsis"], ["adult_HC"]),
55
+ ("paediatric sepsis vs paediatric HC", ["ped_sepsis"], ["ped_HC"]),
56
+ ("all sepsis vs all controls", ["adult_sepsis", "ped_sepsis"],
57
+ ["adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"])]
58
+
59
+
60
+ def load_poisson():
61
+ spec = importlib.util.spec_from_file_location("poisson_readout", POISSON_PY)
62
+ mod = importlib.util.module_from_spec(spec)
63
+ spec.loader.exec_module(mod)
64
+ return mod
65
+
66
+
67
+ def marker_genes(states: list[dict]) -> list[str]:
68
+ out = []
69
+ for st in states:
70
+ for g in st.get("genes", []) + [x for grp in st.get("require_any", []) for x in grp] + st.get("exclude", []):
71
+ if g not in out:
72
+ out.append(g)
73
+ return out
74
+
75
+
76
+ def panel_setup(states: list[dict]) -> tuple[np.ndarray, np.ndarray, list[str], np.ndarray]:
77
+ """6k panel ids, measured-gene mask (any sample of the dataset), marker symbols present, their panel columns."""
78
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
79
+ panel = d["panel_gene_ids"].astype(str)
80
+ measured = d["panel_measured"].any(0)
81
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
82
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
83
+ pos = {g: i for i, g in enumerate(panel)}
84
+ syms = [g for g in marker_genes(states) if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
85
+ return panel, measured, syms, np.asarray([pos[sym2id[g]] for g in syms], dtype=np.int64)
86
+
87
+
88
+ def cmd_extract(arm: str) -> None:
89
+ states = json.loads((PLAN / "tools/states.json").read_text())
90
+ panel, measured, syms, cols = panel_setup(states)
91
+ raw = sys.stdin.buffer.read()
92
+ sha = hashlib.sha256(raw).hexdigest()
93
+ want = json.loads((POOLED_GEN / f"{arm}.log").read_text())["output_sha256"]
94
+ if sha != want:
95
+ raise SystemExit(f"{arm}: streamed NPZ sha256 {sha[:12]} != pooled receipt {want[:12]}")
96
+ d = np.load(io.BytesIO(raw), allow_pickle=False)
97
+ del raw
98
+ if not np.array_equal(d["gene_ids"].astype(str), panel):
99
+ raise SystemExit(f"{arm}: NPZ gene_ids differ from the 6k panel")
100
+ rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
101
+ n_rows = rates.shape[0]
102
+ full = load_poisson().poisson_integerise(rates, seed=POISSON_SEED, chunk_rows=4096)
103
+ del rates
104
+ gc = pd.read_parquet(POOLED_SCORES / f"{arm}/generated_cells.parquet")
105
+ lab = pd.read_parquet(POOLED_SCORES / f"{arm}/labels/labels.parquet")
106
+ if len(gc) != len(lab) or not (lab.sample_id.astype(str).str.removesuffix("|generated").values == gc.donor.values).all():
107
+ raise SystemExit(f"{arm}: generated_cells and labels are not row-aligned")
108
+ X = full[gc.npz_row.to_numpy()].tocsr()
109
+ del full
110
+ ref = np.load(REF, allow_pickle=False)
111
+ umi = np.asarray(X[:, ref["score_idx"]].sum(1)).ravel()
112
+ if not np.array_equal(umi, gc.umi_scoring_genes.to_numpy()):
113
+ bad = int((umi != gc.umi_scoring_genes.to_numpy()).sum())
114
+ raise SystemExit(f"{arm}: Poisson read-out does not reproduce the benchmark ({bad} cells differ)")
115
+ lib = np.asarray(X[:, np.flatnonzero(measured)].sum(1)).ravel()
116
+ M = X[:, cols].toarray().astype(np.int32)
117
+ WORK.mkdir(parents=True, exist_ok=True)
118
+ np.savez_compressed(WORK / f"{arm}.npz", markers=M, marker_symbols=np.asarray(syms), lib_measured=lib,
119
+ donor=np.asarray(gc.donor, dtype=str), aifi_l1=np.asarray(lab.aifi_l1, dtype=str),
120
+ aifi_l2=np.asarray(lab.aifi_l2, dtype=str),
121
+ receipt=json.dumps({"arm": arm, "npz_sha256": sha, "npz_rows": int(n_rows),
122
+ "cells": int(len(gc)), "poisson_seed": POISSON_SEED,
123
+ "umi_scoring_genes_reproduced": True}))
124
+ print(json.dumps({"arm": arm, "sha256_ok": True, "cells": int(len(gc)), "donors": int(gc.donor.nunique()),
125
+ "poisson_reproduced": True, "median_lib_measured": float(np.median(lib))}))
126
+
127
+
128
+ def observed(states: list[dict], donors: list[str]) -> dict:
129
+ _, measured, syms, cols = panel_setup(states)
130
+ d = np.load(DATA / "cells_panel6k.npz", allow_pickle=False)
131
+ X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
132
+ obs = pd.read_parquet(DATA / "cells_obs.parquet", columns=["sample_id", "group"])
133
+ lab = pd.read_parquet(OBS_LABELS)
134
+ if len(lab) != X.shape[0] or not (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all():
135
+ raise SystemExit("observed labels not aligned with cells_panel6k.npz")
136
+ keep = np.flatnonzero(obs.sample_id.isin(donors).to_numpy())
137
+ Xk = X[keep]
138
+ return {"markers": Xk[:, cols].toarray().astype(np.int32), "marker_symbols": syms,
139
+ "lib": np.asarray(Xk[:, np.flatnonzero(measured)].sum(1)).ravel(),
140
+ "donor": obs.sample_id.to_numpy()[keep].astype(str),
141
+ "lab": lab.iloc[keep][["aifi_l1", "aifi_l2"]].reset_index(drop=True),
142
+ "groups": obs.drop_duplicates("sample_id").set_index("sample_id").group}
143
+
144
+
145
+ def cmd_analyze(arms: list[str]) -> None:
146
+ states = json.loads((PLAN / "tools/states.json").read_text())
147
+ gens = {a: np.load(WORK / f"{a}.npz", allow_pickle=False) for a in arms}
148
+ donors = sorted(set(gens[arms[0]]["donor"]))
149
+ for a in arms:
150
+ if sorted(set(gens[a]["donor"])) != donors:
151
+ raise SystemExit(f"{a}: scored donors differ from {arms[0]}")
152
+ ob = observed(states, donors)
153
+ groups = ob["groups"]
154
+ rng = np.random.default_rng(THIN_SEED)
155
+ per, summ, con = [], [], []
156
+ for arm in arms:
157
+ g = gens[arm]
158
+ syms = list(g["marker_symbols"].astype(str))
159
+ if syms != ob["marker_symbols"]:
160
+ raise SystemExit(f"{arm}: marker columns differ from the observed side")
161
+ sym2col = {s: i for i, s in enumerate(syms)}
162
+ lg = pd.DataFrame({"aifi_l1": g["aifi_l1"], "aifi_l2": g["aifi_l2"]})
163
+ for st in states:
164
+ po, pg = parent_mask(ob["lab"], st["parent"]), parent_mask(lg, st["parent"])
165
+ if st["kind"] == "label":
166
+ ho = ob["lab"].aifi_l2.isin(st["labels"]).to_numpy() & po
167
+ hg = lg.aifi_l2.isin(st["labels"]).to_numpy() & pg
168
+ ht, thin = ho, 1.0
169
+ else:
170
+ ident = {s: s for s in syms}
171
+ _, pcols, req, exc = state_cols(st, ident, sym2col)
172
+ c = pcols + [x for r in req for x in r] + exc
173
+ thin = min(1.0, float(np.median(g["lib_measured"][pg])) / float(np.median(ob["lib"][po])))
174
+ co = ob["markers"][:, c].astype(np.int64)
175
+ ho = call_state(co, st, len(pcols), req, exc) & po
176
+ ct = rng.binomial(co, thin) if thin < 1.0 else co
177
+ ht = call_state(ct, st, len(pcols), req, exc) & po
178
+ hg = call_state(g["markers"][:, c], st, len(pcols), req, exc) & pg
179
+ rows = []
180
+ for s in donors:
181
+ mo, mg = ob["donor"] == s, g["donor"] == s
182
+ rows.append({"arm": arm, "state": st["name"], "donor": s, "group": groups.get(s),
183
+ "obs_parent": int((po & mo).sum()), "obs_state": int((ho & mo).sum()),
184
+ "obsthin_state": int((ht & mo).sum()),
185
+ "gen_parent": int((pg & mg).sum()), "gen_state": int((hg & mg).sum())})
186
+ t = pd.DataFrame(rows)
187
+ t["obsthin_pct"] = 100 * t.obsthin_state / t.obs_parent.where(t.obs_parent > 0)
188
+ t["gen_pct"] = 100 * t.gen_state / t.gen_parent.where(t.gen_parent > 0)
189
+ per.append(t)
190
+ ok = t[["gen_pct", "obsthin_pct"]].dropna()
191
+ rho = float(spearmanr(ok.gen_pct, ok.obsthin_pct).correlation) if len(ok) > 2 else np.nan
192
+ ro = 100 * t.obsthin_state.sum() / max(t.obs_parent.sum(), 1)
193
+ rg = 100 * t.gen_state.sum() / max(t.gen_parent.sum(), 1)
194
+ summ.append({"arm": arm, "state": st["name"], "thin": round(thin, 3),
195
+ "gen": f"{int(t.gen_state.sum()):,} / {int(t.gen_parent.sum()):,}",
196
+ "obs_thinned": f"{int(t.obsthin_state.sum()):,} / {int(t.obs_parent.sum()):,}",
197
+ "obs_native_n": int(t.obs_state.sum()), "gen_pct": rg, "obs_pct": ro,
198
+ "gen_over_obs": rg / ro if ro else np.nan, "spearman_donors": rho})
199
+ for name, A, B in CONTRASTS:
200
+ ga, gb = t[t.group.isin(A)], t[t.group.isin(B)]
201
+ con.append({"arm": arm, "state": st["name"], "contrast": name, "n_a": len(ga), "n_b": len(gb),
202
+ "obs_a": f"{int(ga.obsthin_state.sum())} / {int(ga.obs_parent.sum())}",
203
+ "obs_b": f"{int(gb.obsthin_state.sum())} / {int(gb.obs_parent.sum())}",
204
+ "gen_a": f"{int(ga.gen_state.sum())} / {int(ga.gen_parent.sum())}",
205
+ "gen_b": f"{int(gb.gen_state.sum())} / {int(gb.gen_parent.sum())}",
206
+ "obs_diff": ga.obsthin_pct.mean() - gb.obsthin_pct.mean(),
207
+ "gen_diff": ga.gen_pct.mean() - gb.gen_pct.mean()})
208
+ C = pd.DataFrame(con)
209
+ C["same_direction"] = np.sign(C.obs_diff) == np.sign(C.gen_diff)
210
+ S = pd.DataFrame(summ)
211
+ out = PLAN / "out"
212
+ pd.concat(per).to_csv(out / "sepsis_per_donor.csv", index=False)
213
+ S.to_csv(out / "sepsis_summary.csv", index=False)
214
+ C.to_csv(out / "sepsis_contrasts.csv", index=False)
215
+ with pd.option_context("display.width", 250, "display.max_columns", 30, "display.max_rows", 500):
216
+ print(S.round(3).to_string(index=False))
217
+ print(C.round(2).to_string(index=False))
218
+
219
+
220
+ def main() -> int:
221
+ if len(sys.argv) >= 3 and sys.argv[1] == "extract":
222
+ cmd_extract(sys.argv[2])
223
+ elif len(sys.argv) >= 3 and sys.argv[1] == "analyze":
224
+ cmd_analyze(sys.argv[2:])
225
+ else:
226
+ raise SystemExit(__doc__)
227
+ return 0
228
+
229
+
230
+ if __name__ == "__main__":
231
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261004T174508Z-sepsis-rare-states/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/work/sepsis/lora_n10__raw.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3a2c5a2d29ad455d4fef87cc29dcecf478ab7c34419fef1d9e2fa04cb5d4420f
3
+ size 1921265
paper-releases/pbisc-diffusion/updates/20261004T174508Z-sepsis-rare-states/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/work/sepsis/lora_n20__raw.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:10224c17ab9b836eebdedac6824b7a914841f58089a39319cd437d177e85edb4
3
+ size 2013374
paper-releases/pbisc-diffusion/updates/20261004T174508Z-sepsis-rare-states/diffusion/dataset/server_1/model8/plans/rare_states_screen_20261004/work/sepsis/lora_n40__raw.npz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a86169dad04334523f2f5c1e20b1ec33c8078955e466a8bb9aa460ec8e1fa17f
3
+ size 2001975