junidude14 commited on
Commit
ea9aca2
·
verified ·
1 Parent(s): 382b75f

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261004T051658Z-behcet-c1q-lora3/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/build_dataset.py ADDED
@@ -0,0 +1,195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Behçet LoRA-3 dataset in the paired fine-tuning layout (CPU only).
3
+
4
+ Rows = the 19 bulk PBMC samples of GSE198533 (harmonized order). Three rows have their own sc PBMC library, the pairs
5
+ recovered blind to ages in plans/behcet_pair_recovery_20261004 (out/pairs_recovered.csv): BDV4-PBMC_BD_2,
6
+ BDV5-PBMC_BD_3, BDV6-PBMC_BD_4. Only these three rows have cells; the other 16 rows are generation targets only.
7
+
8
+ Writes data/behcet/ (same files and arithmetic as plans/paired_finetune_intradataset_20260927/tools/prepare_dataset.py,
9
+ whose write_npz and the realbulk condition builder are imported, so the conditions are bit-for-bit what that pipeline
10
+ would produce):
11
+ features.npz bulk_raw, pseudo_raw_sum (0 on rows without sc), bulk_valid, sc_valid, qc_cell_counts, ids, groups
12
+ samples.csv, folds.csv (fold 0 for every row; ft_sdd --train-donors-file then makes the 3 paired rows the training
13
+ set and every other row test), train_donors.txt (BDV4, BDV5, BDV6)
14
+ cells_panel6k.npz, cells_obs.parquet retained cells (flag_conservative_review_pass) of the 3 libraries on the 6k panel
15
+ conditions_raw_fixed.npz every row, real bulk, fixed depth (K = RECIPE_K), cells_per_bulk 5,000
16
+ conditions_cal_fixed.npz every row, bulk x alpha (alpha = gene_multiplier on the 3 pairs), same depth policy
17
+ alpha.npy, BUILD.json
18
+ Output mask: sc_valid = the genes measured in ALL 8 GSE198616 PBMC libraries (they carry two feature tables, 19,826
19
+ and 33,694 features), for every row, so training rows and generation targets share one output space. Counts outside
20
+ it are zeroed in the training cells (count 0 with mask 0 = not measured).
21
+ """
22
+ from __future__ import annotations
23
+
24
+ import hashlib
25
+ import importlib.util
26
+ import json
27
+ import os
28
+ import sys
29
+ from datetime import datetime, timezone
30
+ from pathlib import Path
31
+
32
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
33
+ raise SystemExit("CPU only: run with CUDA_VISIBLE_DEVICES=''")
34
+
35
+ import h5py
36
+ import numpy as np
37
+ import pandas as pd
38
+ import scipy.sparse as sp
39
+
40
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
41
+ PLAN = Path(__file__).resolve().parents[1]
42
+ OUT = PLAN / "data" / "behcet"
43
+ PAIRS = M8 / "plans/behcet_pair_recovery_20261004/out/pairs_recovered.csv"
44
+ DL = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913")
45
+ BULK = DL / "bulk/GSE198533_count/harmonized.h5ad"
46
+ SCDIR = DL / "singlecell/GSE198616"
47
+ INV = DL / "pairing_audit/GSE198616_published_sample_inventory.csv"
48
+ POSITIONS = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/gene_positions.npy"
49
+ POSITIONS_SHA = "653ffa45ac519000baa41086c52408009391d6e68cfb218bc6a50d34163fcb24"
50
+ SELECTED = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv"
51
+ PREP = M8 / "plans/paired_finetune_intradataset_20260927/tools/prepare_dataset.py"
52
+ CELLS_PER_BULK = 5000
53
+ TIERS_USED = ("expression_identity_called_by_primary_rule+age_equal", "expression_best_and_mutual_in_all_rules+age_equal")
54
+
55
+
56
+ def sha(p: Path) -> str:
57
+ h = hashlib.sha256()
58
+ with open(p, "rb") as f:
59
+ for b in iter(lambda: f.read(1 << 22), b""):
60
+ h.update(b)
61
+ return h.hexdigest()
62
+
63
+
64
+ def text(a) -> np.ndarray:
65
+ return np.asarray([x.decode() if isinstance(x, bytes) else str(x) for x in a])
66
+
67
+
68
+ def require(ok: bool, msg: str) -> None:
69
+ if not ok:
70
+ raise SystemExit(msg)
71
+
72
+
73
+ def main() -> int:
74
+ spec = importlib.util.spec_from_file_location("prepare_dataset", PREP)
75
+ PD = importlib.util.module_from_spec(spec)
76
+ sys.modules[spec.name] = PD
77
+ spec.loader.exec_module(PD) # also loads the realbulk condition builder as PD.RB
78
+ RB = PD.RB
79
+ require(sha(POSITIONS) == POSITIONS_SHA, "gene_positions.npy sha differs")
80
+ positions = np.load(POSITIONS).astype(np.int64)
81
+
82
+ import anndata as ad
83
+ b = ad.read_h5ad(BULK)
84
+ gene_ids = b.var_names.to_numpy().astype("U15")
85
+ require(np.array_equal(pd.read_csv(SELECTED).gene_id.to_numpy().astype(str), gene_ids[positions]), "panel ids")
86
+ bX = np.asarray(b.X, dtype=np.float64)
87
+ bulk_valid = np.asarray(b.layers["harmonization_valid"]).astype(bool)
88
+ require(np.isnan(bX[~bulk_valid]).all() and np.array_equal(bX[bulk_valid], np.rint(bX[bulk_valid])), "bulk counts")
89
+ bulk_raw = np.where(bulk_valid, bX, np.nan)
90
+ titles = b.obs_names.to_numpy().astype(str)
91
+ groups = np.where(np.char.startswith(titles, "BD"), "BD", "HC")
92
+ n = len(titles)
93
+
94
+ pairs = pd.read_csv(PAIRS)
95
+ pairs = pairs[pairs.tier.isin(TIERS_USED)].reset_index(drop=True)
96
+ require(len(pairs) == 3, f"expected 3 recovered pairs, got {len(pairs)}")
97
+ inv = pd.read_csv(INV)
98
+ pbmc = inv[inv.source_name == "human PBMC"].gsm.tolist()
99
+ require(len(pbmc) == 8, "8 PBMC libraries")
100
+ # output space: genes measured in all 8 PBMC libraries
101
+ sc_common = np.ones(len(gene_ids), dtype=bool)
102
+ for g in pbmc:
103
+ with h5py.File(SCDIR / g / "pseudobulk_per_published_sample.h5", "r") as f:
104
+ require(np.array_equal(text(f["gene_id"][:]), gene_ids), f"{g}: gene order")
105
+ sc_common &= f["harmonization_valid"][:].astype(bool)
106
+ sc_valid = np.tile(sc_common, (n, 1))
107
+
108
+ pseudo = np.zeros((n, len(gene_ids)))
109
+ qc_n = np.zeros(n, dtype=np.int64)
110
+ row_of = {t: i for i, t in enumerate(titles)}
111
+ blocks, obs_blocks = [], []
112
+ for p in sorted(pairs.itertuples(), key=lambda x: row_of[x.bulk_sample]):
113
+ r = row_of[p.bulk_sample]
114
+ with h5py.File(SCDIR / p.sc_gsm / "canonical.h5ad", "r") as f:
115
+ X = f["X"]
116
+ ncell = len(X["indptr"]) - 1
117
+ full = sp.csr_matrix((X["data"][:], X["indices"][:], X["indptr"][:]), shape=(ncell, len(gene_ids)))
118
+ o = f["obs"]
119
+ keep = o["flag_conservative_review_pass"][:].astype(bool)
120
+ sid = text(o["sample_id"][:])
121
+ bc = text(o["_index"][:])
122
+ require((sid == p.sc_sample).all(), f"{p.sc_gsm}: sample id")
123
+ with h5py.File(SCDIR / p.sc_gsm / "pseudobulk_per_published_sample.h5", "r") as f:
124
+ ref_sum = f["qc_review_pass_cells_sum"][0]
125
+ require(int(f["n_cells"][1, 0]) == int(keep.sum()), f"{p.sc_gsm}: retained-cell count")
126
+ kept = full[np.flatnonzero(keep)].tocsr()
127
+ require(np.array_equal(np.asarray(kept.sum(0)).ravel(), ref_sum), f"{p.sc_gsm}: canonical sum differs")
128
+ kept = kept.multiply(sc_common[None, :]).tocsr() # outside the common space = not measured
129
+ kept.eliminate_zeros()
130
+ pseudo[r] = np.asarray(kept.sum(0)).ravel()
131
+ qc_n[r] = kept.shape[0]
132
+ sub = kept[:, positions].tocsr()
133
+ sub.sort_indices()
134
+ require(np.array_equal(sub.data, np.rint(sub.data)) and (sub.data >= 0).all(), f"{p.sc_gsm}: counts")
135
+ blocks.append(sub.astype(np.int32))
136
+ obs_blocks.append(pd.DataFrame({"barcode": bc[keep], "library_id": p.sc_gsm, "sc_sample": p.sc_sample,
137
+ "sample_id": p.bulk_sample, "donor_id": p.bulk_sample, "group": groups[r],
138
+ "lib_panel": np.asarray(sub.sum(1)).ravel(), "row_sample": np.int32(r)}))
139
+ C = sp.vstack(blocks).tocsr()
140
+ cobs = pd.concat(obs_blocks, ignore_index=True)
141
+ row_sample = cobs.row_sample.to_numpy(np.int32)
142
+ require(bool((np.diff(row_sample) >= 0).all()), "cells grouped by row")
143
+ require(np.array_equal(np.bincount(row_sample, minlength=n), qc_n), "cell counts per row")
144
+
145
+ OUT.mkdir(parents=True, exist_ok=True)
146
+ paired = qc_n > 0
147
+ np.savez_compressed(OUT / "features.npz", gene_ids=gene_ids, sample_ids=titles, donor_ids=titles, groups=groups,
148
+ bulk_raw=bulk_raw, pseudo_raw_sum=np.where(sc_valid, pseudo, np.nan), bulk_valid=bulk_valid,
149
+ sc_valid=sc_valid, qc_cell_counts=qc_n, identity_pass=paired,
150
+ sc_gsm=np.asarray([pairs.set_index("bulk_sample").sc_gsm.get(t, "") for t in titles]))
151
+ np.savez_compressed(OUT / "cells_panel6k.npz", data=C.data, indices=C.indices.astype(np.int32),
152
+ indptr=C.indptr.astype(np.int64), shape=np.array(C.shape, dtype=np.int64),
153
+ row_sample=row_sample, panel_gene_ids=gene_ids[positions], panel_measured=sc_valid[:, positions])
154
+ cobs.to_parquet(OUT / "cells_obs.parquet", index=False)
155
+ pd.DataFrame({"row": np.arange(n), "sample_id": titles, "donor_id": titles, "group": groups,
156
+ "n_cells": qc_n}).to_csv(OUT / "samples.csv", index=False)
157
+ pd.DataFrame({"row": np.arange(n), "sample_id": titles, "donor_id": titles, "group": groups,
158
+ "fold": 0, "inner_val_f0": False}).to_csv(OUT / "folds.csv", index=False)
159
+ (OUT / "train_donors.txt").write_text("".join(t + "\n" for t in titles[paired]))
160
+
161
+ d = {"gene_ids": gene_ids, "sample_ids": titles, "donor_ids": titles, "groups": groups, "sc_valid": sc_valid,
162
+ "n_cells": qc_n}
163
+ bulk0 = np.where(bulk_valid, bX, 0.0)
164
+ raw = RB.to_condition_counts(bulk0, bulk_valid)
165
+ fit = np.flatnonzero(paired)
166
+ valid = bulk_valid[fit].all(0) & sc_common
167
+ alpha = RB.gene_multiplier(bulk0[fit], pseudo[fit], valid)
168
+ cal = RB.to_condition_counts(RB.cpm(bulk0) * alpha[None, :], bulk_valid)
169
+ np.save(OUT / "alpha.npy", alpha)
170
+ rows = np.arange(n)
171
+ files = {"conditions_raw_fixed.npz": PD.write_npz(OUT / "conditions_raw_fixed.npz", d, rows, raw, bulk_valid,
172
+ CELLS_PER_BULK, "raw"),
173
+ "conditions_cal_fixed.npz": PD.write_npz(OUT / "conditions_cal_fixed.npz", d, rows, cal, bulk_valid,
174
+ CELLS_PER_BULK, "cal")}
175
+ for f in ("features.npz", "cells_panel6k.npz", "cells_obs.parquet", "samples.csv", "folds.csv", "train_donors.txt",
176
+ "alpha.npy"):
177
+ files[f] = sha(OUT / f)
178
+ build = {"written_utc": datetime.now(timezone.utc).isoformat(), "rows": n, "paired_rows": titles[paired].tolist(),
179
+ "pairs": pairs.to_dict("records"), "pairs_source": str(PAIRS), "pairs_sha256": sha(PAIRS),
180
+ "cells": int(C.shape[0]), "cells_per_row": dict(zip(titles[paired].tolist(), qc_n[paired].tolist())),
181
+ "sc_common_genes": int(sc_common.sum()), "sc_common_panel_genes": int(sc_common[positions].sum()),
182
+ "recipe_k": int(RB.RECIPE_K), "depth_anchor": float(RB.DEPTH_ANCHOR), "cells_per_bulk": CELLS_PER_BULK,
183
+ "alpha_genes_estimated": int((alpha != 1.0).sum()),
184
+ "inputs": {"bulk": str(BULK), "bulk_sha256": sha(BULK), "sc_dir": str(SCDIR), "prepare_dataset": str(PREP),
185
+ "prepare_dataset_sha256": sha(PREP)},
186
+ "retained_cells_rule": "flag_conservative_review_pass (genes>=200 & UMIs>=500 & mito<=20%)",
187
+ "files": files, "code_sha256": sha(Path(__file__))}
188
+ (OUT / "BUILD.json").write_text(json.dumps(build, indent=1, default=str) + "\n")
189
+ print(json.dumps({k: build[k] for k in ("paired_rows", "cells", "cells_per_row", "sc_common_genes",
190
+ "sc_common_panel_genes", "alpha_genes_estimated")}, indent=1))
191
+ return 0
192
+
193
+
194
+ if __name__ == "__main__":
195
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261004T051658Z-behcet-c1q-lora3/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/run_gpu.sh ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ set -uo pipefail
11
+ export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}"
12
+ export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}"
13
+ M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
14
+ P=$M8/plans/behcet_c1q_lora3_20261004
15
+ FT=$M8/plans/paired_finetune_intradataset_20260927/tools/ft_sdd.py
16
+ S=$M8/plans/aifi_scanvi_rebuild_20260916
17
+ BASE=$M8/runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt
18
+ BASE_SHA=8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633
19
+ PY=/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python
20
+ CPY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
21
+ SPY=/home/sj_server_1/miniforge3/envs/scanvi/bin/python
22
+ DATA=$P/data/behcet
23
+ RUN=$P/runs/lora3
24
+ GEN=$P/generated
25
+ WORK=$P/work
26
+ ARMS=${ARMS:-$P/queues/arms.txt}
27
+ R2=spark-0110
28
+ mkdir -p "$P/logs" "$GEN" "$WORK"
29
+ LOG=$P/logs/run_gpu_$(date +%Y%m%dT%H%M%S).log
30
+ log() { echo "$(date +%FT%T) $*" | tee -a "$LOG"; }
31
+ die() { log "WARN: $*; runner stops"; exit 1; }
32
+ thermal() { until v=$(bash "$M8/plans/floor01_campaign_20260923/tools/thermal_guard.sh"); do sleep 60; done; echo "$v"; }
33
+ cpu() { # cpu NAME CMD... : bounded CPU unit (no GPU), waits for it
34
+ local name=$1; shift
35
+ systemd-run --user --unit="behcet-lora3-$name-$(date +%H%M%S)" --wait --collect --quiet -p MemoryMax=24G \
36
+ -p MemorySwapMax=0 -p CPUQuota=400% -p Nice=10 --working-directory="$P" --setenv=CUDA_VISIBLE_DEVICES= \
37
+ --setenv=PYTHONNOUSERSITE=1 --setenv=OMP_NUM_THREADS=4 --setenv=MKL_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
38
+ -p StandardOutput=append:"$P/logs/$name.log" -p StandardError=append:"$P/logs/$name.log" "$@"
39
+ }
40
+
41
+ [[ "$(sha256sum "$BASE" | cut -d' ' -f1)" == "$BASE_SHA" ]] || die "base checkpoint sha"
42
+ log "runner start; arms $ARMS"
43
+
44
+ # ---- 1. LoRA-3 (fixed 3,000 steps, the LoRA-5 protocol)
45
+ if [[ ! -s $RUN/RUN.json ]]; then
46
+ mkdir -p "$RUN"
47
+ log "--- train lora3 ($(thermal))"
48
+ "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
49
+ OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$FT" --checkpoint "$BASE" --checkpoint-sha "$BASE_SHA" \
50
+ --dataset-dir "$DATA" --condition-npz "$DATA/conditions_raw_fixed.npz" --fold 0 --mode lora --lr 5e-4 \
51
+ --out-dir "$RUN" --train-donors-file "$DATA/train_donors.txt" --fixed-steps 3000 >> "$RUN/train.log" 2>&1 \
52
+ || die "train failed (see $RUN/train.log)"
53
+ 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])")"
54
+ fi
55
+ LORA=$RUN/checkpoint_ft.pt
56
+ LORA_SHA=$(python3 -c "import json;print(json.load(open('$RUN/RUN.json'))['checkpoint_sha256'])")
57
+ [[ "$(sha256sum "$LORA" | cut -d' ' -f1)" == "$LORA_SHA" ]] || die "LoRA checkpoint sha differs from RUN.json"
58
+
59
+ # ---- 2. arms
60
+ while IFS='|' read -r tag which cond seed; do
61
+ [[ -z "${tag// }" || $tag == \#* ]] && continue
62
+ if [[ $which == base ]]; then ck=$BASE; else ck=$LORA; fi
63
+ out=$GEN/$tag.npz; rec=$GEN/$tag.log; err=$GEN/$tag.err
64
+ h5=$WORK/${tag}_poisson.h5ad; lab=$WORK/scanvi_labels_${tag}_f01common
65
+ if [[ -s $rec && ( -s $out || -f $GEN/$tag.moved ) ]]; then
66
+ log "$tag sampled already"
67
+ else
68
+ log "--- sample $tag ckpt=$which seed=$seed ($(thermal))"
69
+ "$HOME/.local/bin/ml-run" /usr/bin/env CUDA_VISIBLE_DEVICES=0 PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
70
+ PYTHONPATH="$M8/src" OMP_NUM_THREADS=4 PYTHONUNBUFFERED=1 "$PY" -u "$M8/scripts/sample_sdd_standalone.py" \
71
+ --checkpoint "$ck" --condition-npz "$cond" --output "$out" --weights ema --batch-size 256 --steps 50 \
72
+ --seed "$seed" --device cuda --conditioner-source embedded --active-logit-threshold 0.0 \
73
+ --support-readout bernoulli > "$rec" 2> "$err" || die "sample $tag failed (see $err)"
74
+ log "$tag sampled: $(python3 -c "import json;d=json.load(open('$rec'));print(d['cells'],'cells', d['output_sha256'][:12])")"
75
+ fi
76
+ if [[ ! -s $h5 ]]; then
77
+ [[ -s $out ]] || die "$tag: NPZ needed for the read-out but not here"
78
+ cpu "readout-$tag" "$CPY" "$S/poisson_readout.py" --npz "$out" --out "$h5" --seed 20260916 \
79
+ --method-name "generated_GSE198533_all19_lora3study_${tag}" --hash-input || die "$tag read-out failed"
80
+ log "$tag read-out done"
81
+ fi
82
+ if [[ ! -s $lab/labels.parquet ]]; then
83
+ systemd-run --user --unit="behcet-lora3-label-$tag-$(date +%H%M%S)" --wait --collect --quiet -p MemoryMax=24G \
84
+ -p MemorySwapMax=0 -p CPUQuota=400% -p Nice=10 --working-directory="$S" --setenv=CUDA_VISIBLE_DEVICES= \
85
+ --setenv=PYTHONNOUSERSITE=1 --setenv=OMP_NUM_THREADS=4 --setenv=MKL_NUM_THREADS=4 --setenv=OPENBLAS_NUM_THREADS=4 \
86
+ -p StandardOutput=append:"$P/logs/label-$tag.log" -p StandardError=append:"$P/logs/label-$tag.log" \
87
+ "$SPY" "$S/predict_scanvi.py" --model-dir "$S/runs/aifi_scanvi_f01common_v1/scanvi_model" --query "$h5" \
88
+ --out-dir "$lab" --device cpu --num-threads 4 --method-name "generated_GSE198533_all19_lora3study_${tag}" \
89
+ --dataset-id GSE198533 --sample-id-col sample_id || die "$tag labelling failed"
90
+ log "$tag labels done"
91
+ fi
92
+ if [[ -s $out ]]; then
93
+ want=$(python3 -c "import json;print(json.load(open('$rec'))['output_sha256'])")
94
+ ssh -n $R2 "mkdir -p '$GEN'" && rsync -a "$out" "$rec" "$err" "$R2:$GEN/" >> "$LOG" 2>&1 || die "$tag: copy to $R2"
95
+ got=$(ssh -n $R2 "sha256sum '$out'" | awk '{print $1}')
96
+ [[ $got == "$want" ]] || die "$tag: sha on $R2 differs"
97
+ 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)"
98
+ rm -f "$out"
99
+ log "$tag NPZ moved to $R2 (sha checked)"
100
+ fi
101
+ done < "$ARMS"
102
+ log "runner finished"
paper-releases/pbisc-diffusion/updates/20261004T051658Z-behcet-c1q-lora3/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/score_arms.sh ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # CPU only. Scores every arm of this study with the earlier Behçet task's wrapper, unchanged
3
+ # (utility_studies_final6k_20260925/behcet/tools/behcet_rules_and_groups.py, which imports analyze_c1q_subset.py
4
+ # read-only): frozen f01common scANVI labels, Poisson read-out seed 20260916, C1Q-high rules D / A / B / C.
5
+ # Gene space: the earlier 5,671-gene shared space intersected with this study's output space (genes measured in all 8
6
+ # GSE198616 PBMC libraries) = work/shared_gene_space_lora3.csv, for every arm, observed included.
7
+ # Observed = GSE198616 PBMC (4 BD vs 4 HC), native depth and binomially thinned to each base arm's monocyte depth.
8
+ set -euo pipefail
9
+ export CUDA_VISIBLE_DEVICES="" OMP_NUM_THREADS=4 MKL_NUM_THREADS=4 OPENBLAS_NUM_THREADS=4
10
+ M8=/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion
11
+ P=$M8/plans/behcet_c1q_lora3_20261004
12
+ B=$M8/plans/utility_studies_final6k_20260925/behcet
13
+ R=$M8/plans/behcet_c1q_repro_20260921
14
+ PY=/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python
15
+ SERIES=/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/datasets/GSE198533/metadata/GSE198533_series_matrix.txt.gz
16
+ INFO=/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/datasets/GSE198616/raw/GSE198616_sample_info.csv.gz
17
+ OBS_H5AD=$R/work/gse198616_pbmc_all8.h5ad
18
+ OBS_LAB=$B/work/scanvi_labels_real_f01common/labels.parquet
19
+ SHARED=$P/work/shared_gene_space_lora3.csv
20
+ $PY - "$R/work/shared_gene_space_genf016k.csv" "$P/data/behcet/conditions_raw_fixed.npz" "$SHARED" <<'EOF'
21
+ import sys, numpy as np, pandas as pd
22
+ sh = pd.read_csv(sys.argv[1]); z = np.load(sys.argv[2], allow_pickle=False)
23
+ out = set(z["gene_ids"].astype(str)[z["output_availability_mask"].all(0)])
24
+ keep = sh[sh.gene_id.astype(str).isin(out)]
25
+ keep.to_csv(sys.argv[3], index=False)
26
+ print(f"shared space: {len(sh)} -> {len(keep)} genes")
27
+ EOF
28
+ ARMS=()
29
+ for tag in zs_raw_s13 zs_cal_s13 lora3_raw_s13 lora3_raw_s04 zs_raw_s04; do
30
+ h5=$P/work/${tag}_poisson.h5ad; lab=$P/work/scanvi_labels_${tag}_f01common/labels.parquet
31
+ [[ -s $h5 && -s $lab ]] || { echo "missing $tag"; exit 1; }
32
+ ARMS+=(--arm "name=$tag,source=generated,h5ad=$h5,labels=$lab,restrict=$SHARED,group=series:$SERIES")
33
+ done
34
+ ARMS+=(--arm "name=obs,source=real,h5ad=$OBS_H5AD,labels=$OBS_LAB,restrict=$SHARED,group=obs:condition,sample_info=$INFO")
35
+ ARMS+=(--arm "name=obs_thin_zs,source=real,h5ad=$OBS_H5AD,labels=$OBS_LAB,restrict=$SHARED,group=obs:condition,sample_info=$INFO,thin_to=zs_raw_s13")
36
+ ARMS+=(--arm "name=obs_thin_lora3,source=real,h5ad=$OBS_H5AD,labels=$OBS_LAB,restrict=$SHARED,group=obs:condition,sample_info=$INFO,thin_to=lora3_raw_s13")
37
+ echo "rules start $(date -Is)"
38
+ $PY $B/tools/behcet_rules_and_groups.py "${ARMS[@]}" --out-dir $P/out/rules_groups
39
+ echo "done $(date -Is)"
paper-releases/pbisc-diffusion/updates/20261004T051658Z-behcet-c1q-lora3/diffusion/dataset/server_1/model8/plans/behcet_c1q_lora3_20261004/tools/summarize.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from pathlib import Path
17
+
18
+ import numpy as np
19
+ import pandas as pd
20
+ from scipy.stats import mannwhitneyu
21
+
22
+ PLAN = Path(__file__).resolve().parents[1]
23
+ OUT = PLAN / "out"
24
+ PAIRS = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/behcet_pair_recovery_20261004/"
25
+ "out/pairs_recovered.csv")
26
+ RULES = ("A", "B", "C", "D")
27
+
28
+
29
+ def gap_row(d: pd.DataFrame, col: str) -> dict:
30
+ bd, hc = d[d.group == "BD"][col].to_numpy(), d[d.group == "HC"][col].to_numpy()
31
+ p = float(mannwhitneyu(bd, hc).pvalue) if len(bd) and len(hc) else np.nan
32
+ return {"n_bd": len(bd), "n_hc": len(hc), "bd_mean_pct": 100 * bd.mean(), "hc_mean_pct": 100 * hc.mean(),
33
+ "gap_pp": 100 * (bd.mean() - hc.mean()), "mw_p": p}
34
+
35
+
36
+ def main() -> int:
37
+ m = pd.read_csv(OUT / "rules_groups/per_sample_group_metrics.csv")
38
+ pairs = pd.read_csv(PAIRS)
39
+ train = set(pairs.bulk_sample)
40
+ rows = []
41
+ for arm, d in m.groupby("arm", sort=False):
42
+ sets = {"observed": d} if arm.startswith("obs") else {"test": d[~d.sample_id.isin(train)], "all": d}
43
+ for sname, s in sets.items():
44
+ for r in RULES:
45
+ rows.append({"arm": arm, "rows": sname, "metric": f"c1q_high_rule_{r}", **gap_row(s, f"c1q_high_fraction_{r}")})
46
+ rows.append({"arm": arm, "rows": sname, "metric": "monocyte_fraction", **gap_row(s, "monocyte_fraction_all_cells")})
47
+ gt = pd.DataFrame(rows)
48
+ gt.to_csv(OUT / "group_table.csv", index=False)
49
+ # in-sample: training donors vs their own observed cells (native and thinned)
50
+ ins = []
51
+ for p in pairs.itertuples():
52
+ for arm, d in m.groupby("arm", sort=False):
53
+ key = p.sc_sample if arm.startswith("obs") else p.bulk_sample
54
+ r = d[d.sample_id == key]
55
+ if len(r):
56
+ r = r.iloc[0]
57
+ ins.append({"donor": p.bulk_sample, "sc_sample": p.sc_sample, "arm": arm,
58
+ "monocyte_fraction_pct": 100 * r.monocyte_fraction_all_cells,
59
+ **{f"c1q_high_{x}_pct": 100 * r[f"c1q_high_fraction_{x}"] for x in RULES}})
60
+ pd.DataFrame(ins).to_csv(OUT / "in_sample.csv", index=False)
61
+ # capability: pooled over all monocytes of the arm (generated: test rows only; observed: all 8 samples)
62
+ cap = []
63
+ for arm, d in m.groupby("arm", sort=False):
64
+ s = d if arm.startswith("obs") else d[~d.sample_id.isin(train)]
65
+ mono = s.n_monocytes.sum()
66
+ cap.append({"arm": arm, "monocytes": int(mono),
67
+ **{f"pooled_rule_{x}_pct": 100 * s[f"n_c1q_high_{x}"].sum() / mono for x in RULES}})
68
+ pd.DataFrame(cap).to_csv(OUT / "capability.csv", index=False)
69
+ summ = {"group_table": gt.round(4).to_dict("records"), "capability": cap, "train_rows": sorted(train)}
70
+ (OUT / "SUMMARY.json").write_text(json.dumps(summ, indent=1, default=float) + "\n")
71
+ with pd.option_context("display.width", 220, "display.max_rows", 500):
72
+ print(gt[gt.metric.isin(["c1q_high_rule_A", "c1q_high_rule_B", "c1q_high_rule_D", "monocyte_fraction"])]
73
+ .round(3).to_string(index=False))
74
+ print(pd.DataFrame(ins).round(2).to_string(index=False))
75
+ print(pd.DataFrame(cap).round(3).to_string(index=False))
76
+ return 0
77
+
78
+
79
+ if __name__ == "__main__":
80
+ raise SystemExit(main())