Created
May 26, 2020 15:45
-
-
Save mikebind/7e9cb1ac13c3cb694cf5d3932008edf9 to your computer and use it in GitHub Desktop.
Code which can be used to demonstrate Slicer crash on tab-autocomplete on my machine. All of the code is auto-generated by the extension wizard except for lines 82-86, which I added.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import unittest | |
import logging | |
import vtk, qt, ctk, slicer | |
from slicer.ScriptedLoadableModule import * | |
from slicer.util import VTKObservationMixin | |
# | |
# AutoCompleteCrash | |
# | |
class AutoCompleteCrash(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 = "AutoCompleteCrash" # TODO: make this more human readable by adding spaces | |
self.parent.categories = ["Examples"] # TODO: set categories (folders where the module shows up in the module selector) | |
self.parent.dependencies = [] # TODO: add here list of module names that this module requires | |
self.parent.contributors = ["John Doe (AnyWare Corp.)"] # TODO: replace with "Firstname Lastname (Organization)" | |
self.parent.helpText = """ | |
This is an example of scripted loadable module bundled in an extension. | |
""" # TODO: update with short description of the module | |
self.parent.helpText += self.getDefaultModuleDocumentationLink() # TODO: verify that the default URL is correct or change it to the actual documentation | |
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. | |
""" # TODO: replace with organization, grant and thanks. | |
# | |
# AutoCompleteCrashWidget | |
# | |
class AutoCompleteCrashWidget(ScriptedLoadableModuleWidget, VTKObservationMixin): | |
"""Uses ScriptedLoadableModuleWidget base class, available at: | |
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py | |
""" | |
def __init__(self, parent=None): | |
""" | |
Called when the user opens the module the first time and the widget is initialized. | |
""" | |
ScriptedLoadableModuleWidget.__init__(self, parent) | |
VTKObservationMixin.__init__(self) # needed for parameter node observation | |
self.logic = None | |
self._parameterNode = None | |
def setup(self): | |
""" | |
Called when the user opens the module the first time and the widget is initialized. | |
""" | |
ScriptedLoadableModuleWidget.setup(self) | |
# Load widget from .ui file (created by Qt Designer) | |
uiWidget = slicer.util.loadUI(self.resourcePath('UI/AutoCompleteCrash.ui')) | |
self.layout.addWidget(uiWidget) | |
self.ui = slicer.util.childWidgetVariables(uiWidget) | |
# Set scene in MRML widgets. Make sure that in Qt designer | |
# "mrmlSceneChanged(vtkMRMLScene*)" signal in is connected to each MRML widget's. | |
# "setMRMLScene(vtkMRMLScene*)" slot. | |
uiWidget.setMRMLScene(slicer.mrmlScene) | |
# Example of adding widgets dynamically (without Qt designer). | |
# This approach is not recommended, but only shown as an illustrative example. | |
parametersCollapsibleButton = ctk.ctkCollapsibleButton() | |
parametersCollapsibleButton.text = "More" | |
parametersCollapsibleButton.collapsed = True | |
self.layout.addWidget(parametersCollapsibleButton) | |
parametersFormLayout = qt.QFormLayout(parametersCollapsibleButton) | |
self.invertedOutputSelector = slicer.qMRMLNodeComboBox() | |
self.invertedOutputSelector.nodeTypes = ["vtkMRMLScalarVolumeNode"] | |
self.invertedOutputSelector.addEnabled = True | |
self.invertedOutputSelector.removeEnabled = True | |
self.invertedOutputSelector.noneEnabled = True | |
self.invertedOutputSelector.setMRMLScene(slicer.mrmlScene) | |
self.invertedOutputSelector.setToolTip("Result with inverted threshold will be written into this volume") | |
parametersFormLayout.addRow("Inverted output volume: ", self.invertedOutputSelector) | |
table = qt.QTableWidget() | |
table.setRowCount(5) | |
table.setColumnCount(3) | |
self.table = table | |
parametersFormLayout.addRow(self.table) | |
# Create a new parameterNode | |
# This parameterNode stores all user choices in parameter values, node selections, etc. | |
# so that when the scene is saved and reloaded, these settings are restored. | |
self.logic = AutoCompleteCrashLogic() | |
self.ui.parameterNodeSelector.addAttribute("vtkMRMLScriptedModuleNode", "ModuleName", self.moduleName) | |
self.setParameterNode(self.logic.getParameterNode()) | |
# Connections | |
self.ui.parameterNodeSelector.connect('currentNodeChanged(vtkMRMLNode*)', self.setParameterNode) | |
self.ui.applyButton.connect('clicked(bool)', self.onApplyButton) | |
# These connections ensure that whenever user changes some settings on the GUI, that is saved in the MRML scene | |
# (in the selected parameter node). | |
self.ui.inputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) | |
self.ui.outputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) | |
self.ui.imageThresholdSliderWidget.connect("valueChanged(double)", self.updateParameterNodeFromGUI) | |
self.ui.invertOutputCheckBox.connect("toggled(bool)", self.updateParameterNodeFromGUI) | |
self.invertedOutputSelector.connect("currentNodeChanged(vtkMRMLNode*)", self.updateParameterNodeFromGUI) | |
# Initial GUI update | |
self.updateGUIFromParameterNode() | |
def cleanup(self): | |
""" | |
Called when the application closes and the module widget is destroyed. | |
""" | |
self.removeObservers() | |
def setParameterNode(self, inputParameterNode): | |
""" | |
Adds observers to the selected parameter node. Observation is needed because when the | |
parameter node is changed then the GUI must be updated immediately. | |
""" | |
if inputParameterNode: | |
self.logic.setDefaultParameters(inputParameterNode) | |
# Set parameter node in the parameter node selector widget | |
wasBlocked = self.ui.parameterNodeSelector.blockSignals(True) | |
self.ui.parameterNodeSelector.setCurrentNode(inputParameterNode) | |
self.ui.parameterNodeSelector.blockSignals(wasBlocked) | |
if inputParameterNode == self._parameterNode: | |
# No change | |
return | |
# Unobserve previusly selected parameter node and add an observer to the newly selected. | |
# Changes of parameter node are observed so that whenever parameters are changed by a script or any other module | |
# those are reflected immediately in the GUI. | |
if self._parameterNode is not None: | |
self.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) | |
if inputParameterNode is not None: | |
self.addObserver(inputParameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode) | |
self._parameterNode = inputParameterNode | |
# Initial GUI update | |
self.updateGUIFromParameterNode() | |
def updateGUIFromParameterNode(self, caller=None, event=None): | |
""" | |
This method is called whenever parameter node is changed. | |
The module GUI is updated to show the current state of the parameter node. | |
""" | |
# Disable all sections if no parameter node is selected | |
self.ui.basicCollapsibleButton.enabled = self._parameterNode is not None | |
self.ui.advancedCollapsibleButton.enabled = self._parameterNode is not None | |
if self._parameterNode is None: | |
return | |
# Update each widget from parameter node | |
# Need to temporarily block signals to prevent infinite recursion (MRML node update triggers | |
# GUI update, which triggers MRML node update, which triggers GUI update, ...) | |
wasBlocked = self.ui.inputSelector.blockSignals(True) | |
self.ui.inputSelector.setCurrentNode(self._parameterNode.GetNodeReference("InputVolume")) | |
self.ui.inputSelector.blockSignals(wasBlocked) | |
wasBlocked = self.ui.outputSelector.blockSignals(True) | |
self.ui.outputSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputVolume")) | |
self.ui.outputSelector.blockSignals(wasBlocked) | |
wasBlocked = self.invertedOutputSelector.blockSignals(True) | |
self.invertedOutputSelector.setCurrentNode(self._parameterNode.GetNodeReference("OutputVolumeInverse")) | |
self.invertedOutputSelector.blockSignals(wasBlocked) | |
wasBlocked = self.ui.imageThresholdSliderWidget.blockSignals(True) | |
self.ui.imageThresholdSliderWidget.value = float(self._parameterNode.GetParameter("Threshold")) | |
self.ui.imageThresholdSliderWidget.blockSignals(wasBlocked) | |
wasBlocked = self.ui.invertOutputCheckBox.blockSignals(True) | |
self.ui.invertOutputCheckBox.checked = (self._parameterNode.GetParameter("Invert") == "true") | |
self.ui.invertOutputCheckBox.blockSignals(wasBlocked) | |
# Update buttons states and tooltips | |
if self._parameterNode.GetNodeReference("InputVolume") and self._parameterNode.GetNodeReference("OutputVolume"): | |
self.ui.applyButton.toolTip = "Compute output volume" | |
self.ui.applyButton.enabled = True | |
else: | |
self.ui.applyButton.toolTip = "Select input and output volume nodes" | |
self.ui.applyButton.enabled = False | |
def updateParameterNodeFromGUI(self, caller=None, event=None): | |
""" | |
This method is called when the user makes any change in the GUI. | |
The changes are saved into the parameter node (so that they are restored when the scene is saved and loaded). | |
""" | |
if self._parameterNode is None: | |
return | |
self._parameterNode.SetNodeReferenceID("InputVolume", self.ui.inputSelector.currentNodeID) | |
self._parameterNode.SetNodeReferenceID("OutputVolume", self.ui.outputSelector.currentNodeID) | |
self._parameterNode.SetParameter("Threshold", str(self.ui.imageThresholdSliderWidget.value)) | |
self._parameterNode.SetParameter("Invert", "true" if self.ui.invertOutputCheckBox.checked else "false") | |
self._parameterNode.SetNodeReferenceID("OutputVolumeInverse", self.invertedOutputSelector.currentNodeID) | |
def onApplyButton(self): | |
""" | |
Run processing when user clicks "Apply" button. | |
""" | |
try: | |
self.logic.run(self.ui.inputSelector.currentNode(), self.ui.outputSelector.currentNode(), | |
self.ui.imageThresholdSliderWidget.value, self.ui.invertOutputCheckBox.checked) | |
if self.invertedOutputSelector.currentNode(): | |
# If additional output volume is selected then result with inverted threshold is written there | |
self.logic.run(self.ui.inputSelector.currentNode(), self.invertedOutputSelector.currentNode(), | |
self.ui.imageThresholdSliderWidget.value, not self.ui.invertOutputCheckBox.checked, showResult=False) | |
except Exception as e: | |
slicer.util.errorDisplay("Failed to compute results: "+str(e)) | |
import traceback | |
traceback.print_exc() | |
# | |
# AutoCompleteCrashLogic | |
# | |
class AutoCompleteCrashLogic(ScriptedLoadableModuleLogic): | |
"""This class should implement all the actual | |
computation done by your module. The interface | |
should be such that other python code can import | |
this class and make use of the functionality without | |
requiring an instance of the Widget. | |
Uses ScriptedLoadableModuleLogic base class, available at: | |
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py | |
""" | |
def setDefaultParameters(self, parameterNode): | |
""" | |
Initialize parameter node with default settings. | |
""" | |
if not parameterNode.GetParameter("Threshold"): | |
parameterNode.SetParameter("Threshold", "50.0") | |
if not parameterNode.GetParameter("Invert"): | |
parameterNode.SetParameter("Invert", "false") | |
def run(self, inputVolume, outputVolume, imageThreshold, invert=False, showResult=True): | |
""" | |
Run the processing algorithm. | |
Can be used without GUI widget. | |
:param inputVolume: volume to be thresholded | |
:param outputVolume: thresholding result | |
:param imageThreshold: values above/below this threshold will be set to 0 | |
:param invert: if True then values above the threshold will be set to 0, otherwise values below are set to 0 | |
:param showResult: show output volume in slice viewers | |
""" | |
if not inputVolume or not outputVolume: | |
raise ValueError("Input or output volume is invalid") | |
logging.info('Processing started') | |
# Compute the thresholded output volume using the Threshold Scalar Volume CLI module | |
cliParams = { | |
'InputVolume': inputVolume.GetID(), | |
'OutputVolume': outputVolume.GetID(), | |
'ThresholdValue' : imageThreshold, | |
'ThresholdType' : 'Above' if invert else 'Below' | |
} | |
cliNode = slicer.cli.run(slicer.modules.thresholdscalarvolume, None, cliParams, wait_for_completion=True, update_display=showResult) | |
logging.info('Processing completed') | |
# | |
# AutoCompleteCrashTest | |
# | |
class AutoCompleteCrashTest(ScriptedLoadableModuleTest): | |
""" | |
This is the test case for your scripted module. | |
Uses ScriptedLoadableModuleTest base class, available at: | |
https://github.com/Slicer/Slicer/blob/master/Base/Python/slicer/ScriptedLoadableModule.py | |
""" | |
def setUp(self): | |
""" Do whatever is needed to reset the state - typically a scene clear will be enough. | |
""" | |
slicer.mrmlScene.Clear(0) | |
def runTest(self): | |
"""Run as few or as many tests as needed here. | |
""" | |
self.setUp() | |
self.test_AutoCompleteCrash1() | |
def test_AutoCompleteCrash1(self): | |
""" Ideally you should have several levels of tests. At the lowest level | |
tests should exercise the functionality of the logic with different inputs | |
(both valid and invalid). At higher levels your tests should emulate the | |
way the user would interact with your code and confirm that it still works | |
the way you intended. | |
One of the most important features of the tests is that it should alert other | |
developers when their changes will have an impact on the behavior of your | |
module. For example, if a developer removes a feature that you depend on, | |
your test should break so they know that the feature is needed. | |
""" | |
self.delayDisplay("Starting the test") | |
# Get/create input data | |
import SampleData | |
inputVolume = SampleData.downloadFromURL( | |
nodeNames='MRHead', | |
fileNames='MR-Head.nrrd', | |
uris='https://github.com/Slicer/SlicerTestingData/releases/download/MD5/39b01631b7b38232a220007230624c8e', | |
checksums='MD5:39b01631b7b38232a220007230624c8e')[0] | |
self.delayDisplay('Finished with download and loading') | |
inputScalarRange = inputVolume.GetImageData().GetScalarRange() | |
self.assertEqual(inputScalarRange[0], 0) | |
self.assertEqual(inputScalarRange[1], 279) | |
outputVolume = slicer.mrmlScene.AddNewNodeByClass("vtkMRMLScalarVolumeNode") | |
threshold = 50 | |
# Test the module logic | |
logic = AutoCompleteCrashLogic() | |
# Test algorithm with non-inverted threshold | |
logic.run(inputVolume, outputVolume, threshold, True) | |
outputScalarRange = outputVolume.GetImageData().GetScalarRange() | |
self.assertEqual(outputScalarRange[0], inputScalarRange[0]) | |
self.assertEqual(outputScalarRange[1], threshold) | |
# Test algorithm with inverted threshold | |
logic.run(inputVolume, outputVolume, threshold, False) | |
outputScalarRange = outputVolume.GetImageData().GetScalarRange() | |
self.assertEqual(outputScalarRange[0], inputScalarRange[0]) | |
self.assertEqual(outputScalarRange[1], inputScalarRange[1]) | |
self.delayDisplay('Test passed') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment