Ejemplo n.º 1
0
Archivo: utils.py Proyecto: matvii/ADAM
def Plot_Occ(tlist,vlist,angles,offset,OCCs,index):
    if index>len(OCCs):
        sys.exit("Index too large for occultation")
    up=np.array([0,0.3977,0.9175])
    M=Ortho_Proj(OCCs[index-1].E,up)
    R=Rot_Matrix(angles[0],angles[1],angles[2],OCCs[index-1].Meantime,0)
    MR=np.dot(M,R.transpose())
    vlist2=np.dot(MR,vlist.transpose()).transpose()
    vlist2=vlist2[:,0:2]
    V=np.dot(M,OCCs[index-1].V.transpose())
    v=V[0:2]
    vlist2[:,0]=vlist2[:,0]+offset[0]
    vlist2[:,1]=vlist2[:,1]+offset[1]
    #plt.figure(figsize=(50,50))
    plt.gca().set_aspect('equal')
    plt.triplot(np.array(vlist2[:,0]).flatten(),np.array(vlist2[:,1]).flatten(), tlist-1, 'g-',alpha=0.5)
    for j in range(0,len(OCCs[index-1].Chordtype)):
        a=OCCs[index-1].Chords[j,0:2]
        b=OCCs[index-1].Chords[j,2:4]
        ctype=OCCs[index-1].Chordtype[j]
        if ctype>=0:
            plt.plot([a[0],b[0]],[a[1],b[1]],'k-')
        if ctype<0:
            plt.plot([a[0],b[0]],[a[1],b[1]],'k--')
    plt.show()
Ejemplo n.º 2
0
def main():
    points = [(1, 0), (1, 1), (-1, 1), (-1, -1), (1, -1), (1, 0)]
    facets = round_trip_connect(0, len(points)-1)

    circ_start = len(points)
    points.extend(
            (3 * np.cos(angle), 3 * np.sin(angle))
            for angle in np.linspace(0, 2*np.pi, 30, endpoint=False))

    facets.extend(round_trip_connect(circ_start, len(points)-1))

    def needs_refinement(vertices, area):
        bary = np.sum(np.array(vertices), axis=0)/3
        max_area = 0.001 + (la.norm(bary, np.inf)-1)*0.01
        return bool(area > max_area)

    info = triangle.MeshInfo()
    info.set_points(points)
    info.set_holes([(0, 0)])
    info.set_facets(facets)

    mesh = triangle.build(info, refinement_func=needs_refinement)

    mesh_points = np.array(mesh.points)
    mesh_tris = np.array(mesh.elements)

    import matplotlib.pyplot as pt
    pt.triplot(mesh_points[:, 0], mesh_points[:, 1], mesh_tris)
    pt.show()
Ejemplo n.º 3
0
def plotgrid_ll(data,size,ll,nore):
    if nore=='n':
        num=dt.closest_node(data,ll)
        region={}
        region['region']=[data['nodexy'][num,0]-size,data['nodexy'][num,0]+size,data['nodexy'][num,1]-size,data['nodexy'][num,1]+size]
        idx=dt.get_nodes_xy(data,region)
        plt.triplot(data['trigridxy'],lw=.5)
        for i in idx:
            plt.text(data['nodexy'][i,0],data['nodexy'][i,1],("%d"%i),fontsize=10,bbox={'facecolor':'white', 'alpha':.7, 'pad':3})
        region2={}
        region2['region']=[data['nodexy'][num,0]-(size*2),data['nodexy'][num,0]+(size*2),data['nodexy'][num,1]-(size*2),data['nodexy'][num,1]+(size*2)]
        plt.axis(region2['region'])
        plt.show()
    if nore=='e':
        num=dt.closest_element(data,ll)
        region={}
        region['region']=[data['uvnode'][num,0]-size,data['uvnode'][num,0]+size,data['uvnode'][num,1]-size,data['uvnode'][num,1]+size]
        idx=dt.get_elements_xy(data,region)
        plt.triplot(data['trigridxy'],lw=.5)
        for i in idx:
            plt.text(data['uvnode'][i,0],data['uvnode'][i,1],("%d"%i),fontsize=10,bbox={'facecolor':'white', 'alpha':.7, 'pad':3})
        region2={}
        region2['region']=[data['uvnode'][num,0]-(size*2),data['uvnode'][num,0]+(size*2),data['uvnode'][num,1]-(size*2),data['uvnode'][num,1]+(size*2)]
        plt.axis(region2['region'])
        plt.show()
Ejemplo n.º 4
0
def colorizedDelaunay(tri,coordCentersX,coordCentersY,lcircle):
    "Basic coloration function for simple vue of the Triangulation. No consideration of node propreties"
    plt.triplot(coordCentersX, coordCentersY, tri.vertices.copy())#manage triangle edges color here
    plt.plot(coordCentersX, coordCentersY, 'o', markersize=1,markerfacecolor='green', markeredgecolor='red')
    plt.show()
    
    return
Ejemplo n.º 5
0
def show(verts1, verts2, tris1, tris2):
    plt.subplot(211)
    plt.xlabel('x')
    plt.ylabel('y')
    plt.triplot(verts1[:,0], verts1[:,1], tris1, 'g-')
    Tv = numpy.ones([len(verts1[:,0]),1])
    plt.triplot(verts2[:,0]+Tv[0,:]*1.25, verts2[:,1], tris2, 'r-')
Ejemplo n.º 6
0
    def graph_grid(self, debug=False):
        ''' 2D xy plot of bathymetry and mesh.
            No inputs required so far'''
        if debug or self._debug:
            print 'Plotting grid...'
        nv = self._var.nv.T -1
        h = self._var.h
        tri = Tri.Triangulation(self._var.lon, self._var.lat, triangles=nv)

        levels=np.arange(-100,-4,1)   # depth contours to plot

        fig = plt.figure(figsize=(18,10))
        plt.rc('font',size='22')
        ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(self._var.lat)*np.pi/180.0)))
        plt.tricontourf(tri, -h,levels=levels,shading='faceted',cmap=plt.cm.gist_earth)
        plt.triplot(tri)
        plt.ylabel('Latitude')
        plt.xlabel('Longitude')
        plt.gca().patch.set_facecolor('0.5')
        cbar=plt.colorbar()
        cbar.set_label('Water Depth (m)', rotation=-90,labelpad=30)

        scale = 1
        ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale))
        ax.xaxis.set_major_formatter(ticks)
        ax.yaxis.set_major_formatter(ticks)
        plt.grid()
        plt.show()

        if debug or self._debug:
            print '...Passed'
Ejemplo n.º 7
0
	def VisTris(self):
		de = Delaunay(self.pts)
		print de
		points = np.array(self.pts)
		plt.triplot(points[:,0], points[:,1], de.simplices.copy())
		plt.plot(points[:,0], points[:,1], 'o')
		plt.show()
Ejemplo n.º 8
0
    def __init__(self,xrange,yrange,pointsArray,simplices,initPosDist,initVelDist,initParticles):
        self.fig = plt.figure(1)				#create plot window
        plt.ion()
        self.ax = plt.gca()	
        self.ax.set_autoscale_on(False)
        self.ax.axis([xrange[0],xrange[1],yrange[0],yrange[1]])	#set boundaries

        self.tri_xy = pointsArray		#includes [[x0 x1 x2 ...		points to triangulate
						#           y0 y1 y2 ...  ]]
	self.tri_simplices = simplices		#includes [[p1,p4,p2],[p8,p4,p6]...]	triangulation of said points
	print self.tri_simplices
        plt.triplot(self.tri_xy[:,0],self.tri_xy[:,1],self.tri_simplices)
        
        self.ax.plot(self.tri_xy[:,0], self.tri_xy[:,1], 'o')

        self.fig.show()
        self.e_array = []

        self.xmin = xrange[0]
        self.xmax = xrange[1]
        self.ymin = yrange[0]
        self.ymax = yrange[1]

        for i in range(0, initParticles):
            a = particle(initPosDist[0],initPosDist[1],initVelDist[0],initVelDist[1])
            self.e_array.append([a, self.ax.plot(a.xpos, a.ypos, 'ro')])
Ejemplo n.º 9
0
def webcam():
  if __name__=='__main__':
    capture=cv.CaptureFromCAM(0)
    cv.NamedWindow('image')
    
    while  True:
      frame=cv.QueryFrame(capture)
      cv.ShowImage('image',frame)
      k=cv.WaitKey(10)
      if k%256==27:
        break

    cv.DestroyWindow('image')

  img=np.asarray(frame[:,:])
  img=img[:,:,0]
  im = Image.fromarray(img)

  a=[]
  img = cv2.medianBlur(img,5) 
  th2 = cv2.adaptiveThreshold(img,255,cv2.ADAPTIVE_THRESH_MEAN_C,\
              cv2.THRESH_BINARY,3,1)
  for i in range (0,th2.shape[0]) :
          for j in range(0,th2.shape[1]):
                  if th2[i,j]==0 :
                        a.append((j,-i))
  points=np.asarray(a)
  for i in a :
          del i
  tri = Delaunay(points)
  plt.triplot(points[:,0], points[:,1], tri.simplices.copy(),linewidth=0.5,color='b')
  #plt.plot(points[:,0], points[:,1], 'o')
  plt.xticks([]), plt.yticks([])
  plt.show()
def fun_display_category_in_triang2D(X, Y, category_name, title="aNother beautiful plot"):
    """
    The function does almost list the one called fun_display_category_in_2D
    except that it uses some triangulation to show the data.
    """
    names_gender = []
    for name in category_name:
        names_gender.append(name[0])

    indices_M = [i for i, s in enumerate(names_gender) if s[0] == "M"]
    indices_F = [j for j, s in enumerate(names_gender) if s[0] == "F"]

    indices_M = np.asarray(indices_M)
    indices_F = np.asarray(indices_F)

    # plt.figure()

    triang = tri.Triangulation(X[indices_M], Y[indices_M])
    # Mask off unwanted triangles.
    xmid = X[triang.triangles].mean(axis=1)
    ymid = Y[triang.triangles].mean(axis=1)
    plt.triplot(triang, "bs-")

    triang = tri.Triangulation(X[indices_F], Y[indices_F])
    # Mask off unwanted triangles.
    xmid = X[triang.triangles].mean(axis=1)
    ymid = Y[triang.triangles].mean(axis=1)
    plt.triplot(triang, "or-")

    plt.xlabel("dimension 1")
    plt.ylabel("dimension 2")
    plt.title("another beautiful plot")
    plt.axis([-1, 1, -1, 1])
    plt.draw()
Ejemplo n.º 11
0
Archivo: main.py Proyecto: zedoul/air
def draw_pdf_contours(dist, border=False, nlevels=200, subdiv=8, **kwargs):
    '''Draws pdf contours over an equilateral triangle (2-simplex).

    Arguments:

        `dist`: A distribution instance with a `pdf` method.

        `border` (bool): If True, the simplex border is drawn.

        `nlevels` (int): Number of contours to draw.

        `subdiv` (int): Number of recursive mesh subdivisions to create.

        kwargs: Keyword args passed on to `plt.triplot`.
    '''
    from matplotlib import ticker, cm
    import math
 
    refiner = tri.UniformTriRefiner(_triangle)
    trimesh = refiner.refine_triangulation(subdiv=subdiv)
    pvals = [dist.pdf(xy2bc(xy)) for xy in zip(trimesh.x, trimesh.y)]
 
    plt.tricontourf(trimesh, pvals, nlevels, **kwargs)
    plt.axis('equal')
    plt.xlim(0, 1)
    plt.ylim(0, 0.75**0.5)
    plt.axis('off')
    if border is True:
        plt.hold(1)
        plt.triplot(_triangle, linewidth=1)
Ejemplo n.º 12
0
def contour(data, x, y, label=None, log=False):

    tri=Triangulation(x,y)

    plt.close('all')
    plt.figure()
    ax=plt.subplot(111)
    ax.minorticks_on()
    if(log):
        ax.set_xscale("log",nonposx='clip')
        ax.set_yscale("log",nonposy='clip')

    ax.set_xlim([min(x.min(),y.min()),max(x.max(),y.max())])
    ax.set_ylim([min(x.min(),y.min()),max(x.max(),y.max())])
    plt.xlabel('r [AU]')
    plt.ylabel('z [AU]')

    nmax=data.max()
    nmin=data.min()
    levels=np.logspace(np.log10(nmin),np.log10(nmax),num=12)

    plt.tricontourf(tri, data, levels, norm=colors.LogNorm(vmin=nmin, vmax=nmax))
    cbar=plt.colorbar(format='%.2e')
    cbar.set_label(label)

    CS=plt.tricontour(tri, data, levels, colors='black', linewidths=1.5)
    plt.clabel(CS, fontsize=8, inline=1)
    cbar.add_lines(CS)

    plt.triplot(tri, color='black', alpha=0.2)

    plt.show(block=False)
Ejemplo n.º 13
0
def get_Triangulation(domain, path=None, save=True, show=False, ics=1,
                      ext='.png'):
    """
    :param domain: :class:`~polyadcirc.run_framework.domain`
    :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: coordinate system (1 cartisian, 2 polar)
    :param string ext: file extesion
    :returns: :class:`matplotlib.tri.Triangulation`

    """

    x = np.array([n.x for n in domain.node.itervalues()])
    y = np.array([n.y for n in domain.node.itervalues()])
    triangles = np.array([e-1 for e in domain.element.itervalues()])
    triangulation = tri.Triangulation(x, y, triangles)
    plt.figure()
    if path == None:
        path = os.getcwd()
    if not os.path.exists(path+'/figs'):
        fm.mkdir(path+'/figs')
    if save or show:
        plt.triplot(triangulation, 'g-')
        plt.title('grid')
        plt.gca().set_aspect('equal')
        add_2d_axes_labels(ics)    
        save_show(path+'/figs/grid', save, show, ext)
    domain.triangulation = triangulation
    return triangulation
    def graphGrid(self,narrowGrid=False, plot=False):
        #nx.draw(self.graph, self.pointIDXY)
        #plt.show()

        #lat = self.data.variables['lat'][:]
        #lon = self.data.variables['lon'][:]
        #nv = self.data.variables['nv'][:].T -1
        #h = self.data.variables['h'][:]
        #lat = self.self.lat
        #lon = self.lon
        #trinodes = self.trinodes[:]
        #h = self.h

        tri = Tri.Triangulation(self.lon, self.lat, triangles=self.trinodes) 
        # xy or latlon based on how you are #Grand Passage

        #levels=np.arange(-38,6,1)   # depth contours to plot

        fig = plt.figure(figsize=(18,10))
        plt.rc('font',size='22')
        ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(self.lat)*np.pi/180.0)))
        #plt.tricontourf(tri,-self.h,shading='faceted',cmap=plt.cm.gist_earth)
        plt.triplot(tri, color='white', linewidth=0.5)
        plt.ylabel('Latitude')
        plt.xlabel('Longitude')
        plt.gca().patch.set_facecolor('0.5')
        #cbar=plt.colorbar()
        #cbar.set_label('Water Depth (m)', rotation=-90,labelpad=30)

        scale = 1
        ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale))
        ax.xaxis.set_major_formatter(ticks)
        ax.yaxis.set_major_formatter(ticks)
        plt.grid()

        maxlat, maxlon = np.max(self.maxcoordinates,axis=0)
        minlat, minlon = np.min(self.mincoordinates,axis=0)
        if narrowGrid:
            ax.set_xlim(minlon,maxlon)
            ax.set_ylim(minlat,maxlat)


        zz = len(self.elements)
        for i,v in enumerate(self.elements):
            source = self.pointIDXY[v[0]]
            target = self.pointIDXY[v[-1]]
            lab = '({:.6},{:.6})-({:.6},{:.6})'.format(source[0], source[1],
                                                       target[0], target[1])

            plt.scatter(self.lonc[v], self.latc[v],
                        s=80, label=lab, c=plt.cm.Set1(i/zz))

        #plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3,fontsize='14', borderaxespad=0.)
        plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3)
        #plt.legend()
        if plot:
            plt.ylabel('Latitude')
            plt.xlabel('Longitude')
            plt.show()
Ejemplo n.º 15
0
    def _render(self, image_view=False, label=None, **kwargs):
        import matplotlib.pyplot as plt
        # Flip x and y for viewing if points are tied to an image
        points = self.points[:, ::-1] if image_view else self.points
        plt.triplot(points[:, 0], points[:, 1], self.trilist,
                    label=label, color='b')

        return self
def triangulate(n):
    X = np.linspace(0,1,n)
    Y = X.copy()
    X,Y = np.meshgrid(X,Y,copy=False)
    A = np.column_stack((X.flat,Y.flat))
    D = st.Delaunay(A)
    plt.triplot(A[:,0],A[:,1],D.simplices.copy())
    plt.show()
Ejemplo n.º 17
0
def delaunay(dataName,dataType,value):
	v_arr=genfromtxt(dataName + str(value) + dataType,delimiter=',' )
	data = np.array([[row[0],row[1]] for row in v_arr])
	dln = sp.spatial.Delaunay(data)
	plt.triplot(data[:,0],data[:,1],dln.simplices.copy(),linewidth=0.5,color='b',marker='.')
	plt.xlim(300,700);plt.ylim(300,700);
	plt.savefig('delaun_' + str(value) + '.png',dpi=200)
	print 'Saved Delaunay @ t=' + str(value)
Ejemplo n.º 18
0
def plot_compact(u, t, stepcounter): 
    if stepcounter % 5 == 0:
        uEuclidnorm = project(u, V); ax.cla(); fig = plt.gcf(); fig.set_size_inches(16, 6.5)
        plt.subplot(1, 2, 1); mplot_function(uEuclidnorm); plt.title("Heat") # Plot norm of velocity
        if t == 0.: plt.colorbar(); plt.axis(G)
        plt.subplot(1, 2, 2);
        if t == 0.: plt.triplot(mesh2triang(mesh)); plt.title("Mesh") # Plot mesh
        plt.suptitle("Heat - t: %f" % (t)); plt.tight_layout(); clear_output(wait=True);    
Ejemplo n.º 19
0
def PlotMesh(M):
  if M.version==0:
    plt.triplot(M.q[:,0],M.q[:,1],M.me,'bo-')
  elif M.version==1:
    plt.triplot(M.q[0],M.q[1],M.me,'bo-')
  plt.axis('equal')
  plt.axis('off')
  plt.show()
Ejemplo n.º 20
0
def delaunay_triangulation(points, plot=False):
    """ Extract a Delaunay's triangulation from the points """
    tri = Delaunay(points)
    if plot:
        plt.triplot(points[:, 0], points[:, 1], tri.simplices.copy())
        plt.plot(points[:, 0], points[:, 1], 'o')
        plt.show()
    return tri.simplices
Ejemplo n.º 21
0
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x ** 2 + y ** 2
        theta = np.arctan2(y, x)
        z = np.cos(theta) / r_sq
        return (np.max(z) - z) / (np.max(z) - np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi / n_angles
    x = (radii * np.cos(angles)).flatten()
    y = (radii * np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0)
    triang.set_mask(mask)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (Ex, Ey) = tci.gradient(triang.x, triang.y)
    E_norm = np.sqrt(Ex ** 2 + Ey ** 2)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect("equal")
    plt.triplot(triang, color="0.8")

    levels = np.arange(0.0, 1.0, 0.01)
    cmap = cm.get_cmap(name="hot", lut=None)
    plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap, linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(
        triang.x,
        triang.y,
        Ex / E_norm,
        Ey / E_norm,
        units="xy",
        scale=10.0,
        zorder=3,
        color="blue",
        width=0.007,
        headwidth=3.0,
        headlength=4.0,
    )
def plot_delaunay(points):
    from scipy.spatial import Delaunay
    tri = Delaunay(points)
    #scipy.spatial.Delaunay()
    plt.triplot(points[:,0], points[:,1], tri.simplices.copy())
    plt.plot(points[:,0], points[:,1], 'o')
    for triangle in tri.simplices:
        print(triangle)
    plt.show()
Ejemplo n.º 23
0
 def plot(self):
     import matplotlib.pyplot as Plt
     if self.triangulation == None:
         self.triangulate()
     Plt.figure()
     Plt.gca().set_aspect('equal')
     Plt.triplot(self.triangulation, 'bo-')
     Plt.title('Delaunay Triangulation')
     Plt.show()
Ejemplo n.º 24
0
def plot_square_triangulation(filename):
    n=5
    x = np.linspace(0, 1, n)
    x, y = map(np.ravel, np.meshgrid(x, x))
    t = triangles(n)
    plt.triplot(x, y, t, color='b')
    plt.scatter(x, y, color='b')
    plt.savefig(filename)
    plt.clf()
Ejemplo n.º 25
0
    def plot(self, color='b'):
        points_in, points_out = self.filter()

        plt.plot(points_in[:,0], points_in[:,1], 'o'+color)
        plt.plot(points_out[:,0], points_out[:,1], 'or')

        points = self.control

        plt.triplot(points[:,0], points[:,1], self.tri.simplices.copy())
Ejemplo n.º 26
0
    def get_bounding(self):

        elements, nodes, = self.abaqus_input.elements, self.abaqus_input.nodes
        displacement = self.abaqus_input.displacement
        seen = set()
        seen_add = seen.add
        layers = sorted([x for x in [i[3] for i in nodes] if not (x in seen or seen_add(x))])
        # self.layer_levels = [i for i, _ in enumerate(layers)]
        print layers
        nodes_map = {node[0]: node[1:] for node in nodes}

        element_map = {element[0]: element[1:] for element in elements}
        temp_mapping = {}
        for key, value in nodes_map.iteritems():
            for layer in layers:
                if layer in temp_mapping and layer in [value[2]]:
                    temp_mapping[layer].append(value[0:2])
                    break
                elif layer in [value[2]]:
                    temp_mapping[layer] = [value[0:2]]
                    break

        points = np.array(temp_mapping[layers[6]])
        # print temp_mapping[layers[6]]
        tri = Delaunay(points)
        # print tri.simplices
        plt.triplot(points[:, 0], points[:, 1], tri.simplices.copy())
        plt.plot(points[:, 0], points[:, 1], "o")

        if len(displacement) > 0:
            for key in temp_mapping:
                temp = []
                for value in temp_mapping[key]:
                    temp.append([value[0] + displacement[0][0], value[1] + displacement[0][1]])
                temp_mapping[key] = temp
        if len(displacement) > 1:
            for key in temp_mapping:
                temp = []
                # print displacement[1]
                for value in temp_mapping[key]:
                    value = [value[0] - displacement[1][0], value[1] - displacement[1][1]]
                    new_value = np.matrix(
                        [
                            [np.cos(np.radians(displacement[1][6])), -np.sin(np.radians(displacement[1][6]))],
                            [np.sin(np.radians(displacement[1][6])), np.cos(np.radians(displacement[1][6]))],
                        ]
                    ) * np.matrix([[value[0]], [value[1]]])
                    # print displacement[1][3]
                    new_value = [
                        float(new_value[0][0] + displacement[1][3]),
                        float(new_value[1][0] + displacement[1][4]),
                    ]
                    temp.append(new_value)

                temp_mapping[key] = temp
        return temp_mapping[layers[6]]
    def graphGrid(self,narrowGrid=False, plot=False):
        ''' A method to graph the grid with the shortest path plotted on the
        grid. narrowGrid will limit the field of view down to only show the
        paths drawn and not the entire grid. If only one path is drawn, this
        can skew the way the grid looks, and is sometime better to view the
        whole grid and zoom in. The plot option is in cause you want to choose
        when to plot the graph in a different part of the code.'''
        lat = self.lat
        lon = self.lon
        nv = self.nv.T - 1
        h = self.h

        tri = Tri.Triangulation(lon, lat, triangles=nv)  # xy or latlon based on how you are #Grand Passage

        levels=np.arange(-38,6,1)   # depth contours to plot

        fig = plt.figure(figsize=(18,10))
        plt.rc('font',size='22')
        ax = fig.add_subplot(111,aspect=(1.0/np.cos(np.mean(lat)*np.pi/180.0)))
        plt.tricontourf(tri, -h,levels=levels,shading='faceted',cmap=plt.cm.gist_earth)
        plt.triplot(tri)
        plt.ylabel('Latitude')
        plt.xlabel('Longitude')
        plt.gca().patch.set_facecolor('0.5')
        cbar=plt.colorbar()
        cbar.set_label('Water Depth (m)', rotation=-90,labelpad=30)

        scale = 1
        ticks = ticker.FuncFormatter(lambda lon, pos: '{0:g}'.format(lon/scale))
        ax.xaxis.set_major_formatter(ticks)
        ax.yaxis.set_major_formatter(ticks)
        plt.grid()

        maxlat, maxlon = np.max(self.maxcoordinates,axis=0)
        minlat, minlon = np.min(self.mincoordinates,axis=0)
        if narrowGrid:
            ax.set_xlim(minlon,maxlon)
            ax.set_ylim(minlat,maxlat)


        zz = len(self.elements)
        for i,v in enumerate(self.elements):
            source = self.pointIDXY[v[0]]
            target = self.pointIDXY[v[-1]]
            lab = '({:.6},{:.6})-({:.6},{:.6})'.format(source[0], source[1],
                                                       target[0], target[1])

            plt.scatter(self.lonc[v], self.latc[v],
                        s=80, label=lab, c=plt.cm.Set1(i/zz))

        plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=2, ncol=3)
        if plot:
            plt.show()
Ejemplo n.º 28
0
def plot_points(X, barycentric=True, border=True, color='k.', **kwargs):
    '''Plots a set of points in the simplex'''
    if barycentric is True:
        X = X.dot(_corners)
    plt.plot(X[:, 0], X[:, 1], color, ms=2, **kwargs)
    plt.axis('equal')
    plt.xlim(0, 1)
    plt.ylim(0, 0.75**0.5)
    plt.axis('off')
    if border is True:
        plt.hold(1)
        plt.triplot(_triangle, linewidth=1)
Ejemplo n.º 29
0
def postprocessor(nodes):
    x = nodes[:, 0]
    y = nodes[:, 1]

    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(x, y, elements, 'ko-')
    plt.title("Elastic Problem")
    plt.xlabel('x')
    plt.ylabel('y')
    plt.xlim(-0.1, 1.1)
    plt.ylim(-0.1, 1.1)
    #plt.savefig("FEM.png")
    plt.show()
Ejemplo n.º 30
0
def test2():
    n = 10
    scale = 10
    xy, triangles = planemesh.build(n, scale)
    halfedges = halfedge.build(triangles)
    heVectors = np.asarray([xy[he.ivertex, :] - xy[he.prev().ivertex, :] for he in halfedges])
    pins = np.asarray([0, n])
    #pinPoses = xy[pins, :]
    pinPoses = np.asarray(( (-scale, 0), (0, 0) ))
    w = 1000.0
    nVertices = xy.shape[0]
    edges, heIndices = halfedge.toEdge(halfedges)
    nEdges = edges.shape[0]
    
    A1top, G = buildA1top(heVectors, halfedges, edges, heIndices, nVertices)
    A1bottom = buildA1bottom(pins, w, nVertices)
    b1 = buildB1(pins, pinPoses, w, nEdges)
    A1 = sp.vstack((A1top, A1bottom))
    tA1 = A1.transpose()
    v1 = spla.spsolve(tA1 * A1, tA1 * b1)
    
    A2top = buildA2top(edges, nVertices)
    A2bottom = buildA2bottom(pins, w, nVertices)
    b2 = buildB2(heVectors, heIndices, edges, pinPoses, w, G, v1)
    A2 = sp.vstack((A2top, A2bottom))
    tA2 = A2.transpose()
    v2x = spla.spsolve(tA2 * A2, tA2 * b2[:, 0])
    v2y = spla.spsolve(tA2 * A2, tA2 * b2[:, 1])
    v2 = np.vstack((v2x, v2y)).T
    
    if n == 1:
        answerA1top = np.asarray(( (     0,      0, -0.25,  0.25, -0.25, -0.25,    0.5,      0),
                                   (     0,      0, -0.25, -0.25,  0.25, -0.25,      0,    0.5),
                                   (-0.333,  0.333, 0.666,     0,     0,     0, -0.333, -0.333),
                                   (-0.333, -0.333,     0, 0.666,     0,     0,  0.333, -0.333),
                                   (   0.5,      0,  -0.5,  -0.5,     0,     0,      0,    0.5),
                                   (     0,    0.5,   0.5,  -0.5,     0,     0,   -0.5,      0),
                                   (-0.333, -0.333,     0,     0, 0.666,     0, -0.333,  0.333),
                                   ( 0.333, -0.333,     0,     0,     0, 0.666, -0.333, -0.333),
                                   (     0,    0.5,     0,     0,  -0.5,  -0.5,    0.5,      0),
                                   (  -0.5,      0,     0,     0,   0.5,  -0.5,      0,    0.5)
                                  ))
        print "Error of G : %e" % la.norm(A1top - answerA1top, np.Inf)
        #print "Full A1top : ", A1top.todense()

    v1 = v1.reshape(-1, 2)
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(v2[:,0], v2[:,1], triangles)
    plt.show()
Ejemplo n.º 31
0
 def Plot(self):
     # 画出来
     plt.triplot(self.pts[:, 0], self.pts[:, 1], self.tri.simplices.copy())
     plt.plot(self.pts[:, 0], self.pts[:, 1], '.')
     plt.show()
Ejemplo n.º 32
0
    def dump_triangulation(self, filename="domain.png"):
        # Get vertex coordinates, partition full and ghost triangles based on self.tri_full_flag

        try:
            import matplotlib
            matplotlib.use('Agg')
            import matplotlib.pyplot as plt
            import matplotlib.tri as tri
        except:
            print "Couldn't import module from matplotlib, probably you need to update matplotlib"
            raise

        vertices = self.get_vertex_coordinates()
        full_mask = num.repeat(self.tri_full_flag == 1, 3)
        ghost_mask = num.repeat(self.tri_full_flag == 0, 3)

        myid = pypar.rank()
        numprocs = pypar.size()

        if myid == 0:

            fig = plt.figure()
            fx = {}
            fy = {}
            gx = {}
            gy = {}

            # Proc 0 gathers full and ghost nodes from self and other processors
            fx[0] = vertices[full_mask, 0]
            fy[0] = vertices[full_mask, 1]
            gx[0] = vertices[ghost_mask, 0]
            gy[0] = vertices[ghost_mask, 1]

            for i in range(1, numprocs):
                fx[i] = pypar.receive(i)
                fy[i] = pypar.receive(i)
                gx[i] = pypar.receive(i)
                gy[i] = pypar.receive(i)

            # Plot full triangles
            for i in range(0, numprocs):
                n = int(len(fx[i]) / 3)

                triang = num.array(range(0, 3 * n))
                triang.shape = (n, 3)
                plt.triplot(fx[i], fy[i], triang, 'g-', linewidth=0.5)

            # Plot ghost triangles
            for i in range(0, numprocs):
                n = int(len(gx[i]) / 3)
                if n > 0:
                    triang = num.array(range(0, 3 * n))
                    triang.shape = (n, 3)
                    plt.triplot(gx[i], gy[i], triang, 'b--', linewidth=0.5)

            # Save triangulation to location pointed by filename
            plt.savefig(filename, dpi=600)

        else:
            # Proc 1..numprocs send full and ghost triangles to Proc 0
            pypar.send(vertices[full_mask, 0], 0)
            pypar.send(vertices[full_mask, 1], 0)
            pypar.send(vertices[ghost_mask, 0], 0)
            pypar.send(vertices[ghost_mask, 1], 0)
Ejemplo n.º 33
0
x = ncoords[:, 0]
y = ncoords[:, 1]
nid_pos = dict(zip(np.arange(len(ncoords)), np.arange(len(ncoords))))

# triangulation to establish nodal connectivity
d = Delaunay(ncoords)
if plot_mesh:
    plt.clf()
    ax = plt.gca()
    ax.set_aspect('equal')
    for s in ax.spines.values():
        s.set_visible(False)
    ax.set_xticks([])
    ax.set_yticks([])
    plt.triplot(ncoords[:, 0], ncoords[:, 1], d.simplices, lw=0.5)
    plt.plot(ncoords[:, 0], ncoords[:, 1], 'o', ms=2)
    plt.show()

#NOTE using dense matrices
K = np.zeros((DOF * nx * ny, DOF * nx * ny))
M = np.zeros((DOF * nx * ny, DOF * nx * ny))

elems = []
# creating tria elements
for s in d.simplices:
    elem = Tria3PlaneStressIso()
    elem.n1 = s[0]
    elem.n2 = s[1]
    elem.n3 = s[2]
    elem.E = E
Ejemplo n.º 34
0
        'node': np.array(mesh_struct.points),
        'perm': perm
    }

    return mesh, el_pos


# demo
if __name__ == "__main__":
    # simple
    mesh_obj, e_pos = create(16)

    # show el_pos
    print(mesh_obj)

    # extract 'node' and 'element'
    p = mesh_obj['node']
    t = mesh_obj['element']

    # show the meshes
    plt.plot()
    plt.triplot(p[:, 0], p[:, 1], t)
    plt.plot(p[e_pos, 0], p[e_pos, 1], 'ro')
    plt.axis('equal')
    plt.xlabel('x')
    plt.ylabel('y')
    title_src = 'number of triangles = ' + str(np.size(t, 0)) + ', ' + \
                'number of nodes = ' + str(np.size(p, 0))
    plt.title(title_src)
    plt.show()
Ejemplo n.º 35
0
ngridx = 100
ngridy = 200
data = np.genfromtxt(
    '/home/vibek/Human_intention/src/Train_model/chair_right_w.csv',
    delimiter=',')

x = data[:, 0]
y = data[:, 1]
z = data[:, 2]

#z = x*np.exp(-x**2 - y**2)

# tricontour.
start = time.clock()
#plt.subplot(212)
triang = tri.Triangulation(x, y)
plt.triplot(x, y, data, 'go-', lw=1.0)
plt.tricontour(x, y, z, 35, linewidths=0.5, colors='k')
plt.tricontourf(x, y, z, 35)
# norm=plt.Normalize(vmax=abs(z).max(), vmin=-abs(z).max()))
plt.colorbar()
plt.plot(x, y, 'ko', ms=3)
plt.xlim(0, 0.4)
plt.ylim(-0.3, 0)
plt.title('tricontour (%d points)' % npts)
print('tricontour seconds: %f' % (time.clock() - start))

#plt.subplots_adjust(hspace=0.5)

plt.show()
Ejemplo n.º 36
0
# 6: case
case = fem.Case(elements + lines)

writer = fem.vtkWriter("/tmp/paraFEM/profil_test")
writer.writeCase(case, 0.0)

steps = 10000
steps_ramp = 1

line_forces = []

for i in range(steps):
    ramp = 1 - (i < steps_ramp) * (1 - float(i) / steps_ramp)
    case.explicitStep(case.getExplicitMaxTimeStep()[0] / 2, ramp)
    if (i % 500) == 0:
        print(i)
        line_forces.append([np.linalg.norm(l.getStress()) for l in lines])
        writer.writeCase(case, 0.)

plt.plot(line_forces)
plt.show()

x, y = np.array(mesh_points).T
triang = mtri.Triangulation(x, y, triangles)

plt.plot(*airfoil.data.T, marker="x")
plt.triplot(triang, lw=0.5, color='0')
plt.axes().set_aspect('equal', 'datalim')
plt.show()

Ejemplo n.º 37
0
    #    xCoefficients = linalg.lu_solve(factorization, globalCoordinates[0])
    #    yCoefficients = linalg.lu_solve(factorization, globalCoordinates[1])
    #
    #    xPolynomial = numpy.polynomial.Polynomial(xCoefficients)
    #    print(xPolynomial.roots())

    return coordinates, mesh["faces"]


coefficients = Transform.getDefaultCoefficients()

domain = [[-2.0, 2.0], [-2.0, 2.0]]

figure, axes = pyplot.subplots()
coordinates, faces = getMesh(coefficients)
lines = pyplot.triplot(coordinates[0], coordinates[1], faces)
axes.set_xlim(domain[0])
axes.set_ylim(domain[1])
pyplot.subplots_adjust(left=0.25, bottom=0.25)

coefficientNames = ["x", "y"]
coefDomain = [-2, 2]

widgets = {
    "sliders": [[], []],
    "axes": [[], []],
    "orientation": ["horizontal", "vertical"],
    "offset": [[0.2, 0.02], [0.02, 0.2]],
    "dOffset": [[0.0, 0.04], [0.04, 0.0]],
    "width": [0.6, 0.03],
    "height": [0.03, 0.6]
Ejemplo n.º 38
0
    with open("map.csv") as f:
        points = [
            tuple(float(x) for x in line.strip().split(","))
            for line in f.readlines()
        ]

    # random.shuffle(points)
    start = time.clock()
    d = DelaunayMap(*points)
    end = time.clock()
    print(end - start)

    start = time.clock()
    for x, y, z in points:
        assert z == d[x, y]
    end = time.clock()
    print(end - start)

    import matplotlib.pyplot as plt
    import matplotlib.tri as mtri
    import numpy as np

    arr = np.array(points).astype("d")
    x, y, _ = arr.transpose()
    triang = mtri.Triangulation(x, y, list(d.triangles_indizes))
    xi, yi = np.meshgrid(np.linspace(0, 5, 200), np.linspace(0, 5, 200))

    plt.triplot(triang, 'ko-')

    plt.show()
# Triangulation of a set of points:

points = np.array([[0, 0], [0, 1.1], [1, 0], [1, 1]])
from scipy.spatial import Delaunay
tri = Delaunay(points)

# We can plot it:

import matplotlib.pyplot as plt
plt.triplot(points[:, 0], points[:, 1], tri.simplices.copy())
plt.plot(points[:, 0], points[:, 1], 'o')
plt.show()

# Point indices and coordinates for the two triangles forming the
# triangulation:

tri.simplices
# array([[2, 3, 0],                 # may vary
# [3, 1, 0]], dtype=int32)

# Note that depending on how rounding errors go, the simplices may
# be in a different order than above.

points[tri.simplices]
# array([[[ 1. ,  0. ],            # may vary
# [ 1. ,  1. ],
# [ 0. ,  0. ]],
# [[ 1. ,  1. ],
# [ 0. ,  1.1],
# [ 0. ,  0. ]]])
Ejemplo n.º 40
0
        print("cluster {} size = {}".format(i,
                                            len(clusters[i].simplex_indices)))

    # fill test
    fill = np.array([[0, 0], [3, 0], [1.5, 3]])  #, [0,0]])
    fill = np.array([[0, 0], [1, 0], [1, 1], [2, 1], [2, 0], [3, 0], [3, 3],
                     [2, 3], [2, 2], [1, 2], [1, 3], [0, 3]])

    # Plot
    colors = [
        'red', 'orange', 'yellow', 'green', 'cyan', 'blue', 'purple', 'magenta'
    ]
    alpha_complex_filtered = np.array(
        [simplex for simplex in a_shape.alpha_complex if np.sum(simplex) > -3])
    plt.triplot(points[:, 0],
                points[:, 1],
                alpha_complex_filtered,
                color='gray')
    # draw full clusters
    for i in range(k):
        alpha_complex = np.array(
            [a_shape.alpha_complex[j] for j in clusters[i].simplex_indices])
        plt.triplot(points[:, 0], points[:, 1], alpha_complex, color=colors[i])
    # draw only boundaries
    for i in range(k):
        boundary = clusters[i].get_boundary()
        alpha_complex = np.array([a_shape.alpha_complex[j] for j in boundary])
        plt.triplot(points[:, 0], points[:, 1], alpha_complex, color=colors[i])

    km_points = km.equalized_cluster_points
    km_points = km.cluster_points
    # plot kmeans
Ejemplo n.º 41
0

# construct rips complex
rips_complex = gudhi.AlphaComplex(points=data)
simplex_tree = rips_complex.create_simplex_tree()


# get data ready for plotting

scale = 0.05
points = np.array(
   [rips_complex.get_point(i) for i in range(simplex_tree.num_vertices())])

# 1-simplicies
coord_1s = np.array(
    [s[0] for s in simplex_tree.get_skeleton(2) if len(s[0]) == 2 and s[1] <= scale])
for idxs in coord_1s:
    plt.plot(points[idxs, 0],points[idxs, 1])


# 2-simplicies
triangles = np.array(
    [s[0] for s in simplex_tree.get_skeleton(2) if len(s[0]) == 3 and s[1] <= scale])
triang = mtri.Triangulation(points[:, 0], points[:, 1], triangles=triangles)

plt.tripcolor(points[:, 0], points[:, 1], triangles, facecolors=np.ones(len(triangles)), edgecolors='k')

plt.triplot(triang, marker="o")

plt.show()
Ejemplo n.º 42
0
def plot1():
    """plot1"""
    data = np.random.rand(100, 2)
    triangles = tri.Triangulation(data[:, 0], data[:, 1])
    plt.triplot(triangles)
    plt.show()
Ejemplo n.º 43
0
    def _contours(self, par=None, expr=None, distr=None, velocity=None, values=None, slice=1, global_cos=True,
                  species=None, style='isolines', ignore_inactive=True, **kwargs):
        """
        Business functions for plotting library.

        :param global_cos: If True, use global coordinate system (default: local)
        :return: GeoDataFrame
        """

        import numpy as np
        import matplotlib.pyplot as plt
        import matplotlib.tri as tri

        # check if keywords arguments are corrent - dirty fix, this required reimplementation.
        if slice > self.doc.getNumberOfSlices():
            raise ValueError("no entitiy provided (either of par, distr or expr parameter must be called) or slice number out of range.")

        # set current species
        if species is not None:
            if type(species) == str:
                speciesID = self.doc.findSpecies(species)
            elif type(species) == int:
                speciesID = species
            else:
                raise ValueError("species must be string (for name) or integer (for id)")
            self.doc.setMultiSpeciesId(speciesID)

        # read incidence matrix and node coordinates
        imat = self.doc.c.mesh.get_imatrix2d(slice=slice, ignore_inactive=ignore_inactive,
                                             split_quads_to_triangles=True)
        x, y = self.doc.getParamValues(Enum.P_MSH_X), self.doc.getParamValues(Enum.P_MSH_Y)

        if global_cos:
            X0 = self.doc.getOriginX()
            Y0 = self.doc.getOriginY()
            x = [X + X0 for X in x]
            y = [Y + Y0 for Y in y]

        # create Triangulation object
        femesh = tri.Triangulation(x, y, np.asarray(imat))

        if style == "edges":
            return plt.triplot(femesh, **kwargs)
        elif style == "faces":
            from matplotlib.colors import LinearSegmentedColormap
            allgrey_cm = LinearSegmentedColormap.from_list("all_grey",
                                                           np.array([[0.5, 0.5, 0.5, 1.], [0.5, 0.5, 0.5, 1.]]))
            return plt.tripcolor(femesh, np.zeros_like(range(self.doc.getNumberOfNodes())),
                                 cmap=allgrey_cm, **kwargs)

        # get values, remove nan values (=inactive elements)
        if par is not None:
            self.doc.getParamSize(par)  # workaround for a crashbug in FEFLOW
            values = self.doc.getParamValues(par)
        elif expr is not None:
            if type(expr) == str:
                exprID = self.doc.getNodalExprDistrIdByName(expr)
            elif type(expr) == int:
                exprID = expr
            else:
                raise ValueError("expr must be string (for name) or integer (for id)")
            values = [self.doc.getNodalExprDistrValue(exprID, n) for n in range(self.doc.getNumberOfNodes())]
        elif distr is not None:
            if type(distr) == str:
                distrID = self.doc.getNodalRefDistrIdByName(distr)
            elif type(distr) == int:
                distrID = distr
            else:
                raise ValueError("distr must be string (for name) or integer (for id)")
            values = [self.doc.getNodalRefDistrValue(distrID, n) for n in range(self.doc.getNumberOfNodes())]
        elif velocity is not None:
            if velocity not in ['v_x', 'v_y', 'v_z','v_norm']:
                raise ValueError("Allowed options vor parameter 'velocity': 'v_x', 'v_y', 'v_z' or 'v_norm'")
            values = self.doc.c.mesh.df.nodes(velocity=True)[velocity]

        elif values is not None:
            values = values  # OK, so this is just to make clear that we are using the values directly!
        else:
            raise ValueError("either of parameter par, expr or distr must be provided!")

        # set nan values to zero
        values = np.nan_to_num(np.asarray(values))

        # generate polygons from matplotlib (suppress output)
        if style == "continuous":
            return plt.tripcolor(femesh, values,
                                 shading='gouraud', **kwargs)
        elif style == "patches":
            try:
                return plt.tripcolor(femesh, facecolors=values.flatten(),
                                 **kwargs)
            except ValueError as e:
                # problems with quad elements --> need to have values for split elements, was
                # not a poblem for nodal values...
                if "Length of color" in str(e):
                    raise NotImplementedError("This function does not support quad elements yet")
                else:
                    raise e

        elif style == "fringes":
            contourset = plt.tricontourf(femesh, values, **kwargs)
            return contourset
        elif style == "isolines":
            contourset = plt.tricontour(femesh, values, **kwargs)
            return contourset
        else:
            raise ValueError("unkonwn style " + str(style))
Ejemplo n.º 44
0
import numpy as np
Ejemplo n.º 45
0
        return True

    sweep_axis = exp.add_sweep([exp.pulse_duration, exp.pulse_voltage],
                               points,
                               refine_func=refine_func)

    # Borrow the descriptor from the main sweep and use it for our direct plotter

    exp.add_plotter(fig1, desc)

    exp.run_sweeps()

    points, mean = sw.load_switching_data(wr.filename)
    mesh, scale_factors = sw.scaled_Delaunay(points)
    fig_mesh = sw.phase_diagram_mesh(points, mean, shading='gouraud')
    plt.triplot(mesh.points[:, 0] / scale_factors[0],
                mesh.points[:, 1] / scale_factors[1], mesh.simplices.copy())

    plt.show()

    # t1 = time.time()
    # for i in range(exp.iterations):
    #     exp.reset()
    #     exp.run_sweeps()
    #     points, mean = sw.load_switching_data(wr.filename)
    #     figs.append(sw.phase_diagram_mesh(points, mean, title="Iteration={}".format(i)))
    #     new_points = refine.refine_scalar_field(points, mean, all_points=False,
    #                                 criterion="integral", threshold = "one_sigma")
    #     if new_points is None:
    #         print("No more points can be added.")
    #         break
    #     print("Added {} new points.".format(len(new_points)))
Ejemplo n.º 46
0
def showDelaunay(pic, points, tri):
    plt.triplot(points[:, 0], points[:, 1], tri.simplices)
    plt.plot(points[:, 0], points[:, 1], 'o')
    plt.imshow(pic)
    plt.show()
Ejemplo n.º 47
0
import matplotlib.pyplot as plt
import numpy as np

A = 90
x = (180 - 90) / 2

print("Value of angle B and C is", x)

x1 = [0, 1, 0]
y1 = [0, 0, 1]

plt.triplot(x1, y1, color='r')

plt.title('triangle')

plt.grid()
plt.show()
Ejemplo n.º 48
0
def plot_model_grid():
    '''
    Plot the grid of models in each metallicity.
    Internal use.
    '''

    grid_kurucz = pd.read_csv('files/grid_points_kurucz.csv')
    for m_h in grid_kurucz.groupby('m_h').size().index:
        plt.figure(figsize=(13, 4))
        index = grid_kurucz['m_h'] == m_h
        grid_matrix = np.array(grid_kurucz.loc[index, ['Teff', 'logg']])
        tri = Delaunay(grid_matrix)
        for i in range(len(tri.simplices) - 1, -1, -1):
            if min(grid_matrix[tri.simplices[i]][:, 0]) >= 35000:
                teff_gap = 5000
            else:
                teff_gap = 1500
            if np.ptp(
                    grid_matrix[tri.simplices[i]][:, 0]) >= teff_gap or np.ptp(
                        grid_matrix[tri.simplices[i]][:, 1]) > 0.5:
                tri.simplices = np.concatenate(
                    [tri.simplices[:i], tri.simplices[i + 1:]])

        plt.triplot(grid_matrix[:, 0],
                    grid_matrix[:, 1],
                    tri.simplices,
                    zorder=0,
                    lw=1,
                    color='gray',
                    alpha=0.5)
        if m_h < 0.5:
            plt.plot([50000, 42500], [5, 5],
                     color='gray',
                     zorder=0,
                     alpha=0.5,
                     lw=1)
        elif m_h == 0.5:
            plt.plot([45000, 40000], [5, 5],
                     color='gray',
                     zorder=0,
                     alpha=0.5,
                     lw=1)
        elif m_h == 1:
            plt.plot([40000, 37500], [5, 5],
                     color='gray',
                     zorder=0,
                     alpha=0.5,
                     lw=1)

        plt.scatter(grid_kurucz.loc[index & (grid_kurucz['length'] == 72),
                                    'Teff'],
                    grid_kurucz.loc[index & (grid_kurucz['length'] == 72),
                                    'logg'],
                    s=5,
                    label='Model length: 72')
        plt.scatter(grid_kurucz.loc[index & (grid_kurucz['length'] == 64),
                                    'Teff'],
                    grid_kurucz.loc[index & (grid_kurucz['length'] == 64),
                                    'logg'],
                    s=5,
                    c='C3',
                    label='Model length: 64')

        plt.legend()
        plt.xlim((1175, 52325))
        plt.title('[Fe/H] = {:.1f}'.format(m_h))
        plt.xlabel(r'$T_\mathrm{{eff}}$')
        plt.ylabel('logg')
        plt.gca().invert_xaxis()
        plt.gca().invert_yaxis()
        plt.tight_layout()
        plt.savefig(
            '../docs/img/grid_points_kurucz/m_h{:+.1f}.png'.format(m_h),
            dpi=250)
        plt.close()
Ejemplo n.º 49
0
def all_aretes(triangles):
    A = []
    for i in triangles:
        A = A + aretes(i)
    return A


def suppr_aretes(points, aretes, lim):
    new_aretes = []
    for i in aretes:
        if (distance(points[i[0]], points[i[1]]) <
                lim) and (i not in new_aretes):
            new_aretes.append(i)
    return new_aretes


points = create_instance(10)
pointsArray = np.array(points)
print_instance(points)

tri = Delaunay(pointsArray)

py.triplot(pointsArray[:, 0], pointsArray[:, 1], tri.simplices)
py.show()

triangles = [list(tri.simplices[i]) for i in range(len(tri.simplices))]

A = all_aretes(triangles)

faretes = suppr_aretes(points, A, distance([0, 0], [200, 200]) / 3)
print(faretes)
Ejemplo n.º 50
0
def test_tri_smooth_gradient():
    # Image comparison based on example trigradient_demo.

    def dipole_potential(x, y):
        """ An electric dipole potential V """
        r_sq = x**2 + y**2
        theta = np.arctan2(y, x)
        z = np.cos(theta) / r_sq
        return (np.max(z) - z) / (np.max(z) - np.min(z))

    # Creating a Triangulation
    n_angles = 30
    n_radii = 10
    min_radius = 0.2
    radii = np.linspace(min_radius, 0.95, n_radii)
    angles = np.linspace(0, 2 * np.pi, n_angles, endpoint=False)
    angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
    angles[:, 1::2] += np.pi / n_angles
    x = (radii * np.cos(angles)).flatten()
    y = (radii * np.sin(angles)).flatten()
    V = dipole_potential(x, y)
    triang = mtri.Triangulation(x, y)
    xmid = x[triang.triangles].mean(axis=1)
    ymid = y[triang.triangles].mean(axis=1)
    mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0)
    triang.set_mask(mask)

    # Refine data - interpolates the electrical potential V
    refiner = mtri.UniformTriRefiner(triang)
    tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)

    # Computes the electrical field (Ex, Ey) as gradient of -V
    tci = mtri.CubicTriInterpolator(triang, -V)
    (Ex, Ey) = tci.gradient(triang.x, triang.y)
    E_norm = np.sqrt(Ex**2 + Ey**2)

    # Plot the triangulation, the potential iso-contours and the vector field
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(triang, color='0.8')

    levels = np.arange(0., 1., 0.01)
    cmap = cm.get_cmap(name='hot', lut=None)
    plt.tricontour(tri_refi,
                   z_test_refi,
                   levels=levels,
                   cmap=cmap,
                   linewidths=[2.0, 1.0, 1.0, 1.0])
    # Plots direction of the electrical vector field
    plt.quiver(triang.x,
               triang.y,
               Ex / E_norm,
               Ey / E_norm,
               units='xy',
               scale=10.,
               zorder=3,
               color='blue',
               width=0.007,
               headwidth=3.,
               headlength=4.)
    plt.show()
Ejemplo n.º 51
0
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import Delaunay, delaunay_plot_2d, tsearch

# The Delaunay triangulation of a set of random points:

pts = np.random.rand(20, 2)
tri = Delaunay(pts)
_ = delaunay_plot_2d(tri)

# Find the simplices containing a given set of points:

loc = np.random.uniform(0.2, 0.8, (5, 2))
s = tsearch(tri, loc)
plt.triplot(pts[:, 0], pts[:, 1], tri.simplices[s], 'b-', mask=s == -1)
plt.scatter(loc[:, 0], loc[:, 1], c='r', marker='x')
plt.show()
Ejemplo n.º 52
0
#X, xlabel = ey, r'$\sigma_{yc}/E$'
#X, xlabel = wirr_wtot, r'$W_{irr}/W_{tot}$'
Y, ylabel = hch, '$\sqrt{A_c / A_{app}}$'
#Y, ylabel = C, '$C/E$'

Z, zlabel = beta, r'$\beta = %1.1f$'
Zlevels = list(set(Z))
Z2, z2label = ey, r'$\epsilon_y = %1.3f$'
Z2levels = list(set(Z2))

# For checking purpose, let's plot the generated mesh. You may see that the mesh is self improving has the simulations complete (this is quite nice).

fig = plt.figure(0)
plt.clf()
fig.add_subplot(121)
plt.triplot(x, y, conn)
plt.title('Delaunay Mesh')
plt.xlabel('x')
plt.ylabel('y')
fig.add_subplot(122)
plt.triplot(X, Y, conn)
plt.title('Deformed Delaunay Mesh')
plt.xlabel('X')
plt.ylabel('Y')
plt.savefig('plots/basic_plot_mesh_DP.png')

plt.figure(0)
plt.clf()
plt.title(title)
plt.grid()
plt.xlabel(xlabel)
Ejemplo n.º 53
0
import pandas as pd
import numpy as np
from scipy.spatial import Delaunay
import matplotlib.pyplot as plt

#df = pd.read_csv('xy_radial.dat', sep=',',header=None)
df = pd.read_csv('File_20160909_b16f10_aMSH_xy38_simulation_info.csv', sep=',',header=1)
points = df.values
tod = np.arange(len(points))

#plt.scatter(points[:,2], points[:,3], s=10, c=points[:,4])
xp = points[:,2]
yp = points[:,3]
xy_pairs = np.array((xp,yp)).T
tod = points[:,4]

tri = Delaunay(xy_pairs)

plt.triplot(xp, yp, tri.simplices)
#plt.plot(points[:,0], points[:,1], 'o')

for j, p in enumerate(xp):
    # plt.text(xp[j]-0.03, yp[j]+0.03, int(tod[j]), ha='right', size='smaller') # label w TOD
    plt.text(xp[j]-0.03, yp[j]+0.03, j, ha='right', size='smaller') # label w index

#plt.title('Delaunay triangulation, cells labeled with time of death')
plt.title('Delaunay triangulation, cells labeled with index')
plt.xticks([])
plt.yticks([])
plt.show()
Ejemplo n.º 54
0
m.run_image(name="image", nphot=1e5, npix=25, pixelsize=1.0, lam="1000", \
        phi=0, incl=0, code="radmc3d", dpc=100, verbose=False, \
        unstructured=True, camera_nrrefine=8, camera_refine_criterion=1, \
        nostar=True)

print(m.images["image"].image.shape)

npix_trift = int(m.images["image"].image[:, 0].size**0.5)

# Plot the image.

triang = tri.Triangulation(m.images["image"].x, m.images["image"].y)

plt.tripcolor(triang, m.images["image"].image[:, 0], "ko-")
plt.triplot(triang, "k.-", linewidth=0.1, markersize=0.1)

plt.axes().set_aspect("equal")

plt.xlim(-12, 12)
plt.ylim(-12, 12)

plt.xlabel('$\Delta$ R.A. ["]', fontsize=14)
plt.ylabel('$\Delta$ Dec. ["]', fontsize=14)

plt.gca().tick_params(labelsize=14)

plt.show()

# Do the Fourier transform with TrIFT
Ejemplo n.º 55
0
def view(coords,
         elt2verts,
         nbDoms,
         partition,
         indInterfNodes=None,
         visuIndElts=True,
         visuIndVerts=True,
         colmap=plt.cm.Accent,
         title=None,
         isPartVert=True):
    fntcol = '#004000'
    quot = max(1, nbDoms - 1)
    fig = plt.figure()
    fig.suptitle(title, fontsize=14, fontweight='bold')
    plt.gca().set_aspect('equal')
    x = coords[:, 0]
    y = coords[:, 1]
    if (partition.shape[0] == coords.shape[0]) and isPartVert:
        # C'est une partition par noeud :
        plt.tripcolor(x,
                      y,
                      elt2verts,
                      partition,
                      shading='gouraud',
                      cmap=colmap)
        plt.triplot(x, y, elt2verts, 'bo-', color='black')
    else:
        # C'est une partition par element :
        isPartVert = False
        plt.tripcolor(x,
                      y,
                      elt2verts,
                      facecolors=partition,
                      edgecolors='k',
                      cmap=colmap)
    if visuIndElts:
        for ie in xrange(elt2verts.shape[0]):
            e = elt2verts[ie, :]
            bary = [(x[e[0]] + x[e[1]] + x[e[2]]) / 3.,
                    (y[e[0]] + y[e[1]] + y[e[2]]) / 3.]
            plt.text(bary[0],
                     bary[1],
                     u"%i" % ie,
                     fontsize=10,
                     fontweight='light',
                     style='italic',
                     ha='center',
                     va='center',
                     color=fntcol)
    if visuIndVerts:
        fntcol = 'black'
        iv = 0
        if isPartVert:
            for v in coords:
                szfnt = 11
                wfont = 'light'
                plt.text(v[0],
                         v[1],
                         u"%i" % iv,
                         ha='center',
                         va='center',
                         fontsize=szfnt,
                         color=fntcol,
                         fontweight=wfont,
                         backgroundcolor=colmap(partition[iv] / quot))
                iv += 1
        else:
            szfnt = 10
            wfont = 'light'
            mask = np.ones((coords.shape[0], ), np.short)
            ie = 0
            for e in elt2verts:
                d = partition[ie]
                bcolor = colmap(d / quot)
                if mask[e[0]] == 1:
                    plt.text(x[e[0]],
                             y[e[0]],
                             u"%i" % e[0],
                             ha='center',
                             va='center',
                             fontsize=szfnt,
                             color=fntcol,
                             fontweight=wfont,
                             backgroundcolor=bcolor)
                    mask[e[0]] = 0
                if mask[e[1]] == 1:
                    plt.text(x[e[1]],
                             y[e[1]],
                             u"%i" % e[1],
                             ha='center',
                             va='center',
                             fontsize=szfnt,
                             color=fntcol,
                             fontweight=wfont,
                             backgroundcolor=bcolor)
                    mask[e[1]] = 0
                if mask[e[2]] == 1:
                    plt.text(x[e[2]],
                             y[e[2]],
                             u"%i" % e[2],
                             ha='center',
                             va='center',
                             fontsize=szfnt,
                             color=fntcol,
                             fontweight=wfont,
                             backgroundcolor=bcolor)
                    mask[e[2]] = 0
                ie += 1

    if (indInterfNodes is not None) and visuIndVerts:
        for iv in indInterfNodes:
            v = coords[iv, :]
            szfnt = 12
            wfont = 'bold'
            d = partition[iv]
            bcolor = colmap(d / quot)
            if not isPartVert:
                bcolor = 'white'
                fntcol = 'black'
            plt.text(v[0],
                     v[1],
                     u"%i" % iv,
                     ha='center',
                     va='center',
                     fontsize=szfnt,
                     color=fntcol,
                     fontweight=wfont,
                     backgroundcolor=bcolor)
    plt.axis('off')
    plt.show()
Ejemplo n.º 56
0
import numpy as np
import matplotlib.pyplot as plt
import vtk
from vtk.numpy_interface import dataset_adapter as dsa

# load a vtk file as input
reader = vtk.vtkUnstructuredGridReader()
reader.SetFileName('../data/fixed0.vtk')
reader.Update()
output = reader.GetOutput()

array_of_points = dsa.WrapDataObject(output).Points
x = array_of_points[:,0]
y = array_of_points[:,1]

array_of_cells = dsa.WrapDataObject(output).Cells
nElement = int(len(array_of_cells) / 4)
element = np.zeros([nElement, 3])
lo = 1
for i in range(nElement):
    element[i,:] = array_of_cells[lo:lo+3]
    lo = lo + 4

plt.figure()
plt.triplot(x, y, element, color='k')
plt.axis('off')
plt.tight_layout()
plt.savefig('../figs/fixed0.pdf', bbox_inches='tight', pad_inches=0)
plt.close()
Ejemplo n.º 57
0
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()

# Create the Triangulation; no triangles so Delaunay triangulation created.
triang = tri.Triangulation(x, y)

# Mask off unwanted triangles.
xmid = x[triang.triangles].mean(axis=1)
ymid = y[triang.triangles].mean(axis=1)
mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0)
triang.set_mask(mask)

# Plot the triangulation.
plt.figure()
plt.gca().set_aspect('equal')
plt.triplot(triang, 'bo-', lw=1)
plt.title('triplot of Delaunay triangulation')

# You can specify your own triangulation rather than perform a Delaunay
# triangulation of the points, where each triangle is given by the indices of
# the three points that make up the triangle, ordered in either a clockwise or
# anticlockwise manner.

xy = np.asarray([[-0.101, 0.872], [-0.080, 0.883], [-0.069, 0.888],
                 [-0.054, 0.890], [-0.045, 0.897], [-0.057, 0.895],
                 [-0.073, 0.900], [-0.087, 0.898], [-0.090, 0.904],
                 [-0.069, 0.907], [-0.069, 0.921], [-0.080, 0.919],
                 [-0.073, 0.928], [-0.052, 0.930], [-0.048, 0.942],
                 [-0.062, 0.949], [-0.054, 0.958], [-0.069, 0.954],
                 [-0.087, 0.952], [-0.087, 0.959], [-0.080, 0.966],
                 [-0.085, 0.973], [-0.087, 0.965], [-0.097, 0.965],
Ejemplo n.º 58
0
    event.canvas.draw()


# Create a Triangulation.
n_angles = 16
n_radii = 5
min_radius = 0.25
radii = np.linspace(min_radius, 0.95, n_radii)
angles = np.linspace(0, 2 * math.pi, n_angles, endpoint=False)
angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
angles[:, 1::2] += math.pi / n_angles
x = (radii * np.cos(angles)).flatten()
y = (radii * np.sin(angles)).flatten()
triangulation = Triangulation(x, y)
xmid = x[triangulation.triangles].mean(axis=1)
ymid = y[triangulation.triangles].mean(axis=1)
mask = np.where(xmid * xmid + ymid * ymid < min_radius * min_radius, 1, 0)
triangulation.set_mask(mask)

# Use the triangulation's default TriFinder object.
trifinder = triangulation.get_trifinder()

# Setup plot and callbacks.
plt.subplot(111, aspect='equal')
plt.triplot(triangulation, 'bo-')
polygon = Polygon([[0, 0], [0, 0]], facecolor='y')  # dummy data for xs,ys
update_polygon(-1)
plt.gca().add_patch(polygon)
plt.gcf().canvas.mpl_connect('motion_notify_event', motion_notify)
plt.show()
Ejemplo n.º 59
0
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt


def build(n, scale):
    dx = scale / n
    xy = []
    triangles = []
    for row in xrange(0, n):
        ioffset = row * (n + 1)
        for col in xrange(0, n):
            xy.append((col * dx, row * dx))
            i = ioffset + col
            triangles.append((i, i + n + 2, i + 1))
            triangles.append((i, i + n + 1, i + n + 2))
        xy.append((n * dx, row * dx))
    for col in xrange(0, n + 1):
        xy.append((col * dx, n * dx))
    return (np.asarray(xy), np.asanyarray(triangles))


if __name__ == '__main__':
    n = 10
    scale = 10
    xy, triangles = build(n, scale)
    plt.figure()
    plt.gca().set_aspect('equal')
    plt.triplot(xy[:, 0], xy[:, 1], triangles)
    plt.show()
Ejemplo n.º 60
0
def afficherMaillage(points):
	#Code pour le afficherMaillage
	tri = Delaunay(points)
	plt.triplot(points[:,0], points[:,1], tri.simplices.copy())
	plt.plot(points[:,0], points[:,1], 'o')
	plt.show()