preprocess.py 7.0 KB

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