コード例 #1
0
ファイル: MakeEbbVideo.py プロジェクト: Rob-Rau/EbbCFD
def plotstate(Mesh, U, field, fname):
	V = Mesh['V']
	E = Mesh['E']
	BE = Mesh['BE']

	f = plt.figure(figsize=(12,6))

	F = pu.getField(U, field)
	plt.tripcolor(V[:,0], V[:,1], triangles=E, facecolors=F, shading='flat', vmin=1.55, vmax=1.9)

	for i in range(len(BE)):
		x = [V[BE[i,0],0], V[BE[i,1],0]]
		y = [V[BE[i,0],1], V[BE[i,1],1]]
		plt.plot(x, y, '-', linewidth=2, color='black')
	
	#dosave = (len(fname) != 0)

	plt.axis('equal')

	#plt.axis([-100, 100,-100, 100])
	plt.axis([-2, 10,-4, 4])
	plt.colorbar()
	#plt.clim(0, 0.8)
	plt.title(field, fontsize=16)

	f.tight_layout()
	plt.show()#block=(not dosave))
	#if (dosave):
	plt.savefig(fname)
	
	plt.close(f)
コード例 #2
0
ファイル: mapcon.py プロジェクト: jirivrany/riskflow123d-post
def draw_map(triangulation, options):
    '''
    get the triangle tuple (concentration, triangle] prepared before
    and draw the map of triangles
    options :
    "map_format": "svg",
    "map_file": "../../mapa"
    '''
    lab_x = options['xlabel'] if value_set(options, 'xlabel') else 'mesh X coord'
    lab_y = options['ylabel'] if value_set(options, 'ylabel') else 'mesh Y coord'
    lab_tit = options['title'] if value_set(options, 'title') else 'Map of concentrations'
    
    
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.tripcolor(triangulation['x_np'],
                  triangulation['y_np'],
                  triangulation['triangles'],
                  facecolors=triangulation['zfaces'],
                  edgecolors='k')
    plt.colorbar()
    plt.title(lab_tit)
    plt.xlabel(lab_x)
    plt.ylabel(lab_y)
    
    plt.savefig(options["map_file"], format=options["map_format"])               
コード例 #3
0
def test_tripcolor():
    x = np.asarray([0, 0.5, 1, 0,   0.5, 1,   0, 0.5, 1, 0.75])
    y = np.asarray([0, 0,   0, 0.5, 0.5, 0.5, 1, 1,   1, 0.75])
    triangles = np.asarray([
        [0, 1, 3], [1, 4, 3],
        [1, 2, 4], [2, 5, 4],
        [3, 4, 6], [4, 7, 6],
        [4, 5, 9], [7, 4, 9], [8, 7, 9], [5, 8, 9]])

    # Triangulation with same number of points and triangles.
    triang = mtri.Triangulation(x, y, triangles)

    Cpoints = x + 0.5*y

    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    Cfaces = 0.5*xmid + ymid

    plt.subplot(121)
    plt.tripcolor(triang, Cpoints, edgecolors='k')
    plt.title('point colors')

    plt.subplot(122)
    plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k')
    plt.title('facecolors')
def mplot_function(f, vmin, vmax, logscale):
    mesh = f.function_space().mesh()
    if (mesh.geometry().dim() != 2):
        raise AttributeError('Mesh must be 2D')
    # DG0 cellwise function
    if f.vector().size() == mesh.num_cells():
        C = f.vector().array()
        if logscale:
            return plt.tripcolor(mesh2triang(mesh), C, vmin=vmin, vmax=vmax, norm=cls.LogNorm() )
        else:
            return plt.tripcolor(mesh2triang(mesh), C, vmin=vmin, vmax=vmax)
    # Scalar function, interpolated to vertices
    elif f.value_rank() == 0:
        C = f.compute_vertex_values(mesh)
        if logscale:
            return plt.tripcolor(mesh2triang(mesh), C, vmin=vmin, vmax=vmax, norm=cls.LogNorm() )
        else:
            return plt.tripcolor(mesh2triang(mesh), C, shading='gouraud', vmin=vmin, vmax=vmax)
    # Vector function, interpolated to vertices
    elif f.value_rank() == 1:
        w0 = f.compute_vertex_values(mesh)
        if (len(w0) != 2*mesh.num_vertices()):
            raise AttributeError('Vector field must be 2D')
        X = mesh.coordinates()[:, 0]
        Y = mesh.coordinates()[:, 1]
        U = w0[:mesh.num_vertices()]
        V = w0[mesh.num_vertices():]
        C = np.sqrt(U*U+V*V)
        return plt.quiver(X,Y,U,V, C, units='x', headaxislength=7, headwidth=7, headlength=7, scale=4, pivot='middle')
コード例 #5
0
ファイル: MeshVisualizer.py プロジェクト: kezilu/pextant
 def draw(self, x = (), y=()):
     #px,py = self.points.to(self.env_model.ROW_COL)
     plt.tripcolor(self.x, self.y, self.mesh.faces, facecolors=self.zfaces, edgecolors='k')
     if len(x) != 0:
         plt.plot(x, y)
     plt.axis('equal')
     plt.show()
コード例 #6
0
ファイル: plotADCIRC.py プロジェクト: lcgraham/PolyADCIRC
def field(domain, z, title, clim = None,  path=None, save=True, show =
          False, ics=1, ext='.png', cmap=plt.cm.jet, fmt=None):
    """
    Given a domain, plot the nodal value z
   
    :param domain: :class:`~polyadcirc.run_framework.domain`
    :param z: :class:`numpy.ndarray`
    :param string title: plot title
    :param clim: :class:`numpy.clim`
    :type path: string or None
    :param path: directory to store plots
    :type save: bool
    :param save: flag for whether or not to save plots
    :type show: bool
    :param show: flag for whether or not to show plots
    :param int ics:  polar coordinate option (1 = cart coords, 2 = polar
        coords)
    :param string ext: file extension
    :param callable fmt: formatter for color bar, takes ``(x, pos)`` returns
        ``string`` 

    """
    if path is None:
        path = os.getcwd()
    plt.figure()
    plt.tripcolor(domain.triangulation, z, shading='gouraud',
                  cmap=cmap)
    plt.gca().set_aspect('equal')
    plt.autoscale(tight=True)
    if clim:
        plt.clim(clim[0], clim[1])
    add_2d_axes_labels(ics=ics)    
    colorbar(fmt=fmt)
    #plt.title(title)
    save_show(os.path.join(path, 'figs', title), save, show, ext)
コード例 #7
0
ファイル: mesh.py プロジェクト: JeroenMulkers/fem2d
 def showSolution(self,dim=2):
     from mpl_toolkits.mplot3d import Axes3D
     from matplotlib import cm, pyplot
     x,y,tri,solution,grad = [],[],[],[],[]
     for n in self.node:
         x.append(n.x)
         y.append(n.y)
         solution.append(n.value)
     for e in self.element:
         tri.append([n.id for n in e.node])
         grad.append(e.grad())
     if dim==2:
         pyplot.figure(figsize=(17,6))
         pyplot.subplot(1,2,1)
         pyplot.title("Solution")
         pyplot.tripcolor(x, y, tri, solution, cmap=cm.jet,  edgecolors='black')
         pyplot.colorbar()
         pyplot.subplot(1,2,2)
         pyplot.title("Gradient")
         pyplot.tripcolor(x, y, tri, grad, cmap=cm.jet,  edgecolors='black')
         pyplot.colorbar()
     elif dim==3:
         fig = pyplot.figure()
         ax = fig.gca(projection='3d')
         ax.plot_trisurf(x, y, tri, z, cmap=cm.jet, linewidth=0.2)
     pyplot.show()
コード例 #8
0
ファイル: bmi_plot.py プロジェクト: csdms/pymt
def quick_plot(bmi, name, **kwds):
    gid = bmi.var_grid(name)
    gtype = bmi.grid_type(gid)
    grid = bmi.grid[gid]

    x, y = grid.node_x.values, grid.node_y.values
    z = bmi.get_value(name)

    x_label = "{name} ({units})".format(
        name=grid.node_x.standard_name, units=grid.node_x.units
    )
    y_label = "{name} ({units})".format(
        name=grid.node_y.standard_name, units=grid.node_y.units
    )

    if gtype in ("unstructured_triangular",):
        tris = bmi.grid_face_node_connectivity(gid).reshape((-1, 3))
        plt.tripcolor(x, y, tris, z, **kwds)
    elif gtype in ("uniform_rectilinear", "structured_quad"):
        shape = bmi.grid_shape(gid)
        spacing = bmi.grid_spacing(gid)
        origin = bmi.grid_origin(gid)
        x = np.arange(shape[-1]) * spacing[-1] + origin[-1]
        y = np.arange(shape[-2]) * spacing[-2] + origin[-2]
        plt.pcolormesh(x, y, z.reshape(shape), **kwds)
    else:
        raise ValueError("no plotter for {gtype}".format(gtype=gtype))

    plt.axis("tight")
    plt.gca().set_aspect("equal")
    plt.xlabel(x_label)
    plt.ylabel(y_label)

    cbar = plt.colorbar()
    cbar.ax.set_ylabel("{name} ({units})".format(name=name, units=bmi.var_units(name)))
コード例 #9
0
ファイル: plottools.py プロジェクト: RobieH/Karsten-datatools
def el_plot(data, Map=False, show=True):
    """
    Plot the elevation for the region from the last time series
    
    :Parameters:
        **data** -- the standard python data dictionary
        
        **Map** -- {True, False} (optional): Optional argument.  If True,
            the elevation will be plotted on a map.  
    """
    trigrid = data['trigrid']
    plt.gca().set_aspect('equal')
    plt.tripcolor(trigrid, data['zeta'][-1,:])
    plt.colorbar()
    plt.title("Elevation")
    if Map:
        #we set the corners of where the map should show up
        llcrnrlon, urcrnrlon = plt.xlim()
        llcrnrlat, urcrnrlat = plt.ylim()
        #we construct the map.  Note that resolution serves to increase
        #or decrease the detail in the coastline.  Currently set to 
        #'i' for 'intermediate'
        m = Basemap(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, \
            resolution='i', suppress_ticks=False)
        #set color for continents.  Default is grey.
        m.fillcontinents(color='ForestGreen')
        m.drawmapboundary()
        m.drawcoastlines()
    if show:
        plt.show()
コード例 #10
0
ファイル: plotADCIRC.py プロジェクト: alarcher/PolyADCIRC
def field(domain, z, title, clim = None,  path=None, save=True, show =
          False, ics=1, ext='.png', cmap=plt.cm.jet):
    """
    Given a domain, plot the nodal value z
   
    :param domain: :class:`~polyadcirc.run_framework.domain`
    :param z: :class:`np.array`
    :param string title: plot title
    :param clim: :class:`np.clim`
    :type path: string or None
    :param path: directory to store plots
    :type save: boolean
    :param save: flag for whether or not to save plots
    :type show: boolean
    :param show: flag for whether or not to show plots
    :param int ics:  polar coordinate option (1 = cart coords, 2 = polar
        coords)
    :param string ext: file extension

    """
    if path == None:
        path = os.getcwd()
    plt.figure()
    plt.tripcolor(domain.triangulation, z, shading='gouraud',
                  cmap=cmap)
    plt.gca().set_aspect('equal')
    plt.autoscale(tight=True)
    if clim:
        plt.clim(clim[0], clim[1])
    add_2d_axes_labels(ics)    
    colorbar()
    #plt.title(title)
    save_show(path+'/figs/'+title, save, show, ext)
コード例 #11
0
ファイル: plot.py プロジェクト: jzrake/gusto
def triangle_vert_plot(filename, args):
    dset = gusto_dataset.GustoDataset(filename)
    x = dset.get_vert_variable('x1')
    z = dset.get_vert_variable('x3')
    f = dset.get_vert_variable(args.data)
    plt.tripcolor(x, z, f)
    plt.axis('equal')
コード例 #12
0
ファイル: plot.py プロジェクト: jzrake/gusto
def triangle_variable_plot(filename, args):
    dset = gusto_dataset.GustoDataset(filename)
    x = dset.get_cell_variable('x1')
    z = dset.get_cell_variable('x3')
    f = dset.get_cell_variable('dg')
    plt.tripcolor(x, z, f)
    plt.axis('equal')
    plt.colorbar()
コード例 #13
0
ファイル: lplot.py プロジェクト: danmfisher/TCC_SSWE
def plot_latlon_tri(lon=None, lat=None, data=None, title='Title', 
	vmin_in=CBAR_MINT, vmax_in=CBAR_MAXT):
	triang = tri.Triangulation(lon, lat)
	fig, ax = plt.subplots()
	plt.gca().set_aspect('equal')
	plt.tripcolor(triang, data, cmap=cm.jet, vmin=vmin_in, vmax=vmax_in)
	label_plot(fig, ax, title)
	return fig
コード例 #14
0
ファイル: tri_mesh_viewer.py プロジェクト: order/lcp-research
def plot_faces(nodes,faces,fn,cmap=None):
    fn = np.ma.array(fn,mask=~np.isfinite(fn))
    assert(fn.size == faces.shape[0])
    if cmap is None:
        cmap = plt.get_cmap('jet')
    cmap.set_bad('w',1.)
    plt.gca()
    plt.tripcolor(nodes[:,0],nodes[:,1],faces,facecolors=fn,
                  edgecolor='k',cmap=cmap)
    plt.colorbar()
コード例 #15
0
ファイル: unsteady2dfem1.py プロジェクト: GuiAlmeidaPC/FEM
def postprocessor(nodes, val):
    x = nodes[:, 0]
    y = nodes[:, 1]

    fig = plt.figure()
    plt.gca().set_aspect('equal')
    plt.tripcolor(x,y,elements,facecolors=val,edgecolors='k')
    plt.colorbar()
    plt.title("Poisson's equation")
    plt.xlabel('x')
    plt.ylabel('y')
    #plt.savefig("FEM.png")
    plt.show()
コード例 #16
0
ファイル: ISSM Element Numbering.py プロジェクト: wuw94/ISSM
def highlightTriangle(index): #give this function the index of element and it will highlight
    clickedTriangleX = [x[elements[index][0]],x[elements[index][1]],x[elements[index][2]]]
    clickedTriangleY = [y[elements[index][0]],y[elements[index][1]],y[elements[index][2]]]
    plt.tripcolor(clickedTriangleX,clickedTriangleY,[0,1,2],cmap=plt.cm.Accent)
    a = elements[index]
    x1 = x[a[0]]
    x2 = x[a[1]]
    x3 = x[a[2]]
    y1 = y[a[0]]
    y2 = y[a[1]]
    y3 = y[a[2]]
    centroid = tuple(((x1+x2+x3)/3,(y1+y2+y3)/3))
    if centroid not in visible:
        visible[centroid] = plt.text(centroid[0], centroid[1], '.' + str(index))
コード例 #17
0
ファイル: ISSM Element Numbering.py プロジェクト: wuw94/ISSM
def onclick(event): #print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(event.button, event.x, event.y, event.xdata, event.ydata))
    #print(event.button, event.x, event.y, event.xdata, event.ydata)
    if event.xdata < maxX and event.xdata > minX and event.ydata < maxY and event.ydata > minY:
        if event.key in ['alt+q','q'] or event.key in ['alt+w','w']:
            # TODO: put clicked triangles into an array
            # after a certain number of clicks, we want to remake the plot, to prevent recursion depth error
            if event.xdata < maxX or event.xdata > minX or event.ydata < maxY or event.ydata > minY:
                jump = index = len(orderedCentroids) // 2
                
                # Complexity of log(n) - ordered binary search to get to the nearest X
                while True:
                    jump = jump //2
                    if jump < 1 or event.xdata == orderedCentroids[index][0]:
                        break
                    index += jump * (int(event.xdata > orderedCentroids[index][0]) - int(event.xdata < orderedCentroids[index][0]))
                
                # Bounce outward checking if point is inside triangle who's centroid is centroid of list (to skip Y checking)
                jump = 1
                while True:
                    if inTriangle(event.xdata,event.ydata,allTriangles[orderedCentroids[index]]):
                        break
                    index += jump * (1-2*(jump % 2 == 0))
                    jump += 1

                # Find which 3 points make up the triangle
                clickedTriangle = allTriangles[orderedCentroids[index]]
                clickedTriangleX = [clickedTriangle[0][0],clickedTriangle[1][0],clickedTriangle[2][0]]
                clickedTriangleY = [clickedTriangle[0][1],clickedTriangle[1][1],clickedTriangle[2][1]]

            if event.key in ['alt+q','q']:
                if orderedCentroids[index] not in visible:
                    plt.tripcolor(clickedTriangleX,clickedTriangleY,[0,1,2],cmap=plt.cm.Accent)
                    visible[orderedCentroids[index]] = plt.text(orderedCentroids[index][0], orderedCentroids[index][1], '.' + str(clickedTriangle[3]))
            elif event.key in ['alt+w','w']:
                if orderedCentroids[index] in visible:
                    plt.tripcolor(clickedTriangleX,clickedTriangleY,[0,1,2],cmap=plt.cm.Greys)
                    visible[orderedCentroids[index]].remove()
                    del visible[orderedCentroids[index]]
            
        elif event.key in ['alt+e','e']:
            typedInput = input('Enter triangle index to highlight:  ')
            try:
                typedInput = int(typedInput)
                highlightTriangle(typedInput)
            except:
                print('Invalid Input')

        plt.draw()
コード例 #18
0
def plot_f_m3d_hdf5_2D(filename,time_id,data_id,plane_id):
	import matplotlib.pyplot as plt
	import matplotlib.tri as triangle
	from matplotlib.pyplot import figure, axes, plot, xlabel, ylabel, title, \
		grid, savefig, show
	(timeframe,nnode_1_plane,R,Z,trianlist,data_name,data_2D)=readhdf5_f_time_data(filename,time_id,data_id,plane_id)
	#plt.gca().set_aspect('equal')
	tri=triangle.Triangulation(R,Z)
	fig = figure(figsize=(6,8))
	plt.tripcolor(tri,data_2D)
	plt.xlabel('R')
	plt.ylabel('Z');
	title_str=format('%s, t=%f'%(data_name,timeframe))
	plt.title(title_str)
	plt.colorbar()
	plt.show()
コード例 #19
0
ファイル: timing_data.py プロジェクト: pwolfram/scrIpT
  def plot(self, savename, astr='.*_fcomp(.*)_focean(.*)_CPL', xlabel='fcomp', ylabel='focean'):
    """ astr is used to build indices from files"""
    matcher = re.compile(astr)
    matches = [(matcher.findall(af)[0][0], matcher.findall(af)[0][1], val) for af, val in zip(self.files, self.vals) if matcher.findall(af) != []]
    points = np.squeeze(np.asarray(matches, dtype='f8'))

    plt.figure()
    tri = Triangulation(points[:,0], points[:,1])
    plt.tripcolor(tri, points[:,2], cmap='viridis')
    plt.colorbar()
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.title(self.units)
    plt.savefig(savename + '.png')

    return #}}}
コード例 #20
0
ファイル: supernova_sph.py プロジェクト: stevemcmillan/amuse
def X_plot_sph(particles, time= 0.0|units.day):

    pyplot.rcParams.update({'font.size': 30})
    figure = pyplot.figure(figsize=(12, 12))
    #f, ax = pyplot.subplots(1,2, sharex=True, sharey=True)    
    
    x = particles.x.value_in(units.RSun)
    y = particles.y.value_in(units.RSun)
    z = particles.rho.value_in(units.g/units.cm**3)

    cax = pyplot.tripcolor(x,y,z)
    max_dens = z.max()
    min_dens = z.min()
    mid_dens = 0.5*(max_dens+min_dens)
    #    cbar = pyplot.colorbar()
    print "dens=", min_dens, mid_dens, max_dens

#    cbar = figure.colorbar(cax, ticks=[min_dens, mid_dens, max_dens], orientation='vertical', fraction=0.045)

#    cbar.ax.set_yticklabels(['Low', ' ', 'High']) 
#    cbar.set_label('mid-plane density', rotation=270)

    pyplot.xlim(0, 10)
    pyplot.ylim(0, 10)
    pyplot.xlabel("x [R$_\odot$]")
    pyplot.ylabel("y [R$_\odot$]")
    t = int(time.value_in(units.s))
    filename = "supernova_sph_T"+str(t)+".png"
    pyplot.savefig(filename)
    pyplot.show()
コード例 #21
0
def plot_fill(value_array,title,sym=0):
    x = nodearray[:,0]
    y = nodearray[:,1]
    triangles = np.array(elements)
    
    if sym:
        x = np.append(x,-x)
        y = np.append(y,y)
        triangles = np.vstack((triangles, triangles+np.amax(triangles)+1))
        value_array = np.append(value_array,value_array) 
    
    plt.figure()
    plt.title(title)
    plt.axes().set_aspect('equal')        
    plt.tripcolor(x,y,triangles,value_array, edgecolors='k',cmap=plt.get_cmap('jet'))
    plt.colorbar()
コード例 #22
0
ファイル: PlotMeshes.py プロジェクト: Rob-Rau/EbbCFD
def plotmesh(Mesh, color):
	V = Mesh['V']
	E = Mesh['E']
	BE = Mesh['BE']

	F = np.zeros((np.size(E)/3, 1))
	F = F[:,0]
	F[:] = 1
	plt.tripcolor(V[:,0], V[:,1], triangles=E, facecolors=F, edgecolors=color, cmap=plt.cm.gray, vmin=0, vmax=1, alpha=1, linewidth=0.5)

	for i in range(len(BE)):
		x = [V[BE[i,0],0], V[BE[i,1],0]]
		y = [V[BE[i,0],1], V[BE[i,1],1]]
		plt.plot(x, y, '-', linewidth=2.5, color=color)

	plt.axis('equal')
	plt.axis([-100, 100,-100, 100])
コード例 #23
0
ファイル: ElasticProblem.py プロジェクト: GuiAlmeidaPC/FEM
def plot_mizes(nodes, elements, mizes, saveimage=False):
    x = nodes[:, 0]
    y = nodes[:, 1]

    plt.figure()
    plt.gca().set_aspect('equal')
    plt.tripcolor(x, y, elements, facecolors=mizes, edgecolors='k')
    plt.colorbar()
    plt.title("von-Mizes stress")
    plt.xlabel('x')
    plt.ylabel('y')
    plt.axis('tight')

    if saveimage == True:
        plt.savefig("mizes.png")
        
    plt.show()
コード例 #24
0
def Plot3DFile(fname, CMAP='gist_rainbow', x=1, y=2, z=3):
    Inarray=np.loadtxt(fname);
    X=Inarray[:,x-1];
    Y=Inarray[:,y-1];
    Z=Inarray[:,z-1];
    ax=plt.subplot()
    p=plt.tripcolor(X, Y, Z, cmap=CMAP)
    plt.colorbar(p, ax=ax)
    return
コード例 #25
0
ファイル: plotADCIRC.py プロジェクト: lcgraham/PolyADCIRC
def station_locations(domain, path=None, bathy = False, save=True, 
                      show=False, ics=1, ext='.png', station_markers=None):
    """
    Given a domain, plot the observation stations 
   
    :param domain: :class:`~polyadcirc.run_framework.domain`
    :type path: string or None
    :param path: directory to store plots
    :type bathy: bool
    :param bathy: flat for whether or not to show bathymetry
    :type save: bool
    :param save: flag for whether or not to save plots
    :type show: bool
    :param show: flag for whether or not to show plots
    :param int ics: coordinate system (1 cartisian, 2 polar)
    :param string ext: file extesion
 
    """
    plt.figure()
    if path is None:
        path = os.getcwd()
    if bathy:
        z = np.array([n.bathymetry for n in domain.node.itervalues()])
        plt.tripcolor(domain.triangulation, z, shading='gouraud',
                      cmap=plt.cm.ocean)
        plt.gca().set_aspect('equal')
    else:
        plt.triplot(domain.triangulation, 'k-')
        plt.gca().set_aspect('equal')

    if station_markers is None:
        station_markers = _stationmarkers
    
    for k, v in domain.stations.iteritems():
        x = np.array([e.x for e in v])
        y = np.array([e.y for e in v])
        plt.plot(x, y, station_markers[k], label = k)
    
    #plt.title('station locations')
    add_2d_axes_labels(ics=ics)    
    #plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
    #           ncol=2, mode="expand", borderaxespad=0.)
    save_show(os.path.join(path, 'figs', 'station_locations'), save, show, ext)
コード例 #26
0
ファイル: plotADCIRC.py プロジェクト: lcgraham/PolyADCIRC
def bathymetry(domain, path=None, save=True, show=False, mesh = False,
               contour = False, ics=1, ext='.png', title=False):
    """
    Given a domain, plot the bathymetry

    :param domain: :class:`~polyadcirc.run_framework.domain`
    :type path: string or None
    :param path: directory to store plots
    :type save: bool
    :param save: flag for whether or not to save plots
    :type show: bool
    :param show: flag for whether or not to show plots
    :type mesh: bool
    :param mesh: flag for whether or not to show mesh
    :param bool contour: use :meth:`~np.pyplot.tripcolor` or
        :meth:`~np.pyplot.tricontour`
    :param int ics: coordinate system (1 cartisian, 2 polar)
    :param string ext: file extesion

    """
    z = domain.array_bathymetry()
    vmax = np.max(z)
    vmin = np.min(z)
    clim = (vmin, vmax)
    if path is None:
        path = os.getcwd()
    plt.figure()
    if mesh:
        plt.triplot(domain.triangulation, 'k-')
    if not contour:
        plt.tripcolor(domain.triangulation, z, shading='gouraud',
                      cmap=plt.cm.ocean)
    else:
        plt.tricontourf(domain.triangulation, z, cmap=plt.cm.ocean)
    plt.gca().set_aspect('equal')
    add_2d_axes_labels(ics=ics)    
    if clim:
        plt.clim(clim[0], clim[1])
    if title:
        plt.title('bathymetry')
    colorbar()
    save_show(os.path.join(path, 'figs', 'bathymetry'), save, show, ext)
コード例 #27
0
	def computeScatteringMatrix(self,Mmax):
		# -- Prepare scattering matrix. 
		scatMat = np.zeros((2*Mmax+1,2*Mmax+1), dtype=np.complex)

		for n in range(2*Mmax+1):
			m = n-Mmax
			# -- Prepare the vector and matrix
			b = np.zeros((self.nTriangles), dtype=np.complex)
			M = np.zeros((self.nTriangles,self.nTriangles), dtype=np.complex)
	
			for i in range(self.nTriangles):
				b[i] = jn(m, self.k*np.linalg.norm(self.centerPoints[i]))*np.exp(1j*m*user_mod(np.arctan2(self.centerPoints[i,1],self.centerPoints[i,0]),2*np.pi))
	
				for j in range(self.nTriangles):
					if (i!=j):
						d = self.k*np.linalg.norm(self.centerPoints[i]-self.centerPoints[j])
						phi1 = user_mod(np.arctan2(self.centerPoints[i,1],self.centerPoints[i,0]),2*np.pi)
						phi2 = user_mod(np.arctan2(self.centerPoints[j,1],self.centerPoints[j,0]),2*np.pi)
						M[i,j] = self.potential*self.k*self.k*1j*hankel1(0, d)*self.areas[j]/4.0
	
			x = np.linalg.solve(np.eye(self.nTriangles,self.nTriangles, dtype=np.complex)-M,b)
			fig2 = plt.figure(figsize=(3,3))
			ax2 = fig2.add_subplot(111)
			ax2.axis('off')
			plt.tripcolor(self.points[:,0], self.points[:,1],self.triangulation.simplices, np.abs(x))
			plt.savefig("intensityTest-%s.pdf" %(self.N))
			

			# -- We compute the corresponding line of the scattering matrix.
			for k in range(2*Mmax+1):
				mp = k-Mmax
				Smm = 0.0
				for h in range(self.nTriangles):
					d = self.k*np.linalg.norm(self.centerPoints[h])
					phi = user_mod(np.arctan2(self.centerPoints[h,1],self.centerPoints[h,0]),2*np.pi)
					Smm += self.potential*jn(mp,d)*np.exp(-1j*mp*phi)*x[h]*self.areas[h]

				Smm = self.k*self.k*1j*Smm/2.0
				Smm += (1.0 if mp==m else 0.0)
				scatMat[k,n] = Smm

		return scatMat
コード例 #28
0
ファイル: visualizer.py プロジェクト: Veterun/cryoem-cvpr2015
def plotwinkeltriple(d,v, vmin=None, vmax=None):
    """ Plots a winkel projection of a function on a sphere evaluated at directions d
    v - values
    """
    
#     phi = n.arctan2(d[:,2],n.linalg.norm(d[:,0:2],axis=1)).reshape((-1,))
    phi = n.arctan2(d[:,2],n.linalg.norm(d[:,0:2],axis=1)).reshape((-1,))
    theta = n.arctan2(d[:,1],d[:,0]).reshape((-1,))

    x,y = winkeltriple(theta,phi)
    
    t_border = n.concatenate( [ n.linspace(n.pi,-n.pi,50), n.ones(50)*-n.pi, n.linspace(-n.pi,n.pi,50), n.ones(50)*n.pi ] )
    ph_border = n.concatenate( [ n.ones(50)*-n.pi/2.0, n.linspace(-n.pi/2,n.pi/2.0,50), n.ones(50)*n.pi/2.0, n.linspace(n.pi/2.0,-n.pi/2.0,50) ] )
    x_border,y_border = winkeltriple(t_border,ph_border)

    plt.hold(True)
    plt.tripcolor(x,y,1e-10 + v,shading='gourad',vmin=vmin+1e-10,vmax=vmax+1e-10,norm=colors.LogNorm())
    plt.plot(x_border,y_border,'-k')
    plt.colorbar()
    plt.show()
コード例 #29
0
def Compare3DFiles(fname1, fname2, CMAP='gist_rainbow', x=1, y=2, z1=3, z2=3):
    Inarray=np.loadtxt(fname1);
    X=Inarray[:,x-1];
    Y=Inarray[:,y-1];
    Z1=Inarray[:,z1-1];
    Inarray2=np.loadtxt(fname2);
    Z2=Inarray2[:,z2-1];
    difZ=Z1-Z2
    ax=plt.subplot()
    p=plt.tripcolor(X, Y, difZ, cmap=CMAP)
    plt.colorbar(p, ax=ax)
    return
コード例 #30
0
ファイル: plotq2_unst.py プロジェクト: smoe1/ImplicitExplicit
def plotq2_unst(outputdir, n1, m, meqn, NumPhysElems, NumPhysNodes, 
                xlow, xhigh, ylow, yhigh, time, x, y, 
                tnode, qsoln, xmid, ymid, qsoln_elem):

    import numpy as np
    import matplotlib.pyplot as plt
    from math import sqrt
    from math import pow
    from math import cos
    from math import sin
    from math import pi

    plt.figure(1)
    plt.clf()
    plt.gca().set_aspect('equal')
    plt.gca().set_xlim([xlow,xhigh])
    #plt.gca().set_ylim([ylow,yhigh])
    p1=plt.tripcolor(x, y, tnode, qsoln[:,m], shading='faceted', vmin=0.0, vmax=1.0)
    tmp1 = "".join(("q(",str(m+1),") at t = "))
    tmp2 = "".join((tmp1,str(time)))
    title = "".join((tmp2,"     [DoGPack]"))
    plt.title(title)
    plt.colorbar()
    plt.draw()


    x0 = -0.25*cos(2.0*pi*time) + 0.50
    y0 =  0.25*sin(2.0*pi*time) + 0.50
    r = np.zeros(NumPhysElems,float)
    for i in range(0,NumPhysElems):
        r[i] = sqrt(pow(xmid[i]-x0,2)+pow(ymid[i]-y0,2))
    ind = r.argsort()
    qscat_ex = np.zeros((NumPhysElems,meqn),float)
    qex(NumPhysElems,meqn,r,qscat_ex)

    err = np.linalg.norm(qscat_ex[:,m]-qsoln_elem[:,m])/np.linalg.norm(qscat_ex[:,m])
    print ""
    print "  Error = ",'{:e}'.format(err)
    print ""
    
    plt.figure(2)
    plt.clf()
    plt.gca().set_aspect('auto')
    plt.gca().set_xlim([0.0,0.5])
    #plt.gca().set_ylim([0.0,1.0])
    plt.plot(r[ind],qscat_ex[ind,m],'k-')
    plt.plot(r[ind],qsoln_elem[ind,m],'bo')
    tmp1 = "".join(("Scattor plot of q(",str(m+1),") at t = "))
    tmp2 = "".join((tmp1,str(time)))
    title = "".join((tmp2,"     [DoGPack]"))
    plt.title(title)
    plt.draw()
コード例 #31
0
ファイル: plotting.py プロジェクト: erdc/podrbf_nirom
def viz_sol(uh, nodes, triangles):
    """
    Visualize the NIROM and HFM solutions over the physical domain
    """

    boundaries = np.linspace(np.amin(uh), np.amax(uh), 11)
    cf = plt.tripcolor(nodes[:, 0],
                       nodes[:, 1],
                       triangles,
                       uh,
                       shading='gouraud')
    plt.axis('equal')

    return cf, boundaries
コード例 #32
0
ファイル: langmuir.py プロジェクト: puncproject/PUNC
def plot(obj, title):
    plt.gca().set_aspect('equal')
    if isinstance(obj, df.Function):
        mesh = obj.function_space().mesh()
        if (mesh.geometry().dim() != 2):
            raise (AttributeError)
        if obj.vector().size() == mesh.num_cells():
            C = obj.vector().get_local()
            plt.tripcolor(mesh2triang(mesh), C, cmap='viridis')
            plt.colorbar()
            plt.title(title)
        else:
            C = obj.compute_vertex_values(mesh)
            plt.tripcolor(mesh2triang(mesh),
                          C,
                          shading='gouraud',
                          cmap='viridis')
            plt.colorbar()
            plt.title(title)
    elif isinstance(obj, df.Mesh):
        if (obj.geometry().dim() != 2):
            raise (AttributeError)
        plt.triplot(mesh2triang(obj), color='k')
コード例 #33
0
def test_tripcolor():
    x = np.asarray([0, 0.5, 1, 0, 0.5, 1, 0, 0.5, 1, 0.75])
    y = np.asarray([0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1, 0.75])
    triangles = np.asarray([[0, 1, 3], [1, 4, 3], [1, 2, 4], [2, 5, 4],
                            [3, 4, 6], [4, 7, 6], [4, 5, 9], [7, 4, 9],
                            [8, 7, 9], [5, 8, 9]])

    # Triangulation with same number of points and triangles.
    triang = mtri.Triangulation(x, y, triangles)

    Cpoints = x + 0.5 * y

    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    Cfaces = 0.5 * xmid + ymid

    plt.subplot(121)
    plt.tripcolor(triang, Cpoints, edgecolors='k')
    plt.title('point colors')

    plt.subplot(122)
    plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k')
    plt.title('facecolors')
コード例 #34
0
def plot_SubTh2simp2D(q, me, u, **kwargs):
    plane = kwargs.pop('plane', True)
    shading = kwargs.pop('shading', 'gouraud')
    kwargs['vmin'] = kwargs.get('vmin', np.min(u))
    kwargs['vmax'] = kwargs.get('vmax', np.max(u))
    fig = plt.gcf()
    if plane:
        return plt.tripcolor(
            q[:, 0], q[:, 1], me, u, shading=shading,
            **kwargs)  #vmin=vmin,vmax=vmax, shading=shading,**kwargs)
    nq = q.shape[0]
    assert isinstance(u, np.ndarray) and u.shape[0] == nq
    Q = np.concatenate((q, u.reshape((nq, 1))), axis=1)
    return plot_SubTh2simp3D(Q, me, u, **kwargs)
コード例 #35
0
ファイル: plotting.py プロジェクト: erdc/podrbf_nirom
def viz_err(uh, snap, nodes, triangles):
    """
    Visualize the NIROM solution relative error over the domain
    """

    cf3 = plt.tripcolor(nodes[:, 0],
                        nodes[:, 1],
                        triangles,
                        uh - snap,
                        shading='flat')
    plt.axis('equal')
    cb = plt.colorbar(cf3)

    return cf3
コード例 #36
0
def plotCSpaceDelaunayGrey(fname1,fname2,P1,P2,maximumEdgeLength=0.2, shade=0.8):
  points2D=np.vstack([P1,P2]).T
  print(points2D)
  tri = Delaunay(points2D)
  # print tri.simplices.shape, '\n', tri.simplices[0]

  triangles = np.empty((0,3),dtype=int)

  for i in range(0, tri.simplices.shape[0]):
    simplex = tri.simplices[i]
    x = tri.points[simplex[0]]
    y = tri.points[simplex[1]]
    z = tri.points[simplex[2]]
    d0 = np.sqrt(np.dot(x-y,x-y))
    d1 = np.sqrt(np.dot(x-z,x-z))
    d2 = np.sqrt(np.dot(z-y,z-y))
    max_edge = max([d0, d1, d2])
    if max_edge <= maximumEdgeLength:
      triangles = np.vstack((triangles, simplex))
  
  zFaces = np.ones(triangles.shape[0])
  cmap = colors.LinearSegmentedColormap.from_list("", [(shade,shade,shade),"grey","grey"])
  plt.tripcolor(P1, P2, triangles, cmap=cmap, facecolors=zFaces,edgecolors='none')
コード例 #37
0
def postprocessor(nodes, slv):
    x = nodes[:, 0]
    y = nodes[:, 1]

    # Color value
    val = []
    for element in elements:
        p0 = slv[element[0]]
        p1 = slv[element[1]]
        p2 = slv[element[2]]
        val.append((p0 + p1 + p2) / 3.)
    val = array(val)

    plt.figure()
    plt.gca().set_aspect('equal')
    plt.tripcolor(x, y, elements, facecolors=val, edgecolors='k')
    plt.colorbar()
    plt.title("Poisson's equation")
    plt.xlabel('x')
    plt.ylabel('y')
    #plt.savefig("FEM.png")
    plt.show()
    print "val\n", val
コード例 #38
0
ファイル: esp.py プロジェクト: mjms3/helo
    def plot_shortest_path(self, start, end, subdivisions=1):
        graph = self._create_graph(self.triangulation, subdivisions=subdivisions)
        cost, path = self.shortest_path(start, end, subdivisions)

        plt.figure()
        plt.gca().set_aspect('equal')
        for edge in graph:
            p1 = edge[0]
            p2 = edge[1]
            plt.plot([p1[0], p2[0]], [p1[1], p2[1]], 'g:', alpha=0.5)
        tri_plot = plt.tripcolor(self.triangulation, self.triangle_weights, cmap=plt.cm.RdYlGn_r)
        plt.plot([p[0] for p in path], [p[1] for p in path], 'k', lw=3)
        plt.colorbar(tri_plot)
        plt.show()
コード例 #39
0
ファイル: mesh_processing.py プロジェクト: neurospin/nitk
def isomap_patch(mesh, mask, show=False):
    """return low-dimensional coordinates for the the patch

    Parameters
    ==========
    mesh: string or nibabel mesh,
          the input mesh to be cherted
    mask: string or array of shape (n_vertices)
          a mask for the region of interest on the mesh
    show: boolean, optional,
          if yes, make an image of the coordinates
    """
    from sklearn.manifold.isomap import Isomap
    # Read the data
    coord, tri = mesh_arrays(mesh)
    if isinstance(mask, basestring):
        mask = gifti.read(mask).darrays[0].data > 0
    else:
        mask = mask.astype(np.bool)
    coord, tri = coord[mask], tri[mask[tri].all(1)]
    tri = np.hstack((0, np.cumsum(mask)[:-1]))[tri]

    # perform the dimension reduction
    xy = Isomap().fit_transform(coord)

    # try to make the sign invariant and repect the orientations
    xy *= np.sign((xy**3).sum(0))
    a, b, c = tri[0]
    xy[:,
       1] *= np.sign(np.linalg.det(np.vstack((xy[b] - xy[a], xy[c] - xy[a]))))

    if show:
        import matplotlib.pyplot as plt
        plt.figure()
        plt.tripcolor(xy.T[0], xy.T[1], tri, (xy**2).sum(1), shading='faceted')
        plt.show()
    return xy
コード例 #40
0
ファイル: visualizer.py プロジェクト: lqhuang/SOD-cryoem
def plotwinkeltriple(d, v, vmin=None, vmax=None):
    """ Plots a winkel projection of a function on a sphere evaluated at directions d
    v - values
    """

    # phi = np.arctan2(d[:,2],np.linalg.norm(d[:,0:2],axis=1)).reshape((-1,))
    phi = np.arctan2(d[:, 2], np.linalg.norm(d[:, 0:2], axis=1)).reshape(
        (-1, ))
    theta = np.arctan2(d[:, 1], d[:, 0]).reshape((-1, ))

    x, y = winkeltriple(theta, phi)

    t_border = np.concatenate([
        np.linspace(np.pi, -np.pi, 50),
        np.ones(50) * -np.pi,
        np.linspace(-np.pi, np.pi, 50),
        np.ones(50) * np.pi
    ])
    ph_border = np.concatenate([
        np.ones(50) * -np.pi / 2.0,
        np.linspace(-np.pi / 2, np.pi / 2.0, 50),
        np.ones(50) * np.pi / 2.0,
        np.linspace(np.pi / 2.0, -np.pi / 2.0, 50)
    ])
    x_border, y_border = winkeltriple(t_border, ph_border)

    plt.hold(True)
    plt.tripcolor(x,
                  y,
                  1e-10 + v,
                  shading='gouraud',
                  vmin=vmin + 1e-10,
                  vmax=vmax + 1e-10,
                  norm=colors.LogNorm())
    plt.plot(x_border, y_border, '-k')
    plt.colorbar()
    plt.show()
コード例 #41
0
    def plt_im_tri(self,
                   depth,
                   fig_name,
                   show_file=True,
                   vmin_=21.0,
                   vmax_=29.0):
        mesh = loadmat("mesh.mat")
        triangles = mesh['triangles']
        meshnode = mesh['meshnode']
        # velocity_obs_loc = np.loadtxt("observation_loc_drogue12345_50ft.dat")
        # bathy = loadmat('true.mat')
        # z_in = np.squeeze(bathy['s_true'])
        # true in meter
        matplotlib.rcParams.update({'font.size': 16})

        offsetx = 220793.
        offsety = 364110.
        fig_index = 1
        plt.figure(fig_index, figsize=(10., 10.), dpi=100)
        fig_index += 1
        ax = plt.gca()
        im = plt.tripcolor(meshnode[:, 0] * 0.3010 - offsetx,
                           meshnode[:, 1] * 0.3010 - offsety,
                           triangles,
                           depth * 0.301,
                           cmap=plt.get_cmap('jet'),
                           vmin=vmin_,
                           vmax=vmax_,
                           label='_nolegend_')
        ax.set_xlabel("Easting [m]")
        ax.set_ylabel("Northing [m]")
        plt.gca().set_aspect('equal', adjustable='box')

        plt.axis([0., 1000., 0., 530.])
        plt.xticks(np.arange(0., 1000. + 10., 200.0))
        plt.yticks(np.arange(0., 530. + 10., 200.0))

        cbar = plt.colorbar(im, fraction=0.025, pad=0.05)
        # cbar = plt.colorbar(im, pad=0.05 )
        cbar.set_label('Elevation [m]')
        plt.rcParams['axes.axisbelow'] = True
        plt.rc('axes', axisbelow=True)
        plt.grid()
        ax.set_axisbelow(True)

        plt.tight_layout()
        plt.savefig(fig_name)
        if show_file:
            plt.show()
コード例 #42
0
def plotq2np_unst(m,meqn,NumPhysElems,NumPhysNodes,xlow,xhigh,ylow,yhigh,time,x,y,tnode,qsoln,xmid,ymid,qsoln_elem,FRAME):
    
    import matplotlib.pyplot as plt

    plt.figure(FRAME)
    plt.clf()
    plt.gca().set_aspect('equal')
    plt.gca().set_xlim([xlow,xhigh])
    plt.gca().set_ylim([ylow,yhigh])
    p1=plt.tripcolor(x, y, tnode, qsoln[:,m], shading='flat')
    tmp1 = "".join(("q(",str(m+1),") at t = "))
    tmp2 = "".join((tmp1,str(time)))
    title = "".join((tmp2,"     [DoGPack]"))
    plt.title(title)
    plt.draw()
コード例 #43
0
def plot_tree(n,
              res=100,
              scaling="normal",
              colorbar=False,
              cmap="RdBu_r",
              clim=None):
    import dufte
    import meshzoo
    from matplotlib import pyplot as plt

    plt.style.use(dufte.style)

    bary, cells = meshzoo.triangle(res)
    evaluator = Eval(bary, scaling)

    plt.set_cmap(cmap)
    plt.gca().set_aspect("equal")
    plt.axis("off")

    for k, level in enumerate(itertools.islice(evaluator, n + 1)):
        for r, z in enumerate(level):
            alpha = numpy.pi * numpy.array([7.0 / 6.0, 11.0 / 6.0, 3.0 / 6.0])
            corners = numpy.array([numpy.cos(alpha), numpy.sin(alpha)])
            corners[0] += 2.1 * (r - k / 2)
            corners[1] -= 1.9 * k
            x, y = numpy.dot(corners, bary)

            plt.tripcolor(x, y, cells, z, shading="flat")
            plt.clim(clim)

            # triangle outlines
            X = numpy.column_stack([corners, corners[:, 0]])
            plt.plot(X[0], X[1], "-k")

    if colorbar:
        plt.colorbar()
コード例 #44
0
def plot_carpet_2d(mesh, f, result_path):

    num_cells = mesh.num_cells()
    num_verts = mesh.num_vertices()
    d = mesh.geometry().dim()

    # Create the triangulation
    mesh_coordinates = mesh.coordinates().reshape((num_verts, d))
    triangles = numpy.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)

    # Get the z values as face colors for each triangle(midpoint)
    fig = plt.figure()

    # Get the z values for each vertex
    plt.figure()
    plt.xlabel('x')
    plt.ylabel('y')
    z = numpy.asarray([f(point) for point in mesh_coordinates])
    plt.tripcolor(triangulation, z, cmap=cm.coolwarm, edgecolors='k')
    fig = plt.gcf()
    fig.savefig(result_path + "-cells-%d-vertices-%d.eps" %
                (num_cells, num_verts))
コード例 #45
0
ファイル: plot.py プロジェクト: mstiegl/BERNAISE
def plot_faces(coords, faces, face_values=None, title=None,
               clabel=None, colorbar=True, save=None, show=True,
               latex=False):
    """ Plot a mesh with values given at faces. """
    if face_values is None:
        colors = np.arange(len(faces))
        clabel = "Face number"
    else:
        colors = face_values
    fig = Figure(title=title, clabel=clabel, colorbar=colorbar,
                 save=save, show=show, latex=latex)
    fig.colorbar_ax = plt.tripcolor(coords[:, 0], coords[:, 1], faces,
                                    facecolors=colors, edgecolors='k')
    ax = plt.gca()
    ax.set_xlim([coords[:, 0].min(), coords[:, 0].max()])
    ax.set_ylim([coords[:, 1].min(), coords[:, 1].max()])
    return fig
コード例 #46
0
    def plot_sphere_a(self, sph):
        self.fig = plt.figure()
        #self.ax = self.fig.add_subplot(111, projection='3d')#.gca(projection='3d')projection = 'mollweide'
        #self.ax = self.fig.add_subplot(111)#, projection = '3d') #'mollweide')#.gca(projection='3d')projection = 'mollweide'
        #self.ax.view_init(elev=90., azim=0)

        #self.ax.axis([-1,1,-1,1, -1, 1])
        """
        self.ax.set_xlim(-0.55, 0.55)
        self.ax.set_ylim(-0.55, 0.55)
        self.ax.set_zlim(-0.55, 0.55)
        """
        #plt.gca().set_aspect('equal')
        #axes = plt.gca()
        #axes.set_xlim([-4,4])
        #axes.set_ylim([-5,35])
        self.x, self.y, self.z = sph.ch.points[
            sph.ch.vertices][:, 0], sph.ch.points[
                sph.ch.vertices][:, 1], sph.ch.points[sph.ch.vertices][:, 2]
        #print("self.x", self.x)
        #self.avg = (self.xc+ self.yc+ self.zc)/3
        #self.x, self.y = sph.Mercator_Projection(-2.3*np.pi/8.)#sph.Mercator_Projection()#s#Mollewide
        self.z = np.zeros(self.x.shape)
        self.triangles = sph.ch.simplices
        #self.xy=np.vstack((self.x, self.y)).T
        #tri = Delaunay(self.xy)
        #tris =mtri.Triangulation(self.x, self.y)
        #self.triangles = tris.triangles
        #self.ax.tricontour(triangles = self.triangles, Z=self.z)#, cmap=plt.cm.Greys_r, antialiased=False)
        #self.surf = self.ax.
        #self.triangles = tri.simplices
        #mask = [s]
        self.surf = plt.tripcolor(
            self.x, self.y, self.triangles, facecolors=self.triangles[:, 0]
        )  #facecolours = self.triangles[:,0], edgecolors = 'k')#, cmap=plt.cm.Greys_r, antialiased=False)
        #self.surf = self.ax.plot_trisurf(self.x,self.y,self.z, triangles=sph.ch.simplices, cmap=plt.cm.Greys_r, alpha = 1)
        #self.surf.set_array(colours)
        #sph.icosahedron_vertices=np.asarray(sph.icosahedron_vertices)
        #self.ax.scatter(sph.icosahedron_vertices[:,0],sph.icosahedron_vertices[:,1], sph.icosahedron_vertices[:,2], c='red')

        plt.show()
        return self.surf, self.fig
コード例 #47
0
ファイル: demo_dolfin.py プロジェクト: AxlaCode/AmorFEA
def plot_sol(args, name, vmin=None, vmax=None):
    path = args.root_path + '/' + args.solutions_path + \
        '/dolfin/' + name + '000000.vtu'
    x, u, tri = get_topology(path)
    colors = u
    fig = plt.figure(figsize=(8, 8))
    plt.gca().set_aspect('equal')
    plt.axis('off')
    # shading='gouraud'
    tpc = plt.tripcolor(x[:, 0],
                        x[:, 1],
                        tri,
                        colors,
                        shading='flat',
                        vmin=vmin,
                        vmax=vmax)
    cb = plt.colorbar(tpc, aspect=20, shrink=0.5)
    cb.ax.tick_params(labelsize=20)
    fig.savefig(args.root_path + '/images/dolfin/' + name + '.png',
                bbox_inches='tight')
コード例 #48
0
def plot(f, is_accurate, to_save):
    n = mesh.num_vertices()
    d = mesh.geometry().dim()
    mesh_coordinates = mesh.coordinates().reshape((n, d))
    triangles = np.asarray([cell.entities(0) for cell in cells(mesh)])
    triangulation = tri.Triangulation(mesh_coordinates[:, 0],
                                      mesh_coordinates[:, 1], triangles)

    fig, ax = plt.subplots()
    zfaces = np.asarray([f(cell.midpoint()) for cell in cells(mesh)])
    ax_plot = plt.tripcolor(triangulation, facecolors=zfaces, edgecolors='k')
    fig.colorbar(ax_plot, ax=ax)
    if is_accurate:
        plt.title('Точное U')
        if to_save:
            plt.savefig('accurate.png')
    else:
        plt.title('Вычисленное U')
        if to_save:
            plt.savefig('calculated.png')
    plt.close()
    return fig
コード例 #49
0
def plot_component(mesh, u, component):
    """ plots a single component of a vector field as a heat maps """
    try:
        w0 = u.compute_vertex_values(mesh)
    except AttributeError:
        uu = project(u)
        w0 = uu.compute_vertex_values(mesh)
    
    n = mesh.num_vertices()
    start = component*n
    stop = (component+1)*n
    tt = w0[start:stop]

    top = max(tt)
    bottom = min(tt)
    fig = plt.figure()    
    cax = plt.tripcolor(mesh2triang(mesh), tt, cmap = cm.coolwarm)
    plt.xlabel('x [$\mu$m]', fontsize=18)
    plt.ylabel('y [$\mu$m]', fontsize=18)
    plt.colorbar()
    plt.tight_layout()
    plt.tick_params(labelsize=16)
    plt.show()
    return fig
コード例 #50
0
    def plot_results(self, soln, okada_soln):
        pts, tris = self.all_mesh
        est = self.get_pt_soln(soln)

        vmax = np.max(okada_soln)
        for d in range(3):
            plt.figure()
            plt.tripcolor(
                pts[:, 0],
                pts[:, 1],
                tris,
                est[:, d],  #shading='gouraud',
                cmap='PuOr',
                vmin=-vmax,
                vmax=vmax)
            plt.title("u " + ['x', 'y', 'z'][d])
            plt.colorbar()

        for d in range(3):
            plt.figure()
            plt.tripcolor(
                pts[:, 0],
                pts[:, 1],
                tris,
                okada_soln[:, d],  #shading='gouraud',
                cmap='PuOr',
                vmin=-vmax,
                vmax=vmax)
            plt.title("Okada u " + ['x', 'y', 'z'][d])
            plt.colorbar()

        for d in range(3):
            plt.figure()
            plt.tripcolor(
                pts[:, 0],
                pts[:, 1],
                tris,
                okada_soln[:, d] - est[:, d],  #shading='gouraud',
                cmap='PuOr')
            plt.title("Diff u " + ['x', 'y', 'z'][d])
            plt.colorbar()

        plt.show()
コード例 #51
0
sio.savemat('data/misc/fishcage/cage_elements_sfm6_musq2.mat',mdict=tempdic)


np.savetxt('data/misc/fishcage/cage_elements_sfm6_musq2.dat',newhost+1,fmt='%i')

drag=np.zeros([newhost.shape[0],])+0.6
depth=np.zeros([newhost.shape[0],])+10

fvcom_savecage('data/misc/fishcage/sfm6_musq2_cage.dat',newhost+1,drag,depth)

trihost=np.zeros([data['uvnodell'].shape[0],])
trihost[newhost]=1

f=plt.figure()
ax=f.add_axes([.125,.1,.775,.8])
triax=plt.tripcolor(data['trigrid'],trihost)
ax.triplot(data['trigrid'],lw=.2)
region={}
region['region']=np.array([-66.925, -66.8,45.0,45.075])
prettyplot_ll(ax,setregion=region,grid=True)
plt.title('Locations with cages')

#eidx=get_elements(data,region)
#for ele in eidx:
    #ax.text(data['uvnodell'][ele,0],data['uvnodell'][ele,1],"{}".format(ele+1))

f.savefig(savepath + 'cage_host_locations_new.png',dpi=2400)
plt.close(f)


remove=np.array([7090,7210,7209,6970,7211,19545,16462,25848,25889,25887,25886,
コード例 #52
0
ファイル: main.py プロジェクト: IgorBaratta/pyMLPG
dmed = (mesh.hmax() + mesh.hmin()) / 2
Xn = nodes(coord)
Xn.set_neighborhood(nei)

# Number of subdomains
nd = 10
K = dok_matrix((Xn.size, Xn.size), dtype=np.complex)
k = 2 * np.pi
f = np.zeros(Xn.size, dtype=np.complex)

A, f = assemble(Xn, k)
u_d = spsolve(A, f)

triang = mesh2triang(mesh)
plt.gca().set_aspect('equal')
plt.tripcolor(triang, np.real(u_d), shading='gouraud')
plt.show()

dx = nd
ovl = 0.1
list_mesh = submeshes(mesh, nd, dx, ovl, Verbose=False)
r, rd = indices(list_mesh, mesh)

R = []
D = []
K = []
Kinv = []
for j in range(nd):
    Ri, Di = restriction(len(r[j]), mt, r[j], rd)
    submesh = list_mesh[j]
    nei = connect(submesh)
コード例 #53
0
import random
import matplotlib.pyplot as plot
import matplotlib.tri as tri


count = 100
X = [random.random() for i in range(count)]
Y = [random.random() for i in range(count)]
Z = [0.] * count

triangles = tri.Triangulation(X, Y)

plot.tripcolor(triangles, Z, edgecolors='w')
plot.show()
コード例 #54
0
plt.title("Caso 2")
plt.ylabel("Temperatura")
plt.xlabel("Tiempo")
plt.legend( loc ='best')
plt.savefig('C2_Tpromedio.png')
plt.close()





C1_ab_xyt = np.genfromtxt("C1_abiertas_x_y_T.dat",comments='T')

n=441;
plt.tripcolor(C1_ab_xyt[0:n+1,0],C1_ab_xyt[0:n+1,1],C1_ab_xyt[0:n+1,2])
plt.title("Caso 1-Abiertas-T 0 ")
plt.ylabel("Y")
plt.xlabel("X")
plt.colorbar()
plt.savefig('C1_ab_T0.png')
plt.close()

plt.tripcolor(C1_ab_xyt[n+1:2*n+1,0],C1_ab_xyt[n+1:2*n+1,1],C1_ab_xyt[n+1:2*n+1,2])
plt.title("Caso 1-Abiertas-T 100 ")
plt.ylabel("Y")
plt.xlabel("X")
plt.colorbar()
plt.savefig('C1_ab_T2.png')
plt.close()
コード例 #55
0
host_lt_depth=np.where((data['uvh'][newhost]<=maxdepth) & (data['uvh'][newhost]>=mindepth))[0]
newhostbool=np.zeros(shape=newhost.shape,dtype=bool)
newhostbool[host_lt_depth]=True

newhost=newhost[host_lt_depth.flatten()]

tempdic={}
tempdic['kelp_elements']=newhost
#sio.savemat('kelp_elements_kit4.mat',mdict=tempdic)


np.savetxt('data/grid_stuff/kelpnodes_'+grid+'.dat',newhost+1,fmt='%i')

drag=np.zeros([newhost.shape[0],])+0.018
depth=np.zeros([newhost.shape[0],])+40

fvcom_savecage('data/cage_files/'+grid+'_cage_'+("%d"%mindepth)+'m_'+("%d"%maxdepth)+'m.dat',newhost+1,drag,depth)

trihost=np.zeros([data['uvnodell'].shape[0],])
trihost[newhost]=1

plt.close()
plt.tripcolor(data['trigrid'],trihost)
plt.colorbar()
plt.grid()
plt.axis(region['region'])
plt.title('Locations with kelp')
plt.savefig(savepath +grid+'_'+regionname+ 'kelp_host_locations_3.png',dpi=1200)
plt.close()

コード例 #56
0
# -*- coding: utf-8 -*-
"""
Created on Sun Sep  9 22:35:18 2018

@author: zdlls
"""

import matplotlib.pyplot as plt
import numpy as np

data = np.loadtxt('waveguide.txt')
x = data[:, 0]
y = data[:, 1]
z = data[:, 2]
plt.tripcolor(x, y, z)
plt.show()
コード例 #57
0
fldvplot[fldspeedplot <= .01] = np.nan
Q = plt.quiver(data['uvnodell'][sidx, 0],
               data['uvnodell'][sidx, 1],
               flduplot[sidx],
               fldvplot[sidx],
               angles='xy',
               scale_units='xy',
               scale=10)
qk = plt.quiverkey(Q, .2, 1.05, 0.25, '0.25 ms^-1', labelpos='W')
plt.grid()
plt.axis(region['region'])
plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
plt.savefig(savepath + name + '_' + regionname + '_vector_maxfld_s_' +
            ("%d" % spacing) + '.png',
            dpi=1200)

#plot max speed
plt.close()
plt.tripcolor(
    data['trigrid'],
    np.max(np.sqrt(newu**2 + newv**2), axis=0),
    vmin=1.15 *
    np.min(np.max(np.sqrt(newu[:, sidx]**2 + newv[:, sidx]**2), axis=0)),
    vmax=.85 *
    np.max(np.max(np.sqrt(newu[:, sidx]**2 + newv[:, sidx]**2), axis=0)))
plt.colorbar()
plt.grid()
plt.axis(region['region'])
plt.gca().get_xaxis().get_major_formatter().set_useOffset(False)
plt.savefig(savepath + name + '_' + regionname + '_maxspeed.png', dpi=1200)
コード例 #58
0
ファイル: PlotEbbSolution.py プロジェクト: Rob-Rau/EbbCFD
def plotstate(Mesh, U, field, fname, clim1, clim2, color, plotExact, plotError):
	V = Mesh['V']
	E = Mesh['E']
	BE = Mesh['BE']

	#f = plt.figure(figsize=(12,6))
	F = pu.getField(U, field)

	if((plotExact == True) or (plotError == True)):
		Exact = F
		s = field.lower()
		if (s == 'pressure'):
			Exact = pu.p_a(V[:,0], V[:,1])
			#F = ((pr - F)/pr)*100.
		elif (s == 'density'):
			Exact = pu.rho_a(V[:,0], V[:,1])
			#F = ((rho_a - F)/rho_a)*100.
		elif (s == 'xmomentum'):
			Exact = pu.rho_a(V[:,0], V[:,1])*pu.u_a(V[:,0], V[:,1])
			#F = ((ru_a - F)/ru_a)*100.
		elif (s == 'ymomentum'):
			Exact = pu.rho_a(V[:,0], V[:,1])*pu.v_a(V[:,0], V[:,1])
			#F = ((rv_a - F)/rv_a)*100.
		elif (s == 'energy'):
			Exact = pu.E_a(V[:,0], V[:,1])
			#F = ((E_a - F)/E_a)*100.
		elif (s == 'renergy'):
			Exact = pu.rE_a(V[:,0], V[:,1])
			#F = ((rE_a - F)/rE_a)*100.
		elif (s == 'xvelocity'):
			Exact = pu.u_a(V[:,0], V[:,1])
			#F = ((u_a - F)/u_a)*100.
		elif (s == 'yvelocity'):
			Exact = pu.v_a(V[:,0], V[:,1])
			#F = ((v_a - F)/v_a)*100.

		if(plotError == True):
			F = np.abs(Exact - F)
			#F = ((Exact - F)/Exact)*100.

		if(plotExact == True):
			F = Exact

		clim1 = np.min(F)
		clim2 = np.max(F)

	if(F.shape[0] == V.shape[0]):
		plt.tripcolor(V[:,0], V[:,1], F, triangles=E, shading='gouraud', edgecolors=color, vmin=clim1, vmax=clim2, linewidth=1)
		#plt.tripcolor(V[:,0], V[:,1], F, triangles=E, shading='flat', edgecolors=color, vmin=clim1, vmax=clim2, linewidth=1)
	else:
		plt.tripcolor(V[:,0], V[:,1], triangles=E, facecolors=F, shading='flat', vmin=clim1, vmax=clim2, linewidth=1)

	for i in range(len(BE)):
		x = [V[BE[i,0],0], V[BE[i,1],0]]
		y = [V[BE[i,0],1], V[BE[i,1],1]]
		plt.plot(x, y, '-', linewidth=2, color='black')
	
	dosave = (len(fname) != 0)

	plt.axis('equal')

	#plt.axis([-100, 100,-100, 100])
	#plt.axis([-0.5, 1.5, -0.75, 1.5])
	#plt.colorbar()
	#plt.clim(0, 0.7)
	#plt.clim(9, 12)

	if(plotError == True):
		plt.title(field+' error', fontsize=16)
	elif(plotExact == True):
		plt.title(field+' exact', fontsize=16)
	else:
		plt.title(field, fontsize=16)
コード例 #59
0
ファイル: gproc.j.py プロジェクト: NelisW/RBF
# differentiate the posterior with respect to x
derivative_gp = posterior_gp.differentiate((1, 0))

# evaluate the posterior and posterior derivative at the interpolation
# points. calling the GaussianProcess instances will return their mean
# and standard deviation at the provided points.
post_mean, post_std = posterior_gp(xitp)
diff_mean, diff_std = derivative_gp(xitp)

## Plotting

# plot the true function
utrue = true_function(xitp)
plt.figure(1)
plt.title('True function')
p = plt.tripcolor(xitp[:, 0], xitp[:, 1], utrue, cmap='viridis')
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.colorbar(p)
plt.tight_layout()

# plot the interpolant
plt.figure(2)
plt.title('RBF interpolant (dots are observations)')
p = plt.tripcolor(xitp[:, 0], xitp[:, 1], post_mean, cmap='viridis')
# plot the observations
plt.scatter(xobs[:, 0],
            xobs[:, 1],
            c=uobs,
            s=40,
            edgecolor='k',
コード例 #60
0
t = t_start

i = 0
while t < t_end:
    print 'time =', t

    u0.assign(u)

    solve(a == L, u, bc)

    plt.figure()
    zfaces = numpy.asarray([u(cell.midpoint()) for cell in cells(mesh)])
    plt.tripcolor(triangulation,
                  facecolors=zfaces,
                  edgecolors='k',
                  vmin=0,
                  vmax=2)
    plt.colorbar()
    kurs = "result/%i.png" % i
    plt.savefig(kurs, format='png')
    plt.close()

    TotFlux = assemble(div(flux(u)) * dx)
    Totu = assemble(u * dx)

    u_val[i, 0] = t
    u_val[i, 1] = Totu
    u_val[i, 2] = TotFlux

    print 'time =', t