Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/common.py +175 -0
- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/compare_calibration.py +107 -0
- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/extract_paired.py +133 -0
- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/features.py +267 -0
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/common.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared helpers of plans/bulkonly_lora5_k4000_20261006 (CPU only; imported, not run).
|
| 2 |
+
|
| 3 |
+
Copied from plans/bulkonly_lora5_20261006/tools/common.py (2026-10-06); added poisson_over_parts and
|
| 4 |
+
BULKONLY_POISSON_SEED for the K = 4,000 version, whose bulk-only sets are generated in row parts with per-draw seeds.
|
| 5 |
+
|
| 6 |
+
Every cell set (bulk-only generated, paired-test generated, paired observed) is reduced to the same compact files so
|
| 7 |
+
the analysis never needs the 2-7 GB generated NPZs again:
|
| 8 |
+
cells.parquet one row per cell: sample_id, celltype_l1_pred (six-type gate), aifi_l1, aifi_l2, aifi_l2_confidence,
|
| 9 |
+
lib_measured (UMI on the cohort's measured panel genes), lib_score (UMI on the scoring genes)
|
| 10 |
+
markers.npz int32 counts of every marker gene of the rare-state rules (plans/rare_states_screen_20261004/tools/
|
| 11 |
+
states.json), columns = marker_symbols
|
| 12 |
+
pb.npz per sample x aifi_l2: summed counts on the 6k panel (float32), cell numbers; per sample x six-type L1 too
|
| 13 |
+
subsample.npz 200 cells per sample (rng 20261006 keyed by sample id; all cells if fewer): CSR integer counts on the
|
| 14 |
+
6k panel + their cells.parquet row index (for embedding / clustering)
|
| 15 |
+
Counts are always integer UMIs: generated cells after the benchmark's Poisson read-out (seed 20260916, one draw over
|
| 16 |
+
the whole NPZ in row order), observed cells as measured.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import hashlib
|
| 21 |
+
import importlib.util
|
| 22 |
+
import json
|
| 23 |
+
import sys
|
| 24 |
+
from pathlib import Path
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
import scipy.sparse as sp
|
| 29 |
+
|
| 30 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 31 |
+
FT = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 32 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 33 |
+
RS = M8 / "plans/rare_states_screen_20261004"
|
| 34 |
+
STATES = RS / "tools/states.json"
|
| 35 |
+
CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
|
| 36 |
+
"canonical_genes.tsv")
|
| 37 |
+
SUB_SEED = 20261006
|
| 38 |
+
SUB_N = 200
|
| 39 |
+
sys.path.insert(0, str(FT / "tools"))
|
| 40 |
+
import ft_common as F # noqa: E402 (PR = poisson_readout, POISSON_SEED, DATASETS, run_annotator, load_reference)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def bulkonly_poisson_seed(draw: int) -> int:
|
| 44 |
+
"""K = 4,000 bulk-only read-out seed of draw j: the benchmark seed (20260916) + j, so the five draws do not share
|
| 45 |
+
their read-out noise (the K = 1,000 version used one seed for every draw). Paired-test sets keep the benchmark
|
| 46 |
+
seed because score_ft.py reads them out."""
|
| 47 |
+
return int(F.POISSON_SEED) + int(draw)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def poisson_over_parts(npzs: list[Path], seed: int, chunk_rows: int = 4096) -> sp.csr_matrix:
|
| 51 |
+
"""One Poisson read-out over the generated_counts of several NPZs taken in order as one matrix.
|
| 52 |
+
|
| 53 |
+
Equal, cell for cell, to F.PR.poisson_integerise(np.vstack(rates), seed=seed): that function advances ONE
|
| 54 |
+
np.random.default_rng(seed) chunk by chunk over the rows in order (float64 rates, rng.poisson), so its stream does
|
| 55 |
+
not depend on where a chunk or a part ends. Here the parts are read one at a time, so the whole set's rates are
|
| 56 |
+
never in memory together. Same checks (finite, non-negative) and the same output (float32 CSR, sorted, no
|
| 57 |
+
explicit zeros).
|
| 58 |
+
"""
|
| 59 |
+
rng = np.random.default_rng(int(seed))
|
| 60 |
+
blocks: list[sp.csr_matrix] = []
|
| 61 |
+
n_cols = None
|
| 62 |
+
for path in npzs:
|
| 63 |
+
d = np.load(path, allow_pickle=False)
|
| 64 |
+
rates = d["generated_counts"]
|
| 65 |
+
n_cols = rates.shape[1] if n_cols is None else n_cols
|
| 66 |
+
if rates.shape[1] != n_cols:
|
| 67 |
+
raise SystemExit(f"{path}: gene axis differs between parts")
|
| 68 |
+
for start in range(0, rates.shape[0], max(int(chunk_rows), 1)):
|
| 69 |
+
dense = np.asarray(rates[start:start + chunk_rows], dtype=np.float64)
|
| 70 |
+
if not np.isfinite(dense).all():
|
| 71 |
+
raise SystemExit(f"{path}: non-finite generated values in rows {start}:")
|
| 72 |
+
if (dense < 0).any():
|
| 73 |
+
raise SystemExit(f"{path}: negative generated values in rows {start}:")
|
| 74 |
+
blocks.append(sp.csr_matrix(rng.poisson(dense).astype(np.float32, copy=False)))
|
| 75 |
+
del rates, d
|
| 76 |
+
out = sp.vstack(blocks, format="csr")
|
| 77 |
+
out.sort_indices()
|
| 78 |
+
out.eliminate_zeros()
|
| 79 |
+
return out.astype(np.float32)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def sha(p: Path) -> str:
|
| 83 |
+
h = hashlib.sha256()
|
| 84 |
+
with open(p, "rb") as f:
|
| 85 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 86 |
+
h.update(b)
|
| 87 |
+
return h.hexdigest()
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def sha_bytes(b: bytes) -> str:
|
| 91 |
+
return hashlib.sha256(b).hexdigest()
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def marker_genes(states: list[dict]) -> list[str]:
|
| 95 |
+
out = []
|
| 96 |
+
for st in states:
|
| 97 |
+
for g in st.get("genes", []) + [x for grp in st.get("require_any", []) for x in grp] + st.get("exclude", []):
|
| 98 |
+
if g not in out:
|
| 99 |
+
out.append(g)
|
| 100 |
+
return out
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def panel_setup(ds: str) -> dict:
|
| 104 |
+
"""6k panel ids (cells_panel6k.npz order = generated NPZ gene order), measured mask, scoring idx, marker columns."""
|
| 105 |
+
d = np.load(FT / "data" / ds / "cells_panel6k.npz", allow_pickle=False)
|
| 106 |
+
panel = d["panel_gene_ids"].astype(str)
|
| 107 |
+
measured = d["panel_measured"].any(0)
|
| 108 |
+
ref = np.load(FT / "scoring_cache" / ds / "reference.npz", allow_pickle=False)
|
| 109 |
+
if not np.array_equal(ref["panel_ids"].astype(str), panel):
|
| 110 |
+
raise SystemExit(f"{ds}: scoring reference panel differs from cells_panel6k.npz")
|
| 111 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 112 |
+
sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
|
| 113 |
+
id2sym = dict(zip(canon.gene_id, canon.gene_symbol))
|
| 114 |
+
pos = {g: i for i, g in enumerate(panel)}
|
| 115 |
+
states = json.loads(STATES.read_text())
|
| 116 |
+
syms = [g for g in marker_genes(states) if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
|
| 117 |
+
return {"panel": panel, "measured": measured, "score_idx": ref["score_idx"].astype(np.int64),
|
| 118 |
+
"marker_symbols": syms, "marker_cols": np.asarray([pos[sym2id[g]] for g in syms], dtype=np.int64),
|
| 119 |
+
"symbols": np.asarray([id2sym.get(g, g) for g in panel], dtype=str), "states_sha256": sha(STATES)}
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def sample_rng(sample: str) -> np.random.Generator:
|
| 123 |
+
key = int.from_bytes(hashlib.sha256(str(sample).encode()).digest()[:8], "little")
|
| 124 |
+
return np.random.default_rng([SUB_SEED, key])
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def write_compact(out: Path, X: sp.csr_matrix, sample_of_cell: np.ndarray, lab: pd.DataFrame, ps: dict,
|
| 128 |
+
receipt: dict) -> dict:
|
| 129 |
+
"""X: integer counts, cells x 6k panel (panel order); lab: aifi_l1, aifi_l2, aifi_l2_confidence[, celltype_l1_pred]."""
|
| 130 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 131 |
+
X = X.tocsr()
|
| 132 |
+
n = X.shape[0]
|
| 133 |
+
if len(sample_of_cell) != n or len(lab) != n:
|
| 134 |
+
raise SystemExit("cells, samples and labels are not row-aligned")
|
| 135 |
+
samples = np.asarray(sample_of_cell, dtype=str)
|
| 136 |
+
cells = pd.DataFrame({"sample_id": samples,
|
| 137 |
+
"celltype_l1_pred": lab["celltype_l1_pred"].astype(str).to_numpy()
|
| 138 |
+
if "celltype_l1_pred" in lab else lab["aifi_l1"].astype(str).to_numpy(),
|
| 139 |
+
"aifi_l1": lab["aifi_l1"].astype(str).to_numpy(), "aifi_l2": lab["aifi_l2"].astype(str).to_numpy(),
|
| 140 |
+
"aifi_l2_confidence": lab["aifi_l2_confidence"].astype(np.float32).to_numpy()
|
| 141 |
+
if "aifi_l2_confidence" in lab else np.full(n, np.nan, np.float32),
|
| 142 |
+
"lib_measured": np.asarray(X[:, np.flatnonzero(ps["measured"])].sum(1)).ravel().astype(np.int64),
|
| 143 |
+
"lib_score": np.asarray(X[:, ps["score_idx"]].sum(1)).ravel().astype(np.int64)})
|
| 144 |
+
cells.to_parquet(out / "cells.parquet", index=False)
|
| 145 |
+
np.savez_compressed(out / "markers.npz", markers=X[:, ps["marker_cols"]].toarray().astype(np.int32),
|
| 146 |
+
marker_symbols=np.asarray(ps["marker_symbols"]))
|
| 147 |
+
# per sample x type pseudobulk (summed integer counts on the 6k panel)
|
| 148 |
+
us = np.asarray(sorted(set(samples)))
|
| 149 |
+
for key, col in (("l2", "aifi_l2"), ("l1", "celltype_l1_pred")):
|
| 150 |
+
types = np.asarray(sorted(set(cells[col])))
|
| 151 |
+
si = pd.Index(us).get_indexer(samples)
|
| 152 |
+
ti = pd.Index(types).get_indexer(cells[col].to_numpy())
|
| 153 |
+
g = si * len(types) + ti
|
| 154 |
+
G = sp.csr_matrix((np.ones(n, np.float32), (g, np.arange(n))), shape=(len(us) * len(types), n))
|
| 155 |
+
S = (G @ X.astype(np.float32)).toarray().reshape(len(us), len(types), X.shape[1]).astype(np.float32)
|
| 156 |
+
N = np.bincount(g, minlength=len(us) * len(types)).reshape(len(us), len(types))
|
| 157 |
+
np.savez_compressed(out / f"pb_{key}.npz", sums=S, n_cells=N, samples=us, types=types,
|
| 158 |
+
gene_ids=ps["panel"], gene_symbols=ps["symbols"])
|
| 159 |
+
# subsample for embedding
|
| 160 |
+
keep = []
|
| 161 |
+
for s in us:
|
| 162 |
+
idx = np.flatnonzero(samples == s)
|
| 163 |
+
if idx.size > SUB_N:
|
| 164 |
+
idx = np.sort(sample_rng(s).choice(idx, SUB_N, replace=False))
|
| 165 |
+
keep.append(idx)
|
| 166 |
+
keep = np.concatenate(keep)
|
| 167 |
+
Xs = X[keep].tocsr().astype(np.int32)
|
| 168 |
+
np.savez_compressed(out / "subsample.npz", data=Xs.data, indices=Xs.indices, indptr=Xs.indptr,
|
| 169 |
+
shape=np.asarray(Xs.shape), cell_row=keep, gene_ids=ps["panel"], gene_symbols=ps["symbols"])
|
| 170 |
+
receipt = {**receipt, "cells": int(n), "samples": int(len(us)), "subsample_cells": int(keep.size),
|
| 171 |
+
"states_json": str(STATES), "states_sha256": ps["states_sha256"],
|
| 172 |
+
"files": {f: sha(out / f) for f in ("cells.parquet", "markers.npz", "pb_l2.npz", "pb_l1.npz",
|
| 173 |
+
"subsample.npz")}}
|
| 174 |
+
(out / "RECEIPT.json").write_text(json.dumps(receipt, indent=1, default=str) + "\n")
|
| 175 |
+
return receipt
|
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/compare_calibration.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Paired-test calibration of the K = 4,000 LoRA-5 cells against the K = 1,000 version (CPU only; 2026-10-06).
|
| 3 |
+
|
| 4 |
+
Reads analysis/features/<ds>/calibration.csv of both plans (tools/features.py: per feature and draw, over the draw's
|
| 5 |
+
paired TEST samples, generated vs observed mean, ratio, Spearman over samples and, per cohort contrast, the generated
|
| 6 |
+
and observed difference). The two versions share their draws (same training donors, same test samples, same
|
| 7 |
+
observed truth), so every comparison is paired by feature x draw.
|
| 8 |
+
Per feature x draw and version:
|
| 9 |
+
level ok 0.5 <= ratio <= 2 and Spearman >= 0.3
|
| 10 |
+
contrast ok same sign as observed and |generated diff| within 0.5-2x of |observed diff| (per contrast)
|
| 11 |
+
Writes analysis/compare_k1000/<ds>/{per_feature.csv, SUMMARY.md}: counts per draw and version, paired medians of
|
| 12 |
+
|log2 ratio| and Spearman, the features that change gate status, and a table of named features (KEY below).
|
| 13 |
+
usage: CUDA_VISIBLE_DEVICES='' compare_calibration.py DATASET
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 22 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
import pandas as pd
|
| 26 |
+
|
| 27 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 28 |
+
K1 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/bulkonly_lora5_20261006")
|
| 29 |
+
KEY = ["l1 | Monocyte", "l1 | NK cell", "l1 | DC", "l1 | B cell", "l1 | T cell", "l2 | MAIT", "l2 | CD14 monocyte",
|
| 30 |
+
"l2 | Plasma cell"]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def load(path: Path) -> pd.DataFrame:
|
| 34 |
+
c = pd.read_csv(path)
|
| 35 |
+
c = c[c.draw.astype(str) != "pooled"].copy()
|
| 36 |
+
c["draw"] = c.draw.astype(int)
|
| 37 |
+
return c
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def gates(c: pd.DataFrame, contrasts: list[str]) -> pd.DataFrame:
|
| 41 |
+
out = c[["kind", "feature", "draw", "n_samples", "gen_mean", "obs_mean", "ratio", "spearman"]].copy()
|
| 42 |
+
out["log2_ratio"] = np.log2(c.ratio.where(c.ratio > 0))
|
| 43 |
+
out["level_ok"] = (c.ratio.between(0.5, 2.0)) & (c.spearman >= 0.3)
|
| 44 |
+
for k in contrasts:
|
| 45 |
+
g, o = c[f"{k}: gen diff"], c[f"{k}: obs diff"]
|
| 46 |
+
rel = (g.abs() / o.abs()).where(o.abs() > 0)
|
| 47 |
+
out[f"{k}: ok"] = (np.sign(g) == np.sign(o)) & rel.between(0.5, 2.0)
|
| 48 |
+
out[f"{k}: same sign"] = np.sign(g) == np.sign(o)
|
| 49 |
+
return out
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main(argv=None) -> int:
|
| 53 |
+
ds = (argv or sys.argv[1:])[0]
|
| 54 |
+
a = load(K1 / "analysis" / "features" / ds / "calibration.csv")
|
| 55 |
+
b = load(PLAN / "analysis" / "features" / ds / "calibration.csv")
|
| 56 |
+
contrasts = [col[: -len(": same sign")] for col in a.columns if col.endswith(": same sign")
|
| 57 |
+
and col.split(": same sign")[0] + ": gen diff" in a.columns and "draws" not in col]
|
| 58 |
+
ga, gb = gates(a, contrasts), gates(b, contrasts)
|
| 59 |
+
m = ga.merge(gb, on=["kind", "feature", "draw"], suffixes=("_k1000", "_k4000"))
|
| 60 |
+
out = PLAN / "analysis" / "compare_k1000" / ds
|
| 61 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 62 |
+
m.to_csv(out / "per_feature.csv", index=False)
|
| 63 |
+
lines = [f"# {ds}: paired-test calibration, LoRA-5 K = 4,000 vs K = 1,000", "",
|
| 64 |
+
f"{m.feature.nunique()} features x {m.draw.nunique()} draws = {len(m)} pairs (same draws, test samples and "
|
| 65 |
+
"observed truth). Level ok: ratio 0.5-2 and Spearman >= 0.3. Contrast ok: same sign and |generated "
|
| 66 |
+
"difference| within 0.5-2x of observed.", "",
|
| 67 |
+
"| draw | level ok K1000 | level ok K4000 | " + " | ".join(f"{k} ok K1000 | K4000" for k in contrasts) + " |",
|
| 68 |
+
"|---|---:|---:|" + "---:|---:|" * len(contrasts)]
|
| 69 |
+
for j, g in m.groupby("draw"):
|
| 70 |
+
cells = [str(int(g.level_ok_k1000.sum())), str(int(g.level_ok_k4000.sum()))]
|
| 71 |
+
for k in contrasts:
|
| 72 |
+
cells += [str(int(g[f"{k}: ok_k1000"].sum())), str(int(g[f"{k}: ok_k4000"].sum()))]
|
| 73 |
+
lines.append(f"| {j} | " + " | ".join(cells) + " |")
|
| 74 |
+
tot = [str(int(m.level_ok_k1000.sum())), str(int(m.level_ok_k4000.sum()))]
|
| 75 |
+
for k in contrasts:
|
| 76 |
+
tot += [str(int(m[f"{k}: ok_k1000"].sum())), str(int(m[f"{k}: ok_k4000"].sum()))]
|
| 77 |
+
lines.append("| all | " + " | ".join(tot) + " |")
|
| 78 |
+
d_lr = (m.log2_ratio_k4000.abs() - m.log2_ratio_k1000.abs()).dropna()
|
| 79 |
+
d_sp = (m.spearman_k4000 - m.spearman_k1000).dropna()
|
| 80 |
+
lines += ["", f"- |log2 ratio| (distance of the generated level from observed), K4000 − K1000: median "
|
| 81 |
+
f"{d_lr.median():+.3f}; closer in {(d_lr < 0).mean():.0%} of {len(d_lr)} pairs.",
|
| 82 |
+
f"- Spearman over test samples, K4000 − K1000: median {d_sp.median():+.3f}; higher in "
|
| 83 |
+
f"{(d_sp > 0).mean():.0%} of {len(d_sp)} pairs."]
|
| 84 |
+
for k in contrasts:
|
| 85 |
+
s1, s4 = m[f"{k}: same sign_k1000"], m[f"{k}: same sign_k4000"]
|
| 86 |
+
lines.append(f"- {k}: same sign in {int(s1.sum())} (K1000) vs {int(s4.sum())} (K4000) of {len(m)} pairs.")
|
| 87 |
+
gained = m[~m.level_ok_k1000 & m.level_ok_k4000].groupby("feature").draw.apply(lambda x: ",".join(map(str, x)))
|
| 88 |
+
lost = m[m.level_ok_k1000 & ~m.level_ok_k4000].groupby("feature").draw.apply(lambda x: ",".join(map(str, x)))
|
| 89 |
+
lines += ["", f"Level gate gained at K4000 ({len(gained)} features; draws): "
|
| 90 |
+
+ "; ".join(f"{f} [{d}]" for f, d in gained.items()),
|
| 91 |
+
"", f"Level gate lost at K4000 ({len(lost)} features; draws): " + "; ".join(f"{f} [{d}]" for f, d in lost.items())]
|
| 92 |
+
key = [f for f in KEY if f in set(m.feature)] + sorted(f for f in set(m.feature) if f.startswith("state |"))
|
| 93 |
+
lines += ["", "Named features, ratio (Spearman) per draw:", "", "| feature | version | " +
|
| 94 |
+
" | ".join(f"d{j}" for j in sorted(m.draw.unique())) + " |", "|---|---|" + "---:|" * m.draw.nunique()]
|
| 95 |
+
for f in key:
|
| 96 |
+
g = m[m.feature == f].set_index("draw").sort_index()
|
| 97 |
+
for v in ("k1000", "k4000"):
|
| 98 |
+
lines.append(f"| {f} | {v} | " + " | ".join(
|
| 99 |
+
f"{g.loc[j, 'ratio_' + v]:.2f} ({g.loc[j, 'spearman_' + v]:.2f})" if j in g.index else "–"
|
| 100 |
+
for j in sorted(m.draw.unique())) + " |")
|
| 101 |
+
(out / "SUMMARY.md").write_text("\n".join(lines) + "\n")
|
| 102 |
+
print("\n".join(lines[:16]))
|
| 103 |
+
return 0
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/extract_paired.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Paired-test calibration sets for the K = 4,000 bulk-only analysis (CPU only; tools/common.py).
|
| 3 |
+
|
| 4 |
+
Adapted from plans/bulkonly_lora5_20261006/tools/extract_paired.py (2026-10-06): the generated set is this plan's
|
| 5 |
+
K = 4,000 paired-test generation of each draw (generated/<ds>/draw<j>/paired_test_K4000.npz, tools/merge_paired.py;
|
| 6 |
+
1,500 cells per test sample, LoRA r16 trained at K = 4,000), read out and labelled by the benchmark scorer in
|
| 7 |
+
tools/score_paired.sh (scores/<ds>/draw<j>/arms/lora5_k4000/). The text below is the first plan's, with those paths.
|
| 8 |
+
|
| 9 |
+
Why: a pattern seen in the bulk-only cells is only worth following if the same LoRA-5 model reproduces it where the
|
| 10 |
+
truth is known. Each few-pair draw already generated cells for its paired TEST samples (the usable samples of the
|
| 11 |
+
cohort's other donors, real bulk at K = 1,000, seed 20260927) and the benchmark labelled them. This tool reduces
|
| 12 |
+
generated paired_finetune_intradataset_20260927/generated/<ds>/fewshot_n5/draw<j>/lora__raw.npz (sepsis: server_1;
|
| 13 |
+
Imperial: streamed from spark-0110) -> the benchmark's own Poisson read-out (seed 20260916, whole NPZ),
|
| 14 |
+
the scored rows of scores/<ds>/fewshot_n5/draw<j>/arms/lora5/generated_cells.parquet, their labels
|
| 15 |
+
(labels/labels.parquet); umi_scoring_genes must be reproduced cell by cell, the NPZ sha must equal its receipt
|
| 16 |
+
observed every cell of the cohort's usable samples (data/<ds>/cells_panel6k.npz, folds.csv fold >= 0) with the
|
| 17 |
+
benchmark's observed labels (scoring_cache/<ds>/observed_labels/labels/labels.parquet, npz_row aligned)
|
| 18 |
+
to the same compact files as the bulk-only sets (cells.parquet, markers.npz, pb_l2/l1.npz, subsample.npz).
|
| 19 |
+
Outputs: work/<ds>/paired_gen/draw<j>/ and work/<ds>/observed/
|
| 20 |
+
usage: CUDA_VISIBLE_DEVICES='' extract_paired.py DATASET gen DRAW
|
| 21 |
+
CUDA_VISIBLE_DEVICES='' extract_paired.py DATASET observed
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import io
|
| 26 |
+
import json
|
| 27 |
+
import os
|
| 28 |
+
import subprocess
|
| 29 |
+
import sys
|
| 30 |
+
import time
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 34 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 35 |
+
|
| 36 |
+
import numpy as np
|
| 37 |
+
import pandas as pd
|
| 38 |
+
import scipy.sparse as sp
|
| 39 |
+
|
| 40 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 41 |
+
import common as C # noqa: E402
|
| 42 |
+
F = C.F
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def load_npz_bytes(path: Path) -> bytes:
|
| 46 |
+
if path.exists():
|
| 47 |
+
return path.read_bytes()
|
| 48 |
+
res = subprocess.run(["ssh", "-n", "spark-0110", "cat", str(path)], capture_output=True, check=True)
|
| 49 |
+
return res.stdout
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def cmd_gen(ds: str, j: int) -> None:
|
| 53 |
+
t0 = time.monotonic()
|
| 54 |
+
g = C.PLAN / "generated" / ds / f"draw{j}" / "paired_test_K4000.npz"
|
| 55 |
+
rec_path = g.with_suffix(".log")
|
| 56 |
+
if rec_path.exists():
|
| 57 |
+
rec = json.loads(rec_path.read_text())
|
| 58 |
+
else:
|
| 59 |
+
rec = json.loads(subprocess.run(["ssh", "-n", "spark-0110", "cat", str(rec_path)], capture_output=True,
|
| 60 |
+
check=True).stdout)
|
| 61 |
+
raw = load_npz_bytes(g)
|
| 62 |
+
got = C.sha_bytes(raw)
|
| 63 |
+
if got != rec["output_sha256"]:
|
| 64 |
+
raise SystemExit(f"{g}: sha {got[:12]} != receipt {rec['output_sha256'][:12]}")
|
| 65 |
+
d = np.load(io.BytesIO(raw), allow_pickle=False)
|
| 66 |
+
del raw
|
| 67 |
+
ps = C.panel_setup(ds)
|
| 68 |
+
if not np.array_equal(d["gene_ids"].astype(str), ps["panel"]):
|
| 69 |
+
raise SystemExit("NPZ gene_ids differ from the 6k panel")
|
| 70 |
+
rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
|
| 71 |
+
n_rows = rates.shape[0]
|
| 72 |
+
full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096).tocsr()
|
| 73 |
+
del rates
|
| 74 |
+
sdir = C.PLAN / "scores" / ds / f"draw{j}" / "arms" / "lora5_k4000"
|
| 75 |
+
gc = pd.read_parquet(sdir / "generated_cells.parquet")
|
| 76 |
+
lab = pd.read_parquet(sdir / "labels" / "labels.parquet")
|
| 77 |
+
if len(gc) != len(lab) or not (lab.sample_id.astype(str).str.removesuffix("|generated").values == gc.donor.values).all():
|
| 78 |
+
raise SystemExit("generated_cells and labels are not row-aligned")
|
| 79 |
+
X = full[gc.npz_row.to_numpy()].tocsr()
|
| 80 |
+
del full
|
| 81 |
+
umi = np.asarray(X[:, ps["score_idx"]].sum(1)).ravel()
|
| 82 |
+
if not np.array_equal(umi, gc.umi_scoring_genes.to_numpy()):
|
| 83 |
+
raise SystemExit(f"Poisson read-out does not reproduce the benchmark ({int((umi != gc.umi_scoring_genes.to_numpy()).sum())} cells)")
|
| 84 |
+
receipt = {"set": "paired_gen", "dataset": ds, "draw": j, "npz": str(g), "npz_sha256": got, "npz_rows": int(n_rows),
|
| 85 |
+
"checkpoint": rec.get("checkpoint"), "checkpoint_sha256": rec.get("checkpoint_sha256"),
|
| 86 |
+
"labels": str(sdir / "labels/labels.parquet"), "labels_sha256": C.sha(sdir / "labels/labels.parquet"),
|
| 87 |
+
"poisson_seed": F.POISSON_SEED, "umi_scoring_genes_reproduced": True,
|
| 88 |
+
"tool": str(Path(__file__).resolve()), "tool_sha256": C.sha(Path(__file__)),
|
| 89 |
+
"common_sha256": C.sha(Path(C.__file__))}
|
| 90 |
+
out = C.write_compact(C.PLAN / "work" / ds / "paired_gen" / f"draw{j}", X, gc.donor.astype(str).to_numpy(), lab, ps,
|
| 91 |
+
receipt)
|
| 92 |
+
print(json.dumps({"dataset": ds, "draw": j, "cells": out["cells"], "samples": out["samples"],
|
| 93 |
+
"seconds": round(time.monotonic() - t0, 1)}))
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def cmd_observed(ds: str) -> None:
|
| 97 |
+
t0 = time.monotonic()
|
| 98 |
+
ps = C.panel_setup(ds)
|
| 99 |
+
dd = C.FT / "data" / ds
|
| 100 |
+
d = np.load(dd / "cells_panel6k.npz", allow_pickle=False)
|
| 101 |
+
X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
|
| 102 |
+
obs = pd.read_parquet(dd / "cells_obs.parquet", columns=["sample_id"])
|
| 103 |
+
lpath = C.FT / "scoring_cache" / ds / "observed_labels" / "labels" / "labels.parquet"
|
| 104 |
+
lab = pd.read_parquet(lpath)
|
| 105 |
+
if len(lab) != X.shape[0] or not (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all():
|
| 106 |
+
raise SystemExit("observed labels not aligned with cells_panel6k.npz")
|
| 107 |
+
folds = pd.read_csv(dd / "folds.csv")
|
| 108 |
+
usable = set(folds.loc[folds.fold >= 0, "sample_id"].astype(str))
|
| 109 |
+
keep = np.flatnonzero(obs.sample_id.astype(str).isin(usable).to_numpy())
|
| 110 |
+
receipt = {"set": "observed", "dataset": ds, "cells_panel6k": str(dd / "cells_panel6k.npz"),
|
| 111 |
+
"cells_panel6k_sha256": C.sha(dd / "cells_panel6k.npz"), "labels": str(lpath), "labels_sha256": C.sha(lpath),
|
| 112 |
+
"usable_samples": len(usable), "tool": str(Path(__file__).resolve()), "tool_sha256": C.sha(Path(__file__)),
|
| 113 |
+
"common_sha256": C.sha(Path(C.__file__))}
|
| 114 |
+
out = C.write_compact(C.PLAN / "work" / ds / "observed", X[keep].astype(np.int64),
|
| 115 |
+
obs.sample_id.astype(str).to_numpy()[keep], lab.iloc[keep].reset_index(drop=True), ps, receipt)
|
| 116 |
+
print(json.dumps({"dataset": ds, "set": "observed", "cells": out["cells"], "samples": out["samples"],
|
| 117 |
+
"seconds": round(time.monotonic() - t0, 1)}))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def main(argv=None) -> int:
|
| 121 |
+
args = argv or sys.argv[1:]
|
| 122 |
+
ds, what = args[0], args[1]
|
| 123 |
+
if what == "gen":
|
| 124 |
+
cmd_gen(ds, int(args[2]))
|
| 125 |
+
elif what == "observed":
|
| 126 |
+
cmd_observed(ds)
|
| 127 |
+
else:
|
| 128 |
+
raise SystemExit("usage: extract_paired.py DATASET gen DRAW | DATASET observed")
|
| 129 |
+
return 0
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
if __name__ == "__main__":
|
| 133 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/features.py
ADDED
|
@@ -0,0 +1,267 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Sample-level features of every cell set and the paired-test calibration table (CPU only; 2026-10-06).
|
| 3 |
+
|
| 4 |
+
Reads the compact files of tools/annotate_bulkonly.py and tools/extract_paired.py (work/<ds>/...) and writes
|
| 5 |
+
analysis/features/<ds>/:
|
| 6 |
+
meta.csv one row per sample of both sets: set (paired = the cohort's usable paired samples; bulkonly),
|
| 7 |
+
sample_id, donor_id, group, case (disease side of the cohort contrast), clinical columns harmonised
|
| 8 |
+
across sets (sepsis: age, sex, infection_source, site; Imperial: severity_peak (mild/moderate vs
|
| 9 |
+
severe/critical), severity_at_sample, days_since_pos_swab, fatal, age, sex, wave), bulk sex flag
|
| 10 |
+
composition.parquet set, draw (-1 = observed), sample_id, level (l1 = six-type gate, l2 = AIFI L2), type, n, n_cells, frac
|
| 11 |
+
states.parquet set, draw, sample_id, state, parent_n, state_n, frac; marker states on observed cells are thinned
|
| 12 |
+
(binomial, seed [20261004, draw, state index]) to the matching generated parent median library of the
|
| 13 |
+
same draw's paired-test cells, as in rare_states_screen_20261004/tools/screen.py (set "observed_thin_d<j>");
|
| 14 |
+
"observed" = native depth; label states are not thinned
|
| 15 |
+
calibration.csv per feature (composition type or state) and draw: mean generated vs observed fraction over the draw's
|
| 16 |
+
paired TEST samples, ratio, Spearman over samples, and each contrast's generated and observed
|
| 17 |
+
difference of group means with direction agreement; plus "pooled" rows over the five draws
|
| 18 |
+
bulkonly.parquet per bulk-only sample and feature: mean, SD and min/max over the five draws
|
| 19 |
+
State rules: plans/rare_states_screen_20261004/tools/states.json (marker rules: >= k of the genes detected, optional
|
| 20 |
+
require_any / exclude; label rules: AIFI L2 labels within a parent), helper functions imported from its screen.py.
|
| 21 |
+
usage: CUDA_VISIBLE_DEVICES='' features.py DATASET
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
import os
|
| 27 |
+
import sys
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 31 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import pandas as pd
|
| 35 |
+
from scipy.stats import spearmanr
|
| 36 |
+
|
| 37 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 38 |
+
import common as C # noqa: E402
|
| 39 |
+
sys.path.insert(0, str(C.RS / "tools"))
|
| 40 |
+
from screen import call_state, parent_mask # noqa: E402
|
| 41 |
+
|
| 42 |
+
THIN_SEED = 20261004
|
| 43 |
+
DRAWS = range(5)
|
| 44 |
+
CONTRASTS = {
|
| 45 |
+
"ye2026_sepsis": [("adult sepsis vs adult HC", "group", ["adult_sepsis"], ["adult_HC"]),
|
| 46 |
+
("adult sepsis vs adult ICU control", "group", ["adult_sepsis"], ["adult_ICU_ctrl"]),
|
| 47 |
+
("sepsis vs all controls", "case", [True], [False])],
|
| 48 |
+
"imperial_eskd": [("COVID+ vs COVID-", "group", ["covid_positive"], ["covid_negative"]),
|
| 49 |
+
("severe/critical vs mild/moderate (COVID+)", "severity_peak", ["severe/critical"], ["mild/moderate"])],
|
| 50 |
+
}
|
| 51 |
+
SEV_SIMPLE = {"mild": "mild/moderate", "moderate": "mild/moderate", "severe": "severe/critical",
|
| 52 |
+
"critical": "severe/critical"}
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def meta_table(ds: str) -> pd.DataFrame:
|
| 56 |
+
dd = C.FT / "data" / ds
|
| 57 |
+
f = np.load(dd / "features.npz", allow_pickle=False)
|
| 58 |
+
folds = pd.read_csv(dd / "folds.csv")
|
| 59 |
+
use = folds.fold.to_numpy() >= 0
|
| 60 |
+
s = lambda k: f[k].astype(str)[use]
|
| 61 |
+
bo = pd.read_csv(C.PLAN / "data" / ds / "bulkonly_meta.csv")
|
| 62 |
+
if ds == "ye2026_sepsis":
|
| 63 |
+
p = pd.DataFrame({"set": "paired", "sample_id": s("sample_ids"), "donor_id": s("donor_ids"), "group": s("groups"),
|
| 64 |
+
"age": pd.to_numeric(s("age_geo"), errors="coerce"), "sex": s("sex_geo"),
|
| 65 |
+
"infection_source": [x if x not in ("NA", "nan") else "none" for x in s("infection_source")],
|
| 66 |
+
"site": s("collection_site"), "sex_flag": False})
|
| 67 |
+
b = pd.DataFrame({"set": "bulkonly", "sample_id": bo.sample_id.astype(str), "donor_id": bo.donor_id.astype(str),
|
| 68 |
+
"group": bo.group, "age": pd.to_numeric(bo.age, errors="coerce"), "sex": bo.sex_geo,
|
| 69 |
+
"infection_source": bo.infection_source, "site": bo.collection_site, "sex_flag": bo.sex_flag})
|
| 70 |
+
m = pd.concat([p, b], ignore_index=True)
|
| 71 |
+
m["case"] = m.group.str.contains("sepsis")
|
| 72 |
+
else:
|
| 73 |
+
bs = pd.read_csv(Path(json.loads((dd / "MANIFEST.json").read_text())["processing_dir"]) / "pairing" /
|
| 74 |
+
"bulk_samples.csv").set_index("bulk_sample")
|
| 75 |
+
pb = s("bulk_sample")
|
| 76 |
+
p = pd.DataFrame({"set": "paired", "sample_id": s("sample_ids"), "bulk_sample": pb, "donor_id": s("donor_ids"),
|
| 77 |
+
"group": s("groups"), "severity_peak": s("severity"),
|
| 78 |
+
"severity_at_sample": s("who_severity_at_sample"),
|
| 79 |
+
"days_since_pos_swab": f["timepoints"][use].astype(float),
|
| 80 |
+
"fatal": [bs.loc[x, "fatal_disease"] if x in bs.index else np.nan for x in pb],
|
| 81 |
+
"age": pd.to_numeric(s("age_meta"), errors="coerce"), "sex": s("sex_meta"),
|
| 82 |
+
"wave": s("bulk_wave"), "sex_flag": False})
|
| 83 |
+
b = pd.DataFrame({"set": "bulkonly", "sample_id": bo.sample_id.astype(str), "bulk_sample": bo.sample_id.astype(str),
|
| 84 |
+
"donor_id": bo.donor_id.astype(str), "group": bo.group,
|
| 85 |
+
"severity_peak": bo.WHO_severity.map(SEV_SIMPLE).fillna("none"),
|
| 86 |
+
"severity_at_sample": bo.WHO_temp_severity.fillna("none").astype(str),
|
| 87 |
+
"days_since_pos_swab": pd.to_numeric(bo.time_from_first_positive_swab, errors="coerce"),
|
| 88 |
+
"fatal": bo.fatal_disease, "age": pd.to_numeric(bo.calc_age, errors="coerce"), "sex": bo.sex,
|
| 89 |
+
"wave": bo.wave, "sex_flag": bo.sex_flag})
|
| 90 |
+
m = pd.concat([p, b], ignore_index=True)
|
| 91 |
+
m["case"] = m.group.eq("covid_positive")
|
| 92 |
+
for j in DRAWS: # paired samples: test sample of draw j? (training donors' samples are not)
|
| 93 |
+
test = set((C.FT / "data" / ds / "fewshot_n5" / f"draw{j}" / "test_samples.txt").read_text().split())
|
| 94 |
+
m[f"paired_test_d{j}"] = m.set.eq("paired") & m.sample_id.isin(test)
|
| 95 |
+
if f"donor_trained_draw{j}" in bo:
|
| 96 |
+
m[f"donor_trained_d{j}"] = m.donor_id.isin(
|
| 97 |
+
json.loads((C.FT / "data" / ds / "fewshot_n5" / "DRAWS.json").read_text())["draw"][str(j)]["train_donors"])
|
| 98 |
+
return m
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def load_set(path: Path) -> dict:
|
| 102 |
+
cells = pd.read_parquet(path / "cells.parquet")
|
| 103 |
+
mk = np.load(path / "markers.npz", allow_pickle=False)
|
| 104 |
+
return {"cells": cells, "markers": mk["markers"], "syms": mk["marker_symbols"].astype(str).tolist()}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def composition(cs: dict, set_name: str, draw: int) -> pd.DataFrame:
|
| 108 |
+
c = cs["cells"]
|
| 109 |
+
out = []
|
| 110 |
+
for level, col in (("l1", "celltype_l1_pred"), ("l2", "aifi_l2")):
|
| 111 |
+
t = c.groupby(["sample_id", col]).size().rename("n").reset_index().rename(columns={col: "type"})
|
| 112 |
+
tot = c.groupby("sample_id").size().rename("n_cells")
|
| 113 |
+
t = t.merge(tot, left_on="sample_id", right_index=True)
|
| 114 |
+
# complete grid (absent type = 0)
|
| 115 |
+
grid = pd.MultiIndex.from_product([tot.index, sorted(c[col].unique())], names=["sample_id", "type"])
|
| 116 |
+
t = t.set_index(["sample_id", "type"]).reindex(grid).reset_index()
|
| 117 |
+
t["n"] = t["n"].fillna(0).astype(int)
|
| 118 |
+
t["n_cells"] = t.sample_id.map(tot)
|
| 119 |
+
t["level"] = level
|
| 120 |
+
out.append(t)
|
| 121 |
+
t = pd.concat(out, ignore_index=True)
|
| 122 |
+
t["frac"] = t.n / t.n_cells
|
| 123 |
+
t.insert(0, "draw", draw)
|
| 124 |
+
t.insert(0, "set", set_name)
|
| 125 |
+
return t
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def state_masks(cs: dict, st: dict, counts: np.ndarray | None = None):
|
| 129 |
+
lab = cs["cells"]
|
| 130 |
+
par = parent_mask(lab, st["parent"])
|
| 131 |
+
if st["kind"] == "label":
|
| 132 |
+
return par, par & lab.aifi_l2.isin(st["labels"]).to_numpy(), []
|
| 133 |
+
syms = cs["syms"]
|
| 134 |
+
pos = [g for g in st["genes"] if g in syms]
|
| 135 |
+
req = [[g for g in grp if g in syms] for grp in st.get("require_any", [])]
|
| 136 |
+
req = [r for r in req if r]
|
| 137 |
+
exc = [g for g in st.get("exclude", []) if g in syms]
|
| 138 |
+
cols = [syms.index(g) for g in pos] + [syms.index(g) for r in req for g in r] + [syms.index(g) for g in exc]
|
| 139 |
+
M = cs["markers"] if counts is None else counts
|
| 140 |
+
hit = call_state(M[:, cols], st, len(pos), [[0] * len(r) for r in req], [0] * len(exc))
|
| 141 |
+
return par, par & hit, pos
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def state_table(cs: dict, states: list[dict], set_name: str, draw: int, counts: np.ndarray | None = None,
|
| 145 |
+
keep_states: list[int] | None = None) -> pd.DataFrame:
|
| 146 |
+
rows = []
|
| 147 |
+
s = cs["cells"].sample_id.to_numpy()
|
| 148 |
+
for i, st in enumerate(states):
|
| 149 |
+
if keep_states is not None and i not in keep_states:
|
| 150 |
+
continue
|
| 151 |
+
par, hit, _ = state_masks(cs, st, counts)
|
| 152 |
+
t = pd.DataFrame({"sample_id": s, "par": par, "hit": hit}).groupby("sample_id")[["par", "hit"]].sum()
|
| 153 |
+
for sid, r in t.iterrows():
|
| 154 |
+
rows.append({"set": set_name, "draw": draw, "sample_id": sid, "state": st["name"], "parent_n": int(r.par),
|
| 155 |
+
"state_n": int(r.hit), "frac": r.hit / r.par if r.par > 0 else np.nan})
|
| 156 |
+
return pd.DataFrame(rows)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def thinned_observed(obs: dict, gen: dict, states: list[dict], j: int) -> pd.DataFrame:
|
| 160 |
+
"""Observed marker states with the observed parent cells thinned to the generated parent median library (draw j)."""
|
| 161 |
+
rows = []
|
| 162 |
+
for i, st in enumerate(states):
|
| 163 |
+
if st["kind"] == "label":
|
| 164 |
+
continue
|
| 165 |
+
po, _, _ = state_masks(obs, st)
|
| 166 |
+
pg, _, _ = state_masks(gen, st)
|
| 167 |
+
lo, lg = obs["cells"].lib_measured.to_numpy(), gen["cells"].lib_measured.to_numpy()
|
| 168 |
+
if po.sum() == 0 or pg.sum() == 0:
|
| 169 |
+
continue
|
| 170 |
+
thin = min(1.0, float(np.median(lg[pg])) / float(np.median(lo[po])))
|
| 171 |
+
rng = np.random.default_rng([THIN_SEED, j, i])
|
| 172 |
+
M = obs["markers"]
|
| 173 |
+
Mt = rng.binomial(M, thin).astype(np.int32) if thin < 1.0 else M
|
| 174 |
+
t = state_table(obs, [st], f"observed_thin_d{j}", -1, counts=Mt)
|
| 175 |
+
t["state"] = st["name"]
|
| 176 |
+
t["thin"] = thin
|
| 177 |
+
rows.append(t)
|
| 178 |
+
return pd.concat(rows, ignore_index=True)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def calib_rows(gen: pd.DataFrame, obs: pd.DataFrame, feat_cols: list[str], meta: pd.DataFrame, ds: str, j: int,
|
| 182 |
+
kind: str) -> list[dict]:
|
| 183 |
+
"""gen / obs: long tables restricted to the draw's paired test samples; feature key = feat_cols."""
|
| 184 |
+
out = []
|
| 185 |
+
mg = gen.merge(obs, on=["sample_id"] + feat_cols, suffixes=("_gen", "_obs"))
|
| 186 |
+
mg = mg.merge(meta[["sample_id"] + [c for c in ("group", "case", "severity_peak") if c in meta]], on="sample_id")
|
| 187 |
+
for key, g in mg.groupby(feat_cols):
|
| 188 |
+
key = key if isinstance(key, tuple) else (key,)
|
| 189 |
+
g = g.dropna(subset=["frac_gen", "frac_obs"])
|
| 190 |
+
if len(g) < 3:
|
| 191 |
+
continue
|
| 192 |
+
rho = spearmanr(g.frac_gen, g.frac_obs).correlation if g.frac_gen.nunique() > 1 and g.frac_obs.nunique() > 1 else np.nan
|
| 193 |
+
r = {"kind": kind, "feature": " | ".join(map(str, key)), "draw": j, "n_samples": len(g),
|
| 194 |
+
"gen_mean": g.frac_gen.mean(), "obs_mean": g.frac_obs.mean(),
|
| 195 |
+
"ratio": g.frac_gen.mean() / g.frac_obs.mean() if g.frac_obs.mean() > 0 else np.nan, "spearman": rho}
|
| 196 |
+
for name, col, a, b in CONTRASTS[ds]:
|
| 197 |
+
ga, gb = g[g[col].isin(a)], g[g[col].isin(b)]
|
| 198 |
+
if len(ga) >= 2 and len(gb) >= 2:
|
| 199 |
+
dg, do = ga.frac_gen.mean() - gb.frac_gen.mean(), ga.frac_obs.mean() - gb.frac_obs.mean()
|
| 200 |
+
r[f"{name}: gen diff"], r[f"{name}: obs diff"] = dg, do
|
| 201 |
+
r[f"{name}: same sign"] = bool(np.sign(dg) == np.sign(do)) if dg != 0 and do != 0 else np.nan
|
| 202 |
+
r[f"{name}: n"] = f"{len(ga)} vs {len(gb)}"
|
| 203 |
+
out.append(r)
|
| 204 |
+
return out
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def main(argv=None) -> int:
|
| 208 |
+
ds = (argv or sys.argv[1:])[0]
|
| 209 |
+
out = C.PLAN / "analysis" / "features" / ds
|
| 210 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 211 |
+
states = json.loads(C.STATES.read_text())
|
| 212 |
+
meta = meta_table(ds)
|
| 213 |
+
meta.to_csv(out / "meta.csv", index=False)
|
| 214 |
+
W = C.PLAN / "work" / ds
|
| 215 |
+
obs = load_set(W / "observed")
|
| 216 |
+
comp, stt, cal = [composition(obs, "observed", -1)], [state_table(obs, states, "observed", -1)], []
|
| 217 |
+
for j in DRAWS:
|
| 218 |
+
pg = load_set(W / "paired_gen" / f"draw{j}")
|
| 219 |
+
comp.append(composition(pg, "paired_gen", j))
|
| 220 |
+
stt.append(state_table(pg, states, "paired_gen", j))
|
| 221 |
+
stt.append(thinned_observed(obs, pg, states, j))
|
| 222 |
+
bo_path = W / "bulkonly" / f"draw{j}"
|
| 223 |
+
if (bo_path / "RECEIPT.json").exists():
|
| 224 |
+
bo = load_set(bo_path)
|
| 225 |
+
comp.append(composition(bo, "bulkonly", j))
|
| 226 |
+
stt.append(state_table(bo, states, "bulkonly", j))
|
| 227 |
+
comp = pd.concat(comp, ignore_index=True)
|
| 228 |
+
stt = pd.concat(stt, ignore_index=True)
|
| 229 |
+
comp.to_parquet(out / "composition.parquet", index=False)
|
| 230 |
+
stt.to_parquet(out / "states.parquet", index=False)
|
| 231 |
+
# calibration on each draw's paired TEST samples
|
| 232 |
+
for j in DRAWS:
|
| 233 |
+
test = set(meta.loc[meta[f"paired_test_d{j}"], "sample_id"])
|
| 234 |
+
g = comp[(comp.set == "paired_gen") & (comp.draw == j) & comp.sample_id.isin(test)]
|
| 235 |
+
o = comp[(comp.set == "observed") & comp.sample_id.isin(test)]
|
| 236 |
+
cal += calib_rows(g[["sample_id", "level", "type", "frac"]], o[["sample_id", "level", "type", "frac"]],
|
| 237 |
+
["level", "type"], meta, ds, j, "composition")
|
| 238 |
+
sg = stt[(stt.set == "paired_gen") & (stt.draw == j) & stt.sample_id.isin(test)]
|
| 239 |
+
for st in states:
|
| 240 |
+
obs_set = "observed" if st["kind"] == "label" else f"observed_thin_d{j}"
|
| 241 |
+
so = stt[(stt.set == obs_set) & (stt.state == st["name"]) & stt.sample_id.isin(test)]
|
| 242 |
+
cal += calib_rows(sg[sg.state == st["name"]][["sample_id", "state", "frac"]], so[["sample_id", "state", "frac"]],
|
| 243 |
+
["state"], meta, ds, j, "state")
|
| 244 |
+
cal = pd.DataFrame(cal)
|
| 245 |
+
num = [c for c in cal.columns if c not in ("kind", "feature", "draw", "n_samples") and not c.endswith(": n")]
|
| 246 |
+
pooled = cal.groupby(["kind", "feature"])[num].agg(lambda x: np.nanmean(pd.to_numeric(x, errors="coerce")))
|
| 247 |
+
pooled["draws"] = cal.groupby(["kind", "feature"]).size()
|
| 248 |
+
for c in [c for c in cal.columns if c.endswith(": same sign")]:
|
| 249 |
+
pooled[c.replace("same sign", "draws same sign")] = cal.groupby(["kind", "feature"])[c].apply(
|
| 250 |
+
lambda x: f"{int(np.nansum(x.astype(float)))}/{int(x.notna().sum())}")
|
| 251 |
+
pooled = pooled.reset_index()
|
| 252 |
+
pooled.insert(2, "draw", "pooled")
|
| 253 |
+
pd.concat([cal, pooled], ignore_index=True).to_csv(out / "calibration.csv", index=False, float_format="%.6g")
|
| 254 |
+
# bulk-only: five-draw summary per sample x feature
|
| 255 |
+
bc = comp[comp.set == "bulkonly"].assign(feature=lambda t: t.level + " | " + t.type)
|
| 256 |
+
bs = stt[stt.set == "bulkonly"].assign(feature=lambda t: "state | " + t.state)
|
| 257 |
+
b = pd.concat([bc[["draw", "sample_id", "feature", "frac"]], bs[["draw", "sample_id", "feature", "frac"]]])
|
| 258 |
+
if len(b):
|
| 259 |
+
agg = b.groupby(["sample_id", "feature"]).frac.agg(["mean", "std", "min", "max", "count"]).reset_index()
|
| 260 |
+
agg.to_parquet(out / "bulkonly.parquet", index=False)
|
| 261 |
+
print(json.dumps({"dataset": ds, "meta_rows": len(meta), "composition_rows": len(comp), "state_rows": len(stt),
|
| 262 |
+
"calibration_rows": len(cal), "bulkonly_draws": sorted(set(comp[comp.set == "bulkonly"].draw))}))
|
| 263 |
+
return 0
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
if __name__ == "__main__":
|
| 267 |
+
sys.exit(main())
|