Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/bulk_compact.py +17 -0
- paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/downstream.py +91 -0
- paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/finalize.py +90 -0
- paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/pool_cv.py +23 -0
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/bulk_compact.py
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen annotation and all6k pseudobulks for new bulk-only generations."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys,os,json
|
| 4 |
+
import numpy as np
|
| 5 |
+
P=Path(__file__).resolve().parents[1];M=P.parents[1];F=M/'plans/paired_finetune_intradataset_20260927';B=M/'plans/bulkonly_lora5_20261006'
|
| 6 |
+
sys.path[:0]=[str(B/'tools'),str(F/'tools')]
|
| 7 |
+
import common as C
|
| 8 |
+
import ft_common as FCommon
|
| 9 |
+
cohort,draw,part=sys.argv[1:];folder=P/f'payload/bulkonly/{cohort}/draw{draw}/part{part}';path=folder/'generated.npz'
|
| 10 |
+
rec=json.loads(path.with_suffix('.log').read_text());assert C.sha(path)==rec['output_sha256'];ps=C.panel_setup(cohort)
|
| 11 |
+
with np.load(path,allow_pickle=False) as z:
|
| 12 |
+
assert np.array_equal(z['gene_ids'].astype(str),ps['panel']);samples=z['sample_ids'].astype(str)[z['bulk_index'].astype(int)]
|
| 13 |
+
X=FCommon.PR.poisson_integerise(np.ascontiguousarray(z['generated_counts'],dtype=np.float32),seed=FCommon.POISSON_SEED,chunk_rows=4096).tocsr()
|
| 14 |
+
ref,man=FCommon.load_reference(FCommon.CACHE_ROOT/cohort);pos={g:i for i,g in enumerate(ps['panel'])};qi=np.asarray([pos[g] for g in ref['query_ids'].astype(str)])
|
| 15 |
+
lab,info=FCommon.run_annotator(X[:,qi],ref['query_ids'].astype(str),samples,work=folder/'annotation',method='trunk4x_bulkonly',spec=FCommon.DATASETS[cohort],split='bulkonly',threads=4,annot=FCommon.annotator_run(),expected_zero_pad=man['gene_sets']['model_genes_missing_from_query'],source_note={'source':str(path),'source_sha256':rec['output_sha256'],'readout':'poisson','seed':FCommon.POISSON_SEED})
|
| 16 |
+
result=C.write_compact(folder/'compact',X,samples,lab,ps,{'dataset':cohort,'draw':int(draw),'part':int(part),'source':str(path),'source_sha256':rec['output_sha256'],'annotation':info,'readout':'whole part NPZ, native saved Poisson seed','clinical_metadata':str(B/f'analysis/features/{cohort}/meta.csv')})
|
| 17 |
+
(folder/'COMPACT.json').write_text(json.dumps(result,indent=2,default=str)+'\n')
|
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/downstream.py
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Execute the sealed same-gene-context matrix. No unchanged baseline training."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from datetime import datetime,timezone
|
| 4 |
+
import json,os,sys,shutil,subprocess
|
| 5 |
+
P=Path(__file__).resolve().parents[1];M=P.parents[1];S=M/'plans/paper_figures_strictpairs_20261012';F=M/'plans/paired_finetune_intradataset_20260927'
|
| 6 |
+
sys.path.insert(0,str(S/'tools'))
|
| 7 |
+
from runtime import Runtime,sha256,atomic_json
|
| 8 |
+
PY='/home/sj_server_1/miniforge3/envs/b2sc-cu130/bin/python';CPU='/home/sj_server_1/miniforge3/envs/cxg_corpus/bin/python'
|
| 9 |
+
def status(phase,**kw):atomic_json(P/'DOWNSTREAM_STATUS.json',{'phase':phase,'at':datetime.now(timezone.utc).isoformat(),**kw})
|
| 10 |
+
def safe_storage():
|
| 11 |
+
contract=json.loads((P/'CONTRACT.json').read_text())
|
| 12 |
+
for source,digest in {**contract['sources'],**contract['configs']}.items():assert sha256(Path(source))==digest,source
|
| 13 |
+
for source,digest in json.loads((P/'WORKFLOW_SEAL.json').read_text())['files'].items():assert sha256(Path(source))==digest,source
|
| 14 |
+
assert os.path.ismount(P/'payload'),'NAS unmounted; stop before falling back to local storage'
|
| 15 |
+
v=os.statvfs(P/'payload');assert v.f_bavail*v.f_frsize>120*2**30,'NAS free space below reserve'
|
| 16 |
+
def main():
|
| 17 |
+
matrix=json.loads((P/'MATRIX.json').read_text());verified=json.loads((P/'PRETRAIN_VERIFIED.json').read_text());safe_storage()
|
| 18 |
+
base=Path(verified['checkpoint']);assert sha256(base)==verified['checkpoint_sha256']
|
| 19 |
+
cache=P/'base_cache';cache.mkdir(exist_ok=True);local=cache/'checkpoint_epoch_016.pt'
|
| 20 |
+
if not local.exists():shutil.copyfile(base,local)
|
| 21 |
+
assert sha256(local)==verified['checkpoint_sha256'];base=local
|
| 22 |
+
rt=Runtime(P/'payload/runtime');parent_sha=verified['checkpoint_sha256']
|
| 23 |
+
def execute(tag,args,resource='cpu',inputs=(),outputs=(),mem=32):
|
| 24 |
+
safe_storage();rt.execute(tag,args,resource=resource,memory_gib=mem,threads=4,inputs=list(inputs),outputs=list(outputs))
|
| 25 |
+
def sample(tag,cp,condition,out,seed):
|
| 26 |
+
out.parent.mkdir(parents=True,exist_ok=True)
|
| 27 |
+
execute(tag,[PY,'-u',str(S/'tools/sample_one.py'),'--checkpoint',str(cp),'--checkpoint-sha',sha256(cp),'--condition',str(condition),'--output',str(out),'--seed',str(seed)],'gpu',[cp,condition,S/'tools/sample_one.py'],[out,out.with_suffix('.log')],48)
|
| 28 |
+
# Final E16 fixed before downstream outcomes. The SLE builder uses a namespace-local compatibility tag.
|
| 29 |
+
for row in matrix['sle']:
|
| 30 |
+
folder=P/f"payload/sle/seed{row['seed_index']}";g=folder/'generated_f016k_e16.npz';status('sle',seed=row['seed'])
|
| 31 |
+
sample('sle-'+str(row['seed_index']),base,M/'artifacts/gse135779_scsemi_split_target42_20260913/donor_conditions.npz',g,row['seed'])
|
| 32 |
+
execute('sle-score-'+str(row['seed_index']),[CPU,str(P/'tools/score_sle.py'),str(row['seed_index'])],inputs=[g,P/'tools/score_sle.py'],outputs=[folder/'DONE.json'])
|
| 33 |
+
# Unadapted/reference-calibrated outputs depend on the new pretrained checkpoint, so cannot reuse x1 cells.
|
| 34 |
+
for cohort in matrix['global_cohorts']:
|
| 35 |
+
for arm in ['raw','refcal']:
|
| 36 |
+
c=S/f'data/external_refcal/{cohort}/conditions_{arm}.npz';g=P/f'payload/global/{cohort}/{arm}.npz'
|
| 37 |
+
status('global_generation',cohort=cohort,arm=arm);sample('global-'+cohort+'-'+arm,base,c,g,20260928)
|
| 38 |
+
jobs=matrix['paired_jobs'];byid={j['id']:j for j in jobs}
|
| 39 |
+
# Canonical strict40 first, then historical full/rank CV, then additional legacy-donor supports.
|
| 40 |
+
for index,j in enumerate(jobs):
|
| 41 |
+
tag=j['id'].replace('/','-');out=Path(j['output']);out.mkdir(parents=True,exist_ok=True);status('paired',job=j['id'],index=index,total=len(jobs))
|
| 42 |
+
if j.get('adapter_alias'):
|
| 43 |
+
alias=byid[j['adapter_alias']];run=Path(alias['output'])/'run'
|
| 44 |
+
r=json.loads((run/'RUN.json').read_text());assert set(r['train_rows'])==set(j['train_samples']) and set(r['test_rows_never_loaded_for_training'])==set(j['test_samples'])
|
| 45 |
+
atomic_json(out/'ADAPTER_ALIAS.json',{'source_run':str(run),'checkpoint_sha256':r['checkpoint_sha256'],'reason':'identical support/test, seed, fixed3000 schedule and exact same f01x4 parent; do not train twice'})
|
| 46 |
+
else:
|
| 47 |
+
run=out/'run';ds=F/f"data/{j['cohort']}"
|
| 48 |
+
if j['family']!='strict':
|
| 49 |
+
execute(tag+'-isolate',[CPU,str(P/'tools/prepare_legacy.py'),j['id']],inputs=[P/'MATRIX.json',ds/'cells_panel6k.npz',ds/'folds.csv',P/'tools/prepare_legacy.py'],outputs=[out/'input'/j['cohort']/'ISOLATION.json'])
|
| 50 |
+
ds=out/'input'/j['cohort']
|
| 51 |
+
cmd=[PY,'-u',str(F/'tools/ft_sdd.py'),'--checkpoint',str(base),'--checkpoint-sha',parent_sha,'--dataset-dir',str(ds),'--condition-npz',j['condition'],'--fold',str(j.get('fold',0)),'--mode',j['mode'],'--lora-rank',str(j['rank']),'--lora-alpha',str(j['alpha']),'--lr',str(j['lr']),'--warmup',str(j['warmup']),'--batch-size',str(j['batch_size']),'--ema-decay',str(j['ema_decay']),'--seed',str(j['seed']),'--max-cuda-gib','24','--min-system-gib','32','--out-dir',str(run)]
|
| 52 |
+
if j['fixed_steps']:cmd+=['--fixed-steps',str(j['fixed_steps'])]
|
| 53 |
+
if j['family']=='strict':cmd+=['--support-manifest',j['support_path']]
|
| 54 |
+
elif j['family']=='legacy5':cmd+=['--train-donors-file',str(ds/'train_donors.txt')]
|
| 55 |
+
else:cmd+=['--max-steps',str(j['max_steps']),'--eval-every',str(j['eval_every']),'--patience',str(j['patience'])]
|
| 56 |
+
execute(tag+'-train',cmd,'gpu',[base,P/'MATRIX.json',Path(j['condition']),ds/'cells_panel6k.npz',F/'tools/ft_sdd.py'],[run/'RUN.json',run/'checkpoint_ft.pt'],64)
|
| 57 |
+
r=json.loads((run/'RUN.json').read_text());assert r['source_checkpoint_sha256']==parent_sha;assert set(r['train_rows'])==set(j['train_samples']);assert set(r['inner_val_rows'])==set(j['validation_samples']);assert set(r['test_rows_never_loaded_for_training'])==set(j['test_samples'])
|
| 58 |
+
if j.get('generation_alias'):
|
| 59 |
+
alias=byid[j['generation_alias']]
|
| 60 |
+
for ext in ['.npz','.log']:
|
| 61 |
+
dst=out/('generated'+ext)
|
| 62 |
+
if not dst.exists():dst.symlink_to(Path(alias['output'])/('generated'+ext))
|
| 63 |
+
atomic_json(out/'GENERATION_ALIAS.json',{'source':alias['output'],'proof':str(P/'GENERATION_REUSE_PROOF.json')})
|
| 64 |
+
else:sample(tag+'-generate',run/'checkpoint_ft.pt',Path(j['test_condition']),out/'generated.npz',j['sampling_seed'])
|
| 65 |
+
if j['family']=='strict':sample(tag+'-pairedcal',base,Path(j['cal_condition']),out/'pairedcal.npz',20260928)
|
| 66 |
+
if j.get('generation_alias'):
|
| 67 |
+
dest=out/'evaluation'
|
| 68 |
+
if not dest.exists():dest.symlink_to(Path(byid[j['generation_alias']]['output'])/'evaluation',target_is_directory=True)
|
| 69 |
+
atomic_json(out/'EVALUATION_ALIAS.json',{'source':str(dest.resolve()),'reason':'Same generated cells, test donors and scoring contract; reuse exact strict Sepsis metrics.'})
|
| 70 |
+
else:execute(tag+'-score',[CPU,str(P/'tools/score_paired.py'),j['id']],inputs=[out/'generated.npz',P/'MATRIX.json',P/'tools/score_paired.py'],outputs=[out/'evaluation/DONE.json'])
|
| 71 |
+
# CV metrics must be scored on the same pooled held-out donors, not averaged fold P/C.
|
| 72 |
+
execute('pool-cv-and-score',[CPU,str(P/'tools/pool_cv.py')],inputs=[P/'MATRIX.json',P/'tools/pool_cv.py'],outputs=[P/'payload/pooled/DONE.json'])
|
| 73 |
+
# Published bulk-only condition files are reused; matching legacy-donor adaptation is explicit.
|
| 74 |
+
for cohort in matrix['bulkonly_cohorts']:
|
| 75 |
+
B=M/'plans/bulkonly_lora5_20261006/data'/cohort
|
| 76 |
+
conditions=sorted(B.glob('bulkonly_raw_part*.npz')) or [B/'bulkonly_raw.npz']
|
| 77 |
+
for draw in range(5):
|
| 78 |
+
j=byid[f'legacy5/{cohort}/draw{draw}'];source=byid[j['adapter_alias']] if j.get('adapter_alias') else j;cp=Path(source['output'])/'run/checkpoint_ft.pt'
|
| 79 |
+
for part,condition in enumerate(conditions):
|
| 80 |
+
dest=P/f'payload/bulkonly/{cohort}/draw{draw}/part{part}/generated.npz';status('bulkonly',cohort=cohort,draw=draw,part=part)
|
| 81 |
+
sample(f'bulk-{cohort}-{draw}-{part}',cp,condition,dest,20260927)
|
| 82 |
+
execute(f'bulk-compact-{cohort}-{draw}-{part}',[CPU,str(P/'tools/bulk_compact.py'),cohort,str(draw),str(part)],inputs=[dest,P/'tools/bulk_compact.py'],outputs=[dest.parent/'COMPACT.json'])
|
| 83 |
+
execute('assemble-comparisons',[CPU,str(P/'tools/finalize.py')],inputs=[P/'MATRIX.json',P/'tools/finalize.py'],outputs=[P/'RESULTS_STATUS.json'])
|
| 84 |
+
result=json.loads((P/'RESULTS_STATUS.json').read_text());status(result['phase'],result=str(P/'RESULTS_STATUS.json'))
|
| 85 |
+
try:
|
| 86 |
+
execute('archive-completed',["/home/sj_server_1/miniforge3/bin/python",str(P/'tools/archive_completed.py')],inputs=[P/'RESULTS_STATUS.json',P/'tools/archive_completed.py'],outputs=[P/'FINAL_ARCHIVE.json'],mem=4)
|
| 87 |
+
except Exception as e:
|
| 88 |
+
status('data_complete_archive_pending',result=str(P/'RESULTS_STATUS.json'),error=str(e))
|
| 89 |
+
if __name__=='__main__':
|
| 90 |
+
try:main()
|
| 91 |
+
except BaseException as e:status('stopped_needs_inspection',error=str(e));raise
|
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/finalize.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Collect paired comparisons without regenerating x1/comparator outputs."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,sys,subprocess,shlex
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
P=Path(__file__).resolve().parents[1];M=P.parents[1];F=M/'plans/paired_finetune_intradataset_20260927';S=M/'plans/paper_figures_strictpairs_20261012';sys.path.insert(0,str(S/'tools'))
|
| 7 |
+
from donor_statistics import paired_donor_bootstrap
|
| 8 |
+
from runtime import sha256
|
| 9 |
+
jobs=json.loads((P/'MATRIX.json').read_text())['paired_jobs'];rows=[];pending=[];long=[]
|
| 10 |
+
def obtain(path):
|
| 11 |
+
if path.is_file():return path
|
| 12 |
+
out=P/'payload/baseline_metadata'/path.relative_to(M);out.parent.mkdir(parents=True,exist_ok=True)
|
| 13 |
+
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=10','spark-0110','cat '+shlex.quote(str(path))],capture_output=True)
|
| 14 |
+
if result.returncode:return None
|
| 15 |
+
out.write_bytes(result.stdout);return out
|
| 16 |
+
|
| 17 |
+
def compatible(a,b):
|
| 18 |
+
return a['reference']['reference_sha256']==b['reference']['reference_sha256'] and set(a['donors'])==set(b['donors']) and a['contrast_definition']==b['contrast_definition'] and a.get('gene_exclusion')==b.get('gene_exclusion')
|
| 19 |
+
def record(j,arm,v,source):
|
| 20 |
+
c=v.get('contrast',{}).get('mean_cp10k',{})
|
| 21 |
+
rows.append({'job':j['id'],'family':j['family'],'budget':json.loads(Path(j['support_path']).read_text())['n_pairs'] if j.get('support_path') else None,'cohort':j['cohort'],'arm':arm,'logfc_r':c.get('mean_r_generated'),'partial_r':c.get('mean_partial_r'),'deg_overlap':v.get('deg_top50',{}).get('sum'),'composition_l1':v['composition']['l1_mean'],'precision':v['precision_coverage']['precision'],'coverage':v['precision_coverage']['coverage'],'expression_r':v['pseudobulk']['r_median'],'source':str(source),'source_sha256':sha256(source)})
|
| 22 |
+
for j in jobs:
|
| 23 |
+
p=Path(j['output'])/'evaluation/score/summary.json';s=json.loads(p.read_text());record(j,'trunk4x',s['per_arm']['trunk4x'],p)
|
| 24 |
+
if not j.get('baseline_score'):continue
|
| 25 |
+
bp=obtain(Path(j['baseline_score']))
|
| 26 |
+
if bp is None:pending.append({'job':j['id'],'reason':'Existing x1 score not yet available','path':j['baseline_score']});continue
|
| 27 |
+
b=json.loads(bp.read_text())
|
| 28 |
+
if not compatible(s,b):pending.append({'job':j['id'],'reason':'Baseline score contract differs; reuse generated output for a matched CPU rescore, never retrain','path':str(bp)});continue
|
| 29 |
+
candidates=['lora','lora5','real_lora__raw']
|
| 30 |
+
key=next((x for x in candidates if x in b['per_arm']),None)
|
| 31 |
+
if key is None:pending.append({'job':j['id'],'reason':'Baseline arm mapping unresolved'});continue
|
| 32 |
+
record(j,'current_x1',b['per_arm'][key],bp)
|
| 33 |
+
if 'scsemi' in b['per_arm']:record(j,'scsemi',b['per_arm']['scsemi'],bp)
|
| 34 |
+
if j['family']=='strict':
|
| 35 |
+
sup=json.loads(Path(j['support_path']).read_text());budget=sup['n_pairs'];mapping=dict(zip(sup['test_sample_ids'],sup['test_donor_ids']))
|
| 36 |
+
oldcsv=obtain(Path(j['baseline_score']).parent/'per_donor.csv')
|
| 37 |
+
if oldcsv is None:continue
|
| 38 |
+
for path,oldarm,newarm in [(p.parent/'per_donor.csv','trunk4x','trunk4x'),(oldcsv,key,'current_x1')]:
|
| 39 |
+
d=pd.read_csv(path);d=d[d.arm==oldarm].copy();d['arm']=newarm;d['draw']=sup['unit'];d['sample_id']=d['donor'].astype(str);d['donor_id']=d.sample_id.map(mapping);assert d.donor_id.notna().all();d['cohort']=j['cohort'];d['budget']=budget;long.append(d)
|
| 40 |
+
# Pooled CV is compared to an exactly matching original pooled arm, never a mean of fold-level P/C.
|
| 41 |
+
for cohort,arm in sorted({(j['cohort'],j['old_arm']) for j in jobs if j['family']=='cv'}):
|
| 42 |
+
p=P/f'payload/pooled/{cohort}/{arm}/score/summary.json';s=json.loads(p.read_text());j={'id':f'pooled/{cohort}/{arm}','family':'pooled_cv','cohort':cohort};record(j,'trunk4x',s['per_arm']['trunk4x'],p)
|
| 43 |
+
found=False
|
| 44 |
+
for bp in (F/f'scores/{cohort}').glob('**/summary.json'):
|
| 45 |
+
if 'pooled' not in str(bp):continue
|
| 46 |
+
try:b=json.loads(bp.read_text())
|
| 47 |
+
except ValueError:continue
|
| 48 |
+
key=arm+'__raw'
|
| 49 |
+
if key in b.get('per_arm',{}) and compatible(s,b):record(j,'current_x1',b['per_arm'][key],bp);found=True;break
|
| 50 |
+
if not found:pending.append({'job':j['id'],'reason':'Matching pooled x1 summary not located; preserve new pooled output and require source-bound comparison'})
|
| 51 |
+
D=P/'comparison';D.mkdir(exist_ok=True);table=pd.DataFrame(rows);table.to_csv(D/'metrics.csv',index=False)
|
| 52 |
+
ci=[]
|
| 53 |
+
if long:
|
| 54 |
+
long=pd.concat(long,ignore_index=True);long.to_csv(D/'donor_metrics.csv',index=False)
|
| 55 |
+
for (cohort,budget),part in long.groupby(['cohort','budget']):
|
| 56 |
+
for metric in ['comp_l1','precision','coverage','pb_r']:
|
| 57 |
+
c=paired_donor_bootstrap(part.rename(columns={metric:'value'}),'trunk4x','current_x1',n_boot=2000,seed=20261013);c.update(cohort=cohort,budget=int(budget),metric=metric);ci.append(c)
|
| 58 |
+
pd.DataFrame(ci).to_csv(D/'paired_donor_ci.csv',index=False)
|
| 59 |
+
# Keep measured cost and every broad cell type, including adverse results.
|
| 60 |
+
cost=[]
|
| 61 |
+
for j in jobs:
|
| 62 |
+
if j.get('adapter_alias'):continue
|
| 63 |
+
rp=Path(j['output'])/'run/RUN.json';r=json.loads(rp.read_text())
|
| 64 |
+
cost.append({'job':j['id'],'cohort':j['cohort'],'family':j['family'],'mode':r['mode'],'steps_run':r['steps_run'],'selected_step':r['selected_step'],'trainable_parameters':r['trainable']['n_trainable'],'base_parameters':r['trainable']['n_total_base'],'wall_seconds':r['wall_seconds'],'source':str(rp),'timing_scope':'observed run walltime, not a controlled speed microbenchmark'})
|
| 65 |
+
pd.DataFrame(cost).to_csv(D/'adaptation_cost.csv',index=False)
|
| 66 |
+
ct=[]
|
| 67 |
+
if isinstance(long,pd.DataFrame):
|
| 68 |
+
for (cohort,budget,arm),q in long.groupby(['cohort','budget','arm']):
|
| 69 |
+
if cohort!='immicro':continue
|
| 70 |
+
for typ in ['T cell','B cell','Monocyte','NK cell','DC','Other']:
|
| 71 |
+
a=q['obs_'+typ].to_numpy();b=q['gen_'+typ].to_numpy()
|
| 72 |
+
ct.append({'budget':int(budget),'arm':arm,'cell_type':typ,'n_donors':q.donor_id.nunique(),'pearson_r':float(np.corrcoef(a,b)[0,1]) if np.std(a)>0 and np.std(b)>0 else None,'mae_percentage_points':float(np.abs(a-b).mean()*100)})
|
| 73 |
+
pd.DataFrame(ct).to_csv(D/'healthy_all_celltypes.csv',index=False)
|
| 74 |
+
import matplotlib
|
| 75 |
+
matplotlib.use('Agg')
|
| 76 |
+
import matplotlib.pyplot as plt
|
| 77 |
+
plt.rcParams.update({'font.family':'sans-serif','font.sans-serif':['Arial','Liberation Sans'],'font.size':11,'axes.spines.top':False,'axes.spines.right':False,'pdf.fonttype':42})
|
| 78 |
+
colors={'trunk4x':'#168FE5','current_x1':'#0D6EA8','scsemi':'#83C6A8'}
|
| 79 |
+
for (cohort,budget),t in table[table.family=='strict'].groupby(['cohort','budget']):
|
| 80 |
+
fig,axes=plt.subplots(2,3,figsize=(12.3,6.3))
|
| 81 |
+
for ax,col in zip(axes.flat,['logfc_r','partial_r','deg_overlap','composition_l1','precision','coverage']):
|
| 82 |
+
for k,(arm,d) in enumerate(t.groupby('arm',sort=True)):
|
| 83 |
+
vals=pd.to_numeric(d[col],errors='coerce').dropna().to_numpy();ax.scatter(np.full(len(vals),k),vals,color=colors[arm],s=20,alpha=.6)
|
| 84 |
+
if len(vals):ax.plot([k-.17,k+.17],[vals.mean()]*2,color=colors[arm],lw=3)
|
| 85 |
+
ax.set_xticks(range(t.arm.nunique()),sorted(t.arm.unique()),rotation=15,ha='right');ax.set_title(col)
|
| 86 |
+
fig.suptitle(cohort+f' · {int(budget)} support pairs · exact-panel comparison');fig.text(.5,.015,'Support/fold points are descriptive, not independent replicates. Each panel holds the support budget fixed; use paired donor CI tables for uncertainty.',ha='center',fontsize=8);fig.tight_layout(rect=(0,.05,1,.95))
|
| 87 |
+
for ext in ['png','pdf','svg']:fig.savefig(D/f'{cohort}_n{int(budget)}.{ext}',dpi=180)
|
| 88 |
+
plt.close(fig)
|
| 89 |
+
(P/'PENDING_EVIDENCE.json').write_text(json.dumps({'comparison_gaps':pending,'rare_identity':'Author fine-cluster annotation/treatment-time alignment required; new marker caches are not proof of population recovery.','bulkonly_reproduction':'New all6k celltype pseudobulks/markers ready; exact original-paper clinical contrast and paired-reference validation remain required.','legacy_K4000':'Not silently substituted with K1000 adapters. A separate matched training/condition contract is needed before that sensitivity is executed.'},indent=2)+'\n')
|
| 90 |
+
(P/'RESULTS_STATUS.json').write_text(json.dumps({'phase':'data_complete_with_review_gates','paired_jobs':len(jobs),'new_adapters':sum(not j.get('adapter_alias') for j in jobs),'comparison_rows':len(rows),'unresolved_comparisons':len(pending),'tables':str(D),'manuscript_or_deck_overwritten':False,'biological_claims_confirmed':False},indent=2)+'\n')
|
paper-releases/pbisc-diffusion/updates/20261013T144247Z-f01-trunk4x-campaign-launch/diffusion/dataset/server_1/model8/plans/f01_trunk4x_complete_20261013/tools/pool_cv.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reuse exact historical fold-pooling arithmetic within a new isolated namespace."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import os,sys,json
|
| 4 |
+
P=Path(__file__).resolve().parents[1];M=P.parents[1];F=M/'plans/paired_finetune_intradataset_20260927';sys.path.insert(0,str(F/'tools'))
|
| 5 |
+
import pool_folds as PO
|
| 6 |
+
import score_ft as FT
|
| 7 |
+
jobs=json.loads((P/'MATRIX.json').read_text())['paired_jobs'];workspace=P/'payload/pool_workspace';PO.TASK=workspace
|
| 8 |
+
pairs=sorted({(j['cohort'],j['old_arm']) for j in jobs if j['family']=='cv'})
|
| 9 |
+
groups={'ye2026_sepsis':('adult_sepsis,ped_sepsis','adult_HC,adult_ICU_ctrl,ped_HC,ped_ICU_ctrl'),'imperial_eskd':('covid_positive','covid_negative'),'giroux2022':('severe','mild'),'ji2025_chili':('TOL,FU1','BC,AC')}
|
| 10 |
+
for cohort,arm in pairs:
|
| 11 |
+
for j in [x for x in jobs if x['family']=='cv' and x['cohort']==cohort and x['old_arm']==arm]:
|
| 12 |
+
d=workspace/f"generated/{cohort}/fold{j['fold']}";d.mkdir(parents=True,exist_ok=True)
|
| 13 |
+
for suffix in ['.npz','.log']:
|
| 14 |
+
dest=d/(arm+'__raw'+suffix);source=Path(j['output'])/('generated'+suffix)
|
| 15 |
+
if not dest.exists():dest.symlink_to(source)
|
| 16 |
+
dest=workspace/f"data/{cohort}/fold{j['fold']}";dest.parent.mkdir(parents=True,exist_ok=True)
|
| 17 |
+
if not dest.exists():dest.symlink_to(F/f"data/{cohort}/fold{j['fold']}",target_is_directory=True)
|
| 18 |
+
out=P/f'payload/pooled/{cohort}/{arm}';PO.main([cohort,'--arms',arm+'__raw','--out',str(out)])
|
| 19 |
+
argv=['--dataset',cohort,'--out',str(out/'score'),'--arm',f'trunk4x={out}/{arm}__raw.npz','--threads','4']
|
| 20 |
+
if cohort in groups:argv+=['--case-groups',groups[cohort][0],'--control-groups',groups[cohort][1]]
|
| 21 |
+
else:argv+=['--no-contrast','--no-deg']
|
| 22 |
+
FT.main(argv)
|
| 23 |
+
(P/'payload/pooled/DONE.json').write_text(json.dumps({'pooled_groups':pairs,'folds_per_group':5,'one_heldout_prediction_per_donor':True},indent=2)+'\n')
|