preprocess.py 7.9 KB

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