junidude14 commited on
Commit
1055468
·
verified ·
1 Parent(s): bf68ed6

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/deconv_strict.py ADDED
@@ -0,0 +1,838 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Exact-support BayesPrism/CIBERSORTx adapter for one strict disease unit.
3
+
4
+ CPU only. Each invocation is an isolated process; legacy modules are imported
5
+ unchanged and their output root and split function are patched in memory.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import csv
11
+ import hashlib
12
+ import importlib
13
+ import json
14
+ import os
15
+ import re
16
+ import subprocess
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
22
+ for key in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
23
+ os.environ.setdefault(key, "4")
24
+
25
+ import numpy as np # noqa: E402
26
+ import pandas as pd # noqa: E402
27
+
28
+ PLAN = Path(__file__).resolve().parents[1]
29
+ OLD = PLAN.parent / "bayesprism_paired_20261006"
30
+ OLD_TOOLS = OLD / "tools"
31
+ KEY = Path("/home/sj_server_1/cibersortx.key")
32
+ GUARD = Path("/home/sj_server_1/.local/libexec/ml-memory-guard")
33
+ SPLIT = "fewshot0"
34
+ sys.path.insert(0, str(OLD_TOOLS))
35
+
36
+
37
+ def sha(path: Path) -> str:
38
+ h = hashlib.sha256()
39
+ with path.open("rb") as f:
40
+ for chunk in iter(lambda: f.read(1 << 20), b""):
41
+ h.update(chunk)
42
+ return h.hexdigest()
43
+
44
+
45
+ def host_preflight() -> None:
46
+ """Host-wide GB10 guard checks before memory-heavy CPU preparation or methods."""
47
+ active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
48
+ capture_output=True, text=True)
49
+ if active.returncode or active.stdout.strip() != "active":
50
+ subprocess.run(["systemctl", "--user", "restart", "ml-memory-guard.service"], check=True)
51
+ active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
52
+ capture_output=True, text=True)
53
+ if active.returncode or active.stdout.strip() != "active":
54
+ raise RuntimeError("ml-memory-guard.service is inactive after restart")
55
+ subprocess.run([str(GUARD), "--check"], check=True)
56
+ apps = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"],
57
+ check=True, capture_output=True, text=True)
58
+ if apps.stdout.strip():
59
+ raise RuntimeError("a CUDA compute job is active; queue this memory-heavy CPU unit until it completes")
60
+ available_kib = next(int(line.split()[1]) for line in Path("/proc/meminfo").read_text().splitlines()
61
+ if line.startswith("MemAvailable:"))
62
+ if available_kib < 48 * 1024 * 1024:
63
+ raise RuntimeError("less than 48 GiB MemAvailable; defer the memory-heavy deconvolution unit")
64
+
65
+
66
+ def validate_support_data(s: dict) -> dict:
67
+ body = {k: v for k, v in s.items() if k != "sha256"}
68
+ digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
69
+ if s.get("schema") != "pbisc.paper.strict-support.v1" or s.get("sha256") != digest:
70
+ raise ValueError("strict support schema or hash mismatch")
71
+ train, test = s.get("train_sample_ids", []), s.get("test_sample_ids", [])
72
+ td, vd = s.get("train_donor_ids", []), s.get("test_donor_ids", [])
73
+ if not train or not test or len(train) != len(td) or len(test) != len(vd):
74
+ raise ValueError("strict support requires aligned sample and donor IDs")
75
+ if len(set(train)) != len(train) or len(set(test)) != len(test) or len(set(td)) != len(td):
76
+ raise ValueError("duplicate strict reference or mixture identity")
77
+ if set(td) & set(vd) or set(train) & set(test):
78
+ raise ValueError("reference and mixture donors/samples overlap")
79
+ if s["cohort"] not in {"ye2026_sepsis", "ji2025_chili", "imperial_eskd", "giroux2022"}:
80
+ raise ValueError("deconvolution supports disease cohorts only")
81
+ if s.get("design") != "disease_existing_draw" or not re.fullmatch(r"draw[0-4]_n5", str(s.get("unit", ""))):
82
+ raise ValueError("deconvolution requires a canonical disease draw unit")
83
+ if s["n_pairs"] != 5 or len(s["train_sample_ids"]) != 5:
84
+ raise ValueError("deconvolution requires exact five-pair support")
85
+ if set(s["excluded_sample_ids"]) & (set(s["train_sample_ids"]) | set(s["test_sample_ids"])):
86
+ raise ValueError("excluded visits entered the reference or mixture")
87
+ return s
88
+
89
+
90
+ def support(path: Path) -> dict:
91
+ s = validate_support_data(json.loads(path.read_text()))
92
+ draw = s["unit"].replace("_n5", "")
93
+ canonical = PLAN / "protocol" / "splits" / s["cohort"] / "disease" / draw / "support.json"
94
+ if path.resolve() != canonical.resolve() or not canonical.is_file():
95
+ raise ValueError("support manifest must be the canonical protocol file")
96
+ return s
97
+
98
+
99
+ def unit_out(s: dict, out: Path | None) -> Path:
100
+ validate_support_data(s)
101
+ expected = (PLAN / "deconvolution" / s["cohort"] / "disease" /
102
+ s["unit"].replace("_n5", "")).resolve()
103
+ if not expected.is_relative_to((PLAN / "deconvolution").resolve()):
104
+ raise ValueError("unit output escapes deconvolution directory")
105
+ chosen = (out or expected).resolve()
106
+ if chosen != expected:
107
+ raise ValueError(f"--out must be the strict unit output: {expected}")
108
+ return chosen
109
+
110
+
111
+ def strict_split(s: dict) -> dict:
112
+ return {"reference": list(s["train_sample_ids"]), "mixture": list(s["test_sample_ids"]),
113
+ "train_donors": list(s["train_donor_ids"]), "excluded_samples": list(s["excluded_sample_ids"]),
114
+ "support_sha256": s["sha256"], "run_json_check": "strict_manifest"}
115
+
116
+
117
+ def bind(s: dict, out: Path) -> None:
118
+ out.mkdir(parents=True, exist_ok=True)
119
+ p = out / "SUPPORT.json"
120
+ if p.exists() and json.loads(p.read_text()) != {
121
+ "support_sha256": s["sha256"], "reference": s["train_sample_ids"],
122
+ "mixture": s["test_sample_ids"], "excluded": s["excluded_sample_ids"]}:
123
+ raise ValueError("output directory is bound to another strict support")
124
+ p.write_text(json.dumps({"support_sha256": s["sha256"], "reference": s["train_sample_ids"],
125
+ "mixture": s["test_sample_ids"], "excluded": s["excluded_sample_ids"]}, indent=2) + "\n")
126
+
127
+
128
+ def patched_modules(s: dict, out: Path):
129
+ C = importlib.import_module("common")
130
+ C.PLAN = out
131
+ C.split_rows = lambda ds, kind, idx: strict_split(s) if (ds, kind, idx) == (s["cohort"], "fewshot", 0) else (_ for _ in ()).throw(ValueError("unexpected split"))
132
+ return C
133
+
134
+
135
+ def prepare(s: dict, out: Path) -> dict:
136
+ bind(s, out)
137
+ previous = out / "INPUTS.json"
138
+ if previous.exists():
139
+ return require_inputs(s, out)
140
+ method_dirs = [out / "inputs" / s["cohort"] / "fewshot0_full" / "bp",
141
+ out / "cibersortx" / s["cohort"] / SPLIT / "out_fractions",
142
+ out / "cibersortx" / s["cohort"] / SPLIT / "out_hires"]
143
+ if any(d.is_dir() and any(d.iterdir()) for d in method_dirs):
144
+ raise ValueError("existing method output has no prepared-input receipt; refusing to rewrite inputs")
145
+ C = patched_modules(s, out)
146
+ ds = s["cohort"]
147
+ aggregate = OLD / "data" / ds / "aggregates_full.npz"
148
+ if not aggregate.is_file():
149
+ raise FileNotFoundError(f"read-only raw-count aggregate missing: {aggregate}")
150
+ link = out / "data" / ds / "aggregates_full.npz"
151
+ link.parent.mkdir(parents=True, exist_ok=True)
152
+ if link.is_symlink() and link.resolve() != aggregate.resolve():
153
+ raise ValueError("aggregate link points to a different source")
154
+ if link.exists() and (not link.is_symlink() or link.resolve() != aggregate.resolve()):
155
+ raise ValueError("aggregate destination is not the read-only legacy link")
156
+ if not link.exists():
157
+ link.symlink_to(aggregate)
158
+ bp = importlib.import_module("build_split")
159
+ bp.main([ds, "fewshot", "0", "full"])
160
+ cx = importlib.import_module("build_cibersortx_inputs")
161
+ cx.SPLITS = [("fewshot", 0)]
162
+ cx.main([ds])
163
+ bdir = out / "inputs" / ds / "fewshot0_full"
164
+ cdir = out / "cibersortx" / ds / SPLIT
165
+ b = json.loads((bdir / "SPLIT.json").read_text())
166
+ c = json.loads((cdir / "INPUT.json").read_text())
167
+ if b["reference"] != s["train_sample_ids"] or b["mixture"] != s["test_sample_ids"]:
168
+ raise ValueError("BayesPrism input rows differ from strict support")
169
+ if c["reference_samples"] != s["train_sample_ids"] or c["mixture_samples"] != s["test_sample_ids"]:
170
+ raise ValueError("CIBERSORTx input rows differ from strict support")
171
+ rec = {"schema": "pbisc.deconvolution.strict-inputs.v1", "support_sha256": s["sha256"],
172
+ "reference_sample_ids": s["train_sample_ids"], "mixture_sample_ids": s["test_sample_ids"],
173
+ "excluded_sample_ids": s["excluded_sample_ids"], "aggregate_source": str(aggregate),
174
+ "aggregate_sha256": sha(aggregate), "bayesprism_split_sha256": sha(bdir / "SPLIT.json"),
175
+ "cibersortx_input_sha256": sha(cdir / "INPUT.json"), "adapter_sha256": sha(Path(__file__))}
176
+ (out / "INPUTS.json").write_text(json.dumps(rec, indent=2) + "\n")
177
+ return rec
178
+
179
+
180
+ def require_inputs(s: dict, out: Path) -> dict:
181
+ rec = json.loads((out / "INPUTS.json").read_text())
182
+ if (rec["support_sha256"] != s["sha256"] or rec["reference_sample_ids"] != s["train_sample_ids"]
183
+ or rec["mixture_sample_ids"] != s["test_sample_ids"]
184
+ or rec["excluded_sample_ids"] != s["excluded_sample_ids"]):
185
+ raise ValueError("prepared inputs differ from strict support")
186
+ aggregate = Path(rec["aggregate_source"])
187
+ link = out / "data" / s["cohort"] / "aggregates_full.npz"
188
+ if not link.is_symlink() or link.resolve() != aggregate.resolve():
189
+ raise ValueError("read-only raw-count aggregate link changed after preparation")
190
+ if sha(aggregate) != rec["aggregate_sha256"]:
191
+ raise ValueError("read-only raw-count aggregate changed after preparation")
192
+ if sha(out / "inputs" / s["cohort"] / "fewshot0_full" / "SPLIT.json") != rec["bayesprism_split_sha256"]:
193
+ raise ValueError("BayesPrism split manifest changed after preparation")
194
+ if sha(out / "cibersortx" / s["cohort"] / SPLIT / "INPUT.json") != rec["cibersortx_input_sha256"]:
195
+ raise ValueError("CIBERSORTx input manifest changed after preparation")
196
+ bdir = out / "inputs" / s["cohort"] / "fewshot0_full"
197
+ cdir = out / "cibersortx" / s["cohort"] / SPLIT
198
+ for directory, filename, field in ((bdir, "SPLIT.json", "files"), (cdir, "INPUT.json", "files")):
199
+ entries = json.loads((directory / filename).read_text())[field]
200
+ for name, digest in entries.items():
201
+ if sha(directory / name) != digest:
202
+ raise ValueError(f"prepared input changed: {directory / name}")
203
+ return rec
204
+
205
+
206
+ def stage_dir(s: dict, out: Path, stage: str) -> Path:
207
+ if stage == "bayesprism":
208
+ return out / "inputs" / s["cohort"] / "fewshot0_full" / "bp"
209
+ if stage in {"fractions", "hires"}:
210
+ return out / "cibersortx" / s["cohort"] / SPLIT / f"out_{stage}"
211
+ raise ValueError(f"unknown method stage {stage}")
212
+
213
+
214
+ def stage_outputs(s: dict, out: Path, stage: str) -> list[Path]:
215
+ d = stage_dir(s, out, stage)
216
+ if stage == "bayesprism":
217
+ zfiles = sorted(d.glob("Z_type_*.tsv.gz"))
218
+ if not zfiles:
219
+ raise FileNotFoundError("BayesPrism type expression Z files missing")
220
+ files = [d / "theta_final.csv", d / "theta_first.csv", d / "genes_used.txt", *zfiles]
221
+ elif stage == "fractions":
222
+ files = [d / "CIBERSORTx_Adjusted.txt"]
223
+ if len(s["test_sample_ids"]) > 8:
224
+ sig = next(iter(sorted(d.glob("*inferred_refsample.bm.K999.txt"))), None)
225
+ if sig is None:
226
+ raise FileNotFoundError("CIBERSORTx Fractions HiRes signature missing")
227
+ files.extend([sig, d / "CIBERSORTx_cell_type_sourceGEP.txt"])
228
+ else:
229
+ files = []
230
+ for typ in ("T cell", "B cell", "Monocyte", "NK cell"):
231
+ f = next(iter(sorted(d.glob(f"CIBERSORTxHiRes_*_{typ.replace(' ', '')}_Window*.txt"))), None)
232
+ if f is None:
233
+ raise FileNotFoundError(f"CIBERSORTx HiRes required type output missing: {typ}")
234
+ files.append(f)
235
+ files.extend(p for p in sorted(d.glob("CIBERSORTxHiRes_*.txt")) if p not in files)
236
+ if not files or any(not f.is_file() for f in files):
237
+ raise FileNotFoundError(f"{stage} required output missing")
238
+ return files
239
+
240
+
241
+ def stage_input_hashes(s: dict, out: Path, stage: str) -> dict[str, str]:
242
+ hashes = {"prepared_inputs": sha(out / "INPUTS.json")}
243
+ if stage == "hires":
244
+ d = out / "cibersortx" / s["cohort"] / SPLIT
245
+ files = [d / "out_fractions" / "RECEIPT.json", d / "sigmatrix.txt",
246
+ d / "source_geps.txt", d / "out_hires" / "fractions_results.txt"]
247
+ if any(not f.is_file() for f in files):
248
+ raise FileNotFoundError("HiRes source inputs or Fractions receipt missing")
249
+ hashes.update({str(f.relative_to(d)): sha(f) for f in files})
250
+ return hashes
251
+
252
+
253
+ def write_stage_receipt(s: dict, out: Path, stage: str) -> None:
254
+ require_inputs(s, out)
255
+ d = stage_dir(s, out, stage)
256
+ if not (d / "DONE").is_file():
257
+ raise FileNotFoundError(f"{stage} completion marker missing")
258
+ files = stage_outputs(s, out, stage)
259
+ receipt = {"schema": "pbisc.deconvolution.method-receipt.v1", "stage": stage,
260
+ "support_sha256": s["sha256"], "input_hashes": stage_input_hashes(s, out, stage),
261
+ "outputs_sha256": {f.name: sha(f) for f in files}}
262
+ (d / "RECEIPT.json").write_text(json.dumps(receipt, indent=2) + "\n")
263
+
264
+
265
+ def verify_stage_receipt(s: dict, out: Path, stage: str) -> dict:
266
+ require_inputs(s, out)
267
+ d = stage_dir(s, out, stage)
268
+ if not (d / "DONE").is_file():
269
+ raise FileNotFoundError(f"{stage} completion marker missing")
270
+ p = d / "RECEIPT.json"
271
+ if not p.is_file():
272
+ raise ValueError(f"{stage} has DONE without a support/input-bound receipt")
273
+ rec = json.loads(p.read_text())
274
+ expected = {"schema": "pbisc.deconvolution.method-receipt.v1", "stage": stage,
275
+ "support_sha256": s["sha256"], "input_hashes": stage_input_hashes(s, out, stage),
276
+ "outputs_sha256": {f.name: sha(f) for f in stage_outputs(s, out, stage)}}
277
+ if rec != expected:
278
+ raise ValueError(f"{stage} receipt differs from prepared inputs or method outputs")
279
+ return rec
280
+
281
+
282
+ def method_output_hashes(s: dict, out: Path, method: str) -> dict[str, str]:
283
+ """Fail closed on extra or missing mixtures; hash every output used by scoring."""
284
+ ds = s["cohort"]
285
+ if method == "bayesprism":
286
+ d = out / "inputs" / ds / "fewshot0_full" / "bp"
287
+ primary = d / "theta_final.csv"
288
+ files = [primary, d / "theta_first.csv", *sorted(d.glob("Z_type_*.tsv.gz"))]
289
+ if not (d / "DONE").is_file():
290
+ raise FileNotFoundError("BayesPrism DONE missing")
291
+ samples = pd.read_csv(primary, index_col=0).index.astype(str).tolist()
292
+ else:
293
+ d = out / "cibersortx" / ds / SPLIT
294
+ primary = d / "out_fractions" / "CIBERSORTx_Adjusted.txt"
295
+ files = [primary, *sorted((d / "out_hires").glob("CIBERSORTxHiRes_*.txt"))]
296
+ if not (d / "out_fractions" / "DONE").is_file():
297
+ raise FileNotFoundError("CIBERSORTx Fractions DONE missing")
298
+ samples = pd.read_csv(primary, sep="\t", index_col=0).index.astype(str).tolist()
299
+ if len(samples) != len(s["test_sample_ids"]) or set(samples) != set(s["test_sample_ids"]):
300
+ raise ValueError(f"{method} output mixtures differ from strict support")
301
+ return {str(p): sha(p) for p in files}
302
+
303
+
304
+ def bayesprism(s: dict, out: Path, threads: int) -> None:
305
+ require_inputs(s, out)
306
+ split = out / "inputs" / s["cohort"] / "fewshot0_full"
307
+ if (split / "bp" / "DONE").is_file():
308
+ verify_stage_receipt(s, out, "bayesprism")
309
+ return
310
+ if (split / "bp").is_dir() and any((split / "bp").iterdir()):
311
+ raise ValueError("partial BayesPrism output exists without a completion receipt")
312
+ subprocess.run(["/home/sj_server_1/miniforge3/bin/Rscript", str(OLD_TOOLS / "run_bp.R"), str(split), str(threads)],
313
+ check=True, env={**os.environ, "CUDA_VISIBLE_DEVICES": ""})
314
+ if not (split / "bp" / "DONE").is_file():
315
+ raise RuntimeError("BayesPrism completion marker missing")
316
+ write_stage_receipt(s, out, "bayesprism")
317
+
318
+
319
+ def credentials(path: Path) -> tuple[str, str]:
320
+ txt = path.read_text()
321
+ user = re.search(r"(?im)^\s*(?:email|username|user)\s*[:=]\s*(\S+)", txt)
322
+ token = re.search(r"(?im)^\s*token\s*[:=]\s*(\S+)", txt)
323
+ bare = [x.strip() for x in txt.splitlines() if x.strip() and not re.match(r"(?i)^\s*(email|username|user)\s*[:=]", x)]
324
+ value = token.group(1) if token else (bare[0] if len(bare) == 1 and re.fullmatch(r"[0-9a-fA-F]{20,}", bare[0]) else None)
325
+ if not user or not value:
326
+ raise ValueError("CIBERSORTx credential file lacks email or token")
327
+ return user.group(1), value
328
+
329
+
330
+ def cx_argv(image: str, binary: str, work: Path, dest: Path, env_file: Path,
331
+ threads: int, flags: list[str]) -> list[str]:
332
+ """Credentials expand only inside the container and never enter host argv."""
333
+ script = f'exec ./{binary} --username "$CX_USER" --token "$CX_TOKEN" "$@"'
334
+ return ["docker", "run", "--rm", "--ulimit", "core=0", "--platform", "linux/amd64",
335
+ "--memory=16g", "--memory-swap=16g", f"--cpus={threads}", "--env-file", str(env_file),
336
+ "-v", f"{work}:/src/data:ro", "-v", f"{dest}:/src/outdir", "--entrypoint", "/bin/bash",
337
+ image, "-c", script, "_", *flags]
338
+
339
+
340
+ def run_cx(argv: list[str], log: Path, user: str, token: str) -> None:
341
+ log.parent.mkdir(parents=True, exist_ok=True)
342
+ with log.open("w") as f, subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
343
+ text=True, bufsize=1) as p:
344
+ assert p.stdout is not None
345
+ for line in p.stdout:
346
+ line = line.replace(user, "[REDACTED]").replace(token, "[REDACTED]")
347
+ line = re.sub(r"(?i)^(>\[Options\]\s*(?:token|username)[^:]*:).*", r"\1 [REDACTED]", line)
348
+ f.write(line)
349
+ if p.wait() != 0:
350
+ raise RuntimeError(f"CIBERSORTx failed; see redacted log {log}")
351
+ if "Abort!" in log.read_text():
352
+ raise RuntimeError(f"CIBERSORTx aborted; see redacted log {log}")
353
+
354
+
355
+ def cibersortx(s: dict, out: Path, threads: int) -> dict:
356
+ require_inputs(s, out)
357
+ d = out / "cibersortx" / s["cohort"] / SPLIT
358
+ meta = json.loads((d / "INPUT.json").read_text())
359
+ if meta["mixture_samples"] != s["test_sample_ids"]:
360
+ raise ValueError("CIBERSORTx mixture differs from strict support")
361
+ images = ["cibersortx/fractions:latest"]
362
+ if len(s["test_sample_ids"]) > 8:
363
+ images.append("cibersortx/hires:latest")
364
+ for image in images:
365
+ subprocess.run(["docker", "image", "inspect", image], stdout=subprocess.DEVNULL, check=True)
366
+ user, token = credentials(KEY)
367
+ with tempfile.TemporaryDirectory(prefix="cx_env_", dir=out) as tmp:
368
+ envfile = Path(tmp) / "env"
369
+ envfile.write_text(f"CX_USER={user}\nCX_TOKEN={token}\n")
370
+ envfile.chmod(0o600)
371
+ fd = d / "out_fractions"
372
+ fd.mkdir(exist_ok=True)
373
+ if (fd / "DONE").exists():
374
+ verify_stage_receipt(s, out, "fractions")
375
+ else:
376
+ if any(fd.iterdir()):
377
+ raise ValueError("partial CIBERSORTx Fractions output exists without a completion receipt")
378
+ flags = ["--single_cell", "TRUE", "--refsample", "refsample.txt", "--mixture", "mixture.txt",
379
+ "--rmbatchSmode", "TRUE", "--fraction", "0", "--replicates", "5", "--sampling", "0.5",
380
+ "--G.min", "300", "--G.max", "500", "--q.value", "0.01", "--perm", "0", "--QN", "FALSE", "--verbose", "TRUE"]
381
+ run_cx(cx_argv("cibersortx/fractions:latest", "CIBERSORTxFractions", d, fd, envfile, threads, flags), fd / "run.redacted.log", user, token)
382
+ if not (fd / "CIBERSORTx_Adjusted.txt").is_file():
383
+ raise RuntimeError("CIBERSORTx fractions output missing")
384
+ (fd / "DONE").write_text("ok\n")
385
+ write_stage_receipt(s, out, "fractions")
386
+ status = {"fractions": "complete", "hires": "pending"}
387
+ if len(s["test_sample_ids"]) <= 8:
388
+ status.update(hires="not_estimable", reason="HiRes needs more than eight mixture samples")
389
+ else:
390
+ hd = d / "out_hires"
391
+ hd.mkdir(exist_ok=True)
392
+ if (hd / "DONE").exists():
393
+ verify_stage_receipt(s, out, "hires")
394
+ else:
395
+ if any(hd.iterdir()):
396
+ raise ValueError("partial CIBERSORTx HiRes output exists without a completion receipt")
397
+ sig = next(iter(sorted(fd.glob("*inferred_refsample.bm.K999.txt"))), None)
398
+ src = fd / "CIBERSORTx_cell_type_sourceGEP.txt"
399
+ res = fd / "CIBERSORTx_Adjusted.txt"
400
+ if sig is None or not src.is_file() or not res.is_file():
401
+ raise RuntimeError("CIBERSORTx Fractions signature/source/results missing for HiRes")
402
+ (d / "sigmatrix.txt").write_bytes(sig.read_bytes())
403
+ (d / "source_geps.txt").write_bytes(src.read_bytes())
404
+ fr = pd.read_csv(res, sep="\t", index_col=0)
405
+ fr[[c for c in fr if c not in ("P-value", "Correlation", "RMSE")]].to_csv(hd / "fractions_results.txt", sep="\t")
406
+ flags = ["--mixture", "mixture.txt", "--sigmatrix", "sigmatrix.txt", "--cibresults", "fractions_results.txt",
407
+ "--rmbatchSmode", "TRUE", "--sourceGEPs", "source_geps.txt", "--subsetgenes", "hires_genes.txt", "--threads", str(threads)]
408
+ run_cx(cx_argv("cibersortx/hires:latest", "CIBERSORTxHiRes", d, hd, envfile, threads, flags), hd / "run.redacted.log", user, token)
409
+ if not list(hd.glob("CIBERSORTxHiRes_*.txt")):
410
+ raise RuntimeError("CIBERSORTx HiRes output missing")
411
+ (hd / "DONE").write_text("ok\n")
412
+ write_stage_receipt(s, out, "hires")
413
+ status["hires"] = "complete"
414
+ (d / "STATUS.json").write_text(json.dumps(status, indent=2) + "\n")
415
+ return status
416
+
417
+
418
+ CONTRAST_GROUPS = {
419
+ "ye2026_sepsis": ({"adult_sepsis", "ped_sepsis"}, {"adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"}),
420
+ "ji2025_chili": ({"TOL", "FU1"}, {"BC", "AC"}),
421
+ "imperial_eskd": ({"covid_positive"}, {"covid_negative"}),
422
+ "giroux2022": ({"severe"}, {"mild"}),
423
+ }
424
+
425
+ LIMMA_R = r'''suppressPackageStartupMessages(library(limma))
426
+ args <- commandArgs(trailingOnly=TRUE)
427
+ if (length(args) != 4L) stop("usage: limma.R metadata.csv observed.tsv.gz method.tsv.gz outdir")
428
+ meta <- read.csv(args[1], stringsAsFactors=FALSE)
429
+ out <- args[4]
430
+ dir.create(out, recursive=TRUE, showWarnings=FALSE)
431
+ group <- factor(meta$condition, levels=c("control", "case"))
432
+ design <- model.matrix(~group)
433
+ blocked <- any(table(meta$donor_id) > 1L)
434
+ for (side in c("observed", "method")) {
435
+ path <- if (side == "observed") args[2] else args[3]
436
+ tab <- read.delim(gzfile(path), row.names=1, check.names=FALSE)
437
+ X <- as.matrix(tab)
438
+ if (ncol(X) != nrow(meta) || nrow(X) < 3L || any(!is.finite(X))) stop("invalid matched expression matrix")
439
+ if (blocked) {
440
+ dc <- duplicateCorrelation(X, design, block=meta$donor_id)
441
+ if (!is.finite(dc$consensus.correlation)) stop("duplicateCorrelation undefined")
442
+ fit <- lmFit(X, design, block=meta$donor_id, correlation=dc$consensus.correlation)
443
+ } else fit <- lmFit(X, design)
444
+ fit <- eBayes(fit)
445
+ top <- topTable(fit, coef=2L, number=Inf, sort.by="none", adjust.method="BH")
446
+ top$gene_id <- rownames(top)
447
+ write.csv(top[,c("gene_id","logFC","P.Value","adj.P.Val")], file.path(out,paste0(side,"_limma.csv")), row.names=FALSE)
448
+ }
449
+ '''
450
+
451
+
452
+ def _log2_cpm(x: np.ndarray) -> np.ndarray:
453
+ x = np.asarray(x, np.float64)
454
+ lib = x.sum(axis=1, keepdims=True)
455
+ if not np.isfinite(x).all() or (x < 0).any() or (lib <= 0).any():
456
+ raise ValueError("nonfinite, negative, or zero-library expression")
457
+ return np.log2(1 + np.divide(x * 1e6, lib, out=np.zeros_like(x), where=lib > 0))
458
+
459
+
460
+ def _collapse_donor_condition(s: dict, case: np.ndarray, ctrl: np.ndarray,
461
+ obs: np.ndarray, method: np.ndarray, bulk: np.ndarray) -> tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray]:
462
+ """Each donor contributes once per condition, regardless of visit count."""
463
+ donors = np.asarray(s["test_donor_ids"], dtype=str)
464
+ condition = np.where(case, "case", "control")
465
+ keys = sorted(set(zip(donors, condition)), key=lambda x: (x[0], x[1]))
466
+ O, M, U = (_log2_cpm(x) for x in (obs, method, bulk))
467
+ meta = pd.DataFrame(keys, columns=["donor_id", "condition"])
468
+ out = []
469
+ for x in (O, M, U):
470
+ out.append(np.stack([x[(donors == d) & (condition == c)].mean(axis=0) for d, c in keys]))
471
+ return meta, *out
472
+
473
+
474
+ def _pearson(x: np.ndarray, y: np.ndarray) -> float:
475
+ if x.size < 3 or np.std(x) == 0 or np.std(y) == 0:
476
+ return float("nan")
477
+ return float(np.corrcoef(x, y)[0, 1])
478
+
479
+
480
+ def _partial(x: np.ndarray, y: np.ndarray, bulk: np.ndarray) -> float:
481
+ centered = bulk - bulk.mean()
482
+ den = float(np.dot(centered, centered))
483
+ if den == 0:
484
+ return float("nan")
485
+ residual = lambda z: z - z.mean() - centered * (np.dot(z - z.mean(), centered) / den)
486
+ return _pearson(residual(x), residual(y))
487
+
488
+
489
+ def _top50(tab: pd.DataFrame) -> set[str]:
490
+ ok = tab.loc[tab["adj.P.Val"].astype(float) < 0.05].copy()
491
+ return set(ok.assign(abs_lfc=ok.logFC.abs()).sort_values("abs_lfc", ascending=False).head(50).gene_id.astype(str))
492
+
493
+
494
+ def corrected_expression(s: dict, B, v: dict, pred: dict, arm: str, out: Path) -> list[dict]:
495
+ """Matched donor-aware limma on continuous log2-CPM; never call this voom."""
496
+ F = B.F
497
+ C = importlib.import_module("common")
498
+ ds = s["cohort"]
499
+ cases, controls = CONTRAST_GROUPS[ds]
500
+ groups = np.asarray(v["groups"], str)
501
+ case, ctrl = np.isin(groups, list(cases)), np.isin(groups, list(controls))
502
+ feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
503
+ fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
504
+ sidpos = {x: i for i, x in enumerate(fsid)}
505
+ genepos = {x: i for i, x in enumerate(feat["gene_ids"].astype(str))}
506
+ bulk = np.asarray(feat["bulk_raw"], np.float64)[[sidpos[x] for x in s["test_sample_ids"]]][:,
507
+ [genepos[x] for x in v["score_ids"]]]
508
+ covered = pred["covered_type"].all(0) if "covered_type" in pred else pred["covered"].all(0)
509
+ base_keep = np.asarray(v.get("keep", np.ones(len(v["score_ids"]), bool)), bool)
510
+ rows = []
511
+ for typ in v["deg_types"]:
512
+ gi = F.GATE.index(typ)
513
+ di = v["deg_types"].index(typ)
514
+ mask = base_keep & (covered[gi] if covered.ndim == 2 else covered)
515
+ observed = np.asarray(v["deg_sum"][:, di, :], np.float64)
516
+ method = np.asarray(pred["Z"][:, gi, :], np.float64)
517
+ mask &= observed.sum(axis=0) > 0
518
+ mask &= method.sum(axis=0) > 0
519
+ eligible = (v["deg_n"][:, di] > 0) & (method.sum(axis=1) > 0) & (case | ctrl)
520
+ donors = np.asarray(s["test_donor_ids"])
521
+ ncase = len(set(donors[eligible & case]))
522
+ nctrl = len(set(donors[eligible & ctrl]))
523
+ common = {"arm": arm, "cell_type": typ, "gene_variant": "donor_covered", "statistic": "limma_log2_cpm",
524
+ "n_genes": int(mask.sum()), "n_test_samples": int(eligible.sum()),
525
+ "n_independent_donors": len(set(donors[eligible])), "n_case_samples": int((eligible & case).sum()),
526
+ "n_control_samples": int((eligible & ctrl).sum()), "n_case_donors": ncase, "n_control_donors": nctrl,
527
+ "method_expression_unit": "continuous log2-CPM on matched observed/method profiles",
528
+ "deg_method": "limma lmFit/eBayes on donor-condition means; duplicateCorrelation for repeated donor conditions"}
529
+ metric_names = ("donor_logfc_r", "donor_partial_r_given_bulk", "donor_limma_top50_overlap")
530
+ if ncase < 2 or nctrl < 2 or mask.sum() < 3:
531
+ reason = "fewer than two independent donors per group or fewer than three common expressed genes"
532
+ rows.extend({**common, "metric": m, "value": "", "status": "not_estimable", "reason": reason} for m in metric_names)
533
+ continue
534
+ if any(np.any(x[eligible][:, mask].sum(axis=1) <= 0) for x in (observed, method, bulk)):
535
+ reason = "a matched profile has zero library on common covered genes"
536
+ rows.extend({**common, "metric": m, "value": "", "status": "not_estimable", "reason": reason} for m in metric_names)
537
+ continue
538
+ ss = {**s, "test_donor_ids": donors[eligible].tolist()}
539
+ meta, O, M, U = _collapse_donor_condition(ss, case[eligible], ctrl[eligible],
540
+ observed[eligible][:, mask], method[eligible][:, mask], bulk[eligible][:, mask])
541
+ iscase = meta.condition.eq("case").to_numpy()
542
+ obs_fc = O[iscase].mean(0) - O[~iscase].mean(0)
543
+ method_fc = M[iscase].mean(0) - M[~iscase].mean(0)
544
+ bulk_fc = U[iscase].mean(0) - U[~iscase].mean(0)
545
+ values = {"donor_logfc_r": _pearson(obs_fc, method_fc),
546
+ "donor_partial_r_given_bulk": _partial(obs_fc, method_fc, bulk_fc)}
547
+ work = out / "score" / "continuous_limma" / arm / typ.replace(" ", "_")
548
+ work.mkdir(parents=True, exist_ok=True)
549
+ meta.to_csv(work / "metadata.csv", index=False)
550
+ genes = np.asarray(v["score_ids"])[mask]
551
+ for side, matrix in (("observed", O), ("method", M)):
552
+ pd.DataFrame(matrix.T, index=pd.Index(genes, name="gene_id")).to_csv(work / f"{side}.tsv.gz", sep="\t")
553
+ script = out / "score" / "continuous_limma" / "limma_continuous.R"
554
+ script.write_text(LIMMA_R)
555
+ try:
556
+ run = subprocess.run(["/home/sj_server_1/miniforge3/bin/Rscript", str(script), str(work / "metadata.csv"), str(work / "observed.tsv.gz"),
557
+ str(work / "method.tsv.gz"), str(work)], capture_output=True, text=True)
558
+ except FileNotFoundError:
559
+ run = None
560
+ if run is None or run.returncode:
561
+ (work / "limma_error.txt").write_text(run.stderr[-8000:] if run is not None else "Rscript unavailable\n")
562
+ values["donor_limma_top50_overlap"] = float("nan")
563
+ reason = "limma continuous-expression fit unavailable; see unit limma_error.txt"
564
+ else:
565
+ obs_top = _top50(pd.read_csv(work / "observed_limma.csv"))
566
+ method_top = _top50(pd.read_csv(work / "method_limma.csv"))
567
+ values["donor_limma_top50_overlap"] = len(obs_top & method_top)
568
+ reason = ""
569
+ for m in metric_names:
570
+ value = values[m]
571
+ rows.append({**common, "metric": m, "value": value if np.isfinite(value) else "",
572
+ "status": "ok" if np.isfinite(value) else "pending" if m == "donor_limma_top50_overlap" else "not_estimable",
573
+ "reason": reason if not np.isfinite(value) else ""})
574
+ return rows
575
+
576
+
577
+ def score_readiness(methods: dict, metrics: dict) -> tuple[str, list[str]]:
578
+ required = ("bayesprism", "cibersortx")
579
+ pending = []
580
+ for name in required:
581
+ record = methods.get(name)
582
+ if record is None or record.get("status") != "complete":
583
+ pending.append(f"{name}: {record.get('reason', 'required method output incomplete') if record else 'required method output missing'}")
584
+ if record and record.get("hires", {}).get("status") == "pending":
585
+ pending.append(f"{name}: {record['hires']['reason']}")
586
+ correction = metrics.get(name, {}).get("corrected_deg", {})
587
+ if record and correction.get("status") not in {"complete", "not_estimable"}:
588
+ pending.append(f"{name}: corrected DEG infrastructure pending")
589
+ return ("pending" if pending else "complete", pending)
590
+
591
+
592
+ def expression_signal(s: dict, B, v: dict, pred: dict, arm: str) -> list[dict]:
593
+ """Legacy metric family on exact strict test samples; donor-aware DEG is separate."""
594
+ SF, F = B.SF, B.F
595
+ C = importlib.import_module("common")
596
+ ds = s["cohort"]
597
+ groups = np.asarray(v["groups"], dtype=str)
598
+ cases, controls = CONTRAST_GROUPS[ds]
599
+ case, ctrl = np.isin(groups, list(cases)), np.isin(groups, list(controls))
600
+ if not case.any() or not ctrl.any() or np.any(~(case | ctrl)):
601
+ raise ValueError("strict test samples do not match the declared case/control groups")
602
+ feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
603
+ fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
604
+ sidpos = {x: i for i, x in enumerate(fsid)}
605
+ genepos = {x: i for i, x in enumerate(feat["gene_ids"].astype(str))}
606
+ sample_rows = [sidpos[x] for x in s["test_sample_ids"]]
607
+ gene_cols = [genepos[x] for x in v["score_ids"]]
608
+ valid = np.asarray(feat["bulk_valid"])[sample_rows][:, gene_cols].astype(bool)
609
+ if not valid.all():
610
+ raise ValueError("scoring genes must be bulk-valid for every strict mixture")
611
+ bulk = np.asarray(feat["bulk_raw"], dtype=np.float64)[sample_rows][:, gene_cols]
612
+ if not np.isfinite(bulk).all() or (bulk < 0).any():
613
+ raise ValueError("invalid strict bulk counts")
614
+ if ds == "giroux2022":
615
+ exclude = C.FT / "data/sex_linked_genes/sex_linked_genes_exclude.csv"
616
+ v["keep"], _ = SF.gene_exclusion(exclude, v["score_ids"])
617
+ contrast = {"enabled": True, "case": case, "ctrl": ctrl}
618
+ obs_deg = SF.observed_deg(v, contrast)
619
+ n_case_donors = len(set(np.asarray(s["test_donor_ids"])[case]))
620
+ n_control_donors = len(set(np.asarray(s["test_donor_ids"])[ctrl]))
621
+ base = {"arm": arm, "n_test_samples": len(s["test_sample_ids"]),
622
+ "n_independent_donors": len(set(s["test_donor_ids"])),
623
+ "n_case_samples": int(case.sum()), "n_control_samples": int(ctrl.sum()),
624
+ "n_case_donors": n_case_donors, "n_control_donors": n_control_donors,
625
+ "method_expression_unit": "BayesPrism posterior type expression" if arm == "bayesprism" else "CIBERSORTx HiRes imputed GEP",
626
+ "deg_method": "historical Welch top50 on method expression; corrected donor-aware DEG pending"}
627
+ if arm == "cibersortx" and (len(s["test_sample_ids"]) <= 8 or not pred.get("has_z") or not any(pred.get("imputed_genes", {}).values())):
628
+ return [{**base, "cell_type": "all", "metric": metric, "value": "", "status": "not_estimable",
629
+ "gene_variant": "covered", "statistic": "mean_cp10k", "n_genes": 0}
630
+ for metric in ("logfc_r", "partial_r_given_bulk", "top50_deg_overlap")]
631
+ G = len(v["score_ids"])
632
+ covered = pred["covered_type"].all(0) if "covered_type" in pred else pred["covered"].all(0)
633
+ masks = (("zero_filled", None), ("covered", covered))
634
+ rows = []
635
+ for variant, mask in masks:
636
+ contrast_rows, deg, _ = B.bp_metrics(v, pred, bulk, contrast, obs_deg, mask)
637
+ for _, r in contrast_rows.iterrows():
638
+ for metric, key in (("logfc_r", "r_generated"), ("partial_r_given_bulk", "partial_r_generated_given_broadcast")):
639
+ value = float(r[key])
640
+ rows.append({**base, "cell_type": r["celltype"], "metric": metric,
641
+ "value": value if np.isfinite(value) else "", "status": "ok" if np.isfinite(value) else "not_estimable",
642
+ "gene_variant": variant, "statistic": r["statistic"], "n_genes": int(r["n_genes"])})
643
+ for typ, overlap in deg.items():
644
+ n_genes = (int(mask[F.GATE.index(typ)].sum()) if mask is not None and mask.ndim == 2
645
+ else int(mask.sum()) if mask is not None else G)
646
+ rows.append({**base, "cell_type": typ, "metric": "top50_deg_overlap",
647
+ "value": int(overlap) if overlap is not None else "", "status": "ok" if overlap is not None else "not_estimable",
648
+ "gene_variant": variant, "statistic": F.DEG_STATISTIC,
649
+ "n_genes": n_genes})
650
+ return rows
651
+
652
+
653
+ def score(s: dict, out: Path) -> dict:
654
+ require_inputs(s, out)
655
+ C = patched_modules(s, out)
656
+ B = importlib.import_module("score_bp")
657
+ F = B.F
658
+ ds = s["cohort"]
659
+ ids = np.asarray(s["test_sample_ids"], dtype=str)
660
+ ref, man = F.load_reference(F.CACHE_ROOT / F.DATASETS[ds].name)
661
+ ref["deg"] = F.load_deg_reference(F.CACHE_ROOT / F.DATASETS[ds].name, man, ref)
662
+ if not set(ids) <= set(ref["donors"].astype(str)):
663
+ raise ValueError("strict test IDs absent from observed reference")
664
+ v = B.light_view(ref, ids.tolist())
665
+ rows, signals, metrics, methods = [], [], {}, {}
666
+ for name in ("bayesprism", "cibersortx"):
667
+ hires_pending = False
668
+ try:
669
+ if name == "bayesprism":
670
+ verify_stage_receipt(s, out, "bayesprism")
671
+ else:
672
+ verify_stage_receipt(s, out, "fractions")
673
+ if len(ids) > 8:
674
+ try:
675
+ verify_stage_receipt(s, out, "hires")
676
+ except FileNotFoundError:
677
+ hires_pending = True
678
+ hashes = method_output_hashes(s, out, name)
679
+ pred = B.load_bp(ds, ["fewshot0_full"], ids, v["score_ids"]) if name == "bayesprism" else B.load_cx(ds, [SPLIT], ids, v["score_ids"])
680
+ except (SystemExit, FileNotFoundError) as e:
681
+ methods[name] = {"status": "pending", "reason": str(e)}
682
+ continue
683
+ fractions = B.to_cells(pred["theta"]["final"], pred["size"])
684
+ if not np.isfinite(fractions).all():
685
+ raise ValueError(f"{name} fractions contain nonfinite values")
686
+ l1 = F.IC.l1(fractions, v["comp"])
687
+ metrics[name] = {"composition_l1_mean": float(np.mean(l1)), "n_samples": len(ids),
688
+ "n_independent_donors": len(set(s["test_donor_ids"]))}
689
+ methods[name] = {"status": "pending" if hires_pending else "complete",
690
+ "composition": "cell_fraction_size_corrected", "output_sha256": hashes}
691
+ for i, sample in enumerate(ids):
692
+ for j, typ in enumerate(F.GATE):
693
+ rows.append({"arm": name, "sample_id": sample, "donor_id": s["test_donor_ids"][i],
694
+ "cell_type": typ, "observed": float(v["comp"][i, j]), "predicted": float(fractions[i, j]),
695
+ "composition_l1": float(l1[i])})
696
+ if name == "cibersortx":
697
+ imputed = pred.get("imputed_genes", {})
698
+ if hires_pending:
699
+ methods[name]["hires"] = {"status": "pending", "reason": "required HiRes output missing"}
700
+ elif len(ids) <= 8:
701
+ methods[name]["hires"] = {"status": "not_estimable", "reason": "at most eight mixture samples"}
702
+ elif not pred.get("has_z"):
703
+ methods[name]["hires"] = {"status": "pending", "reason": "required HiRes result files missing"}
704
+ methods[name]["status"] = "pending"
705
+ elif not any(imputed.values()):
706
+ methods[name]["hires"] = {"status": "not_estimable", "reason": "verified HiRes result has zero imputed genes"}
707
+ else:
708
+ methods[name]["hires"] = {"status": "available", "imputed_genes": imputed}
709
+ method_view = v.copy()
710
+ if hires_pending or (name == "cibersortx" and methods[name]["hires"]["status"] == "pending"):
711
+ corrected = [{"arm": name, "cell_type": typ, "metric": metric, "value": "", "status": "pending",
712
+ "reason": "required HiRes output missing", "gene_variant": "donor_covered",
713
+ "statistic": "limma_log2_cpm", "n_genes": 0,
714
+ "n_test_samples": len(ids), "n_independent_donors": len(set(s["test_donor_ids"])),
715
+ "method_expression_unit": "CIBERSORTx HiRes imputed GEP"}
716
+ for typ in v["deg_types"] for metric in
717
+ ("donor_logfc_r", "donor_partial_r_given_bulk", "donor_limma_top50_overlap")]
718
+ else:
719
+ signals.extend(expression_signal(s, B, method_view, pred, name))
720
+ corrected = corrected_expression(s, B, method_view, pred, name, out)
721
+ signals.extend(corrected)
722
+ deg_rows = [r for r in corrected if r["metric"] == "donor_limma_top50_overlap"]
723
+ metrics[name]["corrected_deg"] = {"method": "limma on matched donor-condition continuous log2-CPM",
724
+ "status": "pending" if any(r["status"] == "pending" for r in deg_rows)
725
+ else "complete" if any(r["status"] == "ok" for r in deg_rows)
726
+ else "not_estimable",
727
+ "n_types_estimable": sum(r["status"] == "ok" for r in deg_rows),
728
+ "n_types_total": len(deg_rows)}
729
+ status, pending = score_readiness(methods, metrics)
730
+ result = {"schema": "pbisc.deconvolution.strict-score.v1", "cohort": ds, "unit": s["unit"],
731
+ "status": status,
732
+ "pending_reasons": pending, "required_methods": ["bayesprism", "cibersortx"],
733
+ "support_sha256": s["sha256"], "reference_sample_ids": s["train_sample_ids"],
734
+ "mixture_sample_ids": s["test_sample_ids"], "methods": methods, "metrics": metrics,
735
+ "observed_reference_sha256": man["reference_sha256"],
736
+ "source_sha256": {"adapter": sha(Path(__file__)), "score_bp": sha(OLD_TOOLS / "score_bp.py"),
737
+ "common": sha(OLD_TOOLS / "common.py"),
738
+ "legacy_aggregate": json.loads((out / "INPUTS.json").read_text())["aggregate_sha256"],
739
+ "features": sha(C.FT / "data" / ds / "features.npz"),
740
+ "observed_deg_reference": ref["deg"].get("sha256")}}
741
+ p = out / "score"
742
+ p.mkdir(exist_ok=True)
743
+ csvpath = p / "figure4_methods.csv"
744
+ if rows:
745
+ with csvpath.open("w", newline="") as f:
746
+ writer = csv.DictWriter(f, fieldnames=list(rows[0]))
747
+ writer.writeheader(); writer.writerows(rows)
748
+ result["figure4_csv"] = str(csvpath)
749
+ result["figure4_csv_sha256"] = sha(csvpath)
750
+ signalpath = p / "expression_signal.csv"
751
+ with signalpath.open("w", newline="") as f:
752
+ writer = csv.DictWriter(f, fieldnames=list(dict.fromkeys(k for row in signals for k in row)))
753
+ writer.writeheader(); writer.writerows(signals)
754
+ result["signal_csv"] = str(signalpath)
755
+ result["signal_sha256"] = sha(signalpath)
756
+ result["expression_metric_provenance"] = {
757
+ "gene_axis": "cohort scoring genes; Giroux sex-linked genes excluded",
758
+ "reference_expression": "observed sample-level cell-type aggregates on strict test samples",
759
+ "method_expression": "BayesPrism posterior type expression or CIBERSORTx HiRes imputed GEP",
760
+ "bulk": "strict test sample real bulk raw counts from features.npz",
761
+ "sample_unit": "sample; repeated visits retained with explicit donor IDs",
762
+ "top50_deg": "historical Welch benchmark statistic; not corrected patient-level inference",
763
+ "corrected_deg": "limma lmFit/eBayes on matched observed/method continuous log2-CPM donor-condition means; duplicateCorrelation if needed; sensitivity distinct from raw-count edgeR/limma-voom primary",
764
+ "corrected_profile_script_sha256": hashlib.sha256(LIMMA_R.encode()).hexdigest()}
765
+ (p / "SUMMARY.json").write_text(json.dumps(result, indent=2) + "\n")
766
+ if result["status"] == "complete":
767
+ update_figure4(s, result)
768
+ else:
769
+ invalidate_figure4(s, result["pending_reasons"])
770
+ return result
771
+
772
+
773
+ def invalidate_figure4(s: dict, reasons: list[str]) -> None:
774
+ """Retain a prior mapping as inactive so pending reruns cannot look complete."""
775
+ path = PLAN / "deconvolution" / "deconvolution_manifest.json"
776
+ if not path.is_file():
777
+ return
778
+ data = json.loads(path.read_text())
779
+ rel = f'{s["cohort"]}/disease/{s["unit"].replace("_n5", "")}'
780
+ previous = data.get("units", {}).get(rel)
781
+ if previous is None:
782
+ return
783
+ data.setdefault("inactive_units", {})[rel] = {"previous": previous, "reason": reasons}
784
+ del data["units"][rel]
785
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=".deconv_", delete=False) as f:
786
+ json.dump(data, f, indent=2)
787
+ f.write("\n")
788
+ tmp = Path(f.name)
789
+ tmp.replace(path)
790
+
791
+
792
+ def update_figure4(s: dict, result: dict) -> None:
793
+ """Atomic global index consumed by build_results_figures.py --deconvolution-manifest."""
794
+ path = PLAN / "deconvolution" / "deconvolution_manifest.json"
795
+ data = json.loads(path.read_text()) if path.exists() else {"schema": "pbisc.fig4.deconvolution-sources.v1", "units": {}}
796
+ rel = f'{s["cohort"]}/disease/{s["unit"].replace("_n5", "")}'
797
+ data["units"][rel] = {"csv": result["figure4_csv"], "sha256": result["figure4_csv_sha256"],
798
+ "signal_csv": result["signal_csv"], "signal_sha256": result["signal_sha256"],
799
+ "support_sha256": s["sha256"], "reference_sample_ids": s["train_sample_ids"],
800
+ "mixture_sample_ids": s["test_sample_ids"], "methods": result["methods"],
801
+ "metrics": result["metrics"], "source_sha256": result["source_sha256"],
802
+ "expression_metric_provenance": result["expression_metric_provenance"]}
803
+ data.get("inactive_units", {}).pop(rel, None)
804
+ with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=".deconv_", delete=False) as f:
805
+ json.dump(data, f, indent=2)
806
+ f.write("\n")
807
+ tmp = Path(f.name)
808
+ tmp.replace(path)
809
+
810
+
811
+ def main(argv: list[str] | None = None) -> int:
812
+ parser = argparse.ArgumentParser(description=__doc__)
813
+ parser.add_argument("--support-manifest", type=Path, required=True)
814
+ parser.add_argument("--action", choices=("prepare", "bayesprism", "cibersortx", "score", "all"), required=True)
815
+ parser.add_argument("--out", type=Path)
816
+ parser.add_argument("--threads", type=int, default=4)
817
+ a = parser.parse_args(argv)
818
+ if not 1 <= a.threads <= 16:
819
+ parser.error("--threads must be 1..16")
820
+ s = support(a.support_manifest)
821
+ out = unit_out(s, a.out)
822
+ host_preflight()
823
+ if a.action in ("prepare", "all"):
824
+ prepare(s, out)
825
+ if a.action in ("bayesprism", "all"):
826
+ bayesprism(s, out, a.threads)
827
+ if a.action in ("cibersortx", "all"):
828
+ cibersortx(s, out, a.threads)
829
+ if a.action in ("score", "all"):
830
+ result = score(s, out)
831
+ print(json.dumps(result, indent=2))
832
+ if result["status"] != "complete":
833
+ return 1
834
+ return 0
835
+
836
+
837
+ if __name__ == "__main__":
838
+ raise SystemExit(main())
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/disease_signal.py ADDED
@@ -0,0 +1,467 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Donor-aware primary Figure 4 signals from strict scored pseudobulks.
3
+
4
+ No legacy contrast/headline value is read. Counts and corrected limma fits come
5
+ from score_strict's donor_deg outputs. Correlation uncertainty resamples whole
6
+ patients with the SAME weights across all methods and overlapping draws.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import hashlib
12
+ import json
13
+ import os
14
+ from pathlib import Path
15
+
16
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
17
+ import numpy as np
18
+ import pandas as pd
19
+ from scipy.stats import rankdata
20
+
21
+ ROOT = Path(__file__).resolve().parents[1]
22
+ OLD = ROOT.parent / "paired_finetune_intradataset_20260927"
23
+ COHORTS = ("ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
24
+ ARMS = ("raw", "refcal", "lora", "scsemi", "pairedcal")
25
+ METRICS = ("pearson_r", "spearman_r", "partial_r")
26
+ TABLES = {"signal": "fig4_donor_aware_signal.csv", "summary": "fig4_donor_aware_summary.csv",
27
+ "genes": "fig4_donor_aware_genes.csv", "cat": "fig4_donor_aware_cat.csv"}
28
+
29
+
30
+ def sha(path: Path) -> str:
31
+ h = hashlib.sha256()
32
+ with path.open("rb") as f:
33
+ for block in iter(lambda: f.read(1024 * 1024), b""):
34
+ h.update(block)
35
+ return h.hexdigest()
36
+
37
+
38
+ def load(path: Path) -> dict:
39
+ return json.loads(path.read_text())
40
+
41
+
42
+ def prepare_profiles(rows: pd.DataFrame, genes: list[str], cases: list[str], controls: list[str]) -> dict:
43
+ """One log2-CPM profile per donor×contrast group, with equal condition weights.
44
+
45
+ Upstream sums visits within donor×original condition. We normalize that
46
+ pseudobulk once, then average original conditions within a contrast group.
47
+ Thus a patient with two case labels does not count twice in the case mean.
48
+ Missing cell-type profiles remain absent rather than becoming zero cells.
49
+ """
50
+ if set(cases) & set(controls):
51
+ raise ValueError("case and control labels overlap")
52
+ rows = rows.loc[rows.condition.isin(cases + controls)].copy()
53
+ if rows.empty:
54
+ return {"donors": np.array([], str), "case": np.array([], bool),
55
+ "values": np.empty((0, len(genes))), "zero_libraries": 0}
56
+ keys = ["donor_id", "condition", "gene_id"]
57
+ if rows.duplicated(keys).any() or rows[keys].isna().any().any():
58
+ raise ValueError("duplicate or missing donor-condition-gene identity")
59
+ if set(rows.gene_id.astype(str)) != set(genes):
60
+ raise ValueError("pseudobulk gene axis differs from genes_kept")
61
+ matrix = rows.pivot(index=["donor_id", "condition"], columns="gene_id", values="count").reindex(columns=genes)
62
+ if matrix.isna().any().any():
63
+ raise ValueError("a donor-condition profile has an incomplete measured gene axis")
64
+ values = matrix.to_numpy(float)
65
+ if not np.isfinite(values).all() or (values < 0).any():
66
+ raise ValueError("pseudobulk counts must be finite and nonnegative")
67
+ totals = values.sum(axis=1)
68
+ good = totals > 0
69
+ matrix = matrix.iloc[np.flatnonzero(good)]
70
+ values = np.log2(1. + 1e6 * values[good] / totals[good, None])
71
+ ids = matrix.index.get_level_values("donor_id").astype(str).to_numpy()
72
+ labels = matrix.index.get_level_values("condition").astype(str).to_numpy()
73
+ groups = np.isin(labels, cases)
74
+ unique = sorted(set(zip(ids, groups)))
75
+ return {"donors": np.asarray([x[0] for x in unique]),
76
+ "case": np.asarray([x[1] for x in unique], bool),
77
+ "values": np.stack([values[(ids == d) & (groups == c)].mean(0) for d, c in unique])
78
+ if unique else np.empty((0, len(genes))),
79
+ "zero_libraries": int((~good).sum())}
80
+
81
+
82
+ def effect(profiles: dict, weights: dict[str, int] | None = None) -> np.ndarray:
83
+ p = profiles
84
+ w = np.ones(len(p["donors"])) if weights is None else np.asarray([weights.get(x, 0) for x in p["donors"]])
85
+ result = []
86
+ for group in (True, False):
87
+ selected = p["case"] == group
88
+ if len(set(p["donors"][selected & (w > 0)])) < 2:
89
+ return np.full(p["values"].shape[1], np.nan)
90
+ result.append(np.average(p["values"][selected], axis=0, weights=w[selected]))
91
+ return result[0] - result[1]
92
+
93
+
94
+ def patient_weights(donors: list[str], *, n_boot: int, seed: int) -> np.ndarray:
95
+ if len(set(donors)) != len(donors) or not donors or n_boot < 1:
96
+ raise ValueError("bootstrap requires unique patients and a positive replicate count")
97
+ return np.random.default_rng(seed).multinomial(len(donors), np.full(len(donors), 1 / len(donors)), size=n_boot)
98
+
99
+
100
+ def bootstrap_effect(profiles: dict, donors: list[str], weights: np.ndarray) -> np.ndarray:
101
+ pos = {d: i for i, d in enumerate(donors)}
102
+ if not set(profiles["donors"]) <= set(pos):
103
+ raise ValueError("pseudobulk donor lies outside bootstrap population")
104
+ w = weights[:, [pos[d] for d in profiles["donors"]]]
105
+ result = []
106
+ valid = np.ones(len(weights), bool)
107
+ for group in (True, False):
108
+ selected = profiles["case"] == group
109
+ wg = w[:, selected]
110
+ # prepare_profiles guarantees one row per donor in each contrast group.
111
+ valid &= (wg > 0).sum(axis=1) >= 2
112
+ den = wg.sum(axis=1)
113
+ result.append(np.divide(wg @ profiles["values"][selected], den[:, None],
114
+ out=np.full((len(weights), profiles["values"].shape[1]), np.nan),
115
+ where=den[:, None] > 0))
116
+ answer = result[0] - result[1]
117
+ answer[~valid] = np.nan
118
+ return answer
119
+
120
+
121
+ def row_correlation(x: np.ndarray, y: np.ndarray) -> np.ndarray:
122
+ x, y = np.atleast_2d(x), np.atleast_2d(y)
123
+ if x.shape != y.shape or x.shape[1] < 3:
124
+ return np.full(x.shape[0], np.nan)
125
+ xc, yc = x - x.mean(axis=1, keepdims=True), y - y.mean(axis=1, keepdims=True)
126
+ den = np.linalg.norm(xc, axis=1) * np.linalg.norm(yc, axis=1)
127
+ return np.divide((xc * yc).sum(axis=1), den, out=np.full(len(x), np.nan), where=den > 1e-12)
128
+
129
+
130
+ def correlations(observed: np.ndarray, generated: np.ndarray, bulk: np.ndarray) -> dict:
131
+ o, g, b = (np.atleast_2d(x) for x in (observed, generated, bulk))
132
+ if o.shape != g.shape or o.shape != b.shape:
133
+ raise ValueError("observed, generated and bulk contrasts must share the gene axis")
134
+ if o.shape[1] < 3:
135
+ return {k: (float('nan') if observed.ndim == 1 else np.full(len(o), np.nan)) for k in METRICS}
136
+ bc = b - b.mean(axis=1, keepdims=True)
137
+ den = (bc * bc).sum(axis=1)
138
+ residual = []
139
+ for x in (o, g):
140
+ xc = x - x.mean(axis=1, keepdims=True)
141
+ slope = np.divide((xc * bc).sum(axis=1), den, out=np.full(len(x), np.nan), where=den > 1e-12)
142
+ residual.append(xc - slope[:, None] * bc)
143
+ answer = {"pearson_r": row_correlation(o, g),
144
+ "spearman_r": row_correlation(rankdata(o, axis=1), rankdata(g, axis=1)),
145
+ "partial_r": row_correlation(*residual)}
146
+ return {k: float(v[0]) for k, v in answer.items()} if observed.ndim == 1 else answer
147
+
148
+
149
+ def interval(x: np.ndarray) -> tuple[float, float, int]:
150
+ good = np.asarray(x)[np.isfinite(x)]
151
+ if len(good) < max(2, .8 * len(x)):
152
+ return float("nan"), float("nan"), len(good)
153
+ lo, hi = np.quantile(good, [.025, .975])
154
+ return float(lo), float(hi), len(good)
155
+
156
+
157
+ def mean_bootstraps(arrays: list[np.ndarray]) -> np.ndarray:
158
+ """Same patient draw across every adaptation draw; require every draw finite."""
159
+ return np.stack(arrays).mean(axis=0)
160
+
161
+
162
+ def rank_metrics(observed: pd.DataFrame, generated: pd.DataFrame, genes: list[str],
163
+ ks=(10, 25, 50, 100, 200, 500)) -> tuple[dict, list[dict], pd.DataFrame]:
164
+ """Corrected limma FDR top50; CAT ranks |moderated t|, deterministic gene ties."""
165
+ required = {"gene_id", "logFC", "t", "adj.P.Val"}
166
+ for table in (observed, generated):
167
+ if not required <= set(table) or table.gene_id.duplicated().any():
168
+ raise ValueError("corrected limma gene table invalid")
169
+ tables = [t[t.gene_id.isin(genes)].copy() for t in (observed, generated)]
170
+ top, rankings = [], []
171
+ merged = pd.DataFrame({"gene_id": genes})
172
+ for label, table in zip(("observed", "generated"), tables):
173
+ if not np.isfinite(table[["logFC", "t", "adj.P.Val"]].to_numpy(float)).all():
174
+ raise ValueError("nonfinite corrected limma output")
175
+ sig = table[table["adj.P.Val"] < .05].assign(abs_lfc=lambda x: x.logFC.abs())
176
+ top.append(set(sig.sort_values(["abs_lfc", "gene_id"], ascending=[False, True]).head(50).gene_id))
177
+ rank = table.assign(abs_t=lambda x: x.t.abs()).sort_values(["abs_t", "gene_id"], ascending=[False, True])
178
+ rankings.append(rank)
179
+ merged = merged.merge(table[list(required)].rename(columns={"logFC": label + "_limma_logFC",
180
+ "t": label + "_limma_t",
181
+ "adj.P.Val": label + "_limma_q"}),
182
+ on="gene_id", how="left", validate="one_to_one")
183
+ result = {"limma_top50": len(top[0] & top[1]), "observed_top50_size": len(top[0]),
184
+ "generated_top50_size": len(top[1]),
185
+ "limma_top50_chance": len(top[0]) * len(top[1]) / len(genes) if genes else np.nan,
186
+ "n_limma_tested_observed": len(tables[0]), "n_limma_tested_generated": len(tables[1])}
187
+ curves = []
188
+ for k in ks:
189
+ available = all(len(t) >= k for t in rankings)
190
+ a, b = rankings[0].head(k), rankings[1].head(k)
191
+ intersection = set(a.gene_id) & set(b.gene_id)
192
+ signs = [dict(zip(t.gene_id, np.sign(t.logFC))) for t in (a, b)]
193
+ same = sum(signs[0][g] == signs[1][g] and signs[0][g] != 0 for g in intersection)
194
+ curves.append({"k": k, "status": "ok" if available else "not_estimable",
195
+ "cat_same_sign": same / k if available else np.nan,
196
+ "cat_any_sign": len(intersection) / k if available else np.nan,
197
+ "chance_same_sign": k / (2 * len(genes)) if available else np.nan,
198
+ "chance_model": "uniform_independent_rankings_symmetric_signs"})
199
+ for c in curves:
200
+ if c["k"] == 50:
201
+ result.update(cat50=c["cat_same_sign"], cat50_chance=c["chance_same_sign"])
202
+ # Extrapolated finite equal-length RBO: lists restricted to the shared fitted universe.
203
+ common = set(rankings[0].gene_id) & set(rankings[1].gene_id)
204
+ ranks = [[g for g in t.gene_id if g in common] for t in rankings]
205
+ p, total, seen_a, seen_b, overlap = .9, 0., set(), set(), 0
206
+ for d, (a, b) in enumerate(zip(*ranks), start=1):
207
+ seen_a.add(a); seen_b.add(b)
208
+ overlap = len(seen_a & seen_b)
209
+ total += (1 - p) * p ** (d - 1) * overlap / d
210
+ result["rbo_p09"] = total + (p ** len(common) * overlap / len(common) if common else np.nan)
211
+ return result, curves, merged
212
+
213
+
214
+ def checked_unit(support_path: Path) -> tuple[dict, dict, Path, dict]:
215
+ """Validate canonical support, strict source binding and completed corrected fits."""
216
+ import score_strict as S
217
+ support = S.read_support(support_path)
218
+ rel = support_path.parent.relative_to(ROOT / "protocol/splits")
219
+ if (support["cohort"] not in COHORTS or support["n_pairs"] != 5
220
+ or support.get("design") != "disease_existing_draw"
221
+ or rel.parts != (support["cohort"], "disease", support["unit"].removesuffix("_n5"))):
222
+ raise ValueError("noncanonical disease strict-five support")
223
+ out = ROOT / "scores" / rel
224
+ summary_path, binding_path, status_path = (out / "score/summary.json", out / "scoring_support.json", out / "statistics/status.json")
225
+ for path in (summary_path, binding_path, status_path, out / "statistics/donor_deg/donor_deg_summary.csv"):
226
+ if not path.is_file():
227
+ raise FileNotFoundError(str(path))
228
+ summary, binding, status = load(summary_path), load(binding_path), load(status_path)
229
+ if (set(summary["arms"]) != set(ARMS) or summary["dataset"] != support["cohort"]
230
+ or summary["donors"] != support["test_sample_ids"]
231
+ or binding.get("schema") != "pbisc.paper.strict-score-binding.v1"
232
+ or binding.get("support_sha256") != support["sha256"]
233
+ or binding.get("test_sample_ids") != support["test_sample_ids"]
234
+ or binding.get("test_donor_ids") != support["test_donor_ids"]
235
+ or set(binding.get("arm_bindings", {})) != set(ARMS)
236
+ or status.get("support_sha256") != support["sha256"]):
237
+ raise ValueError("disease source does not bind canonical strict score")
238
+ if status.get("disease_deg", {}).get("status") not in ("ok", "complete_with_not_estimable"):
239
+ raise FileNotFoundError("corrected disease DEG is pending: " + str(status_path))
240
+ sources = {str(p): sha(p) for p in (support_path, summary_path, binding_path, status_path)}
241
+ for arm in ARMS:
242
+ bound = binding["arm_bindings"][arm]
243
+ pa = summary["per_arm"][arm]
244
+ if bound.get("support_sha256") != support["sha256"] or bound.get("npz_sha256") != pa.get("npz_sha256"):
245
+ raise ValueError("generated NPZ binding differs from corrected score")
246
+ for key in ("receipt", "source_binding"):
247
+ path = Path(bound[key])
248
+ if not path.is_file() or sha(path) != bound[key + "_sha256"]:
249
+ raise ValueError("generation provenance changed: " + str(path))
250
+ sources[str(path)] = bound[key + "_sha256"]
251
+ return support, summary, out, sources
252
+
253
+
254
+ def bulk_rows(support: dict, summary: dict, genes: list[str]) -> tuple[pd.DataFrame, dict]:
255
+ path = OLD / "data" / support["cohort"] / "features.npz"
256
+ folds_path = path.with_name("folds.csv")
257
+ folds = pd.read_csv(folds_path, dtype=str).set_index("sample_id")
258
+ ids = summary["donors"]
259
+ groups = summary["contrast_definition"]["groups"]
260
+ if (folds.loc[ids, "donor_id"].tolist() != support["test_donor_ids"]
261
+ or folds.loc[ids, "group"].tolist() != groups):
262
+ raise ValueError("bulk patient or condition mapping differs from scored support")
263
+ with np.load(path, allow_pickle=False) as z:
264
+ sid = (z["sample_ids"] if "sample_ids" in z.files else z["donor_ids"]).astype(str)
265
+ spos, gpos = {s: i for i, s in enumerate(sid)}, {g: i for i, g in enumerate(z["gene_ids"].astype(str))}
266
+ ix, jx = [spos[x] for x in ids], [gpos[g] for g in genes]
267
+ if not z["bulk_valid"][np.ix_(ix, jx)].all():
268
+ raise ValueError("a scoring gene is unmeasured in a target bulk")
269
+ x = z["bulk_raw"][np.ix_(ix, jx)].astype(float)
270
+ rows = pd.DataFrame({"donor_id": np.repeat(support["test_donor_ids"], len(genes)),
271
+ "condition": np.repeat(groups, len(genes)), "gene_id": np.tile(genes, len(ids)),
272
+ "count": x.reshape(-1)})
273
+ return rows.groupby(["donor_id", "condition", "gene_id"], as_index=False)["count"].sum(), {
274
+ str(path): sha(path), str(folds_path): sha(folds_path)}
275
+
276
+
277
+ def _coverage(profile: dict, prefix: str) -> dict:
278
+ return {prefix + "_n_donors": len(set(profile["donors"])),
279
+ prefix + "_n_case_donors": len(set(profile["donors"][profile["case"]])),
280
+ prefix + "_n_control_donors": len(set(profile["donors"][~profile["case"]])),
281
+ prefix + "_zero_libraries": profile.get("zero_libraries", 0)}
282
+
283
+
284
+ def process_unit(support: dict, summary: dict, out: Path, donors: list[str], weights: np.ndarray,
285
+ sources: dict) -> tuple[list, list, list, dict]:
286
+ dest = out / "statistics/donor_deg"
287
+ genes_path, summary_path = dest / "genes_kept.csv", dest / "donor_deg_summary.csv"
288
+ sources.update({str(p): sha(p) for p in (genes_path, summary_path)})
289
+ genes = pd.read_csv(genes_path).gene_id.astype(str).tolist()
290
+ if len(set(genes)) != len(genes) or not genes:
291
+ raise ValueError("invalid corrected gene axis")
292
+ if support["cohort"] == "giroux2022":
293
+ exclusion = summary.get("gene_exclusion", {})
294
+ if not exclusion or sha(Path(exclusion["file"])) != exclusion["sha256"]:
295
+ raise ValueError("Giroux sex-linked gene exclusion missing or changed")
296
+ if set(genes) & set(pd.read_csv(exclusion["file"]).gene_id.astype(str)):
297
+ raise ValueError("Giroux corrected gene axis includes an excluded sex-linked gene")
298
+ sources[exclusion["file"]] = exclusion["sha256"]
299
+ definitions = summary["contrast_definition"]
300
+ cases, controls = definitions["case_groups"], definitions["control_groups"]
301
+ br, bsources = bulk_rows(support, summary, genes)
302
+ sources.update(bsources)
303
+ bulk = prepare_profiles(br, genes, cases, controls)
304
+ bfc, bboot = effect(bulk), bootstrap_effect(bulk, donors, weights)
305
+ fit_summary = pd.read_csv(summary_path)
306
+ if fit_summary.duplicated(["arm", "celltype"]).any() or set(fit_summary.arm) != set(ARMS):
307
+ raise ValueError("corrected fit summary is incomplete or duplicated")
308
+ types = sorted(fit_summary.celltype.unique())
309
+ if set(zip(fit_summary.arm, fit_summary.celltype)) != {(a, t) for a in ARMS for t in types}:
310
+ raise ValueError("corrected fit summary is not a complete arm by cell-type grid")
311
+ allowed = set(zip(support["test_donor_ids"], definitions["groups"]))
312
+ rows, gene_rows, cat_rows, bootstrap = [], [], [], {}
313
+ for typ in types:
314
+ ref = None
315
+ for arm in ARMS:
316
+ f = fit_summary[(fit_summary.arm == arm) & (fit_summary.celltype == typ)].iloc[0]
317
+ if f.status == "pending":
318
+ raise FileNotFoundError(f"corrected limma pending for {out}: {arm}/{typ}")
319
+ slug = __import__("re").sub(r"[^a-z0-9]+", "_", typ.lower()).strip("_")
320
+ directory = dest / arm / slug
321
+ pb_path, limma_path, status_path = (directory / "donor_condition_pseudobulk.csv",
322
+ directory / "donor_limma_genes.csv", directory / "limma_status.json")
323
+ if not pb_path.is_file() or not status_path.is_file():
324
+ raise FileNotFoundError(str(directory))
325
+ sources.update({str(p): sha(p) for p in (pb_path, status_path)})
326
+ fit_status = load(status_path)
327
+ jobs = {j["side"]: j for j in fit_status.get("jobs", [])}
328
+ if (fit_status.get("status") not in ("ok", "complete_with_not_estimable")
329
+ or (f.status == "ok" and any(jobs.get(s, {}).get("status") != "ok" for s in ("observed", arm)))):
330
+ raise ValueError("corrected limma summary and actual fit status differ")
331
+ table = pd.read_csv(pb_path, dtype={"donor_id": str, "condition": str, "gene_id": str})
332
+ if (not set(table.side) <= {"observed", arm} or not set(table.celltype) <= {typ}
333
+ or not set(zip(table.donor_id, table.condition)) <= allowed):
334
+ raise ValueError("corrected pseudobulk contains a foreign patient/condition/population")
335
+ observed = table[table.side == "observed"].sort_values(["donor_id", "condition", "gene_id"]).reset_index(drop=True)
336
+ if ref is not None and not observed.equals(ref):
337
+ raise ValueError("observed reference differs between methods")
338
+ ref = observed
339
+ o = prepare_profiles(observed, genes, cases, controls)
340
+ g = prepare_profiles(table[table.side == arm], genes, cases, controls)
341
+ keep = observed.groupby("gene_id")["count"].sum().reindex(genes, fill_value=0).to_numpy() > 0
342
+ gene_axis = np.asarray(genes)[keep].tolist()
343
+ ofc, gfc = effect(o), effect(g)
344
+ values = correlations(ofc[keep], gfc[keep], bfc[keep])
345
+ boot = correlations(bootstrap_effect(o, donors, weights)[:, keep],
346
+ bootstrap_effect(g, donors, weights)[:, keep], bboot[:, keep])
347
+ key = (arm, typ)
348
+ bootstrap[key] = boot
349
+ meta = {"cohort": support["cohort"], "draw": support["unit"].removesuffix("_n5"),
350
+ "support_unit": support["unit"], "arm": arm, "celltype": typ,
351
+ "support_sha256": support["sha256"], "n_genes": int(keep.sum()),
352
+ "status": "ok" if np.isfinite(values["pearson_r"]) else "not_estimable",
353
+ "deg_status": str(f.status), "reference_scope": "full_observed_heldout_population",
354
+ "generated_scope": "available_generated_population_no_zero_fill",
355
+ "statistic": "equal_patient_group_mean_log2_cpm_plus1_difference",
356
+ "bootstrap_unit": "same_patient_weights_across_all_methods_and_draws",
357
+ "n_bootstrap": len(weights), **_coverage(o, "observed"), **_coverage(g, "generated"), **values}
358
+ if meta["status"] != "ok":
359
+ meta["reason"] = "fewer than two donors per group, fewer than three expressed genes, or constant contrast"
360
+ for metric in METRICS:
361
+ lo, hi, n = interval(boot[metric])
362
+ meta.update({metric + "_ci_low": lo, metric + "_ci_high": hi, metric + "_bootstrap_valid": n})
363
+ gene = pd.DataFrame({"gene_id": gene_axis, "observed_logFC": ofc[keep],
364
+ "generated_logFC": gfc[keep], "bulk_logFC": bfc[keep]})
365
+ if f.status == "ok":
366
+ if not limma_path.is_file():
367
+ raise FileNotFoundError(str(limma_path))
368
+ sources[str(limma_path)] = sha(limma_path)
369
+ lm = pd.read_csv(limma_path, dtype={"gene_id": str})
370
+ ranks, curves, ranks_gene = rank_metrics(lm[lm.side == "observed"], lm[lm.side == arm], gene_axis)
371
+ meta.update(ranks)
372
+ gene = gene.merge(ranks_gene, on="gene_id", how="left", validate="one_to_one")
373
+ cat_rows.extend({**{k: meta[k] for k in ("cohort", "draw", "arm", "celltype", "support_sha256")}, **c}
374
+ for c in curves)
375
+ else:
376
+ meta["deg_reason"] = "; ".join(str(f.get(k)) for k in ("reason_observed", "reason_generated", "reason_population") if pd.notna(f.get(k)))
377
+ rows.append(meta)
378
+ gene_rows.extend(gene.assign(**{k: meta[k] for k in ("cohort", "draw", "arm", "celltype", "support_sha256")}).to_dict("records"))
379
+ return rows, gene_rows, cat_rows, bootstrap
380
+
381
+
382
+ def main() -> None:
383
+ parser = argparse.ArgumentParser(description=__doc__)
384
+ parser.add_argument("--require-complete", action="store_true")
385
+ parser.add_argument("--n-bootstrap", type=int, default=2000)
386
+ parser.add_argument("--seed", type=int, default=20261012)
387
+ args = parser.parse_args()
388
+ if args.require_complete and (args.n_bootstrap != 2000 or args.seed != 20261012):
389
+ parser.error("publication protocol requires 2000 patient bootstraps and seed 20261012")
390
+ all_rows, all_genes, all_cat, aggregate, missing, units, sources = [], [], [], [], [], {}, {}
391
+ for ci, cohort in enumerate(COHORTS):
392
+ available = []
393
+ for draw in range(5):
394
+ path = ROOT / "protocol/splits" / cohort / "disease" / f"draw{draw}" / "support.json"
395
+ try:
396
+ support, summary, out, source = checked_unit(path)
397
+ available.append((support, summary, out, source))
398
+ except FileNotFoundError as exc:
399
+ missing.append(str(exc))
400
+ if len(available) != 5:
401
+ continue # cohort estimates require all five prespecified adaptation draws
402
+ donors = sorted({d for support, _, _, _ in available for d in support["test_donor_ids"]})
403
+ weights = patient_weights(donors, n_boot=args.n_bootstrap, seed=args.seed + ci)
404
+ boot_by_key = {}
405
+ cohort_rows = []
406
+ for support, summary, out, source in available:
407
+ rows, genes, cats, boots = process_unit(support, summary, out, donors, weights, source)
408
+ all_rows.extend(rows); cohort_rows.extend(rows); all_genes.extend(genes); all_cat.extend(cats)
409
+ sources.update(source)
410
+ units[str(out.relative_to(ROOT / "scores"))] = {"support_sha256": support["sha256"],
411
+ "sources": source}
412
+ for key, item in boots.items():
413
+ boot_by_key.setdefault(key, []).append(item)
414
+ frame = pd.DataFrame(cohort_rows)
415
+ for (arm, celltype), group in frame.groupby(["arm", "celltype"], sort=True):
416
+ row = {"cohort": cohort, "arm": arm, "celltype": celltype, "n_draws": len(group),
417
+ "n_independent_patients": len(donors), "patient_bootstrap_replicates": args.n_bootstrap,
418
+ "status": "ok" if group.status.eq("ok").all() else "contains_not_estimable_draws",
419
+ "bootstrap_unit": "shared_patients_across_draws_and_methods",
420
+ "draw_variation": "SD_across_five_fixed_adaptation_draws_not_a_CI"}
421
+ for metric in (*METRICS, "limma_top50", "limma_top50_chance", "cat50", "cat50_chance", "rbo_p09"):
422
+ values = pd.to_numeric(group.get(metric, pd.Series(dtype=float)), errors="coerce")
423
+ good = values[np.isfinite(values)]
424
+ row[metric + "_n_draws"] = len(good)
425
+ row[metric] = float(good.mean()) if len(good) == 5 else np.nan
426
+ row[metric + "_draw_sd"] = float(good.std(ddof=1)) if len(good) == 5 else np.nan
427
+ if metric in METRICS:
428
+ boot = mean_bootstraps([b[metric] for b in boot_by_key[(arm, celltype)]])
429
+ lo, hi, n = interval(boot)
430
+ row.update({metric + "_ci_low": lo, metric + "_ci_high": hi, metric + "_bootstrap_valid": n})
431
+ baseline = frame[(frame.arm == "scsemi") & (frame.celltype == celltype)]
432
+ base_values = pd.to_numeric(baseline[metric], errors="coerce")
433
+ row[metric + "_minus_scsemi"] = (row[metric] - float(base_values.mean())
434
+ if len(base_values) == 5 and np.isfinite(base_values).all() else np.nan)
435
+ base_boot = mean_bootstraps([b[metric] for b in boot_by_key[("scsemi", celltype)]])
436
+ lo, hi, n = interval(boot - base_boot)
437
+ row.update({metric + "_minus_scsemi_ci_low": lo, metric + "_minus_scsemi_ci_high": hi,
438
+ metric + "_minus_scsemi_bootstrap_valid": n})
439
+ aggregate.append(row)
440
+ output = ROOT / "source_data"
441
+ output.mkdir(parents=True, exist_ok=True)
442
+ outputs = {}
443
+ for key, data in (("signal", all_rows), ("summary", aggregate), ("genes", all_genes), ("cat", all_cat)):
444
+ path = output / TABLES[key]
445
+ frame = pd.DataFrame(data) if data else pd.DataFrame(columns=["cohort", "draw", "arm", "celltype", "status"])
446
+ frame.to_csv(path, index=False)
447
+ outputs[key] = {"path": str(path), "sha256": sha(path), "rows": len(frame)}
448
+ complete = len(units) == 20 and not missing
449
+ provenance = {"schema": "pbisc.fig4.donor-aware-signal.v1", "status": "complete" if complete else "pending",
450
+ "units": units, "missing": missing, "outputs": outputs, "sources": sources,
451
+ "script_sha256": sha(Path(__file__)), "n_bootstrap": args.n_bootstrap, "seed": args.seed,
452
+ "gene_filter": "genes_kept from corrected score including Giroux exclusion; then observed nonzero per type, shared across methods",
453
+ "observed_reference": "full observed heldout population identical across methods; generated absent populations remain absent",
454
+ "expression": "visits summed within original donor-condition, log2(CPM+1), original conditions averaged within group and patient, equal patient case-control difference",
455
+ "bulk_adjustment": "same raw measured bulk contrast for all methods; same patient aggregation; never calibration-specific bulk",
456
+ "uncertainty": "2000 default multinomial patient resamples; shared weights across draws/methods; all visits travel together; >=80% valid required; draw SD separate",
457
+ "deg": "corrected edgeR TMM limma-voom; duplicateCorrelation when repeated donor conditions; FDR<0.05 then top50 absolute logFC; no relabelled Welch",
458
+ "rank_uncertainty": "CAT, RBO and DEG overlap have adaptation draw SD only; limma not refit per patient bootstrap; no fabricated rank CI",
459
+ "legacy_contrast": "not consumed; retained separately as historical sensitivity"}
460
+ (output / "fig4_donor_aware_provenance.json").write_text(json.dumps(provenance, indent=2, allow_nan=False) + "\n")
461
+ print(json.dumps({"status": provenance["status"], "units": len(units), "signal_rows": len(all_rows)}))
462
+ if args.require_complete and not complete:
463
+ raise SystemExit("All 20 corrected disease units are required")
464
+
465
+
466
+ if __name__ == "__main__":
467
+ main()
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/donor_limma.R ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+ # Corrected disease DEG: existing donor x cell-type summed counts, collapsed by
3
+ # donor x condition. Paired conditions use duplicateCorrelation(block=donor).
4
+ suppressPackageStartupMessages({
5
+ library(edgeR)
6
+ library(limma)
7
+ library(jsonlite)
8
+ })
9
+ args <- commandArgs(trailingOnly=TRUE)
10
+ if (length(args) != 4L) stop("usage: donor_limma.R PSEUDOBULK.csv OUT_DIR CASE_LABELS CONTROL_LABELS")
11
+ inp <- read.csv(args[1], stringsAsFactors=FALSE, check.names=FALSE)
12
+ out <- args[2]
13
+ case <- strsplit(args[3], ",", fixed=TRUE)[[1]]
14
+ control <- strsplit(args[4], ",", fixed=TRUE)[[1]]
15
+ if (length(intersect(case, control))) stop("case and control labels overlap")
16
+ if (!"side" %in% names(inp)) inp$side <- "observed"
17
+ required <- c("donor_id", "condition", "celltype", "gene_id", "count", "side")
18
+ if (!all(required %in% names(inp))) stop("pseudobulk columns missing")
19
+ if (any(!is.finite(inp$count) | inp$count < 0)) stop("nonfinite or negative counts")
20
+ inp <- inp[inp$condition %in% c(case, control), , drop=FALSE]
21
+ jobs <- split(inp, interaction(inp$side, inp$celltype, drop=TRUE), drop=TRUE)
22
+ statuses <- list()
23
+ genes_out <- list()
24
+ for (name in names(jobs)) {
25
+ z <- jobs[[name]]
26
+ side <- z$side[1]
27
+ celltype <- z$celltype[1]
28
+ d <- unique(z[,c("donor_id", "condition")])
29
+ d <- d[order(d$donor_id, d$condition),,drop=FALSE]
30
+ d$group <- ifelse(d$condition %in% case, "case", "control")
31
+ ncase <- length(unique(d$donor_id[d$group == "case"]))
32
+ nctrl <- length(unique(d$donor_id[d$group == "control"]))
33
+ blocked <- any(table(d$donor_id) > 1L)
34
+ status <- list(side=side, celltype=celltype, n_donor_condition=nrow(d),
35
+ n_case_donors=ncase, n_control_donors=nctrl,
36
+ n_unique_donors=length(unique(d$donor_id)),
37
+ method=if (blocked) "edgeR_TMM_limma_voom_duplicateCorrelation" else "edgeR_TMM_limma_voom",
38
+ status="pending")
39
+ if (ncase < 2L || nctrl < 2L) {
40
+ status$status <- "not_estimable"
41
+ status$reason <- "fewer than two unique donors in a group"
42
+ statuses[[length(statuses)+1L]] <- status
43
+ next
44
+ }
45
+ result <- tryCatch({
46
+ gs <- sort(unique(z$gene_id))
47
+ sam <- paste(d$donor_id, d$condition, sep="\034")
48
+ M <- matrix(0, nrow=length(gs), ncol=nrow(d), dimnames=list(gs, sam))
49
+ ii <- match(z$gene_id, gs)
50
+ jj <- match(paste(z$donor_id, z$condition, sep="\034"), sam)
51
+ # Input may have multiple sample rows per donor-condition; sum them.
52
+ for (k in seq_len(nrow(z))) M[ii[k], jj[k]] <- M[ii[k], jj[k]] + z$count[k]
53
+ if (any(colSums(M) <= 0)) stop("zero donor-condition library")
54
+ grp <- factor(d$group, levels=c("control", "case"))
55
+ design <- model.matrix(~grp)
56
+ y <- DGEList(counts=M)
57
+ keep <- rowSums(M) > 0 # legacy primary 'nonzero' filter, now donor-aware fit
58
+ if (sum(keep) < 3L) stop("fewer than 3 genes pass nonzero filter")
59
+ y <- y[keep,,keep.lib.sizes=FALSE]
60
+ y <- calcNormFactors(y, method="TMM")
61
+ v <- voom(y, design, plot=FALSE)
62
+ corr <- NA_real_
63
+ if (blocked) {
64
+ dc <- duplicateCorrelation(v, design, block=d$donor_id)
65
+ corr <- dc$consensus.correlation
66
+ if (!is.finite(corr)) stop("duplicateCorrelation undefined")
67
+ v <- voom(y, design, plot=FALSE, block=d$donor_id, correlation=corr)
68
+ fit <- eBayes(lmFit(v, design, block=d$donor_id, correlation=corr))
69
+ } else {
70
+ fit <- eBayes(lmFit(v, design))
71
+ }
72
+ tt <- topTable(fit, coef=2, number=Inf, sort.by="none")
73
+ cols <- c("logFC", "AveExpr", "t", "P.Value", "adj.P.Val", "B")
74
+ if (!identical(rownames(tt), rownames(y))) stop("gene row order changed")
75
+ g <- data.frame(side=side, celltype=celltype, gene_id=rownames(tt),
76
+ tt[,cols,drop=FALSE], check.names=FALSE)
77
+ ord <- order(-abs(g$logFC), g$gene_id)
78
+ significant <- g[ord, , drop=FALSE]
79
+ significant <- significant[is.finite(significant$adj.P.Val) & significant$adj.P.Val < 0.05,,drop=FALSE]
80
+ g$top50 <- g$gene_id %in% head(significant$gene_id, 50L)
81
+ list(genes=g, n_tested=nrow(g), n_sig=nrow(significant),
82
+ top50=head(significant$gene_id, 50L), correlation=corr)
83
+ }, error=function(e) e)
84
+ if (inherits(result, "error")) {
85
+ status$reason <- conditionMessage(result)
86
+ if (grepl("zero donor-condition library|fewer than 3 genes|duplicateCorrelation undefined",
87
+ status$reason)) status$status <- "not_estimable"
88
+ } else {
89
+ status$status <- "ok"
90
+ status$n_tested <- result$n_tested
91
+ status$n_significant_fdr05 <- result$n_sig
92
+ status$top50_gene_ids <- as.list(result$top50)
93
+ if (blocked) status$duplicate_correlation <- result$correlation
94
+ genes_out[[length(genes_out)+1L]] <- result$genes
95
+ }
96
+ statuses[[length(statuses)+1L]] <- status
97
+ }
98
+ if (length(genes_out)) write.csv(do.call(rbind, genes_out), file.path(out, "donor_limma_genes.csv"), row.names=FALSE)
99
+ job_states <- vapply(statuses, function(x) x$status, character(1))
100
+ overall <- if (length(statuses) == 0L) "complete_with_not_estimable" else
101
+ if (any(job_states == "pending")) "partial_or_pending" else
102
+ if (any(job_states == "not_estimable")) "complete_with_not_estimable" else "ok"
103
+ write_json(list(schema="pbisc.paper.donor-deg.v1", status=overall,
104
+ jobs=statuses, versions=list(R=R.version.string, limma=as.character(packageVersion("limma")), edgeR=as.character(packageVersion("edgeR")))),
105
+ file.path(out, "limma_status.json"), auto_unbox=TRUE, pretty=TRUE, na="null")
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/donor_statistics.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Donor-clustered comparisons and donor-aware pseudobulk DEG for strict pairs.
3
+
4
+ The legacy scorers remain untouched. This module reports corrected inference
5
+ separately; visits and reused draw members never become independent donors.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ import subprocess
12
+ from pathlib import Path
13
+
14
+ import numpy as np
15
+ import pandas as pd
16
+
17
+ DEFAULT_BOOTSTRAPS = 2000
18
+ DEFAULT_SEED = 20261012
19
+ REQUIRED_PB = {"donor_id", "sample_id", "condition", "celltype", "gene_id", "count"}
20
+
21
+
22
+ def validate_patient_mapping(mapping: pd.DataFrame) -> pd.DataFrame:
23
+ """One explicit patient per sample; repeated visits of a patient are allowed."""
24
+ need = {"sample_id", "donor_id"}
25
+ if not need <= set(mapping):
26
+ raise ValueError(f"patient mapping missing {sorted(need - set(mapping))}")
27
+ x = mapping.loc[:, ["sample_id", "donor_id"]].copy()
28
+ if x.isna().any().any() or x.astype(str).apply(lambda c: c.str.strip().eq("")).any().any():
29
+ raise ValueError("missing sample or donor identity")
30
+ x = x.astype(str)
31
+ if x.groupby("sample_id").donor_id.nunique().gt(1).any():
32
+ raise ValueError("conflicting donor IDs for a sample")
33
+ return x.drop_duplicates().reset_index(drop=True)
34
+
35
+
36
+ def paired_donor_bootstrap(rows: pd.DataFrame, arm: str, baseline: str, *,
37
+ n_boot: int = DEFAULT_BOOTSTRAPS, seed: int = DEFAULT_SEED) -> dict:
38
+ """Difference arm-baseline, paired by draw+sample, averaged within donor, then bootstrapped by donor.
39
+
40
+ A donor is sampled once per replicate, carrying all its visits and appearances
41
+ across draws. Donors have equal weight irrespective of their visit count.
42
+ """
43
+ need = {"draw", "donor_id", "sample_id", "arm", "value"}
44
+ if not need <= set(rows):
45
+ raise ValueError(f"paired rows missing {sorted(need - set(rows))}")
46
+ if n_boot < 1:
47
+ raise ValueError("n_boot must be positive")
48
+ x = rows.loc[rows.arm.isin((arm, baseline)), list(need)].copy()
49
+ validate_patient_mapping(x)
50
+ if x.duplicated(["draw", "donor_id", "sample_id", "arm"]).any():
51
+ raise ValueError("duplicate draw/sample/arm metric")
52
+ x["value"] = pd.to_numeric(x.value, errors="coerce")
53
+ wide = x.pivot(index=["draw", "donor_id", "sample_id"], columns="arm", values="value")
54
+ if arm not in wide or baseline not in wide:
55
+ raise ValueError("no paired observations")
56
+ paired = wide[[arm, baseline]].replace([np.inf, -np.inf], np.nan)
57
+ n_bad = int(paired.isna().any(axis=1).sum())
58
+ paired = paired.dropna()
59
+ if paired.empty:
60
+ raise ValueError("no paired finite observations")
61
+ differences = paired[arm] - paired[baseline]
62
+ donor_mean = differences.groupby(level="donor_id").mean().sort_index()
63
+ values = donor_mean.to_numpy(dtype=float)
64
+ if len(values) < 2:
65
+ raise ValueError("bootstrap CI needs at least two independent donors")
66
+ rng = np.random.default_rng(seed)
67
+ draws = rng.integers(0, len(values), size=(n_boot, len(values)))
68
+ estimates = values[draws].mean(axis=1)
69
+ lo, hi = np.quantile(estimates, [0.025, 0.975])
70
+ return {"arm": arm, "baseline": baseline, "estimate": float(values.mean()),
71
+ "ci_low": float(lo), "ci_high": float(hi), "n_donors": len(values),
72
+ "n_paired_samples": int(len(paired)), "n_excluded_nonfinite_pairs": n_bad,
73
+ "n_boot": n_boot, "seed": seed, "bootstrap_unit": "donor_all_draws_and_visits"}
74
+
75
+
76
+ def donor_condition_pseudobulk(rows: pd.DataFrame) -> pd.DataFrame:
77
+ """Sum existing per-sample cell-type counts within donor×condition; no new units."""
78
+ if not REQUIRED_PB <= set(rows):
79
+ raise ValueError(f"pseudobulk missing {sorted(REQUIRED_PB - set(rows))}")
80
+ keys = sorted(REQUIRED_PB | ({"side"} if "side" in rows else set()))
81
+ x = rows.loc[:, keys].copy()
82
+ validate_patient_mapping(x)
83
+ if x[list(REQUIRED_PB - {"count"})].isna().any().any():
84
+ raise ValueError("missing pseudobulk identity")
85
+ for col in ("donor_id", "sample_id", "condition", "celltype", "gene_id") + (("side",) if "side" in x else ()):
86
+ if x[col].astype(str).str.strip().eq("").any():
87
+ raise ValueError(f"empty {col}")
88
+ x[col] = x[col].astype(str)
89
+ x["count"] = pd.to_numeric(x["count"], errors="coerce")
90
+ if not np.isfinite(x["count"]).all() or x["count"].lt(0).any():
91
+ raise ValueError("pseudobulk counts must be finite and nonnegative")
92
+ if x.groupby("sample_id").condition.nunique().gt(1).any():
93
+ raise ValueError("conflicting conditions for a sample")
94
+ keys = ["donor_id", "condition", "celltype", "gene_id"] + (["side"] if "side" in x else [])
95
+ out = x.groupby(keys, as_index=False, sort=True)["count"].sum()
96
+ return out
97
+
98
+
99
+ def pseudobulk_rows_from_arrays(*, sample_ids: np.ndarray, donors: np.ndarray,
100
+ conditions: np.ndarray, gene_ids: np.ndarray, celltype: str,
101
+ side: str, n_cells: np.ndarray, sums: np.ndarray) -> pd.DataFrame:
102
+ """Convert legacy sample×celltype summed counts to a narrow table.
103
+
104
+ One row per gene is retained, including measured zeros; samples with no
105
+ cells of this type are excluded, matching the legacy DEG row definition.
106
+ """
107
+ sample_ids, donors, conditions = (np.asarray(x).astype(str) for x in (sample_ids, donors, conditions))
108
+ gene_ids = np.asarray(gene_ids).astype(str)
109
+ n_cells = np.asarray(n_cells)
110
+ sums = np.asarray(sums, dtype=float)
111
+ S, G = len(sample_ids), len(gene_ids)
112
+ if len(donors) != S or len(conditions) != S or n_cells.shape != (S,) or sums.shape != (S, G):
113
+ raise ValueError("pseudobulk array shapes differ")
114
+ if not np.isfinite(sums).all() or (sums < 0).any() or (n_cells < 0).any():
115
+ raise ValueError("invalid pseudobulk counts or cell numbers")
116
+ keep = n_cells > 0
117
+ return pd.DataFrame({"sample_id": np.repeat(sample_ids[keep], G),
118
+ "donor_id": np.repeat(donors[keep], G),
119
+ "condition": np.repeat(conditions[keep], G),
120
+ "celltype": celltype, "side": side,
121
+ "gene_id": np.tile(gene_ids, int(keep.sum())),
122
+ "count": sums[keep].reshape(-1)})
123
+
124
+
125
+ def requires_donor_block(aggregated: pd.DataFrame) -> bool:
126
+ """Use duplicateCorrelation when any donor contributes multiple conditions."""
127
+ return bool(aggregated.groupby("donor_id").condition.nunique().gt(1).any())
128
+
129
+
130
+ def score_table_with_patients(per_donor: pd.DataFrame, mapping: pd.DataFrame,
131
+ *, draw: str) -> pd.DataFrame:
132
+ """Turn numeric legacy per-sample metrics into mapped long rows for inference."""
133
+ if not {"donor", "arm"} <= set(per_donor):
134
+ raise ValueError("legacy per_donor.csv missing donor/sample or arm")
135
+ patients = validate_patient_mapping(mapping)
136
+ x = per_donor.rename(columns={"donor": "sample_id"}).copy()
137
+ x["sample_id"] = x.sample_id.astype(str)
138
+ x = x.merge(patients, on="sample_id", how="left", validate="many_to_one")
139
+ if x.donor_id.isna().any():
140
+ raise ValueError(f"unmapped scored samples: {x.loc[x.donor_id.isna(), 'sample_id'].unique().tolist()[:5]}")
141
+ metrics = [c for c in per_donor if c not in {"donor", "arm", "group"} and pd.api.types.is_numeric_dtype(per_donor[c])]
142
+ out = x.melt(id_vars=["sample_id", "donor_id", "arm"], value_vars=metrics,
143
+ var_name="metric", value_name="value")
144
+ out.insert(0, "draw", str(draw))
145
+ return out
146
+
147
+
148
+ def summarize_metrics(long_rows: pd.DataFrame, *, baseline: str, n_boot: int = DEFAULT_BOOTSTRAPS,
149
+ seed: int = DEFAULT_SEED) -> pd.DataFrame:
150
+ """One corrected CI per metric and paired arm, with explicit undefined status."""
151
+ outputs = []
152
+ for metric, group in long_rows.groupby("metric", sort=True):
153
+ for arm in sorted(set(group.arm) - {baseline}):
154
+ try:
155
+ result = paired_donor_bootstrap(group, arm, baseline, n_boot=n_boot, seed=seed)
156
+ result.update(metric=metric, status="ok")
157
+ except ValueError as exc:
158
+ result = {"metric": metric, "arm": arm, "baseline": baseline,
159
+ "status": "undefined", "reason": str(exc)}
160
+ outputs.append(result)
161
+ return pd.DataFrame(outputs)
162
+
163
+
164
+ def run_donor_limma(aggregated: pd.DataFrame, out_dir: Path, *,
165
+ case: str = "case", control: str = "control", threads: int = 4) -> dict:
166
+ """Fit edgeR TMM + limma voom, adding duplicateCorrelation for paired donors.
167
+
168
+ The R worker writes status per cell type. Any unavailable fit stays an
169
+ explicit gap; its results are never substituted with the old Welch score.
170
+ """
171
+ out_dir = Path(out_dir)
172
+ out_dir.mkdir(parents=True, exist_ok=True)
173
+ path = out_dir / "donor_condition_pseudobulk.csv"
174
+ aggregated.to_csv(path, index=False)
175
+ worker = Path(__file__).with_name("donor_limma.R")
176
+ rscript = Path("/home/sj_server_1/miniforge3/bin/Rscript")
177
+ if not worker.is_file() or not rscript.is_file():
178
+ return {"status": "pending", "reason": "donor limma R worker or Rscript missing"}
179
+ env = dict(os.environ, CUDA_VISIBLE_DEVICES="", OMP_NUM_THREADS=str(threads),
180
+ OPENBLAS_NUM_THREADS=str(threads), MKL_NUM_THREADS=str(threads))
181
+ proc = subprocess.run([str(rscript), "--vanilla", str(worker), str(path), str(out_dir), case, control],
182
+ env=env, capture_output=True, text=True)
183
+ (out_dir / "limma.log").write_text(proc.stdout + "\n--- stderr ---\n" + proc.stderr)
184
+ if proc.returncode:
185
+ return {"status": "pending", "reason": f"R fit failed (exit {proc.returncode}); inspect limma.log"}
186
+ return json.loads((out_dir / "limma_status.json").read_text())