Skip to content

Commit

Permalink
PT/RTDOSE metadata to csv
Browse files Browse the repository at this point in the history
  • Loading branch information
Vishwesh4 committed Dec 7, 2021
1 parent 4c8b72c commit 08616a5
Show file tree
Hide file tree
Showing 5 changed files with 28 additions and 17 deletions.
2 changes: 2 additions & 0 deletions imgtools/autopipeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ def process_one_subject(self, subject_id):
counter[modality] = counter[modality]+1
self.output(f"{subject_id}_{counter[modality]}", doses, output_stream)
metadata[f"size_{output_stream}"] = str(doses.GetSize())
metadata[f"metadata_{output_stream}"] = str(doses.get_metadata())
print(subject_id, " SAVED DOSE")
elif modality == "RTSTRUCT":
#For RTSTRUCT, you need image or PT
Expand Down Expand Up @@ -160,6 +161,7 @@ def process_one_subject(self, subject_id):
counter[modality] = counter[modality] + 1
self.output(f"{subject_id}_{counter[modality]}", pet, output_stream)
metadata[f"size_{output_stream}"] = str(pet.GetSize())
metadata[f"metadata_{output_stream}"] = str(pet.get_metadata())
print(subject_id, " SAVED PET")
return {subject_id: metadata}

Expand Down
2 changes: 1 addition & 1 deletion imgtools/modules/dose.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def show_overlay(self,
plt.imshow(dose_arr[slice_number,:,:], cmap=plt.cm.hot, alpha=.4)
return fig

def form_DVH(self):
def get_metadata(self):
'''
Forms Dose-Value Histogram (DVH) from DICOM metadata
{
Expand Down
29 changes: 21 additions & 8 deletions imgtools/modules/pet.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,12 @@ def read_image(path:str,series_id: Optional[str]=None):
return reader.Execute()

class PET(sitk.Image):
def __init__(self, img_pet, df):
def __init__(self, img_pet, df, factor, calc):
super().__init__(img_pet)
self.img_pet = img_pet
self.df = df
self.factor = factor
self.calc = calc

@classmethod
def from_dicom_pet(cls, path,series_id=None,type="SUV"):
Expand All @@ -39,6 +41,7 @@ def from_dicom_pet(cls, path,series_id=None,type="SUV"):
pet = read_image(path,series_id)
path_one = os.path.join(path,os.listdir(path)[0])
df = dcmread(path_one)
calc = False
try:
if type=="SUV":
factor = df.to_json_dict()['70531000']["Value"][0]
Expand All @@ -47,11 +50,12 @@ def from_dicom_pet(cls, path,series_id=None,type="SUV"):
except:
warnings.warn("Scale factor not available in DICOMs. Calculating based on metadata, may contain errors")
factor = cls.calc_factor(df,type)
calc = True
img_pet = sitk.Cast(pet, sitk.sitkFloat32)

#SimpleITK reads some pixel values as negative but with correct value
img_pet = sitk.Abs(img_pet * factor)
return cls(img_pet, df)
return cls(img_pet, df, factor, calc)

def get_metadata(self):
'''
Expand All @@ -62,15 +66,24 @@ def get_metadata(self):
weight (in kg): PatientWeight
half_life (in seconds): RadiopharmaceuticalInformationSequence[0].RadionuclideHalfLife
injected_dose: RadiopharmaceuticalInformationSequence[0].RadionuclideTotalDose
Values_Assumed: True when some values are not available and are assumed for the calculation of SUV factor
factor: factor used for rescaling to bring it to SUV or ACT
}
'''
self.metadata = {}
self.metadata["weight"] = float(self.df.PatientWeight)
self.metadata["scan_time"] = float(self.df.AcquisitionTime) / 1000
self.metadata["injection_time"] = float(self.df.RadiopharmaceuticalInformationSequence[0].RadiopharmaceuticalStartTime) / 1000
self.metadata["half_life"] = float(self.df.RadiopharmaceuticalInformationSequence[0].RadionuclideHalfLife)
self.metadata["injected_dose"] = float(self.df.RadiopharmaceuticalInformationSequence[0].RadionuclideTotalDose)

try:
self.metadata["weight"] = float(self.df.PatientWeight)
except:
pass
try:
self.metadata["scan_time"] = datetime.datetime.strptime(self.df.AcquisitionTime, '%H%M%S.%f')
self.metadata["injection_time"] = datetime.datetime.strptime(self.df.RadiopharmaceuticalInformationSequence[0].RadiopharmaceuticalStartTime, '%H%M%S.%f')
self.metadata["half_life"] = float(self.df.RadiopharmaceuticalInformationSequence[0].RadionuclideHalfLife)
self.metadata["injected_dose"] = float(self.df.RadiopharmaceuticalInformationSequence[0].RadionuclideTotalDose)
except:
pass
self.metadata["factor"] = self.factor
self.metadata["Values_Assumed"] = self.calc
return self.metadata

def resample_pet(self,
Expand Down
4 changes: 3 additions & 1 deletion imgtools/ops/ops.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def __init__(self,

####### GRAPH ##########
# Form the graph
edge_path = self.parent+"/imgtools_{}_edges.csv".format(self.dataset_name)
edge_path = os.path.join(self.parent,f"/imgtools_{self.dataset_name}_edges.csv")
graph = DataGraph(path_crawl=path_crawl,edge_path=edge_path)
print(f"Forming the graph based on the given modalities: {self.modalities}")
self.df_combined = graph.parser(self.modalities)
Expand All @@ -106,6 +106,8 @@ def __init__(self,
modality = colnames.split("_")[0]
if modality in ["PT","CT","RTDOSE"]:
self.df_combined["size_{}".format(output_stream)] = None
if modality!="CT":
self.df_combined["metadata_{}".format(output_stream)] = None
elif modality=="RTSTRUCT":
self.df_combined["roi_names_{}".format(output_stream)] = None

Expand Down
8 changes: 1 addition & 7 deletions tests/test_autopipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,13 +28,7 @@ def test_pipeline(dataset_path,modalities):
pipeline = AutoPipeline(input_path,output_path_mod,modalities,n_jobs=n_jobs)
#Run for different modalities
comp_path = os.path.join(output_path_mod, "dataset.csv")
if n_jobs > 1 or n_jobs == -1: # == Parallel Processing ==
pipeline.run()
elif n_jobs == 1: # == Series (Single-core) Processing ==
subject_ids = pipeline._get_loader_subject_ids()
for subject_id in subject_ids:
pipeline.process_one_subject(subject_id)
pipeline.graph.to_csv(comp_path)
pipeline.run()

#Check if the crawl and edges exist
crawl_path = ("/").join(input_path.split("/")[:-1]) + "/imgtools_" + input_path.split("/")[-1] + ".csv"
Expand Down

0 comments on commit 08616a5

Please sign in to comment.