iraemmBrowser.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import os
  2. import unittest
  3. from __main__ import vtk, qt, ctk, slicer
  4. from slicer.ScriptedLoadableModule import *
  5. import slicerNetwork
  6. import loadDicom
  7. import json
  8. import datetime
  9. #
  10. # labkeySlicerPythonExtension
  11. #
  12. class iraemmBrowser(ScriptedLoadableModule):
  13. """Uses ScriptedLoadableModule base class, available at:
  14. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  15. """
  16. def __init__(self, parent):
  17. ScriptedLoadableModule.__init__(self, parent)
  18. self.parent.title = "irAEMM Browser" # TODO make this more human readable by adding spaces
  19. self.parent.categories = ["LabKey"]
  20. self.parent.dependencies = []
  21. self.parent.contributors = ["Andrej Studen (UL/FMF)"] # replace with "Firstname Lastname (Organization)"
  22. self.parent.helpText = """
  23. Interface to irAEMM files in LabKey
  24. """
  25. self.parent.acknowledgementText = """
  26. Developed within the medical physics research programme of the Slovenian research agency.
  27. """ # replace with organization, grant and thanks.
  28. #
  29. # labkeySlicerPythonExtensionWidget
  30. #
  31. class iraemmBrowserWidget(ScriptedLoadableModuleWidget):
  32. """Uses ScriptedLoadableModuleWidget base class, available at:
  33. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  34. """
  35. def setup(self):
  36. print("Setting up iraemmBrowserWidget")
  37. ScriptedLoadableModuleWidget.setup(self)
  38. # Instantiate and connect widgets ...
  39. self.network=slicerNetwork.labkeyURIHandler()
  40. fconfig=os.path.join(os.path.expanduser('~'),'.labkey','network.json')
  41. self.network.parseConfig(fconfig)
  42. self.network.initRemote()
  43. self.project="iPNUMMretro/Study"
  44. self.dataset="Imaging"
  45. self.reviewDataset="ImageReview"
  46. self.logic=iraemmBrowserLogic(self)
  47. ds=self.network.filterDataset(self.project,self.dataset,[])
  48. ids=[row['PatientId'] for row in ds['rows']]
  49. ids=list(set(ids))
  50. #
  51. # Setup Area
  52. #
  53. setupCollapsibleButton = ctk.ctkCollapsibleButton()
  54. setupCollapsibleButton.text = "Setup"
  55. self.layout.addWidget(setupCollapsibleButton)
  56. setupFormLayout = qt.QFormLayout(setupCollapsibleButton)
  57. self.ctField=qt.QLabel("ctResampled")
  58. setupFormLayout.addRow("Data field (CT):",self.ctField)
  59. self.petField=qt.QLabel("petResampled")
  60. setupFormLayout.addRow("Data field (PET):",self.petField)
  61. self.segmentationField=qt.QLabel("Segmentation")
  62. setupFormLayout.addRow("Data field (Segmentation):",self.segmentationField)
  63. #
  64. # Patienrs Area
  65. #
  66. patientsCollapsibleButton = ctk.ctkCollapsibleButton()
  67. patientsCollapsibleButton.text = "Patients"
  68. self.layout.addWidget(patientsCollapsibleButton)
  69. patientsFormLayout = qt.QFormLayout(patientsCollapsibleButton)
  70. self.patientList=qt.QComboBox()
  71. for id in ids:
  72. self.patientList.addItem(id)
  73. self.patientList.currentIndexChanged.connect(self.onPatientListChanged)
  74. patientsFormLayout.addRow("Patient:",self.patientList)
  75. self.visitList=qt.QComboBox()
  76. self.visitList.currentIndexChanged.connect(self.onVisitListChanged)
  77. patientsFormLayout.addRow("Visit:",self.visitList)
  78. self.ctCode=qt.QLabel("ctCode")
  79. patientsFormLayout.addRow("CT:",self.ctCode)
  80. self.petCode=qt.QLabel("petCode")
  81. patientsFormLayout.addRow("PET:",self.petCode)
  82. self.segmentationCode=qt.QLabel("segmentationCode")
  83. patientsFormLayout.addRow("Segmentation",self.segmentationCode)
  84. self.patientLoad=qt.QPushButton("Load")
  85. self.patientLoad.clicked.connect(self.onPatientLoadButtonClicked)
  86. patientsFormLayout.addRow("Load patient",self.patientLoad)
  87. self.patientClear=qt.QPushButton("Clear")
  88. self.patientClear.clicked.connect(self.onPatientClearButtonClicked)
  89. patientsFormLayout.addRow("Clear patient",self.patientClear)
  90. self.keepCached=qt.QCheckBox("keep Cached")
  91. self.keepCached.setChecked(1)
  92. patientsFormLayout.addRow("Keep cached",self.keepCached)
  93. #set to a defined state
  94. self.onPatientListChanged(0)
  95. #
  96. # Review Area
  97. #
  98. reviewCollapsibleButton = ctk.ctkCollapsibleButton()
  99. reviewCollapsibleButton.text = "Review"
  100. self.layout.addWidget(reviewCollapsibleButton)
  101. reviewFormLayout = qt.QFormLayout(reviewCollapsibleButton)
  102. self.reviewResult=qt.QComboBox()
  103. reviewFormLayout.addRow("What do you think about the segmentation:",\
  104. self.reviewResult)
  105. self.reviewResult.addItem("Excellent")
  106. self.reviewResult.addItem("Minor deficiencies")
  107. self.reviewResult.addItem("Major deficiencies")
  108. self.reviewResult.addItem("Unusable")
  109. self.reviewComment=qt.QLineEdit("this is a test")
  110. reviewFormLayout.addRow("Comments (optional)",\
  111. self.reviewComment)
  112. self.submitReviewButton=qt.QPushButton("Submit")
  113. reviewFormLayout.addRow("Submit to database",\
  114. self.submitReviewButton)
  115. self.submitReviewButton.clicked.connect(self.onSubmitReviewButtonClicked)
  116. def onPatientListChanged(self,i):
  117. idFilter={'variable':'PatientId','value':self.patientList.currentText,'oper':'eq'}
  118. ds=self.network.filterDataset(self.project,self.dataset, [idFilter])
  119. seq=[int(row['SequenceNum']) for row in ds['rows']]
  120. self.visitList.clear()
  121. for s in seq:
  122. self.visitList.addItem("Visit "+str(s))
  123. self.onVisitListChanged(0)
  124. def onVisitListChanged(self,i):
  125. try:
  126. s=self.visitList.currentText.split(' ')[1]
  127. except IndexError:
  128. return
  129. print("Visit: Selected item: {}->{}".format(i,s))
  130. idFilter={'variable':'PatientId',\
  131. 'value':self.patientList.currentText,'oper':'eq'}
  132. sFilter={'variable':'SequenceNum','value':s,'oper':'eq'}
  133. ds=self.network.filterDataset(self.project,self.dataset,[idFilter,sFilter])
  134. if not len(ds['rows'])==1:
  135. print("Found incorrect number {} of matches for [{}]/[{}]".\
  136. format(len(ds['rows']),\
  137. self.patientList.currentText,s))
  138. row=ds['rows'][0]
  139. #copy row properties for data access
  140. self.currentRow=row
  141. self.petCode.setText(row[self.petField.text])
  142. self.ctCode.setText(row[self.ctField.text])
  143. self.segmentationCode.setText(row[self.segmentationField.text])
  144. def onPatientLoadButtonClicked(self):
  145. print("Load")
  146. #delegate loading to logic
  147. #try:
  148. self.logic.loadImage(self.currentRow,self.keepCached.isChecked())
  149. #except AttributeError:
  150. # print("Missing current row")
  151. # return
  152. def onSubmitReviewButtonClicked(self):
  153. print("Submit")
  154. print("Selected review:{}/{}".format(self.reviewResult.currentIndex,
  155. self.reviewResult.currentText))
  156. print("Comment:{}".format(self.reviewComment))
  157. self.logic.submitReview(self.currentRow,\
  158. self.reviewResult.currentIndex,\
  159. self.reviewComment.text)
  160. def onPatientClearButtonClicked(self):
  161. self.logic.clearVolumesAndSegmentations()
  162. def cleanup(self):
  163. pass
  164. #
  165. # irAEMMBrowserLogic
  166. #
  167. class iraemmBrowserLogic(ScriptedLoadableModuleLogic):
  168. """This class should implement all the actual
  169. computation done by your module. The interface
  170. should be such that other python code can import
  171. this class and make use of the functionality without
  172. requiring an instance of the Widget.
  173. Uses ScriptedLoadableModuleLogic base class, available at:
  174. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  175. """
  176. def __init__(self,parent=None):
  177. ScriptedLoadableModuleLogic.__init__(self, parent)
  178. if not parent==None:
  179. #assume parent has the network set up
  180. self.parent=parent
  181. self.net=parent.network
  182. self.project=parent.project
  183. def setLabkeyInterface(self,net):
  184. #additional way of setting the labkey network interface
  185. #if no parent was provided in logic initialization (stand-alone mode)
  186. self.net=net
  187. def setLabkeyProject(self,project):
  188. self.project=project
  189. def loadImage(self,row,keepCached):
  190. #fields={'ctResampled':True,'petResampled':False}
  191. fields={"CT":self.parent.ctField.text,\
  192. "PET":self.parent.petField.text,\
  193. "Segmentation":self.parent.segmentationField.text}
  194. relativePaths={x:self.project+'/@files/preprocessedImages/'\
  195. +row['patientCode']+'/'+row['visitCode']+'/'+row[y]\
  196. for (x,y) in fields.items()}
  197. volumeNode={}
  198. for f in relativePaths:
  199. p=relativePaths[f]
  200. labkeyPath=self.net.GetLabkeyPathFromRelativePath(p)
  201. rp=self.net.head(labkeyPath)
  202. if not rp.code==200:
  203. print("Failed to get {}".format(labkeyPath))
  204. continue
  205. #pushes it to background
  206. properties={}
  207. #make sure segmentation gets loaded as a labelmap
  208. if f=="Segmentation":
  209. properties["labelmap"]=1
  210. volumeNode[f]=self.net.loadNode(p,'VolumeFile',\
  211. properties=properties,returnNode=True,keepCached=keepCached)
  212. slicer.util.setSliceViewerLayers(background=volumeNode['CT'],\
  213. foreground=volumeNode['PET'],foregroundOpacity=0.5,fit=True)
  214. def clearVolumesAndSegmentations(self):
  215. nodes=slicer.util.getNodesByClass("vtkMRMLVolumeNode")
  216. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationNode"))
  217. res=[slicer.mrmlScene.RemoveNode(f) for f in nodes]
  218. def submitReview(self,currentRow,idx,comment):
  219. row={}
  220. fields=['PatientId','SequenceNum']
  221. #see if we have to update or insert
  222. filters=[]
  223. for f in fields:
  224. filters.append({'variable':f,'value':str(currentRow[f]),'oper':'eq'})
  225. ds=self.net.filterDataset(self.parent.project,\
  226. self.parent.reviewDataset,filters)
  227. mode='insert'
  228. if len(ds['rows'])>0:
  229. row=ds['rows'][0]
  230. mode='update'
  231. else:
  232. for f in fields:
  233. row[f]=currentRow[f]
  234. row['reviewResult']=idx+1 #labkey has 1-based arrays
  235. row['reviewComment']=comment
  236. row['Date']=datetime.datetime.now().ctime()
  237. ds=self.net.modifyDataset(mode,self.parent.project,\
  238. self.parent.reviewDataset,[row])
  239. print("review submitted")
  240. class irAEMMBrowserTest(ScriptedLoadableModuleTest):
  241. """
  242. This is the test case for your scripted module.
  243. Uses ScriptedLoadableModuleTest base class, available at:
  244. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  245. """
  246. def setUp(self):
  247. """ Do whatever is needed to reset the state - typically a scene clear will be enough.
  248. """
  249. slicer.mrmlScene.Clear(0)
  250. def runTest(self):
  251. """Run as few or as many tests as needed here.
  252. """
  253. self.setUp()
  254. self.test_irAEMMBrowser()
  255. def test_irAEMMBrowser(self):
  256. """ Ideally you should have several levels of tests. At the lowest level
  257. tests sould exercise the functionality of the logic with different inputs
  258. (both valid and invalid). At higher levels your tests should emulate the
  259. way the user would interact with your code and confirm that it still works
  260. the way you intended.
  261. One of the most important features of the tests is that it should alert other
  262. developers when their changes will have an impact on the behavior of your
  263. module. For example, if a developer removes a feature that you depend on,
  264. your test should break so they know that the feature is needed.
  265. """
  266. self.delayDisplay("Starting the test")
  267. #
  268. # first, get some data
  269. #