preprocess.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. import os
  2. import json
  3. import re
  4. import subprocess
  5. import nibabel
  6. import shutil
  7. import sys
  8. #nothing gets done if you do import
  9. def getPatientLabel(row,participantField='PatientId'):
  10. return row[participantField].replace('/','_')
  11. def getVisitLabel(row):
  12. return 'VISIT_'+str(int(row['SequenceNum']))
  13. def getStudyLabel(row,participantField='PatientId'):
  14. return getPatientLabel(row,participantField)+'-'+getVisitLabel(row)
  15. def runPreprocess_DM(matlab,generalCodes,niftiTools,studyDir):
  16. #run after all directories have been assembled
  17. script="addpath('"+generalCodes+"');"
  18. script+="addpath('"+niftiTools+"');"
  19. script+="preprocess_DM('"+studyDir+"',0,0);"
  20. script+="test;"
  21. script+="quit();"
  22. #outText=subprocess.check_output(["/bin/echo",script])
  23. try:
  24. outText=subprocess.check_output([matlab,"-nojvm","-r",script])
  25. except subprocess.CalledProcessError as e:
  26. print("Failed with:\n{}".format(e.output.decode('utf-8')))
  27. return False
  28. print(outText.decode('utf-8'))
  29. return True
  30. def getDicom(ofb,row,zipDir,rawDir,im,imageSelector,\
  31. participantField='PatientId'):
  32. #Load the dicom zip file and unzips it. If zip file is already at the expected path, it skips the loading step
  33. #Return True for valid outcome and False for troubles in row formating or unzip failures
  34. seriesId=row[imageSelector[im]];
  35. if seriesId=="0":
  36. return False
  37. print("{}: {}".format(im,seriesId))
  38. fname=os.path.join(zipDir,\
  39. getStudyLabel(row,participantField)+'_'+im+".zip");
  40. #copy data from orthanc
  41. if os.path.isfile(fname):
  42. print("Data already loaded. Skipping")
  43. else:
  44. print("Loading data from orthanc")
  45. ofb.getZip('series',seriesId,fname)
  46. #unzip the zipped dicom series
  47. unzipDir=os.path.join(rawDir,im)
  48. if os.path.isdir(unzipDir):
  49. print("Data already unzipped")
  50. return True
  51. try:
  52. os.mkdir(unzipDir)
  53. except FileExistsError:
  54. shutil.rmtree(unzipDir)
  55. try:
  56. outTxt=subprocess.check_output(["unzip","-d",unzipDir,"-xj",fname])
  57. except subprocess.CalledProcessError:
  58. print("unzip failed for {}".format(fname))
  59. return False
  60. return True
  61. def updateRow(db,project,dataset,row,imageResampledField,gzFileNames,\
  62. participantField='PatientId'):
  63. row['patientCode']=getPatientLabel(row,participantField)
  64. row['visitCode']=getVisitLabel(row)
  65. for im in imageResampledField:
  66. row[imageResampledField[im]]=gzFileNames[im]
  67. db.modifyRows('update',project,'study',dataset,[row])
  68. def main(parameterFile):
  69. fhome=os.path.expanduser('~')
  70. with open(os.path.join(fhome,".labkey","setup.json")) as f:
  71. setup=json.load(f)
  72. sys.path.insert(0,setup["paths"]["nixWrapper"])
  73. import nixWrapper
  74. nixWrapper.loadLibrary("labkeyInterface")
  75. import labkeyInterface
  76. import labkeyDatabaseBrowser
  77. import labkeyFileBrowser
  78. nixWrapper.loadLibrary("orthancInterface")
  79. import orthancInterface
  80. import orthancFileBrowser
  81. fconfig=os.path.join(fhome,'.labkey','network.json')
  82. matlab=setup["paths"]["matlab"]
  83. generalCodes=setup["paths"]["generalCodes"]
  84. niftiTools=setup["paths"]["niftiTools"]
  85. net=labkeyInterface.labkeyInterface()
  86. net.init(fconfig)
  87. db=labkeyDatabaseBrowser.labkeyDB(net)
  88. fb=labkeyFileBrowser.labkeyFileBrowser(net)
  89. onet=orthancInterface.orthancInterface()
  90. onet.init(fconfig)
  91. ofb=orthancFileBrowser.orthancFileBrowser(onet)
  92. with open(parameterFile) as f:
  93. pars=json.load(f)
  94. hi=0
  95. project=pars['Database']['project']
  96. dataset=pars['Database']['queryName']
  97. schema=pars['Database']['schemaName']
  98. tempBase=os.path.join(fhome,'temp')
  99. participantField=pars['Database']['participantField']
  100. #all images from database
  101. ds=db.selectRows(project,schema,dataset,[])
  102. imageSelector={"CT":"CT_orthancId","PET":"PETWB_orthancId"}
  103. #output
  104. imageResampledField={"CT":"ctResampled","PET":"petResampled","patientmask":"ROImask"}
  105. #use webdav to transfer file (even though it is localhost)
  106. i=0
  107. for row in ds["rows"]:
  108. #interesting files are processedDir/studyName_CT_notCropped_2mmVoxel.nii
  109. #asn processedDir/studyName_PET_notCropped_2mmVoxel.nii
  110. volumeFileNames={im:\
  111. getStudyLabel(row,participantField)+'_'+im+
  112. '_notCropped_2mmVoxel.nii'\
  113. for im in imageResampledField}
  114. gzFileNames={im:f+".gz" \
  115. for (im,f) in volumeFileNames.items()}
  116. #build/check remote directory structure
  117. remoteDir=fb.buildPathURL(project,['preprocessedImages',\
  118. getPatientLabel(row,participantField),getVisitLabel(row)])
  119. gzRemoteFiles={im:remoteDir+'/'+f\
  120. for (im,f) in gzFileNames.items()}
  121. remoteFilePresent=[fb.entryExists(f)\
  122. for f in gzRemoteFiles.values()]
  123. for f in gzRemoteFiles.values():
  124. print("[{}]: [{}]".format(f,fb.entryExists(f)))
  125. if all(remoteFilePresent):
  126. print("Entry for row done.")
  127. updateRow(db,project,dataset,row,imageResampledField,\
  128. gzFileNames,participantField)
  129. continue
  130. #setup the directory structure for preprocess_DM
  131. studyDir=os.path.join(tempBase,getStudyLabel(row,participantField))
  132. if not os.path.isdir(studyDir):
  133. os.mkdir(studyDir)
  134. rawDir=os.path.join(studyDir,'Raw')
  135. if not os.path.isdir(rawDir):
  136. os.mkdir(rawDir)
  137. zipDir=os.path.join(studyDir,'Zip')
  138. if not os.path.isdir(zipDir):
  139. os.mkdir(zipDir)
  140. processedDir=os.path.join(studyDir,'Processed')
  141. if not os.path.isdir(processedDir):
  142. os.mkdir(processedDir)
  143. #specify local file names with path
  144. volumeFiles={im:os.path.join(processedDir,f)\
  145. for (im,f) in volumeFileNames.items()}
  146. gzFiles={im:f+".gz"\
  147. for (im,f) in volumeFiles.items()}
  148. filesPresent=[os.path.isfile(f) for f in gzFiles.values()]
  149. if not all(filesPresent):
  150. #use imageSelector -> inputs
  151. for im in imageSelector:
  152. #checks if raw files are already loaded
  153. getDicom(ofb,row,zipDir,rawDir,im,imageSelector,\
  154. participantField)
  155. #preprocess and zip
  156. ok=runPreprocess_DM(matlab,generalCodes,niftiTools,studyDir)
  157. if not ok:
  158. shutil.rmtree(studyDir)
  159. continue
  160. for f in volumeFiles.values():
  161. print("Running gzip {}".format(f))
  162. outText=subprocess.check_output(["/bin/gzip",f])
  163. print(outText.decode('utf-8'))
  164. #upload local files to remote
  165. for im in gzFiles:
  166. #for local,remote in zip(gzFiles,gzRemoteFiles):
  167. local=gzFiles[im]
  168. remote=gzRemoteFiles[im]
  169. print("Uploading {}".format(local))
  170. fb.writeFileToFile(local,remote)
  171. #update row and let it know where the processed files are
  172. updateRow(db,project,dataset,row,imageResampledField,gzFileNames,\
  173. participantField)
  174. #cleanup
  175. shutil.rmtree(studyDir)
  176. if i==-1:
  177. break
  178. i=i+1
  179. print("Done")
  180. if __name__ == '__main__':
  181. main(sys.argv[1])