cerr.dataclasses package

Submodules

cerr.dataclasses.beams module

beams module.

The beams module defines metadata for RT Plan (RTPLAN). The metadata are attributes of the Beams class.

cerr.dataclasses.beams.get_empty_list()[source]

Return an empty list.

Used as a default_factory for dataclass fields that require a mutable list default.

Returns:

An empty list [].

Return type:

list

cerr.dataclasses.beams.get_empty_np_array()[source]

Return an empty 3-D NumPy array with shape (0, 0, 0).

Used as a default_factory for dataclass fields that require a mutable NumPy array default.

Returns:

A zero-element array with shape (0, 0, 0).

Return type:

np.ndarray

class cerr.dataclasses.beams.Beams(PatientName: str = '', PatientID: str = '', PatientBirthDate: str = '', PatientSex: str = '', Manufacturer: str = '', ManufacturerModelName: str = '', RelationshipGroupLength: int = 0, ImagePresentationGroupLength: int = 0, PixelPaddingValue: float = 0, PlanGroupLength: int = 0, RTPlanLabel: str = '', RTPlanDate: str = '', RTPlanTime: str = '', RTPlanGeometry: str = '', TreatmentSites: array = <factory>, PrescriptionDescription: str = '', DoseReferenceSequence: array = <factory>, FractionGroupSequence: array = <factory>, BeamSequence: array = <factory>, PatientSetupSequence: array = <factory>, ReferencedRTGroupLength: int = 0, ReferencedStructureSetSequence: array = <factory>, ReferencedDoseSequence: array = <factory>, ReviewGroupLength: int = 0, ApprovalStatus: str = '', ReviewDate: str = '', ReviewTime: str = '', ReviewerName: str = '', SOPInstanceUID: str = '', beamFileName: str = '', manufacturer: str = '', manufacturerModelName: str = '', deIdentificationMethod: str = '', deidentificationMethodDescription: array = <factory>, BeamUID: str = '')[source]

Bases: object

This class defines data object for Beams in an RTPlan. The metadata is populated from DICOM. .. attribute:: PatientName

Patient’s name

type:

str

PatientID

Patient’s ID

Type:

str

PatientBirthDate

Patient’s birth date

Type:

str

PatientSex

Patient’s gender

Type:

str

Manufacturer

Equipment manufacturer

Type:

str

ManufacturerModelName

Equipment model

Type:

str

PixelPaddingValue

Pixel padding value as defined in (0028,0120) DICOM tag

Type:

float

RTPlanLabel

User-defined label for treatment plan as defined by (300A,0002) DICOM tag

Type:

str

RTPlanDate

Date treatment plan was last modified as defined by (300A,0006) DICOM tag

Type:

str

RTPlanTime

Time treatment plan was last modified as defined by (300A,0007) DICOM tag

Type:

str

RTPlanGeometry

Describes whether RT Plan is based on patient or treatment device geometry (300A,000C) tag

Type:

str

TreatmentSites

A free-text label describing the anatomical treatment site. (3010,0077) tag

Type:

np.array

PrescriptionDescription

User-defined description of treatment prescription as defined in (300A,000E)

Type:

str

FractionGroupSequence

Sequence of Fraction Groups as per (300A,0070) DICOM tag

Type:

np.array

BeamSequence

Sequence of treatment beams for current RT Plan as per (300A,00B0) DICOM tag

Type:

np.array

PatientSetupSequence

Sequence of patient setup data for current plan as per (300A,0180) DICOM tag

Type:

np.array

ReferencedStructureSetSequence

The RT Structure Set on which the RT Plan is based as per (300C,0060) DICOM tag

Type:

np.array

ReferencedDoseSequence

Sequence of Dose References.

Type:

np.array

ApprovalStatus

Approval status at the time the SOP Instance was created as per (300E,0002) DICOM tag.

Type:

str

ReviewDate

Date plan was reviewed

Type:

str

ReviewTime

Time plan was reviewed

Type:

str

ReviewerName

Reviewer name

Type:

str

SOPInstanceUID

SOP Instance UID of the Plan

Type:

str

beamFileName

RTPLAN file name

Type:

str

manufacturer

Scanner Manufacturer

Type:

str

manufacturerModelName

Manufacturer model name

Type:

str

deIdentificationMethod

Indicates whether patient identity has been removed.

Type:

str

deidentificationMethodDescription

codes that specifies the methods used to de-identify patient data

Type:

np.array

BeamUID

pyCERR’s UID of RTPLAN

Type:

str

PatientName: str = ''
PatientID: str = ''
PatientBirthDate: str = ''
PatientSex: str = ''
Manufacturer: str = ''
ManufacturerModelName: str = ''
RelationshipGroupLength: int = 0
ImagePresentationGroupLength: int = 0
PixelPaddingValue: float = 0
PlanGroupLength: int = 0
RTPlanLabel: str = ''
RTPlanDate: str = ''
RTPlanTime: str = ''
RTPlanGeometry: str = ''
TreatmentSites: array
PrescriptionDescription: str = ''
DoseReferenceSequence: array
FractionGroupSequence: array
BeamSequence: array
PatientSetupSequence: array
ReferencedRTGroupLength: int = 0
ReferencedStructureSetSequence: array
ReferencedDoseSequence: array
ReviewGroupLength: int = 0
ApprovalStatus: str = ''
ReviewDate: str = ''
ReviewTime: str = ''
ReviewerName: str = ''
SOPInstanceUID: str = ''
beamFileName: str = ''
manufacturer: str = ''
manufacturerModelName: str = ''
deIdentificationMethod: str = ''
deidentificationMethodDescription: array
BeamUID: str = ''
class cerr.dataclasses.beams.ReferenceSeq(ReferencedSOPClassUID: str = '', ReferencedSOPInstanceUID: str = '')[source]

Bases: object

This class defines referenced sequence. .. attribute:: ReferencedSOPClassUID

Referenced SOP class UID

type:

str

ReferencedSOPInstanceUID

Referenced SOP instance UID

Type:

str

ReferencedSOPClassUID: str = ''
ReferencedSOPInstanceUID: str = ''
class cerr.dataclasses.beams.PatientSetupSeq(PatientSetupNumber: int = 0, PatientPosition: str = '')[source]

Bases: object

This class defines patient setup sequence. .. attribute:: PatientSetupNumber

Identification number of the Patient Setup as per (300A,0182) DICOM tag

type:

int

PatientPosition

Patient position descriptor relative to the equipment as per (0018,5100) DICOM tag

Type:

str

PatientSetupNumber: int = 0
PatientPosition: str = ''
class cerr.dataclasses.beams.DoseReferenceSeq[source]

Bases: object

This class defines sequence of dose references. .. attribute:: DoseReferenceType

Type of dose reference (TARGET, ORGAN_AT_RISK)

type:

str

DoseReferenceUID

Unique identifier for dose reference

Type:

str

ReferencedROINumber

Unique identifier for associated ROI

Type:

str

DeliveryMaximumDose

Max dose (Gy) that can be delivered to the dose reference

Type:

float

TargetPrescriptionDose

Prescribed dose (Gy) to dose reference if DoseReferenceType is TARGET.

Type:

float

DoseReferenceType: str = ''
DoseReferenceUID: str = ''
ReferencedROINumber: str = ''
DeliveryMaximumDose: float = nan
TargetPrescriptionDose: float = nan
class cerr.dataclasses.beams.BeamLimitingDevicePositionSeq(RTBeamLimitingDeviceType: str = '', LeafJawPositions: array = <factory>)[source]

Bases: object

This class defines data model for Sequence of beam limiting device (collimator) jaw or leaf (element) positions. .. attribute:: RTBeamLimitingDeviceType

Type of beam limiting device (collimator) as per (300A,00B8) DICOM tag

type:

str

LeafJawPositions

Positions of beam limiting device (collimator) leaf (element) or jaw pairs (in mm) in IEC BEAM LIMITING DEVICE coordinate axis appropriate to RT Beam Limiting Device Type as defined in (300A,011C) DICOM tag

Type:

np.array

RTBeamLimitingDeviceType: str = ''
LeafJawPositions: array
class cerr.dataclasses.beams.ControlPointSequence(BeamLimitingDevicePositionSequence: array = <factory>, ControlPointIndex: int = nan, NominalBeamEnergy: float = nan, GantryAngle: float = nan, GantryRotationDirection: str = '', BeamLimitingDeviceAngle: float = nan, BeamLimitingDeviceRotationDirection: str = '', PatientSupportAngle: float = nan, TableTopEccentricAngle: float = nan, TableTopEccentricRotationDirection: str = '', IsocenterPosition: array = <factory>, SourceToSurfaceDistance: float = nan, CumulativeMetersetWeight: float = nan)[source]

Bases: object

This class defines data model for the Sequence of machine configurations describing treatment beam. .. attribute:: BeamLimitingDevicePositionSequence

Sequence of beam limiting device (collimator) jaw or leaf (element) positions as per (300A,011A) DICOM tag.

type:

np.array

ControlPointIndex

Index of current Control Point, starting at 0 for first Control Point as per (300A,0112) DICOM tag.

Type:

int

NominalBeamEnergy

Nominal Beam Energy at control point (MV/MeV) as per (300A,0114) DICOM tag

Type:

float

GantryAngle

Gantry angle of radiation source, i.e., orientation of IEC GANTRY coordinate system with respect to IEC FIXED REFERENCE coordinate system (degrees) as per (300A,011E) DICOM tag.

Type:

float

GantryRotationDirection

Direction of Gantry Rotation when viewing gantry from isocenter, for segment following Control Point as per (300A,011F) DICOM tag.

Type:

str

BeamLimitingDeviceAngle

Beam Limiting Device angle, i.e., orientation of IEC BEAM LIMITING DEVICE coordinate system with respect to IEC GANTRY coordinate system (degrees) as per (300A,0120) DICOM tag.

Type:

float

BeamLimitingDeviceRotationDirection

Direction of Beam Limiting Device Rotation when viewing beam limiting device (collimator) from radiation source, for segment following Control Point as per (300A,0121) DICOM tag

Type:

str

PatientSupportAngle

Patient Support angle, i.e., orientation of IEC PATIENT SUPPORT (turntable) coordinate system with respect to IEC FIXED REFERENCE coordinate system (degrees) as per (300A,0122) DICOM tag

Type:

float

TableTopEccentricAngle

Table Top (non-isocentric) angle, i.e., orientation of IEC TABLE TOP ECCENTRIC coordinate system with respect to IEC PATIENT SUPPORT coordinate system (degrees) as per (300A,0125) DICOM tag.

Type:

float

TableTopEccentricRotationDirection
Type:

str

IsocenterPosition

Direction of Table Top Eccentric Rotation when viewing table from above, for segment following Control Point as per (300A,0126) DICOM tag

Type:

np.array

SourceToSurfaceDistance

Source to Patient Surface (skin) distance (mm) as per (300A,0130) DICOM tag

Type:

float

CumulativeMetersetWeight

Cumulative weight to current control point as per (300A,0134) DICOM tag

Type:

float

BeamLimitingDevicePositionSequence: array
ControlPointIndex: int = nan
NominalBeamEnergy: float = nan
GantryAngle: float = nan
GantryRotationDirection: str = ''
BeamLimitingDeviceAngle: float = nan
BeamLimitingDeviceRotationDirection: str = ''
PatientSupportAngle: float = nan
TableTopEccentricAngle: float = nan
TableTopEccentricRotationDirection: str = ''
IsocenterPosition: array
SourceToSurfaceDistance: float = nan
CumulativeMetersetWeight: float = nan
class cerr.dataclasses.beams.RefBeamSeq(ReferencedBeamNumber: int = 0, BeamMeterset: float = 0)[source]

Bases: object

This class defies data model for the sequence of Beams in current Fraction Group contributing to dose as per (300C,0004) DICOM tag. .. attribute:: ReferencedBeamNumber

Uniquely identifies Beam specified by Beam Number as per (300C,0006) DICOM tag

type:

int

BeamMeterset

Meterset duration over which image is to be acquired, specified in Monitor units (MU) as per (3002,0032) DICOM tag

Type:

float

ReferencedBeamNumber: int = 0
BeamMeterset: float = 0
class cerr.dataclasses.beams.FractionGroupSeq(FractionGroupNumber: int = 0, NumberOfFractionsPlanned: int = 0, NumberOfBeams: int = 0, NumberOfBrachyApplicationSetups: int = 0, RadiationType: str = '', RefBeamSeq: array = <factory>)[source]

Bases: object

This class defines data model for Sequence of Fraction Groups in current Fraction Scheme as per (300A,0070) DICOM tag. .. attribute:: FractionGroupNumber

Identification number of the Fraction Group as per (300A,0071)

type:

int

NumberOfFractionsPlanned

Total number of treatments (Fractions) prescribed for current Fraction Group as per (300A,0078)

Type:

int

NumberOfBeams

Number of Beams in current Fraction Group as per (300A,0080)

Type:

int

NumberOfBrachyApplicationSetups

Number of Brachy Application Setups in current Fraction Group as per (300A,00A0)

Type:

int

RadiationType

Particle type of Beam as per (300A,00C6)

Type:

str

RefBeamSeq

Sequence of Beams in current Fraction Group contributing to dose as per (300C,0004)

Type:

np.array

FractionGroupNumber: int = 0
NumberOfFractionsPlanned: int = 0
NumberOfBeams: int = 0
NumberOfBrachyApplicationSetups: int = 0
RadiationType: str = ''
RefBeamSeq: array
class cerr.dataclasses.beams.BeamSeq(Manufacturer: str = '', BeamName: str = '', BeamType: str = '', BeamDescription: str = '', BeamNumber: int = 0, SourceAxisDistance: float = 0, BeamLimitingDevicePositionSeq: array = <factory>, RadiationType: str = '', TreatmentDeliveryType: str = '', NumberOfWedges: float = 0, NumberOfBoli: float = 0, NumberOfCompensators: float = 0, NumberOfBlocks: float = 0, NumberOfControlPoints: float = 0, ControlPointSequence: array = <factory>)[source]

Bases: object

This class defines data model for Sequence of treatment beams for current RT Plan as per (300A,00B0) DICOM tag. .. attribute:: Manufacturer

Manufacturer of the equipment to be used for beam delivery as per (0008,0070)

type:

str

BeamName

primary beam identifier (often referred to as “field identifier”) as per (300A,00C2)

Type:

str

BeamType

Motion characteristic of Beam as per (300A,00C4)

Type:

str

BeamDescription

User-defined description for Beam as per (300A,00C3)

Type:

str

BeamNumber

Identification number of the Beam as per (300A,00C0)

Type:

int

SourceAxisDistance

Radiation source to Gantry rotation axis distance of the equipment that is to be used for beam delivery (mm) as per (300A,00B4)

Type:

float

BeamLimitingDevicePositionSeq

Sequence of beam limiting device (collimator) jaw or leaf (element) sets as per (300A,00B6)

Type:

np.array

RadiationType

Particle type of Beam as per (300A,00C6)

Type:

str

TreatmentDeliveryType

Delivery Type of treatment as per (300A,00CE)

Type:

str

NumberOfWedges

Number of wedges associated with current Beam as per (300A,00D0)

Type:

float

NumberOfBoli

Number of boli associated with current Beam as per (300A,00ED)

Type:

float

NumberOfCompensators

Number of compensators associated with current Beam as per (300A,00E0)

Type:

float

NumberOfBlocks

Number of shielding blocks associated with Beam as per (300A,00F0)

Type:

float

NumberOfControlPoints

Number of control points in Beam as per (300A,0110)

Type:

float

ControlPointSequence

Sequence of machine configurations describing treatment beam as per (300A,0111)

Type:

np.array

Manufacturer: str = ''
BeamName: str = ''
BeamType: str = ''
BeamDescription: str = ''
BeamNumber: int = 0
SourceAxisDistance: float = 0
BeamLimitingDevicePositionSeq: array
RadiationType: str = ''
TreatmentDeliveryType: str = ''
NumberOfWedges: float = 0
NumberOfBoli: float = 0
NumberOfCompensators: float = 0
NumberOfBlocks: float = 0
NumberOfControlPoints: float = 0
ControlPointSequence: array
class json_serialize(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(obj)[source]

Serialize a Beams instance to a JSON-compatible dictionary.

Overrides json.JSONEncoder.default to handle Beams objects by returning a compact dictionary containing only the beam’s UID. All other object types are serialized as an empty string instead of raising a TypeError.

Parameters:

obj (object) – The object to serialize.

Returns:

{'beams': obj.BeamUID} when obj is a Beams instance; otherwise an empty string "".

Return type:

dict or str

cerr.dataclasses.beams.load_beams(file_list)[source]

This routine parses a list of DICOM files and imports metadata from RTPLAN modality into a list of pyCERR’s Beams objects

Parameters:

file_list (List[str]) – List of DICOM file paths.

Returns:

List of pyCERR’s Beam objects.

Return type:

List[cerr.dataclasses.beams.Beams]

cerr.dataclasses.deform module

structure module.

Ths deform module defines metadata for deformation (REG). The metadata are attributes of the Deform class. This module also defines routines for transforming and accessing the Deformation Vector Field metadata in CERR coordinate system.

cerr.dataclasses.deform.get_empty_list()[source]

Return an empty list.

Used as a default_factory for dataclass fields that require a mutable list default.

Returns:

An empty list [].

Return type:

list

cerr.dataclasses.deform.get_empty_np_array()[source]

Return an empty 3-D NumPy array with shape (0, 0, 0).

Used as a default_factory for dataclass fields that require a mutable NumPy array default.

Returns:

A zero-element array with shape (0, 0, 0).

Return type:

np.ndarray

class cerr.dataclasses.deform.Deform(baseScanUID: str = '', movScanUID: str = '', algorithm: str = '', algorithmParams: dict = <factory>, deformParams: dict = <factory>, deformUID: str = '', registrationTool: str = '', deformOutFileType: str = '', deformOutFilePath: str = '', dvfMatrix: numpy.ndarray = <factory>, xOffset: float = 0.0, yOffset: float = 0.0, dx: float = 0.0, dy: float = 0.0, imageOrientationPatient: <built-in function array> = <factory>, imagePositionPatientV: <built-in function array> = <factory>, zValuesV: numpy.ndarray = <factory>, Image2PhysicalTransM: numpy.ndarray = <factory>, Image2VirtualPhysicalTransM: numpy.ndarray = <factory>, cerrToDcmTransM: numpy.ndarray = <factory>)[source]

Bases: object

baseScanUID: str = ''
movScanUID: str = ''
algorithm: str = ''
algorithmParams: dict
deformParams: dict
deformUID: str = ''
registrationTool: str = ''
deformOutFileType: str = ''
deformOutFilePath: str = ''
dvfMatrix: ndarray
xOffset: float = 0.0
yOffset: float = 0.0
dx: float = 0.0
dy: float = 0.0
imageOrientationPatient: array
imagePositionPatientV: array
zValuesV: ndarray
Image2PhysicalTransM: ndarray
Image2VirtualPhysicalTransM: ndarray
cerrToDcmTransM: ndarray
convertDcmToCerrVirtualCoords()[source]

Compute and store coordinate-system transformation matrices for the DVF.

Builds the affine mapping from DICOM image indices to DICOM physical (patient) coordinates (Image2PhysicalTransM) and to pyCERR’s virtual physical coordinate system (Image2VirtualPhysicalTransM), accounting for the possibility that CERR’s slice ordering is the reverse of DICOM’s. Also populates xOffset, yOffset, and cerrToDcmTransM (the transformation that converts pyCERR xyz coordinates in cm back to DICOM physical coordinates in mm).

The method operates entirely on the instance attributes already set (imageOrientationPatient, imagePositionPatientV, dvfMatrix, dx, dy) and updates the following attributes in-place:

Attributes set:
xOffset (float): X-coordinate of the DVF volume centre in the CERR

coordinate system (cm).

yOffset (float): Y-coordinate of the DVF volume centre in the CERR

coordinate system (cm, sign-flipped relative to DICOM column direction).

Image2PhysicalTransM (np.ndarray): 4×4 affine from DICOM image

indices to DICOM physical coordinates (cm).

Image2VirtualPhysicalTransM (np.ndarray): 4×4 affine from DICOM

image indices to pyCERR virtual physical coordinates (cm).

cerrToDcmTransM (np.ndarray): 4×4 matrix converting pyCERR xyz
  1. to DICOM physical coordinates (mm).

getDVFXYZVals()[source]

Compute the x, y, and z coordinate vectors for the DVF grid.

Derives spatial coordinate arrays from the stored grid offsets (xOffset, yOffset), voxel spacings (dx, dy), and per-slice z-values (zValuesV) based on the dimensions of dvfMatrix.

Returns:

A 3-tuple (xvals, yvals, zvals) where

  • xvals (np.ndarray): 1-D array of x-coordinates (cm) for each column of the DVF grid, increasing left-to-right.

  • yvals (np.ndarray): 1-D array of y-coordinates (cm) for each row of the DVF grid, decreasing top-to-bottom (CERR convention).

  • zvals (np.ndarray): 1-D array of z-coordinates (cm) for each slice, taken directly from self.zValuesV.

Return type:

tuple

getDeformDict()[source]

Return a shallow copy of the Deform instance’s attribute dictionary.

Returns:

A dictionary mapping each attribute name to its current value for this Deform instance.

Return type:

dict

cerr.dataclasses.deform.flipSliceOrderFlag(deform)[source]

Determine whether the slice ordering in the Deform object is reversed relative to DICOM.

Computes the slice normal from the image orientation cosines and projects consecutive imagePositionPatient vectors onto it. A negative dot-product difference indicates that DICOM slices are stored in the opposite order from pyCERR’s internal convention.

Parameters:

deform (Deform) – A Deform dataclass instance whose imageOrientationPatient (shape (6,)) and imagePositionPatientV (shape (N, 3)) attributes are already populated.

Returns:

True if the slice order should be flipped (i.e. DICOM stores slices in descending z-order relative to pyCERR), False otherwise.

Return type:

bool

cerr.dataclasses.dose module

dose module.

The dose module defines metadata for an RTDOSE object. The metadata are attributes of the Dose class. This module also defines routines for transforming and accessing the Dose metadata in CERR coordinate system.

cerr.dataclasses.dose.get_empty_list()[source]

Return an empty list, used as a default factory for dataclass list fields.

Returns:

An empty list.

Return type:

list

cerr.dataclasses.dose.get_empty_np_array()[source]

Return an empty 3-D NumPy array, used as a default factory for dataclass array fields.

Returns:

An empty array with shape (0, 0, 0).

Return type:

np.ndarray

class cerr.dataclasses.dose.Dose(caseNumber: int = 0, patientName: str = '', doseNumber: int = 0, doseType: str = '', doseSummationType: str = '', refBeamNumber: int = 0, refFractionGroupNumber: int = 0, numberMultiFrameImages: int = 0, doseUnits: str = '', doseScale: float = 1, fractionGroupID: str = '', numberOfTx: int = 0, orientationOfDose: str = '', imagePositionPatient: array = <factory>, imageOrientationPatient: array = <factory>, numberRepresentation: int = 0, numberOfDimensions: int = 0, sizeOfDimension1: int = 0, sizeOfDimension2: int = 0, sizeOfDimension3: int = 0, coord1OFFirstPoint: float = 0, coord2OFFirstPoint: float = 0, horizontalGridInterval: float = 0, verticalGridInterval: float = 0, doseDescription: str = '', doseEdition: str = '', unitNumber: int = 0, writer: str = '', dateWritten: str = '', planNumberOfOrigin: int = 0, planEditionOfOrigin: str = '', studyNumberOfOrigin: int = 0, studyInstanceUID: str = '', manufacturer: str = '', manufacturerModelName: str = '', deIdentificationMethod: str = '', deidentificationMethodDescription: array = <factory>, versionNumberOfProgram: str = '', xcoordOfNormaliznPoint: float = nan, ycoordOfNormaliznPoint: float = nan, zcoordOfNormaliznPoint: float = nan, doseAtNormaliznPoint: float = nan, doseError: float = nan, coord3OfFirstPoint: float = nan, depthGridInterval: float = nan, planIDOfOrigin: str = '', doseArray: array = <factory>, zValues: array = <factory>, delivered: str = '', cachedColor: str = '', cachedTime: str = '', numCachedSlices: int = 0, transferProtocol: str = '', associatedScan: int = nan, transM: array = <factory>, doseUID: str = '', assocScanUID: str = '', assocBeamUID: str = '', doseFileName: str = '', frameOfReferenceUID: str = '', refRTPlanSopInstanceUID: str = '', refStructSetSopInstanceUID: str = '', prescriptionDose: float = 0, doseOffset: float = 0, cerrToDcmTransM: array = <factory>, Image2PhysicalTransM: array = <factory>, cerrDcmSliceDirMatch: bool = False)[source]

Bases: object

This class defines data object for RTDose. The metadata is populated from DICOM.

patientName

Patient’s name

Type:

str

doseType

Type of dose as per (3004,0004). Values can be PHYSICAL, EFFECTIVE or ERROR

Type:

str

doseSummationType

Type of dose summation as per (3004,000A)

Type:

str

refBeamNumber

Referenced beam number from ReferencedRTPlanSequence

Type:

int

refFractionGroupNumber

Referenced Fraction Group number from ReferencedRTPlanSequence

Type:

int

numberMultiFrameImages

Number of image frames

Type:

int

doseUnits

Units used to describe dose. GY or RELATIVE

Type:

str

doseScale

Scaling factor that when multiplied by the dose grid data found in Pixel Data (7FE0,0010) Attribute of the Image Pixel Module, yields grid doses in the dose units as specified by Dose Units (3004,0002).

Type:

float

fractionGroupID

Fraction Group ID from Referenced RTPLAN

Type:

str

imagePositionPatient

x,y,z coordinate of the top left voxel of the dose volume.

Type:

np.array

imageOrientationPatient

Direction cosine of dose row and column with patient coordinate system.

Type:

np.array

sizeOfDimension1

Number of columns of doseArray

Type:

int

sizeOfDimension2

Number of rows of doseArray

Type:

int

sizeOfDimension3

Number of slices of doseArray

Type:

int

coord1OFFirstPoint

x-coordinate of dose in CERR virtual coordinates

Type:

float

coord2OFFirstPoint

y-coordinate of dose in CERR virtual coordinates

Type:

float

horizontalGridInterval

delta x of dose in CERR virtual coordinates

Type:

float

verticalGridInterval

delta y of dose in CERR virtual coordinates

Type:

float

writer

Equipment Manufacturer for RTDOSE delivery.

Type:

str

dateWritten

Study Date.

Type:

str

studyInstanceUID

Study Instance UID of dose.

Type:

str

manufacturer

Scanner Manufacturer

Type:

str

manufacturerModelName

Manufacturer model name

Type:

str

deIdentificationMethod

Indicates whether patient identity has been removed.

Type:

str

deidentificationMethodDescription

codes that specifies the methods used to de-identify patient data

Type:

np.array

xcoordOfNormaliznPoint

x-ccordinate of normalization point

Type:

float

ycoordOfNormaliznPoint

y-ccordinate of normalization point

Type:

float

zcoordOfNormaliznPoint

z-ccordinate of normalization point

Type:

float

doseAtNormaliznPoint

dose at normalization point

Type:

float

coord3OfFirstPoint

z-coordinate of dose in CERR virtual coordinates

Type:

float

doseArray

3D volume for RTODSE in doseUnits

Type:

np.array

zValues

z-coordinates of doseArray in CERR virtual coordinate system.

Type:

np.array

delivered

whether the dose was delivered.

Type:

str

transM

transformation matrix to transform dose.

Type:

np.array

doseUID

unique identifier of dose.

Type:

str

assocScanUID

associated scan’s unique identifier

Type:

str

assocBeamUID

associated RTPLAN’s unique identifier

Type:

str

doseFileName

dose file name

Type:

str

frameOfReferenceUID

Frame of Reference UID

Type:

str

refRTPlanSopInstanceUID

SOP Instance UID of associated RTPLAN

Type:

str

refStructSetSopInstanceUID

SOP Instance UID of referenced RTSTRUCT

Type:

str

prescriptionDose

Prescription dose

Type:

float

doseOffset

offset value to add to doseArray

Type:

float

Image2PhysicalTransM

Transformation matrix to convert pyCERR’s dose row,col,slc to DICOM physical coordinates.

Type:

np.ndarray

cerrDcmSliceDirMatch

Flag whether pyCERR slice order matches DICOM.

Type:

bool

caseNumber: int = 0
patientName: str = ''
doseNumber: int = 0
doseType: str = ''
doseSummationType: str = ''
refBeamNumber: int = 0
refFractionGroupNumber: int = 0
numberMultiFrameImages: int = 0
doseUnits: str = ''
doseScale: float = 1
fractionGroupID: str = ''
numberOfTx: int = 0
orientationOfDose: str = ''
imagePositionPatient: array
imageOrientationPatient: array
numberRepresentation: int = 0
numberOfDimensions: int = 0
sizeOfDimension1: int = 0
sizeOfDimension2: int = 0
sizeOfDimension3: int = 0
coord1OFFirstPoint: float = 0
coord2OFFirstPoint: float = 0
horizontalGridInterval: float = 0
verticalGridInterval: float = 0
doseDescription: str = ''
doseEdition: str = ''
unitNumber: int = 0
writer: str = ''
dateWritten: str = ''
planNumberOfOrigin: int = 0
planEditionOfOrigin: str = ''
studyNumberOfOrigin: int = 0
studyInstanceUID: str = ''
manufacturer: str = ''
manufacturerModelName: str = ''
deIdentificationMethod: str = ''
deidentificationMethodDescription: array
versionNumberOfProgram: str = ''
xcoordOfNormaliznPoint: float = nan
ycoordOfNormaliznPoint: float = nan
zcoordOfNormaliznPoint: float = nan
doseAtNormaliznPoint: float = nan
doseError: float = nan
coord3OfFirstPoint: float = nan
depthGridInterval: float = nan
planIDOfOrigin: str = ''
doseArray: array
zValues: array
delivered: str = ''
cachedColor: str = ''
cachedTime: str = ''
numCachedSlices: int = 0
transferProtocol: str = ''
associatedScan: int = nan
transM: array
doseUID: str = ''
assocScanUID: str = ''
assocBeamUID: str = ''
doseFileName: str = ''
frameOfReferenceUID: str = ''
refRTPlanSopInstanceUID: str = ''
refStructSetSopInstanceUID: str = ''
prescriptionDose: float = 0
doseOffset: float = 0
cerrToDcmTransM: array
Image2PhysicalTransM: array
cerrDcmSliceDirMatch: bool = False
class json_serialize(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(obj)[source]

Serialize a Dose object to a JSON-compatible dictionary.

Parameters:

obj – The object to serialize.

Returns:

A dictionary with key 'dose' mapped to the dose’s UID

when obj is a Dose instance, otherwise an empty string.

Return type:

dict

getNiiAffine()[source]

Routine for affine transformation of pyCERR dose object for storing in NifTi format

Returns:

3x3 affine matrix

Return type:

np.ndarray

getSitkImage()[source]

Convert the pyCERR Dose object to a SimpleITK Image.

The dose array is reoriented from pyCERR’s (row, col, slice) order to SimpleITK’s (z, y, x) order, and image metadata (origin, spacing, direction cosines) are applied.

Returns:

A 3-D SimpleITK image populated with the dose array and spatial metadata.

Return type:

SimpleITK.Image

getDoseDict()[source]

Return a shallow copy of the Dose instance’s attribute dictionary.

Returns:

A dictionary mapping each attribute name to its current value for this Dose instance. Used for HDF5 serialization.

Return type:

dict

saveNii(niiFileName)[source]

Routine to save pyCERR Dose object to NifTi file

Parameters:

niiFileName (str) – File name including the full path to save the pyCERR dose object to NifTi file.

Returns:

0 when NifTi file is written successfully.

Return type:

int

getImage2PhysicalTransM(assocScanNum, planC)[source]

Compute the 4x4 affine matrix that maps dose image indices to DICOM physical coordinates (cm).

Parameters:
  • assocScanNum (int) – Index of the associated scan in planC.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object.

Returns:

A 4x4 homogeneous transformation matrix that converts (column, row, slice) image indices to physical coordinates in cm.

Return type:

np.ndarray

convertDcmToCerrVirtualCoords(planC)[source]

Convert dose grid coordinates from DICOM to pyCERR virtual coordinates.

Populates coord1OFFirstPoint, coord2OFFirstPoint, horizontalGridInterval, verticalGridInterval, and zValues in pyCERR’s virtual coordinate system. Also flips the dose array and z-values when the DICOM slice order does not match pyCERR’s expected order, and sets cerrDcmSliceDirMatch accordingly.

More information about virtual coordinates is on the Wiki: https://github.com/cerr/pyCERR/wiki/Coordinate-system

Parameters:

planC (cerr.plan_container.PlanC) – pyCERR’s plan container object used to look up the associated scan and its coordinate transforms.

Returns:

The updated Dose instance (self).

Return type:

Dose

getDoseXYZVals()[source]

Routine to obtain pyCERR dose object’s x,y,z grid coordinates. The coordinates are in pyCERR’s virtual coordinate system.

Returns:

x, y, z coordinates corresponding to the columns, rows, slices of scan voxels

Return type:

tuple

getDoseAt(xV, yV, zV)[source]

Return interpolated dose values at the specified pyCERR virtual coordinates.

Parameters:
  • xV (np.ndarray or float) – x-coordinates (columns) at which to interpolate the dose, in pyCERR virtual coordinate units (cm).

  • yV (np.ndarray or float) – y-coordinates (rows) at which to interpolate the dose, in pyCERR virtual coordinate units (cm).

  • zV (np.ndarray or float) – z-coordinates (slices) at which to interpolate the dose, in pyCERR virtual coordinate units (cm).

Returns:

Array of interpolated dose values at each (x, y, z) point.

Return type:

np.ndarray

getAssociatedBeamNum(planC)[source]

Routine to obtain index of planC.beams that generated this RTDOSE

Parameters:

planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

Returns:

index of planC.beams

Return type:

int

cerr.dataclasses.dose.loadDose(file_list)[source]

Parse a list of DICOM files and return pyCERR Dose objects for each RTDOSE file found.

Parameters:

file_list (list) – list of files to read into pyCERR’s Dose object

Returns:

List whose elements are pyCERR Dose objects containing metadata from file_list.

Return type:

List[cerr.dataclasses.dose.Dose]

cerr.dataclasses.dose.importNii(file_list, assocScanNum, planC)[source]

This routine imports RT dose distributions from a list of nii files into planC.

Parameters:
  • file_list (List or str) – List of nii file paths or a string containing path for a single file.

  • assocScanNum (int) – index of scan in planC to associate the segmentation.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object.

Returns:

pyCERR’s plan container object

Return type:

cerr.plan_container.PlanC

cerr.dataclasses.dose.getDoseNumFromUID(assocDoseUID, planC) int[source]

Return the index of the dose in planC whose UID matches the given doseUID.

Parameters:
Returns:

index of planC.dose matching input assocDoseUID, or None if not found.

Return type:

int

cerr.dataclasses.dose.getPrescriptionDose(doseIdx, planC)[source]

Return the prescription dose for the plan associated with the specified dose.

Parameters:
Returns:

Prescribed dose in Gy, or None if the tag is unavailable.

Return type:

float

cerr.dataclasses.dose.getNumFrx(doseIdx, planC)[source]

Return the number of planned fractions for the dose at the given index.

Parameters:
Returns:

Number of planned fractions, or None if the tag is unavailable.

Return type:

int

cerr.dataclasses.dose.getFrxSize(doseIdx, planC)[source]

Return the fraction size (dose per fraction) for the dose at the given index.

Computed as the prescription dose divided by the number of planned fractions.

Parameters:
Returns:

Fraction size in Gy.

Return type:

float

cerr.dataclasses.dose.fractionSizeCorrect(dose, stdFrxSize, abRatio, planC=None, inputFrxSize=None)[source]

Convert a dose distribution to its radiobiological equivalent at a different fraction size.

Uses the linear-quadratic (LQ) model to compute the equivalent dose when the fraction size is changed from inputFrxSize to stdFrxSize.

Parameters:
  • dose (np.ndarray or int) – 3-D dose array in Gy, or an integer index into planC.dose. When an index is supplied, planC must also be provided.

  • stdFrxSize (float) – Target (output) fraction size in Gy.

  • abRatio (float) – Alpha/beta ratio in Gy for the tissue of interest.

  • planC (cerr.plan_container.PlanC, optional) – pyCERR’s plan container object. Required when dose is an index. Defaults to None.

  • inputFrxSize (float, optional) – Fraction size of the input dose in Gy. Required when dose is a numpy array. Defaults to None.

Returns:

Dose array corrected to the equivalent dose at stdFrxSize.

Return type:

np.ndarray

cerr.dataclasses.dose.fractionNumCorrect(dose, stdFrxNum, abRatio, planC=None, inputFrxNum=None)[source]

Convert a dose distribution to its radiobiological equivalent delivered in a different number of fractions.

Uses the linear-quadratic (LQ) model to compute the equivalent total dose when the number of fractions changes from inputFrxNum to stdFrxNum, solving the resulting quadratic equation analytically.

Parameters:
  • dose (np.ndarray or int) – 3-D dose array in Gy, or an integer index into planC.dose. When an index is supplied, planC must also be provided.

  • stdFrxNum (int) – Target (output) number of fractions.

  • abRatio (float) – Alpha/beta ratio in Gy for the tissue of interest.

  • planC (cerr.plan_container.PlanC, optional) – pyCERR’s plan container object. Required when dose is an index. Defaults to None.

  • inputFrxNum (int, optional) – Number of fractions of the input dose. Required when dose is a numpy array. Defaults to None.

Returns:

Dose array corrected to the equivalent total dose delivered in stdFrxNum fractions.

Return type:

np.ndarray

cerr.dataclasses.dose.sum(doseIndV, planC, fxCorrectDict={}, frxSizeV=None)[source]

Sum multiple dose distributions onto a shared grid, with optional fractionation correction.

The output grid spans the union of all input dose grid extents and uses the finest resolution found across all inputs. Each dose is resampled to the shared grid before summation.

Parameters:
  • doseIndV (list) – Indices of doses in planC to be summed.

  • planC (plan_container.planC) – pyCERR’s plan container object.

  • fxCorrectDict (dict) – Dictionary specifying correctionType ('fractionNum' or 'fractionSize') and any additional keyword arguments forwarded to the correction function. Pass an empty dict (default) to skip fractionation correction.

  • frxSizeV (list, optional) – Per-dose fraction sizes used when fxCorrectDict is provided and fraction size cannot be inferred from the plan. Defaults to None.

Returns:

  • sumDose (np.ndarray): Summed dose array on the shared grid.

  • refGrid (tuple): (xOutV, yOutV, zOutV) coordinate vectors of the output dose grid.

Return type:

tuple

cerr.dataclasses.header module

header module.

The header module defines metadata for header. The header metadata are useful to keep track of pyCERR version used in creation of plan container object as well as date stamp when it is saved.

class cerr.dataclasses.header.Header(dateCreated: str = '20260617', dateLastSaved: str = '', writer: str = '', version: str = '0.1.test000+ghash')[source]

Bases: object

dt = datetime.datetime(2026, 6, 17, 18, 11, 49, 86184)
dateCreated: str = '20260617'
dateLastSaved: str = ''
writer: str = ''
version: str = '0.1.test000+ghash'

cerr.dataclasses.imrt module

cerr.dataclasses.imrt.get_empty_list()[source]
cerr.dataclasses.imrt.get_empty_np_array()[source]
class cerr.dataclasses.imrt.IM(IMSetup: dict = <factory>, IMDosimetry: dict = <factory>, IMUID: str = '')[source]

Bases: object

IMSetup: dict
IMDosimetry: dict
IMUID: str = ''

cerr.dataclasses.scan module

scan module.

This module defines pyCERR data object for images (CT, MR, PT, US). Metadata can be imported from various file formats such as DICOM, NifTi. It also provides methods to transform the Scan object to other formats such NifTi, SimpleITK and for converting images to real world units and SUV calculation.

cerr.dataclasses.scan.get_empty_list()[source]

Return an empty list, used as a default factory for dataclass fields.

Returns:

An empty list.

Return type:

list

cerr.dataclasses.scan.get_empty_np_array()[source]

Return an empty 3-D numpy array, used as a default factory for dataclass fields.

Returns:

A zero-element array with shape (0, 0, 0).

Return type:

np.ndarray

class cerr.dataclasses.scan.Scan(scanArray: ndarray = <factory>, scanType: str = '', scanInfo: ScanInfo = <factory>, uniformScanInfo: UniformScanInfo = <factory>, scanArraySuperior: ndarray = <factory>, scanArrayInferior: ndarray = <factory>, thumbnails: ndarray = <factory>, transM: ndarray = <factory>, scanUID: str = '', assocDeformUID: str = '', assocTextureUID: str = '', assocBaseScanUID: str = '', assocMovingScanUID: str = '', Image2PhysicalTransM: ndarray = <factory>, Image2VirtualPhysicalTransM: ndarray = <factory>, cerrToDcmTransM: ndarray = <factory>)[source]

Bases: object

This class defines data object for volumetric images such as CT, MR, PET or derived image type.

scanArray

numpy array for the image.

Type:

np.ndarray

scanType

Type of scan. e.g. ‘CT SCAN’

Type:

str

scanInfo

scan_info object containing metadata for each scan slice

Type:

cerr.dataclasses.scan_info.ScanInfo

scanUID

unique identifier for each scan.

Type:

str

assocDeformUID

optional, UID of associated deformation object that was used to generate this scan.

Type:

str

assocTextureUID

optional, UID of associated texture object that was used to generate this scan.

Type:

str

assocBaseScanUID

optional, UID of associated base scan in the deformation that was used to generate this scan.

Type:

str

assocMovingScanUID

optional, UID of associated moving scan in the deformation that was used to generate this scan.

Type:

str

Image2PhysicalTransM

Transformation matrix to convert pyCERR row,col,slc to DICOM physical coordinates.

Type:

np.ndarray

Image2VirtualPhysicalTransM

Transformation matrix to convert pyCERR’s scan row,col,slc to pyCERR virtual coordinates.

Type:

np.ndarray

cerrToDcmTransM

Transformation matrix to convert pyCERR virtual x,y,z coordinates to DICOM physical coordinates.

Type:

np.ndarray

scanArray: ndarray
scanType: str = ''
scanInfo: ScanInfo
uniformScanInfo: UniformScanInfo
scanArraySuperior: ndarray
scanArrayInferior: ndarray
thumbnails: ndarray
transM: ndarray
scanUID: str = ''
assocDeformUID: str = ''
assocTextureUID: str = ''
assocBaseScanUID: str = ''
assocMovingScanUID: str = ''
Image2PhysicalTransM: ndarray
Image2VirtualPhysicalTransM: ndarray
cerrToDcmTransM: ndarray
class json_serialize(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(obj)[source]

Serialize a Scan instance to a JSON-compatible dictionary.

Parameters:

obj (Any) – Object to serialize. When the object is an instance of Scan its scanUID is returned; all other types fall back to an empty string.

Returns:

{'scan': obj.scanUID} for Scan instances,

otherwise an empty string.

Return type:

str | dict

getScanArray()[source]

Routine to obtain image in the units defined in planC.scan[scanNum].scanInfo[slcNum].imageUnits :returns:

CTOffset is added to to scanArray such that the resulting array is in

real world units such as HU, SUV

Return type:

np.ndarray

getNiiAffine()[source]

Routine for affine transformation of pyCERR scan object for storing in NifTi format

Returns:

3x3 affine matrix

Return type:

np.ndarray

saveNii(niiFileName)[source]

Routine to save pyCERR Scan object to NifTi file

Parameters:

niiFileName (str) – File name including the full path to save the pyCERR scan object to NifTi file.

Returns:

0 when NifTi file is written successfully.

Return type:

int

getSitkImage()[source]

Routine to convert pyCERR Scan object to SimpleITK Image object

Returns:

SimpleITK Image

Return type:

sitk.Image

getScanXYZVals()[source]

Routine to obtain pyCERR scan object’s x,y,z grid coordinates. The coordinates are in pyCERR’s virtual coordinate system.

Returns:

x, y, z coordinates corresponding to the columns, rows, slices of scan voxels

Return type:

tuple

getScanSize()[source]

Routine to get scan dimensions.

Returns:

numRows, numCols, numSlcs of pyCERR scan object

Return type:

np.array

getUniformScanSize()[source]

Return the size of the uniformized scan.

Returns:

numRows, numCols, numSlcs

Return type:

np.array

getScanOrientation()[source]

Routine to get orientation of sacn w.r.t. patient.

Returns:

3-character String representing the orientation of Scans’s row, column and slice.

Return type:

str

getScanSpacing()[source]

Routine to get voxel spacing in cm.

Returns:

3-element array containing dx, dy, dz of scan

Return type:

np.array

convertDcmToCerrVirtualCoords()[source]

Routine to get scan from DICOM to pyCERR virtual coordinates. More information about virtual coordinates is on the Wiki https://github.com/cerr/pyCERR/wiki/Coordinate-system

convertDcmToRealWorldUnits(opts={})[source]

Routine to convert pixel array from DICOM storage units to real world units.

Parameters:

opts (dict) –

Dictionary of options to convert to real world units. Currrently, only one option if supported - importMRPreciseValueFlag (yes or no) to specify whether to convert MR image from

Philips scanner to precise values.

convertToSUV(suvType=None)[source]

Routine to convert pixel array for PET scan from DICOM storage to SUV

Parameters:

suvType (str) – optional, type of SUV. When not specified, the suvType is read from DICOM if available. When not specified and not available in DIOCM, a default value of ‘BW’ is used. Currently supported options are ‘BW’, ‘BSA’, ‘LBM’, ‘LBMJANMA’

getScanDict()[source]

Routine to get dictionary representation of scan metadata

Returns:

fields of the dictionary are attributes of the Scan object.

Return type:

dict

getDcmScanInfo() list[source]

This routine return a list of scanInfo from scan object. The order corresponds to scanArray slice dimension

Returns:

list of scanInfo dictionaries

Return type:

list

cerr.dataclasses.scan.flipSliceOrderFlag(scan)[source]

Routine to determine slice order for determining the origin for conversion to NifTi and SimpleITK formats.

Parameters:

scan (cerr.dataclasses.scan.Scan) – pyCERR scan object

Returns:

True when dot product of slice normal and imagePositionPatient increases with slice order

Return type:

bool

cerr.dataclasses.scan.getITKDirection(scan)[source]
Parameters:

scan (cerr.dataclasses.scan.Scan) – pyCERR scan object

Returns:

9-element array of direction cosines of row, column and slice w.r.t. patient.

Return type:

np.ndarray

cerr.dataclasses.scan.dcm_hhmmss(time_str)[source]

Parse a DICOM time string (HHMMSS) into its components and total seconds.

Parameters:

time_str (str) – DICOM-format time string with at least 6 characters in HHMMSS order (fractional seconds are accepted but currently ignored).

Returns:

A 5-element tuple (totSec, hh, mm, ss, fract) where

totSec (int) is the total number of seconds since midnight, hh (int) is hours, mm (int) is minutes, ss (int) is seconds, and fract is None (reserved for future use).

Return type:

tuple

cerr.dataclasses.scan.dcm_to_np_date(dateStr)[source]

Convert a DICOM date string (YYYYMMDD) to a numpy datetime64 object.

Parameters:

dateStr (str) – DICOM-format date string, exactly 8 characters in YYYYMMDD order.

Returns:

A numpy.datetime64 with day precision when

dateStr is 8 characters long, otherwise None.

Return type:

np.datetime64 | None

cerr.dataclasses.scan.get_slice_position(scan_info_item)[source]

Extract the z-position from an enumerated scan-info pair for sort key use.

Parameters:

scan_info_item (tuple) – A (index, ScanInfo) pair as produced by enumerate. The second element must have a zValue attribute.

Returns:

The zValue of the scan-info slice, in centimetres.

Return type:

float

cerr.dataclasses.scan.populateScanInfoFields(s_info, ds)[source]
Parameters:
Returns:

scanInfo object with attributes populated from metadata from input ds.

Return type:

cerr.dataclasses.scan_info.ScanInfo

cerr.dataclasses.scan.populateRealWorldFields(s_info, perFrameSeq)[source]
Parameters:
  • s_info (cerr.dataclasses.scan_info.ScanInfo) – pyCERR’s scanInfo object for storing metadata per slice.

  • perFrameSeq (pydicom.dataset.Dataset) – pydicom dataset object or ds.PerFrameFunctionalGroupsSequence

  • images. (for multiFrameFlg)

Returns:

scanInfo object with attributes populated from metadata from input ds.

Return type:

cerr.dataclasses.scan_info.ScanInfo

cerr.dataclasses.scan.populateRadiopharmaFields(s_info, seq)[source]
Parameters:
  • s_info (cerr.dataclasses.scan_info.ScanInfo) – pyCERR’s scanInfo object for storing metadata per slice.

  • seq (pydicom.dataset.Dataset) – dataset containing radiopharma metadata for PET scan.

Returns:

scanInfo object with attributes populated from metadata from input ds.

Return type:

cerr.dataclasses.scan_info.ScanInfo

cerr.dataclasses.scan.parseScanInfoFields(ds, multiFrameFlg=False) -> (<class 'cerr.dataclasses.scan_info.ScanInfo'>, <property object at 0x7d1ce74c9b70>, <class 'str'>)[source]
Parameters:
  • ds (pydicom.dataset.Dataset) – Dataset object read from DICOM file

  • multiFrameFlg (bool) – True when dataset is multiFrame image, otherwise False.

Returns:

scanInfo object with attributes populated from metadata from input ds.

Return type:

cerr.dataclasses.scan_info.ScanInfo

cerr.dataclasses.scan.loadSortedScanInfo(file_list)[source]
Parameters:

file_list (list) – list of files to read into pyCERR’s Scan object

Returns:

pyCERR scan object containing metadata from the file_list.

Return type:

cerr.daatclasses.scan.Scan

cerr.dataclasses.scan.parseScanInfoFromDB(scanObj, scanInfoList)[source]

Assign scanInfo from the list of dictionaries to scanObj by matching zValue per slice

Parameters:
  • scanObj (cerr.dataclasses.scan.Scan) – pyCERR’s Scan object whose scanInfo needs to be populated

  • scanInfoList (list) – list of dictionaries with fields corresponding to scanInfo

Returns:

0 when field assignment is successful

cerr.dataclasses.scan.getScanNumFromUID(assocScanUID, planC) int[source]
Parameters:
  • assocScanUID (str) – UID of scan.

  • planC (cerr.plan_container.planC) – pyCERR’s plan container object.

Returns:

index within planC.scan that matches input assocScanUID.

Return type:

int

cerr.dataclasses.scan.getCERRScanArrayFromITK(itkImage, assocScanNum, planC)[source]

This routine returns a numpy array in pyCERR coordinate system (orientation) from a SimpleITK Image.

Parameters:
  • itkImage (SimpleITK.Image) – SimpleITK’s Image object

  • assocScanNum (int) – Scan index to associate orientation of itkImage in pyCERR.

  • planC (cerr.planC_container.planC) – pyCERR’s plan container object.

Returns:

array in CERR virtual coordinates.

Return type:

np.ndarray

cerr.dataclasses.scan_info module

scan_info module.

The scan_info module defines metadata for images (CT, PT, MR, US). The metadata are attributes of the ScanInfo class. This metadata is used to generate physical grid coordinates and for conversion of raw image to real world units.

cerr.dataclasses.scan_info.get_empty_list()[source]
cerr.dataclasses.scan_info.get_empty_np_array()[source]
class cerr.dataclasses.scan_info.ScanInfo(imageNumber: float = 0.0, imageType: str = '', caseNumber: int = 0, patientName: str = '', patientID: str = '', patientBirthDate: str = '', scanType: str = '', CTOffset: float = 0.0, rescaleSlope: float = 1.0, rescaleIntercept: float = 0.0, rescaleType: str = '', scaleSlope: float = nan, scaleIntercept: float = nan, realWorldValueSlope: float = nan, realWorldValueIntercept: float = nan, realWorldMeasurCodeMeaning: str = '', philipsImageUnits: str = '', philipsRescaleSlope: float = nan, philipsRescaleIntercept: float = nan, grid1Units: float = 0.0, grid2Units: float = 0.0, numberRepresentation: int = 0, bitsAllocated: int = nan, bitsStored: int = nan, pixelRepresentation: int = nan, numberOfDimensions: int = 3, sizeOfDimension1: int = 512, sizeOfDimension2: int = 512, zValue: float = 0.0, xOffset: float = 0.0, yOffset: float = 0.0, CTAir: float = 0.0, CTWater: float = 0.0, sliceThickness: float = 0.0, voxelThickness: float = 1.0, siteOfInterest: str = '', unitNumber: int = 0, seriesDescription: str = '', studyDescription: str = '', scannerType: str = '', manufacturer: str = '', scanFileName: str = '', headInOut: str = '', positionInScan: float = '', patientAttitude: str = '', bValue: float = 0.0, acquisitionDate: str = '', acquisitionTime: str = '', patientWeight: float = '', patientSize: float = '', patientBmi: float = '', patientSex: str = '', injectionTime: str = '', injectionDate: str = '', injectedDose: float = '', halfLife: float = '', imageUnits: str = '', suvType: str = '', petCountSource: str = '', petSeriesType: str = '', petNumSlices: int = '', petPrimarySourceOfCounts: str = '', petDecayCorrectionDateTime: str = '', petDecayCorrection: str = '', petCorrectedImage: str = '', seriesDate: str = '', seriesTime: str = '', studyDate: str = '', studyTime: str = '', tapeOfOrigin: str = '', studyNumberOfOrigin: int = 0, scanID: str = '', scanNumber: int = 0, scanDate: str = '', CTScale: float = 0.0, distrustAbove: float = '', imageSource: str = '', transferProtocol: str = '', studyInstanceUID: str = '', seriesInstanceUID: str = '', sopInstanceUID: str = '', sopClassUID: str = '', frameOfReferenceUID: str = '', patientPosition: str = '', imageOrientationPatient: array = <factory>, imagePositionPatient: array = <factory>, windowCenter: float = '', windowWidth: float = '', temporalPositionIndex: float = '', triggerTime: float = '', frameAcquisitionDuration: float = '', frameReferenceDateTime: str = '', patientIdentityRemoved: str = '', deIdentificationMethod: str = '', deidentificationMethodDescription: array = <factory>, contrastBolusAgent: str = '', philipsSUVScaleFactor: float = '', philipsActivityConcentrationScaleFactor: float = '', gePETDecayCorrectionDateTime: float = '', siemensPETDecayCorrectionDateTime: float = '')[source]

Bases: object

This class defines data object for a scan slice.

imageType

Type of scan. MR SCAN, CT SCAN, PT SCAN.

Type:

str

patientName

Patient’s name

Type:

str

patientID

Patieint’s ID

Type:

str

patientBirthDate

Patient’s date of birth

Type:

str

CTOffset

Offset to add to scanArray to get image in scanUnits (e.g. HU). This is required so as to store only (+)ve values in scanArray.

Type:

float

rescaleSlope

m in the equation Output units = m*SV + b. Slope to transform image from storage to real world units as per (0028,1053) tag.

Type:

float

rescaleIntercept

b in the equation Output units = m*SV + b. Read from (0028,1052) tag

Type:

float

rescaleType

Specifies the output units of Rescale Slope (0028,1053) and Rescale Intercept (0028,1052)

Type:

str

scaleSlope

Private tag (2005,100E) used for conversion to MR precise values

Type:

float

scaleIntercept

Private tag (2005,100D)

Type:

float

realWorldValueSlope

The Slope value in relationship between stored values (SV) and the Real World Values as per (0040,9225) tag.

Type:

float

realWorldValueIntercept

The Intercept value in relationship between stored values (SV) and the Real World values as per (0040,9224) tag.

Type:

float

realWorldMeasurCodeMeaning

Real World code value as per (0008,0100) tag

Type:

str

philipsImageUnits

Private tag containing image units as per (2005,140B)

Type:

str

philipsRescaleSlope

Private tag containing rescale slope as per (2005,140A)

Type:

float

philipsRescaleIntercept

Private tag containing rescale intercept as per (2005,1409)

Type:

float

grid1Units

delta y of the scan grid in CERR virtual coordinates

Type:

float

grid2Units

delta x of the scan grid in CERR virtual coordinates

Type:

float

bitsAllocated

Number of bits allocated for each pixel sample as per (0028,0100)

Type:

int

bitsStored

Number of bits stored for each pixel sample as per (0028,0101)

Type:

int

pixelRepresentation

Data representation of the pixel samples as per (0028,0103) 0000H - unsigned integer, 0001H - 2’s complement

Type:

int

numberOfDimensions

Number of scan dimensions

Type:

int

sizeOfDimension1

Number of rows of scanArray

Type:

int

sizeOfDimension2

Number of columns of scanArray

Type:

int

zValue

z-coordinate of the slice in CERR virtual coordinate system

Type:

float

xOffset

x-offset of the center of scanArray in CERR virtual coordinates

Type:

float

yOffset

y-offset of the center of scanArray in CERR virtual coordinates

Type:

float

sliceThickness

Nominal slice thickness as per (0018,0050).

Type:

float

voxelThickness

Physical spacing between the next and the previous slice in CERR virtual coordinates.

Type:

float

seriesDescription

Series description as per (0008,103E)

Type:

str

studyDescription

Study description as per (0008,1030)

Type:

str

scannerType

Manufacturer model name

Type:

str

manufacturer

Scanner Mmanufacturer

Type:

str

scanFileName

Location of DICOM file from which metadata was read

Type:

str

bValue

b-value of MR scan

Type:

float

acquisitionDate

Acquisition date

Type:

str

acquisitionTime

Acquisition time

Type:

str

patientWeight

Patient’s weight

Type:

float

patientSize

Patient’s size

Type:

float

patientBmi

Patient’s BMI

Type:

float

patientSex

Patient’s gender

Type:

str

injectionTime

The actual time of radiopharmaceutical administration to the patient for imaging purposes.

Type:

str

injectionDate

The actual date of radiopharmaceutical administration to the patient for imaging purposes.

Type:

str

injectedDose

The radiopharmaceutical dose administered to the patient measured in MegaBecquerels (MBq) at the Radiopharmaceutical Start DateTime (0018,1078).

Type:

float

halfLife

The radionuclide half life, in seconds, that was used in the correction of this image.

Type:

float

imageUnits

realWorldMeasurCodeMeaning when available or rescaleType.

Type:

str

suvType

The type of SUV stored in scanArray as per (0054,1006) tag.

Type:

str

petCountSource

The primary source of counts as per (0054,1002). EMISSION or TRANSMISSION

Type:

str

petSeriesType

A multi-valued indicator of the type of Series as per (0054,1000).

Type:

str

philipsActivityConcentrationScaleFactor

Used to convert the pixel data from counts to Activity Concentration (in Bq/ml) as per (7053, 1009 tag

Type:

float

petNumSlices

The number of slices in each separate volume as per (0054,0081)

Type:

int

petDecayCorrectionDateTime

The date and time to which all frames in this Image were decay corrected as per (0018,9701)

Type:

str

decayCorrection

Whether Decay (DECY) correction has been applied to image. YES or NO.

Type:

float

correctedImage

One or more values that indicate which, if any, corrections have been applied to the image as per (0028,0051)

Type:

float

seriesDate

Series date

Type:

str

seriesTime

Series yime

Type:

str

studyDate

Study date

Type:

str

studyTime

Study time

Type:

str

studyInstanceUID

Study Instance UID

Type:

str

seriesInstanceUID

Series Instance UID of image volume

Type:

str

sopInstanceUID

SOP Instance UID of image frame

Type:

str

sopClassUID

SOP Class UID of image frame

Type:

str

frameOfReferenceUID

Frame of Reference UID

Type:

str

imageOrientationPatient

Direction cosine of dose row and column with patient coordinate system.

Type:

np.array

imagePositionPatient

x,y,z coordinate of the top left voxel of the scan volume.

Type:

np.array

windowCenter

Window center used for visualization

Type:

float

windowWidth

Window width used for visualization

Type:

float

temporalPositionIndex

Temporal position in the dynamic sequence from the FrameContentSequence.

Type:

float

triggerTime

Time, in msec, between peak of the R wave and the peak of the echo produced.

Type:

float

frameAcquisitionDuration

Duration of Frame acquisition from the FrameContentSequence.

Type:

float

frameReferenceDateTime

FrameReferenceDateTime from the FrameContentSequence

Type:

str

patientIdentityRemoved

A text string describing the de-identification method.

Type:

str

deIdentificationMethod

Indicates whether patient identity has been removed.

Type:

str

deidentificationMethodDescription

codes that specifies the methods used to de-identify patient data

Type:

np.array

ContrastBolusAgent

Contrast or bolus agent.

Type:

str

philipsSUVScaleFactor

Philips scanner private tag to convert PET pixel data from counts to Standardized Uptake Value (SUV)

Type:

float

philipsActivityConcentrationScaleFactor

Philips scanner private tag to convert stored pixel values (after applying the Rescale Slope (0028,1053)) into Activity Concentration units (MBq/mL).

Type:

float

gePETDecayCorrectionDateTime

GE scanner private tag for the date and time to which all frames in this Image were decay corrected.

Type:

float

siemensPETDecayCorrectionDateTime

Siemens scanner private tag for the date and time to which all frames in this Image were decay corrected.

Type:

float

imageNumber: float = 0.0
imageType: str = ''
caseNumber: int = 0
patientName: str = ''
patientID: str = ''
patientBirthDate: str = ''
scanType: str = ''
CTOffset: float = 0.0
rescaleSlope: float = 1.0
rescaleIntercept: float = 0.0
rescaleType: str = ''
scaleSlope: float = nan
scaleIntercept: float = nan
realWorldValueSlope: float = nan
realWorldValueIntercept: float = nan
realWorldMeasurCodeMeaning: str = ''
philipsImageUnits: str = ''
philipsRescaleSlope: float = nan
philipsRescaleIntercept: float = nan
grid1Units: float = 0.0
grid2Units: float = 0.0
numberRepresentation: int = 0
bitsAllocated: int = nan
bitsStored: int = nan
pixelRepresentation: int = nan
numberOfDimensions: int = 3
sizeOfDimension1: int = 512
sizeOfDimension2: int = 512
zValue: float = 0.0
xOffset: float = 0.0
yOffset: float = 0.0
CTAir: float = 0.0
CTWater: float = 0.0
sliceThickness: float = 0.0
voxelThickness: float = 1.0
siteOfInterest: str = ''
unitNumber: int = 0
seriesDescription: str = ''
studyDescription: str = ''
scannerType: str = ''
manufacturer: str = ''
scanFileName: str = ''
headInOut: str = ''
positionInScan: float = ''
patientAttitude: str = ''
bValue: float = 0.0
acquisitionDate: str = ''
acquisitionTime: str = ''
patientWeight: float = ''
patientSize: float = ''
patientBmi: float = ''
patientSex: str = ''
injectionTime: str = ''
injectionDate: str = ''
injectedDose: float = ''
halfLife: float = ''
imageUnits: str = ''
suvType: str = ''
petCountSource: str = ''
petSeriesType: str = ''
petNumSlices: int = ''
petPrimarySourceOfCounts: str = ''
petDecayCorrectionDateTime: str = ''
petDecayCorrection: str = ''
petCorrectedImage: str = ''
seriesDate: str = ''
seriesTime: str = ''
studyDate: str = ''
studyTime: str = ''
tapeOfOrigin: str = ''
studyNumberOfOrigin: int = 0
scanID: str = ''
scanNumber: int = 0
scanDate: str = ''
CTScale: float = 0.0
distrustAbove: float = ''
imageSource: str = ''
transferProtocol: str = ''
studyInstanceUID: str = ''
seriesInstanceUID: str = ''
sopInstanceUID: str = ''
sopClassUID: str = ''
frameOfReferenceUID: str = ''
patientPosition: str = ''
imageOrientationPatient: array
imagePositionPatient: array
windowCenter: float = ''
windowWidth: float = ''
temporalPositionIndex: float = ''
triggerTime: float = ''
frameAcquisitionDuration: float = ''
frameReferenceDateTime: str = ''
patientIdentityRemoved: str = ''
deIdentificationMethod: str = ''
deidentificationMethodDescription: array
contrastBolusAgent: str = ''
philipsSUVScaleFactor: float = ''
philipsActivityConcentrationScaleFactor: float = ''
gePETDecayCorrectionDateTime: float = ''
siemensPETDecayCorrectionDateTime: float = ''
class cerr.dataclasses.scan_info.UniformScanInfo(sliceNumSup: int = 0, sliceNumInf: int = 0, supInfScansCreated: int = 0, minCTValue: float = 0.0, maxCTValue: float = 0.0, firstZValue: float = 0.0)[source]

Bases: object

sliceNumSup: int = 0
sliceNumInf: int = 0
supInfScansCreated: int = 0
minCTValue: float = 0.0
maxCTValue: float = 0.0
firstZValue: float = 0.0
cerr.dataclasses.scan_info.deduce_voxel_thickness(scan_info) ScanInfo[source]

cerr.dataclasses.structure module

structure module.

Ths structure module defines metadata for segmentation (RTSTRUCT, SEG). The metadata are attributes of the Structre class. This module also defines routines for transforming and accessing the Structure metadata in CERR coordinate system and to convert images to real world units.

cerr.dataclasses.structure.get_empty_list()[source]

Return an empty list used as a default factory for dataclass fields.

Returns:

An empty list.

Return type:

list

cerr.dataclasses.structure.get_empty_np_array()[source]

Return an empty 3-D NumPy array used as a default factory for dataclass fields.

Returns:

An empty array with shape (0, 0, 0).

Return type:

np.ndarray

class cerr.dataclasses.structure.Structure(roiNumber: int = 0, patientName: str = '', structureName: str = '', ROIInterpretedType: str = '', structureFormat: str = '', numberOfScans: int = 0, maximumNumberScans: int = 0, maximumPointsPerSegment: int = 0, maximumSegmentsPerScan: int = 0, structureEdition: str = '', writer: str = '', manufacturerModelName: str = '', dateWritten: str = '', structureColor: List = <factory>, structureDescription: str = '', roiGenerationAlgorithm: str = '', roiGenerationDescription: str = '', studyNumberOfOrigin: str = '', contour: List = <factory>, rasterSegments: ndarray = <factory>, DSHPoints: ndarray = <factory>, orientationOfStructure: str = '', transferProtocol: str = '', visible: bool = True, strUID: str = '', assocScanUID: str = '', structSetSopInstanceUID: str = '', rasterized: bool = False, referencedFrameOfReferenceUID: str = '', referencedSeriesUID: str = '', structureFileName: str = '', structureFileFormat: str = '', deIdentificationMethod: str = '', deidentificationMethodDescription: array = <factory>)[source]

Bases: object

This class defines data object for volumetric segmentation. The metadata can be populated from DICOM, NifTi and numpy arrays.

patientName

Patient’s name.

Type:

str

structureName

Structure’s name.

Type:

str

ROIInterpretedType

maps to DICOM tag (3006,00A4).

Type:

str

numberOfScans

Number of scan slices containing segmentation.

Type:

int

dateWritten

Date structure was created. Corresponds to DICOM tag (3006,0008) StructureSetDate.

Type:

str

structureColor

rgb triplet representing the color for this structure

Type:

List

structureDescription

Description of the structure. DICOM SeriesDescription.

Type:

str

roiGenerationAlgorithm

Permitted values are AUTOMATIC, SEMIAUTOMATIC and MANUAL

Type:

str) = Type of algorithm used to generate ROI. DICOM tag (3006,0036

roiGenerationDescription

User-defined description of technique used to generate ROI. DICOM tag (3006,0038).

Type:

str

contour

List of contours including segmentation x,y,z CERR virtual coordinates per scan slice. The ith entry in the list corresponds to the ith slice of the associated scanArray.

Type:

List

rasterSegments

Numpy array of size numSegments x 10. The columns of this array are z-value, y-value, x segment start, x segment stop, x increment, slice, row, column start, column stop, voxel thickness for that slice. Each row represents a scan segment.

Type:

np.ndarray

strUID

unique identifier for structure object

Type:

str

assocScanUID

unique identifier for the scan associated with the structure object.

Type:

str

structSetSopInstanceUID

str = “”

Type:

str

referencedFrameOfReferenceUID

UID for frame of reference

Type:

str

referencedSeriesUID

UID of structure series i.e. DICOM SeriesInstanceUID

Type:

str

structureFileName

Structure file name

Type:

str

manufacturerModelName

Manufacturer model name

Type:

str

writer

Manufacturer in DICOM terms

Type:

str

structureFileFormat

File format from which structure’s metadata was populated. Permitted values are “RTSTRUCT”, “NPARRAY”, “NIFTI”.

Type:

str

deIdentificationMethod

Indicates whether patient identity has been removed.

Type:

str

deidentificationMethodDescription

codes that specifies the methods used to de-identify patient data

Type:

np.array

roiNumber: int = 0
patientName: str = ''
structureName: str = ''
ROIInterpretedType: str = ''
structureFormat: str = ''
numberOfScans: int = 0
maximumNumberScans: int = 0
maximumPointsPerSegment: int = 0
maximumSegmentsPerScan: int = 0
structureEdition: str = ''
writer: str = ''
manufacturerModelName: str = ''
dateWritten: str = ''
structureColor: List
structureDescription: str = ''
roiGenerationAlgorithm: str = ''
roiGenerationDescription: str = ''
studyNumberOfOrigin: str = ''
contour: List
rasterSegments: ndarray
DSHPoints: ndarray
orientationOfStructure: str = ''
transferProtocol: str = ''
visible: bool = True
strUID: str = ''
assocScanUID: str = ''
structSetSopInstanceUID: str = ''
rasterized: bool = False
referencedFrameOfReferenceUID: str = ''
referencedSeriesUID: str = ''
structureFileName: str = ''
structureFileFormat: str = ''
deIdentificationMethod: str = ''
deidentificationMethodDescription: array
saveNii(niiFileName, planC)[source]

Routine to save pyCERR Structure object to NifTi file

Parameters:
  • niiFileName (str) – File name including the full path to save the pyCERR scan object to NifTi file.

  • planC (cerr.plan_container.PlanC) – pyCERR plan container object.

Returns:

0 when NifTi file is written successfully.

Return type:

int

convertDcmToCerrVirtualCoords(planC)[source]

Routine to convert x,y,z coordinates of segmentation from DICOM to pyCERR virtual coordinates. More information about virtual coordinates is on the Wiki https://github.com/cerr/pyCERR/wiki/Coordinate-system

getStructureAssociatedScan(planC)[source]
Parameters:

planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

Returns:

associated scan index for structure object based on the scan UID associated with

the structure.

Return type:

int

getSitkImage(planC)[source]

Routine to convert pyCERR Structure object to SimpleITK Image object

Returns:

SimpleITK Image with value of 1 assigned to segmented pixels

Return type:

sitk.Image

getContourPolygons(planC, rcsFlag=False, dicomFlag=False)[source]

This routine returns the list of polygonal coordinates for all the segments of input structutre.

Parameters:
  • strNum (int) – index of structure element in planC.structure

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

  • rcsFlag (bool) – optional, flag to return polygonal coordinates in row,col,slc units. By default, the polygonal coordinates are returned in physical units of cm.

  • dicomFlag (bool) – optional, flag to return polygonal coordinates in DICOM coordinate system and units of mm.

Returns:

list of nx3 arrays corresponding to polygonal segments, where n is the number of points in that segment,

the columns of each array are x,y,z coordinates in physical units of cm or r,c,s units.

Return type:

list

getStructDict()[source]

Routine to get dictionary representation of structure metadata

Returns:

fields of the dictionary are attributes of the Structure object.

Return type:

dict

saveJson(jsonFileName, planC)[source]
Parameters:
  • structNumV (List) – List of structure indices to export to JSON format.

  • jsonFileName (str) – JSON file name.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

Returns:

None

saveContoursToJson(planC, physicalUnitsFlag=True, jsonFileName='')[source]

Save contour polygons in DICOM coordinate system to a json file. :param planC: pyCERR’s plan container object :type planC: cerr.plan_container.PlanC :param physicalUnitsFlag: Flag to save coordinates in Physical units. :type physicalUnitsFlag: bool :param jsonFileName: file name to write JSON.

if empty, Only the JSON-formatted string is returned in-memory.

Returns:

JSON-formatted string containing the contour metadata.

Return type:

str

class cerr.dataclasses.structure.Contour(referencedSopInstanceUID: str = '', referencedSopClassUID: str = '', segments: array = <factory>)[source]

Bases: object

This class defines data object for storing segmented contours. The metadata can be populated from DICOM, NifTi and numpy arrays.

referencedSopInstanceUID

Instance UID of associated image slice.

Type:

str

referencedSopClassUID

Class UID of associated image slice.

Type:

str

segments

array of segments.

Type:

np.array

referencedSopInstanceUID: str = ''
referencedSopClassUID: str = ''
segments: array
class cerr.dataclasses.structure.Segment(points: ndarray = <factory>)[source]

Bases: object

This class defines data object for storing contour segments.

points

(n X 3) array containing x,y,z coordinates of the segment in pyCERR virtual coordinate system.

Type:

numpy.ndarray

points: ndarray
class cerr.dataclasses.structure.jsonSerializeSegment(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(segObj)[source]

Serialize a Segment instance to a JSON-compatible dictionary.

Parameters:

segObj (Segment) – Segment object to serialize.

Returns:

Dictionary with a points key containing the serialized

contour point coordinates.

Return type:

dict

Raises:

TypeError – When segObj is not a Segment instance.

class cerr.dataclasses.structure.jsonSerializeContour(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(ctrObj)[source]

Serialize a Contour instance to a JSON-compatible dictionary.

Parameters:

ctrObj (Contour) – Contour object to serialize.

Returns:

Dictionary containing referencedSopClassUID,

referencedSopInstanceUID, and segments keys.

Return type:

dict

Raises:

TypeError – When ctrObj is not a Contour instance.

class cerr.dataclasses.structure.jsonSerializeStruct(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)[source]

Bases: JSONEncoder

default(strObj)[source]

Serialize a Structure instance to a JSON-compatible dictionary.

Only the fields listed in fieldsList are exported together with the nested contour data.

Parameters:

strObj (Structure) – Structure object to serialize.

Returns:

Dictionary whose keys are the fields from fieldsList plus

a contour list of serialized contour entries.

Return type:

dict

Raises:

TypeError – When strObj is not a Structure instance.

cerr.dataclasses.structure.getJsonList(structNumV, planC)[source]

Return a JSON-formatted string (or list of strings) for the specified structures.

Parameters:
  • structNumV (Structure, int, float, np.integer, np.floating, or list) – A single Structure object, a scalar structure index, or a list of indices into planC.structure.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object.

Returns:

A JSON-formatted string when structNumV is a

Structure object, otherwise a list of JSON-formatted strings—one per requested structure index.

Return type:

str or list[str]

cerr.dataclasses.structure.saveJson(structNumV, jsonFileName, planC)[source]
Parameters:
  • structNumV (List) – List of structure indices to export to JSON format.

  • jsonFileName (str) – JSON file name.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

Returns:

None

cerr.dataclasses.structure.importJson(planC, strList=None, jsonFileName=None)[source]
Parameters:
  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object.

  • strList (list of structures) – (optional) list of structure metadata imported from json. Required when jsonFileName is None.

  • jsonFileName – (optional) JSON file name containing structure metadata. Required when strList is None.

Returns:

pyCERR’s plan container object.

Return type:

cerr.plan_container.PlanC

cerr.dataclasses.structure.parseContours(contour_seq)[source]

This routine parses the ContourSequence metadata from DICOM and returns a list of pyCERR Contour objects.

Parameters:

contour_seq (pydicom.dataset.Dataset) – Pydicom Dataset object for ContourSequence, DICOM tag (3006,0040).

Returns:

list of pyCERR Contour objects

Return type:

List[cerr.dataclasses.structure.Contour]

cerr.dataclasses.structure.loadStructure(file_list)[source]

This routine parses a list of DICOM files and imports metadata from RTSTRUCT and SEG modalities to a list of pyCERR’s Structure objects .

Parameters:

file_list (List[str]) – List of DICOM file paths.

Returns:

List of pyCERR’s Structure objects.

Return type:

List[cerr.dataclasses.structure.Structure]

cerr.dataclasses.structure.importNii(file_list, assocScanNum, planC, labels_dict={})[source]

This routine imports segmentation from a list of nii files into planC.

Parameters:
  • file_list (List or str) – List of nii file paths or a string containing path for a single file.

  • assocScanNum (int) – index of scan in planC to associate the segmentation.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object.

  • labels_dict (dict) – dictionary of index to structure name mapping. e.g. {‘GTV’:1, ‘Lung_total’: 2}

Returns:

pyCERR’s plan container object

Return type:

cerr.plan_container.PlanC

cerr.dataclasses.structure.importStructureMask(mask3M, assocScanNum, structName, planC, structNum=None)[source]
Parameters:
  • mask3M (np.ndarray) – binary mask for segmentation which is of the same shape as the associated scan

  • assocScanNum (int) – index of scan object within planC.scan to associate the structure

  • structName (str) – Name of the structure

  • planC (cerr.plan_container.PlanC) – pyCERR’s container object

  • structNum (int or None) – optional, index of structure object within planC.structure to replace

Returns:

pyCERR’s container object with updated planC.structure attribute

Return type:

cerr.plan_container.PlanC

cerr.dataclasses.structure.createSitkImage(mask3M, assocScanNum, planC)[source]
Parameters:
  • mask3M (np.ndarray or int or list) – binary mask for segmentation which is of the same shape as the associated scan, Or a list of structure indices from planC.structure

  • assocScanNum (int) – index of scan object within planC.scan to associate the structure

  • planC (cerr.plan_container.PlanC) – pyCERR’s container object

  • structNum (int or None) – optional, index of structure object within planC.structure to replace

Returns:

SimpleITK Image

Return type:

SimpleITK.Image

cerr.dataclasses.structure.getColorForStructNum(structNum)[source]

This routine returns the rgb color triplet to assign to a new structure object.

Parameters:

structNum (int) – index of structure object in planC.structure

Returns:

rgb triplet

Return type:

List

cerr.dataclasses.structure.copyToScan(structNum, scanNum, planC)[source]

This routine copies structure object at index structNum to scan objact at index scanNum in planC.scan.

Parameters:
  • structNum (int) – index of structure object in planC.structure

  • scanNum (int) – index of scan object in planC.scan

  • planC (cerr.plan_container.PlanC) – pyCERR’s planc ontainer object

Returns:

updated planC with new planC.structure element associated with scanNum

Return type:

cerr.plan_container.PlanC)

cerr.dataclasses.structure.getStructNumFromUID(assocStrUID, planC) int[source]

This routine returns the index of the planC.structure element corresponding to the input pyCERR’s structure UID

Parameters:
Returns:

Index of the planC.structure element corresponding to the input UID

None when there is no matching element in planC.structure corresponding to the input UID.

Return type:

int

cerr.dataclasses.structure.getStructNumFromSOPInstanceUID(assocStrUID, planC) int[source]

This routine returns the index of the planC.structure element corresponding to the input SOP Instance UID

Parameters:
  • assocStrUID (str) – SOP Instance UID of the structure object

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

Returns:

Index of the planC.structure element corresponding to the input UID

None when there is no matching element in planC.structure corresponding to the input SOP Instance UID.

Return type:

int

cerr.dataclasses.structure.calcIsocenter(strNum, planC)[source]

This routine calculates the isocenter of the input structure index in planC.structure

Parameters:
  • strNum (int) – Index of structure object in planC.structure

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container

Returns:

x,y,z coordinates in pyCERR’s virtual coordinate system for the isocenter.

Return type:

List

cerr.dataclasses.structure.getMatchingIndex(structName, strList, matchCriteria='exact')[source]

This routine returns the index of element/s from the list of structure names that match the input name.

Parameters:
  • structName (str) – Structure name to find a match

  • strList – List of structure names

  • matchCriteria – Criteria used to find the match ‘EXACT’ - returns indices of exact matches ‘FIRSTCHARS’ - returns indices where first characters of elements in the list match input structName

Returns:

list of matching indices from input strList

Return type:

List

cerr.dataclasses.structure.getClosedMask(structNum, structuringElementSizeCm, planC, saveFlag=False, replaceFlag=None, procSructName=None)[source]

Function for morphological closing and hole-filling for binary masks

Parameters:
  • structNum – int for index of structure in planC.

  • structuringElementSizeCm – float for size of structuring element for closing in cm

  • planC – pyCERR plan container object.

  • saveFlag – [optional, default=False] bool flag for saving processed mask to planC.

  • replaceFlag – [optional, default=False] bool flag for replacing input mask with processed mask in planC.

  • procSructName – [optional, default=None] string for output structure name. Original structure name is used if None.

Returns:

np.ndarray(dtype=bool) for filled mask. planC: pyCERR plan container object.

Return type:

filledMask3M

cerr.dataclasses.structure.getLargestConnComps(structNum, numConnComponents, planC=None, saveFlag=None, replaceFlag=None, procSructName=None)[source]

Function to retain ‘N’ largest connected components in input binary mask

Parameters:
  • structNum – int for index of structure in planC (OR) np.ndarray(dtype=bool) 3D binary mask.

  • numConnComponents – number of connected components.

  • planC – [optional, default=None] pyCERR plan container object.

  • saveFlag – [optional, default=False] bool flag for importing filtered mask to planC if set to True.

  • replaceFlag – [optional, default=False] bool flag for replacing input mask with processed mask to planC if set to True.

  • procSructName – [optional, default=None] string for output structure name. Original structure name is used if empty.

Returns:

np.ndarray(dtype=bool) filtered binary mask. planC: pyCERR plan container object.

Return type:

maskOut3M

cerr.dataclasses.structure.getSurfaceExpand(structNum, marginCm, planC, restrict_2d=False)[source]

Expand or contract a structure mask by a uniform surface margin and save the result to planC.

Parameters:
  • structNum (int) – Index of the structure in planC.structure.

  • marginCm (float) – Expansion margin in centimetres. Negative values produce a contraction (shrinkage) of the mask.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object.

  • restrict_2d (bool) – When True, the expansion is limited to the in-plane (2-D) directions only. Defaults to False.

Returns:

Updated plan container object with the

expanded/contracted structure appended to planC.structure.

Return type:

cerr.plan_container.PlanC

cerr.dataclasses.structure.getGaussianBlurredMask(structNum, sigmaVoxel, planC, saveFlag=False, replaceFlag=None, procSructName=None)[source]

Function for Gaussian blurring of binary masks

Parameters:
  • structNum (int) – int for index of structure in planC.

  • sigmaVoxel (float) – sigma used in Gaussian in units of number of voxels. corresponding to each image dimension.

  • planC – pyCERR plan container object.

  • saveFlag – [optional, default=False] bool flag for saving processed mask to planC.

  • replaceFlag – [optional, default=False] bool flag for replacing input mask with processed mask in planC.

  • procSructName – [optional, default=None] string for output structure name. Original structure name is used if None.

Returns:

np.ndarray(dtype=bool) for filled mask. planC: pyCERR plan container object.

Return type:

filledMask3M

cerr.dataclasses.structure.getBsplineSmoothing(structNum, resolutionFactor, smootingFactor, planC, replaceFlag=None, procSructName=None)[source]
Parameters:
  • structNum (int) – Index of structure in planC.structure

  • resolutionFactor (float) – Factor to control the number of points in the output contours relative to the original. For example, resolutionFactor of 1.2 would add 20% points to the original contours.

  • smootingFactor (float) – Factor to control smoothing of the contours. It can be 0, meaning no smoothing is applied. Value of 0.1-0.15 is reasonable.

  • planC (cerr.plan_container.PlanC) – pyCERR’s plan container object

  • replaceFlag (bool) – when True, contours of the originl structure are replaced by smooth contours. If False, a new structure is added to planC.

  • procSructName (str) – Name of structure. When not specifid, the original structure name is retained.

Returns:

pyCERR’s plan container object.

Return type:

cerr.plan_container.PlanC

cerr.dataclasses.structure.getLabelMap(planC, labelDict=None, strNumV=None, dim=3)[source]

Function to create label map for user-specified structures.

Parameters:
  • planC (plan_container.planC) – pyCERR plan_container object.

  • labelDict (dict) – [optional, default={}] dictionary mapping indices with structure names.

  • strNumV (list) – [optional, default=None] Structure indices to be exported.

  • dim (int) – [optional, default=3] int indicating dimensions of output label map. When set to 3, returns 3D label map np.array(dtype=int). When set to 4, returns 4D array of binary masks (required for overlapping structures).

Returns:

np.ndarray(dtype=int) for label map.

Return type:

labelMap3M

cerr.dataclasses.structure.getMaskList(strNumV, planC, labelDict=None, binFlag=False)[source]

Function to create list of label maps (default) or binary masks (binFlag=True) of user-specified structures.

Parameters:
  • strNumV – list of structure indices to be exported.

  • planC – pyCERR plan_container object.

  • labelDict – [optional, default={}] dictionary mapping indices with structure names.

  • binFlag – Set to true to return binary masks rather than label maps (default)

Returns:

list(dtype=bool) of binary masks.

Return type:

maskList

Module contents