Exemple #1
0
def mesh_as_vtk_polydata(verts,
                         tris=None,
                         uv=None,
                         normals=None,
                         tris_uv=None,
                         tris_normals=None):
    # do vertex and uv or normal topology differ? in that case, flatten those arrays
    if tris is not None and (tris_uv is not None or tris_normals is not None):
        if tris_normals is None:
            tris_normals = tris
        if tris_uv is None:
            tris_uv = tris
        verts_flat = verts[tris].reshape(-1, 3)
        tris_flat = np.arange(len(verts_flat)).reshape(-1, 3)

        pd = tvtk.PolyData(points=verts_flat, polys=tris_flat)
        if uv is not None:
            pd.point_data.t_coords = uv[tris_uv].reshape(-1, 2)
        if normals is not None:
            pd.point_data.normals = normals[tris_normals].reshape(-1, 3)
    else:
        # use data as-is
        pd = tvtk.PolyData(points=verts)
        if tris is not None:
            pd.polys = tris
        if uv is not None:
            assert len(uv) == len(verts)
            pd.point_data.t_coords = uv
        if normals is not None:
            assert len(normals) == len(verts)
            pd.point_data.normals = normals

    return pd
Exemple #2
0
    def plot_mesh(self, mlab, geo):

        points = geo['node_X']
        triangles = geo['t_elem_node_map']
        quads = geo['q_elem_node_map']
        #scalars = random.random(points.shape)

        # The TVTK dataset.
        qmesh = tvtk.PolyData(points=points, polys=quads)
        mlab.pipeline.surface(qmesh, representation='wireframe')

        # The TVTK dataset.
        tmesh = tvtk.PolyData(points=points, polys=triangles)
        mlab.pipeline.surface(tmesh, representation='wireframe')
Exemple #3
0
    def __init__(self, renwin, **traits):
        super(Picker, self).__init__(**traits)

        self.pointpicker = tvtk.PointPicker()
        self.cellpicker = tvtk.CellPicker()
        self.worldpicker = tvtk.WorldPointPicker()
        self.probe_data = tvtk.PolyData()
        # 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
        configure_input(self.p_mapper, self.p_source)
        self.p_actor.mapper = self.p_mapper

        self.probe_data.points = [[0.0, 0.0, 0.0]]

        self.text_rep = tvtk.TextRepresentation()
        self.text_widget = tvtk.TextWidget()
        self.data = PickedData(renwin=renwin)
        self.data.text_actor = tvtk.TextActor()
        self.text_setup()
        self.widgets = False
Exemple #4
0
    def _render_mesh(self,
                     mesh_type="surface",
                     ambient_light=0.0,
                     specular_light=0.0,
                     alpha=1.0):
        from tvtk.api import tvtk

        pd = tvtk.PolyData()
        pd.points = self.points
        pd.polys = self.trilist
        pd.point_data.t_coords = self.tcoords_per_point
        mapper = tvtk.PolyDataMapper()
        mapper.set_input_data(pd)
        p = tvtk.Property(
            representation=mesh_type,
            opacity=alpha,
            ambient=ambient_light,
            specular=specular_light,
        )
        actor = tvtk.Actor(mapper=mapper, property=p)
        # Get the pixels from our image class which are [0, 1] and scale
        # back to valid pixels. Then convert to tvtk ImageData.
        texture = self.texture.pixels_with_channels_at_back(out_dtype=np.uint8)
        if self.texture.n_channels == 1:
            texture = np.stack([texture] * 3, axis=-1)
        image_data = np.flipud(texture).ravel()
        image_data = image_data.reshape([-1, 3])
        image = tvtk.ImageData()
        image.point_data.scalars = image_data
        image.dimensions = self.texture.width, self.texture.height, 1
        texture = tvtk.Texture()
        texture.set_input_data(image)
        actor.texture = texture
        self.figure.scene.add_actors(actor)
        self._actors.append(actor)
Exemple #5
0
def main(hdf5_animation_file, sid='50004', pid='jiggle_on_toes'):
    with h5py.File(hdf5_animation_file, 'r') as f:
        verts = f[sid + '_' + pid].value.transpose([2, 0, 1])
        tris = f['faces'].value

    pd = tvtk.PolyData(points=verts[0], polys=tris)
    normals = tvtk.PolyDataNormals(input=pd, splitting=False)
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=normals.output))
    actor.property.set(edge_color=(0.5, 0.5, 0.5),
                       ambient=0.0,
                       specular=0.15,
                       specular_power=128.,
                       shading=True,
                       diffuse=0.8)

    fig = mlab.figure(bgcolor=(1, 1, 1))
    fig.scene.add_actor(actor)

    @mlab.animate(delay=40, ui=False)
    def animation():
        for i in count():
            frame = i % len(verts)
            pd.points = verts[frame]
            fig.scene.render()
            yield

    a = animation()
    fig.scene.z_minus_view()
    mlab.show()
def convexhull(ch3d):
    poly = tvtk.PolyData()
    poly.points = ch3d.points
    poly.polys = ch3d.simplices
    sphere = tvtk.SphereSource(radius=0.02)
    points3d = tvtk.Glyph3D()
    points3d.set_source_connection(sphere.output_port)
    points3d.set_input_data(poly)
    # 绘制凸多面体的面,设置半透明度
    m1 = tvtk.PolyDataMapper()
    m1.set_input_data(poly)
    a1 = tvtk.Actor(mapper=m1)
    a1.property.opacity = 0.3
    # 绘制凸多面体的边,设置为红色
    m2 = tvtk.PolyDataMapper()
    m2.set_input_data(poly)
    a2 = tvtk.Actor(mapper=m2)
    a2.property.representation = "wireframe"
    a2.property.line_width = 2.0
    a2.property.color = (1.0, 0, 0)
    # 绘制凸多面体的顶点,设置为绿色
    m3 = tvtk.PolyDataMapper(input_connection=points3d.output_port)
    a3 = tvtk.Actor(mapper=m3)
    a3.property.color = (0.0, 1.0, 0.0)
    return [a1, a2, a3]
Exemple #7
0
def draw_cubic_solid(origin,size):
    actors = []
    x = numpy.array([1,0,0])
    y = numpy.array([0,1,0])
    z = numpy.array([0,0,1])

    verts = [ origin + y*size,
              origin + y*size + x*size,
              origin + y*size + x*size + z*size,
              origin + y*size + z*size,
              origin,
              origin + x*size,
              origin + x*size + z*size,
              origin + z*size]

    # indexes into verts
    edges = [ [0,1], [1,2], [2,3], [3,0],
              [4,5], [5,6], [6,7], [7,4],
              [4,0], [5,1], [6,2], [7,3] ]

    pd = tvtk.PolyData()
    pd.points = verts
    pd.lines = edges
    if 1:
        pt = tvtk.TubeFilter(radius=0.0254*0.5,input=pd,
                             number_of_sides=12,
                             vary_radius='vary_radius_off',
                             )
        m = tvtk.PolyDataMapper(input=pt.output)
        a = tvtk.Actor(mapper=m)
        a.property.color = .9, .9, .9
        a.property.specular = 0.3
        actors.append(a)
    return actors
def grid2poly(grid):
    """ Read grid and convert to polydata """
    points = grid.nodes
    
    face_coords_mask = np.dstack([grid.faces.mask, grid.faces.mask])
    face_coords = np.ma.masked_array(
        grid.nodes[grid.faces], 
        face_coords_mask
    )

    # select faces that we need to duplicate
    # TODO: duplicate these (with nodes moved to other end of the world) (mod something...)
    x_max, y_max = face_coords.max(axis=(1)).T
    x_min, y_min = face_coords.min(axis=(1)).T
    mask = (x_min < -150) & (x_max > 150) 

    # Select faces
    faces = grid.faces[~mask]
    n_cells = faces.shape[0]
    cell_array = tvtk.CellArray()

    counts = (~faces.mask).sum(axis=1)
    assert faces.min() >= 0, 'expected 0 based faces'
    cell_idx = np.c_[counts, faces.filled(-999)].ravel()
    cell_idx = cell_idx[cell_idx != -999]
    cell_array.set_cells(n_cells, cell_idx)

    # fill in the properties
    polydata = tvtk.PolyData()
    # fill in z dimension
    polydata.points = np.c_[points, np.zeros_like(points[:, 0])]
    polydata.polys = cell_array
        
    return polydata, mask 
Exemple #9
0
def main(hdf5_animation_file):
    weights = None
    with h5py.File(hdf5_animation_file, 'r') as f:
        verts = f['verts'].value
        tris = f['tris'].value
        if 'weights' in f:
            weights = f['weights'].value

    pd = tvtk.PolyData(points=verts[0], polys=tris)
    normals = tvtk.PolyDataNormals(input=pd, splitting=False)
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(input=normals.output))
    actor.property.set(edge_color=(0.5, 0.5, 0.5), ambient=0.0,
                       specular=0.15, specular_power=128., shading=True, diffuse=0.8)

    fig = mlab.figure(bgcolor=(1,1,1))
    fig.scene.add_actor(actor)

    @mlab.animate(delay=40, ui=False)
    def animation():
        for i in count():
            if weights is not None:
                w_str = ",".join(["%0.2f"] * weights.shape[1])
                print ("Frame %d Weights = " + w_str) % tuple([i] + weights[i].tolist())
            frame = i % len(verts)
            pd.points = verts[frame]
            fig.scene.render()
            yield

    a = animation()
    fig.scene.z_minus_view()
    mlab.show()
Exemple #10
0
def cal_mesh_normals_api(verts,tris):
    pd = tvtk.PolyData(points=verts, polys=tris)
    n = tvtk.PolyDataNormals(input=pd,splitting=False)
    n.update()
    norms = n.output.point_data.normals
    #already normalized
    return norms
    def setup_pipeline(self):
        """Override this method so that it *creates* the tvtk
        pipeline.

        This method is invoked when the object is initialized via
        `__init__`.  Note that at the time this method is called, the
        tvtk data pipeline will *not* yet be setup.  So upstream data
        will not be available.  The idea is that you simply create the
        basic objects and setup those parts of the pipeline not
        dependent on upstream sources and filters.  You should also
        set the `actors` attribute up at this point.
        """
        # Create and setup the default objects.
        self.seed = tvtk.PolyData(points=self.seed_points)
        self.stream_tracer = tvtk.StreamTracer(
            maximum_propagation=2000,
            integration_direction='backward',
            compute_vorticity=False,
            integrator_type='runge_kutta4',
        )
        self.ribbon_filter = tvtk.RibbonFilter()
        self.tube_filter = tvtk.TubeFilter()

        self.actor = mayavi.components.actor.Actor()
        # Setup the actor suitably for this module.
        self.actor.property.line_width = 2.0
Exemple #12
0
def depos2pts(arr):
    '''
    Convert numpy array like which comes from 'depo_data_0' key of npz
    file from NumpyDepoSaver to tvtk unstructured grid.
    '''
    from tvtk.api import tvtk, write_data

    npts = arr.shape[1]
    # t,q,x,y,z,dl,dt
    q = arr[1, :].reshape(npts)
    pts = arr[2:5, :].T

    indices = list(range(npts))

    ret = tvtk.PolyData(points=pts)
    verts = numpy.arange(0, npts, 1)
    verts.shape = (npts, 1)
    ret.verts = verts
    ret.point_data.scalars = indices[:npts]
    ret.point_data.scalars.name = 'indices'

    ret.point_data.add_array(q)
    ret.point_data.get_array(1).name = 'charge'

    return ret
Exemple #13
0
def save_evaluate_vtk(result, outfile, **kwds):
    '''
    Save a evaluation result to a VTK file.
    '''
    from tvtk.api import tvtk, write_data

    points = result.parent_by_type('volume').array_data_by_type()['points']

    filter = tvtk.AppendFilter()

    pot = result.array_data_by_type()['scalar']

    pd = tvtk.PolyData(points=points)
    pd.point_data.scalars = pot.T
    pd.point_data.scalars.name = result.name
    pd.cell_data.scalars = pot.T
    pd.cell_data.scalars.name = result.name

    if False:
        filter.add_input_data(pd)
        filter.update()
        ug = tvtk.UnstructuredGrid()
        ug.shallow_copy(filter.get_output())
        write_data(ug, outfile)
    else:
        write_data(pd, outfile)
    return
Exemple #14
0
def vtk_convexhull(ch, radius=0.02):
    from tvtk.api import tvtk

    poly = tvtk.PolyData()
    poly.points = ch.points
    poly.polys = ch.simplices

    sphere = tvtk.SphereSource(radius=radius)
    points3d = tvtk.Glyph3D()
    points3d.set_source_connection(sphere.output_port)
    points3d.set_input_data(poly)

    m1 = tvtk.PolyDataMapper()
    m1.set_input_data(poly)
    a1 = tvtk.Actor(mapper=m1)
    a1.property.opacity = 0.3

    m2 = tvtk.PolyDataMapper()
    m2.set_input_data(poly)
    a2 = tvtk.Actor(mapper=m2)
    a2.property.representation = "wireframe"
    a2.property.line_width = 2.0
    a2.property.color = (1.0, 0, 0)

    m3 = tvtk.PolyDataMapper(input_connection=points3d.output_port)
    a3 = tvtk.Actor(mapper=m3)
    a3.property.color = (0.0, 1.0, 0.0)
    return [a1, a2, a3]
Exemple #15
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()
        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)
Exemple #16
0
def visualize_point_correspondences(source_pts,
                                    target_pts,
                                    ij_corr=None,
                                    scalars=None,
                                    point_size=10):
    if ij_corr is None:
        if source_pts.shape != target_pts.shape:
            raise ValueError(
                "must have same amount of source and target points, or specify ij_corr parameter"
            )
        ij_corr = np.column_stack(
            (np.arange(len(source_pts)), np.arange(len(target_pts))))

    p = source_pts[ij_corr[:, 0]]
    p2 = target_pts[ij_corr[:, 1]]

    pd = tvtk.PolyData(points=p, verts=np.r_[:len(p)].reshape((-1, 1)))
    actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
    configure_input_data(actor.mapper, pd)
    actor.property.point_size = point_size
    if scalars is not None:
        pd.point_data.scalars = scalars
        actor.mapper.scalar_range = scalars.min(), scalars.max()
    mlab.gcf().scene.add_actor(actor)

    class Ctrl(ta.HasTraits):
        alpha = ta.Range(0., 1.)

        def _alpha_changed(self):
            pd.points = p + self.alpha * (p2 - p)
            mlab.gcf().scene.render()

    Ctrl().configure_traits()
Exemple #17
0
def do_save(grid, arrays):
    from tvtk.api import tvtk
    from tvtk.api import write_data

    pd = tvtk.PolyData()
    pd.points = grid.leaf_view.vertices.T
    pd.polys = grid.leaf_view.elements
    pd.point_data.scalars = grid.leaf_view.domain_indices
    pd.point_data.scalars.name = "domains"
    write_data(pd, "test_kitchen_sink_grid.vtk")

    abn = {a.type: a.data for a in arrays}
    mgrid = abn["mgrid"]
    potential = abn["gscalar"]
    gradient = abn["gvector"]

    print dimensions, potential.shape

    print 'spacing:', spacing
    print 'origin:', origin
    print 'dimensions:', dimensions
    sp = tvtk.StructuredPoints(spacing=spacing,
                               origin=origin,
                               dimensions=dimensions)
    sp.point_data.scalars = potential.ravel(order='F')
    sp.point_data.scalars.name = "potential"
    sp.point_data.vectors = gradient.ravel(order='F')
    sp.point_data.vectors.name = "gradient"

    write_data(sp, "test_kitchen_sink_potential.vtk")

    numpy.savez_compressed("test_kitchen_sink.npz", **abn)
Exemple #18
0
    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:
            configure_input_data(tf, pd)
            configure_input_data(mapper, tf.output)

        a = _make_actor(mapper=mapper)
        a.property.color = self.color
        self.actors.append(a)
Exemple #19
0
 def _generate_obbtree(self, trimesh_obj):
     ''' 用来生成一个可用的obbtree对象,加速后面相交的判断 '''
     poly = tvtk.PolyData(points=trimesh_obj.vertices,
                          polys=trimesh_obj.faces)
     tree = tvtk.OBBTree(data_set=poly, tolerance=1.e-8)
     tree.build_locator()
     return tree
Exemple #20
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
Exemple #21
0
    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

        configure_input_data(self.glyph, 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)
Exemple #22
0
    def _show3(self, col='r', Id=[0], H_Id=0, alpha=0.2):

        # gett list of all boundaries
        lbd = np.array([b.bd for b in self.box])
        shb = lbd.shape
        lbdr = lbd.reshape(shb[0] * shb[1], shb[2])

        # mapping of single boundaries to get the 8 vertices of the boxN
        mapp = np.array([[0, 0, 0], [0, 1, 0], [1, 1, 0], [1, 0, 0], [0, 0, 1],
                         [0, 1, 1], [1, 1, 1], [1, 0, 1]],
                        dtype='int')

        # repeat the coordinates mapping for all the boxes + shift index
        mappe = np.tile(mapp,
                        (shb[0], 1)) + np.repeat(np.arange(shb[0]), 8)[:, None]

        # get coordintaes of all verticesof all boxN
        allpt = np.array(
            [lbdr[mappe[:, 0], 0], lbdr[mappe[:, 1], 1], lbdr[mappe[:, 2], 2]])

        edges = [[0, 1, 2], [0, 2, 3], [0, 1, 5], [0, 4, 5], [1, 5, 2],
                 [5, 6, 2], [2, 6, 7], [2, 7, 3], [0, 3, 4], [3, 7, 4],
                 [4, 5, 6], [4, 6, 7]]

        # as many edges as boxN
        edgese = np.tile(edges, (shb[0], 1)) + np.repeat(
            np.arange(shb[0]) * 8, 12)[:, None]

        mesh = tvtk.PolyData(points=allpt.T, polys=edgese)
        if col == 'r':
            color = (1, 0, 0)
        elif col == 'b':
            color = (0, 0, 1)
        mlab.pipeline.surface(mesh, opacity=alpha, color=color)
Exemple #23
0
def voxelize(pts, polys, shape=(256, 256, 256), center=(128, 128, 128), mp=True):
    from tvtk.api import tvtk
    
    pd = tvtk.PolyData(points=pts + center + (0, 0, 0), polys=polys)
    plane = tvtk.Planes(normals=[(0,0,1)], points=[(0,0,0)])
    clip = tvtk.ClipPolyData(clip_function=plane, input=pd)
    feats = tvtk.FeatureEdges(
        manifold_edges=False, 
        non_manifold_edges=False, 
        feature_edges=False,
        boundary_edges=True,
        input=clip.output)

    def func(i):
        plane.points = [(0,0,i)]
        feats.update()
        vox = np.zeros(shape[:2][::-1], np.uint8)
        if feats.output.number_of_lines > 0:
            epts = feats.output.points.to_array()
            edges = feats.output.lines.to_array().reshape(-1, 3)[:,1:]
            for poly in trace_poly(edges):
                vox += rasterize(epts[poly][:,:2]+[.5, .5], shape=shape[:2][::-1])
        return vox % 2

    if mp:
        from . import mp
        layers = mp.map(func, range(shape[2]))
    else:
        #layers = map(func, range(shape[2]))
        layers = [func(x) for x in range(shape[2])] # python3 compatible

    return np.array(layers).T
Exemple #24
0
def quiver(positions, directions, renderer=renderer):
    ''' lines is nx6 numpy array with each row containing position and
    direction  x, y, z, nx, ny, nz '''

    positions = np.array(positions, dtype=np.float32) # cast all arrays to float
    directions = np.array(directions, dtype=np.float32) # cast all arrays to float

    # Create a vtkPoints object and store the points in it
    pts = np.vstack((positions, positions + directions))

    # Create a cell array to store the lines 
    pointids = np.arange(pts.shape[0], dtype=np.int)

    # lines is nx2 array with each row containing 2 points to be connected
    lines = pointids.reshape((2, -1)).T
     
    # Create a polydata to store everything in
    linesPolyData = tvtk.PolyData()
    # Add the points to the dataset
    linesPolyData.points = pts
    # Add the lines to the dataset
    linesPolyData.lines = lines
     
    # Set line colors
    # color from the vector direction
    magnitudes = mlab.vector_lengths(directions, axis=1).reshape((-1, 1))
    magnitudes[magnitudes == 0] = 1 # make magnitudes non zero
    colors = np.abs((directions/magnitudes)) * 255
    colors = colors.astype(np.uint8)
    linesPolyData.cell_data.scalars = colors
    linesPolyData.cell_data.scalars.name = 'colors'
     
    return visualise(linesPolyData, renderer=renderer)
Exemple #25
0
def get_mayavi_cubic_arena_source(engine, info=None):

    v = info['verts4x4']  # arranged in 2 rectangles of 4 verts

    points = v
    lines = [[0, 1], [1, 2], [2, 3], [3, 0], [4, 5], [5, 6], [6, 7], [7, 4],
             [0, 4], [1, 5], [2, 6], [3, 7]]

    if 0:
        import enthought.mayavi.tools.mlab as mlab
        for lineseg in lines:
            p0 = points[lineseg[0]]
            p1 = points[lineseg[1]]
            x = np.array([p0[0], p1[0]])
            y = np.array([p0[1], p1[1]])
            z = np.array([p0[2], p1[2]])
            mlab.plot3d(x, y, z)

    #polys = numpy.arange(0, len(points), 1, 'l')
    #polys = numpy.reshape(polys, (len(points), 1))
    pd = tvtk.PolyData(
        points=points,  #polys=polys,
        lines=lines)

    e = engine
    e.add_source(VTKDataSource(data=pd, name='cubic arena'))

    s = Surface()
    e.add_module(s)
Exemple #26
0
def cylindrical_post(info=None):
    verts = info['verts']
    diameter = info['diameter']

    radius = diameter / 2.0
    actors = []
    verts = numpy.asarray(verts)
    pd = tvtk.PolyData()

    np = len(verts) - 1
    lines = numpy.zeros((np, 2), numpy.int64)
    lines[:, 0] = numpy.arange(0, np - 0.5, 1, numpy.int64)
    lines[:, 1] = numpy.arange(1, np + 0.5, 1, numpy.int64)

    pd.points = verts
    pd.lines = lines

    pt = tvtk.TubeFilter(
        radius=radius,
        input=pd,
        number_of_sides=20,
        vary_radius='vary_radius_off',
    )
    m = tvtk.PolyDataMapper(input=pt.output)
    a = tvtk.Actor(mapper=m)
    a.property.color = 0, 0, 0
    a.property.specular = 0.3
    actors.append(a)
    return actors
Exemple #27
0
    def make_grid(self):
        """return an unstructured grid, based on contours (xc, yc) with possible
        scalar and vector values"""

        # Get the contours
        xc = self.ds.variables['FlowElemContour_x']
        yc = self.ds.variables['FlowElemContour_y']

        ncells = xc.shape[0]
        # We're using an unstructured grid
        grid = tvtk.PolyData()
        ncells = xc.shape[0]
        X = xc[:]
        Y = yc[:]
        Z = np.zeros_like(X)
        pts = np.c_[X.ravel(), Y.ravel(), Z.ravel()]

        # quads all the way down
        # quads with different resolutions actually don't work so well
        cell_array = tvtk.CellArray()
        # For unstructured grids you need to count the number of edges per cell
        cell_idx = np.array([[4] + [i * 4 + j for j in range(4)]
                             for i in range(ncells)]).ravel()
        cell_array.set_cells(ncells, cell_idx)

        # fill in the properties
        grid.points = pts
        grid.polys = cell_array
        return grid
Exemple #28
0
 def setUp(self):
     x = np.arange(1, 10)
     y = np.sqrt(x)
     z = np.zeros_like(x)
     points = np.c_[x, y, z]
     polydata = tvtk.PolyData()
     polydata.points = points
     self.polydata = polydata
 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
Exemple #30
0
def decimate(pts, polys):
    from tvtk.api import tvtk
    pd = tvtk.PolyData(points=pts, polys=polys)
    dec = tvtk.DecimatePro(input=pd)
    dec.set(preserve_topology=True, splitting=False, boundary_vertex_deletion=False, target_reduction=1.0)
    dec.update()
    dpts = dec.output.points.to_array()
    dpolys = dec.output.polys.to_array().reshape(-1, 4)[:,1:]
    return dpts, dpolys