Archive 4 checkpoints (1-4)
Browse files- paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/REPORT.md +34 -0
- paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/RUNNING_OBSERVATION.json +173 -0
- paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/MANIFEST.json +14 -0
- paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/tools/deconv_strict.py +838 -0
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/REPORT.md
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Existing-results reuse and duplicate-work cleanup — 2026-10-13
|
| 2 |
+
|
| 3 |
+
The user authorized a whole-Model8 audit, prevention of redundant computation, rebuilding the available-results deck, and discarding assistant-created duplicate work.
|
| 4 |
+
|
| 5 |
+
## Decisions implemented
|
| 6 |
+
|
| 7 |
+
- The root EXPERIMENT_INDEX.md / JSONL registry cover the entire non-environment working tree, distinguish archive copies, and expose metadata reuse candidates. Matching metadata never substitutes for verified scientific equivalence.
|
| 8 |
+
- Five repeated Sepsis LoRA training runs have identical64serialized tensor payloads to their original checkpoints, with matching support, base model, conditioning, optimizer and3000step recipe. The duplicate execution cost was601.36seconds. They are excluded as independent model evidence. See CONFIRMED_DUPLICATE_TRAINING.json.
|
| 9 |
+
- All5completed Sepsis BayesPrism/CIBERSORTx results are now adopted with verified original support, inputs, output axes/hashes and draw-specific sampling. No method reruns were launched. Missing proof fails closed instead of falling back to expensive recomputation. Fresh corrected CPU statistics remain required.
|
| 10 |
+
- Healthy strict curves differ from old n+7validation / early-stopping curves. Imperial/Giroux/Ji exact-five support differs from old12–15/12–14/7–9sample support. These are retained as explicitly changed protocols, not labelled duplicates.
|
| 11 |
+
- The new34slide deck reuses completed evidence. Three saved-table redraws add healthy composition and corrected rare-state views without training or cell generation. Historical/diagnostic designs and pending strict updates are visibly separated.
|
| 12 |
+
-45superseded generated working files were deleted (20,002,296bytes);36independent archivedpayload copies were read back and SHA-verified. Nine derivative rendering files are reproducible from the archivedPPTX. Original76slide deck, frozenarchives, sourcefigures, logs and manifests were preserved.
|
| 13 |
+
|
| 14 |
+
## Retained evidence, not independent results
|
| 15 |
+
|
| 16 |
+
Five duplicate-training serialized checkpoint files remain in place because current generation/train receipts bind their distinct full-file SHA values. Their tensorpayloads match the originals, but serialization metadata differs. Deleting them or substituting the older bytes would break existing output provenance and restart verification. Their duplicate status and canonical original links are recorded in the registry; no further training is scheduled to reproduce them. Remaining stagedmanuscript source and15authored edit templates are consumed by the campaign finalizer and are not disposable duplicates. Only the two obsolete previewPDFs were removed.
|
| 17 |
+
|
| 18 |
+
## Current deck
|
| 19 |
+
|
| 20 |
+
presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_results_review_20261013.pdf
|
| 21 |
+
presentations/2026-09-30--paper-summary--r00/PBISC-Diffusion_results_review_20261013.pptx
|
| 22 |
+
|
| 23 |
+
The old76slide deck remains the source/reference deck. The TODO-heavy8page layout and prior strict-preview deck have been retired. Figure6 remains awaiting user-prepared data.
|
| 24 |
+
|
| 25 |
+
## Verification
|
| 26 |
+
|
| 27 |
+
- Deconvolution integration:193passed,1dependency skip,18subtests; independent staticreview found no blockers. See deconvolution_tests_final.xml and deconvolution_verification.json.
|
| 28 |
+
- Registry field/unknown/confirmedalias tests are recorded by the final verification run.
|
| 29 |
+
- Deck:34nativePDF pages and34PPTX slides, source hashes and shape bounds checked; native and renderedPPTX views inspected.
|
| 30 |
+
- No sealed Model8source or canonical manuscript text changed. No GitHub push or Overleaf synchronization.
|
| 31 |
+
|
| 32 |
+
## Coverage boundary
|
| 33 |
+
|
| 34 |
+
EXPERIMENT_REUSE_COVERAGE.json records precise scan counts and exclusions. Array/checkpoint payloads are inventoried, not all reloaded/hashed. The five confirmedSepsis duplicates have a separate streaming tensorpayload verification. Environment/cache descendants and directorysymlink targets are explicitly excluded from payload inspection; cross-host locationcatalog records are distinguished from fresh fileobservations.
|
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/RUNNING_OBSERVATION.json
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"at_utc": "2026-10-13T00:50:08.946968+00:00",
|
| 3 |
+
"source_host": "server_1",
|
| 4 |
+
"two_host_controller": {
|
| 5 |
+
"schema": "pbisc.two-host.status.v1",
|
| 6 |
+
"config_sha256": "56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9",
|
| 7 |
+
"config_path": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/recoveries/two_host/config.json",
|
| 8 |
+
"state": "running",
|
| 9 |
+
"services": {
|
| 10 |
+
"local": {
|
| 11 |
+
"unit": "pbisc-strict-resume-20261012-local.service",
|
| 12 |
+
"remote": false,
|
| 13 |
+
"state": "running",
|
| 14 |
+
"properties": {
|
| 15 |
+
"Result": "success",
|
| 16 |
+
"ExecMainCode": "0",
|
| 17 |
+
"ExecMainStatus": "0",
|
| 18 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 local",
|
| 19 |
+
"LoadState": "loaded",
|
| 20 |
+
"ActiveState": "active",
|
| 21 |
+
"SubState": "running"
|
| 22 |
+
},
|
| 23 |
+
"observed_at": "2026-10-13T00:49:57.557704+00:00"
|
| 24 |
+
},
|
| 25 |
+
"remote-immicro-healthy-fold2-n5": {
|
| 26 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold2-n5.service",
|
| 27 |
+
"remote": true,
|
| 28 |
+
"state": "completed",
|
| 29 |
+
"properties": {
|
| 30 |
+
"Result": "success",
|
| 31 |
+
"ExecMainCode": "1",
|
| 32 |
+
"ExecMainStatus": "0",
|
| 33 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold2-n5",
|
| 34 |
+
"LoadState": "loaded",
|
| 35 |
+
"ActiveState": "active",
|
| 36 |
+
"SubState": "exited"
|
| 37 |
+
},
|
| 38 |
+
"observed_at": "2026-10-12T15:37:49.285312+00:00"
|
| 39 |
+
},
|
| 40 |
+
"remote-immicro-healthy-fold3-n5": {
|
| 41 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold3-n5.service",
|
| 42 |
+
"remote": true,
|
| 43 |
+
"state": "completed",
|
| 44 |
+
"properties": {
|
| 45 |
+
"Result": "success",
|
| 46 |
+
"ExecMainCode": "1",
|
| 47 |
+
"ExecMainStatus": "0",
|
| 48 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold3-n5",
|
| 49 |
+
"LoadState": "loaded",
|
| 50 |
+
"ActiveState": "active",
|
| 51 |
+
"SubState": "exited"
|
| 52 |
+
},
|
| 53 |
+
"observed_at": "2026-10-12T16:25:09.346766+00:00"
|
| 54 |
+
},
|
| 55 |
+
"remote-immicro-healthy-fold4-n5": {
|
| 56 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold4-n5.service",
|
| 57 |
+
"remote": true,
|
| 58 |
+
"state": "completed",
|
| 59 |
+
"properties": {
|
| 60 |
+
"Result": "success",
|
| 61 |
+
"ExecMainCode": "1",
|
| 62 |
+
"ExecMainStatus": "0",
|
| 63 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold4-n5",
|
| 64 |
+
"LoadState": "loaded",
|
| 65 |
+
"ActiveState": "active",
|
| 66 |
+
"SubState": "exited"
|
| 67 |
+
},
|
| 68 |
+
"observed_at": "2026-10-12T17:07:27.009369+00:00"
|
| 69 |
+
},
|
| 70 |
+
"remote-immicro-healthy-fold2-n10": {
|
| 71 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold2-n10.service",
|
| 72 |
+
"remote": true,
|
| 73 |
+
"state": "completed",
|
| 74 |
+
"properties": {
|
| 75 |
+
"Result": "success",
|
| 76 |
+
"ExecMainCode": "1",
|
| 77 |
+
"ExecMainStatus": "0",
|
| 78 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold2-n10",
|
| 79 |
+
"LoadState": "loaded",
|
| 80 |
+
"ActiveState": "active",
|
| 81 |
+
"SubState": "exited"
|
| 82 |
+
},
|
| 83 |
+
"observed_at": "2026-10-12T18:23:29.790344+00:00"
|
| 84 |
+
},
|
| 85 |
+
"remote-immicro-healthy-fold2-n20": {
|
| 86 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold2-n20.service",
|
| 87 |
+
"remote": true,
|
| 88 |
+
"state": "completed",
|
| 89 |
+
"properties": {
|
| 90 |
+
"Result": "success",
|
| 91 |
+
"ExecMainCode": "1",
|
| 92 |
+
"ExecMainStatus": "0",
|
| 93 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold2-n20",
|
| 94 |
+
"LoadState": "loaded",
|
| 95 |
+
"ActiveState": "active",
|
| 96 |
+
"SubState": "exited"
|
| 97 |
+
},
|
| 98 |
+
"observed_at": "2026-10-12T19:56:23.501050+00:00"
|
| 99 |
+
},
|
| 100 |
+
"remote-immicro-healthy-fold2-n40": {
|
| 101 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold2-n40.service",
|
| 102 |
+
"remote": true,
|
| 103 |
+
"state": "completed",
|
| 104 |
+
"properties": {
|
| 105 |
+
"Result": "success",
|
| 106 |
+
"ExecMainCode": "1",
|
| 107 |
+
"ExecMainStatus": "0",
|
| 108 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold2-n40",
|
| 109 |
+
"LoadState": "loaded",
|
| 110 |
+
"ActiveState": "active",
|
| 111 |
+
"SubState": "exited"
|
| 112 |
+
},
|
| 113 |
+
"observed_at": "2026-10-12T22:30:51.330725+00:00"
|
| 114 |
+
},
|
| 115 |
+
"remote-immicro-healthy-fold3-n10": {
|
| 116 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold3-n10.service",
|
| 117 |
+
"remote": true,
|
| 118 |
+
"state": "completed",
|
| 119 |
+
"properties": {
|
| 120 |
+
"Result": "success",
|
| 121 |
+
"ExecMainCode": "1",
|
| 122 |
+
"ExecMainStatus": "0",
|
| 123 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold3-n10",
|
| 124 |
+
"LoadState": "loaded",
|
| 125 |
+
"ActiveState": "active",
|
| 126 |
+
"SubState": "exited"
|
| 127 |
+
},
|
| 128 |
+
"observed_at": "2026-10-12T23:38:15.249264+00:00"
|
| 129 |
+
},
|
| 130 |
+
"remote-immicro-healthy-fold3-n20": {
|
| 131 |
+
"unit": "pbisc-strict-resume-20261012-remote-immicro-healthy-fold3-n20.service",
|
| 132 |
+
"remote": true,
|
| 133 |
+
"state": "running",
|
| 134 |
+
"properties": {
|
| 135 |
+
"Result": "success",
|
| 136 |
+
"ExecMainCode": "0",
|
| 137 |
+
"ExecMainStatus": "0",
|
| 138 |
+
"Description": "PBISC strict two-host 56c62625359d63a2944984a4f60fd4b4b1aabc621826b1105f09be0e06a5fdd9 remote-immicro-healthy-fold3-n20",
|
| 139 |
+
"LoadState": "loaded",
|
| 140 |
+
"ActiveState": "active",
|
| 141 |
+
"SubState": "running"
|
| 142 |
+
},
|
| 143 |
+
"observed_at": "2026-10-13T00:49:58.108393+00:00"
|
| 144 |
+
}
|
| 145 |
+
},
|
| 146 |
+
"remote_imported": [
|
| 147 |
+
"immicro-healthy-fold2-n5",
|
| 148 |
+
"immicro-healthy-fold3-n5",
|
| 149 |
+
"immicro-healthy-fold4-n5",
|
| 150 |
+
"immicro-healthy-fold2-n10",
|
| 151 |
+
"immicro-healthy-fold2-n20",
|
| 152 |
+
"immicro-healthy-fold2-n40",
|
| 153 |
+
"immicro-healthy-fold3-n10"
|
| 154 |
+
],
|
| 155 |
+
"figure6": "waiting_user_data_no_execution",
|
| 156 |
+
"error": null,
|
| 157 |
+
"updated_at": "2026-10-13T00:49:58.108819+00:00",
|
| 158 |
+
"active": "immicro-healthy-fold3-n20",
|
| 159 |
+
"local_state": "running",
|
| 160 |
+
"remote_state": "running"
|
| 161 |
+
},
|
| 162 |
+
"local_campaign": {
|
| 163 |
+
"state": "running",
|
| 164 |
+
"stage": "all",
|
| 165 |
+
"started_at": "2026-10-12T14:35:32.695904+00:00",
|
| 166 |
+
"units_selected": 28,
|
| 167 |
+
"units_completed_this_invocation": 8,
|
| 168 |
+
"figure6": "waiting_user_data_no_execution",
|
| 169 |
+
"active": "imperial_eskd-disease-draw1",
|
| 170 |
+
"updated_at": "2026-10-13T00:29:29.149206+00:00"
|
| 171 |
+
},
|
| 172 |
+
"note": "Observation only. Ongoing scientifically changed exact-pair experiments are not marked complete by the current deck."
|
| 173 |
+
}
|
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/MANIFEST.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"files": [
|
| 3 |
+
{
|
| 4 |
+
"source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/deconv_strict.py",
|
| 5 |
+
"backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/tools/deconv_strict.py",
|
| 6 |
+
"sha256": "4ff691ee95f5a96722cc2e5369d5aecdee68218dfab349b73e9d29bd224b22e4"
|
| 7 |
+
},
|
| 8 |
+
{
|
| 9 |
+
"source": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/tools/finalize_campaign.py",
|
| 10 |
+
"backup": "/home/sj_server_1/PBISC/immun-pbmc-fm/model_8_sparse_data_diffusion/plans/paper_figures_strictpairs_20261012/audit_reuse_20261013/backups/deconvolution/tools/finalize_campaign.py",
|
| 11 |
+
"sha256": "017e1a8a5d9c1a60bc082852c29019bf566c0c6aceafba91b1c9991918aba985"
|
| 12 |
+
}
|
| 13 |
+
]
|
| 14 |
+
}
|
paper-releases/pbisc-diffusion/updates/20261013T005008Z-reuse-audit-results-deck/diffusion/dataset/server_1/model8/pl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usr/bin/env python3
|
| 2 |
+
"""Exact-support BayesPrism/CIBERSORTx adapter for one strict disease unit.
|
| 3 |
+
|
| 4 |
+
CPU only. Each invocation is an isolated process; legacy modules are imported
|
| 5 |
+
unchanged and their output root and split function are patched in memory.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import argparse
|
| 10 |
+
import csv
|
| 11 |
+
import hashlib
|
| 12 |
+
import importlib
|
| 13 |
+
import json
|
| 14 |
+
import os
|
| 15 |
+
import re
|
| 16 |
+
import subprocess
|
| 17 |
+
import sys
|
| 18 |
+
import tempfile
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = ""
|
| 22 |
+
for key in ("OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", "MKL_NUM_THREADS"):
|
| 23 |
+
os.environ.setdefault(key, "4")
|
| 24 |
+
|
| 25 |
+
import numpy as np # noqa: E402
|
| 26 |
+
import pandas as pd # noqa: E402
|
| 27 |
+
|
| 28 |
+
PLAN = Path(__file__).resolve().parents[1]
|
| 29 |
+
OLD = PLAN.parent / "bayesprism_paired_20261006"
|
| 30 |
+
OLD_TOOLS = OLD / "tools"
|
| 31 |
+
KEY = Path("/home/sj_server_1/cibersortx.key")
|
| 32 |
+
GUARD = Path("/home/sj_server_1/.local/libexec/ml-memory-guard")
|
| 33 |
+
SPLIT = "fewshot0"
|
| 34 |
+
sys.path.insert(0, str(OLD_TOOLS))
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def sha(path: Path) -> str:
|
| 38 |
+
h = hashlib.sha256()
|
| 39 |
+
with path.open("rb") as f:
|
| 40 |
+
for chunk in iter(lambda: f.read(1 << 20), b""):
|
| 41 |
+
h.update(chunk)
|
| 42 |
+
return h.hexdigest()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def host_preflight() -> None:
|
| 46 |
+
"""Host-wide GB10 guard checks before memory-heavy CPU preparation or methods."""
|
| 47 |
+
active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
|
| 48 |
+
capture_output=True, text=True)
|
| 49 |
+
if active.returncode or active.stdout.strip() != "active":
|
| 50 |
+
subprocess.run(["systemctl", "--user", "restart", "ml-memory-guard.service"], check=True)
|
| 51 |
+
active = subprocess.run(["systemctl", "--user", "is-active", "ml-memory-guard.service"],
|
| 52 |
+
capture_output=True, text=True)
|
| 53 |
+
if active.returncode or active.stdout.strip() != "active":
|
| 54 |
+
raise RuntimeError("ml-memory-guard.service is inactive after restart")
|
| 55 |
+
subprocess.run([str(GUARD), "--check"], check=True)
|
| 56 |
+
apps = subprocess.run(["nvidia-smi", "--query-compute-apps=pid,process_name,used_memory", "--format=csv,noheader"],
|
| 57 |
+
check=True, capture_output=True, text=True)
|
| 58 |
+
if apps.stdout.strip():
|
| 59 |
+
raise RuntimeError("a CUDA compute job is active; queue this memory-heavy CPU unit until it completes")
|
| 60 |
+
available_kib = next(int(line.split()[1]) for line in Path("/proc/meminfo").read_text().splitlines()
|
| 61 |
+
if line.startswith("MemAvailable:"))
|
| 62 |
+
if available_kib < 48 * 1024 * 1024:
|
| 63 |
+
raise RuntimeError("less than 48 GiB MemAvailable; defer the memory-heavy deconvolution unit")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def validate_support_data(s: dict) -> dict:
|
| 67 |
+
body = {k: v for k, v in s.items() if k != "sha256"}
|
| 68 |
+
digest = hashlib.sha256(json.dumps(body, sort_keys=True, separators=(",", ":"), allow_nan=False).encode()).hexdigest()
|
| 69 |
+
if s.get("schema") != "pbisc.paper.strict-support.v1" or s.get("sha256") != digest:
|
| 70 |
+
raise ValueError("strict support schema or hash mismatch")
|
| 71 |
+
train, test = s.get("train_sample_ids", []), s.get("test_sample_ids", [])
|
| 72 |
+
td, vd = s.get("train_donor_ids", []), s.get("test_donor_ids", [])
|
| 73 |
+
if not train or not test or len(train) != len(td) or len(test) != len(vd):
|
| 74 |
+
raise ValueError("strict support requires aligned sample and donor IDs")
|
| 75 |
+
if len(set(train)) != len(train) or len(set(test)) != len(test) or len(set(td)) != len(td):
|
| 76 |
+
raise ValueError("duplicate strict reference or mixture identity")
|
| 77 |
+
if set(td) & set(vd) or set(train) & set(test):
|
| 78 |
+
raise ValueError("reference and mixture donors/samples overlap")
|
| 79 |
+
if s["cohort"] not in {"ye2026_sepsis", "ji2025_chili", "imperial_eskd", "giroux2022"}:
|
| 80 |
+
raise ValueError("deconvolution supports disease cohorts only")
|
| 81 |
+
if s.get("design") != "disease_existing_draw" or not re.fullmatch(r"draw[0-4]_n5", str(s.get("unit", ""))):
|
| 82 |
+
raise ValueError("deconvolution requires a canonical disease draw unit")
|
| 83 |
+
if s["n_pairs"] != 5 or len(s["train_sample_ids"]) != 5:
|
| 84 |
+
raise ValueError("deconvolution requires exact five-pair support")
|
| 85 |
+
if set(s["excluded_sample_ids"]) & (set(s["train_sample_ids"]) | set(s["test_sample_ids"])):
|
| 86 |
+
raise ValueError("excluded visits entered the reference or mixture")
|
| 87 |
+
return s
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def support(path: Path) -> dict:
|
| 91 |
+
s = validate_support_data(json.loads(path.read_text()))
|
| 92 |
+
draw = s["unit"].replace("_n5", "")
|
| 93 |
+
canonical = PLAN / "protocol" / "splits" / s["cohort"] / "disease" / draw / "support.json"
|
| 94 |
+
if path.resolve() != canonical.resolve() or not canonical.is_file():
|
| 95 |
+
raise ValueError("support manifest must be the canonical protocol file")
|
| 96 |
+
return s
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def unit_out(s: dict, out: Path | None) -> Path:
|
| 100 |
+
validate_support_data(s)
|
| 101 |
+
expected = (PLAN / "deconvolution" / s["cohort"] / "disease" /
|
| 102 |
+
s["unit"].replace("_n5", "")).resolve()
|
| 103 |
+
if not expected.is_relative_to((PLAN / "deconvolution").resolve()):
|
| 104 |
+
raise ValueError("unit output escapes deconvolution directory")
|
| 105 |
+
chosen = (out or expected).resolve()
|
| 106 |
+
if chosen != expected:
|
| 107 |
+
raise ValueError(f"--out must be the strict unit output: {expected}")
|
| 108 |
+
return chosen
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def strict_split(s: dict) -> dict:
|
| 112 |
+
return {"reference": list(s["train_sample_ids"]), "mixture": list(s["test_sample_ids"]),
|
| 113 |
+
"train_donors": list(s["train_donor_ids"]), "excluded_samples": list(s["excluded_sample_ids"]),
|
| 114 |
+
"support_sha256": s["sha256"], "run_json_check": "strict_manifest"}
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
def bind(s: dict, out: Path) -> None:
|
| 118 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 119 |
+
p = out / "SUPPORT.json"
|
| 120 |
+
if p.exists() and json.loads(p.read_text()) != {
|
| 121 |
+
"support_sha256": s["sha256"], "reference": s["train_sample_ids"],
|
| 122 |
+
"mixture": s["test_sample_ids"], "excluded": s["excluded_sample_ids"]}:
|
| 123 |
+
raise ValueError("output directory is bound to another strict support")
|
| 124 |
+
p.write_text(json.dumps({"support_sha256": s["sha256"], "reference": s["train_sample_ids"],
|
| 125 |
+
"mixture": s["test_sample_ids"], "excluded": s["excluded_sample_ids"]}, indent=2) + "\n")
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def patched_modules(s: dict, out: Path):
|
| 129 |
+
C = importlib.import_module("common")
|
| 130 |
+
C.PLAN = out
|
| 131 |
+
C.split_rows = lambda ds, kind, idx: strict_split(s) if (ds, kind, idx) == (s["cohort"], "fewshot", 0) else (_ for _ in ()).throw(ValueError("unexpected split"))
|
| 132 |
+
return C
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
def prepare(s: dict, out: Path) -> dict:
|
| 136 |
+
bind(s, out)
|
| 137 |
+
previous = out / "INPUTS.json"
|
| 138 |
+
if previous.exists():
|
| 139 |
+
return require_inputs(s, out)
|
| 140 |
+
method_dirs = [out / "inputs" / s["cohort"] / "fewshot0_full" / "bp",
|
| 141 |
+
out / "cibersortx" / s["cohort"] / SPLIT / "out_fractions",
|
| 142 |
+
out / "cibersortx" / s["cohort"] / SPLIT / "out_hires"]
|
| 143 |
+
if any(d.is_dir() and any(d.iterdir()) for d in method_dirs):
|
| 144 |
+
raise ValueError("existing method output has no prepared-input receipt; refusing to rewrite inputs")
|
| 145 |
+
C = patched_modules(s, out)
|
| 146 |
+
ds = s["cohort"]
|
| 147 |
+
aggregate = OLD / "data" / ds / "aggregates_full.npz"
|
| 148 |
+
if not aggregate.is_file():
|
| 149 |
+
raise FileNotFoundError(f"read-only raw-count aggregate missing: {aggregate}")
|
| 150 |
+
link = out / "data" / ds / "aggregates_full.npz"
|
| 151 |
+
link.parent.mkdir(parents=True, exist_ok=True)
|
| 152 |
+
if link.is_symlink() and link.resolve() != aggregate.resolve():
|
| 153 |
+
raise ValueError("aggregate link points to a different source")
|
| 154 |
+
if link.exists() and (not link.is_symlink() or link.resolve() != aggregate.resolve()):
|
| 155 |
+
raise ValueError("aggregate destination is not the read-only legacy link")
|
| 156 |
+
if not link.exists():
|
| 157 |
+
link.symlink_to(aggregate)
|
| 158 |
+
bp = importlib.import_module("build_split")
|
| 159 |
+
bp.main([ds, "fewshot", "0", "full"])
|
| 160 |
+
cx = importlib.import_module("build_cibersortx_inputs")
|
| 161 |
+
cx.SPLITS = [("fewshot", 0)]
|
| 162 |
+
cx.main([ds])
|
| 163 |
+
bdir = out / "inputs" / ds / "fewshot0_full"
|
| 164 |
+
cdir = out / "cibersortx" / ds / SPLIT
|
| 165 |
+
b = json.loads((bdir / "SPLIT.json").read_text())
|
| 166 |
+
c = json.loads((cdir / "INPUT.json").read_text())
|
| 167 |
+
if b["reference"] != s["train_sample_ids"] or b["mixture"] != s["test_sample_ids"]:
|
| 168 |
+
raise ValueError("BayesPrism input rows differ from strict support")
|
| 169 |
+
if c["reference_samples"] != s["train_sample_ids"] or c["mixture_samples"] != s["test_sample_ids"]:
|
| 170 |
+
raise ValueError("CIBERSORTx input rows differ from strict support")
|
| 171 |
+
rec = {"schema": "pbisc.deconvolution.strict-inputs.v1", "support_sha256": s["sha256"],
|
| 172 |
+
"reference_sample_ids": s["train_sample_ids"], "mixture_sample_ids": s["test_sample_ids"],
|
| 173 |
+
"excluded_sample_ids": s["excluded_sample_ids"], "aggregate_source": str(aggregate),
|
| 174 |
+
"aggregate_sha256": sha(aggregate), "bayesprism_split_sha256": sha(bdir / "SPLIT.json"),
|
| 175 |
+
"cibersortx_input_sha256": sha(cdir / "INPUT.json"), "adapter_sha256": sha(Path(__file__))}
|
| 176 |
+
(out / "INPUTS.json").write_text(json.dumps(rec, indent=2) + "\n")
|
| 177 |
+
return rec
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def require_inputs(s: dict, out: Path) -> dict:
|
| 181 |
+
rec = json.loads((out / "INPUTS.json").read_text())
|
| 182 |
+
if (rec["support_sha256"] != s["sha256"] or rec["reference_sample_ids"] != s["train_sample_ids"]
|
| 183 |
+
or rec["mixture_sample_ids"] != s["test_sample_ids"]
|
| 184 |
+
or rec["excluded_sample_ids"] != s["excluded_sample_ids"]):
|
| 185 |
+
raise ValueError("prepared inputs differ from strict support")
|
| 186 |
+
aggregate = Path(rec["aggregate_source"])
|
| 187 |
+
link = out / "data" / s["cohort"] / "aggregates_full.npz"
|
| 188 |
+
if not link.is_symlink() or link.resolve() != aggregate.resolve():
|
| 189 |
+
raise ValueError("read-only raw-count aggregate link changed after preparation")
|
| 190 |
+
if sha(aggregate) != rec["aggregate_sha256"]:
|
| 191 |
+
raise ValueError("read-only raw-count aggregate changed after preparation")
|
| 192 |
+
if sha(out / "inputs" / s["cohort"] / "fewshot0_full" / "SPLIT.json") != rec["bayesprism_split_sha256"]:
|
| 193 |
+
raise ValueError("BayesPrism split manifest changed after preparation")
|
| 194 |
+
if sha(out / "cibersortx" / s["cohort"] / SPLIT / "INPUT.json") != rec["cibersortx_input_sha256"]:
|
| 195 |
+
raise ValueError("CIBERSORTx input manifest changed after preparation")
|
| 196 |
+
bdir = out / "inputs" / s["cohort"] / "fewshot0_full"
|
| 197 |
+
cdir = out / "cibersortx" / s["cohort"] / SPLIT
|
| 198 |
+
for directory, filename, field in ((bdir, "SPLIT.json", "files"), (cdir, "INPUT.json", "files")):
|
| 199 |
+
entries = json.loads((directory / filename).read_text())[field]
|
| 200 |
+
for name, digest in entries.items():
|
| 201 |
+
if sha(directory / name) != digest:
|
| 202 |
+
raise ValueError(f"prepared input changed: {directory / name}")
|
| 203 |
+
return rec
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def stage_dir(s: dict, out: Path, stage: str) -> Path:
|
| 207 |
+
if stage == "bayesprism":
|
| 208 |
+
return out / "inputs" / s["cohort"] / "fewshot0_full" / "bp"
|
| 209 |
+
if stage in {"fractions", "hires"}:
|
| 210 |
+
return out / "cibersortx" / s["cohort"] / SPLIT / f"out_{stage}"
|
| 211 |
+
raise ValueError(f"unknown method stage {stage}")
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def stage_outputs(s: dict, out: Path, stage: str) -> list[Path]:
|
| 215 |
+
d = stage_dir(s, out, stage)
|
| 216 |
+
if stage == "bayesprism":
|
| 217 |
+
zfiles = sorted(d.glob("Z_type_*.tsv.gz"))
|
| 218 |
+
if not zfiles:
|
| 219 |
+
raise FileNotFoundError("BayesPrism type expression Z files missing")
|
| 220 |
+
files = [d / "theta_final.csv", d / "theta_first.csv", d / "genes_used.txt", *zfiles]
|
| 221 |
+
elif stage == "fractions":
|
| 222 |
+
files = [d / "CIBERSORTx_Adjusted.txt"]
|
| 223 |
+
if len(s["test_sample_ids"]) > 8:
|
| 224 |
+
sig = next(iter(sorted(d.glob("*inferred_refsample.bm.K999.txt"))), None)
|
| 225 |
+
if sig is None:
|
| 226 |
+
raise FileNotFoundError("CIBERSORTx Fractions HiRes signature missing")
|
| 227 |
+
files.extend([sig, d / "CIBERSORTx_cell_type_sourceGEP.txt"])
|
| 228 |
+
else:
|
| 229 |
+
files = []
|
| 230 |
+
for typ in ("T cell", "B cell", "Monocyte", "NK cell"):
|
| 231 |
+
f = next(iter(sorted(d.glob(f"CIBERSORTxHiRes_*_{typ.replace(' ', '')}_Window*.txt"))), None)
|
| 232 |
+
if f is None:
|
| 233 |
+
raise FileNotFoundError(f"CIBERSORTx HiRes required type output missing: {typ}")
|
| 234 |
+
files.append(f)
|
| 235 |
+
files.extend(p for p in sorted(d.glob("CIBERSORTxHiRes_*.txt")) if p not in files)
|
| 236 |
+
if not files or any(not f.is_file() for f in files):
|
| 237 |
+
raise FileNotFoundError(f"{stage} required output missing")
|
| 238 |
+
return files
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def stage_input_hashes(s: dict, out: Path, stage: str) -> dict[str, str]:
|
| 242 |
+
hashes = {"prepared_inputs": sha(out / "INPUTS.json")}
|
| 243 |
+
if stage == "hires":
|
| 244 |
+
d = out / "cibersortx" / s["cohort"] / SPLIT
|
| 245 |
+
files = [d / "out_fractions" / "RECEIPT.json", d / "sigmatrix.txt",
|
| 246 |
+
d / "source_geps.txt", d / "out_hires" / "fractions_results.txt"]
|
| 247 |
+
if any(not f.is_file() for f in files):
|
| 248 |
+
raise FileNotFoundError("HiRes source inputs or Fractions receipt missing")
|
| 249 |
+
hashes.update({str(f.relative_to(d)): sha(f) for f in files})
|
| 250 |
+
return hashes
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def write_stage_receipt(s: dict, out: Path, stage: str) -> None:
|
| 254 |
+
require_inputs(s, out)
|
| 255 |
+
d = stage_dir(s, out, stage)
|
| 256 |
+
if not (d / "DONE").is_file():
|
| 257 |
+
raise FileNotFoundError(f"{stage} completion marker missing")
|
| 258 |
+
files = stage_outputs(s, out, stage)
|
| 259 |
+
receipt = {"schema": "pbisc.deconvolution.method-receipt.v1", "stage": stage,
|
| 260 |
+
"support_sha256": s["sha256"], "input_hashes": stage_input_hashes(s, out, stage),
|
| 261 |
+
"outputs_sha256": {f.name: sha(f) for f in files}}
|
| 262 |
+
(d / "RECEIPT.json").write_text(json.dumps(receipt, indent=2) + "\n")
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def verify_stage_receipt(s: dict, out: Path, stage: str) -> dict:
|
| 266 |
+
require_inputs(s, out)
|
| 267 |
+
d = stage_dir(s, out, stage)
|
| 268 |
+
if not (d / "DONE").is_file():
|
| 269 |
+
raise FileNotFoundError(f"{stage} completion marker missing")
|
| 270 |
+
p = d / "RECEIPT.json"
|
| 271 |
+
if not p.is_file():
|
| 272 |
+
raise ValueError(f"{stage} has DONE without a support/input-bound receipt")
|
| 273 |
+
rec = json.loads(p.read_text())
|
| 274 |
+
expected = {"schema": "pbisc.deconvolution.method-receipt.v1", "stage": stage,
|
| 275 |
+
"support_sha256": s["sha256"], "input_hashes": stage_input_hashes(s, out, stage),
|
| 276 |
+
"outputs_sha256": {f.name: sha(f) for f in stage_outputs(s, out, stage)}}
|
| 277 |
+
if rec != expected:
|
| 278 |
+
raise ValueError(f"{stage} receipt differs from prepared inputs or method outputs")
|
| 279 |
+
return rec
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def method_output_hashes(s: dict, out: Path, method: str) -> dict[str, str]:
|
| 283 |
+
"""Fail closed on extra or missing mixtures; hash every output used by scoring."""
|
| 284 |
+
ds = s["cohort"]
|
| 285 |
+
if method == "bayesprism":
|
| 286 |
+
d = out / "inputs" / ds / "fewshot0_full" / "bp"
|
| 287 |
+
primary = d / "theta_final.csv"
|
| 288 |
+
files = [primary, d / "theta_first.csv", *sorted(d.glob("Z_type_*.tsv.gz"))]
|
| 289 |
+
if not (d / "DONE").is_file():
|
| 290 |
+
raise FileNotFoundError("BayesPrism DONE missing")
|
| 291 |
+
samples = pd.read_csv(primary, index_col=0).index.astype(str).tolist()
|
| 292 |
+
else:
|
| 293 |
+
d = out / "cibersortx" / ds / SPLIT
|
| 294 |
+
primary = d / "out_fractions" / "CIBERSORTx_Adjusted.txt"
|
| 295 |
+
files = [primary, *sorted((d / "out_hires").glob("CIBERSORTxHiRes_*.txt"))]
|
| 296 |
+
if not (d / "out_fractions" / "DONE").is_file():
|
| 297 |
+
raise FileNotFoundError("CIBERSORTx Fractions DONE missing")
|
| 298 |
+
samples = pd.read_csv(primary, sep="\t", index_col=0).index.astype(str).tolist()
|
| 299 |
+
if len(samples) != len(s["test_sample_ids"]) or set(samples) != set(s["test_sample_ids"]):
|
| 300 |
+
raise ValueError(f"{method} output mixtures differ from strict support")
|
| 301 |
+
return {str(p): sha(p) for p in files}
|
| 302 |
+
|
| 303 |
+
|
| 304 |
+
def bayesprism(s: dict, out: Path, threads: int) -> None:
|
| 305 |
+
require_inputs(s, out)
|
| 306 |
+
split = out / "inputs" / s["cohort"] / "fewshot0_full"
|
| 307 |
+
if (split / "bp" / "DONE").is_file():
|
| 308 |
+
verify_stage_receipt(s, out, "bayesprism")
|
| 309 |
+
return
|
| 310 |
+
if (split / "bp").is_dir() and any((split / "bp").iterdir()):
|
| 311 |
+
raise ValueError("partial BayesPrism output exists without a completion receipt")
|
| 312 |
+
subprocess.run(["/home/sj_server_1/miniforge3/bin/Rscript", str(OLD_TOOLS / "run_bp.R"), str(split), str(threads)],
|
| 313 |
+
check=True, env={**os.environ, "CUDA_VISIBLE_DEVICES": ""})
|
| 314 |
+
if not (split / "bp" / "DONE").is_file():
|
| 315 |
+
raise RuntimeError("BayesPrism completion marker missing")
|
| 316 |
+
write_stage_receipt(s, out, "bayesprism")
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def credentials(path: Path) -> tuple[str, str]:
|
| 320 |
+
txt = path.read_text()
|
| 321 |
+
user = re.search(r"(?im)^\s*(?:email|username|user)\s*[:=]\s*(\S+)", txt)
|
| 322 |
+
token = re.search(r"(?im)^\s*token\s*[:=]\s*(\S+)", txt)
|
| 323 |
+
bare = [x.strip() for x in txt.splitlines() if x.strip() and not re.match(r"(?i)^\s*(email|username|user)\s*[:=]", x)]
|
| 324 |
+
value = token.group(1) if token else (bare[0] if len(bare) == 1 and re.fullmatch(r"[0-9a-fA-F]{20,}", bare[0]) else None)
|
| 325 |
+
if not user or not value:
|
| 326 |
+
raise ValueError("CIBERSORTx credential file lacks email or token")
|
| 327 |
+
return user.group(1), value
|
| 328 |
+
|
| 329 |
+
|
| 330 |
+
def cx_argv(image: str, binary: str, work: Path, dest: Path, env_file: Path,
|
| 331 |
+
threads: int, flags: list[str]) -> list[str]:
|
| 332 |
+
"""Credentials expand only inside the container and never enter host argv."""
|
| 333 |
+
script = f'exec ./{binary} --username "$CX_USER" --token "$CX_TOKEN" "$@"'
|
| 334 |
+
return ["docker", "run", "--rm", "--ulimit", "core=0", "--platform", "linux/amd64",
|
| 335 |
+
"--memory=16g", "--memory-swap=16g", f"--cpus={threads}", "--env-file", str(env_file),
|
| 336 |
+
"-v", f"{work}:/src/data:ro", "-v", f"{dest}:/src/outdir", "--entrypoint", "/bin/bash",
|
| 337 |
+
image, "-c", script, "_", *flags]
|
| 338 |
+
|
| 339 |
+
|
| 340 |
+
def run_cx(argv: list[str], log: Path, user: str, token: str) -> None:
|
| 341 |
+
log.parent.mkdir(parents=True, exist_ok=True)
|
| 342 |
+
with log.open("w") as f, subprocess.Popen(argv, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
|
| 343 |
+
text=True, bufsize=1) as p:
|
| 344 |
+
assert p.stdout is not None
|
| 345 |
+
for line in p.stdout:
|
| 346 |
+
line = line.replace(user, "[REDACTED]").replace(token, "[REDACTED]")
|
| 347 |
+
line = re.sub(r"(?i)^(>\[Options\]\s*(?:token|username)[^:]*:).*", r"\1 [REDACTED]", line)
|
| 348 |
+
f.write(line)
|
| 349 |
+
if p.wait() != 0:
|
| 350 |
+
raise RuntimeError(f"CIBERSORTx failed; see redacted log {log}")
|
| 351 |
+
if "Abort!" in log.read_text():
|
| 352 |
+
raise RuntimeError(f"CIBERSORTx aborted; see redacted log {log}")
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def cibersortx(s: dict, out: Path, threads: int) -> dict:
|
| 356 |
+
require_inputs(s, out)
|
| 357 |
+
d = out / "cibersortx" / s["cohort"] / SPLIT
|
| 358 |
+
meta = json.loads((d / "INPUT.json").read_text())
|
| 359 |
+
if meta["mixture_samples"] != s["test_sample_ids"]:
|
| 360 |
+
raise ValueError("CIBERSORTx mixture differs from strict support")
|
| 361 |
+
images = ["cibersortx/fractions:latest"]
|
| 362 |
+
if len(s["test_sample_ids"]) > 8:
|
| 363 |
+
images.append("cibersortx/hires:latest")
|
| 364 |
+
for image in images:
|
| 365 |
+
subprocess.run(["docker", "image", "inspect", image], stdout=subprocess.DEVNULL, check=True)
|
| 366 |
+
user, token = credentials(KEY)
|
| 367 |
+
with tempfile.TemporaryDirectory(prefix="cx_env_", dir=out) as tmp:
|
| 368 |
+
envfile = Path(tmp) / "env"
|
| 369 |
+
envfile.write_text(f"CX_USER={user}\nCX_TOKEN={token}\n")
|
| 370 |
+
envfile.chmod(0o600)
|
| 371 |
+
fd = d / "out_fractions"
|
| 372 |
+
fd.mkdir(exist_ok=True)
|
| 373 |
+
if (fd / "DONE").exists():
|
| 374 |
+
verify_stage_receipt(s, out, "fractions")
|
| 375 |
+
else:
|
| 376 |
+
if any(fd.iterdir()):
|
| 377 |
+
raise ValueError("partial CIBERSORTx Fractions output exists without a completion receipt")
|
| 378 |
+
flags = ["--single_cell", "TRUE", "--refsample", "refsample.txt", "--mixture", "mixture.txt",
|
| 379 |
+
"--rmbatchSmode", "TRUE", "--fraction", "0", "--replicates", "5", "--sampling", "0.5",
|
| 380 |
+
"--G.min", "300", "--G.max", "500", "--q.value", "0.01", "--perm", "0", "--QN", "FALSE", "--verbose", "TRUE"]
|
| 381 |
+
run_cx(cx_argv("cibersortx/fractions:latest", "CIBERSORTxFractions", d, fd, envfile, threads, flags), fd / "run.redacted.log", user, token)
|
| 382 |
+
if not (fd / "CIBERSORTx_Adjusted.txt").is_file():
|
| 383 |
+
raise RuntimeError("CIBERSORTx fractions output missing")
|
| 384 |
+
(fd / "DONE").write_text("ok\n")
|
| 385 |
+
write_stage_receipt(s, out, "fractions")
|
| 386 |
+
status = {"fractions": "complete", "hires": "pending"}
|
| 387 |
+
if len(s["test_sample_ids"]) <= 8:
|
| 388 |
+
status.update(hires="not_estimable", reason="HiRes needs more than eight mixture samples")
|
| 389 |
+
else:
|
| 390 |
+
hd = d / "out_hires"
|
| 391 |
+
hd.mkdir(exist_ok=True)
|
| 392 |
+
if (hd / "DONE").exists():
|
| 393 |
+
verify_stage_receipt(s, out, "hires")
|
| 394 |
+
else:
|
| 395 |
+
if any(hd.iterdir()):
|
| 396 |
+
raise ValueError("partial CIBERSORTx HiRes output exists without a completion receipt")
|
| 397 |
+
sig = next(iter(sorted(fd.glob("*inferred_refsample.bm.K999.txt"))), None)
|
| 398 |
+
src = fd / "CIBERSORTx_cell_type_sourceGEP.txt"
|
| 399 |
+
res = fd / "CIBERSORTx_Adjusted.txt"
|
| 400 |
+
if sig is None or not src.is_file() or not res.is_file():
|
| 401 |
+
raise RuntimeError("CIBERSORTx Fractions signature/source/results missing for HiRes")
|
| 402 |
+
(d / "sigmatrix.txt").write_bytes(sig.read_bytes())
|
| 403 |
+
(d / "source_geps.txt").write_bytes(src.read_bytes())
|
| 404 |
+
fr = pd.read_csv(res, sep="\t", index_col=0)
|
| 405 |
+
fr[[c for c in fr if c not in ("P-value", "Correlation", "RMSE")]].to_csv(hd / "fractions_results.txt", sep="\t")
|
| 406 |
+
flags = ["--mixture", "mixture.txt", "--sigmatrix", "sigmatrix.txt", "--cibresults", "fractions_results.txt",
|
| 407 |
+
"--rmbatchSmode", "TRUE", "--sourceGEPs", "source_geps.txt", "--subsetgenes", "hires_genes.txt", "--threads", str(threads)]
|
| 408 |
+
run_cx(cx_argv("cibersortx/hires:latest", "CIBERSORTxHiRes", d, hd, envfile, threads, flags), hd / "run.redacted.log", user, token)
|
| 409 |
+
if not list(hd.glob("CIBERSORTxHiRes_*.txt")):
|
| 410 |
+
raise RuntimeError("CIBERSORTx HiRes output missing")
|
| 411 |
+
(hd / "DONE").write_text("ok\n")
|
| 412 |
+
write_stage_receipt(s, out, "hires")
|
| 413 |
+
status["hires"] = "complete"
|
| 414 |
+
(d / "STATUS.json").write_text(json.dumps(status, indent=2) + "\n")
|
| 415 |
+
return status
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
CONTRAST_GROUPS = {
|
| 419 |
+
"ye2026_sepsis": ({"adult_sepsis", "ped_sepsis"}, {"adult_HC", "adult_ICU_ctrl", "ped_HC", "ped_ICU_ctrl"}),
|
| 420 |
+
"ji2025_chili": ({"TOL", "FU1"}, {"BC", "AC"}),
|
| 421 |
+
"imperial_eskd": ({"covid_positive"}, {"covid_negative"}),
|
| 422 |
+
"giroux2022": ({"severe"}, {"mild"}),
|
| 423 |
+
}
|
| 424 |
+
|
| 425 |
+
LIMMA_R = r'''suppressPackageStartupMessages(library(limma))
|
| 426 |
+
args <- commandArgs(trailingOnly=TRUE)
|
| 427 |
+
if (length(args) != 4L) stop("usage: limma.R metadata.csv observed.tsv.gz method.tsv.gz outdir")
|
| 428 |
+
meta <- read.csv(args[1], stringsAsFactors=FALSE)
|
| 429 |
+
out <- args[4]
|
| 430 |
+
dir.create(out, recursive=TRUE, showWarnings=FALSE)
|
| 431 |
+
group <- factor(meta$condition, levels=c("control", "case"))
|
| 432 |
+
design <- model.matrix(~group)
|
| 433 |
+
blocked <- any(table(meta$donor_id) > 1L)
|
| 434 |
+
for (side in c("observed", "method")) {
|
| 435 |
+
path <- if (side == "observed") args[2] else args[3]
|
| 436 |
+
tab <- read.delim(gzfile(path), row.names=1, check.names=FALSE)
|
| 437 |
+
X <- as.matrix(tab)
|
| 438 |
+
if (ncol(X) != nrow(meta) || nrow(X) < 3L || any(!is.finite(X))) stop("invalid matched expression matrix")
|
| 439 |
+
if (blocked) {
|
| 440 |
+
dc <- duplicateCorrelation(X, design, block=meta$donor_id)
|
| 441 |
+
if (!is.finite(dc$consensus.correlation)) stop("duplicateCorrelation undefined")
|
| 442 |
+
fit <- lmFit(X, design, block=meta$donor_id, correlation=dc$consensus.correlation)
|
| 443 |
+
} else fit <- lmFit(X, design)
|
| 444 |
+
fit <- eBayes(fit)
|
| 445 |
+
top <- topTable(fit, coef=2L, number=Inf, sort.by="none", adjust.method="BH")
|
| 446 |
+
top$gene_id <- rownames(top)
|
| 447 |
+
write.csv(top[,c("gene_id","logFC","P.Value","adj.P.Val")], file.path(out,paste0(side,"_limma.csv")), row.names=FALSE)
|
| 448 |
+
}
|
| 449 |
+
'''
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
def _log2_cpm(x: np.ndarray) -> np.ndarray:
|
| 453 |
+
x = np.asarray(x, np.float64)
|
| 454 |
+
lib = x.sum(axis=1, keepdims=True)
|
| 455 |
+
if not np.isfinite(x).all() or (x < 0).any() or (lib <= 0).any():
|
| 456 |
+
raise ValueError("nonfinite, negative, or zero-library expression")
|
| 457 |
+
return np.log2(1 + np.divide(x * 1e6, lib, out=np.zeros_like(x), where=lib > 0))
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def _collapse_donor_condition(s: dict, case: np.ndarray, ctrl: np.ndarray,
|
| 461 |
+
obs: np.ndarray, method: np.ndarray, bulk: np.ndarray) -> tuple[pd.DataFrame, np.ndarray, np.ndarray, np.ndarray]:
|
| 462 |
+
"""Each donor contributes once per condition, regardless of visit count."""
|
| 463 |
+
donors = np.asarray(s["test_donor_ids"], dtype=str)
|
| 464 |
+
condition = np.where(case, "case", "control")
|
| 465 |
+
keys = sorted(set(zip(donors, condition)), key=lambda x: (x[0], x[1]))
|
| 466 |
+
O, M, U = (_log2_cpm(x) for x in (obs, method, bulk))
|
| 467 |
+
meta = pd.DataFrame(keys, columns=["donor_id", "condition"])
|
| 468 |
+
out = []
|
| 469 |
+
for x in (O, M, U):
|
| 470 |
+
out.append(np.stack([x[(donors == d) & (condition == c)].mean(axis=0) for d, c in keys]))
|
| 471 |
+
return meta, *out
|
| 472 |
+
|
| 473 |
+
|
| 474 |
+
def _pearson(x: np.ndarray, y: np.ndarray) -> float:
|
| 475 |
+
if x.size < 3 or np.std(x) == 0 or np.std(y) == 0:
|
| 476 |
+
return float("nan")
|
| 477 |
+
return float(np.corrcoef(x, y)[0, 1])
|
| 478 |
+
|
| 479 |
+
|
| 480 |
+
def _partial(x: np.ndarray, y: np.ndarray, bulk: np.ndarray) -> float:
|
| 481 |
+
centered = bulk - bulk.mean()
|
| 482 |
+
den = float(np.dot(centered, centered))
|
| 483 |
+
if den == 0:
|
| 484 |
+
return float("nan")
|
| 485 |
+
residual = lambda z: z - z.mean() - centered * (np.dot(z - z.mean(), centered) / den)
|
| 486 |
+
return _pearson(residual(x), residual(y))
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
def _top50(tab: pd.DataFrame) -> set[str]:
|
| 490 |
+
ok = tab.loc[tab["adj.P.Val"].astype(float) < 0.05].copy()
|
| 491 |
+
return set(ok.assign(abs_lfc=ok.logFC.abs()).sort_values("abs_lfc", ascending=False).head(50).gene_id.astype(str))
|
| 492 |
+
|
| 493 |
+
|
| 494 |
+
def corrected_expression(s: dict, B, v: dict, pred: dict, arm: str, out: Path) -> list[dict]:
|
| 495 |
+
"""Matched donor-aware limma on continuous log2-CPM; never call this voom."""
|
| 496 |
+
F = B.F
|
| 497 |
+
C = importlib.import_module("common")
|
| 498 |
+
ds = s["cohort"]
|
| 499 |
+
cases, controls = CONTRAST_GROUPS[ds]
|
| 500 |
+
groups = np.asarray(v["groups"], str)
|
| 501 |
+
case, ctrl = np.isin(groups, list(cases)), np.isin(groups, list(controls))
|
| 502 |
+
feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
|
| 503 |
+
fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
|
| 504 |
+
sidpos = {x: i for i, x in enumerate(fsid)}
|
| 505 |
+
genepos = {x: i for i, x in enumerate(feat["gene_ids"].astype(str))}
|
| 506 |
+
bulk = np.asarray(feat["bulk_raw"], np.float64)[[sidpos[x] for x in s["test_sample_ids"]]][:,
|
| 507 |
+
[genepos[x] for x in v["score_ids"]]]
|
| 508 |
+
covered = pred["covered_type"].all(0) if "covered_type" in pred else pred["covered"].all(0)
|
| 509 |
+
base_keep = np.asarray(v.get("keep", np.ones(len(v["score_ids"]), bool)), bool)
|
| 510 |
+
rows = []
|
| 511 |
+
for typ in v["deg_types"]:
|
| 512 |
+
gi = F.GATE.index(typ)
|
| 513 |
+
di = v["deg_types"].index(typ)
|
| 514 |
+
mask = base_keep & (covered[gi] if covered.ndim == 2 else covered)
|
| 515 |
+
observed = np.asarray(v["deg_sum"][:, di, :], np.float64)
|
| 516 |
+
method = np.asarray(pred["Z"][:, gi, :], np.float64)
|
| 517 |
+
mask &= observed.sum(axis=0) > 0
|
| 518 |
+
mask &= method.sum(axis=0) > 0
|
| 519 |
+
eligible = (v["deg_n"][:, di] > 0) & (method.sum(axis=1) > 0) & (case | ctrl)
|
| 520 |
+
donors = np.asarray(s["test_donor_ids"])
|
| 521 |
+
ncase = len(set(donors[eligible & case]))
|
| 522 |
+
nctrl = len(set(donors[eligible & ctrl]))
|
| 523 |
+
common = {"arm": arm, "cell_type": typ, "gene_variant": "donor_covered", "statistic": "limma_log2_cpm",
|
| 524 |
+
"n_genes": int(mask.sum()), "n_test_samples": int(eligible.sum()),
|
| 525 |
+
"n_independent_donors": len(set(donors[eligible])), "n_case_samples": int((eligible & case).sum()),
|
| 526 |
+
"n_control_samples": int((eligible & ctrl).sum()), "n_case_donors": ncase, "n_control_donors": nctrl,
|
| 527 |
+
"method_expression_unit": "continuous log2-CPM on matched observed/method profiles",
|
| 528 |
+
"deg_method": "limma lmFit/eBayes on donor-condition means; duplicateCorrelation for repeated donor conditions"}
|
| 529 |
+
metric_names = ("donor_logfc_r", "donor_partial_r_given_bulk", "donor_limma_top50_overlap")
|
| 530 |
+
if ncase < 2 or nctrl < 2 or mask.sum() < 3:
|
| 531 |
+
reason = "fewer than two independent donors per group or fewer than three common expressed genes"
|
| 532 |
+
rows.extend({**common, "metric": m, "value": "", "status": "not_estimable", "reason": reason} for m in metric_names)
|
| 533 |
+
continue
|
| 534 |
+
if any(np.any(x[eligible][:, mask].sum(axis=1) <= 0) for x in (observed, method, bulk)):
|
| 535 |
+
reason = "a matched profile has zero library on common covered genes"
|
| 536 |
+
rows.extend({**common, "metric": m, "value": "", "status": "not_estimable", "reason": reason} for m in metric_names)
|
| 537 |
+
continue
|
| 538 |
+
ss = {**s, "test_donor_ids": donors[eligible].tolist()}
|
| 539 |
+
meta, O, M, U = _collapse_donor_condition(ss, case[eligible], ctrl[eligible],
|
| 540 |
+
observed[eligible][:, mask], method[eligible][:, mask], bulk[eligible][:, mask])
|
| 541 |
+
iscase = meta.condition.eq("case").to_numpy()
|
| 542 |
+
obs_fc = O[iscase].mean(0) - O[~iscase].mean(0)
|
| 543 |
+
method_fc = M[iscase].mean(0) - M[~iscase].mean(0)
|
| 544 |
+
bulk_fc = U[iscase].mean(0) - U[~iscase].mean(0)
|
| 545 |
+
values = {"donor_logfc_r": _pearson(obs_fc, method_fc),
|
| 546 |
+
"donor_partial_r_given_bulk": _partial(obs_fc, method_fc, bulk_fc)}
|
| 547 |
+
work = out / "score" / "continuous_limma" / arm / typ.replace(" ", "_")
|
| 548 |
+
work.mkdir(parents=True, exist_ok=True)
|
| 549 |
+
meta.to_csv(work / "metadata.csv", index=False)
|
| 550 |
+
genes = np.asarray(v["score_ids"])[mask]
|
| 551 |
+
for side, matrix in (("observed", O), ("method", M)):
|
| 552 |
+
pd.DataFrame(matrix.T, index=pd.Index(genes, name="gene_id")).to_csv(work / f"{side}.tsv.gz", sep="\t")
|
| 553 |
+
script = out / "score" / "continuous_limma" / "limma_continuous.R"
|
| 554 |
+
script.write_text(LIMMA_R)
|
| 555 |
+
try:
|
| 556 |
+
run = subprocess.run(["/home/sj_server_1/miniforge3/bin/Rscript", str(script), str(work / "metadata.csv"), str(work / "observed.tsv.gz"),
|
| 557 |
+
str(work / "method.tsv.gz"), str(work)], capture_output=True, text=True)
|
| 558 |
+
except FileNotFoundError:
|
| 559 |
+
run = None
|
| 560 |
+
if run is None or run.returncode:
|
| 561 |
+
(work / "limma_error.txt").write_text(run.stderr[-8000:] if run is not None else "Rscript unavailable\n")
|
| 562 |
+
values["donor_limma_top50_overlap"] = float("nan")
|
| 563 |
+
reason = "limma continuous-expression fit unavailable; see unit limma_error.txt"
|
| 564 |
+
else:
|
| 565 |
+
obs_top = _top50(pd.read_csv(work / "observed_limma.csv"))
|
| 566 |
+
method_top = _top50(pd.read_csv(work / "method_limma.csv"))
|
| 567 |
+
values["donor_limma_top50_overlap"] = len(obs_top & method_top)
|
| 568 |
+
reason = ""
|
| 569 |
+
for m in metric_names:
|
| 570 |
+
value = values[m]
|
| 571 |
+
rows.append({**common, "metric": m, "value": value if np.isfinite(value) else "",
|
| 572 |
+
"status": "ok" if np.isfinite(value) else "pending" if m == "donor_limma_top50_overlap" else "not_estimable",
|
| 573 |
+
"reason": reason if not np.isfinite(value) else ""})
|
| 574 |
+
return rows
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def score_readiness(methods: dict, metrics: dict) -> tuple[str, list[str]]:
|
| 578 |
+
required = ("bayesprism", "cibersortx")
|
| 579 |
+
pending = []
|
| 580 |
+
for name in required:
|
| 581 |
+
record = methods.get(name)
|
| 582 |
+
if record is None or record.get("status") != "complete":
|
| 583 |
+
pending.append(f"{name}: {record.get('reason', 'required method output incomplete') if record else 'required method output missing'}")
|
| 584 |
+
if record and record.get("hires", {}).get("status") == "pending":
|
| 585 |
+
pending.append(f"{name}: {record['hires']['reason']}")
|
| 586 |
+
correction = metrics.get(name, {}).get("corrected_deg", {})
|
| 587 |
+
if record and correction.get("status") not in {"complete", "not_estimable"}:
|
| 588 |
+
pending.append(f"{name}: corrected DEG infrastructure pending")
|
| 589 |
+
return ("pending" if pending else "complete", pending)
|
| 590 |
+
|
| 591 |
+
|
| 592 |
+
def expression_signal(s: dict, B, v: dict, pred: dict, arm: str) -> list[dict]:
|
| 593 |
+
"""Legacy metric family on exact strict test samples; donor-aware DEG is separate."""
|
| 594 |
+
SF, F = B.SF, B.F
|
| 595 |
+
C = importlib.import_module("common")
|
| 596 |
+
ds = s["cohort"]
|
| 597 |
+
groups = np.asarray(v["groups"], dtype=str)
|
| 598 |
+
cases, controls = CONTRAST_GROUPS[ds]
|
| 599 |
+
case, ctrl = np.isin(groups, list(cases)), np.isin(groups, list(controls))
|
| 600 |
+
if not case.any() or not ctrl.any() or np.any(~(case | ctrl)):
|
| 601 |
+
raise ValueError("strict test samples do not match the declared case/control groups")
|
| 602 |
+
feat = np.load(C.FT / "data" / ds / "features.npz", allow_pickle=False)
|
| 603 |
+
fsid = (feat["sample_ids"] if "sample_ids" in feat.files else feat["donor_ids"]).astype(str)
|
| 604 |
+
sidpos = {x: i for i, x in enumerate(fsid)}
|
| 605 |
+
genepos = {x: i for i, x in enumerate(feat["gene_ids"].astype(str))}
|
| 606 |
+
sample_rows = [sidpos[x] for x in s["test_sample_ids"]]
|
| 607 |
+
gene_cols = [genepos[x] for x in v["score_ids"]]
|
| 608 |
+
valid = np.asarray(feat["bulk_valid"])[sample_rows][:, gene_cols].astype(bool)
|
| 609 |
+
if not valid.all():
|
| 610 |
+
raise ValueError("scoring genes must be bulk-valid for every strict mixture")
|
| 611 |
+
bulk = np.asarray(feat["bulk_raw"], dtype=np.float64)[sample_rows][:, gene_cols]
|
| 612 |
+
if not np.isfinite(bulk).all() or (bulk < 0).any():
|
| 613 |
+
raise ValueError("invalid strict bulk counts")
|
| 614 |
+
if ds == "giroux2022":
|
| 615 |
+
exclude = C.FT / "data/sex_linked_genes/sex_linked_genes_exclude.csv"
|
| 616 |
+
v["keep"], _ = SF.gene_exclusion(exclude, v["score_ids"])
|
| 617 |
+
contrast = {"enabled": True, "case": case, "ctrl": ctrl}
|
| 618 |
+
obs_deg = SF.observed_deg(v, contrast)
|
| 619 |
+
n_case_donors = len(set(np.asarray(s["test_donor_ids"])[case]))
|
| 620 |
+
n_control_donors = len(set(np.asarray(s["test_donor_ids"])[ctrl]))
|
| 621 |
+
base = {"arm": arm, "n_test_samples": len(s["test_sample_ids"]),
|
| 622 |
+
"n_independent_donors": len(set(s["test_donor_ids"])),
|
| 623 |
+
"n_case_samples": int(case.sum()), "n_control_samples": int(ctrl.sum()),
|
| 624 |
+
"n_case_donors": n_case_donors, "n_control_donors": n_control_donors,
|
| 625 |
+
"method_expression_unit": "BayesPrism posterior type expression" if arm == "bayesprism" else "CIBERSORTx HiRes imputed GEP",
|
| 626 |
+
"deg_method": "historical Welch top50 on method expression; corrected donor-aware DEG pending"}
|
| 627 |
+
if arm == "cibersortx" and (len(s["test_sample_ids"]) <= 8 or not pred.get("has_z") or not any(pred.get("imputed_genes", {}).values())):
|
| 628 |
+
return [{**base, "cell_type": "all", "metric": metric, "value": "", "status": "not_estimable",
|
| 629 |
+
"gene_variant": "covered", "statistic": "mean_cp10k", "n_genes": 0}
|
| 630 |
+
for metric in ("logfc_r", "partial_r_given_bulk", "top50_deg_overlap")]
|
| 631 |
+
G = len(v["score_ids"])
|
| 632 |
+
covered = pred["covered_type"].all(0) if "covered_type" in pred else pred["covered"].all(0)
|
| 633 |
+
masks = (("zero_filled", None), ("covered", covered))
|
| 634 |
+
rows = []
|
| 635 |
+
for variant, mask in masks:
|
| 636 |
+
contrast_rows, deg, _ = B.bp_metrics(v, pred, bulk, contrast, obs_deg, mask)
|
| 637 |
+
for _, r in contrast_rows.iterrows():
|
| 638 |
+
for metric, key in (("logfc_r", "r_generated"), ("partial_r_given_bulk", "partial_r_generated_given_broadcast")):
|
| 639 |
+
value = float(r[key])
|
| 640 |
+
rows.append({**base, "cell_type": r["celltype"], "metric": metric,
|
| 641 |
+
"value": value if np.isfinite(value) else "", "status": "ok" if np.isfinite(value) else "not_estimable",
|
| 642 |
+
"gene_variant": variant, "statistic": r["statistic"], "n_genes": int(r["n_genes"])})
|
| 643 |
+
for typ, overlap in deg.items():
|
| 644 |
+
n_genes = (int(mask[F.GATE.index(typ)].sum()) if mask is not None and mask.ndim == 2
|
| 645 |
+
else int(mask.sum()) if mask is not None else G)
|
| 646 |
+
rows.append({**base, "cell_type": typ, "metric": "top50_deg_overlap",
|
| 647 |
+
"value": int(overlap) if overlap is not None else "", "status": "ok" if overlap is not None else "not_estimable",
|
| 648 |
+
"gene_variant": variant, "statistic": F.DEG_STATISTIC,
|
| 649 |
+
"n_genes": n_genes})
|
| 650 |
+
return rows
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def score(s: dict, out: Path) -> dict:
|
| 654 |
+
require_inputs(s, out)
|
| 655 |
+
C = patched_modules(s, out)
|
| 656 |
+
B = importlib.import_module("score_bp")
|
| 657 |
+
F = B.F
|
| 658 |
+
ds = s["cohort"]
|
| 659 |
+
ids = np.asarray(s["test_sample_ids"], dtype=str)
|
| 660 |
+
ref, man = F.load_reference(F.CACHE_ROOT / F.DATASETS[ds].name)
|
| 661 |
+
ref["deg"] = F.load_deg_reference(F.CACHE_ROOT / F.DATASETS[ds].name, man, ref)
|
| 662 |
+
if not set(ids) <= set(ref["donors"].astype(str)):
|
| 663 |
+
raise ValueError("strict test IDs absent from observed reference")
|
| 664 |
+
v = B.light_view(ref, ids.tolist())
|
| 665 |
+
rows, signals, metrics, methods = [], [], {}, {}
|
| 666 |
+
for name in ("bayesprism", "cibersortx"):
|
| 667 |
+
hires_pending = False
|
| 668 |
+
try:
|
| 669 |
+
if name == "bayesprism":
|
| 670 |
+
verify_stage_receipt(s, out, "bayesprism")
|
| 671 |
+
else:
|
| 672 |
+
verify_stage_receipt(s, out, "fractions")
|
| 673 |
+
if len(ids) > 8:
|
| 674 |
+
try:
|
| 675 |
+
verify_stage_receipt(s, out, "hires")
|
| 676 |
+
except FileNotFoundError:
|
| 677 |
+
hires_pending = True
|
| 678 |
+
hashes = method_output_hashes(s, out, name)
|
| 679 |
+
pred = B.load_bp(ds, ["fewshot0_full"], ids, v["score_ids"]) if name == "bayesprism" else B.load_cx(ds, [SPLIT], ids, v["score_ids"])
|
| 680 |
+
except (SystemExit, FileNotFoundError) as e:
|
| 681 |
+
methods[name] = {"status": "pending", "reason": str(e)}
|
| 682 |
+
continue
|
| 683 |
+
fractions = B.to_cells(pred["theta"]["final"], pred["size"])
|
| 684 |
+
if not np.isfinite(fractions).all():
|
| 685 |
+
raise ValueError(f"{name} fractions contain nonfinite values")
|
| 686 |
+
l1 = F.IC.l1(fractions, v["comp"])
|
| 687 |
+
metrics[name] = {"composition_l1_mean": float(np.mean(l1)), "n_samples": len(ids),
|
| 688 |
+
"n_independent_donors": len(set(s["test_donor_ids"]))}
|
| 689 |
+
methods[name] = {"status": "pending" if hires_pending else "complete",
|
| 690 |
+
"composition": "cell_fraction_size_corrected", "output_sha256": hashes}
|
| 691 |
+
for i, sample in enumerate(ids):
|
| 692 |
+
for j, typ in enumerate(F.GATE):
|
| 693 |
+
rows.append({"arm": name, "sample_id": sample, "donor_id": s["test_donor_ids"][i],
|
| 694 |
+
"cell_type": typ, "observed": float(v["comp"][i, j]), "predicted": float(fractions[i, j]),
|
| 695 |
+
"composition_l1": float(l1[i])})
|
| 696 |
+
if name == "cibersortx":
|
| 697 |
+
imputed = pred.get("imputed_genes", {})
|
| 698 |
+
if hires_pending:
|
| 699 |
+
methods[name]["hires"] = {"status": "pending", "reason": "required HiRes output missing"}
|
| 700 |
+
elif len(ids) <= 8:
|
| 701 |
+
methods[name]["hires"] = {"status": "not_estimable", "reason": "at most eight mixture samples"}
|
| 702 |
+
elif not pred.get("has_z"):
|
| 703 |
+
methods[name]["hires"] = {"status": "pending", "reason": "required HiRes result files missing"}
|
| 704 |
+
methods[name]["status"] = "pending"
|
| 705 |
+
elif not any(imputed.values()):
|
| 706 |
+
methods[name]["hires"] = {"status": "not_estimable", "reason": "verified HiRes result has zero imputed genes"}
|
| 707 |
+
else:
|
| 708 |
+
methods[name]["hires"] = {"status": "available", "imputed_genes": imputed}
|
| 709 |
+
method_view = v.copy()
|
| 710 |
+
if hires_pending or (name == "cibersortx" and methods[name]["hires"]["status"] == "pending"):
|
| 711 |
+
corrected = [{"arm": name, "cell_type": typ, "metric": metric, "value": "", "status": "pending",
|
| 712 |
+
"reason": "required HiRes output missing", "gene_variant": "donor_covered",
|
| 713 |
+
"statistic": "limma_log2_cpm", "n_genes": 0,
|
| 714 |
+
"n_test_samples": len(ids), "n_independent_donors": len(set(s["test_donor_ids"])),
|
| 715 |
+
"method_expression_unit": "CIBERSORTx HiRes imputed GEP"}
|
| 716 |
+
for typ in v["deg_types"] for metric in
|
| 717 |
+
("donor_logfc_r", "donor_partial_r_given_bulk", "donor_limma_top50_overlap")]
|
| 718 |
+
else:
|
| 719 |
+
signals.extend(expression_signal(s, B, method_view, pred, name))
|
| 720 |
+
corrected = corrected_expression(s, B, method_view, pred, name, out)
|
| 721 |
+
signals.extend(corrected)
|
| 722 |
+
deg_rows = [r for r in corrected if r["metric"] == "donor_limma_top50_overlap"]
|
| 723 |
+
metrics[name]["corrected_deg"] = {"method": "limma on matched donor-condition continuous log2-CPM",
|
| 724 |
+
"status": "pending" if any(r["status"] == "pending" for r in deg_rows)
|
| 725 |
+
else "complete" if any(r["status"] == "ok" for r in deg_rows)
|
| 726 |
+
else "not_estimable",
|
| 727 |
+
"n_types_estimable": sum(r["status"] == "ok" for r in deg_rows),
|
| 728 |
+
"n_types_total": len(deg_rows)}
|
| 729 |
+
status, pending = score_readiness(methods, metrics)
|
| 730 |
+
result = {"schema": "pbisc.deconvolution.strict-score.v1", "cohort": ds, "unit": s["unit"],
|
| 731 |
+
"status": status,
|
| 732 |
+
"pending_reasons": pending, "required_methods": ["bayesprism", "cibersortx"],
|
| 733 |
+
"support_sha256": s["sha256"], "reference_sample_ids": s["train_sample_ids"],
|
| 734 |
+
"mixture_sample_ids": s["test_sample_ids"], "methods": methods, "metrics": metrics,
|
| 735 |
+
"observed_reference_sha256": man["reference_sha256"],
|
| 736 |
+
"source_sha256": {"adapter": sha(Path(__file__)), "score_bp": sha(OLD_TOOLS / "score_bp.py"),
|
| 737 |
+
"common": sha(OLD_TOOLS / "common.py"),
|
| 738 |
+
"legacy_aggregate": json.loads((out / "INPUTS.json").read_text())["aggregate_sha256"],
|
| 739 |
+
"features": sha(C.FT / "data" / ds / "features.npz"),
|
| 740 |
+
"observed_deg_reference": ref["deg"].get("sha256")}}
|
| 741 |
+
p = out / "score"
|
| 742 |
+
p.mkdir(exist_ok=True)
|
| 743 |
+
csvpath = p / "figure4_methods.csv"
|
| 744 |
+
if rows:
|
| 745 |
+
with csvpath.open("w", newline="") as f:
|
| 746 |
+
writer = csv.DictWriter(f, fieldnames=list(rows[0]))
|
| 747 |
+
writer.writeheader(); writer.writerows(rows)
|
| 748 |
+
result["figure4_csv"] = str(csvpath)
|
| 749 |
+
result["figure4_csv_sha256"] = sha(csvpath)
|
| 750 |
+
signalpath = p / "expression_signal.csv"
|
| 751 |
+
with signalpath.open("w", newline="") as f:
|
| 752 |
+
writer = csv.DictWriter(f, fieldnames=list(dict.fromkeys(k for row in signals for k in row)))
|
| 753 |
+
writer.writeheader(); writer.writerows(signals)
|
| 754 |
+
result["signal_csv"] = str(signalpath)
|
| 755 |
+
result["signal_sha256"] = sha(signalpath)
|
| 756 |
+
result["expression_metric_provenance"] = {
|
| 757 |
+
"gene_axis": "cohort scoring genes; Giroux sex-linked genes excluded",
|
| 758 |
+
"reference_expression": "observed sample-level cell-type aggregates on strict test samples",
|
| 759 |
+
"method_expression": "BayesPrism posterior type expression or CIBERSORTx HiRes imputed GEP",
|
| 760 |
+
"bulk": "strict test sample real bulk raw counts from features.npz",
|
| 761 |
+
"sample_unit": "sample; repeated visits retained with explicit donor IDs",
|
| 762 |
+
"top50_deg": "historical Welch benchmark statistic; not corrected patient-level inference",
|
| 763 |
+
"corrected_deg": "limma lmFit/eBayes on matched observed/method continuous log2-CPM donor-condition means; duplicateCorrelation if needed; sensitivity distinct from raw-count edgeR/limma-voom primary",
|
| 764 |
+
"corrected_profile_script_sha256": hashlib.sha256(LIMMA_R.encode()).hexdigest()}
|
| 765 |
+
(p / "SUMMARY.json").write_text(json.dumps(result, indent=2) + "\n")
|
| 766 |
+
if result["status"] == "complete":
|
| 767 |
+
update_figure4(s, result)
|
| 768 |
+
else:
|
| 769 |
+
invalidate_figure4(s, result["pending_reasons"])
|
| 770 |
+
return result
|
| 771 |
+
|
| 772 |
+
|
| 773 |
+
def invalidate_figure4(s: dict, reasons: list[str]) -> None:
|
| 774 |
+
"""Retain a prior mapping as inactive so pending reruns cannot look complete."""
|
| 775 |
+
path = PLAN / "deconvolution" / "deconvolution_manifest.json"
|
| 776 |
+
if not path.is_file():
|
| 777 |
+
return
|
| 778 |
+
data = json.loads(path.read_text())
|
| 779 |
+
rel = f'{s["cohort"]}/disease/{s["unit"].replace("_n5", "")}'
|
| 780 |
+
previous = data.get("units", {}).get(rel)
|
| 781 |
+
if previous is None:
|
| 782 |
+
return
|
| 783 |
+
data.setdefault("inactive_units", {})[rel] = {"previous": previous, "reason": reasons}
|
| 784 |
+
del data["units"][rel]
|
| 785 |
+
with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=".deconv_", delete=False) as f:
|
| 786 |
+
json.dump(data, f, indent=2)
|
| 787 |
+
f.write("\n")
|
| 788 |
+
tmp = Path(f.name)
|
| 789 |
+
tmp.replace(path)
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def update_figure4(s: dict, result: dict) -> None:
|
| 793 |
+
"""Atomic global index consumed by build_results_figures.py --deconvolution-manifest."""
|
| 794 |
+
path = PLAN / "deconvolution" / "deconvolution_manifest.json"
|
| 795 |
+
data = json.loads(path.read_text()) if path.exists() else {"schema": "pbisc.fig4.deconvolution-sources.v1", "units": {}}
|
| 796 |
+
rel = f'{s["cohort"]}/disease/{s["unit"].replace("_n5", "")}'
|
| 797 |
+
data["units"][rel] = {"csv": result["figure4_csv"], "sha256": result["figure4_csv_sha256"],
|
| 798 |
+
"signal_csv": result["signal_csv"], "signal_sha256": result["signal_sha256"],
|
| 799 |
+
"support_sha256": s["sha256"], "reference_sample_ids": s["train_sample_ids"],
|
| 800 |
+
"mixture_sample_ids": s["test_sample_ids"], "methods": result["methods"],
|
| 801 |
+
"metrics": result["metrics"], "source_sha256": result["source_sha256"],
|
| 802 |
+
"expression_metric_provenance": result["expression_metric_provenance"]}
|
| 803 |
+
data.get("inactive_units", {}).pop(rel, None)
|
| 804 |
+
with tempfile.NamedTemporaryFile("w", dir=path.parent, prefix=".deconv_", delete=False) as f:
|
| 805 |
+
json.dump(data, f, indent=2)
|
| 806 |
+
f.write("\n")
|
| 807 |
+
tmp = Path(f.name)
|
| 808 |
+
tmp.replace(path)
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def main(argv: list[str] | None = None) -> int:
|
| 812 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 813 |
+
parser.add_argument("--support-manifest", type=Path, required=True)
|
| 814 |
+
parser.add_argument("--action", choices=("prepare", "bayesprism", "cibersortx", "score", "all"), required=True)
|
| 815 |
+
parser.add_argument("--out", type=Path)
|
| 816 |
+
parser.add_argument("--threads", type=int, default=4)
|
| 817 |
+
a = parser.parse_args(argv)
|
| 818 |
+
if not 1 <= a.threads <= 16:
|
| 819 |
+
parser.error("--threads must be 1..16")
|
| 820 |
+
s = support(a.support_manifest)
|
| 821 |
+
out = unit_out(s, a.out)
|
| 822 |
+
host_preflight()
|
| 823 |
+
if a.action in ("prepare", "all"):
|
| 824 |
+
prepare(s, out)
|
| 825 |
+
if a.action in ("bayesprism", "all"):
|
| 826 |
+
bayesprism(s, out, a.threads)
|
| 827 |
+
if a.action in ("cibersortx", "all"):
|
| 828 |
+
cibersortx(s, out, a.threads)
|
| 829 |
+
if a.action in ("score", "all"):
|
| 830 |
+
result = score(s, out)
|
| 831 |
+
print(json.dumps(result, indent=2))
|
| 832 |
+
if result["status"] != "complete":
|
| 833 |
+
return 1
|
| 834 |
+
return 0
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
if __name__ == "__main__":
|
| 838 |
+
raise SystemExit(main())
|