diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000000000000000000000000000000000000..7b9ac8c1ebe1d259abd2cdd141d1ec0f0ccaf532 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,7 @@ +*.pt filter=lfs diff=lfs merge=lfs -text +*.npz filter=lfs diff=lfs merge=lfs -text +*.safetensors filter=lfs diff=lfs merge=lfs -text +figures/routine_demo.pdf filter=lfs diff=lfs merge=lfs -text +figures/routine_demo.png filter=lfs diff=lfs merge=lfs -text +figures/routine_results.png filter=lfs diff=lfs merge=lfs -text +figures/workflow.png filter=lfs diff=lfs merge=lfs -text diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..04dcfbc4567480393a3393a64a8f40f480afccb8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 The rawct authors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7523939d88cb0c24ba838f01189ec6d3ea5c7ab8 --- /dev/null +++ b/README.md @@ -0,0 +1,138 @@ +--- +library_name: pytorch +language: +- en +tags: +- medical-imaging +- ct +- feature-extraction +- research +--- +# Proj2Rep-CTFM + +**CT projections to image foundation-model representations.** + +Proj2Rep predicts CT-FM embeddings from CT detector measurements, using a measurement denoiser, analytic back-projection and a learned encoder. It produces 512-dimensional slab embeddings and regional features for representation research in chest and abdomen CT. + +Paper: *Proj2Rep: Predicting image foundation-model representations from CT detector measurements*. + +![Proj2Rep measurement-to-embedding workflow](figures/workflow.png) + +**Input:** prepared CT projections and scanner geometry. **Output:** CT-FM feature representations. Denoising is already part of inference. + +## Results at a glance + +Selected **routine-dose, full-view** results from the latest release (RC3): + +- **0.970 chest / 0.959 abdomen Pearson r** in five-fold patient-level cross-validation of the measurement-encoder recipe. +- **0.945 Refined / 0.933 Adaptive r** in the separate 117-patient manufacturer-adaptation evaluation. +- **Refined R² = 0.886**, compared with **0.873** for the unrefined parent, in that adaptation evaluation. + +![Routine-dose results](figures/routine_results.png) + +Left: held-out fold models, 197 patients. Right: manufacturer adaptation, 117 patients. Bars show pointwise 95% whole-patient bootstrap intervals (2,000 resamples), conditional on trained fits. The two panels use distinct evaluation protocols. Chest and pooled abdomen are the primary cross-validation groups; the two abdomen manufacturer rows subdivide the pooled abdomen group. + +## Demo images + +![Scanner reference, before and after denoising, with matched zooms](figures/routine_demo.png) + +Routine-dose chest example at the same anatomical position and display window (−1250 to 450 HU). **Left:** scanner reference. **Middle:** back-projection of the original measurements. **Right:** back-projection after the learned measurement denoiser. The lower row enlarges the cyan-marked regions using the same normalized crop. These are stored preprocessing outputs from the all-development denoiser, shown as a qualitative illustration; the held-out results are reported separately below. Denoising operates on projections before back-projection; the model then encodes the resulting volume into embeddings. + +400 dpi PNGs and vector PDFs: [results](figures/routine_results.pdf) · [routine-dose demo](figures/routine_demo.pdf) · [workflow](figures/workflow.pdf). + +## Choose a model + +| Model | Folder | Intended use | +|---|---|---| +| **Proj2Rep-Universal** | `universal/` | Encoder and denoiser trained on all 197 development scans; general embedding extraction within the supported data conventions | +| **Proj2Rep-Adaptive** | `adaptive/` | GE/Siemens base encoders with chest/abdomen readouts, two support draws, full or 1/2, 1/4, 1/8 views | +| **Proj2Rep-Refined** | `refined/` | GE/Siemens encoders refined with full-view support data; full-view inference only | + +Manufacturer denoisers are in `preprocessing/`. Adaptive uses ten target patients per body region and a readout matched to view stride. Refined uses ten chest and ten abdomen support patients per manufacturer. Draws 0 and 1 are alternative support selections, not independent evaluation cohorts. The CLI retains `--model adapter` for Adaptive compatibility. + +## Cross-validation results + +197 patients (99 chest, 98 abdomen), five folds, routine dose and full views. Results describe the held-out fold models of the Universal training recipe. The released Universal checkpoint was subsequently fitted to all 197 development scans. + +| Group | Patients | Measurement r (95% CI) | Trained image r | Measurement R² | +|---|---:|---|---:|---:| +| Chest | 99 | 0.970 (0.967–0.972) | 0.968 | 0.940 | +| Abdomen | 98 | 0.959 (0.955–0.962) | 0.957 | 0.919 | +| Abdomen GE | 49 | 0.944 (0.938–0.950) | 0.941 | 0.890 | +| Abdomen Siemens | 49 | 0.956 (0.951–0.961) | 0.954 | 0.913 | + +[Routine-dose CV estimates](results/cv.csv). Pearson r measures association with the routine-image CT-FM features; R² additionally reflects scale and offset agreement. + +## Adaptation results + +117 evaluation patients, 3,432 slabs, routine dose and full views. Overall scores equally weight four manufacturer/body-region strata. The two support draws use the same evaluation patients. + +| Group | Patients | Adaptive r (95% CI) | Refined r (95% CI) | Refined R² | +|---|---:|---|---|---:| +| GE chest | 29 | 0.952 (0.946–0.957) | 0.955 (0.949–0.961) | 0.906 | +| GE abdomen | 29 | 0.913 (0.893–0.934) | 0.923 (0.912–0.934) | 0.846 | +| Siemens chest | 30 | 0.938 (0.926–0.950) | 0.958 (0.953–0.964) | 0.913 | +| Siemens abdomen | 29 | 0.931 (0.921–0.938) | 0.942 (0.933–0.948) | 0.881 | + +Overall Adaptive r: **0.933 (0.927–0.940)**; Refined r: **0.945 (0.941–0.948)**. + +Refinement improves R² over the unrefined parent by **0.013** (95% CI 0.012–0.015). This is an absolute R² difference, evaluated on the same patients. + +[Overall estimates](results/overall.csv) · [Manufacturer and region estimates](results/adaptation.csv). + +## Run inference + +Install the download utility with `pip install -U huggingface_hub`. Download the repository: + +```python +from huggingface_hub import snapshot_download +snapshot_download("markjiang1/Proj2Rep-CTFM", local_dir="Proj2Rep-CTFM") +``` + +Install a suitable PyTorch build, then from the downloaded directory: + +```bash +pip install -r requirements.txt +python infer.py --help +python infer.py scan --case /data/C001 --region chest --model adapter --draw 0 --source routine --view-stride 1 --output embeddings.npz +python infer.py scan --case /data/L004 --region abdomen --model refined --draw 1 --source routine --view-stride 1 --output refined.npz +python -m proj2rep encode --cases /data/C001 --work universal --folds -1 --out embeddings/ +``` + +The case directory must follow the projection and geometry conventions; see [input preparation and public API](USAGE.md). Ordinary CT image files alone are insufficient. Universal returns slab positions (`z0`), slab embeddings (`slab`) and regional embeddings (`regions`). Keep `manifest.json` and scanner conventions with the models; they are required runtime inputs. + + + +## Smaller downloads + +For **Universal-only embedding extraction**, download about **321 MB** of runtime files instead of the full **2.24 GB** repository: + +```bash +hf download markjiang1/Proj2Rep-CTFM --local-dir Proj2Rep-Universal \ + --include 'config.json' 'universal/*' 'proj2rep/*' 'requirements.txt' 'README.md' 'USAGE.md' 'LICENSE' +cd Proj2Rep-Universal +pip install -r requirements.txt +python -m proj2rep encode --cases /data/C001 --work universal --folds -1 --out embeddings/ +``` + +Use the complete package for Adaptive or Refined. Download sizes describe the current files and exclude installed dependencies. Keep `config.json` in filtered downloads so normal Hub download counting remains available. Add `--revision ` to pin a reproducible version. + +## Current release + +This repository distributes the latest release (RC3). Earlier packaging snapshots contained identical weights and have been removed. Universal, Adaptive and Refined are distinct functional configurations within this single release. + +## Evaluation scope + +This card presents selected routine-dose, full-view CT-FM embedding-agreement results for chest and abdomen from GE and Siemens scanners. Clinical outcome validation is outside this evaluation. Pearson correlation was added post hoc using saved predictions. + +Code: [MIT license](LICENSE). Upstream terms: [CT-FM model card](https://huggingface.co/project-lighter/ct_fm_feature_extractor). + +## Download the complete model package + +```bash +hf download markjiang1/Proj2Rep-CTFM --local-dir Proj2Rep-CTFM +``` + +This downloads the model files together with `config.json`, the package metadata used by Hugging Face's native download counter. Use the inference instructions above to load the model. The package metadata does not replace the runtime model configuration. + +Download totals appear on this repository's model page. Hugging Face counts requests for designated files; downloading individual weight files without the configuration may not register. Counts represent Hub requests, not unique users. See [Hugging Face download statistics](https://huggingface.co/docs/hub/models-download-stats). diff --git a/USAGE.md b/USAGE.md new file mode 100644 index 0000000000000000000000000000000000000000..e8aa030fe79ad72585fc60c4859880c691eb4ea4 --- /dev/null +++ b/USAGE.md @@ -0,0 +1,277 @@ +# proj2rep + +**Read CT scans straight from the scanner's detector measurements, in the feature space of a CT +image foundation model.** + +`proj2rep` trains an encoder to predict the CT-FM features of a routine-dose scanner image +from helical CT projection measurements. In five-fold patient-held-out testing, image-trained +probes localized lung nodules and liver lesions in regional measurement features at routine +and supplied low dose. [Regional localization results](#regional-lesion-localization). + +``` +measurements ─► denoiser ─► back-projection ─► encoder ─► embeddings (512 per slab + 4×4 regional grid) + ▲ +routine-dose image ─► CT-FM (frozen) ─── target ──┘ +``` + +--- + +## 1. Install + +You need Python 3.10+, an NVIDIA GPU and PyTorch with CUDA ([pytorch.org](https://pytorch.org)). + +```bash +git clone proj2rep && cd proj2rep +pip install -r requirements.txt +python -m pytest tests -q # quick check, runs on CPU +``` + +## 2. Download + +**Model weights (teacher).** Download `model.safetensors` from +[project-lighter/ct_fm_feature_extractor](https://huggingface.co/project-lighter/ct_fm_feature_extractor) +and save it, e.g. as `weights/ct_fm.safetensors`. + +**Data.** You need CT scans with their raw projection data in **DICOM-CT-PD** format, plus the +reconstructed images of the same scans. A public example is the *LDCT and Projection Data* +collection on The Cancer Imaging Archive (TCIA), which provides routine-dose and simulated +reduced-dose projections with matching images for chest, abdomen and head scans. Download it with +the TCIA tools (NBIA Data Retriever or `idc-index`). Any scanner exporting DICOM-CT-PD works. + +## 3. Prepare the data + +Convert each scan once into a folder with a few `.npy` / `.json` files (layout below). Use any +DICOM reader (e.g. `pydicom`). Per scan: + +1. **Projections → `proj_full.npy`.** Read every DICOM-CT-PD projection file in acquisition order. + Each file is one view: a `rows × columns` detector array. Convert pixels to line integrals with + `RescaleSlope` / `RescaleIntercept` and stack them to `(views, rows, columns)`, float16. + Averaging consecutive views in groups of 2–4 keeps files small and works well. +2. **Per-view positions → `views.npz`.** From each view: gantry angle (7031,1001) → `angle_rad`, + table position (7031,1002) → `z_mm`, and source distance (7031,1003) plus the flying focal + spot offset (7033,100D) → `source_isocenter_mm`. Average them the same way if you averaged views. +3. **Scanner geometry → `geometry.json`** (fields in the table below). From the first view: + detector spacing (7029,1002 / 7029,1006), detector size (7029,1010 / 7029,1011), + source-detector distance (7031,1031), central element (7031,1033), water attenuation + (7041,1001), plus `Manufacturer` and `PatientPosition`. Set `stored_views_per_rotation` to the + views per rotation (7033,1013) divided by your averaging factor. +4. **Images → `image_full.npy` + `image.json`.** The reconstructed routine-dose series as `(slices, + rows, columns)` int16 HU, sorted by table position, with slice positions and pixel grid in + `image.json`. +5. **Low dose (optional) → `proj_low.npy`.** If you have a reduced-dose version of the same scan + (e.g. the simulated reduced-dose projections in the TCIA collection), convert it exactly like + step 1. It must have the same views as `proj_full`. Its reconstructed image can go in + `image_low.npy` for comparison. +6. **Cohort table → `cases.csv`** with one row per scan: `case_id` (the folder name), `region` + (e.g. `chest`), and `low_dose_fraction` (e.g. `0.25`) if you have `proj_low`. + +That is all; the pipeline does everything else. + +## 4. Train (cross-validation) + +One command runs the full pipeline with 5-fold cross-validation on 8 GPUs: + +```bash +scripts/run_cv.sh /path/to/data /path/to/work weights/ct_fm.safetensors 8 5 +# DATA_ROOT WORK_DIR TEACHER GPUS FOLDS +``` + +What it runs for every fold: + +| step | what it does | +|---|---| +| `calibrate` | learns each scanner vendor's geometry convention and draws the folds (once) | +| `train-denoiser` | trains the measurement denoiser | +| `bank` | builds denoised back-projections at several dose levels and view counts | +| `train-encoder` | trains the encoder to match CT-FM | +| `evaluate` | embeds the held-out scans | +| `stress` | tests the held-out scans at lower dose and fewer views | +| `report` | summarises all folds (at the end) | + +You can also run steps one by one, on any number of GPUs: + +```bash +torchrun --standalone --nproc_per_node 8 -m proj2rep train-encoder --data DATA --work WORK --fold 0 --teacher weights/ct_fm.safetensors +python -m proj2rep report --data DATA --work WORK # single process works too +``` + +`bank`, `evaluate` and `stress` split the scans across processes and are mostly CPU-bound, so they +run faster with several processes per GPU: `--nproc_per_node 24` on 8 GPUs puts three on each +(about 10 GB of GPU memory per process). With the script: `PROCS=24 scripts/run_cv.sh ...`. + +**Final model.** Cross-validation tells you how well the method works on your data. For the model +you deploy, train on every scan with `--fold -1`: + +```bash +RUN="torchrun --standalone --nproc_per_node 8 -m proj2rep" +$RUN train-denoiser --data DATA --work WORK --fold -1 +$RUN bank --data DATA --work WORK --fold -1 +$RUN train-encoder --data DATA --work WORK --fold -1 --teacher weights/ct_fm.safetensors +``` + +If a run is interrupted, just start it again: finished steps are skipped and training continues +from its last checkpoint. Change settings by passing options, e.g. +`ENCODER_ARGS="--steps 12000" scripts/run_cv.sh ...` (all options: `python -m proj2rep --help`). + +## 5. Results + +Everything is written to the work directory: + +``` +WORK/report/agreement.csv how well the encoder matches CT-FM on held-out scans, per region and scanner +WORK/report/stress.csv the same at each dose level and view count, raw route vs. reconstruct-then-encode +WORK/encoder/fold.pt trained encoders WORK/denoiser/fold.pt trained denoisers +WORK/eval/, WORK/stress/ held-out embeddings per scan +WORK/logs/ logs of every step +``` + +The agreement score is R²: the share of the CT-FM embedding's variance that the encoder +reproduces (1 = identical), with 95% confidence intervals. + +## 6. Pretrained model + +A pretrained model is provided with the releases of this repository (`proj2rep_weights.zip`). It was +trained on the 197 chest and abdomen scans (Siemens and GE) of the TCIA *LDCT and Projection Data* +collection. Unpack it and use the folder as the work directory when encoding: + +```bash +unzip proj2rep_weights.zip -d weights/ # weights/proj2rep_weights/{encoder,denoiser}/fold-1.pt, convention.json +python -m proj2rep encode --cases /path/to/scanA --work weights/proj2rep_weights --folds -1 --out embeddings/ +``` + +Selected routine-dose evaluation results are in the [model card](README.md#cross-validation-results). + +## 7. Encode new scans + +Prepare the new scans the same way (images are not needed — only `image.json` to set the output +grid), then: + +```bash +python -m proj2rep encode --cases /path/to/scanA /path/to/scanB --work WORK --folds -1 --out embeddings/ +``` + +`--folds -1` uses the final model; `--folds 0 1 2 3 4` averages the cross-validation models +instead. Each `embeddings/.npz` contains `z0` (slab positions, every 12 mm), `slab` +`(n, 512)` and `regions` `(n, 16, 512)`. Use them anywhere you would use CT-FM +image embeddings. + +### Regional lesion localization + +Generate an 8 × 8 grid for each slab, then apply the packaged lung nodule or liver lesion probe. For example, from the release directory run + +```bash +python -m proj2rep encode --cases /path/to/scanA --work WORK --folds -1 --grid 8 --out embeddings/ +python -m proj2rep lesion --task nodule --input embeddings/scanA.npz --out scanA_nodules.npz +``` + +Use `--task liver` for abdominal scans. Each output contains `scores` with shape +`(slabs, 8, 8)` and the matching slab positions `z0`. Rows and columns follow the +regional encoder grid. The class-balanced logistic scores rank regions for a +research localization task and have no calibrated diagnostic threshold. + +Both probes use the 512 local CT-FM features of each region. The packaged +weights were refitted on all routine-dose training images after five-fold +patient-held-out evaluation. Comparisons in the paper use the held-out +predictions. The 4 × 4 and 8 × 8 grids have different region labels and class +prevalence. + +## Feature offsets for a new manufacturer + +A frozen measurement encoder can be calibrated with paired routine-dose scans. Fit one offset per encoder, manufacturer and body region using scanner-image and measurement embeddings of the same slab centres. Each input directory holds one NPZ per examination with matching filenames, physical slab centres in `z0` and 512-feature embeddings in `slab`. The output contains corrected global slab embeddings. + +```bash +python -m proj2rep feature-offset fit measurement/ reference/ offset.npz +python -m proj2rep feature-offset apply offset.npz evaluation_scan.npz corrected_slab.npz +``` + +## Reference + +### Data layout + +``` +DATA_ROOT/ + cases.csv + / + geometry.json scanner geometry + views.npz angle_rad (V,), z_mm (V,) [, source_isocenter_mm (V,)] + proj_full.npy (V, rows, columns) line integrals, routine dose + proj_low.npy optional, reduced dose, same shape + image.json image grid + image_full.npy (S, H, W) int16 HU, routine-dose image + image_low.npy optional, reduced-dose image +``` + +**cases.csv** + +| column | needed | meaning | +|---|---|---| +| `case_id` | yes | folder name | +| `region` | recommended | any label (`chest`, `abdomen`, `head`, ...) | +| `low_dose_fraction` | with `proj_low` | dose of `proj_low` relative to routine, e.g. `0.25` | +| `manufacturer` | no | taken from `geometry.json` if empty | +| `fold` | no | your own folds; otherwise drawn by region and scanner and saved to `WORK/folds.csv` | +| `exclude` | no | `1` to leave a scan out | + +Extra columns are kept and ignored. + +**geometry.json** + +| field | meaning | +|---|---| +| `manufacturer` | `SIEMENS`, `GE`, `PHILIPS`, `CANON`, ... | +| `source_detector_mm` | source-to-detector distance | +| `source_isocenter_mm` | source-to-isocentre distance (if not per view in `views.npz`) | +| `column_spacing_mm`, `row_spacing_mm` | detector element spacing | +| `central_element` | `[column, row]` of the central ray, 1-based | +| `detector_rows`, `detector_columns` | detector size | +| `water_mu_per_mm` | water attenuation, for HU | +| `stored_views_per_rotation` | views per rotation as stored in `proj_full.npy` | +| `patient_position` | `FFS`, `HFS`, ... | +| `low_dose_fraction` | optional, used if `cases.csv` has none | + +**image.json**: `z_mm` (slice positions), `pixel_spacing_mm` `[row, column]`, `origin_mm` `[x, y]`, +`thickness_mm`, `rows`, `columns`, and optionally `rotation_center_mm` `[x, y]` (default `[0, 0]`). + +### Main options + +| step | option | default | meaning | +|---|---|---|---| +| calibrate | `--folds` | 5 | number of folds | +| train-denoiser | `--steps` / `--batch` / `--lr` | 8000 / 8 / 3e-4 | `--batch` is split across GPUs | +| | `--min-dose` | 0.02 | lowest simulated dose | +| | `--views` | 1 1 2 4 8 | view-thinning factors used in training | +| bank | `--levels` | full low | dose levels to build (`min` adds a lower one) | +| | `--views` | 1 2 4 8 | view counts to build (every k-th view) | +| train-encoder | `--steps` / `--batch` / `--lr` | 16000 / 16 / 1e-4 | `--batch` is split across GPUs | +| | `--views` | 1 2 4 8 | view counts used in training | +| | `--max-dose-level` | 1 | 1 = down to `proj_low`; 2 = down to the `min` level | +| | `--clean` | 0.15 | share of routine-dose samples | +| | `--snap-z` | 0.5 | share of training slabs placed with an edge exactly on a slice, as evaluation slabs are | +| bank, train-encoder | `--no-thin` | — | `REGION:MANUFACTURER` groups kept at all views | + +### Adding more data + +New scanners, body regions and sites need no code changes — add folders and rows to `cases.csv`. +To keep an existing split, copy the `fold` column from `WORK/folds.csv` into `cases.csv` and give +the new scans a fold. New vendors are calibrated automatically from a few scans with images. + +A model trained on one manufacturer reproduces the anatomy of another manufacturer's scans but in +the image style of the one it was trained on, so agreement drops on a manufacturer it has never +seen. About ten scans per body region from the new manufacturer, added to training, restore most of +it. Train on every manufacturer you plan to encode. + +### Code + +``` +proj2rep/data.py cases, folds, slabs +proj2rep/geometry.py back-projection and vendor calibration +proj2rep/models.py denoiser, CT-FM teacher, encoder +proj2rep/train_denoiser.py proj2rep/bank.py proj2rep/train_encoder.py +proj2rep/evaluate.py proj2rep/stress.py proj2rep/report.py proj2rep/encode.py +scripts/run_cv.sh full pipeline +tests/ synthetic-data tests +``` + +## License + +MIT diff --git a/adaptive/README.md b/adaptive/README.md new file mode 100644 index 0000000000000000000000000000000000000000..643c3fc6339b233465cd74fa19012910bbabd3ba --- /dev/null +++ b/adaptive/README.md @@ -0,0 +1,18 @@ +# Proj2Rep-Adaptive + +Current release: RC3. + +## Selected routine-dose, full-view results + +Manufacturer-adaptation evaluation on 117 patients; both support draws use the same evaluation patients. + +| Group | Patients | Adaptive r (95% CI) | Refined r (95% CI) | Refined R² | +|---|---:|---|---|---:| +| GE chest | 29 | 0.952 (0.946–0.957) | 0.955 (0.949–0.961) | 0.906 | +| GE abdomen | 29 | 0.913 (0.893–0.934) | 0.923 (0.912–0.934) | 0.846 | +| Siemens chest | 30 | 0.938 (0.926–0.950) | 0.958 (0.953–0.964) | 0.913 | +| Siemens abdomen | 29 | 0.931 (0.921–0.938) | 0.942 (0.933–0.948) | 0.881 | + +![Routine-dose results](../figures/routine_results.png) + +See the [main model card](../README.md) for confidence intervals, model selection, input preparation and inference commands. diff --git a/adaptive/ge/abdomen_draw0.npz b/adaptive/ge/abdomen_draw0.npz new file mode 100644 index 0000000000000000000000000000000000000000..207a72c3961d96bd2f267d322f99dd29cd8e6a6b --- /dev/null +++ b/adaptive/ge/abdomen_draw0.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5f02e1f964415424d185242a421e39caf2e828476dac95f82d8eb1fb667ed454 +size 3942256 diff --git a/adaptive/ge/abdomen_draw1.npz b/adaptive/ge/abdomen_draw1.npz new file mode 100644 index 0000000000000000000000000000000000000000..b0c1f334574469991009467834bb493b870e367d --- /dev/null +++ b/adaptive/ge/abdomen_draw1.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7c5067d65de9c33ba5f0ba907de355fc05db0db57297e495d5c5564966ad9066 +size 3943029 diff --git a/adaptive/ge/base.pt b/adaptive/ge/base.pt new file mode 100644 index 0000000000000000000000000000000000000000..74108dddb0dc07d03b5aaefab553ff2513dc2361 --- /dev/null +++ b/adaptive/ge/base.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54b532b56b90af0f3a30f648cb8d8b231c926fab5b8d47d5803f783687c43f64 +size 311152534 diff --git a/adaptive/ge/chest_draw0.npz b/adaptive/ge/chest_draw0.npz new file mode 100644 index 0000000000000000000000000000000000000000..3faa24ca799e89ba555a5174f28db4540512b109 --- /dev/null +++ b/adaptive/ge/chest_draw0.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:d6f90c33f3b93480f210a1e442018be0bbeba993d045bd534e09ea0b295a54ec +size 3950959 diff --git a/adaptive/ge/chest_draw1.npz b/adaptive/ge/chest_draw1.npz new file mode 100644 index 0000000000000000000000000000000000000000..36e8418bf43be0e44f1be4302e1d2b4999043f86 --- /dev/null +++ b/adaptive/ge/chest_draw1.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b1daa48d0514468922fc3c41a842501bb2a90a3ae0ad2ecb060073a3faebeab1 +size 3947849 diff --git a/adaptive/siemens/abdomen_draw0.npz b/adaptive/siemens/abdomen_draw0.npz new file mode 100644 index 0000000000000000000000000000000000000000..2bdf582ef63f0a33f165996e9fef80a3dfdd15d3 --- /dev/null +++ b/adaptive/siemens/abdomen_draw0.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:51974a4f0faecfffaa720d64bce3fa3fd8a41c60146d4637eb26be954d797f30 +size 3935703 diff --git a/adaptive/siemens/abdomen_draw1.npz b/adaptive/siemens/abdomen_draw1.npz new file mode 100644 index 0000000000000000000000000000000000000000..4b40a2e15255a81f90e564dde82d671136e3ac59 --- /dev/null +++ b/adaptive/siemens/abdomen_draw1.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:bdcd7efccfa4199375b52021ae76de1c85ddd7474ced937cfbab2d0e33f8afea +size 3927879 diff --git a/adaptive/siemens/base.pt b/adaptive/siemens/base.pt new file mode 100644 index 0000000000000000000000000000000000000000..b8aa9f3751a853c48530a730f4f66396b993f5d9 --- /dev/null +++ b/adaptive/siemens/base.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:316b5812e22e99bcbeb4b3227b0edb13b33c9d11358174303337a1444b824a1c +size 311152534 diff --git a/adaptive/siemens/chest_draw0.npz b/adaptive/siemens/chest_draw0.npz new file mode 100644 index 0000000000000000000000000000000000000000..ce47d6574d5d16145dd06cf1551c9b13c28afebe --- /dev/null +++ b/adaptive/siemens/chest_draw0.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:1a3068bc042874e7e176c4db0bfc901ad8e8f13ee396096b1a111eaff50f86a5 +size 3945065 diff --git a/adaptive/siemens/chest_draw1.npz b/adaptive/siemens/chest_draw1.npz new file mode 100644 index 0000000000000000000000000000000000000000..c6ada3d877d1203e70bd86a20c87659f186dd8c9 --- /dev/null +++ b/adaptive/siemens/chest_draw1.npz @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ffe8ec7cb85cfbe3fc6ebfbcf6e2efab026a6e273a4a6d692a6ce790094fc912 +size 3943373 diff --git a/config.json b/config.json new file mode 100644 index 0000000000000000000000000000000000000000..b716ae50a63226e180d4743aed2636844d0781e5 --- /dev/null +++ b/config.json @@ -0,0 +1,39 @@ +{ + "package_name": "Proj2Rep-CTFM", + "repository_id": "markjiang1/Proj2Rep-CTFM", + "weight_files": [ + "adaptive/ge/abdomen_draw0.npz", + "adaptive/ge/abdomen_draw1.npz", + "adaptive/ge/base.pt", + "adaptive/ge/chest_draw0.npz", + "adaptive/ge/chest_draw1.npz", + "adaptive/siemens/abdomen_draw0.npz", + "adaptive/siemens/abdomen_draw1.npz", + "adaptive/siemens/base.pt", + "adaptive/siemens/chest_draw0.npz", + "adaptive/siemens/chest_draw1.npz", + "preprocessing/ge/denoiser.pt", + "preprocessing/siemens/denoiser.pt", + "refined/ge/draw0.pt", + "refined/ge/draw1.pt", + "refined/siemens/draw0.pt", + "refined/siemens/draw1.pt", + "universal/denoiser/fold-1.pt", + "universal/encoder/fold-1.pt" + ], + "configuration_scope": "Repository package metadata. Use the documented inference entry point and runtime configuration to load the model.", + "model_family": "Proj2Rep", + "variants": [ + "Universal", + "Adaptive", + "Refined" + ], + "embedding_dim": 512, + "runtime_manifest": "manifest.json", + "scanner_conventions": "convention.json", + "minimum_python_version": "3.11", + "entry_points": { + "universal": "python -m proj2rep encode", + "adaptive_and_refined": "python infer.py scan" + } +} diff --git a/convention.json b/convention.json new file mode 100644 index 0000000000000000000000000000000000000000..a9bef110e1f4546d91de1b3892d336e2a7c79280 --- /dev/null +++ b/convention.json @@ -0,0 +1,14 @@ +{ + "GE": [ + 1, + 2, + 1, + -1 + ], + "SIEMENS": [ + 1, + 2, + 1, + 1 + ] +} diff --git a/figures/routine_demo.pdf b/figures/routine_demo.pdf new file mode 100644 index 0000000000000000000000000000000000000000..3929bee28fcaa323f124a1c973f0d008b51a68c1 --- /dev/null +++ b/figures/routine_demo.pdf @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:b8b52581d964b55df0a0b31210043d0a7c0456aca54036b700b2605a75dea15c +size 345921 diff --git a/figures/routine_demo.png b/figures/routine_demo.png new file mode 100644 index 0000000000000000000000000000000000000000..b81c27c82488ea317bd2a12a8d6c5ad5c01d7194 --- /dev/null +++ b/figures/routine_demo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0f6773b06cab97f3642c1327c34f15fb9cc72cb67264b9ea3dba8905dc33ddad +size 1020030 diff --git a/figures/routine_results.pdf b/figures/routine_results.pdf new file mode 100644 index 0000000000000000000000000000000000000000..36204f99e5922db82037a02df140ae780cffefc3 Binary files /dev/null and b/figures/routine_results.pdf differ diff --git a/figures/routine_results.png b/figures/routine_results.png new file mode 100644 index 0000000000000000000000000000000000000000..2c2cdc391038034af5f458bdd830207a88b9532d --- /dev/null +++ b/figures/routine_results.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:e8a04f9e4d2ebdb6aab02082765df8f7283986e1689b09414ccbcef0047e5487 +size 195347 diff --git a/figures/workflow.pdf b/figures/workflow.pdf new file mode 100644 index 0000000000000000000000000000000000000000..8e36a74d7fded444fa021b2acadba645acb0bc9e Binary files /dev/null and b/figures/workflow.pdf differ diff --git a/figures/workflow.png b/figures/workflow.png new file mode 100644 index 0000000000000000000000000000000000000000..b0f6c158f78220d22b5e1ff33dfaf7bfb67eadbe --- /dev/null +++ b/figures/workflow.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:61c7dca43b483de82e2716c088eebda0c88e2b315079f5564c59e8dfc5e21c89 +size 124557 diff --git a/infer.py b/infer.py new file mode 100644 index 0000000000000000000000000000000000000000..656a8968172e8d38d82a1d9f070bda2ec196ecd6 --- /dev/null +++ b/infer.py @@ -0,0 +1,226 @@ +"""Proj2Rep: infer one draw of a CT projection encoder or apply its readout to archived base features.""" + +import argparse +import hashlib +import json +import os +import tempfile +from pathlib import Path + +import numpy as np +from readout import predict + + +class Bundle: + def __init__(self, path): + self.path = path + self.manifest = json.loads((path / "manifest.json").read_text()) + + def checked(self, name): + path = self.path / name + with path.open("rb") as source: + digest = hashlib.file_digest(source, "sha256").hexdigest() + if digest != self.manifest["sha256"][name]: + raise ValueError(f"asset digest mismatch: {name}") + return path + + +def saved_features(args, bundle): + assets = bundle.manifest["manufacturers"][args.manufacturer] + expected = bundle.manifest["sha256"][assets["base"]] + with np.load(args.input, allow_pickle=False) as data: + if "patient" in data and len(np.unique(data["patient"])) != 1: + raise ValueError("supply one patient per input archive") + if "region" in data and str(data["region"].item()) != args.region: + raise ValueError("archived region differs from requested region") + if ( + args.key in ("slab", "base_slab") + and "model" in data + and args.key != "base_slab" + ): + raise ValueError("use base_slab from adapter output to apply another draw") + internal = str(data["base_sha256"].item()) if "base_sha256" in data else None + if internal and args.base_sha256 and internal != args.base_sha256: + raise ValueError("conflicting input and command-line base digests") + if (internal or args.base_sha256) != expected: + raise ValueError( + "specify the SHA-256 of the matching unadapted base encoder" + ) + if ( + "view_stride" in data + and int(data["view_stride"].item()) != args.view_stride + ): + raise ValueError("input acquisition stride differs from requested stride") + if ( + args.key.startswith("raw_views_") + and args.key != f"raw_views_{args.view_stride}" + ): + raise ValueError("archive key and requested angular stride differ") + if ( + args.key.startswith("raw_dose") or args.key in ("raw_full", "raw_low") + ) and args.view_stride != 1: + raise ValueError("dose arrays use full angular sampling") + x, z = data[args.key], data["z0"] + return x, z + + +def infer_scan(args, bundle): + import torch + from proj2rep.data import Case, slab_rows, to_input + from proj2rep.geometry import Conventions, Geometry, reconstruct, sparse + from proj2rep.models import Denoiser, Encoder, denoise_scan + + if args.view_stride > 1 and (args.source != "routine" or args.model != "adapter"): + raise ValueError( + "sparse-view inference requires routine projections and the adapter model" + ) + if args.source == "routine-bank" and args.model != "adapter": + raise ValueError( + "refined routine inference already uses the rounded bank convention" + ) + case = Case(args.case.parent, args.case.name) + vendor = case.manufacturer.upper() + args.manufacturer = next( + ( + name + for name in bundle.manifest["manufacturers"] + if vendor.startswith(name.upper()) + ), + None, + ) + if args.manufacturer is None: + raise ValueError(f"no packaged model for {vendor}") + assets = bundle.manifest["manufacturers"][args.manufacturer] + encoder_name = ( + assets["base"] if args.model == "adapter" else assets["refined"][str(args.draw)] + ) + device = torch.device(args.device) + if device.type != "cuda" or not torch.cuda.is_available(): + raise ValueError("scan inference requires a CUDA device supporting bfloat16") + with torch.cuda.device(device): + if not torch.cuda.is_bf16_supported(): + raise ValueError("scan inference requires CUDA bfloat16 support") + + def load(module, name): + module.load_state_dict( + torch.load(bundle.checked(name), map_location="cpu", weights_only=True) + ) + return module.to(device).eval().requires_grad_(False) + + with torch.inference_mode(): + dn = load(Denoiser(), assets["denoiser"]) + enc = load(Encoder(), encoder_name).to(memory_format=torch.channels_last_3d) + geo = Geometry(case) + zs, z = geo.image_z[geo.valid()], case.grid() + if not len(z): + raise ValueError("scan covers no complete 36-mm slab") + if args.slab_index is not None: + z = z[args.slab_index] + convention = Conventions(bundle.checked("convention.json"))(geo) + views = case.array("proj_low" if args.source == "supplied" else "proj_full") + if views.shape != (len(geo.angle), geo.rows, geo.cols) or len(geo.z) != len( + geo.angle + ): + raise ValueError("projections and original per-view geometry disagree") + stride = args.view_stride + geometry = sparse(geo, stride) if stride > 1 else geo + measurements = np.ascontiguousarray(views[::stride], dtype=np.float32) + denoised = denoise_scan(dn, measurements, device) + del measurements + vol = reconstruct(geometry, denoised, zs, device, convention) + if args.model == "refined" or args.source in ("supplied", "routine-bank"): + vol = vol.clamp(-2000, 6000).round().short() + out = [] + for centre in z: + rows, flip = slab_rows(zs, centre) + slab = vol[rows].float() + x = to_input(slab.flip(0) if flip else slab)[None].contiguous( + memory_format=torch.channels_last_3d + ) + with torch.autocast("cuda", dtype=torch.bfloat16): + out.append(enc(x)[0][0].cpu().numpy()) + return np.stack(out), z, encoder_name + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument( + "--root", + type=Path, + default=Path(__file__).resolve().parent, + help="unpacked model bundle", + ) + shared = argparse.ArgumentParser(add_help=False) + shared.add_argument("--region", choices=("chest", "abdomen"), required=True) + shared.add_argument("--draw", type=int, choices=(0, 1), required=True) + shared.add_argument("--view-stride", type=int, choices=(1, 2, 4, 8), required=True) + shared.add_argument("--output", type=Path, required=True) + modes = parser.add_subparsers(dest="mode", required=True) + scan = modes.add_parser("scan", parents=[shared]) + scan.add_argument("--case", type=Path, required=True) + scan.add_argument( + "--source", choices=("routine", "supplied", "routine-bank"), default="routine" + ) + scan.add_argument("--model", choices=("adapter", "refined"), required=True) + scan.add_argument("--device", default="cuda:0") + scan.add_argument( + "--slab-index", + type=int, + nargs="+", + help="optional zero-based indices on the full physical grid", + ) + features = modes.add_parser("features", parents=[shared]) + features.add_argument("--input", type=Path, required=True) + features.add_argument("--key", required=True) + features.add_argument( + "--base-sha256", help="required for archives without embedded base_sha256" + ) + features.add_argument("--manufacturer", choices=("GE", "Siemens"), required=True) + args = parser.parse_args() + if args.output.exists(): + parser.error(f"output already exists: {args.output}") + bundle = Bundle(args.root) + if args.mode == "scan": + x, z, encoder = infer_scan(args, bundle) + else: + args.model = "adapter" + x, z = saved_features(args, bundle) + encoder = bundle.manifest["manufacturers"][args.manufacturer]["base"] + values = { + "z0": z, + "manufacturer": args.manufacturer, + "region": args.region, + "model": args.model, + "draw": args.draw, + "view_stride": args.view_stride, + "encoder_sha256": bundle.manifest["sha256"][encoder], + } + if z.shape != (len(x),) or not np.isfinite(z).all() or not np.isfinite(x).all(): + raise ValueError("invalid slab features or z0") + if args.mode == "scan": + values.update(case_id=args.case.name, source=args.source) + if args.model == "adapter": + assets = bundle.manifest["manufacturers"][args.manufacturer] + key = assets["heads"][args.region][str(args.draw)] + with np.load(bundle.checked(key), allow_pickle=False) as head: + metadata = json.loads(head["metadata"].item()) + if metadata["sha256"] != values["encoder_sha256"]: + raise ValueError("readout and base encoder digests disagree") + values.update( + slab=predict(head, x, args.view_stride), + base_slab=x, + base_sha256=values["encoder_sha256"], + readout_sha256=bundle.manifest["sha256"][key], + ) + else: + values["slab"] = x + args.output.parent.mkdir(parents=True, exist_ok=True) + with tempfile.NamedTemporaryFile(dir=args.output.parent, suffix=".npz") as tmp: + np.savez_compressed(tmp, **values) + tmp.flush() + os.link(tmp.name, args.output) + print(f"{args.output}: {len(x)} slabs") + + +if __name__ == "__main__": + main() diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..6c8594867d72287fb0c5540ec814e27ff8178cb6 --- /dev/null +++ b/manifest.json @@ -0,0 +1,84 @@ +{ + "format": 1, + "manufacturers": { + "GE": { + "base": "adaptive/ge/base.pt", + "denoiser": "preprocessing/ge/denoiser.pt", + "fold": 10, + "heads": { + "abdomen": { + "0": "adaptive/ge/abdomen_draw0.npz", + "1": "adaptive/ge/abdomen_draw1.npz" + }, + "chest": { + "0": "adaptive/ge/chest_draw0.npz", + "1": "adaptive/ge/chest_draw1.npz" + } + }, + "refined": { + "0": "refined/ge/draw0.pt", + "1": "refined/ge/draw1.pt" + } + }, + "Siemens": { + "base": "adaptive/siemens/base.pt", + "denoiser": "preprocessing/siemens/denoiser.pt", + "fold": 11, + "heads": { + "abdomen": { + "0": "adaptive/siemens/abdomen_draw0.npz", + "1": "adaptive/siemens/abdomen_draw1.npz" + }, + "chest": { + "0": "adaptive/siemens/chest_draw0.npz", + "1": "adaptive/siemens/chest_draw1.npz" + } + }, + "refined": { + "0": "refined/siemens/draw0.pt", + "1": "refined/siemens/draw1.pt" + } + } + }, + "release": { + "snapshot": "correlation", + "supported_modes": { + "adapter": [ + 1, + 2, + 4, + 8 + ], + "refined": [ + 1 + ] + }, + "weights_identical_across_historical_snapshots": true + }, + "sha256": { + "adaptive/ge/base.pt": "54b532b56b90af0f3a30f648cb8d8b231c926fab5b8d47d5803f783687c43f64", + "preprocessing/ge/denoiser.pt": "aea29f6c832a2e6fcd05ae4369acc14ceca72a161627cb5de88597aae3daf83a", + "refined/ge/draw0.pt": "54b290e77a01bab1fe3feab0cd41d11910d51b88550ed8b73a4b2290a4bfb370", + "refined/ge/draw1.pt": "19bd30de60567dbeea90174fd2cf853a5dc58d95ad90fe5e31757d87162d4ffd", + "adaptive/ge/chest_draw0.npz": "d6f90c33f3b93480f210a1e442018be0bbeba993d045bd534e09ea0b295a54ec", + "adaptive/ge/chest_draw1.npz": "b1daa48d0514468922fc3c41a842501bb2a90a3ae0ad2ecb060073a3faebeab1", + "adaptive/ge/abdomen_draw0.npz": "5f02e1f964415424d185242a421e39caf2e828476dac95f82d8eb1fb667ed454", + "adaptive/ge/abdomen_draw1.npz": "7c5067d65de9c33ba5f0ba907de355fc05db0db57297e495d5c5564966ad9066", + "adaptive/siemens/base.pt": "316b5812e22e99bcbeb4b3227b0edb13b33c9d11358174303337a1444b824a1c", + "preprocessing/siemens/denoiser.pt": "00f45f34db1b1f8c6af407f97efc0429bd94fd66de3335ee7d9701aa01e7aff2", + "refined/siemens/draw0.pt": "fe224da48c0e9cfe50e657abcf86146d1ca945202770ae0cd6bc49ae5b18aed4", + "refined/siemens/draw1.pt": "95dba94ad1e89eb33087382ef588a496c1a5c6e1da8b666487a7f3b09d2b2085", + "adaptive/siemens/chest_draw0.npz": "1a3068bc042874e7e176c4db0bfc901ad8e8f13ee396096b1a111eaff50f86a5", + "adaptive/siemens/chest_draw1.npz": "ffe8ec7cb85cfbe3fc6ebfbcf6e2efab026a6e273a4a6d692a6ce790094fc912", + "adaptive/siemens/abdomen_draw0.npz": "51974a4f0faecfffaa720d64bce3fa3fd8a41c60146d4637eb26be954d797f30", + "adaptive/siemens/abdomen_draw1.npz": "bdcd7efccfa4199375b52021ae76de1c85ddd7474ced937cfbab2d0e33f8afea", + "convention.json": "f974350d8b516cb7e533e08c548b4281958a92ad8736613157b064a31e11c811" + }, + "name": "Proj2Rep-CTFM", + "model_family": "Proj2Rep", + "variants": [ + "Universal", + "Adaptive", + "Refined" + ] +} diff --git a/preprocessing/ge/denoiser.pt b/preprocessing/ge/denoiser.pt new file mode 100644 index 0000000000000000000000000000000000000000..0998162ad8eee8a4217ad99dfff519050655c9e0 --- /dev/null +++ b/preprocessing/ge/denoiser.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aea29f6c832a2e6fcd05ae4369acc14ceca72a161627cb5de88597aae3daf83a +size 10145213 diff --git a/preprocessing/siemens/denoiser.pt b/preprocessing/siemens/denoiser.pt new file mode 100644 index 0000000000000000000000000000000000000000..55fda473bf290a5f4edb79b38e6446ad8000d3dc --- /dev/null +++ b/preprocessing/siemens/denoiser.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:00f45f34db1b1f8c6af407f97efc0429bd94fd66de3335ee7d9701aa01e7aff2 +size 10145213 diff --git a/proj2rep/__init__.py b/proj2rep/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..b51063a9673f5cce0ce2b575c3e8cae9cc9841ac --- /dev/null +++ b/proj2rep/__init__.py @@ -0,0 +1,7 @@ +"""proj2rep: read CT detector measurements into the feature space of a frozen CT image foundation model. + +Pipeline (see README.md): + calibrate -> train-denoiser -> bank -> train-encoder -> evaluate / stress -> encode +""" + +__version__ = "1.0.0" diff --git a/proj2rep/__main__.py b/proj2rep/__main__.py new file mode 100644 index 0000000000000000000000000000000000000000..411a6a051a73e7e7eb3a689d18cb63cd02ae02b8 --- /dev/null +++ b/proj2rep/__main__.py @@ -0,0 +1,30 @@ +"""Command line: python -m proj2rep [options] (multi-GPU: torchrun --nproc_per_node N -m proj2rep ...)""" + +import sys + +COMMANDS = { + "calibrate": "proj2rep.calibrate_cli", + "feature-offset": "proj2rep.feature_offset", + "train-denoiser": "proj2rep.train_denoiser", + "bank": "proj2rep.bank", + "train-encoder": "proj2rep.train_encoder", + "evaluate": "proj2rep.evaluate", + "stress": "proj2rep.stress", + "report": "proj2rep.report", + "encode": "proj2rep.encode", + "lesion": "proj2rep.lesion", +} + + +def main(): + if len(sys.argv) < 2 or sys.argv[1] not in COMMANDS: + print(__doc__) + print("commands: " + ", ".join(COMMANDS)) + sys.exit(0 if len(sys.argv) > 1 and sys.argv[1] in ("-h", "--help") else 2) + import importlib + + importlib.import_module(COMMANDS[sys.argv[1]]).main(sys.argv[2:]) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/bank.py b/proj2rep/bank.py new file mode 100644 index 0000000000000000000000000000000000000000..4925454d00be3eae4821e6495ec9cd6884502ca8 --- /dev/null +++ b/proj2rep/bank.py @@ -0,0 +1,77 @@ +"""Denoised back-projections of every case at several dose levels and view fractions, for one fold. + +Uses the fold's own denoiser, so held-out cases are processed by a model that never saw them. +Levels: `full` (routine dose), `low` (the supplied reduced dose), `min` (noise scaled to +--min-dose of routine). View fractions: keep every k-th view. Cases are split across GPUs. + + torchrun --nproc_per_node 8 -m proj2rep bank --data DATA --work WORK --fold 0 +Output: WORK/bank/fold//_v.npy (int16 HU, 256 x 256) and z_mm.npy +""" + +import argparse +from pathlib import Path + +import numpy as np + +from . import dist +from .data import group_of, load_cohort +from .geometry import Conventions, Geometry, reconstruct, sparse +from .models import denoise_scan +from .train_denoiser import load, noise_scale + + +def bank_dir(work, fold, case_id): + return Path(work) / "bank" / f"fold{fold}" / case_id + + +def build_case(case, model, conv, out, device, levels, views, min_dose): + geo = Geometry(case) + zs = geo.image_z[geo.valid()] + out.mkdir(parents=True, exist_ok=True) + np.save(out / "z_mm.npy", zs) + full = np.asarray(case.array("proj_full"), dtype=np.float32) + noise = None + if case.has("proj_low"): + noise = np.asarray(case.array("proj_low"), dtype=np.float32) - full + for level in levels: + if level != "full" and (noise is None or not case.low_dose_fraction): + continue + scale = {"full": 0.0, "low": 1.0}[level] if level != "min" else noise_scale(case.low_dose_fraction, min_dose) + for k in views if level != "min" else [1]: + path = out / f"{level}_v{k}.npy" + if path.exists(): + continue + data = np.ascontiguousarray((full + scale * noise if scale else full)[::k]) + g = sparse(geo, k) if k > 1 else geo + vol = reconstruct(g, denoise_scan(model, data, device), zs, device, conv(geo)) + tmp = path.with_suffix(".tmp.npy") + np.save(tmp, vol.clamp(-2000, 6000).round().short().cpu().numpy()) + tmp.replace(path) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + p.add_argument("--fold", type=int, required=True, help="fold whose models are used (-1: the model trained on every case)") + p.add_argument("--levels", nargs="+", default=["full", "low"], choices=["full", "low", "min"]) + p.add_argument("--views", type=int, nargs="+", default=[1, 2, 4, 8]) + p.add_argument("--min-dose", type=float, default=0.025) + p.add_argument("--no-thin", nargs="*", default=[], help="REGION:MANUFACTURER groups built at all views only") + a = p.parse_args(argv) + + rank, world, device = dist.init() + cohort = load_cohort(a.data, work_dir=a.work) + model = load(a.work, a.fold, device) + conv = Conventions(Path(a.work) / "convention.json") + ids = cohort.cases(cohort.ids(), image=False)[rank::world] + for i, case in enumerate(ids): + cid = case.id + views = [1] if group_of(case, a.no_thin) else a.views + build_case(case, model, conv, bank_dir(a.work, a.fold, cid), device, a.levels, views, a.min_dose) + print(f"[rank {rank}] bank fold {a.fold}: {cid} ({i + 1}/{len(ids)})", flush=True) + dist.done(sync=False) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/calibrate_cli.py b/proj2rep/calibrate_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..753a8ba2105341a86ae12f0314538c964f4497f5 --- /dev/null +++ b/proj2rep/calibrate_cli.py @@ -0,0 +1,31 @@ +"""Calibrate each manufacturer's geometric convention against the scanner images. + + python -m proj2rep calibrate --data DATA --work WORK +Writes WORK/convention.json (needed by every later step) and draws the cross-validation folds +(WORK/folds.csv) if cases.csv has no fold column. +""" + +import argparse +from pathlib import Path + +import torch + +from .data import load_cohort +from .geometry import calibrate + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + p.add_argument("--folds", type=int, default=5) + p.add_argument("--cases-per-manufacturer", type=int, default=3) + p.add_argument("--device", default="cuda:0" if torch.cuda.is_available() else "cpu") + a = p.parse_args(argv) + cohort = load_cohort(a.data, folds=a.folds, work_dir=a.work) + print(f"{len(cohort.table)} cases, folds:", cohort.table.fold.value_counts().sort_index().to_dict(), flush=True) + calibrate(cohort, Path(a.work) / "convention.json", a.device, a.cases_per_manufacturer) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/data.py b/proj2rep/data.py new file mode 100644 index 0000000000000000000000000000000000000000..3c76535eb22c5eefbb0ba0870f25f3de128fd145 --- /dev/null +++ b/proj2rep/data.py @@ -0,0 +1,201 @@ +"""Cohort, folds and per-case data access. + +A data root holds one folder per case plus a cohort table: + + /cases.csv + //geometry.json scanner and detector geometry + //views.npz angle_rad (V,), z_mm (V,) [, source_isocenter_mm (V,)] + //proj_full.npy (V, rows, cols) line integrals, routine dose + //proj_low.npy optional, same shape: reduced-dose scan of the same acquisition + //image.json reconstruction grid: z_mm, pixel_spacing_mm, origin_mm, thickness_mm + //image_full.npy (S, H, W) HU, routine-dose reconstruction (teacher input) + //image_low.npy optional, scanner reconstruction of proj_low (same slices) + +See README.md for every field. +""" + +import json +import os +from dataclasses import dataclass +from functools import cached_property +from pathlib import Path + +import numpy as np +import pandas as pd +import torch +import torch.nn.functional as F +from sklearn.model_selection import StratifiedKFold + +HALF = 18.0 # slab half-length along the table, mm (a slab is 36 mm) +STEP = 12.0 # spacing of evaluation slabs, mm +SLAB_SHAPE = (24, 256, 256) # encoder input (slices, rows, columns) +HU_RANGE = (-1024.0, 2048.0) # intensity window of the encoder input + + +def to_input(x): + """HU volume (S, H, W) -> encoder input (1, 24, 256, 256), values in [0, 1].""" + lo, hi = HU_RANGE + x = (x.clamp(lo, hi) - lo) / (hi - lo) + return F.interpolate(x[None, None], SLAB_SHAPE, mode="trilinear", align_corners=False)[0] + + +def slab_rows(z, z0): + keep = np.flatnonzero(np.abs(z - z0) <= HALF) + if len(keep) == 0: + raise ValueError(f"no slices within {HALF} mm of z0={z0:.1f}") + return slice(keep[0], keep[-1] + 1), z[keep[0]] > z[keep[-1]] + + +class Case: + """Lazy access to one case folder.""" + + def __init__(self, root, case_id, row=None): + self.id, self.dir = case_id, Path(root) / case_id + self.row = row or {} + + @cached_property + def geometry(self): + return json.loads((self.dir / "geometry.json").read_text()) + + @cached_property + def image_meta(self): + return json.loads((self.dir / "image.json").read_text()) + + @cached_property + def views(self): + with np.load(self.dir / "views.npz") as v: + return {k: v[k] for k in v.files} + + def _field(self, name): + """Value from cases.csv, falling back to geometry.json when the cell is empty.""" + v = self.row.get(name) + if v is None or (isinstance(v, float) and np.isnan(v)) or str(v).strip() in ("", "nan"): + v = self.geometry.get(name) + return v + + @property + def manufacturer(self): + return str(self._field("manufacturer")).strip() + + @property + def region(self): + return str(self.row.get("region", "unknown")) + + @property + def low_dose_fraction(self): + f = self._field("low_dose_fraction") + if f is None: + return None + f = float(f) + if not 0 < f < 1: + raise ValueError(f"{self.id}: low_dose_fraction must be between 0 and 1, got {f}") + return f + + def has(self, name): + return (self.dir / f"{name}.npy").exists() + + def array(self, name): + """proj_full, proj_low, image_full, image_low as read-only memory maps.""" + return np.load(self.dir / f"{name}.npy", mmap_mode="r") + + @cached_property + def image_z(self): + return np.asarray(self.image_meta["z_mm"], dtype=np.float64) + + @cached_property + def slab_range(self): + """Slab centres with full image coverage and measurements around them.""" + vz = self.views["z_mm"] + lo = max(self.image_z.min(), vz.min()) + HALF + hi = min(self.image_z.max(), vz.max()) - HALF + return lo, hi + + def image_slab(self, z0, mirror=False, dose="full"): + """Scanner image slab in the encoder input convention (1, 24, 256, 256).""" + rows, flip = slab_rows(self.image_z, z0) + x = torch.from_numpy(np.array(self.array(f"image_{dose}")[rows], dtype=np.float32)) + x = to_input(x.flip(0) if flip else x) + return x.flip(-1) if mirror else x + + def grid(self): + lo, hi = self.slab_range + return np.arange(lo, hi + 1e-6, STEP) + + def usable(self, image=True): + """Covers at least one 36 mm slab (and has a routine-dose image when image=True).""" + lo, hi = self.slab_range + return hi >= lo and (self.has("image_full") or not image) + + +@dataclass +class Cohort: + root: Path + table: pd.DataFrame # one row per case: case_id, region, manufacturer, fold, ... + + def case(self, case_id): + return Case(self.root, case_id, self.table.set_index("case_id").loc[case_id].to_dict()) + + def split(self, fold): + """(training case ids, held-out case ids) for a cross-validation fold.""" + t = self.table + return t.case_id[t.fold != fold].tolist(), t.case_id[t.fold == fold].tolist() + + def ids(self): + return self.table.case_id.tolist() + + def cases(self, ids, image=True): + """Case objects for ids, skipping (with a message) cases too short or without images.""" + out = [] + for c in map(self.case, ids): + if c.usable(image): + out.append(c) + else: + print(f"skipping {c.id}: shorter than one slab" + (" or no image_full.npy" if image else ""), flush=True) + return out + + +def load_cohort(data_root, folds=5, seed=1234, strata=("region", "manufacturer"), work_dir=None): + """Read cases.csv; draw stratified folds if the table has no `fold` column. + + Cases with `exclude` set are dropped after the folds are drawn, so excluding a case + never moves another case to a different fold. Drawn folds are written to + /folds.csv so later steps and reruns use the same split. + """ + root = Path(data_root) + t = pd.read_csv(root / "cases.csv", dtype={"case_id": str}) + if "manufacturer" not in t: + t["manufacturer"] = None + t["manufacturer"] = [Case(root, c, {"manufacturer": m}).manufacturer for c, m in zip(t.case_id, t.manufacturer)] + if "region" not in t: + t["region"] = "unknown" + saved = Path(work_dir) / "folds.csv" if work_dir else None + if "fold" not in t: + if saved and saved.exists(): + t = t.merge(pd.read_csv(saved, dtype={"case_id": str}), on="case_id", how="left") + if t.fold.isna().any(): + raise ValueError(f"{saved} does not cover every case in cases.csv; delete it to redraw folds") + else: + key = t[list(strata)].astype(str).agg("|".join, axis=1) + small = key.map(key.value_counts()) < folds # rare strata are pooled + key[small] = "other" + t["fold"] = -1 + for f, (_, te) in enumerate(StratifiedKFold(folds, shuffle=True, random_state=seed).split(t, key)): + t.loc[t.index[te], "fold"] = f + if saved: # atomic: concurrent ranks write identical content + saved.parent.mkdir(parents=True, exist_ok=True) + tmp = saved.with_suffix(f".{os.getpid()}.tmp") + t[["case_id", "fold"]].to_csv(tmp, index=False) + os.replace(tmp, saved) + t["fold"] = t.fold.astype(int) + if "exclude" in t: + t = t[~t.exclude.fillna(0).astype(bool)] + return Cohort(root, t.reset_index(drop=True)) + + +def group_of(case, no_thin): + """True if the case belongs to a REGION:MANUFACTURER group listed in no_thin.""" + for g in no_thin: + region, _, maker = g.partition(":") + if (region in ("*", case.region)) and case.manufacturer.upper().startswith(maker.upper()): + return True + return False diff --git a/proj2rep/dist.py b/proj2rep/dist.py new file mode 100644 index 0000000000000000000000000000000000000000..c2cb8ff0c68c9b43bbe3ab52c45548322798e6d5 --- /dev/null +++ b/proj2rep/dist.py @@ -0,0 +1,41 @@ +"""Multi-GPU helpers. Every entry point works under `torchrun --nproc_per_node N` and as a plain single process.""" + +import os +from datetime import timedelta + +import torch +import torch.distributed as dist + +# Steps that split cases across GPUs can leave ranks idle for a long time; keep collectives patient. +TIMEOUT = timedelta(hours=12) + + +def init(): + """Start the process group when launched by torchrun. Returns (rank, world size, device).""" + local = int(os.environ.get("LOCAL_RANK", "0")) + if torch.cuda.is_available(): + local %= torch.cuda.device_count() # more processes than GPUs: several share a GPU + torch.cuda.set_device(local) + if "RANK" in os.environ and not dist.is_initialized(): + dist.init_process_group("nccl" if torch.cuda.is_available() else "gloo", timeout=TIMEOUT) + rank, world = (dist.get_rank(), dist.get_world_size()) if dist.is_initialized() else (0, 1) + return rank, world, torch.device(f"cuda:{local}" if torch.cuda.is_available() else "cpu") + + +def broadcast(t, src=0): + if dist.is_initialized(): + dist.broadcast(t, src) + return t + + +def done(sync=True): + """End the process group. sync=False for steps whose ranks work on independent cases.""" + if dist.is_initialized(): + if sync: + dist.barrier() + dist.destroy_process_group() + + +def log(rank, *a): + if rank == 0: + print(*a, flush=True) diff --git a/proj2rep/encode.py b/proj2rep/encode.py new file mode 100644 index 0000000000000000000000000000000000000000..7af34a64a3a1cb471f6ffce53fc87dc6887ff1a2 --- /dev/null +++ b/proj2rep/encode.py @@ -0,0 +1,71 @@ +"""Encode new scans from their measurements with a trained denoiser and encoder. + +A case folder needs geometry.json, views.npz, proj_full.npy (any dose) and image.json, which +here only defines the output grid (z_mm, pixel_spacing_mm, origin_mm, thickness_mm); no image +array is read. Embeddings of the fold models are averaged when several folds are given. + + python -m proj2rep encode --cases DIR [DIR ...] --work WORK --folds 0 1 2 3 4 --out embeddings/ +Output per case: /.npz with z0 (n,), slab (n, 512), regions (n, grid*grid, 512). +""" + +import argparse +from pathlib import Path + +import numpy as np +import torch + +from .data import STEP, Case, slab_rows, to_input +from .evaluate import embed +from .geometry import Conventions, Geometry, reconstruct +from .models import denoise_scan +from .train_denoiser import load as load_denoiser +from .train_encoder import load as load_encoder + + +def encode_case(case, models, conv, device, grid=4): + geo = Geometry(case) + zs = geo.image_z[geo.valid()] + lo, hi = case.slab_range + z = np.arange(lo, hi + 1e-6, STEP) + data = case.array("proj_full") + slabs, regions = [], [] + for enc, dn in models: + vol = reconstruct(geo, denoise_scan(dn, data, device), zs, device, conv(geo)) + xs = [] + for z0 in z: + rows, flip = slab_rows(zs, z0) + x = vol[rows].float().cpu() + xs.append(to_input(x.flip(0) if flip else x)) + + def run(x, enc=enc): + with torch.autocast("cuda", dtype=torch.bfloat16): + return enc(x.to(device).contiguous(memory_format=torch.channels_last_3d), grid=grid) + + s, r = embed(run, xs) + slabs.append(s) + regions.append(r.astype(np.float32)) + return {"z0": z, "slab": np.mean(slabs, 0), "regions": np.mean(regions, 0).astype(np.float16)} + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--cases", nargs="+", required=True, help="case folders") + p.add_argument("--work", required=True, help="training work directory (models and convention.json)") + p.add_argument("--folds", type=int, nargs="+", default=[0]) + p.add_argument("--grid", type=int, choices=[4, 8], default=4, help="regional grid side length (8 for lesion scoring)") + p.add_argument("--out", required=True) + p.add_argument("--device", default="cuda:0" if torch.cuda.is_available() else "cpu") + a = p.parse_args(argv) + device = torch.device(a.device) + models = [(load_encoder(a.work, f, device), load_denoiser(a.work, f, device)) for f in a.folds] + conv = Conventions(Path(a.work) / "convention.json") + out = Path(a.out) + out.mkdir(parents=True, exist_ok=True) + for folder in map(Path, a.cases): + case = Case(folder.parent, folder.name) + np.savez_compressed(out / f"{case.id}.npz", **encode_case(case, models, conv, device, a.grid)) + print("encoded", case.id, flush=True) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/evaluate.py b/proj2rep/evaluate.py new file mode 100644 index 0000000000000000000000000000000000000000..e32418d6843ec4d6a687ec9d7afa52d98b70276e --- /dev/null +++ b/proj2rep/evaluate.py @@ -0,0 +1,79 @@ +"""Held-out evaluation of one fold: embeddings on a fixed 12 mm grid of slabs for every held-out case. + +Writes WORK/eval/fold/.npz with + z0 slab centres + teacher_full teacher on the scanner routine-dose image (the target) + raw_full, raw_low encoder on denoised measurements at routine and at the supplied low dose + teacher_low teacher on the scanner's own low-dose image, where image_low.npy exists +(each slab embedding (n, 512); regional embeddings with suffix _regions, (n, 16, 512)). + + torchrun --nproc_per_node 8 -m proj2rep evaluate --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors +""" + +import argparse +from pathlib import Path + +import numpy as np +import torch + +from . import dist +from .bank import bank_dir +from .data import load_cohort +from .models import load_teacher, teach +from .train_encoder import BankSlabs, load + + +@torch.inference_mode() +def embed(fn, xs, batch=16): + s, r = [], [] + for i in range(0, len(xs), batch): + u, w = fn(torch.stack(xs[i : i + batch])) + s.append(u.float().cpu().numpy()) + r.append(w.float().cpu().numpy().astype(np.float16)) + return np.concatenate(s), np.concatenate(r) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + p.add_argument("--fold", type=int, required=True) + p.add_argument("--teacher", required=True) + a = p.parse_args(argv) + + rank, world, device = dist.init() + work = Path(a.work) + cohort = load_cohort(a.data, work_dir=work) + _, held = cohort.split(a.fold) + teacher, model = load_teacher(a.teacher, device), load(work, a.fold, device) + out = work / "eval" / f"fold{a.fold}" + out.mkdir(parents=True, exist_ok=True) + + def run_encoder(x): + with torch.autocast("cuda", dtype=torch.bfloat16): + return model(x.to(device).contiguous(memory_format=torch.channels_last_3d)) + + def run_teacher(x): + return teach(teacher, x.to(device)) + + for case in cohort.cases(held)[rank::world]: + cid = case.id + path = out / f"{cid}.npz" + if path.exists(): + continue + src = BankSlabs(case, bank_dir(work, a.fold, cid)) + z = case.grid() + res = {"z0": z} + res["teacher_full"], res["teacher_full_regions"] = embed(run_teacher, [case.image_slab(z0) for z0 in z]) + res["raw_full"], res["raw_full_regions"] = embed(run_encoder, [src.slab(z0, 0.0) for z0 in z]) + if src.has("low", 1): + res["raw_low"], res["raw_low_regions"] = embed(run_encoder, [src.slab(z0, 1.0) for z0 in z]) + if case.has("image_low"): + res["teacher_low"], res["teacher_low_regions"] = embed(run_teacher, [case.image_slab(z0, dose="low") for z0 in z]) + np.savez_compressed(path, **res) + print(f"[rank {rank}] evaluated fold {a.fold}: {cid} ({len(z)} slabs)", flush=True) + dist.done(sync=False) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/feature_offset.py b/proj2rep/feature_offset.py new file mode 100644 index 0000000000000000000000000000000000000000..734584a24726cdbaa50d95998b048429287ec223 --- /dev/null +++ b/proj2rep/feature_offset.py @@ -0,0 +1,92 @@ +"""Fit and apply a constant offset for global CT-FM slab embeddings.""" + +import argparse +from pathlib import Path +from tempfile import NamedTemporaryFile + +import numpy as np + + +def exam_residual(measurement, reference): + if ( + measurement.ndim != 2 + or not len(measurement) + or measurement.shape != reference.shape + or measurement.shape[1] != 512 + ): + raise ValueError("Expected paired nonempty arrays of 512 features per slab") + if not np.isfinite(measurement).all() or not np.isfinite(reference).all(): + raise ValueError("Nonfinite calibration feature") + return (reference.astype(np.float64) - measurement).mean(axis=0) + + +def load_scan(path): + with np.load(path) as scan: + z, slab = scan["z0"], scan["slab"] + if z.ndim != 1 or len(z) == 0 or slab.shape != (len(z), 512): + raise ValueError(f"{path}: inconsistent slab coordinates or features") + if ( + not np.isfinite(z).all() + or len(np.unique(z)) != len(z) + or not np.isfinite(slab).all() + ): + raise ValueError(f"{path}: invalid slab coordinates or features") + return z, slab + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + subs = parser.add_subparsers(dest="action", required=True) + fit = subs.add_parser( + "fit", help="pair equally named exam files from each directory" + ) + fit.add_argument("measurement_dir", type=Path) + fit.add_argument("reference_dir", type=Path) + fit.add_argument("out", type=Path) + apply = subs.add_parser( + "apply", help="write corrected global embeddings for one scan" + ) + apply.add_argument("offset", type=Path) + apply.add_argument("scan", type=Path) + apply.add_argument("out", type=Path) + args = parser.parse_args(argv) + if args.action == "fit": + measurement = {p.name: p for p in args.measurement_dir.glob("*.npz")} + reference = {p.name: p for p in args.reference_dir.glob("*.npz")} + if not measurement or measurement.keys() != reference.keys(): + parser.error( + "Expected one matched pair of files per calibration examination" + ) + if args.out.resolve() in { + p.resolve() for p in [*measurement.values(), *reference.values()] + }: + parser.error("Choose an offset file separate from the calibration scans") + residuals = [] + for name in sorted(measurement): + z, x = load_scan(measurement[name]) + rz, y = load_scan(reference[name]) + if not np.array_equal(z, rz): + raise ValueError(f"{name}: calibration slab coordinates differ") + residuals.append(exam_residual(x, y)) + arrays = {"offset": np.mean(residuals, axis=0), "examinations": len(residuals)} + else: + if args.out.resolve() in (args.scan.resolve(), args.offset.resolve()): + parser.error("Choose an output path separate from the scan and offset") + z, x = load_scan(args.scan) + with np.load(args.offset) as saved: + offset = saved["offset"] + if offset.shape != (512,) or not np.isfinite(offset).all(): + raise ValueError("Expected a finite 512-feature offset") + arrays = {"z0": z, "slab": x.astype(float) + offset} + with NamedTemporaryFile(dir=args.out.parent, delete=False) as file: + tmp = Path(file.name) + try: + np.savez_compressed(file, **arrays) + file.flush() + tmp.replace(args.out) + finally: + tmp.unlink(missing_ok=True) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/geometry.py b/proj2rep/geometry.py new file mode 100644 index 0000000000000000000000000000000000000000..3260a246264d3890e7fc91f0082ce536bccb1724 --- /dev/null +++ b/proj2rep/geometry.py @@ -0,0 +1,173 @@ +"""Analytic back-projection of helical fan-beam measurements onto the reconstruction grid. + +Ramp filter along detector columns with fan-beam cosine weighting, then, for every output +slice, back-projection of the gantry rotation of views nearest to that slice, with detector +rows chosen by the cone angle. A fast, vendor-independent reconstruction that the encoder is +trained to read. Output is in HU on the case's image grid at 256 x 256. + +Vendors store angles, columns and rows with different signs and offsets. `calibrate` picks, +per manufacturer, the convention whose back-projection best matches the scanner images. +""" + +import copy +import itertools +import json +import math +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +SIZE = 256 # output pixels per side + + +class Geometry: + def __init__(self, case, size=SIZE): + g, im, v = case.geometry, case.image_meta, case.views + self.case, self.manufacturer = case.id, case.manufacturer.upper() + self.head_first = str(g.get("patient_position", "FFS")).upper().startswith("HF") + sid = v.get("source_isocenter_mm") + self.sid = float(np.mean(sid)) if sid is not None else float(g["source_isocenter_mm"]) + self.sdd = float(g["source_detector_mm"]) + self.dgamma = float(g["column_spacing_mm"]) / self.sdd + self.drow = float(g["row_spacing_mm"]) + self.c0, self.r0 = g["central_element"][0] - 1, g["central_element"][1] - 1 # 1-based in the file + self.rows, self.cols = int(g["detector_rows"]), int(g["detector_columns"]) + self.mu = float(g["water_mu_per_mm"]) + self.n = round(float(g["stored_views_per_rotation"])) + self.angle, self.z = v["angle_rad"].astype(np.float64), v["z_mm"].astype(np.float64) + self.image_z = np.asarray(im["z_mm"], dtype=np.float64) + self.thickness = float(im.get("thickness_mm", 1.5)) + # DICOM order: pixel_spacing_mm = [between rows (y), between columns (x)] + sy, sx = (float(v) for v in im["pixel_spacing_mm"]) + width, height = int(im.get("columns", 512)), int(im.get("rows", im.get("columns", 512))) + self.x = im["origin_mm"][0] + (np.arange(size) + 0.5) * sx * width / size - 0.5 * sx + self.y = im["origin_mm"][1] + (np.arange(size) + 0.5) * sy * height / size - 0.5 * sy + c = im.get("rotation_center_mm") or [0.0, 0.0] + self.centre = (float(c[0]), float(c[1])) + + def valid(self): + """Indices of image slices with measurements on both sides.""" + return np.flatnonzero((self.image_z >= self.z.min()) & (self.image_z <= self.z.max())) + + +def sparse(geo, k): + """The same acquisition keeping every k-th view (use with data[::k]).""" + g = copy.copy(geo) + g.angle, g.z, g.n = geo.angle[::k], geo.z[::k], max(geo.n // k, 1) + return g + + +def ramp(geo, device): + """Equiangular fan-beam ramp kernel, including the column step.""" + n = torch.arange(-(geo.cols - 1), geo.cols, device=device, dtype=torch.float64) + k = torch.zeros_like(n) + odd = (n.abs() % 2) == 1 + k[odd] = -1 / (2 * math.pi**2 * torch.sin(n[odd] * geo.dgamma) ** 2) + k[n == 0] = 1 / (8 * geo.dgamma**2) + return (k * geo.dgamma).float() + + +def _filter(geo, views, kernel): + gamma = (torch.arange(geo.cols, device=views.device) - geo.c0) * geo.dgamma + x = views.float() * (geo.sid * torch.cos(gamma)) + return F.conv1d(x.reshape(-1, 1, geo.cols), kernel[None, None], padding=geo.cols - 1).reshape(views.shape) + + +class Conventions: + """Per-manufacturer geometric convention (angle sign, quarter turns, column sign, row sign).""" + + def __init__(self, path): + self.path = Path(path) + self.table = json.loads(self.path.read_text()) if self.path.exists() else {} + + def __call__(self, geo): + key = next((k for k in self.table if geo.manufacturer.startswith(k)), None) + if key is None: + raise KeyError(f"no calibrated convention for manufacturer {geo.manufacturer!r}; run `proj2rep calibrate`") + return oriented(self.table[key], geo) + + +def oriented(conv, geo): + """Feet-first convention -> the one for this case (head-first mirrors left-right and the table axis).""" + sa, quarter, sc, sr = conv + return [-sa, quarter, -sc, -sr] if geo.head_first else [sa, quarter, sc, sr] + + +@torch.no_grad() +def backproject(geo, data, zs, device, conv): + """data: (V, rows, cols) line integrals -> HU volume (len(zs), SIZE, SIZE).""" + sa, quarter, sc, sr = conv + kernel = ramp(geo, device) + x = torch.tensor(geo.x - geo.centre[0], device=device, dtype=torch.float32) + y = torch.tensor(geo.y - geo.centre[1], device=device, dtype=torch.float32) + yy, xx = torch.meshgrid(y, x, indexing="ij") + out = torch.zeros(len(zs), len(y), len(x), device=device) + for i, z in enumerate(zs): + c = int(np.abs(geo.z - z).argmin()) + a = min(max(c - geo.n // 2, 0), max(len(geo.z) - geo.n, 0)) + pick = slice(a, a + geo.n) + q = _filter(geo, torch.from_numpy(np.array(data[pick], dtype=np.float32)).to(device), kernel) + beta = torch.tensor(sa * geo.angle[pick] + quarter * math.pi / 2, device=device, dtype=torch.float32) + dz = torch.tensor(z - geo.z[pick], device=device, dtype=torch.float32) + ux, uy = -torch.sin(beta)[:, None, None], torch.cos(beta)[:, None, None] + along = geo.sid - (xx * ux + yy * uy) + across = xx * uy - yy * ux + dist2 = along**2 + across**2 + col = geo.c0 + sc * torch.atan2(across, along) / geo.dgamma + row = geo.r0 + sr * dz[:, None, None] * geo.sdd / dist2.sqrt() / geo.drow + grid = torch.stack([2 * col / (geo.cols - 1) - 1, 2 * row.clamp(0, geo.rows - 1) / (geo.rows - 1) - 1], -1) + s = F.grid_sample(q[:, None], grid, mode="bilinear", padding_mode="zeros", align_corners=True)[:, 0] + out[i] = (s / dist2).sum(0) * (2 * math.pi / len(beta)) + return 1000 * (out / geo.mu - 1) + + +def reconstruct(geo, data, zs, device, conv, chunk=8): + """Back-projection averaged over the image slice thickness, in chunks of slices.""" + n = max(1, round(geo.thickness / 1.5)) + offsets = (np.arange(n) - (n - 1) / 2) * geo.thickness / n + zs = np.asarray(zs) + parts = [] + for i in range(0, len(zs), chunk): + z = zs[i : i + chunk] + parts.append(sum(backproject(geo, data, z + o, device, conv) for o in offsets) / n) + return torch.cat(parts) + + +def reference(case, geo, zs): + """Scanner image at the given slices, on the 256 x 256 grid, HU.""" + im = case.array("image_full") + idx = [int(np.abs(geo.image_z - z).argmin()) for z in zs] + x = torch.from_numpy(np.stack([im[i] for i in idx]).astype(np.float32)).clamp(-1024, 3000) + return F.interpolate(x[:, None], (SIZE, SIZE), mode="area")[:, 0] + + +def calibrate(cohort, out, device, per_vendor=3): + """Choose each manufacturer's convention by correlation with the scanner images.""" + result, report = {}, {} + cases = cohort.cases(cohort.ids()) + makers = sorted({c.manufacturer.upper().split()[0] for c in cases}) + for maker in makers: + mine = sorted((c for c in cases if c.manufacturer.upper().startswith(maker)), key=lambda c: Geometry(c).head_first) + pick = mine[:per_vendor] # feet-first cases first; head-first cases are scored through `oriented` + if not pick: + continue + score = {} + for case in pick: + geo = Geometry(case) + data = case.array("proj_full") + v = geo.valid() + zs = geo.image_z[v[[len(v) // 3, 2 * len(v) // 3]]] + ref = reference(case, geo, zs).to(device) + for conv in itertools.product((1, -1), (0, 1, 2, 3), (1, -1), (1, -1)): + r = backproject(geo, data, zs, device, oriented(conv, geo)).clamp(-1024, 3000) + c = torch.corrcoef(torch.stack([r.flatten(), ref.flatten()]))[0, 1].item() + score[conv] = score.get(conv, 0) + c / len(pick) + best = sorted(score, key=score.get, reverse=True) + result[maker] = list(best[0]) + report[maker] = {"cases": [c.id for c in pick], "top": [[list(b), round(score[b], 4)] for b in best[:4]]} + print(maker, report[maker], flush=True) + Path(out).parent.mkdir(parents=True, exist_ok=True) + Path(out).write_text(json.dumps(result, indent=1) + "\n") + return report diff --git a/proj2rep/lesion.py b/proj2rep/lesion.py new file mode 100644 index 0000000000000000000000000000000000000000..2f7bac1a533a2c85e7cf17ae430529be121d3aa2 --- /dev/null +++ b/proj2rep/lesion.py @@ -0,0 +1,47 @@ +"""Score lung nodule or liver lesion localization on CT-FM v12 regional features. + +python -m proj2rep lesion --task nodule --input embeddings/scan.npz --out scan_nodule.npz +""" + +import argparse +from pathlib import Path + +import numpy as np +from scipy.special import expit + + +def local_scores(regions, weights): + """Apply the training standardization and logistic head; output rows and columns follow the encoder grid.""" + grid = int(weights["grid"]) + if regions.ndim != 3 or regions.shape[1:] != (grid**2, len(weights["coef"])): + raise ValueError(f"Expected (slabs, {grid**2}, {len(weights['coef'])}) CT-FM features; encode with --grid {grid}") + if not np.isfinite(regions).all(): + raise ValueError("The scan contains missing or non-finite regional embeddings") + x = regions.astype(np.float32, copy=True) + x -= weights["mean"] + x /= weights["scale"] + logits = x.reshape(-1, x.shape[-1]) @ weights["coef"] + weights["intercept"] + return expit(logits).reshape(len(x), grid, grid) + + +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--task", choices=("nodule", "liver"), required=True) + parser.add_argument("--input", type=Path, required=True, help="one scan produced by proj2rep encode --grid 8") + parser.add_argument("--out", type=Path, required=True, help="output NPZ with slab positions and regional scores") + args = parser.parse_args(argv) + path = Path(__file__).parent / "weights" / f"{args.task}_grid8.npz" + with np.load(path) as weights, np.load(args.input) as scan: + scores = local_scores(scan["regions"], weights) + z0 = scan["z0"] + if z0.shape != (len(scores),) or not np.isfinite(z0).all(): + raise ValueError("Expected one finite z0 coordinate per slab") + if args.out.resolve() == args.input.resolve(): + raise ValueError("Use a separate file for the output scores") + with args.out.open("wb") as file: + np.savez_compressed(file, z0=z0, scores=scores, task=args.task, grid=int(weights["grid"])) + print(f"Scored {len(scores)} slabs for {args.task} localization") + + +if __name__ == "__main__": + main() diff --git a/proj2rep/models.py b/proj2rep/models.py new file mode 100644 index 0000000000000000000000000000000000000000..f6baaf4122705eb3bd48827e415deb67b2fbd27c --- /dev/null +++ b/proj2rep/models.py @@ -0,0 +1,131 @@ +"""Networks: measurement denoiser, frozen image teacher, and the measurement encoder. + +Teacher: the CT-FM image encoder (SegResNet encoder, 512 output features), frozen. +Encoder: the same architecture, initialised from the teacher and trained to reproduce the +teacher's embedding of the routine-dose image from back-projected measurements. +Both return a slab embedding (B, 512) and a 4 x 4 grid of regional embeddings (B, 16, 512). +""" + +import torch +import torch.nn.functional as F +from torch import nn + +DIM, GRID = 512, 4 +CT_FM = {"spatial_dims": 3, "in_channels": 1, "init_filters": 32, "blocks_down": [1, 2, 2, 4, 4]} +CLIP, SCALE = 12.0, 4.0 # line integrals are clipped to [-1, CLIP] and divided by SCALE in the denoiser + + +def segres_encoder(): + from monai.networks.nets.segresnet_ds import SegResEncoder + + return SegResEncoder(**CT_FM) + + +def load_teacher(path, device): + """Frozen CT-FM weights from a .safetensors file (see README for where to obtain them).""" + from safetensors.torch import load_file + + model = segres_encoder() + model.load_state_dict(load_file(str(path)), strict=True) + return model.to(device).eval().requires_grad_(False) + + +def pool(h, grid=GRID): + return h.mean((2, 3, 4)), F.adaptive_avg_pool3d(h, (1, grid, grid)).flatten(2).transpose(1, 2) + + +@torch.no_grad() +def teach(teacher, x): + with torch.autocast("cuda", dtype=torch.bfloat16): + h = teacher(x)[-1].float() + return pool(h) + + +class Encoder(nn.Module): + """Back-projected measurements (B, 1, 24, 256, 256) -> teacher-space embeddings.""" + + def __init__(self, teacher_path=None): + super().__init__() + self.net = segres_encoder() + if teacher_path: + from safetensors.torch import load_file + + self.net.load_state_dict(load_file(str(teacher_path)), strict=True) + + def forward(self, x, grid=GRID): + return pool(self.net(x)[-1].float(), grid) + + +class _Block(nn.Module): + def __init__(self, c): + super().__init__() + self.a, self.b = nn.Conv3d(c, c, 3, padding=1), nn.Conv3d(c, c, 3, padding=1) + self.n1, self.n2 = nn.GroupNorm(8, c), nn.GroupNorm(8, c) + + def forward(self, x): + return x + self.b(F.silu(self.n2(self.a(F.silu(self.n1(x)))))) + + +class Denoiser(nn.Module): + """Residual network over (views, detector rows, detector columns): reduced-dose -> routine-dose line integrals. + + Two levels; the coarse level halves views and columns, not rows. The output layer starts at + zero, so an untrained denoiser is the identity. + """ + + def __init__(self, c=48): + super().__init__() + self.stem = nn.Conv3d(1, c, 3, padding=1) + self.fine1 = nn.Sequential(_Block(c), _Block(c)) + self.down = nn.Conv3d(c, 2 * c, (2, 1, 2), stride=(2, 1, 2)) + self.coarse = nn.Sequential(*[_Block(2 * c) for _ in range(4)]) + self.up = nn.ConvTranspose3d(2 * c, c, (2, 1, 2), stride=(2, 1, 2)) + self.fine2 = nn.Sequential(_Block(c), _Block(c)) + self.head = nn.Conv3d(c, 1, 3, padding=1) + nn.init.zeros_(self.head.weight) + nn.init.zeros_(self.head.bias) + + def forward(self, x): + u = x.clamp(-1, CLIP) / SCALE + h = self.fine1(self.stem(u)) + h = self.fine2(h + self.up(self.coarse(self.down(h)))) + return (u + self.head(h)) * SCALE + + +@torch.inference_mode() +def denoise_scan(model, scan, device, chunk=96, margin=8): + """Whole scan (V, rows, cols) -> denoised float16 array, processed in overlapping view chunks.""" + import numpy as np + + v, _, c = scan.shape + out = np.empty(scan.shape, np.float16) + for a in range(0, v, chunk): + lo, hi = max(a - margin, 0), min(a + chunk + margin, v) + hi -= (hi - lo) % 2 + if hi <= a: + out[a:] = scan[a:] + continue + x = torch.from_numpy(np.asarray(scan[lo:hi], dtype=np.float32)).to(device)[None, None] + if c % 2: + x = F.pad(x, (0, 1)) + with torch.autocast("cuda", dtype=torch.bfloat16): + y = model(x)[0, 0, :, :, :c].float() + stop = min(a + chunk, hi) + out[a:stop] = y[a - lo : stop - lo].cpu().numpy() + if stop < min(a + chunk, v): + out[stop : min(a + chunk, v)] = scan[stop : min(a + chunk, v)] + return out + + +def short_ramp(device, n=31): + """Short ramp kernel used in the denoiser loss (shape of what back-projection sees).""" + k = torch.arange(-n, n + 1, device=device, dtype=torch.float32) + w = torch.zeros_like(k) + odd = k.abs() % 2 == 1 + w[odd] = -1 / (torch.pi * k[odd]) ** 2 + w[n] = 0.25 + return w * 4 + + +def ramp_columns(x, kernel): + return F.conv1d(x.reshape(-1, 1, x.shape[-1]), kernel[None, None], padding=len(kernel) // 2).reshape(x.shape) diff --git a/proj2rep/report.py b/proj2rep/report.py new file mode 100644 index 0000000000000000000000000000000000000000..34b7029112d40b4a7a0cc2a3b7d0dc464ca64b21 --- /dev/null +++ b/proj2rep/report.py @@ -0,0 +1,91 @@ +"""Cross-validated report: agreement with the teacher by region and manufacturer, pooled over folds. + +Agreement is the variance of the teacher's routine-dose slab embedding explained by a route (R², +averaged over the 512 features), with 95% intervals from a case-level bootstrap. + + python -m proj2rep report --data DATA --work WORK +Writes WORK/report/agreement.csv, WORK/report/stress.csv and prints both tables. +""" + +import argparse +from pathlib import Path + +import numpy as np +import pandas as pd + +from .data import load_cohort + + +def r2(x, t): + return float(np.mean(1 - ((x - t) ** 2).sum(0) / ((t - t.mean(0)) ** 2).sum(0))) + + +def bootstrap(parts, keys, b=500, seed=0): + """parts: {case: {key: (n, 512)}}; {key: (estimate, low, high, cases)} for each route against teacher_full, + each route scored on every case that has it.""" + rng = np.random.default_rng(seed) + out = {} + for k in keys: + cases = [c for c in parts if k in parts[c]] + if not cases: + continue + + def stat(who, k=k): + return r2(np.concatenate([parts[c][k] for c in who]), np.concatenate([parts[c]["teacher_full"] for c in who])) + + draws = [stat(rng.choice(cases, len(cases))) for _ in range(b)] + out[k] = (stat(cases), *np.quantile(draws, [0.025, 0.975]), len(cases)) + return out + + +def load_parts(work, sub, cohort): + parts = {} + for f in sorted((Path(work) / sub).glob("fold*/*.npz")): + if f.stem in set(cohort.ids()): + with np.load(f) as d: + parts[f.stem] = {k: d[k] for k in d.files if not k.endswith("_regions")} + return parts + + +def table(parts, cohort, keys): + t = cohort.table.set_index("case_id") + groups = {"all": list(parts)} + for (reg, man), g in t.loc[list(parts)].groupby(["region", "manufacturer"]): + groups[f"{reg} / {man}"] = g.index.tolist() + rows = [] + for name, ids in groups.items(): + sub = {c: parts[c] for c in ids} + for k, (est, lo, hi, n) in bootstrap(sub, [k for k in keys if any(k in v for v in sub.values())]).items(): + rows.append({"group": name, "route": k, "cases": n, "r2": est, "low": lo, "high": hi}) + return pd.DataFrame(rows) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + a = p.parse_args(argv) + cohort = load_cohort(a.data, work_dir=a.work) + out = Path(a.work) / "report" + out.mkdir(parents=True, exist_ok=True) + pd.set_option("display.width", 200) + + ev = load_parts(a.work, "eval", cohort) + if ev: + t = table(ev, cohort, ["raw_full", "raw_low", "teacher_low"]) + t.to_csv(out / "agreement.csv", index=False) + print("Held-out agreement with the teacher (R²):") + print(t.pivot_table(index="group", columns="route", values="r2", sort=False).round(3).to_string(), "\n") + + st = load_parts(a.work, "stress", cohort) + if st: + keys = sorted({k for v in st.values() for k in v if k.startswith(("raw_", "plain_"))}) + t = table(st, cohort, keys) + t[["route", "condition"]] = t.route.str.split("_", n=1, expand=True) + t.to_csv(out / "stress.csv", index=False) + print("Stress test (R² against the teacher on the routine-dose image):") + print(t.pivot_table(index=["group", "condition"], columns="route", values="r2", sort=False).round(3).to_string()) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/stress.py b/proj2rep/stress.py new file mode 100644 index 0000000000000000000000000000000000000000..5a4cba8de9d70e4fb0831e296b627a01457055ab --- /dev/null +++ b/proj2rep/stress.py @@ -0,0 +1,104 @@ +"""Stress test of one fold's held-out cases: lower dose and fewer views than routine. + +Two routes per condition, both scored against the teacher on the routine-dose scanner image: + raw measurements -> fold denoiser -> back-projection -> fold encoder + plain measurements -> back-projection -> frozen teacher (reconstruct, then encode) +Dose levels are reached by scaling the supplied noise (proj_low - proj_full) to the target dose +fraction. View conditions keep every k-th view of the routine-dose scan. + + torchrun --nproc_per_node 8 -m proj2rep stress --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors +""" + +import argparse +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F + +from . import dist +from .data import load_cohort, slab_rows, to_input +from .evaluate import embed +from .geometry import SIZE, Conventions, Geometry, reconstruct, sparse +from .models import denoise_scan, load_teacher, teach +from .train_denoiser import load as load_denoiser +from .train_denoiser import noise_scale +from .train_encoder import load as load_encoder + +DOSES = (1.0, 0.25, 0.1, 0.05, 0.025) +VIEWS = (2, 4, 8) + + +def conditions(case): + out = [("views", k) for k in VIEWS] + if case.has("proj_low") and case.low_dose_fraction: + out = [("dose", d) for d in DOSES] + out + else: + out = [("dose", 1.0)] + out + return out + + +def label(kind, value): + return f"{kind}_{value:g}" + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + p.add_argument("--fold", type=int, required=True) + p.add_argument("--teacher", required=True) + a = p.parse_args(argv) + + rank, world, device = dist.init() + work = Path(a.work) + cohort = load_cohort(a.data, work_dir=work) + _, held = cohort.split(a.fold) + teacher, enc, dn = load_teacher(a.teacher, device), load_encoder(work, a.fold, device), load_denoiser(work, a.fold, device) + conv = Conventions(work / "convention.json") + out = work / "stress" / f"fold{a.fold}" + out.mkdir(parents=True, exist_ok=True) + + def run_encoder(x): + with torch.autocast("cuda", dtype=torch.bfloat16): + return enc(x.to(device).contiguous(memory_format=torch.channels_last_3d)) + + def run_teacher(x): + return teach(teacher, x.to(device)) + + for case in cohort.cases(held)[rank::world]: + cid = case.id + path = out / f"{cid}.npz" + if path.exists(): + continue + geo = Geometry(case) + zs = geo.image_z[geo.valid()] + z = case.grid() + res = {"z0": z, "teacher_full": embed(run_teacher, [case.image_slab(z0) for z0 in z])[0]} + # Where the scanner image holds padding instead of data (outside its reconstruction circle), + # the plain route is blanked too, so both of the teacher's inputs cover the same field. + scanner = torch.from_numpy(np.asarray(case.array("image_full")[geo.valid()], dtype=np.float32)) + blank = (F.interpolate(scanner[:, None], (SIZE, SIZE), mode="area")[:, 0] < -1500).to(device) + full = np.asarray(case.array("proj_full"), dtype=np.float32) + noise = np.asarray(case.array("proj_low"), dtype=np.float32) - full if case.has("proj_low") else None + for kind, value in conditions(case): + if kind == "dose": + s = 0.0 if value == 1 else noise_scale(case.low_dose_fraction, value) + g, data = geo, (full + s * noise if s else full) + else: + g, data = sparse(geo, value), np.ascontiguousarray(full[::value]) + for route, vol in (("raw", reconstruct(g, denoise_scan(dn, data, device), zs, device, conv(geo))), + ("plain", reconstruct(g, data, zs, device, conv(geo)).masked_fill(blank, -1024))): # fmt: skip + slabs = [] + for z0 in z: + rows, flip = slab_rows(zs, z0) + x = vol[rows].float().cpu() + slabs.append(to_input(x.flip(0) if flip else x)) + res[f"{route}_{label(kind, value)}"] = embed(run_encoder if route == "raw" else run_teacher, slabs)[0] + np.savez_compressed(path, **res) + print(f"[rank {rank}] stress fold {a.fold}: {cid}", flush=True) + dist.done(sync=False) + + +if __name__ == "__main__": + main() diff --git a/proj2rep/train_denoiser.py b/proj2rep/train_denoiser.py new file mode 100644 index 0000000000000000000000000000000000000000..e4869c51813dbee4163800f4a6df8c038519b2c1 --- /dev/null +++ b/proj2rep/train_denoiser.py @@ -0,0 +1,128 @@ +"""Train the measurement denoiser for one cross-validation fold. + +Reduced-dose line integrals -> routine-dose line integrals of the same acquisition. Training +spans a continuous dose range by scaling the supplied noise (proj_low - proj_full) to a random +dose fraction, and optionally keeps only every 2nd, 4th or 8th view (sparse acquisitions). +Loss: L1 on the line integrals plus L1 after a ramp filter along detector columns. + + torchrun --nproc_per_node 8 -m proj2rep train-denoiser --data DATA --work WORK --fold 0 +""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader, Dataset + +from . import dist +from .data import load_cohort +from .models import CLIP, Denoiser, ramp_columns, short_ramp + +CROP = (24, 32, 512) # views, rows, columns + + +def noise_scale(supplied, fraction): + """Multiple of the supplied noise whose variance matches `fraction` of routine dose.""" + return float(np.sqrt((1 / fraction - 1) / (1 / supplied - 1))) + + +class Crops(Dataset): + """Random crops of one fixed shape from every case, so scanners with different detectors batch together.""" + + def __init__(self, cases, n, seed, min_dose, views): + self.cases, self.n, self.seed, self.min_dose, self.views = cases, n, tuple(seed), min_dose, views + shapes = np.array([c.array("proj_full").shape for c in cases]) + cols = min(CROP[2], int(shapes[:, 2].min())) + self.shape = (CROP[0], min(CROP[1], int(shapes[:, 1].min())), cols - cols % 2) + + def __len__(self): + return self.n + + def __getitem__(self, i): + rng = np.random.default_rng((*self.seed, i)) + case = self.cases[rng.integers(len(self.cases))] + full, low = case.array("proj_full"), case.array("proj_low") + nv, nr, nc = self.shape + k = int(rng.choice([k for k in self.views if nv * k <= full.shape[0]] or [1])) + v = int(rng.integers(0, full.shape[0] - nv * k + 1)) + r, c = int(rng.integers(0, full.shape[1] - nr + 1)), int(rng.integers(0, full.shape[2] - nc + 1)) + s = (slice(v, v + nv * k, k), slice(r, r + nr), slice(c, c + nc)) + y, x = torch.from_numpy(full[s].astype(np.float32)), torch.from_numpy(low[s].astype(np.float32)) + f = float(np.exp(rng.uniform(np.log(self.min_dose), np.log(0.6)))) + a = 0.0 if rng.random() < 0.1 else noise_scale(case.low_dose_fraction, f) + x = y + a * (x - y) + for d in (0, 1, 2): + if rng.random() < 0.5: + x, y = x.flip(d), y.flip(d) + return x[None], y[None] + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + p.add_argument("--fold", type=int, required=True, help="cross-validation fold; -1 trains on every case") + p.add_argument("--steps", type=int, default=8000) + p.add_argument("--batch", type=int, default=8, help="global batch (split across GPUs)") + p.add_argument("--lr", type=float, default=3e-4) + p.add_argument("--min-dose", type=float, default=0.02, help="lowest simulated dose fraction") + p.add_argument("--views", type=int, nargs="+", default=[1, 1, 2, 4, 8], help="view-keeping factors to draw from") + p.add_argument("--workers", type=int, default=8) + a = p.parse_args(argv) + + rank, world, device = dist.init() + work = Path(a.work) + cohort = load_cohort(a.data, work_dir=work) + train, _ = cohort.split(a.fold) + cases = [c for c in cohort.cases(train, image=False) if c.has("proj_low") and c.low_dose_fraction] + if not cases: + raise SystemExit("no training case has proj_low and low_dose_fraction") + out = work / "denoiser" + out.mkdir(parents=True, exist_ok=True) + torch.manual_seed(a.fold + 1) + model = Denoiser().to(device) + if world > 1: + model = DDP(model, device_ids=[device.index]) + opt = torch.optim.AdamW(model.parameters(), a.lr, weight_decay=1e-4) + sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05) + per = max(a.batch // world, 1) + data = Crops(cases, a.steps * per, (a.fold + 1, rank), a.min_dose, a.views) + loader = DataLoader(data, per, num_workers=a.workers, drop_last=True, persistent_workers=a.workers > 0) + kernel = short_ramp(device) + dist.log(rank, f"fold {a.fold}: {len(cases)} training cases, {world} GPU(s), batch {per}/GPU") + start, hist = time.time(), [] + for step, (x, y) in enumerate(loader): + x, y = x.to(device), y.to(device).clamp(-1, CLIP) + with torch.autocast("cuda", dtype=torch.bfloat16): + pred = model(x).float() + loss = F.l1_loss(pred, y) + F.l1_loss(ramp_columns(pred, kernel), ramp_columns(y, kernel)) + opt.zero_grad(set_to_none=True) + loss.backward() + nn.utils.clip_grad_norm_(model.parameters(), 1.0) + opt.step() + sched.step() + hist.append(loss.item()) + if step % 100 == 99: + dist.log(rank, f"denoiser fold {a.fold} step {step + 1} loss {np.mean(hist[-100:]):.4f} {time.time() - start:.0f}s") + if rank == 0: + net = model.module if world > 1 else model + torch.save(net.state_dict(), out / f"fold{a.fold}.pt") + (out / f"fold{a.fold}.json").write_text(json.dumps({"steps": a.steps, "batch": a.batch, "cases": len(cases), + "seconds": time.time() - start}, indent=1) + "\n") # fmt: skip + dist.done() + + +def load(work, fold, device): + model = Denoiser().to(device) + model.load_state_dict(torch.load(Path(work) / "denoiser" / f"fold{fold}.pt", map_location=device, weights_only=True)) + return model.eval() + + +if __name__ == "__main__": + main() diff --git a/proj2rep/train_encoder.py b/proj2rep/train_encoder.py new file mode 100644 index 0000000000000000000000000000000000000000..81e9cace842a5d01e24522929de1564f9a481287 --- /dev/null +++ b/proj2rep/train_encoder.py @@ -0,0 +1,248 @@ +"""Train the measurement encoder for one cross-validation fold. + +Input: a 36 mm slab of the denoised back-projection (from `proj2rep bank`) at a random dose level +and view fraction. Target: the frozen teacher's slab and regional embeddings of the scanner's +routine-dose image of the same slab. The encoder starts from the teacher's weights. Both inputs +get the same random mirror, in-plane zoom and shift. Half of the slabs are placed with an edge on +a slice position, as the evaluation grid is (--snap-z). + +Multi-GPU: DistributedDataParallel with synchronised BatchNorm; each GPU draws its own slabs. +Training state is saved every --save-every steps and resumed automatically. + + torchrun --nproc_per_node 8 -m proj2rep train-encoder --data DATA --work WORK --fold 0 --teacher ct_fm.safetensors +""" + +import argparse +import json +import time +from pathlib import Path + +import numpy as np +import torch +import torch.nn.functional as F +from torch import nn +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.utils.data import DataLoader, Dataset + +from . import dist +from .bank import bank_dir +from .data import HALF, group_of, load_cohort, slab_rows, to_input +from .models import Encoder, load_teacher, teach + + +class BankSlabs: + """Denoised back-projections of one case at the levels and view fractions on disk.""" + + def __init__(self, case, folder): + self.case, self.dir, self.z, self.files = case, folder, np.load(folder / "z_mm.npy"), {} + + def vol(self, level, k): + if (level, k) not in self.files: + self.files[level, k] = np.load(self.dir / f"{level}_v{k}.npy", mmap_mode="r") + return self.files[level, k] + + def has(self, level, k): + return (self.dir / f"{level}_v{k}.npy").exists() + + def slab(self, z0, u=0.0, k=1, mirror=False): + """Dose position u: 0 routine, 1 supplied low dose, 2 lowest level; linear in between.""" + rows, flip = slab_rows(self.z, z0) + + def get(level): + return torch.from_numpy(np.array(self.vol(level, k)[rows], dtype=np.float32)) + + if u <= 0: + x = get("full") + elif u <= 1: + x = get("full") + x = x + u * (get("low") - x) + else: + x = get("low") + x = x + (u - 1) * (get("min") - x) + x = to_input(x.flip(0) if flip else x) + return x.flip(-1) if mirror else x + + +class Slabs(Dataset): + def __init__(self, sources, n, seed, a, offset=0): + """Sample i is drawn from seed and offset + i, so a resumed run continues the same stream.""" + self.sources, self.n, self.seed, self.a, self.offset = sources, n, seed, a, offset + + def __len__(self): + return self.n + + def __getitem__(self, i): + a, rng = self.a, np.random.default_rng((*self.seed, self.offset + i)) + src = self.sources[rng.integers(len(self.sources))] + lo, hi = src.case.slab_range + z0, mirror = snap(rng.uniform(lo, hi), src.z, lo, hi, rng.random() < a.snap_z), bool(rng.integers(2)) + views = [k for k in a.views if src.has("full", k)] if not group_of(src.case, a.no_thin) else [1] + views = views or [1] + k = int(rng.choice(views, p=view_weights(views))) + top = a.max_dose_level if k == 1 else min(a.max_dose_level, 1.0) + if not src.has("low", k): + top = 0.0 + if top > 1 and not src.has("min", 1): + top = 1.0 + u = 0.0 if rng.random() < a.clean else float(rng.uniform(0, top)) + return src.slab(z0, u, k, mirror), src.case.image_slab(z0, mirror) + + +def snap(z0, z, lo, hi, on=True): + """Nearest slab centre whose edge lies exactly on a slice position. + + Evaluation slabs start at the first slice, so their edges fall on slices whenever the slice + spacing divides the slab length, and such a slab holds one slice more than a slab at a random + position. Training half of the slabs this way keeps both kinds in distribution. + """ + if not on: + return z0 + edge = np.concatenate([z + HALF, z - HALF]) + edge = edge[(edge >= lo) & (edge <= hi)] + return float(edge[np.abs(edge - z0).argmin()]) if len(edge) else z0 + + +def view_weights(views): + """All views (k = 1) on 40% of slabs, the thinned fractions sharing the rest.""" + if len(views) == 1: + return None + w = np.array([0.4 if k == 1 else 0.6 / (len(views) - (1 in views)) for k in views]) + return w / w.sum() + + +def field_of_view(x, y, gen, zoom=(0.8, 1.2), move=0.2): + """Same random in-plane zoom and shift for input and target; half of the batch unchanged.""" + n = len(x) + scale = torch.where(torch.rand(n, generator=gen) < 0.5, torch.ones(n), torch.empty(n).uniform_(*zoom, generator=gen)) + shift = (torch.rand(n, 2, generator=gen) - 0.5) * move * (scale != 1)[:, None] + theta = torch.zeros(n, 3, 4) + theta[:, 0, 0], theta[:, 1, 1], theta[:, 2, 2] = scale, scale, 1 + theta[:, 0, 3], theta[:, 1, 3] = shift[:, 0], shift[:, 1] + g = F.affine_grid(theta.to(x.device), x.shape, align_corners=False) + return F.grid_sample(x, g, align_corners=False), F.grid_sample(y, g, align_corners=False) + + +def target_stats(teacher, sources, n, device, seed): + """Mean and spread of the teacher embeddings, for a balanced loss across features.""" + rng = np.random.default_rng(seed) + s, r = [], [] + for _ in range(n // 8): + xs = [] + for _ in range(8): + src = sources[rng.integers(len(sources))] + lo, hi = src.case.slab_range + xs.append(src.case.image_slab(rng.uniform(lo, hi))) + u, w = teach(teacher, torch.stack(xs).to(device)) + s.append(u) + r.append(w.flatten(0, 1)) + s, r = torch.cat(s), torch.cat(r) + return torch.stack([s.mean(0), s.std(0).clamp_min(1e-4), r.mean(0), r.std(0).clamp_min(1e-4)]) + + +def main(argv=None): + p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("--data", required=True) + p.add_argument("--work", required=True) + p.add_argument("--fold", type=int, required=True, help="cross-validation fold; -1 trains on every case") + p.add_argument("--teacher", required=True, help="CT-FM feature extractor weights (.safetensors)") + p.add_argument("--steps", type=int, default=16000) + p.add_argument("--batch", type=int, default=16, help="global batch (split across GPUs)") + p.add_argument("--lr", type=float, default=1e-4) + p.add_argument("--views", type=int, nargs="+", default=[1, 2, 4, 8], help="view fractions to train on") + p.add_argument("--max-dose-level", type=float, default=1.0, help="1: down to the supplied low dose; 2: down to the bank's min level") + p.add_argument("--clean", type=float, default=0.15, help="share of slabs at routine dose") + p.add_argument("--no-thin", nargs="*", default=[], help="REGION:MANUFACTURER groups trained at all views only") + p.add_argument("--snap-z", type=float, default=0.5, help="share of slabs placed with an edge exactly on a slice") + p.add_argument("--stats", type=int, default=800, help="slabs used for the target statistics") + p.add_argument("--save-every", type=int, default=500) + p.add_argument("--workers", type=int, default=8) + a = p.parse_args(argv) + + rank, world, device = dist.init() + work = Path(a.work) + cohort = load_cohort(a.data, work_dir=work) + train, _ = cohort.split(a.fold) + sources = [BankSlabs(c, bank_dir(work, a.fold, c.id)) for c in cohort.cases(train)] + missing = [s.case.id for s in sources if not s.has("full", 1)] + if missing: + raise SystemExit(f"no bank for {len(missing)} training cases (e.g. {missing[0]}); run `proj2rep bank --fold {a.fold}` first") + if 1 not in a.views: + raise SystemExit("--views must include 1 (all views)") + out = work / "encoder" + out.mkdir(parents=True, exist_ok=True) + name, resume = f"fold{a.fold}", out / f"fold{a.fold}.resume.pt" + + teacher = load_teacher(a.teacher, device) + stats = torch.zeros(4, 512, device=device) + if rank == 0: + stats = target_stats(teacher, sources, max(a.stats, 64), device, a.fold + 1) + sm, ss, rm, rs = dist.broadcast(stats) + + torch.manual_seed(a.fold + 1) + model = Encoder(a.teacher).to(device) + if world > 1: + model = nn.SyncBatchNorm.convert_sync_batchnorm(model) + model = model.to(memory_format=torch.channels_last_3d) + opt = torch.optim.AdamW(model.parameters(), a.lr, weight_decay=0.01) + sched = torch.optim.lr_scheduler.OneCycleLR(opt, a.lr, total_steps=a.steps, pct_start=0.05) + gen = torch.Generator() + first = 0 + if resume.exists(): + state = torch.load(resume, map_location=device, weights_only=False) + if state.get("steps", a.steps) != a.steps or state.get("batch", a.batch) != a.batch: + raise SystemExit( + f"{resume} was saved with --steps {state.get('steps')} --batch {state.get('batch')}; use the same or delete it" + ) + model.load_state_dict(state["model"]) + opt.load_state_dict(state["opt"]) + sched.load_state_dict(state["sched"]) + first = state["step"] + dist.log(rank, f"resumed {resume} at step {first}") + net = DDP(model, device_ids=[device.index]) if world > 1 else model + + per = max(a.batch // world, 1) + data = Slabs(sources, (a.steps - first) * per, (a.fold + 1, rank), a, offset=first * per) + loader = DataLoader( + data, per, num_workers=a.workers, drop_last=True, persistent_workers=a.workers > 0, prefetch_factor=4 if a.workers else None + ) + dist.log(rank, f"encoder fold {a.fold}: {len(sources)} training cases, {world} GPU(s), batch {per}/GPU, steps {first}..{a.steps}") + net.train() + start, hist = time.time(), [] + for step, (x, image) in enumerate(loader, start=first): + gen.manual_seed(1_000_003 * (a.fold + 1) + 1000 * step + rank) # per-step seed: identical after a resume + x, image = field_of_view(x.to(device), image.to(device), gen) + ts, tr = teach(teacher, image) + with torch.autocast("cuda", dtype=torch.bfloat16): + ps, pr = net(x) + loss = F.mse_loss((ps - sm) / ss, (ts - sm) / ss) + F.mse_loss((pr - rm) / rs, (tr - rm) / rs) + opt.zero_grad(set_to_none=True) + loss.backward() + nn.utils.clip_grad_norm_(net.parameters(), 5.0) + opt.step() + sched.step() + hist.append(loss.item()) + if step % 100 == 99: + dist.log(rank, f"encoder fold {a.fold} step {step + 1} loss {np.mean(hist[-100:]):.4f} {time.time() - start:.0f}s") + if (step + 1) % a.save_every == 0 and step + 1 < a.steps and rank == 0: + torch.save({"model": model.state_dict(), "opt": opt.state_dict(), "sched": sched.state_dict(), "step": step + 1, + "steps": a.steps, "batch": a.batch}, + resume.with_suffix(".tmp")) # fmt: skip + resume.with_suffix(".tmp").replace(resume) + if rank == 0: # SyncBatchNorm keeps BatchNorm's parameter names, so the weights load into a plain Encoder + torch.save(model.state_dict(), out / f"{name}.pt") + resume.unlink(missing_ok=True) + meta = {k: v for k, v in vars(a).items() if k not in ("data", "work", "teacher")} + (out / f"{name}.json").write_text( + json.dumps({**meta, "cases": len(sources), "gpus": world, "seconds": time.time() - start}, indent=1) + "\n" + ) + dist.done() + + +def load(work, fold, device): + model = Encoder().to(device) + model.load_state_dict(torch.load(Path(work) / "encoder" / f"fold{fold}.pt", map_location=device, weights_only=True)) + return model.eval().to(memory_format=torch.channels_last_3d) + + +if __name__ == "__main__": + main() diff --git a/readout.py b/readout.py new file mode 100644 index 0000000000000000000000000000000000000000..e2b4ccf4cd88b4d6895d33d898d6eff17267d810 --- /dev/null +++ b/readout.py @@ -0,0 +1,38 @@ +"""Apply a trained residual readout to v12 leave-one-manufacturer-out slab features.""" + +import argparse +from pathlib import Path + +import numpy as np + + +def predict(head, features, view_stride): + strides = head["view_strides"].tolist() + if view_stride not in strides: + raise ValueError(f"view stride must be one of {strides}") + x = np.asarray(features, dtype=np.float32) + if x.ndim != 2 or x.shape[1] != 512 or not len(x) or not np.isfinite(x).all(): + raise ValueError("expected finite slab features with shape (slabs, 512)") + i = strides.index(view_stride) + return x + head["bias"][i] + (x - head["input_mean"][i]) @ head["matrix"][i] + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("head", type=Path) + parser.add_argument( + "features", type=Path, help="Numpy .npy matrix from the matching base encoder" + ) + parser.add_argument("output", type=Path, help="output .npy file") + parser.add_argument("--view-stride", type=int, required=True, choices=[1, 2, 4, 8]) + args = parser.parse_args() + with np.load(args.head, allow_pickle=False) as head: + result = predict( + head, np.load(args.features, allow_pickle=False), args.view_stride + ) + with args.output.open("wb") as stream: + np.save(stream, result) + + +if __name__ == "__main__": + main() diff --git a/refined/README.md b/refined/README.md new file mode 100644 index 0000000000000000000000000000000000000000..62841de1c818d3e849e2f590b7a35920330b162f --- /dev/null +++ b/refined/README.md @@ -0,0 +1,18 @@ +# Proj2Rep-Refined + +Current release: RC3. + +## Selected routine-dose, full-view results + +Manufacturer-adaptation evaluation on 117 patients; both support draws use the same evaluation patients. + +| Group | Patients | Adaptive r (95% CI) | Refined r (95% CI) | Refined R² | +|---|---:|---|---|---:| +| GE chest | 29 | 0.952 (0.946–0.957) | 0.955 (0.949–0.961) | 0.906 | +| GE abdomen | 29 | 0.913 (0.893–0.934) | 0.923 (0.912–0.934) | 0.846 | +| Siemens chest | 30 | 0.938 (0.926–0.950) | 0.958 (0.953–0.964) | 0.913 | +| Siemens abdomen | 29 | 0.931 (0.921–0.938) | 0.942 (0.933–0.948) | 0.881 | + +![Routine-dose results](../figures/routine_results.png) + +See the [main model card](../README.md) for confidence intervals, model selection, input preparation and inference commands. diff --git a/refined/ge/draw0.pt b/refined/ge/draw0.pt new file mode 100644 index 0000000000000000000000000000000000000000..1458b1e4efe950249d500c22687ec997e9b98a27 --- /dev/null +++ b/refined/ge/draw0.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54b290e77a01bab1fe3feab0cd41d11910d51b88550ed8b73a4b2290a4bfb370 +size 311152534 diff --git a/refined/ge/draw1.pt b/refined/ge/draw1.pt new file mode 100644 index 0000000000000000000000000000000000000000..843abf2a7c739e8c758db0a6df8c85782cde5a07 --- /dev/null +++ b/refined/ge/draw1.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:19bd30de60567dbeea90174fd2cf853a5dc58d95ad90fe5e31757d87162d4ffd +size 311152534 diff --git a/refined/siemens/draw0.pt b/refined/siemens/draw0.pt new file mode 100644 index 0000000000000000000000000000000000000000..287499120b5258e9331782813444d687f76efb57 --- /dev/null +++ b/refined/siemens/draw0.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fe224da48c0e9cfe50e657abcf86146d1ca945202770ae0cd6bc49ae5b18aed4 +size 311152534 diff --git a/refined/siemens/draw1.pt b/refined/siemens/draw1.pt new file mode 100644 index 0000000000000000000000000000000000000000..10001fc9e9259de2760e5247192607992f01e525 --- /dev/null +++ b/refined/siemens/draw1.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:95dba94ad1e89eb33087382ef588a496c1a5c6e1da8b666487a7f3b09d2b2085 +size 311152534 diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..90c8644fbb16ad3fe0ac9f35df1893f68547b91a --- /dev/null +++ b/requirements.txt @@ -0,0 +1,6 @@ +numpy>=1.26 +torch>=2.4 +monai>=1.4 +pandas>=2.0 +scikit-learn>=1.4 +safetensors>=0.4 diff --git a/results/adaptation.csv b/results/adaptation.csv new file mode 100644 index 0000000000000000000000000000000000000000..3303812ea34b05dd46b8d9f24eb8c06e5528da2f --- /dev/null +++ b/results/adaptation.csv @@ -0,0 +1,5 @@ +study,group,patients,slabs,condition,parent_valid_features,parent_bootstrap_min_valid_features,refined_valid_features,refined_bootstrap_min_valid_features,adapter_valid_features,adapter_bootstrap_min_valid_features,parent_r,parent_r_low,parent_r_high,parent_r2,parent_r2_low,parent_r2_high,refined_r,refined_r_low,refined_r_high,refined_r2,refined_r2_low,refined_r2_high,adapter_r,adapter_r_low,adapter_r_high,adapter_r2,adapter_r2_low,adapter_r2_high,refined_vs_parent_r,refined_vs_parent_r_low,refined_vs_parent_r_high,refined_vs_parent_r2,refined_vs_parent_r2_low,refined_vs_parent_r2_high,refined_vs_adapter_r,refined_vs_adapter_r_low,refined_vs_adapter_r_high,refined_vs_adapter_r2,refined_vs_adapter_r2_low,refined_vs_adapter_r2_high +adaptation,GE chest,29,647,dose_1,512,512,512,512,512,512,0.9550879715385698,0.9489905323064995,0.960465861861422,0.8973765578767845,0.8839058546858828,0.906491743373648,0.9554279598760448,0.9493556961988944,0.960751541065372,0.9060427598029516,0.891861197276571,0.9153448492998758,0.9516654357899068,0.945677519367974,0.9570476611085034,0.8998037367927791,0.8837521883566416,0.910124049222391,0.000339988337475,0.0002787139769619,0.0004089691722405,0.0086662019261669,0.0069738634965612,0.0106159915303808,0.003762524086138,0.0017786297642147,0.0058032684676756,0.0062390230101723,-0.0003676436881682,0.0131519813769972 +adaptation,GE abdomen,29,924,dose_1,512,512,512,512,512,512,0.9230994506765576,0.91194561590447,0.9336895885737688,0.8228115882141327,0.7947251154040291,0.8383282252340106,0.9233281936530278,0.9121684542353512,0.9338870245076536,0.8456723943233793,0.8163901588684818,0.8630014346923339,0.9126579938346104,0.8925041214694136,0.9339475105097936,0.8159694545820955,0.7431106648457237,0.863107346967509,0.0002287429764701,0.0001741530287477,0.0002887749603357,0.0228608061092465,0.0185161774116865,0.0283337755374078,0.0106701998184172,-0.0009098877853069,0.0223717482185527,0.0297029397412837,-0.0033477171571473,0.0758507550523946 +adaptation,Siemens chest,30,777,dose_1,512,512,512,512,512,512,0.9582389190020996,0.9523824154553894,0.9634930972498066,0.9072045121290724,0.8928638987830987,0.9166974005517884,0.9584301308512596,0.9526239221492686,0.9637011935513174,0.9126512672407836,0.8990541623379379,0.9216806310130315,0.9384814146129148,0.9259021402798148,0.9498997405208848,0.8702281399209092,0.8425818922793354,0.8881778944504884,0.0001912118491602,0.0001415507384945,0.0002421830639756,0.0054467551117111,0.0041801371308876,0.0070213684747736,0.019948716238345,0.0126980508847662,0.0281862363532002,0.0424231273198743,0.0294470712890926,0.0607833391533863 +adaptation,Siemens abdomen,29,1084,dose_1,512,512,512,512,512,512,0.9417213647823504,0.9327638809539835,0.9475990413806248,0.8641718347080913,0.8404573444295045,0.8762442393364571,0.941910571074621,0.9329444497070648,0.94778068524672,0.880538137572463,0.8602264511212354,0.8905911871085697,0.9310710712451746,0.9212985108258748,0.9379626545429464,0.8559259507134158,0.8313899086819027,0.8680070879218493,0.0001892062922704,0.0001304676522541,0.0002526978299999,0.0163663028643716,0.0132542307005848,0.0212707756255176,0.0108394998294463,0.0081799513177831,0.0135714870445707,0.0246121868590472,0.0182899140796043,0.0333015904856012 diff --git a/results/cv.csv b/results/cv.csv new file mode 100644 index 0000000000000000000000000000000000000000..0e723c69f96c10a4b2e49df40a17f7228587c1f4 --- /dev/null +++ b/results/cv.csv @@ -0,0 +1,5 @@ +study,group,patients,slabs,condition,measurement_valid_features,measurement_bootstrap_min_valid_features,image_valid_features,image_bootstrap_min_valid_features,frozen_valid_features,frozen_bootstrap_min_valid_features,measurement_r,measurement_r_low,measurement_r_high,measurement_r2,measurement_r2_low,measurement_r2_high,image_r,image_r_low,image_r_high,image_r2,image_r2_low,image_r2_high,frozen_r,frozen_r_low,frozen_r_high,frozen_r2,frozen_r2_low,frozen_r2_high,measurement_vs_image_r,measurement_vs_image_r_low,measurement_vs_image_r_high,measurement_vs_image_r2,measurement_vs_image_r2_low,measurement_vs_image_r2_high,measurement_vs_frozen_r,measurement_vs_frozen_r_low,measurement_vs_frozen_r_high,measurement_vs_frozen_r2,measurement_vs_frozen_r2_low,measurement_vs_frozen_r2_high +cv,chest,99,2413,dose_1,512,512,512,512,512,512,0.969748886327772,0.9673087303057244,0.972038312474074,0.9401635506514808,0.9350347266332082,0.9443545336585032,0.9679194398297056,0.965500570874818,0.9701735213047014,0.9364990511826724,0.9314027244927996,0.94065528948041,0.8784918143511478,0.8677401525076096,0.8875673772725636,0.5495751751817909,0.5122673250539928,0.5796268204394361,0.0018294464980663,0.001391779396042,0.0022613125379918,0.0036644994688085,0.0027846456299426,0.0045889144326482,0.0912570719766243,0.0828064771861441,0.1008735550078521,0.3905883754696899,0.3603321358388512,0.426303453843903 +cv,abdomen,98,3427,dose_1,512,512,512,512,512,512,0.9591056320587068,0.955358274450444,0.9622422144059792,0.9194822274483444,0.9118750202461008,0.9251018572645884,0.9568266713100152,0.953170265155456,0.9599566478425618,0.9147822834501472,0.9072766922954336,0.920282414364686,0.7351928999971533,0.7183543736095569,0.7530719801458099,-1.3668672063004457,-1.6071076697701965,-1.1739842921577734,0.0022789607486913,0.0018046374176617,0.002763354823079,0.0046999439981972,0.0038295436033276,0.0056372369181459,0.2239127320615533,0.2065711595685837,0.2390916130770732,2.28634943374879,2.0949346376390103,2.519567016068352 +cv,abdomen GE,49,1569,dose_1,512,512,512,512,512,512,0.9441739334338706,0.9376815690012842,0.9495145649452772,0.890281018285924,0.8766542584194589,0.8991460883339022,0.9414553089755416,0.9350331804639088,0.9466700490395862,0.884540738617456,0.8709363547643499,0.8933519137141149,0.7815457636702221,0.7592875955696763,0.8032293888782551,-1.4700154868476203,-1.7967752942586928,-1.2183787001924422,0.0027186244583288,0.0017969553305585,0.0037666415490127,0.005740279668468,0.0038342816999419,0.0082412919607702,0.1626281697636484,0.1446893946592687,0.1799666567655436,2.3602965051335447,2.1116121490469104,2.681411635525278 +cv,abdomen Siemens,49,1858,dose_1,512,512,512,512,512,512,0.9562148933696016,0.9506582455542169,0.9605188462326576,0.9132628142894754,0.9013337948417012,0.920886762943132,0.9537547394976726,0.948189829918064,0.9582358373153688,0.9076953977710936,0.8959364376546824,0.9152291014417534,0.7630494571749475,0.7425156233419626,0.7819886403215134,-2.1351445935043447,-2.7126209459217985,-1.7623764681284848,0.0024601538719289,0.0018259393139417,0.0031498178075771,0.0055674165183818,0.0041770447682541,0.007198656707668,0.1931654361946541,0.1764079128014433,0.2101641896705186,3.04840740779382,2.6767986974495783,3.624348744396354 diff --git a/results/overall.csv b/results/overall.csv new file mode 100644 index 0000000000000000000000000000000000000000..bb97699c4b302d6da2a59c622941d18248596bc2 --- /dev/null +++ b/results/overall.csv @@ -0,0 +1,2 @@ +study,group,patients,slabs,condition,parent_r,parent_r_low,parent_r_high,parent_r2,parent_r2_low,parent_r2_high,refined_r,refined_r_low,refined_r_high,refined_r2,refined_r2_low,refined_r2_high,adapter_r,adapter_r_low,adapter_r_high,adapter_r2,adapter_r2_low,adapter_r2_high,refined_vs_parent_r,refined_vs_parent_r_low,refined_vs_parent_r_high,refined_vs_parent_r2,refined_vs_parent_r2_low,refined_vs_parent_r2_high,refined_vs_adapter_r,refined_vs_adapter_r_low,refined_vs_adapter_r_high,refined_vs_adapter_r2,refined_vs_adapter_r2_low,refined_vs_adapter_r2_high +adaptation,equal-group mean,117,3432,dose_1,0.9445369264998944,0.9404511433397889,0.9481211276249942,0.8728911232320202,0.861705492159437,0.8780184429689213,0.9447742138637384,0.940680463326096,0.9483688815602972,0.8862261397348943,0.8752473538595775,0.891571352087534,0.9334689788706516,0.9270776663680896,0.9400370073720072,0.8604818205022999,0.8391168125029644,0.8729795438280004,0.0002372873638439,0.000211337668489,0.000267972533945,0.013335016502874,0.0120233900276411,0.0154138138039883,0.0113052349930866,0.0077035254099066,0.0145476483121485,0.0257443192325944,0.0165586418984158,0.0384828664339115 diff --git a/universal/README.md b/universal/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cbae8544b7f16387865df4b9fdf85b176bf2cc4f --- /dev/null +++ b/universal/README.md @@ -0,0 +1,18 @@ +# Proj2Rep-Universal + +Current release: RC3. + +## Selected routine-dose, full-view results + +Five-fold held-out recipe evaluation on 197 patients; the released checkpoint uses all development scans. + +| Group | Patients | Measurement r (95% CI) | Trained image r | Measurement R² | +|---|---:|---|---:|---:| +| Chest | 99 | 0.970 (0.967–0.972) | 0.968 | 0.940 | +| Abdomen | 98 | 0.959 (0.955–0.962) | 0.957 | 0.919 | +| Abdomen Ge | 49 | 0.944 (0.938–0.950) | 0.941 | 0.890 | +| Abdomen Siemens | 49 | 0.956 (0.951–0.961) | 0.954 | 0.913 | + +![Routine-dose results](../figures/routine_results.png) + +See the [main model card](../README.md) for confidence intervals, model selection, input preparation and inference commands. diff --git a/universal/convention.json b/universal/convention.json new file mode 100644 index 0000000000000000000000000000000000000000..a9bef110e1f4546d91de1b3892d336e2a7c79280 --- /dev/null +++ b/universal/convention.json @@ -0,0 +1,14 @@ +{ + "GE": [ + 1, + 2, + 1, + -1 + ], + "SIEMENS": [ + 1, + 2, + 1, + 1 + ] +} diff --git a/universal/denoiser/fold-1.pt b/universal/denoiser/fold-1.pt new file mode 100644 index 0000000000000000000000000000000000000000..aeac63560c8fb4324d16c8125b2d7aed66b401ff --- /dev/null +++ b/universal/denoiser/fold-1.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:0137ad63d179564db3f0f98ae1e95ee02b47acfedd379c799fd17026a8094a70 +size 10145213 diff --git a/universal/encoder/fold-1.pt b/universal/encoder/fold-1.pt new file mode 100644 index 0000000000000000000000000000000000000000..32c5ae7b9e9427babbbf94d080d3f5d2bfbcb26c --- /dev/null +++ b/universal/encoder/fold-1.pt @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:7db86f41211e06d9f460c1cedd3dd83079d6c24773d798e21e7dbba4381985b2 +size 311148769