cardiacSPECT.py 16 KB

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