コード例 #1
0
ファイル: mayaviCTA.py プロジェクト: XiaoweiXu/vasctree
def viewImg(img, spacing, contours):
    mlab.figure(bgcolor=(0, 0, 0), size=(400, 400))
    
    src = mlab.pipeline.scalar_field(img)
    # Our data is not equally spaced in all directions:
    src.spacing = [1, 1, 1]
    src.update_image_data = True
    
    
    # Extract some inner structures: the ventricles and the inter-hemisphere
    # fibers. We define a volume of interest (VOI) that restricts the
    # iso-surfaces to the inner of the brain. We do this with the ExtractGrid
    # filter.
    blur = mlab.pipeline.user_defined(blur, filter='ImageGaussianSmooth')
    print("blur type is",type(blur),blur.max())
    #voi = mlab.pipeline.extract_grid(blur)
    #voi.set(x_min=125, x_max=193, y_min=92, y_max=125, z_min=34, z_max=75)
    
    #mlab.pipeline.iso_surface(src, contours=[1,2], colormap='Spectral')
    mlab.pipeline.contour3d(blur)
        
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    
    mlab.show()
コード例 #2
0
ファイル: shelf_contour.py プロジェクト: mandli/storm_surge
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)
コード例 #3
0
    def newSurface(self):
        processes = self.plotter.getProcesses()

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

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

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

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

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

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

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

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

        mlab.show()
コード例 #4
0
    def _plot_max_Value( self ):
        X = self.X_hf[:, 0]
        Y = self.Y_hf[:, 0]
        Z = self.Z_hf[:, 0]


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

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

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

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

        mlab.show
コード例 #5
0
def spin(fcm, idx0, idx1, idx2):
    """Plots 3D data as points in space."""
    x = fcm[:, idx0]
    y = fcm[:, idx1]
    z = fcm[:, idx2]

    s = trilinear_interpolate(x, y, z)

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

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

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

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

    mlab.figure()
    mlab.points3d(x, y, z, s, mode='point')
    mlab.xlabel(fcm.channels[idx0])
    mlab.ylabel(fcm.channels[idx1])
    mlab.zlabel(fcm.channels[idx2])
コード例 #6
0
ファイル: maps_3d.py プロジェクト: Garyfallidis/nipy
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
    """ Capture a screeshot of the Mayavi figure and display it in the
        matplotlib axes.
    """
    import pylab as pl

    # Late import to avoid triggering wx imports before needed.
    from enthought.mayavi import mlab

    if mayavi_fig is None:
        mayavi_fig = mlab.gcf()
    else:
        mlab.figure(mayavi_fig)
    if mpl_axes is not None:
        pl.axes(mpl_axes)

    filename = tempfile.mktemp(".png")
    mlab.savefig(filename, figure=mayavi_fig)
    image3d = pl.imread(filename)
    if autocrop:
        bg_color = mayavi_fig.scene.background
        image3d = autocrop_img(image3d, bg_color)
    pl.imshow(image3d)
    pl.axis("off")
    os.unlink(filename)
コード例 #7
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()
コード例 #8
0
ファイル: mayaviCTA.py プロジェクト: XiaoweiXu/vasctree
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()
コード例 #9
0
    def test_close(self):
        """ Various tests for mlab.close().
        """
        f = mlab.figure()
        self.assert_(f.running)
        mlab.close(f)
        self.assertFalse(f.running)

        f = mlab.figure(314)
        self.assert_(f.running)
        mlab.close(314)
        self.assertFalse(f.running)

        f = mlab.figure('test_figure')
        self.assert_(f.running)
        mlab.close('test_figure')
        self.assertFalse(f.running)

        f = mlab.figure()
        self.assert_(f.running)
        mlab.close()
        self.assertFalse(f.running)

        figs = [mlab.figure() for i in range(5)]
        for f in figs:
            self.assert_(f.running)
        mlab.close(all=True)
        for f in figs:
            self.assertFalse(f.running)
コード例 #10
0
def rotate():
    mlab.figure(3)
    for tt in linspace(30,160,14):
        mlab.view(0,tt)
        mlab.draw()
        mlab.savefig('sphere-rotate%s.png' % str(int(tt)).zfill(3))
    os.system("convert sphere-rotate*.png sphere.gif")
コード例 #11
0
    def test_close(self):
        """ Various tests for mlab.close().
        """
        f = mlab.figure()
        self.assert_(f.running)
        mlab.close(f)
        self.assertFalse(f.running)

        f = mlab.figure(314)
        self.assert_(f.running)
        mlab.close(314)
        self.assertFalse(f.running)

        f = mlab.figure('test_figure')
        self.assert_(f.running)
        mlab.close('test_figure')
        self.assertFalse(f.running)

        f = mlab.figure()
        self.assert_(f.running)
        mlab.close()
        self.assertFalse(f.running)

        figs = [mlab.figure() for i in range(5)]
        for f in figs:
            self.assert_(f.running)
        mlab.close(all=True)
        for f in figs:
            self.assertFalse(f.running)
コード例 #12
0
    def plotSurface(surface):
        """plot a surface using mayavi"""

        # create a figure
        mlab.figure()
        # create a surface plot
        surfPlot = mlab.mesh(surface['x'], surface['y'], surface['value'])
コード例 #13
0
 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
コード例 #14
0
ファイル: show.py プロジェクト: temporaer/wurzel
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()
コード例 #15
0
ファイル: mayaviCTA.py プロジェクト: XiaoweiXu/vasctree
def viewImg2(img, spacing, contours):
    print("In viewImg2: (min,max)=(%f,%f)"%(img.min(),img.max()))
    print("contours=",contours)
    mlab.figure(bgcolor=(0, 0, 0), size=(400, 400))
    
    src = mlab.pipeline.scalar_field(img)
    # Our data is not equally spaced in all directions:
    src.spacing = [1, 1, 1]
    src.update_image_data = True
    
    
    # Extract some inner structures: the ventricles and the inter-hemisphere
    # fibers. We define a volume of interest (VOI) that restricts the
    # iso-surfaces to the inner of the brain. We do this with the ExtractGrid
    # filter.
    blur = mlab.pipeline.user_defined(src, filter='ImageGaussianSmooth')
    #mlab.pipeline.volume(blur, vmin=0.2, vmax=0.8)
    mlab.pipeline.iso_surface(src, contours=contours)
    #mlab.pipeline.image_plane_widget(blur,
    #                            plane_orientation='z_axes',
    #                            slice_index=img.shape[0]/2,
    #                        )
    #voi = mlab.pipeline.extract_grid(blur)
    #voi.set(x_min=125, x_max=193, y_min=92, y_max=125, z_min=34, z_max=75)
    
    #mlab.pipeline.iso_surface(src, contours=[1,2], colormap='Spectral')
    #mlab.pipeline.contour3d(blur)
        
    mlab.view(-125, 54, 'auto','auto')
    mlab.roll(-175)
    
    mlab.show()
コード例 #16
0
 def plotSurface(surface):
   """plot a surface using mayavi"""
   
   # create a figure
   mlab.figure()
   # create a surface plot
   surfPlot = mlab.mesh(surface['x'], surface['y'], surface['value'])
コード例 #17
0
ファイル: demo.py プロジェクト: FOSSEE/workshops-more-scipy
def show_convection3(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)

    if new_fig:
        mlab.figure(fgcolor=(0., 0., 0.), bgcolor=(0.5, 0.5, 0.5),
                    size=(600,600))
    src = mlab.pipeline.vector_field(u, v, w)
    magnitude = mlab.pipeline.extract_vector_norm(src)
    mlab.outline()

    # We apply the following modules on the magnitude object, in order to
    # be able to display the norm of the vectors, eg as the color.
    iso = mlab.pipeline.iso_surface(magnitude, contours=[1.9, ], 
                                    opacity=0.3)

    vec = mlab.pipeline.vectors(magnitude, 
                                mask_points=40,
                                line_width=1,
                                color=(1, 1, 1),
                                scale_factor=4.)

    flow = mlab.pipeline.streamline(magnitude, 
                                    seedtype='plane',
                                    seed_visible=True,
                                    seed_scale=0.5,
                                    seed_resolution=1,
                                    linetype='ribbon',)

    vcp = mlab.pipeline.vector_cut_plane(magnitude, mask_points=2,
                                         scale_factor=4,
                                         colormap='jet',
                                         plane_orientation='x_axes')
コード例 #18
0
ファイル: experimental.py プロジェクト: whitews/fcm
def spin(fcm, idx0, idx1, idx2):
    """Plots 3D data as points in space."""
    x = fcm[:, idx0]
    y = fcm[:, idx1]
    z = fcm[:, idx2]

    s = trilinear_interpolate(x, y, z)

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

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

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

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

    mlab.figure()
    mlab.points3d(x, y, z, s, mode='point')
    mlab.xlabel(fcm.channels[idx0])
    mlab.ylabel(fcm.channels[idx1])
    mlab.zlabel(fcm.channels[idx2])
コード例 #19
0
ファイル: ChgPlot.py プロジェクト: nchisholm/DFTMiniProject1
def ChargeDensityFog3D(directory, save_file=None , DrawAtoms=True, DrawCell=True, opacity_range=[0,1]):
    # Get data from calculation files
    with jasp(directory) as calc:
        atoms = calc.get_atoms()
        x, y, z, cd = calc.get_charge_density()

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

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

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

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

    #Show a legend
    mlab.colorbar(title="e- density\n(e/Ang^3)", orientation="vertical", nb_labels=5, label_fmt='%.2f')
    mlab.view(azimuth=-90, elevation=90, distance='auto') # Set viewing angle
    mlab.show()
    if save_file != None:
        mlab.savefig(save_file)
コード例 #20
0
ファイル: demo.py プロジェクト: FOSSEE/workshops
def show_convection1(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)
    if new_fig:
        mlab.figure(size=(600, 600))

    mlab.quiver3d(u, v, w)
    mlab.outline()
コード例 #21
0
ファイル: view_3d.py プロジェクト: axelvonderheide/scratch
 def _show_button_fired( self ):
     p, r = self.data.slice
 
     
     
     mlab.figure( 'Continuous fibers' )
     mlab.plot3d( p[:, 0], p[:, 1], p[:, 2], r,
                  tube_radius=20, tube_sides=20, colormap='Spectral' ) 
コード例 #22
0
ファイル: demo.py プロジェクト: FOSSEE/workshops-more-scipy
def show_convection1(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)
    if new_fig:
        mlab.figure(size=(600,600))

    mlab.quiver3d(u, v, w)
    mlab.outline()
コード例 #23
0
ファイル: demo.py プロジェクト: FOSSEE/workshops-more-scipy
def show_convection2(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)
    if new_fig:
        mlab.figure(size=(600,600))

    src = mlab.pipeline.vector_field(u, v, w)
    mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.)
    mlab.outline()
コード例 #24
0
ファイル: demo.py プロジェクト: FOSSEE/workshops
def show_convection2(new_fig=True):
    x, y, z = np.mgrid[0:1:20j, 0:1:20j, 0:1:20j]
    u, v, w = convection_cell(x, y, z)
    if new_fig:
        mlab.figure(size=(600, 600))

    src = mlab.pipeline.vector_field(u, v, w)
    mlab.pipeline.vectors(src, mask_points=20, scale_factor=3.)
    mlab.outline()
コード例 #25
0
def main():
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 400))
    print "Generating the mlab images..."
    illustrate_module(mlab)
    mayavi2.close()
    print "Done generating the mlab images"
    print "Generating the example pages"
    from render_examples import render_examples
    render_examples(render_images=True)
    print "Done generating the example pages"
コード例 #26
0
ファイル: render_images.py プロジェクト: sjl421/code-2
def main():
    mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 400))
    print "Generating the mlab images..."
    illustrate_module(mlab)
    mayavi2.close()
    print "Done generating the mlab images"
    print "Generating the example pages"
    from render_examples import render_examples
    render_examples(render_images=True)
    print "Done generating the example pages"
コード例 #27
0
def plotThisThing(state, proc):
    react = sData.getInitReactant(state)
    prod = sData.getInitReactant(proc)
    #react, prod = sData.getReacProd(state,proc)
    cn = ChangingNeighbors(react, prod, cutoffs)


    ln = cn.nrValues(cn.lostNeighbors)
    indxs = np.where(ln > 0)
    ln = ln[indxs]
    pos = react.get_positions()[indxs]
    t = react.get_atomic_numbers()[indxs]
    pts = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],t,t,t,scalars=ln, mode='sphere')

    pts.glyph.color_mode = 'color_by_scalar'
    pts.glyph.glyph_source.glyph_source.center = [0,0,0]

    indx2 = np.setdiff1d(np.array(range(prod.get_number_of_atoms())),indxs[0])
    p = react.get_positions()[indx2]
    t2 = react.get_atomic_numbers()[indx2]
    pt = mlab.quiver3d(p[:,0],p[:,1],p[:,2],t2,t2,t2, opacity=.06, mode='sphere')
    
    mlab.figure()
    
    ln = cn.nrValues(cn.newNeighbors)
    indxs = np.where(ln > 0)
    ln = ln[indxs]
    pos = react.get_positions()[indxs]
    t = react.get_atomic_numbers()[indxs]
    pts = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],t,t,t,scalars=ln, mode='sphere')

    pts.glyph.color_mode = 'color_by_scalar'
    pts.glyph.glyph_source.glyph_source.center = [0,0,0]

    indx2 = np.setdiff1d(np.array(range(prod.get_number_of_atoms())),indxs[0])
    p = react.get_positions()[indx2]
    t2 = react.get_atomic_numbers()[indx2]
    pt = mlab.quiver3d(p[:,0],p[:,1],p[:,2],t2,t2,t2, opacity=.06, mode='sphere')
    
    mlab.figure()
    
    ln = cn.nrValues(cn.lostNeighbors) + cn.nrValues(cn.newNeighbors)
    indxs = np.where(ln > 0)
    ln = ln[indxs]
    pos = react.get_positions()[indxs]
    t = react.get_atomic_numbers()[indxs]
    pts = mlab.quiver3d(pos[:,0], pos[:,1], pos[:,2],t,t,t,scalars=ln, mode='sphere')

    pts.glyph.color_mode = 'color_by_scalar'
    pts.glyph.glyph_source.glyph_source.center = [0,0,0]

    indx2 = np.setdiff1d(np.array(range(prod.get_number_of_atoms())),indxs[0])
    p = react.get_positions()[indx2]
    t2 = react.get_atomic_numbers()[indx2]
    pt = mlab.quiver3d(p[:,0],p[:,1],p[:,2],t2,t2,t2, opacity=.06, mode='sphere')
コード例 #28
0
    def plotmask(self, region=None, resolution=20, slat=71, slon=-70, hemi="s"):
        """Plot the mask.
        """
        try:
            import enthought.mayavi.mlab as ml

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

            mayavi = False
            print "using matplotlib"

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

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

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

        print "plotting mask ..."
        if mayavi:
            ml.figure()
            ml.imshow(m_mask)
            ml.show()
        else:
            pl.figure()
            pl.imshow(m_mask, origin="lower", interpolation="nearest")
            pl.show()
        print "done!"
コード例 #29
0
ファイル: plot_mayavi.py プロジェクト: ANDESD/geoclaw-group
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)
コード例 #30
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)
コード例 #31
0
ファイル: zurich.py プロジェクト: tbetcke/PyPWDG
def plotsquare3d(us):
    from enthought.mayavi.mlab import surf, show, colorbar, xlabel, ylabel, figure
    for u in us:
        figure()
        Np = 60
        points = uniformsquarepoints(Np)
        x = points[:,0].reshape(Np,Np)
        y = points[:,1].reshape(Np,Np)
        up = np.real(u(points))
        surf(x,y, up.reshape(Np,Np))
        colorbar()
        xlabel('x')
        ylabel('y')
    show()
コード例 #32
0
    def plotmask(self, region=None, resolution=20, slat=71, slon=-70, hemi='s'):
        """Plot the mask.
        """
        try:
            import enthought.mayavi.mlab as ml 
            mayavi = True
            print 'using mayavi'
        except:
            import pylab as pl
            mayavi = False
            print 'using matplotlib'

        if self.maskfile is None:
            print 'error: plotmask: get mask file first:'
            print '>>> m = Mask()'
            print ">>> m.getmask('fname')"
            print 'then you can do:'
            print ">>> m.plotmask(region='left/right/bottom/top', resolution=20)"
            sys.exit()
     
        m_mask = self.m_mask
        x_mask = self.x_mask
        y_mask = self.y_mask
        
        if region is not None:
            left, right, bottom, top = str.split(region, '/')
            left, bottom = self.mapll(left, bottom, slat=slat, slon=slon, hemi=hemi)
            right, top = self.mapll(right, top, slat=slat, slon=slon, hemi=hemi)
            jmin, = np.where(x_mask == np.rint(left))
            jmax, = np.where(x_mask == np.rint(right))
            imin, = np.where(y_mask == np.rint(bottom))
            imax, = np.where(y_mask == np.rint(top))
            #x_mask = x_mask[jmin:jmax+1:resolution]
            #y_mask = y_mask[imin:imax+1:resolution]
            m_mask = m_mask[imin:imax+1:resolution, jmin:jmax+1:resolution]
        else:
            #x_mask = x_mask[::resolution]
            #y_mask = y_mask[::resolution]
            m_mask = m_mask[::resolution,::resolution]
        
        print 'plotting mask ...'
        if mayavi:
            ml.figure()
            ml.imshow(m_mask)
            ml.show()
        else:
            pl.figure()
            pl.imshow(m_mask, origin='lower', interpolation='nearest')
            pl.show()
        print 'done!'
コード例 #33
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)
コード例 #34
0
ファイル: experimental.py プロジェクト: whitews/fcm
def surface(fcm, idx0, idx1):
    """Plots a surface plot for 2D data."""
    x = fcm[:, idx0]
    y = fcm[:, idx1]
    bins = int(numpy.sqrt(len(x)))
    z, xedge, yedge = numpy.histogram2d(y, x, bins=[bins, bins],
                                        range=[(numpy.min(y), numpy.max(y)),
                                               (numpy.min(x), numpy.max(x))]
                                        )

    mlab.figure()
    mlab.surf(xedge, yedge, z, warp_scale='auto')
    mlab.xlabel(fcm.channels[idx0])
    mlab.ylabel(fcm.channels[idx1])
    mlab.zlabel('Density')
コード例 #35
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)
コード例 #36
0
ファイル: PCloud.py プロジェクト: DavidB-CMU/moped
    def show_3d(self):
        """SHOW_3D - Use mayavi2 to visualize point cloud.
        
        Usage: obj.show_3d()

        """

        from enthought.mayavi import mlab

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

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

        mlab.view(180, 180)
        mlab.show()
コード例 #37
0
    def __init__(self, objects, objectsOverlay, objectInputOverlay, outputdir):
        self.objects = objects
        self.objectsOverlay = objectsOverlay
        self.objectsInputOverlay = objectInputOverlay
        self.outputdir = outputdir
        self.counter = 0
        self.max_spread_x = 0
        self.max_spread_y = 0
        self.max_spread_z = 0
        for iobj in self.objects.values():
            spread_x = max(iobj[0]) - min(iobj[0])
            if self.max_spread_x < spread_x:
                self.max_spread_x = spread_x
            spread_y = max(iobj[1]) - min(iobj[1])
            if self.max_spread_y < spread_y:
                self.max_spread_y = spread_y
            spread_z = max(iobj[2]) - min(iobj[2])
            if self.max_spread_z < spread_z:
                self.max_spread_z = spread_z
        self.max_spread_x = self.max_spread_x / 2 + 10
        self.max_spread_y = self.max_spread_y / 2 + 10
        self.max_spread_z = self.max_spread_z / 2

        from enthought.mayavi import mlab
        # Returns the current scene.
        self.scene = mlab.figure(size=(2 * self.max_spread_x,
                                       2 * self.max_spread_y),
                                 bgcolor=(1., 1., 1.))

        self.engine = mlab.get_engine()
コード例 #38
0
def surface(fcm, idx0, idx1):
    """Plots a surface plot for 2D data."""
    x = fcm[:, idx0]
    y = fcm[:, idx1]
    bins = int(numpy.sqrt(len(x)))
    z, xedge, yedge = numpy.histogram2d(y,
                                        x,
                                        bins=[bins, bins],
                                        range=[(numpy.min(y), numpy.max(y)),
                                               (numpy.min(x), numpy.max(x))])

    mlab.figure()
    mlab.surf(xedge, yedge, z, warp_scale='auto')
    mlab.xlabel(fcm.channels[idx0])
    mlab.ylabel(fcm.channels[idx1])
    mlab.zlabel('Density')
コード例 #39
0
    def getData(self, data_D, data_H, name):
        """
        plot passed in data as a surface
        """

        #plotting
        fig = mlab.figure(size=(512, 512))

        cl.enqueue_read_buffer(lbm.queue, data_D, data_H).wait()

        # retrieve mid cell points from cell node data
        Nx = lbm.X.size - 1
        Ny = lbm.Y.size - 1
        x = np.zeros((Nx))
        y = np.zeros((Ny))

        for i in range(1, lbm.X.size):
            x[i - 1] = (lbm.X[i] - lbm.X[i - 1]) / 2.0 + lbm.X[i - 1]

        for i in range(1, lbm.Y.size):
            y[i - 1] = (lbm.Y[i] - lbm.Y[i - 1]) / 2.0 + lbm.Y[i - 1]

        s = mlab.surf(x, y, data_H, warp_scale='auto', colormap="jet")
        mlab.axes(s)
        sb = mlab.scalarbar(s, title=name)

        self.s = s
        self.data_D = data_D
        self.data_H = data_H
コード例 #40
0
    def animateVTKFiles_2D(folder):
        if not os.path.isdir(folder):
            return

        vtkFiles = []
        for f in sorted(os.listdir(folder)):
            if f.endswith(".vtk"):
                vtkFiles.append(os.path.join(folder, f))

        if len(vtkFiles) == 0:
            return

        figure = mlab.figure(size=(800, 600))
        figure.scene.disable_render = True
        vtkSource = VTKFileReader()
        vtk_file = vtkFiles[0]
        vtkSource.initialize(vtk_file)
        surface = mlab.pipeline.surface(vtkSource)
        axes = mlab.axes()
        colorbar = mlab.colorbar(object=surface, orientation='horizontal')
        mlab.view(0, 0)
        figure.scene.disable_render = False
        mlab.draw()

        a = animateVTKFiles(figure, vtkSource, vtkFiles)
コード例 #41
0
ファイル: denplot.py プロジェクト: ourobouros/WRed
def test_den():
    P = np.random.random((10,10))
    #P=np.load(r'c:\maxdenP.np.npy')
    #myfilestr=r'c:\structfactors_density.dat'
    #x,y,z=np.loadtxt(myfilestr).T
    #P=z.reshape((101,101))
    #print P.shape
    fig=mlab.figure()    
    x,y,z=gen_as()   
    #view along z-axis
    pts_as=mlab.points3d(x,y,z-.125,color=(1,0,0),colormap='gist_rainbow',figure=fig,scale_factor=.1)
    x,y,z=gen_fe()  
    print 'x',x
    print 'y',y
    print 'z',z
    pts_fe=mlab.points3d(x,y,z-.125,color=(0,1,0),colormap='gist_rainbow',figure=fig,scale_factor=.02)
    x,y,z=gen_sr()  
    pts_sr=mlab.points3d(x,y,z-.125,color=(0,0,1),colormap='gist_rainbow',figure=fig)
    outline=mlab.outline(figure=fig,extent=[0,1,0,1,-1,0])
    mlab.orientation_axes(figure=fig,xlabel='a',ylabel='b',zlabel='c')
    print 'shape',P.shape
    P = P[:,:, np.newaxis]
    print 'after',P.shape
    src = mlab.pipeline.scalar_field(P)
    #src = mlab.pipeline.array2d_source(P)
    surf = mlab.pipeline.surface(src,figure=fig,extent=[0,1,0,1,-1,0],name='surf2',opacity=0.4)
    #surf.transform.GetTransform().RotateX(90)
    print 'done'
コード例 #42
0
ファイル: training.py プロジェクト: JaimeIvanCervantes/hytra
 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
コード例 #43
0
    def __init__(self, stim_xml_filename=None, num_points=5, scale_factor=0.01, ghost_length=20, resolution=4):

        # initialize the viewer window
        self.f = mlab.figure(size=(800, 600))
        self.f.scene.anti_aliasing_frames = 1
        visual.set_viewer(self.f)

        ################# moving fly objects ################
        self.num_points = num_points
        self.plot_objects = [
            Object(ghost_length=ghost_length, scale_factor=scale_factor, resolution=resolution)
            for i in range(self.num_points)
        ]
        ######################################################

        self.objects = None
        self.speed = np.zeros(self.num_points)

        ################### stimulus xml #####################
        if stim_xml_filename is not None:
            actors = []
            stim_xml = xml_stimulus.xml_stimulus_from_filename(stim_xml_filename)
            actors.extend(stim_xml.get_tvtk_actors())
            for a in actors:
                visual.show_actor(a)
        ######################################################

        # ROS stuff
        rospy.Subscriber("flydra_mainbrain_super_packets", flydra_mainbrain_super_packet, self.callback)
        rospy.init_node("listener", anonymous=True)

        # run the animation
        self.animate()
コード例 #44
0
ファイル: VolProj.py プロジェクト: RuralCat/CLipPYME
    def __init__(self,channels, thresholds, pixelsize = (1., 1., 1.)):
        self.f = mlab.figure()

        self.isos = []
        self.projs = []

        for im, th, i in zip(channels, thresholds, range(len(channels))):
            c = mlab.contour3d(im, contours=[th], color = pylab.cm.gist_rainbow(float(i)/len(channels))[:3])
            c.mlab_source.dataset.spacing = pixelsize
            self.isos.append(c)

            ps = []
            thf = th*1.5

            pr = im.mean(2)
            #f = im.max()/pr.max()
            #pr *= im.max()/pr.max()
            ps.append(self.drawProjection((255*pylab.minimum(pr/(1.*thf), 1)).astype('uint8'), 'z', c))
            pr = im.mean(0)
            #pr *= im.max()/pr.max()
            ps.append(self.drawProjection((255*pylab.minimum(pr/(.6*thf), 1)).astype('uint8'), 'x', c))
            pr = im.mean(1)
            #pr *= im.max()/pr.max()
            ps.append(self.drawProjection((255*pylab.minimum(pr/(.8*thf), 1)).astype('uint8'), 'y', c))

            self.projs.append(ps)
コード例 #45
0
ファイル: magstruct_nd1kb.py プロジェクト: ourobouros/WRed
def draw_struct():
    fig = mlab.figure()
    r = gen_fe()
    s = gen_spins()
    #view along z-axis
    x = r[:, 0]
    y = r[:, 1]
    z = r[:, 2]
    u = s[:, 0]
    v = s[:, 1]
    w = s[:, 2]

    #print x.shape
    #print y.shape
    #print z.shape
    pts_as = mlab.points3d(x,
                           y,
                           z,
                           color=(0, 0, 1),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.1)
    mlab.quiver3d(x, y, z, u, v, w, line_width=3, scale_factor=.3, figure=fig)
    outline = mlab.outline(figure=fig, extent=[0, 1, 0, 1, 0, 1])
    mlab.orientation_axes(figure=fig, xlabel='a', ylabel='b', zlabel='c')
    print 'done'
 def CreateReducedModel(self,bandwidth=0.04,bandthresh=0.01,neighthresh=0.01,showdata=False,savefile=None):
     self.measurements,indices = self.Prune(self.rawmeasurements,100,neighthresh**2,1)
     uniformpoints,dists,pointscale = self.UniformlySampleSpace(bandwidth,bandthresh)
     if showdata:
         from enthought.mayavi import mlab
         mlab.figure(1,fgcolor=(0,0,0), bgcolor=(1,1,1))
         src = mlab.pipeline.scalar_field(dists)
         mlab.pipeline.iso_surface(src,contours=[0.01],opacity=0.1)
         mlab.pipeline.volume(mlab.pipeline.scalar_field(dists*500))
         v = pointscale[0]*self.trimesh.vertices+pointscale[1]
         mlab.triangular_mesh(v[:,0],v[:,1],v[:,2],self.trimesh.indices,color=(0,0,0.5))
     if savefile is None:
         savefile = self.getfilename()
     print 'saving measurements to %s'%savefile
     mkdir_recursive(os.path.split(savefile)[0])
     savetxt(savefile,uniformpoints,'%f')
コード例 #47
0
 def showVTKFile_2D(filename):
     figure = mlab.figure(size=(800, 600))
     vtkSource = VTKFileReader()
     vtkSource.initialize(filename)
     surface = mlab.pipeline.surface(vtkSource)
     axes = mlab.axes()
     colorbar = mlab.colorbar(object=surface, orientation='horizontal')
     mlab.view(0, 0)
     mlab.show()
コード例 #48
0
ファイル: bfo_3d.py プロジェクト: ourobouros/WRed
def test_den():
    #P = np.random.random((10,10))
    #P=np.load(r'c:\maxdenP.np.npy')
    #myfilestr=r'c:\structfactors_density.dat'
    #x,y,z=np.loadtxt(myfilestr).T
    #P=z.reshape((101,101))
    #print P.shape
    fig = mlab.figure(fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    x, y, z = np.array([[1, 0, 1], [0, -1, 1], [-1, 0, -1], [0, 1, -1],
                        [1, 1, 0], [-1, -1, 0]], 'float64').T
    #view along z-axis
    pts_as = mlab.points3d(x,
                           y,
                           z,
                           color=(1, 0, 0),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.3)
    #x,y,z=gen_fe()
    print 'x', x, x.shape
    print 'y', y, y.shape
    print 'z', z, z.shape
    x, y, z = np.array([
        [0, 1, 1],
        [0, -1, -1],
    ], 'float64').T
    pts_FE = mlab.points3d(x,
                           y,
                           z,
                           color=(0, 1, 0),
                           colormap='gist_rainbow',
                           figure=fig,
                           scale_factor=.3)
    mlab.text3d(0, 1, 1, '011', scale=.2, color=(1, 1, 0))
    mlab.text3d(1, 1, 0, '110', scale=.2)
    mlab.text3d(-1, -1, 0, '-1-10', scale=.2)
    mlab.text3d(1, 0, 1, '101', scale=.2)
    mlab.text3d(0, -1, 1, '0-11', scale=.2)
    mlab.text3d(-1, 0, -1, '-10-1', scale=.2)
    mlab.text3d(0, 1, -1, '01-1', scale=.2)

    #pts_fe=mlab.points3d(x,y,z-.125,color=(0,1,0),colormap='gist_rainbow',figure=fig,scale_factor=.02)
    #x,y,z=gen_sr()
    #print 'x',x,x.shape
    #pts_sr=mlab.points3d(x,y,z-.125,color=(0,0,1),colormap='gist_rainbow',figure=fig)
    #outline=mlab.outline(figure=fig,extent=[0,1,0,1,-1,0])
    outline = mlab.outline(figure=fig)
    mlab.orientation_axes(figure=fig, xlabel='a', ylabel='b', zlabel='c')
    #print 'shape',P.shape
    #P = P[:,:, np.newaxis]
    #print 'after',P.shape
    #src = mlab.pipeline.scalar_field(P)
    #src = mlab.pipeline.array2d_source(P)
    #surf = mlab.pipeline.surface(src,figure=fig,extent=[0,1,0,1,-1,0],name='surf2',opacity=0.4)
    #surf.transform.GetTransform().RotateX(90)
    print 'done'
コード例 #49
0
def disp_odf(sph_map, theta_res=64, phi_res=32, colormap='RGB', colors=256):

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

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

    nvox = np.prod(sph_map.shape)

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

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

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

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

            oo = mlab.mesh(x * odf_ii + x_cen.flat[ii],
                           y * odf_ii + y_cen.flat[ii],
                           z * odf_ii + z_cen.flat[ii],
                           scalars=np.int16(odf_im))
            oo.module_manager.scalar_lut_manager.lut.table = lut
        else:
            mlab.mesh(x * odf_ii + x_cen.flat[ii],
                      y * odf_ii + y_cen.flat[ii],
                      z * odf_ii + z_cen.flat[ii],
                      scalars=odf_ii,
                      colormap=colormap)
コード例 #50
0
def plot_connections(data_file, min, max, bins, params=None, output=''):

    print("Creating connection profile graphs.")

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

    # Ignore first line
    f.readline()

    data = []

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

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

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

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

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

    # Create and save various viewpoints of histogram figure

    mlab.axes(z_axis_visibility=False)

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

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

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

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

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

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

    mlab.colorbar(orientation="vertical")

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

    mlab.savefig(output + "above.eps", size=[600, 400])
コード例 #51
0
def view(dataset):
    """ Open up a mayavi scene and display the dataset in it.
    """
    fig = mlab.figure(bgcolor=(1, 1, 1),
                      fgcolor=(0, 0, 0),
                      figure=dataset.class_name[3:])
    surf = mlab.pipeline.surface(dataset, opacity=0.1)
    mlab.pipeline.surface(
        mlab.pipeline.extract_edges(surf),
        color=(0, 0, 0),
    )
コード例 #52
0
ファイル: demo.py プロジェクト: FOSSEE/workshops
def show_lorenz(new_fig=True):
    x, y, z = np.mgrid[-50:50:100j, -50:50:100j, -10:60:70j]
    u, v, w = lorenz(x, y, z)

    if new_fig:
        fig = mlab.figure(size=(600, 600), bgcolor=(0, 0, 0))

    # Plot the flow of trajectories with suitable parameters.
    f = mlab.flow(x, y, z, u, v, w, line_width=3, colormap='Paired')
    f.module_manager.scalar_lut_manager.reverse_lut = True
    f.stream_tracer.integration_direction = 'both'
    f.stream_tracer.maximum_propagation = 200
コード例 #53
0
    def On3DVolume(self, event):
        try:
            from enthought.mayavi import mlab
        except ImportError:
            from mayavi import mlab

        self.dsviewer.f3d = mlab.figure()
        self.dsviewer.f3d.scene.stereo = True

        for i in range(self.image.data.shape[3]):
            #c = mlab.contour3d(im.img, contours=[pylab.mean(ivp.clim)], color = pylab.cm.gist_rainbow(float(i)/len(self.images))[:3])
            v = mlab.pipeline.volume(mlab.pipeline.scalar_field(numpy.minimum(255*(self.image.data[:,:,:,i] -self.do.Offs[i])*self.do.Gains[i], 254).astype('uint8')))
コード例 #54
0
def feature_plot(unit,size,delta_xyz):
    '''
    A three dimensional plot the the voxilized feature. Does what spy_on but
    does a three dimensional plot rather then z slices.

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

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

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


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


    feature_size = shape(unit)
    mlab.figure(0)
    s = mlab.contour3d(xyz[0],xyz[1],xyz[2],dumbie_unit,opacity=.07,contours = 20)
    mlab.figure(1)
    t = mlab.contour3d(xyz[0],xyz[1],xyz[2]*10,dumbie_unit,opacity=.07,contours = 20)
    mlab.figure(2)
    u = mlab.contour3d(dumbie_unit,opacity=.05,contours = 20)
    mlab.show()
    return
コード例 #55
0
ファイル: plot.py プロジェクト: nbachela/hermes
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
コード例 #56
0
    def On3DIsosurf(self, event):
        try:
            from enthought.mayavi import mlab
        except ImportError:
            from mayavi import mlab

        self.dsviewer.f3d = mlab.figure()
        self.dsviewer.f3d.scene.stereo = True

        for i in range(self.image.data.shape[3]):
            c = mlab.contour3d(self.image.data[:,:,:,i].squeeze().astype('f'), contours=[self.do.Offs[i] + .5/self.do.Gains[i]], color = matplotlib.cm.gist_rainbow(float(i)/self.image.data.shape[3])[:3])
            self.lastSurf = c
            c.mlab_source.dataset.spacing = self.image.voxelsize