Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/build_strengthened_master_20261013.py +150 -0
- paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/strengthen_corpus_20261013.py +318 -0
- paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/strengthen_disease_metrics_20261013.py +354 -0
- paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/strengthen_healthy_adaptation_20261013.py +229 -0
paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/build_strengthened_master_20261013.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Expand the verified 142-page master with source-bound strengthening panels."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
from collections import defaultdict
|
| 4 |
+
from datetime import datetime, timezone
|
| 5 |
+
import copy
|
| 6 |
+
import csv
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import sys
|
| 12 |
+
if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
|
| 13 |
+
raise SystemExit('CPU-only deck build requires empty CUDA_VISIBLE_DEVICES')
|
| 14 |
+
D = Path(__file__).resolve().parents[1]
|
| 15 |
+
A = D / 'data/strengthening_20261013'
|
| 16 |
+
PARENT = D/'data/celltypes_palette_master_20261013/spec.json'
|
| 17 |
+
OUT = 'PBISC-Diffusion_expanded_master_20261013_strengthened'
|
| 18 |
+
sys.path[:0] = [str(D), str(D/'tools')]
|
| 19 |
+
import generate_deck as G
|
| 20 |
+
from reorder_master_figures_20261013 import draw_card, draw_note
|
| 21 |
+
from pptx import Presentation
|
| 22 |
+
from pptx.util import Inches
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def sha(path):
|
| 26 |
+
with Path(path).open('rb') as f:
|
| 27 |
+
return hashlib.file_digest(f, 'sha256').hexdigest()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def normalized(slide, family, index):
|
| 31 |
+
s = copy.deepcopy(slide)
|
| 32 |
+
group = s.get('deck_group') or s.get('section') or {'corpus':'Figure 1','healthy':'Figure 3',
|
| 33 |
+
'disease_metrics':'Figure 4','rare_literature':'Figure 5'}[family]
|
| 34 |
+
s.update(deck_group=group, section=group, addition_key=f'strengthening:{family}:{index}')
|
| 35 |
+
if family=='rare_literature' and index==1:s['title']='Ye sepsis: published markers in paired scRNA'
|
| 36 |
+
if family=='rare_literature' and index==2:s['title']='Transcriptional programs and rare-population identity'
|
| 37 |
+
s.setdefault('kind', 'content');s.setdefault('layout','full');s.setdefault('keywords',[])
|
| 38 |
+
s.setdefault('section_label',group)
|
| 39 |
+
if 'figure' in s and not s.get('figures'):s['figures']=[s['figure']]
|
| 40 |
+
s['figures']=[str(Path(p).relative_to(D)) if Path(p).is_absolute() else p for p in s.get('figures',[])]
|
| 41 |
+
s.setdefault('footnote',s.get('note',''))
|
| 42 |
+
s.setdefault('footnote_full',s.get('note',s['footnote']))
|
| 43 |
+
s.setdefault('sources','; '.join(s.get('source_refs',[])))
|
| 44 |
+
if isinstance(s['sources'],list):s['sources']='; '.join(x['path'] if isinstance(x,dict) else x for x in s['sources'])
|
| 45 |
+
return s
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main():
|
| 49 |
+
parent=json.loads(PARENT.read_text())['slides']
|
| 50 |
+
assert len(parent)==142
|
| 51 |
+
parent_manifest=json.loads((PARENT.parent/'manifest.json').read_text())
|
| 52 |
+
for s in parent:
|
| 53 |
+
for f in s.get('figures',[]):
|
| 54 |
+
p=str(D/f);assert sha(p)==parent_manifest['sources'][p]['sha256'],p
|
| 55 |
+
results={f:json.loads((A/f/'result.json').read_text()) for f in ['corpus','healthy','disease_metrics','rare_literature']}
|
| 56 |
+
added={f:[normalized(s,f,i) for i,s in enumerate(r['slides'])] for f,r in results.items()}
|
| 57 |
+
slides=[];held_corpus=None
|
| 58 |
+
for n,ss in enumerate(parent,1):
|
| 59 |
+
s=copy.deepcopy(ss);s['parent_142_page']=n
|
| 60 |
+
if n==9:s['footnote_full']=s.get('footnote_full','').replace('target once','target at least once')
|
| 61 |
+
if n==8:
|
| 62 |
+
# Full old chart remains available in supplementary; the main text
|
| 63 |
+
# now uses the requested explicit two-level condition classification.
|
| 64 |
+
s.update(deck_group='Supp S01',section='Supp S01',section_label='Supp. S01',
|
| 65 |
+
title='Corpus reference: assay and source composition')
|
| 66 |
+
s['keywords']=[]
|
| 67 |
+
s['footnote']='Original corpus overview. Healthy 88.5% is a cell share; the revised condition detail is in Figure 1.'
|
| 68 |
+
s['footnote_full']=s['footnote']+'\n'+s.get('footnote_full','')
|
| 69 |
+
held_corpus=s
|
| 70 |
+
slides.extend(added['corpus'])
|
| 71 |
+
continue
|
| 72 |
+
if s['deck_group']=='Supp S01' and held_corpus is not None:
|
| 73 |
+
slides.append(held_corpus);held_corpus=None
|
| 74 |
+
slides.append(s)
|
| 75 |
+
if n==28:slides.extend(added['healthy'][:2])
|
| 76 |
+
if n==30:slides.extend(added['healthy'][2:])
|
| 77 |
+
if n==40:slides.extend(x for x in added['disease_metrics'] if not x['deck_group'].startswith('Supp'))
|
| 78 |
+
if n==42:slides.extend(added['rare_literature'])
|
| 79 |
+
if n==110:slides.extend(x for x in added['disease_metrics'] if x['deck_group'].startswith('Supp'))
|
| 80 |
+
assert held_corpus is None
|
| 81 |
+
assert len(slides)==142+sum(map(len,added.values()))
|
| 82 |
+
assert sorted(s['parent_142_page'] for s in slides if 'parent_142_page' in s)==list(range(1,143))
|
| 83 |
+
assert sorted(s['original_slide'] for s in slides if 'original_slide' in s)==list(range(1,77))
|
| 84 |
+
mapping={s['parent_142_page']:n for n,s in enumerate(slides,1) if 'parent_142_page' in s}
|
| 85 |
+
groups=defaultdict(list)
|
| 86 |
+
for n,s in enumerate(slides,1):groups[s['deck_group']].append(n)
|
| 87 |
+
for s in slides:
|
| 88 |
+
if s.get('kind')=='plan_card':
|
| 89 |
+
s['rows']=[(h,b,re.sub(r'\d+',lambda m:str(mapping[int(m.group())]),p) if re.match(r'^pp?\.',p) else p)
|
| 90 |
+
for h,b,p in s['rows']]
|
| 91 |
+
byold={s['source_page_131']:s for s in slides if s.get('source_page_131')}
|
| 92 |
+
byold[1]['subtitle']=f'{len(slides)} slides | Corpus detail, held-out adaptation, disease metrics and paper-grounded rare targets'
|
| 93 |
+
newpages={family:[n for n,s in enumerate(slides,1) if s.get('addition_key','').startswith('strengthening:'+family+':')]
|
| 94 |
+
for family in added}
|
| 95 |
+
c=newpages['corpus'];h=newpages['healthy'];di=newpages['disease_metrics'];r=newpages['rare_literature']
|
| 96 |
+
byold[7]['rows']=[('1a','Experimental overview',f'p. {mapping[7]}'),
|
| 97 |
+
('1b','Healthy / disease-at-risk, detailed conditions and cell types',f'p. {c[0]}'),
|
| 98 |
+
('1c','41.4M corpus to 33.1M training: split and K recipes','pp. '+', '.join(map(str,c[1:]))),
|
| 99 |
+
('1d','Recorded noise-to-cell PCA stages',f'p. {mapping[10]}')]
|
| 100 |
+
byold[7]['footnote']='Cell shares, split allocation and recipe exposure have distinct denominators. K does not exclude 8.25M cells.'
|
| 101 |
+
byold[53]['rows']=[('3a','Expression mismatch; same-donor output recovery','pp. '+', '.join(map(str,[mapping[26],mapping[27],*h[:2]]))),
|
| 102 |
+
('3b','Full FT and LoRA ranks','pp. '+', '.join(map(str,[mapping[29],mapping[30]]))),
|
| 103 |
+
('3c','Fixed test, random nested support and all six types','pp. '+', '.join(map(str,[h[2],mapping[31],mapping[32]]))),
|
| 104 |
+
('3d','Genuine total-five comparison','pp. '+', '.join(map(str,[mapping[33],mapping[34]])))]
|
| 105 |
+
byold[61]['rows']=[('4a','Disease contrasts: five-support and five-fold','pp. '+', '.join(map(str,[mapping[37],mapping[38]]))),
|
| 106 |
+
('4b','Complete CV-CAT, including scSemiProfiler',f'p. {di[0]}'),
|
| 107 |
+
('4c','LogFC / partial correlation / RBO',f'p. {di[1]}'),
|
| 108 |
+
('4d','Strict Sepsis: five support draws and donor-aware DEG',f'p. {di[2]}'),
|
| 109 |
+
('4e','Deconvolution comparator endpoints',f'p. {mapping[40]}')]
|
| 110 |
+
byold[61]['footnote']='Paired disease benchmarks: pooled historical CV and strict five-support results remain separate; observed controls are cell resampling, not donor ceilings.'
|
| 111 |
+
byold[87]['rows']=[('5a','Original-paper targets and observed-truth gates','pp. '+', '.join(map(str,r))),
|
| 112 |
+
('5b','Ye: pediatric pulmonary cycling monocytes','Observed marker diagnostic; exact cluster TODO'),
|
| 113 |
+
('5c','Imperial: wave2 steroid-associated monocytes','Match steroid timing and fine labels: TODO'),
|
| 114 |
+
('Gate','Giroux/Ji: verify a paper-reported rare target first','No forced rare-population claim')]
|
| 115 |
+
byold[87]['footnote']='Observed marker diagnostics are not completed author-cluster reproduction. Matched observed/PBISC/scSemi identity panels remain the next analysis.'
|
| 116 |
+
for key in [7,53,61,87]:byold[key]['footnote_full']=byold[key]['footnote']
|
| 117 |
+
for s in slides:
|
| 118 |
+
if s.get('kind')=='plan_card' and s.get('source_page_131')==109:
|
| 119 |
+
s['rows']=[(a,b,f'pp. {min(groups["Supp S03"])}-{max(groups["Supp S06"])}' if a=='S03-S06' else c) for a,b,c in s['rows']]
|
| 120 |
+
prs=Presentation();prs.slide_width=Inches(G.SLIDE_W);prs.slide_height=Inches(G.SLIDE_H)
|
| 121 |
+
funcs={'title':G.build_title,'agenda':G.build_agenda,'divider':G.build_divider,'content':G.build_content,
|
| 122 |
+
'plan_card':draw_card,'evidence_note':draw_note}
|
| 123 |
+
for n,s in enumerate(slides,1):
|
| 124 |
+
fn=funcs[s['kind']];fn(prs,s) if s['kind']=='title' else fn(prs,s,n)
|
| 125 |
+
prs.save(D/(OUT+'.pptx'))
|
| 126 |
+
(A/'spec.json').write_text(json.dumps({'deck':{'output_pptx':OUT+'.pptx','output_pdf':OUT+'.pdf'},'slides':slides},indent=2)+'\n')
|
| 127 |
+
rows=[dict(page=n,parent_142_page=s.get('parent_142_page',''),original_76_page=s.get('original_slide',''),
|
| 128 |
+
group=s['deck_group'],title=s['title'],addition=s.get('addition_key','')) for n,s in enumerate(slides,1)]
|
| 129 |
+
with (A/'page_map.csv').open('w',newline='',encoding='utf-8-sig') as f:
|
| 130 |
+
writer=csv.DictWriter(f,fieldnames=list(rows[0]));writer.writeheader();writer.writerows(rows)
|
| 131 |
+
inputs={str(p):{'sha256':sha(p)} for p in [PARENT,Path(__file__),D/'generate_deck.py',D/'tools/reorder_master_figures_20261013.py',
|
| 132 |
+
D/'PBISC-Diffusion_color_palette_20261013.md',*[A/f/'result.json' for f in added]]}
|
| 133 |
+
for s in slides:
|
| 134 |
+
for f in s.get('figures',[]):inputs[str(D/f)]={'sha256':sha(D/f)}
|
| 135 |
+
for family,result in results.items():
|
| 136 |
+
for src in result.get('sources',[]):
|
| 137 |
+
if isinstance(src,dict) and 'path' in src and 'sha256' in src:
|
| 138 |
+
assert sha(src['path'])==src['sha256'],(family,src['path'])
|
| 139 |
+
inputs[src['path']]={'sha256':src['sha256']}
|
| 140 |
+
protected={str(p):sha(p) for p in [PARENT,D/'PBISC-Diffusion_expanded_master_20261013_celltypes_palette.pptx',
|
| 141 |
+
D/'PBISC-Diffusion_expanded_master_20261013_celltypes_palette.pdf']}
|
| 142 |
+
manifest=dict(schema='pbisc.strengthening.master.v1',created_at=datetime.now(timezone.utc).isoformat(),
|
| 143 |
+
total_slides=len(slides),parent_pages=142,original_pages=76,newpages=newpages,groups=dict(groups),
|
| 144 |
+
sources=inputs,protected_sources=protected,slides=slides,new_training=False,new_inference=False,
|
| 145 |
+
parent_spec=str(PARENT),output={'pptx':{'path':str(D/(OUT+'.pptx')),'sha256':sha(D/(OUT+'.pptx'))}})
|
| 146 |
+
(A/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
|
| 147 |
+
print(json.dumps({'pages':len(slides),'newpages':newpages,'groups':dict(groups)}))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
if __name__=='__main__':main()
|
paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/strengthen_corpus_20261013.py
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Figure 1 corpus and recipe clarification from saved small metadata only.
|
| 3 |
+
|
| 4 |
+
No expression arrays, model imports, new sampling, training, or inference.
|
| 5 |
+
All writes are confined to the dedicated strengthening/corpus directories.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import ast
|
| 10 |
+
from collections import Counter
|
| 11 |
+
import csv
|
| 12 |
+
import hashlib
|
| 13 |
+
import json
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
import matplotlib
|
| 17 |
+
matplotlib.use("Agg")
|
| 18 |
+
import matplotlib.pyplot as plt
|
| 19 |
+
from matplotlib.patches import FancyBboxPatch, Rectangle
|
| 20 |
+
|
| 21 |
+
D = Path(__file__).resolve().parents[1]
|
| 22 |
+
M = D.parents[1]
|
| 23 |
+
MS = Path('/home/sj_server_1/PBISC/paper-release-20260928/manuscript')
|
| 24 |
+
C = MS/'source_data/corpus'
|
| 25 |
+
INDEX = M.parent/'model_7_no_annotation_sh_hwang/data/e2_full_index/dataset_manifest.json'
|
| 26 |
+
RUN = M/'runs/f01_6k_1x_seed20260627'
|
| 27 |
+
PLAN = M/'plans/full_recipe_allcells_6k_broad_20260909'
|
| 28 |
+
FIG = D/'figures/strengthening_20261013/corpus'
|
| 29 |
+
DATA = D/'data/strengthening_20261013/corpus'
|
| 30 |
+
FULL = (12.3, 5.6)
|
| 31 |
+
INK, SUB, LIGHT = '#1A1A1A', '#626262', '#DADDE1'
|
| 32 |
+
SPLIT_COL = {'train':'#5B6E8F', 'val':'#9AACC4', 'test':'#C9D2DF'}
|
| 33 |
+
SOURCES: dict[str, dict] = {}
|
| 34 |
+
ASSETS: list[str] = []
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def digest(path: Path) -> str:
|
| 38 |
+
h=hashlib.sha256()
|
| 39 |
+
with path.open('rb') as f:
|
| 40 |
+
for b in iter(lambda:f.read(1<<20),b''):h.update(b)
|
| 41 |
+
return h.hexdigest()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def source(path: Path, role: str) -> Path:
|
| 45 |
+
if path.stat().st_size>16<<20:raise ValueError(f'Metadata input exceeds16MiB: {path}')
|
| 46 |
+
SOURCES[str(path)]={'path':str(path),'host':'server_1','sha256':digest(path),'bytes':path.stat().st_size,'role':role}
|
| 47 |
+
return path
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def document(path: Path, role: str) -> dict:
|
| 51 |
+
return json.loads(source(path,role).read_text())
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def table(path: Path, role: str) -> list[dict]:
|
| 55 |
+
with source(path,role).open(newline='') as f:return list(csv.DictReader(f))
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def write_csv(name: str, rows: list[dict]) -> None:
|
| 59 |
+
p=DATA/(name+'.csv')
|
| 60 |
+
with p.open('w',newline='') as f:
|
| 61 |
+
w=csv.DictWriter(f,fieldnames=list(rows[0]));w.writeheader();w.writerows(rows)
|
| 62 |
+
ASSETS.append(str(p))
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def load() -> dict:
|
| 66 |
+
summ=document(C/'corpus_summary.json','saved corpus condition, split and overlap totals')
|
| 67 |
+
groups=table(C/'corpus_cellgroups.csv','cell-level condition counts; not sample-majority labels')
|
| 68 |
+
ds=table(C/'corpus_datasets.csv','independent dataset-level cell and split totals')
|
| 69 |
+
samples=table(C/'corpus_samples.csv','registered sample and split totals')
|
| 70 |
+
assay=table(C/'corpus_assay_condition.csv','independent assay-condition aggregation')
|
| 71 |
+
celltypes=table(C/'corpus_celltypes.csv','existing harmonized source L1/L2 cell-type counts')
|
| 72 |
+
source(C/'README.md','condition definitions and internal donor overlap caveat')
|
| 73 |
+
source(C/'dataset_info.csv','healthy stimulation/CMV and disease-label interpretation')
|
| 74 |
+
source(MS/'scripts/corpus/build_corpus_tables.py','source condition harmonization implementation')
|
| 75 |
+
colorcode=source(MS/'scripts/corpus/build_figure1_corpus.py','existing biological condition and split colors')
|
| 76 |
+
maps={}
|
| 77 |
+
for n in ast.parse(colorcode.read_text()).body:
|
| 78 |
+
if isinstance(n,ast.Assign):
|
| 79 |
+
for t in n.targets:
|
| 80 |
+
if isinstance(t,ast.Name) and t.id in ['COND_COLOR','L1_COLOR','L1_ORDER','L1_MERGE']:
|
| 81 |
+
maps[t.id]=ast.literal_eval(n.value)
|
| 82 |
+
cmap=maps['COND_COLOR']
|
| 83 |
+
assert cmap and set(cmap)==set(summ['condition_cells'])
|
| 84 |
+
idx=document(INDEX,'registered source corpus, split unit, K and platform recipe quotas')
|
| 85 |
+
contract=document(RUN/'ALLCELL_DATA_CONTRACT.json','final Model8 all-cell training coverage and emitted targets')
|
| 86 |
+
status=document(RUN/'RUN_STATUS.json','final Model8 completion and corpus fingerprint')
|
| 87 |
+
cfg=document(RUN/'effective_config.json','final Model8 gene panel and all-K target cap')
|
| 88 |
+
coverage=document(PLAN/'coverage_v1/summary.json','registered recipe unique coverage and sampling semantics')
|
| 89 |
+
source(M.parent/'model_7_no_annotation_sh_hwang/src/model7_no_annotation/data_e2.py','K distinct cells sampled within a sample; count-sum pseudobulk')
|
| 90 |
+
source(M/'src/pbisc_sdd/ladder_experiment.py','all-K plus top-up training contract implementation')
|
| 91 |
+
topups=table(PLAN/'topup_v1/topup_recipes.csv','saved explicit top-up recipe sizes and split')
|
| 92 |
+
source(D/'PBISC-Diffusion_color_palette_20261013.md','method palette; biological category colors exempt')
|
| 93 |
+
cond=Counter(); splits=Counter(); cross=Counter(); health_hand=Counter(); total=0;cmv=0
|
| 94 |
+
for r in groups:
|
| 95 |
+
n=int(r['n_cells']);total+=n;cond[r['condition']]+=n;splits[r['split']]+=n;cross[(r['condition'],r['split'])]+=n
|
| 96 |
+
if r['condition']=='Healthy':health_hand[r['handling']]+=n
|
| 97 |
+
if r['cmv_seropositive_healthy']=='True':
|
| 98 |
+
assert r['condition']=='Healthy';cmv+=n
|
| 99 |
+
assert total==summ['cells']==idx['n_cells']==sum(int(r['n_cells']) for r in ds)==sum(int(r['n_cells']) for r in assay)
|
| 100 |
+
l1raw=Counter();l1=Counter()
|
| 101 |
+
for r in celltypes:
|
| 102 |
+
l1raw[r['celltype_l1']]+=int(r['n_cells'])
|
| 103 |
+
l1[maps['L1_MERGE'].get(r['celltype_l1'],r['celltype_l1'])]+=int(r['n_cells'])
|
| 104 |
+
assert dict(l1raw)==summ['celltype_l1_cells'] and sum(l1.values())==total
|
| 105 |
+
assert set(l1)==set(maps['L1_ORDER'])
|
| 106 |
+
assert dict(cond)==summ['condition_cells'] and dict(splits)==summ['split_cells']
|
| 107 |
+
assert cmv==summ['cmv_seropositive_healthy_cells']
|
| 108 |
+
assert len(samples)==summ['samples']==6507 and len({r['sample_key'] for r in samples})==6507
|
| 109 |
+
assert Counter(r['split'] for r in samples)==Counter(summ['split_samples'])
|
| 110 |
+
for s in ['train','val','test']:assert splits[s]==sum(int(r[s+'_cells']) for r in ds)
|
| 111 |
+
assert summ['base_cells']+summ['overlay_cells']==total and len(ds)==summ['datasets']==22
|
| 112 |
+
cov=contract['coverage_after_topup'];pairing=contract['pairing'];orig=contract['original_recipe_coverage']
|
| 113 |
+
assert contract['status']==status['status']=='COMPLETED' and status['epochs_completed']==16
|
| 114 |
+
assert idx['corpus_fingerprint']==pairing['source_corpus_fingerprint']==status['corpus_fingerprint']==coverage['corpus_fingerprint']
|
| 115 |
+
assert cov['train_universe_cells']==cov['train_cells_covered_after_topup']==splits['train'] and cov['train_cell_coverage_after_topup']==1
|
| 116 |
+
assert orig['represented_cells']+cov['topup_target_cells']==splits['train']
|
| 117 |
+
assert contract['expected_target_cells_by_epoch']==contract['observed_target_cells_by_epoch']
|
| 118 |
+
assert sum(contract['observed_target_cells_by_epoch'])==cov['total_target_exposures_with_topup']==contract['total_target_cells']
|
| 119 |
+
assert cov['validation']['status']=='PASS' and cov['validation']['nontrain_cells']==0
|
| 120 |
+
assert coverage['heldout_target_exposures']==0 and coverage['all_k_member_occurrences_become_targets'] is True
|
| 121 |
+
assert idx['k_values']==[250,500,1000,2000,4000] and cfg['data']['train_cells_per_block']==4000
|
| 122 |
+
assert 'proportion_hint' not in cfg['data']
|
| 123 |
+
assert len(topups)==cov['topup_recipes'] and all(r['split']=='train' for r in topups)
|
| 124 |
+
tk=[int(r['k']) for r in topups]
|
| 125 |
+
assert sum(tk)==cov['topup_target_cells'] and max(tk)==4000 and min(tk)==1
|
| 126 |
+
quotas=idx['k_quotas_per_epoch'];assert sum(quotas.values())==pairing['registered_recipes_per_epoch']==8192
|
| 127 |
+
assert sum(idx['platform_quotas_per_epoch'].values())==8192
|
| 128 |
+
nonhealthy=total-cond['Healthy'];risk=cond['ACPA+ at risk of RA'];disease=nonhealthy-risk
|
| 129 |
+
# Fixed explanatory captions are bound to this frozen source snapshot.
|
| 130 |
+
assert (total,cond['Healthy'],nonhealthy,risk,disease)==(41395184,36639276,4755908,1792129,2963779)
|
| 131 |
+
assert dict(splits)=={'train':33141380,'val':4361032,'test':3892772}
|
| 132 |
+
assert (orig['represented_cells'],cov['topup_target_cells'],cov['topup_recipes'],contract['total_target_cells'])==(31145450,1995930,3658,195639930)
|
| 133 |
+
out={'total_cells':total,'healthy_cells':cond['Healthy'],'disease_or_at_risk_cells':nonhealthy,
|
| 134 |
+
'disease_history_without_at_risk_cells':disease,'at_risk_cells':risk,
|
| 135 |
+
'healthy_fraction':cond['Healthy']/total,'disease_or_at_risk_fraction':nonhealthy/total,
|
| 136 |
+
'condition_cells':dict(cond),'split_cells':dict(splits),'split_samples':summ['split_samples'],
|
| 137 |
+
'healthy_handling_cells':dict(health_hand),'cmv_seropositive_healthy_cells':cmv,
|
| 138 |
+
'conditions':summ['conditions_order'],'colors':cmap,'summary':summ,
|
| 139 |
+
'celltype_counts':dict(l1),'celltype_colors':maps['L1_COLOR'],'celltype_order':maps['L1_ORDER'],
|
| 140 |
+
'index':idx,'contract':contract,'topup_k_min':min(tk),'topup_k_max':max(tk),
|
| 141 |
+
'internal_overlap_donors':summ['donors_in_more_than_one_split'],
|
| 142 |
+
'internal_overlap_val_test_samples':summ['val_test_samples_whose_donor_has_train_samples']}
|
| 143 |
+
write_csv('condition_counts',[{'condition':c,'n_cells':cond[c],'corpus_fraction':cond[c]/total,
|
| 144 |
+
'detail_fraction':cond[c]/nonhealthy if c!='Healthy' else '',
|
| 145 |
+
'overview_group':'Healthy' if c=='Healthy' else 'Disease / at-risk',
|
| 146 |
+
'interpretation':'at risk, not confirmed RA' if c=='ACPA+ at risk of RA' else 'source disease/history annotation' if c!='Healthy' else 'healthy donor status; stimulation/vaccination/CMV context retained',
|
| 147 |
+
'color':cmap[c]} for c in summ['conditions_order']])
|
| 148 |
+
write_csv('condition_by_split',[{'condition':c,'split':s,'n_cells':cross[(c,s)],'share_of_split':cross[(c,s)]/splits[s]} for c in summ['conditions_order'] for s in ['train','val','test']])
|
| 149 |
+
write_csv('celltype_counts',[{'celltype':c,'n_cells':l1[c],'corpus_fraction':l1[c]/total,
|
| 150 |
+
'color':maps['L1_COLOR'][c]} for c in maps['L1_ORDER']])
|
| 151 |
+
write_csv('split_counts',[{'split':s,'n_cells':splits[s],'n_samples':summ['split_samples'][s],
|
| 152 |
+
'cell_fraction':splits[s]/total,'registered_fraction':idx['split_fractions'][s]} for s in ['train','val','test']])
|
| 153 |
+
slots=cov['slot_coverage']
|
| 154 |
+
write_csv('recipe_counts',[{'recipe_kind':'registered','K':k,'recipes_per_part':quotas[str(k)],
|
| 155 |
+
'target_occurrences_per_part':k*quotas[str(k)],'parts':16,'source':str(INDEX)} for k in idx['k_values']]+[
|
| 156 |
+
{'recipe_kind':'coverage top-up','K':f'{min(tk)}–{max(tk)}, actual tail size',
|
| 157 |
+
'recipes_per_part':f"{min(x['topup_recipes'] for x in slots)}–{max(x['topup_recipes'] for x in slots)}",
|
| 158 |
+
'target_occurrences_per_part':f"{min(x['topup_target_cells'] for x in slots)}–{max(x['topup_target_cells'] for x in slots)}",
|
| 159 |
+
'parts':16,'source':str(RUN/'ALLCELL_DATA_CONTRACT.json')}])
|
| 160 |
+
return out
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def save(fig: plt.Figure, stem: str) -> str:
|
| 164 |
+
for ext in ['png','pdf','svg']:
|
| 165 |
+
p=FIG/(stem+'.'+ext);fig.savefig(p,dpi=220,bbox_inches=None,facecolor='white');ASSETS.append(str(p))
|
| 166 |
+
plt.close(fig);return str((FIG/(stem+'.png')).relative_to(D))
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
def donut(ax, counts: list[int], colors: list[str], center_top: str, center_bottom: str) -> None:
|
| 170 |
+
ax.pie(counts,colors=colors,startangle=90,counterclock=False,
|
| 171 |
+
wedgeprops={'width':.29,'edgecolor':'white','linewidth':1.4})
|
| 172 |
+
ax.text(0,.06,center_top,ha='center',va='center',fontsize=22,fontweight='bold')
|
| 173 |
+
ax.text(0,-.18,center_bottom,ha='center',va='center',fontsize=12,color=SUB)
|
| 174 |
+
ax.set_aspect('equal')
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def disease_overview(z: dict) -> str:
|
| 178 |
+
fig=plt.figure(figsize=FULL)
|
| 179 |
+
fig.text(.028,.965,'41,395,184 cells · 22 datasets · 6,507 registered samples · 3,199 donor identities',fontsize=16,fontweight='bold')
|
| 180 |
+
fig.text(.028,.887,'Healthy versus disease / at-risk',fontsize=14,fontweight='bold')
|
| 181 |
+
fig.text(.355,.887,'Disease / at-risk detail',fontsize=14,fontweight='bold')
|
| 182 |
+
fig.text(.687,.887,'Source cell-type composition',fontsize=14,fontweight='bold')
|
| 183 |
+
a=fig.add_axes([.035,.461,.275,.415]);b=fig.add_axes([.367,.461,.275,.415]);cax=fig.add_axes([.700,.461,.275,.415])
|
| 184 |
+
donut(a,[z['healthy_cells'],z['disease_or_at_risk_cells']],[z['colors']['Healthy'],'#94776F'],'41.40M','source cells')
|
| 185 |
+
detail=sorted([c for c in z['conditions'] if c!='Healthy'],key=lambda c:z['condition_cells'][c],reverse=True)
|
| 186 |
+
donut(b,[z['condition_cells'][c] for c in detail],[z['colors'][c] for c in detail],'4.756M','disease / at-risk')
|
| 187 |
+
ct=z['celltype_order'];donut(cax,[z['celltype_counts'][c] for c in ct],[z['celltype_colors'][c] for c in ct],'41.40M','source cells')
|
| 188 |
+
fig.text(.028,.431,f"Healthy: {z['healthy_cells']:,} ({z['healthy_fraction']*100:.1f}%)",fontsize=12.4,fontweight='bold',color='#52647D')
|
| 189 |
+
fig.text(.028,.384,f"Disease / at-risk: {z['disease_or_at_risk_cells']:,} ({z['disease_or_at_risk_fraction']*100:.1f}%)",fontsize=11.5,color='#765B54')
|
| 190 |
+
fig.text(.028,.305,'Healthy donor status includes:',fontsize=12,fontweight='bold')
|
| 191 |
+
fig.text(.028,.259,'• 9.763M in-vitro cytokine/PBS or IL-36 cells\n• 9.216M CMV-seropositive healthy cells\n• Post-vaccination draws',fontsize=10.8,va='top',linespacing=1.6,color=SUB)
|
| 192 |
+
fig.text(.028,.130,'ACPA+ at risk is not confirmed RA.',fontsize=11,fontweight='bold')
|
| 193 |
+
fig.text(.028,.082,'Disease/history excluding at-risk: 7.16%\nAt-risk alone: 4.33% of all source cells',fontsize=10.5,va='top',linespacing=1.4,color=SUB)
|
| 194 |
+
for i,c in enumerate(detail):
|
| 195 |
+
y=.433-i*.035
|
| 196 |
+
fig.patches.append(Rectangle((.35,y-.010),.010,.019,transform=fig.transFigure,color=z['colors'][c],lw=0))
|
| 197 |
+
fig.text(.368,y,c,fontsize=10.5,va='center')
|
| 198 |
+
fig.text(.653,y,f"{z['condition_cells'][c]:,} · {z['condition_cells'][c]/z['disease_or_at_risk_cells']*100:.1f}%",fontsize=10.3,color=SUB,va='center',ha='right')
|
| 199 |
+
for i,c in enumerate(ct):
|
| 200 |
+
y=.433-i*.035
|
| 201 |
+
fig.patches.append(Rectangle((.685,y-.010),.010,.019,transform=fig.transFigure,color=z['celltype_colors'][c],lw=0))
|
| 202 |
+
fig.text(.703,y,c,fontsize=10.5,va='center')
|
| 203 |
+
pct=z['celltype_counts'][c]/z['total_cells']*100
|
| 204 |
+
pp=f'{pct:.1f}%' if pct>=.1 else '<0.1%'
|
| 205 |
+
fig.text(.987,y,f"{z['celltype_counts'][c]:,} · {pp}",fontsize=10.3,color=SUB,va='center',ha='right')
|
| 206 |
+
fig.text(.355,.026,'Shares describe source cells; annotations are not model inputs.',fontsize=10.8,color=SUB)
|
| 207 |
+
return save(fig,'healthy_disease_overview')
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def box(ax,x,y,w,h,title,body,fill='#F5F6F8',headsize=15,bodysize=13):
|
| 211 |
+
ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle='round,pad=.018,rounding_size=.06',fc=fill,ec='#D7DCE3',lw=1))
|
| 212 |
+
ax.text(x+.18,y+h-.18,title,va='top',fontsize=headsize,fontweight='bold',color=INK)
|
| 213 |
+
ax.text(x+.18,y+.16,body,va='bottom',fontsize=bodysize,linespacing=1.45,color=SUB)
|
| 214 |
+
|
| 215 |
+
|
| 216 |
+
def arrow(ax,x0,y0,x1,y1):
|
| 217 |
+
ax.annotate('',(x1,y1),(x0,y0),arrowprops=dict(arrowstyle='-|>',lw=1.3,color='#7F8A98',shrinkA=2,shrinkB=2))
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def split_schematic(z: dict) -> str:
|
| 221 |
+
fig,ax=plt.subplots(figsize=FULL);ax.set(xlim=(0,12.3),ylim=(0,5.6));ax.axis('off')
|
| 222 |
+
box(ax,.18,4.2,11.92,1.10,'41,395,184 source cells','22 datasets · 6,507 registered samples · 3,199 donor identities',fill='#F1F3F6',headsize=20,bodysize=14)
|
| 223 |
+
xx=[.18,4.25,8.32]
|
| 224 |
+
for x,s,head in zip(xx,['train','val','test'],['Training source','Validation source','Test source']):
|
| 225 |
+
box(ax,x,2.45,3.78,1.35,head,f"{z['split_cells'][s]:,} cells ({z['split_cells'][s]/z['total_cells']*100:.2f}%)\n{z['split_samples'][s]:,} samples",fill={'train':'#E8EDF4','val':'#F0F3F7','test':'#F5F6F8'}[s],headsize=16,bodysize=14)
|
| 226 |
+
arrow(ax,x+1.89,4.18,x+1.89,3.83)
|
| 227 |
+
box(ax,.18,.93,5.63,1.05,'Only the training split supplies optimization targets','Saved all-cell coverage: all 33,141,380 training cells represented.',fill='#E8EDF4',headsize=14,bodysize=12.5)
|
| 228 |
+
arrow(ax,2.07,2.43,2.07,2.02)
|
| 229 |
+
box(ax,6.13,.93,5.97,1.05,'The 8,253,804-cell difference is validation + test','K controls recipe size; it is not the cause of this source-count difference.',fill='#F7F7F7',headsize=14,bodysize=12)
|
| 230 |
+
ax.text(.23,.48,'Registered rule: dataset_id + donor_id, nominal 80/10/10; realized cell fractions differ because group sizes differ.',fontsize=11.5,color=SUB)
|
| 231 |
+
ax.text(.23,.15,'Metadata audit: 0 sample overlaps, but 27 biological donors span internal splits. This does not establish external test-cohort overlap.',fontsize=11.5,color=SUB)
|
| 232 |
+
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
|
| 233 |
+
return save(fig,'source_split_flow')
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def recipe_schematic(z: dict) -> str:
|
| 237 |
+
fig,ax=plt.subplots(figsize=FULL);ax.set(xlim=(0,12.3),ylim=(0,5.6));ax.axis('off')
|
| 238 |
+
box(ax,.18,4.01,3.31,1.3,'One training sample','Choose K distinct cells\nwithout replacement inside a recipe',headsize=15,bodysize=12.5)
|
| 239 |
+
box(ax,4.03,4.01,3.83,1.3,'Sum counts → pseudobulk condition','Same condition accompanies all\nK individual-cell training targets',headsize=14,bodysize=12.5)
|
| 240 |
+
box(ax,8.40,4.01,3.68,1.3,'Training spans 16 schedule parts','Cell reuse across recipes is allowed.\nK is not generated-cell count.',headsize=14,bodysize=12.5)
|
| 241 |
+
arrow(ax,3.49,4.66,4.03,4.66);arrow(ax,7.86,4.66,8.4,4.66)
|
| 242 |
+
ax.text(.22,3.58,'Registered K grid',fontsize=16,fontweight='bold')
|
| 243 |
+
ax.text(4.00,3.58,'Coverage correction after the registered grid',fontsize=16,fontweight='bold')
|
| 244 |
+
ks=z['index']['k_values'];q=z['index']['k_quotas_per_epoch']
|
| 245 |
+
for i,k in enumerate(ks):
|
| 246 |
+
yy=3.16-i*.39
|
| 247 |
+
ax.text(.26,yy,f'K = {k:,}',fontsize=13,va='center')
|
| 248 |
+
ax.add_patch(Rectangle((1.65,yy-.105),1.18*q[str(k)]/max(q.values()),.21,fc='#7E91AE',ec='none'))
|
| 249 |
+
ax.text(2.91,yy,f'{q[str(k)]:,}',fontsize=12,va='center')
|
| 250 |
+
ax.text(.26,1.08,'8,192 registered recipes / part',fontsize=12,fontweight='bold')
|
| 251 |
+
ax.text(.26,.72,'Recipe quotas, not source-cell proportions',fontsize=10.5,color=SUB)
|
| 252 |
+
orig=z['contract']['original_recipe_coverage'];cov=z['contract']['coverage_after_topup']
|
| 253 |
+
box(ax,4.0,2.54,8.08,.82,'31,145,450 unique training cells covered by the regular grid','93.98% of the training universe; 1,995,930 cells were still unseen.',headsize=14,bodysize=12)
|
| 254 |
+
arrow(ax,8.04,2.50,8.04,2.24)
|
| 255 |
+
box(ax,4.0,1.34,8.08,.87,'+ 3,658 top-up recipes → all 33,141,380 training cells','Actual top-up K = 1–4,000; small tails are retained without duplicate padding.',fill='#E8EDF4',headsize=14,bodysize=12)
|
| 256 |
+
ax.text(4.05,.81,'195,639,930 total training-target occurrences ≠ 33,141,380 unique cells',fontsize=13,fontweight='bold')
|
| 257 |
+
ax.text(.22,.29,'Source shares are not sampler exposure: platform recipe quotas use square-root cell weighting; target occurrences also depend on K.',fontsize=11.3,color=SUB)
|
| 258 |
+
ax.text(.22,.04,'Saved final-run contract verifies all emitted target counts. Disease-specific exposure frequencies are not computed from source-cell shares.',fontsize=11.3,color=SUB)
|
| 259 |
+
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
|
| 260 |
+
return save(fig,'recipe_coverage_and_exposure')
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def build() -> dict:
|
| 264 |
+
SOURCES.clear();ASSETS.clear();FIG.mkdir(parents=True,exist_ok=True);DATA.mkdir(parents=True,exist_ok=True)
|
| 265 |
+
plt.rcParams.update({'font.family':'sans-serif','font.sans-serif':['Arial','Liberation Sans'],'font.size':14,
|
| 266 |
+
'axes.spines.top':False,'axes.spines.right':False,'pdf.fonttype':42,'svg.fonttype':'none',
|
| 267 |
+
'figure.facecolor':'white','axes.facecolor':'white','text.color':INK})
|
| 268 |
+
z=load();panels=[]
|
| 269 |
+
common='Saved corpus metadata and final f01_6k_1x_seed20260627 E16 training contract; no raw expression arrays or new model runs. Biological condition/split colors retain their existing meanings, independent of the method palette. '
|
| 270 |
+
cases=[('corpus_conditions','Corpus composition: health, disease risk and cell types','Two-level condition view with the existing cell-type statistics',disease_overview(z),
|
| 271 |
+
'Source-cell shares. Disease / at-risk includes ACPA+ at-risk, not confirmed RA. Healthy includes stimulation, vaccination and CMV contexts.',
|
| 272 |
+
'Left denominator41,395,184; Healthy36,639,276(88.51%); disease/at-risk4,755,908(11.49%). Detail contains11 source conditions, including ACPA+ at-risk1,792,129; disease/history subtotal excluding at-risk2,963,779. Post-COVID remains a history/post-infection label and Cytopenia is retained verbatim, not called a confirmed malignancy. Counts derive from cell-level groups, not per-sample majority condition. Healthy includes9,762,726 in-vitro cells: Parse9,697,974 (90 cytokines or PBS) and IL-36/PBS healthy-donor cells64,752. CMV-seropositive healthy cells9,215,690; post-vaccination source draws remain Healthy. These are donor/handling context, not inferred active disease. Right donut preserves original harmonized L1 source cell-type counts and colors: NKT/Granulocyte/Neutrophil/Mast→Other, unknown/overlay labels→Unlabelled, matching the source figure merge rules. Total source-cell denominator is checked again. The model receives no disease/cell-type labels in this final base run.'),
|
| 273 |
+
('corpus_splits','From 41.40M source cells to 33.14M training cells','The difference is a split boundary, not K-based exclusion',split_schematic(z),
|
| 274 |
+
'Source train/validation/test counts, not validation recipe exposure. No sample overlap; 27 biological donors span internal corpus splits.',
|
| 275 |
+
'Exact counts: training33,141,380, validation4,361,032, test3,892,772; sum41,395,184. Source samples5232/648/627. Split rule dataset_id+donor_id with sample_id fallback; nominal0.8/0.1/0.1 and realized cell proportions differ. Independent source metadata found27 biological donors with multi-split samples (26GSE274680,1GSE132802),38validation/test samples and659,112cells (331,377val,327,735test) sharing a biological donor with training. These are INTERNAL corpus overlaps, not evidence that external SLE/paired benchmark patients occur in training. Actual validation recipes consume selected cells, not the entire validation source split. Source-count identity and final-run corpus fingerprint are checked.'),
|
| 276 |
+
('corpus_recipes','Recipe K and training exposure are different counts','All training cells are covered after explicit top-up recipes',recipe_schematic(z),
|
| 277 |
+
'Saved all-cell audit: 33,141,380 unique training cells covered. K defines recipe membership; 195,639,930 target occurrences include reuse.',
|
| 278 |
+
'Registered K250/500/1000/2000/4000 has recipe quotas745/1489/2234/2979/745 per part (weights1/2/3/4/1);8192recipes/part×16parts=131072. All K members are targets because cells_per_block4000 is at least maxK. Registered recipes alone cover31,145,450 unique train cells (93.9775%); top-up3658recipes adds1,995,930 previously unseen train cells once, totaling33,141,380(100%). Top-upK1–4000 preserves small tails without padding; total134730recipes. Total195,639,930target occurrences across16parts include repeated source cells and do not imply195Munique cells. Platform quotas10x4691,Parse2625,ScaleBio698,Seq-Well178 per part derive from square-root source-cell counts, not natural corpus prevalence. Disease-specific exposure proportions are not available in these figures. K is distinct from N_gen, the number of cells sampled at inference.')]
|
| 279 |
+
source(Path(__file__).resolve(),'reproducible metadata-only figure builder')
|
| 280 |
+
for key,title,subtitle,figure,foot,note in cases:
|
| 281 |
+
assert len(foot)<=180
|
| 282 |
+
panels.append({'key':key,'kind':'content','title':title,'subtitle':subtitle,'figure':figure,'figures':[figure],
|
| 283 |
+
'section':'Figure 1','section_label':'Figure 1 support','keywords':[],
|
| 284 |
+
'footnote':foot,'note':common+note,'footnote_full':common+note,'palette':'biological',
|
| 285 |
+
'source_refs':list(SOURCES),'source_bindings':list(SOURCES.values())})
|
| 286 |
+
limitations=['Disease / at-risk is not synonymous with confirmed active disease. ACPA+ risk, Post-COVID history and Cytopenia remain explicit.',
|
| 287 |
+
'Donor and source-cell proportions are different. Disease/cell-type annotations are descriptive only and were not supplied to the final base model.',
|
| 288 |
+
'Source-cell composition is not the distribution of training-target occurrences. No disease-exposure frequencies are inferred.',
|
| 289 |
+
'Dataset-donor split keys did not ensure strict biological-donor separation for27 internal donors. External target overlap requires separate linkage.',
|
| 290 |
+
'The source validation/test totals do not equal cells used by fixed validation/test recipes. These figures make no performance/generalization claim.',
|
| 291 |
+
'All-cell coverage is a verified saved contract, not a fresh audit of raw cell-ID arrays. Existing cell-type corpus panels are untouched.']
|
| 292 |
+
verified={'source_total':z['total_cells'],'healthy':z['healthy_cells'],'disease_or_at_risk':z['disease_or_at_risk_cells'],
|
| 293 |
+
'at_risk':z['at_risk_cells'],'disease_history_without_at_risk':z['disease_history_without_at_risk_cells'],
|
| 294 |
+
'condition_cells':z['condition_cells'],'split_cells':z['split_cells'],'split_samples':z['split_samples'],
|
| 295 |
+
'celltype_display_counts':z['celltype_counts'],
|
| 296 |
+
'healthy_in_vitro':z['healthy_handling_cells']['in vitro'],'healthy_cmv_seropositive':z['cmv_seropositive_healthy_cells'],
|
| 297 |
+
'k_values':z['index']['k_values'],'recipe_quotas':z['index']['k_quotas_per_epoch'],
|
| 298 |
+
'original_unique_train_covered':z['contract']['original_recipe_coverage']['represented_cells'],
|
| 299 |
+
'unique_topup_cells':z['contract']['coverage_after_topup']['topup_target_cells'],
|
| 300 |
+
'final_unique_train_covered':z['split_cells']['train'],'target_occurrences':z['contract']['total_target_cells'],
|
| 301 |
+
'final_run_corpus_fingerprint':z['index']['corpus_fingerprint'],
|
| 302 |
+
'checks':{'cellgroup_dataset_assay_totals_equal':True,'split_crosschecks_equal':True,'sample_keys_unique':True,
|
| 303 |
+
'condition_counts_match_source_summary':True,'topup_k_sum_matches_coverage':True,'expected_observed_targets_equal':True,
|
| 304 |
+
'final_training_coverage_100pct':True,'nontrain_targets_zero':True},
|
| 305 |
+
'limitations':limitations}
|
| 306 |
+
p=DATA/'verified_data.json';p.write_text(json.dumps(verified,indent=2)+'\n');ASSETS.append(str(p))
|
| 307 |
+
p=DATA/'LIMITATIONS.md';p.write_text('# Interpretation and integration notes\n\n'+'\n'.join('- '+x for x in limitations)+'\n\nRecommended placement: combined corpus donut beside the existing corpus overview; split and recipe schematics immediately after it. Preserve the existing cell-type composition evidence.\n');ASSETS.append(str(p))
|
| 308 |
+
hashes={'sources':list(SOURCES.values()),'outputs':[{'path':p,'sha256':digest(Path(p))} for p in ASSETS]}
|
| 309 |
+
p=DATA/'hashes.json';p.write_text(json.dumps(hashes,indent=2)+'\n');ASSETS.append(str(p))
|
| 310 |
+
p=DATA/'result.json';ASSETS.append(str(p))
|
| 311 |
+
result={'schema':'pbisc.strengthening.corpus.v1','panels':panels,'slides':panels,'assets':ASSETS.copy(),
|
| 312 |
+
'sources':list(SOURCES.values()),'verified_data':verified,'recommendations':['Keep the two-level disease / at-risk design on one slide.','Keep original cell-type statistics elsewhere.','Do not claim donor-disjoint evaluation from sample-level split separation.'],
|
| 313 |
+
'new_training':False,'new_inference':False,'raw_expression_payload_read':False}
|
| 314 |
+
p.write_text(json.dumps(result,indent=2)+'\n');return result
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
if __name__=='__main__':
|
| 318 |
+
r=build();print(json.dumps({'panels':len(r['panels']),'assets':len(r['assets']),'sources':len(r['sources'])}))
|
paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/strengthen_disease_metrics_20261013.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Source-only Figure 4 supplements: CV ranks and strict Sepsis metrics.
|
| 2 |
+
|
| 3 |
+
Saved CSV/JSON inputs only. No model, generated-array, DEG fit or deconvolution
|
| 4 |
+
execution. Frozen source snapshots and precise protocol/metric scope accompany
|
| 5 |
+
every figure; support draws are not treated as independent biological replicates.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import hashlib
|
| 10 |
+
import json
|
| 11 |
+
import os
|
| 12 |
+
import shutil
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
|
| 16 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 17 |
+
import numpy as np
|
| 18 |
+
import pandas as pd
|
| 19 |
+
import style as ST
|
| 20 |
+
import matplotlib.pyplot as plt
|
| 21 |
+
from matplotlib.lines import Line2D
|
| 22 |
+
|
| 23 |
+
D = Path(__file__).resolve().parents[1]
|
| 24 |
+
M = D.parents[1]
|
| 25 |
+
F = M / "plans/paired_finetune_intradataset_20260927/scores_contrast"
|
| 26 |
+
P = M / "plans/paper_figures_strictpairs_20261012"
|
| 27 |
+
DATA = D / "data/strengthening_20261013/disease_metrics"
|
| 28 |
+
FIG = D / "figures/strengthening_20261013/disease_metrics"
|
| 29 |
+
COHORTS = ["ye2026_sepsis", "imperial_eskd", "giroux2022", "ji2025_chili"]
|
| 30 |
+
NAMES = dict(zip(COHORTS, ["Sepsis", "Imperial ESKD", "Giroux", "CHILI"]))
|
| 31 |
+
METHODS = ["raw", "cal", "lora", "scsemi", "broadcast", "full"]
|
| 32 |
+
COL = {"raw": "#C3E2F4", "cal": "#59A8DF", "lora": "#168FE5", "scsemi": "#83C6A8",
|
| 33 |
+
"broadcast": "#4D4D4D", "full": "#0D6EA8", "refcal": "#59A8DF", "pairedcal": "#59A8DF"}
|
| 34 |
+
LAB = {"raw": "Raw zero-shot", "cal": "Paired calibration", "lora": "PBISC LoRA", "scsemi": "scSemiProfiler",
|
| 35 |
+
"broadcast": "Raw bulk broadcast", "full": "Full FT (Sepsis)", "refcal": "Reference calibration",
|
| 36 |
+
"pairedcal": "Paired calibration"}
|
| 37 |
+
MARK = {"raw": "D", "cal": "s", "lora": "o", "scsemi": "^", "broadcast": "x", "full": "v",
|
| 38 |
+
"refcal": "D", "pairedcal": "s"}
|
| 39 |
+
CT4 = {"T cell", "B cell", "Monocyte", "NK cell"}
|
| 40 |
+
CT5 = CT4 | {"DC"}
|
| 41 |
+
ARMS = {"raw": "zs__raw", "cal": "zs__cal", "lora": "real_lora__raw", "scsemi": "scsemi__raw", "full": "real_full__raw"}
|
| 42 |
+
REFERENCES = [
|
| 43 |
+
{"metric": "CAT", "citation": "Irizarry et al. Nature Methods 2005;2:345–350", "url": "https://doi.org/10.1038/nmeth756",
|
| 44 |
+
"verification": "Read local original paper: CAT is top-list overlap versus list size. Same-sign agreement and moderated-t ranking are this benchmark's explicit extensions."},
|
| 45 |
+
{"metric": "RBO", "citation": "Webber, Moffat & Zobel. ACM TOIS 2010;28:20", "url": "https://doi.org/10.1145/1852102.1852106",
|
| 46 |
+
"verification": "Read local original paper Eq. 32; saved scorer uses extrapolated RBO, p=0.98. Displayed value averages descending and ascending t rankings, then five cell types."},
|
| 47 |
+
{"metric": "limma-voom", "citation": "Law et al. Genome Biology 2014;15:R29", "url": "https://pmc.ncbi.nlm.nih.gov/articles/PMC4053721/",
|
| 48 |
+
"verification": "Primary full text checked: log-count precision weights enter limma. Saved donor-aware implementation uses edgeR TMM, voom, lmFit and eBayes."},
|
| 49 |
+
{"metric": "biological replication", "citation": "Squair et al. Nature Communications 2021;12:5692", "url": "https://pmc.ncbi.nlm.nih.gov/articles/PMC8479118/",
|
| 50 |
+
"verification": "Primary paper supports using biological replicates rather than independent-cell inference. Existing donor-aware DEG tables are reused; no new fit or CI is computed."},
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def sha(path: Path) -> str:
|
| 55 |
+
h = hashlib.sha256()
|
| 56 |
+
with path.open("rb") as f:
|
| 57 |
+
for block in iter(lambda: f.read(1 << 20), b""):
|
| 58 |
+
h.update(block)
|
| 59 |
+
return h.hexdigest()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class Build:
|
| 63 |
+
def __init__(self):
|
| 64 |
+
DATA.mkdir(parents=True, exist_ok=True)
|
| 65 |
+
FIG.mkdir(parents=True, exist_ok=True)
|
| 66 |
+
self.sources, self.assets, self.slides, self.inventory = {}, [], [], []
|
| 67 |
+
|
| 68 |
+
def source(self, path, role="saved numerical evidence"):
|
| 69 |
+
p = Path(path).resolve()
|
| 70 |
+
if str(p) not in self.sources:
|
| 71 |
+
item = dict(path=str(p), sha256=sha(p), bytes=p.stat().st_size, role=role, host="server_1")
|
| 72 |
+
if p.suffix in {".csv", ".json"}:
|
| 73 |
+
relative = p.relative_to(M) if p.is_relative_to(M) else Path("external") / p.name
|
| 74 |
+
target = DATA / "source_snapshot" / relative
|
| 75 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 76 |
+
shutil.copy2(p, target)
|
| 77 |
+
assert sha(target) == item["sha256"]
|
| 78 |
+
item["snapshot"] = str(target)
|
| 79 |
+
self.assets.append(str(target))
|
| 80 |
+
self.sources[str(p)] = item
|
| 81 |
+
return p
|
| 82 |
+
|
| 83 |
+
def csv(self, p, role="saved numerical evidence"):
|
| 84 |
+
p = self.source(p, role)
|
| 85 |
+
return pd.read_csv(self.sources[str(p)].get("snapshot", p))
|
| 86 |
+
|
| 87 |
+
def js(self, p, role="saved provenance metadata"):
|
| 88 |
+
p = self.source(p, role)
|
| 89 |
+
return json.loads(Path(self.sources[str(p)].get("snapshot", p)).read_text())
|
| 90 |
+
|
| 91 |
+
def table(self, df, name):
|
| 92 |
+
p = DATA / name
|
| 93 |
+
df.to_csv(p, index=False)
|
| 94 |
+
self.assets.append(str(p))
|
| 95 |
+
|
| 96 |
+
def figure(self, fig, stem, title, footnote, notes, subtitle):
|
| 97 |
+
paths = []
|
| 98 |
+
for ext in ["png", "pdf", "svg"]:
|
| 99 |
+
p = FIG / f"{stem}.{ext}"
|
| 100 |
+
fig.savefig(p, dpi=300, bbox_inches="tight", pad_inches=.04)
|
| 101 |
+
paths.append(str(p)); self.assets.append(str(p))
|
| 102 |
+
plt.close(fig)
|
| 103 |
+
self.slides.append(dict(kind="content", layout="full", key=f"strengthen_{stem}",
|
| 104 |
+
role="f4_disease_metrics", title=title, subtitle=subtitle,
|
| 105 |
+
section_label="Fig. 4 · Disease integrity", figures=[str(Path(paths[0]).relative_to(D))],
|
| 106 |
+
figure=paths[0], palette="native", keywords=[], footnote=footnote,
|
| 107 |
+
footnote_full=notes, notes=notes, note=notes,
|
| 108 |
+
sources="; ".join(self.sources), metric_references=REFERENCES,
|
| 109 |
+
refs={"cv_complete_cat": ["Irizarry et al. 2005; Law et al. 2014"],
|
| 110 |
+
"cv_multimetric": ["Webber et al. 2010"],
|
| 111 |
+
"strict_sepsis_multimetric": ["Law et al. 2014; Squair et al. 2021"]}[stem],
|
| 112 |
+
refs_full=[r["citation"] + ". " + r["url"] + " — " + r["verification"] for r in REFERENCES]))
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
def legend(fig, methods=METHODS, y=1.04, extra=None):
|
| 116 |
+
handles = [Line2D([], [], color=COL[m], marker=MARK[m], mec="#4D4D4D", mew=.6,
|
| 117 |
+
mfc="white" if m in {"cal", "full"} else COL[m], lw=1.9,
|
| 118 |
+
ls="--" if m in {"cal", "full"} else "-") for m in methods]
|
| 119 |
+
labels = [LAB[m] for m in methods]
|
| 120 |
+
if extra:
|
| 121 |
+
handles.append(extra[0]); labels.append(extra[1])
|
| 122 |
+
fig.legend(handles, labels, ncol=3, loc="upper center", bbox_to_anchor=(.52, y), fontsize=11.5,
|
| 123 |
+
columnspacing=1.8, handlelength=2.1)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def cv_inputs(b):
|
| 127 |
+
heads, curves, contracts = [], [], []
|
| 128 |
+
for ds in COHORTS:
|
| 129 |
+
roots = {"base": F / ds / "pooled", "sc": F / ds / "scsemi_cv_20261002/pooled"}
|
| 130 |
+
manifest = {k: b.js(p / "manifest.json") for k, p in roots.items()}
|
| 131 |
+
for key in ["donors", "contrast", "reference_sha256", "n_genes_disease_scores", "genes_per_type", "gene_exclusion", "deg_reference"]:
|
| 132 |
+
assert manifest["base"][key] == manifest["sc"][key], (ds, key)
|
| 133 |
+
for j in manifest.values():
|
| 134 |
+
assert j["repro_all_pass"] is True and j["params"]["rbo_p"] == .98
|
| 135 |
+
tables = {k: {name: b.csv(p / f"{name}.csv") for name in ["headline", "cat", "rbo", "contrast", "ceiling"]}
|
| 136 |
+
for k, p in roots.items()}
|
| 137 |
+
for method in METHODS:
|
| 138 |
+
if method == "full" and ds != "ye2026_sepsis":
|
| 139 |
+
continue
|
| 140 |
+
arm = "zs__raw" if method == "broadcast" else ARMS[method]
|
| 141 |
+
key = "sc" if method == "scsemi" else "base"
|
| 142 |
+
assert manifest[key]["arms"][arm]["receipt_verified"] is True
|
| 143 |
+
h = tables[key]["headline"].set_index("arm").loc[arm]
|
| 144 |
+
assert bool(h.repro_pass)
|
| 145 |
+
pred = f"broadcast:{h.condition}" if method == "broadcast" else f"generated:{arm}"
|
| 146 |
+
cat = tables[key]["cat"].query("arm == @arm and predictor == @pred")
|
| 147 |
+
assert set(cat.celltype) == CT5 and cat.pred_defined.all()
|
| 148 |
+
assert set(cat.k) == {10, 20, 50, 100, 200, 500} and (cat.k_eff == cat.k).all()
|
| 149 |
+
g = cat.groupby("k").agg(value=("cat_same_sign", "mean"), chance=("chance_same_sign", "mean"),
|
| 150 |
+
n_types=("celltype", "nunique"), tested_genes_min=("G_both", "min"), tested_genes_max=("G_both", "max")).reset_index()
|
| 151 |
+
assert (g.n_types == 5).all()
|
| 152 |
+
prefix = "broadcast_" if method == "broadcast" else ""
|
| 153 |
+
assert np.isclose(float(g.loc[g.k == 100, "value"].iloc[0]), h[prefix + "cat100"], atol=1e-12)
|
| 154 |
+
rbo = tables[key]["rbo"].query("arm == @arm and predictor == @pred")
|
| 155 |
+
assert set(rbo.celltype) == CT5 and rbo.pred_defined.all()
|
| 156 |
+
assert np.isclose(rbo.rbo_ext_mean_up_down.mean(), h[prefix + "rbo_up_down"], atol=1e-12)
|
| 157 |
+
contrast = tables[key]["contrast"].query("arm == @arm and statistic == 'mean_cp10k'")
|
| 158 |
+
contrast = contrast.loc[contrast.celltype.isin(CT4)]
|
| 159 |
+
assert set(contrast.celltype) == CT4
|
| 160 |
+
field = "pearson_r_broadcast" if method == "broadcast" else "pearson_r_generated"
|
| 161 |
+
assert np.isclose(contrast[field].mean(), h[prefix + "pearson_r"], atol=1e-12)
|
| 162 |
+
heads.append(dict(dataset=ds, method=method, arm=arm, pearson_r=float(h[prefix + "pearson_r"]),
|
| 163 |
+
partial_r=np.nan if method == "broadcast" else float(h.partial_r),
|
| 164 |
+
rbo_up_down=float(h[prefix + "rbo_up_down"]), cat100=float(h[prefix + "cat100"]),
|
| 165 |
+
split_half_cell_repeat_r=float(h.splithalf_r_AB), n_samples=manifest[key]["n_samples"]))
|
| 166 |
+
curves.append(g.assign(dataset=ds, method=method, arm=arm, source=str(roots[key] / "cat.csv")))
|
| 167 |
+
for arm in manifest["base"]["arms"]:
|
| 168 |
+
if arm not in set(ARMS.values()):
|
| 169 |
+
b.inventory.append(dict(dataset=ds, arm=arm, status="not in common all-pair measured-bulk comparator family",
|
| 170 |
+
reason="support-budget/recipe ablation or sc-only/oracle pseudobulk control; retained in original evidence deck"))
|
| 171 |
+
contracts.append(dict(dataset=ds, samples=manifest["base"]["n_samples"],
|
| 172 |
+
contrast=manifest["base"]["contrast"], scoring_genes=manifest["base"]["genes_per_type"],
|
| 173 |
+
reference_sha256=manifest["base"]["reference_sha256"], same_scsemi_evaluation_contract=True,
|
| 174 |
+
caveat="Historical pooled five-fold CV; Imperial sample/visit rows are not independent patients; Giroux sex-gene exclusion does not remove confounding."))
|
| 175 |
+
return pd.DataFrame(heads), pd.concat(curves, ignore_index=True), contracts
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def cv_figures(b, h, c):
|
| 179 |
+
caveat = ("Historical pooled five-fold CV, all available training pairs with inner-validation access; not strict-five support. "
|
| 180 |
+
"Methods share each cohort's scored sample set, disease contrast, reference, observed detection mask and gene exclusions. "
|
| 181 |
+
"Imperial repeated sample/visit rows remain a historical estimand, not independent patients. Giroux excludes recorded sex-linked genes "
|
| 182 |
+
"but this does not remove sex/severity confounding or establish causal disease effects. The common deployable comparator family is "
|
| 183 |
+
"raw/calibrated zero-shot, all-pair LoRA and scSemiProfiler, with raw-bulk broadcast as a null; Sepsis full FT is additionally shown. "
|
| 184 |
+
"Other budget/recipe/sc-only/oracle arms are recorded in the inventory and retained in the original deck. BayesPrism/CIBERSORTx results "
|
| 185 |
+
"belong to different saved support/endpoint contracts and are not silently merged. CAT and RBO average five types (T/B/Monocyte/NK/DC); "
|
| 186 |
+
"Pearson and partial-r average four types (T/B/Monocyte/NK). CAT ranks limma-voom primary nonzero-filter genes by absolute moderated t, "
|
| 187 |
+
"requires matching logFC sign, and is plotted at k=10/20/50/100/200/500. Tested ranking universes can differ by method; counts are retained. "
|
| 188 |
+
"RBO is extrapolated Eq.32 at p=.98, averaging ascending/descending t rankings. Partial r removes each arm's own condition-specific "
|
| 189 |
+
"bulk-broadcast vector by linear residualization; broadcast versus itself is undefined and omitted, not zero. Observed-repeat r splits "
|
| 190 |
+
"the same samples' cells, so it is a conditional cell-resampling reference, not an independent-patient ceiling or CI. No new test, fit or generation.")
|
| 191 |
+
fig, axes = plt.subplots(2, 2, figsize=ST.FULL)
|
| 192 |
+
fig.subplots_adjust(left=.075, right=.985, bottom=.145, top=.79, hspace=.43, wspace=.25)
|
| 193 |
+
ymax = min(1, np.ceil(c.value.max() * 10 + .5) / 10)
|
| 194 |
+
for ax, ds in zip(axes.flat, COHORTS):
|
| 195 |
+
for method in METHODS:
|
| 196 |
+
q = c.loc[(c.dataset == ds) & (c.method == method)]
|
| 197 |
+
if q.empty:
|
| 198 |
+
continue
|
| 199 |
+
ax.plot(np.arange(6), q.value, color=COL[method], marker=MARK[method], ms=5,
|
| 200 |
+
mec="#4D4D4D", mew=.45, mfc="white" if method in {"cal", "full"} else COL[method],
|
| 201 |
+
lw=2.2 if method == "lora" else 1.6, ls="--" if method in {"cal", "full", "broadcast"} else "-")
|
| 202 |
+
ax.set_title(NAMES[ds], loc="left", fontsize=14)
|
| 203 |
+
ax.set_xticks(range(6), [10, 20, 50, 100, 200, 500], fontsize=11)
|
| 204 |
+
ax.set_ylim(0, ymax); ax.grid(axis="y", color="#E6E6E6", lw=.6); ax.set_axisbelow(True)
|
| 205 |
+
legend(fig)
|
| 206 |
+
fig.text(.015, .46, "Same-sign top-k overlap (CAT)", va="center", rotation=90, fontsize=13)
|
| 207 |
+
fig.text(.53, .065, "Ranked genes per list (k) · mean over T, B, Monocyte, NK and DC", ha="center", fontsize=12)
|
| 208 |
+
b.figure(fig, "cv_complete_cat", "Disease gene rankings: complete CV comparison",
|
| 209 |
+
"Historical 5-fold CV; mean over five types. All saved scSemi curves included. Imperial retains visit-level sampling; not a strict-five result.", caveat,
|
| 210 |
+
"Same-sign correspondence at the top; all four disease cohorts")
|
| 211 |
+
|
| 212 |
+
fig, axes = plt.subplots(1, 3, figsize=ST.FULL, sharey=True)
|
| 213 |
+
fig.subplots_adjust(left=.135, right=.98, top=.77, bottom=.15, wspace=.25)
|
| 214 |
+
offsets = dict(zip(METHODS, np.linspace(-.25, .25, len(METHODS))))
|
| 215 |
+
for ax, metric, label in zip(axes, ["pearson_r", "partial_r", "rbo_up_down"],
|
| 216 |
+
["LogFC Pearson r", "Partial r | bulk", "Rank agreement (RBO)"]):
|
| 217 |
+
for method in METHODS:
|
| 218 |
+
q = h.loc[h.method == method]
|
| 219 |
+
y = np.array([COHORTS.index(ds) for ds in q.dataset]) + offsets[method]
|
| 220 |
+
ax.scatter(q[metric], y, color=COL[method], marker=MARK[method], s=53,
|
| 221 |
+
edgecolors="#4D4D4D" if MARK[method] != "x" else None, linewidths=.55, zorder=3)
|
| 222 |
+
if metric == "pearson_r":
|
| 223 |
+
q = h.loc[h.method == "lora"]
|
| 224 |
+
ax.scatter(q.split_half_cell_repeat_r, [COHORTS.index(ds) for ds in q.dataset], color="#4D4D4D", marker="|", s=220, linewidths=2)
|
| 225 |
+
ax.set_title(label, fontsize=14)
|
| 226 |
+
ax.set_xlim((-.15, 1) if metric != "rbo_up_down" else (0, .48))
|
| 227 |
+
ax.axvline(0, color="#D0D0D0", lw=.8); ax.grid(axis="x", color="#E6E6E6", lw=.6); ax.set_axisbelow(True)
|
| 228 |
+
ax.set_yticks(range(4), [NAMES[d] for d in COHORTS]); ax.set_ylim(3.5, -.5)
|
| 229 |
+
legend(fig, extra=(Line2D([], [], color="#4D4D4D", marker="|", ms=12, ls="none"), "Observed cell-repeat r"))
|
| 230 |
+
fig.text(.55, .055, "No CI shown · observed repeat uses the same patients · broadcast partial r is undefined", ha="center", fontsize=11)
|
| 231 |
+
b.figure(fig, "cv_multimetric", "Disease integrity depends on cohort and endpoint",
|
| 232 |
+
"Historical 5-fold CV. r: four types; RBO: five types, p=0.98. Gray repeat markers reflect same-patient cell resampling, not independent ceilings.", caveat,
|
| 233 |
+
"Correlation, bulk-adjusted correlation and rank agreement")
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
def strict_sepsis(b):
|
| 237 |
+
protocol = b.js(P / "protocol/PROTOCOL.json", "strict experiment definition")
|
| 238 |
+
assert protocol["strict_pairs"] == "one_sample_per_unique_donor" and protocol["lora_fixed_steps"] == 3000
|
| 239 |
+
rows, deg_rows, units = [], [], []
|
| 240 |
+
arms = ["raw", "refcal", "pairedcal", "scsemi", "lora"]
|
| 241 |
+
for draw in range(5):
|
| 242 |
+
receipt = b.js(P / f"receipts/ye2026_sepsis-disease-draw{draw}-score.json", "completed scoring receipt")
|
| 243 |
+
assert receipt["state"] == "completed"
|
| 244 |
+
for item in receipt["outputs"]:
|
| 245 |
+
p = b.source(item["path"], "receipt-bound completed output")
|
| 246 |
+
assert sha(p) == item["sha256"] and p.stat().st_size == item["bytes"]
|
| 247 |
+
support = b.js(P / f"protocol/splits/ye2026_sepsis/disease/draw{draw}/support.json", "exact support and held-out identity")
|
| 248 |
+
body = {k: v for k, v in support.items() if k != "sha256"}
|
| 249 |
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
| 250 |
+
assert digest == support["sha256"] and len(set(support["train_sample_ids"])) == len(set(support["train_donor_ids"])) == 5
|
| 251 |
+
assert set(support["train_donor_ids"]).isdisjoint(support["test_donor_ids"])
|
| 252 |
+
base = P / f"scores/ye2026_sepsis/disease/draw{draw}"
|
| 253 |
+
status = b.js(base / "statistics/status.json")
|
| 254 |
+
assert status["support_sha256"] == digest and status["disease_deg"]["status"] == "ok"
|
| 255 |
+
con = base / "contrast/ye2026_sepsis/strict"
|
| 256 |
+
manifest = b.js(con / "manifest.json")
|
| 257 |
+
assert set(manifest["donors"]) == set(support["test_sample_ids"])
|
| 258 |
+
assert manifest["repro_all_pass"] is True
|
| 259 |
+
h = b.csv(con / "headline.csv")
|
| 260 |
+
assert set(h.arm) == set(arms) and h.repro_pass.all()
|
| 261 |
+
d = b.csv(base / "statistics/donor_deg/donor_deg_summary.csv", "completed donor-aware DEG summary; frozen/hash-bound here")
|
| 262 |
+
assert set(d.arm) == set(arms) and (d.status == "ok").all()
|
| 263 |
+
for arm in arms:
|
| 264 |
+
assert set(d.loc[d.arm == arm, "celltype"]) == CT5
|
| 265 |
+
assert manifest["arms"][arm]["receipt_verified"] is True
|
| 266 |
+
z = h.set_index("arm").loc[arm]
|
| 267 |
+
dd = d.loc[d.arm == arm]
|
| 268 |
+
assert (dd.method_observed == "edgeR_TMM_limma_voom").all() and (dd.method_generated == "edgeR_TMM_limma_voom").all()
|
| 269 |
+
rows.append(dict(draw=draw, arm=arm, pearson_r=float(z.pearson_r), partial_r=float(z.partial_r),
|
| 270 |
+
cat100=float(z.cat100), rbo_up_down=float(z.rbo_up_down),
|
| 271 |
+
donor_deg_top50=float(dd.top50_overlap_count.sum()),
|
| 272 |
+
observed_list_total=float(dd.observed_top50_size.sum()),
|
| 273 |
+
split_half_cell_repeat_r=float(z.splithalf_r_AB)))
|
| 274 |
+
deg_rows.append(d.assign(draw=draw))
|
| 275 |
+
units.append(dict(draw=draw, support_sha256=digest, n_test_samples=len(support["test_sample_ids"]),
|
| 276 |
+
n_test_donors=len(set(support["test_donor_ids"])), receipt_at=receipt["at"]))
|
| 277 |
+
data = pd.DataFrame(rows)
|
| 278 |
+
b.table(data, "strict_sepsis_per_draw.csv")
|
| 279 |
+
b.table(pd.concat(deg_rows), "strict_sepsis_donor_deg_by_type.csv")
|
| 280 |
+
mean = data.groupby("arm").mean(numeric_only=True).drop(columns="draw").reset_index()
|
| 281 |
+
b.table(mean, "strict_sepsis_mean.csv")
|
| 282 |
+
fig, axes = plt.subplots(1, 4, figsize=ST.FULL, sharey=True)
|
| 283 |
+
fig.subplots_adjust(left=.17, right=.985, top=.86, bottom=.17, wspace=.30)
|
| 284 |
+
metrics = ["pearson_r", "partial_r", "cat100", "donor_deg_top50"]
|
| 285 |
+
titles = ["LogFC r", "Partial r | bulk", "CAT at k = 100", "Donor-aware DEG"]
|
| 286 |
+
for ax, metric, title in zip(axes, metrics, titles):
|
| 287 |
+
for y, arm in enumerate(arms):
|
| 288 |
+
q = data.loc[data.arm == arm].sort_values("draw")
|
| 289 |
+
ax.scatter(q[metric], y + np.linspace(-.16, .16, 5), s=24, color=COL[arm], edgecolors="#4D4D4D", linewidths=.35, alpha=.8)
|
| 290 |
+
ax.scatter([q[metric].mean()], [y], marker="D", s=79, color=COL[arm], edgecolors="#303030", linewidths=.9, zorder=5)
|
| 291 |
+
ax.set_title(title, fontsize=13)
|
| 292 |
+
ax.set_yticks(range(5), [LAB[a] for a in arms], fontsize=12)
|
| 293 |
+
ax.set_ylim(4.55, -.55); ax.grid(axis="x", color="#E5E5E5", lw=.6); ax.set_axisbelow(True)
|
| 294 |
+
ax.axvline(0, color="#C4C4C4", lw=.8)
|
| 295 |
+
if metric in {"pearson_r", "partial_r"}: ax.set_xlim(-.18, .7)
|
| 296 |
+
if metric == "cat100": ax.set_xlim(0, .18)
|
| 297 |
+
if metric == "donor_deg_top50": ax.set_xlim(0, 30); ax.set_xlabel("Overlap count", fontsize=11.5)
|
| 298 |
+
fig.text(.58, .97, "Sepsis · five total support pairs · five completed support draws", ha="center", fontsize=13)
|
| 299 |
+
fig.text(.57, .076, "Small dots: saved support draws; large diamonds: descriptive mean (not a confidence interval)", ha="center", fontsize=11)
|
| 300 |
+
fig.text(.57, .022, "r: T/B/Monocyte/NK; CAT and DEG: these four types + DC. Raw/reference calibration need no target pairs.", ha="center", fontsize=10.5, color="#4D4D4D")
|
| 301 |
+
note = ("Frozen Sepsis draws 0–4 only; every draw has a completed scoring receipt with verified byte sizes and SHA-256 values. "
|
| 302 |
+
"Each support has exactly five unique samples from five unique donors, no held-out donor overlap. Strict protocol uses fixed 3000 LoRA steps, "
|
| 303 |
+
"one sample per donor, no extra target validation selection; paired calibration/scSemi share support. Raw and external-reference calibration "
|
| 304 |
+
"are zero-target-pair controls. Reference calibration additionally anchors on unlabelled target bulks, so information access differs as specified "
|
| 305 |
+
"in the saved protocol. Each point is one support draw; donors overlap across draws and dots are not independent biological replicates. "
|
| 306 |
+
"Diamonds are descriptive means, not CI or statistical tests. All five saved generator arms included. Pearson/partial r average four cell types; "
|
| 307 |
+
"CAT100 averages five. DEG sums top-50 overlap over T/B/Monocyte/NK/DC after existing donor-condition pseudobulk edgeR-TMM limma-voom fits, "
|
| 308 |
+
"nonzero gene filter and BH FDR<.05, ranked by absolute logFC; overlaps do not themselves enforce same direction. The theoretical upper bound "
|
| 309 |
+
"is 250, but the actual observed significant-list total is saved for each draw and can be lower. CAT is same-sign moderated-t ranking agreement, "
|
| 310 |
+
"not FDR significance. Ranking universes may differ by method. No new DEG fit, array scoring, training or inference. Receipt outputs directly bind "
|
| 311 |
+
"status and contrast manifests; the referenced numerical CSVs are additionally frozen and SHA-bound by this figure bundle, not claimed to have an "
|
| 312 |
+
"original receipt hash they never had. Other cohorts and deconvolution endpoint families are not combined with this completed Sepsis subset.")
|
| 313 |
+
b.figure(fig, "strict_sepsis_multimetric", "Five-pair Sepsis: metrics across all support draws",
|
| 314 |
+
"Sepsis draws 0–4 only; five total support pairs. Points show overlapping support draws, not independent replicates or CI. Donor-aware DEG reused.", note,
|
| 315 |
+
"Complete Sepsis subset; no inference across unfinished cohorts")
|
| 316 |
+
return units
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def build():
|
| 320 |
+
b = Build()
|
| 321 |
+
b.source(Path(__file__), "CPU-only aggregation and rendering script")
|
| 322 |
+
b.source(D / "tools/style.py", "Arial slide typography; colors applied locally")
|
| 323 |
+
b.source(D / "PBISC-Diffusion_color_palette_20261013.md", "approved method colors")
|
| 324 |
+
b.source(D / "data/figure_assignment_20261013/AUTHOR_SCOPE.md", "author-defined figure scope")
|
| 325 |
+
proposal = D / "data/strengthening_20261013/STRENGTHENING_PROPOSAL_before_revision.md"
|
| 326 |
+
assert sha(proposal) == "991d3fe0800c88f99a020f65f08c2ed5942481b55422e210ca9160e4561b435a", "Original proposal snapshot changed"
|
| 327 |
+
b.source(proposal, "frozen original proposal read for this analysis, before the root-authored revision")
|
| 328 |
+
for p in [F.parent / "tools/contrast_extra.py", P / "tools/score_strict.py", P / "tools/donor_statistics.py", P / "tools/donor_limma.R"]:
|
| 329 |
+
b.source(p, "saved metric implementation; not executed")
|
| 330 |
+
refroot = Path("/home/sj_server_1/PBISC/paper-release-20260928/reference-papers/evaluation-metrics")
|
| 331 |
+
for n in ["Irizarry2005_Multiple_laboratory_comparison_microarray_platforms.pdf", "Webber2010_Rank_biased_overlap_similarity_indefinite_rankings.pdf"]:
|
| 332 |
+
b.source(refroot / n, "original metric paper checked against implementation")
|
| 333 |
+
h, c, contracts = cv_inputs(b)
|
| 334 |
+
b.table(h, "cv_multimetric.csv"); b.table(c, "cv_cat_complete.csv")
|
| 335 |
+
cv_figures(b, h, c)
|
| 336 |
+
units = strict_sepsis(b)
|
| 337 |
+
for ds in COHORTS:
|
| 338 |
+
b.inventory.append(dict(dataset=ds, method="BayesPrism/CIBERSORTx", status="not merged with CV or strict-generator family",
|
| 339 |
+
reason="existing results use a separate support/endpoint evaluation contract; no matching CV CAT/RBO was supplied"))
|
| 340 |
+
for item in b.sources.values():
|
| 341 |
+
assert sha(Path(item["path"])) == item["sha256"], ("input changed while building", item["path"])
|
| 342 |
+
result = dict(schema="pbisc.strengthening.disease_metrics.v1", built_utc=datetime.now(timezone.utc).isoformat(),
|
| 343 |
+
slides=b.slides, panels=b.slides, sources=list(b.sources.values()), assets=b.assets,
|
| 344 |
+
metric_references=REFERENCES, cv_comparison_contracts=contracts, strict_sepsis_units=units,
|
| 345 |
+
exclusions=b.inventory, scope="Descriptive redraw of saved metrics; historical CV and total-five Sepsis remain separate",
|
| 346 |
+
proof_scope="Exact source hashing and frozen CSV/JSON snapshots plus original completion metadata; no raw generated-array or checkpoint revalidation")
|
| 347 |
+
out = DATA / "result.json"
|
| 348 |
+
out.write_text(json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False) + "\n")
|
| 349 |
+
return result
|
| 350 |
+
|
| 351 |
+
|
| 352 |
+
if __name__ == "__main__":
|
| 353 |
+
r = build()
|
| 354 |
+
print(json.dumps(dict(slides=len(r["slides"]), sources=len(r["sources"]), assets=len(r["assets"]))))
|
paper-releases/pbisc-diffusion/updates/20261013T115045Z-figure-strengthening-154/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/strengthen_healthy_adaptation_20261013.py
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Saved donor-level adaptation evidence and verified historical split diagram."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import ast
|
| 4 |
+
import hashlib
|
| 5 |
+
import json
|
| 6 |
+
import os
|
| 7 |
+
import sys
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
|
| 11 |
+
raise SystemExit('CPU-only: set CUDA_VISIBLE_DEVICES empty')
|
| 12 |
+
D = Path(__file__).resolve().parents[1]
|
| 13 |
+
M = D.parents[1]
|
| 14 |
+
F = M / 'plans/paired_finetune_intradataset_20260927'
|
| 15 |
+
A = D / 'data/strengthening_20261013/healthy'
|
| 16 |
+
O = D / 'figures/strengthening_20261013/healthy'
|
| 17 |
+
sys.path.insert(0, str(D / 'tools'))
|
| 18 |
+
import style
|
| 19 |
+
import matplotlib.pyplot as plt
|
| 20 |
+
from matplotlib.patches import Patch, Rectangle
|
| 21 |
+
TYPES = ['T cell', 'B cell', 'Monocyte', 'NK cell', 'DC', 'Other']
|
| 22 |
+
# Biological colours, deliberately distinct from method colours.
|
| 23 |
+
CELL_COLOURS = ['#0072B2', '#D55E00', '#009E73', '#CC79A7', '#E69F00', '#56B4E9']
|
| 24 |
+
ARMS = [('zs__raw', 'Raw zero-shot', '#C3E2F4'),
|
| 25 |
+
('zs__cal', 'Input calibration', '#59A8DF'),
|
| 26 |
+
('real_full__raw', 'Full fine-tuning', '#0D6EA8'),
|
| 27 |
+
('real_lora__raw', 'LoRA r16', '#168FE5')]
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def sha(p):
|
| 31 |
+
with Path(p).open('rb') as f:
|
| 32 |
+
return hashlib.file_digest(f, 'sha256').hexdigest()
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def save(fig, name):
|
| 36 |
+
for ext in ['png', 'pdf', 'svg']:
|
| 37 |
+
fig.savefig(O / f'{name}.{ext}', dpi=200)
|
| 38 |
+
plt.close(fig)
|
| 39 |
+
return str((O / f'{name}.png').relative_to(D))
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def record(title, figure, footnote, details):
|
| 43 |
+
return dict(kind='content', title=title, figures=[figure], layout='full', keywords=[],
|
| 44 |
+
section='Figure 3', deck_group='Figure 3', section_label='Fig. 3 · Adaptation',
|
| 45 |
+
footnote=footnote, footnote_full=details, sources=str(F / 'scores/immicro/pooled/per_donor.csv'))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def main():
|
| 49 |
+
A.mkdir(parents=True, exist_ok=True)
|
| 50 |
+
O.mkdir(parents=True, exist_ok=True)
|
| 51 |
+
p = F / 'scores/immicro/pooled/per_donor.csv'
|
| 52 |
+
d = pd.read_csv(p)
|
| 53 |
+
scorer_summary = json.loads((p.parent/'summary.json').read_text())
|
| 54 |
+
selected = d[d.arm.isin([x[0] for x in ARMS])].copy()
|
| 55 |
+
raw = selected[selected.arm == 'zs__raw'].set_index('donor')
|
| 56 |
+
# Ordering depends only on the observed reference, never method performance.
|
| 57 |
+
order = raw.sort_values(['obs_Monocyte', 'obs_T cell'], kind='stable').index
|
| 58 |
+
obs = raw.loc[order, ['obs_' + t for t in TYPES]].to_numpy()
|
| 59 |
+
assert len(order) == len(set(order)) == 107
|
| 60 |
+
assert np.allclose(obs.sum(1), 1)
|
| 61 |
+
matrices = []
|
| 62 |
+
summary = []
|
| 63 |
+
for arm, title, colour in ARMS:
|
| 64 |
+
assert scorer_summary['per_arm'][arm]['receipt_verified']
|
| 65 |
+
assert scorer_summary['per_arm'][arm]['pseudobulk']['n_genes'] == 5508
|
| 66 |
+
q = selected[selected.arm == arm].set_index('donor').loc[order]
|
| 67 |
+
assert len(q) == 107 and np.allclose(q[['obs_' + t for t in TYPES]], obs)
|
| 68 |
+
assert q.n_generated_cells.eq(1500).all()
|
| 69 |
+
mat = q[['gen_' + t for t in TYPES]].to_numpy()
|
| 70 |
+
assert np.allclose(mat.sum(1), 1)
|
| 71 |
+
assert np.allclose(np.abs(mat - obs).sum(1), q.comp_l1)
|
| 72 |
+
matrices.append(mat)
|
| 73 |
+
summary.append({'arm': arm, 'n_donors': len(q), 'composition_l1_mean': float(q.comp_l1.mean()),
|
| 74 |
+
'fraction_mae_pp': float(np.abs(mat - obs).mean() * 100),
|
| 75 |
+
'pb_r_median': float(q.pb_r.median())})
|
| 76 |
+
selected.to_csv(A / 'matched_donor_metrics.csv', index=False)
|
| 77 |
+
pd.DataFrame({'position': np.arange(1, 108), 'donor': order}).to_csv(A / 'observed_only_order.csv', index=False)
|
| 78 |
+
pd.DataFrame(summary).to_csv(A / 'summary.csv', index=False)
|
| 79 |
+
fig, axes = plt.subplots(5, 1, figsize=style.FULL, sharex=True)
|
| 80 |
+
for ax, values, label in zip(axes, [obs] + matrices, ['Observed paired scRNA'] + [x[1] for x in ARMS]):
|
| 81 |
+
bottom = np.zeros(107)
|
| 82 |
+
for j, (t, c) in enumerate(zip(TYPES, CELL_COLOURS)):
|
| 83 |
+
ax.bar(np.arange(107), values[:, j] * 100, bottom=bottom, width=1, color=c, linewidth=0)
|
| 84 |
+
bottom += values[:, j] * 100
|
| 85 |
+
ax.set_ylim(0, 100)
|
| 86 |
+
ax.set_yticks([0, 100], ['0', '100%'], fontsize=9)
|
| 87 |
+
ax.text(-.09, .5, label, transform=ax.transAxes, ha='right', va='center', fontsize=11)
|
| 88 |
+
ax.tick_params(axis='x', length=0)
|
| 89 |
+
ax.spines[['top', 'right', 'bottom']].set_visible(False)
|
| 90 |
+
axes[-1].set_xticks([0, 26, 53, 80, 106], ['1', '27', '54', '81', '107'])
|
| 91 |
+
axes[-1].set_xlabel('Same 107 held-out donors, ordered by observed monocyte fraction', fontsize=12)
|
| 92 |
+
axes[0].set_xlim(-.5, 106.5)
|
| 93 |
+
fig.legend([Patch(color=c) for c in CELL_COLOURS], TYPES, ncol=6, loc='upper center', fontsize=11,
|
| 94 |
+
bbox_to_anchor=(.60, 1.015))
|
| 95 |
+
fig.subplots_adjust(left=.235, right=.99, bottom=.105, top=.905, hspace=.22)
|
| 96 |
+
stack = save(fig, 'same_donors_composition')
|
| 97 |
+
details = ('Same 107 ImMicro healthy donors, pooled five-fold held-out predictions and six frozen broad cell types. '
|
| 98 |
+
'Every donor and type retained; display order uses observed monocyte fraction only. Each generated arm has '
|
| 99 |
+
'1500 cells/sample; observed fractions use all available scored observed cells. Full FT and LoRA consume the '
|
| 100 |
+
'raw measured-bulk input, as does raw zero-shot. Input calibration is a separate comparator. Adaptation '
|
| 101 |
+
'improves generated-cell composition; it does not change the measured bulk or establish that every '
|
| 102 |
+
'transcriptional mismatch disappears. Historical training has 78–79 train plus 7 inner-validation pairs/fold. '
|
| 103 |
+
'No new training, inference, annotation, or scoring; this reuses saved donor metrics.')
|
| 104 |
+
slides = [record('Adaptation recovers the observed cell mixture', stack,
|
| 105 |
+
'Same 107 held-out donors in every row. Full FT / LoRA use raw measured bulk; colours identify cell types.', details)]
|
| 106 |
+
# Two donor-matched outcome views; no fitted projection and no selected successes.
|
| 107 |
+
fig, axes = plt.subplots(1, 2, figsize=style.FULL)
|
| 108 |
+
for ax, col, ylabel, reference in zip(axes, ['comp_l1', 'pb_r'],
|
| 109 |
+
['Cell-mixture error (L1; lower is better)',
|
| 110 |
+
'Generated vs observed gene-expression r'], [0, 1]):
|
| 111 |
+
vals = np.array([selected[selected.arm == arm].set_index('donor').loc[order, col].to_numpy() for arm, _, _ in ARMS])
|
| 112 |
+
for i in range(107):
|
| 113 |
+
ax.plot(range(4), vals[:, i], color='#D6DCE1', lw=.5, alpha=.55, zorder=1)
|
| 114 |
+
for i, (_, _, colour) in enumerate(ARMS):
|
| 115 |
+
jitter = np.random.default_rng(20261013).uniform(-.11, .11, 107)
|
| 116 |
+
ax.scatter(i+jitter, vals[i], s=9, color=colour, edgecolors='none', zorder=2)
|
| 117 |
+
med = float(np.median(vals[i]))
|
| 118 |
+
ax.plot([i-.18, i+.18], [med, med], color='#202D35', lw=2.3, zorder=3)
|
| 119 |
+
ax.text(i, 1.035, f'{med:.3f}', transform=ax.get_xaxis_transform(), ha='center', fontsize=12)
|
| 120 |
+
ax.set_xticks(range(4), ['Raw', 'Calibration', 'Full FT', 'LoRA r16'], fontsize=11)
|
| 121 |
+
ax.set_ylabel(ylabel, fontsize=12)
|
| 122 |
+
ax.axhline(reference, color='#8B959C', lw=.8, ls='--')
|
| 123 |
+
ax.set_ylim((0, max(1, float(np.max(vals))*1.04)) if col == 'comp_l1' else (min(.4, float(np.min(vals))-.02), 1.02))
|
| 124 |
+
ax.set_xlim(-.45, 3.45)
|
| 125 |
+
ax.grid(axis='y', color='#EDF0F2', lw=.6)
|
| 126 |
+
fig.text(.5, .97, 'Same-donor trajectories · dark bars and labels = medians', ha='center', fontsize=12)
|
| 127 |
+
fig.subplots_adjust(left=.075, right=.99, bottom=.14, top=.85, wspace=.29)
|
| 128 |
+
metric = save(fig, 'same_donors_output_recovery')
|
| 129 |
+
slides.append(record('Adaptation: mixture error and expression agreement', metric,
|
| 130 |
+
'107 matched donors; lines connect the same person. Gene-expression r is a donor pseudobulk Pearson correlation.',
|
| 131 |
+
details + ' Error = sum across six types of absolute fraction differences. Expression r is saved pb_r, '
|
| 132 |
+
'the per-donor Pearson correlation of log1p-CPM(summed generated expression rates) versus '
|
| 133 |
+
'log1p-CPM(observed pseudobulk) on the same 5,508 scorer genes; '
|
| 134 |
+
'not cell-wise correspondence. Lines are not diffusion trajectories. No significance tests.'))
|
| 135 |
+
# Reproduce receipts, nested selection, and exact donor non-overlap.
|
| 136 |
+
folds = pd.read_csv(F / 'data/immicro/folds.csv')
|
| 137 |
+
prep = json.loads((F / 'data/immicro/PREPARE.json').read_text())
|
| 138 |
+
# Execute only the archived pure split function, avoiding training imports.
|
| 139 |
+
tree = ast.parse((F/'tools/prepare_dataset.py').read_text())
|
| 140 |
+
fn = next(node for node in tree.body if isinstance(node, ast.FunctionDef) and node.name == 'make_folds')
|
| 141 |
+
namespace = {'np': np, 'pd': pd}
|
| 142 |
+
exec(compile(ast.Module(body=[fn], type_ignores=[]), 'saved_make_folds', 'exec'), namespace)
|
| 143 |
+
replay = namespace['make_folds'](
|
| 144 |
+
{'sample_ids':folds.sample_id.to_numpy(), 'donor_ids':folds.donor_id.to_numpy(),
|
| 145 |
+
'groups':folds.group.to_numpy(), 'use':folds.fold.ge(0).to_numpy()},
|
| 146 |
+
prep['folds'], prep['seed'], prep['inner_frac'])
|
| 147 |
+
pd.testing.assert_frame_equal(folds, replay, check_dtype=False)
|
| 148 |
+
sources = [p, F/'data/immicro/folds.csv', F/'data/immicro/PREPARE.json',
|
| 149 |
+
F/'tools/prepare_dataset.py', F/'tools/ft_sdd.py', F/'tools/score_ft.py',p.parent/'summary.json']
|
| 150 |
+
audits = []
|
| 151 |
+
roles = []
|
| 152 |
+
for fold in range(5):
|
| 153 |
+
test = set(folds.loc[folds.fold == fold, 'sample_id'])
|
| 154 |
+
inner = set(folds.loc[folds[f'inner_val_f{fold}'], 'sample_id'])
|
| 155 |
+
pool = set(folds.sample_id) - test - inner
|
| 156 |
+
previous = set()
|
| 157 |
+
for budget in [5, 10, 20, 40, 'all']:
|
| 158 |
+
rp = F/f'runs/immicro/fold{fold}'/('real_lora' if budget == 'all' else f'lora_n{budget}')/'RUN.json'
|
| 159 |
+
sources.append(rp)
|
| 160 |
+
run = json.loads(rp.read_text())
|
| 161 |
+
tr = set(run['train_rows']); va = set(run['inner_val_rows']); te = set(run['test_rows_never_loaded_for_training'])
|
| 162 |
+
assert te == test and va == inner and not tr & (te|va) and tr <= pool
|
| 163 |
+
assert previous <= tr
|
| 164 |
+
if budget != 'all':
|
| 165 |
+
subset = run['train_subset']
|
| 166 |
+
assert not subset['strata_regex']
|
| 167 |
+
pool_rows = folds.index[folds.sample_id.isin(pool)].to_numpy()
|
| 168 |
+
perm = np.random.default_rng(subset['subset_seed']).permutation(len(pool_rows))
|
| 169 |
+
replay = set(folds.loc[pool_rows[perm[:budget]], 'sample_id'])
|
| 170 |
+
assert tr == replay and len(tr) == budget
|
| 171 |
+
else:
|
| 172 |
+
assert tr == pool
|
| 173 |
+
unused = pool-tr
|
| 174 |
+
audits.append(dict(fold=fold, budget=budget, train=len(tr), validation=len(va), test=len(te), unused=len(unused),
|
| 175 |
+
subset_seed=(run.get('train_subset') or {}).get('subset_seed'),
|
| 176 |
+
no_overlap=True, nested=True, receipt=str(rp)))
|
| 177 |
+
for donor in folds.sample_id:
|
| 178 |
+
roles.append(dict(fold=fold,budget=budget,donor=donor,
|
| 179 |
+
role='train' if donor in tr else 'validation' if donor in va else 'test' if donor in te else 'unused'))
|
| 180 |
+
previous=tr
|
| 181 |
+
pd.DataFrame(audits).to_csv(A/'split_audit.csv',index=False)
|
| 182 |
+
pd.DataFrame(roles).to_csv(A/'donor_roles.csv',index=False)
|
| 183 |
+
fig, ax=plt.subplots(figsize=style.FULL)
|
| 184 |
+
ax.axis('off');ax.set_xlim(0,107);ax.set_ylim(-.7,5.2)
|
| 185 |
+
split_colours={'train':'#168FE5','validation':'#D9B23F','unused':'#EDF0F2','test':'#56646E'}
|
| 186 |
+
for row,budget in enumerate([5,10,20,40,'all']):
|
| 187 |
+
entry=next(a for a in audits if a['fold']==0 and a['budget']==budget)
|
| 188 |
+
y=4-row
|
| 189 |
+
ax.text(-2,y+.25, 'All train-pool' if budget=='all' else f'LoRA {budget}',ha='right',va='center',fontsize=12)
|
| 190 |
+
left=0
|
| 191 |
+
for role in ['train','unused','validation','test']:
|
| 192 |
+
count=entry[role]
|
| 193 |
+
if count:
|
| 194 |
+
ax.add_patch(Rectangle((left,y),count,.5,facecolor=split_colours[role],edgecolor='white',linewidth=1))
|
| 195 |
+
ax.text(left+count/2,y+.25,str(count),ha='center',va='center',fontsize=11,
|
| 196 |
+
color='white' if role in ['train','test'] else '#24333D')
|
| 197 |
+
left+=count
|
| 198 |
+
ax.text(53.5,4.9,'107 donors → fixed outer test fold + remaining donor pool',ha='center',fontsize=14)
|
| 199 |
+
ax.text(53.5,-.48,'Example: fold 0. Other folds keep 21–22 test and 7 validation donors.',ha='center',fontsize=12)
|
| 200 |
+
fig.legend([Patch(color=split_colours[k]) for k in split_colours],
|
| 201 |
+
['Train','Validation','Unused at this budget','Held-out test'],ncol=4,
|
| 202 |
+
loc='lower center',bbox_to_anchor=(.53,-.02),fontsize=11)
|
| 203 |
+
fig.subplots_adjust(left=.18,right=.99,top=.97,bottom=.13)
|
| 204 |
+
split=save(fig,'fixed_test_split')
|
| 205 |
+
detail = ('Historical ImMicro CV, not strict total-support experiment. Outer group-stratified donor folds and '
|
| 206 |
+
f'inner validation use seed {prep["seed"]}. Saved training subsets use fold-specific seeds '
|
| 207 |
+
+ ', '.join(str(a['subset_seed']) for a in audits if a['budget']==20)
|
| 208 |
+
+ '. Within each fold one random permutation yields nested 5/10/20/40 training subsets; exact replay '
|
| 209 |
+
'matches all 20 saved subset memberships. Every budget has identical held-out test donors (22,22,21,21,21), '
|
| 210 |
+
'and seven validation donors. All uses78,78,79,79,79 training donors. Each of107 donors contributes one '
|
| 211 |
+
'held-out prediction to the pooled metric. With n20,58–59 remaining training-pool donors are unused, '
|
| 212 |
+
'not moved into the test fold. The separate legacy healthy five-draw comparison uses '
|
| 213 |
+
'5 support+0 validation,102 test/draw. The newer strict healthy support campaign instead keeps '
|
| 214 |
+
'outer-fold held-out tests and has no extra validation; do not conflate these two total-five designs. '
|
| 215 |
+
'No training/test overlap or membership changes were introduced.')
|
| 216 |
+
slides.append(record('What does “all pairs” actually mean?',split,
|
| 217 |
+
'Random, nested training subsets; the test fold stays fixed. “All” = all available training pairs in that fold.',detail))
|
| 218 |
+
slides[-1]['sources']='; '.join(str(p) for p in sources if 'RUN.json' not in str(p))
|
| 219 |
+
result=dict(schema='pbisc.strengthening.healthy.v1',slides=slides,summary=summary,split_audit=audits,
|
| 220 |
+
sources=[dict(path=str(p),sha256=sha(p)) for p in [Path(__file__),*sources]],
|
| 221 |
+
assets=[str(p) for p in [*O.glob('*'),*A.glob('*.csv')]],new_training=False,new_inference=False,
|
| 222 |
+
checks={'matched107':True,'outer_and_inner_seed_replay':True,
|
| 223 |
+
'nested_membership_replay_20of20':True,'identical_test_all_budgets':True})
|
| 224 |
+
(A/'result.json').write_text(json.dumps(result,indent=2)+'\n')
|
| 225 |
+
print(json.dumps({'slides':len(slides),'summary':summary,'fold0':audits[:5]}))
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
if __name__=='__main__':
|
| 229 |
+
main()
|