junidude14 commited on
Commit
c456f14
·
verified ·
1 Parent(s): ad0042a

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261004T003810Z-behcet-pair-recovery/diffusion/dataset/server_1/model8/plans/behcet_pair_recovery_20261004/out/_v1_resid_test/calibration_draws.csv.gz ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:49719b61cd7b9e76769100feef831e4f74e32d5beb4d9aa3ea720878324bc93b
3
+ size 36980
paper-releases/pbisc-diffusion/updates/20261004T003810Z-behcet-pair-recovery/diffusion/dataset/server_1/model8/plans/behcet_pair_recovery_20261004/out/_v1_resid_test/calibration_summary.csv ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cohort,method,threshold,sensitivity,wrong_call_rate,top1_true_rate_shared,mutual_true_rate_shared,nonshared_mutual_rate,all_3_called_rate,draws
2
+ liu2021,onoff,1.3626443024048644,0.36666666666666664,0.00625,1.0,0.9833333333333333,0.71,0.0,20
3
+ liu2021,resid_k0,0.8394240244593645,0.5,0.00625,0.95,0.9333333333333333,0.58,0.05,20
4
+ liu2021,resid_k1,1.220069016273678,0.4666666666666667,0.00625,0.9,0.8833333333333333,0.51,0.05,20
5
+ liu2021,resid_k2,1.2791889420983222,0.4666666666666667,0.00625,0.8333333333333334,0.8333333333333334,0.49,0.05,20
6
+ liu2021,resid_k3,1.5582282806423087,0.13333333333333333,0.00625,0.7,0.6333333333333333,0.46,0.0,20
7
+ ye2026_sepsis,onoff,1.4397104875288682,0.18333333333333332,0.00625,0.6166666666666667,0.5666666666666667,0.71,0.0,20
8
+ ye2026_sepsis,resid_k0,0.7393212842494536,0.18333333333333332,0.00625,0.6333333333333333,0.6,0.66,0.0,20
9
+ ye2026_sepsis,resid_k1,1.8082082324686677,0.15,0.00625,0.7166666666666667,0.7,0.7,0.0,20
10
+ ye2026_sepsis,resid_k2,1.4773404910375751,0.21666666666666667,0.00625,0.65,0.6,0.68,0.0,20
11
+ ye2026_sepsis,resid_k3,1.3144402334737855,0.25,0.00625,0.5833333333333334,0.5166666666666667,0.67,0.0,20
paper-releases/pbisc-diffusion/updates/20261004T003810Z-behcet-pair-recovery/diffusion/dataset/server_1/model8/plans/behcet_pair_recovery_20261004/out/_v1_resid_test/recover_pairs_v1.py ADDED
@@ -0,0 +1,343 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Behçet (Zheng 2022) bulk <-> sc PBMC donor pairing from expression alone, with a calibrated decision rule (CPU only).
3
+
4
+ Question (user, 2026-10-04): can the bulk (GSE198533, 9 BD + 10 HC) and sc PBMC (GSE198616, 4 BD + 4 HC) samples be
5
+ paired, so that PBISC's paired LoRA can be tried on Behçet? The authors state that 3 BD donors are in both, without
6
+ saying which. The datalake rule is: do not infer identity from age / sex; so ages are NOT used to find pairs. They are
7
+ only compared afterwards (tools/unblind_ages.py).
8
+
9
+ Score (same arithmetic as the cohort assemblers' residualised identity test, e.g. processing/liu2021_v1_20261002/code/
10
+ liu2021_assemble.py): genes valid in every bulk and sc row, not on chrY; log2 CPM; within each modality centre and
11
+ remove the top-k sample PCs (computed on expressed genes: bulk mean > 3, sc mean > 1 log2 CPM); keep the TOP_N genes with
12
+ the highest residual variance in both modalities (rank sum); Pearson bulk x sc. k = 0 is centring only.
13
+ A second, independent score uses only on/off genes chosen from the bulk alone (CPM < OFF in >= 2 bulks and >= ON in
14
+ >= 2 bulks; deletion polymorphisms and null-allele eQTLs behave like this), centred log2(CPM + 1), Pearson.
15
+
16
+ Decision rule (frozen before Behçet is scored): an sc sample is paired with bulk b when b is its best bulk, it is b's
17
+ best sc sample (mutual best), and its margin (z of the best minus z of the second-best bulk, z over the bulk rows of
18
+ that sc column) is >= the threshold. The threshold and k come from positive controls with known pairs, drawn to
19
+ Behçet's shape (case bulk 9, control bulk 10, case sc 4, control sc 4, 3 case donors in both; every other slot a
20
+ different donor): Ye 2026 sepsis (Chinese cohort, one 10x library per donor, as Behçet) and Liu 2021 (HTO-pooled
21
+ libraries; control bulk 7 because it has 11 control donors). Ground truth = identity-pass pairs of
22
+ plans/paired_finetune_intradataset_20260927/data/<ds>/pairs.csv. Threshold = the smallest margin at which
23
+ <= 1 % of all sc columns in the draws get a wrong call (a call on a non-shared sc sample, or on the wrong bulk),
24
+ chosen on sepsis; Liu is the replication.
25
+ Outputs: <plan>/out/{calibration_draws.csv, calibration_summary.csv, RULE.json, behcet_scores_k*.csv,
26
+ behcet_calls.csv, behcet_onoff_scores.csv, behcet_top_genes.csv, sex_check.csv, SUMMARY.json}
27
+ usage: recover_pairs.py [--draws N]
28
+ """
29
+ from __future__ import annotations
30
+
31
+ import argparse
32
+ import hashlib
33
+ import json
34
+ import os
35
+ import sys
36
+ from pathlib import Path
37
+
38
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
39
+ raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
40
+
41
+ import h5py
42
+ import numpy as np
43
+ import pandas as pd
44
+ from scipy.stats import rankdata
45
+
46
+ PLAN = Path(__file__).resolve().parents[1]
47
+ OUT = PLAN / "out"
48
+ DL = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing")
49
+ REF = DL / "strict_qc_v1_20260913/reference/canonical_genes.tsv"
50
+ PAIRDATA = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
51
+ "paired_finetune_intradataset_20260927/data")
52
+ BEHCET_INV = DL / "strict_qc_v1_20260913/pairing_audit/GSE198616_published_sample_inventory.csv"
53
+ BEHCET_BULK_META = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/datasets/GSE198533/metadata/"
54
+ "GSE198533_series_matrix.txt.gz")
55
+ TOP_N = 2000
56
+ KS = (0, 1, 2, 3)
57
+ OFF, ON = 0.5, 5.0
58
+ FALSE_CALL_MAX = 0.01
59
+ SEED = 20261004
60
+ CONTROLS = {
61
+ "ye2026_sepsis": {"bulk": DL / "ye2026_sepsis_v1_20260927/bulk/GSE279448_htseq_counts/harmonized.h5ad",
62
+ "sc_dir": DL / "ye2026_sepsis_v1_20260927/singlecell", "sc_key": "sc_gsm",
63
+ "case": ("adult_sepsis", "ped_sepsis"),
64
+ "ctrl": ("adult_HC", "ped_HC", "adult_ICU_ctrl", "ped_ICU_ctrl"),
65
+ "design": dict(case_bulk=9, ctrl_bulk=10, case_sc=4, ctrl_sc=4, shared=3)},
66
+ "liu2021": {"bulk": DL / "liu2021_v1_20261002/bulk/GSE161918_htseq/harmonized.h5ad",
67
+ "sc_dir": DL / "liu2021_v1_20261002/singlecell", "sc_key": "sc_sample",
68
+ "case": ("COVID",), "ctrl": ("HC",),
69
+ "design": dict(case_bulk=9, ctrl_bulk=7, case_sc=4, ctrl_sc=4, shared=3)},
70
+ }
71
+
72
+
73
+ def sha(p: Path) -> str:
74
+ h = hashlib.sha256()
75
+ with open(p, "rb") as f:
76
+ for b in iter(lambda: f.read(1 << 22), b""):
77
+ h.update(b)
78
+ return h.hexdigest()
79
+
80
+
81
+ def text(a) -> list:
82
+ return [x.decode() if isinstance(x, bytes) else str(x) for x in a]
83
+
84
+
85
+ def load_bulk(path: Path):
86
+ import anndata as ad
87
+ a = ad.read_h5ad(path)
88
+ X = np.asarray(a.X, dtype=np.float64)
89
+ V = np.asarray(a.layers["harmonization_valid"]).astype(bool)
90
+ if not np.isfinite(X[V]).all() or (X[V] < 0).any():
91
+ raise SystemExit(f"{path}: invalid values inside the measured mask")
92
+ gsm = a.obs["source_GSM"].astype(str).to_numpy() if "source_GSM" in a.obs else a.obs_names.to_numpy().astype(str)
93
+ return np.where(V, X, 0.0), V, a.obs_names.to_numpy().astype(str), gsm, a.var_names.to_numpy().astype(str)
94
+
95
+
96
+ def load_sc(sc_dir: Path, ids: list[str], gene_ids: np.ndarray):
97
+ S = np.zeros((len(ids), len(gene_ids)))
98
+ V = np.zeros_like(S, dtype=bool)
99
+ n = np.zeros(len(ids), dtype=int)
100
+ for i, g in enumerate(ids):
101
+ s = json.loads((sc_dir / g / "summary.json").read_text())
102
+ if s["status"] != "PASS":
103
+ raise SystemExit(f"{g}: sc status {s['status']}")
104
+ with h5py.File(sc_dir / g / "pseudobulk_per_published_sample.h5", "r") as f:
105
+ if text(f["gene_id"][:]) != list(gene_ids):
106
+ raise SystemExit(f"{g}: gene order")
107
+ if f.attrs["units"] != "UMI_counts" or len(f["sample_id"]) != 1:
108
+ raise SystemExit(f"{g}: units / sample count")
109
+ S[i] = f["qc_review_pass_cells_sum"][0]
110
+ V[i] = f["harmonization_valid"][:].astype(bool)
111
+ n[i] = int(f["n_cells"][1, 0])
112
+ return S, V, n
113
+
114
+
115
+ def logcpm(m: np.ndarray, cols: np.ndarray) -> np.ndarray:
116
+ x = m[:, cols]
117
+ return np.log2(x / x.sum(1, keepdims=True) * 1e6 + 1)
118
+
119
+
120
+ def pearson(a: np.ndarray, b: np.ndarray) -> np.ndarray:
121
+ a = a - a.mean(1, keepdims=True)
122
+ b = b - b.mean(1, keepdims=True)
123
+ a /= np.linalg.norm(a, axis=1, keepdims=True)
124
+ b /= np.linalg.norm(b, axis=1, keepdims=True)
125
+ return a @ b.T
126
+
127
+
128
+ def resid_scores(B, BV, S, SV, chr_y, k: int, return_genes=False):
129
+ common = BV.all(0) & SV.all(0) & ~chr_y
130
+ lb, ls = logcpm(B, common), logcpm(S, common)
131
+ expressed = (lb.mean(0) > 3) & (ls.mean(0) > 1)
132
+ ex = np.flatnonzero(expressed)
133
+
134
+ def resid(x):
135
+ xc = x - x.mean(0)
136
+ if k == 0:
137
+ return xc
138
+ u = np.linalg.svd(xc[:, ex], full_matrices=False)[0][:, :k]
139
+ return xc - u @ (u.T @ xc)
140
+
141
+ rb, rs = resid(lb), resid(ls)
142
+ vb = np.where(expressed, rb.var(0), -1.0)
143
+ vs = np.where(expressed, rs.var(0), -1.0)
144
+ sel = np.argsort(rankdata(-vb) + rankdata(-vs), kind="mergesort")[:TOP_N]
145
+ R = pearson(rb[:, sel], rs[:, sel])
146
+ if return_genes:
147
+ return R, np.flatnonzero(common)[sel], rb[:, sel], rs[:, sel]
148
+ return R
149
+
150
+
151
+ def onoff_scores(B, BV, S, SV, chr_y, return_genes=False):
152
+ common = BV.all(0) & SV.all(0) & ~chr_y
153
+ cb = B[:, common] / B[:, common].sum(1, keepdims=True) * 1e6
154
+ cs = S[:, common] / S[:, common].sum(1, keepdims=True) * 1e6
155
+ sel = ((cb < OFF).sum(0) >= 2) & ((cb >= ON).sum(0) >= 2) & (cs.mean(0) >= 1)
156
+ if sel.sum() < 5:
157
+ R = np.full((B.shape[0], S.shape[0]), np.nan)
158
+ return (R, np.flatnonzero(common)[sel], None, None) if return_genes else R
159
+ lb = np.log2(cb[:, sel] + 1)
160
+ ls = np.log2(cs[:, sel] + 1)
161
+ lb, ls = lb - lb.mean(0), ls - ls.mean(0)
162
+ R = pearson(lb, ls)
163
+ return (R, np.flatnonzero(common)[sel], lb, ls) if return_genes else R
164
+
165
+
166
+ def calls(R: np.ndarray):
167
+ """Per sc column: best bulk, mutual-best flag, margin (z best - z second over bulk rows)."""
168
+ z = (R - R.mean(0)) / R.std(0)
169
+ out = []
170
+ for s in range(R.shape[1]):
171
+ o = np.argsort(-R[:, s])
172
+ out.append({"sc": s, "best": int(o[0]), "mutual": bool(np.argmax(R[o[0]]) == s),
173
+ "margin": float(z[o[0], s] - z[o[1], s]), "r_best": float(R[o[0], s]),
174
+ "second": int(o[1])})
175
+ return out
176
+
177
+
178
+ def draw_design(truth: pd.DataFrame, case, ctrl, d: dict, rng):
179
+ """One Behçet-shaped design: distinct donors in every slot; returns bulk GSMs, sc ids, truth map sc->bulk."""
180
+ t = truth[truth.identity_pass].copy()
181
+ t = t.groupby("donor_id", sort=True).head(1) # one pair per donor
182
+ cases = t[t.group.isin(case)].donor_id.to_numpy()
183
+ ctrls = t[t.group.isin(ctrl)].donor_id.to_numpy()
184
+ need_case = d["case_bulk"] + d["case_sc"] - d["shared"]
185
+ need_ctrl = d["ctrl_bulk"] + d["ctrl_sc"]
186
+ if len(cases) < need_case or len(ctrls) < need_ctrl:
187
+ raise SystemExit(f"design needs {need_case} case / {need_ctrl} control donors, have {len(cases)} / {len(ctrls)}")
188
+ dc = rng.choice(cases, need_case, replace=False)
189
+ dk = rng.choice(ctrls, need_ctrl, replace=False)
190
+ shared = dc[:d["shared"]]
191
+ case_bulk = dc[:d["case_bulk"]]
192
+ case_sc = np.concatenate([shared, dc[d["case_bulk"]:]])
193
+ ctrl_bulk, ctrl_sc = dk[:d["ctrl_bulk"]], dk[d["ctrl_bulk"]:]
194
+ row = t.set_index("donor_id")
195
+ bulk_donors = np.concatenate([case_bulk, ctrl_bulk])
196
+ sc_donors = np.concatenate([case_sc, ctrl_sc])
197
+ return bulk_donors, sc_donors, row
198
+
199
+
200
+ def calibrate(name: str, cfg: dict, chr_y, gene_ids, draws: int, rng) -> pd.DataFrame:
201
+ truth = pd.read_csv(PAIRDATA / name / "pairs.csv")
202
+ truth["identity_pass"] = truth.identity_pass.astype(str).str.lower() == "true"
203
+ Ball, BVall, _, bgsm, bgenes = load_bulk(cfg["bulk"])
204
+ if list(bgenes) != list(gene_ids):
205
+ raise SystemExit(f"{name}: bulk gene order")
206
+ brow = {g: i for i, g in enumerate(bgsm)}
207
+ t = truth[truth.identity_pass]
208
+ sc_ids = sorted(set(t[cfg["sc_key"]].astype(str)))
209
+ Sall, SVall, _ = load_sc(cfg["sc_dir"], sc_ids, gene_ids)
210
+ srow = {g: i for i, g in enumerate(sc_ids)}
211
+ rows = []
212
+ for it in range(draws):
213
+ bulk_donors, sc_donors, row = draw_design(truth, cfg["case"], cfg["ctrl"], cfg["design"], rng)
214
+ bi = [brow[row.loc[d, "bulk_gsm"]] for d in bulk_donors]
215
+ si = [srow[str(row.loc[d, cfg["sc_key"]])] for d in sc_donors]
216
+ true_b = {j: (list(bulk_donors).index(d) if d in set(bulk_donors) else -1) for j, d in enumerate(sc_donors)}
217
+ B, BV, S, SV = Ball[bi], BVall[bi], Sall[si], SVall[si]
218
+ for method, R in [(f"resid_k{k}", resid_scores(B, BV, S, SV, chr_y, k)) for k in KS] + \
219
+ [("onoff", onoff_scores(B, BV, S, SV, chr_y))]:
220
+ if np.isnan(R).all():
221
+ continue
222
+ for c in calls(R):
223
+ tb = true_b[c["sc"]]
224
+ rows.append({"cohort": name, "draw": it, "method": method, "sc_slot": c["sc"], "shared": tb >= 0,
225
+ "best_is_true": bool(tb >= 0 and c["best"] == tb), "mutual": c["mutual"],
226
+ "margin": c["margin"], "r_best": c["r_best"]})
227
+ return pd.DataFrame(rows)
228
+
229
+
230
+ def rule_table(df: pd.DataFrame) -> pd.DataFrame:
231
+ """Per cohort x method: threshold at <= FALSE_CALL_MAX wrong calls per sc column, and the sensitivity there."""
232
+ out = []
233
+ for (cohort, method), g in df.groupby(["cohort", "method"]):
234
+ cand = g[g.mutual]
235
+ wrong = cand[~cand.best_is_true].margin.to_numpy() # non-shared sc called, or shared on the wrong bulk
236
+ right = cand[cand.best_is_true].margin.to_numpy()
237
+ n_cols = len(g)
238
+ thr = np.inf
239
+ for m in np.sort(np.concatenate([wrong, right, [0.0]])):
240
+ if (wrong >= m).sum() / n_cols <= FALSE_CALL_MAX:
241
+ thr = float(m)
242
+ break
243
+ n_shared = int(g.shared.sum())
244
+ out.append({"cohort": cohort, "method": method, "threshold": thr,
245
+ "sensitivity": float((right >= thr).sum() / n_shared),
246
+ "wrong_call_rate": float((wrong >= thr).sum() / n_cols),
247
+ "top1_true_rate_shared": float(g[g.shared].best_is_true.mean()),
248
+ "mutual_true_rate_shared": float((g[g.shared].best_is_true & g[g.shared].mutual).mean()),
249
+ "nonshared_mutual_rate": float(g[~g.shared].mutual.mean()),
250
+ "all_3_called_rate": float(g[g.shared].assign(ok=lambda x: x.best_is_true & x.mutual & (x.margin >= thr))
251
+ .groupby("draw").ok.all().mean()),
252
+ "draws": int(g.draw.nunique())})
253
+ return pd.DataFrame(out)
254
+
255
+
256
+ def main() -> int:
257
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
258
+ ap.add_argument("--draws", type=int, default=1000)
259
+ a = ap.parse_args()
260
+ OUT.mkdir(parents=True, exist_ok=True)
261
+ canon = pd.read_csv(REF, sep="\t", dtype=str)
262
+ gene_ids = canon.gene_id.to_numpy().astype(str)
263
+ sym = canon.gene_symbol.to_numpy().astype(str)
264
+ chr_y = canon.chromosome.astype(str).isin(["Y", "chrY"]).to_numpy()
265
+ rng = np.random.default_rng(SEED)
266
+
267
+ # ---------------- 1. calibration on known pairs (before Behçet is scored)
268
+ cal = pd.concat([calibrate(n, c, chr_y, gene_ids, a.draws, rng) for n, c in CONTROLS.items()], ignore_index=True)
269
+ cal.to_csv(OUT / "calibration_draws.csv.gz", index=False)
270
+ rt = rule_table(cal)
271
+ rt.to_csv(OUT / "calibration_summary.csv", index=False)
272
+ print(rt.round(3).to_string(index=False), flush=True)
273
+ sep = rt[rt.cohort == "ye2026_sepsis"].sort_values(["sensitivity", "method"], ascending=[False, True])
274
+ primary = sep.iloc[0]
275
+ rule = {"primary_method": primary.method, "threshold": primary.threshold,
276
+ "chosen_on": "ye2026_sepsis: highest sensitivity at <= 1 % wrong calls per sc column",
277
+ "secondary_method": "onoff", "secondary_threshold": float(sep[sep.method == "onoff"].threshold.iloc[0]),
278
+ "false_call_max": FALSE_CALL_MAX, "draws": a.draws, "seed": SEED, "top_n": TOP_N,
279
+ "liu2021_at_this_rule": rt[(rt.cohort == "liu2021") & (rt.method == primary.method)].to_dict("records"),
280
+ "frozen_before_behcet": True}
281
+ (OUT / "RULE.json").write_text(json.dumps(rule, indent=1, default=float) + "\n")
282
+
283
+ # ---------------- 2. Behçet, blind to ages
284
+ B, BV, blab, bgsm, bgenes = load_bulk(DL / "strict_qc_v1_20260913/bulk/GSE198533_count/harmonized.h5ad")
285
+ if list(bgenes) != list(gene_ids):
286
+ raise SystemExit("behcet: bulk gene order")
287
+ inv = pd.read_csv(BEHCET_INV)
288
+ inv = inv[inv.source_name == "human PBMC"].sort_values("title")
289
+ sc_ids, sc_lab = inv.gsm.tolist(), inv.title.tolist()
290
+ S, SV, ncell = load_sc(DL / "strict_qc_v1_20260913/singlecell/GSE198616", sc_ids, gene_ids)
291
+ # sex check on chrY genes (canonical axis; XIST is not protein-coding)
292
+ ycpm_b = B[:, chr_y].sum(1) / B.sum(1) * 1e6
293
+ ycpm_s = S[:, chr_y].sum(1) / S.sum(1) * 1e6
294
+ pd.concat([pd.DataFrame({"sample": blab, "modality": "bulk", "chrY_cpm": ycpm_b}),
295
+ pd.DataFrame({"sample": sc_lab, "modality": "sc", "chrY_cpm": ycpm_s, "cells": ncell})]
296
+ ).to_csv(OUT / "sex_check.csv", index=False)
297
+ res = {}
298
+ for k in KS:
299
+ R, genes, rb, rs = resid_scores(B, BV, S, SV, chr_y, k, return_genes=True)
300
+ pd.DataFrame(R, index=blab, columns=sc_lab).to_csv(OUT / f"behcet_scores_k{k}.csv")
301
+ res[f"resid_k{k}"] = (R, genes, rb, rs)
302
+ Ro, og, ob, os_ = onoff_scores(B, BV, S, SV, chr_y, return_genes=True)
303
+ pd.DataFrame(Ro, index=blab, columns=sc_lab).to_csv(OUT / "behcet_onoff_scores.csv")
304
+ res["onoff"] = (Ro, og, ob, os_)
305
+ rows = []
306
+ for method, (R, *_rest) in res.items():
307
+ thr = rule["threshold"] if method == rule["primary_method"] else (
308
+ rule["secondary_threshold"] if method == "onoff" else
309
+ float(rt[(rt.cohort == "ye2026_sepsis") & (rt.method == method)].threshold.iloc[0]))
310
+ for c in calls(R):
311
+ rows.append({"method": method, "sc_sample": sc_lab[c["sc"]], "best_bulk": blab[c["best"]],
312
+ "second_bulk": blab[c["second"]], "r_best": c["r_best"], "mutual": c["mutual"],
313
+ "margin": c["margin"], "threshold": thr,
314
+ "called": bool(c["mutual"] and c["margin"] >= thr)})
315
+ cl = pd.DataFrame(rows)
316
+ cl.to_csv(OUT / "behcet_calls.csv", index=False)
317
+ # genes behind each primary-method call: largest products of standardised residuals
318
+ R, genes, rb, rs = res[rule["primary_method"]]
319
+ zb = rb / rb.std(0)
320
+ zs = rs / rs.std(0)
321
+ tg = []
322
+ for _, r in cl[(cl.method == rule["primary_method"]) & cl.called].iterrows():
323
+ b, s = list(blab).index(r.best_bulk), sc_lab.index(r.sc_sample)
324
+ p = zb[b] * zs[s]
325
+ for j in np.argsort(-p)[:15]:
326
+ tg.append({"sc_sample": r.sc_sample, "bulk": r.best_bulk, "gene": sym[genes[j]], "gene_id": gene_ids[genes[j]],
327
+ "z_bulk": float(zb[b, j]), "z_sc": float(zs[s, j]), "product": float(p[j])})
328
+ pd.DataFrame(tg).to_csv(OUT / "behcet_top_genes.csv", index=False)
329
+ summary = {"rule": rule, "behcet_primary_calls": cl[cl.method == rule["primary_method"]].to_dict("records"),
330
+ "behcet_onoff_calls": cl[cl.method == "onoff"].to_dict("records"),
331
+ "inputs": {"bulk": str(DL / "strict_qc_v1_20260913/bulk/GSE198533_count/harmonized.h5ad"),
332
+ "sc": {l: str(DL / "strict_qc_v1_20260913/singlecell/GSE198616" / g) for g, l in zip(sc_ids, sc_lab)},
333
+ "controls": {n: {"bulk": str(c["bulk"]), "pairs": str(PAIRDATA / n / "pairs.csv")}
334
+ for n, c in CONTROLS.items()}},
335
+ "code_sha256": sha(Path(__file__)), "ages_used": False}
336
+ (OUT / "SUMMARY.json").write_text(json.dumps(summary, indent=1, default=str) + "\n")
337
+ with pd.option_context("display.width", 200):
338
+ print(cl.round(3).to_string(index=False))
339
+ return 0
340
+
341
+
342
+ if __name__ == "__main__":
343
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261004T003810Z-behcet-pair-recovery/diffusion/dataset/server_1/model8/plans/behcet_pair_recovery_20261004/out/_v1_resid_test/recover_pairs_v2a_margin_only.py ADDED
@@ -0,0 +1,387 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Behçet (Zheng 2022) bulk <-> sc PBMC donor pairing from expression alone, with a validated decision rule (CPU only).
3
+
4
+ Question (user, 2026-10-04): can bulk GSE198533 (9 BD + 10 HC) and sc PBMC GSE198616 (4 BD + 4 HC) be paired, so that
5
+ PBISC's paired LoRA can be tried on Behçet? The authors state that 3 BD donors are in both, without saying which.
6
+ Datalake rule: identity is not inferred from age / sex, so ages are NOT used here; tools/unblind_ages.py compares them
7
+ afterwards.
8
+
9
+ v2 (this file). v1 (residual top-variance genes, out/_v1_resid_test/) put the true pair first in only 60-70 % of
10
+ Behçet-shaped sepsis draws, so its rule could not support a call. v2 scores identity only on genes that carry a
11
+ STABLE donor signal, learnt from other cohorts:
12
+
13
+ 1. Identity genes. In cohorts with several timepoints per donor (Imperial ESKD, Liu 2021, Ji 2025, Giroux 2022), take
14
+ the identity-pass pairs of plans/paired_finetune_intradataset_20260927/data/<ds>/pairs.csv and pair each donor's
15
+ bulk at one timepoint with its sc at ANOTHER timepoint, so state shared by one blood draw cannot contribute. Per
16
+ gene: log2(CPM + 1) (genes valid everywhere, not chrY, not in the sex-linked exclusion list), centred within each
17
+ modality and group, Pearson across donors between bulk and sc. Cohorts are combined by Fisher z weighted by
18
+ sqrt(n - 3); genes with mean CPM >= 0.5 in both modalities of every cohort. The top G genes (G = 100, fixed a priori;
19
+ 50 and 200 reported) are the identity set.
20
+ 2. Score of one bulk x sc table: on the identity genes, log2(CPM + 1) centred within modality and disease group (the
21
+ group labels are known in both modalities), Pearson bulk x sc.
22
+ 3. Decision rule: sc sample s is paired with bulk b when b is its best bulk, s is b's best sc sample (mutual best), and
23
+ the margin (z of the best minus z of the second-best bulk, z over the bulk rows of column s) is >= T. T is the
24
+ smallest margin with <= 1 % wrong calls per sc column, in 1,000 Behçet-shaped draws (case bulk 9, control bulk 10,
25
+ case sc 4, control sc 4, 3 case donors in both, every other slot a different donor) of a cohort whose genes were NOT
26
+ used to learn the identity set:
27
+ ye2026_sepsis (primary; Chinese cohort, one 10x library per donor like Behçet): identity set from all 4 cohorts
28
+ liu2021 (replication; HTO-pooled libraries, control bulk 7): identity set learnt without Liu
29
+ Behçet uses the 4-cohort identity set (the one validated on sepsis) and the sepsis threshold.
30
+ Outputs (<plan>/out/): identity_genes_{all4,no_liu}.csv, calibration_draws.csv.gz, calibration_summary.csv, RULE.json,
31
+ behcet_scores.csv (G = 100), behcet_scores_G{50,200}.csv, behcet_calls.csv, behcet_gene_evidence.csv, sex_check.csv,
32
+ SUMMARY.json
33
+ usage: recover_pairs.py [--draws N]
34
+ """
35
+ from __future__ import annotations
36
+
37
+ import argparse
38
+ import hashlib
39
+ import json
40
+ import os
41
+ import sys
42
+ from pathlib import Path
43
+
44
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
45
+ raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
46
+
47
+ import h5py
48
+ import numpy as np
49
+ import pandas as pd
50
+
51
+ PLAN = Path(__file__).resolve().parents[1]
52
+ OUT = PLAN / "out"
53
+ DL = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing")
54
+ REF = DL / "strict_qc_v1_20260913/reference/canonical_genes.tsv"
55
+ PAIRDATA = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/"
56
+ "paired_finetune_intradataset_20260927/data")
57
+ SEXLIST = PAIRDATA / "sex_linked_genes/sex_linked_genes_exclude.csv"
58
+ BEHCET_BULK = DL / "strict_qc_v1_20260913/bulk/GSE198533_count/harmonized.h5ad"
59
+ BEHCET_SC = DL / "strict_qc_v1_20260913/singlecell/GSE198616"
60
+ BEHCET_INV = DL / "strict_qc_v1_20260913/pairing_audit/GSE198616_published_sample_inventory.csv"
61
+ G_PRIMARY, G_SENS = 100, (50, 200)
62
+ MIN_CPM = 0.5
63
+ FALSE_CALL_MAX = 0.01
64
+ SEED = 20261004
65
+ # bulk_key: column of pairs.csv; bulk_match: 'gsm' = harmonized obs source_GSM, 'name' = harmonized obs name
66
+ COHORTS = {
67
+ "imperial_eskd": dict(bulk=DL / "imperial_eskd_v1_20260928/bulk/Zenodo_6497251_htseq_counts/harmonized.h5ad",
68
+ sc_dir=DL / "imperial_eskd_v1_20260928/singlecell", bulk_key="bulk_sample", bulk_match="name",
69
+ sc_key="sc_sample"),
70
+ "liu2021": dict(bulk=DL / "liu2021_v1_20261002/bulk/GSE161918_htseq/harmonized.h5ad",
71
+ sc_dir=DL / "liu2021_v1_20261002/singlecell", bulk_key="bulk_gsm", bulk_match="gsm",
72
+ sc_key="sc_sample", case=("COVID",), ctrl=("HC",),
73
+ design=dict(case_bulk=9, ctrl_bulk=7, case_sc=4, ctrl_sc=4, shared=3)),
74
+ "ji2025_chili": dict(bulk=DL / "ji2025_chili_v1_20260928/bulk/GSE287540_salmon_counts/harmonized.h5ad",
75
+ sc_dir=DL / "ji2025_chili_v1_20260928/singlecell", bulk_key="bulk_gsm", bulk_match="gsm",
76
+ sc_key="sc_gsm"),
77
+ "giroux2022": dict(bulk=DL / "giroux2022_v1_20260928/bulk/GSE206263_featureCounts/harmonized.h5ad",
78
+ sc_dir=DL / "giroux2022_v1_20260928/singlecell", bulk_key="bulk_gsm", bulk_match="gsm",
79
+ sc_key="sc_gsm"),
80
+ "ye2026_sepsis": dict(bulk=DL / "ye2026_sepsis_v1_20260927/bulk/GSE279448_htseq_counts/harmonized.h5ad",
81
+ sc_dir=DL / "ye2026_sepsis_v1_20260927/singlecell", bulk_key="bulk_gsm", bulk_match="gsm",
82
+ sc_key="sc_gsm", case=("adult_sepsis", "ped_sepsis"),
83
+ ctrl=("adult_HC", "ped_HC", "adult_ICU_ctrl", "ped_ICU_ctrl"),
84
+ design=dict(case_bulk=9, ctrl_bulk=10, case_sc=4, ctrl_sc=4, shared=3)),
85
+ }
86
+ LEARN = ("imperial_eskd", "liu2021", "ji2025_chili", "giroux2022")
87
+ TESTS = {"ye2026_sepsis": "all4", "liu2021": "no_liu"}
88
+
89
+
90
+ def sha(p: Path) -> str:
91
+ h = hashlib.sha256()
92
+ with open(p, "rb") as f:
93
+ for b in iter(lambda: f.read(1 << 22), b""):
94
+ h.update(b)
95
+ return h.hexdigest()
96
+
97
+
98
+ def text(a) -> list:
99
+ return [x.decode() if isinstance(x, bytes) else str(x) for x in a]
100
+
101
+
102
+ def load_bulk(path: Path):
103
+ import anndata as ad
104
+ a = ad.read_h5ad(path)
105
+ X = np.asarray(a.X, dtype=np.float64)
106
+ V = np.asarray(a.layers["harmonization_valid"]).astype(bool)
107
+ if not np.isfinite(X[V]).all() or (X[V] < 0).any():
108
+ raise SystemExit(f"{path}: invalid values inside the measured mask")
109
+ names = a.obs_names.to_numpy().astype(str)
110
+ gsm = a.obs["source_GSM"].astype(str).to_numpy() if "source_GSM" in a.obs else np.full(len(names), "")
111
+ return np.where(V, X, 0.0), V, names, gsm, a.var_names.to_numpy().astype(str)
112
+
113
+
114
+ def load_sc(sc_dir: Path, ids: list[str], gene_ids: np.ndarray):
115
+ S = np.zeros((len(ids), len(gene_ids)))
116
+ V = np.zeros_like(S, dtype=bool)
117
+ n = np.zeros(len(ids), dtype=int)
118
+ for i, g in enumerate(ids):
119
+ s = json.loads((sc_dir / g / "summary.json").read_text())
120
+ if s["status"] != "PASS":
121
+ raise SystemExit(f"{g}: sc status {s['status']}")
122
+ with h5py.File(sc_dir / g / "pseudobulk_per_published_sample.h5", "r") as f:
123
+ if text(f["gene_id"][:]) != list(gene_ids):
124
+ raise SystemExit(f"{g}: gene order")
125
+ if f.attrs["units"] != "UMI_counts" or len(f["sample_id"]) != 1:
126
+ raise SystemExit(f"{g}: units / sample count")
127
+ S[i] = f["qc_review_pass_cells_sum"][0]
128
+ V[i] = f["harmonization_valid"][:].astype(bool)
129
+ n[i] = int(f["n_cells"][1, 0])
130
+ return S, V, n
131
+
132
+
133
+ def cpm(m: np.ndarray) -> np.ndarray:
134
+ return m / m.sum(1, keepdims=True) * 1e6
135
+
136
+
137
+ def group_centre(x: np.ndarray, groups) -> np.ndarray:
138
+ x = x.copy()
139
+ groups = np.asarray(groups)
140
+ for g in np.unique(groups):
141
+ m = groups == g
142
+ x[m] -= x[m].mean(0)
143
+ return x
144
+
145
+
146
+ def pearson(a: np.ndarray, b: np.ndarray) -> np.ndarray:
147
+ a = a - a.mean(1, keepdims=True)
148
+ b = b - b.mean(1, keepdims=True)
149
+ a = a / np.linalg.norm(a, axis=1, keepdims=True)
150
+ b = b / np.linalg.norm(b, axis=1, keepdims=True)
151
+ return a @ b.T
152
+
153
+
154
+ class Cohort:
155
+ """One paired cohort: all identity-pass pairs, bulk and sc rows of every pair loaded once."""
156
+
157
+ def __init__(self, name: str, gene_ids: np.ndarray):
158
+ cfg = COHORTS[name]
159
+ self.name, self.cfg = name, cfg
160
+ p = pd.read_csv(PAIRDATA / name / "pairs.csv", dtype=str, keep_default_na=False)
161
+ p = p[p.identity_pass.str.lower() == "true"].reset_index(drop=True)
162
+ B, BV, names, gsm, genes = load_bulk(cfg["bulk"])
163
+ if list(genes) != list(gene_ids):
164
+ raise SystemExit(f"{name}: bulk gene order")
165
+ key = {x: i for i, x in enumerate(gsm if cfg["bulk_match"] == "gsm" else names)}
166
+ miss = [x for x in p[cfg["bulk_key"]] if x not in key]
167
+ if miss:
168
+ raise SystemExit(f"{name}: {len(miss)} pair bulk ids not in the bulk table, e.g. {miss[:3]}")
169
+ bi = [key[x] for x in p[cfg["bulk_key"]]]
170
+ self.B, self.BV = B[bi], BV[bi]
171
+ self.S, self.SV, _ = load_sc(cfg["sc_dir"], p[cfg["sc_key"]].tolist(), gene_ids)
172
+ self.pairs = p
173
+
174
+ def cross_timepoint(self):
175
+ """Each donor with >= 2 pairs: bulk of its first pair x sc of its second pair (different blood draws)."""
176
+ bi, si, grp_b, grp_s = [], [], [], []
177
+ for d, g in self.pairs.groupby("donor_id", sort=True):
178
+ if len(g) < 2:
179
+ continue
180
+ i, j = g.index[0], g.index[1]
181
+ bi.append(i); si.append(j)
182
+ grp_b.append(self.pairs.group[i]); grp_s.append(self.pairs.group[j])
183
+ return np.array(bi), np.array(si), grp_b, grp_s
184
+
185
+
186
+ def learn_identity_genes(cohorts: list[Cohort], exclude: np.ndarray, gene_ids, sym) -> pd.DataFrame:
187
+ zsum = np.zeros(len(gene_ids)); wsum = 0.0
188
+ ok = ~exclude
189
+ per = {}
190
+ for c in cohorts:
191
+ bi, si, gb, gs = c.cross_timepoint()
192
+ if len(bi) < 6:
193
+ raise SystemExit(f"{c.name}: only {len(bi)} donors with two timepoints")
194
+ B, S = c.B[bi], c.S[si]
195
+ ok &= c.BV[bi].all(0) & c.SV[si].all(0)
196
+ cb, cs = cpm(B), cpm(S)
197
+ ok &= (cb.mean(0) >= MIN_CPM) & (cs.mean(0) >= MIN_CPM)
198
+ lb = group_centre(np.log2(cb + 1), gb)
199
+ ls = group_centre(np.log2(cs + 1), gs)
200
+ lb, ls = lb - lb.mean(0), ls - ls.mean(0)
201
+ den = np.sqrt((lb ** 2).sum(0) * (ls ** 2).sum(0))
202
+ r = np.divide((lb * ls).sum(0), den, out=np.zeros(len(gene_ids)), where=den > 0)
203
+ n = len(bi)
204
+ w = np.sqrt(n - 3)
205
+ zsum += w * np.arctanh(np.clip(r, -0.999, 0.999)); wsum += w
206
+ per[c.name] = (r, n)
207
+ z = np.where(ok, zsum / wsum, -np.inf)
208
+ order = np.argsort(-z)
209
+ rows = []
210
+ for rank, j in enumerate(order[:max(G_SENS + (G_PRIMARY,))], 1):
211
+ rec = {"rank": rank, "gene_id": gene_ids[j], "gene_symbol": sym[j], "fisher_z": float(z[j])}
212
+ for name, (r, n) in per.items():
213
+ rec[f"r_{name}"] = float(r[j]); rec[f"n_{name}"] = n
214
+ rows.append(rec)
215
+ return pd.DataFrame(rows)
216
+
217
+
218
+ def score(B, BV, S, SV, gidx, groups_b, groups_s) -> np.ndarray:
219
+ if not (BV[:, gidx].all() and SV[:, gidx].all()):
220
+ raise SystemExit("an identity gene is not measured in some row")
221
+ lb = group_centre(np.log2(cpm(B)[:, gidx] + 1), groups_b)
222
+ ls = group_centre(np.log2(cpm(S)[:, gidx] + 1), groups_s)
223
+ lb, ls = lb - lb.mean(0), ls - ls.mean(0)
224
+ return pearson(lb, ls)
225
+
226
+
227
+ def calls(R: np.ndarray):
228
+ z = (R - R.mean(0)) / R.std(0)
229
+ out = []
230
+ for s in range(R.shape[1]):
231
+ o = np.argsort(-R[:, s])
232
+ out.append({"sc": s, "best": int(o[0]), "second": int(o[1]), "mutual": bool(np.argmax(R[o[0]]) == s),
233
+ "margin": float(z[o[0], s] - z[o[1], s]), "r_best": float(R[o[0], s]),
234
+ "r_second": float(R[o[1], s])})
235
+ return out
236
+
237
+
238
+ def calibrate(c: Cohort, gsets: dict, draws: int, rng) -> pd.DataFrame:
239
+ cfg = c.cfg
240
+ d = cfg["design"]
241
+ first = c.pairs.groupby("donor_id", sort=True).head(1) # one pair per donor
242
+ case = first[first.group.isin(cfg["case"])].index.to_numpy()
243
+ ctrl = first[first.group.isin(cfg["ctrl"])].index.to_numpy()
244
+ need_case, need_ctrl = d["case_bulk"] + d["case_sc"] - d["shared"], d["ctrl_bulk"] + d["ctrl_sc"]
245
+ if len(case) < need_case or len(ctrl) < need_ctrl:
246
+ raise SystemExit(f"{c.name}: design needs {need_case}/{need_ctrl} donors, has {len(case)}/{len(ctrl)}")
247
+ rows = []
248
+ for it in range(draws):
249
+ dc = rng.choice(case, need_case, replace=False)
250
+ dk = rng.choice(ctrl, need_ctrl, replace=False)
251
+ bulk = np.concatenate([dc[:d["case_bulk"]], dk[:d["ctrl_bulk"]]])
252
+ sc = np.concatenate([dc[:d["shared"]], dc[d["case_bulk"]:], dk[d["ctrl_bulk"]:]])
253
+ gb = ["case"] * d["case_bulk"] + ["ctrl"] * d["ctrl_bulk"]
254
+ gs = ["case"] * d["case_sc"] + ["ctrl"] * d["ctrl_sc"]
255
+ truth = {j: (list(bulk).index(x) if x in set(bulk) else -1) for j, x in enumerate(sc)}
256
+ for gname, gidx in gsets.items():
257
+ R = score(c.B[bulk], c.BV[bulk], c.S[sc], c.SV[sc], gidx, gb, gs)
258
+ for k in calls(R):
259
+ tb = truth[k["sc"]]
260
+ rows.append({"cohort": c.name, "genes": gname, "draw": it, "sc_slot": k["sc"], "shared": tb >= 0,
261
+ "best_is_true": bool(tb >= 0 and k["best"] == tb), "mutual": k["mutual"],
262
+ "margin": k["margin"], "r_best": k["r_best"]})
263
+ return pd.DataFrame(rows)
264
+
265
+
266
+ def rule_table(df: pd.DataFrame) -> pd.DataFrame:
267
+ out = []
268
+ for (cohort, genes), g in df.groupby(["cohort", "genes"]):
269
+ cand = g[g.mutual]
270
+ wrong = cand[~cand.best_is_true].margin.to_numpy() # non-shared sc called, or shared on the wrong bulk
271
+ right = cand[cand.best_is_true].margin.to_numpy()
272
+ n_cols = len(g)
273
+ thr = np.inf
274
+ for m in np.sort(np.concatenate([wrong, right, [0.0]])):
275
+ if (wrong >= m).sum() / n_cols <= FALSE_CALL_MAX:
276
+ thr = float(m)
277
+ break
278
+ sh = g[g.shared].assign(ok=lambda x: x.best_is_true & x.mutual & (x.margin >= thr))
279
+ out.append({"cohort": cohort, "genes": genes, "threshold": thr,
280
+ "sensitivity": float(sh.ok.mean()), "wrong_call_rate": float((wrong >= thr).sum() / n_cols),
281
+ "draws_with_any_wrong_call": float(cand[~cand.best_is_true & (cand.margin >= thr)].draw.nunique()
282
+ / g.draw.nunique()),
283
+ "top1_true_rate_shared": float(g[g.shared].best_is_true.mean()),
284
+ "mutual_true_rate_shared": float((g[g.shared].best_is_true & g[g.shared].mutual).mean()),
285
+ "all_3_called_rate": float(sh.groupby("draw").ok.all().mean()), "draws": int(g.draw.nunique())})
286
+ return pd.DataFrame(out)
287
+
288
+
289
+ def main() -> int:
290
+ ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
291
+ ap.add_argument("--draws", type=int, default=1000)
292
+ a = ap.parse_args()
293
+ OUT.mkdir(parents=True, exist_ok=True)
294
+ canon = pd.read_csv(REF, sep="\t", dtype=str)
295
+ gene_ids = canon.gene_id.to_numpy().astype(str)
296
+ sym = canon.gene_symbol.to_numpy().astype(str)
297
+ chr_y = canon.chromosome.astype(str).isin(["Y", "chrY"]).to_numpy()
298
+ sexl = set(pd.read_csv(SEXLIST).gene_id.astype(str))
299
+ exclude = chr_y | np.isin(gene_ids, list(sexl))
300
+ pos = {g: i for i, g in enumerate(gene_ids)}
301
+ coh = {n: Cohort(n, gene_ids) for n in COHORTS}
302
+ print({n: len(c.pairs) for n, c in coh.items()}, flush=True)
303
+
304
+ # ---------------- 1. identity genes (never from the cohort they are tested on, never from Behçet)
305
+ tables = {"all4": learn_identity_genes([coh[n] for n in LEARN], exclude, gene_ids, sym),
306
+ "no_liu": learn_identity_genes([coh[n] for n in LEARN if n != "liu2021"], exclude, gene_ids, sym)}
307
+ for k, t in tables.items():
308
+ t.to_csv(OUT / f"identity_genes_{k}.csv", index=False)
309
+ print(tables["all4"].head(30)[["rank", "gene_symbol", "fisher_z"] + [c for c in tables["all4"] if c.startswith("r_")]]
310
+ .round(3).to_string(index=False), flush=True)
311
+
312
+ def gsets(t):
313
+ return {f"G{G}": np.array([pos[g] for g in t.gene_id[:G]]) for G in (G_PRIMARY,) + G_SENS}
314
+
315
+ # ---------------- 2. calibration (before Behçet is scored)
316
+ rng = np.random.default_rng(SEED)
317
+ cal = pd.concat([calibrate(coh[n], gsets(tables[t]), a.draws, rng) for n, t in TESTS.items()], ignore_index=True)
318
+ cal.to_csv(OUT / "calibration_draws.csv.gz", index=False)
319
+ rt = rule_table(cal)
320
+ rt.to_csv(OUT / "calibration_summary.csv", index=False)
321
+ print(rt.round(4).to_string(index=False), flush=True)
322
+ prim = rt[(rt.cohort == "ye2026_sepsis") & (rt.genes == f"G{G_PRIMARY}")].iloc[0]
323
+ rule = {"identity_genes": f"identity_genes_all4.csv top {G_PRIMARY}", "threshold": float(prim.threshold),
324
+ "rule": "mutual best and margin >= threshold", "calibrated_on": "ye2026_sepsis, Behçet-shaped draws",
325
+ "sepsis": prim.to_dict(),
326
+ "liu2021_replication": rt[(rt.cohort == "liu2021") & (rt.genes == f"G{G_PRIMARY}")].iloc[0].to_dict(),
327
+ "sensitivity_gene_counts": {g: float(rt[(rt.cohort == "ye2026_sepsis") & (rt.genes == g)].threshold.iloc[0])
328
+ for g in (f"G{x}" for x in G_SENS)},
329
+ "false_call_max_per_sc_column": FALSE_CALL_MAX, "draws": a.draws, "seed": SEED,
330
+ "frozen_before_behcet_scored": True, "ages_used": False}
331
+ (OUT / "RULE.json").write_text(json.dumps(rule, indent=1, default=float) + "\n")
332
+
333
+ # ---------------- 3. Behçet, blind to ages
334
+ B, BV, blab, _, bgenes = load_bulk(BEHCET_BULK)
335
+ if list(bgenes) != list(gene_ids):
336
+ raise SystemExit("behcet: bulk gene order")
337
+ inv = pd.read_csv(BEHCET_INV)
338
+ inv = inv[inv.source_name == "human PBMC"].sort_values("title")
339
+ sc_ids, sc_lab = inv.gsm.tolist(), inv.title.tolist()
340
+ S, SV, ncell = load_sc(BEHCET_SC, sc_ids, gene_ids)
341
+ gb = ["BD" if x.startswith("BD") else "HC" for x in blab]
342
+ gs = ["BD" if "_BD_" in x else "HC" for x in sc_lab]
343
+ ycpm = lambda m: m[:, chr_y].sum(1) / m.sum(1) * 1e6
344
+ pd.concat([pd.DataFrame({"sample": blab, "modality": "bulk", "group": gb, "chrY_cpm": ycpm(B)}),
345
+ pd.DataFrame({"sample": sc_lab, "modality": "sc", "group": gs, "chrY_cpm": ycpm(S), "cells": ncell})]
346
+ ).to_csv(OUT / "sex_check.csv", index=False)
347
+ rows, Rs = [], {}
348
+ for gname, gidx in gsets(tables["all4"]).items():
349
+ R = score(B, BV, S, SV, gidx, gb, gs)
350
+ Rs[gname] = R
351
+ pd.DataFrame(R, index=blab, columns=sc_lab).to_csv(
352
+ OUT / ("behcet_scores.csv" if gname == f"G{G_PRIMARY}" else f"behcet_scores_{gname}.csv"))
353
+ thr = float(rt[(rt.cohort == "ye2026_sepsis") & (rt.genes == gname)].threshold.iloc[0])
354
+ for k in calls(R):
355
+ rows.append({"genes": gname, "sc_sample": sc_lab[k["sc"]], "best_bulk": blab[k["best"]],
356
+ "second_bulk": blab[k["second"]], "r_best": k["r_best"], "r_second": k["r_second"],
357
+ "mutual": k["mutual"], "margin": k["margin"], "threshold": thr,
358
+ "called": bool(k["mutual"] and k["margin"] >= thr)})
359
+ cl = pd.DataFrame(rows)
360
+ cl.to_csv(OUT / "behcet_calls.csv", index=False)
361
+ # per-gene evidence for every sc sample's best bulk (primary gene set): log2 CPM in both, and on/off flags
362
+ gidx = gsets(tables["all4"])[f"G{G_PRIMARY}"]
363
+ lb, ls = np.log2(cpm(B)[:, gidx] + 1), np.log2(cpm(S)[:, gidx] + 1)
364
+ ev = []
365
+ for _, r in cl[cl.genes == f"G{G_PRIMARY}"].iterrows():
366
+ b, s = list(blab).index(r.best_bulk), sc_lab.index(r.sc_sample)
367
+ for jj, j in enumerate(gidx):
368
+ ev.append({"sc_sample": r.sc_sample, "best_bulk": r.best_bulk, "gene": sym[j], "gene_id": gene_ids[j],
369
+ "bulk_log2cpm": float(lb[b, jj]), "sc_log2cpm": float(ls[s, jj]),
370
+ "bulk_rank_among_19": int((lb[:, jj] > lb[b, jj]).sum() + 1),
371
+ "sc_rank_among_8": int((ls[:, jj] > ls[s, jj]).sum() + 1)})
372
+ pd.DataFrame(ev).to_csv(OUT / "behcet_gene_evidence.csv", index=False)
373
+ summary = {"rule": rule, "behcet_calls_primary": cl[cl.genes == f"G{G_PRIMARY}"].to_dict("records"),
374
+ "inputs": {"behcet_bulk": str(BEHCET_BULK), "behcet_bulk_sha256": sha(BEHCET_BULK),
375
+ "behcet_sc": {l: str(BEHCET_SC / g) for g, l in zip(sc_ids, sc_lab)},
376
+ "pairs": {n: str(PAIRDATA / n / "pairs.csv") for n in COHORTS},
377
+ "sex_linked_exclusion": str(SEXLIST)},
378
+ "n_pairs_identity_pass": {n: len(c.pairs) for n, c in coh.items()},
379
+ "code_sha256": sha(Path(__file__)), "ages_used": False}
380
+ (OUT / "SUMMARY.json").write_text(json.dumps(summary, indent=1, default=str) + "\n")
381
+ with pd.option_context("display.width", 200):
382
+ print(cl.round(3).to_string(index=False))
383
+ return 0
384
+
385
+
386
+ if __name__ == "__main__":
387
+ sys.exit(main())