convertToNRRD.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. import os
  2. import sys
  3. import json
  4. import pathlib
  5. import slicer
  6. import subprocess
  7. import shutil
  8. #for all rows in xconfig[queryName] import dicom and convert to nrrd
  9. def main(configFile):
  10. print('Running with {}'.format(configFile))
  11. with open(configFile) as f:
  12. xconfig=json.load(f)
  13. fsetup=os.path.join(os.path.expanduser('~'),'.labkey','setup.json')
  14. with open(fsetup) as f:
  15. setup=json.load(f)
  16. sys.path.append(setup['paths']['nixWrapper'])
  17. import nixWrapper
  18. nixWrapper.loadLibrary('labkeyInterface')
  19. import labkeyInterface
  20. import labkeyDatabaseBrowser
  21. import labkeyFileBrowser
  22. nixWrapper.loadLibrary('orthancInterface')
  23. import orthancInterface
  24. import orthancDatabaseBrowser
  25. import orthancFileBrowser
  26. #one should be smart to figure this out if pwd is not the same as the directory of the script
  27. pwd=os.path.dirname(os.path.abspath(__file__))
  28. pwdUp=os.path.dirname(pwd)
  29. pythonScripts=os.path.join(pwdUp,'pythonScripts')
  30. sys.path.append(pythonScripts)
  31. import config
  32. import getData
  33. print('Config loaded')
  34. net=labkeyInterface.labkeyInterface()
  35. fnet=os.path.join(os.path.expanduser('~'),'.labkey',xconfig['network'])
  36. net.init(fnet)
  37. r['CT']=
  38. net.getCSRF()
  39. fb=labkeyFileBrowser.labkeyFileBrowser(net)
  40. db=labkeyDatabaseBrowser.labkeyDB(net)
  41. onet=orthancInterface.orthancInterface()
  42. onet.init(fnet)
  43. ofb=orthancFileBrowser.orthancFileBrowser(onet)
  44. odb=orthancDatabaseBrowser.orthancDB(onet)
  45. qFilter=config.getFilter(xconfig)
  46. ds=db.selectRows(xconfig['project'],xconfig['schemaName'],xconfig['queryName'],qFilter)
  47. try:
  48. rows=ds['rows']
  49. except KeyError:
  50. print('No rows returned')
  51. return
  52. for r in rows:
  53. print("Loading {}/{}".format(config.getPatientId(r,xconfig),config.getVisitId(r,xconfig)))
  54. rPath=fb.formatPathURL(xconfig['project'],config.getOutputDir(r,xconfig))
  55. rPath+='/'+config.getNodeName(r,xconfig,'CT')+'.nrrd'
  56. entryDone=fb.entryExists(rPath)
  57. if entryDone:
  58. try:
  59. if not xconfig['recalculate']:
  60. print('Entry done')
  61. continue
  62. except KeyError:
  63. print('Entry done')
  64. continue
  65. print('Forced recalculation')
  66. print('{} available:{}'.format(config.getNodeName(r,xconfig,'CT'),fb.entryExists(rPath)))
  67. #loadPatient into slicer
  68. patient=loadPatient(ofb,r,xconfig)
  69. #convert to nodes
  70. addCT(r,patient,xconfig)
  71. addFrames(r,patient,xconfig)
  72. addDummyInputFunction(r,patient,xconfig)
  73. nodes=slicer.mrmlScene.GetNodesByClass('vtkMRMLScalarVolumeNode')
  74. print('Nodes')
  75. for node in nodes:
  76. print('\t{}'.format(node.GetName()))
  77. storeNode(fb,r,xconfig,node)
  78. nodes=slicer.mrmlScene.GetNodesByClass('vtkMRMLDoubleArrayNode')
  79. print('Nodes (double array)')
  80. for node in nodes:
  81. print('\t{}'.format(node.GetName()))
  82. storeNode(fb,r,xconfig,node)
  83. nodes=slicer.mrmlScene.GetNodesByClass('vtkMRMLTableNode')
  84. print('Nodes (table)')
  85. for node in nodes:
  86. print('\t{}'.format(node.GetName()))
  87. storeNode(fb,r,xconfig,node)
  88. clearNodes(r,xconfig)
  89. #addCT and addFrames fill r['ct'] and r['spect']
  90. db.modifyRows('update',xconfig['project'],xconfig['schemaName'],xconfig['queryName'],[r])
  91. getData.updateStatus(db,r,setup,'convertToNRRD')
  92. def clearNodes(row,xconfig):
  93. nodes=slicer.mrmlScene.GetNodesByClass('vtkMRMLScalarVolumeNode')
  94. nodes1=slicer.mrmlScene.GetNodesByClass('vtkMRMLDoubleArrayNode')
  95. nodes2=slicer.mrmlScene.GetNodesByClass('vtkMRMLTableNode')
  96. for n in nodes1:
  97. nodes.AddItem(n)
  98. for n in nodes2:
  99. nodes.AddItem(n)
  100. res=[slicer.mrmlScene.RemoveNode(f) for f in nodes]
  101. def loadPatient(ofb,r,xconfig):
  102. sys.path.append('../pythonScripts')
  103. import parseDicom
  104. import vtkInterface
  105. pd=parseDicom.parseDicom()
  106. masterPath=downloadAndUnzip(ofb,r,"nmMaster",xconfig)
  107. pd.readMasterDirectory(masterPath,False)
  108. print('Time [{} .. {}]'.format(pd.frame_start,pd.frame_stop))
  109. clearUnzipDir(r,xconfig)
  110. nmPath=downloadAndUnzip(ofb,r,"nmCorrData",xconfig)
  111. frame_data, frame_time, frame_duration, frame_origin, \
  112. frame_pixel_size, frame_orientation=\
  113. pd.readNMDirectory(nmPath,False)
  114. print('Frame time {}'.format(frame_time))
  115. clearUnzipDir(r,xconfig)
  116. ctPath=downloadAndUnzip(ofb,r,"ct",xconfig)
  117. ct_data,ct_origin,ct_pixel_size, \
  118. ct_orientation=pd.readCTDirectory(ctPath,False)
  119. print('CT pixel {}'.format(ct_pixel_size))
  120. clearUnzipDir(r,xconfig)
  121. ct_orientation=vtkInterface.completeOrientation(ct_orientation)
  122. frame_orientation=vtkInterface.completeOrientation(frame_orientation)
  123. ct={'data':ct_data,'origin':ct_origin,'pixel_size':ct_pixel_size,
  124. 'orientation':ct_orientation}
  125. nm={'data':frame_data,'time':frame_time,'duration':frame_duration,
  126. 'origin':frame_origin,'pixel_size':frame_pixel_size,
  127. 'orientation':frame_orientation}
  128. return {'CT':ct,'NM':nm}
  129. print('Done')
  130. def clearUnzipDir(r,xconfig):
  131. import config
  132. zipDir=config.getLocalDir(r,xconfig)
  133. try:
  134. os.mkdir(zipDir)
  135. except FileExistsError:
  136. shutil.rmtree(zipDir)
  137. return zipDir
  138. def downloadAndUnzip(ofb,r,code,xconfig):
  139. import config
  140. pathList=xconfig['tempDir'].split('/')
  141. pathList.insert(0,os.path.expanduser('~'))
  142. tempDir=os.path.join(*pathList)
  143. if not os.path.isdir(tempDir):
  144. print('Creating {}'.format(tempDir))
  145. os.makedirs(tempDir)
  146. orthancId=r[code+'OrthancId']
  147. fileCode='{}_{}'.format(config.getCode(r,xconfig),code)
  148. zipFile=os.path.join(tempDir,fileCode+'.zip')
  149. ofb.getZip('series',orthancId,zipFile)
  150. zipDir=clearUnzipDir(r,xconfig)
  151. try:
  152. outTxt=subprocess.check_output(["unzip","-d",zipDir,"-xj",zipFile])
  153. except subprocess.CalledProcessError:
  154. print("unzip failed for {}".format(zipFile))
  155. return ""
  156. return zipDir
  157. def addCT(r,patient,xconfig):
  158. import config
  159. import vtkInterface
  160. ct=patient['CT']
  161. vtkData=vtkInterface.numpyToVTK(ct['data'],ct['data'].shape)
  162. nodeName=config.getNodeName(r,xconfig,'CT')
  163. addNode(nodeName,vtkData,ct['origin'],ct['pixel_size'],ct['orientation'],0)
  164. r['ct']=f'{nodeName}.nrrd'
  165. def addFrames(r,patient,xconfig):
  166. import vtkInterface
  167. import config
  168. #convert data from numpy.array to vtkImageData
  169. #use time point it
  170. nm=patient['NM']
  171. print("NFrames: {}".format(nm['data'].shape[3]))
  172. for it in range(0,nm['data'].shape[3]):
  173. frame_data=nm['data'][:,:,:,it];
  174. nodeName=config.getNodeName(r,xconfig,'NM',it)
  175. vtkData=vtkInterface.numpyToVTK(frame_data,frame_data.shape)
  176. addNode(nodeName,vtkData,nm['origin'],nm['pixel_size'],nm['orientation'],1)
  177. #last one will be kept
  178. r['spect']=f'{nodeName}.nrrd'
  179. def addNode(nodeName,v,origin,pixel_size,orientation,dataType):
  180. #origin,orientation in lps
  181. #dataType=0 is CT (to background)
  182. #dataType=1 is SPECT, view not adjusted, foreground,
  183. newNode=slicer.vtkMRMLScalarVolumeNode()
  184. newNode.SetName(nodeName)
  185. v.SetOrigin([0,0,0])
  186. v.SetSpacing([1,1,1])
  187. ijkToRAS = vtk.vtkMatrix4x4()
  188. #think how to do this with image orientation
  189. #orientation from lps to ras
  190. rasOrientation=[-orientation[i] if (i%3 < 2) else orientation[i]
  191. for i in range(0,len(orientation))]
  192. #origin from lps to ras
  193. rasOrigin=[-origin[i] if (i%3<2) else origin[i] for i in range(0,len(origin))]
  194. for i in range(0,3):
  195. for j in range(0,3):
  196. ijkToRAS.SetElement(i,j,pixel_size[i]*rasOrientation[3*j+i])
  197. ijkToRAS.SetElement(i,3,rasOrigin[i])
  198. newNode.SetIJKToRASMatrix(ijkToRAS)
  199. newNode.SetAndObserveImageData(v)
  200. slicer.mrmlScene.AddNode(newNode)
  201. def addDummyInputFunction(r,patient,xconfig):
  202. import config
  203. nm=patient['NM']
  204. n=nm['data'].shape[3]
  205. dnsNodeName=config.getNodeName(r,xconfig,'Dummy')
  206. dns = slicer.mrmlScene.GetNodesByClassByName('vtkMRMLDoubleArrayNode',dnsNodeName)
  207. if dns.GetNumberOfItems() == 0:
  208. try:
  209. dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
  210. except AttributeError:
  211. addDummyTable(dnsNodeName,n,nm)
  212. return
  213. else:
  214. dn = dns.GetItemAsObject(0)
  215. dn.SetSize(n)
  216. ft=nm['time']
  217. dt=nm['duration']
  218. for i in range(0,n):
  219. fx=ft[i]
  220. fy=dt[i]
  221. dn.SetValue(i, 0, fx)
  222. dn.SetValue(i, 1, fy)
  223. dn.SetValue(i, 2, 0)
  224. print('{} ({},{})'.format(i,fx,fy))
  225. def addDummyTable(dnsNodeName,n,nm):
  226. #add vtkMRMLTableNodes
  227. dns = slicer.mrmlScene.GetNodesByClassByName('vtkMRMLTableNode',dnsNodeName)
  228. if dns.GetNumberOfItems() == 0:
  229. dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLTableNode())
  230. dn.SetName(dnsNodeName)
  231. else:
  232. dn = dns.GetItemAsObject(0)
  233. dn.RemoveAllColumns()
  234. ft=nm['time']
  235. dt=nm['duration']
  236. tCol=vtk.vtkDoubleArray()
  237. dCol=vtk.vtkDoubleArray()
  238. for i in range(n):
  239. tCol.InsertNextValue(ft[i])
  240. dCol.InsertNextValue(dt[i])
  241. tcol=dn.AddColumn(tCol)
  242. tcol.SetName('time')
  243. dcol=dn.AddColumn(dCol)
  244. dcol.SetName('duration')
  245. def storeNode(fb,row,xconfig,node):
  246. import config
  247. suffix=".nrrd"
  248. isTable=False
  249. if node.__class__.__name__=="vtkMRMLDoubleArrayNode":
  250. suffix=".mcsv"
  251. if node.__class__.__name__=="vtkMRMLTableNode":
  252. suffix=".mcsv"
  253. isTable=True
  254. if (node.__class__.__name__=="vtkMRMLTransformNode" or \
  255. node.__class__.__name__=="vtkMRMLGridTransformNode"):
  256. suffix=".h5"
  257. fileName=node.GetName()+suffix
  258. localPath=os.path.join(config.getLocalDir(row,xconfig),fileName)
  259. if isTable:
  260. storeTable(node,localPath)
  261. else:
  262. slicer.util.saveNode(node,localPath)
  263. print("Stored to: {}".format(localPath))
  264. labkeyPath=fb.buildPathURL(xconfig['project'],config.getPathList(row,xconfig))
  265. print ("Remote: {}".format(labkeyPath))
  266. #checks if exists
  267. remoteFile=labkeyPath+'/'+fileName
  268. fb.writeFileToFile(localPath,remoteFile)
  269. def storeTable(node,filename):
  270. #mimic old vtkMRMLDoubleArray format
  271. table=node.GetTable()
  272. ft=table.GetColumnByName('time')
  273. fd=table.GetColumnByName('duration')
  274. n=ft.GetNumberOfValues()
  275. print(f'Storing {n} values')
  276. with open(filename,'w') as f:
  277. f.write(f'# measurement file {filename}\n')
  278. f.write('# no labels\n')
  279. for i in range(n):
  280. _t=ft.GetTuple1(i)
  281. _d=fd.GetTuple1(i)
  282. print(f'{_t},{_d},0')
  283. f.write(f'{_t},{_d},0\n')
  284. def readPatient(fb,localDir,project,patientId):
  285. rDir=fb.formatPathURL(project,'/'.join([patientId]))
  286. lDir=os.path.join(localDir,patientId)
  287. if not os.path.isdir(lDir):
  288. os.makedirs(lDir)
  289. ok,files=fb.listRemoteDir(rDir)
  290. locFiles=[]
  291. for f in files:
  292. print(f)
  293. p=pathlib.Path(f)
  294. localFile=os.path.join(lDir,p.name)
  295. fb.readFileToFile(f,localFile)
  296. locFiles.append(localFile)
  297. print('Done')
  298. return locFiles
  299. if __name__=='__main__':
  300. main(sys.argv[1])
  301. quit()