Пример #1
0
    def show(self, sln, show=True, lib="mpl", notebook=False, filename="a.png",
            **options):
        """
        Shows the solution.

        show ... should it actually plot the window? Set to False in tests.
        lib .... which library to use for the plotting? either "mpl" or "mayavi"
        notebook ... are we running inside Sage notebook? If True, just save
                the image to a.png
        filename ... the name of the filename if we are saving the image (e.g.
                notebook == False)
        """
        self._lib = lib
        self._notebook = notebook
        if lib == "mpl":
            plot_sln_mpl(sln, **options)
            import pylab
            if show:
                if notebook:
                    pylab.savefig(filename)
                else:
                    pylab.ion()
                    pylab.draw()
                    pylab.ioff()
        elif lib == "mayavi":
            plot_sln_mayavi(sln, notebook=notebook)
            from enthought.mayavi import mlab
            if show:
                if notebook:
                    mlab.savefig(filename)
                else:
                    mlab.show()
        else:
            raise NotImplementedError("Unknown library '%s'" % lib)
Пример #2
0
def viewImg(img, spacing, contours):
    mlab.figure(bgcolor=(0, 0, 0), size=(400, 400))
    
    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
    
    
    # Extract some inner structures: the ventricles and the inter-hemisphere
    # fibers. We define a volume of interest (VOI) that restricts the
    # iso-surfaces to the inner of the brain. We do this with the ExtractGrid
    # filter.
    blur = mlab.pipeline.user_defined(blur, filter='ImageGaussianSmooth')
    print("blur type is",type(blur),blur.max())
    #voi = mlab.pipeline.extract_grid(blur)
    #voi.set(x_min=125, x_max=193, y_min=92, y_max=125, z_min=34, z_max=75)
    
    #mlab.pipeline.iso_surface(src, contours=[1,2], colormap='Spectral')
    mlab.pipeline.contour3d(blur)
        
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    
    mlab.show()
Пример #3
0
def feature_plot(unit,size,delta_xyz):
    '''
    A three dimensional plot the the voxilized feature. Does what spy_on but
    does a three dimensional plot rather then z slices.

    feature (type: Lego_Model): contains all of the information required to
    calculate the scattering off the feature
    '''
    from enthought.mayavi import mlab

    dumbie_unit = roll(unit,1,axis = 0)
    dumbie_unit = roll(dumbie_unit,1,axis = 1)
    dumbie_unit[:,0,:] = 0.0
    dumbie_unit[:,-1,:] = 0.0
    dumbie_unit[0,:,:] = 0.0
    dumbie_unit[-1,:,:] = 0.0

    xyz = indices((unit.shape), 'd')


    xyz[0] *= delta_xyz[0]
    xyz[1] *= delta_xyz[1]
    xyz[2] *= delta_xyz[2]


    feature_size = shape(unit)
    mlab.figure(0)
    s = mlab.contour3d(xyz[0],xyz[1],xyz[2],dumbie_unit,opacity=.07,contours = 20)
    mlab.figure(1)
    t = mlab.contour3d(xyz[0],xyz[1],xyz[2]*10,dumbie_unit,opacity=.07,contours = 20)
    mlab.figure(2)
    u = mlab.contour3d(dumbie_unit,opacity=.05,contours = 20)
    mlab.show()
    return
Пример #4
0
def main(argv=None):
    """docstring for main"""
    from enthought.mayavi import mlab
    if argv is None:
        argv = sys.argv

    x1 = x2 = y1 = y2 = 0
    fname = ''
    try:
        fname = argv[1]
        x1, x2, y1, y2 = [int(i) for i in argv[2:]]
    except:
        print('Usage: {0} fname x1 x2 y1 y2'.format(argv[0]))

    print(x1, x2, y1, y2)
    ds = gdal.Open(fname)
    band = ds.GetRasterBand(1)
    STORED_VALUE = band.ReadAsArray(x1, y1, x2 - x1, y2 - y1)
    ds = 0

    # PDS label infos:
    SCALING_FACTOR = 0.25
    OFFSET = -8000
    topo = (STORED_VALUE * SCALING_FACTOR) + OFFSET
    mlab.surf(topo, warp_scale=1 / 115., vmin=1700)
    mlab.colorbar(orientation='vertical',
                  title='Height [m]',
                  label_fmt='%4.0f')
    mlab.show()
Пример #5
0
    def etest(self):
        from enthought.mayavi import mlab
        from numpy import pi, sin, cos, exp, arange, array
        ni=10
        dr, dphi, dtheta = 1.0/ni, 2*pi/ni, pi/ni

        rlin = arange(0.0,1.0+dr,dr)
        plin = arange(0.0,2*pi+dphi,dphi)
        tlin = arange(0.0,pi+dtheta,dtheta)
        r,phi,theta = ndgrid(rlin,plin,tlin)

        a=1

        fr = .5*exp(-r/a)*(cos(2*pi*r/a)+1.0)
        fp = (1.0/6.0)*(cos(3.0*phi)+5.0)
        ft = (1.0/6.0)*(cos(10.0*theta)+5.0)

        f = fr*fp*ft

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


        #mayavi
        #mlab.contour3d(x,y,z,f)
        #mlab.contour3d(r,phi,theta,f)
        i=7
        #mlab.mesh(x[i],y[i],z[i],scalars=f[i])
        mlab.mesh(f[i]*x[i],f[i]*y[i],f[i]*z[i],scalars=f[i])
        mlab.show()

        return
Пример #6
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()
Пример #7
0
def viewImg2(img, spacing, contours):
    print("In viewImg2: (min,max)=(%f,%f)"%(img.min(),img.max()))
    print("contours=",contours)
    mlab.figure(bgcolor=(0, 0, 0), size=(400, 400))
    
    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
    
    
    # Extract some inner structures: the ventricles and the inter-hemisphere
    # fibers. We define a volume of interest (VOI) that restricts the
    # iso-surfaces to the inner of the brain. We do this with the ExtractGrid
    # filter.
    blur = mlab.pipeline.user_defined(src, filter='ImageGaussianSmooth')
    #mlab.pipeline.volume(blur, vmin=0.2, vmax=0.8)
    mlab.pipeline.iso_surface(src, contours=contours)
    #mlab.pipeline.image_plane_widget(blur,
    #                            plane_orientation='z_axes',
    #                            slice_index=img.shape[0]/2,
    #                        )
    #voi = mlab.pipeline.extract_grid(blur)
    #voi.set(x_min=125, x_max=193, y_min=92, y_max=125, z_min=34, z_max=75)
    
    #mlab.pipeline.iso_surface(src, contours=[1,2], colormap='Spectral')
    #mlab.pipeline.contour3d(blur)
        
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    
    mlab.show()
Пример #8
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()
Пример #9
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
Пример #10
0
    def isosurface(self):
        from enthought.mayavi import mlab

        npoints,ndim = self.points.shape
        dimensions = array([20,20,20])

        x = zeros(dimensions)
        y = zeros(dimensions)
        z = zeros(dimensions)
        s = zeros(dimensions)

        ipoint = 0
        for i in range(dimensions[0]):
            for j in range(dimensions[1]):
                for k in range(dimensions[2]):
                    r = self.points[ipoint,:]
                    u = dot(self.axinv,r)
                    #u=r
                    x[i,j,k] = u[0]
                    y[i,j,k] = u[1]
                    z[i,j,k] = u[2]
                    s[i,j,k] = self.E[ipoint]
                    ipoint+=1
                #end for
            #end for
        #end for

        mlab.contour3d(x,y,z,s)
        mlab.show()

        return
def main():
    #set some values to be used later
    sh_order = 6
    verts, edges, efaces = create_unit_sphere(4)

    #read_data from disk
    data, fa, bvec, bval, voxel_size = sample_hardi_data()
    data_slice = data[32:76, 32:76, 26:27]
    fa_slice = fa[32:76, 32:76, 26]

    #normalize data by dividing by b0, this is needed so we can take log later
    norm_data = normalize_data(data_slice, bval, min_signal=1)

    #create an instance of the model
    model_instance = MonoExpOpdfModel(sh_order, bval, bvec, .006)
    model_instance.set_sampling_points(verts, edges)

    #use the model it fit the data
    opdfs_sampled_at_verts = model_instance.evaluate(norm_data)
    opdfs_sph_harm_coef = model_instance.fit_data(norm_data)

    #display the opdf blobs using mayavi
    faces = edges[efaces, 0]
    show_blobs(opdfs_sampled_at_verts, verts, faces)
    mlab.imshow(fa_slice, colormap='gray', interpolate=False)
    mlab.show()
Пример #12
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() 
Пример #13
0
def main(argv=None):
    """docstring for main"""
    from enthought.mayavi import mlab

    if argv is None:
        argv = sys.argv

    x1 = x2 = y1 = y2 = 0
    fname = ""
    try:
        fname = argv[1]
        x1, x2, y1, y2 = [int(i) for i in argv[2:]]
    except:
        print("Usage: {0} fname x1 x2 y1 y2".format(argv[0]))

    print(x1, x2, y1, y2)
    ds = gdal.Open(fname)
    band = ds.GetRasterBand(1)
    STORED_VALUE = band.ReadAsArray(x1, y1, x2 - x1, y2 - y1)
    ds = 0

    # PDS label infos:
    SCALING_FACTOR = 0.25
    OFFSET = -8000
    topo = (STORED_VALUE * SCALING_FACTOR) + OFFSET
    mlab.surf(topo, warp_scale=1 / 115.0, vmin=1700)
    mlab.colorbar(orientation="vertical",
                  title="Height [m]",
                  label_fmt="%4.0f")
    mlab.show()
Пример #14
0
def display_points_func():
    from enthought.mayavi import mlab
    scf = shelf["scf"]
    mo = MolecularOrbital(scf, 0)
    x, y, z = make_grid(np.mgrid)
    obj = mlab.contour3d(x, y, z, mo(x, y, z))
    mlab.show()
Пример #15
0
def display_points(val=0.3):
    scalars = shelf["scalars"]
    scalars = generate_points()
    shelf["scalars"] = scalars
    min = scalars.min()
    max = scalars.max()

    from enthought.mayavi import mlab
    x, y, z = make_grid(np.mgrid)
    contours = list(np.arange(-val, val, 0.02))
    obj = mlab.contour3d(x,
                         y,
                         z,
                         scalars,
                         contours=contours,
                         opacity=0.3,
                         colormap="PRGn",
                         transparent=True)

    display_atoms()
    #    source = mlab.pipeline.scalar_field(x,y,z,scalars)
    #    vol = mlab.pipeline.volume(source, vmin=min+0.65*(max-min),
    #                               vmax=min+0.9*(max-min))
    #    mlab.view(132, 54, 45, [21, 20, 21.5])
    mlab.show()
Пример #16
0
def display_points_func():
    from enthought.mayavi import mlab 
    scf = shelf["scf"]
    mo  = MolecularOrbital(scf,0)
    x,y,z = make_grid(np.mgrid)
    obj = mlab.contour3d(x,y,z,mo(x,y,z) )
    mlab.show()
Пример #17
0
    def _viztest3d(self, extra_bb):
        """
        3D vizualization of CPRep for obj
        """
        from enthought.mayavi import mlab
        import numpy as np
        f = mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(640,640))
        mlab.clf()

        if self._hasParam:
            L = self.ParamGrid()
            x,y,z = L
            #print x,y,z
            #s = mlab.mesh(xb, yb, zb, scalars=real((Eplot_bulb*E*uxx).reshape(xb.shape)))
            # TODO: mayavi bug, opacity<1
            s = mlab.mesh(x, y, z, scalars=z, opacity=1.0)

        a,b = self.getBB()
        ll = (b+a)/2 - (extra_bb)*(b-a)/2
        rr = (b+a)/2 + (extra_bb)*(b-a)/2
        for i in range(0,40):
            x = np.random.uniform( ll, rr )
            cp,dist,bdy,other = self.cp(x)
            colt = (0.5,0.5,0.5)
            op = 0.3
            l = mlab.plot3d([x[0],cp[0]], [x[1],cp[1]], [x[2], cp[2]], color=colt, opacity=op, tube_radius=0.1)
        #mlab.title('3d viz test')
        mlab.show()
Пример #18
0
    def mtest(self):
        from enthought.mayavi import mlab
        # Create the data.
        from numpy import pi, sin, cos, mgrid, arange, array
        ni = 100.0
        dtheta, dphi = pi/ni, pi/ni

        #[theta,phi] = mgrid[0:pi+dtheta:dtheta,0:2*pi+dphi:dphi]

        #tlin = arange(0,pi+dtheta,dtheta)
        #plin = arange(0,2*pi+dphi,dphi)
        tlin = pi*array([0,.12,.2,.31,.43,.56,.63,.75,.87,.92,1])
        plin = 2*pi*array([0,.11,.22,.34,.42,.58,.66,.74,.85,.97,1])
        theta,phi = ndgrid(tlin,plin)

        fp = (1.0/6.0)*(cos(3.0*phi)+5.0)
        ft = (1.0/6.0)*(cos(10.0*theta)+5.0)

        r = fp*ft

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

        # View it.
        s = mlab.mesh(x, y, z, scalars=r)
        mlab.show()
        return
Пример #19
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()
Пример #20
0
    def newSurface(self):
        processes = self.plotter.getProcesses()

        if not self._cv_dlg:
            self._cv_dlg = daeChooseVariable(daeChooseVariable.plot3D)
        self._cv_dlg.updateProcessesList(processes)
        self._cv_dlg.setWindowTitle('Choose variable for 3D plot')
        if self._cv_dlg.exec_() != QtWidgets.QDialog.Accepted:
            return False

        variable, domainIndexes, domainPoints, xAxisLabel, yAxisLabel, zAxisLabel, xPoints, yPoints, zPoints, currentTime = self._cv_dlg.getPlot3DData(
        )
        xPoints = numpy.array(xPoints)
        yPoints = numpy.array(yPoints)

        xmax = numpy.max(xPoints)
        ymax = numpy.max(yPoints)
        zmax = numpy.max(zPoints)

        xmin = numpy.min(xPoints)
        ymin = numpy.min(yPoints)
        zmin = numpy.min(zPoints)

        warp = 'auto'
        #if((xmax == xmin) or (ymax == ymin) or (zmax == zmin)):
        #    warp = 'auto'
        #else:
        #    warp = math.sqrt( (xmax-xmin)*(ymax-ymin) ) / (zmax-zmin)

        # colormap='gist_earth', 'RdBu'
        stype = 'surface'
        mlab.figure()
        if (stype == 'surface'):
            #print "warp=", warp
            #print "[xmin, xmax, ymin, ymax, zmin, zmax]=", [xmin, xmax, ymin, ymax, zmin, zmax]
            mlab.surf(xPoints,
                      yPoints,
                      zPoints,
                      warp_scale=warp,
                      representation='surface')
            mlab.colorbar(orientation='vertical')
            #mlab.title('polar mesh')
            #mlab.outline()
            mlab.axes(ranges=[xmin, xmax, ymin, ymax, zmin, zmax], nb_labels=3)

            mlab.xlabel(xAxisLabel)
            mlab.ylabel(yAxisLabel)
            mlab.zlabel(zAxisLabel)
        elif (stype == 'map'):
            mlab.imshow(zPoints)
            mlab.colorbar(orientation='vertical')
            #mlab.title('polar mesh')
            #mlab.outline()
            mlab.axes(ranges=[xmin, xmax, ymin, ymax], nb_labels=3)

            mlab.xlabel(xAxisLabel)
            mlab.ylabel(yAxisLabel)
            mlab.zlabel(zAxisLabel)

        mlab.show()
Пример #21
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()
Пример #22
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()
Пример #23
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()
Пример #24
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)
Пример #25
0
def testVerticalSurface():
    import pylab, numpy
    pylab.clf()

    no_of_phenotypes = 5
    x, y = numpy.mgrid[
        0:2 * no_of_phenotypes:1, 0:10:
        1]  #added a gap of 1 column between two phenotypes. one phenotype occupies two rows & two columns.

    #remove the gap in x & y
    needed_index_ls = [0, 5]
    #for i in [0, 5]:
    #	for j in range(no_of_phenotypes):
    #		needed_index_ls.append(no_of_phenotypes*i+j)
    #for i in range(0, no_of_phenotypes):
    #	needed_index_ls.append(2*i)
    #needed_index_ls.append(3*i+1)
    #y[3*i+1][1]=2
    x = x[:, needed_index_ls]
    y = y[:, needed_index_ls]

    enrichment_matrix = numpy.ones(x.shape, numpy.float)
    enrichment_matrix[:, :] = 10
    enrichment_matrix[0, 0] = 3

    from enthought.mayavi import mlab
    mlab.clf()
    #from palos.yh_mayavi import customBarchart
    bar = customBarchart(x,
                         y,
                         enrichment_matrix,
                         x_scale=0.9,
                         y_scale=4.5,
                         opacity=1,
                         mode='cube',
                         color=(0, 1, 0),
                         scale_factor=1.0)
    """
	#mlab.ylabel("KW")
	#mlab.xlabel("Emma")
	#mlab.zlabel("Enrichment Ratio")
	from palos.DrawMatrix import get_font 
	font = get_font()
	
	for i in range(len(xlabel_ls)):
		label = xlabel_ls[i]
		char_width, char_height = font.getsize(label)	#W is the the biggest(widest)
		
		mlab.text(2*i, 0, label, z=0, width=char_width/1500.)	#min(0.0075*len(label), 0.04))
	
	"""
    s = numpy.zeros(x.shape, numpy.int)
    #s[0,1]=0.5
    surf = mlab.surf(x,
                     y,
                     s,
                     opacity=0.6,
                     extent=[-1, 2 * no_of_phenotypes, -1, 10, 0.0, 0.0])
    mlab.show()
    def mlab3Dview():

        e_arr = orthogonalize([x, w])
        n_e_arr = [ e / np.max(np.fabs(e)) for e in e_arr ]

        n_mu_q_arr = mu_q_arr / np.max(np.fabs(mu_q_arr))
        m.surf(n_e_arr[0], n_e_arr[1], n_mu_q_arr)
        m.show()
Пример #27
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()
Пример #28
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()
Пример #29
0
 def plot(self, lib="mayavi", show=True):
     if lib == "mayavi":
         self._plot_mayavi_()
         if show:
             from enthought.mayavi import mlab
             mlab.show()
     else:
         raise NotImplementedError()
Пример #30
0
    def _viztest3d(self):
        """
        3D vizualization of CPRep for obj with boundary
        """
        from enthought.mayavi import mlab
        import numpy as np
        f = mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1), size=(500,700))
        mlab.clf()

        #s = mlab.mesh(xb, yb, zb, scalars=real(evec_b.reshape(xb.shape)))
        #l = mlab.plot3d(xs, ys, zs, real(evec_s))
        #mlab.title(str(ii) + ' ew=' + str(eval), size=0.2)

        #mlab.show()
        #mlab.savefig('b_horn' + str(ii) + '_' + str(eval) + '.png')
        #s = mlab.mesh(xb, yb, zb, scalars=real((Eplot_bulb*E*uxx).reshape(xb.shape)))
        #l = mlab.plot3d(xs, ys, zs, real((Eplot_stem*E*uxx).reshape(xs.shape)))

        #(x1,y1),(x2,y2),(x3,y3) = mesh2d(resolution=3)

        # TODO: is has param:
        if self._hasParam:
            L = self.ParamGrid()
            x,y,z = L
            #print x,y,z
            #s = mlab.mesh(xb, yb, zb, scalars=real((Eplot_bulb*E*uxx).reshape(xb.shape)))
            # TODO: mayavi bug, opacity<1
            s = mlab.mesh(x, y, z, scalars=z, opacity=1.0)

        a,b = self.getBB()
        ll = (b+a)/2 - (extra_bb)*(b-a)/2
        rr = (b+a)/2 + (extra_bb)*(b-a)/2
        for i in range(0,200):
            x = np.random.uniform( ll, rr )
            cp,dist,bdy,other = self.cp(x)
            drawplot = False
            if bdy==1:
                if (np.random.random(1) < 1.0):
                    drawplot = True
                    col = 'g'
                    colt = (0.5,1,.2)
                    op = 0.9
            elif bdy==2:
                if (np.random.random(1) < 1.0):
                    drawplot = True
                    col = 'b'
                    colt = (.2,.5,1)
                    op = 0.9
            else:
                if ( (np.random.random(1) < 0.5) and (dist <= max((b-a)/10)) ):
                    drawplot = True
                    col = 'k'
                    colt = (0.5,0.5,0.5)
                    op = 0.3
            if drawplot:
                l = mlab.plot3d([x[0],cp[0]], [x[1],cp[1]], [x[2], cp[2]], color=colt, opacity=op)#, tube_radius=0.1)
        #mlab.title('3d viz test')
        mlab.show()
Пример #31
0
    def show(self, sln, show=True, lib="mayavi", notebook=None,
            filename="scalar.png", **options):
        """
        Shows the solution.

        show ... should it actually plot the window? Set to False in tests.
        lib .... which library to use for the plotting? either "mpl" or "mayavi"
        notebook ... are we running inside Sage notebook? If True, just save
                the image to a.png
        filename ... the name of the filename if we are saving the image (e.g.
                notebook == False)

        Example:

        >>> 1 + 1
        2
        >>> 1 + 2
        3
        """
        if notebook is None:
            try:
                from sagenb.misc.support import EMBEDDED_MODE
            except ImportError:
                EMBEDDED_MODE = False
            notebook = EMBEDDED_MODE

        self._lib = lib
        self._notebook = notebook
        if lib == "glut":
            if self._glut_view is None:
                from _hermes2d import ScalarView
                self._glut_view = ScalarView(self._name)
            self._glut_view.show(sln)
        elif lib == "mpl":
            plot_sln_mpl(sln, **options)
            import pylab
            if show:
                if notebook:
                    pylab.savefig(filename)
                else:
                    pylab.ion()
                    pylab.draw()
                    pylab.ioff()
        elif lib == "mayavi":
            plot_sln_mayavi(sln, notebook=notebook)
            from enthought.mayavi import mlab
            if show:
                engine = mlab.get_engine()
                image = engine.current_scene
                image.scene.background = (1.0, 1.0, 1.0)
                image.scene.foreground = (0.0, 0.0, 0.0)
                #mlab.colorbar(orientation="vertical")
                if notebook:
                    mlab.savefig(filename)
                else:
                    mlab.show()
        else:
            raise NotImplementedError("Unknown library '%s'" % lib)
Пример #32
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()    
Пример #33
0
 def showVTKFile_2D(filename):
     figure = mlab.figure(size=(800, 600))
     vtkSource = VTKFileReader()
     vtkSource.initialize(filename)
     surface = mlab.pipeline.surface(vtkSource)
     axes = mlab.axes()
     colorbar = mlab.colorbar(object=surface, orientation='horizontal')
     mlab.view(0, 0)
     mlab.show()
Пример #34
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()
Пример #35
0
def test_segmentation():
    rospy.wait_for_service('segment_pointcloud')
    try:
        pts3d, intensities, labels, image, image_angle, polygon = get_test_data(
        )
        ROS_pointcloud = convert_pointcloud_to_ROS(pts3d, intensities, labels)
        ROS_image = convert_cvimage_to_ROS(image)
        imageSize = cv.cvGetSize(image)

        ROS_polygon = convert_polygon_to_ROS(polygon)

        segment_pointcloud = rospy.ServiceProxy('segment_pointcloud',
                                                Segmentation)
        request = SegmentationRequest()
        request.imageWidth = 41
        request.pointcloud = ROS_pointcloud
        request.image = ROS_image
        request.imageWidth = imageSize.width
        request.imageHeight = imageSize.height
        request.imageAngle = image_angle
        request.regionOfInterest2D = ROS_polygon
        request.laserHeightAboveGround = 1.32
        request.numberOfPointsToClassify = 1000  #-1 == all

        response = segment_pointcloud(request)

        pts3d_bound, intensities, labels = convert_ROS_pointcloud_to_pointcloud(
            response.pointcloud)
        cfg = configuration.configuration('../data/ROS_test_client/',
                                          'dummyScanner')
        pc = processor.processor(cfg)

        pc.scan_dataset = scan_dataset()
        pc.scan_dataset.image_artag_filename = ''
        pc.scan_dataset.table_plane_translation = np.matrix([0, 0, 0]).T

        pc.scan_dataset.ground_plane_translation = np.matrix(
            [0, 0, request.laserHeightAboveGround]).T
        pc.scan_dataset.ground_plane_rotation = ''
        pc.scan_dataset.is_labeled = True
        pc.scan_dataset.id = 'ROStest'
        pc.image_angle = ''
        pc.pts3d_bound = pts3d_bound
        pc.map_polys = labels
        pc.scan_dataset.ground_plane_normal = np.matrix([0., 0., 1.]).T

        from enthought.mayavi import mlab
        pc.display_3d('labels')
        mlab.show()

        return response
    except rospy.ServiceException, e:
        print "Service call failed: %s" % e
Пример #36
0
def plot_3d(lats,lons,depth,vs,runlat,runlon,vtkname='rayleigh_c_u.vtk',
            annotate_depth=False,coastline=False,annotate_lat=True,annotate_lon=True):
    """
    plot 3d results using mayavi
    """
    if coastline:
        plot_canada_map()
    sgrid = get_tvtk_grid(lats,lons,depth,vs)
    d = mlab.pipeline.add_dataset(sgrid)
    #sf = mlab.pipeline.surface(d)
    #gx = mlab.pipeline.grid_plane(d)
    #gx.grid_plane.axis = 'x'
    gy = mlab.pipeline.grid_plane(d)
    gy.grid_plane.axis = 'x'
    gy.module_manager.scalar_lut_manager.show_scalar_bar = True
    gy.module_manager.scalar_lut_manager.lut_mode = 'jet'
    gy.module_manager.scalar_lut_manager.data_range = np.array([ 2. ,  4.8])
    gy.module_manager.scalar_lut_manager.scalar_bar_representation.maximum_size = np.array([100000, 100000])
    gy.module_manager.scalar_lut_manager.scalar_bar_representation.minimum_size = np.array([1, 1])
    gy.module_manager.scalar_lut_manager.scalar_bar_representation.position2 = np.array([ 0.08796009,  0.56264591])
    gy.module_manager.scalar_lut_manager.scalar_bar_representation.position = np.array([ 0.03396896,  0.39182879])
    gy.actor.mapper.progress = 1.0
    gy.actor.mapper.scalar_range = np.array([ 0.,  1.])
    gy.actor.mapper.scalar_visibility = True
    gy.actor.property.representation = 'surface'
    gy.grid_plane.position = 6

    #gz = mlab.pipeline.grid_plane(d)
    #gz.grid_plane.axis = 'z'
    if annotate_lat:
        for lat in runlat:
            x,y,z = convert_pt(lat,-58.,10.)
            txt = mlab.text3d(x,y,z,'%d'%(lat),color=(0,0,0),line_width=10.0)
            txt.scale = [20,20,20]
    if annotate_lon:
        for lon in runlon[1::]:
            x,y,z = convert_pt(49.,lon,10.)
            txt = mlab.text3d(x,y,z,'%d'%(lon),color=(0,0,0),line_width=10.0)
            txt.scale = [20,20,20]
    if annotate_depth:
        for dp in [-10,-40,-80,-120]:
            x,y,z = convert_pt(49,-68.,dp)
            txt = mlab.text3d(x,y,z,'%d km'%(dp),color=(0,0,0),line_width=10.0)
            txt.scale = [20,20,20]

    ### Include 3D screenshot in matplotlib
    #arr = mlab.screenshot()
    #import pylab as pl
    #pl.imshow(arr)
    #pl.show()
    mlab.text(0.76,0.86,'49N',width=0.1)
    mlab.show()
Пример #37
0
    def plotmask(self, region=None, resolution=20, slat=71, slon=-70, hemi="s"):
        """Plot the mask.
        """
        try:
            import enthought.mayavi.mlab as ml

            mayavi = True
            print "using mayavi"
        except:
            import pylab as pl

            mayavi = False
            print "using matplotlib"

        if self.maskfile is None:
            print "error: plotmask: get mask file first:"
            print ">>> m = Mask()"
            print ">>> m.getmask('fname')"
            print "then you can do:"
            print ">>> m.plotmask(region='left/right/bottom/top', resolution=20)"
            sys.exit()

        m_mask = self.m_mask
        x_mask = self.x_mask
        y_mask = self.y_mask

        if region is not None:
            left, right, bottom, top = str.split(region, "/")
            left, bottom = self.mapll(left, bottom, slat=slat, slon=slon, hemi=hemi)
            right, top = self.mapll(right, top, slat=slat, slon=slon, hemi=hemi)
            jmin, = np.where(x_mask == np.rint(left))
            jmax, = np.where(x_mask == np.rint(right))
            imin, = np.where(y_mask == np.rint(bottom))
            imax, = np.where(y_mask == np.rint(top))
            # x_mask = x_mask[jmin:jmax+1:resolution]
            # y_mask = y_mask[imin:imax+1:resolution]
            m_mask = m_mask[imin : imax + 1 : resolution, jmin : jmax + 1 : resolution]
        else:
            # x_mask = x_mask[::resolution]
            # y_mask = y_mask[::resolution]
            m_mask = m_mask[::resolution, ::resolution]

        print "plotting mask ..."
        if mayavi:
            ml.figure()
            ml.imshow(m_mask)
            ml.show()
        else:
            pl.figure()
            pl.imshow(m_mask, origin="lower", interpolation="nearest")
            pl.show()
        print "done!"
Пример #38
0
def Analyze_Phase(name):

    #parameters of the binary liquid model
    k = 0.04
    a = 0.04

    phase_numpy, velx_numpy, vely_numpy, velz_numpy = Read_Phase(name)

    Show_Phase(phase_numpy, velx_numpy, vely_numpy, velz_numpy)
    dims = phase_numpy.shape

    print dims

    center = phase_numpy[dims[0] / 2, dims[1] / 2, :]
    z1 = numpy.min(numpy.where(center < 0.0))
    z2 = numpy.max(numpy.where(center < 0.0))
    if z1 == 0:
        z2 = numpy.min(numpy.where(center > 0.0)) + dims[2]
        z1 = numpy.max(numpy.where(center > 0.0))
    pylab.figure()
    pylab.plot(center)
    print z1, z2

    mid = ((z1 + z2) / 2) % dims[2]
    print mid
    slice = phase_numpy[:, :, mid]
    shape = slice.shape
    prof_axis = slice[shape[0] / 2, :]
    prof_diag = numpy.diag(slice)

    #axis_zero=(1.0-Get_Zero(prof_axis)/(0.5*(shape[1]-2)))
    #diag_zero=(math.sqrt(2.0)-math.sqrt(2.0)*Get_Zero(prof_diag)/(0.5*(shape[1]-2)))

    print "Velx", velx_numpy[dims[0] / 2, dims[1] / 2, mid]
    print "Vely", vely_numpy[dims[0] / 2, dims[1] / 2, mid]
    print "Velz", velz_numpy[dims[0] / 2, dims[1] / 2, mid]

    #Calculation of the capillary number
    capillary = velx_numpy[dims[0] / 2, dims[1] / 2,
                           mid] * (2.0 / 3.0) / math.sqrt(8.0 * k * a / 9.0)

    #    pylab.figure()
    #    pylab.imshow(phase_numpy[:,:,mid])
    #    pylab.figure()
    #    pylab.plot(prof_axis)
    #    pylab.figure()
    #    pylab.plot(prof_diag)

    mlab.show()

    #print axis_zero,diag_zero
    print "Capillary=", capillary
	def _plotbutton1_fired(self):
		mlab.clf()
		self.loaddata()
		field=mlab.pipeline.scalar_field(self.sregion)     # Generate a scalar field
		mlab.pipeline.volume(field,vmax=self.datamax,vmin=self.datamin) # Render the field with dots

		mlab.outline()
		mlab.xlabel('RA(J2000)')
		mlab.ylabel('DEC(J2000)')
		mlab.zlabel('Velocity')
		mlab.view(azimuth=0, elevation=0)
		mlab.show()
		
		self.field   = field
Пример #40
0
    def plotmask(self, region=None, resolution=20, slat=71, slon=-70, hemi='s'):
        """Plot the mask.
        """
        try:
            import enthought.mayavi.mlab as ml 
            mayavi = True
            print 'using mayavi'
        except:
            import pylab as pl
            mayavi = False
            print 'using matplotlib'

        if self.maskfile is None:
            print 'error: plotmask: get mask file first:'
            print '>>> m = Mask()'
            print ">>> m.getmask('fname')"
            print 'then you can do:'
            print ">>> m.plotmask(region='left/right/bottom/top', resolution=20)"
            sys.exit()
     
        m_mask = self.m_mask
        x_mask = self.x_mask
        y_mask = self.y_mask
        
        if region is not None:
            left, right, bottom, top = str.split(region, '/')
            left, bottom = self.mapll(left, bottom, slat=slat, slon=slon, hemi=hemi)
            right, top = self.mapll(right, top, slat=slat, slon=slon, hemi=hemi)
            jmin, = np.where(x_mask == np.rint(left))
            jmax, = np.where(x_mask == np.rint(right))
            imin, = np.where(y_mask == np.rint(bottom))
            imax, = np.where(y_mask == np.rint(top))
            #x_mask = x_mask[jmin:jmax+1:resolution]
            #y_mask = y_mask[imin:imax+1:resolution]
            m_mask = m_mask[imin:imax+1:resolution, jmin:jmax+1:resolution]
        else:
            #x_mask = x_mask[::resolution]
            #y_mask = y_mask[::resolution]
            m_mask = m_mask[::resolution,::resolution]
        
        print 'plotting mask ...'
        if mayavi:
            ml.figure()
            ml.imshow(m_mask)
            ml.show()
        else:
            pl.figure()
            pl.imshow(m_mask, origin='lower', interpolation='nearest')
            pl.show()
        print 'done!'
Пример #41
0
def start_vtk(component):
    f = mlab.figure(size=(700,500))
    m = mlab.test_mesh()
    scene = mlab.gcf().scene
    render_window = scene.render_window
    renderer = scene.renderer
    rwi = scene.interactor
    window = EnableVTKWindow(rwi, renderer,
            component = component,
            istyle_class = tvtk.InteractorStyleTrackballCamera,
            bgcolor = "transparent",
            event_passthrough = True,
            )
    mlab.show()
Пример #42
0
def plotsquare3d(us):
    from enthought.mayavi.mlab import surf, show, colorbar, xlabel, ylabel, figure
    for u in us:
        figure()
        Np = 60
        points = uniformsquarepoints(Np)
        x = points[:,0].reshape(Np,Np)
        y = points[:,1].reshape(Np,Np)
        up = np.real(u(points))
        surf(x,y, up.reshape(Np,Np))
        colorbar()
        xlabel('x')
        ylabel('y')
    show()
Пример #43
0
def test_segmentation():
    rospy.wait_for_service("segment_pointcloud")
    try:
        pts3d, intensities, labels, image, image_angle, polygon = get_test_data()
        ROS_pointcloud = convert_pointcloud_to_ROS(pts3d, intensities, labels)
        ROS_image = convert_cvimage_to_ROS(image)
        imageSize = cv.cvGetSize(image)

        ROS_polygon = convert_polygon_to_ROS(polygon)

        segment_pointcloud = rospy.ServiceProxy("segment_pointcloud", Segmentation)
        request = SegmentationRequest()
        request.imageWidth = 41
        request.pointcloud = ROS_pointcloud
        request.image = ROS_image
        request.imageWidth = imageSize.width
        request.imageHeight = imageSize.height
        request.imageAngle = image_angle
        request.regionOfInterest2D = ROS_polygon
        request.laserHeightAboveGround = 1.32
        request.numberOfPointsToClassify = 1000  # -1 == all

        response = segment_pointcloud(request)

        pts3d_bound, intensities, labels = convert_ROS_pointcloud_to_pointcloud(response.pointcloud)
        cfg = configuration.configuration("../data/ROS_test_client/", "dummyScanner")
        pc = processor.processor(cfg)

        pc.scan_dataset = scan_dataset()
        pc.scan_dataset.image_artag_filename = ""
        pc.scan_dataset.table_plane_translation = np.matrix([0, 0, 0]).T

        pc.scan_dataset.ground_plane_translation = np.matrix([0, 0, request.laserHeightAboveGround]).T
        pc.scan_dataset.ground_plane_rotation = ""
        pc.scan_dataset.is_labeled = True
        pc.scan_dataset.id = "ROStest"
        pc.image_angle = ""
        pc.pts3d_bound = pts3d_bound
        pc.map_polys = labels
        pc.scan_dataset.ground_plane_normal = np.matrix([0.0, 0.0, 1.0]).T

        from enthought.mayavi import mlab

        pc.display_3d("labels")
        mlab.show()

        return response
    except rospy.ServiceException, e:
        print "Service call failed: %s" % e
Пример #44
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
Пример #45
0
def read(name):
    from enthought.tvtk.api import tvtk
    from enthought.mayavi import mlab
    import numpy

    gridreader = tvtk.XMLStructuredGridReader()
    gridreader.file_name = name
    gridreader.update()

    grid = gridreader.output
    data = grid.point_data
    points = grid.points
    dims = grid.dimensions
    dims = dims.tolist()
    dims.reverse()
    phase = numpy.array(data.get_array("Phase"))
    velocity = numpy.array(data.get_array("Velocity"))
    velx = velocity[:, 0]
    vely = velocity[:, 1]
    velz = velocity[:, 2]
    phase_numpy = phase.reshape(dims)
    velx_numpy = velx.reshape(dims)
    vely_numpy = vely.reshape(dims)
    velz_numpy = velz.reshape(dims)

    fig = mlab.figure()

    src = mlab.pipeline.scalar_field(phase_numpy)
    mlab.axes()

    v = mlab.pipeline.vector_field(velx_numpy, vely_numpy, velz_numpy)
    vx = mlab.pipeline.scalar_field(velx_numpy)
    vy = mlab.pipeline.scalar_field(vely_numpy)
    vz = mlab.pipeline.scalar_field(velz_numpy)

    extract = mlab.pipeline.extract_grid(src)
    extract.set(z_min=1, z_max=dims[2] - 2, y_min=1, y_max=dims[1] - 2)
    surf = mlab.pipeline.contour_surface(extract)

    mlab.pipeline.image_plane_widget(vx,
                                     plane_orientation='x_axes',
                                     slice_index=250)
    #mlab.pipeline.vectors(v, mask_points=20, scale_factor=3.)
    mlab.pipeline.vector_cut_plane(v, mask_points=2, scale_factor=3)
    mlab.show()
def marsyasplay(sfname):
    mng = marsyas.MarSystemManager()

    net = mng.create("Series", "series")
    net.addMarSystem(mng.create("SoundFileSource", "src"))
    net.addMarSystem(mng.create("BinauralCARFAC", "carfac"))
    net.updControl("SoundFileSource/src/mrs_string/filename",
                   marsyas.MarControlPtr.from_string(sfname))

    outData = net.getControl("mrs_realvec/processedData")

    data = np.zeros((96, 200, 1))
    while net.getControl("SoundFileSource/src/mrs_bool/hasData").to_bool():
        net.tick()
        a = np.array(outData.to_realvec()).reshape((96, 200, 1))
        data = np.append(data, a, axis=2)

    obj = mlab.contour3d(data, contours=4, transparent=True)
    mlab.show()
Пример #47
0
def Show_Phase(phase_numpy):
    dims = phase_numpy.shape

    fig = mlab.figure()
    src = mlab.pipeline.scalar_field(phase_numpy)

    mlab.outline()
    mlab.orientation_axes()
    #v= mlab.pipeline.vector_field(velx_numpy,vely_numpy,velz_numpy)
    #vx=mlab.pipeline.scalar_field(velx_numpy)
    #vy=mlab.pipeline.scalar_field(vely_numpy)
    #vz=mlab.pipeline.scalar_field(velz_numpy)
    extract = mlab.pipeline.extract_grid(src)
    extract.set(x_min=1, x_max=dims[0] - 2, y_min=1, y_max=dims[1] - 2)
    surf = mlab.pipeline.contour_surface(extract)

    #mlab.pipeline.image_plane_widget(vx, plane_orientation='x_axes', slice_index=250)
    #mlab.pipeline.vectors(v, mask_points=20, scale_factor=3.)
    #mlab.pipeline.vector_cut_plane(v, mask_points=2, scale_factor=3)
    mlab.show()
Пример #48
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()
Пример #49
0
def Analyze_NoForce_Consequence():
    ax_zeros = []
    diag_zeros = []
    capillaries = []
    os.chdir("NoForce")
    for i in range(1, 5):
        print os.getcwd()
        name = "steady" + str(2 * i) + "00000_0.vti"
        print name
        axis_zero, diag_zero, capillary = Analyze_Phase(name)
        ax_zeros.append(axis_zero)
        diag_zeros.append(diag_zero)
        capillaries.append(capillary)
        #Calculate the capillary number
        os.chdir("..")
    pylab.plot(capillaries, ax_zeros)
    pylab.plot(capillaries, diag_zeros)
    #numpy.savetxt("steady.txt",zip(capillaries,ax_zeros,diag_zeros))
    pylab.show()
    mlab.show()