code stringlengths 1 1.72M | language stringclasses 1 value |
|---|---|
# 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 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 |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class extractGrid(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._config.sampleRate = (1, 1, 1)
configList = [
('Sample rate:', 'sampleRate', 'tuple:int,3', 'tupleText',
'Subsampling rate.')]
self._extractGrid = vtkdevide.vtkPVExtractVOI()
module_utils.setup_vtk_object_progress(self, self._extractGrid,
'Subsampling structured grid.')
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkExtractGrid' : self._extractGrid})
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._extractGrid
def execute_module(self):
self._extractGrid.Update()
def get_input_descriptions(self):
return ('VTK Dataset',)
def set_input(self, idx, inputStream):
self._extractGrid.SetInput(inputStream)
def get_output_descriptions(self):
return ('Subsampled VTK Dataset',)
def get_output(self, idx):
return self._extractGrid.GetOutput()
def logic_to_config(self):
self._config.sampleRate = self._extractGrid.GetSampleRate()
def config_to_logic(self):
self._extractGrid.SetSampleRate(self._config.sampleRate)
| 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 |
# imageGaussianSmooth copyright (c) 2003 by Charl P. Botha cpbotha@ieee.org
# $Id: resampleImage.py 3229 2008-09-04 17:06:13Z cpbotha $
# performs image smoothing by convolving with a Gaussian
import gen_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
class resampleImage(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageResample = vtk.vtkImageResample()
module_utils.setup_vtk_object_progress(self, self._imageResample,
'Resampling image.')
# 0: nearest neighbour
# 1: linear
# 2: cubic
self._config.interpolationMode = 1
self._config.magFactors = [1.0, 1.0, 1.0]
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)
self.set_input(0, None)
# don't forget to call the close() method of the vtkPipeline mixin
IntrospectModuleMixin.close(self)
# take out our view interface
if self._view_frame is not None:
self._view_frame.Destroy()
# get rid of our reference
del self._imageResample
# and finally call our base dtor
ModuleBase.close(self)
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageResample.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageResample.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._imageResample.GetOutput()
def logic_to_config(self):
istr = self._imageResample.GetInterpolationModeAsString()
# we do it this way so that when the values in vtkImageReslice
# are changed, we won't be affected
self._config.interpolationMode = {'NearestNeighbor': 0,
'Linear': 1,
'Cubic': 3}[istr]
for i in range(3):
mfi = self._imageResample.GetAxisMagnificationFactor(i, None)
self._config.magFactors[i] = mfi
def config_to_logic(self):
if self._config.interpolationMode == 0:
self._imageResample.SetInterpolationModeToNearestNeighbor()
elif self._config.interpolationMode == 1:
self._imageResample.SetInterpolationModeToLinear()
else:
self._imageResample.SetInterpolationModeToCubic()
for i in range(3):
self._imageResample.SetAxisMagnificationFactor(
i, self._config.magFactors[i])
def view_to_config(self):
itc = self._view_frame.interpolationTypeChoice.GetSelection()
if itc < 0 or itc > 2:
# default when something weird happens to choice
itc = 1
self._config.interpolationMode = itc
txtTup = self._view_frame.magFactorXText.GetValue(), \
self._view_frame.magFactorYText.GetValue(), \
self._view_frame.magFactorZText.GetValue()
for i in range(3):
self._config.magFactors[i] = gen_utils.textToFloat(
txtTup[i], self._config.magFactors[i])
def config_to_view(self):
self._view_frame.interpolationTypeChoice.SetSelection(
self._config.interpolationMode)
txtTup = self._view_frame.magFactorXText, \
self._view_frame.magFactorYText, \
self._view_frame.magFactorZText
for i in range(3):
txtTup[i].SetValue(str(self._config.magFactors[i]))
def execute_module(self):
self._imageResample.Update()
def streaming_execute_module(self):
self._imageResample.GetOutput().Update()
def view(self, parent_window=None):
if self._view_frame is None:
self._createViewFrame()
# following ModuleBase convention to indicate that view is
# available.
self.view_initialised = True
# and make sure the view is up to date
self._module_manager.sync_module_view_with_logic(self)
# if the window was visible already. just raise it
self._view_frame.Show(True)
self._view_frame.Raise()
def _createViewFrame(self):
self._module_manager.import_reload(
'modules.filters.resources.python.resampleImageViewFrame')
import modules.filters.resources.python.resampleImageViewFrame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.filters.resources.python.resampleImageViewFrame.\
resampleImageViewFrame)
objectDict = {'vtkImageResample' : self._imageResample}
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.viewFramePanel,
objectDict, None)
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.viewFramePanel)
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import vtkdevide
class extractHDomes(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageMathSubtractH = vtk.vtkImageMathematics()
self._imageMathSubtractH.SetOperationToAddConstant()
self._reconstruct = vtkdevide.vtkImageGreyscaleReconstruct3D()
# second input is marker
self._reconstruct.SetInput(1, self._imageMathSubtractH.GetOutput())
self._imageMathSubtractR = vtk.vtkImageMathematics()
self._imageMathSubtractR.SetOperationToSubtract()
self._imageMathSubtractR.SetInput(1, self._reconstruct.GetOutput())
module_utils.setup_vtk_object_progress(self, self._imageMathSubtractH,
'Preparing marker image.')
module_utils.setup_vtk_object_progress(self, self._reconstruct,
'Performing reconstruction.')
module_utils.setup_vtk_object_progress(self, self._imageMathSubtractR,
'Subtracting reconstruction.')
self._config.h = 50
configList = [
('H-dome height:', 'h', 'base:float', 'text',
'The required difference in brightness between an h-dome and\n'
'its surroundings.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'ImageMath Subtract H' : self._imageMathSubtractH,
'ImageGreyscaleReconstruct3D' : self._reconstruct,
'ImageMath Subtract R' : self._imageMathSubtractR})
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._imageMathSubtractH
del self._reconstruct
del self._imageMathSubtractR
def get_input_descriptions(self):
return ('Input image (VTK)',)
def set_input(self, idx, inputStream):
self._imageMathSubtractH.SetInput(0, inputStream)
# first input of the reconstruction is the image
self._reconstruct.SetInput(0, inputStream)
self._imageMathSubtractR.SetInput(0, inputStream)
def get_output_descriptions(self):
return ('h-dome extraction (VTK image)',)
def get_output(self, idx):
return self._imageMathSubtractR.GetOutput()
def logic_to_config(self):
self._config.h = - self._imageMathSubtractH.GetConstantC()
def config_to_logic(self):
self._imageMathSubtractH.SetConstantC( - self._config.h)
def execute_module(self):
self._imageMathSubtractR.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 |
import input_array_choice_mixin
from input_array_choice_mixin import InputArrayChoiceMixin
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
INTEG_TYPE = ['RK2', 'RK4', 'RK45']
INTEG_TYPE_TEXTS = ['Runge-Kutta 2', 'Runge-Kutta 4', 'Runge-Kutta 45']
INTEG_DIR = ['FORWARD', 'BACKWARD', 'BOTH']
INTEG_DIR_TEXTS = ['Forward', 'Backward', 'Both']
ARRAY_IDX = 0
class streamTracer(ScriptedConfigModuleMixin, InputArrayChoiceMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
InputArrayChoiceMixin.__init__(self)
# 0 = RK2
# 1 = RK4
# 2 = RK45
self._config.integrator = INTEG_TYPE.index('RK2')
self._config.max_prop = 5.0
self._config.integration_direction = INTEG_DIR.index(
'FORWARD')
configList = [
('Vectors selection:', 'vectorsSelection', 'base:str', 'choice',
'The attribute that will be used as vectors for the warping.',
(input_array_choice_mixin.DEFAULT_SELECTION_STRING,)),
('Max propagation:', 'max_prop', 'base:float', 'text',
'The streamline will propagate up to this lenth.'),
('Integration direction:', 'integration_direction', 'base:int', 'choice',
'Select an integration direction.',
INTEG_DIR_TEXTS),
('Integrator type:', 'integrator', 'base:int', 'choice',
'Select an integrator for the streamlines.',
INTEG_TYPE_TEXTS)]
self._streamTracer = vtk.vtkStreamTracer()
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkStreamTracer' : self._streamTracer})
module_utils.setup_vtk_object_progress(self, self._streamTracer,
'Tracing stream lines.')
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._streamTracer
def execute_module(self):
self._streamTracer.Update()
if self.view_initialised:
choice = self._getWidget(0)
self.iac_execute_module(self._streamTracer, choice,
ARRAY_IDX)
def get_input_descriptions(self):
return ('VTK Vector dataset', 'VTK source geometry')
def set_input(self, idx, inputStream):
if idx == 0:
self._streamTracer.SetInput(inputStream)
else:
self._streamTracer.SetSource(inputStream)
def get_output_descriptions(self):
return ('Streamlines polydata',)
def get_output(self, idx):
return self._streamTracer.GetOutput()
def logic_to_config(self):
self._config.max_prop = \
self._streamTracer.GetMaximumPropagation()
self._config.integration_direction = \
self._streamTracer.GetIntegrationDirection()
self._config.integrator = self._streamTracer.GetIntegratorType()
# this will extract the possible choices
self.iac_logic_to_config(self._streamTracer, ARRAY_IDX)
def config_to_logic(self):
self._streamTracer.SetMaximumPropagation(self._config.max_prop)
self._streamTracer.SetIntegrationDirection(self._config.integration_direction)
self._streamTracer.SetIntegratorType(self._config.integrator)
# it seems that array_idx == 1 refers to vectors
# array_idx 0 gives me only the x-component of multi-component
# arrays
self.iac_config_to_logic(self._streamTracer, ARRAY_IDX)
def config_to_view(self):
# first get our parent mixin to do its thing
ScriptedConfigModuleMixin.config_to_view(self)
choice = self._getWidget(0)
self.iac_config_to_view(choice)
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class extractImageComponents(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._extract = vtk.vtkImageExtractComponents()
module_utils.setup_vtk_object_progress(self, self._extract,
'Extracting components.')
self._config.component1 = 0
self._config.component2 = 1
self._config.component3 = 2
self._config.numberOfComponents = 1
self._config.fileLowerLeft = False
configList = [
('Component 1:', 'component1', 'base:int', 'text',
'Zero-based index of first component to extract.'),
('Component 2:', 'component2', 'base:int', 'text',
'Zero-based index of second component to extract.'),
('Component 3:', 'component3', 'base:int', 'text',
'Zero-based index of third component to extract.'),
('Number of components:', 'numberOfComponents', 'base:int',
'choice',
'Number of components to extract. Only this number of the '
'above-specified component indices will be used.',
('1', '2', '3'))]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkImageExtractComponents' : self._extract})
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._extract
def get_input_descriptions(self):
return ('Multi-component vtkImageData',)
def set_input(self, idx, inputStream):
self._extract.SetInput(inputStream)
def get_output_descriptions(self):
return ('Extracted component vtkImageData',)
def get_output(self, idx):
return self._extract.GetOutput()
def logic_to_config(self):
# numberOfComponents is 0-based !!
self._config.numberOfComponents = \
self._extract.GetNumberOfComponents()
self._config.numberOfComponents -= 1
c = self._extract.GetComponents()
self._config.component1 = c[0]
self._config.component2 = c[1]
self._config.component3 = c[2]
def config_to_logic(self):
# numberOfComponents is 0-based !!
nc = self._config.numberOfComponents
nc += 1
if nc == 1:
self._extract.SetComponents(self._config.component1)
elif nc == 2:
self._extract.SetComponents(self._config.component1,
self._config.component2)
else:
self._extract.SetComponents(self._config.component1,
self._config.component2,
self._config.component3)
def execute_module(self):
self._extract.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
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 ScriptedConfigModuleMixin
import module_utils
import vtk
import vtktudoss
class FastSurfaceToDistanceField(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._clean_pd = vtk.vtkCleanPolyData()
module_utils.setup_vtk_object_progress(
self, self._clean_pd,
'Cleaning up polydata')
self._cpt_df = vtktudoss.vtkCPTDistanceField()
module_utils.setup_vtk_object_progress(
self, self._cpt_df,
'Converting surface to distance field')
# connect the up
self._cpt_df.SetInputConnection(
self._clean_pd.GetOutputPort())
self._config.max_dist = 1.0
self._config.padding = 0.0
self._config.dimensions = (64, 64, 64)
configList = [
('Maximum distance:', 'max_dist', 'base:float',
'text',
'Maximum distance up to which field will be '
'calculated.'),
('Dimensions:', 'dimensions', 'tuple:int,3',
'tupleText',
'Resolution of resultant distance field.'),
('Padding:', 'padding', 'base:float', 'text',
'Padding of distance field around surface.')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkCleanPolyData' : self._clean_pd,
'vtkCPTDistanceField' : self._cpt_df})
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._clean_pd
del self._cpt_df
def get_input_descriptions(self):
return ('Surface (vtkPolyData)',)
def set_input(self, idx, inputStream):
self._clean_pd.SetInput(inputStream)
def get_output_descriptions(self):
return ('Distance field (VTK Image Data)',)
def get_output(self, idx):
return self._cpt_df.GetOutput()
def logic_to_config(self):
self._config.max_dist = self._cpt_df.GetMaximumDistance()
self._config.padding = self._cpt_df.GetPadding()
self._config.dimensions = self._cpt_df.GetDimensions()
def config_to_logic(self):
self._cpt_df.SetMaximumDistance(self._config.max_dist)
self._cpt_df.SetPadding(self._config.padding)
self._cpt_df.SetDimensions(self._config.dimensions)
def execute_module(self):
self._cpt_df.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 |
# 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 |
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 |
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
import module_utils
import vtk
class transformVolumeData(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._imageReslice = vtk.vtkImageReslice()
self._imageReslice.SetInterpolationModeToCubic()
self._imageReslice.SetAutoCropOutput(1)
# initialise any mixins we might have
NoConfigModuleMixin.__init__(
self,
{'Module (self)' : self,
'vtkImageReslice' : self._imageReslice})
module_utils.setup_vtk_object_progress(self, self._imageReslice,
'Resampling volume')
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)
# don't forget to call the close() method of the vtkPipeline mixin
NoConfigModuleMixin.close(self)
# get rid of our reference
del self._imageReslice
def get_input_descriptions(self):
return ('VTK Image Data', 'VTK Transform')
def set_input(self, idx, inputStream):
if idx == 0:
self._imageReslice.SetInput(inputStream)
else:
if inputStream == None:
# disconnect
self._imageReslice.SetResliceTransform(None)
else:
# resliceTransform transforms the resampling grid, which
# is equivalent to transforming the volume with its inverse
self._imageReslice.SetResliceTransform(
inputStream.GetInverse())
def get_output_descriptions(self):
return ('Transformed VTK Image Data',)
def get_output(self, idx):
return self._imageReslice.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._imageReslice.Update()
| 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 |
# this one was generated with:
# for i in *.py; do n=`echo $i | cut -f 1 -d .`; \
# echo -e "class $n:\n kits = ['vtk_kit']\n cats = ['Filters']\n" \
# >> blaat.txt; done
class appendPolyData:
kits = ['vtk_kit']
cats = ['Filters']
help = """DeVIDE encapsulation of the vtkAppendPolyDataFilter that
enables us to combine multiple PolyData structures into one.
DANGER WILL ROBINSON: contact the author, this module is BROKEN.
"""
class clipPolyData:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['polydata', 'clip', 'implicit']
help = \
"""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.
"""
class closing:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale morphological closing on the input image.
Dilation is followed by erosion. The structuring element is ellipsoidal
with user specified sizes in 3 dimensions. Specifying a size of 1 in any
dimension will disable processing in that dimension.
"""
class contour:
kits = ['vtk_kit']
cats = ['Filters']
help = """Extract isosurface from volume data.
"""
class decimate:
kits = ['vtk_kit']
cats = ['Filters']
help = """Reduce number of triangles in surface mesh by merging triangles
in areas of low detail.
"""
class DICOMAligner:
kits = ['vtk_kit', 'wx_kit']
cats = ['DICOM','Filters']
keywords = ['align','reslice','rotate','orientation','dicom']
help = """Aligns a vtkImageData volume (as read from DICOM) to the
standard DICOM LPH (Left-Posterior-Head) coordinate system.
If alignment is not performed the image's "world" (patient LPH)
coordinates may be computed incorrectly (e.g. in Slice3DViewer).
The transformation reslices the original volume, then moves
the image origin as required. The new origin has to be at the centre
of the voxel with most negative LPH coordinates.
Example use case: Before aligning multiple MRI sequences
for fusion/averaging
(Module by Francois Malan)"""
class doubleThreshold:
kits = ['vtk_kit']
cats = ['Filters']
help = """Apply a lower and an upper threshold to the input image data.
"""
class EditMedicalMetaData:
kits = ['vtk_kit']
cats = ['Filters', 'Medical', 'DICOM']
help = """Edit Medical Meta Data structure. Use this to edit for
example the medical meta data output of a DICOMReader before
writing DICOM data to disk, or to create new meta data. You don't
have to supply an input.
"""
class extractGrid:
kits = ['vtk_kit']
cats = ['Filters']
help = """Subsamples input dataset.
This module makes use of the ParaView vtkPVExtractVOI class, which can
handle structured points, structured grids and rectilinear grids.
"""
class extractHDomes:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Extracts light structures, also known as h-domes.
The user specifies the parameter 'h' that indicates how much brighter the
light structures are than their surroundings. In short, this algorithm
performs a fast greyscale reconstruction of the input image from a marker
that is the image - h. The result of this reconstruction is subtracted
from the image.
See 'Morphological Grayscale Reconstruction in Image Analysis:
Applications and Efficient Algorithms', Luc Vincent, IEEE Trans. on Image
Processing, 1993.
"""
class extractImageComponents:
kits = ['vtk_kit']
cats = ['Filters']
help = """Extracts one, two or three components from multi-component
image data.
Specify the indices of the components you wish to extract and the number
of components.
"""
class FastSurfaceToDistanceField:
kits = ['vtk_kit','vtktudoss_kit']
cats = ['Filters']
keywords = ['distance','distance field', 'mauch', 'polydata',
'implicit']
help = """Given an input surface (vtkPolyData), create a signed
distance field with the surface at distance 0. Uses Mauch's very
fast CPT / distance field implementation.
"""
class FitEllipsoidToMask:
kits = ['numpy_kit', 'vtk_kit']
cats = ['Filters']
keywords = ['PCA', 'eigen-analysis', 'principal components', 'ellipsoid']
help = """Given an image mask in VTK image data format, perform eigen-
analysis on the world coordinates of 'on' points.
Returns dictionary with eigen values in 'u', eigen vectors in 'v' and
world coordinates centroid of 'on' points.
"""
class glyphs:
kits = ['vtk_kit']
cats = ['Filters']
help = """Visualise vector field with glyphs.
After connecting this module, execute your network once, then you
can select the relevant vector attribute to glyph from the
'Vectors Selection' choice in the interface.
"""
class greyReconstruct:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs grey value reconstruction of mask I from marker J.
Theoretically, marker J is dilated and the infimum with mask I is
determined. This infimum now takes the place of J. This process is
repeated until stability.
This module uses a DeVIDE specific implementation of Luc Vincent's fast
hybrid algorithm for greyscale reconstruction.
"""
class ICPTransform:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['iterative closest point transform', 'map',
'register', 'registration']
help = """Use iterative closest point transform to map two
surfaces onto each other with an affine transform.
Three different transform modes are available:
<ul>
<li>Rigid: rotation + translation</li>
<li>Similarity: rigid + isotropic scaling</li>
<li>Affine: rigid + scaling + shear</li>
</ul>
The output of this class is a linear transform that can be used as
input to for example a transformPolydata class.
"""
class imageFillHoles:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Filter to fill holes.
In binary images, holes are image regions with 0-value that are completely
surrounded by regions of 1-value. This module can be used to fill these
holes. This filling also works on greyscale images.
In addition, the definition of a hole can be adapted by 'deactivating'
image borders so that 0-value regions that touch these deactivated borders
are still considered to be holes and will be filled.
This module is based on two DeVIDE-specific filters: a fast greyscale
reconstruction filter as per Luc Vincent and a special image border mask
generator filter.
"""
class imageFlip:
kits = ['vtk_kit']
cats = ['Filters']
help = """Flips image (volume) with regards to a single axis.
At the moment, this flips by default about Z. You can change this by
introspecting and calling the SetFilteredAxis() method via the
object inspection.
"""
class imageGaussianSmooth:
kits = ['vtk_kit']
cats = ['Filters']
help = """Performs 3D Gaussian filtering of the input volume.
"""
class imageGradientMagnitude:
kits = ['vtk_kit']
cats = ['Filters']
help = """Calculates the gradient magnitude of the input volume using
central differences.
"""
class imageGreyDilate:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale 3D dilation on the input.
"""
class imageGreyErode:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale 3D erosion on the input.
"""
class ImageLogic:
kits = ['vtk_kit']
cats = ['Filters', 'Combine']
help = """Performs pointwise boolean logic operations on input images.
WARNING: vtkImageLogic in VTK 5.0 has a bug where it does require two
inputs even if performing a NOT or a NOP. This has been fixed in VTK CVS.
DeVIDE will upgrade to > 5.0 as soon as a new stable VTK is released.
"""
class imageMask:
kits = ['vtk_kit']
cats = ['Filters', 'Combine']
help = """The input data (input 1) is masked with the mask (input 2).
The output image is identical to the input image wherever the mask has
a value. The output image is 0 everywhere else.
"""
class imageMathematics:
kits = ['vtk_kit']
cats = ['Filters', 'Combine']
help = """Performs point-wise mathematical operations on one or two images.
The underlying logic can do far more than the UI shows at this moment.
Please let me know if you require more options.
"""
class imageMedian3D:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs 3D morphological median on input data.
"""
class landmarkTransform:
kits = ['vtk_kit']
cats = ['Filters']
help = """The landmarkTransform will calculate a 4x4 linear transform
that maps from a set of source landmarks to a set of target landmarks.
The mapping is optimised with a least-squares metric.
For convenience, there are two inputs that you can use in any
combination (either or both). All points that you supply (for
example the output of slice3dVWR modules) will be combined
internally into one list and then divided into two groups based on
the point names: the one group with names starting with 'source'
the other with 'target'. Points will then be matched up by name,
so 'source example 1' will be matched with 'target example 1'.
This module will supply a vtkTransform at its output. By
connecting the vtkTransform to a transformPolyData or a
transformVolume module, you'll be able to perform the actual
transformation.
See the "Performing landmark registration on two volumes" example in the
"Useful Patterns" section of the DeVIDE F1 central help.
"""
class marchingCubes:
kits = ['vtk_kit']
cats = ['Filters']
help = """Extract surface from input volume using the Marching Cubes
algorithm.
"""
class morphGradient:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale morphological gradient on the input image.
This is done by performing an erosion and a dilation of the input image
and then subtracting the erosion from the dilation. The structuring
element is ellipsoidal with user specified sizes in 3 dimensions.
Specifying a size of 1 in any dimension will disable processing in that
dimension.
This module can also return both half gradients: the inner (image -
erosion) and the outer (dilation - image).
"""
class opening:
kits = ['vtk_kit']
cats = ['Filters', 'Morphology']
keywords = ['morphology']
help = """Performs a greyscale morphological opening on the input image.
Erosion is followed by dilation. The structuring element is ellipsoidal
with user specified sizes in 3 dimensions. Specifying a size of 1 in any
dimension will disable processing in that dimension.
"""
class MIPRender:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """Performs Maximum Intensity Projection on the input volume /
image.
"""
class PerturbPolyPoints:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['polydata','move','perturb','random','noise','shuffle']
help = """Randomly perturbs each polydata vertex in a uniformly random direction"""
class polyDataConnect:
kits = ['vtk_kit']
cats = ['Filters']
help = """Perform connected components analysis on polygonal data.
In the default 'point seeded regions' mode:
Given a number of seed points, extract all polydata that is
directly or indirectly connected to those seed points. You could see
this as a polydata-based region growing.
"""
class polyDataNormals:
kits = ['vtk_kit']
cats = ['Filters']
help = """Calculate surface normals for input data mesh.
"""
class probeFilter:
kits = ['vtk_kit']
cats = ['Filters']
help = """Maps source values onto input dataset.
Input can be e.g. polydata and source a volume, in which case interpolated
values from the volume will be mapped on the vertices of the polydata,
i.e. the interpolated values will be associated as the attributes of the
polydata points.
"""
class RegionGrowing:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['region growing', 'threshold', 'automatic',
'segmentation']
help = """Perform 3D region growing with automatic thresholding
based on seed positions.
Given any number of seed positions (for example the first output
of a slice3dVWR), first calculate lower and upper thresholds
automatically as follows:
<ol>
<li>calculate mean intensity over all seed positions.</li>
<li>lower threshold = mean - auto_thresh_interval%
* [full input data scalar range].</li>
<li>upper threshold = mean + auto_thresh_interval% * [full input
data scalar range].</li>
</ol>
After the data has been thresholded with the automatic thresholds,
a 3D region growing is started from all seed positions.
"""
class resampleImage:
kits = ['vtk_kit']
cats = ['Filters']
help = """Resample an image using nearest neighbour, linear or cubic
interpolation.
"""
class seedConnect:
kits = ['vtk_kit']
cats = ['Filters']
help = """3D region growing.
Finds all points connected to the seed points that also have values
equal to the 'Input Connected Value'. This module casts all input to
unsigned char. The output is also unsigned char.
"""
class selectConnectedComponents:
kits = ['vtk_kit']
cats = ['Filters']
help = """3D region growing.
Finds all points connected to the seed points that have the same values
as at the seed points. This is primarily useful for selecting connected
components.
"""
class shellSplatSimple:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """Simple configuration for ShellSplatting an input volume.
ShellSplatting is a fast direct volume rendering method. See
http://visualisation.tudelft.nl/Projects/ShellSplatting for more
information.
"""
class StreamerVTK:
kits = ['vtk_kit']
cats = ['Streaming']
keywords = ['streaming', 'streamer', 'hybrid']
help = """Use this module to terminate streaming subsets of
networks consisting of VTK modules producing image or poly data.
This module requests input in blocks to build up a complete output
dataset. Together with the hybrid scheduling in DeVIDE, this
can save loads of memory.
"""
class streamTracer:
kits = ['vtk_kit']
cats = ['Filters']
help = """Visualise a vector field with stream lines.
After connecting this module, execute your network once, then you
can select the relevant vector attribute to glyph from the
'Vectors Selection' choice in the interface.
"""
class surfaceToDistanceField:
kits = ['vtk_kit']
cats = ['Filters']
help = """Given an input surface (vtkPolyData), create an unsigned
distance field with the surface at distance 0.
The user must specify the dimensions and bounds of the output volume.
WARNING: this filter is *incredibly* slow, even for small volumes and
extremely simple geometry. Only use this if you know exactly what
you're doing.
"""
class transformImageToTarget:
kits = ['vtk_kit']
cats = ['Filters']
keywords = ['align','reslice','rotate','orientation','transform','resample']
help = """Transforms input volume by the supplied geometrical transform, and maps it onto a new coordinate frame (orientation, extent, spacing) specified by the
the specified target grid. The target is not overwritten, but a new volume is created with the desired orientation, dimensions and spacing.
This volume is then filled by probing the transformed source. Areas for which no values are found are zero-padded.
"""
class transformPolyData:
kits = ['vtk_kit']
cats = ['Filters']
help = """Given a transform, for example the output of the
landMarkTransform, this module will transform its input polydata.
"""
class transformVolumeData:
kits = ['vtk_kit']
cats = ['Filters']
help = """Transform volume according to 4x4 homogeneous transform.
"""
class ExpVolumeRender:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """EXPERIMENTAL Volume Render.
This is an experimental volume renderer module used to test out
new ideas. Handle with EXTREME caution, it might open portals to
other dimensions, letting through its evil minions into ours, and
forcing you to take a stand with only a crowbar at your disposal.
If you would rather just volume render some data, please use the
non-experimental VolumeRender module.
"""
class VolumeRender:
kits = ['vtk_kit']
cats = ['Volume Rendering']
help = """Use direct volume rendering to visualise input volume.
You can select between traditional raycasting, 2D texturing and 3D
texturing. The raycaster can only handler unsigned short or unsigned char
data, so you might have to use a vtkShiftScale module to preprocess.
You can supply your own opacity and colour transfer functions at the
second and third inputs. If you don't supply these, the module will
create opacity and/or colour ramps based on the supplied threshold.
"""
class warpPoints:
kits = ['vtk_kit']
cats = ['Filters']
help = """Warp input points according to their associated vectors.
After connecting this module up, you have to execute the network
once, then select the relevant vectors from the 'Vectors
Selection' choice in the interface.
"""
class wsMeshSmooth:
kits = ['vtk_kit']
cats = ['Filters']
help = """Module that runs vtkWindowedSincPolyDataFilter on its input data
for mesh smoothing.
"""
| 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 |
# 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 |
# 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
class VolumeRender(
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)', 'GPU raycasting',
'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_otf = None
self._input_ctf = 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',
'colour transfer function')
def set_input(self, idx, inputStream):
if idx == 0:
self._input_data = inputStream
elif idx == 1:
self._input_otf = inputStream
else:
self._input_ctf = 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:
# gpu raycasting
self._setup_for_gpu_raycasting()
elif self._config.rendering_type == 2:
# 2d texture
self._setup_for_2d_texture()
elif self._config.rendering_type == 3:
# 3d texture
self._setup_for_3d_texture()
elif self._config.rendering_type == 4:
# 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.
"""
self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
self._volume_mapper.SetBlendModeToComposite()
#self._volume_mapper.SetBlendModeToMaximumIntensity()
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
def _setup_for_gpu_raycasting(self):
"""This doesn't seem to work. After processing is complete,
it stalls on actually rendering the volume. No idea.
"""
self._volume_mapper = vtk.vtkGPUVolumeRayCastMapper()
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(otf)
self._volume_property.SetColor(ctf)
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 |
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 |
# imageGaussianSmooth copyright (c) 2003 by Charl P. Botha cpbotha@ieee.org
# $Id$
# performs image smoothing by convolving with a Gaussian
import gen_utils
from module_base import ModuleBase
from module_mixins import IntrospectModuleMixin
import module_utils
import vtk
class imageGaussianSmooth(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._imageGaussianSmooth = vtk.vtkImageGaussianSmooth()
module_utils.setup_vtk_object_progress(self, self._imageGaussianSmooth,
'Smoothing image with Gaussian')
self._config.standardDeviation = (2.0, 2.0, 2.0)
self._config.radiusCutoff = (1.5, 1.5, 1.5)
self._view_frame = None
self._module_manager.sync_module_logic_with_config(self)
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
IntrospectModuleMixin.close(self)
# take out our view interface
if self._view_frame is not None:
self._view_frame.Destroy()
# get rid of our reference
del self._imageGaussianSmooth
# and finally call our base dtor
ModuleBase.close(self)
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageGaussianSmooth.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageGaussianSmooth.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._imageGaussianSmooth.GetOutput()
def logic_to_config(self):
self._config.standardDeviation = self._imageGaussianSmooth.\
GetStandardDeviations()
self._config.radiusCutoff = self._imageGaussianSmooth.\
GetRadiusFactors()
def config_to_logic(self):
self._imageGaussianSmooth.SetStandardDeviations(
self._config.standardDeviation)
self._imageGaussianSmooth.SetRadiusFactors(
self._config.radiusCutoff)
def view_to_config(self):
# continue with textToTuple in gen_utils
stdText = self._view_frame.stdTextCtrl.GetValue()
self._config.standardDeviation = gen_utils.textToTypeTuple(
stdText, self._config.standardDeviation, 3, float)
cutoffText = self._view_frame.radiusCutoffTextCtrl.GetValue()
self._config.radiusCutoff = gen_utils.textToTypeTuple(
cutoffText, self._config.radiusCutoff, 3, float)
def config_to_view(self):
stdText = '(%.2f, %.2f, %.2f)' % self._config.standardDeviation
self._view_frame.stdTextCtrl.SetValue(stdText)
cutoffText = '(%.2f, %.2f, %.2f)' % self._config.radiusCutoff
self._view_frame.radiusCutoffTextCtrl.SetValue(cutoffText)
def execute_module(self):
self._imageGaussianSmooth.Update()
def view(self, parent_window=None):
if self._view_frame is None:
self._createViewFrame()
# the logic is the bottom line in this case
self._module_manager.sync_module_view_with_logic(self)
# if the window was visible already. just raise it
self._view_frame.Show(True)
self._view_frame.Raise()
def _createViewFrame(self):
self._module_manager.import_reload(
'modules.filters.resources.python.imageGaussianSmoothViewFrame')
import modules.filters.resources.python.imageGaussianSmoothViewFrame
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.filters.resources.python.imageGaussianSmoothViewFrame.\
imageGaussianSmoothViewFrame)
objectDict = {'vtkImageGaussianSmooth' : self._imageGaussianSmooth}
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.viewFramePanel,
objectDict, None)
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.viewFramePanel)
| 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 |
# dumy __init__ so this directory can function as a package
| Python |
# dumy __init__ so this directory can function as a package
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class imageMask(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# setup VTK pipeline #########################################
# 1. vtkImageMask
self._imageMask = vtk.vtkImageMask()
self._imageMask.GetOutput().SetUpdateExtentToWholeExtent()
#self._imageMask.SetMaskedOutputValue(0)
module_utils.setup_vtk_object_progress(self, self._imageMask,
'Masking image')
# 2. vtkImageCast
self._image_cast = vtk.vtkImageCast()
# type required by vtkImageMask
self._image_cast.SetOutputScalarTypeToUnsignedChar()
# connect output of cast to imagemask input
self._imageMask.SetMaskInput(self._image_cast.GetOutput())
module_utils.setup_vtk_object_progress(
self, self._image_cast,
'Casting mask image to unsigned char')
###############################################################
self._config.not_mask = False
self._config.masked_output_value = 0.0
config_list = [
('Negate (NOT) mask:', 'not_mask', 'base:bool', 'checkbox',
'Should mask be negated (NOT operator applied) before '
'applying to input?'),
('Masked output value:', 'masked_output_value', 'base:float',
'text', 'Positions outside the mask will be assigned this '
'value.')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' :self,
'vtkImageMask' : self._imageMask})
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._imageMask
del self._image_cast
def get_input_descriptions(self):
return ('vtkImageData (data)', 'vtkImageData (mask)')
def set_input(self, idx, inputStream):
if idx == 0:
self._imageMask.SetImageInput(inputStream)
else:
self._image_cast.SetInput(inputStream)
def get_output_descriptions(self):
return (self._imageMask.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._imageMask.GetOutput()
def logic_to_config(self):
self._config.not_mask = bool(self._imageMask.GetNotMask())
# GetMaskedOutputValue() is not wrapped. *SIGH*
#self._config.masked_output_value = \
# self._imageMask.GetMaskedOutputValue()
def config_to_logic(self):
self._imageMask.SetNotMask(self._config.not_mask)
self._imageMask.SetMaskedOutputValue(self._config.masked_output_value)
def execute_module(self):
self._imageMask.Update()
def streaming_execute_module(self):
self._imageMask.Update()
| Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class morphGradient(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
# main morph gradient
self._imageDilate = vtk.vtkImageContinuousDilate3D()
self._imageErode = vtk.vtkImageContinuousErode3D()
self._imageMath = vtk.vtkImageMathematics()
self._imageMath.SetOperationToSubtract()
self._imageMath.SetInput1(self._imageDilate.GetOutput())
self._imageMath.SetInput2(self._imageErode.GetOutput())
# inner gradient
self._innerImageMath = vtk.vtkImageMathematics()
self._innerImageMath.SetOperationToSubtract()
self._innerImageMath.SetInput1(None) # has to take image
self._innerImageMath.SetInput2(self._imageErode.GetOutput())
# outer gradient
self._outerImageMath = vtk.vtkImageMathematics()
self._outerImageMath.SetOperationToSubtract()
self._outerImageMath.SetInput1(self._imageDilate.GetOutput())
self._outerImageMath.SetInput2(None) # has to take image
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')
module_utils.setup_vtk_object_progress(self, self._imageMath,
'Subtracting erosion from '
'dilation')
module_utils.setup_vtk_object_progress(self, self._innerImageMath,
'Subtracting erosion from '
'image (inner)')
module_utils.setup_vtk_object_progress(self, self._outerImageMath,
'Subtracting image from '
'dilation (outer)')
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,
'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._imageDilate
del self._imageErode
del self._imageMath
def get_input_descriptions(self):
return ('vtkImageData',)
def set_input(self, idx, inputStream):
self._imageDilate.SetInput(inputStream)
self._imageErode.SetInput(inputStream)
self._innerImageMath.SetInput1(inputStream)
self._outerImageMath.SetInput2(inputStream)
def get_output_descriptions(self):
return ('Morphological gradient (vtkImageData)',
'Morphological inner gradient (vtkImageData)',
'Morphological outer gradient (vtkImageData)')
def get_output(self, idx):
if idx == 0:
return self._imageMath.GetOutput()
if idx == 1:
return self._innerImageMath.GetOutput()
else:
return self._outerImageMath.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):
# we only execute the main gradient
self._imageMath.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class wsMeshSmooth(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._wsPDFilter = vtk.vtkWindowedSincPolyDataFilter()
module_utils.setup_vtk_object_progress(self, self._wsPDFilter,
'Smoothing polydata')
# setup some defaults
self._config.numberOfIterations = 20
self._config.passBand = 0.1
self._config.featureEdgeSmoothing = False
self._config.boundarySmoothing = True
self._config.non_manifold_smoothing = False
config_list = [
('Number of iterations', 'numberOfIterations', 'base:int', 'text',
'Algorithm will stop after this many iterations.'),
('Pass band (0 - 2, default 0.1)', 'passBand', 'base:float',
'text', 'Indication of frequency cut-off, the lower, the more '
'it smoothes.'),
('Feature edge smoothing', 'featureEdgeSmoothing', 'base:bool',
'checkbox', 'Smooth feature edges (large dihedral angle)'),
('Boundary smoothing', 'boundarySmoothing', 'base:bool',
'checkbox', 'Smooth boundary edges (edges with only one face).'),
('Non-manifold smoothing', 'non_manifold_smoothing',
'base:bool', 'checkbox',
'Smooth non-manifold vertices, for example output of '
'discrete marching cubes (multi-material).')]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkWindowedSincPolyDataFilter' : self._wsPDFilter})
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._wsPDFilter
def get_input_descriptions(self):
return ('vtkPolyData',)
def set_input(self, idx, inputStream):
self._wsPDFilter.SetInput(inputStream)
def get_output_descriptions(self):
return (self._wsPDFilter.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._wsPDFilter.GetOutput()
def logic_to_config(self):
self._config.numberOfIterations = self._wsPDFilter.\
GetNumberOfIterations()
self._config.passBand = self._wsPDFilter.GetPassBand()
self._config.featureEdgeSmoothing = bool(
self._wsPDFilter.GetFeatureEdgeSmoothing())
self._config.boundarySmoothing = bool(
self._wsPDFilter.GetBoundarySmoothing())
self._config.non_manifold_smoothing = bool(
self._wsPDFilter.GetNonManifoldSmoothing())
def config_to_logic(self):
self._wsPDFilter.SetNumberOfIterations(self._config.numberOfIterations)
self._wsPDFilter.SetPassBand(self._config.passBand)
self._wsPDFilter.SetFeatureEdgeSmoothing(
self._config.featureEdgeSmoothing)
self._wsPDFilter.SetBoundarySmoothing(
self._config.boundarySmoothing)
self._wsPDFilter.SetNonManifoldSmoothing(
self._config.non_manifold_smoothing)
def execute_module(self):
self._wsPDFilter.Update()
# no streaming yet :) (underlying filter works with 2 streaming
# pieces, no other settings)
| Python |
# dumy __init__ so this directory can function as a package
| Python |
__author__ = 'Francois'
# PerturbPolyPoints.py by Francois Malan - 2012-12-06
# Randomly perturbs each polydata vertex by a uniformly sampled magnitude and random direction
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import vtk
import numpy
import math
import random
class PerturbPolyPoints(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self.sync_module_logic_with_config()
self._config.perturbation_magnitude = 0.15 #tolerance (distance) for determining if a point lies on a plane
self._config.use_gaussian = False
config_list = [
('Perturbation Magnitude:', 'perturbation_magnitude', 'base:float', 'text',
'The magnitude of the perturbation (upperlimit for uniform distribution, or twice the standard deviation for Gaussian distribution). '
'The 2x scaling ensures that the typical perturbation magnitudes are similar.'),
('Gaussian distribution:', 'use_gaussian', 'base:bool', 'checkbox',
'Should a Gaussian distribution be used instead of a uniform distribution?'),
]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self})
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)
def set_input(self, idx, input_stream):
if idx == 0:
self.source_poly = input_stream
def get_input_descriptions(self):
return ('vtkPolyData', )
def get_output_descriptions(self):
return ('vtkPolyData', )
def get_output(self, idx):
return self.output_poly
def _normalize(self, vector):
length = math.sqrt(numpy.dot(vector, vector))
if length == 0:
return numpy.array([1,0,0])
return vector / length
def _perturb_points(self, poly, magnitude):
assert isinstance(poly, vtk.vtkPolyData)
points = poly.GetPoints()
n = poly.GetNumberOfPoints()
for i in range(n):
point = points.GetPoint(i)
vector = numpy.array([random.random(),random.random(),random.random()]) - 0.5
direction = self._normalize(vector)
magnitude = 0.0
if not self._config.use_gaussian:
magnitude = random.random() * self._config.perturbation_magnitude
else:
magnitude = random.gauss(0.0, self._config.perturbation_magnitude/2.0)
vector = direction * magnitude
newpoint = numpy.array(point) + vector
points.SetPoint(i, (newpoint[0],newpoint[1],newpoint[2]))
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def execute_module(self):
self.output_poly = vtk.vtkPolyData()
self.output_poly.DeepCopy(self.source_poly)
self._perturb_points(self.output_poly, self._config.perturbation_magnitude) | Python |
# DicomAligner.py by Francois Malan - 2011-06-23
# Revised as version 2.0 on 2011-07-07
from module_base import ModuleBase
from module_mixins import NoConfigModuleMixin
from module_kits.misc_kit import misc_utils
import wx
import os
import vtk
import itk
import math
import numpy
class DICOMAligner(
NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
NoConfigModuleMixin.__init__(
self, {'Module (self)' : self})
self.sync_module_logic_with_config()
self._ir = vtk.vtkImageReslice()
self._ici = vtk.vtkImageChangeInformation()
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
NoConfigModuleMixin.close(self)
def set_input(self, idx, input_stream):
if idx == 0:
self._imagedata = input_stream
else:
self._metadata = input_stream
self._input = input_stream
def get_input_descriptions(self):
return ('vtkImageData (from DICOMReader port 0)', 'Medical metadata (from DICOMReader port 1)')
def get_output_descriptions(self):
return ('vtkImageData', )
def get_output(self, idx):
return self._output
def _convert_input(self):
'''
Performs the required transformation to match the image to the world coordinate system defined by medmeta
'''
# the first two columns of the direction cosines matrix represent
# the x,y axes of the DICOM slices in the patient's LPH space
# if we want to resample the images so that x,y are always LP
# the inverse should do the trick (transpose should also work as long as boths sets of axes
# is right-handed but let's stick to inverse for safety)
dcmatrix = vtk.vtkMatrix4x4()
dcmatrix.DeepCopy(self._metadata.direction_cosines)
dcmatrix.Invert()
origin = self._imagedata.GetOrigin()
spacing = self._imagedata.GetSpacing()
extent = self._imagedata.GetExtent()
# convert our new cosines to something we can give the ImageReslice
dcm = [[0,0,0] for _ in range(3)]
for col in range(3):
for row in range(3):
dcm[col][row] = dcmatrix.GetElement(row, col)
# do it.
self._ir.SetResliceAxesDirectionCosines(dcm[0], dcm[1], dcm[2])
self._ir.SetInput(self._imagedata)
self._ir.SetAutoCropOutput(1)
self._ir.SetInterpolationModeToCubic()
isotropic_sp = min(min(spacing[0],spacing[1]),spacing[2])
self._ir.SetOutputSpacing(isotropic_sp, isotropic_sp, isotropic_sp)
self._ir.Update()
output = self._ir.GetOutput()
#We now have to check whether the origin needs to be moved from its prior position
#Yes folks - the reslice operation screws up the origin and we must fix it.
#(Since the IPP is INDEPENDENT of the IOP, a reslice operation to fix the axes' orientation
# should not rotate the origin)
#
#The origin's coordinates (as provided by the DICOMreader) are expressed in PATIENT-LPH
#We are transforming the voxels (i.e. image coordiante axes)
# FROM IMAGE TO LPH coordinates. We must not transform the origin in this
# sense- only the image axes (and therefore voxels). However, vtkImageReslice
# (for some strange reason) transforms the origin according to the
# transformation matrix (?). So we need to reset this.
#Once the image is aligned to the LPH coordinate axes, a voxel(centre)'s LPH coordinates
# = origin + image_coordinates * spacing.
#But, there is a caveat.
# Since both image coordinates and spacing are positive, the origin must be at
# the "most negative" corner (in LPH terms). Even worse, if the LPH axes are not
# perpendicular relative to the original image axes, this "most negative" corner will
# lie outside of the original image volume (in a zero-padded region) - see AutoCropOutput.
# But the original origin is defined at the "most negative" corner in IMAGE
# coordinates(!). This means that the origin should, in most cases, be
# translated from its original position, depending on the relative LPH and
# image axes' orientations.
#
#The (x,y,z) components of the new origin are, independently, the most negative x,
#most negative y and most negative z LPH coordinates of the eight ORIGINAL IMAGE corners.
#To determine this we compute the eight corner coordinates and do a minimization.
#
#Remember that (in matlab syntax)
# p_world = dcm_matrix * diag(spacing)*p_image + origin
#for example: for a 90 degree rotation around the x axis this is
# [p_x] [ 1 0 0][nx*dx] [ox]
# [p_y] = [ 0 0 1][ny*dy] + [oy]
# [p_z] [ 0 -1 0][nz*dz] [oz]
#, where p is the LPH coordinates, d is the spacing, n is the image
# coordinates and o is the origin (IPP of the slice with the most negative IMAGE z coordinate).
originn = numpy.array(origin)
dcmn = numpy.array(dcm)
corners = numpy.zeros((3,8))
#first column of the DCM is a unit LPH-space vector in the direction of the first IMAGE axis, etc.
#From this it follows that the displacements along the full IMAGE's x, y and z extents are:
sx = spacing[0]*extent[1]*dcmn[:,0]
sy = spacing[1]*extent[3]*dcmn[:,1]
sz = spacing[2]*extent[5]*dcmn[:,2]
corners[:,0] = originn
corners[:,1] = originn + sx
corners[:,2] = originn + sy
corners[:,3] = originn + sx + sy
corners[:,4] = originn + sz
corners[:,5] = originn + sx + sz
corners[:,6] = originn + sy + sz
corners[:,7] = originn + sx + sy + sz
newOriginX = min(corners[0,:]);
newOriginY = min(corners[1,:]);
newOriginZ = min(corners[2,:]);
#Since we set the direction cosine matrix to unity we have to reset the
#axis labels array as well.
self._ici.SetInput(output)
self._ici.Update()
fd = self._ici.GetOutput().GetFieldData()
fd.RemoveArray('axis_labels_array')
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
fd.RemoveArray('axis_labels_array')
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
axis_labels_array.InsertNextValue(lut['R'])
axis_labels_array.InsertNextValue(lut['L'])
axis_labels_array.InsertNextValue(lut['A'])
axis_labels_array.InsertNextValue(lut['P'])
axis_labels_array.InsertNextValue(lut['F'])
axis_labels_array.InsertNextValue(lut['H'])
fd.AddArray(axis_labels_array)
self._ici.Update()
output = self._ici.GetOutput()
output.SetOrigin(newOriginX, newOriginY, newOriginZ)
self._output = output
def execute_module(self):
self._convert_input() | 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 |
# 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 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 NoConfigModuleMixin
import module_utils
import vtk
class transformPolyData(NoConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
self._transformPolyData = vtk.vtkTransformPolyDataFilter()
NoConfigModuleMixin.__init__(
self, {'vtkTransformPolyDataFilter' : self._transformPolyData})
module_utils.setup_vtk_object_progress(self, self._transformPolyData,
'Transforming geometry')
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._transformPolyData
def get_input_descriptions(self):
return ('vtkPolyData', 'vtkTransform')
def set_input(self, idx, inputStream):
if idx == 0:
self._transformPolyData.SetInput(inputStream)
else:
self._transformPolyData.SetTransform(inputStream)
def get_output_descriptions(self):
return (self._transformPolyData.GetOutput().GetClassName(), )
def get_output(self, idx):
return self._transformPolyData.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._transformPolyData.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 |
# todo:
# * vtkVolumeMapper::SetCroppingRegionPlanes(xmin,xmax,ymin,ymax,zmin,zmax)
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
class MIPRender(
ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# initialise our base class
ModuleBase.__init__(self, module_manager)
#for o in self._objectDict.values():
#
# setup some config defaults
self._config.threshold = 1250
self._config.interpolation = 0 # nearest
# this is not in the interface yet, change by introspection
self._config.mip_colour = (0.0, 0.0, 1.0)
config_list = [
('Threshold:', 'threshold', 'base:float', 'text',
'Used to generate transfer function if none is supplied'),
('Interpolation:', 'interpolation', 'base:int', 'choice',
'Linear (high quality, slower) or nearest neighbour (lower '
'quality, faster) interpolation',
('Nearest Neighbour', 'Linear'))]
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self})
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._otf
del self._ctf
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', 'transfer functions')
def set_input(self, idx, inputStream):
if idx == 0:
if inputStream is None:
# disconnect this way, else we get:
# obj._volume_mapper.SetInput(None)
# TypeError: ambiguous call, multiple overloaded methods match the arguments
self._volume_mapper.SetInputConnection(0, None)
else:
self._volume_mapper.SetInput(inputStream)
else:
pass
def get_output_descriptions(self):
return ('vtkVolume',)
def get_output(self, idx):
return self._volume
def logic_to_config(self):
self._config.interpolation = \
self._volume_property.GetInterpolationType()
def config_to_logic(self):
self._otf.RemoveAllPoints()
t = self._config.threshold
p1 = t - t / 10.0
p2 = t + t / 5.0
print "MIP: %.2f - %.2f" % (p1, p2)
self._otf.AddPoint(p1, 0.0)
self._otf.AddPoint(p2, 1.0)
self._otf.AddPoint(self._config.threshold, 1.0)
self._ctf.RemoveAllPoints()
self._ctf.AddHSVPoint(p1, 0.0, 0.0, 0.0)
self._ctf.AddHSVPoint(p2, *self._config.mip_colour)
self._volume_property.SetInterpolationType(self._config.interpolation)
def execute_module(self):
self._volume_mapper.Update()
def _create_pipeline(self):
# setup our pipeline
self._otf = vtk.vtkPiecewiseFunction()
self._ctf = vtk.vtkColorTransferFunction()
self._volume_property = vtk.vtkVolumeProperty()
self._volume_property.SetScalarOpacity(self._otf)
self._volume_property.SetColor(self._ctf)
self._volume_property.ShadeOn()
self._volume_property.SetAmbient(0.1)
self._volume_property.SetDiffuse(0.7)
self._volume_property.SetSpecular(0.2)
self._volume_property.SetSpecularPower(10)
self._volume_raycast_function = vtk.vtkVolumeRayCastMIPFunction()
self._volume_mapper = vtk.vtkVolumeRayCastMapper()
# can also used FixedPoint, but then we have to use:
# SetBlendModeToMaximumIntensity() and not SetVolumeRayCastFunction
#self._volume_mapper = vtk.vtkFixedPointVolumeRayCastMapper()
self._volume_mapper.SetVolumeRayCastFunction(
self._volume_raycast_function)
module_utils.setup_vtk_object_progress(self, self._volume_mapper,
'Preparing render.')
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 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 |
import gen_utils
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
EMODES = {
1:'Point seeded regions',
2:'Cell seeded regions',
3:'Specified regions',
4:'Largest region',
5:'All regions',
6:'Closest point region'
}
class polyDataConnect(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._polyDataConnect = vtk.vtkPolyDataConnectivityFilter()
# we're not going to use this feature just yet
self._polyDataConnect.ScalarConnectivityOff()
#
self._polyDataConnect.SetExtractionModeToPointSeededRegions()
module_utils.setup_vtk_object_progress(self, self._polyDataConnect,
'Finding connected surfaces')
# default is point seeded regions (we store zero-based)
self._config.extraction_mode = 0
self._config.colour_regions = 0
config_list = [
('Extraction mode:', 'extraction_mode', 'base:int',
'choice',
'What kind of connected regions should be extracted.',
[EMODES[i] for i in range(1,7)]),
('Colour regions:', 'colour_regions', 'base:int',
'checkbox',
'Should connected regions be coloured differently.')
]
# and the mixin constructor
ScriptedConfigModuleMixin.__init__(
self, config_list,
{'Module (self)' : self,
'vtkPolyDataConnectivityFilter' : self._polyDataConnect})
# 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._seedIds = []
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)
# don't forget to call the close() method of the vtkPipeline mixin
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._polyDataConnect
def get_input_descriptions(self):
return ('vtkPolyData', 'Seed points')
def set_input(self, idx, inputStream):
if idx == 0:
# will work for None and not-None
self._polyDataConnect.SetInput(inputStream)
else:
self._input_points = inputStream
def get_output_descriptions(self):
return (self._polyDataConnect.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._polyDataConnect.GetOutput()
def logic_to_config(self):
# extractionmodes in vtkPolyDataCF start at 1
# we store it as 0-based
emode = self._polyDataConnect.GetExtractionMode()
self._config.extraction_mode = emode - 1
self._config.colour_regions = \
self._polyDataConnect.GetColorRegions()
def config_to_logic(self):
# extractionmodes in vtkPolyDataCF start at 1
# we store it as 0-based
self._polyDataConnect.SetExtractionMode(
self._config.extraction_mode + 1)
self._polyDataConnect.SetColorRegions(
self._config.colour_regions)
def execute_module(self):
if self._polyDataConnect.GetExtractionMode() == 1:
self._sync_pdc_to_input_points()
self._polyDataConnect.Update()
def _sync_pdc_to_input_points(self):
# extract a list from the input points
temp_list = []
if self._input_points and self._polyDataConnect.GetInput():
for i in self._input_points:
id = self._polyDataConnect.GetInput().FindPoint(i['world'])
if id > 0:
temp_list.append(id)
if temp_list != self._seedIds:
self._seedIds = temp_list
# I'm hoping this clears the list
self._polyDataConnect.InitializeSeedList()
for seedId in self._seedIds:
self._polyDataConnect.AddSeed(seedId)
print "adding %d" % (seedId)
| 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 |
# 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 |
# 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 |
# __init__.py by Charl P. Botha <cpbotha@ieee.org>
# $Id$
# used to be module list, now dummy file
| Python |
# $Id: BMPRDR.py 1853 2006-02-01 17:16:28Z cpbotha $
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class BMPReader(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkBMPReader()
self._reader.SetFileDimensionality(3)
self._reader.SetAllow8BitBMP(1)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading BMP images.')
self._config.filePattern = '%03d.bmp'
self._config.firstSlice = 0
self._config.lastSlice = 1
self._config.spacing = (1,1,1)
self._config.fileLowerLeft = False
configList = [
('File pattern:', 'filePattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : wx.OPEN,
'fileMask' :
'BMP files (*.bmp)|*.bmp|All files (*.*)|*.*'}),
('First slice:', 'firstSlice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'lastSlice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'fileLowerLeft', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkBMPReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
#self._config.filePrefix = self._reader.GetFilePrefix()
self._config.filePattern = self._reader.GetFilePattern()
self._config.firstSlice = self._reader.GetFileNameSliceOffset()
e = self._reader.GetDataExtent()
self._config.lastSlice = self._config.firstSlice + e[5] - e[4]
self._config.spacing = self._reader.GetDataSpacing()
self._config.fileLowerLeft = bool(self._reader.GetFileLowerLeft())
def config_to_logic(self):
#self._reader.SetFilePrefix(self._config.filePrefix)
self._reader.SetFilePattern(self._config.filePattern)
self._reader.SetFileNameSliceOffset(self._config.firstSlice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.lastSlice -
self._config.firstSlice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.fileLowerLeft)
def execute_module(self):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class vtpRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkXMLPolyDataReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK Poly Data (*.vtp)|*.vtp|All files (*)|*',
{'vtkXMLPolyDataReader': self._reader})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading VTK PolyData')
self._viewFrame = None
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkPolyData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkPolyDataReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class metaImageRDR(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkMetaImageReader()
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading MetaImage data.')
self._config.filename = ''
configList = [
('File name:', 'filename', 'base:str', 'filebrowser',
'The name of the MetaImage file you want to load.',
{'fileMode' : wx.OPEN,
'fileMask' :
'MetaImage single file (*.mha)|*.mha|MetaImage separate header '
'(*.mhd)|*.mhd|All files (*.*)|*.*'})]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkMetaImageReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.filename = self._reader.GetFileName()
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def execute_module(self):
self._reader.Update()
| Python |
# $Id: vtpWRT.py 2401 2006-12-20 20:29:15Z cpbotha $
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import types
from modules.viewers.slice3dVWRmodules.selectedPoints import outputSelectedPoints
class points_reader(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'DeVIDE points (*.dvp)|*.dvp|All files (*)|*',
{'Module (self)': self},
fileOpen=True)
# set up some defaults
self._config.filename = ''
self._output_points = None
self.sync_module_logic_with_config()
def close(self):
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise NotImplementedError
def get_output_descriptions(self):
return ('DeVIDE points',)
def get_output(self, idx):
return self._output_points
def logic_to_config(self):
pass
def config_to_logic(self):
pass
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
if self._config.filename:
fh = file(self._config.filename)
ltext = fh.read()
fh.close()
points_list = eval(ltext)
self._output_points = outputSelectedPoints()
self._output_points.extend(points_list)
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class pngRDR(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkPNGReader()
self._reader.SetFileDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading PNG images.')
self._config.filePattern = '%03d.png'
self._config.firstSlice = 0
self._config.lastSlice = 1
self._config.spacing = (1,1,1)
self._config.fileLowerLeft = False
configList = [
('File pattern:', 'filePattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : wx.OPEN,
'fileMask' :
'PNG files (*.png)|*.png|All files (*.*)|*.*'}),
('First slice:', 'firstSlice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'lastSlice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'fileLowerLeft', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkPNGReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
#self._config.filePrefix = self._reader.GetFilePrefix()
self._config.filePattern = self._reader.GetFilePattern()
self._config.firstSlice = self._reader.GetFileNameSliceOffset()
e = self._reader.GetDataExtent()
self._config.lastSlice = self._config.firstSlice + e[5] - e[4]
self._config.spacing = self._reader.GetDataSpacing()
self._config.fileLowerLeft = bool(self._reader.GetFileLowerLeft())
def config_to_logic(self):
#self._reader.SetFilePrefix(self._config.filePrefix)
self._reader.SetFilePattern(self._config.filePattern)
self._reader.SetFileNameSliceOffset(self._config.firstSlice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.lastSlice -
self._config.firstSlice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.fileLowerLeft)
def execute_module(self):
self._reader.Update()
| Python |
from module_base import ModuleBase
from module_mixins import ScriptedConfigModuleMixin
import module_utils
import vtk
import wx
class JPEGReader(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkJPEGReader()
self._reader.SetFileDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading JPG images.')
self._config.filePattern = '%03d.jpg'
self._config.firstSlice = 0
self._config.lastSlice = 1
self._config.spacing = (1,1,1)
self._config.fileLowerLeft = False
configList = [
('File pattern:', 'filePattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : wx.OPEN,
'fileMask' :
'JPG files (*.jpg)|*.jpg|All files (*.*)|*.*'}),
('First slice:', 'firstSlice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'lastSlice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'fileLowerLeft', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkJPEGReader' : self._reader})
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._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
#self._config.filePrefix = self._reader.GetFilePrefix()
self._config.filePattern = self._reader.GetFilePattern()
self._config.firstSlice = self._reader.GetFileNameSliceOffset()
e = self._reader.GetDataExtent()
self._config.lastSlice = self._config.firstSlice + e[5] - e[4]
self._config.spacing = self._reader.GetDataSpacing()
self._config.fileLowerLeft = bool(self._reader.GetFileLowerLeft())
def config_to_logic(self):
#self._reader.SetFilePrefix(self._config.filePrefix)
self._reader.SetFilePattern(self._config.filePattern)
self._reader.SetFileNameSliceOffset(self._config.firstSlice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.lastSlice -
self._config.firstSlice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.fileLowerLeft)
def execute_module(self):
self._reader.Update()
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
from module_base import ModuleBase
from module_kits.misc_kit import misc_utils
from module_mixins import \
IntrospectModuleMixin
import module_utils
import gdcm
import vtk
import vtkgdcm
import wx
from module_kits.misc_kit.devide_types import MedicalMetaData
class DRDropTarget(wx.PyDropTarget):
def __init__(self, dicom_reader):
wx.PyDropTarget.__init__(self)
self._fdo = wx.FileDataObject()
self.SetDataObject(self._fdo)
self._dicom_reader = dicom_reader
def OnDrop(self, x, y):
return True
def OnData(self, x, y, d):
if self.GetData():
filenames = self._fdo.GetFilenames()
lb = self._dicom_reader._view_frame.dicom_files_lb
lb.Clear()
lb.AppendItems(filenames)
return d
class DICOMReader(IntrospectModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtkgdcm.vtkGDCMImageReader()
# NB NB NB: for now we're SWITCHING off the VTK-compatible
# Y-flip, until the X-mirror issues can be solved.
self._reader.SetFileLowerLeft(1)
self._ici = vtk.vtkImageChangeInformation()
self._ici.SetInputConnection(0, self._reader.GetOutputPort(0))
# create output MedicalMetaData and populate it with the
# necessary bindings.
mmd = MedicalMetaData()
mmd.medical_image_properties = \
self._reader.GetMedicalImageProperties()
mmd.direction_cosines = \
self._reader.GetDirectionCosines()
self._output_mmd = mmd
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading DICOM data')
self._view_frame = None
self._file_dialog = None
self._config.dicom_filenames = []
# if this is true, module will still try to load set even if
# IPP sorting fails by sorting images alphabetically
self._config.robust_spacing = False
self.sync_module_logic_with_config()
def close(self):
IntrospectModuleMixin.close(self)
# we just delete our binding. Destroying the view_frame
# should also take care of this one.
del self._file_dialog
if self._view_frame is not None:
self._view_frame.Destroy()
self._output_mmd.close()
del self._output_mmd
del self._reader
ModuleBase.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('DICOM data (vtkStructuredPoints)',
'Medical Meta Data')
def get_output(self, idx):
if idx == 0:
return self._ici.GetOutput()
elif idx == 1:
return self._output_mmd
def logic_to_config(self):
# we deliberately don't do any processing here, as we want to
# limit all DICOM parsing to the execute_module
pass
def config_to_logic(self):
# we deliberately don't add filenames to the reader here, as
# we would need to sort them, which would imply scanning all
# of them during this step
# we return False to indicate that we haven't made any changes
# to the underlying logic (so that the MetaModule knows it
# doesn't have to invalidate us after a call to
# config_to_logic)
return False
def view_to_config(self):
lb = self._view_frame.dicom_files_lb
# just clear out the current list
# and copy everything, only if necessary!
if self._config.dicom_filenames[:] == lb.GetStrings()[:]:
return False
else:
self._config.dicom_filenames[:] = lb.GetStrings()[:]
return True
def config_to_view(self):
# get listbox, clear it out, add filenames from the config
lb = self._view_frame.dicom_files_lb
if self._config.dicom_filenames[:] != lb.GetStrings()[:]:
lb.Clear()
lb.AppendItems(self._config.dicom_filenames)
def execute_module(self):
# have to cast to normal strings (from unicode)
filenames = [str(i) for i in self._config.dicom_filenames]
# make sure all is zeroed.
self._reader.SetFileName(None)
self._reader.SetFileNames(None)
# we only sort and derive slice-based spacing if there are
# more than 1 filenames
if len(filenames) > 1:
sorter = gdcm.IPPSorter()
sorter.SetComputeZSpacing(True)
sorter.SetZSpacingTolerance(1e-2)
ret = sorter.Sort(filenames)
alpha_sorted = False
if not ret:
if self._config.robust_spacing:
self._module_manager.log_warning(
'Could not sort DICOM filenames by IPP. Doing alphabetical sorting.')
filenames.sort()
alpha_sorted = True
else:
raise RuntimeError(
'Could not sort DICOM filenames before loading.')
if sorter.GetZSpacing() == 0.0 and not alpha_sorted:
msg = 'DICOM IPP sorting yielded incorrect results.'
raise RuntimeError(msg)
# then give the reader the sorted list of files
sa = vtk.vtkStringArray()
if alpha_sorted:
flist = filenames
else:
flist = sorter.GetFilenames()
for fn in flist:
sa.InsertNextValue(fn)
self._reader.SetFileNames(sa)
elif len(filenames) == 1:
self._reader.SetFileName(filenames[0])
else:
raise RuntimeError(
'No DICOM filenames to read.')
# now do the actual reading
self._reader.Update()
# see what the reader thinks the spacing is
spacing = list(self._reader.GetDataSpacing())
if len(filenames) > 1 and not alpha_sorted:
# after the reader has done its thing,
# impose derived spacing on the vtkImageChangeInformation
# (by default it takes the SpacingBetweenSlices, which is
# not always correct)
spacing[2] = sorter.GetZSpacing()
# single or multiple filenames, we have to set the correct
# output spacing on the image change information
print "SPACING: ", spacing
self._ici.SetOutputSpacing(spacing)
self._ici.Update()
# integrate DirectionCosines into output data ###############
# DirectionCosines: first two columns are X and Y in the LPH
# coordinate system
dc = self._reader.GetDirectionCosines()
x_cosine = \
dc.GetElement(0,0), dc.GetElement(1,0), dc.GetElement(2,0)
y_cosine = \
dc.GetElement(0,1), dc.GetElement(1,1), dc.GetElement(2,1)
# calculate plane normal (z axis) in LPH coordinate system by taking the cross product
norm = [0,0,0]
vtk.vtkMath.Cross(x_cosine, y_cosine, norm)
xl = misc_utils.major_axis_from_iop_cosine(x_cosine)
yl = misc_utils.major_axis_from_iop_cosine(y_cosine)
# vtkGDCMImageReader swaps the y (to fit the VTK convention),
# but does not flip the DirectionCosines here, so we do that.
# (only if the reader is flipping)
if yl and not self._reader.GetFileLowerLeft():
yl = tuple((yl[1], yl[0]))
zl = misc_utils.major_axis_from_iop_cosine(norm)
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
if xl and yl and zl:
# add this data as a vtkFieldData
fd = self._ici.GetOutput().GetFieldData()
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
for l in xl + yl + zl:
axis_labels_array.InsertNextValue(lut[l])
fd.AddArray(axis_labels_array)
def _create_view_frame(self):
import modules.readers.resources.python.DICOMReaderViewFrame
reload(modules.readers.resources.python.DICOMReaderViewFrame)
self._view_frame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.DICOMReaderViewFrame.\
DICOMReaderViewFrame)
# make sure the listbox is empty
self._view_frame.dicom_files_lb.Clear()
object_dict = {
'Module (self)' : self,
'vtkGDCMImageReader' : self._reader}
module_utils.create_standard_object_introspection(
self, self._view_frame, self._view_frame.view_frame_panel,
object_dict, None)
module_utils.create_eoca_buttons(self, self._view_frame,
self._view_frame.view_frame_panel)
# now add the event handlers
self._view_frame.add_files_b.Bind(wx.EVT_BUTTON,
self._handler_add_files_b)
self._view_frame.remove_files_b.Bind(wx.EVT_BUTTON,
self._handler_remove_files_b)
# also the drop handler
dt = DRDropTarget(self)
self._view_frame.dicom_files_lb.SetDropTarget(dt)
# follow ModuleBase convention to indicate that we now have
# a view
self.view_initialised = True
def view(self, parent_window=None):
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 _add_filenames_to_listbox(self, filenames):
# only add filenames that are not in there yet...
lb = self._view_frame.dicom_files_lb
# create new dictionary with current filenames as keys
dup_dict = {}.fromkeys(lb.GetStrings(), 1)
fns_to_add = [fn for fn in filenames
if fn not in dup_dict]
lb.AppendItems(fns_to_add)
def _handler_add_files_b(self, event):
if not self._file_dialog:
self._file_dialog = wx.FileDialog(
self._view_frame,
'Select files to add to the list', "", "",
"DICOM files (*.dcm)|*.dcm|DICOM files (*.img)|*.img|All files (*)|*",
wx.OPEN | wx.MULTIPLE)
if self._file_dialog.ShowModal() == wx.ID_OK:
new_filenames = self._file_dialog.GetPaths()
self._add_filenames_to_listbox(new_filenames)
def _handler_remove_files_b(self, event):
lb = self._view_frame.dicom_files_lb
sels = list(lb.GetSelections())
# we have to delete from the back to the front
sels.sort()
sels.reverse()
for sel in sels:
lb.Delete(sel)
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
import os
class vtkPolyDataRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Constructor (initialiser) for the PD reader.
This is almost standard code for most of the modules making use of
the FilenameViewModuleMixin mixin.
"""
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtk.vtkPolyDataReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK data (*.vtk)|*.vtk|All files (*)|*',
{'vtkPolyDataReader': self._reader})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading vtk polydata')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
# call the close method of the mixin
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
# equivalent to return ('vtkPolyData',)
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkPolyDataReader to try and execute (if there's a filename)
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class plyRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkPLYReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'(Stanford) Polygon File Format (*.ply)|*.ply|All files (*)|*',
{'vtkPLYReader': self._reader,
'Module (self)' : self})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading PLY PolyData')
# set up some defaults
self._config.filename = ''
# there is no view yet...
self._module_manager.sync_module_logic_with_config(self)
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkPolyData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkPLYReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update() | Python |
import gen_utils
from module_base import ModuleBase
from module_mixins import vtkPipelineConfigModuleMixin
from module_mixins import FileOpenDialogModuleMixin
import module_utils
import vtk
import wx
class rawVolumeRDR(ModuleBase,
vtkPipelineConfigModuleMixin,
FileOpenDialogModuleMixin):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkImageReader()
self._reader.SetFileDimensionality(3)
# FIXME: make configurable (or disable)
#self._reader.SetFileLowerLeft(1)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading raw volume data')
self._dataTypes = {'Double': vtk.VTK_DOUBLE,
'Float' : vtk.VTK_FLOAT,
'Long' : vtk.VTK_LONG,
'Unsigned Long' : vtk.VTK_UNSIGNED_LONG,
'Integer' : vtk.VTK_INT,
'Unsigned Integer' : vtk.VTK_UNSIGNED_INT,
'Short' : vtk.VTK_SHORT,
'Unsigned Short' : vtk.VTK_UNSIGNED_SHORT,
'Char' : vtk.VTK_CHAR,
'Unsigned Char' : vtk.VTK_UNSIGNED_CHAR}
self._viewFrame = None
# now setup some defaults before our sync
self._config.filename = ''
self._config.dataType = self._reader.GetDataScalarType()
# 1 is little endian
self._config.endianness = 1
self._config.headerSize = 0
self._config.extent = (0, 128, 0, 128, 0, 128)
self._config.spacing = (1.0, 1.0, 1.0)
self.sync_module_logic_with_config()
def close(self):
# close down the vtkPipeline stuff
vtkPipelineConfigModuleMixin.close(self)
# take out our view interface
if self._viewFrame is not None:
self._viewFrame.Destroy()
# get rid of our reference
del self._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception, 'rawVolumeRDR has no input!'
def get_output_descriptions(self):
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
# now setup some defaults before our sync
self._config.filename = self._reader.GetFileName()
self._config.dataType = self._reader.GetDataScalarType()
self._config.endianness = self._reader.GetDataByteOrder()
# it's going to try and calculate this... do we want this behaviour?
self._config.headerSize = self._reader.GetHeaderSize()
self._config.extent = self._reader.GetDataExtent()
self._config.spacing = self._reader.GetDataSpacing()
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
self._reader.SetDataScalarType(self._config.dataType)
self._reader.SetDataByteOrder(self._config.endianness)
self._reader.SetHeaderSize(self._config.headerSize)
self._reader.SetDataExtent(self._config.extent)
self._reader.SetDataSpacing(self._config.spacing)
def view_to_config(self):
if self._viewFrame is None:
self._createViewFrame()
self._config.filename = self._viewFrame.filenameText.GetValue()
# first get the selected string
dtcString = self._viewFrame.dataTypeChoice.GetStringSelection()
# this string MUST be in our dataTypes dictionary, get its value
self._config.dataType = self._dataTypes[dtcString]
# we have little endian first, but in VTK world it has to be 1
ebs = self._viewFrame.endiannessRadioBox.GetSelection()
self._config.endianness = not ebs
# try and convert headerSize control to int, if it doesn't work,
# use old value
try:
headerSize = int(self._viewFrame.headerSizeText.GetValue())
except:
headerSize = self._config.headerSize
self._config.headerSize = headerSize
# try and convert the string to a tuple
# yes, this is a valid away! see:
# http://mail.python.org/pipermail/python-list/1999-April/000546.html
try:
extent = eval(self._viewFrame.extentText.GetValue())
# now check that extent is a 6-element tuple
if type(extent) != tuple or len(extent) != 6:
raise Exception
# make sure that each element is an int
extent = tuple([int(i) for i in extent])
except:
# if this couldn't be converted to a 6-element int tuple, default
# to what's in config
extent = self._config.extent
self._config.extent = extent
try:
spacing = eval(self._viewFrame.spacingText.GetValue())
# now check that spacing is a 3-element tuple
if type(spacing) != tuple or len(spacing) != 3:
raise Exception
# make sure that each element is an FLOAT
spacing = tuple([float(i) for i in spacing])
except:
# if this couldn't be converted to a 6-element int tuple, default
# to what's in config
spacing = self._config.spacing
self._config.spacing = spacing
def config_to_view(self):
self._viewFrame.filenameText.SetValue(self._config.filename)
# now we have to find self._config.dataType in self._dataTypes
# I believe that I can assume .values() and .keys() to be consistent
# with each other (if I don't mutate the dictionary)
idx = self._dataTypes.values().index(self._config.dataType)
self._viewFrame.dataTypeChoice.SetStringSelection(
self._dataTypes.keys()[idx])
self._viewFrame.endiannessRadioBox.SetSelection(
not self._config.endianness)
self._viewFrame.headerSizeText.SetValue(str(self._config.headerSize))
self._viewFrame.extentText.SetValue(str(self._config.extent))
spacingText = "(%.3f, %.3f, %.3f)" % tuple(self._config.spacing)
self._viewFrame.spacingText.SetValue(spacingText)
def execute_module(self):
# get the reader to read :)
self._reader.Update()
def view(self, parent_window=None):
if self._viewFrame is None:
self._createViewFrame()
self.sync_module_view_with_logic()
# 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.readers.resources.python.rawVolumeRDRViewFrame
reload(modules.readers.resources.python.rawVolumeRDRViewFrame)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.rawVolumeRDRViewFrame.\
rawVolumeRDRViewFrame)
# bind the file browse button
wx.EVT_BUTTON(self._viewFrame,
self._viewFrame.browseButtonId,
self._browseButtonCallback)
# setup object introspection
objectDict = {'vtkImageReader' : self._reader}
module_utils.create_standard_object_introspection(
self, self._viewFrame, self._viewFrame.viewFramePanel,
objectDict, None)
# standard module buttons + events
module_utils.create_eoca_buttons(self, self._viewFrame,
self._viewFrame.viewFramePanel)
# finish setting up the output datatype choice
self._viewFrame.dataTypeChoice.Clear()
for aType in self._dataTypes.keys():
self._viewFrame.dataTypeChoice.Append(aType)
def _browseButtonCallback(self, event):
path = self.filenameBrowse(self._viewFrame,
"Select a raw volume filename",
"All files (*)|*")
if path != None:
self._viewFrame.filenameText.SetValue(path)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
class BMPReader:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of BMP files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d can be used for
example, in which case %d will be replaced by an integer zero padded to 3
digits, i.e. 000, 001, 002 etc. %d counts from the 'First slice' to the
'Last slice'.
"""
class DICOMReader:
kits = ['vtk_kit']
cats = ['Readers', 'Medical', 'DICOM']
help = """New module for reading DICOM data.
GDCM-based module for reading DICOM data. This is newer than
dicomRDR (which is DCMTK-based) and should be able to read more
kinds of data. The interface is deliberately less rich, as the
DICOMReader is supposed to be used in concert with the
DICOMBrowser.
If DICOMReader fails to read your DICOM data, please also try the
dicomRDR as its code is a few more years more mature than that of
the more flexible but younger DICOMReader.
"""
class dicomRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Module for reading DICOM data.
This is older DCMTK-based DICOM reader class. It used to be the
default in DeVIDE before the advent of the GDCM-based DICOMReader
in 8.5.
Add DICOM files (they may be from multiple series) by using the 'Add'
button on the view/config window. You can select multiple files in
the File dialog by holding shift or control whilst clicking. You
can also drag and drop files from a file or DICOM browser either
onto an existing dicomRDR or directly onto the Graph Editor
canvas.
"""
class JPEGReader:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of JPG (JPEG) files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d can be used for
example, in which case %d will be replaced by an integer zero padded to 3
digits, i.e. 000, 001, 002 etc. %d counts from the 'First slice' to the
'Last slice'.
"""
class metaImageRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads MetaImage format files.
MetaImage files have an .mha or .mhd file extension. .mha files are
single files containing header and data, whereas .mhd are separate headers
that refer to a separate raw data file.
"""
class objRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for OBJ polydata format.
"""
class plyRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for the Polygon File Format (Stanford Triangle Format) polydata format.
"""
class pngRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of PNG files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d can be used for
example, in which case %d will be replaced by an integer zero padded to 3
digits, i.e. 000, 001, 002 etc. %d counts from the 'First slice' to the
'Last slice'.
"""
class points_reader:
# BUG: empty kits list screws up dependency checking
kits = ['vtk_kit']
cats = ['Writers']
help = """TBD
"""
class rawVolumeRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Use this module to read raw data volumes from disk.
"""
class stlRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for simple STL triangle-based polydata format.
"""
class TIFFReader:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads a series of TIFF files.
Set the file pattern by making use of the file browsing dialog. Replace
the increasing index by a %d format specifier. %03d can be used for
example, in which case %d will be replaced by an integer zero padded to 3
digits, i.e. 000, 001, 002 etc. %d counts from the 'First slice' to the
'Last slice'.
"""
class vtiRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for VTK XML Image Data, the preferred format for all
VTK-compatible image data storage.
"""
class vtkPolyDataRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for legacy VTK polydata.
"""
class vtkStructPtsRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reader for legacy VTK structured points (image) data.
"""
class vtpRDR:
kits = ['vtk_kit']
cats = ['Readers']
help = """Reads VTK PolyData in the VTK XML format.
VTP is the preferred format for DeVIDE PolyData.
"""
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import gen_utils
from module_kits.misc_kit import misc_utils
import os
from module_base import ModuleBase
from module_mixins import \
IntrospectModuleMixin, FileOpenDialogModuleMixin
import module_utils
import stat
import wx
import vtk
import vtkdevide
import module_utils
class dicomRDR(ModuleBase,
IntrospectModuleMixin,
FileOpenDialogModuleMixin):
def __init__(self, module_manager):
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtkdevide.vtkDICOMVolumeReader()
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading DICOM data')
self._viewFrame = None
self._fileDialog = None
# setup some defaults
self._config.dicomFilenames = []
self._config.seriesInstanceIdx = 0
self._config.estimateSliceThickness = 1
# do the normal thang (down to logic, up again)
self.sync_module_logic_with_config()
def close(self):
if self._fileDialog is not None:
del self._fileDialog
# this will take care of all the vtkPipeline windows
IntrospectModuleMixin.close(self)
if self._viewFrame is not None:
# take care of our own window
self._viewFrame.Destroy()
# also remove the binding we have to our reader
del self._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('DICOM data (vtkStructuredPoints)',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.seriesInstanceIdx = self._reader.GetSeriesInstanceIdx()
# refresh our list of dicomFilenames
del self._config.dicomFilenames[:]
for i in range(self._reader.get_number_of_dicom_filenames()):
self._config.dicomFilenames.append(
self._reader.get_dicom_filename(i))
self._config.estimateSliceThickness = self._reader.\
GetEstimateSliceThickness()
def config_to_logic(self):
self._reader.SetSeriesInstanceIdx(self._config.seriesInstanceIdx)
# this will clear only the dicom_filenames_buffer without setting
# mtime of the vtkDICOMVolumeReader
self._reader.clear_dicom_filenames()
for fullname in self._config.dicomFilenames:
# this will simply add a file to the buffer list of the
# vtkDICOMVolumeReader (will not set mtime)
self._reader.add_dicom_filename(fullname)
# if we've added the same list as we added at the previous exec
# of apply_config(), the dicomreader is clever enough to know that
# it doesn't require an update. Yay me.
self._reader.SetEstimateSliceThickness(
self._config.estimateSliceThickness)
def view_to_config(self):
self._config.seriesInstanceIdx = self._viewFrame.si_idx_spin.GetValue()
lb = self._viewFrame.dicomFilesListBox
count = lb.GetCount()
filenames_init = []
for n in range(count):
filenames_init.append(lb.GetString(n))
# go through list of files in directory, perform trivial tests
# and create a new list of files
del self._config.dicomFilenames[:]
for filename in filenames_init:
# at the moment, we check that it's a regular file
if stat.S_ISREG(os.stat(filename)[stat.ST_MODE]):
self._config.dicomFilenames.append(filename)
if len(self._config.dicomFilenames) == 0:
wx.LogError('Empty directory specified, not attempting '
'change in config.')
self._config.estimateSliceThickness = self._viewFrame.\
estimateSliceThicknessCheckBox.\
GetValue()
def config_to_view(self):
# first transfer list of files to listbox
lb = self._viewFrame.dicomFilesListBox
lb.Clear()
for fn in self._config.dicomFilenames:
lb.Append(fn)
# at this stage, we can always assume that the logic is current
# with the config struct...
self._viewFrame.si_idx_spin.SetValue(self._config.seriesInstanceIdx)
# some information in the view does NOT form part of the config,
# but comes directly from the logic:
# we're going to be reading some information from the _reader which
# is only up to date after this call
self._reader.UpdateInformation()
# get current SeriesInstanceIdx from the DICOMReader
# FIXME: the frikking SpinCtrl does not want to update when we call
# SetValue()... we've now hard-coded it in wxGlade (still doesn't work)
self._viewFrame.si_idx_spin.SetValue(
int(self._reader.GetSeriesInstanceIdx()))
# try to get current SeriesInstanceIdx (this will run at least
# UpdateInfo)
si_uid = self._reader.GetSeriesInstanceUID()
if si_uid == None:
si_uid = "NONE"
self._viewFrame.si_uid_text.SetValue(si_uid)
msii = self._reader.GetMaximumSeriesInstanceIdx()
self._viewFrame.seriesInstancesText.SetValue(str(msii))
# also limit the spin-control
self._viewFrame.si_idx_spin.SetRange(0, msii)
sd = self._reader.GetStudyDescription()
if sd == None:
self._viewFrame.study_description_text.SetValue("NONE");
else:
self._viewFrame.study_description_text.SetValue(sd);
rp = self._reader.GetReferringPhysician()
if rp == None:
self._viewFrame.referring_physician_text.SetValue("NONE");
else:
self._viewFrame.referring_physician_text.SetValue(rp);
dd = self._reader.GetDataDimensions()
ds = self._reader.GetDataSpacing()
self._viewFrame.dimensions_text.SetValue(
'%d x %d x %d at %.2f x %.2f x %.2f mm / voxel' % tuple(dd + ds))
self._viewFrame.estimateSliceThicknessCheckBox.SetValue(
self._config.estimateSliceThickness)
def execute_module(self):
# get the vtkDICOMVolumeReader to try and execute
self._reader.Update()
# now get some metadata out and insert it in our output stream
# first determine axis labels based on IOP ####################
iop = self._reader.GetImageOrientationPatient()
row = iop[0:3]
col = iop[3:6]
# the cross product (plane normal) based on the row and col will
# also be in the LPH coordinate system
norm = [0,0,0]
vtk.vtkMath.Cross(row, col, norm)
xl = misc_utils.major_axis_from_iop_cosine(row)
yl = misc_utils.major_axis_from_iop_cosine(col)
zl = misc_utils.major_axis_from_iop_cosine(norm)
lut = {'L' : 0, 'R' : 1, 'P' : 2, 'A' : 3, 'F' : 4, 'H' : 5}
if xl and yl and zl:
# add this data as a vtkFieldData
fd = self._reader.GetOutput().GetFieldData()
axis_labels_array = vtk.vtkIntArray()
axis_labels_array.SetName('axis_labels_array')
for l in xl + yl + zl:
axis_labels_array.InsertNextValue(lut[l])
fd.AddArray(axis_labels_array)
# window/level ###############################################
def _createViewFrame(self):
import modules.readers.resources.python.dicomRDRViewFrame
reload(modules.readers.resources.python.dicomRDRViewFrame)
self._viewFrame = module_utils.instantiate_module_view_frame(
self, self._module_manager,
modules.readers.resources.python.dicomRDRViewFrame.\
dicomRDRViewFrame)
# make sure the listbox is empty
self._viewFrame.dicomFilesListBox.Clear()
objectDict = {'dicom reader' : self._reader}
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)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.addButton.GetId(),
self._handlerAddButton)
wx.EVT_BUTTON(self._viewFrame, self._viewFrame.removeButton.GetId(),
self._handlerRemoveButton)
# follow ModuleBase convention to indicate that we now have
# a view
self.view_initialised = True
def view(self, parent_window=None):
if self._viewFrame is None:
self._createViewFrame()
self.sync_module_view_with_logic()
self._viewFrame.Show(True)
self._viewFrame.Raise()
def _handlerAddButton(self, event):
if not self._fileDialog:
self._fileDialog = wx.FileDialog(
self._module_manager.get_module_view_parent_window(),
'Select files to add to the list', "", "",
"DICOM files (*.dcm)|*.dcm|DICOM files (*.img)|*.img|All files (*)|*",
wx.OPEN | wx.MULTIPLE)
if self._fileDialog.ShowModal() == wx.ID_OK:
newFilenames = self._fileDialog.GetPaths()
# first check for duplicates in the listbox
lb = self._viewFrame.dicomFilesListBox
count = lb.GetCount()
oldFilenames = []
for n in range(count):
oldFilenames.append(lb.GetString(n))
filenamesToAdd = [fn for fn in newFilenames
if fn not in oldFilenames]
for fn in filenamesToAdd:
lb.Append(fn)
def _handlerRemoveButton(self, event):
"""Remove all selected filenames from the internal list.
"""
lb = self._viewFrame.dicomFilesListBox
sels = list(lb.GetSelections())
# we have to delete from the back to the front
sels.sort()
sels.reverse()
# build list
for sel in sels:
lb.Delete(sel)
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# dumy __init__ so this directory can function as a package
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
import os
class objRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Constructor (initialiser) for the PD reader.
This is almost standard code for most of the modules making use of
the FilenameViewModuleMixin mixin.
"""
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtk.vtkOBJReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'Wavefront OBJ data (*.obj)|*.obj|All files (*)|*',
{'vtkOBJReader': self._reader})
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading Wavefront OBJ data')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
# call the close method of the mixin
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
# equivalent to return ('vtkPolyData',)
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkSTLReader to try and execute (if there's a filename)
if len(self._reader.GetFileName()):
self._reader.Update()
| 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, WX_OPEN
import module_utils
import vtk
class TIFFReader(ScriptedConfigModuleMixin, ModuleBase):
def __init__(self, module_manager):
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkTIFFReader()
self._reader.SetFileDimensionality(3)
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading TIFF images.')
self._config.file_pattern = '%03d.tif'
self._config.first_slice = 0
self._config.last_slice = 1
self._config.spacing = (1,1,1)
self._config.file_lower_left = False
configList = [
('File pattern:', 'file_pattern', 'base:str', 'filebrowser',
'Filenames will be built with this. See module help.',
{'fileMode' : WX_OPEN,
'fileMask' :
'TIFF files (*.tif or *.tiff)|*.tif;*.tiff|All files (*.*)|*.*'}),
('First slice:', 'first_slice', 'base:int', 'text',
'%d will iterate starting at this number.'),
('Last slice:', 'last_slice', 'base:int', 'text',
'%d will iterate and stop at this number.'),
('Spacing:', 'spacing', 'tuple:float,3', 'text',
'The 3-D spacing of the resultant dataset.'),
('Lower left:', 'file_lower_left', 'base:bool', 'checkbox',
'Image origin at lower left? (vs. upper left)')]
ScriptedConfigModuleMixin.__init__(
self, configList,
{'Module (self)' : self,
'vtkTIFFReader' : self._reader})
self.sync_module_logic_with_config()
def close(self):
# this will take care of all display thingies
ScriptedConfigModuleMixin.close(self)
ModuleBase.close(self)
# get rid of our reference
del self._reader
def get_input_descriptions(self):
return ()
def set_input(self, idx, inputStream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
self._config.file_pattern = self._reader.GetFilePattern()
self._config.first_slice = self._reader.GetFileNameSliceOffset()
e = self._reader.GetDataExtent()
self._config.last_slice = self._config.first_slice + e[5] - e[4]
self._config.spacing = self._reader.GetDataSpacing()
self._config.file_lower_left = bool(self._reader.GetFileLowerLeft())
def config_to_logic(self):
self._reader.SetFilePattern(self._config.file_pattern)
self._reader.SetFileNameSliceOffset(self._config.first_slice)
self._reader.SetDataExtent(0,0,0,0,0,
self._config.last_slice -
self._config.first_slice)
self._reader.SetDataSpacing(self._config.spacing)
self._reader.SetFileLowerLeft(self._config.file_lower_left)
def execute_module(self):
self._reader.Update()
def streaming_execute_module(self):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class vtiRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkXMLImageDataReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK Image Data (*.vti)|*.vti|All files (*)|*',
{'vtkXMLImageDataReader': self._reader,
'Module (self)' : self})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading VTK ImageData')
# set up some defaults
self._config.filename = ''
# there is no view yet...
self._module_manager.sync_module_logic_with_config(self)
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkImageData',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkPolyDataReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update()
def streaming_execute_module(self):
if len(self._reader.GetFileName()):
self._reader.UpdateInformation()
self._reader.GetOutput().SetUpdateExtentToWholeExtent()
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
import os
class stlRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
"""Constructor (initialiser) for the PD reader.
This is almost standard code for most of the modules making use of
the FilenameViewModuleMixin mixin.
"""
# call the constructor in the "base"
ModuleBase.__init__(self, module_manager)
# setup necessary VTK objects
self._reader = vtk.vtkSTLReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'STL data (*.stl)|*.stl|All files (*)|*',
{'vtkSTLReader': self._reader})
module_utils.setup_vtk_object_progress(self, self._reader,
'Reading STL data')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
# call the close method of the mixin
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
# equivalent to return ('vtkPolyData',)
return (self._reader.GetOutput().GetClassName(),)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkSTLReader to try and execute (if there's a filename)
if len(self._reader.GetFileName()):
self._reader.Update()
| Python |
# $Id$
from module_base import ModuleBase
from module_mixins import FilenameViewModuleMixin
import module_utils
import vtk
class vtkStructPtsRDR(FilenameViewModuleMixin, ModuleBase):
def __init__(self, module_manager):
# call parent constructor
ModuleBase.__init__(self, module_manager)
self._reader = vtk.vtkStructuredPointsReader()
# ctor for this specific mixin
FilenameViewModuleMixin.__init__(
self,
'Select a filename',
'VTK data (*.vtk)|*.vtk|All files (*)|*',
{'vtkStructuredPointsReader': self._reader})
module_utils.setup_vtk_object_progress(
self, self._reader,
'Reading vtk structured points data')
# set up some defaults
self._config.filename = ''
self.sync_module_logic_with_config()
def close(self):
del self._reader
FilenameViewModuleMixin.close(self)
def get_input_descriptions(self):
return ()
def set_input(self, idx, input_stream):
raise Exception
def get_output_descriptions(self):
return ('vtkStructuredPoints',)
def get_output(self, idx):
return self._reader.GetOutput()
def logic_to_config(self):
filename = self._reader.GetFileName()
if filename == None:
filename = ''
self._config.filename = filename
def config_to_logic(self):
self._reader.SetFileName(self._config.filename)
def view_to_config(self):
self._config.filename = self._getViewFrameFilename()
def config_to_view(self):
self._setViewFrameFilename(self._config.filename)
def execute_module(self):
# get the vtkPolyDataReader to try and execute
if len(self._reader.GetFileName()):
self._reader.Update()
| 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 |
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 |
# $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 |
# 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 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 |
# 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 |
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 |
# $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 |
# 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 |
# 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 |
# 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 |
# 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 |
# 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 |
# 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 |
# 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 |
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 |
# 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 |
# 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 |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
# I could have done this with just a module variable, but I found this
# Borg thingy too nice not to use. See:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/66531
class CounterBorg:
"""Borg-pattern (similar to a Singleton) for maintaining a
monotonically increasing counter.
Instantiate this anywhere, and call get() to return and increment
the increasing counter. DeVIDE uses this to stamp modified and
execute times of modules.
"""
# we start with 1, so that client code can init to 0 and guarantee
# an initial invalid state. The counter is explicitly long, this
# gives us unlimited precision (up to your memory limits, YEAH!)
__shared_state = {'counter' : 1L}
def __init__(self):
self.__dict__ = self.__shared_state
def get(self):
c = self.counter
self.counter += 1
return c
def counter():
return CounterBorg().get()
| 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 ConfigParser
import sys, os, fnmatch
import re
import copy
import gen_utils
import glob
from meta_module import MetaModule
import modules
import mutex
from random import choice
from module_base import DefaultConfigClass
import time
import types
import traceback
# some notes with regards to extra module state/logic required for scheduling
# * in general, execute_module()/transfer_output()/etc calls do exactly that
# when called, i.e. they don't automatically cache. The scheduler should
# take care of caching by making the necessary isModified() or
# shouldTransfer() calls. The reason for this is so that the module
# actions can be forced
#
# notes with regards to execute on change:
# * devide.py should register a "change" handler with the ModuleManager.
# I've indicated places with "execute on change" where I think this
# handler should be invoked. devide.py can then invoke the scheduler.
#########################################################################
class ModuleManagerException(Exception):
pass
#########################################################################
class ModuleSearch:
"""Class for doing relative fast searches through module metadata.
@author Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self):
# dict of dicts of tuple, e.g.:
# {'isosurface' : {('contour', 'keywords') : 1,
# ('marching', 'help') : 1} ...
self.search_dict = {}
self.previous_partial_text = ''
self.previous_results = None
def build_search_index(self, available_modules, available_segments):
"""Build search index given a list of available modules and segments.
@param available_modules: available modules dictionary from module
manager with module metadata classes as values.
@param available_segments: simple list of segments.
"""
self.search_dict.clear()
def index_field(index_name, mi_class, field_name, split=False):
try:
field = getattr(mi_class, field_name)
except AttributeError:
pass
else:
if split:
iter_list = field.split()
else:
iter_list = field
for w in iter_list:
wl = w.lower()
if wl not in self.search_dict:
self.search_dict[wl] = {(index_name,
field_name) : 1}
else:
self.search_dict[wl][(index_name,
field_name)] = 1
for module_name in available_modules:
mc = available_modules[module_name]
index_name = 'module:%s' % (module_name,)
short_module_name = mc.__name__.lower()
if short_module_name not in self.search_dict:
self.search_dict[short_module_name] = {(index_name, 'name') :
1}
else:
# we don't have to increment, there can be only one unique
# complete module_name
self.search_dict[short_module_name][(index_name, 'name')] = 1
index_field(index_name, mc, 'keywords')
index_field(index_name, mc, 'help', True)
for segment_name in available_segments:
index_name = 'segment:%s' % (segment_name,)
# segment name's are unique by definition (complete file names)
self.search_dict[segment_name] = {(index_name, 'name') : 1}
def find_matches(self, partial_text):
"""Do partial text (containment) search through all module names,
help and keywords.
Simple caching is currently done. Each space-separated word in
partial_text is searched for and results are 'AND'ed.
@returns: a list of unique tuples consisting of (modulename,
where_found) where where_found is 'name', 'keywords' or 'help'
"""
# cache results in case the user asks for exactly the same
if partial_text == self.previous_partial_text:
return self.previous_results
partial_words = partial_text.lower().split()
# dict mapping from full.module.name -> {'where_found' : 1, 'wf2' : 1}
# think about optimising this with a bit mask rather; less flexible
# but saves space and is at least as fast.
def find_one_word(search_word):
"""Searches for all partial / containment matches with
search_word.
@returns: search_results dict mapping from module name to
dictionary with where froms as keys and 1s as values.
"""
search_results = {}
for w in self.search_dict:
if w.find(search_word) >= 0:
# we can have partial matches with more than one key
# returning the same location, so we stuff results in a
# dict too to consolidate results
for k in self.search_dict[w].keys():
# k[1] is where_found, k[0] is module_name
if k[0] not in search_results:
search_results[k[0]] = {k[1] : 1}
else:
search_results[k[0]][k[1]] = 1
return search_results
# search using each of the words in the given list
search_results_list = []
for search_word in partial_words:
search_results_list.append(find_one_word(search_word))
# if more than one word, combine the results;
# a module + where_from result is only shown if ALL words occur in
# that specific module + where_from.
sr0 = search_results_list[0]
srl_len = len(search_results_list)
if srl_len > 1:
# will create brand-new combined search_results dict
search_results = {}
# iterate through all module names in the first word's results
for module_name in sr0:
# we will only process a module_name if it occurs in the
# search results of ALL search words
all_found = True
for sr in search_results_list[1:]:
if module_name not in sr:
all_found = False
break
# now only take results where ALL search words occur
# in the same where_from of a specific module
if all_found:
temp_finds = {}
for sr in search_results_list:
# sr[module_name] is a dict with where_founds as keys
# by definition (dictionary) all where_founds are
# unique per sr[module_name]
for i in sr[module_name].keys():
if i in temp_finds:
temp_finds[i] += 1
else:
temp_finds[i] = 1
# extract where_froms for which the number of hits is
# equal to the number of words.
temp_finds2 = [wf for wf in temp_finds.keys() if
temp_finds[wf] == srl_len]
# make new dictionary from temp_finds2 list as keys,
# 1 as value
search_results[module_name] = dict.fromkeys(temp_finds2,1)
else:
# only a single word was searched for.
search_results = sr0
self.previous_partial_text = partial_text
rl = search_results
self.previous_results = rl
return rl
#########################################################################
class PickledModuleState:
def __init__(self):
self.module_config = DefaultConfigClass()
# e.g. modules.Viewers.histogramSegment
self.module_name = None
# this is the unique name of the module, e.g. dvm15
self.instance_name = None
#########################################################################
class PickledConnection:
def __init__(self, source_instance_name=None, output_idx=None,
target_instance_name=None, input_idx=None, connection_type=None):
self.source_instance_name = source_instance_name
self.output_idx = output_idx
self.target_instance_name = target_instance_name
self.input_idx = input_idx
self.connection_type = connection_type
#########################################################################
class ModuleManager:
"""This class in responsible for picking up new modules in the modules
directory and making them available to the rest of the program.
@todo: we should split this functionality into a ModuleManager and
networkManager class. One ModuleManager per processing node,
global networkManager to coordinate everything.
@todo: ideally, ALL module actions should go via the MetaModule.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, devide_app):
"""Initialise module manager by fishing .py devide modules from
all pertinent directories.
"""
self._devide_app = devide_app
# module dictionary, keyed on instance... cool.
# values are MetaModules
self._module_dict = {}
appdir = self._devide_app.get_appdir()
self._modules_dir = os.path.join(appdir, 'modules')
#sys.path.insert(0,self._modules_dir)
self._userModules_dir = os.path.join(appdir, 'userModules')
############################################################
# initialise module Kits - Kits are collections of libraries
# that modules can depend on. The Kits also make it possible
# for us to write hooks for when these libraries are imported
import module_kits
module_kits.load(self)
# binding to module that can be used without having to do
# import module_kits
self.module_kits = module_kits
##############################################################
self.module_search = ModuleSearch()
# make first scan of available modules
self.scan_modules()
# auto_execute mode, still need to link this up with the GUI
self.auto_execute = True
# this is a list of modules that have the ability to start a network
# executing all by themselves and usually do... when we break down
# a network, we should take these out first. when we build a network
# we should put them down last
# slice3dVWRs must be connected LAST, histogramSegment second to last
# and all the rest before them
self.consumerTypeTable = {'slice3dVWR' : 5,
'histogramSegment' : 4}
# we'll use this to perform mutex-based locking on the progress
# callback... (there SHOULD only be ONE ModuleManager instance)
self._inProgressCallback = mutex.mutex()
def refresh_module_kits(self):
"""Go through list of imported module kits, reload each one, and
also call its refresh() method if available.
This means a kit author can work on a module_kit and just refresh
when she wants her changes to be available. However, the kit must
have loaded successfully at startup, else no-go.
"""
for module_kit in self.module_kits.module_kit_list:
kit = getattr(self.module_kits, module_kit)
try:
refresh_method = getattr(kit, "refresh")
except AttributeError:
pass
else:
try:
reload(kit)
refresh_method()
except Exception, e:
self._devide_app.log_error_with_exception(
'Unable to refresh module_kit %s: '
'%s. Continuing...' %
(module_kit, str(e)))
else:
self.set_progress(100, 'Refreshed %s.' % (module_kit,))
def close(self):
"""Iterates through each module and closes it.
This is only called during devide application shutdown.
"""
self.delete_all_modules()
def delete_all_modules(self):
"""Deletes all modules.
This is usually only called during the offline mode of operation. In
view mode, the GraphEditor takes care of the deletion of all networks.
"""
# this is fine because .items() makes a copy of the dict
for mModule in self._module_dict.values():
print "Deleting %s (%s) >>>>>" % \
(mModule.instance_name,
mModule.instance.__class__.__name__)
try:
self.delete_module(mModule.instance)
except Exception, e:
# we can't allow a module to stop us
print "Error deleting %s (%s): %s" % \
(mModule.instance_name,
mModule.instance.__class__.__name__,
str(e))
print "FULL TRACE:"
traceback.print_exc()
def apply_module_view_to_logic(self, instance):
"""Interface method that can be used by clients to transfer module
view to underlying logic.
This is called by module_utils (the ECASH button handlers) and thunks
through to the relevant MetaModule call.
"""
mModule = self._module_dict[instance]
try:
# these two MetaModule wrapper calls will take care of setting
# the modified flag / time correctly
if self._devide_app.view_mode:
# only in view mode do we call this transfer
mModule.view_to_config()
mModule.config_to_logic()
# we round-trip so that view variables that are dependent on
# the effective changes to logic and/or config can update
instance.logic_to_config()
if self._devide_app.view_mode:
instance.config_to_view()
except Exception, e:
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
def sync_module_logic_with_config(self, instance):
"""Method that should be called during __init__ for all (view and
non-view) modules, after the config structure has been set.
In the view() method, or after having setup the view in view-modules,
also call syncModuleViewWithLogic()
"""
instance.config_to_logic()
instance.logic_to_config()
def sync_module_view_with_config(self, instance):
"""If DeVIDE is in view model, transfor config information to view
and back again. This is called AFTER sync_module_logic_with_config(),
usually in the module view() method after createViewFrame().
"""
if self._devide_app.view_mode:
# in this case we don't round trip, view shouldn't change
# things that affect the config.
instance.config_to_view()
def sync_module_view_with_logic(self, instance):
"""Interface method that can be used by clients to transfer config
information from the underlying module logic (model) to the view.
At the moment used by standard ECASH handlers.
"""
try:
instance.logic_to_config()
# we only do the view transfer if DeVIDE is in the correct mode
if self._devide_app.view_mode:
instance.config_to_view()
except Exception, e:
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
syncModuleViewWithLogic = sync_module_view_with_logic
def blockmodule(self, meta_module):
meta_module.blocked = True
def unblockmodule(self, meta_module):
meta_module.blocked = False
def log_error(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_error(message)
def log_error_list(self, message_list):
self._devide_app.log_error_list(message_list)
def log_error_with_exception(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_error_with_exception(message)
def log_info(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_info(message)
def log_message(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_message(message)
def log_warning(self, message):
"""Convenience method that can be used by modules.
"""
self._devide_app.log_warning(message)
def scan_modules(self):
"""(Re)Check the modules directory for *.py files and put them in
the list self.module_files.
"""
# this is a dict mapping from full module name to the classes as
# found in the module_index.py files
self._available_modules = {}
appDir = self._devide_app.get_appdir()
# module path without trailing slash
modulePath = self.get_modules_dir()
# search through modules hierarchy and pick up all module_index files
####################################################################
module_indices = []
def miwFunc(arg, dirname, fnames):
"""arg is top-level module path.
"""
module_path = arg
for fname in fnames:
mi_full_name = os.path.join(dirname, fname)
if not fnmatch.fnmatch(fname, 'module_index.py'):
continue
# e.g. /viewers/module_index
mi2 = os.path.splitext(
mi_full_name.replace(module_path, ''))[0]
# e.g. .viewers.module_index
mim = mi2.replace(os.path.sep, '.')
# remove . before
if mim.startswith('.'):
mim = mim[1:]
# special case: modules in the central devide
# module dir should be modules.viewers.module_index
# this is mostly for backward compatibility
if module_path == modulePath:
mim = 'modules.%s' % (mim)
module_indices.append(mim)
os.path.walk(modulePath, miwFunc, arg=modulePath)
for emp in self.get_app_main_config().extra_module_paths:
# make sure there are no extra spaces at the ends, as well
# as normalize and absolutize path (haha) for this
# platform
emp = os.path.abspath(emp.strip())
if emp and os.path.exists(emp):
# make doubly sure we only process an EMP if it's
# really there
if emp not in sys.path:
sys.path.insert(0,emp)
os.path.walk(emp, miwFunc, arg=emp)
# iterate through the moduleIndices, building up the available
# modules list.
import module_kits # we'll need this to check available kits
failed_mis = {}
for mim in module_indices:
# mim is importable module_index spec, e.g.
# modules.viewers.module_index
# if this thing was imported before, we have to remove it, else
# classes that have been removed from the module_index file
# will still appear after the reload.
if mim in sys.modules:
del sys.modules[mim]
try:
# now we can import
__import__(mim, globals(), locals())
except Exception, e:
# make a list of all failed moduleIndices
failed_mis[mim] = sys.exc_info()
msgs = gen_utils.exceptionToMsgs()
# and log them as mesages
self._devide_app.log_info(
'Error loading %s: %s.' % (mim, str(e)))
for m in msgs:
self._devide_app.log_info(m.strip(), timeStamp=False)
# we don't want to throw an exception here, as that would
# mean that a singe misconfigured module_index file can
# prevent the whole scan_modules process from completing
# so we'll report on errors here and at the end
else:
# reload, as this could be a run-time rescan
m = sys.modules[mim]
reload(m)
# find all classes in the imported module
cs = [a for a in dir(m)
if type(getattr(m,a)) == types.ClassType]
# stuff these classes, keyed on the module name that they
# represent, into the modules list.
for a in cs:
# a is the name of the class
c = getattr(m,a)
module_deps = True
for kit in c.kits:
if kit not in module_kits.module_kit_list:
module_deps = False
break
if module_deps:
module_name = mim.replace('module_index', a)
self._available_modules[module_name] = c
# we should move this functionality to the graphEditor. "segments"
# are _probably_ only valid there... alternatively, we should move
# the concept here
segmentList = []
def swFunc(arg, dirname, fnames):
segmentList.extend([os.path.join(dirname, fname)
for fname in fnames
if fnmatch.fnmatch(fname, '*.dvn')])
os.path.walk(os.path.join(appDir, 'segments'), swFunc, arg=None)
# this is purely a list of segment filenames
self.availableSegmentsList = segmentList
# self._available_modules is a dict keyed on module_name with
# module description class as value
self.module_search.build_search_index(self._available_modules,
self.availableSegmentsList)
# report on accumulated errors - this is still a non-critical error
# so we don't throw an exception.
if len(failed_mis) > 0:
failed_indices = '\n'.join(failed_mis.keys())
self._devide_app.log_error(
'The following module indices failed to load '
'(see message log for details): \n%s' \
% (failed_indices,))
self._devide_app.log_info(
'%d modules and %d segments scanned.' %
(len(self._available_modules), len(self.availableSegmentsList)))
########################################################################
def get_appdir(self):
return self._devide_app.get_appdir()
def get_app_main_config(self):
return self._devide_app.main_config
def get_available_modules(self):
"""Return the available_modules, a dictionary keyed on fully qualified
module name (e.g. modules.Readers.vtiRDR) with values the classes
defined in module_index files.
"""
return self._available_modules
def get_instance(self, instance_name):
"""Given the unique instance name, return the instance itself.
If the module doesn't exist, return None.
"""
found = False
for instance, mModule in self._module_dict.items():
if mModule.instance_name == instance_name:
found = True
break
if found:
return mModule.instance
else:
return None
def get_instance_name(self, instance):
"""Given the actual instance, return its unique instance. If the
instance doesn't exist in self._module_dict, return the currently
halfborn instance.
"""
try:
return self._module_dict[instance].instance_name
except Exception:
return self._halfBornInstanceName
def get_meta_module(self, instance):
"""Given an instance, return the corresponding meta_module.
@param instance: the instance whose meta_module should be returned.
@return: meta_module corresponding to instance.
@raise KeyError: this instance doesn't exist in the module_dict.
"""
return self._module_dict[instance]
def get_modules_dir(self):
return self._modules_dir
def get_module_view_parent_window(self):
# this could change
return self.get_module_view_parent_window()
def get_module_spec(self, module_instance):
"""Given a module instance, return the full module spec.
"""
return 'module:%s' % (module_instance.__class__.__module__,)
def get_module_view_parent_window(self):
"""Get parent window for module windows.
THIS METHOD WILL BE DEPRECATED. The ModuleManager and view-less
(back-end) modules shouldn't know ANYTHING about windows or UI
aspects.
"""
try:
return self._devide_app.get_interface().get_main_window()
except AttributeError:
# the interface has no main_window
return None
def create_module(self, fullName, instance_name=None):
"""Try and create module fullName.
@param fullName: The complete module spec below application directory,
e.g. modules.Readers.hdfRDR.
@return: module_instance if successful.
@raises ModuleManagerException: if there is a problem creating the
module.
"""
if fullName not in self._available_modules:
raise ModuleManagerException(
'%s is not available in the current Module Manager / '
'Kit configuration.' % (fullName,))
try:
# think up name for this module (we have to think this up now
# as the module might want to know about it whilst it's being
# constructed
instance_name = self._make_unique_instance_name(instance_name)
self._halfBornInstanceName = instance_name
# perform the conditional import/reload
self.import_reload(fullName)
# import_reload requires this afterwards for safety reasons
exec('import %s' % fullName)
# in THIS case, there is a McMillan hook which'll tell the
# installer about all the devide modules. :)
ae = self.auto_execute
self.auto_execute = False
try:
# then instantiate the requested class
module_instance = None
exec(
'module_instance = %s.%s(self)' % (fullName,
fullName.split('.')[-1]))
finally:
# do the following in all cases:
self.auto_execute = ae
# if there was an exception, it will now be re-raised
if hasattr(module_instance, 'PARTS_TO_INPUTS'):
pti = module_instance.PARTS_TO_INPUTS
else:
pti = None
if hasattr(module_instance, 'PARTS_TO_OUTPUTS'):
pto = module_instance.PARTS_TO_OUTPUTS
else:
pto = None
# and store it in our internal structures
self._module_dict[module_instance] = MetaModule(
module_instance, instance_name, fullName, pti, pto)
# it's now fully born ;)
self._halfBornInstanceName = None
except ImportError, e:
# we re-raise with the three argument form to retain full
# trace information.
es = "Unable to import module %s: %s" % (fullName, str(e))
raise ModuleManagerException, es, sys.exc_info()[2]
except Exception, e:
es = "Unable to instantiate module %s: %s" % (fullName, str(e))
raise ModuleManagerException, es, sys.exc_info()[2]
# return the instance
return module_instance
def import_reload(self, fullName):
"""This will import and reload a module if necessary. Use this only
for things in modules or userModules.
If we're NOT running installed, this will run import on the module.
If it's not the first time this module is imported, a reload will
be run straight after.
If we're running installed, reloading only makes sense for things in
userModules, so it's only done for these modules. At the moment,
the stock Installer reload() is broken. Even with my fixes, it doesn't
recover memory used by old modules, see:
http://trixie.triqs.com/pipermail/installer/2003-May/000303.html
This is one of the reasons we try to avoid unnecessary reloads.
You should use this as follows:
ModuleManager.import_reloadModule('full.path.to.my.module')
import full.path.to.my.module
so that the module is actually brought into the calling namespace.
import_reload used to return the modulePrefix object, but this has
been changed to force module writers to use a conventional import
afterwards so that the McMillan installer will know about dependencies.
"""
# this should yield modules or userModules
modulePrefix = fullName.split('.')[0]
# determine whether this is a new import
if not sys.modules.has_key(fullName):
newModule = True
else:
newModule = False
# import the correct module - we have to do this in anycase to
# get the thing into our local namespace
exec('import ' + fullName)
# there can only be a reload if this is not a newModule
if not newModule:
exec('reload(' + fullName + ')')
# we need to inject the import into the calling dictionary...
# importing my.module results in "my" in the dictionary, so we
# split at '.' and return the object bound to that name
# return locals()[modulePrefix]
# we DON'T do this anymore, so that module writers are forced to
# use an import statement straight after calling import_reload (or
# somewhere else in the module)
def isInstalled(self):
"""Returns True if devide is running from an Installed state.
Installed of course refers to being installed with Gordon McMillan's
Installer. This can be used by devide modules to determine whether
they should use reload or not.
"""
return hasattr(modules, '__importsub__')
def execute_module(self, meta_module, part=0, streaming=False):
"""Execute module instance.
Important: this method does not result in data being transferred
after the execution, it JUST performs the module execution. This
method is called by the scheduler during network execution. No
other call should be used to execute a single module!
@param instance: module instance to be executed.
@raise ModuleManagerException: this exception is raised with an
informative error string if a module fails to execute.
@return: Nothing.
"""
try:
# this goes via the MetaModule so that time stamps and the
# like are correctly reported
meta_module.execute_module(part, streaming)
except Exception, e:
# get details about the errored module
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Unable to execute part %d of module %s (%s): %s' \
% (part, instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
def execute_network(self, startingModule=None):
"""Execute local network in order, starting from startingModule.
This is a utility method used by module_utils to bind to the Execute
control found on must module UIs. We are still in the process
of formalising the concepts of networks vs. groups of modules.
Eventually, networks will be grouped by process node and whatnot.
@todo: integrate concept of startingModule.
"""
try:
self._devide_app.network_manager.execute_network(
self._module_dict.values())
except Exception, e:
# if an error occurred, but progress is not at 100% yet,
# we have to put it there, else app remains in visually
# busy state.
if self._devide_app.get_progress() < 100.0:
self._devide_app.set_progress(
100.0, 'Error during network execution.')
# we are directly reporting the error, as this is used by
# a utility function that is too compact to handle an
# exception by itself. Might change in the future.
self._devide_app.log_error_with_exception(str(e))
def view_module(self, instance):
instance.view()
def delete_module(self, instance):
"""Destroy module.
This will disconnect all module inputs and outputs and call the
close() method. This method is used by the graphEditor and by
the close() method of the ModuleManager.
@raise ModuleManagerException: if an error occurs during module
deletion.
"""
# get details about the module (we might need this later)
meta_module = self._module_dict[instance]
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# first disconnect all outgoing connections
inputs = self._module_dict[instance].inputs
outputs = self._module_dict[instance].outputs
# outputs is a list of lists of tuples, each tuple containing
# module_instance and input_idx of the consumer module
for output in outputs:
if output:
# we just want to walk through the dictionary tuples
for consumer in output:
# disconnect all consumers
self.disconnect_modules(consumer[0], consumer[1])
# inputs is a list of tuples, each tuple containing module_instance
# and output_idx of the producer/supplier module
for input_idx in range(len(inputs)):
try:
# also make sure we fully disconnect ourselves from
# our producers
self.disconnect_modules(instance, input_idx)
except Exception, e:
# we can't allow this to prevent a destruction, just log
self.log_error_with_exception(
'Module %s (%s) errored during disconnect of input %d. '
'Continuing with deletion.' % \
(instance_name, module_name, input_idx))
# set supplier to None - so we know it's nuked
inputs[input_idx] = None
# we've disconnected completely - let's reset all lists
self._module_dict[instance].reset_inputsOutputs()
# store autoexecute, then disable
ae = self.auto_execute
self.auto_execute = False
try:
try:
# now we can finally call close on the instance
instance.close()
finally:
# do the following in all cases:
# 1. remove module from our dict
del self._module_dict[instance]
# 2. reset auto_execute mode
self.auto_execute = ae
# the exception will now be re-raised if there was one
# to begin with.
except Exception, e:
# we're going to re-raise the exception: this method could be
# called by other parties that need to do alternative error
# handling
# create new exception message
es = 'Error calling close() on module %s (%s): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
def connect_modules(self, output_module, output_idx,
input_module, input_idx):
"""Connect output_idx'th output of provider output_module to
input_idx'th input of consumer input_module. If an error occurs
during connection, an exception will be raised.
@param output_module: This is a module instance.
"""
# record connection (this will raise an exception if the input
# is already occupied)
self._module_dict[input_module].connectInput(
input_idx, output_module, output_idx)
# record connection on the output of the producer module
# this will also initialise the transfer times
self._module_dict[output_module].connectOutput(
output_idx, input_module, input_idx)
def disconnect_modules(self, input_module, input_idx):
"""Disconnect a consumer module from its provider.
This method will disconnect input_module from its provider by
disconnecting the link between the provider and input_module at
the input_idx'th input port of input_module.
All errors will be handled internally in this function, i.e. no
exceptions will be raised.
@todo: factor parts of this out into the MetaModule.
FIXME: continue here... (we can start converting some of
the modules to shallow copy their data; especially the slice3dVWR
is a problem child.)
"""
meta_module = self._module_dict[input_module]
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
try:
input_module.set_input(input_idx, None)
except Exception, e:
# if the module errors during disconnect, we have no choice
# but to continue with deleting it from our metadata
# at least this way, no data transfers will be attempted during
# later network executions.
self._devide_app.log_error_with_exception(
'Module %s (%s) errored during disconnect of input %d. '
'Removing link anyway.' % \
(instance_name, module_name, input_idx))
# trace it back to our supplier, and tell it that it has one
# less consumer (if we even HAVE a supplier on this port)
s = self._module_dict[input_module].inputs[input_idx]
if s:
supp = s[0]
suppOutIdx = s[1]
self._module_dict[supp].disconnectOutput(
suppOutIdx, input_module, input_idx)
# indicate to the meta data that this module doesn't have an input
# anymore
self._module_dict[input_module].disconnectInput(input_idx)
def deserialise_module_instances(self, pmsDict, connectionList):
"""Given a pickled stream, this method will recreate all modules,
configure them and connect them up.
@returns: (newModulesDict, connectionList) - newModulesDict maps from
serialised/OLD instance name to newly created instance; newConnections
is a connectionList of the connections taht really were made during
the deserialisation.
@TODO: this should go to NetworkManager and should return meta_modules
in the dictionary, not module instances.
"""
# store and deactivate auto-execute
ae = self.auto_execute
self.auto_execute = False
# newModulesDict will act as translator between pickled instance_name
# and new instance!
newModulesDict = {}
failed_modules_dict = []
for pmsTuple in pmsDict.items():
# each pmsTuple == (instance_name, pms)
# we're only going to try to create a module if the module_man
# says it's available!
try:
newModule = self.create_module(pmsTuple[1].module_name)
except ModuleManagerException, e:
self._devide_app.log_error_with_exception(
'Could not create module %s:\n%s.' %
(pmsTuple[1].module_name, str(e)))
# make sure
newModule = None
if newModule:
# set its config!
try:
# we need to DEEP COPY the config, else it could easily
# happen that objects have bindings to the same configs!
# to see this go wrong, switch off the deepcopy, create
# a network by copying/pasting a vtkPolyData, load
# two datasets into a slice viewer... now save the whole
# thing and load it: note that the two readers are now
# reading the same file!
configCopy = copy.deepcopy(pmsTuple[1].module_config)
# the API says we have to call get_config() first,
# so that the module has another place where it
# could lazy prepare the thing (slice3dVWR does
# this)
cfg = newModule.get_config()
# now we merge the stored config with the new
# module config
cfg.__dict__.update(configCopy.__dict__)
# and then we set it back with set_config
newModule.set_config(cfg)
except Exception, e:
# it could be a module with no defined config logic
self._devide_app.log_warning(
'Could not restore state/config to module %s: %s' %
(newModule.__class__.__name__, e))
# try to rename the module to the pickled unique instance name
# if this name is already taken, use the generated unique instance
# name
self.rename_module(newModule,pmsTuple[1].instance_name)
# and record that it's been recreated (once again keyed
# on the OLD unique instance name)
newModulesDict[pmsTuple[1].instance_name] = newModule
# now we're going to connect all of the successfully created
# modules together; we iterate DOWNWARDS through the different
# consumerTypes
newConnections = []
for connection_type in range(max(self.consumerTypeTable.values()) + 1):
typeConnections = [connection for connection in connectionList
if connection.connection_type == connection_type]
for connection in typeConnections:
if newModulesDict.has_key(connection.source_instance_name) and \
newModulesDict.has_key(connection.target_instance_name):
sourceM = newModulesDict[connection.source_instance_name]
targetM = newModulesDict[connection.target_instance_name]
# attempt connecting them
print "connecting %s:%d to %s:%d..." % \
(sourceM.__class__.__name__, connection.output_idx,
targetM.__class__.__name__, connection.input_idx)
try:
self.connect_modules(sourceM, connection.output_idx,
targetM, connection.input_idx)
except:
pass
else:
newConnections.append(connection)
# now do the POST connection module config!
for oldInstanceName,newModuleInstance in newModulesDict.items():
# retrieve the pickled module state
pms = pmsDict[oldInstanceName]
# take care to deep copy the config
configCopy = copy.deepcopy(pms.module_config)
# now try to call set_configPostConnect
try:
newModuleInstance.set_configPostConnect(configCopy)
except AttributeError:
pass
except Exception, e:
# it could be a module with no defined config logic
self._devide_app.log_warning(
'Could not restore post connect state/config to module '
'%s: %s' % (newModuleInstance.__class__.__name__, e))
# reset auto_execute
self.auto_execute = ae
# we return a dictionary, keyed on OLD pickled name with value
# the newly created module-instance and a list with the connections
return (newModulesDict, newConnections)
def request_auto_execute_network(self, module_instance):
"""Method that can be called by an interaction/view module to
indicate that some action by the user should result in a network
update. The execution will only be performed if the
AutoExecute mode is active.
"""
if self.auto_execute:
print "auto_execute ##### #####"
self.execute_network()
def serialise_module_instances(self, module_instances):
"""Given
"""
# dictionary of pickled module instances keyed on unique module
# instance name
pmsDict = {}
# we'll use this list internally to check later (during connection
# pickling) which modules are being written away
pickledModuleInstances = []
for module_instance in module_instances:
if self._module_dict.has_key(module_instance):
# first get the MetaModule
mModule = self._module_dict[module_instance]
# create a picklable thingy
pms = PickledModuleState()
try:
print "SERIALISE: %s - %s" % \
(str(module_instance),
str(module_instance.get_config()))
pms.module_config = module_instance.get_config()
except AttributeError, e:
self._devide_app.log_warning(
'Could not extract state (config) from module %s: %s' \
% (module_instance.__class__.__name__, str(e)))
# if we can't get a config, we pickle a default
pms.module_config = DefaultConfigClass()
#pms.module_name = module_instance.__class__.__name__
# we need to store the complete module name
# we could also get this from meta_module.module_name
pms.module_name = module_instance.__class__.__module__
# this will only be used for uniqueness purposes
pms.instance_name = mModule.instance_name
pmsDict[pms.instance_name] = pms
pickledModuleInstances.append(module_instance)
# now iterate through all the actually pickled module instances
# and store all connections in a connections list
# three different types of connections:
# 0. connections with source modules with no inputs
# 1. normal connections
# 2. connections with targets that are exceptions, e.g. sliceViewer
connectionList = []
for module_instance in pickledModuleInstances:
mModule = self._module_dict[module_instance]
# we only have to iterate through all outputs
for output_idx in range(len(mModule.outputs)):
outputConnections = mModule.outputs[output_idx]
# each output can of course have multiple outputConnections
# each outputConnection is a tuple:
# (consumerModule, consumerInputIdx)
for outputConnection in outputConnections:
if outputConnection[0] in pickledModuleInstances:
# this means the consumerModule is also one of the
# modules to be pickled and so this connection
# should be stored
# find the type of connection (1, 2, 3), work from
# the back...
moduleClassName = \
outputConnection[0].__class__.__name__
if moduleClassName in self.consumerTypeTable:
connection_type = self.consumerTypeTable[
moduleClassName]
else:
connection_type = 1
# FIXME: we still have to check for 0: iterate
# through all inputs, check that none of the
# supplier modules are in the list that we're
# going to pickle
print '%s has connection type %d' % \
(outputConnection[0].__class__.__name__,
connection_type)
connection = PickledConnection(
mModule.instance_name, output_idx,
self._module_dict[outputConnection[0]].instance_name,
outputConnection[1],
connection_type)
connectionList.append(connection)
return (pmsDict, connectionList)
def generic_progress_callback(self, progressObject,
progressObjectName, progress, progressText):
"""progress between 0.0 and 1.0.
"""
if self._inProgressCallback.testandset():
# first check if execution has been disabled
# the following bit of code is risky: the ITK to VTK bridges
# seem to be causing segfaults when we abort too soon
# if not self._executionEnabled:
# try:
# progressObject.SetAbortExecute(1)
# except Exception:
# pass
# try:
# progressObject.SetAbortGenerateData(1)
# except Exception:
# pass
# progress = 1.0
# progressText = 'Execution ABORTED.'
progressP = progress * 100.0
fullText = '%s: %s' % (progressObjectName, progressText)
if abs(progressP - 100.0) < 0.01:
# difference smaller than a hundredth
fullText += ' [DONE]'
self.setProgress(progressP, fullText)
self._inProgressCallback.unlock()
def get_consumers(self, meta_module):
"""Determine meta modules that are connected to the outputs of
meta_module.
This method is called by: scheduler, self.recreate_module_in_place.
@todo: this should be part of the MetaModule code, as soon as
the MetaModule inputs and outputs are of type MetaModule and not
instance.
@param instance: module instance of which the consumers should be
determined.
@return: list of tuples, each consisting of (this module's output
index, the consumer meta module, the consumer input index)
"""
consumers = []
# get outputs from MetaModule: this is a list of list of tuples
# outer list has number of outputs elements
# inner lists store consumer modules for that output
# tuple contains (consumerModuleInstance, consumerInputIdx)
outputs = meta_module.outputs
for output_idx in range(len(outputs)):
output = outputs[output_idx]
for consumerInstance, consumerInputIdx in output:
consumerMetaModule = self._module_dict[consumerInstance]
consumers.append(
(output_idx, consumerMetaModule, consumerInputIdx))
return consumers
def get_producers(self, meta_module):
"""Return a list of meta modules, output indices and the input
index through which they supply 'meta_module' with data.
@todo: this should be part of the MetaModule code, as soon as
the MetaModule inputs and outputs are of type MetaModule and not
instance.
@param meta_module: consumer meta module.
@return: list of tuples, each tuple consists of producer meta module
and output index as well as input index of the instance input that
they connect to.
"""
# inputs is a list of tuples, each tuple containing module_instance
# and output_idx of the producer/supplier module; if the port is
# not connected, that position in inputs contains "None"
inputs = meta_module.inputs
producers = []
for i in range(len(inputs)):
pTuple = inputs[i]
if pTuple is not None:
# unpack
pInstance, pOutputIdx = pTuple
pMetaModule = self._module_dict[pInstance]
# and store
producers.append((pMetaModule, pOutputIdx, i))
return producers
def setModified_DEPRECATED(self, module_instance):
"""Changed modified ivar in MetaModule.
This ivar is used to determine whether module_instance needs to be
executed to become up to date. It should be set whenever changes
are made that dirty the module state, for example parameter changes
or topology changes.
@param module_instance: the instance whose modified state sbould be
changed.
@param value: the new value of the modified ivar, True or False.
"""
self._module_dict[module_instance].modified = True
def set_progress(self, progress, message, noTime=False):
"""Progress is in percent.
"""
self._devide_app.set_progress(progress, message, noTime)
setProgress = set_progress
def _make_unique_instance_name(self, instance_name=None):
"""Ensure that instance_name is unique or create a new unique
instance_name.
If instance_name is None, a unique one will be created. An
instance_name (whether created or passed) will be permuted until it
unique and then returned.
"""
# first we make sure we have a unique instance name
if not instance_name:
instance_name = "dvm%d" % (len(self._module_dict),)
# now make sure that instance_name is unique
uniqueName = False
while not uniqueName:
# first check that this doesn't exist in the module dictionary
uniqueName = True
for mmt in self._module_dict.items():
if mmt[1].instance_name == instance_name:
uniqueName = False
break
if not uniqueName:
# this means that this exists already!
# create a random 3 character string
chars = 'abcdefghijklmnopqrstuvwxyz'
tl = ""
for i in range(3):
tl += choice(chars)
instance_name = "%s%s%d" % (instance_name, tl,
len(self._module_dict))
return instance_name
def rename_module(self, instance, name):
"""Rename a module in the module dictionary
"""
# if we get a duplicate name, we either add (%d) after, or replace
# the existing %d with something that makes it all unique...
mo = re.match('(.*)\s+\(([1-9]+)\)', name)
if mo:
basename = mo.group(1)
i = int(mo.group(2)) + 1
else:
basename = name
i = 1
while (self.get_instance(name) != None):
# add a number (%d) until the name is unique
name = '%s (%d)' % (basename, i)
i += 1
try:
# get the MetaModule and rename it.
self._module_dict[instance].instance_name = name
except Exception:
return False
# some modules and mixins support the rename call and use it
# to change their window titles. Neat.
# this was added on 20090322, so it's not supported
# everywhere.
try:
instance.rename(name)
except AttributeError:
pass
# everything proceeded according to plan.
# so return the new name
return name
def modify_module(self, module_instance, part=0):
"""Call this whenever module state has changed in such a way that
necessitates a re-execution, for instance when parameters have been
changed or when new input data has been transferred.
"""
self._module_dict[module_instance].modify(part)
modify_module = modify_module
def recreate_module_in_place(self, meta_module):
"""Destroy, create and reconnect a module in place.
This function works but is not being used at the moment. It was
intended for graphEditor-driven module reloading, but it turned out
that implementing that in the graphEditor was easier. I'm keeping
this here for reference purposes.
@param meta_module: The module that will be destroyed.
@returns: new meta_module.
"""
# 1. store input and output connections, module name, module state
#################################################################
# prod_tuple contains a list of (prod_meta_module, output_idx,
# input_idx) tuples
prod_tuples = self.get_producers(meta_module)
# cons_tuples contains a list of (output_index, consumer_meta_module,
# consumer input index)
cons_tuples = self.get_consumers(meta_module)
# store the instance name
instance_name = meta_module.instance_name
# and the full module spec name
full_name = meta_module.module_name
# and get the module state (we make a deep copy just in case)
module_config = copy.deepcopy(meta_module.instance.get_config())
# 2. instantiate a new one and give it its old config
###############################################################
# because we instantiate the new one first, if this instantiation
# breaks, an exception will be raised and no harm will be done,
# we still have the old one lying around
# instantiate
new_instance = self.create_module(full_name, instance_name)
# and give it its old config back
new_instance.set_config(module_config)
# 3. delete the old module
#############################################################
self.delete_module(meta_module.instance)
# 4. now rename the new module
#############################################################
# find the corresponding new meta_module
meta_module = self._module_dict[new_instance]
# give it its old name back
meta_module.instance_name = instance_name
# 5. connect it up
#############################################################
for producer_meta_module, output_idx, input_idx in prod_tuples:
self.connect_modules(
producer_meta_module.instance, output_idx,
new_instance, input_idx)
for output_idx, consumer_meta_module, input_idx in cons_tuples:
self.connect_modules(
new_instance, output_idx,
consumer_meta_module.instance, input_idx)
# we should be done now
return meta_module
def should_execute_module(self, meta_module, part=0):
"""Determine whether module_instance requires execution to become
up to date.
Execution is required when the module is new or when the user has made
parameter or introspection changes. All of these conditions should be
indicated by calling L{ModuleManager.modify(instance)}.
@return: True if execution required, False if not.
"""
return meta_module.shouldExecute(part)
def should_transfer_output(
self,
meta_module, output_idx, consumer_meta_module,
consumer_input_idx, streaming=False):
"""Determine whether output data has to be transferred from
module_instance via output outputIndex to module consumerInstance.
Output needs to be transferred if:
- module_instance has new or changed output (i.e. it has
executed after the previous transfer)
- consumerInstance does not have the data yet
Both of these cases are handled with a transfer timestamp per
output connection (defined by output idx, consumer module, and
consumer input idx)
This method is used by the scheduler.
@return: True if output should be transferred, False if not.
"""
return meta_module.should_transfer_output(
output_idx, consumer_meta_module, consumer_input_idx,
streaming)
def transfer_output(
self,
meta_module, output_idx, consumer_meta_module,
consumer_input_idx, streaming=False):
"""Transfer output data from module_instance to the consumer modules
connected to its specified output indexes.
This will be called by the scheduler right before execution to
transfer the given output from module_instance instance to the correct
input on the consumerInstance. In general, this is only done if
should_transfer_output is true, so the number of unnecessary transfers
should be minimised.
This method is in ModuleManager and not in MetaModule because it
involves more than one MetaModule.
@param module_instance: producer module whose output data must be
transferred.
@param outputIndex: only output data produced by this output will
be transferred.
@param consumerInstance: only data going to this instance will be
transferred.
@param consumerInputIdx: data enters consumerInstance via this input
port.
@raise ModuleManagerException: if an error occurs getting the data
from or transferring it to a new module.
"""
#print 'transferring data %s:%d' % (module_instance.__class__.__name__,
# outputIndex)
# double check that this connection already exists
consumer_instance = consumer_meta_module.instance
if meta_module.findConsumerInOutputConnections(
output_idx, consumer_instance, consumer_input_idx) == -1:
raise Exception, 'ModuleManager.transfer_output called for ' \
'connection that does not exist.'
try:
# get data from producerModule output
od = meta_module.instance.get_output(output_idx)
except Exception, e:
# get details about the errored module
instance_name = meta_module.instance_name
module_name = meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Faulty transfer_output (get_output on module %s (%s)): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
# we only disconnect if we're NOT streaming!
if not streaming:
# experiment here with making shallowcopies if we're working with
# VTK data. I've double-checked (20071027): calling update on
# a shallowcopy is not able to get a VTK pipeline to execute.
# TODO: somehow this should be part of one of the moduleKits
# or some other module-related pluggable logic.
if od is not None and hasattr(od, 'GetClassName') and hasattr(od, 'ShallowCopy'):
nod = od.__class__()
nod.ShallowCopy(od)
od = nod
try:
# set on consumerInstance input
consumer_meta_module.instance.set_input(consumer_input_idx, od)
except Exception, e:
# get details about the errored module
instance_name = consumer_meta_module.instance_name
module_name = consumer_meta_module.instance.__class__.__name__
# and raise the relevant exception
es = 'Faulty transfer_output (set_input on module %s (%s)): %s' \
% (instance_name, module_name, str(e))
# we use the three argument form so that we can add a new
# message to the exception but we get to see the old traceback
# see: http://docs.python.org/ref/raise.html
raise ModuleManagerException, es, sys.exc_info()[2]
# record that the transfer has just happened
meta_module.timeStampTransferTime(
output_idx, consumer_instance, consumer_input_idx,
streaming)
# also invalidate the consumerModule: it should re-execute when
# a transfer has been made. We only invalidate the part that
# takes responsibility for that input.
part = consumer_meta_module.getPartForInput(consumer_input_idx)
consumer_meta_module.modify(part)
#print "modified", consumer_meta_module.instance.__class__.__name__
# execute on change
# we probably shouldn't automatically execute here... transfers
# mean that some sort of network execution is already running
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
import itk
import re
from module_kits.misc_kit.misc_utils import get_itk_img_type_and_dim
from module_kits.misc_kit.misc_utils import \
get_itk_img_type_and_dim_shortstring
get_img_type_and_dim = get_itk_img_type_and_dim
get_img_type_and_dim_shortstring = \
get_itk_img_type_and_dim_shortstring
def coordinates_to_vector_container(points, initial_distance=0):
"""Convert list of 3-D index coordinates to an ITK
VectorContainer for use with the FastMarching filter.
@param points: Python iterable containing 3-D index (integer)
coordinates.
@param initial_distance: Initial distance that will be set on
these nodes for the fast marching.
"""
vc = itk.VectorContainer[itk.UI,
itk.LevelSetNode[itk.F, 3]].New()
# this will clear it
vc.Initialize()
for pt_idx, pt in enumerate(points):
# cast each coordinate element to integer
x,y,z = [int(e) for e in pt]
idx = itk.Index[3]()
idx.SetElement(0, x)
idx.SetElement(1, y)
idx.SetElement(2, z)
node = itk.LevelSetNode[itk.F, 3]()
node.SetValue(initial_distance)
node.SetIndex(idx)
vc.InsertElement(pt_idx, node)
return vc
def setup_itk_object_progress(dvModule, obj, nameOfObject, progressText,
objEvals=None, module_manager=None):
"""
@param dvModlue: instance containing binding to obj. Usually this
is a DeVIDE module. If not, remember to pass module_manager
parameter.
@param obj: The ITK object that needs to be progress updated.
@param module_manager: If set, will be used as binding to
module_manager. If set to None, dvModule._module_manager will be
used. This can be used in cases when obj is NOT a member of a
DeVIDE module, iow when dvModule is not a DeVIDE module.
"""
# objEvals is on optional TUPLE of obj attributes that will be called
# at each progress callback and filled into progressText via the Python
# % operator. In other words, all string attributes in objEvals will be
# eval'ed on the object instance and these values will be filled into
# progressText, which has to contain the necessary number of format tokens
# first we have to find the attribute of dvModule that binds
# to obj. We _don't_ want to have a binding to obj hanging around
# in our callable, because this means that the ITK object can never
# be destroyed. Instead we look up the binding everytime the callable
# is invoked by making use of getattr on the devideModule binding.
# find attribute string of obj in dvModule
di = dvModule.__dict__.items()
objAttrString = None
for key, value in di:
if value is obj:
objAttrString = key
break
if not objAttrString:
raise Exception, 'Could not determine attribute string for ' \
'object %s.' % (obj.__class__.__name__)
if module_manager is None:
mm = dvModule._module_manager
else:
mm = module_manager
# sanity check objEvals
if type(objEvals) != type(()) and objEvals != None:
raise TypeError, 'objEvals should be a tuple or None.'
def commandCallable():
# setup for and get values of all requested objEvals
values = []
if type(objEvals) == type(()):
for objEval in objEvals:
values.append(
eval('dvModule.%s.%s' % (objAttrString, objEval)))
values = tuple(values)
# do the actual callback
mm.generic_progress_callback(getattr(dvModule, objAttrString),
nameOfObject, getattr(dvModule, objAttrString).GetProgress(),
progressText % values)
# get rid of all bindings
del values
pc = itk.PyCommand.New()
pc.SetCommandCallable(commandCallable)
res = obj.AddObserver(itk.ProgressEvent(), pc)
# we DON'T have to store a binding to the PyCommand; during AddObserver,
# the ITK object makes its own copy. The ITK object will also take care
# of destroying the observer when it (the ITK object) is destroyed
#obj.progressPyCommand = pc
setupITKObjectProgress = setup_itk_object_progress
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
"""itk_kit package driver file.
Inserts the following modules in sys.modules: itk, InsightToolkit.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
VERSION = ''
def setDLFlags():
# brought over from ITK Wrapping/CSwig/Python
# Python "help(sys.setdlopenflags)" states:
#
# setdlopenflags(...)
# setdlopenflags(n) -> None
#
# Set the flags that will be used for dlopen() calls. Among other
# things, this will enable a lazy resolving of symbols when
# importing a module, if called as sys.setdlopenflags(0) To share
# symbols across extension modules, call as
#
# sys.setdlopenflags(dl.RTLD_NOW|dl.RTLD_GLOBAL)
#
# GCC 3.x depends on proper merging of symbols for RTTI:
# http://gcc.gnu.org/faq.html#dso
#
try:
import dl
newflags = dl.RTLD_NOW|dl.RTLD_GLOBAL
except:
newflags = 0x102 # No dl module, so guess (see above).
try:
oldflags = sys.getdlopenflags()
sys.setdlopenflags(newflags)
except:
oldflags = None
return oldflags
def resetDLFlags(data):
# brought over from ITK Wrapping/CSwig/Python
# Restore the original dlopen flags.
try:
sys.setdlopenflags(data)
except:
pass
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# if we're frozen, make sure we grab the wrapitk contained in this kit
p1 = os.path.dirname(__file__)
p2 = os.path.join(p1, os.path.join('wrapitk', 'python'))
p3 = os.path.join(p1, os.path.join('wrapitk', 'lib'))
sys.path.insert(0, p2)
sys.path.insert(0, p3)
# and now the LD_LIBRARY_PATH / PATH
if sys.platform == 'win32':
so_path_key = 'PATH'
else:
so_path_key = 'LD_LIBRARY_PATH'
# this doesn't work on Linux in anycase
if so_path_key in os.environ:
os.environ[so_path_key] = '%s%s%s' % \
(p3, os.pathsep, os.environ[so_path_key])
else:
os.environ[so_path_key] = p3
# with WrapITK, this takes almost no time
import itk
theModuleManager.setProgress(5, 'Initialising ITK: start')
# let's get the version (which will bring in VXLNumerics and Base)
# setup the kit version
global VERSION
isv = itk.Version.GetITKSourceVersion()
ind = re.match('.*Date: ([0-9]+-[0-9]+-[0-9]+).*', isv).group(1)
VERSION = '%s (%s)' % (itk.Version.GetITKVersion(), ind)
theModuleManager.setProgress(45, 'Initialising ITK: VXLNumerics, Base')
if pre_import:
# then ItkVtkGlue (at the moment this is fine, VTK is always there;
# keep in mind for later when we allow VTK-less startups)
a = itk.VTKImageToImageFilter
theModuleManager.setProgress(
75,
'Initialising ITK: BaseTransforms, SimpleFilters, ItkVtkGlue')
# user can address this as module_kits.itk_kit.utils.blaat()
import module_kits.itk_kit.utils as utils
theModuleManager.setProgress(100, 'Initialising ITK: DONE')
| Python |
# $Id: __init__.py 1945 2006-03-05 01:06:37Z cpbotha $
# 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.
"""matplotlib_kit package driver file.
Inserts the following modules in sys.modules: matplotlib, pylab.
@author: Charl P. Botha <http://cpbotha.net/>
"""
import os
import re
import sys
import types
# you have to define this
VERSION = ''
def init(theModuleManager, pre_import=True):
if hasattr(sys, 'frozen') and sys.frozen:
# matplotlib supports py2exe by checking for matplotlibdata in the appdir
# but this is only done on windows (and therefore works for our windows
# installer builds). On non-windows, we have to stick it in the env
# to make sure that MPL finds its datadir (only if we're frozen)
mpldir = os.path.join(theModuleManager.get_appdir(), 'matplotlibdata')
os.environ['MATPLOTLIBDATA'] = mpldir
# import the main module itself
# this doesn't import numerix yet...
global matplotlib
import matplotlib
# use WX + Agg backend (slower, but nicer that WX)
matplotlib.use('WXAgg')
# interactive mode: user can use pylab commands from any introspection
# interface, changes will be made immediately and matplotlib cooperates
# nicely with main WX event loop
matplotlib.interactive(True)
# with matplotlib 1.0.1 we can't do this anymore.
# makes sure we use the numpy backend
#from matplotlib import rcParams
#rcParams['numerix'] = 'numpy'
theModuleManager.setProgress(25, 'Initialising matplotlib_kit: config')
# @PATCH:
# this is for the combination numpy 1.0.4 and matplotlib 0.91.2
# matplotlib/numerix/ma/__init__.py:
# . normal installation fails on "from numpy.ma import *", so "from
# numpy.core.ma import *" is done, thus bringing in e.g. getmask
# . pyinstaller binaries for some or other reason succeed on
# "from numpy.ma import *" (no exception raised), therefore do
# not do "from numpy.core.ma import *", and therefore things like
# getmask are not imported.
# solution:
# we make sure that "from numpy.ma import *" actually brings in
# numpy.core.ma by importing that and associating the module
# binding to the global numpy.ma.
#if hasattr(sys, 'frozen') and sys.frozen:
# import numpy.core.ma
# sys.modules['numpy.ma'] = sys.modules['numpy.core.ma']
# import the pylab interface, make sure it's available from this namespace
global pylab
import pylab
theModuleManager.setProgress(90, 'Initialising matplotlib_kit: pylab')
# build up VERSION
global VERSION
VERSION = '%s' % (matplotlib.__version__,)
theModuleManager.setProgress(100, 'Initialising matplotlib_kit: complete')
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import gdcm
def sort_ipp(filenames):
"""STOP PRESS. This is currently incomplete. I'm waiting to see
what's going to happen with the IPPSorter in GDCM.
Given a list of filenames, make use of the gdcm scanner to sort
them all according to IPP.
@param filenames: list of full pathnames that you want to have
sorted.
@returns: tuple with (average z space,
"""
s = gdcm.Scanner()
# we need the IOP and the IPP tags
iop_tag = gdcm.Tag(0x0020, 0x0037)
s.AddTag(iop_tag)
ipp_tag = gdcm.Tag(0x0020, 0x0032)
s.AddTag(ipp_tag)
ret = s.Scan(filenames)
if not ret:
return (0, [])
for f in filenames:
mapping = s.GetMapping(f)
pttv = gdcm.PythonTagToValue(mapping)
pttv.Start()
while not pttv.IsAtEnd():
tag = pttv.GetCurrentTag()
val = pttv.GetCurrentValue()
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
"""gdcm_kit driver module.
This pre-loads GDCM2, the second generation Grass Roots Dicom library,
used since 2008 by DeVIDE for improved DICOM loading / saving support.
"""
import os
import sys
VERSION = ''
def init(module_manager, pre_import=True):
# as of 20080628, the order of importing vtkgdcm and gdcm IS
# important on Linux. vtkgdcm needs to go before gdcm, else very
# strange things happen due to the dl (dynamic loading) switches.
global vtkgdcm
import vtkgdcm
global gdcm
import gdcm
# since 2.0.9, we do the following to locate part3.xml:
if hasattr(sys, 'frozen') and sys.frozen:
g = gdcm.Global.GetInstance()
# devide.spec puts Part3.xml in devide_dir/gdcmdata/XML/
g.Prepend(os.path.join(
module_manager.get_appdir(), 'gdcmdata','XML'))
if not g.LoadResourcesFiles():
raise RuntimeError('Could not setup GDCM resource files.')
# will be available as module_kits.gdcm_kit.utils after the client
# programmer has done module_kits.gdcm_kit
import module_kits.gdcm_kit.utils
global VERSION
VERSION = gdcm.Version.GetVersion()
module_manager.set_progress(100, 'Initialising gdcm_kit: complete.')
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import re
# map from itk type string to string
ITKTSTR_STRING = {
'C' : 'char',
'D' : 'double',
'F' : 'float',
'L' : 'long',
'S' : 'short'
}
# map from itk type sign to string
ITKTSGN_STRING = {
'U' : 'unsigned',
'S' : 'signed'
}
def get_itk_img_type_and_dim_shortstring(itk_img):
"""Return short string representing type and dimension of itk
image.
This method has been put here so that it's available to non-itk
dependent modules, such as the QuickInfo, and does not require
any access to the ITK library itself.
"""
# repr is e.g.:
# <itkImagePython.itkImageSS3; proxy of <Swig Object of type 'itkImageSS3 *' at 0x6ec1570> >
rs = repr(itk_img)
# pick out the short code
mo = re.search('^<itkImagePython.itkImage(.*);.*>', rs)
if not mo:
raise TypeError, 'This method requires an ITK image as input.'
else:
return mo.groups()[0]
def get_itk_img_type_and_dim(itk_img):
"""Returns itk image type as a tuple with ('type', 'dim',
'qualifier'), e.g. ('float', '3', 'covariant vector')
This method has been put here so that it's available to non-itk
dependent modules, such as the QuickInfo, and does not require
any access to the ITK library itself.
"""
ss = get_itk_img_type_and_dim_shortstring(itk_img)
# pull that sucker apart
# groups:
# 0: covariant / complex
# 1: vector
# 2: type shortstring
# 3: dimensions (in case of vector, doubled up)
mo = re.search('(C*)(V*)([^0-9]+)([0-9]+)', ss)
c, v, tss, dim = mo.groups()
if c and v:
qualifier = 'covariant vector'
elif c:
qualifier = 'complex'
elif v:
qualifier = 'vector'
else:
qualifier = ''
if len(tss) > 1:
sign_string = ITKTSGN_STRING[tss[0]]
type_string = ITKTSTR_STRING[tss[1]]
else:
sign_string = ''
type_string = ITKTSTR_STRING[tss[0]]
# in the case of a vector of 10-dims, does that become 1010?
if qualifier == 'vector':
dim_string = dim[0:len(dim) / 2]
else:
dim_string = dim[0]
fss = '%s %s' % (sign_string, type_string)
return (fss.strip(), dim_string, qualifier)
def get_itk_img_type_and_dim_DEPRECATED(itk_img):
"""Returns itk image type as a tuple with ('type', 'dim', 'v').
This method has been put here so that it's available to non-itk
dependent modules, such as the QuickInfo, and does not require
any access to the ITK library itself.
"""
try:
t = itk_img.this
except AttributeError, e:
raise TypeError, 'This method requires an ITK image as input.'
else:
# g will be e.g. ('float', '3') or ('unsigned_char', '2')
# note that we use the NON-greedy version so it doesn't break
# on vectors
# example strings:
# Image.F3: _f04b4f1b_p_itk__SmartPointerTitk__ImageTfloat_3u_t_t
# Image.VF33: _600e411b_p_itk__SmartPointerTitk__ImageTitk__VectorTfloat_3u_t_3u_t_t'
mo = re.search('.*itk__ImageT(.*?)_([0-9]+)u*_t',
itk_img.this)
if not mo:
raise TypeError, 'This method requires an ITK Image as input.'
else:
g = mo.groups()
# see if it's a vector
if g[0].startswith('itk__VectorT'):
vectorString = 'V'
# it's a vector, so let's remove the 'itk__VectorT' bit
g = list(g)
g[0] = g[0][len('itk__VectorT'):]
g = tuple(g)
else:
vectorString = ''
# this could also be ('float', '3', 'V'), or ('unsigned_char', '2', '')
return g + (vectorString,)
def major_axis_from_iop_cosine(iop_cosine):
"""Given an IOP direction cosine, i.e. either the row or column,
return a tuple with two components from LRPAFH signifying the
direction of the cosine. For example, if the cosine is pointing from
Left to Right (1\0\0) we return ('L', 'R').
If the direction cosine is NOT aligned with any of the major axes,
we return None.
Based on a routine from dclunie's pixelmed software and info from
http://www.itk.org/pipermail/insight-users/2003-September/004762.html
but we've flipped some things around to make more sense.
IOP direction cosines are always in the LPH coordinate system (patient-relative):
* x is right to left
* y is anterior to posterior
* z is foot to head
"""
obliquity_threshold = 0.8
orientation_x = [('L', 'R'), ('R', 'L')][int(iop_cosine[0] > 0)]
orientation_y = [('P', 'A'), ('A', 'P')][int(iop_cosine[1] > 0)]
orientation_z = [('H', 'F'), ('F', 'H')][int(iop_cosine[2] > 0)]
abs_x = abs(iop_cosine[0])
abs_y = abs(iop_cosine[1])
abs_z = abs(iop_cosine[2])
if abs_x > obliquity_threshold and abs_x > abs_y and abs_x > abs_z:
return orientation_x
elif abs_y > obliquity_threshold and abs_y > abs_x and abs_y > abs_z:
return orientation_y
elif abs_z > obliquity_threshold and abs_z > abs_x and abs_z > abs_y:
return orientation_z
else:
return None
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
class MedicalMetaData:
def __init__(self):
self.medical_image_properties = None
self.direction_cosines = None
def close(self):
del self.medical_image_properties
del self.direction_cosines
def deep_copy(self, source_mmd):
"""Given another MedicalMetaData instance source_mmd, copy its
contents to this instance.
"""
if not source_mmd is None:
self.medical_image_properties.DeepCopy(
source_mmd.medical_image_properties)
self.direction_cosines.DeepCopy(
source_mmd.direction_cosines)
| Python |
# Copyright (c) Charl P. Botha, TU Delft.
# All rights reserved.
# See COPYRIGHT for details.
class SubjectMixin(object):
def __init__(self):
# dictionary mapping from event name to list of observer
# callables
self._observers = {}
def add_observer(self, event_name, observer):
"""Add an observer to this subject.
observer is a function that takes the subject instance as parameter.
"""
try:
if not observer in self._observers[event_name]:
self._observers[event_name].append(observer)
except KeyError:
self._observers[event_name] = [observer]
def close(self):
del self._observers
def notify(self, event_name):
try:
for observer in self._observers[event_name]:
if callable(observer):
# call observer with the observed subject as param
observer(self)
except KeyError:
# it could be that there are no observers for this event,
# in which case we just shut up
pass
def remove_observer(self, event_name, observer):
self._observers[event_name].remove(observer)
| Python |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import sys
VERSION = 'INTEGRATED'
# debug print command: if DEBUG is true, outputs to stdout, if not
# then outputs nothing.
# import with: from module_kits.misc_kit import dprint
DEBUG=False
if DEBUG:
def dprint(*msg):
print msg
else:
def dprint(*msg):
pass
def init(module_manager, pre_import=True):
global misc_utils
import misc_utils
global mixins
import mixins
global types
module_manager.set_progress(100, 'Initialising misc_kit: complete.')
| Python |
import code
from code import softspace
import os
import sys
import wx
import new
def sanitise_text(text):
"""When we process text before saving or executing, we sanitise it
by changing all CR/LF pairs into LF, and then nuking all remaining CRs.
This consistency also ensures that the files we save have the correct
line-endings depending on the operating system we are running on.
It also turns out that things break when after an indentation
level at the very end of the code, there is no empty line. For
example (thanks to Emiel v. IJsseldijk for reproducing!):
def hello():
print "hello" # and this is the last line of the text
Will not completely define method hello.
To remedy this, we add an empty line at the very end if there's
not one already.
"""
text = text.replace('\r\n', '\n')
text = text.replace('\r', '')
lines = text.split('\n')
if lines and len(lines[-1]) != 0:
return text + '\n'
else:
return text
def runcode(self, code):
"""Execute a code object.
Our extra-special verson of the runcode method. We use this when we
want py_shell_mixin._run_source() to generate real exceptions, and
not just output to stdout, for example when CodeRunner is executed
as part of a network. This runcode() is explicitly called by our local
runsource() method.
"""
try:
exec code in self.locals
except SystemExit:
raise
except:
raise
#self.showtraceback()
else:
if softspace(sys.stdout, 0):
print
def runsource(self, source, filename="<input>", symbol="single",
runcode=runcode):
"""Compile and run some source in the interpreter.
Our extra-special verson of the runsource method. We use this when we
want py_shell_mixin._run_source() to generate real exceptions, and
not just output to stdout, for example when CodeRunner is executed
as part of a network. This method calls our special runcode() method
as well.
Arguments are as for compile_command(), but pass in interp instance as
first parameter!
"""
try:
# this could raise OverflowError, SyntaxEror, ValueError
code = self.compile(source, filename, symbol)
except (OverflowError, SyntaxError, ValueError):
# Case 1
raise
#return False
if code is None:
# Case 2
return True
# Case 3
runcode(self, code)
return False
class PythonShellMixin:
def __init__(self, shell_window, module_manager):
# init close handlers
self.close_handlers = []
self.shell_window = shell_window
self.module_manager = module_manager
self._last_fileselector_dir = ''
def close(self, exception_printer):
for ch in self.close_handlers:
try:
ch()
except Exception, e:
exception_printer(
'Exception during PythonShellMixin close_handlers: %s' %
(str(e),))
del self.shell_window
def _open_python_file(self, parent_window):
filename = wx.FileSelector(
'Select file to open into current edit',
self._last_fileselector_dir, "", "py",
"Python files (*.py)|*.py|All files (*.*)|*.*",
wx.OPEN, parent_window)
if filename:
# save directory for future use
self._last_fileselector_dir = \
os.path.dirname(filename)
f = open(filename, 'r')
t = f.read()
t = sanitise_text(t)
f.close()
return filename, t
else:
return (None, None)
def _save_python_file(self, filename, text):
text = sanitise_text(text)
f = open(filename, 'w')
f.write(text)
f.close()
def _saveas_python_file(self, text, parent_window):
filename = wx.FileSelector(
'Select filename to save current edit to',
self._last_fileselector_dir, "", "py",
"Python files (*.py)|*.py|All files (*.*)|*.*",
wx.SAVE, parent_window)
if filename:
# save directory for future use
self._last_fileselector_dir = \
os.path.dirname(filename)
# if the user has NOT specified any fileextension, we
# add .py. (on Win this gets added by the
# FileSelector automatically, on Linux it doesn't)
if os.path.splitext(filename)[1] == '':
filename = '%s.py' % (filename,)
self._save_python_file(filename, text)
return filename
return None
def _run_source(self, text, raise_exceptions=False):
"""Compile and run the source given in text in the shell interpreter's
local namespace.
The idiot pyshell goes through the whole shell.push -> interp.push
-> interp.runsource -> InteractiveInterpreter.runsource hardcoding the
'mode' parameter (effectively) to 'single', thus breaking multi-line
definitions and whatnot.
Here we do some deep magic (ha ha) to externally override the interp
runsource. Python does completely rule.
We do even deeper magic when raise_exceptions is True: we then
raise real exceptions when errors occur instead of just outputting to
stederr.
"""
text = sanitise_text(text)
interp = self.shell_window.interp
if raise_exceptions:
# run our local runsource, don't do any stdout/stderr redirection,
# this is happening as part of a network.
more = runsource(interp, text, '<input>', 'exec')
else:
# our 'traditional' version for normal in-shell introspection and
# execution. Exceptions are turned into nice stdout/stderr
# messages.
stdin, stdout, stderr = sys.stdin, sys.stdout, sys.stderr
sys.stdin, sys.stdout, sys.stderr = \
interp.stdin, interp.stdout, interp.stderr
# look: calling class method with interp instance as first
# parameter comes down to the same as interp calling runsource()
# as its parent method.
more = code.InteractiveInterpreter.runsource(
interp, text, '<input>', 'exec')
# make sure the user can type again
self.shell_window.prompt()
sys.stdin = stdin
sys.stdout = stdout
sys.stderr = stderr
return more
def output_text(self, text):
self.shell_window.write(text + '\n')
self.shell_window.prompt()
def support_vtk(self, interp):
if hasattr(self, 'vtk_renderwindows'):
return
import module_kits
if 'vtk_kit' not in module_kits.module_kit_list:
self.output_text('No VTK support.')
return
from module_kits import vtk_kit
vtk = vtk_kit.vtk
def get_render_info(instance_name):
instance = self.module_manager.get_instance(instance_name)
if instance is None:
return None
class RenderInfo:
pass
render_info = RenderInfo()
render_info.renderer = instance.get_3d_renderer()
render_info.render_window = instance.get_3d_render_window()
render_info.interactor = instance.\
get_3d_render_window_interactor()
return render_info
new_dict = {'vtk' : vtk,
'vtk_get_render_info' : get_render_info}
interp.locals.update(new_dict)
self.__dict__.update(new_dict)
self.output_text('VTK support loaded.')
def support_matplotlib(self, interp):
if hasattr(self, 'mpl_figure_handles'):
return
import module_kits
if 'matplotlib_kit' not in module_kits.module_kit_list:
self.output_text('No matplotlib support.')
return
from module_kits import matplotlib_kit
pylab = matplotlib_kit.pylab
# setup shutdown logic ########################################
self.mpl_figure_handles = []
def mpl_close_handler():
for fh in self.mpl_figure_handles:
pylab.close(fh)
self.close_handlers.append(mpl_close_handler)
# hook our mpl_new_figure method ##############################
# mpl_new_figure hook so that all created figures are registered
# and will be closed when the module is closed
def mpl_new_figure(*args, **kwargs):
handle = pylab.figure(*args, **kwargs)
self.mpl_figure_handles.append(handle)
return handle
def mpl_close_figure(handle):
"""Close matplotlib figure.
"""
pylab.close(handle)
if handle in self.mpl_figure_handles:
idx = self.mpl_figure_handles.index(handle)
del self.mpl_figure_handles[idx]
# replace our hook's documentation with the 'real' documentation
mpl_new_figure.__doc__ = pylab.figure.__doc__
# stuff the required symbols into the module's namespace ######
new_dict = {'matplotlib' : matplotlib_kit.matplotlib,
'pylab' : matplotlib_kit.pylab,
'mpl_new_figure' : mpl_new_figure,
'mpl_close_figure' : mpl_close_figure}
interp.locals.update(new_dict)
self.__dict__.update(new_dict)
self.output_text('matplotlib support loaded.')
| 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 |
# Copyright (c) Charl P. Botha, TU Delft
# All rights reserved.
# See COPYRIGHT for details.
import wx
from wx import py
from wx import stc
class DVEditWindow(py.editwindow.EditWindow):
"""DeVIDE EditWindow.
This fixes all of the py screwups by providing a re-usable Python
EditWindow component. The Py components are useful, they've just been put
together in a really unfortunate way. Poor Orbtech.
Note: SaveFile/LoadFile.
@author: Charl P. Botha <http://cpbotha.net/>
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize,
style=wx.CLIP_CHILDREN | wx.SUNKEN_BORDER):
py.editwindow.EditWindow.__init__(self, parent, id, pos, size, style)
self._setup_folding_and_numbers()
self.interp = None
self.observer_modified = None
# we only want insertions and deletions of text to be detected
# by self._handler_modified
self.SetModEventMask(stc.STC_MOD_INSERTTEXT |
stc.STC_MOD_DELETETEXT)
# Assign handlers for keyboard events.
self.Bind(wx.EVT_CHAR, self._handler_char)
self.Bind(stc.EVT_STC_MARGINCLICK, self._handler_marginclick)
self.Bind(stc.EVT_STC_MODIFIED, self._handler_modified)
def _handler_char(self, event):
"""Keypress event handler.
Only receives an event if OnKeyDown calls event.Skip() for the
corresponding event."""
# in wxPython this used to be KeyCode(). In 2.8 it's an ivar.
key = event.KeyCode
if self.interp is None:
event.Skip()
return
if key in self.interp.getAutoCompleteKeys():
# Usually the dot (period) key activates auto completion.
if self.AutoCompActive():
self.AutoCompCancel()
self.ReplaceSelection('')
self.AddText(chr(key))
text, pos = self.GetCurLine()
text = text[:pos]
if self.autoComplete:
self.autoCompleteShow(text)
elif key == ord('('):
# The left paren activates a call tip and cancels an
# active auto completion.
if self.AutoCompActive():
self.AutoCompCancel()
self.ReplaceSelection('')
self.AddText('(')
text, pos = self.GetCurLine()
text = text[:pos]
self.autoCallTipShow(text)
else:
# Allow the normal event handling to take place.
event.Skip()
def _handler_marginclick(self, evt):
# fold and unfold as needed
if evt.GetMargin() == 2:
if evt.GetShift() and evt.GetControl():
self._fold_all()
else:
lineClicked = self.LineFromPosition(evt.GetPosition())
if self.GetFoldLevel(lineClicked) & stc.STC_FOLDLEVELHEADERFLAG:
if evt.GetShift():
self.SetFoldExpanded(lineClicked, True)
self._fold_expand(lineClicked, True, True, 1)
elif evt.GetControl():
if self.GetFoldExpanded(lineClicked):
self.SetFoldExpanded(lineClicked, False)
self._fold_expand(lineClicked, False, True, 0)
else:
self.SetFoldExpanded(lineClicked, True)
self._fold_expand(lineClicked, True, True, 100)
else:
self.ToggleFold(lineClicked)
def _handler_modified(self, evt):
if callable(self.observer_modified):
self.observer_modified(self)
def _fold_all(self):
lineCount = self.GetLineCount()
expanding = True
# find out if we are folding or unfolding
for lineNum in range(lineCount):
if self.GetFoldLevel(lineNum) & stc.STC_FOLDLEVELHEADERFLAG:
expanding = not self.GetFoldExpanded(lineNum)
break
lineNum = 0
while lineNum < lineCount:
level = self.GetFoldLevel(lineNum)
if level & stc.STC_FOLDLEVELHEADERFLAG and \
(level & stc.STC_FOLDLEVELNUMBERMASK) == stc.STC_FOLDLEVELBASE:
if expanding:
self.SetFoldExpanded(lineNum, True)
lineNum = self._fold_expand(lineNum, True)
lineNum = lineNum - 1
else:
lastChild = self.GetLastChild(lineNum, -1)
self.SetFoldExpanded(lineNum, False)
if lastChild > lineNum:
self.HideLines(lineNum+1, lastChild)
lineNum = lineNum + 1
def _fold_expand(self, line, doExpand, force=False, visLevels=0, level=-1):
lastChild = self.GetLastChild(line, level)
line = line + 1
while line <= lastChild:
if force:
if visLevels > 0:
self.ShowLines(line, line)
else:
self.HideLines(line, line)
else:
if doExpand:
self.ShowLines(line, line)
if level == -1:
level = self.GetFoldLevel(line)
if level & stc.STC_FOLDLEVELHEADERFLAG:
if force:
if visLevels > 1:
self.SetFoldExpanded(line, True)
else:
self.SetFoldExpanded(line, False)
line = self._fold_expand(line, doExpand, force, visLevels-1)
else:
if doExpand and self.GetFoldExpanded(line):
line = self._fold_expand(line, True, force, visLevels-1)
else:
line = self._fold_expand(
line, False, force, visLevels-1)
else:
line = line + 1
return line
def _setup_folding_and_numbers(self):
# from our direct ancestor
self.setDisplayLineNumbers(True)
# the rest is from the wxPython StyledControl_2 demo
self.SetProperty("fold", "1")
self.SetMargins(0,0)
self.SetEdgeMode(stc.STC_EDGE_BACKGROUND)
self.SetEdgeColumn(78)
self.SetMarginType(2, stc.STC_MARGIN_SYMBOL)
self.SetMarginMask(2, stc.STC_MASK_FOLDERS)
self.SetMarginSensitive(2, True)
self.SetMarginWidth(2, 12)
# Like a flattened tree control using circular headers and curved joins
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPEN,
stc.STC_MARK_CIRCLEMINUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDER,
stc.STC_MARK_CIRCLEPLUS, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERSUB,
stc.STC_MARK_VLINE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERTAIL,
stc.STC_MARK_LCORNERCURVE, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEREND,
stc.STC_MARK_CIRCLEPLUSCONNECTED, "white", "#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDEROPENMID,
stc.STC_MARK_CIRCLEMINUSCONNECTED, "white",
"#404040")
self.MarkerDefine(stc.STC_MARKNUM_FOLDERMIDTAIL,
stc.STC_MARK_TCORNERCURVE, "white", "#404040")
def set_interp(self, interp):
"""Assign new py.Interpreter instance to this EditWindow.
This instance will be used for autocompletion. This is often a
py.Shell's interp instance.
"""
self.interp = interp
def autoCallTipShow(self, command):
"""Display argument spec and docstring in a popup window."""
if self.interp is None:
return
if self.CallTipActive():
self.CallTipCancel()
(name, argspec, tip) = self.interp.getCallTip(command)
# if tip:
# dispatcher.send(signal='Shell.calltip', sender=self,
# calltip=tip)
if not self.autoCallTip:
return
if argspec:
startpos = self.GetCurrentPos()
self.AddText(argspec + ')')
endpos = self.GetCurrentPos()
self.SetSelection(endpos, startpos)
if tip:
curpos = self.GetCurrentPos()
size = len(name)
tippos = curpos - (size + 1)
fallback = curpos - self.GetColumn(curpos)
# In case there isn't enough room, only go back to the
# fallback.
tippos = max(tippos, fallback)
self.CallTipShow(tippos, tip)
self.CallTipSetHighlight(0, size)
def autoCompleteShow(self, command):
"""Display auto-completion popup list."""
if self.interp is None:
return
list = self.interp.getAutoCompleteList(
command,
includeMagic=self.autoCompleteIncludeMagic,
includeSingle=self.autoCompleteIncludeSingle,
includeDouble=self.autoCompleteIncludeDouble)
if list:
options = ' '.join(list)
offset = 0
self.AutoCompShow(offset, options)
| Python |
import wx
from wx import py
class DVShell(py.shell.Shell):
"""DeVIDE shell.
Once again, PyCrust makes some pretty bad calls here and there. With this
override we fix some of them.
1. passing locals=None will result in shell.Shell setting locals to
__main__.__dict__ (!!) in contrast to the default behaviour of the Python
code.InteractiveInterpreter , which is what we do here.
"""
def __init__(self, parent, id=-1, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.CLIP_CHILDREN,
introText='', locals=None, InterpClass=None,
startupScript=None, execStartupScript=False,
*args, **kwds):
# default behaviour for InteractiveInterpreter
if locals is None:
locals = {"__name__": "__console__", "__doc__": None}
py.shell.Shell.__init__(self, parent, id, pos,
size, style,
introText, locals, InterpClass,
startupScript, execStartupScript,
*args, **kwds)
| 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 |
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.