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/export_healthy_visuals.py +412 -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/export_rare_visuals.py +332 -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/export_scsemi_strict.py +198 -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/figure2_panels.py +163 -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/export_healthy_visuals.py
ADDED
|
@@ -0,0 +1,412 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CPU-only strict Figure 3 visual and operational-time exporter.
|
| 3 |
+
|
| 4 |
+
Consumes all five finished n=5 ImMicro score calls. Replays the scorer's whole-NPZ
|
| 5 |
+
Poisson readout, selecting the exact generated rows in its P/C subsample. Fits one
|
| 6 |
+
PCA50 and UMAP on pooled real R1 cells, then projects R2 and every generated arm
|
| 7 |
+
into those fixed axes. Never reads legacy native visualization outputs.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
import argparse
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import shutil
|
| 15 |
+
import sys
|
| 16 |
+
import tempfile
|
| 17 |
+
import zipfile
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
|
| 20 |
+
raise SystemExit("Set CUDA_VISIBLE_DEVICES='' for CPU visual export")
|
| 21 |
+
for k in ('OMP_NUM_THREADS','OPENBLAS_NUM_THREADS','MKL_NUM_THREADS','NUMBA_NUM_THREADS'):
|
| 22 |
+
os.environ.setdefault(k,'4')
|
| 23 |
+
import numpy as np
|
| 24 |
+
import pandas as pd
|
| 25 |
+
import scipy.sparse as sp
|
| 26 |
+
from sklearn.decomposition import PCA
|
| 27 |
+
|
| 28 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 29 |
+
M8=ROOT.parents[1]
|
| 30 |
+
OLD=M8/'plans/paired_finetune_intradataset_20260927'
|
| 31 |
+
sys.path.insert(0,str(OLD/'tools'))
|
| 32 |
+
sys.path.insert(0,str(ROOT/'tools'))
|
| 33 |
+
import ft_common as F
|
| 34 |
+
import score_ft as S
|
| 35 |
+
from rare_cache_builder import _score_rows, _stream_poisson, validate_score_arm
|
| 36 |
+
from build_results_figures import ARMS, strict_unit, sha
|
| 37 |
+
from runtime import Runtime
|
| 38 |
+
|
| 39 |
+
CANON=Path('/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/processing/strict_qc_v1_20260913/reference/canonical_genes.tsv')
|
| 40 |
+
MARKERS=('CD3D','CD3E','IL7R','CD4','CD8A','CD8B','MS4A1','CD79A','CD79B',
|
| 41 |
+
'NKG7','GNLY','KLRD1','LST1','S100A8','S100A9','FCGR3A','FCER1A',
|
| 42 |
+
'CST3','CLEC10A','PPBP')
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def marker_axis(score_ids: np.ndarray, canonical: pd.DataFrame) -> tuple[list[str],list[str],np.ndarray]:
|
| 46 |
+
if not {'gene_symbol','gene_id'} <= set(canonical):
|
| 47 |
+
raise ValueError('canonical gene table lacks gene_symbol or gene_id')
|
| 48 |
+
sym2id=dict(zip(canonical.gene_symbol.astype(str),canonical.gene_id.astype(str)))
|
| 49 |
+
pos={g:i for i,g in enumerate(score_ids.astype(str))}
|
| 50 |
+
symbols=[s for s in MARKERS if sym2id.get(s) in pos]
|
| 51 |
+
if len(symbols)<10 or len(set(symbols))!=len(symbols):
|
| 52 |
+
raise ValueError('too few measured canonical marker genes')
|
| 53 |
+
ids=[sym2id[s] for s in symbols]
|
| 54 |
+
return symbols,ids,np.asarray([pos[g] for g in ids],dtype=np.int64)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def unit_inputs() -> list[dict]:
|
| 58 |
+
units=[]
|
| 59 |
+
for i in range(5):
|
| 60 |
+
path=ROOT/'protocol/splits/immicro/healthy'/f'fold{i}'/'n5/support.json'
|
| 61 |
+
if not path.is_file(): raise FileNotFoundError(path)
|
| 62 |
+
unit,reason=strict_unit(path)
|
| 63 |
+
if unit is None: raise ValueError(f'fold{i} strict score incomplete: {reason}')
|
| 64 |
+
if unit['support']['n_pairs']!=5 or unit['support']['design']!='healthy_outerfold':
|
| 65 |
+
raise ValueError('Figure 3 requires exact five-pair healthy outer folds')
|
| 66 |
+
expected_cells=1500*len(unit['support']['test_sample_ids'])
|
| 67 |
+
for arm in ARMS:
|
| 68 |
+
if unit['summary']['per_arm'][arm].get('n_generated_cells')!=expected_cells:
|
| 69 |
+
raise ValueError(f'Figure 3 {arm} generation budget differs from 1,500 per test sample')
|
| 70 |
+
units.append(unit)
|
| 71 |
+
seen=[s for u in units for s in u['support']['test_sample_ids']]
|
| 72 |
+
if len(seen)!=107 or len(set(seen))!=107:
|
| 73 |
+
raise ValueError('healthy OOF requires exactly 107 disjoint test samples across folds')
|
| 74 |
+
return units
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def resource_preflight(units: list[dict]) -> None:
|
| 78 |
+
Runtime(ROOT).preflight('cpu',memory_gib=16)
|
| 79 |
+
largest=0
|
| 80 |
+
for source in {u['summary']['per_arm'][arm]['npz'] for u in units for arm in ARMS}:
|
| 81 |
+
with zipfile.ZipFile(source) as z:
|
| 82 |
+
largest=max(largest,z.getinfo('generated_counts.npy').file_size)
|
| 83 |
+
free=shutil.disk_usage(ROOT/'source_data').free
|
| 84 |
+
if free < largest + (2<<30):
|
| 85 |
+
raise OSError(f'Figure 3 streamed NPZ needs at least {largest+(2<<30)} free bytes; only {free} available')
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def receipt_seconds(path: Path, required_output: Path | None = None) -> tuple[float,dict]:
|
| 89 |
+
if not path.is_file(): raise FileNotFoundError(path)
|
| 90 |
+
r=json.loads(path.read_text())
|
| 91 |
+
if r.get('state')!='completed' or not np.isfinite(r.get('seconds',float('nan'))) or r['seconds']<0:
|
| 92 |
+
raise ValueError(f'incomplete runtime receipt: {path}')
|
| 93 |
+
if required_output is not None:
|
| 94 |
+
entries={Path(x['path']).resolve():x for x in r.get('outputs',[])}
|
| 95 |
+
actual=required_output.resolve()
|
| 96 |
+
if actual not in entries or entries[actual].get('sha256')!=sha(required_output):
|
| 97 |
+
raise ValueError(f'runtime receipt does not bind output: {path}')
|
| 98 |
+
return float(r['seconds']),{'path':str(path.resolve()),'sha256':sha(path),'seconds':float(r['seconds'])}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def global_allocation(units: list[dict]) -> dict[str,float]:
|
| 102 |
+
total=sum(len(u['support']['test_sample_ids']) for u in units)
|
| 103 |
+
if total<=0:raise ValueError('no strict held-out samples for global generation allocation')
|
| 104 |
+
return {u['rel']:len(u['support']['test_sample_ids'])/total for u in units}
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def operational_runtime(units: list[dict]) -> tuple[list[dict],dict]:
|
| 108 |
+
"""Split comparable GPU-job wall time into adaptation and generation."""
|
| 109 |
+
rows=[]; evidence={'schema':'pbisc.fig3.runtime-evidence.v1','pretraining_excluded':True,
|
| 110 |
+
'runtime_scope':'gpu_job_wall_seconds_only','units':{}}
|
| 111 |
+
allocation=global_allocation(units)
|
| 112 |
+
global_time={}
|
| 113 |
+
for arm in ('raw','refcal'):
|
| 114 |
+
p=ROOT/'receipts'/f'global-immicro-{arm}.json'
|
| 115 |
+
seconds,rec=receipt_seconds(p,ROOT/'generated/global/immicro'/f'{arm}.npz')
|
| 116 |
+
global_time[arm]=(seconds,rec)
|
| 117 |
+
for u in units:
|
| 118 |
+
rel=u['rel']; fold=u['support']['unit'].split('_')[0]
|
| 119 |
+
tag='immicro-healthy-'+fold+'-n5'
|
| 120 |
+
run=ROOT/'runs'/rel/'lora/RUN.json'
|
| 121 |
+
if not run.is_file(): raise FileNotFoundError(run)
|
| 122 |
+
rd=json.loads(run.read_text())
|
| 123 |
+
if (rd.get('support_sha256')!=u['support']['sha256'] or rd.get('fixed_steps')!=3000
|
| 124 |
+
or rd.get('selected_step')!=3000 or not np.isfinite(rd.get('wall_seconds',float('nan')))):
|
| 125 |
+
raise ValueError(f'LoRA runtime RUN.json does not bind strict support: {run}')
|
| 126 |
+
train_seconds,train_rec=receipt_seconds(ROOT/'receipts'/f'{tag}-train.json',run)
|
| 127 |
+
if abs(train_seconds-float(rd['wall_seconds']))>max(60.0,0.25*train_seconds):
|
| 128 |
+
raise ValueError(f'LoRA run and training receipt times differ: {run}')
|
| 129 |
+
vals={}
|
| 130 |
+
for arm in ('raw','refcal'):
|
| 131 |
+
seconds,rec=global_time[arm]
|
| 132 |
+
vals[arm]={'adaptation_seconds':0.0,'generation_seconds':seconds*allocation[rel],
|
| 133 |
+
'scope':'cohort_global_gpu_sampling_apportioned_by_held_out_sample_count',
|
| 134 |
+
'sources':[rec]}
|
| 135 |
+
lora_sample,lora_rec=receipt_seconds(ROOT/'receipts'/f'{tag}-lora.json',ROOT/'generated'/rel/'lora.npz')
|
| 136 |
+
vals['lora']={'adaptation_seconds':train_seconds,'generation_seconds':lora_sample,
|
| 137 |
+
'scope':'fold_gpu_training_plus_gpu_sampling',
|
| 138 |
+
'sources':[{'path':str(run.resolve()),'sha256':sha(run),'wall_seconds':float(rd['wall_seconds'])},train_rec,lora_rec]}
|
| 139 |
+
pc_seconds,pc_rec=receipt_seconds(ROOT/'receipts'/f'{tag}-pairedcal.json',ROOT/'generated'/rel/'pairedcal.npz')
|
| 140 |
+
vals['pairedcal']={'adaptation_seconds':0.0,'generation_seconds':pc_seconds,
|
| 141 |
+
'scope':'fold_generation_calibration_prepared_separately',
|
| 142 |
+
'sources':[pc_rec]}
|
| 143 |
+
files=[];phase_seconds={'scpretrain':0.0,'scinfer':0.0}
|
| 144 |
+
for suffix in ('scinputs','scprepare','scexport','scvalidate'):
|
| 145 |
+
p=ROOT/'receipts'/f'{tag}-{suffix}.json'
|
| 146 |
+
_,r=receipt_seconds(p, ROOT/'generated'/rel/'scsemi.npz' if suffix=='scexport' else None)
|
| 147 |
+
files.append(r)
|
| 148 |
+
for phase in ('scpretrain','scinfer'):
|
| 149 |
+
found=sorted((ROOT/'receipts').glob(f'{tag}-{phase}-*.json'))
|
| 150 |
+
if not found: raise ValueError(f'missing scSemi {phase} receipts for {tag}')
|
| 151 |
+
for p in found:
|
| 152 |
+
seconds,r=receipt_seconds(p);files.append(r);phase_seconds[phase]+=seconds
|
| 153 |
+
scstatus=ROOT/'scsemi'/rel/'status.json'
|
| 154 |
+
status=json.loads(scstatus.read_text())
|
| 155 |
+
if not status.get('pretrain_complete') or not status.get('infer_complete'):
|
| 156 |
+
raise ValueError(f'scSemi work incomplete: {scstatus}')
|
| 157 |
+
files.append({'path':str(scstatus.resolve()),'sha256':sha(scstatus),'status':'complete'})
|
| 158 |
+
vals['scsemi']={'adaptation_seconds':phase_seconds['scpretrain'],
|
| 159 |
+
'generation_seconds':phase_seconds['scinfer'],
|
| 160 |
+
'scope':'fold_scsemi_gpu_pretrain_and_infer_only',
|
| 161 |
+
'excluded_cpu_seconds':sum(x.get('seconds',0) for x in files)
|
| 162 |
+
-sum(phase_seconds.values()),
|
| 163 |
+
'sources':files}
|
| 164 |
+
evidence['units'][rel]=vals
|
| 165 |
+
for arm in ARMS:
|
| 166 |
+
component=vals[arm]
|
| 167 |
+
rows.append({'fold':u['support']['unit'],'arm':arm,
|
| 168 |
+
'adaptation_seconds':component['adaptation_seconds'],
|
| 169 |
+
'generation_seconds':component['generation_seconds'],
|
| 170 |
+
'operational_seconds':component['adaptation_seconds']+component['generation_seconds'],
|
| 171 |
+
'scope':component['scope'],
|
| 172 |
+
'support_sha256':u['support']['sha256']})
|
| 173 |
+
return rows,evidence
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def replay_scored_arm(u: dict,arm: str, score_ids: np.ndarray, score_idx: np.ndarray,
|
| 177 |
+
marker_idx: np.ndarray, temp_dir: Path) -> tuple[sp.csr_matrix,np.ndarray,np.ndarray]:
|
| 178 |
+
"""Return exact P/C subsample counts and aligned labels/sample IDs."""
|
| 179 |
+
score=Path(u['summary_path']).parent
|
| 180 |
+
source=Path(u['summary']['per_arm'][arm]['npz'])
|
| 181 |
+
checksum=sha(source)
|
| 182 |
+
validate_score_arm(score,arm,source,checksum,u['support'])
|
| 183 |
+
gc,lab=_score_rows(score,arm,u['support'])
|
| 184 |
+
sub=gc.in_pc_subsample.to_numpy(dtype=bool)
|
| 185 |
+
if not sub.any(): raise ValueError(f'{arm}: no scored P/C subsample')
|
| 186 |
+
sample=gc.loc[sub,'donor'].astype(str).to_numpy()
|
| 187 |
+
label=lab.loc[sub,'aifi_l1'].astype(str).to_numpy()
|
| 188 |
+
selected=gc.loc[sub,'npz_row'].to_numpy(dtype=np.int64)
|
| 189 |
+
with zipfile.ZipFile(source) as z:
|
| 190 |
+
with z.open('gene_ids.npy') as f: genes=np.load(f,allow_pickle=False).astype(str)
|
| 191 |
+
with z.open('sample_ids.npy') as f: sample_ids=np.load(f,allow_pickle=False).astype(str)
|
| 192 |
+
with z.open('bulk_index.npy') as f: bulk=np.load(f,allow_pickle=False).astype(int)
|
| 193 |
+
if (not np.array_equal(genes[score_idx],score_ids) or selected.max()>=len(bulk)
|
| 194 |
+
or not np.array_equal(sample_ids[bulk[selected]],sample)):
|
| 195 |
+
raise ValueError(f'{arm}: generated NPZ row/gene/sample mismatch')
|
| 196 |
+
temp=temp_dir/f'{arm}_rates.npy'
|
| 197 |
+
with z.open('generated_counts.npy') as src,temp.open('wb') as dst:
|
| 198 |
+
shutil.copyfileobj(src,dst,length=4<<20)
|
| 199 |
+
rates=np.load(temp,mmap_mode='r',allow_pickle=False)
|
| 200 |
+
measured=np.zeros(len(genes),dtype=bool);measured[score_idx]=True
|
| 201 |
+
counts,_,umi=_stream_poisson(rates,selected,measured,score_idx,score_idx,chunk_rows=512)
|
| 202 |
+
del rates
|
| 203 |
+
temp.unlink()
|
| 204 |
+
if not np.array_equal(umi,gc.loc[sub,'umi_scoring_genes'].to_numpy()):
|
| 205 |
+
raise ValueError(f'{arm}: replayed Poisson UMI differs from scored cells')
|
| 206 |
+
return sp.csr_matrix(counts),sample,label
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def embed_reference(r1: sp.csr_matrix, others: list[sp.csr_matrix]):
|
| 210 |
+
"""One fixed real-R1 fit; each candidate is projected into that fit."""
|
| 211 |
+
import umap
|
| 212 |
+
X1=F.SB.cp10k_log1p(r1)
|
| 213 |
+
ncomp=min(50,X1.shape[0]-1,X1.shape[1])
|
| 214 |
+
if ncomp<2: raise ValueError('insufficient real R1 cells or measured genes')
|
| 215 |
+
pca=PCA(n_components=ncomp,svd_solver='randomized',random_state=20261012).fit(X1)
|
| 216 |
+
z1=pca.transform(X1).astype(np.float32)
|
| 217 |
+
model=umap.UMAP(n_neighbors=15,min_dist=.3,n_components=2,random_state=20261012,
|
| 218 |
+
transform_seed=20261012).fit(z1)
|
| 219 |
+
coords=[model.embedding_.astype(np.float32)]
|
| 220 |
+
for x in others:
|
| 221 |
+
z=F.SB.project(x,pca.mean_.astype(np.float32),pca.components_.astype(np.float32))
|
| 222 |
+
coords.append(model.transform(z).astype(np.float32))
|
| 223 |
+
return coords,pca,model
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def scored_composition_rows(units: list[dict]) -> list[dict]:
|
| 227 |
+
"""Full scored 1,500-cell generation and all observed QC cells per test sample."""
|
| 228 |
+
labels=tuple(map(str,F.GATE));result=[]
|
| 229 |
+
for u in units:
|
| 230 |
+
source=Path(u['per_path'])
|
| 231 |
+
if not source.is_file():raise FileNotFoundError(source)
|
| 232 |
+
digest=sha(source)
|
| 233 |
+
for row in u['rows']:
|
| 234 |
+
n_gen=int(row['n_generated_cells']);n_obs=int(row['n_observed_cells'])
|
| 235 |
+
if n_gen!=1500 or n_obs<=0:
|
| 236 |
+
raise ValueError(f'Figure 3 composition requires 1,500 generated and positive observed cells: {row["donor"]}')
|
| 237 |
+
obs=np.asarray([float(row[f'obs_{name}']) for name in labels])
|
| 238 |
+
gen=np.asarray([float(row[f'gen_{name}']) for name in labels])
|
| 239 |
+
if (not np.isfinite(obs).all() or not np.isfinite(gen).all()
|
| 240 |
+
or np.min(obs)<0 or np.min(gen)<0 or np.max(obs)>1 or np.max(gen)>1
|
| 241 |
+
or not np.isclose(obs.sum(),1,atol=1e-5)
|
| 242 |
+
or not np.isclose(gen.sum(),1,atol=1e-5)):
|
| 243 |
+
raise ValueError(f'Figure 3 composition fractions invalid: {row["donor"]}/{row["arm"]}')
|
| 244 |
+
for j,name in enumerate(labels):
|
| 245 |
+
result.append({'fold':u['support']['unit'],'arm':row['arm'],'sample_id':row['donor'],
|
| 246 |
+
'cell_type':name,'observed_total':n_obs,'generated_total':n_gen,
|
| 247 |
+
'observed_fraction':float(obs[j]),'generated_fraction':float(gen[j]),
|
| 248 |
+
'delta_pp':100*float(gen[j]-obs[j]),
|
| 249 |
+
'score_per_donor_sha256':digest})
|
| 250 |
+
return result
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def build():
|
| 254 |
+
units=unit_inputs() # all read-only checks before substantial arrays
|
| 255 |
+
runtime_rows,evidence=operational_runtime(units)
|
| 256 |
+
resource_preflight(units)
|
| 257 |
+
ref_path=Path(units[0]['summary']['reference']['cache'])
|
| 258 |
+
if any(Path(u['summary']['reference']['cache']).resolve()!=ref_path.resolve() for u in units):
|
| 259 |
+
raise ValueError('five folds use different observed reference caches')
|
| 260 |
+
ref,manifest=F.load_reference(ref_path)
|
| 261 |
+
if any(u['summary']['reference']['reference_sha256']!=manifest['reference_sha256'] for u in units):
|
| 262 |
+
raise ValueError('scored reference hash differs from loaded real cells')
|
| 263 |
+
score_ids=ref['score_ids'].astype(str);score_idx=ref['score_idx'].astype(np.int64)
|
| 264 |
+
if not np.array_equal(ref['panel_ids'][score_idx].astype(str),score_ids):
|
| 265 |
+
raise ValueError('reference score/panel gene axis mismatch')
|
| 266 |
+
canonical=pd.read_csv(CANON,sep='\t',dtype=str)
|
| 267 |
+
symbols,ids,marker_idx=marker_axis(score_ids,canonical)
|
| 268 |
+
r1s=[];r2s=[];r1_sample=[];r2_sample=[];r1_labels=[];r2_labels=[]
|
| 269 |
+
for u in units:
|
| 270 |
+
view=S.make_view(ref,u['support']['test_sample_ids'])
|
| 271 |
+
selected=set(u['support']['test_sample_ids'])
|
| 272 |
+
for side,outm,outs,outl in (('r1',r1s,r1_sample,r1_labels),('r2',r2s,r2_sample,r2_labels)):
|
| 273 |
+
mask=np.isin(ref[f'{side}_donor'],[np.where(ref['donors'].astype(str)==s)[0][0] for s in selected])
|
| 274 |
+
matrix=view[side.upper()]
|
| 275 |
+
if mask.sum()!=matrix.shape[0]: raise ValueError('real reference/view row mismatch')
|
| 276 |
+
outm.append(matrix)
|
| 277 |
+
outs.extend(ref['donors'][ref[f'{side}_donor'][mask]].astype(str).tolist())
|
| 278 |
+
outl.extend(ref[f'{side}_label'][mask].astype(str).tolist())
|
| 279 |
+
del view
|
| 280 |
+
real1=sp.vstack(r1s,format='csr');real2=sp.vstack(r2s,format='csr')
|
| 281 |
+
del ref,r1s,r2s
|
| 282 |
+
# Fit once on all out-of-fold real R1 cells; R2 and generated use fixed axes.
|
| 283 |
+
xy, pca, model=embed_reference(real1,[real2])
|
| 284 |
+
arrays={'xy':[xy[0],xy[1]],'arm':[np.repeat('real_R1',real1.shape[0]),np.repeat('real_R2',real2.shape[0])],
|
| 285 |
+
'cell_type':[np.asarray(r1_labels),np.asarray(r2_labels)],
|
| 286 |
+
'sample_id':[np.asarray(r1_sample),np.asarray(r2_sample)],
|
| 287 |
+
'marker_values':[F.SB.cp10k_log1p(real1)[:,marker_idx],F.SB.cp10k_log1p(real2)[:,marker_idx]],
|
| 288 |
+
'marker_detected':[np.asarray(real1[:,marker_idx].toarray()>0,dtype=np.uint8),
|
| 289 |
+
np.asarray(real2[:,marker_idx].toarray()>0,dtype=np.uint8)]}
|
| 290 |
+
del real1,real2,xy
|
| 291 |
+
import umap # explicitly bind UMAP implementation in receipt
|
| 292 |
+
with tempfile.TemporaryDirectory(prefix='fig3-rates-',dir=ROOT/'source_data') as tmp:
|
| 293 |
+
for u in units:
|
| 294 |
+
with tempfile.TemporaryDirectory(prefix='unit-',dir=tmp) as unit_tmp:
|
| 295 |
+
for arm in ARMS:
|
| 296 |
+
counts,samples,labels=replay_scored_arm(u,arm,score_ids,score_idx,marker_idx,Path(unit_tmp))
|
| 297 |
+
z=F.SB.project(counts,pca.mean_.astype(np.float32),pca.components_.astype(np.float32))
|
| 298 |
+
coord=model.transform(z).astype(np.float32)
|
| 299 |
+
arrays['xy'].append(coord)
|
| 300 |
+
arrays['arm'].append(np.repeat(arm,len(samples)))
|
| 301 |
+
arrays['cell_type'].append(labels)
|
| 302 |
+
arrays['sample_id'].append(samples)
|
| 303 |
+
arrays['marker_values'].append(F.SB.cp10k_log1p(counts)[:,marker_idx])
|
| 304 |
+
arrays['marker_detected'].append(np.asarray(counts[:,marker_idx].toarray()>0,dtype=np.uint8))
|
| 305 |
+
del counts,z,coord
|
| 306 |
+
out=ROOT/'source_data';out.mkdir(exist_ok=True)
|
| 307 |
+
visual=out/'fig3_visual_data.npz';sidecar=out/'fig3_visual_data.json'
|
| 308 |
+
values={k:np.concatenate(v,axis=0) for k,v in arrays.items()}
|
| 309 |
+
values['marker_symbols']=np.asarray(symbols)
|
| 310 |
+
values['marker_gene_ids']=np.asarray(ids)
|
| 311 |
+
coordinates=out/'fig3_umap_coordinates.csv'
|
| 312 |
+
pd.DataFrame({'umap_x':values['xy'][:,0],'umap_y':values['xy'][:,1],
|
| 313 |
+
'arm':values['arm'],'cell_type':values['cell_type'],
|
| 314 |
+
'sample_id':values['sample_id']}).to_csv(coordinates,index=False)
|
| 315 |
+
composition=pd.DataFrame(scored_composition_rows(units))
|
| 316 |
+
composition.to_csv(out/'fig3_celltype_fractions.csv',index=False)
|
| 317 |
+
codetect=[]
|
| 318 |
+
for arm in ('real_R1','real_R2',*ARMS):
|
| 319 |
+
arm_mask=values['arm']==arm
|
| 320 |
+
for cell_type in sorted(set(values['cell_type'][arm_mask].astype(str))):
|
| 321 |
+
mask=arm_mask & (values['cell_type']==cell_type)
|
| 322 |
+
binary=values['marker_detected'][mask].astype(np.int64)
|
| 323 |
+
pair=binary.T @ binary
|
| 324 |
+
for i,s1 in enumerate(symbols):
|
| 325 |
+
for j in range(i,len(symbols)):
|
| 326 |
+
codetect.append({'arm':arm,'cell_type':cell_type,'marker_a':s1,
|
| 327 |
+
'marker_b':symbols[j],'n_cells':int(mask.sum()),
|
| 328 |
+
'n_codetected':int(pair[i,j])})
|
| 329 |
+
pd.DataFrame(codetect).to_csv(out/'fig3_marker_codetection.csv',index=False)
|
| 330 |
+
np.savez_compressed(visual,**values)
|
| 331 |
+
receipt={'schema':'pbisc.fig3.visual.v1','npz_sha256':sha(visual),
|
| 332 |
+
'support_sha256s':[u['support']['sha256'] for u in units],
|
| 333 |
+
'score_sha256s':[sha(Path(u['summary_path'])) for u in units],
|
| 334 |
+
'score_binding_sha256s':[u['binding_sha256'] for u in units],
|
| 335 |
+
'generated_npz_sha256s':[u['summary']['per_arm'][a]['npz_sha256'] for u in units for a in ARMS],
|
| 336 |
+
'reference_fit':'real_R1_only','projection':'fixed_real_R1_pca_umap',
|
| 337 |
+
'pca_components':int(pca.n_components_),'umap_seed':20261012,'umap_neighbors':15,'umap_min_dist':.3,
|
| 338 |
+
'umap_version':getattr(umap,'__version__','unknown'),
|
| 339 |
+
'canonical_marker_gene_ids':ids,'canonical_marker_symbols':symbols,
|
| 340 |
+
'reference_npz':str((ref_path/'reference.npz').resolve()),
|
| 341 |
+
'reference_sha256':manifest['reference_sha256'],
|
| 342 |
+
'coordinates_csv':str(coordinates.resolve()),'coordinates_sha256':sha(coordinates),
|
| 343 |
+
'composition_csv':str((out/'fig3_celltype_fractions.csv').resolve()),
|
| 344 |
+
'composition_sha256':sha(out/'fig3_celltype_fractions.csv'),
|
| 345 |
+
'cells':int(len(values['arm'])),'pretraining_excluded':True}
|
| 346 |
+
sidecar.write_text(json.dumps(receipt,indent=2)+'\n')
|
| 347 |
+
evidence_path=out/'fig3_runtime_evidence.json'
|
| 348 |
+
evidence_path.write_text(json.dumps(evidence,indent=2)+'\n')
|
| 349 |
+
for r in runtime_rows:
|
| 350 |
+
r['receipt_path']=str(evidence_path.resolve())
|
| 351 |
+
r['receipt_sha256']=sha(evidence_path)
|
| 352 |
+
runtime=out/'fig3_runtime.csv'
|
| 353 |
+
pd.DataFrame(runtime_rows).to_csv(runtime,index=False)
|
| 354 |
+
(out/'fig3_runtime.json').write_text(json.dumps({'schema':'pbisc.fig3.runtime.v2',
|
| 355 |
+
'csv_sha256':sha(runtime),'support_sha256s':[u['support']['sha256'] for u in units],
|
| 356 |
+
'pretraining_excluded':True,'runtime_scope':'gpu_job_wall_seconds_only',
|
| 357 |
+
'components':['adaptation_seconds','generation_seconds'],
|
| 358 |
+
'global_generation_allocation':'held_out_test_samples_per_fold_over_total_107'},indent=2)+'\n')
|
| 359 |
+
print(json.dumps({'visual':str(visual),'runtime':str(runtime),'cells':len(values['arm'])}))
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def self_test():
|
| 363 |
+
from rare_cache_builder import _stream_poisson
|
| 364 |
+
rates=np.array([[1.2,.5,0.0],[0.2,2.1,1.0],[3.0,0.0,.1]],dtype=float)
|
| 365 |
+
selected=np.array([2,0],dtype=np.int64)
|
| 366 |
+
whole=np.random.default_rng(20260916).poisson(rates)
|
| 367 |
+
got,_,umi=_stream_poisson(rates,selected,np.ones(3,bool),np.arange(3),np.arange(3),chunk_rows=2)
|
| 368 |
+
assert np.array_equal(got,whole[selected]) and np.array_equal(umi,whole[selected].sum(1))
|
| 369 |
+
canonical=pd.DataFrame({'gene_symbol':list(MARKERS),'gene_id':[f'g{i}' for i in range(len(MARKERS))]})
|
| 370 |
+
sym,ids,ix=marker_axis(np.asarray([f'g{i}' for i in range(len(MARKERS))]),canonical)
|
| 371 |
+
assert len(sym)==len(MARKERS) and np.array_equal(ix,np.arange(len(MARKERS)))
|
| 372 |
+
weights=global_allocation([{'rel':'a','support':{'test_sample_ids':['1','2']}},
|
| 373 |
+
{'rel':'b','support':{'test_sample_ids':['3','4','5']}}])
|
| 374 |
+
assert abs(weights['a']-.4)<1e-12 and abs(weights['b']-.6)<1e-12
|
| 375 |
+
gate=tuple(F.GATE)
|
| 376 |
+
with tempfile.TemporaryDirectory() as tmp:
|
| 377 |
+
score=Path(tmp)/'per_donor.csv';score.write_text('fixture\n')
|
| 378 |
+
per=[]
|
| 379 |
+
for arm in ARMS:
|
| 380 |
+
row={'arm':arm,'donor':'S','n_generated_cells':1500,'n_observed_cells':2000}
|
| 381 |
+
row.update({f'obs_{name}':1.0 if j==0 else 0.0 for j,name in enumerate(gate)})
|
| 382 |
+
row.update({f'gen_{name}':.5 if j<2 else 0.0 for j,name in enumerate(gate)})
|
| 383 |
+
per.append(row)
|
| 384 |
+
u={'support':{'unit':'fold0_n5'},'rows':per,'per_path':str(score)}
|
| 385 |
+
comp=scored_composition_rows([u])
|
| 386 |
+
assert len(comp)==len(ARMS)*len(gate)
|
| 387 |
+
b=next(r for r in comp if r['arm']==ARMS[0] and r['cell_type']==gate[1])
|
| 388 |
+
assert b['observed_fraction']==0 and b['generated_fraction']==.5
|
| 389 |
+
per[0]['n_generated_cells']=1499
|
| 390 |
+
try:scored_composition_rows([u])
|
| 391 |
+
except ValueError as e:assert '1,500 generated' in str(e)
|
| 392 |
+
else:raise AssertionError('composition accepted incomplete generated cell budget')
|
| 393 |
+
print('Figure 3 exporter self-test passed: Poisson row order, marker axis, full-cell composition')
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def self_test_embedding():
|
| 397 |
+
rng=np.random.default_rng(7)
|
| 398 |
+
real=sp.csr_matrix(rng.poisson(2.0,size=(32,60)).astype(np.int32))
|
| 399 |
+
other=sp.csr_matrix(rng.poisson(2.0,size=(7,60)).astype(np.int32))
|
| 400 |
+
xy,pca,_=embed_reference(real,[other])
|
| 401 |
+
assert xy[0].shape==(32,2) and xy[1].shape==(7,2)
|
| 402 |
+
assert np.isfinite(xy[0]).all() and np.isfinite(xy[1]).all()
|
| 403 |
+
assert pca.n_components_==31
|
| 404 |
+
print('Figure 3 embedding fixture passed: one real-R1 fit, projected candidate')
|
| 405 |
+
|
| 406 |
+
if __name__=='__main__':
|
| 407 |
+
p=argparse.ArgumentParser();p.add_argument('--self-test',action='store_true')
|
| 408 |
+
p.add_argument('--self-test-embedding',action='store_true')
|
| 409 |
+
args=p.parse_args()
|
| 410 |
+
if args.self_test: self_test()
|
| 411 |
+
elif args.self_test_embedding: self_test_embedding()
|
| 412 |
+
else: build()
|
paper-releases/pbisc-diffusion/updates/20261012T130738Z-strictpairs-implementation/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T130738Z-strictpairs-implementation/snapshot/tools/export_rare_visuals.py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Strict Figure 5 marker-space illustrations from complete scored cache manifests.
|
| 3 |
+
|
| 4 |
+
Each donor is assigned one available held-out draw by a fixed hash, before state calls.
|
| 5 |
+
PCA and UMAP fit observed cells only; generated cells use that frozen transform.
|
| 6 |
+
The projection is a marker-space illustration, separate from all-draw numeric scores.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import argparse
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 17 |
+
raise SystemExit("rare-state visuals require CUDA_VISIBLE_DEVICES=''")
|
| 18 |
+
|
| 19 |
+
import matplotlib
|
| 20 |
+
matplotlib.use("Agg")
|
| 21 |
+
import matplotlib.pyplot as plt
|
| 22 |
+
import numpy as np
|
| 23 |
+
import pandas as pd
|
| 24 |
+
from sklearn.decomposition import PCA
|
| 25 |
+
from sklearn.preprocessing import StandardScaler
|
| 26 |
+
|
| 27 |
+
from build_figure5 import (HERE, STATES, STRICT_ARMS, _load, _metadata, _parent, _seed,
|
| 28 |
+
_sha256, _thin_depth, _thin_subset, require_complete_strict,
|
| 29 |
+
validate_strict_cache)
|
| 30 |
+
from rare_metrics import call_marker_state, validate_marker_coverage
|
| 31 |
+
|
| 32 |
+
EXAMPLES = (
|
| 33 |
+
{"slug": "sepsis_ms1", "cohort": "ye2026_sepsis", "state": "MS1 monocyte (IL1R2+)"},
|
| 34 |
+
{"slug": "sepsis_cycling_monocyte", "cohort": "ye2026_sepsis",
|
| 35 |
+
"state": "Cycling monocyte (Ye 2026)"},
|
| 36 |
+
{"slug": "imperial_cycling_tnk", "cohort": "imperial_eskd", "state": "Cycling T/NK"},
|
| 37 |
+
)
|
| 38 |
+
ARM_ORDER = ("observed", "raw", "refcal", "pairedcal", "scsemi", "lora")
|
| 39 |
+
SEED = 20261012
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def choose_donor_draws(units: list[dict], cohort: str, metadata: pd.DataFrame) -> dict[str, str]:
|
| 43 |
+
"""Select one available held-out draw per actual donor, independent of any result."""
|
| 44 |
+
mapping = metadata.set_index("sample_id").donor_id.astype(str)
|
| 45 |
+
available: dict[str, set[str]] = {}
|
| 46 |
+
for unit in units:
|
| 47 |
+
if unit["cohort"] != cohort:
|
| 48 |
+
continue
|
| 49 |
+
for sample in unit["test_sample_ids"]:
|
| 50 |
+
if sample not in mapping:
|
| 51 |
+
raise ValueError(f"{cohort}: sample {sample} lacks donor metadata")
|
| 52 |
+
available.setdefault(mapping[sample], set()).add(unit["unit"])
|
| 53 |
+
selected = {}
|
| 54 |
+
for donor, draws in available.items():
|
| 55 |
+
ordered = sorted(draws)
|
| 56 |
+
digest = hashlib.sha256(f"{SEED}|{cohort}|{donor}".encode()).digest()
|
| 57 |
+
selected[donor] = ordered[int.from_bytes(digest[:8], "little") % len(ordered)]
|
| 58 |
+
return selected
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def read_units(manifest_dir: Path) -> list[dict]:
|
| 62 |
+
paths = sorted(manifest_dir.rglob("rare_manifest.json"))
|
| 63 |
+
units = []
|
| 64 |
+
for path in paths:
|
| 65 |
+
doc = json.loads(path.read_text())
|
| 66 |
+
if doc.get("schema") != "pbisc.figure5.marker-caches.v1":
|
| 67 |
+
raise ValueError(f"wrong rare marker manifest schema: {path}")
|
| 68 |
+
for raw in doc["units"]:
|
| 69 |
+
unit = dict(raw)
|
| 70 |
+
for key in ("sample_metadata", "support_manifest", "observed_cache"):
|
| 71 |
+
unit[key] = str((path.parent / unit[key]).resolve())
|
| 72 |
+
unit["generated_caches"] = {a: str((path.parent / p).resolve())
|
| 73 |
+
for a, p in unit["generated_caches"].items()}
|
| 74 |
+
units.append(unit)
|
| 75 |
+
require_complete_strict(units)
|
| 76 |
+
return units
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _check_unit(unit: dict) -> dict:
|
| 80 |
+
support = json.loads(Path(unit["support_manifest"]).read_text())
|
| 81 |
+
body = {k: v for k, v in support.items() if k != "sha256"}
|
| 82 |
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"),
|
| 83 |
+
allow_nan=False).encode()).hexdigest()
|
| 84 |
+
if (support.get("schema") != "pbisc.paper.strict-support.v1" or
|
| 85 |
+
support.get("sha256") != digest or support.get("cohort") != unit["cohort"] or
|
| 86 |
+
support.get("unit") != f'{unit["unit"]}_n5' or
|
| 87 |
+
support.get("test_sample_ids") != unit["test_sample_ids"] or
|
| 88 |
+
support.get("train_sample_ids") != unit["train_sample_ids"] or
|
| 89 |
+
support.get("train_donor_ids") != unit["train_donor_ids"]):
|
| 90 |
+
raise ValueError("visual cache support mismatch")
|
| 91 |
+
if _sha256(Path(unit["observed_cache"])) != unit.get("observed_cache_sha256"):
|
| 92 |
+
raise ValueError("visual observed cache hash mismatch")
|
| 93 |
+
checked = {**unit, "test_donor_ids": support["test_donor_ids"]}
|
| 94 |
+
for arm, path in unit["generated_caches"].items():
|
| 95 |
+
cache = _load(Path(path))
|
| 96 |
+
validate_strict_cache(cache, Path(path), checked, arm, support["sha256"])
|
| 97 |
+
if set(cache["sample_id"].astype(str)) != set(unit["test_sample_ids"]):
|
| 98 |
+
raise ValueError(f"{arm}: visual scored sample set differs from strict support")
|
| 99 |
+
return support
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _selected_parent_cells(unit: dict, chosen: dict[str, str], state: dict,
|
| 103 |
+
cells_per_sample: int) -> tuple[list[dict], list[str]]:
|
| 104 |
+
metadata = _metadata(Path(unit["sample_metadata"]))
|
| 105 |
+
obs = _load(Path(unit["observed_cache"]))
|
| 106 |
+
generated = {arm: _load(Path(path)) for arm, path in unit["generated_caches"].items()}
|
| 107 |
+
symbols = list(obs["marker_symbols"].astype(str))
|
| 108 |
+
validate_marker_coverage(state, symbols)
|
| 109 |
+
if any(list(cache["marker_symbols"].astype(str)) != symbols for cache in generated.values()):
|
| 110 |
+
raise ValueError("visual marker columns differ across methods")
|
| 111 |
+
records = []
|
| 112 |
+
obs_ids = obs["sample_id"].astype(str)
|
| 113 |
+
gen_ids = {arm: cache["sample_id"].astype(str) for arm, cache in generated.items()}
|
| 114 |
+
for sample in unit["test_sample_ids"]:
|
| 115 |
+
donor = str(metadata.loc[sample].donor_id)
|
| 116 |
+
if chosen.get(donor) != unit["unit"]:
|
| 117 |
+
continue
|
| 118 |
+
ids = {arm: np.flatnonzero(values == sample) for arm, values in gen_ids.items()}
|
| 119 |
+
oidx = np.flatnonzero(obs_ids == sample)
|
| 120 |
+
budget = min(cells_per_sample, int(unit["cell_budget"]), len(oidx),
|
| 121 |
+
*(len(v) for v in ids.values()))
|
| 122 |
+
if budget <= 0:
|
| 123 |
+
raise ValueError(f"{sample}: no common cells for visual")
|
| 124 |
+
for arm in ARM_ORDER:
|
| 125 |
+
cache = obs if arm == "observed" else generated[arm]
|
| 126 |
+
idx = oidx if arm == "observed" else ids[arm]
|
| 127 |
+
x = _thin_depth(_thin_subset(
|
| 128 |
+
cache, idx, budget, _seed(unit["cohort"], unit["unit"], sample, "visual", arm)),
|
| 129 |
+
float(unit["depth_target"]),
|
| 130 |
+
_seed(unit["cohort"], unit["unit"], sample, "visual", arm, "depth"))
|
| 131 |
+
parent = _parent(x, state)
|
| 132 |
+
hits = call_marker_state(x["markers"], symbols, state) & parent
|
| 133 |
+
records.append(dict(arm=arm, cohort=unit["cohort"], draw=unit["unit"],
|
| 134 |
+
donor_id=donor, sample_id=sample, group=str(metadata.loc[sample].group),
|
| 135 |
+
markers=x["markers"][parent], hits=hits[parent],
|
| 136 |
+
selected_all_cells=budget, selected_parent_cells=int(parent.sum()),
|
| 137 |
+
selected_cells_below_depth_target=x["below_target"],
|
| 138 |
+
depth_target=float(unit["depth_target"])))
|
| 139 |
+
return records, symbols
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def _make_projection(records: list[dict], symbols: list[str], example: dict,
|
| 143 |
+
state: dict) -> tuple[pd.DataFrame, pd.DataFrame]:
|
| 144 |
+
real = [r["markers"] for r in records if r["arm"] == "observed" and len(r["markers"])]
|
| 145 |
+
if not real or sum(len(x) for x in real) < 16:
|
| 146 |
+
raise ValueError("fewer than 16 real parent cells for 15-neighbor UMAP")
|
| 147 |
+
observed = np.vstack(real)
|
| 148 |
+
scaler = StandardScaler().fit(np.log1p(observed))
|
| 149 |
+
n_components = min(20, len(symbols), len(observed) - 1)
|
| 150 |
+
pca = PCA(n_components=n_components, random_state=SEED).fit(scaler.transform(np.log1p(observed)))
|
| 151 |
+
real_pc = pca.transform(scaler.transform(np.log1p(observed)))
|
| 152 |
+
import umap
|
| 153 |
+
mapper = umap.UMAP(n_neighbors=15, n_components=2, min_dist=.15,
|
| 154 |
+
random_state=SEED, transform_seed=SEED, n_jobs=1).fit(real_pc)
|
| 155 |
+
cells, heat = [], []
|
| 156 |
+
genes = list(dict.fromkeys(state["genes"] +
|
| 157 |
+
[g for grp in state.get("require_any", []) for g in grp] + state.get("exclude", [])))
|
| 158 |
+
pos = {g: i for i, g in enumerate(symbols)}
|
| 159 |
+
real_cursor = 0
|
| 160 |
+
for record in records:
|
| 161 |
+
counts = record["markers"]
|
| 162 |
+
if not len(counts):
|
| 163 |
+
continue
|
| 164 |
+
if record["arm"] == "observed":
|
| 165 |
+
xy = mapper.embedding_[real_cursor:real_cursor + len(counts)]
|
| 166 |
+
real_cursor += len(counts)
|
| 167 |
+
else:
|
| 168 |
+
pc = pca.transform(scaler.transform(np.log1p(counts)))
|
| 169 |
+
xy = mapper.transform(pc)
|
| 170 |
+
for k in range(len(counts)):
|
| 171 |
+
cells.append(dict(example=example["slug"], cohort=example["cohort"],
|
| 172 |
+
state=example["state"], arm=record["arm"],
|
| 173 |
+
donor_id=record["donor_id"], sample_id=record["sample_id"],
|
| 174 |
+
selected_draw=record["draw"], group=record["group"],
|
| 175 |
+
state_hit=bool(record["hits"][k]), umap1=float(xy[k, 0]),
|
| 176 |
+
umap2=float(xy[k, 1]), projection_fit_source="observed_only",
|
| 177 |
+
projection_space="measured_marker_counts",
|
| 178 |
+
depth_target=record["depth_target"],
|
| 179 |
+
cell_budget_used=record["selected_all_cells"]))
|
| 180 |
+
for arm in ARM_ORDER:
|
| 181 |
+
xs = [r["markers"] for r in records if r["arm"] == arm and len(r["markers"])]
|
| 182 |
+
if not xs:
|
| 183 |
+
continue
|
| 184 |
+
x = np.vstack(xs)
|
| 185 |
+
positive = (x[:, [pos[g] for g in state["genes"]]] > 0).sum(axis=1)
|
| 186 |
+
for gene in genes:
|
| 187 |
+
c = x[:, pos[gene]]
|
| 188 |
+
heat.append(dict(example=example["slug"], cohort=example["cohort"],
|
| 189 |
+
state=example["state"], arm=arm, marker=gene,
|
| 190 |
+
n_parent_cells=len(x), detection_pct=100*float((c > 0).mean()),
|
| 191 |
+
mean_count=float(c.mean()), codetection_pct=100*float((positive >= 2).mean()),
|
| 192 |
+
depth_target=records[0]["depth_target"]))
|
| 193 |
+
return pd.DataFrame(cells), pd.DataFrame(heat)
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
def _plot_panels(cells: pd.DataFrame, heat: pd.DataFrame, statuses: list[dict], out: Path) -> None:
|
| 197 |
+
fig, axs = plt.subplots(len(EXAMPLES), 3, figsize=(13, 11), constrained_layout=True)
|
| 198 |
+
plt.rcParams.update({"font.family": "DejaVu Sans", "font.size": 8, "pdf.fonttype": 42})
|
| 199 |
+
for row, example in enumerate(EXAMPLES):
|
| 200 |
+
ex = cells[cells.example == example["slug"]]
|
| 201 |
+
hm = heat[heat.example == example["slug"]]
|
| 202 |
+
status = next(s for s in statuses if s["example"] == example["slug"])
|
| 203 |
+
if status["status"] != "available":
|
| 204 |
+
for ax in axs[row]:
|
| 205 |
+
ax.axis("off")
|
| 206 |
+
ax.text(.02, .8, f'{example["state"]}: unavailable\n{status["reason"]}',
|
| 207 |
+
transform=ax.transAxes, va="top")
|
| 208 |
+
continue
|
| 209 |
+
real = ex[ex.arm == "observed"]
|
| 210 |
+
lora = ex[ex.arm == "lora"]
|
| 211 |
+
for col, foreground in ((0, real), (1, lora)):
|
| 212 |
+
ax = axs[row, col]
|
| 213 |
+
ax.scatter(real.umap1, real.umap2, s=2, color="#bfc9cc", alpha=.35)
|
| 214 |
+
if col == 1:
|
| 215 |
+
ax.scatter(lora.umap1, lora.umap2, s=3, color="#81b6bf", alpha=.22)
|
| 216 |
+
rare = foreground[foreground.state_hit.astype(bool)]
|
| 217 |
+
ax.scatter(rare.umap1, rare.umap2, s=8, color="#c14c40", alpha=.85)
|
| 218 |
+
ax.set_xlabel("UMAP 1")
|
| 219 |
+
ax.set_ylabel("UMAP 2")
|
| 220 |
+
ax.set_title(f'{example["state"]}\n' +
|
| 221 |
+
("real held-out reference" if col == 0 else "LoRA projected onto real map"))
|
| 222 |
+
ax = axs[row, 2]
|
| 223 |
+
mat = hm.pivot(index="marker", columns="arm", values="detection_pct")
|
| 224 |
+
mat = mat.reindex(columns=[a for a in ARM_ORDER if a in mat.columns])
|
| 225 |
+
cod = hm.groupby("arm").codetection_pct.first().reindex(mat.columns)
|
| 226 |
+
mat.loc["≥2 positive markers"] = cod
|
| 227 |
+
img = ax.imshow(mat.to_numpy(), aspect="auto", cmap="magma", vmin=0,
|
| 228 |
+
vmax=max(5, float(np.nanmax(mat.to_numpy()))))
|
| 229 |
+
ax.set_xticks(range(len(mat.columns)), mat.columns, rotation=35, ha="right")
|
| 230 |
+
ax.set_yticks(range(len(mat.index)), mat.index)
|
| 231 |
+
ax.set_title("Detected cells (%) + codetection")
|
| 232 |
+
fig.colorbar(img, ax=ax, fraction=.045, pad=.02)
|
| 233 |
+
fig.suptitle("Figure 5 rare-state visual examples · real-only marker-space projection\n"
|
| 234 |
+
"One held-out draw per donor fixed by hash; all-draw numeric results shown separately",
|
| 235 |
+
fontsize=13, weight="bold")
|
| 236 |
+
(out / "figures").mkdir(parents=True, exist_ok=True)
|
| 237 |
+
for ext in ("pdf", "svg", "png"):
|
| 238 |
+
fig.savefig(out / "figures" / f"fig5_rare_visuals_strict.{ext}", dpi=220, bbox_inches="tight")
|
| 239 |
+
plt.close(fig)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def build_visuals(units: list[dict], out: Path, *, require_complete: bool = True,
|
| 243 |
+
validate_sources: bool = True, cells_per_sample: int = 100) -> dict:
|
| 244 |
+
if require_complete:
|
| 245 |
+
require_complete_strict(units)
|
| 246 |
+
prior = json.loads((out / "reports/rare_provenance.json").read_text())
|
| 247 |
+
if (len(prior.get("units", [])) != 20 or
|
| 248 |
+
{u.get("evidence_tier") for u in prior["units"]} != {"strict"}):
|
| 249 |
+
raise ValueError("complete strict rare numeric analysis required before visuals")
|
| 250 |
+
if cells_per_sample <= 0:
|
| 251 |
+
raise ValueError("visual cells_per_sample must be positive")
|
| 252 |
+
if len({float(u["depth_target"]) for u in units}) != 1:
|
| 253 |
+
raise ValueError("visual input has mixed depth target")
|
| 254 |
+
if len({int(u["cell_budget"]) for u in units}) != 1:
|
| 255 |
+
raise ValueError("visual input has mixed cell budget")
|
| 256 |
+
states = {s["name"]: s for s in json.loads(STATES.read_text())}
|
| 257 |
+
all_cells, all_heat, statuses, choices = [], [], [], []
|
| 258 |
+
for example in EXAMPLES:
|
| 259 |
+
cohort_units = [u for u in units if u["cohort"] == example["cohort"]]
|
| 260 |
+
if not cohort_units:
|
| 261 |
+
statuses.append(dict(example=example["slug"], status="unavailable",
|
| 262 |
+
reason="cohort cache absent"))
|
| 263 |
+
continue
|
| 264 |
+
meta = pd.read_csv(cohort_units[0]["sample_metadata"], dtype=str)
|
| 265 |
+
chosen = choose_donor_draws(cohort_units, example["cohort"], meta)
|
| 266 |
+
choices.extend(dict(example=example["slug"], cohort=example["cohort"],
|
| 267 |
+
donor_id=d, selected_draw=draw, rule="sha256(seed|cohort|donor) mod available draws")
|
| 268 |
+
for d, draw in chosen.items())
|
| 269 |
+
state = states[example["state"]]
|
| 270 |
+
records, symbols = [], None
|
| 271 |
+
try:
|
| 272 |
+
for unit in cohort_units:
|
| 273 |
+
if not any(draw == unit["unit"] for draw in chosen.values()):
|
| 274 |
+
continue
|
| 275 |
+
if validate_sources:
|
| 276 |
+
_check_unit(unit)
|
| 277 |
+
subset, syms = _selected_parent_cells(unit, chosen, state, cells_per_sample)
|
| 278 |
+
if symbols is not None and symbols != syms:
|
| 279 |
+
raise ValueError("marker symbols differ across selected draws")
|
| 280 |
+
symbols = syms
|
| 281 |
+
records.extend(subset)
|
| 282 |
+
if not records:
|
| 283 |
+
raise ValueError("no selected held-out cells")
|
| 284 |
+
cells, heat = _make_projection(records, symbols, example, state)
|
| 285 |
+
all_cells.append(cells)
|
| 286 |
+
all_heat.append(heat)
|
| 287 |
+
statuses.append(dict(example=example["slug"], status="available",
|
| 288 |
+
real_parent_cells=int((cells.arm == "observed").sum()),
|
| 289 |
+
generated_parent_cells=int((cells.arm != "observed").sum())))
|
| 290 |
+
except ValueError as exc:
|
| 291 |
+
if "missing mandatory marker" not in str(exc) and "fewer than 16 real parent" not in str(exc):
|
| 292 |
+
raise
|
| 293 |
+
statuses.append(dict(example=example["slug"], status="unavailable", reason=str(exc)))
|
| 294 |
+
cells = pd.concat(all_cells, ignore_index=True) if all_cells else pd.DataFrame()
|
| 295 |
+
heat = pd.concat(all_heat, ignore_index=True) if all_heat else pd.DataFrame()
|
| 296 |
+
(out / "source_data").mkdir(parents=True, exist_ok=True)
|
| 297 |
+
(out / "reports").mkdir(parents=True, exist_ok=True)
|
| 298 |
+
cells.to_csv(out / "source_data/rare_visual_cells.csv", index=False)
|
| 299 |
+
heat.to_csv(out / "source_data/rare_visual_heatmap.csv", index=False)
|
| 300 |
+
pd.DataFrame(choices).drop_duplicates().to_csv(out / "source_data/rare_visual_donor_draws.csv", index=False)
|
| 301 |
+
_plot_panels(cells, heat, statuses, out)
|
| 302 |
+
visual_status = "complete" if any(s["status"] == "available" for s in statuses) else "unavailable"
|
| 303 |
+
report = {"schema": "pbisc.figure5.marker-visuals.v1", "status": visual_status,
|
| 304 |
+
"evidence_tier": "strict", "projection": "PCA and 15-neighbor UMAP fit observed marker counts only; generated transform frozen",
|
| 305 |
+
"projection_seed": SEED, "donor_draw_seed": SEED,
|
| 306 |
+
"projection_space": "measured_marker_counts_illustration_not_numeric_score",
|
| 307 |
+
"visual_cells_per_sample_cap": cells_per_sample,
|
| 308 |
+
"common_analysis_cell_budget": int(units[0]["cell_budget"]),
|
| 309 |
+
"common_depth_target": float(units[0]["depth_target"]),
|
| 310 |
+
"examples": statuses, "all_draw_numeric_metrics": "source_data/rare_summary.csv"}
|
| 311 |
+
(out / "reports/rare_visual_provenance.json").write_text(json.dumps(report, indent=2) + "\n")
|
| 312 |
+
if require_complete:
|
| 313 |
+
prior_path = out / "reports/rare_provenance.json"
|
| 314 |
+
prior = json.loads(prior_path.read_text())
|
| 315 |
+
prior["visuals"] = {"status": visual_status, "provenance": "reports/rare_visual_provenance.json",
|
| 316 |
+
"figure": "figures/fig5_rare_visuals_strict.pdf"}
|
| 317 |
+
prior_path.write_text(json.dumps(prior, indent=2) + "\n")
|
| 318 |
+
return report
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def main() -> None:
|
| 322 |
+
ap = argparse.ArgumentParser(description=__doc__)
|
| 323 |
+
ap.add_argument("--manifest-dir", type=Path, required=True)
|
| 324 |
+
ap.add_argument("--output", type=Path, default=HERE)
|
| 325 |
+
ap.add_argument("--cells-per-sample", type=int, default=100)
|
| 326 |
+
args = ap.parse_args()
|
| 327 |
+
units = read_units(args.manifest_dir)
|
| 328 |
+
print(json.dumps(build_visuals(units, args.output, cells_per_sample=args.cells_per_sample)))
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
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/export_scsemi_strict.py
ADDED
|
@@ -0,0 +1,198 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Adapted from paired_finetune_intradataset_20260927/scsemi/tools/export_npz.py.
|
| 2 |
+
# Strict support extension; legacy exporter remains unchanged.
|
| 3 |
+
#!/usr/bin/env python
|
| 4 |
+
"""Adapter: completed scSemiProfiler target shards -> the benchmark's generated NPZ + JSON receipt (CPU only).
|
| 5 |
+
|
| 6 |
+
Per target (condition-NPZ order):
|
| 7 |
+
cells upstream output has one generated cell per cell of the assigned representative (n_rep cells).
|
| 8 |
+
Keep 1,500: n_rep >= 1500 -> 1,500 drawn without replacement; n_rep < 1500 -> whole permutations of the
|
| 9 |
+
n_rep cells concatenated until 1,500 (each cell used floor/ceil(1500/n_rep) times). Stream
|
| 10 |
+
default_rng([20260927, uint64(sha256(target)[:8])]) (the scorer's donor-keyed stream form); kept rows sorted.
|
| 11 |
+
depth upstream values are normalized expression (library-normalised ZINB means, values <= 10 zeroed). Each kept
|
| 12 |
+
cell is rescaled to sum to D = the median per-cell UMI on the modeled genes of the representatives'
|
| 13 |
+
observed cells (inputs_manifest depth.value; label-free, from the training pairs only). All-zero cells stay
|
| 14 |
+
zero (counted). Result = expected counts (Poisson rates), what score_ft.py reads out.
|
| 15 |
+
genes modeled genes placed at their 6k-panel columns; every other panel column is 0.
|
| 16 |
+
metadata_json.input_condition_path = the split's test_raw.npz, so the scorer's bulk-broadcast baseline works.
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import argparse
|
| 21 |
+
import hashlib
|
| 22 |
+
import json
|
| 23 |
+
import math
|
| 24 |
+
import os
|
| 25 |
+
import sys
|
| 26 |
+
from datetime import datetime, timezone
|
| 27 |
+
from pathlib import Path
|
| 28 |
+
|
| 29 |
+
if os.environ.get("CUDA_VISIBLE_DEVICES") != "":
|
| 30 |
+
raise SystemExit("run with CUDA_VISIBLE_DEVICES=''")
|
| 31 |
+
|
| 32 |
+
import numpy as np
|
| 33 |
+
import pandas as pd
|
| 34 |
+
import scipy.sparse as sp
|
| 35 |
+
|
| 36 |
+
M8 = Path("/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion")
|
| 37 |
+
PANEL = M8 / "artifacts/panel_ladder_floor01_1m_20260923/tiers/6k/selected_genes.csv"
|
| 38 |
+
SEED = 20260927
|
| 39 |
+
N_CELLS = 1500
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def sha(path: Path) -> str:
|
| 43 |
+
h = hashlib.sha256()
|
| 44 |
+
with open(path, "rb") as f:
|
| 45 |
+
for block in iter(lambda: f.read(1 << 24), b""):
|
| 46 |
+
h.update(block)
|
| 47 |
+
return h.hexdigest()
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def target_rng(target: str) -> np.random.Generator:
|
| 51 |
+
key = int.from_bytes(hashlib.sha256(str(target).encode()).digest()[:8], "little")
|
| 52 |
+
return np.random.default_rng([SEED, key])
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def pick_rows(n_src: int, target: str, n_out: int = N_CELLS) -> np.ndarray:
|
| 56 |
+
if n_src < 1:
|
| 57 |
+
raise ValueError(f"{target}: no generated cells")
|
| 58 |
+
rng = target_rng(target)
|
| 59 |
+
if n_src >= n_out:
|
| 60 |
+
return np.sort(rng.choice(n_src, size=n_out, replace=False))
|
| 61 |
+
reps = math.ceil(n_out / n_src)
|
| 62 |
+
return np.sort(np.concatenate([rng.permutation(n_src) for _ in range(reps)])[:n_out])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def to_expected_counts(X: np.ndarray, depth: float) -> tuple[np.ndarray, int]:
|
| 66 |
+
lib = X.sum(1, dtype=np.float64)
|
| 67 |
+
scale = np.divide(depth, lib, out=np.zeros_like(lib), where=lib > 0)
|
| 68 |
+
return (X * scale[:, None]).astype(np.float32), int((lib <= 0).sum())
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def strict_arm_metadata(man: dict, support: dict) -> dict:
|
| 72 |
+
if man.get("mode") != "strict" or man.get("dataset") != support["cohort"]:
|
| 73 |
+
raise ValueError("strict export requires strict dataset inputs")
|
| 74 |
+
if (man.get("support_sha256") != support["sha256"] or
|
| 75 |
+
[r["sample_id"] for r in man["representatives"]] != support["train_sample_ids"] or
|
| 76 |
+
man["train_donors"] != support["train_donor_ids"] or
|
| 77 |
+
man["target_order_test_samples"] != support["test_sample_ids"]):
|
| 78 |
+
raise ValueError("export support or reference budget mismatch")
|
| 79 |
+
return {"arm": "scsemi", "support_sha256": support["sha256"], "cohort": support["cohort"],
|
| 80 |
+
"unit": support["unit"], "n_pairs": support["n_pairs"],
|
| 81 |
+
"train_sample_ids": support["train_sample_ids"], "train_donor_ids": support["train_donor_ids"]}
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def main(argv=None) -> int:
|
| 85 |
+
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 86 |
+
ap.add_argument("--work", type=Path, required=True)
|
| 87 |
+
ap.add_argument("--out", type=Path, required=True, help="generated NPZ path (receipt = same stem .log)")
|
| 88 |
+
ap.add_argument("--support-manifest", type=Path, required=True)
|
| 89 |
+
a = ap.parse_args(argv)
|
| 90 |
+
work, out = a.work.resolve(), a.out.resolve()
|
| 91 |
+
man = json.loads((work / "inputs/inputs_manifest.json").read_text())
|
| 92 |
+
run = json.loads((work / "run_manifest.json").read_text())
|
| 93 |
+
smoke = bool(man.get("smoke"))
|
| 94 |
+
if smoke and "/scsemi/smoke/" not in str(out):
|
| 95 |
+
raise SystemExit("smoke outputs never go to the benchmark's generated/ tree")
|
| 96 |
+
if out.exists() or out.with_suffix(".log").exists():
|
| 97 |
+
raise SystemExit(f"{out} or its receipt exists; never overwrite (preserve and inspect)")
|
| 98 |
+
from run_scsemi_strict import validate_strict_inputs
|
| 99 |
+
support = validate_strict_inputs(a.support_manifest, work, phase="export", reuse_from=None)
|
| 100 |
+
strict_meta = strict_arm_metadata(man, support)
|
| 101 |
+
signature = run["run_signature"]
|
| 102 |
+
genes = man["modeled_genes"]["gene_ids"]
|
| 103 |
+
pidx = np.asarray(man["modeled_genes"]["panel_index"], dtype=np.int64)
|
| 104 |
+
panel = pd.read_csv(PANEL)
|
| 105 |
+
panel_ids = np.asarray(panel.gene_id.astype(str).tolist(), dtype=str) # fixed-width unicode: loads with allow_pickle=False
|
| 106 |
+
panel_symbols = np.asarray(panel.gene_symbol.astype(str).tolist(), dtype=str)
|
| 107 |
+
if not np.array_equal(panel_ids[pidx], np.asarray(genes)):
|
| 108 |
+
raise SystemExit("modeled genes do not sit at the recorded panel columns")
|
| 109 |
+
depth = float(man["depth"]["value"])
|
| 110 |
+
if not (np.isfinite(depth) and depth > 0):
|
| 111 |
+
raise SystemExit("invalid depth")
|
| 112 |
+
targets = man["condition_sample_order"] if not smoke else [t for t in man["condition_sample_order"]
|
| 113 |
+
if t in set(man["target_order_test_samples"])]
|
| 114 |
+
if sorted(targets) != sorted(man["target_order_test_samples"]):
|
| 115 |
+
raise SystemExit("targets differ from the condition NPZ order")
|
| 116 |
+
per, src_rows = [], []
|
| 117 |
+
G = np.zeros((len(targets) * N_CELLS, panel_ids.size), dtype=np.float32)
|
| 118 |
+
for i, t in enumerate(targets):
|
| 119 |
+
rec = json.loads((work / "shards" / f"{t}.json").read_text())
|
| 120 |
+
shard = work / "shards" / f"{t}.npz"
|
| 121 |
+
if not rec.get("complete") or rec["run_signature"] != signature or rec["shard_sha256"] != sha(shard):
|
| 122 |
+
raise SystemExit(f"{t}: shard incomplete or receipt mismatch")
|
| 123 |
+
C = sp.load_npz(shard).tocsr()
|
| 124 |
+
if C.shape[1] != len(genes):
|
| 125 |
+
raise SystemExit(f"{t}: shard has {C.shape[1]} genes")
|
| 126 |
+
rows = pick_rows(C.shape[0], t)
|
| 127 |
+
X = C[rows].toarray().astype(np.float64)
|
| 128 |
+
if not np.isfinite(X).all() or (X < 0).any():
|
| 129 |
+
raise SystemExit(f"{t}: non-finite or negative values")
|
| 130 |
+
E, n_zero = to_expected_counts(X, depth)
|
| 131 |
+
G[i * N_CELLS:(i + 1) * N_CELLS, pidx] = E
|
| 132 |
+
src_rows.append(rows.astype(np.int32))
|
| 133 |
+
mult = np.bincount(rows, minlength=C.shape[0])
|
| 134 |
+
per.append({"sample_id": t, "representative": rec["representative"], "n_upstream_cells": int(C.shape[0]),
|
| 135 |
+
"with_replacement": bool(C.shape[0] < N_CELLS), "max_multiplicity": int(mult.max()),
|
| 136 |
+
"zero_library_cells": n_zero, "elapsed_seconds": rec["elapsed_seconds"],
|
| 137 |
+
"median_nonzero_genes": float(np.median((E > 0).sum(1)))})
|
| 138 |
+
lib = G.sum(1, dtype=np.float64)
|
| 139 |
+
nz = lib > 0
|
| 140 |
+
checks = {"finite": bool(np.isfinite(G).all()), "nonnegative": bool((G >= 0).all()),
|
| 141 |
+
"zero_outside_modeled_genes": bool(not G[:, np.setdiff1d(np.arange(panel_ids.size), pidx)].any()),
|
| 142 |
+
"nonzero_cells_sum_to_depth": bool(np.allclose(lib[nz], depth, rtol=1e-4)),
|
| 143 |
+
"gene_order_equals_panel": True, "cells_per_target": N_CELLS}
|
| 144 |
+
if not all(v for k, v in checks.items() if isinstance(v, bool)):
|
| 145 |
+
raise SystemExit(f"output checks failed: {checks}")
|
| 146 |
+
n_t = len(targets)
|
| 147 |
+
avail = np.zeros((n_t, panel_ids.size), dtype=bool)
|
| 148 |
+
avail[:, pidx] = True
|
| 149 |
+
arm = strict_meta["arm"]
|
| 150 |
+
meta = {"method": "scSemiProfiler", "arm": arm,
|
| 151 |
+
"setting": run["protocol"]["setting"], "dataset": man["dataset"], "mode": man["mode"], "split": man["split"],
|
| 152 |
+
"input_condition_path": man["condition_npz"], "input_condition_sha256": man["condition_sha256"],
|
| 153 |
+
"seed": SEED, "run_signature": signature, "upstream_commit": run["protocol"]["upstream_commit"],
|
| 154 |
+
"protocol": run["protocol"], "representatives": [r["sample_id"] for r in man["representatives"]],
|
| 155 |
+
"train_donors": man["train_donors"], "n_modeled_genes": len(genes),
|
| 156 |
+
"unit": "expected_counts (Poisson rates)", "depth_rule": man["depth"]["rule"], "depth": depth,
|
| 157 |
+
"cell_rule": "1500 per target from the n_rep upstream cells: without replacement if n_rep >= 1500, else "
|
| 158 |
+
"whole permutations concatenated to 1500; default_rng([20260927, uint64 LE sha256(target)[:8]]); "
|
| 159 |
+
"kept rows sorted (source_row)",
|
| 160 |
+
"support_readout": "upstream (values <= 10 normalized units zeroed by fast_semi)", "smoke": smoke,
|
| 161 |
+
"code_migrations": [{"at": m["at"], "transitions": m["transitions"], "to_code_signature": m["to_code_signature"]}
|
| 162 |
+
for m in run.get("migrations", [])],
|
| 163 |
+
"work": str(work)}
|
| 164 |
+
meta["strict_support"] = strict_meta
|
| 165 |
+
if "budget" in man:
|
| 166 |
+
meta["budget"] = man["budget"]
|
| 167 |
+
if "reuse" in run: # pretraining / hvset reused from another run (run_scsemi_paired.py --reuse-from)
|
| 168 |
+
meta["reuse"] = run["reuse"]
|
| 169 |
+
out.parent.mkdir(parents=True, exist_ok=True)
|
| 170 |
+
tmp = out.with_name(out.stem + ".tmp.npz")
|
| 171 |
+
np.savez_compressed(tmp, generated_counts=G, gene_ids=panel_ids, gene_symbols=panel_symbols,
|
| 172 |
+
sample_ids=np.asarray(targets), bulk_index=np.repeat(np.arange(n_t, dtype=np.int64), N_CELLS),
|
| 173 |
+
cells_per_bulk=np.full(n_t, N_CELLS, dtype=np.int64), output_availability_mask=avail,
|
| 174 |
+
source_row=np.concatenate(src_rows), metadata_json=np.asarray(json.dumps(meta)))
|
| 175 |
+
with np.load(tmp, allow_pickle=False) as chk: # the scorer opens NPZs with allow_pickle=False
|
| 176 |
+
for key in chk.files:
|
| 177 |
+
chk[key]
|
| 178 |
+
os.replace(tmp, out)
|
| 179 |
+
receipt = {"output": str(out), "output_sha256": sha(out), "written_utc": datetime.now(timezone.utc).isoformat(),
|
| 180 |
+
"condition_npz": man["condition_npz"], "condition_sha256": man["condition_sha256"], "seed": SEED,
|
| 181 |
+
"bulks": n_t, "cells": int(G.shape[0]), "genes": int(panel_ids.size), "modeled_genes": len(genes),
|
| 182 |
+
"depth": depth, "checks": checks, "per_target": per,
|
| 183 |
+
"total_target_seconds": float(sum(p["elapsed_seconds"] for p in per)),
|
| 184 |
+
"median_target_seconds": float(np.median([p["elapsed_seconds"] for p in per])),
|
| 185 |
+
"run_signature": signature, "code_migrations": meta["code_migrations"],
|
| 186 |
+
"exporter_sha256": sha(Path(__file__)), "smoke": smoke,
|
| 187 |
+
"strict_support": strict_meta, "inputs_manifest_sha256": sha(work / "inputs/inputs_manifest.json"),
|
| 188 |
+
"inputs_manifest_path": str(work / "inputs/inputs_manifest.json")}
|
| 189 |
+
rtmp = out.with_name(out.stem + ".log.tmp")
|
| 190 |
+
rtmp.write_text(json.dumps(receipt, indent=1) + "\n")
|
| 191 |
+
os.replace(rtmp, out.with_suffix(".log"))
|
| 192 |
+
print(json.dumps({k: receipt[k] for k in ("output", "bulks", "cells", "modeled_genes", "depth",
|
| 193 |
+
"median_target_seconds")}))
|
| 194 |
+
return 0
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
if __name__ == "__main__":
|
| 198 |
+
sys.exit(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/figure2_panels.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Figure 2: native pseudobulk design and separately evaluated real-bulk adaptation."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json
|
| 4 |
+
import hashlib
|
| 5 |
+
import csv
|
| 6 |
+
import numpy as np
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
+
OLD = ROOT.parent / 'paired_finetune_intradataset_20260927'
|
| 10 |
+
RANK_ARMS = (
|
| 11 |
+
('Full FT', 'real_full__raw', 'real_full', 'pooled'),
|
| 12 |
+
('LoRA r=4', 'lora_r4__raw', 'lora_r4', 'lora_rank_20261001/pooled'),
|
| 13 |
+
('LoRA r=16', 'real_lora__raw', 'real_lora', 'pooled'),
|
| 14 |
+
('LoRA r=64', 'lora_r64__raw', 'lora_r64', 'lora_rank_20261001/pooled'),
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
def sha(path):
|
| 18 |
+
return hashlib.file_digest(Path(path).open('rb'), 'sha256').hexdigest()
|
| 19 |
+
|
| 20 |
+
def read(path):
|
| 21 |
+
return json.loads(Path(path).read_text())
|
| 22 |
+
|
| 23 |
+
def historical_rank_rows():
|
| 24 |
+
"""All four arms trained on the same real-bulk folds and validation donors."""
|
| 25 |
+
rows, proofs = [], []
|
| 26 |
+
reference = None
|
| 27 |
+
for label, arm, run_name, score_rel in RANK_ARMS:
|
| 28 |
+
score = OLD / 'scores/immicro' / score_rel / 'summary.json'
|
| 29 |
+
summary = read(score)
|
| 30 |
+
signature = (summary['donors'], summary['reference']['reference_sha256'],
|
| 31 |
+
summary['reference']['features_sha256'])
|
| 32 |
+
if reference is None:
|
| 33 |
+
reference = signature
|
| 34 |
+
if signature != reference:
|
| 35 |
+
raise ValueError('historical rank/full scoring references or held-out donors differ')
|
| 36 |
+
params = set()
|
| 37 |
+
run_proofs = []
|
| 38 |
+
for fold in range(5):
|
| 39 |
+
source = OLD / 'runs/immicro' / f'fold{fold}' / run_name / 'RUN.json'
|
| 40 |
+
record = read(source)
|
| 41 |
+
baseline = read(OLD / 'runs/immicro' / f'fold{fold}/real_full/RUN.json')
|
| 42 |
+
if not record['condition_npz'].endswith('/conditions_raw_fixed.npz'):
|
| 43 |
+
raise ValueError('Figure 2 rank selection requires real-bulk adaptation')
|
| 44 |
+
for key in ('condition_npz_sha256', 'source_checkpoint_sha256'):
|
| 45 |
+
if record[key] != baseline[key]:
|
| 46 |
+
raise ValueError(f'rank/full {key} differs')
|
| 47 |
+
for key in ('train_rows', 'inner_val_rows', 'test_rows_never_loaded_for_training'):
|
| 48 |
+
if set(record[key]) != set(baseline[key]):
|
| 49 |
+
raise ValueError(f'rank/full {key} differs in fold {fold}')
|
| 50 |
+
params.add(record['trainable']['n_trainable'])
|
| 51 |
+
run_proofs.append({'fold': fold, 'source': str(source), 'sha256': sha(source),
|
| 52 |
+
'train_samples': len(record['train_rows']),
|
| 53 |
+
'validation_samples': len(record['inner_val_rows']),
|
| 54 |
+
'test_samples': len(record['test_rows_never_loaded_for_training'])})
|
| 55 |
+
if len(params) != 1:
|
| 56 |
+
raise ValueError('parameter count differs across historical folds')
|
| 57 |
+
metric = summary['per_arm'][arm]
|
| 58 |
+
rows.append({'design': 'historical_real_bulk_5fold_pooled107', 'arm': arm,
|
| 59 |
+
'label': label, 'precision': metric['precision_coverage']['precision'],
|
| 60 |
+
'coverage': metric['precision_coverage']['coverage'],
|
| 61 |
+
'comp_l1': metric['composition']['l1_mean'], 'trainable_parameters': params.pop(),
|
| 62 |
+
'source': str(score), 'source_sha256': sha(score)})
|
| 63 |
+
proofs.append({'arm': arm, 'folds': run_proofs})
|
| 64 |
+
return rows, proofs
|
| 65 |
+
|
| 66 |
+
def strict_curve_rows(units):
|
| 67 |
+
rows = []
|
| 68 |
+
for unit in units:
|
| 69 |
+
support = unit['support']
|
| 70 |
+
for arm in ('lora', 'pairedcal', 'scsemi', 'raw', 'refcal'):
|
| 71 |
+
metric = unit['summary']['per_arm'][arm]
|
| 72 |
+
pc = metric['precision_coverage']
|
| 73 |
+
rows.append({'design': 'strict_exact_n', 'fold': support['unit'].split('_')[0],
|
| 74 |
+
'n_pairs': support['n_pairs'], 'target_pairs_used': 0 if arm in ('raw','refcal') else support['n_pairs'],
|
| 75 |
+
'arm': arm, 'precision': pc['precision'], 'coverage': pc['coverage'],
|
| 76 |
+
'comp_l1': metric['composition']['l1_mean'],
|
| 77 |
+
'support_sha256': support['sha256'], 'summary': unit['summary_path'],
|
| 78 |
+
'summary_sha256': sha(unit['summary_path'])})
|
| 79 |
+
return rows
|
| 80 |
+
|
| 81 |
+
def render(pretrain, strict, missing, provenance, api):
|
| 82 |
+
plt, colors = api.plt, api.COLORS
|
| 83 |
+
fig, axs = plt.subplots(3, 3, figsize=(7.09, 7.45), layout='constrained')
|
| 84 |
+
for ax, family, title in ((axs[0,0], 'architecture_floor1pct', 'A Architecture · 1% floor'),
|
| 85 |
+
(axs[0,1], 'panel_floor0.1pct', 'B Gene panel · 0.1% floor')):
|
| 86 |
+
for j, row in enumerate(r for r in pretrain if r['family'] == family):
|
| 87 |
+
ax.scatter(float(row['coverage']), float(row['precision']), s=23,
|
| 88 |
+
color=colors['real_R2_independent'] if row['method']=='real_R2_independent' else f'C{j%8}')
|
| 89 |
+
ax.annotate(row['method'].replace('real_R2_independent','Real R2'),
|
| 90 |
+
(float(row['coverage']),float(row['precision'])),xytext=(2,3),textcoords='offset points',fontsize=5.3)
|
| 91 |
+
ax.set(title=title, xlabel='Coverage', ylabel='Precision'); ax.grid(alpha=.15)
|
| 92 |
+
composition = ROOT/'source_data/ablation_pretrain_composition.csv'
|
| 93 |
+
ax=axs[0,2]
|
| 94 |
+
if composition.is_file():
|
| 95 |
+
receipt=read(ROOT/'source_data/ablation_pretrain_composition_receipt.json')
|
| 96 |
+
if receipt.get('schema')!='pbisc.fig2.ablation-composition.v1' or receipt.get('status')!='complete':
|
| 97 |
+
raise ValueError('pretraining composition is not complete')
|
| 98 |
+
expected=receipt['outputs']['ablation_pretrain_composition.csv']
|
| 99 |
+
if expected['path']!=str(composition) or expected['sha256']!=sha(composition):
|
| 100 |
+
raise ValueError('pretraining composition source hash differs')
|
| 101 |
+
for key in ('pc_receipt','pc_csv'):
|
| 102 |
+
entry=receipt['inputs'][key]
|
| 103 |
+
if sha(entry['path'])!=entry['sha256']:
|
| 104 |
+
raise ValueError('composition and P/C no longer share the same rescore inputs')
|
| 105 |
+
rr=api.records(composition)
|
| 106 |
+
keys=list(dict.fromkeys((r['family'],r['method']) for r in rr))
|
| 107 |
+
for j,(family,method) in enumerate(keys):
|
| 108 |
+
vals=[float(r['comp_l1']) for r in rr if r['family']==family and r['method']==method]
|
| 109 |
+
ax.scatter(np.full(len(vals),j),vals,s=3,alpha=.2,color='C0' if family.startswith('architecture') else 'C1')
|
| 110 |
+
ax.plot(j,np.mean(vals),'_',color='black',markersize=8)
|
| 111 |
+
ax.set_xticks(range(len(keys)),[m.replace('real_R2_independent','Real R2') for _,m in keys],rotation=90,fontsize=4.7)
|
| 112 |
+
ax.set(title='C Composition · separate sweeps',ylabel='Donor composition L1')
|
| 113 |
+
else:
|
| 114 |
+
api.pending(ax,'C Composition','Common-reference native pseudobulk composition rescoring pending.')
|
| 115 |
+
hist,proof=historical_rank_rows()
|
| 116 |
+
for j,r in enumerate(hist):
|
| 117 |
+
axs[1,0].scatter(r['coverage'],r['precision'],s=25,color=f'C{j}')
|
| 118 |
+
axs[1,0].annotate(r['label'],(r['coverage'],r['precision']),xytext=(2,3),textcoords='offset points',fontsize=5.3)
|
| 119 |
+
axs[1,1].bar(j,r['comp_l1'],color=f'C{j}')
|
| 120 |
+
axs[1,2].bar(j,r['trainable_parameters'],color=f'C{j}')
|
| 121 |
+
axs[1,0].set(title='D Real-bulk 5-fold quality',xlabel='Coverage',ylabel='Precision')
|
| 122 |
+
for ax,title,label in ((axs[1,1],'E Same folds · composition','Mean donor L1'),
|
| 123 |
+
(axs[1,2],'F Adapted parameters','Trainable parameters')):
|
| 124 |
+
ax.set(title=title,ylabel=label)
|
| 125 |
+
ax.set_xticks(range(4),[r['label'] for r in hist],rotation=40,ha='right',fontsize=5.5)
|
| 126 |
+
axs[1,2].set_yscale('log')
|
| 127 |
+
rows=strict_curve_rows(strict)
|
| 128 |
+
labels={'lora':'LoRA r=16','pairedcal':'Same-n calibration','scsemi':'scSemiProfiler','raw':'Raw (0 pairs)','refcal':'External ref-cal (0 pairs)'}
|
| 129 |
+
for ax,key,title in zip(axs[2],('precision','coverage','comp_l1'),('G Strict-n precision','H Strict-n coverage','I Strict-n composition')):
|
| 130 |
+
if not rows:
|
| 131 |
+
api.pending(ax,title,'Five outer folds × n=5, 10, 20, 40 pending.'); continue
|
| 132 |
+
for arm in ('lora','pairedcal','scsemi','raw','refcal'):
|
| 133 |
+
rr=[r for r in rows if r['arm']==arm]
|
| 134 |
+
if arm in ('raw','refcal'):
|
| 135 |
+
by_fold={r['fold']:float(r[key]) for r in rr}
|
| 136 |
+
if any(abs(float(r[key])-by_fold[r['fold']])>1e-10 for r in rr):
|
| 137 |
+
raise ValueError('zero-pair baseline differs across n within a fixed outer fold')
|
| 138 |
+
ax.axhline(np.mean(list(by_fold.values())),ls='--',color=colors[arm],label=labels[arm],lw=.9)
|
| 139 |
+
else:
|
| 140 |
+
ns=sorted({r['n_pairs'] for r in rr})
|
| 141 |
+
means=[]
|
| 142 |
+
for n in ns:
|
| 143 |
+
vv=[float(r[key]) for r in rr if r['n_pairs']==n];means.append(np.mean(vv))
|
| 144 |
+
ax.scatter([n]*len(vv),vv,s=7,alpha=.3,color=colors[arm])
|
| 145 |
+
ax.plot(ns,means,'o-',markersize=3,lw=.9,color=colors[arm],label=labels[arm])
|
| 146 |
+
ax.set(title=title,xlabel='Exact paired samples',ylabel='Composition L1' if key=='comp_l1' else key.capitalize())
|
| 147 |
+
ax.set_xticks([5,10,20,40]);ax.grid(alpha=.1)
|
| 148 |
+
if rows: axs[2,1].legend(fontsize=4.8,loc='best',frameon=False)
|
| 149 |
+
for ax in axs.flat:
|
| 150 |
+
ax.title.set_fontsize(7)
|
| 151 |
+
if len(strict) < 20:
|
| 152 |
+
fig.suptitle(f'Review preview · strict healthy units {len(strict)}/20; remaining results pending',fontsize=8,color='#963f29')
|
| 153 |
+
api.save(fig,'fig2_ablation_and_support')
|
| 154 |
+
api.write_csv(ROOT/'source_data/fig2_historical_rank_full.csv',hist,list(hist[0]))
|
| 155 |
+
(ROOT/'source_data/fig2_historical_rank_full_provenance.json').write_text(json.dumps({'schema':'pbisc.fig2.rank-realbulk.v1','selection':'quality-size balance; not best on every metric','arms':proof},indent=2)+'\n')
|
| 156 |
+
api.write_csv(ROOT/'source_data/fig2_strict_curve.csv',rows,
|
| 157 |
+
['design','fold','n_pairs','target_pairs_used','arm','precision','coverage','comp_l1','support_sha256','summary','summary_sha256'])
|
| 158 |
+
return {'strict_complete_units':len(strict),'strict_expected_units':20,'strict_missing':missing,
|
| 159 |
+
'historical_design':'historical_real_bulk_5fold_pooled107','historical_sources':hist,
|
| 160 |
+
'pretrain_composition_ready':composition.is_file(),
|
| 161 |
+
'pretrain_source':str(ROOT/'source_data/ablation_pretrain_pc.csv'),
|
| 162 |
+
'pretrain_source_sha256':sha(ROOT/'source_data/ablation_pretrain_pc.csv'),
|
| 163 |
+
'pretrain_receipt_sha256':sha(ROOT/'source_data/ablation_pretrain_pc_receipt.json')}
|