Source code for pymedphys._dicom.dose

# Copyright (C) 2025-2026 Matthew Jennings
# Copyright (C) 2016-2021 Matthew Jennings and Simon Biggs

# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at

#     http://www.apache.org/licenses/LICENSE-2.0

# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""A DICOM RT Dose toolbox"""

import copy
from typing import Sequence

from pymedphys._imports import matplotlib, plt, pydicom, scipy
from pymedphys._imports import numpy as np

from . import orientation
from .compat import ensure_transfer_syntax
from .coords import (
    _COORDINATE_ACCEPTANCE_TOLERANCE_MM,
    _DoseGridGeometry,
    coords_from_xyz_axes,
    coords_in_datasets_are_equal,
)
from .header import patient_ids_in_datasets_are_equal
from .rtplan import get_surface_entry_point_with_fallback, require_gantries_be_zero
from .structure import pull_structure

# pylint: disable=C0103


[docs] def zyx_and_dose_from_dataset(dataset): """Return a DICOM RT Dose grid with ascending (z, y, x) DICOM axes. Parameters ---------- dataset : pydicom.dataset.Dataset An RT Dose dataset whose Image Orientation (Patient) is one of the eight supported transverse cardinal orientations (head or feet first; supine, prone, or decubitus left or right). Returns ------- coords : tuple of numpy.ndarray The (z, y, x) DICOM axes of the dose grid, each strictly ascending. dose : numpy.ndarray The dose, indexed ``dose[i_z, i_y, i_x]`` at ``(z[i_z], y[i_y], x[i_x])``. Notes ----- The pixel array is reordered to match the axes: an axis the scanner stored in descending order (for example x for head first prone, or z for feet first) is flipped, and for decubitus orientations, whose rows run along x, rows and columns are swapped. For head first supine with increasing slice offsets the dose is the pixel array unchanged. Head first supine grids with decreasing slice offsets are reversed in z. Accepted direction cosines within 1e-4 of a supported cardinal orientation are snapped to it for axis extraction; the positional effect grows with grid extent. The rearrangement itself does not resample dose or move voxels. Keep the returned coordinates and dose together when indexing or plotting. Gamma calculated with this pair as its reference has the same shape and index order as the returned dose, which can differ from ``pixel_array``. To recover raw storage order, apply the inverse reversals and dimension permutation to the result. """ geometry = _DoseGridGeometry.from_dataset(dataset) x, y, z = geometry.dicom_axes() dose = dose_from_dataset(dataset) # pydicom drops the slice dimension of a single-slice pixel array. slices = geometry.local_axes[2].size dose = dose.reshape(slices, int(dataset.Rows), int(dataset.Columns)) # Map pixel dimensions (slice, row, column) onto patient (z, y, x). dose = np.transpose(dose, geometry.xyz_to_pixel_dimensions[::-1]) axes = [z, y, x] for dimension, axis in enumerate(axes): if axis.size > 1 and axis[1] < axis[0]: axes[dimension] = axis[::-1] dose = np.flip(dose, axis=dimension) coords = tuple(np.ascontiguousarray(axis) for axis in axes) return coords, np.ascontiguousarray(dose)
def dose_from_dataset(ds): r"""Extract the dose grid from a DICOM RT Dose file.""" ensure_transfer_syntax(ds) return ds.pixel_array * ds.DoseGridScaling
[docs] def dicom_dose_interpolate(interp_coords, dicom_dose_dataset): """Interpolates across a DICOM dose dataset. Parameters ---------- interp_coords : tuple(z, y, x) A tuple of coordinates in DICOM order, z axis first, then y, then x where x, y, and z are DICOM axes. dicom_dose_dataset : pydicom.Dataset An RT DICOM Dose object """ interp_z = np.asarray(interp_coords[0])[:, None, None] interp_y = np.asarray(interp_coords[1])[None, :, None] interp_x = np.asarray(interp_coords[2])[None, None, :] coords, dicom_dose_dataset = zyx_and_dose_from_dataset(dicom_dose_dataset) interpolation = scipy.interpolate.RegularGridInterpolator( coords, dicom_dose_dataset ) try: result = interpolation((interp_z, interp_y, interp_x)) except ValueError: print(f"coords: {coords}") raise return result
[docs] def depth_dose(depths, dose_dataset, plan_dataset): """Interpolates dose for defined depths within a DICOM dose dataset. Since the DICOM dose dataset is in CT coordinates the corresponding DICOM plan is also required in order to calculate the conversion between CT coordinate space and depth. Currently, `depth_dose()` only supports a `dose_dataset` for which the patient orientation is HFS and that any beams in `plan_dataset` have gantry angle equal to 0 (head up). Depth is assumed to be purely in the y axis direction in DICOM coordinates. Parameters ---------- depths : numpy.ndarray An array of depths to interpolate within the DICOM dose file. 0 is defined as the surface of the phantom using either the ``SurfaceEntryPoint`` parameter or a combination of ``SourceAxisDistance``, ``SourceToSurfaceDistance``, and ``IsocenterPosition``. dose_dataset : pydicom.dataset.Dataset The RT DICOM dose dataset to be interpolated plan_dataset : pydicom.dataset.Dataset The RT DICOM plan used to extract surface parameters and verify gantry angle 0 beams are used. """ orientation.require_dicom_patient_position(dose_dataset, "HFS") require_gantries_be_zero(plan_dataset) depths = np.asarray(depths) surface_entry_point = get_surface_entry_point_with_fallback(plan_dataset) depth_adjust = surface_entry_point.y y = depths + depth_adjust x, z = [surface_entry_point.x], [surface_entry_point.z] coords = (z, y, x) extracted_dose = np.squeeze(dicom_dose_interpolate(coords, dose_dataset)) return extracted_dose
[docs] def profile(displacements, depth, direction, dose_dataset, plan_dataset): """Interpolates dose for cardinal angle horizontal profiles within a DICOM dose dataset. Since the DICOM dose dataset is in CT coordinates the corresponding DICOM plan is also required in order to calculate the conversion between CT coordinate space and depth and horizontal displacement. Currently, `profile()` only supports a `dose_dataset` for which the patient orientation is HFS and that any beams in `plan_dataset` have gantry angle equal to 0 (head up). Depth is assumed to be purely in the y axis direction in DICOM coordinates. Parameters ---------- displacements : numpy.ndarray An array of displacements to interpolate within the DICOM dose file. 0 is defined in the DICOM z or x directions based either upon the ``SurfaceEntryPoint`` or the ``IsocenterPosition`` depending on what is available within the DICOM plan file. depth : float The depth at which to interpolate within the DICOM dose file. 0 is defined as the surface of the phantom using either the ``SurfaceEntryPoint`` parameter or a combination of ``SourceAxisDistance``, ``SourceToSurfaceDistance``, and ``IsocenterPosition``. direction : str, one of ('inplane', 'inline', 'crossplane', 'crossline') Corresponds to the axis upon which to apply the displacements. - 'inplane' or 'inline' converts to DICOM z direction - 'crossplane' or 'crossline' converts to DICOM x direction dose_dataset : pydicom.dataset.Dataset The RT DICOM dose dataset to be interpolated plan_dataset : pydicom.dataset.Dataset The RT DICOM plan used to extract surface and isocentre parameters and verify gantry angle 0 beams are used. """ orientation.require_dicom_patient_position(dose_dataset, "HFS") require_gantries_be_zero(plan_dataset) displacements = np.asarray(displacements) surface_entry_point = get_surface_entry_point_with_fallback(plan_dataset) depth_adjust = surface_entry_point.y y = [depth + depth_adjust] if direction in ("inplane", "inline"): coords = (displacements + surface_entry_point.z, y, [surface_entry_point.x]) elif direction in ("crossplane", "crossline"): coords = ([surface_entry_point.z], y, displacements + surface_entry_point.x) else: raise ValueError( "Expected direction to be equal to one of " "'inplane', 'inline', 'crossplane', or 'crossline'" ) extracted_dose = np.squeeze(dicom_dose_interpolate(coords, dose_dataset)) return extracted_dose
def get_dose_grid_structure_mask( structure_name: str, structure_dataset: "pydicom.Dataset", dose_dataset: "pydicom.Dataset", ): """Determines the 3D boolean mask defining whether or not a grid point is inside or outside of a defined structure. In its current implementation the dose grid and the planes upon which the structures are defined need to be aligned. This is due to the implementation only stepping through each structure plane and undergoing a 2D mask on the respective dose grid. In order to undergo a mask when the contours and dose grids do not align inter-slice contour interpolation would be required. For now, having two contours for the same structure name on a single slice is also not supported. The contours may be listed in any order. Parameters ---------- structure_name The name of the structure for which the mask is to be created structure_dataset : pydicom.Dataset An RT Structure DICOM object containing the respective structures. dose_dataset : pydicom.Dataset An RT Dose DICOM object from which the grid mask coordinates are determined. Returns ------- mask : numpy.ndarray of bool Indexed ``mask[slice, row, column]`` like the dose dataset's pixel array in every supported orientation, including decubitus grids, whose rows run along x. Raises ------ ValueError If an unsupported contour is provided or the dose grid does not align with the structure planes. """ geometry = _DoseGridGeometry.from_dataset(dose_dataset) x_dose, y_dose, z_dose = geometry.dicom_axes() # Supported orientations are transverse, so x and y vary only within a # slice. The first slice gives the patient x and y of each (row, column). xx, yy, _ = coords_from_xyz_axes( (x_dose, y_dose, z_dose[:1]), geometry.xyz_to_pixel_dimensions )[:, 0] rows, columns = xx.shape points = np.column_stack((xx.ravel(), yy.ravel())) x_structure, y_structure, z_structure = pull_structure( structure_name, structure_dataset ) contour_z_values = [] for item in z_structure: unique_item = np.unique(item) if len(unique_item) != 1: raise ValueError("Only one z value per contour supported") contour_z_values.append(unique_item[0]) structure_z_values = np.sort(contour_z_values) if np.unique(structure_z_values).size != structure_z_values.size: raise ValueError("Only one contour per slice is currently supported") # The contour slices must be consecutive dose slices. sorted_dose_z = np.sort(z_dose) first_dose_index = int(np.searchsorted(sorted_dose_z, structure_z_values[0])) aligned_dose_z = sorted_dose_z[ first_dose_index : first_dose_index + structure_z_values.size ] if not np.array_equal(aligned_dose_z, structure_z_values): raise ValueError( "Only contours where both, there are no gaps in the " "z-axis of the contours, and the contour axis and dose " "axis, are aligned are supported." ) mask = np.zeros((len(z_dose), rows, columns), dtype=bool) # A ContourSequence may list its contours in any order, so apply each # contour to the dose slice at its own z. for x_contour, y_contour, z_contour in zip( x_structure, y_structure, contour_z_values ): dose_index = int(np.flatnonzero(z_dose == z_contour)[0]) structure_polygon = matplotlib.path.Path( np.column_stack((x_contour, y_contour)) ) # This logical "or" here is actually in place for the case where # there may be multiple contours on the one slice. That's not # going to be used at the moment however, as that case is not # yet supported in the logic above. mask[dose_index] = mask[dose_index] | ( structure_polygon.contains_points(points).reshape(rows, columns) ) return mask def find_dose_within_structure(structure_name, structure_dataset, dose_dataset): mask = get_dose_grid_structure_mask(structure_name, structure_dataset, dose_dataset) # pydicom drops the slice dimension of a single-slice pixel array. dose = dose_from_dataset(dose_dataset).reshape(mask.shape) return dose[mask] def create_dvh(structure, structure_dataset, dose_dataset): structure_dose_values = find_dose_within_structure( structure, structure_dataset, dose_dataset ) hist = np.histogram(structure_dose_values, 100) freq = hist[0] bin_edge = hist[1] bin_mid = (bin_edge[1::] + bin_edge[:-1:]) / 2 cumulative = np.cumsum(freq[::-1]) cumulative = cumulative[::-1] bin_mid = np.append([0], bin_mid) cumulative = np.append(cumulative[0], cumulative) percent_cumulative = cumulative / cumulative[0] * 100 plt.plot(bin_mid, percent_cumulative, label=structure) plt.title("DVH") plt.xlabel("Dose (Gy)") plt.ylabel("Relative Volume (%)") def sum_doses_in_datasets( datasets: Sequence["pydicom.dataset.Dataset"], ) -> "pydicom.dataset.Dataset": """Sum two or more DICOM dose grids and save to new DICOM RT Dose dataset" Parameters ---------- datasets : sequence of pydicom.dataset.Dataset A sequence of DICOM RT Dose datasets whose doses are to be summed. Returns ------- pydicom.dataset.Dataset A new DICOM RT Dose dataset whose dose is the sum of all doses within `datasets` """ for ds in datasets: ensure_transfer_syntax(ds) if not all(ds.Modality == "RTDOSE" for ds in datasets): raise ValueError("`datasets` must only contain DICOM RT Dose datasets.") if not patient_ids_in_datasets_are_equal(datasets): raise ValueError("Patient ID must match for all datasets") if not all(ds.DoseSummationType == "PLAN" for ds in datasets): raise ValueError( "Only DICOM RT Doses whose DoseSummationTypes are 'PLAN' are supported" ) if not all(ds.DoseUnits == datasets[0].DoseUnits for ds in datasets): raise ValueError( "All DICOM RT Doses must have the same units ('GY or 'RELATIVE')" ) if not coords_in_datasets_are_equal(datasets): raise ValueError( "All dose grids must have coincident coordinates: corresponding voxel " f"centres must agree within {_COORDINATE_ACCEPTANCE_TOLERANCE_MM} mm" ) ds_summed = copy.deepcopy(datasets[0]) ds_summed.BitsAllocated = 32 ds_summed.BitsStored = 32 ds_summed.HighBit = 31 ds_summed.DoseSummationType = "MULTI_PLAN" ds_summed.DoseComment = "Summed Dose" if not all(ds.DoseType in ("PHYSICAL", "EFFECTIVE") for ds in datasets): raise ValueError( "Only DICOM RT Doses whose DoseTypes are 'PHYSICAL' or " "'EFFECTIVE' are supported" ) if any(ds.DoseType == "EFFECTIVE" for ds in datasets): ds_summed.DoseType = "EFFECTIVE" else: ds_summed.DoseType = "PHYSICAL" doses = np.array([dose_from_dataset(ds) for ds in datasets]) doses_summed = np.sum(doses, axis=0, dtype=np.float32) ds_summed.DoseGridScaling = np.max(doses_summed) / (2 ** int(ds_summed.HighBit)) pixel_array_summed = (doses_summed / ds_summed.DoseGridScaling).astype(np.uint32) ds_summed.PixelData = pixel_array_summed.tobytes() return ds_summed