Example #1
0
def draw_volume(scalars):
    # filts out low data
    nmax = np.amax(scalars)
    nmin = np.amin(scalars)
    #nptp = nmax - nmin
    #lowBound = nmin + nptp*0
    #for i in np.nditer(scalars, op_flags=['readwrite']):
    #    if i<lowBound: i[...] = 0
        
    # Get the shape of axes
    shape = scalars.shape
    
    # draw
    fig = mlab.figure(bgcolor=(0,0,0), size=(800,800) )
    src = mlab.pipeline.scalar_field(scalars)
    src.update_image_data = True
    #src.spacing = [1, 1, 1]
    
    vol = mlab.pipeline.volume(src)
    
    change_volume_property(vol)
    #change_test(vol)
    
    #vol = mlab.pipeline.image_plane_widget(src,plane_orientation='z_axes', slice_index=shape[2]/2)
    ax = mlab.axes(nb_labels=5, ranges=(0,shape[0],0,shape[1],0,shape[2]))
    
    mlab.savefig("result.jpg")
    print "nmax =", nmax
    print "nmin =", nmin
    
    viewkeeper = mlab.view()
    print "View", mlab.view()
    draw_map(shape[0],shape[1])
    mlab.view(viewkeeper[0],viewkeeper[1],viewkeeper[2],viewkeeper[3])
Example #2
0
def setup():
    sc = mlab.figure(0)
    mlab.view(90., -90., 3.)
    mlab.roll(90.)
    arm = Arm()
    neuron = Neuron(arm)
    return neuron, arm
Example #3
0
def curvature_normalization(data_dir, subj, close=True):
    """Normalize the curvature map and plot contour over fsaverage."""
    surf_dir = op.join(data_dir, subj, "surf")
    snap_dir = op.join(data_dir, subj, "snapshots")
    for hemi in ["lh", "rh"]:

        cmd = ["mri_surf2surf",
               "--srcsubject", subj,
               "--trgsubject", "fsaverage",
               "--hemi", hemi,
               "--sval", op.join(surf_dir, "%s.curv" % hemi),
               "--tval", op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi)]

        sub.check_output(cmd)

        b = Brain("fsaverage", hemi, "inflated",
                  config_opts=dict(background="white",
                                   width=700, height=500))
        curv = nib.load(op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi))
        curv = (curv.get_data() > 0).squeeze()
        b.add_contour_overlay(curv, min=0, max=1.5, n_contours=2, line_width=4)
        b.contour["colorbar"].visible = False
        for view in ["lat", "med"]:
            b.show_view(view)
            mlab.view(distance=330)
            png = op.join(snap_dir, "%s.surf_warp_%s.png" % (hemi, view))
            b.save_image(png)

        if close:
            b.close()
Example #4
0
    def __view(self, viewargs=None, roll=None):
        """Wrapper for mlab.view()

        Parameters
        ----------
        viewargs: dict
            mapping with keys corresponding to mlab.view args
        roll: num
            int or float to set camera roll

        Returns
        -------
        camera settings: tuple
            view settings, roll setting

        """
        try:
            from mayavi import mlab
        except ImportError:
            from enthought.mayavi import mlab

        if viewargs:
            viewargs['reset_roll'] = True
            mlab.view(**viewargs)
        if not roll is None:
            mlab.roll(roll)
        return mlab.view(), mlab.roll()
Example #5
0
def savefig(filename,mlabview=[],magnification = 3):
    """
    Save mayavi figure

    Parameters
    ----------

    name : str
        name of the figure
    mlabview : [] | (x,y,z, np.array([ xroll,yroll,zroll]))
        specifyy angle of camera view ( see mayavi.view )
    magnification : int
        resolution of the generated image ( see mayavi.savefig)

    """
    import os


    path = os.path.dirname(filename)
    if not mlabview == []:
        mlab.view(mlabview)
    if os.path.exists(path):
        mlab.savefig(filename+'.png',magnification=magnification )
    else:
        os.mkdir(path)
        mlab.savefig(filename+'.png',magnification=magnification )
    mlab.close()
def view():
    from mayavi.modules.glyph import Glyph
    from simphony_mayavi.sources.api import EngineSource
    from mayavi import mlab

    # Define EngineSource, choose dataset
    src = EngineSource(engine=engine_wrapper,
                       dataset="particles")

    # choose the CUBA attribute for display
    src.point_scalars_name = "TEMPERATURE"

    mayavi.add_source(src)

    # customise the visualisation
    g = Glyph()
    gs = g.glyph.glyph_source
    gs.glyph_source = gs.glyph_dict['sphere_source']
    g.glyph.glyph.scale_factor = 0.2
    g.glyph.scale_mode = 'data_scaling_off'
    mayavi.add_module(g)

    # add legend
    module_manager = src.children[0]
    module_manager.scalar_lut_manager.show_scalar_bar = True
    module_manager.scalar_lut_manager.show_legend = True

    # set camera
    mlab.view(-65., 60., 14., [1.5, 2., 2.5])
Example #7
0
def test_surface_normals(plot=False, skip_asserts=False,
                         write_reference=False):
    "Test the surface normals of a horseshoe mesh"
    sim = openmodes.Simulation()
    mesh = sim.load_mesh(osp.join(mesh_dir, 'horseshoe_rect.msh'))
    part = sim.place_part(mesh)
    basis = sim.basis_container[part]

    r, rho = basis.integration_points(mesh.nodes, triangle_centres)
    normals = mesh.surface_normals
    r = r.reshape((-1, 3))

    if write_reference:
        write_2d_real(osp.join(reference_dir, 'surface_r.txt'), r)
        write_2d_real(osp.join(reference_dir, 'surface_normals.txt'), normals)

    r_ref = read_2d_real(osp.join(reference_dir, 'surface_r.txt'))
    normals_ref = read_2d_real(osp.join(reference_dir, 'surface_normals.txt'))

    if not skip_asserts:
        assert_allclose(r, r_ref)
        assert_allclose(normals, normals_ref)

    if plot:
        from mayavi import mlab
        mlab.figure()
        mlab.quiver3d(r[:, 0], r[:, 1], r[:, 2],
                      normals[:, 0], normals[:, 1], normals[:, 2],
                      mode='cone')
        mlab.view(distance='auto')
        mlab.show()
Example #8
0
def mark_gt_box3d( lidar_dir, gt_boxes3d_dir, mark_dir):

    os.makedirs(mark_dir, exist_ok=True)
    fig   = mlab.figure(figure=None, bgcolor=(0,0,0), fgcolor=None, engine=None, size=(500, 500))
    dummy = np.zeros((10,10,3),dtype=np.uint8)

    for file in sorted(glob.glob(lidar_dir + '/*.npy')):
        name = os.path.basename(file).replace('.npy','')

        lidar_file   = lidar_dir     +'/'+name+'.npy'
        boxes3d_file = gt_boxes3d_dir+'/'+name+'.npy'
        lidar   = np.load(lidar_file)
        boxes3d = np.load(boxes3d_file)

        mlab.clf(fig)
        draw_didi_lidar(fig, lidar, is_grid=1, is_axis=1)
        if len(boxes3d)!=0:
            draw_didi_boxes3d(fig, boxes3d)

        azimuth,elevation,distance,focalpoint = MM_PER_VIEW1
        mlab.view(azimuth,elevation,distance,focalpoint)
        mlab.show(1)
        imshow('dummy',dummy)
        cv2.waitKey(1)

        mlab.savefig(mark_dir+'/'+name+'.png',figure=fig)
Example #9
0
File: cfm.py Project: gely/coseis
 def on_key_press(obj, event, save=[0]):
     k = obj.GetKeyCode()
     isurf = save[0]
     fig.scene.disable_render = True
     if k in '[]{}':
         c, s, p = surfs[isurf]
         if p.color == color_bg:
             p.color = color_hl
         else:
             p.color = color_bg
             d = {'[': -1, ']': 1, '{': -1, '}': 1}[k]
             isurf = (isurf + d) % len(surfs)
             c, s, p = surfs[isurf]
             p.color = color_hl
         print('\n' + '\n'.join(s))
         if k in '{}':
             mlab.view(focalpoint=c)
     elif k == '\\':
         surfs[isurf][-1].color = color_bg
     elif k == '0':
         mlab.view(view_azimuth, view_elevation)
         fig.scene.camera.view_angle = view_angle
     elif k in '/?h':
         print(doc)
     fig.scene.disable_render = False
     save[0] = isurf
     return
Example #10
0
    def reset_view(self):
        center = self.shape * self.spacing / 2. + (self.shape + 1) % 2 * self.spacing / 2.
        width = (self.shape * self.spacing)[:2]
        width = np.min(width) * 0.5

        self.scene.scene.background = (0, 0, 0)
        mlab.view(*([(0, 0), (90, 0), (0, 0)][self.axis]),
                  focalpoint=center,
                  figure=self.scene.mayavi_scene)
        self.scene.scene.parallel_projection = True
        self.scene.scene.camera.parallel_scale = width * 1.2
        self.scene.scene.interactor.interactor_style = tvtk.InteractorStyleImage()

        try: #WX window
            self.scene.scene_editor.control.SetFocusFromKbd
            def focusfunc(vtkobj, i):
                self.scene.scene_editor.control.SetFocusFromKbd()
        except AttributeError: #QT window
            self.scene.scene_editor.control.setFocus
            def focusfunc(vtkobj, i):
                self.scene.scene_editor.control.setFocus()

        self.scene.interactor.add_observer("MouseMoveEvent", focusfunc)
        self.scene.interactor.add_observer("KeyReleaseEvent", self.handle_keys)
        self._outline_color_changed()
    def setUp(self):
        # set up source
        sgrid = datasets.generateStructuredGrid()
        source = VTKDataSource(data=sgrid)

        self.engine = mlab.get_engine()

        # set up scene, first scene is empty
        # second scene has the settings we want to restore
        for _ in range(2):
            fig = mlab.figure()
            fig.scene.off_screen_rendering = True

        # add source
        self.engine.add_source(source)

        # add more modules
        self.engine.add_module(IsoSurface())
        self.engine.add_module(Text3D())
        self.modules = source.children[0].children

        # set camera
        self.view = (25., 14., 20., [0., 0., 2.5])
        mlab.view(*self.view)

        # save the visualisation
        self.temp_dir = tempfile.mkdtemp()
        self.filename = os.path.join(self.temp_dir, "test_vis.mv2")
        self.engine.save_visualization(self.filename)

        # save the scene as an image for comparison later
        self.ref_saved_filename = os.path.join(self.temp_dir, "ref_saved.png")
        mlab.savefig(self.ref_saved_filename)
Example #12
0
 def plot_text(self, label, X, text, size=1):
     view = mlab.view()
     roll = mlab.roll()
     self.figure.scene.disable_render = True
     
     scale = (size, size, size)
     mlab_objs = self.plots.get(label)
     
     if mlab_objs != None:
         if len(mlab_objs) != len(text):
             for obj in mlab_objs:
                 obj.remove()
         self.plots.pop(label)
     
     mlab_objs = self.plots.get(label)
     if mlab_objs == None:
         text_objs = []
         for x, t in zip(X, text):
             text_objs.append(mlab.text3d(x[0], x[1], x[2], str(t), scale=scale))
         self.plots[label] = text_objs
     elif len(mlab_objs) == len(text):
         for i, obj in enumerate(mlab_objs):
             obj.position = X[i,:]
             obj.text = str(text[i])
             obj.scale = scale
     else:
         print "HELP, I shouldn\'t be here!!!!!"
     
     self.figure.scene.disable_render = False
     mlab.view(*view)
     mlab.roll(roll)
def view():
    from mayavi import mlab
    from mayavi.modules.glyph import Glyph
    from simphony_mayavi.sources.api import CUDSFileSource

    mayavi.new_scene()

    # Mayavi Source
    src = CUDSFileSource()
    src.initialize('lattices.cuds')

    # choose a dataset for display
    src.dataset = 'orthorhombic'

    mayavi.add_source(src)

    # customise the visualisation
    g = Glyph()
    gs = g.glyph.glyph_source
    gs.glyph_source = gs.glyph_dict['sphere_source']
    g.glyph.glyph.scale_factor = 0.05
    g.glyph.scale_mode = 'data_scaling_off'
    mayavi.add_module(g)

    # add legend
    module_manager = src.children[0]
    module_manager.scalar_lut_manager.show_scalar_bar = True
    module_manager.scalar_lut_manager.show_legend = True

    # customise the camera
    mlab.view(63., 38., 3., [5., 4., 0.])
Example #14
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!
Example #15
0
    def plot_points(self, label, X, color=None, size=None, mode=None):

        mlab.figure(self.figure.name)

        if color == None:
            color = (1, 0, 0)

        if size == None and mode == None or size == 0:
            size = 1
            mode = "point"
        if size == None:
            size = 1
        if mode == None:
            mode = "sphere"

        if isinstance(X, list):
            X = scipy.array(X)

        if len(X.shape) == 1:
            X = scipy.array([X])

        mlab_obj = self.plots.get(label)
        if mlab_obj == None:
            if isinstance(color, tuple):
                self.plots[label] = mlab.points3d(X[:, 0], X[:, 1], X[:, 2], color=color, scale_factor=size, mode=mode)
            else:
                self.plots[label] = mlab.points3d(
                    X[:, 0], X[:, 1], X[:, 2], color, scale_factor=size, scale_mode="none", mode=mode
                )

        else:
            self.figure.scene.disable_render = True
            view = mlab.view()

            ### Commented out since VTK gives an error when using mlab_source.set
            # ~ if X.shape[0] == mlab_obj.mlab_source.x.shape[0]:
            # ~ if isinstance(color, tuple):
            # ~ mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2])
            # ~ mlab_obj.actor.property.color = color
            # ~ else:
            # ~ mlab_obj.mlab_source.set(x=X[:,0], y=X[:,1], z=X[:,2], scalars=color)
            # ~
            # ~
            # ~ else:
            # ~ self.clear(label)
            # ~ if isinstance(color, tuple):
            # ~ self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color=color, scale_factor=size, mode=mode)
            # ~ else:
            # ~ self.plots[label] = mlab.points3d(X[:,0], X[:,1], X[:,2], color, scale_factor=size, scale_mode='none', mode=mode)

            self.clear(label)
            if isinstance(color, tuple):
                self.plots[label] = mlab.points3d(X[:, 0], X[:, 1], X[:, 2], color=color, scale_factor=size, mode=mode)
            else:
                self.plots[label] = mlab.points3d(
                    X[:, 0], X[:, 1], X[:, 2], color, scale_factor=size, scale_mode="none", mode=mode
                )

            mlab.view(*view)
            self.figure.scene.disable_render = False
Example #16
0
 def anim():
   global bondcolors
   while True:
     print mlab.view(), mlab.roll()
     bondcolors[:] = bondcolors*.5
     bondsrc.update()
     yield
def plot_isosurface(crystal):
    filename = './output/potentialfield.txt'
    data = np.genfromtxt(filename, delimiter='\t')
    size = np.round((len(data))**(1/3))
    X = np.reshape(data[:,0], (size,size,size))
    Y = np.reshape(data[:,1], (size,size,size))
    Z = np.reshape(data[:,2], (size,size,size))
    DeltaU = np.reshape(data[:,3], (size,size,size))
    average = np.average(crystal.coordinates[:,0])
    start = average - crystal.a
    end = average + crystal.a
    coords1 = np.array([[start, start, start]])
    coords2 = np.array([[end, end, end]])
    array1 = np.repeat(coords1,len(crystal.coordinates),axis=0)
    array2 = np.repeat(coords2,len(crystal.coordinates),axis=0)
    basefilter1 = np.greater(crystal.coordinates,array1)
    basefilter2 = np.less(crystal.coordinates,array2)
    basefilter = np.nonzero(np.all(basefilter1*basefilter2, axis=1))
    base = crystal.coordinates[basefilter]   

    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(1, 1, 1), size=(2048,2048))
    dataset = mlab.contour3d(X, Y, Z, DeltaU, contours=[3.50],color=(1,0.25,0))
    scatter = mlab.points3d(base[:,0], 
                            base[:,1], 
                            base[:,2],
                            color=(0.255,0.647,0.88),
                            resolution=24, 
                            scale_factor=1.0, 
                            opacity=0.40)
    mlab.view(azimuth=17, elevation=90, distance=10, focalpoint=[average,average-0.2,average])
    mlab.draw()
    savename = './output/3Dpotential.png'
    mlab.savefig(savename, size=(2048,2048))
    mlab.show()
    def update_plot(self):
        """
        This function is called when the view is opened. We don't
        populate the scene when the view is not yet open, as some
        VTK features require a GLContext.
        """

        stream = file('universe.yaml', 'r')
        universe = yaml.load(stream)
        self.universe = universe

        self.universe.bind_to_scene(self.scene)

        self.universe.compile()

        # We can do normal mlab calls on the embedded scene.
        # self.scene.mlab.test_points3d()

        mlab.view(45, 45)
        mlab.view(azimuth=0, elevation=0, distance=30, focalpoint=(0, 0, 0))

        @mlab.animate(delay=50, ui=False)
        def animate():
            f = mlab.gcf()
            while 1:
                self.universe.next_step()
                f.scene.render()
                yield

        self.a = animate() # Starts the animation.
Example #19
0
def main(argv):
    if ( len(argv) != 1 ):
        print ("Usage: python visualizeField.py <datafile.json>")
        return

    # Read input file
    try:
        infile = open( argv[0], 'r' )
    except:
        print ("Error when opening file %s"%(argv[0]))
        return
    data = json.load( infile )
    infile.close()

    y = np.array( data["points"]["y"] )
    z = np.array( data["points"]["z"] )
    x = np.zeros( len(y) )
    Ex = np.array( data["field"]["x"] )
    pts = mlab.points3d( y, z, x, Ex, scale_mode="scalar", scale_factor=0.0, mode="point")
    mesh = mlab.pipeline.delaunay2d( pts )
    surf = mlab.pipeline.surface( mesh )
    
    fname = "Figures/fieldyzPlane.png"
    mlab.view(0.0,0.0,1.0, (0.0,0.0,0.0))
    mlab.scalarbar()
    mlab.xlabel( "y" )
    mlab.ylabel( "z" )
    mlab.show()
Example #20
0
	def _plotbutton1_fired(self):
		mlab.clf()
		self.loaddata()
		self.sregion[np.where(self.sregion<self.datamin)] = self.datamin
		self.sregion[np.where(self.sregion>self.datamax)] = self.datamax

		# The following codes from: http://docs.enthought.com/mayavi/mayavi/auto/example_atomic_orbital.html#example-atomic-orbital
		field = mlab.pipeline.scalar_field(self.sregion)     # Generate a scalar field
		colored = self.sregion
		vol=self.sregion.shape
		for v in range(0,vol[2]-1):
			colored[:,:,v] = self.extent[4] + v*(-1)*abs(self.hdr['cdelt3'])
		new = field.image_data.point_data.add_array(colored.T.ravel())
		field.image_data.point_data.get_array(new).name = 'color'
		field.image_data.point_data.update()

		field2 = mlab.pipeline.set_active_attribute(field, point_scalars='scalar')
		contour = mlab.pipeline.contour(field2)
		contour2 = mlab.pipeline.set_active_attribute(contour, point_scalars='color')

		mlab.pipeline.surface(contour2, colormap='jet', opacity=self.opacity)
		
		## Insert a continuum plot
		##im = pyfits.open('g28_SMA1.cont.image.fits')
		##dat = im[0].data
		##dat0 = dat[0]
		##channel = dat0[0]
		##region = np.swapaxes(channel[self.xstart:self.xend,self.ystart:self.yend]*1000.,0,1)
		##field = mlab.contour3d(region, colormap='gist_ncar')
		##field.contour.minimum_contour = 5

		self.field = field
		self.labels()
		mlab.view(azimuth=0, elevation=0, distance='auto')
		mlab.show()
Example #21
0
 def __init__(self,start,end,maxd=5000.,n=100):
     '''
     Constructor
     '''
     self.start=start
     self.end=end
     self.lopath=numpy.linspace(start[0], end[0], n)
     self.lapath=numpy.linspace(start[1], end[1], n)
     self.set_proj()
     self.tile=TiffReader(lon=self.lopath[0],lat=self.lapath[0])
     self.tile.readit()
     for i in range(n):
             if not self.tile==TiffReader(lon=self.lopath[i],lat=self.lapath[i]):
                     self.tile=TiffReader(lon=self.lopath[i],lat=self.lapath[i])
                     self.tile.readit()
             if not hasattr(self,'mesh'):
                     lo,la,z=self.tile.subset(rect=None, around=(self.lopath[i],self.lapath[i],maxd))
                     x,y=self.proj(lo,la)
                     x=x-x.mean()
                     y=y-y.mean()
                     self.mesh=mlab.mesh(x,y,z,scalars=z,vmax=1500.,vmin=0.)
                     mlab.view(180.,45.,maxd,numpy.array([x.max(),0,z.max()]))
             else:
                     lo,la,self.mesh.mlab_source.z=self.tile.subset(rect=None, around=(self.lopath[i],self.lapath[i],maxd))
                     self.mesh.mlab_source.scalars=self.mesh.mlab_source.z
                     mlab.view(180.,45.,5*x.max(),numpy.array([x.max(),0,self.mesh.mlab_source.z.max()]))
             mlab.draw()
Example #22
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
    def set_parallel_view(self, forward=None, up=None, scale=None):
        """Set view to parallel projection

        Parameters
        ----------
        forward : scalar
            Move the view forward (mm).
        up : scalar
            Move the view upward (mm).
        scale : scalar
            Mayavi parallel_scale parameter. Default is 95 for the inflated
            surface, 75 otherwise. Smaller numbers correspond to zooming in.
        """
        if scale is True:
            surf = self.geo['rh' if self._hemi == 'rh' else 'lh'].surf
            if surf == 'inflated':
                scale = 95
            else:
                scale = 75  # was 65 for WX backend

        from mayavi import mlab

        for figs in self._figures:
            for fig in figs:
                if forward is not None or up is not None:
                    mlab.view(focalpoint=(0, forward or 0, up or 0),
                              figure=fig)
                if scale is not None:
                    fig.scene.camera.parallel_scale = scale
                fig.scene.camera.parallel_projection = True
                fig.render()
Example #24
0
def fig_2d():
    
    ml.test_imshow()
    ml.view(0, 0)
    #fig = ml.gcf()

    #fig.scene.interactor.interactor_style = tvtk.InteractorStyleImage()
    ml.show()
Example #25
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!
Example #26
0
def makeRzAs(year=2014, plot=False, beamSubdivisionLength=1e-3, channels=range(60), withMSEvec=False,
    outputplot=False):
    '''generates MSE R, z, A coords for pi and sigma from a FARO measurement'''

    #year = 2015 if year == 2017 else year

    s0, s, row, column = getLOSfromSPRD(int(year))

    s1 = s0 + 2.2*s
    s0 = s0 + 1.0*s

    v0, v = getNBIgeo()
    v1 = v0 + v

    isecs = getApproxIntersections(s0, s1, v0, v1, beamSubdivisionLength)


    toplot = {}
    toplot['LOS'] = []

    if plot or outputplot:
        import kk_abock as kk
        try:
            if plot: from mayavi import mlab # needs intel/12.1!!!!
        except Exception, e:
            print 'mayavi failed to load, are you using intel/12.1?'
            raise e
        for i in xrange(60):
            ts0 = s0 - 1.5*s
            if plot: mlab.plot3d([ts0[i,0], s1[i,0]], [ts0[i,1], s1[i,1]], [ts0[i,2], s1[i,2]], tube_radius=None, color=(1,0,0))
            toplot['LOS'].append([[ts0[i,0], s1[i,0]], [ts0[i,1], s1[i,1]], [ts0[i,2], s1[i,2]]])

        if plot: mlab.points3d(isecs[:,0], isecs[:,1], isecs[:,2])
        if plot: mlab.plot3d([v0[0], v1[0]], [v0[1], v1[1]], [v0[2], v1[2]], color=(0,1,0))
        if plot: mlab.view(0, 0, distance=10, focalpoint=[0,0,0])

        toplot['isecs'] = [isecs[:,0], isecs[:,1], isecs[:,2]]
        toplot['beam'] = [[v0[0], v1[0]], [v0[1], v1[1]], [v0[2], v1[2]]]

        for R in [1.65]: #, 1.8, 1.95]: # axis
            x = R * cos(np.linspace(0,2*np.pi, 128))
            y = R * sin(np.linspace(0,2*np.pi, 128))
            if plot: mlab.plot3d(x,y,[0]*len(x), tube_radius=None)
            toplot['axis'] = [x,y,[0]*len(x)]

        eq = kk.kk()
        eq.Open(31113, 'AUGD', 'EQI')
        sepR, sepz = [], []
        for a in xrange(360):
            res = eq.rhopol_to_Rz(3.0, 0.99, a, True)
            sepR.append(res['R'])
            sepz.append(res['z'])
        sepR = np.array(sepR)
        sepz = np.array(sepz)
        # separatrix:
        phi = -0.37
        if plot: mlab.plot3d(np.cos(phi)*sepR, np.sin(phi)*sepR, sepz, tube_radius=None)
        toplot['sep'] = [np.cos(phi)*sepR, np.sin(phi)*sepR, sepz]
Example #27
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()
Example #28
0
 def show(self):
     """
     Display the Bloch sphere and corresponding data sets.
     """
     from mayavi import mlab
     self.make_sphere()
     mlab.view(azimuth=self.view[0], elevation=self.view[1], distance=5)
     if self.fig:
         mlab.show()
Example #29
0
def autoPositionCamera():
    """
    Set camera position looking along the x-axis.
    """
    s = mlab.gcf().scene
    s.disable_render = True
    mlab.view(90,90,distance='auto',focalpoint='auto')
    mlab.roll(0)
    s.disable_render = False
def plot_big(MH, MHexam, points_proj, points_projal, skel_projal, ViewP, proj_type, plot_type="normal", fnum=1):
  
    # Plotting
    print "Plot figure z-axis reversed (because z=0 is top of scan)"
    mlab.figure(fnum, bgcolor=(1,1,1), size=(800,800))
    mlab.clf()
    #airway plot    
    mlab.triangular_mesh(MH.vertices[:,0], MH.vertices[:,1], MH.vertices[:,2]*(-1), 
                         MH.faces, colormap='Blues', representation='wireframe', 
                         line_width=0.5)
    try:
        mlab.triangular_mesh(MHexam.vertices[:,0], MHexam.vertices[:,1], 
                             MHexam.vertices[:,2]*(-1), MHexam.faces,
                             colormap='Greens', representation='surface',
                             opacity=0.2)
    except:
        print "Example mesh not plotted"
    #airway axes
    #mlab.axes('off') #extent=([-200, 200, -200,200, 200,-200])) 
    #points on the airway
    mlab.points3d(MH.silvert1[:,0], MH.silvert1[:,1], MH.silvert1[:,2]*(-1), 
                  scale_factor=1, color=(0,0,0))
#    #projected points
    mlab.points3d(points_proj[:,0], points_proj[:,1], points_proj[:,2]*(-1), 
                  scale_factor=1, color=(0,0,0))  
    
    if plot_type is "normal":        
#    #alignment points
        mlab.points3d(MH.points[:,0], MH.points[:,1], MH.points[:,2]*(-1), 
                      scale_factor=2, color=(0,1,0))
        
        #skeleton
        mlab.points3d(MH.skel[:,0], MH.skel[:,1], MH.skel[:,2]*(-1), 
                      scale_factor=0.5, color=(0.5,0.5,1))
    #    #alignment points
        mlab.points3d(points_projal[:,0], points_projal[:,1], points_projal[:,2]*(-1), 
                      scale_factor=2, color=(0,1,0))
        
    try:
        mlab.points3d(skel_projal[:,0], skel_projal[:,1], skel_projal[:,2]*(-1), 
                      scale_factor=0.5, color=(0.5,0.5,1))
    except:
        print "skeleton not plotted"
    #view direction
    #if proj_type=="Lodox":
    #    ViewL=np.array([ViewP, ViewP])
    #    ViewL[0,2]=30; ViewL[1,2]=-30        
    #    
    #    mlab.plot3d(ViewL[:,0]/10, ViewL[:,1], ViewL[:,2]*(-1), 
    #                color=(0,0,0), 
    #                tube_radius=1, opacity=1)
    
    #elif proj_type=="normal":
    #    mlab.points3d(ViewP[0]/10, ViewP[1], ViewP[2]*(-1), 
    #                  scale_factor=4, color=(1,0,0))
    
    mlab.view(elevation=80,azimuth=20)
Example #31
0
    idx2_np, grouped_xyz2_np = sess.run([idx2, grouped_xyz2])
    grouped_xyz1_np = np.reshape(grouped_xyz1_np, [-1, 3])
    grouped_xyz2_np = np.reshape(grouped_xyz2_np, [-1, 3])

import mayavi.mlab as mlab

xyz1 = np.reshape(xyz1, [-1, 3])
xyz2 = np.reshape(xyz2, [-1, 3])
mlab.points3d(grouped_xyz1_np[:, 0],
              grouped_xyz1_np[:, 1],
              grouped_xyz1_np[:, 2],
              color=(1, 0, 0),
              scale_factor=0.01)
mlab.points3d(grouped_xyz2_np[:, 0],
              grouped_xyz2_np[:, 1],
              grouped_xyz2_np[:, 2],
              color=(0, 0, 1),
              scale_factor=0.01)
mlab.points3d(xyz1[:, 0],
              xyz1[:, 1],
              xyz1[:, 2],
              color=(1, 1, 1),
              scale_factor=0.008)
mlab.points3d(xyz2[:, 0],
              xyz2[:, 1],
              xyz2[:, 2],
              color=(1, 1, 1),
              scale_factor=0.008)
mlab.view()
input()
Example #32
0
    foreground='black',
    time_label='',
    initial_time=1,
    figure=[fig3, fig4],
)
brain2.scale_data_colormap(1e-23, 1.5e-23, 2.5e-23, True)

mlab.savefig('../paper/figures/power_scrambled_lh.png', figure=fig3, magnification=4)
mlab.savefig('../paper/figures/power_scrambled_rh.png', figure=fig4, magnification=4)

# Show difference in power between the two experimental conditions, relative to the baseline power
figs = []
for i, freq in enumerate(freq_bands):
    fig5 = mlab.figure(size=(300, 300))
    mlab.clf()
    #brain3 = stc_contrast.copy().crop(i, i).plot(
    brain3 = stc_contrast.plot(
        subject='sub002',
        hemi='both',
        background='white',
        foreground='black',
        time_label='',
        colormap='mne',
        initial_time=i,
        figure=fig5,
    )
    mlab.view(-90, 110, 420, [0, 0, 0], figure=fig5)
    figs.append(fig5)

    mlab.savefig('../paper/figures/power_contrast_%s-%s-occ.png' % (freq[0], freq[1]), figure=fig5, magnification=4)
tris = lh['tris']  # Groups of three vertices that form triangles
dip_pos = lh['rr'][lh['vertno']]  # The position of the dipoles
white = (1.0, 1.0, 1.0)  # RGB values for a white color
gray = (0.5, 0.5, 0.5)  # RGB values for a gray color
red = (1.0, 0.0, 0.0)  # RGB valued for a red color

mlab.figure(size=(600, 400), bgcolor=white)

# Plot the cortex
mlab.triangular_mesh(verts[:, 0], verts[:, 1], verts[:, 2], tris, color=gray)

# Mark the position of the dipoles with small red dots
mlab.points3d(dip_pos[:, 0], dip_pos[:, 1], dip_pos[:, 2], color=red,
              scale_factor=1E-3)

mlab.view(azimuth=180, distance=0.25)

###############################################################################
# .. _plot_dipole_orientations_fixed_orientations:
#
# Fixed dipole orientations
# -------------------------
# While the source space defines the position of the dipoles, the inverse
# operator defines the possible orientations of them. One of the options is to
# assign a fixed orientation. Since the neural currents from which MEG and EEG
# signals originate flows mostly perpendicular to the cortex [1]_, restricting
# the orientation of the dipoles accordingly places a useful restriction on the
# source estimate.
#
# By specifying ``fixed=True`` when calling
# :func:`mne.minimum_norm.make_inverse_operator`, the dipole orientations are
Example #34
0
###############################################################################
# Project 3D electrodes to a 2D snapshot
# --------------------------------------
#
# Because we have the 3D location of each electrode, we can use the
# :func:`mne.viz.snapshot_brain_montage` function to return a 2D image along
# with the electrode positions on that image. We use this in conjunction with
# :func:`mne.viz.plot_alignment`, which visualizes electrode positions.

fig = plot_alignment(info,
                     subject='sample',
                     subjects_dir=subjects_dir,
                     surfaces=['pial'],
                     meg=False)
mlab.view(200, 70)
xy, im = snapshot_brain_montage(fig, mon)

# Convert from a dictionary to array to plot
xy_pts = np.vstack([xy[ch] for ch in info['ch_names']])

# Define an arbitrary "activity" pattern for viz
activity = np.linspace(100, 200, xy_pts.shape[0])

# This allows us to use matplotlib to create arbitrary 2d scatterplots
fig2, ax = plt.subplots(figsize=(10, 10))
ax.imshow(im)
ax.scatter(*xy_pts.T, c=activity, s=200, cmap='coolwarm')
ax.set_axis_off()
# fig2.savefig('./brain.png', bbox_inches='tight')  # For ClickableImage
Example #35
0
def main(arg):
    """Main function of the script"""
    client = carla.Client(arg.host, arg.port)
    client.set_timeout(10.0)
    client.load_world('Town05')
    client.reload_world()
    world = client.get_world()
    data = np.genfromtxt('background.csv', delimiter=',')
    print('loading background data, size: {}'.format(data.shape))
    background_data = process_background(data)
    try:
        original_settings = world.get_settings()
        settings = world.get_settings()
        traffic_manager = client.get_trafficmanager(8000)
        traffic_manager.set_synchronous_mode(True)

        delta = 0.05

        settings.fixed_delta_seconds = delta
        settings.synchronous_mode = True
        settings.no_rendering_mode = arg.no_rendering
        world.apply_settings(settings)

        blueprint_library = world.get_blueprint_library()
        # vehicle_bp = blueprint_library.filter(arg.filter)[0]
        # vehicle_transform = random.choice(world.get_map().get_spawn_points())
        # vehicle = world.spawn_actor(vehicle_bp, vehicle_transform)
        # vehicle.set_autopilot(arg.no_autopilot)

        lidar_bp = generate_lidar_bp(arg, world, blueprint_library, delta)
        lidar_transform = carla.Transform(carla.Location(x=-65.0, y=3.0,
                                                         z=6.0))
        lidar = world.spawn_actor(lidar_bp, lidar_transform)

        fig = mlab.figure(size=(960, 540), bgcolor=(0.05, 0.05, 0.05))
        vis = mlab.points3d(0, 0, 0, 0, mode='point', figure=fig)
        mlab.view(distance=25)
        buf = {'pts': np.zeros((1, 3)), 'intensity': np.zeros(1)}

        #  @mlab.animate(delay=100)
        def anim():
            i = 0
            while True:
                vis.mlab_source.reset(x=buf['pts'][:, 0],
                                      y=buf['pts'][:, 1],
                                      z=buf['pts'][:, 2],
                                      scalars=buf['intensity'])
                mlab.savefig(f'{i%10}.png', figure=fig)
                time.sleep(0.1)
                i += 1

        if arg.semantic:
            lidar.listen(lambda data: semantic_lidar_callback(
                data, buf, background_data))
        else:
            lidar.listen(
                lambda data: lidar_callback(data, buf, background_data))

        loopThread = threading.Thread(target=carlaEventLoop,
                                      args=[world],
                                      daemon=True)
        loopThread.start()
        anim()
        #  mlab.show()

    finally:
        world.apply_settings(original_settings)
        traffic_manager.set_synchronous_mode(False)

        vehicle.destroy()
        lidar.destroy()
    mne.surface.complete_surface_info(surf, copy=False)
hsp = warp.transform(hsp)

###############################################################################
# Plot the transformed surfaces and digitization (blue) on template (black):

from mayavi import mlab  # noqa

t_color = (0.1, 0.3, 1)
fig = mlab.figure(size=(400, 600), bgcolor=(1., 1., 1.))
for surf, color in zip(fsaverage_surfs + sample_surfs,
                       [(0., 0., 0.)] * len(fsaverage_surfs) +
                       [t_color] * len(sample_surfs)):
    mesh = mlab.pipeline.triangular_mesh_source(*surf['rr'].T,
                                                triangles=surf['tris'])
    mesh.data.point_data.normals = surf['nn']
    mesh.data.cell_data.normals = None
    surf = mlab.pipeline.surface(mesh,
                                 figure=fig,
                                 reset_zoom=True,
                                 opacity=0.33,
                                 color=color)
    surf.actor.property.backface_culling = True
mlab.points3d(hsp[:, 0],
              hsp[:, 1],
              hsp[:, 2],
              color=t_color,
              scale_factor=0.005,
              opacity=0.25)
mlab.view(45, 90)
Example #37
0
    import urllib
    print 'Downloading data, please wait (10M)'
    opener = urllib.urlopen(
        'http://staging.enthought.com/projects/mayavi/N36W113.hgt.zip')
    open('N36W113.hgt.zip', 'wb').write(opener.read())

# Load the data (signed 2 byte integers, big endian) ##########################
import zipfile
import numpy as np

data = np.fromstring(
    zipfile.ZipFile('N36W113.hgt.zip').read('N36W113.hgt'), '>i2')
data.shape = (3601, 3601)
data = data.astype(np.float32)

# Plot an interesting section #################################################
from mayavi import mlab
data = data[:1000, 900:1900]
# Convert missing values into something more sensible.
data[data == -32768] = data[data > 0].min()

mlab.figure(size=(400, 320), bgcolor=(0.16, 0.28, 0.46))
mlab.surf(data, colormap='gist_earth', warp_scale=0.2, vmin=1200, vmax=1610)
# The data takes a lot of memory, and the surf command has created a
# copy. We free the inital memory.
del data

# A view of the canyon
mlab.view(-5.9, 83, 570, [5.3, 20, 238])
mlab.show()
mlab.plot3d([-200, 200], [0, 0], [0, 0], color=frame_c[0], **_args)
mlab.plot3d([0, 0], [-200, 200], [0, 0], color=frame_c[1],**_args)
mlab.plot3d([0, 0], [0, 0], [-75, 75], color=frame_c[2], **_args)

pts = mlab.points3d(pfe_Sc[i, 1:, 0], pfe_Sc[i, 1:, 1], pfe_Sc[i, 1:, 2],
                    color=(.85, .85, .85), scale_factor=10, resolution=64)

body = mlab.mesh(foils_Sc[i, :, :, 0],
                 foils_Sc[i, :, :, 1],
                 foils_Sc[i, :, :, 2],
                 scalars=foil_color[i],
                 colormap='YlGn', opacity=1,
                 vmin=0, vmax=1)

#YZ_mesh = mlab.mesh(YZ_S[i, :, :, 0], YZ_S[i, :, :, 1], YZ_S[i, :, :, 2],
#                    color=bmap[2], opacity=.25)
#XZ_mesh = mlab.mesh(XZ_S[i, :, :, 0], XZ_S[i, :, :, 1], XZ_S[i, :, :, 2],
#                    color=bmap[1], opacity=.25)
#XY_mesh = mlab.mesh(XY_S[i, :, :, 0], XY_S[i, :, :, 1], XY_S[i, :, :, 2],
#                    color=bmap[0], opacity=.25)

#mlab.orientation_axes()
fig.scene.isometric_view()

if False:
    mlab.view(azimuth=0, elevation=90, distance='auto')  # side view (y-z)
    mlab.view(azimuth=-90, elevation=90, distance='auto')  # back view (x-z)
    mlab.view(azimuth=-90, elevation=-90, distance='auto')  # front view (x-z)
    mlab.view(azimuth=0, elevation=0, distance='auto')  # top view (x-y)

Example #39
0
rmax = np.amax(rhof)
rmin = np.amin(rhof)

x = np.linspace(0., dsizex, ncel_pic, endpoint=False)
y = np.linspace(0., dsizey, ncel_pic, endpoint=False)
z = np.linspace(0., dsizez, ncel_pic, endpoint=False)

Y, X, Z = np.meshgrid(x, y, z)

## Generate 3D contour plot of final density with Mayavi ##
mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(1024, 768))
mlab.contour3d(X,
               Y,
               Z,
               rhof / np.mean(rhof),
               contours=32,
               opacity=.5,
               colormap='jet',
               vmax=np.amax(rhof) / np.mean(rhof),
               vmin=np.amin(rhof) / np.mean(rhof))
mlab.colorbar(orientation='vertical')
mlab.view(azimuth=30, elevation=60, distance='auto')
mlab.axes()
mlab.savefig('MayaviFrames/Cyclotron3D_nc' + str(ncx) + '_nppc' +
             str(N_per_sparse_cell) + '_final.png',
             size=(640, 480))

mlab.show()

plt.show()
def draw_lidar(pc,
               color=None,
               fig1=None,
               bgcolor=(0, 0, 0),
               pts_scale=1,
               pts_mode='point',
               pts_color=None):
    ''' Draw lidar points
    Args:
        pc: numpy array (n,3) of XYZ
        color: numpy array (n) of intensity or whatever
        fig: mayavi figure handler, if None create new one otherwise will use it
    Returns:
        fig: created or used fig
    '''
    # if fig1 is None: fig1 = mlab.figure(figure="point cloud", bgcolor=bgcolor, fgcolor=None, engine=None, size=(1600, 1000))

    mlab.clf(figure=None)
    if color is None: color = pc[:, 2]
    mlab.points3d(pc[:, 0],
                  pc[:, 1],
                  pc[:, 2],
                  color,
                  color=pts_color,
                  mode=pts_mode,
                  colormap='gnuplot',
                  scale_factor=pts_scale,
                  figure=fig1)

    # draw origin
    mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='sphere', scale_factor=0.2)

    # draw axis
    axes = np.array([
        [2., 0., 0., 0.],
        [0., 2., 0., 0.],
        [0., 0., 2., 0.],
    ],
                    dtype=np.float64)

    mlab.plot3d([0, axes[0, 0]], [0, axes[0, 1]], [0, axes[0, 2]],
                color=(1, 0, 0),
                tube_radius=None,
                figure=fig1)
    mlab.plot3d([0, axes[1, 0]], [0, axes[1, 1]], [0, axes[1, 2]],
                color=(0, 1, 0),
                tube_radius=None,
                figure=fig1)
    mlab.plot3d([0, axes[2, 0]], [0, axes[2, 1]], [0, axes[2, 2]],
                color=(0, 0, 1),
                tube_radius=None,
                figure=fig1)

    # draw fov (todo: update to real sensor spec.)
    fov = np.array(
        [  # 45 degree
            [20., 20., 0., 0.],
            [20., -20., 0., 0.],
        ],
        dtype=np.float64)

    mlab.plot3d([0, fov[0, 0]], [0, fov[0, 1]], [0, fov[0, 2]],
                color=(1, 1, 1),
                tube_radius=None,
                line_width=1,
                figure=fig1)
    mlab.plot3d([0, fov[1, 0]], [0, fov[1, 1]], [0, fov[1, 2]],
                color=(1, 1, 1),
                tube_radius=None,
                line_width=1,
                figure=fig1)

    # draw square region
    TOP_Y_MIN = -20
    TOP_Y_MAX = 20
    TOP_X_MIN = 0
    TOP_X_MAX = 40
    TOP_Z_MIN = -2.0
    TOP_Z_MAX = 0.4

    x1 = TOP_X_MIN
    x2 = TOP_X_MAX
    y1 = TOP_Y_MIN
    y2 = TOP_Y_MAX
    mlab.plot3d([x1, x1], [y1, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig1)
    mlab.plot3d([x2, x2], [y1, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig1)
    mlab.plot3d([x1, x2], [y1, y1], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig1)
    mlab.plot3d([x1, x2], [y2, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig1)

    # mlab.orientation_axes()
    mlab.view(azimuth=180,
              elevation=70,
              focalpoint=[12.0909996, -1.04700089, -2.03249991],
              distance=60.0,
              figure=fig1)
    return fig1
Example #41
0
                      1.6,
                      vecs[0, 0],
                      vecs[0, 1],
                      0,
                      line_width=3.,
                      scale_factor=2.,
                      scale_mode='vector',
                      color=(0, 1, 1))
        mlab.quiver3d(mu[0],
                      mu[1],
                      1.6,
                      vecs[1, 0],
                      vecs[1, 1],
                      0,
                      line_width=3.,
                      scale_factor=2.,
                      scale_mode='vector',
                      color=(0, 1, 1))

        box = dataset.calib.T_cam2_imu.dot(np.vstack((box.T, np.ones((1, 8)))))
        im = draw_class.draw_projected_box3d(im, box[:3].T,
                                             dataset.calib.P_rect_20, 0)

    config = (180, 10, 120, [30, 0, 0])
    mlab.view(*config)
    mlab.savefig('./output/detection/%s/%05d.png' % (args.name, idd),
                 magnification=4)
    cv2.imwrite('./output/detection/%s/%05d-cam.jpg' % (args.name, idd),
                im[:, :, ::-1] * 255)
    mlab.clf()
Example #42
0
            mlab.mesh(x + j * dx,
                      y,
                      z - i * dx,
                      scalars=om,
                      colormap=cmap,
                      vmax=0.3 * om_max,
                      vmin=-0.3 * om_max)
        else:
            mlab.mesh(x + j * dx,
                      y,
                      z - i * dx,
                      scalars=om,
                      colormap=cmap,
                      vmax=0.6 * om_max,
                      vmin=-0.6 * om_max)

#plot the spherical harmonics
for j, ell in enumerate([6, 11, 21]):
    s = sph_harm(0, ell, thth, phiphi).real
    mlab.mesh(x + 3 * dx,
              y,
              z - j * dx,
              scalars=s,
              colormap=cmap,
              vmax=0.4,
              vmin=-.4)

mlab.view(-90, 90, distance=4)
#mlab.savefig("%s/fig1_headon.pdf" %(output_folder), magnification=1)
mlab.show()
Example #43
0
def draw_lidar(pc,
               color=None,
               fig=None,
               bgcolor=(0, 0, 0),
               pts_scale=1,
               pts_mode='point',
               pts_color=None):
    """
     Draw lidar points
    :param pc: numpy array (n,3) of XYZ
    :param color: numpy array (n) of intensity or whatever
    :param fig: mayavi figure handler, if None create new one otherwise will use it
    :param bgcolor:
    :param pts_scale:
    :param pts_mode:
    :param pts_color:
    :return: created or used fig
    """

    if "mlab" not in sys.modules:
        try:
            import mayavi.mlab as mlab
        except BaseException:
            print("mlab module should be installed")
            return

    if fig is None:
        fig = mlab.figure(figure=None,
                          bgcolor=bgcolor,
                          fgcolor=None,
                          engine=None,
                          size=(1600, 1000))
    if color is None:
        color = pc[:, 2]
    mlab.points3d(pc[:, 0],
                  pc[:, 1],
                  pc[:, 2],
                  color,
                  color=pts_color,
                  mode=pts_mode,
                  colormap='gnuplot',
                  scale_factor=pts_scale,
                  figure=fig)

    # draw origin
    mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='sphere', scale_factor=0.2)

    # draw axis
    axes = np.array([
        [2., 0., 0., 0.],
        [0., 2., 0., 0.],
        [0., 0., 2., 0.],
    ],
                    dtype=np.float64)
    mlab.plot3d([0, axes[0, 0]], [0, axes[0, 1]], [0, axes[0, 2]],
                color=(1, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[1, 0]], [0, axes[1, 1]], [0, axes[1, 2]],
                color=(0, 1, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[2, 0]], [0, axes[2, 1]], [0, axes[2, 2]],
                color=(0, 0, 1),
                tube_radius=None,
                figure=fig)

    # draw fov Todo: update to real sensor spec.
    fov = np.array(
        [  # 45 degree
            [20., 20., 0., 0.],
            [20., -20., 0., 0.],
        ],
        dtype=np.float64)

    mlab.plot3d([0, fov[0, 0]], [0, fov[0, 1]], [0, fov[0, 2]],
                color=(1, 1, 1),
                tube_radius=None,
                line_width=1,
                figure=fig)
    mlab.plot3d([0, fov[1, 0]], [0, fov[1, 1]], [0, fov[1, 2]],
                color=(1, 1, 1),
                tube_radius=None,
                line_width=1,
                figure=fig)

    # draw square region
    TOP_Y_MIN = -20
    TOP_Y_MAX = 20
    TOP_X_MIN = 0
    TOP_X_MAX = 40
    TOP_Z_MIN = -2.0
    TOP_Z_MAX = 0.4

    x1 = TOP_X_MIN
    x2 = TOP_X_MAX
    y1 = TOP_Y_MIN
    y2 = TOP_Y_MAX
    mlab.plot3d([x1, x1], [y1, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)
    mlab.plot3d([x2, x2], [y1, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)
    mlab.plot3d([x1, x2], [y1, y1], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)
    mlab.plot3d([x1, x2], [y2, y2], [0, 0],
                color=(0.5, 0.5, 0.5),
                tube_radius=0.1,
                line_width=1,
                figure=fig)

    # mlab.orientation_axes()
    mlab.view(azimuth=180,
              elevation=70,
              focalpoint=[12.0909996, -1.04700089, -2.03249991],
              distance=62.0,
              figure=fig)

    return fig
Example #44
0
    if nx.__version__ < '0.99':
        raise ImportError('The version of NetworkX must be at least '
                          '0.99 to run this example')

    # Make a NetworkX graph out of our point and edge data
    g = build_geometric_graph(x, y, z, edges)

    # Compute minimum spanning tree using networkx
    # nx.mst returns an edge generator
    edges = nx.minimum_spanning_tree(g).edges(data=True)
    start_idx, end_idx, _ = np.array(list(edges)).T
    start_idx = start_idx.astype(np.int)
    end_idx = end_idx.astype(np.int)

    # Plot this with Mayavi
    graph_plot(
        x,
        y,
        z,
        start_idx,
        end_idx,
        edge_scalars=z[start_idx],
        opacity=0.8,
        colormap='summer',
        line_width=4,
    )

    mlab.view(60, 46, 4)
    mlab.show()
Example #45
0
    ax.set_ylabel('Z (m)')
    ax.set_zlabel('$n_e (10^{18}m^{-3})$')

    fig3D.show(0)

else:
    from mayavi import mlab
    from mayavi.version import version as mayver
    from matplotlib.colors import LightSource

    ## Mayavi need .T to get the column/row order right - otherwise crash or hang
    maymap = 'jet' if mayver < '4.5.0' else 'rainbow'
    surf = mlab.surf(-tgrid.T,
                     zgrid.T,
                     gridded_ne.T,
                     colormap=maymap,
                     warp_scale='auto')
    # Change the visualization parameters.
    surf.actor.property.interpolation = 'phong'
    surf.actor.property.ambient = 0.05
    surf.actor.property.diffuse = 0.1
    mlab.view(azimuth=45, elevation=80)
    #surf.actor.property.interpolation='gouraud'
    #surf.actor.property.specular = 0.1
    #surf.actor.property.specular_power = 5

    if mayver < '4.5.0':
        print('Close mayavi window to return to prompt as version is {mv}'.
              format(mv=mayver))
        mlab.show()
Example #46
0
def draw_lidar(
    pc,
    color=None,
    fig=None,
    bgcolor=(0, 0, 0),
    pts_scale=0.3,
    pts_mode="sphere",
    pts_color=None,
    color_by_intensity=False,
    pc_label=False,
):
    """ Draw lidar points
    Args:
        pc: numpy array (n,3) of XYZ
        color: numpy array (n) of intensity or whatever
        fig: mayavi figure handler, if None create new one otherwise will use it
    Returns:
        fig: created or used fig
    """
    # ind = (pc[:,2]< -1.65)
    # pc = pc[ind]
    pts_mode = "point"
    print("====================", pc.shape)
    if fig is None:
        fig = mlab.figure(
            figure=None, bgcolor=bgcolor, fgcolor=None, engine=None, size=(1600, 1000)
        )
    if color is None:
        color = pc[:, 2]
    if pc_label:
        color = pc[:, 4]
    if color_by_intensity:
        color = pc[:, 2]

    mlab.points3d(
        pc[:, 0],
        pc[:, 1],
        pc[:, 2],
        color,
        color=pts_color,
        mode=pts_mode,
        colormap="gnuplot",
        scale_factor=pts_scale,
        figure=fig,
    )

    # draw origin
    mlab.points3d(0, 0, 0, color=(1, 1, 1), mode="sphere", scale_factor=0.2)

    # draw axis
    axes = np.array(
        [[2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0]],
        dtype=np.float64,
    )
    mlab.plot3d(
        [0, axes[0, 0]],
        [0, axes[0, 1]],
        [0, axes[0, 2]],
        color=(1, 0, 0),
        tube_radius=None,
        figure=fig,
    )
    mlab.plot3d(
        [0, axes[1, 0]],
        [0, axes[1, 1]],
        [0, axes[1, 2]],
        color=(0, 1, 0),
        tube_radius=None,
        figure=fig,
    )
    mlab.plot3d(
        [0, axes[2, 0]],
        [0, axes[2, 1]],
        [0, axes[2, 2]],
        color=(0, 0, 1),
        tube_radius=None,
        figure=fig,
    )

    # draw fov (todo: update to real sensor spec.)
    fov = np.array(
        [[20.0, 20.0, 0.0, 0.0], [20.0, -20.0, 0.0, 0.0]], dtype=np.float64  # 45 degree
    )

    mlab.plot3d(
        [0, fov[0, 0]],
        [0, fov[0, 1]],
        [0, fov[0, 2]],
        color=(1, 1, 1),
        tube_radius=None,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [0, fov[1, 0]],
        [0, fov[1, 1]],
        [0, fov[1, 2]],
        color=(1, 1, 1),
        tube_radius=None,
        line_width=1,
        figure=fig,
    )

    # draw square region
    TOP_Y_MIN = -20
    TOP_Y_MAX = 20
    TOP_X_MIN = 0
    TOP_X_MAX = 40
    TOP_Z_MIN = -2.0
    TOP_Z_MAX = 0.4

    x1 = TOP_X_MIN
    x2 = TOP_X_MAX
    y1 = TOP_Y_MIN
    y2 = TOP_Y_MAX
    mlab.plot3d(
        [x1, x1],
        [y1, y2],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [x2, x2],
        [y1, y2],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [x1, x2],
        [y1, y1],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [x1, x2],
        [y2, y2],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )

    # mlab.orientation_axes()
    mlab.view(
        azimuth=180,
        elevation=70,
        focalpoint=[12.0909996, -1.04700089, -2.03249991],
        distance=62.0,
        figure=fig,
    )
    return fig
Example #47
0
import numpy as np
from mayavi import mlab
from Xfrac import XfracFile

fname = 'data/xfrac3d_7.305.bin'
#fname = 'xfrac3d_10.023.bin'

x, y, z = np.ogrid[0:500:300j, 0:500:300j, 0:500:300j]
data = XfracFile(fname).xi

#mlab.init_notebook()
#f0 = mlab.figure(size=(600, 500), bgcolor=(0,0,0))
#f0 = mlab.figure(bgcolor=(0,0,0))
#mlab.clf()

src = mlab.pipeline.scalar_field(data)
vol = mlab.pipeline.volume(src)#, vmin=0.5, vmax=1)

#mlab.draw()
mlab.outline()
mlab.axes(ranges=[0, 500, 0, 500, 0, 500], nb_labels=6, xlabel='x', ylabel='y', zlabel='z')
mlab.view(azimuth=40, elevation=70, distance=1000, focalpoint=[150,120,100])
#mlab.savefig('test.png')
mlab.show()