Esempio n. 1
0
    def update_scene():

        #  clear figure
        mlab.clf(fig1)

        # Plot new data feature
        points = all_points[file_i]

        # Rescale points for visu
        points = (points * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0

        # Show point clouds colorized with activations
        activations = mlab.points3d(points[:, 0],
                                    points[:, 1],
                                    points[:, 2],
                                    points[:, 2],
                                    scale_factor=3.0,
                                    scale_mode='none',
                                    figure=fig1)

        # New title
        mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
        text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->'
        mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
        mlab.orientation_axes()

        return
Esempio n. 2
0
def plot_matrix(connectmat_file, centers_file, threshold_pct=5, weight_edges=False,
                node_scale_factor=2, edge_radius=.5, resolution=8, name_scale_factor=1,
                names_file=None, node_indiv_colors=[], highlight_nodes=[], fliplr=False):
    """
    Given a connectivity matrix and a (x,y,z) centers file for each region, plot the 3D network
    """
    matrix = core.file_reader(connectmat_file)
    nodes = core.file_reader(centers_file)
    if names_file:
        names = core.file_reader(names_file,1)
    num_nodes = len(nodes)
    edge_thresh_pct = threshold_pct / 100.0
    matrix_flat = np.array(matrix).flatten()
    edge_thresh = np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
    
    matrix = core.file_reader(connectmat_file)
    ma = np.array(matrix)

    thresh = scipy.stats.scoreatpercentile(ma.ravel(),100-threshold_pct)
    ma_thresh = ma*(ma > thresh)
    
    if highlight_nodes:
        nr = ma.shape[0]
        subset_mat = np.zeros((nr, nr))
        for i in highlight_nodes:
            subset_mat[i,:] = 1
            subset_mat[:,i] = 1
        ma_thresh = ma_thresh * subset_mat
        
    if fliplr:
        new_nodes = []
        for node in nodes:
            new_nodes.append([45-node[0],node[1],node[2]]) # HACK
        nodes = new_nodes
    
    mlab.figure(bgcolor=(1, 1, 1), size=(400, 400))
    for count,(x,y,z) in enumerate(nodes):
        if node_indiv_colors:
            mlab.points3d(x,y,z, color=colors[node_indiv_colors[count]], scale_factor=node_scale_factor, resolution=resolution)
        else:
            mlab.points3d(x,y,z, color=(0,1,0), scale_factor=node_scale_factor, resolution=resolution)
        if names_file:
            width = .025*name_scale_factor*len(names[count])
            print width
            print names[count]
            mlab.text(x, y,names[count], z=z,width=.025*len(names[count]),color=(0,0,0))
    for i in range(num_nodes-1):    
        x0,y0,z0 = nodes[i]
        for j in range(i+1, num_nodes):
            #if matrix[i][j] > edge_thresh:
            if ma_thresh[i][j] > edge_thresh:
                x1,y1,z1 = nodes[j]
                if weight_edges:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=matrix[i][j]/matrix_flat.max(),
                            color=(1,1,1))
                else:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=edge_radius,
                            color=(1,1,1))
Esempio n. 3
0
 def add_text(self, string):
     """
     Adds some interesting text to the current mayavi-canvas.
     :param string: String to put in the image
     """
     c = (1.,1.,1.) if self.color_scheme == 'dark' else (0.,0.,0.)
     mlab.text(0.025,0.025, string, color=c, width=0.3)
Esempio n. 4
0
def mayaView(num, path="./data"):
    """
    num is a str eg. "20-1", "400"
    loads images from ./data
    """
    assert type(num) == str
    x = np.load(path + '/xdata{}.dat'.format(num))
    y = np.load(path + '/ydata{}.dat'.format(num))
    z = np.load(path + '/zdata{}.dat'.format(num))
    density = np.load(path + '/density{}.dat'.format(num))

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

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

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

    mlab.colorbar(orientation='vertical')
    mlab.axes()
    mlab.savefig(
        '/home/ada/Documents/SUTD/Term 3/Physical Chemistry/Schrodinger-Assignment/Images/'
        + num + '.png')
Esempio n. 5
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!
def do_test(lines, scalars, show=False, txt=""):
    viscid.logger.info('--> ' + txt)
    title = txt + '\n' + "\n".join(
        textwrap.wrap("scalars = {0}".format(scalars), width=50))

    try:
        from viscid.plot import vpyplot as vlt
        from matplotlib import pyplot as plt

        vlt.clf()
        vlt.plot_lines(lines, scalars=scalars)
        plt.title(title)
        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if show:
            vlt.show()
    except ImportError:
        pass

    try:
        from mayavi import mlab
        vlab, _ = get_mvi_fig()

        vlab.clf()
        vlab.plot_lines3d(lines, scalars=scalars)
        vlab.fancy_axes()
        mlab.text(0.05, 0.05, title)
        vlab.savefig(next_plot_fname(__file__, series='q3'))
        if show:
            vlab.show(stop=True)
    except ImportError:
        pass
Esempio n. 7
0
def make_frame(t):
    i = int(np.ceil(t * speed_factor / dt))
    source2 = runname + '_{0:04}'.format(i) + '.asc'
    # Load the dem into a numpy array
    arr = np.loadtxt(source2, skiprows=6)

    for i in range(0, ny):

        H_cent[i, 0:nx] = arr[i, 0:nx]

    W_cent = B_cent + H_cent
    idx = np.ma.masked_where(H_cent == -9999, W_cent)
    W_cent[np.where(np.ma.getmask(idx) == True)] = np.nan

    mlab.clf()  # clear the figure (to reset the colors)
    topo = mlab.surf(xs, ys, B_cent, color=(0.5, 0.6, 0.7))
    mlab.outline(topo, color=(.7, .7, .7))
    surf = mlab.surf(xs, ys, W_cent + 1.e-1, color=(0.4, 0.4, 0.4))
    surf.actor.property.interpolation = 'phong'
    surf.actor.property.specular = 1.0
    surf.actor.property.specular_power = 50
    mlab.text(-10,
              0,
              't=' + str(t * speed_factor) + 's',
              z=10,
              width=0.15,
              color=(0, 0, 0))
    return mlab.screenshot(antialiased=True)
Esempio n. 8
0
    def setup(self):
        print('running setup')
        self.generate_color_and_size()
        self.fig = mlab.figure(figure=mlab.gcf())
        self.fig.scene.interactor.interactor_style = tvtk.InteractorStyleTerrain(
        )
        self.update_plot()

        # The general mouse based clicker - which reveals point information
        # of the known and labelled datapoints
        self.info_picker = self.fig.on_mouse_pick(self.view_point_information)
        self.info_picker.tolerance = 0.01

        # picker which allows to re-assign the point trajectory number
        self.reassign_picker = self.fig.on_mouse_pick(self.reassign_callback,
                                                      type='point',
                                                      button='Right')
        self.reassign_picker.tolerance = 0.01

        # outline which indicates which point has been clicked on
        self.outline = mlab.outline(line_width=3, color=(0.9, 0.9, 0.9))

        self.outline.outline_mode = 'cornered'
        self.outline.bounds = (0.05, 0.05, 0.05, 0.05, 0.05, 0.05)

        self.click_text = mlab.text(0.8, 0.8, 'STARTING INFO')
        self.traj_text = mlab.text(0.8, 0.6, 'Trajectory number')
        self.pointtype_text = mlab.text(0.8, 0.87, 'Point Type')
        self.pointtype_info = mlab.text(0.8, 0.82, '')

        mlab.axes()
Esempio n. 9
0
 def _render_mesh(self, scaled_distances_between_meshes, type_cmap,
                  scalar_range, show_statistics):
     from mayavi import mlab
     # v = mlab.figure(figure=figure_name, size=size,
     #                bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
     src = mlab.pipeline.triangular_mesh_source(
         self.points[:, 0],
         self.points[:, 1],
         self.points[:, 2],
         self.trilist,
         scalars=scaled_distances_between_meshes)
     surf = mlab.pipeline.surface(src, colormap=type_cmap)
     # When font size bug resolved, uncomment
     # cb=mlab.colorbar(title='Distances in mm',
     # orientation='vertical', nb_labels=5)
     # cb.title_text_property.font_size = 20
     # cb.label_text_property.font_family = 'times'
     # cb.label_text_property.font_size=10
     cb = mlab.colorbar(orientation='vertical', nb_labels=5)
     cb.data_range = scalar_range
     cb.scalar_bar_representation.position = [0.8, 0.15]
     cb.scalar_bar_representation.position2 = [0.15, 0.7]
     text = mlab.text(0.8, 0.85, 'Distances in mm')
     text.width = 0.20
     if show_statistics:
         text2 = mlab.text(
             0.5, 0.02, 'Mean error {:.3}mm \nMax error {:.3}mm \
                       '.format(scaled_distances_between_meshes.mean(),
                                scaled_distances_between_meshes.max()))
         text2.width = 0.20
     surf.module_manager.scalar_lut_manager.reverse_lut = True
     # perhaps we shouud usew kwargs
     # if camera_settings is None:
     mlab.gcf().scene.z_plus_view()
Esempio n. 10
0
        def update_scene():

            #  clear figure
            mlab.clf(fig1)

            # Plot new data feature
            points = all_points[file_i]
            responses = all_responses[file_i]
            min_response, max_response = np.min(responses), np.max(responses)
            responses = (responses - min_response) / (max_response - min_response)

            # Rescale points for visu
            points = (points * 1.5 / config.in_radius + np.array([1.0, 1.0, 1.0])) * 50.0

            # Show point clouds colorized with activations
            activations = mlab.points3d(points[:, 0],
                                        points[:, 1],
                                        points[:, 2],
                                        responses,
                                        scale_factor=3.0,
                                        scale_mode='none',
                                        vmin=0.1,
                                        vmax=0.9,
                                        figure=fig1)

            # New title
            mlab.title(feature_files[file_i], color=(0, 0, 0), size=0.3, height=0.01)
            text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->'
            mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
            mlab.orientation_axes()

            return
Esempio n. 11
0
def plot_matrix_metric(connectmat_file,centers_file,threshold_pct,grp_metrics=None,node_metric='bc',
                       weight_edges=0,node_scale_factor=2,edge_radius=.5,resolution=8,name_scale_factor=1,names_file=0,
                       red_nodes=None):
    """
    Given a connectivity matrix and a (x,y,z) centers file for each region, plot the 3D network
    """
    matrix=core.file_reader(connectmat_file)
    nodes=core.file_reader(centers_file)
    if names_file:
        names = core.file_reader(names_file,1)
    num_nodes = len(nodes)
    edge_thresh_pct = threshold_pct / 100.0
    matrix_flat=np.array(matrix).flatten()
    edge_thresh=np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
    
    if grp_metrics: # regional metrics caclulated elsewhere, loaded in
        node_colors = {}     # define colors for each metric
        node_colors['s'] = (1,  0.733,  0)
        node_colors['cc'] = (0.53, 0.81, 0.98)
        node_colors['bc'] = (0.5,  1,  0)
        node_colors['eloc'] = (1,  0 ,  1)
        node_colors['ereg'] = (1,  1,  0)
        
        node_metrics={}
        metrics = np.array(core.file_reader(grp_metrics))
        cols = np.shape(metrics)[1]
        for i in range(cols):
            colmean = np.mean(metrics[:,i])
            colscale = 2 / colmean
            metrics[:,i] = metrics[:,i] * colscale # make node mean size 2
        node_metrics['s'] = metrics[:,0] # strength
        node_metrics['cc'] = metrics[:,1] # clustering coefficient
        node_metrics['bc'] = metrics[:,2] # betweenness centrality
        node_metrics['eloc'] = metrics[:,3] # local efficiency
        node_metrics['ereg'] = metrics[:,4] # regional efficiency
    
    mlab.figure(bgcolor=(1, 1, 1), size=(800, 800))
    for count,(x,y,z) in enumerate(nodes):
        if grp_metrics:
            mlab.points3d(x,y,z, color=node_colors[node_metric],
                          scale_factor=node_metrics[node_metric][count], resolution=resolution)
        else:
            mlab.points3d(x,y,z, color=(0,1,0), scale_factor=node_scale_factor, resolution=resolution)
        if names_file:
            mlab.text(x, y,names[count], z=z,width=.02*name_scale_factor*len(names[count]),color=(0,0,0))
    
    for i in range(num_nodes-1):    
        x0,y0,z0=nodes[i]
        for j in range(i+1, num_nodes):
            if matrix[i][j] > edge_thresh:
                x1,y1,z1=nodes[j]
                if weight_edges:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=matrix[i][j]/matrix_flat.max(),
                            color=(1,1,1))
                else:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=edge_radius,
                            color=(1,1,1))
Esempio n. 12
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()
Esempio n. 13
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!
Esempio n. 14
0
 def UpdatedSceneSettings(self):
     self.updatedScene.interactor.interactor_style = \
         tvtk.InteractorStyleTerrain()
     # The distance value is set in such a way that the entire surface should be visible without need to zoom out.
     self.updatedScene.scene.mlab.view(30, 60, distance=2.5 * 512)
     mlab.surf(np.zeros([2, 2]),
               figure=self.updatedScene.mayavi_scene,
               opacity=0)  # Dummy surface
     mlab.text(0.6, 0.9, 'Eroded', width=0.4)
Esempio n. 15
0
def draw_dots3d(dots, edges, fignum, clear=True,
                title='',
                size=(1024, 768), graph_colormap='viridis',
                bgcolor=(1, 1, 1),
                node_color=(0.3, 0.65, 0.3), node_size=0.01,
                edge_color=(0.3, 0.3, 0.9), edge_size=0.003,
                text_size=0.14, text_color=(0, 0, 0), text_coords=[0.84, 0.75], text={},
                title_size=0.3,
                angle=get_ra()):

    # https://stackoverflow.com/questions/17751552/drawing-multiplex-graphs-with-networkx

    # numpy array of x, y, z positions in sorted node order
    xyz = shrink_to_3d(dots)

    if fignum == 0:
        mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)

    # Mayavi is buggy, and following code causes sockets leak.
    #if mlab.options.offscreen:
    #    mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)
    #elif fignum == 0:
    #    mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)

    if clear:
        mlab.clf()

    # the x,y, and z co-ordinates are here
    # manipulate them to obtain the desired projection perspective

    pts = mlab.points3d(xyz[:, 0], xyz[:, 1], xyz[:, 2],
                        scale_factor=node_size,
                        scale_mode='none',
                        color=node_color,
                        #colormap=graph_colormap,
                        resolution=20,
                        transparent=False)

    mlab.text(text_coords[0], text_coords[1], '\n'.join(['{} = {}'.format(n, v) for n, v in text.items()]), width=text_size)

    if clear:
        mlab.title(title, height=0.95)
        mlab.roll(next(angle))
        mlab.orientation_axes(pts)
        mlab.outline(pts)

    """
    for i, (x, y, z) in enumerate(xyz):
        label = mlab.text(x, y, str(i), z=z,
                          width=text_size, name=str(i), color=text_color)
        label.property.shadow = True
    """

    pts.mlab_source.dataset.lines = edges
    tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
    mlab.pipeline.surface(tube, color=edge_color)
def create_animation(filename): # create an animation from a saved file using mayavi (not complete)

    f_pointer = h5py.File(filename, "a")
    
    res_alpha = f_pointer["parres/particles"][:]
    N_size = f_pointer["parameters/control"][0,0]
    N_grid = f_pointer["parameters/control"][0,1]
    N_rings = f_pointer["parameters/control"][0,2]
    N_particles = f_pointer["parameters/control"][0,3]
    N_step = f_pointer["parameters/control"][0,4]
    h = f_pointer["parameters/control"][0,5]
    t_step = f_pointer["parameters/control"][0,6]
    t_total = f_pointer["parameters/control"][0,7]
    t_time= f_pointer["parameters/control"][0,8]
    kin_vis = f_pointer["parameters/control"][0,9]
    ring=[]
    for i in range(0,N_rings):
        R = f_pointer["parameters/rings"][i,0]
        r = f_pointer["parameters/rings"][i,1]
        x_pos = f_pointer["parameters/rings"][i,2]
        y_pos = f_pointer["parameters/rings"][i,3]
        z_pos = f_pointer["parameters/rings"][i,4]
        x_ang = f_pointer["parameters/rings"][i,5]
        y_ang = f_pointer["parameters/rings"][i,6]
        Re = f_pointer["parameters/rings"][i,7]
        N_phi = f_pointer["parameters/rings"][i,8]
        N_d = f_pointer["parameters/rings"][i,9]
        N_p = f_pointer["parameters/rings"][i,10]
        color = (float(f_pointer["parameters/rings"][i,11]),float(f_pointer["parameters/rings"][i,12]),float(f_pointer["parameters/rings"][i,13]))
        ring.append(ring_val(R, r, x_pos, y_pos, z_pos, x_ang, y_ang, Re, N_phi, N_d, int(N_p), color))
    f_pointer.close()
    
    
    
    N = 0
    """for i in range(0,N_rings):
      
        fig = mlab.points3d(res_alpha[0,N:N + ring[i].N_p - 1,0,0], res_alpha[0,N:N + ring[i].N_p - 1,1,0], res_alpha[0,N:N + ring[i].N_p - 1,2,0], scale_factor=0.1, color = ring[i].color)
        N = N + ring[i].N_p"""
    fig = mlab.points3d(res_alpha[0,:,0,0], res_alpha[0,:,1,0], res_alpha[0,:,2,0], scale_factor=0.1, color = (0,1,1))
    mlab.axes(extent=[0,N_size,0,N_size,0,N_size])
    info = "P=" + str(int(N_particles)) + "\nG=" + str(int(N_grid)) + "\nt=" + str(0)
    mlab.text(0.1,0.1,info)

    @mlab.animate(delay=40, ui=True)
    def anim():
        for i in range(0,N_step):
            
            fig.mlab_source.set(x=res_alpha[0,:,0,i], y=res_alpha[0,:,1,i], z=res_alpha[0,:,2,i])
                
            yield

    anim()
    mlab.show()
    print "check"
Esempio n. 17
0
 def test_text(self):
     """ Test the text module.
     """
     data = np.random.random((3, 3, 3))
     src = mlab.pipeline.scalar_field(data)
     # Some smoke testing
     mlab.text(0.1, 0.9, 'foo')
     mlab.text(3, 3, 'foo', z=3)
     mlab.title('foo')
     # Check that specifying 2D positions larger than 1 raises an
     # error
     self.assertRaises(ValueError, mlab.text, 0, 1.5, 'test')
 def test_text(self):
     """ Test the text module.
     """
     data = np.random.random((3, 3, 3))
     src = mlab.pipeline.scalar_field(data)
     # Some smoke testing
     mlab.text(0.1, 0.9, 'foo')
     mlab.text(3, 3, 'foo', z=3)
     mlab.title('foo')
     # Check that specifying 2D positions larger than 1 raises an
     # error
     self.assertRaises(ValueError, mlab.text, 0, 1.5, 'test')
Esempio n. 19
0
def add_legend():
    x = 0.01
    y = 0.95
    width = 0.05

    for filename in colors.keys():
        color = colors[filename]
        name = filename.split("/")[-1]

        mlab.text(x, y, "TT", width=width, color=color)
        mlab.text(x + 0.03, y, name, width=width)
        y -= 0.05
def create_plot_mayavi(alpha,ring,control): # create figure with mayavi

    N = 0

    for i in range(0,control.N_rings):
        mlab.points3d(alpha[N:N + ring[i].N_p - 1,0,0], alpha[N:N + ring[i].N_p - 1,1,0], alpha[N:N + ring[i].N_p - 1,2,0], scale_factor=0.1, color = ring[i].color)
        N = N + ring[i].N_p
    
    mlab.axes(extent=[0,control.N_size,0,control.N_size,0,control.N_size])
    info = "P=" + str(control.N_particles) + "\nG=" + str(control.N_grid) + "\nt=" + str(control.t_time)
    mlab.text(0.1,0.1,info)
    
    mlab.show()
Esempio n. 21
0
def plot_orbital_list(orbital_idx, C, bases, postfix='', **kwargs):
    """ Visualizing all orbitals
    """

    for j, i in enumerate(orbital_idx):
        if i - 1 >= C.shape[1] or i - 1 < 0:
            print('Orbital %d does not exist. Skipping' % i)
        else:
            plot_orbital(C[:, i - 1], bases, color=cm.tab10(j)[:3], **kwargs)
            mlab.text(0.05,
                      0.1 * j,
                      str(i) + postfix,
                      width=0.2,
                      color=cm.tab10(j)[:3])
Esempio n. 22
0
 def Animate(self, filename):
     mlab.clf()
     extent1 = (0, 20, 0, 20,0, 10)
     s = mlab.surf(self.x , self.y, self.u[1:-1,1:-1], colormap="Blues", warp_scale=5,extent=extent1)
     mlab.axes(s, color=(.7, .7, .7), extent=extent1, ranges=(0, 20, 0, 20, 0, 10), 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" % self.t)
     mlab.view(142, -72, 50)
     f = mlab.gcf()
     camera = f.scene.camera
     camera.yaw(0)
     mlab.savefig(filename)
Esempio n. 23
0
    def show_variable_timecourse(self, var, time_point, start_value,
                                 end_value):
        """Show an animation of all the section that have 
        the recorded variable among time"""

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

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

        self.redraw_color(new_scalar, var)

        if not self.colorbar:
            self.colorbar = mlab.colorbar(orientation='vertical')
            time_point_string = "%.3f" % time_point
            self.timelabel = mlab.text(0.05,
                                       0.05,
                                       time_point_string,
                                       width=0.05)

        self.colorbar.data_range = [start_value, end_value]
        time = self.manager.groups['t'][time_point]
        time_point_string = "%.3f" % round(time, 3)
        self.timelabel.text = time_point_string
        self.mayavi.visualization.scene.disable_render = False
Esempio n. 24
0
def title(text, **kwargs):
    """ textproperty options
    textproperty={
      'background_color': (0.0, 1.0, 0.0),
      'background_opacity': 0.1143,
      'bold': 1,
      'color': (0.0, 0.0, 0.0),
      'font_family': 'arial',
      'font_family_min_value': 0,
      'font_file': None,
      'font_size': 16,
      'italic': 0,
      'italic_': 0,
      'justification': 'centered',
      'line_offset': 0.0,
      'line_spacing': 1.1,
      'opacity': 1.0,
      'orientation': 0.0,
      'shadow': 1,
      'shadow_offset': array([ 1, -1]),
      'vertical_justification': 'top'
    }
  """
    justification = kwargs.pop('justification', 'center')
    vertical_justification = kwargs.pop('vertical_justification', 'top')
    textproperty = kwargs.pop('textproperty', dict())
    kwargs['color'] = check_color(kwargs.pop('color', 'White'))
    t = mlab.text(0.5, 0.99, text, **kwargs)
    t.actor.text_scale_mode = 'none'
    t.actor.text_property.justification = justification
    t.actor.text_property.vertical_justification = vertical_justification
    if len(textproperty):
        t.actor.text_property.trait_set(**textproperty)
    return t
Esempio n. 25
0
    def show_variable_timecourse(self, var, time_point, start_value, end_value):
        """Show an animation of all the section that have 
        the recorded variable among time"""

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

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

        self.redraw_color(new_scalar, var)

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

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

        self.mayavi.visualization.scene.disable_render = False
Esempio n. 26
0
    def surface_timeseries(surface, data, step=1):
        """
        
        """
        fig = mlab.figure(figure="surface_timeseries", fgcolor=(0.5, 0.5, 0.5))
        #Plot an initial surface and colourbar #TODO: Change to use plot_surface function, see below.
        surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0],
                                         surface.vertices[:, 1],
                                         surface.vertices[:, 2],
                                         surface.triangles,
                                         scalars=data[0, :],
                                         vmin=data.min(), vmax=data.max(),
                                         figure=fig)
        mlab.colorbar(object=surf_mesh, orientation="vertical")

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

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

        #Movie
        k = 0
        while 1:
            if abs(k) >= tpts:
                k = 0
            surf.set(scalars=data[k, :])
            time_step.set(text=("%s of %s" % (str(k), str(tpts))))
            k += step
            yield
        mlab.show()
def label_init():
  from mayavi.mlab import points3d
  obj = points3d(0., 0., 0., scale_factor=0.01, color=(0., 0., 0.))
  global actlbl
  actlbl = text(.4, .1, 'odorname', width=.15)
  actlbl.text = ''
  obj.remove()
    def surface_timeseries(surface, data, step=1):
        """
        
        """
        fig = mlab.figure(figure="surface_timeseries", fgcolor=(0.5, 0.5, 0.5))
        #Plot an initial surface and colourbar #TODO: Change to use plot_surface function, see below.
        surf_mesh = mlab.triangular_mesh(surface.vertices[:, 0],
                                         surface.vertices[:, 1],
                                         surface.vertices[:, 2],
                                         surface.triangles,
                                         scalars=data[0, :],
                                         vmin=data.min(), vmax=data.max(),
                                         figure=fig)
        mlab.colorbar(object=surf_mesh, orientation="vertical")

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

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

        #Movie
        k = 0
        while 1:
            if abs(k) >= tpts:
                k = 0
            surf.set(scalars=data[k, :])
            time_step.set(text=("%s of %s" % (str(k), str(tpts))))
            k += step
            yield
        mlab.show(stop=True)
def draw_coordinate_system_axes(fig, coordinate_system, offset=0.0, scale=1.0, draw_labels=True):
    points, lengths = coordinate_system_arrows(coordinate_system, offset=offset, scale=scale)
    mlab.figure(fig, bgcolor=fig.scene.background)
    arrows = mlab.quiver3d(
        points[:, 0],
        points[:, 1],
        points[:, 2],
        lengths[0, :],
        lengths[1, :],
        lengths[2, :],
        scalars=np.array([3, 2, 1]),
        mode="arrow",
    )
    arrows.glyph.color_mode = "color_by_scalar"
    arrows.glyph.glyph.scale_factor = scale
    data = arrows.parent.parent
    data.name = coordinate_system.name
    glyph_scale = arrows.glyph.glyph.scale_factor * 1.1
    # label_col = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    labels = []
    if draw_labels:
        for i in range(3):
            labels.append(
                mlab.text(
                    points[i, 0] + glyph_scale * coordinate_system.basis[i, 0],
                    points[i, 1] + glyph_scale * coordinate_system.basis[i, 1],
                    coordinate_system.labels[i],
                    z=points[i, 2] + glyph_scale * coordinate_system.basis[i, 2],
                    # color=label_col[i],
                    width=0.1 * scale,
                )
            )
    return arrows, labels
 def update_scene():
     mlab.clf(fig1)  # 清空figure
     vis_points = points[file_i]  # 取出要显示的点云
     vis_points = (vis_points * 1.5 + np.array([1.0, 1.0, 1.0])) * 50  # 对点云进行缩放
     # show point clouds colorized with activations
     activations = mlab.points3d(vis_points[:, 0],
                                 vis_points[:, 1],
                                 vis_points[:, 2],
                                 vis_points[:, 2],
                                 scale_factor=3.0,
                                 scale_mode='none',
                                 figure=fig1)
     mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
     text = '<--- (press g for previous' + 50 * '' + '(press h for next)---->'
     mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
     mlab.orientation_axes()
     return
Esempio n. 31
0
 def draw_axis_name(self, axis_name):
     global_axis_name = self.controller.get_global_axis_name(axis_name)
     if global_axis_name == 'w':
         width = 0.06
     else:
         width = 0.04
     t = mlab.text(0.01, 0.9, global_axis_name, width=width, color=(1, 0, 0))
     return t
Esempio n. 32
0
def plot_mesh(coord_array, tri_array, plnsrf):
    """ plot_mesh plots an unsorted triangular part mesh from xyz coordinates and triangle connectivity
    :param coord_array: xyz coordinates per vertex in array of shape=(#points, 3)
    :param tri_array: vertex connection indices of the part in array of shape=(#triangles, 3)
    :return:
    """
    mlab.figure(figure="Mesh", bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))

    # Create black wireframe mesh
    wire_mesh = mlab.triangular_mesh(coord_array[:, 0],
                                     coord_array[:, 1],
                                     coord_array[:, 2],
                                     tri_array,
                                     scalars=None,
                                     line_width=0.1,
                                     representation='wireframe',
                                     color=(0, 0, 0),
                                     opacity=0.05)

    # Create face coloring
    wire_mesh.mlab_source.dataset.cell_data
    wire_mesh.mlab_source.dataset.cell_data.scalars = np.ones(
        shape=(tri_array.shape[0]))
    wire_mesh.mlab_source.dataset.cell_data.scalars.name = 'Cell data'
    wire_mesh.mlab_source.update()

    mesh = mlab.pipeline.set_active_attribute(wire_mesh,
                                              cell_scalars='Cell data')
    surf = mlab.pipeline.surface(mesh, colormap='jet')

    # Retrieve the LUT colormap of the surf object. (256x4)
    # this is an array of (R, G, B, A) values (each in range 0-255)
    lut = surf.module_manager.scalar_lut_manager.lut.table.to_array()

    # Modify lut for single green color
    lut[:, 0] = np.ones((lut.shape[0])) * 75
    lut[:, 1] = np.ones((lut.shape[0])) * 173
    lut[:, 2] = np.ones((lut.shape[0])) * 137
    lut[:, 3] = np.ones((lut.shape[0])) * 255

    # Now use this colormap
    surf.module_manager.scalar_lut_manager.lut.table = lut

    #display the number of planes
    for pn in range(1, np.amax(plnsrf) + 1):
        center = np.mean(coord_array[np.nonzero(plnsrf == pn)[0], :], axis=0)

        label = mlab.text(
            center[0],
            center[1],
            '%d' % pn,
            z=center[2],
            width=0.05,
        )
        label.property.shadow = True

    # Show plot
    mlab.show()
Esempio n. 33
0
def plot_matrix_path(connectmat_file,centers_file,paths_file,path_num=0,threshold_pct=5,weight_edges=False,
                     node_scale_factor=2,edge_radius=.5,resolution=8,name_scale_factor=1,names_file=0):
    """
    Given a connectivity matrix and a (x,y,z) centers file for each region, plot the 3D network;
    paths file contains columns listing nodes contained in path
    """
    matrix=core.file_reader(connectmat_file)
    nodes=core.file_reader(centers_file)
    paths=zip(*core.file_reader(paths_file))
    path=paths[path_num]
    path_pairs=zip(path[0:len(path)-1],path[1:])
    print path_pairs
    if names_file:
        names=core.file_reader(names_file)
    num_nodes=len(nodes)
    edge_thresh_pct=(float(threshold_pct)/100)
    matrix_flat=np.array(matrix).flatten()
    edge_thresh=np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
    mlab.figure(bgcolor=(1, 1, 1), size=(400, 400))
    for count,(x,y,z) in enumerate(nodes):
        mlab.points3d(x,y,z, color=(0,1,0), scale_factor=node_scale_factor, resolution=resolution)
        if names_file:
            width=.025*name_scale_factor*len(names[count])
            mlab.text(x, y,names[count], z=z,width=.025*name_scale_factor,color=(0,0,0))
    for i in range(num_nodes-1):    
        x0,y0,z0=nodes[i]
        for j in range(i+1, num_nodes): 
            if matrix[i][j] > edge_thresh:
                x1,y1,z1=nodes[j]
                if weight_edges:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=matrix[i][j]/matrix_flat.max(),
                            color=(1,1,1))
                else:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=edge_radius,
                            color=(1,1,1))
    for n1,n2 in path_pairs:
        n1=int(n1)
        n2=int(n2)
        x0,y0,z0=nodes[n1]
        x1,y1,z1=nodes[n2]
        mlab.plot3d( [x0,x1], [y0,y1], [z0,z1],
                    tube_radius=1,
                    color=(0,0,1))
def plotComparePaths_t_error_3DSurface(fix_path_list,
                                       tvec_error_mean_list_AllPaths,
                                       grid_reso=0.1,
                                       width=6,
                                       height=3):
    """
    Plot the measured paths with 3D surface(like mountain, high mountain means big error, low mountain means small error)
    1.Figure:
    :param xyError_list_AllPaths:
    :param width: 3 [m]
    :param height: 6 [m]
    :param grid_reso: default 0.1 [m]
    :return:
    """
    #TODO
    path_num = len(fix_path_list)

    gridX = int(height / grid_reso)
    gridY = int(width / grid_reso)

    X, Y = np.mgrid[0:height:grid_reso, 0:width:grid_reso]
    Z = np.zeros((gridX, gridY))

    for i in range(path_num):
        Rmat_error_mean_list = tvec_error_mean_list_AllPaths[i]
        fixed_path = fix_path_list[i]
        x_real = fixed_path[0, :]
        y_real = fixed_path[1, :]

        ix = (x_real - grid_reso / 2) / grid_reso
        ix = ix.astype(int)
        iy = (y_real - grid_reso / 2) / grid_reso
        iy = iy.astype(int)

        Z[ix, iy] = Rmat_error_mean_list

    s = mlab.surf(X, Y, Z, warp_scale="auto")

    # cat1_extent = (0, 30, 0, 60, -10, 10)
    mlab.outline(s, color=(.7, .7, .7))
    mlab.text(0, 30, 'pf', z=0, width=0)
    mlab.text(30, 30, 'A*', z=0, width=0.14)
    # mlab.title('Compare path errors between potential field method and A*',size = 10)

    mlab.show()
Esempio n. 35
0
 def plot_u(u, x, xv, y, yv, t, n):
     print " ploting"
     if t[n] == 0:
         time.sleep(2)
     if plot_method == 1:
         mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
              caxis=[-1,1])
     elif plot_method == 2:
         surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
               colorbar=True, colormap=hot(), caxis=[-1,1],
               shading='flat')
     elif plot_method == 3:
         # mayavi plotting
         mlab.clf()
         extent1 = (0, 20, 0, 20,-2, 2)
         s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,
                      extent=extent1)
         mlab.axes(s, color=(.7, .7, .7), extent=extent1,
         ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
         zlabel='',
         x_axis_visibility=False, z_axis_visibility=False)
         mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
         mlab.text(2, -2.5, '', z=-4, width=0.1)
         mlab.colorbar(object=None, title=None, orientation='horizontal',
                       nb_labels=None, nb_colors=None, label_fmt=None)
         mlab.title('t=%g' % t[n])
         mlab.view(142, -72, 50)
         f = mlab.gcf()
         camera = f.scene.camera
         camera.yaw(0)
         #g = mlab.figure()
         #g.scene.movie_maker.record = True
         
     
     if plot_method > 0:
         if not os.path.exists(path):
             os.makedirs(path)
         time.sleep(0) # pause between frames
         if save_plot and plot_method == 3:
             filename = '%s/%08d.png'%(path,n)
             mlab.savefig(filename)  # time consuming!
         elif save_plot and plot_method != 3:
             filename = '%s/%08d.png'%(path,n)
             savefig(filename)  # time consuming!
Esempio n. 36
0
def showvolume(Vin, currentfigurenum):
    mlab.figure(currentfigurenum, bgcolor=(1, 1, 1), fgcolor=(1, 1, 1))
    mlab.clf()

    p = mlab.contour3d(Vin.vol, color=(1, 0, 0))
    mlab.text(0.05,
              0.95,
              'Please close the window to continue calculations.',
              color=(0, 0, 0),
              width=0.9)
    mlab.text(0.3, 0.05, 'Rotate using click&drag', color=(0, 0, 0), width=0.4)

    c_scene = mlab.get_engine().current_scene
    # c_scene.scene.light_manager.light_mode = 'vtk';
    c_scene.scene.camera.position = [0, 0, -128]
    c_scene.scene.camera.view_up = [-1, 0, 0]
    c_scene.scene.render()
    mlab.show()
    return p
Esempio n. 37
0
    def update_scene():

        #  clear figure
        mlab.clf(fig1)

        # Rescale points for visu
        p1 = (query * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0
        p2 = (supports * 1.5 + np.array([1.0, 1.0, 1.0])) * 50.0

        l1 = p1[:, 2] * 0
        l1[file_i] = 1

        l2 = p2[:, 2] * 0 + 2
        l2[neighbors[file_i]] = 3

        # Show point clouds colorized with activations
        activations = mlab.points3d(p1[:, 0],
                                    p1[:, 1],
                                    p1[:, 2],
                                    l1,
                                    scale_factor=2.0,
                                    scale_mode='none',
                                    vmin=0.0,
                                    vmax=3.0,
                                    figure=fig1)

        activations = mlab.points3d(p2[:, 0],
                                    p2[:, 1],
                                    p2[:, 2],
                                    l2,
                                    scale_factor=3.0,
                                    scale_mode='none',
                                    vmin=0.0,
                                    vmax=3.0,
                                    figure=fig1)

        # New title
        mlab.title(str(file_i), color=(0, 0, 0), size=0.3, height=0.01)
        text = '<--- (press g for previous)' + 50 * ' ' + '(press h for next) --->'
        mlab.text(0.01, 0.01, text, color=(0, 0, 0), width=0.98)
        mlab.orientation_axes()

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

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

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



        
        if plot_u > 0:
            path = 'Figures_wave2D'
            if not os.path.exists(path):
                os.makedirs(path)
            time.sleep(0) # pause between frames
            if save_plot and plot_u != 3:
                filename = '%s/tmp_%08d.png' % (path, n)
            elif save_plot and plot_u == 3:
                filename = '%s/tmp_%08d.png' % (path, n)
                mlab.savefig(filename)  # time consuming!
def plotComparePaths_DisError_3DSurface(xyError_list_AllPaths,
                                        grid_reso=0.1,
                                        width=6,
                                        height=3):
    """
    Using Mayavi
    Plot the measured paths with 3D surface(like mountain, high mountain means big error, low mountain means small error)
    1.Figure:
    :param xyError_list_AllPaths:
    :param width: 3 [m]
    :param height: 6 [m]
    :param grid_reso: default 0.1 [m]
    :return:
    """
    path_num = len(xyError_list_AllPaths)
    gridX = int(height / grid_reso)
    gridY = int(width / grid_reso)

    X, Y = np.mgrid[0:height:grid_reso, 0:width:grid_reso]
    Z = np.zeros((gridX, gridY))

    for i in range(path_num):
        xyError_list = xyError_list_AllPaths[i]
        iter_num = xyError_list.shape[0] / 3
        for j in range(iter_num):
            x_real = xyError_list[0 + j * 3, :]
            y_real = xyError_list[1 + j * 3, :]

            ix = (x_real - grid_reso / 2) / grid_reso
            ix = ix.astype(int)

            iy = (y_real - grid_reso / 2) / grid_reso
            iy = iy.astype(int)
            Z[ix, iy] = xyError_list[2 + j * 3, :]

    s = mlab.surf(X, Y, Z, warp_scale="auto")

    mlab.outline(s, color=(.7, .7, .7))
    mlab.text(0, 30, 'pf', z=0, width=0)
    mlab.text(30, 30, 'A*', z=0, width=0.14)
    # mlab.title('Compare path errors between potential field method and A*',size = 10)

    mlab.show()
Esempio n. 40
0
    def xmas_balls(connectivity,
                   node_data=None,
                   edge_data=True,
                   labels_data=True,
                   balls_colormap='Blues',
                   bgcolor=(1, 1, 1),
                   node_size=10.,
                   edge_color=(0.8, 0.8, 0.8),
                   edge_size=0.2,
                   text_size=0.042,
                   text_color=(0, 0, 0)):
        """
        Plots coloured balls at the region centres of connectivity, colour and
        size is determined by a vector of length number of regions (node_data).
        
        Optional: adds the connections between pair of nodes.
        
        """
        G = nx.from_numpy_matrix(numpy.matrix(connectivity.weights))

        mlab.figure(1, bgcolor=bgcolor)
        mlab.clf()
        # scalar colors
        if node_data is not None:
            scalars = node_data
            mlab.colorbar(orientation="vertical")
        else:
            scalars = numpy.array(G.nodes()) * 20

        pts = mlab.points3d(connectivity.centres[:, 0],
                            connectivity.centres[:, 1],
                            connectivity.centres[:, 2],
                            scalars,
                            scale_factor=node_size,
                            scale_mode='none',
                            colormap=balls_colormap,
                            resolution=20)

        if labels_data:
            for i, (x, y, z) in enumerate(connectivity.centres):
                label = mlab.text(x,
                                  y,
                                  connectivity.region_labels[i],
                                  z=z,
                                  width=text_size,
                                  name=str(connectivity.region_labels[i]),
                                  color=text_color)
                label.property.shadow = False

        if edge_data:
            pts.mlab_source.dataset.lines = numpy.array(G.edges())
            tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
            mlab.pipeline.surface(tube, color=edge_color)

        mlab.show()
Esempio n. 41
0
def draw_graph3d(graph,  graph_colormap='winter',  bgcolor = (1,  1,  1), 
                 node_size=0.03, 
                 edge_color=(0.8,  0.8,  0.8),  edge_size=0.002, 
                 text_size=0.008,  text_color=(0,  0,  0)):

    H = nx.Graph()

    ## add edges
    #for node,  edges in graph.items():
    #    for edge,  val in edges.items():
    #        if val == 1:
    #            H.add_edge(node,  edge)
    
    # add edges
    for edge in graph:
        H.add_edge(edge[0],  edge[1])

    G = nx.convert_node_labels_to_integers(H)

    graph_pos = nx.spring_layout(G,  dim=3)

    # numpy array of x, y, z positions in sorted node order
    xyz = np.array([graph_pos[v] for v in sorted(G)])

    # scalar colors
    scalars = np.array(G.nodes())+5
    mlab.figure(1,  bgcolor=bgcolor)
    mlab.clf()

    pts = mlab.points3d(xyz[:,  0],  xyz[:,  1],  xyz[:,  2], 
                        scalars, 
                        scale_factor=node_size, 
                        scale_mode='none', 
                        colormap=graph_colormap, 
                        resolution=20)

    for i,  (x,  y,  z) in enumerate(xyz):
        label = mlab.text(x,  y,  str(i),  z=z, 
                          width=text_size,  name=str(i),  color=text_color)
        label.property.shadow = True

    print(np.array(G.edges))

    print(np.array(list(G.edges())))
    print(type(G.edges()))
    print(type(list(G.edges())))
    print(len(list(G.edges())))
    print(len(list(G.edges())))
    print(len(G.edges()))

    pts.mlab_source.dataset.lines = np.array(G.edges())
    tube = mlab.pipeline.tube(pts,  tube_radius=edge_size)
    mlab.pipeline.surface(tube,  color=edge_color)

    mlab.show()  # interactive window
Esempio n. 42
0
        def redraw_scene(self, scene, cur_scatter_data):
            # Notice how each mlab call points explicitely to the figure it
            # applies to.
            mlab.clf(figure=scene.mayavi_scene)
            x = cur_scatter_data[0]
            y = cur_scatter_data[1]
            z = cur_scatter_data[2]
            xlabel_text = cur_scatter_data[3][0]
            ylabel_text = cur_scatter_data[3][1]
            zlabel_text = cur_scatter_data[3][2]
            cur_colors = cur_scatter_data[4]
            cur_scales = [np.array(x) for x in cur_scatter_data[5]]
            label_unique = cur_scatter_data[6]
            points_dict.clear()
            for ii in range(len(label_unique)):
                points_dict[label_unique[ii]] = mlab.points3d(
                    x[ii],
                    y[ii],
                    z[ii],
                    cur_scales[ii] * self.cur_scale,
                    color=cur_colors[ii][0],
                    scale_factor=0.01,
                    opacity=self.cur_opacity / 100)
            for ii in range(len(outputs_unique)):
                mlab.text(0.02,
                          1 - 0.035 * (ii + 1),
                          '-' + str(outputs_unique[ii]),
                          width=0.06,
                          color=all_colors[ii])

            cur_axex = mlab.axes(xlabel=xlabel_text,
                                 ylabel=ylabel_text,
                                 zlabel=zlabel_text,
                                 extent=[
                                     min(sum(x, [])),
                                     max(sum(x, [])),
                                     min(sum(y, [])),
                                     max(sum(y, [])),
                                     min(sum(z, [])),
                                     max(sum(z, []))
                                 ])
            cur_axex.axes.font_factor = 0.8
def do_test(lines, scalars, show=False, txt=""):
    viscid.logger.info('--> ' + txt)
    title = txt + '\n' + "\n".join(textwrap.wrap("scalars = {0}".format(scalars),
                                                 width=50))

    try:
        from viscid.plot import vpyplot as vlt
        from matplotlib import pyplot as plt

        vlt.clf()
        vlt.plot_lines(lines, scalars=scalars)
        plt.title(title)
        vlt.savefig(next_plot_fname(__file__, series='q2'))
        if show:
            vlt.show()
    except ImportError:
        pass

    try:
        from mayavi import mlab
        from viscid.plot import vlab

        try:
            fig = _global_ns['figure']
            vlab.clf()
        except KeyError:
            fig = vlab.figure(size=[1200, 800], offscreen=not show,
                              bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
            _global_ns['figure'] = fig

        vlab.clf()
        vlab.plot_lines3d(lines, scalars=scalars)
        vlab.fancy_axes()
        mlab.text(0.05, 0.05, title)
        vlab.savefig(next_plot_fname(__file__, series='q3'))
        if show:
            vlab.show(stop=True)
    except ImportError:
        pass
Esempio n. 44
0
def anim():
    global vessels, colorGradient, timeText, showingNode
    timeText = None
    while True:
        if timeText != None:
            timeText.remove()            
        timeText = mlab.text(0.01, 0.01, 'Time: ' + str(g.globals.time), width=0.3)
        for (top, bottom, host) in vessels:
            lutT = top.module_manager.scalar_lut_manager.lut.table.to_array()
            lutB = bottom.module_manager.scalar_lut_manager.lut.table.to_array()
            count = host.getBacteriaCount()
            colorNdx = int(float(count) / parameters.cell_count_color_mapping * (len(colorGradient) - 1))
            if colorNdx >= len(colorGradient):
                colorNdx = len(colorGradient) - 1
            color = colorGradient[colorNdx]
            assert len(color) == 6
            ones = np.ones(np.shape(lutT[:, 0]))
            R = int(color[0:2], 16)
            G = int(color[2:4], 16)
            B = int(color[4:6], 16)
            #R
            lutT[:,0] = ones * R
            lutB[:,0] = ones * R
            #G
            lutT[:,1] = ones * G
            lutB[:,1] = ones * G
            #B
            lutT[:,2] = ones * B
            lutB[:,2] = ones * B            
            top.module_manager.scalar_lut_manager.lut.table = lutT
            bottom.module_manager.scalar_lut_manager.lut.table = lutB
        
        if showingNode is not None:
            (ax1, ax2) = plots
            ax1.cla()
            history = copy.deepcopy(showingNode.getCellCountHistory())
            x = np.linspace(0, len(history) * parameters.cell_count_history_interval, len(history))
            y = history
            ax1.plot(x, y, 'r')
            ax1.set_title('Bacteria Count history')            

            ax2.cla()
            history = copy.deepcopy(showingNode.getFlowHistory())
            x = np.linspace(0, len(history) * parameters.cell_count_history_interval, len(history))
            y = history
            ax2.plot(x, y, 'b')
            ax2.set_title('Blood flow history')  
        mlab.draw()
        if parameters.verbose:      
            print("updating graph")
        yield
Esempio n. 45
0
def draw_graph3d(
    graph,
    graph_colormap="winter",
    bgcolor=(1, 1, 1),
    node_size=0.03,
    edge_color=(0.8, 0.8, 0.8),
    edge_size=0.002,
    text_size=0.008,
    text_color=(0, 0, 0),
):

    H = nx.Graph()

    # add edges
    for node, edges in graph.items():
        for edge, val in edges.items():
            if val == 1:
                H.add_edge(node, edge)

    G = nx.convert_node_labels_to_integers(H)

    graph_pos = nx.spring_layout(G, dim=3)

    # numpy array of x,y,z positions in sorted node order
    xyz = np.array([graph_pos[v] for v in sorted(G)])

    # scalar colors
    scalars = np.array(G.nodes()) + 5
    mlab.figure(1, bgcolor=bgcolor)
    mlab.clf()

    pts = mlab.points3d(
        xyz[:, 0],
        xyz[:, 1],
        xyz[:, 2],
        scalars,
        scale_factor=node_size,
        scale_mode="none",
        colormap=graph_colormap,
        resolution=20,
    )

    for i, (x, y, z) in enumerate(xyz):
        label = mlab.text(x, y, str(i), z=z, width=text_size, name=str(i), color=text_color)
        label.property.shadow = True

    pts.mlab_source.dataset.lines = np.array(G.edges())
    tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
    mlab.pipeline.surface(tube, color=edge_color)

    mlab.show()  # interactive window
def add_cbar_label(cbar,title):
    position = cbar.scalar_bar_representation.position
    position2 = cbar.scalar_bar_representation.position2
    
    x = position[0] + position2[0] #+ 0.002
    y = position[1]
    
    text = mlab.text(x,y,title)
    text.property.font_size = 24
    set_text(text.property)
    
    text.property.orientation = 90.
    text.width = 0.205
    
    return text
Esempio n. 47
0
def draw_graph3d(graph, graph_colormap='summer', bgcolor = (0, 0, 0),
                 node_size=0.05,
                 edge_color=(0.5, 0.5, 0.5), edge_size=0.0005,
                 text_size=0.004, text_color=(1, 1, 1)):

    H=nx.Graph()

    # add edges
    for node, edges in graph.items():
        for edge, val in edges.items():
            if val == 1:
                H.add_edge(node, edge)

    G=nx.convert_node_labels_to_integers(H)
    #G=H

    graph_pos=nx.random_layout(G, dim=3)

    # numpy array of x,y,z positions in sorted node order
    xyz=np.array([graph_pos[v] for v in sorted(G)])

    # scalar colors
    scalars=np.array(G.nodes())+5
    mlab.figure(1, bgcolor=bgcolor)
    mlab.clf()

    pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2],
                        scalars,
                        scale_factor=node_size,
                        scale_mode='none',
                        colormap=graph_colormap,
                        resolution=20)

    mlab.figure(1).scene.disable_render = True
    for i, (x, y, z) in enumerate(xyz):
        label = mlab.text(x, y, graph.keys()[i], z=z,
                          width=len(graph.keys()[i])*text_size, name=str(i), color=text_color)
        label.property.shadow = False
    

    pts.mlab_source.dataset.lines = np.array(G.edges())
    tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
    mlab.pipeline.surface(tube, color=edge_color)
    
    mlab.figure(1).scene.disable_render = False

    mlab.show() # interactive window
Esempio n. 48
0
def draw_graph3d(graph_colormap='winter', bgcolor = (1, 1, 1),
                 node_size=0.03,
                 edge_color=(0.8, 0.8, 0.8), edge_size=0.002,
                 text_size=0.008, text_color=(0, 0, 0)): 
    
    H = nx.Graph()
    
    db = db_utils.getDBInstance()
    nodes = db.webpages.find()
    edges = []
    for node in nodes:
        iurls = node["incoming_links"]
        for iurl in iurls:
            H.add_edge(iurl, node["url"])

    G= nx.convert_node_labels_to_integers(H)

    graph_pos=nx.spring_layout(G, dim=3)

    # numpy array of x,y,z positions in sorted node order
    xyz=np.array([graph_pos[v] for v in sorted(G)])

    # scalar colors
    scalars=np.array(G.nodes())+5
    mlab.figure(1, bgcolor=bgcolor)
    mlab.clf()

    pts = mlab.points3d(xyz[:,0], xyz[:,1], xyz[:,2],
                        scalars,
                        scale_factor=node_size,
                        scale_mode='none',
                        colormap=graph_colormap,
                        resolution=20)

    for i, (x, y, z) in enumerate(xyz):
        label = mlab.text(x, y, str(i), z=z,
                          width=text_size, name=str(i), color=text_color)
        label.property.shadow = True

    pts.mlab_source.dataset.lines = np.array(G.edges())
    tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
    mlab.pipeline.surface(tube, color=edge_color)

    mlab.show() # interactive window
Esempio n. 49
0
def picker_callback(picker):
    global vessels, lastSelected, bound, showingNode, plots
    if 'lastSelected' not in globals():
        lastSelected = None
    if 'bound' not in globals():
        bound = None
    picked = picker.actors
    for (top, bottom, node) in vessels:
        if top.actor.actor._vtk_obj in [o._vtk_obj for o in picked] or bottom.actor.actor._vtk_obj in [o._vtk_obj for o in picked]:
            if lastSelected != None:
                lastSelected.remove()
            lastSelected = mlab.text(node.start.x, node.start.y, node.name, width=0.2, z=node.start.z)
            if bound != None:
                (tBound, bBound) = bound
                tBound.remove()
                bBound.remove()
            tBound = mlab.outline(top)
            bBound = mlab.outline(bottom)
            bound = (tBound, bBound)
            if plots is None:
                f, plots = plt.subplots(2, 1)
            (ax1, ax2) = plots
            ax1.cla()
            history = copy.deepcopy(node.getCellCountHistory())
            x = np.linspace(0, len(history) * parameters.cell_count_history_interval, len(history))
            y = history
            ax1.plot(x, y, 'r')
            ax1.set_title('Bacteria Count history')            

            ax2.cla()
            history = copy.deepcopy(node.getFlowHistory())
            x = np.linspace(0, len(history) * parameters.cell_count_history_interval, len(history))
            y = history
            ax2.plot(x, y, 'b')
            ax2.set_title('Blood flow history')            

            if showingNode is None:
                plt.show()

            showingNode = node

            break
Esempio n. 50
0
def parse_boxes(filenames, dim):
  """from a list of filenames to 21cmFast output order them and make a movie
  using ffmpeg"""

  savedir='./slice_temp'
  if not os.path.isdir(savedir):
    os.mkdir(savedir)
  boxes=[]
  redshifts=[]
  for filename in sorted(filenames,reverse=True):
    param_dict=parse_filename(filename)
    box_data=open_box(filename,dim)
    boxes.append(box_data)
    redshifts.append(param_dict['z'])

  s=boxes[0]
  indx=dim-1
  lz=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                            plane_orientation='z_axes',
                            slice_index=indx,colormap='black-white'
                        )
  lx=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                            plane_orientation='x_axes',
                            slice_index=indx,colormap='black-white'
                        )
  ly=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                            plane_orientation='y_axes',
                            slice_index=indx,colormap='black-white'
                        )

  titlestr='z=%3.2d' % redshifts[0]
  tit=mlab.text(0.1,0.9,titlestr,width=0.1)
  #s=sp

  fig=mlab.gcf()
  msx=lx.mlab_source
  msy=ly.mlab_source
  msz=lz.mlab_source
  
  for i in range(1,len(boxes)):
    #l=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
    #                        plane_orientation='y_axes',
    #                        slice_index=i,colormap='black-white'
    #                    )
    msx.reset(scalars=boxes[i])
    msy.reset(scalars=boxes[i])
    msz.reset(scalars=boxes[i])
    
    #print dir(ms)
    #print ms
    #camera=fig.scene.camera
    #camera.yaw(i)
    titlestr='z=%3.2d' % redshifts[i]
    mlab.text(0.1,0.9,titlestr,width=0.1)
    #fig.reset(text=titlestr)
    fig.scene.reset_zoom()
    mlab.draw()
    #time.sleep(1)
    fname='volume_slice_frame%03d.png' % i
    filename=os.path.join(savedir,fname)
    print filename
    mlab.savefig(filename)

  mlab.close()
  #mlab.show()
  #call ffmpeg to make a movie
  # -r controls the framerate in frames/second
  #needs better handling in case ffmpeg asks for user response
  cmd='ffmpeg -f image2 -r 5 -i ./slice_temp/volume_slice_frame%03d.png -sameq ./slice_temp/anim.mov -pass 2'
  (status,output)=commands.getstatusoutput(cmd)
  print status
  
  return
Esempio n. 51
0
connections = np.array(connections)
# We add lines between the points that we have previously created by
# directly modifying the VTK dataset.
points.mlab_source.dataset.lines = connections
points.mlab_source.reset()
# To represent the lines, we use the surface module. Using a wireframe
# representation allows to control the line-width.
mlab.pipeline.surface(points, color=(1, 1, 1),
                              representation='wireframe',
                              line_width=4,
                              name='Connections')

###############################################################################
# Display city names
for city, index in cities.iteritems():
    label = mlab.text(x[index], y[index], city, z=z[index],
                      width=0.016 * len(city), name=city)
    label.property.shadow = True

###############################################################################
# Display continents outline, using the VTK Builtin surface 'Earth'
from mayavi.sources.builtin_surface import BuiltinSurface
continents_src = BuiltinSurface(source='earth', name='Continents')
# The on_ratio of the Earth source controls the level of detail of the
# continents outline.
continents_src.data_source.on_ratio = 2
continents = mlab.pipeline.surface(continents_src, color=(0, 0, 0))

###############################################################################
# Display a semi-transparent sphere, for the surface of the Earth

# We use a sphere Glyph, throught the points3d mlab function, rather than
Esempio n. 52
0
def envelopes3d_group_by(results, 
                         outcome,
                         groupBy = 'policy', 
                         discretesize = None,
                         logSpace=False,
                         ymin = None,
                         ymax = None):
    '''
    
    Function for making 3d envelopes. In contrast to the envelopes in 
    :mod:`graphs`, this version shows the density for every time step, instead 
    of only for the end state. Note that this function makes an envelope for 
    only 1 outcome. This envelopes will group the results based on the
    specified uncertainty. The user can supply a discretesize function
    to control the grouping in case of parameterUncertainties. This function
    will make a separate envelope for each group.
    
    :param results: The return from :meth:`run experiments`.
    :param outcome: Specify the name of outcome of interest for which you want to make 
                    the 3d envelopes.
    :param groupBy: The uncertainty to group by. (default=policy)
    :param discretesize: a discretesize function to control the grouping in case of parameterUncertainties
    :param logSpace: Boolean, if true, the log of the input data is used
    :param ymin: If provided, lower bound for the KDE, if not, ymin = np.min(results.get(outcome))
    :param ymax: If provided, lower bound for the KDE, if not, ymax = np.max(results.get(outcome))
    
    '''
    def f(x, y, results):
        """
        function that performs the kde for each timestep
        """
        
        x1 = x[:,0]
        y1 = y[0,:]
        results = np.asarray(results)
        
        z = []
        for i in range(len(list(x1))):
            data = results[:, i]
            try:
                z1 = kde.gaussian_kde(data)
                z1 = z1.evaluate(y1)
            except:
                z1 = np.zeros(shape=y1.shape)
            z.append(z1)
        z = np.asarray(z)
        z = np.log(z+1)
    
        return z
    
    #prepare the data
    experiments, results = results

    #get time axis
    try:
        time = results.pop('TIME')[0, :]
    except:
        time =  np.arange(0, results.values()[0].shape[1])
    
    
    def make_logical(cases, criterion, interval=False):
        if interval:
            
            return (cases[groupBy] >= criterion[0]) & (cases[groupBy] < criterion[1]) 
        else:
            return cases[groupBy]== criterion
    
    
    #get the results for the specific outcome of interest
    results = results.get(outcome)
    
    #log results
    if logSpace:
        results = np.log(results+1)
   
    #generate the grid
    if ymin == None:
        ymin = np.min(results)
        info("ymin: %s" % ymin)
    if ymax == None:
        ymax = np.max(results)
        info("ymax: %s" % ymax)

    length = min(100, results.shape[1])
    y = np.arange(ymin, ymax, (ymax-ymin)/length)
    X, Y = np.meshgrid(time, y)

    z = []

    #do the preparation for grouping by
    interval=False
    if (experiments[groupBy].dtype == np.float32) |\
       (experiments[groupBy].dtype == np.float64) |\
       ((experiments[groupBy].dtype == np.int) & (len(set(experiments[groupBy])) > 5)):
        interval=True
        if discretesize:
            categories = discretesize(experiments[groupBy])
        else:
            categories = make_continuous_grouping_specifiers(experiments[groupBy])
    else:
        categories = set(experiments[groupBy])
        
    
    for category in categories:
        if interval:
            info("calculating kde for (%s, %s)" % (category))
        else:
            info("calculating kde for %s" % (category))
        logical = make_logical(experiments, category, interval)
        
        Z = f(X.T,Y.T, results=results[logical])
        z.append(Z)

    #calculate the kde for the grid
    #visualize results
    fig = mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    
    fig.scene.disable_render = True
    for i, category in enumerate(categories):        
        if interval:
            info("plotting (%s, %s)" % (category))
        else:
            info("plotting %s" % (category))
        
        Z = z[i]
        extent = (-14+i*10,-6+i*10, 0,10, 0,5)
        s = mlab.mesh(X,Y, Z.T, extent=extent)
        mlab.outline(s, color=(.7, .7, .7), extent=extent)
        if i==0:
            mlab.axes(s,
                      extent=extent,
                      xlabel = '',
                      ylabel = '',
                      zlabel = 'density',
                      x_axis_visibility=False,
                      y_axis_visibility=False, 
                      z_axis_visibility=False) 
        
        category_name = repr(category)
            
        mlab.text(-16+10*i, i+10, category_name, z=-2, width=0.14)
    fig.scene.disable_render = False
    mlab.title(outcome, line_width=0.5)
    mlab.show()
Esempio n. 53
0
    def make_side_view(self, axis_name):
        scene = getattr(self, 'scene_%s' % axis_name)
        scene.scene.parallel_projection = True
        ipw_3d   = getattr(self, 'ipw_3d_%s' % axis_name)

        # We create the image_plane_widgets in the side view using a
        # VTK dataset pointing to the data on the corresponding
        # image_plane_widget in the 3D view (it is returned by
        # ipw_3d._get_reslice_output())
        side_src = ipw_3d.ipw._get_reslice_output()
        ipw = mlab.pipeline.image_plane_widget(
                            side_src,
                            plane_orientation='z_axes',
                            vmin=self.data.min(),
                            vmax=self.data.max(),
                            figure=scene.mayavi_scene,
                            name='Cut view %s' % axis_name,
                            )
        setattr(self, 'ipw_%s' % axis_name, ipw)

        # Extract the spacing of the side_src to convert coordinates
        # into indices
        spacing = side_src.spacing

        # Make left-clicking create a crosshair
        ipw.ipw.left_button_action = 0

        x, y, z = self.position
        cursor = mlab.points3d(x, y, z,
                            mode='axes',
                            color=(0, 0, 0),
                            scale_factor=2*max(self.data.shape),
                            figure=scene.mayavi_scene,
                            name='Cursor view %s' % axis_name,
                        )
        self.cursors[axis_name] = cursor

        # Add a callback on the image plane widget interaction to
        # move the others
        this_axis_number = self._axis_names[axis_name]
        def move_view(obj, evt):
            # Disable rendering on all scene
            position = list(obj.GetCurrentCursorPosition()*spacing)[:2]
            position.insert(this_axis_number, self.position[this_axis_number])
            # We need to special case y, as the view has been rotated.
            if axis_name is 'y':
                position = position[::-1]
            self.position = position

        ipw.ipw.add_observer('InteractionEvent', move_view)
        ipw.ipw.add_observer('StartInteractionEvent', move_view)

        # Center the image plane widget
        ipw.ipw.slice_position = 0.5*self.data.shape[
                                        self._axis_names[axis_name]]

        # 2D interaction: only pan and zoom
        scene.scene.interactor.interactor_style = \
                                 tvtk.InteractorStyleImage()
        scene.scene.background = (0, 0, 0)

        # Some text:
        mlab.text(0.01, 0.8, axis_name, width=0.08)

        # Choose a view that makes sens
        views = dict(x=(0, 0), y=(90, 180), z=(0, 0))
        mlab.view(views[axis_name][0],
                  views[axis_name][1],
                  focalpoint=0.5*np.array(self.data.shape),
                  figure=scene.mayavi_scene)
        scene.scene.camera.parallel_scale = 0.52*np.mean(self.data.shape)
Esempio n. 54
0
        def trackPlotter(self,plotVars,plotGradients=None,plotProjGrad=False):
            '''Gradients must be one of one of minimizedFunc or fixedFuncs as these are only ones
               Stored in gradient dict
            '''
            assert len(plotVars) == 3, "Track plotter requires 3 plotVars for 3D track! You gave: %s" % len(plotVars)
            for i,track in enumerate(self.trackData):
                stepScale = minimizeAlgorithm.norm(array(track['deltas']))
                pointList=zip(*track['points'])
                xs_ys_zs=[]
                #Here we search through the available data and add the correct data to plot to xs_ys_zs
                for plotVar in plotVars:
                    gotItFlag=False
                    for pointIndex,pointVar in enumerate(track['independentVars']):
                        if pointVar==plotVar:
                            print 'got ind var %s' % plotVar
                            xs_ys_zs.append(pointList[pointIndex])
                            gotItFlag=True
                            break
                    if gotItFlag:
                        continue
                    for availData in track.keys():
                        if availData == plotVar:
                            print 'got other track var %s' % plotVar
                            gotItFlag=True
                            xs_ys_zs.append(track[plotVar])
                            break
                    assert gotItFlag, "uh oh didn't find our variable to plot '%s'" % plotVar
                print 'redmax:   ', track['RedMax']
                print 'baryMass: ', track['baryMass']
                mlab.plot3d(*xs_ys_zs,
                            color=(1-(1./(i%3+1)),1,1./(i%2+1.)),
                            reset_zoom=False,
                            tube_radius=None)

                if plotGradients:
                    if plotVars == track['independentVars']:
                        print "Mkay good, you're plotting gradients in same space as your tracks"
                        pass
                    else:
                        assert False, "Bad! WARNING your gradients are not in the same space as your tracks!!"
                    if not isinstance(plotGradients,tuple):
                        plotGradients = [plotGradients]
                    for j,grad in enumerate(plotGradients):
                        vxs,vys,vzs= returnGradientXsYsZsForPlot(track['gradDicts'],grad)
                        print vxs
                        print vys
                        print vzs
                        thisColor=( (j%2)/2.+0.5,1./(j+1.3),((j+1)%2.)/1.7 )
                        mlab.quiver3d(xs_ys_zs[0],xs_ys_zs[1],xs_ys_zs[2],
                                      vxs,vys,vzs,
                                      color=thisColor,
                                      scale_factor=stepScale )
                        label = grad + " " * ( self.maxLabelLength - len(grad) )
                        mlab.text(0.01,0.1 + j*0.2, label, color=thisColor, width=0.1)
                if plotProjGrad:
                    assert plotVars== track['independentVars']
                    vxs,vys,vzs=zip(*track['projGrads'])
                    mlab.quiver3d(xs_ys_zs[0],xs_ys_zs[1],xs_ys_zs[2],
                                  vxs,vys,vzs,
                                  color=(1,1,1),
                                  scale_factor=stepScale )
                    mlab.text(0.5,0.1 , "projGrad", color=(1,1,1), width=0.1)
            # Below move doesnt work
            #print mlab.move(xs_ys_zs[0][0],xs_ys_zs[1][0],xs_ys_zs[2][0])  # move camera to first point
            mlab.show()
            return 0
Esempio n. 55
0
def drawOriginAxes(plotExtents, displace=None, colAxes=True, cones=True,
                   xaxis=True, yaxis=True, zaxis=True, opacity=1.0,
                   scale_arrow_width=1.0, scale_label=0.5,
                   label_color=(0.1,0.1,0.1), visible=True, cone_scale_factor=1.0,
                   axis_tube_radius=0.05, axis_mono_col=(0.1,0.1,0.1)):
    """Function to draw crossed axes through the origin. The three axes have the
    option of adding a cone, and also may or may not have different colors.
    The axes are also labeled.


    Examples
    --------
    >>>plotExtents = (-10,10,-10,10,-10,10)
    >>>drawOriginAxes(plotExtents,colAxes=True,opacity=0.90)

    #also, if you need to scale the arrow & bar widths and the text label use:
    
    >>>drawOriginAxes(plotExtents, colAxes=True,scale_arrow_width=0.95, scale_label=0.5, opacity=0.95)

    Notes
    -----
    For simple, crossed axes without different colors, lables, and cones, it is
    better (simplicity) to use:

    >>>x = np.array([0]);y = np.array([0]);z = np.array([0]); # These may be standard Python scalars too
    >>>ss = some value (extent of the axes)
    >>>caxis = mlab.points3d(x, y, z, ss, mode='axes',color=(0,1,0), scale_factor=1)
    >>>caxis.actor.property.lighting = False
    """
    #even if the user doesn't want any axis through the origin, we need to draw
    #something before a Mayavi axes can be attached. So we draw only the z-axis
    #and set it's visibility to False
    if visible==False:
        cones=False          #don't draw any cones
        xaxis=False          #don't draw x-axis
        yaxis=False          #don't draw y-axis
        zaxis=True           #draw the z-axis
    ext2subtract = 0.0
    if cones==True:
        ext2subtract = 1.0*cone_scale_factor
    oa_xlim = np.array([plotExtents[0], plotExtents[1] - ext2subtract])
    oa_ylim = np.array([plotExtents[2], plotExtents[3] - ext2subtract])
    oa_zlim = np.array([plotExtents[4], plotExtents[5] - ext2subtract])

    center = np.array([0,0])
    oa_colork = label_color  # label color

    if colAxes:
        oa_colR = (0.9, 0, 0)
        oa_colG = (0, 0.9, 0)
        oa_colB = (0, 0, 0.9)
    else:
        oa_colR = axis_mono_col 
        oa_colG = axis_mono_col 
        oa_colB = axis_mono_col

    # x-axis
    if xaxis:
        x = np.array([oa_xlim[1]]);y = np.array([0]);z = np.array([0])
        u = np.array([1]); v = np.array([0]); w = np.array([0])
        if cones:
            x_cone = mlab.quiver3d(x, y, z, u, v, w, mode='cone', color=oa_colR, 
                                   scale_factor=cone_scale_factor)
            x_cone.actor.property.lighting = False
            x_cone.actor.property.opacity = opacity
            x_cone.actor.actor.scale = np.array((scale_arrow_width, scale_arrow_width, scale_arrow_width))
        x_axis = mlab.plot3d(oa_xlim, center, center, color=oa_colR, line_width=1.0,
                             tube_radius=axis_tube_radius, name='oax')
        x_axis.actor.actor.scale = np.array((1.0, scale_arrow_width, scale_arrow_width)) # don't scale along the x-axis
        x_axis.actor.property.lighting = False
        x_axis.actor.property.opacity = opacity
        # lately, text3d isn't working
        #xaxis_label = mlab.text3d(0.9*oa_xlim[1], 0, 0, 'x', scale=scale_label, color=oa_colork)
        xaxis_label = mlab.text(x=0.9*oa_xlim[1], y=0.0*oa_ylim[1], 
                                z=0, text='x', width=0.01*scale_label, color=oa_colork)
        
    # y-axis
    if yaxis:
        x = np.array([0]);y = np.array([oa_ylim[1]]);z = np.array([0])
        u = np.array([0]);v = np.array([1]);w = np.array([0])
        if cones:
            y_cone = mlab.quiver3d(x, y, z, u, v, w, mode='cone', color=oa_colG, 
                                   scale_factor=cone_scale_factor)
            y_cone.actor.property.lighting = False
            y_cone.actor.property.opacity = opacity
            y_cone.actor.actor.scale = np.array((scale_arrow_width, scale_arrow_width, scale_arrow_width))
        y_axis = mlab.plot3d(center,oa_ylim,center, color=oa_colG, line_width=1.0,
                             tube_radius=axis_tube_radius, name='oay')
        y_axis.actor.actor.scale = np.array((scale_arrow_width, 1.0, scale_arrow_width))  # don't scale along the y-axis
        y_axis.actor.property.lighting = False
        y_axis.actor.property.opacity = opacity
        #lately, text3d is not working        
        #yaxis_label = mlab.text3d(0,0.9*oa_ylim[1],0,'y',scale=scale_label,color=oa_colork)
        yaxis_label = mlab.text(x=0.015*oa_xlim[1], y=0.9*oa_ylim[1], 
                                z=0, text='y', width=0.01*scale_label, color=oa_colork)
    # z-axis
    if zaxis:
        x = np.array([0]);y = np.array([0]);z = np.array([oa_zlim[1]])
        u = np.array([0]);v = np.array([0]);w = np.array([1])
        if cones:
            z_cone = mlab.quiver3d(x, y, z, u, v, w, mode='cone', color=oa_colB, 
                                   scale_factor=cone_scale_factor)
            z_cone.actor.property.lighting = False
            z_cone.actor.property.opacity = opacity
            z_cone.actor.actor.scale = np.array((scale_arrow_width, scale_arrow_width, scale_arrow_width))
        z_axis = mlab.plot3d(center, center, oa_zlim, color=oa_colB, line_width=1.0,
                             tube_radius=axis_tube_radius, name='oaz')
        z_axis.actor.actor.scale = np.array((scale_arrow_width,scale_arrow_width, 1.0))  # don't scale along the z-axis
        z_axis.actor.property.lighting = False
        z_axis.actor.property.opacity = opacity
        #lately, text3d isn't working         
        #zaxis_label = mlab.text3d(0,0,0.9*oa_zlim[1],'z',scale=scale_label,color=oa_colork)
        zaxis_label = mlab.text(x=0.01*oa_xlim[1], y=0.0*oa_ylim[1], 
                                z=0.9*oa_zlim[1], text='z', width=0.01*scale_label, color=oa_colork)

    if visible==False:
        z_axis.actor.actor.visibility=False
        zaxis_label.actor.visibility=False
Esempio n. 56
0
    # ... and a sphere at the same location.                    
    mlab.quiver3d([my_x],
                  [my_y - sphere_size/4.],
                  [my_z],
                  [0],[1],[0],
                  scalars = [1],
                  scale_factor = sphere_size/2.,
                  scale_mode = 'scalar',
                  mode = 'sphere',
                  line_width = lw*0.75,
                  name = gal,
                  color=galcolors[k])
                  
    # Finally, add the galaxy name as 3D text.             
    #mlab.text3d(my_x,my_y,my_z,'HCG91'+gal[-1],scale=20,color = (0,0,0))        
    mlab.text(my_x,my_y,'HCG91'+gal[-1],color=(0,0,0),z=my_z,width=0.1) 
                 
# Next, add peculiar HII regions of interest inside HCG 91c
# (See Vogt+, MNRAS (2015) for details)

# First, compute their coordinates                
coords_91c = [[ratodeg(gals['hcg91c']['ra']), 
               dectodeg(gals['hcg91c']['dec']),0,0]]
    
coords_91c_plot = (np.array(coords_91c)-np.array([ramean,decmean,0,0]))*3600.
coords_91c_plot[0][0] *= np.cos(np.radians(decmin))

cube_size = 5
hx1 = coords_91c_plot[0][0] - 3.2 
hx2 = coords_91c_plot[0][0] - 7.0
hx3 = coords_91c_plot[0][0] - 10.5
Esempio n. 57
0
def plot_evoked_field(evoked, surf_maps, time=None, time_label='t = %0.0f ms',
                      n_jobs=1):
    """Plot MEG/EEG fields on head surface and helmet in 3D

    Parameters
    ----------
    evoked : instance of mne.Evoked
        The evoked object.
    surf_maps : list
        The surface mapping information obtained with make_field_map.
    time : float | None
        The time point at which the field map shall be displayed. If None,
        the average peak latency (across sensor types) is used.
    time_label : str
        How to print info about the time instant visualized.
    n_jobs : int
        Number of jobs to run in parallel.

    Returns
    -------
    fig : instance of mlab.Figure
        The mayavi figure.
    """
    types = [t for t in ['eeg', 'grad', 'mag'] if t in evoked]

    time_idx = None
    if time is None:
        time = np.mean([evoked.get_peak(ch_type=t)[1] for t in types])

    if not evoked.times[0] <= time <= evoked.times[-1]:
        raise ValueError('`time` (%0.3f) must be inside `evoked.times`' % time)
    time_idx = np.argmin(np.abs(evoked.times - time))

    types = [sm['kind'] for sm in surf_maps]

    # Plot them
    from mayavi import mlab
    alphas = [1.0, 0.5]
    colors = [(0.6, 0.6, 0.6), (1.0, 1.0, 1.0)]
    colormap = mne_analyze_colormap(format='mayavi')
    colormap_lines = np.concatenate([np.tile([0., 0., 255., 255.], (127, 1)),
                                     np.tile([0., 0., 0., 255.], (2, 1)),
                                     np.tile([255., 0., 0., 255.], (127, 1))])

    fig = mlab.figure(bgcolor=(0.0, 0.0, 0.0), size=(600, 600))

    for ii, this_map in enumerate(surf_maps):
        surf = this_map['surf']
        map_data = this_map['data']
        map_type = this_map['kind']
        map_ch_names = this_map['ch_names']

        if map_type == 'eeg':
            pick = pick_types(evoked.info, meg=False, eeg=True)
        else:
            pick = pick_types(evoked.info, meg=True, eeg=False, ref_meg=False)

        ch_names = [evoked.ch_names[k] for k in pick]

        set_ch_names = set(ch_names)
        set_map_ch_names = set(map_ch_names)
        if set_ch_names != set_map_ch_names:
            message = ['Channels in map and data do not match.']
            diff = set_map_ch_names - set_ch_names
            if len(diff):
                message += ['%s not in data file. ' % list(diff)]
            diff = set_ch_names - set_map_ch_names
            if len(diff):
                message += ['%s not in map file.' % list(diff)]
            raise RuntimeError(' '.join(message))

        data = np.dot(map_data, evoked.data[pick, time_idx])

        x, y, z = surf['rr'].T
        nn = surf['nn']
        # make absolutely sure these are normalized for Mayavi
        nn = nn / np.sum(nn * nn, axis=1)[:, np.newaxis]

        # Make a solid surface
        vlim = np.max(np.abs(data))
        alpha = alphas[ii]
        with warnings.catch_warnings(record=True):  # traits
            mesh = mlab.pipeline.triangular_mesh_source(x, y, z, surf['tris'])
        mesh.data.point_data.normals = nn
        mesh.data.cell_data.normals = None
        mlab.pipeline.surface(mesh, color=colors[ii], opacity=alpha)

        # Now show our field pattern
        with warnings.catch_warnings(record=True):  # traits
            mesh = mlab.pipeline.triangular_mesh_source(x, y, z, surf['tris'],
                                                        scalars=data)
        mesh.data.point_data.normals = nn
        mesh.data.cell_data.normals = None
        with warnings.catch_warnings(record=True):  # traits
            fsurf = mlab.pipeline.surface(mesh, vmin=-vlim, vmax=vlim)
        fsurf.module_manager.scalar_lut_manager.lut.table = colormap

        # And the field lines on top
        with warnings.catch_warnings(record=True):  # traits
            mesh = mlab.pipeline.triangular_mesh_source(x, y, z, surf['tris'],
                                                        scalars=data)
        mesh.data.point_data.normals = nn
        mesh.data.cell_data.normals = None
        with warnings.catch_warnings(record=True):  # traits
            cont = mlab.pipeline.contour_surface(mesh, contours=21,
                                                 line_width=1.0,
                                                 vmin=-vlim, vmax=vlim,
                                                 opacity=alpha)
        cont.module_manager.scalar_lut_manager.lut.table = colormap_lines

    if '%' in time_label:
        time_label %= (1e3 * evoked.times[time_idx])
    mlab.text(0.01, 0.01, time_label, width=0.4)
    mlab.view(10, 60)
    return fig
Esempio n. 58
0
    jx.append(gradientDictList[i]['J'][1])
    jy.append(gradientDictList[i]['J'][2])
    jz.append(gradientDictList[i]['J'][3])

    tx.append(gradientDictList[i]['ToverW'][1])
    ty.append(gradientDictList[i]['ToverW'][2])
    tz.append(gradientDictList[i]['ToverW'][3])

f=mlab.figure(bgcolor=(.5,.5,.5))


j=mlab.quiver3d(xs,ys,zs,jx,jy,jz, scale_factor=.002,color=(1,0,0),name='J')
m=mlab.quiver3d(xs,ys,zs,baryX,baryY,baryZ, scale_factor=.013,color=(0,0,1),name='Mb')
t=mlab.quiver3d(xs,ys,zs,tx,ty,tz, scale_factor=.1,color=(0,1,0),name='T/W')
pt=mlab.quiver3d(xs,ys,zs,us,vs,ws, scale_factor=.01,color=(1,1,1),name='projT/W')
mlab.text(.01,.2,'J   ',color=(1,0,0),width=0.1)
mlab.text(.01,.4,'Mb  ',color=(0,0,1),width=0.1)
mlab.text(.01,.5,'T/W ',color=(0,1,0),width=0.1)
mlab.text(.01,.6,'-projT/W',color=(1,1,1),width=0.1)
mlab.title("Gradients along track")


mlab.axes(color=(.7,.7,.7),xlabel='a')
mlab.xlabel('a')
mlab.ylabel('edMax')
mlab.zlabel('rpoe')

mlab.show()

exit()
###############################