Example #1
0
def run():
    dp = DatasetProcessor("L2_22aug.dat")
    #dp = DatasetProcessor("L2_22aug.pickle")
    dp.D -= dp.D.min()

    mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    mlab.clf()
    #dp.show_imgs()

    sigmas = [1.5, 3.0]
    sigmas2 = [0.0, 0.0]
    cms = ["bone", "Spectral"]
    for sigma, sigma2, cm in zip(sigmas, sigmas2, cms):
        gc.collect()
        if True:
            D = gaussian_filter(dp.D, sigma)
            l1, l2, l3 = get_ev(D, sigma2)
            save_lambdas([l1, l2, l3])
        else:
            l1, l2, l3 = load_lambdas()
        dp.S = select_struct(l1, l2, l3, 0.25, 0.5, 0.5)
        gc.collect()
        dp.S -= dp.S.min()
        dp.show_found(cm)
    plt.show()
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
File: plot.py Project: certik/phaml
def plot_sln_mayavi(x, y, mesh, sln_values, colorbar=False):
    """
    Plot a solution using mayavi.

    Example:

    >>> from numpy import array
    >>> from femhub.plot import plot_sln_mayavi
    >>> f = plot_sln_mayavi([0, 1, 1], [0, 0, 1], [1, 2, 3])
    >>> f.savefig("a.png")

    """
    from enthought.mayavi import mlab
    #mlab.options.offscreen = True
    mlab.clf()
    #mlab.options.show_scalar_bar = False
    z = [0] * len(x)
    mlab.triangular_mesh(x, y, z, mesh, scalars=sln_values)
    engine = mlab.get_engine()
    image = engine.current_scene
    image.scene.background = (1.0, 1.0, 1.0)
    image.scene.foreground = (0.0, 0.0, 0.0)
    if colorbar:
        mlab.colorbar(orientation="vertical")
    mlab.view(0, 0)
    return mlab
Example #4
0
def show_votegrid(vg, color=(1, 0, 0), opacity=1):
    from enthought.mayavi import mlab
    mlab.clf()
    x, y, z = np.nonzero(vg > 0)
    if not color is None:
        mlab.points3d(x,
                      y,
                      z,
                      opacity=opacity,
                      color=color,
                      scale_factor=1,
                      scale_mode='none',
                      mode='cube')
    else:
        mlab.points3d(x,
                      y,
                      z,
                      vg[vg > 0],
                      opacity=opacity,
                      scale_factor=1,
                      scale_mode='none',
                      mode='cube')

    gridmin, gridmax = config.bounds
    X, Y, Z = np.array(gridmax) - gridmin
    #mlab.axes(extent=[0,0,0,X,Y,Z])
    mlab.draw()
    def plot(self):
        "绘制场景"
        # 产生三维网格
        x, y, z = np.mgrid[
            self.x0 : self.x1 : 1j * self.points,
            self.y0 : self.y1 : 1j * self.points,
            self.z0 : self.z1 : 1j * self.points,
        ]

        # 根据函数计算标量场的值
        scalars = eval(self.function)
        mlab.clf()  # 清空当前场景

        # 绘制等值平面
        g = mlab.contour3d(x, y, z, scalars, contours=8, transparent=True)
        g.contour.auto_contours = self.autocontour
        mlab.axes()  # 添加坐标轴

        # 添加一个X-Y的切面
        s = mlab.pipeline.scalar_cut_plane(g)
        cutpoint = (self.x0 + self.x1) / 2, (self.y0 + self.y1) / 2, (self.z0 + self.z1) / 2
        s.implicit_plane.normal = (0, 0, 1)  # x cut
        s.implicit_plane.origin = cutpoint

        self.g = g
        self.scalars = scalars
        # 计算标量场的值的范围
        self.v0 = np.min(scalars)
        self.v1 = np.max(scalars)
    def plot(self):
        "绘制场景"
        # 产生三维网格
        x, y, z = np.mgrid[self.x0:self.x1:1j * self.points,
                           self.y0:self.y1:1j * self.points,
                           self.z0:self.z1:1j * self.points]

        # 根据函数计算标量场的值
        scalars = eval(self.function)
        mlab.clf()  # 清空当前场景

        # 绘制等值平面
        g = mlab.contour3d(x, y, z, scalars, contours=8, transparent=True)
        g.contour.auto_contours = self.autocontour
        mlab.axes()  # 添加坐标轴

        # 添加一个X-Y的切面
        s = mlab.pipeline.scalar_cut_plane(g)
        cutpoint = (self.x0 + self.x1) / 2, (self.y0 + self.y1) / 2, (
            self.z0 + self.z1) / 2
        s.implicit_plane.normal = (0, 0, 1)  # x cut
        s.implicit_plane.origin = cutpoint

        self.g = g
        self.scalars = scalars
        # 计算标量场的值的范围
        self.v0 = np.min(scalars)
        self.v1 = np.max(scalars)
Example #7
0
 def plot_orbits3d(self,xaxis='x',yaxis='y',clf=True,**kwargs):
     """
     Plots a 3D plot of the particles and their orbits with mayavi.
     
     :param bool clf: If True, clear figure before plotting.
     
     kwargs are passed into :func:`enthough.mayavi.mlab.plot3d`.
     
     :returns: 
         the result of :func:`enthough.mayavi.mlab.plot3d` and the result of
         :func:`enthough.mayavi.mlab.quiver3d`
     """
     from enthought.mayavi import mlab as M
     
     if clf:
         M.clf()
         
     orbarr = self.getOrbits()[1].transpose((1,2,0))
     t = self._orbt
     
     pntress = []
     for o in orbarr:
         pntress.append(M.plot3d(o[0],o[1],o[2],t,**kwargs))
     
     xp,yp,zp = self.particles.position.T
     vx,vy,vz = self.particles.velocity.T
     quiverres = M.quiver3d(xp,yp,zp,vx,vy,vz)
     
     return pntress,quiverres
Example #8
0
def run():
    dp = DatasetProcessor("L2_22aug.dat")
    #dp = DatasetProcessor("L2_22aug.pickle")
    dp.D -= dp.D.min()

    mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    mlab.clf()
    #dp.show_imgs()

    sigmas  = [1.5, 3.0]
    sigmas2 = [0.0, 0.0]
    cms     = ["bone", "Spectral"]
    for sigma, sigma2, cm in zip(sigmas,sigmas2,cms):
        gc.collect()
        if True:
            D = gaussian_filter(dp.D, sigma)
            l1,l2,l3 = get_ev(D, sigma2)
            save_lambdas([l1,l2,l3])
        else:
            l1,l2,l3 = load_lambdas()
        dp.S  = select_struct(l1,l2,l3,0.25,0.5,0.5)
        gc.collect()
        dp.S -= dp.S.min()
        dp.show_found(cm)
    plt.show()
Example #9
0
def evolve_visual3d(msnake, levelset=None, num_iters=20):
    """
    Visual evolution of a three-dimensional morphological snake.
    
    Parameters
    ----------
    msnake : MorphGAC or MorphACWE instance
        The morphological snake solver.
    levelset : array-like, optional
        If given, the levelset of the solver is initialized to this. If not
        given, the evolution will use the levelset already set in msnake.
    num_iters : int, optional
        The number of iterations.
    """
    from enthought.mayavi import mlab
    
    if levelset is not None:
        msnake.levelset = levelset
    
    fig = mlab.gcf()
    mlab.clf()
    src = mlab.pipeline.scalar_field(msnake.data)
    mlab.pipeline.image_plane_widget(src, plane_orientation='x_axes', colormap='gray')
    cnt = mlab.contour3d(msnake.levelset, contours=[0.5])
    
    for i in xrange(num_iters):
        msnake.step()
        cnt.mlab_source.scalars = msnake.levelset
    
    # Return the last levelset.
    return msnake.levelset
Example #10
0
 def showCell(self, number, firstFrame=True):
     """
     Show cell with label 'number', its surrounding, descendants, etc.
     The second argument specifies whether the given cell label corresponds to a cell
     from the first of the two time frames (default) or to a cell from the second frame
     """
     
     # set the bounding box of the volume to be displayed
     if firstFrame:
         bbox = self.file1["features"][str(number)]["bbox"][:]
     else:
         bbox = self.file2["features"][str(number)]["bbox"][:]
     bbox[0] = bbox[0] - min(self.borderSize, bbox[0]) # make sure that bbox[0] >= 0 (no array bound violation)
     bbox[1] = bbox[1] - min(self.borderSize, bbox[1])
     bbox[2] = bbox[2] - min(self.borderSize, bbox[2])
     bbox[3] = bbox[3] + min(self.borderSize, self.shape[2]-bbox[3]) # make sure that bbox[3] <= self.shape[0] (no array bound violation)
     bbox[4] = bbox[4] + min(self.borderSize, self.shape[1]-bbox[4])
     bbox[5] = bbox[5] + min(self.borderSize, self.shape[0]-bbox[5])
     if firstFrame:
         partner = self.findDescendent(number)
         number1 = number
         number2 = partner
         partnerStr = "descendent(s) "
     else:
         partner = self.findAncestor(number)
         number1 = partner
         number2 = number
         partnerStr = "ancestor "
     
     # load the data
     seg1 = self.file1["segmentation"]["labels"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
     seg2 = self.file2["segmentation"]["labels"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
     raw1 = self.file1["raw"]["volume"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
     raw2 = self.file2["raw"]["volume"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
     
     print "Drawing cell number ",number," and its ", partnerStr ,partner
     t0 = time.time()
     
     #draw everything
     fig1 = mlab.figure(1, size=(500,450))
     mlab.clf(fig1)
     self.drawImagePlane(fig1, raw1, 'gray')
     self.drawImagePlane(fig1, raw2, 'copper', 'y_axes')
     self.drawVolumeWithoutReferenceCell(fig1, seg1, number1, (0,0,1),0.2)
     self.drawVolumeWithoutReferenceCell(fig1, seg2, number2, (0.2,0,0.8),0.2)
     self.drawReferenceCell(fig1, seg1, number1, (0.5,1,0), 0.4)
     self.drawReferenceCell(fig1, seg2, number2, (0.8,0.8,0),0.3)
     self.drawArrows(fig1, bbox, number1, number2)
     if firstFrame:
         allneighbors = self.getNeighbors(seg1, number1)
         for i in allneighbors:
             p = self.findDescendent(i)
             self.drawArrows(fig1, bbox, i, p)
     else:
         allneighbors = self.getNeighbors(seg2, number2)
         for i in allneighbors:
             p = self.findAncestor(i)
             self.drawArrows(fig1, bbox, p, i)
     t = time.time() - t0
     print "Time for drawing:",t
Example #11
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 #12
0
def plotsln(mesh, z=None, sln=None, colorbar=False, view=(0,0),
        filename="a.png"):
    """
    Plot a solution for the mesh editor in the online lab.
    """
    x = [n[0] for n in mesh.nodes]
    y = [n[1] for n in mesh.nodes]
    if z == None:
        try:
            z = [n[2] for n in mesh.nodes]
        except IndexError:
            z = [0]*len(y)
    from enthought.mayavi import mlab
    mlab.options.offscreen = True
    mlab.clf()
    #mlab.options.show_scalar_bar = False
    mlab.triangular_mesh(x, y, z, mesh.elems, scalars=sln)
    engine = mlab.get_engine()
    image = engine.current_scene
    image.scene.background = (1.0, 1.0, 1.0)
    image.scene.foreground = (0.0, 0.0, 0.0)
    if colorbar:
        mlab.colorbar(orientation="vertical")
    if view:
        mlab.view(view[0], view[1])
    mlab.savefig(filename)
 def __call__(self, **options):
     my_options = dict(size=(400, 300), bgcolor=(1, 1, 1), 
                       fgcolor=(0, 0, 0), )
     my_options.update(options)
     mlab.figure(self.n, **my_options)
     mlab.clf()
     self.n += 1
Example #14
0
 def test_test_backend(self):
     """Test if setting the backend to 'test' works."""
     mlab.options.backend = 'test'
     mlab.test_contour3d()
     mlab.clf()
     mlab.pipeline.open(get_example_data('cube.vti'))
     mlab.clf()
Example #15
0
def evolve_visual3d(msnake, levelset=None, num_iters=20):
    """
    Visual evolution of a three-dimensional morphological snake.
    
    Parameters
    ----------
    msnake : MorphGAC or MorphACWE instance
        The morphological snake solver.
    levelset : array-like, optional
        If given, the levelset of the solver is initialized to this. If not
        given, the evolution will use the levelset already set in msnake.
    num_iters : int, optional
        The number of iterations.
    """
    from enthought.mayavi import mlab

    if levelset is not None:
        msnake.levelset = levelset

    fig = mlab.gcf()
    mlab.clf()
    src = mlab.pipeline.scalar_field(msnake.data)
    mlab.pipeline.image_plane_widget(src,
                                     plane_orientation='x_axes',
                                     colormap='gray')
    cnt = mlab.contour3d(msnake.levelset, contours=[0.5])

    for i in xrange(num_iters):
        msnake.step()
        cnt.mlab_source.scalars = msnake.levelset

    # Return the last levelset.
    return msnake.levelset
Example #16
0
def testVerticalSurface():
    import pylab, numpy
    pylab.clf()

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

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

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

    from enthought.mayavi import mlab
    mlab.clf()
    #from palos.yh_mayavi import customBarchart
    bar = customBarchart(x,
                         y,
                         enrichment_matrix,
                         x_scale=0.9,
                         y_scale=4.5,
                         opacity=1,
                         mode='cube',
                         color=(0, 1, 0),
                         scale_factor=1.0)
    """
	#mlab.ylabel("KW")
	#mlab.xlabel("Emma")
	#mlab.zlabel("Enrichment Ratio")
	from palos.DrawMatrix import get_font 
	font = get_font()
	
	for i in range(len(xlabel_ls)):
		label = xlabel_ls[i]
		char_width, char_height = font.getsize(label)	#W is the the biggest(widest)
		
		mlab.text(2*i, 0, label, z=0, width=char_width/1500.)	#min(0.0075*len(label), 0.04))
	
	"""
    s = numpy.zeros(x.shape, numpy.int)
    #s[0,1]=0.5
    surf = mlab.surf(x,
                     y,
                     s,
                     opacity=0.6,
                     extent=[-1, 2 * no_of_phenotypes, -1, 10, 0.0, 0.0])
    mlab.show()
Example #17
0
def do_mlab():
    ############################################################
    # run all the "test_foobar" functions in the mlab module.
    for name, func in getmembers(mlab):
        if not callable(func) or not name[:4] in ('test', 'Test'):
            continue
        mlab.clf()
        func()
Example #18
0
def do_mlab():
    ############################################################
    # run all the "test_foobar" functions in the mlab module.
    for name, func in getmembers(mlab):
        if not callable(func) or not name[:4] in ('test', 'Test'):
            continue
        mlab.clf()
        func()
Example #19
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 #20
0
def capture_image(func, filename):
    """ Runs a function doing some mayavi drawing and save the resulting
        scene to a file.
    """
    mlab.clf()
    func()
    if not filename[-4:] in ('.jpg', '.png'):
        filename = '%s.jpg' % filename
    mlab.savefig(filename, size=(400, 400))
    os.system('convert %s -trim %s' % (filename, filename))
Example #21
0
def capture_image(func, filename):
    """ Runs a function doing some mayavi drawing and save the resulting
        scene to a file.
    """
    mlab.clf()
    func()
    if not filename[-4:] in ('.jpg', '.png'):
        filename = '%s.jpg' % filename
    mlab.savefig(filename , size=(400, 400) )
    os.system('convert %s -trim %s' % (filename, filename))
Example #22
0
    def run(self):
        MayaviDaemon._viewers.append(self)
        
        mlab.clf()

        bounds = zeros((0, 6))
        
        self.cellsource = self.setup_source(self.cellfname)
        if self.cellsource is not None:
            tmp = [out.cell_data.scalars for out in self.cellsource.outputs \
                   if out.cell_data.scalars is not None]
            self.has_cell_scalars = (len(tmp) > 0)
            tmp = [out.cell_data.vectors for out in self.cellsource.outputs \
                   if out.cell_data.vectors is not None]
            self.has_cell_vectors = (len(tmp) > 0)
            tmp = [out.cell_data.tensors for out in self.cellsource.outputs \
                   if out.cell_data.tensors is not None]
            self.has_cell_tensors = (len(tmp) > 0)

            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.cellsource.outputs]),
                                 axis=0)


        self.facesource = self.setup_source(self.facefname)
        if self.facesource is not None:
            tmp = [out.point_data.scalars for out in self.facesource.outputs \
                   if out.point_data.scalars is not None]
            self.has_face_scalars = (len(tmp) > 0)
            tmp = [out.point_data.vectors for out in self.facesource.outputs \
                   if out.point_data.vectors is not None]
            self.has_face_vectors = (len(tmp) > 0)
            tmp = [out.point_data.tensors for out in self.facesource.outputs \
                   if out.point_data.tensors is not None]
            self.has_face_tensors = (len(tmp) > 0)
            
            bounds = concatenate((bounds, 
                                  [out.bounds for out in self.facesource.outputs]),
                                 axis=0)
                                 
        boundsmin = bounds.min(axis=0)
        boundsmax = bounds.max(axis=0)
        
        bounds = (boundsmin[0], boundsmax[1], 
                  boundsmin[2], boundsmax[3], 
                  boundsmin[4], boundsmax[5])

        self.bounds = where(self.bounds == array((None,)),
                            bounds, 
                            self.bounds).astype(float)

        self.view_data()

        # Poll the lock file.
        self.timer = Timer(1000 / self.fps, self.poll_file)
Example #23
0
def plotfield(ufunc):
    d = ufunc(x, y, z, t)
    print "field: min, max, mean, std = %g, %g, %g, %g" % (
            d.min(), d.max(), d.mean(), d.std() )
    print "lwall: min, max, mean, std = %g, %g, %g, %g" % (
            d[:,0,:].min(), d[:,0,:].max(), d[:,0,:].mean(), d[:,0,:].std() )
    print "uwall: min, max, mean, std = %g, %g, %g, %g" % (
            d[:,-1,:].min(), d[:,-1,:].max(), d[:,-1,:].mean(), d[:,-1,:].std() )
    mlab.clf()
    f = mlab.contour3d(x, y, z, d, transparent = True)
    return (d, f)
Example #24
0
def plotfield(ufunc):
    d = ufunc(x, y, z, t)
    print "field: min, max, mean, std = %g, %g, %g, %g" % (d.min(), d.max(),
                                                           d.mean(), d.std())
    print "lwall: min, max, mean, std = %g, %g, %g, %g" % (
        d[:, 0, :].min(), d[:, 0, :].max(), d[:, 0, :].mean(), d[:,
                                                                 0, :].std())
    print "uwall: min, max, mean, std = %g, %g, %g, %g" % (d[:, -1, :].min(
    ), d[:, -1, :].max(), d[:, -1, :].mean(), d[:, -1, :].std())
    mlab.clf()
    f = mlab.contour3d(x, y, z, d, transparent=True)
    return (d, f)
Example #25
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 #26
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 #27
0
def show_votegrid(vg, color=(1, 0, 0), opacity=1):
    from enthought.mayavi import mlab

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

    gridmin, gridmax = config.bounds
    X, Y, Z = np.array(gridmax) - gridmin
    # mlab.axes(extent=[0,0,0,X,Y,Z])
    mlab.draw()
	def _plotbutton1_fired(self):
		mlab.clf()
		self.loaddata()
		field=mlab.pipeline.scalar_field(self.sregion)     # Generate a scalar field
		mlab.pipeline.volume(field,vmax=self.datamax,vmin=self.datamin) # Render the field with dots

		mlab.outline()
		mlab.xlabel('RA(J2000)')
		mlab.ylabel('DEC(J2000)')
		mlab.zlabel('Velocity')
		mlab.view(azimuth=0, elevation=0)
		mlab.show()
		
		self.field   = field
Example #29
0
def render_vol(data, new_window = True):
    """ Renders simple volume data such as ROI """

    from enthought.mayavi import mlab
    import numpy as np
    
    if new_window:
        mlab.figure(1,fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
        mlab.clf()
        
    src = mlab.pipeline.scalar_field(data)
    src.image_data.update_data()
    
    volume = mlab.pipeline.contour(src)
    volume_surf = mlab.pipeline.surface(volume)
Example #30
0
    def save(self,it):

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

        mlab.clf()
        mlab.points3d(msh.x[:,0], msh.x[:,1], zeros(w.shape), w,
                      scale_factor=self.__scale, scale_mode=self.__mode)
        mlab.outline(extent=[msh.BB[0,0],msh.BB[1,0],msh.BB[0,1],msh.BB[1,1],
                     0,0])
        mlab.view(0,0,self.__zoom,self.__xView)
        mlab.colorbar()
        fSol =  ''.join([self.__figDir,'/',self.__name,'%04d.png'% it])
        #print fSol
        mlab.savefig(fSol)
Example #31
0
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)
Example #32
0
def run_mlab_file(filename, image_file):
    ## XXX: Monkey-patch mlab.show, so that we keep control of the 
    ## the mainloop
    old_show = mlab.show
    def my_show(func=None):
        pass
    mlab.show = my_show
    mlab.clf()
    e = mlab.get_engine()
    e.close_scene(mlab.gcf())
    execfile(filename, {'__name__': '__main__'})
    mlab.savefig(image_file)
    size = mlab.gcf().scene.get_size()
    for scene in e.scenes:
        e.close_scene(scene)
    mlab.show = old_show
	def _plotbutton2_fired(self):
		mlab.clf()
		self.loaddata()
		field=mlab.contour3d(self.sregion,colormap='gist_ncar')     # Generate a scalar field
		field.contour.maximum_contour = self.datamax
		field.contour.minimum_contour = self.datamin
		field.actor.property.opacity = self.opacity

		mlab.outline()
		mlab.xlabel('RA(J2000)')
		mlab.ylabel('DEC(J2000)')
		mlab.zlabel('Velocity')
		mlab.view(azimuth=0, elevation=0)
		mlab.show()

		self.field   = field
Example #34
0
def testVerticalSurface():
	import pylab, numpy
	pylab.clf()
	
	no_of_phenotypes = 5
	x, y = numpy.mgrid[0:2*no_of_phenotypes:1, 0:10:1]	#added a gap of 1 column between two phenotypes. one phenotype occupies two rows & two columns.
	
	
	#remove the gap in x & y
	needed_index_ls = [0,5]
	#for i in [0, 5]:
	#	for j in xrange(no_of_phenotypes):
	#		needed_index_ls.append(no_of_phenotypes*i+j)
	#for i in range(0, no_of_phenotypes):
	#	needed_index_ls.append(2*i)
		#needed_index_ls.append(3*i+1)
		#y[3*i+1][1]=2
	x = x[:, needed_index_ls]
	y = y[:, needed_index_ls]
	
	enrichment_matrix = numpy.ones(x.shape, numpy.float)
	enrichment_matrix[:,:] =10
	enrichment_matrix[0,0]=3
	
	from enthought.mayavi import mlab
	mlab.clf()
	from pymodule.yh_mayavi import customBarchart
	bar = customBarchart(x, y , enrichment_matrix, y_scale=4.5, opacity=1, mode='cube', color=(0,1,0), scale_factor=1.0, x_scale=0.9)
	"""
	#mlab.ylabel("KW")
	#mlab.xlabel("Emma")
	#mlab.zlabel("Enrichment Ratio")
	from pymodule.DrawMatrix import get_font 
	font = get_font()
	
	for i in range(len(xlabel_ls)):
		label = xlabel_ls[i]
		char_width, char_height = font.getsize(label)	#W is the the biggest(widest)
		
		mlab.text(2*i, 0, label, z=0, width=char_width/1500.)	#min(0.0075*len(label), 0.04))
	
	"""
	s = numpy.zeros(x.shape, numpy.int)
	#s[0,1]=0.5
	surf = mlab.surf(x, y, s, opacity=0.6, extent=[-1, 2*no_of_phenotypes, -1, 10, 0.0,0.0])
	mlab.show()
    def plot(self):
        """
        Visualize the current data volume with two perpendicular
        image plane widgets.
        """
        mlab.clf(figure=self.slices_scene.mayavi_scene)
        self.slices_scene.scene.background = (0, 0, 0)

        self.s = mlab.pipeline.scalar_field(\
            self.dataset[self.dataset.time].astype(np.float),
                    figure=self.slices_scene.mayavi_scene)
        self.ipw_x = mlab.pipeline.image_plane_widget(self.s,
                figure=self.slices_scene.mayavi_scene,
                plane_orientation = 'x_axes')
        self.ipw_y = mlab.pipeline.image_plane_widget(self.s,
                figure=self.slices_scene.mayavi_scene,
                plane_orientation = 'y_axes')
        self.ipw_x.parent.scalar_lut_manager.lut_mode = 'gist_gray'
Example #36
0
def make_3d_graph(scalarfield, filename):
    mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0))
    #mlab.options.offscreen = True
    #win = e.new_scene()
    #src = mlab.pipeline.scalar_scatter(Phi_graph)
    #e.add_source(src)
    #e.add_module(IsoSurface())
    #e.add_module(
    #win.scene.isometric_view()
    #win.scene.save(filename,size=(800,600))
    mlab.clf()
    mlab.contour3d(scalarfield,opacity=.5,transparent=True)#,contours=[1.0])
#    mlab.outline()
    mlab.zlabel('Z')
    mlab.xlabel('X')
    mlab.ylabel('Y')
    print 'saving %s' % filename
    mlab.savefig(filename)
Example #37
0
def run_mlab_file(filename, image_file):
    ## XXX: Monkey-patch mlab.show, so that we keep control of the
    ## the mainloop
    old_show = mlab.show

    def my_show(func=None):
        pass

    mlab.show = my_show
    mlab.clf()
    e = mlab.get_engine()
    e.close_scene(mlab.gcf())
    execfile(filename, {'__name__': '__main__'})
    mlab.savefig(image_file)
    size = mlab.gcf().scene.get_size()
    for scene in e.scenes:
        e.close_scene(scene)
    mlab.show = old_show
Example #38
0
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 = 100.
            #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 = 10.
            #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)
            if 0:
                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)

    #mlab.view(*V)
    t = frame.t
Example #39
0
def mcrtmv(frames, dt, Lx, Ly, Nx, Ny, savemovie=False, mvname='test'):
    x = np.linspace(0, Lx, Nx)
    y = np.linspace(0, Lx, Nx)
    X, Y = np.meshgrid(x, y)
    size = 500, 500

    fig = ml.figure(size=size, bgcolor=(1., 1., 1.))

    #fig.scene.anti_aliasing_frames=07

    #extent = [0,Nx-1,0,Ny-1,-30,30]

    ml.clf(figure=fig)
    u = np.loadtxt('data/solution_%06d.txt' % 1)

    fname = 'data/_tmp%07d.png' % 1
    s = ml.surf(x, y, u, figure=fig, vmin=-1, vmax=1)
    ml.axes(extent=[0, Lx, 0, Ly, -2, 2])
    ml.colorbar()
    ml.xlabel('x position')
    ml.ylabel('y position')
    ml.zlabel('wave amplitude')
    if savemovie == True:
        pl.ion()
        arr = ml.screenshot()
        img = pl.imshow(arr)
        pl.axis('off')

    for i in range(2, frames):

        u = np.loadtxt('data/solution_%06d.txt' % i)
        s.mlab_source.scalars = u
        fname = 'data/_tmp%07d.png' % i
        if savemovie == True:
            arr = ml.screenshot()
            img.set_array(arr)
            pl.savefig(filename=fname)  #,figure=fig)
            print 'Saving frame', fname
            pl.draw()

    fig.scene.disable_render = False
    os.system(
        "mencoder 'mf://data/_tmp*.png' -mf type=png:fps=20 -ovc lavc -lavcopts vcodec=wmv2 -oac copy -o %s.mpg"
        % mvname)
Example #40
0
    def plot3d(self,ix=0,iy=1,iz=2,clf=True):
        """
        Generates a 3-dimensional plot of the data set and principle components
        using mayavi.

        ix, iy, and iz specify which of the input p-dimensions to place on each of
        the x,y,z axes, respectively (0-indexed).
        """
        import enthought.mayavi.mlab as M
        if clf:
            M.clf()
        z3=np.zeros(3)
        v=(self.getEigenvectors()*self.getEigenvalues())
        M.quiver3d(z3,z3,z3,v[ix],v[iy],v[iz],scale_factor=5)
        M.points3d(self.N[:,ix],self.N[:,iy],self.N[:,iz],scale_factor=0.3)
        if self.names:
            M.axes(xlabel=self.names[ix]+'/sigma',ylabel=self.names[iy]+'/sigma',zlabel=self.names[iz]+'/sigma')
        else:
            M.axes()
Example #41
0
 def plot_velocities3d(self,clf=True,**kwargs):
     """
     Plots the particle velocities in a 3d projection with mayavi.
     
     :param bool clf: If True, clear figure before plotting.
         
     kwargs are passed into :func:`enthought.mayavi.mlab.quiver3d`.
     
     :returns: The result of the plotting command
     """
     from enthought.mayavi import mlab as M
     
     if clf:
         M.clf()
         
     args = list(self._pos.T)
     args.extend(list(self._vel.T))
     
     return M.quiver3d(*args,**kwargs)
Example #42
0
def plotframe(frameno):

    plotdata = ClawPlotData()
    plotdata.outdir = "_output"
    plotdata = setplot(plotdata)
    frame = plotdata.getframe(frameno)
    x = frame.grids[0].c_center[0]
    y = frame.grids[0].c_center[1]
    q = frame.grids[0].q
    eta = q[:,:,3]
    eta = where(q[:,:,0] > 1.,eta,nan)
    #import pdb; pdb.set_trace()

    mlab.figure(3,bgcolor=(1,1,1))
    mlab.clf()
    #plot_solid_sphere()
    plot_lat_long_lines()
    #x = 360 - x
    X,Y,Z = plot_eta(x,y,eta)
Example #43
0
def make_multiple_3d_graphs(data, filename):
    '''data is a list of 3d scalar fields. filename is a string, probably ending in .png'''
    mlab.figure(bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,600))

#    f = mlab.gcf()
#    camera = f.scene.camera
#    cam.parallel_scale = 9

#    view = mlab.view()
#    roll = mlab.roll()
#    print 'camera view is:',view
#    print 'camera roll is:',roll

    #mlab.options.offscreen = True
    #win = e.new_scene()
    #src = mlab.pipeline.scalar_scatter(Phi_graph)
    #e.add_source(src)
    #e.add_module(IsoSurface())
    #e.add_module(
    #win.scene.isometric_view()
    #win.scene.save(filename,size=(800,600))
    i=0
#    print 'mean is: ',data[i].mean()
#    print 'min is: ',data[i].min()
    for contourpercent in [.232,]:  # [.16, .20,.22,.232,.25,.28,.32,.36,.40,.44,.48,.52,.56,.60,.64,.68,.72]:
        mlab.clf()
#        contourpercent = .232 # .28, .24 is good
        value = (data[i].max()-data[i].min())*contourpercent+data[i].min()
        print 'graphing contours at',contourpercent,'of min-max distance, where value is ',value,'(versus a max of',data[i].max(),'and a min of',data[i].min(),', and a range of ',data[i].max()-data[i].min(),').'
    #    print 'graphing data[%i].shape='%i,data[i].shape
        mlab.contour3d(data[i],contours=[value],opacity=.36,transparent=True,colormap='bone')
        for i in range(1,len(data)):
    #        print data[i]
    #        print 'graphing data[%i].shape='%i,data[i].shape
            mlab.contour3d(data[i],contours=[(data[i].max()-data[i].min())*contourpercent+data[i].min()],opacity=.56,transparent=True)
    #    mlab.view(distance=36.0)
    #    mlab.outline()
    #    mlab.zlabel('Z')
    #    mlab.xlabel('X')
    #    mlab.ylabel('Y')
        tosave = filename + '%.03f'%contourpercent + '.png'
        print 'saving %s' % tosave
        mlab.savefig(tosave)
Example #44
0
    def do(self):
        ############################################################
        # Imports.
        from enthought.mayavi import mlab
              
        ############################################################
        # Create a new scene and set up the visualization.
        s = self.new_scene()

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

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

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

        # Test glyphs with number-only coordinnates
        mlab.points3d(0, 0, 0, resolution=50)
Example #45
0
 def plot_particles3d(self,clf=True,**kwargs):
     """
     Plots the particle locations in a 3d projection with mayavi.
     
     :param bool clf: If True, clear figure before plotting.
         
     kwargs are passed into :func:`enthought.mayavi.mlab.points3d`.
     
     :returns: The result of the plotting command
     """
     from enthought.mayavi import mlab as M
     
     if clf:
         M.clf()
         
     args = list(self._pos.T)
     args.append(self._mass)
     kwargs.setdefault('mode','point')
     
     return M.points3d(*args,**kwargs)
Example #46
0
def draw_atoms(at,
               colours=None,
               colorbar=None,
               atom_scale_factor=1.0,
               cell=True,
               origin=[0., 0., 0.],
               shift=[.5, .5, .5],
               supercell=[1, 1, 1],
               bonds=True,
               cutoff_factor=1.2,
               bond_radius=0.2,
               bond_colour=(.55, .55, .55),
               arrows=None,
               arrow_colour=(0, 0, 0),
               arrow_scale_factor=1.0,
               clf=True):

    if clf: mlab.clf()

    fig = mlab.gcf()
    fig.scene.disable_render = True

    balls = add_balls(at, colours, colorbar, atom_scale_factor)

    if cell:
        add_cell(at, balls, origin, shift, supercell)

    if bonds:
        add_bonds(at, balls, cutoff_factor, bond_radius, bond_colour)

    if arrows:
        arrows = add_arrows(at, arrows, arrow_colour, arrow_scale_factor)

    fig.scene.disable_render = False

    if arrows:
        return (balls, arrows)
    else:
        return balls
Example #47
0
def plot_sln_mayavi(sln, offscreen=False, show_scale=True):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    It takes the vertices from linearizer and interpolates them.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if offscreen:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)
    mlab.view(distance=4)
    mlab.view(focalpoint=(.35, 0, 0))
    mlab.colorbar(title="Solution", orientation="vertical")

    #mlab.move(right=-1.0, up=-10.0)
    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return mlab
Example #48
0
def plot_sln_mayavi(sln, notebook=False):
    """
    Plots the Solution() instance sln using Linearizer() and matplotlib.

    Currently only a very simple version is implemented, that takes the
    vertices from linearizer and interpolates them. More sophisticated version
    should take the triangles.
    """
    lin = Linearizer()
    lin.process_solution(sln)
    vert = lin.get_vertices()
    triangles = lin.get_triangles()
    from numpy import zeros
    from enthought.mayavi import mlab
    x = vert[:, 0]
    y = vert[:, 1]
    z = zeros(len(y))
    t = vert[:, 2]
    if notebook:
        # the off screen rendering properly works only with VTK-5.2 or above:
        mlab.options.offscreen = True
    mlab.clf()
    s = mlab.triangular_mesh(x, y, z, triangles, scalars=t)
    mlab.view(0, 0)

    # Below is a code that does exactly what the "View along the +Z axis"
    # button does:
    #scene = mlab.get_engine().current_scene.scene
    #scene.camera.focal_point = [0, 0, 0]
    #scene.camera.position = [0, 0, 1]
    #scene.camera.view_up = [0, 1, 0]
    #scene.renderer.reset_camera()
    #scene.render()
    # the above looks ok, but there is still quite a large margin, so we prefer
    # to just call .view(0, 0), which seems to be working fine.
    return s
Example #49
0
Y = X
Z = 1.5 * X

ext = [min(X), max(X), min(Y), max(Y), min(Z), max(Z)]

fig3d = mlab.figure(bgcolor=(1.0, 1.0, 1.0),
                    fgcolor=(0.0, 0.0, 0.0),
                    size=(1280, 1280))

angle = 1.0 * 25

for frame in range(len(fileh.root.Time[1:])):
    frame = frame_skip * frame
    # 3D Movie

    mlab.clf(figure=fig3d)
    #Simple contour
    scene = mlab.contour3d((fileh.root.Phi[2:-2, 2:-2, 2:-2, frame]**2),
                           contours=50,
                           extent=ext,
                           vmax=fmax,
                           vmin=fmin)  #, colormap='ylgn')

    # Cutplane
    #E  = gradient(fileh.root.Phi[:,:,:,frame])
    #mlab.quiver3d(E[0], E[1], E[2])
    #src = mlab.pipeline.vector_field(E[2], E[1], E[0])
    #mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.)
    #mlab.pipeline.vector_cut_plane(src, mask_points=1, scale_factor=5)
    #src = mlab.pipeline.vector_field(E[0], E[1], E[2])
    #magnitude = mlab.pipeline.extract_vector_norm(src)
"""
Use Mayavi to visualize the structure of a VolumeImg
"""

from enthought.mayavi import mlab
import numpy as np

x, y, z = np.mgrid[-5:5:64j, -5:5:64j, -5:5:64j]

data = x*x*0.5 + y*y + z*z*2.0

mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
mlab.clf()

src = mlab.pipeline.scalar_field(x, y, z, data)

mlab.pipeline.surface(src, opacity=0.4)

src2 = mlab.pipeline.scalar_field(x[::9, ::9, ::9],
                                  y[::9, ::9, ::9],
                                  z[::9, ::9, ::9],
                                  data[::9, ::9, ::9])
mlab.pipeline.surface(mlab.pipeline.extract_edges(src2), color=(0, 0, 0))
mlab.pipeline.glyph(src2, mode='cube', scale_factor=0.4, scale_mode='none')
mlab.savefig('viz_volume_structure.png')
mlab.show()


Example #51
0
def vector_movie_v0(timestamp,
                    tmin=50.0,
                    tmax=250.0,
                    nskip=100,
                    integrate=False,
                    showplot=False):

    from frc_data_class import FrcData, FrcDataOld

    from enthought.mayavi import mlab

    from enthought.mayavi.mlab import quiver3d, savefig, view, clf

    from scipy import arange, ndarray, array, zeros
    from scipy.integrate import cumtrapz

    import numpy

    filename = 'mag.x1.' + timestamp + '.csv'

    shot = FrcData(filename)

    if tmin > tmax:

        temp = tmin

        tmin = tmax

        tmax = temp

    imin = tmin * 1e-6 / shot.deltat

    imax = tmax * 1e-6 / shot.deltat

    n = imax - imin

    time = shot.timepoints[imin:imax]

    Bx = ndarray((16, n), float)

    By = ndarray((16, n), float)

    Bz = ndarray((16, n), float)

    Bdot = {}

    # for ch in arange(16):
    #
    #     for axis in ['x','y','z']:
    #
    #         filename = 'mag.'+axis+str(ch+1)+'.'+timestamp+'.csv'
    #
    #         shot = FrcData(filename)
    #
    #         dB = shot.voltage[imin:imax]*calfactor
    #
    #         Bdot[axis] = dB/numpy.max(abs(dB))
    #
    #
    #
    #     if integrate:
    #
    #         Bx[ch,1:] = cumtrapz(Bdot['x'],x=time)
    #
    #         By[ch,1:] = cumtrapz(Bdot['y'],x=time)
    #
    #         Bz[ch,1:] = cumtrapz(Bdot['z'],x=time)
    #
    #     else:
    #
    #         Bx[ch,:] = Bdot['x']
    #
    #         By[ch,:] = Bdot['y']
    #
    #         Bz[ch,:] = Bdot['z']

    modB = numpy.sqrt(Bx**2 + By**2 + Bz**2)

    Bmin = numpy.min(modB)

    Bmax = numpy.max(modB)

    modB = modB / Bmax

    x = zeros(16)

    y = zeros(16)

    z = arange(16)

    # if showplot:
    #     pass
    # else:
    #     #mlab.options.offscreen=True
    #     pass

    box = 0.5

    fig = quiver3d(x,
                   y,
                   z,
                   Bx[:, 0],
                   By[:, 0],
                   Bz[:, 0],
                   mode='arrow',
                   scale_mode='scalar',
                   resolution=20,
                   color=(0.1, 1.0, 0.1),
                   vmin=Bmin,
                   vmax=Bmax,
                   scalars=modB[:, 0],
                   scale_factor=0.9,
                   extent=(-box, box, -box, box, -9, 9))

    view(azimuth=0, elevation=90, distance=30)

    source = fig.mlab_source

    frames = range(int(round(n / nskip)))

    for j in frames:

        i = j * nskip

        source.set(u=Bx[:, i], v=By[:, i], w=Bz[:, i], scalars=modB[:, i])

        savefile = 'anim' + str(j) + '.png'

        #print 'Creating image '+str(j)
        #savefig(savefile)
    clf()
Example #52
0
def make_flash_bem(subject, subjects_dir, flash05, flash30, show=False):
    """Create 3-Layers BEM model from Flash MRI images

    Parameters
    ----------
    subject : string
        Subject name
    subjects_dir : string
        Directory containing subjects data (Freesurfer SUBJECTS_DIR)
    flash05 : string
        Full path of the NIFTI file for the
        FLASH sequence with a spin angle of 5 degrees
    flash30 : string
        Full path of the NIFTI file for the
        FLASH sequence with a spin angle of 30 degrees
    show : bool
        Show surfaces in 3D to visually inspect all three BEM
        surfaces (recommended)

    Notes
    -----
    This program assumes that both Freesurfer/FSL, and MNE,
    including MNE's Matlab Toolbox, are installed properly.
    For reference please read the MNE manual and wiki, and Freesurfer's wiki:
    http://www.nmr.mgh.harvard.edu/meg/manuals/
    http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/sofMNE.php
    http://www.nmr.mgh.harvard.edu/martinos/userInfo/data/MNE_register/index.php
    http://surfer.nmr.mgh.harvard.edu/
    http://surfer.nmr.mgh.harvard.edu/fswiki

    References:
    B. Fischl, D. H. Salat, A. J. van der Kouwe, N. Makris, F. Segonne,
    B. T. Quinn, and A. M. Dale, "Sequence-independent segmentation of magnetic
    resonance images," Neuroimage, vol. 23 Suppl 1, pp. S69-84, 2004.
    J. Jovicich, S. Czanner, D. Greve, E. Haley, A. van der Kouwe, R. Gollub,
    D. Kennedy, F. Schmitt, G. Brown, J. Macfall, B. Fischl, and A. Dale,
    "Reliability in multi-site structural MRI studies: effects of gradient
    non-linearity correction on phantom and human data," Neuroimage,
    vol. 30, Epp. 436-43, 2006.
    """
    os.environ['SUBJECT'] = subject
    os.chdir(os.path.join(subjects_dir, subject, "mri"))
    if not os.path.exists('flash'):
        os.mkdir("flash")
    os.chdir("flash")
    # flash_dir = os.getcwd()
    if not os.path.exists('parameter_maps'):
        os.mkdir("parameter_maps")
    print("--- Converting Flash 5")
    os.system('mri_convert -flip_angle %s -tr 25 %s mef05.mgz' %
                                            (5 * math.pi / 180, flash05))
    print("--- Converting Flash 30")
    os.system('mri_convert -flip_angle %s -tr 25 %s mef30.mgz' %
                                            (30 * math.pi / 180, flash30))
    print("--- Running mne_flash_bem")
    os.system('mne_flash_bem --noconvert')
    os.chdir(os.path.join(subjects_dir, subject, 'bem'))
    if not os.path.exists('flash'):
        os.mkdir("flash")
    os.chdir("flash")
    print("[done]")

    if show:
        fnames = ['outer_skin.surf', 'outer_skull.surf', 'inner_skull.surf']
        head_col = (0.95, 0.83, 0.83)  # light pink
        skull_col = (0.91, 0.89, 0.67)
        brain_col = (0.67, 0.89, 0.91)  # light blue
        colors = [head_col, skull_col, brain_col]
        from enthought.mayavi import mlab
        mlab.clf()
        for fname, c in zip(fnames, colors):
            points, faces = mne.read_surface(fname)
            mlab.triangular_mesh(points[:, 0], points[:, 1], points[:, 2], faces,
                                 color=c, opacity=0.3)
        mlab.show()
Example #53
0
def dense_reconstruction(S, P1, P2, H1, H2, region=None, step=1, imbw1=None):
    """
    Build and show a dense reconstruction.
    
    Parameters
    ----------
    S : ndarray
        Matrix of disparities.
    P1, P2 : ndarray
        Projection matrices of the stereo pair.
    H1, H2 : ndarray
        Homographies which rectify the images of the stereo
        pair. See projmat2rectify.
    region : array-like, optional
        Region of the matrix of disparities that will be used for
        the dense reconstruction. It must be expressed
        as [x_min, x_max, y_min, y_max].
        
        If not given, the full matrix of disparities is considered.
    step : integer, optional
        Quality of the reconstruction. Only one of every 'step' pixels
        inside the region of interest is taken for the reconstruction.
        
        If not given, all pixels are used.
    imbw1 : ndarray, optional
        The image before rectification. This is used to assign a color
        to the 3D vertices of the reconstruction. If not given, an arbitrary
        color is assigned to vertices.
        
        imbw1 should be a gray scale image.
    """
    if region is None:
        region = [0, S.shape[1], 0, S.shape[0]]

    # The matrix of disparities is smoothed.
    H = np.ones((3, 3)) / 9.0
    S = ndimage.convolve(np.double(S), H, mode='constant')

    # Point correspondences.
    X, Y = np.mgrid[region[0]:region[1] + 1:step, region[2]:region[3] + 1:step]
    num_points = np.prod(X.shape)
    points1 = np.ones((3, num_points))
    points1[0, :] = X.ravel()
    points1[1, :] = Y.ravel()
    X2 = X.ravel() + S[np.int32(points1[1, :]), np.int32(points1[0, :])]
    points2 = np.copy(points1)
    points2[0, :] = X2

    # Colors
    if imbw1 is not None:
        points1back = hom2cart(np.dot(la.inv(H1), points1))
        colors = ndimage.map_coordinates(imbw1,
                                         [points1back[1], points1back[0]],
                                         order=1)
    else:
        colors = None

    # Polygons.
    vlist = np.arange(0, num_points)
    vlist = vlist.reshape(X.shape)
    vlist1 = vlist[:-1, :-1]
    vlist2 = vlist[:-1, 1:]
    vlist3 = vlist[1:, 1:]
    vlist4 = vlist[1:, :-1]
    faces1 = np.array([vlist1.ravel(), vlist2.ravel(), vlist3.ravel()])
    faces2 = np.array([vlist1.ravel(), vlist3.ravel(), vlist4.ravel()])
    faces = matarray(faces1, faces2).T

    # Reconstruction.
    from stereo import reconstruct
    M = reconstruct(points1, points2, np.dot(H1, P1), np.dot(H2, P2))

    # Show the result.
    try:
        from enthought.mayavi import mlab
    except ImportError:
        from mayavi import mlab
    mlab.clf()
    mlab.triangular_mesh(M[0],
                         M[1],
                         M[2],
                         faces,
                         scalars=colors,
                         colormap='gray')

    return M, faces, colors
Example #54
0
    def showCell(self, number, firstFrame=True):
        """
        Show cell with label 'number', its surrounding, descendants, etc.
        The second argument specifies whether the given cell label corresponds to a cell
        from the first of the two time frames (default) or to a cell from the second frame
        """

        # set the bounding box of the volume to be displayed
        if firstFrame:
            bbox = self.file1["features"][str(number)]["bbox"][:]
        else:
            bbox = self.file2["features"][str(number)]["bbox"][:]
        bbox[0] = bbox[0] - min(
            self.borderSize,
            bbox[0])  # make sure that bbox[0] >= 0 (no array bound violation)
        bbox[1] = bbox[1] - min(self.borderSize, bbox[1])
        bbox[2] = bbox[2] - min(self.borderSize, bbox[2])
        bbox[3] = bbox[3] + min(
            self.borderSize, self.shape[2] - bbox[3]
        )  # make sure that bbox[3] <= self.shape[0] (no array bound violation)
        bbox[4] = bbox[4] + min(self.borderSize, self.shape[1] - bbox[4])
        bbox[5] = bbox[5] + min(self.borderSize, self.shape[0] - bbox[5])
        if firstFrame:
            partner = self.findDescendent(number)
            number1 = number
            number2 = partner
            partnerStr = "descendent(s) "
        else:
            partner = self.findAncestor(number)
            number1 = partner
            number2 = number
            partnerStr = "ancestor "

        # load the data
        seg1 = self.file1["segmentation"]["labels"][bbox[2]:bbox[5],
                                                    bbox[1]:bbox[4],
                                                    bbox[0]:bbox[3]]
        seg2 = self.file2["segmentation"]["labels"][bbox[2]:bbox[5],
                                                    bbox[1]:bbox[4],
                                                    bbox[0]:bbox[3]]
        raw1 = self.file1["raw"]["volume"][bbox[2]:bbox[5], bbox[1]:bbox[4],
                                           bbox[0]:bbox[3]]
        raw2 = self.file2["raw"]["volume"][bbox[2]:bbox[5], bbox[1]:bbox[4],
                                           bbox[0]:bbox[3]]

        print "Drawing cell number ", number, " and its ", partnerStr, partner
        t0 = time.time()

        #draw everything
        fig1 = mlab.figure(1, size=(500, 450))
        mlab.clf(fig1)
        self.drawImagePlane(fig1, raw1, 'gray')
        self.drawImagePlane(fig1, raw2, 'copper', 'y_axes')
        self.drawVolumeWithoutReferenceCell(fig1, seg1, number1, (0, 0, 1),
                                            0.2)
        self.drawVolumeWithoutReferenceCell(fig1, seg2, number2, (0.2, 0, 0.8),
                                            0.2)
        self.drawReferenceCell(fig1, seg1, number1, (0.5, 1, 0), 0.4)
        self.drawReferenceCell(fig1, seg2, number2, (0.8, 0.8, 0), 0.3)
        self.drawArrows(fig1, bbox, number1, number2)
        if firstFrame:
            allneighbors = self.getNeighbors(seg1, number1)
            for i in allneighbors:
                p = self.findDescendent(i)
                self.drawArrows(fig1, bbox, i, p)
        else:
            allneighbors = self.getNeighbors(seg2, number2)
            for i in allneighbors:
                p = self.findAncestor(i)
                self.drawArrows(fig1, bbox, p, i)
        t = time.time() - t0
        print "Time for drawing:", t
# -*- coding: utf-8 -*-
Example #56
0
def plot_3d_spectrum_mayavi(fs, fignum=None, vmin=None, vmax=None, 
                            pop_ids=None):
    """
    Logarithmic heatmap of single 3d FS.

    This method relies on MayaVi2's mlab interface. See http://code.enthought.com/projects/mayavi/docs/development/html/mayavi/mlab.html . To edit plot
    properties, click leftmost icon in the toolbar.

    If you get an ImportError upon calling this function, it is likely that you
    don't have mayavi installed.

    fs: FS to plot
    vmin: Values in fs below vmin are masked in plot.
    vmax: Values in fs above vmax saturate the color spectrum.
    fignum: Figure number to plot into. If None, a new figure will be created.
            Note that these are MayaVi figures, which are separate from
            matplotlib figures.
    pop_ids: If not None, override pop_ids stored in Spectrum.
    """
    from enthought.mayavi import mlab

    fig = mlab.figure(fignum, bgcolor=(1,1,1))
    mlab.clf(fig)

    if vmin is None:
        vmin = fs.min()
    if vmax is None:
        vmax = fs.max()

    # Which entries should I plot?
    toplot = numpy.logical_not(fs.mask)
    toplot = numpy.logical_and(toplot, fs.data >= vmin)

    # For the color mapping
    normalized = (numpy.log(fs)-numpy.log(vmin))\
            /(numpy.log(vmax)-numpy.log(vmin))
    normalized = numpy.minimum(normalized, 1)

    xs,ys,zs = numpy.indices(fs.shape)
    flat_xs = xs.flatten()
    flat_ys = ys.flatten()
    flat_zs = zs.flatten()
    flat_toplot = toplot.flatten()
    
    mlab.barchart(flat_xs[flat_toplot], flat_ys[flat_toplot], 
                  flat_zs[flat_toplot], normalized.flatten()[flat_toplot], 
                  colormap='hsv', scale_mode='none', lateral_scale=1, 
                  figure=fig)

    if pop_ids is None:
        if fs.pop_ids is not None:
            pop_ids = fs.pop_ids
        else:
            pop_ids = ['pop0','pop1','pop2']

    a = mlab.axes(xlabel=pop_ids[0],ylabel=pop_ids[1],zlabel=pop_ids[2], 
                  figure=fig, color=(0,0,0))
    a.axes.label_format = ""
    a.title_text_property.color = (0,0,0)
    mlab.text3d(fs.sample_sizes[0],fs.sample_sizes[1],fs.sample_sizes[2]+1, 
                '(%i,%i,%i)'%tuple(fs.sample_sizes), scale=0.75, figure=fig,
                color=(0,0,0))
    mlab.view(azimuth=-40, elevation=65, distance='auto', focalpoint='auto')

    mlab.show()
Example #57
0
fig1 = mlab.figure()
fig2 = mlab.figure()
#mlab.gcf().scene.y_plus_view()
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]