imageBrowser.py 31 KB

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