Metadata-Version: 2.4
Name: diff-fvr
Version: 1.1.1
Summary: Differentiable Fourier Volume Rendering (Diff-FVR & PoU-FVR) for fast biplanar 3D-2D X-ray registration on CPU and GPU
Author-email: Pareel Amre <pareel.amre@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/pareelamre/diff-fvr
Project-URL: Repository, https://github.com/pareelamre/diff-fvr
Project-URL: Issues, https://github.com/pareelamre/diff-fvr/issues
Keywords: digitally-reconstructed-radiographs,fourier-volume-rendering,3d-2d-registration,spine-surgery,medical-imaging,image-guided-interventions
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Science/Research
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: numpy>=1.24.0
Requires-Dist: scipy>=1.10.0
Requires-Dist: pandas>=2.0.0
Requires-Dist: matplotlib>=3.7.0
Requires-Dist: pillow>=9.5.0
Requires-Dist: pydicom>=2.4.0
Requires-Dist: simpleitk>=2.2.0
Requires-Dist: scikit-image>=0.20.0
Provides-Extra: torch
Requires-Dist: torch>=2.0.0; extra == "torch"
Provides-Extra: gpu
Requires-Dist: torch>=2.0.0; extra == "gpu"
Requires-Dist: triton>=2.1.0; sys_platform == "linux" and extra == "gpu"
Dynamic: license-file

# Diff-FVR: Differentiable Fourier Volume Rendering

Research software for parallel-beam digitally reconstructed radiographs (DRRs)
and biplanar 3D–2D registration. It precomputes a padded 3D Fourier transform,
extracts a 2D frequency slice for each pose, and compares candidate projections
using a spectral similarity objective. Optional modules explore gradients,
articulated spine models, metal masking, and PyTorch acceleration.

**Research prototype. Clinical accuracy and suitability for surgical navigation
have not been established by the experiments in this repository.**

Author: Pareel Amre · TU Dresden · `pareel.amre@gmail.com`
License: [MIT](https://github.com/pareelamre/diff-fvr/blob/master/LICENSE)

## What the experiments establish

The `experiments/` directory contains 31 numbered simulation, real C-arm
fluoroscopy, and NVIDIA A100 GPU benchmark studies (plus the `9b` magnification
approximation). These explore rendering speed and fidelity, registration
convergence, noise, occlusion, truncation, articulation, motion, PyTorch/Triton/`CUDAGraph`
acceleration, and multi-subject clinical cohort registration.

Experiments 7, 12, and 13 each use one source CT volume and multiple randomized
poses. Their target images are generated by the same Fourier renderer used by
the optimizer, with optional synthetic noise. They are **same-renderer simulation
tests**, not registration against acquired fluoroscopy and not a multi-patient
clinical validation. Other stress tests simulate selected image effects; their
results do not demonstrate real-world robustness. mTRE uses eight synthetic
volume landmarks, not annotated anatomical landmarks.

Historical CSVs and figures in `outputs/paper_figures/` predate the physical-unit
correction. CT-derived error values were computed in voxels while labeled mm;
derived success rates and accuracy claims must be regenerated. The previous
README's numerical accuracy and speed claims are withdrawn pending verified
reruns with documented units, hardware, and an independent projection reference.
See [result limitations](https://github.com/pareelamre/diff-fvr/blob/master/outputs/paper_figures/README.md).

## Real Paired C-Arm & DiffDRR Benchmark (Experiments 25–26)

Experiments `25` and `26` evaluate Diff-FVR against **DiffDRR 0.6.1** (Siddon
cone-beam raycasting) on real paired pelvic CT + physical C-arm fluoroscopy
(`DeepFluoro`, `subject01`–`subject06`) with ground-truth `SE(3)` poses
and 3D anatomical fiducials (`128×128` interior crop, CPU):

- **Forward Speed & Perspective Fidelity (`exp25`, `subject01`, 10 views):**
  `10.9 ms` mean single-DRR latency (`~92 FPS`) vs. `1153.8 ms` (`~0.87 FPS`)
  for DiffDRR `0.6.1` (**`106x`** mean speedup), with `NCC(Diff-FVR, DiffDRR) = 0.9213–0.9863`
  (mean `0.9676`).
- **Bi-Planar Real C-Arm Registration (`exp25`, `subject01`, 4 pairs, init `9.69 mm`):**
  Diff-FVR (35 steps) runs in `1.9 s` (`7.04 mm` mean mTRE); a coarse-to-fine
  **Hybrid** (`30 Diff-FVR + 15 DiffDRR`) reaches `5.93 mm` in `62.1 s`, matching
  pure DiffDRR (`5.95 mm` in `103.3 s`) with `40%` lower runtime.
- **Multi-Subject Cohort (`exp26`, `subject01`–`subject06`, `N=6`):**
  **`88.3x`** mean forward speedup (`14.7 ms` vs. `1248.1 ms`), mean
  `NCC(Diff-FVR, DiffDRR) = 0.9550`, `2.24 s` mean Diff-FVR registration
  (`6.04 mm`), and `3.41 mm` Hybrid (`123.27 s`) vs. `3.73 mm` DiffDRR (`157.97 s`).

## NVIDIA A100 GPU Benchmark, PoU-FVR Pareto Ablation (`exp29`), & Multi-Start Registration (`exp30`)

`experiments/exp29_gpu_triton_and_ablation.py` (verified on **NVIDIA A100-SXM4-40GB**,
commit `53158de`, `Triton=True`, zero OOM entries across all 135 `(H, B, method)` cells)
benchmarks SE(3)-invariant ray-cached, fused-Triton (`pou_pinhole_warp_sum`), and
`CUDAGraph`-captured `PoU-FVR` across `H ∈ {128, 200, 256, 512}` and `B ∈ {1, 16, 64}`
against DiffDRR and `nanodrr` (`n=500` and `n=200` PyTorch and Triton/`torch.compile`
kernels), with sequential micro-batching (`[mb=16]`) automatically engaged only where
`nanodrr torch` at `512×512, B=64` would otherwise exceed 40 GB VRAM (`93.75 GiB` unchunked):

- **Cone-Beam Forward Latency & Memory (`PoU-FVR Triton+CUDAGraph` / `PoU-FVR Triton`, `2×2×2` bf16, `0.394 s` 3D FFT prep):**
  - `256×256, B=1`: **`0.108 ms`** `CUDAGraph` (`9,254 FPS`) / `1.241 ms` eager (`5.0 MB`) — **`152x`** faster than `DiffDRR f32` (`16.425 ms`, `2,581.5 MB`), **`6.5x`** faster than `nanodrr triton+compile (n=500)` (`0.707 ms`), and **`5.3x`** faster than `n=200` (`0.570 ms`).
  - `256×256, B=64`: **`1.969 ms`** `CUDAGraph` (`32,501 FPS`) / `2.703 ms` eager (`320.0 MB`) — **`58.7x`** faster than `nanodrr torch` (`115.53 ms`, `32,144 MB`), **`7.25x`** faster than `nanodrr triton+compile (n=500)` (`14.28 ms`), and **`3.06x`** faster than `n=200` (`6.03 ms`).
  - `512×512, B=1`: **`0.114 ms`** `CUDAGraph` (`8,738 FPS`) — **`11.8x`** faster than `nanodrr triton+compile (n=500)` (`1.352 ms`) and **`7.3x`** faster than `n=200` (`0.835 ms`).
  - `512×512, B=16`: **`0.576 ms`** `CUDAGraph` (`27,773 FPS`) / `1.386 ms` eager (`80.0 MB`) — **`195x`** faster than `nanodrr torch` (`112.42 ms`, `32,145 MB`) and **`24.7x`** faster than `nanodrr triton+compile (n=500)` (`14.24 ms`).
  - `512×512, B=64`: **`2.415 ms`** `CUDAGraph` (`26,506 FPS`) / `3.163 ms` eager (`320.0 MB`) — **`185x`** faster than `nanodrr torch [mb=16]` (`446.13 ms`, `32,193 MB`), **`23.0x`** faster than `nanodrr triton+compile (n=500)` (`55.43 ms`), and **`9.4x`** faster than `n=200` (`22.65 ms`).
- **Full End-to-End Differentiable `fwd+bwd` Training Throughput (`PoU-FVR Triton` vs. `nanodrr triton n=500`):**
  - `256×256, B=16`: **`4.270 ms`** (`80.0 MB`) vs. `10.318 ms` (**`2.42x`**).
  - `256×256, B=64`: **`7.074 ms`** (`320.0 MB`) vs. `38.836 ms` (**`5.49x`**).
  - `512×512, B=16`: **`6.137 ms`** (`80.0 MB`) vs. `38.628 ms` (**`6.29x`**).
  - `512×512, B=64`: **`21.843 ms`** (`320.0 MB`) vs. `150.999 ms` (**`6.91x`**).
- **Parallel-Beam Dual-Domain Loss (`TorchDiffFVR Zero-IFFT NCC`, zero-IFFT in loop):**
  Sustains `0.666–1.294 ms` up to `256×256, B=64` (`49,454 FPS`, `96.0 MB`) and
  `3.470 ms` at `512×512, B=64` (`18,445 FPS`, `384.0 MB`).
- **PoU-FVR Block / Resolution Pareto Ablation (`H=256×256, sdd=1020 mm`, `B=1`):**
  Across `1×1×1` (`0.63–0.98 MB`, `1.20 ms`, `NCC=0.921–0.934`), `2×2×2` (`2.82–7.82 MB`,
  `1.22–1.23 ms`, `NCC=0.926–0.942`), `2×4×2 @ 48–96` (`5.63–22.50 MB`, `1.23–1.26 ms`,
  `NCC=0.932–0.955`, `EdgeNCC=0.508–0.746`), and `4×4×2 @ 80` (`31.25 MB`, `1.26 ms`,
  **`NCC=0.9633`**, `EdgeNCC=0.7319`), fused-Triton forward latency stays nearly flat at
  `1.20–1.26 ms` vs. synthetic ray-marching ground truth.
- **Bi-Planar `B=64` Multi-Start GPU Registration (`exp30`, 10 DeepFluoro trials, mean init `15.79 mm`, 50 steps):**
  With `warmup_pinhole` and dynamic Triton loops eliminating Trial-1 cold-start recompilation (`2.129 s` on Trial 1):
  - `PoU-FVR Triton (2×4×2@80 bf16)`: **`0.950 mm`** mean mTRE (`0.848 mm` median), **`100% < 2 mm`**, **`2.161 s`** mean (`2.11–2.20 s` across all 10 trials), `1,348 MB` peak VRAM (**`2.79x`** faster than `nanodrr triton+compile`).
  - `Hybrid PoU-Triton + nanodrr polish`: **`1.495 mm`** mean mTRE (`1.475 mm` median), **`100% < 2 mm`**, **`1.341 s`** mean (`1.15–1.24 s` steady-state), `464 MB` peak VRAM (**`4.50x`** faster than `nanodrr triton+compile`).
  - `nanodrr triton+compile (bf16 n=500)`: `1.503 mm` mean mTRE, `100% < 2 mm`, `6.035 s` mean, `355 MB` peak VRAM.
  - `nanodrr torch (f32 n=500)`: **`OOM`** at `B=64` during autograd on all trials.
- **6-Subject Real Clinical DeepFluoro GPU Cohort (`exp31`, `subject01`–`subject06`, `18` trials, mean init `12.00 mm`, `H=256, B=64`):**
  True-pose cone-beam forward parity spans `NCC = 0.9782–0.9986` across all 6 patients.
  - `Hybrid PoU-Triton + DiffDRR polish`: **`1.069 mm`** mean mTRE (`0.938 mm` median), **`100.0%` (`18/18`) `< 2 mm`** and **`100.0% < 5 mm`**, **`1.818 s`** mean (`1.034 mm`, `0.873 mm` median, `100% < 2 mm` on `n=15` wide-angle pairs `> 15 deg`).
  - `PoU-FVR Triton Multi-Start (B=64)`: **`1.786 mm`** mean mTRE (`1.907 mm` median), `50.0% < 2 mm`, **`100.0% < 5 mm`**, `2.110 s` mean, **`1,348.0 MB`** peak VRAM (**`4.07x` less VRAM** than DiffDRR).
  - `DiffDRR Single-Start (f32 B=1)`: `7.216 mm` mean mTRE (`3.130 mm` median), `50.0% < 2 mm`, `61.1% < 5 mm`, `3.259 s` mean, `5,490.8 MB` peak VRAM (trapped at `11.0–21.1 mm` on out-of-basin starts).
  Full CSVs are saved in [outputs/exp29_gpu_benchmark.csv](https://github.com/pareelamre/diff-fvr/blob/master/outputs/exp29_gpu_benchmark.csv),
  [outputs/exp29_pou_ablation.csv](https://github.com/pareelamre/diff-fvr/blob/master/outputs/exp29_pou_ablation.csv),
  [outputs/exp30_gpu_multistart_reg.csv](https://github.com/pareelamre/diff-fvr/blob/master/outputs/exp30_gpu_multistart_reg.csv),
  [outputs/exp30_gpu_multistart_summary.csv](https://github.com/pareelamre/diff-fvr/blob/master/outputs/exp30_gpu_multistart_summary.csv),
  [outputs/exp31_deepfluoro_gpu_cohort.csv](https://github.com/pareelamre/diff-fvr/blob/master/outputs/exp31_deepfluoro_gpu_cohort.csv), and
  [outputs/exp31_deepfluoro_gpu_summary.csv](https://github.com/pareelamre/diff-fvr/blob/master/outputs/exp31_deepfluoro_gpu_summary.csv).

## Projection geometry and physical units

- `RobustDiffFVREngine` accepts a **cubic, isotropic** volume and spacing
  `(Z, Y, X)` in mm. Its poses use `(yaw, pitch, roll, tx, ty, tz)`, with
  rotations in degrees and translations/bounds in **mm**.
- The CLI preserves CT spacing while resampling to an isotropic cube that fits
  the longest physical dimension. NPY input contains HU values and defaults to
  one mm per voxel; use `--spacing-mm Z Y X` when this differs. DICOM spacing
  comes from its metadata.
- AP projects along Y, with X horizontal and Z vertical. Lateral projects along
  X, with Y horizontal and Z vertical. Targets must already match the rendered
  image shape, orientation, pixel spacing, and field of view. Arbitrary acquired
  X-rays are not automatically calibrated, rescaled, or registered in patient
  DICOM coordinates.
- This is a **parallel-beam** engine. SDD/SAD settings now raise an error rather
  than being silently ignored. `render_calibrated_drr` retains its legacy name
  for compatibility; it performs no cone-beam or perspective correction.
  Experiment 9b's isocenter scaling is an approximation, not a general calibration
  model. Full cone-beam geometry requires a separate implementation and validation.
- Low-level NumPy renderers, the original experimental registration engines, and
  gradients retain their existing **voxel-coordinate** conventions.
  They do not share the robust core's mm API. `compute_mtre_6dof` returns mm when
  passed measured `spacing`; use `translation_units='mm'` for robust-core poses,
  or the default `'voxels'` for low-level poses. Omitted spacing assumes 1 mm.
  The optional Torch backend is a separate experimental implementation; physical
  coordinate parity with the robust core has not been established.

Compatibility changes: the robust core interprets translations as mm even when
spacing differs from 1 mm; explicit SDD/SAD configuration is rejected.
`fvr.cli.load_volume` now returns `(attenuation_volume, spacing_zyx_mm)`.
Failed CLI optimization writes `success: false` and exits with status 1;
optimizer convergence alone does not establish registration accuracy.

## Install and try a simulation

```bash
pip install -e .

# Generate two synthetic targets on the same grid (parallel-beam model).
fvr-render --ct data/dicom --res 96 --view ap --tx 4 --ty 2 --tz 3 --out outputs/example_ap.png
fvr-render --ct data/dicom --res 96 --view lateral --tx 4 --ty 2 --tz 3 --out outputs/example_lat.png

# Recover the pose from those simulated targets.
fvr-register --ct data/dicom --res 96 --ap outputs/example_ap.png --lat outputs/example_lat.png --out outputs/example_pose.json

# Focused synthetic regressions and CT-based integration smoke test.
python tests/test_physical_units.py
python tests/test_core_engine.py
```

Optional Torch support: `pip install -e '.[torch]'`. Run its tests with
`python tests/test_torch_engine.py`; CUDA availability is environment dependent.

The [browser demonstration](https://pareelamre.github.io/diff-fvr/) is a scripted
illustration with synthetic images and an interpolated convergence animation.
It does not execute the Python registration engine or measure clinical accuracy.

## Repository

`src/fvr/` contains renderers, registration, metrics, DICOM loading and CLI code;
`tests/` contains synthetic regressions and integration scripts; `experiments/`
contains simulation studies; `docs/` contains the illustrative browser demo;
`outputs/exp29_*.csv`, `outputs/exp30_*.csv`, and `outputs/exp31_*.csv` store
the verified NVIDIA A100 GPU benchmark, PoU-FVR Pareto, multi-start registration, and 6-subject DeepFluoro cohort tables;
`outputs/paper_figures/` contains historical generated results.
