Metadata-Version: 2.4
Name: pyconvert
Version: 0.1.0a1
Summary: PyConveRT: convert radiotherapy treatment data between clinical DICOM/NIfTI and machine-learning-ready arrays, preserving geometry and semantics in both directions.
Author-email: Author One <author-one@example.org>, Author Two <author-two@example.org>
License: MIT
Project-URL: Homepage, https://github.com/MUW-AIRO/pyconvert
Project-URL: Bug Tracker, https://github.com/MUW-AIRO/pyconvert/issues
Project-URL: Documentation, https://github.com/MUW-AIRO/pyconvert#readme
Keywords: radiotherapy,radiation therapy,DICOM,NIfTI,preprocessing,machine learning,medical imaging
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Science/Research
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: pandas
Requires-Dist: numpy
Requires-Dist: pydicom>=3.0
Requires-Dist: scipy
Requires-Dist: scikit-image
Requires-Dist: scikit-learn
Requires-Dist: pydantic
Requires-Dist: pydantic-settings
Requires-Dist: rich
Requires-Dist: SimpleITK
Requires-Dist: opencv-python
Requires-Dist: nibabel>=5.3.3
Provides-Extra: dev
Requires-Dist: pytest>=8.4.2; extra == "dev"
Requires-Dist: ruff>=0.6.0; extra == "dev"
Requires-Dist: mypy>=1.11.0; extra == "dev"
Requires-Dist: pytest-cov>=5.0.0; extra == "dev"
Provides-Extra: viewer
Requires-Dist: PySide6>=6.8.2; extra == "viewer"
Requires-Dist: pyqtgraph>=0.14.0; extra == "viewer"
Dynamic: license-file

# PyConveRT — Radiotherapy Data Conversion for Machine Learning

[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
[![CI](https://github.com/MUW-AIRO/pyconvert/actions/workflows/ci.yml/badge.svg)](https://github.com/MUW-AIRO/pyconvert/actions/workflows/ci.yml)

PyConveRT converts radiotherapy treatment data **both ways** between clinical DICOM/NIfTI exports and machine-learning-ready formats. The **forward** path reads DICOM (CT, MR, RTDOSE, RTSTRUCT, RTPLAN) or NIfTI, harmonises the region-of-interest (ROI) names that differ between institutions and planning systems, resamples volumes to a user-specified isocentric grid, and writes NumPy `.npy` / NIfTI `.nii.gz` arrays plus JSON plan representations. The **reverse** path writes those ML-ready outputs back to valid, coherent DICOM. It is the data-transfer and conversion layer that feeds and receives from downstream machine learning — it contains no ML itself.

---

## Features

- **Multi-modality support** — CT, MR, RTDOSE, RTSTRUCT, RTPLAN from DICOM or NIfTI sources
- **Batch preprocessing** — `Preprocessor` class iterates over a patient directory tree
- **Isocentric resampling** — centre on the plan isocenter, a structure's centre of mass, or explicit coordinates
- **ROI harmonisation** — map structure names onto canonical names by exact lookup in an explicit ROI map across treatment planning systems via a JSON config
- **UID graph** — tracks DICOM UID references between modalities, enabling consistency checks
- **NIfTI round-trip** — load from NIfTI, preprocess, and save back to NIfTI; NIfTI files written by pyconvert (such as the ProstArc dataset) carry their DICOM identity in a header and load without any config; other NIfTI data load via a file-mapping config
- **DICOM reverse path** — write a preprocessed case back to a coherent DICOM case (CT, RTSTRUCT, RTPLAN, RTDOSE sharing one Study / Frame of Reference / Patient) via `write_case_dicom`; round-trip regression tests reconstruct the pixel, dose, mask and plan data within per-type tolerances (lossless for discrete labels and plan fields, int16/uint16 quantisation for CT/dose)
- **Interactive visualiser** — optional PySide6/PyQtGraph viewer (beam's-eye view, DVH, multi-planar CT/dose/structures) for DICOM and pyconvert NIfTI/JSON cases

---

## Installation

### Core library

```bash
git clone https://github.com/MUW-AIRO/pyconvert.git
cd pyconvert
pip install .
```

### With development tools (pytest)

```bash
pip install ".[dev]"
```

### With the interactive visualiser

```bash
pip install ".[viewer]"
```

> **Python ≥ 3.11** is required.

---

## Data Flow

```
DICOM files / NIfTI files
        │
        ▼
    DataReader          reads & filters files by SOP class
        │
        ▼
  Modality handlers     per-modality preprocessing and resampling
  ┌─────────────┬───────────────┬──────────────┬──────────────┐
  │  CT / MR    │   Dose        │ StructureSet │    Plan      │
  │  (Image)    │   (Dose)      │ (StructureSet│ (PlanHandler)│
  └─────────────┴───────────────┴──────────────┴──────────────┘
        │                                             │
        │                                    Beam / ControlPoint
        ▼
    Case                groups handlers for one treatment episode
        │
        ▼
  .nii.gz / .npy        ML-ready arrays on disk
  + plan .json          plan, beams, control points
        │
        ▼  reverse path (write_case_dicom)
  DICOM                 CT, RTSTRUCT, RTPLAN, RTDOSE as one coherent case
```

---

## Quick Start

The examples run from the root of a repository checkout on the bundled MrAlderson phantom
(`tests/example_data/dicom/MrAlderson`, two cases). With an installed package, pass your own data
and config paths (the default configs ship in `pyconvert/utils/`).

### High-level: preprocessing a single DICOM case

```python
from pathlib import Path
from pyconvert.case import Case

case = Case.from_dicom(
    dicom_path=Path("tests/example_data/dicom/MrAlderson/Case1/"),
    modalities=["CT", "RTDOSE", "RTSTRUCT", "RTPLAN"],
    roi_config_path=Path("src/pyconvert/utils/dcm_roi_config.json"),
)

# Resample to a 128³ grid centred on the plan isocenter
case.preprocess_all(
    config_path=Path("src/pyconvert/utils/config_small.json"),
    isocenter="plan",
)

# Save as NIfTI
case.save_all_nifti(save_path=Path("output/MrAlderson/Case1/"))
```

### High-level: batch preprocessing a directory

```python
from pathlib import Path
from pyconvert.preprocess import Preprocessor

preproc = Preprocessor(input_folder="tests/example_data/dicom/", source_format="dicom")

summary = preproc.process_all_cases(
    output_folder=Path("output/"),
    config_path=Path("src/pyconvert/utils/config_small.json"),
    isocenter="plan",
    modalities=["CT", "RTDOSE", "RTSTRUCT", "RTPLAN"],
    roi_config_path=Path("src/pyconvert/utils/dcm_roi_config.json"),
    save_format="nifti",
)

print(f"Processed {summary['successful']}/{summary['total']} cases successfully")
```

### High-level: loading a ProstArc case (NIfTI/JSON)

Cases of the ProstArc dataset, and any NIfTI/JSON written by pyconvert, load from the pyconvert
headers in their files, without a config:

```python
from pathlib import Path
from pyconvert.case import Case

case = Case.from_nifti(nifti_path=Path("ProstArc/<patient>/<case>/"))

case.preprocess_all(
    config_path=Path("src/pyconvert/utils/config_small.json"),
    isocenter="plan",
)
case.save_all_nifti(save_path=Path("output/<patient>/<case>/"))
```

NIfTI data not written by pyconvert need a config whose `file_mapping` names the CT, dose and mask
files (see `src/pyconvert/utils/nifti_roi_config.json`), passed as `roi_config_path`.

### Mid-level: using individual handlers

For finer control, handlers can be used directly without a `Case`:

```python
from pathlib import Path
import numpy as np
from pyconvert.handlers.image import CT
from pyconvert.handlers.dose import Dose
from pyconvert.handlers.structure_set import StructureSet
from pyconvert.handlers.plan.plan_handler import Plan

DICOM_PATH = Path("tests/example_data/dicom/MrAlderson/Case1/")
OUTPUT_PATH = Path("output/MrAlderson/Case1/")

ISOCENTER = np.array([5.15, -174.82, -608.73])  # mm
OUTPUT_SIZE = np.array([128, 128, 128])
VOXEL_SIZE = np.array([3.125, 3.125, 3.125])    # mm

# CT
ct = CT.from_dicom(DICOM_PATH)[0]
ct.preprocess(isocenter=ISOCENTER, output_volume_size=OUTPUT_SIZE, output_voxel_size=VOXEL_SIZE)
ct.save_nifti(OUTPUT_PATH)

# Dose
dose = Dose.from_dicom(DICOM_PATH)[0]
dose.preprocess(isocenter=ISOCENTER, output_volume_size=OUTPUT_SIZE, output_voxel_size=VOXEL_SIZE)
dose.save_nifti(OUTPUT_PATH)

# Structure set
structs = StructureSet.from_dicom(
    dicom_series_path=DICOM_PATH,
    roi_config_path=Path("src/pyconvert/utils/dcm_roi_config.json"),
)[0]
structs.preprocess(isocenter=ISOCENTER, output_volume_size=OUTPUT_SIZE, output_voxel_size=VOXEL_SIZE)
structs.save_nifti(OUTPUT_PATH)

# Plan
plan = Plan.from_dicom(DICOM_PATH)[0]
plan.preprocess(config_path=Path("src/pyconvert/utils/config_small.json"))
plan.save_json(OUTPUT_PATH)
```

### Writing a case back to DICOM

```python
from pyconvert.writers.reverse_case import write_case_dicom

# CT slices, RTSTRUCT, RTPLAN and RTDOSE (plus beam doses) sharing one Study,
# Frame of Reference and patient. "reuse" keeps the case's UIDs; "generate" mints new ones.
write_case_dicom(case, "output/MrAlderson/Case1_dicom/", mode="reuse")
```

A case loaded from NIfTI/JSON (`Case.from_nifti`) is written back the same way.

### VMAT control-point sampling

By default a plan keeps its raw control points (`interpolate=False`). Passing
`interpolate=True` resamples each VMAT beam's control points onto a uniform
gantry-angle grid. Interpolated angles use the **native RayStation / IEC / DICOM
convention** — the same convention as the raw path and the source DICOM (no
offset) — and an arc that crosses gantry 0/360 is handled correctly.

Choose one sampling mode (kwargs override the matching config key):

```python
# Equidistant count (config NUM_POINTS is the default)
plan.preprocess(config_path=CONFIG, interpolate=True, num_points=180)

# Equidistant angular spacing (uniform density; per-arc counts vary)
plan.preprocess(config_path=CONFIG, interpolate=True, spacing_deg=2.0)

# Explicit target angles (non-equidistant allowed; "keep original" via source angles)
plan.preprocess(config_path=CONFIG, interpolate=True, angles=[181.0, 200.0, 250.0])
```

By default each beam is sampled over its own true arc extent (first → last gantry
angle), which produces no padding. Optionally pin a fixed absolute window applied
to every beam ("map every plan onto a full arc"): control points inside the real
arc are interpolated active, and grid points in the pinned window but outside the
real arc become **inactive padding** (`IsActive=False`, boundary-copied). With a
non-divisible `spacing_deg` window the final interval is shortened to land on the
stop angle and a warning is logged.

```python
plan.preprocess(
    config_path=CONFIG, interpolate=True, spacing_deg=1.0,
    start_angle=0.0, stop_angle=360.0,       # pinned full-arc window
    neutralize_inactive_cps=True,            # blank padding apertures to a closed sentinel
)
```

`neutralize_inactive_cps` is an ML-representation option (padding keeps its
boundary-flat cumulative meterset weight but its aperture — every present
beam-limiting device — is blanked so it cannot be misread as a delivered
aperture); the default boundary copy is the
reverse-path-safe behaviour. The optional config keys `SPACING_DEG`,
`START_ANGLE`, `STOP_ANGLE` and `NEUTRALIZE_INACTIVE` set the same knobs from the
JSON config (absent keys preserve the `NUM_POINTS` default).

### Interactive visualiser

The viewer (BEV, DVH, MPR) needs the `viewer` extra (`pip install "pyconvert[viewer]"`). Open a
case from the command line, from a DICOM folder or a pyconvert NIfTI/JSON folder:

```bash
python -m pyconvert.visualizer --dicom tests/example_data/dicom/MrAlderson/Case1
python -m pyconvert.visualizer --nifti /path/to/released/case
```

Without `--roi-config` every structure is shown under its original name; with a config, DICOM
ROIs are restricted to and renamed by its aliases. From Python:

```python
from pathlib import Path
from pyconvert.visualizer.app import launch_from_processed_dir

launch_from_processed_dir(Path("output/MrAlderson/Case1/"))
```

Or from a loaded `Case`:

```python
from pyconvert.visualizer.app import launch_from_case

launch_from_case(case)
```

---

## Configuration

Preprocessing parameters are controlled by a JSON config file: the output grid
(`OUTPUT_SIZE` in voxels, `VOXEL_SIZE` in mm, both x, y, z) and the plan options
(`INTERPOLATE_PLAN`, `NUM_POINTS`, `SPACING_DEG`, `START_ANGLE`, `STOP_ANGLE`,
`NEUTRALIZE_INACTIVE`, see above; `NUM_LEAVES`):

```json
{
    "OUTPUT_SIZE": [128, 128, 128],
    "VOXEL_SIZE": [3.125, 3.125, 3.125],
    "INTERPOLATE_PLAN": false,
    "NUM_POINTS": 180,
    "NUM_LEAVES": 80
}
```

Two example configs are provided:

| Config | Volume (voxels) | Voxel size (mm) |
|---|---|---|
| `config_small.json` | 128 × 128 × 128 | 3.125 × 3.125 × 3.125 |
| `config_large.json` | 128 × 128 × 320 | 3.125 × 3.125 × 1.25 |

### ROI configuration

Structure name harmonisation is driven by a JSON file that lists, per canonical name, the
institution-specific names mapped onto it (`roi_definitions`: `canonical_name`, `synonyms`,
`color`). Matching is an exact lookup; a structure not in the map is left out, and two structures
mapping to the same canonical name raise an error. Without a ROI config every structure is kept
under its original name. See `src/pyconvert/utils/dcm_roi_config.json` (DICOM) and
`nifti_roi_config.json` (NIfTI file mapping) for examples.

---

## Project Structure

```
src/pyconvert/
├── case.py              # Case: single treatment episode (DICOM or NIfTI)
├── preprocess.py        # Preprocessor: batch pipeline
├── constants.py         # Modality enum and shared constants
├── patient.py           # Patient: groups multiple Cases
├── handlers/            # Per-modality forward pipelines (read + preprocess + store)
│   ├── abstract_type.py     Base class for all handlers
│   ├── data_reader.py       DICOM file reader and SOP-class filter
│   ├── image.py             CT and MR image handling
│   ├── dose.py              RTDOSE handling
│   ├── structure_set.py     RTSTRUCT + ROI harmonisation
│   └── plan/                RTPLAN modality (aggregate root + parts + algorithms)
│       ├── plan_handler.py      RTPLAN handling (Plan aggregate root)
│       ├── beam.py              Beam and control-point model
│       ├── control_point.py     Single control-point representation
│       └── interpolation.py     VMAT control-point sampling
├── writers/            # Reverse path: write a processed Case back to DICOM
├── uid/                # UID graph, UID sets, and NIfTI UID extensions
├── rt_utils/           # Adapted from qurit/rt-utils (MIT)
├── utils/              # Config loading, geometry, grid_data container, ROI configs
└── visualizer/         # Optional PySide6/PyQtGraph viewer

example_scripts/        # Runnable examples on the bundled phantom (handlers, Case, batch,
                        # resampling a released case, reverse path, dataset export)
tests/                  # unit/, integration/, smoke/ (golden files), visualizer/
```

---

## Running Tests

```bash
# All public tests
python -m pytest tests/unit tests/integration tests/smoke -v

# Unit tests only
python -m pytest tests/unit -v

# Exclude tests that require confidential local datasets
python -m pytest -m "not requires_lund and not requires_sweden"

# Viewer tests (need the viewer extra)
python -m pytest tests/visualizer
```

See [TESTING.md](TESTING.md) for the full test guide.

---

## Dataset

PyConveRT ships with a small committed phantom (`tests/example_data/dicom/MrAlderson`)
so every example runs offline.

**Publicly available on Zenodo: the phantom only.** A single de-identified phantom
will be published on Zenodo for citation and quick experimentation. This is the *only*
part of the data hosted on Zenodo — the full clinical dataset is **not**.

> **Placeholder** — the Zenodo record is not yet minted. The record ID, DOI, and
> link below are placeholders and are filled in on publication.

- **Phantom (Zenodo):** `https://doi.org/10.5281/zenodo.PLACEHOLDER` — *DOI placeholder*

**Full dataset — access-controlled, not on Zenodo.** The complete clinical dataset
is not distributed through Zenodo.
Qualified researchers must first sign a **data-transfer agreement (DTA)**; once it
is in place, access is granted through a separate secure internal file-transfer
system. Contact the authors (see `pyproject.toml`) to start the DTA process.

### Released format and resampling

Each released ProstArc case is one folder of NIfTI + plan JSON on its native grids: `CT_<uid>.nii.gz`
(HU), `Dose_0_<uid>.nii.gz` (plan dose, Gy) and `Dose_<n>_<uid>.nii.gz` (beam doses, if any),
one `mask_<ROI>_<uid>.nii.gz` per structure on the CT grid, and `plan_<uid>.json`. Every file
carries its source DICOM identity in a pyconvert header, so `Case.from_nifti(<case folder>)`
loads the case without any config.

`resample_dataset.py` loads one released case and resamples it onto the isocentric grid of a
config (`OUTPUT_SIZE`, `VOXEL_SIZE`), centred on the plan isocentre or a
structure's centre of mass. Without `--data-dir` it first writes the bundled phantom in the
released format, so it runs offline:

```bash
python example_scripts/resample_dataset.py
# on a released case:
python example_scripts/resample_dataset.py --data-dir /path/to/dataset/<patient>/<case> \
    --output-dir ./resampled --config src/pyconvert/utils/config_large.json --isocenter plan
```

---

## Citation

> **Placeholder** — final citation and DOI added on publication (arXiv pending).
> The BibTeX below is provisional; the version, year, and a DOI will be filled in
> when the paper and archival record are released.

If you use PyConveRT in your research, please cite:

```bibtex
@software{pyconvert_PLACEHOLDER,
  author  = {Author One and Author Two},  % PLACEHOLDER: real authors added on publication
  title   = {{PyConveRT}: Radiotherapy Data Conversion for Machine Learning},
  year    = {PLACEHOLDER},
  url     = {https://github.com/MUW-AIRO/pyconvert},
  license = {MIT},
}
```

A `CITATION.cff` file is also provided for automated citation tools.

---

## Contributing

Contributions are welcome! See [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on setting up the development environment, running tests, and submitting pull requests.

---

## Acknowledgements

The `src/pyconvert/rt_utils/` subpackage is adapted from
[**rt-utils**](https://github.com/qurit/rt-utils) by the Qurit Lab, BC Cancer
Research Institute, released under the MIT License. See [NOTICE](NOTICE) for
full attribution.

---

## License

This project is licensed under the MIT License — see the [LICENSE](LICENSE) file for details.
