Skip to main content
Pre-release

This release is a pre-release and may not be stable for production use.

PyConveRT — Radiotherapy Data Conversion for Machine Learning

Python 3.11+ License: MIT CI

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

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

With development tools (pytest)

pip install ".[dev]"

With the interactive visualiser

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

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

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:

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:

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

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

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

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:

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:

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:

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

{
    "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

# 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 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:

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:

@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 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 by the Qurit Lab, BC Cancer Research Institute, released under the MIT License. See NOTICE for full attribution.


License

This project is licensed under the MIT License — see the LICENSE file for details.

Metadata

Release files for pyconvert 0.1.0a1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for pyconvert 0.1.0a1
File Size Uploaded Provenance Actions
pyconvert-0.1.0a1.tar.gz 201.8 kB Without provenance Details for pyconvert-0.1.0a1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for pyconvert 0.1.0a1
File Interpreter ABI Platform Actions
pyconvert-0.1.0a1-py3-none-any.whl Python 3 none any Details for pyconvert-0.1.0a1-py3-none-any.whl

Total release size: 424.3 kB

Release files / pyconvert-0.1.0a1.tar.gz

Download URL pyconvert-0.1.0a1.tar.gz
Size 201.8 kB
Tags Source
SHA-256 checksum
How to use checksums
612ef8c8fa5279d6ec531a999c8e1c9bac2b8b165361ba1555fa16936c4cc39b
BLAKE2b-256 checksum
How to use checksums
7a8dc1930b3eda9808ab0b7562932f518c84127263300a98987c8b1f620cd77f
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.0

Release files / pyconvert-0.1.0a1-py3-none-any.whl

Download URL pyconvert-0.1.0a1-py3-none-any.whl
Size 222.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
f93ec3776849c8429befcde94aa1d07a8837bdd260f27c074d1f7bbe0f029af0
BLAKE2b-256 checksum
How to use checksums
d2a806b116de77b1941c25426ccc1d36e65820728afdc298099dc95516088cb0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.0

Security for pyconvert 0.1.0a1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release
Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page