Generation#

Objects#

pydicer.generate.object.add_dose_object(working_directory: Path, dose: Image, dose_id: str, patient_id: str, linked_plan: Optional[Union[str, Series]] = None, for_uid: Optional[str] = None, datasets: Optional[Union[str, list]] = None)#

Add a generated dose object to the project.

Parameters:
  • working_directory (pathlib.Path) – The project working directory.

  • dose (sitk.Image) – A SimpleITK.Image of the dose volume to add.

  • dose_id (str) – The unique ID of the new dose object.

  • patient_id (str) – The ID of the patient of this object.

  • linked_plan (str|pd.Series, optional) – The hashed_uid or the Pandas DataFrame row of the RTPLAN object to link to. If None the new object won’t be linked. Defaults to None.

  • for_uid (str, optional) – Frame Of Reference UID for new data object. If not provided it will be extracted from the linked plan (if available). Defaults to None.

  • datasets (list|str, optional) – The name(s) of the dataset(s) to add the object to. Defaults to None.

Raises:
  • ValueError – Raised then the patient ID does not exist

  • SystemError – Raised when a linked_plan is provided but can’t be found for this patient.

pydicer.generate.object.add_image_object(working_directory: Path, image: Image, image_id: str, modality: str, patient_id: str, linked_image: Optional[Series] = None, for_uid: Optional[str] = None, datasets: Optional[Union[str, list]] = None)#

Add a generated image object to the project.

Parameters:
  • working_directory (pathlib.Path) – The project working directory.

  • image (sitk.Image) – The SimpleITK.Image object to save.

  • image_id (str) – The unique ID of the new image object.

  • modality (str) – The modality of the image being saved.

  • patient_id (str) – The ID of the patient of this object.

  • linked_image (str|pd.Series, optional) – The hashed_uid or the Pandas DataFrame row of the image object to link to. If None the new object won’t be linked. Defaults to None.

  • for_uid (str, optional) – Frame Of Reference UID for new data object. If not provided it will be extracted from the linked image (if available). Defaults to None.

  • datasets (list|str, optional) – The name(s) of the dataset(s) to add the object to. Defaults to None.

Raises:
  • ValueError – Raised then the patient ID does not exist

  • SystemError – Raised when a linked_image is provided but can’t be found for this patient.

pydicer.generate.object.add_object(working_directory: Path, object_id: str, patient_id: str, object_type: str, modality: str, for_uid: Optional[str] = None, referenced_sop_instance_uid: Optional[str] = None, datasets: Optional[Union[str, list]] = None)#

Add a generated object to the project.

Parameters:
  • working_directory (pathlib.Path) – The working directory of the project.

  • object_id (str) – The unique ID of the new object.

  • patient_id (str) – The ID of the patient for which the object is being added.

  • object_type (str) – The type of object, must be one of “image”, “structure”, “plan” or “dose”.

  • modality (str) – The modality of the object (as per the DICOM standard)

  • for_uid (str, optional) – The Frame of Reference UID. Defaults to None.

  • referenced_sop_instance_uid (str, optional) – The SOP Instance UID of the object referenced by the generated object. Defaults to None.

  • datasets (list|str, optional) – The name(s) of the dataset(s) to add the object to. Defaults to None.

Raises:
  • ValueError – Raised in object_type is not “image”, “structure”, “plan” or “dose”.

  • ValueError – Raised if the patient does not exist in the project.

  • SystemError – Raised if the generated object does not yet exist on the file system.

  • SystemError – Raised if an object with this ID has already exists in the project.

pydicer.generate.object.add_structure_object(working_directory: Path, structures: dict, structure_id: str, patient_id: str, linked_image: Optional[Union[str, Series]] = None, for_uid: Optional[str] = None, datasets: Optional[Union[str, list]] = None)#

Add a generated structure object to the project.

Parameters:
  • working_directory (pathlib.Path) – The project working directory.

  • structures (dict) – A dict object container structure names as key and SimpleITK.Image of the corresponding structure mask as value.

  • structure_id (str) – The unique ID of the new structure object.

  • patient_id (str) – The ID of the patient of this object.

  • linked_image (str|pd.Series, optional) – The hashed_uid or the Pandas DataFrame row of the image object to link to. If None the new object won’t be linked. Defaults to None.

  • for_uid (str, optional) – Frame Of Reference UID for new data object. If not provided it will be extracted from the linked image (if available). Defaults to None.

  • datasets (list|str, optional) – The name(s) of the dataset(s) to add the object to. Defaults to None.

Raises:
  • ValueError – Raised then the patient ID does not exist

  • SystemError – Raised when a linked_image is provided but can’t be found for this patient.

pydicer.generate.object.get_linked_for_and_ref_uid(working_directory: Path, patient_id: str, linked_obj: Optional[Union[str, Series]] = None) tuple#

Determine the linked frame of reference UID and SOP instance UID

Parameters:
  • working_directory (pathlib.Path) – The project working directory.

  • patient_id (str) – The ID of the patient containing the objects.

  • str|pd.Series (linked_obj) – The hashed_uid or the Pandas DataFrame row of the object to link to. If None the new object won’t be linked.

  • optional) – The hashed_uid or the Pandas DataFrame row of the object to link to. If None the new object won’t be linked.

Raises:

SystemError – Raised when no link is found.

Returns:

A tuple containing he frame of reference UID and the referenced SOP instance UID.

Return type:

tuple

Auto-segmentation#

pydicer.generate.segmentation.get_segmentation_log_path(image_row: Series) Path#

Get the auto-segmentation log path given an image entry.

Parameters:

image_row (pd.Series) – A row of an image of a converted data frame.

Returns:

Path to the relavant patient’s auto-segmentation log.

Return type:

pathlib.Path

pydicer.generate.segmentation.read_all_segmentation_logs(working_directory: Path, dataset_name: str = 'data', segment_id: Optional[str] = None, modality: Optional[str] = None) DataFrame#

Read all auto-segmentation logs in a dataset. :param dataset_name: The name of the dataset to read for. :type dataset_name: str :param segment_id: The ID of the auto-segmentation run. :type segment_id: str :param modality: The modality of the images to read logs for. :type modality: str

Returns:

The pandas DataFrame object with all logs for the dataset.

Return type:

pd.DataFrame

pydicer.generate.segmentation.read_segmentation_log()#

Read the auto-segmentation log given an image entry.

Parameters:

image_row (pd.Series) – A row of an image of a converted data frame.

Returns:

The pandas DataFrame object describing the log.

Return type:

pd.DataFrame

pydicer.generate.segmentation.segment_dataset(working_directory: Path, segment_id: str, segmentation_function: Callable, dataset_name: str = 'data', modality: str = 'CT', force: False = False)#

Run an auto-segmentation function across all images of a given modality in a dataset.

Parameters:
  • working_directory (Path) – The PyDicer working directory.

  • segment_id (str) – The ID to be given to track the results of this segmentation.

  • segmentation_function (Callable) – The function to call to run the segemtantion. Excepts a SimpleITK.Image as input and returns a dict object with structure names as keys and SimpleITK.Image masks as values.

  • dataset_name (str, optional) – The name of the dataset to run auto-segmentation on. Defaults to CONVERTED_DIR_NAME which run across all images available.

  • modality (str, optional) – The modality of the image to run on. Defaults to “CT”.

  • force (bool, optional) – If True, the segmetation will be re-run for each image even if it was already previously run. Defaults to False.

pydicer.generate.segmentation.segment_image(working_directory: Path, image_row: Series, segment_id: str, segmentation_function: Callable, dataset_name: Optional[str] = None, force: bool = False)#

Run an auto-segmentation function on an image. Provide the image row of the converted DataFrame to auto-segment, segmentation results will be save as a new object within the patient’s data.

The segment_function provided should accept a SimpleITK image as input and return a dict with structure names as keys and SimpleITK images as value.

If you segmentation algorithm requires further customisation, consider wrapping it in a function to match this notation. For example, to run the TotalSegmentator, you can define a warpper function like:

```python import tempfile from pathlib import Path import SimpleITK as sitk

def run_total_segmentator(input_image: sitk.Image) -> dict:

# Import within function since this is an optional dependency
from totalsegmentator.python_api import (

totalsegmentator, # pylint: disable=import-outside-toplevel

)

results = {}

with tempfile.TemporaryDirectory() as working_dir:

working_dir = Path(working_dir)

# Save the temporary image file for total segmentator to find input_dir = working_dir.joinpath(“input”) input_dir.mkdir() input_file = input_dir.joinpath(“img.nii.gz”) sitk.WriteImage(input_image, str(input_file))

# Prepare a temporary folder for total segmentator to store the output output_dir = working_dir.joinpath(“output”) output_dir.mkdir()

# Run total segmentator totalsegmentator(input_dir, output_dir)

# Load the output masks into a dict to return for mask_file in output_dir.glob(”*.nii.gz”):

mask = sitk.ReadImage(str(mask_file))

# Check if the mask is empty, total segmentator stores empty mask files for # structures that aren’t within FOV if sitk.GetArrayFromImage(mask).sum() == 0:

continue

structure_name = mask_file.name.replace(“.nii.gz”)

results[structure_name] = mask

return results

```

Parameters:
  • working_directory (Path) – The PyDicer working directory.

  • image_row (pd.Series) – The image row of the converted DataFrame to use for segmentation.

  • segment_id (str) – The ID to be given to track the results of this segmentation.

  • segmentation_function (Callable) – The function to call to run the segemtantion. Excepts a SimpleITK.Image as input and returns a dict object with structure names as keys and SimpleITK.Image masks as values.

  • dataset_name (str, optional) – The name of the dataset to add the segmented structure set to. Defaults to None.

  • force (bool, optional) – If True, the segmetation will be re-run. Defaults to False.

Raises:

TypeError – The segmentation function returned the wrong type (requies a dict)

pydicer.generate.segmentation.write_autoseg_log(image_row: ~pandas.core.series.Series, segment_id: str, start_time: <module 'datetime' from '/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/datetime.py'>, end_time: <module 'datetime' from '/opt/hostedtoolcache/Python/3.9.18/x64/lib/python3.9/datetime.py'>, success: bool, error_msg: str)#

Writes the auto-segmentation log for an auto-segmentation run.

Parameters:
  • image_row (pd.Series) – The row of an image of a converted data frame on which the auto-segmentation was run.

  • segment_id (str) – The ID of the auto-segmentation run.

  • start_time (datetime) – The date/time the run started.

  • end_time (datetime) – The date/time the run ended.

  • success (bool) – Boolean flag inicated if the auto-segmentation was run successfully or not.

  • error_msg (str) – A string indicating the error message if there was an error.

Models#

pydicer.generate.models.get_available_mhub_models() dict#

Determine which mHub models have been configured for use in PyDicer.

Returns:

A dictionary with mhub model id as key and the path to the config file as value.

Return type:

dict

pydicer.generate.models.load_output_nifti(output_dir: Path) dict#

Loads segmentation masks saved as Nifti’s in an output directory into a dictionary for use in PyDicer.

Parameters:

output_dir (Path) – The output directory of a segmentation model.

Returns:

Dictionary of segmentation masks with the structure name as key and sitk.Image mask

as value.

Return type:

dict

pydicer.generate.models.run_mhub_model(input_image: Image, mhub_model: str, mhub_config_file: Optional[Path] = None, gpu: bool = True) dict#

Use Docker to run a model made available through mHub: https://mhub.ai/

Parameters:
  • input_image (sitk.Image) – The SimpleITK image to segment.

  • mhub_model (str) – The name of the model to run. Must be configured (check get_available_mhub_models) or a custom mhub_config_file should be provided.

  • mhub_config_file (Path, optional) – Path to a custom config file to use. Defaults to None.

  • gpu (bool, optional) – If True, all gpus will be requested when running the Docker image. Defaults to True.

Raises:
  • ImportError – Raised if the Python Docker SDK is not installed.

  • ValueError – Raised if an mHub model which has not been configured for use in PyDicer is requested. Use the get_available_mhub_models function to determine available models.

Returns:

Dictionary of segmentations with structure name as key and sitk.Image mask as value.

Return type:

dict

pydicer.generate.models.run_total_segmentator(input_image: Image) dict#

Run Total Segmentator on a given input image. Ensure the Total Segmentator is installed:

` pip install TotalSegmentator `

See https://github.com/wasserth/TotalSegmentator for more information.

Parameters:

input_image (sitk.Image) – Input image (should be CT) to segment.

Returns:

Dictionary of segmentations with structure name as key and sitk.Image mask as value.

Return type:

dict