Dose Constraints

Define Constraint base class, along with specializations MaxConstraint, MinConstraint, MeanConstraint and PercentileConstranint. Also define ConstraintList container and function D() for instantiating constraints with a syntax used by clinicians, e.g.:

D('max') < 30 * Gy
D('min') > 20 * Gy
D('mean') > 25 * Gy
D(90) > 22 * Gy
D(5) < 29 * Gy

Also define the DVH (dose volume histogram) object for converting structure dose vectors to plottable DVH data sets.

Atrributes:
RELOPS (__ConstraintRelops): Defines constants
RELOPS.GEQ, RELOPS.LEQ, and RELOPS.INDEFINITE for categorizing inequality constraint directions.
class dose.Constraint[source]

Base class for dose constraints.

The MinConstraint, MaxConstraint, MeanConstraint and PercentileConstraint types all inherit from Constraint. This class defines all the basic getters and setters for constraint properties such as the type of threshold, constraint direction (relop) and dose bound, as well as other shared properties such as slack and dual values relevant to the Constraint object’s role in treatment plan optimization problems.

__eq__(other)[source]

Overload operator ==

Define comparison between constraints by comparing their relops, doses and thresholds.

Parameters:( (other) – class:’Constraint’): Value to be compared.
Returns:obj:bool: True if compared constraints are equivalent.
Raises:TypeError – If other is not a Constraint.
__ge__(other)[source]

Reroute operator >= to operator >

__gt__(other)[source]

Overload operator >.

Enable Constraint.dose and Constraint.relop to be set via syntax ‘constraint > dose’.

Parameters:other – Value that Constraint.dose will be set to.
Returns:Updated version of this object.
Return type:Constraint
__le__(other)[source]

Reroute operator <= to operator <

__lt__(other)[source]

Overload operator <.

Enable Constraint.dose and Constraint.relop to be set via syntax ‘constraint < dose’.

Parameters:other – Value that Constraint.dose will be set to.
Returns:Updated version of this object.
Return type:Constraint
__str__()[source]

Stringify Constraint as ‘D{threshold} {<= or >=} {dose}’

active

True if constraint active in most recent plan that used it.

dose

Dose bound for constraint.

Getter returns dose in absolute terms (i.e., DeliveredDose units.)

Setter accepts dose in absolute or relative terms. That is, dose may be provided provided in units of Percent or in units of DeliveredDose, such as Gray.

Raises:TypeError – If dose not of allowed types.
dose_achieved

Constraint dose +/- slack.

dual_value

Value of dual variable associated with constraint.

This property is intended to reflect information about the state of the Constraint in the context of the most recent run of an optimization problem that it was used in. Accordingly, it is to be managed by some client(s) of the Constraint and not the object itself.

In particular, this property is meant to hold the value of the dual variable associated with the dose constraint in some solver’s representation of an optimization problem, and the value should be that attained at the conclusion of a solver run.

priority

Constraint priority.

Priority is one of {0, 1, 2, 3}. Constraint priorities are used when incorporating a Constraint in an optimization problem with slack allowed.

Priority 0 indicates that the constraint should be enforced strictly even when the overall problem formulation permits dose constraint slacks.

The remaining values (1, 2, and 3) represent ranked tiers; slacks are permitted and penalized according to the priority: the slack variable for a Priority 1 constraint is penalizeed more heavily than that of a Priority 2 constraint, which is in turn penalized more heavily than the slack variable associated with a Priority 3 constraint. This mechanism allows users to encourage some constraints to be met more closely than others, even when slack is allowed for all of them.

Raises:
  • TypeError – If priority not an int:.
  • ValueError – If priority not in {0, 1, 2, 3}.
relop

Constraint relop (i.e., sense of inequality).

Should be one of <, >, <=, or >=.

The setter method does not differentiate between strict and non-strict inequalities (i.e., < versus <=), but both syntaxes are allowed for convenience.

Raises:Value Error – If user tries to build a maximum dose constraint with a lower dose bound or a minimum dose constraint with an upper dose bound, or if relop is not one of the expected string values.
resolved

Indicator that constraint is complete and well-formed.

rx_dose

Prescription dose associated with constraint.

This property is optional, but required when the Constraint.dose is phrased in relative terms (i.e., of type Percent). It provides the numerical basis on which to interpret the relative value of Constraint.dose.

Raises:TypeError – If rx_dose is not of type DeliveredDose, e.g., Gray or centiGray.
slack

Value of slack variable associated with constraint.

This property is intended to reflect information about the state of the Constraint in the context of the most recent run of an optimization problem that it was used in. Accordingly, it is to be managed by some client(s) of the Constraint and not the object itself.

In particular, this property is meant to hold the value of the slack variable associated with the dose constraint in some solver’s representation of an optimization problem, and the value should be that attained at the conclusion of a solver run.

Raises:
  • TypeError – If slack is not an int or float.
  • ValueError – If slack is negative.
symbol

Strict inequality str of Constraint.relop.

threshold

Constraint threshold—percentile, min, max or mean.

upper

Indicator of upper dose constraint (or, ‘less than’ inequality).

Parameters:None
Returns:True if constraint of type “D(threshold) < dose”.
Return type:bool
Raises:ValueError – If Constraint.relop is not set.
class dose.ConstraintList[source]

Container for Constraint objects.

items

dict

Dictionary of constraints in container, keyed by hashed values generated upon addition of constraint to container.

last_key

Key generated upon most recent addition of a constraint to the container.

__getitem__(key)[source]

Overload operator [].

__iadd__(other)[source]

Overload operator +=.

Enable syntax ConstraintList += Constraint.

Parameters:other – Singleton, or iterable collection of Constraint objects to append to this ConstraintList.
Returns:Updated version of this object.
Return type:ConstraintList
Raises:TypeError – If other is not a Constraint or iterable collection of constraints.
__isub__(other)[source]

Overload operator -=.

Enables syntaxes
ConstraintList -= Constraint, and ConstraintList -= key.

Remove other from this ConstraintList if it is a key with a corresponding Constraint, or if it is a Constraint for which an exactly equivalent Constraint is found in the list.

Parameters:otherConstraint or key to a Constraint to be removed from this ConstraintList.
Returns:Updated version of this object.
Return type:ConstraintList
__iter__()[source]

Python3-compatible iterator implementation.

__str__()[source]

Stringify list by concatenating strings of each constraint.

clear()[source]

Clear constraints from ConstraintList.

Parameters:None
Returns:None
contains(constr)[source]

Test whether search Constraint exists in this ConstraintList.

Parameters:constr (Constraint) – Search term.
Returns:True if a Constraint equivalent to constr found in this ConstraintList.
Return type:bool
keys

Keys of constraints in list.

list

list of Constraint objects in ConstraintList.

mean_only

True if list exclusively contains mean constraints.

plotting_data

List of matplotlib-compatible data for all constraints.

size

Number of constraints in list.

dose.D(threshold, relop=None, dose=None)[source]

Utility for constructing dose constraints with clinical syntax.

Parameters:
  • threshold – Specify type of dose constraint; if real-valued or of type Percent, parsed as a percentile constraint. If string-valued, tentatively interpreted as a mean, minimum, or maximum type dose constraint.
  • relop (optional) – Sense of inequality. Expected to be compatible with Constraint.relop setter.
  • dose (optional) – Dose bound. Expected to be compatible with Constraint.dose setter.
Returns:

Return type depends on argument threshold.

Return type:

Constraint

Raises:

ValueError – If threshold does not conform to expected types or formats.

Examples

>>> D('mean') > 30 * Gy
>>> D('min') > 10 * Gy
>>> D('max') < 5 * Gy
>>> D(30) < 4 * Gy
>>> D(90) > 47 * Gy
class dose.DVH(n_voxels, maxlength=1000)[source]

Representation of a dose volume histogram.

Given a vector of doses, the DVH object generates the corresponding dose volume histogram (DVH).

A DVH is associated with a planning structure, which will have a finite volume or number of voxels. A DVH curve (or graph) is a set of points \((d, p)\)—with \(p\) in the interval \([0, 100]\)–where for each dose level \(d\), the value \(p\) gives the percent of voxels in the associated structure receiving a radiation dose \(\ge d\).

Sampling is performed if necessary to keep data series length short enough to be conveniently transmitted (e.g., as part of an interactive user interface) and plotted (e.g., with matplotlib utilities) with low latency.

Note that the set of (dose, percentile) pairs are maintained as two sorted, length-matched, vectors of dose and percentile values, respectively.

MAX_LENGTH

int

Default maximum length constant to use when constructing and possibly sampling DVH cures.

data

Sorted dose values from DVH curve.

The data provided to the setter are sorted to form the abscissa values for the DVH curve. If the length of the input exceeds the maximum data series length (as determined when the object was initialized), the input data is sampled.

Raises:
  • ValueError – If size of input data does not match size of
  • structure associated with DVH as specified to
  • object initializer.
dose_at_percentile(percentile)[source]

Read off DVH curve to get dose value at percentile.

Since the DVH object maintains the DVH curve of (dose, percentile) pairs as two sorted vectors, to approximate the the dose d at percentile percentile, we retrieve the index i that yields the nearest percentile value. The corresponding i’th dose is returned. When the nearest percentile is not within 0.5%, the two nearest neighbor percentiles and two nearest neighbor dose values are used to approximate the dose at the queried percentile by linear interpolation.

Parameters:percentile (int, float or Percent) – Queried percentile for which to retrieve corresponding dose level.
Returns:Dose value from DVH curve corresponding to queried percentile, or nan if the curve has not been populated with data.
max_dose

Largest dose value in DVH curve.

min_dose

Smallest dose value in DVH curve.

percentile_at_dose(dose)[source]

Read off DVH curve to get precentile value at dose.

Parameters:dose (int, float, or DeliveredDose) – Quertied dose for which to retrieve the corresponding percentile. Assumed to have same units as DVH data.
Returns:Percentile value from DVH curve corresponding to queried dose, or nan if the curve has not been populated with data.
plotting_data

Dictionary of matplotlib-compatible plotting data.

populated

True if DVH curve is populated.

resample(maxlength)[source]

Re-sampled copy of this :class`DVH`

Parameters:maxlength (int) – Maximum length at which to series re-sample data.
Returns:Re-sampled DVH curve; return original curve if maxlength is None.
Return type:DVH
class dose.MaxConstraint(relop=None, dose=None)[source]

Maximum dose constraint.

Extend base class Constraint. Express an upper bound on the maximum dose to a structure.

plotting_data

Dictionary of matplotlib-compatible data.

class dose.MeanConstraint(relop=None, dose=None)[source]

Mean dose constraint.

Extend base class Constraint. Express an upper or lower bound on the mean dose to a structure.

plotting_data

Dictionary of matplotlib-compatible data.

class dose.MinConstraint(relop=None, dose=None)[source]

Minimum dose constraint.

Extend base class Constraint. Express a lower bound on the minimum dose to a structure.

plotting_data

Dictionary of matplotlib-compatible data.

class dose.PercentileConstraint(percentile=None, relop=None, dose=None)[source]

Percentile, i.e. dose-volume, or partial dose constraint.

Allow for dose bounds to be applied to a certain fraction of a structure involved in treatment planning. For instance, a lower constraint,

>>>     # D80 > 60 Gy,

requires at least 80% of the voxels in a structure must receive 60 Grays or greater, and an upper constraint,

>>>     # D25 < 5 Gy,

requires no more than 25% of the voxels in a structure to receive 25 Grays or greater.

Extend base class Constraint, recast Constraint.threshold as PercentileConstraint.percentile.

get_maxmargin_fulfillers(y, had_slack=False)[source]

Get indices to values of y deepest in feasible set.

In particular, given len(y), if m voxels are required to respect this PercentileConstraint exactly, y is assumed to contain at least m entries that respect the constraint (for instance, y is generated by a convex program that includes a convex restriction of the dose constraint).

Procedure.

\[\begin{array}{rl} \mathbf{0.} & \mbox{Define} \\ & p = \mbox{percent non-violating} \cdot \mbox{structure size} = \mbox{percent non-violating} \cdot \mathbf{len}(y) \\ \mathbf{1.} & \mbox{Get margins: } y - \mbox{dose bound}. \\ \mathbf{2.} & \mbox{Sort margin indices by margin values.} \\ \mathbf{3.} & \mbox{If upper constraint, return indices of $p$ most negative entries}. \\ \mathbf{4.} & \mbox{If lower constraint, return indices of $p$ most positive entries}. \\ \end{array}\]
Parameters:
  • y – Vector-like input data of length m.
  • had_slack (bool, optional) – Define margin relative to slack-modulated dose value instead of the base dose value of this PercentileConstraint.
Returns:

Vector of indices that yield the p entries of y that fulfill this PercentileConstraint with the greatest margin.

Return type:

numpy.ndarray

percentile

Percentile threshold in interval (0, 100).

Raises:TypeError – If percentile is not int, float, or Percent.
plotting_data

Dictionary of matplotlib-compatible data.