Ejemplo n.º 1
0
def plotROI3d(ROI):
    x = ROI['x']
    y = ROI['y']
    z = ROI['z']
    mlab.points3d(x - np.mean(x),
                  y - np.mean(y),
                  z - np.mean(z), opacity=.1)
Ejemplo n.º 2
0
def viewImgWithNodes(img, spacing, contours,g, title=''):

    mlab.figure(bgcolor=(0, 0, 0), size=(900, 900))
    
    #src = mlab.pipeline.scalar_field(img)
    ## Our data is not equally spaced in all directions:
    #src.spacing = [1, 1, 1]
    #src.update_image_data = True
    #
    #mlab.pipeline.iso_surface(src, contours=contours, opacity=0.2)
    nodes = np.array(g.nodes())
    dsize = 4*np.ones(nodes.shape[0],dtype='float32')
    print(dsize.shape,nodes.shape)
    #mlab.points3d(nodes[:,0],nodes[:,1],nodes[:,2],color=(0.0,1.0,0.0))
    mlab.points3d(nodes[:,2],nodes[:,1],nodes[:,0],dsize,color=(0.0,0.0,1.0), scale_factor=0.25)
    
    for n1, n2, edge in g.edges(data=True):
        path = [n1]+edge['path']+[n2]
        pa = np.array(path)
        #print pa
        mlab.plot3d(pa[:,2],pa[:,1],pa[:,0],color=(0,1,0),tube_radius=0.25)
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    mlab.title(title, height=0.1)
    
    mlab.show()
Ejemplo n.º 3
0
def spin(fcm, idx0, idx1, idx2):
    """Plots 3D data as points in space."""
    x = fcm[:, idx0]
    y = fcm[:, idx1]
    z = fcm[:, idx2]

    s = trilinear_interpolate(x, y, z)

    #     bins = int(len(x)**(1/3.0))

    #     xfrac, xint = numpy.modf((x - numpy.min(x))/
    #                              (numpy.max(x)-numpy.min(x))*(bins-1))
    #     yfrac, yint = numpy.modf((y - numpy.min(y))/
    #                              (numpy.max(y)-numpy.min(y))*(bins-1))
    #     zfrac, zint = numpy.modf((z - numpy.min(z))/
    #                              (numpy.max(z)-numpy.min(z))*(bins-1))

    #     xint = xint.astype('i')
    #     yint = yint.astype('i')
    #     zint = zint.astype('i')

    # not interpolated - kiv write trilinear_interpolate function
    #     h, edges = numpy.histogramdd(fcm[:,[idx0, idx1, idx2]], bins=bins)
    #     v = h[xint, yint, zint]

    mlab.figure()
    mlab.points3d(x, y, z, s, mode='point')
    mlab.xlabel(fcm.channels[idx0])
    mlab.ylabel(fcm.channels[idx1])
    mlab.zlabel(fcm.channels[idx2])
Ejemplo n.º 4
0
    def _plot_max_Value( self ):
        X = self.X_hf[:, 0]
        Y = self.Y_hf[:, 0]
        Z = self.Z_hf[:, 0]


        plot_col = getattr( self, self.plot_column )[:, 0]
        scale = 1 / max( plot_col )
#        if self.plot_column == 'n_tex':
#            plot_col = where( plot_col < 0, 0, plot_col )

        mlab.figure( figure = "SFB532Demo",
                     bgcolor = ( 1.0, 1.0, 1.0 ),
                     fgcolor = ( 0.0, 0.0, 0.0 ) )

        mlab.points3d( X, Y, ( -1.0 ) * Z, plot_col,
#                       colormap = "gist_rainbow",
#                       colormap = "Reds",
                       colormap = "copper",
                       mode = "cube",
                       scale_factor = scale )
        mlab.outline()

        mlab.scalarbar( title = self.plot_column, orientation = 'vertical' )

        mlab.show
Ejemplo n.º 5
0
 def _plot_fired( self ):
     X = self.info_shell.X[:, 0]
     Y = self.info_shell.Y[:, 0]
     Z = self.info_shell.Z[:, 0]
     plot_col = getattr( self, self.plot_column )[:, 0]
     mlab.points3d( X, Y, Z, plot_col )
     mlab.show()
Ejemplo n.º 6
0
    def show_3d(self):
        """SHOW_3D - Use mayavi2 to visualize point cloud.
        
        Usage: obj.show_3d()

        """

        from enthought.mayavi import mlab

        # I want at most 50K points
        stride = 1 + len(self) / 50000

        pts = self[:, ::stride]
        colors = np.ones(pts.shape[1], dtype=np.uint8)
        # Draw clusters in point cloud
        fig = mlab.figure()
        mlab.points3d(
            pts[0, :],
            pts[1, :],
            pts[2, :],
            colors,
            colormap="spectral",
            figure=fig,
            scale_mode="none",
            scale_factor=0.02,
        )

        mlab.view(180, 180)
        mlab.show()
Ejemplo n.º 7
0
def initialize_rope_from_cloud(xyzs, plotting=False):
    xyzs = xyzs.reshape(-1,3)
    if len(xyzs) > 500: xyzs = xyzs[::len(xyzs)//500]

    pdists = ssd.squareform(ssd.pdist(xyzs,'sqeuclidean'))
    G = nx.Graph()
    for (i_from, row) in enumerate(pdists):
        to_inds = np.flatnonzero(row[:i_from] < MAX_DIST**2)
        for i_to in to_inds:
            G.add_edge(i_from, i_to, weight = pdists[i_from, i_to])

    A = nx.floyd_warshall_numpy(G)
    A[np.isinf(A)] = 0
    (i_from_long, i_to_long) = np.unravel_index(A.argmax(), A.shape)

    nodes = G.nodes();
    path = nx.shortest_path(G, source=nodes[i_from_long], target=nodes[i_to_long])
    xyz_path = xyzs[path,:]
    xyzs_unif = curves.unif_resample(xyz_path,N_CTRL_PTS,tol=.005)
    labels = np.ones(len(xyzs_unif)-1,'int')
    labels[[0,-1]] = 2

    if plotting:
        import enthought.mayavi.mlab as mlab
        mlab.plot3d(*xyzs_unif.T, tube_radius=.001)
        mlab.points3d(*xyzs.T, scale_factor=.01)
        mlab.show()

    return xyzs_unif, labels
Ejemplo n.º 8
0
def plot_XYZ():
    mlab.points3d( X, Y, Z_wf,
                   error_Z_abs,
                   colormap = "YlOrBr",
                   mode = "cube",
                   scale_factor = 100. )
    mlab.scalarbar( orientation = 'vertical' )
Ejemplo n.º 9
0
    def show_3d(self):
        """SHOW - Use mayavi2 to visualize point cloud.
        
        Usage: DepthImage.show()

        """
       
        from enthought.mayavi import mlab
       
        # Get 3D points
        pts = self.tocloud()

        # I want at most 50K points
        stride = 1 + pts.shape[1]/50000

        pts = np.c_[pts[:,::stride], pts[:,::stride]]
        colors = np.ones(pts.shape[1], dtype=np.uint8)

        # Draw clusters in point cloud
        fig = mlab.figure()
        mlab.points3d(pts[0,:], pts[1,:], pts[2,:], \
                      colors, colormap='spectral', figure=fig, \
                      scale_mode='none', scale_factor=0.02)

        mlab.view(180,180)
        mlab.show() 
Ejemplo n.º 10
0
def plot_atoms(atoms):

    for atom in atoms:
        pos = atom.position
        mlab.points3d(
            [pos[0]],
            [pos[1]],
            [pos[2]],
            scale_factor=4,
            resolution=20,
            color=(1, 0, 0),  # this should get species specifuc
            scale_mode="none",
        )

    (u0, u1, u2) = atoms.get_cell()
    origin = np.array([0.0, 0.0, 0.0])

    plot_cylinder(origin, u0)
    plot_cylinder(origin, u1)
    plot_cylinder(origin, u2)

    plot_cylinder(u0, u0 + u1)
    plot_cylinder(u0, u0 + u2)

    plot_cylinder(u1, u1 + u0)
    plot_cylinder(u1, u1 + u2)

    plot_cylinder(u2, u2 + u0)
    plot_cylinder(u2, u2 + u1)

    plot_cylinder(u0 + u1, u0 + u1 + u2)
    plot_cylinder(u1 + u2, u0 + u1 + u2)
    plot_cylinder(u0 + u2, u0 + u1 + u2)
    mlab.show()
Ejemplo n.º 11
0
def spin(fcm, idx0, idx1, idx2):
    """Plots 3D data as points in space."""
    x = fcm[:, idx0]
    y = fcm[:, idx1]
    z = fcm[:, idx2]

    s = trilinear_interpolate(x, y, z)

#     bins = int(len(x)**(1/3.0))

#     xfrac, xint = numpy.modf((x - numpy.min(x))/
#                              (numpy.max(x)-numpy.min(x))*(bins-1))
#     yfrac, yint = numpy.modf((y - numpy.min(y))/
#                              (numpy.max(y)-numpy.min(y))*(bins-1))
#     zfrac, zint = numpy.modf((z - numpy.min(z))/
#                              (numpy.max(z)-numpy.min(z))*(bins-1))

#     xint = xint.astype('i')
#     yint = yint.astype('i')
#     zint = zint.astype('i')

#     # not interpolated - kiv write trilinear_interpolate function
#     h, edges = numpy.histogramdd(fcm[:,[idx0, idx1, idx2]], bins=bins)
#     v = h[xint, yint, zint]

    mlab.figure()
    mlab.points3d(x, y, z, s, mode='point')
    mlab.xlabel(fcm.channels[idx0])
    mlab.ylabel(fcm.channels[idx1])
    mlab.zlabel(fcm.channels[idx2])
Ejemplo n.º 12
0
def show_votegrid(vg, color=(1, 0, 0), opacity=1):
    from enthought.mayavi import mlab
    mlab.clf()
    x, y, z = np.nonzero(vg > 0)
    if not color is None:
        mlab.points3d(x,
                      y,
                      z,
                      opacity=opacity,
                      color=color,
                      scale_factor=1,
                      scale_mode='none',
                      mode='cube')
    else:
        mlab.points3d(x,
                      y,
                      z,
                      vg[vg > 0],
                      opacity=opacity,
                      scale_factor=1,
                      scale_mode='none',
                      mode='cube')

    gridmin, gridmax = config.bounds
    X, Y, Z = np.array(gridmax) - gridmin
    #mlab.axes(extent=[0,0,0,X,Y,Z])
    mlab.draw()
Ejemplo n.º 13
0
 def drawArrows(self, figure, bbox, number, partner):
     """
     draw an 'arrow' from the cell 'number' to 'partner'
     """
     #load the center of mass position
     n = np.array(number)
     p = np.array(partner)
     n.shape = (n.size, )
     p.shape = (p.size, )
     if p.size > 0 and n.size > 0:
             com1 = self.file1["features"][str(n[0])]["com"][:]
             com2 = self.file2["features"][str(p[0])]["com"][:]
             #write the cell label as text
             mlab.text3d(com1[2]-bbox[2]+1,com1[1]-bbox[1]+1,com1[0]-bbox[0]+1, str(number), color=(1,1,1), figure=figure)
             
             #plot a point where the current cell is
             mlab.points3d([com1[2]-bbox[2]+1],[com1[1]-bbox[1]+1],[com1[0]-bbox[0]+1],color=(0,0,1), figure=figure)
             
             #plot a line to the descendant's center
             mlab.plot3d([com1[2]-bbox[2]+1,com2[2]-bbox[2]+1],
                         [com1[1]-bbox[1]+1,com2[1]-bbox[1]+1],
                         [com1[0]-bbox[0]+1,com2[0]-bbox[0]+1],
                         tube_radius=0.2, color=(1,0,0), figure=figure)
             
             #plot a second line, if there is a split
             if p.size == 2:
                 com3 = self.file2["features"][str(p[1])]["com"][:]
                 mlab.plot3d([com1[2]-bbox[2]+1,com3[2]-bbox[2]+1],
                             [com1[1]-bbox[1]+1,com3[1]-bbox[1]+1],
                             [com1[0]-bbox[0]+1,com3[0]-bbox[0]+1],
                             tube_radius=0.2, color=(1,0,0), figure=figure)
Ejemplo n.º 14
0
def plot_atoms(atoms):

    for atom in atoms:
        pos = atom.get_position()
        mlab.points3d(
            [pos[0]],
            [pos[1]],
            [pos[2]],
            scale_factor=4,
            resolution=20,
            color=(1, 0, 0),  #this should get species specifuc
            scale_mode='none')

    (u0, u1, u2) = atoms.get_cell()
    origin = np.array([0.0, 0.0, 0.0])

    plot_cylinder(origin, u0)
    plot_cylinder(origin, u1)
    plot_cylinder(origin, u2)

    plot_cylinder(u0, u0 + u1)
    plot_cylinder(u0, u0 + u2)

    plot_cylinder(u1, u1 + u0)
    plot_cylinder(u1, u1 + u2)

    plot_cylinder(u2, u2 + u0)
    plot_cylinder(u2, u2 + u1)

    plot_cylinder(u0 + u1, u0 + u1 + u2)
    plot_cylinder(u1 + u2, u0 + u1 + u2)
    plot_cylinder(u0 + u2, u0 + u1 + u2)
    mlab.show()
Ejemplo n.º 15
0
def test_den():
    P = np.random.random((10,10))
    #P=np.load(r'c:\maxdenP.np.npy')
    #myfilestr=r'c:\structfactors_density.dat'
    #x,y,z=np.loadtxt(myfilestr).T
    #P=z.reshape((101,101))
    #print P.shape
    fig=mlab.figure()    
    x,y,z=gen_as()   
    #view along z-axis
    pts_as=mlab.points3d(x,y,z-.125,color=(1,0,0),colormap='gist_rainbow',figure=fig,scale_factor=.1)
    x,y,z=gen_fe()  
    print 'x',x
    print 'y',y
    print 'z',z
    pts_fe=mlab.points3d(x,y,z-.125,color=(0,1,0),colormap='gist_rainbow',figure=fig,scale_factor=.02)
    x,y,z=gen_sr()  
    pts_sr=mlab.points3d(x,y,z-.125,color=(0,0,1),colormap='gist_rainbow',figure=fig)
    outline=mlab.outline(figure=fig,extent=[0,1,0,1,-1,0])
    mlab.orientation_axes(figure=fig,xlabel='a',ylabel='b',zlabel='c')
    print 'shape',P.shape
    P = P[:,:, np.newaxis]
    print 'after',P.shape
    src = mlab.pipeline.scalar_field(P)
    #src = mlab.pipeline.array2d_source(P)
    surf = mlab.pipeline.surface(src,figure=fig,extent=[0,1,0,1,-1,0],name='surf2',opacity=0.4)
    #surf.transform.GetTransform().RotateX(90)
    print 'done'
Ejemplo n.º 16
0
def plot_normals(pts, normals, curvature=None):

    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1

    u = normals[0, :].A1
    v = normals[1, :].A1
    w = normals[2, :].A1

    if curvature != None:
        #mlab.points3d(x,y,z,curvature,mode='point',scale_factor=1.0)
        mlab.points3d(x,
                      y,
                      z,
                      curvature,
                      mode='sphere',
                      scale_factor=0.1,
                      mask_points=1)
        mlab.colorbar()
    else:
        mlab.points3d(x, y, z, mode='point')
    mlab.quiver3d(x, y, z, u, v, w, mask_points=16, scale_factor=0.1)
    #    mlab.axes()
    mlab.show()
Ejemplo n.º 17
0
def ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]):
    # Get data from calculation files
    with jasp(directory) as calc:
        atoms = calc.get_atoms()
        x, y, z, cd = calc.get_charge_density()

    mlab.figure(bgcolor=(0,0,0), size=(640,480))

    # Draw atoms
    if DrawAtoms == True:
        for atom in atoms:
            mlab.points3d(atom.x,
                          atom.y,
                          atom.z,
                          scale_factor=vdw_radii[atom.number]/10.,
                          resolution=16,
                          color=tuple(cpk_colors[atom.number]),
                          scale_mode='none')
    # Draw unit cell
    if DrawCell == True:
        a1, a2, a3 = atoms.get_cell()
        origin = [0,0,0]
        cell_matrix = [[origin, a1],
                       [origin, a2],
                       [origin, a3],
                       [a1, a1+a2],
                       [a1, a1+a3],
                       [a2, a2+a1],
                       [a2, a2+a3],
                       [a3, a1+a3],
                       [a3, a2+a3],
                       [a1+a2, a1+a2+a3],
                       [a2+a3, a1+a2+a3],
                       [a1+a3, a1+a3+a2]] # contains all points on the box
        for p1, p2 in cell_matrix:
            mlab.plot3d([p1[0], p2[0]], # x-coords of box
                        [p1[1], p2[1]], # y-coords
                        [p1[2], p2[2]]) # z-coords

    # Plot the charge density
    src = mlab.pipeline.scalar_field(x, y, z, cd) #Source data
    vmin = cd.min() #find minimum and maximum value of CD data
    vmax = cd.max()
    vol = mlab.pipeline.volume(src) # Make a volumetric representation of the data

    # Set opacity transfer function
    from tvtk.util.ctf import PiecewiseFunction
    otf = PiecewiseFunction()
    otf.add_point(vmin, opacity_range[0]) #Transparency at zero electron density
    otf.add_point(vmax*1, opacity_range[1]) #Transparency at max electron density
    vol._otf=otf
    vol._volume_property.set_scalar_opacity(otf)

    #Show a legend
    mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f')
    mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle
    mlab.show()
    if save_file != None:
        mlab.savefig(save_file)
Ejemplo n.º 18
0
def plot_XYZ():
    mlab.points3d( X, Y, Z,
                   error_t_rel,
#                   error_t_abs,
                   colormap = "YlOrBr",
                   mode = "cube",
                   scale_factor = 0.015 )
    mlab.scalarbar( orientation = 'vertical' )
Ejemplo n.º 19
0
 def _plot_mayavi_(self):
     from enthought.mayavi import mlab
     color = number2color(self._Z)
     mlab.points3d(self.position[:1], self.position[1:2], self.position[2:],
             scale_factor=3,
             resolution=20,
             color=color,
             scale_mode="none")
Ejemplo n.º 20
0
def downsample_cb(cloud_down):
    print "downsample_cb got called."
    pts = ros_pts_to_np(cloud_down.pts)
    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1
    mlab.points3d(x, y, z, mode="point")
    mlab.show()
Ejemplo n.º 21
0
def downsample_cb(cloud_down):
    print 'downsample_cb got called.'
    pts = ros_pts_to_np(cloud_down.pts)
    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1
    mlab.points3d(x, y, z, mode='point')
    mlab.show()
Ejemplo n.º 22
0
def plotResult3d(result, scale_field='grid_area'):
    """Takes a detailed results numpy array
        
    plots the points, scaled by the num_expressors column
    """
    mlab.points3d(result.data['x'] - np.mean(result.data['x']),
                  result.data['y'] - np.mean(result.data['y']),
                  result.data['z'] - np.mean(result.data['z']),
                  result.data[scale_field])
def plot_taxel_registration_dict(d, color):
    tar = d['transform_array_response']
    x_l, y_l, z_l = [], [], []
    for t in tar.data:
        x_l.append(t.translation.x)
        y_l.append(t.translation.y)
        z_l.append(t.translation.z)

    mlab.points3d(x_l, y_l, z_l, mode='sphere', color=color, scale_factor=0.002)
Ejemplo n.º 24
0
def demo2():
    from enthought.mayavi import mlab
    pts = generate_pts()
    direction, magnitudes = gaussian_curvature(pts)    
    print 'eigen values', magnitudes.T
    mlab.points3d(pts[0,:].A1, pts[1,:].A1, pts[2,:].A1, mode='sphere', scale_factor=.05)
    plot_axis(0,0,0, direction)
    plot_axis(2,0,0, np.eye(3))
    mlab.show()    
Ejemplo n.º 25
0
def test_den():
    #P = np.random.random((10,10))
    #P=np.load(r'c:\maxdenP.np.npy')
    #myfilestr=r'c:\structfactors_density.dat'
    #x,y,z=np.loadtxt(myfilestr).T
    #P=z.reshape((101,101))
    #print P.shape
    fig = mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    x, y, z = np.array([[1, 0, 1], [0, -1, 1], [-1, 0, -1], [0, 1, -1],
                        [1, 1, 0], [-1, -1, 0]], 'float64').T
    #view along z-axis
    pts_as = mlab.points3d(x,
                           y,
                           z,
                           color=(1, 0, 0),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.3)
    #x,y,z=gen_fe()
    print 'x', x, x.shape
    print 'y', y, y.shape
    print 'z', z, z.shape
    x, y, z = np.array([
        [0, 1, 1],
        [0, -1, -1],
    ], 'float64').T
    pts_FE = mlab.points3d(x,
                           y,
                           z,
                           color=(0, 1, 0),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.3)
    mlab.text3d(0, 1, 1, '011', scale=.2, color=(1, 1, 0))
    mlab.text3d(1, 1, 0, '110', scale=.2)
    mlab.text3d(-1, -1, 0, '-1-10', scale=.2)
    mlab.text3d(1, 0, 1, '101', scale=.2)
    mlab.text3d(0, -1, 1, '0-11', scale=.2)
    mlab.text3d(-1, 0, -1, '-10-1', scale=.2)
    mlab.text3d(0, 1, -1, '01-1', scale=.2)

    #pts_fe=mlab.points3d(x,y,z-.125,color=(0,1,0),colormap='gist_rainbow',figure=fig,scale_factor=.02)
    #x,y,z=gen_sr()
    #print 'x',x,x.shape
    #pts_sr=mlab.points3d(x,y,z-.125,color=(0,0,1),colormap='gist_rainbow',figure=fig)
    #outline=mlab.outline(figure=fig,extent=[0,1,0,1,-1,0])
    outline = mlab.outline(figure=fig)
    mlab.orientation_axes(figure=fig, xlabel='a', ylabel='b', zlabel='c')
    #print 'shape',P.shape
    #P = P[:,:, np.newaxis]
    #print 'after',P.shape
    #src = mlab.pipeline.scalar_field(P)
    #src = mlab.pipeline.array2d_source(P)
    #surf = mlab.pipeline.surface(src,figure=fig,extent=[0,1,0,1,-1,0],name='surf2',opacity=0.4)
    #surf.transform.GetTransform().RotateX(90)
    print 'done'
Ejemplo n.º 26
0
def display_atoms():
    mol = Molecule.from_file("eth.cml")
    cords=[]
    power = []
    mc = mass_centre(mol)
    for atom in mol:
        cords.append(atom.r  )
        power.append(atom.atno)
    x,y,z = zip(*cords)
    from enthought.mayavi import mlab
    mlab.points3d(x,y,z,power,scale_mode='none')
Ejemplo n.º 27
0
def display_atoms():
    mol = Molecule.from_file("eth.cml")
    cords = []
    power = []
    mc = mass_centre(mol)
    for atom in mol:
        cords.append(atom.r)
        power.append(atom.atno)
    x, y, z = zip(*cords)
    from enthought.mayavi import mlab
    mlab.points3d(x, y, z, power, scale_mode='none')
Ejemplo n.º 28
0
def demo1():
    from enthought.mayavi import mlab
    pts = generate_pts()
    directions, magnitudes = gaussian_curvature(pts)
    print directions.T.A[0].tolist()

    print magnitudes.tolist()
    mlab.points3d(pts[0,:].A1, pts[1,:].A1, pts[2,:].A1, mode='sphere', scale_factor=.05)
    plot_axis(0,0,0, directions)
    plot_axis(2,0,0, np.eye(3))
    mlab.show()
Ejemplo n.º 29
0
def plotKernel3d(k):
    xs=[]
    ys=[]
    zs=[]
    datas=[]
    for x in range(k.shape[0]):
        for y in range(k.shape[1]):
            for z in range(k.shape[2]):
                xs.append(x)
                ys.append(y)
                zs.append(z)
                datas.append(k[x,y,z])
    mlab.points3d(xs,ys,zs,datas)
Ejemplo n.º 30
0
def plot_taxel_registration_dict(d, color):
    tar = d['transform_array_response']
    x_l, y_l, z_l = [], [], []
    for t in tar.data:
        x_l.append(t.translation.x)
        y_l.append(t.translation.y)
        z_l.append(t.translation.z)

    mlab.points3d(x_l,
                  y_l,
                  z_l,
                  mode='sphere',
                  color=color,
                  scale_factor=0.002)
Ejemplo n.º 31
0
def show_votegrid(vg, color=(1, 0, 0), opacity=1):
    from enthought.mayavi import mlab

    mlab.clf()
    x, y, z = np.nonzero(vg > 0)
    if not color is None:
        mlab.points3d(x, y, z, opacity=opacity, color=color, scale_factor=1, scale_mode="none", mode="cube")
    else:
        mlab.points3d(x, y, z, vg[vg > 0], opacity=opacity, scale_factor=1, scale_mode="none", mode="cube")

    gridmin, gridmax = config.bounds
    X, Y, Z = np.array(gridmax) - gridmin
    # mlab.axes(extent=[0,0,0,X,Y,Z])
    mlab.draw()
Ejemplo n.º 32
0
def test_den():
    #P = np.random.random((10,10))
    #P=np.load(r'c:\maxdenP.np.npy')
    #myfilestr=r'c:\structfactors_density.dat'
    #x,y,z=np.loadtxt(myfilestr).T
    #P=z.reshape((101,101))
    #print P.shape
    fig=mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    x,y,z=np.array([[1,0,1],
                    [0,-1,1],
                    [-1,0,-1],
                    [0,1,-1],
                    [1,1,0],
                    [-1,-1,0]
                    ],'float64').T
    #view along z-axis
    pts_as=mlab.points3d(x,y,z,color=(1,0,0),colormap='gist_rainbow',figure=fig,scale_factor=.3)
    #x,y,z=gen_fe()
    print 'x',x,x.shape
    print 'y',y,y.shape
    print 'z',z,z.shape
    x,y,z=np.array([[0,1,1],
                    [0,-1,-1],
                    ],'float64').T
    pts_FE=mlab.points3d(x,y,z,color=(0,1,0),colormap='gist_rainbow',figure=fig,scale_factor=.3)
    mlab.text3d(0, 1, 1,'011',scale=.2,color=(1,1,0))
    mlab.text3d(1, 1, 0,'110',scale=.2)
    mlab.text3d(-1, -1, 0,'-1-10',scale=.2)
    mlab.text3d(1, 0, 1,'101',scale=.2)
    mlab.text3d(0, -1, 1,'0-11',scale=.2)
    mlab.text3d(-1, 0, -1,'-10-1',scale=.2)
    mlab.text3d(0, 1, -1,'01-1',scale=.2)


    #pts_fe=mlab.points3d(x,y,z-.125,color=(0,1,0),colormap='gist_rainbow',figure=fig,scale_factor=.02)
    #x,y,z=gen_sr()
    #print 'x',x,x.shape
    #pts_sr=mlab.points3d(x,y,z-.125,color=(0,0,1),colormap='gist_rainbow',figure=fig)
    #outline=mlab.outline(figure=fig,extent=[0,1,0,1,-1,0])
    outline=mlab.outline(figure=fig)
    mlab.orientation_axes(figure=fig,xlabel='a',ylabel='b',zlabel='c')
    #print 'shape',P.shape
    #P = P[:,:, np.newaxis]
    #print 'after',P.shape
    #src = mlab.pipeline.scalar_field(P)
    #src = mlab.pipeline.array2d_source(P)
    #surf = mlab.pipeline.surface(src,figure=fig,extent=[0,1,0,1,-1,0],name='surf2',opacity=0.4)
    #surf.transform.GetTransform().RotateX(90)
    print 'done'
Ejemplo n.º 33
0
    def save(self,it):

        msh = self.__msh
        w = (self.__eqn).get(self.__var)()

        mlab.clf()
        mlab.points3d(msh.x[:,0], msh.x[:,1], zeros(w.shape), w,
                      scale_factor=self.__scale, scale_mode=self.__mode)
        mlab.outline(extent=[msh.BB[0,0],msh.BB[1,0],msh.BB[0,1],msh.BB[1,1],
                     0,0])
        mlab.view(0,0,self.__zoom,self.__xView)
        mlab.colorbar()
        fSol =  ''.join([self.__figDir,'/',self.__name,'%04d.png'% it])
        #print fSol
        mlab.savefig(fSol)
Ejemplo n.º 34
0
def plot_cell(cell):
    x0,x1,y0,y1,z0,z1 = cell.bounds
    p = mlab.points3d((x0+x1)/2, (y0+y1)/2, (z0+z1)/2, opacity=0.2, mode="cube")
    cube = p.glyph.glyph_source.glyph_source
    cube.x_length = x1-x0
    cube.y_length = y1-y0
    cube.z_length = z1-z0
Ejemplo n.º 35
0
 def plot_points(self, x, y, z, spikes=[], t=0, color=(0.5, 0.5, 0.5), csize=1./75.):
     """ Plot spheres representing each node in network """
     if t==0:
         pts = mlab.points3d(x,y,z,
                             color=color,
                             scale_factor = csize)
     else:
         ind = spikes[spikes[:,0]==t, 1].astype(int)
         #ind = ind[ind<=numgran] # looks like there are some indices greater than numgran
         pts = mlab.points3d(x[ind],
                             y[ind],
                             z[ind],
                             color=color,
                             scale_factor = csize)
     pts.glyph.scale_mode = 'data_scaling_off'
     return pts
Ejemplo n.º 36
0
def draw_struct():
    fig = mlab.figure()
    r = gen_fe()
    s = gen_spins()
    #view along z-axis
    x = r[:, 0]
    y = r[:, 1]
    z = r[:, 2]
    u = s[:, 0]
    v = s[:, 1]
    w = s[:, 2]

    #print x.shape
    #print y.shape
    #print z.shape
    pts_as = mlab.points3d(x,
                           y,
                           z,
                           color=(0, 0, 1),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.1)
    mlab.quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=.3, figure=fig)
    outline = mlab.outline(figure=fig, extent=[0, 1, 0, 1, 0, 1])
    mlab.orientation_axes(figure=fig, xlabel='a', ylabel='b', zlabel='c')
    print 'done'
Ejemplo n.º 37
0
    def show( self, x, y, z_middle, displayed_value ):
        """Test contour_surf on regularly spaced co-ordinates like MayaVi.
        """
        print '*** plotting data***'
        s = points3d( X, Y, z_middle, displayed_value, colormap = "gist_rainbow", mode = "cube", scale_factor = 0.3 )

        sb = colorbar( s )
        # Recorded script from Mayavi2
        #try:
        #    engine = mayavi.engine
        #except NameError:
        #    from enthought.mayavi.api import Engine
        #    engine = Engine()
        #    engine.start()
        #if len(engine.scenes) == 0:
        #    engine.new_scene()
        # ------------------------------------------- 
        glyph = s#.pipeline.scenes[0].children[0].children[0].children[0]
        glyph.glyph.glyph_source.glyph_source.center = array( [ 0., 0., 0.] )
        glyph.glyph.glyph_source.glyph_source.progress = 1.0
        glyph.glyph.glyph_source.glyph_source.x_length = 0.6
        glyph.glyph.glyph_source.glyph_source.y_length = 0.6
        sb.scalar_bar.title = 'thickness [m]'
        #print s.pipeline
        #s.scene.background = (1.0, 1.0, 1.0)

        return s
Ejemplo n.º 38
0
    def display(self):
        """ Display Electrode in Mayavi """
        f = mlab.figure(figure=mlab.gcf(),
                        bgcolor=(0,0,0),
                        size=(800,600))

        # Build Electrode tip
        x, y, z = self.shaft[0,:].T
        self.mlab_tip = mlab.points3d(array(x),
                                      array(y),
                                      array(z),
                                      scale_factor=self.diameter,
                                      color=(0.5, 0.5, 0.5),
                                      name='Electrode Tip')
        self.mlab_tip.glyph.glyph_source.glyph_source.theta_resolution = 30
        self.mlab_tip.glyph.glyph_source.glyph_source.phi_resolution   = 16

        # Build Electrode Shaft
        x, y, z = self.shaft.T
        self.mlab_shaft = mlab.plot3d(x.T, y.T, z.T,
                               color=(0.5, 0.5, 0.5),
                               tube_radius=self.diameter / 2,
                               tube_sides=40,
                               name='Electrode')
        self.mlab_shaft.parent.parent.filter.capping=True
Ejemplo n.º 39
0
def compute_delaunay_edges(x, y, z, visualize=False):
    """ Given 3-D points, returns the edges of their 
        Delaunay triangulation.

        Parameters
        -----------
        x: ndarray
            x coordinates of the points
        y: ndarray
            y coordinates of the points
        z: ndarray
            z coordinates of the points

        Returns
        ---------
        new_x: ndarray
            new x coordinates of the points (same coords but different 
            assignment of points)
        new_y: ndarray
            new y coordinates of the points (same coords but different 
            assignment of points)
        new_z: ndarray
            new z coordinates of the points (same coords but different 
            assignment of points)
        edges: 2D ndarray.
            The indices of the edges of the Delaunay triangulation as a
            (N, 2) array [[pair1_index1, pair1_index2],
                          [pair2_index1, pair2_index2], 
                          ...                         ]
    """
    if visualize:
        vtk_source = mlab.points3d(x, y, z, opacity=0.3, mode='2dvertex')
        vtk_source.actor.property.point_size = 3
    else:
        vtk_source = mlab.points3d(x, y, z, figure=False)
    delaunay = mlab.pipeline.delaunay3d(vtk_source)
    delaunay.filter.offset = 999  # seems more reliable than the default
    edges = mlab.pipeline.extract_edges(delaunay)
    if visualize:
        mlab.pipeline.surface(edges, opacity=0.3, line_width=3)

    # We extract the output array. the 'points' attribute itself
    # is a TVTK array, that we convert to a numpy array using
    # its 'to_array' method.
    new_x, new_y, new_z = edges.outputs[0].points.to_array().T
    lines = edges.outputs[0].lines.to_array()
    return new_x, new_y, new_z, np.array([lines[1::3], lines[2::3]]).T
Ejemplo n.º 40
0
def initialize_rope(label_img, xyz,bgr, plotting=False):

    # XXX that sucks
    rope_mask = (label_img==1) | ndi.morphology.binary_dilation(label_img==2,np.ones((5,5)))
    rope_mask = ndi.binary_opening(rope_mask, np.ones((3,3)))
    rope_mask = ndi.binary_dilation(rope_mask, np.ones((15,15)))

    skel = mip.skeletonize(rope_mask)

    if plotting: 
        cv2.imshow('bgr',bgr.copy())
        cv2.imshow('labels',label_img.astype('uint8')*50)
        cv2.imshow("skel", skel.astype('uint8')*50)
        cv2.imshow("rope_mask", rope_mask.astype('uint8')*50)
        cv2.waitKey(5)


    #start_end = (uv_start, uv_end) = get_cc_centers(label_img==2,2)


    G = skel2graph(skel)
    path2d = longest_shortest_path(G)
    path3d = to3d(path2d,xyz)


    xyzs_unif = curves.unif_resample(path3d,N_CTRL_PTS,tol=.0025)

    #us,vs = xyz2uv(xyzs_unif).T
    #labels = label_img[us,vs]
    labels = np.ones(xyzs_unif.shape[0]-1,'int')
    labels[0] = labels[-1] = 2

    if plotting:
        xs,ys,zs = xyzs_unif.T
        us_skel, vs_skel = np.nonzero(skel)
        xs_skel, ys_skel, zs_skel = to3d(np.c_[us_skel, vs_skel], xyz).T

        import matplotlib.pyplot as plt, enthought.mayavi.mlab as mlab
        mlab.plot3d(xs,ys,zs,np.arange(len(xs)),tube_radius=.0025, colormap='spectral')
        mlab.points3d(xs_skel, ys_skel, zs_skel, scale_factor=.02, color=(1,1,1),opacity=.1)
        for (i,path) in enumerate(path3d):
            mlab.text3d(path[0,0],path[0,1],path[0,2],str(2*i),scale=.01,color=(0,0,0))
            mlab.text3d(path[-1,0],path[-1,1],path[-1,2],str(2*i+1),scale=.01,color=(0,0,0))
        mlab.show()


    return xyzs_unif, labels
Ejemplo n.º 41
0
def compute_delaunay_edges(x, y, z, visualize=False):
    """ Given 3-D points, returns the edges of their 
        Delaunay triangulation.

        Parameters
        -----------
        x: ndarray
            x coordinates of the points
        y: ndarray
            y coordinates of the points
        z: ndarray
            z coordinates of the points

        Returns
        ---------
        new_x: ndarray
            new x coordinates of the points (same coords but different 
            assignment of points)
        new_y: ndarray
            new y coordinates of the points (same coords but different 
            assignment of points)
        new_z: ndarray
            new z coordinates of the points (same coords but different 
            assignment of points)
        edges: 2D ndarray.
            The indices of the edges of the Delaunay triangulation as a
            (N, 2) array [[pair1_index1, pair1_index2],
                          [pair2_index1, pair2_index2], 
                          ...                         ]
    """
    if visualize:
        vtk_source = mlab.points3d(x, y, z, opacity=0.3, mode='2dvertex')
        vtk_source.actor.property.point_size = 3
    else:
        vtk_source = mlab.points3d(x, y, z, figure=False)
    delaunay =  mlab.pipeline.delaunay3d(vtk_source)
    delaunay.filter.offset = 999    # seems more reliable than the default
    edges = mlab.pipeline.extract_edges(delaunay)
    if visualize:
        mlab.pipeline.surface(edges, opacity=0.3, line_width=3)

    # We extract the output array. the 'points' attribute itself
    # is a TVTK array, that we convert to a numpy array using
    # its 'to_array' method.
    new_x, new_y, new_z = edges.outputs[0].points.to_array().T
    lines = edges.outputs[0].lines.to_array()
    return new_x, new_y, new_z, np.array([lines[1::3], lines[2::3]]).T
Ejemplo n.º 42
0
def plot_cell(cell):
    x0, x1, y0, y1, z0, z1 = cell.bounds
    p = mlab.points3d((x0 + x1) / 2, (y0 + y1) / 2, (z0 + z1) / 2,
                      opacity=0.2,
                      mode="cube")
    cube = p.glyph.glyph_source.glyph_source
    cube.x_length = x1 - x0
    cube.y_length = y1 - y0
    cube.z_length = z1 - z0
Ejemplo n.º 43
0
    def drawArrows(self, figure, bbox, number, partner):
        """
        draw an 'arrow' from the cell 'number' to 'partner'
        """
        #load the center of mass position
        n = np.array(number)
        p = np.array(partner)
        n.shape = (n.size, )
        p.shape = (p.size, )
        if p.size > 0 and n.size > 0:
            com1 = self.file1["features"][str(n[0])]["com"][:]
            com2 = self.file2["features"][str(p[0])]["com"][:]
            #write the cell label as text
            mlab.text3d(com1[2] - bbox[2] + 1,
                        com1[1] - bbox[1] + 1,
                        com1[0] - bbox[0] + 1,
                        str(number),
                        color=(1, 1, 1),
                        figure=figure)

            #plot a point where the current cell is
            mlab.points3d([com1[2] - bbox[2] + 1], [com1[1] - bbox[1] + 1],
                          [com1[0] - bbox[0] + 1],
                          color=(0, 0, 1),
                          figure=figure)

            #plot a line to the descendant's center
            mlab.plot3d([com1[2] - bbox[2] + 1, com2[2] - bbox[2] + 1],
                        [com1[1] - bbox[1] + 1, com2[1] - bbox[1] + 1],
                        [com1[0] - bbox[0] + 1, com2[0] - bbox[0] + 1],
                        tube_radius=0.2,
                        color=(1, 0, 0),
                        figure=figure)

            #plot a second line, if there is a split
            if p.size == 2:
                com3 = self.file2["features"][str(p[1])]["com"][:]
                mlab.plot3d([com1[2] - bbox[2] + 1, com3[2] - bbox[2] + 1],
                            [com1[1] - bbox[1] + 1, com3[1] - bbox[1] + 1],
                            [com1[0] - bbox[0] + 1, com3[0] - bbox[0] + 1],
                            tube_radius=0.2,
                            color=(1, 0, 0),
                            figure=figure)
Ejemplo n.º 44
0
    def plot3d(self,ix=0,iy=1,iz=2,clf=True):
        """
        Generates a 3-dimensional plot of the data set and principle components
        using mayavi.

        ix, iy, and iz specify which of the input p-dimensions to place on each of
        the x,y,z axes, respectively (0-indexed).
        """
        import enthought.mayavi.mlab as M
        if clf:
            M.clf()
        z3=np.zeros(3)
        v=(self.getEigenvectors()*self.getEigenvalues())
        M.quiver3d(z3,z3,z3,v[ix],v[iy],v[iz],scale_factor=5)
        M.points3d(self.N[:,ix],self.N[:,iy],self.N[:,iz],scale_factor=0.3)
        if self.names:
            M.axes(xlabel=self.names[ix]+'/sigma',ylabel=self.names[iy]+'/sigma',zlabel=self.names[iz]+'/sigma')
        else:
            M.axes()
Ejemplo n.º 45
0
    def do(self):
        ############################################################
        # Imports.
        from enthought.mayavi import mlab
              
        ############################################################
        # Create a new scene and set up the visualization.
        s = self.new_scene()

        ############################################################
        # run all the "test_foobar" functions in the mlab module.
        for name, func in getmembers(mlab):
            if not callable(func) or not name[:4] in ('test', 'Test'):
                continue
            mlab.clf()
            func()
            # Mayavi has become too fast: the operator cannot see if the
            # Test function was succesful.
            sleep(0.1)
     
        ############################################################
        # Test some specific corner-cases
        import numpy
        x, y, z = numpy.mgrid[1:10, 1:10, 1:10]
        u, v, w = numpy.mgrid[1:10, 1:10, 1:10]
        s = numpy.sqrt(u**2 + v**2)
        
        mlab.clf()
        # Test the extra argument "scalars"
        mlab.quiver3d(x, y, z, u, v, w, scalars=s)

        # Test surf with strange-shaped inputs
        X, Y = numpy.ogrid[-10:10, -10:10]
        Z = X**2 + Y**2
        mlab.surf(X, Y, Z)
        mlab.surf(X.ravel(), Y.ravel(), Z)

        x, y, z = numpy.mgrid[-10:10, -10:10, -3:2]
        mlab.flow(x, y, z)

        # Test glyphs with number-only coordinnates
        mlab.points3d(0, 0, 0, resolution=50)
Ejemplo n.º 46
0
 def _plot3d(self, a, showCP, npoints):
     
     """
         Internal plot function, use Spline.plot().
     """
     if not isplot3d:
         raise NotImplementedError('Lacking Mayavi to do the plotting.')
         
     x = self(np.linspace(self.knots[2],self.knots[-3],npoints,endpoint=0))
     k = self(np.hstack((self.knots[2:-3],self.knots[-3]-1e-15)))
     ml.plot3d(x[:,a[0]],x[:,a[1]],x[:,a[2]],color=(.5,.2,.3))
     ml.points3d(k[:,a[0]],k[:,a[1]],k[:,a[2]],
                 color=(.5,.2,.3),scale_factor=.3)
     
     if showCP:
         ml.plot3d(self.cp[:,a[0]], self.cp[:,a[1]],
                   self.cp[:,a[2]], color=(.2,.4,.4))
         ml.points3d(self.cp[:,a[0]], self.cp[:,a[1]],
                     self.cp[:,a[2]], color=(.2,.4,.4), scale_factor=.3)
     ml.show()
Ejemplo n.º 47
0
def plot_points(pts,
                color=(1., 1., 1.),
                scale_factor=0.02,
                mode='point',
                scalar_list=None):
    if scalar_list != None:
        mlab.points3d(pts[0, :].A1,
                      pts[1, :].A1,
                      pts[2, :].A1,
                      scalar_list,
                      mode=mode,
                      scale_factor=scale_factor)
        mlab.colorbar()
    else:
        mlab.points3d(pts[0, :].A1,
                      pts[1, :].A1,
                      pts[2, :].A1,
                      mode=mode,
                      color=color,
                      scale_factor=scale_factor)
Ejemplo n.º 48
0
def plot_normals(pts,
                 normals,
                 curvature=None,
                 mask_points=1,
                 color=(0., 1., 0.),
                 scale_factor=0.1):
    x = pts[0, :].A1
    y = pts[1, :].A1
    z = pts[2, :].A1

    u = normals[0, :].A1
    v = normals[1, :].A1
    w = normals[2, :].A1

    if curvature != None:
        curvature = np.array(curvature)
        #idxs = np.where(curvature>0.03)
        #mlab.points3d(x[idxs],y[idxs],z[idxs],curvature[idxs],mode='sphere',scale_factor=0.1,mask_points=1)
        mlab.points3d(x,
                      y,
                      z,
                      curvature,
                      mode='sphere',
                      scale_factor=0.1,
                      mask_points=1,
                      color=color)
        #        mlab.points3d(x,y,z,mode='point')
        mlab.colorbar()
    else:
        mlab.points3d(x, y, z, mode='point')
    mlab.quiver3d(x,
                  y,
                  z,
                  u,
                  v,
                  w,
                  mask_points=mask_points,
                  scale_factor=scale_factor,
                  color=color)
    def generate_mayavi_point_plot(self, srcid_sciclasses_list):
        """ Generate a Mayavi mlab 3D plot which summarizes iterative
        classification of a TUTOR source over the number of epochs
        used/added.
        """
        # # # # # # # # #
        # TODO: I should label which science class by color, as Y axis labels

        from enthought.mayavi.scripts import mayavi2
        mayavi2.standalone(globals())
        from enthought.mayavi import mlab
        
        epoch_ids = [0] # x
        class_groups = [0] # y
        probs = [0] # z
        styles = [0] # numbers used for coloring & glyph sizes
        
        for src_id,sci_classes in srcid_sciclasses_list:
            #print 'src_id:', src_id
            i = 0
            for class_name, class_dict in sci_classes.class_dict.iteritems():
                epoch_ids.extend(class_dict['epoch_ids'])
                class_groups.extend([1]*len(class_dict['epoch_ids']))
                probs.extend(class_dict['probs'])
                styles.extend([i + 1]*len(class_dict['epoch_ids']))
                i += 1

        mlab.points3d(numpy.array(epoch_ids),
                      numpy.array(class_groups),
                      numpy.array(probs)*100.0,
                      numpy.array(styles),
                      colormap="Paired",
                      scale_mode="none",
                      scale_factor=2.0)
        mlab.axes(xlabel='N of epochs',
                  ylabel='science class',
                  zlabel='% Prob.')
Ejemplo n.º 50
0
    def test_several_scene_models(self):
        """ Check that plotting to scene attributes using their
            mlab attribute does create objects as children, and does not
            unset the current scene
        """
        class TestObject(HasTraits):
            scene1 = Instance(MlabSceneModel, ())
            scene2 = Instance(MlabSceneModel, ())

        test_object = TestObject()
        x, y, z = np.random.random((3, 10))
        plt = mlab.plot3d(x, y, z, figure=test_object.scene1.mayavi_scene)
        pts = mlab.points3d(x, y, z, figure=test_object.scene2.mayavi_scene)

        # Check that each figure got the module it should have
        self.assertEqual(plt.scene, test_object.scene1)
        self.assertEqual(pts.scene, test_object.scene2)
Ejemplo n.º 51
0
 def plot_particles3d(self,clf=True,**kwargs):
     """
     Plots the particle locations in a 3d projection with mayavi.
     
     :param bool clf: If True, clear figure before plotting.
         
     kwargs are passed into :func:`enthought.mayavi.mlab.points3d`.
     
     :returns: The result of the plotting command
     """
     from enthought.mayavi import mlab as M
     
     if clf:
         M.clf()
         
     args = list(self._pos.T)
     args.append(self._mass)
     kwargs.setdefault('mode','point')
     
     return M.points3d(*args,**kwargs)
Ejemplo n.º 52
0
def mayavi(structure, N=10):
  """ import this module and run mayavi to see the divide and conquer boxes. 
  
      Enjoy and play around.
  """
  from enthought.mayavi.mlab import points3d
  from pylada.crystal.cppwrappers import periodic_dnc

  mesh, boxes = periodic_dnc(structure, nperbox=30, overlap=0.25, return_mesh = True)

  x, y, z, s = [], [], [], []
  for i, box in enumerate(boxes):
    if i == N: continue
    x.extend([(atom.pos[0] + trans[0]) for atom, trans, inbox in box if inbox])
    y.extend([(atom.pos[1] + trans[1]) for atom, trans, inbox in box if inbox])
    z.extend([(atom.pos[2] + trans[2]) for atom, trans, inbox in box if inbox])
    s.extend([0.5 for atom, trans, inbox in box if inbox])
  points3d(x,y,z,s, scale_factor=0.1, colormap="copper")

  x, y, z, s = [], [], [], []
  for i, box in enumerate(boxes):
    if i < N: continue
    x.extend([(atom.pos[0] + trans[0]) for atom, trans, inbox in box if inbox])
    y.extend([(atom.pos[1] + trans[1]) for atom, trans, inbox in box if inbox])
    z.extend([(atom.pos[2] + trans[2]) for atom, trans, inbox in box if inbox])
    s.extend([float(i+1) + (0. if inbox else 0.4) for atom, trans, inbox in box if inbox])
    break
  points3d(x,y,z,s, scale_factor=0.004, colormap="autumn")
  x, y, z, s = [], [], [], []
  for i, box in enumerate(boxes):
    if i < N: continue
    x.extend([(atom.pos[0] + trans[0]) for atom, trans, inbox in box if not inbox])
    y.extend([(atom.pos[1] + trans[1]) for atom, trans, inbox in box if not inbox])
    z.extend([(atom.pos[2] + trans[2]) for atom, trans, inbox in box if not inbox])
    s.extend([float(i+2) + (0. if inbox else 0.4) for atom, trans, inbox in box if not inbox])
    break
  points3d(x,y,z,s, scale_factor=0.01, opacity=0.3)
Ejemplo n.º 53
0
                   fgcolor=(0.0, 0.0, 0.0),
                   size=(1200, 900))

surf2 = mlab.contour3d(x,y,z,scidata_cleana,contours=[10],\
                opacity=0.5, colormap='RdYlBu', name='[O III]-1')
mlab.outline()
surf3 = mlab.contour3d(x,y,z,scidata_cleana,contours=[40],\
                opacity=1, colormap='Blues', name='[O III]-2')

surf5 = mlab.contour3d(x_b,y_b,z_b,scidata_cleanb,contours=[10],\
                           opacity=0.1,colormap='autumn', name='Hbeta')

surf6 = mlab.points3d((stars[:, 0] - size_x / 2) * 0.5 * astopc,
                      (stars[:, 1] - size_y / 2.) * 0.5 * astopc,
                      stars[:, 0] * 0.0,
                      stars[:, 2] * 0.5 * astopc * 2,
                      color=(0, 0, 0),
                      scale_factor=1,
                      name='Stars')

# Now to make it look decent ...
ax = mlab.axes(extent=[-10, 10, -12, 12, -7, 7], nb_labels=5)
ax.axes.fly_mode = 'outer_edges'
ax.title_text_property.font_size = 10
ax.title_text_property.font_family = 'courier'
ax.label_text_property.font_family = 'courier'

# And a bit of references if anyone is interested ...
mlab.text(
    0.05,
    0.95,
# Now, visualize the connectivity in 3D
try:
    from enthought.mayavi import mlab
except:
    from mayavi import mlab

mlab.figure(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))

# Plot the sensor locations
sens_loc = [raw.info['chs'][picks[i]]['loc'][:3] for i in idx]
sens_loc = np.array(sens_loc)

pts = mlab.points3d(sens_loc[:, 0],
                    sens_loc[:, 1],
                    sens_loc[:, 2],
                    color=(1, 1, 1),
                    opacity=1,
                    scale_factor=0.005)

# Get the strongest connections
n_con = 20  # show up to 20 connections
min_dist = 0.05  # exclude sensors that are less than 5cm apart
threshold = np.sort(con, axis=None)[-n_con]
ii, jj = np.where(con >= threshold)

# Remove close connections
con_nodes = list()
con_val = list()
for i, j in zip(ii, jj):
    if linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
        con_nodes.append((i, j))
x, y, z = np.mgrid[:6, :7, :8]
c = np.zeros((6, 7, 8), dtype=np.int)
c.fill(1)
k = np.random.randint(2, 5, size=(6, 7))

idx_i, idx_j, _ = np.ogrid[:6, :7, :8]
idx_k = k[:, :, np.newaxis] + np.arange(3)
c[idx_i, idx_j, idx_k] = np.random.randint(2, 6, size=(6, 7, 3))

mlab.points3d(x[c > 1],
              y[c > 1],
              z[c > 1],
              c[c > 1],
              mode="cube",
              scale_factor=0.8,
              scale_mode="none",
              transparent=True,
              vmin=0,
              vmax=8,
              colormap="Greys")

mlab.points3d(x[c == 1],
              y[c == 1],
              z[c == 1],
              c[c == 1],
              mode="cube",
              scale_factor=0.8,
              scale_mode="none",
              transparent=True,
              vmin=0,