skrt.dose module

Classes related to doses and plans.

class skrt.dose.Constraint(opts=None, **kwargs)

Bases: Data

Container for data relating to a dose constraint.

__init__(opts=None, **kwargs)

Constructor of Container class.

The following constraint attributes may be set via opts or **kwargs, but are otherwise initialised to None:

  • weight

  • minimum_dose

  • maximum_dose

  • full_volume_dose,

  • prescription_dose

  • underdose_volume_fraction

  • overdose_volume_fraction

Parameters:

opts: dict, default=None

Dictionary to be used in setting instance attributes (dictionary keys) and their initial values.

`**`kwargs

Keyword-value pairs to be used in setting instance attributes and their initial values.

classmethod get_weight_and_objectives()

Return weight and objectives that may be associated with a constraint.

class skrt.dose.Dose(*args, **kwargs)

Bases: ImageOverlay

Class representing a radiotherapy dose field. This is the same as the Image class, but with overridden plotting behaviour, and with extra functionality relating to ROIs.

Attributes of a Dose object should usually be accessed via their getter methods, rather than directly, to ensure that attribute values have been loaded.

__init__(*args, **kwargs)

Initialise from a medical image source.

Parameters:

pathstr/array/Nifti1Image, default = “”

Source of image data. Can be either:

  1. A string, optionally with wildcards, containing the path to one or multiple dicom files, the path to a directory containg dicom files, or the path to a single nifti file;

  2. A list of paths, optionally with wildcards, to dicom files;

  3. A string, optionally containing wildcards, containing the path to a single numpy file containing a 2D or 3D array;

  4. A 2D or 3D numpy array;

  5. A nibabel.nifti1.Nifti1Image object;

  6. An existing Image object to be cloned; in this case, all other input args except <title> will be ignored, as these will be taken from the existing Image.

Notes:

  1. If path points to a single file, all files in the same directory as this file are considered also.

2. When path resolves to multiple dicom files, only files that match the values of the first file for the dicom attributes: “StudyInstanceUID”, “SeriesNumber”, “Modality”, “ImageOrientationPatient”. When path points to a single file in a directory with others, this file is taken as the first file. Otherwise, files are sorted according to natural sort order (so “2.dcm” before “11.dcm”). To load images from files in a single directory (or in a directory tree) that may have different values for these, it could be better to use the skrt.patient.Patient class:

from skrt import Patient p = Patient(“path/to/directory”, unsorted_dicom=True)

For more details, see documentation of Patient class.

loadbool, default=True

If True, the image data will be immediately loaded. Otherwise, it can be loaded later with the load() method.

titlestr, default=None

Title to use when plotting the image. If None and <source> is a path, a title will be automatically generated from the filename.

affine4x4 array, default=None

Array containing the affine matrix to use if <source> is a numpy array or path to a numpy file. If not None, this takes precendence over <voxel_size> and <origin>.

voxel_sizetuple, default=(1, 1, 1)

Voxel sizes in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

origintuple, default=(0, 0, 0)

Origin position in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

nifti_arraybool, default=False

If True and <source> is a numpy array or numpy file, the array will be treated as a nifti-style array, i.e. (x, y, z) in (row, column, slice), as opposed to dicom style.

downsampleint/list, default=None

Amount by which to downsample the image. Can be a single value for all axes, or a list containing downsampling amounts in order (x, y, z).

dtypetype, default=None

Type to which loaded data should be cast.

auto_timestampbool default=False

If true and no valid timestamp is found within the path string, timestamp generated from current date and time.

default_intensitytuple,None default=(-200, 300)

Default intensity range for image display. This can be specified as a two-element tuple, giving minimum and maximum, or if set to None then intensity range used is from the minimum of zero and the image minimum, to the image maximum. If WindowCenter and WindowWidth are defined in a DICOM source file, these values will be used instead to define the default intensity range.

log_level: str/int/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of skrt.core.Defaults().log_level.

copy_dicom(*args, **kwargs)

Copy (single) source dicom file.

The present class (skrt.dose.Dose) inherits from skrt.image.Image, which in turn inherits from skrt.core.Dated. This method forces calling of the copy_dicom() method of the latter. For details of parameters, see documentation for: skrt.core.Dated.copy_dicom().

get_bed(*args, **kwargs)

Alias for skrt.dose.Dose method get_biologically_effective_dose().

See aliased method for documentation.

get_biologically_effective_dose(rois=None, alpha_beta_ratios=None, n_fraction=None, fill=0, standardise=False, force=False)

Get a Dose object where array values are biologically effective dose.

The biologically effective dose, BED, for a volume element characterised by linear and quadratic coefficients alpha and beta for the linear-quadratic equation, is related to the physical dose, D, delivered over n equal fractions as:

BED = D * (1 + (D/n) / (alpha/beta)).

Parameters:

roisROI/StructureSet/list, default=None

Object(s) specifying ROIs for which calculation is to be performed. The object(s) can be a single skrt.structures.ROI object, a single skrt.structures.StructureSet object, or a list containing any combination of ROI and StructureSet objects.

alpha_beta_ratiosdict, default=None

By default, values of alpha over beta used are the values set for individual ROIs, for example using skrt.StructureSet.set_alpha_beta_ratios(). The default values can be overridden here by passing a dictionary where keys are ROI names and values are revised values for alpha over beta.

n_fractionfloat, default=None

Number of equal-dose fractions over which physical total dose is delivered. If None, the value returned by self.get_n_fraction() is used.

fillfloat/None, default=0

Specification of dose value to set outside of ROIs, and for ROIs where alpha over beta has a null value. If a float, this is used as the default dose value. If None, physical-dose values are retained.

standardisebool, default=False

If False, the data arrays for Doses and for ROI masks will be kept in the orientation in which they were loaded; otherwise, they will be converted to standard dicom-style orientation, such that [column, row, slice] corresponds to the [x, y, z] axes.

forcebool, default=False

Determine action if the current dose object has dose_type set to “EFFECTIVE”. If False, write an error message, and don’t apply the formula for recalculating dose. If True, apply the formula, even if the dose_type suggests that dose values have already been corrected for biological effect.

get_dose_in_roi(roi, standardise=True)

Return 1D numpy array containing all of the dose values for the voxels inside an ROI. Fails if the ROI and dose arrays are not the same size.

get_dose_in_roi_3d(roi, standardise=True)

Return copy of the dose array that has values retained inside an ROI, and set to zero elsewhere. Fails if the ROI and dose arrays are not the same size.

get_dose_quantile(roi, quantile=0.5)

Get specified dose quantile inside an ROI.

get_dose_summation_type()

Get type of dose summation.

Possible values include:

  • “PLAN”: dose summed over all fraction groups;

  • “MULTI_PLAN”: dose summed over two or more plans;

  • “FRACTION”: dose for a single fraction group;

  • “BEAM”: dose for one or more beams.

For details, see:

get_dose_type()

Get dose type.

Possible values are:

  • “PHYSICAL”: physical dose;

  • “EFFECTIVE”: physical dose adjusted for a given biological effect;

  • “ERROR”: difference between ideal and planned dose.

For details, see:

get_dose_units()

Get unit of dose.

Possible values include:

  • “GY”: Gray;

  • “RELATIVE”: dose relative to a reference dose.

For details, see:

get_eqd(*args, **kwargs)

Alias for skrt.dose.Dose method get_equivalent_dose().

See aliased method for documentation.

get_equivalent_dose(dose_rate=2, rois=None, alpha_beta_ratios=None, n_fraction=None, fill=0, standardise=False, force=False)

Get a Dose object where array values are equivalent dose for a specified dose per fraction.

If a physical dose, D, is delivered over n equal fractions to a volume element characterised by linear and quadratic coefficients alpha and beta for the linear-quadratic equation, the total equivalent dose, EQDd, at a dose rate d per fraction, is:

EQDd = D * ((D/n) + (alpha/beta)) / (d + (alpha/beta)).

It approaches the biologically effective dose, BED, as d tends to zero:

EQD0 = D * (1 + (D/n) / (alpha/beta)) = BED.

Parameters:

dose_ratefloat, default=2

Dose (Gy) per fraction for which calculation is to be determined.

roisROI/StructureSet/list, default=None

Object(s) specifying ROIs for which calculation is to be performed. The object(s) can be a single skrt.structures.ROI object, a single skrt.structures.StructureSet object, or a list containing any combination of ROI and StructureSet objects.

alpha_beta_ratiosdict, default=None

By default, values of alpha over beta used are the values set for individual ROIs, for example using skrt.StructureSet.set_alpha_beta_ratios(). The default values can be overridden here by passing a dictionary where keys are ROI names and values are revised values for alpha over beta.

n_fractionfloat, default=None

Number of equal-dose fractions over which physical total dose is delivered. If None, the value returned by self.get_n_fraction() is used.

fillfloat/None, default=0

Specification of dose value to set outside of ROIs, and for ROIs where alpha over beta has a null value. If a float, this is used as the default dose value. If None, physical-dose values are retained.

standardisebool, default=False

If False, the data arrays for Doses and for ROI masks will be kept in the orientation in which they were loaded; otherwise, they will be converted to standard dicom-style orientation, such that [column, row, slice] corresponds to the [x, y, z] axes.

forcebool, default=False

Determine action if the current dose object has dose_type set to “EFFECTIVE”. If False, write an error message, and don’t apply the formula for recalculating dose. If True, apply the formula, even if the dose_type suggests that dose values have already been corrected for biological effect.

get_max_dose_in_rois(rois=None)

Return maximum dose in a set of rois.

Parameter:

roislist, default=None

List of ROI objects, for which maximum dose is to be determined.

get_mean_dose(roi)

Get mean dose inside an ROI.

get_n_fraction()

Return number of dose fractions.

load(*args, **kwargs)

Load self and set default maximum plotting intensity from max of data array if not yet set.

plot_DVH(*args, **kwargs)

Alias for plot_dvh().

plot_dvh(rois=None, bins=50, dose_min=0, dose_max=None, figsize=(8, 4), lw=2, n_colour=None, cmap='turbo', grid=True, fname=None, legend_bbox_to_anchor=(1.01, 0.5), legend_loc='center left')

Plot dose-volume histogram for specified ROI(s).

Parameters:

roisROI/StructureSet/list, default=None

ROI(s) for which dose-volume histogram is to be plotted. This can be a single skrt.structures.ROI object, a single skrt.structures.StructureSet object, or a list containing any combination of ROI and StructureSet objects.

binsint, default=50

Number of bins in the dose-volume histogram.

dose_minfloat, default=0

Minimum dose value to be included.

dose_maxfloat, default=None

Maximum dose value to be included. If None, this is set to the maximum dose for the ROI(s) considered.

figsizetuple of floats, default=(8, 5)

Dimensions (inches) of the matplotlib figure

lwfloat, default=2

Width (relative to matplotlib default) of line used in drawing histogram outlines.

n_colourint, default=None

Number of colours over which to cycle when drawing histograms based on a colour map. In None, the ROI color attribute is used to define histogram colour.

cmapstr, default=’turbo’

Name of a matplotlib colour map from which to define set of colours over which to cycle when drawing histograms.

For predfined names see:

https://matplotlib.org/stable/gallery/color/colormap_reference.html

gridbool, default=True

If True, overlay a grid on the dose-volume histogram.

fnamestr, default=None

Name of file for saving output.

set_image(image)

Set associated image. Image.add_dose(self) will also be called.

set_plan(plan)

Set associated plan, initialising it if needed.

class skrt.dose.ImageOverlay(path='', load=True, image=None, **kwargs)

Bases: Image

Image that can be associated with another Image, and whose plotting functionality includes the ability to plot overlaid on its associated Image.

__init__(path='', load=True, image=None, **kwargs)

Initialise from a medical image source.

Parameters:

pathstr/array/Nifti1Image, default = “”

Source of image data. Can be either:

  1. A string, optionally with wildcards, containing the path to one or multiple dicom files, the path to a directory containg dicom files, or the path to a single nifti file;

  2. A list of paths, optionally with wildcards, to dicom files;

  3. A string, optionally containing wildcards, containing the path to a single numpy file containing a 2D or 3D array;

  4. A 2D or 3D numpy array;

  5. A nibabel.nifti1.Nifti1Image object;

  6. An existing Image object to be cloned; in this case, all other input args except <title> will be ignored, as these will be taken from the existing Image.

Notes:

  1. If path points to a single file, all files in the same directory as this file are considered also.

2. When path resolves to multiple dicom files, only files that match the values of the first file for the dicom attributes: “StudyInstanceUID”, “SeriesNumber”, “Modality”, “ImageOrientationPatient”. When path points to a single file in a directory with others, this file is taken as the first file. Otherwise, files are sorted according to natural sort order (so “2.dcm” before “11.dcm”). To load images from files in a single directory (or in a directory tree) that may have different values for these, it could be better to use the skrt.patient.Patient class:

from skrt import Patient p = Patient(“path/to/directory”, unsorted_dicom=True)

For more details, see documentation of Patient class.

loadbool, default=True

If True, the image data will be immediately loaded. Otherwise, it can be loaded later with the load() method.

titlestr, default=None

Title to use when plotting the image. If None and <source> is a path, a title will be automatically generated from the filename.

affine4x4 array, default=None

Array containing the affine matrix to use if <source> is a numpy array or path to a numpy file. If not None, this takes precendence over <voxel_size> and <origin>.

voxel_sizetuple, default=(1, 1, 1)

Voxel sizes in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

origintuple, default=(0, 0, 0)

Origin position in mm in order (x, y, z) to use if <source> is a numpy array or path to a numpy file and <affine> is not provided.

nifti_arraybool, default=False

If True and <source> is a numpy array or numpy file, the array will be treated as a nifti-style array, i.e. (x, y, z) in (row, column, slice), as opposed to dicom style.

downsampleint/list, default=None

Amount by which to downsample the image. Can be a single value for all axes, or a list containing downsampling amounts in order (x, y, z).

dtypetype, default=None

Type to which loaded data should be cast.

auto_timestampbool default=False

If true and no valid timestamp is found within the path string, timestamp generated from current date and time.

default_intensitytuple,None default=(-200, 300)

Default intensity range for image display. This can be specified as a two-element tuple, giving minimum and maximum, or if set to None then intensity range used is from the minimum of zero and the image minimum, to the image maximum. If WindowCenter and WindowWidth are defined in a DICOM source file, these values will be used instead to define the default intensity range.

log_level: str/int/None, default=None

Severity level for event logging. If the value is None, log_level is set to the value of skrt.core.Defaults().log_level.

get_image()

Return associated image.

property max

Return maximum data value.

plot(view=None, sl=None, idx=None, pos=None, ax=None, gs=None, figsize=None, zoom=None, colorbar=False, xlabel=None, ylabel=None, no_xlabel=False, no_ylabel=False, xticks=None, yticks=None, no_xticks=False, no_yticks=False, no_xtick_labels=False, no_ytick_labels=False, include_image=True, opacity=None, intensity=None, mpl_kwargs=None, show=True, mask=None, mask_threshold=0.5, masked=True, invert_mask=False, mask_color='black', **kwargs)

Plot this overlay, optionally overlaid on its associated Image.

Parameters:

viewstr

Orientation in which to compute the index. Can be “x-y”, “x-z”, “y-x”, “y-z”, “z-x”, or “z-y”. If None, the initial view is chosen to match the image orienation.

slint, default=None

Slice number to plot. Takes precedence over <idx> and <pos> if not None. If all of <sl>, <idx>, and <pos> are None, the central slice will be plotted.

idxint, default=None

Index of the slice in the array to plot. Takes precendence over <pos>.

posfloat, default=None

Position in mm of the slice to plot. Will be rounded to the nearest slice. Only used if <sl> and <idx> are both None.

axmatplotlib.pyplot.Axes, default=None

Axes on which to plot. If None, new axes will be created.

gsmatplotlib.gridspec.GridSpec, default=None

If not None and <ax> is None, new axes will be created on the current matplotlib figure with this gridspec.

figsizefloat, default=None

Figure height in inches; only used if <ax> and <gs> are None.

include_imagebool, default=False

If True and this ImageOverlay has an associate image, it will be plotted overlaid on the image.

opacityfloat, default=None

If plotting on top of an image, this sets the opacity of the overlay (0 = fully transparent, 1 = fully opaque).

mpl_kwargsdict, default=None

Dictionary of keyword arguments to pass to matplotlib.imshow().

colorbarint/bool, default=False

Indicate whether to display colour bar(s): - 1 or True: colour bar for main image; - 2: colour bars for main image and for any associated image or overlay; - 0 or False: no colour bar.

xlabelstr, default=None

Custom label for the x axis. If None, the label is set to be the coordinate axis and units, for example “x (mm)”. If False or ‘’, the x axis will not be labelled.

ylabelstr, default=None

Custom label for the y axis. If None, the label is set to be the coordinate axis and units, for example “y (mm)”. If False or ‘’, the x axis will not be labelled.

no_xlabelbool, default=False

If True, the x axis will not be labelled.

no_ylabelbool, default=False

If True, the y axis will not be labelled.

xtickstuple/dict, default=None

Tick locations and custom tick labels for the x axis.

ytickstuple/dict, default=None

Tick locations and custom tick labels for the y axis.

no_xticksbool, default=False

If True, ticks (and their labels) on the x axis will not be shown.

no_yticksbool, default=False

If True, ticks (and their labels) on the y axis will not be shown.

no_xtick_labelsbool, default=False

If True, ticks on the x axis will not be labelled.

no_ytick_labelsbool, default=False

If True, ticks on the y axis will not be labelled.

showbool, default = True

If True, the plot will be displayed immediately.

maskImage/list/ROI/str/StructureSet, default=None

Image object representing a mask or a source from which an Image object can be initialised. In addition to the sources accepted by the Image constructor, the source may be an ROI, a list of ROIs or a StructureSet. In the latter cases, the mask image is derived from the ROI mask(s).

mask_thresholdfloat, default=0.5

Threshold for mask data. Values above and below this value are set to True and False respectively. Taken into account only if the mask image has non-boolean data.

maskedbool, default=True

If True and a mask is specified, the image is masked.

invert_maskbool, default=False

If True and a mask is applied, the mask will be inverted.

mask_colormatplotlib color, default=”black”

color in which to plot masked areas.

`**`kwargs:

Keyword args to pass to skrt.image.Image.plot().

set_image(image)

Set associated image, initialising it if needed.

class skrt.dose.Plan(path='', load=True)

Bases: Archive

Class representing a radiotherapy plan.

Attributes of a Plan object should usually be accessed via their getter methods, rather than directly, to ensure that attribute values have been loaded.

__init__(path='', load=True)

Instantiate Plan from a DICOM rtplan file.

Parameters:

path: str/pathlib.Path, default=””

Path to DICOM rtplan file from which plan is to be instantiated.

load: bool, default=True

If True, load plan data immediately. If False, plan data will be loaded automatically the first time that a Plan method requiring the data is called, or may be explicitly loaded by calling the load() method.

add_dose(dose)

Add a Dose object to be associated with this plan. This does not affect the plan associated with the Dose object.

Parameters:

doseskrt.dose.Dose

A Dose object to assign to this plan.

clear_doses()

Clear all dose maps associated with this plan.

get_approval_status()

Return plan approval status.

get_description()

Return plan description.

get_dicom_dataset()

Return pydicom.dataset.FileDataset object associated with this plan.

get_dose_objective(objective='maximum_dose', idx_dose=0, dose=None)

Obtain Dose object representing weight or objective of dose constraint.

Parameters: objective : str, default=’maximum_dose’

Identifier of objective for which information is to be obtained. For a list of objectives, see skrt.dose.Constraint class.

idx_doseint, default=0

Index of dose object in self.doses from which dose data are to be taken.

doseskrt.dose.Dose, default=None

Dose object from which dose data are to be taken. If specified, idx_dose is ignored.

get_doses()

Return Dose objects associated with this plan.

get_image()

Return Image object associated with this plan.

get_machine(machines=None)

Return machine name.

Parameter:

machines: dict, default=None

Dictionary mapping between station names and machine names.

get_n_beam_seq()

Return number of beam sequences for this plan.

get_n_fraction()

Return number of fractions for this plan.

get_n_fraction_group()

Return number of fraction groups for this plan.

get_name()

Return plan name.

get_organs_at_risk()

Return list of ROIs identified in plan as organs at risk.

get_prescription_description()

Return plan prescription description.

get_station_name()

Return station name.

get_structure_set()

Return StructureSet object associated with this plan.

get_target_dose()

Return dose to target (tumour) for this plan.

get_targets()

Return list of ROIs identified in plan as targets.

load(force=False)

Load plan data.

Parameter:

force: bool, default=False

If True, plan data will be reloaded from file, even if loaded previously.

load_constraints(force=False)

Load dose constraints from plan.

Parameter: force: bool, default=False

If True, dose constraints will be reloaded from file, even if loaded previously.

set_image(image)

Set associated image, initialising it if needed.

set_structure_set(structure_set)

Set associated structure set, initialising it if needed.

skrt.dose.remove_duplicate_doses(doses=None)

Remove duplicates from a list of dose objects.

Dose instance dose1 is taken to be a duplicate of dose2 if dose1.has_same_data(dose2) is True.

Parameter: doses: list, default=None

List of dose objects, from which duplicates are to be removed.

skrt.dose.sum_doses(doses=None)

Sum doses of the same geometry.

If not all doses have the same same geometry (shape, origin, voxel size), None is returned. Otherwise, a Dose object is returned that has the same geometry as the input doses, and where array values are the sums of the array values of the input doses.

Parameter: doses: list, default=None

List of Dose objects to be summed.