/
LumpNav2.py
2713 lines (2343 loc) · 127 KB
/
LumpNav2.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
import os
import datetime
import time
import json
from packaging import version
import numpy as np
import vtk, qt, ctk, slicer
import logging
from slicer.ScriptedLoadableModule import *
from slicer.util import VTKObservationMixin
import Viewpoint
try:
import matplotlib.pyplot as plt
except:
slicer.util.pip_install('matplotlib')
import matplotlib.pyplot as plt
try:
from sklearn import datasets
except:
slicer.util.pip_install('scikit-learn')
from sklearn import datasets
try:
from mlxtend.plotting import plot_decision_regions
except:
slicer.util.pip_install('mlxtend')
from mlxtend.plotting import plot_decision_regions
#
# LumpNav2
#
# Finding where guidelet.py and ultrasound.py are stored:
# C:\Users\(_NAME_)\AppData\Roaming\NA-MIC\Extensions-28257\SlicerIGT\lib\Slicer-4.10\qt-scripted-modules\Guidelet\GuideletLib\Guidelet.py
# C:\Users\(_NAME_)\AppData\Roaming\NA-MIC\Extensions-28257\SlicerIGT\lib\Slicer-4.10\qt-scripted-modules\Guidelet\GuideletLib\UltraSound.py
class LumpNav2(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
def __init__(self, parent):
ScriptedLoadableModule.__init__(self, parent)
self.parent.title = "LumpNav2"
self.parent.categories = ["IGT"]
self.parent.dependencies = [] # TODO: add here list of module names that this module requires
self.parent.contributors = ["Perk Lab (Queen's University)"]
# TODO: update with short description of the module and a link to online module documentation
self.parent.helpText = """
This is an example of scripted loadable module bundled in an extension.
See more information in <a href="https://github.com/organization/projectname#LumpNav2">module documentation</a>.
"""
self.parent.acknowledgementText = """
This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc., Andras Lasso, PerkLab,
and Steve Pieper, Isomics, Inc. and was partially funded by NIH grant 3P41RR013218-12S1.
"""
# Additional initialization step after application startup is complete
slicer.app.connect("startupCompleted()", registerSampleData)
#
# Register sample data sets in Sample Data module
#
def registerSampleData():
"""
Add data sets to Sample Data module.
"""
# It is always recommended to provide sample data for users to make it easy to try the module,
# but if no sample data is available then this method (and associated startupCompeted signal connection) can be removed.
import SampleData
iconsPath = os.path.join(os.path.dirname(__file__), 'Resources/Icons')
# To ensure that the source code repository remains small (can be downloaded and installed quickly)
# it is recommended to store data sets that are larger than a few MB in a Github release.
# LumpNav21
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category='LumpNav2',
sampleName='LumpNav21',
# Thumbnail should have size of approximately 260x280 pixels and stored in Resources/Icons folder.
# It can be created by Screen Capture module, "Capture all views" option enabled, "Number of images" set to "Single".
thumbnailFileName=os.path.join(iconsPath, 'LumpNav21.png'),
# Download URL and target file name
uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95",
fileNames='LumpNav21.nrrd',
# Checksum to ensure file integrity. Can be computed by this command:
# import hashlib; print(hashlib.sha256(open(filename, "rb").read()).hexdigest())
checksums = 'SHA256:998cb522173839c78657f4bc0ea907cea09fd04e44601f17c82ea27927937b95',
# This node name will be used when the data set is loaded
nodeNames='LumpNav21'
)
# LumpNav22
SampleData.SampleDataLogic.registerCustomSampleDataSource(
# Category and sample name displayed in Sample Data module
category='LumpNav2',
sampleName='LumpNav22',
thumbnailFileName=os.path.join(iconsPath, 'LumpNav22.png'),
# Download URL and target file name
uris="https://github.com/Slicer/SlicerTestingData/releases/download/SHA256/1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97",
fileNames='LumpNav22.nrrd',
checksums = 'SHA256:1a64f3f422eb3d1c9b093d1a18da354b13bcf307907c66317e2463ee530b7a97',
# This node name will be used when the data set is loaded
nodeNames='LumpNav22'
)
# Event filter for LumpNav widget main window
class LumpNavEventFilter(qt.QWidget):
"""
Install this event filter to overwrite default behavior of main window events like closing the window or saving the
scene.
"""
def __init__(self, moduleWidget):
qt.QWidget.__init__(self)
self.moduleWidget = moduleWidget
def eventFilter(self, object, event):
if event.type() == qt.QEvent.Close:
if self.moduleWidget.confirmExit():
slicer.app.quit()
return True
else:
event.ignore()
return True
# elif (event.type() == qt.QEvent.KeyPress and event.key() == qt.Qt.Key_S and (event.modifiers() & qt.Qt.ControlModifier)):
# print("CTRL + S intercepted")
# return True
return False
#
# LumpNav2Widget
#
class LumpNav2Widget(ScriptedLoadableModuleWidget, VTKObservationMixin):
"""Uses ScriptedLoadableModuleWidget base class, available at:
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py
"""
# Variables to store widget state
SLICER_RECOMMENDED_VERSION = "5.0.0"
SLICER_INTERFACE_VISIBLE = "LumpNav2/SlicerInterfaceVisible"
NORMAL_BRIGHTNESS = 300
BRIGHT_BRIGHTNESS = 220
BRIGHTEST_BRIGHTNESS = 140
FONT_SIZE_DEFAULT = 20
VIEW_COORD_HEIGHT_LIMIT = 0.6
VIEW_COORD_WIDTH_LIMIT = 0.9
SAVE_FOLDER_SETTING = "LumpNav2/LastSaveFolder"
# Tool calibration
PIVOT_CALIBRATION = 0
SPIN_CALIBRATION = 1
PIVOT_CALIBRATION_TIME_SEC = 5.0
CAUTERY_CALIBRATION_THRESHOLD_SETTING = "LumpNav2/CauteryCalibrationThresholdMm"
CAUTERY_CALIBRATION_THRESHOLD_DEFAULT = 1.0
LAST_PIVOT_CALIBRATION_RESULT = "LastPivotCalibrationResult"
NEEDLE_CALIBRATION_THRESHOLD_SETTING = "LumpNav2/NeedleCalibrationThresholdMm"
NEEDLE_CALIBRATION_THRESHOLD_DEFAULT = 1.0
def __init__(self, parent=None):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
ScriptedLoadableModuleWidget.__init__(self, parent)
slicer.mymodW = self # then in python interactor, call "self = slicer.mymod" to use
VTKObservationMixin.__init__(self) # needed for parameter node observation
self.logic = None
self._parameterNode = None
self._updatingGUIFromParameterNode = False
self._updatingGUIFromMRML = False
self._updatingGui = False
self.saveTime = vtk.vtkTimeStamp()
self.observedNeedleModel = None
self.observedCauteryModel = None
self.observedTrackingSeqBrNode = None
self.observedUltrasoundSeqBrNode = None
self.observedEventTableNode = None
self.observedPlusServerLauncherNode = None
self.observedNeedleTipToNeedleNode = None
# Timer for pivot calibration controls
self.pivotCalibrationLogic = slicer.modules.pivotcalibration.logic()
self.pivotCalibrationStopTime = 0
self.pivotSamplingTimer = qt.QTimer()
self.pivotSamplingTimer.setInterval(500)
self.pivotSamplingTimer.setSingleShot(True)
self.pivotCalibrationMode = self.PIVOT_CALIBRATION # Default value, but it is always set when starting pivot calibration
self.pivotCalibrationResultNode = None
def setup(self):
"""
Called when the user opens the module the first time and the widget is initialized.
"""
# Check Slicer version and display message if older than recommended
currentSlicerVersion = str(slicer.app.mainApplicationMajorVersion) + "." + \
str(slicer.app.mainApplicationMinorVersion) + "." + \
str(slicer.app.mainApplicationPatchVersion)
if version.parse(currentSlicerVersion) < version.parse(self.SLICER_RECOMMENDED_VERSION):
msg = qt.QMessageBox()
msg.setIcon(qt.QMessageBox.Information)
msg.setTextFormat(qt.Qt.RichText)
msg.setText(f"Current 3D Slicer version ({currentSlicerVersion}) is older than the recommended version "
f"({self.SLICER_RECOMMENDED_VERSION}). This may lead to unexpected behaviour.")
msg.setInformativeText("3D Slicer releases can be downloaded <a href='https://download.slicer.org/'>here</a>.")
msg.setWindowTitle("3D Slicer")
msg.setStandardButtons(qt.QMessageBox.Ok)
msg.setModal(True)
msg.exec()
ScriptedLoadableModuleWidget.setup(self)
# Load widget from .ui file (created by Qt Designer).
# Additional widgets can be instantiated manually and added to self.layout.
uiWidget = slicer.util.loadUI(self.resourcePath('UI/LumpNav2.ui'))
self.layout.addWidget(uiWidget)
self.ui = slicer.util.childWidgetVariables(uiWidget)
# Set scene in MRML widgets. Make sure that in Qt designer the top-level qMRMLWidget's
# "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's.
# "setMRMLScene(vtkMRMLScene*)" slot.
uiWidget.setMRMLScene(slicer.mrmlScene)
# Create logic class. Logic implements all computations that should be possible to run
# in batch mode, without a graphical user interface.
self.logic = LumpNav2Logic()
self._updatingGUIFromParameterNode = True
self.logic.setup()
self._updatingGUIFromParameterNode = False
# Install event filter for main window.
self.eventFilter = LumpNavEventFilter(self)
slicer.util.mainWindow().installEventFilter(self.eventFilter)
# Set state of custom UI button
self.setCustomStyle(not self.getSlicerInterfaceVisible())
# Connections
# These connections ensure that we update parameter node when scene is closed
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.StartCloseEvent, self.onSceneStartClose)
self.addObserver(slicer.mrmlScene, slicer.mrmlScene.EndCloseEvent, self.onSceneEndClose)
# QT connections
self.ui.toolsCollapsibleButton.connect('contentsCollapsed(bool)', self.onToolsCollapsed)
self.ui.contouringCollapsibleButton.connect('contentsCollapsed(bool)', self.onContouringCollapsed)
self.ui.navigationCollapsibleButton.connect('contentsCollapsed(bool)', self.onNavigationCollapsed)
# Tool calibration
self.ui.cauteryCalibrationButton.connect('clicked()', self.onCauteryCalibrationButton)
self.ui.undoCauteryCalibrationButton.connect('clicked()', self.onUndoCauteryCalibrationClicked)
self.ui.needleMinusFiveButton.connect('clicked()', self.onNeedleMinusFiveClicked)
self.ui.needleMinusOneButton.connect('clicked()', self.onNeedleMinusOneClicked)
self.ui.needlePlusOneButton.connect('clicked()', self.onNeedlePlusOneClicked)
self.ui.needlePlusFiveButton.connect('clicked()', self.onNeedlePlusFiveClicked)
needleLength = self.logic.getNeedleLength()
self.ui.needleLengthLabel.text = f"Needle length: {needleLength:.0f}mm"
# contouring
self.ui.normalBrightnessButton.connect('toggled(bool)', self.onNormalBrightnessClicked)
self.ui.brightBrightnessButton.connect('toggled(bool)', self.onBrightBrightnessClicked)
self.ui.brightestBrightnessButton.connect('toggled(bool)', self.onBrightestBrightnessClicked)
self.ui.markPointsButton.connect('toggled(bool)', self.onMarkPointsToggled)
self.ui.deleteLastFiducialButton.connect('clicked()', self.onDeleteLastFiducialClicked)
self.ui.deleteAllFiducialsButton.connect('clicked()', self.onDeleteAllFiducialsClicked)
self.ui.selectPointsToEraseButton.connect('toggled(bool)', self.onErasePointsToggled)
self.ui.markPointCauteryTipButton.connect('clicked()', self.onMarkPointCauteryTipClicked)
self.ui.startStopRecordingButton.connect('toggled(bool)', self.onStartStopRecordingClicked)
self.ui.freezeUltrasoundButton.connect('toggled(bool)', self.onFreezeUltrasoundClicked)
self.pivotSamplingTimer.connect('timeout()', self.onPivotSamplingTimeout)
# navigation
self.ui.leftBreastButton.connect('clicked()', self.onLeftBreastButtonClicked)
self.ui.rightBreastButton.connect('clicked()', self.onRightBreastButtonClicked)
displayRulerEnabled = slicer.util.settingsValue(self.logic.DISPLAY_RULER_SETTING, True, converter=slicer.util.toBool)
self.ui.displayRulerButton.checked = displayRulerEnabled
self.ui.displayRulerButton.connect('toggled(bool)', self.onDisplayRulerButtonClicked)
displayDistanceEnabled = slicer.util.settingsValue(self.logic.DISPLAY_DISTANCE_SETTING, True, converter=slicer.util.toBool)
self.ui.displayDistanceButton.checked = displayDistanceEnabled
self.ui.displayDistanceButton.connect('toggled(bool)', self.onDisplayDistanceClicked)
self.ui.increaseDistanceFontSizeButton.connect('clicked()', self.onIncreaseDistanceFontSizeClicked)
self.ui.decreaseDistanceFontSizeButton.connect('clicked()', self.onDecreaseDistanceFontSizeClicked)
self.ui.leftAutoCenterCameraButton.connect('toggled(bool)', self.onLeftAutoCenterCameraButtonClicked)
self.ui.rightAutoCenterCameraButton.connect('toggled(bool)', self.onRightAutoCenterCameraButtonClicked)
self.ui.bottomAutoCenterCameraButton.connect('toggled(bool)', self.onBottomAutoCenterCameraButtonClicked)
self.ui.leftCauteryCameraButton.connect('toggled(bool)', self.onLeftCauteryCameraButtonClicked)
self.ui.rightCauteryCameraButton.connect('toggled(bool)', self.onRightCauteryCameraButtonClicked)
self.ui.bottomCauteryCameraButton.connect('toggled(bool)', self.onBottomCauteryCameraButtonClicked)
self.ui.deleteLastFiducialNavigationButton.connect('clicked()', self.onDeleteLastFiducialClicked)
cauteryToolSelected = slicer.util.settingsValue(self.logic.CAUTERY_MODEL_SELECTED, True, converter=slicer.util.toBool)
self.ui.toolModelButton.setChecked(cauteryToolSelected)
self.ui.toolModelButton.connect('toggled(bool)', self.onToolModelClicked)
self.ui.threeDViewButton.connect('toggled(bool)', self.onDual3DViewButton)
breachMarkupsDisplayEnabled = slicer.util.settingsValue(self.logic.BREACH_MARKUPS_DISPLAY_SETTING, True, converter=slicer.util.toBool)
self.ui.breachLocationButton.checked = breachMarkupsDisplayEnabled
self.ui.breachLocationButton.connect('toggled(bool)', self.onBreachLocationButtonClicked)
self.ui.deleteTumorBreachButton.connect('clicked()', self.onDeleteTumorBreachButtonClicked)
self.ui.increaseBreachFiducialSize.connect('clicked()', self.onIncreaseBreachFiducialSize)
self.ui.decreaseBreachFiducialSize.connect('clicked()', self.onDecreaseBreachFiducialSize)
# Event recording
self.ui.eventTable.setSelectionBehavior(qt.QAbstractItemView.SelectRows)
self.ui.eventTable.connect('cellChanged(int, int)', self.onEventTableChanged)
self.ui.eventTable.connect('itemSelectionChanged()', self.onEventSelectionChanged)
self.ui.addEventButton.connect('clicked()', self.onAddEventButtonClicked)
self.ui.deleteEventButton.connect('clicked()', self.onDeleteEventButtonClicked)
self.ui.eventTableExportButton.connect('clicked()', self.onEventTableExportClicked)
# settings panel
self.ui.customUiButton.connect('toggled(bool)', self.onCustomUiClicked)
self.ui.startPlusButton.connect('toggled(bool)', self.onStartPlusClicked)
self.ui.displayRASButton.connect('toggled(bool)', self.onDisplayRASClicked)
self.ui.displayCauteryStateButton.connect('toggled(bool)', self.onDisplayCauteryStateClicked)
needleVisibilitySetting = slicer.util.settingsValue(self.logic.NEEDLE_VISIBILITY_SETTING, True, converter=slicer.util.toBool)
self.ui.needleVisibilityButton.checked = needleVisibilitySetting
self.ui.needleVisibilityButton.connect('toggled(bool)', self.onNeedleVisibilityToggled)
self.ui.trackingSequenceBrowserButton.connect('toggled(bool)', self.onTrackingSequenceBrowser)
cauteryVisible = slicer.util.settingsValue(self.logic.CAUTERY_VISIBILITY_SETTING, True, converter=slicer.util.toBool)
self.ui.cauteryVisibilityButton.checked = cauteryVisible
self.ui.cauteryVisibilityButton.connect('toggled(bool)', self.onCauteryVisibilityToggled)
warningSoundEnabled = slicer.util.settingsValue(self.logic.WARNING_SOUND_SETTING, True, converter=slicer.util.toBool)
self.ui.warningSoundButton.checked = warningSoundEnabled
self.ui.warningSoundButton.connect('toggled(bool)', self.onWarningSoundToggled)
breachMarkupsProximityThreshold = slicer.util.settingsValue(self.logic.BREACH_MARKUPS_PROXIMITY_THRESHOLD, 1, converter=lambda x: int(x))
self.ui.breachMarkupsThresholdSpinBox.value = breachMarkupsProximityThreshold
self.ui.breachMarkupsThresholdSpinBox.connect('valueChanged(int)', self.onBreachMarkupsProximityChanged)
self.ui.exitButton.connect('clicked()', self.onExitButtonClicked)
self.ui.saveSceneButton.connect('clicked()', self.onSaveSceneClicked)
lastSavePath = slicer.util.settingsValue(self.SAVE_FOLDER_SETTING, os.path.dirname(slicer.util.modulePath(self.logic.moduleName)))
self.ui.saveFolderSelector.directory = lastSavePath
self.ui.saveFolderSelector.connect('directoryChanged(const QString)', self.onSavePathChanged)
lastHostname = slicer.util.settingsValue(self.logic.HOSTNAME_SETTING, "")
if lastHostname != "":
self.ui.hostnameLineEdit.text = lastHostname
self.ui.hostnameLineEdit.connect('editingFinished()', self.onHostnameChanged)
configFilepath = slicer.util.settingsValue(self.logic.CONFIG_FILE_SETTING, self.logic.resourcePath(self.logic.CONFIG_FILE_DEFAULT))
self.ui.plusConfigFileSelector.currentPath = configFilepath
self.ui.plusConfigFileSelector.connect('currentPathChanged(const QString)', self.onPlusConfigFileChanged)
needleLengthOffset = slicer.util.settingsValue(
self.logic.NEEDLE_LENGTH_OFFSET_SETTING, self.logic.NEEDLE_LENGTH_OFFSET_DEFAULT, converter=lambda x: float(x)
)
if needleLengthOffset:
self.ui.needleLengthOffsetSpinBox.value = needleLengthOffset
self.ui.needleLengthOffsetSpinBox.connect('valueChanged(double)', self.onNeedleLengthOffsetChanged)
self.ui.segmentationVisibility.connect('toggled(bool)', self.onSegmentationVisibilityToggled)
# Add custom layouts
self.logic.addCustomLayouts()
# Make sure parameter node is initialized (needed for module reload)
self.initializeParameterNode()
def onCauteryCalibrationButton(self):
logging.info('onCauteryCalibrationButton')
cauteryToNeedle = self._parameterNode.GetNodeReference(self.logic.CAUTERY_TO_NEEDLE)
cauteryTipToCautery = self._parameterNode.GetNodeReference(self.logic.CAUTERYTIP_TO_CAUTERY)
# Save previous pivot calibration to parameter node
if self.pivotCalibrationResultNode:
lastPivotCalibration = self._parameterNode.GetNodeReference(self.LAST_PIVOT_CALIBRATION_RESULT)
if lastPivotCalibration is None:
lastPivotCalibration = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLLinearTransformNode", self.LAST_PIVOT_CALIBRATION_RESULT)
self._parameterNode.SetNodeReferenceID(self.LAST_PIVOT_CALIBRATION_RESULT, lastPivotCalibration.GetID())
pivotCalibrationResultMatrix = vtk.vtkMatrix4x4()
self.pivotCalibrationResultNode.GetMatrixTransformToParent(pivotCalibrationResultMatrix)
lastPivotCalibration.SetMatrixTransformToParent(pivotCalibrationResultMatrix)
self.startPivotCalibration(cauteryToNeedle, cauteryTipToCautery)
def startPivotCalibration(self, toolToReferenceTransformNode, toolTipToToolTransformNode):
self.pivotCalibrationMode = self.PIVOT_CALIBRATION
self.ui.cauteryCalibrationButton.setEnabled(False)
self.pivotCalibrationResultNode = toolTipToToolTransformNode
self.pivotCalibrationLogic.SetAndObserveTransformNode(toolToReferenceTransformNode)
self.pivotCalibrationStopTime = time.time() + self.PIVOT_CALIBRATION_TIME_SEC
self.pivotCalibrationLogic.SetRecordingState(True)
self.onPivotSamplingTimeout()
def onPivotSamplingTimeout(self):
remainingTime = self.pivotCalibrationStopTime - time.time()
self.ui.cauteryCalibrationLabel.setText("Calibrating for {0:.0f} more seconds".format(remainingTime))
if time.time() < self.pivotCalibrationStopTime:
self.pivotSamplingTimer.start() # continue
else:
self.onStopPivotCalibration() # calibration completed
def onStopPivotCalibration(self):
self.pivotCalibrationLogic.SetRecordingState(False)
self.ui.cauteryCalibrationButton.setEnabled(True)
if self.pivotCalibrationMode == self.PIVOT_CALIBRATION:
calibrationSuccess = self.pivotCalibrationLogic.ComputePivotCalibration()
else:
calibrationSuccess = self.pivotCalibrationLogic.ComputeSpinCalibration()
# TODO: check if this is cautery or needle calibration and use different thresholds
calibrationThresholdStr = slicer.util.settingsValue(
self.CAUTERY_CALIBRATION_THRESHOLD_SETTING, self.CAUTERY_CALIBRATION_THRESHOLD_DEFAULT)
calibrationThreshold = float(calibrationThresholdStr)
if not calibrationSuccess:
self.ui.cauteryCalibrationLabel.setText("Calibration failed: " + self.pivotCalibrationLogic.GetErrorText())
self.pivotCalibrationLogic.ClearToolToReferenceMatrices()
return
# Warning if RMSE is too high, but still use calibration
if self.pivotCalibrationLogic.GetPivotRMSE() >= calibrationThreshold:
self.ui.cauteryCalibrationLabel.setText("Warning: RMSE = {0:.2f} mm".format(self.pivotCalibrationLogic.GetPivotRMSE()))
else:
self.ui.cauteryCalibrationLabel.setText("Success, RMSE = {0:.2f} mm".format(self.pivotCalibrationLogic.GetPivotRMSE()))
toolTipToToolMatrix = vtk.vtkMatrix4x4()
self.pivotCalibrationLogic.GetToolTipToToolMatrix(toolTipToToolMatrix)
self.pivotCalibrationLogic.ClearToolToReferenceMatrices()
self.pivotCalibrationResultNode.SetMatrixTransformToParent(toolTipToToolMatrix)
lastPivotCalibration = self._parameterNode.GetNodeReference(self.LAST_PIVOT_CALIBRATION_RESULT)
if lastPivotCalibration is not None:
self.ui.undoCauteryCalibrationButton.enabled = True
# Save calibration result so this calibration will be loaded in the next session automatically
pivotCalibrationResultName = self.pivotCalibrationResultNode.GetName()
pivotCalibrationFileWithPath = self.resourcePath(pivotCalibrationResultName + ".h5")
slicer.util.saveNode(self.pivotCalibrationResultNode, pivotCalibrationFileWithPath)
if self.pivotCalibrationMode == self.PIVOT_CALIBRATION:
logging.info("Pivot calibration completed. Tool: {0}. RMSE = {1:.2f} mm".format(
self.pivotCalibrationResultNode.GetName(), self.pivotCalibrationLogic.GetPivotRMSE()))
else:
logging.info("Spin calibration completed.")
def onUndoCauteryCalibrationClicked(self):
logging.info("onUndoCauteryCalibrationClicked")
self.ui.undoCauteryCalibrationButton.enabled = False
# Replace current calibration with previous one and save
lastPivotCalibration = self._parameterNode.GetNodeReference(self.LAST_PIVOT_CALIBRATION_RESULT)
lastPivotCalibrationMatrix = vtk.vtkMatrix4x4()
lastPivotCalibration.GetMatrixTransformToParent(lastPivotCalibrationMatrix)
self.pivotCalibrationResultNode.SetMatrixTransformToParent(lastPivotCalibrationMatrix)
pivotCalibrationResultName = self.pivotCalibrationResultNode.GetName()
pivotCalibrationFileWithPath = self.resourcePath(pivotCalibrationResultName + ".h5")
slicer.util.saveNode(self.pivotCalibrationResultNode, pivotCalibrationFileWithPath)
self.ui.cauteryCalibrationLabel.setText("Pivot calibration reverted")
def onNeedleMinusFiveClicked(self):
logging.info("onNeedleMinusFiveClicked")
self.onChangeNeedleLength(-5)
def onNeedleMinusOneClicked(self):
logging.info("onNeedleMinusOneClicked")
self.onChangeNeedleLength(-1)
def onNeedlePlusOneClicked(self):
logging.info("onNeedlePlusOneClicked")
self.onChangeNeedleLength(1)
def onNeedlePlusFiveClicked(self):
logging.info("onNeedlePlusFiveClicked")
self.onChangeNeedleLength(5)
def onChangeNeedleLength(self, diff):
currentOffset = slicer.util.settingsValue(
self.logic.NEEDLE_LENGTH_OFFSET_SETTING, self.logic.NEEDLE_LENGTH_OFFSET_DEFAULT, converter=lambda x: float(x)
)
self.ui.needleLengthOffsetSpinBox.setValue(currentOffset - diff)
def onNeedleLengthOffsetChanged(self, value):
logging.info(f"onNeedleLengthOffsetChanged({value})")
settings = qt.QSettings()
settings.setValue(self.logic.NEEDLE_LENGTH_OFFSET_SETTING, value)
self.logic.setNeedleModel()
self.updateNeedleLengthLabel()
def updateNeedleLengthLabel(self, caller=None, event=None):
needleLength = self.logic.getNeedleLength()
self.ui.needleLengthLabel.text = f"Needle length: {needleLength:.0f}mm"
def onExitButtonClicked(self):
mainwindow = slicer.util.mainWindow()
mainwindow.close()
def onSavePathChanged(self, path):
if path:
abspath = os.path.abspath(path)
self.ui.saveFolderSelector.directory = abspath
settings = qt.QSettings()
settings.setValue(self.SAVE_FOLDER_SETTING, abspath)
logging.info(f"onSavePathChanged({abspath})")
def onSaveSceneClicked(self): # common
#
# save the mrml scene to a temp directory, then zip it
#
qt.QApplication.setOverrideCursor(qt.Qt.WaitCursor)
sceneSaveDirectory = self.ui.saveFolderSelector.directory
sceneSaveDirectory = sceneSaveDirectory + "/" + self.logic.moduleName + "-" + time.strftime("%Y%m%d-%H%M%S")
logging.info("Saving scene to: {0}".format(sceneSaveDirectory))
if not os.access(sceneSaveDirectory, os.F_OK):
os.makedirs(sceneSaveDirectory)
applicationLogic = slicer.app.applicationLogic()
saveSuccess = applicationLogic.SaveSceneToSlicerDataBundleDirectory(sceneSaveDirectory, None)
qt.QApplication.restoreOverrideCursor()
if saveSuccess:
# Record time stamp of save
self.saveTime.Modified()
logging.info("Scene saved to: {0}".format(sceneSaveDirectory))
slicer.util.showStatusMessage(f"Scene saved to {sceneSaveDirectory}.", 5000)
else:
logging.error("Scene saving failed")
slicer.util.showStatusMessage(f"Failed to save scene to {sceneSaveDirectory}.", 5000)
def confirmExit(self):
msgBox = qt.QMessageBox()
msgBox.setStyleSheet(slicer.util.mainWindow().styleSheet)
msgBox.setWindowTitle("Confirm Exit")
msgBox.setText("Some data may not have been saved yet.")
msgBox.setInformativeText("Do you still want to exit?")
saveExitButton = msgBox.addButton("Save and Exit", qt.QMessageBox.DestructiveRole)
discardButton = msgBox.addButton("Discard and Exit", qt.QMessageBox.DestructiveRole)
cancelButton = msgBox.addButton("Cancel", qt.QMessageBox.RejectRole)
msgBox.setModal(True)
msgBox.exec()
if msgBox.clickedButton() == saveExitButton:
# Automatically save if changes were made since last save
if self._parameterNode.GetMTime() > self.saveTime.GetMTime():
self.onSaveSceneClicked()
slicer.util.infoDisplay(f"Scene saved to {self.ui.saveFolderSelector.directory}. Press OK to exit.", windowTitle="Save Scene")
else:
logging.info("No changes made since last save. Exiting.")
slicer.util.showStatusMessage("No changes made since last save. Exiting.", 5000)
slicer.util.infoDisplay("No changes made since last save. Press OK to exit.", windowTitle="Save Scene")
return True
if msgBox.clickedButton() == discardButton:
return True
return False
def onNeedleVisibilityToggled(self, toggled):
logging.info("onNeedleVisibilityToggled({})".format(toggled))
self.logic.setNeedleVisibility(toggled)
def onCauteryVisibilityToggled(self, toggled):
logging.info("onCauteryVisibilityToggled({})".format(toggled))
self.logic.setCauteryVisibility(toggled)
def onWarningSoundToggled(self, toggled):
logging.info("onWarningSoundToggled({})".format(toggled))
self.logic.setWarningSound(toggled)
def onToolsCollapsed(self, collapsed):
if not collapsed:
self.ui.contouringCollapsibleButton.collapsed = True
self.ui.navigationCollapsibleButton.collapsed = True
slicer.app.layoutManager().setLayout(self.logic.LAYOUT_2D3D)
viewNode = slicer.app.layoutManager().threeDWidget(0).mrmlViewNode()
if not self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeAutoCenter():
self.enableAutoCenterInViewNode(viewNode)
slicer.util.resetSliceViews()
def onContouringCollapsed(self, collapsed):
if not collapsed:
self.ui.toolsCollapsibleButton.collapsed = True
self.ui.navigationCollapsibleButton.collapsed = True
slicer.app.layoutManager().setLayout(6)
slicer.util.resetSliceViews()
def onNavigationCollapsed(self, collapsed):
"""
Called when the navigation tab is collapsed or expanded
"""
logging.info(f"onNavigationCollapsed({collapsed})")
if collapsed:
self.logic.setBreachWarningOn(False)
if self.ui.markPointsButton.checked:
self.ui.markPointsButton.setChecked(False)
self.logic.setMarkPoints(False)
if self.ui.selectPointsToEraseButton.checked:
self.ui.selectPointsToEraseButton.setChecked(False)
self.logic.setErasePoints(False)
else:
self.ui.toolsCollapsibleButton.collapsed = True
self.ui.contouringCollapsibleButton.collapsed = True
self.onDual3DViewButton(self.ui.threeDViewButton.checked)
# Set 3D view settings
layoutManager = slicer.app.layoutManager()
for i in range(layoutManager.threeDViewCount):
view = layoutManager.threeDWidget(i).mrmlViewNode()
view.SetOrientationMarkerType(view.OrientationMarkerTypeHuman)
view.SetOrientationMarkerSize(view.OrientationMarkerSizeLarge)
view.SetBoxVisible(False)
view.SetAxisLabelsVisible(False)
interactionNode = slicer.app.applicationLogic().GetInteractionNode()
interactionNode.SetCurrentInteractionMode(interactionNode.ViewTransform)
self.logic.setBreachWarningOn(True)
self.updateGUIFromParameterNode()
def onDual3DViewButton(self, toggled):
logging.info(f"onDual3DViewButton({toggled})")
self.ui.threeDViewButton.checked = toggled
if toggled:
self.ui.threeDViewButton.text = "Triple 3D View"
self.ui.bottomAutoCenterCameraButton.setEnabled(False)
self.ui.bottomCauteryCameraButton.setEnabled(False)
slicer.app.layoutManager().setLayout(self.logic.LAYOUT_DUAL3D)
else:
self.ui.threeDViewButton.text = "Dual 3D View"
self.ui.bottomAutoCenterCameraButton.setEnabled(True)
self.ui.bottomCauteryCameraButton.setEnabled(True)
slicer.app.layoutManager().setLayout(self.logic.LAYOUT_TRIPLE3D)
def onStartStopRecordingClicked(self, toggled):
if toggled:
self.ui.startStopRecordingButton.text = "Stop Ultrasound Recording"
else:
self.ui.startStopRecordingButton.text = "Start Ultrasound Recording"
self.logic.onUltrasoundSequenceBrowserClicked(toggled)
reconstructionVolume = self._parameterNode.GetNodeReference(self.logic.RECONSTRUCTION_VOLUME)
if self.ui.segmentationThresholdSlider.mrmlVolumeNode() != reconstructionVolume:
self.ui.segmentationThresholdSlider.setMRMLVolumeNode(reconstructionVolume)
self.ui.segmentationThresholdSlider.setThresholdBounds(200, 254) # TODO: magic numbers
def onBreachLocationButtonClicked(self, toggled):
logging.info(f"onBreachLocationButtonClicked({toggled})")
settings = qt.QSettings()
settings.setValue(self.logic.BREACH_MARKUPS_DISPLAY_SETTING, toggled)
parameterNode = self._parameterNode
breachMarkups_Needle = parameterNode.GetNodeReference(self.logic.BREACH_MARKUPS_NEEDLE)
if toggled:
breachMarkups_Needle.SetDisplayVisibility(1)
else:
breachMarkups_Needle.SetDisplayVisibility(0)
def onIncreaseBreachFiducialSize(self):
logging.info("onIncreaseBreachFiducialSize")
previousFontSize = slicer.util.settingsValue(self.logic.BREACH_MARKUPS_SIZE_SETTING,
self.logic.BREACH_MARKUPS_SIZE_DEFAULT,
converter=lambda x: float(x))
newFontSize = previousFontSize + 1
settings = qt.QSettings()
settings.setValue(self.logic.BREACH_MARKUPS_SIZE_SETTING, newFontSize)
self.logic.setBreachFiducialSize(newFontSize)
def onDecreaseBreachFiducialSize(self):
logging.info("onDecreaseBreachFiducialSize")
previousFontSize = slicer.util.settingsValue(self.logic.BREACH_MARKUPS_SIZE_SETTING,
self.logic.BREACH_MARKUPS_SIZE_DEFAULT,
converter=lambda x: float(x))
newFontSize = previousFontSize - 1
settings = qt.QSettings()
settings.setValue(self.logic.BREACH_MARKUPS_SIZE_SETTING, newFontSize)
self.logic.setBreachFiducialSize(newFontSize)
def onDeleteTumorBreachButtonClicked(self):
logging.info("onDeleteTumorBreachButtonClicked")
parameterNode = self._parameterNode
breachMarkups_Needle = parameterNode.GetNodeReference(self.logic.BREACH_MARKUPS_NEEDLE)
breachMarkups_Needle.RemoveAllControlPoints()
def onDisplayRulerButtonClicked(self, toggled):
logging.info(f"onDisplayRulerButtonClicked({toggled})")
settings = qt.QSettings()
settings.setValue(self.logic.DISPLAY_RULER_SETTING, toggled)
self.logic.setRulerVisibility(toggled)
def onDisplayDistanceClicked(self, toggled):
logging.info("onDisplayDistanceClicked({})".format(toggled))
settings = qt.QSettings()
settings.setValue(self.logic.DISPLAY_DISTANCE_SETTING, toggled)
self.logic.setRulerDistanceVisibility(toggled)
def onIncreaseDistanceFontSizeClicked(self):
logging.info("onIncreaseDistanceFontSizeClicked")
previousFontSize = slicer.util.settingsValue(self.logic.RULER_FONT_SIZE,
self.logic.RULER_DISTANCE_DEFAULT_FONT_SIZE,
converter=lambda x: float(x))
newFontSize = previousFontSize + 1
settings = qt.QSettings()
settings.setValue(self.logic.RULER_FONT_SIZE, newFontSize)
self.logic.setRulerDistanceFontSize(newFontSize)
def onDecreaseDistanceFontSizeClicked(self):
logging.info("onDecreaseDistanceFontSizeClicked")
previousFontSize = slicer.util.settingsValue(self.logic.RULER_FONT_SIZE,
self.logic.RULER_DISTANCE_DEFAULT_FONT_SIZE,
converter=lambda x: float(x))
newFontSize = previousFontSize - 1
settings = qt.QSettings()
settings.setValue(self.logic.RULER_FONT_SIZE, newFontSize)
self.logic.setRulerDistanceFontSize(newFontSize)
def onToolModelClicked(self, toggled):
logging.info('onToolModelClicked')
if toggled:
self.ui.toolModelButton.text = "Stick Model"
else:
self.ui.toolModelButton.text = "Cautery Model"
self.logic.setToolModelClicked(toggled)
def onBreachMarkupsProximityChanged(self, value):
logging.info(f"onBreachMarkupsProximityChanged({value})")
settings = qt.QSettings()
settings.setValue(self.logic.BREACH_MARKUPS_PROXIMITY_THRESHOLD, value)
def onFreezeUltrasoundClicked(self, toggled):
logging.info(f"onFreezeUltrasoundClicked({toggled})")
if toggled:
self.ui.freezeUltrasoundButton.text = "Un-Freeze"
else:
self.ui.freezeUltrasoundButton.text = "Freeze"
self.logic.setFreezeUltrasoundClicked(toggled)
def onPlusConfigFileChanged(self, configFilepath):
logging.info(f"onPlusConfigFileChanged({configFilepath})")
settings = qt.QSettings()
settings.setValue(self.logic.CONFIG_FILE_SETTING, configFilepath)
self.logic.setPlusConfigFile(configFilepath)
def onHostnameChanged(self):
newHostname = self.ui.hostnameLineEdit.text
settings = qt.QSettings()
settings.setValue(self.logic.HOSTNAME_SETTING, newHostname)
self.logic.setHostname(newHostname)
logging.info(f"onHostnameChanged({newHostname})")
def onStartPlusClicked(self, toggled):
logging.info(f"onStartPlusClicked({toggled})")
if toggled:
self.ui.startPlusButton.text = "Stop PLUS"
self.ui.plusConfigFileSelector.enabled = False
self.ui.hostnameLineEdit.enabled = False
else:
self.ui.startPlusButton.text = "Start PLUS"
self.ui.plusConfigFileSelector.enabled = True
self.ui.hostnameLineEdit.enabled = True
self.logic.setPlusServerClicked(toggled)
def onDisplayRASClicked(self, toggled):
logging.info(f"onDisplayRASClicked({toggled})")
parameterNode = self._parameterNode
RASMarkups = parameterNode.GetNodeReference(self.logic.RAS_MARKUPS)
if toggled:
RASMarkups.SetDisplayVisibility(1)
else:
RASMarkups.SetDisplayVisibility(0)
def onDisplayCauteryStateClicked(self, toggled):
logging.info("onDisplayCauteryStateClicked({})".format(toggled))
self.logic.setDisplayCauteryStateClicked(toggled)
def onCustomUiClicked(self, checked):
self.setCustomStyle(checked)
def onTrackingSequenceBrowser(self, toggled):
logging.info("onTrackingSequenceBrowserToggled({})".format(toggled))
self.logic.setTrackingSequenceBrowser(toggled)
def onUltrasoundSequenceBrowser(self, toggled):
logging.info("onUltrasoundSequenceBrowserToggled({})".format(toggled))
self.logic.onUltrasoundSequenceBrowserClicked(toggled)
def onNormalBrightnessClicked(self):
logging.info("onNormalBrightnessClicked")
self.logic.setBrightness(self.NORMAL_BRIGHTNESS)
def onBrightBrightnessClicked(self):
logging.info("onBrightBrightnessClicked")
self.logic.setBrightness(self.BRIGHT_BRIGHTNESS)
def onBrightestBrightnessClicked(self):
logging.info("onBrightestBrightnessClicked")
self.logic.setBrightness(self.BRIGHTEST_BRIGHTNESS)
def onMarkPointsToggled(self, toggled):
logging.info(f"onMarkPointsToggled({toggled})")
if self._updatingGui:
return
self._updatingGui = True
if toggled:
self.ui.selectPointsToEraseButton.setChecked(False)
self.logic.setMarkPoints(toggled)
self._updatingGui = False
def onErasePointsToggled(self, toggled):
logging.info(f"onErasePointsToggled({toggled})")
if self._updatingGui:
return
self._updatingGui = True
if toggled:
self.ui.markPointsButton.setChecked(False)
self.logic.setErasePoints(toggled)
self._updatingGui = False
def onMarkPointCauteryTipClicked(self):
logging.info("Mark point at cautery tip clicked")
self.logic.setMarkPointCauteryTipClicked()
def onDeleteLastFiducialClicked(self):
logging.info('onDeleteLastFiducialClicked')
tumorMarkups_Needle = self._parameterNode.GetNodeReference(self.logic.TUMOR_MARKUPS_NEEDLE)
numberOfPoints = tumorMarkups_Needle.GetNumberOfControlPoints()
self.logic.setDeleteLastFiducialClicked(numberOfPoints)
def onDeleteAllFiducialsClicked(self):
logging.info('onDeleteAllFiducialsClicked')
self.logic.setDeleteAllFiducialsClicked()
self.updateGUIFromParameterNode()
def onSegmentationVisibilityToggled(self, toggled):
logging.info("onSegmentationVisibilityToggled")
if toggled:
self.ui.segmentationVisibility.text = "Hide AI Segmentation"
else:
self.ui.segmentationVisibility.text = "Show AI Segmentation"
self.ui.segmentationThresholdSlider.enabled = toggled
self.logic.setSegmentationVisibility(toggled)
def getViewNode(self, viewName):
"""
Get the view node for the selected 3D view
"""
logging.debug("getViewNode")
viewNode = slicer.util.getFirstNodeByName(viewName)
return viewNode
def onLeftBreastButtonClicked(self):
logging.info(f"onLeftButtonClicked()")
cameraNode1 = self.getCamera('View1')
cameraNode2 = self.getCamera('View2')
cameraNode3 = self.getCamera('View3')
# TODO: Don't use magic numbers
cameraNode1.SetPosition(-242.0042709749552, 331.2026122150233, -36.6617924419265)
cameraNode1.SetViewUp(0.802637869051714, 0.5959392355990031, -0.025077452777348814)
cameraNode1.SetFocalPoint(0.0, 0.0, 0.0)
cameraNode1.SetViewAngle(25.0)
cameraNode1.ResetClippingRange()
cameraNode2.SetPosition(0.0, 500.0, 0.0)
cameraNode2.SetViewUp(1.0, 0.0, 0.0)
cameraNode2.SetFocalPoint(0.0, 0.0, 0.0)
cameraNode2.SetViewAngle(25.0)
cameraNode2.ResetClippingRange()
cameraNode3.SetPosition(0.0, 0.0, -500.0)
cameraNode3.SetViewUp(0.0, 0.0, 0.0)
cameraNode3.SetFocalPoint(0.0, 0.0, 0.0)
cameraNode3.SetViewAngle(20.0)
cameraNode3.ResetClippingRange()
# Enable auto-center
for i in range(slicer.app.layoutManager().threeDViewCount):
viewNode = slicer.app.layoutManager().threeDWidget(i).mrmlViewNode()
if not self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeAutoCenter():
self.enableAutoCenterInViewNode(viewNode)
self.updateGUIButtons()
def onRightBreastButtonClicked(self):
logging.info(f"onRightButtonClicked()")
cameraNode1 = self.getCamera('View1')
cameraNode2 = self.getCamera('View2')
cameraNode3 = self.getCamera('View3')
# TODO: magic numbers
cameraNode1.SetPosition(275.4944476449362, 309.31555951664205, 42.169967768629164)
cameraNode1.SetViewUp(-0.749449157051234, 0.661802245162601, -0.018540477149624528)
cameraNode1.SetFocalPoint(0.0, 0.0, 0.0)
cameraNode1.SetViewAngle(25.0)
cameraNode1.ResetClippingRange()
cameraNode2.SetPosition(0.0, 500.0, 0.0)
cameraNode2.SetViewUp(-1.0, 0.0, 0.0)
cameraNode2.SetFocalPoint(0.0, 0.0, 0.0)
cameraNode2.SetViewAngle(25.0)
cameraNode2.ResetClippingRange()
cameraNode3.SetPosition(0.0, 0.0, -500.0)
cameraNode3.SetViewUp(0.0, 0.0, 0.0)
cameraNode3.SetFocalPoint(0.0, 0.0, 0.0)
cameraNode3.SetViewAngle(20.0)
cameraNode3.ResetClippingRange()
# Enable auto-center
for i in range(slicer.app.layoutManager().threeDViewCount):
viewNode = slicer.app.layoutManager().threeDWidget(i).mrmlViewNode()
if not self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeAutoCenter():
self.enableAutoCenterInViewNode(viewNode)
self.updateGUIButtons()
def onLeftCauteryCameraButtonClicked(self, toggled):
logging.info("onLeftFollowCameraButtonClicked")
self.onCauteryCameraButtonClicked("View1")
def onRightCauteryCameraButtonClicked(self, toggled):
logging.info("onRightFollowCameraButtonClicked")
self.onCauteryCameraButtonClicked("View2")
def onBottomCauteryCameraButtonClicked(self, toggled):
logging.info("onBottomFollowCameraButtonClicked")
self.onCauteryCameraButtonClicked("View3")
def onCauteryCameraButtonClicked(self, viewName):
viewNode = self.getViewNode(viewName)
if self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeBullseye():
self.disableBullseyeInViewNode(viewNode)
self.enableAutoCenterInViewNode(viewNode)
else:
self.enableBullseyeInViewNode(viewNode)
self.updateGUIButtons()
def disableBullseyeInViewNode(self, viewNode):
if self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeBullseye():
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).bullseyeStop()
def enableBullseyeInViewNode(self, viewNode):
self.disableViewpointInViewNode(viewNode)
cauteryCameraToCautery = self._parameterNode.GetNodeReference(self.logic.CAUTERYCAMERA_TO_CAUTERY)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).setViewNode(viewNode)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).bullseyeSetTransformNode(cauteryCameraToCautery)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).bullseyeStart()
def onLeftAutoCenterCameraButtonClicked(self, toggled):
logging.info("onLeftAutoCenterButtonClicked")
self.onAutoCenterButtonClicked('View1')
def onRightAutoCenterCameraButtonClicked(self, toggled):
logging.info("onRightAutoCenterCameraButtonClicked")
self.onAutoCenterButtonClicked('View2')
def onBottomAutoCenterCameraButtonClicked(self, toggled):
logging.info("onBottomAutoCenterCameraButtonClicked")
self.onAutoCenterButtonClicked('View3')
def onAutoCenterButtonClicked(self, viewName):
viewNode = self.getViewNode(viewName)
if self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeAutoCenter():
self.disableAutoCenterInViewNode(viewNode)
else:
self.enableAutoCenterInViewNode(viewNode)
self.updateGUIButtons()
def disableAutoCenterInViewNode(self, viewNode):
if self.logic.viewpointLogic.getViewpointForViewNode(viewNode).isCurrentModeAutoCenter():
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterStop()
def enableAutoCenterInViewNode(self, viewNode):
self.disableViewpointInViewNode(viewNode)
tumorModel = self._parameterNode.GetNodeReference(self.logic.TUMOR_MODEL)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).setViewNode(viewNode)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterSetSafeXMinimum(-self.VIEW_COORD_WIDTH_LIMIT)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterSetSafeXMaximum(self.VIEW_COORD_WIDTH_LIMIT)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterSetSafeYMinimum(-self.VIEW_COORD_HEIGHT_LIMIT)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterSetSafeYMaximum(self.VIEW_COORD_HEIGHT_LIMIT)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterSetModelNode(tumorModel)
self.logic.viewpointLogic.getViewpointForViewNode(viewNode).autoCenterStart()
def disableViewpointInViewNode(self, viewNode):
logging.debug("disableViewpointInViewNode")
self.disableAutoCenterInViewNode(viewNode)
self.disableBullseyeInViewNode(viewNode)
def updateGUIButtons(self):
# Left view node
autoCenterBlockSignalState = self.ui.leftAutoCenterCameraButton.blockSignals(True)
bullseyeBlockSignalState = self.ui.leftCauteryCameraButton.blockSignals(True)
leftViewNode = self.getViewNode("View1")
if self.logic.viewpointLogic.getViewpointForViewNode(leftViewNode).isCurrentModeAutoCenter():
self.ui.leftAutoCenterCameraButton.setChecked(True)
self.ui.leftCauteryCameraButton.setChecked(False)
elif self.logic.viewpointLogic.getViewpointForViewNode(leftViewNode).isCurrentModeBullseye():
self.ui.leftAutoCenterCameraButton.setChecked(False)
self.ui.leftCauteryCameraButton.setChecked(True)
else:
self.ui.leftAutoCenterCameraButton.setChecked(False)
self.ui.leftCauteryCameraButton.setChecked(False)
self.ui.leftAutoCenterCameraButton.blockSignals(autoCenterBlockSignalState)
self.ui.leftCauteryCameraButton.blockSignals(bullseyeBlockSignalState)
# Right view node
autoCenterBlockSignalState = self.ui.rightAutoCenterCameraButton.blockSignals(True)
bullseyeBlockSignalState = self.ui.rightCauteryCameraButton.blockSignals(True)
rightViewNode = self.getViewNode("View2")
if self.logic.viewpointLogic.getViewpointForViewNode(rightViewNode).isCurrentModeAutoCenter():
self.ui.rightAutoCenterCameraButton.setChecked(True)
self.ui.rightCauteryCameraButton.setChecked(False)
elif self.logic.viewpointLogic.getViewpointForViewNode(rightViewNode).isCurrentModeBullseye():
self.ui.rightAutoCenterCameraButton.setChecked(False)
self.ui.rightCauteryCameraButton.setChecked(True)
else:
self.ui.rightAutoCenterCameraButton.setChecked(False)
self.ui.rightCauteryCameraButton.setChecked(False)
self.ui.rightAutoCenterCameraButton.blockSignals(autoCenterBlockSignalState)
self.ui.rightCauteryCameraButton.blockSignals(bullseyeBlockSignalState)
# Bottom view node
autoCenterBlockSignalState = self.ui.bottomAutoCenterCameraButton.blockSignals(True)
bullseyeBlockSignalState = self.ui.bottomCauteryCameraButton.blockSignals(True)