imageBrowser.py 31 KB

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