Exemple #1
0
def anim(s, d, *args, **kwargs):
    """ Animate graph s with data d[nt,nx,ny] 
    optional argument s1 -> additional bundled graph
    optional kargument 'save = False' -> save png files for creating movie
    """

    if len(args) == 1:
        s1 = args[0]
    else:
        s1 = None

    try:
        save = kwargs['save']
    except:
        save = False

    nt = d.shape[0]

    print('animating for ', nt, 'timesteps')
    if save == True:
        print('Saving pics in folder Movie')
        if not os.path.exists('Movie'):
            os.makedirs('Movie')

    for i in range(nt):
        s.mlab_source.scalars = d[i, :, :]
        if s1 != None: s1.mlab_source.scalars = d[i, :, :]
        title = "t=" + np.string0(i)
        mlab.title(title, height=1.1, size=0.26)
        if save == True: mlab.savefig('Movie/anim%d.png' % i)
        yield
Exemple #2
0
def viewImgWithNodes(img, spacing, contours,g, title=''):

    mlab.figure(bgcolor=(0, 0, 0), size=(900, 900))
    
    #src = mlab.pipeline.scalar_field(img)
    ## Our data is not equally spaced in all directions:
    #src.spacing = [1, 1, 1]
    #src.update_image_data = True
    #
    #mlab.pipeline.iso_surface(src, contours=contours, opacity=0.2)
    nodes = np.array(g.nodes())
    dsize = 4*np.ones(nodes.shape[0],dtype='float32')
    print(dsize.shape,nodes.shape)
    #mlab.points3d(nodes[:,0],nodes[:,1],nodes[:,2],color=(0.0,1.0,0.0))
    mlab.points3d(nodes[:,2],nodes[:,1],nodes[:,0],dsize,color=(0.0,0.0,1.0), scale_factor=0.25)
    
    for n1, n2, edge in g.edges(data=True):
        path = [n1]+edge['path']+[n2]
        pa = np.array(path)
        #print pa
        mlab.plot3d(pa[:,2],pa[:,1],pa[:,0],color=(0,1,0),tube_radius=0.25)
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    mlab.title(title, height=0.1)
    
    mlab.show()
Exemple #3
0
def anim(s, d, *args, **kwargs):
    """ Animate graph s with data d[nt,nx,ny] 
    optional argument s1 -> additional bundled graph
    optional kargument 'save = False' -> save png files for creating movie
    """ 
       
    if len(args) == 1:
        s1 = args[0]
    else:
        s1=None

    try:
        save = kwargs['save']
    except:
        save = False
                    
            
    nt=d.shape[0]
    
    print('animating for ',nt,'timesteps') 
    if save == True : 
        print('Saving pics in folder Movie') 
        if not os.path.exists('Movie'):
            os.makedirs('Movie')

   
    for i in range(nt):
        s.mlab_source.scalars = d[i,:,:]
        if s1 != None : s1.mlab_source.scalars = d[i,:,:]
        title="t="+np.string0(i)
        mlab.title(title,height=1.1, size=0.26)
        if save == True : mlab.savefig('Movie/anim%d.png'%i)
        yield
Exemple #4
0
 def test_text(self):
     """ Test the text module.
     """
     data = np.random.random((3, 3, 3))
     src = mlab.pipeline.scalar_field(data)
     # Some smoke testing
     mlab.text(0.1, 0.9, 'foo')
     mlab.text(3, 3, 'foo', z=3)
     mlab.title('foo')
     # Check that specifying 2D positions larger than 1 raises an
     # error
     self.assertRaises(ValueError, mlab.text, 0, 1.5, 'test')
Exemple #5
0
 def test_text(self):
     """ Test the text module.
     """
     data = np.random.random((3, 3, 3))
     src = mlab.pipeline.scalar_field(data)
     # Some smoke testing
     mlab.text(0.1, 0.9, 'foo')
     mlab.text(3, 3, 'foo', z=3)
     mlab.title('foo')
     # Check that specifying 2D positions larger than 1 raises an
     # error
     self.assertRaises(ValueError, mlab.text, 0, 1.5, 'test')
Exemple #6
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)
Exemple #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)
def plotframe(frameno,level=1, water_opacity=1.):

    plotdata = ClawPlotData()
    plotdata.outdir = outdir
    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]
        
            topo = eta - h
            cutoff = 0.5
            #cutoff2 = -500.
            shift = 0.
            scale = 1.
            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)
            scale = 12.
            #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='YlGn',warp_scale=scale,\
                          vmin=-0.3,vmax=0.3)
            mlab.surf(x,y,water1,colormap='Blues',warp_scale=scale,\
                          vmin=-0.2,vmax=0.3, opacity=water_opacity)

    # set the view:  (Do V = view() to figure out the current view)
    V = (29.157490879985176,\
     67.560491214404507,\
     79.798910042690324,\
     array([ 0.        ,  1.        , -0.07500005]))

    mlab.view(*V)
    t = frame.t
    mlab.title('Time = %5.2f' % t,color=(0,0,0),height=0.1,size=0.5)
Exemple #9
0
def anim(s, d, *args, **kwargs):
    """Animate graph with mayavi

    Parameters
    ----------
    s : mayavi axis object
        Axis to animate data on
    d : array_like
        3-D array to animate
    s1 : mayavi axis object, optional
        Additional bundled graph (first item in *args)
    save : bool, optional
        Save png files for creating movie (default: False)

    """

    if len(args) == 1:
        s1 = args[0]
    else:
        s1=None

    try:
        save = kwargs['save']
    except:
        save = False
                    
            
    nt=d.shape[0]
    
    print('animating for ',nt,'timesteps') 
    if save == True : 
        print('Saving pics in folder Movie') 
        if not os.path.exists('Movie'):
            os.makedirs('Movie')

   
    for i in range(nt):
        s.mlab_source.scalars = d[i,:,:]
        if s1 is not None : s1.mlab_source.scalars = d[i,:,:]
        title="t="+np.string0(i)
        mlab.title(title,height=1.1, size=0.26)
        if save == True : mlab.savefig('Movie/anim%d.png'%i)
        yield
Exemple #10
0
    def play(self, fileroot='Network', mspikes=[], gspikes=[], save_png=False,
             sim_step=10, windowsize=10):
        view = mlab.view()
        f = mlab.gcf()
        if not mspikes:
            mspikes = self.mspikes
        if not gspikes:
            gspikes = self.gspikes
        img_counter = 0
        ts = sort(array([t for t in set(gspikes[:,0])])) # can use either spike set
        ts = ts[(ts > self.sim_start) * (ts < self.sim_end)]
        mqueue = []; gqueue = [];
        for t in ts[::sim_step]:
            self.t = t
            mlab.gcf().scene.disable_render=True
            timestamp = u"Time: %.1f" % (t)
            print timestamp
            if save_png:
                # Diplay time stamp
                f.name = timestamp
                try:ftitle.text = timestamp
                except:ftitle = mlab.title(timestamp)

            # Delete old spheres
            if len(mqueue) >= windowsize:
                mpts=mqueue.pop(0)
                mpts.parent.parent.remove()
                gpts=gqueue.pop(0)
                gpts.parent.parent.remove()

            # It would be great to make prevoius arrays dimmer

            # Plot activate spheres
            mqueue.append(self.plot_points(self.mx,
                                           self.my,
                                           self.mz,
                                           mspikes,
                                           t=t,
                                           color=(1., 1., 1.),
                                           csize = self.mcsize))
            gqueue.append(self.plot_points(self.gx,
                                           self.gy,
                                           self.gz,
                                           gspikes,
                                           t=t,
                                           color=(1., 1., 1.),
                                           csize = self.gcsize))
            mlab.view(view [0], view [1], view [2], view [3])
            mlab.gcf().scene.disable_render=False
            if save_png:
                f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter))
                img_counter += 1
        return mqueue, gqueue
Exemple #11
0
def viewGraph(g, sub=3,title=''):

    mlab.figure(bgcolor=(0, 0, 0), size=(900, 900))
    nodes = g.nodes()
    random.shuffle(nodes)
    nodes = np.array(nodes[0:100])
    #mlab.points3d(nodes[:,2],nodes[:,1],nodes[:,0],color=(0.0,0.0,1.0))
    edges = g.edges(data=True)
    print(len(edges))
    input('continue')
    count = 0
    for n1, n2, edge in edges:
        count += 1
        if( count % 100 == 0 ):
            print(count)
        path = [n1]+edge['path']+[n2]
        pa = np.array(path)
        #print pa
        mlab.plot3d(pa[::sub,2],pa[::sub,1],pa[::sub,0],color=(0,1,0),tube_radius=0.75)
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    mlab.title(title, height=0.1)
    
    mlab.show()
Exemple #12
0
    def play(self, fileroot='cell', show_colorbar=True, show_title=False):
        ''' Step through cell response over time '''
        dt = self.play_dt
        tstop = self.play_tstop
        nrn.init()
        nrn.cvode_active(0)
        img_counter=0
        f = mlab.gcf()
        if show_colorbar: mlab.colorbar(self.mlab_cell)
        nrn.initPlot()
        nrn.init()
        nrn.initPlot()
        nrn.init()
        for x in xrange(0, int(tstop/dt)):
            timestamp = "TIME: %.1f" % (x*dt)
            print timestamp
            if show_title:
                try:
                    ftitle.text = timestamp
                except:
                    ftitle = mlab.title(timestamp)
            nrn.continuerun(x*dt)

            dataset = self.mlab_cell.mlab_source.dataset
            v = array(self.calculate_voltage())
            dataset.point_data.remove_array('data')
            array_id = dataset.point_data.add_array(v.T.ravel())
            dataset.point_data.get_array(array_id).name = 'data'
            dataset.point_data.update()
            self.mlab_cell.update_data()
            self.mlab_cell.update_pipeline()

            if self.save_img:
                f.scene.save_png('img/%s_%03d.png' % (fileroot, img_counter))

            img_counter += 1
Exemple #13
0
cat1_extent = (-14,-6, -4,4, 0,5)
surf_cat1 = mlab.surf(x-10, y, cat1, colormap='Spectral', warp_scale=5, 
            extent=cat1_extent, vmin=-0.5, vmax=0.5)
mlab.outline(surf_cat1, color=(.7, .7, .7))
mlab.axes(surf_cat1, color=(.7, .7, .7), extent=cat1_extent, 
            ranges=(0,1, 0,1, 0,1), xlabel='', ylabel='',
            zlabel='Probability',
            x_axis_visibility=False, z_axis_visibility=False)

mlab.text(-18, -4, '1 photon', z=-4, width=0.13)

cat2_extent = (-4,4, -4,4, 0,5)
surf_cat2 = mlab.surf(x, y, cat2, colormap='Spectral', warp_scale=5, 
            extent=cat2_extent, vmin=-0.5, vmax=0.5)
mlab.outline(surf_cat2, color=(0.7, .7, .7), extent=cat2_extent)

mlab.text(-4, -3, '2 photons', z=-4, width=0.14)

cat3_extent = (6,14, -4,4, 0,5)
surf_cat3 = mlab.surf(x+10, y, cat3, colormap='Spectral', warp_scale=5, 
            extent=cat3_extent, vmin=-0.5, vmax=0.5)
mlab.outline(surf_cat3, color=(.7, .7, .7), extent=cat3_extent)

mlab.text(6, -2.5, '3 photons', z=-4, width=0.14)

mlab.title('Multi-photons cats Wigner function')

mlab.view(142, -72, 32)

mlab.show()
Exemple #14
0
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):
    picked = picker_obj.actors
    if mesh.actor.actor._vtk_obj in [o._vtk_obj for o in picked]:
Exemple #15
0
def mshplot3D(mesh, scale=[1, 1, 1], elm_ids=[], labels=[0, 0, 0]):
    ''' Plot 3D meshes (and optionally label vertices, elements, and edges)

    @param mesh A 3D mesh object

    @param elm_ids Numpy array of elements that will be plotted. If left empty,
                   all elements are plotted.

    @param labels (\c bool) List of three elements indicateting what should be
                           labeled. By default, nothing is labeled
                           labels[0]=True labels vertices
                           labels[1]=True labels elements
                           labels[2]=True labels edges

    @param scale (\c int) List indicating the scaling of the vertices -- this
                          is used to scale the z-direction for a thin mesh. By
                          default, there is no scaling, i.e. scale = [1, 1, 1]

    @see msh.mesh.Mesh3D

    @author Matt Ueckermann
    '''
    if type(elm_ids) is not int:
        if len(elm_ids) == 0:
            elm_ids = np.arange(len(mesh.elm))
    #Figure out how many vertices are in each element type
    n_vert_in_type = [len(int_el_pqr(element=element, dim=3)[0]) \
        for element in mesh.u_elm_type]

    #Now create the TVTK data-structures for the 'cells' and 'offsets'
    #cells give [#verts, vert1id, vert2id...,vertnid, #verts ...]
    #offsets gives the id's in the cells list where #verts are listed. So above
    # it is [0, n+1]
    cells = np.array([], dtype=int)
    offset = np.array([], dtype=int)
    for elm, elm_type in zip(mesh.elm[elm_ids, :], mesh.elm_type[elm_ids]):
        n_vt = n_vert_in_type[elm_type]
        offset = np.append(offset, len(cells))
        cells = np.append(cells, [n_vt] + elm[:n_vt].tolist())

    #Also have to create a list of element-types -- to do that we have to
    #convert from my numbering system to the TVTK numbering system
    if mesh.dim == 3:
        type_convert = np.array([tvtk.Tetra().cell_type,\
            tvtk.Hexahedron().cell_type, tvtk.Wedge().cell_type])
    elif mesh.dim == 2:
        type_convert = np.array([tvtk.Triangle().cell_type,\
            tvtk.Quad().cell_type])
    cell_types = mesh.u_elm_type[mesh.elm_type[elm_ids]]
    cell_types = type_convert[cell_types]

    #To help visualize the mesh, we color it be the distance from the origin
    if mesh.dim == 3:
        x, y, z = mesh.vert[:].T
    elif mesh.dim == 2:
        x, y = mesh.vert[:, :2].T
        z = np.zeros_like(x)
    dist = np.sqrt(x**2 + y**2 + z**2)
    #and we scale the x, y, z, coordinates according the the assigned 'scale'
    points = np.column_stack((x * scale[0], y * scale[1], z * scale[2]))

    #Now we create the data-structures
    cell_array = tvtk.CellArray()
    cell_array.set_cells(len(offset), cells)

    ug = tvtk.UnstructuredGrid(points=points)
    ug.set_cells(cell_types, offset, cell_array)
    ug.point_data.scalars = dist.ravel()
    ug.point_data.scalars.name = 'Distance from Origin'

    #Next we set the new data-structures as a mayavi source
    src = sources.vtk_data_source.VTKDataSource(data=ug)

    #Extract the edges from the grid
    edges = mlab.pipeline.extract_edges(src)

    #Use a shorter name for the elements
    elm = mesh.elm[elm_ids, :]

    if any(labels) and len(elm) > 20:
        string = "WARNING:\nAre you sure you want to label more than 20" + \
            "elements in 3D? -- Labels are very memory" + \
            "(apparently -- who would have guessed?) \nY(es) to proceed:"
        answer = raw_input(string)

        if answer.lower() not in ['yes', 'y', 'yes']:
            labels = [0, 0, 0]

    #Next add labels if desired:
    maxdist = np.max(dist) / 2.
    if labels[0]:  #Vertex labels
        for i in xrange(len(offset)):
            for vnum in elm[i, :]:
                if vnum >= 0:
                    mlab.text3d(points[vnum, 0], points[vnum, 1], \
                        points[vnum, 2], '%d' % vnum, \
                        color=(0, 0, 0), scale=0.02*maxdist)
    if labels[1]:  #element labels
        for i in xrange(len(offset)):
            if elm_ids[i] < 0:
                elm_label = mesh.numelm + elm_ids[i]
            else:
                elm_label = elm_ids[i]
            x = np.mean(points[elm[i, :cells[offset[i]]], 0])
            y = np.mean(points[elm[i, :cells[offset[i]]], 1])
            z = np.mean(points[elm[i, :cells[offset[i]]], 2])
            mlab.text3d(x, y, z, '%d' % elm_label, color=(0.3, 0.3, 0.9), \
                scale=0.03*maxdist)
    if labels[2]:  #edge labels
        if len(elm_ids) < len(mesh.elm):
            elm2ed = connect_elm2ed(mesh.elm2elm[:], mesh.ed2ed)
            ed_ids = np.unique(elm2ed[elm_ids])
            ed_ids = ed_ids[ed_ids >= 0]
            ed2ed = mesh.ed2ed[ed_ids, :]
        else:
            ed_ids = np.arange(len(mesh.ed2ed))
            ed2ed = mesh.ed2ed[:]

        for i in xrange(len(ed2ed)):
            n = 8
            if ed2ed[i, -1] < 0:
                n = 7
            x = np.mean(points[ed2ed[i, 4:n], 0])
            y = np.mean(points[ed2ed[i, 4:n], 1])
            z = np.mean(points[ed2ed[i, 4:n], 2])
            mlab.text3d(x, y, z, '%d' % ed_ids[i], color=(0.3, 0.9, 0.3), \
                scale=0.03*maxdist)

    #And plot them!
    mlab.pipeline.surface(edges, opacity=0.4, line_width=2)
    mlab.axes()
    mlab.title('3D mesh', size=0.5, height=0.95)
    #mlab.show()

    return cells, offset, cell_types
Exemple #16
0
x,y,z = Y.shape[:-1]


if (len(sys.argv)>=4):
    if sys.argv[3] == '-x':
        inp = raw_input("Enter the coordinates for the visualisation : '(x,y,z)' ")
        exec( '(xmax,ymax,zmax) = ' + inp)
else:
    imax = abs(Y[...,-1]).argmax()
    zmax = imax % z
    ymax = ( (imax - zmax) / z ) % y 
    xmax = (imax -y -z) / y / z
mlab.figure(size=(800,600))
p = mlab.pipeline.scalar_field(Y[...,i])
p.scene.background = (0.9,0.9,0.9)
titl=mlab.title(str("Potential at time: %.0f ms."% t[i]),size=0.5)
s = mlab.pipeline.image_plane_widget( p,
                            plane_orientation='x_axes',
                            slice_index=xmax,
                            vmin = -60,
                            vmax = 10
                        )

s2 = mlab.pipeline.image_plane_widget(p,
                            plane_orientation='y_axes',
                            slice_index=ymax,
                            vmin = -60,
                            vmax = 10
                        )
s3 = mlab.pipeline.image_plane_widget( p,
                            plane_orientation='z_axes',
Exemple #17
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
Exemple #18
0
def pattern_uv(
    array_ip,
    u_scan=0,
    v_scan=0,
    u_min=-1,
    u_max=1,
    u_num=50,
    v_min=-1,
    v_max=1,
    v_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 planar array in uv-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 u_scan, v_scan: beam scan position in uv-domain
    :param u_min, etc:     limits of uv-domain
    :param u_num, v_num:   number of points between 'u_min' and 'u_max' including 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 ... if False, nothing happens
    :param mayavi_app:     if True, the 3D plot will be opened in the MayaVi application
    
    :rtype:                A list, [u,v,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
    u_numj = complex(0, u_num)
    v_numj = complex(0, v_num)

    # Making sure all elements in the z-column of the "array_ip" are zeros
    z_flag = True
    if (abs(z) > 0).sum():
        print "All elements in the z-column of array input should be zero."
        z_flag = False

    # After making sure, proceed to the next level, i.e., evaluate the pattern
    if z_flag:

        [u, v] = np.mgrid[u_min:u_max:u_numj, v_min:v_max:v_numj]
        u1 = np.reshape(u, (u.size, -1))
        v1 = np.reshape(v, (v.size, -1))
        A = np.reshape(A, (len(A), -1))
        U = np.tile(u1 - u_scan, len(x))
        V = np.tile(v1 - v_scan, len(x))
        X = np.tile(x, (u.size, 1))
        Y = np.tile(y, (u.size, 1))

        # Evaluating array-factor of the planar array
        AF1 = np.dot(np.exp(1j * k * (U * X + V * Y)), 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 plot_type == "rect":  # rectangular plot
                if mayavi_app:  # opens the 3D plot in MayaVi Application
                    mlab.options.backend = "envisage"
                plt3d = mlab.surf(u, v, F_plt, warp_scale="auto")
                ranges1 = [u_min, u_max, v_min, v_max, F_plt.min(), F_plt.max()]
                mlab.axes(xlabel="u", ylabel="v", 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 == "contour":  # contour plot
                plt.contourf(u, v, F_plt)
                vs = plt.Circle((0, 0), radius=1, edgecolor="w", fill=False)
                ax = plt.gca()
                ax.add_patch(vs)
                plt.axis("image")
                plt.grid(True)
                plt.xlabel(
                    r"$u,\ \mathrm{where}\ u=\sin \theta \cos \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$",
                    fontsize=16,
                )
                plt.ylabel(
                    r"$v,\ \mathrm{where}\ v=\sin \theta \sin \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$",
                    fontsize=16,
                )
                plt.colorbar(format="$%.2f$")
                plt.show()
    return u, v, F
Exemple #19
0
def RunMayavi(directory):
    figure = mlab.figure(bgcolor=(.5, .5, .5))
    #figure.scene.disable_render = True
    #figure.scene.magnification = 5
    #figure.scene.off_screen_rendering = True

    ## Try to load the structure as wireframe
    if os.path.exists(os.path.join(directory, 'structure.vtk')):
        data_source = mlab.pipeline.open(
            os.path.join(directory, 'structure.vtk'))
        iso_surface = mlab.pipeline.iso_surface(data_source,
                                                color=(.8, .8, .8),
                                                contours=2,
                                                opacity=.3)
        iso_surface.actor.property.representation = 'wireframe'
        #iso_surface.actor.property.representation = 'surface'
        iso_surface.actor.property.line_width = .5
        #iso_surface.contour.minimum_contour = 2.
        iso_surface.name = 'Permittivity 3-D contours'

        surface = mlab.pipeline.surface(data_source,
                                        opacity=.3,
                                        colormap='Greys',
                                        vmin=1.0,
                                        vmax=10.)

        ## For black outline in 2-D view
        #surface.actor.property.specular_color = (0.0, 0.0, 0.0)
        #surface.actor.property.diffuse_color = (0.0, 0.0, 0.0)
        #surface.actor.property.ambient_color = (0.0, 0.0, 0.0)
        #surface.actor.property.color = (0.0, 0.0, 0.0)
        #surface.actor.property.representation = 'wireframe'

        surface.name = 'Permittivity surface'
        surface.visible = False

    mlab.orientation_axes(opacity=.5)
    mlab.title(os.path.basename(directory), size=.2, height=.01)

    ## Process each file
    filenames = [
        n for n in os.listdir(directory)
        if (n[-4:] == '.vtk' and not ('structure' in n) and (not 'slice' in n))
    ]
    filenames.sort()
    for (count, filename) in enumerate(filenames):
        ## Load the files
        data_source = mlab.pipeline.open(os.path.join(directory, filename))

        ## Plot electric field as the x-component scalar value (blue-white-red)
        if 'Evec' in filename:
            evs = mlab.pipeline.extract_vector_components(data_source)
            cutplane = mlab.pipeline.scalar_cut_plane(
                evs, plane_orientation='x_axes', colormap='RdBu')
            symmetric_colors(evs.children[0].scalar_lut_manager)
            cutplane.actor.mapper.interpolate_scalars_before_mapping = True
            cutplane.implicit_plane.widget.enabled = False
            cutplane.name = "Electric field x-component"

            ## Warp scalar
            cutplane.enable_warp_scalar = True
            cutplane.warp_scalar.filter.normal = np.array([1., 0., 0.])
            cutplane.warp_scalar.filter.scale_factor = 100.0

        ## Plot magnetic field as black vectors
        if 'Hvec' in filename:
            #cutplane = mlab.pipeline.vector_cut_plane(data_source,
            #plane_orientation='x_axes', mask_points=1, scale_factor=2, mode="cone", color=(0,0,0))
            cutplane = mlab.pipeline.vector_cut_plane(
                data_source,
                plane_orientation='x_axes',
                mask_points=1,
                scale_factor=2,
                mode="cone")
            cutplane.name = "Magnetic field"
            cutplane.implicit_plane.widget.enabled = False

        if count > 1:
            cutplane.visible = False  ## hide all snapshots except the first

    ## Set up the camera
    figure.scene.camera.clipping_range = [1, 1000]
    figure.scene.camera.focal_point = [10, 10, 30]

    # Y-Z view
    figure.scene.camera.position = [140, 10, 27]
    figure.scene.camera.focal_point = [10, 10, 27]
    figure.scene.camera.view_up = [0, -1, 0]

    # X-Z view
    #figure.scene.camera.position = [10, 140, 27]
    #figure.scene.camera.view_up = [1, 0, 0]
    #figure.scene.camera.compute_view_plane_normal()

    figure.scene.parallel_projection = True

    figure.scene.disable_render = False
    figure.scene.render()
    figure.scene.save(u'/home/filip/snapshot4.png')

    mlab.show()
[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
y = rp*np.sin(theta)*np.sin(phi)
y[np.isinf(y)] = np.nan
Exemple #21
0
def pattern_uv(array_ip, u_scan=0, v_scan=0, u_min= -1, u_max=1, u_num=50,
               v_min= -1, v_max=1, v_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 planar array in uv-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 u_scan, v_scan: beam scan position in uv-domain
    :param u_min, etc:     limits of uv-domain
    :param u_num, v_num:   number of points between 'u_min' and 'u_max' including 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 ... if False, nothing happens
    :param mayavi_app:     if True, the 3D plot will be opened in the MayaVi application
    
    :rtype:                A list, [u,v,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
    u_numj = complex(0, u_num)
    v_numj = complex(0, v_num)

    # Making sure all elements in the z-column of the "array_ip" are zeros
    z_flag = True
    if ((abs(z) > 0).sum()):
        print "All elements in the z-column of array input should be zero."
        z_flag = False

    # After making sure, proceed to the next level, i.e., evaluate the pattern
    if(z_flag):

        [u, v] = np.mgrid[u_min:u_max:u_numj, v_min:v_max:v_numj]
        u1 = np.reshape(u, (u.size, -1))
        v1 = np.reshape(v, (v.size, -1))
        A = np.reshape(A, (len(A), -1))
        U = np.tile(u1 - u_scan, len(x))
        V = np.tile(v1 - v_scan, len(x))
        X = np.tile(x, (u.size, 1))
        Y = np.tile(y, (u.size, 1))

        # Evaluating array-factor of the planar array
        AF1 = np.dot(np.exp(1j * k * (U * X + V * Y)), 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(plot_type == "rect"): # rectangular plot
                if (mayavi_app): # opens the 3D plot in MayaVi Application
                    mlab.options.backend = 'envisage'                
                plt3d = mlab.surf(u, v, F_plt, warp_scale='auto')
                ranges1 = [u_min, u_max, v_min, v_max, F_plt.min(), F_plt.max()]
                mlab.axes(xlabel='u', ylabel='v', 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 == "contour"): # contour plot
                plt.contourf(u, v, F_plt)
                vs = plt.Circle((0, 0), radius=1, edgecolor='w', fill=False)
                ax = plt.gca(); ax.add_patch(vs)                
                plt.axis('image'); plt.grid(True)
                plt.xlabel(r'$u,\ \mathrm{where}\ u=\sin \theta \cos \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$', fontsize=16)
                plt.ylabel(r'$v,\ \mathrm{where}\ v=\sin \theta \sin \phi\ \mathrm{in}\ \mathrm{the}\ \mathrm{visible-space}$', fontsize=16)
                plt.colorbar(format='$%.2f$')
                plt.show()                
    return u, v, F
Exemple #22
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
Exemple #23
0
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)

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

def picker_callback(picker_obj):
    picked = picker_obj.actors
Exemple #24
0
	if False:
		from enthought.mayavi import mlab
		fig1 = mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0),size=(800,800))
		#mlab.points3d(ph_a, th_a, r_a, s_a,opacity=0.1,scale_factor=3)#, color=(0,0,1))
		mlab.points3d(ph_r, th_r, r_r, s_r,opacity=0.3,scale_factor=2)#, color=(1,0,0))
		mlab.axes(ranges=[0.0, 90.0, 0.0, 90.0, 3.0, 9.0])
		#mlab.orientation_axes()
		mlab.xlabel("phi")
		mlab.ylabel("theta")
		mlab.zlabel("centroid\ndistance")
		#mlab.colorbar(nb_labels=2,nb_colors=2,label_fmt='')
		mlab.colorbar()
		#mlab.text(0.1,0.1,"attraction",color=(0,0,1),width=0.1)
		#mlab.text(0.8,0.1,"repulsion",color=(1,0,0),width=0.1)
		mlab.text(0.1,0.8,"%s-%s (n=%i; x=%i); (%s)"%(res1,res2,ndata,countNone,pdblistfile),width=0.8)
		mlab.title("Free Energy (%s,%s)"%(res1,res2),size=0.3,height=0.7,figure=fig1)
		viewdist = 120
		elevation = 60  # angle or 'rotate'
		azimuth = 180+45 # angle or 'rotate'
		mlab.view(distance=viewdist,elevation=elevation, azimuth=azimuth)
	
		mlab.savefig(pdblistfile+"_%s_%s_r_theta_phi.png"%(res1,res2))
	
		mlab.show()
	
		#sys.exit()
	##############
	
	for i in xrange(len(bins[0])):
		tmp = []
		for j in xrange(len(bins[1])):
Exemple #25
0

def picker_callback(picker):
    """ Picker callback: this get called when on pick events. 
    """
    if picker.actor in red_glyphs.actor.actors:
        # Find which data point corresponds to the point picked:
        # we have to account for the fact that each data point is
        # represented by a glyph with several points 
        point_id = picker.point_id/glyph_points.shape[0]
        # If the no points have been selected, we have '-1'
        if point_id != -1:
            # Retrieve the coordinnates coorresponding to that data
            # point
            x, y, z = x1[point_id], y1[point_id], z1[point_id]
            # Move the outline to the data point.
            outline.bounds = (x-0.1, x+0.1, 
                              y-0.1, y+0.1, 
                              z-0.1, z+0.1)


picker = figure.on_mouse_pick(picker_callback)

# Decrease the tolerance, so that we can more easily select a precise
# point.
picker.tolerance = 0.01

mlab.title('Click on red balls')

mlab.show()