imageBrowser.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. def addInfoSection(self):
  51. #a python overview of json settings
  52. infoCollapsibleButton = ctk.ctkCollapsibleButton()
  53. infoCollapsibleButton.text = "Info"
  54. self.layout.addWidget(infoCollapsibleButton)
  55. infoLayout = qt.QFormLayout(infoCollapsibleButton)
  56. self.participantField=qt.QLabel("PatientId")
  57. infoLayout.addRow("Participant field:",self.participantField)
  58. self.ctField=qt.QLabel("ctResampled")
  59. infoLayout.addRow("Data field (CT):",self.ctField)
  60. self.petField=qt.QLabel("petResampled")
  61. infoLayout.addRow("Data field (PET):",self.petField)
  62. self.userField=qt.QLabel("Loading")
  63. infoLayout.addRow("User",self.userField)
  64. self.idField=qt.QLabel("Loading")
  65. infoLayout.addRow("ID",self.idField)
  66. #Add logic at some point
  67. #self.logic=imageBrowserLogic(self)
  68. def updatePatientList(self,ids):
  69. self.patientList.clear()
  70. for id in ids:
  71. self.patientList.addItem(id)
  72. def addPatientsSelector(self):
  73. #
  74. # Patients Area
  75. #
  76. patientsCollapsibleButton = ctk.ctkCollapsibleButton()
  77. patientsCollapsibleButton.text = "Patients"
  78. #don't add it yet
  79. self.layout.addWidget(patientsCollapsibleButton)
  80. patientsFormLayout = qt.QFormLayout(patientsCollapsibleButton)
  81. self.patientList=qt.QComboBox()
  82. self.patientList.currentIndexChanged.connect(self.onPatientListChanged)
  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. self.patientSave=qt.QPushButton("Save")
  95. self.patientSave.clicked.connect(self.onPatientSaveButtonClicked)
  96. patientsFormLayout.addRow("Save segmentation",self.patientSave)
  97. self.patientClear=qt.QPushButton("Clear")
  98. self.patientClear.clicked.connect(self.onPatientClearButtonClicked)
  99. patientsFormLayout.addRow("Clear patient",self.patientClear)
  100. self.keepCached=qt.QCheckBox("keep Cached")
  101. self.keepCached.setChecked(1)
  102. patientsFormLayout.addRow("Keep cached",self.keepCached)
  103. def addSetupSection(self):
  104. setupCollapsibleButton = ctk.ctkCollapsibleButton()
  105. setupCollapsibleButton.text = "Setup"
  106. self.layout.addWidget(setupCollapsibleButton)
  107. #Form layout (maybe one can think of more intuitive layouts)
  108. setupFormLayout = qt.QFormLayout(setupCollapsibleButton)
  109. self.serverList=qt.QComboBox()
  110. self.serverList.addItem('<Select>')
  111. self.serverList.addItem("astuden")
  112. self.serverList.addItem("adoma")
  113. self.serverList.addItem("kzevnik")
  114. self.serverList.currentIndexChanged.connect(self.onServerListChanged)
  115. setupFormLayout.addRow("Select user:",self.serverList)
  116. self.setupList=qt.QComboBox()
  117. self.setupList.addItem('<Select>')
  118. self.setupList.addItem("limfomiPET_iBrowser.json")
  119. self.setupList.currentIndexChanged.connect(self.onSetupListChanged)
  120. setupFormLayout.addRow("Setup:",self.setupList)
  121. def addReviewSection(self):
  122. #
  123. # Review Area
  124. #
  125. reviewCollapsibleButton = ctk.ctkCollapsibleButton()
  126. reviewCollapsibleButton.text = "Review"
  127. self.layout.addWidget(reviewCollapsibleButton)
  128. self.reviewBoxLayout = qt.QVBoxLayout(reviewCollapsibleButton)
  129. self.reviewFormLayout = qt.QFormLayout()
  130. self.reviewSegment=qt.QComboBox()
  131. self.reviewSegment.currentIndexChanged.connect(\
  132. self.onReviewSegmentChanged)
  133. self.reviewFormLayout.addRow("Selected region:",self.reviewSegment)
  134. self.reviewResult=qt.QComboBox()
  135. sLabel="What do you think about the segmentation:"
  136. self.reviewFormLayout.addRow(sLabel,self.reviewResult)
  137. reviewOptions=['Select','Excellent','Minor deficiencies',\
  138. 'Major deficiencies','Unusable']
  139. for opt in reviewOptions:
  140. self.reviewResult.addItem(opt)
  141. self.aeResult=qt.QComboBox()
  142. aeLabel="Is organ suffering from adverse effect?"
  143. self.reviewFormLayout.addRow(aeLabel,self.aeResult)
  144. aeOptions=['Select','Yes','No']
  145. for opt in aeOptions:
  146. self.aeResult.addItem(opt)
  147. #self.aeResult.setCurrentIndex(0)
  148. self.updateReview=qt.QPushButton("Save")
  149. saLabel="Save segmentation and AE decision for current segment"
  150. self.reviewFormLayout.addRow(saLabel,self.updateReview)
  151. self.updateReview.clicked.connect(self.onUpdateReviewButtonClicked)
  152. self.reviewBoxLayout.addLayout(self.reviewFormLayout)
  153. submitFrame=qt.QGroupBox("Submit data")
  154. self.submitFormLayout=qt.QFormLayout()
  155. self.reviewComment=qt.QTextEdit("this is a test")
  156. self.submitFormLayout.addRow("Comments (optional)",self.reviewComment)
  157. self.submitReviewButton=qt.QPushButton("Submit")
  158. self.submitFormLayout.addRow("Submit to database",\
  159. self.submitReviewButton)
  160. self.submitReviewButton.clicked.connect(\
  161. self.onSubmitReviewButtonClicked)
  162. submitFrame.setLayout(self.submitFormLayout)
  163. submitFrame.setFlat(1)
  164. #submitFrame.setFrameShape(qt.QFrame.StyledPanel)
  165. #submitFrame.setFrameShadow(qt.QFrame.Sunken)
  166. submitFrame.setStyleSheet("background-color:rgba(220,215,180,45)")
  167. self.reviewBoxLayout.addWidget(submitFrame)
  168. def addSegmentEditor(self):
  169. editorCollapsibleButton = ctk.ctkCollapsibleButton()
  170. editorCollapsibleButton.text = "Segment Editor"
  171. self.layout.addWidget(editorCollapsibleButton)
  172. hLayout=qt.QVBoxLayout(editorCollapsibleButton)
  173. self.segmentEditorWidget=slicer.qMRMLSegmentEditorWidget()
  174. hLayout.addWidget(self.segmentEditorWidget)
  175. self.segmentEditorWidget.setMRMLScene(slicer.mrmlScene)
  176. segEditorNode=slicer.vtkMRMLSegmentEditorNode()
  177. slicer.mrmlScene.AddNode(segEditorNode)
  178. self.segmentEditorWidget.setMRMLSegmentEditorNode(segEditorNode)
  179. def onSetupListChanged(self,i):
  180. status=self.logic.setConfig(self.setupList.currentText)
  181. try:
  182. if status['error']=='FILE NOT FOUND':
  183. print('File {} not found.'.format(self.setupList.currentText))
  184. return
  185. except KeyError:
  186. pass
  187. self.updatePatientList(status['ids'])
  188. self.onPatientListChanged(0)
  189. def onServerListChanged(self,i):
  190. status=self.logic.setServer(self.serverList.currentText)
  191. try:
  192. if status['error']=='KEY ERROR':
  193. self.serverList.setStyleSheet('background-color: violet')
  194. if status['error']=='ID ERROR':
  195. self.serverList.setStyleSheet('background-color: red')
  196. return
  197. except KeyError:
  198. pass
  199. self.idField.setText(status['id'])
  200. self.userField.setText(status['displayName'])
  201. self.serverList.setStyleSheet('background-color: green')
  202. def onPatientListChanged(self,i):
  203. idFilter={'variable':'PatientId',
  204. 'value':self.patientList.currentText,
  205. 'oper':'eq'}
  206. ds=self.logic.getDataset(dbFilter=[idFilter])
  207. seq=[int(row['SequenceNum']) for row in ds['rows']]
  208. self.visitList.clear()
  209. for s in seq:
  210. self.visitList.addItem("Visit "+str(s))
  211. self.onVisitListChanged(0)
  212. def onVisitListChanged(self,i):
  213. try:
  214. s=self.visitList.currentText.split(' ')[1]
  215. except IndexError:
  216. return
  217. print("Visit: Selected item: {}->{}".format(i,s))
  218. idFilter={'variable':'PatientId',\
  219. 'value':self.patientList.currentText,'oper':'eq'}
  220. sFilter={'variable':'SequenceNum','value':s,'oper':'eq'}
  221. ds=self.logic.getDataset(dbFilter=[idFilter,sFilter])
  222. if not len(ds['rows'])==1:
  223. print("Found incorrect number {} of matches for [{}]/[{}]".\
  224. format(len(ds['rows']),\
  225. self.patientList.currentText,s))
  226. row=ds['rows'][0]
  227. #copy row properties for data access
  228. self.currentRow=row
  229. self.petCode.setText(row[self.petField.text])
  230. self.ctCode.setText(row[self.ctField.text])
  231. #self.segmentationCode.setText(row[self.segmentationField.text])
  232. def onPatientLoadButtonClicked(self):
  233. print("Load")
  234. #delegate loading to logic
  235. self.logic.loadImages(self.currentRow,self.keepCached.isChecked())
  236. self.logic.loadSegmentation(self.currentRow)
  237. self.setSegmentEditor()
  238. #self.logic.loadReview(self.currentRow)
  239. #self.logic.loadAE(self.currentRow)
  240. #self.onReviewSegmentChanged()
  241. def setSegmentEditor(self):
  242. #use current row to set segment in segment editor
  243. self.segmentEditorWidget.setSegmentationNode(
  244. self.logic.volumeNode['Segmentation'])
  245. self.segmentEditorWidget.setMasterVolumeNode(
  246. self.logic.volumeNode['PET'])
  247. def onReviewSegmentChanged(self):
  248. pass
  249. def onPatientClearButtonClicked(self):
  250. self.logic.clearVolumesAndSegmentations()
  251. def onPatientSaveButtonClicked(self):
  252. self.logic.saveSegmentation()
  253. def cleanup(self):
  254. pass
  255. def loadLibrary(name):
  256. #utility function to load nix library from git
  257. fwrapper=nixModule.getWrapper('nixWrapper.py')
  258. p=pathlib.Path(fwrapper)
  259. sys.path.append(str(p.parent))
  260. import nixWrapper
  261. return nixWrapper.loadLibrary(name)
  262. #
  263. # imageBrowserLogic
  264. #
  265. class imageBrowserLogic(ScriptedLoadableModuleLogic):
  266. """This class should implement all the actual
  267. computation done by your module. The interface
  268. should be such that other python code can import
  269. this class and make use of the functionality without
  270. requiring an instance of the Widget.
  271. Uses ScriptedLoadableModuleLogic base class, available at:
  272. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  273. """
  274. def __init__(self,parent=None):
  275. ScriptedLoadableModuleLogic.__init__(self, parent)
  276. print('imageBrowserLogic loading')
  277. if not parent==None:
  278. #use layout and data from parent widget
  279. self.parent=parent
  280. fhome=os.path.expanduser('~')
  281. fsetup=os.path.join(fhome,'.labkey','setup.json')
  282. try:
  283. with open(fsetup) as f:
  284. self.setup=json.load(f)
  285. except FileNotFoundError:
  286. self.setup={}
  287. try:
  288. pt=self.setup['paths']
  289. except KeyError:
  290. self.setup['paths']={}
  291. lName='labkeyInterface'
  292. loadLibrary(lName)
  293. import labkeyInterface
  294. import labkeyDatabaseBrowser
  295. import labkeyFileBrowser
  296. self.network=labkeyInterface.labkeyInterface()
  297. self.dbBrowser=labkeyDatabaseBrowser
  298. self.fBrowser=labkeyFileBrowser
  299. self.tempDir=os.path.join(os.path.expanduser('~'),'temp')
  300. if not os.path.isdir(self.tempDir):
  301. os.mkdir(self.tempDir)
  302. print('imageBrowserLogic setup complete')
  303. def setServer(self,serverName):
  304. #additional way of setting the labkey network interface
  305. #if no parent was provided in logic initialization (stand-alone mode)
  306. status={}
  307. fileName="NONE"
  308. if serverName=="astuden":
  309. fileName="astuden.json"
  310. if serverName=="adoma":
  311. fileName="adoma.json"
  312. if serverName=="kzevnik":
  313. fileName="kzevnik.json"
  314. if fileName=="NONE":
  315. print("No path was associated with server {}".format(serverName))
  316. status['error']='KEY ERROR'
  317. return status
  318. fconfig=os.path.join(os.path.expanduser('~'),'.labkey',fileName)
  319. self.network.init(fconfig)
  320. self.remoteId=self.network.getUserId()
  321. if self.remoteId==None:
  322. status['error']='ID ERROR'
  323. return status
  324. status['displayName']=self.remoteId['displayName']
  325. status['id']=self.remoteId['id']
  326. #reset db and fb (they are thin classes anyhow)
  327. self.db=self.dbBrowser.labkeyDB(self.network)
  328. self.fb=self.fBrowser.labkeyFileBrowser(self.network)
  329. return status
  330. def setConfig(self,configName):
  331. status={}
  332. fileName=os.path.join(os.path.expanduser('~'),'.labkey',configName)
  333. if not os.path.isfile(fileName):
  334. status['error']='FILE NOT FOUND'
  335. return status
  336. with open(fileName,'r') as f:
  337. self.isetup=json.load(f)
  338. #self.project=self.isetup['project']
  339. #"iPNUMMretro/Study"
  340. #self.schema='study'
  341. #self.dataset=self.isetup['query']
  342. ds=self.getDataset()
  343. ids=[row[self.isetup['participantField']] for row in ds['rows']]
  344. status['ids']=list(set(ids))
  345. return status
  346. def getDataset(self,name="Imaging",dbFilter=[]):
  347. dset=self.isetup['datasets'][name]
  348. project=dset['project']
  349. schema=dset['schema']
  350. query=dset['query']
  351. try:
  352. return self.db.selectRows(project,schema,query, \
  353. dbFilter,dset['view'])
  354. except KeyError:
  355. return self.db.selectRows(project,schema,query,dbFilter)
  356. def loadImage(self,iData):
  357. #unpack iData
  358. idx=iData['idx']
  359. path=iData['path']
  360. keepCached=iData['keepCached']
  361. dset=self.isetup['datasets'][iData['dataset']]
  362. localPath=os.path.join(self.tempDir,path[-1])
  363. if not os.path.isfile(localPath):
  364. #download from server
  365. remotePath=self.fb.formatPathURL(dset['project'],'/'.join(path))
  366. if not self.fb.entryExists(remotePath):
  367. print("Failed to get {}".format(remotePath))
  368. return
  369. self.fb.readFileToFile(remotePath,localPath)
  370. properties={}
  371. filetype='VolumeFile'
  372. #make sure segmentation gets loaded as a labelmap
  373. if idx=="Segmentation":
  374. filetype='SegmentationFile'
  375. #properties["labelmap"]=1
  376. self.volumeNode[idx]=slicer.util.loadNodeFromFile(localPath,
  377. filetype=filetype,properties=properties)
  378. if not keepCached:
  379. os.remove(localPath)
  380. def loadImages(self,row,keepCached):
  381. #fields={'ctResampled':True,'petResampled':False}
  382. fields={"CT":self.parent.ctField.text,\
  383. "PET":self.parent.petField.text}
  384. path=[self.isetup['imageDir'],row['patientCode'],row['visitCode']]
  385. relativePaths={x:path+[row[y]] for (x,y) in fields.items()}
  386. self.volumeNode={}
  387. for f in relativePaths:
  388. iData={'idx':f,'path':relativePaths[f],
  389. 'keepCached':keepCached,'dataset':'Imaging'}
  390. self.loadImage(iData)
  391. #mimic abdominalCT standardized window setting
  392. self.volumeNode['CT'].GetScalarVolumeDisplayNode().\
  393. SetWindowLevel(1400, -500)
  394. #set colormap for PET to PET-Heat (this is a verbatim setting from
  395. #the Volumes->Display->Lookup Table colormap identifier)
  396. self.volumeNode['PET'].GetScalarVolumeDisplayNode().\
  397. SetAndObserveColorNodeID(\
  398. slicer.util.getNode('PET-Heat').GetID())
  399. slicer.util.setSliceViewerLayers(background=self.volumeNode['CT'],\
  400. foreground=self.volumeNode['PET'],foregroundOpacity=0.5,fit=True)
  401. def loadSegmentation(self,row):
  402. userFilter={'variable':'User','value':'{}'.format(self.remoteId['id']),
  403. 'oper':'eq'}
  404. pField=self.isetup['participantField']
  405. idFilter={'variable':pField,'value':row[pField],'oper':'eq'}
  406. visitFilter={'variable':'visitCode','value':row['visitCode'],'oper':'eq'}
  407. ds=self.getDataset(name='SegmentationsMaster',
  408. dbFilter=[idFilter,visitFilter,userFilter])
  409. if len(ds['rows'])>1:
  410. print('Multiple segmentations found!')
  411. return
  412. if len(ds['rows'])==1:
  413. #update self.segmentationEntry
  414. self.segmentationEntry=ds['rows'][0]
  415. self.segmentationEntry['origin']='database'
  416. self.loadSegmentationFromEntry()
  417. return
  418. #create new segmentation
  419. self.createSegmentation(row)
  420. def getSegmentationPath(self):
  421. path=[self.isetup['imageDir'],
  422. self.segmentationEntry['patientCode'],
  423. self.segmentationEntry['visitCode']]
  424. path.append('Segmentations')
  425. return path
  426. def loadSegmentationFromEntry(self):
  427. #compile path
  428. entry=self.segmentationEntry
  429. path=self.getSegmentationPath()
  430. path.append(entry['latestFile'])
  431. iData={'idx':'Segmentation','path':path,
  432. 'keepCached':0,'dataset':'SegmentationsMaster'}
  433. self.loadImage(iData)
  434. def saveSegmentation(self):
  435. #get the latest key by adding an entry to SegmentationList
  436. copyFields=['ParticipantId','patientCode','visitCode','User']
  437. outRow={x:self.segmentationEntry[x] for x in copyFields}
  438. sList=self.isetup['datasets']['SegmentationsList']
  439. resp=self.db.modifyRows('insert',sList['project'],
  440. sList['schema'],sList['query'],[outRow])
  441. encoding=chardet.detect(resp)['encoding']
  442. respJSON=json.loads(resp.decode(encoding))
  443. outRow=respJSON['rows'][0]
  444. #print(outRow)
  445. #construct file name with known key
  446. uName=re.sub(' ','_',self.remoteId['displayName'])
  447. fName='Segmentation_{}-{}_{}_{}.nrrd'.format(
  448. self.segmentationEntry['patientCode'],
  449. self.segmentationEntry['visitCode'],
  450. uName,outRow['Key'])
  451. path=self.getSegmentationPath()
  452. path.append(fName)
  453. self.saveNode(self.volumeNode['Segmentation'],'SegmentationsMaster',path)
  454. #update SegmentationList with know file name
  455. outRow['Segmentation']=fName
  456. self.db.modifyRows('update',sList['project'],
  457. sList['schema'],sList['query'],[outRow])
  458. #update SegmentationsMaster
  459. self.segmentationEntry['latestFile']=fName
  460. self.segmentationEntry['version']=outRow['Key']
  461. des=self.isetup['datasets']['SegmentationsMaster']
  462. op='insert'
  463. if self.segmentationEntry['origin']=='database':
  464. op='update'
  465. self.db.modifyRows(op,des['project'],
  466. des['schema'],des['query'],[self.segmentationEntry])
  467. #since we loaded a version, origin should be set to dataset
  468. self.segmentationEntry['origin']='dataset'
  469. def saveNode(self,node,dataset,path):
  470. fName=path[-1]
  471. localPath=os.path.join(self.tempDir,fName)
  472. slicer.util.saveNode(node,localPath)
  473. dset=self.isetup['datasets'][dataset]
  474. #exclude file name when building directory structure
  475. remotePath=self.fb.buildPathURL(dset['project'],path[:-1])
  476. remotePath+='/'+fName
  477. self.fb.writeFileToFile(localPath,remotePath)
  478. #add entry to segmentation list
  479. def createSegmentation(self,entry):
  480. #create segmentation entry for database update
  481. #note that origin is not set to database
  482. copyFields=['ParticipantId','patientCode','visitCode','SequenceNum']
  483. self.segmentationEntry={x:entry[x] for x in copyFields}
  484. self.segmentationEntry['User']=self.remoteId['id']
  485. self.segmentationEntry['origin']='created'
  486. self.segmentationEntry['version']=-1111
  487. #create a segmentation node
  488. uName=re.sub(' ','_',self.remoteId['displayName'])
  489. segNode=slicer.vtkMRMLSegmentationNode()
  490. self.volumeNode['Segmentation']=segNode
  491. segNode.SetName('Segmentation_{}_{}_{}'.
  492. format(entry['patientCode'],entry['visitCode'],uName))
  493. slicer.mrmlScene.AddNode(segNode)
  494. segNode.CreateDefaultDisplayNodes()
  495. segNode.SetReferenceImageGeometryParameterFromVolumeNode(self.volumeNode['PET'])
  496. segNode.GetSegmentation().AddEmptySegment("Lesion","Lesion")
  497. def clearVolumesAndSegmentations(self):
  498. nodes=slicer.util.getNodesByClass("vtkMRMLVolumeNode")
  499. nodes.extend(slicer.util.getNodesByClass("vtkMRMLSegmentationNode"))
  500. res=[slicer.mrmlScene.RemoveNode(f) for f in nodes]
  501. #self.segmentationNode=None
  502. #self.reviewResult={}
  503. #self.aeList={}
  504. class imageBrowserTest(ScriptedLoadableModuleTest):
  505. """
  506. This is the test case for your scripted module.
  507. Uses ScriptedLoadableModuleTest base class, available at:
  508. https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
  509. """
  510. def setup(self):
  511. """ Do whatever is needed to reset the state - typically a scene clear will be enough.
  512. """
  513. slicer.mrmlScene.Clear(0)
  514. def runTest(self):
  515. """Run as few or as many tests as needed here.
  516. """
  517. self.setUp()
  518. self.test_irAEMMBrowser()
  519. def test_irAEMMBrowser(self):
  520. """ Ideally you should have several levels of tests. At the lowest level
  521. tests sould exercise the functionality of the logic with different inputs
  522. (both valid and invalid). At higher levels your tests should emulate the
  523. way the user would interact with your code and confirm that it still works
  524. the way you intended.
  525. One of the most important features of the tests is that it should alert other
  526. developers when their changes will have an impact on the behavior of your
  527. module. For example, if a developer removes a feature that you depend on,
  528. your test should break so they know that the feature is needed.
  529. """
  530. self.delayDisplay("Starting the test")
  531. #
  532. # first, get some data
  533. #