Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_scsemi_paired.py +540 -0
- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/scan_trailing_batch.py +71 -0
- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/validate_export.py +112 -0
- paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/verify_lean_cellgraph.py +94 -0
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/run_scsemi_paired.py
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Pinned scSemiProfiler in its native paired-representative mode, real bulk, gene sets on (resumable).
|
| 3 |
+
|
| 4 |
+
Phases (each invocation does a bounded amount of work and exits; receipts make every step skippable):
|
| 5 |
+
prepare CPU. upstream initsetup(bulk, normed=False) + fixed representatives + upstream nearest-representative
|
| 6 |
+
assignment (representative_selection.update_membership on processed_bulkdata.obsm['X_pca']) +
|
| 7 |
+
upstream scprocess(rep cells, normed=False, threshold 1e-3, geneset=True, k=15).
|
| 8 |
+
pretrain GPU (via ml-run only). Per representative: fastrecon (VAE100/GAN100, lr 1e-3) then reconst_pretrain2
|
| 9 |
+
(VAE50/GAN50, lr 1e-4), exactly the calls upstream scinfer() makes. --max-reps bounds one call.
|
| 10 |
+
infer GPU (via ml-run only). Per target: fast_semi(rep, target, rep's pretrain-2 model, bulktype='real',
|
| 11 |
+
pseudocount 0.1, lr 2e-4, 150 epochs x 5 ministages), the call upstream scinfer() makes.
|
| 12 |
+
The upstream dense output is re-encoded losslessly as CSR (verified equal) with a receipt holding the
|
| 13 |
+
per-target runtime. --max-targets bounds one call.
|
| 14 |
+
|
| 15 |
+
CUDA work belongs to the coordinating agent and must run through ml-run. No automatic retries. Partial
|
| 16 |
+
outputs are preserved; an unreceipted upstream artefact stops the run for inspection.
|
| 17 |
+
--smoke (only under scsemi/smoke/, CPU) shrinks the epoch budget to exercise the plumbing.
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
import argparse
|
| 22 |
+
from datetime import datetime, timezone
|
| 23 |
+
import fcntl
|
| 24 |
+
import gc
|
| 25 |
+
import hashlib
|
| 26 |
+
import importlib.metadata
|
| 27 |
+
import json
|
| 28 |
+
import os
|
| 29 |
+
from pathlib import Path
|
| 30 |
+
import re
|
| 31 |
+
import resource
|
| 32 |
+
import shutil
|
| 33 |
+
import sys
|
| 34 |
+
import time
|
| 35 |
+
import types
|
| 36 |
+
|
| 37 |
+
HERE = Path(__file__).resolve().parents[1]
|
| 38 |
+
SEED = 20260927
|
| 39 |
+
MIGRATIONS = HERE / "compat_migrations.json" # approved code transitions a run may migrate across
|
| 40 |
+
MIGRATABLE = {"source", "wrapper_sha256"} # binding components an approved transition may change
|
| 41 |
+
PROTOCOL = {
|
| 42 |
+
"method": "scSemiProfiler", "setting": "paired_fixed_representatives_realbulk_genesets",
|
| 43 |
+
"upstream_commit": "c2aea021188759e56ecf14578915c0237aaa75d2",
|
| 44 |
+
"initsetup": {"logged": False, "normed": False, "geneselection": False, "batch": 1},
|
| 45 |
+
"scprocess": {"logged": False, "normed": False, "cellfilter": False, "threshold": 0.001, "geneset": True,
|
| 46 |
+
"weight": 0.5, "k": 15},
|
| 47 |
+
"representatives": "fixed: every usable row of the split's training donors (no active learning)",
|
| 48 |
+
"assignment": "upstream representative_selection.update_membership: nearest representative by Euclidean "
|
| 49 |
+
"distance in processed_bulkdata.obsm['X_pca'] (initsetup PCA of log1p CP10K real bulk)",
|
| 50 |
+
"pretrain1": {"vaesteps": 100, "gansteps": 100, "lr": 1e-3, "k": 15, "diagw": 1},
|
| 51 |
+
"pretrain2": {"vaesteps": 50, "gansteps": 50, "lr": 1e-4, "k": 15, "diagw": 1.0},
|
| 52 |
+
"infer": {"bulktype": "real", "pseudocount": 0.1, "lr": 2e-4, "epochs": 150, "ministages": 5, "k": 15,
|
| 53 |
+
"diagw": 1.0},
|
| 54 |
+
"seeds": {"base": SEED, "pretrain1": "base + 1000 + bulk row index", "pretrain2": "base + 2000 + bulk row index",
|
| 55 |
+
"target": "base + bulk row index (frozen campaign rule)"},
|
| 56 |
+
"output_unit": "normalized_expression (upstream fast_semi output: ZINB mean, rep-cell library, values <= 10 zeroed)",
|
| 57 |
+
"cellgraph_impl": "tools/lean_cellgraph.fast_cellgraph_lean replaces upstream singlecell_process.fast_cellgraph "
|
| 58 |
+
"inside scprocess: same arithmetic, chunked (16 GiB CPU cap); bit-identical outputs verified "
|
| 59 |
+
"(validation/lean_cellgraph_*.json)",
|
| 60 |
+
"scprocess_orchestration": "cohort hvset first (upstream scprocess's own steps: sorted sample_ids, normalize_total "
|
| 61 |
+
"1e4, dense, X*(X>10), getGeneSetMatrix score formula, concatenate, log1p, "
|
| 62 |
+
"highly_variable_genes) -> hvset.npy; then upstream scprocess once per representative "
|
| 63 |
+
"(it skips hvset when hvset.npy exists). Bit-identical to one scprocess call over all "
|
| 64 |
+
"representatives (validation/prepared_*.json); peak memory is one representative",
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def cohort_hvset(project: Path, rep_sc: Path, threshold: float) -> "np.ndarray":
|
| 69 |
+
"""Upstream scprocess's hvset block, run representative by representative (same order, same arithmetic)."""
|
| 70 |
+
import numpy as np
|
| 71 |
+
import anndata
|
| 72 |
+
import scanpy as sc
|
| 73 |
+
from scSemiProfiler.singlecell_process import getGeneSetMatrix
|
| 74 |
+
R = anndata.read_h5ad(rep_sc)
|
| 75 |
+
sids = np.unique(R.obs["sample_ids"])
|
| 76 |
+
zps = []
|
| 77 |
+
for sid in sids:
|
| 78 |
+
a = R[(R.obs["sample_ids"] == sid).to_numpy()].copy()
|
| 79 |
+
sc.pp.normalize_total(a, target_sum=1e4)
|
| 80 |
+
X = np.array(a.X.todense())
|
| 81 |
+
X = X * np.array(X > 1e4 * threshold)
|
| 82 |
+
genes_upper = [g.upper() for g in list(a.var.index)]
|
| 83 |
+
gene_set_matrix, _ = getGeneSetMatrix("c2.cp.v7.4.symbols.gmt", genes_upper, "genesets/")
|
| 84 |
+
zp = X.dot(np.array(gene_set_matrix).T)
|
| 85 |
+
eps = 1e-6
|
| 86 |
+
den = (np.array(gene_set_matrix.sum(axis=1)) + eps)
|
| 87 |
+
zp = (zp + eps) / den
|
| 88 |
+
zp = zp - eps / den
|
| 89 |
+
zps.append(zp)
|
| 90 |
+
del a, X
|
| 91 |
+
zps = np.concatenate(zps, axis=0)
|
| 92 |
+
zdata = anndata.AnnData(zps)
|
| 93 |
+
sc.pp.log1p(zdata)
|
| 94 |
+
sc.pp.highly_variable_genes(zdata)
|
| 95 |
+
hvset = zdata.var.highly_variable
|
| 96 |
+
np.save(str(project) + "/hvset.npy", hvset)
|
| 97 |
+
return np.asarray(hvset)
|
| 98 |
+
SMOKE_BUDGET = {"pretrain1": {"vaesteps": 1, "gansteps": 1}, "pretrain2": {"vaesteps": 1, "gansteps": 1},
|
| 99 |
+
"infer": {"epochs": 2}}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def sha256(path: Path) -> str:
|
| 103 |
+
digest = hashlib.sha256()
|
| 104 |
+
with Path(path).open("rb") as stream:
|
| 105 |
+
for chunk in iter(lambda: stream.read(16 * 1024 * 1024), b""):
|
| 106 |
+
digest.update(chunk)
|
| 107 |
+
return digest.hexdigest()
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def write_json(path: Path, value: dict) -> None:
|
| 111 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 112 |
+
tmp = path.with_name(path.name + ".tmp")
|
| 113 |
+
with tmp.open("w") as stream:
|
| 114 |
+
json.dump(value, stream, indent=1, default=str)
|
| 115 |
+
stream.write("\n")
|
| 116 |
+
stream.flush()
|
| 117 |
+
os.fsync(stream.fileno())
|
| 118 |
+
tmp.replace(path)
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def canonical_sha(value) -> str:
|
| 122 |
+
return hashlib.sha256(json.dumps(value, sort_keys=True).encode()).hexdigest()
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
def resolve_run_identity(run_file: Path, binding: dict, code_signature: str) -> tuple[str, list]:
|
| 126 |
+
"""The run's identity is the signature it was created with (every receipt is signed with it). A later code
|
| 127 |
+
version may continue the run only if its binding differs from the run's latest binding in MIGRATABLE components
|
| 128 |
+
alone and each change is an approved transition in compat_migrations.json; the migration is appended to
|
| 129 |
+
run_manifest.json. Anything else refuses, as before."""
|
| 130 |
+
rec = json.loads(run_file.read_text())
|
| 131 |
+
identity = rec["run_signature"]
|
| 132 |
+
migrations = rec.get("migrations", [])
|
| 133 |
+
if migrations:
|
| 134 |
+
last, last_sig = migrations[-1]["to_binding"], migrations[-1]["to_code_signature"]
|
| 135 |
+
else:
|
| 136 |
+
last, last_sig = {k: rec.get(k) for k in binding}, identity
|
| 137 |
+
if canonical_sha(last) != identity:
|
| 138 |
+
raise SystemExit("run_manifest.json binding does not hash to its run_signature; inspect")
|
| 139 |
+
if last == binding:
|
| 140 |
+
return identity, migrations
|
| 141 |
+
changed = sorted(k for k in set(last) | set(binding) if last.get(k) != binding.get(k))
|
| 142 |
+
if set(changed) - MIGRATABLE:
|
| 143 |
+
raise SystemExit(f"work dir belongs to different inputs/code/environment ({changed}); use a fresh work dir")
|
| 144 |
+
approved = json.loads(MIGRATIONS.read_text())["transitions"] if MIGRATIONS.exists() else []
|
| 145 |
+
used = []
|
| 146 |
+
for k in changed:
|
| 147 |
+
frm = canonical_sha(last[k]) if k == "source" else last[k]
|
| 148 |
+
to = canonical_sha(binding[k]) if k == "source" else binding[k]
|
| 149 |
+
hit = [x for x in approved if x["component"] == k and x["from"] == frm and x["to"] == to]
|
| 150 |
+
if not hit:
|
| 151 |
+
raise SystemExit(f"code change in {k} ({str(frm)[:12]} -> {str(to)[:12]}) is not an approved migration "
|
| 152 |
+
f"in {MIGRATIONS.name}; use a fresh work dir")
|
| 153 |
+
used.append(hit[0]["id"])
|
| 154 |
+
migrations = migrations + [{"at": datetime.now(timezone.utc).isoformat(), "host": os.uname().nodename,
|
| 155 |
+
"from_code_signature": last_sig, "to_code_signature": code_signature,
|
| 156 |
+
"changed": changed, "transitions": used, "to_binding": binding}]
|
| 157 |
+
rec["migrations"] = migrations
|
| 158 |
+
write_json(run_file, rec)
|
| 159 |
+
return identity, migrations
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main(argv=None) -> int:
|
| 163 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 164 |
+
ap.add_argument("--work", type=Path, required=True)
|
| 165 |
+
ap.add_argument("--phase", choices=["prepare", "pretrain", "infer", "status"], required=True)
|
| 166 |
+
ap.add_argument("--device", default="cuda:0")
|
| 167 |
+
ap.add_argument("--threads", type=int, default=4)
|
| 168 |
+
ap.add_argument("--max-reps", type=int, default=0, help="pretrain: at most N representatives this call (0 = all)")
|
| 169 |
+
ap.add_argument("--max-targets", type=int, default=0, help="infer: at most N targets this call (0 = all)")
|
| 170 |
+
ap.add_argument("--smoke", action="store_true")
|
| 171 |
+
a = ap.parse_args(argv)
|
| 172 |
+
if not 1 <= a.threads <= 6:
|
| 173 |
+
ap.error("--threads must be 1..6")
|
| 174 |
+
for name in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS", "NUMEXPR_NUM_THREADS", "NUMBA_NUM_THREADS"):
|
| 175 |
+
os.environ[name] = str(a.threads)
|
| 176 |
+
work = a.work.resolve()
|
| 177 |
+
if a.smoke and "/scsemi/smoke/" not in str(work) + "/":
|
| 178 |
+
raise SystemExit("--smoke only under scsemi/smoke/")
|
| 179 |
+
if a.phase in ("prepare", "status") and a.device != "cpu":
|
| 180 |
+
a.device = "cpu"
|
| 181 |
+
if a.device == "cpu" and os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 182 |
+
raise SystemExit("CPU phases require CUDA_VISIBLE_DEVICES=''")
|
| 183 |
+
if a.device.startswith("cuda") and a.smoke:
|
| 184 |
+
raise SystemExit("smoke runs are CPU only")
|
| 185 |
+
inputs = work / "inputs"
|
| 186 |
+
project = work / "scsemi_project"
|
| 187 |
+
events = work / "events.jsonl"
|
| 188 |
+
protocol = json.loads(json.dumps(PROTOCOL))
|
| 189 |
+
if a.smoke:
|
| 190 |
+
for k, v in SMOKE_BUDGET.items():
|
| 191 |
+
protocol[k].update(v)
|
| 192 |
+
protocol["SMOKE"] = "reduced epoch budget; plumbing test only, never a benchmark output"
|
| 193 |
+
|
| 194 |
+
def event(kind: str, **values) -> None:
|
| 195 |
+
v = {"at": datetime.now(timezone.utc).isoformat(), "event": kind, "phase": a.phase, **values,
|
| 196 |
+
"max_rss_gib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**20, 2)}
|
| 197 |
+
with events.open("a") as s:
|
| 198 |
+
s.write(json.dumps(v, default=str) + "\n")
|
| 199 |
+
s.flush()
|
| 200 |
+
os.fsync(s.fileno())
|
| 201 |
+
print(json.dumps(v, default=str), flush=True)
|
| 202 |
+
|
| 203 |
+
# shared code lock: tools/compat_patch_*.py replaces vendor files under the exclusive lock, so this call never
|
| 204 |
+
# verifies or imports a half-updated vendor; released once the vendor modules are imported
|
| 205 |
+
code_lock = open(HERE / ".code_update.lock", "a")
|
| 206 |
+
fcntl.flock(code_lock, fcntl.LOCK_SH)
|
| 207 |
+
man = json.loads((inputs / "inputs_manifest.json").read_text())
|
| 208 |
+
if bool(man.get("smoke")) != a.smoke:
|
| 209 |
+
raise SystemExit("smoke flag differs from the inputs' smoke flag")
|
| 210 |
+
for name, digest in man["files"].items():
|
| 211 |
+
if sha256(inputs / name) != digest:
|
| 212 |
+
raise SystemExit(f"input {name} differs from its manifest")
|
| 213 |
+
vendor = HERE / "vendor/scSemiProfiler"
|
| 214 |
+
source = json.loads((vendor.parent / "source_manifest.json").read_text())
|
| 215 |
+
for name, expected in source["files"].items():
|
| 216 |
+
if sha256(vendor / name) != expected:
|
| 217 |
+
raise SystemExit(f"vendor source hash mismatch: {name}")
|
| 218 |
+
assets = json.loads((HERE / "genesets/geneset_assets.json").read_text())
|
| 219 |
+
gmt_src = HERE / "genesets/c2.cp.v7.4.symbols.gmt"
|
| 220 |
+
if sha256(gmt_src) != assets["mapped_gmt_sha256"] or sha256(vendor / "genesets/c2.cp.v7.4.symbols.gmt") != assets["original_gmt_sha256"]:
|
| 221 |
+
raise SystemExit("gene-set asset hash mismatch")
|
| 222 |
+
versions = {n: importlib.metadata.version(n) for n in ["torch", "scvi-tools", "scanpy", "anndata", "lightning",
|
| 223 |
+
"numpy", "scikit-learn", "faiss-cpu", "gseapy"]}
|
| 224 |
+
binding = {"protocol": protocol, "inputs": man["files"], "source": source, "environment": versions,
|
| 225 |
+
"wrapper_sha256": sha256(Path(__file__)), "lean_cellgraph_sha256": sha256(HERE / "tools/lean_cellgraph.py"),
|
| 226 |
+
"geneset_mapped_gmt_sha256": assets["mapped_gmt_sha256"]}
|
| 227 |
+
code_signature = canonical_sha(binding)
|
| 228 |
+
run_file = work / "run_manifest.json"
|
| 229 |
+
migrations: list = []
|
| 230 |
+
if run_file.exists():
|
| 231 |
+
signature, migrations = resolve_run_identity(run_file, binding, code_signature)
|
| 232 |
+
else:
|
| 233 |
+
signature = code_signature
|
| 234 |
+
reps = [r["sample_id"] for r in man["representatives"]]
|
| 235 |
+
targets = list(man["target_order_test_samples"])
|
| 236 |
+
sids_expected = man["bulk_row_order"]
|
| 237 |
+
for s_ in sids_expected:
|
| 238 |
+
if not re.fullmatch(r"[A-Za-z0-9_.+-]+", s_):
|
| 239 |
+
raise SystemExit(f"unsafe sample id {s_!r}")
|
| 240 |
+
if not run_file.exists():
|
| 241 |
+
write_json(run_file, {"run_signature": signature, **binding, "work": str(work), "hostname": os.uname().nodename})
|
| 242 |
+
|
| 243 |
+
def status() -> dict:
|
| 244 |
+
pre = json.loads((work / "prepared.json").read_text()) if (work / "prepared.json").exists() else None
|
| 245 |
+
done_r = [r for r in reps if all((project / "models" / f"{b}{r}.receipt.json").exists()
|
| 246 |
+
for b in ("fast_reconst1_", "fastreconst2_"))]
|
| 247 |
+
done_t = [t for t in targets if (work / "shards" / f"{t}.json").exists()]
|
| 248 |
+
st = {"prepared": pre is not None, "n_reps": len(reps), "reps_pretrained": len(done_r),
|
| 249 |
+
"n_targets": len(targets), "targets_done": len(done_t),
|
| 250 |
+
"pretrain_complete": len(done_r) == len(reps), "infer_complete": len(done_t) == len(targets),
|
| 251 |
+
"run_signature": signature, "updated": datetime.now(timezone.utc).isoformat()}
|
| 252 |
+
write_json(work / "status.json", st)
|
| 253 |
+
return st
|
| 254 |
+
|
| 255 |
+
if a.phase == "status":
|
| 256 |
+
fcntl.flock(code_lock, fcntl.LOCK_UN)
|
| 257 |
+
print(json.dumps(status()))
|
| 258 |
+
return 0
|
| 259 |
+
|
| 260 |
+
import numpy as np
|
| 261 |
+
import anndata
|
| 262 |
+
import scipy.sparse as sp
|
| 263 |
+
sys.path.insert(0, str(vendor))
|
| 264 |
+
import torch
|
| 265 |
+
import scvi
|
| 266 |
+
import scSemiProfiler
|
| 267 |
+
from scSemiProfiler.inference import fastrecon, reconst_pretrain2, fast_semi
|
| 268 |
+
from scSemiProfiler.representative_selection import update_membership
|
| 269 |
+
fcntl.flock(code_lock, fcntl.LOCK_UN)
|
| 270 |
+
torch.set_num_threads(a.threads)
|
| 271 |
+
os.chdir(work) # upstream reads "genesets/" and writes vaegan_train.txt relative to the cwd
|
| 272 |
+
event("start", run_signature=signature, code_signature=code_signature,
|
| 273 |
+
migrations=[m["transitions"] for m in migrations], device=a.device, host=os.uname().nodename)
|
| 274 |
+
try:
|
| 275 |
+
# ------------------------------------------------------------------ prepare (CPU)
|
| 276 |
+
prep = work / "prepared.json"
|
| 277 |
+
if a.phase == "prepare":
|
| 278 |
+
if prep.exists():
|
| 279 |
+
event("prepare_already_done")
|
| 280 |
+
status()
|
| 281 |
+
return 0
|
| 282 |
+
if project.exists():
|
| 283 |
+
raise SystemExit("partial upstream project without prepared.json; preserve and inspect")
|
| 284 |
+
gdir = work / "genesets"
|
| 285 |
+
gdir.mkdir(exist_ok=True)
|
| 286 |
+
shutil.copyfile(gmt_src, gdir / "c2.cp.v7.4.symbols.gmt")
|
| 287 |
+
t0 = time.monotonic()
|
| 288 |
+
P = protocol["initsetup"]
|
| 289 |
+
scSemiProfiler.initsetup(str(project), str(inputs / "bulk.h5ad"), logged=P["logged"], normed=P["normed"],
|
| 290 |
+
geneselection=P["geneselection"], batch=P["batch"])
|
| 291 |
+
if not (project / "processed_bulkdata.h5ad").exists():
|
| 292 |
+
raise SystemExit("upstream initsetup did not write processed_bulkdata.h5ad")
|
| 293 |
+
sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
|
| 294 |
+
if sids != sids_expected:
|
| 295 |
+
raise SystemExit("upstream sids.txt differs from the input bulk order")
|
| 296 |
+
rep_idx = [sids.index(r) for r in reps]
|
| 297 |
+
scSemiProfiler.set_representatives(str(project), rep_idx)
|
| 298 |
+
bulk = anndata.read_h5ad(project / "processed_bulkdata.h5ad")
|
| 299 |
+
pca = np.asarray(bulk.obsm["X_pca"], dtype=np.float64)
|
| 300 |
+
labels = update_membership(reduced_bulk=pca, representatives=rep_idx)
|
| 301 |
+
(project / "status/init_cluster_labels.txt").write_text("".join(f"{int(x)}\n" for x in labels))
|
| 302 |
+
dist = np.sqrt(((pca[:, None, :] - pca[rep_idx][None, :, :]) ** 2).sum(-1))
|
| 303 |
+
assign = {t: {"representative": reps[int(labels[sids.index(t)])],
|
| 304 |
+
"distances": {reps[i]: float(dist[sids.index(t), i]) for i in range(len(reps))}} for t in targets}
|
| 305 |
+
for i, r in enumerate(reps):
|
| 306 |
+
if int(labels[sids.index(r)]) != i:
|
| 307 |
+
raise SystemExit(f"representative {r} not assigned to itself")
|
| 308 |
+
write_json(work / "assignment.json", {"rule": protocol["assignment"], "n_pca_components": int(pca.shape[1]),
|
| 309 |
+
"bulk_row_order": sids, "representative_indices": rep_idx,
|
| 310 |
+
"targets": assign,
|
| 311 |
+
"targets_per_representative": {r: sum(v["representative"] == r for v in assign.values()) for r in reps}})
|
| 312 |
+
del bulk
|
| 313 |
+
S = protocol["scprocess"]
|
| 314 |
+
import scSemiProfiler.singlecell_process as upstream_sp
|
| 315 |
+
sys.path.insert(0, str(HERE / "tools"))
|
| 316 |
+
from lean_cellgraph import fast_cellgraph_lean
|
| 317 |
+
upstream_sp.fast_cellgraph = fast_cellgraph_lean # resolved from module globals inside scprocess
|
| 318 |
+
if S["logged"] or S["normed"] or S["cellfilter"] or S["geneset"] is not True:
|
| 319 |
+
raise SystemExit("cohort_hvset replicates the logged=False, normed=False, cellfilter=False, geneset=True path only")
|
| 320 |
+
(project / "geneset_scores").mkdir(exist_ok=True)
|
| 321 |
+
cohort_hvset(project, inputs / "rep_sc.h5ad", S["threshold"])
|
| 322 |
+
event("cohort_hvset_done")
|
| 323 |
+
R = anndata.read_h5ad(inputs / "rep_sc.h5ad")
|
| 324 |
+
per_rep = work / "inputs_per_rep"
|
| 325 |
+
per_rep.mkdir(exist_ok=True)
|
| 326 |
+
for r in reps:
|
| 327 |
+
f_r = per_rep / f"{r}.h5ad"
|
| 328 |
+
R[(R.obs["sample_ids"] == r).to_numpy()].copy().write_h5ad(f_r)
|
| 329 |
+
scSemiProfiler.scprocess(str(project), str(f_r), logged=S["logged"], normed=S["normed"],
|
| 330 |
+
cellfilter=S["cellfilter"], threshold=S["threshold"], geneset=S["geneset"],
|
| 331 |
+
weight=S["weight"], k=S["k"])
|
| 332 |
+
f_r.unlink()
|
| 333 |
+
gc.collect()
|
| 334 |
+
per_rep.rmdir()
|
| 335 |
+
del R
|
| 336 |
+
genes = man["modeled_genes"]["gene_ids"]
|
| 337 |
+
if np.load(project / "hvgenes.npy", allow_pickle=True).astype(str).tolist() != genes:
|
| 338 |
+
raise SystemExit("upstream altered the modeled gene axis")
|
| 339 |
+
hvset = np.load(project / "hvset.npy", allow_pickle=False).astype(bool)
|
| 340 |
+
if hvset.shape != (2922,) or not hvset.any():
|
| 341 |
+
raise SystemExit("no variable gene-set features selected; refuse silent no-geneset fallback")
|
| 342 |
+
qc = {"selected_gene_sets": int(hvset.sum()), "reps": {}}
|
| 343 |
+
for r in reps:
|
| 344 |
+
f_sc, f_gs = project / "sample_sc" / f"{r}.h5ad", project / "geneset_scores" / f"{r}.npy"
|
| 345 |
+
if not f_sc.exists() or not f_gs.exists():
|
| 346 |
+
raise SystemExit(f"upstream scprocess did not write {r}")
|
| 347 |
+
g = np.load(f_gs, allow_pickle=False)
|
| 348 |
+
if not np.isfinite(g).all() or (g < 0).any():
|
| 349 |
+
raise SystemExit(f"{r}: non-finite / negative gene-set scores")
|
| 350 |
+
h = anndata.read_h5ad(f_sc, backed="r")
|
| 351 |
+
X = np.asarray(h.X[:])
|
| 352 |
+
n_feat = len(h.uns["feature_var"])
|
| 353 |
+
if h.var_names.astype(str).tolist() != genes or n_feat != len(genes) + int(hvset.sum()):
|
| 354 |
+
raise SystemExit(f"{r}: prepared axis / feature variance length mismatch")
|
| 355 |
+
glib = X.sum(1)
|
| 356 |
+
slib = g[:, hvset].sum(1)
|
| 357 |
+
h.file.close()
|
| 358 |
+
if g.shape[0] != X.shape[0]:
|
| 359 |
+
raise SystemExit(f"{r}: gene-set score rows differ from cells")
|
| 360 |
+
if (glib <= 0).any() or (slib <= 0).any():
|
| 361 |
+
raise SystemExit(f"{r}: {int((glib <= 0).sum())} cells with empty thresholded gene library, "
|
| 362 |
+
f"{int((slib <= 0).sum())} with empty selected gene-set library (log would be -inf)")
|
| 363 |
+
qc["reps"][r] = {"n_cells": int(X.shape[0]), "median_thresholded_gene_library": float(np.median(glib)),
|
| 364 |
+
"median_nonzero_genes": float(np.median((X > 0).sum(1))),
|
| 365 |
+
"zero_score_pathways": int(np.all(g == 0, axis=0).sum())}
|
| 366 |
+
del X, g
|
| 367 |
+
files = ["processed_bulkdata.h5ad", "hvgenes.npy", "sids.txt", "hvset.npy", "hvmask.npy",
|
| 368 |
+
"status/init_representatives.txt", "status/init_cluster_labels.txt"]
|
| 369 |
+
files += [f"sample_sc/{r}.h5ad" for r in reps] + [f"geneset_scores/{r}.npy" for r in reps]
|
| 370 |
+
write_json(work / "geneset_feature_qc.json", {"run_signature": signature, **qc})
|
| 371 |
+
write_json(prep, {"run_signature": signature, "seconds": round(time.monotonic() - t0, 1),
|
| 372 |
+
"files": {f: sha256(project / f) for f in files},
|
| 373 |
+
"genesets_gmt_sha256": sha256(gdir / "c2.cp.v7.4.symbols.gmt")})
|
| 374 |
+
event("prepared", seconds=round(time.monotonic() - t0, 1), selected_gene_sets=int(hvset.sum()))
|
| 375 |
+
status()
|
| 376 |
+
return 0
|
| 377 |
+
|
| 378 |
+
# ------------------------------------------------------------------ GPU phases
|
| 379 |
+
if not prep.exists():
|
| 380 |
+
raise SystemExit("run --phase prepare first")
|
| 381 |
+
prepared = json.loads(prep.read_text())
|
| 382 |
+
if prepared["run_signature"] != signature:
|
| 383 |
+
raise SystemExit("prepared.json belongs to another run signature")
|
| 384 |
+
for name, digest in prepared["files"].items():
|
| 385 |
+
if name.startswith("sample_sc/"):
|
| 386 |
+
continue # large; verified per representative when used
|
| 387 |
+
if sha256(project / name) != digest:
|
| 388 |
+
raise SystemExit(f"prepared file changed: {name}")
|
| 389 |
+
sids = [x.strip() for x in (project / "sids.txt").read_text().splitlines() if x.strip()]
|
| 390 |
+
assign = json.loads((work / "assignment.json").read_text())["targets"]
|
| 391 |
+
for sub in ("models", "history", "tmp", "inferreddata"):
|
| 392 |
+
(project / sub).mkdir(exist_ok=True)
|
| 393 |
+
verified_sc: set[str] = set()
|
| 394 |
+
|
| 395 |
+
def verify_sc(r: str) -> None:
|
| 396 |
+
if r not in verified_sc:
|
| 397 |
+
if sha256(project / f"sample_sc/{r}.h5ad") != prepared["files"][f"sample_sc/{r}.h5ad"]:
|
| 398 |
+
raise SystemExit(f"prepared sample_sc/{r}.h5ad changed")
|
| 399 |
+
verified_sc.add(r)
|
| 400 |
+
|
| 401 |
+
def ckpt_ok(path: Path) -> bool:
|
| 402 |
+
rp = path.with_name(path.name + ".receipt.json")
|
| 403 |
+
if not path.exists():
|
| 404 |
+
if rp.exists():
|
| 405 |
+
raise SystemExit(f"receipt without checkpoint: {rp}")
|
| 406 |
+
return False
|
| 407 |
+
if not rp.exists():
|
| 408 |
+
raise SystemExit(f"unreceipted checkpoint {path}; preserve and inspect")
|
| 409 |
+
rec = json.loads(rp.read_text())
|
| 410 |
+
if rec["run_signature"] != signature or rec["sha256"] != sha256(path):
|
| 411 |
+
raise SystemExit(f"checkpoint receipt mismatch: {path}")
|
| 412 |
+
return True
|
| 413 |
+
|
| 414 |
+
def shim(state_path: Path):
|
| 415 |
+
sd = torch.load(state_path, map_location=a.device, weights_only=True)
|
| 416 |
+
return types.SimpleNamespace(module=types.SimpleNamespace(state_dict=lambda: sd))
|
| 417 |
+
|
| 418 |
+
if a.phase == "pretrain":
|
| 419 |
+
P1, P2 = protocol["pretrain1"], protocol["pretrain2"]
|
| 420 |
+
n_done = 0
|
| 421 |
+
for r in reps:
|
| 422 |
+
c1 = project / "models" / f"fast_reconst1_{r}"
|
| 423 |
+
c2 = project / "models" / f"fastreconst2_{r}"
|
| 424 |
+
ok1, ok2 = ckpt_ok(c1), ckpt_ok(c2)
|
| 425 |
+
if ok1 and ok2:
|
| 426 |
+
continue
|
| 427 |
+
if a.max_reps and n_done >= a.max_reps:
|
| 428 |
+
break
|
| 429 |
+
verify_sc(r)
|
| 430 |
+
idx = sids.index(r)
|
| 431 |
+
model1 = None
|
| 432 |
+
if not ok1:
|
| 433 |
+
scvi.settings.seed = SEED + 1000 + idx
|
| 434 |
+
event("pretrain_start", stage=1, representative=r, seed=SEED + 1000 + idx)
|
| 435 |
+
t0 = time.monotonic()
|
| 436 |
+
model1 = fastrecon(str(project), r, device=a.device, k=P1["k"], diagw=P1["diagw"],
|
| 437 |
+
vaesteps=P1["vaesteps"], gansteps=P1["gansteps"], lr=P1["lr"])
|
| 438 |
+
el = time.monotonic() - t0
|
| 439 |
+
write_json(c1.with_name(c1.name + ".receipt.json"), {"run_signature": signature, "sha256": sha256(c1),
|
| 440 |
+
"stage": 1, "representative": r, "seed": SEED + 1000 + idx, "elapsed_seconds": el,
|
| 441 |
+
"code_signature": code_signature,
|
| 442 |
+
"device": a.device, "complete": True})
|
| 443 |
+
event("pretrain_complete", stage=1, representative=r, elapsed_seconds=round(el, 1))
|
| 444 |
+
if not ok2:
|
| 445 |
+
pre = model1 if model1 is not None else shim(c1)
|
| 446 |
+
scvi.settings.seed = SEED + 2000 + idx
|
| 447 |
+
event("pretrain_start", stage=2, representative=r, seed=SEED + 2000 + idx)
|
| 448 |
+
t0 = time.monotonic()
|
| 449 |
+
model2 = reconst_pretrain2(str(project), r, pre, device=a.device, k=P2["k"], diagw=P2["diagw"],
|
| 450 |
+
vaesteps=P2["vaesteps"], gansteps=P2["gansteps"], lr=P2["lr"])
|
| 451 |
+
el = time.monotonic() - t0
|
| 452 |
+
write_json(c2.with_name(c2.name + ".receipt.json"), {"run_signature": signature, "sha256": sha256(c2),
|
| 453 |
+
"stage": 2, "representative": r, "seed": SEED + 2000 + idx, "elapsed_seconds": el,
|
| 454 |
+
"code_signature": code_signature,
|
| 455 |
+
"device": a.device, "complete": True})
|
| 456 |
+
event("pretrain_complete", stage=2, representative=r, elapsed_seconds=round(el, 1))
|
| 457 |
+
del model2
|
| 458 |
+
del model1
|
| 459 |
+
gc.collect()
|
| 460 |
+
if a.device.startswith("cuda"):
|
| 461 |
+
torch.cuda.empty_cache()
|
| 462 |
+
n_done += 1
|
| 463 |
+
st = status()
|
| 464 |
+
event("pretrain_call_done", reps_this_call=n_done, **{k: st[k] for k in ("reps_pretrained", "n_reps")})
|
| 465 |
+
return 0
|
| 466 |
+
|
| 467 |
+
if a.phase == "infer":
|
| 468 |
+
I = protocol["infer"]
|
| 469 |
+
missing = [r for r in reps if not (ckpt_ok(project / "models" / f"fast_reconst1_{r}")
|
| 470 |
+
and ckpt_ok(project / "models" / f"fastreconst2_{r}"))]
|
| 471 |
+
if missing:
|
| 472 |
+
raise SystemExit(f"pretraining incomplete for {missing}")
|
| 473 |
+
shards = work / "shards"
|
| 474 |
+
shards.mkdir(exist_ok=True)
|
| 475 |
+
genelen = len(man["modeled_genes"]["gene_ids"])
|
| 476 |
+
n_done = 0
|
| 477 |
+
for t in targets:
|
| 478 |
+
rec_path = shards / f"{t}.json"
|
| 479 |
+
shard = shards / f"{t}.npz"
|
| 480 |
+
if rec_path.exists():
|
| 481 |
+
rec = json.loads(rec_path.read_text())
|
| 482 |
+
if rec["run_signature"] != signature or rec["shard_sha256"] != sha256(shard):
|
| 483 |
+
raise SystemExit(f"target shard receipt mismatch: {t}")
|
| 484 |
+
continue
|
| 485 |
+
if shard.exists():
|
| 486 |
+
raise SystemExit(f"shard without receipt: {shard}; preserve and inspect")
|
| 487 |
+
if a.max_targets and n_done >= a.max_targets:
|
| 488 |
+
break
|
| 489 |
+
r = assign[t]["representative"]
|
| 490 |
+
verify_sc(r)
|
| 491 |
+
upstream = project / "inferreddata" / f"{r}_to_{t}.npy"
|
| 492 |
+
if upstream.exists():
|
| 493 |
+
raise SystemExit(f"unreceipted upstream output {upstream}; preserve and inspect")
|
| 494 |
+
rid, tid = sids.index(r), sids.index(t)
|
| 495 |
+
scvi.settings.seed = SEED + tid
|
| 496 |
+
event("target_start", sample_id=t, representative=r, seed=SEED + tid)
|
| 497 |
+
t0 = time.monotonic()
|
| 498 |
+
fast_semi(str(project), rid, tid, str(project / "models" / f"fastreconst2_{r}"), device=a.device,
|
| 499 |
+
k=I["k"], diagw=I["diagw"], bulktype=I["bulktype"], pseudocount=I["pseudocount"], lr=I["lr"],
|
| 500 |
+
epochs=I["epochs"], ministages=I["ministages"])
|
| 501 |
+
elapsed = time.monotonic() - t0
|
| 502 |
+
M = np.load(upstream, allow_pickle=False)
|
| 503 |
+
n_rep_cells = json.loads((work / "geneset_feature_qc.json").read_text())["reps"][r]["n_cells"]
|
| 504 |
+
if M.shape != (n_rep_cells, genelen) or not np.isfinite(M).all() or (M < 0).any():
|
| 505 |
+
raise SystemExit(f"{t}: invalid upstream output {M.shape} (expected {(n_rep_cells, genelen)})")
|
| 506 |
+
C = sp.csr_matrix(M)
|
| 507 |
+
tmp = shards / f"{t}.tmp.npz"
|
| 508 |
+
sp.save_npz(tmp, C, compressed=False)
|
| 509 |
+
back = sp.load_npz(tmp).toarray()
|
| 510 |
+
if back.dtype != M.dtype or not np.array_equal(back, M):
|
| 511 |
+
raise SystemExit(f"{t}: CSR re-encoding is not lossless")
|
| 512 |
+
tmp.replace(shard)
|
| 513 |
+
lib = M.sum(1)
|
| 514 |
+
rec = {"sample_id": t, "representative": r, "rep_bulk_index": rid, "target_bulk_index": tid,
|
| 515 |
+
"seed": SEED + tid, "elapsed_seconds": elapsed, "device": a.device, "run_signature": signature,
|
| 516 |
+
"code_signature": code_signature,
|
| 517 |
+
"shape": list(M.shape), "dtype": str(M.dtype), "nnz": int(C.nnz),
|
| 518 |
+
"zero_fraction": float(1 - C.nnz / M.size), "zero_rows": int((lib == 0).sum()),
|
| 519 |
+
"mean_library_normalized": float(lib.mean()), "matrix_unit": "normalized_expression",
|
| 520 |
+
"upstream_npy": str(upstream), "upstream_npy_sha256": sha256(upstream),
|
| 521 |
+
"shard": str(shard), "shard_sha256": sha256(shard), "lossless_csr_verified": True,
|
| 522 |
+
"upstream_npy_removed": True, "created_at": datetime.now(timezone.utc).isoformat(), "complete": True}
|
| 523 |
+
write_json(rec_path, rec)
|
| 524 |
+
upstream.unlink() # dense copy of a verified lossless shard (disk)
|
| 525 |
+
del M, C, back
|
| 526 |
+
gc.collect()
|
| 527 |
+
n_done += 1
|
| 528 |
+
event("target_complete", sample_id=t, representative=r, elapsed_seconds=round(elapsed, 2),
|
| 529 |
+
zero_rows=rec["zero_rows"], zero_fraction=round(rec["zero_fraction"], 4))
|
| 530 |
+
st = status()
|
| 531 |
+
event("infer_call_done", targets_this_call=n_done, **{k: st[k] for k in ("targets_done", "n_targets")})
|
| 532 |
+
return 0
|
| 533 |
+
except BaseException as exc:
|
| 534 |
+
event("failed", error_type=type(exc).__name__, message=str(exc)[:2000])
|
| 535 |
+
raise
|
| 536 |
+
return 0
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
if __name__ == "__main__":
|
| 540 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/scan_trailing_batch.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Scan every representative of every split for a size-1 trailing training batch (CPU only, reads files only).
|
| 3 |
+
|
| 4 |
+
Upstream training batch sizes (vendor c2aea02):
|
| 5 |
+
pretrain 1 + 2 : vaegan.fastgenerator.train() default batch_size 128 (fastrecon / reconst_pretrain2 pass none)
|
| 6 |
+
inference : fast_semi batch_size = min(n, 9000), 5 ministages, same train(); final sampling loader same size
|
| 7 |
+
A split crashes (BatchNorm1d in training mode, 1 sample) when n % 128 == 1, or n > 9000 and n % 9000 == 1.
|
| 8 |
+
Cell counts: the split's inputs_manifest.json when it exists on this host (prepared), else the data files
|
| 9 |
+
(data/<ds>/cells_panel6k.npz row_sample over the split's representative rows, same rule as prepare_draw_inputs.py).
|
| 10 |
+
usage: scan_trailing_batch.py OUT.json [--cv]
|
| 11 |
+
"""
|
| 12 |
+
import json
|
| 13 |
+
import sys
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import numpy as np
|
| 17 |
+
import pandas as pd
|
| 18 |
+
|
| 19 |
+
T = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paired_finetune_intradataset_20260927")
|
| 20 |
+
S = T / "scsemi"
|
| 21 |
+
DS = ["ji2025_chili", "giroux2022", "ye2026_sepsis", "immicro", "imperial_eskd"]
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def reps_from_data(ds, mode, j):
|
| 25 |
+
d = T / "data" / ds
|
| 26 |
+
if not (d / "folds.csv").exists() or not (d / "cells_panel6k.npz").exists():
|
| 27 |
+
return None
|
| 28 |
+
f = pd.read_csv(d / "folds.csv")
|
| 29 |
+
n = np.bincount(np.load(d / "cells_panel6k.npz")["row_sample"], minlength=len(f))
|
| 30 |
+
if mode == "fewshot":
|
| 31 |
+
tr = [x.strip() for x in (d / "fewshot_n5" / f"draw{j}" / "train_donors.txt").read_text().splitlines() if x.strip()]
|
| 32 |
+
m = f.donor_id.astype(str).isin(tr) & (f.fold >= 0)
|
| 33 |
+
else:
|
| 34 |
+
m = (f.fold >= 0) & (f.fold != j)
|
| 35 |
+
return {str(s): int(c) for s, c in zip(f.sample_id[m], n[m.to_numpy()])}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def main():
|
| 39 |
+
out, cv = Path(sys.argv[1]), "--cv" in sys.argv
|
| 40 |
+
rows = []
|
| 41 |
+
for ds in DS:
|
| 42 |
+
for mode in (["fewshot", "cv"] if cv else ["fewshot"]):
|
| 43 |
+
for j in range(5):
|
| 44 |
+
w = S / "work" / ds / ("fewshot_n5" if mode == "fewshot" else "cv") / (f"draw{j}" if mode == "fewshot" else f"fold{j}")
|
| 45 |
+
man = w / "inputs/inputs_manifest.json"
|
| 46 |
+
if man.exists():
|
| 47 |
+
reps, src = {r["sample_id"]: r["n_cells"] for r in json.loads(man.read_text())["representatives"]}, "inputs_manifest"
|
| 48 |
+
else:
|
| 49 |
+
reps, src = reps_from_data(ds, mode, j), "data"
|
| 50 |
+
if reps is None:
|
| 51 |
+
continue
|
| 52 |
+
for r, n in reps.items():
|
| 53 |
+
pre = n % 128 == 1
|
| 54 |
+
inf = n > 9000 and n % 9000 == 1
|
| 55 |
+
rows.append({"dataset": ds, "mode": mode, "split": j, "representative": r, "n_cells": n,
|
| 56 |
+
"n_mod_128": n % 128, "pretrain_size1_batch": pre, "inference_size1_batch": inf,
|
| 57 |
+
"source": src})
|
| 58 |
+
df = pd.DataFrame(rows)
|
| 59 |
+
hit = df[df.pretrain_size1_batch | df.inference_size1_batch]
|
| 60 |
+
res = {"host_rows": len(df), "affected": hit.to_dict("records"),
|
| 61 |
+
"affected_splits": sorted({f"{r['mode']}|{r['dataset']}|{r['split']}" for r in hit.to_dict("records")}),
|
| 62 |
+
"splits_scanned": int(df.groupby(["dataset", "mode", "split"]).ngroups),
|
| 63 |
+
"representatives_scanned": len(df), "min_mod_128_nonzero": int(df.n_mod_128[df.n_mod_128 > 0].min())}
|
| 64 |
+
out.write_text(json.dumps(res, indent=1) + "\n")
|
| 65 |
+
print(json.dumps({k: res[k] for k in ("splits_scanned", "representatives_scanned", "affected_splits")}))
|
| 66 |
+
for r in res["affected"]:
|
| 67 |
+
print(r)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
if __name__ == "__main__":
|
| 71 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/validate_export.py
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Independent check of one exported scSemiProfiler NPZ against its shards, inputs and receipt (CPU only).
|
| 3 |
+
|
| 4 |
+
Recomputes every output row from the lossless target shards (source_row, depth, modeled columns) without importing
|
| 5 |
+
export_npz.py, and checks the receipt sha, the scorer's contract (gene_ids == 6k panel, generated_counts,
|
| 6 |
+
sample_ids, bulk_index, metadata_json.input_condition_path -> condition NPZ with those samples), shapes, gene order,
|
| 7 |
+
finiteness, non-negativity and per-target cell counts. Writes <npz stem>.validation.json; exit 1 on any failure.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import sys
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 19 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import pandas as pd
|
| 23 |
+
import scipy.sparse as sp
|
| 24 |
+
|
| 25 |
+
PANEL = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv")
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def sha(path: Path) -> str:
|
| 29 |
+
h = hashlib.sha256()
|
| 30 |
+
with open(path, "rb") as f:
|
| 31 |
+
for block in iter(lambda: f.read(1 << 24), b""):
|
| 32 |
+
h.update(block)
|
| 33 |
+
return h.hexdigest()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def main(argv=None) -> int:
|
| 37 |
+
ap = argparse.ArgumentParser()
|
| 38 |
+
ap.add_argument("--work", type=Path, required=True)
|
| 39 |
+
ap.add_argument("--npz", type=Path, required=True)
|
| 40 |
+
a = ap.parse_args(argv)
|
| 41 |
+
work, npz = a.work.resolve(), a.npz.resolve()
|
| 42 |
+
fails: list[str] = []
|
| 43 |
+
|
| 44 |
+
def check(ok: bool, msg: str) -> None:
|
| 45 |
+
if not ok:
|
| 46 |
+
fails.append(msg)
|
| 47 |
+
|
| 48 |
+
rec = json.loads(npz.with_suffix(".log").read_text())
|
| 49 |
+
check(rec["output_sha256"] == sha(npz), "receipt output_sha256 != NPZ sha256")
|
| 50 |
+
man = json.loads((work / "inputs/inputs_manifest.json").read_text())
|
| 51 |
+
run = json.loads((work / "run_manifest.json").read_text())
|
| 52 |
+
panel = pd.read_csv(PANEL).gene_id.astype(str).to_numpy()
|
| 53 |
+
d = np.load(npz, allow_pickle=False)
|
| 54 |
+
need = {"generated_counts", "gene_ids", "sample_ids", "bulk_index", "metadata_json"}
|
| 55 |
+
check(need <= set(d.files), f"missing keys {need - set(d.files)}")
|
| 56 |
+
G = d["generated_counts"]
|
| 57 |
+
ids = d["sample_ids"].astype(str)
|
| 58 |
+
bi = d["bulk_index"].astype(np.int64)
|
| 59 |
+
src = d["source_row"].astype(np.int64)
|
| 60 |
+
meta = json.loads(str(d["metadata_json"]))
|
| 61 |
+
check(np.array_equal(d["gene_ids"].astype(str), panel), "gene_ids differ from the 6k panel (order)")
|
| 62 |
+
check(G.dtype == np.float32 and G.ndim == 2 and G.shape[1] == 6000, f"generated_counts {G.dtype} {G.shape}")
|
| 63 |
+
check(G.shape[0] == ids.size * 1500 and bi.size == G.shape[0] and src.size == G.shape[0], "row counts")
|
| 64 |
+
check(np.array_equal(np.bincount(bi, minlength=ids.size), np.full(ids.size, 1500)), "1500 cells per target")
|
| 65 |
+
check(bool(np.isfinite(G).all()) and bool((G >= 0).all()), "non-finite or negative values")
|
| 66 |
+
check(sorted(ids.tolist()) == sorted(man["target_order_test_samples"]), "sample_ids differ from the targets")
|
| 67 |
+
cond = Path(meta["input_condition_path"])
|
| 68 |
+
check(cond.is_file() and sha(cond) == meta["input_condition_sha256"], "condition NPZ missing or sha differs")
|
| 69 |
+
with np.load(cond, allow_pickle=False) as cz:
|
| 70 |
+
cids = set(cz["sample_ids"].astype(str).tolist())
|
| 71 |
+
check(set(ids.tolist()) <= cids, "condition NPZ lacks some targets (broadcast baseline would fail)")
|
| 72 |
+
pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
|
| 73 |
+
check(np.array_equal(panel[pidx], np.asarray(man["modeled_genes"]["gene_ids"])), "modeled genes / panel columns")
|
| 74 |
+
other = np.setdiff1d(np.arange(6000), pidx)
|
| 75 |
+
check(not G[:, other].any(), "non-zero values outside the modeled genes")
|
| 76 |
+
depth = float(man["depth"]["value"])
|
| 77 |
+
assigned = json.loads((work / "assignment.json").read_text())["targets"]
|
| 78 |
+
max_abs = 0.0
|
| 79 |
+
for i, t in enumerate(ids):
|
| 80 |
+
r = json.loads((work / "shards" / f"{t}.json").read_text())
|
| 81 |
+
shard = work / "shards" / f"{t}.npz"
|
| 82 |
+
check(r["run_signature"] == run["run_signature"] and r["shard_sha256"] == sha(shard), f"{t}: shard receipt")
|
| 83 |
+
C = sp.load_npz(shard).tocsr()
|
| 84 |
+
rows = src[bi == i]
|
| 85 |
+
n = C.shape[0]
|
| 86 |
+
check(rows.min() >= 0 and rows.max() < n, f"{t}: source rows out of range")
|
| 87 |
+
mult = np.bincount(rows, minlength=n)
|
| 88 |
+
if n >= 1500:
|
| 89 |
+
check(mult.max() == 1, f"{t}: duplicates although n_rep >= 1500")
|
| 90 |
+
else:
|
| 91 |
+
check(mult.min() >= 1500 // n and mult.max() <= -(-1500 // n), f"{t}: uneven reuse")
|
| 92 |
+
X = C[rows].toarray().astype(np.float64)
|
| 93 |
+
lib = X.sum(1)
|
| 94 |
+
want = np.zeros_like(X)
|
| 95 |
+
want[lib > 0] = X[lib > 0] / lib[lib > 0, None] * depth
|
| 96 |
+
got = G[bi == i][:, pidx].astype(np.float64)
|
| 97 |
+
max_abs = max(max_abs, float(np.abs(got - want).max()))
|
| 98 |
+
check(np.allclose(got, want, rtol=1e-5, atol=1e-4), f"{t}: values differ from the shard recomputation")
|
| 99 |
+
check(r["representative"] == assigned[t]["representative"], f"{t}: representative differs from assignment.json")
|
| 100 |
+
out = {"npz": str(npz), "npz_sha256": rec["output_sha256"], "targets": int(ids.size), "cells": int(G.shape[0]),
|
| 101 |
+
"modeled_genes": int(pidx.size), "depth": depth, "max_abs_diff_vs_recomputation": max_abs,
|
| 102 |
+
"run_signature": run["run_signature"], "passed": not fails, "failures": fails}
|
| 103 |
+
npz.with_suffix(".validation.json").write_text(json.dumps(out, indent=1) + "\n")
|
| 104 |
+
print(json.dumps({k: out[k] for k in ("targets", "cells", "modeled_genes", "depth", "max_abs_diff_vs_recomputation", "passed")}))
|
| 105 |
+
if fails:
|
| 106 |
+
print("\n".join(fails), file=sys.stderr)
|
| 107 |
+
return 1
|
| 108 |
+
return 0
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
if __name__ == "__main__":
|
| 112 |
+
sys.exit(main())
|
paper-releases/pbisc-diffusion/updates/20260928T225702Z-paired-ft-scsemi-delta/diffusion/dataset/server_1/model8/plans/paired_finetune_intradataset_20260927/scsemi/tools/verify_lean_cellgraph.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
"""Bit-identity check: upstream fast_cellgraph vs tools/lean_cellgraph.fast_cellgraph_lean (CPU only).
|
| 3 |
+
|
| 4 |
+
Each representative's cells are prepared exactly as upstream scprocess does before calling fast_cellgraph
|
| 5 |
+
(normalize_total 1e4, dense, background removal X * (X > 10), obs['cellidx']), then both functions run on copies.
|
| 6 |
+
Compared bitwise: obs['selfw'], obsm['adj'], obsm['neighbors'], obsm['neighborx'] (dtype and values) and the returned
|
| 7 |
+
adjacency tensor. A synthetic case (n = 1025, so the last 1024-row chunk holds one row) is always included.
|
| 8 |
+
Writes --out JSON; exit 1 on any difference.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import resource
|
| 16 |
+
import sys
|
| 17 |
+
import time
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
|
| 20 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 21 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 22 |
+
|
| 23 |
+
import anndata
|
| 24 |
+
import numpy as np
|
| 25 |
+
import scanpy as sc
|
| 26 |
+
import scipy.sparse as sp
|
| 27 |
+
|
| 28 |
+
HERE = Path(__file__).resolve().parents[1]
|
| 29 |
+
sys.path.insert(0, str(HERE / "vendor/scSemiProfiler"))
|
| 30 |
+
sys.path.insert(0, str(HERE / "tools"))
|
| 31 |
+
from scSemiProfiler.singlecell_process import fast_cellgraph # noqa: E402
|
| 32 |
+
from lean_cellgraph import fast_cellgraph_lean # noqa: E402
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def same(a, b) -> bool:
|
| 36 |
+
a, b = np.asarray(a), np.asarray(b)
|
| 37 |
+
return a.dtype == b.dtype and a.shape == b.shape and bool(np.array_equal(a, b))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def compare(ad: anndata.AnnData, k: int = 15) -> dict:
|
| 41 |
+
t0 = time.monotonic()
|
| 42 |
+
a1, t1 = fast_cellgraph(ad.copy(), k=k, diagw=1.0)
|
| 43 |
+
s1 = time.monotonic() - t0
|
| 44 |
+
t0 = time.monotonic()
|
| 45 |
+
a2, t2 = fast_cellgraph_lean(ad.copy(), k=k, diagw=1.0)
|
| 46 |
+
s2 = time.monotonic() - t0
|
| 47 |
+
res = {"n_cells": int(ad.n_obs), "selfw": same(a1.obs["selfw"].to_numpy(), a2.obs["selfw"].to_numpy()),
|
| 48 |
+
"adj": same(a1.obsm["adj"], a2.obsm["adj"]), "neighbors": same(a1.obsm["neighbors"], a2.obsm["neighbors"]),
|
| 49 |
+
"neighborx": same(a1.obsm["neighborx"], a2.obsm["neighborx"]),
|
| 50 |
+
"adj_tensor": bool(t1.dtype == t2.dtype and t1.shape == t2.shape and bool((t1 == t2).all())),
|
| 51 |
+
"upstream_seconds": round(s1, 1), "lean_seconds": round(s2, 1)}
|
| 52 |
+
res["identical"] = all(res[x] for x in ("selfw", "adj", "neighbors", "neighborx", "adj_tensor"))
|
| 53 |
+
return res
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def prepared(X: sp.csr_matrix, genes: list[str]) -> anndata.AnnData:
|
| 57 |
+
ad = anndata.AnnData(X.astype(np.float32).tocsr())
|
| 58 |
+
ad.var_names = genes
|
| 59 |
+
sc.pp.normalize_total(ad, target_sum=1e4)
|
| 60 |
+
D = np.array(ad.X.todense())
|
| 61 |
+
D = D * np.array(D > 1e4 * 1e-3)
|
| 62 |
+
out = anndata.AnnData(D)
|
| 63 |
+
out.var_names = genes
|
| 64 |
+
out.obs["cellidx"] = range(out.n_obs)
|
| 65 |
+
return out
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def main(argv=None) -> int:
|
| 69 |
+
ap = argparse.ArgumentParser()
|
| 70 |
+
ap.add_argument("--rep-sc", type=Path, help="inputs/rep_sc.h5ad of a split")
|
| 71 |
+
ap.add_argument("--reps", default="", help="comma list (default: all representatives)")
|
| 72 |
+
ap.add_argument("--out", type=Path, required=True)
|
| 73 |
+
a = ap.parse_args(argv)
|
| 74 |
+
results = {}
|
| 75 |
+
rng = np.random.default_rng(20260927)
|
| 76 |
+
syn = sp.random(1025, 300, density=0.05, format="csr", random_state=rng, data_rvs=lambda n: rng.integers(1, 20, n))
|
| 77 |
+
results["synthetic_n1025"] = compare(prepared(syn, [f"g{i}" for i in range(300)]))
|
| 78 |
+
if a.rep_sc:
|
| 79 |
+
R = anndata.read_h5ad(a.rep_sc)
|
| 80 |
+
reps = a.reps.split(",") if a.reps else list(dict.fromkeys(R.obs["sample_ids"].astype(str)))
|
| 81 |
+
for r in reps:
|
| 82 |
+
m = (R.obs["sample_ids"].astype(str) == r).to_numpy()
|
| 83 |
+
results[r] = compare(prepared(R.X[m], list(R.var_names)))
|
| 84 |
+
print(r, results[r], flush=True)
|
| 85 |
+
ok = all(v["identical"] for v in results.values())
|
| 86 |
+
rec = {"rep_sc": str(a.rep_sc) if a.rep_sc else None, "all_identical": ok, "results": results,
|
| 87 |
+
"max_rss_gib": round(resource.getrusage(resource.RUSAGE_SELF).ru_maxrss / 2**20, 2)}
|
| 88 |
+
a.out.write_text(json.dumps(rec, indent=1) + "\n")
|
| 89 |
+
print(json.dumps({"all_identical": ok, "n": len(results)}))
|
| 90 |
+
return 0 if ok else 1
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
if __name__ == "__main__":
|
| 94 |
+
sys.exit(main())
|