Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_figure5.py +439 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_results_figures.py +1035 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_review_deck.py +280 -0
- paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/campaign.py +292 -0
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_figure5.py
ADDED
|
@@ -0,0 +1,439 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Build zero-aware Figure 5 data from marker caches (CPU only).
|
| 3 |
+
|
| 4 |
+
Usage:
|
| 5 |
+
CUDA_VISIBLE_DEVICES='' python tools/build_figure5.py --manifest path/to/rare_manifest.json
|
| 6 |
+
CUDA_VISIBLE_DEVICES='' python tools/build_figure5.py --legacy-diagnostic
|
| 7 |
+
|
| 8 |
+
Manifest: {"schema":"pbisc.figure5.marker-caches.v1","units":[{"cohort":"...",
|
| 9 |
+
"unit":"draw0","design":"strict5pair","train_sample_ids":[...],
|
| 10 |
+
"train_donor_ids":[...],"test_sample_ids":[...],
|
| 11 |
+
"sample_metadata":"...csv","support_manifest":".../support.json","observed_cache":"...npz",
|
| 12 |
+
"generated_caches":{"lora5":"...npz","scsemi5":"...npz"},
|
| 13 |
+
"cell_budget":500,"depth_target":1000}]}
|
| 14 |
+
Paths are relative to the manifest. Cache arrays: markers, marker_symbols, lib_measured,
|
| 15 |
+
sample_id (or legacy donor), aifi_l1, aifi_l2. All test samples and arms must be present.
|
| 16 |
+
"""
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import hashlib
|
| 21 |
+
import json
|
| 22 |
+
import os
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 26 |
+
raise SystemExit("Figure 5 requires CUDA_VISIBLE_DEVICES=''")
|
| 27 |
+
|
| 28 |
+
import numpy as np
|
| 29 |
+
import pandas as pd
|
| 30 |
+
import scipy.sparse as sp
|
| 31 |
+
|
| 32 |
+
from rare_metrics import (abundance_summary, aggregate_donors, bootstrap_mae,
|
| 33 |
+
call_marker_state, validate_design, validate_marker_coverage)
|
| 34 |
+
|
| 35 |
+
HERE = Path(__file__).resolve().parents[1]
|
| 36 |
+
M8 = HERE.parents[1]
|
| 37 |
+
OLD = M8 / "plans/rare_states_paired_20261008"
|
| 38 |
+
FT = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 39 |
+
STATES = M8 / "plans/rare_states_screen_20261004/tools/states.json"
|
| 40 |
+
COHORTS = ("ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 41 |
+
LEGACY_ARMS = ("zs_raw", "zs_cal", "scsemi5", "lora5")
|
| 42 |
+
STRICT_ARMS = frozenset(("lora", "pairedcal", "scsemi", "raw", "refcal"))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def require_complete_strict(units: list[dict]) -> None:
|
| 46 |
+
expected = {(c, f"draw{i}") for c in COHORTS for i in range(5)}
|
| 47 |
+
seen = [(u["cohort"], u["unit"]) for u in units]
|
| 48 |
+
if len(seen) != len(set(seen)):
|
| 49 |
+
raise ValueError("duplicate strict cohort/draw")
|
| 50 |
+
missing = expected - set(seen)
|
| 51 |
+
extra = set(seen) - expected
|
| 52 |
+
if missing or extra:
|
| 53 |
+
raise ValueError(f"missing strict cohort/draw units: {sorted(missing)}; extra: {sorted(extra)}")
|
| 54 |
+
for u in units:
|
| 55 |
+
if u.get("design") != "strict5pair":
|
| 56 |
+
raise ValueError("all final Figure 5 units must be strict5pair")
|
| 57 |
+
if set(u.get("generated_caches", {})) != STRICT_ARMS:
|
| 58 |
+
raise ValueError(f'{u["cohort"]} {u["unit"]}: strict arms must be {sorted(STRICT_ARMS)}')
|
| 59 |
+
if len({int(u["cell_budget"]) for u in units}) != 1:
|
| 60 |
+
raise ValueError("strict units have mixed cell_budget")
|
| 61 |
+
if len({float(u["depth_target"]) for u in units}) != 1:
|
| 62 |
+
raise ValueError("strict units have mixed depth_target")
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _seed(*parts: object) -> int:
|
| 66 |
+
return int.from_bytes(hashlib.sha256("|".join(map(str, parts)).encode()).digest()[:8], "little")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def _sha256(path: Path) -> str:
|
| 70 |
+
h = hashlib.sha256()
|
| 71 |
+
with path.open("rb") as f:
|
| 72 |
+
for block in iter(lambda: f.read(4 << 20), b""):
|
| 73 |
+
h.update(block)
|
| 74 |
+
return h.hexdigest()
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _load(path: Path) -> dict:
|
| 78 |
+
if not path.is_file():
|
| 79 |
+
raise FileNotFoundError(path)
|
| 80 |
+
with np.load(path, allow_pickle=False) as z:
|
| 81 |
+
d = {k: z[k] for k in ("markers", "marker_symbols", "lib_measured", "aifi_l1", "aifi_l2")}
|
| 82 |
+
d["sample_id"] = z["sample_id"] if "sample_id" in z else z["donor"]
|
| 83 |
+
if "receipt" in z:
|
| 84 |
+
d["receipt"] = str(z["receipt"])
|
| 85 |
+
n = len(d["sample_id"])
|
| 86 |
+
if d["markers"].shape != (n, len(d["marker_symbols"])) or any(
|
| 87 |
+
len(d[k]) != n for k in ("lib_measured", "aifi_l1", "aifi_l2")
|
| 88 |
+
):
|
| 89 |
+
raise ValueError(f"unaligned cache: {path}")
|
| 90 |
+
return d
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def validate_strict_cache(cache: dict, path: Path, unit: dict, arm: str, support_sha: str) -> None:
|
| 94 |
+
expected = unit.get("generated_cache_sha256", {}).get(arm)
|
| 95 |
+
if not expected or _sha256(path) != expected:
|
| 96 |
+
raise ValueError(f"{arm}: marker cache content hash mismatch or absent")
|
| 97 |
+
try:
|
| 98 |
+
rec = json.loads(cache["receipt"])
|
| 99 |
+
except (KeyError, TypeError, json.JSONDecodeError) as exc:
|
| 100 |
+
raise ValueError(f"{arm}: invalid marker cache receipt") from exc
|
| 101 |
+
fixed = {"schema": "pbisc.figure5.marker-cache.v1", "cohort": unit["cohort"],
|
| 102 |
+
"unit": f'{unit["unit"]}_n5', "arm": arm, "support_sha256": support_sha,
|
| 103 |
+
"poisson_seed": 20260916, "benchmark_umi_reproduced": True,
|
| 104 |
+
"cells": len(cache["sample_id"])}
|
| 105 |
+
for key, value in fixed.items():
|
| 106 |
+
if rec.get(key) != value:
|
| 107 |
+
raise ValueError(f"{arm}: marker cache receipt mismatch: {key}")
|
| 108 |
+
required_files = {"scoring_support": "scoring_support_sha256",
|
| 109 |
+
"score_summary": "score_summary_sha256",
|
| 110 |
+
"score_generated_cells": "score_generated_cells_sha256"}
|
| 111 |
+
for source, digest in required_files.items():
|
| 112 |
+
source_path = Path(rec.get(source, ""))
|
| 113 |
+
if not source_path.is_file() or _sha256(source_path) != rec.get(digest):
|
| 114 |
+
raise ValueError(f"{arm}: marker cache source hash mismatch: {source.replace('_', ' ')}")
|
| 115 |
+
labels = Path(rec.get("score_generated_cells", "")).parent / "labels/labels.parquet"
|
| 116 |
+
if not labels.is_file() or _sha256(labels) != rec.get("score_labels_sha256"):
|
| 117 |
+
raise ValueError(f"{arm}: marker cache labels hash mismatch")
|
| 118 |
+
summary = json.loads(Path(rec["score_summary"]).read_text())
|
| 119 |
+
binding_path = Path(rec["scoring_support"])
|
| 120 |
+
if binding_path.resolve() != (Path(rec["score_summary"]).parent.parent / "scoring_support.json").resolve():
|
| 121 |
+
raise ValueError(f"{arm}: scoring support path differs from score run")
|
| 122 |
+
binding = json.loads(binding_path.read_text())
|
| 123 |
+
expected_binding = {
|
| 124 |
+
"schema": "pbisc.paper.strict-score-binding.v1",
|
| 125 |
+
"support_sha256": support_sha,
|
| 126 |
+
"cohort": unit["cohort"],
|
| 127 |
+
"unit": f'{unit["unit"]}_n5',
|
| 128 |
+
"test_sample_ids": unit["test_sample_ids"],
|
| 129 |
+
"test_donor_ids": unit.get("test_donor_ids"),
|
| 130 |
+
}
|
| 131 |
+
# The frozen support's donor list is copied into the unit during validation below.
|
| 132 |
+
if any(binding.get(k) != v for k, v in expected_binding.items()):
|
| 133 |
+
raise ValueError(f"{arm}: scoring support binding mismatch")
|
| 134 |
+
scored = summary.get("per_arm", {}).get(arm, {})
|
| 135 |
+
if (summary.get("schema") != "paired_ft_scores.v1" or summary.get("dataset") != unit["cohort"] or
|
| 136 |
+
set(summary.get("donors", [])) != set(unit["test_sample_ids"]) or
|
| 137 |
+
scored.get("npz_sha256") != rec.get("generated_npz_sha256") or
|
| 138 |
+
Path(scored.get("npz", "")).resolve() != Path(rec.get("generated_npz", "")).resolve() or
|
| 139 |
+
scored.get("receipt_verified") is not True or
|
| 140 |
+
scored.get("poisson", {}).get("seed") != 20260916 or
|
| 141 |
+
scored.get("poisson", {}).get("rule") != "whole NPZ, rows in NPZ order"):
|
| 142 |
+
raise ValueError(f"{arm}: cache differs from score summary arm provenance")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _observed_legacy(cohort: str, states: list[dict]) -> dict:
|
| 146 |
+
"""Read the old cache source directly; avoid the old screen module's unrelated anndata import."""
|
| 147 |
+
panel_path = FT / "data" / cohort / "cells_panel6k.npz"
|
| 148 |
+
with np.load(panel_path, allow_pickle=False) as z:
|
| 149 |
+
matrix = sp.csr_matrix((z["data"], z["indices"], z["indptr"]), shape=tuple(z["shape"]))
|
| 150 |
+
panel = z["panel_gene_ids"].astype(str)
|
| 151 |
+
measured = z["panel_measured"].any(0)
|
| 152 |
+
canon = pd.read_csv(
|
| 153 |
+
Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/"
|
| 154 |
+
"strict_qc_v1_20260913/reference/canonical_genes.tsv"), sep="\t", dtype=str)
|
| 155 |
+
sym2id = dict(zip(canon.gene_symbol, canon.gene_id))
|
| 156 |
+
pos = {g: i for i, g in enumerate(panel)}
|
| 157 |
+
genes = list(dict.fromkeys(g for st in states for g in
|
| 158 |
+
(st.get("genes", []) + [v for group in st.get("require_any", []) for v in group]
|
| 159 |
+
+ st.get("exclude", []))))
|
| 160 |
+
symbols = [g for g in genes if sym2id.get(g) in pos and measured[pos[sym2id[g]]]]
|
| 161 |
+
cols = [pos[sym2id[g]] for g in symbols]
|
| 162 |
+
obs = pd.read_parquet(FT / "data" / cohort / "cells_obs.parquet", columns=["sample_id"])
|
| 163 |
+
lab = pd.read_parquet(FT / "scoring_cache" / cohort / "observed_labels/labels/labels.parquet",
|
| 164 |
+
columns=["sample_id", "aifi_l1", "aifi_l2"])
|
| 165 |
+
if len(lab) != matrix.shape[0] or not np.array_equal(lab.sample_id.astype(str), obs.sample_id.astype(str)):
|
| 166 |
+
raise ValueError(f"{cohort}: observed labels not aligned")
|
| 167 |
+
return dict(markers=matrix[:, cols].toarray().astype(np.int32),
|
| 168 |
+
marker_symbols=np.asarray(symbols),
|
| 169 |
+
lib_measured=np.asarray(matrix[:, np.flatnonzero(measured)].sum(1)).ravel(),
|
| 170 |
+
sample_id=obs.sample_id.astype(str).to_numpy(),
|
| 171 |
+
aifi_l1=lab.aifi_l1.astype(str).to_numpy(),
|
| 172 |
+
aifi_l2=lab.aifi_l2.astype(str).to_numpy())
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def _thin_subset(cache: dict, idx: np.ndarray, target: int, seed: int) -> dict:
|
| 176 |
+
rng = np.random.default_rng(seed)
|
| 177 |
+
idx = np.sort(rng.choice(idx, size=target, replace=False))
|
| 178 |
+
markers = cache["markers"][idx].astype(np.int64, copy=True)
|
| 179 |
+
libs = cache["lib_measured"][idx].astype(float)
|
| 180 |
+
return dict(markers=markers, libs=libs,
|
| 181 |
+
l1=cache["aifi_l1"][idx].astype(str), l2=cache["aifi_l2"][idx].astype(str))
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def _thin_depth(x: dict, target: float, seed: int) -> dict:
|
| 185 |
+
rng = np.random.default_rng(seed)
|
| 186 |
+
prob = np.minimum(1.0, target / np.maximum(x["libs"], 1))
|
| 187 |
+
y = dict(x)
|
| 188 |
+
y["markers"] = rng.binomial(x["markers"], prob[:, None])
|
| 189 |
+
y["below_target"] = int((x["libs"] < target).sum())
|
| 190 |
+
return y
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _parent(x: dict, state: dict) -> np.ndarray:
|
| 194 |
+
parent = state["parent"]
|
| 195 |
+
return (np.ones(len(x["l1"]), bool) if parent == ["ALL"] else
|
| 196 |
+
np.isin(x["l1"], parent) | np.isin(x["l2"], parent))
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def _state(x: dict, symbols: list[str], state: dict) -> tuple[np.ndarray, np.ndarray, float]:
|
| 200 |
+
parent = _parent(x, state)
|
| 201 |
+
if state["kind"] == "label":
|
| 202 |
+
hit = np.isin(x["l2"], state["labels"]) & parent
|
| 203 |
+
return parent, hit, float("nan")
|
| 204 |
+
hit = call_marker_state(x["markers"], symbols, state) & parent
|
| 205 |
+
pos = {g: i for i, g in enumerate(symbols)}
|
| 206 |
+
n_detect = (x["markers"][:, [pos[g] for g in state["genes"]]] > 0).sum(axis=1)
|
| 207 |
+
codetection = float((n_detect[parent] >= 2).mean()) if parent.any() else float("nan")
|
| 208 |
+
return parent, hit, codetection
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def _metadata(path: Path) -> pd.DataFrame:
|
| 212 |
+
m = pd.read_csv(path, dtype={"sample_id": str, "donor_id": str})
|
| 213 |
+
if not {"sample_id", "donor_id", "group"} <= set(m):
|
| 214 |
+
raise ValueError(f"{path}: require sample_id, donor_id, group")
|
| 215 |
+
m = m[["sample_id", "donor_id", "group"]].drop_duplicates()
|
| 216 |
+
if m.sample_id.duplicated().any() or m[["sample_id", "donor_id", "group"]].isna().any().any():
|
| 217 |
+
raise ValueError(f"{path}: missing or ambiguous sample identity")
|
| 218 |
+
return m.set_index("sample_id")
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def analyze_unit(unit: dict, base: Path, states: list[dict], observed: dict | None = None) -> tuple[list, list, dict]:
|
| 222 |
+
tier = validate_design(unit)
|
| 223 |
+
path = lambda p: (base / p).resolve()
|
| 224 |
+
metadata = _metadata(path(unit["sample_metadata"]))
|
| 225 |
+
support_sha = None
|
| 226 |
+
if tier == "strict":
|
| 227 |
+
if not unit.get("support_manifest"):
|
| 228 |
+
raise ValueError("strict5pair requires support_manifest")
|
| 229 |
+
support = json.loads(path(unit["support_manifest"]).read_text())
|
| 230 |
+
body = {k: v for k, v in support.items() if k != "sha256"}
|
| 231 |
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"),
|
| 232 |
+
allow_nan=False).encode()).hexdigest()
|
| 233 |
+
if support.get("schema") != "pbisc.paper.strict-support.v1" or support.get("sha256") != digest:
|
| 234 |
+
raise ValueError("support_manifest schema/hash mismatch")
|
| 235 |
+
for key in ("cohort", "train_sample_ids", "train_donor_ids", "test_sample_ids"):
|
| 236 |
+
if support[key] != unit[key]:
|
| 237 |
+
raise ValueError(f"support_manifest mismatch: {key}")
|
| 238 |
+
if support["unit"] != f'{unit["unit"]}_n5':
|
| 239 |
+
raise ValueError("support_manifest mismatch: unit")
|
| 240 |
+
support_sha = support["sha256"]
|
| 241 |
+
if [metadata.loc[s].donor_id for s in unit["train_sample_ids"]] != unit["train_donor_ids"]:
|
| 242 |
+
raise ValueError("training donor metadata differs from support manifest")
|
| 243 |
+
if set(metadata.loc[unit["test_sample_ids"]].donor_id) & set(unit["train_donor_ids"]):
|
| 244 |
+
raise ValueError("selected training donor appears in test")
|
| 245 |
+
if list(metadata.loc[unit["test_sample_ids"]].donor_id) != support["test_donor_ids"]:
|
| 246 |
+
raise ValueError("test donor metadata differs from support manifest")
|
| 247 |
+
unit = {**unit, "test_donor_ids": support["test_donor_ids"]}
|
| 248 |
+
obs = observed if observed is not None else _load(path(unit["observed_cache"]))
|
| 249 |
+
arms = {a: _load(path(p)) for a, p in unit["generated_caches"].items()}
|
| 250 |
+
if not arms:
|
| 251 |
+
raise ValueError("unit has no generated arms")
|
| 252 |
+
if tier == "strict":
|
| 253 |
+
observed_sha = unit.get("observed_cache_sha256")
|
| 254 |
+
if not observed_sha or _sha256(path(unit["observed_cache"])) != observed_sha:
|
| 255 |
+
raise ValueError("observed marker cache content hash mismatch or absent")
|
| 256 |
+
for arm, cache in arms.items():
|
| 257 |
+
validate_strict_cache(cache, path(unit["generated_caches"][arm]), unit, arm, support_sha)
|
| 258 |
+
symbols = list(obs["marker_symbols"].astype(str))
|
| 259 |
+
for arm, g in arms.items():
|
| 260 |
+
if list(g["marker_symbols"].astype(str)) != symbols:
|
| 261 |
+
raise ValueError(f"{arm}: markers differ from observed cache")
|
| 262 |
+
test_samples = list(map(str, unit["test_sample_ids"]))
|
| 263 |
+
if len(set(test_samples)) != len(test_samples) or not test_samples:
|
| 264 |
+
raise ValueError("test_sample_ids must be nonempty and unique")
|
| 265 |
+
if not set(test_samples) <= set(metadata.index):
|
| 266 |
+
raise ValueError("test samples lack metadata")
|
| 267 |
+
if tier == "strict" and set(unit["train_sample_ids"]) & set(test_samples):
|
| 268 |
+
raise ValueError("training samples included in test")
|
| 269 |
+
obs_ids = obs["sample_id"].astype(str)
|
| 270 |
+
arm_ids = {a: g["sample_id"].astype(str) for a, g in arms.items()}
|
| 271 |
+
for a, ids in arm_ids.items():
|
| 272 |
+
if set(ids) != set(test_samples):
|
| 273 |
+
raise ValueError(f"{a}: generated sample set differs from manifest test samples")
|
| 274 |
+
if not set(test_samples) <= set(obs_ids):
|
| 275 |
+
raise ValueError("observed cache missing test samples")
|
| 276 |
+
cell_budget = int(unit["cell_budget"])
|
| 277 |
+
depth_target = float(unit["depth_target"])
|
| 278 |
+
if cell_budget <= 0 or depth_target <= 0:
|
| 279 |
+
raise ValueError("positive common cell_budget and depth_target required")
|
| 280 |
+
eligible = []
|
| 281 |
+
omitted = []
|
| 282 |
+
for st in states:
|
| 283 |
+
try:
|
| 284 |
+
validate_marker_coverage(st, symbols)
|
| 285 |
+
eligible.append(st)
|
| 286 |
+
except ValueError as exc:
|
| 287 |
+
omitted.append({"state": st["name"], "reason": str(exc)})
|
| 288 |
+
# An unmeasured mandatory gene invalidates that rule, not every other state in the unit.
|
| 289 |
+
# Record the omission explicitly so it cannot be counted as a model miss.
|
| 290 |
+
rows = []
|
| 291 |
+
budgets = {}
|
| 292 |
+
depth_below = 0
|
| 293 |
+
for sample in test_samples:
|
| 294 |
+
oidx = np.flatnonzero(obs_ids == sample)
|
| 295 |
+
gidx = {a: np.flatnonzero(ids == sample) for a, ids in arm_ids.items()}
|
| 296 |
+
budget = min(cell_budget, len(oidx), *(len(v) for v in gidx.values()))
|
| 297 |
+
if budget <= 0:
|
| 298 |
+
raise ValueError(f"{sample}: no common cells")
|
| 299 |
+
budgets[sample] = budget
|
| 300 |
+
# The observed selection and depth draw are shared across every method.
|
| 301 |
+
o = _thin_depth(_thin_subset(obs, oidx, budget, _seed(unit["cohort"], unit["unit"], sample, "obs")),
|
| 302 |
+
depth_target, _seed(unit["cohort"], unit["unit"], sample, "obs-depth"))
|
| 303 |
+
depth_below += o["below_target"]
|
| 304 |
+
m = metadata.loc[sample]
|
| 305 |
+
for arm, g in arms.items():
|
| 306 |
+
q = _thin_depth(_thin_subset(g, gidx[arm], budget, _seed(unit["cohort"], unit["unit"], sample, arm)),
|
| 307 |
+
depth_target, _seed(unit["cohort"], unit["unit"], sample, arm, "depth"))
|
| 308 |
+
depth_below += q["below_target"]
|
| 309 |
+
for st in eligible:
|
| 310 |
+
po, ho, co = _state(o, symbols, st)
|
| 311 |
+
pg, hg, cg = _state(q, symbols, st)
|
| 312 |
+
rows.append(dict(cohort=unit["cohort"], unit=unit["unit"], design=unit["design"],
|
| 313 |
+
evidence_tier=tier, arm=arm, state=st["name"], state_kind=st["kind"],
|
| 314 |
+
sample_id=sample, donor_id=str(m.donor_id), group=str(m.group),
|
| 315 |
+
obs_total=budget, gen_total=budget, obs_parent=int(po.sum()),
|
| 316 |
+
obs_state=int(ho.sum()), gen_parent=int(pg.sum()), gen_state=int(hg.sum()),
|
| 317 |
+
obs_codetection=co, gen_codetection=cg, cell_budget_used=budget,
|
| 318 |
+
depth_target=depth_target))
|
| 319 |
+
per = pd.DataFrame(rows)
|
| 320 |
+
summ = []
|
| 321 |
+
for (arm, state), x in per.groupby(["arm", "state"], sort=False):
|
| 322 |
+
d = abundance_summary(x)
|
| 323 |
+
lo, hi = bootstrap_mae(x, seed=_seed(unit["cohort"], unit["unit"], arm, state), n_boot=1000)
|
| 324 |
+
d.update(dict(cohort=unit["cohort"], unit=unit["unit"], design=unit["design"],
|
| 325 |
+
evidence_tier=tier, arm=arm, state=state, state_kind=x.state_kind.iloc[0],
|
| 326 |
+
mae_donor_ci_low=lo, mae_donor_ci_high=hi,
|
| 327 |
+
obs_codetection=float(x.obs_codetection.mean()),
|
| 328 |
+
gen_codetection=float(x.gen_codetection.mean())))
|
| 329 |
+
summ.append(d)
|
| 330 |
+
prov = dict(cohort=unit["cohort"], unit=unit["unit"], design=unit["design"],
|
| 331 |
+
evidence_tier=tier, test_samples=len(test_samples),
|
| 332 |
+
support_sha256=support_sha,
|
| 333 |
+
train_samples=len(unit["train_sample_ids"]),
|
| 334 |
+
train_donors=len(set(unit["train_donor_ids"])),
|
| 335 |
+
actual_test_donors=int(metadata.loc[test_samples].donor_id.nunique()),
|
| 336 |
+
max_cell_budget=cell_budget, min_cell_budget_used=min(budgets.values()),
|
| 337 |
+
depth_target=depth_target, selected_cells_below_target=depth_below,
|
| 338 |
+
omitted_states=omitted, states_scored=len(eligible),
|
| 339 |
+
cache_paths={a: str(path(p)) for a, p in unit["generated_caches"].items()})
|
| 340 |
+
return rows, summ, prov
|
| 341 |
+
|
| 342 |
+
|
| 343 |
+
def legacy_units(states: list[dict]) -> list[tuple[dict, dict]]:
|
| 344 |
+
out = []
|
| 345 |
+
for cohort in COHORTS:
|
| 346 |
+
observed = _observed_legacy(cohort, states)
|
| 347 |
+
meta = FT / "data" / cohort / "pairs.csv"
|
| 348 |
+
m = _metadata(meta)
|
| 349 |
+
for draw in range(5):
|
| 350 |
+
caches = {a: OLD / "work" / cohort / f"draw{draw}" / f"{a}.npz" for a in LEGACY_ARMS}
|
| 351 |
+
if not all(p.is_file() for p in caches.values()):
|
| 352 |
+
continue
|
| 353 |
+
with np.load(caches["lora5"], allow_pickle=False) as z:
|
| 354 |
+
samples = list(dict.fromkeys(z["donor"].astype(str)))
|
| 355 |
+
train_donors = (FT / "data" / cohort / f"fewshot_n5/draw{draw}/train_donors.txt").read_text().splitlines()
|
| 356 |
+
train = pd.read_csv(meta, dtype={"sample_id": str, "donor_id": str})
|
| 357 |
+
train = train[train.donor_id.isin(train_donors)]
|
| 358 |
+
# Legacy support includes every visit of each selected donor.
|
| 359 |
+
unit = dict(cohort=cohort, unit=f"draw{draw}", design="legacy_5donor",
|
| 360 |
+
train_sample_ids=train.sample_id.tolist(), train_donor_ids=train.donor_id.tolist(),
|
| 361 |
+
test_sample_ids=samples, sample_metadata=str(meta),
|
| 362 |
+
generated_caches={a: str(p) for a, p in caches.items()},
|
| 363 |
+
cell_budget=1500, depth_target=1000)
|
| 364 |
+
if not set(samples) <= set(m.index):
|
| 365 |
+
raise ValueError(f"{cohort} draw{draw}: legacy cache sample absent from pairs.csv")
|
| 366 |
+
out.append((unit, observed))
|
| 367 |
+
return out
|
| 368 |
+
|
| 369 |
+
|
| 370 |
+
def main() -> None:
|
| 371 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 372 |
+
group = ap.add_mutually_exclusive_group(required=True)
|
| 373 |
+
group.add_argument("--manifest", type=Path)
|
| 374 |
+
group.add_argument("--manifest-dir", type=Path, help="directory of 20 per-unit rare_manifest.json files")
|
| 375 |
+
group.add_argument("--legacy-diagnostic", action="store_true")
|
| 376 |
+
ap.add_argument("--output", type=Path, default=HERE)
|
| 377 |
+
args = ap.parse_args()
|
| 378 |
+
states = json.loads(STATES.read_text())
|
| 379 |
+
if args.manifest or args.manifest_dir:
|
| 380 |
+
paths = ([args.manifest] if args.manifest else
|
| 381 |
+
sorted(args.manifest_dir.rglob("rare_manifest.json")))
|
| 382 |
+
units = []
|
| 383 |
+
for path in paths:
|
| 384 |
+
manifest = json.loads(path.read_text())
|
| 385 |
+
if manifest.get("schema") != "pbisc.figure5.marker-caches.v1":
|
| 386 |
+
raise ValueError(f"wrong marker cache manifest schema: {path}")
|
| 387 |
+
for u in manifest["units"]:
|
| 388 |
+
# Per-unit cache builder writes absolute paths; resolve relative paths here as well.
|
| 389 |
+
u = dict(u)
|
| 390 |
+
for key in ("sample_metadata", "support_manifest", "observed_cache"):
|
| 391 |
+
if key in u:
|
| 392 |
+
u[key] = str((path.parent / u[key]).resolve())
|
| 393 |
+
u["generated_caches"] = {a: str((path.parent / p).resolve())
|
| 394 |
+
for a, p in u["generated_caches"].items()}
|
| 395 |
+
units.append((u, None))
|
| 396 |
+
require_complete_strict([u for u, _ in units])
|
| 397 |
+
base = Path("/")
|
| 398 |
+
else:
|
| 399 |
+
units = legacy_units(states)
|
| 400 |
+
base = Path("/")
|
| 401 |
+
all_rows, all_summary, provenance = [], [], []
|
| 402 |
+
for unit, obs in units:
|
| 403 |
+
rows, summary, prov = analyze_unit(unit, base, states, obs)
|
| 404 |
+
all_rows.extend(rows)
|
| 405 |
+
all_summary.extend(summary)
|
| 406 |
+
provenance.append(prov)
|
| 407 |
+
print(json.dumps({"cohort": prov["cohort"], "unit": prov["unit"],
|
| 408 |
+
"tier": prov["evidence_tier"], "states": prov["states_scored"]}), flush=True)
|
| 409 |
+
out = args.output
|
| 410 |
+
(out / "source_data").mkdir(parents=True, exist_ok=True)
|
| 411 |
+
(out / "reports").mkdir(parents=True, exist_ok=True)
|
| 412 |
+
if not all_rows:
|
| 413 |
+
raise ValueError("no complete units available")
|
| 414 |
+
per = pd.DataFrame(all_rows)
|
| 415 |
+
per.to_csv(out / "source_data/rare_per_sample.csv", index=False)
|
| 416 |
+
donor = (per.groupby(["cohort", "unit", "design", "evidence_tier", "arm", "state"], sort=False)
|
| 417 |
+
.apply(aggregate_donors, include_groups=False).reset_index())
|
| 418 |
+
donor.to_csv(out / "source_data/rare_per_donor.csv", index=False)
|
| 419 |
+
pd.DataFrame(all_summary).to_csv(out / "source_data/rare_summary.csv", index=False)
|
| 420 |
+
pd.DataFrame([dict(cohort=p["cohort"], unit=p["unit"], design=p["design"],
|
| 421 |
+
evidence_tier=p["evidence_tier"], state=o["state"], reason=o["reason"])
|
| 422 |
+
for p in provenance for o in p["omitted_states"]],
|
| 423 |
+
columns=["cohort", "unit", "design", "evidence_tier", "state", "reason"]).to_csv(
|
| 424 |
+
out / "source_data/rare_ineligible_states.csv", index=False)
|
| 425 |
+
(out / "reports/rare_provenance.json").write_text(
|
| 426 |
+
json.dumps({"schema": "pbisc.figure5.analysis.v1", "units": provenance,
|
| 427 |
+
"visuals": {"status": "awaiting_strict_marker_visual_export"}
|
| 428 |
+
if {p["evidence_tier"] for p in provenance} == {"strict"}
|
| 429 |
+
else {"status": "diagnostic_only"},
|
| 430 |
+
"metric_label": "high_low_abundance_auroc ranks abundance, not binary detection",
|
| 431 |
+
"zero_draws": "included; conditional rate NA only if parent count is zero",
|
| 432 |
+
"bootstrap": "donor cluster, seed derived from cohort/unit/arm/state",
|
| 433 |
+
"legacy_notice": "legacy_5donor is diagnostic and not a strict5pair result"}, indent=2) + "\n")
|
| 434 |
+
print(json.dumps({"samples": len(per), "summary_rows": len(all_summary), "tiers":
|
| 435 |
+
sorted({p["evidence_tier"] for p in provenance})}))
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
if __name__ == "__main__":
|
| 439 |
+
main()
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_results_figures.py
ADDED
|
@@ -0,0 +1,1035 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ay pending.
|
| 3 |
+
|
| 4 |
+
Run with CUDA_VISIBLE_DEVICES='' python tools/build_results_figures.py.
|
| 5 |
+
--require-complete fails unless all strict units and required Figure 3 visual data exist.
|
| 6 |
+
The optional Figure 3 visual NPZ is an *export* from scored strict units, not a
|
| 7 |
+
substitute for score summaries. Its JSON sidecar must bind all five support hashes.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import argparse
|
| 12 |
+
import csv
|
| 13 |
+
import hashlib
|
| 14 |
+
import json
|
| 15 |
+
import os
|
| 16 |
+
import tempfile
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
|
| 20 |
+
raise SystemExit("Set CUDA_VISIBLE_DEVICES='' for the CPU figure builder")
|
| 21 |
+
import matplotlib
|
| 22 |
+
matplotlib.use('Agg')
|
| 23 |
+
import matplotlib.pyplot as plt
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 27 |
+
M8 = ROOT.parents[1]
|
| 28 |
+
OLD = M8 / 'plans/paired_finetune_intradataset_20260927'
|
| 29 |
+
COHORTS = ('ye2026_sepsis', 'imperial_eskd', 'giroux2022', 'ji2025_chili')
|
| 30 |
+
ARMS = ('raw', 'refcal', 'lora', 'scsemi', 'pairedcal')
|
| 31 |
+
DECONV_METHODS = ('bayesprism', 'cibersortx')
|
| 32 |
+
COLORS = {'raw':'#999999', 'refcal':'#0072B2', 'lora':'#D55E00',
|
| 33 |
+
'scsemi':'#009E73', 'pairedcal':'#CC79A7', 'real_R2_independent':'#222222',
|
| 34 |
+
'bayesprism':'#B35C1E', 'cibersortx':'#6F63A8'}
|
| 35 |
+
plt.rcParams.update({'font.family':'DejaVu Sans', 'font.size':8, 'axes.titlesize':9,
|
| 36 |
+
'axes.labelsize':8, 'legend.fontsize':7, 'svg.fonttype':'none',
|
| 37 |
+
'pdf.fonttype':42, 'axes.spines.top':False,
|
| 38 |
+
'axes.spines.right':False, 'savefig.dpi':300})
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def sha(path: Path) -> str:
|
| 42 |
+
h = hashlib.sha256()
|
| 43 |
+
with path.open('rb') as f:
|
| 44 |
+
for chunk in iter(lambda: f.read(1024*1024), b''):
|
| 45 |
+
h.update(chunk)
|
| 46 |
+
return h.hexdigest()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def read_json(path: Path) -> dict:
|
| 50 |
+
return json.loads(path.read_text())
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def records(path: Path) -> list[dict]:
|
| 54 |
+
with path.open(newline='') as f:
|
| 55 |
+
return list(csv.DictReader(f))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def write_csv(path: Path, rows: list[dict], columns: list[str]) -> None:
|
| 59 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 60 |
+
with path.open('w', newline='') as f:
|
| 61 |
+
w = csv.DictWriter(f, fieldnames=columns, extrasaction='ignore')
|
| 62 |
+
w.writeheader(); w.writerows(rows)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def save(fig, name: str):
|
| 66 |
+
out = ROOT/'figures'/name
|
| 67 |
+
out.parent.mkdir(exist_ok=True)
|
| 68 |
+
for ext in ('pdf','svg','png'):
|
| 69 |
+
fig.savefig(out.with_suffix('.'+ext), bbox_inches='tight', dpi=300)
|
| 70 |
+
plt.close(fig)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def pending(ax, title, detail):
|
| 74 |
+
ax.set_axis_off()
|
| 75 |
+
ax.text(0.02, 0.87, title, weight='bold', transform=ax.transAxes)
|
| 76 |
+
ax.text(0.02, 0.52, 'PENDING', color='#9A6700', weight='bold', fontsize=11,
|
| 77 |
+
transform=ax.transAxes)
|
| 78 |
+
ax.text(0.02, 0.34, detail, color='#555555', wrap=True, transform=ax.transAxes)
|
| 79 |
+
ax.add_patch(plt.Rectangle((0.01,0.04),.98,.91, fill=False, edgecolor='#CCCCCC',
|
| 80 |
+
transform=ax.transAxes, clip_on=False))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def strict_unit(support_path: Path, require_stats=False) -> tuple[dict|None, str]:
|
| 84 |
+
"""Return a verified strict score, or an explicit pending reason; reject wrong designs."""
|
| 85 |
+
support = read_json(support_path)
|
| 86 |
+
if support.get('schema') != 'pbisc.paper.strict-support.v1':
|
| 87 |
+
raise ValueError(f'wrong support schema: {support_path}')
|
| 88 |
+
body = {k:v for k,v in support.items() if k != 'sha256'}
|
| 89 |
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(',', ':'), allow_nan=False).encode()).hexdigest()
|
| 90 |
+
if support.get('sha256') != digest:
|
| 91 |
+
raise ValueError(f'support hash mismatch: {support_path}')
|
| 92 |
+
expected_design = 'healthy_outerfold' if support['cohort'] == 'immicro' else 'disease_existing_draw'
|
| 93 |
+
if support.get('design') != expected_design or support.get('n_pairs') not in ((5,10,20,40) if expected_design == 'healthy_outerfold' else (5,)):
|
| 94 |
+
raise ValueError(f'wrong strict support design: {support_path}')
|
| 95 |
+
if support.get('n_pairs') != len(support.get('train_donor_ids', [])) or len(set(support['train_donor_ids'])) != support['n_pairs']:
|
| 96 |
+
raise ValueError(f'nonunique or incomplete donor support: {support_path}')
|
| 97 |
+
if set(support['train_donor_ids']) & set(support['test_donor_ids']):
|
| 98 |
+
raise ValueError(f'train/test donor overlap: {support_path}')
|
| 99 |
+
if len(support['train_sample_ids']) != support['n_pairs']:
|
| 100 |
+
raise ValueError(f'wrong sample count: {support_path}')
|
| 101 |
+
rel = support_path.relative_to(ROOT/'protocol/splits').parent
|
| 102 |
+
out = ROOT/'scores'/rel
|
| 103 |
+
summary_path = out/'score/summary.json'
|
| 104 |
+
if not summary_path.is_file():
|
| 105 |
+
return None, f'missing {summary_path.relative_to(ROOT)}'
|
| 106 |
+
summary = read_json(summary_path)
|
| 107 |
+
if summary.get('dataset') != support['cohort'] or set(summary.get('donors', [])) != set(support['test_sample_ids']):
|
| 108 |
+
raise ValueError(f'score/test sample mismatch: {summary_path}')
|
| 109 |
+
if set(summary.get('arms', [])) != set(ARMS):
|
| 110 |
+
raise ValueError(f'wrong strict arms: {summary_path}')
|
| 111 |
+
if summary.get('schema') != 'paired_ft_scores.v1':
|
| 112 |
+
raise ValueError(f'wrong score schema: {summary_path}')
|
| 113 |
+
binding_path=out/'scoring_support.json'
|
| 114 |
+
if not binding_path.is_file():
|
| 115 |
+
return None, f'missing strict score binding: {binding_path.relative_to(ROOT)}'
|
| 116 |
+
binding=read_json(binding_path)
|
| 117 |
+
if (binding.get('schema')!='pbisc.paper.strict-score-binding.v1'
|
| 118 |
+
or binding.get('support_sha256')!=support['sha256']
|
| 119 |
+
or binding.get('cohort')!=support['cohort'] or binding.get('unit')!=support['unit']
|
| 120 |
+
or binding.get('test_sample_ids')!=support['test_sample_ids']
|
| 121 |
+
or binding.get('test_donor_ids')!=support['test_donor_ids']
|
| 122 |
+
or set(binding.get('arm_bindings',{}))!=set(ARMS)):
|
| 123 |
+
raise ValueError(f'strict score binding differs from support: {binding_path}')
|
| 124 |
+
per = out/'score/per_donor.csv'
|
| 125 |
+
if not per.is_file():
|
| 126 |
+
return None, f'missing {per.relative_to(ROOT)}'
|
| 127 |
+
rows = records(per)
|
| 128 |
+
if not rows or {(r['arm'],r['donor']) for r in rows} != {(a,d) for a in ARMS for d in support['test_sample_ids']}:
|
| 129 |
+
raise ValueError(f'incomplete or duplicate per-donor cells: {per}')
|
| 130 |
+
for arm in ARMS:
|
| 131 |
+
pa = summary['per_arm'].get(arm, {})
|
| 132 |
+
bound=binding['arm_bindings'][arm]
|
| 133 |
+
source = Path(pa.get('npz',''))
|
| 134 |
+
expected = (ROOT/'generated/global'/support['cohort']/f'{arm}.npz' if arm in ('raw','refcal')
|
| 135 |
+
else ROOT/'generated'/rel/f'{arm}.npz')
|
| 136 |
+
if source.resolve() != expected.resolve() or not source.is_file() or not pa.get('receipt_verified') or not pa.get('npz_sha256'):
|
| 137 |
+
raise ValueError(f'unverified strict source for {arm}: {summary_path}')
|
| 138 |
+
if (bound.get('support_sha256')!=support['sha256']
|
| 139 |
+
or bound.get('npz')!=str(source) or bound.get('npz_sha256')!=pa['npz_sha256']):
|
| 140 |
+
raise ValueError(f'{arm} score source differs from strict generation binding: {binding_path}')
|
| 141 |
+
for key in ('receipt','source_binding'):
|
| 142 |
+
item=Path(bound.get(key,''))
|
| 143 |
+
if not item.is_file() or sha(item)!=bound.get(key+'_sha256'):
|
| 144 |
+
raise ValueError(f'{arm} source binding changed: {item}')
|
| 145 |
+
if not (out/'score/arms'/arm/'generated_cells.parquet').is_file():
|
| 146 |
+
return None, f'missing generated-cell labels for {arm}: {rel}'
|
| 147 |
+
stats = out/'statistics/status.json'
|
| 148 |
+
if require_stats:
|
| 149 |
+
if not stats.is_file() or not (out/'statistics/donor_bootstrap_2000.csv').is_file():
|
| 150 |
+
return None, f'corrected donor statistics pending: {rel}'
|
| 151 |
+
stat = read_json(stats)
|
| 152 |
+
if stat.get('support_sha256') != support['sha256'] or stat.get('bootstrap_replicates') != 2000:
|
| 153 |
+
raise ValueError(f'wrong donor statistics provenance: {stats}')
|
| 154 |
+
return {'support':support, 'summary':summary, 'rows':rows, 'summary_path':str(summary_path),
|
| 155 |
+
'binding_sha256':sha(binding_path),
|
| 156 |
+
'per_path':str(per), 'stat_path':str(stats) if stats.exists() else None,
|
| 157 |
+
'rel':str(rel)}, ''
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def collect(cohort: str, kind: str, sizes=(5,), require_stats=False):
|
| 161 |
+
complete, missing = [], []
|
| 162 |
+
for i in range(5):
|
| 163 |
+
for n in sizes:
|
| 164 |
+
path = ROOT/'protocol/splits'/cohort/kind/f'{"fold" if kind=="healthy" else "draw"}{i}'
|
| 165 |
+
if kind == 'healthy': path = path/f'n{n}'
|
| 166 |
+
path = path/'support.json'
|
| 167 |
+
if not path.is_file():
|
| 168 |
+
missing.append(str(path.relative_to(ROOT))); continue
|
| 169 |
+
if read_json(path).get('cohort') != cohort:
|
| 170 |
+
raise ValueError(f'cohort/path mismatch: {path}')
|
| 171 |
+
unit, reason = strict_unit(path, require_stats=require_stats)
|
| 172 |
+
if unit: complete.append(unit)
|
| 173 |
+
else: missing.append(reason)
|
| 174 |
+
return complete, missing
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def fig2(pretrain: list[dict], strict: list[dict], missing: list[str], provenance: list[dict]):
|
| 178 |
+
import figure2_panels
|
| 179 |
+
import sys
|
| 180 |
+
return figure2_panels.render(pretrain, strict, missing, provenance, sys.modules[__name__])
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def fig3_type_palette() -> dict[str,str]:
|
| 184 |
+
return {'T cell':'#0072B2','B cell':'#E69F00','Monocyte':'#009E73',
|
| 185 |
+
'NK cell':'#CC79A7','DC':'#D55E00','Other':'#666666'}
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def fig3_umap_by_type(xy: np.ndarray, arms: np.ndarray, celltypes: np.ndarray) -> tuple[float,float,float,float]:
|
| 189 |
+
"""Six fixed-coordinate panels, with one shared biological cell-type palette."""
|
| 190 |
+
from matplotlib.lines import Line2D
|
| 191 |
+
palette=fig3_type_palette()
|
| 192 |
+
methods=('real_R2','raw','refcal','pairedcal','scsemi','lora')
|
| 193 |
+
if xy.ndim!=2 or xy.shape[1]!=2 or len(xy)!=len(arms) or len(arms)!=len(celltypes):
|
| 194 |
+
raise ValueError('Figure 3 UMAP arrays unaligned')
|
| 195 |
+
if not set(celltypes) <= set(palette):
|
| 196 |
+
raise ValueError(f'Figure 3 UMAP has unknown cell types: {sorted(set(celltypes)-set(palette))}')
|
| 197 |
+
use=np.isin(arms,methods)
|
| 198 |
+
if not np.isfinite(xy[use]).all():raise ValueError('Figure 3 UMAP has nonfinite coordinates')
|
| 199 |
+
bounds=np.array([xy[use,0].min(),xy[use,0].max(),xy[use,1].min(),xy[use,1].max()],float)
|
| 200 |
+
dx=max(1e-6,bounds[1]-bounds[0]);dy=max(1e-6,bounds[3]-bounds[2])
|
| 201 |
+
limits=(bounds[0]-.03*dx,bounds[1]+.03*dx,bounds[2]-.03*dy,bounds[3]+.03*dy)
|
| 202 |
+
fig,axs=plt.subplots(2,3,figsize=(7.09,4.8),sharex=True,sharey=True,layout='constrained')
|
| 203 |
+
for ax,arm in zip(axs.flat,methods):
|
| 204 |
+
sel=arms==arm
|
| 205 |
+
if not sel.any():raise ValueError(f'Figure 3 UMAP arm missing: {arm}')
|
| 206 |
+
for label,color in palette.items():
|
| 207 |
+
mask=sel&(celltypes==label)
|
| 208 |
+
if mask.any():ax.scatter(xy[mask,0],xy[mask,1],s=.45,alpha=.42,
|
| 209 |
+
color=color,linewidths=0)
|
| 210 |
+
ax.set(xlim=limits[:2],ylim=limits[2:])
|
| 211 |
+
ax.set_title('Real R2' if arm=='real_R2' else arm,loc='left',weight='bold',fontsize=8)
|
| 212 |
+
handles=[Line2D([0],[0],marker='o',linestyle='',color=color,markersize=5,label=label)
|
| 213 |
+
for label,color in palette.items()]
|
| 214 |
+
fig.legend(handles=handles,loc='lower center',ncol=6,frameon=False,
|
| 215 |
+
bbox_to_anchor=(.5,-.075),fontsize=6,columnspacing=1.15)
|
| 216 |
+
fig.suptitle('Figure 3 · pooled OOF illustration on one real-R1 PCA/UMAP',fontsize=10,weight='bold')
|
| 217 |
+
save(fig,'fig3_umap_by_celltype')
|
| 218 |
+
return limits
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def fig3_composition_fractions(rows: list[dict], units: list[dict]) -> None:
|
| 222 |
+
"""Full scored observed and 1,500-generated-cell fractions per held-out sample."""
|
| 223 |
+
palette=fig3_type_palette();methods=('raw','refcal','pairedcal','scsemi','lora')
|
| 224 |
+
expected={s for u in units for s in u['support']['test_sample_ids']}
|
| 225 |
+
expected_rows={(s,a,t) for s in expected for a in methods for t in palette}
|
| 226 |
+
if (len(rows)!=len(expected_rows) or
|
| 227 |
+
{(r['sample_id'],r['arm'],r['cell_type']) for r in rows}!=expected_rows):
|
| 228 |
+
raise ValueError('Figure 3 composition fractions have missing/duplicate sample-arm-type rows')
|
| 229 |
+
binding={u['support']['unit']:sha(Path(u['per_path'])) for u in units}
|
| 230 |
+
sample_fold={s:u['support']['unit'] for u in units for s in u['support']['test_sample_ids']}
|
| 231 |
+
for r in rows:
|
| 232 |
+
observed=float(r['observed_fraction']);generated=float(r['generated_fraction'])
|
| 233 |
+
if (r['fold']!=sample_fold[r['sample_id']]
|
| 234 |
+
or r.get('score_per_donor_sha256')!=binding[r['fold']]
|
| 235 |
+
or int(r['generated_total'])!=1500 or int(r['observed_total'])<=0
|
| 236 |
+
or not 0<=observed<=1 or not 0<=generated<=1):
|
| 237 |
+
raise ValueError('Figure 3 full-cell composition provenance or fraction differs')
|
| 238 |
+
for sample in expected:
|
| 239 |
+
for arm in methods:
|
| 240 |
+
rr=[r for r in rows if r['sample_id']==sample and r['arm']==arm]
|
| 241 |
+
if (not np.isclose(sum(float(r['observed_fraction']) for r in rr),1,atol=1e-5)
|
| 242 |
+
or not np.isclose(sum(float(r['generated_fraction']) for r in rr),1,atol=1e-5)):
|
| 243 |
+
raise ValueError('Figure 3 full-cell composition fractions do not sum to one')
|
| 244 |
+
fig,axs=plt.subplots(2,3,figsize=(7.09,4.25),layout='constrained')
|
| 245 |
+
for ax,(cell_type,color) in zip(axs.flat,palette.items()):
|
| 246 |
+
base=[float(r['observed_fraction']) for r in rows if r['arm']=='raw' and r['cell_type']==cell_type]
|
| 247 |
+
ax.bar(0,100*np.mean(base),color='#444444',alpha=.65)
|
| 248 |
+
for j,arm in enumerate(methods,1):
|
| 249 |
+
vals=[float(r['generated_fraction']) for r in rows if r['arm']==arm and r['cell_type']==cell_type]
|
| 250 |
+
ax.bar(j,100*np.mean(vals),color=COLORS[arm],alpha=.65)
|
| 251 |
+
fold_vals=[np.mean([float(r['generated_fraction']) for r in rows if r['arm']==arm
|
| 252 |
+
and r['cell_type']==cell_type and r['fold']==u['support']['unit']])
|
| 253 |
+
for u in units]
|
| 254 |
+
ax.scatter([j]*len(fold_vals),100*np.asarray(fold_vals),s=9,color=COLORS[arm])
|
| 255 |
+
ax.set_xticks(range(6),('Real R2',*methods),rotation=65,ha='right',fontsize=5)
|
| 256 |
+
ax.set_ylabel('Cell fraction (%)',fontsize=6)
|
| 257 |
+
ax.set_title(cell_type,loc='left',weight='bold',color=color)
|
| 258 |
+
fig.suptitle('Figure 3 · observed versus generated cell-type fractions; dots are outer folds',
|
| 259 |
+
fontsize=10,weight='bold')
|
| 260 |
+
save(fig,'fig3_composition_fractions')
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def validate_fig3_runtime_components(rows: list[dict]) -> None:
|
| 264 |
+
required={'fold','arm','adaptation_seconds','generation_seconds','operational_seconds'}
|
| 265 |
+
if not rows or not required <= set(rows[0]):
|
| 266 |
+
raise ValueError('Figure 3 runtime components missing')
|
| 267 |
+
for r in rows:
|
| 268 |
+
adaptation=float(r['adaptation_seconds']);generation=float(r['generation_seconds'])
|
| 269 |
+
total=float(r['operational_seconds'])
|
| 270 |
+
if (not np.isfinite([adaptation,generation,total]).all()
|
| 271 |
+
or min(adaptation,generation,total)<0
|
| 272 |
+
or not np.isclose(adaptation+generation,total,rtol=1e-8,atol=1e-5)
|
| 273 |
+
or r['arm'] in ('raw','refcal','pairedcal') and adaptation!=0):
|
| 274 |
+
raise ValueError('Figure 3 adaptation/generation runtime components disagree')
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def fig3(units: list[dict], missing: list[str]):
|
| 278 |
+
rows=[]
|
| 279 |
+
for u in units:
|
| 280 |
+
for r in u['rows']:
|
| 281 |
+
rows.append({'fold':u['support']['unit'].split('_')[0],'arm':r['arm'],'sample_id':r['donor'],
|
| 282 |
+
'comp_l1':r.get('comp_l1',''),'pb_r':r.get('pb_r',''),
|
| 283 |
+
'precision':r.get('precision',''),'coverage':r.get('coverage',''),
|
| 284 |
+
'support_sha256':u['support']['sha256'],
|
| 285 |
+
'score_sha256':sha(Path(u['summary_path']))})
|
| 286 |
+
write_csv(ROOT/'source_data/fig3_per_sample.csv',rows,
|
| 287 |
+
['fold','arm','sample_id','comp_l1','pb_r','precision','coverage','support_sha256','score_sha256'])
|
| 288 |
+
complete=len(units)==5 and not missing
|
| 289 |
+
extra_rows=[]
|
| 290 |
+
if complete:
|
| 291 |
+
for u in units:
|
| 292 |
+
base=ROOT/'scores'/u['rel']/'extras/immicro/strict'
|
| 293 |
+
manifest=base/'manifest.json'
|
| 294 |
+
if not manifest.is_file(): break
|
| 295 |
+
m=read_json(manifest)
|
| 296 |
+
call=m.get('calls',{}).get(u['summary_path'])
|
| 297 |
+
if not call or call.get('summary_sha256')!=sha(Path(u['summary_path'])):
|
| 298 |
+
raise ValueError(f'Figure 3 extras do not bind strict score: {manifest}')
|
| 299 |
+
for filename in ('metrics.csv','en.csv'):
|
| 300 |
+
source=base/filename
|
| 301 |
+
if not source.is_file(): break
|
| 302 |
+
for r in records(source):
|
| 303 |
+
extra_rows.append({'fold':u['support']['unit'],'table':filename,
|
| 304 |
+
'source_sha256':sha(source),**r})
|
| 305 |
+
if extra_rows:
|
| 306 |
+
write_csv(ROOT/'source_data/fig3_extras.csv',extra_rows,
|
| 307 |
+
list(dict.fromkeys(k for r in extra_rows for k in r)))
|
| 308 |
+
fig,axs=plt.subplots(2,3,figsize=(7.09,5.0),layout='constrained')
|
| 309 |
+
labels=[('A Common real-R1 projection','Real R2 + five arms; fixed PCA/UMAP'),
|
| 310 |
+
('B Canonical marker expression','All measured canonical marker genes'),
|
| 311 |
+
('C Cell composition','Observed versus generated; donor paired'),
|
| 312 |
+
('D Precision / coverage','Strict out-of-fold scores'),
|
| 313 |
+
('E C2ST / MMD / energy','Strict extras, matched reference'),
|
| 314 |
+
('F Operational time','Fine-tuning + inference; pretraining excluded')]
|
| 315 |
+
# Render only direct scorer values with all five verified folds. Visual fields
|
| 316 |
+
# require a separate source-bound export; never infer them from labels alone.
|
| 317 |
+
for ax,(title,detail) in zip(axs.flat,labels): pending(ax,title,detail)
|
| 318 |
+
visual=ROOT/'source_data/fig3_visual_data.npz'
|
| 319 |
+
sidecar=ROOT/'source_data/fig3_visual_data.json'
|
| 320 |
+
visual_ready=False
|
| 321 |
+
if complete and visual.is_file() and sidecar.is_file():
|
| 322 |
+
v=read_json(sidecar)
|
| 323 |
+
hashes=sorted(u['support']['sha256'] for u in units)
|
| 324 |
+
if v.get('schema')!='pbisc.fig3.visual.v1' or sorted(v.get('support_sha256s',[]))!=hashes or v.get('npz_sha256')!=sha(visual):
|
| 325 |
+
raise ValueError('Figure 3 visual export has wrong strict provenance')
|
| 326 |
+
if (sorted(v.get('score_sha256s',[]))!=sorted(sha(Path(u['summary_path'])) for u in units)
|
| 327 |
+
or sorted(v.get('score_binding_sha256s',[]))!=sorted(u['binding_sha256'] for u in units)
|
| 328 |
+
or sorted(v.get('generated_npz_sha256s',[]))!=sorted(
|
| 329 |
+
u['summary']['per_arm'][arm]['npz_sha256'] for u in units for arm in ARMS)):
|
| 330 |
+
raise ValueError('Figure 3 visual export is not bound to the strict score and generated cells')
|
| 331 |
+
if v.get('reference_fit')!='real_R1_only' or v.get('projection')!='fixed_real_R1_pca_umap' or not v.get('canonical_marker_gene_ids'):
|
| 332 |
+
raise ValueError('Figure 3 visual export lacks fixed real-R1 projection or canonical marker definition')
|
| 333 |
+
for path_key,hash_key in (('coordinates_csv','coordinates_sha256'),
|
| 334 |
+
('composition_csv','composition_sha256')):
|
| 335 |
+
source=Path(v.get(path_key,''))
|
| 336 |
+
if not source.is_file() or sha(source)!=v.get(hash_key):
|
| 337 |
+
raise ValueError(f'Figure 3 source-data provenance differs: {path_key}')
|
| 338 |
+
# Fixed real-R1 coordinates, with all arms projected by the exporter.
|
| 339 |
+
with np.load(visual,allow_pickle=False) as z:
|
| 340 |
+
required={'xy','arm','cell_type','sample_id','marker_values','marker_detected','marker_symbols'}
|
| 341 |
+
if not required <= set(z.files): raise ValueError('Figure 3 visual data missing required arrays')
|
| 342 |
+
xy,arms,celltypes=z['xy'],z['arm'].astype(str),z['cell_type'].astype(str)
|
| 343 |
+
sample_ids=z['sample_id'].astype(str)
|
| 344 |
+
markers,symbols=z['marker_values'],z['marker_symbols'].astype(str)
|
| 345 |
+
detected=z['marker_detected']
|
| 346 |
+
if (len(symbols)!=len(v['canonical_marker_gene_ids']) or len(set(symbols))!=len(symbols)
|
| 347 |
+
or list(symbols)!=v.get('canonical_marker_symbols')
|
| 348 |
+
or not {'real_R2',*ARMS} <= set(arms)):
|
| 349 |
+
raise ValueError('Figure 3 canonical marker list is incomplete or duplicated')
|
| 350 |
+
allowed_samples=set().union(*(set(u['support']['test_sample_ids']) for u in units))
|
| 351 |
+
if (xy.ndim!=2 or xy.shape[1]!=2 or len(xy)!=len(arms)
|
| 352 |
+
or len(arms)!=len(celltypes) or len(sample_ids)!=len(arms)
|
| 353 |
+
or not set(sample_ids) <= allowed_samples
|
| 354 |
+
or markers.shape!=(len(arms),len(symbols)) or detected.shape!=markers.shape):
|
| 355 |
+
raise ValueError('Figure 3 visual arrays are unaligned')
|
| 356 |
+
for arm in ('real_R2',*ARMS):
|
| 357 |
+
if set(sample_ids[arms==arm])!=allowed_samples:
|
| 358 |
+
raise ValueError(f'Figure 3 visual export misses strict OOF samples for {arm}')
|
| 359 |
+
fig3_umap_by_type(xy,arms,celltypes)
|
| 360 |
+
fig3_composition_fractions(records(Path(v['composition_csv'])),units)
|
| 361 |
+
axs[0,0].clear()
|
| 362 |
+
sel=arms=='real_R2'
|
| 363 |
+
for label,color in fig3_type_palette().items():
|
| 364 |
+
mask=sel&(celltypes==label)
|
| 365 |
+
if mask.any():axs[0,0].scatter(xy[mask,0],xy[mask,1],s=.35,alpha=.4,
|
| 366 |
+
color=color,label=label)
|
| 367 |
+
axs[0,0].set_title('A Real R2 on shared real-R1 axes',loc='left',weight='bold')
|
| 368 |
+
axs[0,0].legend(markerscale=5,fontsize=4.5,ncol=2)
|
| 369 |
+
axs[0,1].clear()
|
| 370 |
+
show=len(symbols)
|
| 371 |
+
mat=np.vstack([np.nanmean(markers[arms==a,:show],axis=0) for a in ('real_R2','lora','scsemi','refcal','pairedcal')])
|
| 372 |
+
axs[0,1].imshow(mat,aspect='auto',cmap='viridis');axs[0,1].set_yticks(range(5),('Real R2','LoRA','scSemi','Ref-cal','Pair-cal'),fontsize=6)
|
| 373 |
+
axs[0,1].set_xticks(range(show),symbols[:show],rotation=90,fontsize=5);axs[0,1].set_title(labels[1][0],loc='left',weight='bold')
|
| 374 |
+
dfig,dax=plt.subplots(figsize=(7.09,max(3.0,0.22*len(set(celltypes))*5)),layout='constrained')
|
| 375 |
+
ylabels=[]; xx=[]; yy=[]; sizes=[]; means=[]
|
| 376 |
+
for arm in ('real_R2','lora','scsemi','refcal','pairedcal'):
|
| 377 |
+
for cell_type in sorted(set(celltypes)):
|
| 378 |
+
mask=(arms==arm)&(celltypes==cell_type)
|
| 379 |
+
if not mask.any(): continue
|
| 380 |
+
y=len(ylabels);ylabels.append(f'{arm} · {cell_type}')
|
| 381 |
+
for j in range(len(symbols)):
|
| 382 |
+
xx.append(j);yy.append(y)
|
| 383 |
+
sizes.append(4+70*float(np.mean(detected[mask,j])))
|
| 384 |
+
means.append(float(np.mean(markers[mask,j])))
|
| 385 |
+
art=dax.scatter(xx,yy,s=sizes,c=means,cmap='viridis',edgecolor='none')
|
| 386 |
+
dfig.colorbar(art,ax=dax,label='Mean log1p(CP10k)')
|
| 387 |
+
dax.set_xticks(range(len(symbols)),symbols,rotation=90,fontsize=6)
|
| 388 |
+
dax.set_yticks(range(len(ylabels)),ylabels,fontsize=5)
|
| 389 |
+
dax.invert_yaxis();dax.set_title('Figure 3 marker dot plot · size = detection fraction',loc='left',weight='bold')
|
| 390 |
+
save(dfig,'fig3_canonical_marker_dotplot')
|
| 391 |
+
visual_ready=True
|
| 392 |
+
if complete:
|
| 393 |
+
axs[0,2].clear()
|
| 394 |
+
for j,arm in enumerate(ARMS):
|
| 395 |
+
vals=[]
|
| 396 |
+
for u in units:
|
| 397 |
+
rr=[float(r['comp_l1']) for r in rows if r['arm']==arm and r['fold']==u['support']['unit'].split('_')[0] and r['comp_l1']]
|
| 398 |
+
if rr: vals.append(np.mean(rr))
|
| 399 |
+
if vals:
|
| 400 |
+
axs[0,2].bar(j,np.mean(vals),color=COLORS[arm],alpha=.55)
|
| 401 |
+
axs[0,2].scatter([j]*len(vals),vals,s=10,color=COLORS[arm])
|
| 402 |
+
axs[0,2].set_xticks(range(5),ARMS,rotation=30,ha='right',fontsize=5)
|
| 403 |
+
axs[0,2].set_ylabel('Mean donor composition L1')
|
| 404 |
+
axs[0,2].set_title('C Composition · 5 fold means + points',loc='left',weight='bold')
|
| 405 |
+
axs[1,0].clear()
|
| 406 |
+
for arm in ARMS:
|
| 407 |
+
rr=[u['summary']['per_arm'][arm].get('precision_coverage',{}) for u in units]
|
| 408 |
+
rr=[x for x in rr if 'precision' in x and 'coverage' in x]
|
| 409 |
+
if rr:
|
| 410 |
+
cov=[float(x['coverage']) for x in rr];pre=[float(x['precision']) for x in rr]
|
| 411 |
+
axs[1,0].scatter(cov,pre,s=10,alpha=.35,color=COLORS[arm])
|
| 412 |
+
axs[1,0].scatter(np.mean(cov),np.mean(pre),s=35,label=arm+' mean',color=COLORS[arm])
|
| 413 |
+
axs[1,0].set_title('D P/C · 5 fold means + points',loc='left',weight='bold')
|
| 414 |
+
axs[1,0].set_xlabel('Coverage');axs[1,0].set_ylabel('Precision');axs[1,0].legend(fontsize=5)
|
| 415 |
+
metric=[r for r in extra_rows if r.get('table')=='metrics.csv' and r.get('mode')=='raw'
|
| 416 |
+
and r.get('set') in ARMS]
|
| 417 |
+
if metric:
|
| 418 |
+
axs[1,1].clear()
|
| 419 |
+
for j,arm in enumerate(ARMS):
|
| 420 |
+
rr=[r for r in metric if r['set']==arm and r.get('c2st_rf_auc')]
|
| 421 |
+
if rr:
|
| 422 |
+
vals=[float(r['c2st_rf_auc']) for r in rr]
|
| 423 |
+
axs[1,1].bar(j,np.mean(vals),color=COLORS[arm],alpha=.55)
|
| 424 |
+
axs[1,1].scatter([j]*len(vals),vals,s=10,color=COLORS[arm])
|
| 425 |
+
axs[1,1].set_xticks(range(5),ARMS,rotation=30,ha='right',fontsize=5)
|
| 426 |
+
axs[1,1].set_ylabel('C2ST RF AUC')
|
| 427 |
+
axs[1,1].set_title('E C2ST · 5 fold means + points',loc='left',weight='bold')
|
| 428 |
+
runtime=ROOT/'source_data/fig3_runtime.csv'
|
| 429 |
+
runtime_manifest=ROOT/'source_data/fig3_runtime.json'
|
| 430 |
+
runtime_ready=False
|
| 431 |
+
if complete and runtime.is_file() and runtime_manifest.is_file():
|
| 432 |
+
rm=read_json(runtime_manifest)
|
| 433 |
+
rr=records(runtime)
|
| 434 |
+
if (rm.get('schema')!='pbisc.fig3.runtime.v2' or rm.get('csv_sha256')!=sha(runtime)
|
| 435 |
+
or sorted(rm.get('support_sha256s',[]))!=sorted(u['support']['sha256'] for u in units)
|
| 436 |
+
or rm.get('pretraining_excluded') is not True
|
| 437 |
+
or rm.get('runtime_scope')!='gpu_job_wall_seconds_only'
|
| 438 |
+
or rm.get('components')!=['adaptation_seconds','generation_seconds']
|
| 439 |
+
or {(r['fold'],r['arm']) for r in rr}!={(u['support']['unit'],a) for u in units for a in ARMS}):
|
| 440 |
+
raise ValueError('Figure 3 runtime source is incomplete or has wrong provenance')
|
| 441 |
+
validate_fig3_runtime_components(rr)
|
| 442 |
+
for r in rr:
|
| 443 |
+
if not r.get('receipt_path') or not Path(r['receipt_path']).is_file() or not r.get('receipt_sha256') or sha(Path(r['receipt_path']))!=r['receipt_sha256']:
|
| 444 |
+
raise ValueError('Figure 3 runtime receipt missing or changed')
|
| 445 |
+
evidence=read_json(Path(rr[0]['receipt_path']))
|
| 446 |
+
if (evidence.get('schema')!='pbisc.fig3.runtime-evidence.v1'
|
| 447 |
+
or evidence.get('pretraining_excluded') is not True
|
| 448 |
+
or evidence.get('runtime_scope')!='gpu_job_wall_seconds_only'):
|
| 449 |
+
raise ValueError('Figure 3 operational-time evidence schema differs')
|
| 450 |
+
for unit in evidence.get('units',{}).values():
|
| 451 |
+
for arm in unit.values():
|
| 452 |
+
for source in arm['sources']:
|
| 453 |
+
path=Path(source['path'])
|
| 454 |
+
if not path.is_file() or sha(path)!=source['sha256']:
|
| 455 |
+
raise ValueError(f'Figure 3 operational-time source changed: {path}')
|
| 456 |
+
rfig,rax=plt.subplots(figsize=(7.09,2.9),layout='constrained')
|
| 457 |
+
axs[1,2].clear()
|
| 458 |
+
for j,arm in enumerate(ARMS):
|
| 459 |
+
vals=[float(r['operational_seconds']) for r in rr if r['arm']==arm]
|
| 460 |
+
axs[1,2].bar(j,np.mean(vals)/3600,color=COLORS[arm],alpha=.55)
|
| 461 |
+
axs[1,2].scatter([j]*len(vals),np.asarray(vals)/3600,s=10,color=COLORS[arm])
|
| 462 |
+
adapt=[float(r['adaptation_seconds'])/3600 for r in rr if r['arm']==arm]
|
| 463 |
+
generate=[float(r['generation_seconds'])/3600 for r in rr if r['arm']==arm]
|
| 464 |
+
rax.bar(j,np.mean(adapt),color=COLORS[arm],alpha=.9,
|
| 465 |
+
label='Adaptation / training' if j==0 else None)
|
| 466 |
+
rax.bar(j,np.mean(generate),bottom=np.mean(adapt),color=COLORS[arm],alpha=.35,
|
| 467 |
+
hatch='//',label='Generation / inference' if j==0 else None)
|
| 468 |
+
rax.scatter([j]*len(vals),np.asarray(vals)/3600,s=11,color=COLORS[arm])
|
| 469 |
+
axs[1,2].set_xticks(range(5),ARMS,rotation=30,ha='right',fontsize=5)
|
| 470 |
+
axs[1,2].set_ylabel('GPU-job wall hours · corpus pretraining excluded')
|
| 471 |
+
axs[1,2].set_title('F Training / sampling GPU jobs',loc='left',weight='bold')
|
| 472 |
+
rax.set_xticks(range(5),ARMS)
|
| 473 |
+
rax.set_ylabel('GPU-job wall hours · corpus pretraining excluded')
|
| 474 |
+
rax.set_title('Figure 3 · GPU adaptation and generation components; dots are outer folds',
|
| 475 |
+
loc='left',weight='bold')
|
| 476 |
+
rax.legend(frameon=False,fontsize=7)
|
| 477 |
+
save(rfig,'fig3_runtime_components')
|
| 478 |
+
runtime_ready=True
|
| 479 |
+
save(fig,'fig3_healthy_strict_oof')
|
| 480 |
+
extras_complete=all(
|
| 481 |
+
{'metrics.csv','en.csv'} <= {r['table'] for r in extra_rows if r['fold']==u['support']['unit']}
|
| 482 |
+
and set(ARMS) <= {r.get('set') for r in extra_rows if r['fold']==u['support']['unit'] and r['table']=='metrics.csv'}
|
| 483 |
+
for u in units) and len(units)==5
|
| 484 |
+
if extras_complete:
|
| 485 |
+
efig,eaxs=plt.subplots(1,3,figsize=(7.09,2.35),layout='constrained')
|
| 486 |
+
defs=(('C2ST RF AUC','metrics.csv','c2st_rf_auc'),
|
| 487 |
+
('MMD² sum','metrics.csv','mmd2_sum'),('Normalized error E_N','en.csv','en'))
|
| 488 |
+
for ax,(title,table,key) in zip(eaxs,defs):
|
| 489 |
+
for j,arm in enumerate(ARMS):
|
| 490 |
+
rr=[r for r in extra_rows if r['table']==table and r.get('set')==arm
|
| 491 |
+
and r.get(key) and (table=='en.csv' and r.get('cellset')=='pc' and r.get('distance')=='sq'
|
| 492 |
+
or table=='metrics.csv' and r.get('mode')=='raw')]
|
| 493 |
+
if rr:
|
| 494 |
+
vals=[float(r[key]) for r in rr]
|
| 495 |
+
ax.bar(j,np.mean(vals),color=COLORS[arm],alpha=.55)
|
| 496 |
+
ax.scatter([j]*len(vals),vals,s=8,color=COLORS[arm])
|
| 497 |
+
ax.set_xticks(range(5),ARMS,rotation=45,ha='right',fontsize=5)
|
| 498 |
+
ax.set_title(title,loc='left',weight='bold')
|
| 499 |
+
save(efig,'fig3_realism_metrics')
|
| 500 |
+
return {'strict_complete_folds':len(units),'strict_expected_folds':5,'missing':missing,
|
| 501 |
+
'visual_export_ready':visual_ready,'visual_export':str(visual) if visual_ready else None,
|
| 502 |
+
'umap_by_celltype_ready':visual_ready,'composition_fractions_ready':visual_ready,
|
| 503 |
+
'extras_rows':len(extra_rows),'extras_complete':extras_complete,
|
| 504 |
+
'runtime_ready':runtime_ready,'runtime_components_ready':runtime_ready}
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
def donor_signal_panels(all_units: dict[str, list[dict]]) -> tuple[list[dict], list[str]]:
|
| 508 |
+
"""Render only source-bound corrected signals; legacy headline is never primary."""
|
| 509 |
+
def number(value):
|
| 510 |
+
try: return float(value)
|
| 511 |
+
except (ValueError, TypeError): return float('nan')
|
| 512 |
+
provenance = ROOT/'source_data/fig4_donor_aware_provenance.json'
|
| 513 |
+
reason = []
|
| 514 |
+
data = {key: [] for key in ('signal', 'summary', 'genes', 'cat')}
|
| 515 |
+
if not provenance.is_file():
|
| 516 |
+
reason.append('Donor-aware signal processor has not completed.')
|
| 517 |
+
else:
|
| 518 |
+
manifest = read_json(provenance)
|
| 519 |
+
if manifest.get('schema') != 'pbisc.fig4.donor-aware-signal.v1':
|
| 520 |
+
raise ValueError('wrong corrected Figure 4 signal schema')
|
| 521 |
+
if manifest.get('status') != 'complete':
|
| 522 |
+
reason.append('All 20 corrected disease units are required.')
|
| 523 |
+
else:
|
| 524 |
+
expected = {u['rel']: u['support']['sha256'] for units in all_units.values() for u in units}
|
| 525 |
+
actual = {key: item['support_sha256'] for key, item in manifest.get('units', {}).items()}
|
| 526 |
+
if len(expected) != 20 or actual != expected:
|
| 527 |
+
raise ValueError('corrected Figure 4 source support differs from strict scores')
|
| 528 |
+
for source, digest in manifest.get('sources', {}).items():
|
| 529 |
+
path = Path(source)
|
| 530 |
+
if not path.is_file() or sha(path) != digest:
|
| 531 |
+
raise ValueError(f'corrected disease input changed: {source}')
|
| 532 |
+
for key in data:
|
| 533 |
+
item = manifest['outputs'][key]
|
| 534 |
+
path = Path(item['path'])
|
| 535 |
+
if not path.is_file() or sha(path) != item['sha256']:
|
| 536 |
+
raise ValueError(f'corrected disease output changed: {path}')
|
| 537 |
+
data[key] = records(path)
|
| 538 |
+
names = ('fig4_disease_signal_strict', 'fig4_disease_signal_scatter',
|
| 539 |
+
'fig4_disease_signal_heatmap', 'fig4_disease_signal_cat')
|
| 540 |
+
if reason:
|
| 541 |
+
for name in names:
|
| 542 |
+
fig, ax = plt.subplots(figsize=(7.09, 3.4))
|
| 543 |
+
pending(ax, 'Figure 4 · donor-aware primary disease signal', '\n'.join(reason))
|
| 544 |
+
save(fig, name)
|
| 545 |
+
return [], reason
|
| 546 |
+
metric_defs = (('pearson_r', 'Pearson logFC r'), ('spearman_r', 'Spearman logFC r'),
|
| 547 |
+
('partial_r', 'Partial r given bulk'), ('cat50', 'Signed CAT@50'),
|
| 548 |
+
('limma_top50', 'Donor-limma top-50 overlap'))
|
| 549 |
+
types = sorted({r['celltype'] for r in data['signal']})
|
| 550 |
+
fig, axs = plt.subplots(len(metric_defs), 4, figsize=(7.09, 9.3), layout='constrained')
|
| 551 |
+
for i, (metric, label) in enumerate(metric_defs):
|
| 552 |
+
for j, cohort in enumerate(COHORTS):
|
| 553 |
+
ax = axs[i, j]
|
| 554 |
+
for t, celltype in enumerate(types):
|
| 555 |
+
for a, arm in enumerate(ARMS):
|
| 556 |
+
candidates = [r for r in data['summary'] if r['cohort'] == cohort and r['arm'] == arm and r['celltype'] == celltype]
|
| 557 |
+
if len(candidates) != 1:
|
| 558 |
+
raise ValueError('corrected disease summary has an incomplete method/type grid')
|
| 559 |
+
row = candidates[0]
|
| 560 |
+
y = t + (a - 2) * .13
|
| 561 |
+
try: value = float(row.get(metric, 'nan'))
|
| 562 |
+
except ValueError: value = float('nan')
|
| 563 |
+
if not np.isfinite(value):
|
| 564 |
+
ax.text(.98, y, 'NE', transform=ax.get_yaxis_transform(), ha='right', va='center',
|
| 565 |
+
color=COLORS[arm], fontsize=3.2)
|
| 566 |
+
continue
|
| 567 |
+
ax.plot(value, y, 'o', ms=2.5, color=COLORS[arm], label=arm if t == 0 else None)
|
| 568 |
+
try:
|
| 569 |
+
lo, hi = float(row.get(metric+'_ci_low', 'nan')), float(row.get(metric+'_ci_high', 'nan'))
|
| 570 |
+
except ValueError:
|
| 571 |
+
lo = hi = float('nan')
|
| 572 |
+
if np.isfinite([lo, hi]).all():
|
| 573 |
+
ax.plot([lo, hi], [y, y], color=COLORS[arm], lw=.65)
|
| 574 |
+
# Draw points are descriptive variation; they are not independent patients.
|
| 575 |
+
draws = [r for r in data['signal'] if r['cohort'] == cohort and r['arm'] == arm and r['celltype'] == celltype]
|
| 576 |
+
for draw in draws:
|
| 577 |
+
try: val = float(draw.get(metric, 'nan'))
|
| 578 |
+
except ValueError: val = float('nan')
|
| 579 |
+
if np.isfinite(val): ax.plot(val, y, '|', ms=3.5, alpha=.3, color=COLORS[arm])
|
| 580 |
+
if metric in ('cat50', 'limma_top50'):
|
| 581 |
+
try: chance = float(row[metric+'_chance'])
|
| 582 |
+
except (KeyError, ValueError): chance = float('nan')
|
| 583 |
+
if np.isfinite(chance): ax.plot(chance, y, 'x', ms=2.4, color='#444444')
|
| 584 |
+
ax.set_yticks(range(len(types)), types if j == 0 else [], fontsize=5.5)
|
| 585 |
+
ax.set_ylim(len(types)-.5, -.5)
|
| 586 |
+
if metric in ('pearson_r', 'spearman_r', 'partial_r'): ax.set_xlim(-1, 1)
|
| 587 |
+
elif metric == 'cat50': ax.set_xlim(0, 1)
|
| 588 |
+
else: ax.set_xlim(0, 50)
|
| 589 |
+
ax.set_xlabel(label, fontsize=6)
|
| 590 |
+
ax.tick_params(axis='x', labelsize=5.5)
|
| 591 |
+
if i == 0: ax.set_title(cohort, fontsize=7, weight='bold', loc='left')
|
| 592 |
+
handles = [plt.Line2D([0], [0], marker='o', color=COLORS[a], label=a, lw=.7, ms=3) for a in ARMS]
|
| 593 |
+
fig.legend(handles=handles, loc='outside lower center', ncol=5, fontsize=6)
|
| 594 |
+
fig.suptitle('Exact five pairs · equal-patient contrasts\nLines: patient-bootstrap 95% CI; ticks: five adaptation draws; ×: rank chance; NE: not estimable', fontsize=8)
|
| 595 |
+
save(fig, names[0])
|
| 596 |
+
# Fixed visual slice: draw0 monocytes, selected before generated results.
|
| 597 |
+
genes = [r for r in data['genes'] if r['draw'] == 'draw0' and r['celltype'] == 'monocyte']
|
| 598 |
+
if not genes:
|
| 599 |
+
# Canonical references currently spell this type with an initial capital.
|
| 600 |
+
genes = [r for r in data['genes'] if r['draw'] == 'draw0' and r['celltype'].lower() == 'monocyte']
|
| 601 |
+
finite = [abs(float(r[k])) for r in genes for k in ('observed_logFC', 'generated_logFC')
|
| 602 |
+
if r.get(k) not in ('', 'nan') and np.isfinite(float(r[k]))]
|
| 603 |
+
limit = max([1.] + finite) * 1.04
|
| 604 |
+
fig, axs = plt.subplots(5, 4, figsize=(7.09, 8.8), layout='constrained')
|
| 605 |
+
for i, arm in enumerate(ARMS):
|
| 606 |
+
for j, cohort in enumerate(COHORTS):
|
| 607 |
+
ax = axs[i, j]
|
| 608 |
+
subset = [r for r in genes if r['cohort'] == cohort and r['arm'] == arm]
|
| 609 |
+
if subset:
|
| 610 |
+
ax.scatter([number(r['observed_logFC']) for r in subset], [number(r['generated_logFC']) for r in subset],
|
| 611 |
+
s=1.1, color=COLORS[arm], alpha=.25, rasterized=True)
|
| 612 |
+
ax.plot([-limit, limit], [-limit, limit], '--', color='#555555', lw=.5)
|
| 613 |
+
ax.set(xlim=(-limit, limit), ylim=(-limit, limit))
|
| 614 |
+
else: pending(ax, arm, 'Monocyte contrast not estimable.')
|
| 615 |
+
if i == 0: ax.set_title(cohort, fontsize=7, loc='left')
|
| 616 |
+
if j == 0: ax.set_ylabel(arm+'\ngenerated logFC', fontsize=6)
|
| 617 |
+
if i == 4: ax.set_xlabel('Observed logFC', fontsize=6)
|
| 618 |
+
ax.tick_params(labelsize=5)
|
| 619 |
+
fig.suptitle('Prespecified illustration: draw 0 · monocytes · all common expressed genes', fontsize=8)
|
| 620 |
+
save(fig, names[1])
|
| 621 |
+
fig, axs = plt.subplots(2, 2, figsize=(7.09, 5.4), layout='constrained')
|
| 622 |
+
for ax, cohort in zip(axs.flat, COHORTS):
|
| 623 |
+
selected = [r for r in genes if r['cohort'] == cohort and r['arm'] == 'raw'
|
| 624 |
+
and np.isfinite(number(r['observed_logFC']))]
|
| 625 |
+
selected = sorted(selected, key=lambda r: (-abs(float(r['observed_logFC'])), r['gene_id']))[:20]
|
| 626 |
+
gene_ids = [r['gene_id'] for r in selected]
|
| 627 |
+
values = [[float(r['observed_logFC']) for r in selected]]
|
| 628 |
+
for arm in ARMS:
|
| 629 |
+
lookup = {r['gene_id']: r for r in genes if r['cohort'] == cohort and r['arm'] == arm}
|
| 630 |
+
values.append([number(lookup[g]['generated_logFC']) if g in lookup else np.nan for g in gene_ids])
|
| 631 |
+
if gene_ids:
|
| 632 |
+
im = ax.imshow(np.asarray(values), cmap='RdBu_r', vmin=-limit, vmax=limit, aspect='auto')
|
| 633 |
+
ax.set_xticks(range(len(gene_ids)), gene_ids, rotation=90, fontsize=3.8)
|
| 634 |
+
ax.set_yticks(range(6), ['observed', *ARMS], fontsize=6)
|
| 635 |
+
fig.colorbar(im, ax=ax, fraction=.025, pad=.02, label='logFC')
|
| 636 |
+
else: pending(ax, cohort, 'Monocyte contrast not estimable.')
|
| 637 |
+
ax.set_title(cohort+' · top 20 observed |logFC|', fontsize=7, loc='left')
|
| 638 |
+
save(fig, names[2])
|
| 639 |
+
fig, axs = plt.subplots(len(types), 4, figsize=(7.09, 8.8), layout='constrained', squeeze=False)
|
| 640 |
+
for i, celltype in enumerate(types):
|
| 641 |
+
for j, cohort in enumerate(COHORTS):
|
| 642 |
+
ax = axs[i, j]
|
| 643 |
+
for arm in ARMS:
|
| 644 |
+
selected = [r for r in data['cat'] if r['cohort'] == cohort and r['arm'] == arm and r['celltype'] == celltype]
|
| 645 |
+
xx, yy, chance = [], [], []
|
| 646 |
+
for k in sorted({int(r['k']) for r in selected}):
|
| 647 |
+
rr = [r for r in selected if int(r['k']) == k and r['status'] == 'ok']
|
| 648 |
+
if len(rr) == 5:
|
| 649 |
+
xx.append(k); yy.append(np.mean([float(r['cat_same_sign']) for r in rr]))
|
| 650 |
+
chance.append(np.mean([float(r['chance_same_sign']) for r in rr]))
|
| 651 |
+
if xx:
|
| 652 |
+
ax.plot(xx, yy, color=COLORS[arm], lw=.8)
|
| 653 |
+
if arm == 'raw': ax.plot(xx, chance, '--', color='#555555', lw=.6)
|
| 654 |
+
ax.set_xscale('log'); ax.set_ylim(0, 1)
|
| 655 |
+
ax.tick_params(labelsize=5)
|
| 656 |
+
if i == 0: ax.set_title(cohort, fontsize=7, loc='left')
|
| 657 |
+
if j == 0: ax.set_ylabel(celltype+'\nsigned CAT', fontsize=6)
|
| 658 |
+
if i == len(types)-1: ax.set_xlabel('Top k corrected limma |t|', fontsize=6)
|
| 659 |
+
fig.suptitle('Mean of five fixed adaptation draws; dashed: independent-rank/sign chance', fontsize=8)
|
| 660 |
+
save(fig, names[3])
|
| 661 |
+
return data['signal'], []
|
| 662 |
+
|
| 663 |
+
|
| 664 |
+
def historical_fivefold_rows() -> tuple[list[dict], list[str]]:
|
| 665 |
+
"""Match historical real-bulk LoRA and scSemiProfiler before comparing them."""
|
| 666 |
+
rows, missing = [], []
|
| 667 |
+
for cohort in COHORTS:
|
| 668 |
+
score_root = OLD/('scores_nosex' if cohort == 'giroux2022' else 'scores')/cohort
|
| 669 |
+
paths = {'lora': score_root/'pooled/summary.json',
|
| 670 |
+
'scsemi': score_root/'scsemi_cv_20261002/pooled/summary.json'}
|
| 671 |
+
if any(not p.is_file() for p in paths.values()):
|
| 672 |
+
missing.append(cohort+': historical real-bulk LoRA/scSemi five-fold pair missing')
|
| 673 |
+
continue
|
| 674 |
+
lora, scsemi = (read_json(paths[k]) for k in ('lora', 'scsemi'))
|
| 675 |
+
if (lora['donors'] != scsemi['donors']
|
| 676 |
+
or lora['reference']['reference_sha256'] != scsemi['reference']['reference_sha256']
|
| 677 |
+
or lora['reference']['features_sha256'] != scsemi['reference']['features_sha256']
|
| 678 |
+
or lora.get('gene_exclusion') != scsemi.get('gene_exclusion')
|
| 679 |
+
or lora['contrast_definition'] != scsemi['contrast_definition']):
|
| 680 |
+
raise ValueError('historical five-fold comparison does not share test/reference/gene/contrast protocol: '+cohort)
|
| 681 |
+
if cohort == 'giroux2022':
|
| 682 |
+
ex = lora.get('gene_exclusion', {})
|
| 683 |
+
if (not ex or Path(ex['file']).name != 'sex_linked_genes_exclude.csv'
|
| 684 |
+
or sha(Path(ex['file'])) != ex['sha256']):
|
| 685 |
+
raise ValueError('Giroux historical comparison requires the canonical sex-linked exclusion')
|
| 686 |
+
lp, sp = lora['per_arm']['real_lora__raw'], scsemi['per_arm']['scsemi__raw']
|
| 687 |
+
for key in ('seed', 'rule', 'n_rows_whole_npz'):
|
| 688 |
+
if lp['poisson'][key] != sp['poisson'][key]:
|
| 689 |
+
raise ValueError('historical five-fold readout differs: '+cohort)
|
| 690 |
+
if (lp['annotation']['model_pt_sha256'] != sp['annotation']['model_pt_sha256']
|
| 691 |
+
or lp['generation']['input_condition_sha256'] != sp['generation']['input_condition_sha256']):
|
| 692 |
+
raise ValueError('historical five-fold annotation or bulk condition differs: '+cohort)
|
| 693 |
+
# Fold-specific identities establish that this is the same outer split.
|
| 694 |
+
folds = []
|
| 695 |
+
for f in range(5):
|
| 696 |
+
a = OLD/'scores'/cohort/f'fold{f}'/'summary.json'
|
| 697 |
+
b = OLD/'scores'/cohort/'scsemi_cv_20261002'/f'fold{f}'/'summary.json'
|
| 698 |
+
if not a.is_file() or not b.is_file():
|
| 699 |
+
missing.append(f'{cohort}: historical fold {f} source missing')
|
| 700 |
+
break
|
| 701 |
+
aa, bb = read_json(a), read_json(b)
|
| 702 |
+
if aa['donors'] != bb['donors']:
|
| 703 |
+
raise ValueError('historical outer-fold samples differ: '+cohort)
|
| 704 |
+
folds.extend(aa['donors'])
|
| 705 |
+
if len(folds) != len(set(folds)) or set(folds) != set(lora['donors']):
|
| 706 |
+
raise ValueError('historical pooled samples do not cover five disjoint test folds: '+cohort)
|
| 707 |
+
for arm, source_name, summary, path in (('lora', 'real_lora__raw', lora, paths['lora']),
|
| 708 |
+
('scsemi', 'scsemi__raw', scsemi, paths['scsemi']),
|
| 709 |
+
('raw', 'zs__raw', lora, paths['lora']),
|
| 710 |
+
('legacy_cal', 'zs__cal', lora, paths['lora'])):
|
| 711 |
+
if source_name not in summary['per_arm']:
|
| 712 |
+
missing.append(f'{cohort}: historical {source_name} missing'); continue
|
| 713 |
+
pa = summary['per_arm'][source_name]
|
| 714 |
+
contrast = pa.get('contrast', {}).get('mean_cp10k', {})
|
| 715 |
+
rows.append({'cohort': cohort, 'design': 'historical_5fold_separate', 'arm': arm,
|
| 716 |
+
'source_arm': source_name, 'pb_r_median': pa.get('pseudobulk', {}).get('r_median'),
|
| 717 |
+
'comp_l1_mean': pa.get('composition', {}).get('l1_mean'),
|
| 718 |
+
'logfc_pearson_legacy_mean': contrast.get('mean_r_generated'),
|
| 719 |
+
'partial_r_legacy_mean': contrast.get('mean_partial_r'),
|
| 720 |
+
'deg_welch_legacy_sum': pa.get('deg_top50', {}).get('sum'),
|
| 721 |
+
'statistical_scope': 'historical sample-level estimators; not donor-corrected strict primary',
|
| 722 |
+
'n_test_samples': len(summary['donors']), 'reference_sha256': summary['reference']['reference_sha256'],
|
| 723 |
+
'gene_exclusion_sha256': summary.get('gene_exclusion', {}).get('sha256', ''),
|
| 724 |
+
'source': str(path), 'source_sha256': sha(path)})
|
| 725 |
+
return rows, missing
|
| 726 |
+
|
| 727 |
+
|
| 728 |
+
def fig4(all_units: dict[str,list[dict]], all_missing: dict[str,list[str]],
|
| 729 |
+
deconvolution_manifest: Path | None = None):
|
| 730 |
+
rows=[]; statrows=[]; contrast_rows=[]; legacy_contrast_missing=[]
|
| 731 |
+
fig,axs=plt.subplots(2,2,figsize=(7.09,5.2),layout='constrained')
|
| 732 |
+
for ax,cohort in zip(axs.flat,COHORTS):
|
| 733 |
+
units=all_units[cohort]
|
| 734 |
+
complete=len(units)==5 and not all_missing[cohort]
|
| 735 |
+
if not complete:
|
| 736 |
+
pending(ax,cohort,'Exact five-pair disease draws and corrected donor statistics pending.')
|
| 737 |
+
continue
|
| 738 |
+
for u in units:
|
| 739 |
+
patient_of = dict(zip(u['support']['test_sample_ids'], u['support']['test_donor_ids']))
|
| 740 |
+
for r in u['rows']:
|
| 741 |
+
rows.append({'cohort':cohort,'design':'strict_exact5_donor_draw','draw':u['support']['unit'].removesuffix('_n5'),
|
| 742 |
+
'arm':r['arm'],'sample_id':r['donor'],'donor_id':patient_of[r['donor']], 'comp_l1':r.get('comp_l1',''),
|
| 743 |
+
'pb_r':r.get('pb_r',''),'support_sha256':u['support']['sha256'],
|
| 744 |
+
'summary_sha256':sha(Path(u['summary_path']))})
|
| 745 |
+
sf=Path(u['stat_path']).parent/'donor_bootstrap_2000.csv'
|
| 746 |
+
for r in records(sf):
|
| 747 |
+
statrows.append({'cohort':cohort,**r,'draw':u['support']['unit'].removesuffix('_n5'),
|
| 748 |
+
'support_sha256':u['support']['sha256'],'source_sha256':sha(sf)})
|
| 749 |
+
cb=ROOT/'scores'/u['rel']/'contrast'/cohort/'strict'
|
| 750 |
+
manifest=cb/'manifest.json'
|
| 751 |
+
required=('headline.csv','cat.csv','deg_limma.csv')
|
| 752 |
+
if not manifest.is_file() or any(not (cb/f).is_file() for f in required):
|
| 753 |
+
legacy_contrast_missing.append(f'{u["rel"]}: historical-sensitivity contrast pending')
|
| 754 |
+
else:
|
| 755 |
+
cm=read_json(manifest)
|
| 756 |
+
call=cm.get('calls',{}).get(u['summary_path'])
|
| 757 |
+
if not call or call.get('summary_sha256')!=sha(Path(u['summary_path'])):
|
| 758 |
+
raise ValueError(f'Figure 4 contrast does not bind strict score: {manifest}')
|
| 759 |
+
for filename in required:
|
| 760 |
+
source=cb/filename
|
| 761 |
+
for r in records(source):
|
| 762 |
+
contrast_rows.append({'cohort':cohort,'draw':u['support']['unit'].removesuffix('_n5'),
|
| 763 |
+
'design':'legacy_visit_level_sensitivity_not_primary',
|
| 764 |
+
'table':filename,'source_sha256':sha(source),**r})
|
| 765 |
+
for j,arm in enumerate(ARMS):
|
| 766 |
+
patient_values={}
|
| 767 |
+
for r in rows:
|
| 768 |
+
if r['cohort']==cohort and r['arm']==arm and r['pb_r']:
|
| 769 |
+
patient_values.setdefault(r['donor_id'],[]).append(float(r['pb_r']))
|
| 770 |
+
if patient_values:
|
| 771 |
+
ax.bar(j,np.mean([np.mean(values) for values in patient_values.values()]),color=COLORS[arm])
|
| 772 |
+
ax.set_xticks(range(5),ARMS,rotation=30,ha='right',fontsize=6)
|
| 773 |
+
ax.set_title(cohort+' · strict exact five-pair draws',loc='left',weight='bold')
|
| 774 |
+
ax.set_ylabel('Patient-mean pseudobulk correlation')
|
| 775 |
+
save(fig,'fig4_disease_strict_draws')
|
| 776 |
+
write_csv(ROOT/'source_data/fig4_strict_per_sample.csv',rows,
|
| 777 |
+
['cohort','design','draw','arm','sample_id','donor_id','comp_l1','pb_r','support_sha256','summary_sha256'])
|
| 778 |
+
if statrows:
|
| 779 |
+
cols=list(dict.fromkeys(k for r in statrows for k in r))
|
| 780 |
+
write_csv(ROOT/'source_data/fig4_corrected_statistics.csv',statrows,cols)
|
| 781 |
+
if contrast_rows:
|
| 782 |
+
write_csv(ROOT/'source_data/fig4_strict_contrast.csv',contrast_rows,
|
| 783 |
+
list(dict.fromkeys(k for r in contrast_rows for k in r)))
|
| 784 |
+
corrected_rows, contrast_missing = donor_signal_panels(all_units)
|
| 785 |
+
deconv_rows=[]; deconv_missing=[]; deconv_signal=[]; signal_missing=[]
|
| 786 |
+
mapping=deconvolution_manifest or ROOT/'deconvolution/deconvolution_manifest.json'
|
| 787 |
+
if mapping.is_file():
|
| 788 |
+
dm=read_json(mapping)
|
| 789 |
+
if dm.get('schema')!='pbisc.fig4.deconvolution-sources.v1':
|
| 790 |
+
raise ValueError('wrong Figure 4 deconvolution mapping schema')
|
| 791 |
+
configs=dm.get('units',{})
|
| 792 |
+
for cohort in COHORTS:
|
| 793 |
+
for u in all_units[cohort]:
|
| 794 |
+
config=configs.get(u['rel'])
|
| 795 |
+
if not config:
|
| 796 |
+
deconv_missing.append(f'{u["rel"]}: no deconvolution mapping');continue
|
| 797 |
+
source=Path(config['csv'])
|
| 798 |
+
if (config.get('support_sha256')!=u['support']['sha256'] or not source.is_file()
|
| 799 |
+
or sha(source)!=config.get('sha256')):
|
| 800 |
+
raise ValueError(f'deconvolution source/provenance mismatch: {u["rel"]}')
|
| 801 |
+
if (set(config.get('reference_sample_ids',[]))!=set(u['support']['train_sample_ids'])
|
| 802 |
+
or set(config.get('mixture_sample_ids',[]))!=set(u['support']['test_sample_ids'])):
|
| 803 |
+
raise ValueError(f'deconvolution reference/mixture support mismatch: {u["rel"]}')
|
| 804 |
+
vals=records(source)
|
| 805 |
+
if not vals or not {'arm','sample_id','donor_id','cell_type','observed','predicted','composition_l1'} <= set(vals[0]):
|
| 806 |
+
raise ValueError(f'deconvolution columns missing: {source}')
|
| 807 |
+
patient_of=dict(zip(u['support']['test_sample_ids'],u['support']['test_donor_ids']))
|
| 808 |
+
if ({r['sample_id'] for r in vals} != set(u['support']['test_sample_ids'])
|
| 809 |
+
or {r['arm'] for r in vals} != set(DECONV_METHODS)
|
| 810 |
+
or {(r['sample_id'],r['arm']) for r in vals}!={(s,a) for s in patient_of for a in DECONV_METHODS}
|
| 811 |
+
or any(r['donor_id']!=patient_of[r['sample_id']] for r in vals)):
|
| 812 |
+
raise ValueError(f'deconvolution samples/arms differ from strict support: {source}')
|
| 813 |
+
for r in vals:
|
| 814 |
+
deconv_rows.append({'cohort':cohort,'draw':u['support']['unit'].removesuffix('_n5'),
|
| 815 |
+
'support_sha256':u['support']['sha256'],
|
| 816 |
+
'source_sha256':sha(source),**r})
|
| 817 |
+
signal_path=Path(config.get('signal_csv',''))
|
| 818 |
+
if not signal_path.is_file() or not config.get('signal_sha256'):
|
| 819 |
+
signal_missing.append(f'{u["rel"]}: cell-type expression signal missing')
|
| 820 |
+
elif sha(signal_path)!=config['signal_sha256']:
|
| 821 |
+
raise ValueError(f'deconvolution signal hash differs: {u["rel"]}')
|
| 822 |
+
else:
|
| 823 |
+
signal_vals=records(signal_path)
|
| 824 |
+
needed={'arm','cell_type','metric','value','status','gene_variant','statistic',
|
| 825 |
+
'n_genes','n_test_samples','n_independent_donors','n_case_samples',
|
| 826 |
+
'n_control_samples','method_expression_unit','deg_method'}
|
| 827 |
+
if not signal_vals or not needed <= set(signal_vals[0]):
|
| 828 |
+
raise ValueError(f'deconvolution expression columns missing: {signal_path}')
|
| 829 |
+
if {r['arm'] for r in signal_vals}!=set(DECONV_METHODS):
|
| 830 |
+
raise ValueError(f'deconvolution expression methods differ: {signal_path}')
|
| 831 |
+
for r in signal_vals:
|
| 832 |
+
if r['status'] in ('ok','available','complete'):
|
| 833 |
+
try: valid=np.isfinite(float(r['value']))
|
| 834 |
+
except ValueError: valid=False
|
| 835 |
+
if not valid:
|
| 836 |
+
raise ValueError(f'available deconvolution expression has no finite value: {signal_path}')
|
| 837 |
+
deconv_signal.append({'cohort':cohort,'draw':u['support']['unit'].removesuffix('_n5'),
|
| 838 |
+
'support_sha256':u['support']['sha256'],
|
| 839 |
+
'source_sha256':sha(signal_path),**r})
|
| 840 |
+
else:
|
| 841 |
+
deconv_missing.append(f'{mapping} missing')
|
| 842 |
+
if deconv_rows:
|
| 843 |
+
write_csv(ROOT/'source_data/fig4_deconvolution.csv',deconv_rows,
|
| 844 |
+
list(dict.fromkeys(k for r in deconv_rows for k in r)))
|
| 845 |
+
dfig,daxs=plt.subplots(2,2,figsize=(7.09,5.2),layout='constrained')
|
| 846 |
+
for ax,cohort in zip(daxs.flat,COHORTS):
|
| 847 |
+
for arm in DECONV_METHODS:
|
| 848 |
+
rr=[r for r in deconv_rows if r['cohort']==cohort and r['arm']==arm]
|
| 849 |
+
if rr:
|
| 850 |
+
obs=np.asarray([float(r['observed']) for r in rr]);pred=np.asarray([float(r['predicted']) for r in rr])
|
| 851 |
+
ax.scatter(obs,pred,s=3,alpha=.25,label=arm,color=COLORS[arm])
|
| 852 |
+
ax.plot([0,1],[0,1],color='#444444',linewidth=.7,linestyle='--')
|
| 853 |
+
ax.set(xlim=(0,1),ylim=(0,1),xlabel='Observed fraction',ylabel='Predicted fraction')
|
| 854 |
+
ax.set_title(cohort+' · strict same-support',loc='left',weight='bold')
|
| 855 |
+
daxs[0,0].legend(fontsize=5)
|
| 856 |
+
save(dfig,'fig4_deconvolution_strict')
|
| 857 |
+
if deconv_signal:
|
| 858 |
+
write_csv(ROOT/'source_data/fig4_deconvolution_signal.csv',deconv_signal,
|
| 859 |
+
list(dict.fromkeys(k for r in deconv_signal for k in r)))
|
| 860 |
+
efig,eaxs=plt.subplots(3,4,figsize=(7.09,5.5),layout='constrained')
|
| 861 |
+
definitions=(('donor_logfc_r','Donor logFC r'),
|
| 862 |
+
('donor_partial_r_given_bulk','Donor partial r'),
|
| 863 |
+
('donor_limma_top50_overlap','Donor limma top-50'))
|
| 864 |
+
for i,(metric,label) in enumerate(definitions):
|
| 865 |
+
for j,cohort in enumerate(COHORTS):
|
| 866 |
+
ax=eaxs[i,j]
|
| 867 |
+
found=False
|
| 868 |
+
for k,arm in enumerate(DECONV_METHODS):
|
| 869 |
+
rr=[r for r in deconv_signal if r['cohort']==cohort and r['arm']==arm
|
| 870 |
+
and r['metric']==metric and r['status'] in ('ok','available','complete')
|
| 871 |
+
and r['gene_variant']=='donor_covered']
|
| 872 |
+
if rr:
|
| 873 |
+
found=True
|
| 874 |
+
ax.bar(k,np.mean([float(r['value']) for r in rr]),color=COLORS[arm])
|
| 875 |
+
if not found: pending(ax,label,'Donor-aware method signal is not estimable or pending.')
|
| 876 |
+
else: ax.set_xticks(range(len(DECONV_METHODS)),DECONV_METHODS,rotation=45,ha='right',fontsize=5)
|
| 877 |
+
if i==0: ax.set_title(cohort,loc='left',weight='bold',fontsize=7)
|
| 878 |
+
if j==0: ax.set_ylabel(label,fontsize=7)
|
| 879 |
+
save(efig,'fig4_deconvolution_expression_strict')
|
| 880 |
+
hfig,haxs=plt.subplots(3,4,figsize=(7.09,5.5),layout='constrained')
|
| 881 |
+
historical=(('logfc_r','LogFC r · zero-filled'),
|
| 882 |
+
('partial_r_given_bulk','Partial r · zero-filled'),
|
| 883 |
+
('top50_deg_overlap','Welch top-50 · exploratory'))
|
| 884 |
+
for i,(metric,label) in enumerate(historical):
|
| 885 |
+
for j,cohort in enumerate(COHORTS):
|
| 886 |
+
ax=haxs[i,j]
|
| 887 |
+
for k,arm in enumerate(DECONV_METHODS):
|
| 888 |
+
rr=[r for r in deconv_signal if r['cohort']==cohort and r['arm']==arm
|
| 889 |
+
and r['metric']==metric and r['status']=='ok'
|
| 890 |
+
and (metric=='top50_deg_overlap' or
|
| 891 |
+
r['gene_variant']=='zero_filled' and r['statistic']=='mean_cp10k')]
|
| 892 |
+
if rr: ax.bar(k,np.mean([float(r['value']) for r in rr]),color=COLORS[arm])
|
| 893 |
+
ax.set_xticks(range(len(DECONV_METHODS)),DECONV_METHODS,rotation=45,ha='right',fontsize=5)
|
| 894 |
+
if i==0: ax.set_title(cohort,loc='left',weight='bold',fontsize=7)
|
| 895 |
+
if j==0: ax.set_ylabel(label,fontsize=7)
|
| 896 |
+
save(hfig,'fig4_deconvolution_historical_signal')
|
| 897 |
+
sfig,saxs=plt.subplots(2,4,figsize=(7.09,3.8),layout='constrained')
|
| 898 |
+
for i,(metric,label) in enumerate((('logfc_r','LogFC r'),
|
| 899 |
+
('partial_r_given_bulk','Partial r'))):
|
| 900 |
+
for j,cohort in enumerate(COHORTS):
|
| 901 |
+
ax=saxs[i,j]
|
| 902 |
+
for k,arm in enumerate(DECONV_METHODS):
|
| 903 |
+
for v,variant in enumerate(('zero_filled','covered')):
|
| 904 |
+
rr=[r for r in deconv_signal if r['cohort']==cohort and r['arm']==arm
|
| 905 |
+
and r['metric']==metric and r['gene_variant']==variant
|
| 906 |
+
and r['statistic']=='mean_cp10k' and r['status']=='ok']
|
| 907 |
+
if rr:ax.bar(k+(.22 if v else -.22),np.mean([float(r['value']) for r in rr]),
|
| 908 |
+
width=.38,color=COLORS[arm],alpha=1 if v==0 else .55,
|
| 909 |
+
hatch='' if v==0 else '//')
|
| 910 |
+
ax.set_xticks(range(len(DECONV_METHODS)),DECONV_METHODS,rotation=45,ha='right',fontsize=5)
|
| 911 |
+
if i==0:ax.set_title(cohort,loc='left',weight='bold',fontsize=7)
|
| 912 |
+
if j==0:ax.set_ylabel(label+'\nsolid: zero-filled\nhatched: covered',fontsize=6)
|
| 913 |
+
save(sfig,'fig4_deconvolution_covered_sensitivity')
|
| 914 |
+
legacy, historical_missing = historical_fivefold_rows()
|
| 915 |
+
write_csv(ROOT/'source_data/fig4_historical_5fold.csv',legacy,
|
| 916 |
+
list(dict.fromkeys(k for r in legacy for k in r)) if legacy else ['cohort','design','arm'])
|
| 917 |
+
oldfig,oldaxs=plt.subplots(3,4,figsize=(7.09,6.2),layout='constrained')
|
| 918 |
+
for i,(metric,label) in enumerate((('pb_r_median','Pseudobulk r median'),
|
| 919 |
+
('logfc_pearson_legacy_mean','Historical logFC r'),
|
| 920 |
+
('partial_r_legacy_mean','Historical partial r'))):
|
| 921 |
+
for j,cohort in enumerate(COHORTS):
|
| 922 |
+
ax=oldaxs[i,j]
|
| 923 |
+
rr=[r for r in legacy if r['cohort']==cohort and r.get(metric) is not None]
|
| 924 |
+
for k,r in enumerate(rr):ax.bar(k,float(r[metric]),color=COLORS.get(r['arm'],'#666666'))
|
| 925 |
+
ax.set_xticks(range(len(rr)),[r['arm'] for r in rr],rotation=60,ha='right',fontsize=5)
|
| 926 |
+
if i==0:ax.set_title(cohort,loc='left',weight='bold',fontsize=7)
|
| 927 |
+
if j==0:ax.set_ylabel(label,fontsize=7)
|
| 928 |
+
oldfig.suptitle('Historical donor-level five-fold design · original sample-level signal estimator\nReal-bulk LoRA and scSemiProfiler share test folds, reference, gene exclusion and readout',fontsize=8)
|
| 929 |
+
save(oldfig,'fig4_historical_5fold_separate')
|
| 930 |
+
return {'strict_complete_draws':{c:len(all_units[c]) for c in COHORTS},
|
| 931 |
+
'strict_expected_draws_per_cohort':5,'strict_missing':all_missing,
|
| 932 |
+
'historical_design':'historical_5fold_separate','legacy_rows':len(legacy),
|
| 933 |
+
'historical_missing':historical_missing,
|
| 934 |
+
'contrast_rows':len(corrected_rows),'contrast_missing':contrast_missing,
|
| 935 |
+
'legacy_contrast_rows':len(contrast_rows),'legacy_contrast_missing':legacy_contrast_missing,
|
| 936 |
+
'primary_signal_source':'fig4_donor_aware_signal.csv; corrected patient-aware counts/limma',
|
| 937 |
+
'deconvolution_rows':len(deconv_rows),'deconvolution_missing':deconv_missing,
|
| 938 |
+
'deconvolution_signal_rows':len(deconv_signal),'deconvolution_signal_missing':signal_missing,
|
| 939 |
+
'deconvolution_scope':'composition and method-supported cell-type expression; no generated-cell P/C',
|
| 940 |
+
'deconvolution_deg':'donor-aware continuous-expression limma sensitivity primary where estimable; historical Welch separate'}
|
| 941 |
+
|
| 942 |
+
|
| 943 |
+
def self_test_collectors():
|
| 944 |
+
"""Exercise pending, invalid design, and mismatched score provenance in isolation."""
|
| 945 |
+
global ROOT
|
| 946 |
+
original=ROOT
|
| 947 |
+
try:
|
| 948 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 949 |
+
ROOT=Path(tmp)
|
| 950 |
+
path=ROOT/'protocol/splits/immicro/healthy/fold0/n5/support.json'
|
| 951 |
+
path.parent.mkdir(parents=True)
|
| 952 |
+
support={'schema':'pbisc.paper.strict-support.v1','cohort':'immicro',
|
| 953 |
+
'design':'healthy_outerfold','unit':'fold0_n5','n_pairs':5,
|
| 954 |
+
'train_sample_ids':[f'T{i}' for i in range(5)],
|
| 955 |
+
'train_donor_ids':[f'T{i}' for i in range(5)],
|
| 956 |
+
'test_sample_ids':['Q'],'test_donor_ids':['Q']}
|
| 957 |
+
def write():
|
| 958 |
+
body={k:v for k,v in support.items() if k!='sha256'}
|
| 959 |
+
support['sha256']=hashlib.sha256(json.dumps(body,sort_keys=True,separators=(',',':')).encode()).hexdigest()
|
| 960 |
+
path.write_text(json.dumps(support))
|
| 961 |
+
write()
|
| 962 |
+
assert strict_unit(path)[0] is None, 'missing score must remain pending'
|
| 963 |
+
support['design']='historical_nplus7';write()
|
| 964 |
+
try: strict_unit(path)
|
| 965 |
+
except ValueError as e: assert 'wrong strict support design' in str(e)
|
| 966 |
+
else: raise AssertionError('wrong design accepted')
|
| 967 |
+
support['design']='healthy_outerfold';write()
|
| 968 |
+
summary=ROOT/'scores/immicro/healthy/fold0/n5/score/summary.json'
|
| 969 |
+
summary.parent.mkdir(parents=True)
|
| 970 |
+
summary.write_text(json.dumps({'schema':'paired_ft_scores.v1','dataset':'immicro',
|
| 971 |
+
'donors':['WRONG'],'arms':list(ARMS)}))
|
| 972 |
+
try: strict_unit(path)
|
| 973 |
+
except ValueError as e: assert 'score/test sample mismatch' in str(e)
|
| 974 |
+
else: raise AssertionError('mismatched score provenance accepted')
|
| 975 |
+
summary.write_text(json.dumps({'schema':'paired_ft_scores.v1','dataset':'immicro',
|
| 976 |
+
'donors':['Q'],'arms':list(ARMS)}))
|
| 977 |
+
assert 'missing strict score binding' in strict_unit(path)[1]
|
| 978 |
+
binding=summary.parent.parent/'scoring_support.json'
|
| 979 |
+
binding.write_text(json.dumps({'schema':'pbisc.paper.strict-score-binding.v1',
|
| 980 |
+
'support_sha256':'WRONG','arm_bindings':{}}))
|
| 981 |
+
try: strict_unit(path)
|
| 982 |
+
except ValueError as e: assert 'strict score binding differs' in str(e)
|
| 983 |
+
else: raise AssertionError('wrong strict binding accepted')
|
| 984 |
+
finally:
|
| 985 |
+
ROOT=original
|
| 986 |
+
print('collector self-test passed: pending, wrong design, wrong score/test and binding provenance')
|
| 987 |
+
|
| 988 |
+
|
| 989 |
+
def main():
|
| 990 |
+
p=argparse.ArgumentParser()
|
| 991 |
+
p.add_argument('--require-complete',action='store_true')
|
| 992 |
+
p.add_argument('--self-test',action='store_true')
|
| 993 |
+
p.add_argument('--deconvolution-manifest',type=Path,
|
| 994 |
+
help='explicit same-support disease deconvolution source mapping')
|
| 995 |
+
a=p.parse_args()
|
| 996 |
+
if a.self_test:
|
| 997 |
+
self_test_collectors();return
|
| 998 |
+
pre=records(ROOT/'source_data/ablation_pretrain_pc.csv')
|
| 999 |
+
receipt=ROOT/'source_data/ablation_pretrain_pc_receipt.json'
|
| 1000 |
+
pr=read_json(receipt)
|
| 1001 |
+
if (pr.get('schema')!='pbisc.fig2.pretrain_pc.v1' or pr.get('recipe',{}).get('n_pcs')!=50
|
| 1002 |
+
or pr.get('recipe',{}).get('local_k')!=10 or pr.get('gene_axis',{}).get('n')!=1006):
|
| 1003 |
+
raise ValueError('Figure 2 pretraining receipt differs from shared P/C protocol')
|
| 1004 |
+
expected={'architecture_floor1pct','panel_floor0.1pct'}
|
| 1005 |
+
if {r['family'] for r in pre}!=expected or not all(r['n_genes']=='1006' and r['n_donors']=='42' and r['local_k']=='10' for r in pre):
|
| 1006 |
+
raise ValueError('Figure 2 pretraining source has wrong families or shared rescore definition')
|
| 1007 |
+
healthy, hm=collect('immicro','healthy',sizes=(5,10,20,40))
|
| 1008 |
+
h5,h5m=collect('immicro','healthy',sizes=(5,))
|
| 1009 |
+
disease={}; missing={}
|
| 1010 |
+
for cohort in COHORTS:
|
| 1011 |
+
disease[cohort],missing[cohort]=collect(cohort,'disease',require_stats=True)
|
| 1012 |
+
out={'schema':'pbisc.paper.figures234.v1',
|
| 1013 |
+
'figure2':fig2(pre,healthy,hm,[]),
|
| 1014 |
+
'figure3':fig3(h5,h5m),
|
| 1015 |
+
'figure4':fig4(disease,missing,a.deconvolution_manifest)}
|
| 1016 |
+
complete=(out['figure2']['strict_complete_units']==20 and out['figure2']['pretrain_composition_ready']
|
| 1017 |
+
and out['figure3']['visual_export_ready']
|
| 1018 |
+
and out['figure3']['extras_complete'] and out['figure3']['runtime_ready']
|
| 1019 |
+
and all(len(disease[c])==5 for c in COHORTS)
|
| 1020 |
+
and not out['figure4']['contrast_missing'] and not out['figure4']['deconvolution_missing']
|
| 1021 |
+
and not out['figure4']['deconvolution_signal_missing'])
|
| 1022 |
+
out['status']='complete' if complete else 'pending'
|
| 1023 |
+
(ROOT/'reports/figures234_readiness.json').write_text(json.dumps(out,indent=2)+'\n')
|
| 1024 |
+
lines=['# Figure 2–4 readiness','',f"Status: **{out['status']}**.",'',
|
| 1025 |
+
'Figure 2 measured pretraining P/C is plotted. Historical rank/full uses a pooled 107-donor reference; strict size points will use each outer fold\'s 21–22 donor reference.',
|
| 1026 |
+
f"Strict healthy support-size scores: {len(healthy)}/20 units. Figure 3 strict n=5 folds: {len(h5)}/5; visual export: {out['figure3']['visual_export_ready']}.",
|
| 1027 |
+
'Figure 4 corrected exact-five-pair draws: '+', '.join(f'{c} {len(disease[c])}/5' for c in COHORTS)+'.',
|
| 1028 |
+
f"Figure 4 deconvolution composition rows: {out['figure4']['deconvolution_rows']}; expression signal rows: {out['figure4']['deconvolution_signal_rows']}.",
|
| 1029 |
+
'', 'No strict, DEG, deconvolution, C2ST, MMD, energy, marker, or runtime value is inferred from a missing file.',
|
| 1030 |
+
'Historical five-fold values remain in separate source tables.']
|
| 1031 |
+
(ROOT/'reports/figures234_readiness.md').write_text('\n'.join(lines)+'\n')
|
| 1032 |
+
print(json.dumps({'status':out['status'],'strict_healthy':len(healthy),'strict_disease':{c:len(disease[c]) for c in COHORTS}}))
|
| 1033 |
+
if a.require_complete and not complete: raise SystemExit(2)
|
| 1034 |
+
|
| 1035 |
+
if __name__=='__main__': main()
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/build_review_deck.py
ADDED
|
@@ -0,0 +1,280 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Assemble a clearly labeled review PPTX; fail closed for a final deck."""
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
import argparse
|
| 5 |
+
import csv
|
| 6 |
+
import hashlib
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import re
|
| 10 |
+
import tempfile
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
|
| 13 |
+
raise SystemExit("Set CUDA_VISIBLE_DEVICES='' for the CPU deck builder")
|
| 14 |
+
from pptx import Presentation
|
| 15 |
+
from pptx.util import Inches, Pt
|
| 16 |
+
from pptx.dml.color import RGBColor
|
| 17 |
+
from pptx.enum.shapes import MSO_SHAPE
|
| 18 |
+
|
| 19 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 20 |
+
COHORTS=('ye2026_sepsis','imperial_eskd','giroux2022','ji2025_chili')
|
| 21 |
+
RARE_ARMS={'raw','refcal','pairedcal','scsemi','lora'}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def sha(path: Path) -> str:
|
| 25 |
+
h=hashlib.sha256()
|
| 26 |
+
with path.open('rb') as f:
|
| 27 |
+
for chunk in iter(lambda:f.read(1<<20),b''):h.update(chunk)
|
| 28 |
+
return h.hexdigest()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def final_gate(root: Path) -> dict:
|
| 32 |
+
"""Fail closed unless Figures 2–5 have current strict source evidence."""
|
| 33 |
+
ready=json.loads((root/'reports/figures234_readiness.json').read_text())
|
| 34 |
+
if ready.get('status')!='complete':
|
| 35 |
+
raise ValueError('Figure 2–4 strict results are pending')
|
| 36 |
+
provenance=root/'reports/rare_provenance.json'
|
| 37 |
+
visual=root/'reports/rare_visual_provenance.json'
|
| 38 |
+
if not provenance.is_file() or not visual.is_file():
|
| 39 |
+
raise ValueError('strict Figure 5 numeric or visual provenance missing')
|
| 40 |
+
rare=json.loads(provenance.read_text());vis=json.loads(visual.read_text())
|
| 41 |
+
expected={(c,f'draw{i}') for c in COHORTS for i in range(5)}
|
| 42 |
+
units=rare.get('units',[])
|
| 43 |
+
if (rare.get('schema')!='pbisc.figure5.analysis.v1' or len(units)!=20
|
| 44 |
+
or {(u.get('cohort'),u.get('unit')) for u in units}!=expected
|
| 45 |
+
or any(u.get('design')!='strict5pair' or u.get('evidence_tier')!='strict' for u in units)
|
| 46 |
+
or rare.get('visuals',{}).get('status')!='complete'):
|
| 47 |
+
raise ValueError('Figure 5 source is diagnostic or incomplete; exact 20 strict units required')
|
| 48 |
+
if (vis.get('schema')!='pbisc.figure5.marker-visuals.v1' or vis.get('status')!='complete'
|
| 49 |
+
or vis.get('evidence_tier')!='strict' or len(vis.get('examples',[]))!=3
|
| 50 |
+
or not any(x.get('status')=='available' for x in vis['examples'])
|
| 51 |
+
or any(x.get('status') not in ('available','unavailable') for x in vis['examples'])):
|
| 52 |
+
raise ValueError('Figure 5 strict marker visuals incomplete')
|
| 53 |
+
hashes={str(provenance):sha(provenance),str(visual):sha(visual)}
|
| 54 |
+
for name in ('rare_per_sample.csv','rare_per_donor.csv','rare_summary.csv','rare_ineligible_states.csv',
|
| 55 |
+
'rare_visual_cells.csv','rare_visual_heatmap.csv','rare_visual_donor_draws.csv'):
|
| 56 |
+
path=root/'source_data'/name
|
| 57 |
+
if not path.is_file() or path.stat().st_size==0:raise ValueError(f'Figure 5 source data missing: {path}')
|
| 58 |
+
hashes[str(path)]=sha(path)
|
| 59 |
+
for name in ('rare_per_sample.csv','rare_per_donor.csv','rare_summary.csv'):
|
| 60 |
+
path=root/'source_data'/name
|
| 61 |
+
with path.open(newline='') as f:
|
| 62 |
+
reader=csv.DictReader(f)
|
| 63 |
+
if not reader.fieldnames or 'evidence_tier' not in reader.fieldnames:
|
| 64 |
+
raise ValueError(f'Figure 5 table lacks evidence tier: {path}')
|
| 65 |
+
if not any(True for _ in reader):raise ValueError(f'Figure 5 table empty: {path}')
|
| 66 |
+
with path.open(newline='') as f:
|
| 67 |
+
if any(r['evidence_tier']!='strict' for r in csv.DictReader(f)):
|
| 68 |
+
raise ValueError(f'Figure 5 table mixes diagnostic rows: {path}')
|
| 69 |
+
for u in units:
|
| 70 |
+
cohort,draw=u['cohort'],u['unit']
|
| 71 |
+
manifest=root/'work/rare_strict_caches'/cohort/'disease'/draw/'rare_manifest.json'
|
| 72 |
+
support=root/'protocol/splits'/cohort/'disease'/draw/'support.json'
|
| 73 |
+
if not manifest.is_file() or not support.is_file():
|
| 74 |
+
raise ValueError(f'Figure 5 strict support/cache manifest missing: {cohort}/{draw}')
|
| 75 |
+
s=json.loads(support.read_text());body={k:v for k,v in s.items() if k!='sha256'}
|
| 76 |
+
digest=hashlib.sha256(json.dumps(body,sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest()
|
| 77 |
+
if s.get('sha256')!=digest or u.get('support_sha256')!=digest:
|
| 78 |
+
raise ValueError(f'Figure 5 support hash differs: {cohort}/{draw}')
|
| 79 |
+
m=json.loads(manifest.read_text())
|
| 80 |
+
mu=m.get('units',[])
|
| 81 |
+
if (m.get('schema')!='pbisc.figure5.marker-caches.v1' or len(mu)!=1
|
| 82 |
+
or mu[0].get('cohort')!=cohort or mu[0].get('unit')!=draw
|
| 83 |
+
or mu[0].get('design')!='strict5pair'
|
| 84 |
+
or Path(mu[0].get('support_manifest','')).resolve()!=support.resolve()
|
| 85 |
+
or set(mu[0].get('generated_caches',{}))!=RARE_ARMS):
|
| 86 |
+
raise ValueError(f'Figure 5 cache manifest design/arms differ: {cohort}/{draw}')
|
| 87 |
+
item=mu[0]
|
| 88 |
+
cache_paths={'observed':(item['observed_cache'],item['observed_cache_sha256'])}
|
| 89 |
+
cache_paths.update({arm:(item['generated_caches'][arm],item['generated_cache_sha256'][arm])
|
| 90 |
+
for arm in RARE_ARMS})
|
| 91 |
+
for arm,(raw,expected_sha) in cache_paths.items():
|
| 92 |
+
path=Path(raw)
|
| 93 |
+
if not path.is_file() or sha(path)!=expected_sha:
|
| 94 |
+
raise ValueError(f'Figure 5 {arm} source hash differs: {cohort}/{draw}')
|
| 95 |
+
hashes[str(path)]=expected_sha
|
| 96 |
+
if u.get('cache_paths')!=item['generated_caches']:
|
| 97 |
+
raise ValueError(f'Figure 5 analyzed cache paths differ: {cohort}/{draw}')
|
| 98 |
+
hashes[str(manifest)]=sha(manifest);hashes[str(support)]=sha(support)
|
| 99 |
+
for stem in ('fig5_rare_states_strict','fig5_rare_visuals_strict','fig5_all_states_strict','fig5_behcet_rules_strict'):
|
| 100 |
+
for ext in ('pdf','svg','png'):
|
| 101 |
+
path=root/'figures'/f'{stem}.{ext}'
|
| 102 |
+
if not path.is_file() or path.stat().st_size==0:
|
| 103 |
+
raise ValueError(f'Figure 5 strict figure missing: {path}')
|
| 104 |
+
hashes[str(path)]=sha(path)
|
| 105 |
+
return {'schema':'pbisc.review-deck.final-gate.v1','status':'complete',
|
| 106 |
+
'strict_rare_units':20,'source_sha256':hashes}
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def text(slide,x,y,w,h,value,size=16,bold=False,color=(25,38,48)):
|
| 110 |
+
box=slide.shapes.add_textbox(Inches(x),Inches(y),Inches(w),Inches(h))
|
| 111 |
+
frame=box.text_frame;frame.word_wrap=True
|
| 112 |
+
p=frame.paragraphs[0];p.text=value
|
| 113 |
+
p.font.name='Aptos';p.font.size=Pt(size);p.font.bold=bold;p.font.color.rgb=RGBColor(*color)
|
| 114 |
+
return box
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def add_picture(slide,image: Path, crop: tuple[float,float] | None = None):
|
| 118 |
+
from PIL import Image
|
| 119 |
+
with Image.open(image) as im: ratio=im.width/im.height
|
| 120 |
+
if crop:
|
| 121 |
+
top,bottom=crop
|
| 122 |
+
if not 0<=top<bottom<=1:raise ValueError('invalid figure crop')
|
| 123 |
+
ratio/=bottom-top
|
| 124 |
+
maxw,maxh=11.9,5.7
|
| 125 |
+
w=min(maxw,maxh*ratio);h=w/ratio
|
| 126 |
+
picture=slide.shapes.add_picture(str(image),Inches((13.333-w)/2),
|
| 127 |
+
Inches(.95+(maxh-h)/2),width=Inches(w),height=Inches(h))
|
| 128 |
+
if crop:
|
| 129 |
+
picture.crop_left=0;picture.crop_right=0
|
| 130 |
+
picture.crop_top=top;picture.crop_bottom=1-bottom
|
| 131 |
+
return picture
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def white_band(slide,y: float,h: float):
|
| 135 |
+
band=slide.shapes.add_shape(MSO_SHAPE.RECTANGLE,Inches(0),Inches(y),Inches(13.333),Inches(h))
|
| 136 |
+
band.fill.solid();band.fill.fore_color.rgb=RGBColor(255,255,255)
|
| 137 |
+
band.line.fill.background()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def export_figure1_panels(root: Path) -> dict[str,Path]:
|
| 141 |
+
"""Crop the source SVG viewBox; retain editable vector panel exports."""
|
| 142 |
+
import cairosvg
|
| 143 |
+
source=root/'figures/fig1_overview.svg'
|
| 144 |
+
raw=source.read_text()
|
| 145 |
+
match=re.search(r'<svg\s[^>]*>',raw)
|
| 146 |
+
if not match:raise ValueError('Figure 1 SVG root missing')
|
| 147 |
+
tag=match.group(0)
|
| 148 |
+
view=re.search(r'viewBox="([^"]+)"',tag)
|
| 149 |
+
if not view:raise ValueError('Figure 1 SVG viewBox missing')
|
| 150 |
+
x,y,width,height=map(float,view.group(1).split())
|
| 151 |
+
result={}
|
| 152 |
+
for slug,(start,end) in {'ab':(0,.395),'cd':(.395,.65),'e':(.65,1)}.items():
|
| 153 |
+
top=y+height*start;crop_h=height*(end-start)
|
| 154 |
+
new=tag
|
| 155 |
+
new=re.sub(r'width="[^"]+"',f'width="{width:g}pt"',new,count=1)
|
| 156 |
+
new=re.sub(r'height="[^"]+"',f'height="{crop_h:g}pt"',new,count=1)
|
| 157 |
+
new=re.sub(r'viewBox="[^"]+"',f'viewBox="{x:g} {top:g} {width:g} {crop_h:g}"',new,count=1)
|
| 158 |
+
svg=root/'deck'/f'fig1_panel_{slug}.svg'
|
| 159 |
+
png=root/'deck'/f'fig1_panel_{slug}.png'
|
| 160 |
+
svg.parent.mkdir(exist_ok=True)
|
| 161 |
+
svg.write_text(raw[:match.start()]+new+raw[match.end():])
|
| 162 |
+
cairosvg.svg2png(url=str(svg),write_to=str(png),output_width=2126,
|
| 163 |
+
output_height=round(2126*crop_h/width))
|
| 164 |
+
result[slug]=png
|
| 165 |
+
return result
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def self_test_gate():
|
| 169 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 170 |
+
root=Path(tmp)
|
| 171 |
+
(root/'reports').mkdir()
|
| 172 |
+
(root/'reports/figures234_readiness.json').write_text(json.dumps({'status':'complete'}))
|
| 173 |
+
(root/'reports/rare_provenance.json').write_text(json.dumps({
|
| 174 |
+
'schema':'pbisc.figure5.analysis.v1','units':[{'cohort':'ye2026_sepsis',
|
| 175 |
+
'unit':'draw0','design':'legacy_5donor','evidence_tier':'diagnostic'}],
|
| 176 |
+
'visuals':{'status':'diagnostic_only'}}))
|
| 177 |
+
(root/'reports/rare_visual_provenance.json').write_text(json.dumps({'status':'complete'}))
|
| 178 |
+
try:final_gate(root)
|
| 179 |
+
except ValueError as e:assert 'diagnostic or incomplete' in str(e)
|
| 180 |
+
else:raise AssertionError('final deck accepted legacy rare-state evidence')
|
| 181 |
+
print('final-deck gate self-test passed: complete Figures 2–4 cannot admit diagnostic Figure 5')
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def main():
|
| 185 |
+
ap=argparse.ArgumentParser();ap.add_argument('--require-complete',action='store_true')
|
| 186 |
+
ap.add_argument('--self-test',action='store_true')
|
| 187 |
+
a=ap.parse_args()
|
| 188 |
+
if a.self_test:self_test_gate();return
|
| 189 |
+
ready=json.loads((ROOT/'reports/figures234_readiness.json').read_text())
|
| 190 |
+
gate=None
|
| 191 |
+
if a.require_complete:
|
| 192 |
+
try:gate=final_gate(ROOT)
|
| 193 |
+
except (ValueError,FileNotFoundError) as e:raise SystemExit(f'Final deck blocked: {e}')
|
| 194 |
+
export_figure1_panels(ROOT)
|
| 195 |
+
prs=Presentation();prs.slide_width=Inches(13.333);prs.slide_height=Inches(7.5)
|
| 196 |
+
sections=[('Figure 1 · complete overview','fig1_overview.png','Index view; following slides enlarge each section.',None),
|
| 197 |
+
('Figure 1 · pretraining and adaptation','deck/fig1_panel_ab.png','Sections a–b: five independent paired donors and measured-gene diffusion.',None),
|
| 198 |
+
('Figure 1 · condition and sampling','deck/fig1_panel_cd.png','Sections c–d: K_cond, per-cell depth and N_gen are distinct quantities.',None),
|
| 199 |
+
('Figure 1 · pretraining corpus','deck/fig1_panel_e.png','Section e: assay, condition and cell-type coverage.',None),
|
| 200 |
+
('Figure 2 · Ablations and support size','fig2_ablation_and_support.png','Measured pretraining P/C; historical pooled-107 scores separate from strict foldwise curve.',None),
|
| 201 |
+
('Figure 2 · Native pseudobulk ablations','fig2_ablation_and_support.png','Same held-out cells/readout; architecture and gene-panel floors are separate sweeps.',(0,.35)),
|
| 202 |
+
('Figure 2 · Real-bulk rank selection','fig2_ablation_and_support.png','Matched five-fold full FT versus LoRA r=4, 16, 64; quality and trainable parameters.',(.35,.69)),
|
| 203 |
+
('Figure 2 · Strict paired-data budget','fig2_ablation_and_support.png','All five comparators; raw and external ref-cal use zero target paired sc. Pending units remain unfilled.',(.69,1)),
|
| 204 |
+
('Figure 3 · Healthy out-of-fold','fig3_healthy_strict_oof.png','Strict n=5 results and fixed real-R1 projection are pending where indicated.'),
|
| 205 |
+
('Figure 4 · Disease cohorts','fig4_disease_strict_draws.png','Four exact-five-pair cohorts; pending panels do not claim performance.'),
|
| 206 |
+
]
|
| 207 |
+
sections=[x if len(x)==4 else (*x,None) for x in sections]
|
| 208 |
+
if (ROOT/'figures/fig3_canonical_marker_dotplot.png').is_file():
|
| 209 |
+
sections.append(('Figure 3 · canonical marker dot plot','fig3_canonical_marker_dotplot.png',
|
| 210 |
+
'Strict scored cells; dot size is marker detection fraction.',None))
|
| 211 |
+
for detail in ('umap_by_celltype','composition_fractions','runtime_components'):
|
| 212 |
+
if (ROOT/f'figures/fig3_{detail}.png').is_file():
|
| 213 |
+
sections.append((f'Figure 3 · {detail.replace("_"," ")}',f'fig3_{detail}.png',
|
| 214 |
+
'Common real-only reference, observed/generated cell fractions and split operating time.',None))
|
| 215 |
+
if (ROOT/'figures/fig4_disease_signal_strict.png').is_file():
|
| 216 |
+
sections.append(('Figure 4 · disease signal','fig4_disease_signal_strict.png',
|
| 217 |
+
'Exact five-pair draws; source-bound partial logFC, CAT and donor DEG.',None))
|
| 218 |
+
for detail in ('scatter','heatmap','cat'):
|
| 219 |
+
if (ROOT/f'figures/fig4_disease_signal_{detail}.png').is_file():
|
| 220 |
+
sections.append((f'Figure 4 · disease {detail}',f'fig4_disease_signal_{detail}.png',
|
| 221 |
+
'Donor-aware effects; shared patient resampling across all draws.',None))
|
| 222 |
+
if (ROOT/'figures/fig4_deconvolution_strict.png').is_file():
|
| 223 |
+
sections.append(('Figure 4 · deconvolution composition','fig4_deconvolution_strict.png',
|
| 224 |
+
'BayesPrism and CIBERSORTx on identical five-pair support.',None))
|
| 225 |
+
if (ROOT/'figures/fig4_deconvolution_expression_strict.png').is_file():
|
| 226 |
+
sections.append(('Figure 4 · deconvolution expression','fig4_deconvolution_expression_strict.png',
|
| 227 |
+
'Donor-aware continuous-expression signal where estimable.',None))
|
| 228 |
+
if (ROOT/'figures/fig4_deconvolution_historical_signal.png').is_file():
|
| 229 |
+
sections.append(('Figure 4 · exploratory expression comparison','fig4_deconvolution_historical_signal.png',
|
| 230 |
+
'Historical Welch comparison; separate from donor-aware sensitivity.',None))
|
| 231 |
+
sections.append(('Figure 4 · historical comparison','fig4_historical_5fold_separate.png',
|
| 232 |
+
'Historical five-fold design shown separately from exact five-pair draws.',None))
|
| 233 |
+
if a.require_complete:
|
| 234 |
+
sections.extend([('Figure 5 · strict rare states','fig5_rare_states_strict.png',
|
| 235 |
+
'Twenty exact five-pair draws; all zero-state draws retained.',None),
|
| 236 |
+
('Figure 5 · strict marker visuals','fig5_rare_visuals_strict.png',
|
| 237 |
+
'Fixed real-only marker projection; illustrations separate from numeric scores.',None),
|
| 238 |
+
('Figure 5 · all predefined states','fig5_all_states_strict.png',
|
| 239 |
+
'Every state and draw; observed-zero refers to the declared sampled cell budget.',None),
|
| 240 |
+
('Figure 5 · Behcet rule comparison','fig5_behcet_rules_strict.png',
|
| 241 |
+
'Single-gene versus multi-gene C1Q; descriptive unmatched reference includes training donors.',None)])
|
| 242 |
+
else:
|
| 243 |
+
sections.append(('Figure 5 · diagnostic only','fig5_rare_states_diagnostic.png',
|
| 244 |
+
'Legacy five-donor caches; not an exact five-pair result.',None))
|
| 245 |
+
for detail in ('all_states','behcet_rules'):
|
| 246 |
+
path=ROOT/f'figures/fig5_{detail}_diagnostic.png'
|
| 247 |
+
if path.is_file():
|
| 248 |
+
sections.append((f'Figure 5 · {detail.replace("_"," ")} · diagnostic',path.name,
|
| 249 |
+
'Descriptive preview; Behcet calibration uses the same three candidate pairs.',None))
|
| 250 |
+
for title,basename,note,crop in sections:
|
| 251 |
+
image=ROOT/basename if basename.startswith('deck/') else ROOT/'figures'/basename
|
| 252 |
+
if not image.is_file(): raise FileNotFoundError(image)
|
| 253 |
+
slide=prs.slides.add_slide(prs.slide_layouts[6])
|
| 254 |
+
add_picture(slide,image,crop)
|
| 255 |
+
white_band(slide,0,.88)
|
| 256 |
+
white_band(slide,6.72,.78)
|
| 257 |
+
text(slide,.55,.32,12.2,.55,title,24,True)
|
| 258 |
+
text(slide,.55,6.85,12.2,.38,note,11,color=(90,97,104))
|
| 259 |
+
if not a.require_complete and ready['status']!='complete' and title.startswith(('Figure 2','Figure 3','Figure 4')):
|
| 260 |
+
text(slide,11.1,.3,1.65,.45,'REVIEW · PENDING',10,True,(154,103,0))
|
| 261 |
+
if not a.require_complete and title.startswith('Figure 5'):
|
| 262 |
+
text(slide,10.8,.3,2.0,.45,'DIAGNOSTIC ONLY',10,True,(154,103,0))
|
| 263 |
+
slide=prs.slides.add_slide(prs.slide_layouts[6])
|
| 264 |
+
text(slide,.6,.45,12,.55,'Evidence and readiness',25,True)
|
| 265 |
+
f2,f3,f4=ready['figure2'],ready['figure3'],ready['figure4']
|
| 266 |
+
lines=[f"Figure 2 strict healthy support scores: {f2['strict_complete_units']}/20 units",
|
| 267 |
+
f"Figure 3 strict n=5 folds: {f3['strict_complete_folds']}/5; visual export: {f3['visual_export_ready']}",
|
| 268 |
+
'Figure 4 exact-five-pair draws: '+', '.join(f'{k} {v}/5' for k,v in f4['strict_complete_draws'].items()),
|
| 269 |
+
'Figure 5: 20 strict units and three visual examples verified.' if gate else
|
| 270 |
+
'Figure 5: diagnostic legacy caches; strict data and visuals pending.',
|
| 271 |
+
'Historical five-fold results use separate source tables and are not strict support.',
|
| 272 |
+
'Figure 6 awaits user-provided bulk-only reproduction data.']
|
| 273 |
+
for i,line in enumerate(lines):text(slide,.8,1.35+i*.82,11.8,.66,line,17)
|
| 274 |
+
out=ROOT/'deck'/('paper_figures_final.pptx' if a.require_complete else 'paper_figures_review.pptx')
|
| 275 |
+
out.parent.mkdir(exist_ok=True)
|
| 276 |
+
prs.save(out)
|
| 277 |
+
if gate:(ROOT/'deck'/'final_gate_sources.json').write_text(json.dumps(gate,indent=2)+'\n')
|
| 278 |
+
(ROOT/'deck'/'README.md').write_text('# Paper figure decks\n\nReview PPTX/PDF includes a clearly labeled diagnostic Figure 5 and visible pending panels. `--require-complete` checks Figures 2–5 source evidence and writes a separate final PPTX only when all strict inputs are complete. Figure 1 has vector panel exports and readable method/corpus slides. The PDF is exported from the PPTX using bounded headless LibreOffice.\n')
|
| 279 |
+
print(out)
|
| 280 |
+
if __name__=='__main__':main()
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/campaign.py
ADDED
|
@@ -0,0 +1,292 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Run authorized Figure 1–5 exact-pair experiments sequentially with immutable receipts."""
|
| 2 |
+
from __future__ import annotations
|
| 3 |
+
import argparse
|
| 4 |
+
import fcntl
|
| 5 |
+
import json
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import sys
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
+
|
| 10 |
+
from runtime import Runtime, ReceiptError, atomic_json, sha256, stamp
|
| 11 |
+
|
| 12 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 13 |
+
M8 = ROOT.parents[1]
|
| 14 |
+
OLD = M8 / "plans/paired_finetune_intradataset_20260927"
|
| 15 |
+
COHORTS = ("immicro", "ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili")
|
| 16 |
+
PY = "/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python"
|
| 17 |
+
CPU_PY = "/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python"
|
| 18 |
+
SC_PY = str(M8 / "plans/immicro_scsemi_comparison_20260927/runtime_env/bin/python")
|
| 19 |
+
BASE = M8 / "runs/f01_6k_1x_seed20260627/checkpoint_epoch_016.pt"
|
| 20 |
+
BASE_SHA = "8c7cd0e83e2bc19fe03dfcbc084919a1e2f61be8cc8bc12f4caf543dfda91633"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def read_support(path: Path) -> dict:
|
| 24 |
+
m = json.loads(path.read_text())
|
| 25 |
+
if m["cohort"] not in COHORTS:
|
| 26 |
+
raise ValueError("cohort outside authorized Figure 1–5 scope")
|
| 27 |
+
return m
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def relative(path: Path) -> Path:
|
| 31 |
+
return path.relative_to(ROOT / "protocol/splits").parent
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def name(path: Path) -> str:
|
| 35 |
+
return "-".join(relative(path).parts)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def discover_units() -> list[Path]:
|
| 39 |
+
paths = list((ROOT / "protocol/splits").glob("**/support.json"))
|
| 40 |
+
return sorted(paths, key=lambda p: (read_support(p)["n_pairs"] != 5,
|
| 41 |
+
COHORTS.index(read_support(p)["cohort"]), str(p)))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_full_campaign(stage: str, units: list[Path]) -> bool:
|
| 45 |
+
"""Partial/pilot invocations must never render a final paper."""
|
| 46 |
+
return stage == "all" and set(units) == set(discover_units()) and len(units) == 40
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def archive_completed_campaign(runtime: Runtime) -> None:
|
| 50 |
+
"""One task-end versioned delta under the paper's standing archive authorization."""
|
| 51 |
+
final = json.loads((ROOT / "FINALIZATION_STATUS.json").read_text())
|
| 52 |
+
if final.get("state") != "complete" or final.get("stage") != "all":
|
| 53 |
+
raise ReceiptError("cannot publish completed assets before all-stage finalization")
|
| 54 |
+
pointer = ROOT / "FINAL_ARCHIVE_REQUEST.json"
|
| 55 |
+
if pointer.exists():
|
| 56 |
+
identifier = json.loads(pointer.read_text())["id"]
|
| 57 |
+
else:
|
| 58 |
+
identifier = datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ") + "-strictpairs-results"
|
| 59 |
+
atomic_json(pointer, {"id": identifier, "state": "prepared_for_task_end", "at": stamp()})
|
| 60 |
+
release = Path("/home/sj_server_1/PBISC/paper-release-20260928")
|
| 61 |
+
helper = ROOT / "tools/archive_completed.py"
|
| 62 |
+
request = ROOT / "archive" / identifier / "request.json"
|
| 63 |
+
runtime.execute("archive-final-snapshot", [CPU_PY, str(helper), "--state", "complete", "--id", identifier],
|
| 64 |
+
memory_gib=4, threads=2, inputs=[helper, ROOT / "FINALIZATION_STATUS.json"], outputs=[request])
|
| 65 |
+
cli = release / "maintenance/update.py"
|
| 66 |
+
python = "/home/sj_server_1/miniforge3/bin/python"
|
| 67 |
+
runtime.execute("archive-final-prepare", [python, str(cli), "prepare", "--request", str(request), "--id", identifier],
|
| 68 |
+
memory_gib=4, threads=2, inputs=[request, cli], outputs=[release / "updates" / identifier / "manifest.json"])
|
| 69 |
+
verified = release / "updates" / identifier / "UPDATE_VERIFIED.json"
|
| 70 |
+
runtime.execute("archive-final-publish", [python, str(cli), "publish", identifier, "--execute"],
|
| 71 |
+
memory_gib=4, threads=2, inputs=[request, cli], outputs=[verified])
|
| 72 |
+
latest = json.loads((release / "LATEST.json").read_text())
|
| 73 |
+
if latest.get("id") != identifier or latest.get("verified_receipt_sha256") != sha256(verified):
|
| 74 |
+
raise ReceiptError("published archive verification/latest pointer mismatch")
|
| 75 |
+
atomic_json(ROOT / "FINAL_ARCHIVE_VERIFIED.json", {"id": identifier, "receipt": str(verified),
|
| 76 |
+
"sha256": sha256(verified), "at": stamp()})
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def data_dir(path: Path) -> Path:
|
| 80 |
+
return ROOT / "data" / relative(path)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def run_dir(path: Path) -> Path:
|
| 84 |
+
return ROOT / "runs" / relative(path) / "lora"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def gen_dir(path: Path) -> Path:
|
| 88 |
+
return ROOT / "generated" / relative(path)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def check_support(path: Path) -> dict:
|
| 92 |
+
import pandas as pd
|
| 93 |
+
from support_manifest import load_manifest
|
| 94 |
+
m = read_support(path)
|
| 95 |
+
m = load_manifest(path, pd.read_csv(OLD / "data" / m["cohort"] / "folds.csv"))
|
| 96 |
+
rec = json.loads((data_dir(path) / "CONDITIONS.json").read_text())
|
| 97 |
+
if rec["support_sha256"] != m["sha256"] or rec["fit_sample_ids"] != m["train_sample_ids"]:
|
| 98 |
+
raise ReceiptError("condition calibration support mismatch")
|
| 99 |
+
for f, expected in rec["files_sha256"].items():
|
| 100 |
+
if sha256(data_dir(path) / f) != expected:
|
| 101 |
+
raise ReceiptError(f"condition hash mismatch: {f}")
|
| 102 |
+
return m
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def train_command(path: Path) -> list[str]:
|
| 106 |
+
m = read_support(path)
|
| 107 |
+
return [PY, "-u", str(OLD / "tools/ft_sdd.py"), "--checkpoint", str(BASE), "--checkpoint-sha", BASE_SHA,
|
| 108 |
+
"--dataset-dir", str(OLD / "data" / m["cohort"]), "--condition-npz",
|
| 109 |
+
str(OLD / "data" / m["cohort"] / "conditions_raw_fixed.npz"), "--fold", "0", "--mode", "lora",
|
| 110 |
+
"--lora-rank", "16", "--lora-alpha", "16", "--lr", "0.0005", "--fixed-steps", "3000",
|
| 111 |
+
"--seed", "20260927", "--support-manifest", str(path), "--out-dir", str(run_dir(path))]
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def train_inputs(path: Path) -> list[Path]:
|
| 115 |
+
cohort = read_support(path)["cohort"]
|
| 116 |
+
data = OLD / "data" / cohort
|
| 117 |
+
return [path, data / "conditions_raw_fixed.npz", OLD / "tools/ft_sdd.py",
|
| 118 |
+
ROOT / "tools/support_manifest.py", data / "cells_panel6k.npz", data / "folds.csv"]
|
| 119 |
+
|
| 120 |
+
|
| 121 |
+
def sample(runtime: Runtime, tag: str, checkpoint: Path, ck_sha: str, condition: Path, output: Path,
|
| 122 |
+
support: Path | None = None, seed: int = 20260928) -> None:
|
| 123 |
+
wrapper = ROOT / "tools/sample_one.py"
|
| 124 |
+
argv = [PY, "-u", str(wrapper), "--checkpoint", str(checkpoint), "--checkpoint-sha", ck_sha,
|
| 125 |
+
"--condition", str(condition), "--output", str(output), "--seed", str(seed)]
|
| 126 |
+
runtime.execute(tag, argv, resource="gpu", memory_gib=16,
|
| 127 |
+
inputs=[wrapper, M8 / "scripts/sample_sdd_standalone.py", condition,
|
| 128 |
+
*([support] if support else [])], outputs=[output, output.with_suffix(".log")])
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def run_diffusion(runtime: Runtime, path: Path) -> None:
|
| 132 |
+
m = check_support(path)
|
| 133 |
+
tag, out = name(path), gen_dir(path)
|
| 134 |
+
runtime.execute(f"{tag}-train", train_command(path), resource="gpu", memory_gib=16,
|
| 135 |
+
inputs=train_inputs(path),
|
| 136 |
+
outputs=[run_dir(path) / "checkpoint_ft.pt", run_dir(path) / "RUN.json"])
|
| 137 |
+
record = json.loads((run_dir(path) / "RUN.json").read_text())
|
| 138 |
+
if set(record["train_rows"]) != set(m["train_sample_ids"]) or record["inner_val_rows"]:
|
| 139 |
+
raise ReceiptError("trained support differs from strict manifest")
|
| 140 |
+
if record["fixed_steps"] != 3000 or record["selected_step"] != 3000:
|
| 141 |
+
raise ReceiptError("strict training did not finish its fixed schedule")
|
| 142 |
+
sample(runtime, f"{tag}-lora", run_dir(path) / "checkpoint_ft.pt", record["checkpoint_sha256"],
|
| 143 |
+
data_dir(path) / "test_raw.npz", out / "lora.npz", path)
|
| 144 |
+
sample(runtime, f"{tag}-pairedcal", BASE, BASE_SHA, data_dir(path) / "test_cal.npz",
|
| 145 |
+
out / "pairedcal.npz", path)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def scsemi_command(path: Path, phase: str) -> list[str]:
|
| 149 |
+
return [SC_PY, "-u", str(ROOT / "tools/run_scsemi_strict.py"), "--support-manifest", str(path),
|
| 150 |
+
"--work", str(ROOT / "scsemi" / relative(path)), "--phase", phase,
|
| 151 |
+
"--device", "cpu" if phase == "prepare" else "cuda:0", "--threads", "4", "--lean-hvset"]
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def run_scsemi(runtime: Runtime, path: Path) -> None:
|
| 155 |
+
m = check_support(path)
|
| 156 |
+
tag, work, output = name(path), ROOT / "scsemi" / relative(path), gen_dir(path) / "scsemi.npz"
|
| 157 |
+
adoption = work / "adopted_legacy/ADOPTION.json"
|
| 158 |
+
if adoption.is_file():
|
| 159 |
+
verifier = ROOT / "tools/verify_scsemi_adoption.py"
|
| 160 |
+
runtime.execute(f"{tag}-scadopt", [SC_PY, str(verifier), "--support-manifest", str(path),
|
| 161 |
+
"--npz", str(output), "--out", str(work / "ADOPTED_OUTPUT_VALIDATION.json")],
|
| 162 |
+
memory_gib=8, threads=2,
|
| 163 |
+
inputs=[path, verifier, ROOT / "tools/import_scsemi_legacy.py", adoption, output.with_suffix(".log")],
|
| 164 |
+
outputs=[work / "ADOPTED_OUTPUT_VALIDATION.json"])
|
| 165 |
+
return
|
| 166 |
+
prepare = OLD / "scsemi/tools/prepare_draw_inputs.py"
|
| 167 |
+
runtime.execute(f"{tag}-scinputs", [SC_PY, "-u", str(prepare), "--dataset", m["cohort"],
|
| 168 |
+
"--support-manifest", str(path), "--work", str(work)], memory_gib=16,
|
| 169 |
+
inputs=[path, prepare], outputs=[work / "inputs/inputs_manifest.json"])
|
| 170 |
+
wrapper = ROOT / "tools/run_scsemi_strict.py"
|
| 171 |
+
runtime.execute(f"{tag}-scprepare", scsemi_command(path, "prepare"), memory_gib=16,
|
| 172 |
+
inputs=[path, wrapper, work / "inputs/inputs_manifest.json"], outputs=[work / "prepared.json"])
|
| 173 |
+
for phase, completed, counter, bound in (("pretrain", "pretrain_complete", "reps_pretrained", "--max-reps"),
|
| 174 |
+
("infer", "infer_complete", "targets_done", "--max-targets")):
|
| 175 |
+
while True:
|
| 176 |
+
status = json.loads((work / "status.json").read_text())
|
| 177 |
+
if status[completed]:
|
| 178 |
+
break
|
| 179 |
+
before = status[counter]
|
| 180 |
+
argv = scsemi_command(path, phase) + [bound, "2" if phase == "pretrain" else "8"]
|
| 181 |
+
runtime.execute(f"{tag}-sc{phase}-{before}", argv, resource="gpu", memory_gib=48,
|
| 182 |
+
inputs=[path, wrapper, work / "prepared.json"])
|
| 183 |
+
after = json.loads((work / "status.json").read_text())
|
| 184 |
+
if after[counter] <= before:
|
| 185 |
+
raise ReceiptError("scSemi phase returned without progress")
|
| 186 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 187 |
+
exporter = ROOT / "tools/export_scsemi_strict.py"
|
| 188 |
+
runtime.execute(f"{tag}-scexport", [SC_PY, str(exporter), "--support-manifest", str(path),
|
| 189 |
+
"--work", str(work), "--out", str(output)], memory_gib=16,
|
| 190 |
+
inputs=[path, exporter, work / "prepared.json"], outputs=[output, output.with_suffix(".log")])
|
| 191 |
+
validation = output.with_suffix(".validation.json")
|
| 192 |
+
runtime.execute(f"{tag}-scvalidate", [SC_PY, str(OLD / "scsemi/tools/validate_export.py"),
|
| 193 |
+
"--work", str(work), "--npz", str(output)], memory_gib=16,
|
| 194 |
+
inputs=[path, output.with_suffix(".log")], outputs=[validation])
|
| 195 |
+
if not json.loads(validation.read_text())["passed"]:
|
| 196 |
+
raise ReceiptError("scSemi export validation failed")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def run_global(runtime: Runtime, cohort: str) -> None:
|
| 200 |
+
source = ROOT / "data/external_refcal" / cohort
|
| 201 |
+
for arm in ("raw", "refcal"):
|
| 202 |
+
sample(runtime, f"global-{cohort}-{arm}", BASE, BASE_SHA, source / f"conditions_{arm}.npz",
|
| 203 |
+
ROOT / "generated/global" / cohort / f"{arm}.npz")
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def run_score(runtime: Runtime, path: Path) -> None:
|
| 207 |
+
m = check_support(path)
|
| 208 |
+
output = ROOT / "scores" / relative(path)
|
| 209 |
+
argv = [CPU_PY, "-u", str(ROOT / "tools/score_strict.py"), "--support-manifest", str(path),
|
| 210 |
+
"--out", str(output), "--action", "all", "--threads", "4"]
|
| 211 |
+
arms = {arm: gen_dir(path) / f"{arm}.npz" for arm in ("lora", "pairedcal", "scsemi")}
|
| 212 |
+
arms.update({arm: ROOT / "generated/global" / m["cohort"] / f"{arm}.npz" for arm in ("raw", "refcal")})
|
| 213 |
+
for arm, artifact in arms.items():
|
| 214 |
+
if not artifact.is_file():
|
| 215 |
+
raise ReceiptError(f"required output not yet ready: {artifact}")
|
| 216 |
+
argv.extend(["--arm", f"{arm}={artifact}"])
|
| 217 |
+
runtime.execute(f"{name(path)}-score", argv, memory_gib=32,
|
| 218 |
+
inputs=[path, *[ROOT / "tools" / f for f in
|
| 219 |
+
("score_strict.py", "donor_statistics.py", "donor_limma.R")],
|
| 220 |
+
*[OLD / "tools" / f for f in
|
| 221 |
+
("score_ft.py", "extra_metrics.py", "contrast_extra.py")],
|
| 222 |
+
*[p.with_suffix(".log") for p in arms.values()]],
|
| 223 |
+
outputs=[output / "score/summary.json", output / "statistics/status.json",
|
| 224 |
+
output / "statistics/donor_bootstrap_2000.csv",
|
| 225 |
+
output / "extras" / m["cohort"] / "strict/manifest.json",
|
| 226 |
+
output / "contrast" / m["cohort"] / "strict/manifest.json"])
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
def main() -> None:
|
| 230 |
+
p = argparse.ArgumentParser(description=__doc__)
|
| 231 |
+
p.add_argument("action", choices=("status", "run"))
|
| 232 |
+
p.add_argument("--stage", choices=("diffusion", "scsemi", "global", "score", "all"), default="all")
|
| 233 |
+
p.add_argument("--only", help="unit name, e.g. immicro-healthy-fold0-n5")
|
| 234 |
+
p.add_argument("--max-units", type=int)
|
| 235 |
+
p.add_argument("--wait-lock", action="store_true", help="queue behind an already authorized controller")
|
| 236 |
+
a = p.parse_args()
|
| 237 |
+
units = discover_units()
|
| 238 |
+
if a.only:
|
| 239 |
+
units = [path for path in units if name(path) == a.only]
|
| 240 |
+
if not units:
|
| 241 |
+
p.error("no such unit")
|
| 242 |
+
if a.max_units is not None:
|
| 243 |
+
units = units[:a.max_units]
|
| 244 |
+
status_path = ROOT / "CAMPAIGN_STATUS.json"
|
| 245 |
+
if a.action == "status":
|
| 246 |
+
print(status_path.read_text() if status_path.exists() else json.dumps({"state": "prepared", "units": len(units)}))
|
| 247 |
+
return
|
| 248 |
+
lock = (ROOT / ".campaign.lock").open("a")
|
| 249 |
+
if a.wait_lock:
|
| 250 |
+
print("Waiting for the active campaign controller to release its lock.", flush=True)
|
| 251 |
+
fcntl.flock(lock, fcntl.LOCK_EX | (0 if a.wait_lock else fcntl.LOCK_NB))
|
| 252 |
+
runtime = Runtime(ROOT)
|
| 253 |
+
state = {"state": "running", "stage": a.stage, "started_at": stamp(), "units_selected": len(units),
|
| 254 |
+
"units_completed_this_invocation": 0, "figure6": "waiting_user_data_no_execution"}
|
| 255 |
+
atomic_json(status_path, state)
|
| 256 |
+
try:
|
| 257 |
+
if a.stage in ("global", "all"):
|
| 258 |
+
for cohort in COHORTS:
|
| 259 |
+
if any(read_support(x)["cohort"] == cohort for x in units):
|
| 260 |
+
state.update(active=f"global-{cohort}", updated_at=stamp())
|
| 261 |
+
atomic_json(status_path, state)
|
| 262 |
+
run_global(runtime, cohort)
|
| 263 |
+
for path in units:
|
| 264 |
+
state.update(active=name(path), updated_at=stamp())
|
| 265 |
+
atomic_json(status_path, state)
|
| 266 |
+
if a.stage in ("diffusion", "all"):
|
| 267 |
+
run_diffusion(runtime, path)
|
| 268 |
+
if a.stage in ("scsemi", "all"):
|
| 269 |
+
run_scsemi(runtime, path)
|
| 270 |
+
if a.stage in ("score", "all"):
|
| 271 |
+
run_score(runtime, path)
|
| 272 |
+
state["units_completed_this_invocation"] += 1
|
| 273 |
+
if is_full_campaign(a.stage, units):
|
| 274 |
+
state.update(active="finalize-figures-and-documents", updated_at=stamp())
|
| 275 |
+
atomic_json(status_path, state)
|
| 276 |
+
finalizer = ROOT / "tools/finalize_campaign.py"
|
| 277 |
+
runtime.execute("finalize-campaign", [CPU_PY, "-u", str(finalizer), "--stage", "all"],
|
| 278 |
+
memory_gib=2, inputs=[finalizer],
|
| 279 |
+
outputs=[ROOT / "FINALIZATION_STATUS.json"])
|
| 280 |
+
state.update(active="archive-completed-figures-and-documents", updated_at=stamp())
|
| 281 |
+
atomic_json(status_path, state)
|
| 282 |
+
archive_completed_campaign(runtime)
|
| 283 |
+
state.update(state="selected_stage_completed", active=None, updated_at=stamp())
|
| 284 |
+
except BaseException as exc:
|
| 285 |
+
state.update(state="stopped_needs_inspection", error=str(exc), updated_at=stamp())
|
| 286 |
+
raise
|
| 287 |
+
finally:
|
| 288 |
+
atomic_json(status_path, state)
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
if __name__ == "__main__":
|
| 292 |
+
main()
|