예제 #1
0
# -*- coding: utf-8 -*-
from .example_cut_plane import read_data
from tvtk.api import tvtk
from scpy2.tvtk.tvtkhelp import ivtk_scene, event_loop, make_outline

plot3d = read_data()
grid = plot3d.output.get_block(0)

contours = tvtk.ContourFilter()
contours.set_input_data(grid)
contours.generate_values(8, grid.point_data.scalars.range)
mapper = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range,
                             input_connection=contours.output_port)
actor = tvtk.Actor(mapper=mapper)
actor.property.opacity = 0.3

outline_actor = make_outline(grid)

win = ivtk_scene([actor, outline_actor])
win.scene.isometric_view()
event_loop()
예제 #2
0
    def get_tvtk_actors(self):
        filename = self.filename
        kwargs = self.kwargs

        ### draw floor
        actors = []

        x0 = -1.5/2
        x1 = 1.5/2
        y0 = -.305/2
        y1 = .305/2
        z0 = .314

        inc = 0.05
        if 1:
            nx = int(math.ceil((x1-x0)/inc))
            ny = int(math.ceil((y1-y0)/inc))
            eps = 1e-10
            x1 = x0+nx*inc+eps
            y1 = y0+ny*inc+eps

        segs = []
        for x in numpy.r_[x0:x1:inc]:
            seg =[(x,y0,z0),
                  (x,y1,z0)]
            segs.append(seg)
        for y in numpy.r_[y0:y1:inc]:
            seg =[(x0,y,z0),
                  (x1,y,z0)]
            segs.append(seg)

        if 1:
            verts = []
            for seg in segs:
                verts.extend(seg)
            verts = numpy.asarray(verts)

            pd = tvtk.PolyData()

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

            pd.points = verts
            pd.lines = lines

            pt = tvtk.TubeFilter(radius=0.001,input=pd,
                                 number_of_sides=4,
                                 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)

        ###################
        stim = None
        try:
            condition, stim = conditions.get_condition_stimname_from_filename(filename, **kwargs)
            print 'Data from condition "%s",with stimulus'%(condition,),stim
        except KeyError, err:
            if kwargs.get('force_stimulus',False):
                raise
            else:
                print 'Unknown condition and stimname'
예제 #3
0
alpha = norm(z)

# combine hue and alpha into a Nx4 matrix
rgba_vals = np.concatenate((colors, alpha[:, None]), axis=1)

# 4) add data to plot

# plot points in x,y,z
mesh = mlab.pipeline.triangular_mesh_source(x, y, z, tris, figure=fig)
mesh.data.point_data.scalars.number_of_components = 4  # r, g, b, a
mesh.data.point_data.scalars = (rgba_vals * 255).astype('ubyte')

# tvtk for vis
mapper = tvtk.PolyDataMapper()
configure_input_data(mapper, mesh.data)
actor = tvtk.Actor()
actor.mapper = mapper
fig.scene.add_actor(actor)

# 5) project rgba matrix to flat cortex patch:
fig = mlab.figure()
b2 = Brain('fsaverage',
           hemi,
           'cortex.patch.flat',
           subjects_dir=subjects_dir,
           background='white',
           figure=fig)
print('original rgba_vals.shape:', rgba_vals.shape)
rgba_vals = b2.geo[hemi].surf_to_patch_array(rgba_vals)
print('patch-compatible rgba_vals.shape:', rgba_vals.shape)
예제 #4
0
# VTK replacing C++ setters and getters by Python properties and
# converting numpy arrays to VTK arrays when setting data.
from tvtk.api import tvtk

v = mlab.figure()

# Create a first sphere
# The source generates data points
sphere = tvtk.SphereSource(center=(0, 0, 0), radius=0.5)
# The mapper converts them into position in, 3D with optionally color (if
# scalar information is available).
sphere_mapper = tvtk.PolyDataMapper(input=sphere.output)
# The Property will give the parameters of the material.
p = tvtk.Property(opacity=0.2, color=(1, 0, 0))
# The actor is the actually object in the scene.
sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
v.scene.add_actor(sphere_actor)

# Create a second sphere
sphere2 = tvtk.SphereSource(center=(7, 0, 1), radius=0.2)
sphere_mapper2 = tvtk.PolyDataMapper(input=sphere2.output)
p = tvtk.Property(opacity=0.3, color=(1, 0, 0))
sphere_actor2 = tvtk.Actor(mapper=sphere_mapper2, property=p)
v.scene.add_actor(sphere_actor2)

# Create a line between the two spheres
line = tvtk.LineSource(point1=(0, 0, 0), point2=(7, 0, 1))
line_mapper = tvtk.PolyDataMapper(input=line.output)
line_actor = tvtk.Actor(mapper=line_mapper)
v.scene.add_actor(line_actor)
예제 #5
0
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")
예제 #6
0
    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
예제 #7
0
    def initialize(self, X, Y, initial_data=None, vmin=None, vmax=None):
        """
		Create objects to plot on
		"""
        if initial_data == None:
            initial_data = zeros(shape(X))
            if vmin == None:
                self.vmin = -1.0
            if vmax == None:
                self.vmax = 1.0
        else:
            if vmin == None:
                self.vmin = np.min(np.min(initial_data))
            if vmax == None:
                self.vmax = np.max(np.max(initial_data))
        x_min = np.min(np.min(X))
        y_min = np.min(np.min(Y))
        x_max = np.max(np.max(X))
        y_max = np.max(np.max(Y))
        x_middle = (x_min + x_max) / 2
        y_middle = (y_min + y_max) / 2
        z_middle = np.mean(np.mean(initial_data))
        L = x_max - x_min
        diffs = np.shape(X)
        x_diff = diffs[0]
        y_diff = diffs[1]
        z_diff = 1.0  #self.vmax-self.vmin

        self.tvtk = tvtk
        self.sp = tvtk.StructuredPoints(origin=(x_middle, y_middle, z_middle),
                                        dimensions=(x_diff, y_diff, 1),
                                        spacing=(2 * L / (x_diff - 1),
                                                 2 * L / (y_diff - 1), 100.0))

        self.z = np.transpose(initial_data).flatten()

        self.sp.point_data.scalars = self.z
        self.geom_filter = tvtk.ImageDataGeometryFilter(input=self.sp)
        self.warp = tvtk.WarpScalar(input=self.geom_filter.output)
        self.normals = tvtk.PolyDataNormals(input=self.warp.output)

        # The rest of the VTK pipeline.
        self.m = tvtk.PolyDataMapper(input=self.normals.output,
                                     scalar_range=(self.vmin, self.vmax))
        p = tvtk.Property(opacity=0.5, color=(1, 1, 1), representation="s")
        self.a = tvtk.Actor(mapper=self.m, property=p)

        self.ren = tvtk.Renderer(background=(0.0, 0.0, 0.0))

        self.ren.add_actor(self.a)

        # Get a nice view.
        self.cam = self.ren.active_camera
        self.cam.azimuth(-50)
        self.cam.roll(90)

        # Create a RenderWindow, add the renderer and set its size.
        self.rw = tvtk.RenderWindow(size=(800, 800))
        self.rw.add_renderer(self.ren)

        # Create the RenderWindowInteractor
        self.rwi = tvtk.RenderWindowInteractor(render_window=self.rw)

        self.rwi.initialize()
        self.ren.reset_camera()
        self.rwi.render()
예제 #8
0
def display_3d_model(array_3d, pointcloud=None, centroids=None):
    '''
    Method renders space-filling atomic model of PDB data.
    Param:
        pdb_data - np.array ; mulitchanneled pdb atom coordinates
        skeletal - boolean ; if true shows model without radial information
        attenmap - np.array
    '''

    # Dislay 3D Mesh Rendering
    v = mlab.figure(bgcolor=(1.0,1.0,1.0))

    if array_3d is not None:

        # Color Mapping
        n = len(array_3d)
        cm = [winter(float(i)/n)[:3] for i in range(n)]

        for j in range(len(array_3d)):
            c = tuple(cm[j])

            # Coordinate Information
            xx, yy, zz = np.where(array_3d[j] > 0.0)
            xx = xx.astype('float') - ((resolution * array_3d.shape[1])/2.0)
            yy = yy.astype('float') - ((resolution * array_3d.shape[1])/2.0)
            zz = zz.astype('float') - ((resolution * array_3d.shape[1])/2.0)

            # Generate Voxels For Protein
            append_filter = vtk.vtkAppendPolyData()
            for i in range(len(xx)):
                input1 = vtk.vtkPolyData()
                voxel_source = vtk.vtkCubeSource()
                voxel_source.SetCenter(xx[i],yy[i],zz[i])
                voxel_source.SetXLength(1)
                voxel_source.SetYLength(1)
                voxel_source.SetZLength(1)
                voxel_source.Update()
                input1.ShallowCopy(voxel_source.GetOutput())
                append_filter.AddInputData(input1)
            append_filter.Update()

            #  Remove Any Duplicate Points.
            clean_filter = vtk.vtkCleanPolyData()
            clean_filter.SetInputConnection(append_filter.GetOutputPort())
            clean_filter.Update()

            # Render Voxels
            pd = tvtk.to_tvtk(clean_filter.GetOutput())
            cube_mapper = tvtk.PolyDataMapper()
            configure_input_data(cube_mapper, pd)
            p = tvtk.Property(opacity=1.0, color=c)
            cube_actor = tvtk.Actor(mapper=cube_mapper, property=p)
            v.scene.add_actor(cube_actor)

    if pointcloud is not None:

        # Generate Voxels For Pointcloud
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(pointcloud)):
            input1 = vtk.vtkPolyData()
            voxel_source = vtk.vtkCubeSource()
            voxel_source.SetCenter(pointcloud[i][0],pointcloud[i][1], pointcloud[i][2])
            voxel_source.SetXLength(1)
            voxel_source.SetYLength(1)
            voxel_source.SetZLength(1)
            voxel_source.Update()
            input1.ShallowCopy(voxel_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Voxels
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        cube_mapper = tvtk.PolyDataMapper()
        configure_input_data(cube_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=(1.0,0.5,0.5))
        cube_actor = tvtk.Actor(mapper=cube_mapper, property=p)
        v.scene.add_actor(cube_actor)

    if centroids is not None:

        # Generate Mesh For Centroids
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(centroids)):
            input1 = vtk.vtkPolyData()
            sphere_source = vtk.vtkSphereSource()
            sphere_source.SetCenter(centroids[i][0],centroids[i][1],centroids[i][2])
            sphere_source.SetRadius(4.0)
            sphere_source.Update()
            input1.ShallowCopy(sphere_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Mesh
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        sphere_mapper = tvtk.PolyDataMapper()
        configure_input_data(sphere_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=(1.0,0.0,1.0))
        sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
        v.scene.add_actor(sphere_actor)

    mlab.show()
예제 #9
0
        """
        p1 = seg.origin
        p2 = p1 + seg.MAX_RAY_LENGTH * seg.direction
        i = self.intersect_with_line(p1, p2)
        if i is None:
            return None
        i = numpy.array(i)
        dist = numpy.sqrt(((i - p1)**2).sum())
        return dist, i, 0, self


if __name__ == "__main__":
    oap = OffAxisParabloid()

    mapper = tvtk.PolyDataMapper(input=oap.pipeline.output)
    actor = tvtk.Actor(mapper=mapper)
    ren = tvtk.Renderer()
    ren.add_actor(actor)

    ax = tvtk.Axes(origin=(0, 0, 0))
    axes_map = tvtk.PolyDataMapper(input=ax.output)
    axes_act = tvtk.Actor(mapper=axes_map)
    ren.add_actor(axes_act)

    ren.background = (0.7, 0.6, 0.5)

    renwin = tvtk.RenderWindow()
    renwin.add_renderer(ren)

    iren = tvtk.RenderWindowInteractor(render_window=renwin)
    iren.start()
예제 #10
0
파일: object.py 프로젝트: lukius/mlab-tools
 def _set_actor(self):
     self.actor = tvtk.Actor(mapper=self.mapper)
     self.actor.mapper.update()
def vtkLine(p1, p2):
  src = tvtk.LineSource(point1=tuple(p1), point2=tuple(p2))
  mapper = tvtk.PolyDataMapper(input=src.output)
  actor = tvtk.Actor(mapper=mapper)
  return actor
예제 #12
0
def main(*anim_files):
    fig = mlab.figure(bgcolor=(1, 1, 1))
    all_verts = []
    pds = []
    actors = []
    datasets = []
    glyph_pds = []
    glyph_actors = []

    colors = cycle([(1, 1, 1), (1, 0, 0), (0, 1, 0), (0, 0, 1)])

    for i, (f, color) in enumerate(zip(anim_files, colors)):
        data = h5py.File(f, 'r')
        verts = data['verts'].value
        tris = data['tris'].value
        print f
        print "  Vertices: ", verts.shape
        print "  Triangles: ", tris.shape
        datasets.append(data)

        # setup mesh
        pd = tvtk.PolyData(points=verts[0], polys=tris)
        normals = tvtk.PolyDataNormals(compute_point_normals=True,
                                       splitting=False)
        configure_input_data(normals, pd)
        actor = tvtk.Actor(mapper=tvtk.PolyDataMapper())
        configure_input(actor.mapper, normals)
        actor.mapper.immediate_mode_rendering = True
        actor.visibility = False
        fig.scene.add_actor(actor)

        actors.append(actor)
        all_verts.append(verts)
        pds.append(normals)

        # setup arrows
        arrow = tvtk.ArrowSource(tip_length=0.25,
                                 shaft_radius=0.03,
                                 shaft_resolution=32,
                                 tip_resolution=4)
        glyph_pd = tvtk.PolyData()
        glyph = tvtk.Glyph3D()
        scale_factor = verts.reshape(-1, 3).ptp(0).max() * 0.1
        glyph.set(scale_factor=scale_factor,
                  scale_mode='scale_by_vector',
                  color_mode='color_by_scalar')
        configure_input_data(glyph, glyph_pd)
        configure_source_data(glyph, arrow)
        glyph_actor = tvtk.Actor(mapper=tvtk.PolyDataMapper(),
                                 visibility=False)
        configure_input(glyph_actor.mapper, glyph)
        fig.scene.add_actor(glyph_actor)

        glyph_actors.append(glyph_actor)
        glyph_pds.append(glyph_pd)

    actors[0].visibility = True
    glyph_actors[0].visibility = True

    class Viewer(HasTraits):
        animator = Instance(Animator)
        visible = Enum(*range(len(pds)))
        normals = Bool(True)
        export_off = Button
        restpose = Bool(True)
        show_scalars = Bool(True)
        show_bones = Bool(True)
        show_actual_bone_centers = Bool(False)

        def _export_off_changed(self):
            fd = FileDialog(title='Export OFF',
                            action='save as',
                            wildcard='OFF Meshes|*.off')
            if fd.open() == OK:
                v = all_verts[self.visible][self.animator.current_frame]
                save_off(fd.path, v, tris)

        @on_trait_change('visible, normals, restpose, show_scalars, show_bones'
                         )
        def _changed(self):
            for a in actors + glyph_actors:
                a.visibility = False
            for d in pds:
                d.compute_point_normals = self.normals
            actors[self.visible].visibility = True
            actors[self.visible].mapper.scalar_visibility = self.show_scalars
            glyph_actors[self.visible].visibility = self.show_bones
            #for i, visible in enumerate(self.visibilities):
            #    actors[i].visibility = visible
            self.animator.render = True

        def show_frame(self, frame):
            v = all_verts[self.visible][frame]
            dataset = datasets[self.visible]
            if not self.restpose:
                rbms_frame = dataset['rbms'][frame]
                v = v * dataset.attrs['scale'] + dataset.attrs['verts_mean']
                v = blend_skinning(v,
                                   dataset['segments'].value,
                                   rbms_frame,
                                   method=dataset.attrs['skinning_method'])
            pds[self.visible].input.points = v
            if 'scalar' in dataset and self.show_scalars:
                if dataset['scalar'].shape[0] == all_verts[
                        self.visible].shape[0]:
                    scalar = dataset['scalar'][frame]
                else:
                    scalar = dataset['scalar'].value
                pds[self.visible].input.point_data.scalars = scalar
            else:
                pds[self.visible].input.point_data.scalars = None
            if 'bone_transformations' in dataset and self.show_bones:
                W = dataset['bone_blendweights'].value
                T = dataset['bone_transformations'].value
                gpd = glyph_pds[self.visible]
                if self.show_actual_bone_centers:
                    verts0 = dataset['verts_restpose'].value
                    mean_bonepoint = verts0[W.argmax(axis=1)]  # - T[0,:,:,3]
                    #mean_bonepoint = np.array([
                    #    np.average(verts0, weights=w, axis=0) for w in W])
                    #gpd.points = np.repeat(mean_bonepoint + T[frame,:,:,3], 3, 0)
                    #print np.tile(mean_bonepoint + T[frame,:,:,3], 3).reshape((-1, 3))
                    #gpd.points = np.tile(mean_bonepoint + T[frame,:,:,3], 3).reshape((-1, 3))
                    pts = []
                    for i in xrange(T.shape[1]):
                        #offset = V.transform(V.hom4(mean_bonepoint[i]), T[frame,i,:,:])
                        offset = np.dot(T[frame, i], V.hom4(mean_bonepoint[i]))
                        pts += [offset] * 3
                    gpd.points = np.array(pts)

                else:
                    bonepoint = np.array(
                        [np.average(v, weights=w, axis=0) for w in W])
                    gpd.points = np.repeat(bonepoint, 3, 0)
                gpd.point_data.vectors = \
                        np.array(map(np.linalg.inv, T[frame,:,:,:3])).reshape(-1, 3)
                # color vertices
                vert_colors = vertex_weights_to_colors(W)
                pds[self.visible].input.point_data.scalars = vert_colors
                bone_colors = hue_linspace_colors(W.shape[0],
                                                  sat=0.8,
                                                  light=0.7)
                gpd.point_data.scalars = np.repeat(bone_colors, 3, 0)

        view = View(
            Group(
                Group(Item('visible'),
                      Item('export_off'),
                      Item('normals'),
                      Item('restpose'),
                      Item('show_scalars'),
                      Item('show_bones'),
                      Item('show_actual_bone_centers'),
                      label="Viewer"),
                Item('animator', style='custom', show_label=False),
            ))

    app = Viewer()
    animator = Animator(verts.shape[0], app.show_frame)
    app.animator = animator
    app.edit_traits()
    mlab.show()
예제 #13
0
def maven_orbit_image(time,
                      camera_pos=[1, 0, 0],
                      camera_up=[0, 0, 1],
                      extent=3,

                      parallel_projection=True,

                      view_from_orbit_normal=False,
                      view_from_periapsis=False,

                      show_maven=False,
                      show_orbit=True,
                      label_poles=None,

                      show=True,
                      transparent_background=False,
                      background_color=(0, 0, 0)):
    """Creates an image of Mars and the MAVEN orbit at a specified time.

    Parameters
    ----------
    time : str
        Time to diplay, in a string format interpretable by spiceypy.str2et.

    camera_pos : length 3 iterable
        Position of camera in MSO coordinates.
    camera_up : length 3 iterable
        Vector defining the image vertical.
    extent : float
        Half-width of image in Mars radii.

    parallel_projection : bool
        Whether to display an isomorphic image from the camera
        position. If False, goofy things happen. Defaults to True.

    view_from_orbit_normal : bool
        Override camera_pos with a camera position along MAVEN's orbit
        normal. Defaults to False.
    view_from_periapsis : bool
        Override camera_pos with a camera position directly above
        MAVEN's periapsis. Defaults to False.

    show_maven : bool
        Whether to draw a circle showing the position of MAVEN at the
        specified time. Defaults to False.
    show_orbit : bool
        Whether to draw the MAVEN orbit. Defaults to True.
    label_poles : bool
        Whether to draw an 'N' and 'S' above the visible poles of Mars.

    show : bool
        Whether to show the image when called, or supress
        display. Defaults to True.
    transparent_background : bool
        If True, the image background is transparent, otherwise it is
        set to background_color. Defaults to False.
    background_color : RGB1 tuple
        Background color to use if transparent_background=False.
        Specified as an RGB tuple with values between 0 and 1.

    Returns
    -------
    rgb_array : 1000x1000x3 numpy array of image RGB values
        Image RGB values.
    return_coords : dict
        Description of the image coordinate system useful for plotting
        on top of output image.

    Notes
    -----
    Call maven_iuvs.load_iuvs_spice() before calling this function to
    ensure kernels are loaded.

    """
    myet = spice.str2et(time)

    # disable mlab display (this is done by matplotlib later)
    mlab.options.offscreen = True

    # create a figure window (and scene)
    mlab_pix = 1000
    mfig = mlab.figure(size=(mlab_pix, mlab_pix),
                       bgcolor=background_color)

    # disable rendering as objects are added
    mfig.scene.disable_render = True

    #
    # Set up the planet surface
    #

    # load and map the Mars surface texture
    image_file = os.path.join(anc_dir, 'marssurface_2.jpg')
    img = tvtk.JPEGReader()
    img.file_name = image_file
    texture = tvtk.Texture(input_connection=img.output_port, interpolate=1)

    # attach the texture to a sphere
    mars_radius = 3395.
    sphere_radius = 1  # radius of planet is 1 rM
    sphere_resolution = 180  # 180 points on the sphere
    sphere = tvtk.TexturedSphereSource(radius=sphere_radius,
                                       theta_resolution=sphere_resolution,
                                       phi_resolution=sphere_resolution)
    sphere_mapper = tvtk.PolyDataMapper(input_connection=sphere.output_port)
    mars = tvtk.Actor(mapper=sphere_mapper, texture=texture)

    # adjust the reflection properties for a pretty image
    mars.property.ambient = 0.2  # so the nightside is slightly visible
    mars.property.specular = 0.15  # make it shinier near dayside

    # now apply the rotation matrix to the planet

    # tvtk only thinks about rotations with Euler angles, so we need
    # to use a SPICE routine to get these from the rotation matrix

    # to get from the surface to MSO coordinates we'd normally do
    # this:
    rmat = spice.pxform('IAU_MARS', 'MAVEN_MSO', myet)

    # but we need to use transpose because spice.m2eul assumes the matrix
    # defines a coordinate system rotation, the inverse of the matrix
    # to rotate vectors
    trmat = spice.pxform('MAVEN_MSO', 'IAU_MARS', myet)

    # now we can get the Euler angles
    rangles = np.rad2deg(spice.m2eul(trmat, 2, 1, 3))
    #                                      ^^^^^^^^
    #                                      2,1,3 because vtk performs
    #                                      rotations in the order
    #                                      z,x,y and SPICE wants these
    #                                      in REVERSE order

    mars.orientation = rangles[[1, 0, 2]]
    #                           ^^^^^^^
    #                           orientation must be specified as x,y,z
    #                           rotations in that order even though they
    #                           are applied in the order above

    # OK, that was hard, but now we're good!

    mfig.scene.add_actor(mars)

    #
    # make a lat/lon grid
    #

    line_x = []
    line_y = []
    line_z = []
    line_o = []

    line_t = np.linspace(0, 2*np.pi, 100)
    line_r = 1.0

    longrid = np.arange(0, 360, 30)
    for lon in longrid:
        line_x.append(line_r*np.cos(np.deg2rad(lon))*np.cos(line_t))
        line_x.append([0])
        line_y.append(line_r*np.sin(np.deg2rad(lon))*np.cos(line_t))
        line_y.append([0])
        line_z.append(line_r*np.sin(line_t))
        line_z.append([0])
        line_o.append(np.ones_like(line_t))
        line_o.append([0])

    latgrid = np.arange(-90, 90, 30)[1:]
    for lat in latgrid:
        line_x.append(line_r*np.cos(np.deg2rad(lat))*np.cos(line_t))
        line_x.append([0])
        line_y.append(line_r*np.cos(np.deg2rad(lat))*np.sin(line_t))
        line_y.append([0])
        line_z.append(line_r*np.sin(np.deg2rad(lat))*np.ones_like(line_t))
        line_z.append([0])
        line_o.append(np.ones_like(line_t))
        line_o.append([0])

    line_x = np.concatenate(line_x)
    line_y = np.concatenate(line_y)
    line_z = np.concatenate(line_z)
    line_o = np.concatenate(line_o)

    linearray = [np.matmul(rmat, [x, y, z]) for x, y, z in zip(line_x,
                                                               line_y,
                                                               line_z)]
    (line_x, line_y, line_z) = np.transpose(np.array(linearray))

    grid_linewidth = 0.25*mlab_pix/1000
    mlab.plot3d(line_x, line_y, line_z, line_o,
                transparent=True,
                color=(0, 0, 0),
                tube_radius=None,
                line_width=grid_linewidth)

    #
    # compute the spacecraft orbit
    #

    # for the given time, we determine the orbit period
    maven_state = spice.spkezr('MAVEN', myet,
                               'MAVEN_MME_2000', 'NONE', 'MARS')[0]
    marsmu = spice.bodvrd('MARS', 'GM', 1)[1][0]
    maven_elements = spice.oscltx(maven_state, myet, marsmu)
    orbit_period = 1.001*maven_elements[-1]

    # make an etlist corresponding to the half-orbit ahead and behind
    orbit_subdivisions = 2000
    etlist = (myet
              - orbit_period/2
              + orbit_period*np.linspace(0, 1,
                                         num=orbit_subdivisions))

    # get the position of the orbit in MSO
    statelist = spice.spkezr('MAVEN', etlist,
                             'MAVEN_MSO', 'NONE', 'MARS')[0]
    statelist = np.append(statelist, [statelist[0]], axis=0)  # close the orbit
    poslist = np.transpose(statelist)[:3]/mars_radius  # scale to Mars radius

    # plot the orbit
    orbitcolor = np.array([222, 45, 38])/255  # a nice red
    orbitcolor = tuple(orbitcolor)
    maven_x, maven_y, maven_z = poslist
    if show_orbit:
        mlab.plot3d(maven_x, maven_y, maven_z,
                    color=orbitcolor,
                    tube_radius=None,
                    line_width=3*mlab_pix/1000)

    if not parallel_projection:
        # add a dot indicating the location of the Sun
        # this only makes sense with a perspective transform... with
        # orthographic coordinates we're always too far away
        # TODO: non parallel projection results in goofy images
        sun_distance = 10
        sun_sphere = tvtk.SphereSource(center=(sun_distance, 0, 0),
                                       radius=1*np.pi/180*sun_distance,
                                       theta_resolution=sphere_resolution,
                                       phi_resolution=sphere_resolution)
        sun_sphere_mapper = tvtk.PolyDataMapper(input_connection=sun_sphere.output_port)
        sun_sphere = tvtk.Actor(mapper=sun_sphere_mapper)
        sun_sphere.property.ambient = 1.0
        sun_sphere.property.lighting = False
        # mfig.scene.add_actor(sun_sphere)

        # put a line along the x-axis towards the sun
        # sunline_x=np.arange(0, 5000, 1)
        # mlab.plot3d(sunline_x, 0*sunline_x, 0*sunline_x,
        #             color=(1.0,1.0,1.0),
        #             tube_radius=None,line_width=6)

    #
    # Define camera coordinates
    #

    if view_from_periapsis:
        # to do this we need to get the position of apoapsis and the
        # orbit normal
        rlist = [np.linalg.norm(p) for p in np.transpose(poslist)]
        apoidx = np.argmax(rlist)
        apostate = spice.spkezr('MAVEN', etlist[apoidx],
                                'MAVEN_MSO', 'NONE', 'MARS')[0]
        camera_pos = -1.0 * apostate[:3]
        camera_pos = 5 * (camera_pos/np.linalg.norm(camera_pos))
        camera_up = np.cross(apostate[:3], apostate[-3:])
        camera_up = camera_up/np.linalg.norm(camera_up)
        parallel_projection = True

    if view_from_orbit_normal:
        # to do this we need to get the position of apoapsis and the
        # orbit normal
        rlist = [np.linalg.norm(p) for p in np.transpose(poslist)]
        apoidx = np.argmax(rlist)
        apostate = spice.spkezr('MAVEN', etlist[apoidx],
                                'MAVEN_MSO', 'NONE', 'MARS')[0]
        camera_up = apostate[:3]
        camera_up = camera_up/np.linalg.norm(camera_up)
        camera_pos = np.cross(apostate[:3], apostate[-3:])
        camera_pos = 5 * (camera_pos/np.linalg.norm(camera_pos))
        parallel_projection = True

    # construct an orthonormal coordinate system
    camera_pos = np.array(camera_pos)
    camera_pos_norm = camera_pos/np.linalg.norm(camera_pos)
    camera_up = (camera_up
                 - camera_pos_norm*np.dot(camera_pos_norm,
                                          camera_up))
    camera_up = camera_up/np.linalg.norm(camera_up)
    camera_right = np.cross(-camera_pos_norm, camera_up)

    # set location of camera and orthogonal projection
    camera = mlab.gcf().scene.camera
    if parallel_projection:
        camera_pos = 5*camera_pos_norm
        camera.parallel_projection = True
        camera.parallel_scale = extent  # half box size
    else:
        # TODO: this results in goofy images, fix this
        camera.parallel_projection = False
        camera.view_angle = 50
    camera.position = np.array(camera_pos)
    camera.focal_point = (0, 0, 0)
    camera.view_up = camera_up
    camera.clipping_range = (0.01, 5000)

    #
    # Set up lighting
    #

    # The only light is the Sun, which is fixed on the MSO +x axis.

    # VTK's default lights are uniform and don't fall off with
    # distance, which is what we want
    mfig.scene.light_manager.light_mode = "vtk"
    sun = mfig.scene.light_manager.lights[0]
    sun.activate = True
    sun_vec = (1, 0, 0)

    # The only way to set a light in mayavi/vtk is with respect to the
    # camera position. This means we have to get elevation/azimuth
    # coordinates for the Sun with respect to the camera, which could
    # be anywhere.

    # Here's how the coordinate system is defined:
    # elevation:
    #    [-90 -- +90]
    #    +90 places the light along the direction of camera_up
    # azimuth:
    #    [-180 -- +180],
    #    +90 is in the plane of camera_up and camera_right.
    #    +/-180 is behind, pointing at the camera
    #    -90 places light to the left

    # so, to get elevation we need to put the sun in scene coordinates
    sun_scene = np.matmul([camera_right, camera_up, camera_pos_norm],
                          sun_vec)

    # elevation is the angle is latitude measured wrt the y-axis of
    # the scene
    sun_elevation = np.rad2deg(np.arcsin(np.dot(sun_scene, [0, 1, 0])))
    # azimuth is the angle in the x-z plane, clockwise from the z-axis
    sun_azimuth = np.rad2deg(np.arctan2(sun_scene[0], sun_scene[2]))

    # now we can set the location of the light, computed to always lie
    # along MSO+x
    sun.azimuth = sun_azimuth
    sun.elevation = sun_elevation

    # set the brightness of the Sun based on the ambient lighting of
    # Mars so there is no washing out
    sun.intensity = 1.0 - mars.property.ambient

    #
    # Render the 3D scene
    #

    mfig.scene.disable_render = False
    # mfig.scene.anti_aliasing_frames = 0 # can uncomment to make
    #                                     # rendering faster and uglier
    mlab.show()

    mode = 'rgba' if transparent_background else 'rgb'
    img = mlab.screenshot(mode=mode, antialiased=True)
    mlab.close(all=True)  # 3D stuff ends here

    #
    # Draw text and labels in matplotlib
    #

    fig, ax = plt.subplots(1, 1,
                           dpi=400*mlab_pix/1000,
                           figsize=(2.5, 2.5))
    ax.imshow(img)

    # put an arrow along the orbit direction
    if show_orbit:
        arrow_width = 5
        arrow_length = 1.5*arrow_width
        # by default, draw the arrow at the closest point on the orbit
        # to the viewer
        arrowidx = np.argmax([np.dot(camera_pos_norm, p) for p in
                              np.transpose(poslist)])
        if view_from_periapsis:
            # draw the arrow 45 degrees after periapsis
            arrowidx = np.argmax(
                [np.dot(
                    (camera_right + camera_pos_norm)/np.sqrt(2),
                    p)
                 for p in np.transpose(poslist)])
        if view_from_orbit_normal:
            # draw the arrow 45 degrees after periapsis
            arrowidx = np.argmax(
                [np.dot(
                    (camera_right-camera_up)/np.sqrt(2.),
                    p)
                 for p in np.transpose(poslist)])

        arrowetlist = etlist[arrowidx] + 5*60*np.array([0, 1])
        arrowstatelist = spice.spkezr('MAVEN', arrowetlist,
                                      'MAVEN_MSO', 'NONE', 'MARS')[0]
        arrowdir = arrowstatelist[1][:3] - arrowstatelist[0][:3]
        arrowdirproj = [np.dot(camera_right, arrowdir),
                        np.dot(camera_up, arrowdir)]
        arrowdirproj = arrowdirproj/np.linalg.norm(arrowdirproj)

        arrowloc = np.transpose(poslist)[arrowidx]
        arrowlocproj = np.array([np.dot(camera_right, arrowloc),
                                 np.dot(camera_up, arrowloc)])
        arrowlocdisp = (arrowlocproj + extent)/extent/2
        arrow = ax.annotate('',
                            xytext=(arrowlocdisp - 0.05*arrowdirproj),
                            xy=(arrowlocdisp + 0.05*arrowdirproj),
                            xycoords='axes fraction',
                            textcoords='axes fraction',
                            arrowprops=dict(facecolor=orbitcolor,
                                            edgecolor='none',
                                            width=0,
                                            headwidth=arrow_width,
                                            headlength=arrow_length))

    # label the poles
    if view_from_periapsis:
        label_poles = True
    if view_from_orbit_normal:
        label_poles = True
    if label_poles is None:
        label_poles = False

    if label_poles:
        # label the north and south pole if they are visible
        def label_pole(loc, lbl):
            polepos = np.matmul(rmat, loc)
            poleposproj = np.array([np.dot(camera_right, polepos),
                                    np.dot(camera_up, polepos)])
            poleposdisp = (poleposproj+extent)/extent/2

            # determine if the north pole is visible
            polevis = (not (np.linalg.norm([poleposproj]) < 1
                            and np.dot(camera_pos, polepos) < 0))
            if polevis:
                polelabel = ax.text(*poleposdisp, lbl,
                                    transform=ax.transAxes,
                                    color='#888888',
                                    ha='center', va='center',
                                    size=4, zorder=1)
                # outline the letter
                polelabel.set_path_effects([
                    path_effects.withStroke(linewidth=0.75, foreground='k')])

        label_pole([0, 0,  1], 'N')
        label_pole([0, 0, -1], 'S')

    if show_orbit:
        # add a mark for periapsis and apoapsis

        rlist = [np.linalg.norm(p) for p in np.transpose(poslist)]

        # find periapsis/apoapsis
        def label_apsis(apsis_fn, label, **kwargs):
            apsisidx = apsis_fn(rlist)
            apsispos = np.transpose(poslist)[apsisidx]
            apsisposproj = np.array([np.dot(camera_right, apsispos),
                                     np.dot(camera_up, apsispos)])
            apsisposdisp = (apsisposproj + extent)/extent/2
            apsisvis = (not (np.linalg.norm([apsisposproj]) < 1
                             and np.dot(camera_pos, apsispos) < 0))

            if apsisvis:
                apsis = mpatches.CirclePolygon(apsisposdisp, 0.015,
                                               resolution=4,
                                               transform=ax.transAxes,
                                               fc=orbitcolor, lw=0, zorder=10)
                ax.add_patch(apsis)
                ax.text(*apsisposdisp, label,
                        transform=ax.transAxes,
                        color='k',
                        ha='center',
                        size=4, zorder=10,
                        **kwargs)

        label_apsis(np.argmin, 'P', va='center_baseline')
        label_apsis(np.argmax, 'A', va='center')

    if show_maven:
        # add a dot for the spacecraft location
        mavenpos = spice.spkezr('MAVEN', myet,
                                'MAVEN_MSO', 'NONE', 'MARS')[0][:3]/mars_radius
        mavenposproj = np.array([np.dot(camera_right, mavenpos),
                                 np.dot(camera_up, mavenpos)])
        mavenposdisp = (mavenposproj + extent)/extent/2
        mavenvis = (not (np.linalg.norm([mavenposproj]) < 1
                         and np.dot(camera_pos, mavenpos) < 0))
        if mavenvis:
            maven = mpatches.Circle(mavenposdisp, 0.012,
                                    transform=ax.transAxes,
                                    fc=orbitcolor,
                                    lw=0, zorder=11)
            ax.add_patch(maven)
            ax.text(*mavenposdisp, 'M',
                    transform=ax.transAxes,
                    color='k', ha='center', va='center_baseline',
                    size=4, zorder=11)

    # suppress all whitespace around the plot
    plt.subplots_adjust(top=1, bottom=0, right=1, left=0,
                        hspace=0, wspace=0)
    plt.margins(0, 0)
    ax.set_axis_off()
    ax.xaxis.set_major_locator(plt.NullLocator())
    ax.yaxis.set_major_locator(plt.NullLocator())

    fig.canvas.draw()

    rgb_array = fig2rgb_array(fig)

    if not show:
        plt.close(fig)

    return_coords = {'extent': extent,
                     'scale': '3395 km',
                     'camera_pos': camera_pos,
                     'camera_pos_norm': camera_pos_norm,
                     'camera_up': camera_up,
                     'camera_right': camera_right,
                     'orbit_coords': poslist}

    return rgb_array, return_coords
예제 #14
0
def anim():
  x = 0.2
  y = 0.3
  z = 0.4

  cb1 = sch.Box(x, y, z)
  cb2 = sch.Box(x, y, z)

  pair = sch.CD_Pair(cb1, cb2)

  b1s = tvtk.CubeSource(x_length=x, y_length=y, z_length=z)
  b2s = tvtk.CubeSource(x_length=x, y_length=y, z_length=z)

  b1m = tvtk.PolyDataMapper(input=b1s.output)
  b2m = tvtk.PolyDataMapper(input=b2s.output)

  b1a = tvtk.Actor(mapper=b1m)
  b2a = tvtk.Actor(mapper=b2m)

  line = tvtk.LineSource()
  lineM = tvtk.PolyDataMapper(input=line.output)
  lineA = tvtk.Actor(mapper=lineM)

  b1a.user_transform = tvtk.Transform()
  b2a.user_transform = tvtk.Transform()

  b1T = sva.PTransformd.Identity()
  b2T = sva.PTransformd(Vector3d.UnitZ()*2.)

  setTransform(b1a, b1T)
  setTransform(b2a, b2T)

  viewer = mlab.gcf()
  viewer.scene.add_actors([b1a, b2a, lineA])

  rx = ry = rz = 0.
  t = 0
  while True:
    b1T = sva.PTransformd(sva.RotZ(rz)*sva.RotY(ry)*sva.RotX(rx))
    b2T = sva.PTransformd(Vector3d(0., 0., 2. + np.sin(t)))

    setTransform(b1a, b1T)
    setTransform(b2a, b2T)

    cb1.transform(b1T)
    cb2.transform(b2T)

    p1 = Vector3d()
    p2 = Vector3d()
    pair.distance(p1, p2)

    line.point1 = list(p1)
    line.point2 = list(p2)


    rx += 0.01
    ry += 0.005
    rz += 0.002
    t += 0.05
    viewer.scene.render()
    yield
예제 #15
0
v = mlab.figure()

# Create a sphere
# The source generates data points
sphere = tvtk.SphereSource(center=(0, 0, 0), radius=0.5)
# The mapper converts them into position in, 3D with optionally color (if
# scalar information is available).
sphere_mapper = tvtk.PolyDataMapper()
configure_input_data(sphere_mapper, sphere.output)
sphere.update()

# The Property will give the parameters of the material.
p = tvtk.Property(opacity=0.2, color=(1, 0, 0))
# The actor is the actually object in the scene.
sphere_actor = tvtk.Actor(position=(0, 0, 0), mapper=sphere_mapper, property=p)
v.scene.add_actor(sphere_actor)

# Create a cylinder
cylinder = tvtk.CylinderSource(center=(0, 0, 0), radius=0.2, resolution=16)
cylinder_mapper = tvtk.PolyDataMapper()
configure_input_data(cylinder_mapper, cylinder.output)
cylinder.update()
p = tvtk.Property(opacity=0.3, color=(0, 0, 1))
cylinder_actor = tvtk.Actor(position=(7, 0, 1), mapper=cylinder_mapper,
                            property=p, orientation=(90, 0, 90))
v.scene.add_actor(cylinder_actor)

# Create a line between the two spheres
line = tvtk.LineSource(point1=(0, 0, 0), point2=(7, 0, 1))
line_mapper = tvtk.PolyDataMapper()
예제 #16
0
def display_3d_model(pdb_data, centroids=None):
    '''
    Method renders space-filling atomic model of PDB data.
    Param:
        pdb_data - np.array ; mulitchanneled pdb atom coordinates
        skeletal - boolean ; if true shows model without radial information
        attenmap - np.array
    '''

    # Dislay 3D Mesh Rendering
    v = mlab.figure(bgcolor=(1.0, 1.0, 1.0))

    if pdb_data is not None:
        # Color Mapping
        n = len(pdb_data)
        cm = [jet(float(i) / n)[:3] for i in range(n)]

        for j in range(len(pdb_data)):
            c = cm[j]

            # Coordinate, Radius Information
            r = pdb_data[j][:, 0].astype('float')
            x = pdb_data[j][:, 1].astype('float')
            y = pdb_data[j][:, 2].astype('float')
            z = pdb_data[j][:, 3].astype('float')

            # Generate Mesh For Protein
            append_filter = vtk.vtkAppendPolyData()
            for i in range(len(pdb_data[j])):
                input1 = vtk.vtkPolyData()
                sphere_source = vtk.vtkSphereSource()
                sphere_source.SetCenter(x[i], y[i], z[i])
                sphere_source.SetRadius(r[i])
                sphere_source.Update()
                input1.ShallowCopy(sphere_source.GetOutput())
                append_filter.AddInputData(input1)
            append_filter.Update()

            #  Remove Any Duplicate Points.
            clean_filter = vtk.vtkCleanPolyData()
            clean_filter.SetInputConnection(append_filter.GetOutputPort())
            clean_filter.Update()

            # Render Mesh
            pd = tvtk.to_tvtk(clean_filter.GetOutput())
            sphere_mapper = tvtk.PolyDataMapper()
            configure_input_data(sphere_mapper, pd)
            p = tvtk.Property(opacity=1.0, color=(0.0, 0.4, 0.8))
            sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
            v.scene.add_actor(sphere_actor)

    if centroids is not None:

        # Generate Mesh For Protein
        append_filter = vtk.vtkAppendPolyData()
        for i in range(len(centroids)):
            input1 = vtk.vtkPolyData()
            sphere_source = vtk.vtkSphereSource()
            sphere_source.SetCenter(centroids[i][0], centroids[i][1],
                                    centroids[i][2])
            sphere_source.SetRadius(2.0)
            sphere_source.Update()
            input1.ShallowCopy(sphere_source.GetOutput())
            append_filter.AddInputData(input1)
        append_filter.Update()

        #  Remove Any Duplicate Points.
        clean_filter = vtk.vtkCleanPolyData()
        clean_filter.SetInputConnection(append_filter.GetOutputPort())
        clean_filter.Update()

        # Render Mesh
        pd = tvtk.to_tvtk(clean_filter.GetOutput())
        sphere_mapper = tvtk.PolyDataMapper()
        configure_input_data(sphere_mapper, pd)
        p = tvtk.Property(opacity=1.0, color=(1.0, 0.0, 0.0))
        sphere_actor = tvtk.Actor(mapper=sphere_mapper, property=p)
        v.scene.add_actor(sphere_actor)

    mlab.show()
plot3d = read_data()
grid = plot3d.output.get_block(0)

mask = tvtk.MaskPoints(random_mode=True, on_ratio=50)
mask.set_input_data(grid)

arrow_source = tvtk.ArrowSource()
arrows = tvtk.Glyph3D(input_connection=mask.output_port,
                      scale_factor=2 /
                      np.max(grid.point_data.scalars.to_array()))
arrows.set_source_connection(arrow_source.output_port)

arrows_mapper = tvtk.PolyDataMapper(scalar_range=grid.point_data.scalars.range,
                                    input_connection=arrows.output_port)
arrows_actor = tvtk.Actor(mapper=arrows_mapper)

center = grid.center
sphere = tvtk.SphereSource(center=(2, center[1], center[2]),
                           radius=2,
                           phi_resolution=6,
                           theta_resolution=6)
sphere_mapper = tvtk.PolyDataMapper(input_connection=sphere.output_port)

sphere_actor = tvtk.Actor(mapper=sphere_mapper)
sphere_actor.property.set(representation="wireframe", color=(0, 0, 0))

streamer = tvtk.StreamLine(step_length=0.0001,
                           integration_direction="forward",
                           integrator=tvtk.RungeKutta4())
streamer.set_input_data(grid)
예제 #18
0
def plotThreePlanes(potentialOp, gridFun, limits, dimensions,
                    colorRange=None, transformation='real', evalOps=None):
    """
    Plot the potential generated by applying a potential operator to a grid
    function on the xy, xz and yz planes.

    *Parameters:*
       - potentialOp (PotentialOperator)
            A potential operator.
       - gridFun (GridFunction)
            A grid function.
       - limits (tuple)
            Tuple (min, max) or (xmin, xmax, ymin, ymax, zmin, zmax)
            specifying the extent of each plane on which the potential
            will be plotted.
       - dimensions (tuple)
            Scalar or tuple (xdim, ydim, zdim) specifying the number of samples
            in each direction.
       - colorRange (tuple)
            Tuple (min, max) determining the range of data to be plotted.
            If set to None, the data range is determined automatically.
       - transformation ('real', 'imag', 'abs' or a callable object)
            Determines how the potential is transformed before plotting.
       - evalOps (EvaluationOptions)
            Options controlling the evaluation of the potential.
    """

    if np.isscalar(dimensions):
        dims = (dimensions, dimensions, dimensions)
    else:
        if len(dimensions) == 3:
            dims = dimensions
        else:
            raise ValueError("dimensions must be a scalar or a tuple with 3 elements")
    if len(limits) == 2:
        lims = (limits[0], limits[1], limits[0], limits[1], limits[0], limits[1])
    elif len(limits) == 6:
        lims = limits
    else:
        raise ValueError("limits must be a tuple with 2 or 6 elements")
    origin = ((lims[0] + lims[1]) / 2.,
              (lims[2] + lims[3]) / 2.,
              (lims[4] + lims[5]) / 2.)
    (points1,vals1) = py_ext.evaluatePotentialOnPlane(
        potentialOp,gridFun,lims[:4],dims[:2],plane="xy",origin=origin,
        evalOps=evalOps)
    (points2,vals2) = py_ext.evaluatePotentialOnPlane(
        potentialOp,gridFun,lims[:2]+lims[4:],dims[:1]+dims[2:],plane="xz",
        origin=origin,evalOps=evalOps)
    (points3,vals3) = py_ext.evaluatePotentialOnPlane(
        potentialOp,gridFun,lims[2:],dims[1:],plane="yz",origin=origin,
        evalOps=evalOps)

    if not hasattr(transformation, '__call__'):
        if transformation=='real':
            data_transform = lambda point,val:np.real(val)
        elif transformation=='imag':
            data_transform = lambda point,val:np.imag(val)
        elif transformation=='abs':
            data_transform = lambda point,val:np.abs(val)
        else:
            raise ValueError("Unknown value for 'transformation'. It needs to be 'real', 'imag', 'abs' or a Python Callable!")
    else:
        data_transform = transformation

    vals1 = data_transform(points1,vals1)
    vals2 = data_transform(points2,vals2)
    vals3 = data_transform(points3,vals3)

    if colorRange is None:
        minVal = np.min([vals1,vals2,vals3])
        maxVal = np.max([vals1,vals2,vals3])
        colorRange = (minVal,maxVal)

    g1 = tvtk.StructuredGrid(dimensions=(dims[0],dims[1],1),points=points1)
    g2 = tvtk.StructuredGrid(dimensions=(dims[0],dims[2],1),points=points2)
    g3 = tvtk.StructuredGrid(dimensions=(dims[1],dims[2],1),points=points3)


    # Add data

    g1.point_data.scalars = vals1
    g2.point_data.scalars = vals2
    g3.point_data.scalars = vals3


    # Create actors

    mapper1 = tvtk.DataSetMapper(input=g1)
    mapper1.scalar_range = colorRange
    actor1 = tvtk.Actor(mapper=mapper1)

    mapper2 = tvtk.DataSetMapper(input=g2)
    mapper2.scalar_range = colorRange
    actor2 = tvtk.Actor(mapper=mapper2)

    mapper3 = tvtk.DataSetMapper(input=g3)
    mapper3.scalar_range = colorRange 
    actor3 = tvtk.Actor(mapper=mapper3)

    gActor = gridActor(gridFun.grid())

    legend = legendActor(actor1)

    plotTvtkActors([actor1,actor2,actor3,gActor,legend])
예제 #19
0
#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
# output).  In tvtk it is represented as both a property and as a
# method.  Using the output property will work fine if all you want is
# the default output.  OTOH if you want the N'th output use
# get_output(N).
m.input = cs.output  # or m.input = cs.get_output()

# Create the actor and set its mapper.
a = tvtk.Actor()
a.mapper = m

# Create a Renderer, add the actor and set its background color.
ren = tvtk.Renderer()
ren.add_actor(a)
ren.background = (0.1, 0.2, 0.4)

# Create a RenderWindow, add the renderer and set its size.
rw = tvtk.RenderWindow()
rw.add_renderer(ren)
rw.size = (300, 300)

# Create the RenderWindowInteractor
rwi = tvtk.RenderWindowInteractor()
rwi.render_window = rw
예제 #20
0
    plot3d = read_data()
    grid = plot3d.output.get_block(0)

    # 创建颜色映射表

    import pylab as pl

    lut = tvtk.LookupTable()
    lut.table = pl.cm.cool(np.arange(0, 256)) * 255

    # 显示StructuredGrid中的一个网格面
    plane = tvtk.StructuredGridGeometryFilter(extent=(0, 100, 0, 100, 6, 6))
    plane.set_input_data(grid)
    plane_mapper = tvtk.PolyDataMapper(input_connection=plane.output_port, lookup_table=lut)
    plane_mapper.scalar_range = grid.scalar_range
    plane_actor = tvtk.Actor(mapper=plane_mapper)

    lut2 = tvtk.LookupTable()
    lut2.table = pl.cm.cool(np.arange(0, 256)) * 255

    cut_plane = tvtk.Plane(origin=grid.center, normal=(-0.287, 0, 0.9579))
    cut = tvtk.Cutter(cut_function=cut_plane)
    cut.set_input_data(grid)
    cut_mapper = tvtk.PolyDataMapper(lookup_table=lut2, input_connection=cut.output_port)
    cut_actor = tvtk.Actor(mapper=cut_mapper)

    outline_actor = make_outline(grid)

    from scpy2.tvtk.tvtkhelp import ivtk_scene, event_loop

    win = ivtk_scene([plane_actor, cut_actor, outline_actor])
예제 #21
0
#CuboidSource.py
from tvtk.api import tvtk

# 创建一个长方体数据源,并且同时设置其长宽高
s = tvtk.CubeSource(x_length=1.0, y_length=2.0, z_length=3.0)
# 使用PolyDataMapper将数据转换为图形数据
m = tvtk.PolyDataMapper(input_connection=s.output_port)
# 创建一个Actor
a = tvtk.Actor(mapper=m)
# 创建一个Renderer,将Actor添加进去
r = tvtk.Renderer(background=(0, 0, 0))
r.add_actor(a)
# 创建一个RenderWindow(窗口),将Renderer添加进去
w = tvtk.RenderWindow(size=(300, 300))
w.add_renderer(r)
# 创建一个RenderWindowInteractor(窗口的交互工具)
i = tvtk.RenderWindowInteractor(render_window=w)
# 开启交互
i.initialize()
i.start()
예제 #22
0
text_mapper = tvtk.PolyDataMapper(input=vtext.get_output())
p2 = tvtk.Property(color=(0.3, 0.3, 0.3))
text_actor = tvtk.Follower(mapper=text_mapper, property=p2)
text_actor.position = (0, -L / 4., 0)
f.scene.add_actor(text_actor)

# start line
mlab.plot3d([0, 0], [-L / 2., L / 2.], [0, 0], figure=f)
# tracks
mlab.plot3d([0, 10.], [-L / 2., -L / 2.], [0, 0], figure=f, line_width=1)
mlab.plot3d([0, 10.], [L / 2., L / 2.], [0, 0], figure=f, line_width=1)

# distance between robots
line = tvtk.LineSource(point1=robot_x_pos, point2=robot_y_pos)
line_mapper = tvtk.PolyDataMapper(input=line.output)
line_actor = tvtk.Actor(mapper=line_mapper)
f.scene.add_actor(line_actor)

# Location of the robot
delta = 0.1
surf_length = 5.
surf_width = .5

X_x, Y_x = np.meshgrid(
    np.arange(x_hat[0, 0, 0] - surf_length, x_hat[0, 0, 0] + surf_length,
              delta),
    np.arange(robot_x.pos[1] - surf_width, robot_x.pos[1] + surf_width, delta))
Z_x = matplotlib.mlab.bivariate_normal(X_x.T, Y_x.T, P[0, 0, 0], .1,
                                       x_hat[0, 0, 0], robot_x.pos[1])
surface_x = mlab.surf(X_x.T, Y_x.T, Z_x, representation='wireframe')
ms_x = surface_x.mlab_source