cerr.utils package

Submodules

cerr.utils.ai_pipeline module

This module defines routines useful to build and deploy AI models

cerr.utils.ai_pipeline.createSessionDir(sessionPath, inputDicomPath, inputSubDirs=None)[source]

Function to create a directory to write temporary files when deploying AI models. inputDicomPath

Parameters:
  • sessionPath (string) – Desired location of session directory

  • inputDicomPath (string) – Path to DICOM input data. The session directory is assigned a unique name derived in aprt from the DICOM folder name.

  • inputSubDirs (list) – [optional, default=None] Create subdirectories for inputs other than scans.

Returns:

Path to directory containing data input to AI model modOutputPath (string): Path to directory containing data output by AI model

Return type:

modInputPath (string)

cerr.utils.ai_pipeline.getAssocFilteredScanNum(scanNumV, planC)[source]

Function to return index of filtered scan derived from original input scan.

Parameters:
  • scanNumV (list) – Original scan indices in planC

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

Returns:

Filtered scan indices in planC created from input list

of scans.

Return type:

filtScanNumV (list)

cerr.utils.ai_pipeline.getAssocWarpedScanNum(scanNumV, planC)[source]

Function to return index of deformed scan derived from original input scan.

Parameters:
  • scanNumV (list) – Original scan indices in planC

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

Returns:

Warped scan indices in planC created from input list

of scans.

Return type:

warpedScanNumV (list)

cerr.utils.ai_pipeline.getAssocResampledScanNum(scanNumV, planC)[source]

Function to return index of resampled scan derived from original input scan.

Parameters:
  • scanNumV (list) – Original scan indices in planC

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

Returns:

Resampled scan indices in planC created from input list

of scans.

Return type:

warpedScanNumV (list)

cerr.utils.ai_pipeline.getScanNumFromIdentifier(idDict, planC, origFlag: bool = False)[source]

Function to retrieve index of scan with metadata matching user-input identifier(s).

Parameters:
  • idDict (dictionary) – Scan identifiers specified in keys specifying, with corresponding values specifying expected quantity. Supported identifiers include: ‘imageType’, ‘seriesDescription’, ‘scanNum’, ‘scanType’, ‘seriesDate’ (may be” first” or “last”), ‘studyDate’ (may be” first” or “last”), and ‘assocStructure’ (use structure name to identify associated scans. Set to ‘none’ to select scans with no associated structures)

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

  • origFlag (bool) – [optional, default:False] Flag to ignore ‘warped’, ‘resampled’ or ‘filtered’ scans.

Returns:

Scan indices matching specified identifier(s).

Return type:

scanNumV (np.array)

cerr.utils.custom_colormaps module

Custom color maps for the Viewer

cerr.utils.custom_colormaps.starInterp()[source]

cerr.utils.image_proc module

Pre- and post-processing transformations for AI models

cerr.utils.image_proc.resizeScanAndMask(scan3M, mask4M, gridS, outputImgSizeV, method, limitsM=None, preserveAspectFlag=False)[source]

Function to resize input scan and mask using specified coordinates, method, and output dimensions. Supports preserving aspect ratio and slice-wise resizing within bounding box limits.

Parameters:
  • scan3M (np.ndarray) – 3D input scan.

  • mask4M (np.ndarray) – 4D input mask of dimension [nRows x nCols x nSlices x nStructures] (stack of binary masks representing various structures).

  • gridS (tuple) – Vectors (xV, yV, zV) for coordinates of input scan/mask (3D methods) OR matrices of slices-wise coordinates (xM, yM, zM) of input scan/mask (2D methods).

  • outputImgSizeV (np.array) – Output image dimensions [nRows, nCols, nSlices].

  • method (string) –

    Resizing method for input scan. Supported options include ‘padorcrop3d’, ‘pad3d’, ‘unpad3d’, ‘pad2d’, ‘unpad2d’, ‘padslices’ ‘unpadslices’, ‘bilinear’,’bicubic’, and ‘nearest’.

    Note: Masks are resized using ‘nearest’ for input methods ‘bilinear’,’bicubic’, and ‘nearest’.

  • limitsM (np.ndarray) – [optional, default=None] Extents of bounding box on each slice. minr = limitsM[slcNum, 0], maxr = limitsM[slcNum, 1], minc = limitsM[slcNum, 2], maxc = limitsM[slcNum, 3]

  • preserveAspectFlag (bool) – Flag to preserve input aspect ratio by padding prior to resizing.

Returns:

3D resized scan. maskOut4M (np.ndarray): 4D resized mask. gridOutS (tuple): Vectors (xV, yV, zV) for coordinates of output scan/mask (3D methods)

OR matrices of slices-wise coordinates (xM, yM, zM) of input scan/mask (2D methods).

Return type:

scanOut3M (np.ndarray)

cerr.utils.image_proc.transformScan(scan3M, mask4M, gridS, orientation)[source]

Transpose a scan (and optional mask/grid) into a target anatomical orientation.

Reorders the axes of scan3M and mask4M so that the data is laid out in the requested viewing plane without resampling.

Parameters:
  • scan3M (np.ndarray) – 3D input scan array with shape [nRows, nCols, nSlices].

  • mask4M (np.ndarray or None) – 4D mask array with shape [nRows, nCols, nSlices, nStructures], or None if no mask is needed.

  • gridS (tuple or None) – Coordinate tuple (xV, yV, zV) for the input scan/mask, or None if coordinates are not required.

  • orientation (str) – Target orientation. Supported values are 'axial' (no change), 'coronal', and 'sagittal'.

Returns:

A three-element tuple (outScan3M, outMask4M, outGridS) where

  • outScan3M (np.ndarray): Transposed scan array.

  • outMask4M (np.ndarray or None): Transposed mask array, or None if mask4M was None.

  • outGridS (tuple or None): Reordered coordinate tuple, or None if gridS was None.

Return type:

tuple

Raises:

ValueError – If orientation is not one of the supported values.

cerr.utils.interp module

cerr.utils.interp.finterp3(xInterpV, yInterpV, zInterpV, field3M, xFieldV, yFieldV, zFieldV, OOBV=None)[source]

Perform fast trilinear interpolation of a 3D scalar field.

Interpolates field3M at the query coordinates (xInterpV, yInterpV, zInterpV) using trilinear interpolation. Points that fall outside the field grid are assigned OOBV.

Parameters:
  • xInterpV (np.ndarray) – 1-D array of x (column-direction) query coordinates.

  • yInterpV (np.ndarray) – 1-D array of y (row-direction) query coordinates.

  • zInterpV (np.ndarray) – 1-D array of z (slice-direction) query coordinates.

  • field3M (np.ndarray) – 3D array of scalar field values with shape [nRows, nCols, nSlices].

  • xFieldV (np.ndarray) – 1-D array of x grid coordinates for field3M. Must be uniformly spaced.

  • yFieldV (np.ndarray) – 1-D array of y grid coordinates for field3M. Must be uniformly spaced.

  • zFieldV (np.ndarray) – 1-D array of z grid coordinates for field3M. May be non-uniformly spaced.

  • OOBV (float, optional) – Value assigned to out-of-bounds query points. Defaults to np.nan.

Returns:

1-D array of interpolated values with the same length as xInterpV. Out-of-bounds entries are set to OOBV.

Return type:

np.ndarray

cerr.utils.interp.finterp2(x, y, z, xi, yi, uniformFlag=0, outOfRangeVal=nan)[source]

This Python version of the finterp2 function should now work similarly to the MATLAB version for regularly spaced matrices and uniform grids. The output zi will be a 2D array interpolated from the input z based on the provided xi and yi vectors. The uniformFlag parameter is optional and defaults to 0. The outOfRangeVal parameter is also optional and defaults to np.nan.

cerr.utils.mask module

Functions for processing of binary masks, including morphological operations and custom routines mask generation.

cerr.utils.mask.getDown2Mask(inM, sample)[source]

Create a 2D downsampling mask by marking every sample-th row and column.

Parameters:
  • inM (np.ndarray) – 2D input array whose shape determines the mask size.

  • sample (int) – Step size used to select rows and columns.

Returns:

Boolean array of the same shape as inM with True at every sample-th row/column intersection.

Return type:

np.ndarray

cerr.utils.mask.getDown3Mask(mask3M, sampleTrans, sampleAxis)[source]

Create a 3D downsampling mask by applying 2D downsampling on selected slices.

Parameters:
  • mask3M (np.ndarray) – 3D input array whose shape determines the mask size.

  • sampleTrans (int) – Step size for downsampling within each transverse slice (rows and columns).

  • sampleAxis (int) – Step size for selecting slices along the third axis.

Returns:

Boolean array of the same shape as mask3M with True only at sampled row/column/slice positions.

Return type:

np.ndarray

cerr.utils.mask.getSurfacePoints(mask3M, sampleTrans=1, sampleAxis=1)[source]

Routine to obtain sruface coordinates of the input mask

Parameters:
  • mask3M (numpy.ndarray) – binary mask representing segmentation

  • sampleTrans (int) – optional, sample rate in transverse plane

  • 9int) (sampleAxis) – optional, sample rate along slices

Returns:

r,c,s coordinates of surface voxels

Return type:

tuple

cerr.utils.mask.surfaceExpand(mask3M, dxyz, marginCm, restrict_2d=False)[source]

Expand or contract a binary mask by a physical margin along its surface.

Surface voxels are identified and a spherical ball of radius marginCm is applied at each surface point to grow (positive margin) or shrink (negative margin) the mask.

Parameters:
  • mask3M (np.ndarray) – 3D binary input mask.

  • dxyz (array-like) – Voxel spacing in cm as [dx, dy, dz].

  • marginCm (float) – Margin to apply in cm. Positive values expand the mask; negative values contract it.

  • restrict_2d (bool) – If True, expansion is performed independently on each transverse slice (no inter-slice spreading). Defaults to False.

Returns:

Boolean array of the same shape as mask3M representing the expanded (or contracted) mask.

Return type:

np.ndarray

cerr.utils.mask.createStructuringElement(sizeCm, resolutionCmV, dimensions=3, shape='flat')[source]

Function to create structuring element for morphological operations given desired dimensions in cm.

Parameters:
  • sizeCm (np.float) – Size of structuring element in cm.

  • resolutionCmV (np.array) – Image resolution in cm [dx, dy, dz].

  • dimensions (int) – [optional, default=3] Specify 3 for 3D or 2 for 2D.

  • shape (string) – [optional, default=’flat’] Geometric neighborhood shape. Supported values: ‘flat’, ‘sphere’, ‘disk’.

Returns:

Structuring element.

Return type:

structuringElement (np.ndarray)

cerr.utils.mask.fillHoles(binaryMask)[source]

Function to fill small holes in input binary mask

Parameters:

binaryMask – np.ndarray(type=bool) for input mask.

Returns:

np.ndarray(type=bool) for filled mask.

Return type:

filledMask

cerr.utils.mask.morphologicalClosing(binaryMask, structuringElement)[source]

Function for morphological closing of input binary mask

Parameters:
  • binaryMask (np.ndarray(dtype=bool)) – Input mask.

  • structuringElement (np.array) – Flat morphological structuring element.

Returns:

Closed mask using input structuring element.

Return type:

numpy.ndarray(dtype=bool)

cerr.utils.mask.blurring(binaryMask, sigmaVox, filtType='gaussian')[source]

Function for Gaussian blurring of input binary mask

Parameters:
  • binaryMask (numpy.array) – Binary mask to blur.

  • sigmaVox (float) – Sigma for Gaussian OR filter radius for box filter (in units of voxels).

  • filtType (string) – [optional, default:’gaussian’] ‘gaussian’ or ‘box’ smoothing filter.

Returns:

Blurred mask using Gaussian blur with input sigma.

Return type:

numpy.ndarray(dtype=bool)

cerr.utils.mask.computeBoundingBox(binaryMaskM, is2DFlag=False, maskFlag=0)[source]

Function for finding extents of bounding box given a binary mask

Parameters:
  • binaryMaskM (np.ndarray(type=bool)) – Input mask.

  • is2DFlag (bool) – [optional, default=False] Flag for computing slice-wise extents if true.

  • maskFlag (int) – [optional, default=0] If maskFlag > 0, it is interpreted as a padding parameter.

Returns:

Start of mask along rows. maxr(int): End of mask along rows. minc(int): Start of mask along cols. maxc(int): End of mask along cols. mins(int): Start of mask along slices. maxs(int): End of mask along slices. bboxmask (np.ndarray(dtype=bool)): Mask of bounding box.

Return type:

minr (int)

cerr.utils.mask.closeMask(mask3M, inputResV, structuringElementSizeCm, shape='flat')[source]

Function for morphological closing and hole-filling for binary masks

Parameters:
  • mask3M (np.ndarray) – Binary mask to close and hole-fill.

  • inputResV (np.array) – Physical Resolution of the mask in cm.

  • structuringElementSizeCm (float) – Size of structuring element for closing in cm

  • shape (str) – Shape of structuring element. May be ‘flat’, ‘disk’, or ‘sphere’.

Returns:

Filled mask.

Return type:

filledMask3M (np.ndarray(dtype=bool))

cerr.utils.mask.largestConnComps(mask3M, numConnComponents, minSize=0, dim=3)[source]

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

Parameters:
  • mask3M (np.ndarray(dtype=bool)) – 3D binary segmentation mask (OR) 3D binary mask.

  • numConnComponents (int) – number of largest components to retain.

  • minSize (int) – [optional, default=0] Min. size of connected component to retain.

  • dim (int) – [optional, default=3. Includes 26 neighbours in 3D ] 2 (2D) or 3 (3D).

Returns:

3D mask with labels corresponding to components.

Return type:

maskOut3M (np.ndarray(dtype=bool))

cerr.utils.mask.getCouchLocationHough(scan3M, minLengthOpt=None, retryOpt=False)[source]

Function to identify location (row no.) of couch in input scan

Parameters:
  • scan3M (np.ndarray) – Input scan.

  • minLengthOpt (float) – [optional, default=None] Minimum length of couch expected (in no. voxels). If set to None, min. length is taken to be 1/8th image size.

  • retryOpt (bool) – [optional, default=False] Flag to rerun search with minLengthOpt halved if couch length is 0.

Returns:

Row no. representing couch location. selectedLines (dict): Candidate lines representing couch.

Return type:

yCouch (int)

cerr.utils.mask.getPatientOutline(scan3M, outThreshold=-400, slicesV=None, minMaskSize=1500, normFlag=False)[source]

Function to extract binary mask of patient outline on input scan.

Parameters:
  • scan3M (np.ndarray) – 3D scan.

  • outThreshold (float) – [optional, default=-400] Intensity level representing air. -400 HU is for CT scans. Users should input appropriate threshold for other modalities.

  • slicesV (np.array) – [optional, default=None] Range of slices for outline extraction. All slices are analyzed if set to None.

  • minMaskSize (int) – [optional, default=1500] Minimum acceptable size of mask on any slice in no. voxels.

  • normFlag (bool) – [optional, default=False] Flag to normalize scan3M before applying air threshold (recommended for MR images).

Returns:

Mask of patient outline.

Return type:

conn3dPtMask3M (np.ndarray(dtype=bool))

cerr.utils.statistics module

Functions to compute statistics

cerr.utils.statistics.quantile(x, q)[source]

Function to compute specified quantile from input array.

Returns:

qth quantile of values in input x.

cerr.utils.statistics.prctile(x, p)[source]

MATLAB prctile.m equivalent function to compute percentile

cerr.utils.statistics.round(x)[source]

Substitute for numpy.round(), which uses a fast but inexact algorithm. This function avoids documented issues of numpy.round() e.g. rounding of inputs exactly halfway between rounded decimal values to the nearest even value. See: https://numpy.org/doc/stable/reference/generated/numpy.round.html

cerr.utils.uid module

cerr.utils.uid.createUID(modality)[source]

Function to create a unique identifier for various pyCERR dataclass objects.

Parameters:

modality – string for pyCERR object. May be ‘SCAN’, ‘STRUCTURE’, ‘DOSE’, ‘BEAMS’, ‘STRUCTURESET’, ‘DVH’, ‘IVH’, ‘DEFORM’, ‘BEAM’, ‘CERR’, ‘TEXTURE’, ‘ANNOTATION’, ‘SEGLABEL’, ‘REGISTRATION’, ‘IM’, ‘FEATURESET’.

Returns:

Unique identifier for object of specified class, using current date and time.

Module contents