cardiacSPECT.py 15 KB

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