def view_surface():
    from enthought.mayavi import mlab
    g = Grid(surface_param)
    xyz_grid = g[-1:1:201j,-1:1:101j]
    x, y, z = xyz_grid.transposed_values
    mlab.mesh(x, y, z)
    mlab.draw()
Example #2
0
def mesh_plot(X,T,eta):
    from enthought.mayavi import mlab
    X = 2000*X/np.abs(x.min())
    eta = 1000*eta
    mlab.figure(1)
    mlab.clf()
    mlab.mesh(X,T,eta)
Example #3
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
Example #4
0
def view_surface():
    from enthought.mayavi import mlab
    g = Grid(surface_param)
    xyz_grid = g[-1:1:201j, -1:1:101j]
    x, y, z = xyz_grid.transposed_values
    mlab.mesh(x, y, z)
    mlab.draw()
Example #5
0
def plot_connections(data_file, min, max, bins,
                     params=None, output=''):
    
    print("Creating connection profile graphs.")
    
    # Read data points from file
    f = open(data_file, 'r')

    # Ignore first line
    f.readline()

    data = []

    for line in f:
        temp = line.split(' ')
        if params != None:
            if check_node([int(temp[1])], params):
                data.append([float(temp[4]), float(temp[5])]);
        else:
            data.append([float(temp[4]), float(temp[5])]);

    # Create histogram data based on the retrieved data.
    histogram_data = histogram2d(data, min, max, bins)

    # Open a new Mayavi2 figure
    f = mlab.figure()

    # Convert histogram bin count to relative densities.
    m = np.max(histogram_data[2].max(axis=0))
    histogram_data[2] = histogram_data[2]/float(m)

    # Plot histogram data
    mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2])
    #surf(histogram_data[0], histogram_data[1], histogram_data[2])

    # Create and save various viewpoints of histogram figure

    mlab.axes(z_axis_visibility=False)

    mlab.view(azimuth=0, elevation=90) # X

    mlab.savefig(output+"xaxis.eps", size=[600,400])

    mlab.view(azimuth=90, elevation=270) # Y

    mlab.savefig(output+"yaxis.eps", size=[600,400])

    mlab.view(azimuth=45, elevation=45) # Perspective

    mlab.savefig(output+"perspective.eps", size=[600,400])

    mlab.colorbar(orientation="vertical")

    mlab.view(azimuth=0, elevation=0) # Z

    mlab.savefig(output+"above.eps", size=[600,400])
Example #6
0
def plot_connections(data_file, min, max, bins, params=None, output=''):

    print("Creating connection profile graphs.")

    # Read data points from file
    f = open(data_file, 'r')

    # Ignore first line
    f.readline()

    data = []

    for line in f:
        temp = line.split(' ')
        if params != None:
            if check_node([int(temp[1])], params):
                data.append([float(temp[4]), float(temp[5])])
        else:
            data.append([float(temp[4]), float(temp[5])])

    # Create histogram data based on the retrieved data.
    histogram_data = histogram2d(data, min, max, bins)

    # Open a new Mayavi2 figure
    f = mlab.figure()

    # Convert histogram bin count to relative densities.
    m = np.max(histogram_data[2].max(axis=0))
    histogram_data[2] = histogram_data[2] / float(m)

    # Plot histogram data
    mlab.mesh(histogram_data[0], histogram_data[1], histogram_data[2])
    #surf(histogram_data[0], histogram_data[1], histogram_data[2])

    # Create and save various viewpoints of histogram figure

    mlab.axes(z_axis_visibility=False)

    mlab.view(azimuth=0, elevation=90)  # X

    mlab.savefig(output + "xaxis.eps", size=[600, 400])

    mlab.view(azimuth=90, elevation=270)  # Y

    mlab.savefig(output + "yaxis.eps", size=[600, 400])

    mlab.view(azimuth=45, elevation=45)  # Perspective

    mlab.savefig(output + "perspective.eps", size=[600, 400])

    mlab.colorbar(orientation="vertical")

    mlab.view(azimuth=0, elevation=0)  # Z

    mlab.savefig(output + "above.eps", size=[600, 400])
Example #7
0
def plotframe(frameno, level=1):

    plotdata = ClawPlotData()
    plotdata.outdir = "_output"
    print "Plotting solution from ", plotdata.outdir
    plotdata = setplot(plotdata)
    try:
        frame = plotdata.getframe(frameno)
    except:
        print "Unable to get frame"
        return
    mlab.figure(1, bgcolor=(1, 1, 1), size=(700, 600))
    mlab.clf()
    for grid in frame.grids:
        if grid.level <= level:

            y = grid.c_center[1]
            x = grid.c_center[0]
            q = grid.q
            eta = q[:, :, 3]
            h = q[:, :, 0]
            #return x,y,eta
            #eta = where(q[:,:,0] > 1.,eta,nan)
            #import pdb; pdb.set_trace()

            topo = eta - h
            cutoff = 0.5
            #cutoff2 = -500.
            shift = 0.
            scale = 10.
            topo1 = scale * where(topo < cutoff, topo - shift, cutoff - shift)
            #topo1 = scale*where(topo>cutoff2, topo1, nan)
            eta1 = scale * where(eta < cutoff, eta - shift, cutoff - shift)
            water1 = where(h >= 1.e-3, eta1, nan)
            mlab.mesh(x, y, topo1, colormap='Greens', vmin=-1.0, vmax=0.8)
            mlab.mesh(x, y, water1, colormap='Blues', vmin=-0.8, vmax=0.8)
            #mlab.surf(x,y,topo1,colormap='Greens',warp_scale=10,vmin=-0.8,vmax=0.5)
            #mlab.surf(x,y,water1,colormap='Blues',warp_scale=10,vmin=-0.8,vmax=0.5)
            V = (150.95115856920216,\
             80.12676623482308,\
             13.359093592227218,\
             array([ 2.744     ,  1.70099999, -0.04745156]))

            V =  (-108.612973405259,\
              62.96905073871072,\
              13.359093592227456,\
              array([ 2.744     ,  1.70099999, -0.04745156]))

            mlab.view(*V)
    t = frame.t
    mlab.title('Time = %5.2f' % t, color=(0, 0, 0), height=0.1, size=0.5)
Example #8
0
def plotframe(frameno,level=1):

    plotdata = ClawPlotData()
    plotdata.outdir = "_output"
    print "Plotting solution from ",plotdata.outdir
    plotdata = setplot(plotdata)
    try:
        frame = plotdata.getframe(frameno)
    except:
        print "Unable to get frame"
        return
    mlab.figure(1,bgcolor=(1,1,1),size=(700,600))
    mlab.clf()
    for grid in frame.grids:
        if grid.level <= level:

            y = grid.c_center[1]
            x = grid.c_center[0]
            q = grid.q
            eta = q[:,:,3]
            h = q[:,:,0]
            #return x,y,eta
            #eta = where(q[:,:,0] > 1.,eta,nan)
            #import pdb; pdb.set_trace()
        
            topo = eta - h
            cutoff = 0.5
            #cutoff2 = -500.
            shift = 0.
            scale = 10.
            topo1 = scale*where(topo<cutoff, topo-shift, cutoff-shift)
            #topo1 = scale*where(topo>cutoff2, topo1, nan)
            eta1 = scale*where(eta<cutoff, eta-shift, cutoff-shift)
            water1 = where(h>=1.e-3, eta1, nan)
            mlab.mesh(x,y,topo1,colormap='Greens',vmin=-1.0, vmax=0.8)
            mlab.mesh(x,y,water1,colormap='Blues',vmin=-0.8, vmax=0.8)
            #mlab.surf(x,y,topo1,colormap='Greens',warp_scale=10,vmin=-0.8,vmax=0.5)
            #mlab.surf(x,y,water1,colormap='Blues',warp_scale=10,vmin=-0.8,vmax=0.5)
            V = (150.95115856920216,\
             80.12676623482308,\
             13.359093592227218,\
             array([ 2.744     ,  1.70099999, -0.04745156]))
             
            V =  (-108.612973405259,\
              62.96905073871072,\
              13.359093592227456,\
              array([ 2.744     ,  1.70099999, -0.04745156]))
 
            mlab.view(*V)
    t = frame.t
    mlab.title('Time = %5.2f' % t,color=(0,0,0),height=0.1,size=0.5)
def plot_solid_sphere():

    #latitude = linspace(-pi/2, pi/2, 50)
    #longitude = linspace(0, 2*pi, 400)
    latitude = linspace(0, pi/2, 30)
    longitude = linspace(-pi/2, pi/2, 100)
    theta,phi = meshgrid(longitude,latitude)
    X = 0.97*cos(theta)*cos(phi)
    Y = 0.97*sin(theta)*cos(phi)
    Z = 0.97*sin(phi)

    #mlab.figure(3,bgcolor=(1,1,1))
    #mlab.clf()
    mlab.mesh(X,Y,Z,color=(1,1,1))
Example #10
0
    def plotSurface(surface):
        """plot a surface using mayavi"""

        # create a figure
        mlab.figure()
        # create a surface plot
        surfPlot = mlab.mesh(surface['x'], surface['y'], surface['value'])
Example #11
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
 def plotSurface(surface):
   """plot a surface using mayavi"""
   
   # create a figure
   mlab.figure()
   # create a surface plot
   surfPlot = mlab.mesh(surface['x'], surface['y'], surface['value'])
Example #13
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()
Example #14
0
File: myobject.py Project: m4z/adef
 def flaeche_berechnen(self):
     self.x_werte = self.x(self.u_f, self.v_f)
     self.y_werte = self.y(self.u_f, self.v_f)
     self.z_werte = self.z(self.u_f, self.v_f)
     self.mesh = mlab.mesh(self.x_werte, self.y_werte, self.z_werte, color=(0.6, 0.6, 0.6))
     self.cursor3d = mlab.points3d(0.0, 0.0, 0.0, mode="sphere", color=(0, 0, 0), scale_factor=0.03)
     ############################################
     self.fig.on_mouse_pick(lambda picker_obj: self.picker_callback(picker_obj))
Example #15
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()
Example #16
0
File: myutil.py Project: Hyso/adef
def ebene(x,y,z,u1,v1,w1,u2,v2,w2,rgb,ii,myname):
    px1,py1,pz1 = [u1[ii]+u2[ii]+x[ii],x[ii]],[v1[ii]+v2[ii]+y[ii],y[ii]],[w1[ii]+w2[ii]+z[ii],z[ii]]
    px2,py2,pz2 = [u1[ii]-u2[ii]+x[ii],x[ii]],[v1[ii]-v2[ii]+y[ii],y[ii]],[w1[ii]-w2[ii]+z[ii],z[ii]]
    px3,py3,pz3 = [-u1[ii]-u2[ii]+x[ii],x[ii]],[-v1[ii]-v2[ii]+y[ii],y[ii]],[-w1[ii]-w2[ii]+z[ii],z[ii]]
    px4,py4,pz4 = [-u1[ii]+u2[ii]+x[ii],x[ii]],[-v1[ii]+v2[ii]+y[ii],y[ii]],[-w1[ii]+w2[ii]+z[ii],z[ii]]
    px = array([px1,px2,px3,px4,px1])
    py = array([py1,py2,py3,py4,py1])
    pz = array([pz1,pz2,pz3,pz4,pz1])
    return mlab.mesh(px,py,pz,color=rgb,opacity=0.5,name=myname)
Example #17
0
File: odf.py Project: MarcCote/dipy
def disp_odf(sph_map, theta_res=64, phi_res=32, colormap='RGB', colors=256):

    pi = np.pi
    sin = np.sin
    cos = np.cos

    theta, phi = np.mgrid[0:2*pi:theta_res*1j, 0:pi:phi_res*1j] 
    x = sin(phi)*cos(theta)
    y = sin(phi)*sin(theta)
    z = cos(phi)
    
    nvox = np.prod(sph_map.shape)

    x_cen, y_cen, z_cen = _3grid(sph_map.shape)
    
    odf_values = sph_map.evaluate_at(theta, phi)
    max_value = odf_values.max()

    mlab.figure()
    for ii in range(nvox):
        odf_ii = odf_values.reshape(nvox, theta_res, phi_res)[ii,:,:]
        odf_ii /= max_value * 2
        if colormap == 'RGB':
            rgb = np.r_['-1,3,0', x*odf_ii, y*odf_ii, z*odf_ii]
            rgb = np.abs(rgb*255/rgb.max()).astype('uint8')
            odf_im = Image.fromarray(rgb, mode='RGB')
            odf_im = odf_im.convert('P', palette=Image.ADAPTIVE, colors=colors)
            
            lut = np.empty((colors,4),'uint8')
            lut[:, 3] = 255
            lut[:, 0:3] = np.reshape(odf_im.getpalette(),(colors,3))

            oo = mlab.mesh(x*odf_ii + x_cen.flat[ii], 
                           y*odf_ii + y_cen.flat[ii], 
                           z*odf_ii + z_cen.flat[ii], 
                           scalars=np.int16(odf_im))
            oo.module_manager.scalar_lut_manager.lut.table=lut
        else:
            mlab.mesh(x*odf_ii + x_cen.flat[ii],
                      y*odf_ii + y_cen.flat[ii],
                      z*odf_ii + z_cen.flat[ii],
                      scalars=odf_ii,
                      colormap=colormap)
Example #18
0
def disp_odf(sph_map, theta_res=64, phi_res=32, colormap='RGB', colors=256):

    pi = np.pi
    sin = np.sin
    cos = np.cos

    theta, phi = np.mgrid[0:2 * pi:theta_res * 1j, 0:pi:phi_res * 1j]
    x = sin(phi) * cos(theta)
    y = sin(phi) * sin(theta)
    z = cos(phi)

    nvox = np.prod(sph_map.shape)

    x_cen, y_cen, z_cen = _3grid(sph_map.shape)

    odf_values = sph_map.evaluate_at(theta, phi)
    max_value = odf_values.max()

    mlab.figure()
    for ii in range(nvox):
        odf_ii = odf_values.reshape(nvox, theta_res, phi_res)[ii, :, :]
        odf_ii /= max_value * 2
        if colormap == 'RGB':
            rgb = np.r_['-1,3,0', x * odf_ii, y * odf_ii, z * odf_ii]
            rgb = np.abs(rgb * 255 / rgb.max()).astype('uint8')
            odf_im = Image.fromarray(rgb, mode='RGB')
            odf_im = odf_im.convert('P', palette=Image.ADAPTIVE, colors=colors)

            lut = np.empty((colors, 4), 'uint8')
            lut[:, 3] = 255
            lut[:, 0:3] = np.reshape(odf_im.getpalette(), (colors, 3))

            oo = mlab.mesh(x * odf_ii + x_cen.flat[ii],
                           y * odf_ii + y_cen.flat[ii],
                           z * odf_ii + z_cen.flat[ii],
                           scalars=np.int16(odf_im))
            oo.module_manager.scalar_lut_manager.lut.table = lut
        else:
            mlab.mesh(x * odf_ii + x_cen.flat[ii],
                      y * odf_ii + y_cen.flat[ii],
                      z * odf_ii + z_cen.flat[ii],
                      scalars=odf_ii,
                      colormap=colormap)
Example #19
0
 def flaeche_berechnen(self):
     self.x_werte = self.x(self.u_f, self.v_f)
     self.y_werte = self.y(self.u_f, self.v_f)
     self.z_werte = self.z(self.u_f, self.v_f)
     self.mesh = mlab.mesh(self.x_werte, self.y_werte, self.z_werte, color=(0.6, 0.6, 0.6))
     ##         print self.u_f.shape , self.v_f.shape
     ##         print self.u_f
     ############ von __init__ hier runter geholt
     self.cursor3d = mlab.points3d(0.0, 0.0, 0.0, mode="sphere", color=(0, 0, 0), scale_factor=0.03)
     ############################################
     # TODO: sah kein unterschied zwischen den beiden zeilen hier drunter.
     self.fig.on_mouse_pick(lambda picker_obj: self.picker_callback(picker_obj))
Example #20
0
def plot_gk_on_sphere(g_k):

    r = 0.3
    phi, theta = np.mgrid[0:np.pi:101j, 0:2 * np.pi:101j]

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

    xyz = np.vstack([x.flatten(), y.flatten(), z.flatten()]).T

    density = evaluate_gk_on_sphere(g_k, xyz)

    fig = plt.figure()
    ax = fig.gca(projection='3d')
    mlab.mesh(x,
              y,
              z,
              scalars=np.imag(density).reshape(x.shape),
              colormap='jet')
    mlab.show()

    return
Example #21
0
def plot_eta(x,y,eta):

    theta = x * 2*pi / 360.
    phi = y * 2*pi / 360.
    X = 0.99*cos(theta)*cos(phi)
    Y = 0.99*sin(theta)*cos(phi)
    Z = 0.99*sin(phi)
    #import pdb; pdb.set_trace()
    Z = where(isnan(eta),nan,Z)

    if 0:
        # elevate according to eta:
        #X = X * (1. + 0.03*eta)
        #Y = Y * (1. + 0.03*eta)
        #Z = Z * (1. + 0.03*eta)
        # for big-radial-ocean:
        X = X * (1. + 0.3*eta)
        Y = Y * (1. + 0.3*eta)
        Z = Z * (1. + 0.3*eta)

    #cmap = make_colormap({0:[0,1,1], 1:[0,1,.5]})
    cmap = 'gist_earth'
    cmap = 'Blues'
    #cmap = 'Spectral'
    #mlab.mesh(X,Y,Z,scalars=eta,colormap=cmap, vmin = -1., vmax = 1.)
    # for big-radial-ocean:
    mlab.mesh(X,Y,Z,scalars=eta,colormap=cmap, vmin = -0.3, vmax = 0.3)
    V = (-3.4181052450711888, 74.940316958346571, 3.2320542851649994,\
          array([ 0.5,  0. ,  0.5]))
    mlab.view(*V)
    #mlab.view(0,40)

    mlab.figure(2,bgcolor=(1,1,1))
    mlab.clf()
    mlab.mesh(x,y,eta,colormap=cmap, vmin = -1., vmax = 1.)

    return X,Y,Z
Example #22
0
def mmesh():
    """A very pretty picture of spherical harmonics translated from
    the octaviz example."""
    pi = numpy.pi
    cos = numpy.cos
    sin = numpy.sin
    dphi, dtheta = pi/250.0, pi/250.0
    [phi,theta] = numpy.mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta]
    m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4;
    r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7
    x = r*sin(phi)*cos(theta)
    y = r*cos(phi)
    z = r*sin(phi)*sin(theta);

    return mesh(x, y, z, colormap="bone")
Example #23
0
# -*- coding: utf-8 -*-
from enthought.mayavi import mlab

x = [[-1, 1, 1, -1, -1], [-1, 1, 1, -1, -1]]

y = [[-1, -1, -1, -1, -1], [1, 1, 1, 1, 1]]

z = [[1, 1, -1, -1, 1], [1, 1, -1, -1, 1]]

box = mlab.mesh(x, y, z, representation="surface")
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(box)
mlab.show()
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

x, y = np.mgrid[-2:2:20j, -2:2:20j] 
z = x * np.exp( - x**2 - y**2)
z *= 2
c = 2*x + y 

pl = mlab.mesh(x, y, z, scalars=c) 
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(pl)
mlab.show()
Example #25
0
planenormal = h * kbasis[0] + k * kbasis[1] + l * kbasis[2]
theta = arcsin(vlen(planenormal) / k_photon / 2)

##########################################
#angle between diffraction plane and surface
theta1 = arccos(vlen(planenormal * array([0, 0, 1])) / vlen(planenormal))
phi1 = arctan(planenormal[1] / planenormal[0])

textwidth = 0.005

#######################
# the surface
x, y = mgrid[-100:101, -100:101] / 100 * a
z = x - x
mlab.mesh(x, y, z, opacity=0.5)
text = 'film surface'
mlab.text(1.1 * a, 0, 'film surface', z=0, width=len(text) * textwidth)

at.plot3d(text='(0,0,0)')
mlab.quiver3d([0], [0], [0], [0], [0], [1],
              mode='2ddash',
              color=(0, 0, 1),
              scale_mode="none",
              scale_factor=6)
text = 'surface normal'
mlab.text(0, 0, text, z=1.1 * c, width=len(text) * textwidth)

##########################
# the diffraction plane
plane_kx = planenormal[0] / planenormal[2]
Example #26
0
# Create the data.
from numpy import pi, sin, cos, mgrid
dphi, dtheta = pi/250.0, pi/250.0
[phi,theta] = mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta]
m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4;
r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7
x = r*sin(phi)*cos(theta)
y = r*cos(phi)
z = r*sin(phi)*sin(theta)

# View it.
from enthought.mayavi import mlab
s = mlab.mesh(x, y, z)
mlab.show()

Example #27
0
# -*- coding: utf-8 -*-
from numpy import *
from enthought.mayavi import mlab

# Create the data.
dphi, dtheta = pi / 20.0, pi / 20.0
[phi, theta] = mgrid[0:pi + dphi * 1.5:dphi, 0:2 * pi + dtheta * 1.5:dtheta]
m0 = 4
m1 = 3
m2 = 2
m3 = 3
m4 = 6
m5 = 2
m6 = 6
m7 = 4
r = sin(m0 * phi)**m1 + cos(m2 * phi)**m3 + sin(m4 * theta)**m5 + cos(
    m6 * theta)**m7
x = r * sin(phi) * cos(theta)
y = r * cos(phi)
z = r * sin(phi) * sin(theta)

# View it.
s = mlab.mesh(x, y, z, representation="wireframe", line_width=1.0)

mlab.show()
Example #28
0
#==============================================================================
# Plotting current vectors
#==============================================================================

#mlab.options.backend = 'envisage'         # one way to save visualization
#f = mlab.figure()
c1 = mlab.points3d(0, 0, 0)
mlab.quiver3d(x, y, z2, J_x, J_y, J_z, colormap="jet", scale_factor=1)

#==============================================================================
# Plotting actual ***boids
#==============================================================================

if (eps1 == 1):

    s2 = mlab.mesh(x, y, z2, colormap="gray", transparent=True)
#    mlab.quiver3d(x, y, z2, u2, v2, w2, scale_factor=1)
else:

    #    sr = mlab.mesh(x_r, y_r, z_r, colormap="gray", transparent=True)

    s2 = mlab.mesh(x, y, z2, colormap="gray", transparent=True)
#    mlab.quiver3d(x, y, z2, u2, v2, w2,colormap="gray",transparent=True, scale_factor=1)

#    s1 = mlab.mesh(x, y, z1,colormap="gray", transparent=True)
#    mlab.quiver3d(x, y, z1, u1, v1, w1,colormap="gray",transparent=True, scale_factor=1)

#==============================================================================
# Show the scene
#==============================================================================
Example #29
0
from scipy.special import sph_harm

# Create a sphere
r = 0.3
pi = np.pi
cos = np.cos
sin = np.sin
phi, theta = np.mgrid[0:pi:101j, 0:2*pi:101j]

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

mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
mlab.clf()
# Represent spherical harmonics on the surface of the sphere
for n in range(1, 6):
    for m in range(n):
        s = sph_harm(m, n, theta, phi).real

        mlab.mesh(x-m, y-n, z, scalars=s, colormap='jet')

        s[s<0] *= 0.97

        s /= s.max()
        mlab.mesh(s*x-m, s*y-n, s*z+1.3, scalars=s, colormap='Spectral')

mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
mlab.show()

Example #30
0
from numpy import *
from enthought.mayavi import mlab

polar = linspace(0, pi, 100)
azimuth = linspace(0, 2 * pi, 100)
phi, th = meshgrid(polar, azimuth)

r = 0.25 * sqrt(5.0 / pi) * (3 * cos(phi)**2 - 1)  #Ylm(0,2)

x = r * sin(phi) * cos(th)
y = r * cos(phi)
z = r * sin(phi) * sin(th)
mlab.mesh(x, y, z)

mlab.show()
Example #31
0
view2=mlab.view(120,90)
print view2
#mlab.pitch(90)
span+=1
for j in range(skip,cnt-1):
    if j%span!=0 and j!=0:
        continue
    print "TimeStep: %d" % (times[j])
    xx=xs[j]
    yy=ys[j]
    zz=zs[j]
    tt=ts[j]
    mlab.clf(fig1)
    mlab.clf(fig2)
    mlab.points3d(xx,yy,zz,tt,colormap="gist_heat",scale_factor=0.2,figure=fig1)
    mlab.mesh(xdummy,ydummy,pairdistro[j],figure=fig2)
    mlab.show(stop=True)

mlab.close(all=True)


#Bond lengths
"""
print "Calculating histogram of bond lengths corresponding to the minimum energy."
n=pes.index(min(pes))
xs=xs[n][:N]
ys=ys[n][:N]
zs=zs[n][:N]
radii=list()
for i in range(N):
    for j in range(i+1,N):
x_pca_axis, y_pca_axis, z_pca_axis = V.T*pca_score/pca_score.min()

mlab.view(-20.8, 83, 9, [0.18, 0.2, -0.24])
#mlab.savefig('pca_3d.jpg')
mlab.quiver3d(0.1*x_pca_axis, 0.1*y_pca_axis, 0.1*z_pca_axis,
                2*x_pca_axis, 2*y_pca_axis, 2*z_pca_axis,
                color=(0.6, 0, 0), line_width=2)

x_pca_axis, y_pca_axis, z_pca_axis = 3*V.T
x_pca_plane = np.r_[x_pca_axis[:2], - x_pca_axis[1::-1]]
y_pca_plane = np.r_[y_pca_axis[:2], - y_pca_axis[1::-1]]
z_pca_plane = np.r_[z_pca_axis[:2], - z_pca_axis[1::-1]]

x_pca_plane.shape = (2, 2)
y_pca_plane.shape = (2, 2)
z_pca_plane.shape = (2, 2)

mlab.mesh(x_pca_plane, y_pca_plane, z_pca_plane, color=(0.6, 0, 0),
            opacity=0.1)
mlab.mesh(x_pca_plane, y_pca_plane, z_pca_plane, color=(0.6, 0, 0),
            representation='wireframe', line_width=3, opacity=0.3)

#mlab.title('PCA axis')
mlab.view(-20.8, 83, 9, [0.18, 0.2, -0.24])
#mlab.savefig('pca_3d_axis.jpg')

# A view
mlab.view(3.3, 43.8, 9.2, [0.04, -0.11, -0.17])
#mlab.savefig('pca_3d_aligned.jpg')

Example #33
0
z=npzfile['z']
fm=npzfile['fm']

########################################################
# Set up the window

f = mlab.figure(size=(800,600))
# Tell visual to use this as the viewer.
visual.set_viewer(f)

########################################################
# Do the appropriate graph

#s = mlab.contour_surf(r,z,fun, contours=30, line_width=.5, transparent=True)
#s=mlab.surf(r,z,fun, colormap='Spectral')
s = mlab.mesh(r,z,fm[0,:,:], scalars=fm[0,:,:], colormap='PuOr')#, wrap_scale='true')#, representation='wireframe')
s.enable_contours=True
s.contour.filled_contours=True

# Define perspective and optional attributes. You can also implement from the window afterwards

mlab.view(0,0)
#mlab.view(-94.159958841373324,
# 53.777002382688906,
# 8.2311808018087582)
mlab.draw(f)
mlab.colorbar(orientation="vertical")
#mlab.axes()
#mlab.outline()

Example #34
0
def pattern_tp(array_ip, tht_scan=0, phi_scan=0, tht_min=0, tht_max=np.pi, tht_num=50,
               phi_min=0, phi_max=2 * np.pi, phi_num=50, scale="dB",
               dB_limit= -40, factor="GF", plot_type="rect",
               mayavi_app=False):
    r"""
    Function to evaluate 3D AF/GF/NF of a arbitrary 3D array in (tht, phi)-domain.
    By default, this function calculates the gain-factor (GF).
   
    :param array_ip:       array excitation data in 'Arraytool' input format (see :func:`ip_format`)
    :param tht_scan, etc:  beam scan position in (tht, phi)-domain
    :param tht_min, etc:   limits of (tht, phi)-domain
    :param tht_num, etc:   number of points between 'tht_min' and 'tht_max' including
                           the boundaries
    :param scale:          specifies the scale choice ... dB/linear
    :param dB_limit:       cutoff limit (see :func:`cutoff`)
    :param factor:         type of pattern you need ... AF/NF/GF
    :param plot_type:      can be rect/polar/contour ... if False, nothing happens
    :param mayavi_app:     if True, the 3D plot will be opened in the MayaVi application
    
    :rtype:                A list, [tht,phi,F]
    """
    x = array_ip[:, 0]
    y = array_ip[:, 1]
    z = array_ip[:, 2]
    A = array_ip[:, 3] # un-packing "array_ip" finished
    k = 2 * np.pi # (angular) wave-number, which is 2*pi when lambda = 1
    tht_numj = complex(0, tht_num)
    phi_numj = complex(0, phi_num)

    [tht, phi] = np.mgrid[tht_min:tht_max:tht_numj, phi_min:phi_max:phi_numj]
    u = np.sin(tht) * np.cos(phi); v = np.sin(tht) * np.sin(phi); w = np.cos(tht)
    u1 = np.reshape(u, (u.size, -1))
    v1 = np.reshape(v, (v.size, -1))
    w1 = np.reshape(w, (w.size, -1))
    u_scan = np.sin(tht_scan) * np.cos(phi_scan)
    v_scan = np.sin(tht_scan) * np.sin(phi_scan)
    w_scan = np.cos(tht_scan)
    
    A = np.reshape(A, (len(A), -1))
    U = np.tile(u1 - u_scan, len(x))
    V = np.tile(v1 - v_scan, len(x))
    W = np.tile(w1 - w_scan, len(x))
    X = np.tile(x, (u.size, 1))
    Y = np.tile(y, (u.size, 1))
    Z = np.tile(z, (u.size, 1))

    # Evaluating array-factor of the planar array
    AF1 = np.dot(np.exp(1j * k * (U * X + V * Y + W * Z)), A)
    AF = np.reshape(AF1, u.shape)

    # Evaluation of F = (AF/GF/NF) => depending upon the user's choice
    if(factor == "AF"):
        F = AF; n1 = ""; ff = "Array-Factor "; f1 = "AF "
    elif(factor == "GF"):
        P_inc = ((abs(A)) ** 2).sum()
        GF = AF / np.sqrt(P_inc) # Converting the AF to GF
        F = GF; n1 = ""; ff = "Gain-Factor "; f1 = "GF "
    elif(factor == "NF"):
        norm_fact = (abs(A)).sum()
        F = AF / norm_fact
        n1 = "Normalized "; ff = "Factor "; f1 = "NF "

    # converting 'F' from linear to dB scale, if needed
    if(scale == "linear"):
        F_plt = abs(F)
        ss = "in linear scale"
    elif(scale == "dB"):
        F = 20 * np.log10(abs(F))
        # cutoff the "F" below some limit ... just for the plotting purpose
        F_plt = cutoff(F, dB_limit)
        ss = "in dB scale"

    # plotting the factor (AF/GF/NF)
    if(plot_type):
        if (mayavi_app): # opens the 3D plot in MayaVi Application
            mlab.options.backend = 'envisage'
        if(plot_type == "rect"): # rectangular plot
            plt3d = mlab.surf(tht, phi, F_plt, warp_scale='auto')
            ranges1 = [tht.min(), tht.max(), phi.min(), phi.max(), F_plt.min(), F_plt.max()]
            mlab.axes(xlabel='Tht', ylabel='Phi', zlabel=f1,
                      ranges=ranges1, nb_labels=5)
            mlab.title(n1 + ff + ss, size=0.35)
            mlab.colorbar(orientation="vertical", nb_labels=5)
            plt3d.scene.isometric_view()
            mlab.show()
        if(plot_type == "polar"): # rectangular plot
            if(scale == "dB"):
                F_plt = F_plt - dB_limit
            F_plt_x = F_plt * u; F_plt_y = F_plt * v; F_plt_z = F_plt * w            
            ranges1 = [F_plt_x.min(), F_plt_x.max(), F_plt_y.min(), F_plt_y.max(), F_plt_z.min(), F_plt_z.max()]
            plt3d = mlab.mesh(F_plt_x, F_plt_y, F_plt_z, scalars=F_plt, extent=ranges1)
            mlab.axes(xlabel='x', ylabel='y', zlabel='z',
                      ranges=ranges1, nb_labels=5)
            mlab.title(n1 + ff + ss, size=0.35)
            mlab.colorbar(orientation="vertical", nb_labels=5)
            plt3d.scene.isometric_view()
            mlab.show()        
        if(plot_type == "contour"): # contour plot
            plt.contourf(tht, phi, F_plt)
            plt.axis('tight'); plt.grid(True)
            plt.xlabel(r'$\theta$', fontsize=16)
            plt.ylabel(r'$\phi$', fontsize=16)
            plt.colorbar(format='$%.2f$')
            plt.show()                
    return tht, phi, F
def scan_strain_space( max_strain = 0.0002 ):

    rho = 0.03
    E_f = 70000
    E_m = 24000  
    E_c = E_m * ( 1 - rho ) + E_f * rho


    R = max_strain
    n_R = 30
    in_R = 30j
    
    Alpha_min =  - math.pi / 2.0 * 0.5
    Alpha_max =    math.pi / 2.0 * 1.5
    n_Alpha = 19
    in_Alpha = 19j
    
    phi_fn = PhiFnStrainHardeningLinear(  E_m = E_m, E_f = E_f, rho = rho,
                                          sigma_0 = 5.0, 
                                          alpha = 0.4, beta = 0.4, Elimit = 1.0 )
    #phi_fn = PhiFnStrainSoftening()

    explorer = MATSExplore( dim = MATS2DExplore( mats_eval = \
                                                 MATS2DMicroplaneDamage(E = E_c, nu = 0.25,
                                                                        n_mp = 30, 
                                                                        phi_fn = phi_fn) ))

    explorer.tloop.bcond_list[0].max_strain = R
    explorer.tloop.tline.step = 1.0 / (n_R-1)
    teps = explorer.tloop.tstepper.rtrace_mngr[ 'strain - strain' ]
    teps.idx_y = 3
#    r, alpha = numpy.mgrid[0:R:in_R, Alpha_min:Alpha_max: in_Alpha ]
#    print 'r', r
#    print 'alpha', alpha
#    
#    x = r * numpy.cos( alpha )
#    y = r * numpy.sin( alpha )

    def f( alpha_rad ):
        explorer.tloop.reset()        
        print 'calculating', alpha_rad
        explorer.tloop.bcond_list[0].alpha_rad = alpha_rad
        u = explorer.tloop.eval()
        tsig = explorer.tloop.tstepper.rtrace_mngr[ 'time - sig_norm' ]
        #teps = explorer.tloop.tstepper.rtrace_mngr[ 'strain - strain' ]        
        tsig.refresh()
        teps.refresh()
        return teps.trace.xdata, teps.trace.ydata, tsig.trace.ydata            

    alpha_arr = numpy.linspace( Alpha_min, Alpha_max, n_Alpha )
    print 'alpha_arr', alpha_arr
    
    sfunc = numpy.frompyfunc( f, 1, 3 )
    xarr_list, yarr_list, zarr_list  = sfunc( alpha_arr )
    print 'x',xarr_list
    print 'y',yarr_list
    print 'z',zarr_list
    
    x = numpy.array( numpy.vstack( xarr_list ), dtype = 'float_' ).T
    y = numpy.array( numpy.vstack( yarr_list ), dtype = 'float_' ).T
    z = numpy.array( numpy.vstack( zarr_list ), dtype = 'float_' ).T

    maxx = numpy.max( numpy.abs( x ) )
    maxy = numpy.max( numpy.abs( y ) )
    maxz = numpy.max( z ) / 0.5
    
    x /= maxx
    y /= maxy
    z /= maxz
    
    print 'x', x
    print 'y', y
    print 'z', z
    
    s = mlab.mesh(x, y, z, colormap="bone" )
    return
Example #36
0
The boy surface is a mathematical parametric surface, see
http://en.wikipedia.org/wiki/Boy%27s_surface . We display it by sampling
the two parameters of the surface on a grid and using the mlab's mesh
function: :func:`enthought.mayavi.mlab.mesh`.
"""

# Author: Gael Varoquaux <*****@*****.**> 
# Copyright (c) 2007, Enthought, Inc.
# License: BSD Style.


from numpy import sin, cos, mgrid, pi, sqrt 
from enthought.mayavi import mlab

mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
u, v = mgrid[-0.035:pi:0.01, -0.035:pi:0.01]

X = 2/3.* (cos(u)* cos(2*v) 
        + sqrt(2)* sin(u)* cos(v))* cos(u) / (sqrt(2) - sin(2*u)* sin(3*v))
Y = 2/3.* (cos(u)* sin(2*v) - sqrt(2)* sin(u)* sin(v))* cos(u) / (sqrt(2)
        - sin(2*u)* sin(3*v))
Z = -sqrt(2)* cos(u)* cos(u) / (sqrt(2) - sin(2*u)* sin(3*v))
S = sin(u)

mlab.mesh(X, Y, Z, scalars=S, colormap='YlGnBu', )

# Nice view from the front
mlab.view(.0, -5.0, 4)
mlab.show()
# -*- coding: utf-8 -*-
"""
用mesh()绘制旋转抛物面
"""
import numpy as np
from enthought.mayavi import mlab

rho, theta = np.mgrid[0:1:40j, 0:2 * np.pi:40j]

z = rho * rho

x = rho * np.cos(theta)
y = rho * np.sin(theta)

s = mlab.mesh(x, y, z)
mlab.show()
# -*- coding: utf-8 -*-
from enthought.mayavi import mlab

x = [[-1,1,1,-1,-1],
     [-1,1,1,-1,-1]]

y = [[-1,-1,-1,-1,-1],
     [ 1, 1, 1, 1, 1]]

z = [[1,1,-1,-1,1],
     [1,1,-1,-1,1]]

box = mlab.mesh(x, y, z, representation="surface")
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(box)
mlab.show()
Example #39
0
r = 0.3
pi = np.pi
cos = np.cos
sin = np.sin
phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j]

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

mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
mlab.clf()
# Represent spherical harmonics on the surface of the sphere
for n in range(1, 6):
    for m in range(n):
        s = sph_harm(m, n, theta, phi).real

        mlab.mesh(x - m, y - n, z, scalars=s, colormap='jet')

        s[s < 0] *= 0.97

        s /= s.max()
        mlab.mesh(s * x - m,
                  s * y - n,
                  s * z + 1.3,
                  scalars=s,
                  colormap='Spectral')

mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
mlab.show()
Example #40
0
# -*- coding: utf-8 -*-
from numpy import *
from enthought.mayavi import mlab

# Create the data.
dphi, dtheta = pi/20.0, pi/20.0
[phi,theta] = mgrid[0:pi+dphi*1.5:dphi,0:2*pi+dtheta*1.5:dtheta]
m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 6; m5 = 2; m6 = 6; m7 = 4;
r = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7
x = r*sin(phi)*cos(theta)
y = r*cos(phi)
z = r*sin(phi)*sin(theta)

# View it.
s = mlab.mesh(x, y, z, representation="wireframe", line_width=1.0 )

mlab.show()
              2 * z_pca_axis,
              color=(0.6, 0, 0),
              line_width=2)

x_pca_axis, y_pca_axis, z_pca_axis = 3 * V.T
x_pca_plane = np.r_[x_pca_axis[:2], -x_pca_axis[1::-1]]
y_pca_plane = np.r_[y_pca_axis[:2], -y_pca_axis[1::-1]]
z_pca_plane = np.r_[z_pca_axis[:2], -z_pca_axis[1::-1]]

x_pca_plane.shape = (2, 2)
y_pca_plane.shape = (2, 2)
z_pca_plane.shape = (2, 2)

mlab.mesh(x_pca_plane,
          y_pca_plane,
          z_pca_plane,
          color=(0.6, 0, 0),
          opacity=0.1)
mlab.mesh(x_pca_plane,
          y_pca_plane,
          z_pca_plane,
          color=(0.6, 0, 0),
          representation='wireframe',
          line_width=3,
          opacity=0.3)

#mlab.title('PCA axis')
mlab.view(-20.8, 83, 9, [0.18, 0.2, -0.24])
#mlab.savefig('pca_3d_axis.jpg')

# A view
Example #42
0
x, y = extent
n = z.shape
if draft:
    x = x[0] + ddeg * np.arange( n[0] )
    y = y[0] + ddeg * np.arange( n[1] )
else:
    x = x[0] + 0.5 * ddeg * np.arange( n[0] * 2 - 1 )
    y = y[0] + 0.5 * ddeg * np.arange( n[1] * 2 - 1 )
    z = cst.data.upsample( z )
y, x = np.meshgrid( y, x )
s = np.maximum( 0.01, z )
i = (x + y) < -84.0
s[i] = z[i]
x, y = proj( x, y )
cmap = cst.mlab.colormap( cmap, 2.5 )
surf = mlab.mesh( x, y, z, scalars=s, vmin=-4, vmax=4, figure=fig )
surf.module_manager.scalar_lut_manager.lut.table = cmap
surf.actor.property.ambient = 0.0
surf.actor.property.diffuse = 1.0
surf.actor.property.specular = 0.6
surf.actor.property.specular_power = 10
surf.parent.parent.filter.splitting = False

# lighting
fig.scene.light_manager.lights[0].azimuth = 30
fig.scene.light_manager.lights[0].elevation = 30
fig.scene.light_manager.lights[0].intensity = 1.0
fig.scene.light_manager.lights[0].activate = True
fig.scene.light_manager.lights[1].activate = False
fig.scene.light_manager.lights[2].activate = False
Example #43
0
# -*- coding: utf-8 -*-
import numpy as np
from enthought.mayavi import mlab

const = 2.19967e34
x, y = np.mgrid[0:700:200j, 300:1500:200j]
z = np.exp(-x / y) * np.sqrt(x) / (y**1.5)
c = const * z

pl = mlab.mesh(x, y, z, scalars=c)
mlab.axes(xlabel='Energy(eV)', ylabel='Temprature(k)', zlabel='N/2.19967e34')
mlab.outline(pl)
mlab.show()
Example #44
0
"""

# Author: Gael Varoquaux <*****@*****.**>
# Copyright (c) 2007, Enthought, Inc.
# License: BSD Style.

from numpy import sin, cos, mgrid, pi, sqrt
from enthought.mayavi import mlab

mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
u, v = mgrid[-0.035:pi:0.01, -0.035:pi:0.01]

X = 2 / 3. * (cos(u) * cos(2 * v) + sqrt(2) * sin(u) * cos(v)) * cos(u) / (
    sqrt(2) - sin(2 * u) * sin(3 * v))
Y = 2 / 3. * (cos(u) * sin(2 * v) - sqrt(2) * sin(u) * sin(v)) * cos(u) / (
    sqrt(2) - sin(2 * u) * sin(3 * v))
Z = -sqrt(2) * cos(u) * cos(u) / (sqrt(2) - sin(2 * u) * sin(3 * v))
S = sin(u)

mlab.mesh(
    X,
    Y,
    Z,
    scalars=S,
    colormap='YlGnBu',
)

# Nice view from the front
mlab.view(.0, -5.0, 4)
mlab.show()
Example #45
0
m5 = 2
m6 = 2
m7 = 4
s = sin(m0 * phi) ** m1 + cos(m2 * phi) ** m3 + sin(m4 * theta) ** m5 + cos(m6 * theta) ** m7
x = sin(phi) * cos(theta)
y = cos(phi)
z = sin(phi) * sin(theta)

################################################################################
# Plot the data
from enthought.mayavi import mlab

# A first plot in 3D
fig = mlab.figure(1)
mlab.clf()
mesh = mlab.mesh(x, y, z, scalars=s)
cursor3d = mlab.points3d(0.0, 0.0, 0.0, mode="axes", color=(0, 0, 0), scale_factor=0.5)
mlab.title("Click on the ball")

# A second plot, flat
fig2d = mlab.figure(2)
mlab.clf()
im = mlab.imshow(s)
cursor = mlab.points3d(0, 0, 0, mode="2dthick_cross", color=(0, 0, 0), scale_factor=10)
mlab.view(90, 0)

################################################################################
# Some logic to select 'mesh' and the data index when picking.


def picker_callback(picker_obj):
# Author: Gael Varoquaux <*****@*****.**>
# Copyright (c) 2008, Enthought, Inc.
# License: BSD Style.

from enthought.mayavi import mlab
import numpy as np
from scipy.special import sph_harm

# Create a sphere
r = 0.3
pi = np.pi
cos = np.cos
sin = np.sin
phi, theta = np.mgrid[0:pi:101j, 0:2 * pi:101j]

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

mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
mlab.clf()
# Represent spherical harmonics on the surface of the sphere
for l in range(0, 5):
    for m in range(l):
        s = sph_harm(m, l, theta, phi).real

        mlab.mesh(x + m, y - l, z, scalars=s, colormap='jet')

mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
mlab.show()
Example #47
0
# setup figure
pixels = 640, 360
size = pixels[0], pixels[1] + 48
fig = mlab.figure( None, size=size, bgcolor=(1,1,1), fgcolor=(0,0,0) )
mlab.clf()
fig.scene.disable_render = True
fig.scene.set_size( pixels )

# plot segments
i = 0
for n in nn:
    x = xx[i:i+n]
    y = yy[i:i+n]
    z = zz[i:i+n]
    s = ss[i:i+n]
    h = mlab.mesh( x, y, z, scalars=s, vmin=vmin, vmax=vmax )
    lut = cst.mlab.colormap( 'bgr' )[::-1]
    h.module_manager.scalar_lut_manager.lut.table = lut
    i += n
    if 1:
        x = np.concatenate( [x[:,0], x[::-1,-1], x[:1,0]] )
        y = np.concatenate( [y[:,0], y[::-1,-1], y[:1,0]] )
        z = np.concatenate( [z[:,0], z[::-1,-1], z[:1,0]] )
        mlab.plot3d( x, y, z, line_width=0.5, tube_radius=None )

# plot coastline
extent = (-120.0, -117.0), (33.0, 35.0)
x, y = cst.data.mapdata( 'coastlines', 'high', extent, 10.0 )
x, y = proj( x, y )
z = np.zeros_like( x )
mlab.plot3d( x, y, z, color=(0,0,0), line_width=0.5, tube_radius=None )
Example #48
0
z=npzfile['z']
fm=npzfile['fm']

########################################################
# Set up the window

f = mlab.figure(size=(800,600))
# Tell visual to use this as the viewer.
visual.set_viewer(f)

########################################################
# Do the appropriate graph

#s = mlab.contour_surf(r,z,fun, contours=30, line_width=.5, transparent=True)
#s=mlab.surf(r,z,fun, colormap='Spectral')
s = mlab.mesh(r,z,fm[0,:,:], scalars=fm[0,:,:], colormap='PuOr')#, wrap_scale='true')#, representation='wireframe')
s.enable_contours=True
s.contour.filled_contours=True

# Define perspective and optional attributes. You can also implement from the window afterwards

mlab.view(0,0)
#mlab.view(-94.159958841373324,
# 53.777002382688906,
# 8.2311808018087582)
mlab.draw(f)
mlab.colorbar(orientation="vertical")
#mlab.axes()
#mlab.outline()

# Set up our grid

[phi,theta] = np.meshgrid(phi,theta)

# Radius of displayed sphere

r = 5

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

#Plot Sphere

mlab.figure("Figure 1")
figure1 = mlab.mesh(x,y,z,representation='wireframe')
mlab.axes()
mlab.title("Figure 1")
mlab.outline()

#Make the radius a function of theta and phi
#antenna pattern response to a +/- polarized wave
#See Eq. 7 of Anholm et al. (Phys. Rev. D 79, 084030 (2009))

rp = np.absolute(.5*np.sin(theta)**2 * (np.cos(phi)**2 - 
	np.sin(phi)**2) / (1 + np.cos(theta)))

rp_mask = np.ma.masked_invalid(rp)

x = rp*np.sin(theta)*np.cos(phi)
x[np.isinf(x)] = np.nan
Example #50
0
def pattern_tp(
    array_ip,
    tht_scan=0,
    phi_scan=0,
    tht_min=0,
    tht_max=np.pi,
    tht_num=50,
    phi_min=0,
    phi_max=2 * np.pi,
    phi_num=50,
    scale="dB",
    dB_limit=-40,
    factor="GF",
    plot_type="rect",
    mayavi_app=False,
):
    r"""
    Function to evaluate 3D AF/GF/NF of a arbitrary 3D array in (tht, phi)-domain.
    By default, this function calculates the gain-factor (GF).
   
    :param array_ip:       array excitation data in 'Arraytool' input format (see :func:`ip_format`)
    :param tht_scan, etc:  beam scan position in (tht, phi)-domain
    :param tht_min, etc:   limits of (tht, phi)-domain
    :param tht_num, etc:   number of points between 'tht_min' and 'tht_max' including
                           the boundaries
    :param scale:          specifies the scale choice ... dB/linear
    :param dB_limit:       cutoff limit (see :func:`cutoff`)
    :param factor:         type of pattern you need ... AF/NF/GF
    :param plot_type:      can be rect/polar/contour ... if False, nothing happens
    :param mayavi_app:     if True, the 3D plot will be opened in the MayaVi application
    
    :rtype:                A list, [tht,phi,F]
    """
    x = array_ip[:, 0]
    y = array_ip[:, 1]
    z = array_ip[:, 2]
    A = array_ip[:, 3]  # un-packing "array_ip" finished
    k = 2 * np.pi  # (angular) wave-number, which is 2*pi when lambda = 1
    tht_numj = complex(0, tht_num)
    phi_numj = complex(0, phi_num)

    [tht, phi] = np.mgrid[tht_min:tht_max:tht_numj, phi_min:phi_max:phi_numj]
    u = np.sin(tht) * np.cos(phi)
    v = np.sin(tht) * np.sin(phi)
    w = np.cos(tht)
    u1 = np.reshape(u, (u.size, -1))
    v1 = np.reshape(v, (v.size, -1))
    w1 = np.reshape(w, (w.size, -1))
    u_scan = np.sin(tht_scan) * np.cos(phi_scan)
    v_scan = np.sin(tht_scan) * np.sin(phi_scan)
    w_scan = np.cos(tht_scan)

    A = np.reshape(A, (len(A), -1))
    U = np.tile(u1 - u_scan, len(x))
    V = np.tile(v1 - v_scan, len(x))
    W = np.tile(w1 - w_scan, len(x))
    X = np.tile(x, (u.size, 1))
    Y = np.tile(y, (u.size, 1))
    Z = np.tile(z, (u.size, 1))

    # Evaluating array-factor of the planar array
    AF1 = np.dot(np.exp(1j * k * (U * X + V * Y + W * Z)), A)
    AF = np.reshape(AF1, u.shape)

    # Evaluation of F = (AF/GF/NF) => depending upon the user's choice
    if factor == "AF":
        F = AF
        n1 = ""
        ff = "Array-Factor "
        f1 = "AF "
    elif factor == "GF":
        P_inc = ((abs(A)) ** 2).sum()
        GF = AF / np.sqrt(P_inc)  # Converting the AF to GF
        F = GF
        n1 = ""
        ff = "Gain-Factor "
        f1 = "GF "
    elif factor == "NF":
        norm_fact = (abs(A)).sum()
        F = AF / norm_fact
        n1 = "Normalized "
        ff = "Factor "
        f1 = "NF "

    # converting 'F' from linear to dB scale, if needed
    if scale == "linear":
        F_plt = abs(F)
        ss = "in linear scale"
    elif scale == "dB":
        F = 20 * np.log10(abs(F))
        # cutoff the "F" below some limit ... just for the plotting purpose
        F_plt = cutoff(F, dB_limit)
        ss = "in dB scale"

    # plotting the factor (AF/GF/NF)
    if plot_type:
        if mayavi_app:  # opens the 3D plot in MayaVi Application
            mlab.options.backend = "envisage"
        if plot_type == "rect":  # rectangular plot
            plt3d = mlab.surf(tht, phi, F_plt, warp_scale="auto")
            ranges1 = [tht.min(), tht.max(), phi.min(), phi.max(), F_plt.min(), F_plt.max()]
            mlab.axes(xlabel="Tht", ylabel="Phi", zlabel=f1, ranges=ranges1, nb_labels=5)
            mlab.title(n1 + ff + ss, size=0.35)
            mlab.colorbar(orientation="vertical", nb_labels=5)
            plt3d.scene.isometric_view()
            mlab.show()
        if plot_type == "polar":  # rectangular plot
            if scale == "dB":
                F_plt = F_plt - dB_limit
            F_plt_x = F_plt * u
            F_plt_y = F_plt * v
            F_plt_z = F_plt * w
            ranges1 = [F_plt_x.min(), F_plt_x.max(), F_plt_y.min(), F_plt_y.max(), F_plt_z.min(), F_plt_z.max()]
            plt3d = mlab.mesh(F_plt_x, F_plt_y, F_plt_z, scalars=F_plt, extent=ranges1)
            mlab.axes(xlabel="x", ylabel="y", zlabel="z", ranges=ranges1, nb_labels=5)
            mlab.title(n1 + ff + ss, size=0.35)
            mlab.colorbar(orientation="vertical", nb_labels=5)
            plt3d.scene.isometric_view()
            mlab.show()
        if plot_type == "contour":  # contour plot
            plt.contourf(tht, phi, F_plt)
            plt.axis("tight")
            plt.grid(True)
            plt.xlabel(r"$\theta$", fontsize=16)
            plt.ylabel(r"$\phi$", fontsize=16)
            plt.colorbar(format="$%.2f$")
            plt.show()
    return tht, phi, F
Example #51
0
phi, theta = np.mgrid[0:pi:180j,0:2*pi:180j]
m0 = 4; m1 = 3; m2 = 2; m3 = 3; m4 = 1; m5 = 2; m6 = 2; m7 = 4;
s = sin(m0*phi)**m1 + cos(m2*phi)**m3 + sin(m4*theta)**m5 + cos(m6*theta)**m7
x = sin(phi)*cos(theta)
y = cos(phi)
z = sin(phi)*sin(theta)

################################################################################
# Plot the data
from enthought.mayavi import mlab

# A first plot in 3D
fig = mlab.figure(1)
mlab.clf()
mesh = mlab.mesh(x, y, z, scalars=s)
cursor3d = mlab.points3d(0., 0., 0., mode='axes',
                                color=(0, 0, 0),
                                scale_factor=0.5)
mlab.title('Click on the ball')

# A second plot, flat
fig2d = mlab.figure(2)
mlab.clf()
im = mlab.imshow(s)
cursor = mlab.points3d(0, 0, 0, mode='2dthick_cross',
                                color=(0, 0, 0),
                                scale_factor=10)
mlab.view(90, 0)

################################################################################
Example #52
0
################################################################

xx = zeros((Ntheta, Nphi))
yy = zeros((Ntheta, Nphi))
zz = zeros((Ntheta, Nphi))

for i in range(Ntheta):
    for j in range(Nphi):
        xx[i, j] = sin(THETA[i]) * cos(PHI[j])
        yy[i, j] = sin(THETA[i]) * sin(PHI[j])
        zz[i, j] = cos(THETA[i])

############################### MAYAVI #################################

mlab.figure('Radius')
mlab.mesh(xx, yy, zz, scalars=RADIUS, colormap='jet')
mlab.colorbar()
mlab.draw()

mlab.figure('Radius (bis)')
mlab.mesh(RADIUS * xx, RADIUS * yy, RADIUS * zz, colormap='jet')
mlab.colorbar()
mlab.draw()

############################## PYPLOT ##################################

xx = RADIUS * xx
yy = RADIUS * yy
zz = RADIUS * zz

figure(0)