def animateGIF(filename, prices):
    '''Creates a mayavi visualization of a pd DataFrame containing stock prices
    Then uses MoviePy to animate and save as a gif
    Inputs:
    prices => a pd DataFrame, w/ index: dates; columns: company names
    '''
     #Imports mlab here to delay starting of mayavi engine until necessary
    from mayavi import mlab
    
    #Because of current mayavi requirements, replaces dates and company names with integers
    x_length, y_length = prices.shape
    xTime = np.array([list(xrange(x_length)),] * y_length).transpose()
    yCompanies = np.array([list(xrange(y_length)),] * x_length)
    
    #Sort indexed prices by total return on last date
    lastDatePrices = prices.iloc[-1]
    lastDatePrices.sort_values(inplace=True)
    sortOrder = lastDatePrices.index
    zPrices = prices[sortOrder]
    
    #Create mayavi2 object
    fig = mlab.figure(bgcolor=(.4,.4,.4))
    vis = mlab.surf(xTime, yCompanies, zPrices)
    mlab.outline(vis)
    mlab.orientation_axes(vis)
    mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price')
    
    animation = mpy.VideoClip(make_frame, duration = 4).resize(1.0)
    animation.write_gif(filename, fps=20)
    
Example #2
0
	def labels(self):
		'''
		Add 3d text to show the axes.
		'''
		fontsize = max(self.xrang, self.yrang)/40.
		tcolor = (1,1,1)
		mlab.text3d(self.xrang/2,-40,self.zrang+40,'R.A.',scale=fontsize,orient_to_camera=True,color=tcolor)
		mlab.text3d(-40,self.yrang/2,self.zrang+40,'Decl.',scale=fontsize,orient_to_camera=True,color=tcolor)
		mlab.text3d(-40,-40,self.zrang/2-10,'V (km/s)',scale=fontsize,orient_to_camera=True,color=tcolor)
		# Label the coordinates of the corners
		# Lower left corner
		ra0 = self.extent[0]; dec0 = self.extent[2]
		c = coord.ICRS(ra=ra0, dec=dec0, unit=(u.degree, u.degree))
		RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s'
		mlab.text3d(0,-20,self.zrang+20,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s'
		mlab.text3d(-80,0,self.zrang+20,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		# Upper right corner
		ra0 = self.extent[1]; dec0 = self.extent[3]
		c = coord.ICRS(ra=ra0, dec=dec0, unit=(u.degree, u.degree))
		RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s'
		mlab.text3d(self.xrang,-20,self.zrang+20,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s'
		mlab.text3d(-80,self.yrang,self.zrang+20,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		# V axis
		if self.extent[5] > self.extent[4]:
			v0 = self.extent[4]; v1 = self.extent[5]
		else:
			v0 = self.extent[5]; v1 = self.extent[4]
		mlab.text3d(-20,-20,self.zrang,str(round(v0,1)),scale=fontsize,orient_to_camera=True,color=tcolor)
		mlab.text3d(-20,-20,0,str(round(v1,1)),scale=fontsize,orient_to_camera=True,color=tcolor)

		mlab.axes(self.field, ranges=self.extent, x_axis_visibility=False, y_axis_visibility=False, z_axis_visibility=False)
		mlab.outline()
Example #3
0
def visualization3D_notimage(image3D):
    """
    :param image3D: image object from readDirWithBinaryDAta
    :return:
    """

    s=image3D
    src = mlab.pipeline.scalar_field(image3D)
    src.spacing=[1,1,5]
    src.update_image_data = (1,1,5)
    '''
    mlab.pipeline.image_plane_widget(src,
                                     plane_orientation='x_axes',
                                     slice_index=1,
                                    colormap='black-white'


    )
    mlab.pipeline.image_plane_widget(src,
                                     plane_orientation='z_axes',
                                     slice_index=1,
                                     colormap='black-white'


    )
    '''



    mlab.pipeline.iso_surface(src, contours=[0.5,1], opacity=1,colormap='black-white')

    mlab.outline()

    mlab.show()
Example #4
0
    def displayDensity(self, densityValues):
        self.numberOfElectrons(densityValues)
        source = mlab.pipeline.scalar_field(self.x, self.y, self.z, 
                                            densityValues)    
        densityPlot = mlab.pipeline.image_plane_widget(source,
                        colormap="hot",opacity = 1, transparent=True,                   
                        plane_orientation='x_axes',vmin = self.vmin,
                                vmax = self.vmax*0.01,
                        slice_index=20,)

        densityPlot = mlab.pipeline.image_plane_widget(source,
                    colormap="hot",  opacity = 1,transparent=True,vmin = self.vmin,
                                vmax = self.vmax*0.01,
                    plane_orientation='y_axes',
                    slice_index=20,)         
                    
        densityPlot = mlab.pipeline.image_plane_widget(source,
                colormap="hot",   opacity = 1, transparent=True, vmin = self.vmin,
                                vmax = self.vmax*0.01,                            
                plane_orientation='z_axes',
                slice_index=20,)    
                
        mlab.outline()
#        mlab.axes()
        
        return densityPlot.mlab_source 
Example #5
0
def main_plot3():
    __import__("matplotlib").rcParams.update({'axes.labelsize': 20,
                                              'axes.titlesize': 20})
    from pylab import plot, show, imshow, figure, colorbar, xlabel, ylabel
    from pylab import legend, title, savefig, close, grid
    from mpl_toolkits.mplot3d import axes3d
    import matplotlib.pyplot as plt
    from matplotlib import cm
    from mayavi import mlab

    names = ['res5.json', 'res24.json', 'res26.json', 'res28.json']
    ps = _load_jsons(names, 'ps')
    ns = _load_jsons(names, 'ns')
    print(len(ps[0]))

    T_fine = r_[0:len(ps) - 1]
    N_fine = r_[:101]
    T_fine, N_fine = np.meshgrid(T_fine, N_fine)

    P_all = array([(array(p[:len(p) // 2]) + p[len(p) // 2:]) for p in ps])
    P_fine = P_all[T_fine, N_fine]
    surf = mlab.mesh(N_fine / (len(N_fine) - 1), P_fine, T_fine / (len(ps) - 1),
                     colormap='blue-red')
    surf.module_manager.scalar_lut_manager.reverse_lut = True

    ax = mlab.axes(xlabel='State (n)', ylabel="Population", zlabel="Time",
                   nb_labels=6, extent=[0, 1, 0, 1, 0, 1],
                   ranges=[0, len(N_fine) - 1, 0, 1, 0, 1])
    ax.label_text_property.font_size = 5

    mlab.outline(surf, color=(.7, .7, .7),
                 extent=[0, 1, 0, 1, 0, 1])
    mlab.show()
Example #6
0
 def plot_3D( self ):
     x = self.compute3D_plot[0]
     y = self.compute3D_plot[1]
     z = self.compute3D_plot[2]
     # print x_axis, y_axis, z_axis
     if self.autowarp_bool:
         x = x / x[-1]
         y = y / y[-1]
         z = z / z[-1] * self.z_scale
     mlab.surf( x, y , z, representation = 'wireframe' )
     engine = Engine()
     engine.start()
     if len( engine.scenes ) == 75.5:
         engine.new_scene()
         surface = engine.scenes[0].children[0].children[0].children[0].children[0].children[0]
         surface.actor.mapper.scalar_range = np.array( [ 6.97602671, 8.8533387 ] )
         surface.actor.mapper.scalar_visibility = False
         scene = engine.scenes[0]
         scene.scene.background = ( 1.0, 1.0, 1.0 )
         surface.actor.property.specular_color = ( 0.0, 0.0, 0.0 )
         surface.actor.property.diffuse_color = ( 0.0, 0.0, 0.0 )
         surface.actor.property.ambient_color = ( 0.0, 0.0, 0.0 )
         surface.actor.property.color = ( 0.0, 0.0, 0.0 )
         surface.actor.property.line_width = 1.
         scene.scene.isometric_view()
         mlab.xlabel( self.x_name3D )
         mlab.ylabel( self.y_name3D )
     mlab.outline()
     mlab.show()
Example #7
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
def plot3D(name, X, Y, Z, zlabel):
    """
    Plots a 3d surface plot of Z using the mayavi mlab.mesh function.

    Parameters
    ----------
    name: string
        The name of the figure.
    X: 2d ndarray
        The x-axis data.
    Y: 2d ndarray
        The y-axis data.
    Z: 2d nd array
        The z-axis data.
    zlabel: The title that appears on the z-axis.
    """
    mlab.figure(name)
    mlab.clf()
    plotData = mlab.mesh(X/(np.max(X) - np.min(X)),
                         Y/(np.max(Y) - np.min(Y)),
                         Z/(np.max(Z) - np.min(Z)))
    mlab.outline(plotData)
    mlab.axes(plotData, ranges=[np.min(X), np.max(X),
                                np.min(Y), np.max(Y),
                                np.min(Z), np.max(Z)])
    mlab.xlabel('Space ($x$)')
    mlab.ylabel('Time ($t$)')
    mlab.zlabel(zlabel)
Example #9
0
def animateGIF(filename, prices):
    '''Creates a mayavi visualization of a pd DataFrame containing stock prices
    Then uses MoviePy to animate and save as a gif
    Inputs:
    prices => a pd DataFrame, w/ index: dates; columns: company names
    '''
    #Because of mayavi requirements, replace dates and company names with integers
    #until workaround is figured out
    x_length, y_length = prices.shape
    xTime = np.array([list(xrange(x_length)),] * y_length).transpose()
    yCompanies = np.array([list(xrange(y_length)),] * x_length)
    
    #Sort indexed prices by total return on last date
    lastDatePrices = prices.iloc[-1]
    lastDatePrices.sort_values(inplace=True)
    sortOrder = lastDatePrices.index
    zPrices = prices[sortOrder]
    
    
    #Create mayavi2 object
    dims = xTime.shape
    fig = mlab.figure(bgcolor=(.4,.4,.4))
    vis = mlab.surf(xTime, yCompanies, zPrices)
    mlab.outline(vis)
    mlab.orientation_axes(vis)
    mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price')
    
#    duration = 2 #Duration of the animation in seconds (will loop)
    
    animation = mpy.VideoClip(make_frame, duration = 4).resize(1.0)
#    animation.write_videofile('prototype_animation.mp4', fps=20)
    animation.write_gif(filename, fps=20)
Example #10
0
def visualizePrices(prices):
    '''Creates a mayavi visualization of a pd DataFrame containing stock prices
    Inputs:
    prices => a pd DataFrame, w/ index: dates; columns: company names
    '''
    #Imports mlab here to delay starting of mayavi engine until necessary
    from mayavi import mlab
    
    #Because of current mayavi requirements, replaces dates and company names with integers
    x_length, y_length = prices.shape
    xTime = np.array([list(xrange(x_length)),] * y_length).transpose()
    yCompanies = np.array([list(xrange(y_length)),] * x_length)
    
    #Sort indexed prices by total return on last date
    lastDatePrices = prices.iloc[-1]
    lastDatePrices.sort_values(inplace=True)
    sortOrder = lastDatePrices.index
    zPrices = prices[sortOrder]
    
    #Create mayavi2 object
    fig = mlab.figure(bgcolor=(.4,.4,.4))
    vis = mlab.surf(xTime, yCompanies, zPrices)
    mlab.outline(vis)
    mlab.orientation_axes(vis)
    #mlab.title('S&P 500 Market Data Visualization', size = .25)
    mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price')
    
    mlab.show()
Example #11
0
def etsIntro():
    x, y = np.ogrid[-2:2:20j, -2:2:20j]
    z = x * np.exp( - x**2 - y**2)
    
    pl = mlab.surf(x, y, z, warp_scale="auto")
    mlab.axes(xlabel='x', ylabel='y', zlabel='z')
    mlab.outline(pl)
Example #12
0
def PlotHorizon3d(tss):
    """
    Plot a list of horizons.

    Parameters
    ----------

    tss : list of trappedsurface
        All the trapped surfaces to visualize.
    """
    from mayavi import mlab
    cmaps = ['bone', 'jet', 'hot', 'cool', 'spring', 'summer', 'winter']
    assert len(cmaps) > len(tss)
    extents = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
    for ts, cm in zip(tss, cmaps):
        mlab.mesh(ts.X, ts.Y, ts.Z, colormap=cm, opacity=0.4)
        extents[0] = min(extents[0], np.min(ts.X))
        extents[1] = max(extents[1], np.max(ts.X))
        extents[2] = min(extents[2], np.min(ts.Y))
        extents[3] = max(extents[3], np.max(ts.Y))
        extents[4] = min(extents[4], np.min(ts.Z))
        extents[5] = max(extents[5], np.max(ts.Z))
    mlab.axes(extent=extents)
    mlab.outline(extent=extents)
    mlab.show()
Example #13
0
        def _showSimple():
            max_interpol_pts = 10

            def interpolate_section(section):
                sec_start = section.get_distal_npa4()
                sec_end = section.get_proximal_npa4()
                length = section.get_length()
                rad = min(section.d_r, section.p_r)
                n = min(max(int(lToRRatio * length / rad), 1), max_interpol_pts)
                j_vec_steps = (sec_end - sec_start) / n

                int_pts = [sec_start + k * j_vec_steps for k in range(0, n)]
                return int_pts

            lbs = []
            for morph in self.morphs:
                lb = SeqUtils.flatten(ListBuilderSectionVisitor(functor=interpolate_section,  morph=morph) ())
                lbs.extend(lb)

            pts = numpy.array(lbs)

            x = pts[:, 0]
            y = pts[:, 1]
            z = pts[:, 2]
            s = pts[:, 3]

            mlab.points3d(x, y, z, s, colormap=self.colormap, scale_factor=self.scale_factor)
            mlab.outline()
Example #14
0
 def showContour(self):
     """
     Display real space model using contour
     """
     mlab.contour3d(self.array, contours=8, opacity=0.3, transparent=True)
     mlab.outline()
     mlab.show()
Example #15
0
    def plot_potential_cartesian(self, fig=None, x=None, y=None, z=None):
        if not self.USE_MAYAVI:
            return None
        if fig is None:
            fig = mlab.figure('Potential')#, bgcolor=(0, 0, 0))
            #fig = mlab.figure('Potential', bgcolor=(0, 0, 0))
        else:
            mlab.figure(fig, bgcolor=fig.scene.background)

        if x is None:
            x = np.linspace(1e-9, 5e-8, num=100, endpoint=True)
        if y is None:
            y = np.linspace(1e-9, 5e-8, num=100, endpoint=True)
        if z is None:
            z = np.linspace(1e-9, 5e-8, num=100, endpoint=True)
        x_grid, y_grid, z_grid = np.meshgrid(x, y, z)
        r_grid, theta_grid, phi_grid = Vectors3D.cartesian_to_spherical(x_grid, y_grid, z_grid)
        volumetric_data = self.potential_on_grid(r_grid, theta_grid, phi_grid)
        #volumetric_data = 1 / (x_grid**2 + y_grid**2 + z_grid**2)
        #mlab.contour3d(x_grid, y_grid, z_grid, volumetric_data, colormap='jet')
        #mlab.contour3d(volumetric_data, colormap='jet')

        source = mlab.pipeline.scalar_field(volumetric_data)
        min = volumetric_data.min()
        max = volumetric_data.max()
        vol = mlab.pipeline.volume(source)
        #vol = mlab.pipeline.volume(source, vmin=min + 0.65 * (max - min),
        #                           vmax=min + 0.9 * (max - min))


        mlab.outline()
        return fig
Example #16
0
        def _showSimple():
            maxInterpolPts = 10
            
            def interpolateSection(section):
                sStart = section.getDistalNPA4()
                sEnd = section.getProximalNPA4()
                length = section.getLength()
                rad = min(section.d_r, section.p_r)  
                n = min( max( int( lToRRatio * length / rad ), 1 ), maxInterpolPts)
                jVecSteps = ( sEnd-sStart ) / n
                
                intPts = [ sStart + k*jVecSteps for k in range(0,n) ]
                return intPts 
                
            lbs = []
            for morph in self.morphs:
                lb = Flatten( ListBuilderSectionVisitor(functor=interpolateSection,  morph=morph ) () ) 
                lbs.extend( lb )
                
            
            pts = numpy.array( lbs )

            x = pts[:, 0]
            y = pts[:, 1]
            z = pts[:, 2]
            s = pts[:, 3]
            
            mlab.points3d(x, y, z, s, colormap=self.colormap, scale_factor=self.scale_factor)
            mlab.outline()
Example #17
0
    def action(u, x, xv, y, yv, t, n):
        #print 'action, t=',t,'\nu=',u, '\Nx=',x, '\Ny=', y
        if plot == 1:
            mesh(xv, yv, u, title='t=%g' %t[n])
            time.sleep(0.2) # pause between frames

        elif plot == 2:
            # mayavi plotting
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u, colormap='Blues', warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
            ranges=(0, 10, 0, 10, -1, 1), xlabel='', ylabel='',
            zlabel='',
            x_axis_visibility=False, z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(2, -2.5, '', z=-4, width=0.1)
            mlab.colorbar(object=None, title=None, orientation='horizontal', nb_labels=None, nb_colors=None, label_fmt=None)
            mlab.title('test 1D t=%g' % t[n])

            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)
        
        
        if plot > 0:
            path = 'Figures_wave2D'
            time.sleep(0) # pause between frames
            if save_plot and plot != 2:
                filename = '%s/%08d.png' % (path, n)
                savefig(filename)  # time consuming!
            elif save_plot and plot == 2:
                filename = '%s/%08d.png' % (path,n)
                mlab.savefig(filename)  # time consuming!
Example #18
0
 def plot(self):
   """Plots the geometry using the package Mayavi."""
   print('\nPlot the three-dimensional geometry ...')
   from mayavi import mlab
   x_init = self.gather_coordinate('x', position='initial')
   y_init = self.gather_coordinate('y', position='initial')
   z_init = self.gather_coordinate('z', position='initial')
   x = self.gather_coordinate('x')
   y = self.gather_coordinate('y')
   z = self.gather_coordinate('z')
   figure = mlab.figure('body', size=(600, 600))
   figure.scene.disable_render = False
   same = (numpy.allclose(x, x_init, rtol=1.0E-06) and
           numpy.allclose(y, y_init, rtol=1.0E-06) and
           numpy.allclose(z, z_init, rtol=1.0E-06))
   if not same:
     mlab.points3d(x_init, y_init, z_init, name='initial',
                   scale_factor=0.01, color=(0, 0, 1))
   mlab.points3d(x, y, z, name='current',
                 scale_factor=0.01, color=(1, 0, 0))
   mlab.axes()
   mlab.orientation_axes()
   mlab.outline()
   figure.scene.disable_render = True
   mlab.show()
Example #19
0
 def plot_mayavi(self):
     """Use mayavi to plot a phenotype phase plane in 3D.
     The resulting figure will be quick to interact with in real time,
     but might be difficult to save as a vector figure.
     returns: mlab figure object"""
     from mayavi import mlab
     figure = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
     figure.name = "Phenotype Phase Plane"
     max = 10.0
     xmax = self.reaction1_fluxes.max()
     ymax = self.reaction2_fluxes.max()
     zmax = self.growth_rates.max()
     xgrid, ygrid = meshgrid(self.reaction1_fluxes, self.reaction2_fluxes)
     xgrid = xgrid.transpose()
     ygrid = ygrid.transpose()
     xscale = max / xmax
     yscale = max / ymax
     zscale = max / zmax
     mlab.surf(xgrid * xscale, ygrid * yscale, self.growth_rates * zscale,
               representation="wireframe", color=(0, 0, 0), figure=figure)
     mlab.mesh(xgrid * xscale, ygrid * yscale, self.growth_rates * zscale,
               scalars=self.shadow_prices1 + self.shadow_prices2,
               resolution=1, representation="surface", opacity=0.75,
               figure=figure)
     # draw axes
     mlab.outline(extent=(0, max, 0, max, 0, max))
     mlab.axes(opacity=0, ranges=[0, xmax, 0, ymax, 0, zmax])
     mlab.xlabel(self.reaction1_name)
     mlab.ylabel(self.reaction2_name)
     mlab.zlabel("Growth rates")
     return figure
Example #20
0
def visualizePrices(prices):
    '''Creates a mayavi visualization of a pd DataFrame containing stock prices
    Inputs:
    prices => a pd DataFrame, w/ index: dates; columns: company names
    '''
    #Because of mayavi requirements, replace dates and company names with integers
    #until workaround is figured out
    x_length, y_length = prices.shape
    xTime = np.array([list(xrange(x_length)),] * y_length).transpose()
    yCompanies = np.array([list(xrange(y_length)),] * x_length)
    
    #Sort indexed prices by total return on last date
    lastDatePrices = prices.iloc[-1]
    lastDatePrices.sort_values(inplace=True)
    sortOrder = lastDatePrices.index
    zPrices = prices[sortOrder]
    
    #Create mayavi2 object
    dims = xTime.shape
    fig = mlab.figure(bgcolor=(.4,.4,.4))
    vis = mlab.surf(xTime, yCompanies, zPrices)
    mlab.outline(vis)
    mlab.orientation_axes(vis)
    #mlab.title('S&P 500 Market Data Visualization', size = .25)
    mlab.axes(vis, nb_labels=0, xlabel = 'Time', ylabel = 'Company', zlabel = 'Price')
    
    #Functionality to be added:
    #    cursor3d = mlab.points3d(0., 0., 0., mode='axes',
    #                                color=(0, 0, 0),
    #                                scale_factor=20)
    #picker = fig.on_mouse_pick(picker_callback)
    
    mlab.show()
Example #21
0
    def plot_mcontour(self, ndim0, ndim1, z, show_mode):
        "use mayavi.mlab to plot contour."
        if not mayavi_installed:
            self.__logger.info("Mayavi is not installed on your device.")
            return
        #do 2d interpolation
        #get slice object
        s = np.s_[0:ndim0:1, 0:ndim1:1]
        x, y = np.ogrid[s]
        mx, my = np.mgrid[s]
        #use cubic 2d interpolation
        interpfunc = interp2d(x, y, z, kind='cubic')
        newx = np.linspace(0, ndim0, 600)
        newy = np.linspace(0, ndim1, 600)
        newz = interpfunc(newx, newy)
        #mlab
        face = mlab.surf(newx, newy, newz, warp_scale=2)
        mlab.axes(xlabel='x', ylabel='y', zlabel='z')
        mlab.outline(face)
        #save or show
        if show_mode == 'show':
            mlab.show()
        elif show_mode == 'save':
            mlab.savefig('mlab_contour3d.png')
        else:
            raise ValueError('Unrecognized show mode parameter : ' +
                             show_mode)

        return
Example #22
0
def disp_pts(pts1, pts2, color1=(1,0,0), color2=(0,1,0)):
    figure = mlab.gcf()
    mlab.clf()
    figure.scene.disable_render = True

    pts1_glyphs   = mlab.points3d(pts1[:,0], pts1[:,1], pts1[:,2], color=color1, resolution=20, scale_factor=0.001)
    pts2_glyphs   = mlab.points3d(pts2[:,0], pts2[:,1], pts2[:,2], color=color2, resolution=20, scale_factor=0.001)
    glyph_points1 = pts1_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()
    glyph_points2 = pts2_glyphs.glyph.glyph_source.glyph_source.output.points.to_array()

    dd = 0.001

    outline1 = mlab.outline(pts1_glyphs, line_width=3)
    outline1.outline_mode = 'full'
    p1x, p1y, p1z = pts1[0,:]
    outline1.bounds = (p1x-dd, p1x+dd,
                       p1y-dd, p1y+dd,
                       p1z-dd, p1z+dd)

    pt_id1 = mlab.text(0.8, 0.2, '0 .', width=0.1, color=color1)

    outline2 = mlab.outline(pts2_glyphs, line_width=3)
    outline2.outline_mode = 'full'
    p2x, p2y, p2z = pts2[0,:]
    outline2.bounds = (p2x-dd, p2x+dd,
                       p2y-dd, p2y+dd,
                       p2z-dd, p2z+dd)  
    pt_id2 = mlab.text(0.8, 0.01, '0 .', width=0.1, color=color2)
    
    figure.scene.disable_render = False


    def picker_callback(picker):
        """ Picker callback: this gets called during pick events.
        """
        if picker.actor in pts1_glyphs.actor.actors:
            point_id = picker.point_id/glyph_points1.shape[0]
            if point_id != -1:
                ### show the point id
                pt_id1.text = '%d .'%point_id
                #mlab.title('%d'%point_id)
                x, y, z = pts1[point_id,:]
                outline1.bounds = (x-dd, x+dd,
                                   y-dd, y+dd,
                                   z-dd, z+dd)
        elif picker.actor in pts2_glyphs.actor.actors:
            point_id = picker.point_id/glyph_points2.shape[0]
            if point_id != -1:
                ### show the point id
                pt_id2.text = '%d .'%point_id
                x, y, z = pts2[point_id,:]
                outline2.bounds = (x-dd, x+dd,
                                   y-dd, y+dd,
                                   z-dd, z+dd)


    picker = figure.on_mouse_pick(picker_callback)
    picker.tolerance = dd/2.
    mlab.show()
Example #23
0
 def show(self):
     """
     Display real space model using volume
     """
     max_ = np.max(self.array)
     mlab.pipeline.volume(mlab.pipeline.scalar_field(self.array), vmin=0.2*max_, vmax=0.9*max_)
     mlab.outline()
     mlab.show()
Example #24
0
 def draw_cloud(self, points3d, scale=1):
     scale = self.scale * scale
     mlab.points3d(points3d[:, 0], points3d[:, 1],
                   points3d[:, 2], points3d[:, 2],
                   colormap='jet', opacity=0.75, scale_factor=scale)
     mlab.outline()
     mlab.colorbar(title='Planar disparity (mm)')
     mlab.axes()
Example #25
0
    def plot_u(u, x, xv, y, yv, t, n):
        """User action function for plotting."""
        if t[n] == 0:
            time.sleep(2)
        if plot_method == 1:
            # Works well with Gnuplot backend, not with Matplotlib
            st.mesh(x, y, u, title='t=%g' % t[n], zlim=[-1,1],
                    caxis=[-1,1])
        elif plot_method == 2:
            # Works well with Gnuplot backend, not with Matplotlib
            st.surfc(xv, yv, u, title='t=%g' % t[n], zlim=[-1, 1],
                  colorbar=True, colormap=st.hot(), caxis=[-1,1],
                  shading='flat')
        elif plot_method == 3:
            print 'Experimental 3D matplotlib...under development...'
            # Probably too slow
            #plt.clf()
            ax = fig.add_subplot(111, projection='3d')
            u_surf = ax.plot_surface(xv, yv, u, alpha=0.3)
            #ax.contourf(xv, yv, u, zdir='z', offset=-100, cmap=cm.coolwarm)
            #ax.set_zlim(-1, 1)
            # Remove old surface before drawing
            if u_surf is not None:
                ax.collections.remove(u_surf)
            plt.draw()
            time.sleep(1)
        elif plot_method == 4:
	    # Mayavi visualization
            mlab.clf()
            extent1 = (0, 20, 0, 20,-2, 2)
            s = mlab.surf(x , y, u,
                          colormap='Blues',
                          warp_scale=5,extent=extent1)
            mlab.axes(s, color=(.7, .7, .7), extent=extent1,
                      ranges=(0, 10, 0, 10, -1, 1),
                      xlabel='', ylabel='', zlabel='',
                      x_axis_visibility=False,
                      z_axis_visibility=False)
            mlab.outline(s, color=(0.7, .7, .7), extent=extent1)
            mlab.text(6, -2.5, '', z=-4, width=0.14)
            mlab.colorbar(object=None, title=None,
                          orientation='horizontal',
                          nb_labels=None, nb_colors=None,
                          label_fmt=None)
            mlab.title('Gaussian t=%g' % t[n])
            mlab.view(142, -72, 50)
            f = mlab.gcf()
            camera = f.scene.camera
            camera.yaw(0)

        if plot_method > 0:
            time.sleep(0) # pause between frames
            if save_plot:
                filename = 'tmp_%04d.png' % n
		if plot_method == 4:
                    mlab.savefig(filename)  # time consuming!
		elif plot_method in (1,2):
                    st.savefig(filename)  # time consuming!
Example #26
0
 def show(self):
   '''Show the 3D diagram in the screen.''' 
   from mayavi import mlab
   self.triangleMesh= mlab.triangular_mesh(self.x, self.y, self.z, self.triangles, scalars= self.scalars)
   mlab.colorbar(self.triangleMesh, orientation='vertical')
   mlab.outline(self.triangleMesh)
   mlab.axes(self.triangleMesh, xlabel= self.axialForceLabel, ylabel= self.bendingMomentYLabel, zlabel= self.bendingMomentZLabel)
   #mlab.title(self.title)
   mlab.show()
Example #27
0
def draw():
	
	
	m,g = read(sys.argv[1])
	init_mlab_scene((1024,768))
	print "Drawing Nickel" 
	mlab.points3d(m.x, m.y, m.z, m.t, mode="point", scale_mode="none",scale_factor=m.d, colormap="black-white")
	print "Drawing Nitrogenium"
	mlab.points3d(g.x, g.y, g.z, g.t, mode="point", scale_mode="none",scale_factor=g.d, colormap="cool") 
	mlab.outline()
Example #28
0
def plotCutPlanes(s):
    mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                            plane_orientation='x_axes',
                            slice_index=100,
                        )
    mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                            plane_orientation='y_axes',
                            slice_index=100,
                        )
    mlab.outline()
Example #29
0
 def draw_mesh(self, mesh, color=WHITE, opacity=0.7):
     x, y, z, triangles = self._get_triangular_mesh(mesh)
     mlab.triangular_mesh(x, y, z, triangles, color=color,
                          opacity=opacity, representation='surface')
     #mlab.triangular_mesh(x, y, z, triangles, colormap='bone',
     #                     opacity=0.8, representation='surface')
     mlab.triangular_mesh(x, y, z, triangles, color=(0, 0, 0),
                          line_width=1.0, representation='wireframe')
     mlab.outline()
     mlab.axes()
Example #30
0
	def labels(self):
		'''
		Add 3d text to show the axes.
		'''
		fontsize = max(self.xrang, self.yrang)/40.
		tcolor = (1,1,1)
		mlab.text3d(self.xrang/2,-10,self.zrang+10,'R.A.',scale=fontsize,orient_to_camera=True,color=tcolor)
		mlab.text3d(-10,self.yrang/2,self.zrang+10,'Decl.',scale=fontsize,orient_to_camera=True,color=tcolor)
		mlab.text3d(-10,-10,self.zrang/2-10,'V (km/s)',scale=fontsize,orient_to_camera=True,color=tcolor)

		# Add scale bars
		if self.leng != 0.0:
			distance = self.dist * 1e3
			length = self.leng
			leng_pix = np.round(length/distance/np.pi*180./np.abs(self.hdr['cdelt1']))
			bar_x = [self.xrang-20-leng_pix, self.xrang-20]
			bar_y = [self.yrang-10, self.yrang-10]
			bar_z = [0, 0]
			mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.)
			mlab.text3d(self.xrang-30-leng_pix,self.yrang-25,0,'{:.2f} pc'.format(length),scale=fontsize,orient_to_camera=False,color=tcolor)
		if self.vsp != 0.0:
			vspan = self.vsp
			vspan_pix = np.round(vspan/np.abs(self.hdr['cdelt3']/1e3))
			bar_x = [self.xrang, self.xrang]
			bar_y = [self.yrang-10, self.yrang-10]
			bar_z = np.array([5, 5+vspan_pix])*self.zscale
			mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.)
			mlab.text3d(self.xrang,self.yrang-25,10,'{:.1f} km/s'.format(vspan),scale=fontsize,orient_to_camera=False,color=tcolor,orientation=(0,90,0))

		# Label the coordinates of the corners
		# Lower left corner
		ra0 = self.extent[0]; dec0 = self.extent[2]
		c = SkyCoord(ra=ra0*u.degree, dec=dec0*u.degree, frame='icrs')
		RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s'
		mlab.text3d(0,-10,self.zrang+5,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s'
		mlab.text3d(-40,0,self.zrang+5,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		# Upper right corner
		ra0 = self.extent[1]; dec0 = self.extent[3]
		c = SkyCoord(ra=ra0*u.degree, dec=dec0*u.degree, frame='icrs')
		RA_ll = str(int(c.ra.hms.h))+'h'+str(int(c.ra.hms.m))+'m'+str(round(c.ra.hms.s,1))+'s'
		mlab.text3d(self.xrang,-10,self.zrang+5,RA_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		DEC_ll = str(int(c.dec.dms.d))+'d'+str(int(abs(c.dec.dms.m)))+'m'+str(round(abs(c.dec.dms.s),1))+'s'
		mlab.text3d(-40,self.yrang,self.zrang+5,DEC_ll,scale=fontsize,orient_to_camera=True,color=tcolor)
		# V axis
		if self.extent[5] > self.extent[4]:
			v0 = self.extent[4]; v1 = self.extent[5]
		else:
			v0 = self.extent[5]; v1 = self.extent[4]
		mlab.text3d(-10,-10,self.zrang,str(round(v0,1)),scale=fontsize,orient_to_camera=True,color=tcolor)
		mlab.text3d(-10,-10,0,str(round(v1,1)),scale=fontsize,orient_to_camera=True,color=tcolor)

		mlab.axes(self.field, ranges=self.extent, x_axis_visibility=False, y_axis_visibility=False, z_axis_visibility=False)
		mlab.outline()
           curve_z,
           tube_radius=0.2,
           extent=(0, 1, 0, 1, 0, 1))

plt.figure(3, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0))
# Use 'warp_scale' for vertical scaling
plt.surf(xv, yv, hv, warp_scale=0.01, color=(.5, .5, .5))
plt.plot3d(curve_x, curve_y, 0.01 * curve_z, tube_radius=0.2)
# endsimpleplots

# Create one figure with three subplots
plt.figure(4, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0))
plt.mesh(xv, yv, hv, extent=(0, 0.25, 0, 0.25, 0, 0.25), colormap='cool')
plt.outline(
    plt.mesh(xv,
             yv,
             hv,
             extent=(0.375, 0.625, 0, 0.25, 0, 0.25),
             colormap='Accent'))
plt.outline(plt.mesh(xv,
                     yv,
                     hv,
                     extent=(0.75, 1, 0, 0.25, 0, 0.25),
                     colormap='prism'),
            color=(.5, .5, .5))
# endsubplot

hv = h0 / (1 + (xv**2 + yv**2) / (R**2))

# Default contour plot plotted together with surf.
plt.figure(5, fgcolor=(.0, .0, .0), bgcolor=(1.0, 1.0, 1.0))
plt.surf(xv, yv, hv, warp_scale=0.01)
Example #32
0
import numpy as np
import h5py
from mayavi import mlab
f = h5py.File('visual.h5', 'r')
for key in f['visual']:
    vis = np.array(f['visual'][key])
    mlab.contour3d(vis, contours=8, opacity=.2)
nx, ny, nz = vis.shape
f.close()
mlab.outline(extent=[0, nx, 0, ny, 0, nz])
mlab.show()
def test_3_6(dx, dy, dt):
    """
    """
    bc = {'N': None, 'W': None, 'E': None, 'S': None}
    mx = 2
    my = 2
    Lx = 5.
    Ly = 5.
    T = 10./2.**.5

    # # # #
    sin = np.sin
    cos = np.cos
    pi = np.pi
    exp = np.exp

    k = 0.9
    B = 1.0

    kx = mx*pi/Lx
    ky = my*pi/Ly
    A = B
    b = np.sqrt(2*k*kx**2 + 2*k*ky**2)
    c = b/2
    w = np.sqrt(kx**2*k + ky**2*k - c**2)

    def u_e(x, y, t):
        return (A*cos(w*t) + B*sin(w*t)) * \
            exp(-c*t) * cos(kx*x) * cos(ky*y)

    def f(x, y, t):
        return 0.0

    def q(x, y):
        return k

    def I(x, y):
        return B*cos(kx*x)*cos(ky*y)

    def V(x, y):
        return 0.0

    Nt = int(round(T/float(dt)))
    Nx = int(round(Lx/float(dx)))
    Ny = int(round(Ly/float(dy)))
    x, y, dx, dy, dt = get_dt(Lx, Ly, Nx, Ny, dt, q)

    e = np.zeros((Nx+1, Ny+1, Nt+1))

    # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#surf
    test_extent = (0, Lx, 0, Ly, -1, 1)
    X, Y = np.meshgrid(x, y)
    Z = I(X, Y)
    mlab.figure(1, size=(1920, 1080), fgcolor=(1, 1, 1),
                bgcolor=(0.5, 0.5, 0.5))
    ms1 = mlab.surf(X.T, Y.T, Z.T, colormap='Spectral')
    ms2 = mlab.surf(X.T, Y.T, Z.T, color=(0.0, .0, .0),
                    representation="wireframe")
    mlab.outline(ms1, color=(0.7, .7, .7), extent=test_extent)
    ax = mlab.axes(ms1, color=(.7, .7, .7), extent=test_extent,
                   ranges=test_extent, xlabel='X', ylabel='Y',
                   zlabel='u(t)')
    ax.axes.label_format = '%.1f'
    mlab.view(142, -72, sqrt(Lx**2+Ly**2)*4)

    def action(u, x, y, t, n):
        u_exakt = u_e(X.T, Y.T, t[n])
        e[:, :, n] = u_exakt-u

        ms1.mlab_source.set(z=u_exakt, scalars=u_exakt)
        ms2.mlab_source.set(z=u, scalars=u)
        mlab.title('standing damped wave, t = {:.2f}'.format(t[n]))
        filename = os.path.join(out_path, '{}_{:06d}{}'.format(prefix, n, ext))
        print(filename)
        mlab.savefig(filename=filename)
        return

    solver(I, f, q, bc, Lx, Ly, Nx, Ny, dt, T, b, V,
           user_action=action, version='vectorized')
    mlab.show()
#    print(e.min(), e.max(), e.mean())
    return e, dx, dy, dt
Example #34
0
x, y = x.flatten(), y.flatten()
z = np.zeros(K * K)

colors = 1.0 * (x + y) / (max(x) + max(y))  # Rainbow color
##colors = 0.0 * (x + y)/(max(x)+max(y))      # Dark blue color

nodes = mlab.points3d(x, y, z, opacity=0.1, scale_factor=0.5)
nodes.glyph.scale_mode = 'scale_by_vector'
nodes.mlab_source.dataset.point_data.scalars = colors

for i in range(K):
    nodes = mlab.points3d(x, y, z + i, opacity=0.1, scale_factor=0.5)
    nodes.glyph.scale_mode = 'scale_by_vector'
    nodes.mlab_source.dataset.point_data.scalars = colors

mlab.outline(extent=[0, 10, 0, 10, 0, 10])
mlab.axes(extent=[0, 10, 0, 10, 0, 10],
          line_width=1.0,
          x_axis_visibility=True,
          y_axis_visibility=True,
          z_axis_visibility=True)
##mlab.show()

# ======================================================================= #
# ======================================================================= #
# ======================================================================= #

# -------------------------------------------------------------------------

# ======================================================================= #
# ======================= ORBITING STUFF ANIMATION ====================== #
    print(X.shape)
    print(Y.shape)
    print(Z.shape)
    return Lx, Ly, dx, dy, X, Y, Z


if __name__ == '__main__':
    Lx = 100
    B0 = -15
    Ba = 15
    Bmx = 50
    Bmy = 50  # symmetrie Linie
    Bs = 10  # ?
    b = 1
    Lx, Ly, dx, dy, X, Y, Z = get_mt_st_helens(Lx, Ba, B0)
    print(dx, dy)
    print(Lx, Ly)
    test_extent = (0, Lx, 0, Ly, B0, Ba)
    bottom = mlab.surf(X.T, Y.T, Z.T, colormap='gist_earth')
    mlab.outline(bottom, color=(0.7, .7, .7), extent=test_extent)
    ax = mlab.axes(bottom,
                   color=(.7, .7, .7),
                   extent=test_extent,
                   ranges=test_extent,
                   xlabel='X',
                   ylabel='Y',
                   zlabel='H')

    mlab.view(30, -72, np.sqrt(Lx**2 + Ly**2) * 2)
    mlab.show()
Example #36
0
#!/usr/bin/env python2
# -*- coding:utf-8 -*-
from numpy import pi, sin, cos, mgrid
import numpy as np
from mayavi import mlab

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

pl = mlab.surf(x, y, z, warp_scale="auto")
mlab.axes(xlabel='x', ylabel='y', zlabel='z')
mlab.outline(pl)

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

# # View it.
s = mlab.mesh(x, y, z)
Example #37
0
Note that, as we know the expression of the function, it would be simpler
and more efficient to directly sample it on the sphere.
"""
import numpy as np

from mayavi import mlab
from tvtk.api import tvtk
from tvtk.common import configure_source_data

# The angular par of the spherical harmonic (3, 2)
x, y, z = np.mgrid[-.5:.5:100j, -.5:.5:100j, -.5:.5:100j]
Phi = np.angle((x+y*1j)**2*z)

field = mlab.pipeline.scalar_field(x, y, z, Phi)
ipw = mlab.pipeline.image_plane_widget(field)
mlab.outline(field)

surface = mlab.pipeline.builtin_surface()
surface.source = 'sphere'
surface.data_source.radius = .4
surface.data_source.phi_resolution = 200
surface.data_source.theta_resolution = 200
probe_filter = tvtk.ProbeFilter()
configure_source_data(probe_filter, field.outputs[0])
probe = mlab.pipeline.user_defined(surface, filter=probe_filter)

surf = mlab.pipeline.surface(probe)

fig = mlab.gcf()

################################################################################
Example #38
0
def generate_cartesian_volume(fig, length=250, spacing=10):
    '''
    Generates a meshed cartesian volume that encapsulates the ROI.
    
    INPUTS:
        - fig    : Scene/figure to populate.
        - length : Length of axes ( generates a KxKxK sized cube ).
        - spacing: Spacing between consecutive lines.

    OUTPUT:
        - No return; generates a mesh on the render window.
    '''
    print("Constructing cartesian volume ..."),

    K = length + 1  # Number of lines to plot
    N = spacing  # Subdivisions (aka K/N lines are drawn)

    # Draw horizontal lines on the xy-, yz-, and xz-planes
    lvlC_H = np.arange(0, K, N)  # Horizontal level curve
    lvlC_V = np.zeros_like(lvlC_H)  # Vertical level curve
    H, V = np.meshgrid(lvlC_H, lvlC_V)  # Mesh both arrays to a matrix (a grid)
    lvlC_0 = np.zeros_like(
        H)  # Force everything into a 2D plane by setting the 3rd plane to 0

    for i in range(0, K, N):
        mlab.mesh(H,
                  V + i,
                  lvlC_0,
                  figure=fig,
                  representation='mesh',
                  tube_radius=0.25,
                  color=(1., 1., 1.))

        mlab.mesh(lvlC_0,
                  H,
                  V + i,
                  figure=fig,
                  representation='mesh',
                  tube_radius=0.25,
                  color=(1., 1., 1.))

        mlab.mesh(H,
                  lvlC_0,
                  V + i,
                  figure=fig,
                  representation='mesh',
                  tube_radius=0.25,
                  color=(1., 1., 1.))

    # Draw vertical lines on the xy-, yz-, and xz-planes
    lvlC_V = np.arange(0, K, N)  # Vertical level curve
    lvlC_H = np.zeros_like(lvlC_V)  # Horizontal level curve
    H, V = np.meshgrid(lvlC_H,
                       lvlC_V)  # Mesh both arrays to form a matrix (a grid)
    lvlC_0 = np.zeros_like(
        H)  # Force everything into a 2D plane by setting the 3rd plane to 0

    for i in range(0, K, N):
        mlab.mesh(H + i,
                  V,
                  lvlC_0,
                  figure=fig,
                  representation='mesh',
                  tube_radius=0.25,
                  color=(1., 1., 1.))

        mlab.mesh(lvlC_0,
                  H + i,
                  V,
                  figure=fig,
                  representation='mesh',
                  tube_radius=0.25,
                  color=(1., 1., 1.))

        mlab.mesh(H + i,
                  lvlC_0,
                  V,
                  figure=fig,
                  representation='mesh',
                  tube_radius=0.25,
                  color=(1., 1., 1.))

    # Generate outline and label axes
    mlab.outline(extent=[0, K - 1, 0, K - 1, 0, K - 1], figure=fig)
    mlab.axes(extent=[0, K - 1, 0, K - 1, 0, K - 1],
              figure=fig,
              line_width=1.0,
              x_axis_visibility=True,
              y_axis_visibility=True,
              z_axis_visibility=True)

    print("SUCCESS!")
Example #39
0
            x2 = uniform_grid(1, dims, ext)
            mlab.clf()
            src = mlab.pipeline.array2d_source(x1, x2, data_slice)
            # Plot a slice as a falsecolor image
            if plot_type == 1:
                obj = mlab.pipeline.image_actor(src, colormap='gist_ncar')
                mlab.view(azimuth=0,
                          elevation=0,
                          distance=2 * np.max(sizes),
                          focalpoint=origin)
            # Plot a slice as a 3D surface
            if plot_type == 2:
                warp = mlab.pipeline.warp_scalar(src, warp_scale=1.0)
                normals = mlab.pipeline.poly_data_normals(warp)
                obj = mlab.pipeline.surface(normals, colormap='gist_ncar')
                mlab.outline(extent=ext)
                #WARNING: the z-axis will include the warp factor and is highly misleading
                #mlab.axes(src,z_axis_visibility=False,extent=ext,xlabel=plot_dict['xlabel'],ylabel=plot_dict['ylabel'],zlabel=plotter.name)
                mlab.view(azimuth=90,
                          elevation=60,
                          distance=5 * np.max(sizes),
                          focalpoint=origin)
            s = s0 * len(slices[1]) + s1
            mlab.savefig('tempfile{:03d}.png'.format(s))

# 3D PLOTS

if num_slice_axes == 1:
    for s in slices[0]:
        print('Rendering frame', s, '...')
        data_slice, plot_dict = plotter.volume3d(slicing_spec, s, dyn_range)
Example #40
0
    def show_map(self, didx, thresh=None, show=True, closeup=False):
        if show:
            from mayavi import mlab
            # For the heaavvvyyy runs...
            # mlab.options.offscreen = True
        if thresh == None:
            thresh = 0.1  # self.params.prior + 0.1*self.params.prior
        subselected = self.alphas.flatten() > thresh
        fig = mlab.figure(bgcolor=(1, 1, 1),
                          fgcolor=(0, 0, 0),
                          size=(800, 600))
        scaled_xs = (self.global_xs * self.params.res -
                     self.params.dims[0] / 2.0).flatten()[subselected]
        scaled_ys = (self.global_ys * self.params.res -
                     self.params.dims[1] / 2.0).flatten()[subselected]
        scaled_zs = (self.global_zs * self.params.res).flatten()[subselected]

        if didx == 0:
            # Rotate by 180 about Z since mocap arena has x facing backwards
            scaled_xs = -scaled_xs
            scaled_ys = -scaled_ys

        if didx == 1 or didx == 2:
            self.alphas = self.global_zs * self.params.res

        obj = mlab.points3d(scaled_xs,
                            scaled_ys,
                            scaled_zs,
                            self.alphas.flatten()[subselected],
                            figure=fig,
                            mode='cube',
                            scale_mode='none',
                            scale_factor=self.params.res,
                            colormap='viridis',
                            vmin=0.0,
                            vmax=1.0)
        obj.glyph.color_mode = 'color_by_scalar'

        # if didx==0:
        #     cb = mlab.colorbar(object=obj, orientation='horizontal', title='Occupancy')
        #     cb.scalar_bar.unconstrained_font_size = True
        #     cb.label_text_property.font_size=16
        if not closeup:
            outline = mlab.outline(color=(0, 0, 0))
            outline.outline_mode = 'cornered'
            axes = mlab.axes(color=(0, 0, 0),
                             nb_labels=5,
                             ranges=[
                                 -self.params.dims[0] / 2.0,
                                 self.params.dims[0] / 2.0,
                                 -self.params.dims[1] / 2.0,
                                 self.params.dims[1] / 2.0, 0,
                                 self.params.dims[2]
                             ])
            axes.axes.label_format = '%.2f'
            axes.label_text_property.bold = False

        filename = self.dir_path + self.title + '.png'
        # mlab.title(self.title, height=0.9)
        cam = fig.scene.camera

        if didx == 0:
            cam.zoom(0.8)
            cam.focal_point = (0, 0, 0.5)
            cam.position = cam.position + (0, 0, -1.5)

            if closeup:
                # For Hand zoom
                cam.position = [
                    1.2778361880731004, 1.0320858725903652, 1.78619247887134
                ]
                cam.focal_point = [
                    -0.6277706322975143, 0.09905530113369865,
                    1.3639411406184958
                ]
                cam.view_angle = 37.5
                cam.view_up = [
                    -0.16874950695747495, -0.09915466969595163,
                    0.9806589393765275
                ]
                cam.clipping_range = [0.007254798749460739, 7.254798749460739]

        if didx == 1:

            cam.position = [
                3.633748241697305, 2.5587483132228788, 4.68374820612078
            ]
            cam.focal_point = [
                -0.04999995231628418, -1.1249998807907104, 1.0000000121071935
            ]
            cam.view_angle = 30.0
            cam.view_up = [0.0, 0.0, 1.0]
            cam.clipping_range = [0.016383043070992025, 16.383043070992024]

            # For chair zoom
            if closeup:
                cam.position = [
                    2.319401891144527, -1.1163001192205257, 2.143165504968805
                ]
                cam.focal_point = [
                    1.1456461918469256, -2.290055818518119, 0.9694098056712085
                ]
                cam.view_angle = 30.0
                cam.view_up = [0.0, 0.0, 1.0]
                cam.clipping_range = [0.011199111522278649, 11.199111522278649]

        if didx == 2:
            if closeup:
                cam.position = [
                    10.956703963028406, 10.956703963028406, 3.866704193214095
                ]
                cam.focal_point = [
                    7.489999771118164, 7.489999771118164, 0.4000000013038516
                ]
                cam.view_angle = 30.0
                cam.view_up = [0.0, 0.0, 1.0]
                cam.clipping_range = [0.03297374234716125, 32.97374234716125]
        mlab.savefig(filename, figure=fig)
        if show:
            mlab.show()
        mlab.close(all=True)
Example #41
0
print("done")

volume_figure = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
vol = mlab.pipeline.volume(mlab.pipeline.scalar_field(data),
                           vmin=args.vmin,
                           vmax=args.vmax)

ctf = ColorTransferFunction()
ctf.add_rgb_point(0, 1, 1, 1)
ctf.add_rgb_point(1, 0, 0, 0.3)

vol._volume_property.set_color(ctf)
vol._ctf = ctf
vol.update_ctf = True
mlab.outline()

if args.show_cut:
    cut_figure = mlab.figure(bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
    mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(data),
                                     plane_orientation='x_axes',
                                     slice_index=data.shape[0] / 2,
                                     figure=cut_figure)
    mlab.sync_camera(volume_figure, cut_figure)
    mlab.outline()

if args.show_iso:
    # downsample to get a somewhat smoother surface
    downscaled = scipy.ndimage.zoom(data, 256.0 / data.shape[0])

    # do some blurring to get smoother contours
Example #42
0
for i in range (0, K, 5):
    mlab.plot3d( H, lvlCurve_0, V+i )

# Level curves to draw vertical lines on the xz-plane
lvlCurve_V = np.arange(0, K, 5)
lvlCurve_H = np.zeros_like(lvlCurve_V)
H, V = np.meshgrid(lvlCurve_H, lvlCurve_V)
H, V = H.flatten(), V.flatten()
##lvlCurve_0 = np.zeros(K*K)          # Force everything into the xy-plane (z=0)
lvlCurve_0 = np.zeros_like(H)                          # Force everything into the xy-plane (z=0)

for i in range (0, K, 5):
    mlab.plot3d( H+i, lvlCurve_0, V )

# Setup cartesian space
mlab.outline( extent=[0, K-1, 0, K-1, 0, K-1] )
mlab.axes( extent=[0, K-1, 0, K-1, 0, K-1],
           line_width = 1.0,
           x_axis_visibility=True,
           y_axis_visibility=True,
           z_axis_visibility=True )
  
##mlab.show()

# ======================================================================= #
# ======================================================================= #
# ======================================================================= #

# -------------------------------------------------------------------------

# ======================================================================= #
Example #43
0
#maya.figure(size=(800, 600)) # For Mac
maya.figure(bgcolor=(1.0, 1.0, 1.0), size=(800, 600))
maya.contour3d(T,
               colormap='jet',
               contours=4,
               name='Temperature',
               vmax=0.7,
               vmin=0.3)
maya.colorbar(title='Temperature', orientation='vertical', nb_labels=3)

#src = maya.pipeline.scalar_field(T)
#maya.pipeline.surface(src, colormap='jet')
#maya.colorbar(title='Temperature', orientation='vertical', nb_labels=3)

#maya.quiver3d(X, Y, Z, V1, V2, V3, colormap = 'Oranges', line_width=0.2, scale_factor=0.5, mask_points=600)
#maya.colorbar(title='Velocity', nb_labels=3)

maya.outline()
maya.show()

################################################################

###################### Ring Spectrum ################################
"""
t.ring_spectrum_showtime()
data = t.ring_spectrum_read(6,'Uek')
data = np.array(data)
print data
"""
######################################################################
Example #44
0
        if iteration == -1:
            iterword = 'initial grid'
        elif iteration == -2:
            iterword = 'post initialization'
        elif iteration == -3:
            iterword = 'latest save'
        else:
            iterword = '%08i' % iteration
        itertext = mlab.text(.02, .95, iterword, figure=figure, width=.2)

    if not args.notext:
        mlab.orientation_axes(figure=figure, name='bob')

    # Draw the cell
    cell = mlab.outline(extent=[0, dim[0], 0, dim[1], 0, dim[2]],
                        color=(0, 0, 0),
                        line_width=3)

    if (celltype == 'walls' and not args.hide_walls):
        sheet_points = array([[0, 0, 0], [dim[0], 0, 0], [dim[0], dim[1], 0],
                              [0, dim[1], 0], [0, 0, dim[2]],
                              [dim[0], 0, dim[2]], [dim[0], dim[1], dim[2]],
                              [0, dim[1], dim[2]]])
        sheet_connections = array([[0, 1, 2, 3], [4, 5, 6, 7]])
        sheetmesh = tvtk.PolyData(points=sheet_points, polys=sheet_connections)
        mlab.pipeline.surface(sheetmesh, opacity=.6, color=(1, 1, 1))

    # if(celltype == 'walls'and not args.hide_walls):
    #   nbars = 11
    #   x = tile(repeat(linspace(0, dim[0], nbars), 2), 2)
    #   y = tile(array([0, dim[1]]), 2*nbars)
Example #45
0
def show_box(box_data):
  """from box_data produce a 3D image of surfaces and display it"""

  use_color_flag=True
  reverse_redshift_flag=True

  (dimx,dimy,dimz)=box_data.shape
  print box_data.shape

  mycolor='black-white'

  if use_color_flag:
      mycolor='blue-red'
      mycolor='RdBu'
      #need to set color scale to be symmetric around zero

  if reverse_redshift_flag:
    print 'want to be able to reseverse long axis ordering'
    box_data=numpy.flipud(box_data)
    #box_data=box_data[:,::-1,:]

  print box_data.min(), box_data.max()
  #clip_data
  clip=30.0
  vmax=clip
  vmin= -clip
  box_data[box_data>vmax]=vmax
  box_data[box_data<vmin]=vmin
  
  print box_data.min(), box_data.max()
  c_black=(0.0,0.0,0.0)
  c_white=(1.0,1.0,1.0)

  #s=box_data
  mlab.figure(1,bgcolor=c_white,fgcolor=c_black)
  planex=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(box_data),
                            plane_orientation='x_axes',
                            slice_index=dimx-1,colormap=mycolor
                        )
  planey=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(box_data),
                            plane_orientation='y_axes',
                            slice_index=dimy-1,colormap=mycolor
                        )

  planez=mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(box_data),
                            plane_orientation='z_axes',
                            slice_index=dimz-1,colormap=mycolor
                        )

  # colormap='blue-red' may be useful for 21 cm brightness maps
  # although it passes through white not black
  


  #now try to invert the color scheme

  lut=planez.module_manager.scalar_lut_manager.lut.table.to_array()
  lut=numpy.flipud(lut)
  #lut=lutForTBMap()
  #print help(lut)
  planex.module_manager.scalar_lut_manager.lut.table = lut
  planey.module_manager.scalar_lut_manager.lut.table = lut
  planez.module_manager.scalar_lut_manager.lut.table = lut

  mlab.draw()  #force update of figure

  mlab.colorbar()
  mlab.outline(color=c_black)
  
  #mlab.show()

  filename='volume_slice.png'
  figsave=mlab.gcf()
  #mlab.savefig(filename,figure=figsave,magnification=4.)
  mlab.savefig(filename,size=(1800,800),figure=figsave,magnification=4)
  mlab.close()

  #Can't get MayaVi to output a good eps, so use PIL to convert
  im = Image.open(filename)
  im.save("volume_slice.eps")
  
  return
Example #46
0
sinth = sin(theta)
costh = cos(theta)

m = 0
for k in range(K):
    for j in range(J):
        for i in range(I):
            rho += (c[m] * np.power(sinphi, i + j) * np.power(cosphi, k) *
                    np.power(sinth, j) * np.power(costh, i))
            m += 1

xs = rho * sin(phi) * cos(theta)
ys = rho * sin(phi) * sin(theta)
zs = rho * cos(phi)

import mayavi.mlab as mylab
fig = mylab.figure(1, bgcolor=(0, 0, 0))
mylab.clf()
ps = 1. * np.ones_like(x)
mylab.points3d(x,
               y,
               z, (ps),
               scale_factor=0.025,
               colormap='Spectral',
               opacity=1.)
mylab.mesh(xs, ys, zs, colormap="bone", opacity=0.5)
mylab.outline()
mylab.xlabel('X')
mylab.ylabel('Y')
mylab.zlabel('Z')
Example #47
0
    def labels(self):
        '''
		Add 3d text to show the axes.
		'''
        fontsize = max(self.xrang, self.yrang) / 40.
        tcolor = (1, 1, 1)
        mlab.text3d(self.xrang / 2,
                    -10,
                    self.zrang + 10,
                    'R.A.',
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        mlab.text3d(-10,
                    self.yrang / 2,
                    self.zrang + 10,
                    'Decl.',
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        mlab.text3d(-10,
                    -10,
                    self.zrang / 2 - 10,
                    'V (km/s)',
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)

        # Add scale bars
        if self.leng != 0.0:
            distance = self.dist * 1e3
            length = self.leng
            leng_pix = np.round(length / distance / np.pi * 180. /
                                np.abs(self.hdr['cdelt1']))
            bar_x = [self.xrang - 20 - leng_pix, self.xrang - 20]
            bar_y = [self.yrang - 10, self.yrang - 10]
            bar_z = [0, 0]
            mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.)
            mlab.text3d(self.xrang - 30 - leng_pix,
                        self.yrang - 25,
                        0,
                        '{:.2f} pc'.format(length),
                        scale=fontsize,
                        orient_to_camera=False,
                        color=tcolor)
        if self.vsp != 0.0:
            vspan = self.vsp
            vspan_pix = np.round(vspan / np.abs(self.hdr['cdelt3'] / 1e3))
            bar_x = [self.xrang, self.xrang]
            bar_y = [self.yrang - 10, self.yrang - 10]
            bar_z = np.array([5, 5 + vspan_pix]) * self.zscale
            mlab.plot3d(bar_x, bar_y, bar_z, color=tcolor, tube_radius=1.)
            mlab.text3d(self.xrang,
                        self.yrang - 25,
                        10,
                        '{:.1f} km/s'.format(vspan),
                        scale=fontsize,
                        orient_to_camera=False,
                        color=tcolor,
                        orientation=(0, 90, 0))

        # Label the coordinates of the corners
        # Lower left corner
        ra0 = self.extent[0]
        dec0 = self.extent[2]
        c = SkyCoord(ra=ra0 * u.degree, dec=dec0 * u.degree, frame='icrs')
        RA_ll = str(int(c.ra.hms.h)) + 'h' + str(int(c.ra.hms.m)) + 'm' + str(
            round(c.ra.hms.s, 1)) + 's'
        mlab.text3d(0,
                    -10,
                    self.zrang + 5,
                    RA_ll,
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        DEC_ll = str(int(c.dec.dms.d)) + 'd' + str(int(abs(
            c.dec.dms.m))) + 'm' + str(round(abs(c.dec.dms.s), 1)) + 's'
        mlab.text3d(-40,
                    0,
                    self.zrang + 5,
                    DEC_ll,
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        # Upper right corner
        ra0 = self.extent[1]
        dec0 = self.extent[3]
        c = SkyCoord(ra=ra0 * u.degree, dec=dec0 * u.degree, frame='icrs')
        RA_ll = str(int(c.ra.hms.h)) + 'h' + str(int(c.ra.hms.m)) + 'm' + str(
            round(c.ra.hms.s, 1)) + 's'
        mlab.text3d(self.xrang,
                    -10,
                    self.zrang + 5,
                    RA_ll,
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        DEC_ll = str(int(c.dec.dms.d)) + 'd' + str(int(abs(
            c.dec.dms.m))) + 'm' + str(round(abs(c.dec.dms.s), 1)) + 's'
        mlab.text3d(-40,
                    self.yrang,
                    self.zrang + 5,
                    DEC_ll,
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        # V axis
        if self.extent[5] > self.extent[4]:
            v0 = self.extent[4]
            v1 = self.extent[5]
        else:
            v0 = self.extent[5]
            v1 = self.extent[4]
        mlab.text3d(-10,
                    -10,
                    self.zrang,
                    str(round(v0, 1)),
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)
        mlab.text3d(-10,
                    -10,
                    0,
                    str(round(v1, 1)),
                    scale=fontsize,
                    orient_to_camera=True,
                    color=tcolor)

        mlab.axes(self.field,
                  ranges=self.extent,
                  x_axis_visibility=False,
                  y_axis_visibility=False,
                  z_axis_visibility=False)
        mlab.outline()
def task4():
    """
    """
    h = 0.5
    dx = dy = h
    dt = 0

    I0 = 0
    Ia = 40  # height wave
    Im = 0
    Is = 5

    B0 = -30
    Ba = 28
    Bmx = 50
    Bmy = 50  # symmetrie Linie
    Bs = 100  # ~Breite
    b = 1

    Lx = 150
    Ly = 150
    T = 15

    g = 9.81

    Lx, Ly, dx, dy, X, Y, Z_HELEN = get_mt_st_helens(Lx, Ba, B0)

    def st_helens(x, y):
#        print(x.shape, Z_HELEN.shape)
        if x.ravel().shape != Y.ravel().shape:
            _z_ = np.ones_like(x)*Z_HELEN.min()  # the fake mesh for c_max pukes here
#            print(_z_)
            return _z_
        else:
            return Z_HELEN.reshape(x.shape)

    def H(x, y):
        z = -st_helens(x, y)
#        print("H: ", z.min(), z.max())
        return z

    def q(x, y):
        return g*H(x, y)

    def I(x, y):  # 7
        return I0 + Ia*np.exp(-((x-Im)/Is)**2)

    def B8(x, y):  # 8
        return B0 + Ba*np.exp(-((x-Bmx)/Bs)**2-((y-Bmy)/(b*Bs))**2)

    def B9(x, y):  # 9
        return B0+Ba*np.cos(np.pi*(x-Bmx)/(2*Bs))*np.cos(np.pi*(y-Bmy)/(2*Bs))

    def B10(x, y):  # 10
        res = np.ones_like(x) * B0
        l1 = ((Bmx-Bs) <= x) & (x <= (Bmx+Bs))
        l2 = ((Bmy-b*Bs) <= y) & (y <= (Bmy+b*Bs))
        res[l1 & l2] = B0 + Ba
        return res

    def V(x, y):
        return 0.0

    def f(x, y, t):
        return 0.0

    bc = {'N': None, 'W': None, 'E': None, 'S': None}

    Nx = int(round(Lx/float(dx)))
    Ny = int(round(Ly/float(dy)))

    x, y, dx, dy, dt = get_dt(Lx, Ly, Nx, Ny, dt, q)


    # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#surf
    test_extent = (0, Lx, 0, Ly, B0, Ia)
    X, Y = np.meshgrid(x, y)
    Z = I(X, Y)
    print(Z.shape)
    mlab.figure(1, size=(1920/2, 1080/2), fgcolor=(0, 0, 0),
                bgcolor=(1., 1., 1.))
    bottom = mlab.surf(X.T, Y.T, -H(X, Y).T, colormap='gist_earth')
    ms2 = mlab.surf(X.T, Y.T, Z.T, colormap='jet', opacity=0.5,
                    transparent=True, vmin=0, vmax=Ia/15)
    mlab.outline(ms2, color=(0.7, .7, .7), extent=test_extent)
    ax = mlab.axes(ms2, color=(.7, .7, .7), extent=test_extent,
                   ranges=test_extent, xlabel='X', ylabel='Y',
                   zlabel='H')
    ax.axes.label_format = ''
    mlab.view(140, -72, np.sqrt(Lx**2+Ly**2)*1.5)

    def action(u, x, y, t, n):
#        u_exakt = u_e(X.T, Y.T, t[n])
#        e[:, :, n] = u_exakt-u

#        ms1.mlab_source.set(z=u_exakt, scalars=u_exakt)
        nn = 10
        if n%nn == 0:
            ms2.mlab_source.set(z=u, scalars=u)
            mlab.title('Tsunami, t = {:.2f}'.format(t[n]))
            # concate filename with zero padded index number as suffix
            filename = os.path.join(out_path, '{}_{:06d}{}'.format(prefix, n//nn, ext))
            print(filename)
            mlab.savefig(filename=filename)
        return

    solver(I, f, q, bc, Lx, Ly, Nx, Ny, dt, T, b, V,
           user_action=action, version='vectorized')
    mlab.show()
#    print(e.min(), e.max(), e.mean())
    return
Example #49
0
# volume rendering
mlab.pipeline.volume(mlab.pipeline.scalar_field(s))
mlab.show()


# change the data limits
mlab.pipeline.volume(mlab.pipeline.scalar_field(s), vmin=0, vmax=0.8)
mlab.show()


# cut planes
mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                                 plane_orientation='x_axes',
                                 slice_index=10)
mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(s),
                                 plane_orientation='y_axes',
                                 slice_index=10)
mlab.outline()
mlab.show()


# combination
src = mlab.pipeline.scalar_field(s)
mlab.pipeline.iso_surface(src, contours=[s.min()+0.1*s.ptp(), ], opacity=0.1)  # ptp is the range 
mlab.pipeline.iso_surface(src, contours=[s.max()-0.1*s.ptp(), ],)
mlab.pipeline.image_plane_widget(src,
                                 plane_orientation='z_axes',
                                 slice_index=10)

mlab.show()
Example #50
0
#mlab.figure(bgcolor=(1,1,1))
#surf = mlab.surf(z,colormap='cool')
#mlab.show()
##访问surf对象的LUT
#用mlab.points3d建立红色和白色小球的集合
#选取事件

import numpy as np
from mayavi import mlab

figure = mlab.gcf()
x1, y1, z1 = np.random.random((3, 10))
red_glyphs = mlab.points3d(x1, y1, z1, color=(1, 0, 0), resolution=100)
x2, y2, z2 = np.random.random((3, 10))
white_glyphs = mlab.points3d(x2, y2, z2, color=(0.9, 0.9, 0.9), resolution=5)
outline = mlab.outline(line_width=3)
outline.outline_mode = 'cornered'
outline.bounds = (x1[0] - 0.1, x1[0] + 0.1, y1[0] - 0.1, y1[0] + 0.1,
                  z1[0] - 0.1, z1[0] + 0.1)
glyph_points = red_glyphs.glyph.glyph_source.glyph_source.output.points.to_array(
)


def picker_callback(picker):
    if picker.actor in red_glyphs.actor.actors:
        point_id = int(picker.point_id / glyph_points.shape[0])
        if point_id != -1:
            x, y, z = x1[point_id], y1[point_id], z1[point_id]
            outline.bounds = (x - 0.1, x + 0.1, y - 0.1, y + 0.1, z - 0.1,
                              z + 0.1)
def test_3_4(dx, dy, dt):
    """
    """
    bc = {'N': None, 'W': None, 'E': None, 'S': None}
    A = 2.3
    mx = 3
    my = 4
    c = 1  #
    b = 1.0
    Lx = 10
    Ly = 10
    T = 2*10/2.**.5
    w = 2*np.pi/T

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

    def u_e(x, y, t):
        kx = mx*np.pi/Lx
        ky = my*np.pi/Ly
        return A*np.cos(kx*x)*np.cos(ky*y)*np.cos(w*t)

    def f(x, y, t):
        res = A*(-Lx**2*Ly**2*w*(b*sin(t*w) + w*cos(t*w)) +
                 pi**2*Lx**2*c**2*my**2*cos(t*w) +
                 pi**2*Ly**2*c**2*mx**2*cos(t*w)) * \
            cos(pi*mx*x/Lx)*cos(pi*my*y/Ly)/(Lx**2*Ly**2)
        return res

    def I(x, y):
        return A*cos(pi*mx*x/Lx)*cos(pi*my*y/Ly)

    def V(x, y):
        return 0.0

    def q(x, y):
        return c**2

    Nt = int(round(T/float(dt)))
    Nx = int(round(Lx/float(dx)))
    Ny = int(round(Ly/float(dy)))
    x, y, dx, dy, dt = get_dt(Lx, Ly, Nx, Ny, dt, q)

    e = np.zeros((Nx+1, Ny+1, Nt+1))

    # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#surf
    test_extent = (0, Lx, 0, Ly, 0, 1)
    X, Y = np.meshgrid(x, y)
    Z = I(X, Y)
    mlab.figure(1, size=(1920, 1080), fgcolor=(1, 1, 1),
                bgcolor=(0.5, 0.5, 0.5))
    ms1 = mlab.surf(X.T, Y.T, Z.T, colormap='Spectral')
    ms2 = mlab.surf(X.T, Y.T, Z.T, color=(0.0, .0, .0),
                    representation="wireframe")
    mlab.outline(ms1, color=(0.7, .7, .7), extent=test_extent)
    ax = mlab.axes(ms1, color=(.7, .7, .7), extent=test_extent,
                   ranges=test_extent, xlabel='X', ylabel='Y',
                   zlabel='u(t)')
    ax.axes.label_format = '%.0f'
    mlab.view(142, -72, 32)

    def action(u, x, y, t, n):
        u_exakt = u_e(X.T, Y.T, t[n])
        e[:, :, n] = u_exakt-u

        ms1.mlab_source.set(z=u_exakt, scalars=u_exakt)
        ms2.mlab_source.set(z=u, scalars=u)
        mlab.title('standing undamped wave, t = {:.2f}'.format(t[n]))
        # concate filename with zero padded index number as suffix
        filename = os.path.join(out_path, '{}_{:06d}{}'.format(prefix, n, ext))
        print(filename)
        mlab.savefig(filename=filename)
        return

    solver(I, f, q, bc, Lx, Ly, Nx, Ny, dt, T, b, V,
           user_action=action, version='vectorized')
    mlab.show()
#    print(e.min(), e.max(), e.mean())
    return e, dx, dy, dt
Example #52
0
def mayaxes(title_string='VOID', xlabel='VOID', ylabel='VOID', zlabel='VOID', handle='VOID', \
    title_size=25, ticks=7, font_scaling=0.7, background='w'):

    if type(title_string) != str or type(xlabel) != str or type(
            ylabel) != str or type(zlabel) != str:
        print('ERROR: label inputs must all be strings')
        return
    elif type(ticks) != int:
        print('ERROR: number of ticks must be an integer')
        return
    elif type(font_scaling) != float and type(font_scaling) != int:
        print('Error: font scaling factor must be an integer or a float')
        return

    from mayavi.mlab import axes, title, gcf, outline

    # Create axes object
    ax = axes()

    # Font factor globally adjusts figure text size
    ax.axes.font_factor = font_scaling

    # Number of ticks along each axis
    ax.axes.number_of_labels = ticks

    # Set axis labels to input strings
    # (spaces are included for padding so that labels do not intersect with axes)
    if xlabel == 'void' or xlabel == 'Void' or xlabel == 'VOID':
        print 'X axis label title disabled'
    else:
        ax.axes.x_label = '          ' + xlabel

    if ylabel == 'void' or ylabel == 'Void' or ylabel == 'VOID':
        print 'Y axis label disabled'
    else:
        ax.axes.y_label = ylabel + '          '

    if zlabel == 'void' or zlabel == 'Void' or zlabel == 'VOID':
        print 'Z axis label disabled'
    else:
        ax.axes.z_label = zlabel + '     '

    # Create figure title
    if title_string == 'void' or title_string == 'Void' or title_string == 'VOID':
        print 'Figure title disabled'
    else:
        text_title = title(title_string)
        text_title.x_position = 0.5
        text_title.y_position = 0.9
        text_title.property.color = (0.0, 0.0, 0.0)
        text_title.actor.text_scale_mode = 'none'
        text_title.property.font_size = title_size
        text_title.property.justification = 'centered'

    # Create bounding box
    if handle == 'void' or handle == 'Void' or handle == 'VOID':
        print 'Bounding box disabled'
    else:
        if background == 'w':
            bounding_box = outline(handle, color=(0.0, 0.0, 0.0), opacity=0.2)
        elif background == 'b':
            bounding_box = outline(handle, color=(1.0, 1.0, 1.0), opacity=0.2)

    # Set axis, labels and titles to neat black text
    #ax.property.color = (0.0, 0.0, 0.0)
    #ax.title_text_property.color = (0.0, 0.0, 0.0)
    #ax.label_text_property.color = (0.0, 0.0, 0.0)
    ax.label_text_property.bold = False
    ax.label_text_property.italic = False
    ax.title_text_property.italic = False
    ax.title_text_property.bold = False

    # Reset axis range
    ax.axes.use_ranges = True

    # Set scene background, axis and text colours
    fig = gcf()
    if background == 'w':
        fig.scene.background = (1.0, 1.0, 1.0)
        ax.label_text_property.color = (0.0, 0.0, 0.0)
        ax.property.color = (0.0, 0.0, 0.0)
        ax.title_text_property.color = (0.0, 0.0, 0.0)
    elif background == 'b':
        fig.scene.background = (0.0, 0.0, 0.0)
        ax.label_text_property.color = (1.0, 1.0, 1.0)
        ax.property.color = (1.0, 1.0, 1.0)
        ax.title_text_property.color = (1.0, 1.0, 1.0)
    fig.scene.parallel_projection = True
Example #53
0
def plot(filename, number_bins=6):
    """Plot the cubes from a file.

    The cubes are stratified into number_bins norm bins. The
    transparency of the cubes is set depending on which norm bin the
    cube is in.
    """

    re_matrix_A = re.compile("^\s*Matrix A$")
    re_matrix_B = re.compile("^\s*Matrix B$")
    re_matrix_C = re.compile("^\s*Matrix C$")
    re_product_space = re.compile("^\s*Product Space$")

    fd = open(filename)
    (block_size, A_i, A_j, A_width_i, A_width_j,
     A_norm) = read_squares(fd, re_matrix_A, end=re_matrix_B)
    (block_size, B_i, B_j, B_width_i, B_width_j,
     B_norm) = read_squares(fd, re_matrix_B, end=re_matrix_C)
    (block_size, C_i, C_j, C_width_i, C_width_j,
     C_norm) = read_squares(fd, re_matrix_C, end=re_product_space)

    (prod_i, prod_j, prod_k, prod_width_i, prod_width_j, prod_width_k,
     prod_norm) = read_cubes(fd, re_product_space)

    # Get the current figure.
    figure = mlab.gcf()

    # Get the engine.
    engine = mlab.get_engine()

    # Clean the figure.
    mlab.clf()

    # Turn off rendering (for performance).
    figure.scene.disable_render = True

    # Tune background color.
    figure.scene.background = (1., 1., 1.)

    # Stratify matrix squares.
    (norms_stratified, A_i_stratified, A_j_stratified, A_width_i_stratified,
     A_width_j_stratified) = stratify(number_bins, A_norm, A_i, A_j, A_width_i,
                                      A_width_j)

    # Add matrices.
    print("Plotting matrix A")
    for i in range(number_bins):
        if len(A_i_stratified[i]) > 0:
            points = mlab.points3d(A_i_stratified[i],
                                   [1 for j in range(len(A_i_stratified[i]))],
                                   A_j_stratified[i],
                                   mode='cube',
                                   color=(0.0, 0.5019607843137255,
                                          0.5019607843137255),
                                   scale_factor=1,
                                   opacity=0.5 * (i + 1) / float(number_bins))

            points.glyph.glyph_source.glyph_source.x_length = block_size
            points.glyph.glyph_source.glyph_source.y_length = 0
            points.glyph.glyph_source.glyph_source.z_length = block_size

    (norms_stratified, B_i_stratified, B_j_stratified, B_width_i_stratified,
     B_width_j_stratified) = stratify(number_bins, B_norm, B_i, B_j, B_width_i,
                                      B_width_j)

    # Add matrices.
    print("Plotting matrix B")
    for i in range(number_bins):
        if len(B_i_stratified[i]) > 0:
            points = mlab.points3d([1 for j in range(len(B_i_stratified[i]))],
                                   B_j_stratified[i],
                                   B_i_stratified[i],
                                   mode='cube',
                                   color=(0.5019607843137255, 0.0, 0.0),
                                   scale_factor=1,
                                   opacity=0.5 * (i + 1) / float(number_bins))
            points.glyph.glyph_source.glyph_source.x_length = 0
            points.glyph.glyph_source.glyph_source.y_length = block_size
            points.glyph.glyph_source.glyph_source.z_length = block_size

    (norms_stratified, C_i_stratified, C_j_stratified, C_width_i_stratified,
     C_width_j_stratified) = stratify(number_bins, C_norm, C_i, C_j, C_width_i,
                                      C_width_j)

    # Add matrices.
    print("Plotting matrix C")
    for i in range(number_bins):
        if len(C_i_stratified[i]) > 0:
            points = mlab.points3d(C_i_stratified[i],
                                   C_j_stratified[i],
                                   [1 for j in range(len(C_i_stratified[i]))],
                                   mode='cube',
                                   color=(0.5019607843137255, 0.0,
                                          0.5019607843137255),
                                   scale_factor=1,
                                   opacity=0.5 * (i + 1) / float(number_bins))
            points.glyph.glyph_source.glyph_source.x_length = block_size
            points.glyph.glyph_source.glyph_source.y_length = block_size
            points.glyph.glyph_source.glyph_source.z_length = 0

    # Stratify cubes by norm.
    (norms_stratified, prod_i_stratified, prod_j_stratified,
     prod_k_stratified) = stratify(number_bins, prod_norm, prod_i, prod_j,
                                   prod_k)

    # Add cubes.
    print("Plotting product cubes")
    for i in range(number_bins):
        if len(prod_i_stratified[i]) > 0:
            points = mlab.points3d(prod_i_stratified[i],
                                   prod_j_stratified[i],
                                   prod_k_stratified[i],
                                   mode='cube',
                                   color=(0.2, .2, .2),
                                   scale_factor=1,
                                   opacity=0.75 * (i + 1) / float(number_bins))
            points.glyph.glyph_source.glyph_source.x_length = block_size
            points.glyph.glyph_source.glyph_source.y_length = block_size
            points.glyph.glyph_source.glyph_source.z_length = block_size

    i_max = max(numpy.amax(prod_i), numpy.amax(prod_j),
                numpy.amax(prod_k)) + block_size / 2
    print("i_max = {:e}".format(i_max))

    # Insert fake invisible data-set for axes.
    mlab.points3d([1, i_max], [1, i_max], [1, i_max],
                  mode='cube',
                  scale_factor=0)
    #mlab.axes(xlabel="i", ylabel="j", zlabel="k", extent=[1, xmax, 1, xmax, 1, xmax])

    # Box around the whole thing.
    mlab.outline(extent=[1, i_max, 1, i_max, 1, i_max])

    outline = engine.scenes[0].children[-1].children[0].children[1]
    outline.actor.property.color = (0, 0, 0)
    outline.actor.property.line_width = 2

    # Add axes.
    from mayavi.modules.axes import Axes
    axes = Axes()
    engine.add_module(axes, obj=None)

    axes.axes.label_format = '%-3.0f'
    axes.axes.width = 2
    axes.axes.x_label = 'i'
    axes.axes.y_label = 'j'
    axes.axes.z_label = 'k'
    axes.label_text_property.color = (0, 0, 0)
    axes.label_text_property.opacity = 0.0
    axes.label_text_property.shadow = True
    axes.label_text_property.shadow_offset = numpy.array([1, -1])
    axes.property.color = (0, 0, 0)
    axes.property.display_location = 'background'
    axes.title_text_property.color = (0, 0, 0)
    axes.title_text_property.shadow_offset = numpy.array([1, -1])

    figure.scene.disable_render = False
    figure.scene.camera.compute_view_plane_normal()

    import os.path
    #-------------------------------------------------------------------------------------------------------
    #./spammsand_invsqrt 33_x8_11_S.mm 1.d-1 1.d-3 1.d-1 1.d-1 D U R b=16
    #    figure.scene.isometric_view()
    #    png_filename = os.path.splitext(filename)[0] + "_isov.png"
    #    print("Saving image to " + png_filename)
    #    figure.scene.save(png_filename,size=(1024,1024))
    #    figure.scene.camera.position = [2381.7518163797836, 2526.3678093421449, 2530.13269951962]
    #    figure.scene.camera.focal_point = [440.00000000000028, 440.0000000000029, 439.99999999999733]
    #    figure.scene.camera.view_angle = 30.0
    #    figure.scene.camera.view_up = [-0.4189314063923294, -0.41776697205346547, 0.80620545383879905]
    #    figure.scene.camera.clipping_range = [1986.7866107311997, 5491.0522577990569]
    #    figure.scene.camera.compute_view_plane_normal()
    #    figure.scene.render()
    #    png_filename = os.path.splitext(filename)[0] + "_cant_x.png"
    #    print("Saving image to " + png_filename)
    #    figure.scene.save(png_filename,size=(1024,1024))

    #./spammsand_invsqrt water_500_to_6-311gss.mm 1.d-2 1.d-4 1.d-1 0.d0 D U R

    figure.scene.camera.position = [
        35816.735234550884, 38331.094829602851, 41443.525860211055
    ]
    figure.scene.camera.focal_point = [
        2614.1156973829502, 2621.6382407405645, -241.34477379674968
    ]
    figure.scene.camera.view_angle = 30.0
    figure.scene.camera.view_up = [
        -0.45361775222697864, -0.4654155004102597, 0.76001272807921516
    ]
    figure.scene.camera.clipping_range = [
        26313.825398895184, 87716.669164634935
    ]
    figure.scene.camera.compute_view_plane_normal()
    figure.scene.render()

    png_filename = os.path.splitext(filename)[0] + "_cant_x.png"
    print("Saving image to " + png_filename)
    figure.scene.save(png_filename, size=(768, 768))
Example #54
0
from mayavi import mlab
import numpy as np

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

face = mlab.surf(x,y,z,warp_scale =2)
axes = mlab.axes(xlabel = 'x',ylabel = 'y',zlabel = 'z', color = (0,0,0))

outline = mlab.outline(face,color = (0,0,0))
def pulse(C=1, Nx=200, Ny=0, animate=True, version='vectorized', T=2,
          loc='center', pulse_tp='gaussian', slowness_factor=2,
          medium=[0.7, 0.9], every_frame=1, sigma=0.05):
    """
    Various peaked-shaped initial conditions on [0,1].
    Wave velocity is decreased by the slowness_factor inside
    medium. The loc parameter can be 'center' or 'left',
    depending on where the initial pulse is to be located.
    The sigma parameter governs the width of the pulse.
    """
    # Use scaled parameters: L=1 for domain length, c_0=1
    # for wave velocity outside the domain.
    Lx = 1.0
    Ly = 1.0
    c_0 = 1.0
    if loc == 'center':
        xc = Lx/2
    elif loc == 'left':
        xc = 0

    if pulse_tp in ('gaussian', 'Gaussian'):

        def I(x):
            return exp(-0.5*((x-xc)/sigma)**2)

    elif pulse_tp == 'plug':

        def I(x):
            _I_ = np.ones_like(x)
            _I_[abs(x-xc) > sigma] = 0
            return _I_

    elif pulse_tp == 'cosinehat':

        def I(x):
            # One period of a cosine
            w = 2
            a = w*sigma
            return (0.5*(1 + np.cos(np.pi*(x-xc)/a))
                    if xc - a <= x <= xc + a else 0)

    elif pulse_tp == 'half-cosinehat':

        def I(x):
            # Half a period of a cosine
            w = 4
            a = w*sigma
            return (np.cos(np.pi*(x-xc)/a)
                    if xc - 0.5*a <= x <= xc + 0.5*a else 0)
    else:
        raise ValueError('Wrong pulse_tp="%s"' % pulse_tp)

    def c(x):
        return c_0/slowness_factor \
               if medium[0] <= x <= medium[1] else c_0

    ##############
    def q(x, y):
        if Ny == 0:
            l = x
        elif Nx == 0:
            l = y

        if isinstance(l, np.ndarray):
            _q_ = np.zeros_like(l).ravel()
            for i, elem in enumerate(np.nditer(l)):
                _q_[i] = c(elem)**2
            _q_.shape = l.shape
            return _q_
        else:
            return c(x)**2

    def I_2D(x, y):
        if Ny == 0:
            l = x
        elif Nx == 0:
            l = y
        return I(l)

    def f(x, y, t):
        return 0

    def V(x, y):
        return 0

    dt = 0  # is calculated in the solver
    b = 0
    bc = {'N': None, 'W': None, 'E': None, 'S': None}
    ##############

    # initialize plot
    # https://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html#surf
    test_extent = (0, Lx, 0, Ly, 0, 1)
    x = np.linspace(0, Lx, Nx+1)  # mesh points in x dir
    y = np.linspace(0, Ly, Ny+1)  # mesh points in y dir
    X, Y = np.meshgrid(x, y)
    Z = I_2D(X, Y)
    mlab.figure(1, size=(1920, 1080), fgcolor=(1, 1, 1),
                bgcolor=(0.5, 0.5, 0.5))
#    ms1 = mlab.surf(X.T, Y.T, Z.T, colormap='Spectral')
    ms2 = mlab.points3d(X.ravel(), Y.ravel(), Z.ravel(), color=(0.0, .0, .0),
                        scale_factor=.025)
    mlab.outline(ms2, color=(0.7, .7, .7), extent=test_extent)
    ax = mlab.axes(ms2, color=(.7, .7, .7), extent=test_extent,
                   ranges=test_extent, xlabel='X', ylabel='Y',
                   zlabel='u(t)')
    ax.axes.label_format = '%.0f'
    mlab.view(142, -72, 5)
    last_solution = Z.T

    def action(u, x, y, t, n):
        if n > 1:
            # every timestep exactly 2 cells change. If the wave is at the
            # boundary, only two cells change.
            msg = "the plug should travel exactly one cell per time step"
            cells_with_new_value = (u-last_solution) != 0
            print(np.sum(cells_with_new_value))
            assert ((np.sum(cells_with_new_value) == 4) |
                    (np.sum(cells_with_new_value) == 2) |
                    (np.sum(cells_with_new_value) == 0)), msg

        ms2.mlab_source.set(z=u)
        mlab.title('pulse, t = {:.2f}'.format(t[n]))
        last_solution[:, :] = u[:, :]
        # concate filename with zero padded index number as suffix
        filename = os.path.join(out_path, '{}_{:06d}{}'.format(prefix, n, ext))
        print(filename)
        mlab.savefig(filename=filename)
        return
    solver(I_2D, f, q, bc, Lx, Ly, Nx, Ny, dt, T, b, V,
           user_action=action, version='vectorized')
    mlab.show()
Example #56
0
    def plot3dstats(self, andarg,  alpha=0.0, outputfp="../results/combo_plot_mlab.png"):
        """
        plot3d plots the stastics for a given data frame.

        :param pd.DataFrame df: The given data frame to show stats for.
        :param str image: Is the image to plot at the bottom.
        """
        #"""
        conf = self._conf['3dplot']
        try:
            med,std,cov,_ = self.analyse_feature(andarg, ['u','v'])
        except ValueError as e:
            errmsg="To few samples in output"
            log.warn(errmsg)
            print(errmsg)
            return -1
        print(1)
        # First make the image
        df = self.select_data(andarg)
        # fig = plt.Figure(figsize=(15,15))
        fig = mlab.figure(bgcolor=(1,1,1))

        if conf['showimg']:
            if 'filename' in andarg.keys() and len(df) > 0:
                setdir = self.setdir
                image_path = f"{setdir}/images/{df['filename'].iloc[0]}"
                # Read the color image
                img:np.ndarray = cv2.imread(image_path)
                print(img.shape)

                # Resize the image
                # scale_percent = conf['resize']
                # width = int(img.shape[1] * scale_percent / 1000)
                # height = int(img.shape[0] * scale_percent / 1000)
                # dim = (width, height)
                # img = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)
                print(img.shape)
                # Convert to gray scale
                image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
                print(image.shape)
                obj=mlab.imshow(image)
                # obj.actor.orientation = np.rad2deg(camera.w_Rt_c.euler)
                # pp = np.array([0, 0, camera.f])[:,None]
                # w_pp = camera.w_Rt_c.forward(pp)
                # obj.actor.position = w_pp.ravel()
                # obj.actor.scale = [0.8, 0.8, 0.8]
            else:
                log.warn(f"andarg has no filename")
                raise IndexError("No filename was declared in andarg keys")

        # Drawing the NGD
        print(4)
        if not np.linalg.det(cov) == 0 and conf['plotstd']:
            rv = multivariate_normal(med, cov)
            zscaling = conf['zscaling']

            sample= self.select_data(andarg,['u','v'])
            imgsize = self.select_data(andarg,['width','height'])

            # Bounds parameters
            x_abs = np.max(imgsize.iloc[:,0])
            y_abs = np.max(imgsize.iloc[:,1])
            try:
                obj.actor.rotate_z(90)
                obj.actor.position = [x_abs/2,y_abs/2,0]
            except NameError:
                log.info("No image showed")
            xy_abs = np.max([x_abs,y_abs])
            ax_extent = [0,xy_abs,0,xy_abs]
            ax_ranges = [0,x_abs,0,y_abs, 0,conf['zplotrange']]

            # gstep = conf['gridstep']
            gstep = conf['resize']
            xx = np.arange(0,x_abs,gstep)
            yy = np.arange(0,y_abs,gstep)
            x_grid, y_grid = np.meshgrid(xx.T,yy.T)

            pos = np.empty(x_grid.shape + (2,))
            pos[:, :, 0] = x_grid
            pos[:, :, 1] = y_grid

            levels = np.linspace(0,1,40)

            # rv.pdf is the f(x,y)=z function
            z = zscaling*rv.pdf(pos)

            # plot the surface
            grid = mlab.surf(z.T,
                    # colormap='RdY1Bu',
                    # warp_scale=0.3,
                    warp_scale='auto',
                    representation='wireframe',
                    line_width=0.5,
                    extent=ax_ranges
                    )
            # Set opacity of the surface grid
            grid.actor.property.opacity = 0.5
            # grid.actor.rotate_z(180)

            # Shows the outline box aruond the figure
            mlab.outline(
                    color=(0, 0, 0),
                    opacity=0.8
                    )
            # plot the scatter for collected data:
            print(sample)
            print(sample.shape)
            xt = []
            yt = []
            zt = []
            tt = sample/conf['resize']
            value = [1*conf['markersize'] for _ in np.arange(0,sample.shape[0])]
            gt = lambda i,j: int(tt.iloc[i][j])
            w = np.max(imgsize['width'])
            for i in np.arange(0,sample.shape[0]):
                xt.append(-1*gt(i,0)*conf['resize'] + w)
                yt.append(1*gt(i,1)*conf['resize'])
                zt.append(z[gt(i,0), gt(i,1)])

            # z = zscaling*rv.pdf(zz)
            # mlab.points3d(sample['u'],sample['v'],z,value)
            pplot:mayavi.modules.glyph.Glyph = mlab.points3d(xt,yt,zt,value,scale_factor=1)



            # Showing or saving the figure
            cview = conf['view']
            mlab.view(
                    azimuth=cview['azimuth'],
                    distance=cview['distance'],
                    roll=cview['roll'])
            # mlab.show()
            # mlab.savefig("../results/combo_plot_mlab.png")
            mlab.savefig(outputfp)
            mlab.close()
Example #57
0
def View3D(g, path=None, gb=None):
    ##############################################################################
    # Resolution

    n = 51

    #compute Bxy
    [Br, Bz, x, y, q] = View2D(g, option=1)

    rd = g.r.max() + .5
    zd = g.z.max() + .5
    ##############################################################################
    # The grid of points on which we want to evaluate the field
    X, Y, Z = np.mgrid[-rd:rd:n * 1j, -rd:rd:n * 1j, -zd:zd:n * 1j]
    ## Avoid rounding issues :
    #f = 1e4  # this gives the precision we are interested by :
    #X = np.round(X * f) / f
    #Y = np.round(Y * f) / f
    #Z = np.round(Z * f) / f

    r = np.c_[X.ravel(), Y.ravel(), Z.ravel()]

    ##############################################################################
    # Calculate field
    # First initialize a container matrix for the field vector :
    B = np.empty_like(r)

    #Compute Toroidal field
    # fpol is given between simagx (psi on the axis) and sibdry (
    # psi on limiter or separatrix). So the toroidal field (fpol/R) and the q profile are within these boundaries
    # For each r,z we have psi thus we get fpol if (r,z) is within the boundary (limiter or separatrix) and fpol=fpol(outer_boundary) for outside

    #The range of psi is g.psi.max(), g.psi.min() but we have f(psi) up to the limit. Thus we use a new extended variable padded up to max psi
    # set points between psi_limit and psi_max

    add_psi = np.linspace(g.sibdry, g.psi.max(), 10)

    # define the x (psi) array
    xf = np.arange(np.float(g.qpsi.size)) * (
        g.sibdry - g.simagx) / np.float(g.qpsi.size - 1) + g.simagx

    # pad the extra values excluding the 1st value

    xf = np.concatenate((xf, add_psi[1::]), axis=0)

    # pad fpol with corresponding points

    fp = np.lib.pad(g.fpol, (0, 9), 'edge')

    # create interpolating function

    f = interpolate.interp1d(xf, fp)

    #calculate Toroidal field

    Btrz = old_div(f(g.psi), g.r)

    rmin = g.r[:, 0].min()
    rmax = g.r[:, 0].max()
    zmin = g.z[0, :].min()
    zmax = g.z[0, :].max()

    B1p, B2p, B3p, B1t, B2t, B3t = magnetic_field(g, X, Y, Z, rmin, rmax, zmin,
                                                  zmax, Br, Bz, Btrz)

    bpnorm = np.sqrt(B1p**2 + B2p**2 + B3p**2)
    btnorm = np.sqrt(B1t**2 + B2t**2 + B3t**2)

    BBx = B1p + B1t
    BBy = B2p + B2t
    BBz = B3p + B3t
    btotal = np.sqrt(BBx**2 + BBy**2 + BBz**2)

    Psi = psi_field(g, X, Y, Z, rmin, rmax, zmin, zmax)

    ##############################################################################
    # Visualization

    # We threshold the data ourselves, as the threshold filter produce a
    # data structure inefficient with IsoSurface
    #bmax = bnorm.max()
    #
    #B1[B > bmax] = 0
    #B2[B > bmax] = 0
    #B3[B > bmax] = 0
    #bnorm[bnorm > bmax] = bmax

    mlab.figure(1, size=(1080,
                         1080))  #, bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5))

    mlab.clf()

    fieldp = mlab.pipeline.vector_field(X,
                                        Y,
                                        Z,
                                        B1p,
                                        B2p,
                                        B3p,
                                        scalars=bpnorm,
                                        name='Bp field')

    fieldt = mlab.pipeline.vector_field(X,
                                        Y,
                                        Z,
                                        B1t,
                                        B2t,
                                        B3t,
                                        scalars=btnorm,
                                        name='Bt field')

    field = mlab.pipeline.vector_field(X,
                                       Y,
                                       Z,
                                       BBx,
                                       BBy,
                                       BBz,
                                       scalars=btotal,
                                       name='B field')

    field2 = mlab.pipeline.scalar_field(X, Y, Z, Psi, name='Psi field')

    #vectors = mlab.pipeline.vectors(field,
    #                      scale_factor=1,#(X[1, 0, 0] - X[0, 0, 0]),
    #                      )

    #vcp1 = mlab.pipeline.vector_cut_plane(fieldp,
    #                                        scale_factor=1,
    #                                        colormap='jet',
    #                                        plane_orientation='y_axes')
    ##
    #vcp2 = mlab.pipeline.vector_cut_plane(fieldt,
    #                                        scale_factor=1,
    #                                        colormap='jet',
    #                                        plane_orientation='x_axes')

    # Mask random points, to have a lighter visualization.
    #vectors.glyph.mask_input_points = True
    #vectors.glyph.mask_points.on_ratio = 6

    #vcp = mlab.pipeline.vector_cut_plane(field1)
    #vcp.glyph.glyph.scale_factor=5*(X[1, 0, 0] - X[0, 0, 0])
    # For prettier picture:
    #vcp1.implicit_plane.widget.enabled = False
    #vcp2.implicit_plane.widget.enabled = False

    iso = mlab.pipeline.iso_surface(field2,
                                    contours=[Psi.min() + .01],
                                    opacity=0.4,
                                    colormap='bone')

    for i in range(q.size):
        iso.contour.contours[i + 1:i + 2] = [q[i]]

    iso.compute_normals = True
    #

    #mlab.pipeline.image_plane_widget(field2,
    #                            plane_orientation='x_axes',
    #                            #slice_index=10,
    #                            extent=[-rd, rd, -rd, rd, -zd,zd]
    #                        )
    #mlab.pipeline.image_plane_widget(field2,
    #                            plane_orientation='y_axes',
    #                           # slice_index=10,
    #                            extent=[-rd, rd, -rd,rd, -zd,zd]
    #                        )

    #scp = mlab.pipeline.scalar_cut_plane(field2,
    #                                        colormap='jet',
    #                                        plane_orientation='x_axes')
    # For prettier picture and with 2D streamlines:
    #scp.implicit_plane.widget.enabled = False
    #scp.enable_contours = True
    #scp.contour.number_of_contours = 20

    #

    # Magnetic Axis

    s = mlab.pipeline.streamline(field)
    s.streamline_type = 'line'
    s.seed.widget = s.seed.widget_list[3]
    s.seed.widget.position = [g.rmagx, 0., g.zmagx]
    s.seed.widget.enabled = False

    #  q=i surfaces

    for i in range(np.shape(x)[0]):

        s = mlab.pipeline.streamline(field)
        s.streamline_type = 'line'
        ##s.seed.widget = s.seed.widget_list[0]
        ##s.seed.widget.center = 0.0, 0.0, 0.0
        ##s.seed.widget.radius = 1.725
        ##s.seed.widget.phi_resolution = 16
        ##s.seed.widget.handle_direction =[ 1.,  0.,  0.]
        ##s.seed.widget.enabled = False
        ##s.seed.widget.enabled = True
        ##s.seed.widget.enabled = False
        #
        if x[i].size > 1:
            s.seed.widget = s.seed.widget_list[3]
            s.seed.widget.position = [x[i][0], 0., y[i][0]]
            s.seed.widget.enabled = False

    # A trick to make transparency look better: cull the front face
    iso.actor.property.frontface_culling = True

    #mlab.view(39, 74, 0.59, [.008, .0007, -.005])
    out = mlab.outline(extent=[-rd, rd, -rd, rd, -zd, zd], line_width=.5)
    out.outline_mode = 'cornered'
    out.outline_filter.corner_factor = 0.0897222

    w = mlab.gcf()
    w.scene.camera.position = [
        13.296429046581462, 13.296429046581462, 12.979811259697154
    ]
    w.scene.camera.focal_point = [0.0, 0.0, -0.31661778688430786]
    w.scene.camera.view_angle = 30.0
    w.scene.camera.view_up = [0.0, 0.0, 1.0]
    w.scene.camera.clipping_range = [13.220595435695394, 35.020427055647517]
    w.scene.camera.compute_view_plane_normal()
    w.scene.render()
    w.scene.show_axes = True

    mlab.show()

    if (path != None):
        #BOUT data
        #path='../Aiba/'
        #
        #gb = file_import(path+'aiba.bout.grd.nc')
        #gb = file_import("../cbm18_8_y064_x516_090309.nc")
        #gb = file_import("cbm18_dens8.grid_nx68ny64.nc")
        #gb = file_import("/home/ben/run4/reduced_y064_x256.nc")

        data = collect('P', path=path)
        data = data[50, :, :, :]
        #data0=collect("P0", path=path)
        #data=data+data0[:,:,None]

        s = np.shape(data)
        nz = s[2]

        sgrid = create_grid(gb, data, 1)

        # OVERPLOT the GRID
        #mlab.pipeline.add_dataset(sgrid)
        #gr=mlab.pipeline.grid_plane(sgrid)
        #gr.grid_plane.axis='x'

        ## pressure scalar cut plane from bout
        scpb = mlab.pipeline.scalar_cut_plane(sgrid,
                                              colormap='jet',
                                              plane_orientation='x_axes')

        scpb.implicit_plane.widget.enabled = False
        scpb.enable_contours = True
        scpb.contour.filled_contours = True
        #
        scpb.contour.number_of_contours = 20
    #
    #
    #loc=sgrid.points
    #p=sgrid.point_data.scalars

    # compute pressure from scatter points interpolation
    #pint=interpolate.griddata(loc, p, (X, Y, Z), method='linear')
    #dpint=np.ma.masked_array(pint,np.isnan(pint)).filled(0.)
    #
    #p2 = mlab.pipeline.scalar_field(X, Y, Z, dpint, name='P field')
    #
    #scp2 = mlab.pipeline.scalar_cut_plane(p2,
    #                                        colormap='jet',
    #                                        plane_orientation='y_axes')
    #
    #scp2.implicit_plane.widget.enabled = False
    #scp2.enable_contours = True
    #scp2.contour.filled_contours=True
    #scp2.contour.number_of_contours = 20
    #scp2.contour.minimum_contour=.001

    # CHECK grid orientation
    #fieldr = mlab.pipeline.vector_field(X, Y, Z, -BBx, BBy, BBz,
    #                                  scalars=btotal, name='B field')
    #
    #sg=mlab.pipeline.streamline(fieldr)
    #sg.streamline_type = 'tube'
    #sg.seed.widget = sg.seed.widget_list[3]
    #sg.seed.widget.position=loc[0]
    #sg.seed.widget.enabled = False

    #OUTPUT grid

    #ww = tvtk.XMLStructuredGridWriter(input=sgrid, file_name='sgrid.vts')
    #ww.write()

    return
Example #58
0
import numpy as np

r, theta = np.mgrid[0:10, -np.pi:np.pi:10j]

x = r * np.cos(theta)

y = r * np.sin(theta)

z = np.sin(r) / r

from mayavi import mlab

s = mlab.mesh(x, y, z, colormap='gist_earth', extent=[0, 1, 0, 1, 0, 1])

mlab.mesh(x,
          y,
          z,
          extent=[0, 1, 0, 1, 0, 1],
          representation='wireframe',
          line_width=1,
          color=(0.5, 0.5, 0.5))
mlab.colorbar(s, orientation='vertical')
mlab.title('polar mesh')
mlab.outline(s)
mlab.axes(s)
mlab.savefig('3dmesh.png')
mlab.show()
Example #59
0
		mlab.figure(size=(1366,1366),fgcolor=(0,0,0),bgcolor=(1,1,1))
	
	if ARG1 == 'E':
		Ex = fin[str(n)]['Ex'][:]
		Ey = fin[str(n)]['Ey'][:]
		Ez = fin[str(n)]['Ez'][:]
		
		Ex = 0.5  *( Ex[ind(I-1,J-1,K-1)] + Ex[ind( I ,J-1,K-1)] )
		Ey = 0.5  *( Ey[ind(I-1,J-1,K-1)] + Ey[ind(I-1, J ,K-1)] )
		Ez = 0.5  *( Ez[ind(I-1,J-1,K-1)] + Ez[ind(I-1,J-1, K )] )
		
		field = mlab.pipeline.extract_vector_norm(mlab.pipeline.vector_field(Ex,Ey,Ez)); del Ex, Ey, Ez;
		mlab.text(0.65,0.9,'t = '+"%.4f"%(-1.5-0.5*Dt + n*Dt)+' s',width=0.3)
		color = (30./255,144./255,1)
		
		mlab.outline(extent=[0,200,0,200,0,200],opacity=0.2,color=(0,0,0))
		mlab.orientation_axes()
		
		if n == 60:
			line = mlab.pipeline.streamline(field, seedtype='sphere',seed_visible=True,integration_direction='both',vmin=0,vmax=1,color=color)
			line.streamline_type = 'tube'
			line.tube_filter.radius = 2
			line.stream_tracer.maximum_propagation = 500
			line.seed.widget.center = [100.5,100.5,100.75]
			line.seed.widget.radius = 10
			line.seed.widget.theta_resolution=5
			line.seed.widget.phi_resolution=5
			
			#line.seed.widget.enabled=False
		
		elif n == 1:
Example #60
0
def draw_dots3d(dots,
                edges,
                fignum,
                clear=True,
                title='',
                size=(1024, 768),
                graph_colormap='viridis',
                bgcolor=(1, 1, 1),
                node_color=(0.3, 0.65, 0.3),
                node_size=0.01,
                edge_color=(0.3, 0.3, 0.9),
                edge_size=0.003,
                text_size=0.14,
                text_color=(0, 0, 0),
                text_coords=[0.84, 0.75],
                text={},
                title_size=0.3,
                angle=get_ra()):

    # https://stackoverflow.com/questions/17751552/drawing-multiplex-graphs-with-networkx

    # numpy array of x, y, z positions in sorted node order
    xyz = shrink_to_3d(dots)

    if fignum == 0:
        mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)

    # Mayavi is buggy, and following code causes sockets leak.
    #if mlab.options.offscreen:
    #    mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)
    #elif fignum == 0:
    #    mlab.figure(fignum, bgcolor=bgcolor, fgcolor=text_color, size=size)

    if clear:
        mlab.clf()

    # the x,y, and z co-ordinates are here
    # manipulate them to obtain the desired projection perspective

    pts = mlab.points3d(
        xyz[:, 0],
        xyz[:, 1],
        xyz[:, 2],
        scale_factor=node_size,
        scale_mode='none',
        color=node_color,
        #colormap=graph_colormap,
        resolution=20,
        transparent=False)

    mlab.text(text_coords[0],
              text_coords[1],
              '\n'.join(['{} = {}'.format(n, v) for n, v in text.items()]),
              width=text_size)

    if clear:
        mlab.title(title, height=0.95)
        mlab.roll(next(angle))
        mlab.orientation_axes(pts)
        mlab.outline(pts)
    """
    for i, (x, y, z) in enumerate(xyz):
        label = mlab.text(x, y, str(i), z=z,
                          width=text_size, name=str(i), color=text_color)
        label.property.shadow = True
    """

    pts.mlab_source.dataset.lines = edges
    tube = mlab.pipeline.tube(pts, tube_radius=edge_size)
    mlab.pipeline.surface(tube, color=edge_color)