segmentationBrowser.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972
  1. import os
  2. import unittest
  3. from __main__ import vtk, qt, ctk, slicer
  4. from slicer.ScriptedLoadableModule import *
  5. import json
  6. import datetime
  7. import sys
  8. import nixModule
  9. import pathlib
  10. import chardet
  11. import re
  12. import functools
  13. #
  14. # labkeySlicerPythonExtension
  15. #
  16. class segmentationBrowser(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. self.parent.title = "segmentation Browser"
  23. # TODO make this more human readable by adding spaces
  24. self.parent.categories = ["LabKey"]
  25. self.parent.dependencies = []
  26. self.parent.contributors = ["Andrej Studen (UL/FMF)"]
  27. # replace with "Firstname Lastname (Organization)"
  28. self.parent.helpText = """
  29. Interface to stored segmentation files in LabKey
  30. """
  31. self.parent.acknowledgementText = """
  32. Developed within the medical physics research programme
  33. of the Slovenian research agency.
  34. """ # replace with organization, grant and thanks.
  35. #
  36. # labkeySlicerPythonExtensionWidget
  37. #
  38. class segmentationBrowserWidget(ScriptedLoadableModuleWidget):
  39. """Uses ScriptedLoadableModuleWidget base class, available at:
  40. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  41. """
  42. def setup(self):
  43. print("Setting up segmentationBrowserWidget")
  44. ScriptedLoadableModuleWidget.setup(self)
  45. # Instantiate and connect widgets ...
  46. self.logic=segmentationBrowserLogic(self)
  47. self.addInfoSection()
  48. self.addSetupSection()
  49. self.addPatientsSelector()
  50. self.addSegmentViewer()
  51. self.addWindowManipulator()
  52. def addInfoSection(self):
  53. #a python overview of json settings
  54. infoCollapsibleButton = ctk.ctkCollapsibleButton()
  55. infoCollapsibleButton.text = "Info"
  56. self.layout.addWidget(infoCollapsibleButton)
  57. infoLayout = qt.QFormLayout(infoCollapsibleButton)
  58. self.participantField=qt.QLabel("PatientId")
  59. infoLayout.addRow("Participant field:",self.participantField)
  60. self.ctField=qt.QLabel("ctResampled")
  61. infoLayout.addRow("Data field (CT):",self.ctField)
  62. self.petField=qt.QLabel("petResampled")
  63. infoLayout.addRow("Data field (PET):",self.petField)
  64. self.userField=qt.QLabel("Loading")
  65. infoLayout.addRow("User",self.userField)
  66. self.idField=qt.QLabel("Loading")
  67. infoLayout.addRow("ID",self.idField)
  68. #Add logic at some point
  69. #self.logic=segmentationBrowserLogic(self)
  70. def addPatientsSelector(self):
  71. #
  72. # Patients Area
  73. #
  74. patientsCollapsibleButton = ctk.ctkCollapsibleButton()
  75. patientsCollapsibleButton.text = "Patients"
  76. #don't add it yet
  77. self.layout.addWidget(patientsCollapsibleButton)
  78. patientsFormLayout = qt.QFormLayout(patientsCollapsibleButton)
  79. self.patientList=qt.QComboBox()
  80. self.patientList.currentIndexChanged.connect(self.onPatientListChanged)
  81. self.patientList.setEditable(True)
  82. self.patientList.setInsertPolicy(qt.QComboBox.NoInsert)
  83. patientsFormLayout.addRow("Patient:",self.patientList)
  84. self.visitList=qt.QComboBox()
  85. self.visitList.currentIndexChanged.connect(self.onVisitListChanged)
  86. patientsFormLayout.addRow("Visit:",self.visitList)
  87. self.ctCode=qt.QLabel("ctCode")
  88. patientsFormLayout.addRow("CT:",self.ctCode)
  89. self.petCode=qt.QLabel("petCode")
  90. patientsFormLayout.addRow("PET:",self.petCode)
  91. self.patientLoad=qt.QPushButton("Load")
  92. self.patientLoad.clicked.connect(self.onPatientLoadButtonClicked)
  93. patientsFormLayout.addRow("Load patient",self.patientLoad)
  94. #no Save button
  95. #self.patientSave=qt.QPushButton("Save")
  96. #self.patientSave.clicked.connect(self.onPatientSaveButtonClicked)
  97. #patientsFormLayout.addRow("Save segmentation",self.patientSave)
  98. self.patientClear=qt.QPushButton("Clear")
  99. self.patientClear.clicked.connect(self.onPatientClearButtonClicked)
  100. patientsFormLayout.addRow("Clear patient",self.patientClear)
  101. self.keepCached=qt.QCheckBox("keep Cached")
  102. self.keepCached.setChecked(1)
  103. patientsFormLayout.addRow("Keep cached",self.keepCached)
  104. def addSetupSection(self):
  105. setupCollapsibleButton = ctk.ctkCollapsibleButton()
  106. setupCollapsibleButton.text = "Setup"
  107. self.layout.addWidget(setupCollapsibleButton)
  108. #Form layout (maybe one can think of more intuitive layouts)
  109. setupFormLayout = qt.QFormLayout(setupCollapsibleButton)
  110. self.serverList=qt.QComboBox()
  111. self.serverList.addItem('<Select>')
  112. self.serverList.addItem("astuden")
  113. self.serverList.addItem("adoma")
  114. self.serverList.addItem("kzevnik")
  115. self.serverList.currentIndexChanged.connect(self.onServerListChanged)
  116. setupFormLayout.addRow("Select user:",self.serverList)
  117. self.setupList=qt.QComboBox()
  118. self.setupList.addItem('<Select>')
  119. self.setupList.addItem("limfomiPET_iBrowser.json")
  120. self.setupList.addItem("iraemm_iBrowserProspective.json")
  121. self.setupList.addItem("iraemm_iBrowserRetrospective.json")
  122. self.setupList.addItem("ORLPET_iBrowser.json")
  123. self.setupList.currentIndexChanged.connect(self.onSetupListChanged)
  124. setupFormLayout.addRow("Setup:",self.setupList)
  125. def addReviewSection(self):
  126. #
  127. # Review Area (not used, relic)
  128. #
  129. reviewCollapsibleButton = ctk.ctkCollapsibleButton()
  130. reviewCollapsibleButton.text = "Review"
  131. self.layout.addWidget(reviewCollapsibleButton)
  132. self.reviewBoxLayout = qt.QVBoxLayout(reviewCollapsibleButton)
  133. self.reviewFormLayout = qt.QFormLayout()
  134. self.reviewSegment=qt.QComboBox()
  135. self.reviewSegment.currentIndexChanged.connect(\
  136. self.onReviewSegmentChanged)
  137. self.reviewFormLayout.addRow("Selected region:",self.reviewSegment)
  138. self.reviewResult=qt.QComboBox()
  139. sLabel="What do you think about the segmentation:"
  140. self.reviewFormLayout.addRow(sLabel,self.reviewResult)
  141. reviewOptions=['Select','Excellent','Minor deficiencies',\
  142. 'Major deficiencies','Unusable']
  143. for opt in reviewOptions:
  144. self.reviewResult.addItem(opt)
  145. self.aeResult=qt.QComboBox()
  146. aeLabel="Is organ suffering from adverse effect?"
  147. self.reviewFormLayout.addRow(aeLabel,self.aeResult)
  148. aeOptions=['Select','Yes','No']
  149. for opt in aeOptions:
  150. self.aeResult.addItem(opt)
  151. #self.aeResult.setCurrentIndex(0)
  152. self.updateReview=qt.QPushButton("Save")
  153. saLabel="Save segmentation and AE decision for current segment"
  154. self.reviewFormLayout.addRow(saLabel,self.updateReview)
  155. self.updateReview.clicked.connect(self.onUpdateReviewButtonClicked)
  156. self.reviewBoxLayout.addLayout(self.reviewFormLayout)
  157. submitFrame=qt.QGroupBox("Submit data")
  158. self.submitFormLayout=qt.QFormLayout()
  159. self.reviewComment=qt.QTextEdit("this is a test")
  160. self.submitFormLayout.addRow("Comments (optional)",self.reviewComment)
  161. self.submitReviewButton=qt.QPushButton("Submit")
  162. self.submitFormLayout.addRow("Submit to database",\
  163. self.submitReviewButton)
  164. self.submitReviewButton.clicked.connect(\
  165. self.onSubmitReviewButtonClicked)
  166. submitFrame.setLayout(self.submitFormLayout)
  167. submitFrame.setFlat(1)
  168. #submitFrame.setFrameShape(qt.QFrame.StyledPanel)
  169. #submitFrame.setFrameShadow(qt.QFrame.Sunken)
  170. submitFrame.setStyleSheet("background-color:rgba(220,215,180,45)")
  171. self.reviewBoxLayout.addWidget(submitFrame)
  172. def addSegmentViewer(self):
  173. #not used (for review)
  174. editorCollapsibleButton = ctk.ctkCollapsibleButton()
  175. editorCollapsibleButton.text = "Segment Viewer"
  176. self.layout.addWidget(editorCollapsibleButton)
  177. self.vSegViewLayout=qt.QVBoxLayout(editorCollapsibleButton)
  178. segList=' '.join(self.logic.segmentList)
  179. label=qt.QLabel(" {}".format(segList))
  180. self.vSegViewLayout.addWidget(label)
  181. self.segList=[]
  182. def addWindowManipulator(self):
  183. windowManipulatorCollapsibleButton=ctk.ctkCollapsibleButton()
  184. windowManipulatorCollapsibleButton.text="CT Window Manipulator"
  185. self.layout.addWidget(windowManipulatorCollapsibleButton)
  186. hLayout=qt.QHBoxLayout(windowManipulatorCollapsibleButton)
  187. ctWins={'CT:bone':self.onCtBoneButtonClicked,
  188. 'CT:air':self.onCtAirButtonClicked,
  189. 'CT:abdomen':self.onCtAbdomenButtonClicked,
  190. 'CT:brain':self.onCtBrainButtonClicked,
  191. 'CT:lung':self.onCtLungButtonClicked}
  192. for ctWin in ctWins:
  193. ctButton=qt.QPushButton(ctWin)
  194. ctButton.clicked.connect(ctWins[ctWin])
  195. hLayout.addWidget(ctButton)
  196. def onSetupListChanged(self,i):
  197. status=self.logic.setConfig(self.setupList.currentText)
  198. try:
  199. if status['error']=='FILE NOT FOUND':
  200. print('File {} not found.'.format(self.setupList.currentText))
  201. return
  202. except KeyError:
  203. pass
  204. #sort ids
  205. ids=status['ids']
  206. ids.sort()
  207. self.updatePatientList(ids)
  208. self.onPatientListChanged(0)
  209. def onServerListChanged(self,i):
  210. status=self.logic.setServer(self.serverList.currentText)
  211. try:
  212. if status['error']=='KEY ERROR':
  213. self.serverList.setStyleSheet('background-color: violet')
  214. if status['error']=='ID ERROR':
  215. self.serverList.setStyleSheet('background-color: red')
  216. return
  217. except KeyError:
  218. pass
  219. self.idField.setText(status['id'])
  220. self.userField.setText(status['displayName'])
  221. self.serverList.setStyleSheet('background-color: green')
  222. def onPatientListChanged(self,i):
  223. self.visitList.clear()
  224. self.petCode.setText("")
  225. self.ctCode.setText("")
  226. #add potential filters from setup to dbFilter
  227. ds=self.logic.getDataset(dbFilter={'participant':self.patientList.currentText})
  228. visitVar=self.logic.getVarName(var='visitField')
  229. dt=datetime.datetime
  230. #label is a combination of sequence number and date of imaging
  231. try:
  232. seq={row['SequenceNum']:
  233. {'label':row[visitVar],
  234. 'date': dt.strptime(row['studyDate'],'%Y/%m/%d %H:%M:%S')}
  235. for row in ds['rows']}
  236. except TypeError:
  237. #if studyDate is empty, this will return no possible visits
  238. return
  239. #apply lookup to visitVar if available
  240. try:
  241. seq={x:
  242. {'label':ds['lookups'][visitVar][seq[x]['label']],
  243. 'date':seq[x]['date']}
  244. for x in seq}
  245. except KeyError:
  246. pass
  247. #format label
  248. seq={x:'{} ({})'.format(seq[x]['label'],dt.strftime(seq[x]['date'],'%d-%b-%Y'))
  249. for x in seq}
  250. for s in seq:
  251. #onVisitListChanged is called for every addItem
  252. self.visitList.addItem(seq[s],s)
  253. #self.onVisitListChanged(0)
  254. def onVisitListChanged(self,i):
  255. #ignore calls on empty list
  256. if self.visitList.count==0:
  257. return
  258. #get sequence num
  259. s=self.visitList.itemData(i)
  260. print("Visit: SequenceNum:{}, label{}".format(s,self.visitList.currentText))
  261. dbFilter={'participant':self.patientList.currentText,
  262. 'seqNum':s}
  263. ds=self.logic.getDataset(dbFilter=dbFilter)
  264. if not len(ds['rows'])==1:
  265. print("Found incorrect number {} of matches for [{}]/[{}]".\
  266. format(len(ds['rows']),\
  267. self.patientList.currentText,s))
  268. row=ds['rows'][0]
  269. #copy row properties for data access
  270. self.currentRow=row
  271. self.petCode.setText(row[self.petField.text])
  272. self.ctCode.setText(row[self.ctField.text])
  273. #self.segmentationCode.setText(row[self.segmentationField.text])
  274. def updatePatientList(self,ids):
  275. self.patientList.clear()
  276. for id in ids:
  277. self.patientList.addItem(id)
  278. def onPatientLoadButtonClicked(self):
  279. #clear first
  280. self.logic.clearVolumesAndSegmentations()
  281. print("Load")
  282. #delegate loading to logic
  283. self.logic.loadImages(self.currentRow,self.keepCached.isChecked())
  284. self.logic.loadSegmentations(self.currentRow)
  285. self.updateSegmentationViewer(self.logic.segmentationRows)
  286. #self.logic.loadReview(self.currentRow)
  287. #self.logic.loadAE(self.currentRow)
  288. #self.onReviewSegmentChanged()
  289. def generateSegmentationView(self):
  290. s=qt.QHBoxLayout()
  291. nm=qt.QLabel("name")
  292. s.addWidget(nm)
  293. for g in self.logic.segmentList:
  294. t=qt.QCheckBox()
  295. s.addWidget(t)
  296. return s
  297. def setSegmentationViewName(self,s,name):
  298. label=s.itemAt(0).widget()
  299. label.setText(name)
  300. def getWidgetsFromLayout(self,s):
  301. return [s.itemAt(i).widget() for i in range(s.count())]
  302. def hideLayout(self,s):
  303. for w in self.getWidgetsFromLayout(s):
  304. w.hide()
  305. def disconnect(self,s):
  306. for w in self.getWidgetsFromLayout(s)[1:]:
  307. try:
  308. w.stateChanged.disconnect()
  309. except TypeError:
  310. continue
  311. def showLayout(self,s):
  312. for w in self.getWidgetsFromLayout(s):
  313. w.show()
  314. def refreshCallbacks(self,s,entry):
  315. w=self.getWidgetsFromLayout(s)
  316. for i in range(len(self.logic.segmentList)):
  317. w[i+1].stateChanged.connect(functools.partial(self.onSegmentationViewChanged,
  318. latestFile=entry['latestFile'],
  319. segment=self.logic.segmentList[i]))
  320. def getUserMap(self):
  321. users=self.logic.lookups['core:Users']
  322. #print('{}'.format(users))
  323. return users
  324. def updateSegmentationViewer(self,rows):
  325. users=self.getUserMap()
  326. for s in self.segList:
  327. self.hideLayout(s)
  328. self.disconnect(s)
  329. #can't hide a layout
  330. #s.hide()
  331. i=0
  332. for r in rows:
  333. try:
  334. s=self.segList[i]
  335. except IndexError:
  336. #assume we only have to add one (since we iterate sequentially)
  337. self.segList.append(self.generateSegmentationView())
  338. s=self.segList[i]
  339. self.vSegViewLayout.addLayout(s)
  340. self.showLayout(s)
  341. self.setSegmentationViewName(s,users[r['User']])
  342. self.refreshCallbacks(s,r)
  343. i+=1
  344. def onReviewSegmentChanged(self):
  345. pass
  346. def onPatientClearButtonClicked(self):
  347. self.logic.clearVolumesAndSegmentations()
  348. def onPatientSaveButtonClicked(self):
  349. #not used
  350. self.logic.saveSegmentation()
  351. def onCtBoneButtonClicked(self):
  352. self.logic.setWindow('CT:bone')
  353. def onCtAirButtonClicked(self):
  354. self.logic.setWindow('CT:air')
  355. def onCtAbdomenButtonClicked(self):
  356. self.logic.setWindow('CT:abdomen')
  357. def onCtBrainButtonClicked(self):
  358. self.logic.setWindow('CT:brain')
  359. def onCtLungButtonClicked(self):
  360. self.logic.setWindow('CT:lung')
  361. def onSegmentationViewChanged(self,state,latestFile,segment):
  362. print('onSegmentationViewChanged {} {} {} '.format(latestFile,segment,state))
  363. self.logic.toggleSegmentVisibility(latestFile,segment,state>0)
  364. def cleanup(self):
  365. pass
  366. def loadLibrary(name):
  367. #utility function to load nix library from git
  368. fwrapper=nixModule.getWrapper('nixWrapper.py')
  369. p=pathlib.Path(fwrapper)
  370. sys.path.append(str(p.parent))
  371. import nixWrapper
  372. return nixWrapper.loadLibrary(name)
  373. #
  374. # segmentationBrowserLogic
  375. #
  376. class segmentationBrowserLogic(ScriptedLoadableModuleLogic):
  377. """This class should implement all the actual
  378. computation done by your module. The interface
  379. should be such that other python code can import
  380. this class and make use of the functionality without
  381. requiring an instance of the Widget.
  382. Uses ScriptedLoadableModuleLogic base class, available at:
  383. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  384. """
  385. def __init__(self,parent=None):
  386. ScriptedLoadableModuleLogic.__init__(self, parent)
  387. print('segmentationBrowserLogic loading')
  388. if not parent==None:
  389. #use layout and data from parent widget
  390. self.parent=parent
  391. fhome=os.path.expanduser('~')
  392. fsetup=os.path.join(fhome,'.labkey','setup.json')
  393. try:
  394. with open(fsetup) as f:
  395. self.setup=json.load(f)
  396. except FileNotFoundError:
  397. self.setup={}
  398. try:
  399. pt=self.setup['paths']
  400. except KeyError:
  401. self.setup['paths']={}
  402. lName='labkeyInterface'
  403. loadLibrary(lName)
  404. import labkeyInterface
  405. import labkeyDatabaseBrowser
  406. import labkeyFileBrowser
  407. self.network=labkeyInterface.labkeyInterface()
  408. self.dbBrowser=labkeyDatabaseBrowser
  409. self.fBrowser=labkeyFileBrowser
  410. self.tempDir=os.path.join(os.path.expanduser('~'),'temp')
  411. if not os.path.isdir(self.tempDir):
  412. os.mkdir(self.tempDir)
  413. self.lookups={}
  414. self.segmentList=["Liver","Blood","Marrow","Disease","Deauville"]
  415. print('segmentationBrowserLogic setup complete')
  416. def setServer(self,serverName):
  417. #additional way of setting the labkey network interface
  418. #if no parent was provided in logic initialization (stand-alone mode)
  419. status={}
  420. fileName="NONE"
  421. if serverName=="astuden":
  422. fileName="astuden.json"
  423. if serverName=="adoma":
  424. fileName="adoma.json"
  425. if serverName=="kzevnik":
  426. fileName="kzevnik.json"
  427. if fileName=="NONE":
  428. print("No path was associated with server {}".format(serverName))
  429. status['error']='KEY ERROR'
  430. return status
  431. fconfig=os.path.join(os.path.expanduser('~'),'.labkey',fileName)
  432. self.network.init(fconfig)
  433. self.remoteId=self.network.getUserId()
  434. if self.remoteId==None:
  435. status['error']='ID ERROR'
  436. return status
  437. status['displayName']=self.remoteId['displayName']
  438. status['id']=self.remoteId['id']
  439. #reset db and fb (they are thin classes anyhow)
  440. self.db=self.dbBrowser.labkeyDB(self.network)
  441. self.fb=self.fBrowser.labkeyFileBrowser(self.network)
  442. return status
  443. def setConfig(self,configName):
  444. status={}
  445. fileName=os.path.join(os.path.expanduser('~'),'.labkey',configName)
  446. if not os.path.isfile(fileName):
  447. status['error']='FILE NOT FOUND'
  448. return status
  449. with open(fileName,'r') as f:
  450. self.isetup=json.load(f)
  451. #self.project=self.isetup['project']
  452. #"iPNUMMretro/Study"
  453. #self.schema='study'
  454. #self.dataset=self.isetup['query']
  455. #include filters...
  456. ds=self.getDataset()
  457. ids=[row[self.isetup['participantField']] for row in ds['rows']]
  458. status['ids']=list(set(ids))
  459. return status
  460. def getVarName(self,name="Imaging",var="visitField"):
  461. dset=self.isetup['datasets'][name]
  462. defaults={"visitField":"imagingVisitId"}
  463. try:
  464. return dset[var]
  465. except KeyError:
  466. return defaults[var]
  467. def getDataset(self,name="Imaging",dbFilter={}):
  468. dset=self.isetup['datasets'][name]
  469. project=dset['project']
  470. schema=dset['schema']
  471. query=dset['query']
  472. #add default filters
  473. qFilter=[]
  474. try:
  475. for qf in dset['filter']:
  476. v=dset['filter'][qf]
  477. qFilter.append({'variable':qf,'value':v,'oper':'eq'})
  478. except KeyError:
  479. pass
  480. for f in dbFilter:
  481. if f=='participant':
  482. qFilter.append({'variable':self.isetup['participantField'],
  483. 'value':dbFilter[f],'oper':'eq'})
  484. continue
  485. if f=='seqNum':
  486. qFilter.append({'variable':'SequenceNum',
  487. 'value':'{}'.format(dbFilter[f]),
  488. 'oper':'eq'})
  489. continue
  490. qFilter.append({'variable':f,'value':dbFilter[f],'oper':'eq'})
  491. try:
  492. ds=self.db.selectRows(project,schema,query, \
  493. qFilter,dset['view'])
  494. except KeyError:
  495. ds=self.db.selectRows(project,schema,query,qFilter)
  496. #get lookups as well
  497. lookups={}
  498. for f in ds['metaData']['fields']:
  499. try:
  500. lookup=f['lookup']
  501. except KeyError:
  502. continue
  503. var=f['name']
  504. lookupCode='{}:{}'.format(lookup['schema'],lookup['queryName'])
  505. try:
  506. lookups[var]=self.lookups[lookupCode]
  507. except KeyError:
  508. self.lookups[lookupCode]=self.loadLookup(project,lookup)
  509. lookups[var]=self.lookups[lookupCode]
  510. return {'rows':ds['rows'],'lookups':lookups}
  511. def loadLookup(self,project,lookup):
  512. qData={}
  513. key=lookup['keyColumn']
  514. value=lookup['displayColumn']
  515. fSet=self.db.selectRows(project,lookup['schema'],lookup['queryName'],[])
  516. for q in fSet['rows']:
  517. qData[q[key]]=q[value]
  518. return qData
  519. def loadImage(self,iData):
  520. #unpack iData
  521. idx=iData['idx']
  522. path=iData['path']
  523. keepCached=iData['keepCached']
  524. dset=self.isetup['datasets'][iData['dataset']]
  525. localPath=os.path.join(self.tempDir,path[-1])
  526. if not os.path.isfile(localPath):
  527. #download from server
  528. remotePath=self.fb.formatPathURL(dset['project'],'/'.join(path))
  529. if not self.fb.entryExists(remotePath):
  530. print("Failed to get {}".format(remotePath))
  531. return
  532. self.fb.readFileToFile(remotePath,localPath)
  533. properties={}
  534. filetype='VolumeFile'
  535. #make sure segmentation gets loaded as a labelmap
  536. if idx=="Segmentation":
  537. filetype='SegmentationFile'
  538. #properties["labelmap"]=1
  539. try:
  540. volumeIdx=iData['volumeIdx']
  541. except KeyError:
  542. volumeIdx=idx
  543. self.volumeNode[volumeIdx]=slicer.util.loadNodeFromFile(localPath,
  544. filetype=filetype,properties=properties)
  545. if not keepCached:
  546. os.remove(localPath)
  547. def loadImages(self,row,keepCached):
  548. #fields={'ctResampled':True,'petResampled':False}
  549. fields={"CT":self.parent.ctField.text,\
  550. "PET":self.parent.petField.text}
  551. path=[self.isetup['imageDir'],row['patientCode'],row['visitCode']]
  552. relativePaths={x:path+[row[y]] for (x,y) in fields.items()}
  553. self.volumeNode={}
  554. for f in relativePaths:
  555. iData={'idx':f,'path':relativePaths[f],
  556. 'keepCached':keepCached,'dataset':'Imaging'}
  557. self.loadImage(iData)
  558. #mimic abdominalCT standardized window setting
  559. self.volumeNode['CT'].GetScalarVolumeDisplayNode().\
  560. SetAutoWindowLevel(False)
  561. self.volumeNode['CT'].GetScalarVolumeDisplayNode().\
  562. SetWindowLevel(1400, -500)
  563. #set colormap for PET to PET-Heat (this is a verbatim setting from
  564. #the Volumes->Display->Lookup Table colormap identifier)
  565. self.volumeNode['PET'].GetScalarVolumeDisplayNode().\
  566. SetAndObserveColorNodeID(\
  567. slicer.util.getNode('Inferno').GetID())
  568. slicer.util.setSliceViewerLayers(background=self.volumeNode['CT'],\
  569. foreground=self.volumeNode['PET'],foregroundOpacity=0.5,fit=True)
  570. def loadSegmentations(self,row, loadFile=1):
  571. dbFilter={
  572. #'User':'{}'.format(self.remoteId['id']),
  573. 'participant':row[self.isetup['participantField']],
  574. 'visitCode':row['visitCode']}
  575. ds=self.getDataset(name='SegmentationsMaster',
  576. dbFilter=dbFilter)
  577. self.segmentationRows=ds['rows']
  578. if len(self.segmentationRows)<0:
  579. print('No segmentations for {}'.format(dbFilter))
  580. return
  581. for r in self.segmentationRows:
  582. #update self.segmentationEntry
  583. #self.segmentationEntry=ds['rows'][0]
  584. #self.segmentationEntry['origin']='database'
  585. #if loadFile:
  586. self.loadSegmentationFromEntry(r)
  587. #make invisile by default
  588. for s in self.segmentList:
  589. self.toggleSegmentVisibility(r['latestFile'],s,False)
  590. print('load Segmentation: done')
  591. #create new segmentation
  592. #self.createSegmentation(row)
  593. def getSegmentationPath(self,entry):
  594. path=[self.isetup['imageDir'],
  595. entry['patientCode'],
  596. entry['visitCode']]
  597. path.append('Segmentations')
  598. return path
  599. def loadSegmentationFromEntry(self,r):
  600. #compile path
  601. entry=r
  602. path=self.getSegmentationPath(entry)
  603. path.append(entry['latestFile'])
  604. iData={'idx':'Segmentation','path':path,
  605. 'keepCached':0,'dataset':'SegmentationsMaster',
  606. 'volumeIdx':entry['latestFile']}
  607. self.loadImage(iData)
  608. #look for missing segments
  609. return
  610. #skip this
  611. segNode=self.volumeNode['Segmentation']
  612. seg=segNode.GetSegmentation()
  613. segNames=[seg.GetNthSegmentID(i) for i in range(seg.GetNumberOfSegments())]
  614. print('Segments')
  615. try:
  616. segmentList=self.isetup['segmentList']
  617. except KeyError:
  618. segmentList=self.segmentList
  619. for s in segmentList:
  620. if s not in segNames:
  621. seg.AddEmptySegment(s,s)
  622. print(s)
  623. print('Done')
  624. def toggleSegmentVisibility(self,latestFile,segmentId,visible):
  625. segNode=self.volumeNode[latestFile]
  626. if segNode==None:
  627. print('Could not find segNode')
  628. return
  629. seg=segNode.GetSegmentation()
  630. segment=seg.GetSegment(segmentId)
  631. if segment==None:
  632. print('Could not find segment {}'.format(segmentId))
  633. return
  634. segNode.GetDisplayNode().SetSegmentVisibility(segmentId, visible)
  635. def saveSegmentation(self):
  636. #not used
  637. #get the latest key by adding an entry to SegmentationList
  638. copyFields=[self.isetup['participantField'],'patientCode','visitCode','User']
  639. outRow={x:self.segmentationEntry[x] for x in copyFields}
  640. sList=self.isetup['datasets']['SegmentationsList']
  641. resp=self.db.modifyRows('insert',sList['project'],
  642. sList['schema'],sList['query'],[outRow])
  643. encoding=chardet.detect(resp)['encoding']
  644. respJSON=json.loads(resp.decode(encoding))
  645. outRow=respJSON['rows'][0]
  646. #print(outRow)
  647. #construct file name with known key
  648. uName=re.sub(' ','_',self.remoteId['displayName'])
  649. fName='Segmentation_{}-{}_{}_{}.nrrd'.format(
  650. self.segmentationEntry['patientCode'],
  651. self.segmentationEntry['visitCode'],
  652. uName,outRow['Key'])
  653. path=self.getSegmentationPath()
  654. path.append(fName)
  655. self.saveNode(self.volumeNode['Segmentation'],'SegmentationsMaster',path)
  656. #update SegmentationList with know file name
  657. outRow['Segmentation']=fName
  658. self.db.modifyRows('update',sList['project'],
  659. sList['schema'],sList['query'],[outRow])
  660. #update SegmentationsMaster
  661. self.segmentationEntry['latestFile']=fName
  662. self.segmentationEntry['version']=outRow['Key']
  663. des=self.isetup['datasets']['SegmentationsMaster']
  664. op='insert'
  665. if self.segmentationEntry['origin']=='database':
  666. op='update'
  667. print('Saving: mode={}'.format(op))
  668. resp=self.db.modifyRows(op,des['project'],
  669. des['schema'],des['query'],[self.segmentationEntry])
  670. print(resp)
  671. #since we loaded a version, origin should be set to database
  672. self.loadSegmentation(self.segmentationEntry,0)
  673. #self.segmentationEntry['origin']='database'
  674. def saveNode(self,node,dataset,path):
  675. #not used
  676. fName=path[-1]
  677. localPath=os.path.join(self.tempDir,fName)
  678. slicer.util.saveNode(node,localPath)
  679. dset=self.isetup['datasets'][dataset]
  680. #exclude file name when building directory structure
  681. remotePath=self.fb.buildPathURL(dset['project'],path[:-1])
  682. remotePath+='/'+fName
  683. self.fb.writeFileToFile(localPath,remotePath)
  684. #add entry to segmentation list
  685. def createSegmentation(self,entry):
  686. #not used
  687. #create segmentation entry for database update
  688. #note that origin is not set to database
  689. copyFields=[self.isetup['participantField'],'patientCode','visitCode','SequenceNum']
  690. #copyFields=['ParticipantId','patientCode','visitCode','SequenceNum']
  691. self.segmentationEntry={x:entry[x] for x in copyFields}
  692. self.segmentationEntry['User']=self.remoteId['id']
  693. self.segmentationEntry['origin']='created'
  694. self.segmentationEntry['version']=-1111
  695. #create a segmentation node
  696. uName=re.sub(' ','_',self.remoteId['displayName'])
  697. segNode=slicer.vtkMRMLSegmentationNode()
  698. self.volumeNode['Segmentation']=segNode
  699. segNode.SetName('Segmentation_{}_{}_{}'.
  700. format(entry['patientCode'],entry['visitCode'],uName))
  701. slicer.mrmlScene.AddNode(segNode)
  702. segNode.CreateDefaultDisplayNodes()
  703. segNode.SetReferenceImageGeometryParameterFromVolumeNode(self.volumeNode['PET'])
  704. try:
  705. segmentList=self.isetup['segmentList']
  706. except KeyError:
  707. segmentList=self.segmentList
  708. for s in segmentList:
  709. segNode.GetSegmentation().AddEmptySegment(s,s)
  710. def clearVolumesAndSegmentations(self):
  711. nodes=slicer.util.getNodesByClass("vtkMRMLVolumeNode")
  712. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationNode"))
  713. res=[slicer.mrmlScene.RemoveNode(f) for f in nodes]
  714. try:
  715. self.volumeNode.clear()
  716. except AttributeError:
  717. pass
  718. #self.segmentationNode=None
  719. #self.reviewResult={}
  720. #self.aeList={}
  721. def setWindow(self,windowName):
  722. #default
  723. w=1400
  724. l=-500
  725. if windowName=='CT:bone':
  726. w=1000
  727. l=400
  728. if windowName=='CT:air':
  729. w=1000
  730. l=-426
  731. if windowName=='CT:abdomen':
  732. w=350
  733. l=40
  734. if windowName=='CT:brain':
  735. w=100
  736. l=50
  737. if windowName=='CT:lung':
  738. w=1400
  739. l=-500
  740. self.volumeNode['CT'].GetScalarVolumeDisplayNode().\
  741. SetWindowLevel(w,l)
  742. print('setWindow: {} {}/{}'.format(windowName,w,l))
  743. class segmentationBrowserTest(ScriptedLoadableModuleTest):
  744. """
  745. This is the test case for your scripted module.
  746. Uses ScriptedLoadableModuleTest base class, available at:
  747. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  748. """
  749. def setup(self):
  750. """ Do whatever is needed to reset the state - typically a scene clear will be enough.
  751. """
  752. slicer.mrmlScene.Clear(0)
  753. def runTest(self):
  754. """Run as few or as many tests as needed here.
  755. """
  756. self.setUp()
  757. self.test_irAEMMBrowser()
  758. def test_irAEMMBrowser(self):
  759. """ Ideally you should have several levels of tests. At the lowest level
  760. tests sould exercise the functionality of the logic with different inputs
  761. (both valid and invalid). At higher levels your tests should emulate the
  762. way the user would interact with your code and confirm that it still works
  763. the way you intended.
  764. One of the most important features of the tests is that it should alert other
  765. developers when their changes will have an impact on the behavior of your
  766. module. For example, if a developer removes a feature that you depend on,
  767. your test should break so they know that the feature is needed.
  768. """
  769. self.delayDisplay("Starting the test")
  770. #
  771. # first, get some data
  772. #