junidude14 commited on
Commit
a78e1a9
·
verified ·
1 Parent(s): 972825d

Archive 4 checkpoints (1-4)

Browse files
paper-releases/pbisc-diffusion/updates/20261013T094815Z-all-celltypes-final-palette-142/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/pair_budget_celltypes_20261013/fraction_mae.pdf ADDED
Binary file (31.5 kB). View file
 
paper-releases/pbisc-diffusion/updates/20261013T094815Z-all-celltypes-final-palette-142/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/pair_budget_celltypes_20261013/fraction_mae.png ADDED

Git LFS Details

  • SHA256: a9ec7305dce62e56975363e4b19c1c7512f4fdc3ed58136baaf5bfe61d19f370
  • Pointer size: 131 Bytes
  • Size of remote file: 339 kB
paper-releases/pbisc-diffusion/updates/20261013T094815Z-all-celltypes-final-palette-142/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/figures/pair_budget_celltypes_20261013/fraction_mae.svg ADDED
paper-releases/pbisc-diffusion/updates/20261013T094815Z-all-celltypes-final-palette-142/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/apply_final_palette_20261013.py ADDED
@@ -0,0 +1,464 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Apply the final method palette to explicitly audited deck assets.
2
+
3
+ Sources are never changed. Vector rewrites preserve text, paths and images;
4
+ native exceptions replay saved-table renderers. One legacy PNG receives only a
5
+ source-defined, region-bounded method-arrow colour translation with pixel proof.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import argparse
10
+ import ast
11
+ import base64
12
+ import hashlib
13
+ import importlib.util
14
+ import json
15
+ import os
16
+ import shutil
17
+ import sys
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ os.environ["CUDA_VISIBLE_DEVICES"] = ""
22
+ import fitz
23
+ import numpy as np
24
+ import pandas as pd
25
+ from PIL import Image
26
+
27
+ D = Path(__file__).resolve().parents[1]
28
+ sys.path.insert(0, str(D / "tools"))
29
+ import review_palette_pdf as V
30
+
31
+ DATA = D / "data/final_palette_20261013"
32
+ FIG = D / "figures/final_palette_20261013"
33
+ DECISION = D / "PBISC-Diffusion_color_palette_20261013.md"
34
+ DEFAULT_SPEC = D / "data/figure_enrichment_20261013/spec.json"
35
+ LO, CAL, RAW, SC, BP, CX = "#168FE5", "#59A8DF", "#C3E2F4", "#83C6A8", "#D9B23F", "#F0D77D"
36
+ FULL = "#0D6EA8"
37
+ RULES: dict[str, dict] = {}
38
+
39
+
40
+ def rule(names, mapping=None, *, reason, mode="vector"):
41
+ for name in names.split():
42
+ if name in RULES:
43
+ raise ValueError("Duplicate semantic rule: " + name)
44
+ RULES[name] = {"mode": mode, "mapping": mapping or {}, "reason": reason}
45
+
46
+
47
+ STANDARD = {"#C5AA4B": LO, "#2166AC": SC, "#E8DDAE": RAW, "#B59A50": CAL}
48
+ SC_ONLY = {**STANDARD, "#8E823C": "#3F91C5"}
49
+ ARCH = {"#C5AA4B": LO, "#8F772B": FULL, "#B59A50": CAL, "#66531E": "#164C70",
50
+ "#D8C57E": "#A6D4EF", "#9D8240": "#388DBD", "#806A25": FULL}
51
+ OLD_ARCH = {**STANDARD, "#D4BE75": "#93C6E8", "#806A25": FULL, "#6F5B1B": "#164C70",
52
+ "#DED09B": "#A6D4EF", "#978034": "#377FAD", "#E69F00": SC}
53
+ MODES = {**SC_ONLY, "#806A25": FULL, "#D4BE75": "#92C4E5"}
54
+ INPUTS = {"#E8DDAE": RAW, "#D2BC70": "#A6D4EF", "#B59A50": CAL, "#9C8138": "#388FCA",
55
+ "#806A25": "#79B8E0", "#C5AA4B": "#73B8E5", "#65521B": "#267FB9", "#A68B3C": "#9BCDEC"}
56
+
57
+ rule("fig1d_corpus sec01_slide_a trajectory_four_pca_frames sec05_cells_umap sec01_fig1a_denoiser",
58
+ reason="Cell types, corpus categories or value/support computational components; not method-series colours.", mode="preserve")
59
+ rule("sec02_backbone_compare", reason="PBISC column and changed-feature highlights use PBISC blue; the colour-word caption becomes neutral while every table cell stays fixed.", mode="native-backbone")
60
+ rule("sec02_bulk_conditioning", reason="Colours distinguish input/conditioning components, not competing models.", mode="preserve")
61
+ rule("sec06_eval_design sec09_cohorts", reason="Neutral sample/design metadata.", mode="preserve")
62
+ rule("labels_real_cell_repeat labels_metrics_overview", reason="Real-cell sampling schematic or metric-family categories, not method colours.", mode="preserve")
63
+ rule("mismatch_expression_values", reason="Blue density represents numbers of donor-gene observations, not a method series.", mode="preserve")
64
+ rule("sec05_shift_cohorts", reason="Input-space measured versus offset-removed diagnostic; preserve its non-model intervention encoding.", mode="preserve")
65
+ rule("stored_real_reference_umap saved_density_difference input_control_composition label_transitions immicro_replicate_controls annotation_agreement",
66
+ reason="Cell-type/cohort palettes, density or confusion-matrix values, or observed-reference controls.", mode="preserve")
67
+ rule("strict_ye2026_sepsis_deg strict_imperial_eskd_deg covid_endpoints external_rare_screen rare_misses_1 rare_misses_2 sepsis_rare_support sepsis_rare_direction review_style_20261013_rare_observed",
68
+ reason="Heatmap colours encode numerical magnitudes; row/column labels carry method identities.", mode="preserve")
69
+ rule("review_style_20261013_rare_corrected_comparison", reason="Point colours identify cohorts, while axes identify the methods.", mode="preserve")
70
+ rule("covid_monocyte_direction_detail covid_cd14_direction_detail", reason="Filled versus open gold/white markers identify depth1000 versus native readout, not models.", mode="preserve")
71
+ rule("c1q_cross_disease", reason="Colours identify one-gene versus two-gene C1Q rules, not methods.", mode="preserve")
72
+ rule("bulkonly_imperial_wave_shift bulkonly_verification_history sec10_paired_subset_cohorts",
73
+ reason="Wave, audit disposition or planning status; preserve these non-method colours.", mode="preserve")
74
+ rule("fig5_rare_fivefold", reason="All point colours identify cohorts; pale acceptable-error band is a numeric guide.", mode="preserve")
75
+ rule("fig1_umap_seven_panels_by_label_depth1000", reason="Cell types and grey reference cells only, including embedded raster points.", mode="preserve")
76
+ rule("fraction_correlation fraction_mae", reason="New all-celltype plots already use the approved final method palette.", mode="approved-native")
77
+
78
+ rule("fig1b_overview_nature", {"#8F772B": FULL, "#F6F0DC": "#EDF6FC", "#DED09B": "#A2D1ED", "#A48A34": LO},
79
+ reason="Model blocks and adaptation arrows only; biological channels retain their original colours.")
80
+ rule("arch_context_vs_trunk arch_hint_injection", {**ARCH, "#F7F2DF": "#EDF6FC", "#DDD5BC": "#BBD9EA", "#FCFAF1": "#F8FBFE"},
81
+ reason="PBISC computational blocks, model variants and their pale backgrounds; no measured biology.")
82
+ rule("arch_width_arm_register arch_panel_arm_register", {"#F7F2DF": "#EDF6FC", "#806A25": FULL, "#E4DFD2": "#D4E4EF", "#FCFBF6": "#F8FBFE"},
83
+ reason="Model-register header and stripe colours; all parameter/time text stays fixed.")
84
+ rule("arch_width_loss_progression arch_panel_loss_progression arch_all_arm_compute", ARCH,
85
+ reason="PBISC architecture/gene-panel variants; line styles, markers and failed-run status retained.")
86
+ rule("sec03_width_bench", OLD_ARCH, reason="PBISC architecture variants blue; scSemi reference mint.")
87
+ rule("sec03_panel", {**STANDARD, "#978034": "#377FAD"}, reason="PBISC gene panels blue; scSemi reference mint.")
88
+ rule("labels_ablation", {"#C5AA4B": LO, "#B79A3F": CAL, "#967B2B": FULL, "#DEC975": "#A6D4EF"},
89
+ reason="PBISC ablation families use blue shades; black real-cell repeat reference remains unchanged.")
90
+ rule("mismatch_same_donor_errors", {"#C5AA4B": CAL}, reason="Ten-pair calibration medium blue; measured bulk and paired lines remain neutral.")
91
+ rule("sec06_ft_method", {"#C5AA4B": LO}, reason="Trainable PBISC LoRA blocks and merges.")
92
+ rule("review_style_20261013_rank fig2_healthy_modes fig4_disease_variants sec07_ft_modes", MODES,
93
+ reason="LoRA bright blue; full FT darker blue; other PBISC adaptation variants retain distinct blue shades.")
94
+ rule("fig3_healthy_pairs fig3_healthy_fewpair fig3_healthy_copy fig2_healthy_pairs fig4_disease_fewpair sec09_fewpair_cells sec09_extra_ksens sec09_same_pairs sec04_sle_benchmark sec04_sle_per_celltype fig3_time_days sec09_extra_fewpair sec09_scsemi_representative",
95
+ STANDARD, reason="LoRA, same-pair calibration, raw conditions and scSemi method identities.")
96
+ rule("fig4_disease_fivefold sec09_cat_curves sec09_extra_fivefold fig2_healthy_cells fig2_healthy_realism", SC_ONLY,
97
+ reason="PBISC raw/calibrated/sc-only/LoRA blue family and scSemi mint.")
98
+ rule("review_style_20261013_healthy_composition", {"#C5AA4B": LO, "#2166AC": SC}, reason="Paired PBISC-versus-scSemi absolute-error and donor-win comparison.")
99
+ rule("sec09_time_to_apply", {"#C5AA4B": LO, "#E5D59C": CAL, "#2166AC": SC, "#67A9CF": "#B6DEC8"}, reason="Adaptation/generation stages retain light/dark variants within each method family.")
100
+ rule("secS_deconv_disease secS_deconv_composition", {"#C5AA4B": LO, "#2166AC": SC, "#009E73": BP, "#6A51A3": CX}, reason="PBISC blue, scSemi mint, BayesPrism gold and CIBERSORTx pale gold.")
101
+ rule("sec04_sle_broadcast", {"#C5AA4B": LO, "#2166AC": SC}, reason="PBISC and scSemi methods; bulk broadcast remains its labelled neutral reference.")
102
+ rule("sec05_cells_metrics", {"#E8DDAE": RAW, "#B59A50": CAL, "#C5AA4B": "#79B8E0"}, reason="PBISC raw versus pseudobulk-conditioned controls; actual observed cells remain grey.")
103
+ rule("fig2_healthy_rank sec07_rank_sweep", {"#C5AA4B": LO, "#E8DDAE": "#9DCFEF", "#806A25": FULL}, reason="PBISC rank variants, not a method-versus-cell-type colour encoding.")
104
+ rule("sec07_k_aug", {"#C5AA4B": LO, "#5E5E5E": CAL, "#BDBDBD": RAW}, reason="All three arms are PBISC LoRA conditions: plain blue, multi-K medium blue, half-batch recipes pale blue. Neutral text and axes stay unchanged.", mode="vector-gray-variants")
105
+ rule("sec08_pairs_realism sec08_pairs_signal", {**STANDARD, "#DAC990": "#A6D4EF"}, reason="LoRA/raw/calibrated/TPM inputs blue family; scSemi mint; observed and null references neutral.")
106
+ rule("sec08_cross_cohort sec08_cross_cohort_steps", {**STANDARD, "#D4BE75": "#86BDE2", "#978034": "#3E92C7", "#665522": FULL}, reason="Distinct PBISC cross-cohort adaptation variants.")
107
+ rule("sec07_no_pretraining sec08_cross_scratch secS_scratch_rare_states", {**STANDARD, "#806A25": "#BC9632", "#D4BE75": "#86BDE2", "#978034": "#3E92C7", "#665522": FULL},
108
+ reason="Pretrained PBISC/adaptation blue; from-scratch comparator dark yellow; neutral references unchanged.")
109
+ rule("sec10_other_tissues", {"#C5AA4B": LO, "#806A25": "#BC9632"}, reason="Pretrained-versus-scratch evidence; prospective tissue labels unchanged.")
110
+ rule("secA_scsemi_readout", {"#C5AA4B": LO, "#2166AC": SC, "#67A9CF": "#B6DEC8"}, reason="Official and modified scSemi mint shades; original hatching retained.")
111
+ rule("fig5_rare_fraction fig5_rare_donors", {"#C5AA4B": LO, "#E8DDAE": RAW, "#2166AC": SC},
112
+ reason="Already separated method-colour tuples; Ji/Imperial and all cohort colours remain unchanged.")
113
+ rule("review_style_20261013_behcet", {"#C5AA4B": LO, "#B59A50": CAL}, reason="PBISC conditions and LoRA, with observed references black.")
114
+ rule("sec05_behcet_direction", {"#E8DDAE": RAW, "#B59A50": CAL}, reason="Raw-bulk PBISC diagnostic; neutral observed and pseudobulk oracle controls retained.")
115
+ rule("matched_similarity nearest_real_by_type labels_within_type_centroids stored_matched_trajectories raw_tpm_top_genes donor_axes reference_choice depth_matched_quality labels_detection_and_library",
116
+ INPUTS, reason="PBISC input-condition variants only. Distinct six-cell-type palette and reference grey are untouched; no LoRA in these panels.")
117
+ rule("sle_conditioning_interventions", {"#C5AA4B": LO, "#806A25": FULL, "#B59A50": CAL, "#E8DDAE": RAW}, reason="PBISC conditioning intervention variants; not disease/cohort-category colours.")
118
+ rule("strict_sepsis_quality strict_sepsis_realism strict_imperial_draw0_quality", {"#C5AA4B": LO, "#2166AC": SC, "#E9DFB9": RAW, "#D7C788": "#88BFE4", "#97802C": CAL}, reason="Five explicit strict comparison methods; real/real remains grey.")
119
+ rule("behcet_k4000", {"#DDD0A0": RAW, "#C5AA4B": LO, "#826B22": FULL}, reason="Raw versus LoRA K1000/K4000 method settings.")
120
+ rule("k4000_quality k4000_disease k4000_calibration", {"#C5AA4B": LO, "#826B22": FULL}, reason="Existing PBISC K1000/K4000 recipe variants.")
121
+ rule("deconv_expression_coverage", {"#6A51A3": CX}, reason="CIBERSORTx method, with open-marker missingness retained.")
122
+ rule("fig_randolph_celltype_response", {"#E8DDAE": RAW, "#B59A50": "#82BDE3", "#978034": CAL, "#806A25": "#79B8E0", "#2166AC": SC}, reason="PBISC raw/refcal/cal/pseudobulk conditions; neutral measured/oracle broadcasts retained.")
123
+ rule("gene_length_input gene_length_stable refcal_top_genes healthy_ft_comparison sle_disjoint_truth_control", reason="Source-native role-specific replay, required by embedded method rasters/shared colour roles.", mode="native")
124
+ rule("fig2_covid_hc_monocyte_arrows_depth1000", reason="PNG-only recorded map: recolour only source-defined method arrows/legend in their known panels; protect every other pixel.", mode="scoped-raster")
125
+
126
+
127
+ def sha(path):
128
+ with Path(path).open("rb") as handle:
129
+ return hashlib.file_digest(handle, "sha256").hexdigest()
130
+
131
+
132
+ def binding(path, role="source"):
133
+ p = Path(path).resolve()
134
+ return {"path": str(p), "sha256": sha(p), "bytes": p.stat().st_size, "role": role}
135
+
136
+
137
+ def dump(path, obj):
138
+ Path(path).write_text(json.dumps(obj, indent=2, allow_nan=False) + "\n")
139
+
140
+
141
+ def module(name):
142
+ p = D / "tools" / f"{name}.py"
143
+ spec = importlib.util.spec_from_file_location("_final_palette_" + name, p)
144
+ obj = importlib.util.module_from_spec(spec); spec.loader.exec_module(obj)
145
+ return obj
146
+
147
+
148
+ def collect(spec_path):
149
+ spec = json.loads(Path(spec_path).read_text())
150
+ assets = {}
151
+ for number, slide in enumerate(spec["slides"], 1):
152
+ for value in slide.get("figures", []):
153
+ p = Path(value); p = p if p.is_absolute() else D / p
154
+ assets.setdefault(p.resolve(), []).append(number)
155
+ extra = D / "data/pair_budget_celltypes_20261013/result.json"
156
+ if extra.exists():
157
+ for slide in json.loads(extra.read_text())["slides"]:
158
+ for value in slide["figures"]:
159
+ p = Path(value); p = p if p.is_absolute() else D / p
160
+ assets.setdefault(p.resolve(), [])
161
+ missing = [str(p) for p in assets if p.stem not in RULES]
162
+ if missing:
163
+ raise ValueError("Unclassified semantic assets: " + "; ".join(missing))
164
+ return assets
165
+
166
+
167
+ def pdf_geometry(source, target, *, caption_change=False, backbone_caption_change=False):
168
+ left, right = V._geometry(Path(source)), V._geometry(Path(target))
169
+ if caption_change or backbone_caption_change:
170
+ for document in (left, right):
171
+ for page in document:
172
+ for block in page["text_geometry"].get("blocks", []):
173
+ for line in block.get("lines", []):
174
+ # Character lists are used by rawdict; remove only the
175
+ # explicitly permitted colour-word caption line.
176
+ for span in line.get("spans", []):
177
+ text = "".join(c["c"] for c in span.get("chars", []))
178
+ permitted = (caption_change and "bars: generated log1p cp10k shift" in text.lower()) or (backbone_caption_change and text in {"orange = changed from SDD", "Highlighted = changed from SDD"})
179
+ if permitted:
180
+ span.clear(); line.pop("bbox", None); block.pop("bbox", None)
181
+ if left != right:
182
+ raise ValueError("Native rerender changed text/page geometry: " + str(source))
183
+ return True
184
+
185
+
186
+ def native_backbone(source):
187
+ """Replay only the original table drawing block, using its frozen 18-cell CSV."""
188
+ import matplotlib.pyplot as plt
189
+ source = Path(source)
190
+ renderer = D / "tools/sec02_backbone.py"
191
+ original_csv = D / "data/sec02_backbone_compare.csv"
192
+ frame = pd.read_csv(original_csv, keep_default_na=False)
193
+ if len(frame) != 18 or frame.duplicated(["row", "model"]).any():
194
+ raise ValueError("Backbone table must contain the original 18 distinct cells")
195
+ text = renderer.read_text()
196
+ parsed = ast.parse(text)
197
+ literals = {node.targets[0].id: ast.literal_eval(node.value) for node in parsed.body
198
+ if isinstance(node, ast.Assign) and len(node.targets) == 1
199
+ and isinstance(node.targets[0], ast.Name) and node.targets[0].id in {"ROWS", "COLS"}}
200
+ cells = {}; states = {}
201
+ for row in frame.itertuples(index=False):
202
+ value = tuple(row.cell_text.split(" | ")) if row.vs_sdd == "partial" else row.cell_text
203
+ cells[(row.row, row.model)] = (value, [])
204
+ if row.model == "PBISC-Diffusion": states[row.row] = (row.vs_sdd, row.vs_sdd_basis)
205
+ if set(cells) != {(row, name) for row in literals["ROWS"] for name, _ in literals["COLS"]}:
206
+ raise ValueError("Backbone table axes do not match source renderer")
207
+ start = 'W, H = style.FULL[0], 4.5'
208
+ stop = 'style.save(fig, "sec02_backbone_compare", FIG)'
209
+ if text.count(start) != 1 or text.count(stop) != 1:
210
+ raise ValueError("Backbone drawing section is ambiguous")
211
+ block = text[text.index(start):text.index(stop) + len(stop)]
212
+ if block.count('PB = style.ARM["pbisc"]') != 1 or block.count('"orange = changed from SDD"') != 1:
213
+ raise ValueError("Expected backbone palette/caption not found")
214
+ block = block.replace('PB = style.ARM["pbisc"]', 'PB = "#168FE5"').replace('"orange = changed from SDD"', '"Highlighted = changed from SDD"')
215
+ outdir = FIG / "native"; outdir.mkdir(parents=True, exist_ok=True)
216
+ datadir = DATA / "native"; datadir.mkdir(parents=True, exist_ok=True)
217
+ with plt.rc_context():
218
+ style = module("style")
219
+ scope = {**literals, "cells": cells, "VS_SDD": states, "style": style, "plt": plt, "FIG": outdir}
220
+ exec(compile(block, str(renderer) + "::comparison-only", "exec"), scope)
221
+ copied_csv = datadir / original_csv.name
222
+ shutil.copyfile(original_csv, copied_csv)
223
+ target_pdf = outdir / source.with_suffix(".pdf").name
224
+ pdf_geometry(source.with_suffix(".pdf"), target_pdf, backbone_caption_change=True)
225
+ return {"png": str(outdir/source.name), "pdf": str(target_pdf), "original": binding(source),
226
+ "original_pdf": binding(source.with_suffix(".pdf")), "sources": [binding(renderer), binding(D/"tools/style.py"), binding(original_csv)],
227
+ "original_csv": binding(original_csv), "new_csv": binding(copied_csv),
228
+ "numeric_csv_equal": sha(original_csv) == sha(copied_csv), "table_cells_preserved": 18,
229
+ "text_geometry_preserved_except_declared_caption": True,
230
+ "text_changes": [{"old": "orange = changed from SDD", "new": "Highlighted = changed from SDD", "reason": "Remove obsolete colour word"}],
231
+ "mapping": {"#D55E00": LO}, "preservation_pass": True}
232
+
233
+
234
+ def vector_k_variants(source):
235
+ """Translate only source-proven PBISC bar colours, including PDF DeviceGray."""
236
+ source = Path(source)
237
+ target_pdf = FIG / source.with_suffix(".pdf").name
238
+ target_png = FIG / source.name
239
+ gray_rules = {"#5E5E5E": CAL, "#BDBDBD": RAW}
240
+ counts = {old: 0 for old in gray_rules}; stream_proofs = []
241
+ with tempfile.TemporaryDirectory(prefix=".k-variants-", dir=FIG) as tmp:
242
+ intermediate = Path(tmp)/"plain.pdf"; updated = Path(tmp)/target_pdf.name
243
+ plain_proof = V.recolor_pdf(source.with_suffix(".pdf"), intermediate, {"#C5AA4B": LO})
244
+ with V.pikepdf.Pdf.open(intermediate) as pdf:
245
+ images_before = V._image_payloads(pdf)
246
+ expected = {}
247
+ for label, stream in V._content_streams(pdf):
248
+ before = list(V.pikepdf.parse_content_stream(stream)); after = list(before); slots = []
249
+ for index, instruction in enumerate(before):
250
+ if str(instruction.operator) != "g": continue
251
+ for old, new in gray_rules.items():
252
+ gray = int(old[1:3], 16)/255
253
+ if len(instruction.operands) == 1 and abs(float(instruction.operands[0])-gray) < 1e-8:
254
+ after[index] = V.pikepdf.ContentStreamInstruction(list(V._rgb(new)), V.pikepdf.Operator("rg"))
255
+ slots.append(index); counts[old] += 1
256
+ kept_before = [item for i,item in enumerate(before) if i not in slots]
257
+ kept_after = [item for i,item in enumerate(after) if i not in slots]
258
+ before_hash = V._fingerprint(kept_before, ignore_rgb=False)
259
+ if before_hash != V._fingerprint(kept_after, ignore_rgb=False):
260
+ raise ValueError("Non-target PDF operator changed")
261
+ expected[label] = V._fingerprint(after, ignore_rgb=False)
262
+ if slots:
263
+ stream.write(V.pikepdf.unparse_content_stream(after))
264
+ stream_proofs.append({"stream":label,"changed_color_slots":slots,"all_other_operator_sha256":before_hash})
265
+ if counts != {"#5E5E5E":10,"#BDBDBD":10}:
266
+ raise ValueError("K-variant grey operand counts differ from the source-defined five bars per arm: " + repr(counts))
267
+ pdf.save(updated)
268
+ with V.pikepdf.Pdf.open(updated) as pdf:
269
+ actual = {label: V._fingerprint(list(V.pikepdf.parse_content_stream(stream)), ignore_rgb=False)
270
+ for label, stream in V._content_streams(pdf)}
271
+ if actual != expected or V._image_payloads(pdf) != images_before:
272
+ raise ValueError("Serialized K-variant content/image preservation failed")
273
+ pdf_geometry(source.with_suffix(".pdf"), updated)
274
+ png = Path(tmp)/target_png.name
275
+ render = V.render_pdf_to_png(updated, png, dpi=200)
276
+ updated.replace(target_pdf); png.replace(target_png)
277
+ render.update(pdf=str(target_pdf), png=str(target_png))
278
+ return {"png":str(target_png),"pdf":str(target_pdf),"original":binding(source),
279
+ "original_pdf":binding(source.with_suffix(".pdf")),"renderer":binding(D/"tools/sec07_k_aug.py"),
280
+ "plain_lora_rgb_proof":plain_proof,"devicegray_to_rgb":gray_rules,"matched_color_operators":counts,
281
+ "method_bar_count":{"multi_k":5,"half_batch_recipes":5},"stream_proofs":stream_proofs,
282
+ "all_non_target_operators_preserved":True,"text_geometry_preserved":True,
283
+ "image_payloads_preserved":True,"render":render,"preservation_pass":True}
284
+
285
+
286
+ def native_replays(needed):
287
+ import matplotlib.pyplot as plt
288
+ from matplotlib.colors import to_hex
289
+ from matplotlib.text import Text
290
+ h = module("expanded_healthy_materials")
291
+ h.FIG = FIG / "native"; h.DATA = DATA / "native"
292
+ h.FIG.mkdir(parents=True, exist_ok=True); h.DATA.mkdir(parents=True, exist_ok=True)
293
+ for arm, old in list(h.COL.items()):
294
+ h.COL[arm] = INPUTS.get(old, old)
295
+
296
+ class Replay(h.MaterialBuilder):
297
+ def finish(self, fig, key, *args, **kwargs):
298
+ if key == "sle_disjoint_truth_control":
299
+ colors = {"#aaaaaa": BP, "#cccccc": CX, "#c5aa4b": LO, "#2166ac": SC}
300
+ for ax in fig.axes:
301
+ for patch in ax.patches:
302
+ old = to_hex(patch.get_facecolor())
303
+ if old in colors: patch.set_facecolor(colors[old])
304
+ if key == "refcal_top_genes":
305
+ for text in fig.findobj(match=Text):
306
+ if "Gold bars:" in text.get_text():
307
+ text.set_text(text.get_text().replace("Gold bars:", "Bars:"))
308
+ super().finish(fig, key, *args, **kwargs)
309
+
310
+ b = Replay()
311
+ settings = {"font.family":"sans-serif", "font.sans-serif":["Arial","Liberation Sans","DejaVu Sans"],
312
+ "font.size":14,"axes.labelsize":14,"axes.titlesize":14,"xtick.labelsize":12,"ytick.labelsize":12,
313
+ "legend.fontsize":12,"axes.spines.top":False,"axes.spines.right":False,"axes.linewidth":1.,
314
+ "pdf.fonttype":42,"ps.fonttype":42,"svg.fonttype":"none","figure.facecolor":"white","axes.facecolor":"white"}
315
+ with plt.rc_context(settings):
316
+ if "gene_length_input" in needed: h.gene_length(b, False)
317
+ if "gene_length_stable" in needed: h.gene_length(b, True)
318
+ if "refcal_top_genes" in needed: h.top_genes(b, True)
319
+ if "sle_disjoint_truth_control" in needed: h.split_half(b)
320
+ proofs = {}
321
+ for key in needed - {"healthy_ft_comparison"}:
322
+ original_csv = D / "data/expanded_master_20261013/healthy" / f"{key}.csv"
323
+ generated_csv = h.DATA / f"{key}.csv"
324
+ pd.testing.assert_frame_equal(pd.read_csv(original_csv), pd.read_csv(generated_csv), check_exact=True, check_dtype=False)
325
+ proofs[key] = {"png": str(h.FIG / f"{key}.png"), "pdf": str(h.FIG / f"{key}.pdf"),
326
+ "sources": list(b.sources.values()), "numeric_csv_equal": True,
327
+ "original_csv": binding(original_csv), "new_csv": binding(generated_csv),
328
+ "text_changes": [{"old":"Gold bars:","new":"Bars:","reason":"Remove obsolete colour word"}] if key == "refcal_top_genes" else []}
329
+ if "healthy_ft_comparison" in needed:
330
+ f = module("figure_order_healthy_ft_20261013")
331
+ f.FIG = FIG / "native"; f.DATA = DATA / "native"
332
+ f.COLORS = [RAW, CAL, FULL, LO]
333
+ result = f.build()
334
+ pd.testing.assert_frame_equal(pd.read_csv(D / "data/figure_order_fixed_20261013/healthy_ft_comparison.csv"),
335
+ pd.read_csv(f.DATA / "healthy_ft_comparison.csv"), check_exact=True, check_dtype=False)
336
+ proofs["healthy_ft_comparison"] = {"png": str(f.FIG / "healthy_ft_comparison.png"),
337
+ "pdf": str(f.FIG / "healthy_ft_comparison.pdf"),
338
+ "numeric_csv_equal": True, "source_renderer_proof": result, "text_changes": [],
339
+ "method_colors": dict(zip(f.ORDER, f.COLORS)),
340
+ "numerical_estimates_count": 12,
341
+ "role_separation": "Full FT uses #0D6EA8; paired calibration #59A8DF; LoRA #168FE5"}
342
+ return proofs
343
+
344
+
345
+ def scoped_arrow_png(source):
346
+ """Translate unambiguous method-colour cores and white antialias edges only."""
347
+ from scipy.ndimage import binary_dilation
348
+ colors = {"#D62728": RAW, "#7B3294":"#A6D4EF", "#1A9850":"#78B8E1", "#91CF60":"#91C7E8", "#E08214":CAL, "#1F5FBF":"#439ACF"}
349
+ panel = {"#D62728":(1,0), "#7B3294":(2,0), "#1A9850":(3,0), "#91CF60":(0,1), "#E08214":(1,1), "#1F5FBF":(2,1)}
350
+ with Image.open(source) as im:
351
+ array = np.asarray(im.convert("RGBA")).copy(); dpi = im.info.get("dpi", (150,150))
352
+ result = array.copy(); rgb = array[:,:,:3]; height,width = rgb.shape[:2]
353
+ biological = ["#C2A5CF","#A6DBA0","#1B7837","#762A83"]
354
+ changed = np.zeros((height,width), dtype=bool); masks = {}; records=[]
355
+ for old,new in colors.items():
356
+ c = np.asarray([int(old[i:i+2],16) for i in (1,3,5)],dtype=float)
357
+ target = np.asarray([int(new[i:i+2],16) for i in (1,3,5)],dtype=float)
358
+ column,row = panel[old]
359
+ allowed = np.zeros((height,width),dtype=bool)
360
+ # Wide subplot regions derive from the original 2x4 source layout.
361
+ x0,x1=int(column*width/4),int((column+1)*width/4)
362
+ y0,y1=(int(.12*height),int(.52*height)) if row==0 else (int(.50*height),int(.87*height))
363
+ allowed[y0:y1,x0:x1]=True
364
+ allowed[int(.48*height):,int(.77*width):]=True # PCA vector comparison + method legend
365
+ core=np.all(rgb==c.astype(np.uint8),axis=2)&allowed
366
+ if int(core.sum())<20: raise ValueError("Method colour core missing: "+old)
367
+ candidate=binary_dilation(core,iterations=1)&allowed&~core
368
+ ys,xs=np.where(candidate);pixels=rgb[ys,xs].astype(float);direction=255-c
369
+ alpha=((255-pixels)@direction)/(direction@direction)
370
+ expected=255-alpha[:,None]*direction
371
+ good=(alpha>=.08)&(alpha<=1)&(np.max(np.abs(expected-pixels),axis=1)<=.65)
372
+ for bio in biological:
373
+ bc=np.asarray([int(bio[i:i+2],16) for i in (1,3,5)],dtype=float);bd=255-bc
374
+ ba=((255-pixels)@bd)/(bd@bd)
375
+ ambiguous=(ba>=.04)&(ba<=1)&(np.max(np.abs((255-ba[:,None]*bd)-pixels),axis=1)<=1.0)
376
+ good &= ~ambiguous
377
+ mask=core.copy();mask[ys[good],xs[good]]=True
378
+ if np.any(mask&changed):raise ValueError("Method pixel masks overlap")
379
+ result[core,:3]=target.astype(np.uint8)
380
+ result[ys[good],xs[good],:3]=np.rint(255-alpha[good,None]*(255-target)).clip(0,255).astype(np.uint8)
381
+ changed |= mask;masks[old]=mask
382
+ records.append({"old":old,"new":new,"opaque_core_pixels":int(core.sum()),"unambiguous_antialias_pixels":int(good.sum()),
383
+ "panel":list(panel[old]),"panel_rectangle_pixels":[x0,y0,x1,y1],
384
+ "summary_rectangle_pixels":[int(.77*width),int(.48*height),width,height]})
385
+ if not np.array_equal(result[~changed],array[~changed]) or not np.array_equal(result[:,:,3],array[:,:,3]):
386
+ raise ValueError("Protected pixel/alpha preservation failed")
387
+ for bio in biological:
388
+ c=np.asarray([int(bio[i:i+2],16) for i in (1,3,5)],dtype=np.uint8);mask=np.all(rgb==c,axis=2)
389
+ if not np.array_equal(result[mask],array[mask]):raise ValueError("Biological core colours changed")
390
+ target=FIG/(source.stem+'.png');Image.fromarray(result,'RGBA').save(target,dpi=dpi)
391
+ pdf=target.with_suffix('.pdf')
392
+ with fitz.open() as doc:
393
+ page=doc.new_page(width=width*72/dpi[0],height=height*72/dpi[1]);page.insert_image(page.rect,filename=str(target));doc.save(pdf)
394
+ svg=target.with_suffix('.svg');svg.write_text(f'<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}"><image width="{width}" height="{height}" href="data:image/png;base64,{base64.b64encode(target.read_bytes()).decode()}"/></svg>\n')
395
+ maskpath=DATA/(source.stem+'_method_masks.npz');np.savez_compressed(maskpath,**{key.removeprefix('#'):value for key,value in masks.items()})
396
+ proof={"mode":"source-defined scientific raster chart colour translation", "source":binding(source),
397
+ "mapping":colors,"method_masks":records,"mask_file":binding(maskpath),"image_dimensions":[width,height],
398
+ "changed_pixels":int(changed.sum()),"protected_pixels":int((~changed).sum()),"protected_pixels_bit_exact":True,
399
+ "alpha_channel_bit_exact":True,"biological_core_colours_bit_exact":True,"pixel_positions_unchanged":True,
400
+ "geometry_or_statistic_recomputation":False,"ambiguous_antialias_pixels":"left unchanged",
401
+ "source_definition":str(D.parents[1]/'plans/utility_studies_final6k_20260925/refcal_scoring/arunachalam/tools/analyze_placement_refcal.py'),
402
+ "preservation_pass":True,"png":str(target),"pdf":str(pdf),"svg":str(svg)}
403
+ return proof
404
+
405
+
406
+ def run(spec_path=DEFAULT_SPEC, *, prepare_only=False):
407
+ DATA.mkdir(parents=True,exist_ok=True);FIG.mkdir(parents=True,exist_ok=True)
408
+ assets=collect(spec_path)
409
+ catalog={str(path):{**RULES[path.stem],"slides":pages} for path,pages in assets.items()}
410
+ dump(DATA/'SEMANTIC_MAP.json',{"decision":binding(DECISION),"input_spec":binding(spec_path),"assets":catalog})
411
+ if prepare_only:return {"assets_classified":len(catalog),"semantic_map":str(DATA/'SEMANTIC_MAP.json')}
412
+ originals={str(path):sha(path) for path in assets}
413
+ for path in assets:
414
+ if path.with_suffix('.pdf').exists():originals[str(path.with_suffix('.pdf'))]=sha(path.with_suffix('.pdf'))
415
+ dump(DATA/'ORIGINALS_BEFORE.json',originals)
416
+ needed={p.stem for p in assets if RULES[p.stem]['mode']=='native'}
417
+ native=native_replays(needed)
418
+ mapping={};records=[];sources=[binding(DECISION),binding(spec_path),binding(Path(__file__)),binding(D/'tools/review_palette_pdf.py')]
419
+ for path,pages in assets.items():
420
+ r=RULES[path.stem];mode=r['mode'];record={"original":str(path),"source_png_sha256":originals[str(path)],"slides":pages,"reason":r['reason'],"action":mode}
421
+ sources.append(binding(path,'original figure'))
422
+ if mode in {'preserve','approved-native'}:
423
+ mapping[str(path)]=str(path);record['output']=str(path);record['preservation_pass']=True
424
+ elif mode=='native':
425
+ proof=native[path.stem];out=Path(proof['png']);pdf_geometry(path.with_suffix('.pdf'),Path(proof['pdf']),caption_change=path.stem=='refcal_top_genes')
426
+ proof.update({'original':binding(path),'original_pdf':binding(path.with_suffix('.pdf')),'text_geometry_preserved_except_declared_caption':True,'preservation_pass':True})
427
+ receipt=DATA/(path.stem+'.proof.json');dump(receipt,proof);mapping[str(path)]=str(out);record.update(output=str(out),proof=str(receipt),preservation_pass=True)
428
+ elif mode=='scoped-raster':
429
+ proof=scoped_arrow_png(path);receipt=DATA/(path.stem+'.proof.json');dump(receipt,proof);mapping[str(path)]=proof['png'];record.update(output=proof['png'],proof=str(receipt),preservation_pass=True)
430
+ elif mode=='native-backbone':
431
+ proof=native_backbone(path);receipt=DATA/(path.stem+'.proof.json');dump(receipt,proof);mapping[str(path)]=proof['png'];record.update(output=proof['png'],proof=str(receipt),preservation_pass=True)
432
+ elif mode=='vector-gray-variants':
433
+ proof=vector_k_variants(path);receipt=DATA/(path.stem+'.proof.json');dump(receipt,proof);mapping[str(path)]=proof['png'];record.update(output=proof['png'],proof=str(receipt),preservation_pass=True)
434
+ else:
435
+ original_pdf=path.with_suffix('.pdf')
436
+ if not original_pdf.is_file():raise FileNotFoundError('No vector companion for '+str(path))
437
+ sources.append(binding(original_pdf,'source vector figure'))
438
+ target_pdf=FIG/(path.stem+'.pdf');target_png=FIG/(path.stem+'.png')
439
+ with tempfile.TemporaryDirectory(prefix='.build-',dir=FIG) as tmp:
440
+ pdf=Path(tmp)/target_pdf.name;png=Path(tmp)/target_png.name
441
+ proof=V.recolor_pdf(original_pdf,pdf,r['mapping'],rgb_tolerance=5.1e-7 if path.stem=='fig1b_overview_nature' else 1e-8)
442
+ render=V.render_pdf_to_png(pdf,png,dpi=300 if path.stem=='fig1b_overview_nature' else 200)
443
+ pdf.replace(target_pdf);png.replace(target_png)
444
+ proof['destination']=str(target_pdf);render.update(pdf=str(target_pdf),png=str(target_png));proof.update(render=render,semantic_reason=r['reason'],source_png=binding(path))
445
+ receipt=DATA/(path.stem+'.proof.json');dump(receipt,proof);mapping[str(path)]=str(target_png);record.update(output=str(target_png),proof=str(receipt),preservation_pass=True)
446
+ record['output_sha256']=sha(mapping[str(path)]);records.append(record)
447
+ changed=[path for path,expected in originals.items() if sha(path)!=expected]
448
+ if changed:raise ValueError('Original assets changed: '+repr(changed))
449
+ outputs=[str(path) for root in (FIG,DATA/'native') for path in root.rglob('*') if path.is_file()]
450
+ outputs += [str(p) for p in DATA.glob('*.proof.json')]+[str(p) for p in DATA.glob('*_method_masks.npz')]
451
+ result={"schema":"pbisc.final-deck-palette.v1","decision":binding(DECISION),"mapping":mapping,"records":records,
452
+ "sources":sources,"assets":sorted(set(outputs)),"coverage":{"total":len(assets),"mapped":len(mapping),"preservation_pass":all(r['preservation_pass'] for r in records)},
453
+ "originals_unchanged":True,"no_new_inference":True,"no_new_statistics":True,
454
+ "native_text_exception":"'Gold bars:' becomes 'Bars:' in refcal_top_genes; 'orange = changed from SDD' becomes 'Highlighted = changed from SDD' in sec02_backbone_compare. All table values and other text stay fixed.",
455
+ "raster_exception":"One PNG-only COVID arrow plot uses saved source colours and protected per-method pixel masks; no coordinate fit or resampling.",
456
+ "unresolved":[]}
457
+ dump(DATA/'ASSET_MAP.json',result);dump(DATA/'result.json',result)
458
+ return result
459
+
460
+
461
+ if __name__=='__main__':
462
+ parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--spec',type=Path,default=DEFAULT_SPEC);parser.add_argument('--prepare-only',action='store_true');args=parser.parse_args()
463
+ result=run(args.spec,prepare_only=args.prepare_only)
464
+ print(json.dumps(result.get('coverage',result),indent=2))