junidude14 commited on
Commit
beba575
·
verified ·
1 Parent(s): 6bfb94b

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T072655Z-enriched-140-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/figure_enrichment_20261013/trajectory_step_50.svg ADDED
paper-releases/pbisc-diffusion/updates/20261013T072655Z-enriched-140-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/build_enriched_master_20261013.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Extend the author-ordered master with source-bound Figure 1-3 material."""
2
+ from pathlib import Path
3
+ from datetime import datetime, timezone
4
+ from collections import defaultdict
5
+ import copy
6
+ import csv
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import sys
11
+ if os.environ.get('CUDA_VISIBLE_DEVICES')!='':
12
+ raise SystemExit('CPU only: set CUDA_VISIBLE_DEVICES empty')
13
+ D=Path(__file__).resolve().parents[1]
14
+ A=D/'data/figure_enrichment_20261013'
15
+ F=D/'figures/figure_enrichment_20261013'
16
+ PARENT=D/'data/figure_order_fixed_20261013/spec.json'
17
+ OUT='PBISC-Diffusion_expanded_master_20261013_enriched'
18
+ sys.path.insert(0,str(D));sys.path.insert(0,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:return hashlib.file_digest(f,'sha256').hexdigest()
27
+
28
+
29
+ def read(name):return json.loads((A/name).read_text())
30
+
31
+
32
+ def normalize(s,group,key=None):
33
+ s=copy.deepcopy(s)
34
+ if isinstance(s.get('sources'),list):
35
+ s['source_bindings']=s['sources']
36
+ s['sources']='; '.join(x['path'] if isinstance(x,dict) else x for x in s['sources'])
37
+ s.update(kind='content',deck_group=group,section=group,section_label=group,layout='full')
38
+ s.setdefault('keywords',[])
39
+ s['figures']=[str(Path(p).relative_to(D)) if Path(p).is_absolute() else p for p in s['figures']]
40
+ if key:s['addition_key']='enrichment:'+key
41
+ if 'notes' in s:s.setdefault('footnote_full',s['notes'])
42
+ s.setdefault('footnote_full',s.get('footnote',''))
43
+ return s
44
+
45
+
46
+ def revise(s,new):
47
+ lineage={k:s[k] for k in ['source_page_131','parent_page','original_slide','original_title','original_footnote','addition_key'] if k in s}
48
+ # Old presenter notes can describe a different analysis even when the slide
49
+ # image is replaced. Keep historical wording in the preserved parent deck.
50
+ for field in ('say','text_source','numbers','refs','refs_full','keywords','layout','rows','figures_before_palette'):
51
+ s.pop(field,None)
52
+ s.update(new);s.update(lineage)
53
+ s['previous_figures']=copy.deepcopy(parent_by[s['parent_page']].get('figures',[]))
54
+ return s
55
+
56
+
57
+ def realword(text):
58
+ return (text.replace('Real R2','Real-cell repeat').replace('real-R2','real-cell repeat')
59
+ .replace('real R2','real-cell repeat').replace('Real R1','Observed reference')
60
+ .replace('real R1','observed reference').replace('real-R1','observed-reference'))
61
+
62
+
63
+ def build():
64
+ global parent_by
65
+ parent=json.loads(PARENT.read_text())['slides']
66
+ parent_by={i:copy.deepcopy(s) for i,s in enumerate(parent,1)}
67
+ by={s['source_page_131']:copy.deepcopy(s) for s in parent}
68
+ for i,s in enumerate(parent,1):by[s['source_page_131']]['parent_page']=i
69
+ arch=read('arch_result.json'); ar={r['role']:r for r in arch['slides']}
70
+ mismatch=read('mismatch_result.json')
71
+ labels=read('labels_result.json')
72
+ trajectory=read('trajectory_provenance.json')
73
+ trajectory_slide=normalize({'title':'From Gaussian noise to generated cell states',
74
+ 'figures':[str(F/'trajectory_four_pca_frames.png')],
75
+ 'footnote':'Recorded ctx2048 E12 EMA; same-donor pseudobulk illustration. Colour reveal shows step progress, not identity confidence.',
76
+ 'footnote_full':trajectory['caption'],'sources':str(A/'trajectory_provenance.json')},
77
+ 'Figure 1','trajectory_four_pca_frames')
78
+ real_control=normalize({'title':'Real-cell repeat: a sampling reference',
79
+ 'figures':[labels['control_explanation']['png']],
80
+ 'footnote':'Compare disjoint real-cell samples from the same donors. This measures sampling variability, not a theoretical ceiling.',
81
+ 'footnote_full':'Previously called Real R2. The reference uses one 100-cell draw per donor; the control uses a disjoint 100-cell draw from the same 42 donors. Biological n remains 42.',
82
+ 'sources':labels['control_explanation']['provenance']},'Figure 2','real_cell_repeat')
83
+ width=revise(by[12],normalize(ar['width_validation'],'Figure 2'))
84
+ revise(by[21],normalize(mismatch['slides'][0],'Figure 3'))
85
+ mismatch_extra=[normalize(s,'Figure 3',s['key']) for s in mismatch['slides'][1:]]
86
+ by[15]['previous_figures']=by[15]['figures'];by[15]['figures']=[str(Path(labels['ablation']['png']).relative_to(D))]
87
+ by[15]['footnote']='SLE pseudobulk; common 1,006-gene evaluation. Real-cell repeat compares disjoint observed-cell draws from the same donors.'
88
+ by[15]['sources']=labels['ablation']['provenance']
89
+ # Clarify remaining technical shorthand in supplementary figures as well.
90
+ replacements={41:labels['metrics_overview']['png'],31:str(F/'labels_within_type_centroids.png'),47:str(F/'labels_detection_and_library.png')}
91
+ for old,path in replacements.items():
92
+ by[old]['previous_figures']=by[old]['figures'];by[old]['figures']=[str(Path(path).relative_to(D))]
93
+ def add(role):return normalize(ar[role],'Figure 2',ar[role]['key'])
94
+ main2=[by[19],by[20],add('diagram'),add('hint_diagram'),width,by[13],add('architecture_arm_table'),
95
+ by[14],add('gene_validation'),add('gene_arm_table'),add('architecture_and_gene_cost'),real_control,by[15]]
96
+ slides=[]
97
+ for s in parent:
98
+ old=s['source_page_131']
99
+ if old==19:slides.extend(main2);continue
100
+ if old in (20,12,13,14,15):continue
101
+ slides.append(by[old])
102
+ if old==16:slides.append(trajectory_slide)
103
+ if old==21:slides.extend(mismatch_extra)
104
+ assert len(slides)==140,len(slides)
105
+ assert sorted(s['parent_page'] for s in slides if 'parent_page' in s)==list(range(1,132))
106
+ assert sorted(s['original_slide'] for s in slides if 'original_slide' in s)==list(range(1,77))
107
+ page_by_old={s['source_page_131']:i for i,s in enumerate(slides,1) if 'source_page_131' in s}
108
+ page_by_role={s['role']:i for i,s in enumerate(slides,1) if s.get('role')}
109
+ groups=defaultdict(list)
110
+ for i,s in enumerate(slides,1):groups[s['deck_group']].append(i)
111
+ def pg(*olds):return ', '.join(str(page_by_old[o]) for o in olds)
112
+ def rp(*roles):return ', '.join(str(page_by_role[r]) for r in roles)
113
+ def setcard(old,title,rows,foot):
114
+ s=by[old];s.update(title=title,rows=rows,footnote=foot,footnote_full=foot)
115
+ by[1]['subtitle']=f'{len(slides)} slides | Author-defined Figures 1-6 | Expanded model and expression views'
116
+ by[1]['title']='PBISC-Diffusion: manuscript evidence'
117
+ by[2]['title']='Figures 1-6: the expanded evidence map'
118
+ by[3].update(title='How this expanded deck is organized',rows=[
119
+ ('Figure 1: noise to cells','A recorded four-stage PCA view follows the experiment overview and corpus statistics.'),
120
+ ('Figure 2: model design and ablations','Context/trunk and hint diagrams, full validation curves, SLE benchmarks, exact parameters and observed training times.'),
121
+ ('Figure 3: expression mismatch to adaptation','Direct same-person expression comparisons lead into full FT, LoRA rank and paired-data efficiency.')],
122
+ footnote='Existing outputs are reused. Historical 131-page lineage is preserved; new views do not imply new training or inference.')
123
+ setcard(4,'Manuscript map: the six figures',[
124
+ ('Figure 1','Experimental overview, corpus and recorded denoising','Overview / illustration'),
125
+ ('Figure 2','Model components, validation, SLE ablations and cost','Pseudobulk development'),
126
+ ('Figure 3','Expression mismatch > full FT > rank > pair budget','Healthy measured pairs'),
127
+ ('Figure 4','Disease logFC, DEG and CAT benchmarks','Disease measured pairs'),
128
+ ('Figure 5','Rare-population identity in paired samples','Qualitative assembly'),
129
+ ('Figure 6','Published-finding reproduction from bulk-only samples','Planned')],
130
+ 'Six author-defined scopes. Training validation and SLE biological benchmarks are labelled separately within Figure 2.')
131
+ traj_page=next(i for i,s in enumerate(slides,1) if s.get('addition_key')=='enrichment:trajectory_four_pca_frames')
132
+ setcard(7,'Figure 1: overview, corpus and denoising',[
133
+ ('1a','Pretraining > paired adaptation > bulk-to-cell inference','p. '+pg(9)),
134
+ ('1b-c','Corpus statistics and generation workflow','pp. '+pg(11,16)),
135
+ ('1d','Four recorded PCA stages: step 0 / 17 / 33 / 50','p. '+str(traj_page)),
136
+ ('Colour','Colour reveals endpoint cell types as denoising progresses','Recorded illustration')],
137
+ 'Trajectory colours show progress, not calibrated confidence. Architecture and gene-context ablations remain in Figure 2.')
138
+ setcard(20,'Figure 2: architecture and gene context',[
139
+ ('2a-b','Context / trunk widths and predicted / oracle hint input','pp. '+rp('diagram','hint_diagram')),
140
+ ('2c-d','Architecture validation progression and SLE benchmark','pp. '+pg(12,13)),
141
+ ('2e-f','Gene-context benchmark and validation progression','pp. '+pg(14)+', '+rp('gene_validation')),
142
+ ('2g','All arms: parameters and observed training time','p. '+rp('architecture_and_gene_cost')),
143
+ ('2h-i','Real-cell repeat explained; common-axis model comparison','pp. '+str(next(i for i,s in enumerate(slides,1) if s.get('addition_key')=='enrichment:real_cell_repeat'))+', '+pg(15)),
144
+ ('Arm details','Exact widths, genes, endpoints, run completion and timing','pp. '+rp('architecture_arm_table','gene_arm_table'))],
145
+ 'Validation curves use corpus recipes; biological benchmarks use SLE pseudobulk. No measured bulk-sc paired performance in Figure 2.')
146
+ mp=[i for i,s in enumerate(slides,1) if s.get('role','').startswith('f3_expression')]
147
+ setcard(53,'Figure 3: the paired-adaptation story',[
148
+ ('3a','Same-person expression mismatch and donor-level error','pp. '+', '.join(map(str,mp))),
149
+ ('3b','Effect on generated cells; raw / calibrated / full FT / LoRA','pp. '+pg(23,5)),
150
+ ('3c','Full FT versus LoRA r4 / r16 / r64','p. '+pg(51)),
151
+ ('3d','Training-pair budget: historical n + 7 validation','p. '+pg(49)),
152
+ ('3e-f','Genuine five-pair performance and donor-level errors','pp. '+pg(54,55))],
153
+ 'All performance panels use healthy measured bulk-sc pairs. Input calibration is a separately labelled ten-pair diagnostic.')
154
+ setcard(61,'Figure 4: disease signal preservation',[
155
+ ('4a','Disease signal with five training donors','p. '+pg(63)),
156
+ ('4b','Five-fold held-out disease comparisons','p. '+pg(67)),
157
+ ('4c','Agreement across disease-gene list lengths','p. '+pg(68)),
158
+ ('4d','Cell-type expression comparison with deconvolution','p. '+pg(71)),
159
+ ('Scope','Sepsis, Imperial, Giroux and Ji','Measured paired data')],
160
+ 'Keep cohort-specific exceptions visible. Detailed quality and partial corrected DEG remain in Supplementary.')
161
+ def extent(a,b):return f'pp. {min(groups[a])}-{max(groups[b])}'
162
+ setcard(109,'Supplementary evidence map',[
163
+ ('S01-S02','Methods and additional SLE controls',extent('Supp S01','Supp S02')),
164
+ ('S03-S06','Input diagnostics, evaluation, healthy quality and budgets',extent('Supp S03','Supp S06')),
165
+ ('S07-S09','Cohorts, disease quality, corrected DEG and diagnostics',extent('Supp S07','Supp S09')),
166
+ ('S10-S11','Paired rare-state quantities and external screens',extent('Supp S10','Supp S11')),
167
+ ('S12-S14','Transfer, scratch, readout and bulk-only cohort shift',extent('Supp S12','Supp S14')),
168
+ ('Archive','Historical scoring and earlier bulk-only plans',extent('Historical archive','Historical archive'))],
169
+ 'Width-validation curves moved from supplementary into Figure 2; the prior figure remains in the preserved source deck.')
170
+ labels_by_role={'diagram':'Fig. 2a','hint_diagram':'Fig. 2b','width_validation':'Fig. 2c',
171
+ 'gene_validation':'Fig. 2f','architecture_and_gene_cost':'Fig. 2g',
172
+ 'architecture_arm_table':'Fig. 2 details','gene_arm_table':'Fig. 2 details',
173
+ 'f3_expression_mismatch':'Fig. 3a','f3_expression_discrepancy':'Fig. 3a detail'}
174
+ for s in slides:
175
+ if s.get('role') in labels_by_role:s['section_label']=labels_by_role[s['role']]
176
+ if s.get('source_page_131')==13:s['section_label']='Fig. 2d'
177
+ if s.get('source_page_131')==14:s['section_label']='Fig. 2e'
178
+ if s.get('source_page_131')==15:s['section_label']='Fig. 2i'
179
+ if s.get('source_page_131')==23:s['section_label']='Fig. 3b detail'
180
+ if s.get('addition_key')=='enrichment:real_cell_repeat':s['section_label']='Fig. 2h'
181
+ if s.get('addition_key')=='enrichment:trajectory_four_pca_frames':s['section_label']='Fig. 1d'
182
+ for field in ('footnote','footnote_full','say'):
183
+ if s.get(field):s[field]=realword(s[field])
184
+ if s.get('keywords'):s['keywords']=[realword(t) for t in s['keywords']]
185
+ if s.get('refs') and len(G.wrap(s.get('footnote',''),G.FOOT_PT,G.FOOT_W))>1:s.pop('refs')
186
+ # Short on-slide titles; full original titles remain in the source records.
187
+ short={'Architecture arms: dimensions, completion and endpoint rule':'Architecture arms: dimensions and endpoints',
188
+ 'All ablation arms: parameters and observed training time':'All ablation arms: parameters and training time',
189
+ 'Same-person RNA assays give different expression values':'Bulk and pooled cells: different expression values'}
190
+ s['title']=short.get(s['title'],s['title'])
191
+ spec={'deck':{'output_pptx':OUT+'.pptx','output_pdf':OUT+'.pdf'},'slides':slides}
192
+ prs=Presentation();prs.slide_width=Inches(G.SLIDE_W);prs.slide_height=Inches(G.SLIDE_H)
193
+ renderers={'title':G.build_title,'agenda':G.build_agenda,'divider':G.build_divider,
194
+ 'content':G.build_content,'plan_card':draw_card,'evidence_note':draw_note}
195
+ for n,s in enumerate(slides,1):
196
+ fn=renderers[s['kind']]
197
+ fn(prs,s) if s['kind']=='title' else fn(prs,s,n)
198
+ prs.save(D/(OUT+'.pptx'))
199
+ (A/'spec.json').write_text(json.dumps(spec,indent=2)+'\n')
200
+ mapping=[{'current_page':i,'parent_reordered_page':s.get('parent_page',''),
201
+ 'original_expanded_page':s.get('source_page_131',''),'original_76_page':s.get('original_slide',''),
202
+ 'group':s['deck_group'],'panel':s.get('section_label',''),'title':s['title'],
203
+ 'addition_key':s.get('addition_key','')} for i,s in enumerate(slides,1)]
204
+ with (A/'page_map.csv').open('w',encoding='utf-8-sig',newline='') as f:
205
+ w=csv.DictWriter(f,fieldnames=list(mapping[0]));w.writeheader();w.writerows(mapping)
206
+ sources={str(p):{'sha256':sha(p)} for p in [PARENT,Path(__file__),D/'generate_deck.py',
207
+ D/'tools/reorder_master_figures_20261013.py',A/'arch_result.json',A/'mismatch_result.json',
208
+ A/'labels_result.json',A/'trajectory_provenance.json']}
209
+ for record in arch['sources']+mismatch['sources']+trajectory['sources']:
210
+ p=Path(record['path']);actual=sha(p)
211
+ assert actual==record['sha256'],p
212
+ sources[str(p)]={'sha256':actual}
213
+ for s in slides:
214
+ for f in s.get('figures',[]):sources[str(D/f)]={'sha256':sha(D/f)}
215
+ protected={str(D/f):sha(D/f) for s in parent for f in s.get('figures',[])}
216
+ for suffix in ('pptx','pdf'):
217
+ p=D/('PBISC-Diffusion_expanded_master_20261013_reordered.'+suffix);protected[str(p)]=sha(p)
218
+ manifest={'schema':'pbisc.enriched-master.v1','created_at':datetime.now(timezone.utc).isoformat(),
219
+ 'parent_spec':str(PARENT),'parent_spec_sha256':sha(PARENT),'slides':slides,'groups':dict(groups),
220
+ 'parent_pages':131,'total_slides':len(slides),'new_slides':len(slides)-131,
221
+ 'sources':sources,'protected_sources':protected,'new_training':False,'new_inference':False,
222
+ 'new_projection_fit':False,'descriptive_analysis':'Saved same-donor expression values summarized on 5,508 shared genes; no calibration refitting.',
223
+ 'output':{'pptx':{'path':str(D/(OUT+'.pptx')),'sha256':sha(D/(OUT+'.pptx'))}}}
224
+ (A/'manifest.json').write_text(json.dumps(manifest,indent=2)+'\n')
225
+ print(json.dumps({'slides':len(slides),'groups':dict(groups),'pptx':str(D/(OUT+'.pptx'))}))
226
+
227
+
228
+ if __name__=='__main__':build()
paper-releases/pbisc-diffusion/updates/20261013T072655Z-enriched-140-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/enrich_architecture_20261013.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Source-bound Figure 2 enrichment. CPU-only; no model or array imports.
3
+
4
+ Reads saved JSON histories/configs, small result CSVs, and implementation text.
5
+ Does not train, sample, rescore, fetch remote data, or overwrite old figures.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import csv
10
+ import hashlib
11
+ import json
12
+ import math
13
+ from pathlib import Path
14
+
15
+ import matplotlib
16
+ matplotlib.use("Agg")
17
+ import matplotlib.pyplot as plt
18
+ from matplotlib.patches import FancyBboxPatch
19
+ from matplotlib.ticker import MaxNLocator
20
+
21
+ D = Path(__file__).resolve().parents[1]
22
+ M = D.parents[1]
23
+ OUT = D / "figures/figure_enrichment_20261013"
24
+ DATA = D / "data/figure_enrichment_20261013"
25
+ FULL = (12.3, 5.6)
26
+ INK, GREY, GOLD, DARK, PALE = "#1A1A1A", "#6E6E6E", "#C5AA4B", "#806A25", "#F7F2DF"
27
+ COLORS = ["#C5AA4B", "#8F772B", "#B59A50", "#66531E", "#D8C57E", "#9D8240"]
28
+ STYLES = ["-", "--", "-.", ":", "--", "-."]
29
+ MARKERS = ["o", "s", "^", "D", "P", "v"]
30
+ PREFIX = "s0_6k_allK_topup16_seed20260627_"
31
+ RUNS = [
32
+ ("base", "1× baseline", PREFIX + "bundle_v2", "server_1", "architecture"),
33
+ ("context", "Context ×4", PREFIX + "archctx2048_v1", "server_2", "architecture"),
34
+ ("trunk", "Trunk ×4", PREFIX + "arch4x_ctx512_v1", "server_1", "architecture"),
35
+ ("both", "Trunk + context ×4", PREFIX + "arch4x_v1", "server_2", "architecture"),
36
+ ("sixteen", "Trunk + context ×16", PREFIX + "arch16x_v1", "server_2", "architecture"),
37
+ ("hint", "1× + 9-fraction hint", PREFIX + "prop_v1", "server_1", "architecture"),
38
+ ("2k", "2k genes", "f01_2k_1x_seed20260627", "server_1", "gene_panel"),
39
+ ("3k", "3k genes", "f01_3k_1x_seed20260627", "server_2", "gene_panel"),
40
+ ("6k", "6k genes", "f01_6k_1x_seed20260627", "server_1", "gene_panel"),
41
+ ("15k", "15,114 genes", "f01_p15k_1x_seed20260627", "server_2", "gene_panel"),
42
+ ]
43
+ SOURCES: dict[str, dict] = {}
44
+ ASSETS: list[str] = []
45
+
46
+
47
+ def sha(path: Path) -> str:
48
+ h = hashlib.sha256()
49
+ with path.open("rb") as f:
50
+ for b in iter(lambda: f.read(1 << 20), b""):
51
+ h.update(b)
52
+ return h.hexdigest()
53
+
54
+
55
+ def source(path: Path, role: str, host: str = "server_1", origin: str | None = None) -> Path:
56
+ if not path.is_file():
57
+ raise FileNotFoundError(path)
58
+ SOURCES[str(path)] = {"path": str(path), "sha256": sha(path), "role": role,
59
+ "host": "server_1", "original_host": host,
60
+ "original_path": origin or str(path)}
61
+ return path
62
+
63
+
64
+ def read_json(path: Path, role: str, host: str = "server_1", origin: str | None = None) -> dict:
65
+ return json.loads(source(path, role, host, origin).read_text())
66
+
67
+
68
+ def write_csv(name: str, rows: list[dict]) -> None:
69
+ p = DATA / ("arch_" + name + ".csv")
70
+ fields = list(dict.fromkeys(k for row in rows for k in row))
71
+ with p.open("w", newline="") as f:
72
+ w = csv.DictWriter(f, fieldnames=fields)
73
+ w.writeheader(); w.writerows(rows)
74
+ ASSETS.append(str(p))
75
+
76
+
77
+ def count_parameters(g: int, c: int, widths: list[int], t: int, hint: int) -> int:
78
+ """Exact Linear/LayerNorm parameter arithmetic from model.py; no torch/model allocation."""
79
+ linear = lambda a, b: a * b + b
80
+ n = linear(t, c) + linear(c, c)
81
+ n += linear(3*g+6+hint, c) + 2*c + linear(c, c)
82
+ n += 2*c + linear(c, c)
83
+ edges = [(4*g, widths[0])] + list(zip(widths[:-1], widths[1:]))
84
+ edges += [(widths[i+1], widths[i]) for i in reversed(range(len(widths)-1))]
85
+ n += sum(linear(a, b) + linear(c, b) + 2*b for a, b in edges)
86
+ n += linear(widths[0], widths[0]) + 2*widths[0] + 2*linear(widths[0], g)
87
+ return n
88
+
89
+
90
+ def sat_epoch(hist: list[dict], tolerance: float) -> int | None:
91
+ if len(hist) != 16 or hist[-1]["epoch"] != 16:
92
+ return None
93
+ end = hist[-1]["validation"]["loss"]
94
+ return next(h["epoch"] for i, h in enumerate(hist)
95
+ if all(x["validation"]["loss"] <= end*(1+tolerance) for x in hist[i:]))
96
+
97
+
98
+ def load_runs() -> tuple[list[dict], list[dict]]:
99
+ rows, epochs = [], []
100
+ for key, label, name, host, family in RUNS:
101
+ orig = M / "runs" / name
102
+ local = orig if host == "server_1" else D / "data/sec03_server2_snapshots" / name
103
+ cfg = read_json(local/"effective_config.json", "saved training configuration", host, str(orig/"effective_config.json"))
104
+ status = read_json(local/"RUN_STATUS.json", "saved run completion/failure metadata", host, str(orig/"RUN_STATUS.json"))
105
+ hist = read_json(local/"history.json", "complete saved epoch history", host, str(orig/"history.json"))["epochs"]
106
+ hist = sorted(hist, key=lambda x: x["epoch"])
107
+ assert [h["epoch"] for h in hist] == list(range(1, len(hist)+1))
108
+ g, c, w = cfg["data"]["n_genes"], cfg["model"]["context_dim"], cfg["model"]["hidden_dims"]
109
+ hint = 9 if key == "hint" else 0
110
+ params = count_parameters(g, c, w, cfg["model"]["time_embedding_dim"], hint)
111
+ if "parameters" in status:
112
+ assert params == status["parameters"], (key, params, status["parameters"])
113
+ else:
114
+ manifest = read_json(M/"plans/arch_ablation_6k_20260913/MANIFEST.json", "16x declared parameter count")
115
+ assert params == manifest["variants"]["16x"]["params"]
116
+ ts = sum(h["train_seconds"] for h in hist)
117
+ steps = sum(h["train"]["optimizer_steps"] for h in hist)
118
+ final_steps = hist[-1]["train"]["optimizer_steps"]
119
+ row = dict(key=key, label=label, family=family, run=name, original_host=host,
120
+ original_path=str(orig), local_metadata=str(local), status=status["status"],
121
+ n_genes=g, detection_floor="1%" if family == "architecture" else "0.1%",
122
+ hidden_dims=" / ".join(map(str,w)), context_dim=c,
123
+ condition_dim=3*g+6+hint, hint_dim=hint, parameters=params,
124
+ completed_parts=len(hist), optimizer_steps=steps,
125
+ train_seconds_completed_parts=ts,
126
+ validation_seconds_completed_parts=sum(h["validation_seconds"] for h in hist),
127
+ train_seconds_per_step_weighted=ts/steps,
128
+ last_part_seconds_per_step=hist[-1]["train_seconds"]/final_steps,
129
+ final_val_loss=hist[-1]["validation"]["loss"],
130
+ saturation_part_0_5pct=sat_epoch(hist,.005),
131
+ saturation_part_1pct=sat_epoch(hist,.01),
132
+ saturation_part_2pct=sat_epoch(hist,.02),
133
+ late_loss_drop_pct_per_part=((hist[11]["validation"]["loss"]-hist[15]["validation"]["loss"])/4/hist[15]["validation"]["loss"]*100) if len(hist)==16 else None,
134
+ training_seed=cfg["training"]["seed"], batch_size=cfg["training"]["batch_size"],
135
+ error=status.get("error", ""),
136
+ runtime_note="Observed train-loop elapsed time including loading; excludes validation, checkpoint writes, restart gaps and failed partial parts. Loader/host changes prevent controlled speed claims.")
137
+ rows.append({**row, "history":hist, "config":cfg})
138
+ elapsed=0.0
139
+ for h in hist:
140
+ elapsed += h["train_seconds"]
141
+ epochs.append(dict(key=key,family=family,run=name,part=h["epoch"],
142
+ global_step=h["global_step"],train_loss=h["train"]["loss"],
143
+ validation_loss=h["validation"]["loss"],
144
+ relative_to_own_E16=h["validation"]["loss"]/hist[-1]["validation"]["loss"] if len(hist)==16 else None,
145
+ train_seconds=h["train_seconds"],validation_seconds=h["validation_seconds"],
146
+ optimizer_steps=h["train"]["optimizer_steps"],
147
+ train_seconds_per_optimizer_step=h["train_seconds"]/h["train"]["optimizer_steps"],
148
+ cumulative_train_seconds=elapsed,
149
+ source_path=str(local/"history.json"),original_host=host))
150
+ # Same architecture validation elements; different gene panels are not a common absolute-loss axis.
151
+ assert len({h["validation"]["support_elements"] for r in rows[:6] for h in r["history"]}) == 1
152
+ return rows, epochs
153
+
154
+
155
+ def setup() -> None:
156
+ OUT.mkdir(parents=True, exist_ok=True); DATA.mkdir(parents=True, exist_ok=True)
157
+ plt.rcParams.update({"font.family":"sans-serif", "font.sans-serif":["Arial","Liberation Sans"],
158
+ "font.size":14,"axes.labelsize":14,"axes.titlesize":14,
159
+ "xtick.labelsize":12,"ytick.labelsize":12,"legend.fontsize":12,
160
+ "axes.spines.top":False,"axes.spines.right":False,
161
+ "figure.facecolor":"white","axes.facecolor":"white",
162
+ "pdf.fonttype":42,"svg.fonttype":"none","text.color":INK,"legend.frameon":False,
163
+ "axes.labelcolor":INK,"savefig.facecolor":"white"})
164
+
165
+
166
+ def save(fig: plt.Figure, name: str) -> str:
167
+ for ext in ["png","pdf","svg"]:
168
+ p=OUT/("arch_"+name+"."+ext)
169
+ fig.savefig(p,dpi=220,bbox_inches=None)
170
+ ASSETS.append(str(p))
171
+ plt.close(fig)
172
+ return str((OUT/("arch_"+name+".png")).relative_to(D))
173
+
174
+
175
+ def card(ax, x: float,y: float,w: float,h: float,title: str,body: str="", fill: str=PALE,fs: int=14) -> None:
176
+ ax.add_patch(FancyBboxPatch((x,y),w,h,boxstyle="round,pad=0.012,rounding_size=0.045",fc=fill,ec="#DDD5BC",lw=1))
177
+ ax.text(x+w/2,y+h-.16,title,ha="center",va="top",fontsize=fs,fontweight="bold",color=DARK)
178
+ if body: ax.text(x+w/2,y+.12,body,ha="center",va="bottom",fontsize=fs-1,linespacing=1.45)
179
+
180
+
181
+ def arrow(ax,x0,y0,x1,y1,style="-",color=GREY) -> None:
182
+ ax.annotate("",(x1,y1),(x0,y0),arrowprops=dict(arrowstyle="-|>",lw=1.25,linestyle=style,color=color,shrinkA=2,shrinkB=2))
183
+
184
+
185
+ def width_diagram(rows: list[dict]) -> str:
186
+ fig,ax=plt.subplots(figsize=FULL);ax.set(xlim=(0,12.3),ylim=(0,5.6));ax.axis("off")
187
+ card(ax,.1,4.08,3.25,1.22,"Bulk condition + measurements","G+6 bulk/depth features\n+ 2G measurement features")
188
+ card(ax,3.8,4.08,3.65,1.22,"Context encoder · width C","Linear(3G+6 → C), then C → C")
189
+ card(ax,8.05,4.08,4.05,1.22,"Time + condition → shared context","time encoding → C; add, then mix")
190
+ arrow(ax,3.35,4.67,3.8,4.67);arrow(ax,7.45,4.67,8.05,4.67)
191
+ card(ax,.1,1.58,2.35,1.88,"Gene-space input","noisy value + support: 2G\nself-conditioning: 2G\nconcatenate → 4G",fs=13)
192
+ card(ax,2.9,1.58,6.62,1.88,"Denoiser trunk · seven conditioned blocks","",fill="#FCFAF1")
193
+ widths=[1024,1024,512,256,512,1024,1024]
194
+ for i,v in enumerate(widths):
195
+ x=3.10+i*.86; height=.36+.43*v/1024
196
+ ax.add_patch(FancyBboxPatch((x,2.08-height/2),.62,height,boxstyle="round,pad=0.01",fc=COLORS[i%3],ec=DARK,lw=.6))
197
+ ax.text(x+.31,2.08,str(v),ha="center",va="center",fontsize=11)
198
+ arrow(ax,x+.31,2.81,x+.31,2.08+height/2,color=DARK)
199
+ ax.text(6.14,3.70,"same C-dimensional context → a learned bias in every block",ha="center",fontsize=12,color=DARK)
200
+ ax.text(6.15,1.30,"3 matching-width skip additions",ha="center",fontsize=11.5,color=GREY)
201
+ arrow(ax,10.07,4.08,10.07,3.50)
202
+ ax.plot([10.07,9.72,9.72,3.41],[3.50,3.50,2.81,2.81],color=DARK,lw=1)
203
+ card(ax,9.92,1.58,2.18,1.88,"Output trunk","value head: G\nsupport logits: G\n→ joint clean estimate",fs=13)
204
+ arrow(ax,2.45,2.5,2.9,2.5);arrow(ax,9.52,2.5,9.92,2.5)
205
+ ax.text(.18,.97,"Context ×4: C 512 → 2,048; trunk widths stay fixed.",fontsize=14,fontweight="bold")
206
+ ax.text(.18,.56,"Trunk ×4: [1,024, 1,024, 512, 256] → [4,096, 4,096, 2,048, 1,024]; C stays 512.",fontsize=13)
207
+ ax.text(.18,.18,"Both ×4 / ×16 change both axes. Multipliers describe widths, not parameter counts. G = 6,000 for architecture arms.",fontsize=11.5,color=GREY)
208
+ fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
209
+ return save(fig,"context_vs_trunk")
210
+
211
+
212
+ def hint_diagram(report: dict) -> str:
213
+ fig,ax=plt.subplots(figsize=FULL);ax.set(xlim=(0,12.3),ylim=(0,5.6));ax.axis("off")
214
+ card(ax,.12,3.83,3.77,1.5,"Predicted hint · bulk-only input","6k pseudobulk → log1p(CPM)\nstandardize → MLP 6,000→512→256→9\nsoftmax → nine fractions",fs=13)
215
+ card(ax,.12,1.90,3.77,1.5,"Oracle hint · diagnostic only","Target donor's scANVI L1 labels\ncount and normalize nine cell types\nuses observed single-cell truth",fs=13)
216
+ card(ax,4.4,2.66,3.60,1.39,"Replace only the 9-value hint","[base G+6 | hint 9 | measurements 2G]\nG = 6,000 → 18,015 inputs",fs=13)
217
+ card(ax,8.53,2.66,3.63,1.39,"Same hint-trained denoiser","condition_encoder: 18,015 → 512\n54,189,792 denoiser parameters",fs=13)
218
+ arrow(ax,3.89,4.54,4.4,3.50);arrow(ax,3.89,2.60,4.4,3.10);arrow(ax,8,3.35,8.53,3.35)
219
+ ax.text(6.2,4.76,"Training: observed sample-level fractions",ha="center",fontsize=13,fontweight="bold")
220
+ ax.text(6.2,4.35,"Recipe block_id → sample_key → 9-fraction table",ha="center",fontsize=12,color=GREY)
221
+ arrow(ax,6.2,4.15,6.2,4.05)
222
+ ax.text(8.21,2.10,"After encoding: add time context, mix, inject into all 7 trunk blocks.",ha="center",fontsize=12)
223
+ ax.text(.18,1.22,"Pred and oracle are two inference conditions, not two trained diffusion models.",fontsize=15,fontweight="bold")
224
+ ax.text(.18,.79,"Predictor selected by corpus-validation L1: MLP 0.075 vs ridge 0.090; 106 MLP epochs.",fontsize=13)
225
+ ax.text(.18,.38,f"42 SLE donors: predicted vs oracle fraction L1 = {report['benchmark42']['predicted_vs_oracle_l1_mean']:.3f}. Auxiliary predictor adds 3,206,153 parameters; its runtime is not recorded.",fontsize=12,color=GREY)
226
+ fig.subplots_adjust(left=0,right=1,bottom=0,top=1)
227
+ return save(fig,"hint_injection")
228
+
229
+
230
+ def loss_plot(rows: list[dict], family: str) -> str:
231
+ selected=[r for r in rows if r["family"]==family]
232
+ fig,axes=plt.subplots(1,2,figsize=FULL)
233
+ panel=family=="gene_panel"
234
+ for i,r in enumerate(selected):
235
+ h=r["history"]; x=[z["epoch"] for z in h]
236
+ final=h[-1]["validation"]["loss"]
237
+ yy=[z["validation"]["loss"]/(final if panel else 1) for z in h]
238
+ lab=r["label"]+(" · stopped after E2" if len(h)<16 else "")
239
+ axes[0].plot(x,yy,color=COLORS[i],ls=STYLES[i],marker=MARKERS[i],ms=5,lw=1.9,label=lab,
240
+ markerfacecolor="white" if i%2 else COLORS[i],markeredgewidth=1.0)
241
+ late_yy=yy if panel else [(z["validation"]["loss"]/final-1)*100 for z in h]
242
+ if len(h)==16:
243
+ axes[1].plot(x,late_yy,color=COLORS[i],ls=STYLES[i],marker=MARKERS[i],ms=5,lw=1.9,
244
+ markerfacecolor="white" if i%2 else COLORS[i],markeredgewidth=1.0)
245
+ se=r["saturation_part_1pct"]
246
+ if se is not None:
247
+ axes[1].scatter([se],[late_yy[se-1]],s=115,facecolors="none",edgecolors=INK,lw=1.1,zorder=6)
248
+ axes[0].set_xlim(.6,16.4);axes[1].set_xlim(6.5,16.5)
249
+ axes[0].set_xticks([1,4,8,12,16]);axes[1].set_xticks([7,10,12,14,16])
250
+ axes[0].set_title("All saved parts",loc="left",fontweight="bold")
251
+ axes[1].set_title("Late progression · hollow ring = 1% endpoint rule",loc="left",fontsize=13)
252
+ for ax in axes:
253
+ ax.set_xlabel("Schedule part (historical epoch)")
254
+ ax.set_ylabel("Corpus validation loss / own E16" if panel else "Corpus validation loss")
255
+ ax.grid(axis="y",color="#EAEAEA",lw=.7);ax.yaxis.set_major_locator(MaxNLocator(6))
256
+ if panel:
257
+ axes[1].set_ylim(.998,1.042);axes[1].axhline(1.01,ls=":",color=GREY,lw=1)
258
+ else:
259
+ axes[1].set_ylabel("Loss above own E16 (%)")
260
+ axes[1].set_ylim(-.1,5.5);axes[1].axhline(1.0,ls=":",color=GREY,lw=1)
261
+ handles,labels=axes[0].get_legend_handles_labels()
262
+ fig.legend(handles,labels,loc="upper center",bbox_to_anchor=(.51,.99),ncol=3 if not panel else 4,
263
+ fontsize=11,handlelength=2.4,columnspacing=1.8)
264
+ footer=("Panels predict different genes: absolute losses are not a fair cross-panel ranking. Every curve has one training seed."
265
+ if panel else "Same 6k panel / validation support. 16× has two parts only: no E16 or saturation claim. Overlapping curves are genuine.")
266
+ fig.text(.07,.025,footer,fontsize=11,color=GREY)
267
+ fig.subplots_adjust(left=.075,right=.985,bottom=.17,top=.78,wspace=.29)
268
+ return save(fig,"panel_loss_progression" if panel else "width_loss_progression")
269
+
270
+
271
+ def compute_plot(rows: list[dict]) -> str:
272
+ fig,axes=plt.subplots(1,3,figsize=FULL,gridspec_kw={"width_ratios":[1.05,1,1]})
273
+ ys=list(range(len(rows)))
274
+ labels=[r["label"]+(" †" if r["key"]=="sixteen" else "") for r in rows]
275
+ for ax in axes:
276
+ ax.set_yticks(ys);ax.invert_yaxis();ax.set_ylim(9.65,-.65)
277
+ ax.axhline(5.5,color="#D6D6D6",lw=1);ax.grid(axis="x",color="#EAEAEA",zorder=0)
278
+ ax.spines['left'].set_visible(False);ax.tick_params(axis="y",length=0)
279
+ values=[[r["parameters"]/1e6 for r in rows],
280
+ [r["train_seconds_per_step_weighted"] for r in rows],
281
+ [r["train_seconds_completed_parts"]/3600 for r in rows]]
282
+ for j,(ax,v) in enumerate(zip(axes,values)):
283
+ ax.barh(ys,v,color=[COLORS[i%6] for i in ys],height=.61,zorder=3,edgecolor=DARK,lw=.4)
284
+ for i,val in enumerate(v):
285
+ x=val*1.10 if j==0 else val+max(v)*.035
286
+ ax.text(x,i,f"{val:,.1f}" if j!=1 else f"{val:.3f}",va="center",fontsize=10.5)
287
+ if j==0:
288
+ ax.set_xscale("log");ax.set_xlim(12,7200);ax.set_yticklabels(labels,fontsize=11.5)
289
+ else:
290
+ ax.set_xlim(0,max(v)*1.33);ax.set_yticklabels([])
291
+ axes[0].set_xlabel("Denoiser parameters (million; log)",fontsize=12)
292
+ axes[1].set_xlabel("Observed train seconds / update",fontsize=12)
293
+ axes[2].set_xlabel("Sum of logged training hours",fontsize=12)
294
+ axes[0].set_title("Capacity",loc="left",fontweight="bold")
295
+ axes[1].set_title("Weighted across completed parts",loc="left",fontsize=12)
296
+ axes[2].set_title("Completed parts only",loc="left",fontsize=12)
297
+ fig.text(.025,.062,"† 16×: E1–E2 only; others E1–E16. Hint pred/oracle share one training run. Auxiliary MLP: +3.206M parameters, timing NA.",fontsize=11)
298
+ fig.text(.025,.023,"Historical observations include data loading and changing loader/host conditions; they are not controlled hardware-speed comparisons.",fontsize=11,color=GREY)
299
+ fig.subplots_adjust(left=.207,right=.99,bottom=.19,top=.92,wspace=.28)
300
+ return save(fig,"all_arm_compute")
301
+
302
+
303
+ def audit_table(rows: list[dict], family: str) -> str:
304
+ selected=[r for r in rows if r["family"]==family]
305
+ fig,ax=plt.subplots(figsize=FULL);ax.axis("off")
306
+ col=["Arm / inference use","G / condition","Trunk down widths","Context","Params","Parts","1% / 0.5% / 2%"]
307
+ body=[]
308
+ for r in selected:
309
+ dims=r['hidden_dims'].replace(' / ',' /\n',1) if r['key']=='sixteen' else r['hidden_dims']
310
+ sats=" / ".join("NA" if r[f"saturation_part_{k}"] is None else str(r[f"saturation_part_{k}"]) for k in ["1pct","0_5pct","2pct"])
311
+ body.append([r["label"]+("\npred + oracle: same weights" if r['key']=='hint' else ""),
312
+ f"{r['n_genes']:,} /\n{r['condition_dim']:,}",dims,str(r['context_dim']),
313
+ f"{r['parameters']/1e6:.3f}M",str(r['completed_parts']),sats])
314
+ table=ax.table(cellText=body,colLabels=col,cellLoc="left",colLoc="left",loc="upper left",
315
+ bbox=[.005,.26,.99,.64],colWidths=[.205,.105,.26,.075,.10,.06,.195])
316
+ table.auto_set_font_size(False);table.set_fontsize(11.3)
317
+ for (i,j),cell in table.get_celld().items():
318
+ cell.set_edgecolor("#E4DFD2");cell.set_linewidth(.6);cell.PAD=.055
319
+ if i==0: cell.set_facecolor(PALE);cell.get_text().set_weight("bold");cell.get_text().set_color(DARK)
320
+ else: cell.set_facecolor("white" if i%2 else "#FCFBF6")
321
+ ax.text(.008,.955,"Architecture family · 1% detection-floor genes" if family=='architecture' else "Gene-panel family · 0.1% detection-floor genes",fontsize=15,fontweight="bold",transform=ax.transAxes)
322
+ ax.text(.008,.19,"Last column: first part after which every remaining validation loss is within the stated tolerance of that run's E16 loss.",fontsize=11.6,transform=ax.transAxes)
323
+ ax.text(.008,.125,"This is a retrospective endpoint rule, not proof of convergence; sensitivity to 0.5% / 1% / 2% is retained.",fontsize=11.6,transform=ax.transAxes)
324
+ if family=='architecture':
325
+ ax.text(.008,.068,"Pred also needs a separately trained 3.206M-parameter MLP; predictor training/inference timing is NA and not included.",fontsize=11.4,color=GREY,transform=ax.transAxes)
326
+ note=("16×: FAILED_PRESERVED after E2; memory floor during resumed part 3. 2× was retired before the reported suite; it has no curve here."
327
+ if family=='architecture' else "Each panel is one trained checkpoint. Five 6k sampling seeds reuse one checkpoint; 2k/3k/15k each have one sampling seed.")
328
+ ax.text(.008,.016 if family=='architecture' else .043,note,fontsize=11.3,color=GREY,transform=ax.transAxes)
329
+ fig.subplots_adjust(left=.025,right=.98,bottom=.02,top=.99)
330
+ return save(fig,"width_arm_register" if family=='architecture' else "panel_arm_register")
331
+
332
+
333
+ def build() -> dict:
334
+ SOURCES.clear(); ASSETS.clear(); setup()
335
+ paths=[M/"src/pbisc_sdd/model.py",M/"src/pbisc_sdd/experiment.py",M/"src/pbisc_sdd/data.py",
336
+ M/"src/pbisc_sdd/ladder_experiment.py",M/"src/pbisc_sdd/proportion_hint.py",
337
+ M/"plans/prop_condition_6k_20260916/train_proportion_predictor.py",
338
+ M/"plans/prop_condition_6k_20260916/README.md",M/"plans/arch_ablation_6k_20260913/README.md",
339
+ D/"tools/sec03_common.py",D/"tools/sec03_panel.py",D/"tools/sec03_width_bench.py",
340
+ M/"scripts/sample_sdd_standalone.py"]
341
+ for p in paths: source(p,"implementation and historical protocol semantics")
342
+ assert "time_context + condition_context" in paths[0].read_text()
343
+ assert "base_condition, hint_values" in paths[1].read_text()
344
+ assert "condition, bulk_analog, output_analog" in paths[2].read_text()
345
+ report=read_json(M/"plans/prop_condition_6k_20260916/predictor_v1/predictor_report.json","saved separate hint predictor metrics")
346
+ assert report['winner_by_val']=='mlp' and len(report['labels'])==9
347
+ assert 6000*512+512+512*256+256+256*9+9 == 3206153
348
+ rows,epochs=load_runs()
349
+ public=[{k:v for k,v in r.items() if k not in ['history','config']} for r in rows]
350
+ write_csv("training_arms",public);write_csv("loss_and_timing_by_part",epochs)
351
+ variants=[]
352
+ for r in public:
353
+ for mode in (["pred","oracle"] if r['key']=='hint' else ["standard"]):
354
+ variants.append({**r,"inference_variant":mode,"independent_training_key":r['key'],
355
+ "external_predictor_parameters":3206153 if mode=='pred' else 0,
356
+ "external_predictor_training_seconds":None,
357
+ "oracle_target_truth_access":mode=='oracle'})
358
+ write_csv("inference_variant_register",variants)
359
+ # Verify saved figure tables without regenerating scores.
360
+ for name in ['sec03_width_loss.csv','sec03_panel_loss.csv','sec03_width_bench.csv','sec03_panel_bench.csv','sec03_panel_seeds.csv']:
361
+ source(D/'data'/name,"existing figure source table; no rescoring")
362
+ aliases={'base':'1x','context':'ctx4x','trunk':'trunk4x','both':'4x','sixteen':'16x','hint':'prop'}
363
+ with (D/'data/sec03_width_loss.csv').open() as f: old=list(csv.DictReader(f))
364
+ for r in rows[:6]:
365
+ saved={int(float(z['epoch'])):z for z in old if z['variant']==aliases[r['key']]}
366
+ for h in r['history']:
367
+ assert math.isclose(float(saved[h['epoch']]['val_loss']),h['validation']['loss'],rel_tol=1e-13)
368
+ common=("Source-only enrichment: saved configs/history + implementation; no new model training, inference or statistical scoring. "
369
+ "Validation curves describe internal pretraining-corpus recipes (192 × 64), not SLE held-out donor scores. "
370
+ "Figure 2 benchmark scores remain SLE pseudobulk, not measured bulk–sc paired performance. "
371
+ "Architecture and gene-panel families have different detection-floor gene selections and must be compared within family. ")
372
+ timing=("History train_seconds times train_one_epoch including data loading and heartbeat overhead. Divide its sum by recorded optimizer_steps for weighted seconds/update. "
373
+ "Sum only completed parts; validation, checkpoint writes, resume gaps and failed partial parts excluded. RUN_STATUS.wall_seconds resets on resumed invocations and is not a total. "
374
+ "Hosts, loader settings and competing load changed; do not interpret timing ratios as a controlled benchmark. Server_2 histories are existing local snapshots, not a live-status claim.")
375
+ specs=[
376
+ ("context_vs_trunk","Where context width and trunk width change",width_diagram(rows),11,
377
+ "Code-derived diagram. Width multipliers are not parameter multipliers; all architecture arms use 6,000 genes.",
378
+ "Seven conditioned blocks: down widths [1024,1024,512,256], up widths [512,1024,1024], three additive skips. Context = mixer(time encoder + condition encoder); each block adds its own projected context. No latent-space diffusion. Visual organization follows the public website's condition strip / input / denoiser / output cards; fresh vector implementation, not copied recordings."),
379
+ ("hint_injection","Predicted and oracle hints: one trained denoiser",hint_diagram(report),11,
380
+ "Pred/oracle share hint-trained weights. Oracle reads target scANVI fractions; the separate predictor's training time is unavailable.",
381
+ "Training sample fractions are joined by recipe block_id→sample_key. Pred is corpus-trained MLP (train5232/val648/test627 samples), chosen by validation L1 against ridge; log1p(CPM), train-standardized, two hidden GELU/dropout layers and softmax. Oracle aggregates target donor observed AIFI-L1 labels over nine categories. Hint is appended after base G+6, before 2G measurement context; first condition layer 18015→512. Baseline denoiser and hint denoiser are separately trained; pred and oracle share hint denoiser. Predictor params3206153 calculated from recorded architecture, excluded from denoiser count."),
382
+ ("width_loss_progression","Architecture: full and late validation progression",loss_plot(rows,"architecture"),12,
383
+ "Corpus validation; same 6k genes. Hollow ring: within 1% of own E16 thereafter. 16× stops at E2; saturation remains NA.",
384
+ "Full saved E1–E16 curves with a late-region view. No smoothing, curve fitting or extrapolation. One training seed. Endpoint proximity is a retrospective summary, not established convergence; tolerance sensitivity is in arm register."),
385
+ ("panel_loss_progression","Gene panels: progression relative to each endpoint",loss_plot(rows,"gene_panel"),13,
386
+ "Corpus validation, normalized to each panel's E16. Different gene sets prevent comparing absolute losses across panels.",
387
+ "All four panels have 16 saved parts. Curves use each panel's own denominator; this compares progression shape, not identical-objective performance. One training seed for every panel; five 6k generation seeds are not five training repetitions."),
388
+ ("all_arm_compute","All ablation arms: parameters and observed training time",compute_plot(rows),13,
389
+ "Observed train-loop time includes loading; excludes validation/restarts/checkpoint writes. 16× has E1–E2 only; no controlled speed claim.",timing),
390
+ ("width_arm_register","Architecture arms: dimensions, completion and endpoint rule",audit_table(rows,"architecture"),12,
391
+ "Six independent training runs; pred/oracle reuse the hint run. 16× incomplete; retired 2× is not a completed result.",
392
+ "Counts derived arithmetically from exact Linear/LayerNorm definitions and checked against all available RUN_STATUS parameters; 16× checked against recorded manifest. Saturation columns use 1%,0.5%,2% relative to own E16. 16× memory-floor failure preserved; discarded2× design not counted as trained evidence."),
393
+ ("panel_arm_register","Gene-panel arms: exact sizes and training provenance",audit_table(rows,"gene_panel"),13,
394
+ "Four separately trained panels; 6k sampling seeds reuse one checkpoint. Saturation is endpoint-relative, not proof of convergence.",
395
+ "Nominal15k is15114 genes. Fixed trunk/context widths; parameters change because input/output and condition projections depend on G. Architecture6k 1% and final6k0.1% are distinct panels/checkpoints despite equal parameter counts.")]
396
+ roles={"context_vs_trunk":"diagram", "hint_injection":"hint_diagram", "width_loss_progression":"width_validation",
397
+ "panel_loss_progression":"gene_validation", "all_arm_compute":"architecture_and_gene_cost",
398
+ "width_arm_register":"architecture_arm_table", "panel_arm_register":"gene_arm_table"}
399
+ source(Path(__file__).resolve(),"reproducible CPU-only enrichment renderer")
400
+ slides=[]
401
+ for key,title,png,after,foot,full in specs:
402
+ assert len(foot)<=180,(key,len(foot))
403
+ slides.append(dict(key="arch_"+key,kind="content",type="content",title=title,
404
+ section="Figure 2",section_label="Figure 2 support",figures=[png],keywords=[],
405
+ footnote=foot,footnote_full=common+full,
406
+ notes=common+full,after_current=after,after_current_page=after,
407
+ palette="native",role=roles[key],sources=list(SOURCES.values()),
408
+ replace_current_page=43 if key=='width_loss_progression' else None,
409
+ replacement_previous_131_page=12 if key=='width_loss_progression' else None))
410
+ payload=dict(schema="pbisc.figure-enrichment.architecture.v1",slides=slides,assets=ASSETS.copy(),
411
+ sources=list(SOURCES.values()),training_runs=10,inference_variants=11,
412
+ scope="Figure 2: all architecture/hint and final gene-panel arms in sec03; excludes retired2x and unrelated pilot/loss-policy studies.",
413
+ style_reference="https://www.virtualhumanlab.com/research/pbisc-diffusion/; code-native redraw; no website data copied",
414
+ timing_definition=timing,
415
+ limitations=["No training seed replicates; five6k seeds are generation repeats.","16x onlyE1–E2; saturationNA; failedpartial elapsed excluded.","Separate hint predictor runtimeNA.","SLEscores and corpusloss are distinct evidence.","Historical loader/host changes preclude controlledspeedclaims."],
416
+ source_validation={"width_csv_losses_match_history":True,"all_recorded_parameter_counts_match_arithmetic":True})
417
+ hashes={"schema":"pbisc.architecture-enrichment.hashes.v1", "sources":list(SOURCES.values()),
418
+ "assets":[{"path":p,"sha256":sha(Path(p))} for p in ASSETS],
419
+ "self_and_result_json_excluded_to_avoid_recursive_hashes":True}
420
+ p=DATA/"arch_hashes.json";p.write_text(json.dumps(hashes,indent=2)+"\n")
421
+ payload["assets"].append(str(p))
422
+ payload["assets"].extend([str(DATA/"arch_additions.json"),str(DATA/"arch_result.json")])
423
+ p=DATA/"arch_additions.json";p.write_text(json.dumps(payload,indent=2)+"\n")
424
+ p=DATA/"arch_result.json";p.write_text(json.dumps(payload,indent=2)+"\n")
425
+ return payload
426
+
427
+
428
+ if __name__=="__main__":
429
+ result=build()
430
+ print(json.dumps({"slides":len(result['slides']),"assets":len(result['assets']),"sources":len(result['sources'])}))
paper-releases/pbisc-diffusion/updates/20261013T072655Z-enriched-140-slide-master/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/enrich_expression_mismatch_20261013.py ADDED
@@ -0,0 +1,264 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Direct paired ImMicro expression mismatch, using the verified 5508-gene axis.
2
+
3
+ Reads saved assay-level matrices and saved calibration conditions only. It never
4
+ loads generated expression, fits calibration/PCA, initializes CUDA, or trains a
5
+ model. The other-cohort compact reduction supplies only the immutable gene IDs
6
+ of the identical final-model checkpoint, never any expression values.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import hashlib
11
+ import json
12
+ import os
13
+ from pathlib import Path
14
+
15
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
16
+
17
+ import numpy as np
18
+ import pandas as pd
19
+ import style as ST
20
+ import matplotlib.pyplot as plt
21
+ from matplotlib.colors import LogNorm
22
+
23
+ D = Path(__file__).resolve().parents[1]
24
+ M = D.parents[1]
25
+ U = M / "plans/utility_studies_final6k_20260925"
26
+ S = U / "umap/sample_level"
27
+ C = M / "plans/realbulk_generation_20260922/conditions"
28
+ FEATURES = Path("/home/sj_server_1/gblee/datalake/paired-pbmc-bulk-sc/analyses/offset_sample_size_20260914/features.npz")
29
+ PANEL = S / "reduced/reduced_Arunachalam_paired12.npz"
30
+ FIG = D / "figures/figure_enrichment_20261013"
31
+ DATA = D / "data/figure_enrichment_20261013"
32
+ RAW_COLOR, CAL_COLOR = "#777777", "#C5AA4B"
33
+
34
+
35
+ def sha(path: Path) -> str:
36
+ h = hashlib.sha256()
37
+ with path.open("rb") as f:
38
+ for block in iter(lambda: f.read(1 << 20), b""):
39
+ h.update(block)
40
+ return h.hexdigest()
41
+
42
+
43
+ def log_cpm(values: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
44
+ totals = values.sum(axis=1)
45
+ if not np.isfinite(values).all() or (values < 0).any() or (totals <= 0).any():
46
+ raise ValueError("Common-axis expression contains missing/negative values or an empty library")
47
+ return np.log1p(values / totals[:, None] * 1e6), totals
48
+
49
+
50
+ def build() -> dict:
51
+ sources: dict[str, dict] = {}
52
+ assets: list[str] = []
53
+ def source(path: Path, role: str) -> Path:
54
+ path = path.resolve()
55
+ sources[str(path)] = {"path": str(path), "sha256": sha(path), "bytes": path.stat().st_size, "role": role}
56
+ return path
57
+ def document(path: Path, role: str) -> dict:
58
+ return json.loads(source(path, role).read_text())
59
+ def save_table(frame: pd.DataFrame, name: str) -> Path:
60
+ path = DATA / f"mismatch_{name}.csv"
61
+ frame.to_csv(path, index=False); assets.append(str(path))
62
+ return path
63
+ def save(fig, name: str) -> Path:
64
+ for ext in ("png", "pdf", "svg"):
65
+ path = FIG / f"mismatch_{name}.{ext}"
66
+ fig.savefig(path, dpi=ST.DPI, bbox_inches="tight", pad_inches=0.07, facecolor="white")
67
+ assets.append(str(path))
68
+ plt.close(fig)
69
+ return FIG / f"mismatch_{name}.png"
70
+
71
+ FIG.mkdir(parents=True, exist_ok=True); DATA.mkdir(parents=True, exist_ok=True)
72
+ condition_manifest = document(C / "MANIFEST_ImMicro.json", "saved group-held-out ten-pair calibration recipe and condition hashes")
73
+ source(FEATURES, "actual paired ImMicro bulk counts and observed single-cell summed UMI, gene availability and donor IDs")
74
+ if sources[str(FEATURES.resolve())]["sha256"] != condition_manifest["source_sha256"]:
75
+ raise ValueError("Assay matrix differs from the saved ImMicro condition source")
76
+ panel_meta = document(PANEL.with_suffix(".json"), "receipt of compact final-model reduction used only to recover panel IDs")
77
+ immicro_meta = document(S / "reduced/reduced_ImMicro_native.json", "matching final-model ImMicro checkpoint lineage")
78
+ source(PANEL, "only panel_ids array read; no other-cohort expression is used")
79
+ if sha(PANEL) != panel_meta["out_sha256"]:
80
+ raise ValueError("Gene-axis carrier fails its saved reduction hash")
81
+ checkpoints = {v["checkpoint_sha256"] for meta in (panel_meta, immicro_meta) for v in meta["files"].values()}
82
+ if len(checkpoints) != 1:
83
+ raise ValueError("Panel carrier and ImMicro were generated from different checkpoints")
84
+ with np.load(PANEL, allow_pickle=False) as z:
85
+ panel_ids = z["panel_ids"].astype(str)
86
+ with np.load(FEATURES, allow_pickle=False) as z:
87
+ gene_ids = z["gene_ids"].astype(str)
88
+ donors = z["donor_ids"].astype(str)
89
+ pools = z["pools"].astype(str)
90
+ bvalid = z["bulk_valid"].astype(bool).all(axis=0)
91
+ svalid = z["sc_valid"].astype(bool).all(axis=0)
92
+ shared = bvalid & svalid
93
+ if not np.array_equal(shared, z["common_all_donors"].astype(bool)):
94
+ raise ValueError("Saved shared measurement support disagrees with actual assay masks")
95
+ mapping = {gene: i for i, gene in enumerate(gene_ids)}
96
+ positions = np.array([mapping[g] for g in panel_ids], dtype=int)
97
+ kept_panel_positions = np.flatnonzero(shared[positions])
98
+ cols = positions[kept_panel_positions]
99
+ if len(donors) != 107 or len(set(donors)) != 107 or len(panel_ids) != 6000 or len(cols) != 5508:
100
+ raise ValueError("Expected 107 unique donors and exactly 5508 shared genes of the final 6000-gene model panel")
101
+ bulk = np.asarray(z["bulk_raw"][:, cols], dtype=np.float64)
102
+ pseudo = np.asarray(z["pseudo_raw_sum"][:, cols], dtype=np.float64)
103
+ raw, raw_total = log_cpm(bulk)
104
+ observed, pseudo_total = log_cpm(pseudo)
105
+
106
+ # Use the stored calibrated inputs, not a newly estimated multiplier.
107
+ cal = None
108
+ for arm in ("raw", "cal", "pseudo"):
109
+ path = source(C / f"conditions_ImMicro_{arm}.npz", f"saved {arm} model-condition profile; only bulk_counts and identity metadata read")
110
+ if sha(path) != condition_manifest["arms"][arm]["sha256"]:
111
+ raise ValueError(f"Saved {arm} condition no longer matches its receipt")
112
+ with np.load(path, allow_pickle=False) as z:
113
+ if not np.array_equal(z["gene_ids"].astype(str), gene_ids) or not np.array_equal(z["sample_ids"].astype(str), donors):
114
+ raise ValueError("Condition donors/gene order do not match actual paired assays")
115
+ expression, _ = log_cpm(np.asarray(z["bulk_counts"][:, cols], dtype=float))
116
+ if arm == "cal": cal = expression
117
+ else:
118
+ expected = raw if arm == "raw" else observed
119
+ if not np.allclose(expression, expected, rtol=0, atol=1e-10):
120
+ raise ValueError(f"Common-axis {arm} condition does not reproduce assay expression")
121
+ if cal is None: raise ValueError("No saved paired-calibration values")
122
+ for pool, info in condition_manifest["calibration_per_group"].items():
123
+ ids = np.asarray(info["calibration_rows"], dtype=int)
124
+ if len(ids) != 10 or (pools[ids] == pool).any() or donors[ids].tolist() != info["calibration_samples"]:
125
+ raise ValueError("Calibration includes evaluated pool/donor or differs from saved recipe")
126
+
127
+ cached = document(S / "ImMicro/metrics_ImMicro.json", "old common-axis normalization and expression-space reference scale")
128
+ if cached["n_genes"] != len(cols) or cached["n_samples"] != len(donors):
129
+ raise ValueError("Old expression diagnostic uses a different donor/gene set")
130
+ old_distance_path = source(S / "ImMicro/per_sample_distance_ImMicro_native.csv", "existing full-expression distances used solely as a reproduction check")
131
+ old_distance = pd.read_csv(old_distance_path)
132
+ unit = cached["settings"]["native"]["sum"]["full"]["unit"]["D"]
133
+ max_distance_gap = 0.0
134
+ for label, matrix in (("raw", raw), ("cal", cal)):
135
+ old = old_distance[(old_distance.space == "full") & (old_distance.group == label)].set_index("donor_id")
136
+ if len(old) != 107: raise ValueError("Old full-gene distance coverage incomplete")
137
+ actual = np.linalg.norm(matrix - observed, axis=1) / unit
138
+ gap = float(np.max(np.abs(actual - old.loc[donors, "distance_to_own_observed_D"].to_numpy())))
139
+ max_distance_gap = max(max_distance_gap, gap)
140
+ if gap > 1e-5: raise ValueError(f"Recovered gene axis/normalization differs from saved {label} expression analysis: {gap}")
141
+
142
+ gene_table = pd.DataFrame({"gene_id": panel_ids[kept_panel_positions], "canonical_position": cols,
143
+ "final_panel_position": kept_panel_positions, "measured_in_all_107_both_assays": True})
144
+ gene_path = save_table(gene_table, "gene_axis")
145
+ raw_error = np.abs(raw - observed).mean(axis=1)
146
+ cal_error = np.abs(cal - observed).mean(axis=1)
147
+ per_donor = pd.DataFrame({"donor_id": donors, "pool": pools, "genes": len(cols),
148
+ "bulk_raw_common_gene_total": raw_total, "sc_sum_common_gene_total": pseudo_total,
149
+ "raw_mae_log1p_cpm": raw_error, "saved_calibration_mae_log1p_cpm": cal_error,
150
+ "raw_minus_calibration_mae": raw_error - cal_error,
151
+ "raw_rmse_log1p_cpm": np.sqrt(((raw-observed)**2).mean(axis=1)),
152
+ "saved_calibration_rmse_log1p_cpm": np.sqrt(((cal-observed)**2).mean(axis=1))})
153
+ donor_path = save_table(per_donor, "per_donor_errors")
154
+ # Every donor × shared-gene value contributes; no marker or donor selection.
155
+ high = np.ceil(max(raw.max(), observed.max(), cal.max()) * 2) / 2
156
+ edges = np.linspace(0, high, 121)
157
+ matrices, density_rows = [], []
158
+ for arm, values in (("raw", raw), ("saved_calibration", cal)):
159
+ counts = np.zeros((120, 120), dtype=np.int64)
160
+ for start in range(0, len(donors), 8):
161
+ block = np.histogram2d(observed[start:start+8].ravel(), values[start:start+8].ravel(), bins=(edges, edges))[0]
162
+ counts += block.astype(np.int64)
163
+ if int(counts.sum()) != len(donors) * len(cols): raise ValueError("Density plot dropped paired gene values")
164
+ matrices.append(counts)
165
+ for i in range(120):
166
+ for j in range(120):
167
+ density_rows.append({"arm": arm, "sc_log1p_cpm_left": edges[i], "sc_log1p_cpm_right": edges[i+1],
168
+ "bulk_log1p_cpm_left": edges[j], "bulk_log1p_cpm_right": edges[j+1], "donor_gene_pairs": int(counts[i,j])})
169
+ bins_path = save_table(pd.DataFrame(density_rows), "density_bins")
170
+ display_style = {"font.family": "sans-serif", "font.sans-serif": ["Arial", "Liberation Sans", "DejaVu Sans"],
171
+ "font.size": 14, "axes.labelsize": 14, "axes.titlesize": 14, "xtick.labelsize": 12, "ytick.labelsize": 12,
172
+ "legend.fontsize": 12, "legend.frameon": False, "axes.spines.top": False, "axes.spines.right": False,
173
+ "figure.facecolor": "white", "axes.facecolor": "white", "pdf.fonttype": 42, "svg.fonttype": "none"}
174
+ with plt.rc_context(display_style):
175
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL, sharex=True, sharey=True)
176
+ fig.subplots_adjust(left=0.08, right=0.88, bottom=0.18, top=0.86, wspace=0.26)
177
+ vmax = max(int(x.max()) for x in matrices)
178
+ for ax, counts, title in zip(axes, matrices, ["Measured bulk", "Saved paired calibration · diagnostic"]):
179
+ im = ax.imshow(np.ma.masked_equal(counts.T, 0), origin="lower", extent=(0, high, 0, high),
180
+ aspect="equal", cmap="Blues", norm=LogNorm(vmin=1, vmax=vmax), interpolation="nearest")
181
+ ax.plot([0, high], [0, high], "--", color="#252525", linewidth=1)
182
+ ax.set_title(title, loc="left", pad=10)
183
+ ax.set_xlabel("Same-donor scRNA-seq sum\n(pseudobulk; log1p CPM)")
184
+ ax.set_ylabel("Bulk expression (log1p CPM)")
185
+ ax.set_xlim(0, high); ax.set_ylim(0, high)
186
+ cax = fig.add_axes([0.91, 0.23, 0.018, 0.56])
187
+ cb = fig.colorbar(im, cax=cax); cb.set_label("Donor–gene pairs per bin", fontsize=12)
188
+ fig.text(0.08, 0.98, f"107 paired healthy donors × {len(cols):,} shared final-model genes", fontsize=15, ha="left", va="top")
189
+ fig.text(0.08, 0.025, "Dashed line: equal expression · all measured zeros retained · same gene axis and normalization", fontsize=11, color=ST.SUBINK)
190
+ expression_figure = save(fig, "expression_values")
191
+
192
+ fig, axes = plt.subplots(1, 2, figsize=ST.FULL)
193
+ fig.subplots_adjust(left=0.085, right=0.98, bottom=0.21, top=0.86, wspace=0.32)
194
+ jitter = np.linspace(-0.10, 0.10, len(donors))
195
+ # Fixed source donor order; all 107 are shown, no donor ranking/selection.
196
+ for i in range(len(donors)):
197
+ axes[0].plot([jitter[i], 1+jitter[i]], [raw_error[i], cal_error[i]], color="#B9B9B9", linewidth=0.6, alpha=0.45)
198
+ axes[0].scatter(jitter, raw_error, s=19, color=RAW_COLOR, zorder=3)
199
+ axes[0].scatter(1+jitter, cal_error, s=19, color=CAL_COLOR, zorder=3)
200
+ for x, values in ((0, raw_error), (1, cal_error)):
201
+ median = float(np.median(values))
202
+ axes[0].plot([x-0.15, x+0.15], [median, median], color=ST.INK, linewidth=2.0, zorder=4)
203
+ axes[0].annotate(f"Median {median:.3f}", (x, median), xytext=(0, 15), textcoords="offset points", ha="center", fontsize=12,
204
+ bbox={"facecolor": "white", "edgecolor": "none", "pad": 1.5})
205
+ axes[0].set_xticks([0, 1], ["Measured bulk", "Paired-calibrated bulk\n(diagnostic)"])
206
+ axes[0].set_xlim(-0.3, 1.3); axes[0].set_ylim(bottom=0)
207
+ axes[0].set_ylabel("Same-donor mean absolute error\n(log1p-CPM units)")
208
+ axes[0].set_title("Each line = one donor", loc="left")
209
+ for values, label, color in ((raw_error, "Measured bulk", RAW_COLOR), (cal_error, "Saved paired calibration", CAL_COLOR)):
210
+ xs = np.sort(values); ys = 100 * np.arange(1, len(xs)+1) / len(xs)
211
+ axes[1].step(np.r_[0, xs], np.r_[0, ys], where="post", label=label, color=color, linewidth=2)
212
+ axes[1].set_xlabel("Same-donor mean absolute error\n(log1p-CPM units)")
213
+ axes[1].set_ylabel("Donors at or below this error (%)")
214
+ axes[1].set_ylim(0, 102); axes[1].set_xlim(left=0); axes[1].legend(loc="lower right")
215
+ axes[1].set_title("All 107 donors · lower error is better", loc="left")
216
+ for ax in axes: ax.grid(axis="y", color="#EAEAEA", linewidth=0.7); ax.set_axisbelow(True)
217
+ fig.text(0.085, 0.035, "Calibration used 10 pairs from other sc pools; the evaluated donor and its entire pool were excluded.", fontsize=11, color=ST.SUBINK)
218
+ errors_figure = save(fig, "same_donor_errors")
219
+
220
+ source(Path(__file__), "figure builder; no model generation or calibration fit")
221
+ source(D / "tools/style.py", "original 76-slide figure typography")
222
+ for path in (gene_path, donor_path, bins_path): source(path, "exact display source table")
223
+ notes = (f"ImMicro, 107 unique paired healthy donors. All {len(cols)} final-model panel genes measured by both assays in every donor are included; "
224
+ "the other 492 model genes are excluded by availability, never filled as measured zeros. Each assay row is separately normalized to 1e6 "
225
+ "over the same 5508 genes and transformed by natural log(1+CPM). Axes are gene-expression profiles, not cell-type counts, learned embeddings or PCA. "
226
+ "Observed pseudobulk is the sum of the donor's measured single-cell UMI counts. The saved calibrated condition uses the historical gene-wise "
227
+ "multiplier from exactly 10 other-pool paired donors, with the evaluated donor's whole sc pool excluded. It is a paired-information diagnostic, "
228
+ "not zero-shot deployment, LoRA output or the current strict-five budget. Source condition hashes and raw/pseudobulk normalization are verified. "
229
+ "The full-expression distances reproduce the old saved analysis within its rounded CSV precision. Assay differences can include cell capture, "
230
+ "pool/batch, depth and assay chemistry; this plot does not attribute them to one mechanism or treat scRNA-seq as noise-free truth. "
231
+ "No individual genes or donors were chosen for a favorable example. The plots describe 107 biological donors; donor–gene points are not independent replicates.")
232
+ footer1 = "107 paired donors; all 5,508 shared final-model genes. log1p CPM on the same gene axis. Saved calibration uses 10 other-pool pairs."
233
+ footer2 = "Each line = one donor. Error averages all 5,508 genes; no nearest-neighbor score. Ten-pair, other-pool calibration is diagnostic."
234
+ slides = []
235
+ for key, title, figure, footer, role in [
236
+ ("mismatch_expression_values", "Same-person RNA assays give different expression values", expression_figure, footer1, "f3_expression_mismatch"),
237
+ ("mismatch_same_donor_errors", "Paired calibration reduces same-donor expression error", errors_figure, footer2, "f3_expression_discrepancy")]:
238
+ slides.append({"kind": "content", "layout": "full", "key": key, "role": role, "title": title,
239
+ "section_label": "Fig. 3 · Input expression", "figures": [str(figure.relative_to(D))], "keywords": [],
240
+ "footnote": footer, "footnote_full": notes, "notes": notes,
241
+ "sources": "; ".join(sources), "palette": "biological", "after_original": 17})
242
+ summary = {"n_donors": 107, "n_shared_genes": len(cols), "donor_gene_pairs_per_density_panel": 107*len(cols),
243
+ "raw_median_mae_log1p_cpm": float(np.median(raw_error)), "calibrated_median_mae_log1p_cpm": float(np.median(cal_error)),
244
+ "raw_mean_mae_log1p_cpm": float(raw_error.mean()), "calibrated_mean_mae_log1p_cpm": float(cal_error.mean()),
245
+ "donors_with_lower_error_after_saved_calibration": int((cal_error < raw_error).sum()),
246
+ "reproduction_max_abs_gap_in_old_rounded_distance_D": max_distance_gap,
247
+ "checkpoint_sha256": next(iter(checkpoints)), "panel_carrier_expression_used": False,
248
+ "mask": "final 6000-gene panel intersect all-donor bulk_valid and sc_valid; 5508 genes",
249
+ "normalization": "ln(1 + 1e6 * count_g / sum_counts_over_same_5508_genes)",
250
+ "new_calibration_fit": False, "new_generation": False, "new_training": False,
251
+ "new_work": "paired expression binning and donor-wise descriptive errors from existing assays/calibrated conditions"}
252
+ analysis_path = DATA / "mismatch_analysis.json"
253
+ analysis_path.write_text(json.dumps(summary, indent=2) + "\n"); assets.append(str(analysis_path)); source(analysis_path, "descriptive expression comparison and validation")
254
+ result = {"schema": "pbisc.figure-enrichment.expression-mismatch.v1", "slides": slides,
255
+ "sources": list(sources.values()), "assets": assets, "summary": summary,
256
+ "recommended_footer": footer1, "no_new_generation": True}
257
+ (DATA / "mismatch_result.json").write_text(json.dumps(result, indent=2) + "\n")
258
+ return result
259
+
260
+
261
+ if __name__ == "__main__":
262
+ result = build()
263
+ print(json.dumps({"slides": len(result["slides"]), "summary": result["summary"],
264
+ "result": str(DATA / "mismatch_result.json")}, indent=2))