def test_object_cache(self): """Test if object cache works.""" cs = tvtk.ConeSource() hash1 = hash(cs) o = cs.output if hasattr(o, 'producer_port'): src = o.producer_port.producer else: src = o.source self.assertEqual(src, cs) self.assertEqual(hash1, hash(src)) del cs, src gc.collect() cs = tvtk.ConeSource() # Force cs to be gc'd! if hasattr(o, 'producer_port'): src = o.producer_port.producer else: src = o.source self.assertEqual(hash1 != hash(src), True) # Test for a bug with collections and the object cache. r = tvtk.Renderer() def _get_props(obj): if hasattr(obj, 'view_props'): return obj.view_props else: return obj.props p = _get_props(r) l1 = len(tvtk_base._object_cache) p1 = _get_props(r) del p1 l2 = len(tvtk_base._object_cache) self.assertEqual(l1, l2)
def test_object_cache(self): """Test if object cache works.""" cs = tvtk.ConeSource() hash1 = hash(cs) o = cs.output if hasattr(o, 'producer_port'): src = o.producer_port.producer else: src = cs.executive.algorithm self.assertEqual(src, cs) self.assertEqual(hash1, hash(src)) del cs, src gc.collect() # The test sometimes fails as VTK seems to generate objects with the # same memory address and hash, we try to force it to allocate more # objects so as to not end up reusing the same address and hash. junk = [tvtk.ConeSource() for i in range(50)] # Now get another ConeSource and ensure the hash is different. cs = tvtk.ConeSource() o = cs.output if hasattr(o, 'producer_port'): src = o.producer_port.producer else: src = cs.executive.algorithm ############################################################## # This assertion is related to a bug fixed in VTK 6 onwards # For VTK 5.x this test is inconsistent, hence skipeed for 5.x # See http://review.source.kitware.com/#/c/15095/ ############################################################## if vtk_major_version > 5: self.assertEqual(hash1 != hash(src), True) self.assertEqual(hash(cs), hash(src)) # Test for a bug with collections and the object cache. r = tvtk.Renderer() def _get_props(obj): if hasattr(obj, 'view_props'): return obj.view_props else: return obj.props p = _get_props(r) l1 = len(tvtk_base._object_cache) p1 = _get_props(r) del p1 l2 = len(tvtk_base._object_cache) self.assertEqual(l1, l2)
def test_property_change_notification(self): """Test if changes to properties generate notification events.""" # Create a dummy class to test with. class Junk: def f(self, obj, name, old, new): self.data = obj, name, old, new z = Junk() cs = tvtk.ConeSource() m = tvtk.PolyDataMapper() if vtk_major_version < 6: m.on_trait_change(z.f, 'input') m.input = cs.output self.assertEqual(z.data, (m, 'input', None, cs.output)) m.input = None self.assertEqual(z.data, (m, 'input', cs.output, None)) m.on_trait_change(z.f, 'input', remove=True) m.input = cs.output else: m.on_trait_change(z.f, 'input_connection') m.input_connection = cs.output_port self.assertEqual(z.data, (m, 'input_connection', None, cs.output_port)) m.input_connection = None self.assertEqual(z.data, (m, 'input_connection', cs.output_port, None)) m.on_trait_change(z.f, 'input_connection', remove=True) m.input_connection = cs.output_port a = tvtk.Actor() a.on_trait_change(z.f, 'mapper') a.on_trait_change(z.f, 'property') a.mapper = m self.assertEqual(z.data, (a, 'mapper', None, m)) old = a.property new = tvtk.Property() a.property = new self.assertEqual(z.data, (a, 'property', old, new)) # Check if property notification occurs on add_input/remove_input a = tvtk.AppendPolyData() pd = tvtk.PolyData() if vtk_major_version < 6: a.on_trait_change(z.f, 'input') a.add_input(pd) old, new = None, pd self.assertEqual(z.data, (a, 'input', old, new)) a.remove_input(pd) old, new = pd, None self.assertEqual(z.data, (a, 'input', old, new)) a.remove_all_inputs() old, new = None, None self.assertEqual(z.data, (a, 'input', old, new)) else: a.add_input_data(pd) self.assertEqual(a.input, pd) a.remove_input_data(pd) self.assertEqual(a.input, None) a.remove_all_inputs() self.assertEqual(a.input, None)
def test_simple_usage(self): # Given cs = tvtk.ConeSource() ef = tvtk.ElevationFilter(input_connection=cs.output_port) # When p = PipelineBrowser(root_object=[ef]) # Then self.assertEqual(len(p._root.children), 1) kids = list(p._root.children) self.assertEqual(kids[0].name, 'ElevationFilter') gk = list(kids[0].children) self.assertEqual(len(gk), 1) self.assertEqual(gk[0].name, 'ConeSource') ggk = list(gk[0].children) self.assertEqual(len(ggk), 0) # Check if the default traits_view returns correctly. p.default_traits_view() # When # Check if editing a selected object fires a ui change. self.count = 0 def callback(): self.count += 1 p.on_trait_change(callback, 'object_edited') p._on_select(gk[0]) cs.height = 2.0 # Then self.assertTrue(self.count > 0)
def drawsoma(): pts = self.mitral.soma.points center = misc.centroid(pts) # calc. soma radius radius = 0. for p in pts: radius += misc.distance(p, center) radius /= len(pts) radius *= cone_factor # versor u = tuple( misc.versor(self.mitral.apic.points[0], self.mitral.apic.points[1])) src = tvtk.ConeSource(center=tuple(center[0:3]), radius=radius, height=radius, direction=u, resolution=20) mapper = tvtk.PolyDataMapper(input=src.output) actor = tvtk.Actor(mapper=mapper) fig.scene.add_actor(actor) actor.property.color = self.soma_color return actor
def setUp(self): self.cs = cs = tvtk.ConeSource() self.ef = ef = tvtk.ElevationFilter(input_connection=cs.output_port) self.m = m = tvtk.PolyDataMapper(input_connection=ef.output_port) self.a = tvtk.Actor(mapper=m) self.ren = tvtk.Renderer() self.ren.add_actor(self.a) self.renwin = tvtk.RenderWindow() self.renwin.add_renderer(self.ren)
def test_object_cache(self): """Test if object cache works.""" cs = tvtk.ConeSource() hash1 = hash(cs) o = cs.output if hasattr(o, 'producer_port'): src = o.producer_port.producer else: src = cs.executive.algorithm self.assertEqual(src, cs) self.assertEqual(hash1, hash(src)) del cs, src gc.collect() # The test sometimes fails as VTK seems to generate objects with the # same memory address and hash, we try to force it to allocate more # objects so as to not end up reusing the same address and hash. junk = [vtk.vtkConeSource() for i in range(5)] # Now get another ConeSource and ensure the hash is different. cs = tvtk.ConeSource() o = cs.output if hasattr(o, 'producer_port'): src = o.producer_port.producer else: src = cs.executive.algorithm self.assertEqual(hash1 != hash(src), True) self.assertEqual(hash(cs), hash(src)) # Test for a bug with collections and the object cache. r = tvtk.Renderer() def _get_props(obj): if hasattr(obj, 'view_props'): return obj.view_props else: return obj.props p = _get_props(r) l1 = len(tvtk_base._object_cache) p1 = _get_props(r) del p1 l2 = len(tvtk_base._object_cache) self.assertEqual(l1, l2)
def get_cone(base, radius, v): if type(base) != tuple: base = tuple(base) if type(v) != tuple: v = tuple(v) src = tvtk.ConeSource(center=base, radius=radius*radius_factor, height=radius, direction=v, resolution=20) mapper = tvtk.PolyDataMapper(input=src.output) actor = tvtk.Actor(mapper=mapper) fig.scene.add_actor(actor) return actor
def _glyph_dict_default(self): g = {'glyph_source2d': tvtk.GlyphSource2D(glyph_type='arrow', filled=False), 'arrow_source': tvtk.ArrowSource(), 'cone_source': tvtk.ConeSource(height=1.0, radius=0.2, resolution=15), 'cylinder_source': tvtk.CylinderSource(height=1.0, radius=0.15, resolution=10), 'sphere_source': tvtk.SphereSource(), 'cube_source': tvtk.CubeSource(), 'axes': tvtk.Axes(symmetric=1)} return g
def test_basic(self): """Test a simple tvtk pipeline.""" # If this works without any problems, we are ok. cs = tvtk.ConeSource() m = tvtk.PolyDataMapper() m.input_connection = cs.output_port # This should work. m.set_input_data(cs.get_output()) # This should also work. a = tvtk.Actor() a.mapper = m cs.resolution = 36 p = a.property p.representation = 'w'
def test01(): s = tvtk.ConeSource(height=6.0, radius=2.0) m = tvtk.PolyDataMapper(input_connection=s.output_port) a = tvtk.Actor(mapper=m) r = tvtk.Renderer(background=(1, 0, 0)) r.add_actor(a) w = tvtk.RenderWindow(size=(300, 300)) w.add_renderer(r) i = tvtk.RenderWindowInteractor(render_window=w) i.initialize() i.start()
def main(instantiate_gui=True): """Simple test case.""" from tvtk.tools import ivtk v = ivtk.viewer(browser=False, instantiate_gui=instantiate_gui) cs = tvtk.ConeSource() m = tvtk.PolyDataMapper(input_connection=cs.output_port) a = tvtk.Actor(mapper=m) v.scene.add_actor(a) v.scene.reset_zoom() b = PipelineBrowser(v.scene) b.show() return v, b, a
def test_init_traits(self): """Test if the objects traits can be set in __init__.""" p = tvtk.Property(opacity=0.1, color=(1, 0, 0), representation='p') self.assertEqual(p.opacity, 0.1) self.assertEqual(p.color, (1.0, 0.0, 0.0)) self.assertEqual(p.representation, 'points') # Test case where the object traits are wrong. self.assertRaises(TraitError, tvtk.Property, foo='bar') cs = tvtk.ConeSource(radius=0.1, height=0.5, resolution=32) self.assertEqual(cs.radius, 0.1) self.assertEqual(cs.height, 0.5) self.assertEqual(cs.resolution, 32) # Test case where the object traits are wrong. self.assertRaises(TraitError, tvtk.ConeSource, foo=1)
def cone_actor(center=(0, 0, 0), height=1.0, radius=0.5, direction=(1, 0, 0), resolution=100, color=colors.red, opacity=1.0): """ Sets up a cone actor and returns the tvtk.Actor object.""" source = tvtk.ConeSource(center=center, height=height, radius=radius, direction=direction, resolution=resolution) mapper = tvtk.PolyDataMapper(input=source.output) p = tvtk.Property(opacity=opacity, color=color) actor = tvtk.Actor(mapper=mapper, property=p) return actor
def test(): for module_name in [ 'numpy', 'scipy', 'pandas', 'statsmodels', 'pytables', 'xarray', 'dask', 'PIL', 'sqlalchemy', 'psycopg2', 'pymongo', 'rasterio', 'shapely', 'fiona', 'rasterio', 'geopandas', 'mercantile', 'pyproj', 'hdf4', 'hdf5', 'h5py', 'netcdf4', 'matplotlib', 'seaborn', 'bokeh', 'holoviews', 'geoviews', 'notebook', 'flask', 'marshmallow', 'theano', 'tensorflow', 'keras' ]: print("Importing {}:".format(module_name)) module = None try: module = importlib.import_module(module_name) except (ImportError, AttributeError): try: module = importlib.import_module(module_name) except (ImportError, AttributeError): print(" Import failed") if module is None: continue try: print(" version={}".format(module.__version__)) except AttributeError: print(" No version available") print("Importing gdal:") from osgeo import gdal print(" version={}".format(gdal.__version__)) print("Importing tvtk:") from tvtk.api import tvtk from tvtk.common import configure_input cs = tvtk.ConeSource() cs.resolution = 36 m = tvtk.PolyDataMapper() configure_input(m, cs.output) a = tvtk.Actor() a.mapper = m p = a.property p.representation = 'w' print(" OK")
def __source_dict_default(self): """Default value for source dict.""" sd = { 'arrow': tvtk.ArrowSource(), 'cone': tvtk.ConeSource(), 'cube': tvtk.CubeSource(), 'cylinder': tvtk.CylinderSource(), 'disk': tvtk.DiskSource(), 'earth': tvtk.EarthSource(), 'line': tvtk.LineSource(), 'outline': tvtk.OutlineSource(), 'plane': tvtk.PlaneSource(), 'point': tvtk.PointSource(), 'polygon': tvtk.RegularPolygonSource(), 'sphere': tvtk.SphereSource(), 'superquadric': tvtk.SuperquadricSource(), 'textured sphere': tvtk.TexturedSphereSource(), 'glyph2d': tvtk.GlyphSource2D() } return sd
def test_data_changed_is_fired_when_object_is_modified(self): # Given cs = tvtk.ConeSource() # When src = mlab.pipeline.add_dataset(cs) # Then self.assertTrue(isinstance(src, VTKObjectSource)) # When self.count = 0 def callback(): self.count += 1 src.on_trait_change(callback, 'data_changed') cs.height = 2.0 # Then self.assertTrue(self.count > 0)
def PlotCone(Figure, Radius=1., Origin=(0, 0, 0), Resolution=10, Height=1., Direction=(0, 0, 1)): cone = tvtk.ConeSource(center=Origin, radius=Radius, resolution=Resolution, height=Height, direction=Direction) configure_input_data(tvtk.PolyDataMapper(), cone.output) cone.update() p = tvtk.Property(opacity=0.8, color=RED) actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(), property=p) Figure.scene.add_actor(actor)
def plot_vectors(self): """ Plots vectors on the Bloch sphere. """ from mayavi import mlab from tvtk.api import tvtk import matplotlib.colors as colors ii = 0 for k in range(len(self.vectors)): vec = np.array(self.vectors[k]) norm = np.linalg.norm(vec) theta = np.arccos(vec[2] / norm) phi = np.arctan2(vec[1], vec[0]) vec -= 0.5 * self.vector_head_height * \ np.array([np.sin(theta) * np.cos(phi), np.sin(theta) * np.sin(phi), np.cos(theta)]) color = colors.colorConverter.to_rgb(self.vector_color[np.mod( k, len(self.vector_color))]) mlab.plot3d([0, vec[0]], [0, vec[1]], [0, vec[2]], name='vector' + str(ii), tube_sides=100, line_width=self.vector_width, opacity=self.vector_alpha[k], color=color) cone = tvtk.ConeSource(height=self.vector_head_height, radius=self.vector_head_radius, resolution=100) cone_mapper = tvtk.PolyDataMapper( input_connection=cone.output_port) prop = tvtk.Property(opacity=self.vector_alpha[k], color=color) cc = tvtk.Actor(mapper=cone_mapper, property=prop) cc.rotate_z(np.degrees(phi)) cc.rotate_y(-90 + np.degrees(theta)) cc.position = vec self.fig.scene.add_actor(cc)
def test_simple_vtk_object_source(self): # Given cs = tvtk.ConeSource() ef = tvtk.ElevationFilter(input_connection=cs.output_port) engine = self.e # When src = VTKObjectSource(object=ef) engine.add_source(src) # Then self.assertEqual(src.outputs[0], ef) self.assertEqual(src.browser.root_object, [ef]) self.assertEqual(src.output_info.datasets, ['any']) self.assertEqual(src.name, 'VTK (ElevationFilter)') # When src.object = cs # Then self.assertEqual(src.outputs[0], cs) self.assertEqual(src.browser.root_object, [cs]) self.assertEqual(src.output_info.datasets, ['poly_data']) self.assertEqual(src.name, 'VTK (ConeSource)')
def test_glyph_pipeline(self): # Given rta = tvtk.RTAnalyticSource() cs = tvtk.ConeSource() g = tvtk.Glyph3D(input_connection=rta.output_port) g.set_source_connection(cs.output_port) m = tvtk.PolyDataMapper(input_connection=g.output_port) tg = self._make_tree_generator() # When/Then kids = tg.get_children(cs) self.assertEqual(len(kids), 0) kids = tg.get_children(rta) self.assertEqual(len(kids), 0) kids = tg.get_children(g) self.assertEqual(len(kids), 2) self.assertEqual(kids['input'], [rta, cs]) kids = tg.get_children(m) self.assertEqual(len(kids), 3) self.assertEqual(kids['input'], [g]) self.assertEqual(kids['lookup_table'], m.lookup_table)
# -*- coding: utf-8 -*- from tvtk.api import tvtk # 创建一个圆锥数据源,并且同时设置其高度,底面半径和底面圆的分辨率(用36边形近似) cs = tvtk.ConeSource(height=3.0, radius=1.0, resolution=36) # 使用PolyDataMapper将数据转换为图形数据 m = tvtk.PolyDataMapper(input_connection=cs.output_port) # 创建一个Actor a = tvtk.Actor(mapper=m) # 创建一个Renderer,将Actor添加进去 ren = tvtk.Renderer(background=(1, 1, 1)) ren.add_actor(a) # 创建一个RenderWindow(窗口),将Renderer添加进去 rw = tvtk.RenderWindow(size=(300, 300)) rw.add_renderer(ren) # 创建一个RenderWindowInteractor(窗口的交互工具) rwi = tvtk.RenderWindowInteractor(render_window=rw) # 开启交互 rwi.initialize() rwi.start()
def vtk_actors(self): if (self.actors is None): self.actors = [] points = _getfem_to_tvtk_points(self.sl.pts()) (triangles, cv2tr) = self.sl.splxs(2) triangles = numpy.array(triangles.transpose(), 'I') data = tvtk.PolyData(points=points, polys=triangles) if self.scalar_data is not None: data.point_data.scalars = numpy.array(self.scalar_data) if self.vector_data is not None: data.point_data.vectors = numpy.array(self.vector_data) if self.glyph_name is not None: mask = tvtk.MaskPoints() mask.maximum_number_of_points = self.glyph_nb_pts mask.random_mode = True mask.input = data if self.glyph_name == 'default': if self.vector_data is not None: self.glyph_name = 'arrow' else: self.glyph_name = 'ball' glyph = tvtk.Glyph3D() glyph.scale_mode = 'scale_by_vector' glyph.color_mode = 'color_by_scalar' #glyph.scale_mode = 'data_scaling_off' glyph.vector_mode = 'use_vector' # or 'use_normal' glyph.input = mask.output if self.glyph_name == 'arrow': glyph.source = tvtk.ArrowSource().output elif self.glyph_name == 'ball': glyph.source = tvtk.SphereSource().output elif self.glyph_name == 'cone': glyph.source = tvtk.ConeSource().output elif self.glyph_name == 'cylinder': glyph.source = tvtk.CylinderSource().output elif self.glyph_name == 'cube': glyph.source = tvtk.CubeSource().output else: raise Exception("Unknown glyph name..") #glyph.scaling = 1 #glyph.scale_factor = self.glyph_scale_factor data = glyph.output if self.show_faces: ## if self.deform is not None: ## data.point_data.vectors = array(numarray.transpose(self.deform)) ## warper = tvtk.WarpVector(input=data) ## data = warper.output ## lut = tvtk.LookupTable() ## lut.hue_range = 0.667,0 ## c=gf_colormap('tripod') ## lut.number_of_table_values=c.shape[0] ## for i in range(0,c.shape[0]): ## lut.set_table_value(i,c[i,0],c[i,1],c[i,2],1) self.mapper = tvtk.PolyDataMapper(input=data) self.mapper.scalar_range = self.scalar_data_range self.mapper.scalar_visibility = True # Create mesh actor for display self.actors += [tvtk.Actor(mapper=self.mapper)] if self.show_edges: (Pe, E1, E2) = self.sl.edges() if Pe.size: E = numpy.array( numpy.concatenate((E1.transpose(), E2.transpose()), axis=0), 'I') edges = tvtk.PolyData(points=_getfem_to_tvtk_points(Pe), polys=E) mapper_edges = tvtk.PolyDataMapper(input=edges) actor_edges = tvtk.Actor(mapper=mapper_edges) actor_edges.property.representation = 'wireframe' #actor_edges.property.configure_traits() actor_edges.property.color = self.edges_color actor_edges.property.line_width = self.edges_width actor_edges.property.ambient = 0.5 self.actors += [actor_edges] if self.sl.nbsplxs(1): # plot tubes (seg, cv2seg) = self.sl.splxs(1) seg = numpy.array(seg.transpose(), 'I') data = tvtk.Axes(origin=(0, 0, 0), scale_factor=0.5, symmetric=1) data = tvtk.PolyData(points=points, lines=seg) tube = tvtk.TubeFilter(radius=0.4, number_of_sides=10, vary_radius='vary_radius_off', input=data) mapper = tvtk.PolyDataMapper(input=tube.output) actor_tubes = tvtk.Actor(mapper=mapper) #actor_tubes.property.representation = 'wireframe' actor_tubes.property.color = self.tube_color #actor_tubes.property.line_width = 8 #actor_tubes.property.ambient = 0.5 self.actors += [actor_tubes] if self.use_scalar_bar: self.scalar_bar = tvtk.ScalarBarActor( title=self.scalar_data_name, orientation='horizontal', width=0.8, height=0.07) self.scalar_bar.position_coordinate.coordinate_system = 'normalized_viewport' self.scalar_bar.position_coordinate.value = 0.1, 0.01, 0.0 self.actors += [self.scalar_bar] if (self.lookup_table is not None): self.set_colormap(self.lookup_table) return self.actors
def _get_primitive(self): return tvtk.ConeSource(center=self.center, height=self.height, radius=self.radius, direction=self.direction, resolution=self.resolution)
SelectionSource SphereSource SuperquadricSource TessellatedBoxSource TextSource TexturedSphereSource UniformHyperTreeGridSource VideoSource VolumeOutlineSource Win32VideoSource ''' # 立方体 s1 = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0) # 圆锥 s2 = tvtk.ConeSource(center=(1, 5, 6)) # pprint(dir(s2)) print(s2) a = 1 # a.__getattribute__() # # a.__se # a.__get # 显示一个三维度对象 for item in dir(tvtk): if not item.endswith("Source"): continue try: s2 = tvtk.__getattribute__(item)() if not hasattr(s2, "output_port"): print(item) continue print("on:", item)
# coding: utf-8 #from tvtk.tools import tvtk_doc #tvtk_doc.main() from tvtk.api import tvtk s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0) s1 = tvtk.ConeSource(radius=1.0, height=2.0) m = tvtk.PolyDataMapper(input_connection=s1.output_port) a = tvtk.Actor(mapper=m) w = tvtk.RenderWindow(size=(300, 350)) r = tvtk.Renderer(background=(0, 0, 0)) r.add_actor(a) w.add_renderer(r) i = tvtk.RenderWindowInteractor(render_window=w) i.initialize() i.start()
#!/usr/bin/env python """A simple example demonstrating TVTK. This example is basically a translation of the VTK tutorial demo available in VTK/Examples/Tutorial/Step6/Python/Cone6.py. """ # Author: Prabhu Ramachandran <*****@*****.**> # Copyright (c) 2004, Enthought, Inc. # License: BSD Style. from tvtk.api import tvtk # Create a cone source and configure it. cs = tvtk.ConeSource() cs.height = 3.0 cs.radius = 1.0 cs.resolution = 36 # Print the traits of the cone. #cs.print_traits() val = tvtk.PolyData() #val = cs.get_output() val.print_traits() # Setup the rest of the pipeline. m = tvtk.PolyDataMapper() # Note that VTK's GetOutput method is special because it has two call # signatures: GetOutput() and GetOutput(int N) (which gets the N'th
from tvtk.api import tvtk from CStvtkfunc import ivtk_scene, event_loop #读入PLot3D数据 plot3d = tvtk.MultiBlockPLOT3DReader(xyz_file_name="Element\combxyz.bin", q_file_name="Element\combq.bin", scalar_function_number=100, vector_function_number=200) plot3d.update() grid = plot3d.output.get_block(0) #对数据集中的数据进行随机选取,每50个点选择一个点 mask = tvtk.MaskPoints(random_mode=True, on_ratio=50) mask.set_input_data(grid) #创建表示箭头的PolyData数据集 glyph_source = tvtk.ConeSource() #在Mask采样后的PolyData数据集每个点上放置一个箭头 #箭头的方向、长度和颜色由于点对应的矢量和标量数据决定 glyph = tvtk.Glyph3D(input_connection=mask.output_port, scale_factor=2) glyph.set_source_connection(glyph_source.output_port) m = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range, input_connection=glyph.output_port) a = tvtk.Actor(mapper=m) #窗口绘制 win = ivtk_scene(a) win.scene.isometric_view() event_loop()