예제 #1
0
    def test_collection(self):
        """Test if Collection objects work nicely."""
        ac = tvtk.ActorCollection()
        self.assertEqual(len(ac), 0)
        self.assertRaises(IndexError, ac.__getitem__, 0)
        a_list = []
        a = tvtk.Actor()
        a_list.append(a)
        ac.append(a)
        self.assertRaises(TypeError, ac.__getitem__, 's')
        self.assertEqual(len(ac), 1)
        a = tvtk.Actor()
        a_list.append(a)
        ac.append(a)
        self.assertEqual(len(ac), 2)

        # Test iterator nature.
        for i, j in zip(ac, a_list):
            self.assertEqual(i._vtk_obj, j._vtk_obj)
        for i, j in enumerate(ac):
            self.assertEqual(a_list[i]._vtk_obj, j._vtk_obj)

        # Test __setitem__.
        ac[0] = a_list[1]
        ac[1] = a_list[0]
        self.assertEqual(ac[0]._vtk_obj, a_list[1]._vtk_obj)
        self.assertEqual(ac[1]._vtk_obj, a_list[0]._vtk_obj)
        self.assertRaises(TypeError, ac.__setitem__, 's', a_list[1])

        # Test __delitem__.
        del ac[-2]
        self.assertEqual(ac[0]._vtk_obj, a_list[0]._vtk_obj)
        self.assertEqual(len(ac), 1)
        self.assertRaises(TypeError, ac.__delitem__, 1.414)
        del ac[0]
        self.assertEqual(len(ac), 0)

        # Test __repr__.
        self.assertEqual(repr(ac), '[]')

        # test extend.
        ac.extend(a_list)
        self.assertEqual(len(ac), 2)
        for i, j in enumerate(ac):
            self.assertEqual(a_list[i]._vtk_obj, j._vtk_obj)

        # Test the prop collection.
        pc = tvtk.PropCollection()
        a = tvtk.Actor()
        pc.append(a)
        self.assertEqual(pc[0], a)
        for i in pc:
            self.assertEqual(i, a)
예제 #2
0
def earth_actor(radius=0.5, opacity=1.0):
    """ Creates an earth source and returns the actor. """
    source = tvtk.EarthSource(radius=radius, on_ratio=16, outline=0)
    mapper = tvtk.PolyDataMapper(input=source.output)
    prop = tvtk.Property(opacity=opacity)
    actor = tvtk.Actor(mapper=mapper, property=prop)
    return actor
예제 #3
0
 def __init__(self, *args, **kwargs):
     Primitive.__init__(self, **kwargs)
     self.source = tvtk.ConeSource()
     self.polyDataMapper = tvtk.PolyDataMapper()
     self.polyDataMapper.input = self.source.output
     self.actor = tvtk.Actor(mapper=self.polyDataMapper)
     self.handle_arguments(*args, **kwargs)
예제 #4
0
    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
예제 #5
0
 def add_isocontour(self, val=None):
     if val is None: val = (self._max_val + self._min_val) * 0.5
     isocontour = tvtk.ContourFilter(executive=tvtk.CompositeDataPipeline())
     isocontour.input = self._hdata_set
     isocontour.generate_values(1, (val, val))
     lut_manager = LUTManager(data_name=self.field, scene=self.scene)
     isocontour_normals = tvtk.PolyDataNormals(
         executive=tvtk.CompositeDataPipeline())
     isocontour_normals.input_connection = isocontour.output_port
     iso_mapper = tvtk.HierarchicalPolyDataMapper(
         input_connection=isocontour_normals.output_port,
         lookup_table=lut_manager.lut)
     iso_mapper.scalar_range = (self._min_val, self._max_val)
     iso_actor = tvtk.Actor(mapper=iso_mapper)
     self.scene.add_actors(iso_actor)
     self.operators.append(
         MappingIsoContour(operator=isocontour,
                           vmin=self._min_val,
                           vmax=self._max_val,
                           vdefault=val,
                           mapper=iso_mapper,
                           post_call=self.scene.render,
                           lut_manager=lut_manager,
                           scene=self.scene))
     return self.operators[-1]
예제 #6
0
 def add_contour(self, val=None):
     if val is None:
         if self._min_val != self._min_val:
             self._min_val = 1.0
         val = (self._max_val + self._min_val) * 0.5
     cubes = tvtk.MarchingCubes(executive=tvtk.CompositeDataPipeline())
     cubes.input = self._hdata_set
     cubes.set_value(0, val)
     lut_manager = LUTManager(data_name=self.field, scene=self.scene)
     cube_mapper = tvtk.HierarchicalPolyDataMapper(
         input_connection=cubes.output_port, lookup_table=lut_manager.lut)
     cube_mapper.color_mode = 'map_scalars'
     cube_mapper.scalar_range = (self._min_val, self._max_val)
     cube_actor = tvtk.Actor(mapper=cube_mapper)
     self.scene.add_actors(cube_actor)
     self.operators.append(
         MappingMarchingCubes(operator=cubes,
                              vmin=self._min_val,
                              vmax=self._max_val,
                              vdefault=val,
                              mapper=cube_mapper,
                              post_call=self.scene.render,
                              lut_manager=lut_manager,
                              scene=self.scene))
     return self.operators[-1]
예제 #7
0
 def _redraw_background_plane(self):
     if self.construction and self.scene:
         if self._bg_plane_width == self.construction.width and self._bg_plane_height == self.construction.height:
             return
         if self._bg_plane_actor:
             self.scene.remove_actor(self._bg_plane_actor)
         if self._axis:
             self.scene.remove_actor(self._axis)
         w, h = self.construction.width, self.construction.height
         plane = tvtk.PlaneSource(x_resolution=int(w), y_resolution=int(h))
         scalation = tvtk.Transform()
         scalation.scale((w, h, 1))
         scale_plane = tvtk.TransformPolyDataFilter(transform=scalation,
                                                    input=plane.output)
         self._bg_plane_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(
             input=scale_plane.output))
         self._bg_plane_actor.property.set(representation='wireframe',
                                           line_stipple_pattern=0xF0F0,
                                           opacity=0.15)
         self.scene.add_actor(self._bg_plane_actor)
         self._axis = tvtk.CubeAxesActor2D(
             camera=self.scene.camera,
             z_axis_visibility=False,
             corner_offset=0,
             bounds=[-w / 2, w / 2, -h / 2, h / 2, 0, 0])
         self.scene.add_actor(self._axis)
         self._bg_plane_picker = tvtk.CellPicker(tolerance=0,
                                                 pick_from_list=True)
         self._bg_plane_picker.pick_list.append(self._bg_plane_actor)
         self._bg_plane_width, self._bg_plane_height = self.construction.width, self.construction.height
예제 #8
0
    def __init__(self,
                 filename,
                 colour=None,
                 position=[0, 0, 0],
                 orientation=None,
                 rotation=None):
        self.filename = filename
        self.reader = tvtk.STLReader(file_name=filename)
        self.mapper = tvtk.PolyDataMapper()
        configure_input_data(self.mapper, self.reader.output)
        self.reader.update()
        self.actor = tvtk.Actor(mapper=self.mapper)

        if colour:
            self.actor.property.color = colour

        self.actor.position = position
        if rotation is None:
            if orientation is None:
                self.actor.orientation = [0, 0, 0]
            else:
                a2 = -180 * np.arctan(orientation[0] / orientation[1]) / np.pi
                a1 = 180 * np.arcsin(orientation[2]) / np.pi
                self.actor.orientation = [a1, 0, a2]
        else:
            self.actor.orientation = rotation
    def make_probe(self):
        src = self.ipl.poly_data_algorithm

        map = tvtk.PolyDataMapper(lookup_table=self.lm.lut)
        act = tvtk.Actor(mapper=map)

        calc_B = self.calc_B
        calc_B.input = src.output

        def execute():
            print "calc fields!"
            output = calc_B.poly_data_output
            points = output.points.to_array().astype('d')
            nodes = self.wire.nodes.astype('d')
            vectors = calc_wire_B_field(nodes, points, self.wire.radius)
            output.point_data.vectors = vectors
            mag = np.sqrt((vectors**2).sum(axis=1))
            map.scalar_range = (mag.min(), mag.max())

        calc_B.set_execute_method(execute)

        cone = tvtk.ConeSource(height=0.05, radius=0.01, resolution=15)
        cone.update()

        glyph = self.glyph
        glyph.input_connection = calc_B.output_port
        glyph.source = cone.output
        glyph.scale_mode = 'scale_by_vector'
        glyph.color_mode = 'color_by_vector'

        map.input_connection = glyph.output_port
        self.scene.add_actor(act)
예제 #10
0
 def _scene_default(self):
     cube = self.cube
     map = tvtk.PolyDataMapper(input=cube.output)
     act = tvtk.Actor(mapper=map)
     scene = SceneModel()
     scene.add_actor(act)
     return scene
예제 #11
0
 def __init__(self, *args, **kwargs):
     Primitive.__init__(self, *kwargs)
     self.source = tvtk.Axes(symmetric=1)
     self.tube = tvtk.TubeFilter(vary_radius='vary_radius_off',
                                 input=self.source.output)
     self.mapper = tvtk.PolyDataMapper(input=self.tube.output)
     self.actor = tvtk.Actor(mapper=self.mapper)
     self.handle_arguments(*args, **kwargs)
예제 #12
0
def cube_actor(center=(0, 0, 0), color=colors.blue, opacity=1.0):
    """ Creates a cube and returns the tvtk.Actor. """

    source = tvtk.CubeSource(center=center)    
    mapper = tvtk.PolyDataMapper(input=source.output)
    p = tvtk.Property(opacity=opacity, color=color)
    actor = tvtk.Actor(mapper=mapper, property=p)
    return actor
예제 #13
0
def arrow_actor(color=colors.peacock, opacity=1.0, resolution=24):
    """ Creates a 3D Arrow and returns an actor. """
    source = tvtk.ArrowSource(tip_resolution=resolution,
                              shaft_resolution=resolution)
    mapper = tvtk.PolyDataMapper(input=source.output)
    prop = tvtk.Property(opacity=opacity, color=color)
    actor = tvtk.Actor(mapper=mapper, property=prop)
    return actor
예제 #14
0
def cylinder_actor(center=(0, 0, 0), radius=0.5, resolution=64,
                   color=colors.green, opacity=1.0):
    """ Creates a cylinder and returns a tvtk.Actor. """
    source = tvtk.CylinderSource(center=center, radius=radius,
                                 resolution=resolution)
    mapper = tvtk.PolyDataMapper(input=source.output)
    prop = tvtk.Property(opacity=opacity, color=color)
    actor = tvtk.Actor(mapper=mapper, property=prop)
    return actor
 def _make_pipeline(self):
     self.func.on_trait_change(self.on_change, "anytrait")
     src = self.source
     src.on_trait_change(self.on_change, "anytrait")
     src.parametric_function = self.func
     map = tvtk.PolyDataMapper(input_connection=src.output_port)
     act = tvtk.Actor(mapper=map)
     self.scene.add_actor(act)
     self.src = src
예제 #16
0
def axes_actor(origin=(0, 0, 0), scale_factor=1.0, radius=0.02,
               sides=12):
    """Creates a simple axes actor and returns a tvtk.Actor object."""
    axes = tvtk.Axes(origin=origin, scale_factor=scale_factor, symmetric=1)
    tube = tvtk.TubeFilter(radius=radius, number_of_sides=sides,
                           vary_radius='vary_radius_off',
                           input=axes.output)
    mapper = tvtk.PolyDataMapper(input=tube.output)
    actor = tvtk.Actor(mapper=mapper)
    return actor
예제 #17
0
def sphere_actor(center=(0, 0, 0), radius=0.5, resolution=32,
                 color=colors.purple, opacity=1.0):
    """ Creates a sphere and returns the actor. """
    source = tvtk.SphereSource(center=center, radius=radius,
                               theta_resolution=resolution,
                               phi_resolution=resolution)
    mapper = tvtk.PolyDataMapper(input=source.output)
    prop = tvtk.Property(opacity=opacity, color=color)
    actor = tvtk.Actor(mapper=mapper, property=prop)
    return actor
예제 #18
0
def _make_actor(**kwargs):
    """Return a TVTK actor.  If `mlab.USE_LOD_ACTOR` is `True` it
    returns an LODActor if not it returns a normal actor.
    """
    if USE_LOD_ACTOR:
        r = tvtk.LODActor(number_of_cloud_points=1500)
        r.property.point_size = 2.0
        r.set(**kwargs)
        return r
    else:
        return tvtk.Actor(**kwargs)
예제 #19
0
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
예제 #20
0
 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)
예제 #21
0
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()
예제 #22
0
 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 = cs.output  # This should work.
     m.input = cs.get_output()  # This should also work.
     a = tvtk.Actor()
     a.mapper = m
     cs.resolution = 36
     p = a.property
     p.representation = 'w'
예제 #23
0
 def toggle_grid_boundaries(self):
     if self._grid_boundaries_actor is None:
         # We don't need to track this stuff right now.
         ocf = tvtk.OutlineCornerFilter(
             executive=tvtk.CompositeDataPipeline(), corner_factor=0.5)
         ocf.input = self._hdata_set
         ocm = tvtk.HierarchicalPolyDataMapper(
             input_connection=ocf.output_port)
         self._grid_boundaries_actor = tvtk.Actor(mapper=ocm)
         self.scene.add_actor(self._grid_boundaries_actor)
     else:
         self._grid_boundaries_actor.visibility = \
         (not self._grid_boundaries_actor.visibility)
예제 #24
0
 def _add_plane(self, origin=(0.0, 0.0, 0.0), normal=(0, 1, 0)):
     plane = tvtk.Plane(origin=origin, normal=normal)
     cutter = tvtk.Cutter(executive=tvtk.CompositeDataPipeline(),
                          cut_function=plane)
     cutter.input = self._hdata_set
     lut_manager = LUTManager(data_name=self.field, scene=self.scene)
     smap = tvtk.HierarchicalPolyDataMapper(
         scalar_range=(self._min_val, self._max_val),
         lookup_table=lut_manager.lut,
         input_connection=cutter.output_port)
     sactor = tvtk.Actor(mapper=smap)
     self.scene.add_actors(sactor)
     return plane, lut_manager
예제 #25
0
def show(d):
    l = tvtk.LookupTable(table_range=(0, 1))
    m = tvtk.PolyDataMapper(input=d.output,
                            scalar_visibility=True,
                            scalar_mode="use_cell_data")
    p = tvtk.Property(representation="s")
    a = tvtk.Actor(mapper=m, property=p)

    ren = tvtk.Renderer(background=(.1, .2, .4))
    ren.add_actor(a)
    rw = tvtk.RenderWindow(size=(600, 600))
    rw.add_renderer(ren)
    rwi = tvtk.RenderWindowInteractor(render_window=rw)
    rwi.initialize()
    rwi.start()
예제 #26
0
def main(instantiate_gui=True):
    """Simple test case."""
    from enthought.tvtk.tools import ivtk

    v = ivtk.viewer(browser=False, instantiate_gui=instantiate_gui)
    cs = tvtk.ConeSource()
    m = tvtk.PolyDataMapper(input=cs.output)
    a = tvtk.Actor(mapper=m)
    v.scene.add_actor(a)
    v.scene.reset_zoom()

    b = PipelineBrowser(v.scene)
    b.show()

    return v, b, a
예제 #27
0
 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
예제 #28
0
    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))
예제 #29
0
    def _get_actor_or_follower(self, old=None):
        """ Get a tvtk.Actor or a tvtk.Follower for the actor of the
            object and wire the callbacks to it.
            If old is given, it is the old actor, to remove its
            callbacks.
        """
        if self.orient_to_camera:
            new = tvtk.Follower()
            if self.scene is not None:
                new.camera = self.scene.camera
        else:
            new = tvtk.Actor()
        if old is not None:
            self.sync_trait('position', old, 'position', remove=True)
            self.sync_trait('scale', old, 'scale', remove=True)
            self.sync_trait('orientation', old, 'orientation', remove=True)

        self.sync_trait('position', new, 'position')
        self.sync_trait('scale', new, 'scale')
        self.sync_trait('orientation', new, 'orientation')
        return new
예제 #30
0
파일: tvtk.py 프로젝트: cggos/sci_cmp
# -*- coding: utf-8 -*-
"""
Created on Wed Nov  9 08:36:22 2016

@author: Gordon
"""

from enthought.tvtk.api import tvtk

# 创建一个圆锥数据源,并且同时设置其高度,底面半径和底面圆的分辨率(用36边形近似)
cs = tvtk.ConeSource(height=3.0, radius=1.0, resolution=36)
# 使用PolyDataMapper将数据转换为图形数据
m = tvtk.PolyDataMapper(input = cs.output)
# 创建一个Actor
a = tvtk.Actor(mapper=m)
# 创建一个Renderer,将Actor添加进去
ren = tvtk.Renderer(background=(0.1, 0.2, 0.4))
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()