def __init__(self, points, **traits): super(MLabBase, self).__init__(**traits) assert len(points[0]) == 3, "The points must be 3D" self.points = points np = len(points) - 1 lines = numpy.zeros((np, 2), 'l') lines[:, 0] = numpy.arange(0, np - 0.5, 1, 'l') lines[:, 1] = numpy.arange(1, np + 0.5, 1, 'l') pd = tvtk.PolyData(points=points, lines=lines) self.poly_data = pd mapper = tvtk.PolyDataMapper() self.mapper = mapper tf = self.tube_filter tf.radius = self.radius if self.use_tubes: tf.input = pd mapper.input = tf.output a = _make_actor(mapper=mapper) a.property.color = self.color self.actors.append(a)
def __init__(self, renwin, **traits): super(Picker, self).__init__(**traits) self.renwin = renwin self.pointpicker = tvtk.PointPicker() self.cellpicker = tvtk.CellPicker() self.worldpicker = tvtk.WorldPointPicker() self.probe_data = tvtk.PolyData() self._tolerance_changed(self.tolerance) # Use a set of axis to show the picked point. self.p_source = tvtk.Axes() self.p_mapper = tvtk.PolyDataMapper() self.p_actor = tvtk.Actor() self.p_source.symmetric = 1 self.p_actor.pickable = 0 self.p_actor.visibility = 0 prop = self.p_actor.property prop.line_width = 2 prop.ambient = 1.0 prop.diffuse = 0.0 self.p_mapper.input = self.p_source.output self.p_actor.mapper = self.p_mapper self.probe_data.points = [[0.0, 0.0, 0.0]] self.ui = None
def view(): col0 = numpy.arange(0, numpts - 1, 1) col1 = numpy.arange(1, numpts, 1) lines = array([col0, col1]).transpose() curve = tvtk.PolyData(points=points, lines=lines) # assign temperature in sequence so that we now the "direction" of the curve curve.point_data.scalars = numpy.arange(0, numpts, 1) curve.point_data.scalars.name = 'temperature' from enthought.mayavi.sources.vtk_data_source import VTKDataSource #from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.surface import Surface from enthought.mayavi.modules.axes import Axes from enthought.mayavi.modules.text import Text scene = mayavi.new_scene() scene.scene.background = (1.0, 1.0, 1.0) scene.scene.foreground = (0.0, 0.0, 0.0) src = VTKDataSource(data=curve) mayavi.add_source(src) #mayavi.add_module(Outline()) s = Surface() mayavi.add_module(s) s.actor.property.set(representation='p', color=(0., 1., 0.), line_width=2)
def __init__(self, points, vectors=None, scalars=None, **traits): super(Glyphs, self).__init__(**traits) if vectors is not None: assert len(points) == len(vectors) if scalars is not None: assert len(points) == len(scalars) self.points = points self.vectors = vectors self.scalars = scalars polys = numpy.arange(0, len(points), 1, 'l') polys = numpy.reshape(polys, (len(points), 1)) pd = tvtk.PolyData(points=points, polys=polys) if self.vectors is not None: pd.point_data.vectors = vectors pd.point_data.vectors.name = 'vectors' if self.scalars is not None: pd.point_data.scalars = scalars pd.point_data.scalars.name = 'scalars' self.poly_data = pd self.glyph.input = pd if self.glyph_source: self.glyph.source = self.glyph_source.output mapper = tvtk.PolyDataMapper(input=self.glyph.output) actor = _make_actor(mapper=mapper) actor.property.color = self.color self.actors.append(actor)
def _redraw_elements(self): if self.construction: jp = self.construction.joint_positions[ self.construction.element_index_table].reshape((-1, 2)) self._elements_polydata.points = pts2dto3d(jp) self._elements_polydata.lines = N.r_[:len( self.construction.elements) * 2].reshape( (-1, 2)) # => [[0,1],[2,3],[4,5],...] radii = N.array( [e.material.radius for e in self.construction.elements]) self._elements_polydata.point_data.scalars = N.column_stack( (radii, radii)).ravel() * self.amplify_radius # set scalars of elements when enabled by the user if self.show_simulation and self.construction.simulated and len( self.construction.elements) > 0: # show element stress if self.show_scalar == 'stress': self._elements_actor.mapper.lookup_table = self._scalar_bar_stress.lookup_table breakage = (N.abs( self.construction.simulation_result.element_stresses) / self.construction.max_element_stress_array ) * 100. # percentual breakage self._elements_polydata.cell_data.scalars = breakage self._scalar_bar_stress.lookup_table.table_range = \ self._elements_actor.mapper.scalar_range = (0, 100) # show element strain elif self.show_scalar == 'strain': self._elements_actor.mapper.lookup_table = self._scalar_bar_strain.lookup_table strains = self.construction.simulation_result.element_strains self._elements_polydata.cell_data.scalars = strains # set strain scalar range if self.auto_scalar_range: max_strain = N.abs(strains).max() scalar_range = (-max_strain, max_strain) else: scalar_range = (-self.scalar_range_max, self.scalar_range_max) self._scalar_bar_strain.lookup_table.table_range = \ self._elements_actor.mapper.scalar_range = scalar_range else: self._elements_polydata.cell_data.scalars = None # deformed wireframe model: if self.show_simulation and self.construction.simulated and len(self.construction.joints) > 0 \ and self.construction.simulation_result.okay: # amplify displacements so they become visible jp = self.construction.joint_positions + \ self.construction.simulation_result.joint_displacements * self.displacement_amplify_factor self._deformed_elements_polydata.points = pts2dto3d(jp) self._deformed_elements_polydata.lines = self.construction.element_index_table self._deformed_elements_actor.visibility = True else: self._deformed_elements_actor.visibility = False # redraw selected element highlight if isinstance(self.selected_object, model.Element): self._hl_element_ribbons.input = tvtk.PolyData(\ points=[list(self.selected_object.joint1.position)+[0], list(self.selected_object.joint2.position)+[0]], lines=[[0,1]]) self._hl_element_ribbons.width = max( self.selected_object.material.radius, 0.05) * 2.0
def plot_cell(cell): p = tvtk.PolyData() p.points = cell.points poly = [] ids = list(cell.point_ids) for i in xrange(cell.number_of_faces): poly.append([ids.index(x) for x in cell.get_face(i).point_ids]) p.polys = poly mlab.pipeline.surface(p, opacity=0.3)
def make_scatter(self): pd = tvtk.PolyData() pd.points = 100 + 100 * random.random((1000, 3)) verts = arange(0, 1000, 1) verts.shape = (1000, 1) pd.verts = verts pd.point_data.scalars = random.random(1000) pd.point_data.scalars.name = 'scalars' return pd
def cpy_to_vtk(cpy): pd = tvtk.AppendPolyData() names = [] for name, (points, panels) in cpy.iteritems(): p = tvtk.PolyData(points=points, polys=panels) names.append(name) p.cell_data.scalars = len(names) * np.ones(panels.shape[0]) pd.add_input(p) return names, pd
def fault(showTaper=False): vertices = numpy.array( [ [12.0, 0.0, 0.0], # 0 [12.0, 12.0, 0.0], # 1 [12.0, 16.0, 0.0], # 2 [12.0, 0.0, -12.0], # 3 [12.0, 12.0, -12.0], # 4 [12.0, 0.0, -16.0], # 5 [12.0, 12.0, -16.0], # 6 [12.0, 16.0, -16.0] ], # 7 dtype=numpy.float32) # Setup VTK vertices if not showTaper: polys = numpy.array( [ [0, 3, 1], [1, 3, 4], [3, 5, 4], [4, 5, 6], [1, 6, 2], [2, 6, 7] ], dtype=numpy.int32) # Setup VTK simplices data = [{'name': "fault", 'object': tvtk.PolyData(points=vertices, polys=polys)}] else: polys = numpy.array( [ [0, 3, 1], [1, 3, 4] ], dtype=numpy.int32) polysTaper = numpy.array( [ [3, 5, 4], [4, 5, 6], [1, 6, 2], [2, 6, 7] ], dtype=numpy.int32) data= [{'name': "fault", 'object': tvtk.PolyData(points=vertices, polys=polys)}, {'name': "taper", 'object': tvtk.PolyData(points=vertices, polys=polysTaper)}] return data
def _setup_elements_picker(self): if self.scene and self.construction: #print "setup elements picker" pd = tvtk.PolyData(points=pts2dto3d( self.construction.joint_positions), lines=self.construction.element_index_table) self._pick_elements_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper( input=pd)) self._element_picker = tvtk.CellPicker(pick_from_list=True, tolerance=0.005) self._element_picker.pick_list.append(self._pick_elements_actor)
def visual_test(jpos, jfreedom, loads, elements, E, r, p, max_stress=3e+8): displacements, strains, stresses, mass, status, times = analyse_truss(jpos, jfreedom, loads, elements, E, r, p) jpos_d = jpos + displacements*100 print status print times print 'displacements: ', displacements print 'strains: ', strains print 'stresses: ', stresses #strains_abs = N.abs(strains) from enthought.tvtk.api import tvtk from enthought.tvtk.tools import ivtk from enthought.pyface.api import GUI v = ivtk.viewer(False, False) v.scene.z_plus_view() pd = tvtk.PolyData() pts = jpos[elements].reshape((-1,2)) pd.points = N.column_stack((pts[:,0], pts[:,1], N.zeros(len(pts)))) pd.lines = N.r_[:len(elements)*2].reshape((-1,2)) pd.cell_data.scalars = -strains pd.point_data.scalars = N.column_stack((r, r)).ravel() #tubes = tvtk.TubeFilter(input=pd, radius=N.sqrt(element_A.max() / N.pi), number_of_sides=16) tubes = tvtk.TubeFilter(input=pd, number_of_sides=16, vary_radius='vary_radius_by_absolute_scalar', capping=True) #tubes = tvtk.RibbonFilter(input=pd, use_default_normal=True, vary_width=True) b = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=tubes.output, scalar_range=(-N.abs(strains).max(), N.abs(strains).max()), scalar_mode='use_cell_data')) b.mapper.lookup_table.hue_range = (0, 0.66) v.scene.add_actor(b) pd1 = tvtk.PolyData() pd1.points = N.column_stack((jpos_d[:,0], jpos_d[:,1], N.zeros(len(jpos)))) pd1.lines = elements tubes1 = tvtk.TubeFilter(input=pd1, radius=0.01, number_of_sides=16) a = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=tubes1.output)) a.property.opacity = 0.3 v.scene.add_actor(a) print "strain: ", strains.min(), strains.max() v.scene.reset_zoom() GUI().start_event_loop()
def make_triangle_polydata(triangles, points, scalars=None): t = numpy.asarray(triangles, 'l') assert t.shape[1] == 3, "The list of polygons must be Nx3." if scalars is not None: assert len(points) == len(numpy.ravel(scalars)) pd = tvtk.PolyData(points=points, polys=t) if scalars is not None: pd.point_data.scalars = numpy.ravel(scalars) pd.point_data.scalars.name = 'scalars' return pd
def setUp(self): datasets = [ tvtk.ImageData(), tvtk.StructuredPoints(), tvtk.RectilinearGrid(), tvtk.StructuredGrid(), tvtk.PolyData(), tvtk.UnstructuredGrid(), ] exts = ['.vti', '.vti', '.vtr', '.vts', '.vtp', '.vtu'] self.datasets = datasets self.exts = exts
def polydata(): # The numpy array data. points = array([[0, -0.5, 0], [1.5, 0, 0], [0, 1, 0], [0, 0, 0.5], [-1, -1.5, 0.1], [0, -1, 0.5], [-1, -0.5, 0], [1, 0.8, 0]], 'f') triangles = array([[0, 1, 3], [1, 2, 3], [1, 0, 5], [2, 3, 4], [3, 0, 4], [0, 5, 4], [2, 4, 6], [2, 1, 7]]) scalars = random.random(points.shape) # The TVTK dataset. mesh = tvtk.PolyData(points=points, polys=triangles) mesh.point_data.scalars = scalars mesh.point_data.scalars.name = 'scalars' return mesh
def reset(self, **traits): """Creates the dataset afresh or resets existing data source.""" # First set the attributes without really doing anything since # the notification handlers are not called. self.set(trait_change_notify=False, **traits) points = self.points scalars = self.scalars x, y, z = self.x, self.y, self.z points = np.c_[x.ravel(), y.ravel(), z.ravel()].ravel() points.shape = (points.size/3, 3) self.set(points=points, trait_change_notify=False) triangles = self.triangles assert triangles.shape[1] == 3, \ "The shape of the triangles array must be (X, 3)" assert triangles.max() < len(points), \ "The triangles indices must be smaller that the number of points" assert triangles.min() >= 0, \ "The triangles indices must be positive or null" if self.dataset is None: pd = tvtk.PolyData() else: pd = self.dataset # Set the points first, and the triangles after: so that the # polygone can refer to the right points, in the polydata. pd.set(points=points) pd.set(polys=triangles) if (not 'scalars' in traits and scalars is not None and scalars.shape != x.shape): # The scalars where set probably automatically to z, by the # factory. We need to reset them, as the size has changed. scalars = z if scalars is not None and len(scalars) > 0: if not scalars.flags.contiguous: scalars = scalars.copy() self.set(scalars=scalars, trait_change_notify=False) assert x.shape == scalars.shape pd.point_data.scalars = scalars.ravel() pd.point_data.scalars.name = 'scalars' self.dataset = pd
def reset(self, **traits): """Creates the dataset afresh or resets existing data source.""" # First set the attributes without really doing anything since # the notification handlers are not called. self.set(trait_change_notify=False, **traits) points = self.points scalars = self.scalars x, y, z = self.x, self.y, self.z assert len(x.shape) == 2, "Array x must be 2 dimensional." assert len(y.shape) == 2, "Array y must be 2 dimensional." assert len(z.shape) == 2, "Array z must be 2 dimensional." assert x.shape == y.shape, "Arrays x and y must have same shape." assert y.shape == z.shape, "Arrays y and z must have same shape." #Points in the grid source will always be created using x,y,z #Changing of points is not allowed because it cannot be used to modify values of x,y,z nx, ny = x.shape points = np.c_[x.ravel(), y.ravel(), z.ravel()].ravel() points.shape = (nx*ny, 3) self.set(points=points, trait_change_notify=False) i, j = np.mgrid[0:nx-1,0:ny-1] i, j = np.ravel(i), np.ravel(j) t1 = i*ny+j, (i+1)*ny+j, (i+1)*ny+(j+1) t2 = (i+1)*ny+(j+1), i*ny+(j+1), i*ny+j nt = len(t1[0]) triangles = np.zeros((nt*2, 3), 'l') triangles[0:nt,0], triangles[0:nt,1], triangles[0:nt,2] = t1 triangles[nt:,0], triangles[nt:,1], triangles[nt:,2] = t2 if self.dataset is None: pd = tvtk.PolyData() else: pd = self.dataset pd.set(points=points, polys=triangles) if scalars is not None and len(scalars) > 0: if not scalars.flags.contiguous: scalars = scalars.copy() self.set(scalars=scalars, trait_change_notify=False) assert x.shape == scalars.shape pd.point_data.scalars = scalars.ravel() pd.point_data.scalars.name = 'scalars' self.dataset = pd
def add_lines(self, points): np = len(points) - 1 lines = scipy.zeros((np, 2), "l") lines[:, 0] = scipy.arange(0, np - 0.5, 1, "l") lines[:, 1] = scipy.arange(1, np + 0.5, 1, "l") pd = tvtk.PolyData(points=points, lines=lines) d = VTKDataSource() d.data = pd self.scene.add_child(d) filter = tvtk.TubeFilter(number_of_sides=6) filter.radius = 0.01 f = FilterBase(filter=filter, name="TubeFilter") d.add_child(f) s = Surface() s.actor.mapper.scalar_visibility = False d.add_child(s)
def ProbeData(self, coordinates, name): """Interpolate field values at these coordinates.""" # Initialise locator bbox = self.ugrid.bounds locator = tvtk.PointLocator(data_set=self.ugrid, tolerance=10.0) locator.update() # Initialise probe points = tvtk.Points() ilen, jlen = coordinates.shape for i in range(ilen): points.insert_next_point(coordinates[i][0], coordinates[i][1], coordinates[i][2]) polydata = tvtk.PolyData(points=points) probe = tvtk.ProbeFilter(input=polydata, source=self.ugrid) probe.update() # Reposition invalid nodes at nearest mesh vertices alid_ids = probe.valid_points valid_points = tvtk.Points() valid_loc = 0 for i in range(ilen): if valid_ids.get_tuple1(valid_loc) == i: valid_points.insert_next_point(coordinates[i][0], coordinates[i][1], coordinates[i][2]) valid_loc = valid_loc + 1 else: nearest = locator.find_closest_point( [coordinates[i][0], coordinates[i][1], coordinates[i][2]]) point = self.ugrid.points.get_point(nearest) valid_points.insert_next_point(point[0], point[1], point[2]) polydata.points = valid_points probe.input = polydata probe.update() # Get final updated values pointdata = probe.output.point_data vtkdata = pointdata.get_array(name) nc = vtkdata.number_of_components() nt = vtkdata.number_of_tuples() array = arr(vtkdata) array.shape = (nt, nc) return array
def test_array_conversion(self): """Test if Numeric/VTK array conversion works.""" # This is only a simple test. data = numpy.array( [[0, 0, 0, 10], [1, 0, 0, 20], [0, 1, 0, 20], [0, 0, 1, 30]], 'f') triangles = numpy.array([[0, 1, 3], [0, 3, 2], [1, 2, 3], [0, 2, 1]]) points = data[:, :3] temperature = data[:, -1] mesh = tvtk.PolyData() mesh.points = points mesh.polys = triangles mesh.point_data.scalars = temperature # Test if a normal float array also works. temp = tvtk.FloatArray() temp.from_array(temperature) mesh.point_data.scalars = temp
def reset(self, **traits): """Creates the dataset afresh or resets existing data source.""" # First set the attributes without really doing anything since # the notification handlers are not called. self.set(trait_change_notify=False, **traits) points = self.points scalars = self.scalars x, y, z = self.x, self.y, self.z if 'points' in traits: x=points[:,0].ravel() y=points[:,1].ravel() z=points[:,2].ravel() self.set(x=x,y=y,z=z,trait_change_notify=False) else: points = np.c_[x.ravel(), y.ravel(), z.ravel()].ravel() points.shape = (len(x), 3) self.set(points=points, trait_change_notify=False) # Create the dataset. n_pts = len(points) - 1 lines = np.zeros((n_pts, 2), 'l') lines[:,0] = np.arange(0, n_pts-0.5, 1, 'l') lines[:,1] = np.arange(1, n_pts+0.5, 1, 'l') if self.dataset is None: pd = tvtk.PolyData() else: pd = self.dataset # Avoid lines refering to non existing points: First set the # lines to None, then set the points, then set the lines # refering to the new points. pd.set(lines=None) pd.set(points=points) pd.set(lines=lines) if scalars is not None and len(scalars) > 0: assert len(x) == len(scalars) pd.point_data.scalars = np.ravel(scalars) pd.point_data.scalars.name = 'scalars' self.dataset = pd
def test_tvtk_dataset_name(self): "Can tvtk datasets can be converted to names correctly." datasets = [ tvtk.ImageData(), tvtk.StructuredPoints(), tvtk.RectilinearGrid(), tvtk.StructuredGrid(), tvtk.PolyData(), tvtk.UnstructuredGrid(), tvtk.Property(), # Not a dataset! 'foo', # Not a TVTK object. ] expect = [ 'image_data', 'image_data', 'rectilinear_grid', 'structured_grid', 'poly_data', 'unstructured_grid', 'none', 'none' ] result = [pipeline_info.get_tvtk_dataset_name(d) for d in datasets] self.assertEqual(result, expect)
def _mk_polydata(self): """ Creates a PolyData vtk data set using the factory's attributes. """ points = c_[self.position_x.ravel(), self.position_y.ravel(), self.position_z.ravel(), ] lines = None if self.lines: np = len(points) - 1 lines = zeros((np, 2), 'l') lines[:, 0] = arange(0, np - 0.5, 1, 'l') lines[:, 1] = arange(1, np + 0.5, 1, 'l') self._vtk_source = tvtk.PolyData(points=points, lines=lines) if (self.connectivity_triangles is not None and self.connected): assert self.connectivity_triangles.shape[1] == 3, \ "The connectivity list must be Nx3." self._vtk_source.polys = self.connectivity_triangles self._mayavi_source = VTKDataSource(data=self._vtk_source)
def _drawLines(self, points, color=[1,1,1]): nrays = points.shape[0] npts = points.shape[2] nsegs = npts - 1 lines = np.zeros((nsegs*nrays, 2), 'l') pts_cat = np.zeros([npts*nrays, 3], 'f') for j in range(nrays): pts_cat[(j*npts):((j+1)*npts), :] = points[j,:,:].T lines[(j*nsegs):((j+1)*nsegs),0] = (j*npts) + np.arange(0, nsegs-0.5, 1, 'l') lines[(j * nsegs):((j + 1) * nsegs),1] = (j * npts) + np.arange(1, nsegs + 0.5, 1, 'l') #lines[:,1] = np.arange(1, nsegs+0.5, 1, 'l') d = tvtk.PolyData(points=pts_cat, lines=lines) m = tvtk.PolyDataMapper() configure_input_data(m, d) a = tvtk.Actor(mapper=m) a.property.color = color self.f.scene.add_actor(a) return a
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() 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 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() a.on_trait_change(z.f, 'input') pd = tvtk.PolyData() 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))
def main(): # Create some random points to view. pd = tvtk.PolyData() pd.points = np.random.random((1000, 3)) verts = np.arange(0, 1000, 1) verts.shape = (1000, 1) pd.verts = verts pd.point_data.scalars = np.random.random(1000) pd.point_data.scalars.name = 'scalars' # Now visualize it using mayavi2. from enthought.mayavi.sources.vtk_data_source import VTKDataSource from enthought.mayavi.modules.outline import Outline from enthought.mayavi.modules.surface import Surface mayavi.new_scene() d = VTKDataSource() d.data = pd mayavi.add_source(d) mayavi.add_module(Outline()) s = Surface() mayavi.add_module(s) s.actor.property.set(representation='p', point_size=2)
def reset(self, **traits): """Creates the dataset afresh or resets existing data source.""" # First convert numbers to arrays. for name in ('x', 'y', 'z', 'u', 'v', 'w', 'scalars'): if name in traits and traits[name] is not None: traits[name] = np.atleast_1d(traits[name]) # First set the attributes without really doing anything since # the notification handlers are not called. self.set(trait_change_notify=False, **traits) vectors = self.vectors scalars = self.scalars points = self.points x, y, z = self.x, self.y, self.z x = np.atleast_1d(x) y = np.atleast_1d(y) z = np.atleast_1d(z) if 'points' in traits: x=points[:,0].ravel() y=points[:,1].ravel() z=points[:,2].ravel() self.set(x=x,y=y,z=z,trait_change_notify=False) else: points = np.c_[x.ravel(), y.ravel(), z.ravel()].ravel() points.shape = (points.size/3, 3) self.set(points=points, trait_change_notify=False) u, v, w = self.u, self.v, self.w if u is not None: u = np.atleast_1d(u) v = np.atleast_1d(v) w = np.atleast_1d(w) if len(u) > 0: vectors = np.c_[u.ravel(), v.ravel(), w.ravel()].ravel() vectors.shape = (vectors.size/3, 3) self.set(vectors=vectors, trait_change_notify=False) if 'vectors' in traits: u=vectors[:,0].ravel() v=vectors[:,1].ravel() w=vectors[:,2].ravel() self.set(u=u,v=v,w=w,trait_change_notify=False) else: if u is not None and len(u) > 0: vectors = np.c_[u.ravel(), v.ravel(), w.ravel()].ravel() vectors.shape = (vectors.size/3, 3) self.set(vectors=vectors, trait_change_notify=False) if vectors is not None and len(vectors) > 0: assert len(points) == len(vectors) if scalars is not None: scalars = np.atleast_1d(scalars) if len(scalars) > 0: assert len(points) == len(scalars) # Create the dataset. polys = np.arange(0, len(points), 1, 'l') polys = np.reshape(polys, (len(points), 1)) if self.dataset is None: # Create new dataset if none exists pd = tvtk.PolyData() else: # Modify existing one. pd = self.dataset pd.set(points=points, polys=polys) if self.vectors is not None: pd.point_data.vectors = self.vectors pd.point_data.vectors.name = 'vectors' if self.scalars is not None: pd.point_data.scalars = self.scalars pd.point_data.scalars.name = 'scalars' self.dataset = pd
from enthought.mayavi import mlab #from enthought.mayavi.sources.vtk_data_source import VTKDataSource import numpy as np point = np.array([0, 0, 0]) tensor = np.array([20, 0, 0, 0, 20, 0, 0, 0, 20]) engine = mlab.get_engine() engine.start() scene = engine.new_scene() scene.scene.disable_render = True # for speed glyphs = [] for i in range(10): data = tvtk.PolyData(points=[point]) data.point_data.tensors = [tensor] data.point_data.tensors.name = 'some_name' data.point_data.scalars = [i] #data.point_data.scalars.name = 'some_other_name' #mlab.clf() #src = VTKDataSource(data=data) #e = mlab.get_engine() #e.add_source(src) glyph = mlab.pipeline.tensor_glyph(data) glyph.glyph.glyph_source.glyph_source.theta_resolution = 50 glyph.glyph.glyph_source.glyph_source.phi_resolution = 50 actor = glyph.actor # mayavi actor, actor.actor is tvtk actor
def probe_data(mayavi_object, x, y, z, type='scalars', location='points'): """ Retrieve the data from a described by Mayavi visualization object at points x, y, z. **Parameters** :viz_obj: A Mayavi visualization object, or a VTK dataset The object describing the data you are interested in. :x: float or ndarray. The x position where you want to retrieve the data. :y: float or ndarray. The y position where you want to retrieve the data. :z: float or ndarray The z position where you want to retrieve the data. :type: 'scalars', 'vectors' or 'tensors', optional The type of the data to retrieve. :location: 'points' or 'cells', optional The location of the data to retrieve. **Returns** The values of the data at the given point, as an ndarray (or multiple arrays, in the case of vectors or tensors) of the same shape as x, y, and z. """ dataset = tools.get_vtk_src(mayavi_object)[0] assert type in ('scalars', 'vectors', 'cells'), ( "Invalid value for type: must be 'scalars', 'vectors' or " "'cells', but '%s' was given" % type) x = np.atleast_1d(x) y = np.atleast_1d(y) z = np.atleast_1d(z) shape = x.shape assert y.shape == z.shape == shape, \ 'The x, y and z arguments must have the same shape' probe_data = mesh = tvtk.PolyData(points=np.c_[x.ravel(), y.ravel(), z.ravel()]) shape = list(shape) probe = tvtk.ProbeFilter() probe.input = probe_data probe.source = dataset probe.update() if location == 'points': data = probe.output.point_data elif location == 'cells': data = probe.output.cell_data else: raise ValueError("Invalid value for data location, must be " "'points' or 'cells', but '%s' was given." % location) values = getattr(data, type) if values is None: raise ValueError("The object given has no %s data of type %s" % (location, type)) values = values.to_array() if type == 'scalars': values = np.reshape(values, shape) elif type == 'vectors': values = np.reshape(values, shape + [3, ]) values = np.rollaxis(values, -1) else: values = np.reshape(values, shape + [-1, ]) values = np.rollaxis(values, -1) return values
temperature = data[:, -1] ### TVTK PIPELINE # create a renderer renderer = tvtk.Renderer() # create a render window and hand it the renderer render_window = tvtk.RenderWindow(size=(400, 400)) render_window.add_renderer(renderer) # create interactor and hand it the render window # This handles mouse interaction with window. interactor = tvtk.RenderWindowInteractor(render_window=render_window) # Create a mesh from the data created above. mesh = tvtk.PolyData(points=points, polys=triangles) mesh.point_data.scalars = temperature # Set the mapper to scale temperature range # across the entire range of colors mapper = tvtk.PolyDataMapper(input=mesh) mapper.scalar_range = min(temperature), max(temperature) # Create mesh actor for display actor = tvtk.Actor(mapper=mapper) # Create a scalar bar scalar_bar = tvtk.ScalarBarActor(title="Temperature", orientation='horizontal', width=0.8, height=0.17,
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