in pathology/transformation_pipeline/ingestion_lib/dicom_gen/wsi_to_dicom/ingest_wsi_dicom.py [0:0]
def _generate_instance_number_dict(self):
"""Generates internal instance number mapping dictionary.
Dictionary maps[DICOM uid triple] to instance number
WSI images are sorted first by width (total_pixel_matrix_columns) and
then by image type. WSI images are numbered starting at 1. Instance
numbers are incremented when image dimensions or image type changes.
This will number SOP from concatenated instances with the same instance
number.
Non-WSI DICOM instances are renumbered only if absolutely necessary (i.e.
if a WSI received a instance number that was previously allocated to
non-WSI DICOM).
"""
if not self._dicom_wsi_ref_list and not self._other_dicom_ref_list:
return
instance_number = 1
if self._dicom_wsi_ref_list: # iterate over WSI instances
# sort WSI DICOM instances first by the width of the instance.
self._dicom_wsi_ref_list.sort(
reverse=True, key=self._get_dicom_ref_pixel_area
)
# next sort the DICOM by image type. Python sorting is in place
# i.e. relative position is preserved
self._dicom_wsi_ref_list.sort(key=_wsi_image_type_sort_key)
prior_ref = self._dicom_wsi_ref_list[0]
# Now renumber the instances. Instance number is incremented if
# width or image type changes.
prior_key = (prior_ref.image_type, prior_ref.total_pixel_matrix_columns)
for ref in self._dicom_wsi_ref_list:
test_key = (ref.image_type, ref.total_pixel_matrix_columns)
if test_key != prior_key:
instance_number += 1
prior_key = test_key
# store the tuples instance number in the dict so it can be looked up.
self._instance_number_dict[_dcmref_instance_key(ref)] = instance_number
# Iterate over non-WSI DICOM
if self._other_dicom_ref_list:
# Sort these DICOM by instance number, smallest to largest.
self._other_dicom_ref_list.sort(key=_other_instance_number_sort_key)
mapped_instance = None
for ref in self._other_dicom_ref_list:
# Get the instance number previously assigned to the DICOM.
# If it doesn't have one thats ok. Don't assign anything to DICOM.
# Instance numbers are not technically required.
try:
ref_instance_num = int(ref.instance_number)
except ValueError: # if instance_number is not set do not set.
self._instance_number_dict[_dcmref_instance_key(ref)] = None
continue
# if instance number is set then determine if we are seeing a new one
# or mapping one we have seen
if ref_instance_num != mapped_instance: # if it's a new number and its
mapped_instance = ref_instance_num # bigger than what we are
if ref_instance_num > instance_number: # mapping use the new value
instance_number = ref_instance_num # instances sorted sml -> lrg
else:
instance_number += 1 # otherwise increment the instance count
# Assign the non-WSI instance its instance number.
self._instance_number_dict[_dcmref_instance_key(ref)] = instance_number