forked from SlicerProstate/mpReview
-
Notifications
You must be signed in to change notification settings - Fork 1
/
mpReview.py
executable file
·2183 lines (1798 loc) · 87.6 KB
/
mpReview.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import division
import os, json, xml.dom.minidom, string, glob, re, math
import vtk, qt, ctk, slicer
import logging
import CompareVolumes
from Editor import EditorWidget
from EditorLib import EditorLib
import SimpleITK as sitk
import sitkUtils
import datetime
import time
from slicer.ScriptedLoadableModule import *
from mpReviewPreprocessor import mpReviewPreprocessorLogic
from qSlicerMultiVolumeExplorerModuleWidget import qSlicerMultiVolumeExplorerSimplifiedModuleWidget
from qSlicerMultiVolumeExplorerModuleHelper import qSlicerMultiVolumeExplorerModuleHelper as MVHelper
from SlicerDevelopmentToolboxUtils.mixins import ModuleWidgetMixin, ModuleLogicMixin
from SlicerDevelopmentToolboxUtils.buttons import WindowLevelEffectsButton
from SlicerDevelopmentToolboxUtils.helpers import WatchBoxAttribute
from SlicerDevelopmentToolboxUtils.widgets import TargetCreationWidget, XMLBasedInformationWatchBox
from SlicerDevelopmentToolboxUtils.icons import Icons
# DeepLiver
try:
import nrrd
except ImportError, e:
import pip
pip.main(['install', 'pynrrd'])
import nrrd
class mpReview(ScriptedLoadableModule, ModuleWidgetMixin):
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
parent.title = "mpReview"
parent.categories = ["Informatics"]
parent.dependencies = ["SlicerDevelopmentToolbox"]
parent.contributors = ["Andrey Fedorov (SPL)", "Robin Weiss (U. of Chicago)", "Alireza Mehrtash (SPL)",
"Christian Herz (SPL)"]
parent.helpText = """
Multiparametric Image Review (mpReview) module is intended to support review and annotation of multiparametric
image data. The driving use case for the development of this module was review and segmentation of the regions of
interest in prostate cancer multiparametric MRI.
"""
parent.acknowledgementText = """
Supported by NIH U24 CA180918 (PIs Fedorov & Kikinis) and U01CA151261 (PI Fennessy)
""" # replace with organization, grant and thanks.
self.parent = parent
# Add this test to the SelfTest module's list for discovery when the module
# is created. Since this module may be discovered before SelfTests itself,
# create the list if it doesn't already exist.
try:
slicer.selfTests
except AttributeError:
slicer.selfTests = {}
def runTest(self):
return
class mpReviewWidget(ScriptedLoadableModuleWidget, ModuleWidgetMixin):
PIRADS_VIEWFORM_URL = 'https://docs.google.com/forms/d/1Xwhvjn_HjRJAtgV5VruLCDJ_eyj1C-txi8HWn8VyXa4/viewform'
QA_VIEWFORM_URL = 'https://docs.google.com/forms/d/18Ni2rcooi60fev5mWshJA0yaCzHYvmXPhcG2-jMF-uw/viewform'
@property
def inputDataDir(self):
return self.dataDirButton.directory
@inputDataDir.setter
def inputDataDir(self, directory):
logging.debug('Directory selected: %s' % directory)
if not os.path.exists(directory):
directory = None
self.dataDirButton.text = "Choose data directory"
truncatedPath = None
else:
truncatedPath = ModuleLogicMixin.truncatePath(directory)
self.dataDirButton.text = truncatedPath
self.dataDirButton.caption = directory
self.setSetting('InputLocation', directory)
self.checkAndSetLUT()
self.updateStudyTable()
self.informationWatchBox.setInformation("CurrentDataDir", truncatedPath, toolTip=directory)
def __init__(self, parent = None):
ScriptedLoadableModuleWidget.__init__(self, parent)
self.resourcesPath = os.path.join(slicer.modules.mpreview.path.replace(self.moduleName+".py",""), 'Resources')
self.qaFormURL = ''
self.piradsFormURL = ''
# TODO: figure out why module/class hierarchy is different
# between developer builds ans packages
try:
# for developer build...
self.editUtil = EditorLib.EditUtil.EditUtil()
except AttributeError:
# for release package...
self.editUtil = EditorLib.EditUtil()
# mrml node for invoking command line modules
self.CLINode = None
self.logic = mpReviewLogic()
self.multiVolumeExplorer = None
# set up temporary directory
self.tempDir = os.path.join(slicer.app.temporaryPath, 'mpReview-tmp')
self.logic.createDirectory(self.tempDir, message='Temporary directory location: ' + self.tempDir)
self.fiducialLabelPropagateModel = None
self.modulePath = os.path.dirname(slicer.util.modulePath(self.moduleName))
def getAllSliceWidgets(self):
widgetNames = self.layoutManager.sliceViewNames()
return [self.layoutManager.sliceWidget(wn) for wn in widgetNames]
def setOffsetOnAllSliceWidgets(self, offset):
for widget in self.getAllSliceWidgets():
node = widget.mrmlSliceNode()
node.SetSliceOffset(offset)
def linkAllSliceWidgets(self, link):
for widget in self.getAllSliceWidgets():
sc = widget.mrmlSliceCompositeNode()
sc.SetLinkedControl(link)
sc.SetInteractionFlagsModifier(4+8+16)
def setOpacityOnAllSliceWidgets(self, opacity):
for widget in self.getAllSliceWidgets():
sc = widget.mrmlSliceCompositeNode()
sc.SetForegroundOpacity(opacity)
def updateViewRenderer (self):
toolbox = self.editorWidget.toolsBox
toolOption = toolbox.currentOption
for widget in self.getAllSliceWidgets():
view = widget.sliceView()
view.scheduleRender()
def setupIcons(self):
self.studySelectionIcon = self.createIcon('icon-studyselection_fit.png')
self.segmentationIcon = self.createIcon('icon-segmentation_fit.png')
self.completionIcon = self.createIcon('icon-completion_fit.png')
def setupTabBarNavigation(self):
self.tabWidget = qt.QTabWidget()
self.layout.addWidget(self.tabWidget)
self.studyAndSeriesSelectionWidget = qt.QWidget()
self.segmentationWidget = qt.QWidget()
self.completionWidget = qt.QWidget()
self.studyAndSeriesSelectionWidgetLayout = qt.QGridLayout()
self.segmentationWidgetLayout = qt.QVBoxLayout()
self.completionWidgetLayout = qt.QFormLayout()
self.studyAndSeriesSelectionWidget.setLayout(self.studyAndSeriesSelectionWidgetLayout)
self.segmentationWidget.setLayout(self.segmentationWidgetLayout)
self.completionWidget.setLayout(self.completionWidgetLayout)
self.tabWidget.setIconSize(qt.QSize(85, 30))
self.tabWidget.addTab(self.studyAndSeriesSelectionWidget, self.studySelectionIcon, '')
self.tabWidget.addTab(self.segmentationWidget, self.segmentationIcon, '')
self.tabWidget.addTab(self.completionWidget, self.completionIcon, '')
self.setTabsEnabled([1,2], False)
def onTabWidgetClicked(self, currentIndex):
toolbox = self.editorWidget.toolsBox
toolOption = toolbox.currentOption
if self.currentTabIndex == currentIndex:
return
setNewIndex = False
if currentIndex == 0:
setNewIndex = self.onStep1Selected()
if currentIndex == 1:
setNewIndex = self.onStep2Selected()
if currentIndex == 2:
setNewIndex = self.onStep3Selected()
if setNewIndex:
self.currentTabIndex = currentIndex
def setup(self):
ScriptedLoadableModuleWidget.setup(self)
self.setupIcons()
self.setupInformationFrame()
self.setupTabBarNavigation()
self.parameters = {}
self.crosshairNode = slicer.mrmlScene.GetNthNodeByClass(0, 'vtkMRMLCrosshairNode')
self.setupDataAndStudySelectionUI()
self.setupSeriesSelectionView()
self.setupSegmentationToolsUI()
self.setupCompletionUI()
self.setupConnections()
# self.layout.addStretch(1)
self.volumesLogic = slicer.modules.volumes.logic()
# these are the PK maps that should be loaded
self.pkMaps = ['Ktrans','Ve','Auc','TTP','MaxSlope']
self.volumeNodes = {}
self.refSelectorIgnoreUpdates = False
self.selectedStudyName = None
self.dataDirButton.directory = self.getSetting('InputLocation')
self.currentTabIndex = 0
def setupInformationFrame(self):
watchBoxInformation = [WatchBoxAttribute('StudyID', 'Study ID:'),
WatchBoxAttribute('PatientName', 'Name:', 'PatientName'),
WatchBoxAttribute('StudyDate', 'Study Date:', 'StudyDate'),
WatchBoxAttribute('PatientID', 'PID:', 'PatientID'),
WatchBoxAttribute('CurrentDataDir', 'Current Data Dir:'),
WatchBoxAttribute('PatientBirthDate', 'DOB:', 'PatientBirthDate')]
self.informationWatchBox = XMLBasedInformationWatchBox(watchBoxInformation, columns=2)
self.layout.addWidget(self.informationWatchBox)
def setupDataAndStudySelectionUI(self):
self.dataDirButton = ctk.ctkDirectoryButton()
self.studyAndSeriesSelectionWidgetLayout.addWidget(qt.QLabel("Data directory:"), 0, 0, 1, 1)
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.dataDirButton, 0, 1, 1, 2)
self.customLUTInfoIcon = self.createHelperLabel()
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.customLUTInfoIcon, 0, 2, 1, 1, qt.Qt.AlignRight)
self.customLUTInfoIcon.hide()
self.setupStudySelectionView()
def createHelperLabel(self, toolTipText=""):
label = self.createLabel("", pixmap=Icons.info.pixmap(qt.QSize(23, 20)), toolTip=toolTipText)
label.setCursor(qt.Qt.PointingHandCursor)
return label
def setupStudySelectionView(self):
self.studiesGroupBox = ctk.ctkCollapsibleGroupBox()
self.studiesGroupBox.title = "Studies"
studiesGroupBoxLayout = qt.QGridLayout()
self.studiesGroupBox.setLayout(studiesGroupBoxLayout)
self.studiesView, self.studiesModel = self.createListView('StudiesTable', ['Study ID'])
self.studiesView.setSizePolicy(qt.QSizePolicy.Expanding, qt.QSizePolicy.Expanding)
studiesGroupBoxLayout.addWidget(self.studiesView)
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.studiesGroupBox, 2, 0, 1, 3)
def setupSeriesSelectionView(self):
self.seriesGroupBox = qt.QGroupBox("Series")
seriesGroupBoxLayout = qt.QGridLayout()
self.seriesGroupBox.setLayout(seriesGroupBoxLayout)
self.seriesView, self.seriesModel = self.createListView('SeriesTable', ['Series ID'])
self.seriesView.setSelectionMode(qt.QAbstractItemView.ExtendedSelection)
self.selectAllSeriesButton = self.createButton('Select All')
self.deselectAllSeriesButton = self.createButton('Deselect All')
self.selectAllSeriesButton.setEnabled(False)
self.deselectAllSeriesButton.setEnabled(False)
seriesGroupBoxLayout.addWidget(self.seriesView, 0, 0, 1, 2)
seriesGroupBoxLayout.addWidget(self.createHLayout([self.selectAllSeriesButton, self.deselectAllSeriesButton]),
1, 0, 1, 2)
self.studyAndSeriesSelectionWidgetLayout.addWidget(self.seriesGroupBox, 3, 0, 1, 3)
def setupSegmentationToolsUI(self):
self.refSelector = qt.QComboBox()
self.segmentationWidgetLayout.addWidget(self.createHLayout([qt.QLabel("Reference image: "), self.refSelector]))
self.setupMultiVolumeExplorerUI()
self.setupLabelMapEditorUI()
self.setupAdvancedSegmentationSettingsUI()
#self.setupFiducialsUI()
# keep here names of the views created by CompareVolumes logic
self.viewNames = []
self.segmentationWidgetLayout.addStretch(1)
def setupMultiVolumeExplorerUI(self):
self.multiVolumeExplorerArea = ctk.ctkCollapsibleButton()
self.multiVolumeExplorerArea.text = "MultiVolumeExplorer"
self.multiVolumeExplorerArea.collapsed = True
self.multiVolumeExplorer = mpReviewMultiVolumeExplorer(qt.QFormLayout(self.multiVolumeExplorerArea))
self.multiVolumeExplorer.setup()
self.segmentationWidgetLayout.addWidget(self.multiVolumeExplorerArea)
def setupLabelMapEditorUI(self):
self.setupEditorWidget()
self.structuresView = slicer.util.findChildren(self.editorWidget.volumes, 'StructuresView')[0]
self.editorParameterNode = EditorLib.EditUtil.EditUtil.getParameterNode()
self.editorParameterNode.AddObserver(vtk.vtkCommand.ModifiedEvent, self.onEditorWidgetParameterNodeChanged,1.0)
self.editorParameterNode.AddObserver(vtk.vtkCommand.ModifiedEvent, self.onEditorWidgetParameterNodeChanged2,-1.0)
self.addCustomEditorButtons()
self.editorWidget.toolsColor.colorSpin.setEnabled(False)
self.editorWidget.toolsColor.colorPatch.setEnabled(False)
self.editorParameterNode = self.editUtil.getParameterNode()
self.editorParameterNode.SetParameter('propagationMode', str(slicer.vtkMRMLApplicationLogic.LabelLayer))
self.modelsVisibility = True
self.buildModelsButton = qt.QPushButton('Make')
self.modelsVisibilityButton = self.createButton('Hide', checkable=True)
self.labelMapVisibilityButton = self.createButton('Hide', checkable=True)
self.labelMapOutlineButton = self.createButton('Outline', checkable=True)
self.enableJumpToROI = qt.QCheckBox("Jump to ROI")
self.enableJumpToROI.checked = True
editorControls = self.getEditorControls()
modelsFrame = self.createHLayout([qt.QLabel('Structure Models: '), self.buildModelsButton,
self.modelsVisibilityButton, self.labelMapVisibilityButton,
self.labelMapOutlineButton, self.enableJumpToROI])
self.buildModelsButton.hide()
self.modelsVisibilityButton.hide()
perStructureFrame = slicer.util.findChildren(self.editorWidget.volumes, 'PerStructureVolumesFrame')[0]
perStructureFrame.collapsed = False
perStructureFrame.layout().addWidget(editorControls)
perStructureFrame.layout().addWidget(modelsFrame)
def setupEditorWidget(self):
editorWidgetParent = slicer.qMRMLWidget()
editorWidgetParent.setLayout(qt.QVBoxLayout())
editorWidgetParent.setMRMLScene(slicer.mrmlScene)
self.editorWidget = EditorWidget(parent=editorWidgetParent)
self.editorWidget.setup()
try:
self.editorWidget.segmentEditorLabel.hide()
self.editorWidget.infoIconLabel.hide()
except AttributeError:
pass
self.segmentationWidgetLayout.addWidget(editorWidgetParent)
self.hideUnwantedEditorUIElements()
def hideUnwantedEditorUIElements(self):
toHide = {}
toHide[self.editorWidget.volumes] = ['AllButtonsFrameButton', 'ReplaceModelsCheckBox', 'MasterVolumeFrame',
'MergeVolumeFrame', 'SplitStructureButton']
toHide[self.editorWidget.editBoxFrame] = ['WandEffectToolButton', 'LevelTracingEffectToolButton',
'RectangleEffectToolButton', 'IdentifyIslandsEffectToolButton',
'ChangeIslandEffectToolButton', 'RemoveIslandsEffectToolButton',
'SaveIslandEffectToolButton', 'RowFrame4', 'RowFrame3', 'RowFrame2',
'RowFrame1']
for widget, o in toHide.iteritems():
for objectName in o:
try:
slicer.util.findChildren(widget, objectName)[0].hide()
except AttributeError:
continue
def getEditorControls(self):
editBoxFrame = self.editorWidget.editBoxFrame
effectButtonFrame = slicer.util.findChildren(editBoxFrame, 'RowFrame1')[0]
buttons = [c for c in effectButtonFrame.children() if isinstance(c, qt.QToolButton)]
buttons.append(slicer.util.findChildren(editBoxFrame, 'DilateEffectToolButton')[0])
self.windowLevelEffectsButton = WindowLevelEffectsButton()
buttons.append(self.windowLevelEffectsButton)
undoButton = slicer.util.findChildren(editBoxFrame, 'PreviousCheckPointToolButton')[0]
redoButton = slicer.util.findChildren(editBoxFrame, 'NextCheckPointToolButton')[0]
undoRedo = self.createHLayout([qt.QLabel("Undo/Redo:"), undoButton, redoButton])
undoRedo.layout().setAlignment(qt.Qt.AlignLeft)
effectButtons = self.createHLayout(buttons)
effectButtons.layout().setAlignment(qt.Qt.AlignRight)
hbox = self.createHLayout([undoRedo, effectButtons])
return hbox
def addCustomEditorButtons(self):
volumesFrame = self.editorWidget.volumes
buttonsFrame = slicer.util.findChildren(volumesFrame, 'ButtonsFrame')[0]
buttonsFrameLayout = buttonsFrame.layout()
redWidget = self.layoutManager.sliceWidget('Red')
controller = redWidget.sliceController()
moreButton = slicer.util.findChildren(controller, 'MoreButton')[0]
moreButton.toggle()
self.deleteStructureButton = qt.QPushButton('Delete')
self.propagateButton = qt.QPushButton('Propagate')
buttonsFrameLayout.addWidget(self.deleteStructureButton)
buttonsFrameLayout.addWidget(self.propagateButton)
self.propagateButton.hide()
def setupAdvancedSegmentationSettingsUI(self):
self.advancedSettingsArea = ctk.ctkCollapsibleButton()
self.advancedSettingsArea.text = "Advanced Settings"
self.advancedSettingsArea.collapsed = True
self.setupSingleMultiViewSettingsUI()
self.setupViewerOrientationSettingsUI()
self.setupLabelTranslationSettingsUI()
self.ignoreTranslate = False
# Create a transform node
self.transformNode = slicer.vtkMRMLLinearTransformNode()
self.transformNode.SetName('mpReview-transform')
slicer.mrmlScene.AddNode(self.transformNode)
advancedSettingsLayout = qt.QFormLayout(self.advancedSettingsArea)
advancedSettingsLayout.addRow("Show series: ", self.groupWidget)
advancedSettingsLayout.addRow('View orientation: ', self.orientationBox)
advancedSettingsLayout.addRow(self.translateArea)
self.segmentationWidgetLayout.addWidget(self.advancedSettingsArea)
def setupSingleMultiViewSettingsUI(self):
self.multiView = qt.QRadioButton('All')
self.singleView = qt.QRadioButton('Reference only')
self.multiView.setChecked(True)
self.groupWidget = qt.QGroupBox()
self.groupLayout = qt.QFormLayout(self.groupWidget)
self.groupLayout.addRow(self.multiView, self.singleView)
self.viewButtonGroup = qt.QButtonGroup()
self.viewButtonGroup.addButton(self.multiView, 1)
self.viewButtonGroup.addButton(self.singleView, 2)
def setupViewerOrientationSettingsUI(self):
self.orientationBox = qt.QGroupBox()
orientationBoxLayout = qt.QFormLayout()
self.orientationBox.setLayout(orientationBoxLayout)
self.orientationButtons = {}
self.orientations = ("Axial", "Sagittal", "Coronal")
for orientation in self.orientations:
self.orientationButtons[orientation] = self.createRadioButton(orientation, checked=orientation=="Axial")
orientationBoxLayout.addWidget(self.orientationButtons[orientation])
self.currentOrientation = 'Axial'
def setupLabelTranslationSettingsUI(self):
self.translateArea = ctk.ctkCollapsibleButton()
self.translateArea.text = "Translate Selected Label Map"
translateAreaLayout = qt.QFormLayout(self.translateArea)
self.translateLR = self.createSliderWidget(minimum=-200, maximum=200)
self.translatePA = self.createSliderWidget(minimum=-200, maximum=200)
self.translateIS = self.createSliderWidget(minimum=-200, maximum=200)
translateAreaLayout.addRow("Translate LR: ", self.translateLR)
translateAreaLayout.addRow("Translate PA: ", self.translatePA)
translateAreaLayout.addRow("Translate IS: ", self.translateIS)
self.hardenTransformButton = self.createButton("Harden Transform", enabled=False)
translateAreaLayout.addRow(self.hardenTransformButton)
self.translateArea.collapsed = 1
def setupFiducialsUI(self):
self.fiducialsArea = ctk.ctkCollapsibleButton()
self.fiducialsArea.text = "Fiducials"
self.fiducialsArea.collapsed = True
def setupCompletionUI(self):
self.saveButton = qt.QPushButton("Save")
self.completionWidgetLayout.addWidget(self.saveButton)
'''
self.piradsButton = qt.QPushButton("PI-RADS review")
self.layout.addWidget(self.piradsButton)
# self.piradsButton.connect('clicked()',self.onPiradsClicked)
'''
def setupConnections(self):
def setupButtonConnections():
self.dataDirButton.directorySelected.connect(lambda: setattr(self, "inputDataDir", self.dataDirButton.directory))
self.selectAllSeriesButton.connect('clicked()', lambda: self.selectAllSeries(True))
self.deselectAllSeriesButton.connect('clicked()', lambda: self.selectAllSeries(False))
self.deleteStructureButton.connect('clicked()', self.onDeleteStructure)
self.propagateButton.connect('clicked()', self.onPropagateROI)
self.hardenTransformButton.connect('clicked(bool)', self.onHardenTransform)
self.buildModelsButton.connect("clicked()", self.onBuildModels)
self.modelsVisibilityButton.connect("toggled(bool)", self.onModelsVisibilityButton)
self.labelMapVisibilityButton.connect("toggled(bool)", self.onLabelMapVisibilityButton)
self.labelMapOutlineButton.connect('toggled(bool)', self.setLabelOutline)
self.saveButton.connect('clicked()', self.onSaveClicked)
for orientation in self.orientations:
self.orientationButtons[orientation].connect("clicked()", lambda o=orientation: self.setOrientation(o))
self.viewButtonGroup.connect('buttonClicked(int)', self.onViewUpdateRequested)
def setupSliderConnections():
self.translateLR.connect('valueChanged(double)', self.onTranslate)
self.translatePA.connect('valueChanged(double)', self.onTranslate)
self.translateIS.connect('valueChanged(double)', self.onTranslate)
self.multiVolumeExplorer.frameSlider.connect('valueChanged(double)', self.onSliderChanged)
def setupViewConnections():
self.studiesView.selectionModel().connect('currentChanged(QModelIndex, QModelIndex)', self.onStudySelected)
self.seriesView.connect('clicked(QModelIndex)', self.onSeriesSelected)
self.structuresView.connect("activated(QModelIndex)", self.onStructureClicked)
def setupOtherConnections():
self.refSelector.connect('currentIndexChanged(int)', self.onReferenceChanged)
self.tabWidget.connect('currentChanged(int)',self.onTabWidgetClicked)
setupButtonConnections()
setupSliderConnections()
setupViewConnections()
setupOtherConnections()
def onEditorWidgetParameterNodeChanged2(self, caller, event=-1):
effectName = caller.GetParameter("effect")
toolbox = self.editorWidget.toolsBox
toolOption = toolbox.currentOption
attributes = ["paintOver", "thresholdPaint", "smudge", "pixelMode"]
for attr in attributes:
if hasattr(toolOption, attr):
getattr(toolOption, attr).setVisible(False)
def onEditorWidgetParameterNodeChanged(self, caller, event=-1):
effectName = caller.GetParameter("effect")
toolbox = self.editorWidget.toolsBox
toolOption = toolbox.currentOption
attributes = ["paintOver", "thresholdPaint", "smudge", "pixelMode"]
for attr in attributes:
if hasattr(toolOption, attr):
getattr(toolOption, attr).setVisible(False)
try:
slicer.util.findChildren(self.editorWidget.toolsBox.optionsFrame, "EditorHelpButton")[0].hide()
except IndexError:
pass
def enter(self):
userName = self.getSetting('UserName')
if userName is None or userName == '':
name = "DeepLiver"
self.setSetting('UserName', name)
self.parameters['UserName'] = name
url="http://goo.gl/nT1z4L"
self.setSetting('qaFormURL',url)
self.setSetting('piradsFormURL',url)
self.piradsFormURL = url
self.qaFormURL = url
else:
self.parameters['UserName'] = userName
'''
# ask where is the input
if inputLocation == None or inputLocation == '':
self.dirPrompt = qt.QDialog()
self.dirPromptLayout = qt.QVBoxLayout()
self.dirPrompt.setLayout(self.dirPromptLayout)
self.dirLabel = qt.QLabel('Choose the directory with the input data:', self.dirPrompt)
self.dirButton = ctk.ctkDirectoryButton(self.dirPrompt)
self.dirButtonDone = qt.QPushButton('OK', self.dirPrompt)
self.dirButtonDone.connect('clicked()', self.onInputDirEntered)
self.dirPromptLayout.addWidget(self.dirLabel)
self.dirPromptLayout.addWidget(self.dirButton)
self.dirPromptLayout.addWidget(self.dirButtonDone)
self.dirPrompt.exec_()
else:
self.parameters['InputLocation'] = inputLocation
logging.debug('Setting inputlocation in settings to '+inputLocation)
# ask where to keep the results
if resultsLocation == None or resultsLocation == '':
self.dirPrompt = qt.QDialog()
self.dirPromptLayout = qt.QVBoxLayout()
self.dirPrompt.setLayout(self.dirPromptLayout)
self.dirLabel = qt.QLabel('Choose the directory to store the results:', self.dirPrompt)
self.dirButton = ctk.ctkDirectoryButton(self.dirPrompt)
self.dirButtonDone = qt.QPushButton('OK', self.dirPrompt)
self.dirButtonDone.connect('clicked()', self.onResultsDirEntered)
self.dirPromptLayout.addWidget(self.dirLabel)
self.dirPromptLayout.addWidget(self.dirButton)
self.dirPromptLayout.addWidget(self.dirButtonDone)
self.dirPrompt.exec_()
else:
self.parameters['ResultsLocation'] = resultsLocation
'''
def checkAndSetLUT(self):
# Default to module color table
self.colorFile = os.path.join(self.resourcesPath, "Colors/mpReviewColors.csv")
self.customLUTInfoIcon.show()
self.customLUTInfoIcon.toolTip = 'Using Default LUT'
# Check for custom LUT
lookupTableLoc = os.path.join(self.inputDataDir, 'SETTINGS', self.inputDataDir.split(os.sep)[-1] + '-LUT.csv')
logging.debug('Checking for lookup table at : ' + lookupTableLoc)
if os.path.isfile(lookupTableLoc):
# use custom color table
self.colorFile = lookupTableLoc
self.customLUTInfoIcon.toolTip = 'Project-Specific LUT Found'
# Set merge volume in structureListWidget to None so Editor doesn't get confused by missing node
# This may be the first time we get here, in which case editorWidget is not
# created yet. If it has been created, structureListWidget.merge is probably set to
# something that has been removed from the scene by onStep3Select.
try:
self.editorWidget.helper.structureListWidget.merge = None
except AttributeError:
pass
# setup the color table, make sure mpReview LUT is a singleton
allColorTableNodes = slicer.util.getNodes('vtkMRMLColorTableNode*').values()
for ctn in allColorTableNodes:
if ctn.GetName() == 'mpReview':
slicer.mrmlScene.RemoveNode(ctn)
break
self.mpReviewColorNode, self.structureNames = self.logic.loadColorTable(self.colorFile)
def onNameEntered(self):
name = self.nameText.text
if len(name)>0:
self.setSetting('UserName', name)
self.namePrompt.close()
self.parameters['UserName'] = name
def onQAURLEntered(self):
url = self.URLText.text
if len(url)>0:
self.setSetting('qaFormURL',url)
self.URLPrompt.close()
self.qaFormURL = url
def onPIRADSURLEntered(self):
url = self.URLText.text
if len(url)>0:
self.setSetting('piradsFormURL',url)
self.URLPrompt.close()
self.piradsFormURL = url
# def onResultsDirEntered(self):
# path = self.dirButton.directory
# if len(path)>0:
# self.setSetting('ResultsLocation',path)
# self.dirPrompt.close()
# self.parameters['ResultsLocation'] = path
def onViewUpdateRequested(self, id):
# Skip if not in a ref image yet
if self.refSeriesNumber == '-1':
return
# Be sure the viewers are linked, they should be but who knows
self.linkAllSliceWidgets(1)
layoutNode = slicer.util.getNode('*LayoutNode*')
if id == 1:
# If view all
layoutNode.SetViewArrangement(layoutNode.SlicerLayoutUserView)
if id == 2:
# If view ref only
layoutNode.SetViewArrangement(layoutNode.SlicerLayoutOneUpRedSliceView)
def onSeriesSelected(self, modelIndex):
logging.debug('Row selected: '+self.seriesModel.item(modelIndex.row(),0).text())
selectionModel = self.seriesView.selectionModel()
logging.debug('Selection model says row is selected: '+str(selectionModel.isRowSelected(modelIndex.row(),
qt.QModelIndex())))
logging.debug('Row number: '+str(modelIndex.row()))
self.updateSegmentationTabAvailability()
def updateSegmentationTabAvailability(self):
self.setTabsEnabled([1], any(sItem.checkState() == 2 for sItem in self.seriesItems))
def onPIRADSFormClicked(self):
self.webView = qt.QWebView()
self.webView.settings().setAttribute(qt.QWebSettings.DeveloperExtrasEnabled, True)
self.webView.connect('loadFinished(bool)', self.webViewFormLoadedCallback)
self.webView.show()
preFilledURL = self.piradsFormURL
preFilledURL += '?entry.1455103354='+self.getSetting('UserName')
preFilledURL += '&entry.347120626='+self.selectedStudyName
preFilledURL += '&entry.1734306468='+str(self.editorWidget.toolsColor.colorSpin.value)
u = qt.QUrl(preFilledURL)
self.webView.setUrl(u)
# https://docs.google.com/forms/d/18Ni2rcooi60fev5mWshJA0yaCzHYvmXPhcG2-jMF-uw/viewform?entry.1920755914=READER&entry.204001910=STUDY
def onQAFormClicked(self):
self.webView = qt.QWebView()
self.webView.settings().setAttribute(qt.QWebSettings.DeveloperExtrasEnabled, True)
self.webView.connect('loadFinished(bool)', self.webViewFormLoadedCallback)
self.webView.show()
preFilledURL = self.qaFormURL
preFilledURL += '?entry.1920755914='+self.getSetting('UserName')
preFilledURL += '&entry.204001910='+self.selectedStudyName
print('Pre-filled URL:'+preFilledURL)
u = qt.QUrl(preFilledURL)
self.webView.setUrl(u)
def webViewFormLoadedCallback(self,ok):
if not ok:
logging.debug('page did not load')
return
page = self.webView.page()
frame = page.mainFrame()
document = frame.documentElement()
element = document.findFirst('entry.2057130045')
element.setAttribute("value", self.parameters['UserName'])
def onSaveClicked(self):
""" Elements that will be saved:
* segmentation: label map
* w/l for each volume
Convention: create a directory for each type of resource saved,
then subdirectory for each scan that was analyzed
"""
timestamp = datetime.datetime.now().strftime("%Y%m%d%H%M%S")
username = self.getSetting('UserName')
savedMessage = self.saveSegmentations(timestamp, username)# save w/l settings for all non-label volume nodes
'''
volumeNodes = slicer.util.getNodes('vtkMRMLScalarVolumeNode*')
logging.debug('All volume nodes: '+str(volumeNodes))
for key in volumeNodes.keys():
vNode = volumeNodes[key]
if vNode.GetAttribute('LabelMap') == '1':
continue
seriesNumber = string.split(key,':')[0]
logging.debug('W/L for series '+seriesNumber+' is '+str(vNode.GetDisplayNode().GetWindow()))
f = open(wlSettingsDir+'/'+seriesNumber+'-wl.txt','w')
f.write(str(vNode.GetDisplayNode().GetWindow())+' '+str(vNode.GetDisplayNode().GetLevel()))
f.close()
'''
savedMessage += "\n " + self.saveTargets(username, timestamp)
slicer.util.infoDisplay(savedMessage, windowTitle="mpReview")
def saveSegmentations(self, timestamp, username):
wlSettingsDir = os.path.join(self.inputDataDir, self.selectedStudyName, 'WindowLevelSettings')
self.logic.createDirectory(wlSettingsDir)
# save all label nodes (there should be only one per volume!)
labelNodes = slicer.util.getNodes('*-label*')
logging.debug('All label nodes found: ' + str(labelNodes))
savedMessage = 'Segmentations for the following series were saved:\n\n'
for label in labelNodes.values():
labelSeries = label.GetName().split(':')[0]
labelName = label.GetName().split(':')[1]
# structure is root -> study -> resources -> series # ->
# Segmentations/Reconstructions/OncoQuant -> files
segmentationsDir = os.path.join(self.inputDataDir, self.selectedStudyName,
'RESOURCES', labelSeries, 'Segmentations')
self.logic.createDirectory(segmentationsDir)
structureName = labelName[labelName[:-6].rfind("-") + 1:-6]
# Only save labels with known structure names
if any(structureName == s for s in self.structureNames):
logging.debug("structure name is: %s" % structureName)
uniqueID = structureName + '-' + timestamp
labelFileName = os.path.join(segmentationsDir, uniqueID + '.nrrd')
sNode = slicer.vtkMRMLVolumeArchetypeStorageNode()
sNode.SetFileName(labelFileName)
sNode.SetWriteFileFormat('nrrd')
sNode.SetURI(None)
success = sNode.WriteData(label)
# [DeepLiver] Saving the spacing and the special id in the nrrd file
# TODO: Check if the path work with unix based systems
path_segmentation = segmentationsDir + '\\' + uniqueID + '.nrrd'
data_nrrd, header_nrrd = nrrd.read(path_segmentation)
header_nrrd['spacings'] = label.GetSpacing()
dom = xml.dom.minidom.parse(os.path.join(self.inputDataDir, self.selectedStudyName, 'RESOURCES', labelSeries, 'Reconstructions', labelSeries + '.xml'))
root = dom.documentElement
nodelist=root.getElementsByTagName("element")
for node in nodelist:
if node.getAttribute("name")=="SeriesInstanceUID":
seriesinstanceuid = node.firstChild.data
if node.getAttribute("name")=="StudyInstanceUID":
studyinstanceuid = node.firstChild.data
if node.getAttribute("name")=="PatientID":
patientid = node.firstChild.data
header_nrrd['Label'] = structureName
header_nrrd['Series Instance UID'] = seriesinstanceuid
header_nrrd['Study Instance UID'] = studyinstanceuid
header_nrrd['Patient ID'] = patientid
field_info = {'Label': 'string','Series Instance UID': 'string', 'Study Instance UID': 'string', 'Patient ID': 'string'}
nrrd.write(filename=path_segmentation, data=data_nrrd, header=header_nrrd,\
detached_header=False, custom_field_map=field_info)
if success:
savedMessage = savedMessage + label.GetName() + '\n'
logging.debug(label.GetName() + ' has been saved to ' + labelFileName)
return savedMessage
def saveTargets(self, username, timestamp):
savedMessage = ""
return savedMessage
def onBuildModels(self):
"""make models of the structure label nodesvolume"""
if self.refSeriesNumber != '-1':
ref = self.refSeriesNumber
refLongName = self.seriesMap[ref]['LongName']
labelNodes = slicer.util.getNodes('*'+refLongName+'*-label*')
numNodes = slicer.mrmlScene.GetNumberOfNodesByClass( "vtkMRMLModelHierarchyNode" )
outHierarchy = None
for n in xrange(numNodes):
node = slicer.mrmlScene.GetNthNodeByClass( n, "vtkMRMLModelHierarchyNode" )
if node.GetName() == 'mpReview-'+refLongName:
outHierarchy = node
break
# Remove the previous models
if outHierarchy:
collection = vtk.vtkCollection()
outHierarchy.GetChildrenModelNodes(collection)
n = collection.GetNumberOfItems()
if n != 0:
for i in xrange(n):
modelNode = collection.GetItemAsObject(i)
slicer.mrmlScene.RemoveNode(modelNode)
# if models hierarchy does not exist, create it.
else:
outHierarchy = slicer.vtkMRMLModelHierarchyNode()
outHierarchy.SetScene( slicer.mrmlScene )
outHierarchy.SetName( 'mpReview-'+refLongName )
slicer.mrmlScene.AddNode( outHierarchy )
progress = self.createProgressDialog(maximum=len(labelNodes))
step = 0
for label in labelNodes.values():
labelName = label.GetName().split(':')[1]
structureName = labelName[labelName[:-6].rfind("-")+1:-6]
# Only save labels with known structure names
if any(structureName in s for s in self.structureNames):
parameters = {}
parameters["InputVolume"] = label.GetID()
parameters['FilterType'] = "Sinc"
parameters['GenerateAll'] = True
parameters["JointSmoothing"] = False
parameters["SplitNormals"] = True
parameters["PointNormals"] = True
parameters["SkipUnNamed"] = True
# create models for all labels
parameters["StartLabel"] = -1
parameters["EndLabel"] = -1
parameters["Decimate"] = 0
parameters["Smooth"] = 0
parameters["ModelSceneFile"] = outHierarchy
progress.labelText = '\nMaking Model for %s' % structureName
progress.setValue(step)
slicer.app.processEvents()
if progress.wasCanceled:
break
try:
modelMaker = slicer.modules.modelmaker
self.CLINode = slicer.cli.run(modelMaker, self.CLINode,
parameters, wait_for_completion=True)
except AttributeError:
qt.QMessageBox.critical(slicer.util.mainWindow(),'Editor', 'The ModelMaker module is not available'
'<p>Perhaps it was disabled in the application '
'settings or did not load correctly.')
step += 1
progress.close()
#
if outHierarchy:
collection = vtk.vtkCollection()
outHierarchy.GetChildrenModelNodes(collection)
n = collection.GetNumberOfItems()
if n != 0:
for i in xrange(n):
modelNode = collection.GetItemAsObject(i)
displayNode = modelNode.GetDisplayNode()
displayNode.SetSliceIntersectionVisibility(1)
displayNode.SetSliceIntersectionThickness(2)
self.modelsVisibilityButton.checked = False
self.updateViewRenderer()
def removeAllModels(self):
modelHierarchyNodes = []
numNodes = slicer.mrmlScene.GetNumberOfNodesByClass( "vtkMRMLModelHierarchyNode" )
for n in xrange(numNodes):
node = slicer.mrmlScene.GetNthNodeByClass( n, "vtkMRMLModelHierarchyNode")
if node.GetName()[:12] == 'mpReview-':
modelHierarchyNodes.append(node)
for hierarchyNode in modelHierarchyNodes:
modelNodes = vtk.vtkCollection()
hierarchyNode.GetChildrenModelNodes(modelNodes)
for i in range(modelNodes.GetNumberOfItems()) :
slicer.mrmlScene.RemoveNode(modelNodes.GetItemAsObject(i))
slicer.mrmlScene.RemoveNode(hierarchyNode)
self.modelsVisibilityButton.checked = False
self.modelsVisibilityButton.setText('Hide')
def setLabelOutline(self, toggled):
# Update button text
if toggled:
self.labelMapOutlineButton.setText('Filled')
else:
self.labelMapOutlineButton.setText('Outline')
# Set outline on widgets
self.editUtil.setLabelOutline(toggled)
def onModelsVisibilityButton(self,toggled):
if self.refSeriesNumber != '-1':
ref = self.refSeriesNumber
refLongName = self.seriesMap[ref]['LongName']
outHierarchy = None
numNodes = slicer.mrmlScene.GetNumberOfNodesByClass( "vtkMRMLModelHierarchyNode" )
for n in xrange(numNodes):
node = slicer.mrmlScene.GetNthNodeByClass( n, "vtkMRMLModelHierarchyNode" )
if node.GetName() == 'mpReview-'+refLongName:
outHierarchy = node
break
if outHierarchy:
collection = vtk.vtkCollection()
outHierarchy.GetChildrenModelNodes(collection)
n = collection.GetNumberOfItems()
if n != 0:
for i in xrange(n):
modelNode = collection.GetItemAsObject(i)
displayNode = modelNode.GetDisplayNode()
displayNode.SetSliceIntersectionVisibility(0 if toggled else 1)
self.modelsVisibilityButton.setText('Show' if toggled else 'Hide')
self.updateViewRenderer()
def onLabelMapVisibilityButton(self, toggled):
self.labelMapVisibilityButton.setText('Show' if toggled else 'Hide')
sliceLogics = self.layoutManager.mrmlSliceLogics()
for n in range(sliceLogics.GetNumberOfItems()):
sliceLogic = sliceLogics.GetItemAsObject(n)
widget = self.layoutManager.sliceWidget(sliceLogic.GetName())
redCompositeNode = widget.mrmlSliceCompositeNode()
redCompositeNode.SetLabelOpacity(0.0 if toggled else 1.0)
def checkAndLoadLabel(self, seriesNumber, volumeName):
globPath = os.path.join(self.resourcesDir,str(seriesNumber),"Segmentations",
self.getSetting('UserName')+'*')
previousSegmentations = glob.glob(globPath)
if not len(previousSegmentations):
return False,None
#fileName = previousSegmentations[-1]
# Iterate over segmentation files and choose the latest for each structure
latestSegmentations = {}
for segmentation in previousSegmentations:
actualFileName = os.path.split(segmentation)[1]
structureName = actualFileName.split("-")[1] # expectation: username-structure-timestamp.nrrd
# this is to support legacy segmentations that did not use this
# specific LUT, and where labels are specified by numbers
# Use the structure name as defined by the corresponding label ID in
# the selected LUT
if structureName not in self.structureNames and int(structureName)<len(self.structureNames):
structureName = self.structureNames[int(structureName)]
timeStamp = int(actualFileName.split("-")[2][:-5])
if structureName not in latestSegmentations.keys():
latestSegmentations[structureName] = segmentation
else:
storedSegmentation = latestSegmentations[structureName]
storedTimeStamp = int(storedSegmentation[storedSegmentation.rfind("-")+1:-5])
if timeStamp > storedTimeStamp:
latestSegmentations[structureName] = segmentation
for structure,fileName in latestSegmentations.iteritems():
(success,label) = slicer.util.loadLabelVolume(fileName, returnNode=True)
if not success:
return False,None
logging.debug('Setting loaded label name to '+volumeName)
actualFileName = os.path.split(fileName)[1]
label.SetName(volumeName+'-'+structure+'-label')
label.RemoveAllDisplayNodeIDs()
dNode = slicer.vtkMRMLLabelMapVolumeDisplayNode()
slicer.mrmlScene.AddNode(dNode)
dNode.SetAndObserveColorNodeID(self.mpReviewColorNode.GetID())