Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/aggregate_k4000.py +120 -0
- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/annotate_bulkonly.py +135 -0
- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/build_archive_request.py +115 -0
- paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/build_k_conditions.py +178 -0
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/aggregate_k4000.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""LoRA-5 at K = 4,000 vs K = 1,000 on the paired benchmark, over the five few-pair draws (CPU only; 2026-10-06).
|
| 3 |
+
|
| 4 |
+
Reads scores/<ds>/draw<j>/ (tools/score_paired.sh: the benchmark scorer, both arms in one call, the draw's test
|
| 5 |
+
donors) and writes analysis/benchmark/<ds>/{AGGREGATE.md, aggregate.json, per_draw.csv}:
|
| 6 |
+
* per arm, mean +- SD over draws of the benchmark headline metrics (as aggregate_fewshot.py: composition L1,
|
| 7 |
+
precision, coverage, coverage depth-matched, pseudobulk r, monocyte %, top-50 DEG overlap and its broadcast
|
| 8 |
+
analogue) and of the case-vs-control per-cell-type logFC agreement (mean_cp10k, mean of T/B/Mono/NK: r generated,
|
| 9 |
+
r bulk broadcast, partial r given broadcast)
|
| 10 |
+
* paired comparisons over draws (K = 4,000 minus K = 1,000; the same draw = the same training donors and test
|
| 11 |
+
donors) and per donor-draw for composition L1 (Wilcoxon)
|
| 12 |
+
* a scorer check: this plan's lora5 arm against the benchmark's stored draw scores
|
| 13 |
+
(paired_finetune_intradataset_20260927/scores/<ds>/fewshot_n5/draw<j>/summary.json), max |difference|
|
| 14 |
+
usage: CUDA_VISIBLE_DEVICES='' aggregate_k4000.py DATASET
|
| 15 |
+
"""
|
| 16 |
+
from __future__ import annotations
|
| 17 |
+
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 24 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 25 |
+
|
| 26 |
+
import numpy as np
|
| 27 |
+
import pandas as pd
|
| 28 |
+
from scipy.stats import wilcoxon
|
| 29 |
+
|
| 30 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 31 |
+
FT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 32 |
+
ARMS = ("lora5", "lora5_k4000")
|
| 33 |
+
LABEL = {"lora5": "LoRA-5, K = 1,000 (benchmark)", "lora5_k4000": "LoRA-5, K = 4,000"}
|
| 34 |
+
M = ["comp_l1", "precision", "coverage", "coverage_dm", "pb_r_median", "mono_pct_gen", "mono_pct_obs",
|
| 35 |
+
"median_umi_gen", "median_umi_obs", "deg_top50_sum", "deg_top50_sum_broadcast"]
|
| 36 |
+
TYPES4 = ("T cell", "B cell", "Monocyte", "NK cell")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def main(argv=None) -> int:
|
| 40 |
+
ds = (argv or sys.argv[1:])[0]
|
| 41 |
+
root = PLAN / "scores" / ds
|
| 42 |
+
draws = sorted((p for p in root.glob("draw*") if (p / "summary.json").exists()), key=lambda p: int(p.name[4:]))
|
| 43 |
+
rows, per, check = [], [], {}
|
| 44 |
+
for dd in draws:
|
| 45 |
+
s = json.loads((dd / "summary.json").read_text())
|
| 46 |
+
c = pd.read_csv(dd / "contrast.csv")
|
| 47 |
+
c = c[(c.statistic == "mean_cp10k") & c.celltype.isin(TYPES4)]
|
| 48 |
+
for arm in ARMS:
|
| 49 |
+
h = s["headline"][arm]
|
| 50 |
+
ca = c[c.arm == arm]
|
| 51 |
+
rows.append({"draw": int(dd.name[4:]), "arm": arm, **{m: h.get(m) for m in M},
|
| 52 |
+
"logfc_r_gen": float(ca.r_generated.mean()), "logfc_r_broadcast": float(ca.r_broadcast.mean()),
|
| 53 |
+
"logfc_partial_r": float(ca.partial_r_generated_given_broadcast.mean()),
|
| 54 |
+
**{f"logfc_r_{t.split()[0]}": float(ca.loc[ca.celltype == t, "r_generated"].iloc[0])
|
| 55 |
+
for t in TYPES4 if (ca.celltype == t).any()}})
|
| 56 |
+
p = pd.read_csv(dd / "per_donor.csv")
|
| 57 |
+
p["draw"] = int(dd.name[4:])
|
| 58 |
+
per.append(p)
|
| 59 |
+
ref = FT / "scores" / ds / "fewshot_n5" / dd.name / "summary.json"
|
| 60 |
+
if ref.exists():
|
| 61 |
+
rh = json.loads(ref.read_text())["headline"]["lora5"]
|
| 62 |
+
mine = s["headline"]["lora5"]
|
| 63 |
+
diffs = [abs(float(mine[k]) - float(rh[k])) for k in rh if k in mine and k != "seconds"
|
| 64 |
+
and isinstance(rh[k], (int, float)) and isinstance(mine[k], (int, float))
|
| 65 |
+
and np.isfinite(float(rh[k])) and np.isfinite(float(mine[k]))]
|
| 66 |
+
check[dd.name] = {"metrics_compared": len(diffs), "max_abs_diff": max(diffs) if diffs else None}
|
| 67 |
+
df = pd.DataFrame(rows)
|
| 68 |
+
out_dir = PLAN / "analysis" / "benchmark" / ds
|
| 69 |
+
out_dir.mkdir(parents=True, exist_ok=True)
|
| 70 |
+
df.to_csv(out_dir / "per_draw.csv", index=False)
|
| 71 |
+
cols = M + ["logfc_r_gen", "logfc_r_broadcast", "logfc_partial_r"]
|
| 72 |
+
out = {"dataset": ds, "draws": sorted(df.draw.unique().tolist()), "arms": {}, "paired_over_draws": {},
|
| 73 |
+
"scorer_check_vs_benchmark": check}
|
| 74 |
+
lines = [f"# {ds}: LoRA-5 at K = 4,000 vs K = 1,000 on the paired benchmark ({len(draws)} draws)", "",
|
| 75 |
+
"Same five few-pair draws (same 5 training donors each), same test donors, same scorer "
|
| 76 |
+
"(paired_finetune_intradataset_20260927/tools/score_ft.py), 1,500 cells per test sample. Mean ± SD over draws.",
|
| 77 |
+
"", "| metric | " + " | ".join(LABEL[a] for a in ARMS) + " | K4000 − K1000 (draws better / n) |",
|
| 78 |
+
"|---|---:|---:|---|"]
|
| 79 |
+
lower_better = {"comp_l1"}
|
| 80 |
+
closer_better = {"mono_pct_gen": "mono_pct_obs", "median_umi_gen": "median_umi_obs"}
|
| 81 |
+
for m in cols:
|
| 82 |
+
w = df.pivot(index="draw", columns="arm", values=m).astype(float)
|
| 83 |
+
if w[list(ARMS)].isna().all().any():
|
| 84 |
+
continue
|
| 85 |
+
diff = w["lora5_k4000"] - w["lora5"]
|
| 86 |
+
if m in closer_better: # better = closer to the observed value of the same draw's test donors
|
| 87 |
+
o = df.pivot(index="draw", columns="arm", values=closer_better[m]).astype(float)["lora5"]
|
| 88 |
+
better = int(((w["lora5_k4000"] - o).abs() < (w["lora5"] - o).abs()).sum())
|
| 89 |
+
else:
|
| 90 |
+
better = int((diff < 0).sum()) if m in lower_better else int((diff > 0).sum())
|
| 91 |
+
out["paired_over_draws"][m] = {"mean_diff": float(diff.mean()), "draws_better": better, "n": int(diff.notna().sum())}
|
| 92 |
+
for a in ARMS:
|
| 93 |
+
out["arms"].setdefault(a, {})[m] = [float(w[a].mean()), float(w[a].std(ddof=1)) if len(w) > 1 else None]
|
| 94 |
+
cell = " | ".join(f"{w[a].mean():.3f} ± {w[a].std(ddof=1):.3f}" if len(w) > 1 else f"{w[a].mean():.3f}" for a in ARMS)
|
| 95 |
+
tag = "" if m in ("mono_pct_obs", "median_umi_obs", "logfc_r_broadcast", "deg_top50_sum_broadcast") \
|
| 96 |
+
else f"{better} / {int(diff.notna().sum())}"
|
| 97 |
+
lines.append(f"| {m} | {cell} | {diff.mean():+.3f} ({tag}) |" if tag else f"| {m} | {cell} | {diff.mean():+.3f} |")
|
| 98 |
+
pp = pd.concat(per)
|
| 99 |
+
w = pp.pivot_table(index=["draw", "donor"], columns="arm", values="comp_l1")
|
| 100 |
+
x = (w["lora5_k4000"] - w["lora5"]).dropna()
|
| 101 |
+
if len(x) > 0:
|
| 102 |
+
wp = float(wilcoxon(x).pvalue) if (x != 0).any() else float("nan")
|
| 103 |
+
out["comp_l1_per_donor_draw"] = {"mean_diff": float(x.mean()), "frac_k4000_better": float((x < 0).mean()),
|
| 104 |
+
"wilcoxon_p": wp, "n": int(len(x))}
|
| 105 |
+
lines += ["", f"Per donor-draw composition L1, K = 4,000 − K = 1,000: {x.mean():+.4f}; K = 4,000 is better in "
|
| 106 |
+
f"{(x < 0).mean():.0%} of {len(x)} donor-draws (Wilcoxon p {wp:.2g})."]
|
| 107 |
+
lines += ["", "Lower is better for comp_l1; closer to *_obs is better for mono_pct_gen and median_umi_gen; higher is "
|
| 108 |
+
"better for precision, coverage, pseudobulk r, the logFC r values and the top-50 DEG overlap. *_obs and "
|
| 109 |
+
"*broadcast rows are the same for both arms (observed truth / bulk baseline).",
|
| 110 |
+
"", "Scorer check: this plan's K = 1,000 arm vs the benchmark's stored draw scores, max |difference| per draw: "
|
| 111 |
+
+ ", ".join(f"{k} {v['max_abs_diff']:.2g} ({v['metrics_compared']} metrics)" for k, v in check.items()
|
| 112 |
+
if v["max_abs_diff"] is not None) + "."]
|
| 113 |
+
(out_dir / "AGGREGATE.md").write_text("\n".join(lines) + "\n")
|
| 114 |
+
(out_dir / "aggregate.json").write_text(json.dumps(out, indent=1) + "\n")
|
| 115 |
+
print("\n".join(lines))
|
| 116 |
+
return 0
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
if __name__ == "__main__":
|
| 120 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/annotate_bulkonly.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Label the K = 4,000 bulk-only cells of one draw and reduce them to the compact files (CPU only; tools/common.py).
|
| 3 |
+
|
| 4 |
+
Adapted from plans/bulkonly_lora5_20261006/tools/annotate_bulkonly.py (2026-10-06). Differences:
|
| 5 |
+
input the draw's row parts: generated/<ds>/draw<j>/bulkonly_K4000_part<k>.npz + .log receipt, one per part of
|
| 6 |
+
data/<ds>/bulkonly_raw_K4000.PARTS.json; each NPZ sha must equal its receipt, the receipt's condition sha
|
| 7 |
+
the part file, its seed the queue seed (PARTS.json seed + draw x 1,000,003), and every part the checkpoint
|
| 8 |
+
of runs/<ds>/draw<j>/lora_k4000/RUN.json
|
| 9 |
+
read-out ONE Poisson read-out over the whole set (all parts in row order, one generator; common.poisson_over_parts =
|
| 10 |
+
poisson_integerise of the unsplit matrix) with seed 20260916 + draw (common.bulkonly_poisson_seed), so the
|
| 11 |
+
draws do not share read-out noise
|
| 12 |
+
The annotator is unchanged: frozen f01common scANVI (ft_common.run_annotator: predict_scanvi.py, CPU), query genes and
|
| 13 |
+
zero-pad contract of the cohort's scoring reference, sample key "<sample>|generated".
|
| 14 |
+
Output: work/<ds>/bulkonly/draw<j>/{cells.parquet, markers.npz, pb_l2.npz, pb_l1.npz, subsample.npz, RECEIPT.json,
|
| 15 |
+
labels/, predict_scanvi.log}
|
| 16 |
+
usage: CUDA_VISIBLE_DEVICES='' annotate_bulkonly.py DATASET DRAW [--threads 8]
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
import sys
|
| 24 |
+
import time
|
| 25 |
+
from pathlib import Path
|
| 26 |
+
|
| 27 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 28 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 29 |
+
|
| 30 |
+
import numpy as np
|
| 31 |
+
import pandas as pd
|
| 32 |
+
|
| 33 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 34 |
+
import common as C # noqa: E402
|
| 35 |
+
F = C.F
|
| 36 |
+
DRAW_STRIDE = 1_000_003 # tools/make_queue.py
|
| 37 |
+
K = 4000
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def bulkonly_units(ds: str, j: int) -> tuple[list[dict], str]:
|
| 41 |
+
"""The draw's parts in row order with every receipt check done; returns (units, checkpoint sha256)."""
|
| 42 |
+
man = json.loads((C.PLAN / "data" / ds / f"bulkonly_raw_K{K}.PARTS.json").read_text())
|
| 43 |
+
run = json.loads((C.PLAN / "runs" / ds / f"draw{j}" / f"lora_k{K}" / "RUN.json").read_text())
|
| 44 |
+
gdir = C.PLAN / "generated" / ds / f"draw{j}"
|
| 45 |
+
units = []
|
| 46 |
+
for p in man["parts"]:
|
| 47 |
+
npz = gdir / f"bulkonly_K{K}_part{p['part']}.npz"
|
| 48 |
+
cond = C.PLAN / "data" / ds / p["file"]
|
| 49 |
+
rec = json.loads(npz.with_suffix(".log").read_text())
|
| 50 |
+
got = C.sha(npz)
|
| 51 |
+
if got != rec["output_sha256"]:
|
| 52 |
+
raise SystemExit(f"{npz.name}: sha {got[:12]} != receipt {rec['output_sha256'][:12]}")
|
| 53 |
+
if C.sha(cond) != rec.get("condition_sha256") or rec.get("condition_sha256") != p["sha256"]:
|
| 54 |
+
raise SystemExit(f"{npz.name}: receipt condition sha differs from {cond.name} / PARTS.json")
|
| 55 |
+
if int(rec["seed"]) != int(p["seed"]) + j * DRAW_STRIDE:
|
| 56 |
+
raise SystemExit(f"{npz.name}: seed {rec['seed']} != queue seed {int(p['seed']) + j * DRAW_STRIDE}")
|
| 57 |
+
if rec.get("checkpoint_sha256") != run["checkpoint_sha256"]:
|
| 58 |
+
raise SystemExit(f"{npz.name}: checkpoint sha differs from RUN.json")
|
| 59 |
+
units.append({"part": p["part"], "rows": p["rows"], "npz": str(npz), "npz_sha256": got, "condition": str(cond),
|
| 60 |
+
"condition_sha256": rec["condition_sha256"], "seed": int(rec["seed"]),
|
| 61 |
+
"checkpoint": rec.get("checkpoint"), "checkpoint_sha256": rec["checkpoint_sha256"],
|
| 62 |
+
"cells": int(rec["cells"])})
|
| 63 |
+
return units, run["checkpoint_sha256"]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def sample_of_cells(units: list[dict], cells_expected: int) -> np.ndarray:
|
| 67 |
+
out = []
|
| 68 |
+
for u in units:
|
| 69 |
+
d = np.load(u["npz"], allow_pickle=False)
|
| 70 |
+
sid = d["sample_ids"].astype(str)
|
| 71 |
+
bi = d["bulk_index"].astype(np.int64)
|
| 72 |
+
if not (np.bincount(bi, minlength=len(sid)) == cells_expected).all():
|
| 73 |
+
raise SystemExit(f"{u['npz']}: not {cells_expected} cells for every sample")
|
| 74 |
+
out.append(sid[bi])
|
| 75 |
+
return np.concatenate(out)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def main(argv=None) -> int:
|
| 79 |
+
ap = argparse.ArgumentParser()
|
| 80 |
+
ap.add_argument("dataset")
|
| 81 |
+
ap.add_argument("draw", type=int)
|
| 82 |
+
ap.add_argument("--threads", type=int, default=8)
|
| 83 |
+
a = ap.parse_args(argv)
|
| 84 |
+
try:
|
| 85 |
+
from threadpoolctl import threadpool_limits
|
| 86 |
+
threadpool_limits(a.threads)
|
| 87 |
+
except ImportError:
|
| 88 |
+
pass
|
| 89 |
+
t0 = time.monotonic()
|
| 90 |
+
ds, j = a.dataset, a.draw
|
| 91 |
+
units, ck_sha = bulkonly_units(ds, j)
|
| 92 |
+
samples = sample_of_cells(units, 4000)
|
| 93 |
+
meta = pd.read_csv(C.PLAN / "data" / ds / "bulkonly_meta.csv")
|
| 94 |
+
order = pd.unique(samples)
|
| 95 |
+
if list(order) != meta.sample_id.astype(str).tolist():
|
| 96 |
+
raise SystemExit("generated sample order differs from bulkonly_meta.csv")
|
| 97 |
+
ps = C.panel_setup(ds)
|
| 98 |
+
for u in units:
|
| 99 |
+
d = np.load(u["npz"], allow_pickle=False)
|
| 100 |
+
if not np.array_equal(d["gene_ids"].astype(str), ps["panel"]):
|
| 101 |
+
raise SystemExit("NPZ gene_ids differ from the 6k panel")
|
| 102 |
+
seed = C.bulkonly_poisson_seed(j)
|
| 103 |
+
X = C.poisson_over_parts([Path(u["npz"]) for u in units], seed=seed)
|
| 104 |
+
if X.shape[0] != samples.size:
|
| 105 |
+
raise SystemExit("read-out rows differ from the cells")
|
| 106 |
+
ref, man = F.load_reference(F.CACHE_ROOT / ds)
|
| 107 |
+
ppos = {g: i for i, g in enumerate(ps["panel"])}
|
| 108 |
+
qidx = np.asarray([ppos[g] for g in ref["query_ids"].astype(str)], dtype=np.int64)
|
| 109 |
+
work = C.PLAN / "work" / ds / "bulkonly" / f"draw{j}"
|
| 110 |
+
lab, linfo = F.run_annotator(X[:, qidx], list(ref["query_ids"].astype(str)),
|
| 111 |
+
np.asarray([f"{s}|generated" for s in samples], dtype=object), work=work,
|
| 112 |
+
method=f"lora5k4_bulkonly_d{j}", spec=F.DATASETS[ds], split="generated",
|
| 113 |
+
threads=a.threads, annot=F.annotator_run(None),
|
| 114 |
+
expected_zero_pad=man["gene_sets"]["model_genes_missing_from_query"],
|
| 115 |
+
source_note={"kind": "generated_npz_parts", "readout": "poisson", "seed": seed,
|
| 116 |
+
"source_path": ";".join(u["npz"] for u in units),
|
| 117 |
+
"source_sha256": ";".join(u["npz_sha256"] for u in units),
|
| 118 |
+
"poisson_note": "one read-out over all parts in row order, one generator"})
|
| 119 |
+
receipt = {"set": "bulkonly", "version": f"K{K}", "dataset": ds, "draw": j, "generated": units,
|
| 120 |
+
"npz_rows": int(X.shape[0]), "checkpoint_sha256": ck_sha, "poisson_seed": seed,
|
| 121 |
+
"poisson_rule": "one read-out over the whole set (parts in row order, one generator), seed 20260916 + draw",
|
| 122 |
+
"annotation": {k: linfo[k] for k in ("model_pt_sha256", "zero_padded_model_genes", "label_counts",
|
| 123 |
+
"mean_l2_max_prob", "predict_seconds")},
|
| 124 |
+
"tool": str(Path(__file__).resolve()), "tool_sha256": C.sha(Path(__file__)),
|
| 125 |
+
"common_sha256": C.sha(Path(C.__file__))}
|
| 126 |
+
out = C.write_compact(work, X, samples, lab, ps, receipt)
|
| 127 |
+
out["seconds"] = round(time.monotonic() - t0, 1)
|
| 128 |
+
(work / "RECEIPT.json").write_text(json.dumps(out, indent=1, default=str) + "\n")
|
| 129 |
+
print(json.dumps({k: out[k] for k in ("dataset", "draw", "cells", "samples", "seconds")} |
|
| 130 |
+
{"labels_l1": out["annotation"]["label_counts"]}, default=str))
|
| 131 |
+
return 0
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
if __name__ == "__main__":
|
| 135 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/build_archive_request.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""PBISC-Diffusion archive request for one bulk-only LoRA-5 plan (CPU only; 2026-10-06).
|
| 3 |
+
|
| 4 |
+
paper-release-20260928/maintenance/POLICY.md: exact changed assets with provenance; inference outputs as locations
|
| 5 |
+
plus receipts and hashes (never payload); checkpoints as `checkpoint` assets on the host that holds them.
|
| 6 |
+
For PLAN (bulkonly_lora5_20261006 or bulkonly_lora5_k4000_20261006) it lists:
|
| 7 |
+
code tools/*.py, tools/*.sh
|
| 8 |
+
document README.md, share/README.md, analysis/DATA_GUIDE.md, analysis/wf/REPORT_*.md
|
| 9 |
+
report analysis/benchmark/<ds>/AGGREGATE.md, analysis/compare_k1000/<ds>/SUMMARY.md (K = 4,000 plan)
|
| 10 |
+
metadata data/<ds>/*.json, data/<ds>/bulkonly_meta.csv, data/<ds>/paired_test/*.json, queues/*, share/MANIFEST.json,
|
| 11 |
+
share/SHA256SUMS, runs/<ds>/draw<j>/lora_k4000/RUN.json
|
| 12 |
+
condition data/<ds>/*.npz, data/<ds>/paired_test/*.npz
|
| 13 |
+
table analysis/features/<ds>/*, analysis/wf/findings_*.json, analysis/benchmark/<ds>/*.{csv,json},
|
| 14 |
+
analysis/compare_k1000/<ds>/per_feature.csv, scores/<ds>/draw<j>/{summary.json,per_donor.csv,contrast.csv}
|
| 15 |
+
data share_stage/analysis/analysis_bundle.tar.gz (every analysis agent's scripts and tables)
|
| 16 |
+
log logs/*.log, runs/<ds>/draw<j>/lora_k4000/{train.log,history.json}
|
| 17 |
+
checkpoint runs/<ds>/draw<j>/lora_k4000/checkpoint_ft.pt on the host where it exists (sha = RUN.json)
|
| 18 |
+
inference_locations: every generated NPZ with its receipt (sha256, checkpoint, condition, seed), the shared h5ad
|
| 19 |
+
files (sha256 from share/SHA256SUMS) and the R2 share prefix. Only files that exist are listed; nothing is hashed
|
| 20 |
+
twice (receipt sha256 values are taken from the receipts and re-checked here for NPZs on this host).
|
| 21 |
+
usage: build_archive_request.py PLAN_DIR OUT_JSON "summary text"
|
| 22 |
+
"""
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import hashlib
|
| 26 |
+
import json
|
| 27 |
+
import subprocess
|
| 28 |
+
import sys
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
|
| 31 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def sha(p: Path) -> str:
|
| 35 |
+
h = hashlib.sha256()
|
| 36 |
+
with open(p, "rb") as f:
|
| 37 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 38 |
+
h.update(b)
|
| 39 |
+
return h.hexdigest()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def remote_exists(path: Path) -> bool:
|
| 43 |
+
return subprocess.run(["ssh", "-n", "-o", "BatchMode=yes", "spark-0110", f"test -s '{path}'"]).returncode == 0
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def main(argv=None) -> int:
|
| 47 |
+
plan, out, summary = Path(sys.argv[1]).resolve(), Path(sys.argv[2]), sys.argv[3]
|
| 48 |
+
assets, locs = [], []
|
| 49 |
+
|
| 50 |
+
def add(kind: str, paths, host: str = "server_1") -> None:
|
| 51 |
+
for p in sorted(set(paths)):
|
| 52 |
+
if p.is_file() and "__pycache__" not in p.parts and ".bak" not in p.name and not p.name.endswith(".new"):
|
| 53 |
+
assets.append({"host": host, "kind": kind, "source": str(p), "state": "completed"})
|
| 54 |
+
|
| 55 |
+
add("code", list(plan.glob("tools/*.py")) + list(plan.glob("tools/*.sh")))
|
| 56 |
+
add("document", [plan / "README.md", plan / "share/README.md", plan / "analysis/DATA_GUIDE.md",
|
| 57 |
+
*plan.glob("analysis/wf/REPORT_*.md")])
|
| 58 |
+
add("report", list(plan.glob("analysis/benchmark/*/AGGREGATE.md")) + list(plan.glob("analysis/compare_k1000/*/SUMMARY.md")))
|
| 59 |
+
add("metadata", [*plan.glob("data/*/*.json"), *plan.glob("data/*/bulkonly_meta.csv"),
|
| 60 |
+
*plan.glob("data/*/paired_test/*.json"), *plan.glob("queues/*"), plan / "share/MANIFEST.json",
|
| 61 |
+
plan / "share/SHA256SUMS", *plan.glob("runs/*/draw*/lora_k4000/RUN.json")])
|
| 62 |
+
add("condition", list(plan.glob("data/*/*.npz")) + list(plan.glob("data/*/paired_test/*.npz")))
|
| 63 |
+
add("table", [*plan.glob("analysis/features/*/*"), *plan.glob("analysis/wf/findings_*.json"),
|
| 64 |
+
*plan.glob("analysis/benchmark/*/*.csv"), *plan.glob("analysis/benchmark/*/*.json"),
|
| 65 |
+
*plan.glob("analysis/compare_k1000/*/per_feature.csv"),
|
| 66 |
+
*[f for d in plan.glob("scores/*/draw*") for f in (d / "summary.json", d / "per_donor.csv", d / "contrast.csv")]])
|
| 67 |
+
add("data", [plan / "share_stage/analysis/analysis_bundle.tar.gz"])
|
| 68 |
+
add("log", [*plan.glob("logs/*.log"), *plan.glob("runs/*/draw*/lora_k4000/train.log"),
|
| 69 |
+
*plan.glob("runs/*/draw*/lora_k4000/history.json")])
|
| 70 |
+
for rj in sorted(plan.glob("runs/*/draw*/lora_k4000/RUN.json")):
|
| 71 |
+
ck = rj.parent / "checkpoint_ft.pt"
|
| 72 |
+
if ck.is_file():
|
| 73 |
+
if sha(ck) != json.loads(rj.read_text())["checkpoint_sha256"]:
|
| 74 |
+
raise SystemExit(f"{ck}: sha differs from RUN.json")
|
| 75 |
+
assets.append({"host": "server_1", "kind": "checkpoint", "source": str(ck), "state": "completed"})
|
| 76 |
+
elif remote_exists(ck):
|
| 77 |
+
assets.append({"host": "server_2", "kind": "checkpoint", "source": str(ck), "state": "completed"})
|
| 78 |
+
else:
|
| 79 |
+
raise SystemExit(f"{ck}: on neither host")
|
| 80 |
+
for npz in sorted(plan.glob("generated/*/draw*/*.npz")):
|
| 81 |
+
rec_p = npz.with_suffix(".log")
|
| 82 |
+
rec = json.loads(rec_p.read_text())
|
| 83 |
+
if sha(npz) != rec["output_sha256"]:
|
| 84 |
+
raise SystemExit(f"{npz}: sha differs from its receipt")
|
| 85 |
+
ds, draw = npz.parts[-3], npz.parts[-2]
|
| 86 |
+
locs.append({"artifact_role": "inference_output", "experiment": plan.name, "cohort": ds, "draw": draw,
|
| 87 |
+
"host": "server_1", "path": str(npz), "sha256": rec["output_sha256"],
|
| 88 |
+
"output_sha256": rec["output_sha256"], "receipt": str(rec_p),
|
| 89 |
+
"checkpoint": rec.get("checkpoint"), "checkpoint_sha256": rec.get("checkpoint_sha256"),
|
| 90 |
+
"condition_npz": rec.get("condition_npz"), "condition_sha256": rec.get("condition_sha256"),
|
| 91 |
+
"seed": rec.get("seed"), "steps": rec.get("steps"), "cells": rec.get("cells"),
|
| 92 |
+
"state": "completed"})
|
| 93 |
+
sums = {}
|
| 94 |
+
if (plan / "share/SHA256SUMS").exists():
|
| 95 |
+
for line in (plan / "share/SHA256SUMS").read_text().splitlines():
|
| 96 |
+
h, p = line.split(None, 1)
|
| 97 |
+
sums[p.strip()] = h
|
| 98 |
+
for h5 in sorted(plan.glob("share/*/*.h5ad")):
|
| 99 |
+
rel = str(h5.relative_to(plan / "share"))
|
| 100 |
+
locs.append({"artifact_role": "shared_cells_h5ad", "experiment": plan.name, "cohort": h5.parts[-2],
|
| 101 |
+
"host": "server_1", "path": str(h5), "sha256": sums.get(rel) or sha(h5),
|
| 102 |
+
"receipt": str(plan / "share/MANIFEST.json"), "state": "completed"})
|
| 103 |
+
# the R2 share (private bucket) is recorded in the plan README and the request summary: the archive tool takes
|
| 104 |
+
# only server_1 / server_2 locations
|
| 105 |
+
req = {"project_id": "pbisc-diffusion", "summary": summary, "assets": assets, "inference_locations": locs}
|
| 106 |
+
out.write_text(json.dumps(req, indent=1) + "\n")
|
| 107 |
+
kinds = {}
|
| 108 |
+
for a in assets:
|
| 109 |
+
kinds[a["kind"]] = kinds.get(a["kind"], 0) + 1
|
| 110 |
+
print(json.dumps({"assets": len(assets), "by_kind": kinds, "inference_locations": len(locs)}))
|
| 111 |
+
return 0
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20261006T033847Z-bulkonly-lora5-k4000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_k4000_20261006/tools/build_k_conditions.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Real-bulk conditions at recipe size K for the K = 4,000 version of the bulk-only LoRA-5 study (CPU only; 2026-10-06).
|
| 3 |
+
|
| 4 |
+
User request (2026-10-06): after the K = 1,000 version (plans/bulkonly_lora5_20261006), retrain the LoRA-5 models at
|
| 5 |
+
K = 4,000, generate 4,000 cells per bulk-only sample, and share it through R2 like the first version.
|
| 6 |
+
|
| 7 |
+
K is the recipe size of the condition, not a cell number: counts = CPM(bulk on its measured genes) / 1e6 x K x
|
| 8 |
+
DEPTH_ANCHOR and recipe_k = K, i.e. build_realbulk_conditions.to_condition_counts with RECIPE_K replaced by K (as in
|
| 9 |
+
behcet_c1q_lora3_20261004/tools/build_k_conditions.py).
|
| 10 |
+
|
| 11 |
+
Per cohort three condition sets. Each is first rebuilt at K = 1,000 and must equal, byte for byte, the file it is
|
| 12 |
+
derived from (bulk_counts, measurement fraction, recipe_k); otherwise nothing is written.
|
| 13 |
+
training data/<ds>/conditions_raw_fixed_K<K>.npz <- FT data/<ds>/conditions_raw_fixed.npz: every row in folds.csv
|
| 14 |
+
order (what ft_sdd.py --condition-npz needs); bulk = prepare_dataset.load(FT data/<ds>) bulk / bulk_valid
|
| 15 |
+
paired data/<ds>/paired_test/draw<j>_test_raw_K<K>.npz <- FT data/<ds>/fewshot_n5/draw<j>/test_raw.npz: the
|
| 16 |
+
draw's paired test rows (its dataset_rows of the same bulk), 1,500 cells per sample as in the benchmark,
|
| 17 |
+
so the K = 4,000 and K = 1,000 LoRA-5 models are compared at equal cell numbers
|
| 18 |
+
bulk-only data/<ds>/bulkonly_raw_K<K>.npz <- bulkonly_lora5_20261006/data/<ds>/bulkonly_raw.npz: the same samples
|
| 19 |
+
in the same order, --cells-bulkonly cells per sample (4,000); bulk = the harmonized bulk rows read by that
|
| 20 |
+
plan's build_conditions.read_bulk
|
| 21 |
+
Every other key is copied unchanged; recipe_k = K, arm = "raw_K<K>", cells_per_bulk as stated above.
|
| 22 |
+
Also copies bulkonly_meta.csv (sha checked against the first plan's BUILD.json) and writes data/<ds>/K_BUILD.json.
|
| 23 |
+
usage: CUDA_VISIBLE_DEVICES='' build_k_conditions.py DATASET [--k 4000] [--cells-bulkonly 4000]
|
| 24 |
+
"""
|
| 25 |
+
from __future__ import annotations
|
| 26 |
+
|
| 27 |
+
import argparse
|
| 28 |
+
import hashlib
|
| 29 |
+
import importlib.util
|
| 30 |
+
import json
|
| 31 |
+
import os
|
| 32 |
+
import shutil
|
| 33 |
+
import sys
|
| 34 |
+
from datetime import datetime, timezone
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
|
| 37 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 38 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 39 |
+
|
| 40 |
+
import numpy as np
|
| 41 |
+
|
| 42 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 43 |
+
FT = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 44 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 45 |
+
K1 = M8 / "plans/bulkonly_lora5_20261006" # the K = 1,000 version
|
| 46 |
+
sys.path.insert(0, str(FT / "tools"))
|
| 47 |
+
import prepare_dataset as PD # noqa: E402 (load; RB = build_realbulk_conditions)
|
| 48 |
+
RB = PD.RB
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def sha(p: Path) -> str:
|
| 52 |
+
h = hashlib.sha256()
|
| 53 |
+
with open(p, "rb") as f:
|
| 54 |
+
for b in iter(lambda: f.read(1 << 24), b""):
|
| 55 |
+
h.update(b)
|
| 56 |
+
return h.hexdigest()
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def counts_at(expression: np.ndarray, measured: np.ndarray, k: int) -> np.ndarray:
|
| 60 |
+
"""RB.to_condition_counts (fixed depth) with RECIPE_K replaced by k."""
|
| 61 |
+
x = np.where(measured, np.asarray(expression, dtype=np.float64), 0.0)
|
| 62 |
+
return RB.cpm(x) / 1e6 * (k * RB.DEPTH_ANCHOR)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def derive(src: Path, out: Path, counts: np.ndarray, k: int, cells_per_bulk: int | None) -> dict:
|
| 66 |
+
"""Copy every key of src; replace bulk_counts, recipe_k, arm (and cells_per_bulk when given)."""
|
| 67 |
+
base = np.load(src, allow_pickle=True) # donor_ids / groups are object arrays in these files (benchmark format)
|
| 68 |
+
arrays = {key: base[key] for key in base.files}
|
| 69 |
+
if counts.shape != arrays["bulk_counts"].shape:
|
| 70 |
+
raise SystemExit(f"{src.name}: counts shape {counts.shape} != {arrays['bulk_counts'].shape}")
|
| 71 |
+
fr = arrays["bulk_measurement_fraction"]
|
| 72 |
+
if bool((counts[fr == 0] != 0).any()):
|
| 73 |
+
raise SystemExit(f"{out.name}: unmeasured coordinate with a non-zero count")
|
| 74 |
+
arrays["bulk_counts"] = counts
|
| 75 |
+
arrays["recipe_k"] = np.full(len(arrays["recipe_k"]), k, dtype=np.int64)
|
| 76 |
+
arrays["arm"] = np.array(f"raw_K{k}")
|
| 77 |
+
if cells_per_bulk is not None:
|
| 78 |
+
arrays["cells_per_bulk"] = np.full(len(arrays["cells_per_bulk"]), int(cells_per_bulk), dtype=np.int64)
|
| 79 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 80 |
+
np.savez(out, **arrays)
|
| 81 |
+
chk = np.load(out, allow_pickle=True)
|
| 82 |
+
for key in arrays:
|
| 83 |
+
if not np.array_equal(chk[key], arrays[key]):
|
| 84 |
+
raise SystemExit(f"{out.name}: {key} differs after writing")
|
| 85 |
+
return {"file": str(out), "sha256": sha(out), "source": str(src), "source_sha256": sha(src),
|
| 86 |
+
"rows": int(counts.shape[0]), "recipe_k": k,
|
| 87 |
+
"cells_per_bulk": sorted({int(x) for x in arrays["cells_per_bulk"]})}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def main(argv=None) -> int:
|
| 91 |
+
ap = argparse.ArgumentParser()
|
| 92 |
+
ap.add_argument("dataset", choices=("ye2026_sepsis", "imperial_eskd"))
|
| 93 |
+
ap.add_argument("--k", type=int, default=4000)
|
| 94 |
+
ap.add_argument("--cells-bulkonly", type=int, default=4000)
|
| 95 |
+
a = ap.parse_args(argv)
|
| 96 |
+
ds, k = a.dataset, a.k
|
| 97 |
+
if int(RB.RECIPE_K) != 1000:
|
| 98 |
+
raise SystemExit("build_realbulk_conditions.RECIPE_K is not 1000")
|
| 99 |
+
ddir = FT / "data" / ds
|
| 100 |
+
out = PLAN / "data" / ds
|
| 101 |
+
checks, files = {}, {}
|
| 102 |
+
|
| 103 |
+
# ---- training: every row of the dataset
|
| 104 |
+
d = PD.load(ddir)
|
| 105 |
+
ref = np.load(ddir / "conditions_raw_fixed.npz", allow_pickle=True)
|
| 106 |
+
c1 = counts_at(d["bulk"], d["bulk_valid"], 1000)
|
| 107 |
+
checks["training_K1000_equals_conditions_raw_fixed"] = bool(
|
| 108 |
+
np.array_equal(c1, ref["bulk_counts"]) and np.array_equal(c1, RB.to_condition_counts(d["bulk"], d["bulk_valid"]))
|
| 109 |
+
and (ref["recipe_k"] == 1000).all()
|
| 110 |
+
and np.array_equal(d["bulk_valid"].astype(np.float32), ref["bulk_measurement_fraction"]))
|
| 111 |
+
ck = counts_at(d["bulk"], d["bulk_valid"], k)
|
| 112 |
+
|
| 113 |
+
# ---- paired test rows of every draw
|
| 114 |
+
draws = json.loads((ddir / "fewshot_n5" / "DRAWS.json").read_text())["draw"]
|
| 115 |
+
paired = {}
|
| 116 |
+
for j in sorted(draws, key=int):
|
| 117 |
+
src = ddir / "fewshot_n5" / f"draw{j}" / "test_raw.npz"
|
| 118 |
+
t = np.load(src, allow_pickle=True)
|
| 119 |
+
rows = t["dataset_rows"].astype(np.int64)
|
| 120 |
+
ok = (np.array_equal(c1[rows], t["bulk_counts"]) and (t["recipe_k"] == 1000).all()
|
| 121 |
+
and np.array_equal(t["sample_ids"].astype(str), d["sample_ids"][rows])
|
| 122 |
+
and np.array_equal(d["bulk_valid"][rows].astype(np.float32), t["bulk_measurement_fraction"])
|
| 123 |
+
and set(t["cells_per_bulk"].tolist()) == {1500})
|
| 124 |
+
test_ids = [l.strip() for l in (src.parent / "test_samples.txt").read_text().splitlines() if l.strip()]
|
| 125 |
+
ok = ok and sorted(test_ids) == sorted(t["sample_ids"].astype(str).tolist())
|
| 126 |
+
checks[f"paired_draw{j}_K1000_equals_test_raw"] = bool(ok)
|
| 127 |
+
paired[j] = (src, rows)
|
| 128 |
+
|
| 129 |
+
# ---- bulk-only samples (the K = 1,000 plan's file, same order)
|
| 130 |
+
spec = importlib.util.spec_from_file_location("bulkonly_build_conditions", K1 / "tools" / "build_conditions.py")
|
| 131 |
+
BC = importlib.util.module_from_spec(spec)
|
| 132 |
+
spec.loader.exec_module(BC)
|
| 133 |
+
bsrc = K1 / "data" / ds / "bulkonly_raw.npz"
|
| 134 |
+
build1 = json.loads((K1 / "data" / ds / "BUILD.json").read_text())
|
| 135 |
+
if sha(bsrc) != build1["files"]["bulkonly_raw.npz"]:
|
| 136 |
+
raise SystemExit(f"{bsrc} differs from its BUILD.json sha")
|
| 137 |
+
b = np.load(bsrc, allow_pickle=True)
|
| 138 |
+
man = json.loads((ddir / "MANIFEST.json").read_text())
|
| 139 |
+
h5 = Path(man["inputs"]["bulk_harmonized"]["path"])
|
| 140 |
+
if sha(h5) != man["inputs"]["bulk_harmonized"]["sha256"] or str(h5) != build1["bulk_harmonized"]["path"]:
|
| 141 |
+
raise SystemExit(f"{h5}: differs from MANIFEST.json / the first plan's BUILD.json")
|
| 142 |
+
order = b["sample_ids"].astype(str).tolist()
|
| 143 |
+
Xb, Vb = BC.read_bulk(h5, order, d["gene_ids"])
|
| 144 |
+
b1 = counts_at(Xb, Vb, 1000)
|
| 145 |
+
checks["bulkonly_K1000_equals_bulkonly_raw"] = bool(
|
| 146 |
+
np.array_equal(b1, b["bulk_counts"]) and np.array_equal(b1, RB.to_condition_counts(Xb, Vb))
|
| 147 |
+
and (b["recipe_k"] == 1000).all() and np.array_equal(Vb.astype(np.float32), b["bulk_measurement_fraction"]))
|
| 148 |
+
bad = [key for key, v in checks.items() if v is not True]
|
| 149 |
+
if bad:
|
| 150 |
+
raise SystemExit(f"checks failed: {bad}")
|
| 151 |
+
|
| 152 |
+
files["training"] = derive(ddir / "conditions_raw_fixed.npz", out / f"conditions_raw_fixed_K{k}.npz", ck, k, None)
|
| 153 |
+
files["paired"] = {}
|
| 154 |
+
for j, (src, rows) in paired.items():
|
| 155 |
+
files["paired"][j] = derive(src, out / "paired_test" / f"draw{j}_test_raw_K{k}.npz", ck[rows], k, 1500)
|
| 156 |
+
files["bulkonly"] = derive(bsrc, out / f"bulkonly_raw_K{k}.npz", counts_at(Xb, Vb, k), k, a.cells_bulkonly)
|
| 157 |
+
meta_src = K1 / "data" / ds / "bulkonly_meta.csv"
|
| 158 |
+
if sha(meta_src) != build1["files"]["bulkonly_meta.csv"]:
|
| 159 |
+
raise SystemExit(f"{meta_src} differs from its BUILD.json sha")
|
| 160 |
+
shutil.copy2(meta_src, out / "bulkonly_meta.csv")
|
| 161 |
+
files["bulkonly_meta.csv"] = {"file": str(out / "bulkonly_meta.csv"), "sha256": sha(out / "bulkonly_meta.csv"),
|
| 162 |
+
"source": str(meta_src)}
|
| 163 |
+
rec = {"dataset": ds, "k": k, "cells_per_bulk": {"training": "unchanged (not used by ft_sdd.py)", "paired": 1500,
|
| 164 |
+
"bulkonly": a.cells_bulkonly},
|
| 165 |
+
"written_utc": datetime.now(timezone.utc).isoformat(), "tool": str(Path(__file__).resolve()),
|
| 166 |
+
"tool_sha256": sha(Path(__file__)), "builder": str(PD.BUILDER), "builder_sha256": sha(Path(PD.BUILDER)),
|
| 167 |
+
"prepare_dataset_sha256": sha(FT / "tools/prepare_dataset.py"),
|
| 168 |
+
"first_plan_build_conditions_sha256": sha(K1 / "tools" / "build_conditions.py"),
|
| 169 |
+
"depth_anchor": float(RB.DEPTH_ANCHOR), "checks": checks, "files": files}
|
| 170 |
+
(out / "K_BUILD.json").write_text(json.dumps(rec, indent=1, default=str) + "\n")
|
| 171 |
+
print(json.dumps({"dataset": ds, "k": k, "checks": checks,
|
| 172 |
+
"rows": {"training": files["training"]["rows"], "bulkonly": files["bulkonly"]["rows"],
|
| 173 |
+
"paired": {j: v["rows"] for j, v in files["paired"].items()}}}, indent=1))
|
| 174 |
+
return 0
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
if __name__ == "__main__":
|
| 178 |
+
sys.exit(main())
|