Beispiel #1
0
def lorenz_plot(name, N=10, res=2000, step=2, t=10, seed_=120):
    # Select initial conditions
    seed(seed_)
    x0 = -15 + 30 * np.random.rand(N, 3)

    # Solve for the trajectories
    t = np.linspace(0, t, res)
    pts = np.empty((N, res, 3))
    for i, x in enumerate(x0):
        pts[i] = odeint(lorenz_ode, x, t)

    # Select the colors for the different curves.
    colors = np.zeros((N, 3))
    colors[:,1] = np.linspace(0, 1, N)
    colors = map(tuple, colors.tolist())

    # Plot the different trajectories.
    for x, color in zip(pts, colors):
        mlab.plot3d(x[:,0], x[:,1], x[:,2], tube_radius=.2, color=color)

    # Position the camera.
    mlab.gcf().scene.camera.position = np.array([165.40890060328016, -140.77357847515529, 8.2574865327247622]) / 1.55
    mlab.gcf().scene.camera.focal_point = [-1.7792501449584961, -3.6287221908569336, 23.397351264953613]
    mlab.gcf().scene.camera.view_up = [-0.078467260964232038, -0.20339450183237351, 0.97594752194015633]
    mlab.gcf().scene.camera.clipping_range = [128.64624663718814, 328.22549479639167]

    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
Beispiel #2
0
def make_chromatin_movies():
    """
    """
    dnachain.MultiSolenoidVolume(voxelheight=1500, separation=400)\
        .to_line_plot()
    fig = mlab.gcf()
    fig.scene.set_size([1024, 768])
    fig.scene.render()
    time.sleep(1)
    mlab.savefig("example/img/chromatin_multi_straight0000.png")
    step = 5
    for ii in range(1, int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        fname = "example/img/chromatin_multi_straight{:04d}.png".format(ii)
        mlab.savefig(fname)

    dnachain.MultiSolenoidVolume(voxelheight=1500, separation=400, turn=True)\
        .to_line_plot()
    fig = mlab.gcf()
    fig.scene.set_size([1024, 768])
    fig.scene.render()
    time.sleep(1)
    mlab.savefig("example/img/chromatin_multi_turn0000.png")
    step = 5
    for ii in range(1, int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        fname = "example/img/chromatin_multi_turn{:04d}.png".format(ii)
        mlab.savefig(fname)

    dnachain.TurnedSolenoid().to_line_plot()
    fig = mlab.gcf()
    fig.scene.set_size([1024, 768])
    fig.scene.render()
    time.sleep(1)
    mlab.savefig("example/img/chromatin_single_turn0000.png")
    step = 5
    for ii in range(1, int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        fname = "example/img/chromatin_single_turn{:04d}.png".format(ii)
        mlab.savefig(fname)

    dnachain.Solenoid().to_line_plot()
    fig = mlab.gcf()
    fig.scene.set_size([1024, 768])
    fig.scene.render()
    time.sleep(1)
    mlab.savefig("example/img/chromatin_single_straight0000.png")
    step = 5
    for ii in range(1, int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        fname = "example/img/chromatin_single_straight{:04d}.png".format(ii)
        mlab.savefig(fname)
    return None
Beispiel #3
0
def harmonic2(name):
    x = np.linspace(0, np.pi)
    y = np.linspace(0, np.pi)
    x, y = np.meshgrid(x, y, copy=False)
    z = np.sin(2 * x) * np.sin(2 * y)
    mlab.mesh(x, y, z)
    # Zoom in a bit.
    mlab.gcf().scene.camera.position = mlab.gcf().scene.camera.position / 1.3
    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
Beispiel #4
0
def harmonic1(name):
    x = np.linspace(0, np.pi)
    y = np.linspace(0, np.pi)
    x, y = np.meshgrid(x, y, copy=False)
    z = np.sin(x) * np.sin(y)
    # Trick it into setting the perspective as if the figure were centered at the origin.
    f = mlab.mesh(x, y, np.zeros_like(z), scalars=z)
    f.mlab_source.set(z=z)
    # Zoom in a bit.
    mlab.gcf().scene.camera.position = mlab.gcf().scene.camera.position / 1.2
    # Save the plot.
    mlab.savefig(name)
    mlab.clf()
Beispiel #5
0
def plot_basis_function(filename):
    n=5
    x = np.linspace(0, 1, n)
    x, y = np.meshgrid(x, x)
    t = triangles(n)
    vals = np.zeros(x.size)
    vals[n**2 // 2] = 1
    ml.figure(size=(500,500))
    ml.triangular_mesh(x.ravel(), y.ravel(), vals, t)
    ml.pitch(-3.5)
    ml.gcf().scene.camera.position = ml.gcf().scene.camera.position / 1.2
    ml.gcf().scene.save_png(filename)
    ml.clf()
Beispiel #6
0
def lorenz_animation(N=10, res=1000, step=2, t=10, seed_=120, atol=1E-15,
                     rtol=1E-13, delay=10, sigma=10., beta=8./3, rho=28.):
    """ Animate the trajectories given by the Lorenz equations for 'N' starting points.
    Choose random x, y, and z values between -15 and 15.
    Seed the random number generator with 'seed_'.
    Use a resolution of 'res' for the points in the plot.
    Plot the time values between 0 ant 't'.
    When computing the trajectories, pass the tolerances
    'atol' and 'rtol' to the ODE solver.
    At each update, add 'step' points to the plot.
    Use a delay of 'delay' at each update in the animation.
    Use different colors for each trajectory.
    Use the values of 'sigma', 'beta', and 'rho' in the Lorenz ODE. """
    
    # Get initial conditions.
    seed(seed_)
    x0 = -15 + 30 * rand(N, 3)
    
    # Solve for the trajectories.
    t = np.linspace(0, t, res)
    pts = np.empty((N, res, 3))
    for i, x in enumerate(x0):
        pts[i] = odeint(lorenz_ode, x, t,
                        args=(sigma, beta, rho), rtol=rtol, atol=atol)
    
    # Select the colors for the different curves.
    colors = np.zeros((N, 3))
    colors[:,1] = np.linspace(0, 1, N)
    colors = map(tuple, colors.tolist())
    
    # Plot the different trajectories.
    contours = [mlab.plot3d(x[:1,0], x[:1,1], x[:1,2], tube_radius=.15, color=color)
                for x, color in zip(pts, colors)]
    
    # Position the view for the plot.
    mlab.gcf().scene.camera.position = [127.23761585, -108.28736806, 6.35191272]
    mlab.gcf().scene.camera.focal_point = [-1.7792501449584961, -3.6287221908569336, 23.397351264953613]
    mlab.gcf().scene.camera.view_up = [-0.078467260964232038, -0.20339450183237351, 0.97594752194015633]
    mlab.gcf().scene.camera.clipping_range = [128.64624663718814, 328.22549479639167]
    
    # Define the animation.
    @mlab.show
    @mlab.animate(delay=delay)
    def trace_curve():
        for i in xrange(step, res, step):
            for c, x, color in zip(contours, pts, colors):
                c.mlab_source.reset(x=x[:i,0], y=x[:i,1], z=x[:i,2])
            yield
    
    # Run the animation.
    trace_curve()
Beispiel #7
0
def example():
    # setup movie
    m = movie(frame_rate=22.5)
    
    # setup example
    from mayavi import mlab
    mlab.options.offscreen = True
    mlab.test_contour3d()
    f = mlab.gcf() 

    # save frames
    for i in range(36*3):
        f.scene.camera.azimuth(10) # rotate
        f.scene.render()
        mlab.savefig(m.next_frame(), figure=f)
    
    # encode frames
    encoded = m.encode()

    # remove tempdir
    del m
    
    if not encoded:
        # report error
        exit(m.output)
Beispiel #8
0
def plot_save(sub,
              plot_name,
              subfolder=None,
              trial=None,
              idx=None,
              matplotlib_figure=None,
              mayavi=False,
              mayavi_figure=None,
              brain=None,
              dpi=None):
    # Take DPI from Settings if not defined by call
    if not dpi:
        dpi = sub.dpi

    # Todo: Move all possible settings to home-dict (settings-capabilities, e.g boolean, different between os)
    if sub.save_plots and sub.save_plots != 'false':
        # Folder is named by plot_name
        dir_path = join(sub.figures_path, plot_name)

        # Create Subfolder if necessary
        if subfolder:
            dir_path = join(dir_path, subfolder)

        # Create Subfolder for trial if necessary
        if trial:
            dir_path = join(dir_path, trial)

        # Create not existent folders
        if not isdir(dir_path):
            makedirs(dir_path)

        if subfolder and trial and idx:
            file_name = f'{sub.name}-{trial}_{sub.p_preset}_{plot_name}-{subfolder}-{idx}{sub.img_format}'
        elif subfolder and trial:
            file_name = f'{sub.name}-{trial}_{sub.p_preset}_{plot_name}-{subfolder}{sub.img_format}'
        elif trial and idx:
            file_name = f'{sub.name}-{trial}_{sub.p_preset}_{plot_name}-{idx}{sub.img_format}'
        elif trial:
            file_name = f'{sub.name}-{trial}_{sub.p_preset}_{plot_name}{sub.img_format}'
        elif idx:
            file_name = f'{sub.name}_{sub.p_preset}_{plot_name}-{idx}{sub.img_format}'
        else:
            file_name = f'{sub.name}_{sub.p_preset}_{plot_name}{sub.img_format}'

        save_path = join(dir_path, file_name)

        if matplotlib_figure:
            matplotlib_figure.savefig(save_path, dpi=dpi)
        elif mayavi_figure:
            mayavi_figure.savefig(save_path)
        elif brain:
            brain.save_image(save_path)
        elif mayavi:
            mlab.savefig(save_path, figure=mlab.gcf())
        else:
            plt.savefig(save_path, dpi=dpi)

        print('figure: ' + save_path + ' has been saved')
    else:
        print('Not saving plots; set "save_plots" to "True" to save')
Beispiel #9
0
def animate():
    '''
    Callback function to update and animate the plot.
    
    INPUTS:
        - No inputs.

    OUTPUT:
        - No return; does internal calls to update plot.
    '''
    
    f = mlab.gcf()                                      # Get engine handle of figure
    
    while( True ):                                      # Loop 43va
        try:
            # Update
            pos = compute_coordinate()                  # Get updated magnet position

            # Draw
            plt.mlab_source.set( x = pos[0],            # Update last drawn point ...
                                 y = pos[1],            # ... on graph with the ...
                                 z = pos[2] )           # ... current position.

            colors = 0.0 * pos                                       # Dark blue color
            plt.glyph.scale_mode = 'scale_by_vector'
            plt.mlab_source.dataset.point_data.scalars = colors

            yield

        except KeyboardInterrupt:
            closeBTPort( steth )                        # Close BT port at exit
            mlab.close( all=True )                      # Close all figures and scenes
Beispiel #10
0
 def _render_model(self):
   figure = mlab.gcf()
   mlab.clf()
   s = mlab.triangular_mesh(self.coords[:,0], self.coords[:,1],
                            self.coords[:,2], self.tri_index,
                            color=(0.5,0.5,0.5))
   return s.scene
Beispiel #11
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
Beispiel #12
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()
Beispiel #13
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
def _resize_window(size, fig=None):
    if fig is None:
        fig = mlab.gcf()

    try:
        # scene.set_size doesn't seem to work on linux && os x, so
        # go into the backend and do it by hand
        if sys.platform == "darwin" or sys.platform.startswith('linux'):
            toolkit = mayavi.ETSConfig.toolkit

            if toolkit == 'qt4':
                sc = fig.scene
                window_height = sc.control.parent().size().height()
                render_height = sc.render_window.size[1]
                h = window_height - render_height
                sc.control.parent().resize(size[0], size[1] + h)

            elif toolkit == 'wx':
                w, h = size[0], size[1]
                fig.scene.control.Parent.Parent.SetClientSizeWH(w, h)

            else:
                print("Unknown mayavi backend {0} (not qt4 or "
                      "wx); not resizing.".format(toolkit),
                      file=sys.stderr)
        else:
            fig.scene.set_size(size)
    except Exception as e:
        print("Resize didn't work:: {0}".format(repr(e)), file=sys.stderr)
Beispiel #15
0
def animate():
    '''
    Callback function to update and animate the plot.
    
    INPUTS:
        - No inputs.

    OUTPUT:
        - No return; does internal calls to update plot.
    '''

    f = mlab.gcf()  # Get engine handle of figure

    while (True):  # Loop 43va
        try:
            # Update
            pos = compute_coordinate()  # Get updated magnet position

            # Draw
            plt.mlab_source.set(
                x=pos[0],  # Update last drawn point ...
                y=pos[1],  # ... on graph with the ...
                z=pos[2])  # ... current position.
            yield

        except KeyboardInterrupt:
            mlab.close(all=True)  # Close all figures and scenes
Beispiel #16
0
	def _draw(self):
		"""Update the Mayavi objects with new particle information.
		This is called periodically in the GUI thread"""
		if self.data is None:
			return
		
		assert isinstance(threading.current_thread(), threading._MainThread)

		f = mlab.gcf()
		visual.set_viewer(f)

		coords, types, radii, N_changed, bonds, Nbonds_changed, boxl, box_changed = self.data
		self.data = None

		if box_changed or not self.running:
			self.box.set(bounds=(0,boxl[0], 0,boxl[1], 0,boxl[2]))

		if not N_changed:
			self.points.mlab_source.set(x=coords[:,0]%boxl[0], y=coords[:,1]%boxl[1], z=coords[:,2]%boxl[2], u=radii, v=radii, w=radii, scalars=types)
		else:
			self.points.mlab_source.reset(x=coords[:,0]%boxl[0], y=coords[:,1]%boxl[1], z=coords[:,2]%boxl[2], u=radii, v=radii, w=radii, scalars=types)
		if not self.running:
			f.scene.reset_zoom()
			self.running = True

		if not Nbonds_changed:
			if bonds.shape[0] > 0:
				self.arrows.mlab_source.set  (x=bonds[:,0], y=bonds[:,1], z=bonds[:,2], u=bonds[:,3], v=bonds[:,4], w=bonds[:,5])
		else:
			self.arrows.mlab_source.reset(x=bonds[:,0], y=bonds[:,1], z=bonds[:,2], u=bonds[:,3], v=bonds[:,4], w=bonds[:,5], scalars=bonds[:,6])
Beispiel #17
0
def make_fractal_movie(seed="X", iter=6):
    """
    """
    f = hilbert.VoxelisedFractal.fromSeed(seed, iter)
    f.center_fractal()
    pos = np.array([vox.pos for vox in f.fractal])
    max_pos = np.max(pos, axis=0)
    mask = lambda x: np.sum((x[0:3]/max_pos[0:3])**2) <= 1
    f = f.to_pretty_plot(refine=5, mayavi=True, mask=mask)
    fig = mlab.gcf()
    fig.scene.set_size([1024, 768])
    fig.scene.render()
    mlab.savefig("example/img/fractal_rotate0000.png")
    step = 5
    for ii in range(1, int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        mlab.savefig("example/img/fractal_rotate{:04d}.png".format(ii))

    mlab.savefig("example/img/fractal_zoom0000.png")
    nsteps = 200
    for ii in range(nsteps):
        fig.scene.camera.zoom(1.02)
        fig.scene.render()
        mlab.savefig("example/img/fractal_zoom{:04d}.png".format(ii))

    for ii in range(nsteps, nsteps + int(720/step)):
        fig.scene.camera.azimuth(step)
        fig.scene.render()
        mlab.savefig("example/img/fractal_zoom{:04d}.png".format(ii))
    return None
Beispiel #18
0
def main():
    from basic_move import Box
    from enable.api import Container
    container = Container()
    box = Box(bounds=[30,30], position=[20,20], padding=5)
    container.add(box)

    # Create the mlab test mesh and get references to various parts of the
    # VTK pipeline
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor

    # Create the Enable Window
    window = EnableVTKWindow(rwi, renderer,
            component=container,
            #istyle_class = tvtk.InteractorStyleSwitch,
            istyle_class = tvtk.InteractorStyle,
            resizable = "v",
            bounds = [100, 100],
            padding_top = 20,
            padding_bottom = 20,
            padding_left = 20,
            )

    #rwi.render()
    #rwi.start()
    mlab.show()
    return window, render_window
Beispiel #19
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!
Beispiel #20
0
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
    """ Capture a screeshot of the Mayavi figure and display it in the
        matplotlib axes.
    """
    import pylab as pl
    # Late import to avoid triggering wx imports before needed.
    try:
        from mayavi import mlab
    except ImportError:
        # Try out old install of Mayavi, with namespace packages
        from enthought.mayavi import mlab

    if mayavi_fig is None:
        mayavi_fig = mlab.gcf()
    else:
        mlab.figure(mayavi_fig)
    if mpl_axes is not None:
        pl.axes(mpl_axes)

    filename = tempfile.mktemp('.png')
    mlab.savefig(filename, figure=mayavi_fig)
    image3d = pl.imread(filename)
    if autocrop:
        bg_color = mayavi_fig.scene.background
        image3d = autocrop_img(image3d, bg_color)
    pl.imshow(image3d)
    pl.axis('off')
    os.unlink(filename)
Beispiel #21
0
def run_mlab_file(filename, image_file):
    ## XXX: Monkey-patch mlab.show, so that we keep control of the
    ## the mainloop
    old_show = mlab.show
    def my_show(func=None):
        pass
    mlab.show = my_show
    mlab.clf()
    e = mlab.get_engine()
    e.close_scene(mlab.gcf())
    execfile(filename, {'__name__': '__main__'})
    mlab.savefig(image_file)
    size = mlab.gcf().scene.get_size()
    for scene in e.scenes:
        e.close_scene(scene)
    mlab.show = old_show
Beispiel #22
0
def plot_targets(tasks, color=(1., 0., 0.), scale_factor=0.005):
    '''Plot start and end points of tasks.

    Starting points are designated by spheres, and end points by cubes.
    '''
    # draw target positions
    p3d = mlab.pipeline
    fig = mlab.gcf()
    fig.scene.disable_render = True
    
    starts, stops = tasks[:,:3], tasks[:,3:]

    # plot start points
    x,y,z = starts.T
    start_src = p3d.scalar_scatter(x, y, z)
    gl1 = p3d.glyph(start_src)
    gl1.glyph.glyph.scale_factor = scale_factor         # smaller
    gl1.actor.actor.property.color = color # red
    gl1.actor.actor.property.opacity = 0.5 # red

    # plot stop points
    #x,y,z = stops.T
    #stop_src = p3d.scalar_scatter(x, y, z)
    #gl2 = p3d.glyph(stop_src)
    #gl2.glyph.glyph.scale_factor = scale_factor         # smaller
    #gl2.actor.actor.property.color = color # red
    #cube = gl2.glyph.glyph_source.glyph_dict['cube_source']
    #gl2.glyph.glyph_source.glyph_source = cube
    #gl2.actor.actor.property.opacity = 0.5

    fig.scene.disable_render = False
    return gl1
Beispiel #23
0
def disp_pts(pts1, pts2, color1=(1,0,0), color2=(0,1,0)):
    figure = mlab.gcf()
    mlab.clf()
    figure.scene.disable_render = True

    pts1_glyphs   = mlab.points3d(pts1[:,0], pts1[:,1], pts1[:,2], color=color1, resolution=20, scale_factor=0.001)
    pts2_glyphs   = mlab.points3d(pts2[:,0], pts2[:,1], pts2[:,2], color=color2, resolution=20, scale_factor=0.001)
    glyph_points1 = pts1_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()
    glyph_points2 = pts2_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()

    dd = 0.001

    outline1 = mlab.outline(pts1_glyphs, line_width=3)
    outline1.outline_mode = 'full'
    p1x, p1y, p1z = pts1[0,:]
    outline1.bounds = (p1x-dd, p1x+dd,
                       p1y-dd, p1y+dd,
                       p1z-dd, p1z+dd)

    pt_id1 = mlab.text(0.8, 0.2, '0 .', width=0.1, color=color1)

    outline2 = mlab.outline(pts2_glyphs, line_width=3)
    outline2.outline_mode = 'full'
    p2x, p2y, p2z = pts2[0,:]
    outline2.bounds = (p2x-dd, p2x+dd,
                       p2y-dd, p2y+dd,
                       p2z-dd, p2z+dd)  
    pt_id2 = mlab.text(0.8, 0.01, '0 .', width=0.1, color=color2)
    
    figure.scene.disable_render = False


    def picker_callback(picker):
        """ Picker callback: this gets called during pick events.
        """
        if picker.actor in pts1_glyphs.actor.actors:
            point_id = picker.point_id/glyph_points1.shape[0]
            if point_id != -1:
                ### show the point id
                pt_id1.text = '%d .'%point_id
                #mlab.title('%d'%point_id)
                x, y, z = pts1[point_id,:]
                outline1.bounds = (x-dd, x+dd,
                                   y-dd, y+dd,
                                   z-dd, z+dd)
        elif picker.actor in pts2_glyphs.actor.actors:
            point_id = picker.point_id/glyph_points2.shape[0]
            if point_id != -1:
                ### show the point id
                pt_id2.text = '%d .'%point_id
                x, y, z = pts2[point_id,:]
                outline2.bounds = (x-dd, x+dd,
                                   y-dd, y+dd,
                                   z-dd, z+dd)


    picker = figure.on_mouse_pick(picker_callback)
    picker.tolerance = dd/2.
    mlab.show()
Beispiel #24
0
def load_nvm_and_register_images(nvm_file, 
                                 images_path, 
                                 max_sleep_seconds,
                                 every_nth,
                                 single_image = None):

    cams, points, cams_mlab, points_mlab = mayaviu.load_and_plot_nvm_cams(nvm_file)    
    fig = mlab.gcf()
    # signal.signal(signal.SIGUSR1, plot_localized_image_after_signal(fig))

    # if single_image is not None:
    #     tmp_dir = 'tmp_im_dir'
    #     if not os.path.isdir(tmp_dir):
    #         os.mkdir(tmp_dir)
    #     shutil.copy(
    
    # signal.signal(signal.SIGUSR1, localized_image_signal)

    model = vsfm_model.create_from_nvm(nvm_file)
    vsfm_interface = vsfmu.vsfm_interface()
    vsfm_interface.sfm_more_less_visualization_data()
    
    image_files = ['{}/{}'.format(images_path, i) \
                      for i in os.listdir(images_path) if i.find('.jpg') > 0]
    image_basenames = sorted([os.path.basename(_) for _ in image_files])
    image_files = sorted([os.path.abspath(_) for _ in image_files])

    vsfm_interface.sfm_load_nview_match(nvm_file)
    vsfm_interface.view_image_thumbnails()

    mlab.show()
    rtst = rts_thread(vsfm_interface, 
                      nvm_file,
                      model, 
                      model_image_dir = '/home/nrhineha/dev/activity/data/kitchen_seq_x1',
                      image_files = image_files,
                      max_sleep_seconds = max_sleep_seconds)
    rtst.start()
    mlab.show()
    
    # seq = register_temporal_sequence(vsfm_interface, 
    #                                  nvm_file,
    #                                  model, 
    #                                  model_image_dir = '/home/nrhineha/dev/activity/data/kitchen_seq_x1',
    #                                  image_files = image_files,
    #                                  max_sleep_seconds = max_sleep_seconds)
    
    # cams, new_cams = register_image(vsfm_interface, image_files[0])

    # # vsfm_interface.sfm_delete_selected_camera()

    # near_cams= model.lookup_nearby_cameras(new_cams[0])
    # mfn = write_specified_match_file('/home/nrhineha/Desktop/test/loc2.jpg',
    #                                  near_cams, 
    #                                  '/home/nrhineha/dev/activity/data/kitchen_seq_x1')

    # register_image(vsfm_interface, images_path, image_files[1], image_basenames[1], match_specified_fn = os.path.abspath(mfn))
    
    ipdb.set_trace()
Beispiel #25
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
Beispiel #26
0
def plot_lines(lines, scalars=None, style="tube", figure=None,
               name="Lines", tube_radius=0.05, tube_sides=6, **kwargs):
    """Make 3D mayavi plot of lines

    Scalars can be a bunch of single values, or a bunch of rgb data
    to set the color of each line / vertex explicitly. This is
    explained in :py:func:`lines2source`.

    Example:
        A common use case of setting the line color from a topology
        will want to use :py:func:`viscid.topology2color`::

            >>> import viscid
            >>> from viscid.plot import mvi
            >>>
            >>> B = viscid.vlab.get_dipole()
            >>> seeds = viscid.Line([-4, 0, 0], [4, 0, 0])
            >>> lines, topology = viscid.calc_streamlines(B, seeds,
            >>>                                           ibound=0.05)
            >>> scalars = viscid.topology2color(topology)
            >>> mvi.plot_lines(lines, scalars, tube_radius=0.02)
            >>> mvi.mlab.savefig("dipole.x3d")
            >>> viscid.vutil.meshlab_convert("dipole.x3d", "dae")
            >>> mvi.show()

    Parameters:
        lines (list): See :py:func:`lines2source`
        scalar (ndarray): See :py:func:`lines2source`
        style (str): 'strip' or 'tube'
        figure (mayavi.core.scene.Scene): specific figure, or
            :py:func:`mayavi.mlab.gcf`
        name (str): Description
        tube_radius (float): Radius if style == 'tube'
        tube_sides (int): Angular resolution if style == 'tube'
        **kwargs: passed to :meth:`mayavi.mlab.pipeline.surface`. This
            is useful for setting a colormap among other things.

    Returns:
        Mayavi surface module

    Raises:
        ValueError: if style is neither tube nor strip
    """
    style = style.lower()
    if not figure:
        figure = mlab.gcf()

    src = lines2source(lines, scalars=scalars, name=name)

    if style == "tube":
        lines = mlab.pipeline.tube(src, figure=figure, tube_radius=tube_radius,
                                   tube_sides=tube_sides)
    elif style == "strip":
        lines = mlab.pipeline.stripper(src, figure=figure)
    else:
        raise ValueError("Unknown style for lines: {0}".format(style))

    surface = mlab.pipeline.surface(lines, **kwargs)
    return surface
Beispiel #27
0
    def showCloudsWithBBs(self, orgPC=[], fovPC=[], roadPC=[], vehPC=[], pedPC=[], cycPC=[], bb3D=[], fileName="", make_sparse=True):

        mlab.figure(bgcolor=(1, 1, 1), size=(width, height))
        figure = mlab.gcf()

        # make the original point cloud denser by removing every second point
        if make_sparse:
            if len(orgPC):
                orgPC = np.delete(orgPC, list(range(0, orgPC.shape[0], 2)), axis=0)

            if len(orgPC):
                orgPC = np.delete(orgPC, list(range(0, orgPC.shape[0], 2)), axis=0)

            if len(orgPC):
                orgPC = np.delete(orgPC, list(range(0, orgPC.shape[0], 2)), axis=0)

        # colorize point clouds
        if len(orgPC):
            x, y, z = self.getCoordinates(orgPC)
            mlab.points3d(x, y, z, np.ones(len(orgPC)), color=tuple(self.colorOrgPC),
                          colormap="spectral", scale_factor=self.pointSize)

        if len(fovPC):
            x, y, z = self.getCoordinates(fovPC)
            mlab.points3d(x, y, z, np.ones(len(fovPC)), color=tuple(self.colorFovPC),
                          colormap="spectral", scale_factor=self.pointSize)
        if len(roadPC):
            x, y, z = self.getCoordinates(roadPC)
            mlab.points3d(x, y, z, np.ones(len(roadPC)), color=tuple(self.colorRoadPC),
                          colormap="spectral", scale_factor=self.pointSize)

        if len(vehPC):
            x, y, z = self.getCoordinates(vehPC)
            mlab.points3d(x, y, z, np.ones(len(vehPC)), color=tuple(self.colorVehPC),
                          colormap="spectral", scale_factor=self.pointSize)

        if len(pedPC):
            x, y, z = self.getCoordinates(pedPC)
            mlab.points3d(x, y, z, np.ones(len(pedPC)), color=tuple(self.colorPedPC),
                          colormap="spectral", scale_factor=self.pointSize)

        if len(cycPC):
            x, y, z = self.getCoordinates(cycPC)
            mlab.points3d(x, y, z, np.ones(len(cycPC)), color=tuple(self.colorCycPC),
                          colormap="spectral", scale_factor=self.pointSize)

        if bb3D:
            self.draw_3D_bboxes(bb3D, figure, draw_text=False)

        # set camera parameters
        figure.scene.camera.zoom(zoomFactor)
        figure.scene.camera.azimuth(azimuthAngle)
        mlab.view(azimuth=azimuthVal, elevation=elevationVal, distance=distanceVal, focalpoint=focalpointVal)

        if fileName:
        # save the figure
            #print(" saving result " + fileName)
            mlab.savefig(fileName)
            mlab.close()
Beispiel #28
0
def drawrec(rec4points):
    fig = mlab.gcf()
    rec4points = np.vstack((rec4points, rec4points[0, :]))
    mlab.plot3d(rec4points[:, 0],
                rec4points[:, 1],
                rec4points[:, 2],
                tube_radius=None,
                figure=fig)
Beispiel #29
0
    def make_frame(self, t):
        """Make a frame."""

        f = mlab.gcf()
        f.scene.camera.azimuth(1)
        self.update_pts3d()

        return mlab.screenshot(antialiased=True)
Beispiel #30
0
 def anim():
     f = mlab.gcf()
     for count, i in enumerate(range(2,361,2)):
     #while 1:
         f.scene.camera.azimuth(degree_step)
         f.scene.render()
         mlab.savefig('/Users/jessebrown/Desktop/mayavi_figs/r_hipp_network%03d.png' %count)
         yield
Beispiel #31
0
def lorenz_perturbed(N=10, res=10000, step=5, t=50, seed_=120, atol=1E-15,
                     rtol=1E-13, epsilon=2.2e-16, delay=10,
                     sigma=10., beta=8./3, rho=28.):
    """ Animate the trajectories given by the Lorenz equations.
    Plot two trajectories, one with the initial value given by the
    random number generator after you seed it,
    and another that is equal to (1 + epsilon) times the other initial value.
    Choose random x, y, and z values between -15 and 15.
    Seed the random number generator with 'seed_'.
    Use a resolution of 'res' for the points in the plot.
    Plot the time values between 0 ant 't'.
    Pass the tolerances 'atol' and 'rtol' to the ODE solver.
    At each update, add 'step' points to the plot.
    Use a delay of 'delay' at each update in the animation.
    Use different colors for each trajectory.
    Use the values of 'sigma', 'beta', and 'rho' in the Lorenz ODE. """
    # Get initial conditions.
    seed(seed_)
    x1 = -15 + 30 * rand(3)
    x2 = x1 * (1. + epsilon)
    
    # Solve for the trajectories.
    # Plot them.
    t = np.linspace(0, t, res)
    y1 = odeint(lorenz_ode, x1, t, args=(sigma, beta, rho), atol=atol, rtol=rtol)
    c1 = mlab.plot3d(y1[:1,0], y1[:1,1], y1[:1,2], tube_radius=.2, color=(1, 0, 0))
    y2 = odeint(lorenz_ode, x2, t, args=(sigma, beta, rho), atol=atol, rtol=rtol)
    c2 = mlab.plot3d(y2[:1,0], y2[:1,1], y2[:1,2], tube_radius=.2, color=(0, 0, 1))
    
    # Position the view for the plot.
    mlab.gcf().scene.camera.position = [127.23761585, -108.28736806, 6.35191272]
    mlab.gcf().scene.camera.focal_point = [-1.7792501449584961, -3.6287221908569336, 23.397351264953613]
    mlab.gcf().scene.camera.view_up = [-0.078467260964232038, -0.20339450183237351, 0.97594752194015633]
    mlab.gcf().scene.camera.clipping_range = [128.64624663718814, 328.22549479639167]
    
    # Define the animation.
    @mlab.show
    @mlab.animate(delay=delay)
    def trace_curve():
        for i in xrange(2, res, step):
            c1.mlab_source.reset(x=y1[:i,0], y=y1[:i,1], z=y1[:i,2])
            c2.mlab_source.reset(x=y2[:i,0], y=y2[:i,1], z=y2[:i,2])
            yield
    
    # Run the animation.
    trace_curve()
Beispiel #32
0
 def anim():
     f = mlab.gcf()
     while True:
         for sensor in sequence:
             color_vector[:] = 0
             color_vector[sensor] = 1
             points.mlab_source.dataset.point_data.scalars = color_vector
             yield
Beispiel #33
0
    def anim(self):
        """Animate the scene."""

        f = mlab.gcf()
        while 1:
            f.scene.camera.azimuth(1)
            self.update_pts3d()
            yield
Beispiel #34
0
    def visualize(self, object, cutoff=0.2):
        '''
        visualizes object.
        :param object: voxel grid.
        :param cutoff: threshold at which to display the voxel.
        :return:
        '''

        #preprocessing object
        object[object >= cutoff] = 1
        object[object < cutoff] = 0

        src = pipeline.scalar_field(object)
        mlab.gcf()
        pipeline.iso_surface(src)

        mlab.show()
Beispiel #35
0
 def anim():
     f = mlab.gcf()
     while True:
         for observation in observations:
             color_vector[:] = 0
             color_vector[observation] = 1
             points.mlab_source.dataset.point_data.scalars = color_vector
             yield
Beispiel #36
0
 def make_frame(self, t):
     mlab.clf()
     mlab.pipeline.volume(self.sfa, figure=self.scene.mayavi_scene)
     angle, _, _, _ = mlab.view()
     mlab.view(azimuth=angle + 2)
     f = mlab.gcf()
     f.scene._lift()
     return mlab.screenshot()
Beispiel #37
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!
def vis_first_layer(net_input_point_cloud,
                    first_layrer_output,
                    vis_rate=1 / 10,
                    square_plot_nb=16):
    """
    input to the network should be cubic grid point cloud
    :param net_input_point_cloud: 1024 x 3
    :param first_layrer_output:  1024 x 64   number of points x features
    :return:
    """
    assert np.shape(first_layrer_output)[1] > square_plot_nb
    nb_points = np.shape(net_input_point_cloud)[0]
    fig = plt.figure(figsize=(19, 10), dpi=300, facecolor='w')

    small_value = np.ones([square_plot_nb, 2]) / .0  # create array of infs

    for i in range(np.shape(first_layrer_output)[1]):
        values = np.reshape(first_layrer_output[:, i], [-1])
        idx = np.argpartition(values, int(nb_points * vis_rate))
        idx = idx[:int(nb_points * vis_rate)]
        mean_value = np.mean(idx)

        if mean_value < np.max(small_value[:, 0]):
            small_value[np.argmax(small_value, axis=0), :] = np.array(
                [mean_value, i])

    for j in range(np.shape(small_value)[0]):

        i = int(small_value[j, 1])
        values = np.reshape(first_layrer_output[:, i], [-1])
        idx = np.argpartition(values, int(nb_points * vis_rate))
        idx = idx[:int(nb_points * vis_rate)]

        m_fig = mlab.figure(size=(500, 500), bgcolor=(1, 1, 1))

        points = mlab.points3d(net_input_point_cloud[idx, 0],
                               net_input_point_cloud[idx, 1],
                               net_input_point_cloud[idx, 2],
                               net_input_point_cloud[idx, 2] * 10**-2 + 1,
                               colormap='Spectral',
                               scale_factor=0.1,
                               figure=m_fig,
                               resolution=64)
        points.glyph.glyph_source.glyph_source.phi_resolution = 64
        points.glyph.glyph_source.glyph_source.theta_resolution = 64
        # mlab.gcf().scene.parallel_projection = True  # parallel projection
        f = mlab.gcf()  # this two line for mlab.screenshot to work
        f.scene._lift()
        # mlab.show()  # for testing
        img = mlab.screenshot(figure=m_fig)
        ax = fig.add_subplot(int(math.sqrt(square_plot_nb)),
                             int(math.sqrt(square_plot_nb)), (j + 1))
        ax.imshow(img)
        ax.set_axis_off()
        mlab.close()

    plt.subplots_adjust(wspace=0, hspace=0)
    plt.show()
Beispiel #39
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()
Beispiel #40
0
def anim():
    f = mlab.gcf()
    x = 1
    while 1:
        f.scene.camera.azimuth(.5)
        f.scene.render()
        #mlab.savefig("/home/christopher/code/Physics/image{}.png".format(x), figure=f, size=(1920,1080))
        x += 1
        yield
Beispiel #41
0
def close():
    """Close the scene."""
    f = mlab.gcf()
    e = mlab.get_engine()
    e.window.workbench.prompt_on_exit = False
    e.window.close()
    mlab.options.backend = 'auto'
    # Hack: on Linux the splash screen does not go away so we force it.
    GUI.invoke_after(500, e.window.workbench.application.gui.stop_event_loop)
Beispiel #42
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
Beispiel #43
0
def spin():
    '''
    Spin the view interactively
    '''
    f = ml.gcf()
    while 1:
        f.scene.camera.azimuth(1)
        f.scene.render()
        yield
Beispiel #44
0
def close():
    """Close the scene."""
    f = mlab.gcf()
    e = mlab.get_engine()
    e.window.workbench.prompt_on_exit = False
    e.window.close()
    mlab.options.backend = 'auto'
    # Hack: on Linux the splash screen does not go away so we force it.
    GUI.invoke_after(500, e.window.workbench.application.gui.stop_event_loop)
Beispiel #45
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
Beispiel #46
0
def anim():
    f = mlab.gcf()
    for i in range(1,result.shape[0]):
        pos = result_swapped[i]
       # d = gaussian_kde(pos)(pos)*100
        #d = np.ones(d.shape)
        plt.mlab_source.set(x=pos[0], y=pos[1], z=pos[2] )
        #plt.mlab_source.dataset.point_data.scalars = np.ones(pos[1].shape)
        yield
Beispiel #47
0
def draw_udir(vxdist, vxunit, voxize_crop, scale):
    from mayavi import mlab
    from colour import Color
    # should reverser y-axis
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0., 0., 0.), size=(800, 800))
    xx, yy, zz = np.where(1e-2 < vxdist)
    vv = vxdist[np.where(1e-2 < vxdist)]
    xx *= scale
    yy *= scale
    zz *= scale
    # vc = transparent_cmap(mpplot.cm.jet)(vv)
    yy = voxize_crop - 1 - yy
    nodes = mlab.points3d(
        xx,
        yy,
        zz,
        vv,
        mode="cube",
        opacity=0.5,
        # color=Color('khaki').rgb,
        colormap='hot',
        scale_factor=0.9)
    nodes.module_manager.scalar_lut_manager.reverse_lut = True
    nodes.glyph.scale_mode = 'scale_by_vector'
    # nodes.mlab_source.dataset.point_data.scalars = vv
    xx, yy, zz = np.mgrid[
        # (scale / 2):(voxize_crop + (scale / 2)):scale,
        # (scale / 2):(voxize_crop + (scale / 2)):scale,
        # (scale / 2):(voxize_crop + (scale / 2)):scale]
        0:voxize_crop:scale, 0:voxize_crop:scale, 0:voxize_crop:scale]
    yy = voxize_crop - 1 - yy
    mlab.quiver3d(xx,
                  yy,
                  zz,
                  vxunit[..., 0],
                  -vxunit[..., 1],
                  vxunit[..., 2],
                  mode="arrow",
                  color=Color('red').rgb,
                  line_width=8,
                  scale_factor=2)
    mlab.gcf().scene.parallel_projection = True
    mlab.view(0, 0)
    mlab.gcf().scene.camera.zoom(1.5)
def animate(v, f, saveDir, t=None, alpha=1):

    # Create the save directory for the images if it doesn't exist
    if not saveDir.endswith('/'):
        saveDir += '/'
    if not os.path.exists(saveDir):
        os.makedirs(saveDir)

    # Render the mesh
    if t is None:
        tmesh = mlab.triangular_mesh(v[0, 0, :],
                                     v[0, 1, :],
                                     v[0, 2, :],
                                     f - 1,
                                     scalars=np.arange(v.shape[2]),
                                     color=(1, 1, 1))

    # Add texture if given
    else:
        tmesh = mlab.triangular_mesh(v[0, 0, :],
                                     v[0, 1, :],
                                     v[0, 2, :],
                                     f - 1,
                                     scalars=np.arange(v.shape[2]))
        if t.shape[1] is not 3:
            t = t.T
        tmesh.module_manager.scalar_lut_manager.lut.table = np.c_[(
            t * 255), alpha * 255 * np.ones(v.shape[2])].astype(np.uint8)


#        tmesh.actor.pro2perty.lighting = False

# Change viewport to x-y plane and enforce orthographic projection
    mlab.view(0, 0, 'auto', 'auto')

    mlab.gcf().scene.parallel_projection = True

    # Save the first frame, then loop through the rest and save them
    mlab.savefig(saveDir + '00001.png', figure=mlab.gcf())
    tms = tmesh.mlab_source
    for i in range(1, v.shape[0]):
        fName = '{:0>5}'.format(i + 1)
        tms.set(x=v[i, 0, :], y=v[i, 1, :], z=v[i, 2, :])
        mlab.savefig(saveDir + fName + '.png', figure=mlab.gcf())
    def mplot_surface(self, ures=8, vres=8, figax=False, **kwargs):
        """Plot the enclosing surfaces of the volume using Mayavi's `mesh()` function

        Parameters
        ----------
        ures, vres : int
            Specifies the oversampling of the original
            volume in u and v directions. For example:
            if `ures` = 2, and `self.u` = [0, 1, 2, 3],
            then the surface will be resampled at
            [0, 0.5, 1, 1.5, 2, 2.5, 3] prior to
            plotting.

        kwargs : dict
            See Mayavi docs for `mesh()`

        Returns
        -------
            None
        """
        from mayavi import mlab
        from matplotlib.colors import ColorConverter

        if not 'color' in kwargs:
            # Generate random color
            cvec = np.random.rand(3)
            cvec /= math.sqrt(cvec.dot(cvec))
            kwargs['color'] = tuple(cvec)
        else:
            # The following will convert text strings representing
            # colors into their (r, g, b) equivalents (which is
            # the only way Mayavi will accept them)
            from matplotlib.colors import ColorConverter
            cconv = ColorConverter()
            if kwargs['color'] is not None:
                kwargs['color'] = cconv.to_rgb(kwargs['color'])

        # Make new u and v values of (possibly) higher resolution
        # the original ones.
        hru, hrv = self._resample_uv(ures, vres)
        # Sample the surface at the new u, v values and plot
        meshpts1 = self.ev(hru, hrv, np.max(self.l))
        meshpts2 = self.ev(hru, hrv, np.min(self.l))

        if figax is None:
            m1 = mlab.mesh(*meshpts1, **kwargs)
            m2 = mlab.mesh(*meshpts2, **kwargs)

            # Turn off perspective
            fig = mlab.gcf()
            fig.scene.camera.trait_set(parallel_projection=1)
            return fig
        else:
            fig, ax = figax
            m1 = ax.plot_surface(*meshpts1, **kwargs)
            m2 = ax.plot_surface(*meshpts2, **kwargs)
Beispiel #50
0
def anim():
    f = mlab.gcf()
    while True:
        for (x, y, z) in zip(xs, ys, zs):
            print('Updating scene...')
            plt.mlab_source.x[0] = x
            plt.mlab_source.y[0] = y
            plt.mlab_source.z[0] = z
            f.scene.render()
            yield
Beispiel #51
0
 def anim():
     f = mlab.gcf()
     for count, i in enumerate(range(2, 361, 2)):
         #while 1:
         f.scene.camera.azimuth(degree_step)
         f.scene.render()
         mlab.savefig(
             '/Users/jessebrown/Desktop/mayavi_figs/r_hipp_network%03d.png'
             % count)
         yield
Beispiel #52
0
 def anim():
     f = mlab.gcf()
     ms = grd.mlab_source
     while True:
         for i in range(1, z.shape[0]):
             #                    print('Updating scene...')
             scalars = z[i, :]
             ms.trait_set(scalars=scalars)
             date.trait_set(text=t[i])
             yield
def problem8():
    opener = urllib.URLopener()
    opener.retrieve('https://s3.amazonaws.com/storage.enthought.com/www/sample_data/N36W113.hgt.zip', 'N36W113.hgt.zip')
    data = np.fromstring(zipfile.ZipFile('N36W113.hgt.zip').read('N36W113.hgt'), '>i2').reshape((3601, 3601)).astype('float32')
    data = data[:1000, 900:1900]
    data[data == -32768] = data[data>0].min()
    mlab.figure(size=(400, 320), bgcolor = (.16, .28, .46))
    mlab.surf(data, colormap="gist_earth", warp_scale=.2, vmin=1200, vmax=1610)
    mlab.view(-5.9, 83, 570, [5.3, 20, 238])
    return mlab.gcf()
Beispiel #54
0
def run_mlab_file(filename, image_file):
    ## XXX: Monkey-patch mlab.show, so that we keep control of the
    ## the mainloop
    old_show = mlab.show

    def my_show(func=None):
        pass

    mlab.show = my_show
    mlab.clf()
    e = mlab.get_engine()
    e.close_scene(mlab.gcf())
    exec(compile(open(filename).read(), filename, 'exec'),
         {'__name__': '__main__'})
    mlab.savefig(image_file)
    size = mlab.gcf().scene.get_size()
    for scene in e.scenes:
        e.close_scene(scene)
    mlab.show = old_show
Beispiel #55
0
def plot_ionosphere(fld, radius=1.063, crd_system="mhd", figure=None,
                    bounding_lat=0.0, **kwargs):
    """Plot an ionospheric field

    Args:
        fld (Field): Some spherical (phi, theta) / (lot, lat) field
        radius (float): Defaults to 1Re + 400km == 1.063Re
        crd_system (str): Either 'gse' or 'mhd'
        figure (mayavi.core.scene.Scene): specific figure, or
            :py:func:`mayavi.mlab.gcf`
        bounding_lat (float): Description
        **kwargs: passed to :py:func:`mayavi.mlab.mesh`

    Raises:
        ValueError: Description
    """
    if figure is None:
        figure = mlab.gcf()

    if crd_system == "mhd":
        roll = 0.0
    elif crd_system == "gse":
        roll = 180.0
    else:
        raise ValueError("crd_system == '{0}' not understood"
                         "".format(crd_system))

    nphi, ntheta = fld.shape
    sphere = viscid.Sphere([0, 0, 0], r=radius, ntheta=ntheta, nphi=nphi,
                           theta_phi=False, roll=roll)
    verts, arr = sphere.wrap_mesh(fld.data)

    if 'name' not in kwargs:
        kwargs['name'] = fld.name
    m = mlab.mesh(verts[0], verts[1], verts[2], scalars=arr, figure=figure,
                  **kwargs)

    if bounding_lat:
        rp = 1.5 * radius
        z = radius * np.cos((np.pi / 180.0) * bounding_lat)
        clip = mlab.pipeline.data_set_clipper(m.module_manager.parent)
        clip.widget.widget.place_widget(-rp, rp, -rp, rp, -z, z)
        clip.widget.update_implicit_function()
        clip.widget.widget.enabled = False
        insert_filter(clip, m.module_manager)
        # m.module_manager.parent.parent.filter.auto_orient_normals = True
    else:
        pass
        # m.module_manager.parent.filter.auto_orient_normals = True
    m.actor.mapper.interpolate_scalars_before_mapping = True

    m.module_manager.scalar_lut_manager.lut_mode = 'RdBu'
    m.module_manager.scalar_lut_manager.reverse_lut = True

    return m
Beispiel #56
0
def savefig(*args, **kwargs):
    """Wrap mayavi.mlab.savefig with offscreen hack"""
    fig = mlab.gcf()
    prev_offscreen_state = fig.scene.off_screen_rendering
    if sys.platform != "darwin":
        fig.scene.off_screen_rendering = True

    mlab.savefig(*args, **kwargs)

    if fig.scene.off_screen_rendering != prev_offscreen_state:
        fig.scene.off_screen_rendering = prev_offscreen_state
Beispiel #57
0
def clf(figure=None):
    """Clear source data, then clear figure

    Args:
        figure (mayavi.core.scene.Scene): specific figure, or
            :py:func:`mayavi.mlab.gcf`
    """
    if not figure:
        figure = mlab.gcf()
    clear_data(figure)
    mlab.clf(figure)