cardiacSPECT.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  1. import os
  2. import sys
  3. import unittest
  4. import vtk, qt, ctk, slicer
  5. from slicer.ScriptedLoadableModule import *
  6. import logging
  7. import parseDicom
  8. import vtkInterface as vi
  9. import fileIO
  10. import slicer
  11. import numpy as np
  12. import slicerNetwork
  13. #
  14. # cardiacSPECT
  15. #
  16. class cardiacSPECT(ScriptedLoadableModule):
  17. """Uses ScriptedLoadableModule base class, available at:
  18. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  19. """
  20. def __init__(self, parent):
  21. ScriptedLoadableModule.__init__(self, parent)
  22. parent.title = "Cardiac SPECT"
  23. parent.categories = ["Examples"]
  24. parent.dependencies = []
  25. parent.contributors = ["Andrej Studen (FMF/JSI)"] # replace with "Firstname Lastname (Org)"
  26. parent.helpText = """
  27. Load dynamic cardiac SPECT data to Slicer
  28. """
  29. parent.acknowledgementText = """
  30. This module was developed within the frame of the ARRS sponsored medical
  31. physics research programe to investigate quantitative measurements of cardiac
  32. function using sestamibi-like tracers
  33. """ # replace with organization, grant and thanks.
  34. self.parent.helpText += self.getDefaultModuleDocumentationLink()
  35. self.parent = parent
  36. #
  37. # cardiacSPECTWidget
  38. #
  39. class cardiacSPECTWidget(ScriptedLoadableModuleWidget):
  40. """Uses ScriptedLoadableModuleWidget base class, available at:
  41. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  42. """
  43. def setup(self):
  44. ScriptedLoadableModuleWidget.setup(self)
  45. self.selectRemote=fileIO.remoteFileSelector()
  46. try:
  47. self.network=slicer.modules.labkeySlicerPythonExtensionWidget.network
  48. except:
  49. self.network=slicerNetwork.labkeyURIHandler()
  50. self.logic=cardiacSPECTLogic(self)
  51. self.logic.setURIHandler(self.network)
  52. self.selectRemote.setMaster(self)
  53. # Instantiate and connect widgets ...
  54. dataButton = ctk.ctkCollapsibleButton()
  55. dataButton.text = "Data"
  56. self.layout.addWidget(dataButton)
  57. # Layout within the sample collapsible button
  58. dataFormLayout = qt.QFormLayout(dataButton)
  59. #pathGuess="file://"+os.environ['HOME']+"/SPECT"
  60. pathGuess="labkey://" + "dinamic_spect/%40files/Dinamika%20test2/SPECT_Dinamika_Rekonstruirano"
  61. self.dataPath=qt.QLineEdit(pathGuess)
  62. dataFormLayout.addRow("Data location",self.dataPath)
  63. self.remotePath=qt.QLineEdit();
  64. dataFormLayout.addRow('Remote Path', self.remotePath)
  65. self.remotePath.textChanged.connect(self.onRemotePathTextChanged)
  66. browseButton = qt.QPushButton("Browse local")
  67. browseButton.toolTip="Set file location"
  68. dataFormLayout.addRow("Select local",browseButton)
  69. browseButton.connect('clicked(bool)',self.onBrowseButtonClicked)
  70. browseRemoteButton = qt.QPushButton("Browse remote")
  71. browseRemoteButton.toolTip="Set remote location"
  72. dataFormLayout.addRow("Select remote",browseRemoteButton)
  73. browseRemoteButton.connect('clicked(bool)',self.onRemoteBrowseButtonClicked)
  74. dataLoadButton = qt.QPushButton("Load")
  75. dataLoadButton.toolTip="Load data from DICOM"
  76. dataFormLayout.addRow("Data",dataLoadButton)
  77. dataLoadButton.connect('clicked(bool)',self.onDataLoadButtonClicked)
  78. self.dataLoadButton = dataLoadButton
  79. # Add vertical spacer
  80. self.layout.addStretch(1)
  81. #addFrameButton=qt.QPushButton("Add Frame")
  82. #addFrameButton.toolTip="Add frame to VTK"
  83. #dataFormLayout.addWidget(addFrameButton)
  84. #addFrameButton.connect('clicked(bool)',self.onAddFrameButtonClicked)
  85. #addCTButton=qt.QPushButton("Add CT")
  86. #addCTButton.toolTip="Add CT to VTK"
  87. #dataFormLayout.addWidget(addCTButton)
  88. #addCTButton.connect('clicked(bool)',self.onAddCTButtonClicked)
  89. #
  90. # Parameters Area
  91. #
  92. parametersCollapsibleButton = ctk.ctkCollapsibleButton()
  93. parametersCollapsibleButton.text = "Parameters"
  94. self.layout.addWidget(parametersCollapsibleButton)
  95. # Layout within the dummy collapsible button
  96. parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton)
  97. #
  98. # check box to trigger taking screen shots for later use in tutorials
  99. #
  100. hbox1=qt.QHBoxLayout()
  101. frameLabel = qt.QLabel()
  102. frameLabel.setText("Select frame")
  103. hbox1.addWidget(frameLabel)
  104. self.time_frame_select=qt.QSlider(qt.Qt.Horizontal)
  105. self.time_frame_select.valueChanged.connect(self.onTimeFrameSelect)
  106. #self.time_frame_select.connect('valueChanged()', self.onTimeFrameSelect)
  107. self.time_frame_select.setMinimum(0)
  108. self.time_frame_select.setMaximum(0)
  109. self.time_frame_select.setValue(0)
  110. self.time_frame_select.setTickPosition(qt.QSlider.TicksBelow)
  111. self.time_frame_select.setTickInterval(5)
  112. self.time_frame_select.toolTip = "Select the time frame"
  113. hbox1.addWidget(self.time_frame_select)
  114. parametersFormLayout.addRow(hbox1)
  115. hbox2 = qt.QHBoxLayout()
  116. meanROILabel = qt.QLabel()
  117. meanROILabel.setText("MeanROI")
  118. hbox2.addWidget(meanROILabel)
  119. self.meanROIVolume = qt.QLineEdit()
  120. self.meanROIVolume.setText("testVolume15")
  121. hbox2.addWidget(self.meanROIVolume)
  122. self.meanROISegment = qt.QLineEdit()
  123. self.meanROISegment.setText("Segment_1")
  124. hbox2.addWidget(self.meanROISegment)
  125. computeMeanROI = qt.QPushButton("Compute mean ROI")
  126. computeMeanROI.connect('clicked(bool)',self.onComputeMeanROIClicked)
  127. hbox2.addWidget(computeMeanROI)
  128. self.meanROIResult = qt.QLineEdit()
  129. self.meanROIResult.setText("0")
  130. hbox2.addWidget(self.meanROIResult)
  131. parametersFormLayout.addRow(hbox2)
  132. #row 3
  133. hbox3 = qt.QHBoxLayout()
  134. drawTimePlot=qt.QPushButton("Draw ROI time plot")
  135. drawTimePlot.connect('clicked(bool)',self.onDrawTimePlotClicked)
  136. hbox3.addWidget(drawTimePlot)
  137. parametersFormLayout.addRow(hbox3)
  138. #dataFormLayout.addWidget(hbox)
  139. #row 4
  140. hbox4 = qt.QHBoxLayout()
  141. countSegments=qt.QPushButton("Count segmentation segments")
  142. countSegments.connect('clicked(bool)',self.onCountSegmentsClicked)
  143. hbox4.addWidget(countSegments)
  144. self.countSegmentsDisplay=qt.QLineEdit()
  145. self.countSegmentsDisplay.setText("0")
  146. hbox4.addWidget(self.countSegmentsDisplay)
  147. parametersFormLayout.addRow(hbox4)
  148. #
  149. # Apply Button
  150. #
  151. self.applyButton = qt.QPushButton("Apply")
  152. self.applyButton.toolTip = "Run the algorithm."
  153. self.applyButton.enabled = False
  154. parametersFormLayout.addRow(self.applyButton)
  155. # connections
  156. self.applyButton.connect('clicked(bool)', self.onApplyButton)
  157. #self.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
  158. #self.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.onSelect)
  159. # Add vertical spacer
  160. self.layout.addStretch(1)
  161. self.resetPosition=1
  162. def cleanup(self):
  163. pass
  164. def onApplyButton(self):
  165. pass
  166. #logic = cardiacSPECTLogic()
  167. #imageThreshold = self.imageThresholdSliderWidget.value
  168. def onBrowseButtonClicked(self):
  169. startDir=self.dataPath.text
  170. inputDir=qt.QFileDialog.getExistingDirectory(None,
  171. 'Select DICOM directory',startDir)
  172. self.dataPath.setText("file://"+inputDir)
  173. def onRemoteBrowseButtonClicked(self):
  174. self.selectRemote.show()
  175. def onDataLoadButtonClicked(self):
  176. self.logic.loadData(self)
  177. def onRemotePathTextChanged(self,str):
  178. self.dataPath.setText('labkey://'+str)
  179. def onTimeFrameSelect(self):
  180. it=self.time_frame_select.value
  181. selectionNode = slicer.app.applicationLogic().GetSelectionNode()
  182. print("Propagating CT volume")
  183. node=slicer.mrmlScene.GetFirstNodeByName("testCT")
  184. selectionNode.SetReferenceActiveVolumeID(node.GetID())
  185. if self.resetPosition==1:
  186. self.resetPosition=0
  187. slicer.app.applicationLogic().PropagateVolumeSelection(1)
  188. else:
  189. slicer.app.applicationLogic().PropagateVolumeSelection(0)
  190. print("Propagating SPECT volume")
  191. nodeName='testVolume'+str(it)
  192. node=slicer.mrmlScene.GetFirstNodeByName(nodeName)
  193. selectionNode.SetSecondaryVolumeID(node.GetID())
  194. slicer.app.applicationLogic().PropagateForegroundVolumeSelection(0)
  195. node.GetDisplayNode().SetAndObserveColorNodeID('vtkMRMLColorTableNodeRed')
  196. lm = slicer.app.layoutManager()
  197. sID=['Red','Yellow','Green']
  198. for s in sID:
  199. sliceLogic = lm.sliceWidget(s).sliceLogic()
  200. compositeNode = sliceLogic.GetSliceCompositeNode()
  201. compositeNode.SetForegroundOpacity(0.5)
  202. #make sure the viewer is matched to the volume
  203. print("Done")
  204. #to access sliceLogic (slice control) use
  205. #lcol=slicer.app.layoutManager().mrmlSliceLogics() (vtkCollection)
  206. #vtkMRMLSliceLogic are named by colors (Red,Green,Blue)
  207. def onComputeMeanROIClicked(self):
  208. s=self.logic.meanROI(self.meanROIVolume.text,self.meanROISegment.text)
  209. self.meanROIResult.setText(str(s))
  210. def onDrawTimePlotClicked(self):
  211. n=self.time_frame_select.maximum+1
  212. ft=self.logic.frame_time
  213. #find number of segments
  214. ns = self.logic.countSegments()
  215. #add the chart node
  216. cn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartNode())
  217. for j in range(0,ns):
  218. #add node for data
  219. dn = slicer.mrmlScene.AddNode(slicer.vtkMRMLDoubleArrayNode())
  220. dn.SetName(self.logic.getSegmentName(j))
  221. a = dn.GetArray()
  222. a.SetNumberOfTuples(n)
  223. dt=0;
  224. t0=0;
  225. for i in range(0,n):
  226. vol="testVolume"+str(i)
  227. fx=ft[i]
  228. fy=self.logic.meanROI(vol,j)
  229. dt=2*ft[i]-t0
  230. t0+=dt
  231. a.SetComponent(i, 0, fx)
  232. a.SetComponent(i, 1, fy/dt)
  233. a.SetComponent(i, 2, 0)
  234. print("[{0} at {1:.2f}:{2:.2f}]".format(vol,fx,fy))
  235. #fish the number of the segment
  236. cn.AddArray(self.logic.getSegmentName(j), dn.GetID())
  237. cn.SetProperty('default', 'title', 'ROI time plot')
  238. cn.SetProperty('default', 'xAxisLabel', 'time [ms]')
  239. cn.SetProperty('default', 'yAxisLabel', 'Activity (arb)')
  240. #update the chart node
  241. cvns = slicer.mrmlScene.GetNodesByClass('vtkMRMLChartViewNode')
  242. if cvns.GetNumberOfItems() == 0:
  243. cvn = slicer.mrmlScene.AddNode(slicer.vtkMRMLChartViewNode())
  244. else:
  245. cvn = cvns.GetItemAsObject(0)
  246. cvn.SetChartNodeID(cn.GetID())
  247. def onCountSegmentsClicked(self):
  248. self.countSegmentsDisplay.setText(self.logic.countSegments())
  249. #def onAddFrameButtonClicked(self):
  250. # it=int(self.time_frame_select.text)
  251. # self.logic.addFrame(it)
  252. # def onAddCTButtonClicked(self):
  253. # self.logic.addCT()
  254. #
  255. #
  256. # cardiacSPECTLogic
  257. #
  258. class cardiacSPECTLogic(ScriptedLoadableModuleLogic):
  259. """This class should implement all the actual
  260. computation done by your module. The interface
  261. should be such that other python code can import
  262. this class and make use of the functionality without
  263. requiring an instance of the Widget.
  264. Uses ScriptedLoadableModuleLogic base class, available at:
  265. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  266. """
  267. def __init__(self,parent):
  268. ScriptedLoadableModuleLogic.__init__(self, parent)
  269. self.pd=parseDicom.parseDicomLogic(self)
  270. def setURIHandler(self,net):
  271. self.net=net
  272. self.pd.setURIHandler(net)
  273. def loadData(self,widget):
  274. inputDir=str(widget.dataPath.text)
  275. self.frame_data, self.frame_time, self.frame_origin, \
  276. self.frame_pixel_size, self.frame_orientation=self.pd.read_dynamic_SPECT(inputDir)
  277. self.ct_data,self.ct_origin,self.ct_pixel_size, \
  278. self.ct_orientation=self.pd.read_CT(inputDir)
  279. self.ct_orientation=vi.completeOrientation(self.ct_orientation)
  280. self.frame_orientation=vi.completeOrientation(self.frame_orientation)
  281. self.addCT()
  282. self.addFrames()
  283. widget.time_frame_select.setMaximum(self.frame_data.shape[3]-1)
  284. #additional message via qt
  285. qt.QMessageBox.information(
  286. slicer.util.mainWindow(),
  287. 'Slicer Python','Data loaded')
  288. def addNode(self,nodeName,v, lpsOrigin, pixel_size, lpsOrientation, dataType):
  289. # if dataType=0 it is CT data, which gets propagated to background an is
  290. #used to fit the view field dimensions
  291. # if dataType=1, it is SPECT data, which gets propagated to foreground
  292. #and is not fit; keeping window set from CT
  293. #nodeName='testVolume'+str(it)
  294. newNode=slicer.vtkMRMLScalarVolumeNode()
  295. newNode.SetName(nodeName)
  296. #pixel_size=[0,0,0]
  297. #pixel_size=v.GetSpacing()
  298. #print(pixel_size)
  299. #origin=[0,0,0]
  300. #origin=v.GetOrigin()
  301. v.SetOrigin([0,0,0])
  302. v.SetSpacing([1,1,1])
  303. ijkToRAS = vtk.vtkMatrix4x4()
  304. #think how to do this with image orientation
  305. rasOrientation=[-lpsOrientation[i] if (i%3 < 2) else lpsOrientation[i]
  306. for i in range(0,len(lpsOrientation))]
  307. rasOrigin=[-lpsOrigin[i] if (i%3<2) else lpsOrigin[i] for i in range(0,len(lpsOrigin))]
  308. for i in range(0,3):
  309. for j in range(0,3):
  310. ijkToRAS.SetElement(i,j,pixel_size[i]*rasOrientation[3*j+i])
  311. ijkToRAS.SetElement(i,3,rasOrigin[i])
  312. newNode.SetIJKToRASMatrix(ijkToRAS)
  313. newNode.SetAndObserveImageData(v)
  314. slicer.mrmlScene.AddNode(newNode)
  315. def addFrames(self):
  316. #convert data from numpy.array to vtkImageData
  317. #use time point it
  318. print "NFrames: {}".format(self.frame_data.shape[3])
  319. for it in range(0,self.frame_data.shape[3]):
  320. frame_data=self.frame_data[:,:,:,it];
  321. nodeName='testVolume'+str(it)
  322. self.addNode(nodeName,
  323. vi.numpyToVTK(frame_data,frame_data.shape),
  324. self.frame_origin,
  325. self.frame_pixel_size,
  326. self.frame_orientation,1)
  327. def addCT(self):
  328. nodeName='testCT'
  329. self.addNode(nodeName,
  330. #vi.numpyToVTK3D(self.ct_data,
  331. # self.ct_origin,self.ct_pixel_size),
  332. vi.numpyToVTK(self.ct_data,self.ct_data.shape),
  333. self.ct_origin,self.ct_pixel_size,
  334. self.ct_orientation,0)
  335. def meanROI(self, volName1, i):
  336. s=0
  337. #get the segmentation mask
  338. fNode=slicer.mrmlScene.GetNodesByClass("vtkMRMLSegmentationNode").GetItemAsObject(0)
  339. print "Found segmentation node: {}".format(fNode.GetName())
  340. segNode=slicer.vtkMRMLSegmentationNode.SafeDownCast(fNode)
  341. #no python bindings for vtkSegmentation
  342. #if segNode.GetSegmentation().GetNumberOfSegments()==0 :
  343. # print("No segments available")
  344. # return 0
  345. #edit here to change for more segments
  346. segment=segNode.GetSegmentation().GetNthSegmentID(int(i))
  347. mask = segNode.GetBinaryLabelmapRepresentation(segment)
  348. if mask==None:
  349. print("Segment {} not found".format(segment))
  350. return s
  351. print "Got mask for segment {}".format(segment)
  352. #get mask at (x,y,z)
  353. #mask.GetPointData().GetScalars().GetTuple1(mask.FindPoint([x,y,z]))
  354. #get the image data
  355. dataNode=slicer.mrmlScene.GetFirstNodeByName(volName1)
  356. dataImage=dataNode.GetImageData()
  357. # use IJK2RAS to get global coordinates
  358. ijkToRas = vtk.vtkMatrix4x4()
  359. dataNode.GetIJKToRASMatrix(ijkToRas)
  360. #iterate over volume pixelData
  361. n=dataImage.GetNumberOfPoints()
  362. extent=mask.GetExtent()
  363. fM=vtk.vtkMatrix4x4()
  364. mask.GetWorldToImageMatrix(fM)
  365. for i in range(0,n):
  366. #get global coordinates of point i
  367. [ix,iy,iz]=dataImage.GetPoint(i)
  368. position_ijk=[ix, iy, iz, 1]
  369. #ras are global coordinates (in mm)
  370. position_ras=ijkToRas.MultiplyPoint(position_ijk)
  371. fpos=[int(np.round(x)) for x in fM.MultiplyPoint(position_ras)]
  372. outOfRange=False
  373. for k in range(0,3):
  374. if fpos[k]<extent[2*k] or fpos[k]>extent[2*k+1]:
  375. outOfRange=True
  376. break;
  377. if outOfRange:
  378. continue
  379. #find point in mask with the same global coordinates
  380. maskValue=mask.GetPointData().GetScalars().GetTuple1(mask.ComputePointId(fpos[0:3]))
  381. if maskValue == 0:
  382. continue
  383. #use maskValue to project ROI data
  384. s+=maskValue*dataImage.GetPointData().GetScalars().GetTuple1(i)
  385. return s/n
  386. def countSegments(self):
  387. segNodeList=slicer.mrmlScene.GetNodesByClass("vtkMRMLSegmentationNode")
  388. if segNodeList.GetNumberOfItems()==0:
  389. return 0
  390. fNode=segNodeList.GetItemAsObject(0)
  391. segNode=slicer.vtkMRMLSegmentationNode.SafeDownCast(fNode)
  392. if fNode==None:
  393. return 0
  394. return segNode.GetSegmentation().GetNumberOfSegments()
  395. def getSegmentName(self,i):
  396. segNodeList=slicer.mrmlScene.GetNodesByClass("vtkMRMLSegmentationNode")
  397. if segNodeList.GetNumberOfItems()==0:
  398. return "NONE"
  399. fNode=segNodeList.GetItemAsObject(0)
  400. segNode=slicer.vtkMRMLSegmentationNode.SafeDownCast(fNode)
  401. if fNode==None:
  402. return "NONE"
  403. return segNode.GetSegmentation().GetSegment(segNode.GetSegmentation().GetNthSegmentID(i)).GetName()
  404. class cardiacSPECTTest(ScriptedLoadableModuleTest):
  405. """
  406. This is the test case for your scripted module.
  407. Uses ScriptedLoadableModuleTest base class, available at:
  408. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  409. """
  410. def setUp(self):
  411. """ Do whatever is needed to reset the state - typically a scene clear will be enough.
  412. """
  413. slicer.mrmlScene.Clear(0)
  414. def runTest(self):
  415. """Run as few or as many tests as needed here.
  416. """
  417. self.setUp()
  418. self.test_cardiacSPECT1()
  419. def test_cardiacSPECT1(self):
  420. """ Ideally you should have several levels of tests. At the lowest level
  421. tests should exercise the functionality of the logic with different inputs
  422. (both valid and invalid). At higher levels your tests should emulate the
  423. way the user would interact with your code and confirm that it still works
  424. the way you intended.
  425. One of the most important features of the tests is that it should alert other
  426. developers when their changes will have an impact on the behavior of your
  427. module. For example, if a developer removes a feature that you depend on,
  428. your test should break so they know that the feature is needed.
  429. """
  430. self.delayDisplay("Starting the test")
  431. #
  432. # first, get some data
  433. #
  434. self.delayDisplay('Test passed!')