junidude14 commited on
Commit
2d0f7dc
·
verified ·
1 Parent(s): 42555a1

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/build_split.py ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """BayesPrism inputs of one split (CPU only; 2026-10-06). See common.py for the splits and the gene axis.
3
+
4
+ reference per state the summed raw UMI of the split's reference samples' observed cells (data/<ds>/aggregates.npz);
5
+ states with < MIN_STATE_CELLS cells are merged into "<type>|minor" of their type
6
+ mixture the mixture samples' real bulk raw counts (FT data/<ds>/features.npz bulk_raw, the bulk the LoRA condition is
7
+ built from) on the same genes; every gene must be bulk-valid in every mixture sample
8
+ Genes kept: the BayesPrism axis (common.bp_genes) with reference UMI > 0 and bulk-valid in every mixture sample.
9
+ Output inputs/<ds>/<kind><idx>/: reference.tsv.gz (states x genes), state_types.tsv (state, type, n_cells),
10
+ mixture.tsv.gz (samples x genes), SPLIT.json (rows, counts, checks, shas).
11
+ Gene mode (4th argument): score (default) or full (aggregates_full.npz -> inputs/<ds>/<kind><idx>_full/).
12
+ usage: CUDA_VISIBLE_DEVICES='' build_split.py DATASET {fewshot|cv} IDX [score|full]
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import json
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
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
28
+ import common as C # noqa: E402
29
+
30
+
31
+ def main(argv=None) -> int:
32
+ args = argv or sys.argv[1:]
33
+ ds, kind, idx = args[0], args[1], int(args[2])
34
+ mode = args[3] if len(args) > 3 else "score"
35
+ aggp = C.PLAN / "data" / ds / f"aggregates{C.suffix(mode)}.npz"
36
+ sp_ = C.split_rows(ds, kind, idx)
37
+ ag = np.load(aggp, allow_pickle=False)
38
+ sids = ag["sample_ids"].astype(str)
39
+ pos = {s: i for i, s in enumerate(sids)}
40
+ ref_r = np.asarray([pos[s] for s in sp_["reference"]], dtype=np.int64)
41
+ mix_r = np.asarray([pos[s] for s in sp_["mixture"]], dtype=np.int64)
42
+ sums = ag["sums"][ref_r].sum(0) # states x genes
43
+ ncell = ag["n_cells"][ref_r].sum(0)
44
+ states, types = ag["states"].astype(str), ag["state_types"].astype(str)
45
+ big = ncell >= C.MIN_STATE_CELLS
46
+ rows, names, tys, ns = [], [], [], []
47
+ for i in np.flatnonzero(big):
48
+ rows.append(sums[i]); names.append(states[i]); tys.append(types[i]); ns.append(int(ncell[i]))
49
+ for t in sorted(set(types)):
50
+ small = (~big) & (types == t) & (ncell > 0)
51
+ if small.any():
52
+ rows.append(sums[small].sum(0)); names.append(f"{t}|minor"); tys.append(t); ns.append(int(ncell[small].sum()))
53
+ ref = np.vstack(rows)
54
+ feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
55
+ fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
56
+ if not np.array_equal(fsid, sids):
57
+ raise SystemExit("features.npz sample order differs from the aggregates")
58
+ gpos = {g: i for i, g in enumerate(feat["gene_ids"].astype(str))}
59
+ gcols = np.asarray([gpos[g] for g in ag["gene_ids"].astype(str)], dtype=np.int64)
60
+ valid = feat["bulk_valid"].astype(bool)[mix_r][:, gcols].all(0)
61
+ bulk = np.asarray(feat["bulk_raw"], np.float64)[mix_r][:, gcols]
62
+ if not np.isfinite(bulk[:, valid]).all() or (bulk[:, valid] < 0).any() or \
63
+ (bulk[:, valid] != np.round(bulk[:, valid])).any():
64
+ raise SystemExit("mixture counts are not finite non-negative integers on valid genes")
65
+ keep = valid & (ref.sum(0) > 0)
66
+ genes = ag["gene_ids"].astype(str)[keep]
67
+ out = C.PLAN / "inputs" / ds / f"{kind}{idx}{C.suffix(mode)}"
68
+ out.mkdir(parents=True, exist_ok=True)
69
+ pd.DataFrame(ref[:, keep], index=pd.Index(names, name="state"), columns=genes).to_csv(
70
+ out / "reference.tsv.gz", sep="\t", float_format="%.0f")
71
+ pd.DataFrame({"state": names, "type": tys, "n_cells": ns}).to_csv(out / "state_types.tsv", sep="\t", index=False)
72
+ pd.DataFrame(bulk[:, keep].astype(np.int64), index=pd.Index(sp_["mixture"], name="sample"), columns=genes).to_csv(
73
+ out / "mixture.tsv.gz", sep="\t")
74
+ rec = {"dataset": ds, "kind": kind, "idx": idx, **{k: v for k, v in sp_.items()},
75
+ "n_reference_samples": int(ref_r.size), "n_mixture_samples": int(mix_r.size),
76
+ "reference_cells": int(ncell.sum()), "states": len(names), "states_merged_minor": int((~big & (ncell > 0)).sum()),
77
+ "types": sorted(set(tys)), "missing_types": sorted(set(types) - set(tys)),
78
+ "bp_axis_genes": int(ag["gene_ids"].size), "genes_kept": int(keep.sum()),
79
+ "genes_dropped_not_bulk_valid": int((~valid).sum()), "genes_dropped_zero_reference": int((valid & (ref.sum(0) == 0)).sum()),
80
+ "gene_mode": mode, "aggregates_sha256": C.sha(aggp),
81
+ "files": {f: C.sha(out / f) for f in ("reference.tsv.gz", "state_types.tsv", "mixture.tsv.gz")},
82
+ "tool_sha256": C.sha(Path(__file__)), "common_sha256": C.sha(Path(C.__file__))}
83
+ (out / "SPLIT.json").write_text(json.dumps(rec, indent=1) + "\n")
84
+ print(json.dumps({k: rec[k] for k in ("dataset", "kind", "idx", "n_reference_samples", "n_mixture_samples",
85
+ "reference_cells", "states", "genes_kept", "types")}))
86
+ return 0
87
+
88
+
89
+ if __name__ == "__main__":
90
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/common.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared definitions of plans/bayesprism_paired_20261006 (CPU only; imported, not run).
2
+
3
+ User request (2026-10-06): compare the paired LoRA results with reference deconvolution, BayesPrism given the SAME
4
+ paired donors as reference, on the paired benchmark's own donors, truth and scorer. In the SLE zero-shot test
5
+ BayesPrism's cell-type expression Z beat the generator (utility_studies_final6k_20260925/sle_broadcast/RESULTS.md);
6
+ the paired benchmark had no such comparison.
7
+
8
+ Splits (the paired benchmark's own):
9
+ fewshot draw j reference = the usable rows of the draw's 5 training donors (fewshot_n5/draw<j>/train_donors.txt,
10
+ folds.csv fold >= 0: exactly ft_sdd.py's training rows); mixture = the draw's test samples
11
+ (test_samples.txt). Compared with arm lora5 of scores/<ds>/fewshot_n5/draw<j>.
12
+ cv fold k reference = runs/<ds>/fold<k>/real_lora/RUN.json train_rows + inner_val_rows (every pair the
13
+ LoRA fold model could use; scSemiProfiler's same-pair representatives); mixture = folds.csv fold == k
14
+ (= RUN.json test_rows_never_loaded_for_training). Pooled over folds and compared with arm
15
+ real_lora__raw of scores/<ds>/pooled (5-fold CV) and scsemi__raw of scsemi_cv_20261002/pooled.
16
+ Genes: the cohort's scoring genes (scoring_cache/<ds>/reference.npz score_ids: measured by both assays in every sample,
17
+ inside the model panel) minus chrY, chrM, XIST and TSIX (sex / mitochondrial genes that deconvolution guides remove;
18
+ ~18 genes, 0.3 %), so BayesPrism's Z lies on the scorer's own gene axis.
19
+ Reference states: observed cells' frozen-annotator labels, "<six-type gate>|<AIFI L2>" (each state has one type);
20
+ types: the six-type gate (T cell, B cell, Monocyte, NK cell, DC, Other), the scorer's composition axis.
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import json
26
+ from pathlib import Path
27
+
28
+ import numpy as np
29
+ import pandas as pd
30
+
31
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
32
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
33
+ PLAN = Path(__file__).resolve().parents[1]
34
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
35
+ "canonical_genes.tsv")
36
+ COHORTS = ("immicro", "ye2026_sepsis", "ji2025_chili", "imperial_eskd", "giroux2022")
37
+ MIN_STATE_CELLS = 20 # smaller reference states are merged into "<type>|minor"
38
+ DROP_SYMBOLS = {"XIST", "TSIX"}
39
+ DROP_CHROM = {"chrY", "chrM"}
40
+
41
+
42
+ def sha(p: Path) -> str:
43
+ h = hashlib.sha256()
44
+ with open(p, "rb") as f:
45
+ for b in iter(lambda: f.read(1 << 24), b""):
46
+ h.update(b)
47
+ return h.hexdigest()
48
+
49
+
50
+ def bp_genes(ds: str) -> np.ndarray:
51
+ """Scoring genes of the cohort minus chrY / chrM / XIST / TSIX, in score_ids order."""
52
+ ref = np.load(FT / "scoring_cache" / ds / "reference.npz", allow_pickle=False)
53
+ ids = ref["score_ids"].astype(str)
54
+ canon = pd.read_csv(CANON, sep="\t", dtype=str).set_index("gene_id")
55
+ c = canon.loc[ids]
56
+ keep = ~(c.chromosome.isin(DROP_CHROM) | c.gene_symbol.isin(DROP_SYMBOLS)).to_numpy()
57
+ return ids[keep]
58
+
59
+
60
+ def full_genes(ds: str) -> np.ndarray:
61
+ """BayesPrism's recommended gene set ('full' mode): the canonical protein-coding axis minus chrX, chrY, chrM and
62
+ ribosomal RPS/RPL/MRPS/MRPL genes (cleanup.genes defaults), limited to genes the cohort's sc assay measured in every
63
+ sample (features.npz sc_valid); bulk validity and reference UMI are applied per split."""
64
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
65
+ f = np.load(FT / "data" / ds / "features.npz", allow_pickle=False)
66
+ if not np.array_equal(f["gene_ids"].astype(str), canon.gene_id.to_numpy()):
67
+ raise SystemExit("features.npz gene axis differs from the canonical gene table")
68
+ bad = canon.chromosome.isin(["chrX", "chrY", "chrM"]) | canon.gene_symbol.str.match(r"^(RP[SL]\d|MRP[SL]\d)")
69
+ sc_ok = f["sc_valid"].astype(bool).all(0)
70
+ return canon.gene_id.to_numpy().astype(str)[(~bad.to_numpy()) & sc_ok]
71
+
72
+
73
+ def genes_for(ds: str, mode: str) -> np.ndarray:
74
+ return bp_genes(ds) if mode == "score" else full_genes(ds)
75
+
76
+
77
+ def suffix(mode: str) -> str:
78
+ return "" if mode == "score" else f"_{mode}"
79
+
80
+
81
+ def local_copy(path: str | Path, want_sha: str | None = None) -> Path:
82
+ """A file of the paired benchmark that may exist only on spark-0110 (same absolute path): copied once into
83
+ remote_cache/ (sha checked when known); the original is never touched."""
84
+ import subprocess
85
+ path = Path(path)
86
+ if path.exists():
87
+ return path
88
+ dst = PLAN / "remote_cache" / str(path).lstrip("/")
89
+ if not dst.exists():
90
+ dst.parent.mkdir(parents=True, exist_ok=True)
91
+ subprocess.run(["rsync", "-a", f"spark-0110:{path}", str(dst)], check=True)
92
+ if want_sha and sha(dst) != want_sha:
93
+ raise SystemExit(f"{path}: copied file sha differs from the recorded sha")
94
+ return dst
95
+
96
+
97
+ def folds(ds: str) -> pd.DataFrame:
98
+ return pd.read_csv(FT / "data" / ds / "folds.csv")
99
+
100
+
101
+ def split_rows(ds: str, kind: str, idx: int) -> dict:
102
+ """Reference and mixture sample ids of one split (see module doc), with the cross-checks that are possible."""
103
+ f = folds(ds)
104
+ if kind == "fewshot":
105
+ d = FT / "data" / ds / "fewshot_n5" / f"draw{idx}"
106
+ want = {l.strip() for l in (d / "train_donors.txt").read_text().splitlines() if l.strip()}
107
+ ref = f.loc[f.donor_id.astype(str).isin(want) & (f.fold >= 0), "sample_id"].astype(str).tolist()
108
+ mix = [l.strip() for l in (d / "test_samples.txt").read_text().splitlines() if l.strip()]
109
+ rj = FT / "runs" / ds / "fewshot_n5" / f"draw{idx}" / "lora" / "RUN.json"
110
+ if not rj.exists(): # Imperial's runs live on spark-0110; a sha-checked RUN.json copy was kept here
111
+ rj = M8 / "plans/bulkonly_lora5_20261006/ckpt_tmp" / ds / f"draw{idx}" / "RUN.json"
112
+ check = None
113
+ if rj.exists():
114
+ r = json.loads(rj.read_text())
115
+ check = sorted(r["train_rows"]) == sorted(ref) and sorted(r["test_rows_never_loaded_for_training"]) == sorted(mix)
116
+ if not check:
117
+ raise SystemExit(f"{ds} draw {idx}: rows differ from {rj}")
118
+ return {"reference": ref, "mixture": mix, "train_donors": sorted(want), "run_json_check": check}
119
+ if kind == "cv":
120
+ r = json.loads(local_copy(FT / "runs" / ds / f"fold{idx}" / "real_lora" / "RUN.json").read_text())
121
+ ref = list(r["train_rows"]) + list(r.get("inner_val_rows", []))
122
+ mix = f.loc[f.fold == idx, "sample_id"].astype(str).tolist()
123
+ if sorted(r["test_rows_never_loaded_for_training"]) != sorted(mix):
124
+ raise SystemExit(f"{ds} fold {idx}: test rows differ from RUN.json")
125
+ if set(ref) & set(mix):
126
+ raise SystemExit(f"{ds} fold {idx}: reference and mixture overlap")
127
+ return {"reference": ref, "mixture": mix, "run_json_check": True,
128
+ "n_train_rows": len(r["train_rows"]), "n_inner_val_rows": len(r.get("inner_val_rows", []))}
129
+ raise SystemExit(f"unknown split kind {kind}")
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/finalize.sh ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # After both BayesPrism lanes (units bp-lane-a, bp-lane-b): score every finished comparison (score_bp.py; a split
3
+ # whose BayesPrism or stored score is missing is logged and skipped) and write the tables (aggregate_bp.py).
4
+ # CPU only; each scoring call in a bounded scope (MemoryMax 16G, 2 threads). usage: finalize.sh
5
+ set -uo pipefail
6
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
7
+ export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
8
+ P=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/bayesprism_paired_20261006
9
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
10
+ LOG=$P/logs/finalize_$(date +%Y%m%dT%H%M%S).log
11
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
12
+ while systemctl --user is-active --quiet bp-lane-a || systemctl --user is-active --quiet bp-lane-b; do sleep 60; done
13
+ log "lanes finished"
14
+ score() {
15
+ systemd-run --user --scope --quiet -p MemoryMax=16G -p MemorySwapMax=0 -p CPUQuota=200% \
16
+ nice -n 10 env CUDA_VISIBLE_DEVICES= PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 \
17
+ "$PY" "$P/tools/score_bp.py" "$@" >> "$LOG" 2>&1
18
+ }
19
+ n_fail=0
20
+ for ds in immicro ye2026_sepsis ji2025_chili imperial_eskd giroux2022; do
21
+ for j in 0 1 2 3 4; do score "$ds" fewshot "$j" || { n_fail=$((n_fail+1)); log "WARN: $ds fewshot $j"; }; done
22
+ score "$ds" cv || { n_fail=$((n_fail+1)); log "WARN: $ds cv"; }
23
+ done
24
+ "$PY" "$P/tools/aggregate_bp.py" >> "$LOG" 2>&1 || { n_fail=$((n_fail+1)); log "WARN: aggregate"; }
25
+ log "finalize done; failed=$n_fail"
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/finalize_cx.sh ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Score every CIBERSORTx comparison (score_bp.py ... cibersortx; same scorer, donors and gates as BayesPrism) and write
3
+ # results/TABLE_*_cibersortx.csv + RESULTS_cibersortx.md. Optionally re-score the full-gene BayesPrism CV of the cohorts
4
+ # in RESCORE_FULL_CV (picks up scSemiProfiler 5-fold results finished after finalize_full.sh) and rewrite the full tables.
5
+ # CPU only; each scoring call in a bounded scope (MemoryMax 16G, 2 threads). usage: finalize_cx.sh env: RESCORE_FULL_CV
6
+ set -uo pipefail
7
+ P=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/bayesprism_paired_20261006
8
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
9
+ LOG=$P/logs/finalize_cx_$(date +%Y%m%dT%H%M%S).log
10
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
11
+ score() { systemd-run --user --scope --quiet -p MemoryMax=16G -p MemorySwapMax=0 -p CPUQuota=200% nice -n 10 \
12
+ env CUDA_VISIBLE_DEVICES= PYTHONDONTWRITEBYTECODE=1 OMP_NUM_THREADS=2 OPENBLAS_NUM_THREADS=2 "$PY" "$P/tools/score_bp.py" "$@" >> "$LOG" 2>&1; }
13
+ n_fail=0
14
+ for ds in immicro ye2026_sepsis ji2025_chili imperial_eskd giroux2022; do
15
+ for j in 0 1 2 3 4; do score "$ds" fewshot "$j" cibersortx || { n_fail=$((n_fail+1)); log "WARN: cibersortx $ds fewshot $j"; }; done
16
+ score "$ds" cv cibersortx || { n_fail=$((n_fail+1)); log "WARN: cibersortx $ds cv"; }
17
+ done
18
+ "$PY" "$P/tools/aggregate_bp.py" cibersortx >> "$LOG" 2>&1 || { n_fail=$((n_fail+1)); log "WARN: aggregate cibersortx"; }
19
+ if [[ -n ${RESCORE_FULL_CV:-} ]]; then
20
+ for ds in $RESCORE_FULL_CV; do score "$ds" cv full || { n_fail=$((n_fail+1)); log "WARN: full $ds cv"; }; done
21
+ "$PY" "$P/tools/aggregate_bp.py" full >> "$LOG" 2>&1 || { n_fail=$((n_fail+1)); log "WARN: aggregate full"; }
22
+ fi
23
+ log "finalize_cx done; failed=$n_fail"
24
+ (( n_fail == 0 ))