PyPlanAnalysis.io¶
DICOM auto-discovery and loading, CT/dose grid resampling, and RT Struct mask extraction (binary and fractional/supersampled).
PyPlanAnalysis.io¶
DICOM discovery and loading, CT/dose grid resampling, and RT Struct mask extraction (binary and fractional).
- find_dicom_files(folder)[source]¶
Auto-discover RT Dose (physical dose, LET), RT Struct, RT Plan and CT files belonging to the same plan, by inspecting DICOM modality tags and cross-reference (Referenced UID) tags. The folder (and its sub-folders) may contain extra or unrelated files of any of these types; this function searches through all of them for the one set that is actually linked together.
- Return type:
dict- Returns:
dict with keys – “dose”, “let”, “rtstruct”, “rtplan” : Path or None “CT” : Path to the directory holding the matched CT
series, or None
”Patient_ID” : str or None “linked” : True if RTPLAN -> RTSTRUCT -> CT was fully
confirmed via DICOM reference tags; False if a fallback/best-guess match had to be used; None if there wasn’t enough data to even attempt the check (e.g. no RTSTRUCT and no CT found at all).
- ”link_warnings”: list[str], one entry per fallback
that was needed, explaining what couldn’t be confirmed and what was used instead.
- Parameters:
folder (Path)
- load_ct_series(ct_folder)[source]¶
Load a multi-slice CT DICOM series from a folder.
Slices are sorted by ImagePositionPatient z-coordinate. Spacing is taken from PixelSpacing of the first slice and the z-step between consecutive slice positions.
- Return type:
tuple- Returns:
sitk_image (SimpleITK.Image (x, y, z ordering internally))
ct_geometry (dict with keys:) – “origin” : [x0, y0, z0] mm (corner of first voxel) “spacing” : [dx, dy, dz] mm “shape” : (nz, ny, nx) — numpy (z,y,x) convention “z_positions” : np.ndarray of slice z-coordinates length nz
- Parameters:
ct_folder (str | Path)
- resample_dose_to_new_grid(dose_sitk, dose_ds, new_spacing, interpolator=SimpleITK.sitkLinear)[source]¶
Resample RTDOSE onto a new isotropic/anisotropic grid :type dose_sitk: sitk.Image Original dose image :param dose_sitk: :type dose_sitk: sitk.Image Original dose image :type dose_ds: pydicom Dataset RTDOSE dataset :param dose_ds: :type dose_ds: pydicom Dataset RTDOSE dataset :type new_spacing: tuple/list (sx, sy, sz) in mm :param new_spacing: :type new_spacing: tuple/list (sx, sy, sz) in mm
- Returns:
resampled_dose (sitk.Image)
updated_info (dict)
dose_ds (updated dataset)
- resample_dose_on_ct(sitk_dose, sitk_ct)[source]¶
Resample a dose (or LET) SimpleITK image onto the CT grid.
The CT image defines the output origin, spacing, direction, and size. This ensures that the resampled dose array is perfectly aligned with the CT grid on which contours will be rasterised.
- Parameters:
sitk_dose (SimpleITK.Image (dose or LET, in dose-grid coordinates))
sitk_ct (SimpleITK.Image (full CT series))
- Return type:
Image- Returns:
SimpleITK.Image same grid as sitk_ct
- load_dose_grid(path)[source]¶
Load a DICOM RT Dose file (dose or LET stored as dose grid).
- Return type:
tuple- Returns:
array (np.ndarray shape (z, y, x))
ds (pydicom Dataset)
- Parameters:
path (str | Path)
- get_grid_geometry(ds)[source]¶
Extract (origin, spacing) from an RT Dose dataset.
- Return type:
tuple- Returns:
origin ([x0, y0, z0] mm)
spacing ([dx, dy, dz] mm)
- get_all_structure_names(rtstruct_ds)[source]¶
Return list of all structure names in an RT Struct dataset.
- Return type:
list
- get_structure_mask_on_grid(struct_name, rtstruct_ds, origin, spacing, shape, z_positions)[source]¶
Rasterise RT Struct contours for struct_name onto an arbitrary grid.
This is the core function used for both dose-grid and CT-grid masking. Contour z-values are matched to the nearest z in z_positions.
- Parameters:
struct_name (str)
rtstruct_ds (pydicom Dataset)
origin ([x0, y0, z0] mm — physical coordinate of voxel (0,0,0) corner)
spacing ([dx, dy, dz] mm)
shape ((nz, ny, nx) — numpy array shape)
z_positions (1-D array of z-coordinates for each slice (length nz))
- Return type:
ndarray- Returns:
mask (np.ndarray bool, shape (nz, ny, nx))
- get_roi_center_of_mass(struct_name, rtstruct_ds)[source]¶
Compute the 3-D center of mass (mm, in the RT Struct’s patient coordinate system) of a structure directly from its contour polygons — no dose/CT grid required.
Each contour (one per slice) contributes its own 2-D polygon centroid, weighted by that contour’s area, so slices with more cross-sectional area count more towards the overall COM volume-weighted approximation without needing a full 3-D mask.
- Parameters:
struct_name (str) – Structure name as it appears in the RT Struct.
rtstruct_ds (pydicom Dataset)
- Return type:
ndarray- Returns:
np.ndarray, shape (3,), or None –
[x, y, z]center of mass in mm. ReturnsNoneif no usable contour data is available for this structure.
- contour_area_signed(xy)[source]¶
Signed polygon area via the shoelace formula.
- Parameters:
xy (np.ndarray, shape (N, 2)) – Polygon vertices [x, y] in mm.
- Returns:
float – Signed area; positive for counter-clockwise vertex order, negative for clockwise. Used to detect contour holes.
- smooth_contour(poly_xy, n_pts=300)[source]¶
Resample a contour polygon onto
n_ptsevenly-spaced points using a periodic B-spline fit. Not used by default in the fractional-mask pipeline (see inline note inget_fractional_mask_on_grid); kept available for callers who want smoothed contours.- Parameters:
poly_xy (np.ndarray, shape (N, 2)) – Polygon vertices [x, y] in mm.
n_pts (int, default 300) – Number of points in the resampled output.
- Returns:
np.ndarray, shape (n_pts, 2) – Smoothed polygon vertices. Falls back to the original polygon, unchanged, if the spline fit fails.
- rasterize_supersampled(smooth_xy, x0, y0, dx, dy, ny, nx, N)[source]¶
Rasterise one contour polygon onto a grid at N times finer resolution, then average back down — giving each output voxel a fractional [0, 1] membership value instead of a hard binary in/out.
- Parameters:
smooth_xy (np.ndarray, shape (N, 2)) – Polygon vertices [x, y] in mm.
x0 (float) – Grid origin (mm) in x and y.
y0 (float) – Grid origin (mm) in x and y.
dx (float) – Grid voxel spacing (mm) in x and y.
dy (float) – Grid voxel spacing (mm) in x and y.
ny (int) – Output grid shape.
nx (int) – Output grid shape.
N (int) – Supersampling factor per side (N² sub-samples per voxel).
- Returns:
np.ndarray, shape (ny, nx), float32 – Fractional coverage of each voxel by the polygon, in [0, 1].
- compute_roi_volume_comparison(frac_mask, dx, dy, dz)[source]¶
Print and return the total volume of a fractional mask, plus a per-slice breakdown — useful for sanity-checking
get_fractional_mask_on_gridoutput against a TPS-reported volume.- Parameters:
frac_mask (np.ndarray, shape (nz, ny, nx)) – Fractional voxel membership mask, values in [0, 1].
dx (float) – Voxel spacing (mm) in x, y, z.
dy (float) – Voxel spacing (mm) in x, y, z.
dz (float) – Voxel spacing (mm) in x, y, z.
- Returns:
float – Total volume in cc (sum of fractional weights x voxel volume).
- prismatoid_volume(frac_mask, dx, dy, dz)[source]¶
Volume of a fractional mask via the prismatoid (Simpson’s-rule-like) formula between consecutive slices, instead of a flat sum-of-slices approximation. Slightly more accurate for structures with rapidly changing cross-sectional area between slices.
- Parameters:
frac_mask (np.ndarray, shape (nz, ny, nx)) – Fractional voxel membership mask, values in [0, 1].
dx (float) – Voxel spacing (mm) in x, y, z.
dy (float) – Voxel spacing (mm) in x, y, z.
dz (float) – Voxel spacing (mm) in x, y, z.
- Returns:
float – Total volume in cc.
- get_fractional_mask_on_grid(struct_name, rtstruct_ds, origin, spacing, shape, z_positions, supersample=4)[source]¶
Compute a fractional voxel membership mask on an arbitrary grid.
Each voxel receives a value in [0,1] — the fraction of its physical area (in xy) that lies inside the RT Struct contour, estimated by supersampling (supersample² sub-points per voxel).
- Parameters:
struct_name (str)
rtstruct_ds (pydicom Dataset)
origin ([x0, y0, z0] mm)
spacing ([dx, dy, dz] mm)
shape ((nz, ny, nx))
z_positions (1-D array length nz)
supersample (N subdivisions per side (default 4 → 16 sub-points/voxel))
- Return type:
ndarray- Returns:
frac_mask (np.ndarray float32, shape (nz, ny, nx), values in [0, 1])