Proj2Rep-CTFM / USAGE.md
markjiang1's picture
Optimized release: verified metadata, download instructions and package structure
76eb7b3
|
Raw History Blame Contribute Delete
13.3 kB

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.

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).

git clone <this repository> 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 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:

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:

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:

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 <step> --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<F>.pt       trained encoders        WORK/denoiser/fold<F>.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:

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.

7. Encode new scans

Prepare the new scans the same way (images are not needed β€” only image.json to set the output grid), then:

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/<scan>.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

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.

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
  <case_id>/
    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