Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/README.md +57 -0
- paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/tools/build_inputs.py +170 -0
- paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/tools/compare.py +116 -0
- paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/tools/run_gpu.sh +70 -0
paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/README.md
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# C1Q-high monocytes across diseases: in-corpus vs not (2026-10-04)
|
| 2 |
+
|
| 3 |
+
**Question (user).** Behçet is not in the pretraining corpus. Is that why the model hardly generates C1Q-high
|
| 4 |
+
monocytes? Test other diseases with C1Q-high monocytes.
|
| 5 |
+
|
| 6 |
+
**Design.**
|
| 7 |
+
- Final model (f01 6k 1× E16), zero-shot. Each sample's own sc pseudobulk is the condition, at fixed depth K = 1,000,
|
| 8 |
+
so there is no real-bulk shift. One sampling seed (20260913).
|
| 9 |
+
- Cells generated per sample: 5,000 for DRESS and Kawasaki, 3,000 for SLE.
|
| 10 |
+
- Observed cells use the paired benchmark's QC (genes ≥ 200, UMI ≥ 500, mito ≤ 20 %).
|
| 11 |
+
- Both sides are labelled by the frozen f01common scANVI model. C1Q genes are counted in monocytes as in the Behçet
|
| 12 |
+
scoring.
|
| 13 |
+
- Observed monocytes are binomially thinned to the generated median monocyte library on the shared measured genes.
|
| 14 |
+
|
| 15 |
+
| dataset | in corpus | samples | ≥ 2 C1Q genes, obs → gen | gen / obs | Spearman over samples (≥ 2 genes) | ≥ 1 C1Q gene gen / obs |
|
| 16 |
+
|---|---|---:|---|---:|---:|---:|
|
| 17 |
+
| **DRESS** GSE132802, all 7 PBMC samples | **yes** | 7 | 11.9 → 2.9 % | 0.24 | **0.96** | 0.93 |
|
| 18 |
+
| uncultured PBMC (HV, DRESS1, 2 weeks after) | yes | 3 | 2.6 → 1.4 % | **0.53** | | 1.27 |
|
| 19 |
+
| cultured / stimulated PBMC | yes | 4 | 51.4 → 4.5 % | 0.09 | | 0.39 |
|
| 20 |
+
| **Kawasaki** GSE168732 (6 KD before / after IVIG, 3 HC) | no | 15 | 5.5 → 0.54 % | **0.10** | 0.17 | 0.47 |
|
| 21 |
+
| **SLE** GSE135779 (children + adults, SLE + HC) | no | 56 | 2.5 → 0.50 % | **0.20** | 0.42 | 0.68 |
|
| 22 |
+
| Behçet (earlier, LoRA-3 on real bulk) | no | 16 | 2.4 → 0.25–0.46 % | 0.10–0.18 | – | 0.63 |
|
| 23 |
+
|
| 24 |
+
Monocyte share is reproduced in every dataset: Spearman 0.96 / 0.89 / 0.97.
|
| 25 |
+
|
| 26 |
+
**Disease direction for ≥ 2 C1Q genes** (observed vs generated, per-sample means):
|
| 27 |
+
- Kawasaki before vs after IVIG: observed +3.05 pp, generated −0.36 pp (**reversed**). Kawasaki before IVIG vs HC:
|
| 28 |
+
observed +2.92, generated +0.35.
|
| 29 |
+
- SLE adults vs adult HC: observed +1.50, generated −0.10 (**reversed**). SLE children vs child HC: observed +0.59,
|
| 30 |
+
generated +0.11.
|
| 31 |
+
|
| 32 |
+
## Reading
|
| 33 |
+
|
| 34 |
+
1. **Being in the corpus helps.**
|
| 35 |
+
- DRESS, which the model was trained on, has its per-sample C1Q ranking reproduced (Spearman 0.96).
|
| 36 |
+
- Its ordinary PBMC samples reach about half the observed multi-gene C1Q rate.
|
| 37 |
+
- The two diseases outside the corpus reach 0.10–0.20×, track their samples weakly (0.17–0.42), and lose or reverse
|
| 38 |
+
the disease direction. So the user's hypothesis is partly right.
|
| 39 |
+
2. **But being in the corpus is not enough.**
|
| 40 |
+
- DRESS samples were training samples, so part of that fit is recall of seen samples.
|
| 41 |
+
- Even there the multi-gene state comes out at about 0.5× in ordinary PBMC.
|
| 42 |
+
- In the cultured, macrophage-like samples (≥ 2 C1Q genes in 51 % of monocytes) it comes out at only 0.09×.
|
| 43 |
+
- The generator still compresses rare co-expression.
|
| 44 |
+
3. **Not tested here.** Whether adding a disease's own cells fixes it (sc-only LoRA on part of the SLE donors, tested on
|
| 45 |
+
held-out donors) is the direct next test of the hypothesis.
|
| 46 |
+
|
| 47 |
+
## Files
|
| 48 |
+
|
| 49 |
+
- `tools/build_inputs.py` → `data/<ds>/` (observed 6k-panel h5ad, `conditions_pseudo_K1000.npz`, `samples.csv`,
|
| 50 |
+
`BUILD.json`).
|
| 51 |
+
- `tools/run_gpu.sh` + `queues/arms.txt` → `generated/` (receipts; NPZs moved to spark-0110 at the same paths, sha-checked)
|
| 52 |
+
and `work/` (read-out h5ad, labels).
|
| 53 |
+
- `tools/compare.py` → `out/{per_sample,summary,group_means}.csv`.
|
| 54 |
+
- The DRESS source is
|
| 55 |
+
`gblee/datalake/single-cell-RNA-seq-datasets/_staged_new_blocks/300_A_GSE132802_…raw_counts.h5ad`. That folder is
|
| 56 |
+
being archived to the NAS (`NAS_INVENTORY`, `gblee_datalake_20261004`), so a rebuild after local deletion needs a
|
| 57 |
+
restore from there.
|
paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/tools/build_inputs.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Inputs for the cross-disease C1Q-high test (CPU only; user request 2026-10-04: "실험해봐").
|
| 3 |
+
|
| 4 |
+
Question: is the missing C1Q-high monocyte state in generated Behçet cells due to Behçet being absent from the
|
| 5 |
+
pretraining corpus? Test the final model zero-shot on three other diseases with C1Q-high monocytes, each conditioned
|
| 6 |
+
on its own samples' sc pseudobulk (no real-bulk shift), and compare generated with observed cells per sample:
|
| 7 |
+
dress GSE132802 DRESS/DiHS, PBMC samples only IN the corpus (300b_A, 34,051 cells; corpus monocytes with
|
| 8 |
+
>= 2 C1Q genes 14 %, tools of behcet_c1q_lora3/corpus_c1q)
|
| 9 |
+
kawasaki GSE168732 Kawasaki disease before / after IVIG + healthy NOT in the corpus (C1Qhi reported by Zheng 2022)
|
| 10 |
+
sle GSE135779 childhood + adult SLE and healthy (Nehar-Belaid) NOT in the corpus (C1Qhi reported by Zheng 2022)
|
| 11 |
+
Per dataset (cells kept: genes >= 200, UMI >= 500, mito <= 20 %, the paired benchmark's rule):
|
| 12 |
+
data/<ds>/observed_panel6k.h5ad kept cells on the 6k panel (raw counts; unmeasured panel genes are 0), obs sample_id,
|
| 13 |
+
group, n_genes, umi; scANVI labels are added later by tools/run.sh
|
| 14 |
+
data/<ds>/conditions_pseudo_K1000.npz per sample: sc pseudobulk (sum of kept cells) on the 20,097 axis at fixed depth
|
| 15 |
+
(realbulk_generation builder, K = RECIPE_K = 1000), the paired benchmark's NPZ layout
|
| 16 |
+
(prepare_dataset.write_npz); output_availability_mask = genes measured in the dataset
|
| 17 |
+
data/<ds>/samples.csv, BUILD.json
|
| 18 |
+
usage: build_inputs.py dress|kawasaki|sle
|
| 19 |
+
"""
|
| 20 |
+
from __future__ import annotations
|
| 21 |
+
|
| 22 |
+
import hashlib
|
| 23 |
+
import importlib.util
|
| 24 |
+
import json
|
| 25 |
+
import os
|
| 26 |
+
import sys
|
| 27 |
+
from datetime import datetime, timezone
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
|
| 30 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 31 |
+
raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
|
| 32 |
+
|
| 33 |
+
import anndata as ad
|
| 34 |
+
import numpy as np
|
| 35 |
+
import pandas as pd
|
| 36 |
+
import scipy.sparse as sp
|
| 37 |
+
|
| 38 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 39 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 40 |
+
DL = Path("/home/sj_server_1/gblee/datalake/single-cell-RNA-seq-datasets")
|
| 41 |
+
CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
|
| 42 |
+
"canonical_genes.tsv")
|
| 43 |
+
POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
|
| 44 |
+
POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
|
| 45 |
+
PREP = M8 / "plans/paired_finetune_intradataset_20260927/tools/prepare_dataset.py"
|
| 46 |
+
SRC = {
|
| 47 |
+
"dress": DL / "_staged_new_blocks/300_A_GSE132802_DRESS_DiHS_skin_blood_cultured_PBMC_scRNAseq/"
|
| 48 |
+
"300_A_GSE132802_DRESS_DiHS_skin_blood_cultured_PBMC_scRNAseq.raw_counts.h5ad",
|
| 49 |
+
"kawasaki": DL / "PBMC-cells/045_A_GSE168732_Kawasaki_disease_PBMC_before_after_IVIG/processed_h5ad",
|
| 50 |
+
"sle": DL / "PBMC-cells/004_A_GSE135779_Nehar-Belaid_et_al._childhood_+_adult_SLE_PBMC_single-cell_dataset/"
|
| 51 |
+
"gse135779_processed.h5ad",
|
| 52 |
+
}
|
| 53 |
+
CELLS_PER_BULK = {"dress": 5000, "kawasaki": 5000, "sle": 3000}
|
| 54 |
+
MIN_GENES, MIN_UMI, MAX_MITO = 200, 500, 20.0
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def sha(p: Path) -> str:
|
| 58 |
+
h = hashlib.sha256()
|
| 59 |
+
with open(p, "rb") as f:
|
| 60 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 61 |
+
h.update(b)
|
| 62 |
+
return h.hexdigest()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load(ds: str, canon: pd.DataFrame):
|
| 66 |
+
"""-> X (cells x 20,097 canonical, csr int), measured (20,097 bool), obs (sample_id, group)."""
|
| 67 |
+
ids = canon.gene_id.to_numpy().astype(str)
|
| 68 |
+
col_of = {g: i for i, g in enumerate(ids)}
|
| 69 |
+
if ds == "dress":
|
| 70 |
+
a = ad.read_h5ad(SRC[ds])
|
| 71 |
+
a = a[(a.obs.tissue.astype(str) == "PBMC").to_numpy()].copy()
|
| 72 |
+
X0, genes = sp.csr_matrix(a.X), a.var_names.astype(str).to_numpy()
|
| 73 |
+
obs = pd.DataFrame({"sample_id": a.obs.sample_name.astype(str).to_numpy(),
|
| 74 |
+
"group": (a.obs.disease.astype(str) + "|" + a.obs.condition.astype(str)).to_numpy()})
|
| 75 |
+
mito = np.array([s.startswith("MT-") for s in canon.set_index("gene_id").reindex(genes).gene_symbol.fillna("").astype(str)])
|
| 76 |
+
elif ds == "kawasaki":
|
| 77 |
+
Xs, obs_l, genes = [], [], None
|
| 78 |
+
for f in sorted(SRC[ds].glob("*.h5ad")):
|
| 79 |
+
a = ad.read_h5ad(f)
|
| 80 |
+
g = a.var_names.astype(str).to_numpy()
|
| 81 |
+
if genes is None:
|
| 82 |
+
genes, sym = g, a.var.gene_symbol.astype(str).to_numpy()
|
| 83 |
+
elif not np.array_equal(g, genes):
|
| 84 |
+
raise SystemExit(f"{f.name}: gene order differs")
|
| 85 |
+
tag = f.name.split("_")[1] + "_" + f.name.split("_")[2] # e.g. P1_before, H1_health
|
| 86 |
+
Xs.append(sp.csr_matrix(a.X))
|
| 87 |
+
obs_l.append(pd.DataFrame({"sample_id": [tag] * a.n_obs,
|
| 88 |
+
"group": ["KD_before" if "before" in tag else "KD_after" if "after" in tag else "HC"] * a.n_obs}))
|
| 89 |
+
X0, obs = sp.vstack(Xs).tocsr(), pd.concat(obs_l, ignore_index=True)
|
| 90 |
+
mito = np.char.startswith(sym.astype(str), "MT-")
|
| 91 |
+
else:
|
| 92 |
+
import h5py
|
| 93 |
+
from anndata.experimental import read_elem
|
| 94 |
+
a = ad.read_h5ad(SRC[ds], backed="r") # obs / var only; X (log-normalised) is not loaded
|
| 95 |
+
with h5py.File(SRC[ds], "r") as f:
|
| 96 |
+
X0 = sp.csr_matrix(read_elem(f["layers/counts"]))
|
| 97 |
+
sym = np.asarray(a.var_names.astype(str).tolist(), dtype=str)
|
| 98 |
+
# symbols -> canonical ids (unique symbols only)
|
| 99 |
+
s2i = canon.drop_duplicates("gene_symbol", keep=False).set_index("gene_symbol").gene_id
|
| 100 |
+
genes = np.array([s2i.get(s, "") for s in sym])
|
| 101 |
+
obs = pd.DataFrame({"sample_id": a.obs.sample_title.astype(str).str.split(" ").str[0].to_numpy(),
|
| 102 |
+
"group": a.obs.dataset_group.astype(str).to_numpy()})
|
| 103 |
+
mito = np.char.startswith(sym, "MT-")
|
| 104 |
+
if not np.allclose(X0.data, np.rint(X0.data)):
|
| 105 |
+
raise SystemExit(f"{ds}: counts are not integers")
|
| 106 |
+
umi = np.asarray(X0.sum(1)).ravel()
|
| 107 |
+
ng = np.diff(X0.indptr)
|
| 108 |
+
mt = np.asarray(X0[:, np.flatnonzero(mito)].sum(1)).ravel() / np.maximum(umi, 1) * 100
|
| 109 |
+
keep = (ng >= MIN_GENES) & (umi >= MIN_UMI) & (mt <= MAX_MITO)
|
| 110 |
+
cols = np.array([col_of.get(g, -1) for g in genes])
|
| 111 |
+
ok = cols >= 0
|
| 112 |
+
X0 = X0[np.flatnonzero(keep)][:, np.flatnonzero(ok)].tocsr()
|
| 113 |
+
# duplicate canonical columns (rare) are summed
|
| 114 |
+
M = sp.csr_matrix((np.ones(ok.sum()), (np.arange(ok.sum()), cols[ok])), shape=(ok.sum(), len(ids)))
|
| 115 |
+
X = (X0 @ M).tocsr()
|
| 116 |
+
X.data = np.rint(X.data)
|
| 117 |
+
measured = np.zeros(len(ids), dtype=bool)
|
| 118 |
+
measured[cols[ok]] = True
|
| 119 |
+
obs = obs[keep].reset_index(drop=True)
|
| 120 |
+
obs["umi"] = umi[keep]
|
| 121 |
+
obs["n_genes"] = ng[keep]
|
| 122 |
+
return X, measured, obs, {"cells_in": int(len(keep)), "cells_kept": int(keep.sum()),
|
| 123 |
+
"source_genes": int(len(genes)), "mapped_genes": int(ok.sum()), "measured_canonical": int(measured.sum())}
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def main() -> int:
|
| 127 |
+
ds = sys.argv[1]
|
| 128 |
+
spec = importlib.util.spec_from_file_location("prepare_dataset", PREP)
|
| 129 |
+
PD = importlib.util.module_from_spec(spec)
|
| 130 |
+
sys.modules[spec.name] = PD
|
| 131 |
+
spec.loader.exec_module(PD)
|
| 132 |
+
RB = PD.RB
|
| 133 |
+
if sha(POSITIONS) != POSITIONS_SHA:
|
| 134 |
+
raise SystemExit("gene_positions sha")
|
| 135 |
+
pos = np.load(POSITIONS).astype(np.int64)
|
| 136 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 137 |
+
ids = canon.gene_id.to_numpy().astype("U15")
|
| 138 |
+
X, measured, obs, info = load(ds, canon)
|
| 139 |
+
out = PLAN / "data" / ds
|
| 140 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 141 |
+
samples = sorted(obs.sample_id.unique())
|
| 142 |
+
grp = obs.groupby("sample_id").group.first()
|
| 143 |
+
pb = np.zeros((len(samples), len(ids)))
|
| 144 |
+
for i, s in enumerate(samples):
|
| 145 |
+
pb[i] = np.asarray(X[np.flatnonzero(obs.sample_id.to_numpy() == s)].sum(0)).ravel()
|
| 146 |
+
meas = np.tile(measured, (len(samples), 1))
|
| 147 |
+
d = {"gene_ids": ids, "sample_ids": np.array(samples), "donor_ids": np.array(samples),
|
| 148 |
+
"groups": grp.reindex(samples).to_numpy().astype(str), "sc_valid": meas,
|
| 149 |
+
"n_cells": obs.sample_id.value_counts().reindex(samples).to_numpy()}
|
| 150 |
+
cond = RB.to_condition_counts(pb, meas)
|
| 151 |
+
sha_c = PD.write_npz(out / "conditions_pseudo_K1000.npz", d, np.arange(len(samples)), cond, meas,
|
| 152 |
+
CELLS_PER_BULK[ds], "pseudo")
|
| 153 |
+
o = ad.AnnData(X=X[:, pos].astype(np.float32), obs=obs.assign(sample_id=obs.sample_id.astype(str)),
|
| 154 |
+
var=pd.DataFrame(index=ids[pos]))
|
| 155 |
+
o.obs.index = [f"{ds}_{i}" for i in range(o.n_obs)]
|
| 156 |
+
o.write_h5ad(out / "observed_panel6k.h5ad")
|
| 157 |
+
pd.DataFrame({"sample_id": samples, "group": d["groups"], "n_cells": d["n_cells"],
|
| 158 |
+
"pseudobulk_umi": pb.sum(1)}).to_csv(out / "samples.csv", index=False)
|
| 159 |
+
build = {"dataset": ds, "source": str(SRC[ds]), "written_utc": datetime.now(timezone.utc).isoformat(), **info,
|
| 160 |
+
"qc": {"min_genes": MIN_GENES, "min_umi": MIN_UMI, "max_mito_pct": MAX_MITO}, "samples": len(samples),
|
| 161 |
+
"recipe_k": int(RB.RECIPE_K), "cells_per_bulk": CELLS_PER_BULK[ds], "panel_measured": int(measured[pos].sum()),
|
| 162 |
+
"c1q_measured": {g: bool(measured[list(ids).index(canon.set_index('gene_symbol').gene_id[g])]) for g in ("C1QA", "C1QB", "C1QC")},
|
| 163 |
+
"conditions_sha256": sha_c, "code_sha256": sha(Path(__file__))}
|
| 164 |
+
(out / "BUILD.json").write_text(json.dumps(build, indent=1) + "\n")
|
| 165 |
+
print(json.dumps(build, indent=1))
|
| 166 |
+
return 0
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
if __name__ == "__main__":
|
| 170 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/tools/compare.py
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Generated vs observed C1Q state per sample, for every dataset with a generated arm (CPU only).
|
| 3 |
+
|
| 4 |
+
Inputs per dataset ds and arm tag (<ds>_zs_s13 ...): data/<ds>/observed_panel6k.h5ad + work/obs_labels_<ds>/labels.parquet
|
| 5 |
+
(observed), work/<tag>_poisson.h5ad + work/scanvi_labels_<tag>_f01common/labels.parquet (generated; Poisson read-out
|
| 6 |
+
seed 20260916). Monocytes = frozen f01common scANVI celltype_l1_pred 'Monocyte', the same labels and C1Q counting as the
|
| 7 |
+
Behçet scoring. C1Q genes C1QA / C1QB / C1QC are resolved through the canonical gene table.
|
| 8 |
+
Depth: observed monocytes are binomially thinned (seed 20261004) by one constant per dataset so that their median
|
| 9 |
+
library on the measured panel genes equals the generated arm's median monocyte library (both sides are restricted to
|
| 10 |
+
the same measured panel genes); if the observed median is already lower, nothing is thinned.
|
| 11 |
+
Per sample: monocyte share of all cells, % of monocytes with >= 1 and >= 2 C1Q genes, mean C1Q UMI per monocyte.
|
| 12 |
+
Per dataset: pooled rates, generated / observed ratios, Spearman over samples (generated vs observed, depth-matched),
|
| 13 |
+
group means. Outputs: out/per_sample.csv, out/summary.csv, out/group_means.csv
|
| 14 |
+
usage: compare.py TAG [TAG ...]
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import sys
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import anndata as ad
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
import scipy.sparse as sp
|
| 25 |
+
from scipy.stats import spearmanr
|
| 26 |
+
|
| 27 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 28 |
+
CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
|
| 29 |
+
"canonical_genes.tsv")
|
| 30 |
+
SEED = 20261004
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def mono_stats(X: sp.csr_matrix, cols: np.ndarray, mono: np.ndarray, samples: np.ndarray, thin: float, rng) -> pd.DataFrame:
|
| 34 |
+
rows = []
|
| 35 |
+
for s in pd.unique(samples):
|
| 36 |
+
m = samples == s
|
| 37 |
+
mm = np.flatnonzero(m & mono)
|
| 38 |
+
c = X[mm][:, cols].toarray().astype(np.int64)
|
| 39 |
+
if thin < 1.0:
|
| 40 |
+
c = rng.binomial(c, thin)
|
| 41 |
+
k = (c > 0).sum(1)
|
| 42 |
+
rows.append({"sample_id": s, "cells": int(m.sum()), "monocytes": len(mm),
|
| 43 |
+
"mono_pct": 100 * len(mm) / max(int(m.sum()), 1),
|
| 44 |
+
"c1q_ge1_pct": 100 * float((k >= 1).mean()) if len(mm) else np.nan,
|
| 45 |
+
"c1q_ge2_pct": 100 * float((k >= 2).mean()) if len(mm) else np.nan,
|
| 46 |
+
"n_ge2": int((k >= 2).sum()), "c1q_umi_mean": float(c.sum(1).mean()) if len(mm) else np.nan})
|
| 47 |
+
return pd.DataFrame(rows)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def main() -> int:
|
| 51 |
+
tags = sys.argv[1:]
|
| 52 |
+
canon = pd.read_csv(CANON, sep="\t", dtype=str)
|
| 53 |
+
c1q = canon[canon.gene_symbol.isin(["C1QA", "C1QB", "C1QC"])].gene_id.tolist()
|
| 54 |
+
rng = np.random.default_rng(SEED)
|
| 55 |
+
per, summ, grp_rows = [], [], []
|
| 56 |
+
for tag in tags:
|
| 57 |
+
ds = tag.split("_")[0]
|
| 58 |
+
ob = ad.read_h5ad(PLAN / f"data/{ds}/observed_panel6k.h5ad")
|
| 59 |
+
lo = pd.read_parquet(PLAN / f"work/obs_labels_{ds}/labels.parquet")
|
| 60 |
+
gn = ad.read_h5ad(PLAN / f"work/{tag}_poisson.h5ad")
|
| 61 |
+
lg = pd.read_parquet(PLAN / f"work/scanvi_labels_{tag}_f01common/labels.parquet")
|
| 62 |
+
if len(lo) != ob.n_obs or len(lg) != gn.n_obs:
|
| 63 |
+
raise SystemExit(f"{tag}: labels / cells differ")
|
| 64 |
+
samples_csv = pd.read_csv(PLAN / f"data/{ds}/samples.csv").set_index("sample_id")
|
| 65 |
+
# common measured panel genes (generated output mask = genes measured in the dataset)
|
| 66 |
+
Xo, Xg = sp.csr_matrix(ob.X), sp.csr_matrix(gn.X)
|
| 67 |
+
vo, vg = list(ob.var_names.astype(str)), list(gn.var_names.astype(str))
|
| 68 |
+
meas = np.asarray((Xo.sum(0) > 0)).ravel()
|
| 69 |
+
shared = [g for g, mk in zip(vo, meas) if mk and g in set(vg)]
|
| 70 |
+
io = np.array([vo.index(g) for g in shared]); ig = np.array([vg.index(g) for g in shared])
|
| 71 |
+
Xo, Xg = Xo[:, io].tocsr(), Xg[:, ig].tocsr()
|
| 72 |
+
cols = np.array([shared.index(g) for g in c1q])
|
| 73 |
+
mo = lo.celltype_l1_pred.to_numpy() == "Monocyte"
|
| 74 |
+
mg = lg.celltype_l1_pred.to_numpy() == "Monocyte"
|
| 75 |
+
lib_o = np.median(np.asarray(Xo[mo].sum(1)).ravel())
|
| 76 |
+
lib_g = np.median(np.asarray(Xg[mg].sum(1)).ravel())
|
| 77 |
+
thin = min(1.0, lib_g / lib_o)
|
| 78 |
+
so = ob.obs.sample_id.astype(str).to_numpy()
|
| 79 |
+
sgen = gn.obs.sample_id.astype(str).to_numpy()
|
| 80 |
+
po = mono_stats(Xo, cols, mo, so, 1.0, rng).add_prefix("obs_").rename(columns={"obs_sample_id": "sample_id"})
|
| 81 |
+
pt = mono_stats(Xo, cols, mo, so, thin, rng).add_prefix("obsthin_").rename(columns={"obsthin_sample_id": "sample_id"})
|
| 82 |
+
pg = mono_stats(Xg, cols, mg, sgen, 1.0, rng).add_prefix("gen_").rename(columns={"gen_sample_id": "sample_id"})
|
| 83 |
+
t = po.merge(pt, on="sample_id").merge(pg, on="sample_id")
|
| 84 |
+
t.insert(0, "arm", tag); t.insert(1, "dataset", ds)
|
| 85 |
+
t["group"] = t.sample_id.map(samples_csv.group)
|
| 86 |
+
per.append(t)
|
| 87 |
+
pooled = lambda d, p, k: 100 * d[f"{p}_{k}"].mul(d[f"{p}_monocytes"]).sum() / 100 / d[f"{p}_monocytes"].sum()
|
| 88 |
+
rec = {"arm": tag, "dataset": ds, "samples": len(t), "obs_monocytes": int(t.obs_monocytes.sum()),
|
| 89 |
+
"gen_monocytes": int(t.gen_monocytes.sum()), "obs_median_mono_lib": lib_o, "gen_median_mono_lib": lib_g,
|
| 90 |
+
"thin_factor": thin}
|
| 91 |
+
for k in ("c1q_ge1_pct", "c1q_ge2_pct"):
|
| 92 |
+
rec[f"obs_{k}"] = pooled(t, "obs", k); rec[f"obsthin_{k}"] = pooled(t, "obsthin", k)
|
| 93 |
+
rec[f"gen_{k}"] = pooled(t, "gen", k)
|
| 94 |
+
rec[f"ratio_{k}"] = rec[f"gen_{k}"] / rec[f"obsthin_{k}"] if rec[f"obsthin_{k}"] else np.nan
|
| 95 |
+
ok = t[[f"gen_{k}", f"obsthin_{k}"]].dropna()
|
| 96 |
+
rec[f"spearman_{k}"] = float(spearmanr(ok.iloc[:, 0], ok.iloc[:, 1]).correlation) if len(ok) > 2 else np.nan
|
| 97 |
+
ok = t[["gen_mono_pct", "obs_mono_pct"]]
|
| 98 |
+
rec["spearman_mono_pct"] = float(spearmanr(ok.gen_mono_pct, ok.obs_mono_pct).correlation)
|
| 99 |
+
rec["obs_mono_pct_mean"], rec["gen_mono_pct_mean"] = t.obs_mono_pct.mean(), t.gen_mono_pct.mean()
|
| 100 |
+
summ.append(rec)
|
| 101 |
+
g = t.groupby("group")[["obs_mono_pct", "gen_mono_pct", "obsthin_c1q_ge1_pct", "gen_c1q_ge1_pct",
|
| 102 |
+
"obsthin_c1q_ge2_pct", "gen_c1q_ge2_pct"]].mean().reset_index()
|
| 103 |
+
g.insert(0, "arm", tag)
|
| 104 |
+
grp_rows.append(g)
|
| 105 |
+
out = PLAN / "out"
|
| 106 |
+
out.mkdir(exist_ok=True)
|
| 107 |
+
P, Sm, G = pd.concat(per), pd.DataFrame(summ), pd.concat(grp_rows)
|
| 108 |
+
P.to_csv(out / "per_sample.csv", index=False); Sm.to_csv(out / "summary.csv", index=False); G.to_csv(out / "group_means.csv", index=False)
|
| 109 |
+
with pd.option_context("display.width", 250, "display.max_columns", 40):
|
| 110 |
+
print(Sm.round(3).T.to_string())
|
| 111 |
+
print(G.round(2).to_string(index=False))
|
| 112 |
+
return 0
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
if __name__ == "__main__":
|
| 116 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261004T141237Z-c1q-crossdisease/diffusion/dataset/server_1/model8/plans/c1q_crossdisease_20261004/tools/run_gpu.sh
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env bash
|
| 2 |
+
# Cross-disease C1Q test: zero-shot sampling from the final model on each dataset's sc pseudobulk, then (CPU) Poisson
|
| 3 |
+
# read-out + frozen f01common scANVI labels; the NPZ then moves to spark-0110 at the same path (sha-checked, .moved).
|
| 4 |
+
# GPU steps: thermal gate, then ml-run (ml.slice, shared lock; waits in flock while another job holds the GPU, never
|
| 5 |
+
# overlaps). Steps already done are skipped. No retry: a failed step logs WARN and the runner stops.
|
| 6 |
+
# arms file lines: TAG|CONDITION_NPZ|SEED
|
| 7 |
+
set -uo pipefail
|
| 8 |
+
export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
|
| 9 |
+
export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
|
| 10 |
+
M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
|
| 11 |
+
P=$M8/plans/c1q_crossdisease_20261004
|
| 12 |
+
S=$M8/plans/aifi_scanvi_rebuild_20260916
|
| 13 |
+
BASE=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
|
| 14 |
+
BASE_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
|
| 15 |
+
PY=/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python
|
| 16 |
+
CPY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
|
| 17 |
+
SPY=/home/sj_server_1/miniforge3/envs/scanvi/bin/python
|
| 18 |
+
ARMS=${ARMS:-$P/queues/arms.txt}
|
| 19 |
+
GEN=$P/generated; WORK=$P/work; R2=spark-0110
|
| 20 |
+
mkdir -p "$P/logs" "$GEN" "$WORK"
|
| 21 |
+
LOG=$P/logs/run_gpu_$(date +%Y%m%dT%H%M%S).log
|
| 22 |
+
log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
|
| 23 |
+
die() { log "WARN: $*; runner stops"; exit 1; }
|
| 24 |
+
thermal() { until v=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh"); do sleep 60; done; echo "$v"; }
|
| 25 |
+
unit() { # unit NAME WORKDIR CMD... : bounded CPU unit
|
| 26 |
+
local name=$1 wd=$2; shift 2
|
| 27 |
+
systemd-run --user --unit="c1qx-$name-$(date +%H%M%S)" --wait --collect --quiet -p MemoryMax=24G -p MemorySwapMax=0 \
|
| 28 |
+
-p CPUQuota=400% -p Nice=10 --working-directory="$wd" --setenv=CUDA_VISIBLE_DEVICES= --setenv=PYTHONNOUSERSITE=1 \
|
| 29 |
+
--setenv=OMP_NUM_THREADS=4 --setenv=MKL_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
|
| 30 |
+
-p StandardOutput=append:"$P/logs/$name.log" -p StandardError=append:"$P/logs/$name.log" "$@"
|
| 31 |
+
}
|
| 32 |
+
[[ "$(sha256sum "$BASE" | cut -d' ' -f1)" == "$BASE_SHA" ]] || die "base checkpoint sha"
|
| 33 |
+
log "runner start; arms $ARMS"
|
| 34 |
+
while IFS='|' read -r tag cond seed; do
|
| 35 |
+
[[ -z "${tag// }" || $tag == \#* ]] && continue
|
| 36 |
+
out=$GEN/$tag.npz; rec=$GEN/$tag.log; err=$GEN/$tag.err
|
| 37 |
+
h5=$WORK/${tag}_poisson.h5ad; lab=$WORK/scanvi_labels_${tag}_f01common
|
| 38 |
+
if [[ -s $rec && ( -s $out || -f $GEN/$tag.moved ) ]]; then log "$tag sampled already"
|
| 39 |
+
else
|
| 40 |
+
log "--- sample $tag seed=$seed ($(thermal))"
|
| 41 |
+
"$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 42 |
+
PYTHONPATH="$M8/src" OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
|
| 43 |
+
--checkpoint "$BASE" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 --steps 50 \
|
| 44 |
+
--seed "$seed" --device cuda --conditioner-source embedded --active-logit-threshold 0.0 \
|
| 45 |
+
--support-readout bernoulli > "$rec" 2> "$err" || die "sample $tag failed (see $err)"
|
| 46 |
+
log "$tag sampled: $(python3 -c "import json;d=json.load(open('$rec'));print(d['cells'],'cells', d['output_sha256'][:12])")"
|
| 47 |
+
fi
|
| 48 |
+
if [[ ! -s $h5 ]]; then
|
| 49 |
+
[[ -s $out ]] || die "$tag: NPZ needed for the read-out but not here"
|
| 50 |
+
unit "readout-$tag" "$P" "$CPY" "$S/poisson_readout.py" --npz "$out" --out "$h5" --seed 20260916 \
|
| 51 |
+
--method-name "generated_c1qx_${tag}" --hash-input || die "$tag read-out failed"
|
| 52 |
+
log "$tag read-out done"
|
| 53 |
+
fi
|
| 54 |
+
if [[ ! -s $lab/labels.parquet ]]; then
|
| 55 |
+
unit "label-$tag" "$S" "$SPY" "$S/predict_scanvi.py" --model-dir "$S/runs/aifi_scanvi_f01common_v1/scanvi_model" \
|
| 56 |
+
--query "$h5" --out-dir "$lab" --device cpu --num-threads 4 --method-name "generated_c1qx_${tag}" \
|
| 57 |
+
--sample-id-col sample_id || die "$tag labelling failed"
|
| 58 |
+
log "$tag labels done"
|
| 59 |
+
fi
|
| 60 |
+
if [[ -s $out ]]; then
|
| 61 |
+
want=$(python3 -c "import json;print(json.load(open('$rec'))['output_sha256'])")
|
| 62 |
+
ssh -n $R2 "mkdir -p '$GEN'" && rsync -a "$out" "$rec" "$err" "$R2:$GEN/" >> "$LOG" 2>&1 || die "$tag: copy to $R2"
|
| 63 |
+
got=$(ssh -n $R2 "sha256sum '$out'" | awk '{print $1}')
|
| 64 |
+
[[ $got == "$want" ]] || die "$tag: sha on $R2 differs"
|
| 65 |
+
python3 -c "import json,datetime;json.dump({'moved_to':'$R2','path':'$out','sha256':'$want','at':datetime.datetime.now().isoformat()},open('$GEN/$tag.moved','w'),indent=1)"
|
| 66 |
+
rm -f "$out"
|
| 67 |
+
log "$tag NPZ moved to $R2 (sha checked)"
|
| 68 |
+
fi
|
| 69 |
+
done < "$ARMS"
|
| 70 |
+
log "runner finished"
|