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

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/aggregate_bp.py ADDED
@@ -0,0 +1,131 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Tables of BayesPrism vs LoRA on the paired benchmark (CPU only; 2026-10-06). Reads results/<ds>/*/summary.json.
3
+
4
+ results/TABLE_fewshot.csv / TABLE_cv.csv and RESULTS.md:
5
+ fewshot per cohort, mean +- SD over the five draws: composition L1 (BayesPrism final and first theta in cell units,
6
+ LoRA-5, zero-shot cal), case-vs-control logFC r (mean_cp10k, T/B/Mono/NK mean; BayesPrism Z zero-filled and
7
+ on its covered genes, LoRA-5, bulk broadcast), partial r beyond the broadcast, top-50 DEG overlap (sum over
8
+ types); draws where LoRA beats BayesPrism
9
+ cv per cohort, pooled 5-fold: the same for BayesPrism (reference = each fold's LoRA training pairs), LoRA
10
+ real_lora__raw and, where finished, scSemiProfiler on the same pairs (scsemi__raw)
11
+ usage: aggregate_bp.py
12
+ """
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import sys
17
+ from pathlib import Path
18
+
19
+ import numpy as np
20
+ import pandas as pd
21
+
22
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
23
+ import common as C # noqa: E402
24
+
25
+ LABEL = {"immicro": "ImMicro", "ye2026_sepsis": "Sepsis", "ji2025_chili": "Ji ChILI", "imperial_eskd": "Imperial",
26
+ "giroux2022": "Giroux"}
27
+
28
+
29
+ def row(s: dict) -> dict:
30
+ b, l, br = s["bayesprism"], s["lora"], dict(s.get("broadcast") or {})
31
+ b, l = dict(b), dict(l)
32
+ for d_ in (b, l, br):
33
+ for k in ("logfc_r_mean_cp10k", "logfc_r_mean_cp10k_covered_genes", "partial_r_mean_cp10k", "deg_top50_sum"):
34
+ d_.setdefault(k, np.nan)
35
+ v = b["comp_l1_by_variant"]
36
+ r = {"bp_l1_final": v["final_cells"], "bp_l1_first": v["first_cells"], "lora_l1": l["comp_l1"],
37
+ "bp_r": b["logfc_r_mean_cp10k"], "bp_r_covered": b["logfc_r_mean_cp10k_covered_genes"],
38
+ "lora_r": l["logfc_r_mean_cp10k"], "broadcast_r": br["logfc_r_mean_cp10k"],
39
+ "broadcast_r_covered": br["logfc_r_mean_cp10k_covered_genes"],
40
+ "bp_partial": b["partial_r_mean_cp10k"], "lora_partial": l["partial_r_mean_cp10k"],
41
+ "bp_deg": b["deg_top50_sum"], "lora_deg": l["deg_top50_sum"], "broadcast_deg": br["deg_top50_sum"]}
42
+ r = {k: (np.nan if v is None else v) for k, v in r.items()}
43
+ zc = s["other_arms"].get("zs_cal")
44
+ if zc:
45
+ r["zs_cal_l1"], r["zs_cal_r"], r["zs_cal_deg"] = zc["comp_l1"], zc["logfc_r_mean_cp10k"], zc["deg_top50_sum"]
46
+ for k, x in (s.get("scsemi_cv") or {}).items():
47
+ r["scsemi_l1"], r["scsemi_r"], r["scsemi_deg"] = x["comp_l1"], x["logfc_r_mean_cp10k"], x["deg_top50_sum"]
48
+ break
49
+ return r
50
+
51
+
52
+ def fmt(x: pd.Series, d: int = 3) -> str:
53
+ x = x.dropna()
54
+ if x.empty:
55
+ return "–"
56
+ return f"{x.mean():.{d}f} ± {x.std(ddof=1):.{d}f}" if len(x) > 1 else f"{x.mean():.{d}f}"
57
+
58
+
59
+ def main(argv=None) -> int:
60
+ mode = (argv or sys.argv[1:] or ["full"])[0] # full (BayesPrism's recommended genes, main) | score
61
+ sfx = C.suffix(mode)
62
+ res = C.PLAN / "results"
63
+ fs, cv = [], []
64
+ for ds in C.COHORTS:
65
+ for j in range(5):
66
+ f = res / ds / f"fewshot_draw{j}{sfx}" / "summary.json"
67
+ if f.exists():
68
+ s = json.loads(f.read_text())
69
+ fs.append({"cohort": ds, "draw": s["draw"], **row(s)})
70
+ f = res / ds / f"cv_pooled{sfx}" / "summary.json"
71
+ if f.exists():
72
+ cv.append({"cohort": ds, **row(json.loads(f.read_text()))})
73
+ fs, cv = pd.DataFrame(fs), pd.DataFrame(cv)
74
+ fs.to_csv(res / f"TABLE_fewshot{sfx}.csv", index=False)
75
+ cv.to_csv(res / f"TABLE_cv{sfx}.csv", index=False)
76
+ gene_note = {"full": "BayesPrism genes: its recommended set (canonical protein-coding minus chrX/Y/M and RPS/RPL/MRPS/MRPL, "
77
+ "measured by the sc assay; 15-19k genes).",
78
+ "score": "BayesPrism genes: the scorer's ~5.5-6k scoring genes only (sensitivity run; handicaps composition).",
79
+ "cibersortx": "CIBERSORTx in place of BayesPrism ('BP' columns): official Docker Fractions, single-cell reference "
80
+ "(<=400 cells per type from the same paired donors) with S-mode batch correction, then HiRes "
81
+ "per-sample cell-type expression on the scoring genes (tools/run_cibersortx.sh). One fraction "
82
+ "estimate, so 'final' = 'first'. HiRes needs more samples than cell types: splits with <= 8 "
83
+ "test samples (Ji and Giroux CV folds) have composition only."}[mode]
84
+ meth = "CIBERSORTx" if mode == "cibersortx" else "BayesPrism"
85
+ lines = [f"# {meth} with the same paired donors vs LoRA (paired benchmark; gene mode {mode})", "", gene_note, "",
86
+ "Same donors, observed truth, contrast and scorer as the benchmark (score_ft.py functions; the recomputed "
87
+ "bulk broadcast equals the stored one in every split). BayesPrism reference = the split's paired donors' "
88
+ "observed cells (states = gate | AIFI L2); mixture = the test samples' real bulk. Composition L1 in cell "
89
+ "units (lower is better): 'final' and 'first' BayesPrism theta. logFC r = case-vs-control per-type "
90
+ "logFC (mean CP10K) correlation with observed, mean of T/B/Mono/NK; BayesPrism Z zero-filled on genes "
91
+ "it lacks ('covered' = only genes it models, broadcast recomputed there). DEG = top-50 overlap summed "
92
+ "over types.", "", "## Five-donor draws (mean ± SD over 5 draws)", "",
93
+ "| cohort | L1 BP final | L1 BP first | L1 LoRA-5 | r BP | r BP (covered) | r LoRA-5 | r broadcast | "
94
+ "partial r BP | partial r LoRA-5 | DEG BP | DEG LoRA-5 | DEG broadcast |",
95
+ "|---|" + "---:|" * 12]
96
+ for ds in C.COHORTS:
97
+ g = fs[fs.cohort == ds]
98
+ if g.empty:
99
+ continue
100
+ lines.append(f"| {LABEL[ds]} ({len(g)}) | " + " | ".join(
101
+ fmt(g[c], 1 if "deg" in c else 3) for c in ("bp_l1_final", "bp_l1_first", "lora_l1", "bp_r", "bp_r_covered",
102
+ "lora_r", "broadcast_r", "bp_partial", "lora_partial", "bp_deg",
103
+ "lora_deg", "broadcast_deg")) + " |")
104
+ if not fs.empty:
105
+ best_bp_l1 = fs[["bp_l1_final", "bp_l1_first"]].min(1)
106
+ def cnt(a, b, lower=False):
107
+ m = fs[a].notna() & b.notna() if isinstance(b, pd.Series) else fs[a].notna() & fs[b].notna()
108
+ bb = b if isinstance(b, pd.Series) else fs[b]
109
+ win = (fs[a] < bb) if lower else (fs[a] > bb)
110
+ return f"{int((win & m).sum())}/{int(m.sum())}"
111
+ lines += ["", f"Draws where LoRA-5 beats {meth}: composition " + cnt("lora_l1", best_bp_l1, lower=True)
112
+ + f" (vs {meth}'s better theta), logFC r " + cnt("lora_r", "bp_r") + ", partial r "
113
+ + cnt("lora_partial", "bp_partial") + ", top-50 DEG " + cnt("lora_deg", "bp_deg")
114
+ + f" (ties {int(((fs.lora_deg == fs.bp_deg) & fs.lora_deg.notna()).sum())})."]
115
+ lines += ["", f"## 5-fold CV, pooled ({meth} reference = each fold's LoRA training + inner-validation pairs)", "",
116
+ "| cohort | L1 BP final | L1 BP first | L1 LoRA | L1 scSemi | r BP | r BP (covered) | r LoRA | r scSemi | "
117
+ "r broadcast | partial r BP | partial r LoRA | DEG BP | DEG LoRA | DEG scSemi | DEG broadcast |",
118
+ "|---|" + "---:|" * 15]
119
+ for _, r in cv.iterrows():
120
+ g = lambda c, d=3: (f"{r[c]:.{d}f}" if c in r and pd.notna(r[c]) else "–") # noqa: E731
121
+ lines.append(f"| {LABEL[r.cohort]} | " + " | ".join(
122
+ [g("bp_l1_final"), g("bp_l1_first"), g("lora_l1"), g("scsemi_l1"), g("bp_r"), g("bp_r_covered"), g("lora_r"),
123
+ g("scsemi_r"), g("broadcast_r"), g("bp_partial"), g("lora_partial"), g("bp_deg", 0), g("lora_deg", 0),
124
+ g("scsemi_deg", 0), g("broadcast_deg", 0)]) + " |")
125
+ (res / f"RESULTS{sfx}.md").write_text("\n".join(lines) + "\n")
126
+ print("\n".join(lines))
127
+ return 0
128
+
129
+
130
+ if __name__ == "__main__":
131
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/build_aggregates.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Per sample x reference state summed UMI on the BayesPrism gene axis, for every observed cell of one cohort
3
+ (CPU only; 2026-10-06). Every split's reference is a sum of these rows, so the 7 GB cell matrix is read once.
4
+
5
+ Inputs (read only): FT data/<ds>/cells_full.npz (CSR raw UMI, cells x 20,097 canonical genes, row_sample = dataset
6
+ row), data/<ds>/features.npz (gene_ids, sample_ids), the benchmark's observed labels
7
+ (scoring_cache/<ds>/observed_labels/labels/labels.parquet, npz_row aligned with the cell matrix; the scorer's own
8
+ observed composition comes from the same celltype_l1_pred).
9
+ Output data/<ds>/aggregates.npz: sums [samples, states, genes] float64, n_cells [samples, states], sample_ids, states
10
+ ("<celltype_l1_pred>|<aifi_l2>"), state_types, gene_ids (common.bp_genes order); plus AGGREGATES.json (shas, checks).
11
+ Gene modes: score (default; common.bp_genes -> aggregates.npz) or full (common.full_genes, BayesPrism's recommended
12
+ cleaned axis -> aggregates_full.npz).
13
+ usage: CUDA_VISIBLE_DEVICES='' build_aggregates.py DATASET [score|full]
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ import os
19
+ import sys
20
+ import time
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
+ import scipy.sparse as sp
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
31
+ import common as C # noqa: E402
32
+
33
+
34
+ def main(argv=None) -> int:
35
+ args = argv or sys.argv[1:]
36
+ ds, mode = args[0], (args[1] if len(args) > 1 else "score")
37
+ t0 = time.monotonic()
38
+ dd = C.FT / "data" / ds
39
+ feat = np.load(dd / "features.npz", allow_pickle=False)
40
+ gene_ids = feat["gene_ids"].astype(str)
41
+ sample_ids = feat["sample_ids"].astype(str) if "sample_ids" in feat.files else feat["donor_ids"].astype(str)
42
+ genes = C.genes_for(ds, mode)
43
+ gpos = {g: i for i, g in enumerate(gene_ids)}
44
+ cols = np.asarray([gpos[g] for g in genes], dtype=np.int64)
45
+ z = np.load(dd / "cells_full.npz", allow_pickle=False)
46
+ shape = tuple(int(x) for x in z["shape"])
47
+ if shape[1] != gene_ids.size:
48
+ raise SystemExit("cells_full gene axis differs from features.npz")
49
+ row_sample = z["row_sample"].astype(np.int64)
50
+ lpath = C.FT / "scoring_cache" / ds / "observed_labels" / "labels" / "labels.parquet"
51
+ if lpath.exists(): # the scorer's own observed labels, npz_row-aligned with the cell matrices
52
+ lab = pd.read_parquet(lpath, columns=["sample_id", "celltype_l1_pred", "aifi_l2", "npz_row"])
53
+ if len(lab) != shape[0] or not (lab.npz_row.to_numpy() == np.arange(shape[0])).all():
54
+ raise SystemExit("observed labels are not row-aligned with cells_full.npz")
55
+ if not np.array_equal(sample_ids[row_sample], lab.sample_id.astype(str).to_numpy()):
56
+ raise SystemExit("cells_full row_sample disagrees with the labels' sample_id")
57
+ else: # ImMicro: the published frozen labels joined on cell_index (ft_common.immicro_frozen_labels)
58
+ man = json.loads((C.FT / "scoring_cache" / ds / "reference_manifest.json").read_text())
59
+ lpath = Path(man["labels"]["source"])
60
+ if C.sha(lpath) != man["labels"]["sha256"]:
61
+ raise SystemExit(f"{lpath}: sha differs from the scorer's reference manifest")
62
+ obs = pd.read_parquet(dd / "cells_obs.parquet", columns=["cell_index", "donor_id"])
63
+ if len(obs) != shape[0]:
64
+ raise SystemExit("cells_obs.parquet rows differ from cells_full.npz")
65
+ lab = pd.read_parquet(lpath, columns=["cell_index", "celltype_l1_pred", "aifi_l2"]).set_index("cell_index")
66
+ lab = lab.reindex(obs.cell_index.to_numpy())
67
+ if lab.celltype_l1_pred.isna().any():
68
+ raise SystemExit(f"{int(lab.celltype_l1_pred.isna().sum())} observed cells without a frozen label")
69
+ lab = lab.reset_index(drop=True)
70
+ # ImMicro's dataset rows are donors (features.npz donor_ids); cells_obs sample_id is the library name
71
+ if not np.array_equal(sample_ids[row_sample], obs.donor_id.astype(str).to_numpy()):
72
+ raise SystemExit("cells_full row_sample disagrees with cells_obs.parquet donor_id")
73
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=shape)
74
+ del z
75
+ X = X[:, cols].tocsr().astype(np.float64)
76
+ states_cell = (lab.celltype_l1_pred.astype(str) + "|" + lab.aifi_l2.astype(str)).to_numpy()
77
+ states = np.asarray(sorted(set(states_cell)))
78
+ st_idx = pd.Index(states).get_indexer(states_cell)
79
+ n_s, n_t = sample_ids.size, states.size
80
+ grp = row_sample * n_t + st_idx
81
+ G = sp.csr_matrix((np.ones(grp.size), (grp, np.arange(grp.size))), shape=(n_s * n_t, grp.size))
82
+ sums = (G @ X).toarray().reshape(n_s, n_t, cols.size)
83
+ n_cells = np.bincount(grp, minlength=n_s * n_t).reshape(n_s, n_t)
84
+ if not np.isclose(sums.sum(), X.sum()):
85
+ raise SystemExit("aggregate total differs from the cell matrix total")
86
+ state_types = np.asarray([s.split("|", 1)[0] for s in states])
87
+ out = C.PLAN / "data" / ds
88
+ out.mkdir(parents=True, exist_ok=True)
89
+ agg = out / f"aggregates{C.suffix(mode)}.npz"
90
+ np.savez_compressed(agg, sums=sums, n_cells=n_cells, sample_ids=sample_ids, states=states,
91
+ state_types=state_types, gene_ids=genes)
92
+ rec = {"dataset": ds, "cells": int(shape[0]), "samples": int(n_s), "states": int(n_t), "genes": int(cols.size),
93
+ "scoring_genes": int(np.load(C.FT / "scoring_cache" / ds / "reference.npz")["score_ids"].size),
94
+ "cells_full": str(dd / "cells_full.npz"), "cells_full_sha256": C.sha(dd / "cells_full.npz"),
95
+ "labels": str(lpath), "labels_sha256": C.sha(lpath), "gene_mode": mode, "aggregates_sha256": C.sha(agg),
96
+ "tool_sha256": C.sha(Path(__file__)), "common_sha256": C.sha(Path(C.__file__)),
97
+ "seconds": round(time.monotonic() - t0, 1)}
98
+ (out / f"AGGREGATES{C.suffix(mode)}.json").write_text(json.dumps(rec, indent=1) + "\n")
99
+ print(json.dumps(rec))
100
+ return 0
101
+
102
+
103
+ if __name__ == "__main__":
104
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/build_archive_request.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Archive-maintenance request (paper-release-20260928/maintenance/POLICY.md, project pbisc-diffusion) for the
3
+ 2026-10-08 deconvolution + scSemiProfiler update. CPU only; reads files, writes the request and one manifest.
4
+
5
+ Payload (server_1):
6
+ this plan tools, README, results/ (tables, summaries, RESULTS*.md), logs (credential-free; checked by count),
7
+ small inputs metadata (SPLIT.json, state_types.tsv, AGGREGATES*.json, INPUT.json, hires_genes.txt),
8
+ BayesPrism theta + genes_used (both gene modes), CIBERSORTx fractions / signature / phenoclasses /
9
+ run logs
10
+ paired FT new scSemiProfiler score units (Giroux and sepsis 5-fold, sepsis equal budget, Giroux without
11
+ sex-linked genes, contrast and realism extras) and today's finalize / scoring logs
12
+ deck every deck file; unchanged ones are skipped by update.py (same sha already archived)
13
+ Large outputs kept in place, listed with bytes + sha256 in results/LARGE_OUTPUTS_SHA256.tsv (archived): BayesPrism Z
14
+ (full mode), CIBERSORTx HiRes, source GEPs, S-mode adjusted mixtures, inferred reference copies, per-state aggregates.
15
+ Inference locations: the pooled scSemiProfiler NPZs (receipt = POOL_MANIFEST.json); fold NPZs are registered already.
16
+ usage: build_archive_request.py OUT.json
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import glob
21
+ import hashlib
22
+ import json
23
+ import sys
24
+ from pathlib import Path
25
+
26
+ P = Path(__file__).resolve().parents[1]
27
+ FT = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
28
+ DECK = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/presentations/"
29
+ "2026-09-30--paper-summary--r00")
30
+ LARGE_CX = ("CIBERSORTx_refsample_inferred_refsample.txt", "CIBERSORTx_Mixtures_Adjusted.txt",
31
+ "CIBERSORTx_cell_type_sourceGEP.txt")
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 << 22), b""):
38
+ h.update(b)
39
+ return h.hexdigest()
40
+
41
+
42
+ def files(root: Path, patterns, exclude=lambda p: False):
43
+ out = set()
44
+ for pat in patterns:
45
+ for f in glob.glob(str(root / pat), recursive=True):
46
+ q = Path(f)
47
+ if q.is_file() and not q.is_symlink() and "__pycache__" not in q.parts and not exclude(q):
48
+ out.add(q)
49
+ return sorted(out)
50
+
51
+
52
+ def main(out: str) -> int:
53
+ assets = []
54
+
55
+ def add(paths, kind):
56
+ for p in paths:
57
+ assets.append({"host": "server_1", "source": str(p), "kind": kind, "state": "completed"})
58
+
59
+ # ---- large outputs: manifest only
60
+ large = (files(P, ["inputs/*/*_full/bp/Z_type_*.tsv.gz", "cibersortx/*/*/out_hires/CIBERSORTxHiRes_*.txt",
61
+ "data/*/aggregates*.npz"])
62
+ + [q for n in LARGE_CX for q in files(P, [f"cibersortx/*/*/out_fractions/{n}"])])
63
+ man = P / "results" / "LARGE_OUTPUTS_SHA256.tsv"
64
+ man.write_text("path\tbytes\tsha256\n" + "".join(f"{q.relative_to(P)}\t{q.stat().st_size}\t{sha(q)}\n" for q in large))
65
+ # ---- this plan
66
+ add(files(P, ["tools/*.py", "tools/*.sh", "tools/*.R"]), "code")
67
+ add(files(P, ["README.md"]), "document")
68
+ add(files(P, ["results/**/*.csv", "results/**/*.json", "results/*.tsv"]), "table")
69
+ add(files(P, ["results/*.md"]), "report")
70
+ add(files(P, ["logs/*.log"]), "log")
71
+ add(files(P, ["inputs/*/*/SPLIT.json", "inputs/*/*/state_types.tsv", "data/*/AGGREGATES*.json",
72
+ "cibersortx/*/*/INPUT.json", "cibersortx/*/*/hires_genes.txt"]), "metadata")
73
+ add(files(P, ["inputs/*/*/bp/theta_*.csv", "inputs/*/*/bp/genes_used.txt"]), "data")
74
+ add(files(P, ["cibersortx/*/*/out_fractions/CIBERSORTx_Adjusted.txt",
75
+ "cibersortx/*/*/out_fractions/CIBERSORTx_sigmatrix_Adjusted.txt",
76
+ "cibersortx/*/*/out_fractions/CIBERSORTx_refsample_inferred_phenoclasses*.txt",
77
+ "cibersortx/*/*/out_hires/fractions_results.txt"]), "data")
78
+ add(files(P, ["cibersortx/*/*/out_fractions/.run.log", "cibersortx/*/*/hires_run.log"]), "log")
79
+ # ---- paired fine-tuning plan: new scSemiProfiler units
80
+ units = ["scores/giroux2022/scsemi_cv_20261002", "scores_nosex/giroux2022/scsemi_cv_20261002",
81
+ "scores/ye2026_sepsis/scsemi_cv_20261002", "scores/ye2026_sepsis/scsemi_budget_20261002",
82
+ "scores_contrast/ye2026_sepsis/scsemi_cv_20261002", "scores_contrast/giroux2022/scsemi_cv_20261002"] + \
83
+ [f"scores_extra/{d}/scsemi_cv_20261002" for d in ("immicro", "ye2026_sepsis", "ji2025_chili", "giroux2022")]
84
+ for u in units:
85
+ fs = files(FT, [f"{u}/**/*"])
86
+ add([q for q in fs if q.suffix in (".csv", ".json", ".tsv", ".parquet")], "table")
87
+ add([q for q in fs if q.suffix == ".md"], "report")
88
+ add(files(FT, ["logs/finalize_scsemi_*server1_20261008*.log", "logs/score-giroux2022-scsemi_cv_20261002-*_20261008*.log",
89
+ "logs/score-ye2026_sepsis-scsemi_budget_20261002-*_20261008*.log", "logs/pool-*_20261008*.log",
90
+ "logs/scores_nosex-giroux2022-scsemi_cv-pooled_20261008*.log", "logs/extra-scsemi-cv_20261008*.log",
91
+ "scores_contrast/_logs/cx-sepsis-giroux-scsemi-cv_20261008*.log"]), "log")
92
+ # ---- deck
93
+ add(files(DECK, ["*.pptx", "*.pdf"]), "report")
94
+ add(files(DECK, ["README.md"]), "document")
95
+ add(files(DECK, ["generate_deck.py", "tools/*.py"]), "code")
96
+ add(files(DECK, ["figures/*.png", "figures/*.pdf", "figures/*.svg"]), "figure")
97
+ add(files(DECK, ["data/*.csv"]), "table")
98
+ add(files(DECK, ["data/*.json"]), "config")
99
+ # ---- inference locations: pooled scSemiProfiler NPZs
100
+ locs = []
101
+ for ds, sub in (("giroux2022", "pooled_scsemi_cv_20261002"), ("ye2026_sepsis", "pooled_scsemi_cv_20261002"),
102
+ ("ye2026_sepsis", "pooled_scsemi_budget_20261002")):
103
+ d = FT / "generated" / ds / sub
104
+ m = json.loads((d / "POOL_MANIFEST.json").read_text())
105
+ for arm, a in m["arms"].items():
106
+ got = sha(Path(a["path"]))
107
+ if got != a["sha256"]:
108
+ raise SystemExit(f"{a['path']}: sha differs from POOL_MANIFEST.json")
109
+ locs.append({"artifact_role": "inference_output", "cohort": ds, "experiment": f"scsemi_{sub[7:]}",
110
+ "host": "server_1", "path": a["path"], "receipt": str(d / "POOL_MANIFEST.json"),
111
+ "sha256": got, "output_sha256": got, "state": "completed",
112
+ "note": f"scSemiProfiler {arm}, five test folds pooled (pool_folds.py); fold NPZs registered earlier"})
113
+ req = {"project_id": "pbisc-diffusion",
114
+ "summary": ("2026-10-08: bulk deconvolution with the same paired donors (BayesPrism recommended genes + score-gene "
115
+ "sensitivity; official CIBERSORTx Fractions S-mode + HiRes under qemu on server_1) scored with the "
116
+ "paired benchmark's own truth and scorer (plans/bayesprism_paired_20261006, README + RESULTS*.md); "
117
+ "new scSemiProfiler results (Giroux and sepsis 5-fold CV, Giroux without sex-linked genes, sepsis "
118
+ "equal budget, contrast and realism extras); paper-summary deck updated (two Supplementary slides, "
119
+ "Fig. 3 scSemiProfiler slides refreshed; 64 slides). Large deconvolution outputs stay on server_1, "
120
+ "listed with sha256 in results/LARGE_OUTPUTS_SHA256.tsv. Imperial scSemiProfiler 5-fold is still "
121
+ "running on server_2 (not included)."),
122
+ "assets": assets, "inference_locations": locs}
123
+ Path(out).write_text(json.dumps(req, indent=1))
124
+ kinds = {}
125
+ for a in assets:
126
+ kinds[a["kind"]] = kinds.get(a["kind"], 0) + 1
127
+ print(json.dumps({"assets": len(assets), "by_kind": kinds, "locations": len(locs), "large_outputs": len(large),
128
+ "large_bytes": sum(q.stat().st_size for q in large)}, indent=1))
129
+ return 0
130
+
131
+
132
+ if __name__ == "__main__":
133
+ sys.exit(main(sys.argv[1]))
paper-releases/pbisc-diffusion/updates/20261008T022410Z-deconv-scsemi-deck/diffusion/dataset/server_1/model8/plans/bayesprism_paired_20261006/tools/build_cibersortx_inputs.py ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """CIBERSORTx inputs for every split of one cohort (CPU only; 2026-10-06; user request: CIBERSORTx next to BayesPrism).
3
+
4
+ Same splits as BayesPrism (common.split_rows): reference = the split's paired donors' observed cells, mixture = the
5
+ test samples' real bulk raw counts.
6
+ refsample.txt CIBERSORTx single-cell reference: genes x cells, raw UMI, header = the cell's six-type gate label
7
+ (the scorer's composition axis). Up to CELLS_PER_TYPE cells per type, sampled without replacement
8
+ from the reference donors' cells (rng seeded by cohort, split and type; all cells when fewer).
9
+ mixture.txt genes x samples, the test samples' real bulk raw counts
10
+ hires_genes.txt the cohort's scoring genes (HiRes is asked for these only; the scorer's gene axis)
11
+ Genes: the canonical axis, measured by the cohort's sc assay in every sample and bulk-valid in every mixture sample
12
+ (reference rows may be all zero; CIBERSORTx picks its signature genes, and HiRes imputes every mixture gene). No sex / ribosomal cleanup (CIBERSORTx selects its own signature genes, and
13
+ HiRes must cover the scoring genes). Identifiers: Ensembl ids in both files.
14
+ Output cibersortx/<ds>/<split>/ + INPUT.json (rows, cell numbers, gene numbers, sha256).
15
+ usage: CUDA_VISIBLE_DEVICES='' build_cibersortx_inputs.py DATASET
16
+ """
17
+ from __future__ import annotations
18
+
19
+ import hashlib
20
+ import json
21
+ import os
22
+ import sys
23
+ import time
24
+ from pathlib import Path
25
+
26
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
27
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
28
+
29
+ import numpy as np
30
+ import pandas as pd
31
+ import scipy.sparse as sp
32
+
33
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
34
+ import common as C # noqa: E402
35
+
36
+ CELLS_PER_TYPE = 400
37
+ SPLITS = [("fewshot", k) for k in range(5)] + [("cv", k) for k in range(5)]
38
+ SEED = 20261006
39
+
40
+
41
+ def labels_for(ds: str, n_rows: int) -> np.ndarray:
42
+ lp = C.FT / "scoring_cache" / ds / "observed_labels" / "labels" / "labels.parquet"
43
+ if lp.exists():
44
+ lab = pd.read_parquet(lp, columns=["celltype_l1_pred", "npz_row"])
45
+ if len(lab) != n_rows or not (lab.npz_row.to_numpy() == np.arange(n_rows)).all():
46
+ raise SystemExit("observed labels are not row-aligned")
47
+ return lab.celltype_l1_pred.astype(str).to_numpy()
48
+ man = json.loads((C.FT / "scoring_cache" / ds / "reference_manifest.json").read_text())
49
+ obs = pd.read_parquet(C.FT / "data" / ds / "cells_obs.parquet", columns=["cell_index"])
50
+ lab = pd.read_parquet(man["labels"]["source"], columns=["cell_index", "celltype_l1_pred"]).set_index("cell_index")
51
+ out = lab.celltype_l1_pred.reindex(obs.cell_index.to_numpy())
52
+ if out.isna().any() or len(out) != n_rows:
53
+ raise SystemExit("ImMicro labels do not cover every cell")
54
+ return out.astype(str).to_numpy()
55
+
56
+
57
+ def write_matrix(path: Path, genes: np.ndarray, cols: list[str], M: np.ndarray) -> None:
58
+ """Tab-delimited, first column 'GeneSymbol' (CIBERSORTx convention), integer values."""
59
+ df = pd.DataFrame(np.asarray(M, dtype=np.int64), index=pd.Index(genes, name="GeneSymbol"))
60
+ df.columns = cols # duplicate labels are intended (one column per cell, labelled by type)
61
+ df.to_csv(path, sep="\t")
62
+
63
+
64
+ def main(argv=None) -> int:
65
+ ds = (argv or sys.argv[1:])[0]
66
+ t0 = time.monotonic()
67
+ dd = C.FT / "data" / ds
68
+ feat = np.load(dd / "features.npz", allow_pickle=False)
69
+ sids = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
70
+ gene_ids = feat["gene_ids"].astype(str)
71
+ sc_ok = feat["sc_valid"].astype(bool).all(0)
72
+ score_ids = np.load(C.FT / "scoring_cache" / ds / "reference.npz", allow_pickle=False)["score_ids"].astype(str)
73
+ z = np.load(dd / "cells_full.npz", allow_pickle=False)
74
+ shape = tuple(int(x) for x in z["shape"])
75
+ X = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=shape)
76
+ row_sample = z["row_sample"].astype(np.int64)
77
+ del z
78
+ lab = labels_for(ds, shape[0])
79
+ spos = {s: i for i, s in enumerate(sids)}
80
+ for kind, k in SPLITS:
81
+ sp_ = C.split_rows(ds, kind, k)
82
+ ref_rows = np.asarray([spos[s] for s in sp_["reference"]])
83
+ mix_rows = np.asarray([spos[s] for s in sp_["mixture"]])
84
+ cells = np.flatnonzero(np.isin(row_sample, ref_rows))
85
+ pick = []
86
+ for ti, t in enumerate(sorted(set(lab[cells]))):
87
+ c = cells[lab[cells] == t]
88
+ rng = np.random.default_rng([SEED, int.from_bytes(hashlib.sha256(f"{ds}|{kind}{k}|{t}".encode()).digest()[:4], "little")])
89
+ pick.append(np.sort(rng.choice(c, CELLS_PER_TYPE, replace=False)) if c.size > CELLS_PER_TYPE else c)
90
+ pick = np.concatenate(pick)
91
+ R = X[pick].toarray().T # genes x cells
92
+ valid = feat["bulk_valid"].astype(bool)[mix_rows].all(0)
93
+ keep = sc_ok & valid # reference rows may be all-zero; HiRes imputes every mixture gene
94
+ genes = gene_ids[keep]
95
+ mix = np.asarray(feat["bulk_raw"], np.float64)[mix_rows][:, keep]
96
+ if not np.isfinite(mix).all() or (mix < 0).any() or (mix != np.round(mix)).any():
97
+ raise SystemExit("mixture counts are not non-negative integers")
98
+ out = C.PLAN / "cibersortx" / ds / f"{kind}{k}"
99
+ out.mkdir(parents=True, exist_ok=True)
100
+ write_matrix(out / "refsample.txt", genes, list(lab[pick]), R[keep])
101
+ write_matrix(out / "mixture.txt", genes, sp_["mixture"], mix.T)
102
+ hg = [g for g in score_ids if g in set(genes)]
103
+ (out / "hires_genes.txt").write_text("\n".join(hg) + "\n")
104
+ rec = {"dataset": ds, "kind": kind, "idx": k, "reference_samples": sp_["reference"], "mixture_samples": sp_["mixture"],
105
+ "reference_cells_available": int(cells.size), "reference_cells_used": int(pick.size),
106
+ "cells_per_type_used": pd.Series(lab[pick]).value_counts().to_dict(), "cells_per_type_cap": CELLS_PER_TYPE,
107
+ "genes": int(keep.sum()), "hires_genes": len(hg), "scoring_genes": int(score_ids.size),
108
+ "files": {f: C.sha(out / f) for f in ("refsample.txt", "mixture.txt", "hires_genes.txt")},
109
+ "seed": SEED, "tool_sha256": C.sha(Path(__file__)), "common_sha256": C.sha(Path(C.__file__))}
110
+ (out / "INPUT.json").write_text(json.dumps(rec, indent=1) + "\n")
111
+ print(json.dumps({k_: rec[k_] for k_ in ("dataset", "kind", "idx", "reference_cells_used", "genes", "hires_genes")}),
112
+ flush=True)
113
+ print(json.dumps({"dataset": ds, "seconds": round(time.monotonic() - t0, 1)}))
114
+ return 0
115
+
116
+
117
+ if __name__ == "__main__":
118
+ sys.exit(main())