Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/build_k_conditions.py +70 -0
- paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/corpus_c1q.py +182 -0
- paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/run_gpu.sh +104 -0
- paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/summarize.py +85 -0
paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/build_k_conditions.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Real-bulk conditions of data/behcet at another recipe size K (CPU only; added 2026-10-04 for the LoRA K = 4000 test).
|
| 3 |
+
|
| 4 |
+
counts = CPM(bulk on measured genes) / 1e6 x (K x DEPTH_ANCHOR), recipe_k = K: RB.to_condition_counts with RECIPE_K
|
| 5 |
+
replaced by K, as plans/paired_crosscohort_20261002/tools/prepare_loco.py does. Every other key is copied from
|
| 6 |
+
data/behcet/conditions_raw_fixed.npz (K = 1000), and the K = 1000 arithmetic is first checked byte for byte against
|
| 7 |
+
that file. Output: data/behcet/conditions_raw_fixed_K<K>.npz (+ entry in data/behcet/K_CONDITIONS.json).
|
| 8 |
+
usage: build_k_conditions.py K
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import hashlib
|
| 13 |
+
import importlib.util
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 20 |
+
raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 25 |
+
DATA = Path(__file__).resolve().parents[1] / "data" / "behcet"
|
| 26 |
+
BUILDER = M8 / "plans/realbulk_generation_20260922/build_realbulk_conditions.py"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def sha(p: Path) -> str:
|
| 30 |
+
h = hashlib.sha256()
|
| 31 |
+
with open(p, "rb") as f:
|
| 32 |
+
for b in iter(lambda: f.read(1 << 22), b""):
|
| 33 |
+
h.update(b)
|
| 34 |
+
return h.hexdigest()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def main() -> int:
|
| 38 |
+
k = int(sys.argv[1])
|
| 39 |
+
spec = importlib.util.spec_from_file_location("build_realbulk_conditions", BUILDER)
|
| 40 |
+
RB = importlib.util.module_from_spec(spec)
|
| 41 |
+
sys.modules[spec.name] = RB
|
| 42 |
+
spec.loader.exec_module(RB)
|
| 43 |
+
f = np.load(DATA / "features.npz", allow_pickle=False)
|
| 44 |
+
valid = f["bulk_valid"].astype(bool)
|
| 45 |
+
bulk = np.where(valid, f["bulk_raw"], 0.0)
|
| 46 |
+
|
| 47 |
+
def counts_at(kk: int) -> np.ndarray:
|
| 48 |
+
return RB.cpm(np.where(valid, bulk, 0.0)) / 1e6 * (kk * RB.DEPTH_ANCHOR)
|
| 49 |
+
|
| 50 |
+
base = np.load(DATA / "conditions_raw_fixed.npz", allow_pickle=False)
|
| 51 |
+
if not (int(RB.RECIPE_K) == 1000 and np.array_equal(base["bulk_counts"], counts_at(1000))
|
| 52 |
+
and (base["recipe_k"] == 1000).all()):
|
| 53 |
+
raise SystemExit("K = 1000 arithmetic does not reproduce conditions_raw_fixed.npz")
|
| 54 |
+
arrays = {key: base[key] for key in base.files}
|
| 55 |
+
arrays["bulk_counts"] = counts_at(k)
|
| 56 |
+
arrays["recipe_k"] = np.full(len(arrays["recipe_k"]), k, dtype=np.int64)
|
| 57 |
+
arrays["arm"] = np.array(f"raw_K{k}")
|
| 58 |
+
out = DATA / f"conditions_raw_fixed_K{k}.npz"
|
| 59 |
+
np.savez(out, **arrays)
|
| 60 |
+
rec_path = DATA / "K_CONDITIONS.json"
|
| 61 |
+
rec = json.loads(rec_path.read_text()) if rec_path.exists() else {}
|
| 62 |
+
rec[out.name] = {"k": k, "sha256": sha(out), "from": "conditions_raw_fixed.npz", "from_sha256":
|
| 63 |
+
sha(DATA / "conditions_raw_fixed.npz"), "k1000_check": "byte-identical", "code_sha256": sha(Path(__file__))}
|
| 64 |
+
rec_path.write_text(json.dumps(rec, indent=1) + "\n")
|
| 65 |
+
print(json.dumps(rec[out.name]))
|
| 66 |
+
return 0
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
if __name__ == "__main__":
|
| 70 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/corpus_c1q.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""How common are C1Q-high monocytes in the pretraining corpus? (CPU only; user question 2026-10-04)
|
| 3 |
+
|
| 4 |
+
The final model (runs/f01_6k_1x_seed20260627) was trained on 22 datasets, 41.4 M cells
|
| 5 |
+
(plans/full_recipe_allcells_6k_broad_20260909/coverage_v1/shard_offsets.csv); Behçet (GSE198616) is not one of them.
|
| 6 |
+
This samples cells of every corpus dataset, labels them with the same frozen f01common scANVI model, and counts C1Q
|
| 7 |
+
genes in monocytes exactly as the Behçet scoring does, next to the Behçet observed cells.
|
| 8 |
+
|
| 9 |
+
phase extract: per dataset, up to SHARDS random training shards (base shards of shard_offsets.csv, read from the
|
| 10 |
+
PBISC-data copy, zarr v3 CSR on the 20,097-gene axis), BLOCKS random blocks of BLOCK consecutive cells per shard
|
| 11 |
+
(seed 20261004; datasets with fewer shards get more blocks per shard, ~SHARDS x BLOCKS
|
| 12 |
+
blocks per dataset); columns = the 6k panel (gene_positions.npy). Writes work/corpus_c1q/corpus_sample.h5ad
|
| 13 |
+
(obs: sample_id = dataset short id, dataset_id, shard_id, row) and SAMPLE.json.
|
| 14 |
+
phase analyze (after predict_scanvi on that h5ad): per dataset, monocytes = celltype_l1_pred 'Monocyte'; C1QA/B/C
|
| 15 |
+
(symbols resolved through the canonical gene table; the module JSON lists them) detected per monocyte; library on the
|
| 16 |
+
panel. Rates native, and after binomial thinning of every monocyte by one constant per dataset so that the dataset's
|
| 17 |
+
median monocyte library equals the Behçet observed median (datasets already below it are left as they are and
|
| 18 |
+
flagged). Behçet observed (GSE198616 PBMC, all 8, frozen labels of the earlier task) is scored by the same code.
|
| 19 |
+
Writes out/corpus_c1q.csv and prints it.
|
| 20 |
+
usage: corpus_c1q.py extract | analyze
|
| 21 |
+
"""
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import sys
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 30 |
+
raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pandas as pd
|
| 34 |
+
import scipy.sparse as sp
|
| 35 |
+
|
| 36 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 37 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 38 |
+
WORK = PLAN / "work/corpus_c1q"
|
| 39 |
+
OUT = PLAN / "out"
|
| 40 |
+
SHARDS_CSV = M8 / "plans/full_recipe_allcells_6k_broad_20260909/coverage_v1/shard_offsets.csv"
|
| 41 |
+
ZROOT = Path("/home/sj_server_1/PBISC/PBISC-data/single-cell-data-block-blood/counts/sc_counts")
|
| 42 |
+
POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
|
| 43 |
+
CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
|
| 44 |
+
"canonical_genes.tsv")
|
| 45 |
+
OBS_H5AD = M8 / "plans/behcet_c1q_repro_20260921/work/gse198616_pbmc_all8.h5ad"
|
| 46 |
+
OBS_LAB = M8 / "plans/utility_studies_final6k_20260925/behcet/work/scanvi_labels_real_f01common/labels.parquet"
|
| 47 |
+
C1Q = ("C1QA", "C1QB", "C1QC")
|
| 48 |
+
SHARDS, BLOCKS, BLOCK = 8, 4, 250
|
| 49 |
+
SEED = 20261004
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def extract() -> int:
|
| 53 |
+
import zarr
|
| 54 |
+
import anndata as ad
|
| 55 |
+
rng = np.random.default_rng(SEED)
|
| 56 |
+
so = pd.read_csv(SHARDS_CSV)
|
| 57 |
+
so = so[~so.shard_id.str.endswith("__strict_overlay")]
|
| 58 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 59 |
+
gene_ids = canon.gene_id.to_numpy().astype(str)
|
| 60 |
+
pos = np.load(POSITIONS).astype(np.int64)
|
| 61 |
+
blocks, obs, info = [], [], {}
|
| 62 |
+
for ds, g in so.groupby("dataset_id", sort=True):
|
| 63 |
+
have = [s for s in g.shard_id if (ZROOT / f"{s}.zarr").exists()]
|
| 64 |
+
if not have:
|
| 65 |
+
info[ds] = {"shards_available": 0}
|
| 66 |
+
continue
|
| 67 |
+
pick = rng.choice(have, size=min(SHARDS, len(have)), replace=False)
|
| 68 |
+
n_ds = 0
|
| 69 |
+
for s in sorted(pick):
|
| 70 |
+
grp = zarr.open_group(str(ZROOT / f"{s}.zarr"), mode="r")
|
| 71 |
+
indptr = grp["indptr"][:]
|
| 72 |
+
n = len(indptr) - 1
|
| 73 |
+
mmask = grp["measurement_mask"][:].astype(bool)
|
| 74 |
+
nblk = max(BLOCKS, -(-SHARDS * BLOCKS // len(pick))) # ~SHARDS x BLOCKS blocks per dataset
|
| 75 |
+
starts = rng.choice(max(1, n - BLOCK), size=min(nblk, max(1, n // BLOCK)), replace=False)
|
| 76 |
+
for st in sorted(starts):
|
| 77 |
+
en = min(n, st + BLOCK)
|
| 78 |
+
a, b = int(indptr[st]), int(indptr[en])
|
| 79 |
+
data = grp["data"][a:b]
|
| 80 |
+
idx = grp["indices"][a:b]
|
| 81 |
+
ip = indptr[st:en + 1] - a
|
| 82 |
+
X = sp.csr_matrix((data.astype(np.float32), idx, ip), shape=(en - st, len(gene_ids)))
|
| 83 |
+
X = X[:, pos].tocsr()
|
| 84 |
+
blocks.append(X)
|
| 85 |
+
obs.append(pd.DataFrame({"sample_id": ds.split("_")[0] + "_" + ds.split("_")[1], "dataset_id": ds,
|
| 86 |
+
"shard_id": s, "row": np.arange(st, en),
|
| 87 |
+
"c1q_measured": bool(mmask[pos][np.isin(gene_ids[pos], c1q_ids(canon))].all())}))
|
| 88 |
+
n_ds += en - st
|
| 89 |
+
info[ds] = {"shards_available": len(have), "shards_used": len(pick), "cells": n_ds}
|
| 90 |
+
print(ds[:60], info[ds], flush=True)
|
| 91 |
+
X = sp.vstack(blocks).tocsr()
|
| 92 |
+
o = pd.concat(obs, ignore_index=True)
|
| 93 |
+
o.index = [f"c{i}" for i in range(len(o))]
|
| 94 |
+
a = ad.AnnData(X=X, obs=o, var=pd.DataFrame(index=gene_ids[pos]))
|
| 95 |
+
WORK.mkdir(parents=True, exist_ok=True)
|
| 96 |
+
a.write_h5ad(WORK / "corpus_sample.h5ad")
|
| 97 |
+
(WORK / "SAMPLE.json").write_text(json.dumps({"seed": SEED, "shards_per_dataset": SHARDS, "blocks_per_shard": BLOCKS,
|
| 98 |
+
"block_cells": BLOCK, "cells": int(X.shape[0]), "datasets": info,
|
| 99 |
+
"zarr_root": str(ZROOT), "shard_offsets": str(SHARDS_CSV)}, indent=1, default=int))
|
| 100 |
+
print("cells", X.shape)
|
| 101 |
+
return 0
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def c1q_ids(canon: pd.DataFrame) -> np.ndarray:
|
| 105 |
+
ids = canon[canon.gene_symbol.isin(C1Q)].gene_id.astype(str).to_numpy()
|
| 106 |
+
if len(ids) != 3:
|
| 107 |
+
raise SystemExit("C1Q genes not found once each in the canonical table")
|
| 108 |
+
return ids
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def rates(X: sp.csr_matrix, c1q_cols: np.ndarray, mono: np.ndarray, groups: np.ndarray, target: float | None,
|
| 112 |
+
rng) -> pd.DataFrame:
|
| 113 |
+
"""Per group: monocytes, median panel library, % with >=1 / >=2 C1Q genes, native and depth-matched."""
|
| 114 |
+
rows = []
|
| 115 |
+
for g in pd.unique(groups):
|
| 116 |
+
m = np.flatnonzero(mono & (groups == g))
|
| 117 |
+
if len(m) == 0:
|
| 118 |
+
continue
|
| 119 |
+
Xm = X[m]
|
| 120 |
+
lib = np.asarray(Xm.sum(1)).ravel()
|
| 121 |
+
c = Xm[:, c1q_cols].toarray()
|
| 122 |
+
rec = {"group": g, "monocytes": len(m), "median_mono_lib": float(np.median(lib)),
|
| 123 |
+
"pct_ge1": 100 * float(((c > 0).sum(1) >= 1).mean()), "pct_ge2": 100 * float(((c > 0).sum(1) >= 2).mean())}
|
| 124 |
+
if target is not None:
|
| 125 |
+
f = min(1.0, target / rec["median_mono_lib"])
|
| 126 |
+
ct = rng.binomial(c.astype(np.int64), f)
|
| 127 |
+
rec.update({"thin_factor": f, "below_target": f >= 1.0,
|
| 128 |
+
"pct_ge1_matched": 100 * float(((ct > 0).sum(1) >= 1).mean()),
|
| 129 |
+
"pct_ge2_matched": 100 * float(((ct > 0).sum(1) >= 2).mean())})
|
| 130 |
+
rows.append(rec)
|
| 131 |
+
return pd.DataFrame(rows)
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def analyze() -> int:
|
| 135 |
+
import anndata as ad
|
| 136 |
+
rng = np.random.default_rng(SEED)
|
| 137 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 138 |
+
ids = c1q_ids(canon)
|
| 139 |
+
# Behçet observed, same code, on the same 6k panel columns
|
| 140 |
+
pos = np.load(POSITIONS).astype(np.int64)
|
| 141 |
+
panel = canon.gene_id.to_numpy().astype(str)[pos]
|
| 142 |
+
ob = ad.read_h5ad(OBS_H5AD)
|
| 143 |
+
keep = np.isin(ob.var_names.astype(str), panel)
|
| 144 |
+
Xo = sp.csr_matrix(ob.X[:, keep])
|
| 145 |
+
vo = ob.var_names.astype(str)[keep]
|
| 146 |
+
lo = pd.read_parquet(OBS_LAB)
|
| 147 |
+
if len(lo) != ob.n_obs:
|
| 148 |
+
raise SystemExit("observed labels / cells differ")
|
| 149 |
+
mono_o = lo.celltype_l1_pred.to_numpy() == "Monocyte"
|
| 150 |
+
grp_o = np.where(ob.obs.condition.astype(str).str.contains("BD|Beh", regex=True), "Behcet_BD_obs", "Behcet_HC_obs")
|
| 151 |
+
cols_o = np.array([list(vo).index(i) for i in ids])
|
| 152 |
+
target = float(np.median(np.asarray(Xo[mono_o].sum(1)).ravel()))
|
| 153 |
+
obs_tab = rates(Xo, cols_o, mono_o, grp_o, target, rng)
|
| 154 |
+
# corpus sample
|
| 155 |
+
a = ad.read_h5ad(WORK / "corpus_sample.h5ad")
|
| 156 |
+
lab = pd.read_parquet(WORK / "scanvi_labels/labels.parquet")
|
| 157 |
+
if len(lab) != a.n_obs:
|
| 158 |
+
raise SystemExit("corpus labels / cells differ")
|
| 159 |
+
Xc = sp.csr_matrix(a.X)
|
| 160 |
+
cols = np.array([list(a.var_names.astype(str)).index(i) for i in ids])
|
| 161 |
+
mono_c = lab.celltype_l1_pred.to_numpy() == "Monocyte"
|
| 162 |
+
tab = rates(Xc, cols, mono_c, a.obs.dataset_id.astype(str).to_numpy(), target, rng)
|
| 163 |
+
tab["c1q_measured"] = tab.group.map(a.obs.groupby("dataset_id").c1q_measured.all())
|
| 164 |
+
allc = pd.concat([obs_tab.assign(source="Behcet observed (not in corpus)"), tab.assign(source="corpus")],
|
| 165 |
+
ignore_index=True)
|
| 166 |
+
OUT.mkdir(exist_ok=True)
|
| 167 |
+
allc.to_csv(OUT / "corpus_c1q.csv", index=False)
|
| 168 |
+
with pd.option_context("display.width", 220, "display.max_rows", 100):
|
| 169 |
+
print(f"depth target (Behçet observed median monocyte library on the panel): {target:.0f}")
|
| 170 |
+
print(allc[["source", "group", "monocytes", "median_mono_lib", "pct_ge1", "pct_ge2", "thin_factor",
|
| 171 |
+
"pct_ge1_matched", "pct_ge2_matched"]].round(3).to_string(index=False))
|
| 172 |
+
cc = allc[allc.source == "corpus"]
|
| 173 |
+
w = cc.monocytes / cc.monocytes.sum()
|
| 174 |
+
print(f"corpus pooled (monocyte-weighted): >=2 C1Q genes native {np.sum(w * cc.pct_ge2):.3f}%, "
|
| 175 |
+
f"depth-matched {np.sum(w * cc.pct_ge2_matched):.3f}%; monocytes {int(cc.monocytes.sum())}")
|
| 176 |
+
return 0
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
if __name__ == "__main__":
|
| 180 |
+
if len(sys.argv) != 2 or sys.argv[1] not in ("extract", "analyze"):
|
| 181 |
+
raise SystemExit(__doc__)
|
| 182 |
+
sys.exit(extract() if sys.argv[1] == "extract" else analyze())
|
paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/run_gpu.sh
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Behçet LoRA-3: train once, then sample every arm; after each arm (CPU) Poisson read-out + frozen f01common scANVI
|
| 3 |
+
# labels, then the NPZ moves to spark-0110 at the same path (sha-checked, <npz stem>.moved left here) so this host keeps
|
| 4 |
+
# >= 80 GiB free for the scSemiProfiler queue.
|
| 5 |
+
# GPU steps: thermal gate, then ml-run (ml.slice, shared lock /run/user/1000/ml-gpu0.lock: a step waits in flock while
|
| 6 |
+
# another job holds the GPU, so it interleaves with the scSemiProfiler queue and never overlaps it).
|
| 7 |
+
# Steps already done are skipped (RUN.json; receipt + NPZ or .moved; h5ad; labels). No retry: a failed step logs WARN
|
| 8 |
+
# and the runner stops.
|
| 9 |
+
# arms file lines: TAG|CKPT (base | lora)|CONDITION_NPZ|SEED
|
| 10 |
+
# env (2026-10-04, defaults = the K = 1000 study): ARMS, RUN_DIR (LoRA run dir), TRAIN_COND (training condition NPZ)
|
| 11 |
+
set -uo pipefail
|
| 12 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 13 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 14 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 15 |
+
P=$M8/plans/behcet_c1q_lora3_20261004
|
| 16 |
+
FT=$M8/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py
|
| 17 |
+
S=$M8/plans/aifi_scanvi_rebuild_20260916
|
| 18 |
+
BASE=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
|
| 19 |
+
BASE_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
|
| 20 |
+
PY=/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python
|
| 21 |
+
CPY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
|
| 22 |
+
SPY=/home/sj_server_1/miniforge3/envs/scanvi/bin/python
|
| 23 |
+
DATA=$P/data/behcet
|
| 24 |
+
RUN=${RUN_DIR:-$P/runs/lora3}
|
| 25 |
+
TRAIN_COND=${TRAIN_COND:-$P/data/behcet/conditions_raw_fixed.npz}
|
| 26 |
+
GEN=$P/generated
|
| 27 |
+
WORK=$P/work
|
| 28 |
+
ARMS=${ARMS:-$P/queues/arms.txt}
|
| 29 |
+
R2=spark-0110
|
| 30 |
+
mkdir -p "$P/logs" "$GEN" "$WORK"
|
| 31 |
+
LOG=$P/logs/run_gpu_$(date +%Y%m%dT%H%M%S).log
|
| 32 |
+
log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
|
| 33 |
+
die() { log "WARN: $*; runner stops"; exit 1; }
|
| 34 |
+
thermal() { until v=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh"); do sleep 60; done; echo "$v"; }
|
| 35 |
+
cpu() { # cpu NAME CMD... : bounded CPU unit (no GPU), waits for it
|
| 36 |
+
local name=$1; shift
|
| 37 |
+
systemd-run --user --unit="behcet-lora3-$name-$(date +%H%M%S)" --wait --collect --quiet -p MemoryMax=24G \
|
| 38 |
+
-p MemorySwapMax=0 -p CPUQuota=400% -p Nice=10 --working-directory="$P" --setenv=CUDA_VISIBLE_DEVICES= \
|
| 39 |
+
--setenv=PYTHONNOUSERSITE=1 --setenv=OMP_NUM_THREADS=4 --setenv=MKL_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
|
| 40 |
+
-p StandardOutput=append:"$P/logs/$name.log" -p StandardError=append:"$P/logs/$name.log" "$@"
|
| 41 |
+
}
|
| 42 |
+
|
| 43 |
+
[[ "$(sha256sum "$BASE" | cut -d' ' -f1)" == "$BASE_SHA" ]] || die "base checkpoint sha"
|
| 44 |
+
log "runner start; arms $ARMS"
|
| 45 |
+
|
| 46 |
+
# ---- 1. LoRA-3 (fixed 3,000 steps, the LoRA-5 protocol)
|
| 47 |
+
if [[ ! -s $RUN/RUN.json ]]; then
|
| 48 |
+
mkdir -p "$RUN"
|
| 49 |
+
log "--- train $(basename "$RUN") on $(basename "$TRAIN_COND") ($(thermal))"
|
| 50 |
+
"$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 51 |
+
OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$FT" --checkpoint "$BASE" --checkpoint-sha "$BASE_SHA" \
|
| 52 |
+
--dataset-dir "$DATA" --condition-npz "$TRAIN_COND" --fold 0 --mode lora --lr 5e-4 \
|
| 53 |
+
--out-dir "$RUN" --train-donors-file "$DATA/train_donors.txt" --fixed-steps 3000 >> "$RUN/train.log" 2>&1 \
|
| 54 |
+
|| die "train failed (see $RUN/train.log)"
|
| 55 |
+
log "train done: $(python3 -c "import json;d=json.load(open('$RUN/RUN.json'));print(d['steps_run'],'steps', d['wall_seconds'],'s', d['checkpoint_sha256'][:12])")"
|
| 56 |
+
fi
|
| 57 |
+
LORA=$RUN/checkpoint_ft.pt
|
| 58 |
+
LORA_SHA=$(python3 -c "import json;print(json.load(open('$RUN/RUN.json'))['checkpoint_sha256'])")
|
| 59 |
+
[[ "$(sha256sum "$LORA" | cut -d' ' -f1)" == "$LORA_SHA" ]] || die "LoRA checkpoint sha differs from RUN.json"
|
| 60 |
+
|
| 61 |
+
# ---- 2. arms
|
| 62 |
+
while IFS='|' read -r tag which cond seed; do
|
| 63 |
+
[[ -z "${tag// }" || $tag == \#* ]] && continue
|
| 64 |
+
if [[ $which == base ]]; then ck=$BASE; else ck=$LORA; fi
|
| 65 |
+
out=$GEN/$tag.npz; rec=$GEN/$tag.log; err=$GEN/$tag.err
|
| 66 |
+
h5=$WORK/${tag}_poisson.h5ad; lab=$WORK/scanvi_labels_${tag}_f01common
|
| 67 |
+
if [[ -s $rec && ( -s $out || -f $GEN/$tag.moved ) ]]; then
|
| 68 |
+
log "$tag sampled already"
|
| 69 |
+
else
|
| 70 |
+
log "--- sample $tag ckpt=$which seed=$seed ($(thermal))"
|
| 71 |
+
"$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 72 |
+
PYTHONPATH="$M8/src" OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
|
| 73 |
+
--checkpoint "$ck" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 --steps 50 \
|
| 74 |
+
--seed "$seed" --device cuda --conditioner-source embedded --active-logit-threshold 0.0 \
|
| 75 |
+
--support-readout bernoulli > "$rec" 2> "$err" || die "sample $tag failed (see $err)"
|
| 76 |
+
log "$tag sampled: $(python3 -c "import json;d=json.load(open('$rec'));print(d['cells'],'cells', d['output_sha256'][:12])")"
|
| 77 |
+
fi
|
| 78 |
+
if [[ ! -s $h5 ]]; then
|
| 79 |
+
[[ -s $out ]] || die "$tag: NPZ needed for the read-out but not here"
|
| 80 |
+
cpu "readout-$tag" "$CPY" "$S/poisson_readout.py" --npz "$out" --out "$h5" --seed 20260916 \
|
| 81 |
+
--method-name "generated_GSE198533_all19_lora3study_${tag}" --hash-input || die "$tag read-out failed"
|
| 82 |
+
log "$tag read-out done"
|
| 83 |
+
fi
|
| 84 |
+
if [[ ! -s $lab/labels.parquet ]]; then
|
| 85 |
+
systemd-run --user --unit="behcet-lora3-label-$tag-$(date +%H%M%S)" --wait --collect --quiet -p MemoryMax=24G \
|
| 86 |
+
-p MemorySwapMax=0 -p CPUQuota=400% -p Nice=10 --working-directory="$S" --setenv=CUDA_VISIBLE_DEVICES= \
|
| 87 |
+
--setenv=PYTHONNOUSERSITE=1 --setenv=OMP_NUM_THREADS=4 --setenv=MKL_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
|
| 88 |
+
-p StandardOutput=append:"$P/logs/label-$tag.log" -p StandardError=append:"$P/logs/label-$tag.log" \
|
| 89 |
+
"$SPY" "$S/predict_scanvi.py" --model-dir "$S/runs/aifi_scanvi_f01common_v1/scanvi_model" --query "$h5" \
|
| 90 |
+
--out-dir "$lab" --device cpu --num-threads 4 --method-name "generated_GSE198533_all19_lora3study_${tag}" \
|
| 91 |
+
--dataset-id GSE198533 --sample-id-col sample_id || die "$tag labelling failed"
|
| 92 |
+
log "$tag labels done"
|
| 93 |
+
fi
|
| 94 |
+
if [[ -s $out ]]; then
|
| 95 |
+
want=$(python3 -c "import json;print(json.load(open('$rec'))['output_sha256'])")
|
| 96 |
+
ssh -n $R2 "mkdir -p '$GEN'" && rsync -a "$out" "$rec" "$err" "$R2:$GEN/" >> "$LOG" 2>&1 || die "$tag: copy to $R2"
|
| 97 |
+
got=$(ssh -n $R2 "sha256sum '$out'" | awk '{print $1}')
|
| 98 |
+
[[ $got == "$want" ]] || die "$tag: sha on $R2 differs"
|
| 99 |
+
python3 -c "import json,sys,datetime;json.dump({'moved_to':'$R2','path':'$out','sha256':'$want','at':datetime.datetime.now().isoformat()},open('$GEN/$tag.moved','w'),indent=1)"
|
| 100 |
+
rm -f "$out"
|
| 101 |
+
log "$tag NPZ moved to $R2 (sha checked)"
|
| 102 |
+
fi
|
| 103 |
+
done < "$ARMS"
|
| 104 |
+
log "runner finished"
|
paper-releases/pbisc-diffusion/updates/20261004T065028Z-behcet-c1q-k4000-corpus/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/summarize.py
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Summary of the Behçet LoRA-3 study from out/rules_groups/per_sample_group_metrics.csv (CPU only).
|
| 3 |
+
|
| 4 |
+
Generated arms: zs_raw (base model, real bulk), zs_cal (base, bulk x alpha fitted on the 3 pairs), lora3_raw (LoRA on
|
| 5 |
+
the 3 pairs, real bulk); seeds s13 = 20260913 (the published Behçet seed) and s04 = 20261004.
|
| 6 |
+
Rows of a generated arm: train = BDV4, BDV5, BDV6 (their own cells were the LoRA training data);
|
| 7 |
+
test = the other 6 BD and all 10 HC bulks (never seen in training).
|
| 8 |
+
Observed: GSE198616 PBMC, 4 BD vs 4 HC (mostly other donors than the bulk), native depth and thinned to each base arm.
|
| 9 |
+
Outputs (out/): group_table.csv (per arm x row set x rule: BD mean, HC mean, gap, Mann-Whitney p), in_sample.csv
|
| 10 |
+
(training donors: generated vs their own observed cells), capability.csv (pooled C1Q-state rates in monocytes),
|
| 11 |
+
SUMMARY.json
|
| 12 |
+
usage: summarize.py [RULES_DIR (default out/rules_groups)] [OUTPUT_SUFFIX (default none)] (2026-10-04: K = 4000 test
|
| 13 |
+
is summarised with: summarize.py out/rules_groups_k4000 _k4000)
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import pandas as pd
|
| 23 |
+
from scipy.stats import mannwhitneyu
|
| 24 |
+
|
| 25 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 26 |
+
OUT = PLAN / "out"
|
| 27 |
+
PAIRS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/behcet_pair_recovery_20261004/"
|
| 28 |
+
"out/pairs_recovered.csv")
|
| 29 |
+
RULES = ("A", "B", "C", "D")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def gap_row(d: pd.DataFrame, col: str) -> dict:
|
| 33 |
+
bd, hc = d[d.group == "BD"][col].to_numpy(), d[d.group == "HC"][col].to_numpy()
|
| 34 |
+
p = float(mannwhitneyu(bd, hc).pvalue) if len(bd) and len(hc) else np.nan
|
| 35 |
+
return {"n_bd": len(bd), "n_hc": len(hc), "bd_mean_pct": 100 * bd.mean(), "hc_mean_pct": 100 * hc.mean(),
|
| 36 |
+
"gap_pp": 100 * (bd.mean() - hc.mean()), "mw_p": p}
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main() -> int:
|
| 40 |
+
rdir = Path(sys.argv[1]) if len(sys.argv) > 1 else OUT / "rules_groups"
|
| 41 |
+
suf = sys.argv[2] if len(sys.argv) > 2 else ""
|
| 42 |
+
m = pd.read_csv(rdir / "per_sample_group_metrics.csv")
|
| 43 |
+
pairs = pd.read_csv(PAIRS)
|
| 44 |
+
train = set(pairs.bulk_sample)
|
| 45 |
+
rows = []
|
| 46 |
+
for arm, d in m.groupby("arm", sort=False):
|
| 47 |
+
sets = {"observed": d} if arm.startswith("obs") else {"test": d[~d.sample_id.isin(train)], "all": d}
|
| 48 |
+
for sname, s in sets.items():
|
| 49 |
+
for r in RULES:
|
| 50 |
+
rows.append({"arm": arm, "rows": sname, "metric": f"c1q_high_rule_{r}", **gap_row(s, f"c1q_high_fraction_{r}")})
|
| 51 |
+
rows.append({"arm": arm, "rows": sname, "metric": "monocyte_fraction", **gap_row(s, "monocyte_fraction_all_cells")})
|
| 52 |
+
gt = pd.DataFrame(rows)
|
| 53 |
+
gt.to_csv(OUT / f"group_table{suf}.csv", index=False)
|
| 54 |
+
# in-sample: training donors vs their own observed cells (native and thinned)
|
| 55 |
+
ins = []
|
| 56 |
+
for p in pairs.itertuples():
|
| 57 |
+
for arm, d in m.groupby("arm", sort=False):
|
| 58 |
+
key = p.sc_sample if arm.startswith("obs") else p.bulk_sample
|
| 59 |
+
r = d[d.sample_id == key]
|
| 60 |
+
if len(r):
|
| 61 |
+
r = r.iloc[0]
|
| 62 |
+
ins.append({"donor": p.bulk_sample, "sc_sample": p.sc_sample, "arm": arm,
|
| 63 |
+
"monocyte_fraction_pct": 100 * r.monocyte_fraction_all_cells,
|
| 64 |
+
**{f"c1q_high_{x}_pct": 100 * r[f"c1q_high_fraction_{x}"] for x in RULES}})
|
| 65 |
+
pd.DataFrame(ins).to_csv(OUT / f"in_sample{suf}.csv", index=False)
|
| 66 |
+
# capability: pooled over all monocytes of the arm (generated: test rows only; observed: all 8 samples)
|
| 67 |
+
cap = []
|
| 68 |
+
for arm, d in m.groupby("arm", sort=False):
|
| 69 |
+
s = d if arm.startswith("obs") else d[~d.sample_id.isin(train)]
|
| 70 |
+
mono = s.n_monocytes.sum()
|
| 71 |
+
cap.append({"arm": arm, "monocytes": int(mono),
|
| 72 |
+
**{f"pooled_rule_{x}_pct": 100 * s[f"n_c1q_high_{x}"].sum() / mono for x in RULES}})
|
| 73 |
+
pd.DataFrame(cap).to_csv(OUT / f"capability{suf}.csv", index=False)
|
| 74 |
+
summ = {"group_table": gt.round(4).to_dict("records"), "capability": cap, "train_rows": sorted(train)}
|
| 75 |
+
(OUT / f"SUMMARY{suf}.json").write_text(json.dumps(summ, indent=1, default=float) + "\n")
|
| 76 |
+
with pd.option_context("display.width", 220, "display.max_rows", 500):
|
| 77 |
+
print(gt[gt.metric.isin(["c1q_high_rule_A", "c1q_high_rule_B", "c1q_high_rule_D", "monocyte_fraction"])]
|
| 78 |
+
.round(3).to_string(index=False))
|
| 79 |
+
print(pd.DataFrame(ins).round(2).to_string(index=False))
|
| 80 |
+
print(pd.DataFrame(cap).round(3).to_string(index=False))
|
| 81 |
+
return 0
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
if __name__ == "__main__":
|
| 85 |
+
raise SystemExit(main())
|