Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/AGENTS.md +99 -0
- paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/recoveries/x1_priority_completion_20261015/GPU_UNITS.json +11 -0
- paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/recoveries/x1_priority_completion_20261015/OWNERS.json +11 -0
- paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/build_x1_priority_master_20261015.py +470 -0
paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/AGENTS.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Model 8 PBISC-Diffusion paper maintenance
|
| 2 |
+
|
| 3 |
+
This active Model 8 source and its experiments are part of the
|
| 4 |
+
`pbisc-diffusion` paper. At task start, read
|
| 5 |
+
`../../paper-release-20260928/maintenance/POLICY.md` along with this
|
| 6 |
+
directory's README and applicable parent instructions.
|
| 7 |
+
|
| 8 |
+
At the end of each related task, follow that policy's versioned update
|
| 9 |
+
workflow for the exact source, experiment, checkpoint, or evidence assets that
|
| 10 |
+
changed. From the release root, use
|
| 11 |
+
`maintenance/update.py prepare --request FILE --id ID`, inspect the prepared
|
| 12 |
+
update, then run `maintenance/update.py publish ID --execute` and
|
| 13 |
+
`maintenance/update.py status` under the policy. Record a no-op or pending
|
| 14 |
+
status when no
|
| 15 |
+
asset changed or publication failed; never describe that as an upload. Do not
|
| 16 |
+
regenerate or alter the frozen 2026-09-28 release, its root manifests, or the
|
| 17 |
+
HF `paper-20260928` revision. Inference assets are location plus receipt by
|
| 18 |
+
default unless the task explicitly needs their payload.
|
| 19 |
+
|
| 20 |
+
The private dataset must stay private. Include datalake, VAE, or Model 7 assets
|
| 21 |
+
only with exact evidence that they are dependencies of this diffusion paper.
|
| 22 |
+
The parent host GPU safety rules still apply.
|
| 23 |
+
|
| 24 |
+
## Reuse existing experiments before starting compute
|
| 25 |
+
|
| 26 |
+
User instruction, 2026-10-13: avoid repeating completed Model 8 experiments.
|
| 27 |
+
Start with `EXPERIMENT_INDEX.md` and query `EXPERIMENT_REUSE_INDEX.jsonl` using
|
| 28 |
+
`scripts/audit_experiment_reuse.py`. A missing output in a new plan directory
|
| 29 |
+
does not establish that an experiment has never been done.
|
| 30 |
+
|
| 31 |
+
- Before training, generation, or deconvolution, compare existing source
|
| 32 |
+
receipts: base checkpoint, exact support/test sample and donor IDs, data and
|
| 33 |
+
condition content, measured genes/masks, validation access, optimization and
|
| 34 |
+
selection schedule, seed, and implementation/configuration provenance.
|
| 35 |
+
- Registry matches are candidates, not automatic equivalence. Verify payloads
|
| 36 |
+
and write truthful adoption evidence. Preserve original execution provenance;
|
| 37 |
+
do not relabel an old artifact as newly executed strict work.
|
| 38 |
+
- Changing a sampling seed or receipt format does not justify retraining an
|
| 39 |
+
existing model. Reuse verified checkpoints and run only the genuinely changed
|
| 40 |
+
operation. Missing native receipts call for adoption, not automatic reruns.
|
| 41 |
+
- Record the candidate sources and the exact scientific reason for any new
|
| 42 |
+
operation before launching it. Unknown provenance requires investigation,
|
| 43 |
+
not a conclusion that new compute is necessary. Consult newer live receipts
|
| 44 |
+
when the inventory predates an ongoing campaign.
|
| 45 |
+
- Distinguish existing results, CPU-only statistics/plotting, a new protocol
|
| 46 |
+
update, and missing data in plans and decks. Never label all four as an empty
|
| 47 |
+
TODO. Archive/backup copies and tensor-identical models are not independent
|
| 48 |
+
experimental evidence.
|
| 49 |
+
|
| 50 |
+
The 2026-10-13 audit and confirmed duplicate-training proof are in
|
| 51 |
+
`plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/`.
|
| 52 |
+
Sepsis deconvolution uses verified historical draw-specific outputs through
|
| 53 |
+
`tools/adopt_deconv_legacy.py` in that plan; its methods must not be rerun as a
|
| 54 |
+
fallback when adoption validation fails. Current expanded evidence master (see `presentations/2026-09-30--paper-summary--r00/CURRENT_MASTER.json` for the live page count; all 156 Figure1-focused parent pages and original76 IDs are preserved):
|
| 55 |
+
`presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_expanded_master_20261015_figure1_focused.pptx`.
|
| 56 |
+
Use the build and page map named by `CURRENT_MASTER.json`; the frozen156-page parent remains in `data/x1_priority_20261015/base/`. New x1 core and full CPU evaluations are explicitly distinguished.
|
| 57 |
+
Earlier 155/154/142/140/131-slide decks remain preserved source versions, not the current master.
|
| 58 |
+
The 34-slide review is a historical subset, not the master. The approved method palette is
|
| 59 |
+
`presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_color_palette_20261013.md`:
|
| 60 |
+
PBISC LoRA #168FE5, calibrated #59A8DF, raw #C3E2F4; scSemiProfiler #83C6A8;
|
| 61 |
+
BayesPrism #D9B23F and CIBERSORTx #F0D77D. Preserve biological/cohort colours and quantitative heatmap scales.
|
| 62 |
+
Older gold/blue source figures are preserved historical assets; use the final semantic palette derivatives in current decks.
|
| 63 |
+
|
| 64 |
+
## Current manuscript figure scopes
|
| 65 |
+
|
| 66 |
+
The user's 2026-10-13 definitions supersede old figure numbers inside the deck and earlier plans:
|
| 67 |
+
Figure 1 overview/corpus statistics; Figure 2 architecture/gene-context ablations on SLE pseudobulk;
|
| 68 |
+
Figure 3 healthy measured bulk–sc paired mismatch, full FT, LoRA ranks and support budgets;
|
| 69 |
+
Figure 4 disease measured-paired quantitative integrity comparisons;
|
| 70 |
+
Figure 5 paired rare-population qualitative recovery; Figure 6 paired adaptation followed by
|
| 71 |
+
bulk-only published-finding reproduction (TODO).
|
| 72 |
+
The authoritative scope and proposed 131-page mapping are in
|
| 73 |
+
`presentations/2026-09-30--paper-summary--r00/data/figure_assignment_20261013/`.
|
| 74 |
+
Read `AUTHOR_SCOPE.md` and `ASSIGNMENT.md` before figure work. Preserve the distinction
|
| 75 |
+
between total-five pairs and five training plus extra validation; rank16 is not universally
|
| 76 |
+
best in existing metrics, and disease comparisons have cohort/endpoint exceptions.
|
| 77 |
+
Existing rare-state quantitative slides do not substitute for paired qualitative panels.
|
| 78 |
+
The scope is now applied in the actual reordered PPTX/PDF, not only in planning documents.
|
| 79 |
+
Use `tools/build_x1_priority_master_20261015.py --if-changed` in the presentation directory for current x1 result refreshes. It consumes the immutable156-page base and verified evaluation receipts. `build_figure1_focused_master_20261015.py` is the preserved historical Figure1 branch; rerunning it would omit the new x1 result additions.
|
| 80 |
+
Figure 2 now includes corpus-validation curves and cost metadata alongside SLE pseudobulk
|
| 81 |
+
benchmarks; these are not paired real-bulk performance panels. Figure 1's recorded PCA
|
| 82 |
+
uses an existing ctx2048 E12 illustration, with endpoint colours revealed by denoising progress,
|
| 83 |
+
not per-step confidence. Display real R2 as a real-cell repeat from the same donors, not new donors.
|
| 84 |
+
Healthy pair-budget panels cover all six types with both Pearson correlation and MAE, including adverse results.
|
| 85 |
+
They use historical n+7 validation access, not total-n. Do not omit NK/DC/Other to make a five-pair claim appear stronger.
|
| 86 |
+
|
| 87 |
+
The latest strengthening proposal is `data/figure_assignment_20261013/STRENGTHENING_PROPOSAL.md` under the deck.
|
| 88 |
+
Corpus 41,395,184 vs train 33,141,380 is a split difference, not K exclusion; all training cells are covered after top-up.
|
| 89 |
+
Healthy 88.51% is a source-cell share. The remainder includes ACPA+ at-risk and is labelled Disease / at-risk.
|
| 90 |
+
Historical LoRA all means 78–79 training +7 validation, keeping21–22 test/fold. Nested random training subsets and
|
| 91 |
+
outer/inner splits replay exactly. The legacy total-five102-test/draw design differs from strict healthy outer-fold tests.
|
| 92 |
+
Figure5 original-paper targets require author identity: Ye Mono_c06 pediatric pulmonary and Imperial wave2
|
| 93 |
+
steroid-associated monocytes. Ye observed-marker co-detection is a diagnostic, not reproduced cluster identity;
|
| 94 |
+
fine labels were not found in133 audited canonical obs schemas. Existing generic rare-state rules do not substitute
|
| 95 |
+
for those source-defined populations. Giroux/Ji program results are not automatically rare-population evidence.
|
| 96 |
+
|
| 97 |
+
Figure 1 main corpus panel now uses exact train metadata: 33,141,380 cells, 5,232 samples, 2,572 corrected donor identities; Healthy 88.4241%. The 88.51% healthy share applies to the full source pool only. Training cell-type proportions were recomputed across 432 metadata shards, not scaled from full-source proportions. Use `data/figure1_revision_20261014/train_corpus/result.json`. Figure 1a uses organic vector glyphs; cells/model nodes are schematic, and K is distinct from generated-cell count.
|
| 98 |
+
|
| 99 |
+
Figure 1a now explicitly shows noisy gene-space state -> iterative PBISC denoising -> sparse expression with exact zeros; those profiles are schematic, not recorded data. Figure 1b main proportions use grouped small categories with source membership in `data/figure1_focus_20261015/corpus/display_aggregations.csv`; Unlabelled and ACPA+ at-risk remain separate. Complete training counts are preserved on support page9, full-source composition page10. Do not revert the denoiser to a generic molecular-network icon or drop the detail panel.
|
paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/recoveries/x1_priority_completion_20261015/GPU_UNITS.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
"ji2025_chili-disease-draw2",
|
| 3 |
+
"ji2025_chili-disease-draw3",
|
| 4 |
+
"ji2025_chili-disease-draw4",
|
| 5 |
+
"immicro-healthy-fold0-n10",
|
| 6 |
+
"immicro-healthy-fold0-n20",
|
| 7 |
+
"immicro-healthy-fold0-n40",
|
| 8 |
+
"immicro-healthy-fold1-n10",
|
| 9 |
+
"immicro-healthy-fold1-n20",
|
| 10 |
+
"immicro-healthy-fold1-n40"
|
| 11 |
+
]
|
paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/recoveries/x1_priority_completion_20261015/OWNERS.json
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"ji2025_chili-disease-draw2": "server_1",
|
| 3 |
+
"ji2025_chili-disease-draw3": "server_2",
|
| 4 |
+
"ji2025_chili-disease-draw4": "server_1",
|
| 5 |
+
"immicro-healthy-fold0-n10": "server_2",
|
| 6 |
+
"immicro-healthy-fold0-n20": "server_1",
|
| 7 |
+
"immicro-healthy-fold0-n40": "server_2",
|
| 8 |
+
"immicro-healthy-fold1-n10": "server_1",
|
| 9 |
+
"immicro-healthy-fold1-n20": "server_2",
|
| 10 |
+
"immicro-healthy-fold1-n40": "server_1"
|
| 11 |
+
}
|
paper-releases/pbisc-diffusion/updates/20261015T121654Z-x1-nine-core40-deck/diffusion/dataset/server_1/model8/presentations/2026-09-30--paper-summary--r00/tools/build_x1_priority_master_20261015.py
ADDED
|
@@ -0,0 +1,470 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""CPU-only, repeatable, source-verified x1 results expansion of the 156-page master.
|
| 3 |
+
|
| 4 |
+
Completed core results and completed full CPU statistics have separate admission
|
| 5 |
+
rules. No generated-array loading, fitting, training or inference occurs here.
|
| 6 |
+
The parent deck/spec and Figure 1 assets are immutable inputs. Every successful
|
| 7 |
+
refresh is retained under data/x1_priority_20261015/builds/<UTC-id>/ before the
|
| 8 |
+
versioned x1_priority PPTX/PDF aliases advance.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
import argparse, copy, csv, fcntl, hashlib, json, os, re, shutil, subprocess, sys
|
| 12 |
+
from collections import Counter, defaultdict
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
if os.environ.get('CUDA_VISIBLE_DEVICES') != '':
|
| 16 |
+
raise SystemExit('CPU-only: set CUDA_VISIBLE_DEVICES to the empty string')
|
| 17 |
+
D=Path(__file__).resolve().parents[1]; M=D.parents[1]
|
| 18 |
+
S=M/'plans/paper_figures_strictpairs_20261012'
|
| 19 |
+
A=D/'data/x1_priority_20261015'
|
| 20 |
+
ORIGINAL_PARENT=D/'data/figure1_focus_20261015/spec.json'
|
| 21 |
+
PARENT=A/'base/spec.json'
|
| 22 |
+
STATUS=S/'recoveries/x1_priority_completion_20261015/evaluation/STATUS.json'
|
| 23 |
+
OUT='PBISC-Diffusion_expanded_master_20261015_x1_priority'
|
| 24 |
+
sys.path[:0]=[str(D),str(D/'tools')]
|
| 25 |
+
import numpy as np
|
| 26 |
+
import pandas as pd
|
| 27 |
+
import style as ST
|
| 28 |
+
import matplotlib.pyplot as plt
|
| 29 |
+
from matplotlib.lines import Line2D
|
| 30 |
+
from matplotlib.ticker import MaxNLocator
|
| 31 |
+
from pptx import Presentation
|
| 32 |
+
from pptx.util import Inches
|
| 33 |
+
import fitz
|
| 34 |
+
import generate_deck as G
|
| 35 |
+
from reorder_master_figures_20261013 import draw_card, draw_note
|
| 36 |
+
import verify_expanded_master_20261013 as V
|
| 37 |
+
|
| 38 |
+
COHORTS=['ye2026_sepsis','imperial_eskd','giroux2022','ji2025_chili']
|
| 39 |
+
NAMES={'ye2026_sepsis':'Sepsis','imperial_eskd':'Imperial ESKD','giroux2022':'Giroux','ji2025_chili':'CHILI','immicro':'Healthy ImMicro'}
|
| 40 |
+
ARMS=['raw','refcal','pairedcal','scsemi','lora']
|
| 41 |
+
COL={'raw':'#C3E2F4','refcal':'#59A8DF','pairedcal':'#59A8DF','scsemi':'#83C6A8','lora':'#168FE5'}
|
| 42 |
+
LAB={'raw':'Raw','refcal':'Reference cal.','pairedcal':'Paired cal.','scsemi':'scSemiProfiler','lora':'PBISC x1 LoRA'}
|
| 43 |
+
MARK={'raw':'D','refcal':'s','pairedcal':'s','scsemi':'^','lora':'o'}
|
| 44 |
+
TYPES=['T cell','B cell','Monocyte','NK cell','DC','Other']
|
| 45 |
+
FULL={'full_completed','canonical_full_reused'}
|
| 46 |
+
|
| 47 |
+
def sha(p):
|
| 48 |
+
with Path(p).open('rb') as f:return hashlib.file_digest(f,'sha256').hexdigest()
|
| 49 |
+
|
| 50 |
+
def js(p):return json.loads(Path(p).read_text())
|
| 51 |
+
def savejs(p,v):Path(p).write_text(json.dumps(v,indent=2,allow_nan=False)+'\n')
|
| 52 |
+
def finite(x):
|
| 53 |
+
try:return np.isfinite(float(x))
|
| 54 |
+
except (TypeError,ValueError):return False
|
| 55 |
+
|
| 56 |
+
def initialize_base():
|
| 57 |
+
"""Freeze the complete parent once; user-facing master aliases may advance later."""
|
| 58 |
+
base=A/'base';proof=base/'BASE_VERIFIED.json'
|
| 59 |
+
if proof.exists():
|
| 60 |
+
v=js(proof)
|
| 61 |
+
for p,h in v['protected'].items():
|
| 62 |
+
if sha(p)!=h:raise ValueError(f'Immutable parent changed: {p}')
|
| 63 |
+
return
|
| 64 |
+
base.mkdir(exist_ok=True);(base/'figures').mkdir(exist_ok=True)
|
| 65 |
+
source=js(ORIGINAL_PARENT);original_manifest=js(ORIGINAL_PARENT.parent/'manifest.json')
|
| 66 |
+
if len(source['slides'])!=156:raise ValueError('Expected original156 parent spec')
|
| 67 |
+
original_files=[ORIGINAL_PARENT,D/'PBISC-Diffusion_expanded_master_20261015_figure1_focused.pptx',D/'PBISC-Diffusion_expanded_master_20261015_figure1_focused.pdf']
|
| 68 |
+
if len(Presentation(original_files[1]).slides)!=156:raise ValueError('Create immutablebase before advancing named master aliases')
|
| 69 |
+
if len(fitz.open(original_files[2]))!=156:raise ValueError('Named original PDF is no longer156pages')
|
| 70 |
+
protected={};originals={};bindings={}
|
| 71 |
+
for p in original_files:
|
| 72 |
+
target=base/('source_spec.json' if p==ORIGINAL_PARENT else p.name)
|
| 73 |
+
shutil.copy2(p,target);digest=sha(p)
|
| 74 |
+
if sha(target)!=digest:raise ValueError('Parentcopy hash mismatch')
|
| 75 |
+
protected[str(target)]=digest;originals[str(p)]=digest
|
| 76 |
+
effective=copy.deepcopy(source)
|
| 77 |
+
for slide in effective['slides']:
|
| 78 |
+
slide['parent_original_figure_paths']=slide.get('figures',[])
|
| 79 |
+
repl=[]
|
| 80 |
+
for f in slide.get('figures',[]):
|
| 81 |
+
p=D/f;h=sha(p)
|
| 82 |
+
if original_manifest['sources'][str(p)]['sha256']!=h:raise ValueError(f'Original figure changed: {p}')
|
| 83 |
+
dest=base/'figures'/f'{h[:20]}_{p.name}'
|
| 84 |
+
if not dest.exists():shutil.copy2(p,dest)
|
| 85 |
+
if sha(dest)!=h:raise ValueError('Parentfigure copy hash mismatch')
|
| 86 |
+
repl.append(str(dest.relative_to(D)));bindings[str(dest)]={'sha256':h};protected[str(dest)]=h
|
| 87 |
+
if 'figures'in slide:slide['figures']=repl
|
| 88 |
+
savejs(PARENT,effective);protected[str(PARENT)]=sha(PARENT)
|
| 89 |
+
savejs(base/'manifest.json',{'sources':bindings,'parent_original_sources':originals,'total_slides':156})
|
| 90 |
+
protected[str(base/'manifest.json')]=sha(base/'manifest.json')
|
| 91 |
+
savejs(proof,{'schema':'pbisc.x1.parent156.immutable.v1','status':'PASS','protected':protected,'original_named_sources':originals,'source_page_count':156,'original76_preserved':True})
|
| 92 |
+
|
| 93 |
+
def expected_units():
|
| 94 |
+
out=[]
|
| 95 |
+
for ds in COHORTS:
|
| 96 |
+
for i in range(5):out.append((ds,f'{ds}/disease/draw{i}',f'{ds}-disease-draw{i}'))
|
| 97 |
+
for f in range(5):
|
| 98 |
+
for n in [5,10,20,40]:out.append(('immicro',f'immicro/healthy/fold{f}/n{n}',f'immicro-healthy-fold{f}-n{n}'))
|
| 99 |
+
return out
|
| 100 |
+
|
| 101 |
+
class Evidence:
|
| 102 |
+
def __init__(self, build):
|
| 103 |
+
self.build=build;self.sources={};self.records=[];self.pending=[];self.units=[];self.failures=[];self.optional_gaps=[]
|
| 104 |
+
def snapshot(self,path,role):
|
| 105 |
+
p=Path(path).resolve()
|
| 106 |
+
if str(p) not in self.sources:
|
| 107 |
+
digest=sha(p);target=self.build/'sources'/digest[:16]/p.name
|
| 108 |
+
target.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(p,target)
|
| 109 |
+
if sha(p)!=digest or sha(target)!=digest:raise ValueError(f'Source changed while copying {p}')
|
| 110 |
+
self.sources[str(p)]={'path':str(p),'sha256':digest,'bytes':p.stat().st_size,'role':role,'snapshot':str(target)}
|
| 111 |
+
return Path(self.sources[str(p)]['snapshot'])
|
| 112 |
+
def doc(self,path,role):return js(self.snapshot(path,role))
|
| 113 |
+
def table(self,path,role):return pd.read_csv(self.snapshot(path,role))
|
| 114 |
+
def optional_intervals(self,path,role,required,unit,arm):
|
| 115 |
+
# A one-arm evaluator has no cross-method comparison to estimate.
|
| 116 |
+
# Empty/header-only optional interval output must not discard valid
|
| 117 |
+
# core, realism, contrast, or donor-DEG results from the same arm.
|
| 118 |
+
snap=self.snapshot(path,role)
|
| 119 |
+
try:table=pd.read_csv(snap)
|
| 120 |
+
except pd.errors.EmptyDataError:table=pd.DataFrame(columns=sorted(required))
|
| 121 |
+
if table.empty:
|
| 122 |
+
self.optional_gaps.append({'unit':unit,'arm':arm,'path':str(path),'reason':'no interval rows; not a missing core/full evaluation'})
|
| 123 |
+
return pd.DataFrame(columns=sorted(required))
|
| 124 |
+
if not required <= set(table.columns):
|
| 125 |
+
self.optional_gaps.append({'unit':unit,'arm':arm,'path':str(path),'reason':'interval columns not recognized; other completed metrics retained'})
|
| 126 |
+
return pd.DataFrame(columns=sorted(required))
|
| 127 |
+
return table
|
| 128 |
+
def receipt(self,path):
|
| 129 |
+
j=self.doc(path,'completed evaluation receipt')
|
| 130 |
+
if j.get('state',j.get('status')) not in {'completed','verified','PASS','pass','full_completed','canonical_full_reused'}:
|
| 131 |
+
raise ValueError('receipt not completed')
|
| 132 |
+
for x in j.get('outputs',[]):
|
| 133 |
+
if not isinstance(x,dict) or 'path' not in x or 'sha256' not in x:continue
|
| 134 |
+
p=Path(x['path'])
|
| 135 |
+
if not p.is_file() or sha(p)!=x['sha256']:raise ValueError(f'Receipt hash mismatch: {p}')
|
| 136 |
+
if 'bytes' in x and p.stat().st_size!=x['bytes']:raise ValueError(f'Receipt size mismatch: {p}')
|
| 137 |
+
return j
|
| 138 |
+
def load(self, manifest):
|
| 139 |
+
provided={}
|
| 140 |
+
if manifest.exists():
|
| 141 |
+
st=self.doc(manifest,'evaluation availability snapshot')
|
| 142 |
+
for u in st.get('units',[]):provided[u.get('unit',u.get('id',''))]=u
|
| 143 |
+
for ds,rel,unit in expected_units():
|
| 144 |
+
sup=S/'protocol/splits'/rel/'support.json'
|
| 145 |
+
sp=self.doc(sup,'frozen support/test split')
|
| 146 |
+
h=hashlib.sha256(json.dumps({k:v for k,v in sp.items() if k!='sha256'},sort_keys=True,separators=(',',':'),allow_nan=False).encode()).hexdigest()
|
| 147 |
+
if h!=sp['sha256']:raise ValueError(f'Invalid support hash {unit}')
|
| 148 |
+
n=5 if ds!='immicro' else int(rel.rsplit('n',1)[1])
|
| 149 |
+
if len(set(sp['train_sample_ids']))!=n or len(set(sp['train_donor_ids']))!=n:raise ValueError(f'Wrong strict support {unit}')
|
| 150 |
+
canonical=S/'receipts'/f'{unit}-score.json';base=S/'scores'/rel
|
| 151 |
+
configs={};canonical_ok=False
|
| 152 |
+
if canonical.exists():
|
| 153 |
+
try:
|
| 154 |
+
self.receipt(canonical);canonical_ok=True
|
| 155 |
+
stat=self.doc(base/'statistics/status.json','full statistics status')
|
| 156 |
+
if stat['support_sha256']!=h:raise ValueError('Statistics support mismatch')
|
| 157 |
+
for arm in ARMS:
|
| 158 |
+
configs[arm]={'state':'canonical_full_reused','score_summary':str(base/'score/summary.json'),
|
| 159 |
+
'receipt':str(canonical),'statistics_status':str(base/'statistics/status.json'),
|
| 160 |
+
'extras_manifest':str(base/'extras'/ds/'strict/manifest.json'),
|
| 161 |
+
'contrast_manifest':str(base/'contrast'/ds/'strict/manifest.json'),
|
| 162 |
+
'bootstrap_csv':str(base/'statistics/donor_bootstrap_2000.csv'),
|
| 163 |
+
'individual_bootstrap_csv':str(base/'statistics/individual_donor_bootstrap_2000.csv'),
|
| 164 |
+
'donor_deg_summary':stat.get('disease_deg',{}).get('summary_csv')}
|
| 165 |
+
except (ValueError,FileNotFoundError,KeyError) as e:
|
| 166 |
+
self.failures.append({'unit':unit,'reason':str(e),'excluded_source':str(canonical)})
|
| 167 |
+
configs={}
|
| 168 |
+
pu=provided.get(unit,{})
|
| 169 |
+
if pu.get('support_sha256') and pu['support_sha256']!=h:raise ValueError(f'Manifest support mismatch {unit}')
|
| 170 |
+
for arm,c in pu.get('arms',{}).items():
|
| 171 |
+
if arm in ARMS and (arm not in configs or c.get('state') in FULL):configs[arm]=c
|
| 172 |
+
accepted={}
|
| 173 |
+
for arm,c in configs.items():
|
| 174 |
+
if c.get('state') not in FULL|{'core_only'}:continue
|
| 175 |
+
try:
|
| 176 |
+
if c.get('receipt'):
|
| 177 |
+
bound=self.receipt(c['receipt'])
|
| 178 |
+
if bound.get('support_sha256',h)!=h:raise ValueError('Receipt support mismatch')
|
| 179 |
+
elif not canonical_ok:raise ValueError('Missing validated receipt')
|
| 180 |
+
summary=self.doc(c['score_summary'],'verified core metrics')
|
| 181 |
+
if ds!=summary['dataset'] or arm not in summary['headline']:raise ValueError('Dataset/arm mismatch')
|
| 182 |
+
if set(summary['donors'])!=set(sp['test_sample_ids']):raise ValueError('Test sample mismatch')
|
| 183 |
+
if not summary['per_arm'][arm]['receipt_verified']:raise ValueError('Generation receipt not verified')
|
| 184 |
+
record={'unit':unit,'cohort':ds,'relative':rel,'arm':arm,'state':c['state'],'support_sha256':h,'n':n,
|
| 185 |
+
'fold':int(re.search(r'fold(\d+)',rel).group(1)) if ds=='immicro' else None,
|
| 186 |
+
'draw':int(re.search(r'draw(\d+)',rel).group(1)) if ds!='immicro' else None,
|
| 187 |
+
'headline':summary['headline'][arm], 'composition':summary['per_arm'][arm]['composition'],
|
| 188 |
+
'test_n':len(sp['test_sample_ids']),'source_summary':c['score_summary']}
|
| 189 |
+
if c['state'] in FULL:
|
| 190 |
+
status=self.doc(c['statistics_status'],'completed full-statistics status')
|
| 191 |
+
if status['support_sha256']!=h:raise ValueError('Full statistics support mismatch')
|
| 192 |
+
for key in ['extras_manifest','contrast_manifest']:
|
| 193 |
+
if c.get(key) and Path(c[key]).exists():
|
| 194 |
+
mm=self.doc(c[key],key)
|
| 195 |
+
if not mm.get('skipped') and set(mm.get('donors',[]))!=set(sp['test_sample_ids']):raise ValueError(f'{key}: samples differ')
|
| 196 |
+
if key=='contrast_manifest' and not mm.get('skipped'):
|
| 197 |
+
hh=self.table(Path(c[key]).parent/'headline.csv','disease contrast and ranking metrics')
|
| 198 |
+
rr=hh.loc[hh.arm==arm]
|
| 199 |
+
if len(rr)!=1 or not bool(rr.iloc[0].repro_pass):raise ValueError('Contrast row not reproducible')
|
| 200 |
+
record['contrast']=rr.iloc[0].to_dict()
|
| 201 |
+
if key=='extras_manifest':
|
| 202 |
+
xx=self.table(Path(c[key]).parent/'metrics.csv','full realism metrics')
|
| 203 |
+
rr=xx.loc[(xx['set']==arm)&(xx.real_side=='R1')&(xx['mode']=='raw')]
|
| 204 |
+
if len(rr)==1:record['extras']=rr.iloc[0].to_dict()
|
| 205 |
+
en=self.table(Path(c[key]).parent/'en.csv','sample energy score')
|
| 206 |
+
ee=en.loc[(en['set']==arm)&(en.cellset=='pc')&(en.distance=='sq')]
|
| 207 |
+
if len(ee)==1:record['en']=float(ee.iloc[0].en)
|
| 208 |
+
if c.get('bootstrap_csv') and Path(c['bootstrap_csv']).exists():
|
| 209 |
+
bb=self.optional_intervals(c['bootstrap_csv'],'paired donor bootstrap intervals',{'arm','baseline','metric','status','estimate','ci_low','ci_high'},unit,arm)
|
| 210 |
+
record['bootstrap']=bb.loc[(bb.arm==arm)|(bb.baseline==arm)].to_dict('records')
|
| 211 |
+
record['paired_bootstrap_status']='available' if len(record['bootstrap']) else 'not_available_no_cross_method_rows'
|
| 212 |
+
if c.get('individual_bootstrap_csv') and Path(c['individual_bootstrap_csv']).exists():
|
| 213 |
+
ib=self.optional_intervals(c['individual_bootstrap_csv'],'single-arm unique-donor bootstrap intervals',{'arm','metric','status'},unit,arm)
|
| 214 |
+
record['individual_bootstrap']=ib.loc[ib.arm==arm].to_dict('records')
|
| 215 |
+
record['individual_bootstrap_status']='available' if len(record['individual_bootstrap']) else 'not_estimable_or_empty'
|
| 216 |
+
if c.get('donor_deg_summary') and Path(c['donor_deg_summary']).exists():
|
| 217 |
+
dd=self.table(c['donor_deg_summary'],'donor-aware DEG summary')
|
| 218 |
+
record['donor_deg']=dd.loc[dd.arm==arm].to_dict('records')
|
| 219 |
+
self.records.append(record);accepted[arm]=c['state']
|
| 220 |
+
except (ValueError,KeyError,FileNotFoundError) as e:
|
| 221 |
+
self.failures.append({'unit':unit,'arm':arm,'reason':str(e)})
|
| 222 |
+
self.units.append({'unit':unit,'cohort':ds,'relative':rel,'n':n,'arms':accepted})
|
| 223 |
+
return self
|
| 224 |
+
|
| 225 |
+
class Plots:
|
| 226 |
+
def __init__(self,e):self.e=e;self.b=e.build;self.slides=[]
|
| 227 |
+
def add(self,fig,key,title,group,foot,notes):
|
| 228 |
+
folder=self.b/'figures';folder.mkdir(exist_ok=True)
|
| 229 |
+
for ext in ['png','pdf','svg']:fig.savefig(folder/f'{key}.{ext}',dpi=250,bbox_inches='tight',pad_inches=.06)
|
| 230 |
+
plt.close(fig)
|
| 231 |
+
self.slides.append(dict(kind='content',layout='full',deck_group=group,section=group,section_label=group,
|
| 232 |
+
title=title,figures=[str((folder/f'{key}.png').relative_to(D))],keywords=[],footnote=foot,
|
| 233 |
+
footnote_full=notes,sources=str(self.b/'SOURCE_MANIFEST.json'),addition_key='x1_priority:'+key))
|
| 234 |
+
def status(self):
|
| 235 |
+
fig,axes=plt.subplots(1,2,figsize=ST.FULL,gridspec_kw={'width_ratios':[1,1]});fig.subplots_adjust(wspace=.45,left=.07,right=.97,top=.9,bottom=.25)
|
| 236 |
+
categories=['No admitted result','Core metrics','Full CPU statistics']; colors=['#F0F0F0','#A8CAE3','#168FE5']
|
| 237 |
+
for ax,dslist in zip(axes,[['immicro'],COHORTS]):
|
| 238 |
+
labels=[f'{n} pairs' for n in [5,10,20,40]] if dslist==['immicro'] else [NAMES[x] for x in dslist]
|
| 239 |
+
mat=[]
|
| 240 |
+
for n,ds in enumerate(dslist*4 if dslist==['immicro'] else dslist):
|
| 241 |
+
units=[x for x in self.e.units if x['cohort']==ds and (ds!='immicro' or x['n']==[5,10,20,40][n])]
|
| 242 |
+
units=sorted(units,key=lambda x:x['relative']);mat.append([2 if u['arms'].get('lora') in FULL else 1 if u['arms'].get('lora')=='core_only' else 0 for u in units])
|
| 243 |
+
from matplotlib.colors import ListedColormap
|
| 244 |
+
ax.imshow(mat,cmap=ListedColormap(colors),vmin=0,vmax=2,aspect='auto');ax.set_yticks(range(4),labels)
|
| 245 |
+
ax.set_xticks(range(5),[str(n) for n in range(5)]);ax.set_xlabel('Outer fold' if dslist==['immicro'] else 'Support draw')
|
| 246 |
+
ax.set_title('Healthy strict support' if dslist==['immicro'] else 'Disease strict five-pair')
|
| 247 |
+
ax.spines[['top','right','left','bottom']].set_visible(False)
|
| 248 |
+
for i,row in enumerate(mat):
|
| 249 |
+
for j,v in enumerate(row):ax.text(j,i,['Pending','Core','Full'][v],ha='center',va='center',fontsize=12,color='white' if v==2 else '#4D4D4D')
|
| 250 |
+
self.add(fig,'availability','PBISC x1: completed evidence and remaining units','Supp S07',
|
| 251 |
+
'Frozen snapshot; each square is one strict support/test unit. Core scores and full CPU statistics remain distinct.',
|
| 252 |
+
'Only validated receipt-bound scores are included. Missing scores do not imply missing training or generation. Healthy total-n pairs, no extra validation; disease exact-five support draws. Historical panels remain unchanged.')
|
| 253 |
+
def healthy(self):
|
| 254 |
+
rows=[r for r in self.e.records if r['cohort']=='immicro'];fig,axes=plt.subplots(1,3,figsize=ST.FULL)
|
| 255 |
+
fig.subplots_adjust(left=.07,right=.98,top=.84,bottom=.18,wspace=.38)
|
| 256 |
+
for ax,(key,label) in zip(axes,[('comp_l1','Composition L1 ↓'),('pb_r_median','Sample expression r ↑'),('coverage_dm','Depth-matched coverage ↑')]):
|
| 257 |
+
foldsets=[{r['fold'] for r in rows if r['arm']==arm and r['n']==n} for arm in ['lora','scsemi','pairedcal'] for n in [5,10,20,40]]
|
| 258 |
+
common=set.intersection(*foldsets) if all(foldsets) else set()
|
| 259 |
+
for arm in ['lora','scsemi','pairedcal']:
|
| 260 |
+
rr=[r for r in rows if r['arm']==arm]
|
| 261 |
+
for ni,n in enumerate([5,10,20,40]):
|
| 262 |
+
pts=[r for r in rr if r['n']==n and finite(r['headline'].get(key))]
|
| 263 |
+
for r in pts:ax.scatter(ni+(.035*(r['fold']-2)),r['headline'][key],color=COL[arm],marker=MARK[arm],s=35,alpha=.6,edgecolor='#4D4D4D',linewidth=.35)
|
| 264 |
+
if common:
|
| 265 |
+
vals=[np.mean([r['headline'][key] for r in rr if r['n']==n and r['fold'] in common]) for n in [5,10,20,40]]
|
| 266 |
+
ax.plot(range(4),vals,c=COL[arm],marker=MARK[arm],lw=2,label=LAB[arm]+f' ({len(common)} matched folds)')
|
| 267 |
+
ax.set_xticks(range(4),['5','10','20','40']);ax.set_xlim(-.25,3.25);ax.set_xlabel('Total training pairs');ax.set_ylabel(label);ax.grid(axis='y',alpha=.16)
|
| 268 |
+
fig.legend(handles=[Line2D([],[],color=COL[a],marker=MARK[a],lw=1.8,label=LAB[a]) for a in ['lora','scsemi','pairedcal']],ncol=3,loc='upper center',bbox_to_anchor=(.5,.99))
|
| 269 |
+
self.add(fig,'healthy_budget','Strict paired budget: held-out reconstruction','Figure 3',
|
| 270 |
+
'Dots: available folds. Lines: matched folds across all three methods and four budgets, only when available. No extra validation pairs.',
|
| 271 |
+
'Healthy strict outer folds use total support budgets 5/10/20/40. Do not merge with historical n+7-validation panels. Missing folds stay missing; no interpolation or unmatched-fold mean learning curve.')
|
| 272 |
+
fig,axes=plt.subplots(2,3,figsize=ST.FULL);fig.subplots_adjust(left=.08,right=.98,top=.84,bottom=.16,wspace=.35,hspace=.5)
|
| 273 |
+
for ax,typ in zip(axes.flat,TYPES):
|
| 274 |
+
for ai,arm in enumerate(['lora','scsemi']):
|
| 275 |
+
for ni,n in enumerate([5,10,20,40]):
|
| 276 |
+
rr=[r for r in rows if r['n']==n and r['arm']==arm]
|
| 277 |
+
vals=[100*(r['composition']['mean_fraction_generated'][typ]-r['composition']['mean_fraction_observed'][typ]) for r in rr]
|
| 278 |
+
if vals:ax.scatter(np.full(len(vals),ni)+(ai-.5)*.16,vals,color=COL[arm],marker=MARK[arm],s=30,alpha=.7)
|
| 279 |
+
ax.axhline(0,color='#777777',ls='--',lw=.8);ax.set_title(typ);ax.set_xticks(range(4),[5,10,20,40]);ax.set_xlim(-.25,3.25);ax.set_ylabel('Bias (percentage points)');ax.yaxis.set_major_locator(MaxNLocator(4))
|
| 280 |
+
fig.legend(handles=[Line2D([],[],color=COL[a],marker=MARK[a],lw=0,label=LAB[a]) for a in ['lora','scsemi']],ncol=2,loc='upper center',bbox_to_anchor=(.5,.99))
|
| 281 |
+
self.add(fig,'healthy_types','Strict support: composition bias across all six types','Figure 3',
|
| 282 |
+
'Each dot is one outer fold; generated mean fraction minus observed mean fraction. Zero is unbiased; this is not per-donor MAE.',
|
| 283 |
+
'T/B/Monocyte/NK/DC/Other all retained, including adverse results. Fold-specific mean fractions come from verified core score summaries. No pooling across unmatched folds.')
|
| 284 |
+
def disease(self):
|
| 285 |
+
for ds in COHORTS:
|
| 286 |
+
rr=[r for r in self.e.records if r['cohort']==ds]
|
| 287 |
+
if not rr:continue
|
| 288 |
+
if not any(r.get('contrast') for r in rr):
|
| 289 |
+
fig,axes=plt.subplots(1,2,figsize=ST.FULL);fig.subplots_adjust(left=.09,right=.98,top=.82,bottom=.2,wspace=.32)
|
| 290 |
+
for ax,key,label in zip(axes,['contrast_mean_cp10k_r_gen','deg_top50_sum'],['Disease logFC r ↑','Benchmark top-50 DEG overlap ↑']):
|
| 291 |
+
for arm in ARMS:
|
| 292 |
+
ordered=sorted([r for r in rr if r['arm']==arm and finite(r['headline'].get(key))],key=lambda r:r['draw'])
|
| 293 |
+
if ordered:ax.plot([r['draw'] for r in ordered],[r['headline'][key] for r in ordered],marker=MARK[arm],c=COL[arm],lw=0,label=LAB[arm])
|
| 294 |
+
ax.set_xticks(range(5));ax.set_xlabel('Support draw');ax.set_ylabel(label);ax.grid(axis='y',alpha=.16);ax.yaxis.set_major_locator(MaxNLocator(5))
|
| 295 |
+
if key=='deg_top50_sum':
|
| 296 |
+
values=[r['headline'][key] for r in rr if finite(r['headline'].get(key))]
|
| 297 |
+
ax.set_ylim(-.1,max(1,max(values,default=0)+1));ax.yaxis.set_major_locator(MaxNLocator(5,integer=True))
|
| 298 |
+
handles,labels=axes[0].get_legend_handles_labels()
|
| 299 |
+
fig.legend(handles,labels,ncol=3,loc='upper center',bbox_to_anchor=(.5,.99))
|
| 300 |
+
fig.text(.5,.05,'Full CPU rankings and patient-aware DEG: pending',ha='center',fontsize=12,color='#6E6E6E')
|
| 301 |
+
self.add(fig,'disease_'+ds,NAMES[ds]+': completed core disease metrics','Figure 4',
|
| 302 |
+
'Core scores only. Support draws share patients. Benchmark DEG is the saved cell-level top-50 overlap, not corrected donor-aware DEG.',
|
| 303 |
+
'Per-draw core metrics from validated existing generation. Missing method scores are not zero; no method superiority is claimed without matched comparator results. Full partial-r/CAT/RBO and donor-aware DEG remain pending. This panel upgrades automatically when full contrast receipts are available.')
|
| 304 |
+
continue
|
| 305 |
+
fig,axes=plt.subplots(2,2,figsize=ST.FULL);fig.subplots_adjust(left=.18,right=.97,top=.94,bottom=.13,wspace=.65,hspace=.42)
|
| 306 |
+
metrics=[('headline','contrast_mean_cp10k_r_gen','Disease logFC r ↑'),('contrast','partial_r','Bulk-controlled partial r ↑'),('contrast','cat100','Same-sign CAT100 ↑'),('contrast','rbo_up_down','Rank agreement RBO ↑')]
|
| 307 |
+
for ax,(family,key,label) in zip(axes.flat,metrics):
|
| 308 |
+
sets={arm:{r['draw'] for r in rr if r['arm']==arm and finite(r.get(family,{}).get(key))} for arm in ARMS}
|
| 309 |
+
present=[v for v in sets.values() if v];common=set.intersection(*present) if present else set()
|
| 310 |
+
if not common:ax.text(.5,.5,'Matched full metrics pending',ha='center',va='center',transform=ax.transAxes,color='#6E6E6E',fontsize=11)
|
| 311 |
+
for ai,arm in enumerate(ARMS):
|
| 312 |
+
vals=[float(r[family][key]) for r in rr if r['arm']==arm and r['draw'] in common and finite(r.get(family,{}).get(key))]
|
| 313 |
+
if vals:
|
| 314 |
+
ax.scatter(vals,ai+np.linspace(-.12,.12,len(vals)),color=COL[arm],marker=MARK[arm],s=45,edgecolor='#4D4D4D',linewidth=.45)
|
| 315 |
+
ax.plot([np.mean(vals)],[ai],marker='|',markersize=14,color='#222222',lw=0)
|
| 316 |
+
ax.text(1.02,ai,f'n={len(vals)}',transform=ax.get_yaxis_transform(),va='center',fontsize=10,color='#6E6E6E')
|
| 317 |
+
ax.set_yticks(range(5),[LAB[a] for a in ARMS]);ax.set_ylim(4.5,-.5);ax.set_xlabel(label);ax.grid(axis='x',alpha=.16);ax.xaxis.set_major_locator(MaxNLocator(4))
|
| 318 |
+
self.add(fig,'disease_'+ds,NAMES[ds]+': strict five-pair disease integrity','Figure 4',
|
| 319 |
+
'Each metric uses common draws across available methods. Dots: draws; ticks: means. Shared patients; full CPU results required for rankings.',
|
| 320 |
+
'Same strict support/test and condition for all displayed methods within each draw. Main logFC from core score; partial r/CAT/RBO from full contrast output. Each metric selects the intersection of available method draw sets; all unfiltered values remain in CSV. No statistical significance from overlapping-draw means.')
|
| 321 |
+
def extra(self):
|
| 322 |
+
full=[r for r in self.e.records if r['state'] in FULL]
|
| 323 |
+
for ds in COHORTS:
|
| 324 |
+
rr=[r for r in full if r['cohort']==ds]
|
| 325 |
+
if not rr:continue
|
| 326 |
+
fig,axes=plt.subplots(1,3,figsize=ST.FULL);fig.subplots_adjust(left=.16,right=.96,top=.92,bottom=.18,wspace=.65)
|
| 327 |
+
for ax,(fam,key,label) in zip(axes,[('headline','coverage_dm','Depth-matched coverage ↑'),('extras','c2st_knn_auc','C2ST kNN AUC (0.5 ideal)'),('direct','en','Sample energy score ↓')]):
|
| 328 |
+
for ai,arm in enumerate(ARMS):
|
| 329 |
+
vals=[float(r.get(key,np.nan) if fam=='direct' else r.get(fam,{}).get(key,np.nan)) for r in rr if r['arm']==arm]
|
| 330 |
+
vals=[v for v in vals if np.isfinite(v)]
|
| 331 |
+
if vals:ax.scatter(vals,ai+np.linspace(-.12,.12,len(vals)),c=COL[arm],marker=MARK[arm],s=42,edgecolor='#4D4D4D',linewidth=.4)
|
| 332 |
+
ax.set_yticks(range(5),[LAB[a] for a in ARMS]);ax.set_ylim(4.5,-.5);ax.set_xlabel(label);ax.xaxis.set_major_locator(MaxNLocator(4));ax.grid(axis='x',alpha=.16)
|
| 333 |
+
if key=='c2st_knn_auc':ax.axvline(.5,ls='--',c='#4D4D4D',lw=.8)
|
| 334 |
+
self.add(fig,'extras_'+ds,NAMES[ds]+': full realism and depth controls','Supp S07',
|
| 335 |
+
'Only completed full CPU evaluations. Each point is a support draw; no error bars over overlapping draws.',
|
| 336 |
+
'C2ST raw-mode/R1 kNN AUC, depth-matched coverage and existing PC/squared-distance sample energy score are different diagnostics. Small core-only differences are not substituted for full results.')
|
| 337 |
+
fig,axes=plt.subplots(2,2,figsize=ST.FULL);fig.subplots_adjust(left=.12,right=.98,top=.84,bottom=.13,wspace=.4,hspace=.55)
|
| 338 |
+
for ax,ds in zip(axes.flat,COHORTS):
|
| 339 |
+
for ai,arm in enumerate(['lora','scsemi']):
|
| 340 |
+
for ti,typ in enumerate(TYPES[:5]):
|
| 341 |
+
vals=[float(d['top50_overlap_count']) for r in full if r['cohort']==ds and r['arm']==arm for d in r.get('donor_deg',[]) if d['celltype']==typ and d['status']=='ok' and finite(d.get('top50_overlap_count'))]
|
| 342 |
+
if vals:ax.scatter(np.full(len(vals),ti)+(ai-.5)*.15,vals,c=COL[arm],marker=MARK[arm],s=32,alpha=.75)
|
| 343 |
+
ax.set_title(NAMES[ds]);ax.set_xticks(range(5),['T','B','Mono','NK','DC']);ax.set_xlim(-.35,4.35);ax.set_ylabel('Top-50 overlap ↑');ax.set_ylim(bottom=-.8);ax.yaxis.set_major_locator(MaxNLocator(4));ax.grid(axis='y',alpha=.16)
|
| 344 |
+
if not any(r['cohort']==ds and r.get('donor_deg') for r in full):
|
| 345 |
+
ax.text(.5,.5,'Full CPU results pending',ha='center',va='center',transform=ax.transAxes,color='#6E6E6E',fontsize=12)
|
| 346 |
+
fig.legend(handles=[Line2D([],[],color=COL[a],marker=MARK[a],lw=0,label=LAB[a]) for a in ['lora','scsemi']],ncol=2,loc='upper center',bbox_to_anchor=(.5,.99))
|
| 347 |
+
self.add(fig,'donor_deg','Patient-aware DEG: same support and test samples','Supp S08',
|
| 348 |
+
'Unique-donor pseudobulk; repeated visits handled by the saved model. Dots are support draws, not independent patients.',
|
| 349 |
+
'Only donor_deg rows with status=ok enter this plot. Non-estimable or pending populations remain missing, not zero. These corrected limma-voom overlaps differ from historical cell-level Welch DEG summaries.')
|
| 350 |
+
fig,axes=plt.subplots(1,2,figsize=ST.FULL);fig.subplots_adjust(left=.24,right=.97,top=.93,bottom=.16,wspace=.55)
|
| 351 |
+
for ax,key,label in zip(axes,['comp_l1','pb_r'],['Composition L1: scSemi minus LoRA','Expression r: scSemi minus LoRA']):
|
| 352 |
+
plotted=[]
|
| 353 |
+
for r in full:
|
| 354 |
+
if r['arm']!='lora':continue
|
| 355 |
+
for q in r.get('bootstrap',[]):
|
| 356 |
+
if q.get('arm')=='scsemi' and q.get('baseline')=='lora' and q.get('metric')==key and q.get('status')=='ok' and all(finite(q.get(k)) for k in ['estimate','ci_low','ci_high']):plotted.append((r,q))
|
| 357 |
+
for i,(r,q) in enumerate(plotted):
|
| 358 |
+
v=float(q['estimate']);lo=float(q['ci_low']);hi=float(q['ci_high']);ax.plot([lo,hi],[i,i],c='#999999',lw=1.2);ax.scatter(v,i,c=COL['lora'],s=28)
|
| 359 |
+
labels=[(NAMES[r['cohort']]+(' d'+str(r['draw']) if r['draw'] is not None else ' f'+str(r['fold'])+' n'+str(r['n']))) for r,q in plotted]
|
| 360 |
+
if len(labels)>22:
|
| 361 |
+
ax.clear();ax.text(.5,.5,'Per-unit donor intervals\nare in the exported CSV',ha='center',va='center',transform=ax.transAxes);ax.set_yticks([])
|
| 362 |
+
else:ax.set_yticks(range(len(labels)),labels,fontsize=10);ax.invert_yaxis()
|
| 363 |
+
ax.axvline(0,c='#555555',ls='--',lw=.8);ax.set_xlabel(label);ax.xaxis.set_major_locator(MaxNLocator(4))
|
| 364 |
+
self.add(fig,'donor_intervals','Paired donor uncertainty: saved 2,000-bootstrap intervals','Supp S08',
|
| 365 |
+
'95% percentile intervals within each support draw. No averaging of intervals across overlapping draws; all rows are exported.',
|
| 366 |
+
'Only scSemi-minus-LoRA paired donor bootstrap rows with status=ok. Positive composition delta favors LoRA; positive expression delta favors scSemi. These intervals are not simultaneous or multiplicity-adjusted.')
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
for ds in COHORTS+['immicro']:
|
| 370 |
+
items=[(r,q) for r in full if r['cohort']==ds and r['arm']=='lora' for q in r.get('individual_bootstrap',[]) if q.get('status')=='ok' and all(finite(q.get(k)) for k in ['estimate','ci_low','ci_high'])]
|
| 371 |
+
if not items:continue
|
| 372 |
+
fig,axes=plt.subplots(1,2,figsize=ST.FULL);fig.subplots_adjust(left=.16,right=.98,top=.93,bottom=.16,wspace=.4)
|
| 373 |
+
for ax,key,label in zip(axes,['comp_l1','pb_r'],['Composition L1 ↓','Mean sample expression r ↑']):
|
| 374 |
+
available=[(r,q) for r,q in items if q.get('metric')==key]
|
| 375 |
+
for i,(r,q) in enumerate(available):
|
| 376 |
+
ax.plot([float(q['ci_low']),float(q['ci_high'])],[i,i],c='#777777',lw=1.2)
|
| 377 |
+
ax.scatter(float(q['estimate']),i,c=COL['lora'],s=35)
|
| 378 |
+
labels=[('Draw '+str(r['draw']) if r['draw'] is not None else 'Fold '+str(r['fold'])+' / '+str(r['n'])+' pairs') for r,q in available]
|
| 379 |
+
ax.set_yticks(range(len(labels)),labels,fontsize=11);ax.invert_yaxis();ax.set_xlabel(label);ax.grid(axis='x',alpha=.16)
|
| 380 |
+
if not available:ax.text(.5,.5,'Interval not estimable',transform=ax.transAxes,ha='center',va='center',color='#6E6E6E')
|
| 381 |
+
self.add(fig,'individual_ci_'+ds,NAMES[ds]+': PBISC x1 donor uncertainty','Supp S08',
|
| 382 |
+
'Single-arm estimates and 95% donor-bootstrap intervals. These are not paired method differences; draws share patients.',
|
| 383 |
+
'Saved individual_donor_bootstrap_2000.csv, unique donors with all visits retained. Expression estimate is the donor-average sample r, not the core table median. No cross-method CI is fabricated when only one method is available.')
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def build(args):
|
| 387 |
+
A.mkdir(exist_ok=True);initialize_base();stamp=datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%S%fZ');b=A/'builds'/stamp;b.mkdir(parents=True)
|
| 388 |
+
e=Evidence(b).load(Path(args.status));parent=js(PARENT)['slides'];assert len(parent)==156
|
| 389 |
+
pm=js(PARENT.parent/'manifest.json');protected=js(PARENT.parent/'BASE_VERIFIED.json')['protected']
|
| 390 |
+
for s in parent:
|
| 391 |
+
for f in s.get('figures',[]):
|
| 392 |
+
p=str(D/f)
|
| 393 |
+
if sha(p)!=pm['sources'][p]['sha256']:raise ValueError(f'Parent figure changed: {p}')
|
| 394 |
+
finger=hashlib.sha256(json.dumps({'evidence':{p:v['sha256'] for p,v in e.sources.items() if p!=str(Path(args.status))},'units':e.units,'parent':sha(PARENT),'builder':sha(__file__)},sort_keys=True).encode()).hexdigest()
|
| 395 |
+
old=A/'LATEST.json'
|
| 396 |
+
if args.if_changed and old.exists() and js(old).get('fingerprint')==finger:
|
| 397 |
+
savejs(b/'NO_CHANGE.json',{'fingerprint':finger,'previous':js(old)['build']});print('No numerical evidence delta; skipped rendering');return
|
| 398 |
+
savejs(b/'SOURCE_MANIFEST.json',{'schema':'pbisc.x1.priority.deck-sources.v1','sources':list(e.sources.values()),'units':e.units,'rejected':e.failures,'optional_interval_gaps':e.optional_gaps,'fingerprint':finger})
|
| 399 |
+
flat=[];boots=[];degs=[];individual=[]
|
| 400 |
+
for r in e.records:
|
| 401 |
+
flat.append({k:r[k] for k in ['unit','cohort','arm','state','n','fold','draw','support_sha256']}|r['headline']|{f'contrast_{k}':v for k,v in r.get('contrast',{}).items()})
|
| 402 |
+
individual.extend({'unit':r['unit'],'cohort':r['cohort'],**x} for x in r.get('individual_bootstrap',[]))
|
| 403 |
+
boots.extend({'unit':r['unit'],'cohort':r['cohort'],**x} for x in r.get('bootstrap',[]));degs.extend({'unit':r['unit'],'cohort':r['cohort'],**x} for x in r.get('donor_deg',[]))
|
| 404 |
+
pd.DataFrame(flat).to_csv(b/'ALL_METRICS.csv',index=False);pd.DataFrame(boots).drop_duplicates().to_csv(b/'DONOR_INTERVALS.csv',index=False);pd.DataFrame(degs).drop_duplicates().to_csv(b/'DONOR_DEG.csv',index=False);pd.DataFrame(individual).drop_duplicates().to_csv(b/'INDIVIDUAL_DONOR_INTERVALS.csv',index=False)
|
| 405 |
+
plots=Plots(e);plots.status();plots.healthy();plots.disease();plots.extra()
|
| 406 |
+
additions=defaultdict(list)
|
| 407 |
+
for s in plots.slides:additions[s['deck_group']].append(s)
|
| 408 |
+
last={s['deck_group']:n for n,s in enumerate(parent,1)};slides=[]
|
| 409 |
+
for n,ss in enumerate(parent,1):
|
| 410 |
+
s=copy.deepcopy(ss);s['parent_156_page']=n;slides.append(s)
|
| 411 |
+
if n==last[s['deck_group']]:slides.extend(additions.get(s['deck_group'],[]))
|
| 412 |
+
mapping={s['parent_156_page']:n for n,s in enumerate(slides,1) if 'parent_156_page'in s}
|
| 413 |
+
for s in slides:
|
| 414 |
+
if s['kind']=='plan_card':s['rows']=[(h,c,re.sub(r'\d+',lambda m:str(mapping[int(m.group())]),p) if re.match(r'^pp?\.',p) else p) for h,c,p in s['rows']]
|
| 415 |
+
slides[0]['subtitle']=f'{len(slides)} slides | Preserved full master | Strict x1 results and CPU-statistics snapshot'
|
| 416 |
+
prs=Presentation();prs.slide_width=Inches(G.SLIDE_W);prs.slide_height=Inches(G.SLIDE_H)
|
| 417 |
+
funcs={'title':G.build_title,'agenda':G.build_agenda,'divider':G.build_divider,'content':G.build_content,'plan_card':draw_card,'evidence_note':draw_note}
|
| 418 |
+
for n,s in enumerate(slides,1):funcs[s['kind']](prs,s) if s['kind']=='title' else funcs[s['kind']](prs,s,n)
|
| 419 |
+
pp=b/(OUT+'.pptx');pdf=b/(OUT+'.pdf');prs.save(pp)
|
| 420 |
+
savejs(b/'spec.json',{'deck':{'output_pptx':str(pp),'output_pdf':str(pdf)},'slides':slides})
|
| 421 |
+
pd.DataFrame([{'page':i,'parent_156_page':s.get('parent_156_page'),'group':s['deck_group'],'title':s['title'],'addition':s.get('addition_key','')} for i,s in enumerate(slides,1)]).to_csv(b/'page_map.csv',index=False)
|
| 422 |
+
subprocess.run(['libreoffice',f'-env:UserInstallation=file:///tmp/pbisc-x1-priority-lo-{stamp}','--headless','--convert-to','pdf:impress_pdf_Export:{"UseTaggedPDF":{"type":"boolean","value":"false"},"PDFUACompliance":{"type":"boolean","value":"false"}}','--outdir',str(b),str(pp)],check=True,timeout=600)
|
| 423 |
+
doc=fitz.open(pdf);fail=[];fonts=set();imageproof=[];newpages=[]
|
| 424 |
+
if len(doc)!=len(slides) or len(prs.slides)!=len(slides):fail.append('page count')
|
| 425 |
+
if sorted(s['parent_156_page'] for s in slides if 'parent_156_page'in s)!=list(range(1,157)):fail.append('parent156 coverage')
|
| 426 |
+
if sorted(s['original_slide'] for s in slides if 'original_slide'in s)!=list(range(1,77)):fail.append('original76 coverage')
|
| 427 |
+
for n,(slide,s) in enumerate(zip(prs.slides,slides),1):
|
| 428 |
+
imageproof.append(V._image_proofs(slide,s,n,fail))
|
| 429 |
+
if 'parent_156_page'in s and s.get('figures',[])!=parent[s['parent_156_page']-1].get('figures',[]):fail.append(['parentfigures',n])
|
| 430 |
+
for sh in slide.shapes:
|
| 431 |
+
if sh.left< -2 or sh.top< -2 or sh.left+sh.width>prs.slide_width+2 or sh.top+sh.height>prs.slide_height+2:fail.append(['shape',n,sh.name])
|
| 432 |
+
for tf in V._text_frames(sh):
|
| 433 |
+
for para in tf.paragraphs:
|
| 434 |
+
for run in para.runs:fonts.update(V._font_names(run,para))
|
| 435 |
+
if s.get('addition_key','').startswith('x1_priority:'):newpages.append(n)
|
| 436 |
+
if fonts!={'Arial'}:fail.append(['fonts',list(fonts)])
|
| 437 |
+
for n,page in enumerate(doc,1):
|
| 438 |
+
for block in page.get_text('dict')['blocks']:
|
| 439 |
+
for line in block.get('lines',[]):
|
| 440 |
+
for t in line.get('spans',[]):
|
| 441 |
+
x0,y0,x1,y1=t['bbox']
|
| 442 |
+
if min(x0,y0)<-.75 or x1>page.rect.width+.75 or y1>page.rect.height+.75:fail.append(['pdftext',n,t['text']])
|
| 443 |
+
qa=b/'qa';qa.mkdir();review=fitz.open()
|
| 444 |
+
for n in newpages:
|
| 445 |
+
doc[n-1].get_pixmap(matrix=fitz.Matrix(1.3,1.3)).save(qa/f'page_{n:03}.png');review.insert_pdf(doc,from_page=n-1,to_page=n-1)
|
| 446 |
+
review.save(b/'NEW_RESULTS_REVIEW.pdf',garbage=4,deflate=True);review.close()
|
| 447 |
+
from PIL import Image,ImageOps,ImageDraw
|
| 448 |
+
thumbs=[]
|
| 449 |
+
for n in newpages:
|
| 450 |
+
im=Image.open(qa/f'page_{n:03}.png').convert('RGB');im.thumbnail((480,280));can=Image.new('RGB',(500,310),'#EEEEEE');can.paste(im,((500-im.width)//2,20));ImageDraw.Draw(can).text((10,5),f'Page {n}',fill='black');thumbs.append(can)
|
| 451 |
+
contact=Image.new('RGB',(1000,310*((len(thumbs)+1)//2)),'white')
|
| 452 |
+
for i,im in enumerate(thumbs):contact.paste(im,((i%2)*500,(i//2)*310))
|
| 453 |
+
contact.save(qa/'contact.png')
|
| 454 |
+
for p,h in protected.items():
|
| 455 |
+
if sha(p)!=h:fail.append(['protected source changed',p])
|
| 456 |
+
result={'schema':'pbisc.x1.priority.deck-qa.v1','status':'automated_pass_visual_pending' if not fail else 'failed','failures':fail,'slides':len(slides),'parent156_preserved':True,'original76_preserved':True,'Figure1_parent_pages7to10_preserved':True,'new_pages':newpages,'font':sorted(fonts),'image_checks':imageproof,'source_rejections':e.failures,'optional_interval_gaps':e.optional_gaps,'visual_review':'pending','artifacts':{'pptx':str(pp),'pdf':str(pdf),'preview':str(b/'NEW_RESULTS_REVIEW.pdf'),'contact':str(qa/'contact.png')}}
|
| 457 |
+
savejs(qa/'VERIFICATION.json',result)
|
| 458 |
+
if fail:raise RuntimeError(f'QA failed: {fail}')
|
| 459 |
+
for src,dest in [(pp,D/(OUT+'.pptx')),(pdf,D/(OUT+'.pdf'))]:
|
| 460 |
+
tmp=dest.with_suffix(dest.suffix+'.tmp');shutil.copy2(src,tmp);tmp.replace(dest)
|
| 461 |
+
latest={'build':str(b),'fingerprint':finger,'created_at':datetime.now(timezone.utc).isoformat(),'slides':len(slides),'new_pages':newpages,'accepted_units':len({r['unit'] for r in e.records}),'full_lora_units':sum(r['arm']=='lora' and r['state']in FULL for r in e.records),'artifacts':result['artifacts'],'protected_sources':protected,'visual_review':'pending'}
|
| 462 |
+
latest['verification_path']=str(qa/'VERIFICATION.json');latest['verification_sha256']=sha(qa/'VERIFICATION.json')
|
| 463 |
+
savejs(A/'LATEST.json',latest)
|
| 464 |
+
savejs(A/'VERIFIED.json',{'schema':'pbisc.x1.priority.latest-verified.v1','status':'automated_pass_visual_pending','build':str(b),'fingerprint':finger,'slides':len(slides),'verification':str(qa/'VERIFICATION.json'),'outputs':{str(D/(OUT+ext)):sha(D/(OUT+ext)) for ext in ['.pptx','.pdf']},'parent_base':str(PARENT.parent/'BASE_VERIFIED.json')})
|
| 465 |
+
print(json.dumps({k:v for k,v in latest.items() if k!='protected_sources'}))
|
| 466 |
+
|
| 467 |
+
if __name__=='__main__':
|
| 468 |
+
ap=argparse.ArgumentParser();ap.add_argument('--status',default=str(STATUS));ap.add_argument('--if-changed',action='store_true');args=ap.parse_args();A.mkdir(exist_ok=True)
|
| 469 |
+
with (A/'build.lock').open('a') as lock:
|
| 470 |
+
fcntl.flock(lock,fcntl.LOCK_EX);build(args)
|