junidude14 commited on
Commit
3fb3450
·
verified ·
1 Parent(s): 32a9084

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261006T033406Z-bulkonly-lora5-k1000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_20261006/tools/annotate_bulkonly.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Label the generated cells of one bulk-only set and reduce them to the compact files (CPU only; tools/common.py).
3
+
4
+ Same read-out and annotator as the benchmark scorer (paired_finetune_intradataset_20260927/tools/score_ft.py):
5
+ one Poisson read-out of generated_counts over the whole NPZ (poisson_readout.poisson_integerise, seed 20260916,
6
+ rows in NPZ order); frozen f01common scANVI (ft_common.run_annotator: predict_scanvi.py, CPU, zero query epochs),
7
+ query genes and zero-pad contract from the cohort's scoring reference (scoring_cache/<ds>), sample key
8
+ "<sample>|generated" and the cohort's batch prefix -- exactly how the benchmark labels generated cells.
9
+ Input: generated/<ds>/draw<j>/lora5_bulkonly.npz + .log (receipt; its output_sha256 and condition sha are checked)
10
+ Output: work/<ds>/bulkonly/draw<j>/{cells.parquet, markers.npz, pb_l2.npz, pb_l1.npz, subsample.npz, RECEIPT.json,
11
+ labels/ (labels.parquet + manifest), predict_scanvi.log}
12
+ usage: CUDA_VISIBLE_DEVICES='' annotate_bulkonly.py DATASET DRAW [--threads 8]
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import argparse
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
+
29
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
30
+ import common as C # noqa: E402
31
+ F = C.F
32
+
33
+
34
+ def main(argv=None) -> int:
35
+ ap = argparse.ArgumentParser()
36
+ ap.add_argument("dataset")
37
+ ap.add_argument("draw", type=int)
38
+ ap.add_argument("--threads", type=int, default=8)
39
+ a = ap.parse_args(argv)
40
+ try:
41
+ from threadpoolctl import threadpool_limits
42
+ threadpool_limits(a.threads)
43
+ except ImportError:
44
+ pass
45
+ t0 = time.monotonic()
46
+ ds, j = a.dataset, a.draw
47
+ gdir = C.PLAN / "generated" / ds / f"draw{j}"
48
+ parts_man = C.PLAN / "data" / ds / "PARTS.json"
49
+ if parts_man.exists(): # row parts (tools/split_conditions.py): one NPZ + receipt per part, in row order
50
+ man_p = json.loads(parts_man.read_text())
51
+ units = [(gdir / f"lora5_bulkonly_part{p['part']}.npz", C.PLAN / "data" / ds / p["file"]) for p in man_p["parts"]]
52
+ else:
53
+ units = [(gdir / "lora5_bulkonly.npz", C.PLAN / "data" / ds / "bulkonly_raw.npz")]
54
+ ps = C.panel_setup(ds)
55
+ Xs, sample_list, recs, n_rows = [], [], [], 0
56
+ for npz, cond in units:
57
+ rec = json.loads(npz.with_suffix(".log").read_text())
58
+ got = C.sha(npz)
59
+ if got != rec["output_sha256"]:
60
+ raise SystemExit(f"{npz}: sha {got[:12]} != receipt {rec['output_sha256'][:12]}")
61
+ if C.sha(cond) != rec.get("condition_sha256"):
62
+ raise SystemExit(f"{npz}: receipt condition sha differs from {cond}")
63
+ d = np.load(npz, allow_pickle=False)
64
+ if not np.array_equal(d["gene_ids"].astype(str), ps["panel"]):
65
+ raise SystemExit("NPZ gene_ids differ from the 6k panel")
66
+ sample_ids = d["sample_ids"].astype(str)
67
+ sample_list.append(sample_ids[d["bulk_index"].astype(np.int64)])
68
+ rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
69
+ n_rows += rates.shape[0]
70
+ # one Poisson read-out per generated NPZ (whole file, rows in order), as the benchmark does per NPZ
71
+ Xs.append(F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096).tocsr())
72
+ del rates, d
73
+ recs.append({"npz": str(npz), "npz_sha256": got, "condition": str(cond), "condition_sha256": rec.get("condition_sha256"),
74
+ "seed": rec.get("seed"), "checkpoint": rec.get("checkpoint"), "checkpoint_sha256": rec.get("checkpoint_sha256")})
75
+ import scipy.sparse as sp
76
+ X = sp.vstack(Xs).tocsr()
77
+ samples = np.concatenate(sample_list)
78
+ del Xs
79
+ meta = pd.read_csv(C.PLAN / "data" / ds / "bulkonly_meta.csv")
80
+ if sorted(meta.sample_id.astype(str)) != sorted(set(samples)) or len(set(samples)) != len(meta):
81
+ raise SystemExit("generated samples differ from bulkonly_meta.csv")
82
+ if len({r["checkpoint_sha256"] for r in recs}) != 1:
83
+ raise SystemExit("parts were generated with different checkpoints")
84
+ npz, got, rec = units[0][0], recs[0]["npz_sha256"], recs[0]
85
+ cond = units[0][1]
86
+ ref, man = F.load_reference(F.CACHE_ROOT / ds)
87
+ ppos = {g: i for i, g in enumerate(ps["panel"])}
88
+ qidx = np.asarray([ppos[g] for g in ref["query_ids"].astype(str)], dtype=np.int64)
89
+ spec = F.DATASETS[ds]
90
+ work = C.PLAN / "work" / ds / "bulkonly" / f"draw{j}"
91
+ lab, linfo = F.run_annotator(X[:, qidx], list(ref["query_ids"].astype(str)),
92
+ np.asarray([f"{s}|generated" for s in samples], dtype=object), work=work,
93
+ method=f"lora5_bulkonly_d{j}", spec=spec, split="generated", threads=a.threads,
94
+ annot=F.annotator_run(None), expected_zero_pad=man["gene_sets"]["model_genes_missing_from_query"],
95
+ source_note={"kind": "generated_npz", "readout": "poisson", "seed": F.POISSON_SEED,
96
+ "source_path": ";".join(r["npz"] for r in recs),
97
+ "source_sha256": ";".join(r["npz_sha256"] for r in recs),
98
+ "poisson_note": "one draw per generated NPZ (whole file), every row"})
99
+ receipt = {"set": "bulkonly", "dataset": ds, "draw": j, "generated": recs, "npz_rows": int(n_rows),
100
+ "checkpoint": rec.get("checkpoint"), "checkpoint_sha256": rec.get("checkpoint_sha256"),
101
+ "poisson_seed": F.POISSON_SEED, "poisson_rule": "one read-out per generated NPZ (whole file, row order)",
102
+ "annotation": {k: linfo[k] for k in ("model_pt_sha256", "zero_padded_model_genes", "label_counts",
103
+ "mean_l2_max_prob", "predict_seconds")},
104
+ "tool": str(Path(__file__).resolve()), "tool_sha256": C.sha(Path(__file__)),
105
+ "common_sha256": C.sha(Path(C.__file__))}
106
+ out = C.write_compact(work, X, samples, lab, ps, receipt)
107
+ out["seconds"] = round(time.monotonic() - t0, 1)
108
+ (work / "RECEIPT.json").write_text(json.dumps(out, indent=1, default=str) + "\n")
109
+ print(json.dumps({k: out[k] for k in ("dataset", "draw", "cells", "samples", "seconds")} |
110
+ {"labels_l1": out["annotation"]["label_counts"]}, default=str))
111
+ return 0
112
+
113
+
114
+ if __name__ == "__main__":
115
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261006T033406Z-bulkonly-lora5-k1000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_20261006/tools/build_conditions.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Condition NPZs for the bulk-only samples of a paired cohort (CPU only; 2026-10-06, user request).
3
+
4
+ User request: generate cells with the LoRA-5 setting (the five-donor LoRA r16 models of the few-pair draws) for the
5
+ bulk samples that have no single-cell partner -- Ye 2026 sepsis (122) and Imperial ESKD COVID (164) -- to look for
6
+ cell populations and biological findings.
7
+
8
+ Sources (read, never written):
9
+ bulk counts the cohort's harmonized bulk (MANIFEST.json inputs.bulk_harmonized, canonical 20,097-gene axis,
10
+ X = htseq raw counts, layers['harmonization_valid'])
11
+ bulk-only MANIFEST.json excluded.bulk_samples_without_sc (cross-checked with the pairing table bulk_without_sc.csv)
12
+ metadata sepsis: pairing/GSE279448_samples.csv (GEO characteristics); Imperial: pairing/bulk_samples.csv
13
+ arithmetic prepare_dataset.py (load, write_npz) and realbulk_generation_20260922/build_realbulk_conditions.py
14
+ (to_condition_counts, RECIPE_K, DEPTH_ANCHOR), i.e. exactly the paired benchmark's raw arm
15
+ Checks (all must pass, else nothing is written):
16
+ 1. the same extraction applied to every PAIRED row reproduces features.npz bulk_raw and bulk_valid exactly, and the
17
+ resulting condition rows equal conditions_raw_fixed.npz (bulk_counts, measurement fraction, recipe_k) exactly
18
+ 2. sc_valid is identical in every paired row (one sc feature table per cohort); it is the bulk-only rows'
19
+ output_availability_mask, as for the paired rows
20
+ 3. bulk-only ids = MANIFEST list = pairing table, disjoint from every paired bulk sample; all present in the h5ad
21
+ Outputs: data/<dataset>/bulkonly_raw.npz (sampler input; same keys as conditions_raw_fixed.npz; donor_n_cells = 0, no
22
+ cells exist), data/<dataset>/bulkonly_meta.csv (one row per bulk-only sample, NPZ order, clinical metadata,
23
+ bulk sex flag, draw-training-donor flags), data/<dataset>/BUILD.json (sources, sha256, checks)
24
+ usage: CUDA_VISIBLE_DEVICES='' build_conditions.py DATASET
25
+ """
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import os
31
+ import sys
32
+ from datetime import datetime, timezone
33
+ from pathlib import Path
34
+
35
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
36
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
37
+
38
+ import numpy as np
39
+ import pandas as pd
40
+
41
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
42
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
43
+ PLAN = Path(__file__).resolve().parents[1]
44
+ sys.path.insert(0, str(FT / "tools"))
45
+ import prepare_dataset as PD # noqa: E402 (load, write_npz, RB = build_realbulk_conditions)
46
+
47
+ GROUP_SEPSIS = {"Adult Sepsis": "adult_sepsis", "Pediatric Sepsis": "ped_sepsis", "Adult Healthy Control": "adult_HC",
48
+ "Adult ICU Control": "adult_ICU_ctrl", "Pediatric Healthy Control": "ped_HC",
49
+ "Pediatric ICU Control": "ped_ICU_ctrl"}
50
+ GROUP_IMPERIAL = {"positive": "covid_positive", "negative": "covid_negative", "recovery": "recovery"}
51
+
52
+
53
+ def sha(p: Path) -> str:
54
+ h = hashlib.sha256()
55
+ with open(p, "rb") as f:
56
+ for b in iter(lambda: f.read(1 << 24), b""):
57
+ h.update(b)
58
+ return h.hexdigest()
59
+
60
+
61
+ def read_bulk(h5: Path, ids: list[str], gene_ids: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
62
+ """Rows `ids` of the harmonized bulk: raw counts (0 where not harmonization-valid) and the valid mask."""
63
+ import anndata as ad
64
+ a = ad.read_h5ad(h5)
65
+ if not np.array_equal(a.var_names.astype(str).to_numpy(), gene_ids):
66
+ raise SystemExit(f"{h5}: gene axis differs from features.npz gene_ids")
67
+ pos = {s: i for i, s in enumerate(a.obs_names.astype(str))}
68
+ miss = [s for s in ids if s not in pos]
69
+ if miss:
70
+ raise SystemExit(f"{len(miss)} ids missing from {h5.name}: {miss[:5]}")
71
+ r = np.asarray([pos[s] for s in ids], dtype=np.int64)
72
+ X = np.asarray(a.X[r], dtype=np.float64)
73
+ V = np.asarray(a.layers["harmonization_valid"][r]).astype(bool)
74
+ X = np.where(V, X, 0.0)
75
+ if not np.isfinite(X).all() or (X < 0).any() or (X != np.round(X)).any():
76
+ raise SystemExit("bulk counts are not finite non-negative integers inside the valid mask")
77
+ return X, V
78
+
79
+
80
+ def main(argv=None) -> int:
81
+ ds = (argv or sys.argv[1:])[0]
82
+ if ds not in ("ye2026_sepsis", "imperial_eskd"):
83
+ raise SystemExit("DATASET must be ye2026_sepsis or imperial_eskd")
84
+ ddir = FT / "data" / ds
85
+ man = json.loads((ddir / "MANIFEST.json").read_text())
86
+ h5 = Path(man["inputs"]["bulk_harmonized"]["path"])
87
+ if sha(h5) != man["inputs"]["bulk_harmonized"]["sha256"]:
88
+ raise SystemExit(f"{h5} differs from the sha256 in MANIFEST.json")
89
+ d = PD.load(ddir)
90
+ f = np.load(ddir / "features.npz", allow_pickle=False)
91
+ checks = {}
92
+
93
+ # ---- check 1: the paired rows through the same extraction
94
+ if ds == "imperial_eskd":
95
+ paired_bulk_ids = f["bulk_sample"].astype(str).tolist()
96
+ else:
97
+ paired_bulk_ids = d["sample_ids"].tolist()
98
+ Xp, Vp = read_bulk(h5, paired_bulk_ids, d["gene_ids"])
99
+ checks["paired_bulk_raw_equal"] = bool(np.array_equal(Xp, d["bulk"]))
100
+ checks["paired_bulk_valid_equal"] = bool(np.array_equal(Vp, d["bulk_valid"]))
101
+ raw_p = PD.RB.to_condition_counts(Xp, Vp)
102
+ ref = np.load(ddir / "conditions_raw_fixed.npz", allow_pickle=False)
103
+ checks["paired_condition_counts_equal_conditions_raw_fixed"] = bool(np.array_equal(raw_p, ref["bulk_counts"]))
104
+ checks["paired_measurement_fraction_equal"] = bool(np.array_equal(Vp.astype(np.float32),
105
+ ref["bulk_measurement_fraction"]))
106
+ checks["recipe_k"] = int(PD.RB.RECIPE_K)
107
+ checks["recipe_k_equal"] = bool((ref["recipe_k"] == PD.RB.RECIPE_K).all())
108
+ # ---- check 2: one sc feature table per cohort
109
+ scv = d["sc_valid"]
110
+ checks["sc_valid_identical_across_paired_rows"] = bool((scv == scv[0]).all())
111
+ checks["sc_valid_measured_panel_genes"] = int(scv[0].sum())
112
+ # ---- check 3: the bulk-only list
113
+ key = "bulk_sample" if ds == "imperial_eskd" else "sample_id"
114
+ only = [str(x[key]) for x in man["excluded"]["bulk_samples_without_sc"]]
115
+ ptab = pd.read_csv(Path(man["processing_dir"]) / "pairing" / "bulk_without_sc.csv")
116
+ checks["bulk_only_n"] = len(only)
117
+ checks["bulk_only_equals_pairing_table"] = sorted(only) == sorted(ptab[key].astype(str))
118
+ checks["bulk_only_disjoint_from_paired"] = not (set(only) & set(paired_bulk_ids))
119
+ checks["bulk_only_unique"] = len(set(only)) == len(only)
120
+ bad = [k for k, v in checks.items() if v is False]
121
+ if bad:
122
+ raise SystemExit(f"checks failed: {bad} -> {checks}")
123
+
124
+ # ---- bulk-only rows, metadata
125
+ order = sorted(only) if ds == "ye2026_sepsis" else only # sepsis: id order; Imperial: MANIFEST order (patient, day)
126
+ Xb, Vb = read_bulk(h5, order, d["gene_ids"])
127
+ if ds == "ye2026_sepsis":
128
+ meta = pd.read_csv(Path(man["processing_dir"]) / "pairing" / "GSE279448_samples.csv")
129
+ meta["sample_id"] = meta["Sample_title"].str.replace("bulkRNA ", "", regex=False).str.strip()
130
+ meta = meta.set_index("sample_id").loc[order].reset_index()
131
+ m = pd.DataFrame({"sample_id": order, "donor_id": order,
132
+ "group": meta["ch_group"].map(GROUP_SEPSIS).to_numpy(),
133
+ "gsm": meta["gsm"].to_numpy(), "sex_geo": meta["ch_gender"].to_numpy(),
134
+ "age": meta["ch_age"].to_numpy(),
135
+ "infection_source": meta["ch_sepsis infection_source"].fillna("none").to_numpy(),
136
+ "collection_site": meta["ch_sample collection_site"].to_numpy()})
137
+ sexf = pd.read_csv(ddir / "identity_sex_bulk_all.csv")
138
+ else:
139
+ meta = pd.read_csv(Path(man["processing_dir"]) / "pairing" / "bulk_samples.csv").set_index("bulk_sample")
140
+ meta = meta.loc[order].reset_index()
141
+ m = pd.DataFrame({"sample_id": order, "donor_id": meta["pid"].astype(str).to_numpy(),
142
+ "group": meta["status"].map(GROUP_IMPERIAL).to_numpy()})
143
+ for c in ("sex", "calc_age", "ethnicity", "WHO_severity", "WHO_temp_severity", "fatal_disease",
144
+ "time_from_first_symptoms", "time_from_first_positive_swab", "day_label", "wave", "waves",
145
+ "diabetes", "cause_eskd", "ihd", "copd", "smoking"):
146
+ m[c] = meta[c].to_numpy()
147
+ sexf = pd.read_csv(ddir / "identity_sex_bulk_all.csv")
148
+ if m["group"].isna().any():
149
+ raise SystemExit(f"unmapped groups: {m.loc[m.group.isna()]}")
150
+ # bulk sex call vs metadata (identity_sex_bulk_all.csv covers every bulk sample of the cohort)
151
+ sid_col = [c for c in sexf.columns if c in ("bulk_sample", "sample_id", "sample")][0]
152
+ sx = sexf.set_index(sexf[sid_col].astype(str))
153
+ flag_col = [c for c in sx.columns if "flag" in c or "concord" in c or "differs" in c or "discord" in c]
154
+ m["bulk_sex_call"] = [str(sx.loc[s, "bulk_sex_call"]) if s in sx.index and "bulk_sex_call" in sx.columns else ""
155
+ for s in order]
156
+ meta_sex = m["sex_geo"] if "sex_geo" in m else m["sex"]
157
+ norm = {"male": "male", "m": "male", "female": "female", "f": "female"}
158
+ m["sex_flag"] = [norm.get(str(a).lower(), "?") != str(b).lower() for a, b in zip(meta_sex, m["bulk_sex_call"])]
159
+ # draw training donors (the LoRA-5 models): mark bulk-only samples whose donor trained a draw (Imperial serial samples)
160
+ draws = json.loads((ddir / "fewshot_n5" / "DRAWS.json").read_text())["draw"]
161
+ for j, v in draws.items():
162
+ m[f"donor_trained_draw{j}"] = m["donor_id"].isin([str(x) for x in v["train_donors"]])
163
+
164
+ out = PLAN / "data" / ds
165
+ out.mkdir(parents=True, exist_ok=True)
166
+ dd = {"gene_ids": d["gene_ids"], "sample_ids": np.asarray(order, dtype=str),
167
+ "donor_ids": m["donor_id"].astype(str).to_numpy(), "groups": m["group"].astype(str).to_numpy(),
168
+ "sc_valid": np.repeat(scv[:1], len(order), axis=0), "n_cells": np.zeros(len(order), dtype=np.int64)}
169
+ raw = PD.RB.to_condition_counts(Xb, Vb)
170
+ npz_sha = PD.write_npz(out / "bulkonly_raw.npz", dd, np.arange(len(order)), raw, Vb, 1500, "raw")
171
+ m.to_csv(out / "bulkonly_meta.csv", index=False)
172
+ build = {"dataset": ds, "written_utc": datetime.now(timezone.utc).isoformat(), "tool": str(Path(__file__).resolve()),
173
+ "tool_sha256": sha(Path(__file__)), "bulk_harmonized": {"path": str(h5), "sha256": man["inputs"]["bulk_harmonized"]["sha256"]},
174
+ "manifest": {"path": str(ddir / "MANIFEST.json"), "sha256": sha(ddir / "MANIFEST.json")},
175
+ "prepare_dataset_sha256": sha(FT / "tools/prepare_dataset.py"), "builder": str(PD.BUILDER),
176
+ "builder_sha256": sha(PD.BUILDER), "recipe_k": int(PD.RB.RECIPE_K), "depth_anchor": float(PD.RB.DEPTH_ANCHOR),
177
+ "cells_per_bulk": 1500, "n_bulk_only": len(order), "checks": checks,
178
+ "groups": m["group"].value_counts().to_dict(), "sex_flagged": m.loc[m.sex_flag, "sample_id"].tolist(),
179
+ "files": {"bulkonly_raw.npz": npz_sha, "bulkonly_meta.csv": sha(out / "bulkonly_meta.csv")}}
180
+ (out / "BUILD.json").write_text(json.dumps(build, indent=1, default=str) + "\n")
181
+ print(json.dumps({k: build[k] for k in ("dataset", "n_bulk_only", "checks", "groups", "sex_flagged")}, indent=1,
182
+ default=str))
183
+ return 0
184
+
185
+
186
+ if __name__ == "__main__":
187
+ sys.exit(main())
paper-releases/pbisc-diffusion/updates/20261006T033406Z-bulkonly-lora5-k1000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_20261006/tools/common.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Shared helpers of plans/bulkonly_lora5_20261006 (CPU only; imported, not run).
2
+
3
+ Every cell set (bulk-only generated, paired-test generated, paired observed) is reduced to the same compact files so
4
+ the analysis never needs the 2-7 GB generated NPZs again:
5
+ cells.parquet one row per cell: sample_id, celltype_l1_pred (six-type gate), aifi_l1, aifi_l2, aifi_l2_confidence,
6
+ lib_measured (UMI on the cohort's measured panel genes), lib_score (UMI on the scoring genes)
7
+ markers.npz int32 counts of every marker gene of the rare-state rules (plans/rare_states_screen_20261004/tools/
8
+ states.json), columns = marker_symbols
9
+ pb.npz per sample x aifi_l2: summed counts on the 6k panel (float32), cell numbers; per sample x six-type L1 too
10
+ subsample.npz 200 cells per sample (rng 20261006 keyed by sample id; all cells if fewer): CSR integer counts on the
11
+ 6k panel + their cells.parquet row index (for embedding / clustering)
12
+ Counts are always integer UMIs: generated cells after the benchmark's Poisson read-out (seed 20260916, one draw over
13
+ the whole NPZ in row order), observed cells as measured.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import hashlib
18
+ import importlib.util
19
+ import json
20
+ import sys
21
+ from pathlib import Path
22
+
23
+ import numpy as np
24
+ import pandas as pd
25
+ import scipy.sparse as sp
26
+
27
+ M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
28
+ FT = M8 / "plans/paired_finetune_intradataset_20260927"
29
+ PLAN = Path(__file__).resolve().parents[1]
30
+ RS = M8 / "plans/rare_states_screen_20261004"
31
+ STATES = RS / "tools/states.json"
32
+ CANON = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/"
33
+ "canonical_genes.tsv")
34
+ SUB_SEED = 20261006
35
+ SUB_N = 200
36
+ sys.path.insert(0, str(FT / "tools"))
37
+ import ft_common as F # noqa: E402 (PR = poisson_readout, POISSON_SEED, DATASETS, run_annotator, load_reference)
38
+
39
+
40
+ def sha(p: Path) -> str:
41
+ h = hashlib.sha256()
42
+ with open(p, "rb") as f:
43
+ for b in iter(lambda: f.read(1 << 24), b""):
44
+ h.update(b)
45
+ return h.hexdigest()
46
+
47
+
48
+ def sha_bytes(b: bytes) -> str:
49
+ return hashlib.sha256(b).hexdigest()
50
+
51
+
52
+ def marker_genes(states: list[dict]) -> list[str]:
53
+ out = []
54
+ for st in states:
55
+ for g in st.get("genes", []) + [x for grp in st.get("require_any", []) for x in grp] + st.get("exclude", []):
56
+ if g not in out:
57
+ out.append(g)
58
+ return out
59
+
60
+
61
+ def panel_setup(ds: str) -> dict:
62
+ """6k panel ids (cells_panel6k.npz order = generated NPZ gene order), measured mask, scoring idx, marker columns."""
63
+ d = np.load(FT / "data" / ds / "cells_panel6k.npz", allow_pickle=False)
64
+ panel = d["panel_gene_ids"].astype(str)
65
+ measured = d["panel_measured"].any(0)
66
+ ref = np.load(FT / "scoring_cache" / ds / "reference.npz", allow_pickle=False)
67
+ if not np.array_equal(ref["panel_ids"].astype(str), panel):
68
+ raise SystemExit(f"{ds}: scoring reference panel differs from cells_panel6k.npz")
69
+ canon = pd.read_csv(CANON, sep="\t", dtype=str)
70
+ sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
71
+ id2sym = dict(zip(canon.gene_id, canon.gene_symbol))
72
+ pos = {g: i for i, g in enumerate(panel)}
73
+ states = json.loads(STATES.read_text())
74
+ syms = [g for g in marker_genes(states) if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
75
+ return {"panel": panel, "measured": measured, "score_idx": ref["score_idx"].astype(np.int64),
76
+ "marker_symbols": syms, "marker_cols": np.asarray([pos[sym2id[g]] for g in syms], dtype=np.int64),
77
+ "symbols": np.asarray([id2sym.get(g, g) for g in panel], dtype=str), "states_sha256": sha(STATES)}
78
+
79
+
80
+ def sample_rng(sample: str) -> np.random.Generator:
81
+ key = int.from_bytes(hashlib.sha256(str(sample).encode()).digest()[:8], "little")
82
+ return np.random.default_rng([SUB_SEED, key])
83
+
84
+
85
+ def write_compact(out: Path, X: sp.csr_matrix, sample_of_cell: np.ndarray, lab: pd.DataFrame, ps: dict,
86
+ receipt: dict) -> dict:
87
+ """X: integer counts, cells x 6k panel (panel order); lab: aifi_l1, aifi_l2, aifi_l2_confidence[, celltype_l1_pred]."""
88
+ out.mkdir(parents=True, exist_ok=True)
89
+ X = X.tocsr()
90
+ n = X.shape[0]
91
+ if len(sample_of_cell) != n or len(lab) != n:
92
+ raise SystemExit("cells, samples and labels are not row-aligned")
93
+ samples = np.asarray(sample_of_cell, dtype=str)
94
+ cells = pd.DataFrame({"sample_id": samples,
95
+ "celltype_l1_pred": lab["celltype_l1_pred"].astype(str).to_numpy()
96
+ if "celltype_l1_pred" in lab else lab["aifi_l1"].astype(str).to_numpy(),
97
+ "aifi_l1": lab["aifi_l1"].astype(str).to_numpy(), "aifi_l2": lab["aifi_l2"].astype(str).to_numpy(),
98
+ "aifi_l2_confidence": lab["aifi_l2_confidence"].astype(np.float32).to_numpy()
99
+ if "aifi_l2_confidence" in lab else np.full(n, np.nan, np.float32),
100
+ "lib_measured": np.asarray(X[:, np.flatnonzero(ps["measured"])].sum(1)).ravel().astype(np.int64),
101
+ "lib_score": np.asarray(X[:, ps["score_idx"]].sum(1)).ravel().astype(np.int64)})
102
+ cells.to_parquet(out / "cells.parquet", index=False)
103
+ np.savez_compressed(out / "markers.npz", markers=X[:, ps["marker_cols"]].toarray().astype(np.int32),
104
+ marker_symbols=np.asarray(ps["marker_symbols"]))
105
+ # per sample x type pseudobulk (summed integer counts on the 6k panel)
106
+ us = np.asarray(sorted(set(samples)))
107
+ for key, col in (("l2", "aifi_l2"), ("l1", "celltype_l1_pred")):
108
+ types = np.asarray(sorted(set(cells[col])))
109
+ si = pd.Index(us).get_indexer(samples)
110
+ ti = pd.Index(types).get_indexer(cells[col].to_numpy())
111
+ g = si * len(types) + ti
112
+ G = sp.csr_matrix((np.ones(n, np.float32), (g, np.arange(n))), shape=(len(us) * len(types), n))
113
+ S = (G @ X.astype(np.float32)).toarray().reshape(len(us), len(types), X.shape[1]).astype(np.float32)
114
+ N = np.bincount(g, minlength=len(us) * len(types)).reshape(len(us), len(types))
115
+ np.savez_compressed(out / f"pb_{key}.npz", sums=S, n_cells=N, samples=us, types=types,
116
+ gene_ids=ps["panel"], gene_symbols=ps["symbols"])
117
+ # subsample for embedding
118
+ keep = []
119
+ for s in us:
120
+ idx = np.flatnonzero(samples == s)
121
+ if idx.size > SUB_N:
122
+ idx = np.sort(sample_rng(s).choice(idx, SUB_N, replace=False))
123
+ keep.append(idx)
124
+ keep = np.concatenate(keep)
125
+ Xs = X[keep].tocsr().astype(np.int32)
126
+ np.savez_compressed(out / "subsample.npz", data=Xs.data, indices=Xs.indices, indptr=Xs.indptr,
127
+ shape=np.asarray(Xs.shape), cell_row=keep, gene_ids=ps["panel"], gene_symbols=ps["symbols"])
128
+ receipt = {**receipt, "cells": int(n), "samples": int(len(us)), "subsample_cells": int(keep.size),
129
+ "states_json": str(STATES), "states_sha256": ps["states_sha256"],
130
+ "files": {f: sha(out / f) for f in ("cells.parquet", "markers.npz", "pb_l2.npz", "pb_l1.npz",
131
+ "subsample.npz")}}
132
+ (out / "RECEIPT.json").write_text(json.dumps(receipt, indent=1, default=str) + "\n")
133
+ return receipt
paper-releases/pbisc-diffusion/updates/20261006T033406Z-bulkonly-lora5-k1000/diffusion/dataset/server_1/model8/plans/bulkonly_lora5_20261006/tools/extract_paired.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Paired-test calibration sets for the bulk-only analysis (CPU only; tools/common.py; no new generation).
3
+
4
+ Why: a pattern seen in the bulk-only cells is only worth following if the same LoRA-5 model reproduces it where the
5
+ truth is known. Each few-pair draw already generated cells for its paired TEST samples (the usable samples of the
6
+ cohort's other donors, real bulk at K = 1,000, seed 20260927) and the benchmark labelled them. This tool reduces
7
+ generated paired_finetune_intradataset_20260927/generated/<ds>/fewshot_n5/draw<j>/lora__raw.npz (sepsis: server_1;
8
+ Imperial: streamed from spark-0110) -> the benchmark's own Poisson read-out (seed 20260916, whole NPZ),
9
+ the scored rows of scores/<ds>/fewshot_n5/draw<j>/arms/lora5/generated_cells.parquet, their labels
10
+ (labels/labels.parquet); umi_scoring_genes must be reproduced cell by cell, the NPZ sha must equal its receipt
11
+ observed every cell of the cohort's usable samples (data/<ds>/cells_panel6k.npz, folds.csv fold >= 0) with the
12
+ benchmark's observed labels (scoring_cache/<ds>/observed_labels/labels/labels.parquet, npz_row aligned)
13
+ to the same compact files as the bulk-only sets (cells.parquet, markers.npz, pb_l2/l1.npz, subsample.npz).
14
+ Outputs: work/<ds>/paired_gen/draw<j>/ and work/<ds>/observed/
15
+ usage: CUDA_VISIBLE_DEVICES='' extract_paired.py DATASET gen DRAW
16
+ CUDA_VISIBLE_DEVICES='' extract_paired.py DATASET observed
17
+ """
18
+ from __future__ import annotations
19
+
20
+ import io
21
+ import json
22
+ import os
23
+ import subprocess
24
+ import sys
25
+ import time
26
+ from pathlib import Path
27
+
28
+ if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
29
+ raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
30
+
31
+ import numpy as np
32
+ import pandas as pd
33
+ import scipy.sparse as sp
34
+
35
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
36
+ import common as C # noqa: E402
37
+ F = C.F
38
+
39
+
40
+ def load_npz_bytes(path: Path) -> bytes:
41
+ if path.exists():
42
+ return path.read_bytes()
43
+ res = subprocess.run(["ssh", "-n", "spark-0110", "cat", str(path)], capture_output=True, check=True)
44
+ return res.stdout
45
+
46
+
47
+ def cmd_gen(ds: str, j: int) -> None:
48
+ t0 = time.monotonic()
49
+ g = C.FT / "generated" / ds / "fewshot_n5" / f"draw{j}" / "lora__raw.npz"
50
+ rec_path = g.with_suffix(".log")
51
+ if rec_path.exists():
52
+ rec = json.loads(rec_path.read_text())
53
+ else:
54
+ rec = json.loads(subprocess.run(["ssh", "-n", "spark-0110", "cat", str(rec_path)], capture_output=True,
55
+ check=True).stdout)
56
+ raw = load_npz_bytes(g)
57
+ got = C.sha_bytes(raw)
58
+ if got != rec["output_sha256"]:
59
+ raise SystemExit(f"{g}: sha {got[:12]} != receipt {rec['output_sha256'][:12]}")
60
+ d = np.load(io.BytesIO(raw), allow_pickle=False)
61
+ del raw
62
+ ps = C.panel_setup(ds)
63
+ if not np.array_equal(d["gene_ids"].astype(str), ps["panel"]):
64
+ raise SystemExit("NPZ gene_ids differ from the 6k panel")
65
+ rates = np.ascontiguousarray(d["generated_counts"], dtype=np.float32)
66
+ n_rows = rates.shape[0]
67
+ full = F.PR.poisson_integerise(rates, seed=F.POISSON_SEED, chunk_rows=4096).tocsr()
68
+ del rates
69
+ sdir = C.FT / "scores" / ds / "fewshot_n5" / f"draw{j}" / "arms" / "lora5"
70
+ gc = pd.read_parquet(sdir / "generated_cells.parquet")
71
+ lab = pd.read_parquet(sdir / "labels" / "labels.parquet")
72
+ if len(gc) != len(lab) or not (lab.sample_id.astype(str).str.removesuffix("|generated").values == gc.donor.values).all():
73
+ raise SystemExit("generated_cells and labels are not row-aligned")
74
+ X = full[gc.npz_row.to_numpy()].tocsr()
75
+ del full
76
+ umi = np.asarray(X[:, ps["score_idx"]].sum(1)).ravel()
77
+ if not np.array_equal(umi, gc.umi_scoring_genes.to_numpy()):
78
+ raise SystemExit(f"Poisson read-out does not reproduce the benchmark ({int((umi != gc.umi_scoring_genes.to_numpy()).sum())} cells)")
79
+ receipt = {"set": "paired_gen", "dataset": ds, "draw": j, "npz": str(g), "npz_sha256": got, "npz_rows": int(n_rows),
80
+ "checkpoint": rec.get("checkpoint"), "checkpoint_sha256": rec.get("checkpoint_sha256"),
81
+ "labels": str(sdir / "labels/labels.parquet"), "labels_sha256": C.sha(sdir / "labels/labels.parquet"),
82
+ "poisson_seed": F.POISSON_SEED, "umi_scoring_genes_reproduced": True,
83
+ "tool": str(Path(__file__).resolve()), "tool_sha256": C.sha(Path(__file__)),
84
+ "common_sha256": C.sha(Path(C.__file__))}
85
+ out = C.write_compact(C.PLAN / "work" / ds / "paired_gen" / f"draw{j}", X, gc.donor.astype(str).to_numpy(), lab, ps,
86
+ receipt)
87
+ print(json.dumps({"dataset": ds, "draw": j, "cells": out["cells"], "samples": out["samples"],
88
+ "seconds": round(time.monotonic() - t0, 1)}))
89
+
90
+
91
+ def cmd_observed(ds: str) -> None:
92
+ t0 = time.monotonic()
93
+ ps = C.panel_setup(ds)
94
+ dd = C.FT / "data" / ds
95
+ d = np.load(dd / "cells_panel6k.npz", allow_pickle=False)
96
+ X = sp.csr_matrix((d["data"], d["indices"], d["indptr"]), shape=tuple(d["shape"]))
97
+ obs = pd.read_parquet(dd / "cells_obs.parquet", columns=["sample_id"])
98
+ lpath = C.FT / "scoring_cache" / ds / "observed_labels" / "labels" / "labels.parquet"
99
+ lab = pd.read_parquet(lpath)
100
+ if len(lab) != X.shape[0] or not (lab.npz_row.to_numpy() == np.arange(X.shape[0])).all():
101
+ raise SystemExit("observed labels not aligned with cells_panel6k.npz")
102
+ folds = pd.read_csv(dd / "folds.csv")
103
+ usable = set(folds.loc[folds.fold >= 0, "sample_id"].astype(str))
104
+ keep = np.flatnonzero(obs.sample_id.astype(str).isin(usable).to_numpy())
105
+ receipt = {"set": "observed", "dataset": ds, "cells_panel6k": str(dd / "cells_panel6k.npz"),
106
+ "cells_panel6k_sha256": C.sha(dd / "cells_panel6k.npz"), "labels": str(lpath), "labels_sha256": C.sha(lpath),
107
+ "usable_samples": len(usable), "tool": str(Path(__file__).resolve()), "tool_sha256": C.sha(Path(__file__)),
108
+ "common_sha256": C.sha(Path(C.__file__))}
109
+ out = C.write_compact(C.PLAN / "work" / ds / "observed", X[keep].astype(np.int64),
110
+ obs.sample_id.astype(str).to_numpy()[keep], lab.iloc[keep].reset_index(drop=True), ps, receipt)
111
+ print(json.dumps({"dataset": ds, "set": "observed", "cells": out["cells"], "samples": out["samples"],
112
+ "seconds": round(time.monotonic() - t0, 1)}))
113
+
114
+
115
+ def main(argv=None) -> int:
116
+ args = argv or sys.argv[1:]
117
+ ds, what = args[0], args[1]
118
+ if what == "gen":
119
+ cmd_gen(ds, int(args[2]))
120
+ elif what == "observed":
121
+ cmd_observed(ds)
122
+ else:
123
+ raise SystemExit("usage: extract_paired.py DATASET gen DRAW | DATASET observed")
124
+ return 0
125
+
126
+
127
+ if __name__ == "__main__":
128
+ sys.exit(main())