# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3.8.10 64-bit
#     name: python3
# ---

# # Step 1
# ## Getting data ready
#
# This notebook is a quick demonstration of how I would prepare some DICOM data to start looking more into the imaging.
#
# There are some quick checks about what is converted.

# +
"""
Import some useful modules
"""
# !pip install -U git+https://github.com/pyplati/platipy.git
from pathlib import Path
import zipfile

import SimpleITK as sitk

from platipy.dicom.io.crawl import process_dicom_directory

# %matplotlib notebook

# +
"""
First, unzip the archive
"""

with zipfile.ZipFile("./input/data.zip","r") as zip_ref:
    zip_ref.extractall("./input/DICOM")

# +
"""
Let's have a look at what data we have
"""

input_dir = Path("./input/DICOM/")
list(input_dir.glob("**/*.dcm"))
# -

# ### Read and sort the DICOM directory
#
# This function is actually pretty powerful.
#
# It can read in a lot of DICOM data, and matches the StudyUID and SeriesUID which provides a useful way to index imaging.
#
# It also looks for ReferencedSeriesUID, so can link up RT-STRUCT and RT-DOSE files to the respective image.
#
# There's still room for improvement, check out platipy to contribute!

output = process_dicom_directory(
    dicom_directory=input_dir,
    parent_sorting_field='PatientName',
    output_image_name_format='{parent_sorting_data}_{study_uid_index}_{Modality}_{image_desc}_{SeriesNumber}',
    output_structure_name_format='{parent_sorting_data}_{study_uid_index}_{Modality}_{structure_name}',
    output_dose_name_format='{parent_sorting_data}_{study_uid_index}_{DoseSummationType}',
    return_extra=True,
    output_directory='./input/NIfTI',
    output_file_suffix='.nii.gz',
    overwrite_existing_files=False,
    write_to_disk=True,
)

# ### Data investigation
#
# It's usually a good idea to check basic information about the data you create.

# +
"""
How can we check out what we have?
"""

for ptid in output:
    
    print("Processing",ptid)
    
    img_files = output[ptid]["IMAGES"]
    
    if len(img_files) == 1:
        print("  Single image found.")
        
        img = sitk.ReadImage( str(img_files[0]) )
        print("    Pixel Type:",img.GetPixelIDTypeAsString())
        print("    Resolution:",img.GetSpacing())
        print("    Size:      ",img.GetSize())
        print("    Origin:    ",img.GetOrigin())
        print("    Direction: ",img.GetDirection())

# +
"""
How can we check out what we have?
"""

for ptid in output:
    
    print("Processing",ptid)
    
    s_files = output[ptid]["STRUCTURES"]
    
    print(f"  {len(s_files)} structures found:")

    for s_file in s_files:
        
        s_name = s_file.name[26:-7]
        print("    ", s_name)
# -



StarcoderdataJupyterScriptsDedupFiltered