junidude14 commited on
Commit
c343f07
·
verified ·
1 Parent(s): 2a408df

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261012T131501Z-strictpairs-final-caption/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T131501Z-strictpairs-final-caption/assemble_manuscript.py ADDED
@@ -0,0 +1,592 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stage the PBISC-Diffusion Figure 1--5 manuscript without changing its Git tree.
3
+
4
+ --preview emits an explicitly incomplete review draft. --require-complete refuses
5
+ until every strict unit and its source binding has been verified, then uses the
6
+ same staged file map. No Git, archive or network write is performed here.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ CANON = Path('/home/sj_server_1/PBISC/paper-release-20260928/manuscript')
22
+ STAGE = ROOT / 'manuscript'
23
+ EDITS = STAGE / 'edits'
24
+ COHORTS = ('ye2026_sepsis', 'imperial_eskd', 'giroux2022', 'ji2025_chili')
25
+ FIGURES = {
26
+ 'fig1_overview.pdf': 'fig1_overview.pdf',
27
+ 'fig2_ablation_and_support.pdf': 'fig2_ablation_and_support.pdf',
28
+ 'fig4_historical_5fold_separate.pdf': 'fig4_historical_5fold_separate.pdf',
29
+ }
30
+ FINAL_FIGURES = {
31
+ 'fig3_healthy_strict_oof.pdf': 'fig3_healthy_strict_oof.pdf',
32
+ 'fig3_realism_metrics.pdf': 'fig3_realism_metrics.pdf',
33
+ 'fig3_canonical_marker_dotplot.pdf': 'fig3_canonical_marker_dotplot.pdf',
34
+ 'fig3_umap_by_celltype.pdf': 'fig3_umap_by_celltype.pdf',
35
+ 'fig3_composition_fractions.pdf': 'fig3_composition_fractions.pdf',
36
+ 'fig3_runtime_components.pdf': 'fig3_runtime_components.pdf',
37
+ 'fig4_disease_strict_draws.pdf': 'fig4_disease_strict_draws.pdf',
38
+ 'fig4_disease_signal_strict.pdf': 'fig4_disease_signal_strict.pdf',
39
+ 'fig4_disease_signal_scatter.pdf': 'fig4_disease_signal_scatter.pdf',
40
+ 'fig4_disease_signal_heatmap.pdf': 'fig4_disease_signal_heatmap.pdf',
41
+ 'fig4_disease_signal_cat.pdf': 'fig4_disease_signal_cat.pdf',
42
+ 'fig4_deconvolution_strict.pdf': 'fig4_deconvolution_strict.pdf',
43
+ 'fig4_deconvolution_expression_strict.pdf': 'fig4_deconvolution_expression_strict.pdf',
44
+ 'fig5_rare_states_strict.pdf': 'fig5_rare_states_strict.pdf',
45
+ 'fig5_rare_visuals_strict.pdf': 'fig5_rare_visuals_strict.pdf',
46
+ 'fig5_all_states_strict.pdf': 'fig5_all_states_strict.pdf',
47
+ 'fig5_behcet_rules_strict.pdf': 'fig5_behcet_rules_strict.pdf',
48
+ }
49
+
50
+
51
+ def digest(path: Path) -> str:
52
+ h = hashlib.sha256()
53
+ with path.open('rb') as f:
54
+ for chunk in iter(lambda: f.read(1024 * 1024), b''):
55
+ h.update(chunk)
56
+ return h.hexdigest()
57
+
58
+
59
+ def document(path: Path) -> dict:
60
+ return json.loads(path.read_text())
61
+
62
+
63
+ def rows(path: Path) -> list[dict[str, str]]:
64
+ with path.open(newline='') as f:
65
+ return list(csv.DictReader(f))
66
+
67
+
68
+ def tracked_sources() -> list[Path]:
69
+ raw = subprocess.check_output(['git', '-C', str(CANON), 'ls-files', '-z'])
70
+ paths = [Path(p.decode()) for p in raw.split(b'\0') if p]
71
+ wanted = {'.tex', '.bib', '.cls', '.bst'}
72
+ return [p for p in paths if p.suffix in wanted or
73
+ (p.parts[0] == 'figures' and p.suffix.lower() in {'.pdf', '.png'})]
74
+
75
+
76
+ def checked_provenance(path: Path, label: str) -> dict:
77
+ if not path.is_file():
78
+ raise ValueError(f'{label}: missing {path}')
79
+ item = document(path)
80
+ for entry in item.get('sources', []) + item.get('outputs', []):
81
+ source = Path(entry['path'])
82
+ if not source.is_file() or digest(source) != entry['sha256']:
83
+ raise ValueError(f'{label}: source/output hash mismatch: {source}')
84
+ return item
85
+
86
+
87
+ def strict_gate() -> tuple[list[str], dict]:
88
+ gaps = []
89
+ readiness_path = ROOT / 'reports/figures234_readiness.json'
90
+ readiness = document(readiness_path) if readiness_path.is_file() else {}
91
+ if readiness.get('schema') != 'pbisc.paper.figures234.v1' or readiness.get('status') != 'complete':
92
+ gaps.append('Figures 2--4 readiness is not complete')
93
+ f2, f3, f4 = (readiness.get(k, {}) for k in ('figure2', 'figure3', 'figure4'))
94
+ if f2.get('strict_complete_units') != 20 or f2.get('strict_missing') or not f2.get('pretrain_composition_ready'):
95
+ gaps.append('Figure 2 needs 20/20 strict healthy support units')
96
+ if (f3.get('strict_complete_folds') != 5 or not f3.get('visual_export_ready') or
97
+ not f3.get('extras_complete') or not f3.get('runtime_ready')):
98
+ gaps.append('Figure 3 needs 5/5 folds, visual, extras and time receipts')
99
+ if (set(f4.get('strict_complete_draws', {})) != set(COHORTS) or
100
+ any(f4['strict_complete_draws'].get(c) != 5 for c in COHORTS) or
101
+ any(f4.get(k) for k in ('contrast_missing', 'deconvolution_missing',
102
+ 'deconvolution_signal_missing'))):
103
+ gaps.append('Figure 4 needs 5/5 strict draws per cohort and contrast/deconvolution evidence')
104
+ expected_healthy = {(f'fold{fold}', n) for fold in range(5) for n in (5, 10, 20, 40)}
105
+ expected_disease = {(c, f'draw{draw}') for c in COHORTS for draw in range(5)}
106
+ curve = rows(ROOT / 'source_data/fig2_strict_curve.csv')
107
+ if {(r['fold'], int(r['n_pairs'])) for r in curve} != expected_healthy:
108
+ gaps.append('Figure 2 strict CSV has incomplete fold/size units')
109
+ healthy = rows(ROOT / 'source_data/fig3_per_sample.csv')
110
+ if {r['fold'] for r in healthy} != {f'fold{n}' for n in range(5)}:
111
+ gaps.append('Figure 3 strict per-sample CSV has incomplete folds')
112
+ disease = rows(ROOT / 'source_data/fig4_strict_per_sample.csv')
113
+ if {(r['cohort'], r['draw']) for r in disease} != expected_disease or any(
114
+ r.get('design') != 'strict_exact5_donor_draw' for r in disease):
115
+ gaps.append('Figure 4 strict CSV has incomplete or mixed-design draws')
116
+ for filename, table in [('fig2_strict_curve.csv', curve), ('fig3_per_sample.csv', healthy),
117
+ ('fig4_strict_per_sample.csv', disease)]:
118
+ if not table or any(not r.get('support_sha256') for r in table):
119
+ gaps.append(f'{filename} lacks source-bound support hashes')
120
+ for record in curve + healthy + disease:
121
+ source = record.get('summary')
122
+ source_hash = record.get('summary_sha256')
123
+ if source and source_hash and (not Path(source).is_file() or digest(Path(source)) != source_hash):
124
+ gaps.append(f'score summary hash mismatch: {source}')
125
+ break
126
+ for table, kind in ((curve, 'healthy'), (healthy, 'healthy'), (disease, 'disease')):
127
+ for record in table:
128
+ cohort = record.get('cohort', 'immicro')
129
+ unit = record.get('fold') if kind == 'healthy' else record.get('draw')
130
+ suffix = f'{unit}/n{record["n_pairs"]}' if table is curve else (
131
+ f'{unit}/n5' if kind == 'healthy' else unit)
132
+ support = ROOT / 'protocol/splits' / cohort / kind / suffix / 'support.json'
133
+ if not support.is_file() or document(support).get('sha256') != record.get('support_sha256'):
134
+ gaps.append(f'{cohort}/{kind}/{suffix}: source support mismatch')
135
+ break
136
+ summary = ROOT / 'scores' / cohort / kind / suffix / 'score/summary.json'
137
+ score_sha = record.get('score_sha256') or record.get('summary_sha256')
138
+ if not summary.is_file() or digest(summary) != score_sha:
139
+ gaps.append(f'{cohort}/{kind}/{suffix}: score summary hash mismatch')
140
+ break
141
+ rare_path = ROOT / 'reports/rare_provenance.json'
142
+ rare = document(rare_path) if rare_path.is_file() else {}
143
+ units = rare.get('units', [])
144
+ if (rare.get('schema') != 'pbisc.figure5.analysis.v1' or len(units) != 20 or
145
+ {(u.get('cohort'), u.get('unit')) for u in units} != expected_disease or
146
+ any(u.get('design') != 'strict5pair' or u.get('evidence_tier') != 'strict'
147
+ or not u.get('support_sha256') for u in units)):
148
+ gaps.append('Figure 5 needs all 20 strict rare-state receipts')
149
+ rare_table = rows(ROOT / 'source_data/rare_summary.csv')
150
+ if (not rare_table or {r.get('evidence_tier') for r in rare_table} != {'strict'} or
151
+ {(r['cohort'], r['unit']) for r in rare_table} != expected_disease):
152
+ gaps.append('Figure 5 rare-state CSV is absent, diagnostic or incomplete')
153
+ for cohort, unit in expected_disease:
154
+ subset = [r for r in rare_table if r.get('cohort') == cohort and r.get('unit') == unit]
155
+ if {r.get('arm') for r in subset} != {'raw', 'refcal', 'pairedcal', 'scsemi', 'lora'}:
156
+ gaps.append(f'Figure 5 strict arms incomplete: {cohort}/{unit}')
157
+ break
158
+ for unit in units:
159
+ support = ROOT / 'protocol/splits' / str(unit.get('cohort')) / 'disease' / str(unit.get('unit')) / 'support.json'
160
+ if not support.is_file() or document(support).get('sha256') != unit.get('support_sha256'):
161
+ gaps.append(f'Figure 5 strict support hash mismatch: {unit.get("cohort")}/{unit.get("unit")}')
162
+ break
163
+ if readiness.get('status') == 'complete':
164
+ runtime = ROOT / 'source_data/fig3_runtime.csv'
165
+ runtime_meta = ROOT / 'source_data/fig3_runtime.json'
166
+ visual = ROOT / 'source_data/fig3_visual_data.npz'
167
+ visual_meta = ROOT / 'source_data/fig3_visual_data.json'
168
+ if (not runtime.is_file() or not runtime_meta.is_file() or
169
+ document(runtime_meta).get('csv_sha256') != digest(runtime)):
170
+ gaps.append('Figure 3 runtime source/receipt hash mismatch')
171
+ if (not visual.is_file() or not visual_meta.is_file() or
172
+ document(visual_meta).get('npz_sha256') != digest(visual)):
173
+ gaps.append('Figure 3 visual source/receipt hash mismatch')
174
+ extras = ROOT / 'source_data/fig3_extras.csv'
175
+ if not extras.is_file() or not rows(extras):
176
+ gaps.append('Figure 3 realism extras CSV is missing')
177
+ for name in ('fig4_strict_contrast.csv', 'fig4_deconvolution.csv',
178
+ 'fig4_deconvolution_signal.csv', 'fig4_corrected_statistics.csv',
179
+ 'fig4_cross_draw_donor_ci.csv', 'fig4_donor_aware_signal.csv',
180
+ 'fig4_donor_aware_summary.csv', 'fig4_donor_aware_genes.csv',
181
+ 'fig4_donor_aware_cat.csv'):
182
+ path = ROOT / 'source_data' / name
183
+ if not path.is_file() or not rows(path):
184
+ gaps.append(f'Figure 4 required source table missing: {name}')
185
+ cross = ROOT / 'source_data/fig4_cross_draw_donor_ci.csv'
186
+ cross_receipt = ROOT / 'source_data/fig4_cross_draw_donor_ci.json'
187
+ if (not cross_receipt.is_file() or not cross.is_file() or
188
+ document(cross_receipt).get('csv_sha256') != digest(cross) or
189
+ {r.get('cohort') for r in rows(cross)} != set(COHORTS)):
190
+ gaps.append('Figure 4 five-draw donor-cluster CI source or receipt mismatch')
191
+ corrected = ROOT / 'source_data/fig4_donor_aware_signal.csv'
192
+ corrected_provenance = ROOT / 'source_data/fig4_donor_aware_provenance.json'
193
+ corrected_rows = rows(corrected) if corrected.is_file() else []
194
+ if (not corrected_provenance.is_file() or not corrected_rows or
195
+ {(r.get('cohort'), r.get('draw')) for r in corrected_rows} != expected_disease or
196
+ any(r.get('status') not in ('ok', 'not_estimable') for r in corrected_rows)):
197
+ gaps.append('Figure 4 corrected donor-aware disease signal is absent or incomplete')
198
+ for filename in FINAL_FIGURES:
199
+ if not (ROOT / 'figures' / filename).is_file():
200
+ gaps.append(f'missing strict figure: {filename}')
201
+ return gaps, readiness
202
+
203
+
204
+ def numeric_summary(table: list[dict], keys: tuple[str, ...], metrics: tuple[str, ...]) -> str:
205
+ """Render observed means only; no unsupported ordering or P value."""
206
+ data: dict[tuple[str, ...], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
207
+ for row in table:
208
+ group = tuple(row[k] for k in keys)
209
+ for metric in metrics:
210
+ try:
211
+ value = float(row[metric])
212
+ except (KeyError, ValueError, TypeError):
213
+ continue
214
+ if value == value and value not in (float('inf'), float('-inf')):
215
+ data[group][metric].append(value)
216
+ lines = []
217
+ for group, values in sorted(data.items()):
218
+ parts = [f'{key}={value}' for key, value in zip(keys, group)]
219
+ parts += [f'{metric}={sum(items)/len(items):.3f} (n={len(items)})'
220
+ for metric, items in values.items() if items]
221
+ lines.append('; '.join(parts).replace('_', r'\_') + r'\par')
222
+ return '\n'.join(lines)
223
+
224
+
225
+ def complete_results() -> None:
226
+ """Fill only numbers present in verified strict CSVs; leave no preview placeholders."""
227
+ additions = {
228
+ 2: ('source_data/fig2_strict_curve.csv', ('n_pairs', 'arm'), ('precision', 'coverage', 'comp_l1')),
229
+ 3: ('source_data/fig3_per_sample.csv', ('arm',), ('precision', 'coverage', 'comp_l1')),
230
+ 4: ('source_data/fig4_strict_per_sample.csv', ('cohort', 'arm'), ('pb_r', 'comp_l1')),
231
+ 5: ('source_data/rare_summary.csv', ('cohort', 'arm'), ('mae_donor_pp', 'generated_zero_donors')),
232
+ }
233
+ openers = {
234
+ 2: (r'\subsection*{Pretraining design and strict paired-support curve}' '\n'
235
+ 'The held-out native-pseudobulk precision and coverage ablations use the '
236
+ 'common 1,006-gene rescore described in Methods. Architecture and gene-panel '
237
+ 'families have different training detection floors. The nested ImMicro curve '
238
+ 'uses five outer folds and $n=5,10,20,40$ distinct training donors per fold. '
239
+ 'Historical rank and full-parameter five-fold results are reported separately.\n'),
240
+ 3: (r'\subsection*{Healthy generation with exact five-pair support}' '\n'
241
+ 'Each ImMicro outer fold uses one matched sample from each of five training '
242
+ 'donors for LoRA, paired calibration and scSemiProfiler. The remaining donors '
243
+ 'are evaluated on common observed cells, measured genes and frozen labels. '
244
+ 'Figure~\\ref{fig:fig3} displays the strict quality measures and operational '
245
+ 'time, which excludes population pretraining.\n'),
246
+ 4: (r'\subsection*{Disease comparisons with exact five-pair support}' '\n'
247
+ 'Each of four disease cohorts contributes five frozen draws. One earliest '
248
+ 'identity-passed matched-stratum visit per selected donor trains all arms; '
249
+ 'other visits of that donor are excluded. Donor-aware disease contrasts and '
250
+ 'deconvolution are scored on the common held-out support. The old five-fold '
251
+ 'analysis remains a separate historical sensitivity analysis.\n'),
252
+ 5: (r'\subsection*{Rare states with paired support}' '\n'
253
+ 'All four disease cohorts and five draws use the exact same five-pair supports '
254
+ 'as Figure~\\ref{fig:fig4}. Zero-generated-state draws remain in every '
255
+ 'aggregate, required-marker failures make a state ineligible, and repeated '
256
+ 'visits are clustered by donor. The unmatched Beh\\c{c}et analysis is '
257
+ 'descriptive and separate.\n'),
258
+ }
259
+ for number, (source, keys, metrics) in additions.items():
260
+ path = STAGE / 'sections' / f'results_fig{number}.tex'
261
+ text = openers[number]
262
+ text += ('\n\\textbf{Measured strict-support summary.} Values below are arithmetic means '
263
+ 'of the named source-data rows; $n$ counts rows, not independent donors. '
264
+ 'Donor-cluster uncertainty and formal comparisons require the separate '
265
+ 'statistics receipts.\\par\n')
266
+ text += numeric_summary(rows(ROOT / source), keys, metrics) + '\n'
267
+ if number == 2:
268
+ text += ('\nComposition was evaluated on exactly the same selected cells and Poisson '
269
+ 'counts as the pretraining precision/coverage comparison, using the frozen '
270
+ 'AIFI annotator. The original logFC and top-DEG ablation panels are retained '
271
+ 'separately with their original epoch, readout and seed budgets; their '
272
+ 'absolute scores are not mixed with the new rescore.\\par\n')
273
+ text += numeric_summary(rows(ROOT / 'source_data/ablation_pretrain_composition_summary.csv'),
274
+ ('family', 'method'), ('comp_l1_mean',)) + '\n'
275
+ if number == 3:
276
+ extras = []
277
+ for record in rows(ROOT / 'source_data/fig3_extras.csv'):
278
+ if record.get('table') == 'metrics.csv' and record.get('mode') == 'raw':
279
+ extras.append({'arm': record.get('set', ''), **record})
280
+ elif (record.get('table') == 'en.csv' and record.get('cellset') == 'pc'
281
+ and record.get('distance') == 'sq'):
282
+ extras.append({'arm': record.get('set', ''), **record})
283
+ text += ('\n\\textbf{Realism and operational time.} C2ST AUC, MMD$^2$ '
284
+ 'and $E_N$ are computed from the strict extras; time is fine-tuning '
285
+ 'plus inference seconds, with pretraining excluded.\\par\n')
286
+ text += numeric_summary(extras, ('arm',), ('c2st_rf_auc', 'mmd2_sum', 'en')) + '\n'
287
+ text += numeric_summary(rows(ROOT / 'source_data/fig3_runtime.csv'),
288
+ ('arm',), ('operational_seconds',)) + '\n'
289
+ if number == 4:
290
+ donor_aware = [r for r in rows(ROOT / 'source_data/fig4_donor_aware_signal.csv')
291
+ if r.get('status') == 'ok']
292
+ text += ('\n\\textbf{Primary donor-aware disease signal.} Equal-patient '
293
+ 'condition contrasts, with repeated visits collapsed by donor and '
294
+ 'condition, are reported by cohort, arm, cell type and draw. '
295
+ 'A missing population is marked not estimable and contributes no '
296
+ 'fabricated zero. The values below summarize estimable rows; '
297
+ 'patient-cluster intervals are in the accompanying source tables.\\par\n')
298
+ text += numeric_summary(donor_aware, ('cohort', 'arm'),
299
+ ('pearson_r', 'partial_r', 'cat50', 'limma_top50')) + '\n'
300
+ contrast = [r for r in rows(ROOT / 'source_data/fig4_strict_contrast.csv')
301
+ if r.get('table') == 'headline.csv']
302
+ text += ('\n\\textbf{Historical contrast sensitivity.} The legacy per-sample '
303
+ 'logFC, CAT and limma headline values below retain their original '
304
+ 'independent-sample definition. They are separate from corrected '
305
+ 'donor-aware disease signal.\\par\n')
306
+ text += numeric_summary(contrast, ('cohort', 'arm'),
307
+ ('partial_r', 'cat50', 'limma_top50')) + '\n'
308
+ text += ('\n\\textbf{Cross-draw uncertainty.} Donor-cluster confidence intervals '
309
+ 'over all five verified draws, with repeated visits and draw membership '
310
+ 'kept together, are supplied in '
311
+ '\\texttt{fig4\\_cross\\_draw\\_donor\\_ci.csv}.\\par\n')
312
+ text += ('\n\\textbf{Same-support deconvolution.} Deconvolution '
313
+ 'provides fractions and supported cell-type expression, not '
314
+ 'generated-cell realism scores.\\par\n')
315
+ text += numeric_summary(rows(ROOT / 'source_data/fig4_deconvolution.csv'),
316
+ ('cohort', 'arm'), ('composition_l1',)) + '\n'
317
+ path.write_text(text)
318
+ path = STAGE / 'sections/discussion.tex'
319
+ path.write_text('\\section*{Discussion}\n'
320
+ 'The strict-support numerical summaries in Figs~2--5 report the completed '
321
+ 'five-pair design. They should be interpreted with their donor-cluster '
322
+ 'uncertainty and source tables; row counts are not biological replicates. '
323
+ 'Historical five-fold and unmatched Beh\\c{c}et analyses remain separate. '
324
+ 'Figure~\\ref{fig:fig6} awaits the user-prepared bulk-only reproduction data.\n')
325
+
326
+
327
+ def copy_source_files() -> dict[str, str]:
328
+ before = {}
329
+ for rel in tracked_sources():
330
+ src, dst = CANON / rel, STAGE / rel
331
+ if not src.is_file():
332
+ raise ValueError(f'tracked source missing: {src}')
333
+ before[str(rel)] = digest(src)
334
+ dst.parent.mkdir(parents=True, exist_ok=True)
335
+ shutil.copy2(src, dst)
336
+ return before
337
+
338
+
339
+ def edit_method_model() -> None:
340
+ path = STAGE / 'sections/methods_model.tex'
341
+ body = path.read_text().split('\\subsection*{SLE benchmark and frozen cell-type annotator}')[0]
342
+ body = body.replace('Fig.~\\ref{fig:fig1}b', 'Fig.~\\ref{fig:fig1}')
343
+ body = body.replace('Fig.~\\ref{fig:fig1}a', 'Fig.~\\ref{fig:fig1}')
344
+ body = body.replace('Fig.~\\ref{fig:fig1}c', 'Fig.~\\ref{fig:fig1}')
345
+ body = body.replace('Fig.~\\ref{fig:fig1}d', 'Fig.~\\ref{fig:fig1}')
346
+ body = body.replace('Fig.~\\ref{fig:fig1}f', 'Fig.~\\ref{fig:fig2}')
347
+ body = re.sub(r'It produced every generated cell set in this study except the threshold-read-out sets.*?Unless stated otherwise',
348
+ 'The pretraining design rescoring in Fig.~\\\\ref{fig:fig2} uses saved epoch-16 Bernoulli outputs. Unless stated otherwise',
349
+ body, flags=re.S)
350
+ body += '\n\\subsection*{Held-out pretraining design rescore}\n'
351
+ body += ('Saved architecture and gene-panel outputs for the 42 held-out SLE donors were rescored '
352
+ 'separately. On the common 1,006-gene axis, each donor contributed 100 real reference cells, '
353
+ '100 disjoint real query cells and 100 generated cells per arm. One fixed Poisson read-out, '
354
+ 'a real-reference 50-component PCA and $k=10$ local neighbourhoods defined precision and '
355
+ 'coverage. The architecture and panel families had different training detection floors and '
356
+ 'are not a factorial comparison. One saved generation seed per arm makes these descriptive scores.\n')
357
+ path.write_text(body)
358
+
359
+
360
+ def overlay(final: bool) -> list[str]:
361
+ changed = []
362
+ for src in sorted((EDITS / 'sections').glob('*.tex')):
363
+ dst = STAGE / 'sections' / src.name
364
+ shutil.copy2(src, dst)
365
+ changed.append(str(dst.relative_to(STAGE)))
366
+ edit_method_model()
367
+ changed.append('sections/methods_model.tex')
368
+ main = STAGE / 'main.tex'
369
+ content = main.read_text()
370
+ content = content.replace('% Overleaf main document.', '% RESTRUCTURING DRAFT: strict Figures 3--5 remain pending.\n% Overleaf main document.', 1)
371
+ content = content.replace('% Figures with their legends, each on its own page(s). Panels are the deck\'s vector graphics, placed as-is;\n% the 180 mm journal layout is still to be drawn.',
372
+ '% Figure 1--5 restructuring draft; strict missing panels are explicitly labelled.')
373
+ if final:
374
+ content = content.replace('% RESTRUCTURING DRAFT: strict Figures 3--5 remain pending.\n', '')
375
+ else:
376
+ content = content.replace('\\maketitle',
377
+ '\\maketitle\n\\noindent\\fcolorbox{red}{white}{\\parbox{0.92\\textwidth}{'
378
+ '\\textbf{RESTRUCTURING DRAFT.} Strict five-pair results for Figs 2--5 '
379
+ 'are incomplete. The approved title, abstract and Introduction retain their '
380
+ 'original wording and must be rereviewed against final strict results.}}\\par\\medskip', 1)
381
+ main.write_text(content)
382
+ changed.append('main.tex')
383
+ supp = STAGE / 'supplementary.tex'
384
+ supp_text = supp.read_text()
385
+ supp_text = supp_text.replace('\\begin{document}',
386
+ '\\begin{document}\n\\noindent\\textcolor{red}{[HISTORICAL SUPPLEMENTARY DRAFT: '
387
+ 'legacy analyses have not been reconciled with exact-five-pair support.]}\\par\\medskip', 1)
388
+ supp.write_text(supp_text)
389
+ changed.append('supplementary.tex')
390
+ figures = dict(FIGURES)
391
+ if final:
392
+ complete_results()
393
+ (STAGE / 'sections/fig2.tex').write_text(
394
+ '\\mainfigure{fig:fig2}{Pretraining design, real-bulk adaptation and exact paired-data budgets}\n'
395
+ '\\figpanelh{}{figures/strict_20261012/fig2_ablation_and_support.pdf}{0.80}\n'
396
+ '\\figlegend{Native pseudobulk architecture and panel sweeps use the same held-out '
397
+ 'donors, measured genes and readout within each sweep; the 1\\% and 0.1\\% training '
398
+ 'floors are distinct experiments. Composition uses the same selected cells and frozen '
399
+ 'annotator. Full fine-tuning and LoRA ranks 4, 16 and 64 use matched real-bulk '
400
+ 'five-fold train/validation/test sets. Rank 16 is the quality--parameter-budget choice, '
401
+ 'not the best on every metric. Strict learning curves use exactly 5, 10, 20 or 40 '
402
+ 'different donor/sample pairs, fixed 3,000 LoRA updates and no extra validation pairs. '
403
+ 'Raw and external AIFI calibration use zero target paired single-cell samples. '
404
+ 'Foldwise points and means are descriptive; generated cells are not independent donors.}\n'
405
+ '\\figpanelh{Historical architecture logFC/DEG benchmark; original protocol}{figures/deck_20261010/sec03_width_bench.pdf}{0.44}\n'
406
+ '\\figpanelh{Historical gene-panel logFC/DEG benchmark; original protocol}{figures/deck_20261010/sec03_panel.pdf}{0.44}\n'
407
+ '\\figlegend{These historical panels retain their original epoch aggregation, readouts '
408
+ 'and unequal available generation-seed budgets. They connect the expression/DEG '
409
+ 'endpoints to the newly rescored geometry and composition endpoints, but are not '
410
+ 'same-protocol numerical comparisons with the panels above.}\n')
411
+ changed.append('sections/fig2.tex')
412
+ figures.update(FINAL_FIGURES)
413
+ strict_figures = {
414
+ 'fig3': ('Healthy exact five-pair OOF', 'fig3_healthy_strict_oof.pdf'),
415
+ 'fig4': ('Disease exact five-pair draws', 'fig4_disease_strict_draws.pdf'),
416
+ 'fig5': ('Paired rare states under exact five-pair support', 'fig5_rare_states_strict.pdf'),
417
+ }
418
+ for name, (title, filename) in strict_figures.items():
419
+ p = STAGE / 'sections' / f'{name}.tex'
420
+ panels = f'\\figpanelh{{}}{{figures/strict_20261012/{filename}}}{{0.77}}\n'
421
+ if name == 'fig3':
422
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig3_realism_metrics.pdf}{0.38}\n')
423
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig3_canonical_marker_dotplot.pdf}{0.42}\n')
424
+ for extra in ('umap_by_celltype','composition_fractions','runtime_components'):
425
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig3_{extra}.pdf}}{{0.62}}\n'
426
+ if name == 'fig4':
427
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig4_disease_signal_strict.pdf}{0.48}\n'
428
+ '\\figpanelh{}{figures/strict_20261012/fig4_deconvolution_strict.pdf}{0.42}\n'
429
+ '\\figpanelh{}{figures/strict_20261012/fig4_deconvolution_expression_strict.pdf}{0.48}\n')
430
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig4_historical_5fold_separate.pdf}{0.38}\n')
431
+ for extra in ('scatter','heatmap','cat'):
432
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig4_disease_signal_{extra}.pdf}}{{0.60}}\n'
433
+ if name == 'fig5':
434
+ for extra in ('rare_visuals','all_states','behcet_rules'):
435
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig5_{extra}_strict.pdf}}{{0.72}}\n'
436
+ p.write_text(f'\\mainfigure{{fig:{name}}}{{{title}}}\n' + panels +
437
+ '\\figlegend{Strict-support results and source-data tables are '
438
+ 'reported in the corresponding Results section. Figure 4 historical '
439
+ 'five-fold values appear in a separate labelled panel.}\n')
440
+ for source, target in figures.items():
441
+ src = ROOT / 'figures' / source
442
+ if not src.is_file():
443
+ raise ValueError(f'missing figure: {src}')
444
+ dst = STAGE / 'figures/strict_20261012' / target
445
+ dst.parent.mkdir(parents=True, exist_ok=True)
446
+ shutil.copy2(src, dst)
447
+ changed.append(str(dst.relative_to(STAGE)))
448
+ evidence = ('source_data/fig1_corpus_aggregates.json',
449
+ 'source_data/ablation_pretrain_pc.csv',
450
+ 'source_data/ablation_pretrain_pc_receipt.json',
451
+ 'source_data/fig2_historical_rank_full.csv',
452
+ 'source_data/fig4_historical_5fold.csv',
453
+ 'reports/figure1_provenance.json',
454
+ 'reports/figures234_readiness.json',
455
+ 'reports/rare_provenance.json')
456
+ if final:
457
+ evidence += ('source_data/fig2_strict_curve.csv',
458
+ 'source_data/fig3_per_sample.csv',
459
+ 'source_data/fig3_extras.csv',
460
+ 'source_data/fig3_runtime.csv',
461
+ 'source_data/fig3_runtime.json',
462
+ 'source_data/fig3_visual_data.json',
463
+ 'source_data/fig4_strict_per_sample.csv',
464
+ 'source_data/fig4_corrected_statistics.csv',
465
+ 'source_data/fig4_cross_draw_donor_ci.csv',
466
+ 'source_data/fig4_cross_draw_donor_ci.json',
467
+ 'source_data/fig4_donor_aware_signal.csv',
468
+ 'source_data/fig4_donor_aware_summary.csv',
469
+ 'source_data/fig4_donor_aware_genes.csv',
470
+ 'source_data/fig4_donor_aware_cat.csv',
471
+ 'source_data/fig4_donor_aware_provenance.json',
472
+ 'source_data/fig4_strict_contrast.csv',
473
+ 'source_data/fig4_deconvolution.csv',
474
+ 'source_data/fig4_deconvolution_signal.csv',
475
+ 'source_data/rare_summary.csv',
476
+ 'source_data/rare_ineligible_states.csv',
477
+ 'source_data/rare_behcet_descriptive.csv')
478
+ for rel in evidence:
479
+ src = ROOT / rel
480
+ if not src.is_file():
481
+ raise ValueError(f'missing source data: {src}')
482
+ dst = STAGE / 'strict_20261012' / rel
483
+ dst.parent.mkdir(parents=True, exist_ok=True)
484
+ shutil.copy2(src, dst)
485
+ changed.append(str(dst.relative_to(STAGE)))
486
+ changed.extend(['sections/fig1.tex', 'sections/fig2.tex', 'sections/fig3.tex',
487
+ 'sections/fig4.tex', 'sections/fig5.tex'])
488
+ return sorted(set(changed))
489
+
490
+
491
+ def verify_unchanged_frontmatter(original: dict[str, str]) -> None:
492
+ for name in ('sections/abstract.tex', 'sections/introduction.tex', 'authors.tex'):
493
+ if digest(STAGE / name) != original[name]:
494
+ raise ValueError(f'user-approved frontmatter changed: {name}')
495
+ canonical_main = (CANON / 'main.tex').read_text()
496
+ staged_main = (STAGE / 'main.tex').read_text()
497
+ for pattern in (r'\\title\{[^\n]+', r'\\abstract\{[^\n]+'):
498
+ if re.search(pattern, canonical_main).group() != re.search(pattern, staged_main).group():
499
+ raise ValueError(f'user-approved title or abstract command changed: {pattern}')
500
+
501
+
502
+ def allowed_frontmatter_refresh(previous: dict[str, str], current: dict[str, str],
503
+ *, old_main: str | None = None, new_main: str | None = None) -> dict:
504
+ """Permit only new approved Title, Abstract and Introduction source text."""
505
+ changed = {name: {'previous_sha256': old, 'current_sha256': current.get(name)}
506
+ for name, old in previous.items() if current.get(name) != old}
507
+ allowed = {'main.tex', 'sections/abstract.tex', 'sections/introduction.tex'}
508
+ extra = set(changed) - allowed
509
+ if extra:
510
+ raise ValueError(f'canonical source changed outside approved frontmatter: {sorted(extra)}')
511
+ if 'main.tex' in changed:
512
+ if old_main is None or new_main is None:
513
+ raise ValueError('main.tex changed beyond approved title/abstract commands')
514
+ pattern = r'\\(?:title|abstract)\{[^\n]*\}'
515
+ if re.sub(pattern, r'\\frontmatter{APPROVED}', old_main) != re.sub(
516
+ pattern, r'\\frontmatter{APPROVED}', new_main):
517
+ raise ValueError('main.tex changed beyond approved title/abstract commands')
518
+ return changed
519
+
520
+
521
+ def main() -> None:
522
+ p = argparse.ArgumentParser(description=__doc__)
523
+ mode = p.add_mutually_exclusive_group(required=True)
524
+ mode.add_argument('--preview', action='store_true')
525
+ mode.add_argument('--require-complete', action='store_true')
526
+ args = p.parse_args()
527
+ if subprocess.check_output(['git', '-C', str(CANON), 'status', '--porcelain']).strip():
528
+ raise SystemExit('canonical manuscript is not clean; refusing to assemble')
529
+ checked_provenance(ROOT / 'reports/figure1_provenance.json', 'Figure 1')
530
+ pretrain = checked_provenance(ROOT / 'source_data/ablation_pretrain_pc_receipt.json', 'Figure 2 P/C')
531
+ recipe = pretrain.get('recipe', {})
532
+ if (pretrain.get('schema') != 'pbisc.fig2.pretrain_pc.v1' or
533
+ recipe.get('n_pcs') != 50 or recipe.get('local_k') != 10 or
534
+ pretrain.get('gene_axis', {}).get('n') != 1006 or
535
+ {r['family'] for r in rows(ROOT / 'source_data/ablation_pretrain_pc.csv')} !=
536
+ {'architecture_floor1pct', 'panel_floor0.1pct'}):
537
+ raise SystemExit('Figure 2 measured P/C receipt or source table differs from the frozen rescore')
538
+ gaps, readiness = strict_gate()
539
+ if args.require_complete and gaps:
540
+ raise SystemExit('final assembly refused:\n- ' + '\n- '.join(sorted(set(gaps))))
541
+ previous = STAGE / 'integration_manifest.json'
542
+ refreshed = {}
543
+ if previous.is_file() and args.require_complete:
544
+ prior = document(previous)
545
+ old = prior.get('canonical_source_sha256', {})
546
+ current = {rel: digest(CANON / rel) if (CANON / rel).is_file() else None for rel in old}
547
+ old_main = None
548
+ if current.get('main.tex') != old.get('main.tex'):
549
+ old_head = prior.get('canonical_head')
550
+ if not old_head:
551
+ raise SystemExit('review preview has no canonical head for frontmatter comparison')
552
+ old_main = subprocess.check_output(['git', '-C', str(CANON), 'show',
553
+ f'{old_head}:main.tex'], text=True)
554
+ try:
555
+ refreshed = allowed_frontmatter_refresh(old, current, old_main=old_main,
556
+ new_main=(CANON / 'main.tex').read_text())
557
+ except ValueError as exc:
558
+ raise SystemExit(str(exc)) from exc
559
+ originals = copy_source_files()
560
+ changed = overlay(args.require_complete)
561
+ verify_unchanged_frontmatter(originals)
562
+ # Keep the original claims available for review without placing them in Results.
563
+ legacy = STAGE / 'editorial/legacy_results'
564
+ legacy.mkdir(parents=True, exist_ok=True)
565
+ for name in ('results_fig1', 'results_fig2', 'results_fig3', 'results_fig4',
566
+ 'results_fig5', 'results_fig6', 'methods_paired', 'methods_eval', 'discussion'):
567
+ src = CANON / 'sections' / f'{name}.tex'
568
+ shutil.copy2(src, legacy / src.name)
569
+ changed.append(str((legacy / src.name).relative_to(STAGE)))
570
+ manifest = {
571
+ 'schema': 'pbisc.paper.manuscript-integration.v1',
572
+ 'mode': 'complete' if args.require_complete else 'restructuring_preview',
573
+ 'canonical_root': str(CANON), 'stage_root': str(STAGE),
574
+ 'canonical_head': subprocess.check_output(['git', '-C', str(CANON), 'rev-parse', 'HEAD'], text=True).strip(),
575
+ 'canonical_source_sha256': originals,
576
+ 'approved_frontmatter_refresh': refreshed,
577
+ 'staged_changes': {rel: {'sha256': digest(STAGE / rel),
578
+ 'canonical_sha256': originals.get(rel)} for rel in changed},
579
+ 'figure_source_sha256': {name: digest(ROOT / 'figures' / name) for name in
580
+ (FIGURES | (FINAL_FIGURES if args.require_complete else {}))},
581
+ 'readiness': readiness,
582
+ 'gaps': gaps,
583
+ 'figure6': 'waiting_user_prepared_data; unchanged placeholder',
584
+ 'git_push': False, 'overleaf_sync': False,
585
+ }
586
+ previous.write_text(json.dumps(manifest, indent=2) + '\n')
587
+ print(json.dumps({'mode': manifest['mode'], 'staged_changed_files': len(changed),
588
+ 'gaps': gaps, 'manifest': str(previous)}, indent=2))
589
+
590
+
591
+ if __name__ == '__main__':
592
+ main()
paper-releases/pbisc-diffusion/updates/20261012T131501Z-strictpairs-final-caption/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/archive/20261012T131501Z-strictpairs-final-caption/assemble_manuscript_before_final_caption_fix.py ADDED
@@ -0,0 +1,565 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Stage the PBISC-Diffusion Figure 1--5 manuscript without changing its Git tree.
3
+
4
+ --preview emits an explicitly incomplete review draft. --require-complete refuses
5
+ until every strict unit and its source binding has been verified, then uses the
6
+ same staged file map. No Git, archive or network write is performed here.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import csv
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import shutil
16
+ import subprocess
17
+ from collections import defaultdict
18
+ from pathlib import Path
19
+
20
+ ROOT = Path(__file__).resolve().parents[1]
21
+ CANON = Path('/home/sj_server_1/PBISC/paper-release-20260928/manuscript')
22
+ STAGE = ROOT / 'manuscript'
23
+ EDITS = STAGE / 'edits'
24
+ COHORTS = ('ye2026_sepsis', 'imperial_eskd', 'giroux2022', 'ji2025_chili')
25
+ FIGURES = {
26
+ 'fig1_overview.pdf': 'fig1_overview.pdf',
27
+ 'fig2_ablation_and_support.pdf': 'fig2_ablation_and_support.pdf',
28
+ 'fig4_historical_5fold_separate.pdf': 'fig4_historical_5fold_separate.pdf',
29
+ }
30
+ FINAL_FIGURES = {
31
+ 'fig3_healthy_strict_oof.pdf': 'fig3_healthy_strict_oof.pdf',
32
+ 'fig3_realism_metrics.pdf': 'fig3_realism_metrics.pdf',
33
+ 'fig3_canonical_marker_dotplot.pdf': 'fig3_canonical_marker_dotplot.pdf',
34
+ 'fig3_umap_by_celltype.pdf': 'fig3_umap_by_celltype.pdf',
35
+ 'fig3_composition_fractions.pdf': 'fig3_composition_fractions.pdf',
36
+ 'fig3_runtime_components.pdf': 'fig3_runtime_components.pdf',
37
+ 'fig4_disease_strict_draws.pdf': 'fig4_disease_strict_draws.pdf',
38
+ 'fig4_disease_signal_strict.pdf': 'fig4_disease_signal_strict.pdf',
39
+ 'fig4_disease_signal_scatter.pdf': 'fig4_disease_signal_scatter.pdf',
40
+ 'fig4_disease_signal_heatmap.pdf': 'fig4_disease_signal_heatmap.pdf',
41
+ 'fig4_disease_signal_cat.pdf': 'fig4_disease_signal_cat.pdf',
42
+ 'fig4_deconvolution_strict.pdf': 'fig4_deconvolution_strict.pdf',
43
+ 'fig4_deconvolution_expression_strict.pdf': 'fig4_deconvolution_expression_strict.pdf',
44
+ 'fig5_rare_states_strict.pdf': 'fig5_rare_states_strict.pdf',
45
+ 'fig5_rare_visuals_strict.pdf': 'fig5_rare_visuals_strict.pdf',
46
+ 'fig5_all_states_strict.pdf': 'fig5_all_states_strict.pdf',
47
+ 'fig5_behcet_rules_strict.pdf': 'fig5_behcet_rules_strict.pdf',
48
+ }
49
+
50
+
51
+ def digest(path: Path) -> str:
52
+ h = hashlib.sha256()
53
+ with path.open('rb') as f:
54
+ for chunk in iter(lambda: f.read(1024 * 1024), b''):
55
+ h.update(chunk)
56
+ return h.hexdigest()
57
+
58
+
59
+ def document(path: Path) -> dict:
60
+ return json.loads(path.read_text())
61
+
62
+
63
+ def rows(path: Path) -> list[dict[str, str]]:
64
+ with path.open(newline='') as f:
65
+ return list(csv.DictReader(f))
66
+
67
+
68
+ def tracked_sources() -> list[Path]:
69
+ raw = subprocess.check_output(['git', '-C', str(CANON), 'ls-files', '-z'])
70
+ paths = [Path(p.decode()) for p in raw.split(b'\0') if p]
71
+ wanted = {'.tex', '.bib', '.cls', '.bst'}
72
+ return [p for p in paths if p.suffix in wanted or
73
+ (p.parts[0] == 'figures' and p.suffix.lower() in {'.pdf', '.png'})]
74
+
75
+
76
+ def checked_provenance(path: Path, label: str) -> dict:
77
+ if not path.is_file():
78
+ raise ValueError(f'{label}: missing {path}')
79
+ item = document(path)
80
+ for entry in item.get('sources', []) + item.get('outputs', []):
81
+ source = Path(entry['path'])
82
+ if not source.is_file() or digest(source) != entry['sha256']:
83
+ raise ValueError(f'{label}: source/output hash mismatch: {source}')
84
+ return item
85
+
86
+
87
+ def strict_gate() -> tuple[list[str], dict]:
88
+ gaps = []
89
+ readiness_path = ROOT / 'reports/figures234_readiness.json'
90
+ readiness = document(readiness_path) if readiness_path.is_file() else {}
91
+ if readiness.get('schema') != 'pbisc.paper.figures234.v1' or readiness.get('status') != 'complete':
92
+ gaps.append('Figures 2--4 readiness is not complete')
93
+ f2, f3, f4 = (readiness.get(k, {}) for k in ('figure2', 'figure3', 'figure4'))
94
+ if f2.get('strict_complete_units') != 20 or f2.get('strict_missing') or not f2.get('pretrain_composition_ready'):
95
+ gaps.append('Figure 2 needs 20/20 strict healthy support units')
96
+ if (f3.get('strict_complete_folds') != 5 or not f3.get('visual_export_ready') or
97
+ not f3.get('extras_complete') or not f3.get('runtime_ready')):
98
+ gaps.append('Figure 3 needs 5/5 folds, visual, extras and time receipts')
99
+ if (set(f4.get('strict_complete_draws', {})) != set(COHORTS) or
100
+ any(f4['strict_complete_draws'].get(c) != 5 for c in COHORTS) or
101
+ any(f4.get(k) for k in ('contrast_missing', 'deconvolution_missing',
102
+ 'deconvolution_signal_missing'))):
103
+ gaps.append('Figure 4 needs 5/5 strict draws per cohort and contrast/deconvolution evidence')
104
+ expected_healthy = {(f'fold{fold}', n) for fold in range(5) for n in (5, 10, 20, 40)}
105
+ expected_disease = {(c, f'draw{draw}') for c in COHORTS for draw in range(5)}
106
+ curve = rows(ROOT / 'source_data/fig2_strict_curve.csv')
107
+ if {(r['fold'], int(r['n_pairs'])) for r in curve} != expected_healthy:
108
+ gaps.append('Figure 2 strict CSV has incomplete fold/size units')
109
+ healthy = rows(ROOT / 'source_data/fig3_per_sample.csv')
110
+ if {r['fold'] for r in healthy} != {f'fold{n}' for n in range(5)}:
111
+ gaps.append('Figure 3 strict per-sample CSV has incomplete folds')
112
+ disease = rows(ROOT / 'source_data/fig4_strict_per_sample.csv')
113
+ if {(r['cohort'], r['draw']) for r in disease} != expected_disease or any(
114
+ r.get('design') != 'strict_exact5_donor_draw' for r in disease):
115
+ gaps.append('Figure 4 strict CSV has incomplete or mixed-design draws')
116
+ for filename, table in [('fig2_strict_curve.csv', curve), ('fig3_per_sample.csv', healthy),
117
+ ('fig4_strict_per_sample.csv', disease)]:
118
+ if not table or any(not r.get('support_sha256') for r in table):
119
+ gaps.append(f'{filename} lacks source-bound support hashes')
120
+ for record in curve + healthy + disease:
121
+ source = record.get('summary')
122
+ source_hash = record.get('summary_sha256')
123
+ if source and source_hash and (not Path(source).is_file() or digest(Path(source)) != source_hash):
124
+ gaps.append(f'score summary hash mismatch: {source}')
125
+ break
126
+ for table, kind in ((curve, 'healthy'), (healthy, 'healthy'), (disease, 'disease')):
127
+ for record in table:
128
+ cohort = record.get('cohort', 'immicro')
129
+ unit = record.get('fold') if kind == 'healthy' else record.get('draw')
130
+ suffix = f'{unit}/n{record["n_pairs"]}' if table is curve else (
131
+ f'{unit}/n5' if kind == 'healthy' else unit)
132
+ support = ROOT / 'protocol/splits' / cohort / kind / suffix / 'support.json'
133
+ if not support.is_file() or document(support).get('sha256') != record.get('support_sha256'):
134
+ gaps.append(f'{cohort}/{kind}/{suffix}: source support mismatch')
135
+ break
136
+ summary = ROOT / 'scores' / cohort / kind / suffix / 'score/summary.json'
137
+ score_sha = record.get('score_sha256') or record.get('summary_sha256')
138
+ if not summary.is_file() or digest(summary) != score_sha:
139
+ gaps.append(f'{cohort}/{kind}/{suffix}: score summary hash mismatch')
140
+ break
141
+ rare_path = ROOT / 'reports/rare_provenance.json'
142
+ rare = document(rare_path) if rare_path.is_file() else {}
143
+ units = rare.get('units', [])
144
+ if (rare.get('schema') != 'pbisc.figure5.analysis.v1' or len(units) != 20 or
145
+ {(u.get('cohort'), u.get('unit')) for u in units} != expected_disease or
146
+ any(u.get('design') != 'strict5pair' or u.get('evidence_tier') != 'strict'
147
+ or not u.get('support_sha256') for u in units)):
148
+ gaps.append('Figure 5 needs all 20 strict rare-state receipts')
149
+ rare_table = rows(ROOT / 'source_data/rare_summary.csv')
150
+ if (not rare_table or {r.get('evidence_tier') for r in rare_table} != {'strict'} or
151
+ {(r['cohort'], r['unit']) for r in rare_table} != expected_disease):
152
+ gaps.append('Figure 5 rare-state CSV is absent, diagnostic or incomplete')
153
+ for cohort, unit in expected_disease:
154
+ subset = [r for r in rare_table if r.get('cohort') == cohort and r.get('unit') == unit]
155
+ if {r.get('arm') for r in subset} != {'raw', 'refcal', 'pairedcal', 'scsemi', 'lora'}:
156
+ gaps.append(f'Figure 5 strict arms incomplete: {cohort}/{unit}')
157
+ break
158
+ for unit in units:
159
+ support = ROOT / 'protocol/splits' / str(unit.get('cohort')) / 'disease' / str(unit.get('unit')) / 'support.json'
160
+ if not support.is_file() or document(support).get('sha256') != unit.get('support_sha256'):
161
+ gaps.append(f'Figure 5 strict support hash mismatch: {unit.get("cohort")}/{unit.get("unit")}')
162
+ break
163
+ if readiness.get('status') == 'complete':
164
+ runtime = ROOT / 'source_data/fig3_runtime.csv'
165
+ runtime_meta = ROOT / 'source_data/fig3_runtime.json'
166
+ visual = ROOT / 'source_data/fig3_visual_data.npz'
167
+ visual_meta = ROOT / 'source_data/fig3_visual_data.json'
168
+ if (not runtime.is_file() or not runtime_meta.is_file() or
169
+ document(runtime_meta).get('csv_sha256') != digest(runtime)):
170
+ gaps.append('Figure 3 runtime source/receipt hash mismatch')
171
+ if (not visual.is_file() or not visual_meta.is_file() or
172
+ document(visual_meta).get('npz_sha256') != digest(visual)):
173
+ gaps.append('Figure 3 visual source/receipt hash mismatch')
174
+ extras = ROOT / 'source_data/fig3_extras.csv'
175
+ if not extras.is_file() or not rows(extras):
176
+ gaps.append('Figure 3 realism extras CSV is missing')
177
+ for name in ('fig4_strict_contrast.csv', 'fig4_deconvolution.csv',
178
+ 'fig4_deconvolution_signal.csv', 'fig4_corrected_statistics.csv',
179
+ 'fig4_cross_draw_donor_ci.csv', 'fig4_donor_aware_signal.csv',
180
+ 'fig4_donor_aware_summary.csv', 'fig4_donor_aware_genes.csv',
181
+ 'fig4_donor_aware_cat.csv'):
182
+ path = ROOT / 'source_data' / name
183
+ if not path.is_file() or not rows(path):
184
+ gaps.append(f'Figure 4 required source table missing: {name}')
185
+ cross = ROOT / 'source_data/fig4_cross_draw_donor_ci.csv'
186
+ cross_receipt = ROOT / 'source_data/fig4_cross_draw_donor_ci.json'
187
+ if (not cross_receipt.is_file() or not cross.is_file() or
188
+ document(cross_receipt).get('csv_sha256') != digest(cross) or
189
+ {r.get('cohort') for r in rows(cross)} != set(COHORTS)):
190
+ gaps.append('Figure 4 five-draw donor-cluster CI source or receipt mismatch')
191
+ corrected = ROOT / 'source_data/fig4_donor_aware_signal.csv'
192
+ corrected_provenance = ROOT / 'source_data/fig4_donor_aware_provenance.json'
193
+ corrected_rows = rows(corrected) if corrected.is_file() else []
194
+ if (not corrected_provenance.is_file() or not corrected_rows or
195
+ {(r.get('cohort'), r.get('draw')) for r in corrected_rows} != expected_disease or
196
+ any(r.get('status') not in ('ok', 'not_estimable') for r in corrected_rows)):
197
+ gaps.append('Figure 4 corrected donor-aware disease signal is absent or incomplete')
198
+ for filename in FINAL_FIGURES:
199
+ if not (ROOT / 'figures' / filename).is_file():
200
+ gaps.append(f'missing strict figure: {filename}')
201
+ return gaps, readiness
202
+
203
+
204
+ def numeric_summary(table: list[dict], keys: tuple[str, ...], metrics: tuple[str, ...]) -> str:
205
+ """Render observed means only; no unsupported ordering or P value."""
206
+ data: dict[tuple[str, ...], dict[str, list[float]]] = defaultdict(lambda: defaultdict(list))
207
+ for row in table:
208
+ group = tuple(row[k] for k in keys)
209
+ for metric in metrics:
210
+ try:
211
+ value = float(row[metric])
212
+ except (KeyError, ValueError, TypeError):
213
+ continue
214
+ if value == value and value not in (float('inf'), float('-inf')):
215
+ data[group][metric].append(value)
216
+ lines = []
217
+ for group, values in sorted(data.items()):
218
+ parts = [f'{key}={value}' for key, value in zip(keys, group)]
219
+ parts += [f'{metric}={sum(items)/len(items):.3f} (n={len(items)})'
220
+ for metric, items in values.items() if items]
221
+ lines.append('; '.join(parts).replace('_', r'\_') + r'\par')
222
+ return '\n'.join(lines)
223
+
224
+
225
+ def complete_results() -> None:
226
+ """Fill only numbers present in verified strict CSVs; leave no preview placeholders."""
227
+ additions = {
228
+ 2: ('source_data/fig2_strict_curve.csv', ('n_pairs', 'arm'), ('precision', 'coverage')),
229
+ 3: ('source_data/fig3_per_sample.csv', ('arm',), ('precision', 'coverage', 'comp_l1')),
230
+ 4: ('source_data/fig4_strict_per_sample.csv', ('cohort', 'arm'), ('pb_r', 'comp_l1')),
231
+ 5: ('source_data/rare_summary.csv', ('cohort', 'arm'), ('mae_donor_pp', 'generated_zero_donors')),
232
+ }
233
+ openers = {
234
+ 2: (r'\subsection*{Pretraining design and strict paired-support curve}' '\n'
235
+ 'The held-out native-pseudobulk precision and coverage ablations use the '
236
+ 'common 1,006-gene rescore described in Methods. Architecture and gene-panel '
237
+ 'families have different training detection floors. The nested ImMicro curve '
238
+ 'uses five outer folds and $n=5,10,20,40$ distinct training donors per fold. '
239
+ 'Historical rank and full-parameter five-fold results are reported separately.\n'),
240
+ 3: (r'\subsection*{Healthy generation with exact five-pair support}' '\n'
241
+ 'Each ImMicro outer fold uses one matched sample from each of five training '
242
+ 'donors for LoRA, paired calibration and scSemiProfiler. The remaining donors '
243
+ 'are evaluated on common observed cells, measured genes and frozen labels. '
244
+ 'Figure~\\ref{fig:fig3} displays the strict quality measures and operational '
245
+ 'time, which excludes population pretraining.\n'),
246
+ 4: (r'\subsection*{Disease comparisons with exact five-pair support}' '\n'
247
+ 'Each of four disease cohorts contributes five frozen draws. One earliest '
248
+ 'identity-passed matched-stratum visit per selected donor trains all arms; '
249
+ 'other visits of that donor are excluded. Donor-aware disease contrasts and '
250
+ 'deconvolution are scored on the common held-out support. The old five-fold '
251
+ 'analysis remains a separate historical sensitivity analysis.\n'),
252
+ 5: (r'\subsection*{Rare states with paired support}' '\n'
253
+ 'All four disease cohorts and five draws use the exact same five-pair supports '
254
+ 'as Figure~\\ref{fig:fig4}. Zero-generated-state draws remain in every '
255
+ 'aggregate, required-marker failures make a state ineligible, and repeated '
256
+ 'visits are clustered by donor. The unmatched Beh\\c{c}et analysis is '
257
+ 'descriptive and separate.\n'),
258
+ }
259
+ for number, (source, keys, metrics) in additions.items():
260
+ path = STAGE / 'sections' / f'results_fig{number}.tex'
261
+ text = openers[number]
262
+ text += ('\n\\textbf{Measured strict-support summary.} Values below are arithmetic means '
263
+ 'of the named source-data rows; $n$ counts rows, not independent donors. '
264
+ 'Donor-cluster uncertainty and formal comparisons require the separate '
265
+ 'statistics receipts.\\par\n')
266
+ text += numeric_summary(rows(ROOT / source), keys, metrics) + '\n'
267
+ if number == 3:
268
+ extras = []
269
+ for record in rows(ROOT / 'source_data/fig3_extras.csv'):
270
+ if record.get('table') == 'metrics.csv' and record.get('mode') == 'raw':
271
+ extras.append({'arm': record.get('set', ''), **record})
272
+ elif (record.get('table') == 'en.csv' and record.get('cellset') == 'pc'
273
+ and record.get('distance') == 'sq'):
274
+ extras.append({'arm': record.get('set', ''), **record})
275
+ text += ('\n\\textbf{Realism and operational time.} C2ST AUC, MMD$^2$ '
276
+ 'and $E_N$ are computed from the strict extras; time is fine-tuning '
277
+ 'plus inference seconds, with pretraining excluded.\\par\n')
278
+ text += numeric_summary(extras, ('arm',), ('c2st_rf_auc', 'mmd2_sum', 'en')) + '\n'
279
+ text += numeric_summary(rows(ROOT / 'source_data/fig3_runtime.csv'),
280
+ ('arm',), ('operational_seconds',)) + '\n'
281
+ if number == 4:
282
+ donor_aware = [r for r in rows(ROOT / 'source_data/fig4_donor_aware_signal.csv')
283
+ if r.get('status') == 'ok']
284
+ text += ('\n\\textbf{Primary donor-aware disease signal.} Equal-patient '
285
+ 'condition contrasts, with repeated visits collapsed by donor and '
286
+ 'condition, are reported by cohort, arm, cell type and draw. '
287
+ 'A missing population is marked not estimable and contributes no '
288
+ 'fabricated zero. The values below summarize estimable rows; '
289
+ 'patient-cluster intervals are in the accompanying source tables.\\par\n')
290
+ text += numeric_summary(donor_aware, ('cohort', 'arm'),
291
+ ('pearson_r', 'partial_r', 'cat50', 'limma_top50')) + '\n'
292
+ contrast = [r for r in rows(ROOT / 'source_data/fig4_strict_contrast.csv')
293
+ if r.get('table') == 'headline.csv']
294
+ text += ('\n\\textbf{Historical contrast sensitivity.} The legacy per-sample '
295
+ 'logFC, CAT and limma headline values below retain their original '
296
+ 'independent-sample definition. They are separate from corrected '
297
+ 'donor-aware disease signal.\\par\n')
298
+ text += numeric_summary(contrast, ('cohort', 'arm'),
299
+ ('partial_r', 'cat50', 'limma_top50')) + '\n'
300
+ text += ('\n\\textbf{Cross-draw uncertainty.} Donor-cluster confidence intervals '
301
+ 'over all five verified draws, with repeated visits and draw membership '
302
+ 'kept together, are supplied in '
303
+ '\\texttt{fig4\\_cross\\_draw\\_donor\\_ci.csv}.\\par\n')
304
+ text += ('\n\\textbf{Same-support deconvolution.} Deconvolution '
305
+ 'provides fractions and supported cell-type expression, not '
306
+ 'generated-cell realism scores.\\par\n')
307
+ text += numeric_summary(rows(ROOT / 'source_data/fig4_deconvolution.csv'),
308
+ ('cohort', 'arm'), ('composition_l1',)) + '\n'
309
+ path.write_text(text)
310
+ path = STAGE / 'sections/discussion.tex'
311
+ path.write_text('\\section*{Discussion}\n'
312
+ 'The strict-support numerical summaries in Figs~2--5 report the completed '
313
+ 'five-pair design. They should be interpreted with their donor-cluster '
314
+ 'uncertainty and source tables; row counts are not biological replicates. '
315
+ 'Historical five-fold and unmatched Beh\\c{c}et analyses remain separate. '
316
+ 'Figure~\\ref{fig:fig6} awaits the user-prepared bulk-only reproduction data.\n')
317
+
318
+
319
+ def copy_source_files() -> dict[str, str]:
320
+ before = {}
321
+ for rel in tracked_sources():
322
+ src, dst = CANON / rel, STAGE / rel
323
+ if not src.is_file():
324
+ raise ValueError(f'tracked source missing: {src}')
325
+ before[str(rel)] = digest(src)
326
+ dst.parent.mkdir(parents=True, exist_ok=True)
327
+ shutil.copy2(src, dst)
328
+ return before
329
+
330
+
331
+ def edit_method_model() -> None:
332
+ path = STAGE / 'sections/methods_model.tex'
333
+ body = path.read_text().split('\\subsection*{SLE benchmark and frozen cell-type annotator}')[0]
334
+ body = body.replace('Fig.~\\ref{fig:fig1}b', 'Fig.~\\ref{fig:fig1}')
335
+ body = body.replace('Fig.~\\ref{fig:fig1}a', 'Fig.~\\ref{fig:fig1}')
336
+ body = body.replace('Fig.~\\ref{fig:fig1}c', 'Fig.~\\ref{fig:fig1}')
337
+ body = body.replace('Fig.~\\ref{fig:fig1}d', 'Fig.~\\ref{fig:fig1}')
338
+ body = body.replace('Fig.~\\ref{fig:fig1}f', 'Fig.~\\ref{fig:fig2}')
339
+ body = re.sub(r'It produced every generated cell set in this study except the threshold-read-out sets.*?Unless stated otherwise',
340
+ 'The pretraining design rescoring in Fig.~\\\\ref{fig:fig2} uses saved epoch-16 Bernoulli outputs. Unless stated otherwise',
341
+ body, flags=re.S)
342
+ body += '\n\\subsection*{Held-out pretraining design rescore}\n'
343
+ body += ('Saved architecture and gene-panel outputs for the 42 held-out SLE donors were rescored '
344
+ 'separately. On the common 1,006-gene axis, each donor contributed 100 real reference cells, '
345
+ '100 disjoint real query cells and 100 generated cells per arm. One fixed Poisson read-out, '
346
+ 'a real-reference 50-component PCA and $k=10$ local neighbourhoods defined precision and '
347
+ 'coverage. The architecture and panel families had different training detection floors and '
348
+ 'are not a factorial comparison. One saved generation seed per arm makes these descriptive scores.\n')
349
+ path.write_text(body)
350
+
351
+
352
+ def overlay(final: bool) -> list[str]:
353
+ changed = []
354
+ for src in sorted((EDITS / 'sections').glob('*.tex')):
355
+ dst = STAGE / 'sections' / src.name
356
+ shutil.copy2(src, dst)
357
+ changed.append(str(dst.relative_to(STAGE)))
358
+ edit_method_model()
359
+ changed.append('sections/methods_model.tex')
360
+ main = STAGE / 'main.tex'
361
+ content = main.read_text()
362
+ content = content.replace('% Overleaf main document.', '% RESTRUCTURING DRAFT: strict Figures 3--5 remain pending.\n% Overleaf main document.', 1)
363
+ content = content.replace('% Figures with their legends, each on its own page(s). Panels are the deck\'s vector graphics, placed as-is;\n% the 180 mm journal layout is still to be drawn.',
364
+ '% Figure 1--5 restructuring draft; strict missing panels are explicitly labelled.')
365
+ if final:
366
+ content = content.replace('% RESTRUCTURING DRAFT: strict Figures 3--5 remain pending.\n', '')
367
+ else:
368
+ content = content.replace('\\maketitle',
369
+ '\\maketitle\n\\noindent\\fcolorbox{red}{white}{\\parbox{0.92\\textwidth}{'
370
+ '\\textbf{RESTRUCTURING DRAFT.} Strict five-pair results for Figs 2--5 '
371
+ 'are incomplete. The approved title, abstract and Introduction retain their '
372
+ 'original wording and must be rereviewed against final strict results.}}\\par\\medskip', 1)
373
+ main.write_text(content)
374
+ changed.append('main.tex')
375
+ supp = STAGE / 'supplementary.tex'
376
+ supp_text = supp.read_text()
377
+ supp_text = supp_text.replace('\\begin{document}',
378
+ '\\begin{document}\n\\noindent\\textcolor{red}{[HISTORICAL SUPPLEMENTARY DRAFT: '
379
+ 'legacy analyses have not been reconciled with exact-five-pair support.]}\\par\\medskip', 1)
380
+ supp.write_text(supp_text)
381
+ changed.append('supplementary.tex')
382
+ figures = dict(FIGURES)
383
+ if final:
384
+ complete_results()
385
+ figures.update(FINAL_FIGURES)
386
+ strict_figures = {
387
+ 'fig3': ('Healthy exact five-pair OOF', 'fig3_healthy_strict_oof.pdf'),
388
+ 'fig4': ('Disease exact five-pair draws', 'fig4_disease_strict_draws.pdf'),
389
+ 'fig5': ('Paired rare states under exact five-pair support', 'fig5_rare_states_strict.pdf'),
390
+ }
391
+ for name, (title, filename) in strict_figures.items():
392
+ p = STAGE / 'sections' / f'{name}.tex'
393
+ panels = f'\\figpanelh{{}}{{figures/strict_20261012/{filename}}}{{0.77}}\n'
394
+ if name == 'fig3':
395
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig3_realism_metrics.pdf}{0.38}\n')
396
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig3_canonical_marker_dotplot.pdf}{0.42}\n')
397
+ for extra in ('umap_by_celltype','composition_fractions','runtime_components'):
398
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig3_{extra}.pdf}}{{0.62}}\n'
399
+ if name == 'fig4':
400
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig4_disease_signal_strict.pdf}{0.48}\n'
401
+ '\\figpanelh{}{figures/strict_20261012/fig4_deconvolution_strict.pdf}{0.42}\n'
402
+ '\\figpanelh{}{figures/strict_20261012/fig4_deconvolution_expression_strict.pdf}{0.48}\n')
403
+ panels += ('\\figpanelh{}{figures/strict_20261012/fig4_historical_5fold_separate.pdf}{0.38}\n')
404
+ for extra in ('scatter','heatmap','cat'):
405
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig4_disease_signal_{extra}.pdf}}{{0.60}}\n'
406
+ if name == 'fig5':
407
+ for extra in ('rare_visuals','all_states','behcet_rules'):
408
+ panels += f'\\figpanelh{{}}{{figures/strict_20261012/fig5_{extra}_strict.pdf}}{{0.72}}\n'
409
+ p.write_text(f'\\mainfigure{{fig:{name}}}{{{title}}}\n' + panels +
410
+ '\\figlegend{Strict-support results and source-data tables are '
411
+ 'reported in the corresponding Results section. Figure 4 historical '
412
+ 'five-fold values appear in a separate labelled panel.}\n')
413
+ for source, target in figures.items():
414
+ src = ROOT / 'figures' / source
415
+ if not src.is_file():
416
+ raise ValueError(f'missing figure: {src}')
417
+ dst = STAGE / 'figures/strict_20261012' / target
418
+ dst.parent.mkdir(parents=True, exist_ok=True)
419
+ shutil.copy2(src, dst)
420
+ changed.append(str(dst.relative_to(STAGE)))
421
+ evidence = ('source_data/fig1_corpus_aggregates.json',
422
+ 'source_data/ablation_pretrain_pc.csv',
423
+ 'source_data/ablation_pretrain_pc_receipt.json',
424
+ 'source_data/fig2_historical_rank_full.csv',
425
+ 'source_data/fig4_historical_5fold.csv',
426
+ 'reports/figure1_provenance.json',
427
+ 'reports/figures234_readiness.json',
428
+ 'reports/rare_provenance.json')
429
+ if final:
430
+ evidence += ('source_data/fig2_strict_curve.csv',
431
+ 'source_data/fig3_per_sample.csv',
432
+ 'source_data/fig3_extras.csv',
433
+ 'source_data/fig3_runtime.csv',
434
+ 'source_data/fig3_runtime.json',
435
+ 'source_data/fig3_visual_data.json',
436
+ 'source_data/fig4_strict_per_sample.csv',
437
+ 'source_data/fig4_corrected_statistics.csv',
438
+ 'source_data/fig4_cross_draw_donor_ci.csv',
439
+ 'source_data/fig4_cross_draw_donor_ci.json',
440
+ 'source_data/fig4_donor_aware_signal.csv',
441
+ 'source_data/fig4_donor_aware_summary.csv',
442
+ 'source_data/fig4_donor_aware_genes.csv',
443
+ 'source_data/fig4_donor_aware_cat.csv',
444
+ 'source_data/fig4_donor_aware_provenance.json',
445
+ 'source_data/fig4_strict_contrast.csv',
446
+ 'source_data/fig4_deconvolution.csv',
447
+ 'source_data/fig4_deconvolution_signal.csv',
448
+ 'source_data/rare_summary.csv',
449
+ 'source_data/rare_ineligible_states.csv',
450
+ 'source_data/rare_behcet_descriptive.csv')
451
+ for rel in evidence:
452
+ src = ROOT / rel
453
+ if not src.is_file():
454
+ raise ValueError(f'missing source data: {src}')
455
+ dst = STAGE / 'strict_20261012' / rel
456
+ dst.parent.mkdir(parents=True, exist_ok=True)
457
+ shutil.copy2(src, dst)
458
+ changed.append(str(dst.relative_to(STAGE)))
459
+ changed.extend(['sections/fig1.tex', 'sections/fig2.tex', 'sections/fig3.tex',
460
+ 'sections/fig4.tex', 'sections/fig5.tex'])
461
+ return sorted(set(changed))
462
+
463
+
464
+ def verify_unchanged_frontmatter(original: dict[str, str]) -> None:
465
+ for name in ('sections/abstract.tex', 'sections/introduction.tex', 'authors.tex'):
466
+ if digest(STAGE / name) != original[name]:
467
+ raise ValueError(f'user-approved frontmatter changed: {name}')
468
+ canonical_main = (CANON / 'main.tex').read_text()
469
+ staged_main = (STAGE / 'main.tex').read_text()
470
+ for pattern in (r'\\title\{[^\n]+', r'\\abstract\{[^\n]+'):
471
+ if re.search(pattern, canonical_main).group() != re.search(pattern, staged_main).group():
472
+ raise ValueError(f'user-approved title or abstract command changed: {pattern}')
473
+
474
+
475
+ def allowed_frontmatter_refresh(previous: dict[str, str], current: dict[str, str],
476
+ *, old_main: str | None = None, new_main: str | None = None) -> dict:
477
+ """Permit only new approved Title, Abstract and Introduction source text."""
478
+ changed = {name: {'previous_sha256': old, 'current_sha256': current.get(name)}
479
+ for name, old in previous.items() if current.get(name) != old}
480
+ allowed = {'main.tex', 'sections/abstract.tex', 'sections/introduction.tex'}
481
+ extra = set(changed) - allowed
482
+ if extra:
483
+ raise ValueError(f'canonical source changed outside approved frontmatter: {sorted(extra)}')
484
+ if 'main.tex' in changed:
485
+ if old_main is None or new_main is None:
486
+ raise ValueError('main.tex changed beyond approved title/abstract commands')
487
+ pattern = r'\\(?:title|abstract)\{[^\n]*\}'
488
+ if re.sub(pattern, r'\\frontmatter{APPROVED}', old_main) != re.sub(
489
+ pattern, r'\\frontmatter{APPROVED}', new_main):
490
+ raise ValueError('main.tex changed beyond approved title/abstract commands')
491
+ return changed
492
+
493
+
494
+ def main() -> None:
495
+ p = argparse.ArgumentParser(description=__doc__)
496
+ mode = p.add_mutually_exclusive_group(required=True)
497
+ mode.add_argument('--preview', action='store_true')
498
+ mode.add_argument('--require-complete', action='store_true')
499
+ args = p.parse_args()
500
+ if subprocess.check_output(['git', '-C', str(CANON), 'status', '--porcelain']).strip():
501
+ raise SystemExit('canonical manuscript is not clean; refusing to assemble')
502
+ checked_provenance(ROOT / 'reports/figure1_provenance.json', 'Figure 1')
503
+ pretrain = checked_provenance(ROOT / 'source_data/ablation_pretrain_pc_receipt.json', 'Figure 2 P/C')
504
+ recipe = pretrain.get('recipe', {})
505
+ if (pretrain.get('schema') != 'pbisc.fig2.pretrain_pc.v1' or
506
+ recipe.get('n_pcs') != 50 or recipe.get('local_k') != 10 or
507
+ pretrain.get('gene_axis', {}).get('n') != 1006 or
508
+ {r['family'] for r in rows(ROOT / 'source_data/ablation_pretrain_pc.csv')} !=
509
+ {'architecture_floor1pct', 'panel_floor0.1pct'}):
510
+ raise SystemExit('Figure 2 measured P/C receipt or source table differs from the frozen rescore')
511
+ gaps, readiness = strict_gate()
512
+ if args.require_complete and gaps:
513
+ raise SystemExit('final assembly refused:\n- ' + '\n- '.join(sorted(set(gaps))))
514
+ previous = STAGE / 'integration_manifest.json'
515
+ refreshed = {}
516
+ if previous.is_file() and args.require_complete:
517
+ prior = document(previous)
518
+ old = prior.get('canonical_source_sha256', {})
519
+ current = {rel: digest(CANON / rel) if (CANON / rel).is_file() else None for rel in old}
520
+ old_main = None
521
+ if current.get('main.tex') != old.get('main.tex'):
522
+ old_head = prior.get('canonical_head')
523
+ if not old_head:
524
+ raise SystemExit('review preview has no canonical head for frontmatter comparison')
525
+ old_main = subprocess.check_output(['git', '-C', str(CANON), 'show',
526
+ f'{old_head}:main.tex'], text=True)
527
+ try:
528
+ refreshed = allowed_frontmatter_refresh(old, current, old_main=old_main,
529
+ new_main=(CANON / 'main.tex').read_text())
530
+ except ValueError as exc:
531
+ raise SystemExit(str(exc)) from exc
532
+ originals = copy_source_files()
533
+ changed = overlay(args.require_complete)
534
+ verify_unchanged_frontmatter(originals)
535
+ # Keep the original claims available for review without placing them in Results.
536
+ legacy = STAGE / 'editorial/legacy_results'
537
+ legacy.mkdir(parents=True, exist_ok=True)
538
+ for name in ('results_fig1', 'results_fig2', 'results_fig3', 'results_fig4',
539
+ 'results_fig5', 'results_fig6', 'methods_paired', 'methods_eval', 'discussion'):
540
+ src = CANON / 'sections' / f'{name}.tex'
541
+ shutil.copy2(src, legacy / src.name)
542
+ changed.append(str((legacy / src.name).relative_to(STAGE)))
543
+ manifest = {
544
+ 'schema': 'pbisc.paper.manuscript-integration.v1',
545
+ 'mode': 'complete' if args.require_complete else 'restructuring_preview',
546
+ 'canonical_root': str(CANON), 'stage_root': str(STAGE),
547
+ 'canonical_head': subprocess.check_output(['git', '-C', str(CANON), 'rev-parse', 'HEAD'], text=True).strip(),
548
+ 'canonical_source_sha256': originals,
549
+ 'approved_frontmatter_refresh': refreshed,
550
+ 'staged_changes': {rel: {'sha256': digest(STAGE / rel),
551
+ 'canonical_sha256': originals.get(rel)} for rel in changed},
552
+ 'figure_source_sha256': {name: digest(ROOT / 'figures' / name) for name in
553
+ (FIGURES | (FINAL_FIGURES if args.require_complete else {}))},
554
+ 'readiness': readiness,
555
+ 'gaps': gaps,
556
+ 'figure6': 'waiting_user_prepared_data; unchanged placeholder',
557
+ 'git_push': False, 'overleaf_sync': False,
558
+ }
559
+ previous.write_text(json.dumps(manifest, indent=2) + '\n')
560
+ print(json.dumps({'mode': manifest['mode'], 'staged_changed_files': len(changed),
561
+ 'gaps': gaps, 'manifest': str(previous)}, indent=2))
562
+
563
+
564
+ if __name__ == '__main__':
565
+ main()
paper-releases/pbisc-diffusion/updates/20261012T131501Z-strictpairs-final-caption/diffusion/metadata/inference_locations.json ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ {
2
+ "locations": [],
3
+ "project_id": "pbisc-diffusion",
4
+ "update_id": "20261012T131501Z-strictpairs-final-caption"
5
+ }
paper-releases/pbisc-diffusion/updates/20261012T131501Z-strictpairs-final-caption/diffusion/metadata/request.json ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "assets": [
3
+ {
4
+ "host": "server_1",
5
+ "kind": "code",
6
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/archive/20261012T131501Z-strictpairs-final-caption/assemble_manuscript.py",
7
+ "state": "intermediate"
8
+ },
9
+ {
10
+ "host": "server_1",
11
+ "kind": "code",
12
+ "source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/archive/20261012T131501Z-strictpairs-final-caption/assemble_manuscript_before_final_caption_fix.py",
13
+ "state": "stopped"
14
+ }
15
+ ],
16
+ "inference_locations": [],
17
+ "project_id": "pbisc-diffusion",
18
+ "summary": "Final-gated Figure 2 caption fix: remove pending language only after strict completion; include same-readout composition and all comparator budgets, retain original logFC/DEG panels with explicit historical epoch/readout/seed differences. Current review deck/manuscript remain previews. Ten focused checks and syntax compilation passed. No new scientific experiment, GitHub push or Overleaf sync."
19
+ }