code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
IMAGE_DATA = 0
POLY_DATA = 1
class StreamerVTK(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._image_data_streamer = vtk.vtkImageDataStreamer()
self._poly_data_streamer = vtk.vtkPolyDataStreamer()
NoConfigModuleMixin.__init__(self,
{'module (self)' : self,
'vtkImageDataStreamer' : self._image_data_streamer,
'vtkPolyDataStreamer' : self._poly_data_streamer})
module_utils.setup_vtk_object_progress(self,
self._image_data_streamer, 'Streaming image data')
self._current_mode = None
self.sync_module_logic_with_config()
def close(self):
NoConfigModuleMixin.close(self)
del self._image_data_streamer
del self._poly_data_streamer
def get_input_descriptions(self):
return ('VTK image or poly data',)
def set_input(self, idx, input_stream):
if hasattr(input_stream, 'IsA'):
if input_stream.IsA('vtkImageData'):
self._image_data_streamer.SetInput(input_stream)
self._current_mode = IMAGE_DATA
elif input_stream.IsA('vtkPolyData'):
self._poly_data_streamer.SetInput(input_stream)
self._current_mode = POLY_DATA
def get_output_descriptions(self):
return('VTK image or poly data',)
def get_output(self, idx):
if self._current_mode == IMAGE_DATA:
return self._image_data_streamer.GetOutput()
elif self._current_mode == POLY_DATA:
return self._poly_data_streamer.GetOutput()
else:
return None
def execute_module(self):
pass
def streaming_execute_module(self):
sp = self._module_manager.get_app_main_config().streaming_pieces
if self._current_mode == IMAGE_DATA:
self._image_data_streamer.SetNumberOfStreamDivisions(sp)
self._image_data_streamer.Update()
elif self._current_mode == POLY_DATA:
self._poly_data_streamer.SetNumberOfStreamDivisions(sp)
self._poly_data_streamer.Update()
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class RegionGrowing(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._image_threshold = vtk.vtkImageThreshold()
# seedconnect wants unsigned char at input
self._image_threshold.SetOutputScalarTypeToUnsignedChar()
self._image_threshold.SetInValue(1)
self._image_threshold.SetOutValue(0)
self._seed_connect = vtk.vtkImageSeedConnectivity()
self._seed_connect.SetInputConnectValue(1)
self._seed_connect.SetOutputConnectedValue(1)
self._seed_connect.SetOutputUnconnectedValue(0)
self._seed_connect.SetInput(self._image_threshold.GetOutput())
module_utils.setup_vtk_object_progress(self, self._seed_connect,
'Performing region growing')
module_utils.setup_vtk_object_progress(self, self._image_threshold,
'Thresholding data')
# we'll use this to keep a binding (reference) to the passed object
self._input_points = None
# this will be our internal list of points
self._seed_points = []
self._config._thresh_interval = 5
config_list = [
('Auto threshold interval:', '_thresh_interval', 'base:float',
'text',
'Used to calculate automatic threshold (unit %).')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkImageSeedConnectivity' : self._seed_connect,
'vtkImageThreshold' : self._image_threshold})
self.sync_module_logic_with_config()
def close(self):
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._image_threshold
self._seed_connect.SetInput(None)
del self._seed_connect
ModuleBase.close(self)
def get_input_descriptions(self):
return ('vtkImageData', 'Seed points')
def set_input(self, idx, input_stream):
if idx == 0:
# will work for None and not-None
self._image_threshold.SetInput(input_stream)
else:
if input_stream != self._input_points:
self._input_points = input_stream
def get_output_descriptions(self):
return ('Region growing result (vtkImageData)',)
def get_output(self, idx):
return self._seed_connect.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def execute_module(self):
self._sync_to_input_points()
# calculate automatic thresholds (we can only do this if we have
# seed points and input data)
ii = self._image_threshold.GetInput()
if ii and self._seed_points:
ii.Update()
mins, maxs = ii.GetScalarRange()
ranges = maxs - mins
sums = 0.0
for seed_point in self._seed_points:
# we assume 0'th component!
v = ii.GetScalarComponentAsDouble(
seed_point[0], seed_point[1], seed_point[2], 0)
sums = sums + v
means = sums / float(len(self._seed_points))
lower_thresh = means - \
float(self._config._thresh_interval / 100.0) * \
float(ranges)
upper_thresh = means + \
float(self._config._thresh_interval / 100.0) * \
float(ranges)
print "Auto thresh: ", lower_thresh, " - ", upper_thresh
self._image_threshold.ThresholdBetween(lower_thresh, upper_thresh)
self._seed_connect.Update()
def _sync_to_input_points(self):
# extract a list from the input points
temp_list = []
if self._input_points:
for i in self._input_points:
temp_list.append(i['discrete'])
if temp_list != self._seed_points:
self._seed_points = temp_list
self._seed_connect.RemoveAllSeeds()
# we need to call Modified() explicitly as RemoveAllSeeds()
# doesn't. AddSeed() does, but sometimes the list is empty at
# this stage and AddSeed() isn't called.
self._seed_connect.Modified()
for seedPoint in self._seed_points:
self._seed_connect.AddSeed(seedPoint[0], seedPoint[1],
seedPoint[2])
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class polyDataNormals(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._pdNormals = vtk.vtkPolyDataNormals()
module_utils.setup_vtk_object_progress(self, self._pdNormals,
'Calculating normals')
NoConfigModuleMixin.__init__(
self, {'vtkPolyDataNormals' : self._pdNormals})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
# get rid of our reference
del self._pdNormals
def get_input_descriptions(self):
return ('vtkPolyData',)
def set_input(self, idx, inputStream):
self._pdNormals.SetInput(inputStream)
def get_output_descriptions(self):
return (self._pdNormals.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._pdNormals.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
self._pdNormals.Update()
def streaming_execute_module(self):
self._pdNormals.Update()
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class greyReconstruct(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._greyReconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D()
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkImageGreyscaleReconstruct3D' : self._greyReconstruct})
module_utils.setup_vtk_object_progress(
self, self._greyReconstruct,
'Performing greyscale reconstruction')
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._greyReconstruct
def get_input_descriptions(self):
return ('Mask image I (VTK)', 'Marker image J (VTK)')
def set_input(self, idx, inputStream):
if idx == 0:
self._greyReconstruct.SetInput1(inputStream)
else:
self._greyReconstruct.SetInput2(inputStream)
def get_output_descriptions(self):
return ('Reconstructed image (VTK)', )
def get_output(self, idx):
return self._greyReconstruct.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
self._greyReconstruct.Update()
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class opening(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageDilate = vtk.vtkImageContinuousDilate3D()
self._imageErode = vtk.vtkImageContinuousErode3D()
self._imageDilate.SetInput(self._imageErode.GetOutput())
module_utils.setup_vtk_object_progress(self, self._imageDilate,
'Performing greyscale 3D dilation')
module_utils.setup_vtk_object_progress(self, self._imageErode,
'Performing greyscale 3D erosion')
self._config.kernelSize = (3, 3, 3)
configList = [
('Kernel size:', 'kernelSize', 'tuple:int,3', 'text',
'Size of the kernel in x,y,z dimensions.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageContinuousDilate3D' : self._imageDilate,
'vtkImageContinuousErode3D' : self._imageErode})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._imageDilate
del self._imageErode
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageErode.SetInput(inputStream)
def get_output_descriptions(self):
return ('Opened image (vtkImageData)',)
def get_output(self, idx):
return self._imageDilate.GetOutput()
def logic_to_config(self):
# if the user's futzing around, she knows what she's doing...
# (we assume that the dilate/erode pair are in sync)
self._config.kernelSize = self._imageErode.GetKernelSize()
def config_to_logic(self):
ks = self._config.kernelSize
self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2])
self._imageErode.SetKernelSize(ks[0], ks[1], ks[2])
def execute_module(self):
self._imageErode.Update()
self._imageDilate.Update()
| Python |
import operator
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
import vtkdevide
import wx
from module_mixins import ColourDialogMixin
class shellSplatSimple(IntrospectModuleMixin,
ColourDialogMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
ColourDialogMixin.__init__(
self, module_manager.get_module_view_parent_window())
# setup the whole VTK pipeline that we're going to use
self._createPipeline()
# this is a list of all the objects in the pipeline and will
# be used by the object and pipeline introspection
self._object_dict = {'splatMapper' : self._splatMapper,
'opacity TF' : self._otf,
'colour TF' : self._ctf,
'volumeProp' : self._volumeProperty,
'volume' : self._volume}
# setup some config defaults
# for segmetented data
self._config.threshold = 1.0
# bony kind of colour
self._config.colour = (1.0, 0.937, 0.859)
# high quality, doh
self._config.renderMode = 0
# default. if you don't understand, forget about it. :)
self._config.gradientImageIsGradient = 0
# create the gui
self._view_frame = None
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# get rid of our reference
del self._splatMapper
del self._otf
del self._ctf
del self._volumeProperty
del self._volume
del self._object_dict
ColourDialogMixin.close(self)
# we have to call this mixin close so that all inspection windows
# can be taken care of. They should be taken care of in anycase
# when the viewFrame is destroyed, but we like better safe than
# sorry
IntrospectModuleMixin.close(self)
# take care of our own window
if self._view_frame is not None:
self._view_frame.Destroy()
del self._view_frame
def get_input_descriptions(self):
return ('input image data', 'optional gradient image data')
def set_input(self, idx, inputStream):
if idx == 0:
if inputStream is None:
# we have to disconnect this way
self._splatMapper.SetInputConnection(0, None)
else:
self._splatMapper.SetInput(inputStream)
else:
self._splatMapper.SetGradientImageData(inputStream)
def get_output_descriptions(self):
return ('Shell splat volume (vtkVolume)',)
def get_output(self, idx):
return self._volume
def logic_to_config(self):
# we CAN'T derive the threshold and colour from the opacity and colour
# transfer functions (or we could, but it'd be terribly dirty)
# but fortunately we don't really have to - logiToConfig is only really
# for cases where the logic could return config information different
# from that we programmed it with
# this we can get
self._config.renderMode = self._splatMapper.GetRenderMode()
# this too
self._config.gradientImageIsGradient = self._splatMapper.\
GetShellExtractor().\
GetGradientImageIsGradient()
def config_to_logic(self):
# only modify the transfer functions if they've actually changed
if self._otf.GetSize() != 2 or \
self._otf.GetValue(self._config.threshold - 0.1) != 0.0 or \
self._otf.GetValue(self._config.threshold) != 1.0:
# make a step in the opacity transfer function
self._otf.RemoveAllPoints()
self._otf.AddPoint(self._config.threshold - 0.1, 0.0)
self._otf.AddPoint(self._config.threshold, 1.0)
# sample the two points and check that they haven't changed too much
tfCol1 = self._ctf.GetColor(self._config.threshold)
colDif1 = [i for i in
map(abs, map(operator.sub, self._config.colour, tfCol1))
if i > 0.001]
tfCol2 = self._ctf.GetColor(self._config.threshold - 0.1)
colDif2 = [i for i in
map(abs, map(operator.sub, (0,0,0), tfCol2))
if i > 0.001]
if self._ctf.GetSize() != 2 or colDif1 or colDif2:
# make a step in the colour transfer
self._ctf.RemoveAllPoints()
r,g,b = self._config.colour
# setting two points is not necessary, but we play it safe
self._ctf.AddRGBPoint(self._config.threshold - 0.1, 0, 0, 0)
self._ctf.AddRGBPoint(self._config.threshold, r, g, b)
# set the rendering mode
self._splatMapper.SetRenderMode(self._config.renderMode)
# set the gradientImageIsGradient thingy
self._splatMapper.GetShellExtractor().SetGradientImageIsGradient(
self._config.gradientImageIsGradient)
def view_to_config(self):
# get the threshold
try:
threshold = float(self._view_frame.thresholdText.GetValue())
except:
# this means the user did something stupid, so we revert
# to what's in the config - this will also turn up back
# in the input box, as the DeVIDE arch automatically syncs
# view with logic after having applied changes
threshold = self._config.threshold
# store it in the config
self._config.threshold = threshold
# convert the colour in the input box to something we can use
colour = self._colourDialog.GetColourData().GetColour()
defaultColourTuple = (colour.Red() / 255.0,
colour.Green() / 255.0,
colour.Blue() / 255.0)
colourTuple = self._convertStringToColour(
self._view_frame.colourText.GetValue(),
defaultColourTuple)
# and put it in the right place
self._config.colour = colourTuple
self._config.renderMode = self._view_frame.\
renderingModeChoice.GetSelection()
self._config.gradientImageIsGradient = \
self._view_frame.\
gradientImageIsGradientCheckBox.\
GetValue()
def config_to_view(self):
self._view_frame.thresholdText.SetValue("%.2f" %
(self._config.threshold))
self._view_frame.colourText.SetValue(
"(%.3f, %.3f, %.3f)" % self._config.colour)
self._view_frame.renderingModeChoice.SetSelection(
self._config.renderMode)
self._view_frame.gradientImageIsGradientCheckBox.SetValue(
self._config.gradientImageIsGradient)
def execute_module(self):
self._splatMapper.Update()
def view(self, parent_window=None):
if self._view_frame is None:
self._createViewFrame()
self.sync_module_view_with_logic()
# if the window was visible already. just raise it
self._view_frame.Show(True)
self._view_frame.Raise()
def _colourButtonCallback(self, evt):
# first we have to translate the colour which is in the textentry
# and set it in the colourDialog
colour = self._colourDialog.GetColourData().GetColour()
defaultColourTuple = (colour.Red() / 255.0,
colour.Green() / 255.0,
colour.Blue() / 255.0)
colourTuple = self._convertStringToColour(
self._view_frame.colourText.GetValue(),
defaultColourTuple)
self.setColourDialogColour(colourTuple)
c = self.getColourDialogColour()
if c:
self._view_frame.colourText.SetValue(
"(%.2f, %.2f, %.2f)" % c)
def _convertStringToColour(self, colourString, defaultColourTuple):
"""Attempt to convert colourString into tuple representation.
Returns colour tuple. No scaling is done, i.e. 3 elements in the str
tuple are converted to floats and returned as a 3-tuple.
"""
try:
colourTuple = eval(colourString)
if type(colourTuple) != tuple or len(colourTuple) != 3:
raise Exception
colourTuple = tuple([float(i) for i in colourTuple])
except:
# if we can't convert, we just let the colour chooser use
# its previous default
colourTuple = defaultColourTuple
return colourTuple
def _createPipeline(self):
# setup our pipeline
self._splatMapper = vtkdevide.vtkOpenGLVolumeShellSplatMapper()
self._splatMapper.SetOmegaL(0.9)
self._splatMapper.SetOmegaH(0.9)
# high-quality rendermode
self._splatMapper.SetRenderMode(0)
self._otf = vtk.vtkPiecewiseFunction()
self._otf.AddPoint(0.0, 0.0)
self._otf.AddPoint(0.9, 0.0)
self._otf.AddPoint(1.0, 1.0)
self._ctf = vtk.vtkColorTransferFunction()
self._ctf.AddRGBPoint(0.0, 0.0, 0.0, 0.0)
self._ctf.AddRGBPoint(0.9, 0.0, 0.0, 0.0)
self._ctf.AddRGBPoint(1.0, 1.0, 0.937, 0.859)
self._volumeProperty = vtk.vtkVolumeProperty()
self._volumeProperty.SetScalarOpacity(self._otf)
self._volumeProperty.SetColor(self._ctf)
self._volumeProperty.ShadeOn()
self._volumeProperty.SetAmbient(0.1)
self._volumeProperty.SetDiffuse(0.7)
self._volumeProperty.SetSpecular(0.2)
self._volumeProperty.SetSpecularPower(10)
self._volume = vtk.vtkVolume()
self._volume.SetProperty(self._volumeProperty)
self._volume.SetMapper(self._splatMapper)
def _createViewFrame(self):
mm = self._module_manager
# import/reload the viewFrame (created with wxGlade)
mm.import_reload(
'modules.filters.resources.python.shellSplatSimpleFLTViewFrame')
# this line is harmless due to Python's import caching, but we NEED
# to do it so that the Installer knows that this devide module
# requires it and so that it's available in this namespace.
import modules.filters.resources.python.shellSplatSimpleFLTViewFrame
self._view_frame = module_utils.instantiate_module_view_frame(
self, mm,
modules.filters.resources.python.shellSplatSimpleFLTViewFrame.\
shellSplatSimpleFLTViewFrame)
# setup introspection with default everythings
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.viewFramePanel,
self._object_dict, None)
# create and configure the standard ECAS buttons
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.viewFramePanel)
# now we can finally do our own stuff to
wx.EVT_BUTTON(self._view_frame, self._view_frame.colourButtonId,
self._colourButtonCallback)
| Python |
# todo:
# * vtkVolumeMapper::SetCroppingRegionPlanes(xmin,xmax,ymin,ymax,zmin,zmax)
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
import vtktudoss
class ExpVolumeRender(
ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# at the first config_to_logic (at the end of the ctor), this will
# be set to 0
self._current_rendering_type = -1
# setup some config defaults
self._config.rendering_type = 0
self._config.interpolation = 1 # linear
self._config.ambient = 0.1
self._config.diffuse = 0.7
self._config.specular = 0.6
self._config.specular_power = 80
self._config.threshold = 1250
# this is not in the interface yet, change by introspection
self._config.mip_colour = (0.0, 0.0, 1.0)
config_list = [
('Rendering type:', 'rendering_type', 'base:int', 'choice',
'Direct volume rendering algorithm that will be used.',
('Raycast (fixed point)', '2D Texture', '3D Texture',
'ShellSplatting', 'Raycast (old)')),
('Interpolation:', 'interpolation', 'base:int', 'choice',
'Linear (high quality, slower) or nearest neighbour (lower '
'quality, faster) interpolation',
('Nearest Neighbour', 'Linear')),
('Ambient:', 'ambient', 'base:float', 'text',
'Ambient lighting term.'),
('Diffuse:', 'diffuse', 'base:float', 'text',
'Diffuse lighting term.'),
('Specular:', 'specular', 'base:float', 'text',
'Specular lighting term.'),
('Specular power:', 'specular_power', 'base:float', 'text',
'Specular power lighting term (more focused high-lights).'),
('Threshold:', 'threshold', 'base:float', 'text',
'Used to generate transfer function ONLY if none is supplied')
]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self})
self._input_data = None
self._input_otf0 = None
self._input_ctf0 = None
self._input_otf1 = None
self._input_ctf1 = None
self._volume_raycast_function = None
self._create_pipeline()
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of GUI
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._volume_property
del self._volume_raycast_function
del self._volume_mapper
del self._volume
def get_input_descriptions(self):
return ('input image data',
'opacity transfer function 0',
'colour transfer function 0',
'opacity transfer function 1',
'colour transfer function 1'
)
def set_input(self, idx, inputStream):
if idx == 0:
self._input_data = inputStream
elif idx == 1:
self._input_otf0 = inputStream
elif idx == 2:
self._input_ctf0 = inputStream
elif idx == 3:
self._input_otf1 = inputStream
else:
self._input_ctf1 = inputStream
def get_output_descriptions(self):
return ('vtkVolume',)
def get_output(self, idx):
return self._volume
def logic_to_config(self):
self._config.rendering_type = self._current_rendering_type
self._config.interpolation = \
self._volume_property.GetInterpolationType()
self._config.ambient = self._volume_property.GetAmbient()
self._config.diffuse = self._volume_property.GetDiffuse()
self._config.specular = self._volume_property.GetSpecular()
self._config.specular_power = \
self._volume_property.GetSpecularPower()
def config_to_logic(self):
self._volume_property.SetInterpolationType(self._config.interpolation)
self._volume_property.SetAmbient(self._config.ambient)
self._volume_property.SetDiffuse(self._config.diffuse)
self._volume_property.SetSpecular(self._config.specular)
self._volume_property.SetSpecularPower(self._config.specular_power)
if self._config.rendering_type != self._current_rendering_type:
if self._config.rendering_type == 0:
# raycast fixed point
self._setup_for_fixed_point()
elif self._config.rendering_type == 1:
# 2d texture
self._setup_for_2d_texture()
elif self._config.rendering_type == 2:
# 3d texture
self._setup_for_3d_texture()
elif self._config.rendering_type == 3:
# shell splatter
self._setup_for_shell_splatting()
else:
# old raycaster (very picky about input types)
self._setup_for_raycast()
self._volume.SetMapper(self._volume_mapper)
self._current_rendering_type = self._config.rendering_type
def _setup_for_raycast(self):
self._volume_raycast_function = \
vtk.vtkVolumeRayCastCompositeFunction()
self._volume_mapper = vtk.vtkVolumeRayCastMapper()
self._volume_mapper.SetVolumeRayCastFunction(
self._volume_raycast_function)
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_2d_texture(self):
self._volume_mapper = vtk.vtkVolumeTextureMapper2D()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_3d_texture(self):
self._volume_mapper = vtk.vtkVolumeTextureMapper3D()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_shell_splatting(self):
self._volume_mapper = vtkdevide.vtkOpenGLVolumeShellSplatMapper()
self._volume_mapper.SetOmegaL(0.9)
self._volume_mapper.SetOmegaH(0.9)
# high-quality rendermode
self._volume_mapper.SetRenderMode(0)
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_fixed_point(self):
"""This doesn't seem to work. After processing is complete,
it stalls on actually rendering the volume. No idea.
"""
import vtktudoss
self._volume_mapper = vtktudoss.vtkCVFixedPointVolumeRayCastMapper()
self._volume_mapper.SetBlendModeToComposite()
#self._volume_mapper.SetBlendModeToMaximumIntensity()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def execute_module(self):
otf, ctf = self._create_tfs()
#if self._input_otf is not None:
# otf = self._input_otf
#if self._input_ctf is not None:
# ctf = self._input_ctf
self._volume_property.SetScalarOpacity(
0, self._input_otf0)
self._volume_property.SetColor(
0, self._input_ctf0)
self._volume_property.SetScalarOpacity(
1, self._input_otf1)
self._volume_property.SetColor(
1, self._input_ctf1)
self._volume_mapper.SetInput(self._input_data)
self._volume_mapper.Update()
def _create_tfs(self):
otf = vtk.vtkPiecewiseFunction()
ctf = vtk.vtkColorTransferFunction()
otf.RemoveAllPoints()
t = self._config.threshold
p1 = t - t / 10.0
p2 = t + t / 5.0
print "MIP: %.2f - %.2f" % (p1, p2)
otf.AddPoint(p1, 0.0)
otf.AddPoint(p2, 1.0)
otf.AddPoint(self._config.threshold, 1.0)
ctf.RemoveAllPoints()
ctf.AddHSVPoint(p1, 0.1, 0.7, 1.0)
#ctf.AddHSVPoint(p2, *self._config.mip_colour)
ctf.AddHSVPoint(p2, 0.65, 0.7, 1.0)
return (otf, ctf)
def _create_pipeline(self):
# setup our pipeline
self._volume_property = vtk.vtkVolumeProperty()
self._volume_property.ShadeOn()
self._volume_mapper = None
self._volume = vtk.vtkVolume()
self._volume.SetProperty(self._volume_property)
self._volume.SetMapper(self._volume_mapper)
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import wx
import vtk
class closing(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageDilate = vtk.vtkImageContinuousDilate3D()
self._imageErode = vtk.vtkImageContinuousErode3D()
self._imageErode.SetInput(self._imageDilate.GetOutput())
module_utils.setup_vtk_object_progress(self, self._imageDilate,
'Performing greyscale 3D dilation')
module_utils.setup_vtk_object_progress(self, self._imageErode,
'Performing greyscale 3D erosion')
self._config.kernelSize = (3, 3, 3)
configList = [
('Kernel size:', 'kernelSize', 'tuple:int,3', 'text',
'Size of the kernel in x,y,z dimensions.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageContinuousDilate3D' : self._imageDilate,
'vtkImageContinuousErode3D' : self._imageErode})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._imageDilate
del self._imageErode
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageDilate.SetInput(inputStream)
def get_output_descriptions(self):
return ('Closed image (vtkImageData)',)
def get_output(self, idx):
return self._imageErode.GetOutput()
def logic_to_config(self):
# if the user's futzing around, she knows what she's doing...
# (we assume that the dilate/erode pair are in sync)
self._config.kernelSize = self._imageDilate.GetKernelSize()
def config_to_logic(self):
ks = self._config.kernelSize
self._imageDilate.SetKernelSize(ks[0], ks[1], ks[2])
self._imageErode.SetKernelSize(ks[0], ks[1], ks[2])
def execute_module(self):
self._imageDilate.Update()
self._imageErode.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class marchingCubes(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._contourFilter = vtk.vtkMarchingCubes()
module_utils.setup_vtk_object_progress(self, self._contourFilter,
'Extracting iso-surface')
# now setup some defaults before our sync
self._config.iso_value = 128
config_list = [
('ISO value:', 'iso_value', 'base:float', 'text',
'Surface will pass through points with this value.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkMarchingCubes' : self._contourFilter})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
self.set_input(0, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._contourFilter
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._contourFilter.SetInput(inputStream)
def get_output_descriptions(self):
return (self._contourFilter.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._contourFilter.GetOutput()
def logic_to_config(self):
self._config.iso_value = self._contourFilter.GetValue(0)
def config_to_logic(self):
self._contourFilter.SetValue(0, self._config.iso_value)
def execute_module(self):
self._contourFilter.Update()
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
import numpy
class FitEllipsoidToMask(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._input_data = None
self._output_dict = {}
# polydata pipeline to make crosshairs
self._ls1 = vtk.vtkLineSource()
self._ls2 = vtk.vtkLineSource()
self._ls3 = vtk.vtkLineSource()
self._append_pd = vtk.vtkAppendPolyData()
self._append_pd.AddInput(self._ls1.GetOutput())
self._append_pd.AddInput(self._ls2.GetOutput())
self._append_pd.AddInput(self._ls3.GetOutput())
NoConfigModuleMixin.__init__(
self, {'Module (self)' : self})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
def get_input_descriptions(self):
return ('VTK image data',)
def set_input(self, idx, input_stream):
self._input_data = input_stream
def get_output_descriptions(self):
return ('Ellipsoid (eigen-analysis) parameters', 'Crosshairs polydata')
def get_output(self, idx):
if idx == 0:
return self._output_dict
else:
return self._append_pd.GetOutput()
def execute_module(self):
ii = self._input_data
if not ii:
return
# now we need to iterate through the whole input data
ii.Update()
iorigin = ii.GetOrigin()
ispacing = ii.GetSpacing()
maxx, maxy, maxz = ii.GetDimensions()
numpoints = 0
points = []
for z in range(maxz):
wz = z * ispacing[2] + iorigin[2]
for y in range(maxy):
wy = y * ispacing[1] + iorigin[1]
for x in range(maxx):
v = ii.GetScalarComponentAsDouble(x,y,z,0)
if v > 0.0:
wx = x * ispacing[0] + iorigin[0]
points.append((wx,wy,wz))
# covariance matrix ##############################
if len(points) == 0:
self._output_dict.update({'u' : None, 'v' : None, 'c' : None,
'axis_lengths' : None,
'radius_vectors' : None})
return
# determine centre (x,y,z)
points2 = numpy.array(points)
centre = numpy.average(points2, 0)
cx,cy,cz = centre
# subtract centre from all points
points_c = points2 - centre
covariance = numpy.cov(points_c.transpose())
# eigen-analysis (u eigenvalues, v eigenvectors)
u,v = numpy.linalg.eig(covariance)
# estimate length at 2.0 * standard deviation in both directions
axis_lengths = [4.0 * numpy.sqrt(eigval) for eigval in u]
radius_vectors = numpy.zeros((3,3), float)
for i in range(3):
radius_vectors[i] = v[i] * axis_lengths[i] / 2.0
self._output_dict.update({'u' :u, 'v' : v, 'c' : (cx,cy,cz),
'axis_lengths' : tuple(axis_lengths),
'radius_vectors' : radius_vectors})
# now modify output polydata #########################
lss = [self._ls1, self._ls2, self._ls3]
for i in range(len(lss)):
half_axis = radius_vectors[i] #axis_lengths[i] / 2.0 * v[i]
ca = numpy.array((cx,cy,cz))
lss[i].SetPoint1(ca - half_axis)
lss[i].SetPoint2(ca + half_axis)
self._append_pd.Update()
def pca(points):
"""PCA factored out of execute_module and made N-D. not being used yet.
points is a list of M N-d tuples.
returns eigenvalues (u), eigenvectors (v), axis_lengths and
radius_vectors.
"""
# for a list of M N-d tuples, returns an array with M rows and N
# columns
points2 = numpy.array(points)
# determine centre by averaging over 0th axis (over rows)
centre = numpy.average(points2, 0)
# subtract centre from all points
points_c = points2 - centre
covariance = numpy.cov(points_c.transpose())
# eigen-analysis (u eigenvalues, v eigenvectors)
u,v = numpy.linalg.eig(covariance)
# estimate length at 2.0 * standard deviation in both directions
axis_lengths = [4.0 * numpy.sqrt(eigval) for eigval in u]
N = len(u)
radius_vectors = numpy.zeros((N,N), float)
for i in range(N):
radius_vectors[i] = v[i] * axis_lengths[i] / 2.0
output_dict = {'u' :u, 'v' : v, 'c' : centre,
'axis_lengths' : tuple(axis_lengths),
'radius_vectors' : radius_vectors}
return output_dict
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class ICPTransform(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
# this has no progress feedback
self._icp = vtk.vtkIterativeClosestPointTransform()
self._config.max_iterations = 50
self._config.mode = 'RigidBody'
self._config.align_centroids = True
config_list = [
('Transformation mode:', 'mode', 'base:str', 'choice',
'Rigid: rotation + translation;\n'
'Similarity: rigid + isotropic scaling\n'
'Affine: rigid + scaling + shear',
('RigidBody', 'Similarity', 'Affine')),
('Maximum number of iterations:', 'max_iterations',
'base:int', 'text',
'Maximum number of iterations for ICP.'),
('Align centroids before start', 'align_centroids', 'base:bool', 'checkbox',
'Align centroids before iteratively optimizing closest points? (required for large relative translations)')
]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkIterativeClosestPointTransform' : self._icp})
self.sync_module_logic_with_config()
def close(self):
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._icp
ModuleBase.close(self)
def get_input_descriptions(self):
return ('source vtkPolyData', 'target vtkPolyData')
def set_input(self, idx, input_stream):
if idx == 0:
self._icp.SetSource(input_stream)
else:
self._icp.SetTarget(input_stream)
def get_output_descriptions(self):
return ('Linear transform',)
def get_output(self, idx):
return self._icp
def logic_to_config(self):
self._config.mode = \
self._icp.GetLandmarkTransform().GetModeAsString()
self._config.max_iterations = \
self._icp.GetMaximumNumberOfIterations()
self._config.align_centroids = self._icp.GetStartByMatchingCentroids()
def config_to_logic(self):
lmt = self._icp.GetLandmarkTransform()
if self._config.mode == 'RigidBody':
lmt.SetModeToRigidBody()
elif self._config.mode == 'Similarity':
lmt.SetModeToSimilarity()
else:
lmt.SetModeToAffine()
self._icp.SetMaximumNumberOfIterations(
self._config.max_iterations)
self._icp.SetStartByMatchingCentroids(self._config.align_centroids)
def execute_module(self):
self._module_manager.set_progress(
10, 'Starting ICP.')
self._icp.Update()
self._module_manager.set_progress(
100, 'ICP complete.')
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class seedConnect(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._imageCast = vtk.vtkImageCast()
self._imageCast.SetOutputScalarTypeToUnsignedChar()
self._seedConnect = vtk.vtkImageSeedConnectivity()
self._seedConnect.SetInput(self._imageCast.GetOutput())
module_utils.setup_vtk_object_progress(self, self._seedConnect,
'Performing region growing')
module_utils.setup_vtk_object_progress(self, self._imageCast,
'Casting data to unsigned char')
# we'll use this to keep a binding (reference) to the passed object
self._inputPoints = None
# this will be our internal list of points
self._seedPoints = []
# now setup some defaults before our sync
self._config.inputConnectValue = 1
self._config.outputConnectedValue = 1
self._config.outputUnconnectedValue = 0
config_list = [
('Input connect value:', 'inputConnectValue', 'base:int', 'text',
'Points connected to seed points with this value will be '
'included.'),
('Output connected value:', 'outputConnectedValue', 'base:int',
'text', 'Included points will get this value.'),
('Output unconnected value:', 'outputUnconnectedValue',
'base:int', 'text', 'Non-included points will get this value.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkImageSeedConnectivity' : self._seedConnect,
'vtkImageCast' : self._imageCast})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
self.set_input(0, None)
self.set_input(1, None)
# don't forget to call the close() method of the vtkPipeline mixin
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._imageCast
self._seedConnect.SetInput(None)
del self._seedConnect
def get_input_descriptions(self):
return ('vtkImageData', 'Seed points')
def set_input(self, idx, inputStream):
if idx == 0:
# will work for None and not-None
self._imageCast.SetInput(inputStream)
else:
if inputStream != self._inputPoints:
self._inputPoints = inputStream
def get_output_descriptions(self):
return ('Region growing result (vtkImageData)',)
def get_output(self, idx):
return self._seedConnect.GetOutput()
def logic_to_config(self):
self._config.inputConnectValue = self._seedConnect.\
GetInputConnectValue()
self._config.outputConnectedValue = self._seedConnect.\
GetOutputConnectedValue()
self._config.outputUnconnectedValue = self._seedConnect.\
GetOutputUnconnectedValue()
def config_to_logic(self):
self._seedConnect.SetInputConnectValue(self._config.inputConnectValue)
self._seedConnect.SetOutputConnectedValue(self._config.\
outputConnectedValue)
self._seedConnect.SetOutputUnconnectedValue(self._config.\
outputUnconnectedValue)
def execute_module(self):
self._sync_to_input_points()
self._seedConnect.Update()
# we can't stream this module, as it needs up to date seed points
# before it begins.
def _sync_to_input_points(self):
# extract a list from the input points
tempList = []
if self._inputPoints:
for i in self._inputPoints:
tempList.append(i['discrete'])
if tempList != self._seedPoints:
self._seedPoints = tempList
self._seedConnect.RemoveAllSeeds()
# we need to call Modified() explicitly as RemoveAllSeeds()
# doesn't. AddSeed() does, but sometimes the list is empty at
# this stage and AddSeed() isn't called.
self._seedConnect.Modified()
for seedPoint in self._seedPoints:
self._seedConnect.AddSeed(seedPoint[0], seedPoint[1],
seedPoint[2])
| Python |
from module_base import ModuleBase
from module_mixins import vtkPipelineConfigModuleMixin
import module_utils
import vtk
class contourFLTBase(ModuleBase, vtkPipelineConfigModuleMixin):
def __init__(self, module_manager, contourFilterText):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._contourFilterText = contourFilterText
if contourFilterText == 'marchingCubes':
self._contourFilter = vtk.vtkMarchingCubes()
else: # contourFilter == 'contourFilter'
self._contourFilter = vtk.vtkContourFilter()
module_utils.setup_vtk_object_progress(self, self._contourFilter,
'Extracting iso-surface')
# now setup some defaults before our sync
self._config.isoValue = 128;
self._viewFrame = None
self._createViewFrame()
# transfer these defaults to the logic
self.config_to_logic()
# then make sure they come all the way back up via self._config
self.logic_to_config()
self.config_to_view()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
self.set_input(0, None)
# don't forget to call the close() method of the vtkPipeline mixin
vtkPipelineConfigModuleMixin.close(self)
# take out our view interface
self._viewFrame.Destroy()
# get rid of our reference
del self._contourFilter
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._contourFilter.SetInput(inputStream)
def get_output_descriptions(self):
return (self._contourFilter.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._contourFilter.GetOutput()
def logic_to_config(self):
self._config.isoValue = self._contourFilter.GetValue(0)
def config_to_logic(self):
self._contourFilter.SetValue(0, self._config.isoValue)
def view_to_config(self):
try:
self._config.isoValue = float(
self._viewFrame.isoValueText.GetValue())
except:
pass
def config_to_view(self):
self._viewFrame.isoValueText.SetValue(str(self._config.isoValue))
def execute_module(self):
self._contourFilter.Update()
def view(self, parent_window=None):
# if the window was visible already. just raise it
if not self._viewFrame.Show(True):
self._viewFrame.Raise()
def _createViewFrame(self):
# import the viewFrame (created with wxGlade)
import modules.Filters.resources.python.contourFLTBaseViewFrame
reload(modules.Filters.resources.python.contourFLTBaseViewFrame)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.Filters.resources.python.contourFLTBaseViewFrame.\
contourFLTBaseViewFrame)
objectDict = {'contourFilter' : self._contourFilter}
module_utils.create_standard_object_introspection(
self, self._viewFrame, self._viewFrame.viewFramePanel,
objectDict, None)
module_utils.create_eoca_buttons(
self, self._viewFrame, self._viewFrame.viewFramePanel)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import input_array_choice_mixin # need this for constants
reload(input_array_choice_mixin)
from input_array_choice_mixin import InputArrayChoiceMixin
class warpPoints(ScriptedConfigModuleMixin, InputArrayChoiceMixin,
ModuleBase):
_defaultVectorsSelectionString = 'Default Active Vectors'
_userDefinedString = 'User Defined'
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
InputArrayChoiceMixin.__init__(self)
self._config.scaleFactor = 1
configList = [
('Scale factor:', 'scaleFactor', 'base:float', 'text',
'The warping will be scaled by this factor'),
('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
'The attribute that will be used as vectors for the warping.',
(self._defaultVectorsSelectionString, self._userDefinedString))]
self._warpVector = vtk.vtkWarpVector()
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkWarpVector' : self._warpVector})
module_utils.setup_vtk_object_progress(self, self._warpVector,
'Warping points.')
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._warpVector
def execute_module(self):
self._warpVector.Update()
if self.view_initialised:
# second element in configuration list
choice = self._getWidget(1)
self.iac_execute_module(self._warpVector, choice, 0)
def get_input_descriptions(self):
return ('VTK points/polydata with vector attribute',)
def set_input(self, idx, inputStream):
if inputStream is None:
self._warpVector.SetInputConnection(0, None)
else:
self._warpVector.SetInput(inputStream)
def get_output_descriptions(self):
return ('Warped data',)
def get_output(self, idx):
# we only return something if we have something
if self._warpVector.GetNumberOfInputConnections(0):
return self._warpVector.GetOutput()
else:
return None
def logic_to_config(self):
self._config.scaleFactor = self._warpVector.GetScaleFactor()
# this will extract the possible choices
self.iac_logic_to_config(self._warpVector, 0)
def config_to_view(self):
# first get our parent mixin to do its thing
ScriptedConfigModuleMixin.config_to_view(self)
# the vector choice is the second configTuple
choice = self._getWidget(1)
self.iac_config_to_view(choice)
def config_to_logic(self):
self._warpVector.SetScaleFactor(self._config.scaleFactor)
self.iac_config_to_logic(self._warpVector, 0)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import input_array_choice_mixin
reload(input_array_choice_mixin)
from input_array_choice_mixin import InputArrayChoiceMixin
ARRAY_IDX = 1
# scale vector glyph with scalar, vector magnitude, or separately for each
# direction (using vector components), or don't scale at all
# default is SCALE_BY_VECTOR = 1
glyphScaleMode = ['SCALE_BY_SCALAR', 'SCALE_BY_VECTOR',
'SCALE_BY_VECTORCOMPONENTS', 'DATA_SCALING_OFF']
glyphScaleModeTexts = ['Scale by scalar attribute',
'Scale by vector magnitude',
'Scale with x,y,z vector components',
'Use only scale factor']
# colour by scale (magnitude of scaled vector), by scalar or by vector
# default: COLOUR_BY_VECTOR = 1
glyphColourMode = ['COLOUR_BY_SCALE', 'COLOUR_BY_SCALAR', 'COLOUR_BY_VECTOR']
glyphColourModeTexts = ['Colour by scale', 'Colour by scalar attribute',
'Colour by vector magnitude']
# which data should be used for scaling, orientation and indexing
# default: USE_VECTOR = 0
glyphVectorMode = ['USE_VECTOR', 'USE_NORMAL', 'VECTOR_ROTATION_OFF']
glyphVectorModeTexts = ['Use vector', 'Use normal', 'Do not orient']
# we can use different glyph types in the same visualisation
# default: INDEXING_OFF = 0
# (we're not going to use this right now)
glyphIndexMode = ['INDEXING_OFF', 'INDEXING_BY_SCALAR', 'INDEXING_BY_VECTOR']
class glyphs(ScriptedConfigModuleMixin, InputArrayChoiceMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
InputArrayChoiceMixin.__init__(self)
self._config.scaling = True
self._config.scaleFactor = 1
self._config.scaleMode = glyphScaleMode.index('SCALE_BY_VECTOR')
self._config.colourMode = glyphColourMode.index('COLOUR_BY_VECTOR')
self._config.vectorMode = glyphVectorMode.index('USE_VECTOR')
self._config.mask_on_ratio = 5
self._config.mask_random = True
configList = [
('Scale glyphs:', 'scaling', 'base:bool', 'checkbox',
'Should the size of the glyphs be scaled?'),
('Scale factor:', 'scaleFactor', 'base:float', 'text',
'By how much should the glyph size be scaled if scaling is '
'active?'),
('Scale mode:', 'scaleMode', 'base:int', 'choice',
'Should scaling be performed by vector, scalar or only factor?',
glyphScaleModeTexts),
('Colour mode:', 'colourMode', 'base:int', 'choice',
'Colour is determined based on scalar or vector magnitude.',
glyphColourModeTexts),
('Vector mode:', 'vectorMode', 'base:int', 'choice',
'Should vectors or normals be used for scaling and orientation?',
glyphVectorModeTexts),
('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
'The attribute that will be used as vectors for the warping.',
(input_array_choice_mixin.DEFAULT_SELECTION_STRING,)),
('Mask on ratio:', 'mask_on_ratio', 'base:int', 'text',
'Every Nth point will be glyphed.'),
('Random masking:', 'mask_random', 'base:bool', 'checkbox',
'Pick random distribution of Nth points.')]
self._mask_points = vtk.vtkMaskPoints()
module_utils.setup_vtk_object_progress(self,
self._mask_points, 'Masking points.')
self._glyphFilter = vtk.vtkGlyph3D()
asrc = vtk.vtkArrowSource()
self._glyphFilter.SetSource(0, asrc.GetOutput())
self._glyphFilter.SetInput(self._mask_points.GetOutput())
module_utils.setup_vtk_object_progress(self, self._glyphFilter,
'Creating glyphs.')
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkGlyph3D' : self._glyphFilter})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._mask_points
del self._glyphFilter
def execute_module(self):
self._glyphFilter.Update()
if self.view_initialised:
choice = self._getWidget(5)
self.iac_execute_module(self._glyphFilter, choice,
ARRAY_IDX)
def get_input_descriptions(self):
return ('VTK Vector dataset',)
def set_input(self, idx, inputStream):
self._mask_points.SetInput(inputStream)
def get_output_descriptions(self):
return ('3D glyphs',)
def get_output(self, idx):
return self._glyphFilter.GetOutput()
def logic_to_config(self):
self._config.scaling = bool(self._glyphFilter.GetScaling())
self._config.scaleFactor = self._glyphFilter.GetScaleFactor()
self._config.scaleMode = self._glyphFilter.GetScaleMode()
self._config.colourMode = self._glyphFilter.GetColorMode()
self._config.vectorMode = self._glyphFilter.GetVectorMode()
self._config.mask_on_ratio = \
self._mask_points.GetOnRatio()
self._config.mask_random = bool(self._mask_points.GetRandomMode())
# this will extract the possible choices
self.iac_logic_to_config(self._glyphFilter, ARRAY_IDX)
def config_to_view(self):
# first get our parent mixin to do its thing
ScriptedConfigModuleMixin.config_to_view(self)
# the vector choice is the second configTuple
choice = self._getWidget(5)
self.iac_config_to_view(choice)
def config_to_logic(self):
self._glyphFilter.SetScaling(self._config.scaling)
self._glyphFilter.SetScaleFactor(self._config.scaleFactor)
self._glyphFilter.SetScaleMode(self._config.scaleMode)
self._glyphFilter.SetColorMode(self._config.colourMode)
self._glyphFilter.SetVectorMode(self._config.vectorMode)
self._mask_points.SetOnRatio(self._config.mask_on_ratio)
self._mask_points.SetRandomMode(int(self._config.mask_random))
self.iac_config_to_logic(self._glyphFilter, ARRAY_IDX)
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class clipPolyData(NoConfigModuleMixin, ModuleBase):
"""Given an input polydata and an implicitFunction, this will clip
the polydata.
All points that are inside the implicit function are kept, everything
else is discarded. 'Inside' is defined as all points in the polydata
where the implicit function value is greater than 0.
"""
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._clipPolyData = vtk.vtkClipPolyData()
module_utils.setup_vtk_object_progress(self, self._clipPolyData,
'Calculating normals')
NoConfigModuleMixin.__init__(
self,
{'vtkClipPolyData' : self._clipPolyData})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
# get rid of our reference
del self._clipPolyData
def get_input_descriptions(self):
return ('PolyData', 'Implicit Function')
def set_input(self, idx, inputStream):
if idx == 0:
self._clipPolyData.SetInput(inputStream)
else:
self._clipPolyData.SetClipFunction(inputStream)
def get_output_descriptions(self):
return (self._clipPolyData.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._clipPolyData.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
self._clipPolyData.Update()
| Python |
# landmark_transform.py copyright (c) 2003 by Charl P. Botha <cpbotha@ieee.org>
# $Id$
# see module documentation
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class landmarkTransform(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._input_points = [None, None]
self._source_landmarks = None
self._target_landmarks = None
self._config.mode = 'Rigid'
configList = [('Transformation mode:', 'mode', 'base:str', 'choice',
'Rigid: rotation + translation;\n'
'Similarity: rigid + isotropic scaling\n'
'Affine: rigid + scaling + shear',
('Rigid', 'Similarity', 'Affine'))]
self._landmark_transform = vtk.vtkLandmarkTransform()
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkLandmarkTransform': self._landmark_transform})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._landmark_transform
def get_input_descriptions(self):
return ('Source and/or Target Points',
'Source and/or Target Points')
def set_input(self, idx, input_stream):
if input_stream is not self._input_points[idx]:
if input_stream == None:
self._input_points[idx] = None
elif hasattr(input_stream, 'devideType') and \
input_stream.devideType == 'namedPoints':
self._input_points[idx] = input_stream
else:
raise TypeError, 'This input requires a named points type.'
def get_output_descriptions(self):
return ('vtkTransform',)
def get_output(self, idx):
return self._landmark_transform
def logic_to_config(self):
mas = self._landmark_transform.GetModeAsString()
if mas == 'RigidBody':
mas = 'Rigid'
self._config.mode = mas
def config_to_logic(self):
if self._config.mode == 'Rigid':
self._landmark_transform.SetModeToRigidBody()
elif self._config.mode == 'Similarity':
self._landmark_transform.SetModeToSimilarity()
else:
self._landmark_transform.SetModeToAffine()
def execute_module(self):
self._sync_with_input_points()
self._landmark_transform.Update()
def _sync_with_input_points(self):
# the points have changed, let's see if they really have
if not (self._input_points[0] or self._input_points[1]):
return
all_points = self._input_points[0] + self._input_points[1]
# we want i['world'] eventually
temp_source_points = [i for i in all_points
if i['name'].lower().startswith('source')]
temp_target_points = [i for i in all_points
if i['name'].lower().startswith('target')]
# now put both source and target points in dict keyed on short
# name
slen = len('source')
sdict = {}
tdict = {}
for dict, points in [(sdict, temp_source_points), (tdict,
temp_target_points)]:
for point in points:
# turn 'source moo maa ' into 'moo maa'
name = point['name'][slen:].strip()
# stuff world position in dict keyed by name
dict[name] = point['world']
# use this as decorator list
snames = sdict.keys()
snames.sort()
temp_source_landmarks = [sdict[name] for name in snames]
try:
temp_target_landmarks = [tdict[name] for name in snames]
except KeyError:
raise RuntimeError("There is no target point named '%s'" %
(name))
if temp_source_landmarks != self._source_landmarks or \
temp_target_landmarks != self._target_landmarks:
self._source_landmarks = temp_source_landmarks
self._target_landmarks = temp_target_landmarks
source_landmarks = vtk.vtkPoints()
target_landmarks = vtk.vtkPoints()
landmarkPairs = ((self._source_landmarks, source_landmarks),
(self._target_landmarks, target_landmarks))
for lmp in landmarkPairs:
lmp[1].SetNumberOfPoints(len(lmp[0]))
for pointIdx in range(len(lmp[0])):
lmp[1].SetPoint(pointIdx, lmp[0][pointIdx])
self._landmark_transform.SetSourceLandmarks(source_landmarks)
self._landmark_transform.SetTargetLandmarks(target_landmarks)
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
OPS = ['add', 'subtract', 'multiply', 'divide', 'invert',
'sin', 'cos', 'exp', 'log', 'abs', 'sqr', 'sqrt', 'min',
'max', 'atan', 'atan2', 'multiply by k', 'add c', 'conjugate',
'complex multiply', 'replace c by k']
OPS_DICT = {}
for i,o in enumerate(OPS):
OPS_DICT[o] = i
class imageMathematics(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageMath = vtk.vtkImageMathematics()
self._imageMath.SetInput1(None)
self._imageMath.SetInput2(None)
module_utils.setup_vtk_object_progress(self, self._imageMath,
'Performing image math')
self._config.operation = 'subtract'
self._config.constantC = 0.0
self._config.constantK = 1.0
configList = [
('Operation:', 'operation', 'base:str', 'choice',
'The operation that should be performed.',
tuple(OPS_DICT.keys())),
('Constant C:', 'constantC', 'base:float', 'text',
'The constant C used in some operations.'),
('Constant K:', 'constantK', 'base:float', 'text',
'The constant C used in some operations.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageMathematics' : self._imageMath})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._imageMath
def get_input_descriptions(self):
return ('VTK Image Data 1', 'VTK Image Data 2')
def set_input(self, idx, inputStream):
if idx == 0:
self._imageMath.SetInput1(inputStream)
else:
self._imageMath.SetInput2(inputStream)
def get_output_descriptions(self):
return ('VTK Image Data Result',)
def get_output(self, idx):
return self._imageMath.GetOutput()
def logic_to_config(self):
o = self._imageMath.GetOperation()
# search for o in _operations
for name,idx in OPS_DICT.items():
if idx == o:
break
if idx == o:
self._config.operation = name
else:
# default is subtract
self._config.operation = 'Subtract'
self._config.constantC = self._imageMath.GetConstantC()
self._config.constantK = self._imageMath.GetConstantK()
def config_to_logic(self):
idx = OPS_DICT[self._config.operation]
self._imageMath.SetOperation(idx)
self._imageMath.SetConstantC(self._config.constantC)
self._imageMath.SetConstantK(self._config.constantK)
def execute_module(self):
self._imageMath.Update()
def streaming_execute_module(self):
self._imageMath.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class selectConnectedComponents(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._imageCast = vtk.vtkImageCast()
self._imageCast.SetOutputScalarTypeToUnsignedLong()
self._selectccs = vtkdevide.vtkSelectConnectedComponents()
self._selectccs.SetInput(self._imageCast.GetOutput())
module_utils.setup_vtk_object_progress(self, self._selectccs,
'Marking selected components')
module_utils.setup_vtk_object_progress(self, self._imageCast,
'Casting data to unsigned long')
# we'll use this to keep a binding (reference) to the passed object
self._inputPoints = None
# this will be our internal list of points
self._seedPoints = []
# now setup some defaults before our sync
self._config.outputConnectedValue = 1
self._config.outputUnconnectedValue = 0
configList = [
('Output Connected Value:', 'outputConnectedValue', 'base:int',
'text', 'This value will be assigned to all points in the '
'selected connected components.'),
('Output Unconnected Value:', 'outputUnconnectedValue', 'base:int',
'text', 'This value will be assigned to all points NOT in the '
'selected connected components.')
]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageCast' : self._imageCast,
'vtkSelectConnectedComponents' : self._selectccs})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._imageCast
del self._selectccs
def get_input_descriptions(self):
return ('VTK Connected Components (unsigned long)', 'Seed points')
def set_input(self, idx, inputStream):
if idx == 0:
# will work for None and not-None
self._imageCast.SetInput(inputStream)
else:
if inputStream != self._inputPoints:
self._inputPoints = inputStream
def get_output_descriptions(self):
return ('Selected connected components (vtkImageData)',)
def get_output(self, idx):
return self._selectccs.GetOutput()
def logic_to_config(self):
self._config.outputConnectedValue = self._selectccs.\
GetOutputConnectedValue()
self._config.outputUnconnectedValue = self._selectccs.\
GetOutputUnconnectedValue()
def config_to_logic(self):
self._selectccs.SetOutputConnectedValue(self._config.\
outputConnectedValue)
self._selectccs.SetOutputUnconnectedValue(self._config.\
outputUnconnectedValue)
def execute_module(self):
self._sync_to_input_points()
self._imageCast.Update()
self._selectccs.Update()
def _sync_to_input_points(self):
# extract a list from the input points
tempList = []
if self._inputPoints:
for i in self._inputPoints:
tempList.append(i['discrete'])
if tempList != self._seedPoints:
self._seedPoints = tempList
self._selectccs.RemoveAllSeeds()
# we need to call Modified() explicitly as RemoveAllSeeds()
# doesn't. AddSeed() does, but sometimes the list is empty at
# this stage and AddSeed() isn't called.
self._selectccs.Modified()
for seedPoint in self._seedPoints:
self._selectccs.AddSeed(seedPoint[0], seedPoint[1],
seedPoint[2])
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# TODO: simplify module!! all this muck was necessary due to the old
# demand-driven model. Keep the code around, it could be used as
# illustrative case.
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class modifyHomotopy(NoConfigModuleMixin, ModuleBase):
"""IMPORTANT: this module needs to be updated to the new
event-driven execution scheme. It should still work, but it may also
blow up your computer.
Modifies homotopy of input image I so that the only minima will
be at the user-specified seed-points or marker image, all other
minima will be suppressed and ridge lines separating minima will
be preserved.
Either the seed-points or the marker image (or both) can be used.
The marker image has to be >1 at the minima that are to be enforced
and 0 otherwise.
This module is often used as a pre-processing step to ensure that
the watershed doesn't over-segment.
This module uses a DeVIDE-specific implementation of Luc Vincent's
fast greyscale reconstruction algorithm, extended for 3D.
"""
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# these will be our markers
self._inputPoints = None
# we can't connect the image input directly to the masksource,
# so we have to keep track of it separately.
self._inputImage = None
self._inputImageObserverID = None
# we need to modify the mask (I) as well. The problem with a
# ProgrammableFilter is that you can't request GetOutput() before
# the input has been set...
self._maskSource = vtk.vtkProgrammableSource()
self._maskSource.SetExecuteMethod(self._maskSourceExecute)
self._dualGreyReconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D()
# first input is I (the modified mask)
self._dualGreyReconstruct.SetDual(1)
self._dualGreyReconstruct.SetInput1(self._maskSource.GetStructuredPointsOutput())
# we'll use this to synthesise a volume according to the seed points
self._markerSource = vtk.vtkProgrammableSource()
self._markerSource.SetExecuteMethod(self._markerSourceExecute)
# second input is J (the marker)
self._dualGreyReconstruct.SetInput2(
self._markerSource.GetStructuredPointsOutput())
# we'll use this to change the markerImage into something we can use
self._imageThreshold = vtk.vtkImageThreshold()
# everything equal to or above 1.0 will be "on"
self._imageThreshold.ThresholdByUpper(1.0)
self._imageThresholdObserverID = self._imageThreshold.AddObserver(
'EndEvent', self._observerImageThreshold)
module_utils.setup_vtk_object_progress(
self, self._dualGreyReconstruct,
'Performing dual greyscale reconstruction')
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkImageGreyscaleReconstruct3D' : self._dualGreyReconstruct})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
ModuleBase.close(self)
#
self._imageThreshold.RemoveObserver(self._imageThresholdObserverID)
# get rid of our reference
del self._dualGreyReconstruct
del self._markerSource
del self._maskSource
del self._imageThreshold
def get_input_descriptions(self):
return ('VTK Image Data', 'Minima points', 'Minima image')
def set_input(self, idx, inputStream):
if idx == 0:
if inputStream != self._inputImage:
# if we have a different image input, the seeds will have to
# be rebuilt!
self._markerSource.Modified()
# and obviously the masksource has to know that its "input"
# has changed
self._maskSource.Modified()
self._dualGreyReconstruct.Modified()
if inputStream:
# we have to add an observer
s = inputStream.GetSource()
if s:
self._inputImageObserverID = s.AddObserver(
'EndEvent', self._observerInputImage)
else:
# if we had an observer, remove it
if self._inputImage:
s = self._inputImage.GetSource()
if s and self._inputImageObserverID:
s.RemoveObserver(
self._inputImageObserverID)
self._inputImageObserverID = None
# finally store the new data
self._inputImage = inputStream
elif idx == 1:
if inputStream != self._inputPoints:
# check that the inputStream is either None (meaning
# disconnect) or a valid type
try:
if inputStream != None and \
inputStream.devideType != 'namedPoints':
raise TypeError
except (AttributeError, TypeError):
raise TypeError, 'This input requires a points-type'
if self._inputPoints:
self._inputPoints.removeObserver(
self._observerInputPoints)
self._inputPoints = inputStream
if self._inputPoints:
self._inputPoints.addObserver(self._observerInputPoints)
# the input points situation has changed, make sure
# the marker source knows this...
self._markerSource.Modified()
# as well as the mask source of course
self._maskSource.Modified()
self._dualGreyReconstruct.Modified()
else:
if inputStream != self._imageThreshold.GetInput():
self._imageThreshold.SetInput(inputStream)
# we have a different inputMarkerImage... have to recalc
self._markerSource.Modified()
self._maskSource.Modified()
self._dualGreyReconstruct.Modified()
def get_output_descriptions(self):
return ('Modified VTK Image Data', 'I input', 'J input')
def get_output(self, idx):
if idx == 0:
return self._dualGreyReconstruct.GetOutput()
elif idx == 1:
return self._maskSource.GetStructuredPointsOutput()
else:
return self._markerSource.GetStructuredPointsOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
self._dualGreyReconstruct.Update()
def _markerSourceExecute(self):
imageI = self._inputImage
if imageI:
imageI.Update()
# setup and allocate J output
outputJ = self._markerSource.GetStructuredPointsOutput()
# _dualGreyReconstruct wants inputs the same with regards to
# dimensions, origin and type, so this is okay.
outputJ.CopyStructure(imageI)
outputJ.AllocateScalars()
# we need this to build up J
minI, maxI = imageI.GetScalarRange()
mi = self._imageThreshold.GetInput()
if mi:
if mi.GetOrigin() == outputJ.GetOrigin() and \
mi.GetExtent() == outputJ.GetExtent():
self._imageThreshold.SetInValue(minI)
self._imageThreshold.SetOutValue(maxI)
self._imageThreshold.SetOutputScalarType(imageI.GetScalarType())
self._imageThreshold.GetOutput().SetUpdateExtentToWholeExtent()
self._imageThreshold.Update()
outputJ.DeepCopy(self._imageThreshold.GetOutput())
else:
vtk.vtkOutputWindow.GetInstance().DisplayErrorText(
'modifyHomotopy: marker input should be same dimensions as image input!')
# we can continue as if we only had seeds
scalars = outputJ.GetPointData().GetScalars()
scalars.FillComponent(0, maxI)
else:
# initialise all scalars to maxI
scalars = outputJ.GetPointData().GetScalars()
scalars.FillComponent(0, maxI)
# now go through all seed points and set those positions in
# the scalars to minI
if self._inputPoints:
for ip in self._inputPoints:
x,y,z = ip['discrete']
outputJ.SetScalarComponentFromDouble(x, y, z, 0, minI)
def _maskSourceExecute(self):
inputI = self._inputImage
if inputI:
inputI.Update()
self._markerSource.Update()
outputJ = self._markerSource.GetStructuredPointsOutput()
# we now have an outputJ
if not inputI.GetScalarPointer() or \
not outputJ.GetScalarPointer() or \
not inputI.GetDimensions() > (0,0,0):
vtk.vtkOutputWindow.GetInstance().DisplayErrorText(
'modifyHomotopy: Input is empty.')
return
iMath = vtk.vtkImageMathematics()
iMath.SetOperationToMin()
iMath.SetInput1(outputJ)
iMath.SetInput2(inputI)
iMath.GetOutput().SetUpdateExtentToWholeExtent()
iMath.Update()
outputI = self._maskSource.GetStructuredPointsOutput()
outputI.DeepCopy(iMath.GetOutput())
def _observerInputPoints(self, obj):
# this will be called if anything happens to the points
# simply make sure our markerSource knows that it's now invalid
self._markerSource.Modified()
self._maskSource.Modified()
self._dualGreyReconstruct.Modified()
def _observerInputImage(self, obj, eventName):
# the inputImage has changed, so the marker will have to change too
self._markerSource.Modified()
# logical, input image has changed
self._maskSource.Modified()
self._dualGreyReconstruct.Modified()
def _observerImageThreshold(self, obj, eventName):
# if anything in the threshold has changed, (e.g. the input) we
# have to invalidate everything else after it
self._markerSource.Modified()
self._maskSource.Modified()
self._dualGreyReconstruct.Modified()
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import wx
import vtk
class imageGradientMagnitude(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageGradientMagnitude = vtk.vtkImageGradientMagnitude()
self._imageGradientMagnitude.SetDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._imageGradientMagnitude,
'Calculating gradient magnitude')
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkImageGradientMagnitude' : self._imageGradientMagnitude})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._imageGradientMagnitude
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageGradientMagnitude.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageGradientMagnitude.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._imageGradientMagnitude.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
self._imageGradientMagnitude.Update()
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class ImageLogic(ScriptedConfigModuleMixin, ModuleBase):
# get these values from vtkImageMathematics.h
_operations = ('AND', 'OR', 'XOR', 'NAND', 'NOR', 'NOT', 'NOP')
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._image_logic = vtk.vtkImageLogic()
module_utils.setup_vtk_object_progress(self, self._image_logic,
'Performing image logic')
self._image_cast = vtk.vtkImageCast()
module_utils.setup_vtk_object_progress(
self, self._image_cast,
'Casting scalar type before image logic')
self._config.operation = 0
self._config.output_true_value = 1.0
# 'choice' widget with 'base:int' type will automatically get cast
# to index of selection that user makes.
config_list = [
('Operation:', 'operation', 'base:int', 'choice',
'The operation that should be performed.',
tuple(self._operations)),
('Output true value:', 'output_true_value', 'base:float', 'text',
'Output voxels that are TRUE will get this value.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkImageLogic' : self._image_logic})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._image_logic
del self._image_cast
def get_input_descriptions(self):
return ('VTK Image Data 1', 'VTK Image Data 2')
def set_input(self, idx, inputStream):
if idx == 0:
self._image_logic.SetInput(0, inputStream)
else:
self._image_cast.SetInput(inputStream)
def get_output_descriptions(self):
return ('VTK Image Data Result',)
def get_output(self, idx):
return self._image_logic.GetOutput()
def logic_to_config(self):
self._config.operation = self._image_logic.GetOperation()
self._config.output_true_value = \
self._image_logic.GetOutputTrueValue()
def config_to_logic(self):
self._image_logic.SetOperation(self._config.operation)
self._image_logic.SetOutputTrueValue(self._config.output_true_value)
def execute_module(self):
if self._image_logic.GetInput(0) is not None:
self._image_cast.SetOutputScalarType(
self._image_logic.GetInput(0).GetScalarType())
else:
raise RuntimeError(
'ImageLogic requires at least its first input to run.')
if self._image_cast.GetInput() is not None:
# both inputs, make sure image_cast is connected
self._image_logic.SetInput(1, self._image_cast.GetOutput())
else:
# only one input, disconnect image_cast
self._image_logic.SetInput(1, None)
self._image_logic.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class contour(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._contourFilter = vtk.vtkContourFilter()
module_utils.setup_vtk_object_progress(self, self._contourFilter,
'Extracting iso-surface')
# now setup some defaults before our sync
self._config.iso_value = 128
config_list = [
('ISO value:', 'iso_value', 'base:float', 'text',
'Surface will pass through points with this value.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkContourFilter' : self._contourFilter})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
self.set_input(0, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._contourFilter
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._contourFilter.SetInput(inputStream)
def get_output_descriptions(self):
return (self._contourFilter.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._contourFilter.GetOutput()
def logic_to_config(self):
self._config.iso_value = self._contourFilter.GetValue(0)
def config_to_logic(self):
self._contourFilter.SetValue(0, self._config.iso_value)
def execute_module(self):
self._contourFilter.Update()
def streaming_execute_module(self):
self._contourFilter.Update()
| Python |
# Modified by FrancoisMalan 2011-12-06 so that it can handle an input with larger
# extent than its source. Changes constitute the padder module and pad_source method
import gen_utils
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class probeFilter(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# what a lame-assed filter, we have to make dummy inputs!
# if we don't have a dummy input (but instead a None input) it
# bitterly complains when we do a GetOutput() (it needs the input
# to know the type of the output) - and GetPolyDataOutput() also
# doesn't work.
# NB: this does mean that our probeFilter NEEDS a PolyData as
# probe geometry!
ss = vtk.vtkSphereSource()
ss.SetRadius(0)
self._dummyInput = ss.GetOutput()
#This is also retarded - we (sometimes, see below) need the "padder"
#to get the image extent big enough to satisfy the probe filter.
#No apparent logical reason, but it throws an exception if we don't.
self._padder = vtk.vtkImageConstantPad()
self._source = None
self._input = None
self._probeFilter = vtk.vtkProbeFilter()
self._probeFilter.SetInput(self._dummyInput)
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkProbeFilter' : self._probeFilter})
module_utils.setup_vtk_object_progress(self, self._probeFilter,
'Mapping source on input')
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
NoConfigModuleMixin.close(self)
# get rid of our reference
del self._probeFilter
del self._dummyInput
del self._padder
del self._source
del self._input
def get_input_descriptions(self):
return ('Input', 'Source')
def set_input(self, idx, inputStream):
if idx == 0:
self._input = inputStream
else:
self._source = inputStream
def get_output_descriptions(self):
return ('Input with mapped source values',)
def get_output(self, idx):
return self._probeFilter.GetOutput()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def pad_source(self):
input_extent = self._input.GetExtent()
source_extent = self._source.GetExtent()
if (input_extent[0] < source_extent[0]) or (input_extent[2] < source_extent[2]) or (input_extent[4] < source_extent[4]):
raise Exception('Output extent starts at lower index than source extent. Assumed that both should be zero?')
elif (input_extent[1] > source_extent[1]) or (input_extent[3] > source_extent[3]) or (input_extent[5] > source_extent[5]):
extX = max(input_extent[1], source_extent[1])
extY = max(input_extent[3], source_extent[3])
extZ = max(input_extent[5], source_extent[5])
padX = extX - source_extent[1]
padY = extY - source_extent[3]
padZ = extZ - source_extent[5]
print 'Zero-padding source by (%d, %d, %d) voxels to force extent to match/exceed input''s extent. Lame, eh?' % (padX, padY, padZ)
self._padder.SetInput(self._source)
self._padder.SetConstant(0.0)
self._padder.SetOutputWholeExtent(source_extent[0],extX,source_extent[2],extY,source_extent[4],extZ)
self._padder.Update()
self._source.DeepCopy(self._padder.GetOutput())
def execute_module(self):
if self._source.IsA('vtkImageData') and self._input.IsA('vtkImageData'):
self.pad_source()
self._probeFilter.SetInput(self._input)
self._probeFilter.SetSource(self._source)
self._probeFilter.Update() | Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_kits.vtk_kit
import module_utils
import vtk
import wx
from module_kits.misc_kit.devide_types import MedicalMetaData
class EditMedicalMetaData(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._input_mmd = None
self._output_mmd = MedicalMetaData()
self._output_mmd.medical_image_properties = \
vtk.vtkMedicalImageProperties()
self._output_mmd.direction_cosines = \
vtk.vtkMatrix4x4()
# if the value (as it appears in mk.vtk_kit.constants.mipk)
# appears in the dict, its value refers to the user supplied
# value. when the user resets a field, that key is removed
# from the dict
self._config.new_value_dict = {}
# this is the list of relevant properties
self.mip_attr_l = \
module_kits.vtk_kit.constants.medical_image_properties_keywords
# this will be used to keep track of changes made to the prop
# grid before they are applied to the config
self._grid_value_dict = {}
self._view_frame = None
self.sync_module_logic_with_config()
def close(self):
IntrospectModuleMixin.close(self)
if self._view_frame is not None:
self._view_frame.Destroy()
ModuleBase.close(self)
def get_input_descriptions(self):
return ('Medical Meta Data',)
def set_input(self, idx, input_stream):
self._input_mmd = input_stream
def get_output_descriptions(self):
return ('Medical Meta Data',)
def get_output(self, idx):
return self._output_mmd
def execute_module(self):
# 1. if self._input_mmd is set, copy from self._input_mmd to
# self._output_mmd (mmd.deep_copy checks for None)
self._output_mmd.deep_copy(self._input_mmd)
# 2. show input_mmd.medical_image_properties values in the
# 'current values' column of the properties grid, only if this
# module's view has already been shown
self._grid_sync_with_current()
# 3. apply only changed fields from interface
mip = self._output_mmd.medical_image_properties
for key,val in self._config.new_value_dict.items():
getattr(mip, 'Set%s' % (key))(val)
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def config_to_view(self):
if self._config.new_value_dict != self._grid_value_dict:
self._grid_value_dict.clear()
self._grid_value_dict.update(self._config.new_value_dict)
# now sync grid_value_dict to actual GUI
self._grid_sync_with_dict()
def view_to_config(self):
if self._config.new_value_dict == self._grid_value_dict:
# these two are still equal, so we don't have to do
# anything. Return False to indicate that nothing has
# changed.
return False
# transfer all values from grid_value_dict to dict in config
self._config.new_value_dict.clear()
self._config.new_value_dict.update(self._grid_value_dict)
def view(self):
# all fields touched by user are recorded. when we get a new
# input, these fields are left untouched. mmmkay?
if self._view_frame is None:
self._create_view_frame()
self.sync_module_view_with_logic()
self._view_frame.Show(True)
self._view_frame.Raise()
def _create_view_frame(self):
import modules.filters.resources.python.EditMedicalMetaDataViewFrame
reload(modules.filters.resources.python.EditMedicalMetaDataViewFrame)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.filters.resources.python.EditMedicalMetaDataViewFrame.\
EditMedicalMetaDataViewFrame)
# resize the grid and populate it with the various property
# names
grid = self._view_frame.prop_grid
grid.DeleteRows(0, grid.GetNumberRows())
grid.AppendRows(len(self.mip_attr_l))
for i in range(len(self.mip_attr_l)):
grid.SetCellValue(i, 0, self.mip_attr_l[i])
# key is read-only
grid.SetReadOnly(i, 0)
# current value is also read-only
grid.SetReadOnly(i, 1)
# use special method to set new value (this also takes
# care of cell colouring)
self._grid_set_new_val(i, None)
# make sure the first column fits neatly around the largest
# key name
grid.AutoSizeColumn(0)
def handler_grid_cell_change(event):
# event is a wx.GridEvent
r,c = event.GetRow(), event.GetCol()
grid = self._view_frame.prop_grid
key = self.mip_attr_l[r]
gval = grid.GetCellValue(r,c)
if gval == '':
# this means the user doesn't want this field to be
# changed, so we have to remove it from the
# _grid_value_dict and we have to adapt the cell
del self._grid_value_dict[key]
# we only use this to change the cell background
self._grid_set_new_val(r, gval, value_change=False)
else:
# the user has changed the value, so set it in the
# prop dictionary
self._grid_value_dict[key] = gval
# and make sure the background colour is changed
# appropriately.
self._grid_set_new_val(r, gval, value_change=False)
grid.Bind(wx.grid.EVT_GRID_CELL_CHANGE, handler_grid_cell_change)
object_dict = {
'Module (self)' : self}
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.view_frame_panel,
object_dict, None)
# we don't want enter to OK and escape to cancel, as these are
# used for confirming and cancelling grid editing operations
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.view_frame_panel,
ok_default=False,
cancel_hotkey=False)
# follow ModuleBase convention to indicate that we now have
# a view
self.view_initialised = True
self._grid_sync_with_current()
def _grid_set_new_val(self, row, val, value_change=True):
grid = self._view_frame.prop_grid
if not val is None:
if value_change:
# this does not trigger the CELL_CHANGE handler
grid.SetCellValue(row, 2, val)
grid.SetCellBackgroundColour(row, 2, wx.WHITE)
else:
if value_change:
# this does not trigger the CELL_CHANGE handler
grid.SetCellValue(row, 2, '')
grid.SetCellBackgroundColour(row, 2, wx.LIGHT_GREY)
def _grid_sync_with_current(self):
"""If there's an input_mmd, read out all its data and populate
the current values column. This method is called by the
execute_data and also by _create_view_frame.
"""
# we only do this if we have a view
if not self.view_initialised:
return
if not self._input_mmd is None and \
self._input_mmd.__class__ == \
MedicalMetaData:
mip = self._input_mmd.medical_image_properties
grid = self._view_frame.prop_grid
for i in range(len(self.mip_attr_l)):
key = self.mip_attr_l[i]
val = getattr(mip, 'Get%s' % (key,))()
if val == None:
val = ''
grid.SetCellValue(i, 1, val)
def _grid_sync_with_dict(self):
"""Synchronise property grid with _grid_value_dict ivar.
"""
for kidx in range(len(self.mip_attr_l)):
key = self.mip_attr_l[kidx]
val = self._grid_value_dict.get(key,None)
self._grid_set_new_val(kidx, val)
| Python |
# decimateFLT.py copyright (c) 2003 by Charl P. Botha http://cpbotha.net/
# $Id$
# module that triangulates and decimates polygonal input
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class decimate(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
# the decimator only works on triangle data, so we make sure
# that it only gets triangle data
self._triFilter = vtk.vtkTriangleFilter()
self._decimate = vtk.vtkDecimatePro()
self._decimate.PreserveTopologyOn()
self._decimate.SetInput(self._triFilter.GetOutput())
module_utils.setup_vtk_object_progress(self, self._triFilter,
'Converting to triangles')
module_utils.setup_vtk_object_progress(self, self._decimate,
'Decimating mesh')
# now setup some defaults before our sync
self._config.target_reduction = self._decimate.GetTargetReduction() \
* 100.0
config_list = [
('Target reduction (%):', 'target_reduction', 'base:float', 'text',
'Decimate algorithm will attempt to reduce by this much.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkDecimatePro' : self._decimate,
'vtkTriangleFilter' : self._triFilter})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
self.set_input(0, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._decimate
del self._triFilter
def get_input_descriptions(self):
return ('vtkPolyData',)
def set_input(self, idx, inputStream):
self._triFilter.SetInput(inputStream)
def get_output_descriptions(self):
return (self._decimate.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._decimate.GetOutput()
def logic_to_config(self):
self._config.target_reduction = self._decimate.GetTargetReduction() \
* 100.0
def config_to_logic(self):
self._decimate.SetTargetReduction(
self._config.target_reduction / 100.0)
def execute_module(self):
# get the filter doing its thing
self._triFilter.Update()
self._decimate.Update()
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import vtk
DEFAULT_SELECTION_STRING = 'Default active array'
class InputArrayChoiceMixin:
def __init__(self):
self._config.vectorsSelection = DEFAULT_SELECTION_STRING
self._config.input_array_names = []
self._config.actual_input_array = None
def iac_logic_to_config(self, input_array_filter, array_idx=1):
"""VTK documentation doesn't really specify what the parameter
to GetInputArrayInformation() expects. If you know, please
let me know. It *seems* like it should match the one given to
SetInputArrayToProcess.
"""
names = []
# this is the new way of checking input connections
if input_array_filter.GetNumberOfInputConnections(0):
pd = input_array_filter.GetInput().GetPointData()
if pd:
# get a list of attribute names
for i in range(pd.GetNumberOfArrays()):
names.append(pd.GetArray(i).GetName())
self._config.input_array_names = names
inf = input_array_filter.GetInputArrayInformation(array_idx)
vs = inf.Get(vtk.vtkDataObject.FIELD_NAME())
self._config.actual_input_array = vs
def iac_config_to_view(self, choice_widget):
# find out what the choices CURRENTLY are (except for the
# default and the "user defined")
choiceNames = []
ccnt = choice_widget.GetCount()
for i in range(ccnt):
# cast unicode strings to python default strings
choice_string = str(choice_widget.GetString(i))
if choice_string != DEFAULT_SELECTION_STRING:
choiceNames.append(choice_string)
names = self._config.input_array_names
if choiceNames != names:
# this means things have changed, we have to rebuild
# the choice
choice_widget.Clear()
choice_widget.Append(DEFAULT_SELECTION_STRING)
for name in names:
choice_widget.Append(name)
if self._config.actual_input_array:
si = choice_widget.FindString(self._config.actual_input_array)
if si == -1:
# string not found, that means the user has been playing
# behind our backs, (or he's loading a valid selection
# from DVN) so we add it to the choice as well
choice_widget.Append(self._config.actual_input_array)
choice_widget.SetStringSelection(self._config.actual_input_array)
else:
choice_widget.SetSelection(si)
else:
# no vector selection, so default
choice_widget.SetSelection(0)
def iac_config_to_logic(self, input_array_filter,
array_idx=1, port=0, conn=0):
"""Makes sure 'vectorsSelection' from self._config is applied
to the used vtkGlyph3D filter.
For some filters (vtkGlyph3D) array_idx needs to be 1, for
others (vtkWarpVector, vtkStreamTracer) it needs to be 0.
"""
if self._config.vectorsSelection == \
DEFAULT_SELECTION_STRING:
# default: idx, port, connection, fieldassociation (points), name
input_array_filter.SetInputArrayToProcess(
array_idx, port, conn, 0, None)
else:
input_array_filter.SetInputArrayToProcess(
array_idx, port, conn, 0, self._config.vectorsSelection)
def iac_execute_module(
self, input_array_filter, choice_widget, array_idx):
"""Hook to be called by the class that uses this mixin to
ensure that after the first execute with a displayed view, the
choice widget has been updated.
See glyph module for an example.
"""
self.iac_logic_to_config(input_array_filter, array_idx)
self.iac_config_to_view(choice_widget)
| Python |
# glenoidMouldDesigner.py copyright 2003 Charl P. Botha http://cpbotha.net/
# $Id$
# devide module that designs glenoid moulds by making use of insertion
# axis and model of scapula
# this module doesn't satisfy the event handling requirements of DeVIDE yet
# if you call update on the output PolyData, this module won't know to
# execute, because at the moment main processing takes place in Python-land
# this will be so at least until we convert the processing to a vtkSource
# child that has the PolyData as output or until we fake it with Observers
# This is not critical.
import math
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import operator
import vtk
class glenoidMouldDesign(ModuleBase, NoConfigModuleMixin):
drillGuideInnerDiameter = 3
drillGuideOuterDiameter = 5
drillGuideHeight = 10
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
# and mixin
NoConfigModuleMixin.__init__(self)
self._inputPolyData = None
self._inputPoints = None
self._inputPointsOID = None
self._giaGlenoid = None
self._giaHumerus = None
self._glenoidEdge = None
self._outputPolyData = vtk.vtkPolyData()
# create the frame and display it proudly!
self._viewFrame = self._createViewFrame(
{'Output Polydata': self._outputPolyData})
def close(self):
# disconnect all inputs
self.set_input(0, None)
self.set_input(1, None)
# take care of critical instances
self._outputPolyData = None
# mixin close
NoConfigModuleMixin.close(self)
def get_input_descriptions(self):
return('Scapula vtkPolyData', 'Insertion axis (points)')
def set_input(self, idx, inputStream):
if idx == 0:
# will work for None and not-None
self._inputPolyData = inputStream
else:
if inputStream is not self._inputPoints:
if self._inputPoints:
self._inputPoints.removeObserver(self._inputPointsOID)
if inputStream:
self._inputPointsOID = inputStream.addObserver(
self._inputPointsObserver)
self._inputPoints = inputStream
# initial update
self._inputPointsObserver(None)
def get_output_descriptions(self):
return ('Mould design (vtkPolyData)',) # for now
def get_output(self, idx):
return self._outputPolyData
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
if self._giaHumerus and self._giaGlenoid and \
len(self._glenoidEdge) >= 6 and self._inputPolyData:
# _glenoidEdgeImplicitFunction
# construct eight planes with the insertion axis as mid-line
# the planes should go somewhat further proximally than the
# proximal insertion axis point
# first calculate the distal-proximal glenoid insertion axis
gia = tuple(map(operator.sub, self._giaGlenoid, self._giaHumerus))
# and in one swift move, we normalize it and get the magnitude
giaN = list(gia)
giaM = vtk.vtkMath.Normalize(giaN)
# extend gia with a few millimetres
giaM += 5
gia = tuple([giaM * i for i in giaN])
stuff = []
yN = [0,0,0]
zN = [0,0,0]
angleIncr = 2.0 * vtk.vtkMath.Pi() / 8.0
for i in range(4):
angle = float(i) * angleIncr
vtk.vtkMath.Perpendiculars(gia, yN, zN, angle)
# each ridge is 1 cm (10 mm) - we'll change this later
y = [10.0 * j for j in yN]
origin = map(operator.add, self._giaHumerus, y)
point1 = map(operator.add, origin, [-2.0 * k for k in y])
point2 = map(operator.add, origin, gia)
# now create the plane source
ps = vtk.vtkPlaneSource()
ps.SetOrigin(origin)
ps.SetPoint1(point1)
ps.SetPoint2(point2)
ps.Update()
plane = vtk.vtkPlane()
plane.SetOrigin(ps.GetOrigin())
plane.SetNormal(ps.GetNormal())
pdn = vtk.vtkPolyDataNormals()
pdn.SetInput(self._inputPolyData)
cut = vtk.vtkCutter()
cut.SetInput(pdn.GetOutput())
cut.SetCutFunction(plane)
cut.GenerateCutScalarsOn()
cut.SetValue(0,0)
cut.Update()
contour = cut.GetOutput()
# now find line segment closest to self._giaGlenoid
pl = vtk.vtkPointLocator()
pl.SetDataSet(contour)
pl.BuildLocator()
startPtId = pl.FindClosestPoint(self._giaGlenoid)
cellIds = vtk.vtkIdList()
contour.GetPointCells(startPtId, cellIds)
twoLineIds = cellIds.GetId(0), cellIds.GetId(1)
ptIds = vtk.vtkIdList()
cellIds = vtk.vtkIdList()
# we'll use these to store tuples:
# (ptId, (pt0, pt1, pt2), (n0, n1, n2))
lines = [[],[]]
lineIdx = 0
for startLineId in twoLineIds:
# we have a startLineId, a startPtId and polyData
curStartPtId = startPtId
curLineId = startLineId
onGlenoid = True
offCount = 0
while onGlenoid:
contour.GetCellPoints(curLineId, ptIds)
if ptIds.GetNumberOfIds() != 2:
print 'aaaaaaaaaaaaack!'
ptId0 = ptIds.GetId(0)
ptId1 = ptIds.GetId(1)
nextPointId = [ptId0, ptId1]\
[bool(ptId0 == curStartPtId)]
contour.GetPointCells(nextPointId, cellIds)
if cellIds.GetNumberOfIds() != 2:
print 'aaaaaaaaaaaaaaaack2!'
cId0 = cellIds.GetId(0)
cId1 = cellIds.GetId(1)
nextLineId = [cId0, cId1]\
[bool(cId0 == curLineId)]
# get the normal for the current point
n = contour.GetPointData().GetNormals().GetTuple3(
curStartPtId)
# get the current point
pt0 = contour.GetPoints().GetPoint(curStartPtId)
# store the real ptid, point coords and normal
lines[lineIdx].append((curStartPtId,
tuple(pt0), tuple(n)))
if vtk.vtkMath.Dot(giaN, n) > -0.9:
# this means that this point could be falling off
# the glenoid, let's make a note of the incident
offCount += 1
# if the last N points have been "off" the glenoid,
# it could mean we've really fallen off!
if offCount >= 40:
del lines[lineIdx][-40:]
onGlenoid = False
# get ready for next iteration
curStartPtId = nextPointId
curLineId = nextLineId
# closes: while onGlenoid
lineIdx += 1
# closes: for startLineId in twoLineIds
# we now have two line lists... we have to combine them and
# make sure it still constitutes one long line
lines[0].reverse()
edgeLine = lines[0] + lines[1]
# do line extrusion resulting in a list of 5-element tuples,
# each tuple representing the 5 3-d vertices of a "house"
houses = self._lineExtrudeHouse(edgeLine, plane)
# we will dump ALL the new points in here
newPoints = vtk.vtkPoints()
newPoints.SetDataType(contour.GetPoints().GetDataType())
# but we're going to create 5 lines
idLists = [vtk.vtkIdList() for i in range(5)]
for house in houses:
for vertexIdx in range(5):
ptId = newPoints.InsertNextPoint(house[vertexIdx])
idLists[vertexIdx].InsertNextId(ptId)
# create a cell with the 5 lines
newCellArray = vtk.vtkCellArray()
for idList in idLists:
newCellArray.InsertNextCell(idList)
newPolyData = vtk.vtkPolyData()
newPolyData.SetLines(newCellArray)
newPolyData.SetPoints(newPoints)
rsf = vtk.vtkRuledSurfaceFilter()
rsf.CloseSurfaceOn()
#rsf.SetRuledModeToPointWalk()
rsf.SetRuledModeToResample()
rsf.SetResolution(128, 4)
rsf.SetInput(newPolyData)
rsf.Update()
stuff.append(rsf.GetOutput())
# also add two housies to cap all the ends
capHousePoints = vtk.vtkPoints()
capHouses = []
if len(houses) > 1:
# we only cap if there are at least two houses
capHouses.append(houses[0])
capHouses.append(houses[-1])
capHouseIdLists = [vtk.vtkIdList() for dummy in capHouses]
for capHouseIdx in range(len(capHouseIdLists)):
house = capHouses[capHouseIdx]
for vertexIdx in range(5):
ptId = capHousePoints.InsertNextPoint(house[vertexIdx])
capHouseIdLists[capHouseIdx].InsertNextId(ptId)
if capHouseIdLists:
newPolyArray = vtk.vtkCellArray()
for capHouseIdList in capHouseIdLists:
newPolyArray.InsertNextCell(capHouseIdList)
capPolyData = vtk.vtkPolyData()
capPolyData.SetPoints(capHousePoints)
capPolyData.SetPolys(newPolyArray)
# FIXME: put back
stuff.append(capPolyData)
# closes: for i in range(4)
ap = vtk.vtkAppendPolyData()
# copy everything to output (for testing)
for thing in stuff:
ap.AddInput(thing)
#ap.AddInput(stuff[0])
# seems to be important for vtkAppendPolyData
ap.Update()
# now cut it with the FBZ planes
fbzSupPlane = self._fbzCutPlane(self._fbzSup, giaN,
self._giaGlenoid)
fbzSupClip = vtk.vtkClipPolyData()
fbzSupClip.SetClipFunction(fbzSupPlane)
fbzSupClip.SetValue(0)
fbzSupClip.SetInput(ap.GetOutput())
fbzInfPlane = self._fbzCutPlane(self._fbzInf, giaN,
self._giaGlenoid)
fbzInfClip = vtk.vtkClipPolyData()
fbzInfClip.SetClipFunction(fbzInfPlane)
fbzInfClip.SetValue(0)
fbzInfClip.SetInput(fbzSupClip.GetOutput())
cylinder = vtk.vtkCylinder()
cylinder.SetCenter([0,0,0])
# we make the cut-cylinder slightly larger... it's only there
# to cut away the surface edges, so precision is not relevant
cylinder.SetRadius(self.drillGuideInnerDiameter / 2.0)
# cylinder is oriented along y-axis (0,1,0) -
# we need to calculate the angle between the y-axis and the gia
# 1. calc dot product (|a||b|cos(\phi))
cylDotGia = - giaN[1]
# 2. because both factors are normals, angle == acos
phiRads = math.acos(cylDotGia)
# 3. cp is the vector around which gia can be turned to
# coincide with the y-axis
cp = [0,0,0]
vtk.vtkMath.Cross((-giaN[0], -giaN[1], -giaN[2]),
(0.0, 1.0, 0.0), cp)
# this transform will be applied to all points BEFORE they are
# tested on the cylinder implicit function
trfm = vtk.vtkTransform()
# it's premultiply by default, so the last operation will get
# applied FIRST:
# THEN rotate it around the cp axis so it's relative to the
# y-axis instead of the gia-axis
trfm.RotateWXYZ(phiRads * vtk.vtkMath.RadiansToDegrees(),
cp[0], cp[1], cp[2])
# first translate the point back to the origin
trfm.Translate(-self._giaGlenoid[0], -self._giaGlenoid[1],
-self._giaGlenoid[2])
cylinder.SetTransform(trfm)
cylinderClip = vtk.vtkClipPolyData()
cylinderClip.SetClipFunction(cylinder)
cylinderClip.SetValue(0)
cylinderClip.SetInput(fbzInfClip.GetOutput())
cylinderClip.GenerateClipScalarsOn()
ap2 = vtk.vtkAppendPolyData()
ap2.AddInput(cylinderClip.GetOutput())
# this will cap the just cut polydata
ap2.AddInput(self._capCutPolyData(fbzSupClip))
ap2.AddInput(self._capCutPolyData(fbzInfClip))
# thees one she dosint werk so gooood
#ap2.AddInput(self._capCutPolyData(cylinderClip))
# now add outer guide cylinder, NOT capped
cs1 = vtk.vtkCylinderSource()
cs1.SetResolution(32)
cs1.SetRadius(self.drillGuideOuterDiameter / 2.0)
cs1.CappingOff()
cs1.SetHeight(self.drillGuideHeight) # 15 mm height
cs1.SetCenter(0,0,0)
cs1.Update()
# inner cylinder
cs2 = vtk.vtkCylinderSource()
cs2.SetResolution(32)
cs2.SetRadius(self.drillGuideInnerDiameter / 2.0)
cs2.CappingOff()
cs2.SetHeight(self.drillGuideHeight) # 15 mm height
cs2.SetCenter(0,0,0)
cs2.Update()
# top cap
tc = vtk.vtkDiskSource()
tc.SetInnerRadius(self.drillGuideInnerDiameter / 2.0)
tc.SetOuterRadius(self.drillGuideOuterDiameter / 2.0)
tc.SetCircumferentialResolution(64)
tcTrfm = vtk.vtkTransform()
# THEN flip it so that its centre-line is the y-axis
tcTrfm.RotateX(90)
# FIRST translate the disc
tcTrfm.Translate(0,0,- self.drillGuideHeight / 2.0)
tcTPDF = vtk.vtkTransformPolyDataFilter()
tcTPDF.SetTransform(tcTrfm)
tcTPDF.SetInput(tc.GetOutput())
# bottom cap
bc = vtk.vtkDiskSource()
bc.SetInnerRadius(self.drillGuideInnerDiameter / 2.0)
bc.SetOuterRadius(self.drillGuideOuterDiameter / 2.0)
bc.SetCircumferentialResolution(64)
bcTrfm = vtk.vtkTransform()
# THEN flip it so that its centre-line is the y-axis
bcTrfm.RotateX(90)
# FIRST translate the disc
bcTrfm.Translate(0,0, self.drillGuideHeight / 2.0)
bcTPDF = vtk.vtkTransformPolyDataFilter()
bcTPDF.SetTransform(bcTrfm)
bcTPDF.SetInput(bc.GetOutput())
tubeAP = vtk.vtkAppendPolyData()
tubeAP.AddInput(cs1.GetOutput())
tubeAP.AddInput(cs2.GetOutput())
tubeAP.AddInput(tcTPDF.GetOutput())
tubeAP.AddInput(bcTPDF.GetOutput())
# we have to transform this fucker as well
csTrfm = vtk.vtkTransform()
# go half the height + 2mm upwards from surface
drillGuideCentre = - 1.0 * self.drillGuideHeight / 2.0 - 2
cs1Centre = map(operator.add,
self._giaGlenoid,
[drillGuideCentre * i for i in giaN])
# once again, this is performed LAST
csTrfm.Translate(cs1Centre)
# and this FIRST (we have to rotate the OTHER way than for
# the implicit cylinder cutting, because the cylinder is
# transformed from y-axis to gia, not the other way round)
csTrfm.RotateWXYZ(-phiRads * vtk.vtkMath.RadiansToDegrees(),
cp[0], cp[1], cp[2])
# actually perform the transform
csTPDF = vtk.vtkTransformPolyDataFilter()
csTPDF.SetTransform(csTrfm)
csTPDF.SetInput(tubeAP.GetOutput())
csTPDF.Update()
ap2.AddInput(csTPDF.GetOutput())
ap2.Update()
self._outputPolyData.DeepCopy(ap2.GetOutput())
def view(self):
if not self._viewFrame.Show(True):
self._viewFrame.Raise()
def _buildHouse(self, startPoint, startPointNormal, cutPlane):
"""Calculate the vertices of a single house.
Given a point on the cutPlane, the normal at that point and
the cutPlane normal, this method will calculate and return the
five points (including the start point) defining the
upside-down house. The house is of course oriented with the point
normal projected onto the cutPlane (then normalized again) and the
cutPlaneNormal.
p3 +--+ p2
| |
p4 +--+ p1
\/
p0
startPoint, startPointNormal and cutPlaneNormal are all 3-element
Python tuples. Err, this now returns 6 points. The 6th is a
convenience so that our calling function can easily check for
negative volume. See _lineExtrudeHouse.
"""
# xo = x - o
# t = xo dot normal
# h = x - t * normal
t = vtk.vtkMath.Dot(startPointNormal, cutPlane.GetNormal())
houseNormal = map(operator.sub, startPointNormal,
[t * i for i in cutPlane.GetNormal()])
vtk.vtkMath.Normalize(houseNormal)
houseNormal3 = [3.0 * i for i in houseNormal]
cutPlaneNormal1_5 = [1.5 * i for i in cutPlane.GetNormal()]
mp = map(operator.add, startPoint, houseNormal3)
p1 = tuple(map(operator.add, mp, cutPlaneNormal1_5))
p2 = tuple(map(operator.add, p1, houseNormal3))
p4 = tuple(map(operator.sub, mp, cutPlaneNormal1_5))
p3 = tuple(map(operator.add, p4, houseNormal3))
p5 = tuple(map(operator.add, mp, houseNormal3))
return (tuple(startPoint), p1, p2, p3, p4, p5)
def _capCutPolyData(self, clipPolyData):
# set a vtkCutter up exactly like the vtkClipPolyData
cutter = vtk.vtkCutter()
cutter.SetCutFunction(clipPolyData.GetClipFunction())
cutter.SetInput(clipPolyData.GetInput())
cutter.SetValue(0, clipPolyData.GetValue())
cutter.SetGenerateCutScalars(clipPolyData.GetGenerateClipScalars())
cutStripper = vtk.vtkStripper()
cutStripper.SetInput(cutter.GetOutput())
cutStripper.Update()
cutPolyData = vtk.vtkPolyData()
cutPolyData.SetPoints(cutStripper.GetOutput().GetPoints())
cutPolyData.SetPolys(cutStripper.GetOutput().GetLines())
cpd = vtk.vtkCleanPolyData()
cpd.SetInput(cutPolyData)
tf = vtk.vtkTriangleFilter()
tf.SetInput(cpd.GetOutput())
tf.Update()
return tf.GetOutput()
def _fbzCutPlane(self, fbz, giaN, giaGlenoid):
"""Calculate cut-plane corresponding to fbz.
fbz is a list containing the two points defining a single FBZ
(forbidden zone). giaN is the glenoid-insertion axis normal.
giaGlenoid is the user-selected gia point on the glenoid.
This method will return a cut-plane to enforce the given fbz such
that giaGlenoid is on the inside of the implicit plane.
"""
fbzV = map(operator.sub, fbz[0], fbz[1])
fbzPN = [0,0,0]
vtk.vtkMath.Cross(fbzV, giaN, fbzPN)
vtk.vtkMath.Normalize(fbzPN)
fbzPlane = vtk.vtkPlane()
fbzPlane.SetOrigin(fbz[0])
fbzPlane.SetNormal(fbzPN)
insideVal = fbzPlane.EvaluateFunction(giaGlenoid)
if insideVal < 0:
# eeep, it's outside, so flip the planeNormal
fbzPN = [-1.0 * i for i in fbzPN]
fbzPlane.SetNormal(fbzPN)
return fbzPlane
def _glenoidEdgeImplicitFunction(self, giaGlenoid, edgePoints):
"""Given the on-glenoid point of the glenoid insertion axis and 6
points (in sequence) around the glenoid edge, this will construct
a vtk implicit function that can be used to check whether surface
points are inside or outside.
"""
def _lineExtrudeHouse(self, edgeLine, cutPlane):
"""Extrude the house (square with triangle as roof) along edgeLine.
edgeLine is a list of tuples where each tuple is:
(ptId, (p0, p1, p2), (n0, n1, n2)) with P the point coordinate and
N the normal at that point. The normal determines the orientation
of the housy.
The result is just a line extrusion, i.e. no surfaces yet. In order
to do that, run the output (after it has been converted to a polydata)
through a vtkRuledSurfaceFilter.
This method returns a list of 5-element tuples.
"""
newEdgeLine = []
prevHousePoint0 = None
prevHousePoint5 = None
for point in edgeLine:
housePoints = self._buildHouse(point[1], point[2], cutPlane)
if prevHousePoint0:
v0 = map(operator.sub, housePoints[0], prevHousePoint0)
v1 = map(operator.sub, housePoints[5], prevHousePoint5)
# bad-assed trick to test for negative volume
if vtk.vtkMath.Dot(v0, v1) < 0.0:
negativeVolume = 1
else:
negativeVolume = 0
else:
negativeVolume = 0
if not negativeVolume:
newEdgeLine.append(housePoints[:5])
# we only store it as previous if we actually add it
prevHousePoint0 = housePoints[0]
prevHousePoint5 = housePoints[5]
return newEdgeLine
def _inputPointsObserver(self, obj):
# extract a list from the input points
if self._inputPoints:
# extract the two points with labels 'GIA Glenoid'
# and 'GIA Humerus'
giaGlenoid = [i['world'] for i in self._inputPoints
if i['name'] == 'GIA Glenoid']
giaHumerus = [i['world'] for i in self._inputPoints
if i['name'] == 'GIA Humerus']
glenoidEdge = [i['world'] for i in self._inputPoints
if i['name'] == 'Glenoid Edge Point']
if giaGlenoid and giaHumerus and \
len(glenoidEdge) >= 6:
# we only apply these points to our internal parameters
# if they're valid and if they're new
self._giaGlenoid = giaGlenoid[0]
self._giaHumerus = giaHumerus[0]
self._glenoidEdge = glenoidEdge[:6]
| Python |
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class transformImageToTarget(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._reslicer = vtk.vtkImageReslice()
self._probefilter = vtk.vtkProbeFilter()
#This is retarded - we (sometimes, see below) need the padder
#to get the image extent big enough to satisfy the probe filter.
#No apparent logical reason, but it throws an exception if we don't.
self._padder = vtk.vtkImageConstantPad()
# initialise any mixins we might have
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkImageReslice' : self._reslicer})
module_utils.setup_vtk_object_progress(self, self._reslicer,
'Transforming image (Image Reslice)')
module_utils.setup_vtk_object_progress(self, self._probefilter,
'Performing remapping (Probe Filter)')
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# Rdisconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# don't forget to call the close() method of the vtkPipeline mixin
NoConfigModuleMixin.close(self)
# get rid of our reference
del self._reslicer
del self._probefilter
del self._padder
def get_input_descriptions(self):
return ('Source VTK Image Data', 'VTK Transform', 'Target VTK Image (supplies extent and spacing)')
def set_input(self, idx, inputStream):
if idx == 0:
self._imagedata = inputStream
self._reslicer.SetInput(self._imagedata)
elif idx == 1:
if inputStream == None:
# disconnect
self._transform = vtk.vtkMatrix4x4()
else:
# resliceTransform transforms the resampling grid, which
# is equivalent to transforming the volume with its inverse
self._transform = inputStream.GetMatrix()
self._transform.Invert() #This is required
else:
if inputStream != None:
self._outputVolumeExample = inputStream
else:
# define output extent same as input
self._outputVolumeExample = self._imagedata
def _convert_input(self):
self._reslicer.SetInput(self._imagedata)
self._reslicer.SetResliceAxes(self._transform)
self._reslicer.SetAutoCropOutput(1)
self._reslicer.SetInterpolationModeToCubic()
spacing_i = self._imagedata.GetSpacing()
isotropic_sp = min(min(spacing_i[0],spacing_i[1]),spacing_i[2])
self._reslicer.SetOutputSpacing(isotropic_sp, isotropic_sp, isotropic_sp)
self._reslicer.Update()
source = self._reslicer.GetOutput()
source_extent = source.GetExtent()
output_extent = self._outputVolumeExample.GetExtent()
if (output_extent[0] < source_extent[0]) or (output_extent[2] < source_extent[2]) or (output_extent[4] < source_extent[4]):
raise Exception('Output extent starts at lower index than source extent. Assumed that both should be zero?')
elif (output_extent[1] > source_extent[1]) or (output_extent[3] > source_extent[3]) or (output_extent[5] > source_extent[5]):
extX = max(output_extent[1], source_extent[1])
extY = max(output_extent[3], source_extent[3])
extZ = max(output_extent[5], source_extent[5])
padX = extX - source_extent[1]
padY = extY - source_extent[3]
padZ = extZ - source_extent[5]
print 'Zero-padding source by (%d, %d, %d) voxels to force extent to match/exceed input''s extent. Lame, eh?' % (padX, padY, padZ)
self._padder.SetInput(source)
self._padder.SetConstant(0.0)
self._padder.SetOutputWholeExtent(source_extent[0],extX,source_extent[2],extY,source_extent[4],extZ)
self._padder.Update()
source = self._padder.GetOutput()
#dataType = self._outputVolumeExample.GetScalarType()
#if dataType == 2 | dataType == 4:
output = vtk.vtkImageData()
output.DeepCopy(self._outputVolumeExample)
self._probefilter.SetInput(output)
self._probefilter.SetSource(source)
self._probefilter.Update()
self._output = self._probefilter.GetOutput()
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._output
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def execute_module(self):
self._convert_input() | Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class imageMedian3D(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._config.kernelSize = (3, 3, 3)
configList = [
('Kernel size:', 'kernelSize', 'tuple:int,3', 'text',
'Size of structuring element in pixels.')]
self._imageMedian3D = vtk.vtkImageMedian3D()
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageMedian3D' : self._imageMedian3D})
module_utils.setup_vtk_object_progress(self, self._imageMedian3D,
'Filtering with median')
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
# get rid of our reference
del self._imageMedian3D
def execute_module(self):
self._imageMedian3D.Update()
def streaming_execute_module(self):
self._imageMedian3D.Update()
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageMedian3D.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageMedian3D.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._imageMedian3D.GetOutput()
def logic_to_config(self):
self._config.kernelSize = self._imageMedian3D.GetKernelSize()
def config_to_logic(self):
ks = self._config.kernelSize
self._imageMedian3D.SetKernelSize(ks[0], ks[1], ks[2])
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class imageFillHoles(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageBorderMask = vtkdevide.vtkImageBorderMask()
# input image value for border
self._imageBorderMask.SetBorderMode(1)
# maximum of output for interior
self._imageBorderMask.SetInteriorMode(3)
self._imageGreyReconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D()
# we're going to use the dual, instead of inverting mask and image,
# performing greyscale reconstruction, and then inverting the result
# again. (we should compare results though)
self._imageGreyReconstruct.SetDual(1)
# marker J is second input
self._imageGreyReconstruct.SetInput(
1, self._imageBorderMask.GetOutput())
module_utils.setup_vtk_object_progress(self, self._imageBorderMask,
'Creating image mask.')
module_utils.setup_vtk_object_progress(self, self._imageGreyReconstruct,
'Performing reconstruction.')
self._config.holesTouchEdges = (0,0,0,0,0,0)
configList = [
('Allow holes to touch edges:', 'holesTouchEdges',
'tuple:int,6', 'text',
'Indicate which edges (minX, maxX, minY, maxY, minZ, maxZ) may\n'
'be touched by holes. In other words, a hole touching such an\n'
'edge will not be considered background and will be filled.')
]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageBorderMask' : self._imageBorderMask,
'vtkImageGreyReconstruct' : self._imageGreyReconstruct})
self.sync_module_logic_with_config()
def close(self):
# we play it safe... (the graph_editor/module_manager should have
# disconnected us by now)
for input_idx in range(len(self.get_input_descriptions())):
self.set_input(input_idx, None)
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._imageBorderMask
del self._imageGreyReconstruct
def get_input_descriptions(self):
return ('VTK Image Data to be filled',)
def set_input(self, idx, inputStream):
self._imageBorderMask.SetInput(inputStream)
# first input of the reconstruction is the image
self._imageGreyReconstruct.SetInput(0, inputStream)
def get_output_descriptions(self):
return ('Filled VTK Image Data', 'Marker')
def get_output(self, idx):
if idx == 0:
return self._imageGreyReconstruct.GetOutput()
else:
return self._imageBorderMask.GetOutput()
def logic_to_config(self):
borders = self._imageBorderMask.GetBorders()
# if there is a border, a hole touching that edge is no hole
self._config.holesTouchEdges = [int(not i) for i in borders]
def config_to_logic(self):
borders = [int(not i) for i in self._config.holesTouchEdges]
self._imageBorderMask.SetBorders(borders)
def execute_module(self):
self._imageGreyReconstruct.Update()
| Python |
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
import vtkdevide
import wx
class histogramSegment(IntrospectModuleMixin, ModuleBase):
"""Mooooo! I'm a cow.
$Revision: 1.9 $
"""
_gridCols = [('Type', 0), ('Number of Handles',0)]
_gridTypeCol = 0
_gridNOHCol = 1
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._createViewFrame()
self._grid = self._viewFrame.selectorGrid
self._buildPipeline()
self._selectors = []
self._config.selectorList = []
self._initialiseGrid()
self._bindEvents()
# display the window
self._viewFrame.Show(True)
def close(self):
# disconnect our inputs
for i in range(len(self.get_input_descriptions())):
self.set_input(i, None)
self._renderer.RemoveAllViewProps()
self._viewFrame.rwi.GetRenderWindow().Finalize()
self._viewFrame.rwi.SetRenderWindow(None)
del self._viewFrame.rwi
self._viewFrame.Destroy()
# call close method of base class
ModuleBase.close(self)
def get_config(self):
return self._config
def set_config(self, config):
pass
def set_configPostConnect(self, config):
# first nuke all current selectors (but prevent updates to config
# and the stencil)
indices = range(len(self._selectors))
self._removeSelector(indices, preventSync=True)
for d in config.selectorList:
self._addSelector(d['type'], len(d['handlePositions']))
for hidx in range(len(d['handlePositions'])):
self._selectors[-1]['widget'].SetHandlePosition(
hidx, d['handlePositions'][hidx])
# we've now added all selectors, sync up everything!
self._postSelectorChange()
def get_input_descriptions(self):
return ('Image Data 1', 'Imaga Data 2')
def set_input(self, idx, inputStream):
def checkTypeAndReturnInput(inputStream):
"""Check type of input. None gets returned. The input is
returned if it has a valid type. An exception is thrown if
the input is invalid.
"""
if inputStream == None:
# disconnect
return None
else:
# first check the type
validType = False
try:
if inputStream.IsA('vtkImageData'):
validType = True
except AttributeError:
# validType is already False
pass
if not validType:
raise TypeError, 'Input has to be of type vtkImageData.'
else:
return inputStream
if idx == 0:
input0 = checkTypeAndReturnInput(inputStream)
if input0 == None:
# we HAVE to destroy the overlayipw first (the stencil
# logic is NOT well-behaved)
self._deactivateOverlayIPW()
self._histogram.SetInput1(input0)
self._lookupAppend.SetInput(0, input0)
elif idx == 1:
input1 = checkTypeAndReturnInput(inputStream)
if input1 == None:
# we HAVE to destroy the overlayipw first (the stencil
# logic is NOT well-behaved)
self._deactivateOverlayIPW()
self._histogram.SetInput2(input1)
if self._lookupAppend.GetNumberOfInputPorts() < 2:
self._lookupAppend.AddInput(input1)
else:
self._lookupAppend.SetInput(1, input1)
if self._histogram.GetInput(0) and self._histogram.GetInput(1):
if self._ipw == None:
self._createIPW()
self._activateOverlayIPW()
else:
# this means at least one input is not valid - so we can disable
# the primary IPW. The overlay is dead by this time.
if self._ipw != None:
self._ipw.Off()
self._ipw.SetInteractor(None)
self._ipw.SetInput(None)
self._ipw = None
self._renderer.RemoveActor(self._axes)
self._axes = None
if 0:
# also disable scalarBarWidget
self._scalarBarWidget.Off()
self._scalarBarWidget.SetInteractor(None)
self._scalarBarWidget.GetScalarBarActor().SetLookupTable(
None)
self._scalarBarWidget = None
def get_output_descriptions(self):
return ('Segmented vtkImageData', 'Histogram Stencil')
def get_output(self, idx):
if idx == 0:
return self._lookup.GetOutput()
else:
return self._stencil.GetOutput()
def execute_module(self):
pass
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def view(self):
self._viewFrame.Show(True)
self._viewFrame.Raise()
# -------------------------------------------------------
# END OF API METHODS
# -------------------------------------------------------
def _activateOverlayIPW(self):
if self._overlayipw == None and \
self._ipw and \
self._histogram.GetInput(0) and \
self._histogram.GetInput(1) and \
len(self._selectors) > 0:
# we only do this if absolutely necessary
# connect these two up ONLY if we have valid selectors
self._stencil.SetStencil(self._pdToImageStencil.GetOutput())
self._overlayipw = vtk.vtkImagePlaneWidget()
self._overlayipw.SetInput(self._stencil.GetOutput())
self._stencil.GetOutput().Update()
self._overlayipw.SetInput(self._stencil.GetOutput())
self._overlayipw.SetInteractor(self._viewFrame.rwi)
self._overlayipw.SetPlaneOrientation(2)
self._overlayipw.SetSliceIndex(0)
# build the lut
lut = vtk.vtkLookupTable()
lut.SetTableRange(0, 1)
lut.SetHueRange(0.0, 0.0)
lut.SetSaturationRange(1.0, 1.0)
lut.SetValueRange(1.0, 1.0)
lut.SetAlphaRange(0.0, 0.3)
lut.Build()
self._overlayipw.SetUserControlledLookupTable(1)
self._overlayipw.SetLookupTable(lut)
self._overlayipw.On()
self._overlayipw.InteractionOff()
self._render()
def _deactivateOverlayIPW(self):
if self._overlayipw:
print "switching off overlayipw"
self._overlayipw.Off()
self._overlayipw.SetInteractor(None)
self._overlayipw.SetInput(None)
self._overlayipw = None
print "disconnecting stencil"
# also disconnect this guy, or we crash!
self._stencil.SetStencil(None)
def _addSelector(self, selectorType, numPoints):
if selectorType == 'Spline':
sw = vtk.vtkSplineWidget()
else:
sw = vtkdevide.vtkPolyLineWidget()
sw.SetCurrentRenderer(self._renderer)
sw.SetDefaultRenderer(self._renderer)
sw.SetInput(self._histogram.GetOutput())
sw.SetInteractor(self._viewFrame.rwi)
sw.PlaceWidget()
sw.ProjectToPlaneOn()
sw.SetProjectionNormalToZAxes()
sw.SetProjectionPosition(0.00)
sw.SetPriority(0.6)
sw.SetNumberOfHandles(numPoints)
sw.SetClosed(1)
sw.On()
swPolyData = vtk.vtkPolyData()
self._selectors.append({'type' : selectorType,
'widget' : sw,
'polyData' : swPolyData})
# add it to the appendPd
self._appendPD.AddInput(swPolyData)
nrGridRows = self._grid.GetNumberRows()
self._grid.AppendRows()
self._grid.SetCellValue(nrGridRows, self._gridTypeCol, selectorType)
self._grid.SetCellValue(nrGridRows, self._gridNOHCol,
str(sw.GetNumberOfHandles()))
self._postSelectorChange()
sw.AddObserver('EndInteractionEvent',
self._observerSelectorEndInteraction)
# make sure this is on
self._activateOverlayIPW()
def _bindEvents(self):
# fix the broken grid
wx.grid.EVT_GRID_RANGE_SELECT(
self._grid, self._handlerGridRangeSelect)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.addButton.GetId(),
self._handlerAddSelector)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.removeButton.GetId(),
self._handlerRemoveSelector)
wx.EVT_BUTTON(self._viewFrame,
self._viewFrame.changeHandlesButton.GetId(),
self._handlerChangeNumberOfHandles)
def _buildPipeline(self):
"""Build underlying pipeline and configure rest of pipeline-dependent
UI.
"""
# add the renderer
self._renderer = vtk.vtkRenderer()
self._renderer.SetBackground(0.5, 0.5, 0.5)
self._viewFrame.rwi.GetRenderWindow().AddRenderer(
self._renderer)
self._histogram = vtkdevide.vtkImageHistogram2D()
# make sure the user can't do anything entirely stupid
istyle = vtk.vtkInteractorStyleImage()
self._viewFrame.rwi.SetInteractorStyle(istyle)
# we'll use this to keep track of our ImagePlaneWidget
self._ipw = None
self._overlayipw = None
self._scalarBarWidget = None
#
self._appendPD = vtk.vtkAppendPolyData()
self._extrude = vtk.vtkLinearExtrusionFilter()
self._extrude.SetInput(self._appendPD.GetOutput())
self._extrude.SetScaleFactor(1)
self._extrude.SetExtrusionTypeToNormalExtrusion()
self._extrude.SetVector(0,0,1)
self._pdToImageStencil = vtk.vtkPolyDataToImageStencil()
self._pdToImageStencil.SetInput(self._extrude.GetOutput())
# stupid trick to make image with all ones, but as large as its
# input
self._allOnes = vtk.vtkImageThreshold()
self._allOnes.ThresholdByLower(0.0)
self._allOnes.ThresholdByUpper(0.0)
self._allOnes.SetInValue(1.0)
self._allOnes.SetOutValue(1.0)
self._allOnes.SetInput(self._histogram.GetOutput())
self._stencil = vtk.vtkImageStencil()
self._stencil.SetInput(self._allOnes.GetOutput())
#self._stencil.SetStencil(self._pdToImageStencil.GetOutput())
self._stencil.ReverseStencilOff()
self._stencil.SetBackgroundValue(0)
self._lookupAppend = vtk.vtkImageAppendComponents()
self._lookup = vtkdevide.vtkHistogramLookupTable()
self._lookup.SetInput1(self._lookupAppend.GetOutput())
self._lookup.SetInput2(self._stencil.GetOutput())
module_utils.create_standard_object_introspection(
self, self._viewFrame, self._viewFrame.viewFramePanel,
{'Module (self)' : self,
'vtkHistogram2D' : self._histogram,
'vtkRenderer' : self._renderer},
self._renderer.GetRenderWindow())
# add the ECASH buttons
module_utils.create_eoca_buttons(self, self._viewFrame,
self._viewFrame.viewFramePanel)
def _createIPW(self):
# we have to do this to get the correct log range
self._histogram.GetOutput().Update()
# this means we have newly valid input and should setup an ipw
self._ipw = vtk.vtkImagePlaneWidget()
self._histogram.GetOutput().Update()
self._ipw.SetInput(self._histogram.GetOutput())
self._ipw.SetInteractor(self._viewFrame.rwi)
# normal to the Z-axis
self._ipw.SetPlaneOrientation(2)
self._ipw.SetSliceIndex(0)
# setup specific lut
srange = self._histogram.GetOutput().GetScalarRange()
lut = vtk.vtkLookupTable()
lut.SetScaleToLog10()
lut.SetTableRange(srange)
lut.SetSaturationRange(1.0,1.0)
lut.SetValueRange(1.0, 1.0)
lut.SetHueRange(0.1, 1.0)
lut.Build()
self._ipw.SetUserControlledLookupTable(1)
self._ipw.SetLookupTable(lut)
self._ipw.SetDisplayText(1)
# if we use ContinousCursor, we get OffImage when zoomed
# on Linux (really irritating) but not on Windows. A VTK
# recompile might help, we'll see.
self._ipw.SetUseContinuousCursor(1)
# make sure the user can't twist the plane out of sight
self._ipw.SetMiddleButtonAction(0)
self._ipw.SetRightButtonAction(0)
# add an observer
self._ipw.AddObserver('StartInteractionEvent',
self._observerIPWInteraction)
self._ipw.AddObserver('InteractionEvent',
self._observerIPWInteraction)
self._ipw.AddObserver('EndInteractionEvent',
self._observerIPWInteraction)
self._ipw.On()
self._axes = vtk.vtkCubeAxesActor2D()
self._axes.SetFlyModeToOuterEdges()
# NOBODY will ever know why we have to switch off the Y axis when
# we actually want the Z-axis to go away.
self._axes.YAxisVisibilityOff()
self._axes.SetBounds(self._ipw.GetResliceOutput().GetBounds())
self._renderer.AddActor(self._axes)
self._axes.SetCamera(self._renderer.GetActiveCamera())
self._axes.PickableOff()
if 0:
# now add a scalarbar
self._scalarBarWidget = vtk.vtkScalarBarWidget()
self._scalarBarWidget.SetInteractor(self._viewFrame.rwi)
self._scalarBarWidget.GetScalarBarActor().SetTitle('Frequency')
self._scalarBarWidget.GetScalarBarActor().SetLookupTable(
lut)
# and activate
self._scalarBarWidget.On()
self._resetCamera()
self._render()
def _createViewFrame(self):
# create the viewerFrame
import modules.viewers.resources.python.histogramSegmentFrames
# this reload is temporary during development
reload(modules.viewers.resources.python.histogramSegmentFrames)
viewFrame = modules.viewers.resources.python.histogramSegmentFrames.\
viewFrame
# DeVIDE takes care of the icon and the window close handlers
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, viewFrame)
def _handlerAddSelector(self, event):
typeString = self._viewFrame.selectorTypeChoice.GetStringSelection()
self._addSelector(typeString, 5)
def _handlerChangeNumberOfHandles(self, event):
# first check that the user has actually selected something we
# can work with...
selectedRows = self._grid.GetSelectedRows()
if len(selectedRows) == 0:
return
nohText = wx.GetTextFromUser(
'Enter a new number of handles > 2 for all selected selectors.')
if nohText:
try:
nohInt = int(nohText)
except ValueError:
pass
else:
if nohInt < 2:
nohInt = 2
for row in selectedRows:
self._selectors[row]['widget'].SetNumberOfHandles(nohInt)
self._grid.SetCellValue(row, self._gridNOHCol,
str(nohInt))
# we've made changes to the selectors, so we have to
# notify the stencil.... (and other stuff)
self._postSelectorChange()
def _observerIPWInteraction(self, e, o):
if not self._ipw:
return
cd = 4 * [0.0]
if self._ipw.GetCursorData(cd):
if 0:
# get world position (at least for first two coords)
inp = self._ipw.GetInput()
spacing = inp.GetSpacing()
origin = inp.GetOrigin()
# calculate origin + spacing * discrete (only if we're getting
# discrete values from the IPW, which we aren't)
temp = [s * d for s,d in zip(spacing, cd[0:3])]
w = [o + t for o,t in zip(origin,temp)]
#
self._viewFrame.cursorValuesText.SetValue(
'%.2f, %.2f == %d' % (cd[0], cd[1], int(cd[3])))
def _handlerRemoveSelector(self, event):
selectedRows = self._grid.GetSelectedRows()
if len(selectedRows) > 0:
self._removeSelector(selectedRows)
# after that, we have to sync
self._postSelectorChange()
self._render()
def _handlerGridRangeSelect(self, event):
"""This event handler is a fix for the fact that the row
selection in the wxGrid is deliberately broken. It's also
used to activate and deactivate relevant menubar items.
Whenever a user clicks on a cell, the grid SHOWS its row
to be selected, but GetSelectedRows() doesn't think so.
This event handler will travel through the Selected Blocks
and make sure the correct rows are actually selected.
Strangely enough, this event always gets called, but the
selection is empty when the user has EXPLICITLY selected
rows. This is not a problem, as then the GetSelectedRows()
does return the correct information.
"""
# both of these are lists of (row, column) tuples
tl = self._grid.GetSelectionBlockTopLeft()
br = self._grid.GetSelectionBlockBottomRight()
# this means that the user has most probably clicked on the little
# block at the top-left corner of the grid... in this case,
# SelectRow has no frikking effect (up to wxPython 2.4.2.4) so we
# detect this situation and clear the selection (we're going to be
# selecting the whole grid in anycase.
if tl == [(0,0)] and br == [(self._grid.GetNumberRows() - 1,
self._grid.GetNumberCols() - 1)]:
self._grid.ClearSelection()
for (tlrow, tlcolumn), (brrow, brcolumn) in zip(tl, br):
for row in range(tlrow,brrow + 1):
self._grid.SelectRow(row, True)
def _initialiseGrid(self):
# delete all existing columns
self._grid.DeleteCols(0, self._grid.GetNumberCols())
# we need at least one row, else adding columns doesn't work (doh)
self._grid.AppendRows()
# setup columns
self._grid.AppendCols(len(self._gridCols))
for colIdx in range(len(self._gridCols)):
# add labels
self._grid.SetColLabelValue(colIdx, self._gridCols[colIdx][0])
# set size according to labels
self._grid.AutoSizeColumns()
for colIdx in range(len(self._gridCols)):
# now set size overrides
size = self._gridCols[colIdx][1]
if size > 0:
self._grid.SetColSize(colIdx, size)
# make sure we have no rows again...
self._grid.DeleteRows(0, self._grid.GetNumberRows())
def _observerSelectorEndInteraction(self, obj, evt):
# we don't HAVE to do this immediately, but it's fun
self._postSelectorChange()
def _postSelectorChange(self):
self._syncStencilMask()
self._syncConfigWithSelectors()
def _removeSelector(self, indices, preventSync=False):
if indices:
# we have to delete these things from behind (he he he)
indices.sort()
indices.reverse()
for idx in indices:
# take care of the selector
w = self._selectors[idx]['widget']
wpd = self._selectors[idx]['polyData']
w.Off()
w.SetInteractor(None)
w.SetInput(None)
self._appendPD.RemoveInput(wpd)
del(self._selectors[idx])
# reflect the removal in the grid
self._grid.DeleteRows(idx, 1)
if len(self._selectors) == 0:
self._deactivateOverlayIPW()
if not preventSync:
# sometimes, we don't want this to be called, as it will cause
# unnecessary updates, for example when we nuke ALL selectors
# during a set_config
self._postSelectorChange()
def _render(self):
self._renderer.GetRenderWindow().Render()
def _resetCamera(self):
# make sure camera is cool
cam = self._renderer.GetActiveCamera()
cam.ParallelProjectionOn()
self._renderer.ResetCamera()
ps = cam.GetParallelScale()
# get the camera a tad closer than VTK default
cam.SetParallelScale(ps / 2.9)
def _syncStencilMask(self):
for d in self._selectors:
sw = d['widget']
spd = d['polyData']
# transfer polydata
sw.GetPolyData(spd)
if self._overlayipw:
# the stencil is a bitch - we have to be very careful about when
# we talk to it...
self._stencil.Update()
def _syncConfigWithSelectors(self):
# we could get the data from the selector polydata, but we'll rather
# get it from the handles, because that's ultimately how we'll
# restore it again
del self._config.selectorList[:]
for d in self._selectors:
handlePositions = []
widget = d['widget']
for hidx in range(widget.GetNumberOfHandles()):
# it's important that we create a new var everytime
thp = [0.0, 0.0, 0.0]
widget.GetHandlePosition(hidx, thp)
handlePositions.append(thp)
self._config.selectorList.append(
{'type' : d['type'],
'handlePositions' : handlePositions})
| Python |
from module_kits.misc_kit.mixins import SubjectMixin
import geometry
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import Measure2DFrame
reload(Measure2DFrame)
import vtk
import vtktudoss
import wx
class M2DMeasurementInfo:
pass
class M2DWidget:
"""Class for encapsulating widget binding and all its metadata.
"""
def __init__(self, widget, name, type_string):
"""
@param type_string: ellipse
"""
self.widget = widget
self.name = name
self.type_string = type_string
self.measurement_string = ""
# we'll use this to pack all widget-specific measurement
# information
self.measurement_info = M2DMeasurementInfo()
class M2DWidgetList:
"""List of M2DWidgets that can be queried by name or type.
"""
def __init__(self):
self._wdict = {}
def close(self):
pass
def add(self, widget):
"""widget is an instance of M2DWidget.
"""
if not widget.name:
raise KeyError("Widget has to have a name.")
if widget.name in self._wdict:
raise KeyError("Widget with that name already in list.")
self._wdict[widget.name] = widget
def get_names(self):
return self._wdict.keys()
def get_widget(self, name):
return self._wdict[name]
def get_widgets_of_type(self, type_string):
"""Return a list of all widgets of type type_string.
"""
wlist = []
for wname, w in self._wdict.items():
if w.type_string == type_string:
wlist.append(w)
return wlist
def remove(self, name):
"""Remove widget with name from internal dict.
Return binding to widget that was just removed (so that client
can do widget specific finalisation.
"""
w = self._wdict[name]
del(self._wdict[name])
return w
def rename_widget(self, old_name, new_name):
"""After profuse error-checking, rename widget with old_name
to new_name.
"""
if not new_name:
raise KeyError('Widget cannot have empty name.')
if old_name not in self._wdict:
raise KeyError('widget %s not in list.' % (old_name,))
if new_name in self._wdict:
raise KeyError('widget with name %s alread exists.' %
(new_name,))
w = self.get_widget(old_name)
self.remove(old_name)
w.name = new_name
self.add(w)
def __contains__(self, name):
"""Returns true if there's a widget with that name already in
the list.
"""
return name in self._wdict
class Measure2D(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._view_frame = None
self._viewer = None
self._input_image = None
self._dummy_image_source = vtk.vtkImageMandelbrotSource()
self._widgets = M2DWidgetList()
# build frame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager, Measure2DFrame.Measure2DFrame)
# now link up all event handlers
self._bind_events()
# then build VTK pipeline
self._create_vtk_pipeline()
# set us up with dummy input
self._setup_new_image()
# show everything
self.view()
def close(self):
if self._view_frame is not None:
# with this complicated de-init, we make sure that VTK is
# properly taken care of
self._viewer.GetRenderer().RemoveAllViewProps()
self._viewer.SetupInteractor(None)
self._viewer.SetRenderer(None)
# this finalize makes sure we don't get any strange X
# errors when we kill the module.
self._viewer.GetRenderWindow().Finalize()
self._viewer.SetRenderWindow(None)
self._viewer.DebugOn()
del self._viewer
# done with VTK de-init
self._view_frame.close()
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# GOTCHA!! (finally)
# we need to do this to make sure that the Show() and Raise() above
# are actually performed. Not doing this is what resulted in the
# "empty renderwindow" bug after module reloading, and also in the
# fact that shortly after module creation dummy data rendered outside
# the module frame.
# YEAH.
wx.SafeYield()
self.render()
# so if we bring up the view after having executed the network once,
# re-executing will not do a set_input()! (the scheduler doesn't
# know that the module is now dirty) Two solutions:
# * make module dirty when view is activated
# * activate view at instantiation. <--- we're doing this now.
def get_input_descriptions(self):
return ('Image data',)
def get_output_descriptions(self):
return ('self', 'widget_list')
def get_output(self, idx):
if idx == 0:
return self
else:
return self._widgets
def execute_module(self):
self.render()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def set_input(self, idx, input_stream):
if self._input_image != input_stream:
self._input_image = input_stream
self._setup_new_image()
def _bind_events(self):
"""Setup all event handling based on the view frame.
"""
slice_slider = self._view_frame._image_control_panel.slider
slice_slider.Bind(wx.EVT_SLIDER, self._handler_slice_slider)
new_measurement_button = \
self._view_frame._measurement_panel.create_button
new_measurement_button.Bind(wx.EVT_BUTTON, self._handler_new_measurement_button)
rb = self._view_frame._measurement_panel.rename_button
rb.Bind(wx.EVT_BUTTON,
self._handler_rename_measurement_button)
db = self._view_frame._measurement_panel.delete_button
db.Bind(wx.EVT_BUTTON,
self._handler_delete_measurement_button)
eb = self._view_frame._measurement_panel.enable_button
eb.Bind(wx.EVT_BUTTON,
self._handler_enable_measurement_button)
db = self._view_frame._measurement_panel.disable_button
db.Bind(wx.EVT_BUTTON,
self._handler_disable_measurement_button)
def _create_vtk_pipeline(self):
"""Create pipeline for viewing 2D image data.
"""
if self._viewer is None and not self._view_frame is None:
if True:
self._viewer = vtk.vtkImageViewer2()
self._viewer.SetupInteractor(self._view_frame._rwi)
self._viewer.GetRenderer().SetBackground(0.3,0.3,0.3)
else:
ren = vtk.vtkRenderer()
self._view_frame._rwi.GetRenderWindow().AddRenderer(ren)
def _get_selected_measurement_names(self):
"""Return list of names of selected measurement widgets.
"""
grid = self._view_frame._measurement_panel.measurement_grid
sr = grid.GetSelectedRows()
return [grid.GetCellValue(idx,0) for idx in sr]
def _handler_enable_measurement_button(self, event):
snames = self._get_selected_measurement_names()
for sname in snames:
w = self._widgets.get_widget(sname)
print "about to enable ", w.name
w.widget.SetEnabled(1)
self.render()
def _handler_disable_measurement_button(self, event):
snames = self._get_selected_measurement_names()
for sname in snames:
w = self._widgets.get_widget(sname)
print "about to disable ", w.name
w.widget.SetEnabled(0)
self.render()
def _handler_rename_measurement_button(self, event):
# FIXME: abstract method that returns list of names of
# selected measurement widgets
grid = self._view_frame._measurement_panel.measurement_grid
# returns list of selected row indices, we're only going to
# rename the first one
sr = grid.GetSelectedRows()
if not sr:
return
idx = sr[0]
name = grid.GetCellValue(idx, 0)
new_name = wx.GetTextFromUser(
'Enter a new name for this measurement.',
'Rename Module',
name)
if new_name:
w = self._widgets.get_widget(name)
self._widgets.rename_widget(name, new_name)
self._sync_measurement_grid()
def _handler_delete_measurement_button(self, event):
grid = self._view_frame._measurement_panel.measurement_grid
sr = grid.GetSelectedRows()
if not sr:
return
for idx in sr:
name = grid.GetCellValue(idx, 0)
w = self._widgets.get_widget(name)
w.widget.SetEnabled(0)
w.widget.SetInteractor(None)
self._widgets.remove(name)
self._sync_measurement_grid()
def _handler_new_measurement_button(self, event):
widget_type = 0
if widget_type == 0:
# instantiate widget with correct init vars
name = self._view_frame._measurement_panel.name_cb.GetValue()
if not name or name in self._widgets:
# FIXME: add error message here
pass
else:
w = vtktudoss.vtkEllipseWidget()
w.SetInteractor(self._view_frame._rwi)
w.SetEnabled(1)
widget = M2DWidget(w, name, 'ellipse')
# add it to the internal list
self._widgets.add(widget)
def observer_interaction(o, e):
r = o.GetRepresentation()
s = r.GetLabelText()
widget.measurement_string = s
# c, axis_lengths, radius_vectors
mi = widget.measurement_info
mi.c = [0.0,0.0,0.0]
r.GetCenterWorldPosition(mi.c)
mi.c[2] = 0.0
mi.axis_lengths = (
r.GetSemiMajorAxisLength() * 2.0,
r.GetSemiMinorAxisLength() * 2.0,
0.0)
mi.radius_vectors = (
[0.0,0.0,0.0],
[0.0,0.0,0.0],
[0.0,0.0,0.0])
# these vectors describe the principal HALF-axes
# of the ellipse, starting out from the centre
# (mi.c)
r.GetSemiMajorAxisVector(mi.radius_vectors[0])
r.GetSemiMinorAxisVector(mi.radius_vectors[1])
self._sync_measurement_grid()
# make sure state is initialised (if one just places
# the widget without interacting, the observer won't
# be invoked and measurement_info won't have the
# necessary attributes; if the network then executes,
# there will be errors)
widget.measurement_string = ''
mi = widget.measurement_info
mi.c = [0.0,0.0,0.0]
mi.axis_lengths = (0.0, 0.0, 0.0)
mi.radius_vectors = (
[0.0,0.0,0.0],
[0.0,0.0,0.0],
[0.0,0.0,0.0])
w.AddObserver('EndInteractionEvent',
observer_interaction)
# and then make the display thing sync up
self._sync_measurement_grid()
else:
handle = vtk.vtkPointHandleRepresentation2D()
handle.GetProperty().SetColor(1,0,0)
rep = vtk.vtkDistanceRepresentation2D()
rep.SetHandleRepresentation(handle)
rep.GetAxis().SetNumberOfMinorTicks(4)
rep.GetAxis().SetTickLength(9)
rep.GetAxis().SetTitlePosition(0.2)
w = vtk.vtkDistanceWidget()
w.SetInteractor(self._view_frame._rwi)
#w.CreateDefaultRepresentation()
w.SetRepresentation(rep)
w.SetEnabled(1)
# instantiate widget with correct init vars
widget = M2DWidget(w, 'name', 'ellipse')
# add it to the internal list
self._widgets.add(w)
self.render()
def _handler_slice_slider(self, event):
if not self._input_image is None:
val = self._view_frame._image_control_panel.slider.GetValue()
self._viewer.SetSlice(val)
def render(self):
self._view_frame._rwi.Render()
def _setup_new_image(self):
"""Based on the current self._input_image and the viewer, this thing
will make sure that we reset to some usable default.
"""
if not self._viewer is None:
if not self._input_image is None:
self._viewer.SetInput(self._input_image)
else:
self._viewer.SetInput(self._dummy_image_source.GetOutput())
ii = self._viewer.GetInput()
ii.UpdateInformation()
ii.Update()
range = ii.GetScalarRange()
self._viewer.SetColorWindow(range[1] - range[0])
self._viewer.SetColorLevel(0.5 * (range[1] + range[0]))
icp = self._view_frame._image_control_panel
icp.slider.SetRange(self._viewer.GetSliceMin(),
self._viewer.GetSliceMax())
icp.slider.SetValue(self._viewer.GetSliceMin())
#self._viewer.UpdateDisplayExtent()
self._viewer.GetRenderer().ResetCamera()
def _sync_measurement_grid(self):
"""Synchronise measurement grid with internal list of widgets.
"""
# for now we just nuke the whole thing and redo everything
grid = self._view_frame._measurement_panel.measurement_grid
if grid.GetNumberRows() > 0:
grid.DeleteRows(0, grid.GetNumberRows())
wname_list = self._widgets.get_names()
wname_list.sort()
for wname in wname_list:
w = self._widgets.get_widget(wname)
grid.AppendRows()
cur_row = grid.GetNumberRows() - 1
grid.SetCellValue(cur_row, 0, w.name)
grid.SetCellValue(cur_row, 1, w.type_string)
grid.SetCellValue(cur_row, 2, w.measurement_string)
# in general when we sync, the module is dirty, so we should
# flag this in the module manager. when the user sees this
# and schedules an execute, the scheduler will execute us and
# all parts of the network that are dependent on us.
self._module_manager.modify_module(self)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
from external.ObjectListView import ColumnDefn, EVT_CELL_EDIT_FINISHING
import itk
from module_kits import itk_kit
import module_utils
import vtk
import wx
###########################################################################
class MatchMode:
"""Plugin class that takes care of the Match Mode UI panel,
interaction for indicating matching structures, and the subsequent
registration.
"""
def __init__(self, comedi, config_dict):
raise NotImplementedError
def close(self):
"""De-init everything.
it's important that you de-init everything (including event
bindings) as close() is called many times during normal
application use. Each time the user changes the match mode
tab, the previous match mode is completely de-initialised.
"""
raise NotImplementedError
def get_output(self):
"""Return the transformed data2. Returns None if this is not
possible, due to the lack of input data for example. Call
after having called transform.
"""
raise NotImplementedError
def get_confidence(self):
"""Return confidence field, usually a form of distance field
to the matching structures.
"""
raise NotImplementedError
def transform(self):
"""After calling this method, the output will be available and
ready.
"""
raise NotImplementedError
###########################################################################
class Landmark:
def __init__(self, name, index_pos, world_pos, ren):
# we'll use this to create new actors.
self.ren = ren
self._create_actors()
self.set_name(name)
self.set_world_pos(world_pos)
self.set_index_pos(index_pos)
def close(self):
self.ren.RemoveViewProp(self.c3da)
self.ren.RemoveViewProp(self.ca)
def _create_actors(self):
# 1. create really small 3D cursor to place at relevant point
d = 2 # 2 mm dimension
cs = vtk.vtkCursor3D()
cs.AllOff()
cs.AxesOn()
cs.SetModelBounds(-d, +d, -d, +d, -d, +d)
cs.SetFocalPoint(0,0,0)
m = vtk.vtkPolyDataMapper()
m.SetInput(cs.GetOutput())
self.c3da = vtk.vtkActor()
self.c3da.SetPickable(0)
self.c3da.SetMapper(m)
self.ren.AddActor(self.c3da)
# 2. create caption actor with label
ca = vtk.vtkCaptionActor2D()
ca.GetProperty().SetColor(1,1,0)
tp = ca.GetCaptionTextProperty()
tp.SetColor(1,1,0)
tp.ShadowOff()
ca.SetPickable(0)
ca.SetAttachmentPoint(0,0,0) # we'll move this later
ca.SetPosition(25,10)
ca.BorderOff()
ca.SetWidth(0.3)
ca.SetHeight(0.04)
# this will be changed at the first property set
ca.SetCaption('.')
self.ca = ca
self.ren.AddActor(ca)
def get_world_pos_str(self):
return '%.2f, %.2f, %.2f' % tuple(self.world_pos)
def get_world_pos(self):
return self._world_pos
def set_world_pos(self, world_pos):
self.c3da.SetPosition(world_pos)
self.ca.SetAttachmentPoint(world_pos)
self._world_pos = world_pos
# why have I not been doing this forever?
# - because these properties get clobbered real easy. *sigh*
world_pos = property(get_world_pos, set_world_pos)
def get_name(self):
"""Test doc string!
"""
return self._name
def set_name(self, name):
self.ca.SetCaption(name)
self._name = name
name = property(get_name, set_name)
def get_index_pos(self):
return self._index_pos
def set_index_pos(self, index_pos):
self._index_pos = index_pos[0:3]
index_pos = property(get_index_pos, set_index_pos)
###########################################################################
class LandmarkList:
"""List of landmarks that also maintains a config dictionary.
"""
def __init__(self, config_dict, olv, ren):
"""
@param config_list: list that we will fill with (name,
world_pos) tuples.
@param olv: ObjectListView that will be configured to handle
the UI to the list.
"""
self._config_dict = config_dict
self.landmark_dict = {}
self._olv = olv
self._ren = ren
# there we go, sync internal state to passed config
for name,(index_pos, world_pos) in config_dict.items():
self.add_landmark(index_pos, world_pos, name)
olv.Bind(EVT_CELL_EDIT_FINISHING,
self._handler_olv_edit_finishing)
# if you don't set valueSetter, this thing overwrites my
# pretty property!!
olv.SetColumns([
ColumnDefn("Name", "left", 50, "name",
valueSetter=self.olv_setter),
ColumnDefn("Position", "left", 200, "get_world_pos_str",
isSpaceFilling=True, isEditable=False)])
olv.SetObjects(self.olv_landmark_list)
def add_landmark(self, index_pos, world_pos, name=None):
if name is None:
name = str(len(self.landmark_dict))
lm = Landmark(name, index_pos, world_pos, self._ren)
self.landmark_dict[lm.name] = lm
# set the config_dict. cheap operation, so we do the whole
# thing every time.
self.update_config_dict()
# then update the olv
self._olv.SetObjects(self.olv_landmark_list)
def close(self):
self._olv.Unbind(EVT_CELL_EDIT_FINISHING)
[lm.close() for lm in self.landmark_dict.values()]
def _get_olv_landmark_list(self):
"""Returns list of Landmark objects, sorted by name. This is
given to the ObjectListView.
"""
ld = self.landmark_dict
keys,values = ld.keys(),ld.values()
keys.sort()
return [ld[key] for key in keys]
olv_landmark_list = property(_get_olv_landmark_list)
def get_index_pos_list(self):
"""Retuns a list of 3-element discrete coordinates for the
current landmarks, sorted by name.
"""
ld = self.landmark_dict
keys = ld.keys()
keys.sort()
return [ld[key].index_pos for key in keys]
def _handler_olv_edit_finishing(self, evt):
"""This can get called only for "name" column edits, nothing
else.
"""
if evt.cellValue == evt.rowModel.name:
# we don't care, name stays the same
return
if len(evt.cellValue) > 0 and \
evt.cellValue not in self.landmark_dict:
# unique value, go ahead and change
# our olv_setter will be called at the right
# moment
return
# else we veto this change
# message box?!
evt.Veto()
def olv_setter(self, lm_object, new_name):
# delete the old binding from the dictionary
del self.landmark_dict[lm_object.name]
# change the name in the object
# ARGH! why does this setting clobber the property?!
#lm_object.name = new_name
lm_object.set_name(new_name)
# insert it at its correct spot
self.landmark_dict[new_name] = lm_object
# update the config dict
self.update_config_dict()
def remove_landmarks(self, names_list):
for name in names_list:
# get the landmark
lm = self.landmark_dict[name]
# de-init the landmark
lm.close()
# remove it from the dictionary
del self.landmark_dict[name]
# finally update the config dictionary
self.update_config_dict()
# then tell the olv about the changed situation
self._olv.SetObjects(self.olv_landmark_list)
def move_landmark(self, name, index_pos, world_pos):
lm = self.landmark_dict[name]
#lm.world_pos = world_pos
lm.set_index_pos(index_pos)
lm.set_world_pos(world_pos)
self.update_config_dict()
self._olv.SetObjects(self.olv_landmark_list)
def update_config_dict(self):
# re-init the whole thing; note that we don't re-assign, that
# would just bind to a new dictionary and not modify the
# passed one.
self._config_dict.clear()
for key,value in self.landmark_dict.items():
self._config_dict[key] = value.index_pos, value.world_pos
###########################################################################
KEY_DATA1_LANDMARKS = 'data1_landmarks'
KEY_DATA2_LANDMARKS = 'data2_landmarks'
KEY_MAX_DISTANCE = 'max_distance'
class SStructLandmarksMM(MatchMode):
"""Class representing simple landmark-transform between two sets
of points.
"""
# API methods #####
def __init__(self, comedi, config_dict):
"""
@param comedi: Instance of comedi that will be used to update
GUI and views.
@param config_dict: This dict, part of the main module config,
will be kept up to date throughout.
"""
self._comedi = comedi
self._cfg = config_dict
# if we get an empty config dict, configure!
if 'data1_landmarks' not in self._cfg:
self._cfg['data1_landmarks'] = {}
# do the list
cp = comedi._view_frame.pane_controls.window
r1 = comedi._data1_slice_viewer.renderer
self._data1_landmarks = \
LandmarkList(
self._cfg['data1_landmarks'],
cp.data1_landmarks_olv, r1)
if 'data2_landmarks' not in self._cfg:
self._cfg['data2_landmarks'] = {}
r2 = comedi._data2_slice_viewer.renderer
self._data2_landmarks = \
LandmarkList(
self._cfg['data2_landmarks'],
cp.data2_landmarks_olv, r2)
self._setup_ui()
self._bind_events()
# we'll use this to store a binding to the current output
self._output = None
# and this to store a binding to the current confidence
self._confidence = None
# remember, this turns out to be the transform itself
self._landmark = vtk.vtkLandmarkTransform()
# and this guy is going to do the work
self._trfm = vtk.vtkImageReslice()
self._trfm.SetInterpolationModeToLinear()
# setup a progress message:
module_utils.setup_vtk_object_progress(
self._comedi, self._trfm,
'Transforming Data 2')
# distance field will be calculated up to this distance,
# saving you time and money!
if KEY_MAX_DISTANCE not in self._cfg:
self._cfg[KEY_MAX_DISTANCE] = 43
md = self._cfg[KEY_MAX_DISTANCE]
print "sslm starting itk init"
# use itk fast marching to generate confidence field
self._fm = itk.FastMarchingImageFilter.IF3IF3.New()
self._fm.SetStoppingValue(md)
self._fm.SetSpeedConstant(1.0)
# setup a progress message
print "sslm fm progress start"
itk_kit.utils.setup_itk_object_progress(
self, self._fm, 'itkFastMarchingImageFilter',
'Propagating confidence front.', None,
comedi._module_manager)
print "sslm fm progress end"
# and a threshold to clip off the really high values that fast
# marching inserts after its max distance
self._thresh = t = itk.ThresholdImageFilter.IF3.New()
t.SetOutsideValue(md)
# values equal to or greater than this are set to outside value
t.ThresholdAbove(md)
itk_kit.utils.setup_itk_object_progress(
self, self._thresh, 'itkThresholdImageFilter',
'Clipping high values in confidence field.', None,
comedi._module_manager)
t.SetInput(self._fm.GetOutput())
# and a little something to convert it back to VTK world
self._itk2vtk = itk.ImageToVTKImageFilter.IF3.New()
self._itk2vtk.SetInput(t.GetOutput())
print "sslm mm init end"
def close(self):
self._data1_landmarks.close()
self._data2_landmarks.close()
self._unbind_events()
# get rid of the transform
self._trfm.SetInput(None)
del self._trfm
# nuke landmark
del self._landmark
# nuke fastmarching
del self._fm
del self._thresh
def get_confidence(self):
return self._confidence
def get_output(self):
return self._output
def transform(self):
"""If we have valid data and a valid set of matching
landmarks, transform data2.
Even if nothing has changed, this WILL perform the actual
transformation, so don't call this method unnecessarily.
"""
d1i = self._comedi._data1_slice_viewer.get_input()
d2i = self._comedi._data2_slice_viewer.get_input()
if d1i and d2i:
# we force the landmark to do its thing
try:
self._transfer_landmarks_to_vtk()
except RuntimeError, e:
# could not transfer points
self._output = None
# tell the user why
self._comedi._module_manager.log_error(
str(e))
else:
# points are set, update the transformation
self._landmark.Update()
# reslice transform transforms the sampling grid.
self._trfm.SetResliceTransform(self._landmark.GetInverse())
self._trfm.SetInput(d2i)
self._trfm.SetInformationInput(d1i)
self._trfm.Update()
self._output = self._trfm.GetOutput()
# then calculate distance field #####################
c2vc = itk_kit.utils.coordinates_to_vector_container
lm = self._data1_landmarks
seeds = c2vc(lm.get_index_pos_list(), 0)
self._fm.SetTrialPoints(seeds)
# now make sure the output has exactly the right
# dimensions and everyfink
o = d1i.GetOrigin()
s = d1i.GetSpacing()
d = d1i.GetDimensions()
we = d1i.GetWholeExtent()
fmo = itk.Point.D3()
for i,e in enumerate(o):
fmo.SetElement(i,e)
fms = itk.Vector.D3()
for i,e in enumerate(s):
fms.SetElement(i,e)
fmr = itk.ImageRegion._3()
fmsz = fmr.GetSize()
fmi = fmr.GetIndex()
for i,e in enumerate(d):
fmsz.SetElement(i,e)
# aaah! so that's what the index is for! :)
# some VTK volumes have a 0,0,0 origin, but their
# whole extent does not begin at 0,0,0. For
# example the output of a vtkExtractVOI does this.
fmi.SetElement(i, we[2*i])
self._fm.SetOutputOrigin(fmo)
self._fm.SetOutputSpacing(fms)
self._fm.SetOutputRegion(fmr)
# drag the whole thing through the vtk2itk converter
self._itk2vtk.Update()
self._confidence = self._itk2vtk.GetOutput()
else:
# not enough valid inputs, so no data.
self._output = None
# also disconnect the transform, so we don't keep data
# hanging around
self._trfm.SetInput(None)
#
self._confidence = None
# PRIVATE methods #####
def _add_data1_landmark(self, index_pos, world_pos, name=None):
self._data1_landmarks.add_landmark(index_pos, world_pos)
def _add_data2_landmark(self, index_pos, world_pos, name=None):
self._data2_landmarks.add_landmark(index_pos, world_pos)
def _bind_events(self):
# remember to UNBIND all of these in _unbind_events!
vf = self._comedi._view_frame
cp = vf.pane_controls.window
# bind to the add button
cp.lm_add_button.Bind(wx.EVT_BUTTON, self._handler_add_button)
cp.data1_landmarks_olv.Bind(
wx.EVT_LIST_ITEM_RIGHT_CLICK,
self._handler_solv_right_click)
cp.data2_landmarks_olv.Bind(
wx.EVT_LIST_ITEM_RIGHT_CLICK,
self._handler_tolv_right_click)
def _handler_add_button(self, e):
cp = self._comedi._view_frame.pane_controls.window
v = cp.cursor_text.GetValue()
if v.startswith('d1'):
ip = self._comedi._data1_slice_viewer.current_index_pos
wp = self._comedi._data1_slice_viewer.current_world_pos
self._add_data1_landmark(ip, wp)
elif v.startswith('d2'):
ip = self._comedi._data2_slice_viewer.current_index_pos
wp = self._comedi._data2_slice_viewer.current_world_pos
self._add_data2_landmark(ip, wp)
def _handler_delete_selected_lms(self, evt, i):
cp = self._comedi._view_frame.pane_controls.window
if i == 0:
olv = cp.data1_landmarks_olv
dobjs = olv.GetSelectedObjects()
self._data1_landmarks.remove_landmarks(
[o.name for o in dobjs])
else:
olv = cp.data2_landmarks_olv
dobjs = olv.GetSelectedObjects()
self._data2_landmarks.remove_landmarks(
[o.name for o in dobjs])
def _handler_move_selected_lm(self, evt, i):
cp = self._comedi._view_frame.pane_controls.window
v = cp.cursor_text.GetValue()
if v.startswith('d1') and i == 0:
# get the current world position
ip = self._comedi._data1_slice_viewer.current_index_pos
wp = self._comedi._data1_slice_viewer.current_world_pos
# get the currently selected object
olv = cp.data1_landmarks_olv
mobjs = olv.GetSelectedObjects()
if mobjs:
mobj = mobjs[0]
# now move...
self._data1_landmarks.move_landmark(mobj.name, ip, wp)
elif v.startswith('d2') and i == 1:
# get the current world position
ip = self._comedi._data2_slice_viewer.current_index_pos
wp = self._comedi._data2_slice_viewer.current_world_pos
# get the currently selected object
olv = cp.data2_landmarks_olv
mobjs = olv.GetSelectedObjects()
if mobjs:
mobj = mobjs[0]
# now move...
self._data2_landmarks.move_landmark(mobj.name, ip, wp)
def _handler_solv_right_click(self, evt):
olv = evt.GetEventObject()
# popup that menu
olv.PopupMenu(self._solv_menu, evt.GetPosition())
def _handler_tolv_right_click(self, evt):
olv = evt.GetEventObject()
# popup that menu
olv.PopupMenu(self._tolv_menu, evt.GetPosition())
def _setup_ui(self):
"""Do some UI-specific setup.
"""
vf = self._comedi._view_frame
self._solv_menu = wx.Menu('Landmarks context menu')
self._tolv_menu = wx.Menu('Landmarks context menu')
# i = [0,1] for data1 and data2 landmarks respectively
for i,m in enumerate([self._solv_menu, self._tolv_menu]):
# move landmarks
id_move_landmark = wx.NewId()
m.Append(id_move_landmark,
"Move first selected",
"Move first selected landmark to current cursor.")
vf.Bind(wx.EVT_MENU,
lambda e, i=i:
self._handler_move_selected_lm(e,i),
id = id_move_landmark)
# deletion of landmarks
id_delete_landmark = wx.NewId()
m.Append(id_delete_landmark,
"Delete selected",
"Delete all selected landmarks.")
vf.Bind(wx.EVT_MENU,
lambda e, i=i: self._handler_delete_selected_lms(e,i),
id = id_delete_landmark)
def _transfer_landmarks_to_vtk(self):
"""Copy landmarks from internal vars to sets of vtkPoints,
then set on our landmark transform filter.
"""
sld = self._data1_landmarks.landmark_dict
tld = self._data2_landmarks.landmark_dict
names = sld.keys()
sposs, tposs = [],[]
for name in names:
sposs.append(sld[name].world_pos)
try:
tposs.append(tld[name].world_pos)
except KeyError:
raise RuntimeError(
'Could not find data2 landmark with name %s.'
% (name,))
# now transfer the two lists to vtkPoint lists
# SOURCE:
data1_points = vtk.vtkPoints()
data1_points.SetNumberOfPoints(len(sposs))
for idx,pt in enumerate(sposs):
data1_points.SetPoint(idx, pt)
# TARGET:
data2_points = vtk.vtkPoints()
data2_points.SetNumberOfPoints(len(tposs))
for idx,pt in enumerate(tposs):
data2_points.SetPoint(idx, pt)
# we want to map data2 onto data1
self._landmark.SetSourceLandmarks(data2_points)
self._landmark.SetTargetLandmarks(data1_points)
def _unbind_events(self):
vf = self._comedi._view_frame
cp = vf.pane_controls.window
# bind to the add button
cp.lm_add_button.Unbind(wx.EVT_BUTTON)
cp.data1_landmarks_olv.Unbind(
wx.EVT_LIST_ITEM_RIGHT_CLICK)
cp.data2_landmarks_olv.Unbind(
wx.EVT_LIST_ITEM_RIGHT_CLICK)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
class CodeRunner:
kits = ['wx_kit', 'vtk_kit']
cats = ['Viewers']
help = \
"""CodeRunner facilitates the direct integration of Python code into a
DeVIDE network.
The top part contains three editor interfaces: scratch, setup and
execute. The first is for experimentation and does not take part in
network scheduling. The second, 'setup', will be executed once per
modification that you make, at network execution time. The third,
'execute', will be executed everytime the module is ran during network
execution. You have to apply changes before they will be integrated in
the network execution. If you seen an asterisk (*) on the editor tab, it
means your latest changes have not been applied.
You can execute any editor window during editing by hitting Ctrl-Enter.
This will execute the code currently visible, i.e. it doesn't have to be
applied yet. The three editor windows and the shell window below share
the same interpreter, i.e. things that you define in one window will be
available in all others.
Applied code will also be saved and loaded along with the rest of the
network. You can also save code from the currently selected editor window
to a separate .py file by selecting File|Save from the main menu.
VTK and matplotlib support are included.
To make a new matplotlib figure, do 'h1 = mpl_new_figure()'. To close it,
use 'mpl_close_figure(h1)'. A list of all figures is available in
obj.mpl_figure_handles.
You can retrieve the VTK renderer, render window and render window
interactor of any slice3dVWR by using vtk_get_render_info(name) where name
has been set by right-clicking on a module in the graph editor and
choosing 'Rename Module'.
"""
class CoMedI:
kits = ['vtk_kit', 'itk_kit', 'wx_kit']
cats = ['Viewers']
keywords = ['compare', 'comparative visualisation',
'comparative', 'comparative visualization']
help = \
"""CoMedI: Compare Medical Images
Viewer module for the comparison of arbitrary 2-D and 3-D
medical images.
"""
class DICOMBrowser:
kits = ['vtk_kit', 'gdcm_kit']
cats = ['Viewers', 'Readers', 'DICOM', 'Medical']
help = \
"""DICOMBrowser. Does for DICOM reading what slice3dVWR does for
3-D viewing.
See the main DeVIDE help file (Special Modules | DICOMBrowser) for
more information.
"""
class histogram1D:
kits = ['vtk_kit', 'numpy_kit']
cats = ['Viewers', 'Statistics']
class histogram2D:
kits = ['vtk_kit']
cats = ['Viewers']
class histogramSegment:
kits = ['wx_kit', 'vtk_kit']
cats = ['Viewers']
class LarynxMeasurement:
kits = ['wx_kit', 'vtk_kit', 'gdcm_kit', 'geometry_kit']
cats = ['Viewers']
help = """Module for performing 2D measurements on photos of the
larynx.
Click the 'start' button to select a JPEG image. On this image,
shift click to select the apex of the larynx, then shift click
again to select the bottom half-point. You can now shift-click to
select border points in a clock-wise fashion. The POGO distance
and area will be updated with the addition of each new point.
You can move all points after having placed them. Adjust the
brightness and contrast by dragging the left mouse button, zoom
by dragging the right button or using the mouse wheel, pan with
the middle mouse button.
When you click on the 'next' button, all information about the
current image will be saved and the next image in the directory
will be loaded. If the next image has already been measured by
you previously, the measurements will be loaded and shown. This
means that you can interrupt a measurement session at any time, as
long as you've pressed the 'next' button after the LAST image.
When you have measured all images (check the progress message
box), you can click on the 'Save CSV' button to write all
measurements to disk. You can also do this even if you haven't
done all measurements yet, as long as you have measured a multiple
of three images. The measurements will be written to disk in the
same directory as the measured images and will be called
'measurements.csv'.
"""
class MaskComBinar:
kits = ['vtk_kit', 'wx_kit']
cats = ['Viewers','Readers','Writers','Combine']
help = """An interactive tool for viewing and perfoming operations on binary masks.
Masks are loaded as VTK Imagedata (.vti) files from disk.
File opening commands can be found in the menu bar under "File".
The user has several options:
Load a single binary mask (Ctrl-O)
Load a single (integer) multi-label mask file as a set of binary masks(Ctrl-Alt-O)
Load all .vti files in a given directory (Ctrl-Shift-O)
Once loaded, masks can be selected in either of the two list boxes A and B.
Masks selected in A are shown in blue, while masks selected in B are shown in red.
Overlapping regions are shown in yellow.
The GUI provides several unary, binary or set operations. New output can be stored as a new mask.
Masks may be deleted (pressind "Del" once they are selected).
Any mask shown in the listboxes may be saved to file (Ctrl-S).
The Hausdorff distance can only be calculated if the Metro tool has been installed so that it is available in the
command prompt. If Metro is not installed the Hausdorff operation will report an error.
Furthermore, MaskComBinar currently only supports the WINDOWS version of Metro since it calls metro.exe and relies
on the windows-specific command-line output generated by the windows version of Metro. Future versions should also work
with the Linux version, but this has not yet been tested.
Metro can be downloaded from http://vcg.sourceforge.net/index.php/Metro
Known bug: Under some circumstances the module gets confused with pre-computed 3D isosurfaces (for display purposes).
This can make the module use (leak) working memory, or cause the wrong isosurface to be displayed.
The output is unaffected (to our knowledge).
(Module by Francois Malan)"""
class Measure2D:
kits = ['wx_kit', 'vtk_kit', 'geometry_kit']
cats = ['Viewers']
help = """Module for performing 2D measurements on image slices.
This is a viewer module and can not be used in an offline batch
processing setting.
"""
class QuickInfo:
kits = []
cats = ['Viewers']
help = """Gives more information about any module's output port.
Use this to help identify any type of data.
"""
class SkeletonAUIViewer:
kits = ['vtk_kit', 'wx_kit']
cats = ['Viewers']
help = """Skeleton module to using AUI for the interface and
integrating a VTK renderer panel.
Copy and adapt for your own use. Remember to modify the relevant
module_index.py.
"""
class slice3dVWR:
kits = ['wx_kit', 'vtk_kit']
cats = ['Viewers']
help = """The all-singing, all-dancing slice3dVWR module.
You can view almost anything with this module. Most of its documentation
is part of the application-central help. Press F1 (or select Help from
the main application menu) to see it.
"""
class Slicinator:
kits = ['wx_kit', 'vtk_kit']
cats = ['Viewers']
keywords = ['segmentation', 'contour']
help = """The Slicinator. It will be back!
"""
class TransferFunctionEditor:
kits = ['wx_kit']
cats = ['Viewers', 'Volume Rendering']
help = """Transfer function editor.
Module under heavy development.
"""
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import comedi_utils
reload(comedi_utils)
import vtk
import vtktudoss
from module_kits import vtk_kit
import wx
###########################################################################
# 2D:
# * Checkerboard.
# * difference mode: configurable combinations of LUTs and data
# components. Limited animation possible.
# * magic lens: either in IPW (this is going to be hard) or on
# vtkGDCMImageActor. TODO.
# 3D:
# * context gray (silhouette, data1), focus animated
# * context gray (silhouette, data2), focus difference image
# * thick slab rendering with f+c
###########################################################################
class ComparisonMode:
def __init__(self, comedi, cfg_dict):
pass
def disable_vis(self):
"""This will be called by CoMedI when it sees that we're about
to lose input data, before it calls update_vis(). This is to
give us time to de-init all visual elements whilst data is
still available. This is mostly because the vtkIPW calls
render whenever you try to disable or disconnect it.
"""
pass
def set_inputs(self, data1, data2, data2m, distance):
pass
def update_vis(self):
"""If all inputs are available, update the visualisation.
This also has to be called if there is no valid registered
output anymore so that the view can be disabled.
"""
pass
###########################################################################
class CheckerboardCM(ComparisonMode):
"""Comparison mode that shows a checkerboard of the two matched
datasets.
"""
def __init__(self, comedi, cfg_dict):
self._comedi = comedi
self._cfg = cfg_dict
rwi,ren = comedi.get_compvis_vtk()
self._sv = comedi_utils.CMSliceViewer(rwi, ren)
comedi.sync_slice_viewers.add_slice_viewer(self._sv)
self._cb = vtk.vtkImageCheckerboard()
# we'll store our local bindings here
self._d1 = None
self._d2m = None
def close(self):
self._comedi.sync_slice_viewers.remove_slice_viewer(self._sv)
self._sv.close()
# disconnect the checkerboard
self._cb.SetInput1(None)
self._cb.SetInput2(None)
def disable_vis(self):
self._sv.set_input(None)
def update_vis(self):
# if there's valid data, do the vis man!
d2m = self._comedi.get_data2m()
d1 = self._comedi.get_data1()
new_data = False
if d1 != self._d1:
self._d1 = d1
self._cb.SetInput1(d1)
new_data = True
if d2m != self._d2m:
self._d2m = d2m
self._cb.SetInput2(d2m)
new_data = True
if new_data:
# this means the situation has changed
if d1 and d2m:
# we have two datasets and can checkerboard them
# enable the slice viewer
self._sv.set_input(self._cb.GetOutput())
# sync it to data1
sv1 = self._comedi._data1_slice_viewer
self._comedi.sync_slice_viewers.sync_all(
sv1, [self._sv])
else:
# this means one of our datasets is NULL
# disable the slice viewer
self._sv.set_input(None)
# now check for UI things
cp = self._comedi._view_frame.pane_controls.window
divx = cp.cm_checkerboard_divx.GetValue()
divy = cp.cm_checkerboard_divy.GetValue()
divz = cp.cm_checkerboard_divz.GetValue()
ndiv = self._cb.GetNumberOfDivisions()
if ndiv != (divx, divy, divz):
self._cb.SetNumberOfDivisions((divx, divy, divz))
# we do render to update the 3D view
self._sv.render()
###########################################################################
class Data2MCM(ComparisonMode):
"""Match mode that only displays the matched data2.
"""
def __init__(self, comedi, cfg_dict):
self._comedi = comedi
self._cfg = cfg_dict
rwi,ren = comedi.get_compvis_vtk()
self._sv = comedi_utils.CMSliceViewer(rwi, ren)
comedi.sync_slice_viewers.add_slice_viewer(self._sv)
def close(self):
self._comedi.sync_slice_viewers.remove_slice_viewer(self._sv)
self._sv.close()
def disable_vis(self):
self._sv.set_input(None)
def update_vis(self):
# if there's valid data, do the vis man!
o = self._comedi.match_mode.get_output()
# get current input
ci = self._sv.get_input()
if o != ci:
# new data! do something!
self._sv.set_input(o)
# if it's not null, sync with primary viewer
if o is not None:
sv1 = self._comedi._data1_slice_viewer
self._comedi.sync_slice_viewers.sync_all(
sv1, [self._sv])
# we do render to update the 3D view
self._sv.render()
CMAP_BLUE_TO_YELLOW_KREKEL = 0
CMAP_HEAT_PL = 1
CMAP_BLUE_TO_YELLOW_PL = 2
CMAP_BLACK_TO_WHITE_PL = 3
###########################################################################
class FocusDiffCM(ComparisonMode):
"""Match mode that displays difference between data in focus area
with blue/yellow colour scale, normal greyscale for the context.
"""
# API methods ###################################################
def __init__(self, comedi, cfg_dict):
self._comedi = comedi
self._cfg = cfg_dict
# we'll store our local bindings here
self._d1 = None
self._d2m = None
self._conf = None
self._cmap_range = [-1024, 3072]
self._cmap_type = CMAP_BLUE_TO_YELLOW_PL
# color scales thingy
self._color_scales = vtk_kit.color_scales.ColorScales()
# instantiate us a slice viewer
rwi,ren = comedi.get_compvis_vtk()
self._sv = comedi_utils.CMSliceViewer(rwi, ren)
# now make our own MapToColors
ct = 32
lut = self._sv.ipws[0].GetLookupTable()
self._cmaps = [vtktudoss.vtkCVImageMapToColors() for _ in range(3)]
for i,cmap in enumerate(self._cmaps):
cmap.SetLookupTable(lut)
cmap.SetConfidenceThreshold(ct)
self._sv.ipws[i].SetColorMap(cmap)
self._set_confidence_threshold_ui(ct)
comedi.sync_slice_viewers.add_slice_viewer(self._sv)
# now build up the VTK pipeline #############################
# we'll use these to scale data between 0 and max.
self._ss1 = vtk.vtkImageShiftScale()
self._ss1.SetOutputScalarTypeToShort()
self._ss2 = vtk.vtkImageShiftScale()
self._ss2.SetOutputScalarTypeToShort()
# we have to cast the confidence to shorts as well
self._ssc = vtk.vtkImageShiftScale()
self._ssc.SetOutputScalarTypeToShort()
self._iac = vtk.vtkImageAppendComponents()
# data1 will form the context
self._iac.SetInput(0, self._ss1.GetOutput())
# subtraction will form the focus
self._iac.SetInput(1, self._ss2.GetOutput())
# third input will be the confidence
self._iac.SetInput(2, self._ssc.GetOutput())
# event bindings ############################################
self._bind_events()
def close(self):
self._unbind_events()
self._comedi.sync_slice_viewers.remove_slice_viewer(self._sv)
self._sv.close()
# take care of all our bindings to VTK classes
del self._ss1
del self._ss2
def disable_vis(self):
self._sv.set_input(None)
def update_vis(self):
# if there's valid data, do the vis man!
d2m = self._comedi.get_data2m()
d1 = self._comedi.get_data1()
conf = self._comedi.match_mode.get_confidence()
new_data = False
if d1 != self._d1:
self._d1 = d1
self._ss1.SetInput(d1)
new_data = True
if d2m != self._d2m:
self._d2m = d2m
self._ss2.SetInput(d2m)
new_data = True
if conf != self._conf:
self._conf = conf
self._ssc.SetInput(self._conf)
if d1 and d2m and conf:
if new_data:
self._ss1.Update()
self._ss2.Update()
r = self._ss1.GetOutput().GetScalarRange()
self._set_cmap_type_and_range(
CMAP_BLUE_TO_YELLOW_PL, r, True)
self._set_range_ui(r)
print "about to update iac"
self._iac.SetNumberOfThreads(1)
self._iac.Update()
print "done updating iac"
self._sv.set_input(self._iac.GetOutput())
# sync it to data1
sv1 = self._comedi._data1_slice_viewer
self._comedi.sync_slice_viewers.sync_all(
sv1, [self._sv])
else:
# now new data, but we might want to update the
# vis-settings
self._handler_conf_thresh(event)
self._sync_cmap_type_and_range_with_ui()
else:
self._sv.set_input(None)
# we do render to update the 3D view
self._sv.render()
# PRIVATE methods ###############################################
def _bind_events(self):
vf = self._comedi._view_frame
panel = vf.pane_controls.window
panel.cm_diff_conf_thresh_txt.Bind(
wx.EVT_TEXT_ENTER,
self._handler_conf_thresh)
panel.cm_diff_context_target_choice.Bind(
wx.EVT_CHOICE,
self._handler_focus_context_choice)
panel.cm_diff_focus_target_choice.Bind(
wx.EVT_CHOICE,
self._handler_focus_target_choice)
panel.cm_diff_cmap_choice.Bind(
wx.EVT_CHOICE,
self._handler_cmap_choice)
panel.cm_diff_range0_text.Bind(
wx.EVT_TEXT_ENTER,
self._handler_range0)
panel.cm_diff_range1_text.Bind(
wx.EVT_TEXT_ENTER,
self._handler_range1)
def _handler_cmap_choice(self, event):
self._sync_cmap_type_and_range_with_ui()
def _handler_conf_thresh(self, event):
vf = self._comedi._view_frame
panel = vf.pane_controls.window
v = panel.cm_diff_conf_thresh_txt.GetValue()
try:
v = float(v)
except ValueError:
v = self._cmaps[0].GetConfidenceThreshold()
self._set_confidence_threshold_ui(v)
else:
[cmap.SetConfidenceThreshold(v) for cmap in self._cmaps]
self._sv.render()
def _handler_focus_context_choice(self, event):
c = event.GetEventObject()
val = c.GetSelection()
if val != self._cmaps[0].GetContextTarget():
[cmap.SetContextTarget(val) for cmap in self._cmaps]
self._sv.render()
def _handler_range0(self, event):
self._sync_cmap_type_and_range_with_ui()
def _handler_range1(self, event):
self._sync_cmap_type_and_range_with_ui()
def _handler_focus_target_choice(self, event):
c = event.GetEventObject()
val = c.GetSelection()
if val != self._cmaps[0].GetFocusTarget():
[cmap.SetFocusTarget(val) for cmap in self._cmaps]
self._sv.render()
def _set_confidence_threshold_ui(self, thresh):
vf = self._comedi._view_frame
panel = vf.pane_controls.window
panel.cm_diff_conf_thresh_txt.SetValue('%.1f' % (thresh,))
def _set_range_ui(self, range):
"""Set the given range in the interface.
"""
vf = self._comedi._view_frame
panel = vf.pane_controls.window
r = range
panel.cm_diff_range0_text.SetValue(str(r[0]))
panel.cm_diff_range1_text.SetValue(str(r[1]))
def _unbind_events(self):
vf = self._comedi._view_frame
panel = vf.pane_controls.window
panel.cm_diff_context_target_choice.Unbind(
wx.EVT_CHOICE)
panel.cm_diff_focus_target_choice.Unbind(
wx.EVT_CHOICE)
panel.cm_diff_range0_text.Unbind(
wx.EVT_TEXT_ENTER)
panel.cm_diff_range1_text.Unbind(
wx.EVT_TEXT_ENTER)
def _set_cmap_type_and_range(self, cmap_type, range,
force_update=False):
"""First sanitise, then synchronise the current colormap range
to the specified UI values, also taking into account the
current colour map choice.
"""
vf = self._comedi._view_frame
panel = vf.pane_controls.window
r0 = panel.cm_diff_range0_text.GetValue()
r1 = panel.cm_diff_range1_text.GetValue()
try:
r0 = float(r0)
except ValueError:
r0 = self._cmap_range[0]
try:
r1 = float(r1)
except ValueError:
r1 = self._cmap_range[1]
# swap if necessary
if r0 > r1:
r1,r0 = r0,r1
r = r0,r1
if force_update:
must_update = True
else:
must_update = False
if r0 != self._cmap_range[0] or r1 != self._cmap_range[1]:
must_update = True
self._cmap_range = r
if cmap_type != self._cmap_type:
must_update = True
self._cmap_type = cmap_type
if must_update:
if cmap_type == CMAP_BLUE_TO_YELLOW_KREKEL:
lut = self._color_scales.LUT_BlueToYellow(r)
elif cmap_type == CMAP_HEAT_PL:
lut = self._color_scales.LUT_Linear_Heat(r)
elif cmap_type == CMAP_BLUE_TO_YELLOW_PL:
lut = self._color_scales.LUT_Linear_BlueToYellow(r)
elif cmap_type == CMAP_BLACK_TO_WHITE_PL:
lut = self._color_scales.LUT_Linear_BlackToWhite(r)
for cmap in self._cmaps:
cmap.SetLookupTable2(lut)
self._sv.render()
# we return the possibly corrected range
return r
def _sync_cmap_type_and_range_with_ui(self):
vf = self._comedi._view_frame
panel = vf.pane_controls.window
r0 = panel.cm_diff_range0_text.GetValue()
r1 = panel.cm_diff_range0_text.GetValue()
cmap_type = panel.cm_diff_cmap_choice.GetSelection()
r = self._set_cmap_type_and_range(cmap_type, (r0,r1))
if r[0] != r0 or r[1] != r1:
self._set_range_ui(r)
# PUBLIC methods ################################################
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
# Hello there person reading this source!
# At the moment, I'm trying to get a fully-functioning DICOM browser
# out the door as fast as possible. As soon as the first version is
# out there and my one user can start giving feedback, the following
# major changes are planned:
# * refactoring of the code, specifically to get the dicom slice
# viewer out into a separate class for re-use in the rest of DeVIDE,
# for example by the light-table thingy I'm planning. See issue 38.
# * caching of DICOM searches: a scan of a set of directories will
# create an sqlite file with all scanned information. Name of sql
# file will be stored in config, so that restarts will be REALLY
# quick. One will be able to scan (recreate whole cache file) or
# a quick re-scan (only add new files that have appeared, remove
# files that have disappeared). See issue 39.
import DICOMBrowserFrame
reload(DICOMBrowserFrame)
import gdcm
from module_kits.misc_kit import misc_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import os
import sys
import traceback
import vtk
import vtkgdcm
import wx
class Study:
def __init__(self):
self.patient_name = None
self.patient_id = None
self.uid = None
self.description = None
self.date = None
# maps from series_uid to Series instance
self.series_dict = {}
# total number of slices in complete study
self.slices = 0
# create list of attributes for serialisation functions
s = Study()
STUDY_ATTRS = [i for i in dir(s)
if not i.startswith('__') and
i not in ['uid', 'series_dict']]
class Series:
def __init__(self):
self.uid = None
self.description = None
self.modality = None
self.filenames = []
# number of slices can deviate from number of filenames due to
# multi-frame DICOM files
self.slices = 0
self.rows = 0
self.columns = 0
# create list of attributes for serialisation functions
s = Series()
SERIES_ATTRS = [i for i in dir(s)
if not i.startswith('__') and
i not in ['uid']]
class DICOMBrowser(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
DICOMBrowserFrame.DICOMBrowserFrame)
# change the title to something more spectacular
# default is DICOMBrowser View
self._view_frame.SetTitle('DeVIDE DICOMBrowser')
self._image_viewer = None
self._setup_image_viewer()
# map from study_uid to Study instances
self._study_dict = {}
# map from studies listctrl itemdata to study uid
self._item_data_to_study_uid = {}
# currently selected study_uid
self._selected_study_uid = None
self._item_data_to_series_uid = {}
self._selected_series_uid = None
# store name of currently previewed filename, so we don't
# reload unnecessarily.
self._current_filename = None
self._bind_events()
self._config.dicom_search_paths = []
self._config.lock_pz = False
self._config.lock_wl = False
self._config.s_study_dict = {}
self.sync_module_logic_with_config()
self.sync_module_view_with_logic()
self.view()
# all modules should toggle this once they have shown their
# stuff.
self.view_initialised = True
if os.name == 'posix':
# bug with GTK where the image window appears bunched up
# in the top-left corner. By setting the default view
# (again), it's worked around
self._view_frame.set_default_view()
def close(self):
# with this complicated de-init, we make sure that VTK is
# properly taken care of
self._image_viewer.GetRenderer().RemoveAllViewProps()
self._image_viewer.SetupInteractor(None)
self._image_viewer.SetRenderer(None)
# this finalize makes sure we don't get any strange X
# errors when we kill the module.
self._image_viewer.GetRenderWindow().Finalize()
self._image_viewer.SetRenderWindow(None)
del self._image_viewer
# done with VTK de-init
self._view_frame.close()
self._view_frame = None
IntrospectModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def get_output_descriptions(self):
return ()
def set_input(self, idx, input_stream):
pass
def get_output(self, idx):
pass
def execute_module(self):
pass
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def config_to_view(self):
# show DICOM search paths in interface
tc = self._view_frame.dirs_pane.dirs_files_tc
tc.SetValue(self._helper_dicom_search_paths_to_string(
self._config.dicom_search_paths))
# show value of pz and wl locks
ip = self._view_frame.image_pane
ip.lock_pz_cb.SetValue(self._config.lock_pz)
ip.lock_wl_cb.SetValue(self._config.lock_wl)
# now load the cached study_dict (if available)
self._study_dict = self._deserialise_study_dict(
self._config.s_study_dict)
self._fill_studies_listctrl()
def view_to_config(self):
# self._config is maintained in real-time
pass
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# because we have an RWI involved, we have to do this
# SafeYield, so that the window does actually appear before we
# call the render. If we don't do this, we get an initial
# empty renderwindow.
wx.SafeYield()
self._view_frame.render_image()
def _bind_events(self):
vf = self._view_frame
vf.Bind(wx.EVT_MENU, self._handler_next_image,
id = vf.id_next_image)
vf.Bind(wx.EVT_MENU, self._handler_prev_image,
id = vf.id_prev_image)
# we unbind the existing mousewheel handler so it doesn't
# interfere
self._view_frame.image_pane.rwi.Unbind(wx.EVT_MOUSEWHEEL)
self._view_frame.image_pane.rwi.Bind(
wx.EVT_MOUSEWHEEL, self._handler_mousewheel)
fp = self._view_frame.dirs_pane
fp.ad_button.Bind(wx.EVT_BUTTON,
self._handler_ad_button)
fp.af_button.Bind(wx.EVT_BUTTON,
self._handler_af_button)
fp.scan_button.Bind(wx.EVT_BUTTON,
self._handler_scan_button)
lc = self._view_frame.studies_lc
lc.Bind(wx.EVT_LIST_ITEM_SELECTED,
self._handler_study_selected)
lc = self._view_frame.series_lc
lc.Bind(wx.EVT_LIST_ITEM_SELECTED,
self._handler_series_selected)
# with this one, we'll catch drag events
lc.Bind(wx.EVT_MOTION, self._handler_series_motion)
lc = self._view_frame.files_lc
# we use this event instead of focused, as group / multi
# selections (click, then shift click 5 items down) would fire
# selected events for ALL involved items. With FOCUSED, only
# the item actually clicked on, or keyboarded to, gets the
# event.
lc.Bind(wx.EVT_LIST_ITEM_FOCUSED,
self._handler_file_selected)
# catch drag events (so user can drag and drop selected files)
lc.Bind(wx.EVT_MOTION, self._handler_files_motion)
# the IPP sort button in the files pane
ipp_sort_button = self._view_frame.files_pane.ipp_sort_button
ipp_sort_button.Bind(wx.EVT_BUTTON, self._handler_ipp_sort)
# keep track of the image viewer controls
ip = self._view_frame.image_pane
ip.lock_pz_cb.Bind(wx.EVT_CHECKBOX,
self._handler_lock_pz_cb)
ip.lock_wl_cb.Bind(wx.EVT_CHECKBOX,
self._handler_lock_wl_cb)
ip.reset_b.Bind(wx.EVT_BUTTON,
self._handler_image_reset_b)
def _helper_files_to_files_listctrl(self, filenames):
lc = self._view_frame.files_lc
lc.DeleteAllItems()
self._item_data_to_file = {}
for filename in filenames:
idx = lc.InsertStringItem(sys.maxint, filename)
lc.SetItemData(idx, idx)
self._item_data_to_file[idx] = filename
def _fill_files_listctrl(self):
# get out current Study instance
study = self._study_dict[self._selected_study_uid]
# then the series_dict belonging to that Study
series_dict = study.series_dict
# and finally the specific series instance
series = series_dict[self._selected_series_uid]
# finally copy the filenames to the listctrl
self._helper_files_to_files_listctrl(series.filenames)
lc = self._view_frame.files_lc
# select the first file
if lc.GetItemCount() > 0:
lc.Select(0)
# in this case we have to focus as well, as that's the
# event that it's sensitive to.
lc.Focus(0)
def _fill_series_listctrl(self):
# get out current Study instance
study = self._study_dict[self._selected_study_uid]
# then the series_dict belonging to that Study
series_dict = study.series_dict
# clear the ListCtrl
lc = self._view_frame.series_lc
lc.DeleteAllItems()
# shortcut to the columns class
sc = DICOMBrowserFrame.SeriesColumns
# we're going to need this for the column sorting
item_data_map = {}
self._item_data_to_series_uid = {}
for series_uid, series in series_dict.items():
idx = lc.InsertStringItem(sys.maxint, series.description)
lc.SetStringItem(idx, sc.modality, series.modality)
lc.SetStringItem(idx, sc.num_images, str(series.slices))
rc_string = '%d x %d' % (series.columns, series.rows)
lc.SetStringItem(idx, sc.row_col, rc_string)
# also for the column sorting
lc.SetItemData(idx, idx)
item_data_map[idx] = (
series.description,
series.modality,
series.slices,
rc_string)
self._item_data_to_series_uid[idx] = series.uid
lc.itemDataMap = item_data_map
# select the first series
if lc.GetItemCount() > 0:
lc.SetItemState(0, wx.LIST_STATE_SELECTED,
wx.LIST_STATE_SELECTED)
def _fill_studies_listctrl(self):
"""Given a study dictionary, fill out the complete studies
ListCtrl.
This will also select the first study, triggering that event
handler and consequently filling the series control and the
images control for the first selected series.
"""
lc = self._view_frame.studies_lc
# clear the thing out
lc.DeleteAllItems()
sc = DICOMBrowserFrame.StudyColumns
# this is for the columnsorter
item_data_map = {}
# this is for figuring out which study is selected in the
# event handler
self.item_data_to_study_id = {}
for study_uid, study in self._study_dict.items():
# clean way of mapping from item to column?
idx = lc.InsertStringItem(sys.maxint, study.patient_name)
lc.SetStringItem(idx, sc.patient_id, study.patient_id)
lc.SetStringItem(idx, sc.description, study.description)
lc.SetStringItem(idx, sc.date, study.date)
lc.SetStringItem(idx, sc.num_images, str(study.slices))
lc.SetStringItem(
idx, sc.num_series, str(len(study.series_dict)))
# we set the itemdata to the current index (this will
# change with sorting, of course)
lc.SetItemData(idx, idx)
# for sorting we build up this item_data_map with the same
# hash as key, and the all values occurring in the columns
# as sortable values
item_data_map[idx] = (
study.patient_name,
study.patient_id,
study.description,
study.date,
study.slices,
len(study.series_dict))
self._item_data_to_study_uid[idx] = study.uid
# assign the datamap to the ColumnSorterMixin
lc.itemDataMap = item_data_map
if lc.GetItemCount() > 0:
lc.SetItemState(0, wx.LIST_STATE_SELECTED,
wx.LIST_STATE_SELECTED)
else:
# this means the study LC is empty, i.e. nothing was
# found. In this case, we have to empty the other series
# and file LCs as well.
self._view_frame.series_lc.DeleteAllItems()
self._view_frame.files_lc.DeleteAllItems()
#lc.auto_size_columns()
def _handler_ad_button(self, event):
dlg = wx.DirDialog(self._view_frame,
"Choose a directory to add:",
style=wx.DD_DEFAULT_STYLE
| wx.DD_DIR_MUST_EXIST
)
if dlg.ShowModal() == wx.ID_OK:
p = dlg.GetPath()
tc = self._view_frame.dirs_pane.dirs_files_tc
v = tc.GetValue()
nv = self._helper_dicom_search_paths_to_string(
[v, p])
tc.SetValue(nv)
dlg.Destroy()
def _handler_af_button(self, event):
dlg = wx.FileDialog(
self._view_frame, message="Choose files to add:",
defaultDir="",
defaultFile="",
wildcard="All files (*.*)|*.*",
style=wx.OPEN | wx.MULTIPLE
)
if dlg.ShowModal() == wx.ID_OK:
tc = self._view_frame.dirs_pane.dirs_files_tc
v = tc.GetValue()
nv = self._helper_dicom_search_paths_to_string(
[v] + [str(p) for p in dlg.GetPaths()])
tc.SetValue(nv)
dlg.Destroy()
def _handler_file_selected(self, event):
# this handler gets called one more time AFTER we've destroyed
# the DICOMBrowserViewFrame, so we have to check.
if not self._view_frame:
return
lc = self._view_frame.files_lc
idx = lc.GetItemData(event.m_itemIndex)
filename = self._item_data_to_file[idx]
if filename == self._current_filename:
# we're already viewing this filename, don't try to load
# again.
return
# first make sure the image_viewer has a dummy input, so that
# any previously connected reader can be deallocated first
self._set_image_viewer_dummy_input()
# unlike the DICOMReader, we allow the vtkGDCMImageReader to
# do its y-flipping here.
r = vtkgdcm.vtkGDCMImageReader()
r.SetFileName(filename)
try:
r.Update()
except RuntimeWarning, e:
# reader generates warning of overlay information can't be
# read. We should change the VTK exception support to
# just output some text with a warning and not raise an
# exception.
traceback.print_exc()
# with trackback.format_exc() you can send this to the log
# window.
except RuntimeError, e:
self._module_manager.log_error(
'Could not read %s:\n%s.\nSuggest re-Scan.' %
(os.path.basename(filename), str(e)))
return
self._update_image(r)
self._update_meta_data_pane(r)
self._current_filename = filename
def _handler_ipp_sort(self, event):
# get out current Study instance
study = self._study_dict[self._selected_study_uid]
# then the series_dict belonging to that Study
series_dict = study.series_dict
# and finally the specific series instance
series = series_dict[self._selected_series_uid]
# have to cast to normal strings (from unicode)
filenames = [str(i) for i in series.filenames]
sorter = gdcm.IPPSorter()
ret = sorter.Sort(filenames)
if not ret:
self._module_manager.log_error(
'Could not sort DICOM filenames. ' +
'It could be that this is an invalid collection.')
return
selected_idx = -1
del series.filenames[:]
for idx,fn in enumerate(sorter.GetFilenames()):
series.filenames.append(fn)
if idx >= 0 and fn == self._current_filename:
selected_idx = idx
lc = self._view_frame.files_lc
# now overwrite the listctrl with these sorted filenames
self._helper_files_to_files_listctrl(series.filenames)
# select the file that was selected prior to the sort
if selected_idx >= 0:
lc.Select(selected_idx)
lc.Focus(selected_idx)
def _handler_mousewheel(self, event):
# event.GetWheelRotation() is + or - 120 depending on
# direction of turning.
if event.ControlDown():
delta = 10
else:
delta = 1
if event.GetWheelRotation() > 0:
self._helper_prev_image(delta)
else:
self._helper_next_image(delta)
def _handler_next_image(self, event):
self._helper_next_image()
def _handler_prev_image(self, event):
self._helper_prev_image()
def _helper_next_image(self, delta=1):
"""Go to next image.
We could move this to the display code, it only needs to know
about widgets.
"""
# first see if we're previewing a multi-slice DICOM file
next_file = True
range = [0,0]
self._image_viewer.GetSliceRange(range)
if range[1] - range[0] != 0:
cur_slice = self._image_viewer.GetSlice()
if cur_slice <= range[1] - delta:
new_slice = cur_slice + delta
self._image_viewer.SetSlice(new_slice)
self._image_viewer.ul_text_actor.frnum = new_slice
self._update_image_ul_text()
next_file = False
if next_file:
lc = self._view_frame.files_lc
nidx = lc.GetFocusedItem() + delta
if nidx >= lc.GetItemCount():
nidx = lc.GetItemCount() - 1
lc.Focus(nidx)
def _helper_prev_image(self, delta=1):
"""Move to previous image.
We could move this to the display code, it only needs to know
about widgets.
"""
# first see if we're previewing a multi-slice DICOM file
prev_file = True
range = [0,0]
self._image_viewer.GetSliceRange(range)
if range[1] - range[0] != 0:
cur_slice = self._image_viewer.GetSlice()
if cur_slice >= range[0] + delta:
new_slice = cur_slice - delta
self._image_viewer.SetSlice(new_slice)
self._image_viewer.ul_text_actor.frnum = new_slice
self._update_image_ul_text()
prev_file = False
if prev_file:
lc = self._view_frame.files_lc
nidx = lc.GetFocusedItem() - delta
if nidx < 0:
nidx = 0
lc.Focus(nidx)
def _read_all_tags(self, filename):
r = gdcm.Reader(filename)
r.Read()
f = r.GetFile()
ds = file.GetDataSet()
pds = gdcm.PythonDataSet(ds)
sf = gdcm.StringFilter()
pds.Start() # Make iterator go at begining
dic={}
sf.SetFile(f) # extremely important
while(not pds.IsAtEnd() ):
res = sf.ToStringPair( pds.GetCurrent().GetTag() )
dic[res[0]] = res[1]
pds.Next()
return dic
def _update_image_ul_text(self):
"""Updates upper left text actor according to relevant
instance variables.
"""
ul = self._image_viewer.ul_text_actor
imsize_str = 'Image Size: %d x %d' % (ul.imsize)
imnum_str = 'Image # %s' % (ul.imnum,)
frnum_str = 'Frame # %d' % (ul.frnum,)
ul.SetInput('%s\n%s\n%s' % (
imsize_str, imnum_str, frnum_str))
def _update_image(self, gdcm_reader):
"""Given a vtkGDCMImageReader instance that has read the given
file, update the image viewer.
"""
r = gdcm_reader
self._image_viewer.SetInput(r.GetOutput())
#if r.GetNumberOfOverlays():
# self._image_viewer.AddInput(r.GetOverlay(0))
# now make the nice text overlay thingies!
# DirectionCosines: first two columns are X and Y in the LPH
# coordinate system
dc = r.GetDirectionCosines()
x_cosine = \
dc.GetElement(0,0), dc.GetElement(1,0), dc.GetElement(2,0)
lph = misc_utils.major_axis_from_iop_cosine(x_cosine)
if lph:
self._image_viewer.xl_text_actor.SetInput(lph[0])
self._image_viewer.xr_text_actor.SetInput(lph[1])
else:
self._image_viewer.xl_text_actor.SetInput('X')
self._image_viewer.xr_text_actor.SetInput('X')
y_cosine = \
dc.GetElement(0,1), dc.GetElement(1,1), dc.GetElement(2,1)
lph = misc_utils.major_axis_from_iop_cosine(y_cosine)
if lph:
if r.GetFileLowerLeft():
# no swap
b = lph[0]
t = lph[1]
else:
# we have to swap these around because VTK has the
# convention of image origin at the upper left and GDCM
# dutifully swaps the images when loading to follow this
# convention. Direction cosines (IOP) is not swapped, so
# we have to compensate here.
b = lph[1]
t = lph[0]
self._image_viewer.yb_text_actor.SetInput(b)
self._image_viewer.yt_text_actor.SetInput(t)
else:
self._image_viewer.yb_text_actor.SetInput('X')
self._image_viewer.yt_text_actor.SetInput('X')
mip = r.GetMedicalImageProperties()
d = r.GetOutput().GetDimensions()
ul = self._image_viewer.ul_text_actor
ul.imsize = (d[0], d[1])
ul.imnum = mip.GetImageNumber() # string
ul.frnum = self._image_viewer.GetSlice()
self._update_image_ul_text()
ur = self._image_viewer.ur_text_actor
ur.SetInput('%s\n%s\n%s\n%s' % (
mip.GetPatientName(),
mip.GetPatientID(),
mip.GetStudyDescription(),
mip.GetSeriesDescription()))
br = self._image_viewer.br_text_actor
br.SetInput('DeVIDE\nTU Delft')
# we have a new image in the image_viewer, so we have to reset
# the camera so that the image is visible.
if not self._config.lock_pz:
self._reset_image_pz()
# also reset window level
if not self._config.lock_wl:
self._reset_image_wl()
self._image_viewer.Render()
def _update_meta_data_pane(self, gdcm_reader):
"""Given a vtkGDCMImageReader instance that was used to read a
file, update the meta-data display.
"""
# update image meta-data #####
r = gdcm_reader
mip = r.GetMedicalImageProperties()
r_attr_l = [
'DataOrigin',
'DataSpacing'
]
import module_kits.vtk_kit
mip_attr_l = \
module_kits.vtk_kit.constants.medical_image_properties_keywords
item_data_map = {}
lc = self._view_frame.meta_lc
# only start over if we have to to avoid flickering and
# resetting of scroll bars.
if lc.GetItemCount() != (len(r_attr_l) + len(mip_attr_l)):
lc.DeleteAllItems()
reset_lc = True
else:
reset_lc = False
def helper_av_in_lc(a, v, idx):
if reset_lc:
# in the case of a reset (i.e. we have to build up the
# listctrl from scratch), the idx param is ignored as
# we overwrite it with our own here
idx = lc.InsertStringItem(sys.maxint, a)
else:
# not a reset, so we use the given idx
lc.SetStringItem(idx, 0, a)
lc.SetStringItem(idx, 1, v)
lc.SetItemData(idx, idx)
item_data_map[idx] = (a, v)
idx = 0
for a in r_attr_l:
v = str(getattr(r, 'Get%s' % (a,))())
helper_av_in_lc(a, v, idx)
idx = idx + 1
for a in mip_attr_l:
v = str(getattr(mip, 'Get%s' % (a,))())
helper_av_in_lc(a, v, idx)
idx = idx + 1
# so that sorting (kinda) works
lc.itemDataMap = item_data_map
def _handler_image_reset_b(self, event):
self._reset_image_pz()
self._reset_image_wl()
self._image_viewer.Render()
def _handler_lock_pz_cb(self, event):
cb = self._view_frame.image_pane.lock_pz_cb
self._config.lock_pz = cb.GetValue()
# when the user unlocks pan/zoom, reset it for the current
# image
if not self._config.lock_pz:
self._reset_image_pz()
self._image_viewer.Render()
def _handler_lock_wl_cb(self, event):
cb = self._view_frame.image_pane.lock_wl_cb
self._config.lock_wl = cb.GetValue()
# when the user unlocks window / level, reset it for the
# current image
if not self._config.lock_wl:
self._reset_image_wl()
self._image_viewer.Render()
def _handler_scan_button(self, event):
tc = self._view_frame.dirs_pane.dirs_files_tc
# helper function discards empty strings and strips the rest
paths = self._config.dicom_search_paths = \
self._helper_dicom_search_paths_to_list(tc.GetValue())
# let's put it back in the interface too
tc.SetValue(self._helper_dicom_search_paths_to_string(paths))
try:
self._study_dict = self._scan(paths)
except Exception, e:
# also print the exception
traceback.print_exc()
# i don't want to use log_error_with_exception, because it
# uses a non-standard dialogue box that pops up over the
# main devide window instead of the module view.
self._module_manager.log_error(
'Error scanning DICOM files: %s' % (str(e)))
# serialise study_dict into config
self._config.s_study_dict = self._serialise_study_dict(
self._study_dict)
# do this in anycase...
self._fill_studies_listctrl()
def _handler_files_motion(self, event):
"""Handler for when user drags a file selection somewhere.
"""
if not event.Dragging():
event.Skip()
return
lc = self._view_frame.files_lc
selected_idxs = []
s = lc.GetFirstSelected()
while s != -1:
selected_idxs.append(s)
s = lc.GetNextSelected(s)
if len(selected_idxs) > 0:
data_object = wx.FileDataObject()
for idx in selected_idxs:
data_object.AddFile(self._item_data_to_file[idx])
drop_source = wx.DropSource(lc)
drop_source.SetData(data_object)
drop_source.DoDragDrop(False)
def _handler_series_motion(self, event):
if not event.Dragging():
event.Skip()
return
# get out current Study instance
try:
study = self._study_dict[self._selected_study_uid]
except KeyError:
return
# then the series_dict belonging to that Study
series_dict = study.series_dict
# and finally the specific series instance
# series.filenames is a list of the filenames
try:
series = series_dict[self._selected_series_uid]
except KeyError:
return
# according to the documentation, we can only write to this
# object on Windows and GTK2. Hrrmmpph.
# FIXME. Will have to think up an alternative solution on
# OS-X
data_object = wx.FileDataObject()
for f in series.filenames:
data_object.AddFile(f)
drop_source = wx.DropSource(self._view_frame.series_lc)
drop_source.SetData(data_object)
# False means that files will be copied, NOT moved
drop_source.DoDragDrop(False)
def _handler_series_selected(self, event):
lc = self._view_frame.series_lc
idx = lc.GetItemData(event.m_itemIndex)
series_uid = self._item_data_to_series_uid[idx]
self._selected_series_uid = series_uid
print 'series_uid', series_uid
self._fill_files_listctrl()
def _handler_study_selected(self, event):
# we get the ItemData from the currently selected ListCtrl
# item
lc = self._view_frame.studies_lc
idx = lc.GetItemData(event.m_itemIndex)
# and then use this to find the current study_uid
study_uid = self._item_data_to_study_uid[idx]
self._selected_study_uid = study_uid
print 'study uid', study_uid
self._fill_series_listctrl()
def _helper_dicom_search_paths_to_string(
self, dicom_search_paths):
"""Given a list of search paths, append them into a semicolon
delimited string.
"""
s = [i.strip() for i in dicom_search_paths]
s2 = [i for i in s if len(i) > 0]
return ' ; '.join(s2)
def _helper_dicom_search_paths_to_list(
self, dicom_search_paths):
"""Given a semicolon-delimited string, break into list.
"""
s = [str(i.strip()) for i in dicom_search_paths.split(';')]
return [i for i in s if len(i) > 0]
def _helper_recursive_glob(self, paths):
"""Given a combined list of files and directories, return a
combined list of sorted and unique fully-qualified filenames,
consisting of the supplied filenames and a recursive search
through all supplied directories.
"""
# we'll use this to keep all filenames unique
files_dict = {}
d = gdcm.Directory()
for path in paths:
if os.path.isdir(path):
# we have to cast path to str (it's usually unicode)
# else the gdcm wrappers error on "bad number of
# arguments to overloaded function"
d.Load(str(path), True)
# fromkeys creates a new dictionary with GetFilenames
# as keys; then update merges this dictionary with the
# existing files_dict
normed = [os.path.normpath(i) for i in d.GetFilenames()]
files_dict.update(dict.fromkeys(normed, 1))
elif os.path.isfile(path):
files_dict[os.path.normpath(path)] = 1
# now sort everything
filenames = files_dict.keys()
filenames.sort()
return filenames
def _reset_image_pz(self):
"""Reset the pan/zoom of the current image.
"""
ren = self._image_viewer.GetRenderer()
ren.ResetCamera()
def _reset_image_wl(self):
"""Reset the window/level of the current image.
This assumes that the image has already been read and that it
has a valid scalar range.
"""
iv = self._image_viewer
inp = iv.GetInput()
if inp:
r = inp.GetScalarRange()
iv.SetColorWindow(r[1] - r[0])
iv.SetColorLevel(0.5 * (r[1] + r[0]))
def _scan(self, paths):
"""Given a list combining filenames and directories, search
recursively to find all valid DICOM files. Build
dictionaries.
"""
# UIDs are unique for their domains. Patient ID for example
# is not unique.
# Instance UID (0008,0018)
# Patient ID (0010,0020)
# Study UID (0020,000D) - data with common procedural context
# Study description (0008,1030)
# Series UID (0020,000E)
# see http://public.kitware.com/pipermail/igstk-developers/
# 2006-March/000901.html for explanation w.r.t. number of
# frames; for now we are going to assume that this refers to
# the number of included slices (as is the case for the
# Toshiba 320 slice for example)
tag_to_symbol = {
(0x0008, 0x0018) : 'instance_uid',
(0x0010, 0x0010) : 'patient_name',
(0x0010, 0x0020) : 'patient_id',
(0x0020, 0x000d) : 'study_uid',
(0x0008, 0x1030) : 'study_description',
(0x0008, 0x0020) : 'study_date',
(0x0020, 0x000e) : 'series_uid',
(0x0008, 0x103e) : 'series_description',
(0x0008, 0x0060) : 'modality', # fixed per series
(0x0028, 0x0008) : 'number_of_frames',
(0x0028, 0x0010) : 'rows',
(0x0028, 0x0011) : 'columns'
}
# find list of unique and sorted filenames
filenames = self._helper_recursive_glob(paths)
s = gdcm.Scanner()
# add the tags we want to the scanner
for tag_tuple in tag_to_symbol:
tag = gdcm.Tag(*tag_tuple)
s.AddTag(tag)
# maps from study_uid to instance of Study
study_dict = {}
# we're going to break the filenames up into 10 blocks and
# scan each block separately in order to be able to give
# proper feedback to the user, and also to give the user the
# opportunity to interrupt the scan
num_files = len(filenames)
# no filenames, we return an empty dict.
if num_files == 0:
return study_dict
num_files_per_block = 100
num_blocks = num_files / num_files_per_block
if num_blocks == 0:
num_blocks = 1
blocklen = num_files / num_blocks
blockmod = num_files % num_blocks
block_lens = [blocklen] * num_blocks
if blockmod > 0:
block_lens += [blockmod]
file_idx = 0
progress = 0.0
# setup progress dialog
dlg = wx.ProgressDialog("DICOMBrowser",
"Scanning DICOM data",
maximum = 100,
parent=self._view_frame,
style = wx.PD_CAN_ABORT
| wx.PD_APP_MODAL
| wx.PD_ELAPSED_TIME
| wx.PD_AUTO_HIDE
#| wx.PD_ESTIMATED_TIME
| wx.PD_REMAINING_TIME
)
keep_going = True
error_occurred = False
# and now the processing loop can start
for block_len in block_lens:
# scan the current block of files
try:
self._helper_scan_block(
s, filenames[file_idx:file_idx + block_len],
tag_to_symbol, study_dict)
except Exception:
# error during scan, we have to kill the dialog and
# then re-raise the error
dlg.Destroy()
raise
# update file_idx for the next block
file_idx += block_len
# update progress counter
progress = int(100 * file_idx / float(num_files))
# and tell the progress dialog about our progress
# by definition, progress will be 100 at the end: if you
# add all blocklens together, you have to get 1
(keep_going, skip) = dlg.Update(progress)
if not keep_going:
# user has clicked cancel so we zero the dictionary
study_dict = {}
# and stop the for loop
break
# dialog needs to be taken care of
dlg.Destroy()
# return all the scanned data
return study_dict
def _helper_scan_block(
self, s, filenames, tag_to_symbol, study_dict):
"""Scan list of filenames, fill study_dict. Used by _scan()
to scan list of filenames in blocks.
"""
# d.GetFilenames simply returns a tuple with all
# fully-qualified filenames that it finds.
ret = s.Scan(filenames)
if not ret:
print "scanner failed"
return
# s now contains a Mapping (std::map) from filenames to stuff
# calling s.GetMapping(full filename) returns a TagToValue
# which we convert for our own use with a PythonTagToValue
#pttv = gdcm.PythonTagToValue(mapping)
# what i want:
# a list of studies (indexed on study id): each study object
# contains metadata we want to list per study, plus a list of
# series belonging to that study.
for f in filenames:
mapping = s.GetMapping(f)
# with this we can iterate through all tags for this file
# let's store them all...
file_tags = {}
pttv = gdcm.PythonTagToValue(mapping)
pttv.Start()
while not pttv.IsAtEnd():
tag = pttv.GetCurrentTag() # gdcm::Tag
val = pttv.GetCurrentValue() # string
symbol = tag_to_symbol[(tag.GetGroup(), tag.GetElement())]
file_tags[symbol] = val
pttv.Next()
# take information from file_tags, stuff into all other
# structures...
# we need at least study and series UIDs to continue
if not ('study_uid' in file_tags and \
'series_uid' in file_tags):
continue
study_uid = file_tags['study_uid']
series_uid = file_tags['series_uid']
# create a new study if it doesn't exist yet
try:
study = study_dict[study_uid]
except KeyError:
study = Study()
study.uid = study_uid
study.description = file_tags.get(
'study_description', '')
study.date = file_tags.get(
'study_date', '')
study.patient_name = file_tags.get(
'patient_name', '')
study.patient_id = file_tags.get(
'patient_id', '')
study_dict[study_uid] = study
try:
series = study.series_dict[series_uid]
except KeyError:
series = Series()
series.uid = series_uid
# these should be the same over the whole series
series.description = \
file_tags.get('series_description', '')
series.modality = file_tags.get('modality', '')
series.rows = int(file_tags.get('rows', 0))
series.columns = int(file_tags.get('columns', 0))
study.series_dict[series_uid] = series
series.filenames.append(f)
try:
number_of_frames = int(file_tags['number_of_frames'])
except KeyError:
# means number_of_frames wasn't found
number_of_frames = 1
series.slices = series.slices + number_of_frames
study.slices = study.slices + number_of_frames
def _deserialise_study_dict(self, s_study_dict):
"""Given a serialised study_dict, as generated by
_serialise_study_dict, reconstruct a real study_dict and
return it.
"""
study_dict = {}
for study_uid, s_study in s_study_dict.items():
study = Study()
for a in STUDY_ATTRS:
setattr(study, a, s_study[a])
# explicitly put the uid back
study.uid = study_uid
s_series_dict = s_study['s_series_dict']
for series_uid, s_series in s_series_dict.items():
series = Series()
for a in SERIES_ATTRS:
setattr(series, a, s_series[a])
series.uid = series_uid
study.series_dict[series_uid] = series
study_dict[study_uid] = study
return study_dict
def _serialise_study_dict(self, study_dict):
"""Serialise complete study_dict (including all instances of
Study and of Series) into a simpler form that can be
successfully pickled.
Directly pickling the study_dict, then restoring a network and
trying to serialise again yields the infamous:
'Can't pickle X: it's not the same object as X' where X is
modules.viewers.DICOMBrowser.Study
"""
s_study_dict = {}
for study_uid, study in study_dict.items():
s_study = {}
for a in STUDY_ATTRS:
v = getattr(study, a)
s_study[a] = v
s_series_dict = {}
for series_uid, series in study.series_dict.items():
s_series = {}
for a in SERIES_ATTRS:
v = getattr(series, a)
s_series[a] = v
s_series_dict[series_uid] = s_series
s_study['s_series_dict'] = s_series_dict
s_study_dict[study_uid] = s_study
return s_study_dict
def _set_image_viewer_dummy_input(self):
ds = vtk.vtkImageGridSource()
self._image_viewer.SetInput(ds.GetOutput())
def _setup_image_viewer(self):
# FIXME: I'm planning to factor this out into a medical image
# viewing class, probably in the GDCM_KIT
# setup VTK viewer with dummy source (else it complains)
self._image_viewer = vtkgdcm.vtkImageColorViewer()
self._image_viewer.SetupInteractor(self._view_frame.image_pane.rwi)
self._set_image_viewer_dummy_input()
def setup_text_actor(x, y):
ta = vtk.vtkTextActor()
c = ta.GetPositionCoordinate()
c.SetCoordinateSystemToNormalizedDisplay()
c.SetValue(x,y)
p = ta.GetTextProperty()
p.SetFontFamilyToArial()
p.SetFontSize(14)
p.SetBold(0)
p.SetItalic(0)
p.SetShadow(0)
return ta
ren = self._image_viewer.GetRenderer()
# direction labels left and right #####
xl = self._image_viewer.xl_text_actor = setup_text_actor(0.01, 0.5)
ren.AddActor(xl)
xr = self._image_viewer.xr_text_actor = setup_text_actor(0.99, 0.5)
xr.GetTextProperty().SetJustificationToRight()
ren.AddActor(xr)
# direction labels top and bottom #####
# y coordinate ~ 0, bottom of normalized display
yb = self._image_viewer.yb_text_actor = setup_text_actor(
0.5, 0.01)
ren.AddActor(yb)
yt = self._image_viewer.yt_text_actor = setup_text_actor(
0.5, 0.99)
yt.GetTextProperty().SetVerticalJustificationToTop()
ren.AddActor(yt)
# labels upper-left #####
ul = self._image_viewer.ul_text_actor = \
setup_text_actor(0.01, 0.99)
ul.GetTextProperty().SetVerticalJustificationToTop()
ren.AddActor(ul)
# labels upper-right #####
ur = self._image_viewer.ur_text_actor = \
setup_text_actor(0.99, 0.99)
ur.GetTextProperty().SetVerticalJustificationToTop()
ur.GetTextProperty().SetJustificationToRight()
ren.AddActor(ur)
# labels bottom-right #####
br = self._image_viewer.br_text_actor = \
setup_text_actor(0.99, 0.01)
br.GetTextProperty().SetVerticalJustificationToBottom()
br.GetTextProperty().SetJustificationToRight()
ren.AddActor(br)
| Python |
# - make our own window control for colour-sequence bar
# - this should also have separate (?) line with HSV colour vertices
# - on this line, there should be vertical lines indicating the current
# position of all the opacity transfer function vertices
# - abstract floatcanvas-derived linear function editor into wx_kit
import os
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin,\
FileOpenDialogModuleMixin
import module_utils
from external import transfer_function_widget
import vtk
import wx
TF_LIBRARY = {
'CT Hip (bones+vasculature)' : [
(-1024.0, (0, 0, 0), 0),
(184.65573770491801, (255, 128, 128), 0.0),
(225.20534629404619, (255, 128, 128), 0.73857868020304562),
(304.8359659781288, (255, 128, 128), 0.0),
(377.70491803278696, (233, 231, 148), 0.0),
(379.48967193195631, (233, 231, 148), 1.0),
(3072.0, (255, 255, 255), 1)],
'CT Hip (test)' : [
(-1024.0, (0, 0, 0), 0),
(117.50819672131138, (255, 128, 128), 0.0),
(595.93442622950829, (255, 255, 255), 1.0),
(3072.0, (255, 255, 255), 1)],
'Panoramix (prototype)' : [
(-1024.0, (0, 0, 0), 0),
(136.33994334277622, (214, 115, 115), 0.0),
(159.5467422096317, (230, 99, 99), 0.24788732394366197),
(200.1586402266289, (255, 128, 128), 0.0),
(252.37393767705385, (206, 206, 61), 0.40000000000000002),
(287.18413597733706, (255, 128, 128), 0.0),
(403.21813031161469, (206, 61, 67), 0.13521126760563384),
(525.05382436260629, (255, 255, 255), 0.0),
(612.07932011331445, (255, 255, 255), 0.92957746478873238),
(3072.0, (255, 255, 255), 1)]
}
class TransferFunctionEditor(IntrospectModuleMixin, FileOpenDialogModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._volume_input = None
self._opacity_tf = vtk.vtkPiecewiseFunction()
self._colour_tf = vtk.vtkColorTransferFunction()
self._lut = vtk.vtkLookupTable()
# list of tuples, where each tuple (scalar_value, (r,g,b,a))
self._config.transfer_function = [
(0, (0,0,0), 0),
(255, (255,255,255), 1)
]
self._view_frame = None
self._create_view_frame()
self._bind_events()
self.view()
# all modules should toggle this once they have shown their
# stuff.
self.view_initialised = True
self.config_to_logic()
self.logic_to_config()
self.config_to_view()
def _bind_events(self):
def handler_blaat(event):
tf_widget = event.GetEventObject() # the tf_widget
ret = tf_widget.get_current_point_info()
if not ret is None:
val, col, opacity = ret
vf = self._view_frame
vf.colour_button.SetBackgroundColour(col)
vf.cur_scalar_text.SetValue('%.2f' % (val,))
vf.cur_col_text.SetValue(str(col))
vf.cur_opacity_text.SetValue('%.2f' % (opacity,))
vf = self._view_frame
tfw = vf.tf_widget
tfw.Bind(transfer_function_widget.EVT_CUR_PT_CHANGED,
handler_blaat)
def handler_colour_button(event):
coldialog = wx.ColourDialog(vf, tfw.colour_data)
if coldialog.ShowModal() == wx.ID_OK:
colour = coldialog.GetColourData().GetColour().Get()
tfw.colour_data = coldialog.GetColourData()
tfw.set_current_point_colour(colour)
vf.colour_button.Bind(wx.EVT_BUTTON, handler_colour_button)
def handler_delete_button(event):
tfw.delete_current_point()
vf.delete_button.Bind(wx.EVT_BUTTON, handler_delete_button)
def handler_auto_range_button(event):
try:
range = self._volume_input.GetScalarRange()
except AttributeError:
self._module_manager.log_error(
'Could not determine range from input. ' +
'Have you connected some input data and ' +
'has the network executed at least once?')
else:
vf = self._view_frame
vf.scalar_min_text.SetValue(str(range[0]))
vf.scalar_max_text.SetValue(str(range[1]))
vf.auto_range_button.Bind(wx.EVT_BUTTON,
handler_auto_range_button)
def handler_apply_range_button(event):
try:
min = float(vf.scalar_min_text.GetValue())
max = float(vf.scalar_max_text.GetValue())
except ValueError:
self._module_manager.log_error(
'Invalid scalar MIN / MAX.')
else:
tfw.set_min_max(min, max)
vf.apply_range_button.Bind(wx.EVT_BUTTON,
handler_apply_range_button)
def handler_load_preset_button(event):
key = vf.preset_choice.GetStringSelection()
preset_tf = TF_LIBRARY[key]
tfw.set_transfer_function(preset_tf)
vf.load_preset_button.Bind(wx.EVT_BUTTON,
handler_load_preset_button)
def handler_file_save_button(event):
filename = self.filename_browse(self._view_frame,
'Select DVTF filename to save to',
'DeVIDE Transfer Function (*.dvtf)|*.dvtf|All files (*)|*',
style=wx.SAVE)
if filename:
# if the user has NOT specified any fileextension, we
# add .dvtf. (on Win this gets added by the
# FileSelector automatically, on Linux it doesn't)
if os.path.splitext(filename)[1] == '':
filename = '%s.dvtf' % (filename,)
self._save_tf_to_file(filename)
vf.file_save_button.Bind(wx.EVT_BUTTON,
handler_file_save_button)
def handler_file_load_button(event):
filename = self.filename_browse(self._view_frame,
'Select DVTF filename to load',
'DeVIDE Transfer Function (*.dvtf)|*.dvtf|All files (*)|*',
style=wx.OPEN)
if filename:
self._load_tf_from_file(filename)
vf.file_load_button.Bind(wx.EVT_BUTTON,
handler_file_load_button)
# auto_range_button
def _create_view_frame(self):
import resources.python.tfeditorframe
reload(resources.python.tfeditorframe)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
resources.python.tfeditorframe.TFEditorFrame)
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.view_frame_panel,
{'Module (self)' : self})
# add the ECASH buttons
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.view_frame_panel)
# and customize the presets choice
vf = self._view_frame
keys = TF_LIBRARY.keys()
keys.sort()
vf.preset_choice.Clear()
for key in keys:
vf.preset_choice.Append(key)
vf.preset_choice.Select(0)
def close(self):
for i in range(len(self.get_input_descriptions())):
self.set_input(i, None)
self._view_frame.Destroy()
del self._view_frame
ModuleBase.close(self)
def get_input_descriptions(self):
return ('Optional input volume',)
def get_output_descriptions(self):
return ('VTK Opacity Transfer Function',
'VTK Colour Transfer Function',
'VTK Lookup Table')
def set_input(self, idx, input_stream):
self._volume_input = input_stream
def get_output(self, idx):
if idx == 0:
return self._opacity_tf
elif idx == 1:
return self._colour_tf
else:
return self._lut
def logic_to_config(self):
pass
def config_to_logic(self):
self._opacity_tf.RemoveAllPoints()
self._colour_tf.RemoveAllPoints()
for p in self._config.transfer_function:
self._opacity_tf.AddPoint(p[0], p[2])
r,g,b = [i / 255.0 for i in p[1]]
self._colour_tf.AddRGBPoint(
p[0],r,g,b)
lut_res = 1024
minmax = self._view_frame.tf_widget.get_min_max()
self._lut.SetTableRange(minmax)
self._lut.SetNumberOfTableValues(lut_res)
# lut_res - 1: lut_res points == lut_res-1 intervals
incr = (minmax[1] - minmax[0]) / float(lut_res - 1)
for i in range(lut_res):
v = minmax[0] + i * incr
rgb = self._colour_tf.GetColor(v)
o = self._opacity_tf.GetValue(v)
self._lut.SetTableValue(i, rgb + (o,))
def view_to_config(self):
self._config.transfer_function = \
self._view_frame.tf_widget.get_transfer_function()
def config_to_view(self):
vf = self._view_frame
tfw = vf.tf_widget
tfw.set_transfer_function(
self._config.transfer_function)
min,max = tfw.get_min_max()
vf.scalar_min_text.SetValue('%.1f' % (min,))
vf.scalar_max_text.SetValue('%.1f' % (max,))
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
def execute_module(self):
pass
def _load_tf_from_file(self, filename):
try:
loadf = file(filename, 'r')
tf = eval(loadf.read(), {"__builtins__": {}})
loadf.close()
except Exception, e:
self._module_manager.log_error_with_exception(
'Could not load transfer function: %s.' %
(str(e),))
else:
self._view_frame.tf_widget.set_transfer_function(
tf)
def _save_tf_to_file(self, filename):
tf = self._view_frame.tf_widget.get_transfer_function()
try:
savef = file(filename, 'w')
savef.write("# DeVIDE Transfer Function DVTF v1.0\n%s" % \
(str(tf),))
savef.close()
except Exception, e:
self._module_manager.log_error(
'Error saving transfer function: %s.' % (str(e),))
else:
self._module_manager.log_message(
'Saved %s.' % (filename,))
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import cStringIO
import vtk
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
import wx
# wxPython 2.8.8.1 wx.aui bugs severely on GTK. See:
# http://trac.wxwidgets.org/ticket/9716
# Until this is fixed, use this PyAUI to which I've added a
# wx.aui compatibility layer.
if wx.Platform == "__WXGTK__":
from external import PyAUI
wx.aui = PyAUI
else:
import wx.aui
# using Andrea Gavana's latest Python AUI:
#from external import aui
#wx.aui = aui
# this works fine on Windows. Have not been able to test on Linux
# whilst in Magdeburg.
import resources.python.comedi_frames
reload(resources.python.comedi_frames)
class CMIPane:
"""Class for anything that would like to populate the interface.
Each _create* method returns an instance of this class, populated
with the various required ivars.
"""
def __init__(self):
self.window = None
class CoMedIFrame(wx.Frame):
"""wx.Frame child class used by SkeletonAUIViewer for its
interface.
This is an AUI-managed window, so we create the top-level frame,
and then populate it with AUI panes.
"""
def __init__(self, parent, id=-1, title="", name=""):
wx.Frame.__init__(self, parent, id=id, title=title,
pos=wx.DefaultPosition, size=(1000,600), name=name)
self.menubar = wx.MenuBar()
self.SetMenuBar(self.menubar)
file_menu = wx.Menu()
self.id_file_open = wx.NewId()
file_menu.Append(self.id_file_open, "&Open\tCtrl-O",
"Open a file", wx.ITEM_NORMAL)
self.menubar.Append(file_menu, "&File")
###################################################################
camera_menu = wx.Menu()
self.id_camera_perspective = wx.NewId()
camera_menu.Append(self.id_camera_perspective, "&Perspective",
"Perspective projection mode", wx.ITEM_RADIO)
self.id_camera_parallel = wx.NewId()
camera_menu.Append(self.id_camera_parallel, "Pa&rallel",
"Parallel projection mode", wx.ITEM_RADIO)
camera_menu.AppendSeparator()
self.id_camera_xyzp = wx.NewId()
camera_menu.Append(self.id_camera_xyzp, "View XY from Z+",
"View XY plane face-on from Z+", wx.ITEM_NORMAL)
self.menubar.Append(camera_menu, "&Camera")
###################################################################
views_menu = wx.Menu()
self.id_views_synchronised = wx.NewId()
mi = views_menu.Append(self.id_views_synchronised, "&Synchronised",
"Toggle view synchronisation", wx.ITEM_CHECK)
mi.Check(True)
views_menu.AppendSeparator()
self.id_views_slice2 = wx.NewId()
mi = views_menu.Append(self.id_views_slice2, "Slice &2",
"Toggle slice 2", wx.ITEM_CHECK)
mi.Check(False)
self.id_views_slice3 = wx.NewId()
mi = views_menu.Append(self.id_views_slice3, "Slice &3",
"Toggle slice 3", wx.ITEM_CHECK)
mi.Check(False)
views_menu.AppendSeparator()
views_default_id = wx.NewId()
views_menu.Append(views_default_id, "&Default\tCtrl-0",
"Activate default view layout.", wx.ITEM_NORMAL)
views_max_image_id = wx.NewId()
views_menu.Append(views_max_image_id, "&Maximum image size\tCtrl-1",
"Activate maximum image view size layout.",
wx.ITEM_NORMAL)
self.menubar.Append(views_menu, "&Views")
adv_menu = wx.Menu()
self.id_adv_introspect = wx.NewId()
adv_menu.Append(self.id_adv_introspect, '&Introspect\tAlt-I',
'Introspect this CoMedI instance.', wx.ITEM_NORMAL)
self.menubar.Append(adv_menu, '&Advanced')
# tell FrameManager to manage this frame
self._mgr = wx.aui.AuiManager()
self._mgr.SetManagedWindow(self)
self.pane_controls = self._create_controls_pane()
self._mgr.AddPane(self.pane_controls.window, wx.aui.AuiPaneInfo().
Name("controls").Caption("Controls").
Left().Layer(2).
BestSize(wx.Size(500,800)).
CloseButton(False).MaximizeButton(True))
self.rwi_pane_data1 = self._create_rwi_pane()
self._mgr.AddPane(self.rwi_pane_data1.window, wx.aui.AuiPaneInfo().
Name("data1 rwi").Caption("Data 1").
Left().Position(0).Layer(1).
BestSize(wx.Size(500,400)).
CloseButton(False).MaximizeButton(True))
self.rwi_pane_data2 = self._create_rwi_pane()
self._mgr.AddPane(self.rwi_pane_data2.window, wx.aui.AuiPaneInfo().
Name("data2 rwi").Caption("Data 2").
Left().Position(1).Layer(1).
BestSize(wx.Size(500,400)).
CloseButton(False).MaximizeButton(True))
self.rwi_pane_compvis = self._create_rwi_pane()
self._mgr.AddPane(self.rwi_pane_compvis.window, wx.aui.AuiPaneInfo().
Name("compvis1 rwi").Caption("Main CompVis").
Center().
BestSize(wx.Size(800,800)).
CloseButton(False).MaximizeButton(True))
self.SetMinSize(wx.Size(400, 300))
# first we save this default perspective with all panes
# visible
self._perspectives = {}
self._perspectives['default'] = self._mgr.SavePerspective()
# then we hide all of the panes except the renderer
self._mgr.GetPane("series").Hide()
self._mgr.GetPane("files").Hide()
self._mgr.GetPane("meta").Hide()
# save the perspective again
self._perspectives['max_image'] = self._mgr.SavePerspective()
# and put back the default perspective / view
self._mgr.LoadPerspective(self._perspectives['default'])
# finally tell the AUI manager to do everything that we've
# asked
self._mgr.Update()
# we bind the views events here, because the functionality is
# completely encapsulated in the frame and does not need to
# round-trip to the DICOMBrowser main module.
self.Bind(wx.EVT_MENU, self._handler_default_view,
id=views_default_id)
self.Bind(wx.EVT_MENU, self._handler_max_image_view,
id=views_max_image_id)
def close(self):
for rwi_pane in self.get_rwi_panes():
self._close_rwi_pane(rwi_pane)
self.Destroy()
def _create_files_pane(self):
sl = wx.ListCtrl(self, -1,
style=wx.LC_REPORT)
sl.InsertColumn(0, "Full name")
# we'll autosize this column later
sl.SetColumnWidth(0, 300)
#sl.InsertColumn(SeriesColumns.modality, "Modality")
self.files_lc = sl
return sl
def _create_controls_pane(self):
f = resources.python.comedi_frames.CoMedIControlsFrame(self)
# reparent the panel to us
panel = f.main_panel
panel.Reparent(self)
# still need fpf.* to bind everything
# but we can destroy fpf (everything has been reparented)
f.Destroy()
panel.cursor_text = f.cursor_text
panel.data1_landmarks_olv = f.data1_landmarks_olv
panel.data2_landmarks_olv = f.data2_landmarks_olv
panel.lm_add_button = f.lm_add_button
panel.compare_button = f.compare_button
panel.update_compvis_button = f.update_compvis_button
panel.match_mode_notebook = f.match_mode_notebook
panel.comparison_mode_notebook = f.comparison_mode_notebook
panel.cm_checkerboard_divx = f.cm_checkerboard_divx
panel.cm_checkerboard_divy = f.cm_checkerboard_divy
panel.cm_checkerboard_divz = f.cm_checkerboard_divz
# ok, so this is easier and cleaner.
cm_diff_controls = [
'cm_diff_conf_thresh_txt',
'cm_diff_focus_target_choice',
'cm_diff_context_target_choice',
'cm_diff_cmap_choice',
'cm_diff_range0_text',
'cm_diff_range1_text',
'cm_diff_autorange_button'
]
for ivar in cm_diff_controls:
setattr(panel, ivar, getattr(f, ivar))
cmi_pane = CMIPane()
cmi_pane.window = panel
return cmi_pane
def _create_rwi_pane(self):
"""Return pane with renderer and buttons.
"""
panel = wx.Panel(self, -1)
rwi = wxVTKRenderWindowInteractor(panel, -1, (300,300))
if False:
self.button1 = wx.Button(panel, -1, "Add Superquadric")
self.button2 = wx.Button(panel, -1, "Reset Camera")
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add(self.button1)
button_sizer.Add(self.button2)
sizer1 = wx.BoxSizer(wx.VERTICAL)
sizer1.Add(rwi, 1, wx.EXPAND|wx.BOTTOM, 7)
sizer1.Add(button_sizer)
tl_sizer = wx.BoxSizer(wx.VERTICAL)
tl_sizer.Add(rwi, 1, wx.ALL|wx.EXPAND, 7)
panel.SetSizer(tl_sizer)
tl_sizer.Fit(panel)
ren = vtk.vtkRenderer()
ren.SetBackground(0.5,0.5,0.5)
ren.SetBackground2(1,1,1)
ren.SetGradientBackground(1)
rwi.GetRenderWindow().AddRenderer(ren)
cmi_pane = CMIPane()
cmi_pane.window = panel
cmi_pane.renderer = ren
cmi_pane.rwi = rwi
return cmi_pane
def _close_rwi_pane(self, cmi_pane):
cmi_pane.renderer.RemoveAllViewProps()
cmi_pane.rwi.GetRenderWindow().Finalize()
cmi_pane.rwi.SetRenderWindow(None)
del cmi_pane.rwi
del cmi_pane.renderer # perhaps not...
def _create_meta_pane(self):
ml = wx.ListCtrl(self, -1,
style=wx.LC_REPORT |
wx.LC_HRULES | wx.LC_VRULES |
wx.LC_SINGLE_SEL)
ml.InsertColumn(0, "Key")
ml.SetColumnWidth(0, 70)
ml.InsertColumn(1, "Value")
ml.SetColumnWidth(1, 70)
self.meta_lc = ml
return ml
def _create_series_pane(self):
sl = wx.ListCtrl(self, -1,
style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_SINGLE_SEL,
size=(600,120))
sl.InsertColumn(0, "Description")
sl.SetColumnWidth(1, 170)
sl.InsertColumn(2, "Modality")
sl.InsertColumn(3, "# Images")
sl.InsertColumn(4, "Size")
self.series_lc = sl
return sl
def get_rwi_panes(self):
return [self.rwi_pane_data1,
self.rwi_pane_data2,
self.rwi_pane_compvis]
def get_rwis(self):
return [rwi_pane.rwi for rwi_pane in self.get_rwi_panes()]
def render_all(self):
"""Update embedded RWI, i.e. update the image.
"""
for rwi in self.get_rwis():
rwi.Render()
def set_cam_parallel(self):
"""Set check next to "parallel" menu item.
"""
mi = self.menubar.FindItemById(self.id_camera_parallel)
mi.Check(True)
def set_cam_perspective(self):
"""Set check next to "perspective" menu item.
"""
mi = self.menubar.FindItemById(self.id_camera_perspective)
mi.Check(True)
def _handler_default_view(self, event):
"""Event handler for when the user selects View | Default from
the main menu.
"""
self._mgr.LoadPerspective(
self._perspectives['default'])
def _handler_max_image_view(self, event):
"""Event handler for when the user selects View | Max Image
from the main menu.
"""
self._mgr.LoadPerspective(
self._perspectives['max_image'])
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
from module_kits.vtk_kit.utils import DVOrientationWidget
import operator
import vtk
import wx
class SyncSliceViewers:
"""Class to link a number of CMSliceViewer instances w.r.t.
camera.
FIXME: consider adding option to block certain slice viewers from
participation. Is this better than just removing them?
"""
def __init__(self):
# store all slice viewer instances that are being synced
self.slice_viewers = []
self.observer_tags = {}
# if set to False, no syncing is done.
# user is responsible for doing the initial sync with sync_all
# after this variable is toggled from False to True
self.sync = True
def add_slice_viewer(self, slice_viewer):
if slice_viewer in self.slice_viewers:
return
# we'll use this to store all observer tags for this
# slice_viewer
t = self.observer_tags[slice_viewer] = {}
istyle = slice_viewer.rwi.GetInteractorStyle()
# the following two observers are workarounds for a bug in VTK
# the interactorstyle does NOT invoke an InteractionEvent at
# mousewheel, so we make sure it does in our workaround
# observers.
t['istyle MouseWheelForwardEvent'] = \
istyle.AddObserver('MouseWheelForwardEvent',
self._observer_mousewheel_forward)
t['istyle MouseWheelBackwardEvent'] = \
istyle.AddObserver('MouseWheelBackwardEvent',
self._observer_mousewheel_backward)
# this one only gets called for camera interaction (of course)
t['istyle InteractionEvent'] = \
istyle.AddObserver('InteractionEvent',
lambda o,e: self._observer_camera(slice_viewer))
# this gets call for all interaction with the slice
# (cursoring, slice pushing, perhaps WL)
for idx in range(3):
# note the i=idx in the lambda expression. This is
# because that gets evaluated at define time, whilst the
# body of the lambda expression gets evaluated at
# call-time
t['ipw%d InteractionEvent' % (idx,)] = \
slice_viewer.ipws[idx].AddObserver('InteractionEvent',
lambda o,e,i=idx: self._observer_ipw(slice_viewer, i))
t['ipw%d WindowLevelEvent' % (idx,)] = \
slice_viewer.ipws[idx].AddObserver('WindowLevelEvent',
lambda o,e,i=idx: self._observer_window_level(slice_viewer,i))
self.slice_viewers.append(slice_viewer)
def close(self):
for sv in self.slice_viewers:
self.remove_slice_viewer(sv)
def _observer_camera(self, sv):
"""This observer will keep the cameras of all the
participating slice viewers synched.
It's only called when the camera is moved.
"""
if not self.sync:
return
cc = self.sync_cameras(sv)
[sv.render() for sv in cc]
def _observer_mousewheel_forward(self, vtk_o, vtk_e):
vtk_o.OnMouseWheelForward()
vtk_o.InvokeEvent('InteractionEvent')
def _observer_mousewheel_backward(self, vtk_o, vtk_e):
vtk_o.OnMouseWheelBackward()
vtk_o.InvokeEvent('InteractionEvent')
def _observer_ipw(self, slice_viewer, idx=0):
"""This is called whenever the user does ANYTHING with the
IPW.
"""
if not self.sync:
return
cc = self.sync_ipws(slice_viewer, idx)
[sv.render() for sv in cc]
def _observer_window_level(self, slice_viewer, idx=0):
"""This is called whenever the window/level is changed. We
don't have to render, because the SetWindowLevel() call does
that already.
"""
if not self.sync:
return
self.sync_window_level(slice_viewer, idx)
def remove_slice_viewer(self, slice_viewer):
if slice_viewer in self.slice_viewers:
# first remove all observers that we might have added
t = self.observer_tags[slice_viewer]
istyle = slice_viewer.rwi.GetInteractorStyle()
istyle.RemoveObserver(
t['istyle InteractionEvent'])
istyle.RemoveObserver(
t['istyle MouseWheelForwardEvent'])
istyle.RemoveObserver(
t['istyle MouseWheelBackwardEvent'])
for idx in range(3):
ipw = slice_viewer.ipws[idx]
ipw.RemoveObserver(
t['ipw%d InteractionEvent' % (idx,)])
ipw.RemoveObserver(
t['ipw%d WindowLevelEvent' % (idx,)])
# then delete our record of these observer tags
del self.observer_tags[slice_viewer]
# then delete our record of the slice_viewer altogether
idx = self.slice_viewers.index(slice_viewer)
del self.slice_viewers[idx]
def sync_cameras(self, sv, dest_svs=None):
"""Sync all cameras to that of sv.
Returns a list of changed SVs (so that you know which ones to
render).
"""
cam = sv.renderer.GetActiveCamera()
pos = cam.GetPosition()
fp = cam.GetFocalPoint()
vu = cam.GetViewUp()
ps = cam.GetParallelScale()
if dest_svs is None:
dest_svs = self.slice_viewers
changed_svs = []
for other_sv in dest_svs:
if not other_sv is sv:
other_ren = other_sv.renderer
other_cam = other_ren.GetActiveCamera()
other_cam.SetPosition(pos)
other_cam.SetFocalPoint(fp)
other_cam.SetViewUp(vu)
# you need this too, else the parallel mode does not
# synchronise.
other_cam.SetParallelScale(ps)
other_ren.UpdateLightsGeometryToFollowCamera()
other_ren.ResetCameraClippingRange()
changed_svs.append(other_sv)
return changed_svs
def sync_ipws(self, sv, idx=0, dest_svs=None):
"""Sync all slice positions to that of sv.
Returns a list of cahnged SVs so that you know on which to
call render.
"""
ipw = sv.ipws[idx]
o,p1,p2 = ipw.GetOrigin(), \
ipw.GetPoint1(), ipw.GetPoint2()
if dest_svs is None:
dest_svs = self.slice_viewers
changed_svs = []
for other_sv in dest_svs:
if other_sv is not sv:
other_ipw = other_sv.ipws[idx]
# we only synchronise slice position if it's actually
# changed.
if o != other_ipw.GetOrigin() or \
p1 != other_ipw.GetPoint1() or \
p2 != other_ipw.GetPoint2():
other_ipw.SetOrigin(o)
other_ipw.SetPoint1(p1)
other_ipw.SetPoint2(p2)
other_ipw.UpdatePlacement()
changed_svs.append(other_sv)
return changed_svs
def sync_window_level(self, sv, idx=0, dest_svs=None):
"""Sync all window level settings with that of SV.
Returns list of changed SVs: due to the SetWindowLevel call,
these have already been rendered!
"""
ipw = sv.ipws[idx]
w,l = ipw.GetWindow(), ipw.GetLevel()
if dest_svs is None:
dest_svs = self.slice_viewers
changed_svs = []
for other_sv in dest_svs:
if other_sv is not sv:
other_ipw = other_sv.ipws[idx]
if w != other_ipw.GetWindow() or \
l != other_ipw.GetLevel():
other_ipw.SetWindowLevel(w,l,0)
changed_svs.append(other_sv)
return changed_svs
def sync_all(self, sv, dest_svs=None):
"""Convenience function that performs all syncing possible of
dest_svs to sv. It also take care of making only the
necessary render calls.
"""
# FIXME: take into account all other slices too.
c1 = set(self.sync_cameras(sv, dest_svs))
c2 = set(self.sync_ipws(sv, 0, dest_svs))
c3 = set(self.sync_window_level(sv, 0, dest_svs))
# we only need to call render on SVs that are in c1 or c2, but
# NOT in c3, because WindowLevel syncing already does a
# render. Use set operations for this:
c4 = (c1 | c2) - c3
[isv.render() for isv in c4]
###########################################################################
class CMSliceViewer:
"""Simple class for enabling 1 or 3 ortho slices in a 3D scene.
"""
def __init__(self, rwi, renderer):
self.rwi = rwi
self.renderer = renderer
istyle = vtk.vtkInteractorStyleTrackballCamera()
rwi.SetInteractorStyle(istyle)
# we unbind the existing mousewheel handler so it doesn't
# interfere
rwi.Unbind(wx.EVT_MOUSEWHEEL)
rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel)
self.ipws = [vtk.vtkImagePlaneWidget() for _ in range(3)]
lut = self.ipws[0].GetLookupTable()
for ipw in self.ipws:
ipw.SetInteractor(rwi)
ipw.SetLookupTable(lut)
# we only set the picker on the visible IPW, else the
# invisible IPWs block picking!
self.picker = vtk.vtkCellPicker()
self.picker.SetTolerance(0.005)
self.ipws[0].SetPicker(self.picker)
self.outline_source = vtk.vtkOutlineCornerFilter()
m = vtk.vtkPolyDataMapper()
m.SetInput(self.outline_source.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
a.PickableOff()
self.outline_actor = a
self.dv_orientation_widget = DVOrientationWidget(rwi)
# this can be used by clients to store the current world
# position
self.current_world_pos = (0,0,0)
self.current_index_pos = (0,0,0)
def close(self):
self.set_input(None)
self.dv_orientation_widget.close()
def activate_slice(self, idx):
if idx in [1,2]:
self.ipws[idx].SetEnabled(1)
self.ipws[idx].SetPicker(self.picker)
def deactivate_slice(self, idx):
if idx in [1,2]:
self.ipws[idx].SetEnabled(0)
self.ipws[idx].SetPicker(None)
def get_input(self):
return self.ipws[0].GetInput()
def get_world_pos(self, image_pos):
"""Given image coordinates, return the corresponding world
position.
"""
idata = self.get_input()
if not idata:
return None
ispacing = idata.GetSpacing()
iorigin = idata.GetOrigin()
# calculate real coords
world = map(operator.add, iorigin,
map(operator.mul, ispacing, image_pos[0:3]))
return world
def set_perspective(self):
cam = self.renderer.GetActiveCamera()
cam.ParallelProjectionOff()
def set_parallel(self):
cam = self.renderer.GetActiveCamera()
cam.ParallelProjectionOn()
def _handler_mousewheel(self, event):
# event.GetWheelRotation() is + or - 120 depending on
# direction of turning.
if event.ControlDown():
delta = 10
elif event.ShiftDown():
delta = 1
else:
# if user is NOT doing shift / control, we pass on to the
# default handling which will give control to the VTK
# mousewheel handlers.
self.rwi.OnMouseWheel(event)
return
if event.GetWheelRotation() > 0:
self._ipw1_delta_slice(+delta)
else:
self._ipw1_delta_slice(-delta)
self.render()
self.ipws[0].InvokeEvent('InteractionEvent')
def _ipw1_delta_slice(self, delta):
"""Move to the delta slices fw/bw, IF the IPW is currently
aligned with one of the axes.
"""
ipw = self.ipws[0]
if ipw.GetPlaneOrientation() < 3:
ci = ipw.GetSliceIndex()
ipw.SetSliceIndex(ci + delta)
def render(self):
self.rwi.GetRenderWindow().Render()
def reset_camera(self):
self.renderer.ResetCamera()
def reset_to_default_view(self, view_index):
"""
@param view_index 2 for XY
"""
if view_index == 2:
cam = self.renderer.GetActiveCamera()
# then make sure it's up is the right way
cam.SetViewUp(0,1,0)
# just set the X,Y of the camera equal to the X,Y of the
# focal point.
fp = cam.GetFocalPoint()
cp = cam.GetPosition()
if cp[2] < fp[2]:
z = fp[2] + (fp[2] - cp[2])
else:
z = cp[2]
cam.SetPosition(fp[0], fp[1], z)
# first reset the camera
self.renderer.ResetCamera()
self.render()
def set_input(self, input):
ipw = self.ipws[0]
if input == ipw.GetInput():
return
if input is None:
# remove outline actor, else this will cause errors when
# we disable the IPWs (they call a render!)
self.renderer.RemoveViewProp(self.outline_actor)
self.outline_source.SetInput(None)
self.dv_orientation_widget.set_input(None)
for ipw in self.ipws:
# argh, this disable causes a render
ipw.SetEnabled(0)
ipw.SetInput(None)
else:
self.outline_source.SetInput(input)
self.renderer.AddViewProp(self.outline_actor)
orientations = [2, 0, 1]
active = [1, 0, 0]
for i, ipw in enumerate(self.ipws):
ipw.SetInput(input)
ipw.SetPlaneOrientation(orientations[i]) # axial
ipw.SetSliceIndex(0)
ipw.SetEnabled(active[i])
self.dv_orientation_widget.set_input(input)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
# skeleton of an AUI-based viewer module
# copy and modify for your own purposes.
# set to False for 3D viewer, True for 2D image viewer
IMAGE_VIEWER = True
# import the frame, i.e. the wx window containing everything
import SkeletonAUIViewerFrame
# and do a reload, so that the GUI is also updated at reloads of this
# module.
reload(SkeletonAUIViewerFrame)
# from module_kits.misc_kit import misc_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import os
import sys
import traceback
import vtk
import wx
class SkeletonAUIViewer(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Standard constructor. All DeVIDE modules have these, we do
the required setup actions.
"""
# we record the setting here, in case the user changes it
# during the lifetime of this model, leading to different
# states at init and shutdown.
self.IMAGE_VIEWER = IMAGE_VIEWER
ModuleBase.__init__(self, module_manager)
# create the view frame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
SkeletonAUIViewerFrame.SkeletonAUIViewerFrame)
# change the title to something more spectacular
self._view_frame.SetTitle('Skeleton AUI Viewer')
# create the necessary VTK objects: we only need a renderer,
# the RenderWindowInteractor in the view_frame has the rest.
self.ren = vtk.vtkRenderer()
self.ren.SetBackground(0.5,0.5,0.5)
self._view_frame.rwi.GetRenderWindow().AddRenderer(self.ren)
# hook up all event handlers
self._bind_events()
# anything you stuff into self._config will be saved
self._config.my_string = 'la la'
# make our window appear (this is a viewer after all)
self.view()
# all modules should toggle this once they have shown their
# views.
self.view_initialised = True
# apply config information to underlying logic
self.sync_module_logic_with_config()
# then bring it all the way up again to the view
self.sync_module_view_with_logic()
# the self.timer bits demonstrate how to use a timer to trigger some event
# every few milliseconds. this can for example be used to poll a
# tracking device.
# to see this in action in this example, do the following:
# 1. instantiate the SkeletonAUIViewer
# 2. click on "add superquadric" a few times
# 3. click on "reset camera" so that they are all in view
# 4. click on "start timer event" and see them rotate while you can do
# other things!
self.timer = None
def close(self):
"""Clean-up method called on all DeVIDE modules when they are
deleted.
"""
# we have to take care of de-initialising the timer as well
if self.timer:
self.timer.Stop()
del self.timer
# with this complicated de-init, we make sure that VTK is
# properly taken care of
self.ren.RemoveAllViewProps()
# this finalize makes sure we don't get any strange X
# errors when we kill the module.
self._view_frame.rwi.GetRenderWindow().Finalize()
self._view_frame.rwi.SetRenderWindow(None)
del self._view_frame.rwi
# done with VTK de-init
# now take care of the wx window
self._view_frame.close()
# then shutdown our introspection mixin
IntrospectModuleMixin.close(self)
def get_input_descriptions(self):
# define this as a tuple of input descriptions if you want to
# take input data e.g. return ('vtkPolyData', 'my kind of
# data')
return ()
def get_output_descriptions(self):
# define this as a tuple of output descriptions if you want to
# generate output data.
return ()
def set_input(self, idx, input_stream):
# this gets called right before you get executed. take the
# input_stream and store it so that it's available during
# execute_module()
pass
def get_output(self, idx):
# this can get called at any time when a consumer module wants
# you output data.
pass
def execute_module(self):
# when it's you turn to execute as part of a network
# execution, this gets called.
pass
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def config_to_view(self):
pass
def view_to_config(self):
pass
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# because we have an RWI involved, we have to do this
# SafeYield, so that the window does actually appear before we
# call the render. If we don't do this, we get an initial
# empty renderwindow.
wx.SafeYield()
self.render()
def add_superquadric(self):
"""Add a new superquadric at a random position.
This is called by the event handler for the 'Add Superquadric'
button.
"""
import random
# let's add a superquadric actor to the renderer
sqs = vtk.vtkSuperquadricSource()
sqs.ToroidalOn()
sqs.SetSize(0.1) # default is 0.5
m = vtk.vtkPolyDataMapper()
m.SetInput(sqs.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
pos = [random.random() for _ in range(3)]
a.SetPosition(pos)
a.GetProperty().SetColor([random.random() for _ in range(3)])
self.ren.AddActor(a)
self.render()
# add string to files listcontrol showing where the
# superquadric was placed.
self._view_frame.files_lc.InsertStringItem(
sys.maxint, 'Position (%.2f, %.2f, %.2f)' % tuple(pos))
def _bind_events(self):
"""Bind wx events to Python callable object event handlers.
"""
vf = self._view_frame
vf.Bind(wx.EVT_MENU, self._handler_file_open,
id = vf.id_file_open)
self._view_frame.button1.Bind(wx.EVT_BUTTON,
self._handler_button1)
self._view_frame.button2.Bind(wx.EVT_BUTTON,
self._handler_button2)
self._view_frame.button3.Bind(wx.EVT_BUTTON,
self._handler_button3)
def _handler_button1(self, event):
print "button1 pressed"
self.add_superquadric()
def _handler_button2(self, event):
print "button2 pressed"
self.ren.ResetCamera()
self.render()
def _handler_button3(self, event):
print "button3 pressed"
if not self.timer:
print "installing timer event"
# construct timer, associate it with the main view_frame
self.timer = wx.Timer(self._view_frame)
# then make sure we catch view_frame's EVT_TIMER events
self._view_frame.Bind(wx.EVT_TIMER, self._handler_timer, self.timer)
self.timer.Start(10, oneShot=False) # every 100ms
self._view_frame.button3.SetLabel("Stop Timer Event")
else:
print "uninstalling timer event"
self.timer.Stop()
self.timer = None
self._view_frame.button3.SetLabel("Start Timer Event")
def _handler_timer(self, event):
# at every timer event, rotate camera
self.ren.GetActiveCamera().Azimuth(5)
self.render()
def _handler_file_open(self, event):
print "could have opened file now"
def render(self):
"""Method that calls Render() on the embedded RenderWindow.
Use this after having made changes to the scene.
"""
self._view_frame.render()
| Python |
import vtk
import wx
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
import external.PyAUI as PyAUI
from resources.python import measure2d_panels
reload(measure2d_panels)
class Measure2DFrame(wx.Frame):
def __init__(self, parent, id=-1, title="", pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE |
wx.SUNKEN_BORDER |
wx.CLIP_CHILDREN, name="frame"):
wx.Frame.__init__(self, parent, id, title, pos, size, style, name)
# tell FrameManager to manage this frame
self._mgr = PyAUI.FrameManager()
self._mgr.SetFrame(self)
self._make_menu()
# statusbar
self.statusbar = self.CreateStatusBar(2, wx.ST_SIZEGRIP)
self.statusbar.SetStatusWidths([-2, -3])
self.statusbar.SetStatusText("Ready", 0)
self.statusbar.SetStatusText("DeVIDE Measure2D", 1)
self.SetMinSize(wx.Size(400, 300))
self.SetSize(wx.Size(400, 300))
# could make toolbars here
# now we need to add panes
self._rwi_panel = self._create_rwi_panel()
self._mgr.AddPane(self._rwi_panel,
PyAUI.PaneInfo().Name('rwi').
Caption('Image View').Center().
MinSize(self._rwi_panel.GetSize()))
self._image_control_panel = self._create_image_control_panel()
self._mgr.AddPane(self._image_control_panel,
PyAUI.PaneInfo().Name('image_control').
Caption('Controls').Bottom().
MinSize(self._image_control_panel.GetSize()))
self._measurement_panel = self._create_measurement_panel()
self._mgr.AddPane(self._measurement_panel,
PyAUI.PaneInfo().Name('measurement').
Caption('Measurements').Bottom().
MinSize(self._measurement_panel.GetSize()))
# post-pane setup
self._mgr.Update()
self.perspective_default = self._mgr.SavePerspective()
# these come from the demo
self.Bind(wx.EVT_ERASE_BACKGROUND, self.OnEraseBackground)
self.Bind(wx.EVT_SIZE, self.OnSize)
#self.Bind(wx.EVT_CLOSE, self.OnClose)
# even although we disable the close button, when a window floats
# it gets a close button back, so we have to make sure that when
# the user activates that the windows is merely hidden
self.Bind(PyAUI.EVT_AUI_PANEBUTTON, self.OnPaneButton)
wx.EVT_MENU(self, self.window_default_view_id,
lambda e: self._mgr.LoadPerspective(
self.perspective_default) and self._mgr.Update())
def close(self):
# do the careful thing with the threedRWI and all
self.Destroy()
def _create_rwi_panel(self):
#rwi_panel = wx.Panel(self, -1)
self._rwi = wxVTKRenderWindowInteractor(self, -1, size=(300,100))
#sizer = wx.BoxSizer(wx.VERTICAL)
#sizer.Add(self._rwi, 1, wx.EXPAND | wx.ALL, 4)
#rwi_panel.SetAutoLayout(True)
#rwi_panel.SetSizer(sizer)
#rwi_panel.GetSizer().Fit(rwi_panel)
#rwi_panel.GetSizer().SetSizeHints(rwi_panel)
#return rwi_panel
return self._rwi
def _create_image_control_panel(self):
panel = wx.Panel(self, -1)
#wx.Label(panel, -1, "")
panel.slider = wx.Slider(panel, -1, 0, 0, 64, style=wx.SL_LABELS)
slider_box = wx.BoxSizer(wx.HORIZONTAL)
slider_box.Add(panel.slider, 1, wx.ALL)
tl_sizer = wx.BoxSizer(wx.VERTICAL)
tl_sizer.Add(slider_box, 0, wx.EXPAND, 4)
panel.SetAutoLayout(True)
panel.SetSizer(tl_sizer)
panel.GetSizer().Fit(panel)
panel.GetSizer().SetSizeHints(panel)
return panel
def _handler_grid_range_select(self, event):
"""This event handler is a fix for the fact that the row
selection in the wxGrid is deliberately broken. It's also
used to activate and deactivate relevant menubar items.
Whenever a user clicks on a cell, the grid SHOWS its row
to be selected, but GetSelectedRows() doesn't think so.
This event handler will travel through the Selected Blocks
and make sure the correct rows are actually selected.
Strangely enough, this event always gets called, but the
selection is empty when the user has EXPLICITLY selected
rows. This is not a problem, as then the GetSelectedRows()
does return the correct information.
"""
g = event.GetEventObject()
# both of these are lists of (row, column) tuples
tl = g.GetSelectionBlockTopLeft()
br = g.GetSelectionBlockBottomRight()
# this means that the user has most probably clicked on the little
# block at the top-left corner of the grid... in this case,
# SelectRow has no frikking effect (up to wxPython 2.4.2.4) so we
# detect this situation and clear the selection (we're going to be
# selecting the whole grid in anycase.
if tl == [(0,0)] and br == [(g.GetNumberRows() - 1,
g.GetNumberCols() - 1)]:
g.ClearSelection()
for (tlrow, tlcolumn), (brrow, brcolumn) in zip(tl, br):
for row in range(tlrow,brrow + 1):
g.SelectRow(row, True)
def _create_measurement_panel(self):
# drop-down box with type, name, create button
# grid / list with names and measured data
# also delete button to get rid of things we don't want
# start nasty trick: load wxGlade created frame
mpf = measure2d_panels.MeasurementPanelFrame
self.dummy_measurement_frame = mpf(self, id=-1)
# take and reparent the panel we want
dmf = self.dummy_measurement_frame
panel = dmf.panel
panel.Reparent(self)
panel.create_button = dmf.create_button
panel.measurement_grid = dmf.measurement_grid
panel.name_cb = dmf.name_cb
panel.rename_button = dmf.rename_button
panel.delete_button = dmf.delete_button
panel.enable_button = dmf.enable_button
panel.disable_button = dmf.disable_button
# need this handler to fix brain-dead selection handling
panel.measurement_grid.Bind(wx.grid.EVT_GRID_RANGE_SELECT,
self._handler_grid_range_select)
# destroy wxGlade created frame
dmf.Destroy()
return panel
def _make_menu(self):
# Menu Bar
self.menubar = wx.MenuBar()
self.SetMenuBar(self.menubar)
self.fileNewId = wx.NewId()
self.fileOpenId = wx.NewId()
file_menu = wx.Menu()
file_menu.Append(self.fileNewId, "&New\tCtrl-N",
"Create new network.", wx.ITEM_NORMAL)
file_menu.Append(self.fileOpenId, "&Open\tCtrl-O",
"Open and load existing network.", wx.ITEM_NORMAL)
self.menubar.Append(file_menu, "&File")
window_menu = wx.Menu()
self.window_default_view_id = wx.NewId()
window_menu.Append(
self.window_default_view_id, "Restore &default view",
"Restore default perspective / window configuration.",
wx.ITEM_NORMAL)
self.menubar.Append(window_menu, "&Window")
def OnEraseBackground(self, event):
# from PyAUI demo
event.Skip()
def OnPaneButton(self, event):
event.GetPane().Hide()
def OnSize(self, event):
# from PyAUI demo
event.Skip()
| Python |
from external import wxPyPlot
import gen_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
try:
import Numeric
except:
import numarray as Numeric
import vtk
import wx
class histogram1D(IntrospectModuleMixin, ModuleBase):
"""Calculates and shows 1D histogram (occurrences over value) of its
input data.
$Revision: 1.3 $
"""
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageAccumulate = vtk.vtkImageAccumulate()
module_utils.setup_vtk_object_progress(self, self._imageAccumulate,
'Calculating histogram')
self._viewFrame = None
self._createViewFrame()
self._bindEvents()
self._config.numberOfBins = 256
self._config.minValue = 0.0
self._config.maxValue = 256.0
self.config_to_logic()
self.logic_to_config()
self.config_to_view()
self.view()
def close(self):
for i in range(len(self.get_input_descriptions())):
self.set_input(i, None)
self._viewFrame.Destroy()
del self._viewFrame
del self._imageAccumulate
ModuleBase.close(self)
def get_input_descriptions(self):
return ('VTK Image Data',)
def set_input(self, idx, inputStream):
self._imageAccumulate.SetInput(inputStream)
def get_output_descriptions(self):
return ()
def logic_to_config(self):
# for now, we work on the first component (of a maximum of three)
# we could make this configurable
minValue = self._imageAccumulate.GetComponentOrigin()[0]
cs = self._imageAccumulate.GetComponentSpacing()
ce = self._imageAccumulate.GetComponentExtent()
numberOfBins = ce[1] - ce[0] + 1
# again we use nob - 1 so that maxValue is also part of a bin
maxValue = minValue + (numberOfBins-1) * cs[0]
self._config.numberOfBins = numberOfBins
self._config.minValue = minValue
self._config.maxValue = maxValue
def config_to_logic(self):
co = list(self._imageAccumulate.GetComponentOrigin())
co[0] = self._config.minValue
self._imageAccumulate.SetComponentOrigin(co)
ce = list(self._imageAccumulate.GetComponentExtent())
ce[0] = 0
ce[1] = self._config.numberOfBins - 1
self._imageAccumulate.SetComponentExtent(ce)
cs = list(self._imageAccumulate.GetComponentSpacing())
# we divide by nob - 1 because we want maxValue to fall in the
# last bin...
cs[0] = (self._config.maxValue - self._config.minValue) / \
(self._config.numberOfBins - 1)
self._imageAccumulate.SetComponentSpacing(cs)
def view_to_config(self):
self._config.numberOfBins = gen_utils.textToInt(
self._viewFrame.numBinsSpinCtrl.GetValue(),
self._config.numberOfBins)
self._config.minValue = gen_utils.textToFloat(
self._viewFrame.minValueText.GetValue(),
self._config.minValue)
self._config.maxValue = gen_utils.textToFloat(
self._viewFrame.maxValueText.GetValue(),
self._config.maxValue)
if self._config.minValue > self._config.maxValue:
self._config.maxValue = self._config.minValue
def config_to_view(self):
self._viewFrame.numBinsSpinCtrl.SetValue(
self._config.numberOfBins)
self._viewFrame.minValueText.SetValue(
str(self._config.minValue))
self._viewFrame.maxValueText.SetValue(
str(self._config.maxValue))
def execute_module(self):
if self._imageAccumulate.GetInput() == None:
return
self._imageAccumulate.Update()
# get histogram params directly from logic
minValue = self._imageAccumulate.GetComponentOrigin()[0]
cs = self._imageAccumulate.GetComponentSpacing()
ce = self._imageAccumulate.GetComponentExtent()
numberOfBins = ce[1] - ce[0] + 1
maxValue = minValue + numberOfBins * cs[0]
# end of param extraction
histArray = Numeric.arange(numberOfBins * 2)
histArray.shape = (numberOfBins, 2)
od = self._imageAccumulate.GetOutput()
for i in range(numberOfBins):
histArray[i,0] = minValue + i * cs[0]
histArray[i,1] = od.GetScalarComponentAsDouble(i,0,0,0)
lines = wxPyPlot.PolyLine(histArray, colour='blue')
self._viewFrame.plotCanvas.Draw(
wxPyPlot.PlotGraphics([lines], "Histogram", "Value", "Occurrences")
)
def view(self):
self._viewFrame.Show()
self._viewFrame.Raise()
# ---------------------------------------------------------------
# END of API methods
# ---------------------------------------------------------------
def _createViewFrame(self):
# create the viewerFrame
import modules.viewers.resources.python.histogram1DFrames
reload(modules.viewers.resources.python.histogram1DFrames)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.viewers.resources.python.histogram1DFrames.\
histogram1DFrame)
self._viewFrame.plotCanvas.SetEnableZoom(True)
self._viewFrame.plotCanvas.SetEnableGrid(True)
objectDict = {'Module (self)' : self,
'vtkImageAccumulate' : self._imageAccumulate}
module_utils.create_standard_object_introspection(
self, self._viewFrame, self._viewFrame.viewFramePanel,
objectDict, None)
module_utils.create_eoca_buttons(self, self._viewFrame,
self._viewFrame.viewFramePanel)
def _bindEvents(self):
wx.EVT_BUTTON(self._viewFrame,
self._viewFrame.autoRangeButton.GetId(),
self._handlerAutoRangeButton)
def _handlerAutoRangeButton(self, event):
if self._imageAccumulate.GetInput() == None:
return
self._imageAccumulate.GetInput().Update()
sr = self._imageAccumulate.GetInput().GetScalarRange()
self._viewFrame.minValueText.SetValue(str(sr[0]))
self._viewFrame.maxValueText.SetValue(str(sr[1]))
| Python |
# slice3d_vwr.py copyright (c) 2002-2010 Charl P. Botha
# next-generation of the slicing and dicing devide module
# TODO: 'refresh' handlers in set_input()
# TODO: front-end / back-end module split (someday)
# should we use background renderer for gradient background, or
# built-in VTK functionality?
BACKGROUND_RENDERER = False
GRADIENT_BACKGROUND = True
import cPickle
import gen_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin, ColourDialogMixin
import module_utils
# the following four lines are only needed during prototyping of the modules
# that they import
import modules.viewers.slice3dVWRmodules.sliceDirections
reload(modules.viewers.slice3dVWRmodules.sliceDirections)
import modules.viewers.slice3dVWRmodules.selectedPoints
reload(modules.viewers.slice3dVWRmodules.selectedPoints)
import modules.viewers.slice3dVWRmodules.tdObjects
reload(modules.viewers.slice3dVWRmodules.tdObjects)
import modules.viewers.slice3dVWRmodules.implicits
reload(modules.viewers.slice3dVWRmodules.implicits)
from modules.viewers.slice3dVWRmodules.sliceDirections import sliceDirections
from modules.viewers.slice3dVWRmodules.selectedPoints import selectedPoints
from modules.viewers.slice3dVWRmodules.tdObjects import tdObjects
from modules.viewers.slice3dVWRmodules.implicits import implicits
import os
import time
import vtk
import vtkdevide
import wx
import weakref
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
import operator
#########################################################################
class slice3dVWR(IntrospectModuleMixin, ColourDialogMixin, ModuleBase):
"""Slicing, dicing slice viewing class.
Please see the main DeVIDE help/user manual by pressing F1. This module,
being so absolutely great, has its own section.
$Revision: 1.52 $
"""
NUM_INPUTS = 16
# part 0 is "normal", parts 1,2,3 are the input-independent output parts
PARTS_TO_INPUTS = {0 : tuple(range(NUM_INPUTS))}
#PARTS_TO_OUTPUTS = {0 : (3,), 1 : (0, 1, 2)}
PARTS_TO_OUTPUTS = {0 : (3,4), 1 : (0,4), 2 : (1,4), 3 : (2,4)}
# part 1 does the points, part 2 does the implicit function,
# part 2 does the implicits
# part 3 does the slices polydata
# this makes it possible for various parts of the slice3dVWR to trigger
# only bits of the network that are necessary
# all parts trigger output 4, as that's the 'self' output
gridSelectionBackground = (11, 137, 239)
def __init__(self, module_manager):
# call base constructor
ModuleBase.__init__(self, module_manager)
ColourDialogMixin.__init__(
self, module_manager.get_module_view_parent_window())
self._numDataInputs = self.NUM_INPUTS
# use list comprehension to create list keeping track of inputs
self._inputs = [{'Connected' : None, 'inputData' : None,
'vtkActor' : None, 'ipw' : None}
for i in range(self._numDataInputs)]
# then the window containing the renderwindows
self.threedFrame = None
# the renderers corresponding to the render windows
self._threedRenderer = None
self._outline_source = vtk.vtkOutlineSource()
om = vtk.vtkPolyDataMapper()
om.SetInput(self._outline_source.GetOutput())
self._outline_actor = vtk.vtkActor()
self._outline_actor.SetMapper(om)
self._cube_axes_actor2d = vtk.vtkCubeAxesActor2D()
self._cube_axes_actor2d.SetFlyModeToOuterEdges()
#self._cube_axes_actor2d.SetFlyModeToClosestTriad()
# use box widget for VOI selection
self._voi_widget = vtk.vtkBoxWidget()
# we want to keep it aligned with the cubic volume, thanks
self._voi_widget.SetRotationEnabled(0)
self._voi_widget.AddObserver('InteractionEvent',
self.voiWidgetInteractionCallback)
self._voi_widget.AddObserver('EndInteractionEvent',
self.voiWidgetEndInteractionCallback)
self._voi_widget.NeedsPlacement = True
# also create the VTK construct for actually extracting VOI from data
#self._extractVOI = vtk.vtkExtractVOI()
self._currentVOI = 6 * [0]
# set the whole UI up!
self._create_window()
# our interactor styles (we could add joystick or something too)
self._cInteractorStyle = vtk.vtkInteractorStyleTrackballCamera()
# set the default
self.threedFrame.threedRWI.SetInteractorStyle(self._cInteractorStyle)
rwi = self.threedFrame.threedRWI
rwi.Unbind(wx.EVT_MOUSEWHEEL)
rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel)
# initialise our sliceDirections, this will also setup the grid and
# bind all slice UI events
self.sliceDirections = sliceDirections(
self, self.controlFrame.sliceGrid)
self.selectedPoints = selectedPoints(
self, self.controlFrame.pointsGrid)
# we now have a wx.ListCtrl, let's abuse it
self._tdObjects = tdObjects(self,
self.controlFrame.objectsListGrid)
self._implicits = implicits(self,
self.controlFrame.implicitsGrid)
# setup orientation widget stuff
# NB NB NB: we switch interaction with this off later
# (InteractiveOff()), thus disabling direct translation and
# scaling. If we DON'T do this, interaction with software
# raycasters are greatly slowed down.
self._orientation_widget = vtk.vtkOrientationMarkerWidget()
self._annotated_cube_actor = aca = vtk.vtkAnnotatedCubeActor()
#aca.TextEdgesOff()
aca.GetXMinusFaceProperty().SetColor(1,0,0)
aca.GetXPlusFaceProperty().SetColor(1,0,0)
aca.GetYMinusFaceProperty().SetColor(0,1,0)
aca.GetYPlusFaceProperty().SetColor(0,1,0)
aca.GetZMinusFaceProperty().SetColor(0,0,1)
aca.GetZPlusFaceProperty().SetColor(0,0,1)
self._axes_actor = vtk.vtkAxesActor()
self._orientation_widget.SetInteractor(
self.threedFrame.threedRWI)
self._orientation_widget.SetOrientationMarker(
self._axes_actor)
self._orientation_widget.On()
# make sure interaction is off; when on, interaction with
# software raycasters is greatly slowed down!
self._orientation_widget.InteractiveOff()
#################################################################
# module API methods
#################################################################
def close(self):
# shut down the orientationWidget/Actor stuff
self._orientation_widget.Off()
self._orientation_widget.SetInteractor(None)
self._orientation_widget.SetOrientationMarker(None)
del self._orientation_widget
del self._annotated_cube_actor
# take care of scalarbar
self._showScalarBarForProp(None)
# this is standard behaviour in the close method:
# call set_input(idx, None) for all inputs
for idx in range(self._numDataInputs):
self.set_input(idx, None)
# take care of the sliceDirections
self.sliceDirections.close()
del self.sliceDirections
# the points
self.selectedPoints.close()
del self.selectedPoints
# take care of the threeD objects
self._tdObjects.close()
del self._tdObjects
# the implicits
self._implicits.close()
del self._implicits
# don't forget to call the mixin close() methods
IntrospectModuleMixin.close(self)
ColourDialogMixin.close(self)
# unbind everything that we bound in our __init__
del self._outline_source
del self._outline_actor
del self._cube_axes_actor2d
del self._voi_widget
#del self._extractVOI
del self._cInteractorStyle
# make SURE there are no props in the Renderer
self._threedRenderer.RemoveAllViewProps()
# take care of all our bindings to renderers
del self._threedRenderer
if BACKGROUND_RENDERER:
# also do the background renderer
self._background_renderer.RemoveAllViewProps()
del self._background_renderer
# the remaining bit of logic is quite crucial:
# we can't explicitly Destroy() the frame, as the RWI that it contains
# will only disappear when it's reference count reaches 0, and we
# can't really force that to happen either. If you DO Destroy() the
# frame before the RW destructs, it will cause the application to
# crash because the RW assumes a valid WindowId in its dtor
#
# we have two solutions:
# 1. call a WindowRemap on the RenderWindows so that they reparent
# themselves to newly created windowids
# 2. attach event handlers to the RenderWindow DeleteEvent and
# destroy the containing frame from there
#
# method 2 doesn't alway work, so we use WindowRemap
# hide it so long
#self.threedFrame.Show(0)
#self.threedFrame.threedRWI.GetRenderWindow().SetSize(10,10)
#self.threedFrame.threedRWI.GetRenderWindow().WindowRemap()
# finalize should be available everywhere
self.threedFrame.threedRWI.GetRenderWindow().Finalize()
# zero the RenderWindow
self.threedFrame.threedRWI.SetRenderWindow(None)
# and get rid of the threedRWI interface
del self.threedFrame.threedRWI
# all the RenderWindow()s are now reparented, so we can destroy
# the containing frame
self.threedFrame.Destroy()
# unbind the _view_frame binding
del self.threedFrame
# take care of the objectAnimationFrame
self.objectAnimationFrame.Destroy()
del self.objectAnimationFrame
# take care of the controlFrame too
self.controlFrame.Destroy()
del self.controlFrame
# if we don't give time up here, things go wrong (BadWindow error,
# invalid glcontext, etc). we'll have to integrate this with the
# eventual module front-end / back-end split. This time-slice
# allows wx time to destroy all windows which somehow also leads
# to VTK being able to deallocate everything that it has.
wx.SafeYield()
def execute_module(self, part=0):
# part 0 is the "normal" part and part 1 is the input-independent part
if part == 0:
self.render3D()
else:
# and make sure outputs and things are up to date!
self.get_output(2).Update()
def get_config(self):
# implant some stuff into the _config object and return it
self._config.savedPoints = self.selectedPoints.getSavePoints()
# also save the visible bounds (this will be used during unpickling
# to calculate pointwidget and text sizes and the like)
self._config.boundsForPoints = self._threedRenderer.\
ComputeVisiblePropBounds()
self._config.implicitsState = self._implicits.getImplicitsState()
return self._config
def set_config(self, aConfig):
self._config = aConfig
savedPoints = self._config.savedPoints
self.selectedPoints.setSavePoints(
savedPoints, self._config.boundsForPoints)
# we remain downwards compatible
if hasattr(self._config, 'implicitsState'):
self._implicits.setImplicitsState(self._config.implicitsState)
def get_input_descriptions(self):
# concatenate it num_inputs times (but these are shallow copies!)
return self._numDataInputs * \
('vtkStructuredPoints|vtkImageData|vtkPolyData',)
def set_input(self, idx, inputStream):
"""Attach new input.
This is the slice3dVWR specialisation of the module API set_input
call.
Remember the following: DeVIDE makes connections when the user
requests, but set_input() is only called directly before the
execute call. This means that DeVIDE maintains module connections,
and the slice3dVWR maintains its own internal state w.r.t.
connections.
"""
def add_primary_init(input_stream):
"""After a new primary has been added, a number of other
actions have to be performed.
"""
# add outline actor and cube axes actor to renderer
self._threedRenderer.AddActor(self._outline_actor)
self._outline_actor.PickableOff()
self._threedRenderer.AddActor(self._cube_axes_actor2d)
self._cube_axes_actor2d.PickableOff()
# FIXME: make this toggle-able
self._cube_axes_actor2d.VisibilityOn()
# reset the VOI widget
self._voi_widget.SetInteractor(self.threedFrame.threedRWI)
self._voi_widget.SetInput(input_stream)
# we only want to placewidget if this is the first time
if self._voi_widget.NeedsPlacement:
self._voi_widget.PlaceWidget()
self._voi_widget.NeedsPlacement = False
self._voi_widget.SetPriority(0.6)
self._handlerWidgetEnabledCheckBox()
# also fix up orientation actor thingy...
ala = input_stream.GetFieldData().GetArray('axis_labels_array')
if ala:
lut = list('LRPAFH')
labels = []
for i in range(6):
labels.append(lut[ala.GetValue(i)])
self._set_annotated_cube_actor_labels(labels)
self._orientation_widget.Off()
self._orientation_widget.SetOrientationMarker(
self._annotated_cube_actor)
self._orientation_widget.On()
else:
self._orientation_widget.Off()
self._orientation_widget.SetOrientationMarker(
self._axes_actor)
self._orientation_widget.On()
# end of method add_primary_init()
def _handleNewImageDataInput():
connecteds = [i['Connected'] for i in self._inputs]
# if we already have a primary, make sure the new inputStream
# is added at a higher port number than all existing
# primaries and overlays
if 'vtkImageDataPrimary' in connecteds:
highestPortIndex = connecteds.index('vtkImageDataPrimary')
for i in range(highestPortIndex, len(connecteds)):
if connecteds[i] == 'vtkImageDataOverlay':
highestPortIndex = i
if idx <= highestPortIndex:
raise Exception, \
"Please add overlay data at higher input " \
"port numbers " \
"than existing primary data and overlays."
# tell all our sliceDirections about the new data
# this might throw an exception if the input image data
# is invalid, but that's ok, since we haven't done any
# accounting here yet.
self.sliceDirections.addData(inputStream)
# find out whether this is primary or an overlay, record it
if 'vtkImageDataPrimary' in connecteds:
# there's no way there can be only overlays in the list,
# the check above makes sure of that
self._inputs[idx]['Connected'] = 'vtkImageDataOverlay'
else:
# there are no primaries or overlays, this must be
# a primary then
self._inputs[idx]['Connected'] = 'vtkImageDataPrimary'
# also store binding to the data itself
self._inputs[idx]['inputData'] = inputStream
if self._inputs[idx]['Connected'] == 'vtkImageDataPrimary':
# things to setup when primary data is added
add_primary_init(inputStream)
# reset everything, including ortho camera
self._resetAll()
# update our 3d renderer
self.render3D()
# end of function _handleImageData()
def remove_primary_cleanup():
"""Get rid of other display elements that are related to
the primary.
"""
self._threedRenderer.RemoveActor(self._outline_actor)
self._threedRenderer.RemoveActor(self._cube_axes_actor2d)
# deactivate VOI widget as far as possible
self._voi_widget.SetInput(None)
self._voi_widget.Off()
self._voi_widget.SetInteractor(None)
# end of method remove_primary_cleanup
if inputStream == None:
if self._inputs[idx]['Connected'] == 'tdObject':
self._tdObjects.removeObject(self._inputs[idx]['tdObject'])
self._inputs[idx]['Connected'] = None
self._inputs[idx]['tdObject'] = None
elif self._inputs[idx]['Connected'] == 'vtkImageDataPrimary' or \
self._inputs[idx]['Connected'] == 'vtkImageDataOverlay':
# first do accounting related to removal
if self._inputs[idx]['Connected'] == 'vtkImageDataPrimary':
remove_primary_cleanup()
primary_removed = True
else:
primary_removed = False
# save this variable, need it to remove the data
the_data = self._inputs[idx]['inputData']
self._inputs[idx]['Connected'] = None
self._inputs[idx]['inputData'] = None
# then remove data from the sliceDirections
# this call doesn't require any of the accounting that
# we've already destroyed.
self.sliceDirections.removeData(the_data)
# primary-overlay handling ##############################
# now go through the remaining inputs to find all overlays
# remove them all, re-add them with the first as the new
# primary. This is to allow a graceful removal of a primary
# where remaining overlays will simply re-arrange themselves
# fixme: give the new primary the same plane geometry
# as the old primary.
if primary_removed:
slice_geoms = self.sliceDirections.get_slice_geometries()
overlay_idxs = []
for idx,inp in enumerate(self._inputs):
if inp['Connected'] == 'vtkImageDataOverlay':
self.sliceDirections.removeData(
inp['inputData'])
overlay_idxs.append(idx)
for i,idx2 in enumerate(overlay_idxs):
inp = self._inputs[idx2]
if i == 0:
# convert the first of the overlays to primary
inp['Connected'] = 'vtkImageDataPrimary'
self.sliceDirections.addData(inp['inputData'])
add_primary_init(inp['inputData'])
# we've added a primary, now is the best
# time to set the geometry, before any
# other re-added overlays
self.sliceDirections.set_slice_geometries(
slice_geoms)
else:
self.sliceDirections.addData(inp['inputData'])
if overlay_idxs:
self.render3D()
elif self._inputs[idx]['Connected'] == 'namedWorldPoints':
pass
elif self._inputs[idx]['Connected'] == \
'vtkLookupTable':
# disconnect from sliceDirections
self.sliceDirections.set_lookup_table(
None)
self._inputs[idx]['Connected'] = None
self._inputs[idx]['inputData'] = None
# END of if inputStream is None clause -----------------------------
# check for VTK types
elif hasattr(inputStream, 'GetClassName') and \
callable(inputStream.GetClassName):
if inputStream.GetClassName() == 'vtkVolume' or \
inputStream.GetClassName() == 'vtkPolyData':
# first check if this is a None -> Something or a
# Something -> Something case. In the former case, it's
# a new input, in the latter, it's an existing connection
# that wants to be updated.
if self._inputs[idx]['Connected'] is None:
# our _tdObjects instance likes to do this
self._tdObjects.addObject(inputStream)
# if this worked, we have to make a note that it was
# connected as such
self._inputs[idx]['Connected'] = 'tdObject'
self._inputs[idx]['tdObject'] = inputStream
else:
# todo: take necessary actions to 'refresh' input
self._tdObjects.updateObject(
self._inputs[idx]['tdObject'], inputStream)
# and record the new object in our input lists
self._inputs[idx]['Connected'] = 'tdObject'
self._inputs[idx]['tdObject'] = inputStream
elif inputStream.IsA('vtkImageData'):
if self._inputs[idx]['Connected'] is None:
_handleNewImageDataInput()
else:
# take necessary actions to refresh
prevData = self._inputs[idx]['inputData']
self.sliceDirections.updateData(prevData, inputStream)
# record it in our main structure
self._inputs[idx]['inputData'] = inputStream
elif inputStream.IsA('vtkLookupTable'):
self.sliceDirections.set_lookup_table(
inputStream)
self._inputs[idx]['Connected'] = \
'vtkLookupTable'
self._inputs[idx]['inputData'] = inputStream
else:
raise TypeError, "Wrong input type!"
# ends: elif hasattr GetClassName
elif hasattr(inputStream, 'devideType'):
# todo: re-implement, this will now be called at EVERY
# network execute!
print "has d3type"
if inputStream.devideType == 'namedPoints':
print "d3type correct"
# add these to our selected points!
self._inputs[idx]['Connected'] = 'namedWorldPoints'
for point in inputStream:
self.selectedPoints._storePoint(
(0,0,0), point['world'], 0.0,
point['name'])
else:
raise TypeError, "Input type not recognised!"
def get_output_descriptions(self):
return ('Selected points',
'Implicit Function',
'Slices polydata',
'Slices unstructured grid',
'self (slice3dVWR object)')
def get_output(self, idx):
if idx == 0:
return self.selectedPoints.outputSelectedPoints
elif idx == 1:
return self._implicits.outputImplicitFunction
elif idx == 2:
return self.sliceDirections.ipwAppendPolyData.GetOutput()
elif idx == 3:
return self.sliceDirections.ipwAppendFilter.GetOutput()
else:
return self
# else:
# class RenderInfo:
# def __init__(self, renderer, render_window, interactor):
# self.renderer = renderer
# self.render_window = render_window
# self.interactor = interactor
# render_info = RenderInfo(
# self._threedRenderer,
# self.threedFrame.threedRWI.GetRenderWindow(),
# self.threedFrame.threedRWI)
# return render_info
def view(self):
# when a view is requested, we only show the 3D window
# the user can show the control panel by using the button
# made for that purpose.
self.threedFrame.Show(True)
# make sure the view comes to the front
self.threedFrame.Raise()
# need to call this so that the window is actually refreshed
wx.SafeYield()
# and then make sure the 3D renderer is working (else we
# get empty windows)
self.render3D()
#################################################################
# miscellaneous public methods
#################################################################
def getIPWPicker(self):
return self._ipwPicker
def getViewFrame(self):
return self.threedFrame
def get_3d_renderer(self):
"""All external entities MUST use this method to get to the VTK
renderer.
"""
return weakref.proxy(self._threedRenderer)
def get_3d_render_window(self):
"""All external entities MUST use this method to get to the VTK
render window.
"""
return weakref.proxy(self.threedFrame.threedRWI.GetRenderWindow())
def get_3d_render_window_interactor(self):
"""All external entities MUST use this method to get to the VTK render
window interactor.
"""
return weakref.proxy(self.threedFrame.threedRWI)
def render3D(self):
"""This will cause a render to be called on the encapsulated 3d
RWI.
"""
self.threedFrame.threedRWI.Render()
#################################################################
# internal utility methods
#################################################################
def _create_window(self):
import modules.viewers.resources.python.slice3dVWRFrames
reload(modules.viewers.resources.python.slice3dVWRFrames)
stereo = self._module_manager.get_app_main_config().stereo
#print "STEREO:", stereo
modules.viewers.resources.python.slice3dVWRFrames.S3DV_STEREO = stereo
# threedFrame creation and basic setup -------------------
threedFrame = modules.viewers.resources.python.slice3dVWRFrames.\
threedFrame
self.threedFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, threedFrame)
self.threedFrame.SetTitle('slice3dVWR 3D view')
# see about stereo
#self.threedFrame.threedRWI.GetRenderWindow().SetStereoCapableWindow(1)
# create foreground and background renderers
self._threedRenderer = vtk.vtkRenderer()
if BACKGROUND_RENDERER:
self._background_renderer = vtk.vtkRenderer()
renwin = self.threedFrame.threedRWI.GetRenderWindow()
# I've not yet been able to get depth peeling working on my
# NV 8800 on Ubuntu 8.10 Linux x86_64. Will continue later...
#renwin.SetMultiSamples(0)
#renwin.SetAlphaBitPlanes(1)
#self._threedRenderer.SetUseDepthPeeling(1)
#self._threedRenderer.SetMaximumNumberOfPeels(100)
#self._threedRenderer.SetOcclusionRatio(0.1)
#renwin.AddRenderer(self._threedRenderer)
# use function to setup fg and bg renderers so we can have a
# nice gradient background.
if BACKGROUND_RENDERER:
import module_kits.vtk_kit
module_kits.vtk_kit.utils.setup_renderers(renwin,
self._threedRenderer, self._background_renderer)
else:
self._threedRenderer.SetBackground(0.5,0.5,0.5)
if GRADIENT_BACKGROUND:
self._threedRenderer.SetBackground2(1,1,1)
self._threedRenderer.SetGradientBackground(1)
renwin.AddRenderer(self._threedRenderer)
# controlFrame creation and basic setup -------------------
controlFrame = modules.viewers.resources.python.slice3dVWRFrames.\
controlFrame
self.controlFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, controlFrame)
self.controlFrame.SetTitle('slice3dVWR Controls')
# fix for the grid
#self.controlFrame.spointsGrid.SetSelectionMode(wx.Grid.wxGridSelectRows)
#self.controlFrame.spointsGrid.DeleteRows(
# 0, self.controlFrame.spointsGrid.GetNumberRows())
# add possible point names
self.controlFrame.sliceCursorNameCombo.Clear()
self.controlFrame.sliceCursorNameCombo.Append('Point 1')
self.controlFrame.sliceCursorNameCombo.Append('GIA Glenoid')
self.controlFrame.sliceCursorNameCombo.Append('GIA Humerus')
self.controlFrame.sliceCursorNameCombo.Append('FBZ Superior')
self.controlFrame.sliceCursorNameCombo.Append('FBZ Inferior')
# event handlers for the global control buttons
wx.EVT_BUTTON(self.threedFrame, self.threedFrame.showControlsButtonId,
self._handlerShowControls)
wx.EVT_BUTTON(self.threedFrame, self.threedFrame.resetCameraButtonId,
self._handlerResetCamera)
wx.EVT_BUTTON(self.threedFrame, self.threedFrame.resetAllButtonId,
lambda e: (self._resetAll(), self._resetAll()))
wx.EVT_BUTTON(self.threedFrame, self.threedFrame.saveImageButton.GetId(),
self._handlerSaveImageButton)
wx.EVT_CHOICE(self.threedFrame,
self.threedFrame.projectionChoiceId,
self._handlerProjectionChoice)
wx.EVT_BUTTON(self.threedFrame,
self.threedFrame.introspectButton.GetId(),
self._handlerIntrospectButton)
wx.EVT_BUTTON(self.threedFrame,
self.threedFrame.introspectPipelineButtonId,
lambda e, pw=self.threedFrame, s=self,
rw=self.threedFrame.threedRWI.GetRenderWindow():
s.vtkPipelineConfigure(pw, rw))
def handler_freeze_slices_button(e):
names = self.sliceDirections.get_all_slice_names()
for n in names:
self.sliceDirections._setSliceInteraction(
n, not e.IsChecked())
self.threedFrame.freeze_slices_button.Bind(
wx.EVT_TOGGLEBUTTON, handler_freeze_slices_button)
# event logic for the voi panel
wx.EVT_CHECKBOX(self.controlFrame,
self.controlFrame.voiEnabledCheckBoxId,
self._handlerWidgetEnabledCheckBox)
wx.EVT_CHOICE(self.controlFrame,
self.controlFrame.voiAutoSizeChoice.GetId(),
self._handlerVoiAutoSizeChoice)
wx.EVT_BUTTON(self.controlFrame,
self.controlFrame.voiFilenameBrowseButton.GetId(),
self._handlerVoiFilenameBrowseButton)
wx.EVT_BUTTON(self.controlFrame,
self.controlFrame.voiSaveButton.GetId(),
self._handlerVoiSaveButton)
def _ps_cb():
# FIXME: update to new factoring
sliceDirection = self.getCurrentSliceDirection()
if sliceDirection:
val = self.threedFrame.pushSliceSpinCtrl.GetValue()
if val:
sliceDirection.pushSlice(val)
self.threedFrame.pushSliceSpinCtrl.SetValue(0)
self.threedFrame.threedRWI.Render()
# clicks directly in the window for picking
self.threedFrame.threedRWI.AddObserver('LeftButtonPressEvent',
self._rwiLeftButtonCallback)
# objectAnimationFrame creation and basic setup -------------------
oaf = modules.viewers.resources.python.slice3dVWRFrames.\
objectAnimationFrame
self.objectAnimationFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager, oaf)
# display the windows (but we don't show the oaf yet)
self.view()
if os.name == 'posix':
# yet another workaround for GTK1.2 on Linux (Debian 3.0)
# if we don't do this, the renderer is far smaller than its
# containing window and only corrects once the window is resized
# also, this shouldn't really fix it, but it does:
# then size that we set, is the "small" incorrect size
# but somehow tickling GTK in this way makes everything better
self.threedFrame.threedRWI.GetRenderWindow().SetSize(
self.threedFrame.threedRWI.GetSize())
self.threedFrame.threedRWI._Iren.ConfigureEvent()
wx.SafeYield()
def _set_annotated_cube_actor_labels(self, labels):
aca = self._annotated_cube_actor
aca.SetXMinusFaceText(labels[0])
aca.SetXPlusFaceText(labels[1])
aca.SetYMinusFaceText(labels[2])
aca.SetYPlusFaceText(labels[3])
aca.SetZMinusFaceText(labels[4])
aca.SetZPlusFaceText(labels[5])
def getPrimaryInput(self):
"""Get primary input data, i.e. bottom layer.
If there is no primary input data, this will return None.
"""
inputs = [i for i in self._inputs if i['Connected'] ==
'vtkImageDataPrimary']
if inputs:
inputData = inputs[0]['inputData']
else:
inputData = None
return inputData
def getWorldPositionInInputData(self, discretePos):
if len(discretePos) < 3:
return None
inputData = self.getPrimaryInput()
if inputData:
ispacing = inputData.GetSpacing()
iorigin = inputData.GetOrigin()
# calculate real coords
world = map(operator.add, iorigin,
map(operator.mul, ispacing, discretePos[0:3]))
return world
else:
return None
def getValuesAtDiscretePositionInInputData(self, discretePos):
inputData = self.getPrimaryInput()
if inputData == None:
return
# check that discretePos is in the input volume
validPos = True
extent = inputData.GetExtent()
for d in range(3):
if discretePos[d]< extent[d*2] or discretePos[d] > extent[d*2+1]:
validPos = False
break
if validPos:
nc = inputData.GetNumberOfScalarComponents()
values = []
for c in range(nc):
values.append(inputData.GetScalarComponentAsDouble(
int(discretePos[0]), int(discretePos[1]), int(discretePos[2]), c))
else:
values = None
return values
def getValueAtPositionInInputData(self, worldPosition):
"""Try and find out what the primary image data input value is at
worldPosition.
If there is no inputData, or the worldPosition is outside of the
inputData, None is returned.
"""
inputData = self.getPrimaryInput()
if inputData:
# then we have to update our internal record of this point
ispacing = inputData.GetSpacing()
iorigin = inputData.GetOrigin()
discrete = map(int, map(
round, map(
operator.div,
map(operator.sub, worldPosition, iorigin), ispacing)))
validPos = True
extent = inputData.GetExtent()
for d in range(3):
if discrete[d]< extent[d*2] or discrete[d] > extent[d*2+1]:
validPos = False
break
if validPos:
# we rearch this else if the for loop completed normally
val = inputData.GetScalarComponentAsDouble(discrete[0],
discrete[1],
discrete[2], 0)
else:
val = None
else:
discrete = (0,0,0)
val = None
return (val, discrete)
def _resetAll(self):
"""Arrange everything for a single overlay in a single ortho view.
This method is to be called AFTER the pertinent VTK pipeline has been
setup. This is here, because one often connects modules together
before source modules have been configured, i.e. the success of this
method is dependent on whether the source modules have been configged.
HOWEVER: it won't die if it hasn't, just complain.
It will configure all 3d widgets and textures and thingies, but it
won't CREATE anything.
"""
# we only do something here if we have data
inputDataL = [i['inputData'] for i in self._inputs
if i['Connected'] == 'vtkImageDataPrimary']
if inputDataL:
inputData = inputDataL[0]
else:
return
# we might have ipws, but no inputData, in which we can't do anything
# either, so we bail
if inputData is None:
return
# make sure this is all nicely up to date
inputData.Update()
# set up helper actors
self._outline_source.SetBounds(inputData.GetBounds())
self._cube_axes_actor2d.SetBounds(inputData.GetBounds())
self._cube_axes_actor2d.SetCamera(
self._threedRenderer.GetActiveCamera())
self._threedRenderer.ResetCamera()
# make sure the overlays follow suit
self.sliceDirections.resetAll()
# whee, thaaaar she goes.
self.render3D()
def _save3DToImage(self, filename):
self._module_manager.setProgress(0, "Writing PNG image...")
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(self.threedFrame.threedRWI.GetRenderWindow())
writer = vtk.vtkPNGWriter()
writer.SetInput(w2i.GetOutput())
writer.SetFileName(filename)
writer.Write()
self._module_manager.setProgress(100, "Writing PNG image... [DONE]")
def _showScalarBarForProp(self, prop):
"""Show scalar bar for the data represented by the passed prop.
If prop is None, the scalar bar will be removed and destroyed if
present.
"""
destroyScalarBar = False
if prop:
# activate the scalarbar, connect to mapper of prop
if prop.GetMapper() and prop.GetMapper().GetLookupTable():
if not hasattr(self, '_pdScalarBarActor'):
self._pdScalarBarActor = vtk.vtkScalarBarActor()
self._threedRenderer.AddViewProp(self._pdScalarBarActor)
sname = "Unknown"
s = prop.GetMapper().GetInput().GetPointData().GetScalars()
if s and s.GetName():
sname = s.GetName()
self._pdScalarBarActor.SetTitle(sname)
self._pdScalarBarActor.SetLookupTable(
prop.GetMapper().GetLookupTable())
self.threedFrame.threedRWI.Render()
else:
# the prop doesn't have a mapper or the mapper doesn't
# have a LUT, either way, we switch off the thingy...
destroyScalarBar = True
else:
# the user has clicked "somewhere else", so remove!
destroyScalarBar = True
if destroyScalarBar and hasattr(self, '_pdScalarBarActor'):
self._threedRenderer.RemoveViewProp(self._pdScalarBarActor)
del self._pdScalarBarActor
def _storeSurfacePoint(self, actor, pickPosition):
polyData = actor.GetMapper().GetInput()
if polyData:
xyz = pickPosition
else:
# something really weird went wrong
return
if self.selectedPoints.hasWorldPoint(xyz):
return
val, discrete = self.getValueAtPositionInInputData(xyz)
if val == None:
discrete = (0,0,0)
val = 0
pointName = self.controlFrame.sliceCursorNameCombo.GetValue()
self.selectedPoints._storePoint(
discrete, xyz, val, pointName, True) # lock to surface
#################################################################
# callbacks
#################################################################
def _handler_mousewheel(self, event):
# event.GetWheelRotation() is + or - 120 depending on
# direction of turning.
if event.ControlDown():
delta = 10
elif event.ShiftDown():
delta = 1
else:
# if user is NOT doing shift / control, we pass on to the
# default handling which will give control to the VTK
# mousewheel handlers.
self.threedFrame.threedRWI.OnMouseWheel(event)
return
selected_sds = self.sliceDirections.getSelectedSliceDirections()
if len(selected_sds) == 0:
if len(self.sliceDirections._sliceDirectionsDict) == 1:
# convenience: nothing selected, but there is only one SD, use that then!
sd = self.sliceDirections._sliceDirectionsDict.items()[0][1]
else:
return
else:
sd = selected_sds[0]
if event.GetWheelRotation() > 0:
sd.delta_slice(+delta)
else:
sd.delta_slice(-delta)
self.render3D()
#self.ipws[0].InvokeEvent('InteractionEvent')
def _handlerVoiAutoSizeChoice(self, event):
if self._voi_widget.GetEnabled():
asc = self.controlFrame.voiAutoSizeChoice.GetSelection()
if asc == 0: # bounding box of selected points
swp = self.selectedPoints.getSelectedWorldPoints()
if len(swp) > 0:
minxyz = list(swp[0])
maxxyz = list(swp[0])
# find max bounds of the selected points
for p in swp:
for i in range(3):
if p[i] < minxyz[i]:
minxyz[i] = p[i]
if p[i] > maxxyz[i]:
maxxyz[i] = p[i]
# now set bounds on VOI thingy
# first we zip up minxyz maxxyz to get minx, maxx, miny
# etc., then we use * to break this open into 6 args
self._voi_widget.SetPlaceFactor(1.0)
self._voi_widget.PlaceWidget(minxyz[0], maxxyz[0],
minxyz[1], maxxyz[1],
minxyz[2], maxxyz[2])
# make sure these changes are reflected in the VOI output
self.voiWidgetInteractionCallback(self._voi_widget, None)
self.voiWidgetEndInteractionCallback(self._voi_widget,
None)
self.render3D()
def _handlerWidgetEnabledCheckBox(self, event=None):
# event can be None
if self._voi_widget.GetInput():
if self.controlFrame.voiEnabledCheckBox.GetValue():
self._voi_widget.On()
self.voiWidgetInteractionCallback(self._voi_widget, None)
self.voiWidgetEndInteractionCallback(self._voi_widget,
None)
else:
self._voi_widget.Off()
def _handlerVoiFilenameBrowseButton(self, event):
dlg = wx.FileDialog(self.controlFrame,
"Select VTI filename to write VOI to",
"", "", "*.vti", wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
self.controlFrame.voiFilenameText.SetValue(dlg.GetPath())
def _handlerVoiSaveButton(self, event):
input_data = self.getPrimaryInput()
filename = self.controlFrame.voiFilenameText.GetValue()
if input_data and self._voi_widget.GetEnabled() and filename:
# see if we need to reset to zero origin
zor = self.controlFrame.voiResetToOriginCheck.GetValue()
extractVOI = vtk.vtkExtractVOI()
extractVOI.SetInput(input_data)
extractVOI.SetVOI(self._currentVOI)
writer = vtk.vtkXMLImageDataWriter()
writer.SetDataModeToBinary()
writer.SetFileName(filename)
if zor:
ici = vtk.vtkImageChangeInformation()
ici.SetOutputExtentStart(0,0,0)
ici.SetInput(extractVOI.GetOutput())
writer.SetInput(ici.GetOutput())
else:
writer.SetInput(extractVOI.GetOutput())
writer.Write()
def _handlerIntrospectButton(self, event):
"""Open Python introspection window with this module as main object.
"""
self.miscObjectConfigure(
self.threedFrame, self,
'slice3dVWR %s' % \
(self._module_manager.get_instance_name(self),))
def _handlerProjectionChoice(self, event):
"""Handler for global projection type change.
"""
cam = self._threedRenderer.GetActiveCamera()
if not cam:
return
pcs = self.threedFrame.projectionChoice.GetSelection()
if pcs == 0:
# perspective
cam.ParallelProjectionOff()
else:
cam.ParallelProjectionOn()
self.render3D()
def _handlerResetCamera(self, event):
self._threedRenderer.ResetCamera()
self.render3D()
def _handlerSaveImageButton(self, event):
# first get the filename
# (if we don't specify the parent correctly, the DeVIDE main
# window pops up!)
filename = wx.FileSelector(
"Choose filename for PNG image",
"", "", "png",
"PNG files (*.png)|*.png|All files (*.*)|*.*",
wx.SAVE,
parent=self.threedFrame)
if filename:
self._save3DToImage(filename)
def _handlerShowControls(self, event):
if not self.controlFrame.Show(True):
self.controlFrame.Raise()
def voiWidgetInteractionCallback(self, o, e):
planes = vtk.vtkPlanes()
o.GetPlanes(planes)
bounds = planes.GetPoints().GetBounds()
# first set bounds
self.controlFrame.voiBoundsText.SetValue(
"(%.2f %.2f %.2f %.2f %.2f %.2f) mm" %
bounds)
input_data = self.getPrimaryInput()
if input_data:
ispacing = input_data.GetSpacing()
iorigin = input_data.GetOrigin()
# calculate discrete coords
bounds = planes.GetPoints().GetBounds()
voi = 6 * [0]
# excuse the for loop :)
for i in range(6):
voi[i] = int(round((bounds[i] - iorigin[i / 2]) / ispacing[i / 2]))
# store the VOI (this is a shallow copy)
self._currentVOI = voi
# display the discrete extent
self.controlFrame.voiExtentText.SetValue(
"(%d %d %d %d %d %d)" % tuple(voi))
def voiWidgetEndInteractionCallback(self, o, e):
# adjust the vtkExtractVOI with the latest coords
#self._extractVOI.SetVOI(self._currentVOI)
pass
def _rwiLeftButtonCallback(self, obj, event):
def findPickedProp(obj, onlyTdObjects=False):
# we use a cell picker, because we don't want the point
# to fall through the polygons, if you know what I mean
picker = vtk.vtkCellPicker()
# very important to set this, else we pick the weirdest things
picker.SetTolerance(0.005)
if onlyTdObjects:
pp = self._tdObjects.getPickableProps()
if not pp:
return (None, (0,0,0))
else:
# tell the picker which props it's allowed to pick from
for p in pp:
picker.AddPickList(p)
picker.PickFromListOn()
(x,y) = obj.GetEventPosition()
picker.Pick(x,y,0.0,self._threedRenderer)
return (picker.GetActor(), picker.GetPickPosition())
pickAction = self.controlFrame.surfacePickActionChoice.GetSelection()
if pickAction == 1:
# Place point on surface
actor, pickPosition = findPickedProp(obj, True)
if actor:
self._storeSurfacePoint(actor, pickPosition)
elif pickAction == 2:
# configure picked object
prop, unusedPickPosition = findPickedProp(obj)
if prop:
self.vtkPipelineConfigure(self.threedFrame,
self.threedFrame.threedRWI, (prop,))
elif pickAction == 3:
# show scalarbar for picked object
prop, unusedPickPosition = findPickedProp(obj)
self._showScalarBarForProp(prop)
elif pickAction == 4:
# move the object -- for this we're going to use a special
# vtkBoxWidget
pass
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
# skeleton of an AUI-based viewer module
# copy and modify for your own purposes.
# set to False for 3D viewer, True for 2D image viewer
IMAGE_VIEWER = True
MATCH_MODE_PASSTHROUGH = 0
MATCH_MODE_LANDMARK_SS = 1
MATCH_MODE_STRINGS = [ \
'Single structure landmarks'
]
COMPARISON_MODE_DATA2M = 0
COMPARISON_MODE_CHECKERBOARD = 1
COMPARISON_MODE_DIFFERENCE = 2
# import the frame, i.e. the wx window containing everything
import CoMedIFrame
# and do a reload, so that the GUI is also updated at reloads of this
# module.
reload(CoMedIFrame)
import comedi_match_modes
reload(comedi_match_modes)
import comedi_comparison_modes
reload(comedi_comparison_modes)
import comedi_utils
reload(comedi_utils)
import math
from module_kits.misc_kit import misc_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import operator
import os
import random #temp testing
import sys
import traceback
import vtk
import wx
class CoMedI(IntrospectModuleMixin, ModuleBase):
# API methods
def __init__(self, module_manager):
"""Standard constructor. All DeVIDE modules have these, we do
the required setup actions.
"""
# we record the setting here, in case the user changes it
# during the lifetime of this model, leading to different
# states at init and shutdown.
self.IMAGE_VIEWER = IMAGE_VIEWER
ModuleBase.__init__(self, module_manager)
# create the view frame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
CoMedIFrame.CoMedIFrame)
# change the title to something more spectacular
self._view_frame.SetTitle('CoMedI')
self._setup_vis()
# hook up all event handlers
self._bind_events()
# make our window appear (this is a viewer after all)
self.view()
# all modules should toggle this once they have shown their
# views.
self.view_initialised = True
# this will cause the correct set_cam_* call to be made
self._config.cam_parallel = False
# setup all match modes here. even if the user switches
# modes, all metadata should be serialised, so that after a
# network reload, the user can switch and will get her old
# metadata back from a previous session.
self._config.sstructlandmarksmm_cfg = {}
# default match mode is the landmark thingy
self._config.match_mode = MATCH_MODE_LANDMARK_SS
# this will hold a binding to the current match mode that will
# be initially setup by config_to_logic
self.match_mode = None
self._config.data2mcm_cfg = {}
self._config.checkerboardcm_cfg = {}
self._config.focusdiffcm_cfg = {}
self._config.comparison_mode = COMPARISON_MODE_DATA2M
self.comparison_mode = None
# apply config information to underlying logic
self.sync_module_logic_with_config()
# then bring it all the way up again to the view
self.sync_module_view_with_logic()
def close(self):
"""Clean-up method called on all DeVIDE modules when they are
deleted.
"""
# get rid of match_mode
self.match_mode.close()
self._close_vis()
# now take care of the wx window
self._view_frame.close()
# then shutdown our introspection mixin
IntrospectModuleMixin.close(self)
def get_input_descriptions(self):
# define this as a tuple of input descriptions if you want to
# take input data e.g. return ('vtkPolyData', 'my kind of
# data')
return ('Data 1', 'Data 2')
def get_output_descriptions(self):
# define this as a tuple of output descriptions if you want to
# generate output data.
return ('Matched Data 2', 'Confidence Field')
def set_input(self, idx, input_stream):
# this gets called right before you get executed. take the
# input_stream and store it so that it's available during
# execute_module()
if idx == 0:
self._data1_slice_viewer.set_input(input_stream)
if input_stream is None:
# we're done disconnecting, no syncing necessary
# but we do need to tell the current match_mode
# something is going on.
self._update_mmcm(True)
return
if not self._data2_slice_viewer.get_input():
self._data1_slice_viewer.reset_camera()
self._data1_slice_viewer.render()
else:
# sync ourselves to data2
self.sync_slice_viewers.sync_all(
self._data2_slice_viewer,
[self._data1_slice_viewer])
if idx == 1:
self._data2_slice_viewer.set_input(input_stream)
if input_stream is None:
self._update_mmcm(True)
return
if not self._data1_slice_viewer.get_input():
self._data2_slice_viewer.reset_camera()
self._data2_slice_viewer.render()
else:
self.sync_slice_viewers.sync_all(
self._data1_slice_viewer,
[self._data2_slice_viewer])
def get_output(self, idx):
# this can get called at any time when a consumer module wants
# you output data.
if idx == 0:
return self.match_mode.get_output()
else:
return self.match_mode.get_confidence()
def execute_module(self):
# when it's you turn to execute as part of a network
# execution, this gets called.
pass
# as per usual with viewer modules, we're keeping the config up to
# date throughout execution, so only the config_to_logic and
# config_to_view are implemented, so that things correctly restore
# after a deserialisation.
def logic_to_config(self):
pass
def config_to_logic(self):
# we need to be able to build up the correct MatchMode based
# on the config.
print "sync mm"
self._sync_mm_with_config()
# do the same for the comparison mode
print "sync cm"
self._sync_cm_with_config()
def config_to_view(self):
if self._config.cam_parallel:
self.set_cam_parallel()
# also make sure this is reflected in the menu
self._view_frame.set_cam_parallel()
else:
self.set_cam_perspective()
# also make sure this is reflected in the menu
self._view_frame.set_cam_perspective()
# now also set the correct pages in the match mode and
# comparison mode notebooks.
vf = self._view_frame
cp = vf.pane_controls.window
# ChangeSelection does not trigger the event handlers
cp.match_mode_notebook.ChangeSelection(
self._config.match_mode)
cp.comparison_mode_notebook.ChangeSelection(
self._config.comparison_mode)
def view_to_config(self):
pass
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# because we have an RWI involved, we have to do this
# SafeYield, so that the window does actually appear before we
# call the render. If we don't do this, we get an initial
# empty renderwindow.
wx.SafeYield()
self.render_all()
# PRIVATE methods
def _bind_events(self):
"""Bind wx events to Python callable object event handlers.
"""
vf = self._view_frame
vf.Bind(wx.EVT_MENU, self._handler_cam_perspective,
id = vf.id_camera_perspective)
vf.Bind(wx.EVT_MENU, self._handler_cam_parallel,
id = vf.id_camera_parallel)
vf.Bind(wx.EVT_MENU, self._handler_cam_xyzp,
id = vf.id_camera_xyzp)
vf.Bind(wx.EVT_MENU, self._handler_introspect,
id = vf.id_adv_introspect)
vf.Bind(wx.EVT_MENU, self._handler_synced,
id = vf.id_views_synchronised)
vf.Bind(wx.EVT_MENU, self._handler_slice2,
id = vf.id_views_slice2)
vf.Bind(wx.EVT_MENU, self._handler_slice3,
id = vf.id_views_slice3)
cp = vf.pane_controls.window
cp.compare_button.Bind(wx.EVT_BUTTON, self._handler_compare)
cp.update_compvis_button.Bind(wx.EVT_BUTTON,
self._handler_update_compvis)
cp.match_mode_notebook.Bind(
wx.EVT_NOTEBOOK_PAGE_CHANGED,
self._handler_mm_nbp_changed)
cp.comparison_mode_notebook.Bind(
wx.EVT_NOTEBOOK_PAGE_CHANGED,
self._handler_cm_nbp_changed)
def _close_vis(self):
for sv in self._slice_viewers:
sv.close()
def _handler_cam_parallel(self, event):
self.set_cam_parallel()
def _handler_cam_perspective(self, event):
self.set_cam_perspective()
def _handler_cam_xyzp(self, event):
self._data1_slice_viewer.reset_to_default_view(2)
# then synchronise the rest
self.sync_slice_viewers.sync_all(self._data1_slice_viewer)
def _handler_cm_nbp_changed(self, evt):
# tab indices match the constant value.
self._config.comparison_mode = evt.GetSelection()
self._sync_cm_with_config()
self.comparison_mode.update_vis()
# we have to call this skip so that wx also changes the page
# contents.
evt.Skip()
def _handler_mm_nbp_changed(self, evt):
print "hello you too"
# we have to call this skip so wx also changes the actual tab
# contents.
evt.Skip()
def _handler_compare(self, e):
self._update_mmcm()
def _handler_introspect(self, e):
self.miscObjectConfigure(self._view_frame, self, 'CoMedI')
def _handler_slice2(self, e):
for sv in self.sync_slice_viewers.slice_viewers:
if e.IsChecked():
sv.activate_slice(1)
else:
sv.deactivate_slice(1)
def _handler_slice3(self, e):
for sv in self.sync_slice_viewers.slice_viewers:
if e.IsChecked():
sv.activate_slice(2)
else:
sv.deactivate_slice(2)
def _handler_synced(self, event):
#cb = event.GetEventObject()
if event.IsChecked():
if not self.sync_slice_viewers.sync:
self.sync_slice_viewers.sync = True
# now do the initial sync to data1
self.sync_slice_viewers.sync_all(
self._data1_slice_viewer)
else:
self.sync_slice_viewers.sync = False
def _handler_update_compvis(self, evt):
self.comparison_mode.update_vis()
def _observer_cursor(self, vtk_o, vtk_e, txt):
"""
@param txt: Text identifier that will be prepended to the
cursor position update in the UI.
"""
cd = [0,0,0,0]
cdv = vtk_o.GetCursorData(cd)
if not cdv:
# we're not cursoring
return
c = tuple([int(i) for i in cd])
self._view_frame.pane_controls.window.cursor_text.SetValue(
'%s : %s = %d' % (txt, c[0:3], c[3]))
# also store the current cursor position in an ivar, we need
# it. we probably need to replace this text check with
# something else...
if txt.startswith('d1'):
self._data1_slice_viewer.current_index_pos = c
w = self._data1_slice_viewer.get_world_pos(c)
self._data1_slice_viewer.current_world_pos = w
elif txt.startswith('d2'):
self._data1_slice_viewer.current_index_pos = c
w = self._data2_slice_viewer.get_world_pos(c)
self._data2_slice_viewer.current_world_pos = w
def _setup_vis(self):
# setup data1 slice viewer, instrument its slice viewers with
# observers so that the cursor information is output to the
# GUI
SV = comedi_utils.CMSliceViewer
self._data1_slice_viewer = SV(
self._view_frame.rwi_pane_data1.rwi,
self._view_frame.rwi_pane_data1.renderer)
for ipw in self._data1_slice_viewer.ipws:
ipw.AddObserver(
'InteractionEvent',
lambda o,e: self._observer_cursor(o,e,'d1') )
# do the same for the data2 slice viewer
self._data2_slice_viewer = SV(
self._view_frame.rwi_pane_data2.rwi,
self._view_frame.rwi_pane_data2.renderer)
for ipw in self._data2_slice_viewer.ipws:
ipw.AddObserver(
'InteractionEvent',
lambda o,e: self._observer_cursor(o,e,'d2') )
self._slice_viewers = [ \
self._data1_slice_viewer,
self._data2_slice_viewer]
self.sync_slice_viewers = ssv = comedi_utils.SyncSliceViewers()
for sv in self._slice_viewers:
ssv.add_slice_viewer(sv)
def _sync_cm_with_config(self):
"""Synchronise comparison mode with what's specified in the
config. This is used by config_to_logic as well as the
run-time comparison mode tab switching.
"""
if self.comparison_mode:
self.comparison_mode.close()
self.comparison_mode = None
if self._config.comparison_mode == COMPARISON_MODE_DATA2M:
cm = comedi_comparison_modes.Data2MCM
self.comparison_mode = cm(
self, self._config.data2mcm_cfg)
elif self._config.comparison_mode == \
COMPARISON_MODE_CHECKERBOARD:
cm = comedi_comparison_modes.CheckerboardCM
self.comparison_mode = cm(
self, self._config.checkerboardcm_cfg)
elif self._config.comparison_mode == \
COMPARISON_MODE_DIFFERENCE:
cm = comedi_comparison_modes.FocusDiffCM
self.comparison_mode = cm(
self, self._config.focusdiffcm_cfg)
def _sync_mm_with_config(self):
"""Synchronise match mode with what's specified in the config.
This is used by config_to_logic as well as the run-time match
mode tab switching.
"""
if self.match_mode:
self.match_mode.close()
self.match_mode = None
if self._config.match_mode == MATCH_MODE_LANDMARK_SS:
# we have to create a new one in anycase! This gets
# called if we get a brand new config given to us, too
# much could have changed.
#if mm.__class__.__name__ != SStructLandmarksMM.__name__:
self.match_mode = comedi_match_modes.SStructLandmarksMM(
self, self._config.sstructlandmarksmm_cfg)
def _update_mmcm(self, disable_vis=False):
"""Update the current match mode and the comparison mode.
"""
if disable_vis:
self.comparison_mode.disable_vis()
self.match_mode.transform()
self.comparison_mode.update_vis()
# PUBLIC methods
def get_compvis_vtk(self):
"""Return rwi and renderer used for the compvis. Used mostly
by the various comparison modes.
"""
return (
self._view_frame.rwi_pane_compvis.rwi,
self._view_frame.rwi_pane_compvis.renderer
)
def get_data1(self):
"""Return data1 input.
"""
return self._data1_slice_viewer.get_input()
def get_data2m(self):
"""Return currently matched data2, i.e. the output of the
current match mode.
"""
return self.match_mode.get_output()
def render_all(self):
"""Method that calls Render() on the embedded RenderWindow.
Use this after having made changes to the scene.
"""
self._view_frame.render_all()
def set_cam_perspective(self):
for sv in self.sync_slice_viewers.slice_viewers:
sv.set_perspective()
sv.render()
self._config.cam_parallel = False
def set_cam_parallel(self):
for sv in self.sync_slice_viewers.slice_viewers:
sv.set_parallel()
sv.render()
self._config.cam_parallel = True
| Python |
# check python24/lib/code.py - exceptions raised only result in
# printouts. perhaps we want a real exception?
import code # deep magic
import md5
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin, WindowRenameMixin
import module_utils
import sys
import module_kits.wx_kit
from module_kits.wx_kit.python_shell_mixin import PythonShellMixin
import wx
NUMBER_OF_INPUTS = 5
NUMBER_OF_OUTPUTS = 5
EDITWINDOW_LABELS = ['Scratch', 'Setup', 'Execute']
class CodeRunner(IntrospectModuleMixin, ModuleBase, PythonShellMixin,
WindowRenameMixin):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self.inputs = [None] * NUMBER_OF_INPUTS
self.outputs = [None] * NUMBER_OF_OUTPUTS
self._config.scratch_src = self._config.setup_src = \
self._config.execute_src = ''
self._config_srcs = ['scratch_src',
'setup_src',
'execute_src']
# these are the real deals, i.e. the underlying logic
self._src_scratch = self._src_setup = self._src_execute = ''
self._srcs = ['_src_scratch', '_src_setup', '_src_execute']
# we use this to determine whether the current setup src has been
# executed or not
self._md5_setup_src = ''
self._create_view_frame()
PythonShellMixin.__init__(self, self._view_frame.shell_window,
module_manager)
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.view_frame_panel,
ok_default=False,
cancel_hotkey=False)
# more convenience bindings
self._editwindows = [self._view_frame.scratch_editwindow,
self._view_frame.setup_editwindow,
self._view_frame.execute_editwindow]
self.interp = self._view_frame.shell_window.interp
# set interpreter on all three our editwindows
for ew in self._editwindows:
ew.set_interp(self.interp)
self._bind_events()
self.interp.locals.update(
{'obj' : self})
# initialise macro packages
self.support_vtk(self.interp)
self.support_matplotlib(self.interp)
self.config_to_logic()
self.logic_to_config()
self.config_to_view()
self.view_initialised = True
self.view()
def close(self):
# parameter is exception_printer method
PythonShellMixin.close(self,
self._module_manager.log_error_with_exception)
for i in range(len(self.get_input_descriptions())):
self.set_input(i, None)
self._view_frame.Destroy()
del self._view_frame
ModuleBase.close(self)
def get_input_descriptions(self):
return ('Any input',) * NUMBER_OF_INPUTS
def get_output_descriptions(self):
return ('Dynamic output',) * NUMBER_OF_OUTPUTS
def set_input(self, idx, input_stream):
self.inputs[idx] = input_stream
def get_output(self, idx):
return self.outputs[idx]
def view_to_config(self):
for ew, cn, i in zip(self._editwindows, self._config_srcs,
range(len(self._editwindows))):
setattr(self._config, cn, ew.GetText())
self.set_editwindow_modified(i, False)
def config_to_view(self):
for ew, cn, i in zip(self._editwindows, self._config_srcs,
range(len(self._editwindows))):
ew.SetText(getattr(self._config, cn))
self.set_editwindow_modified(i, False)
def config_to_logic(self):
logic_changed = False
for cn,ln in zip(self._config_srcs, self._srcs):
c = getattr(self._config, cn)
l = getattr(self, ln)
if c != l:
setattr(self, ln, c)
logic_changed = True
return logic_changed
def logic_to_config(self):
config_changed = False
for cn,ln in zip(self._config_srcs, self._srcs):
c = getattr(self._config, cn)
l = getattr(self, ln)
if l != c:
setattr(self._config, cn, l)
config_changed = True
return config_changed
def execute_module(self):
# we only attempt running setup_src if its md5 is different from
# that of the previous setup_src that we attempted to run
hd = md5.md5(self._src_setup).hexdigest()
if hd != self._md5_setup_src:
self._md5_setup_src = hd
self._run_source(self._src_setup, raise_exceptions=True)
self._run_source(self._src_execute, raise_exceptions=True)
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
def _bind_events(self):
wx.EVT_MENU(self._view_frame, self._view_frame.file_open_id,
self._handler_file_open)
wx.EVT_MENU(self._view_frame, self._view_frame.file_save_id,
self._handler_file_save)
wx.EVT_MENU(self._view_frame, self._view_frame.run_id,
self._handler_run)
for i in range(len(self._editwindows)):
def observer_modified(ew, i=i):
self.set_editwindow_modified(i, True)
self._editwindows[i].observer_modified = observer_modified
def _create_view_frame(self):
import resources.python.code_runner_frame
reload(resources.python.code_runner_frame)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
resources.python.code_runner_frame.\
CodeRunnerFrame)
self._view_frame.main_splitter.SetMinimumPaneSize(50)
# tried both self._view_frame.shell_window setFocus /
# SetFocus. On Ubuntu 8.04, wxPython 2.8.7.1 this doesn't
# seem to work.
def _handler_file_open(self, evt):
try:
filename, t = self._open_python_file(self._view_frame)
except IOError, e:
self._module_manager.log_error_with_exception(
'Could not open file %s into CodeRunner edit: %s' %
(filename, str(e)))
else:
if filename is not None:
cew = self._get_current_editwindow()
cew.SetText(t)
self._view_frame.statusbar.SetStatusText(
'Loaded %s into current edit.' % (filename,))
def _handler_file_save(self, evt):
try:
cew = self._get_current_editwindow()
filename = self._saveas_python_file(cew.GetText(),
self._view_frame)
if filename is not None:
self._view_frame.statusbar.SetStatusText(
'Saved current edit to %s.' % (filename,))
except IOError, e:
self._module_manager.log_error_with_exception(
'Could not save CodeRunner edit to file %s: %s' %
(filename, str(e)))
def _handler_run(self, evt):
self.run_current_edit()
def _get_current_editwindow(self):
sel = self._view_frame.edit_notebook.GetSelection()
return [self._view_frame.scratch_editwindow,
self._view_frame.setup_editwindow,
self._view_frame.execute_editwindow][sel]
def run_current_edit(self):
cew = self._get_current_editwindow()
text = cew.GetText()
self._run_source(text)
self._view_frame.statusbar.SetStatusText(
'Current edit run completed.')
def set_editwindow_modified(self, idx, modified):
pt = EDITWINDOW_LABELS[idx]
if modified:
pt += ' *'
self._view_frame.edit_notebook.SetPageText(idx, pt)
| Python |
# implicits.py copyright (c) 2003 Charl P. Botha <cpbotha@ieee.org>
# $Id$
import gen_utils
from modules.viewers.slice3dVWRmodules.shared import s3dcGridMixin
import vtk
import wx
# -------------------------------------------------------------------------
class implicitInfo:
def __init__(self):
self.name = None
self.type = None
self.widget = None
self.bounds = None
self.function = None
class implicits(s3dcGridMixin):
_gridCols = [('Name', 100), ('Type', 75), ('Enabled', 0)]
_gridNameCol = 0
_gridTypeCol = 1
_gridEnabledCol = 2
_implicitTypes = ['Plane', 'Sphere']
_boundsTypes = ['Primary Input', 'Selected object', 'Visible objects',
'Manual']
def __init__(self, slice3dVWRThingy, implicitsGrid):
self.slice3dVWR = slice3dVWRThingy
self._grid = implicitsGrid
# dict with name as key, values are implicitInfo classes
self._implicitsDict = {}
# we have to update this function when:
# * a new implicit is created
# * an implicit is deleted
# * the user has adjusted the representative widget
self.outputImplicitFunction = vtk.vtkImplicitBoolean()
self.outputImplicitFunction.SetOperationTypeToUnion()
self._initialiseGrid()
self._setupGUI()
self._bindEvents()
def close(self):
# delete all implicits, the good way
# this shouldn't cause problems, because the whole slice3dVWR module
# has been disconnected by this time
dNames = self._implicitsDict.keys()
for dName in dNames:
self._deleteImplicit(dName)
# make sure we have no more bindings to any of the implicits data
self._implicitsDict.clear()
# various other thingies
self.slice3dVWR = None
self._grid.ClearGrid()
self._grid = None
def _createImplicitFromUI(self):
cf = self.slice3dVWR.controlFrame
implicitType = cf.implicitTypeChoice.GetStringSelection()
implicitName = cf.implicitNameText.GetValue()
if implicitType in self._implicitTypes:
if implicitName in self._implicitsDict:
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"You have to enter a unique name for the new implicit. "
"Please try again.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
#implicitWidget = None
ren = self.slice3dVWR._threedRenderer
# let's find out which bounds the user wanted
cf = self.slice3dVWR.controlFrame
bt = cf.implicitBoundsChoice.GetStringSelection()
pi = None
bounds = None
bti = self._boundsTypes.index(bt)
if bti == 0:
# primary input
pi = self.slice3dVWR.getPrimaryInput()
if pi == None:
md = wx.MessageDialog(
cf,
"There is no primary input. "
"Please try another bounds type.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
elif bti == 1:
# selected object
objs = self.slice3dVWR._tdObjects._getSelectedObjects()
if not objs:
md = wx.MessageDialog(
cf,
"No object has been selected. "
"Please try another bounds type or select an object.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
try:
prop = self.slice3dVWR._tdObjects.findPropByObject(objs[0])
bounds = prop.GetBounds()
except KeyError:
# this should never ever happen
return
elif bti == 2:
# visible objects
bounds = self.slice3dVWR._threedRenderer.\
ComputeVisiblePropBounds()
elif bti == 3:
# manual
v = cf.implicitManualBoundsText.GetValue()
t = gen_utils.textToTypeTuple(v, (-1, 1, -1, 1, -1, 1),
6, float)
cf.implicitManualBoundsText.SetValue(str(t))
if bounds:
b0 = bounds[1] - bounds[0]
b1 = bounds[3] - bounds[2]
b2 = bounds[5] - bounds[4]
if b0 <= 0 or b1 <= 0 or b2 <= 0:
# not good enough...
bounds = None
md = wx.MessageDialog(
cf,
"Resultant bounds are invalid. "
"Please try again.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
# at this stage, you MUST have pi or bounds!
self._createImplicit(implicitType, implicitName, bounds, pi)
def _createImplicit(self, implicitType, implicitName, bounds, primaryInput):
if implicitType in self._implicitTypes and \
implicitName not in self._implicitsDict:
pi = primaryInput
rwi = self.slice3dVWR.threedFrame.threedRWI
implicitInfoBounds = None
if implicitType == "Plane":
implicitWidget = vtk.vtkImplicitPlaneWidget()
implicitWidget.SetPlaceFactor(1.25)
if pi != None:
implicitWidget.SetInput(pi)
implicitWidget.PlaceWidget()
b = pi.GetBounds()
implicitWidget.SetOrigin(b[0], b[2], b[4])
implicitInfoBounds = b
elif bounds != None:
implicitWidget.PlaceWidget(bounds)
implicitWidget.SetOrigin(bounds[0], bounds[2], bounds[4])
implicitInfoBounds = bounds
else:
# this can never happen
pass
implicitWidget.SetInteractor(rwi)
implicitWidget.On()
# create the implicit function
implicitFunction = vtk.vtkPlane()
# sync it to the initial widget
self._syncPlaneFunctionToWidget(implicitWidget)
# add it to the output
self.outputImplicitFunction.AddFunction(implicitFunction)
# now add an observer to the widget
def observerImplicitPlaneWidget(widget, eventName):
# sync it to the initial widget
ret = self._syncPlaneFunctionToWidget(widget)
# also select the correct grid row
if ret != None:
name, ii = ret
row = self.findGridRowByName(name)
if row >= 0:
self._grid.SelectRow(row)
oId = implicitWidget.AddObserver('EndInteractionEvent',
observerImplicitPlaneWidget)
elif implicitType == "Sphere":
implicitWidget = vtk.vtkSphereWidget()
implicitWidget.SetPlaceFactor(1.25)
implicitWidget.TranslationOn()
implicitWidget.ScaleOn()
#implicitWidget.HandleVisibilityOn()
if pi != None:
implicitWidget.SetInput(pi)
implicitWidget.PlaceWidget()
b = pi.GetBounds()
implicitInfoBounds = b
#implicitWidget.SetOrigin(b[0], b[2], b[4])
elif bounds != None:
implicitWidget.PlaceWidget(bounds)
implicitInfoBounds = bounds
#implicitWidget.SetOrigin(bounds[0], bounds[2], bounds[4])
else:
# this can never happen
pass
implicitWidget.SetInteractor(rwi)
implicitWidget.On()
# create the implicit function
implicitFunction = vtk.vtkSphere()
# sync it to the initial widget
self._syncSphereFunctionToWidget(implicitWidget)
# add it to the output
self.outputImplicitFunction.AddFunction(implicitFunction)
# now add an observer to the widget
def observerImplicitSphereWidget(widget, eventName):
# sync it to the initial widget
ret = self._syncSphereFunctionToWidget(widget)
# also select the correct grid row
if ret != None:
name, ii = ret
row = self.findGridRowByName(name)
if row >= 0:
self._grid.SelectRow(row)
oId = implicitWidget.AddObserver('EndInteractionEvent',
observerImplicitSphereWidget)
if implicitWidget:
# set the priority so it gets interaction before the
# ImagePlaneWidget. 3D widgets have default priority 0.5,
# so we assign our widgets just a tad higher. (voiwidget
# has 0.6 for example)
# NB: in a completely weird twist of events, only slices
# added AFTER this widget will act like they have lower
# priority. The initial slice still takes events from us!
implicitWidget.SetPriority(0.7)
# add to our internal thingy
ii = implicitInfo()
ii.name = implicitName
ii.type = implicitType
ii.widget = implicitWidget
ii.bounds = implicitInfoBounds
ii.oId = oId
ii.function = implicitFunction
self._implicitsDict[implicitName] = ii
# now add to the grid
nrGridRows = self._grid.GetNumberRows()
self._grid.AppendRows()
self._grid.SetCellValue(nrGridRows, self._gridNameCol,
implicitName)
self._grid.SetCellValue(nrGridRows, self._gridTypeCol,
implicitType)
# set the relevant cells up for Boolean
for col in [self._gridEnabledCol]:
self._grid.SetCellRenderer(nrGridRows, col,
wx.grid.GridCellBoolRenderer())
self._grid.SetCellAlignment(nrGridRows, col,
wx.ALIGN_CENTRE,
wx.ALIGN_CENTRE)
self._setImplicitEnabled(ii.name, True)
def _deleteImplicit(self, name):
dRow = self.findGridRowByName(name)
if dRow >= 0:
# delete that row
self._grid.DeleteRows(dRow)
ii = self._implicitsDict[name]
# take care of the widget
w = ii.widget
w.RemoveObserver(ii.oId)
w.Off()
w.SetInteractor(None)
self.outputImplicitFunction.RemoveFunction(ii.function)
# finally remove our record of everything
del self._implicitsDict[name]
def _appendGridCommandsToMenu(self, menu, eventWidget, disable=True):
"""Appends the points grid commands to a menu. This can be used
to build up the context menu or the drop-down one.
"""
commandsTuple = [
('&Create Implicit', 'Create a new implicit with the currently '
'selected name and type',
self._handlerCreateImplicit, False),
('---',),
('Select &All', 'Select all implicits',
self._handlerSelectAllImplicits, False),
('D&Eselect All', 'Deselect all implicits',
self._handlerDeselectAllImplicits, False),
('---',),
('&Show', 'Show selected implicits',
self._handlerShowImplicits, True),
('&Hide', 'Hide selected implicits',
self._handlerHideImplicits, True),
('---',), # important! one-element tuple...
('&Rename',
'Rename selected implicits',
self._handlerRenameImplicits, True),
('&Flip',
'Flip selected implicits if possible.',
self._handlerFlipImplicits, True),
('---',), # important! one-element tuple...
('&Delete', 'Delete selected implicits',
self._handlerDeleteImplicits, True)]
disableList = self._appendGridCommandsTupleToMenu(
menu, eventWidget, commandsTuple, disable)
return disableList
def _bindEvents(self):
controlFrame = self.slice3dVWR.controlFrame
# the store button
wx.EVT_BUTTON(controlFrame, controlFrame.createImplicitButtonId,
self._handlerCreateImplicit)
wx.grid.EVT_GRID_CELL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_LABEL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_RANGE_SELECT(
self._grid, self._handlerGridRangeSelect)
def enablePointsInteraction(self, enable):
"""Enable/disable points interaction in the 3d scene.
"""
if enable:
for selectedPoint in self._pointsList:
if selectedPoint['pointWidget']:
selectedPoint['pointWidget'].On()
else:
for selectedPoint in self._pointsList:
if selectedPoint['pointWidget']:
selectedPoint['pointWidget'].Off()
def findNameImplicitInfoUsingWidget(self, widget):
# let's find widget in our records
found = False
for name, ii in self._implicitsDict.items():
if ii.widget == widget:
found = True
break
if found:
return name, ii
else:
return None
def findGridRowByName(self, name):
nrGridRows = self._grid.GetNumberRows()
rowFound = False
row = 0
while not rowFound and row < nrGridRows:
value = self._grid.GetCellValue(row, self._gridNameCol)
rowFound = (value == name)
row += 1
if rowFound:
# prepare and return the row
row -= 1
return row
else:
return -1
def getImplicitsState(self):
"""Get state of current implicits in a pickle-able data structure.
"""
implicitsState = []
for implicitName, implicitInfo in self._implicitsDict.items():
functionState = None
if implicitInfo.type == 'Plane':
# we need to get origin and normal
o = implicitInfo.widget.GetOrigin()
n = implicitInfo.widget.GetNormal()
functionState = (o, n)
elif implicitInfo.type == 'Sphere':
# we need to get center and radius
c = implicitInfo.widget.GetCenter()
r = implicitInfo.widget.GetRadius()
functionState = (c, r)
else:
break
implicitsState.append({'name' : implicitName,
'type' : implicitInfo.type,
'bounds' : implicitInfo.bounds,
'fState' : functionState})
return implicitsState
def setImplicitsState(self, implicitsState):
"""Given an implicitsState data structure, create implicits exactly
as they were when the implicitsState was generated.
"""
# first delete all implicits
for dname in self._implicitsDict.keys():
self._deleteImplicit(dname)
# now start creating new ones
for state in implicitsState:
self._createImplicit(state['type'], state['name'], state['bounds'], None)
if state['name'] in self._implicitsDict:
# succesful creation - now restore function state
ii = self._implicitsDict[state['name']]
if ii.type == 'Plane':
ii.widget.SetOrigin(state['fState'][0])
ii.widget.SetNormal(state['fState'][1])
self._syncPlaneFunctionToWidget(ii.widget)
elif ii.type == 'Sphere':
ii.widget.SetCenter(state['fState'][0])
ii.widget.SetRadius(state['fState'][1])
self._syncSphereFunctionToWidget(ii.widget)
else:
pass
def _getSelectedImplicitNames(self):
"""Return a list of names representing the currently selected
implicits.
"""
selRows = self._grid.GetSelectedRows()
sNames = []
for sRow in selRows:
sNames.append(self._grid.GetCellValue(sRow, self._gridNameCol))
return sNames
def _handlerFlipImplicits(self, event):
"""If any of the selected implicits are of 'Plane' type, flip it, i.e.
change the direction of the normal.
"""
sNames = self._getSelectedImplicitNames()
for sName in sNames:
ii = self._implicitsDict[sName]
if ii.type == 'Plane':
# flip both the function and the widget
n = ii.function.GetNormal()
fn = [-1.0 * e for e in n]
ii.function.SetNormal(fn)
ii.widget.SetNormal(fn)
if sNames:
# if we don't re-render, we don't see the flipped thingies
self.slice3dVWR.render3D()
def _handlerGridRightClick(self, gridEvent):
"""This will popup a context menu when the user right-clicks on the
grid.
"""
imenu = wx.Menu('Implicits Context Menu')
self._appendGridCommandsToMenu(imenu, self._grid)
self._grid.PopupMenu(imenu, gridEvent.GetPosition())
def _handlerRenameImplicits(self, event):
selRows = self._grid.GetSelectedRows()
rNames = []
for sRow in selRows:
rNames.append(self._grid.GetCellValue(sRow, self._gridNameCol))
for rName in rNames:
self._renameImplicit(rName)
def _renameImplicit(self, name):
"""Pop-up text box asking the user for a new name.
"""
if name in self._implicitsDict:
newName = wx.GetTextFromUser(
'Please enter a new name for "%s".' % (name,),
'Implicit Rename', name)
if newName:
if newName in self._implicitsDict:
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"You have to enter a unique name. "
"Please try again.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
else:
# first the grid
row = self.findGridRowByName(name)
if row >= 0:
self._grid.SetCellValue(row, self._gridNameCol,
newName)
# do the actual renaming
ii = self._implicitsDict[name]
ii.name = newName
del self._implicitsDict[name]
self._implicitsDict[newName] = ii
def _handlerSelectAllImplicits(self, event):
# calling SelectAll and then GetSelectedRows() returns nothing
# so, we select row by row, and that does seem to work!
for row in range(self._grid.GetNumberRows()):
self._grid.SelectRow(row, True)
def _handlerDeselectAllImplicits(self, event):
self._grid.ClearSelection()
def _handlerDeleteImplicits(self, event):
selRows = self._grid.GetSelectedRows()
# first get a list of names
dNames = []
for sRow in selRows:
name = self._grid.GetCellValue(sRow, self._gridNameCol)
dNames.append(name)
for name in dNames:
self._deleteImplicit(name)
def _handlerHideImplicits(self, event):
selectedRows = self._grid.GetSelectedRows()
for sRow in selectedRows:
name = self._grid.GetCellValue(sRow, self._gridNameCol)
self._setImplicitEnabled(name, False)
def _handlerShowImplicits(self, event):
selectedRows = self._grid.GetSelectedRows()
for sRow in selectedRows:
name = self._grid.GetCellValue(sRow, self._gridNameCol)
self._setImplicitEnabled(name, True)
def _handlerImplicitsInteractionOn(self, event):
for idx in self._grid.GetSelectedRows():
self._pointsList[idx]['pointWidget'].On()
def _handlerImplicitsInteractionOff(self, event):
for idx in self._grid.GetSelectedRows():
self._pointsList[idx]['pointWidget'].Off()
def _handlerCreateImplicit(self, event):
"""Create 3d widget and the actual implicit function.
"""
self._createImplicitFromUI()
def hasWorldPoint(self, worldPoint):
worldPoints = [i['world'] for i in self._pointsList]
if worldPoint in worldPoints:
return True
else:
return False
def _initialiseGrid(self):
# setup default selection background
gsb = self.slice3dVWR.gridSelectionBackground
self._grid.SetSelectionBackground(gsb)
# delete all existing columns
self._grid.DeleteCols(0, self._grid.GetNumberCols())
# we need at least one row, else adding columns doesn't work (doh)
self._grid.AppendRows()
# setup columns
self._grid.AppendCols(len(self._gridCols))
for colIdx in range(len(self._gridCols)):
# add labels
self._grid.SetColLabelValue(colIdx, self._gridCols[colIdx][0])
# set size according to labels
self._grid.AutoSizeColumns()
for colIdx in range(len(self._gridCols)):
# now set size overrides
size = self._gridCols[colIdx][1]
if size > 0:
self._grid.SetColSize(colIdx, size)
# make sure we have no rows again...
self._grid.DeleteRows(0, self._grid.GetNumberRows())
def _renameImplicits(self, Idxs, newName):
for idx in Idxs:
self._renameImplicit(idx, newName)
def _setImplicitEnabled(self, implicitName, enabled):
if implicitName in self._implicitsDict:
ii = self._implicitsDict[implicitName]
# in our internal list
ii.enabled = bool(enabled)
# the widget
if ii.widget:
ii.widget.SetEnabled(ii.enabled)
# in the grid
gridRow = self.findGridRowByName(implicitName)
if gridRow >= 0:
gen_utils.setGridCellYesNo(
self._grid, gridRow, self._gridEnabledCol, ii.enabled)
def _setupGUI(self):
# fill out our drop-down menu
self._disableMenuItems = self._appendGridCommandsToMenu(
self.slice3dVWR.controlFrame.implicitsMenu,
self.slice3dVWR.controlFrame, disable=True)
# setup choice component
# first clear
cf = self.slice3dVWR.controlFrame
cf.implicitTypeChoice.Clear()
for implicitType in self._implicitTypes:
cf.implicitTypeChoice.Append(implicitType)
cf.implicitTypeChoice.SetSelection(0)
cf.implicitNameText.SetValue("implicit 0")
# setup bounds type thingies
cf.implicitBoundsChoice.Clear()
for t in self._boundsTypes:
cf.implicitBoundsChoice.Append(t)
cf.implicitBoundsChoice.SetSelection(0)
# setup default value for the manual bounds thingy
cf.implicitManualBoundsText.SetValue('(-1, 1, -1, 1, -1, 1)')
def _syncPlaneFunctionToWidget(self, widget):
# let's find widget in our records
found = False
for name, ii in self._implicitsDict.items():
if ii.widget == widget:
found = True
break
if found:
ii.function.SetOrigin(ii.widget.GetOrigin())
# FIXME: incorporate "sense" setting
ii.function.SetNormal(ii.widget.GetNormal())
self._auto_execute()
# as a convenience, we return the name and ii
return name, ii
else:
return None
def _syncSphereFunctionToWidget(self, widget):
r = self.findNameImplicitInfoUsingWidget(widget)
if r != None:
name, ii = r
ii.function.SetCenter(ii.widget.GetCenter())
ii.function.SetRadius(ii.widget.GetRadius())
self._auto_execute()
# as a convenience, we return the name and ii
return name, ii
else:
return None
def _auto_execute(self):
"""Invalidate part 2 of the slice3dVWR module (the implicits part) and
request an auto execution.
This method should be called when any of the implicits is modified.
"""
mm = self.slice3dVWR._module_manager
# part 2 is responsible for the implicit output
mm.modify_module(self.slice3dVWR, 2)
mm.request_auto_execute_network(self.slice3dVWR)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import operator
import module_utils
import vtk
import wx
class sliceDirection:
"""Class encapsulating all logic behind a single direction.
This class contains the IPWs and related paraphernalia for all layers
(primary + overlays) representing a single view direction. It optionally
has its own window with an orthogonal view.
"""
overlayModes = {'Green Fusion' : 'greenFusion',
'Red Fusion' : 'redFusion',
'Blue Fusion' : 'blueFusion',
'Hue Fusion' : 'hueFusion',
'Hue/Value Fusion' : 'hueValueFusion',
'Green Opacity Range' : 'greenOpacityRange',
'Red Opacity Range' : 'redOpacityRange',
'Blue Opacity Range' : 'blueOpacityRange',
'Hue Opacity Range' : 'hueOpacityRange',
'Primary LUT fusion' : 'primaryLUTFusion'}
def __init__(self, name, sliceDirections, defaultPlaneOrientation=2):
self.sliceDirections = sliceDirections
self._defaultPlaneOrientation = 2
# orthoPipeline is a list of dictionaries. each dictionary is:
# {'planeSource' : vtkPlaneSource, 'planeActor' : vtkActor,
# 'textureMapToPlane' : vtkTextureMapToPlane,
# '
self._orthoPipeline = []
# this is the frame that we will use to display our slice pipeline
self._orthoViewFrame = None
#
self._renderer = None
# list of vtkImagePlaneWidgets (first is "primary", rest are overlays)
self._ipws = []
# then some state variables
self._enabled = True
self._interactionEnabled = True
# list of objects that want to be contoured by this slice
self._contourObjectsDict = {}
self.overlayMode = 'greenOpacityRange'
self.fusionAlpha = 0.4
# we'll use this to store the polydata of our primary slice
self._primaryCopyPlaneSource = vtk.vtkPlaneSource()
self._primaryCopyPlaneSource.SetXResolution(64)
self._primaryCopyPlaneSource.SetYResolution(64)
self.primaryPolyData = self._primaryCopyPlaneSource.GetOutput()
def addContourObject(self, contourObject, prop3D):
"""Activate contouring for the contourObject. The contourObject
is usually a tdObject and specifically a vtkPolyData. We also
need the prop3D that represents this polydata in the 3d scene.
"""
if self._contourObjectsDict.has_key(contourObject):
# we already have this, thanks
return
try:
contourable = contourObject.IsA('vtkPolyData')
except:
contourable = False
if contourable:
# we need a cutter to calculate the contours and then a stripper
# to string them all together
cutter = vtk.vtkCutter()
plane = vtk.vtkPlane()
cutter.SetCutFunction(plane)
trfm = vtk.vtkTransform()
trfm.SetMatrix(prop3D.GetMatrix())
trfmFilter = vtk.vtkTransformPolyDataFilter()
trfmFilter.SetTransform(trfm)
trfmFilter.SetInput(contourObject)
cutter.SetInput(trfmFilter.GetOutput())
stripper = vtk.vtkStripper()
stripper.SetInput(cutter.GetOutput())
#
#tubef = vtk.vtkTubeFilter()
#tubef.SetNumberOfSides(12)
#tubef.SetRadius(0.5)
#tubef.SetInput(stripper.GetOutput())
# and create the overlay at least for the 3d renderer
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(stripper.GetOutput())
mapper.ScalarVisibilityOff()
actor = vtk.vtkActor()
actor.SetMapper(mapper)
c = self.sliceDirections.slice3dVWR._tdObjects.getObjectColour(
contourObject)
actor.GetProperty().SetColor(c)
actor.GetProperty().SetInterpolationToFlat()
# add it to the renderer
self.sliceDirections.slice3dVWR._threedRenderer.AddActor(actor)
# add all necessary metadata to our dict
contourDict = {'contourObject' : contourObject,
'contourObjectProp' : prop3D,
'trfmFilter' : trfmFilter,
'cutter' : cutter,
'tdActor' : actor}
self._contourObjectsDict[contourObject] = contourDict
# now sync the bugger
self.syncContourToObject(contourObject)
def addAllContourObjects(self):
cos = self.sliceDirections.slice3dVWR._tdObjects.getContourObjects()
for co in cos:
prop = self.sliceDirections.slice3dVWR._tdObjects.\
findPropByObject(co)
# addContourObject is clever enough not to try and add contours
# for objects which aren't contourable
self.addContourObject(co, prop)
def removeAllContourObjects(self):
contourObjects = self._contourObjectsDict.keys()
for co in contourObjects:
self.removeContourObject(co)
def removeContourObject(self, contourObject):
if contourObject in self._contourObjectsDict:
# let's remove it from the renderer
actor = self._contourObjectsDict[contourObject]['tdActor']
self.sliceDirections.slice3dVWR._threedRenderer.RemoveActor(actor)
# and remove it from the dict
del self._contourObjectsDict[contourObject]
def syncContourToObjectViaProp(self, prop):
for coi in self._contourObjectsDict.items():
if coi[1]['contourObjectProp'] == prop:
# there can be only one (and contourObject is the key)
self.syncContourToObject(coi[0])
# break out of the innermost loop
break
def syncContourToObject(self, contourObject):
"""Update the contour for the given contourObject. contourObject
corresponds to a tdObject in tdObjects.py.
"""
# yes, in and not in work on dicts, doh
if contourObject not in self._contourObjectsDict:
return
# if there are no ipws, we have no planes!
if not self._ipws:
return
# get the contourObject metadata
contourDict = self._contourObjectsDict[contourObject]
cutter = contourDict['cutter']
plane = cutter.GetCutFunction()
# adjust the implicit plane (if we got this far (i.e.
normal = self._ipws[0].GetNormal()
origin = self._ipws[0].GetOrigin()
plane.SetNormal(normal)
plane.SetOrigin(origin)
# also make sure the transform knows about the new object position
contourDict['trfmFilter'].GetTransform().SetMatrix(
contourDict['contourObjectProp'].GetMatrix())
# calculate it
cutter.Update()
def addData(self, inputData):
"""Add inputData as a new layer.
"""
if inputData is None:
raise Exception, "Hallo, the inputData is none. Doing nothing."
# make sure it's vtkImageData
if hasattr(inputData, 'IsA') and inputData.IsA('vtkImageData'):
# if we already have this data as input, we can't take it
for ipw in self._ipws:
if inputData is ipw.GetInput():
raise Exception,\
"This inputData already exists in this slice."
# make sure it's all up to date
inputData.Update()
if self._ipws:
# this means we already have data and what's added now can
# only be allowed as overlay
# now check if the new data classifies as overlay
mainInput = self._ipws[0].GetInput()
if inputData.GetWholeExtent() != mainInput.GetWholeExtent():
raise Exception, \
"The extent of this inputData " \
"does not match the extent of the existing input" \
", so it can't be used as overlay:\n"\
"[%s != %s]" % \
(inputData.GetWholeExtent(),
mainInput.GetWholeExtent())
# differences in spacing between new input and existing input
spacingDiff = [abs(i - j) for (i,j) in
zip(inputData.GetSpacing(),
mainInput.GetSpacing())]
# maximal allowable difference
spacingEpsilon = 0.0001
if spacingDiff[0] > spacingEpsilon or \
spacingDiff[1] > spacingEpsilon or \
spacingDiff[2] > spacingEpsilon:
raise Exception, \
"The spacing of this inputData " \
"does not match the spacing of the existing input" \
", so it can't be used as overlay.\n"\
"[%s != %s]" % \
(inputData.GetSpacing(),
mainInput.GetSpacing())
self._ipws.append(vtk.vtkImagePlaneWidget())
try:
# with invalid data, this will throw an exception!
self._ipws[-1].SetInput(inputData)
except RuntimeError, e:
# so we undo any changes so far, and re-raise the exception
# calling code will then not make any accounting changes, so
# no harm done.
self._ipws[-1].SetInput(None)
del self._ipws[-1]
raise
self._ipws[-1].UserControlledLookupTableOn()
self._ipws[-1].SetResliceInterpolateToNearestNeighbour()
# now make sure they have the right lut and are synched
# with the main IPW
self._resetOverlays()
if self._orthoViewFrame:
# also update our orthoView
self._createOrthoPipelineForNewIPW(self._ipws[-1])
self._syncOrthoView()
self._orthoViewFrame.RWI.Render()
# if self._ipws ...
else:
# this means primary data!
self._ipws.append(vtk.vtkImagePlaneWidget())
#self._ipws[-1].GetPolyDataAlgorithm().SetXResolution(64)
#self._ipws[-1].GetPolyDataAlgorithm().SetYResolution(64)
try:
# with invalid data, this will throw an exception!
self._ipws[-1].SetInput(inputData)
except RuntimeError, e:
# so we undo any changes so far, and re-raise the exception
# calling code will then not make any accounting changes, so
# no harm done.
self._ipws[-1].SetInput(None)
del self._ipws[-1]
raise
self._ipws[-1].SetPicker(self.sliceDirections.ipwPicker)
# GetColorMap() -- new VTK CVS
self._ipws[-1].GetColorMap().SetOutputFormatToRGB()
#self._ipws[-1].GetImageMapToColors().SetOutputFormatToRGB()
# now make callback for the ipw
self._ipws[-1].AddObserver('StartInteractionEvent',
lambda e, o:
self._ipwStartInteractionCallback())
self._ipws[-1].AddObserver('InteractionEvent',
lambda e, o:
self._ipwInteractionCallback())
self._ipws[-1].AddObserver('EndInteractionEvent',
lambda e, o:
self._ipwEndInteractionCallback())
self._resetPrimary()
# now let's update our orthoView as well (if applicable)
if self._orthoViewFrame:
self._createOrthoPipelineForNewIPW(self._ipws[-1])
# and because it's a primary, we have to reset as well
# self._resetOrthoView() also calls self.SyncOrthoView()
self._resetOrthoView()
self._orthoViewFrame.Render()
# also check for contourObjects (primary data is being added)
self.addAllContourObjects()
# make sure our output polydata is in sync with the new prim
self._syncOutputPolyData()
# first we name ourselves... (ImageReslice loses the input
# scalars name)
rsoPD = self._ipws[-1].GetResliceOutput().GetPointData()
rsoScalars = rsoPD.GetScalars()
if rsoScalars:
if rsoScalars.GetName():
print "sliceDirection.py: WARNING - ResliceOutput " \
"scalars are named."
else:
rsoScalars.SetName('ipw_reslice_output')
# and add ourselvess to the output unstructured grid pointer
self.sliceDirections.ipwAppendFilter.AddInput(
self._ipws[-1].GetResliceOutput())
def updateData(self, prevInputData, newInputData):
"""Change data-object on an existing connection.
"""
primaryUpdated = False
for i in range(len(self._ipws)):
ipw = self._ipws[i]
if prevInputData is ipw.GetInput():
# set new input
ipw.SetInput(newInputData)
if i == 0:
primaryUpdated = True
# this data can occur only once
break
if primaryUpdated:
self._resetPrimary()
self._syncOutputPolyData()
self._syncOverlays()
else:
# the update was for an overlay
self._syncOverlays()
def close(self):
"""Shut down everything."""
# take out all the contours
self.removeAllContourObjects()
# take out the orthoView
self.destroyOrthoView()
# first take care of all our ipws
inputDatas = [i.GetInput() for i in self._ipws]
for inputData in inputDatas:
self.removeData(inputData)
# kill the whole list
del self._ipws
# make sure we don't point to our sliceDirections
del self.sliceDirections
def createOrthoView(self):
"""Create an accompanying orthographic view of the sliceDirection
encapsulated by this object.
"""
# there can be only one orthoPipeline
if not self._orthoPipeline:
import modules.resources.python.slice3dVWRFrames
# import our wxGlade-generated frame
ovf = modules.resources.python.slice3dVWRFrames.orthoViewFrame
self._orthoViewFrame = ovf(
self.sliceDirections.slice3dVWR.threedFrame, id=-1,
title='dummy')
self._orthoViewFrame.SetIcon(module_utils.get_module_icon())
self._renderer = vtk.vtkRenderer()
self._renderer.SetBackground(0.5, 0.5, 0.5)
self._orthoViewFrame.RWI.GetRenderWindow().AddRenderer(
self._renderer)
istyle = vtk.vtkInteractorStyleImage()
self._orthoViewFrame.RWI.SetInteractorStyle(istyle)
wx.EVT_CLOSE(self._orthoViewFrame,
lambda e, s=self: s.destroyOrthoView)
wx.EVT_BUTTON(self._orthoViewFrame,
self._orthoViewFrame.closeButtonId,
lambda e, s=self: s.destroyOrthoView)
for ipw in self._ipws:
self._createOrthoPipelineForNewIPW(ipw)
if self._ipws:
self._resetOrthoView()
self._orthoViewFrame.Show(True)
def destroyOrthoView(self):
"""Destroy the orthoView and disconnect everything associated
with it.
"""
if self._orthoViewFrame:
for layer in self._orthoPipeline:
self._renderer.RemoveActor(layer['planeActor'])
# this will disconnect the texture (it will destruct shortly)
layer['planeActor'].SetTexture(None)
# this should take care of all references
layer = []
self._orthoPipeline = []
# remove our binding to the renderer
self._renderer = None
# remap the RenderWindow (it will create its own new window and
# disappear when we remove our binding to the viewFrame)
self._orthoViewFrame.RWI.GetRenderWindow().WindowRemap()
# finally take care of the GUI
self._orthoViewFrame.Destroy()
# and take care to remove our viewFrame binding
self._orthoViewFrame = None
def enable(self):
"""Switch this sliceDirection on."""
self._enabled = True
for ipw in self._ipws:
ipw.On()
# alse re-enable all contours for this slice
for (contourObject, contourDict) in self._contourObjectsDict.items():
contourDict['tdActor'].VisibilityOn()
def enableInteraction(self):
self._interactionEnabled = True
if self._ipws:
self._ipws[0].SetInteraction(1)
def disable(self):
"""Switch this sliceDirection off."""
self._enabled = False
for ipw in self._ipws:
ipw.Off()
# alse disable all contours for this slice
for (contourObject, contourDict) in self._contourObjectsDict.items():
contourDict['tdActor'].VisibilityOff()
def disableInteraction(self):
self._interactionEnabled = False
if self._ipws:
self._ipws[0].SetInteraction(0)
def getEnabled(self):
return self._enabled
def getInteractionEnabled(self):
return self._interactionEnabled
def getOrthoViewEnabled(self):
return self._orthoViewFrame is not None
def getNumberOfLayers(self):
return len(self._ipws)
def get_slice_geometry(self):
# get the plane geometry of the slice
if self._ipws:
ipw = self._ipws[0]
return ipw.GetOrigin(), ipw.GetPoint1(), ipw.GetPoint2()
else:
return None
def set_slice_geometry(self, geometry):
# restore a plane geometry
if self._ipws and geometry:
# we only do the primary
ipw = self._ipws[0]
ipw.SetOrigin(geometry[0])
ipw.SetPoint1(geometry[1])
ipw.SetPoint2(geometry[2])
ipw.UpdatePlacement()
# and let this take care of the rest.
self._syncOverlays()
def lockToPoints(self, p0, p1, p2):
"""Make the plane co-planar with the plane defined by the three points.
"""
if not self._ipws:
# we can't do anything if we don't have a primary IPW
return
# we pick p0 as the origin
p1o = map(operator.sub, p1, p0)
p2o = map(operator.sub, p2, p0)
planeNormal = [0,0,0]
vtk.vtkMath.Cross(p1o, p2o, planeNormal)
pnSize = vtk.vtkMath.Normalize(planeNormal)
if pnSize > 0:
try:
planeSource = self._ipws[0].GetPolyDataAlgorithm()
except AttributeError:
planeSource = self._ipws[0].GetPolyDataSource()
planeSource.SetNormal(planeNormal)
planeSource.SetCenter(p0)
self._ipws[0].UpdatePlacement()
self._syncAllToPrimary()
else:
wx.wxLogMessage("The points you have chosen don't uniquely "
"define a plane. Please try again.")
def pushSlice(self, val):
if self._ipws:
try:
planeSource = self._ipws[0].GetPolyDataAlgorithm()
except AttributeError:
planeSource = self._ipws[0].GetPolyDataSource()
planeSource.Push(val)
self._ipws[0].UpdatePlacement()
self._syncAllToPrimary()
def delta_slice(self, delta):
"""Move to the delta slices fw/bw, IF the IPW is currently
aligned with one of the axes.
"""
ipw = self._ipws[0]
if ipw.GetPlaneOrientation() < 3:
ci = ipw.GetSliceIndex()
ipw.SetSliceIndex(ci + delta)
self._syncAllToPrimary()
def removeData(self, inputData):
# search for the ipw with this inputData
ipwL = [i for i in self._ipws if i.GetInput() is inputData]
if ipwL:
# there can be only one!
ipw = ipwL[0]
# switch it off
ipw.Off()
# disconnect it from the RWI
ipw.SetInteractor(None)
# we always try removing the input from the appendfilter
self.sliceDirections.ipwAppendFilter.RemoveInput(
ipw.GetResliceOutput())
# disconnect the input
ipw.SetInput(None)
# finally delete our reference
idx = self._ipws.index(ipw)
del self._ipws[idx]
if not self._ipws:
# if there is no data left, we also have to remove all contours
self.removeAllContourObjects()
def resetToACS(self, acs):
"""Reset the current sliceDirection to Axial, Coronal or Sagittal.
"""
# colours of imageplanes; we will use these as keys
ipw_cols = [(1,0,0), (0,1,0), (0,0,1)]
orientation = 2 - acs
for ipw in self._ipws:
# this becomes the new default for resets as well
self._defaultPlaneOrientation = orientation
ipw.SetPlaneOrientation(orientation)
ipw.GetPlaneProperty().SetColor(ipw_cols[orientation])
self._syncAllToPrimary()
def _createOrthoPipelineForNewIPW(self, ipw):
"""This will create and append all the necessary constructs for a
single new layer (ipw) to the self._orthoPipeline.
Make sure you only call this method if the orthoView exists!
After having done this, you still need to call _syncOrthoView() or
_resetOrthoView() if you've added a new primary.
"""
_ps = vtk.vtkPlaneSource()
_pa = vtk.vtkActor()
_tm2p = vtk.vtkTextureMapToPlane()
self._orthoPipeline.append(
{'planeSource' : _ps,
'planeActor' : _pa,
'textureMapToPlane': _tm2p})
_tm2p.AutomaticPlaneGenerationOff()
_tm2p.SetInput(_ps.GetOutput())
mapper = vtk.vtkPolyDataMapper()
mapper.SetInput(_tm2p.GetOutput())
_pa.SetMapper(mapper)
otherTexture = ipw.GetTexture()
# we don't just use the texture, else VTK goes mad re-uploading
# the same texture unnecessarily... let's just make use of the
# same input, we get much more effective use of the
# host->GPU bus
texture = vtk.vtkTexture()
texture.SetInterpolate(otherTexture.GetInterpolate())
texture.SetQuality(otherTexture.GetQuality())
texture.MapColorScalarsThroughLookupTableOff()
texture.RepeatOff()
texture.SetInput(otherTexture.GetInput())
_pa.SetTexture(texture)
self._renderer.AddActor(_pa)
def _resetOverlays(self):
"""Rest all overlays with default LUT, plane orientation and
start position."""
if len(self._ipws) > 1:
# iterate through overlay layers
for ipw in self._ipws[1:]:
lut = vtk.vtkLookupTable()
ipw.SetLookupTable(lut)
self._setOverlayLookupTable(ipw)
ipw.SetInteractor(
self.sliceDirections.slice3dVWR.threedFrame.threedRWI)
# default axial orientation
ipw.SetPlaneOrientation(self._defaultPlaneOrientation)
ipw.SetSliceIndex(0)
ipw.On()
ipw.InteractionOff()
self._syncOverlays()
def _resetOrthoView(self):
"""Calling this will reset the orthogonal camera and bring us in
synchronisation with the primary and overlays.
"""
if self._orthoPipeline and self._ipws:
self._syncOrthoView()
# just get the first planesource
planeSource = self._orthoPipeline[0]['planeSource']
# let's setup the camera
icam = self._renderer.GetActiveCamera()
icam.SetPosition(planeSource.GetCenter()[0],
planeSource.GetCenter()[1], 10)
icam.SetFocalPoint(planeSource.GetCenter())
icam.OrthogonalizeViewUp()
icam.SetViewUp(0,1,0)
icam.SetClippingRange(1,11)
v2 = map(operator.sub, planeSource.GetPoint2(),
planeSource.GetOrigin())
n2 = vtk.vtkMath.Normalize(v2)
icam.SetParallelScale(n2 / 2.0)
icam.ParallelProjectionOn()
def _resetPrimary(self):
"""Reset primary layer.
"""
if self._ipws:
inputData = self._ipws[0].GetInput()
# first make sure that the WHOLE primary will get updated
# when we render, else we get stupid single slice renderings!
inputData.UpdateInformation()
inputData.SetUpdateExtentToWholeExtent()
inputData.Update()
# calculate default window/level once (same as used
# by vtkImagePlaneWidget)
(dmin,dmax) = inputData.GetScalarRange()
import external.fpconst as fpconst
if fpconst.isNaN(dmin) or fpconst.isInf(dmin) or \
fpconst.isNaN(dmax) or fpconst.isInf(dmax):
# sometimes one of the values is infinite
# in that case, we set a window level that should be
# appropriate for many CT and MRI datasets
# if we don't, calculated window could be INF.
iwindow = 4000
ilevel = 1000
else:
iwindow = dmax - dmin
ilevel = 0.5 * (dmin + dmax)
# this doesn't work anymore. We'll have to pack the
# Window/Level data in a field like we do with the
# orientation.
inputData_source = inputData.GetSource()
try:
window = inputData_source.GetWindowWidth()
print "s3dv: Reading LEVEL from DICOM."
except AttributeError:
window = iwindow
print "s3dv: Estimating LEVEL."
try:
level = inputData_source.GetWindowCenter()
print "s3dv: Reading WINDOW from DICOM."
except AttributeError:
level = ilevel
print "s3dv: Estimating WINDOW."
# if window is negative, it means the DICOM reader couldn't
# extract that information and we also have to estimate
if window < 0.0:
window = iwindow
level = ilevel
print "s3dv: DICOM W/L invalid, estimating."
# colours of imageplanes; we will use these as keys
ipw_cols = [(1,0,0), (0,1,0), (0,0,1)]
ipw = self._ipws[0]
ipw.DisplayTextOn()
ipw.SetInteractor(
self.sliceDirections.slice3dVWR.threedFrame.threedRWI)
ipw.SetPlaneOrientation(self._defaultPlaneOrientation)
ipw.SetSliceIndex(0)
ipw.GetPlaneProperty().SetColor(
ipw_cols[ipw.GetPlaneOrientation()])
# set the window and level
# mystery third parameter with VTK-5-2: in C++ it's
# copy=0 default.
ipw.SetWindowLevel(window, level, 0)
ipw.On()
def setAllOverlayLookupTables(self):
if len(self._ipws) > 1:
for ipw in self._ipws[1:]:
self._setOverlayLookupTable(ipw)
def set_lookup_table(self, lut):
if not self._ipws:
return
ipw = self._ipws[0]
if not lut is None:
ipw.UserControlledLookupTableOn()
ipw.SetLookupTable(lut)
ipw.GetColorMap().SetOutputFormatToRGBA()
else:
# make sure lookuptable is reset
ipw.SetLookupTable(None)
ipw.UserControlledLookupTableOff()
ipw.GetColorMap().SetOutputFormatToRGB()
def _setOverlayLookupTable(self, ipw):
"""Configures overlay lookup table according to mode.
fusion: the whole overlay gets constast alpha == srcAlpha.
greenOpacityRange: the overlay gets pure green, opacity 0.0 -> 1.0
hueOpacityRange: the overlay gets hue and opacity 0.0 -> 1.0
"""
redHue = 0.0
greenHue = 0.335
blueHue = 0.670
inputStream = ipw.GetInput()
minv, maxv = inputStream.GetScalarRange()
lut = ipw.GetLookupTable()
lut.SetTableRange((minv,maxv))
mode = self.overlayMode
srcAlpha = self.fusionAlpha
if mode == 'greenFusion':
lut.SetHueRange((greenHue, greenHue))
lut.SetAlphaRange((srcAlpha, srcAlpha))
lut.SetValueRange((0.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'redFusion':
lut.SetHueRange((redHue, redHue))
lut.SetAlphaRange((srcAlpha, srcAlpha))
lut.SetValueRange((0.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'blueFusion':
lut.SetHueRange((blueHue, blueHue))
lut.SetAlphaRange((srcAlpha, srcAlpha))
lut.SetValueRange((0.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'hueFusion':
lut.SetHueRange((0.0, 0.85))
lut.SetAlphaRange((srcAlpha, srcAlpha))
lut.SetValueRange((1.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'hueValueFusion':
lut.SetHueRange((0.0, 1.0))
lut.SetAlphaRange((srcAlpha, srcAlpha))
lut.SetValueRange((0.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'greenOpacityRange':
lut.SetHueRange((greenHue, greenHue))
lut.SetAlphaRange((0.0, 1.0))
lut.SetValueRange((1.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'redOpacityRange':
lut.SetHueRange((redHue, redHue))
lut.SetAlphaRange((0.0, 1.0))
lut.SetValueRange((1.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'blueOpacityRange':
lut.SetHueRange((blueHue, blueHue))
lut.SetAlphaRange((0.0, 1.0))
lut.SetValueRange((1.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'hueOpacityRange':
lut.SetHueRange((0.0, 1.0))
lut.SetAlphaRange((0.0, 1.0))
lut.SetValueRange((1.0, 1.0))
lut.SetSaturationRange((1.0, 1.0))
elif mode == 'primaryLUTFusion':
# we can only be called if there are more IPWs
# get lut of primary ipw
primaryIPW = self._ipws[0]
primaryLUT = primaryIPW.GetLookupTable()
lut.SetHueRange(primaryLUT.GetHueRange())
lut.SetAlphaRange((srcAlpha, srcAlpha))
lut.SetValueRange(primaryLUT.GetValueRange())
lut.SetSaturationRange(primaryLUT.GetSaturationRange())
lut.SetTableRange(primaryLUT.GetTableRange())
lut.Build()
def _syncAllToPrimary(self):
"""This will synchronise everything that can be synchronised to
the primary.
"""
self._syncOverlays()
self._syncOrthoView()
self._syncContours()
if self._orthoViewFrame:
self._orthoViewFrame.RWI.Render()
self._syncOutputPolyData()
def _syncContours(self):
"""Synchronise all contours to current primary plane.
"""
for contourObject in self._contourObjectsDict.keys():
self.syncContourToObject(contourObject)
def _syncOutputPolyData(self):
if len(self._ipws) > 0:
ps = self._ipws[0].GetPolyDataAlgorithm()
self._primaryCopyPlaneSource.SetOrigin(ps.GetOrigin())
self._primaryCopyPlaneSource.SetPoint1(ps.GetPoint1())
self._primaryCopyPlaneSource.SetPoint2(ps.GetPoint2())
self._primaryCopyPlaneSource.Update()
def _syncOverlays(self):
"""Synchronise overlays to current main IPW.
"""
# check that we do have overlays for this direction
if len(self._ipws) > 1:
# we know this is a vtkPlaneSource
try:
pds1 = self._ipws[0].GetPolyDataAlgorithm()
except AttributeError:
pds1 = self._ipws[0].GetPolyDataSource()
for ipw in self._ipws[1:]:
try:
pds2 = ipw.GetPolyDataAlgorithm()
except AttributeError:
pds2 = ipw.GetPolyDataSource()
pds2.SetOrigin(pds1.GetOrigin())
pds2.SetPoint1(pds1.GetPoint1())
pds2.SetPoint2(pds1.GetPoint2())
ipw.UpdatePlacement()
def _syncOrthoView(self):
"""Synchronise all layers of orthoView with what's happening
with our primary and overlays.
"""
if self._orthoPipeline and self._ipws:
# vectorN is pointN - origin
v1 = [0,0,0]
self._ipws[0].GetVector1(v1)
n1 = vtk.vtkMath.Normalize(v1)
v2 = [0,0,0]
self._ipws[0].GetVector2(v2)
n2 = vtk.vtkMath.Normalize(v2)
roBounds = self._ipws[0].GetResliceOutput().GetBounds()
for layer in range(len(self._orthoPipeline)):
planeSource = self._orthoPipeline[layer]['planeSource']
planeSource.SetOrigin(0,0,0)
planeSource.SetPoint1(n1, 0, 0)
planeSource.SetPoint2(0, n2, 0)
tm2p = self._orthoPipeline[layer]['textureMapToPlane']
tm2p.SetOrigin(0,0,0)
tm2p.SetPoint1(roBounds[1] - roBounds[0], 0, 0)
tm2p.SetPoint2(0, roBounds[3] - roBounds[2], 0)
def _ipwStartInteractionCallback(self):
self.sliceDirections.setCurrentSliceDirection(self)
self._ipwInteractionCallback()
def _ipwInteractionCallback(self):
cd = 4 * [0.0]
if self._ipws[0].GetCursorData(cd):
self.sliceDirections.setCurrentCursor(cd)
# find the orthoView (if any) which tracks this IPW
#directionL = [v['direction'] for v in self._orthoViews
# if v['direction'] == direction]
#if directionL:
# self._syncOrthoViewWithIPW(directionL[0])
# [self._viewFrame.ortho1RWI, self._viewFrame.ortho2RWI]\
# [directionL[0]].Render()
def _ipwEndInteractionCallback(self):
# we probably don't have to do all of this, as an interaction
# can also be merely the user mousing around with the cursor!
self._syncOverlays()
self._syncOrthoView()
self._syncContours()
if self._orthoViewFrame:
self._orthoViewFrame.RWI.Render()
self._syncOutputPolyData()
# we have to indicate to the ModuleManager that we might have
# been modified, but we only do it for the output part that's
# responsible for the slices polydata
m = self.sliceDirections.slice3dVWR
m._module_manager.modify_module(m, 3) # part 3 does the slices
m._module_manager.request_auto_execute_network(m)
| Python |
# tdObjects.py copyright (c) 2003 by Charl P. Botha <cpbotha@ieee.org>
# $Id$
# class that controls the 3-D objects list
import gen_utils
reload(gen_utils)
import math
import module_kits
from module_kits.vtk_kit import misc
from modules.viewers.slice3dVWRmodules.shared import s3dcGridMixin
import operator
import vtk
import vtkdevide
import wx
import wx.grid
from wx.lib import colourdb
class tdObjects(s3dcGridMixin):
"""Class for keeping track and controlling everything to do with
3d objects in a slice viewer. A so-called tdObject can be a vtkPolyData
or a vtkVolume at this stage. The internal dict is keyed on the
tdObject binding itself.
"""
_objectColours = ['LIMEGREEN', 'SKYBLUE', 'PERU', 'CYAN',
'GOLD', 'MAGENTA', 'GREY80',
'PURPLE']
_gridCols = [('Object Name', 0), ('Colour', 110), ('Visible', 0),
('Contour', 0), ('Motion', 0), ('Scalars',0)]
_gridNameCol = 0
_gridColourCol = 1
_gridVisibleCol = 2
_gridContourCol = 3
_gridMotionCol = 4
_gridScalarVisibilityCol = 5
def __init__(self, slice3dVWRThingy, grid):
self._tdObjectsDict = {}
self._objectId = 0
self.slice3dVWR = slice3dVWRThingy
self._grid = grid
self._initialiseGrid()
self._bindEvents()
# fill out our drop-down menu
self._disableMenuItems = self._appendGridCommandsToMenu(
self.slice3dVWR.controlFrame.objectsMenu,
self.slice3dVWR.controlFrame, disable=True)
# some GUI events that have to do with the objects list
wx.EVT_BUTTON(self.slice3dVWR.objectAnimationFrame,
self.slice3dVWR.objectAnimationFrame.resetButtonId,
self._handlerObjectAnimationReset)
wx.EVT_SLIDER(self.slice3dVWR.objectAnimationFrame,
self.slice3dVWR.objectAnimationFrame.frameSliderId,
self._handlerObjectAnimationSlider)
# this will fix up wxTheColourDatabase
colourdb.updateColourDB()
def close(self):
self._tdObjectsDict.clear()
self.slice3dVWR = None
self._grid.ClearGrid()
self._grid = None
def addObject(self, tdObject):
"""Takes care of all the administration of adding a new 3-d object
to the list and updating it in the list control.
"""
if tdObject not in self._tdObjectsDict:
# we get to pick a colour and a name
colourName = self._objectColours[
self._objectId % len(self._objectColours)]
# objectName HAS TO BE unique!
objectName = "%s%d" % ('obj', self._objectId)
self._objectId += 1
# create a colour as well
colour = wx.TheColourDatabase.FindColour(colourName).asTuple()
# normalise
nColour = tuple([c / 255.0 for c in colour])
# we'll need this later (when we decide about scalar vis)
scalarsName = None
# now actually create the necessary thingies and add the object
# to the scene
if hasattr(tdObject, 'GetClassName') and \
callable(tdObject.GetClassName):
if tdObject.GetClassName() == 'vtkVolume':
self.slice3dVWR._threedRenderer.AddVolume(tdObject)
self._tdObjectsDict[tdObject] = {'tdObject' : tdObject,
'type' : 'vtkVolume'}
# we have to test this here already... if there's
# a VTK error (for instance volume rendering the wrong
# type) we remove the volume and re-raise the exception
# the calling code will act as if no successful add
# was performed, thus feeding back the error
try:
self.slice3dVWR._threedRenderer.ResetCamera()
self.slice3dVWR.render3D()
except RuntimeError:
self.slice3dVWR._threedRenderer.RemoveVolume(tdObject)
raise
elif tdObject.GetClassName() == 'vtkPolyData':
mapper = vtk.vtkPolyDataMapper()
mapper.ImmediateModeRenderingOn()
mapper.SetInput(tdObject)
actor = vtk.vtkActor()
actor.SetMapper(mapper)
#actor.GetProperty().LoadMaterial('GLSLTwisted')
#actor.GetProperty().ShadingOn()
#actor.GetProperty().AddShaderVariableFloat('Rate', 1.0)
# now we are going to set the PERFECT material
p = actor.GetProperty()
# i prefer flat shading, okay?
p.SetInterpolationToFlat()
# Ka, background lighting coefficient
p.SetAmbient(0.1)
# light reflectance
p.SetDiffuse(0.6)
# the higher Ks, the more intense the highlights
p.SetSpecular(0.4)
# the higher the power, the more localised the
# highlights
p.SetSpecularPower(100)
ren = self.slice3dVWR._threedRenderer
ren.AddActor(actor)
self._tdObjectsDict[tdObject] = {'tdObject' : tdObject,
'type' : 'vtkPolyData',
'vtkActor' : actor}
# to get the name of the scalars we need to do this.
tdObject.Update()
if tdObject.GetPointData().GetScalars():
scalarsName = tdObject.GetPointData().GetScalars().\
GetName()
else:
scalarsName = None
if scalarsName:
mapper.SetScalarRange(tdObject.GetScalarRange())
#mapper.ScalarVisibilityOff()
# if sname and sname.lower().find("curvature") >= 0:
# # if the active scalars have "curvature" somewhere in
# # their name, activate flat shading and scalar vis
# property = actor.GetProperty()
# property.SetInterpolationToFlat()
# mapper.ScalarVisibilityOn()
# else:
# # the user can switch this back on if she really
# # wants it
# # we switch it off as we mostly work with isosurfaces
# mapper.ScalarVisibilityOff()
else:
raise Exception, 'Non-handled tdObject type'
else:
# the object has no GetClassName that's callable
raise Exception, 'tdObject has no GetClassName()'
nrGridRows = self._grid.GetNumberRows()
self._grid.AppendRows()
self._grid.SetCellValue(nrGridRows, self._gridNameCol, objectName)
# set the relevant cells up for Boolean
for col in [self._gridVisibleCol, self._gridContourCol,
self._gridMotionCol, self._gridScalarVisibilityCol]:
self._grid.SetCellRenderer(nrGridRows, col,
wx.grid.GridCellBoolRenderer())
self._grid.SetCellAlignment(nrGridRows, col,
wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
# store the name
self._tdObjectsDict[tdObject]['objectName'] = objectName
# and store the colour
self._setObjectColour(tdObject, nColour)
# and the visibility
self._setObjectVisibility(tdObject, True)
# and the contouring
self._setObjectContouring(tdObject, False)
# and the motion
self._setObjectMotion(tdObject, False)
# scalar visibility
if scalarsName:
self._setObjectScalarVisibility(tdObject, True)
else:
self._setObjectScalarVisibility(tdObject, False)
# ends
else:
raise Exception, 'Attempt to add same object twice.'
def updateObject(self, prevObject, newObject):
"""Method used to update new data on a new connection.
When the ModuleManager transfers data, it simply calls set_input()
with a non-None inputStream on an already non-None connection. This
function will take the necessary steps to update just the object and
keep everything else as is.
@param prevObject: the previous object binding, will be used to remove
if the binding has changed.
@param newObject: the new object binding.
"""
if newObject.GetClassName() == 'vtkVolume':
# remove old object from renderer
self.slice3dVWR._threedRenderer.RemoveVolume(prevObject)
# store the old object dict
objectDict = self._tdObjectsDict[prevObject]
# remove it from our list
del self._tdObjectsDict[prevObject]
# add the object to the renderer
self.slice3dVWR._threedRenderer.AddVolume(newObject)
# modify the stored old object dict with the new object
objectDict['tdObject'] = newObject
# and store it in our list!
self._tdObjectsDict[newObject] = objectDict
elif newObject.GetClassName() == 'vtkPolyData':
objectDict = self._tdObjectsDict[prevObject]
# first remove the contouring (if present) ###############
contouring = objectDict['contour']
if contouring:
self._setObjectContouring(objectDict['tdObject'],
False)
# remove the old object from the dictionary.
del self._tdObjectsDict[prevObject]
# record the new object ###################################
objectDict['tdObject'] = newObject
mapper = objectDict['vtkActor'].GetMapper()
mapper.SetInput(newObject)
self._tdObjectsDict[newObject] = objectDict
# set the new scalar range ################################
if newObject.GetPointData().GetScalars():
scalarsName = newObject.GetPointData().GetScalars().\
GetName()
else:
scalarsName = None
if scalarsName:
mapper.SetScalarRange(newObject.GetScalarRange())
# reactivate the contouring (if it was active before)
if contouring:
self._setObjectContouring(objectDict['tdObject'],
True)
def _appendGridCommandsToMenu(self, menu, eventWidget, disable=True):
"""Appends the points grid commands to a menu. This can be used
to build up the context menu or the drop-down one.
"""
commandsTuple = [
('Select &All', 'Select all objects',
self._handlerObjectSelectAll, False),
('D&Eselect All', 'Deselect all objects',
self._handlerObjectDeselectAll, False),
('---',),
('&Show', 'Show all selected objects',
self._handlerObjectShow, True),
('&Hide', 'Hide all selected objects',
self._handlerObjectHide, True),
('&Motion ON +', 'Enable motion for selected objects',
self._handlerObjectMotionOn, True),
('M&otion OFF', 'Disable motion for selected objects',
self._handlerObjectMotionOff, True),
('Set &Colour',
'Change colour of selected objects',
self._handlerObjectSetColour, True),
('Set O&pacity',
'Change opacity of selected objects',
self._handlerObjectSetOpacity, True),
('Con&touring On +',
'Activate contouring for all selected objects',
self._handlerObjectContourOn, True),
('Conto&uring Off',
'Deactivate contouring for all selected objects',
self._handlerObjectContourOff, True),
('Scalar Visibility On +',
'Activate scalar visibility for all selected objects',
self._handlerObjectScalarVisibilityOn, True),
('Scalar Visibility Off',
'Deactivate scalar visibility for all selected objects',
self._handlerObjectScalarVisibilityOff, True),
('---',), # important! one-element tuple...
('Attach A&xis',
'Attach axis to all selected objects',
self._handlerObjectAttachAxis, True),
('Mo&ve Axis to Slice',
'Move the object (via its axis) to the selected slices',
self._handlerObjectAxisToSlice, True),
('Const&rain Motion',
'Constrain the motion of selected objects to the selected slices',
self._handlerObjectPlaneLock, True),
('Rotate around object axis',
'Rotate selected objects a specified number of degrees around '
'their attached axes.', self._handlerObjectAxisRotate,
True),
('---',), # important! one-element tuple...
('Animate Objects',
'Animate all present objects by controlling exclusive visibility',
self._handlerObjectAnimation, True),
('Invoke Prop Method',
'Invoke the same method on all the selected objects\'s 3D props',
self._handlerObjectPropInvokeMethod, True)]
disableList = self._appendGridCommandsTupleToMenu(
menu, eventWidget, commandsTuple, disable)
return disableList
def _attachAxis(self, sObject, twoPoints):
"""Associate the axis defined by the two world points with the
given tdObject.
"""
# before we attach this axis, we have to disable the current motion
# temporarily (if any) else the transform will go bonkers
motionSwitched = False
if self.getObjectMotion(sObject):
self._setObjectMotion(sObject, False)
motionSwitched = True
# vector from 0 to 1
vn = map(operator.sub, twoPoints[1], twoPoints[0])
# normalise it
d = vtk.vtkMath.Normalize(vn)
# calculate new lengthening vector
v = [0.5 * d * e for e in vn]
new0 = map(operator.sub, twoPoints[0], v)
new1 = map(operator.add, twoPoints[1], v)
# we want the actor double as long
lineSource = vtk.vtkLineSource()
lineSource.SetPoint1(new0)
lineSource.SetPoint2(new1)
tubeFilter = vtk.vtkTubeFilter()
tubeFilter.SetNumberOfSides(8)
# 100 times thinner than it is long
tubeFilter.SetRadius(d / 100.0)
tubeFilter.SetInput(lineSource.GetOutput())
lineMapper = vtk.vtkPolyDataMapper()
lineMapper.SetInput(tubeFilter.GetOutput())
lineActor = vtk.vtkActor()
lineActor.GetProperty().SetColor(1.0, 0.0, 0.0)
lineActor.SetMapper(lineMapper)
self.slice3dVWR._threedRenderer.AddActor(lineActor)
self._tdObjectsDict[sObject]['axisPoints'] = twoPoints
self._tdObjectsDict[sObject]['axisLineActor'] = lineActor
if motionSwitched:
self._setObjectMotion(sObject, True)
def _axisToLineTransform(self, axisPoints, lineOrigin, lineVector):
"""Calculate the transform required to move and rotate an axis
so that it is collinear with the given line.
"""
# 2. calculate vertical distance from first axis point to line
tp0o = map(operator.sub, axisPoints[0], lineOrigin)
bvm = vtk.vtkMath.Dot(tp0o, lineVector) # bad vector magnitude
bv = [bvm * e for e in lineVector] # bad vector
# by subtracting the bad (lineVector-parallel) vector from tp0o,
# we get only the orthogonal distance!
od = map(operator.sub, tp0o, bv)
# negate it
od = [-e for e in od]
# 3. calculate rotation around axis parallel with plane going
# through the first axis point
# let's rotate
# get axis as vector
objectAxis = map(operator.sub, axisPoints[1], axisPoints[0])
objectAxisM = vtk.vtkMath.Norm(objectAxis)
rotAxis = [0.0, 0.0, 0.0]
vtk.vtkMath.Cross(objectAxis, lineVector, rotAxis)
# calculate the new tp[1] (i.e. after the translate)
ntp1 = map(operator.add, axisPoints[1], od)
# relative to line origin
ntp1o = map(operator.sub, ntp1, lineOrigin)
# project down onto line
bvm = vtk.vtkMath.Dot(ntp1o, lineVector)
bv = [bvm * e for e in lineVector]
gv = map(operator.sub, ntp1o, bv)
spdM = vtk.vtkMath.Norm(gv)
# we now have y (spdM) and r (objectAxisM), so use asin
# and convert everything to degrees
rotAngle = math.asin(spdM / objectAxisM) / math.pi * 180
# bvm indicates the orientation of the objectAxis w.r.t. the
# intersection line
# draw the figures, experiment with what this code does when the
# lineVector is exactly the same but with opposite direction :)
if bvm < 0:
rotAngle *= -1.0
# 4. create a homogenous transform with this translation and
# rotation
newTransform = vtk.vtkTransform()
newTransform.Identity()
newTransform.PreMultiply()
newTransform.Translate(od) # vd was the vertical translation
tp0n = [-e for e in axisPoints[0]]
newTransform.Translate(axisPoints[0])
newTransform.RotateWXYZ(
rotAngle, rotAxis[0], rotAxis[1], rotAxis[2])
newTransform.Translate(tp0n)
return newTransform
def _axisToLine(self, tdObject, lineOrigin, lineVector):
objectDict = self._tdObjectsDict[tdObject]
if 'axisPoints' not in objectDict:
# and we do need an axis
return
# switch off motion as we're going to be moving things around
# ourselves and don't want to muck about with the boxwidget
# transform... (although we technically could)
motionSwitched = False
if self.getObjectMotion(tdObject):
self._setObjectMotion(tdObject, False)
motionSwitched = True
# make sure lineVector is normalised
vtk.vtkMath.Normalize(lineVector)
# set up some convenient bindings
axisLineActor = objectDict['axisLineActor']
axisPoints = objectDict['axisPoints']
# 1. okay, first determine the current world coordinates of the
# axis end points by transforming the stored axisPoints with
# the Matrix of the axisLineActor
axisMatrix = vtk.vtkMatrix4x4()
axisLineActor.GetMatrix(axisMatrix)
twoPoints = []
twoPoints.append(axisMatrix.MultiplyPoint(axisPoints[0] + (1,))[0:3])
twoPoints.append(axisMatrix.MultiplyPoint(axisPoints[1] + (1,))[0:3])
newTransform = self._axisToLineTransform(
twoPoints, lineOrigin, lineVector)
# perform the actual transform and flatten all afterwards
self._transformObjectProps(tdObject, newTransform)
# perform other post object motion synchronisation, such as
# for contours e.g.
self._postObjectMotionSync(tdObject)
if motionSwitched:
self._setObjectMotion(tdObject, True)
def _axisToPlaneTransform(self, axisPoints, planeNormal, planeOrigin):
"""Calculate transform required to rotate and move the axis defined
by axisPoints to be coplanar with the plane defined by planeNormal
and planeOrigin.
"""
# 2. calculate vertical translation between the first axis point
# and the plane that we are going to lock to
tpo = map(operator.sub, axisPoints[0], planeOrigin)
# "vertical" distance
vdm = vtk.vtkMath.Dot(tpo, planeNormal)
# vector perpendicular to plane, between plane and tp[0]
vd = [vdm * e for e in planeNormal]
# negate it
vd = [-e for e in vd]
# translation == vd
# 3. calculate rotation around axis parallel with plane going
# through the first axis point
# let's rotate
# get axis as vector
objectAxis = map(operator.sub, axisPoints[1], axisPoints[0])
objectAxisM = vtk.vtkMath.Norm(objectAxis)
rotAxis = [0.0, 0.0, 0.0]
vtk.vtkMath.Cross(objectAxis, planeNormal, rotAxis)
# calculate the new tp[1] (i.e. after the translate)
ntp1 = map(operator.add, axisPoints[1], vd)
# relative to plane origin
ntp1o = map(operator.sub, ntp1, planeOrigin)
# project down onto plane by
# first calculating the orthogonal distance to the plane
spdM = vtk.vtkMath.Dot(ntp1o, planeNormal)
# multiply by planeNormal
#spd = [spdM * e for e in ipw.GetNormal()]
# spd is the plane-normal vector from the new axisPoints[1] to the
# plane
# we now have y (spd) and r (objectAxisM), so use asin
# and convert everything to degrees
rotAngle = math.asin(spdM / objectAxisM) / math.pi * 180
# 4. create a homogenous transform with this translation and
# rotation
newTransform = vtk.vtkTransform()
newTransform.Identity()
newTransform.PreMultiply()
newTransform.Translate(vd) # vd was the vertical translation
tp0n = [-e for e in axisPoints[0]]
newTransform.Translate(axisPoints[0])
newTransform.RotateWXYZ(
-rotAngle, rotAxis[0], rotAxis[1], rotAxis[2])
newTransform.Translate(tp0n)
return newTransform
def _axisToSlice(self, tdObject, sliceDirection):
"""If tdObject has an axis, make the axis lie in the plane
defined by sliceDirection.
"""
if not sliceDirection._ipws:
# we need a plane definition to latch to!
return
objectDict = self._tdObjectsDict[tdObject]
if 'axisPoints' not in objectDict:
# and we do need an axis
return
# switch off motion as we're going to be moving things around
# ourselves and don't want to muck about with the boxwidget
# transform... (although we technically could)
motionSwitched = False
if self.getObjectMotion(tdObject):
self._setObjectMotion(tdObject, False)
motionSwitched = True
# set up some convenient bindings
ipw = sliceDirection._ipws[0]
axisLineActor = objectDict['axisLineActor']
axisPoints = objectDict['axisPoints']
# 1. okay, first determine the current world coordinates of the
# axis end points by transforming the stored axisPoints with
# the Matrix of the axisLineActor
axisMatrix = vtk.vtkMatrix4x4()
axisLineActor.GetMatrix(axisMatrix)
twoPoints = []
twoPoints.append(axisMatrix.MultiplyPoint(axisPoints[0] + (1,))[0:3])
twoPoints.append(axisMatrix.MultiplyPoint(axisPoints[1] + (1,))[0:3])
# calculate the transform needed to move and rotate the axis so that
# it will be coplanar with the plane
newTransform = self._axisToPlaneTransform(
twoPoints, ipw.GetNormal(), ipw.GetOrigin())
# transform the object and all its thingies
self._transformObjectProps(tdObject, newTransform)
# perform other post object motion synchronisation, such as
# for contours e.g.
self._postObjectMotionSync(tdObject)
if motionSwitched:
self._setObjectMotion(tdObject, True)
def _bindEvents(self):
#controlFrame = self.slice3dVWR.controlFrame
wx.grid.EVT_GRID_CELL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_LABEL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_RANGE_SELECT(
self._grid, self._handlerGridRangeSelect)
def _detachAxis(self, tdObject):
"""Remove any object axis-related metadata and actors if tdObject
has them.
"""
try:
actor = self._tdObjectsDict[tdObject]['axisLineActor']
self.slice3dVWR._threedRenderer.RemoveActor(actor)
del self._tdObjectsDict[tdObject]['axisPoints']
del self._tdObjectsDict[tdObject]['axisLineActor']
except KeyError:
# this means the tdObject had no axis - EAFP! :)
pass
def findGridRowByName(self, objectName):
nrGridRows = self._grid.GetNumberRows()
rowFound = False
row = 0
while not rowFound and row < nrGridRows:
value = self._grid.GetCellValue(row, self._gridNameCol)
rowFound = (value == objectName)
row += 1
if rowFound:
# prepare and return the row
row -= 1
return row
else:
return -1
def findObjectByProp(self, prop):
"""Find the tdObject corresponding to prop. Prop can be the vtkActor
corresponding with a vtkPolyData tdObject or a vtkVolume tdObject.
Whatever the case may be, this will return something that is a valid
key in the tdObjectsDict or None
"""
try:
# this will succeed if prop is a vtkVolume
return self._tdObjectsDict[prop]
except KeyError:
#
for objectDict in self._tdObjectsDict.values():
if objectDict['vtkActor'] == prop:
return objectDict['tdObject']
return None
def findObjectByName(self, objectName):
"""Given an objectName, return a tdObject binding.
"""
dictItems = self._tdObjectsDict.items()
dictLen = len(dictItems)
objectFound = False
itemsIdx = 0
while not objectFound and itemsIdx < dictLen:
objectFound = objectName == dictItems[itemsIdx][1]['objectName']
itemsIdx += 1
if objectFound:
itemsIdx -= 1
return dictItems[itemsIdx][0]
else:
return None
def findObjectsByNames(self, objectNames):
"""Given a sequence of object names, return a sequence with bindings
to all the found objects. There could be less objects than names.
"""
dictItems = self._tdObjectsDict.items()
dictLen = len(dictItems)
itemsIdx = 0
foundObjects = []
while itemsIdx < dictLen:
if dictItems[itemsIdx][1]['objectName'] in objectNames:
foundObjects.append(dictItems[itemsIdx][0])
itemsIdx += 1
return foundObjects
def findPropByObject(self, tdObject):
"""Given a tdObject, return the corresponding prop, which could
be a vtkActor or a vtkVolume.
"""
t = self._tdObjectsDict[tdObject]['type']
if t == 'vtkVolume':
return tdObject
if t == 'vtkPolyData':
return self._tdObjectsDict[tdObject]['vtkActor']
else:
raise KeyError
def getPickableProps(self):
return [o['vtkActor'] for o in self._tdObjectsDict.values()
if 'vtkActor' in o]
def _getSelectedObjects(self):
"""Return a list of tdObjects representing the objects that have
been selected by the user.
"""
objectNames = []
selectedRows = self._grid.GetSelectedRows()
for sRow in selectedRows:
objectNames.append(
self._grid.GetCellValue(sRow, self._gridNameCol)
)
objs = self.findObjectsByNames(objectNames)
return objs
def getContourObjects(self):
"""Returns a list of objects that have contouring activated.
"""
return [o['tdObject'] for o in self._tdObjectsDict.values()
if o['contour']]
def getObjectColour(self, tdObject):
"""Given tdObject, this will return that object's current colour
in the scene. If the tdObject doesn't exist in our list, it gets
green by default.
"""
try:
return self._tdObjectsDict[tdObject]['colour']
except:
return (0.0, 1.0, 0.0)
def getObjectMotion(self, tdObject):
"""Returns true if motion has been activated for the tdObject.
"""
return self._tdObjectsDict[tdObject]['motion']
def _handlerGridRightClick(self, gridEvent):
"""This will popup a context menu when the user right-clicks on the
grid.
"""
pmenu = wx.Menu('Objects Context Menu')
self._appendGridCommandsToMenu(pmenu, self._grid)
self._grid.PopupMenu(pmenu, gridEvent.GetPosition())
def _handlerObjectAnimation(self, event):
self.slice3dVWR.objectAnimationFrame.Show()
self.slice3dVWR.objectAnimationFrame.Raise()
self._objectAnimationReset()
def _handlerObjectAnimationReset(self, event):
self._objectAnimationReset()
def _handlerObjectAnimationSlider(self, event):
frameSlider = self.slice3dVWR.objectAnimationFrame.frameSlider
self._objectAnimationSetFrame(frameSlider.GetValue())
def _handlerObjectPropInvokeMethod(self, event):
methodName = wx.GetTextFromUser(
'Enter the name of the method that you would like\n'
'to invoke on all selected objects.')
if methodName:
objs = self._getSelectedObjects()
try:
for obj in objs:
t = self._tdObjectsDict[obj]['type']
prop = None
if t == 'vtkPolyData':
prop = self._tdObjectsDict[obj]['vtkActor']
elif t == 'vtkVolume':
prop = obj # this is the vtkVolume
else:
prop = None
if prop:
exec('prop.%s' % (methodName,))
except Exception:
self.slice3dVWR._module_manager.log_error_with_exception(
'Could not execute %s on object %s\'s prop.' % \
(methodName,
self._tdObjectsDict[obj]['objectName']))
def _handlerObjectSelectAll(self, event):
for row in range(self._grid.GetNumberRows()):
self._grid.SelectRow(row, True)
def _handlerObjectDeselectAll(self, event):
self._grid.ClearSelection()
def _handlerObjectContourOn(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectContouring(obj, True)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectContourOff(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectContouring(obj, False)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectSetColour(self, event):
objs = self._getSelectedObjects()
if objs:
self.slice3dVWR.setColourDialogColour(
self._tdObjectsDict[objs[0]]['colour'])
dColour = self.slice3dVWR.getColourDialogColour()
if dColour:
for obj in objs:
self._setObjectColour(obj, dColour)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectSetOpacity(self, event):
opacityText = wx.GetTextFromUser(
'Enter a new opacity value (0.0 to 1.0) for all selected '
'objects.')
if opacityText:
try:
opacity = float(opacityText)
except ValueError:
pass
else:
if opacity > 1.0:
opacity = 1.0
elif opacity < 0.0:
opacity = 0.0
objs = self._getSelectedObjects()
for obj in objs:
prop = self.findPropByObject(obj)
if prop:
try:
prop.GetProperty().SetOpacity(opacity)
except AttributeError:
# it could be a volume or somesuch...
pass
if objs:
self.slice3dVWR.render3D()
def _handlerObjectHide(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectVisibility(obj, False)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectShow(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectVisibility(obj, True)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectScalarVisibilityOn(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectScalarVisibility(obj, True)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectScalarVisibilityOff(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectScalarVisibility(obj, False)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectMotionOff(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectMotion(obj, False)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectMotionOn(self, event):
objs = self._getSelectedObjects()
for obj in objs:
self._setObjectMotion(obj, True)
if objs:
self.slice3dVWR.render3D()
def _handlerObjectAttachAxis(self, event):
"""The user should have selected at least two points and an object.
This will record the axis formed by the two selected points as the
object axis. If no points are selected, and an axis already exists,
we detach the axis.
"""
worldPoints = self.slice3dVWR.selectedPoints.getSelectedWorldPoints()
sObjects = self._getSelectedObjects()
if len(worldPoints) >= 2 and sObjects:
for sObject in sObjects:
canChange = True
if 'axisPoints' in self._tdObjectsDict[sObject]:
oName = self._tdObjectsDict[sObject]['objectName']
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"Are you sure you want to CHANGE the axis on object "
"%s?" % (oName,),
"Confirm axis change",
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
if md.ShowModal() != wx.ID_YES:
canChange = False
if canChange:
# detach any previous stuff
self._detachAxis(sObject)
# the user asked for it, so we're doing all of 'em
self._attachAxis(sObject, worldPoints[0:2])
# closes for sObject in sObjects...
if sObjects:
self.slice3dVWR.render3D()
elif not worldPoints and sObjects:
# this means the user might want to remove all axes from
# the sObjects
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"Are you sure you want to REMOVE axes "
"from all selected objects?",
"Confirm axis removal",
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
if md.ShowModal() == wx.ID_YES:
for sObject in sObjects:
self._detachAxis(sObject)
if sObjects:
self.slice3dVWR.render3D()
else:
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"To attach an axis to an object, you need to select two "
"points and an object.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
def _handlerObjectAxisToSlice(self, event):
#
sObjects = self._getSelectedObjects()
print len(sObjects)
sSliceDirections = self.slice3dVWR.sliceDirections.\
getSelectedSliceDirections()
if not sSliceDirections:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"Select at least one slice before "
"using AxisToSlice.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
if not sObjects:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"Select at least one object before "
"using AxisToSlice.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
for sObject in sObjects:
if len(sSliceDirections) == 1:
# align axis with plane
self._axisToSlice(sObject, sSliceDirections[0])
elif len(sSliceDirections) == 2:
# align axis with intersection of two planes (ouch)
try:
pn0 = sSliceDirections[0]._ipws[0].GetNormal()
po0 = sSliceDirections[0]._ipws[0].GetOrigin()
pn1 = sSliceDirections[1]._ipws[0].GetNormal()
po1 = sSliceDirections[1]._ipws[0].GetOrigin()
except IndexError:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"The slices you have selected "
"contain no data.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
try:
lineOrigin, lineVector = misc.planePlaneIntersection(
pn0, po0, pn1, po1)
except ValueError, msg:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"The two slices you have selected "
"are parallel, no intersection "
"can be calculated.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
# finally send it to the line
self._axisToLine(sObject, lineOrigin, lineVector)
else:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"You have selected more than two "
"slices. "
"I am not sure what I should think "
"about this.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
if sObjects:
self.slice3dVWR.render3D()
def _handlerObjectPlaneLock(self, event):
"""Lock the selected objects to the selected planes. This will
constrain future motion to the planes as they are currently defined.
If no planes are selected, the system will lift the locking.
"""
sObjects = self._getSelectedObjects()
sSliceDirections = self.slice3dVWR.sliceDirections.\
getSelectedSliceDirections()
if sObjects and sSliceDirections:
for sObject in sObjects:
# first unlock from any previous locks
self._unlockObjectFromPlanes(sObject)
for sliceDirection in sSliceDirections:
self._lockObjectToPlane(sObject, sliceDirection)
elif sObjects:
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"Are you sure you want to UNLOCK the selected objects "
"from all slices?",
"Confirm Object Unlock",
wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION)
if md.ShowModal() == wx.ID_YES:
for sObject in sObjects:
self._unlockObjectFromPlanes(sObject)
else:
md = wx.MessageDialog(
self.slice3dVWR.controlFrame,
"To lock an object to plane, you have to select at least "
"one object and one slice.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
def _handlerObjectAxisRotate(self, event):
#
sObjects = self._getSelectedObjects()
if not sObjects:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"Select at least one object before "
"using rotate around axis.",
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
for sObject in sObjects:
objectDict = self._tdObjectsDict[sObject]
if 'axisPoints' not in objectDict:
md = wx.MessageDialog(self.slice3dVWR.controlFrame,
"Object %s has no attached axis "
"around which it can be rotated. "
"Please attach an axis." \
% (objectDict['objectName'],),
"Information",
wx.OK | wx.ICON_INFORMATION)
md.ShowModal()
return
else:
# we have to check for an axis first
angleText = wx.GetTextFromUser(
'Enter the number of degrees to rotate the selected '
'objects around their attached axes.')
if angleText:
try:
angle = float(angleText)
except ValueError:
pass
else:
# first switch of the motion widget (else things
# get really confusing)
motionSwitched = False
if self.getObjectMotion(sObject):
self._setObjectMotion(sObject, False)
motionSwitched = True
# the stored axis points represent the ORIGINAL
# location of the axis defining points...
# we have to transform these with the current
# transform of the axisactor
axisMatrix = vtk.vtkMatrix4x4()
axisLineActor = objectDict['axisLineActor']
axisLineActor.GetMatrix(axisMatrix)
axisPoints = objectDict['axisPoints']
twoPoints = []
twoPoints.append(axisMatrix.MultiplyPoint(
axisPoints[0] + (1,))[0:3])
twoPoints.append(axisMatrix.MultiplyPoint(
axisPoints[1] + (1,))[0:3])
# do the actual rotation
# calculate the axis vector
v = map(operator.sub, twoPoints[1], twoPoints[0])
vtk.vtkMath.Normalize(v)
# create a transform with the requested rotation
newTransform = vtk.vtkTransform()
newTransform.Identity()
# here we choose PostMultiply, i.e. A * M where M
# is the current trfm and A is new so that our
# actions have a natural order: Ta * R * To * O
# where To is the translation back to the origin,
# R is the rotation and Ta is the translation back
# to where we started. O is the object that is being
# transformed
newTransform.PostMultiply()
# we have a vector from 0 to 1, so we have
# to translate to 0 first
newTransform.Translate([-e for e in twoPoints[0]])
# do the rotation
newTransform.RotateWXYZ(angle, v)
# then transform it back to point 0
newTransform.Translate(twoPoints[0])
# finally apply the transform
self._transformObjectProps(sObject, newTransform)
# make sure everything dependent on this tdObject
# is updated
self._postObjectMotionSync(sObject)
# switch motion back on if it was switched off
if motionSwitched:
self._setObjectMotion(sObject, True)
if sObjects:
self.slice3dVWR.render3D()
def _initialiseGrid(self):
"""Setup the object listCtrl from scratch, mmmkay?
"""
# setup default selection background
gsb = self.slice3dVWR.gridSelectionBackground
self._grid.SetSelectionBackground(gsb)
# delete all existing columns
self._grid.DeleteCols(0, self._grid.GetNumberCols())
# we need at least one row, else adding columns doesn't work (doh)
self._grid.AppendRows()
# setup columns
self._grid.AppendCols(len(self._gridCols))
for colIdx in range(len(self._gridCols)):
# add labels
self._grid.SetColLabelValue(colIdx, self._gridCols[colIdx][0])
# set size according to labels
self._grid.AutoSizeColumns()
for colIdx in range(len(self._gridCols)):
# now set size overrides
size = self._gridCols[colIdx][1]
if size > 0:
self._grid.SetColSize(colIdx, size)
# make sure we have no rows again...
self._grid.DeleteRows(0, self._grid.GetNumberRows())
def _lockObjectToPlane(self, tdObject, sliceDirection):
"""Set it up so that motion of tdObject will be constrained to the
current plane equation of the given sliceDirection.
"""
if not sliceDirection._ipws:
# we need some kind of plane equation!
return
newPlaneNormal = sliceDirection._ipws[0].GetNormal()
try:
self._tdObjectsDict[tdObject]['motionConstraintVectors'].append(
newPlaneNormal)
except KeyError:
self._tdObjectsDict[tdObject][
'motionConstraintVectors'] = [newPlaneNormal]
# if a motionBoxWidget already exists, make sure it knows about the
# new constraints
if 'motionBoxWidget' in self._tdObjectsDict[tdObject]:
self._setupMotionConstraints(
self._tdObjectsDict[tdObject]['motionBoxWidget'],
tdObject)
def _objectAnimationReset(self):
objectsPerFrameSpinCtrl = self.slice3dVWR.objectAnimationFrame.\
objectsPerFrameSpinCtrl
objectsPerFrame = objectsPerFrameSpinCtrl.GetValue()
if objectsPerFrame > 0:
frameSlider = self.slice3dVWR.objectAnimationFrame.frameSlider
# first tell slider what it can do
selectedObjects = self._getSelectedObjects()
numObjects = len(selectedObjects)
frames = numObjects / objectsPerFrame
frameSlider.SetRange(0, frames - 1)
frameSlider.SetValue(0)
self._objectAnimationSetFrame(0)
def _objectAnimationSetFrame(self, frame):
selectedObjects = self._getSelectedObjects()
numObjects = len(selectedObjects)
objectsPerFrameSpinCtrl = self.slice3dVWR.objectAnimationFrame.\
objectsPerFrameSpinCtrl
objectsPerFrame = objectsPerFrameSpinCtrl.GetValue()
if objectsPerFrame > 0 and \
frame < numObjects / objectsPerFrame:
objectNames = []
selectedRows = self._grid.GetSelectedRows()
for i in range(objectsPerFrame):
objectNames.append(self._grid.GetCellValue(
selectedRows[frame * objectsPerFrame + i],
self._gridNameCol))
self._setExclusiveObjectVisibility(objectNames, True)
self.slice3dVWR.render3D()
def _observerMotionBoxWidgetEndInteraction(self, eventObject, eventType):
# make sure the transform is up to date
self._observerMotionBoxWidgetInteraction(eventObject, eventType)
tdObject = self.findObjectByProp(eventObject.GetProp3D())
self._postObjectMotionSync(tdObject)
def _observerMotionBoxWidgetInteraction(self, eventObject, eventType):
bwTransform = vtk.vtkTransform()
eventObject.GetTransform(bwTransform)
eventObject.GetProp3D().SetUserTransform(bwTransform)
# now make sure that the object axis (if any) is also aligned
# find the tdObject corresponding to the prop
tdObject = self.findObjectByProp(eventObject.GetProp3D())
try:
# if there's a line, move it too!
axisLineActor = self._tdObjectsDict[tdObject]['axisLineActor']
axisLineActor.SetUserTransform(bwTransform)
except KeyError:
pass
def _postObjectMotionSync(self, tdObject):
"""Perform any post object motion synchronisation, such as
recalculating the contours. This method is called when the user
has stopped interacting with an object or if the system has
explicitly moved an object.
"""
# and update the contours after we're done moving things around
self.slice3dVWR.sliceDirections.syncContoursToObject(tdObject)
def removeObject(self, tdObject):
if not self._tdObjectsDict.has_key(tdObject):
raise Exception, 'Attempt to remove non-existent tdObject'
# this will take care of motion boxes and the like
self._setObjectMotion(tdObject, False)
oType = self._tdObjectsDict[tdObject]['type']
if oType == 'vtkVolume':
self.slice3dVWR._threedRenderer.RemoveVolume(tdObject)
self.slice3dVWR.render3D()
elif oType == 'vtkPolyData':
# remove all contours due to this object
self._setObjectContouring(tdObject, False)
actor = self._tdObjectsDict[tdObject]['vtkActor']
self.slice3dVWR._threedRenderer.RemoveActor(actor)
try:
# if there was a axisLineActor, remove that as well
lineActor = self._tdObjectsDict[tdObject]['axisLineActor']
self.slice3dVWR._threedRenderer.RemoveActor(lineActor)
except KeyError:
pass
self.slice3dVWR.render3D()
else:
raise Exception,\
'Unhandled object type in tdObjects.removeObject()'
# whatever the case may be, we need to remove it from the wxGrid
# first search for the correct objectName
nrGridRows = self._grid.GetNumberRows()
rowFound = False
row = 0
objectName = self._tdObjectsDict[tdObject]['objectName']
while not rowFound and row < nrGridRows:
value = self._grid.GetCellValue(row, self._gridNameCol)
rowFound = value == objectName
row += 1
if rowFound:
# and then delete just that row
row -= 1
self._grid.DeleteRows(row)
# and from the dict
del self._tdObjectsDict[tdObject]
def _setObjectColour(self, tdObject, dColour):
if self._tdObjectsDict.has_key(tdObject):
if self._tdObjectsDict[tdObject]['type'] == 'vtkPolyData':
objectDict = self._tdObjectsDict[tdObject]
# in our metadata
objectDict['colour'] = dColour
# change its colour in the scene
actor = objectDict['vtkActor']
actor.GetProperty().SetDiffuseColor(dColour)
# and change its colour in the grid
row = self.findGridRowByName(objectDict['objectName'])
if row >= 0:
r,g,b = [c * 255.0 for c in dColour]
colour = wx.Colour(r,g,b)
self._grid.SetCellBackgroundColour(
row, self._gridColourCol, colour)
# also search for the name
cName = wx.TheColourDatabase.FindName(colour)
if not cName:
cName = 'USER DEFINED'
self._grid.SetCellValue(row, self._gridColourCol, cName)
def _setObjectVisibility(self, tdObject, visible):
if self._tdObjectsDict.has_key(tdObject):
objectDict = self._tdObjectsDict[tdObject]
# in our own dict
objectDict['visible'] = bool(visible)
# in the scene
if objectDict['type'] == 'vtkVolume':
tdObject.SetVisibility(bool(visible))
elif objectDict['type'] == 'vtkPolyData':
objectDict['vtkActor'].SetVisibility(bool(visible))
else:
pass
# finally in the grid
gridRow = self.findGridRowByName(objectDict['objectName'])
if gridRow >= 0:
gen_utils.setGridCellYesNo(
self._grid,gridRow, self._gridVisibleCol, visible)
def _setObjectScalarVisibility(self, tdObject, scalarVisibility):
if self._tdObjectsDict.has_key(tdObject):
objectDict = self._tdObjectsDict[tdObject]
# in the scene
if objectDict['type'] == 'vtkPolyData':
objectDict['vtkActor'].GetMapper().SetScalarVisibility(
scalarVisibility)
else:
# in these cases, scalarVisibility is NA, so it remains off
scalarVisibility = False
pass
# in our own dict
objectDict['scalarVisibility'] = bool(scalarVisibility)
# finally in the grid
gridRow = self.findGridRowByName(objectDict['objectName'])
if gridRow >= 0:
gen_utils.setGridCellYesNo(
self._grid,gridRow, self._gridScalarVisibilityCol,
scalarVisibility)
def _setExclusiveObjectVisibility(self, objectNames, visible):
"""Sets the visibility of tdObject to visible and all the other
objects to the opposite. Used by animation.
"""
objs = self._getSelectedObjects()
for obj in objs:
objDict = self._tdObjectsDict[obj]
if objDict['objectName'] in objectNames:
self._setObjectVisibility(obj, visible)
else:
self._setObjectVisibility(obj, not visible)
def _setObjectContouring(self, tdObject, contour):
if self._tdObjectsDict.has_key(tdObject):
objectDict = self._tdObjectsDict[tdObject]
# in our own dict
objectDict['contour'] = bool(contour)
if objectDict['type'] == 'vtkPolyData':
# in the scene
if contour:
self.slice3dVWR.sliceDirections.addContourObject(
tdObject, objectDict['vtkActor'])
else:
self.slice3dVWR.sliceDirections.removeContourObject(
tdObject)
# in the grid
gridRow = self.findGridRowByName(objectDict['objectName'])
if gridRow >= 0:
if objectDict['type'] == 'vtkPolyData':
gen_utils.setGridCellYesNo(
self._grid, gridRow, self._gridContourCol, contour)
else:
self._grid.SetCellValue(gridRow, self._gridContourCol,
'N/A')
def _setObjectMotion(self, tdObject, motion):
if tdObject in self._tdObjectsDict:
objectDict = self._tdObjectsDict[tdObject]
# in our own dict
objectDict['motion'] = bool(motion)
# setup our frikking motionBoxWidget, mmmkay?
if motion:
if 'motionBoxWidget' in objectDict and \
objectDict['motionBoxWidget']:
# take care of the old one
objectDict['motionBoxWidget'].Off()
objectDict['motionBoxWidget'].SetInteractor(None)
objectDict['motionBoxWidget'] = None
# we like to do it anew
objectDict['motionBoxWidget'] = vtkdevide.\
vtkBoxWidgetConstrained()
bw = objectDict['motionBoxWidget']
# let's switch on scaling for now... (I used to have this off,
# but I can't remember exactly why)
bw.ScalingEnabledOn()
# the balls only confuse us!
bw.HandlesOff()
# without the balls, the outlines aren't needed either
bw.OutlineCursorWiresOff()
bw.SetInteractor(self.slice3dVWR.threedFrame.threedRWI)
# also "flatten" the actor (i.e. integrate its UserTransform)
misc.flattenProp3D(objectDict['vtkActor'])
# and the axis, if any
try:
misc.flattenProp3D(objectDict['axisLineActor'])
except KeyError:
pass
bw.SetProp3D(objectDict['vtkActor'])
bw.SetPlaceFactor(1.0)
bw.PlaceWidget()
bw.On()
bw.AddObserver('EndInteractionEvent',
self._observerMotionBoxWidgetEndInteraction)
bw.AddObserver('InteractionEvent',
self._observerMotionBoxWidgetInteraction)
# FIXME: continue here!
# try:
# ipw = self.slice3dVWR._sliceDirections[0]._ipws[0]
# except:
# # no plane, so we don't do anything
# pass
# else:
# bw.ConstrainToPlaneOn()
# bw.SetConstrainPlaneNormal(ipw.GetNormal())
self._setupMotionConstraints(bw, tdObject)
else: # if NOT motion
if 'motionBoxWidget' in objectDict and \
objectDict['motionBoxWidget']:
try:
# let's flatten the prop again (if there is one)
misc.flattenProp3D(objectDict['vtkActor'])
# and flatten the axis (if any)
misc.flattenProp3D(objectDict['axisLineActor'])
except KeyError:
pass
objectDict['motionBoxWidget'].Off()
objectDict['motionBoxWidget'].SetInteractor(None)
objectDict['motionBoxWidget'] = None
# finally in the grid
gridRow = self.findGridRowByName(objectDict['objectName'])
if gridRow >= 0:
if objectDict['type'] == 'vtkPolyData':
gen_utils.setGridCellYesNo(
self._grid, gridRow, self._gridMotionCol, motion)
else:
self._grid.SetCellValue(gridRow, self._gridMotionCol,
'N/A')
def _setupMotionConstraints(self, boxWidget, tdObject):
"""Configure boxWidget (a vtkBoxWidgetConstrained) to constrain as
specified by the motionConstraintVectors member in the objectDict
corresponding to tdObject.
If there are more than two motionConstraintVectors, only the first
two will be used.
"""
try:
mCV = self._tdObjectsDict[tdObject]['motionConstraintVectors']
except KeyError:
mCV = None
if not mCV:
# i.e. this is an empty vector (or we deliberately set it to None)
# either way, we have to disable all constraints
boxWidget.SetConstraintType(0)
elif len(mCV) == 1:
# plane constraint (i.e. we have only a single plane normal)
boxWidget.SetConstraintType(2) # plane
boxWidget.SetConstraintVector(mCV[0])
else:
# line constraint (intersection of two planes that have been
# stored as plane normals
boxWidget.SetConstraintType(1)
# now determine the constraint line by calculating the cross
# product of the two plane normals
lineVector = [0.0, 0.0, 0.0]
vtk.vtkMath.Cross(mCV[0], mCV[1], lineVector)
# and tell the boxWidget about this!
boxWidget.SetConstraintVector(lineVector)
def _transformObjectProps(self, tdObject, transform):
"""This will perform the final transformation on all props belonging
to an object, including the main prop and all extras, such as the
optional object axis. It will also make sure all the transforms of
all props are flattened.
"""
try:
mainProp = self.findPropByObject(tdObject)
objectDict = self._tdObjectsDict[tdObject]
except KeyError:
# invalid tdObject!
return
props = [mainProp]
try:
props.append(objectDict['axisLineActor'])
except KeyError:
# no problem
pass
for prop in props:
# first we make sure that there's no UserTransform
misc.flattenProp3D(prop)
# then set the UserTransform that we want
prop.SetUserTransform(transform)
# then flatten the f*cker (i.e. UserTransform absorbed)
misc.flattenProp3D(prop)
def _unlockObjectFromPlanes(self, tdObject):
"""Make sure that there are no plane constraints on the motion
of the given tdObject.
"""
try:
del self._tdObjectsDict[tdObject]['motionConstraintVectors'][:]
except KeyError:
pass
# if a motionBoxWidget already exists, make sure it knows about
# the changes
if 'motionBoxWidget' in self._tdObjectsDict[tdObject]:
self._setupMotionConstraints(
self._tdObjectsDict[tdObject]['motionBoxWidget'],
tdObject)
| Python |
# shared.py copyright (c) 2003 Charl P. Botha <cpbotha@ieee.org>
# $Id$
#
import wx
class s3dcGridMixin(object):
"""
"""
def _handlerGridRangeSelect(self, event):
"""This event handler is a fix for the fact that the row
selection in the wxGrid is deliberately broken. It's also
used to activate and deactivate relevant menubar items.
Whenever a user clicks on a cell, the grid SHOWS its row
to be selected, but GetSelectedRows() doesn't think so.
This event handler will travel through the Selected Blocks
and make sure the correct rows are actually selected.
Strangely enough, this event always gets called, but the
selection is empty when the user has EXPLICITLY selected
rows. This is not a problem, as then the GetSelectedRows()
does return the correct information.
"""
# both of these are lists of (row, column) tuples
tl = self._grid.GetSelectionBlockTopLeft()
br = self._grid.GetSelectionBlockBottomRight()
# this means that the user has most probably clicked on the little
# block at the top-left corner of the grid... in this case,
# SelectRow has no frikking effect (up to wxPython 2.4.2.4) so we
# detect this situation and clear the selection (we're going to be
# selecting the whole grid in anycase.
if tl == [(0,0)] and br == [(self._grid.GetNumberRows() - 1,
self._grid.GetNumberCols() - 1)]:
self._grid.ClearSelection()
for (tlrow, tlcolumn), (brrow, brcolumn) in zip(tl, br):
for row in range(tlrow,brrow + 1):
self._grid.SelectRow(row, True)
if self._grid.GetSelectedRows():
for mi in self._disableMenuItems:
mi.Enable(True)
else:
for mi in self._disableMenuItems:
mi.Enable(False)
def _appendGridCommandsTupleToMenu(self, menu, eventWidget,
commandsTuple, disable=True):
"""Appends the slice grid commands to a menu. This can be used
to build up the context menu or the drop-down one.
Returns a list with bindings to menu items that have to be disabled.
"""
disableList = []
for command in commandsTuple:
if command[0] == '---':
mi = wx.MenuItem(menu, wx.ID_SEPARATOR)
menu.AppendItem(mi)
else:
id = wx.NewId()
mi = wx.MenuItem(
menu, id, command[0], command[1])
menu.AppendItem(mi)
wx.EVT_MENU(
eventWidget, id, command[2])
if disable and not self._grid.GetSelectedRows() and command[3]:
mi.Enable(False)
if command[3]:
disableList.append(mi)
# the disableList can be used later if the menu is created for use
# in the frame menubar
return disableList
| Python |
# selectedPoints.py copyright (c) 2003 Charl P. Botha <cpbotha@ieee.org>
# $Id$
#
from module_kits.misc_kit.mixins import SubjectMixin
from modules.viewers.slice3dVWRmodules.shared import s3dcGridMixin
import operator
import vtk
import wx
# -------------------------------------------------------------------------
class outputSelectedPoints(list, SubjectMixin):
"""class for passing selected points to an output port.
Derived from list as base and the subject/observer mixin.
"""
devideType = 'namedPoints'
def __init__(self):
list.__init__(self)
SubjectMixin.__init__(self)
def close(self):
SubjectMixin.close(self)
# -------------------------------------------------------------------------
class selectedPoints(s3dcGridMixin):
_gridCols = [('Point Name', 0), ('World', 150), ('Discrete', 100),
('Value', 0)]
_gridNameCol = 0
_gridWorldCol = 1
_gridDiscreteCol = 2
_gridValueCol = 3
def __init__(self, slice3dVWRThingy, pointsGrid):
self.slice3dVWR = slice3dVWRThingy
self._grid = pointsGrid
self._pointsList = []
self._initialiseGrid()
# this will be passed on as input to the next component
self.outputSelectedPoints = outputSelectedPoints()
self._bindEvents()
# fill out our drop-down menu
self._disableMenuItems = self._appendGridCommandsToMenu(
self.slice3dVWR.controlFrame.pointsMenu,
self.slice3dVWR.controlFrame, disable=True)
def close(self):
self.removePoints(range(len(self._pointsList)))
def _appendGridCommandsToMenu(self, menu, eventWidget, disable=True):
"""Appends the points grid commands to a menu. This can be used
to build up the context menu or the drop-down one.
"""
commandsTuple = [
('&Store Point', 'Store the current cursor as point',
self._handlerStoreCursorAsPoint, False),
('---',),
('Select &All', 'Select all slices',
self._handlerPointsSelectAll, False),
('D&Eselect All', 'Deselect all slices',
self._handlerPointsDeselectAll, False),
('---',),
('&Interaction ON +',
'Activate interaction for the selected points',
self._handlerPointsInteractionOn, True),
('I&nteraction OFF',
'Deactivate interaction for the selected points',
self._handlerPointsInteractionOff, True),
('---',), # important! one-element tuple...
('&Rename',
'Rename selected points',
self._handlerPointsRename, True),
('---',), # important! one-element tuple...
('&Delete', 'Delete selected points',
self._handlerPointsDelete, True)]
disableList = self._appendGridCommandsTupleToMenu(
menu, eventWidget, commandsTuple, disable)
return disableList
def _bindEvents(self):
controlFrame = self.slice3dVWR.controlFrame
# the store button
wx.EVT_BUTTON(controlFrame, controlFrame.sliceStoreButtonId,
self._handlerStoreCursorAsPoint)
wx.grid.EVT_GRID_CELL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_LABEL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_RANGE_SELECT(
self._grid, self._handlerGridRangeSelect)
def enablePointsInteraction(self, enable):
"""Enable/disable points interaction in the 3d scene.
"""
if enable:
for selectedPoint in self._pointsList:
if selectedPoint['pointWidget']:
selectedPoint['pointWidget'].On()
else:
for selectedPoint in self._pointsList:
if selectedPoint['pointWidget']:
selectedPoint['pointWidget'].Off()
def getSavePoints(self):
"""Get special list of points that can be easily pickled.
"""
savedPoints = []
for sp in self._pointsList:
savedPoints.append({'discrete' : sp['discrete'],
'world' : sp['world'],
'value' : sp['value'],
'name' : sp['name'],
'lockToSurface' : sp['lockToSurface']})
return savedPoints
def getSelectedWorldPoints(self):
"""Return list of world coordinates that correspond to selected
points.
"""
return [self._pointsList[i]['world']
for i in self._grid.GetSelectedRows()]
def _handlerGridRightClick(self, gridEvent):
"""This will popup a context menu when the user right-clicks on the
grid.
"""
pmenu = wx.Menu('Points Context Menu')
self._appendGridCommandsToMenu(pmenu, self._grid)
self._grid.PopupMenu(pmenu, gridEvent.GetPosition())
def _handlerPointsRename(self, event):
rslt = wx.GetTextFromUser(
'Please enter a new name for the selected points '
'("none" = no name).',
'Points Rename', '')
if rslt:
if rslt.lower() == 'none':
rslt = ''
selRows = self._grid.GetSelectedRows()
self._renamePoints(selRows, rslt)
def _handlerPointsSelectAll(self, event):
# calling SelectAll and then GetSelectedRows() returns nothing
# so, we select row by row, and that does seem to work!
for row in range(self._grid.GetNumberRows()):
self._grid.SelectRow(row, True)
def _handlerPointsDeselectAll(self, event):
self._grid.ClearSelection()
def _handlerPointsDelete(self, event):
selRows = self._grid.GetSelectedRows()
if len(selRows):
# removePoints will call a render
self.removePoints(selRows)
def _handlerPointsInteractionOn(self, event):
for idx in self._grid.GetSelectedRows():
self._pointsList[idx]['pointWidget'].On()
def _handlerPointsInteractionOff(self, event):
for idx in self._grid.GetSelectedRows():
self._pointsList[idx]['pointWidget'].Off()
def _handlerStoreCursorAsPoint(self, event):
"""Call back for the store cursor button.
Calls store cursor method on [x,y,z,v].
"""
self._storeCursor(self.slice3dVWR.sliceDirections.currentCursor)
def hasWorldPoint(self, worldPoint):
worldPoints = [i['world'] for i in self._pointsList]
if worldPoint in worldPoints:
return True
else:
return False
def _initialiseGrid(self):
# setup default selection background
gsb = self.slice3dVWR.gridSelectionBackground
self._grid.SetSelectionBackground(gsb)
# delete all existing columns
self._grid.DeleteCols(0, self._grid.GetNumberCols())
# we need at least one row, else adding columns doesn't work (doh)
self._grid.AppendRows()
# setup columns
self._grid.AppendCols(len(self._gridCols))
for colIdx in range(len(self._gridCols)):
# add labels
self._grid.SetColLabelValue(colIdx, self._gridCols[colIdx][0])
# set size according to labels
self._grid.AutoSizeColumns()
for colIdx in range(len(self._gridCols)):
# now set size overrides
size = self._gridCols[colIdx][1]
if size > 0:
self._grid.SetColSize(colIdx, size)
# make sure we have no rows again...
self._grid.DeleteRows(0, self._grid.GetNumberRows())
def _observerPointWidgetInteraction(self, pw, evt_name):
# we have to find pw in our list
pwidgets = map(lambda i: i['pointWidget'], self._pointsList)
if pw in pwidgets:
idx = pwidgets.index(pw)
# toggle the selection for this point in our list
self._grid.SelectRow(idx)
# if this is lockToSurface, lock it! (and we can only lock
# to something if there're some pickable objects as reported
# by the tdObjects class)
pp = self.slice3dVWR._tdObjects.getPickableProps()
if self._pointsList[idx]['lockToSurface'] and pp:
tdren = self.slice3dVWR._threedRenderer
# convert the actual pointwidget position back to
# display coord
tdren.SetWorldPoint(pw.GetPosition() + (1,))
tdren.WorldToDisplay()
ex,ey,ez = tdren.GetDisplayPoint()
# we make use of a CellPicker (for the same reasons we
# use it during the initial placement of a surface point)
picker = vtk.vtkCellPicker()
# this is quite important
picker.SetTolerance(0.005)
# tell the picker which props it's allowed to pick from
for p in pp:
picker.AddPickList(p)
picker.PickFromListOn()
# and go!
picker.Pick(ex, ey, 0.0, tdren)
if picker.GetActor():
# correct the pointWidget's position so it sticks to
# the surface
pw.SetPosition(picker.GetPickPosition())
# get its position and transfer it to the sphere actor that
# we use
pos = pw.GetPosition()
self._pointsList[idx]['sphereActor'].SetAttachmentPoint(pos)
val, discrete = self.slice3dVWR.getValueAtPositionInInputData(pos)
if val == None:
discrete = (0, 0, 0)
val = 0
# the cursor is a tuple with discrete position and value
self._pointsList[idx]['discrete'] = tuple(discrete)
# 'world' is the world coordinates
self._pointsList[idx]['world'] = tuple(pos)
# and the value
self._pointsList[idx]['value'] = val
self._syncGridRowToSelPoints(idx)
def removePoints(self, idxs):
"""Remove all points at indexes in idxs list.
"""
# we have to delete one by one from back to front
idxs.sort()
idxs.reverse()
ren = self.slice3dVWR._threedRenderer
for idx in idxs:
# remove the sphere actor from the renderer
ren.RemoveActor(self._pointsList[idx]['sphereActor'])
# then deactivate and disconnect the point widget
pw = self._pointsList[idx]['pointWidget']
pw.SetInput(None)
pw.Off()
pw.SetInteractor(None)
# remove the entries from the wxGrid
self._grid.DeleteRows(idx)
# then remove it from our internal list
del self._pointsList[idx]
# rerender
self.slice3dVWR.render3D()
# and sync up output points
self._syncOutputSelectedPoints()
def _renamePoint(self, pointIdx, newName):
"""Given a point index and a new name, this will take care of all
the actions required to rename a point. This is often called for
a series of points, so this function does not refresh the display
or resync the output list. You're responsible for that. :)
"""
if newName != self._pointsList[pointIdx]['name']:
# we only do something if this has really changed and if the name
# is not blank
# first make sure the 3d renderer knows about this
ca = self._pointsList[pointIdx]['sphereActor']
ca.SetCaption(newName)
# now record the change in our internal list
self._pointsList[pointIdx]['name'] = newName
# now in the grid (the rows and pointIdxs correlate)
self._syncGridRowToSelPoints(pointIdx)
def _renamePoints(self, pointIdxs, newName):
for pointIdx in pointIdxs:
self._renamePoint(pointIdx, newName)
# now resync the output points
self._syncOutputSelectedPoints()
# and redraw stuff
self.slice3dVWR.render3D()
def setSavePoints(self, savedPoints, boundsForPoints):
"""Re-install the saved points that were returned with getPoints.
"""
for sp in savedPoints:
self._storePoint(sp['discrete'], sp['world'], sp['value'],
sp['name'], sp['lockToSurface'],
boundsForPoints)
def _storeCursor(self, cursor):
"""Store the point represented by the cursor parameter.
cursor is a 4-tuple with the discrete (data-relative) xyz coords and
the value at that point.
"""
# we first have to check that we don't have this pos already
new_discrete = (int(cursor[0]), int(cursor[1]), int(cursor[2]))
discretes = [i['discrete'] for i in self._pointsList]
if new_discrete in discretes:
return
worldPos = self.slice3dVWR.getWorldPositionInInputData(cursor[0:3])
if worldPos == None:
return
pointName = self.slice3dVWR.controlFrame.sliceCursorNameCombo.\
GetValue()
self._storePoint(new_discrete, tuple(worldPos), cursor[3],
pointName)
def _storePoint(self, discrete, world, value, pointName,
lockToSurface=False, boundsForPoints=None):
tdren = self.slice3dVWR._threedRenderer
tdrwi = self.slice3dVWR.threedFrame.threedRWI
if not boundsForPoints:
bounds = tdren.ComputeVisiblePropBounds()
else:
bounds = boundsForPoints
if bounds[1] - bounds[0] <= 0 or \
bounds[3] - bounds[2] <= 0 or \
bounds[5] - bounds[4] <= 0:
bounds = (-1,1,-1,1,-1,1)
# we use a pointwidget
pw = vtk.vtkPointWidget()
#pw.SetInput(inputData)
pw.PlaceWidget(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4],
bounds[5])
pw.SetPosition(world)
# make priority higher than the default of vtk3DWidget so
# that imageplanes behind us don't get selected the whole time
pw.SetPriority(0.6)
pw.SetInteractor(tdrwi)
pw.AllOff()
pw.On()
#ss.SetRadius((bounds[1] - bounds[0]) / 100.0)
ca = vtk.vtkCaptionActor2D()
ca.GetProperty().SetColor(1,1,0)
tp = ca.GetCaptionTextProperty()
tp.SetColor(1,1,0)
tp.ShadowOff()
ca.SetPickable(0)
ca.SetAttachmentPoint(world)
ca.SetPosition(25,10)
ca.BorderOff()
ca.SetWidth(0.3)
ca.SetHeight(0.04)
# I used to have the problem on my ATI X1600 that interaction
# was extremely slow of 3D was on... problem seems to have
# gone away by itself, or it rather has to do with the slow-
# glcontext-things
ca.ThreeDimensionalLeaderOn()
ca.SetMaximumLeaderGlyphSize(10)
ca.SetLeaderGlyphSize(0.025)
coneSource = vtk.vtkConeSource()
coneSource.SetResolution(6)
# we want the cone's very tip to by at 0,0,0
coneSource.SetCenter(- coneSource.GetHeight() / 2.0, 0, 0)
ca.SetLeaderGlyph(coneSource.GetOutput())
if len(pointName) > 0:
ca.SetCaption(pointName)
else:
ca.SetCaption(".")
# since VTK 20070628, caption actor doesn't like an empty label
tdren.AddActor(ca)
def pw_ei_cb(pw, evt_name):
# make sure our output is good
self._syncOutputSelectedPoints()
pw.AddObserver('StartInteractionEvent', lambda pw, evt_name,
s=self:
s._observerPointWidgetInteraction(pw, evt_name))
pw.AddObserver('InteractionEvent', lambda pw, evt_name,
s=self:
s._observerPointWidgetInteraction(pw, evt_name))
pw.AddObserver('EndInteractionEvent', pw_ei_cb)
# we start with it disabled
pw.Off()
# store the cursor (discrete coords) the coords and the actor
self._pointsList.append({'discrete' : tuple(discrete),
'world' : tuple(world),
'value' : value,
'name' : pointName,
'pointWidget' : pw,
'lockToSurface' : lockToSurface,
'sphereActor' : ca})
self._grid.AppendRows()
#self._grid.AdjustScrollBars()
row = self._grid.GetNumberRows() - 1
self._syncGridRowToSelPoints(row)
# make sure self._outputSelectedPoints is up to date
self._syncOutputSelectedPoints()
self.slice3dVWR.render3D()
def _syncGridRowToSelPoints(self, row):
# this just formats the real point
name = self._pointsList[row]['name']
discrete = self._pointsList[row]['discrete']
world = self._pointsList[row]['world']
value = self._pointsList[row]['value']
discreteStr = "%.0f, %.0f, %.0f" % discrete
worldStr = "%.2f, %.2f, %.2f" % world
self._grid.SetCellValue(row, self._gridNameCol, name)
self._grid.SetCellValue(row, self._gridWorldCol, worldStr)
self._grid.SetCellValue(row, self._gridDiscreteCol, discreteStr)
self._grid.SetCellValue(row, self._gridValueCol, str(value))
def _syncOutputSelectedPoints(self):
"""Sync up the output vtkPoints and names to _sel_points.
We play it safe, as the number of points in this list is usually
VERY low.
"""
temp_output_selected_points = []
# then transfer everything
for i in self._pointsList:
temp_output_selected_points.append({'name' : i['name'],
'discrete' : i['discrete'],
'world' : i['world'],
'value' : i['value']})
if temp_output_selected_points != self.outputSelectedPoints:
# only if the points have changed do we send them out
# we have to copy like this so that outputSelectedPoints
# keeps its type.
self.outputSelectedPoints[:] = temp_output_selected_points[:]
# make sure that the input-independent part of this module knows
# that it has been modified
mm = self.slice3dVWR._module_manager
# sub-part 1 is responsible for producing the points
mm.modify_module(self.slice3dVWR, 1)
mm.request_auto_execute_network(self.slice3dVWR)
| Python |
# sliceDirections.py copyright (c) 2003 Charl P. Botha <cpbotha@ieee.org>
# $Id$
# class encapsulating all instances of the sliceDirection class
import gen_utils
# the following two lines are only needed during prototyping of the modules
# that they import
import modules.viewers.slice3dVWRmodules.sliceDirection
reload(modules.viewers.slice3dVWRmodules.sliceDirection)
from modules.viewers.slice3dVWRmodules.sliceDirection import sliceDirection
from modules.viewers.slice3dVWRmodules.shared import s3dcGridMixin
import vtk
import wx
import wx.grid
class sliceDirections(s3dcGridMixin):
_gridCols = [('Slice Name', 0), ('Enabled', 0), ('Interaction', 0)]
_gridNameCol = 0
_gridEnabledCol = 1
_gridInteractionCol = 2
def __init__(self, slice3dVWRThingy, sliceGrid):
self.slice3dVWR = slice3dVWRThingy
self._grid = sliceGrid
self._sliceDirectionsDict = {}
# this same picker is used on all new IPWS of all sliceDirections
self.ipwPicker = vtk.vtkCellPicker()
self.currentCursor = None
# configure the grid from scratch
self._initialiseGrid()
self._initUI()
# bind all events
self._bindEvents()
# fill out our drop-down menu
self._disableMenuItems = self._appendGridCommandsToMenu(
self.slice3dVWR.controlFrame.slicesMenu,
self.slice3dVWR.controlFrame, disable=True)
self.overlayMode = 'greenOpacityRange'
self.fusionAlpha = 0.4
# this will make all ipw slice polydata available at the output
self.ipwAppendPolyData = vtk.vtkAppendPolyData()
# this append filter will make all slice data available at the output
self.ipwAppendFilter = vtk.vtkAppendFilter()
# create the first slice
self._createSlice('Axial')
def addData(self, theData):
# add this input to all available sliceDirections
for sliceName, sliceDirection in \
self._sliceDirectionsDict.items():
# try to add the data
sliceDirection.addData(theData)
def updateData(self, prevData, newData):
"""Replace prevData with newData.
This call is used to update a data object on an already existing
connection and is used by the slice3dVWR when a new transfer is made
to one of its inputs. This method calls the updateData method of
the various sliceDirection instances.
@param prevData: the old dataset (will be replaced by the new)
@param newData: The new data.
"""
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection.updateData(prevData, newData)
def addContourObject(self, tdObject, prop3D):
"""Activate contouring for tdObject on all sliceDirections.
@param prop3D: the actor/prop representing the tdObject (which is
most often a vtkPolyData) in the 3d scene.
"""
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection.addContourObject(tdObject, prop3D)
def _appendGridCommandsToMenu(self, menu, eventWidget, disable=True):
"""Appends the slice grid commands to a menu. This can be used
to build up the context menu or the drop-down one.
"""
commandsTuple = [
('C&reate Slice', 'Create a new slice',
self._handlerCreateSlice, False),
('---',),
('Select &All', 'Select all slices',
self._handlerSliceSelectAll, False),
('D&Eselect All', 'Deselect all slices',
self._handlerSliceDeselectAll, False),
('---',),
('&Show', 'Show selected slices',
self._handlerSliceShow, True),
('&Hide', 'Hide selected slices',
self._handlerSliceHide, True),
('&Interaction ON', 'Activate Interaction for all selected slices',
self._handlerSliceInteractionOn, True),
('I&nteraction OFF',
'Deactivate Interaction for all selected slices',
self._handlerSliceInteractionOff, True),
('Set &Opacity', 'Change opacity of all selected slices',
self._handlerSliceSetOpacity, True),
('---',),
('&Lock to Points', 'Move the selected slices to selected points',
self._handlerSliceLockToPoints, True),
('---',),
('Reset to A&xial', 'Reset the selected slices to Axial',
self._handlerSliceResetToAxial, True),
('Reset to &Coronal', 'Reset the selected slices to Coronal',
self._handlerSliceResetToCoronal, True),
('Reset to Sa&gittal', 'Reset the selected slices to Sagittal',
self._handlerSliceResetToSagittal, True),
('---',), # important! one-element tuple...
('&Delete', 'Delete selected slices',
self._handlerSliceDelete, True)]
disableList = self._appendGridCommandsTupleToMenu(
menu, eventWidget, commandsTuple, disable)
return disableList
def _bindEvents(self):
controlFrame = self.slice3dVWR.controlFrame
wx.EVT_BUTTON(controlFrame, controlFrame.createSliceButtonId,
self._handlerCreateSlice)
# for ortho view use sliceDirection.createOrthoView()
wx.grid.EVT_GRID_CELL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_LABEL_RIGHT_CLICK(
self._grid, self._handlerGridRightClick)
wx.grid.EVT_GRID_RANGE_SELECT(
self._grid, self._handlerGridRangeSelect)
# now do the fusion stuff
wx.EVT_CHOICE(
self.slice3dVWR.controlFrame,
self.slice3dVWR.controlFrame.overlayModeChoice.GetId(),
self._handlerOverlayModeChoice)
wx.EVT_COMMAND_SCROLL(
self.slice3dVWR.controlFrame,
self.slice3dVWR.controlFrame.fusionAlphaSlider.GetId(),
self._handlerFusionAlphaSlider)
def close(self):
for sliceName, sd in self._sliceDirectionsDict.items():
self._destroySlice(sliceName)
def _createSlice(self, sliceName):
if sliceName:
if sliceName in self._sliceDirectionsDict:
wx.LogError("A slice with that name already exists.")
return None
else:
newSD = sliceDirection(sliceName, self)
self._sliceDirectionsDict[sliceName] = newSD
# setup the correct overlayMode and fusionAlpha
newSD.overlayMode = self.overlayMode
newSD.fusionAlpha = self.fusionAlpha
# now attach all inputs to it
for i in self.slice3dVWR._inputs:
if i['Connected'] == 'vtkImageDataPrimary' or \
i['Connected'] == 'vtkImageDataOverlay':
newSD.addData(i['inputData'])
# add it to our grid
nrGridRows = self._grid.GetNumberRows()
self._grid.AppendRows()
self._grid.SetCellValue(nrGridRows, self._gridNameCol,
sliceName)
# set the relevant cells up for Boolean
for col in [self._gridEnabledCol, self._gridInteractionCol]:
# instead of SetCellRenderer, you could have used
# wxGrid.SetColFormatBool()
self._grid.SetCellRenderer(
nrGridRows, col, wx.grid.GridCellBoolRenderer())
self._grid.SetCellAlignment(
nrGridRows, col, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
# set initial boolean values
self._setSliceEnabled(sliceName, True)
self._setSliceInteraction(sliceName, True)
# and initialise the output polydata
self.ipwAppendPolyData.AddInput(newSD.primaryPolyData)
return newSD
def _destroySlice(self, sliceName):
"""Destroy the named slice."""
if sliceName in self._sliceDirectionsDict:
sliceDirection = self._sliceDirectionsDict[sliceName]
# remove it from the polydata output
self.ipwAppendPolyData.RemoveInput(
sliceDirection.primaryPolyData)
# this will disconnect all inputs
sliceDirection.close()
# remove from the grid
row = self._findGridRowByName(sliceName)
if row >= 0:
self._grid.DeleteRows(row)
# and remove it from our dict
del self._sliceDirectionsDict[sliceName]
def _findGridRowByName(self, sliceName):
nrGridRows = self._grid.GetNumberRows()
rowFound = False
row = 0
while not rowFound and row < nrGridRows:
value = self._grid.GetCellValue(row, self._gridNameCol)
rowFound = (value == sliceName)
row += 1
if rowFound:
# prepare and return the row
row -= 1
return row
else:
return -1
def get_slice_geometries(self):
"""Return dict mapping from slice direction names to
3-element tuples: origin, point1, point2.
"""
geoms = {}
for name, sd in self._sliceDirectionsDict.items():
geoms[name] = sd.get_slice_geometry()
return geoms
def set_slice_geometries(self, geoms):
"""Given the dict returned by get_slice_geometries(),
set all slices to the given plane geometries.
"""
for name, geom in geoms.items():
try:
sd = self._sliceDirectionsDict[name]
sd.set_slice_geometry(geom)
except KeyError:
pass
def getSelectedSliceDirections(self):
"""Returns list with bindings to user-selected sliceDirections.
"""
selectedSliceNames = self._getSelectedSliceNames()
selectedSliceDirections = [self._sliceDirectionsDict[sliceName]
for sliceName in selectedSliceNames]
return selectedSliceDirections
def get_all_slice_names(self):
return self._sliceDirectionsDict.keys()
def _getSelectedSliceNames(self):
"""
"""
sliceNames = []
selectedRows = self._grid.GetSelectedRows()
for row in selectedRows:
sliceNames.append(
self._grid.GetCellValue(row, self._gridNameCol))
return sliceNames
def _handlerCreateSlice(self, event):
sliceName = self.slice3dVWR.controlFrame.createSliceComboBox.GetValue()
newSD = self._createSlice(sliceName)
if newSD:
if sliceName == 'Coronal':
newSD.resetToACS(1)
elif sliceName == 'Sagittal':
newSD.resetToACS(2)
# a new slice was added, re-render!
self.slice3dVWR.render3D()
def _handlerGridRightClick(self, gridEvent):
"""This will popup a context menu when the user right-clicks on the
grid.
"""
pmenu = wx.Menu('Slices Context Menu')
self._appendGridCommandsToMenu(pmenu, self._grid)
self._grid.PopupMenu(pmenu, gridEvent.GetPosition())
def _handlerOverlayModeChoice(self, event):
ss = self.slice3dVWR.controlFrame.overlayModeChoice.\
GetStringSelection()
# look it up
self.overlayMode = sliceDirection.overlayModes[ss]
for sliceName, sliceDir in self._sliceDirectionsDict.items():
sliceDir.overlayMode = self.overlayMode
sliceDir.setAllOverlayLookupTables()
if len(self._sliceDirectionsDict) > 0:
self.slice3dVWR.render3D()
def _handlerFusionAlphaSlider(self, event):
val = self.slice3dVWR.controlFrame.fusionAlphaSlider.GetValue()
self.fusionAlpha = val / 100.0
for sliceName, sliceDir in self._sliceDirectionsDict.items():
sliceDir.fusionAlpha = self.fusionAlpha
sliceDir.setAllOverlayLookupTables()
if len(self._sliceDirectionsDict) > 0:
self.slice3dVWR.render3D()
def _handlerSliceSelectAll(self, event):
for row in range(self._grid.GetNumberRows()):
self._grid.SelectRow(row, True)
def _handlerSliceDeselectAll(self, event):
self._grid.ClearSelection()
def _handlerSliceLockToPoints(self, event):
worldPoints = self.slice3dVWR.selectedPoints.getSelectedWorldPoints()
if len(worldPoints) >= 3:
selectedSliceDirections = self.getSelectedSliceDirections()
for sliceDirection in selectedSliceDirections:
sliceDirection.lockToPoints(
worldPoints[0], worldPoints[1], worldPoints[2])
if selectedSliceDirections:
self.slice3dVWR.render3D()
else:
wx.LogMessage("You have to select at least three points.")
def _handlerSliceHide(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._setSliceEnabled(name, False)
self.slice3dVWR.render3D()
def _handlerSliceShow(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._setSliceEnabled(name, True)
self.slice3dVWR.render3D()
def _handlerSliceShowHide(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._setSliceEnabled(
name, not self._sliceDirectionsDict[name].getEnabled())
self.slice3dVWR.render3D()
def _handlerSliceInteraction(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._setSliceInteraction(
name,
not self._sliceDirectionsDict[name].getInteractionEnabled())
def _handlerSliceInteractionOn(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._setSliceInteraction(
name,
True)
def _handlerSliceInteractionOff(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._setSliceInteraction(
name,
False)
def _handlerSliceSetOpacity(self, event):
opacityText = wx.GetTextFromUser(
'Enter a new opacity value (0.0 to 1.0) for all selected '
'slices.')
if opacityText:
try:
opacity = float(opacityText)
except ValueError:
pass
else:
if opacity > 1.0:
opacity = 1.0
elif opacity < 0.0:
opacity = 0.0
names = self._getSelectedSliceNames()
for name in names:
self._setSliceOpacity(name, opacity)
def _handlerSliceDelete(self, event):
names = self._getSelectedSliceNames()
for name in names:
self._destroySlice(name)
if names:
self.slice3dVWR.render3D()
def _handlerSliceACS(self, event):
selection = self.slice3dVWR.controlFrame.acsChoice.GetSelection()
names = self._getSelectedSliceNames()
for name in names:
sd = self._sliceDirectionsDict[name]
sd.resetToACS(selection)
if names:
self.slice3dVWR.render3D()
def _handlerSliceResetToAxial(self, event):
names = self._getSelectedSliceNames()
for name in names:
sd = self._sliceDirectionsDict[name]
sd.resetToACS(0)
if names:
self.slice3dVWR.render3D()
def _handlerSliceResetToCoronal(self, event):
names = self._getSelectedSliceNames()
for name in names:
sd = self._sliceDirectionsDict[name]
sd.resetToACS(1)
if names:
self.slice3dVWR.render3D()
def _handlerSliceResetToSagittal(self, event):
names = self._getSelectedSliceNames()
for name in names:
sd = self._sliceDirectionsDict[name]
sd.resetToACS(2)
if names:
self.slice3dVWR.render3D()
def _initialiseGrid(self):
# setup default selection background
gsb = self.slice3dVWR.gridSelectionBackground
self._grid.SetSelectionBackground(gsb)
# delete all existing columns
self._grid.DeleteCols(0, self._grid.GetNumberCols())
# we need at least one row, else adding columns doesn't work (doh)
self._grid.AppendRows()
# setup columns
self._grid.AppendCols(len(self._gridCols))
for colIdx in range(len(self._gridCols)):
# add labels
self._grid.SetColLabelValue(colIdx, self._gridCols[colIdx][0])
# set size according to labels
self._grid.AutoSizeColumns()
for colIdx in range(len(self._gridCols)):
# now set size overrides
size = self._gridCols[colIdx][1]
if size > 0:
self._grid.SetColSize(colIdx, size)
# make sure we have no rows again...
self._grid.DeleteRows(0, self._grid.GetNumberRows())
def _initUI(self):
"""Perform any UI initialisation during setup.
"""
#
c = self.slice3dVWR.controlFrame.overlayModeChoice
c.Clear()
overlayModeTexts = sliceDirection.overlayModes.keys()
overlayModeTexts.sort()
for overlayModeText in overlayModeTexts:
c.Append(overlayModeText)
c.SetStringSelection('Green Opacity Range')
def removeData(self, theData):
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection.removeData(theData)
def removeContourObject(self, tdObject):
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection.removeContourObject(tdObject)
def resetAll(self):
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection._resetPrimary()
sliceDirection._resetOverlays()
sliceDirection._syncContours()
def set_lookup_table(self, lut):
for sname, sdirection in self._sliceDirectionsDict.items():
sdirection.set_lookup_table(lut)
def setCurrentCursor(self, cursor):
self.currentCursor = cursor
cf = self.slice3dVWR.controlFrame
# ===================
# discrete position
discretePos = cursor[0:3]
cf.sliceCursorDiscreteText.SetValue('%d, %d, %d' % tuple(discretePos))
# ===================
# world position
worldPos = self.slice3dVWR.getWorldPositionInInputData(discretePos)
if worldPos != None:
worldPosString = '%.2f, %.2f, %.2f' % tuple(worldPos)
else:
worldPosString = 'NA'
cf.sliceCursorWorldText.SetValue(worldPosString)
# ===================
# scalar values
values = self.slice3dVWR.getValuesAtDiscretePositionInInputData(
discretePos)
if values != None:
valuesString = '%s' % (values,)
else:
valuesString = 'NA'
cf.sliceCursorScalarsText.SetValue(valuesString)
def setCurrentSliceDirection(self, sliceDirection):
# find this sliceDirection
sdFound = False
for sliceName, sd in self._sliceDirectionsDict.items():
if sd == sliceDirection:
sdFound = True
break
if sdFound:
row = self._findGridRowByName(sliceName)
if row >= 0:
self._grid.SelectRow(row, False)
def _setSliceEnabled(self, sliceName, enabled):
if sliceName in self._sliceDirectionsDict:
sd = self._sliceDirectionsDict[sliceName]
if enabled:
sd.enable()
else:
sd.disable()
row = self._findGridRowByName(sliceName)
if row >= 0:
gen_utils.setGridCellYesNo(
self._grid, row, self._gridEnabledCol, enabled)
def _setSliceInteraction(self, sliceName, interaction):
if sliceName in self._sliceDirectionsDict:
sd = self._sliceDirectionsDict[sliceName]
if interaction:
sd.enableInteraction()
else:
sd.disableInteraction()
row = self._findGridRowByName(sliceName)
if row >= 0:
gen_utils.setGridCellYesNo(
self._grid, row, self._gridInteractionCol, interaction)
def _setSliceOpacity(self, sliceName, opacity):
if sliceName in self._sliceDirectionsDict:
sd = self._sliceDirectionsDict[sliceName]
for ipw in sd._ipws:
ipw.GetTexturePlaneProperty().SetOpacity(opacity)
def syncContoursToObject(self, tdObject):
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection.syncContourToObject(tdObject)
def syncContoursToObjectViaProp(self, prop):
for sliceName, sliceDirection in self._sliceDirectionsDict.items():
sliceDirection.syncContourToObjectViaProp(prop)
def enableEnabledSliceDirections(self):
"""Enable all sliceDirections that are enabled in the grid control.
This is used as part of the slice3dVWR enable/disable execution logic.
"""
numRows = self._grid.GetNumberRows()
for row in range(numRows):
# val can be 0 or 1
val = int(self._grid.GetCellValue(row, self._gridEnabledCol))
if val:
name = self._grid.GetCellValue(row, self._gridNameCol)
self._sliceDirectionsDict[name].enable()
def disableEnabledSliceDirections(self):
numRows = self._grid.GetNumberRows()
for row in range(numRows):
# val can be 0 or 1
val = int(self._grid.GetCellValue(row, self._gridEnabledCol))
if val:
name = self._grid.GetCellValue(row, self._gridNameCol)
self._sliceDirectionsDict[name].disable()
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import cStringIO
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
import wx
# wxPython 2.8.8.1 wx.aui bugs severely on GTK. See:
# http://trac.wxwidgets.org/ticket/9716
# Until this is fixed, use this PyAUI to which I've added a
# wx.aui compatibility layer.
if wx.Platform == "__WXGTK__":
from external import PyAUI
wx.aui = PyAUI
else:
import wx.aui
# need listmix.ColumnSorterMixin
import wx.lib.mixins.listctrl as listmix
from wx import BitmapFromImage, ImageFromStream
from resources.python import DICOMBrowserPanels
reload(DICOMBrowserPanels)
class StudyColumns:
patient = 0
patient_id = 1
description = 2
date = 3
num_images = 4
num_series = 5
class SeriesColumns:
description = 0
modality = 1
num_images = 2
row_col = 3
class FilesColumns:
name = 0
#----------------------------------------------------------------------
def getSmallUpArrowData():
return \
'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00<IDAT8\x8dcddbf\xa0\x040Q\xa4{h\x18\xf0\xff\xdf\xdf\xffd\x1b\x00\xd3\
\x8c\xcf\x10\x9c\x06\xa0k\xc2e\x08m\xc2\x00\x97m\xd8\xc41\x0c \x14h\xe8\xf2\
\x8c\xa3)q\x10\x18\x00\x00R\xd8#\xec\xb2\xcd\xc1Y\x00\x00\x00\x00IEND\xaeB`\
\x82'
def getSmallUpArrowBitmap():
return BitmapFromImage(getSmallUpArrowImage())
def getSmallUpArrowImage():
stream = cStringIO.StringIO(getSmallUpArrowData())
return ImageFromStream(stream)
#----------------------------------------------------------------------
def getSmallDnArrowData():
return \
"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x00\x10\x00\x00\x00\x10\x08\x06\
\x00\x00\x00\x1f\xf3\xffa\x00\x00\x00\x04sBIT\x08\x08\x08\x08|\x08d\x88\x00\
\x00\x00HIDAT8\x8dcddbf\xa0\x040Q\xa4{\xd4\x00\x06\x06\x06\x06\x06\x16t\x81\
\xff\xff\xfe\xfe'\xa4\x89\x91\x89\x99\x11\xa7\x0b\x90%\ti\xc6j\x00>C\xb0\x89\
\xd3.\x10\xd1m\xc3\xe5*\xbc.\x80i\xc2\x17.\x8c\xa3y\x81\x01\x00\xa1\x0e\x04e\
?\x84B\xef\x00\x00\x00\x00IEND\xaeB`\x82"
def getSmallDnArrowBitmap():
return BitmapFromImage(getSmallDnArrowImage())
def getSmallDnArrowImage():
stream = cStringIO.StringIO(getSmallDnArrowData())
return ImageFromStream(stream)
#----------------------------------------------------------------------
class SortedListCtrl(wx.ListCtrl, listmix.ColumnSorterMixin):
def __init__(self, parent, ID, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
wx.ListCtrl.__init__(self, parent, ID, pos, size, style)
# for the ColumnSorterMixin: this should be a dict mapping
# from item data values to sequence of values for the columns.
# These values will be used for sorting
self.itemDataMap = {}
self.il = wx.ImageList(16, 16)
self.sm_up = self.il.Add(getSmallUpArrowBitmap())
self.sm_dn = self.il.Add(getSmallDnArrowBitmap())
self.SetImageList(self.il, wx.IMAGE_LIST_SMALL)
listmix.ColumnSorterMixin.__init__(self, 5)
def GetListCtrl(self):
"""Method required by ColumnSorterMixin.
"""
return self
def GetSortImages(self):
"""Used by the ColumnSorterMixin.
"""
return (self.sm_dn, self.sm_up)
def auto_size_columns(self):
for idx in range(self.GetColumnCount()):
self.SetColumnWidth(idx, wx.LIST_AUTOSIZE)
class SortedAutoWidthListCtrl(listmix.ListCtrlAutoWidthMixin, SortedListCtrl):
def __init__(self, parent, ID, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=0):
SortedListCtrl.__init__(self, parent, ID, pos, size, style)
listmix.ListCtrlAutoWidthMixin.__init__(self)
class DICOMBrowserFrame(wx.Frame):
def __init__(self, parent, id=-1, title="", name=""):
wx.Frame.__init__(self, parent, id=id, title=title,
pos=wx.DefaultPosition, size=(800,800), name=name)
self.menubar = wx.MenuBar()
self.SetMenuBar(self.menubar)
nav_menu = wx.Menu()
self.id_next_image = wx.NewId()
nav_menu.Append(self.id_next_image, "&Next image\tCtrl-N",
"Go to next image in series", wx.ITEM_NORMAL)
self.id_prev_image = wx.NewId()
nav_menu.Append(self.id_prev_image, "&Previous image\tCtrl-P",
"Go to previous image in series", wx.ITEM_NORMAL)
self.menubar.Append(nav_menu, "&Navigation")
views_menu = wx.Menu()
views_default_id = wx.NewId()
views_menu.Append(views_default_id, "&Default\tCtrl-0",
"Activate default view layout.", wx.ITEM_NORMAL)
views_max_image_id = wx.NewId()
views_menu.Append(views_max_image_id, "&Maximum image size\tCtrl-1",
"Activate maximum image view size layout.",
wx.ITEM_NORMAL)
self.menubar.Append(views_menu, "&Views")
# tell FrameManager to manage this frame
self._mgr = wx.aui.AuiManager()
self._mgr.SetManagedWindow(self)
self._mgr.AddPane(self._create_dirs_pane(), wx.aui.AuiPaneInfo().
Name("dirs").
Caption("Files and Directories to Scan").
Top().Row(0).
Top().
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_studies_pane(), wx.aui.AuiPaneInfo().
Name("studies").Caption("Studies").
Top().Row(1).
BestSize(wx.Size(600, 100)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_series_pane(), wx.aui.AuiPaneInfo().
Name("series").Caption("Series").Top().Row(2).
BestSize(wx.Size(600, 100)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_files_pane(), wx.aui.AuiPaneInfo().
Name("files").Caption("Image Files").
Left().
BestSize(wx.Size(200,400)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_meta_pane(), wx.aui.AuiPaneInfo().
Name("meta").Caption("Image Metadata").
Left().
BestSize(wx.Size(200,400)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_image_pane(), wx.aui.AuiPaneInfo().
Name("image").Caption("Image").
Center().
BestSize(wx.Size(400,400)).
CloseButton(False).MaximizeButton(True))
self.SetMinSize(wx.Size(400, 300))
self._perspectives = {}
self._perspectives['default'] = self._mgr.SavePerspective()
self._mgr.GetPane("dirs").Hide()
self._mgr.GetPane("studies").Hide()
self._mgr.GetPane("series").Hide()
self._mgr.GetPane("files").Hide()
self._mgr.GetPane("meta").Hide()
self._perspectives['max_image'] = self._mgr.SavePerspective()
self._mgr.LoadPerspective(self._perspectives['default'])
self._mgr.Update()
# we bind the views events here, because the functionality is
# completely encapsulated in the frame and does not need to
# round-trip to the DICOMBrowser main module.
self.Bind(wx.EVT_MENU, lambda e: self._mgr.LoadPerspective(
self._perspectives['default']), id=views_default_id)
self.Bind(wx.EVT_MENU, lambda e: self._mgr.LoadPerspective(
self._perspectives['max_image']), id=views_max_image_id)
def close(self):
del self.dirs_pane
del self.studies_lc
del self.series_lc
del self.files_lc
del self.files_pane
self.Destroy()
def _create_dirs_pane(self):
# instantiate the wxGlade-created frame
fpf = DICOMBrowserPanels.FilesPanelFrame(self, id=-1,
size=(200, 150))
# reparent the panel to us
panel = fpf.files_panel
panel.Reparent(self)
# still need fpf.* to bind everything
# but we can destroy fpf (everything has been reparented)
fpf.Destroy()
panel.ad_button = fpf.ad_button
panel.af_button = fpf.af_button
panel.scan_button = fpf.scan_button
panel.dirs_files_tc = fpf.dirs_files_tc
self.dirs_pane = panel
return panel
def _create_files_pane(self):
# instantiated wxGlade frame
iff = DICOMBrowserPanels.ImageFilesFrame(self, id=-1,
size=(400,300))
panel = iff.files_panel
# reparent the panel to us
panel.Reparent(self)
iff.Destroy()
panel.ipp_sort_button = iff.ipp_sort_button
sl = iff.files_lc
sl.InsertColumn(FilesColumns.name, "Full name")
# we'll autosize this column later
sl.SetColumnWidth(FilesColumns.name, 300)
#sl.InsertColumn(SeriesColumns.modality, "Modality")
self.files_lc = sl
self.files_pane = panel
return panel
def _create_image_pane(self):
# instantiate the wxGlade-created frame
ipf = DICOMBrowserPanels.ImagePanelFrame(self, id=-1,
size=(400, 300))
# reparent the panel to us
panel = ipf.image_panel
panel.Reparent(self)
# still need fpf.* to bind everything
# but we can destroy fpf (everything has been reparented)
ipf.Destroy()
panel.rwi = ipf.rwi
panel.lock_pz_cb = ipf.lock_pz_cb
panel.lock_wl_cb = ipf.lock_wl_cb
panel.reset_b = ipf.reset_b
self.image_pane = panel
return panel
def _create_meta_pane(self):
ml = SortedAutoWidthListCtrl(self, -1,
style=wx.LC_REPORT |
wx.LC_HRULES | wx.LC_VRULES |
wx.LC_SINGLE_SEL)
ml.InsertColumn(0, "Key")
ml.SetColumnWidth(0, 70)
ml.InsertColumn(1, "Value")
ml.SetColumnWidth(1, 70)
self.meta_lc = ml
return ml
def _create_studies_pane(self):
sl = SortedAutoWidthListCtrl(self, -1,
style=wx.LC_REPORT |
wx.LC_HRULES |
wx.LC_SINGLE_SEL)
sl.InsertColumn(StudyColumns.patient, "Patient")
sl.SetColumnWidth(StudyColumns.patient, 170)
sl.InsertColumn(StudyColumns.patient_id, "Patient ID")
sl.SetColumnWidth(StudyColumns.patient_id, 100)
sl.InsertColumn(StudyColumns.description, "Description")
sl.SetColumnWidth(StudyColumns.description, 170)
sl.InsertColumn(StudyColumns.date, "Date") # study date
sl.SetColumnWidth(StudyColumns.date, 70)
# total number of images
sl.InsertColumn(StudyColumns.num_images, "# Images")
sl.InsertColumn(StudyColumns.num_series, "# Series")
self.studies_lc = sl
return sl
def _create_series_pane(self):
sl = SortedAutoWidthListCtrl(self, -1,
style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_SINGLE_SEL,
size=(600,120))
sl.InsertColumn(SeriesColumns.description, "Description")
sl.SetColumnWidth(SeriesColumns.description, 170)
sl.InsertColumn(SeriesColumns.modality, "Modality")
sl.InsertColumn(SeriesColumns.num_images, "# Images")
sl.InsertColumn(SeriesColumns.row_col, "Size")
self.series_lc = sl
return sl
def render_image(self):
"""Update embedded RWI, i.e. update the image.
"""
self.image_pane.rwi.Render()
def set_default_view(self):
self._mgr.LoadPerspective(
self._perspectives['default'])
| Python |
#Hacked out of from a class contained in Charl Botha's comedi_utils.py
#Incorporated edits by by Corine Slagboom & Noeska Smit which formed part of their comedi_utils used as part of their Emphysema Viewer.
#Final version by Francois Malan (2010-2011)
from module_kits.vtk_kit.utils import DVOrientationWidget
import operator
import vtk
import wx
class OverlaySliceViewer:
"""Class for viewing 3D binary masks in a slice-view.
Supports arbitrary number of overlays in user-definable colours.
"""
has_active_slices = False
def __init__(self, rwi, renderer):
self.rwi = rwi
self.renderer = renderer
istyle = vtk.vtkInteractorStyleTrackballCamera()
rwi.SetInteractorStyle(istyle)
# we unbind the existing mousewheel handler so it doesn't
# interfere
rwi.Unbind(wx.EVT_MOUSEWHEEL)
rwi.Bind(wx.EVT_MOUSEWHEEL, self._handler_mousewheel)
#This is a collection of 1- or 3-component image plane widgets. Each entry corresponds to a single overlay.
self.ipw_triads = {}
self.add_overlay(0, [0, 0, 0, 0.1]) #Almost-transparent black - for showing the pickable plane stored at id = 0.
# we only set the picker on the visible IPW, else the
# invisible IPWs block picking!
self.picker = vtk.vtkCellPicker()
self.picker.SetTolerance(0.005)
self.ipw_triads[0][0].SetPicker(self.picker)
self.outline_source = vtk.vtkOutlineCornerFilter()
m = vtk.vtkPolyDataMapper()
m.SetInput(self.outline_source.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
a.PickableOff()
self.outline_actor = a
self.dv_orientation_widget = DVOrientationWidget(rwi)
# this can be used by clients to store the current world
# position
self.current_world_pos = (0,0,0)
self.current_index_pos = (0,0,0)
def add_overlay(self, id, rgba_colour):
"""Creates and ads a new (set of) image plane widgets corresponding to a new overlay.
id : the string id which will be used to identify this overlay for future lookups.
rgba_colour : a length 4 vector giving the red,green,blue,opacity value for this overlay. Range = [0,1]
"""
if self.ipw_triads.has_key(id):
raise ValueError('The overlay id = "%s" is already in use! Cannot this id - aborting.' % id)
else:
new_ipw_triad = [vtk.vtkImagePlaneWidget() for _ in range(3)]
lut = new_ipw_triad[0].GetLookupTable()
lut.SetNumberOfTableValues(2)
if len(self.ipw_triads) == 0:
lut.SetTableValue(0,0,0,0,0.1) #Almost-transparent black - for showing the pickable plane
else:
lut.SetTableValue(0,0,0,0,0) #Transparent: for non-interfering overlay on existing layers
lut.SetTableValue(1,rgba_colour[0],rgba_colour[1],rgba_colour[2],rgba_colour[3]) #Specified RGBA for binary "true"
lut.Build()
for ipw in new_ipw_triad:
ipw.SetInteractor(self.rwi)
ipw.SetLookupTable(lut)
self.ipw_triads[id] = new_ipw_triad
base_ipw_triad = self.ipw_triads[0]
# now actually connect the sync_overlay observer
for i,ipw in enumerate(base_ipw_triad):
ipw.AddObserver('InteractionEvent',lambda vtk_o, vtk_e, i=i: self.observer_sync_overlay(base_ipw_triad, new_ipw_triad, i))
#fmalan-edit based on nnsmit-edit
def observer_sync_overlay(self, master_ipw_triad, slave_ipw_triad, ipw_idx):
# get the primary IPW
master_ipw = master_ipw_triad[ipw_idx]
# get the overlay IPW
slave_ipw = slave_ipw_triad[ipw_idx]
# get plane geometry from primary
o,p1,p2 = master_ipw.GetOrigin(),master_ipw.GetPoint1(),master_ipw.GetPoint2()
# and apply to the overlay
slave_ipw.SetOrigin(o)
slave_ipw.SetPoint1(p1)
slave_ipw.SetPoint2(p2)
slave_ipw.UpdatePlacement()
# end edit
def close(self):
for id in self.ipw_triads.keys():
self.set_input(id, None)
self.dv_orientation_widget.close()
def activate_slice(self, id, idx):
if idx in [1,2]:
self.ipw_triads[id][idx].SetEnabled(1)
self.ipw_triads[id][idx].SetPicker(self.picker)
def deactivate_slice(self, id, idx):
if idx in [1,2]:
self.ipw_triads[id][idx].SetEnabled(0)
self.ipw_triads[id][idx].SetPicker(None)
def _get_input(self, id):
return self.ipw_triads[id].GetInput()
def get_world_pos(self, image_pos):
"""Given image coordinates, return the corresponding world
position.
"""
idata = self._get_input(0)
if not idata:
return None
ispacing = idata.GetSpacing()
iorigin = idata.GetOrigin()
# calculate real coords
world = map(operator.add, iorigin,
map(operator.mul, ispacing, image_pos[0:3]))
return world
def set_perspective(self):
cam = self.renderer.GetActiveCamera()
cam.ParallelProjectionOff()
def set_parallel(self):
cam = self.renderer.GetActiveCamera()
cam.ParallelProjectionOn()
def _handler_mousewheel(self, event):
# event.GetWheelRotation() is + or - 120 depending on
# direction of turning.
if event.ControlDown():
delta = 10
elif event.ShiftDown():
delta = 1
else:
# if user is NOT doing shift / control, we pass on to the
# default handling which will give control to the VTK
# mousewheel handlers.
self.rwi.OnMouseWheel(event)
return
if event.GetWheelRotation() > 0:
self._ipw1_delta_slice(+delta)
else:
self._ipw1_delta_slice(-delta)
self.render()
for id in self.ipw_triads.keys():
self.ipw_triads[id][0].InvokeEvent('InteractionEvent')
def _ipw1_delta_slice(self, delta):
"""Move to the delta slices fw/bw, IF the IPW is currently
aligned with one of the axes.
"""
ipw = self.ipw_triads[0][0]
if ipw.GetPlaneOrientation() < 3:
ci = ipw.GetSliceIndex()
ipw.SetSliceIndex(ci + delta)
def render(self):
self.rwi.GetRenderWindow().Render()
#TODO: Check this code
# nnsmit edit
# synch those overlays:
'''
if self.overlay_active == 1:
for i, ipw_overlay in enumerate(self.overlay_ipws):
self.observer_sync_overlay(self.ipw_triads, i, 0)
self.observer_sync_overlay(self.ipw_triads, i, 1)
self.observer_sync_overlay(self.ipw_triads, i, 2)
'''
# end edit
def reset_camera(self):
self.renderer.ResetCamera()
def reset_to_default_view(self, view_index):
"""
@param view_index 2 for XY
"""
if view_index == 2:
cam = self.renderer.GetActiveCamera()
# then make sure it's up is the right way
cam.SetViewUp(0,1,0)
# just set the X,Y of the camera equal to the X,Y of the
# focal point.
fp = cam.GetFocalPoint()
cp = cam.GetPosition()
if cp[2] < fp[2]:
z = fp[2] + (fp[2] - cp[2])
else:
z = cp[2]
cam.SetPosition(fp[0], fp[1], z)
# first reset the camera
self.renderer.ResetCamera()
'''
# nnsmit edit
# synch overlays as well:
if self.overlay_active == 1:
for i, ipw_overlay in enumerate(self.overlay_ipws):
ipw_overlay.SetSliceIndex(0)
'''
self.render()
def set_input(self, id, input):
if self.ipw_triads.has_key(id):
selected_ipw_triad = self.ipw_triads[id]
if input == selected_ipw_triad[0].GetInput():
return
if input is None:
ipw_triad = self.ipw_triads[id]
for ipw in ipw_triad:
# argh, this disable causes a render
ipw.SetEnabled(0)
ipw.SetInput(None)
remaining_active_slices = False
if self.has_active_slices:
for key in self.ipw_triads:
if key != 0:
ipw_triad = self.ipw_triads[key]
for ipw in ipw_triad:
if ipw.GetEnabled():
remaining_active_slices = True
break
if remaining_active_slices:
break
if not remaining_active_slices:
self.has_active_slices = False
self.outline_source.SetInput(None)
self.renderer.RemoveViewProp(self.outline_actor)
self.dv_orientation_widget.set_input(None)
base_ipw_triad = self.ipw_triads[0]
for i, ipw in enumerate(base_ipw_triad):
ipw.SetInput(None)
ipw.SetEnabled(0)
else:
orientations = [2, 0, 1]
active = [1, 0, 0]
if not self.has_active_slices:
self.outline_source.SetInput(input)
self.renderer.AddViewProp(self.outline_actor)
self.dv_orientation_widget.set_input(input)
base_ipw_triad = self.ipw_triads[0]
for i, ipw in enumerate(base_ipw_triad):
ipw.SetInput(input)
ipw.SetPlaneOrientation(orientations[i]) # axial
ipw.SetSliceIndex(0)
ipw.SetEnabled(active[i])
self.has_active_slices = True
base_ipw_triad = self.ipw_triads[0]
for i, ipw in enumerate(selected_ipw_triad):
ipw.SetInput(input)
ipw.SetPlaneOrientation(orientations[i]) # axial
ipw.SetSliceIndex(0)
ipw.SetEnabled(active[i])
self.observer_sync_overlay(base_ipw_triad, selected_ipw_triad, i) #sync to the current position of the base (pickable) triad
else:
raise ValueError('The overlay with id = "%s" was not found!' % id) | Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
# NOTES:
# you can't put the RWI in a StaticBox, it never manages to appear.
# mode: add / subtract
# tool: new region growing, level set (with existing mask), draw
# closed polygon, delete
# ARGH. region growing results in bitmask, but polyline and level set
# require a more accurate representation.
# http://www.nabble.com/vtkContourWidget-with-vtkImageViewer2-td18485627.html
# has more information on how to use the vtkContourWidget
# MITK does segmentation on all three orthogonal directions. For more
# info: http://www.mitk.org/slicebasedsegmentation.html
# to scan convert polygon, you could use: vtkPolyDataToImageStencil
# see the example linked to in the VTK documentation (should be the
# same as the ImageTracerWidget example)
# I checked the documentation, it SHOULD work for 2D as well.
# NBNBNB
# think about having bitmaps as the primary storage (or stencils)
# you also start with a regiongrowing (for example)
# can always convert to polygon to do stuff there, convert back
# add mode, subtract mode, current object, delete (like MITK)
# also list of objects with checkboxes for vis and buttons to change
# colour
# snake still missing
# general requirements:
# * multiple objects (i.e. multiple coloured contours per slice)
# slice segmentation modes:
# * polygon mode
# * freehand drawing
# * 2d levelset
# see design notes on p39 of AM2 moleskine
# mask volume import! (user clicks import, gets to select from which
# input) - mask volume is contoured.
# add reset image button just like the DICOMBrowser
# mouse wheel should go to next/previous slice
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
import wx
class Contour:
pass
class Object:
pass
class Slicinator(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
# internal variables
# config variables
self._config.somevar = 3
self._view_frame = None
self._create_view_frame()
self._create_vtk_pipeline()
# dummy input has been set by create_vtk_pipeline, we this
# ivar we record that we are not connected.
self._input_data = None
self._bind_events()
self.view()
# all modules should toggle this once they have shown their
# stuff.
self.view_initialised = True
self.config_to_logic()
self.logic_to_config()
self.config_to_view()
def close(self):
# with this complicated de-init, we make sure that VTK is
# properly taken care of
self._image_viewer.GetRenderer().RemoveAllViewProps()
self._image_viewer.SetupInteractor(None)
self._image_viewer.SetRenderer(None)
# this finalize makes sure we don't get any strange X
# errors when we kill the module.
self._image_viewer.GetRenderWindow().Finalize()
self._image_viewer.SetRenderWindow(None)
self._image_viewer.DebugOn()
del self._image_viewer
# done with VTK de-init
self._view_frame.Destroy()
del self._view_frame
IntrospectModuleMixin.close(self)
ModuleBase.close(self)
def execute_module(self):
pass
def get_input_descriptions(self):
return ('Input VTK image data',)
def set_input(self, idx, input_data):
if input_data == self._input_data:
return
# handle disconnects
if input_data is None:
self._input_data = None
self._set_image_viewer_dummy_input()
else:
# try and link this up
# method will throw an exception if not valid
self._set_image_viewer_input(input_data)
# if we get here, connection was successful
self._input_data = input_data
def get_output_descriptions(self):
return ()
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def config_to_view(self):
pass
def view_to_config(self):
pass
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# because we have an RWI involved, we have to do this
# SafeYield, so that the window does actually appear before we
# call the render. If we don't do this, we get an initial
# empty renderwindow.
wx.SafeYield()
self._render()
# end of API calls
def _bind_events(self):
self._view_frame.reset_image_button.Bind(
wx.EVT_BUTTON, self._handler_reset_image_button)
def _create_view_frame(self):
import resources.python.slicinator_frames
reload(resources.python.slicinator_frames)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
resources.python.slicinator_frames.SlicinatorFrame)
vf = self._view_frame
def _create_vtk_pipeline(self):
if False:
vf = self._view_frame
ren = vtk.vtkRenderer()
vf.rwi.GetRenderWindow().AddRenderer(ren)
else:
self._image_viewer = vtk.vtkImageViewer2()
self._image_viewer.SetupInteractor(self._view_frame.rwi)
self._image_viewer.GetRenderer().SetBackground(0.3,0.3,0.3)
self._set_image_viewer_dummy_input()
def _handler_reset_image_button(self, event):
self._reset_image()
def _init_cw(self):
self._cw = vtk.vtkContourWidget()
rep = vtk.vtkOrientedGlyphContourRepresentation()
self._cw.SetRepresentation(rep)
iapp = vtk.vtkImageActorPointPlacer()
iapp.SetImageActor(self._image_viewer.GetImageActor())
rep.SetPointPlacer(iapp)
self._cw.SetInteractor(self._view_frame.rwi)
self._cw.On()
def _render(self):
self._image_viewer.Render()
#self._view_frame.rwi.Render()
def _reset_image(self):
self._reset_image_wl()
self._reset_image_pz()
self._render()
def _reset_image_pz(self):
"""Reset the pan/zoom of the current image.
"""
ren = self._image_viewer.GetRenderer()
ren.ResetCamera()
def _reset_image_wl(self):
"""Reset the window/level of the current image.
This assumes that the image has already been read and that it
has a valid scalar range.
"""
iv = self._image_viewer
inp = iv.GetInput()
if inp:
r = inp.GetScalarRange()
iv.SetColorWindow(r[1] - r[0])
iv.SetColorLevel(0.5 * (r[1] + r[0]))
def _set_image_viewer_dummy_input(self):
ds = vtk.vtkImageGridSource()
self._image_viewer.SetInput(ds.GetOutput())
def _set_image_viewer_input(self, input_data):
try:
if not input_data.IsA('vtkImageData'):
raise RuntimeError('Invalid input data.')
except AttributeError:
raise RuntimeError('Invalid input data.')
self._image_viewer.SetInput(input_data)
# module.set_input() only gets called right before an
# execute_module, so we can do our thing here.
self._reset_image()
we = input_data.GetWholeExtent()
min,max = we[4], we[5]
self._reset_slice_spin(min, min, max)
def _reset_slice_spin(self, val, min, max):
self._view_frame.slice_spin.SetValue(val)
self._view_frame.slice_spin.SetRange(min,max)
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# Modified by Francois Malan, LUMC / TU Delft
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
import wx
import wx.lib.inspection
import vtk
# wxPython 2.8.8.1 wx.aui bugs severely on GTK. See:
# http://trac.wxwidgets.org/ticket/9716
# Until this is fixed, use this PyAUI to which I've added a
# wx.aui compatibility layer.
if wx.Platform == "__WXGTK__":
from external import PyAUI
wx.aui = PyAUI
else:
import wx.aui
import MaskComBinarPanels
reload(MaskComBinarPanels)
class MaskComBinarFrame(wx.Frame):
"""wx.Frame child class used by MaskComBinar for its
interface.
This is an AUI-managed window, so we create the top-level frame,
and then populate it with AUI panes.
"""
def __init__(self, parent, id=-1, title="", name=""):
wx.Frame.__init__(self, parent, id=id, title=title,
pos=wx.DefaultPosition, size=(800,600), name=name)
self._create_menubar()
# tell FrameManager to manage this frame
self._mgr = wx.aui.AuiManager()
self._mgr.SetManagedWindow(self)
self._mgr.AddPane(self._create_mask_operations_pane(), wx.aui.AuiPaneInfo().
Name("operations").Caption("Operations").Left().
BestSize(wx.Size(275, 65)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_mask_lists_pane(), wx.aui.AuiPaneInfo().
Name("masks").Caption("Masks").Left().
BestSize(wx.Size(275, 450)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_rwi2d_pane(), wx.aui.AuiPaneInfo().
Name("rwi2D").Caption("2D").
Right().
BestSize(wx.Size(300,500)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_rwi3d_pane(), wx.aui.AuiPaneInfo().
Name("rwi3D").Caption("3D").
Center().
BestSize(wx.Size(300,500)).
CloseButton(False).MaximizeButton(True))
self.SetMinSize(wx.Size(400, 300))
# first we save this default perspective with all panes
# visible
self._perspectives = {}
self._perspectives['default'] = self._mgr.SavePerspective()
# then we hide all of the panes except the renderer
#self._mgr.GetPane("Masks").Hide()
self._mgr.GetPane("files").Hide()
self._mgr.GetPane("meta").Hide()
# save the perspective again
self._perspectives['max_image'] = self._mgr.SavePerspective()
# and put back the default perspective / view
self._mgr.LoadPerspective(self._perspectives['default'])
# finally tell the AUI manager to do everything that we've
# asked
self._mgr.Update()
# # we bind the views events here, because the functionality is
# # completely encapsulated in the frame and does not need to
# # round-trip to the DICOMBrowser main module.
# self.Bind(wx.EVT_MENU, self._handler_default_view,
# id=views_default_id)
#
# self.Bind(wx.EVT_MENU, self._handler_max_image_view,
# id=views_max_image_id)
def close(self):
self.Destroy()
def _create_menubar(self):
self.menubar = wx.MenuBar()
self.SetMenuBar(self.menubar)
menu_file = wx.Menu()
self.id_open_binary_mask = wx.NewId()
menu_file.Append(self.id_open_binary_mask, "&Open binary Mask\tCtrl-O",
"Open a binary mask", wx.ITEM_NORMAL)
self.id_open_multi_mask = wx.NewId()
menu_file.Append(self.id_open_multi_mask, "&Open multilabel Mask\tCtrl-Alt-O",
"Open an integer-labeled mask", wx.ITEM_NORMAL)
self.id_open_mask_dir = wx.NewId()
menu_file.Append(self.id_open_mask_dir, "&Open Directory\tCtrl-Shift-O",
"Open all masks from a directory", wx.ITEM_NORMAL)
self.id_save_mask = wx.NewId()
menu_file.Append(self.id_save_mask, "&Save Mask\tCtrl-S",
"Save a mask", wx.ITEM_NORMAL)
self.id_save_multi_mask = wx.NewId()
menu_file.Append(self.id_save_multi_mask, "&Save multilabel Mask\tCtrl-Alt-S",
"Save selected (A) to multi-label (integer-labeled) mask", wx.ITEM_NORMAL)
self.id_quit = wx.NewId()
menu_file.Append(self.id_quit, "&Exit\tCtrl-Q",
"Exit MaskComBinar", wx.ITEM_NORMAL)
menu_advanced = wx.Menu()
self.id_introspect = wx.NewId()
menu_advanced.Append(self.id_introspect, "Introspect",
"Open an introspection window", wx.ITEM_NORMAL)
menu_help = wx.Menu()
self.id_about = wx.NewId()
menu_help.Append(self.id_about, "About",
"About MaskComBinar", wx.ITEM_NORMAL)
self.menubar.Append(menu_file, "&File")
self.menubar.Append(menu_advanced, "&Advanced")
self.menubar.Append(menu_help, "&Help")
def _create_rwi2d_pane(self):
panel = wx.Panel(self, -1)
self.rwi2d = wxVTKRenderWindowInteractor(panel, -1, (400,400))
self.reset_cam2d_button = wx.Button(panel, -1, "Reset View")
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add(self.reset_cam2d_button)
sizer1 = wx.BoxSizer(wx.VERTICAL)
sizer1.Add(self.rwi2d, 1, wx.EXPAND|wx.BOTTOM, 7)
sizer1.Add(button_sizer)
tl_sizer = wx.BoxSizer(wx.VERTICAL)
tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7)
panel.SetSizer(tl_sizer)
tl_sizer.Fit(panel)
return panel
def _create_rwi3d_pane(self):
panel = wx.Panel(self, -1)
self.rwi3d = wxVTKRenderWindowInteractor(panel, -1, (400,400))
istyle = vtk.vtkInteractorStyleTrackballCamera()
self.rwi3d.SetInteractorStyle(istyle)
self.reset_cam3d_button = wx.Button(panel, -1, "Reset Zoom")
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add(self.reset_cam3d_button)
sizer1 = wx.BoxSizer(wx.VERTICAL)
sizer1.Add(self.rwi3d, 1, wx.EXPAND|wx.BOTTOM, 7)
sizer1.Add(button_sizer)
tl_sizer = wx.BoxSizer(wx.VERTICAL)
tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7)
panel.SetSizer(tl_sizer)
tl_sizer.Fit(panel)
return panel
def _create_mask_lists_pane(self):
# instantiated wxGlade frame
iff = MaskComBinarPanels.MaskListsFrame(self, id=-1,size=(600,200))
panel = iff.mask_lists_panel
# reparent the panel to us
panel.Reparent(self)
self.list_ctrl_maskA = iff.list_ctrl_maskA
self.list_ctrl_maskB = iff.list_ctrl_maskB
self.clear_selection_button = iff.button_clear_selection
self.masks_pane = panel
iff.Destroy()
return panel
def _create_mask_operations_pane(self):
# instantiated wxGlade frame
iff = MaskComBinarPanels.MaskOperationsFrame(self, id=-1,size=(600,200))
panel = iff.mask_operations_panel
# reparent the panel to us
panel.Reparent(self)
self.mask_join_button = iff.add_button
self.mask_subtract_button = iff.subtract_button
self.mask_intersect_button = iff.and_button
self.mask_align_metadata_button = iff.align_metadata_button
self.mask_align_icp_button = iff.align_icp_button
self.split_disconnected_button = iff.split_disconnected_button
self.test_selected_dimensions_button = iff.check_selected_dimensions_button
self.test_all_dimensions_button = iff.check_all_dimensions_button
self.test_selected_intersections_button = iff.check_selected_overlaps_button
self.test_all_intersections_button = iff.check_all_overlaps_button
self.operations_pane = panel
self.volume_button = iff.volume_button
self.dice_coefficient_button = iff.dice_button
self.hausdorff_distance_button = iff.hausdorff_button
self.mean_hausdorff_distance_button = iff.mean_hausdorff_button
iff.Destroy()
return panel
def render(self):
"""Update embedded RWI, i.e. update the image.
"""
self.rwi2d.Render()
self.rwi3d.Render()
def _handler_default_view(self, event):
"""Event handler for when the user selects View | Default from
the main menu.
"""
self._mgr.LoadPerspective(
self._perspectives['default'])
def _handler_max_image_view(self, event):
"""Event handler for when the user selects View | Max Image
from the main menu.
"""
self._mgr.LoadPerspective(
self._perspectives['max_image'])
def clear_selections(self):
indices = self._get_selected_indices_in_listctrl(self.list_ctrl_maskA)
for i in indices:
self.list_ctrl_maskA.Select(i, 0)
indices = self._get_selected_indices_in_listctrl(self.list_ctrl_maskB)
for i in indices:
self.list_ctrl_maskB.Select(i, 0)
def _get_selected_indices_in_listctrl(self, listctrl):
'''Returns the indices of items selected in the provided listctrl'''
indices = set()
index = -1
while True:
index = listctrl.GetNextItem(index, wx.LIST_NEXT_ALL, wx.LIST_STATE_SELECTED)
if index == -1:
break
else:
indices.add(index)
return indices
def _get_all_indices_in_listctrl(self, listctrl):
'''Returns the indices of items selected in the provided listctrl'''
indices = set()
index = -1
while True:
index = listctrl.GetNextItem(index, wx.LIST_NEXT_ALL)
if index == -1:
break
else:
indices.add(index)
return indices
def _get_selected_mask_names_in_listctrl(self, listctrl):
'''Returns the unique identifying names of masks selected in the provided listctrl'''
indices = self._get_selected_indices_in_listctrl(listctrl)
mask_names = set()
for i in indices:
mask_names.add(listctrl.GetItem(i).GetText())
return mask_names
def get_selected_mask_names_a(self):
'''Returns the unique identifying names of masks selected in mask list A'''
return self._get_selected_mask_names_in_listctrl(self.list_ctrl_maskA)
def get_selected_mask_names_b(self):
'''Returns the unique identifying names of masks selected in mask list B'''
return self._get_selected_mask_names_in_listctrl(self.list_ctrl_maskB)
def add_mask(self, mask_name):
num_items = self.list_ctrl_maskA.GetItemCount() #Should be identical for list B
num_itemsB = self.list_ctrl_maskB.GetItemCount()
if num_items != num_itemsB:
self.dialog_error("Numer of items in Lists A doesn't match list B! (%d vs %d)" % (num_items, num_itemsB), "Mask list mismatch!")
self.list_ctrl_maskA.InsertStringItem(num_items, mask_name)
self.list_ctrl_maskB.InsertStringItem(num_items, mask_name)
def delete_mask(self, mask_name):
indices = self._get_all_indices_in_listctrl(self.list_ctrl_maskA)
for index in indices:
list_name = self.list_ctrl_maskA.GetItem(index).GetText()
if list_name == mask_name:
self.list_ctrl_maskA.DeleteItem(index)
self.list_ctrl_maskB.DeleteItem(index)
break
return
def dialog_info(self, message, title):
dlg = wx.MessageDialog(self, message,title,wx.OK)
dlg.ShowModal()
def dialog_exclaim(self, message, title):
dlg = wx.MessageDialog(self, message,title,wx.OK|wx.ICON_EXCLAMATION)
dlg.ShowModal()
def dialog_error(self, message, title):
dlg = wx.MessageDialog(self, message,title,wx.OK|wx.ICON_ERROR)
dlg.ShowModal()
def dialog_yesno(self, message, title):
dlg = wx.MessageDialog(self, message,title,wx.YES_NO|wx.NO_DEFAULT)
return (dlg.ShowModal() == wx.ID_YES)
def dialog_inputtext(self, message, title, default_text):
dlg = wx.TextEntryDialog(self, message, title, default_text)
return [(dlg.ShowModal() == wx.ID_OK), dlg.GetValue()]
def copy_text_to_clipboard(self, text_message):
clipdata = wx.TextDataObject()
clipdata.SetText(text_message)
wx.TheClipboard.Open()
wx.TheClipboard.SetData(clipdata)
wx.TheClipboard.Close()
print 'Text copied to clipboard: %s' % text_message
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class histogram2D(ScriptedConfigModuleMixin, ModuleBase):
"""This module takes two inputs and creates a 2D histogram with input 2
vs input 1, i.e. input 1 on x-axis and input 2 on y-axis.
The inputs have to have identical dimensions.
"""
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._histogram = vtkdevide.vtkImageHistogram2D()
module_utils.setup_vtk_object_progress(self, self._histogram,
'Calculating 2D histogram')
self._config.input1Bins = 256
self._config.input2Bins = 256
self._config.maxSamplesPerBin = 512
configList = [
('Number of bins for input 1', 'input1Bins', 'base:int', 'text',
'The full range of input 1 values will be divided into this many '
'classes.'),
('Number of bins for input 2', 'input2Bins', 'base:int', 'text',
'The full range of input 2 values will be divided into this many '
'classes.'),
('Maximum samples per bin', 'maxSamplesPerBin', 'base:int', 'text',
'The number of samples per 2D bin/class will be truncated to '
'this value.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageHistogram2D' : self._histogram})
self.sync_module_logic_with_config()
self._input0 = None
self._input1 = None
def close(self):
self.set_input(0, None)
self.set_input(1, None)
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
del self._histogram
def get_input_descriptions(self):
return ('Image Data 1', 'Imaga Data 2')
def set_input(self, idx, inputStream):
def checkTypeAndReturnInput(inputStream):
"""Check type of input. None gets returned. The input is
returned if it has a valid type. An exception is thrown if
the input is invalid.
"""
if inputStream == None:
# disconnect
return None
else:
# first check the type
validType = False
try:
if inputStream.IsA('vtkImageData'):
validType = True
except AttributeError:
# validType is already False
pass
if not validType:
raise TypeError, 'Input has to be of type vtkImageData.'
else:
return inputStream
if idx == 0:
self._input0 = checkTypeAndReturnInput(inputStream)
self._histogram.SetInput1(self._input0)
elif idx == 1:
self._input1 = checkTypeAndReturnInput(inputStream)
self._histogram.SetInput2(self._input1)
def get_output_descriptions(self):
return (self._histogram.GetOutput().GetClassName(),)
def get_output(self, idx):
#raise NotImplementedError
return self._histogram.GetOutput()
def execute_module(self):
self._histogram.Update()
def logic_to_config(self):
self._config.input1Bins = self._histogram.GetInput1Bins()
self._config.input2Bins = self._histogram.GetInput2Bins()
self._config.maxSamplesPerBin = self._histogram.GetMaxSamplesPerBin()
def config_to_logic(self):
self._histogram.SetInput1Bins(self._config.input1Bins)
self._histogram.SetInput2Bins(self._config.input2Bins)
self._histogram.SetMaxSamplesPerBin(self._config.maxSamplesPerBin)
# ----------------------------------------------------------------------
# non-API methods start here -------------------------------------------
# ----------------------------------------------------------------------
def _histogramSourceExecute(self):
"""Execute callback for the vtkProgrammableSource histogram instance.
"""
self._histogramSource
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import csv
import geometry
import glob
import os
import math
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin,\
FileOpenDialogModuleMixin
import module_utils
import vtk
import vtkgdcm
import wx
MAJOR_MARKER_SIZE = 10
MINOR_MARKER_SIZE = 7
STATE_INIT = 0
STATE_IMAGE_LOADED = 1
STATE_APEX = 2 # clicked apex
STATE_LM = 3 # clicked lower middle
STATE_NORMAL_MARKERS = 4 # after first marker has been placed
class Measurement:
filename = ''
apex = (0,0) # in pixels
lm = (0,0)
pogo_dist = 0 # distance between apex and lm in pixels
area = 0 # current area, in floating point pixels squared
class LarynxMeasurement(IntrospectModuleMixin, FileOpenDialogModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._state = STATE_INIT
self._config.filename = None
self._current_measurement = None
# pogo line first
# outline of larynx second
self._actors = []
# list of pointwidgets, first is apex, second is lm, others
# are others. :)
self._markers = []
self._pogo_line_source = None
self._area_polydata = None
self._view_frame = None
self._viewer = None
self._reader = vtk.vtkJPEGReader()
self._create_view_frame()
self._bind_events()
self.view()
# all modules should toggle this once they have shown their
# stuff.
self.view_initialised = True
self.config_to_logic()
self.logic_to_config()
self.config_to_view()
def _bind_events(self):
self._view_frame.start_button.Bind(
wx.EVT_BUTTON, self._handler_start_button)
self._view_frame.next_button.Bind(
wx.EVT_BUTTON, self._handler_next_button)
self._view_frame.reset_button.Bind(
wx.EVT_BUTTON, self._handler_reset_button)
self._view_frame.save_csv.Bind(
wx.EVT_BUTTON, self._handler_save_csv_button)
self._view_frame.rwi.AddObserver(
'LeftButtonPressEvent',
self._handler_rwi_lbp)
def _create_view_frame(self):
import resources.python.larynx_measurement_frame
reload(resources.python.larynx_measurement_frame)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
resources.python.larynx_measurement_frame.LarynxMeasurementFrame)
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.view_frame_panel,
{'Module (self)' : self})
# now setup the VTK stuff
if self._viewer is None and not self._view_frame is None:
# vtkImageViewer() does not zoom but retains colour
# vtkImageViewer2() does zoom but discards colour at
# first window-level action.
# vtkgdcm.vtkImageColorViewer() does both right!
self._viewer = vtkgdcm.vtkImageColorViewer()
self._viewer.SetupInteractor(self._view_frame.rwi)
self._viewer.GetRenderer().SetBackground(0.3,0.3,0.3)
self._set_image_viewer_dummy_input()
pp = vtk.vtkPointPicker()
pp.SetTolerance(0.0)
self._view_frame.rwi.SetPicker(pp)
def close(self):
for i in range(len(self.get_input_descriptions())):
self.set_input(i, None)
# with this complicated de-init, we make sure that VTK is
# properly taken care of
self._viewer.GetRenderer().RemoveAllViewProps()
self._viewer.SetupInteractor(None)
self._viewer.SetRenderer(None)
# this finalize makes sure we don't get any strange X
# errors when we kill the module.
self._viewer.GetRenderWindow().Finalize()
self._viewer.SetRenderWindow(None)
del self._viewer
# done with VTK de-init
self._view_frame.Destroy()
del self._view_frame
ModuleBase.close(self)
def get_input_descriptions(self):
return ()
def get_output_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise RuntimeError
def get_output(self, idx):
raise RuntimeError
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
# there is no explicit apply step in this viewer module, so we
# keep the config up to date throughout (this is common for
# pure viewer modules)
pass
def config_to_view(self):
# this will happen right after module reload / network load
if self._config.filename is not None:
self._start(self._config.filename)
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# we need to do this to make sure that the Show() and Raise() above
# are actually performed. Not doing this is what resulted in the
# "empty renderwindow" bug after module reloading, and also in the
# fact that shortly after module creation dummy data rendered outside
# the module frame.
wx.SafeYield()
self.render()
# so if we bring up the view after having executed the network once,
# re-executing will not do a set_input()! (the scheduler doesn't
# know that the module is now dirty) Two solutions:
# * make module dirty when view is activated
# * activate view at instantiation. <--- we're doing this now.
def execute_module(self):
pass
def _add_normal_marker(self, world_pos):
if not len(self._markers) >= 2:
raise RuntimeError(
'There should be 2 or more markers by now!')
pw = self._add_marker(world_pos, (0,1,0), 0.005)
self._markers.append(pw)
self._markers[-1].AddObserver(
'InteractionEvent',
self._handler_nm_ie)
def _add_area_polygon(self):
pd = vtk.vtkPolyData()
self._area_polydata = pd
m = vtk.vtkPolyDataMapper()
m.SetInput(pd)
a = vtk.vtkActor()
a.SetMapper(m)
self._viewer.GetRenderer().AddActor(a)
self._actors.append(a)
def _add_pogo_line(self):
ls = vtk.vtkLineSource()
self._pogo_line_source = ls
m = vtk.vtkPolyDataMapper()
m.SetInput(ls.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
prop = a.GetProperty()
prop.SetLineStipplePattern(0x1010)
prop.SetLineStippleRepeatFactor(1)
self._viewer.GetRenderer().AddActor(a)
self._actors.append(a)
self._update_pogo_distance()
self.render()
def _add_sphere(self, world_pos, radius, colour):
ss = vtk.vtkSphereSource()
ss.SetRadius(radius)
m = vtk.vtkPolyDataMapper()
m.SetInput(ss.GetOutput())
a = vtk.vtkActor()
a.SetMapper(m)
a.SetPosition(world_pos)
a.GetProperty().SetColor(colour)
self._viewer.GetRenderer().AddActor(a)
self.render()
def _add_marker(self, world_pos, colour, size=0.01):
"""
@param size: fraction of visible prop bounds diagonal.
"""
#self._add_sphere(world_pos, MAJOR_MARKER_SIZE, (1,1,0))
pw = vtk.vtkPointWidget()
# we're giving it a small bounding box
pw.TranslationModeOn()
b = self._viewer.GetRenderer().ComputeVisiblePropBounds()
# calculate diagonal
dx,dy = b[1] - b[0], b[3] - b[2]
diag = math.hypot(dx,dy)
d = size * diag
w = world_pos
pwb = w[0] - d, w[0] + d, \
w[1] - d, w[1] + d, \
b[4], b[5]
pw.PlaceWidget(pwb)
pw.SetPosition(world_pos)
pw.SetInteractor(self._view_frame.rwi)
pw.AllOff()
pw.GetProperty().SetColor(colour)
pw.On()
return pw
def _add_apex_marker(self, world_pos):
# this method should only be called when the list is empty!
if self._markers:
raise RuntimeError('Marker list is not empty!')
self._markers.append(self._add_marker(world_pos, (1,1,0)))
self._markers[-1].AddObserver(
'InteractionEvent',
self._handler_alm_ie)
def _add_lm_marker(self, world_pos):
if len(self._markers) != 1:
raise RuntimeError(
'Marker list should have only one entry!')
self._markers.append(self._add_marker(world_pos, (0,1,1)))
self._markers[-1].AddObserver(
'InteractionEvent',
self._handler_alm_ie)
def _create_db(self, filename):
con = sqlite3.connect(filename)
con.execute(
"""create table images
(id integer primary key, filename varchar unique)""")
con.execute(
"""create table coords
(
""")
def _handler_alm_ie(self, pw=None, vtk_e=None):
self._update_pogo_distance()
self._update_area()
def _handler_nm_ie(self, pw=None, vtk_e=None):
self._update_area()
def _handler_rwi_lbp(self, vtk_o, vtk_e):
# we only handle this if the user is pressing shift
if not vtk_o.GetShiftKey():
return
pp = vtk_o.GetPicker() # this will be our pointpicker
x,y = vtk_o.GetEventPosition()
#iapp = vtk.vtkImageActorPointPlacer()
#ren = self._viewer.GetRenderer()
#iapp.SetImageActor(our_actor)
#iapp.ComputeWorldPosition(ren, display_pos, 3xdouble,
# 9xdouble)
if not pp.Pick(x,y,0,self._viewer.GetRenderer()):
print "off image!"
else:
print pp.GetMapperPosition()
# now also get WorldPos
ren = self._viewer.GetRenderer()
ren.SetDisplayPoint(x,y,0)
ren.DisplayToWorld()
w = ren.GetWorldPoint()[0:3]
print w
# we have a picked position and a world point, now decide
# what to do based on our current state
if self._state == STATE_IMAGE_LOADED:
# put down the apex ball
self._add_apex_marker(w)
self._state = STATE_APEX
elif self._state == STATE_APEX:
# put down the LM ball
self._add_lm_marker(w)
self._add_pogo_line()
self._state = STATE_LM
elif self._state == STATE_LM:
# now we're putting down all other markers
self._add_normal_marker(w)
# now create the polydata
self._add_area_polygon()
self._update_area()
self._state = STATE_NORMAL_MARKERS
elif self._state == STATE_NORMAL_MARKERS:
self._add_normal_marker(w)
self._update_area()
def _handler_reset_button(self, evt):
if self._current_measurement.filename:
self._start(self._current_measurement.filename,
reset=True)
def _handler_save_csv_button(self, evt):
fn = self._current_measurement.filename
if not os.path.exists(fn):
return
self._save_dacs_to_csv(fn)
def _handler_start_button(self, evt):
# let user pick image
# - close down any running analysis
# - analyze all jpg images in that dir
# - read / initialise SQL db
# first get filename from user
filename = self.filename_browse(self._view_frame,
'Select FIRST subject image to start processing',
'Subject image (*.jpg)|*.jpg;*.JPG',
style=wx.OPEN)
if filename:
self._start(filename)
def _handler_next_button(self, evt):
# write everything to to measurement files
# first the points
fn = self._current_measurement.filename
if len(self._markers) > 0:
points_name = '%s.pts' % (fn,)
f = open(points_name, 'w')
pts = [m.GetPosition()[0:3] for m in self._markers]
f.write(str(pts))
f.close()
if len(self._markers) >= 3:
# we only write the DAC if there are at least 3 markers,
# else the measurement is not valid...
# then the distance, area and cormack lehane
dac_name = '%s.dac' % (fn,)
f = open(dac_name, 'w')
clg1 = int(self._view_frame.clg1_cbox.GetValue())
d = self._current_measurement.pogo_dist
a = self._current_measurement.area
dac = [d,a,clg1]
f.write(str(dac))
f.close()
# IS there a next file?
# get ext and dir of current file
current_fn = self._current_measurement.filename
# ext is '.JPG'
ext = os.path.splitext(current_fn)[1]
dir = os.path.dirname(current_fn)
all_files = glob.glob(os.path.join(dir, '*%s' % (ext,)))
# we assume the user has this covered (filenames padded)
all_files.sort()
# find index of current file, take next image
idx = all_files.index(current_fn) + 1
if idx < len(all_files):
new_filename = all_files[idx]
else:
new_filename = all_files[0]
self._start(new_filename)
def _load_measurement(self, new_filename):
# see if there's a points file that we can use
points_name = '%s.pts' % (new_filename,)
try:
f = open(points_name)
except IOError:
pass
else:
# just evaluate what's in there, should be an array of
# three-element tuples (we're going to write away the
# world-pos coordinates)
points = eval(f.read(), {"__builtins__": {}})
f.close()
try:
self._add_apex_marker(points[0])
self._state = STATE_APEX
self._add_lm_marker(points[1])
self._add_pogo_line()
self._state = STATE_LM
self._add_normal_marker(points[2])
self._add_area_polygon()
self._update_area()
self._state = STATE_NORMAL_MARKERS
for pt in points[3:]:
self._add_normal_marker(pt)
self._update_area()
except IndexError:
pass
# now make sure everything else is updated
self._update_pogo_distance()
self._update_area()
# cormack lehane grade
dac_name = '%s.dac' % (new_filename,)
try:
f = open(dac_name)
except IOError:
pass
else:
dist, area, clg1 = eval(f.read(), {"__builtins__":{}})
f.close()
#self._current_measurement.clg1 = clg
self._view_frame.clg1_cbox.SetValue(clg1)
def render(self):
# if you call self._viewer.Render() here, you get the
# VTK-window out of main window effect at startup. So don't.
self._view_frame.rwi.Render()
def _reset_image_pz(self):
"""Reset the pan/zoom of the current image.
"""
ren = self._viewer.GetRenderer()
ren.ResetCamera()
def _save_dacs_to_csv(self, current_fn):
# make list of all filenames in current directory
# load all dacs
img_ext = os.path.splitext(current_fn)[1]
dir = os.path.dirname(current_fn)
all_images = glob.glob(os.path.join(dir, '*%s' % (img_ext,)))
all_dacs = glob.glob(os.path.join(dir, '*%s.dac' % (img_ext,)))
if len(all_dacs) == 0:
self._module_manager.log_error(
"No measurements to save yet.")
return
if len(all_dacs) % 3 != 0:
self._module_manager.log_error(
"Number of measurements not a multiple of 3!\n"
"Can't write CSV file.")
return
if len(all_dacs) != len(all_images):
self._module_manager.log_warning(
"You have not yet measured all images yet.\n"
"Will write CSV anyway, please double-check.")
# sort the dacs
all_dacs.sort()
csv_fn = os.path.join(dir, 'measurements.csv')
csv_f = open(csv_fn, 'w')
wrtr = csv.writer(csv_f, delimiter=',',
quotechar='"')
# write header row
wrtr.writerow([
'name', 'clg1 a', 'clg1 b', 'clg1 c',
'norm dist a', 'norm dist b', 'norm dist c',
'dist a', 'dist b', 'dist c',
'norm area a', 'norm area b', 'norm area c',
'area a', 'area b', 'area c'
])
# now go through all the dac files and write them out in
# multiples of three
for i in range(len(all_dacs) / 3):
three_names = []
clg = []
norm_dist = []
dist = []
norm_area = []
area = []
for j in range(3):
# get dac filename and read its contents
dfn = all_dacs[i*3 + j]
d,a,c = eval(open(dfn).read(),
{"__builtins__":{}})
# create short (extensionless) filename for creating
# the measurement title
sfn = os.path.splitext(os.path.basename(dfn))[0]
# we have to strip off the jpg as well
sfn = os.path.splitext(sfn)[0]
# store it for creating the string later
three_names.append(sfn)
if j == 0:
# if this is the first of a three-element group,
# store the distance and area to normalise the
# other two with.
nd = d
na = a
norm_dist.append(1.0)
norm_area.append(1.0)
else:
# if not, normalise and store
norm_dist.append(d / nd)
norm_area.append(a / na)
# store the pixel measurements
clg.append(c)
dist.append(d)
area.append(a)
# write out a measurement line to the CSV file
name3 = '%s-%s-%s' % tuple(three_names)
wrtr.writerow([name3] + clg +
norm_dist + dist +
norm_area + area)
csv_f.close()
def _stop(self):
# close down any running analysis
# first remove all polydatas we might have added to the scene
for a in self._actors:
self._viewer.GetRenderer().RemoveViewProp(a)
for m in self._markers:
m.Off()
m.SetInteractor(None)
del self._markers[:]
# setup dummy image input.
self._set_image_viewer_dummy_input()
# set state to initialised
self._state = STATE_INIT
def _start(self, new_filename, reset=False):
# first see if we can open the new file
new_reader = self._open_image_file(new_filename)
# if so, stop previous session
self._stop()
# replace reader and show the image
self._reader = new_reader
self._viewer.SetInput(self._reader.GetOutput())
# show the new filename in the correct image box
# first shorten it slightly: split it at the path separator,
# take the last two components (last dir comp, filename), then
# prepend a '...' and join them all together again. example
# output: .../tmp/file.jpg
short_p = os.path.sep.join(
['...']+new_filename.split(os.path.sep)[-2:])
self._view_frame.current_image_txt.SetValue(short_p)
self._config.filename = new_filename
cm = Measurement()
cm.filename = self._config.filename
self._current_measurement = cm
self._actors = []
self._reset_image_pz()
self.render()
self._state = STATE_IMAGE_LOADED
# this means that the user doesn't want the stored data, for
# example when resetting the image measurement
if not reset:
self._load_measurement(new_filename)
self.render()
# now determine our current progress by tallying up DAC files
ext = os.path.splitext(new_filename)[1]
dir = os.path.dirname(new_filename)
all_images = glob.glob(os.path.join(dir, '*%s' % (ext,)))
all_dacs = glob.glob(os.path.join(dir, '*%s.dac' % (ext,)))
progress_msg = "%d / %d images complete" % \
(len(all_dacs), len(all_images))
self._view_frame.progress_txt.SetValue(progress_msg)
def _set_image_viewer_dummy_input(self):
ds = vtk.vtkImageGridSource()
self._viewer.SetInput(ds.GetOutput())
def _open_image_file(self, filename):
# create a new instance of the current reader
# to read the passed file.
nr = self._reader.NewInstance()
nr.SetFileName(filename)
# FIXME: trap this error
nr.Update()
return nr
def _update_pogo_distance(self):
"""Based on the first two markers, update the pogo line and
recalculate the distance.
"""
if len(self._markers) >= 2:
p1,p2 = [self._markers[i].GetPosition() for i in range(2)]
self._pogo_line_source.SetPoint1(p1)
self._pogo_line_source.SetPoint2(p2)
pogo_dist = math.hypot(p2[0] - p1[0], p2[1] - p1[1])
# store pogo_dist in Measurement
self._current_measurement.pogo_dist = pogo_dist
self._view_frame.pogo_dist_txt.SetValue('%.2f' %
(pogo_dist,))
def _update_area(self):
"""Based on three or more markers in total, draw a nice
polygon and update the total area.
"""
if len(self._markers) >= 3:
# start from apex, then all markers to the right of the
# pogo line, then the lm point, then all markers to the
# left.
p1,p2 = [self._markers[i].GetPosition()[0:2] for i in range(2)]
z = self._markers[0].GetPosition()[2]
n,mag,lv = geometry.normalise_line(p1,p2)
# get its orthogonal vector
no = - n[1],n[0]
pts = [self._markers[i].GetPosition()[0:2]
for i in range(2, len(self._markers))]
right_pts = []
left_pts = []
for p in pts:
v = geometry.points_to_vector(p1,p)
# project v onto n
v_on_n = geometry.dot(v,n) * n
# then use that to determine the vector orthogonal on
# n from p
v_ortho_n = v - v_on_n
# rl is positive for right hemisphere, negative for
# otherwise
rl = geometry.dot(no, v_ortho_n)
if rl >= 0:
right_pts.append(p)
elif rl < 0:
left_pts.append(p)
vpts = vtk.vtkPoints()
vpts.InsertPoint(0,p1[0],p1[1],z)
for i,j in enumerate(right_pts):
vpts.InsertPoint(i+1,j[0],j[1],z)
if len(right_pts) == 0:
i = -1
vpts.InsertPoint(i+2,p2[0],p2[1],z)
for k,j in enumerate(left_pts):
vpts.InsertPoint(i+3+k,j[0],j[1],z)
num_points = 2 + len(left_pts) + len(right_pts)
assert(vpts.GetNumberOfPoints() == num_points)
self._area_polydata.SetPoints(vpts)
cells = vtk.vtkCellArray()
# we repeat the first point
cells.InsertNextCell(num_points + 1)
for i in range(num_points):
cells.InsertCellPoint(i)
cells.InsertCellPoint(0)
self._area_polydata.SetLines(cells)
# now calculate the polygon area according to:
# http://local.wasp.uwa.edu.au/~pbourke/geometry/polyarea/
all_pts = [p1] + right_pts + [p2] + left_pts + [p1]
tot = 0
for i in range(len(all_pts)-1):
pi = all_pts[i]
pip = all_pts[i+1]
tot += pi[0]*pip[1] - pip[0]*pi[1]
area = - tot / 2.0
# store area in current measurement
self._current_measurement.area = area
self._view_frame.area_txt.SetValue('%.2f' % (area,))
| Python |
from wxPython._controls import wxLIST_MASK_STATE
from wxPython._controls import wxLIST_STATE_SELECTED
import os.path
# Modified by Francois Malan, LUMC / TU Delft
# December 2009
#
# based on the SkeletonAUIViewer:
# skeleton of an AUI-based viewer module
# Copyright (c) Charl P. Botha, TU Delft.
# set to False for 3D viewer, True for 2D image viewer
IMAGE_VIEWER = False
# import the frame, i.e. the wx window containing everything
import MaskComBinarFrame
# and do a reload, so that the GUI is also updated at reloads of this
# module.
reload(MaskComBinarFrame)
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import os
import vtk
import itk
import wx
import copy
import subprocess
#import numpy as np
from OverlaySliceViewer import OverlaySliceViewer
class Mask(object):
def __init__(self, name, file_path, image_data):
self.name = name
self.file_path = file_path
self.data = image_data
# def deepcopy(self):
# return Mask(self.name, self.file_path, self.data.DeepCopy())
class MaskComBinar(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Standard constructor. All DeVIDE modules have these, we do
the required setup actions.
"""
# we record the setting here, in case the user changes it
# during the lifetime of this model, leading to different
# states at init and shutdown.
self.IMAGE_VIEWER = IMAGE_VIEWER
ModuleBase.__init__(self, module_manager)
# create the view frame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
MaskComBinarFrame.MaskComBinarFrame)
# change the title to something more spectacular
self._view_frame.SetTitle('MaskComBinar - a tool for measuring and manipulating binary masks')
#initialise data structures
self._init_data_structures()
self._init_2d_render_window()
self._init_3d_render_window()
self.reset_camera_on_mask_display = True
self.first_save_warning = True
# hook up all event handlers
self._bind_events()
# anything you stuff into self._config will be saved
self._config.last_used_dir = ''
# make our window appear (this is a viewer after all)
self.view()
# all modules should toggle this once they have shown their
# views.
self.view_initialised = True
# apply config information to underlying logic
self.sync_module_logic_with_config()
# then bring it all the way up again to the view
self.sync_module_view_with_logic()
#This tool can be used for introspection of wx components
#
def _init_2d_render_window(self):
#create the necessary VTK objects for the 2D window. We use Charl's CMSliceViewer
#which defines all the nice goodies we'll need
self.ren2d = vtk.vtkRenderer()
self.ren2d.SetBackground(0.4,0.4,0.4)
self.slice_viewer = OverlaySliceViewer(self._view_frame.rwi2d, self.ren2d)
self._view_frame.rwi2d.GetRenderWindow().AddRenderer(self.ren2d)
self.slice_viewer.add_overlay('a', [0, 0, 1, 1]) #Blue for selection A
self.slice_viewer.add_overlay('b', [1, 0, 0, 1]) #Red for selection B
self.slice_viewer.add_overlay('intersect', [1, 1, 0, 1]) #Yellow for for intersection
def _init_3d_render_window(self):
# create the necessary VTK objects for the 3D window: we only need a renderer,
# the RenderWindowInteractor in the view_frame has the rest.
self.ren3d = vtk.vtkRenderer()
self.ren3d.SetBackground(0.6,0.6,0.6)
self._view_frame.rwi3d.GetRenderWindow().AddRenderer(self.ren3d)
def _init_data_structures(self):
self.opacity_3d = 0.5
self.rgb_blue = [0,0,1]
self.rgb_red = [1,0,0]
self.rgb_yellow = [1,1,0]
self.masks = {}
self.surfaces = {} #This prevents recomputing surface meshes
self.actors3d = {}
self.rendered_masks_in_a = set()
self.rendered_masks_in_b = set()
self.rendered_overlap = False
def _load_mask_from_file(self, file_path):
print "Opening file: %s" % (file_path)
filename = os.path.split(file_path)[1]
reader = None
extension = os.path.splitext(filename)[1]
if extension == '.vti': # VTI
reader = vtk.vtkXMLImageDataReader()
elif extension == '.mha': # MHA
reader = vtk.vtkMetaImageReader()
else:
self._view_frame.dialog_error('Unknown file extension: %s' % extension, 'Unable to handle extension')
return
reader.SetFileName(file_path)
reader.Update()
result = vtk.vtkImageData()
result.DeepCopy(reader.GetOutput())
return result
def load_binary_mask_from_file(self, file_path):
mask_image_data = self._load_mask_from_file(file_path)
filename = os.path.split(file_path)[1]
fileBaseName =os.path.splitext(filename)[0]
mask = Mask(fileBaseName, file_path, mask_image_data)
self.add_mask(mask)
def load_multi_mask_from_file(self, file_path):
mask_image_data = self._load_mask_from_file(file_path)
filename = os.path.split(file_path)[1]
fileBaseName =os.path.splitext(filename)[0]
#Now we have to create a separate mask for each integer level.
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(mask_image_data)
accumulator.Update()
max_label = int(accumulator.GetMax()[0])
#We assume all labels to have positive values.
for i in range(1,max_label+1):
label_data = self._threshold_image(mask_image_data, i, i)
new_name = '%s_%d' % (fileBaseName, i)
mask = Mask(new_name, file_path, label_data)
self.add_mask(mask)
def save_mask_to_file(self, mask_name, file_path):
if os.path.exists(file_path):
result = self._view_frame.dialog_yesno("%s already exists! \nOverwrite?" % file_path,"File already exists")
if result == False:
print 'Skipped writing %s' % file_path
return #skip this file if overwrite is denied
mask = self.masks[mask_name]
mask.file_path = file_path
self._save_image_to_file(mask.data, file_path)
print 'Wrote mask %s to %s' % (mask_name, file_path)
def _save_image_to_file(self, imagedata, file_path):
filename = os.path.split(file_path)[1]
extension = os.path.splitext(filename)[1]
writer = None
if extension == '.vti': # VTI
writer = vtk.vtkXMLImageDataWriter()
elif extension == '.mha': # MHA
print 'Attempting to create an mha writer. This has failed in the past (?)'
writer = vtk.vtkMetaImageWriter()
writer.SetCompression(True)
else:
self._view_frame.dialog_error('Unknown file extension: %s' % extension, 'Unable to handle extension')
return
writer.SetInput(imagedata)
writer.SetFileName(file_path)
writer.Update()
result = writer.Write()
if result == 0:
self._view_frame.dialog_error('Error writing %s' % filename, 'Error writing file')
print 'ERROR WRITING FILE!!!'
else:
self._view_frame.dialog_info('Successfully wrote %s' % filename, 'Success')
print 'Successfully wrote %s' % file_path
def add_mask(self, mask):
[accept, name] = self._view_frame.dialog_inputtext('Please choose a name for the new mask','Choose a name', mask.name)
if accept:
mask.name = name
if self.masks.has_key(name):
i=1
new_name = '%s%d' % (name, i)
while self.masks.has_key(new_name):
i += 1
new_name = '%s%d' % (mask.name, i)
mask.name = new_name
self.masks[mask.name] = mask
self._view_frame.add_mask(mask.name)
def delete_masks(self, mask_names):
temp = mask_names.copy()
if len(mask_names) > 0:
mask_names_str = mask_names.pop()
while len(mask_names) > 0:
mask_names_str = mask_names_str + ',%s' % mask_names.pop()
mask_names = temp
if self._view_frame.dialog_yesno('Are you sure you want to delete the following masks: %s' % mask_names_str, 'Delete masks?'):
for mask_name in mask_names:
print 'deleting mask: %s' % mask_name
if self.masks.has_key(mask_name):
self.masks.pop(mask_name)
self._view_frame.delete_mask(mask_name)
else:
self._view_frame.dialog_error('Mask "%s" not found in internal mask list!' % mask_name, 'Mask not found')
if len(self.masks) == 0: #If there are no masks left we disable the 2D viewer's pickable plane
self.slice_viewer.set_input(0, None)
def close(self):
"""Clean-up method called on all DeVIDE modules when they are
deleted.
"""
# with this complicated de-init, we make sure that VTK is
# properly taken care of
self.ren2d.RemoveAllViewProps()
self.ren3d.RemoveAllViewProps()
# this finalize makes sure we don't get any strange X
# errors when we kill the module.
self._view_frame.rwi2d.GetRenderWindow().Finalize()
self._view_frame.rwi2d.SetRenderWindow(None)
del self._view_frame.rwi2d
self._view_frame.rwi3d.GetRenderWindow().Finalize()
self._view_frame.rwi3d.SetRenderWindow(None)
del self._view_frame.rwi3d
# done with VTK de-init
# now take care of the wx window
self._view_frame.close()
# then shutdown our introspection mixin
IntrospectModuleMixin.close(self)
def get_input_descriptions(self):
# define this as a tuple of input descriptions if you want to
# take input data e.g. return ('vtkPolyData', 'my kind of
# data')
return ()
def get_output_descriptions(self):
# define this as a tuple of output descriptions if you want to
# generate output data.
return ()
def set_input(self, idx, input_stream):
# this gets called right before you get executed. take the
# input_stream and store it so that it's available during
# execute_module()
pass
def get_output(self, idx):
# this can get called at any time when a consumer module wants
# your output data.
pass
def execute_module(self):
# when it's your turn to execute as part of a network
# execution, this gets called.
pass
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def config_to_view(self):
pass
def view_to_config(self):
pass
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
# because we have an RWI involved, we have to do this
# SafeYield, so that the window does actually appear before we
# call the render. If we don't do this, we get an initial
# empty renderwindow.
wx.SafeYield()
self.render()
def _update_3d_masks(self, id, removed, added):
rgb_colour = [0,0,0]
if id == 'a':
rgb_colour = self.rgb_blue
elif id == 'b':
rgb_colour = self.rgb_red
for name in removed:
key = id + name
self.ren3d.RemoveActor(self.actors3d[key])
self.render()
for name in added:
self._render_3d_mask(id, name, rgb_colour, self.opacity_3d)
def _update_3d_masks_overlapping(self, mask_a, mask_b, mask_intersect):
self._clear_3d_window()
self._render_3d_data('a_not_b', mask_a.data, self.rgb_blue, self.opacity_3d)
self._render_3d_data('b_not_a', mask_b.data, self.rgb_red, self.opacity_3d)
self._render_3d_data('a_and_b', mask_intersect.data, self.rgb_yellow, self.opacity_3d)
def _clear_3d_window(self):
for actor in self.actors3d.values():
self.ren3d.RemoveActor(actor)
self.ren3d.Clear()
self.rendered_masks_in_a = set()
self.rendered_masks_in_b = set()
self.rendered_overlap = False
def _render_2d_mask(self, id, mask):
mask_data = None
if mask != None:
mask_data = mask.data
self.slice_viewer.set_input(id, mask_data)
if self.reset_camera_on_mask_display:
self.slice_viewer.reset_camera()
#self.slice_viewer.reset_to_default_view(2)
self.slice_viewer.render()
def _render_3d_mask(self, id, name, rgb_colour, opacity):
"""Add the given mask to the 3D display window.
An iso-surface of colour rgb_colour is rendered at value = 1.
"""
surface = None
mask = self.masks[name]
if not self.surfaces.has_key(name):
surface_creator = vtk.vtkDiscreteMarchingCubes()
surface_creator.SetInput(mask.data)
surface_creator.Update()
surface = surface_creator.GetOutput()
self.surfaces[name] = surface
else:
surface = self.surfaces[name]
m = vtk.vtkPolyDataMapper()
m.SetInput(surface)
m.ScalarVisibilityOff()
actor = vtk.vtkActor()
actor.SetMapper(m)
actor.SetPosition(mask.data.GetOrigin())
actor.GetProperty().SetColor(rgb_colour)
actor.GetProperty().SetOpacity(opacity)
#actor.GetProperty().SetInterpolationToFlat()
self.ren3d.AddActor(actor)
self.actors3d[id+name] = actor
if self.reset_camera_on_mask_display:
self.ren3d.ResetCamera()
self.render()
def _render_3d_data(self, id, data, rgb_colour, opacity):
"""Add the given mask to the 3D display window.
An iso-surface of colour rgb_colour is rendered at value = 1.
"""
surface_creator = vtk.vtkDiscreteMarchingCubes()
surface_creator.SetInput(data)
surface_creator.Update()
surface = surface_creator.GetOutput()
m = vtk.vtkPolyDataMapper()
m.SetInput(surface)
m.ScalarVisibilityOff()
actor = vtk.vtkActor()
actor.SetMapper(m)
actor.SetPosition(data.GetOrigin())
actor.GetProperty().SetColor(rgb_colour)
actor.GetProperty().SetOpacity(opacity)
#actor.GetProperty().SetInterpolationToFlat()
self.ren3d.AddActor(actor)
self.actors3d[id] = actor
if self.reset_camera_on_mask_display:
self.ren3d.ResetCamera()
self.render()
def _bind_events(self):
"""Bind wx events to Python callable object event handlers.
"""
vf = self._view_frame
vf.Bind(wx.EVT_MENU, self._handler_open_binary_mask,
id = vf.id_open_binary_mask)
vf.Bind(wx.EVT_MENU, self._handler_open_multi_mask,
id = vf.id_open_multi_mask)
vf.Bind(wx.EVT_MENU, self._handler_save_multi_mask,
id = vf.id_save_multi_mask)
vf.Bind(wx.EVT_MENU, self._handler_open_mask_dir,
id = vf.id_open_mask_dir)
vf.Bind(wx.EVT_MENU, self._handler_save_mask,
id = vf.id_save_mask)
vf.Bind(wx.EVT_MENU, self._handler_close,
id = vf.id_quit)
vf.Bind(wx.EVT_MENU, self._handler_introspect,
id = vf.id_introspect)
vf.Bind(wx.EVT_MENU, self._handler_about,
id = vf.id_about)
self._view_frame.reset_cam2d_button.Bind(wx.EVT_BUTTON,
self._handler_reset_cam2d_button)
self._view_frame.reset_cam3d_button.Bind(wx.EVT_BUTTON,
self._handler_reset_cam3d_button)
self._view_frame.clear_selection_button.Bind(wx.EVT_BUTTON,
self._handler_clear_selection_button)
self._view_frame.list_ctrl_maskA.Bind(wx.EVT_LIST_ITEM_SELECTED, self._handler_listctrl)
self._view_frame.list_ctrl_maskA.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._handler_listctrl)
self._view_frame.list_ctrl_maskB.Bind(wx.EVT_LIST_ITEM_SELECTED, self._handler_listctrl)
self._view_frame.list_ctrl_maskB.Bind(wx.EVT_LIST_ITEM_DESELECTED, self._handler_listctrl)
self._view_frame.list_ctrl_maskA.Bind(wx.EVT_LIST_KEY_DOWN, self._handler_delete_mask_a)
self._view_frame.list_ctrl_maskB.Bind(wx.EVT_LIST_KEY_DOWN, self._handler_delete_mask_b)
#Mask operations
self._view_frame.mask_join_button.Bind(wx.EVT_BUTTON, self._handler_mask_join)
self._view_frame.mask_subtract_button.Bind(wx.EVT_BUTTON, self._handler_mask_subtract)
self._view_frame.mask_intersect_button.Bind(wx.EVT_BUTTON, self._handler_mask_intersect)
self._view_frame.mask_align_metadata_button.Bind(wx.EVT_BUTTON, self._handler_align_masks_metadata)
self._view_frame.mask_align_icp_button.Bind(wx.EVT_BUTTON, self._handler_align_masks_icp)
self._view_frame.split_disconnected_button.Bind(wx.EVT_BUTTON, self._handler_split_disconnected)
#Mask diagnostics
self._view_frame.test_all_dimensions_button.Bind(wx.EVT_BUTTON, self._handler_test_all_dimensions)
self._view_frame.test_selected_dimensions_button.Bind(wx.EVT_BUTTON, self._handler_test_selected_dimensions)
self._view_frame.test_all_intersections_button.Bind(wx.EVT_BUTTON, self._handler_test_all_intersections)
self._view_frame.test_selected_intersections_button.Bind(wx.EVT_BUTTON, self._handler_test_selected_intersections)
#Mask metrics
self._view_frame.volume_button.Bind(wx.EVT_BUTTON, self._handler_compute_volume)
self._view_frame.dice_coefficient_button.Bind(wx.EVT_BUTTON, self._handler_compute_dice_coefficient)
self._view_frame.hausdorff_distance_button.Bind(wx.EVT_BUTTON, self._handler_compute_hausdorff_distance)
self._view_frame.mean_hausdorff_distance_button.Bind(wx.EVT_BUTTON, self._handler_compute_mean_hausdorff_distance)
#self._view_frame.Bind(wx.EVT_SLIDER, self._handler_slider_update)
def _handler_reset_cam2d_button(self, event):
#self.slice_viewer.reset_camera()
self.slice_viewer.reset_to_default_view(2)
self.render()
def _handler_reset_cam3d_button(self, event):
self.ren3d.ResetCamera()
self.render()
def _handler_clear_selection_button(self, event):
self._view_frame.clear_selections()
self._clear_3d_window()
self.slice_viewer.set_input(0, None)
self.slice_viewer.set_input('a', None)
self.slice_viewer.set_input('b', None)
self.slice_viewer.set_input('intersect', None)
self.render()
def _handler_delete_mask_a(self, event):
'''Handler for deleting an mask from either of the two lists (acts on both)'''
if event.KeyCode == 127: #This is the keycode for "delete"
names_a = self._view_frame.get_selected_mask_names_a()
if len(names_a) > 0:
self.delete_masks(names_a)
def _handler_delete_mask_b(self, event):
'''Handler for deleting an mask from either of the two lists (acts on both)'''
if event.KeyCode == 127: #This is the keycode for "delete"
names_b = self._view_frame.get_selected_mask_names_b()
if len(names_b) > 0:
self.delete_masks(names_b)
def _handler_listctrl(self, event):
"""Mask is selected or deselected in listcontrol A"""
if self.rendered_overlap:
self._clear_3d_window()
self.rendered_overlap = False
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
new_in_a = set()
new_in_b = set()
gone_from_a = set()
gone_from_b = set()
#Check what has changed
for name in names_a:
if not name in self.rendered_masks_in_a:
new_in_a.add(name)
for name in self.rendered_masks_in_a:
if not name in names_a:
gone_from_a.add(name)
#Update the list of selected items
self.rendered_masks_in_a = names_a
for name in names_b:
if not name in self.rendered_masks_in_b:
new_in_b.add(name)
for name in self.rendered_masks_in_b:
if not name in names_b:
gone_from_b.add(name)
#Update the list of selected items
self.rendered_masks_in_b = names_b
overlap = None
union_masks_a = None
union_masks_b = None
if (len(gone_from_a) > 0) or (len(new_in_a) > 0) or (len(gone_from_b) > 0) or (len(new_in_b) > 0):
union_masks_a = self.compute_mask_union(names_a)
union_masks_b = self.compute_mask_union(names_b)
self._render_2d_mask('a',union_masks_a)
self._render_2d_mask('b',union_masks_b)
overlap = self._logical_intersect_masks(union_masks_a, union_masks_b)
if self._is_empty_mask(overlap):
overlap = None
self._render_2d_mask('intersect',overlap)
if overlap == None:
#We don't need to render any custom mask - only a list of existing selected masks
self._update_3d_masks('a', gone_from_a, new_in_a)
self._update_3d_masks('b', gone_from_b, new_in_b)
else:
#We require a more expensive custom render to show overlapping areas in 3D
a_not_b = self._logical_subtract_masks(union_masks_a, overlap)
b_not_a = self._logical_subtract_masks(union_masks_b, overlap)
self._update_3d_masks_overlapping(a_not_b, b_not_a, overlap)
self.rendered_masks_in_a = {}
self.rendered_masks_in_b = {}
self.rendered_overlap = True
def _handler_open_binary_mask(self, event):
"""Opens a binary mask file"""
filters = 'Mask files (*.vti;*.mha)|*.vti;*.mha'
dlg = wx.FileDialog(self._view_frame, "Choose a binary mask file", self._config.last_used_dir, "", filters, wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
filename=dlg.GetFilename()
self._config.last_used_dir=dlg.GetDirectory()
full_file_path = "%s\\%s" % (self._config.last_used_dir, filename)
self.load_binary_mask_from_file(full_file_path)
dlg.Destroy()
def _handler_open_multi_mask(self, event):
"""Opens an integer-labeled multi-material mask file"""
filters = 'Mask files (*.vti;*.mha)|*.vti;*.mha'
dlg = wx.FileDialog(self._view_frame, "Choose a multi-label mask file", self._config.last_used_dir, "", filters, wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
filename=dlg.GetFilename()
self._config.last_used_dir=dlg.GetDirectory()
full_file_path = "%s\\%s" % (self._config.last_used_dir, filename)
self.load_multi_mask_from_file(full_file_path)
dlg.Destroy()
def _handler_open_mask_dir(self, event):
"""Opens all masks in a given directory"""
dlg = wx.DirDialog(self._view_frame, "Choose a directory containing masks", self._config.last_used_dir)
if dlg.ShowModal() == wx.ID_OK:
dir_name=dlg.GetPath()
self._config.last_used_dir=dir_name
all_files = os.listdir(dir_name)
#First we set up actor list of files with the correct extension
file_list = []
source_ext = '.vti'
for f in all_files:
file_name = os.path.splitext(f)
if file_name[1] == source_ext:
file_list.append(f)
for filename in file_list:
full_file_path = "%s\\%s" % (dir_name, filename)
self.load_binary_mask_from_file(full_file_path)
dlg.Destroy()
print 'Done!'
def _specify_output_file_path(self):
file_path = None
filters = 'Mask files (*.vti;*.mha)|*.vti;*.mha'
dlg = wx.FileDialog(self._view_frame, "Choose a destination", self._config.last_used_dir, "", filters, wx.SAVE)
if dlg.ShowModal() == wx.ID_OK:
filename=dlg.GetFilename()
self._config.last_used_dir=dlg.GetDirectory()
file_path = "%s\\%s" % (self._config.last_used_dir, filename)
dlg.Destroy()
return file_path
def _handler_save_multi_mask(self, event):
"""Saves a multi-label mask file"""
if self.test_valid_mask_selection_multiple():
file_path = self._specify_output_file_path()
if file_path != None:
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
names = set()
for mask_name in names_a:
names.add(mask_name)
for mask_name in names_b:
names.add(mask_name)
mask_name = names.pop()
imagedata = vtk.vtkImageData()
maskdata = self.masks[mask_name].data
imagedata.DeepCopy(maskdata)
k = 1
for mask_name in names:
k = k+1
maskdata = self.masks[mask_name].data
imath = vtk.vtkImageMathematics()
imath.SetOperationToMultiplyByK()
imath.SetConstantK(k)
print 'Multiplying %s with %d and adding to volume' % (mask_name, k)
imath.SetInput(maskdata)
imath.Update()
adder = vtk.vtkImageMathematics()
adder.SetOperationToAdd()
adder.SetInput1(imagedata)
adder.SetInput2(imath.GetOutput())
adder.Update()
imagedata.DeepCopy(adder.GetOutput())
self._save_image_to_file(imagedata, file_path)
print 'Wrote multi-label mask with %d labels to %s' % (k, file_path)
def _handler_save_mask(self, event):
"""Saves a mask file"""
if self.test_single_mask_selection():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
mask_name = ''
if len(names_b) == 1:
mask_name = names_b.pop()
else:
mask_name = names_a.pop()
file_path = self._specify_output_file_path()
if mask_name != None:
self.save_mask_to_file(mask_name, file_path)
else:
self._view_frame.dialog_exclaim("No valid file name specified")
def _handler_align_masks_metadata(self, event):
"""Aligns two masks by copying metadata from the first to the second (origin, spacing, extent, wholeextent)
As always, creates a new mask in the list of masks as output.
"""
if self.test_single_mask_pair_selection():
#We know that there is only a single mask selected in each of A and B, therefor we only index the 0th element in each
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
maskA = self.masks[names_a.pop()]
maskB = self.masks[names_b.pop()]
mask_data = vtk.vtkImageData()
mask_data.DeepCopy(maskB.data)
mask_data.SetOrigin(maskA.data.GetOrigin())
mask_data.SetExtent(maskA.data.GetExtent())
mask_data.SetWholeExtent(maskA.data.GetWholeExtent())
mask_data.SetSpacing(maskA.data.GetSpacing())
mask = Mask('%s_a' % maskB.name, maskB.file_path, mask_data)
self.add_mask(mask)
def _handler_split_disconnected(self, event):
"""Splits the selected mask into disconnected regions"""
if self.test_single_mask_selection():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
mask_name = ''
if len(names_b) == 1:
mask_name = names_b.pop()
else:
mask_name = names_a.pop()
self._split_disconnected_objects(mask_name)
def _handler_align_masks_icp(self, event):
"""Aligns two masks by using the Iterative Closest Point algorithm (rigid transformation)
As always, creates a new mask in the list of masks as output.
"""
if self.test_single_mask_pair_selection():
#We know that there is only a single mask selected in each of A and B, therefor we only index the 0th element in each
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
maskA = self.masks[names_a.pop()]
maskB = self.masks[names_b.pop()]
#We need meshes (polydata) as input to the ICP algorithm
meshA = None
meshB = None
#actually this should never happen, but let's keep it for making double sure
if not self.surfaces.has_key(maskA.name):
surface_creator_A = vtk.vtkDiscreteMarchingCubes()
surface_creator_A.SetInput(maskA.data)
surface_creator_A.Update()
meshA = surface_creator_A.GetOutput()
else:
meshA = self.surfaces[maskA.name]
#actually this should never happen, but let's keep it for making double sure
if not self.surfaces.has_key(maskB.name):
surface_creator_B = vtk.vtkDiscreteMarchingCubes()
surface_creator_B.SetInput(maskB.data)
surface_creator_B.Update()
meshB = surface_creator_B.GetOutput()
else:
meshB = self.surfaces[maskB.name]
icp = vtk.vtkIterativeClosestPointTransform()
icp.SetMaximumNumberOfIterations(50)
icp.SetSource(meshA)
icp.SetTarget(meshB)
print 'Executing ICP alorithm'
icp.Update()
del meshA, meshB
reslicer = vtk.vtkImageReslice()
reslicer.SetInterpolationModeToNearestNeighbor()
#reslicer.SetInterpolationModeToCubic()
reslicer.SetInput(maskB.data)
reslicer.SetResliceTransform(icp)
reslicer.Update()
del maskA, maskB
result = vtk.vtkImageData()
result.DeepCopy(reslicer.GetOutput())
self.add_mask(Mask('Aligned','',result))
def _handler_compute_volume(self, event):
"""Computes the volume of of mask A (in milliliters)"""
if self.test_valid_mask_selection_a():
names_a = self._view_frame.get_selected_mask_names_a()
union_masksA = self.compute_mask_union(names_a)
spacing = union_masksA.data.GetSpacing()
voxel_volume = spacing[0] * spacing[1] * spacing[2]
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(union_masksA.data)
accumulator.Update()
nonzero_count = accumulator.GetMean()[0] * accumulator.GetVoxelCount()
volume = voxel_volume * nonzero_count / 1000.0
print "Volume = %.2f ml" % (volume)
copy_to_clipboard = self._view_frame.dialog_yesno('Volume = %f ml\n\nCopy to clipboard?' % volume, 'Volume = %.1f%% ml' % (volume))
if copy_to_clipboard:
self._view_frame.copy_text_to_clipboard('%f' % volume)
def _is_empty_mask(self, mask):
if mask == None:
return True
else:
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(mask.data)
accumulator.Update()
return accumulator.GetMax()[0] == 0
def _handler_compute_dice_coefficient(self, event):
"""Computes the Dice coefficient between selections in A and B
Implementation from Charl's coderunner code"""
if self.test_valid_mask_selection_a_and_b():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
union_masksA = self.compute_mask_union(names_a)
union_masksB = self.compute_mask_union(names_b)
# Given two binary volumes, this CodeRunner will implement
# the percentage volume overlap. This is useful for
# doing validation with ground truth / golden standard /
# manually segmented volumes. This is also called the Dice
# coefficient and ranges from 0.0 to 1.0.
# interesting paper w.r.t. segmentation validation:
# Valmet: A new validation tool for assessing and improving 3D object segmentation
# basic idea:
# threshold data (so we have >0 == 1 and everything else 0)
# then histogram into two bins.
threshes = []
for _ in range(2):
t = vtk.vtkImageThreshold()
threshes.append(t)
# anything equal to or lower than 0.0 will be "In"
t.ThresholdByLower(0.0)
# <= 0 -> 0
t.SetInValue(0)
# > 0 -> 1
t.SetOutValue(1)
t.SetOutputScalarTypeToUnsignedChar()
# have to stuff all components into one image
iac = vtk.vtkImageAppendComponents()
iac.SetInput(0, threshes[0].GetOutput())
iac.SetInput(1, threshes[1].GetOutput())
# generate 2 by 2 matrix (histogram)
ia = vtk.vtkImageAccumulate()
ia.SetInput(iac.GetOutput())
ia.SetComponentExtent(0,1, 0,1, 0,0)
threshes[0].SetInput(union_masksA.data)
threshes[1].SetInput(union_masksB.data)
ia.Update()
iasc = ia.GetOutput().GetPointData().GetScalars()
cells = [0] * 4
for i in range(4):
cells[i] = iasc.GetTuple1(i)
# tuple 0: not in actor, not in b
# tuple 1: in actor, not in b
# tuple 2: in b, not in actor
# tuple 3: in actor, in b
# percentage overlap: (a intersect b) / (a union b)
dice_coeff = (2 * cells[3] / (2* cells[3] + cells[1] + cells[2]))
print "Dice Coefficiet = %.2f" % (dice_coeff)
copy_to_clipboard = self._view_frame.dialog_yesno('Dice coefficient = %f\n\nCopy to clipboard?' % dice_coeff, '%.1f%% overlap' % (100*dice_coeff))
if copy_to_clipboard:
self._view_frame.copy_text_to_clipboard('%f' % dice_coeff)
def _compute_hausdorff_distances(self, maskA, maskB):
"""
Computes the Hausdorff Distance between selections in A and B.
Uses the external software tool Metro to do point-based mesh sampling
"""
#We need meshes (polydata) for computing the Hausdorff distances
meshA = None
meshB = None
#actually this should never happen, but let's keep it for making double sure
if not self.surfaces.has_key(maskA.name):
self._view_frame.dialog_exclaim('Mesh belonging to Mask A not found in list, and created on the fly. This is unexpected...', 'Unexpected program state')
surface_creator_A = vtk.vtkDiscreteMarchingCubes()
surface_creator_A.SetInput(maskA.data)
surface_creator_A.Update()
meshA = surface_creator_A.GetOutput()
else:
meshA = self.surfaces[maskA.name]
#actually this should never happen, but let's keep it for making double sure
if not self.surfaces.has_key(maskB.name):
self._view_frame.dialog_exclaim('Mesh belonging to Mask B not found in list, and created on the fly. This is unexpected...', 'Unexpected program state')
surface_creator_B = vtk.vtkDiscreteMarchingCubes()
surface_creator_B.SetInput(maskB.data)
surface_creator_B.Update()
meshB = surface_creator_B.GetOutput()
else:
meshB = self.surfaces[maskB.name]
filename_a = '@temp_mesh_a.ply'
filename_b = '@temp_mesh_b.ply'
ply_writer = vtk.vtkPLYWriter()
ply_writer.SetFileTypeToBinary()
print 'Writing temporary PLY mesh A = %s' % filename_a
ply_writer.SetFileName(filename_a)
ply_writer.SetInput(meshA)
ply_writer.Update()
print 'Writing temporary PLY mesh B = %s' % filename_b
ply_writer.SetFileName(filename_b)
ply_writer.SetInput(meshB)
ply_writer.Update()
command = 'metro.exe %s %s' % (filename_a, filename_b)
p = subprocess.Popen(command, shell=True, stdout = subprocess.PIPE)
outp = p.stdout.read() #The command line output from metro
if len(outp) < 50:
self._view_frame.dialog_error('Hausdorff distance computation requires Metro to be installed and available in the system path.\n\nMetro failed to execute.\n\nAborting.\n\nMetro may be downloaded from http://vcg.sourceforge.net/index.php/Metro', 'Metro was not found')
return
print 'Executing: %s' % command
print '....................................'
print outp
print '....................................'
index = outp.find('max')
hdf = float(outp[index+6:index+54].split()[0]) #Forward Hausdorff distance
index = outp.find('max', index+3)
hdb = float(outp[index+6:index+54].split()[0]) #Backward Hausdorff distance
index = outp.find('mean')
mhdf = float(outp[index+7:index+35].split()[0]) #Forward Mean Hausdorff distance
index = outp.find('mean', index+4)
mhdb = float(outp[index+7:index+35].split()[0]) #Backward Mean Hausdorff distance
hausdorff_distance = max(hdf, hdb)
mean_hausdorff_distance = 0.5 * (mhdf + mhdb)
print 'removing temporary files'
os.remove(filename_a)
os.remove(filename_b)
print 'done!'
print '\nSampled Hausdorff distance = %.4f\nSampled Mean Hausdorff distance = %.4f\n' % (hausdorff_distance, mean_hausdorff_distance)
return [hausdorff_distance, mean_hausdorff_distance]
def _handler_compute_hausdorff_distance(self, event):
"""
Computes the Hausdorff Distance between meshes in A and B.
Uses the external software tool Metro to do point-based mesh sampling
"""
if self.test_single_mask_pair_selection():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
maskA = self.masks[names_a.pop()]
maskB = self.masks[names_b.pop()]
[hausdorff_distance, _] = self._compute_hausdorff_distances(maskA, maskB)
copy_to_clipboard = self._view_frame.dialog_yesno('Hausdorff distance = %.4f mm\n\nCopy to clipboard?' % hausdorff_distance, 'Hausdorff Distance')
if copy_to_clipboard:
self._view_frame.copy_text_to_clipboard('%f' % hausdorff_distance)
def _handler_compute_mean_hausdorff_distance(self, event):
"""
Computes the Mean Hausdorff Distance between meshes in A and B.
Uses the external software tool Metro to do point-based mesh sampling
"""
if self.test_single_mask_pair_selection():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
maskA = self.masks[names_a.pop()]
maskB = self.masks[names_b.pop()]
[_, mean_hausdorff_distance] = self._compute_hausdorff_distances(maskA, maskB)
copy_to_clipboard = self._view_frame.dialog_yesno('Mean Hausdorff distance = %.4f mm\n\nCopy to clipboard?' % mean_hausdorff_distance, 'Mean Hausdorff distance')
if copy_to_clipboard:
self._view_frame.copy_text_to_clipboard('%f' % mean_hausdorff_distance)
def _handler_mask_join(self, event):
"""Computes the union of the masks selected in boxes A and B.
Saves the result as a new Mask
"""
if self.test_valid_mask_selection_any():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
if len(names_a) + len(names_b) < 2:
return
union_masksA = self.compute_mask_union(names_a)
union_masksB = self.compute_mask_union(names_b)
new_mask = None
if len(names_a) == 0:
new_mask = union_masksB
elif len(names_b) == 0:
new_mask = union_masksA
else:
new_mask = self._logical_unite_masks(union_masksA, union_masksB)
self.add_mask(new_mask)
def _handler_mask_subtract(self, event):
"""Subtracts the the union of the masks selected in box B from the union of the masks selected in box A.
Saves the result as a new Mask
"""
if self.test_valid_mask_selection_a_and_b():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
union_masksA = self.compute_mask_union(names_a)
union_masksB = self.compute_mask_union(names_b)
new_mask = self._logical_subtract_masks(union_masksA, union_masksB)
self.add_mask(new_mask)
def _handler_mask_intersect(self, event):
"""Intersects the the union of the masks selected in box A with the union of the masks selected in box B.
Saves the result as a new Mask
"""
if self.test_valid_mask_selection_a_and_b():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
union_masksA = self.compute_mask_union(names_a)
union_masksB = self.compute_mask_union(names_b)
new_mask = self._logical_intersect_masks(union_masksA, union_masksB)
self.add_mask(new_mask)
def _test_intersections(self, mask_name_list):
"""
Tests for intersections between the masks listed in mask_names
"""
mask_names = copy.copy(mask_name_list)
first_name = mask_names.pop()
data = self.masks[first_name].data
intersections_found = False
eight_bit = False
for mask_name in mask_names:
print 'adding %s' % mask_name
data2 = self.masks[mask_name].data
adder = vtk.vtkImageMathematics()
adder.SetOperationToAdd()
adder.SetInput1(data)
adder.SetInput2(data2)
adder.Update()
data = adder.GetOutput()
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(data)
accumulator.Update()
max = accumulator.GetMax()[0]
if max == 255:
eight_bit = True
elif max > 1:
intersections_found = True
else:
self._view_frame.dialog_info("No intersections found.\n(duplicate selections in A and B ignored).", "No intersections")
if eight_bit:
eight_bit_mask_names = ''
mask_names = copy.copy(mask_name_list)
for mask_name in mask_names:
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(self.masks[mask_name].data)
accumulator.Update()
if accumulator.GetMax()[0] == 255:
eight_bit_mask_names = '%s, "%s"' % (eight_bit_mask_names, mask_name)
eight_bit_mask_names = eight_bit_mask_names[2:] #Remove the first two characters for neat display purposes
self._view_frame.dialog_error("Masks should be binary. The following masks were found to be 8-bit:\n%s" % eight_bit_mask_names,"Non-binary mask found!")
elif intersections_found:
mask_name_pair_list = ''
mask_names = copy.copy(mask_name_list)
while len(mask_names) > 0:
name1 = mask_names.pop()
for name2 in mask_names:
adder = vtk.vtkImageMathematics()
adder.SetOperationToAdd()
adder.SetInput1(self.masks[name1].data)
adder.SetInput2(self.masks[name2].data)
adder.Update()
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(adder.GetOutput())
accumulator.Update()
if accumulator.GetMax()[0] == 2:
mask_name_pair_list = '%s,\n ("%s","%s")' % (mask_name_pair_list, name1, name2)
mask_name_pair_list = mask_name_pair_list[2:] #Remove the first two characters for neat display purposes
self._view_frame.dialog_exclaim("Intersections found between the following mask pairs:\n%s" % mask_name_pair_list,"Intersections found!")
def _test_dimensions(self, mask_names, msg):
"""
Tests whether the given masks have matching volumetric dimensions.
In practice mismatches can occur due to problems with feature generation algorithms (such as filtered backprojection)
"""
masks_by_dimensions = {}
masks_by_extent = {}
masks_by_whole_extent = {}
masks_by_spacing = {}
for mask_name in mask_names:
maskdata = self.masks[mask_name].data
dimensions = maskdata.GetDimensions()
spacing = maskdata.GetSpacing()
extent = maskdata.GetExtent()
whole_extent = maskdata.GetWholeExtent()
if not masks_by_dimensions.has_key(dimensions):
masks_by_dimensions[dimensions] = [str(mask_name)]
else:
masks_by_dimensions[dimensions].append(str(mask_name))
if not masks_by_spacing.has_key(spacing):
masks_by_spacing[spacing] = [str(mask_name)]
else:
masks_by_spacing[spacing].append(str(mask_name))
if not masks_by_extent.has_key(extent):
masks_by_extent[extent] = [str(mask_name)]
else:
masks_by_extent[extent].append(str(mask_name))
if not masks_by_whole_extent.has_key(whole_extent):
masks_by_whole_extent[whole_extent] = [str(mask_name)]
else:
masks_by_whole_extent[whole_extent].append(str(mask_name))
if len(masks_by_dimensions.keys()) == 1 and len(masks_by_spacing.keys()) == 1 and len(masks_by_extent.keys()) == 1 and len(masks_by_whole_extent.keys()):
dimension_report = '%s masks have the same dimensions, spacing, extent and whole extent:\n\n' % msg
dimensions = masks_by_dimensions.keys().pop()
dimension_report = '%s dimensions = %s\n' % (dimension_report, str(dimensions))
dimensions = masks_by_spacing.keys().pop()
dimension_report = '%s spacing = %s\n' % (dimension_report, str(dimensions))
dimensions = masks_by_extent.keys().pop()
dimension_report = '%s extent = %s\n' % (dimension_report, str(dimensions))
dimensions = masks_by_whole_extent.keys().pop()
dimension_report = '%s whole extent = %s\n' % (dimension_report, str(dimensions))
self._view_frame.dialog_info(dimension_report, 'No mismatches')
else:
dimension_report = '% masks possess %d unique sets of dimensions. See below:\n' % (msg, len(masks_by_dimensions))
for k in masks_by_dimensions.keys():
dimension_report = '%s\n%s => %s' % (dimension_report, str(k), str( masks_by_dimensions[k]))
dimension_report = '%s\n\n%d unique spacings with their defining masks:\n' % (dimension_report, len(masks_by_spacing))
for k in masks_by_spacing.keys():
dimension_report = '%s\n%s => %s' % (dimension_report, str(k), str( masks_by_spacing[k]))
dimension_report = '%s\n\n%d unique extents with their defining masks:\n' % (dimension_report, len(masks_by_extent))
for k in masks_by_extent.keys():
dimension_report = '%s\n%s => %s' % (dimension_report, str(k), str( masks_by_extent[k]))
dimension_report = '%s\n\n%d unique whole_extents with their defining masks:\n' % (dimension_report, len(masks_by_whole_extent))
for k in masks_by_whole_extent.keys():
dimension_report = '%s\n%s => %s' % (dimension_report, str(k), str( masks_by_whole_extent[k]))
self._view_frame.dialog_exclaim(dimension_report,"Mismatches found!")
def _handler_test_all_dimensions(self, event):
"""
Tests whether any of the loaded masks have mismatching volume dimensions
"""
if len(self.masks) < 2:
self._view_frame.dialog_info("At least 2 masks need to be loaded to compare dimensions!","Fewer than two masks loaded")
return
mask_names = self.masks.keys()
self._test_dimensions(mask_names, 'All')
def _handler_test_selected_dimensions(self, event):
"""
Tests the selected masks have mismatching volume dimensions
"""
if self.test_valid_mask_selection_multiple():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
mask_names = names_a.copy()
for name in names_b:
mask_names.add(name)
self._test_dimensions(mask_names, 'Selected')
def _handler_test_all_intersections(self, event):
"""
Tests whether there is an intersection between any of the loaded masks
"""
if len(self.masks) < 2:
self._view_frame.dialog_info("At least 2 masks need to be loaded to detect intersections!","Fewer than two masks loaded")
return
mask_names = self.masks.keys()
self._test_intersections(mask_names)
def _handler_test_selected_intersections(self, event):
"""
Tests whether there is an intersection between the selected masks
"""
if self.test_valid_mask_selection_multiple():
names_a = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
mask_names = names_a.copy()
for name in names_b:
mask_names.add(name)
self._test_intersections(mask_names)
def compute_mask_union(self, mask_names_set):
'''Computes and returns the union of a set of masks, identified by a set of mask names.'''
mask_names = mask_names_set.copy() #To prevent changes to the passed set due to popping
united_mask = None
if len(mask_names) > 0:
mask_name = mask_names.pop()
united_mask = self.masks[mask_name]
for mask_name in mask_names:
united_mask = self._logical_unite_masks(united_mask, self.masks[mask_name])
return united_mask
def test_single_mask_selection(self):
selectionCountA = self._view_frame.list_ctrl_maskA.GetSelectedItemCount()
selectionCountB = self._view_frame.list_ctrl_maskB.GetSelectedItemCount()
if selectionCountA + selectionCountB == 0:
self._view_frame.dialog_info("No masks are selected in either column A or B.\nThis operation requires a single mask, either in A or B.","No masks selected - invalid operation")
return False
elif selectionCountA + selectionCountB > 1:
self._view_frame.dialog_info("Multiple masks are selected in columns A and/or B.\nThis operation requires a single mask, either in A or B (but not both).","Multiple masks selected - invalid operation")
return False
return True
def test_single_mask_pair_selection(self):
selectionCountA = self._view_frame.list_ctrl_maskA.GetSelectedItemCount()
selectionCountB = self._view_frame.list_ctrl_maskB.GetSelectedItemCount()
if selectionCountA == 0:
self._view_frame.dialog_info("No mask selected in column A.\nThis operation requires a single input each, for A and B.","Too few masks selected - invalid operation")
return False
if selectionCountB == 0:
self._view_frame.dialog_info("No mask selected in column B.\nThis operation requires a single input each, for A and B.","Too few masks selected - invalid operation")
return False
if selectionCountA > 1:
self._view_frame.dialog_info("Multiple masks are selected in column A.\nThis operation requires a single input each, for A and B.","Multiple maks selected - invalid operation")
return False
elif selectionCountB > 1:
self._view_frame.dialog_info("Multiple masks are selected in column B.\nThis operation requires a single input each, for A and B.","Multiple maks selected - invalid operation")
return False
return True
def test_valid_mask_selection_any(self, warn = True):
selectionCountA = self._view_frame.list_ctrl_maskA.GetSelectedItemCount()
selectionCountB = self._view_frame.list_ctrl_maskB.GetSelectedItemCount()
if selectionCountA == 0 and selectionCountB == 0:
if warn:
self._view_frame.dialog_info("No masks are selected.","No masks selected")
return False
return True
def test_valid_mask_selection_multiple(self, warn = True):
names = self._view_frame.get_selected_mask_names_a()
names_b = self._view_frame.get_selected_mask_names_b()
for name in names_b:
names.add(name)
if len(names) < 2:
if warn:
self._view_frame.dialog_info("Fewer than two unique masks selected.","Too few masks selected")
return False
return True
def test_valid_mask_selection_a_and_b(self, warn = True):
selectionCountA = self._view_frame.list_ctrl_maskA.GetSelectedItemCount()
selectionCountB = self._view_frame.list_ctrl_maskB.GetSelectedItemCount()
if selectionCountA == 0:
if warn:
self._view_frame.dialog_info("No mask is selected in column A.\nThis operation requires inputs A and B.","Mask A not defined")
return False
elif selectionCountB == 0:
if warn:
self._view_frame.dialog_info("No mask is selected in column B.\nThis operation requires inputs A and B.","Mask B not defined")
return False
return True
def test_valid_mask_selection_a(self, warn = True):
selection_count_a = self._view_frame.list_ctrl_maskA.GetSelectedItemCount()
if selection_count_a == 0:
if warn:
self._view_frame.dialog_info("This operation requires input from column A.","Mask A not defined")
return False
return True
def test_valid_mask_selection_b(self, warn = True):
selection_count_b = self._view_frame.list_ctrl_maskB.GetSelectedItemCount()
if selection_count_b == 0:
if warn:
self._view_frame.dialog_info("This operation requires input from column B.","Mask B not defined")
return False
return True
def _handler_close(self, event):
"Closes this program"
self.close()
def _handler_introspect(self, event):
self.miscObjectConfigure(self._view_frame, self, 'MaskComBinar')
def _handler_about(self, event):
self._view_frame.dialog_info("MaskComBinar:\nA tool for measuring and manipulating binary masks\n\nby Francois Malan","About MaskComBinar")
def render(self):
"""Method that calls Render() on the embedded RenderWindow.
Use this after having made changes to the scene.
"""
self._view_frame.render()
def _logical_unite_masks(self, maskA, maskB):
"""Returns logical addition of maskA and maskB => maskA OR maskB"""
if maskA == None:
return maskB
elif maskB == None:
return maskA
print 'Joining masks %s and %s' % (maskA.name, maskB.name)
logicOR = vtk.vtkImageLogic()
logicOR.SetOperationToOr()
logicOR.SetInput1(maskA.data)
logicOR.SetInput2(maskB.data)
logicOR.Update()
result = self._threshold_image(logicOR.GetOutput(), 1, 255)
return Mask('Merged','',result)
def _logical_intersect_masks(self, maskA, maskB):
if maskA == None or maskB == None:
return None
print 'Intersecting masks %s and %s' % (maskA.name, maskB.name)
logicAND = vtk.vtkImageLogic()
logicAND.SetOperationToAnd()
logicAND.SetInput1(maskA.data)
logicAND.SetInput2(maskB.data)
logicAND.Update()
result = self._threshold_image(logicAND.GetOutput(), 1, 255)
return Mask('Intersect','',result)
def _logical_subtract_masks(self, maskA, maskB):
"""Returns logical subtraction of maskB from maskA => maskA AND (NOT maskB)"""
if maskB == None:
return maskA
print 'Subtracting mask %s and %s' % (maskA.name, maskB.name)
logicNOT = vtk.vtkImageLogic()
logicNOT.SetOperationToNot()
logicNOT.SetInput1(maskB.data)
logicNOT.Update()
logicAND = vtk.vtkImageLogic()
logicAND.SetOperationToAnd()
logicAND.SetInput1(maskA.data)
logicAND.SetInput2(logicNOT.GetOutput())
logicAND.Update()
result = self._threshold_image(logicAND.GetOutput(), 1, 255)
return Mask('Diff','',result)
def _threshold_image(self, image, lower, upper):
"""Thresholds a VTK Image, returning a signed short mask with 1 inside and 0 outside [lower, upper]"""
thresholder = vtk.vtkImageThreshold()
thresholder.SetInput(image)
thresholder.ThresholdBetween(lower, upper)
thresholder.SetInValue(1)
thresholder.SetOutValue(0)
thresholder.SetOutputScalarTypeToUnsignedChar()
thresholder.Update()
result = vtk.vtkImageData()
result.DeepCopy(thresholder.GetOutput())
return result
def _split_disconnected_objects(self, mask_name):
#This is done by labelling the objects from large to small
#Convert to ITK
mask = self.masks[mask_name]
thresholder = vtk.vtkImageThreshold()
thresholder.SetInput(mask.data)
thresholder.ThresholdBetween(1, 9999)
thresholder.SetInValue(1)
thresholder.SetOutValue(0)
thresholder.SetOutputScalarTypeToShort()
thresholder.Update()
v2i = itk.VTKImageToImageFilter[itk.Image.SS3].New()
v2i.SetInput(thresholder.GetOutput())
ccf = itk.ConnectedComponentImageFilter.ISS3ISS3.New()
ccf.SetInput(v2i.GetOutput())
relabeller = itk.RelabelComponentImageFilter.ISS3ISS3.New()
relabeller.SetInput(ccf.GetOutput())
#convert back to VTK
i2v = itk.ImageToVTKImageFilter[itk.Image.SS3].New()
i2v.SetInput(relabeller.GetOutput())
i2v.Update()
labeled = i2v.GetOutput()
accumulator = vtk.vtkImageAccumulate()
accumulator.SetInput(labeled)
accumulator.Update()
nr_of_components = accumulator.GetMax()[0]
print 'Found %d disconnected mask components' % nr_of_components
message = '%d disconnected components found.\nHow many do you want to accept (large to small)?' % nr_of_components
nr_to_process_str = self._view_frame.dialog_inputtext(message, 'Choose number of disconnected components', '1')[1]
try:
nr_to_process = int(nr_to_process_str)
except:
self._view_frame.dialog_error('Invalid numeric input: %s' % nr_to_process_str, "Invalid input")
return
if (nr_to_process < 0) or (nr_to_process > nr_of_components):
self._view_frame.dialog_error('Number must be between 1 and %d' % nr_of_components, "Invalid input")
return
print 'Saving the largest %d components to new masks' % nr_to_process
thresholder = vtk.vtkImageThreshold()
thresholder.SetInput(labeled)
thresholder.SetInValue(1)
thresholder.SetOutValue(0)
thresholder.SetOutputScalarTypeToUnsignedChar()
for i in range(1, nr_to_process+1):
thresholder.ThresholdBetween(i, i)
thresholder.Update()
mask_data = vtk.vtkImageData()
mask_data.DeepCopy(thresholder.GetOutput())
new_mask = Mask('comp_%d' % i,'',mask_data)
self.add_mask(new_mask) | Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import cStringIO
from vtk.wx.wxVTKRenderWindowInteractor import wxVTKRenderWindowInteractor
import wx
# wxPython 2.8.8.1 wx.aui bugs severely on GTK. See:
# http://trac.wxwidgets.org/ticket/9716
# Until this is fixed, use this PyAUI to which I've added a
# wx.aui compatibility layer.
if wx.Platform == "__WXGTK__":
from external import PyAUI
wx.aui = PyAUI
else:
import wx.aui
# one could have loaded a wxGlade created resource like this:
#from resources.python import DICOMBrowserPanels
#reload(DICOMBrowserPanels)
class SkeletonAUIViewerFrame(wx.Frame):
"""wx.Frame child class used by SkeletonAUIViewer for its
interface.
This is an AUI-managed window, so we create the top-level frame,
and then populate it with AUI panes.
"""
def __init__(self, parent, id=-1, title="", name=""):
wx.Frame.__init__(self, parent, id=id, title=title,
pos=wx.DefaultPosition, size=(800,800), name=name)
self.menubar = wx.MenuBar()
self.SetMenuBar(self.menubar)
file_menu = wx.Menu()
self.id_file_open = wx.NewId()
file_menu.Append(self.id_file_open, "&Open\tCtrl-O",
"Open a file", wx.ITEM_NORMAL)
self.menubar.Append(file_menu, "&File")
views_menu = wx.Menu()
views_default_id = wx.NewId()
views_menu.Append(views_default_id, "&Default\tCtrl-0",
"Activate default view layout.", wx.ITEM_NORMAL)
views_max_image_id = wx.NewId()
views_menu.Append(views_max_image_id, "&Maximum image size\tCtrl-1",
"Activate maximum image view size layout.",
wx.ITEM_NORMAL)
self.menubar.Append(views_menu, "&Views")
# tell FrameManager to manage this frame
self._mgr = wx.aui.AuiManager()
self._mgr.SetManagedWindow(self)
self._mgr.AddPane(self._create_series_pane(), wx.aui.AuiPaneInfo().
Name("series").Caption("Series").Top().
BestSize(wx.Size(600, 100)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_files_pane(), wx.aui.AuiPaneInfo().
Name("files").Caption("Image Files").
Left().
BestSize(wx.Size(200,400)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_meta_pane(), wx.aui.AuiPaneInfo().
Name("meta").Caption("Image Metadata").
Left().
BestSize(wx.Size(200,400)).
CloseButton(False).MaximizeButton(True))
self._mgr.AddPane(self._create_rwi_pane(), wx.aui.AuiPaneInfo().
Name("rwi").Caption("3D Renderer").
Center().
BestSize(wx.Size(400,400)).
CloseButton(False).MaximizeButton(True))
self.SetMinSize(wx.Size(400, 300))
# first we save this default perspective with all panes
# visible
self._perspectives = {}
self._perspectives['default'] = self._mgr.SavePerspective()
# then we hide all of the panes except the renderer
self._mgr.GetPane("series").Hide()
self._mgr.GetPane("files").Hide()
self._mgr.GetPane("meta").Hide()
# save the perspective again
self._perspectives['max_image'] = self._mgr.SavePerspective()
# and put back the default perspective / view
self._mgr.LoadPerspective(self._perspectives['default'])
# finally tell the AUI manager to do everything that we've
# asked
self._mgr.Update()
# we bind the views events here, because the functionality is
# completely encapsulated in the frame and does not need to
# round-trip to the DICOMBrowser main module.
self.Bind(wx.EVT_MENU, self._handler_default_view,
id=views_default_id)
self.Bind(wx.EVT_MENU, self._handler_max_image_view,
id=views_max_image_id)
def close(self):
self.Destroy()
def _create_files_pane(self):
sl = wx.ListCtrl(self, -1,
style=wx.LC_REPORT)
sl.InsertColumn(0, "Full name")
# we'll autosize this column later
sl.SetColumnWidth(0, 300)
#sl.InsertColumn(SeriesColumns.modality, "Modality")
self.files_lc = sl
return sl
def _create_rwi_pane(self):
panel = wx.Panel(self, -1)
self.rwi = wxVTKRenderWindowInteractor(panel, -1, (400,400))
self.button1 = wx.Button(panel, -1, "Add Superquadric")
self.button2 = wx.Button(panel, -1, "Reset Camera")
self.button3 = wx.Button(panel, -1, "Start Timer Event")
button_sizer = wx.BoxSizer(wx.HORIZONTAL)
button_sizer.Add(self.button1)
button_sizer.Add(self.button2)
button_sizer.Add(self.button3)
sizer1 = wx.BoxSizer(wx.VERTICAL)
sizer1.Add(self.rwi, 1, wx.EXPAND|wx.BOTTOM, 7)
sizer1.Add(button_sizer)
tl_sizer = wx.BoxSizer(wx.VERTICAL)
tl_sizer.Add(sizer1, 1, wx.ALL|wx.EXPAND, 7)
panel.SetSizer(tl_sizer)
tl_sizer.Fit(panel)
return panel
def _create_meta_pane(self):
ml = wx.ListCtrl(self, -1,
style=wx.LC_REPORT |
wx.LC_HRULES | wx.LC_VRULES |
wx.LC_SINGLE_SEL)
ml.InsertColumn(0, "Key")
ml.SetColumnWidth(0, 70)
ml.InsertColumn(1, "Value")
ml.SetColumnWidth(1, 70)
self.meta_lc = ml
return ml
def _create_series_pane(self):
sl = wx.ListCtrl(self, -1,
style=wx.LC_REPORT | wx.LC_HRULES | wx.LC_SINGLE_SEL,
size=(600,120))
sl.InsertColumn(0, "Description")
sl.SetColumnWidth(1, 170)
sl.InsertColumn(2, "Modality")
sl.InsertColumn(3, "# Images")
sl.InsertColumn(4, "Size")
self.series_lc = sl
return sl
def render(self):
"""Update embedded RWI, i.e. update the image.
"""
self.rwi.Render()
def _handler_default_view(self, event):
"""Event handler for when the user selects View | Default from
the main menu.
"""
self._mgr.LoadPerspective(
self._perspectives['default'])
def _handler_max_image_view(self, event):
"""Event handler for when the user selects View | Max Image
from the main menu.
"""
self._mgr.LoadPerspective(
self._perspectives['max_image'])
| Python |
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import operator
HTML_START = '<html><body>'
HTML_END = '</body></html>'
def render_actions(lines):
ms = '<p><b><ul>%s</ul></b></p>'
# this should yield: <li>thing 1\n<li>thing 2\n<li>thing 3 etc
bullets = '\n'.join(['<li>%s</li>' % l for l in lines])
return ms % (bullets,)
#return '<p><b>%s</b>' % ('<br>'.join(lines),)
def render_description(lines):
return '<p>%s' % ('<br>'.join(lines),)
def render_main_type(line):
return '<h2>%s</h2>' % (line,)
class QuickInfo(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._input = None
self._view_frame = None
self._create_view_frame()
self.view()
self.view_initialised = True
def _create_view_frame(self):
import resources.python.quick_info_frames
reload(resources.python.quick_info_frames)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
resources.python.quick_info_frames.QuickInfoFrame)
module_utils.create_standard_object_introspection(
self, self._view_frame,
self._view_frame.view_frame_panel,
{'Module (self)' : self})
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.view_frame_panel)
def close(self):
for i in range(len(self.get_input_descriptions())):
self.set_input(i, None)
self._view_frame.Destroy()
del self._view_frame
ModuleBase.close(self)
def get_input_descriptions(self):
return ('Any DeVIDE data',)
def get_output_descriptions(self):
return ()
def set_input(self, idx, input_stream):
self._input = input_stream
def get_output(self, idx):
raise RuntimeError
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
pass
def config_to_view(self):
pass
def view(self):
self._view_frame.Show()
self._view_frame.Raise()
def execute_module(self):
oh = self._view_frame.output_html
ip = self._input
if ip is None:
html = 'There is no input (input is "None").'
elif self.check_vtk(ip):
html = self.analyse_vtk(ip)
elif self.check_itk(ip):
html = self.analyse_itk(ip)
else:
html = 'Could not determine type of data.'
oh.SetPage(html)
def analyse_vtk(self, ip):
lines = [HTML_START]
# main data type
lines.append("<h2>%s</h2>" % (ip.GetClassName(),))
if ip.IsA('vtkPolyData'):
# more detailed human-readable description
lines.append('<p>VTK format polygonal / mesh data<br>')
lines.append('%d points<br>' % (ip.GetNumberOfPoints(),))
lines.append('%d polygons<br>' % (ip.GetNumberOfPolys(),))
# how can the data be visualised
lines.append('<p><b>Surface render with slice3dVWR.</b>')
elif ip.IsA('vtkImageData'):
# more detailed human-readable description
lines.append('<p>VTK format regular grid / volume<br>')
dx,dy,dz = ip.GetDimensions()
lines.append('%d x %d x %d == %d voxels<br>' % \
(dx,dy,dz,dx*dy*dz))
lines.append('physical spacing %.3f x %.3f x %.3f<br>' % \
ip.GetSpacing())
lines.append('<br>image origin (%.2f, %.2f, %.2f)<br>' % \
ip.GetOrigin())
lines.append('<br>image bounds (%.2f, %.2f, %.2f, %.2f, %.2f, %.2f)<br>' % \
ip.GetBounds())
lines.append('image extent (%d, %d, %d, %d, %d, %d)<br>' % \
ip.GetExtent())
# how can the data be visualised
lines.append(render_actions(
["Slice through the data (MPR) with 'slice3dVWR'",
"Extract an isosurface with 'contour'",
"Direct volume render (DVR) with 'VolumeRender'"]
))
elif ip.IsA('vtkImplicitFunction'):
# more detailed human-readable description
lines.append('<p>VTK format implicit function')
# possible actions
lines.append(
"""<p><b>Clip mesh data with 'clipPolyData'<br>
Sample to volume with 'ImplicitToVolume'</b>""")
elif ip.IsA('vtkProp'):
# more detailed human-readable description
lines.append('<p>VTK object in 3-D scene')
# possible actions
lines.append(
render_actions(
["Visualise in 3-D scene with 'slice3dVWR'"])
)
# give information about point (geometry) attributes
try:
pd = ip.GetPointData()
except AttributeError:
pass
else:
na = pd.GetNumberOfArrays()
if na > 0:
lines.append('<p>Data associated with points:<br>')
for i in range(na):
a = pd.GetArray(i)
l = "'%s': %d %d-element tuples of type %s<br>" % \
(a.GetName(), a.GetNumberOfTuples(),
a.GetNumberOfComponents(),
a.GetDataTypeAsString())
lines.append(l)
lines.append(HTML_END)
return '\n'.join(lines)
def check_vtk(self, ip):
try:
cn = ip.GetClassName()
except AttributeError:
return False
else:
if cn.startswith('vtk'):
return True
return False
def analyse_itk(self, ip):
lines = [HTML_START]
noc = ip.GetNameOfClass()
mt = 'itk::%s' % (noc,)
lines.append(render_main_type(mt))
if noc == 'Image':
# general description ##################################
from module_kits.misc_kit.misc_utils import \
get_itk_img_type_and_dim
itype, dim, qual_str = get_itk_img_type_and_dim(ip)
dim = int(dim)
dl = ['ITK format %d-dimensional %s %s image / volume' % \
(dim, itype, qual_str)]
s = ip.GetLargestPossibleRegion().GetSize()
dims = [s.GetElement(i) for i in range(dim)]
# this results in 234 x 234 x 123 x 123 (depending on num
# of dimensions)
dstr = ' x '.join(['%s'] * dim) % tuple(dims)
# the reduce multiplies all dims with each other
dl.append('%s = %d pixels' % \
(dstr, reduce(operator.mul, dims)))
comps = ip.GetNumberOfComponentsPerPixel()
dl.append('%d component(s) per pixel' % (comps,))
# spacing string
spacing = [ip.GetSpacing().GetElement(i)
for i in range(dim)]
sstr = ' x '.join(['%.3f'] * dim) % tuple(spacing)
dl.append('physical spacing %s' % (sstr,))
# origin string
origin = [ip.GetOrigin().GetElement(i)
for i in range(dim)]
ostr = ', '.join(['%.2f'] * dim) % tuple(origin)
dl.append('<br>image origin (%s)' % (ostr,))
lines.append(render_description(dl))
# possible actions ######################################
al = ["Process with other ITK filters",
"Convert to VTK with ITKtoVTK"]
lines.append(render_actions(al))
lines.append(HTML_END)
return '\n'.join(lines)
def check_itk(self, ip):
if repr(ip).startswith('<itk'):
return True
else:
return False
| Python |
# __init__.py by Charl P. Botha <cpbotha@ieee.org>
# $Id$
# used to be module list, now dummy file
| Python |
# dumy __init__ so this directory can function as a package
| Python |
#!/usr/bin/env python
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import re
import getopt
import mutex
import os
import re
import stat
import string
import sys
import time
import traceback
import ConfigParser
# we need to import this explicitly, else the installer builder
# forgets it and the binary has e.g. no help() support.
import site
dev_version = False
try:
# devide_versions.py is written by johannes during building DeVIDE distribution
import devide_versions
except ImportError:
dev_version = True
else:
# check if devide_version.py comes from the same dir as this devide.py
dv_path = os.path.abspath(os.path.dirname(devide_versions.__file__))
d_path = os.path.abspath(os.path.dirname(sys.argv[0]))
if dv_path != d_path:
# devide_versions.py is imported from a different dir than this file, so DEV
dev_version = True
if dev_version:
# if there's no valid versions.py, we have these defaults
# DEVIDE_VERSION is usually y.m.d of the release, or y.m.D if
# development version
DEVIDE_VERSION = "12.3.D"
DEVIDE_REVISION_ID = "DEV"
JOHANNES_REVISION_ID = "DEV"
else:
DEVIDE_VERSION = devide_versions.DEVIDE_VERSION
DEVIDE_REVISION_ID = devide_versions.DEVIDE_REVISION_ID
JOHANNES_REVISION_ID = devide_versions.JOHANNES_REVISION_ID
############################################################################
class MainConfigClass(object):
def __init__(self, appdir):
# first need to parse command-line to get possible --config-profile
# we store all parsing results in pcl_data structure
##############################################################
pcl_data = self._parseCommandLine()
config_defaults = {
'nokits': '',
'interface' : 'wx',
'scheduler' : 'hybrid',
'extra_module_paths' : '',
'streaming_pieces' : 5,
'streaming_memory' : 100000}
cp = ConfigParser.ConfigParser(config_defaults)
cp.read(os.path.join(appdir, 'devide.cfg'))
CSEC = pcl_data.config_profile
# then apply configuration file and defaults #################
##############################################################
nokits = [i.strip() for i in cp.get(CSEC, \
'nokits').split(',')]
# get rid of empty strings (this is not as critical here as it
# is for emps later, but we like to be consistent)
self.nokits = [i for i in nokits if i]
self.streaming_pieces = cp.getint(CSEC, 'streaming_pieces')
self.streaming_memory = cp.getint(CSEC, 'streaming_memory')
self.interface = cp.get(CSEC, 'interface')
self.scheduler = cp.get(CSEC, 'scheduler')
emps = [i.strip() for i in cp.get(CSEC, \
'extra_module_paths').split(',')]
# ''.split(',') will yield [''], which we have to get rid of
self.extra_module_paths = [i for i in emps if i]
# finally apply command line switches ############################
##################################################################
# these ones can be specified in config file or parameters, so
# we have to check first if parameter has been specified, in
# which case it overrides config file specs
if pcl_data.nokits:
self.nokits = pcl_data.nokits
if pcl_data.scheduler:
self.scheduler = pcl_data.scheduler
if pcl_data.extra_module_paths:
self.extra_module_paths = pcl_data.extra_module_paths
# command-line only, defaults set in PCLData ctor
# so we DON'T have to check if config file has already set
# them
self.interface = pcl_data.interface
self.stereo = pcl_data.stereo
self.test = pcl_data.test
self.script = pcl_data.script
self.script_params = pcl_data.script_params
self.load_network = pcl_data.load_network
self.hide_devide_ui = pcl_data.hide_devide_ui
# now sanitise some options
if type(self.nokits) != type([]):
self.nokits = []
def dispUsage(self):
self.disp_version()
print ""
print "-h or --help : Display this message."
print "-v or --version : Display DeVIDE version."
print "--version-more : Display more DeVIDE version info."
print "--config-profile name : Use config profile with name."
print "--no-kits kit1,kit2 : Don't load the specified kits."
print "--kits kit1,kit2 : Load the specified kits."
print "--scheduler hybrid|event"
print " : Select scheduler (def: hybrid)"
print "--extra-module-paths path1,path2"
print " : Specify extra module paths."
print "--interface wx|script"
print " : Load 'wx' or 'script' interface."
print "--stereo : Allocate stereo visuals."
print "--test : Perform built-in unit testing."
print "--script : Run specified .py in script mode."
print "--load-network : Load specified DVN after startup."
print "--hide-devide-ui : Hide the DeVIDE UI at startup."
def disp_version(self):
print "DeVIDE v%s" % (DEVIDE_VERSION,)
def disp_more_version_info(self):
print "DeVIDE rID:", DEVIDE_REVISION_ID
print "Constructed by johannes:", JOHANNES_REVISION_ID
def _parseCommandLine(self):
"""Parse command-line, return all parsed parameters in
PCLData class.
"""
class PCLData:
def __init__(self):
self.config_profile = 'DEFAULT'
self.nokits = None
self.interface = None
self.scheduler = None
self.extra_module_paths = None
self.stereo = False
self.test = False
self.script = None
self.script_params = None
self.load_network = None
self.hide_devide_ui = None
pcl_data = PCLData()
try:
# 'p:' means -p with something after
optlist, args = getopt.getopt(
sys.argv[1:], 'hv',
['help', 'version', 'version-more', 'no-kits=', 'kits=', 'stereo', 'interface=', 'test',
'script=', 'script-params=', 'config-profile=',
'scheduler=', 'extra-module-paths=', 'load-network='])
except getopt.GetoptError,e:
self.dispUsage()
sys.exit(1)
for o, a in optlist:
if o in ('-h', '--help'):
self.dispUsage()
sys.exit(0)
elif o in ('-v', '--version'):
self.disp_version()
sys.exit(0)
elif o in ('--version-more',):
self.disp_more_version_info()
sys.exit(0)
elif o in ('--config-profile',):
pcl_data.config_profile = a
elif o in ('--no-kits',):
pcl_data.nokits = [i.strip() for i in a.split(',')]
elif o in ('--kits',):
# this actually removes the listed kits from the nokits list
kits = [i.strip() for i in a.split(',')]
for kit in kits:
try:
del pcl_data.nokits[pcl_data.nokits.index(kit)]
except ValueError:
pass
elif o in ('--interface',):
if a == 'pyro':
pcl_data.interface = 'pyro'
elif a == 'xmlrpc':
pcl_data.interface = 'xmlrpc'
elif a == 'script':
pcl_data.interface = 'script'
else:
pcl_data.interface = 'wx'
elif o in ('--scheduler',):
if a == 'event':
pcl_data.scheduler = 'event'
else:
pcl_data.scheduler = 'hybrid'
elif o in ('--extra-module-paths',):
emps = [i.strip() for i in a.split(',')]
# get rid of empty paths
pcl_data.extra_module_paths = [i for i in emps if i]
elif o in ('--stereo',):
pcl_data.stereo = True
elif o in ('--test',):
pcl_data.test = True
elif o in ('--script',):
pcl_data.script = a
elif o in ('--script-params',):
pcl_data.script_params = a
elif o in ('--load-network',):
pcl_data.load_network = a
elif o in ('--hide-devide-ui',):
pcl_data.hide_devide_ui = a
return pcl_data
############################################################################
class DeVIDEApp:
"""Main devide application class.
This instantiates the necessary main loop class (wx or headless pyro) and
acts as communications hub for the rest of DeVIDE. It also instantiates
and owns the major components: Scheduler, ModuleManager, etc.
"""
def __init__(self):
"""Construct DeVIDEApp.
Parse command-line arguments, read configuration. Instantiate and
configure relevant main-loop / interface class.
"""
self._inProgress = mutex.mutex()
self._previousProgressTime = 0
self._currentProgress = -1
self._currentProgressMsg = ''
#self._appdir, exe = os.path.split(sys.executable)
if hasattr(sys, 'frozen') and sys.frozen:
self._appdir, exe = os.path.split(sys.executable)
else:
dirname = os.path.dirname(sys.argv[0])
if dirname and dirname != os.curdir:
self._appdir = os.path.abspath(dirname)
else:
self._appdir = os.getcwd()
sys.path.insert(0, self._appdir) # for cx_Freeze
# before this is instantiated, we need to have the paths
self.main_config = MainConfigClass(self._appdir)
####
# startup relevant interface instance
if self.main_config.interface == 'pyro':
from interfaces.pyro_interface import PyroInterface
self._interface = PyroInterface(self)
# this is a GUI-less interface, so wx_kit has to go
self.main_config.nokits.append('wx_kit')
elif self.main_config.interface == 'xmlrpc':
from interfaces.xmlrpc_interface import XMLRPCInterface
self._interface = XMLRPCInterface(self)
# this is a GUI-less interface, so wx_kit has to go
self.main_config.nokits.append('wx_kit')
elif self.main_config.interface == 'script':
from interfaces.script_interface import ScriptInterface
self._interface = ScriptInterface(self)
self.main_config.nokits.append('wx_kit')
else:
from interfaces.wx_interface import WXInterface
self._interface = WXInterface(self)
if 'wx_kit' in self.main_config.nokits:
self.view_mode = False
else:
self.view_mode = True
####
# now startup module manager
try:
# load up the ModuleManager; we do that here as the ModuleManager
# needs to give feedback via the GUI (when it's available)
global module_manager
import module_manager
self.module_manager = module_manager.ModuleManager(self)
except Exception, e:
es = 'Unable to startup the ModuleManager: %s. Terminating.' % \
(str(e),)
self.log_error_with_exception(es)
# this is a critical error: if the ModuleManager raised an
# exception during construction, we have no ModuleManager
# return False, thus terminating the application
return False
####
# start network manager
import network_manager
self.network_manager = network_manager.NetworkManager(self)
####
# start scheduler
import scheduler
self.scheduler = scheduler.SchedulerProxy(self)
if self.main_config.scheduler == 'event':
self.scheduler.mode = \
scheduler.SchedulerProxy.EVENT_DRIVEN_MODE
self.log_info('Selected event-driven scheduler.')
else:
self.scheduler.mode = \
scheduler.SchedulerProxy.HYBRID_MODE
self.log_info('Selected hybrid scheduler.')
####
# call post-module manager interface hook
self._interface.handler_post_app_init()
self.setProgress(100, 'Started up')
def close(self):
"""Quit application.
"""
self._interface.close()
self.network_manager.close()
self.module_manager.close()
# and make 100% we're done
sys.exit()
def get_devide_version(self):
return DEVIDE_VERSION
def get_module_manager(self):
return self.module_manager
def log_error(self, msg):
"""Report error.
In general this will be brought to the user's attention immediately.
"""
self._interface.log_error(msg)
def log_error_list(self, msgs):
self._interface.log_error_list(msgs)
def log_error_with_exception(self, msg):
"""Can be used by DeVIDE components to log an error message along
with all information about current exception.
"""
import gen_utils
emsgs = gen_utils.exceptionToMsgs()
self.log_error_list(emsgs + [msg])
def log_info(self, message, timeStamp=True):
"""Log informative message to the log file or log window.
"""
self._interface.log_info(message, timeStamp)
def log_message(self, message, timeStamp=True):
"""Log a message that will also be brought to the user's attention,
for example in a dialog box.
"""
self._interface.log_message(message, timeStamp)
def log_warning(self, message, timeStamp=True):
"""Log warning message.
This is not as serious as an error condition, but it should also be
brought to the user's attention.
"""
self._interface.log_warning(message, timeStamp)
def get_progress(self):
return self._currentProgress
def set_progress(self, progress, message, noTime=False):
# 1. we shouldn't call setProgress whilst busy with setProgress
# 2. only do something if the message or the progress has changed
# 3. we only perform an update if a second or more has passed
# since the previous update, unless this is the final
# (i.e. 100% update) or noTime is True
# the testandset() method of mutex.mutex is atomic... this will grab
# the lock and set it if it isn't locked alread and then return true.
# returns false otherwise
if self._inProgress.testandset():
if message != self._currentProgressMsg or \
progress != self._currentProgress:
if abs(progress - 100.0) < 0.01 or noTime or \
time.time() - self._previousProgressTime >= 1:
self._previousProgressTime = time.time()
self._currentProgressMsg = message
self._currentProgress = progress
self._interface.set_progress(progress, message, noTime)
# unset the mutex thingy
self._inProgress.unlock()
setProgress = set_progress
def start_main_loop(self):
"""Start the main execution loop.
This will thunk through to the contained interface object.
"""
self._interface.start_main_loop()
def get_appdir(self):
"""Return directory from which DeVIDE has been invoked.
"""
return self._appdir
def get_interface(self):
"""Return binding to the current interface.
"""
return self._interface
############################################################################
def main():
devide_app = DeVIDEApp()
devide_app.start_main_loop()
if __name__ == '__main__':
main()
| Python |
# snippet to save polydata of all selected objects to disc, transformed with
# the currently active object motion for that object. This snippet should be
# run within a slice3dVWR introspection context.
# $Id$
import os
import tempfile
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
# find all polydata objects
so = obj._tdObjects._getSelectedObjects()
polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and
pd.GetClassName() == 'vtkPolyData']
# now find their actors
objectsDict = obj._tdObjects._tdObjectsDict
actors = [objectsDict[pd]['vtkActor'] for pd in polyDatas]
# combining this with the previous statement is more effort than it's worth
names = [objectsDict[pd]['objectName'] for pd in polyDatas]
# now iterate through both, writing each transformed polydata
trfm = vtk.vtkTransform()
mtrx = vtk.vtkMatrix4x4()
trfmPd = vtk.vtkTransformPolyDataFilter()
trfmPd.SetTransform(trfm)
vtpWriter = vtk.vtkXMLPolyDataWriter()
vtpWriter.SetInput(trfmPd.GetOutput())
tempdir = tempfile.gettempdir()
for pd,actor,name in zip(polyDatas,actors,names):
actor.GetMatrix(mtrx)
trfm.Identity()
trfm.SetMatrix(mtrx)
trfmPd.SetInput(pd)
filename = os.path.join(tempdir, '%s.vtp' % (name,))
vtpWriter.SetFileName(filename)
print "Writing %s." % (filename,)
vtpWriter.Write()
else:
print "This snippet must be run from a slice3dVWR introspection window."
| Python |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
numpy_test_figure = obj.mpl_new_figure()
# this example from http://matplotlib.sourceforge.net/screenshots/log_shot.py
dt = 0.01
t = arange(dt, 20.0, dt)
subplot(211)
semilogx(t, sin(2*pi*t))
ylabel('semilog')
xticks([])
setp(gca(), 'xticklabels', [])
grid(True)
subplot(212)
loglog(t, 20*exp(-t/10.0), basey=4)
grid(True)
gca().xaxis.grid(True, which='minor') # minor grid on too
xlabel('time (s)')
ylabel('loglog')
| Python |
# EXPERIMENTAL. DO NOT USE UNLESS YOU ARE JORIK. (OR JORIS)
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
ipw = obj.sliceDirections._sliceDirectionsDict.values()[0]._ipws[0]
if ipw.GetInput():
mins, maxs = ipw.GetInput().GetScalarRange()
else:
mins, maxs = 1, 1000000
lut = vtk.vtkLookupTable()
lut.SetTableRange(mins, maxs)
lut.SetHueRange(0.1, 1.0)
lut.SetSaturationRange(1.0, 1.0)
lut.SetValueRange(1.0, 1.0)
lut.SetAlphaRange(1.0, 1.0)
lut.Build()
ipw.SetUserControlledLookupTable(1)
ipw.SetLookupTable(lut)
else:
print "You have to mark a slice3dVWR module!"
| Python |
# this snippet will rotate the camera in the slice3dVWR that you have
# selected whilst slowly increasing the isovalue of the marchingCubes that
# you have selected and dump every frame as a PNG to the temporary directory
# this is ideal for making movies of propagating surfaces in distance fields
# 1. right click on a slice3dVWR in the graphEditor
# 2. select "Mark Module" from the drop-down menu
# 3. accept "slice3dVWR" as suggestion for the mark index name
# 4. do the same for your marchingCubes (select 'marchingCubes' as index name)
# 5. execute this snippet
import os
import tempfile
import vtk
import wx
# get the slice3dVWR marked by the user
sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')
mc = devideApp.ModuleManager.getMarkedModule('marchingCubes')
if sv and mc:
# bring the window to the front
sv.view()
# make sure it actually happens
wx.Yield()
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(sv._threedRenderer.GetRenderWindow())
pngWriter = vtk.vtkPNGWriter()
pngWriter.SetInput(w2i.GetOutput())
tempdir = tempfile.gettempdir()
fprefix = os.path.join(tempdir, 'devideFrame')
camera = sv._threedRenderer.GetActiveCamera()
for i in range(160):
print i
mc._contourFilter.SetValue(0,i / 2.0)
camera.Azimuth(5)
sv.render3D()
# make sure w2i knows it's a new image
w2i.Modified()
pngWriter.SetFileName('%s%03d.png' % (fprefix, i))
pngWriter.Write()
print "The frames have been written as %s*.png." % (fprefix,)
else:
print "You have to mark a slice3dVWR module and a marchingCubes module!"
| Python |
import vtk
import wx
className = obj.__class__.__name__
if className == 'slice3dVWR':
sds = obj.sliceDirections.getSelectedSliceDirections()
if len(sds) > 0:
opacityText = wx.GetTextFromUser(
'Enter a new opacity value (0.0 to 1.0) for all selected '
'slices.')
opacity = -1.0
try:
opacity = float(opacityText)
except ValueError:
pass
if opacity < 0.0 or opacity > 1.0:
print "Invalid opacity."
else:
for sd in sds:
for ipw in sd._ipws:
prop = ipw.GetTexturePlaneProperty()
prop.SetOpacity(opacity)
else:
print "Please select the slices whose opacity you want to set."
else:
print "You have to run this from a slice3dVWR introspect window."
| Python |
# snippet to be ran in the introspection window of a slice3dVWR to
# export the whole scene as a RIB file. Before you can do this,
# both BACKGROUND_RENDERER and GRADIENT_BACKGROUND in slice3dVWR.py
# should be set to False.
obj._orientation_widget.Off()
rw = obj._threedRenderer.GetRenderWindow()
re = vtk.vtkRIBExporter()
re.SetRenderWindow(rw)
re.SetFilePrefix('/tmp/slice3dVWR')
re.Write()
| Python |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
numpy_test_figure = obj.mpl_new_figure()
a = arange(-30, 30, 0.01)
plot(a, sin(a) / a, label='sinc(x)')
plot(a, cos(a), label='cos(x)')
legend()
grid()
xlabel('x')
ylabel('f(x)')
| Python |
# link cameras of all selected slice3dVWRs
# after having run this, all selected slice3dVWRs will have linked
# cameras, so if you change the view in anyone, all will follow.
# 1. run this in the main DeVIDE introspection window after having
# selected a number of slice3dVWRs
# 2. to unlink views, type unlink_slice3dVWRs() in the bottom
# interpreter window.
def observer_istyle(s3d, s3ds):
cam = s3d._threedRenderer.GetActiveCamera()
pos = cam.GetPosition()
fp = cam.GetFocalPoint()
vu = cam.GetViewUp()
for other_s3d in s3ds:
if not other_s3d is s3d:
other_ren = other_s3d._threedRenderer
other_cam = other_ren.GetActiveCamera()
other_cam.SetPosition(pos)
other_cam.SetFocalPoint(fp)
other_cam.SetViewUp(vu)
other_ren.UpdateLightsGeometryToFollowCamera()
other_ren.ResetCameraClippingRange()
other_s3d.render3D()
def unlink_slice3dVWRs():
for s3d in s3ds:
istyle = s3d.threedFrame.threedRWI.GetInteractorStyle()
istyle.RemoveObservers('InteractionEvent') # more or less safe
iface = devide_app.get_interface()
sg = iface._graph_editor._selected_glyphs.getSelectedGlyphs()
s3ds = [i.module_instance for i in sg if i.module_instance.__class__.__name__ == 'slice3dVWR']
unlink_slice3dVWRs()
for s3d in s3ds:
ren = s3d._threedRenderer
istyle = s3d.threedFrame.threedRWI.GetInteractorStyle()
istyle.AddObserver('InteractionEvent', lambda o,e,s3d=s3d: observer_istyle(s3d,s3ds))
| Python |
# to use this code:
# 1. load into slice3dVWR introspection window
# 2. execute with ctrl-enter or File | Run current edit
# 3. in the bottom window type lm1 = get_lookmark()
# 4. do stuff
# 5. to restore lookmark, do set_lookmark(lm1)
# keep on bugging me to:
# 1. fix slice3dVWR
# 2. build this sort of functionality into the GUI
# cpbotha
def get_plane_infos():
# get out all plane orientations and normals
plane_infos = []
for sd in obj.sliceDirections._sliceDirectionsDict.values():
# each sd has at least one IPW
ipw = sd._ipws[0]
plane_infos.append((ipw.GetOrigin(), ipw.GetPoint1(), ipw.GetPoint2(), ipw.GetWindow(), ipw.GetLevel()))
return plane_infos
def set_plane_infos(plane_infos):
# go through existing sliceDirections, sync if info available
sds = obj.sliceDirections._sliceDirectionsDict.values()
for i in range(len(sds)):
sd = sds[i]
if i < len(plane_infos):
pi = plane_infos[i]
ipw = sd._ipws[0]
ipw.SetOrigin(pi[0])
ipw.SetPoint1(pi[1])
ipw.SetPoint2(pi[2])
ipw.SetWindowLevel(pi[3], pi[4], 0)
ipw.UpdatePlacement()
sd._syncAllToPrimary()
def get_camera_info():
cam = obj._threedRenderer.GetActiveCamera()
p = cam.GetPosition()
vu = cam.GetViewUp()
fp = cam.GetFocalPoint()
ps = cam.GetParallelScale()
return (p, vu, fp, ps)
def get_lookmark():
return (get_plane_infos(), get_camera_info())
def set_lookmark(lookmark):
# first setup the camera
ci = lookmark[1]
cam = obj._threedRenderer.GetActiveCamera()
cam.SetPosition(ci[0])
cam.SetViewUp(ci[1])
cam.SetFocalPoint(ci[2])
# required for parallel projection
cam.SetParallelScale(ci[3])
# also needed to adapt correctly to new camera
ren = obj._threedRenderer
ren.UpdateLightsGeometryToFollowCamera()
ren.ResetCameraClippingRange()
# now do the planes
set_plane_infos(lookmark[0])
obj.render3D()
def reset_to_default_view(view_index):
"""
@param view_index 0 for YZ, 1 for ZX, 2 for XY
"""
cam = obj._threedRenderer.GetActiveCamera()
fp = cam.GetFocalPoint()
cp = cam.GetPosition()
if view_index == 0:
cam.SetViewUp(0,1,0)
if cp[0] < fp[0]:
x = fp[0] + (fp[0] - cp[0])
else:
x = cp[0]
# safety check so we don't put cam in focal point
# (renderer gets into unusable state!)
if x == fp[0]:
x = fp[0] + 1
cam.SetPosition(x, fp[1], fp[2])
elif view_index == 1:
cam.SetViewUp(0,0,1)
if cp[1] < fp[1]:
y = fp[1] + (fp[1] - cp[1])
else:
y = cp[1]
if y == fp[1]:
y = fp[1] + 1
cam.SetPosition(fp[0], y, fp[2])
elif view_index == 2:
# then make sure it's up is the right way
cam.SetViewUp(0,1,0)
# just set the X,Y of the camera equal to the X,Y of the
# focal point.
if cp[2] < fp[2]:
z = fp[2] + (fp[2] - cp[2])
else:
z = cp[2]
if z == fp[2]:
z = fp[2] + 1
cam.SetPosition(fp[0], fp[1], z)
# first reset the camera
obj._threedRenderer.ResetCamera()
obj.render3D()
| Python |
# $Id$
# to use a shader on an actor, do this first before export:
# a = vtk.vtkRIBProperty()
# a.SetVariable('Km', 'float')
# a.SetParameter('Km', '1')
# a.SetDisplacementShader('dented')
# actor.SetProperty(a)
import os
import tempfile
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
rw = obj._threedRenderer.GetRenderWindow()
e = vtk.vtkRIBExporter()
e.SetRenderWindow(rw)
tempdir = tempfile.gettempdir()
outputfilename = os.path.join(tempdir, 'slice3dVWRscene')
e.SetFilePrefix(outputfilename)
e.SetTexturePrefix(outputfilename)
obj._orientationWidget.Off()
e.Write()
obj._orientationWidget.On()
print "Wrote file to %s.rib." % (outputfilename,)
else:
print "You have to run this from the introspection window of a slice3dVWR."
| Python |
# snippet to change the LookupTables (colourmaps) of the selected objects
# this should be run in the introspection context of a slice3dVWR
# $Id$
import os
import tempfile
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
# find all polydata objects
so = obj._tdObjects._getSelectedObjects()
polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and
pd.GetClassName() == 'vtkPolyData']
# now find their Mappers
objectsDict = obj._tdObjects._tdObjectsDict
actors = [objectsDict[pd]['vtkActor'] for pd in polyDatas]
mappers = [a.GetMapper() for a in actors]
for mapper in mappers:
lut = mapper.GetLookupTable()
lut.SetScaleToLog10()
#lut.SetScaleToLinear()
srange = mapper.GetInput().GetScalarRange()
lut.SetTableRange(srange)
lut.SetSaturationRange(1.0,1.0)
lut.SetValueRange(1.0, 1.0)
lut.SetHueRange(0.1, 1.0)
lut.Build()
else:
print "This snippet must be run from a slice3dVWR introspection window."
| Python |
# convert old-style (up to DeVIDE 8.5) to new-style DVN network files
#
# usage:
# load your old network in DeVIDE 8.5, then execute this snippet in
# the main Python introspection window. To open the main Python
# introspection window, select from the main DeVIDE menu: "Window |
# Python Shell". In the window that opens, select "File | Open file
# to current edit" from the main menu to load the file. Now select
# "File | Run current edit" to execute.
import ConfigParser
import os
import wx
# used to translate from old-style attributes to new-style
conn_trans = {
'sourceInstanceName' : 'source_instance_name',
'inputIdx' : 'input_idx',
'targetInstanceName' : 'target_instance_name',
'connectionType' : 'connection_type',
'outputIdx' : 'output_idx'
}
def save_network(pms_dict, connection_list, glyph_pos_dict, filename):
"""Given the serialised network representation as returned by
ModuleManager._serialiseNetwork, write the whole thing to disk
as a config-style DVN file.
"""
cp = ConfigParser.ConfigParser()
# create a section for each module
for pms in pms_dict.values():
sec = 'modules/%s' % (pms.instanceName,)
cp.add_section(sec)
cp.set(sec, 'module_name', pms.moduleName)
cp.set(sec, 'module_config_dict', pms.moduleConfig.__dict__)
cp.set(sec, 'glyph_position', glyph_pos_dict[pms.instanceName])
sec = 'connections'
for idx, pconn in enumerate(connection_list):
sec = 'connections/%d' % (idx,)
cp.add_section(sec)
attrs = pconn.__dict__.keys()
for a in attrs:
cp.set(sec, conn_trans[a], getattr(pconn, a))
cfp = file(filename, 'wb')
cp.write(cfp)
cfp.close()
mm = devide_app.get_module_manager()
mm.log_message('Wrote NEW-style network %s.' % (filename,))
def save_current_network():
"""Pop up file selector to ask for filename, then save new-style
network to that filename.
"""
ge = devide_app._interface._graph_editor
filename = wx.FileSelector(
"Choose filename for NEW-style DVN",
ge._last_fileselector_dir, "", "dvn",
"NEW-style DeVIDE networks (*.dvn)|*.dvn|All files (*.*)|*.*",
wx.SAVE)
if filename:
# make sure it has a dvn extension
if os.path.splitext(filename)[1] == '':
filename = '%s.dvn' % (filename,)
glyphs = ge._get_all_glyphs()
pms_dict, connection_list, glyph_pos_dict = ge._serialiseNetwork(glyphs)
save_network(pms_dict, connection_list, glyph_pos_dict,
filename)
save_current_network()
| Python |
# this is an extremely simple example of a DeVIDE snippet
# Open the Python shell (under Window in the Main Window), click on the
# "Load Snippet" button and select this file.
# it will print the directory where devide is installed and then show
# the main application help
print devideApp.get_appdir()
devideApp.showHelp()
| Python |
# this DeVIDE snippet will determine the surface area of all selected
# 3D objects in a marked slice3dVWR
# in short:
# 1. right click on a slice3dVWR in the graphEditor
# 2. select "Mark Module" from the drop-down menu
# 3. accept "slice3dVWR" as suggestion for the mark index name
# 4. execute this snippet
import vtk
# get the slice3dVWR marked by the user
sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')
if sv:
so = sv._tdObjects._getSelectedObjects()
polyDatas = [pd for pd in so if hasattr(pd, 'GetClassName') and
pd.GetClassName() == 'vtkPolyData']
tf = vtk.vtkTriangleFilter()
mp = vtk.vtkMassProperties()
mp.SetInput(tf.GetOutput())
for pd in polyDatas:
tf.SetInput(pd)
mp.Update()
print "AREA == %f" % (mp.GetSurfaceArea(),)
if len(polyDatas) == 0:
print "You haven't selected any objects for me to work with!"
else:
print "You have to mark a slice3dVWR module!"
| Python |
# $Id$
import os
import tempfile
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
rw = obj._threedRenderer.GetRenderWindow()
try:
e = vtk.vtkGL2PSExporter()
except AttributeError:
print "Your VTK was compiled without GL2PS support."
else:
e.SetRenderWindow(rw)
tempdir = tempfile.gettempdir()
outputfilename = os.path.join(tempdir, 'slice3dVWRscene')
e.SetFilePrefix(outputfilename)
e.SetSortToBSP()
e.SetDrawBackground(0)
e.SetCompress(0)
obj._orientationWidget.Off()
e.Write()
obj._orientationWidget.On()
print "Wrote file to %s." % (outputfilename,)
else:
print "You have to run this from the introspection window of a slice3dVWR."
| Python |
import vtk
className = obj.__class__.__name__
if className == 'slice3dVWR':
rw = obj.threedFrame.threedRWI.GetRenderWindow()
rw.SetStereoTypeToCrystalEyes()
#rw.SetStereoTypeToRedBlue()
rw.SetStereoRender(1)
rw.Render()
else:
print "This snippet must be run from a slice3dVWR introspection window."
| Python |
# short DeVIDE matplotlib demo.
from pylab import *
# close previous figure if it exists
try:
obj.mpl_close_figure(numpy_test_figure)
except NameError:
pass
# square figure and square axes looks better for polar plots
numpy_test_figure = obj.mpl_new_figure(figsize=(8,8))
ax = axes([0.1, 0.1, 0.8, 0.8], polar=True, axisbg='#d5de9c')
# following example from http://matplotlib.sourceforge.net/screenshots/polar_demo.py
# radar green, solid grid lines
rc('grid', color='#316931', linewidth=1, linestyle='-')
rc('xtick', labelsize=15)
rc('ytick', labelsize=15)
r = arange(0,1,0.001)
theta = 2*2*pi*r
polar(theta, r, color='#ee8d18', lw=3)
setp(ax.thetagridlabels, y=1.075) # the radius of the grid labels
title("And there was much rejoicing!", fontsize=20)
| Python |
# snippet that illustrates programmatic setting of Window/Level
# in the slice3dVWR introspection interface
W = 500
L = 1000
sds = obj.sliceDirections._sliceDirectionsDict.values()
for sd in sds:
ipw = sd._ipws[0]
ipw.SetWindowLevel(W, L, 0)
| Python |
# this snippet will rotate the camera in the slice3dVWR that you have
# selected and dump every frame as a PNG to the temporary directory
# you can modify this snippet if you want to make movies of for instance
# deforming surfaces and whatnot
# 1. right click on a slice3dVWR in the graphEditor
# 2. select "Mark Module" from the drop-down menu
# 3. accept "slice3dVWR" as suggestion for the mark index name
# 4. do the same for your superQuadric (select 'superQuadric' as index name)
# 5. execute this snippet
import os
import tempfile
import vtk
import wx
# get the slice3dVWR marked by the user
sv = devideApp.ModuleManager.getMarkedModule('slice3dVWR')
#sq = devideApp.ModuleManager.getMarkedModule('superQuadric')
if sv and sq:
# bring the window to the front
sv.view()
# make sure it actually happens
wx.Yield()
w2i = vtk.vtkWindowToImageFilter()
w2i.SetInput(sv._threedRenderer.GetRenderWindow())
pngWriter = vtk.vtkPNGWriter()
pngWriter.SetInput(w2i.GetOutput())
tempdir = tempfile.gettempdir()
fprefix = os.path.join(tempdir, 'devideFrame')
camera = sv._threedRenderer.GetActiveCamera()
for i in range(2 * 36):
sq._superquadricSource.SetPhiRoundness(i / 36.0)
camera.Azimuth(10)
sv.render3D()
# make sure w2i knows it's a new image
w2i.Modified()
pngWriter.SetFileName('%s%03d.png' % (fprefix, i))
pngWriter.Write()
print "The frames have been written as %s*.png." % (fprefix,)
else:
print "You have to mark a slice3dVWR module and a superQuadric module!"
| Python |
import vtk
import wx
def makeBorderPD(ipw):
# setup source
ps = vtk.vtkPlaneSource()
ps.SetOrigin(ipw.GetOrigin())
ps.SetPoint1(ipw.GetPoint1())
ps.SetPoint2(ipw.GetPoint2())
fe = vtk.vtkFeatureEdges()
fe.SetInput(ps.GetOutput())
tubef = vtk.vtkTubeFilter()
tubef.SetNumberOfSides(12)
tubef.SetRadius(0.5)
tubef.SetInput(fe.GetOutput())
return tubef.GetOutput()
className = obj.__class__.__name__
if className == 'slice3dVWR':
sds = obj.sliceDirections.getSelectedSliceDirections()
if len(sds) > 0:
apd = vtk.vtkAppendPolyData()
for sd in sds:
for ipw in sd._ipws:
apd.AddInput(makeBorderPD(ipw))
mapper = vtk.vtkPolyDataMapper()
mapper.ScalarVisibilityOff()
mapper.SetInput(apd.GetOutput())
actor = vtk.vtkActor()
actor.GetProperty().SetColor(0.0, 0.0, 1.0)
actor.SetMapper(mapper)
if hasattr(obj._threedRenderer, 'addBorderToSlicesActor'):
obj._threedRenderer.RemoveProp(
obj._threedRenderer.addBorderToSlicesActor)
obj._threedRenderer.AddProp(actor)
obj._threedRenderer.addBorderToSlicesActor = actor
else:
print "Please select the slices whose opacity you want to set."
else:
print "You have to run this from a slice3dVWR introspect window."
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import ConfigParser
from ConfigParser import NoOptionError
import copy
from module_kits.misc_kit.mixins import SubjectMixin
from module_manager import PickledModuleState, PickledConnection
import os
import time
import types
class NetworkManager(SubjectMixin):
"""Contains all logic to do with network handling.
This is still work in progress: code has to be refactored out of the
ModuleManager and the GraphEditor.
"""
def __init__(self, devide_app):
self._devide_app = devide_app
SubjectMixin.__init__(self)
def close(self):
SubjectMixin.close(self)
def execute_network(self, meta_modules):
"""Execute network represented by all modules in the list
meta_modules.
"""
# trigger start event so that our observers can auto-save and
# whatnot
self.notify('execute_network_start')
# convert all MetaModules to schedulerModules
sms = self._devide_app.scheduler.meta_modules_to_scheduler_modules(
meta_modules)
print "STARTING network execute ----------------------------"
print time.ctime()
self._devide_app.scheduler.execute_modules(sms)
self._devide_app.set_progress(100.0, 'Network execution complete.')
print "ENDING network execute ------------------------------"
def load_network_DEPRECATED(self, filename):
"""Given a filename, read it as a DVN file and return a tuple with
(pmsDict, connectionList, glyphPosDict) if successful. If not
successful, an exception will be raised.
"""
f = None
try:
# load the fileData
f = open(filename, 'rb')
fileData = f.read()
except Exception, e:
if f:
f.close()
raise RuntimeError, 'Could not load network from %s:\n%s' % \
(filename,str(e))
f.close()
try:
(headerTuple, dataTuple) = cPickle.loads(fileData)
magic, major, minor, patch = headerTuple
pmsDict, connectionList, glyphPosDict = dataTuple
except Exception, e:
raise RuntimeError, 'Could not interpret network from %s:\n%s' % \
(filename,str(e))
if magic != 'DVN' and magic != 'D3N' or (major,minor,patch) != (1,0,0):
raise RuntimeError, '%s is not a valid DeVIDE network file.' % \
(filename,)
return (pmsDict, connectionList, glyphPosDict)
def load_network(self, filename):
"""Given a filename, read it as a DVN file and return a tuple with
(pmsDict, connectionList, glyphPosDict) if successful. If not
successful, an exception will be raised.
All occurrences of %(dvn_dir)s will be expanded to the
directory that the DVN file is being loaded from.
"""
# need this for substitution during reading of
# module_config_dict
dvn_dir = os.path.dirname(filename)
cp = ConfigParser.ConfigParser({'dvn_dir' : dvn_dir})
try:
# load the fileData
cfp = open(filename, 'rb')
except Exception, e:
raise RuntimeError, 'Could not open network file %s:\n%s' % \
(filename,str(e))
try:
cp.readfp(cfp)
except Exception, e:
raise RuntimeError, 'Could not load network from %s:\n%s' % \
(filename,str(e))
finally:
cfp.close()
pms_dict = {}
connection_list = []
glyph_pos_dict = {}
sections = cp.sections()
# we use this dictionary to determine which ConfigParser get
# method to use for the specific connection attribute.
conn_attrs = {
'source_instance_name' : 'get',
'output_idx' : 'getint',
'target_instance_name' : 'get',
'input_idx' : 'getint',
'connection_type' : 'getint'
}
for sec in sections:
if sec.startswith('modules/'):
pms = PickledModuleState()
pms.instance_name = sec.split('/')[-1]
try:
pms.module_name = cp.get(sec, 'module_name')
except NoOptionError:
# there's no module name, so we're ignoring this
# section
continue
try:
mcd = cp.get(sec, 'module_config_dict')
except NoOptionError:
# no config in DVN file, pms will have default
# module_config
pass
else:
# we have to use this relatively safe eval trick to
# unpack and interpret the dict
cd = eval(mcd,
{"__builtins__": {},
'True' : True, 'False' : False})
pms.module_config.__dict__.update(cd)
# store in main pms dict
pms_dict[pms.instance_name] = pms
try:
# same eval trick to get out the glyph position
gp = eval(cp.get(sec, 'glyph_position'),
{"__builtins__": {}})
except NoOptionError:
# no glyph_pos, so we assign it the default origin
gp = (0,0)
glyph_pos_dict[pms.instance_name] = gp
elif sec.startswith('connections/'):
pc = PickledConnection()
for a, getter in conn_attrs.items():
get_method = getattr(cp, getter)
try:
setattr(pc, a, get_method(sec, a))
except NoOptionError:
# if an option is missing, we discard the
# whole connection
break
else:
# this else clause is only entered if the for loop
# above was NOT broken out of, i.e. we only store
# valid connections
connection_list.append(pc)
return pms_dict, connection_list, glyph_pos_dict
def realise_network(self, pms_dict, connection_list):
"""Given pms_dict and connection_list as returned by load_network,
realise the given network and return the realised new_modules_dict and
new_connections.
@TODO: move network-related code from mm.deserialise_module_instances
here.
"""
mm = self._devide_app.get_module_manager()
new_modules_dict, new_connections = mm.deserialise_module_instances(
pms_dict, connection_list)
return new_modules_dict, new_connections
def _transform_relative_paths(self, module_config_dict, dvn_dir):
"""Given a module_config_dict and the directory that a DVN is
being saved to, transform all values of which the keys contain
'filename' or 'file_name' so that:
* if the value is a directory somewhere under the dvn_dir,
replace the dvn_dir part with %(dvn_dir)s
* if the value is a list of directories, do the substitution
for each element.
"""
def transform_single_path(p):
p = os.path.abspath(p)
if p.find(dvn_dir) == 0:
# do the modification in the copy.
# (probably not necessary to be this
# careful)
p = p.replace(dvn_dir, '%(dvn_dir)s')
p = p.replace('\\', '/')
return p
# make a copy, we don't want to modify what the user
# gave us.
new_mcd = copy.deepcopy(module_config_dict)
# then we iterate through the original
for k in module_config_dict:
if k.find('filename') >= 0 or \
k.find('file_name') >= 0:
v = module_config_dict[k]
if type(v) in [
types.StringType,
types.UnicodeType]:
new_mcd[k] = transform_single_path(v)
elif type(v) == types.ListType:
# it's a list, so try to transform every element
# copy everything into a new list new_v
new_v = v[:]
for i,p in enumerate(v):
if type(p) in [
types.StringType,
types.UnicodeType]:
new_v[i] = transform_single_path(p)
new_mcd[k] = new_v
return new_mcd
def save_network(self, pms_dict, connection_list, glyph_pos_dict,
filename, export=False):
"""Given the serialised network representation as returned by
ModuleManager._serialise_network, write the whole thing to disk
as a config-style DVN file.
@param export: If True, will transform all filenames that are
below the network directory to relative pathnames. These will
be expanded (relative to the loaded network) at load-time.
"""
cp = ConfigParser.ConfigParser()
# general section with network configuration
sec = 'general'
cp.add_section(sec)
cp.set(sec, 'export', export)
if export:
# convert all stored filenames, if they are below the
# network directory, to relative pathnames with
# substitutions: $(dvn_dir)s/the/rest/somefile.txt
# on ConfigParser.read we'll supply the NEW dvn_dir
dvn_dir = os.path.abspath(os.path.dirname(filename))
# create a section for each module
for pms in pms_dict.values():
sec = 'modules/%s' % (pms.instance_name,)
cp.add_section(sec)
cp.set(sec, 'module_name', pms.module_name)
if export:
mcd = self._transform_relative_paths(
pms.module_config.__dict__, dvn_dir)
else:
# no export, so we don't have to transform anything
mcd = pms.module_config.__dict__
cp.set(sec, 'module_config_dict', mcd)
cp.set(sec, 'glyph_position', glyph_pos_dict[pms.instance_name])
for idx, pconn in enumerate(connection_list):
sec = 'connections/%d' % (idx,)
cp.add_section(sec)
attrs = pconn.__dict__.keys()
for a in attrs:
cp.set(sec, a, getattr(pconn, a))
cfp = file(filename, 'wb')
cp.write(cfp)
cfp.close()
def clear_network(self):
"""Remove/close complete network.
This method is only called during the non-view mode of operation by
the scripting interface for example.
"""
mm = self._devide_app.get_module_manager()
mm.delete_all_modules()
| Python |
# python rules. severely.
# (c) 2007 cpbotha
import glob
import sys
import os
import shutil
import zipfile
def main():
cwd = os.path.abspath(os.curdir)
hhp_dir = os.path.join(cwd, 'devidehelp_tmphhp')
os.chdir(hhp_dir)
htb_list = glob.glob('*.html') + \
glob.glob('*.png') + \
glob.glob('devide.hh?') + \
['CSHelp.txt']
zf = zipfile.ZipFile('../../devide.htb', 'w', zipfile.ZIP_DEFLATED)
for fn in htb_list:
zf.write(fn)
zf.close()
# also copy the CHM file for the windows people.
shutil.copy('devide.chm', '../../')
if __name__ == '__main__':
main()
| Python |
# example driver script for offline / command-line processing with DeVIDE
# the following variables are magically set in this script:
# interface - instance of ScriptInterface, with the following calls:
# meta_modules = load_and_realise_network()
# execute_network(self, meta_modules)
# clear_network(self)
# instance = get_module_instance(self, module_name)
# config = get_module_config(self, module_name)
# set_module_config(self, module_name, config)
# See devide/interfaces/simple_api_mixin.py for details.
# start the script with:
# dre devide --interface script --script example_offline_driver.py --script-params 0.0,100.0
def main():
# script_params is everything that gets passed on the DeVIDE
# commandline after --script-params
# first get the two strings split by a comma
l,u = script_params.split(',')
# then cast to float
LOWER = float(l)
UPPER = float(u)
print "offline_driver.py starting"
# load the DVN that you prepared
# load_and_realise_network returns module dictionary + connections
mdict,conn = interface.load_and_realise_network(
'BatchModeWithoutUI-ex.dvn')
# parameter is the module name that you assigned in DeVIDE
# using right-click on the module, then "Rename"
thresh_conf = interface.get_module_config('threshold')
# what's returned is module_instance._config (try this in the
# devide module introspection interface by introspecting "Module
# (self)" and then typing "dir(obj._config)"
thresh_conf.lowerThreshold = LOWER
thresh_conf.upperThreshold = UPPER
# set module config back again
interface.set_module_config('threshold', thresh_conf)
# get, change and set writer config to change filename
writer_conf = interface.get_module_config('vtp_wrt')
writer_conf.filename = 'result_%s-%s.vtp' % (str(LOWER),str(UPPER))
interface.set_module_config('vtp_wrt', writer_conf)
# run the network
interface.execute_network(mdict.values())
print "offline_driver.py done."
main()
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import counter
class MetaModule:
"""Class used to store module-related information.
Every instance is contained in a single MetaModule. This is why the
cycle-proof module split has not been implemented as MetaModules.
@todo: at the moment, some interfaces work with a real module instance
as well as a MetaModule. Should be consistent and use all MetaModules.
@todo: document all timestamp logic here, link to scheduler
documentation
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, instance, instance_name, module_name,
partsToInputs=None, partsToOutputs=None):
"""Instance is the actual class instance and instance_name is a unique
name that has been chosen by the user or automatically.
@param module_name: the full spec of the module of which the instance
is encapsulated by this meta_module, for example
modules.filters.blaat. One could also get at this with
instance.__class__.__module__, but that relies on the convention that
the name of the module and contained class is the same.
"""
if instance is None:
raise Exception(
'instance is None during MetaModule instantiation.')
self.instance = instance
self.instance_name = instance_name
self.module_name = module_name
# init blocked ivar
self.blocked = False
# determine number of module parts based on parts to indices mappings
maxPart = 0
if not partsToInputs is None:
maxPart = max(partsToInputs.keys())
if not partsToOutputs is None:
max2 = max(partsToOutputs.keys())
maxPart = max(maxPart, max2)
self.numParts = maxPart + 1
# number of parts has been determined ###############################
# time when module was last brought up to date
# default to 0.0; that will guarantee an initial execution
self.execute_times = self.numParts * [0]
# we use this to record all the times the hybrid scheduler
# touches a streaming module but does not call its
# streaming_execute (because it's NOT terminating)
# this is necessary for the transfer output caching to work;
# we compare touch time to output transfer time
self.streaming_touch_times = self.numParts * [0]
# time when module was last invalidated (through parameter changes)
# default is current time. Along with 0.0 executeTime, this will
# guarantee initial execution.
self.modifiedTimes = self.numParts * [counter.counter()]
# derive partsTo dictionaries #######################################
self._inputsToParts = {}
if not partsToInputs is None:
for part, inputs in partsToInputs.items():
for inp in inputs:
self._inputsToParts[inp] = part
self._outputsToParts = {}
if not partsToOutputs is None:
for part, outputs in partsToOutputs.items():
for outp in outputs:
self._outputsToParts[outp] = part
# partsTo dicts derived ############################################
# to the time when data was last transferred from the encapsulated
# instance through this path
self.transferTimes = {}
# dict containing timestamps when last transfer was done from
# the encapsulated module to each of its consumer connections
self.streaming_transfer_times = {}
# this will create self.inputs, self.outputs
self.reset_inputsOutputs()
def close(self):
del self.instance
del self.inputs
del self.outputs
def view_to_config(self):
"""Wrapper method that transfers info from the module view to its
config data structure. The method also takes care of updating the
modified time if necessary.
"""
res = self.instance.view_to_config()
if res is None or res:
must_modify = True
else:
must_modify = False
if must_modify:
for part in range(self.numParts):
self.modify(part)
def config_to_logic(self):
"""Wrapper method that transfers info from the module config to its
underlying logic. The method also takes care of updating the
modified time if necessary.
"""
res = self.instance.config_to_logic()
if res is None or res:
must_modify = True
else:
must_modify = False
if must_modify:
for part in range(self.numParts):
self.modify(part)
def applyViewToLogic_DEPRECATED(self):
"""Transfer information from module view to its underlying logic
(model) and all the way back up.
The reason for the two-way transfer is so that other logic-linked
view variables get the opportunity to update themselves. This method
will also take care of adapting the modifiedTime.
At the moment this is only called by the event handlers for the
standard ECASH interface devices.
"""
vtc_res = self.instance.view_to_config()
ctl_res = self.instance.config_to_logic()
mustModify = True
if vtc_res is None and ctl_res is None:
# this is an old-style module, we assume that it's made changes
mustModify = True
elif not vtc_res and not ctl_res:
# this means both are false, i.e. NO changes were made to
# the config and no changes were made to the logic... this
# means we need not modify
mustModify = False
else:
# all other cases (for a new style module) means we have to mod
mustModify = True
if mustModify:
# set modified time to now
for part in range(self.numParts):
self.modify(part)
self.instance.logic_to_config()
self.instance.config_to_view()
def findConsumerInOutputConnections(
self, output_idx, consumerInstance, consumerInputIdx=-1):
"""Find the given consumer module and its input index in the
list for the given output index.
@param consumerInputIdx: input index on consumer module. If this is
-1, the code will only check for the correct consumerInstance and
will return the first occurrence.
@return: index of given instance if found, -1 otherwise.
"""
ol = self.outputs[output_idx]
found = False
for i in range(len(ol)):
ci, cii = ol[i]
if ci == consumerInstance and \
(consumerInputIdx == -1 or cii == consumerInputIdx):
found = True
break
#import pdb
#pdb.set_trace()
if found:
return i
else:
return -1
def getPartForInput(self, input_idx):
"""Return module part that takes input input_idx.
"""
if self.numParts > 1:
return self._inputsToParts[input_idx]
else:
return 0
def getPartForOutput(self, output_idx):
"""Return module part that produces output output_idx.
"""
if self.numParts > 1:
return self._outputsToParts[output_idx]
else:
return 0
def connectInput(self, input_idx, producerModule, producerOutputIdx):
"""Record connection on the specified input_idx.
This is one half of recording a complete connection: the supplier
module should also record the connection of this consumer.
@raise Exception: if input is already connected.
@return: Nothing.
"""
# check that the given input is not already connected
if self.inputs[input_idx] is not None:
raise Exception, \
"%d'th input of module %s already connected." % \
(input_idx, self.instance.__class__.__name__)
# record the input connection
self.inputs[input_idx] = (producerModule, producerOutputIdx)
def disconnectInput(self, input_idx):
"""Record disconnection on the given input of the encapsulated
instance.
@return: Nothing.
"""
# if this is a new disconnect, we have to register that the
# module is now modified. For connected data transfers, this
# is done by the scheduler during network execution (when the
# data is actually transferred), but for disconnects, we have
# to modify the module immediately.
if not self.inputs[input_idx] is None:
part = self.getPartForInput(input_idx)
self.modify(part)
self.inputs[input_idx] = None
def connectOutput(self, output_idx, consumerInstance, consumerInputIdx):
"""Record connection on the given output of the encapsulated module.
@return: True if connection recorded, False if not (for example if
connection already exists)
"""
if self.findConsumerInOutputConnections(
output_idx, consumerInstance, consumerInputIdx) >= 0:
# this connection has already been made, bail.
return
# do the connection
ol = self.outputs[output_idx]
ol.append((consumerInstance, consumerInputIdx))
# this is a new connection, so set the transfer times to 0
self.transferTimes[
(output_idx, consumerInstance, consumerInputIdx)] = 0
# also reset streaming transfers
self.streaming_transfer_times[
(output_idx, consumerInstance, consumerInputIdx)] = 0
def disconnectOutput(self, output_idx, consumerInstance, consumerInputIdx):
"""Record disconnection on the given output of the encapsulated module.
"""
# find index of the given consumerInstance and consumerInputIdx
# in the list of consumers connected to producer port output_idx
cidx = self.findConsumerInOutputConnections(
output_idx, consumerInstance, consumerInputIdx)
# if this is a valid index, nuke it
if cidx >= 0:
ol = self.outputs[output_idx]
del ol[cidx]
# also remove the relevant slot from our transferTimes
del self.transferTimes[
(output_idx, consumerInstance, consumerInputIdx)]
del self.streaming_transfer_times[
(output_idx, consumerInstance, consumerInputIdx)]
else:
# consumer not found, the connection didn't exist
raise Exception, \
"Attempt to disconnect output which isn't connected."
def reset_inputsOutputs(self):
numIns = len(self.instance.get_input_descriptions())
numOuts = len(self.instance.get_output_descriptions())
# numIns list of tuples of (supplierModule, supplierOutputIdx)
# if the input is not connected, that position in the list is None
# supplierModule is a module instance, not a MetaModule
self.inputs = [None] * numIns
# numOuts list of lists of tuples of (consumerModule,
# consumerInputIdx); consumerModule is an instance, not a MetaModule
# be careful with list concatenation, it makes copies, which are mostly
# shallow!!!
self.outputs = [[] for _ in range(numOuts)]
def streaming_touch_timestamp_module(self, part=0):
"""
@todo: should change the name of this timestamp.
"""
self.streaming_touch_times[part] = counter.counter()
print "streaming touch stamped:", self.streaming_touch_times[part]
def execute_module(self, part=0, streaming=False):
"""Used by ModuleManager to execute module.
This method also takes care of timestamping the execution time if
execution was successful.
"""
if self.instance:
# this is the actual user function.
# if something goes wrong, an exception will be thrown and
# correctly handled by the invoking module manager
if streaming:
if part == 0:
self.instance.streaming_execute_module()
else:
self.instance.streaming_execute_module(part)
self.execute_times[part] = counter.counter()
print "streaming exec stamped:", self.execute_times[part]
else:
if part == 0:
self.instance.execute_module()
else:
self.instance.execute_module(part)
# if we get here, everything is okay and we can record
# the execution time of this part
self.execute_times[part] = counter.counter()
print "exec stamped:", self.execute_times[part]
def modify(self, part=0):
"""Used by the ModuleManager to timestamp the modified time.
This should be called whenever module state has changed in such a way
as to invalidate the current state of the module. At the moment,
this is called by L{applyViewToLogic()} as well as by the
ModuleManager.
@param part: indicates the part that has to be modified.
"""
self.modifiedTimes[part] = counter.counter()
def shouldExecute(self, part=0):
"""Determine whether the encapsulated module needs to be executed.
"""
print "?? mod > exec? :", self.modifiedTimes[part], self.execute_times[part]
return self.modifiedTimes[part] > self.execute_times[part]
def should_touch(self, part=0):
print "?? mod > touch? :", self.modifiedTimes[part], self.streaming_touch_times[part]
return self.modifiedTimes[part] > self.streaming_touch_times[part]
def should_transfer_output(
self, output_idx, consumer_meta_module, consumer_input_idx,
streaming=False):
"""Determine whether output should be transferred through
the given output index to the input index on the given consumer
module.
If the transferTime is older than executeTime, we should
transfer to our consumer. This means that if we (the producer
module) have executed after the previous transfer, we should
transfer again. When a new consumer module is connected to
us, transfer time is set to 0, so it will always get a
transfer initially. Semantics with viewer modules (internal
division into source and sink modules by the scheduler) are
taken care of by the scheduler.
@param output_idx: index of output of this module through which
output would be transferred
@param consumer_meta_module: the META MODULE associated with the
consumer that's connected to us.
@param consumer_input_idx: the input connection on the consumer
module that we want to transfer to
@param streaming: indicates whether this is to be a streaming
transfer. If so, a different transfer timestamp is used.
"""
consumer_instance = consumer_meta_module.instance
# first double check that we're actually connected on this output
# to the given consumerModule
if self.findConsumerInOutputConnections(
output_idx, consumer_instance, consumer_input_idx) >= 0:
consumerFound = True
else:
consumerFound = False
if consumerFound:
# determine which part is responsible for this output
part = self.getPartForOutput(output_idx)
if streaming:
tTime = self.streaming_transfer_times[
(output_idx, consumer_instance, consumer_input_idx)]
# note that we compare with the touch time, and not
# the execute time, since only the terminating module
# is actually executed.
print "?? streaming transfer? ttime ", tTime, "< touchtime", self.streaming_touch_times[part]
should_transfer = bool(tTime <
self.streaming_touch_times[part])
else:
tTime = self.transferTimes[
(output_idx, consumer_instance, consumer_input_idx)]
print "?? transfer? ttime ", tTime, "< executetime", self.execute_times[part]
should_transfer = bool(tTime < self.execute_times[part])
return should_transfer
else:
return False
def timeStampTransferTime(
self, outputIndex, consumerInstance, consumerInputIdx,
streaming=False):
"""Timestamp given transfer time with current time.
This method is called right after a successful transfer has
been made. Depending on the scheduling mode (event-driven or
hybrid) and whether it's a streaming module that's being
transferred to, the timestamps are set differently to make
sure that after a switch between modes, all transfers are
redone. Please see the documentation in the scheduler module.
@param streaming: determines whether a streaming transfer or a
normal transfer has just occurred.
"""
if streaming:
streaming_transfer_time = counter.counter()
transfer_time = 0
else:
transfer_time = counter.counter()
streaming_transfer_time = 0
# and set the timestamp
self.transferTimes[
(outputIndex, consumerInstance, consumerInputIdx)] = \
transfer_time
self.streaming_transfer_times[
(outputIndex, consumerInstance, consumerInputIdx)] = \
streaming_transfer_time
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""
"""
import mutex
#########################################################################
class SchedulerException(Exception):
pass
class CyclesDetectedException(SchedulerException):
pass
#########################################################################
class SchedulerModuleWrapper:
"""Wrapper class that adapts module instance to scheduler-usable
object.
We can use this to handle exceptions, such as the viewer
split. Module instances are wrapped on an ad hoc basis, so you CAN'T
use equality testing or 'in' tests to check for matches. Use the
L{matches} method.
@ivar instance: the module instance, e.g. instance of child of ModuleBase
@ivar input_independent_part: part of module that is not input dependent,
e.g. in the case of purely interaction-dependent outputs
@ivar input_independent_outputs: list of outputs that are input-dependent.
This has to be set for both dependent and independent parts of a module.
@todo: functionality in this class has been reduced to such an
extent that we should throw it OUT in favour of just working with
(meta_module, part) tuples. These we CAN use for hashing and
equality tests.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, meta_module, part):
self.meta_module = meta_module
self.part = part
def matches(self, otherModule):
"""Checks if two schedulerModules are equivalent.
Module instances are wrapped with this class on an ad hoc basis,
so you can not check for equivalency with the equality or 'in'
operators for example. Use this method instead.
@param otherModule: module with which equivalency should be tested.
@return: True if equivalent, False otherwise.
"""
eq = self.meta_module == otherModule.meta_module and \
self.part == otherModule.part
return eq
#########################################################################
class Scheduler:
"""Coordinates event-driven network execution.
DeVIDE currently supports two main scheduling modes: event-driven
and demand-driven. [1] contains a concise overview of the
scheduling approach, but we'll go into some more detail in this
in-code documentation.
Event-driven scheduling:
This is the default scheduling mode - the network is analysed and
all modules are iterated through in topological order. For each
module, its inputs are transferred from its producer modules if
necessary (i.e. a producer module has been executed since the
previous transfer, or this (consumer) module has been newly
connected (in which case the producer module's output t-time to
this module is set to 0)). All transfers are timestamped. In
event-driven mode, after every transfer, the streaming transfer
timestamp for that connection is set to 0 so that subsequent
hybrid scheduling runs will re-transfer all relevant data. If the
module has been modified, or inputs have been transferred to it
(in which case it is also explicitly modified), its
execute_module() method is then called.
Hybrid scheduling:
This mode of scheduling has to be explicitly invoked by the user.
All modules with a streaming_execute_module() are considered
streamable. The largest subsets of streamable modules are found
(see [1] for details on this algorithm). All modules are iterated
through in topological order and execution continues as for
event-driven scheduling, except when a streamable module is
encountered. In that case, we use a different set of
streaming_transfer_times to check whether we should transfer its
producers' output data pointers (WITHOUT disconnect workaround).
In every case that we do a transfer, the usual transfer timestamps
are set to 0 so that any subsequent event-driven scheduling will
re-transfer. For each re-transfer, the module will be modified,
thus also causing a re-execute when we change to event-driven mode.
Only if the current streamable module is at one of the end points
of the streamable subset and its execute_timestamp is
older than the normal modification time-stamp, is its
streaming_execute_module() method called and the
streaming_execute_timestamp touched.
Timestamps:
There are four collections of timestamps:
1. per module modified_time (initvalue 0)
2. per module execute_time (initvalue 0)
3. per output connection transfer_time
4. per module streaming touch time (initvalue 0)
When a module's configuration is changed by the user (the user
somehow interacts with the module), the module's modified_time is
set to current_time.
When a module execution is scheduled:
* For each supplying connection, the data is transferred if
transfer_time(connection) < execute_time(producer_module), or in
the hybrid case, if transfer_time(connection) <
touch_time(producer_module)
* If data is transferred to a module, that module's modified_time
is set to current_time.
* The module is then executed if modified_time > execute_time.
* If the module is executed, execute_time is set to current_time.
Notes:
* there are two sets of transfer_time timestamps,
one set each for event-driven and hybrid
* there is only ONE set of modified times and of execute_times
* See the timestamp description above, as well as the descriptions
for hybrid and event-driven to see how the scheduler makes sure
that switching between execution models automatically results in
re-execution of modules that are adaptively scheduled.
* in the case that illegal cycles are found, network execution is
aborted.
[1] C.P. Botha and F.H. Post, "Hybrid Scheduling in the DeVIDE
Dataflow Visualisation Environment", accepted for SimVis 2008
This should be a singleton, as we're using a mutex to protect per-
process network execution.
@author: Charl P. Botha <http://cpbotha.net/>
"""
_execute_mutex = mutex.mutex()
def __init__(self, devideApp):
"""Initialise scheduler instance.
@param devideApp: an instance of the devideApplication that we'll use
to communicate with the outside world.
"""
self._devideApp = devideApp
def meta_modules_to_scheduler_modules(self, meta_modules):
"""Preprocess module instance list before cycle detection or
topological sorting to take care of exceptions.
Note that the modules are wrapped anew by this method, so equality
tests with previously existing scheduleModules will not work. You have
to use the L{SchedulerModuleWrapper.matches()} method.
@param module_instances: list of raw module instances
@return: list with SchedulerModuleWrappers
"""
# replace every view module with two segments: final and initial
SchedulerModuleWrappers = []
for mModule in meta_modules:
# wrap every part separately
for part in range(mModule.numParts):
SchedulerModuleWrappers.append(
SchedulerModuleWrapper(mModule, part))
return SchedulerModuleWrappers
def getConsumerModules(self, schedulerModule):
"""Return consumers of schedulerModule as a list of schedulerModules.
The consumers that are returned have been wrapped on an ad hoc basis,
so you can't trust normal equality or 'in' tests. Use the
L{SchedulerModuleWrapper.matches} method instead.
@param schedulerModule: determine modules that are connected to outputs
of this instance.
@param part: Only return modules that are dependent on this part.
@return: list of consumer schedulerModules, ad hoc wrappings.
"""
# get the producer meta module
p_meta_module = schedulerModule.meta_module
# only consumers that are dependent on p_part are relevant
p_part = schedulerModule.part
# consumers is a list of (output_idx, consumerMetaModule,
# consumerInputIdx) tuples
mm = self._devideApp.get_module_manager()
consumers = mm.get_consumers(p_meta_module)
sConsumers = []
for output_idx, consumerMetaModule, consumerInputIdx in consumers:
if p_meta_module.getPartForOutput(output_idx) == p_part:
# now see which part of the consumerMetaModule is dependent
cPart = consumerMetaModule.getPartForInput(consumerInputIdx)
sConsumers.append(
SchedulerModuleWrapper(consumerMetaModule, cPart))
return sConsumers
def getProducerModules(self, schedulerModule):
"""Return producer modules and indices that supply schedulerModule
with data.
The producers that are returned have been wrapped on an ad hoc basis,
so you can't trust normal equality or 'in' tests. Use the
L{SchedulerModuleWrapper.matches} method instead.
@param schedulerModule: determine modules that are connected to inputs
of this instance.
@return: list of tuples with (producer schedulerModule, output
index, consumer input index).
"""
# get the consumer meta module
c_meta_module = schedulerModule.meta_module
# only producers that supply this part are relevant
c_part = schedulerModule.part
# producers is a list of (producerMetaModule, output_idx, input_idx)
# tuples
mm = self._devideApp.get_module_manager()
producers = mm.get_producers(c_meta_module)
sProducers = []
for p_meta_module, outputIndex, consumerInputIdx in producers:
if c_meta_module.getPartForInput(consumerInputIdx) == c_part:
# find part of producer meta module that is actually
# producing for schedulerModule
p_part = p_meta_module.getPartForOutput(outputIndex)
sProducers.append(
(SchedulerModuleWrapper(p_meta_module, p_part),
outputIndex, consumerInputIdx))
return sProducers
def detectCycles(self, schedulerModules):
"""Given a list of moduleWrappers, detect cycles in the topology
of the modules.
@param schedulerModules: list of module instances that has to be
checked.
@return: True if cycles detected, False otherwise.
@todo: check should really be limited to modules in selection.
"""
def detectCycleMatch(visited, currentModule):
"""Recursive function used to check for cycles in the module
network starting from initial module currentModule.
@param visited: list of schedulerModules used during recursion.
@param currentModule: initial schedulerModule
@return: True if cycle detected starting from currentModule
"""
consumers = self.getConsumerModules(currentModule)
for consumer in consumers:
for v in visited:
if consumer.matches(v):
return True
else:
# we need to make a copy of visited and send it along
# if we don't, changes to visit are shared between
# different branches of the recursion; we only want
# it to aggregate per recursion branch
visited_copy = {}
visited_copy.update(visited)
visited_copy[consumer] = 1
if detectCycleMatch(visited_copy, consumer):
return True
# the recursion ends when there are no consumers and
return False
for schedulerModule in schedulerModules:
if detectCycleMatch({schedulerModule : 1},
schedulerModule):
return True
return False
def topoSort(self, schedulerModules):
"""Perform topological sort on list of modules.
Given a list of module instances, this will perform a
topological sort that can be used to determine the execution
order of the give modules. The modules are checked beforehand
for cycles. If any cycles are found, an exception is raised.
@param schedulerModules: list of module instance to be sorted
@return: modules in topological order; in this case the instances DO
match the input instances.
@todo: separate topologically independent trees
"""
def isFinalVertex(schedulerModule, currentList):
"""Determines whether schedulerModule is a final vertex relative
to the currentList.
A final vertex is a vertex/module with no consumers in the
currentList.
@param schedulerModule: module whose finalness is determined
@param currentList: list relative to which the finalness is
determined.
@return: True if final, False if not.
"""
# find consumers
consumers = self.getConsumerModules(schedulerModule)
# now check if any one of these consumers is present in currentList
for consumer in consumers:
for cm in currentList:
if consumer.matches(cm):
return False
return True
if self.detectCycles(schedulerModules):
raise CyclesDetectedException(
'Cycles detected in network. Unable to schedule.')
# keep on finding final vertices, move to final list
scheduleList = [] # this will be the actual schedules list
tempList = schedulerModules[:] # copy of list so we can futz around
while tempList:
finalVertices = [sm for sm in tempList
if isFinalVertex(sm, tempList)]
scheduleList.extend(finalVertices)
for fv in finalVertices:
tempList.remove(fv)
scheduleList.reverse()
return scheduleList
def execute_modules(self, schedulerModules):
"""Execute the modules in schedulerModules in topological order.
For each module, all output is transferred from its consumers and then
it's executed. I'm still thinking about the implications of doing
this the other way round, i.e. each module is executed and its output
is transferred.
Called by SchedulerProxy.execute_modules().
@param schedulerModules: list of modules that should be executed in
order.
@raise CyclesDetectedException: This exception is raised if any
cycles are detected in the modules that have to be executed.
@todo: add start_module parameter, execution skips all modules before
this module in the topologically sorted execution list.
"""
# stop concurrent calls of execute_modules.
if not Scheduler._execute_mutex.testandset():
return
# first remove all blocked modules from the list, before we do any
# kind of analysis.
blocked_module_indices = []
for i in range(len(schedulerModules)):
if schedulerModules[i].meta_module.blocked:
blocked_module_indices.append(i)
blocked_module_indices.reverse()
for i in blocked_module_indices:
del(schedulerModules[i])
# finally start with execution.
try:
if self.detectCycles(schedulerModules):
raise CyclesDetectedException(
'Cycles detected in selected network modules. '
'Unable to execute.')
# this will also check for cycles...
schedList = self.topoSort(schedulerModules)
mm = self._devideApp.get_module_manager()
for sm in schedList:
print "### sched:", sm.meta_module.instance.__class__.__name__
# find all producer modules
producers = self.getProducerModules(sm)
# transfer relevant data
for pmodule, output_index, input_index in producers:
if mm.should_transfer_output(
pmodule.meta_module, output_index,
sm.meta_module, input_index):
print 'transferring output: %s:%d to %s:%d' % \
(pmodule.meta_module.instance.__class__.__name__,
output_index,
sm.meta_module.instance.__class__.__name__,
input_index)
mm.transfer_output(pmodule.meta_module, output_index,
sm.meta_module, input_index)
# finally: execute module if
# ModuleManager thinks it's necessary
if mm.should_execute_module(sm.meta_module, sm.part):
print 'executing part %d of %s' % \
(sm.part, sm.meta_module.instance.__class__.__name__)
mm.execute_module(sm.meta_module, sm.part)
finally:
# in whichever way execution terminates, we have to unlock the
# mutex.
Scheduler._execute_mutex.unlock()
#########################################################################
class EventDrivenScheduler(Scheduler):
pass
#########################################################################
class HybridScheduler(Scheduler):
def execute_modules(self, schedulerModules):
"""Execute the modules in schedulerModules according to hybrid
scheduling strategy. See documentation in Scheduler class and
the paper [1] for a complete description.
@param schedulerModules: list of modules that should be executed in
order.
@raise CyclesDetectedException: This exception is raised if any
cycles are detected in the modules that have to be executed.
@todo: add start_module parameter, execution skips all modules before
this module in the topologically sorted execution list.
"""
# stop concurrent calls of execute_modules.
if not Scheduler._execute_mutex.testandset():
return
# first remove all blocked modules from the list, before we do any
# kind of analysis.
blocked_module_indices = []
for i in range(len(schedulerModules)):
if schedulerModules[i].meta_module.blocked:
blocked_module_indices.append(i)
blocked_module_indices.reverse()
for i in blocked_module_indices:
del(schedulerModules[i])
# finally start with execution.
try:
if self.detectCycles(schedulerModules):
raise CyclesDetectedException(
'Cycles detected in selected network modules. '
'Unable to execute.')
# this will also check for cycles...
schedList = self.topoSort(schedulerModules)
mm = self._devideApp.get_module_manager()
# find largest streamable subsets
streamables_dict, streamable_subsets = \
self.find_streamable_subsets(schedulerModules)
for sm in schedList:
smt = (sm.meta_module, sm.part)
if smt in streamables_dict:
streaming_module = True
print "### streaming ",
else:
streaming_module = False
print "### ",
print "sched:", sm.meta_module.instance.__class__.__name__
# find all producer modules
producers = self.getProducerModules(sm)
# transfer relevant data
for pmodule, output_index, input_index in producers:
pmt = (pmodule.meta_module, pmodule.part)
if streaming_module and pmt in streamables_dict:
streaming_transfer = True
else:
streaming_transfer = False
if mm.should_transfer_output(
pmodule.meta_module, output_index,
sm.meta_module, input_index,
streaming_transfer):
if streaming_transfer:
print 'streaming ',
print 'transferring output: %s:%d to %s:%d' % \
(pmodule.meta_module.instance.__class__.__name__,
output_index,
sm.meta_module.instance.__class__.__name__,
input_index)
mm.transfer_output(pmodule.meta_module, output_index,
sm.meta_module, input_index,
streaming_transfer)
# finally: execute module if
# ModuleManager thinks it's necessary
if streaming_module:
if streamables_dict[smt] == 2:
# terminating module in streamable subset
if mm.should_execute_module(sm.meta_module, sm.part):
print 'streaming executing part %d of %s' % \
(sm.part, \
sm.meta_module.instance.__class__.__name__)
mm.execute_module(sm.meta_module, sm.part,
streaming=True)
# if the module has been
# streaming_executed, it has also been
# touched.
sm.meta_module.streaming_touch_timestamp_module(sm.part)
# make sure we touch the module even if we don't
# execute it. this is used in the transfer
# caching
elif sm.meta_module.should_touch(sm.part):
sm.meta_module.streaming_touch_timestamp_module(sm.part)
else:
# this is not a streaming module, normal semantics
if mm.should_execute_module(sm.meta_module, sm.part):
print 'executing part %d of %s' % \
(sm.part, \
sm.meta_module.instance.__class__.__name__)
mm.execute_module(sm.meta_module, sm.part)
finally:
# in whichever way execution terminates, we have to unlock the
# mutex.
Scheduler._execute_mutex.unlock()
def find_streamable_subsets(self, scheduler_modules):
"""
Algorithm for finding streamable subsets in a network. Also
see Algorithm 2 in the paper [1].
@param scheduler_modules: topologically sorted list of
SchedulerModuleWrapper instances (S).
@return: dictionary of streamable MetaModule bindings (V_ss)
mapping to 1 (non-terminating) or 2 (terminating) and list of
streamable subsets, each an array (M_ss).
"""
# get all streaming modules from S and keep topological
# ordering (S_s == streaming_scheduler_modules)
streamable_modules = []
streamable_modules_dict = {}
for sm in scheduler_modules:
if hasattr(sm.meta_module.instance,
'streaming_execute_module'):
streamable_modules.append((sm.meta_module, sm.part))
# we want to use this to check for streamability later
streamable_modules_dict[(sm.meta_module, sm.part)] = 1
# now the fun begins:
streamables_dict = {} # this is V_ss
streamable_subsets = [] # M_ss
def handle_new_streamable(smt, streamable_subset):
"""Recursive method to do depth-first search for largest
streamable subset.
This is actually the infamous line 9 in the article.
@param: smt is a streamable module tuple (meta_module,
part)
"""
# get all consumers of sm
# getConsumerModules returns ad hoc wrappings!
sm = SchedulerModuleWrapper(smt[0], smt[1])
consumers = self.getConsumerModules(sm)
# if there are no consumers, per def a terminating module
if len(consumers) == 0:
terminating = True
else:
# check if ANY of the the consumers is non-streamable
# in which case sm is also terminating
terminating = False
for c in consumers:
if (c.meta_module,c.part) not in \
streamable_modules_dict:
terminating = True
break
if terminating:
# set sm as the terminating module
streamables_dict[smt] = 2
else:
# add all consumers to streamable_subset M
ctuples = [(i.meta_module, i.part) for i in consumers]
streamable_subset.append(ctuples)
# also add them all to V_ss
streamables_dict.fromkeys(ctuples, 1)
for c in consumers:
handle_new_streamable((c.meta_module, c.part),
streamable_subset)
# smt is a streamable module tuple (meta_module, part)
for smt in streamable_modules:
if not smt in streamables_dict:
# this is a NEW streamable module!
# create new streamable subset
streamable_subset = [smt]
streamables_dict[smt] = 1
# handle this new streamable
handle_new_streamable(smt, streamable_subset)
# handle_new_streamable recursion is done, add
# this subset list of subsets
streamable_subsets.append(streamable_subset)
return streamables_dict, streamable_subsets
#########################################################################
class SchedulerProxy:
"""Proxy class for all schedulers.
Each scheduler mode is represented by a different class, but we
want to use a common instance to access functionality, hence this
proxy.
"""
EVENT_DRIVEN_MODE = 0
HYBRID_MODE = 1
def __init__(self, devide_app):
self.event_driven_scheduler = EventDrivenScheduler(devide_app)
self.hybrid_scheduler = HybridScheduler(devide_app)
# default mode
self.mode = SchedulerProxy.EVENT_DRIVEN_MODE
def get_scheduler(self):
"""Return the correct scheduler instance, dependent on the
current mode.
"""
s = [self.event_driven_scheduler, self.hybrid_scheduler][self.mode]
return s
def execute_modules(self, scheduler_modules):
"""Thunks through to the correct scheduler instance's
execute_modules.
This is called by NetworkManager.execute_network()
"""
self.get_scheduler().execute_modules(scheduler_modules)
def meta_modules_to_scheduler_modules(self, meta_modules):
return self.get_scheduler().meta_modules_to_scheduler_modules(meta_modules)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""Module containing base class for devide modules.
author: Charl P. Botha <cpbotha@ieee.org>
"""
#########################################################################
class GenericObject(object):
"""Generic object into which we can stuff whichever attributes we want.
"""
pass
#########################################################################
class DefaultConfigClass(object):
pass
#########################################################################
class ModuleBase(object):
"""Base class for all modules.
Any module wishing to take part in the devide party will have to offer all
of these methods.
"""
def __init__(self, module_manager):
"""Perform your module initialisation here.
Please also call this init method
(i.e. ModuleBase.__init__(self)). In your own __init__, you
should create your view and show it to the user.
"""
self._module_manager = module_manager
self._config = DefaultConfigClass()
# modules should toggle this variable to True once they have
# initialised and shown their view once.
self.view_initialised = False
def close(self):
"""Idempotent method for de-initialising module as far as possible.
We can't guarantee the calling of __del__, as Python does garbage
collection and the object might destruct a while after we've removed
all references to it.
In addition, with python garbage collection, __del__ can cause
uncollectable objects, so try to avoid it as far as possible.
"""
# we neatly get rid of some references
del self._module_manager
def get_input_descriptions(self):
"""Returns tuple of input descriptions, mostly used by the graph editor
to make a nice glyph for this module."""
raise NotImplementedError
def set_input(self, idx, input_stream):
"""Attaches input_stream (which is e.g. the output of a previous
module) to this module's input at position idx.
If the previous value was None and the current value is not None, it
signifies a connect and the module should initialise as if it's
getting a new input. This usually happens during the first network
execution AFTER a connection.
If the previous value was not-None and the new value is None, it
signifies a disconnect and the module should take the necessary
actions. This usually happens immediatly when the user disconnects an
input
If the previous value was not-None and the current value is not-None,
the module should take actions as for a changed input. This event
signifies a re-transfer on an already existing connection. This can
be considered an event for which this module is an observer.
"""
raise NotImplementedError
def get_output_descriptions(self):
"""Returns a tuple of output descriptions.
Mostly used by the graph editor to make a nice glyph for this module.
These are also clues to the user as to which glyphs can be connected.
"""
raise NotImplementedError
def get_output(self, idx):
"""Get the n-th output.
This will be used for connecting this output to the input of another
module. Whatever is returned by this object MUST have an Update()
method. However you choose to implement it, the Update() should make
sure that the whole chain of logic resulting in the data object has
executed so that the data object is up to date.
"""
raise NotImplementedError
def logic_to_config(self):
"""Synchronise internal configuration information (usually
self._config)with underlying system.
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def config_to_logic(self):
"""Apply internal configuration information (usually self._config) to
the underlying logic.
If this has resulted in changes to the logic, return True, otherwise
return False
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def view_to_config(self):
"""Synchronise internal configuration information with the view (GUI)
of this module.
If this has resulted in changes to the config, return True,
otherwise return False.
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def config_to_view(self):
"""Make the view reflect the internal configuration information.
You only need to implement this if you make use of the standard ECASH
controls.
"""
raise NotImplementedError
def execute_module(self):
"""This should make the model do whatever processing it was designed
to do.
It's important that when this method is called, the module should be
able to cause ALL of the modules preceding it in a glyph chain to
execute (if necessary). If the whole chain consists of VTK objects,
this is easy.
If not, extra measures need to be taken. According to API,
each output/input data object MUST have an Update() method
that can ensure that the logic responsible for that object has
executed thus making the data object current.
In short, execute_module() should call Update() on all of this modules
input objects, directly or indirectly.
"""
raise NotImplementedError
def view(self):
"""Pop up a dialog with all config possibilities, including optional
use of the pipeline browser.
If the dialog is already visible, do something to draw the user's
attention to it. For a wxFrame-based view, you can do something like:
if not frame.Show(True):
frame.Raise()
If the frame is already visible, this will bring it to the front.
"""
raise NotImplementedError
def get_config(self):
"""Returns current configuration of module.
This should return a pickle()able object that encapsulates all
configuration information of this module. The default just returns
self._config, which is None by default. You can override get_config()
and set_config(), or just make sure that your config info always goes
via self._config
In general, you should never need to override this.
"""
# make sure that the config reflects the state of the underlying logic
self.logic_to_config()
# and then return the config struct.
return self._config
def set_config(self, aConfig):
"""Change configuration of module to that stored in aConfig.
If set_config is called with the object previously returned by
get_config(), the module should be in exactly the same state as it was
when get_config() was called. The default sets the default
self._config and applies it to the underlying logic.
In general, you should never need to override this.
"""
# we update the dict of the existing config with the passed
# parameter. This means that the new config is merged with
# the old, but all new members overwrite old one. This is
# more robust.
self._config.__dict__.update(aConfig.__dict__)
# apply the config to the underlying logic
self.config_to_logic()
# bring it back all the way up to the view
self.logic_to_config()
# but only if we are in view mode
if self.view_initialised:
self.config_to_view()
# the config has been set, so we assumem that the module has
# now been modified.
self._module_manager.modify_module(self)
# convenience functions
def sync_module_logic_with_config(self):
self._module_manager.sync_module_logic_with_config(self)
def sync_module_view_with_config(self):
self._module_manager.sync_module_view_with_config(self)
def sync_module_view_with_logic(self):
self._module_manager.sync_module_view_with_logic(self)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
# importing this module shouldn't directly cause other large imports
# do large imports in the init() hook so that you can call back to the
# ModuleManager progress handler methods.
"""geometry_kit package driver file.
Inserts the following modules in sys.modules: geometry.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import sys
# you have to define this
VERSION = 'INTEGRATED'
def init(module_manager, pre_import=True):
global geometry
import geometry
# if we don't do this, the module will be in sys.modules as
# module_kits.stats_kit.stats because it's not in the sys.path.
# iow. if a module is in sys.path, "import module" will put 'module' in
# sys.modules. if a module isn't, "import module" will put
# 'relative.path.to.module' in sys.path.
sys.modules['geometry'] = geometry
module_manager.set_progress(100, 'Initialising geometry_kit: complete.')
def refresh():
# we have none of our own packages yet...
global geometry
reload(geometry)
| Python |
import math
import numpy
epsilon = 1e-12
def abs(v1):
return numpy.absolute(v1)
def norm(v1):
"""Given vector v1, return its norm.
"""
v1a = numpy.array(v1)
norm = numpy.sqrt(numpy.sum(v1a * v1a))
return norm
def normalise_line(p1, p2):
"""Given two points, return normal vector, magnitude and original
line vector.
Example: normal_vec, mag, line_vec = normalize_line(p1_tuple, p2_tuple)
"""
line_vector = numpy.array(p2) - numpy.array(p1)
squared_norm = numpy.sum(line_vector * line_vector)
norm = numpy.sqrt(squared_norm)
if norm != 0.0:
unit_vec = line_vector / norm
else:
unit_vec = line_vector
return (unit_vec, norm, line_vector)
def points_to_vector(p1, p2):
v = numpy.array(p2) - numpy.array(p1)
return v
def dot(v1, v2):
"""Return dot-product between vectors v1 and v2.
"""
dot_product = numpy.sum(numpy.array(v1) * numpy.array(v2))
return dot_product
def move_line_to_target_along_normal(p1, p2, n, target):
"""Move the line (p1,p2) along normal vector n until it intersects
with target.
@returns: Adjusted p1,p2
"""
# n has to be a normal vector, mmmkay?
if norm(n) - 1.0 > epsilon:
raise RuntimeError('normal vector not unit size.')
p1a = numpy.array(p1)
p2a = numpy.array(p2)
ta = numpy.array(target)
# see how far p2a is from ta measured along n
dp = dot(p2a - ta, n)
# better to use an epsilon?
if numpy.absolute(dp) > epsilon:
# calculate vector needed to correct along n
dvec = - dp * n
p1a = p1a + dvec
p2a = p2a + dvec
return (p1a, p2a)
def intersect_line_sphere(p1, p2, sc, r):
"""Calculates intersection between line going through p1 and p2 and
sphere determined by centre sc and radius r.
Requires numpy.
@param p1: tuple, or 1D matrix, or 1D array with first point defining line.
@param p2: tuple, or 1D matrix, or 1D array with second point defining line.
See http://local.wasp.uwa.edu.au/~pbourke/geometry/sphereline/source.cpp
"""
# a is squared distance between the two points defining line
p_diff = numpy.array(p2) - numpy.array(p1)
a = numpy.sum(numpy.multiply(p_diff, p_diff))
b = 2 * ( (p2[0] - p1[0]) * (p1[0] - sc[0]) + \
(p2[1] - p1[1]) * (p1[1] - sc[1]) + \
(p2[2] - p1[2]) * (p1[2] - sc[2]) )
c = sc[0] ** 2 + sc[1] ** 2 + \
sc[2] ** 2 + p1[0] ** 2 + \
p1[1] ** 2 + p1[2] ** 2 - \
2 * (sc[0] * p1[0] + sc[1] * p1[1] + sc[2]*p1[2]) - r ** 2
i = b * b - 4 * a * c
if (i < 0.0):
# no intersections
return []
if (i == 0.0):
# one intersection
mu = -b / (2 * a)
return [ (p1[0] + mu * (p2[0] - p1[0]),
p1[1] + mu * (p2[1] - p1[1]),
p1[2] + mu * (p2[2] - p1[2])) ]
if (i > 0.0):
# two intersections
mu = (-b + math.sqrt( b ** 2 - 4*a*c )) / (2*a)
i1 = (p1[0] + mu * (p2[0] - p1[0]),
p1[1] + mu * (p2[1] - p1[1]),
p1[2] + mu * (p2[2] - p1[2]))
mu = (-b - math.sqrt( b ** 2 - 4*a*c )) / (2*a)
i2 = (p1[0] + mu * (p2[0] - p1[0]),
p1[1] + mu * (p2[1] - p1[1]),
p1[2] + mu * (p2[2] - p1[2]))
# in the case of two intersections, we want to make sure
# that the vector i1,i2 has the same orientation as vector p1,p2
i_diff = numpy.array(i2) - numpy.array(i1)
if numpy.dot(p_diff, i_diff) < 0:
return [i2, i1]
else:
return [i1, i2]
def intersect_line_ellipsoid(p1, p2, ec, radius_vectors):
"""Determine intersection points between line defined by p1 and p2,
and ellipsoid defined by centre ec and three radius vectors (tuple
of tuples, each inner tuple is a radius vector).
This requires numpy.
"""
# create transformation matrix that has the radius_vectors
# as its columns (hence the transpose)
rv = numpy.transpose(numpy.matrix(radius_vectors))
# calculate its inverse
rv_inv = numpy.linalg.pinv(rv)
# now transform the two points
# all points have to be relative to ellipsoid centre
# the [0] at the end and the numpy.array at the start is to make sure
# we pass a row vector (array) to the line_sphere_intersection
p1_e = numpy.array(numpy.matrixmultiply(rv_inv, numpy.array(p1) - numpy.array(ec)))[0]
p2_e = numpy.array(numpy.matrixmultiply(rv_inv, numpy.array(p2) - numpy.array(ec)))[0]
# now we only have to determine the intersection between the points
# (now transformed to ellipsoid space) with the unit sphere centred at 0
isects_e = intersect_line_sphere(p1_e, p2_e, (0.0,0.0,0.0), 1.0)
# transform intersections back to "normal" space
isects = []
for i in isects_e:
# numpy.array(...)[0] is for returning only row of matrix as array
itemp = numpy.array(numpy.matrixmultiply(rv, numpy.array(i)))[0]
isects.append(itemp + numpy.array(ec))
return isects
def intersect_line_mask(p1, p2, mask, incr):
"""Calculate FIRST intersection of line (p1,p2) with mask, as we walk
from p1 to p2 with increments == incr.
"""
p1 = numpy.array(p1)
p2 = numpy.array(p2)
origin = numpy.array(mask.GetOrigin())
spacing = numpy.array(mask.GetSpacing())
incr = float(incr)
line_vector = p2 - p1
squared_norm = numpy.sum(line_vector * line_vector)
norm = numpy.sqrt(squared_norm)
unit_vec = line_vector / norm
curp = p1
intersect = False
end_of_line = False
i_point = numpy.array((), float) # empty array
while not intersect and not end_of_line:
# get voxel coords
voxc = (curp - origin) / spacing
e = mask.GetExtent()
if voxc[0] >= e[0] and voxc[0] <= e[1] and \
voxc[1] >= e[2] and voxc[1] <= e[3] and \
voxc[2] >= e[4] and voxc[2] <= e[5]:
val = mask.GetScalarComponentAsDouble(
voxc[0], voxc[1], voxc[2], 0)
else:
val = 0.0
if val > 0.0:
intersect = True
i_point = curp
else:
curp = curp + unit_vec * incr
cur_squared_norm = numpy.sum(numpy.square(curp - p1))
if cur_squared_norm > squared_norm:
end_of_line = True
if end_of_line:
return None
else:
return i_point
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import wx
def get_system_font_size():
# wx.SYS_ANSI_FIXED_FONT seems to return reliable settings under
# Windows and Linux. SYS_SYSTEM_FONT doesn't do so well on Win.
ft = wx.SystemSettings.GetFont(wx.SYS_ANSI_FIXED_FONT)
return ft.GetPointSize()
def create_html_font_size_array():
"""Based on the system font size, return a 7-element font-size
array that can be used to SetFont() on a wxHtml.
For system font size 8, this should be:
[4,6,8,10,12,14,16]
corresponding with HTML sizes -2 to +4
Currently used to set font sizes on the module documentation
window. Would have liked to use on the module list box as well,
but we can't get to the underlying wxHTML to set it, so we're
forced to use font size=-1 in that case.
"""
sfs = get_system_font_size()
fsa = [0,0,0,0,0,0,0]
for i in range(7):
fsa[i] = sfs + (i-2)*2
return fsa
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import os
import sys
import module_kits.wx_kit
from module_kits.wx_kit.python_shell_mixin import PythonShellMixin
import wx
class Tab:
def __init__(self, editwindow, interp):
self.editwindow = editwindow
self.editwindow.set_interp(interp)
self.filename = ''
self.modified = False
def close(self):
del self.editwindow
class Tabs:
def __init__(self, notebook, parent_window):
self.notebook = notebook
self.parent_window = parent_window
self.tab_list = []
def add_existing(self, editwindow, interp):
self.tab_list.append(Tab(editwindow, interp))
self.set_observer_modified(-1)
editwindow.SetFocus()
def can_close(self, idx):
"""Check if current edit can be closed, also taking action if user
would like to save data first.
@return: True if edit is unmodified OR user has indicated that the
edit can be closed.
"""
if not self.tab_list[idx].modified:
return True
md = wx.MessageDialog(
self.parent_window,
"Current edit has not been saved. "
"Are you sure you want to close it?", "Close confirmation",
style = wx.YES_NO | wx.ICON_QUESTION)
if md.ShowModal() == wx.ID_YES:
return True
else:
return False
def close_current(self):
sel = self.notebook.GetSelection()
if sel >= 0:
if self.can_close(sel):
# save this in case we need it for the new tab
interp = self.tab_list[sel].editwindow.interp
self.notebook.DeletePage(sel)
del self.tab_list[sel]
if self.notebook.GetPageCount() == 0:
self.create_new(interp)
def create_new(self, interp):
pane = wx.Panel(self.notebook, -1)
editwindow = module_kits.wx_kit.dvedit_window.DVEditWindow(pane, -1)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(editwindow, 1, wx.LEFT|wx.RIGHT|wx.EXPAND, 7)
pane.SetAutoLayout(True)
pane.SetSizer(sizer)
sizer.Fit(pane)
sizer.SetSizeHints(pane)
self.notebook.AddPage(pane, "Unnamed")
self.notebook.SetSelection(self.notebook.GetPageCount() - 1)
editwindow.SetFocus()
self.tab_list.append(Tab(editwindow, interp))
self.set_observer_modified(-1)
def get_idx(self, editwindow):
for i in range(len(self.tab_list)):
if self.tab_list[i].editwindow == editwindow:
return i
return -1
def get_current_idx(self):
return self.notebook.GetSelection()
def get_current_tab(self):
sel = self.notebook.GetSelection()
if sel >= 0:
return self.tab_list[sel]
else:
return None
def get_current_text(self):
sel = self.notebook.GetSelection()
if sel >= 0:
t = self.tab_list[sel].editwindow.GetText()
return t
else:
return None
def set_new_loaded_file(self, filename, text):
"""Given a filename and its contents (already loaded), setup the
currently selected tab accordingly.
"""
sel = self.notebook.GetSelection()
if sel >= 0:
self.tab_list[sel].editwindow.SetText(text)
self.tab_list[sel].filename = filename
self.set_tab_modified(sel, False)
def set_observer_modified(self, idx):
def observer_modified(ew):
self.set_tab_modified(self.get_idx(ew), True)
self.tab_list[idx].editwindow.observer_modified = observer_modified
def set_saved(self, filename):
"""Called when current edit / tab has been written to disk.
"""
sel = self.notebook.GetSelection()
if sel >= 0:
self.tab_list[sel].filename = filename
self.set_tab_modified(sel, False)
def set_tab_modified(self, idx, modified):
if self.tab_list[idx].filename:
label = os.path.basename(self.tab_list[idx].filename)
else:
label = 'Unnamed'
if modified:
self.tab_list[idx].modified = True
label += ' *'
else:
self.tab_list[idx].modified = False
self.notebook.SetPageText(idx, label)
class PythonShell(PythonShellMixin):
def __init__(self, parent_window, title, icon, devide_app):
self._devide_app = devide_app
self._parent_window = parent_window
self._frame = self._create_frame()
# set icon
self._frame.SetIcon(icon)
# and change the title
self._frame.SetTitle(title)
# call ctor of mixin
PythonShellMixin.__init__(self, self._frame.shell_window,
self._devide_app.get_module_manager())
self._interp = self._frame.shell_window.interp
# setup structure we'll use for working with the tabs / edits
self._tabs = Tabs(self._frame.edit_notebook, self._frame)
self._tabs.add_existing(self._frame.default_editwindow, self._interp)
self._bind_events()
# make sure that when the window is closed, we just hide it (teehee)
wx.EVT_CLOSE(self._frame, self.close_ps_frame_cb)
#wx.EVT_BUTTON(self._psFrame, self._psFrame.closeButton.GetId(),
# self.close_ps_frame_cb)
# we always start in this directory with our fileopen dialog
#self._snippetsDir = os.path.join(appDir, 'snippets')
#wx.EVT_BUTTON(self._psFrame, self._psFrame.loadSnippetButton.GetId(),
# self._handlerLoadSnippet)
self.support_vtk(self._interp)
self.support_matplotlib(self._interp)
# we can display ourselves
self.show()
def close(self):
PythonShellMixin.close(self, sys.stderr.write)
# take care of the frame
if self._frame:
self._frame.Destroy()
del self._frame
def show(self):
self._frame.Show(True)
self._frame.Iconize(False)
self._frame.Raise()
def hide(self):
self._frame.Show(False)
def close_ps_frame_cb(self, event):
self.hide()
def _bind_events(self):
wx.EVT_MENU(self._frame, self._frame.file_new_id,
self._handler_file_new)
wx.EVT_MENU(self._frame, self._frame.file_close_id,
self._handler_file_close)
wx.EVT_MENU(self._frame, self._frame.file_open_id,
self._handler_file_open)
wx.EVT_MENU(self._frame, self._frame.file_save_id,
self._handler_file_save)
wx.EVT_MENU(self._frame, self._frame.file_saveas_id,
self._handler_file_saveas)
wx.EVT_MENU(self._frame, self._frame.run_id,
self._handler_file_run)
def _create_frame(self):
import resources.python.python_shell_frame
reload(resources.python.python_shell_frame)
frame = resources.python.python_shell_frame.PyShellFrame(
self._parent_window, id=-1, title="Dummy", name='DeVIDE')
return frame
def _handler_file_new(self, event):
self._tabs.create_new(self._interp)
def _handler_file_close(self, event):
self._tabs.close_current()
def _handler_file_open(self, event):
try:
filename, t = self._open_python_file(self._frame)
except IOError, e:
self._devide_app.log_error_with_exception(
'Could not open file %s: %s' %
(filename, str(e)))
else:
if filename:
self._tabs.set_new_loaded_file(filename, t)
def _handler_file_save(self, event):
# if we have a filename, just save, if not, do saveas
current_tab = self._tabs.get_current_tab()
text = self._tabs.get_current_text()
try:
if not current_tab.filename:
# returns None if use cancelled from file save dialog
filename = self._saveas_python_file(text, self._frame)
current_tab.filename = filename
else:
self._save_python_file(current_tab.filename, text)
# we do this
filename = current_tab.filename
except IOError, e:
self._devide_app.log_error_with_exception(
'Could not write file %s: %s' %
(filename, str(e)))
else:
if filename is not None:
self._tabs.set_saved(current_tab.filename)
self.set_statusbar_message('Wrote %s to disc.' % (filename,))
def _handler_file_saveas(self, event):
text = self._tabs.get_current_text()
try:
filename = self._saveas_python_file(text, self._frame)
except IOError, e:
self._devide_app.log_error_with_exception(
'Could not write file %s: %s' %
(filename, str(e)))
else:
if filename is not None:
self._tabs.set_saved(filename)
def _handler_file_run(self, event):
t = self._tabs.get_current_text()
if t is not None:
self._run_source(t)
self.set_statusbar_message('Current run completed.')
def _handlerLoadSnippet(self, event):
dlg = wx.FileDialog(self._psFrame, 'Choose a Python snippet to load.',
self._snippetsDir, '',
'Python files (*.py)|*.py|All files (*.*)|*.*',
wx.OPEN)
if dlg.ShowModal() == wx.ID_OK:
# get the path
path = dlg.GetPath()
# store the dir in the self._snippetsDir
self._snippetsDir = os.path.dirname(path)
# actually run the snippet
self.loadSnippet(path)
# take care of the dlg
dlg.Destroy()
def inject_locals(self, locals_dict):
self._interp.locals.update(locals_dict)
def loadSnippet(self, path):
try:
# redirect std thingies so that output appears in the shell win
self._psFrame.pyShell.redirectStdout()
self._psFrame.pyShell.redirectStderr()
self._psFrame.pyShell.redirectStdin()
# runfile also generates an IOError if it can't load the file
#execfile(path, globals(), self._psFrame.pyShell.interp.locals)
# this is quite sneaky, but yields better results especially
# if there's an exception.
# IMPORTANT: it's very important that we use a raw string
# else things go very wonky under windows when double slashes
# become single slashes and \r and \b and friends do their thing
self._psFrame.pyShell.run('execfile(r"%s")' %
(path,))
except IOError,e:
md = wx.MessageDialog(
self._psFrame,
'Could not open file %s: %s' % (path, str(e)), 'Error',
wx.OK|wx.ICON_ERROR)
md.ShowModal()
# whatever happens, advance shell window with one line so
# the user can type again
self._psFrame.pyShell.push('')
# redirect thingies back
self._psFrame.pyShell.redirectStdout(False)
self._psFrame.pyShell.redirectStderr(False)
self._psFrame.pyShell.redirectStdin(False)
def set_statusbar_message(self, message):
self._frame.statusbar.SetStatusText(message)
| Python |
Subsets and Splits
SQL Console for ajibawa-2023/Python-Code-Large
Provides a useful breakdown of language distribution in the training data, showing which languages have the most samples and helping identify potential imbalances across different language groups.