Exemple #1
0
def avgplot(r_labels,nSubjects,r_vertices,r_faces,nCluster,hemi):
    labels = np.zeros(r_labels.shape[0],dtype=float)
    for i in range(r_labels.shape[0]):
        labels[i] = np.sum(r_labels[i])/nSubjects
    mlab.figure(size=(1024, 768), \
                bgcolor=(1, 1, 1),fgcolor=(0.5,0.5,0.5))
    mlab.triangular_mesh(r_vertices[:, 0], r_vertices[:, 1], r_vertices[:, 2], r_faces, representation='surface',
                         opacity=1, scalars=np.float64(labels))
    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=270)
    mlab.colorbar(orientation='vertical')
    #mlab.show()
    #mlab.close()
    mlab.options.offscreen = True
    mlab.savefig('precentral_mean_r'+hemi + '.png')
    mlab.close()
    labels = np.zeros(r_labels.shape[0], dtype=float)
    freq = np.zeros(r_labels.shape[0], dtype=float)
    for i in range(r_labels.shape[0]):
        mode,count=stats.mode(r_labels[i])
        labels[i] = mode[0]
        freq[i]=count
    mlab.figure(size=(1024, 768), \
                bgcolor=(1, 1, 1),fgcolor=(0.5,0.5,0.5))
    mlab.triangular_mesh(r_vertices[:, 0], r_vertices[:, 1], r_vertices[:, 2], r_faces, representation='surface',
                             opacity=1, scalars=np.float64(labels))
    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=90)
    mlab.colorbar(orientation='vertical')
    #mlab.show()
    #mlab.close()
    mlab.options.offscreen = True
    mlab.savefig('precentral-mode' + hemi+ '.png')
    mlab.close()
    return labels,freq
Exemple #2
0
def UnstructuredMesh(Scalar, x, y, z, Source, Axes, Origin, Figure, Name = '', ColorMap='RdBu', ColorBar=True, Orientation='vertical'):
    ImReal = mlab.points3d(x-3, y, z, Scalar.real, mode = 'sphere', scale_mode = 'none', colormap = CMAP)

    ImImag = mlab.points3d(x+3, y, z, Scalar.imag, mode = 'sphere', scale_mode = 'none', colormap = CMAP)

    mlab.text3d(-3, 0, 3, 'Real', scale = 0.5)
    mlab.text3d(+3, 0, 3, 'Imag', scale = 0.5)

    if ColorBar == True:
        mlab.colorbar(object            = ImReal,
                      label_fmt         = "%.0e",
                      nb_labels         = 5,
                      title             = f'Real part',
                      orientation       = 'vertical' )

        mlab.colorbar(object            = ImImag,
                      label_fmt         = "%.0e",
                      nb_labels         = 5,
                      title             = f'Imag part',
                      orientation       = 'horizontal' )


    if Source is not False:
        WavenumberArrow(Figure, Origin=(-3,0,-3), Scale=1)
        WavenumberArrow(Figure, Origin=(+3,0,-3), Scale=1)

    if Axes is not False:
        AddUnitSphere(Num = 50, Radius = 1., Origin = (-3, 0, 0), Figure = Figure)
        AddUnitSphere(Num = 50, Radius = 1., Origin = (+3, 0, 0), Figure = Figure)
        AddUnitAxes(Figure=Figure, Scale=2.5, Origin=(+3, 0, 0), ScaleTube=0.7)
        AddUnitAxes(Figure=Figure, Scale=2.5, Origin=(-3, 0, 0), ScaleTube=0.7)

    ConfigScene(Figure)

    return Figure, 0
Exemple #3
0
def plot_velocities(activations, velocities, n_points: int = 5000):
    """This functions creates a 3D line plot of network activities
    colored by 'kinetic energy' i.e. rate of change in the dynamic system at
    any given position.

    Args:
        activations: Network activations. Must have dimensions [n_time, n_units].

        velocities: Vector of 'velocities' computed by feeding activations in q(x).
        Must have dimensions [n_time].

        n_points (optional): Number of points to be used for line plot. Recommended to choose values
         between 2000 and 5000. Default: 5000.

     Returns:
         None."""
    activations = np.vstack(activations)
    pca = skld.PCA(3)
    pca.fit(activations)
    X_pca = pca.transform(activations)

    mlab.plot3d(X_pca[:n_points, 0], X_pca[:n_points, 1], X_pca[:n_points, 2],
                velocities[:n_points])
    mlab.colorbar(orientation='vertical')
    mlab.show()
Exemple #4
0
def plot_hks(coord_array, tri_array, HKS, n):
    """ plot_hks plots values at index n of the heat kernel signature matrix of the triangular coord & tri mesh.
    :param coord_array: xyz coordinates per vertex in array of shape=(#points, 3)
    :param tri_array: vertex connection indices of the part in array of shape=(#triangles, 3)
    :param HKS: array of size (#points x #steps) with heat values per point per time step
    :param n: integer n to select desired HKS column at time t for plotting
    :return:
    """

    # Loop over values in n to create HKS plots at different time steps
    for i in n:
        mlab.figure(figure= str(i) + "_steps_HKS" , bgcolor = (1,1,1), fgcolor = (0,0,0))
        
        # Create wireframe mesh
        mesh = mlab.triangular_mesh(coord_array[:, 0], coord_array[:, 1], coord_array[:, 2], tri_array, scalars=None,
                                    line_width=0.1, representation='wireframe', color=(0, 0, 0), opacity=0.05)

        # Create face coloring
        point_data = mesh.mlab_source.dataset.point_data
        point_data.scalars = HKS[:, i]
        point_data.scalars.name = 'Point data'
        point_data.update()

        mesh2 = mlab.pipeline.set_active_attribute(mesh, point_scalars='Point data')
        surf = mlab.pipeline.surface(mesh2)
        
        # Add colorbar
        mlab.colorbar(surf, orientation='vertical')
        
        # Show plot
        mlab.show()
Exemple #5
0
 def make_ipw_3d(self, axis_name):
     ipw = mlab.pipeline.image_plane_widget(
         self.data_src3d,
         figure=self.scene3d.mayavi_scene,
         plane_orientation='%s_axes' % axis_name)
     mlab.colorbar(object=ipw)
     return ipw
def main():

    trimesh = TriMesh_From_OFF("torus.off")
    trimesh.update_Laplacian_weights()

    x, y, z = trimesh.vs[:, 0], trimesh.vs[:, 1], trimesh.vs[:, 2]

    mesh = mlab.triangular_mesh(x,
                                y,
                                z,
                                trimesh.faces,
                                representation='wireframe',
                                opacity=0)

    mesh.mlab_source.dataset.point_data.scalars = trimesh.K_H
    mesh.mlab_source.dataset.point_data.scalars.name = 'Point data'

    mesh.mlab_source.update()
    mesh.parent.update()

    mesh2 = mlab.pipeline.set_active_attribute(mesh,
                                               point_scalars='Point data')
    s2 = mlab.pipeline.surface(mesh2)
    s2.actor.mapper.interpolate_scalars_before_mapping = True
    mlab.colorbar(s2, title='Curvature\n', orientation='vertical')
    mlab.show()
Exemple #7
0
def plot_f_over_sphere(f, n=1001):
    # Create a sphere
    r = 1
    pi = np.pi
    cos = np.cos
    sin = np.sin
    phi, theta = np.mgrid[0:pi:n * 1j, 0:2 * pi:n * 1j]

    x = r * sin(phi) * cos(theta)
    y = r * sin(phi) * sin(theta)
    z = r * cos(phi)

    s = np.zeros_like(x)

    for i in range(n):
        for j in range(n):
            s[i, j] = f(x[i, j], y[i, j], z[i, j])

    mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 400))
    mlab.clf()

    mlab.mesh(x, y, z, scalars=s, colormap='jet')
    mlab.colorbar(orientation='vertical')
    mlab.outline()
    mlab.axes()
    mlab.view(distance=10)
    mlab.show()
def plot_cone_surface(X,Y,Z,title):
    # Some parameters (note size only really changes scale on axis)
    #sizeX,sizeY = 1,2
    #amplitude = 1
    #nPoints = 500

    # Calculate wavenumbers
    #kx = nX*pi/sizeX
    #ky = nY*pi/sizeY

    xyz = np.vstack([X,Y,Z])
    kde = stats.gaussian_kde(xyz)
    density = kde(xyz)
    
    # Plot scatter with mayavi
    figure = mlab.figure(title)
    figure.scene.disable_render = True
    
    pts = mlab.points3d(X, Y, Z, density, scale_mode='none', scale_factor=0.07) 
    mask = pts.glyph.mask_points
    mask.maximum_number_of_points = X.size
    mask.on_ratio = 1
    pts.glyph.mask_input_points = True
    
    figure.scene.disable_render = False 
    mlab.colorbar()
    mlab.axes()
    mlab.show()
Exemple #9
0
 def plotvtk3D(self):
     """
     3D plot using the vtk libraries
     """
     from tvtk.api import tvtk
     from mayavi import mlab
     # Plot the data on a 3D grid
     xy = np.column_stack((self.grd.xp,self.grd.yp))
     dvp = self.F(xy)
     vertexag = 50.0
     
     points = np.column_stack((self.grd.xp,self.grd.yp,dvp*vertexag))
     tri_type = tvtk.Triangle().cell_type
     #tet_type = tvtk.Tetra().cell_type
     ug = tvtk.UnstructuredGrid(points=points)
     ug.set_cells(tri_type, self.grd.cells)
     
     ug.cell_data.scalars = self.grd.dv
     ug.cell_data.scalars.name = 'depths'
     
     f=mlab.gcf()
     f.scene.background = (0.,0.,0.)
     d = mlab.pipeline.add_dataset(ug)
     h=mlab.pipeline.surface(d,colormap='gist_earth')
     mlab.colorbar(object=h,orientation='vertical')
     mlab.view(0,0)
     
     outfile = self.suntanspath+'/depths.png'
     f.scene.save(outfile)      
     print('Figure saved to %s.'%outfile)
Exemple #10
0
    def generate_plots_3d(self):
        self.ax = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(800, 600))
        self.clf = mlab.clf()

        minS, maxS = maxint, 0
        contour_plots = []
        for cond in self.conductors.itervalues():

            minS, maxS, face_data = self.generate_plot_data_for_faces_3d(cond, minS, maxS)
            for (x, y, z, s) in face_data:
                if isinstance(cond, conductor_type_3d['Unstructured']):
                    pts = mlab.points3d(x, y, z, s, scale_mode='none', scale_factor=0.002)
                    mesh = mlab.pipeline.delaunay3d(pts)
                    contour_plots.append(mlab.pipeline.surface(mesh, colormap='viridis'))
                else:
                    if np.min(s) < 0.0:
                        contour_plots.append(mlab.mesh(x, y, z, color=(0, 0, 0), colormap='viridis'))
                    else:
                        contour_plots.append(mlab.mesh(x, y, z, scalars=s, colormap='viridis'))

        for cp in contour_plots:
            cp.module_manager.scalar_lut_manager.trait_set(default_data_range=[minS * 0.95, maxS * 1.05])

        mlab.draw()
        mlab.colorbar(object=contour_plots[0], orientation='vertical')
        mlab.show()
Exemple #11
0
def make_figure(lon=-11.36, lat=-43.31, side=5, title=None, warp_scale=0.2):
    """Plotting interactive crater DEM data with mayavi"""

    range_lon = lon - side / 2, lon + side / 2
    range_lat = lat - side / 2, lat + side / 2

    # TODO: add reprojection to rasterio-based tiff handling
    #dem_arr = mio.square_cutout(lon, lat, side)
    dem_arr = mio.read_warped_window(lon, lat, side)

    surf = mlab.surf(range_lat, range_lon, dem_arr,
                     warp_scale=warp_scale, colormap='gist_earth')
    # TODO: can set a satellite texture on it with
    # surf.actor.actor.texture = optical_moon_image
    if title:
        mlab.title(title)
    mlab.colorbar(title='LOLA elevation model (m)', orientation='vertical',
                  label_fmt='%.1f')
    mlab.axes(xlabel='Longitude', ylabel='Latitude', zlabel='', opacity=0.5)
    ax = mlab.axes()
    #ax.axes.property.color = 'white'
    #ax.axes.axis_title_text_property.color = 'white'
    ax.axes.x_label = "Latitude"
    ax.axes.y_label = "Longitude"
    ax.axes.z_label = "Elevation"
    ax.axes.label_format = ""

    mlab.show()
Exemple #12
0
def view_patch(r, attrib=[], opacity=1, fig=0, show=1):

    if fig == 0:
        fig = mlab.figure()
    else:
        mlab.figure(fig)

    if len(attrib) > 0:
        mlab.triangular_mesh(r.vertices[:, 0],
                             r.vertices[:, 1],
                             r.vertices[:, 2],
                             r.faces,
                             representation='surface',
                             opacity=opacity,
                             scalars=attrib)
    else:
        mlab.triangular_mesh(r.vertices[:, 0],
                             r.vertices[:, 1],
                             r.vertices[:, 2],
                             r.faces,
                             representation='surface',
                             opacity=opacity)

    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=90)
    mlab.colorbar(orientation='horizontal')

    mlab.draw()
    if show > 0:
        mlab.show(stop=True)

    return fig
Exemple #13
0
def do_mlab():

	f = open(sys.argv[1]+"/index.list","r")
	lines = f.readlines()


	calls = []
	lc = None
	for i,line in enumerate(lines):
		calls.append( (i, sys.argv[1]+line[:-1])) #,region=[0,10000,0,30,8,13])
		lc = sys.argv[1]+line[:-1]		
	print calls

	ppservers = ()
	job_server = pp.Server(ppservers=ppservers, ncpus = 10)

	print "Starting pp with", job_server.get_ncpus(), "workers"
	# The following submits 8 jobs and then retrieves the results
	jobs = [ job_server.submit(readdata,(data[1],), (mfilter,), ("mmdlab","mmdlab.datareader")) for data in calls];

	size = int(1920), int(1080)
	fig = mlab.figure('Viz', size=size,bgcolor=(0,0,0))
	fig.scene.anti_aliasing_frames = 0

	import time
	gas  = []
	for i,job in enumerate(jobs):
		(metal,g)  =  job()
		gas.append(g)
		print "Job",i,"done"

	traj = get_traj(gas)

	parts_no = [8144152,8156221, 8131715, 8146196, 8134778, 8141532, 8132951, 8145946, 8133361,
 8129611, 8137788, 8140157, 8146085,]
	lm,lg = readfile_metgas_bin(lc, pfilter=mfilter, parts_at_once=10000)
	for p in parts_no:
		val = traj[p]
		ppl = mlab.plot3d(val["x"], val["y"], val["z"], val["t"], tube_radius=0.025, colormap='cool');
		mlab.colorbar(ppl)
		#for g in gas:
		#	mlab.points3d(g.x[numpy.where(g.n == p)],g.y[numpy.where(g.n == p)],g.z[numpy.where(g.n == p)],scale_factor=lm.d, colormap='cool')
		#	mlab.text(color=(1,0,0),width=0.06,x = g.x[numpy.where(g.n == p)][0],y= g.y[numpy.where(g.n == p)][0],z = g.z[numpy.where(g.n == p)][0],text = str(g.t[numpy.where(g.n == p)][0]))
	#mlab.points3d(lg.x, lg.y, lg.z, lg.t, scale_mode="none",scale_factor=lg.d, colormap="cool")
	
	mscat = mlab.pipeline.scalar_scatter(lm.x, lm.y, lm.z)
	mgauss = mlab.pipeline.gaussian_splatter(mscat)

	mlab.pipeline.iso_surface(mgauss,colormap="black-white",contours=[0.9999,],opacity = 1)
	#mlab.points3d(lm.x, lm.y, lm.z, lm.t, scale_mode="none",scale_factor=lm.d, colormap="copper")
	#for val in traj.values():
	#	
		#print "Drawing metal"
		#metp = mlab.points3d(metal.x,metal.y,metal.z,metal.v,scale_mode="none",scale_factor=metal.d, colormap="copper",mode = "point",mask_points = 100)
		#print "Drawing gas"
		#gasp = mlab.points3d(gas.x,gas.y,gas.z,gas.v,scale_mode="none",scale_factor=gas.d,colormap="cool")
		#print "saving to ./vid/{num:02d}.png".format(num=i)
		#mlab.savefig("./vid/{num:02d}.png".format(num=i))
		#mlab.clf()
	mlab.show()
Exemple #14
0
  def draw(self,**kwargs):
    x = np.linspace(self._base_square_x[0],
                    self._base_square_x[1],self._Nl)
    y = np.linspace(self._base_square_y[0],
                    self._base_square_y[1],self._Nw)
    x,y = np.meshgrid(x,y)
    z = 0.0*x
    for trans in self._transforms:
      p = np.concatenate((x[:,:,None],
                          y[:,:,None],
                          z[:,:,None]),
                          axis=-1)
      p = trans(p)
      pflat = np.reshape(p,(-1,3))
      c = self._f(pflat,*self._f_args,**self._f_kwargs)
      c = np.reshape(c,np.shape(p)[:-1])
      if self._clim is None:
        self._clim = (np.min(c),np.max(c))

      m = mlab.mesh(p[:,:,0],p[:,:,1],p[:,:,2],
                    scalars=c,
                    vmin=self._clim[0],
                    vmax=self._clim[1],**kwargs)

      m.module_manager.scalar_lut_manager.lut.table = self._rgba
      mlab.colorbar()
      mlab.draw()

      if self._plots is None:
        self._plots = (m,trans),

      else:
        self._plots += (m,trans),

    return [i[0] for i in self._plots]
Exemple #15
0
    def action(u, x, xv, y, yv, t, n):
        #print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y
        if plot == 1:
            mesh(xv, yv, u, title='t=%g' %t[n])
            time.sleep(0.2) # pause between frames

        elif plot == 2:
            # mayavi plotting
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
            ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
            zlabel='',
            x_axis_visibility=False, z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(2, -2.5, '', z=-4, width=0.1)
            mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None)
            mlab.title('test 1D t=%g' % t[n])

            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)
        
        
        if plot > 0:
            path = 'Figures_wave2D'
            time.sleep(0) # pause between frames
            if save_plot and plot != 2:
                filename = '%s/%08d.png' % (path, n)
                savefig(filename)  # time consuming!
            elif save_plot and plot == 2:
                filename = '%s/%08d.png' % (path,n)
                mlab.savefig(filename)  # time consuming!
Exemple #16
0
    def startup(self):
        # super().startup()

        # print( len( self.data ) )
        src = mlab.pipeline.scalar_field(self.data, figure=self.mayavi_scene)
        self.mayavi_plot = mlab.pipeline.volume(src,
                                                figure=self.mayavi_scene,
                                                vmin=12,
                                                vmax=14)
        # vmin = 0.8, vmax = 1.0,
        # color = (0.5,0.5,0.5))

        # print_info( self.mayavi_plot._otf )

        mlab.colorbar(self.mayavi_plot, orientation='vertical')

        # see https://docs.enthought.com/mayavi/mayavi/auto/example_magnetic_field.html
        # self.mayavi_plot.glyph.trait_set( mask_input_points = True )
        # self.mayavi_plot.glyph.mask_points.trait_set( on_ratio = 2, random_mode = False )

        # print_info( self.mayavi_plot.glyph.mask_points )

        # self.set_mask_points( 5 )

        # print_info( self.mayavi_plot )

        # self.axes_bounds = self.data.shape * self.scale
        self.set_orientation_axes(1)
        # self.set_outline( 1 )
        self.needs_startup = 0
Exemple #17
0
 def plot_solution(self):
     xn, yn, pn = self.get_plot_data()
     u, v, p = pn[..., 0], pn[..., 1], pn[..., 2]
     for arr in (xn, yn, u, v, p):
         arr.shape = arr.shape + (1, )
     vmag = np.sqrt(u*u + v*v)
     pde = self.pde
     if self.plt1 is None:
         mlab.figure(
             size=(700, 700), fgcolor=(0, 0, 0), bgcolor=(1, 1, 1)
         )
         if self.show_exact and pde.has_exact():
             un = pde.exact(xn, yn)
             mlab.surf(xn, yn, un, colormap='viridis',
                       representation='wireframe')
         src = mlab.pipeline.vector_field(
             xn, yn, np.zeros_like(xn), u, v, np.zeros_like(u),
             scalars=vmag, name='vectors'
         )
         self.plt1 = mlab.pipeline.vectors(
             src, scale_factor=0.2, mask_points=3, colormap='viridis'
         )
         self.plt1.scene.z_plus_view()
         cgp = mlab.pipeline.contour_grid_plane(
             src, opacity=0.8,
             colormap='viridis',
         )
         cgp.enable_contours = False
         mlab.colorbar(self.plt1)
     else:
         self.plt1.mlab_source.trait_set(u=u, v=v, scalars=vmag)
     return self.get_error(xn, yn, pn)
Exemple #18
0
def plot3(X, f=None, axeLab=['', '', ''], clf=True):
    """
    X.shape[0] = 3 or 4
    """

    if clf:
        ml.clf(f)

    for i in range(X.shape[0]):
        assert diff(rg) != 0, 'range of axis %d is zero!' % (i)

    if X.shape[0] == 3:
        ml.plot3d(sc(X[0]), sc(X[1]), sc(X[2]), figure=f, extent=ex)
    elif X.shape[0] == 4:
        p = ml.plot3d(sc(X[0]),
                      sc(X[1]),
                      sc(X[2]),
                      sc(X[3]),
                      figure=f,
                      extent=ex)
        ml.colorbar(p)

    axe(axeLab, rgs(X[0], X[1], X[2]), f)
    out()
    return f
Exemple #19
0
 def plotvtk3D(self):
     """
     3D plot using the vtk libraries
     """
     from tvtk.api import tvtk
     from mayavi import mlab
     # Plot the data on a 3D grid
     xy = np.column_stack((self.grd.xp,self.grd.yp))
     dvp = self.F(xy)
     vertexag = 50.0
     
     points = np.column_stack((self.grd.xp,self.grd.yp,dvp*vertexag))
     tri_type = tvtk.Triangle().cell_type
     #tet_type = tvtk.Tetra().cell_type
     ug = tvtk.UnstructuredGrid(points=points)
     ug.set_cells(tri_type, self.grd.cells)
     
     ug.cell_data.scalars = self.grd.dv
     ug.cell_data.scalars.name = 'depths'
     
     f=mlab.gcf()
     f.scene.background = (0.,0.,0.)
     d = mlab.pipeline.add_dataset(ug)
     h=mlab.pipeline.surface(d,colormap='gist_earth')
     mlab.colorbar(object=h,orientation='vertical')
     mlab.view(0,0)
     
     outfile = self.suntanspath+'/depths.png'
     f.scene.save(outfile)      
     print 'Figure saved to %s.'%outfile
Exemple #20
0
    def surface_timeseries(surface, data, step=1):
        """
        
        """
        fig = mlab.figure(figure="surface_timeseries", fgcolor=(0.5, 0.5, 0.5))
        #Plot an initial surface and colourbar #TODO: Change to use plot_surface function, see below.
        surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0],
                                         surface.vertices[:, 1],
                                         surface.vertices[:, 2],
                                         surface.triangles,
                                         scalars=data[0, :],
                                         vmin=data.min(), vmax=data.max(),
                                         figure=fig)
        mlab.colorbar(object=surf_mesh, orientation="vertical")

        #Handle for the surface object and figure
        surf = surf_mesh.mlab_source

        #Time #TODO: Make actual time rather than points, where/if possible.
        tpts = data.shape[0]
        time_step = mlab.text(0.85, 0.125, ("0 of %s" % str(tpts)),
                              width=0.0625, color=(1, 1, 1), figure=fig,
                              name="counter")

        #Movie
        k = 0
        while 1:
            if abs(k) >= tpts:
                k = 0
            surf.set(scalars=data[k, :])
            time_step.set(text=("%s of %s" % (str(k), str(tpts))))
            k += step
            yield
        mlab.show()
Exemple #21
0
def mayaView(num, path="./data"):
    """
    num is a str eg. "20-1", "400"
    loads images from ./data
    """
    assert type(num) == str
    x = np.load(path + '/xdata{}.dat'.format(num))
    y = np.load(path + '/ydata{}.dat'.format(num))
    z = np.load(path + '/zdata{}.dat'.format(num))
    density = np.load(path + '/density{}.dat'.format(num))

    figure = mlab.figure('DensityPlot')
    mag = density / np.amax(density)

    n = num[0]
    l = num[1]
    if num[2] == "-":
        m = num[2:]
    else:
        m = num[2]

    pts = mlab.points3d(mag, opacity=0.5, transparent=True)
    # pts = mlab.contour3d(mag,opacity =0.5)
    #mlab.title('n= {}, l = {}, m= {}'.format(n,l,m), size= 20)
    mlab.text(0.5, 0.2, 'n= {}, l = {}, m= {}'.format(n, l, m), opacity=1)

    mlab.colorbar(orientation='vertical')
    mlab.axes()
    mlab.savefig(
        '/home/ada/Documents/SUTD/Term 3/Physical Chemistry/Schrodinger-Assignment/Images/'
        + num + '.png')
Exemple #22
0
 def DogPlot(self):
     # puttdog(self.OutDog)
     mlab.clf()
     fileddog = mlab.pipeline.scalar_field(self.cutdog)
     mlab.pipeline.volume(fileddog, vmin=0, vmax=self.numpug - 1)
     mlab.colorbar()
     pass
Exemple #23
0
 def plot3dpoint(self,color):
     #print color.shape
     simple_tm=p3d.triangular_mesh(self.surf_points[:,0], self.surf_points[:,1], 
                            self.surf_points[:,2], 
                            self.surf_elements, 
                            scalars=color)                       
     p3d.colorbar(object=simple_tm, title='Displacement', orientation=None, nb_labels=5, nb_colors=25, label_fmt='%.2f')
Exemple #24
0
def plot_trajectory(perf_data, stimset, stim_class, symbols, post_stim_time=1):
        
    net = perf_data.net
    net.noise_std = 0.0
        
        
    mlab.figure(bgcolor=(0.5, 0.5, 0.5), fgcolor=(0.0, 0.0, 0.0))
    for symbol in symbols:
        stim_md5 = stimset.symbol_to_md5[symbol][0]
        stim = stimset.all_stims[stim_md5]
        net_sims = run_sim(net, {stim_md5:stim},
                           burn_time=100,
                           pre_stim_time = 1,
                           post_stim_time=max(25, post_stim_time),
                           num_trials=1)
        
        sim = net_sims[stim_md5]
        avg_resp = sim.responses[0, :, :].squeeze()
        stim_start = 0
        record_time = len(stim) + 1
        stim_end = len(stim) + post_stim_time
        
        stimsym = stimset.md5_to_symbol[stim_md5]
        #stim_str = '%s:%s (%0.2f)' % (stimsym, ''.join(['%d' % s for s in stim]), perf_data.logit_perf)
        stim_str = '%s:%s' % (stimsym, ''.join(['%d' % s for s in stim]))
    
        t = np.arange(0, stim_end)
        traj = mlab.plot3d(avg_resp[0:stim_end, 0], avg_resp[0:stim_end, 1], avg_resp[0:stim_end, 2], t,
                           colormap='hot', tube_radius=None)
        #mlab.points3d(avg_resp[stim_start, 0], avg_resp[stim_start, 1], avg_resp[stim_start, 2], scale_factor=0.300)
        mlab.points3d(avg_resp[record_time-1, 0], avg_resp[record_time-1, 1], avg_resp[record_time-1, 2], scale_factor=0.900)
    
    mlab.colorbar()
    if len(symbols) == 1:
        mlab.title(stim_str)
    def surface_timeseries(surface, data, step=1):
        """
        
        """
        fig = mlab.figure(figure="surface_timeseries", fgcolor=(0.5, 0.5, 0.5))
        #Plot an initial surface and colourbar #TODO: Change to use plot_surface function, see below.
        surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0],
                                         surface.vertices[:, 1],
                                         surface.vertices[:, 2],
                                         surface.triangles,
                                         scalars=data[0, :],
                                         vmin=data.min(), vmax=data.max(),
                                         figure=fig)
        mlab.colorbar(object=surf_mesh, orientation="vertical")

        #Handle for the surface object and figure
        surf = surf_mesh.mlab_source

        #Time #TODO: Make actual time rather than points, where/if possible.
        tpts = data.shape[0]
        time_step = mlab.text(0.85, 0.125, ("0 of %s" % str(tpts)),
                              width=0.0625, color=(1, 1, 1), figure=fig,
                              name="counter")

        #Movie
        k = 0
        while 1:
            if abs(k) >= tpts:
                k = 0
            surf.set(scalars=data[k, :])
            time_step.set(text=("%s of %s" % (str(k), str(tpts))))
            k += step
            yield
        mlab.show(stop=True)
Exemple #26
0
def mcrtmv(frames, mvname, dt, Lx, Ly, Nx, Ny):
    x = np.linspace(0, Lx, Nx)
    y = np.linspace(0, Ly, Ny)
    X, Y = np.meshgrid(x, y)
    size = 500, 500

    fig = ml.figure(size=size, bgcolor=(1., 1., 1.))

    #fig.scene.anti_aliasing_frames=07

    #extent = [0,Nx-1,0,Ny-1,-30,30]

    ml.clf(figure=fig)
    u = np.loadtxt('test.d%07d' % 1)
    fname = '_tmp%07d.png' % 1
    s = ml.surf(x, y, u, figure=fig, vmin=-0, vmax=1)
    ml.axes(extent=[0, Lx, 0, Ly, -2, 2])
    ml.colorbar()
    ml.xlabel('x position')
    ml.ylabel('y position')
    ml.zlabel('wave amplitude')
    """
	pl.ion()
	arr = ml.screenshot()
	img = pl.imshow(arr)
	pl.axis('off')
	"""
    for i in range(2, frames):
        #arr = ml.screenshot()
        #img.set_array(arr)
        u = np.loadtxt('test.d%07d' % i)
        s.mlab_source.scalars = u
        fname = '_tmp%07d.png' % i
    def startup(self):
        # super().startup()

        # print( len( self.data ) )

        self.mayavi_plot = mlab.flow(*self.data,
                                     figure=self.mayavi_scene,
                                     integration_direction='both',
                                     seedtype='point',
                                     seed_resolution=1,
                                     linetype='line')

        self.set_max_propagation(400)

        self.set_max_nsteps(4000)

        mlab.colorbar(self.mayavi_plot, orientation='vertical')

        # see https://docs.enthought.com/mayavi/mayavi/auto/example_magnetic_field.html
        # self.mayavi_plot.glyph.trait_set( mask_input_points = True )
        # self.mayavi_plot.glyph.mask_points.trait_set( on_ratio = 2, random_mode = False )

        # print_info( self.mayavi_plot.glyph.mask_points )

        # self.set_mask_points( 5 )

        # print_info( self.mayavi_plot )

        self.set_orientation_axes(1)
        # self.set_outline( 1 )
        self.needs_startup = 0
Exemple #28
0
    def generate_plots_3d(self):
        self.ax = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(800, 600))
        self.clf = mlab.clf()

        minS, maxS = maxint, 0
        contour_plots = []
        for cond in self.conductors.itervalues():

            minS, maxS, face_data = self.generate_plot_data_for_faces_3d(cond, minS, maxS)
            for (x, y, z, s) in face_data:
                if isinstance(cond, conductor_type_3d['Unstructured']):
                    pts = mlab.points3d(x, y, z, s, scale_mode='none', scale_factor=0.002)
                    mesh = mlab.pipeline.delaunay3d(pts)
                    contour_plots.append(mlab.pipeline.surface(mesh, colormap='viridis'))
                else:
                    if np.min(s) < 0.0:
                        contour_plots.append(mlab.mesh(x, y, z, color=(0, 0, 0), colormap='viridis'))
                    else:
                        contour_plots.append(mlab.mesh(x, y, z, scalars=s, colormap='viridis'))

        for cp in contour_plots:
            cp.module_manager.scalar_lut_manager.trait_set(default_data_range=[minS * 0.95, maxS * 1.05])

        mlab.draw()
        mlab.colorbar(object=contour_plots[0], orientation='vertical')
        mlab.show()
    def xmas_balls(connectivity, node_data=None, edge_data=False):
        """
        Plots coloured balls at the region centres of connectivity, colour and
        size is determined by a vector of length number of regions (node_data).
        
        Optional: adds the connections between pair of nodes.
        
        """
        centres = connectivity.centres
        edges = numpy.array(numpy.nonzero(connectivity.weights))
        edges = numpy.array([(start, stop) for (start, stop) in edges.T if start != stop])

        if node_data is not None:
            data_scale = 13.0 / node_data.max()
            pts = mlab.points3d(centres[:, 0], centres[:, 1], centres[:, 2],
                                node_data, transparent=True,
                                scale_factor=data_scale,
                                colormap='Blues')

            mlab.colorbar(orientation="vertical")
        else:
            #NOTE: the magic numbers are used to align region centers and surface representation. 
            #Do not ask ... 
            pts = mlab.points3d(centres[:, 0] * 1.13, centres[:, 1] * 1.13 + 15, centres[:, 2] - 25)

        if edge_data:
            pts.mlab_source.dataset.lines = edges
            tube = mlab.pipeline.tube(pts, tube_radius=0.5)
            mlab.pipeline.surface(tube, colormap='binary', opacity=0.142)
Exemple #30
0
    def xmas_balls(connectivity, node_data=None, edge_data=False):
        """
        Plots coloured balls at the region centres of connectivity, colour and
        size is determined by a vector of length number of regions (node_data).
        
        Optional: adds the connections between pair of nodes.
        
        """
        centres = connectivity.centres
        edges = numpy.array(numpy.nonzero(connectivity.weights))
        edges = numpy.array([(start, stop) for (start, stop) in edges.T
                             if start != stop])

        if node_data is not None:
            data_scale = 13.0 / node_data.max()
            pts = mlab.points3d(centres[:, 0],
                                centres[:, 1],
                                centres[:, 2],
                                node_data,
                                transparent=True,
                                scale_factor=data_scale,
                                colormap='Blues')

            mlab.colorbar(orientation="vertical")
        else:
            #NOTE: the magic numbers are used to align region centers and surface representation.
            #Do not ask ...
            pts = mlab.points3d(centres[:, 0] * 1.13,
                                centres[:, 1] * 1.13 + 15, centres[:, 2] - 25)

        if edge_data:
            pts.mlab_source.dataset.lines = edges
            tube = mlab.pipeline.tube(pts, tube_radius=0.5)
            mlab.pipeline.surface(tube, colormap='binary', opacity=0.142)
Exemple #31
0
def scat(X, f=None, axeLab=['', '', ''], clf=True, scale='none'):
    """
    X.shape[0] = 3 or 4
    """

    if clf:
        ml.clf(f)

    if X.shape[0] == 3:
        ml.points3d(sc(X[0].ravel()),
                    sc(X[1].ravel()),
                    sc(X[2].ravel()),
                    figure=f,
                    scale_mode=scale,
                    scale_factor=.02,
                    extent=ex)
    elif X.shape[0] == 4:
        p = ml.points3d(sc(X[0].ravel()),
                        sc(X[1].ravel()),
                        sc(X[2].ravel()),
                        sc(X[3].ravel()),
                        figure=f,
                        scale_mode=scale,
                        scale_factor=.02,
                        extent=ex)
        ml.colorbar(p)

    axe(axeLab, rgs(X[0], X[1], X[2]), f)
    out()
    return f
Exemple #32
0
def UnstructuredAbs(Mesh, Scalar=None, Name='', Figure=None):

    Figure = mlab.figure(figure=None, size=(600, 300))
    visual.set_viewer(Figure)

    if Scalar is None: Scalar = Mesh.Phi.Radian * 0 + 1

    x, y, z = Sp2Cart(Scalar.flatten(), Mesh.Phi.Radian.flatten(),
                      Mesh.Theta.Radian.flatten())

    AddUnitAxes(Figure=Figure, Scale=1., Origin=(0, 0, -1.5))

    AddUnitSphere(Num=50, Radius=1, Origin=(0, 0, 0), Figure=Figure)

    im0 = mlab.points3d(x,
                        y,
                        z,
                        abs(Scalar),
                        mode='sphere',
                        scale_mode='none',
                        colormap=CMAP)

    mlab.colorbar(object=im0,
                  label_fmt="%.0e",
                  nb_labels=5,
                  title='Real part',
                  orientation='horizontal')
Exemple #33
0
def plot_contours(g, ncont=10, vfmin=0.1, vfmax=0.1, ranges=None, vlims=None):
    mlab.clf()

    if vlims is None:
        gmin, gmax, p2p = xutil.MinMax(g)
        vmin, vmax = gmin + p2p * vfmin, gmax - vfmax * p2p
    else:
        vmin, vmax = vlims
    contours = list(np.linspace(vmin, vmax, ncont))

    src = mlab.pipeline.scalar_field(g)

    # mlab.pipeline.iso_surface(src, contours=contours, opacity=0.3, colormap='viridis', vmin=vmin, vmax=vmax)
    mlab.outline()
    mlab.axes(line_width=0.5,
              xlabel='Z',
              ylabel='Y',
              zlabel='X',
              ranges=ranges)
    mlab.pipeline.iso_surface(src,
                              contours=contours[:-1],
                              opacity=0.2,
                              colormap='viridis',
                              vmin=vmin,
                              vmax=vmax)
    mlab.pipeline.iso_surface(src,
                              contours=contours[-1:],
                              opacity=0.8,
                              colormap='viridis',
                              vmin=vmin,
                              vmax=vmax)
    mlab.colorbar(orientation='vertical')
Exemple #34
0
def neighbour_correlation(rho,faces,r_vertices,msk):
    import networkx as nx
    g = nx.Graph()
    g.add_edges_from(faces[:, (0, 1)])
    g.add_edges_from(faces[:, (1, 2)])
    g.add_edges_from(faces[:, (2, 0)])
    g.add_edges_from(faces[:, (1, 0)])
    g.add_edges_from(faces[:, (2, 1)])
    g.add_edges_from(faces[:, (0, 2)])
    Adj = nx.adjacency_matrix(g)
    AdjS = Adj.todense()
    np.fill_diagonal(AdjS, 1)
    # AdjS.shape
    #AdjS = 1.0 * ((AdjS * AdjS * AdjS) > 0)
    AdjS = np.matrix(AdjS) * np.matrix(AdjS)
    AdjS=AdjS>0
    AdjS=1.0*AdjS

    rho_Thresh = np.multiply(AdjS, rho)
    rho_Thresh = np.mean(rho_Thresh, 1)
    labels = np.zeros([r_vertices.shape[0]])
    labels[msk]=rho_Thresh


    mlab.triangular_mesh(r_vertices[:, 0], r_vertices[:, 1], r_vertices[:, 2], faces, representation='surface',
                         opacity=1, scalars=np.float64(labels))


    mlab.gcf().scene.parallel_projection = True
    mlab.view(azimuth=0, elevation=90)
    mlab.colorbar(orientation='horizontal')
    mlab.close()
def showDsweep():
    k_s_sweep = [10**(x-5) for x in range(10)]
    sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)]
    vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)]    
    
    Dmsd = numpy.load(data_dir + "/D_numpy.npy")
    kDa = 1.660538921e-30;
    mass = 40.0*kDa; 
    viscosity = 8.9e-4; 
    diameter = 5e-9; 
    T = 300.0; 
    Dbase = k_b*T/(3.0*numpy.pi*viscosity*diameter);
    Dmsd = Dmsd/Dbase
    
    mlab.figure(1, size=(800, 800), fgcolor=(1, 1, 1),
                                    bgcolor=(0.5, 0.5, 0.5))
    mlab.clf()
    contours = numpy.arange(0.01,2,0.2).tolist()
    obj = mlab.contour3d(Dmsd,contours=contours,transparent=True,vmin=contours[0],vmax=contours[-1])
    outline = mlab.outline(color=(.7, .7, .7),extent=(0,10,0,20,0,10))
    axes = mlab.axes(outline, color=(.7, .7, .7),
            nb_labels = 5,
            ranges=(k_s_sweep[0], k_s_sweep[-1], sl_div_diam_sweep[0], sl_div_diam_sweep[-1], vol_ratio_sweep[0], vol_ratio_sweep[-1]), 
            xlabel='spring stiffness', 
            ylabel='step length',
            zlabel='volume ratio')
    mlab.colorbar(obj,title='D',nb_labels=5)

    mlab.show()
Exemple #36
0
def plot3D_density(it, spec):

    if it == '':
        it = '0'

    if spec == '':
        spec = 'electrons'

    #===============================================================================
    # Parameters of the simulation

    params1 = numpy.loadtxt(".././Zeltron3D/data/phys_params.dat", skiprows=1)
    params2 = numpy.loadtxt(".././Zeltron3D/data/input_params.dat", skiprows=1)

    # Nominal cyclotron frequency
    rho = 2.9979246e+10 / params1[3]

    #===============================================================================
    # The grid
    x = numpy.loadtxt(".././Zeltron3D/data/x.dat")
    y = numpy.loadtxt(".././Zeltron3D/data/y.dat")
    z = numpy.loadtxt(".././Zeltron3D/data/z.dat")

    # The density
    map0 = numpy.loadtxt(".././Zeltron3D/data/densities/mapxyz_" + spec +
                         "_drift0.dat")
    mapd = numpy.loadtxt(".././Zeltron3D/data/densities/mapxyz_" + spec +
                         "_drift" + it + ".dat")
    mapb = numpy.loadtxt(".././Zeltron3D/data/densities/mapxyz_" + spec +
                         "_bg" + it + ".dat")

    nx = len(x) - 1
    ny = len(y) - 1
    nz = len(z) - 1

    dx, ptx = x[1] - x[0], nx * 1j
    dy, pty = y[1] - y[0], ny * 1j
    dz, ptz = z[1] - z[0], nz * 1j

    x, y, z = numpy.ogrid[-dx:dx:ptx, -dy:dy:pty, -dz:dz:ptz]

    mapxyz = numpy.empty((nx, ny, nz))

    for ix in range(0, nx):
        for iy in range(0, ny):
            for iz in range(0, nz):
                mapxyz[ix, iy,
                       iz] = mapd[iy + iz * ny, ix] + mapb[iy + iz * ny, ix]

    mapxyz = mapxyz / numpy.max(map0)

    contour3d(mapxyz, contours=10, transparent=True, opacity=0.9)
    mlab.outline()
    mlab.colorbar(title='n/n0', orientation='vertical', nb_labels=10)
    mlab.axes()
    mlab.title("Time=" + it + ", " + spec)

    #===============================================================================

    mlab.show()
Exemple #37
0
def loadplot(fn: Path):
    datfn = Path(fn).expanduser()

    with h5py.File(datfn, "r") as f:
        Ne = np.rot90(f["/den1"][:128, ...])

    yg = np.linspace(0, 51.2, Ne.shape[2])
    xg = np.linspace(0, 51.2, Ne.shape[1])
    # zg = np.linspace(0, 51.2, Ne.shape[0])
    # %%
    FNe = np.fft.fft2(Ne)
    Fmag = np.fft.fftshift(abs(FNe))
    # %%
    A = np.arange(0, 2 * np.pi, 0.01)
    r = 2 * np.pi / 3  # [m]
    x = r * np.cos(A)
    y = r * np.sin(A)

    # for now just taking the first slice
    f = RectBivariateSpline(xg, yg, Ne[0, ...])

    # interp2d never finished, extremely long run time--never had this problem before (!)
    xm, ym = np.meshgrid(xg, yg)
    #    f = interp2d(xm,ym,Ne)
    # BivarateSpline is using FITPACK, which appears to accept only single coordinate pairs at a time.
    iNe = np.empty(x.size)
    for i, (xi, yi) in enumerate(zip(x, y)):
        iNe[i] = f(xi, yi)

    # %%
    if 0:
        fg = figure()
        ax = fg.gca()
        hi = ax.pcolormesh(xg, yg, Ne)

        ax.set_xlabel("x [m]")
        ax.set_ylabel("y [m]")
        ax.set_title("Number density $N_e$")
        fg.colorbar(hi).set_label("$N_e$ [normalized]")

        ax = figure().gca()
        hi = ax.pcolormesh(Fmag)

        # state machine code--less reliable way to plot
        # plt.pcolormesh(Ne)
        # plt.colorbar()
        # plt.show()

    ax = figure().gca()
    ax.plot(np.degrees(A), iNe)
    ax.set_xlabel("angle [degrees]")
    ax.set_ylabel("power")
    ax.autoscale(True, axis="x", tight=True)

    fg = mlab.figure()
    scf = mlab.pipeline.scalar_field(Ne, figure=fg)
    vol = mlab.pipeline.volume(scf, figure=fg)
    mlab.colorbar(vol)
    mlab.show()
Exemple #38
0
def plot_surface(surf_name, data_orig, hemi='rh', cmin=None, cmax=None, colorbar=True, smooth=5):
    ''' Plots data in a 3D brain surface using the current Mayavi's mlab window. surf_name is a string with the name of the surface, data is a vector of the same length of the number of points in the surface. Function performs smoothing by default, and set the color of the brain to gray by default for points we don't have data. '''

    surf = loadmat('/Users/sudregp/Documents/surfaces/IMAGING_TOOLS/' + surf_name + '.mat')

    nbr = surf['nbr_' + hemi].astype(int)

    # making sure we don't change the original data
    data = data_orig.copy()
    num_voxels = len(data)
    # smoothing data to neighboring voxels with zero value. Algorithm described in MNE-manual-2.7, page 208/356.
    for p in range(smooth):
        print 'Smoothing step ' + str(p + 1) + '/' + str(smooth)
        S = np.zeros([num_voxels, num_voxels])
        for j in range(num_voxels):
            my_neighbors = nbr[j, :] - 1
            # remove entries that are -1
            my_neighbors = np.delete(my_neighbors, np.nonzero(my_neighbors == -1))
            # number of immediate neighbors with non zero values
            Nj = np.sum(data[my_neighbors] != 0)
            if Nj > 0:
                pdb.set_trace()
                S[j, my_neighbors] = 1 / float(Nj)
        data = np.dot(S, data)

    pdb.set_trace()
    # replacing all values that are still 0 by something that is not in the data range.
    data[data == 0] = np.inf

    if cmin is None:
        cmin = np.min(data)
    if cmax is None:
        # check whether we have empty points in the brain. If we do, it has Inf value. If not, the max is the actual maximum of the data
        if len(np.nonzero(np.isinf(data) == True)[0]) == 0:
            cmax = np.max(data)
            add_grey = False
        else:
            cmax = np.unique(np.sort(data))[-2]
            add_grey = True
    else:
        # if cmax was specified, let the person deal with it
        add_grey = False

    surf = mlab.triangular_mesh(surf['coord_' + hemi][0, :], surf['coord_' + hemi][1, :], surf['coord_' + hemi][2, :], surf['tri_' + hemi] - 1, scalars=data, vmax=cmax, vmin=cmin)

    if add_grey:
        # add grey color to scale, and make everything that's infinity that color
        surf.module_manager.scalar_lut_manager.number_of_colors += 1
        lut = surf.module_manager.scalar_lut_manager.lut.table.to_array()
        grey_row = [192, 192, 192, 255]
        # sets the max value in the data range to be gray
        lut = np.vstack((lut, grey_row))
        surf.module_manager.scalar_lut_manager.lut.table = lut

    fig = mlab.gcf()
    # fig.on_mouse_pick(picker_callback)
    mlab.colorbar()

    return surf
def mcrtmv(frames,
           dt,
           mesh,
           d_nodes,
           map,
           savemovie=False,
           mvname='test',
           vmin=-1,
           vmax=1):
    """
	Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac!
	"""

    size = 500, 500

    fig = ml.figure(size=size, bgcolor=(1., 1., 1.))

    #fig.scene.anti_aliasing_frames=07

    #extent = [0,Nx-1,0,Ny-1,-30,30]
    xaxis = np.linspace(0, 1, d_nodes[0] + 1)
    yaxis = np.linspace(0, 1, d_nodes[1] + 1)
    ml.clf(figure=fig)
    u = np.load('solution_%06d.npy' % 1)
    u = numpyfy(u, mesh, d_nodes, map)
    fname = '_tmp%07d.png' % 1
    s = ml.imshow(xaxis, yaxis, u, figure=fig, vmin=vmin, vmax=vmax)
    #scale = 1./np.max(np.abs(u))
    u = u
    ml.axes(extent=[0, 1, 0, 1, 0, 2])
    ml.colorbar()
    ml.xlabel('x position')
    ml.ylabel('y position')
    ml.zlabel('wave amplitude')

    if savemovie == True:
        pl.ion()
        arr = ml.screenshot()
        img = pl.imshow(arr)
        pl.axis('off')

    for i in range(2, frames):

        u = np.load('solution_%06d.npy' % i)
        u = numpyfy(u, mesh, d_nodes, map)
        s.mlab_source.scalars = u
        fname = '_tmp%07d.png' % i
        if savemovie == True:
            arr = ml.screenshot()
            img.set_array(arr)
            pl.savefig(filename=fname)  #,figure=fig)
            print 'Saving frame', fname
            pl.draw()

    fig.scene.disable_render = False
    if savemovie:
        os.system(
            "mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg"
            % mvname)
Exemple #40
0
def plot(pts,color=(1.,1.,1.), scalar_list=None):
    if scalar_list != None:
        mlab.plot3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,scalar_list,
                    representation = 'wireframe', tube_radius = None)
        mlab.colorbar()
    else:
        mlab.plot3d(pts[0,:].A1,pts[1,:].A1,pts[2,:].A1,color=color,
                    representation = 'wireframe', tube_radius = None)
Exemple #41
0
 def draw_cloud(self, points3d, scale=1):
     scale = self.scale * scale
     mlab.points3d(points3d[:, 0], points3d[:, 1],
                   points3d[:, 2], points3d[:, 2],
                   colormap='jet', opacity=0.75, scale_factor=scale)
     mlab.outline()
     mlab.colorbar(title='Planar disparity (mm)')
     mlab.axes()
Exemple #42
0
    def plot_u(u, x, xv, y, yv, t, n):
        """User action function for plotting."""
        if t[n] == 0:
            time.sleep(2)
        if plot_method == 1:
            # Works well with Gnuplot backend, not with Matplotlib
            st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                    caxis=[-1,1])
        elif plot_method == 2:
            # Works well with Gnuplot backend, not with Matplotlib
            st.surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                  colorbar=True, colormap=st.hot(), caxis=[-1,1],
                  shading='flat')
        elif plot_method == 3:
            print 'Experimental 3D matplotlib...under development...'
            # Probably too slow
            #plt.clf()
            ax = fig.add_subplot(111, projection='3d')
            u_surf = ax.plot_surface(xv, yv, u, alpha=0.3)
            #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm)
            #ax.set_zlim(-1, 1)
            # Remove old surface before drawing
            if u_surf is not None:
                ax.collections.remove(u_surf)
            plt.draw()
            time.sleep(1)
        elif plot_method == 4:
	    # Mayavi visualization
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u,
                          colormap='Blues',
                          warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
                      ranges=(0, 10, 0, 10, -1, 1),
                      xlabel='', ylabel='', zlabel='',
                      x_axis_visibility=False,
                      z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(6, -2.5, '', z=-4, width=0.14)
            mlab.colorbar(object=None, title=None,
                          orientation='horizontal',
                          nb_labels=None, nb_colors=None,
                          label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])
            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)

        if plot_method > 0:
            time.sleep(0) # pause between frames
            if save_plot:
                filename = 'tmp_%04d.png' % n
		if plot_method == 4:
                    mlab.savefig(filename)  # time consuming!
		elif plot_method in (1,2):
                    st.savefig(filename)  # time consuming!
Exemple #43
0
def surfacePlot(
    Hmap,
    nrows,
    ncols,
    xyspacing,
    zscale,
    name,
    hRange,
    file_path,
    lutfromfile,
    lut,
    lut_file_path,
    colorbar_on,
    save,
    show,
):

    # Create a grid of the x and y coordinates corresponding to each pixel in the height matrix
    x, y = np.mgrid[0 : ncols * xyspacing : xyspacing, 0 : nrows * xyspacing : xyspacing]

    # Create a new figure
    mlab.figure(size=(1000, 1000))

    # Set the background color if desired
    # bgcolor=(0.16, 0.28, 0.46)

    # Create the surface plot of the reconstructed data
    plot = mlab.surf(x, y, Hmap, warp_scale=zscale, vmin=hRange[0], vmax=hRange[1], colormap=lut)

    # Import the LUT from a file if necessary
    if lutfromfile:
        plot.module_manager.scalar_lut_manager.load_lut_from_file(lut_file_path)

    # Draw the figure with the new LUT if necessary
    mlab.draw()

    # Zoom in to fill the entire window
    f = mlab.gcf()
    f.scene.camera.zoom(1.05)

    # Change the view to a top-down perspective
    mlab.view(270, 0)

    # Add a colorbar if indicated by colorbar_on (=True)
    if colorbar_on:
        # mlab.colorbar(title='Height (nm)', orientation='vertical')
        mlab.colorbar(orientation="vertical")

    # Save the figure if indicated by save (=True)
    if save:
        mlab.savefig(file_path, size=(1000, 1000))
        if show == False:
            mlab.close()

    # Keep the figure open if indicated by show (=True)
    if show:
        mlab.show()
Exemple #44
0
def scatter_contour(nodes,vals,**kwargs):
  pts = 100j
  xmin,xmax = np.min(nodes[:,0]),np.max(nodes[:,0])
  ymin,ymax = np.min(nodes[:,1]),np.max(nodes[:,1])
  zmin,zmax = np.min(nodes[:,2]),np.max(nodes[:,2])
  x,y,z = np.mgrid[xmin:xmax:pts, ymin:ymax:pts, zmin:zmax:pts]
  f = griddata(nodes, vals, (x,y,z),method='linear')
  p = mlab.contour3d(x,y,z,f,**kwargs)
  mlab.colorbar(p)
Exemple #45
0
def field(potential, outfile=None, title="BEM Calculation (field)", cmap="spectral"):
    from mayavi import mlab

    u,v,w = np.gradient(potential)
    obj = mlab.quiver3d(u,v,w, colormap=cmap, vmax=10)
    mlab.colorbar()
    if outfile:
        mlab.savefig(outfile)
    return obj
Exemple #46
0
 def show(self):
   '''Show the 3D diagram in the screen.''' 
   from mayavi import mlab
   self.triangleMesh= mlab.triangular_mesh(self.x, self.y, self.z, self.triangles, scalars= self.scalars)
   mlab.colorbar(self.triangleMesh, orientation='vertical')
   mlab.outline(self.triangleMesh)
   mlab.axes(self.triangleMesh, xlabel= self.axialForceLabel, ylabel= self.bendingMomentYLabel, zlabel= self.bendingMomentZLabel)
   #mlab.title(self.title)
   mlab.show()
Exemple #47
0
	def _plotbutton3_fired(self):
		mlab.clf()
		self.loaddata()
		field = mlab.pipeline.scalar_field(self.sregion) # Generate a scalar field
		mlab.pipeline.volume(field,vmax=self.datamax,vmin=self.datamin)
		
		self.field = field
		self.labels()
		mlab.view(azimuth=0, elevation=0, distance='auto')
		mlab.colorbar()
		mlab.show()
def mcrtmv(frames, dt,mesh, d_nodes, map, savemovie=False, mvname='test', vmin=-1, vmax=1):
	"""
	Creates move from numpyfied results in 2d, using mencoder. Prolly does not work on mac!
	"""


	size = 500,500
	
	fig = ml.figure(size= size, bgcolor=(1.,1.,1.));

	#fig.scene.anti_aliasing_frames=07

	#extent = [0,Nx-1,0,Ny-1,-30,30]
	xaxis = np.linspace(0,1,d_nodes[0]+1)
	yaxis = np.linspace(0,1,d_nodes[1]+1)
	ml.clf(figure=fig)
	u = np.load('solution_%06d.npy'%1);
	u = numpyfy(u, mesh, d_nodes, map)
	fname = '_tmp%07d.png' % 1
	s = ml.imshow(xaxis, yaxis, u,figure=fig,vmin=vmin, vmax=vmax)
	#scale = 1./np.max(np.abs(u))
	u = u
	ml.axes(extent=[0,1,0,1,0,2])
	ml.colorbar()
	ml.xlabel('x position')
	ml.ylabel('y position')
	ml.zlabel('wave amplitude')

	if savemovie == True:
		pl.ion()
		arr = ml.screenshot()
		img = pl.imshow(arr)
		pl.axis('off')
	
	for i in range(2,frames):

		u = np.load('solution_%06d.npy'%i);
		u = numpyfy(u, mesh, d_nodes, map)
		s.mlab_source.scalars = u
		fname = '_tmp%07d.png' % i
		if savemovie == True:
			arr = ml.screenshot()
			img.set_array(arr)
			pl.savefig(filename=fname)#,figure=fig)
			print 'Saving frame', fname
			pl.draw()

	fig.scene.disable_render = False
	if savemovie:
		os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
 def test_colorbar(self):
     """ Test that when an object with scalars hidden is created, it
         does not get a colorbar, unless no other is avalaible.
     """
     a = np.random.random((5, 5))
     s1 = mlab.surf(a, colormap='gist_earth')
     s2 = mlab.surf(a, color=(0, 0, 0))
     mlab.colorbar()
     self.assertEqual(
         s2.module_manager.scalar_lut_manager.show_scalar_bar, False
     )
     self.assertEqual(
         s1.module_manager.scalar_lut_manager.show_scalar_bar, True
     )
Exemple #50
0
def plot_cartesian(traj, xaxis=None, yaxis=None, zaxis=None, color='b',label='_nolegend_',
                   linewidth=2, scatter_size=10, plot_velocity=False):
    import matplotlib_util.util as mpu
    import arm_trajectories as at
    #if traj.__class__ == at.JointTrajectory:
    if isinstance(traj,at.JointTrajectory):
        traj = joint_to_cartesian(traj)

    pts = np.matrix(traj.p_list).T
    label_list = ['X coord (m)', 'Y coord (m)', 'Z coord (m)']
    x = pts[xaxis,:].A1.tolist()
    y = pts[yaxis,:].A1.tolist()

    if plot_velocity:
        vels = np.matrix(traj.v_list).T
        xvel = vels[xaxis,:].A1.tolist()
        yvel = vels[yaxis,:].A1.tolist()

    if zaxis == None:
        mpu.plot_yx(y, x, color, linewidth, '-', scatter_size, label,
                    axis = 'equal', xlabel = label_list[xaxis],
                    ylabel = label_list[yaxis],)
        if plot_velocity:
            mpu.plot_quiver_yxv(y, x, np.matrix([xvel,yvel]),
                                width = 0.001, scale = 1.)
        mpu.legend()
    else:
        from numpy import array
        from enthought.mayavi.api import Engine
        engine = Engine()
        engine.start()
        if len(engine.scenes) == 0:
            engine.new_scene()

        z = pts[zaxis,:].A1.tolist()
        time_list = [t-traj.time_list[0] for t in traj.time_list]
        mlab.plot3d(x,y,z,time_list,tube_radius=None,line_width=4)
        mlab.axes()
        mlab.xlabel(label_list[xaxis])
        mlab.ylabel(label_list[yaxis])
        mlab.zlabel(label_list[zaxis])
        mlab.colorbar(title='Time')

        # ------------------------------------------- 
        axes = engine.scenes[0].children[0].children[0].children[1]
        axes.axes.position = array([ 0.,  0.])
        axes.axes.label_format = '%-#6.2g'
        axes.title_text_property.font_size=4
Exemple #51
0
    def show_variable_timecourse(self, var, time_point, start_value, end_value):
        """Show an animation of all the section that have 
        the recorded variable among time"""

        # Getting the new scalar
        new_scalar = self.get_var_data(var, time_point)

        d = self.dataset.point_data.get_array("diameter")
        if len(d) != len(new_scalar):
            message = (
                "ERROR! MISMATCH on the Vector Length. \
            If you assign the new vectors it will not work \
            Diameter length: %s New Scalar length: %s var: %s"
                % (len(d), len(new_scalar), var)
            )
            logger.error(message)
        # ReEnable the rendering
        self.mayavi.visualization.scene.disable_render = True

        self.redraw_color(new_scalar, var)

        if not self.colorbar:
            self.colorbar = mlab.colorbar(orientation="vertical")
            self.timelabel = mlab.text(0.05, 0.05, str(time_point), width=0.05)

        self.colorbar.data_range = [start_value, end_value]
        time = self.manager.groups["t"][time_point]
        self.timelabel.text = str(round(time, 3))

        self.mayavi.visualization.scene.disable_render = False
Exemple #52
0
 def showWeightedNormals(s,theta=30.0,figm=None,algo='sobel'):
   # according to http://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6375037
   # weighting is 1.0/\sigma_z
   s.sigma_z = 0.0012 + 0.019*(s.d*0.001-0.4)**2
   ang = theta/180.0*np.pi
   s.sigma_l_px = 0.8 + 0.035*ang/(np.pi/2.0-ang)
   s.sigma_l = s.sigma_l_px * s.d*0.001/s.f_d
   s.w = 1.0/(s.sigma_z**2+2*s.sigma_l**2)
   s.getNormals(algo)
   if figm is None:
     figm = mlab.figure(bgcolor=(0,0,0)) 
   mlab.points3d(s.n[s.mask,0],s.n[s.mask,1],s.n[s.mask,2],s.w[s.mask],
       scale_factor=0.01, figure=figm, mode='point',mask_points=1)
   mlab.colorbar(orientation='vertical')
   
   return figm
Exemple #53
0
    def draw_facets(self, test=None, u=None):
        """Draw all facets."""
        if test is not None:
            xs = 1./3.*(self.p[0, self.facets[0, :]] +
                        self.p[0, self.facets[1, :]] +
                        self.p[0, self.facets[2, :]])
            ys = 1./3.*(self.p[1, self.facets[0, :]] +
                        self.p[1, self.facets[1, :]] +
                        self.p[1, self.facets[2, :]])
            zs = 1./3.*(self.p[2, self.facets[0, :]] +
                        self.p[2, self.facets[1, :]] +
                        self.p[2, self.facets[2, :]])
            fset = np.nonzero(test(xs, ys, zs))[0]
        else:
            fset = range(self.facets.shape[1])

        # use mayavi
        if OPT_MAYAVI:
            if u is None:
                mlab.triangular_mesh(self.p[0, :], self.p[1, :], self.p[2, :],
                                     self.facets[:, fset].T)
                mlab.triangular_mesh(self.p[0, :], self.p[1, :], self.p[2, :],
                                     self.facets[:, fset].T,
                                     representation='wireframe',
                                     color=(0, 0, 0))
            else:
                if u.shape[0] == self.facets.shape[1]:
                    newp = np.vstack((self.p[0, self.facets].flatten(order='F'),
                                      self.p[1, self.facets].flatten(order='F')))
                    newp = np.vstack((newp,
                                      self.p[2, self.facets].flatten(order='F')))
                    newt = np.arange(newp.shape[1]).reshape((3, newp.shape[1]/3),
                                                            order='F')
                    newu = np.tile(u, (3, 1)).flatten(order='F')
                    mlab.triangular_mesh(newp[0, :], newp[1, :], newp[2, :],
                                         newt.T, scalars=newu)
                    mlab.triangular_mesh(newp[0, :], newp[1, :], newp[2, :],
                                         newt.T, representation='wireframe',
                                         color=(0, 0, 0))
                    mlab.axes()
                    mlab.colorbar()
                else:
                    raise Exception("Given data vector "
                                    "shape not supported")
        else:
            raise ImportError("Mayavi not supported "
                              "by the host system!")
Exemple #54
0
def colorbar(*args, **kwargs):
    """Wraps mayavi.mlab.colorbar and adjusts cmap if you so choose"""
    cmap = kwargs.pop("cmap", False)
    kwargs, cmap_kwargs = _extract_cmap_kwargs(kwargs)
    cmap_kwargs.pop("cmap")
    ret = mlab.colorbar(*args, **kwargs)
    apply_cmap(ret, cmap=cmap, **cmap_kwargs)
    return ret
 def plot_u(u, x, xv, y, yv, t, n):
     print " ploting"
     if t[n] == 0:
         time.sleep(2)
     if plot_method == 1:
         mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
              caxis=[-1,1])
     elif plot_method == 2:
         surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
               colorbar=True, colormap=hot(), caxis=[-1,1],
               shading='flat')
     elif plot_method == 3:
         # mayavi plotting
         mlab.clf()
         extent1 = (0, 20, 0, 20,-2, 2)
         s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,
                      extent=extent1)
         mlab.axes(s, color=(.7, .7, .7), extent=extent1,
         ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
         zlabel='',
         x_axis_visibility=False, z_axis_visibility=False)
         mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
         mlab.text(2, -2.5, '', z=-4, width=0.1)
         mlab.colorbar(object=None, title=None, orientation='horizontal',
                       nb_labels=None, nb_colors=None, label_fmt=None)
         mlab.title('t=%g' % t[n])
         mlab.view(142, -72, 50)
         f = mlab.gcf()
         camera = f.scene.camera
         camera.yaw(0)
         #g = mlab.figure()
         #g.scene.movie_maker.record = True
         
     
     if plot_method > 0:
         if not os.path.exists(path):
             os.makedirs(path)
         time.sleep(0) # pause between frames
         if save_plot and plot_method == 3:
             filename = '%s/%08d.png'%(path,n)
             mlab.savefig(filename)  # time consuming!
         elif save_plot and plot_method != 3:
             filename = '%s/%08d.png'%(path,n)
             savefig(filename)  # time consuming!
Exemple #56
0
def test_colormap(cmap):
  from mayavi import mlab
  x,y=meshgrid(linspace(0,100,101),linspace(0,100,101))
  z=(x+y)*0.5
  if True:
      mesh_water=mlab.mesh(x.transpose(),y.transpose(),z.transpose(),colormap='gist_earth',vmin=0.,vmax=100.)
      #Retrieve the LUT of the surf object.
      lut = mesh_water.module_manager.scalar_lut_manager.lut.table.to_array()
      lut[:, 0] = cmap[0]
      lut[:, 1] = cmap[1]
      lut[:, 2] = cmap[2]
      mesh_water.module_manager.scalar_lut_manager.lut.table = lut
      mlab.draw()
      mlab.view(50.495536875966657,
 26.902697031665959,
 334.60652149512265,
 array([ 50.,  50.,  50.]))

      mlab.colorbar()
Exemple #57
0
    def action(u, x, xv, y, yv, t, n):
        #print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y
        if t[n] == 0:
            time.sleep(2)
        if plot_u == 1:
            mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                 caxis=[-1,1])
        elif plot_u == 2:
            surf(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                 colorbar=True, colormap=hot(), caxis=[-1,1])

        elif plot_u == 3:
            # mayavi plotting
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
            ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
            zlabel='',
            x_axis_visibility=False, z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(2, -2.5, '', z=-4, width=0.1)
            mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])

            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)



        
        if plot_u > 0:
            path = 'Figures_wave2D'
            if not os.path.exists(path):
                os.makedirs(path)
            time.sleep(0) # pause between frames
            if save_plot and plot_u != 3:
                filename = '%s/tmp_%08d.png' % (path, n)
            elif save_plot and plot_u == 3:
                filename = '%s/tmp_%08d.png' % (path, n)
                mlab.savefig(filename)  # time consuming!
Exemple #58
0
def mcrtmv(frames, dt,Lx,Ly,Nx,Ny,savemovie=False, mvname='test'):
	x = np.linspace(0,Lx,Nx);
	y = np.linspace(0,Lx,Nx);
	X,Y = np.meshgrid(x,y);
	size = 500,500
	
	fig = ml.figure(size= size, bgcolor=(1.,1.,1.));

	#fig.scene.anti_aliasing_frames=07

	#extent = [0,Nx-1,0,Ny-1,-30,30]
	
	ml.clf(figure=fig)
	u = np.loadtxt('solution_%06d.txt'%1);
	fname = '_tmp%07d.png' % 1
	s = ml.surf(x,y,u,figure=fig,vmin=-1,vmax=1)
	ml.axes(extent=[0,Lx,0,Ly,-2,2])
	ml.colorbar()
	ml.xlabel('x position')
	ml.ylabel('y position')
	ml.zlabel('wave amplitude')
	if savemovie == True:
		pl.ion()
		arr = ml.screenshot()
		img = pl.imshow(arr)
		pl.axis('off')
	
	for i in range(2,frames):

		u = np.loadtxt('solution_%06d.txt'%i);
		s.mlab_source.scalars = u
		fname = '_tmp%07d.png' % i
		if savemovie == True:
			arr = ml.screenshot()
			img.set_array(arr)
			pl.savefig(filename=fname)#,figure=fig)
			print 'Saving frame', fname
			pl.draw()

	fig.scene.disable_render = False
	os.system("mencoder 'mf://_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg" % mvname);
Exemple #59
0
def make_figures(coor, fun, interp_results, error):
    # Figure of harmoinc function on sphere in fine cordinates
    # Points3d showing interpolation training points coloured to their value
    mlab.figure()
    vmax, vmin = np.max(fun.fine), np.min(fun.fine)
    mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z,
              scalars=fun.fine, vmax=vmax, vmin=vmin)
    mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse,
                  scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin)
    mlab.colorbar(title='Spherical Harmonic', orientation='vertical')
    # mlab.savefig('interppointssphere.png')

    # Figure showing results of rbf interpolation
    mlab.figure()
    mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z,
              scalars=interp_results, vmax=vmax, vmin=vmin)
    mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse,
                  scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin)
    mlab.colorbar(title='Interpolation', orientation='vertical')
    # mlab.savefig('interpsphere.png')

    mlab.figure()
    mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z,
              scalars=error.errors, vmax=error.max, vmin=-error.max)
    mlab.colorbar(title='Error', orientation='vertical')
    # mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, scalars, scale_factor=0.1, scale_mode='none',vmax=vmax, vmin=vmin)
    # mlab.savefig('interpsphere.png')

    mlab.show()
Exemple #60
0
def make_figures(coor, fun, interp_results, error):
    '''Produce MayaVi figures for interpolation results'''
    mlab.figure()
    vmax, vmin = np.max(fun.fine), np.min(fun.fine)
    mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z,
              scalars=fun.fine, vmax=vmax, vmin=vmin)
    mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse,
                  scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin)
    mlab.colorbar(title='Spherical Harmonic', orientation='vertical')
    mlab.savefig('Figures/poorfunctionsphere.png')

    # Figure showing results of rbf interpolation
    mlab.figure()
    mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z,
              scalars=interp_results, vmax=vmax, vmin=vmin)
    mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, fun.coarse,
                  scale_factor=0.1, scale_mode='none', vmax=vmax, vmin=vmin)
    mlab.colorbar(title='Interpolation', orientation='vertical')
    mlab.savefig('Figures/poorinterpsphere.png')

    mlab.figure()
    mlab.mesh(coor.fine.x, coor.fine.y, coor.fine.z,
              scalars=error.errors, vmax=error.max, vmin=-error.max)
    mlab.colorbar(title='Error', orientation='vertical')
    # mlab.points3d(coor.coarse.x, coor.coarse.y, coor.coarse.z, scalars, scale_factor=0.1, scale_mode='none',vmax=vmax, vmin=vmin)
    mlab.savefig('Figures/poorerrorsphere.png')

    mlab.show()