예제 #1
0
    def __init__(self, x, y, cells,**kwargs):
        
        self.__dict__.update(kwargs)

        Triangulation.__init__(self,x,y,cells)
        
        self.Nc = cells.shape[0]
 def buildTriangulation( self, x, y ):
     trig=None
     if qgis_qhull_fails:
         trig=self._buildtrig_workaround(x,y)
     else:
         trig=Triangulation(x,y)
     analyzer=TriAnalyzer(trig)
     mask=analyzer.get_flat_tri_mask()
     trig.set_mask(mask)
     return trig
        def PlotPoly(self):

                for i in range(0,len(self.poly)):

                        if i < len(self.poly)-1:
                                X = np.vstack((self.poly[i],self.poly[i+1]))
                        else:
                                X = self.poly[i]

                        X = np.vstack((X[:,0],X[:,1],X[:,3])).T
                        hull = ConvexHull(X,qhull_options=self.qhull_options)    


                        x,y,z=X.T
                        tri = Triangulation(x, y, triangles=hull.simplices)

                        triangle_vertices = np.array([np.array([[x[T[0]], y[T[0]], z[T[0]]],
                                [x[T[1]], y[T[1]], z[T[1]]],
                                [x[T[2]], y[T[2]], z[T[2]]]]) for T in tri.triangles])

                        self.tri = tri

                        tri = Poly3DCollection(triangle_vertices)
                        if i == len(self.poly)-1:
                                tri.set_color(self.COLOR_REACHABLE_SET_LAST)
                                tri.set_edgecolor(self.rs_last_edge_color)
                                #self.image.scatter(x,y,z, 'ok', color=np.array((0,0,1.0,0.1)),s=30)

                        else:
                                color_cur = copy.copy(self.COLOR_REACHABLE_SET_LAST)
                                color_cur[3] = color_cur[3]/2.0
                                tri.set_color(color_cur)
                                tri.set_edgecolor('None')

                        self.image.add_collection3d(tri)
예제 #4
0
def getEdgesSLF(IKLE,MESHX,MESHY,showbar=True):

   try:
      from matplotlib.tri import Triangulation
      edges = Triangulation(MESHX,MESHY,IKLE).get_cpp_triangulation().get_edges()
   except:
      #print '... you are in bad luck !'
      #print '       ~>  without matplotlib based on python 2.7, this operation takes ages'
      edges = []
      ibar = 0
      if showbar: pbar = ProgressBar(maxval=len(IKLE)).start()
      for e in IKLE:
         ibar += 1
         if showbar: pbar.update(ibar)
         if [e[0],e[1]] not in edges: edges.append([e[1],e[0]])
         if [e[1],e[2]] not in edges: edges.append([e[2],e[1]])
         if [e[2],e[0]] not in edges: edges.append([e[0],e[2]])
      if showbar: pbar.finish()

   return edges
예제 #5
0
def reload(self, imageName):
    #Let's create a canvas
    self.w.pack()
    self.w.delete("all")
    #Let's create an image
    image = Image.open(imageName)
    pixels = image.load()
    width, height = image.size
    #Just a testing data structure. Don't use this.
    all_pixels = []
    #Use this one when doing calculations.
    points = []
    xarray = []
    yarray = []
    color = ["red", "orange", "yellow", "green", "blue", "violet"]
    #loop(self, points, pixels, all_pixels, width, height)
    for x in range(width):
        for y in range(height):
            cpixel = pixels[x, y]
            foo = random.randint(1, 7)
            if (round(sum(cpixel)) / float(len(cpixel)) > 127) & (x%foo == 0) & (y%foo == 0):
                all_pixels.append(255)
                points.append(Point(x*2, y*2))
                xarray.append(x*2)
                yarray.append(1000 - y*2)
                #self.w.create_oval(x*2, y*2, x*2+1, y*2+1, fill="black")
            else:
                all_pixels.append(0)

    triangulation = Triangulation(xarray, yarray)
    triangles = triangulation.get_masked_triangles()

    polygons = []

    for triangle in triangles:
        self.w.create_polygon([xarray[triangle[0]], 1000 - yarray[triangle[0]]], [xarray[triangle[1]], 1000 - yarray[triangle[1]]], [xarray[triangle[2]], 1000 - yarray[triangle[2]]], fill=random.choice(color))
예제 #6
0
def get_triangulation(lon, lat):
    return Triangulation(lon, lat)
예제 #7
0
rotf = asm(unit_load, ib)

psi = solve(*condense(stokes, rotf, D=ib.find_dofs()))
psi0, = ib.interpolator(psi)(np.zeros((2, 1)))

if __name__ == "__main__":
    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import draw
    from matplotlib.tri import Triangulation

    print('psi0 = {} (cf. exact = 1/64 = {})'.format(psi0, 1/64))

    M, Psi = ib.refinterp(psi, 3)

    ax = draw(mesh)
    ax.tricontour(Triangulation(*M.p, M.t.T), Psi)
    name = splitext(argv[0])[0]
    ax.get_figure().savefig(f'{name}_stream-lines.png')

    refbasis = InteriorBasis(M, ElementTriP1())
    velocity = np.vstack([derivative(Psi, refbasis, refbasis, 1),
                          -derivative(Psi, refbasis, refbasis, 0)])
    ax = draw(mesh)
    sparsity_factor = 2**3      # subsample the arrows
    vector_factor = 2**3        # lengthen the arrows
    x = M.p[:, ::sparsity_factor]
    u = vector_factor * velocity[:, ::sparsity_factor]
    ax.quiver(*x, *u, x[0])
    ax.get_figure().savefig(f'{name}_velocity-vectors.png')
예제 #8
0
import argiope as ag
import numpy as np
import pandas as pd
from matplotlib.tri import Triangulation

mesh = ag.mesh.read_msh("demo.msh")
conn = mesh.split("simplices").unstack()
coords = mesh.nodes.coords.copy()
node_map = pd.Series(data=np.arange(len(coords)), index=coords.index)
conn = node_map.loc[conn.values.flatten()].values.reshape(*conn.shape)
triangulation = Triangulation(coords.x.values, coords.y.values, conn)
"""
nodes, elements = mesh.nodes, mesh.elements
#NODES
nodes_map = np.arange(nodes.index.max()+1)
nodes_map[nodes.index] = np.arange(len(nodes.index))
nodes_map[0] = -1
coords = nodes.coords.as_matrix()
#ELEMENTS
connectivities  = elements.conn.as_matrix()
connectivities[np.isnan(connectivities)] = 0
connectivities = connectivities.astype(np.int32)
connectivities = nodes_map[connectivities]
labels          = np.array(elements.index)
etype           = np.array(elements.type.argiope).flatten()
print(etype)
#TRIANGLES
x, y, tri = [], [], []
for i in range(len(etype)):
  triangles = connectivities[i][argiope.mesh.ELEMENTS[etype[i]]["simplices"]]
  for t in triangles:
def scatter_xyz(points, smooth=0, div=100, ax=None, **options):
    """
    Draws a 3D graph (X, Y, Z).
    The function requires :epkg:`matploblib`
    and :epkg:`scipy`.

    @param      points      (x,y, z=f(x,y) )
    @param      div         number of divisions for axis
    @param      smooth      applies n times a smoothing I * M (convolutional)
    @param      ax          existing graph to plot on (can be None)
    @param      options     others options: xlabel, ylabel, zlabel, title, elev, angle, figsize (if ax is None)
                                - elev, angle: see `view_init <http://matplotlib.org/mpl_toolkits/mplot3d/api.html>`_)
    @return                 fig, ax (fig is None if ax was sent to the function)

    If *ax is None*, axes are created like::

        fig = plt.figure(figsize=options.get('figsize', None))
        ax = fig.gca(projection='3d')

    .. plot::
        :include-source:

        import random
        def generate_gauss(x, y, sigma, N=1000):
            res = []
            for i in range(N):
                u = random.gauss(0, 1)
                a = sigma * u + x
                b = sigma * random.gauss(0, 1) + y + u
                res.append((a, b))
            return res
        def f(a, b):
            return (a ** 2 + b ** 2) ** 0.5
        nuage1 = generate_gauss(0, 0, 3)
        nuage2 = generate_gauss(3, 4, 2)
        nuage = [(a, b, f(a, b)) for a, b in nuage1] + [(a, b, f(a, b)) for a, b in nuage2]

        import matplotlib.pyplot as plt
        from ensae_teaching_cs.helpers.matplotlib_helper_xyz import scatter_xyz
        fig, ax = scatter_xyz(nuage, title="example with random observations")
        plt.show()

    The error ``ValueError: Unknown projection '3d'`` is raised when the line
    ``from mpl_toolkits.mplot3d import Axes3D`` is missing.
    """
    x = [_[0] for _ in points]
    y = [_[1] for _ in points]
    z = [_[2] for _ in points]

    if ax is None:
        import matplotlib.pyplot as plt
        from mpl_toolkits.mplot3d import Axes3D
        if Axes3D is None:
            raise ImportError("Unable to import mpl_toolkits.mplot3d")
        fig = plt.figure(figsize=options.get('figsize', None))
        ax = fig.gca(projection='3d')
    else:
        fig = None

    elev = options.get("elev", 50)
    angle = options.get("angle", 45)
    ax.view_init(elev, angle)

    tri = Triangulation(x, y)
    ax.plot_trisurf(x, y, z, triangles=tri.triangles, cmap='autumn')

    if "xlabel" in options:
        ax.set_xlabel(options["xlabel"])
    if "ylabel" in options:
        ax.set_ylabel(options["ylabel"])
    if "zlabel" in options:
        ax.set_ylabel(options["zlabel"])
    if "title" in options:
        ax.set_title(options["title"])
    return fig, ax
예제 #10
0
def getMPLTri(MESHX,MESHY,IKLE):
   from matplotlib.tri import Triangulation
   mpltri = Triangulation(MESHX,MESHY,IKLE).get_cpp_triangulation()
   return mpltri.get_neighbors(),mpltri.get_edges()
plt.figure(figsize = [6.4, 3.8])

#Loop through each time step and plot results
for ind in range(0, len(timeindays)): 
   dt = datetime.datetime.combine(datetime.date(1990, 1, 1), datetime.time(0, 0)) + datetime.timedelta(days=timeindays[ind])
   dstr = datetime.date.strftime(dt,'%Y%m%d%H:%M:%S')
   dstr = dstr[0:8]+' '+dstr[8:17]
   print('Plotting '+dstr)

   par=np.double(wlv[ind,:])
   par2=np.double(ucur[ind,:])
   par3=np.double(vcur[ind,:])

   flatness=0.10  # flatness is from 0-.5 .5 is equilateral triangle
   tri=Triangulation(lon,lat)
   mask = TriAnalyzer(tri).get_flat_tri_mask(flatness)
   tri.set_mask(mask)

   tli=LinearTriInterpolator(tri,par)
   par_interp=tli(reflon,reflat)
   tli2=LinearTriInterpolator(tri,par2)
   par2_interp=tli2(reflon,reflat)
   tli3=LinearTriInterpolator(tri,par3)
   par3_interp=tli3(reflon,reflat)

   #Set up a Mercator projection basemap
   plt.clf()
   #m=Basemap(projection='merc',llcrnrlon=reflon.min(),urcrnrlon=reflon.max(),\
   #    llcrnrlat=reflat.min(),urcrnrlat=reflat.max(),resolution='h')
   #x,y=m(reflon,reflat)
예제 #12
0
 def setMPLTri(self,set=False):
    if set or self.neighbours == None or self.edges == None:
       #from matplotlib.tri import Triangulation
       mpltri = Triangulation(self.MESHX,self.MESHY,self.IKLE2).get_cpp_triangulation()
       self.neighbours = mpltri.get_neighbors()
       self.edges = mpltri.get_edges()
예제 #13
0
    def element_finder(self):
        from matplotlib.tri import Triangulation

        return Triangulation(self.p[0, :], self.p[1, :],
                             self.t.T).get_trifinder()
예제 #14
0
def plot_backward_facing_step(res):
    u = df.as_vector([res['u0'], res['u1']])
    V = u[0].function_space()
    mesh = V.mesh()

    ############################################################################
    # Get some meta data
    sim = Simulation()
    sim.input.read_yaml(yaml_string=res['input'])
    Re = sim.input.get_value('user_code/constants/Re', required_type='float')
    time = res['time']

    ############################################################################
    # Find the length X1 of primary recirculating bubble

    x1_ypos = -0.99 * H2
    xf, _, _, f = get_probe_values(u[0], [0, x1_ypos, 0], [L2, x1_ypos, 0], 200)
    x1_c0 = get_zero_crossings(xf, f)
    print(x1_c0)

    ############################################################################
    # Find the inflow profile

    x_inflow = -1.5 * H1
    _, y_inflow, _, u0_inflow = get_probe_values(
        u[0], [x_inflow, 0, 0], [x_inflow, H1, 0], 20
    )

    ############################################################################
    # Refine the mesh and get a triangluated stream function
    for _ in range(2):
        old = mesh, V
        mesh = df.refine(mesh)
        V = df.FunctionSpace(mesh, V.ufl_element())
        df.parameters['allow_extrapolation'] = True
        try:
            u0 = df.interpolate(u[0], V)
            u1 = df.interpolate(u[1], V)
            u = df.as_vector([u0, u1])
        except Exception:
            mesh, V = old
            u0, u1 = u[0], u[1]
            print('Refining failed ------------------------------')
            break
        df.parameters['allow_extrapolation'] = False

    sf = StreamFunction(u, degree=V.ufl_element().degree())
    sf.compute()

    levels = get_probe_values(
        sf.psi, [1.5 * H2, -0.5 * H2, 0], [H2, H1 * 0.99, 0], N_levels
    )[-1]
    levels2 = []
    for xi, _idx, _upcrossing in x1_c0:
        # Add stream function values at upcrossing locations
        if xi - 0.3 > 0:
            levels2.append(get_probe_value(sf.psi, (xi - 0.3, x1_ypos, 0)))
        if xi + 0.1 < L2:
            levels2.append(get_probe_value(sf.psi, (xi + 0.1, x1_ypos, 0)))
    if levels2:
        levels = numpy.concatenate((levels, levels2))
    levels.sort()

    coords = mesh.coordinates()
    triangles = []
    for cell in df.cells(mesh):
        cell_vertices = cell.entities(0)
        triangles.append(cell_vertices)
    triangulation = Triangulation(coords[:, 0], coords[:, 1], triangles)
    Z = sf.psi.compute_vertex_values()

    ############################################################################
    # Plot streamlines and velocity distributions

    fig = pyplot.figure(figsize=(15, 2.5))
    ax = fig.add_subplot(111)
    ax.plot([-L1, -L1, 0, 0, L2, L2, -L1], [H1, 0, 0, -H2, -H2, H1, H1], 'k')

    # ax.triplot(triangulation, color='#000000', alpha=0.5, lw=0.25)
    ax.tricontour(
        triangulation, Z, levels, linestyles='solid', colors='#0000AA', linewidths=0.5
    )
    ax.plot(x_inflow + u0_inflow, y_inflow, 'm')
    ax.plot(x_inflow - 6 * (y_inflow - 1) * y_inflow, y_inflow, 'k.', ms=4)

    # ax2 = fig.add_subplot(212)
    # ax2.plot(xf, f)
    # ax2.set_xlim(-L1, L2)

    for xi, _idx, _upcrossing in x1_c0:
        ax.plot(xi, x1_ypos, 'rx')
        # ax.text(xi, x1_ypos+0.1, 'X1=%.3f' % x1, backgroundcolor='white')

    ax.set_title(
        'Re = %g, t = %g, xi = %s' % (Re, time, ', '.join('%.3f' % e[0] for e in x1_c0))
    )
    fig.tight_layout()
예제 #15
0
class MyFigure(FigureCanvas):
    """__图像显示类__
    
    三个子图的初始化 & 三种重建图像的显示方式
    
    """
    def __init__(self, width, height, dpi):
        self.fig = plt.figure(figsize=(width, height), dpi=dpi)
        super(MyFigure, self).__init__(self.fig)
        self.gs = GridSpec(3, 2)  #画布布局

        # 用于三角剖分的顶点坐标
        self.nodes = np.array([[0.0000e+00, 0.0000e+00],
                               [0.0000e+00, 8.3333e-02],
                               [8.3333e-02, 5.1027e-18],
                               [1.0205e-17, -8.3333e-02],
                               [-8.3333e-02, -1.5308e-17],
                               [0.0000e+00, 1.6667e-01],
                               [1.1785e-01, 1.1785e-01],
                               [1.6667e-01, 1.0205e-17],
                               [1.1785e-01, -1.1785e-01],
                               [2.0411e-17, -1.6667e-01],
                               [-1.1785e-01, -1.1785e-01],
                               [-1.6667e-01, -3.0616e-17],
                               [-1.1785e-01, 1.1785e-01],
                               [0.0000e+00, 2.5000e-01],
                               [1.2500e-01, 2.1651e-01],
                               [2.1651e-01, 1.2500e-01],
                               [2.5000e-01, 1.5308e-17],
                               [2.1651e-01, -1.2500e-01],
                               [1.2500e-01, -2.1651e-01],
                               [3.0616e-17, -2.5000e-01],
                               [-1.2500e-01, -2.1651e-01],
                               [-2.1651e-01, -1.2500e-01],
                               [-2.5000e-01, -4.5924e-17],
                               [-2.1651e-01, 1.2500e-01],
                               [-1.2500e-01, 2.1651e-01],
                               [0.0000e+00, 3.3333e-01],
                               [1.2756e-01, 3.0796e-01],
                               [2.3570e-01, 2.3570e-01],
                               [3.0796e-01, 1.2756e-01],
                               [3.3333e-01, 2.0411e-17],
                               [3.0796e-01, -1.2756e-01],
                               [2.3570e-01, -2.3570e-01],
                               [1.2756e-01, -3.0796e-01],
                               [4.0822e-17, -3.3333e-01],
                               [-1.2756e-01, -3.0796e-01],
                               [-2.3570e-01, -2.3570e-01],
                               [-3.0796e-01, -1.2756e-01],
                               [-3.3333e-01, -6.1232e-17],
                               [-3.0796e-01, 1.2756e-01],
                               [-2.3570e-01, 2.3570e-01],
                               [-1.2756e-01, 3.0796e-01],
                               [0.0000e+00, 4.1667e-01],
                               [1.2876e-01, 3.9627e-01],
                               [2.4491e-01, 3.3709e-01],
                               [3.3709e-01, 2.4491e-01],
                               [3.9627e-01, 1.2876e-01],
                               [4.1667e-01, 2.5513e-17],
                               [3.9627e-01, -1.2876e-01],
                               [3.3709e-01, -2.4491e-01],
                               [2.4491e-01, -3.3709e-01],
                               [1.2876e-01, -3.9627e-01],
                               [5.1027e-17, -4.1667e-01],
                               [-1.2876e-01, -3.9627e-01],
                               [-2.4491e-01, -3.3709e-01],
                               [-3.3709e-01, -2.4491e-01],
                               [-3.9627e-01, -1.2876e-01],
                               [-4.1667e-01, -7.6540e-17],
                               [-3.9627e-01, 1.2876e-01],
                               [-3.3709e-01, 2.4491e-01],
                               [-2.4491e-01, 3.3709e-01],
                               [-1.2876e-01, 3.9627e-01],
                               [0.0000e+00, 5.0000e-01],
                               [1.2941e-01, 4.8296e-01],
                               [2.5000e-01, 4.3301e-01],
                               [3.5355e-01, 3.5355e-01],
                               [4.3301e-01, 2.5000e-01],
                               [4.8296e-01, 1.2941e-01],
                               [5.0000e-01, 3.0616e-17],
                               [4.8296e-01, -1.2941e-01],
                               [4.3301e-01, -2.5000e-01],
                               [3.5355e-01, -3.5355e-01],
                               [2.5000e-01, -4.3301e-01],
                               [1.2941e-01, -4.8296e-01],
                               [6.1232e-17, -5.0000e-01],
                               [-1.2941e-01, -4.8296e-01],
                               [-2.5000e-01, -4.3301e-01],
                               [-3.5355e-01, -3.5355e-01],
                               [-4.3301e-01, -2.5000e-01],
                               [-4.8296e-01, -1.2941e-01],
                               [-5.0000e-01, -9.1849e-17],
                               [-4.8296e-01, 1.2941e-01],
                               [-4.3301e-01, 2.5000e-01],
                               [-3.5355e-01, 3.5355e-01],
                               [-2.5000e-01, 4.3301e-01],
                               [-1.2941e-01, 4.8296e-01],
                               [0.0000e+00, 5.8333e-01],
                               [1.2980e-01, 5.6871e-01],
                               [2.5310e-01, 5.2557e-01],
                               [3.6370e-01, 4.5607e-01],
                               [4.5607e-01, 3.6370e-01],
                               [5.2557e-01, 2.5310e-01],
                               [5.6871e-01, 1.2980e-01],
                               [5.8333e-01, 3.5719e-17],
                               [5.6871e-01, -1.2980e-01],
                               [5.2557e-01, -2.5310e-01],
                               [4.5607e-01, -3.6370e-01],
                               [3.6370e-01, -4.5607e-01],
                               [2.5310e-01, -5.2557e-01],
                               [1.2980e-01, -5.6871e-01],
                               [7.1438e-17, -5.8333e-01],
                               [-1.2980e-01, -5.6871e-01],
                               [-2.5310e-01, -5.2557e-01],
                               [-3.6370e-01, -4.5607e-01],
                               [-4.5607e-01, -3.6370e-01],
                               [-5.2557e-01, -2.5310e-01],
                               [-5.6871e-01, -1.2980e-01],
                               [-5.8333e-01, -1.0716e-16],
                               [-5.6871e-01, 1.2980e-01],
                               [-5.2557e-01, 2.5310e-01],
                               [-4.5607e-01, 3.6370e-01],
                               [-3.6370e-01, 4.5607e-01],
                               [-2.5310e-01, 5.2557e-01],
                               [-1.2980e-01, 5.6871e-01],
                               [0.0000e+00, 6.6667e-01],
                               [1.3006e-01, 6.5386e-01],
                               [2.5512e-01, 6.1592e-01],
                               [3.7038e-01, 5.5431e-01],
                               [4.7140e-01, 4.7140e-01],
                               [5.5431e-01, 3.7038e-01],
                               [6.1592e-01, 2.5512e-01],
                               [6.5386e-01, 1.3006e-01],
                               [6.6667e-01, 4.0822e-17],
                               [6.5386e-01, -1.3006e-01],
                               [6.1592e-01, -2.5512e-01],
                               [5.5431e-01, -3.7038e-01],
                               [4.7140e-01, -4.7140e-01],
                               [3.7038e-01, -5.5431e-01],
                               [2.5512e-01, -6.1592e-01],
                               [1.3006e-01, -6.5386e-01],
                               [8.1643e-17, -6.6667e-01],
                               [-1.3006e-01, -6.5386e-01],
                               [-2.5512e-01, -6.1592e-01],
                               [-3.7038e-01, -5.5431e-01],
                               [-4.7140e-01, -4.7140e-01],
                               [-5.5431e-01, -3.7038e-01],
                               [-6.1592e-01, -2.5512e-01],
                               [-6.5386e-01, -1.3006e-01],
                               [-6.6667e-01, -1.2246e-16],
                               [-6.5386e-01, 1.3006e-01],
                               [-6.1592e-01, 2.5512e-01],
                               [-5.5431e-01, 3.7038e-01],
                               [-4.7140e-01, 4.7140e-01],
                               [-3.7038e-01, 5.5431e-01],
                               [-2.5512e-01, 6.1592e-01],
                               [-1.3006e-01, 6.5386e-01],
                               [0.0000e+00, 7.5000e-01],
                               [1.3024e-01, 7.3861e-01],
                               [2.5652e-01, 7.0477e-01],
                               [3.7500e-01, 6.4952e-01],
                               [4.8209e-01, 5.7453e-01],
                               [5.7453e-01, 4.8209e-01],
                               [6.4952e-01, 3.7500e-01],
                               [7.0477e-01, 2.5652e-01],
                               [7.3861e-01, 1.3024e-01],
                               [7.5000e-01, 4.5924e-17],
                               [7.3861e-01, -1.3024e-01],
                               [7.0477e-01, -2.5652e-01],
                               [6.4952e-01, -3.7500e-01],
                               [5.7453e-01, -4.8209e-01],
                               [4.8209e-01, -5.7453e-01],
                               [3.7500e-01, -6.4952e-01],
                               [2.5652e-01, -7.0477e-01],
                               [1.3024e-01, -7.3861e-01],
                               [9.1849e-17, -7.5000e-01],
                               [-1.3024e-01, -7.3861e-01],
                               [-2.5652e-01, -7.0477e-01],
                               [-3.7500e-01, -6.4952e-01],
                               [-4.8209e-01, -5.7453e-01],
                               [-5.7453e-01, -4.8209e-01],
                               [-6.4952e-01, -3.7500e-01],
                               [-7.0477e-01, -2.5652e-01],
                               [-7.3861e-01, -1.3024e-01],
                               [-7.5000e-01, -1.3777e-16],
                               [-7.3861e-01, 1.3024e-01],
                               [-7.0477e-01, 2.5652e-01],
                               [-6.4952e-01, 3.7500e-01],
                               [-5.7453e-01, 4.8209e-01],
                               [-4.8209e-01, 5.7453e-01],
                               [-3.7500e-01, 6.4952e-01],
                               [-2.5652e-01, 7.0477e-01],
                               [-1.3024e-01, 7.3861e-01],
                               [0.0000e+00, 8.3333e-01],
                               [1.3036e-01, 8.2307e-01],
                               [2.5751e-01, 7.9255e-01],
                               [3.7833e-01, 7.4251e-01],
                               [4.8982e-01, 6.7418e-01],
                               [5.8926e-01, 5.8926e-01],
                               [6.7418e-01, 4.8982e-01],
                               [7.4251e-01, 3.7833e-01],
                               [7.9255e-01, 2.5751e-01],
                               [8.2307e-01, 1.3036e-01],
                               [8.3333e-01, 5.1027e-17],
                               [8.2307e-01, -1.3036e-01],
                               [7.9255e-01, -2.5751e-01],
                               [7.4251e-01, -3.7833e-01],
                               [6.7418e-01, -4.8982e-01],
                               [5.8926e-01, -5.8926e-01],
                               [4.8982e-01, -6.7418e-01],
                               [3.7833e-01, -7.4251e-01],
                               [2.5751e-01, -7.9255e-01],
                               [1.3036e-01, -8.2307e-01],
                               [1.0205e-16, -8.3333e-01],
                               [-1.3036e-01, -8.2307e-01],
                               [-2.5751e-01, -7.9255e-01],
                               [-3.7833e-01, -7.4251e-01],
                               [-4.8982e-01, -6.7418e-01],
                               [-5.8926e-01, -5.8926e-01],
                               [-6.7418e-01, -4.8982e-01],
                               [-7.4251e-01, -3.7833e-01],
                               [-7.9255e-01, -2.5751e-01],
                               [-8.2307e-01, -1.3036e-01],
                               [-8.3333e-01, -1.5308e-16],
                               [-8.2307e-01, 1.3036e-01],
                               [-7.9255e-01, 2.5751e-01],
                               [-7.4251e-01, 3.7833e-01],
                               [-6.7418e-01, 4.8982e-01],
                               [-5.8926e-01, 5.8926e-01],
                               [-4.8982e-01, 6.7418e-01],
                               [-3.7833e-01, 7.4251e-01],
                               [-2.5751e-01, 7.9255e-01],
                               [-1.3036e-01, 8.2307e-01],
                               [0.0000e+00, 9.1667e-01],
                               [1.3046e-01, 9.0734e-01],
                               [2.5825e-01, 8.7954e-01],
                               [3.8080e-01, 8.3383e-01],
                               [4.9559e-01, 7.7115e-01],
                               [6.0029e-01, 6.9277e-01],
                               [6.9277e-01, 6.0029e-01],
                               [7.7115e-01, 4.9559e-01],
                               [8.3383e-01, 3.8080e-01],
                               [8.7954e-01, 2.5825e-01],
                               [9.0734e-01, 1.3046e-01],
                               [9.1667e-01, 2.5967e-16],
                               [9.0734e-01, -1.3046e-01],
                               [8.7954e-01, -2.5825e-01],
                               [8.3383e-01, -3.8080e-01],
                               [7.7115e-01, -4.9559e-01],
                               [6.9277e-01, -6.0029e-01],
                               [6.0029e-01, -6.9277e-01],
                               [4.9559e-01, -7.7115e-01],
                               [3.8080e-01, -8.3383e-01],
                               [2.5825e-01, -8.7954e-01],
                               [1.3046e-01, -9.0734e-01],
                               [5.1934e-16, -9.1667e-01],
                               [-1.3046e-01, -9.0734e-01],
                               [-2.5825e-01, -8.7954e-01],
                               [-3.8080e-01, -8.3383e-01],
                               [-4.9559e-01, -7.7115e-01],
                               [-6.0029e-01, -6.9277e-01],
                               [-6.9277e-01, -6.0029e-01],
                               [-7.7115e-01, -4.9559e-01],
                               [-8.3383e-01, -3.8080e-01],
                               [-8.7954e-01, -2.5825e-01],
                               [-9.0734e-01, -1.3046e-01],
                               [-9.1667e-01, -1.6839e-16],
                               [-9.0734e-01, 1.3046e-01],
                               [-8.7954e-01, 2.5825e-01],
                               [-8.3383e-01, 3.8080e-01],
                               [-7.7115e-01, 4.9559e-01],
                               [-6.9277e-01, 6.0029e-01],
                               [-6.0029e-01, 6.9277e-01],
                               [-4.9559e-01, 7.7115e-01],
                               [-3.8080e-01, 8.3383e-01],
                               [-2.5825e-01, 8.7954e-01],
                               [-1.3046e-01, 9.0734e-01],
                               [0.0000e+00, 1.0000e+00],
                               [1.3053e-01, 9.9144e-01],
                               [2.5882e-01, 9.6593e-01],
                               [3.8268e-01, 9.2388e-01],
                               [5.0000e-01, 8.6603e-01],
                               [6.0876e-01, 7.9335e-01],
                               [7.0711e-01, 7.0711e-01],
                               [7.9335e-01, 6.0876e-01],
                               [8.6603e-01, 5.0000e-01],
                               [9.2388e-01, 3.8268e-01],
                               [9.6593e-01, 2.5882e-01],
                               [9.9144e-01, 1.3053e-01],
                               [1.0000e+00, 6.1232e-17],
                               [9.9144e-01, -1.3053e-01],
                               [9.6593e-01, -2.5882e-01],
                               [9.2388e-01, -3.8268e-01],
                               [8.6603e-01, -5.0000e-01],
                               [7.9335e-01, -6.0876e-01],
                               [7.0711e-01, -7.0711e-01],
                               [6.0876e-01, -7.9335e-01],
                               [5.0000e-01, -8.6603e-01],
                               [3.8268e-01, -9.2388e-01],
                               [2.5882e-01, -9.6593e-01],
                               [1.3053e-01, -9.9144e-01],
                               [1.2246e-16, -1.0000e+00],
                               [-1.3053e-01, -9.9144e-01],
                               [-2.5882e-01, -9.6593e-01],
                               [-3.8268e-01, -9.2388e-01],
                               [-5.0000e-01, -8.6603e-01],
                               [-6.0876e-01, -7.9335e-01],
                               [-7.0711e-01, -7.0711e-01],
                               [-7.9335e-01, -6.0876e-01],
                               [-8.6603e-01, -5.0000e-01],
                               [-9.2388e-01, -3.8268e-01],
                               [-9.6593e-01, -2.5882e-01],
                               [-9.9144e-01, -1.3053e-01],
                               [-1.0000e+00, -1.8370e-16],
                               [-9.9144e-01, 1.3053e-01],
                               [-9.6593e-01, 2.5882e-01],
                               [-9.2388e-01, 3.8268e-01],
                               [-8.6603e-01, 5.0000e-01],
                               [-7.9335e-01, 6.0876e-01],
                               [-7.0711e-01, 7.0711e-01],
                               [-6.0876e-01, 7.9335e-01],
                               [-5.0000e-01, 8.6603e-01],
                               [-3.8268e-01, 9.2388e-01],
                               [-2.5882e-01, 9.6593e-01],
                               [-1.3053e-01, 9.9144e-01]])
        # 三角剖分后每个有限元的中心点坐标
        self.tripoints = np.loadtxt(
            r'D:\Proj\EIT\EIT-py\data\tripoints_mean_py.csv', delimiter=",")
        # 边界值柱状图ax1的横轴标签
        self.index_ls = [
            'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'BC', 'BD', 'BE', 'BF',
            'BG', 'BH', 'CD', 'CE', 'CF', 'CG', 'CH', 'DE', 'DF', 'DG', 'DH',
            'EF', 'EG', 'EH', 'FG', 'FH', 'GH'
        ]
        # 反投影图ax3的标注
        self.notate = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
        # 8个电极的圆心角
        self.theta = [
            2 * np.pi / 4, 1 * np.pi / 4, 0 * np.pi / 4, 7 * np.pi / 4,
            6 * np.pi / 4, 5 * np.pi / 4, 4 * np.pi / 4, 3 * np.pi / 4
        ]
        # 生成三角剖分对象
        self.triang = Triangulation(self.nodes[:, 0], self.nodes[:, 1])
        self.trifinder = self.triang.get_trifinder()
        # 图像显示色谱
        self.cmap = plt.cm.RdBu_r
        self.norm = matplotlib.colors.Normalize(vmin=-1, vmax=1)

        # ax1,ax2,ax3初始化
        self.ax1_setup()
        self.ax2_setup()
        self.ax3_setup()

    def ax1_setup(self):
        """ax1:边界数据柱状图"""
        self.ax1 = self.fig.add_subplot(self.gs[0, :], aspect='auto')
        plt.xticks(range(28), self.index_ls)  #设置横坐标标签
        plt.yticks([-10, 0, 10], c='none')  #设置纵坐标刻度范围
        plt.gca().xaxis.set_ticks_position('bottom')
        plt.gca().spines['bottom'].set_position(('data', 0))
        plt.gca().spines['right'].set_color('none')
        plt.gca().spines['left'].set_color('none')
        plt.gca().spines['top'].set_color('none')

    def ax2_setup(self):
        """ax2:图像重建显示"""
        self.ax2 = self.fig.add_subplot(self.gs[1:3, 0], aspect=1)
        self.ax2.triplot(self.triang, linewidth=0.6, color='black')  #绘制三角剖分网格
        self.ax2.set_xticks([-1, 1])
        self.ax2.set_yticks([-1, 1])
        plt.axis('off')
        self.cb = self.fig.colorbar(matplotlib.cm.ScalarMappable(
            norm=self.norm, cmap="RdBu_r"),
                                    ax=self.ax2)  # 绘制色度条
        self.cb.set_ticks([-1, 1])

    def ax3_setup(self):
        """ax3:反投影路径"""
        self.ax3 = self.fig.add_subplot(self.gs[1:3, 1],
                                        projection='polar',
                                        aspect=1)
        for i in np.arange(8):
            plt.annotate(self.notate[i],
                         xy=(self.theta[i], 1),
                         xytext=(self.theta[i], 1.1),
                         xycoords='data')
        plt.axis('off')

    def fe(self, elem_data):
        """以有限元填充方式显示重构图像"""
        self.ax2.tripcolor(self.triang,
                           elem_data,
                           cmap="RdBu_r",
                           norm=self.norm,
                           shading='flat')
        self.ax2.set_xticks([-1, 1])
        self.ax2.set_yticks([-1, 1])
        self.ax2.set_xticks([])
        self.ax2.set_yticks([])

    def interp(self, elem_data):
        """以矩阵插值方式显示重构图像"""
        self.ax2.tripcolor(self.tripoints[:, 0],
                           self.tripoints[:, 1],
                           elem_data,
                           cmap="RdBu_r",
                           norm=self.norm,
                           shading='gouraud')
        self.ax2.set_xticks([-1, 1])
        self.ax2.set_yticks([-1, 1])
        self.ax2.set_xticks([])
        self.ax2.set_yticks([])

    def contour(self, elem_data):
        """以轮廓图填充方式显示重构图像"""
        self.ax2.tricontour(self.tripoints[:, 0],
                            self.tripoints[:, 1],
                            elem_data,
                            levels=5,
                            linewidths=0.5,
                            colors='k')
        self.ax2.tricontourf(self.tripoints[:, 0],
                             self.tripoints[:, 1],
                             elem_data,
                             cmap="RdBu_r",
                             norm=self.norm,
                             levels=5)
        self.ax2.set_xticks([-1, 1])
        self.ax2.set_yticks([-1, 1])
        self.ax2.set_xticks([])
        self.ax2.set_yticks([])
예제 #16
0
    def __init__(self, width, height, dpi):
        self.fig = plt.figure(figsize=(width, height), dpi=dpi)
        super(MyFigure, self).__init__(self.fig)
        self.gs = GridSpec(3, 2)  #画布布局

        # 用于三角剖分的顶点坐标
        self.nodes = np.array([[0.0000e+00, 0.0000e+00],
                               [0.0000e+00, 8.3333e-02],
                               [8.3333e-02, 5.1027e-18],
                               [1.0205e-17, -8.3333e-02],
                               [-8.3333e-02, -1.5308e-17],
                               [0.0000e+00, 1.6667e-01],
                               [1.1785e-01, 1.1785e-01],
                               [1.6667e-01, 1.0205e-17],
                               [1.1785e-01, -1.1785e-01],
                               [2.0411e-17, -1.6667e-01],
                               [-1.1785e-01, -1.1785e-01],
                               [-1.6667e-01, -3.0616e-17],
                               [-1.1785e-01, 1.1785e-01],
                               [0.0000e+00, 2.5000e-01],
                               [1.2500e-01, 2.1651e-01],
                               [2.1651e-01, 1.2500e-01],
                               [2.5000e-01, 1.5308e-17],
                               [2.1651e-01, -1.2500e-01],
                               [1.2500e-01, -2.1651e-01],
                               [3.0616e-17, -2.5000e-01],
                               [-1.2500e-01, -2.1651e-01],
                               [-2.1651e-01, -1.2500e-01],
                               [-2.5000e-01, -4.5924e-17],
                               [-2.1651e-01, 1.2500e-01],
                               [-1.2500e-01, 2.1651e-01],
                               [0.0000e+00, 3.3333e-01],
                               [1.2756e-01, 3.0796e-01],
                               [2.3570e-01, 2.3570e-01],
                               [3.0796e-01, 1.2756e-01],
                               [3.3333e-01, 2.0411e-17],
                               [3.0796e-01, -1.2756e-01],
                               [2.3570e-01, -2.3570e-01],
                               [1.2756e-01, -3.0796e-01],
                               [4.0822e-17, -3.3333e-01],
                               [-1.2756e-01, -3.0796e-01],
                               [-2.3570e-01, -2.3570e-01],
                               [-3.0796e-01, -1.2756e-01],
                               [-3.3333e-01, -6.1232e-17],
                               [-3.0796e-01, 1.2756e-01],
                               [-2.3570e-01, 2.3570e-01],
                               [-1.2756e-01, 3.0796e-01],
                               [0.0000e+00, 4.1667e-01],
                               [1.2876e-01, 3.9627e-01],
                               [2.4491e-01, 3.3709e-01],
                               [3.3709e-01, 2.4491e-01],
                               [3.9627e-01, 1.2876e-01],
                               [4.1667e-01, 2.5513e-17],
                               [3.9627e-01, -1.2876e-01],
                               [3.3709e-01, -2.4491e-01],
                               [2.4491e-01, -3.3709e-01],
                               [1.2876e-01, -3.9627e-01],
                               [5.1027e-17, -4.1667e-01],
                               [-1.2876e-01, -3.9627e-01],
                               [-2.4491e-01, -3.3709e-01],
                               [-3.3709e-01, -2.4491e-01],
                               [-3.9627e-01, -1.2876e-01],
                               [-4.1667e-01, -7.6540e-17],
                               [-3.9627e-01, 1.2876e-01],
                               [-3.3709e-01, 2.4491e-01],
                               [-2.4491e-01, 3.3709e-01],
                               [-1.2876e-01, 3.9627e-01],
                               [0.0000e+00, 5.0000e-01],
                               [1.2941e-01, 4.8296e-01],
                               [2.5000e-01, 4.3301e-01],
                               [3.5355e-01, 3.5355e-01],
                               [4.3301e-01, 2.5000e-01],
                               [4.8296e-01, 1.2941e-01],
                               [5.0000e-01, 3.0616e-17],
                               [4.8296e-01, -1.2941e-01],
                               [4.3301e-01, -2.5000e-01],
                               [3.5355e-01, -3.5355e-01],
                               [2.5000e-01, -4.3301e-01],
                               [1.2941e-01, -4.8296e-01],
                               [6.1232e-17, -5.0000e-01],
                               [-1.2941e-01, -4.8296e-01],
                               [-2.5000e-01, -4.3301e-01],
                               [-3.5355e-01, -3.5355e-01],
                               [-4.3301e-01, -2.5000e-01],
                               [-4.8296e-01, -1.2941e-01],
                               [-5.0000e-01, -9.1849e-17],
                               [-4.8296e-01, 1.2941e-01],
                               [-4.3301e-01, 2.5000e-01],
                               [-3.5355e-01, 3.5355e-01],
                               [-2.5000e-01, 4.3301e-01],
                               [-1.2941e-01, 4.8296e-01],
                               [0.0000e+00, 5.8333e-01],
                               [1.2980e-01, 5.6871e-01],
                               [2.5310e-01, 5.2557e-01],
                               [3.6370e-01, 4.5607e-01],
                               [4.5607e-01, 3.6370e-01],
                               [5.2557e-01, 2.5310e-01],
                               [5.6871e-01, 1.2980e-01],
                               [5.8333e-01, 3.5719e-17],
                               [5.6871e-01, -1.2980e-01],
                               [5.2557e-01, -2.5310e-01],
                               [4.5607e-01, -3.6370e-01],
                               [3.6370e-01, -4.5607e-01],
                               [2.5310e-01, -5.2557e-01],
                               [1.2980e-01, -5.6871e-01],
                               [7.1438e-17, -5.8333e-01],
                               [-1.2980e-01, -5.6871e-01],
                               [-2.5310e-01, -5.2557e-01],
                               [-3.6370e-01, -4.5607e-01],
                               [-4.5607e-01, -3.6370e-01],
                               [-5.2557e-01, -2.5310e-01],
                               [-5.6871e-01, -1.2980e-01],
                               [-5.8333e-01, -1.0716e-16],
                               [-5.6871e-01, 1.2980e-01],
                               [-5.2557e-01, 2.5310e-01],
                               [-4.5607e-01, 3.6370e-01],
                               [-3.6370e-01, 4.5607e-01],
                               [-2.5310e-01, 5.2557e-01],
                               [-1.2980e-01, 5.6871e-01],
                               [0.0000e+00, 6.6667e-01],
                               [1.3006e-01, 6.5386e-01],
                               [2.5512e-01, 6.1592e-01],
                               [3.7038e-01, 5.5431e-01],
                               [4.7140e-01, 4.7140e-01],
                               [5.5431e-01, 3.7038e-01],
                               [6.1592e-01, 2.5512e-01],
                               [6.5386e-01, 1.3006e-01],
                               [6.6667e-01, 4.0822e-17],
                               [6.5386e-01, -1.3006e-01],
                               [6.1592e-01, -2.5512e-01],
                               [5.5431e-01, -3.7038e-01],
                               [4.7140e-01, -4.7140e-01],
                               [3.7038e-01, -5.5431e-01],
                               [2.5512e-01, -6.1592e-01],
                               [1.3006e-01, -6.5386e-01],
                               [8.1643e-17, -6.6667e-01],
                               [-1.3006e-01, -6.5386e-01],
                               [-2.5512e-01, -6.1592e-01],
                               [-3.7038e-01, -5.5431e-01],
                               [-4.7140e-01, -4.7140e-01],
                               [-5.5431e-01, -3.7038e-01],
                               [-6.1592e-01, -2.5512e-01],
                               [-6.5386e-01, -1.3006e-01],
                               [-6.6667e-01, -1.2246e-16],
                               [-6.5386e-01, 1.3006e-01],
                               [-6.1592e-01, 2.5512e-01],
                               [-5.5431e-01, 3.7038e-01],
                               [-4.7140e-01, 4.7140e-01],
                               [-3.7038e-01, 5.5431e-01],
                               [-2.5512e-01, 6.1592e-01],
                               [-1.3006e-01, 6.5386e-01],
                               [0.0000e+00, 7.5000e-01],
                               [1.3024e-01, 7.3861e-01],
                               [2.5652e-01, 7.0477e-01],
                               [3.7500e-01, 6.4952e-01],
                               [4.8209e-01, 5.7453e-01],
                               [5.7453e-01, 4.8209e-01],
                               [6.4952e-01, 3.7500e-01],
                               [7.0477e-01, 2.5652e-01],
                               [7.3861e-01, 1.3024e-01],
                               [7.5000e-01, 4.5924e-17],
                               [7.3861e-01, -1.3024e-01],
                               [7.0477e-01, -2.5652e-01],
                               [6.4952e-01, -3.7500e-01],
                               [5.7453e-01, -4.8209e-01],
                               [4.8209e-01, -5.7453e-01],
                               [3.7500e-01, -6.4952e-01],
                               [2.5652e-01, -7.0477e-01],
                               [1.3024e-01, -7.3861e-01],
                               [9.1849e-17, -7.5000e-01],
                               [-1.3024e-01, -7.3861e-01],
                               [-2.5652e-01, -7.0477e-01],
                               [-3.7500e-01, -6.4952e-01],
                               [-4.8209e-01, -5.7453e-01],
                               [-5.7453e-01, -4.8209e-01],
                               [-6.4952e-01, -3.7500e-01],
                               [-7.0477e-01, -2.5652e-01],
                               [-7.3861e-01, -1.3024e-01],
                               [-7.5000e-01, -1.3777e-16],
                               [-7.3861e-01, 1.3024e-01],
                               [-7.0477e-01, 2.5652e-01],
                               [-6.4952e-01, 3.7500e-01],
                               [-5.7453e-01, 4.8209e-01],
                               [-4.8209e-01, 5.7453e-01],
                               [-3.7500e-01, 6.4952e-01],
                               [-2.5652e-01, 7.0477e-01],
                               [-1.3024e-01, 7.3861e-01],
                               [0.0000e+00, 8.3333e-01],
                               [1.3036e-01, 8.2307e-01],
                               [2.5751e-01, 7.9255e-01],
                               [3.7833e-01, 7.4251e-01],
                               [4.8982e-01, 6.7418e-01],
                               [5.8926e-01, 5.8926e-01],
                               [6.7418e-01, 4.8982e-01],
                               [7.4251e-01, 3.7833e-01],
                               [7.9255e-01, 2.5751e-01],
                               [8.2307e-01, 1.3036e-01],
                               [8.3333e-01, 5.1027e-17],
                               [8.2307e-01, -1.3036e-01],
                               [7.9255e-01, -2.5751e-01],
                               [7.4251e-01, -3.7833e-01],
                               [6.7418e-01, -4.8982e-01],
                               [5.8926e-01, -5.8926e-01],
                               [4.8982e-01, -6.7418e-01],
                               [3.7833e-01, -7.4251e-01],
                               [2.5751e-01, -7.9255e-01],
                               [1.3036e-01, -8.2307e-01],
                               [1.0205e-16, -8.3333e-01],
                               [-1.3036e-01, -8.2307e-01],
                               [-2.5751e-01, -7.9255e-01],
                               [-3.7833e-01, -7.4251e-01],
                               [-4.8982e-01, -6.7418e-01],
                               [-5.8926e-01, -5.8926e-01],
                               [-6.7418e-01, -4.8982e-01],
                               [-7.4251e-01, -3.7833e-01],
                               [-7.9255e-01, -2.5751e-01],
                               [-8.2307e-01, -1.3036e-01],
                               [-8.3333e-01, -1.5308e-16],
                               [-8.2307e-01, 1.3036e-01],
                               [-7.9255e-01, 2.5751e-01],
                               [-7.4251e-01, 3.7833e-01],
                               [-6.7418e-01, 4.8982e-01],
                               [-5.8926e-01, 5.8926e-01],
                               [-4.8982e-01, 6.7418e-01],
                               [-3.7833e-01, 7.4251e-01],
                               [-2.5751e-01, 7.9255e-01],
                               [-1.3036e-01, 8.2307e-01],
                               [0.0000e+00, 9.1667e-01],
                               [1.3046e-01, 9.0734e-01],
                               [2.5825e-01, 8.7954e-01],
                               [3.8080e-01, 8.3383e-01],
                               [4.9559e-01, 7.7115e-01],
                               [6.0029e-01, 6.9277e-01],
                               [6.9277e-01, 6.0029e-01],
                               [7.7115e-01, 4.9559e-01],
                               [8.3383e-01, 3.8080e-01],
                               [8.7954e-01, 2.5825e-01],
                               [9.0734e-01, 1.3046e-01],
                               [9.1667e-01, 2.5967e-16],
                               [9.0734e-01, -1.3046e-01],
                               [8.7954e-01, -2.5825e-01],
                               [8.3383e-01, -3.8080e-01],
                               [7.7115e-01, -4.9559e-01],
                               [6.9277e-01, -6.0029e-01],
                               [6.0029e-01, -6.9277e-01],
                               [4.9559e-01, -7.7115e-01],
                               [3.8080e-01, -8.3383e-01],
                               [2.5825e-01, -8.7954e-01],
                               [1.3046e-01, -9.0734e-01],
                               [5.1934e-16, -9.1667e-01],
                               [-1.3046e-01, -9.0734e-01],
                               [-2.5825e-01, -8.7954e-01],
                               [-3.8080e-01, -8.3383e-01],
                               [-4.9559e-01, -7.7115e-01],
                               [-6.0029e-01, -6.9277e-01],
                               [-6.9277e-01, -6.0029e-01],
                               [-7.7115e-01, -4.9559e-01],
                               [-8.3383e-01, -3.8080e-01],
                               [-8.7954e-01, -2.5825e-01],
                               [-9.0734e-01, -1.3046e-01],
                               [-9.1667e-01, -1.6839e-16],
                               [-9.0734e-01, 1.3046e-01],
                               [-8.7954e-01, 2.5825e-01],
                               [-8.3383e-01, 3.8080e-01],
                               [-7.7115e-01, 4.9559e-01],
                               [-6.9277e-01, 6.0029e-01],
                               [-6.0029e-01, 6.9277e-01],
                               [-4.9559e-01, 7.7115e-01],
                               [-3.8080e-01, 8.3383e-01],
                               [-2.5825e-01, 8.7954e-01],
                               [-1.3046e-01, 9.0734e-01],
                               [0.0000e+00, 1.0000e+00],
                               [1.3053e-01, 9.9144e-01],
                               [2.5882e-01, 9.6593e-01],
                               [3.8268e-01, 9.2388e-01],
                               [5.0000e-01, 8.6603e-01],
                               [6.0876e-01, 7.9335e-01],
                               [7.0711e-01, 7.0711e-01],
                               [7.9335e-01, 6.0876e-01],
                               [8.6603e-01, 5.0000e-01],
                               [9.2388e-01, 3.8268e-01],
                               [9.6593e-01, 2.5882e-01],
                               [9.9144e-01, 1.3053e-01],
                               [1.0000e+00, 6.1232e-17],
                               [9.9144e-01, -1.3053e-01],
                               [9.6593e-01, -2.5882e-01],
                               [9.2388e-01, -3.8268e-01],
                               [8.6603e-01, -5.0000e-01],
                               [7.9335e-01, -6.0876e-01],
                               [7.0711e-01, -7.0711e-01],
                               [6.0876e-01, -7.9335e-01],
                               [5.0000e-01, -8.6603e-01],
                               [3.8268e-01, -9.2388e-01],
                               [2.5882e-01, -9.6593e-01],
                               [1.3053e-01, -9.9144e-01],
                               [1.2246e-16, -1.0000e+00],
                               [-1.3053e-01, -9.9144e-01],
                               [-2.5882e-01, -9.6593e-01],
                               [-3.8268e-01, -9.2388e-01],
                               [-5.0000e-01, -8.6603e-01],
                               [-6.0876e-01, -7.9335e-01],
                               [-7.0711e-01, -7.0711e-01],
                               [-7.9335e-01, -6.0876e-01],
                               [-8.6603e-01, -5.0000e-01],
                               [-9.2388e-01, -3.8268e-01],
                               [-9.6593e-01, -2.5882e-01],
                               [-9.9144e-01, -1.3053e-01],
                               [-1.0000e+00, -1.8370e-16],
                               [-9.9144e-01, 1.3053e-01],
                               [-9.6593e-01, 2.5882e-01],
                               [-9.2388e-01, 3.8268e-01],
                               [-8.6603e-01, 5.0000e-01],
                               [-7.9335e-01, 6.0876e-01],
                               [-7.0711e-01, 7.0711e-01],
                               [-6.0876e-01, 7.9335e-01],
                               [-5.0000e-01, 8.6603e-01],
                               [-3.8268e-01, 9.2388e-01],
                               [-2.5882e-01, 9.6593e-01],
                               [-1.3053e-01, 9.9144e-01]])
        # 三角剖分后每个有限元的中心点坐标
        self.tripoints = np.loadtxt(
            r'D:\Proj\EIT\EIT-py\data\tripoints_mean_py.csv', delimiter=",")
        # 边界值柱状图ax1的横轴标签
        self.index_ls = [
            'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'BC', 'BD', 'BE', 'BF',
            'BG', 'BH', 'CD', 'CE', 'CF', 'CG', 'CH', 'DE', 'DF', 'DG', 'DH',
            'EF', 'EG', 'EH', 'FG', 'FH', 'GH'
        ]
        # 反投影图ax3的标注
        self.notate = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
        # 8个电极的圆心角
        self.theta = [
            2 * np.pi / 4, 1 * np.pi / 4, 0 * np.pi / 4, 7 * np.pi / 4,
            6 * np.pi / 4, 5 * np.pi / 4, 4 * np.pi / 4, 3 * np.pi / 4
        ]
        # 生成三角剖分对象
        self.triang = Triangulation(self.nodes[:, 0], self.nodes[:, 1])
        self.trifinder = self.triang.get_trifinder()
        # 图像显示色谱
        self.cmap = plt.cm.RdBu_r
        self.norm = matplotlib.colors.Normalize(vmin=-1, vmax=1)

        # ax1,ax2,ax3初始化
        self.ax1_setup()
        self.ax2_setup()
        self.ax3_setup()
예제 #17
0
n_radii = 10
min_radius = 0.15
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()
z = function_z(x, y)

# Now create the Triangulation.
# (Creating a Triangulation without specifying the triangles results in the
# Delaunay triangulation of the points.)
triang = 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)

#-----------------------------------------------------------------------------
# Refine data
#-----------------------------------------------------------------------------
refiner = UniformTriRefiner(triang)
tri_refi, z_test_refi = refiner.refine_field(z, subdiv=3)

#-----------------------------------------------------------------------------
# Plot the triangulation and the high-res iso-contours
예제 #18
0
    update_polygon(tri)
    plt.title('In triangle %i' % tri)
    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)
예제 #19
0
# for k in range(0,theta.shape[0]):
#   if k < N:
#     phi[k,:] = 1.57
#   else:
#     phi[k,:] = phiTwist[k-N]


# radius in x-y plane
r = 1 + w * np.cos(phi)

x = np.ravel(r * np.cos(theta))
y = np.ravel(r * np.sin(theta))
z =  np.ravel(w * np.sin(phi))

# triangulate in the underlying parametrization
tri = Triangulation(np.ravel(w), np.ravel(theta))

ax = plt.axes(projection='3d')
ax.plot_trisurf(x, y, z, triangles=tri.triangles,
                    edgecolor='none', color='grey', linewidths=0,
                    alpha=0.5);

# x_middle = np.ravel(r_middle * np.cos(theta_middle))
# y_middle = np.ravel(r_middle * np.sin(theta_middle))
# z_middle = np.ravel(w_middle * np.sin(phi_middle))
x_middle = np.ravel(np.cos(theta))
y_middle = np.ravel(np.sin(theta))
z_middle = np.ravel(0. * np.sin(phi))
plt.plot(x_middle,y_middle,z_middle,'-m',lw=5)

plt.plot([1,-1],[0,0],[0,0.5],'og', markersize=5)
                        # (invalid) initial triangles which will be masked
                        # out. Enter 0 for no mask.

min_circle_ratio = .01  # Minimum circle ratio - border triangles with circle
                        # ratio below this will be masked if they touch a
                        # border. Suggested value 0.01 ; Use -1 to keep
                        # all triangles.

# Random points
random_gen = np.random.mtrand.RandomState(seed=127260)
x_test = random_gen.uniform(-1., 1., size=n_test)
y_test = random_gen.uniform(-1., 1., size=n_test)
z_test = experiment_res(x_test, y_test)

# meshing with Delaunay triangulation
tri = Triangulation(x_test, y_test)
ntri = tri.triangles.shape[0]

# Some invalid data are masked out
mask_init = np.zeros(ntri, dtype=np.bool)
masked_tri = random_gen.randint(0, ntri, int(ntri*init_mask_frac))
mask_init[masked_tri] = True
tri.set_mask(mask_init)


#-----------------------------------------------------------------------------
# Improving the triangulation before high-res plots: removing flat triangles
#-----------------------------------------------------------------------------
# masking badly shaped triangles at the border of the triangular mesh.
mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio)
tri.set_mask(mask)
예제 #21
0
        )
# {{{ generate the surface plot using fancy methods for a nice plot
# creates the Delauney meshing
tri_y = t_axis.ravel()
tri_x = ((f_axis[:,newaxis]*ones_like(t_axis)).ravel()
        -f_axis.mean())/1e3
tri_z = rx_axis.ravel()
# {{{ this part is actually very important, and prevents the data from
# interpolating to 0 at the edges!
# --> in the future, note that nan is a good placeholder for "lack of data"
mask = tri_y == 0 # t=0 are not valid datapoints
tri_y = tri_y[~mask]
tri_x = tri_x[~mask]
tri_z = tri_z[~mask]
# }}}
tri = Triangulation(tri_x,
        tri_y)
# {{{ refining the data -- see https://matplotlib.org/3.1.0/gallery/images_contours_and_fields/tricontour_smooth_delaunay.html#sphx-glr-gallery-images-contours-and-fields-tricontour-smooth-delaunay-py
#     I don't see a difference in the refined (tri_refi) vs. unrefined (tri),
#     but I'm quite possibly missing something, or it's more helpful in other cases
refiner = UniformTriRefiner(tri)
subdiv = 3  # Number of recursive subdivisions of the initial mesh for smooth
            # plots. Values >3 might result in a very high number of triangles
            # for the refine mesh: new triangles numbering = (4**subdiv)*ntri
tri_refi, tri_z_refi = refiner.refine_field(tri_z, subdiv=subdiv)
mask = TriAnalyzer(tri_refi).get_flat_tri_mask(10)
tri_refi = tri_refi.set_mask(~mask)
# }}}
figure(figsize=(5,15),
        facecolor=(1,1,1,0))
if not presentation:
    plot(tri_x,tri_y,'o',
예제 #22
0
    def plot_data(self, ax, column_prefix, offset=None):
        # default value workaround
        if offset is None:
            offset = self.n

        if offset > 0:
            data_portion = self.df[:offset]
            if self.drop_yearly and offset > 0:
                current_date = self.df.loc[offset - 1]['date']
                year_mask = data_portion['date'].apply(
                    lambda x: (current_date - x).days <= 365.25)
                data_portion = data_portion[year_mask]

            titles = [column_prefix + "_t" + str(i) for i in range(3)]
            # set the axial labesl
            ax.set_xlabel(titles[0])
            ax.set_ylabel(titles[1])
            ax.set_zlabel(titles[2])

            # generate the size of the dots (vector of size^2)
            size = 7 * np.ones(len(data_portion))

            if self.coloring == Coloring.DISCRETE_MONTHS_SPLIT_MARKERS or self.coloring == Coloring.DISCRETE_MONTHS_POLYGONS:
                d = {
                    "1 2 3": ("+", 'b'),
                    "4 5 6": ("o", 'g'),
                    "7 8 9": ("^", 'r'),
                    "10 11 12": ("D", 'y')
                }
                for vals, (split_marker, color) in d.items():
                    mask = data_portion['date'].apply(
                        lambda x: x.month in map(int, vals.split(" ")))
                    adf = data_portion[mask]
                    # get the actual columns
                    xs = adf[titles[0]]
                    ys = adf[titles[1]]
                    zs = adf[titles[2]]
                    if self.coloring == Coloring.DISCRETE_MONTHS_POLYGONS:
                        try:
                            X = np.array(list(zip(xs, ys, zs)))
                            if len(X) > 4:
                                cvx = ConvexHull(X)
                                tri = Triangulation(xs,
                                                    ys,
                                                    triangles=cvx.simplices)
                                ax.plot_trisurf(tri,
                                                zs,
                                                alpha=0.2,
                                                color=color)
                        except Exception:
                            print("Couldn't draw convex hull")
                    if self.coloring == Coloring.DISCRETE_MONTHS_SPLIT_MARKERS:
                        marker = split_marker
                    else:
                        marker = 'o'
                    ax.scatter(xs,
                               ys,
                               zs,
                               marker=marker,
                               s=size[mask],
                               c=color)
            else:
                xs = data_portion[titles[0]]
                ys = data_portion[titles[1]]
                zs = data_portion[titles[2]]
                if self.drop_yearly:
                    ax.scatter(xs,
                               ys,
                               zs,
                               marker="o",
                               s=size,
                               c=self.colors[:offset][year_mask])
                else:
                    ax.scatter(xs,
                               ys,
                               zs,
                               marker="o",
                               s=size,
                               c=self.colors[:offset])

            ax.set_title(self.caretype + " " + column_prefix.capitalize())
예제 #23
0
                        # (invalid) initial triangles which will be masked
                        # out. Enter 0 for no mask.

min_circle_ratio = .01  # Minimum circle ratio - border triangles with circle
                        # ratio below this will be masked if they touch a
                        # border. Suggested value 0.01; use -1 to keep
                        # all triangles.

# Random points
random_gen = np.random.RandomState(seed=19680801)
x_test = random_gen.uniform(-1., 1., size=n_test)
y_test = random_gen.uniform(-1., 1., size=n_test)
z_test = experiment_res(x_test, y_test)

# meshing with Delaunay triangulation
tri = Triangulation(x_test, y_test)
ntri = tri.triangles.shape[0]

# Some invalid data are masked out
mask_init = np.zeros(ntri, dtype=bool)
masked_tri = random_gen.randint(0, ntri, int(ntri * init_mask_frac))
mask_init[masked_tri] = True
tri.set_mask(mask_init)


#-----------------------------------------------------------------------------
# Improving the triangulation before high-res plots: removing flat triangles
#-----------------------------------------------------------------------------
# masking badly shaped triangles at the border of the triangular mesh.
mask = TriAnalyzer(tri).get_flat_tri_mask(min_circle_ratio)
tri.set_mask(mask)
class BaseTrig:
    """" Base class to be inherited by CTrig (charges) and GTrig (FE calculation).  The class handles loading
         the triangulation, calculating relevant fields and plotting. Has two plotting functions: heatmap to 
         plot spatially varying fields and boundary_plot to plot just the boundary.
    """
    def __init__(self, lattice, p, method):
        self.method = method
        self.lattice = lattice
        self.p = p  # porosity
        self.holes = None  # list of hole positions
        self.boundary = None
        self.N_holes = None
        self.tri = None  # A matplotlib Tri object.
        self.real_nodes = None
        self.mask = None  # mask for Tri object, specifies which nodes to plot.
        self.length_factor = None

    def calc_tri(self):
        self.N_holes = self.holes.shape[1]
        self.tri = Triangulation(*self.lagrange_nodes(only_real=False))
        self._set_mask()

    def _set_mask(self, crop=np.inf):
        # mask tris which involve a hole
        c1 = self.tri.triangles.min(axis=1) <= self.N_holes

        # mask tris with points outside crop
        c2 = np.abs(self.tri.x[self.tri.triangles]).max(axis=1) > crop
        c3 = np.abs(self.tri.y[self.tri.triangles]).max(axis=1) > crop
        self.mask = c1 | c2 | c3
        self.tri.set_mask(self.mask)

    def lagrange_nodes(self, only_real=True):
        if only_real:
            return self.real_nodes
        else:
            return np.c_[self.holes, self.real_nodes]

    def euler_nodes(self, only_real=True):
        nodes = np.array([self.tri.x, self.tri.y])
        if only_real:
            nodes = nodes[:, self.N_holes:]
        return nodes

    def deform(self, strain, kind='lin'):
        """
        Deforms the mesh. Kind specifiec by which field to deform the mesh. It can be either 'lin'
        for linear response or 'mode' for most unstable mode. strain is the amplitude.
        """
        if 'linear'.startswith(kind):
            H = self.lagrange_nodes()[1].max() - self.lagrange_nodes()[1].min()
            scale = H * strain / 2
            sol = scale * self.d_lin
            self.stress *= scale
        elif 'mode'.startswith(kind):
            sol = strain * self.d_mode
        else:
            raise ValueError(f'didnt understand kind={kind}')

        all_nodes = self.lagrange_nodes(only_real=False)
        self.tri.x = all_nodes[0] + self.append_shit(sol[0])
        self.tri.y = all_nodes[1] + self.append_shit(sol[1])

    def heatmap(self,
                c,
                ax=None,
                cbar=True,
                cmap=None,
                clim=None,
                cax=None,
                crop=None):
        if ax is None:
            ax = plt.gca()
        single_color = c is None
        if single_color:
            c = np.full_like(self.lagrange_nodes()[0], 0)
            clim = [-1, 1]
            color = (0.2980392156862745, 0.4470588235294118,
                     0.6901960784313725)
            cmap = mpl.colors.ListedColormap((color, color))

        if clim is None:
            levels = np.linspace(c.min(), c.max(), 20)
        else:
            levels = np.linspace(*clim, 20)
        if crop:
            self._set_mask(crop)
        if cmap is None and not single_color:
            cmap = sns.color_palette("RdBu_r", 20)
            cmap = mpl.colors.ListedColormap(cmap)

        hf = ax.tricontourf(self.tri,
                            self.append_shit(c),
                            levels=levels,
                            cmap=cmap)
        if not single_color:
            hc = ax.tricontour(self.tri,
                               self.append_shit(c),
                               levels=levels,
                               colors=['0.25', '0.5', '0.5', '0.5', '0.5'],
                               linewidths=[1.0, 0.5, 0.5, 0.5, 0.5])
        ax.set_aspect(1)
        ax.axis('off')
        if cbar:
            if cax is None:
                cbar = plt.colorbar(hf, ax=ax)
            else:
                cbar = plt.colorbar(hf, cax=cax)
        return ax, cbar

    def boundary_plot(self,
                      deformation='mode',
                      fill=True,
                      scale=1,
                      ax=None,
                      facecolor='b',
                      edgecolor='None',
                      alpha=1,
                      skip=1):
        if deformation == 'mode':
            d = self.d_mode[:, self.boundary]
        elif deformation == 'lin':
            d = self.d_lin[:, self.boundary]
        if ax is None:
            ax = plt.gca()

        reference = self.lagrange_nodes()[:, self.boundary]
        if hasattr(self, 'cyc'):
            cyc = self.cyc
        else:
            print('no cyclifier, calculating')
            cyc = Cyclifier(reference)
            self.cyc = cyc
            print('done')

        pos = reference + scale * d
        patch = patchify(cyc(pos, as_patches=True, skip=skip))
        patch.set_facecolor(facecolor)
        patch.set_edgecolor(edgecolor)
        patch.set_alpha(alpha)
        patch = ax.add_patch(patch)
        ax.axis('off')
        ax.set_xticks([])
        ax.set_yticks([])
        ax.axis('equal')
        return patch

    def append_shit(self, x, fill_value=None):
        """Prepend zeros to x on hole nodes."""
        assert x.ndim == 1
        if hasattr(x, 'values'):
            x = x.values
        if fill_value is None:
            fill = x.mean().astype(x.dtype)
        else:
            fill = fill_value
        return np.r_[fill + np.zeros(self.N_holes, dtype=x.dtype), x]

    @property
    def sxy(self):
        return self.stress[2]

    @property
    def syy(self):
        return self.stress[1]

    @property
    def sxx(self):
        return self.stress[0]
예제 #25
0
파일: stats.py 프로젝트: j08lue/oceanpy
def griddata_nn_delaunay(x,y,z,xi,yi):
    """Like matplotlib.mlab.griddata() but strictly using delaunay"""
    tri = Triangulation(x,y)
    interp = tri.nn_interpolator(z)
    return np.ma.masked_invalid(interp(xi,yi)) 
# 在下方设置选取固定范围阈值
layer.SetAttributeFilter("Velocity <= -110")
l = len(layer)
a = np.empty([l, 3])
i = 0
for feature in layer:
    a[i,0] = feature.GetField("X")
    a[i, 1] = feature.GetField("Y")
    a[i, 2] = feature.GetField("Velocity")
    # a[i, 2] = 1
    i = i+1
x_test=a[:,0]
y_test=a[:,1]
z_test=a[:,2]

tri = Triangulation(x_test, y_test)
# nedge = tri.edges.shape[0]
# l = tri.edges
#
# n = np.hypot(x_test[l[:,0]],x_test[l[:,1]])
# m = np.hypot(y_test[l[:,0]],y_test[l[:,1]])
# d = np.sqrt(n**2 + m**2)
a = tri.triangles
b1 = x_test[tri.triangles]
b2 = y_test[tri.triangles]
num = b1.shape[0]
c1 = np.empty([num,3])
c2 = np.empty([num,3])
for i in range (num):
    c1[i, 0] = b1[i, 0] - b1[i, 1]  # X
    c1[i, 1] = b1[i, 1] - b1[i, 2]
 def calc_tri(self):
     self.N_holes = self.holes.shape[1]
     self.tri = Triangulation(*self.lagrange_nodes(only_real=False))
     self._set_mask()
예제 #28
0
    def plot(self, subdivisions=None):
        """Plot the value of this :class:`Function`. This is quite a low
        performance plotting routine so it will perform poorly on
        larger meshes, but it has the advantage of supporting higher
        order function spaces than many widely available libraries.

        :param subdivisions: The number of points in each direction to
          use in representing each element. The default is
          :math:`2d+1` where :math:`d` is the degree of the
          :class:`FunctionSpace`. Higher values produce prettier plots
          which render more slowly!

        """

        fs = self.function_space

        if isinstance(fs.element, VectorFiniteElement):
            coords = Function(fs)
            coords.interpolate(lambda x: x)
            fig = plt.figure()
            ax = fig.gca()
            x = coords.values.reshape(-1, 2)
            v = self.values.reshape(-1, 2)
            plt.quiver(x[:, 0], x[:, 1], v[:, 0], v[:, 1])
            plt.show()
            return

        d = subdivisions or (2 * (fs.element.degree + 1)
                             if fs.element.degree > 1 else 2)

        if fs.element.cell is ReferenceInterval:
            fig = plt.figure()
            fig.add_subplot(111)
            # Interpolation rule for element values.
            local_coords = lagrange_points(fs.element.cell, d)

        elif fs.element.cell is ReferenceTriangle:
            fig = plt.figure()
            ax = fig.gca(projection='3d')
            local_coords, triangles = self._lagrange_triangles(d)

        else:
            raise ValueError("Unknown reference cell: %s" % fs.element.cell)

        function_map = fs.element.tabulate(local_coords)

        # Interpolation rule for coordinates.
        cg1 = LagrangeElement(fs.element.cell, 1)
        coord_map = cg1.tabulate(local_coords)
        cg1fs = FunctionSpace(fs.mesh, cg1)

        for c in range(fs.mesh.entity_counts[-1]):
            vertex_coords = fs.mesh.vertex_coords[cg1fs.cell_nodes[c, :], :]
            x = np.dot(coord_map, vertex_coords)

            local_function_coefs = self.values[fs.cell_nodes[c, :]]
            v = np.dot(function_map, local_function_coefs)

            if fs.element.cell is ReferenceInterval:

                plt.plot(x[:, 0], v, 'k')

            else:
                ax.plot_trisurf(Triangulation(x[:, 0], x[:, 1], triangles),
                                v,
                                linewidth=0)

        plt.show()
예제 #29
0
def gen_map(request, *configs):
    start = datetime.datetime.now()
    """
    example URL: http://127.0.0.1:8000/ice_oceanapi/120/122/26.5/28.5/
    :param request:The page sent the GET content request
    :return:HttpResponse object
    """
    if request.method == 'GET':
        if configs:
            # 类型名称
            type_name = request.POST.get('type_name')
            # 类型排序
            type_sort = request.POST.get('type_sort')
            current_path = os.path.dirname(os.path.abspath(__file__))
            project_path = os.path.abspath(os.path.join(current_path, '../'))
            # print(project_path)

            # https://plot.ly/python/surface-triangulation/
            # https://www.hatarilabs.com/ih-en/triangular-mesh-for-groundwater-models-with-modflow-6-and-flopy-tutorial
            """
                param extent : 确定显示区域
                param file   :  输入文件
            """
            extent = [
                float(configs[0]),
                float(configs[1]),
                float(configs[2]),
                float(configs[3])
            ]
            # extent = [120, 122, 26.5, 28.5]
            # 根据显示范围对图像长宽进行调整
            x_length = extent[0] - extent[1]
            y_length = extent[2] - extent[3]
            rat = x_length / y_length
            f1 = plt.figure(figsize=(5, 5 * rat))
            ax = f1.add_subplot(111, projection=ccrs.PlateCarree())
            canvas = f1.canvas
            # 窗口调整
            ax.axis('off')
            ax.set_position([0, 0, 1, 1])
            ax.set_extent(extent)
            for spine in ax.spines.values():
                spine.set_visible(False)
            ax.background_patch.set_visible(False)
            ax.outline_patch.set_visible(False)
            ax.set_xlim(extent[0], extent[1])
            ax.set_ylim(extent[2], extent[3])
            ax.patch.set_alpha(0.)
            # 首先需要了解的是,加在特定的环境进行数据读取
            triangles_2dm = []
            position = []
            file = 'data_depth/NSwz_001E.2dm'

            meshfile = Mesh(file)
            # print('totally time is ' + str(datetime.datetime.now() - start))
            for index in range(0, len(meshfile.ED)):
                xx = [int(values) - 1 for values in meshfile.ED[index][2:5]]
                triangles_2dm.append(xx)
            tri = Triangulation(meshfile.lon,
                                meshfile.lat,
                                triangles=triangles_2dm)
            # 调整水深
            levels = np.arange(0., 120., 10.0)
            # 颜色调整
            cmap = cm.get_cmap(name='Blues', lut=None)
            # 画图
            cntr2 = ax.tricontourf(tri,
                                   meshfile.h,
                                   levels=levels,
                                   cmap=cmap,
                                   transform=ccrs.PlateCarree())
            # 第一种保存方式(直接对plt 进行保存)
            # 保存图片
            # plt.savefig("ice_ocean\\media\\07192.png", dpi=144, bbox_inches=0.0, transparent=True, profile='tiny')
            # 第二种保存方式(获取Plt的数据并使用cv2进行保存)
            buffer = io.BytesIO()  # 获取输入输出流对象
            canvas.print_png(buffer)  # 将画布上的内容打印到输入输出流对象
            data = buffer.getvalue()  # 获取流的值
            # print("plt的二进制流为:\n", data)
            # buffer.write(data)  # 将数据写入buffer
            # img = Image.open(buffer)  # 使用Image打开图片数据
            # img = np.asarray(img)
            # print("转换的图片array为:\n", img)
            buffer.close()
            result = ""
            print('totally time is ' + str(datetime.datetime.now() - start))
            print("{0}".format(result))
            return HttpResponse(data, content_type='image/png')
        else:
            return HttpResponse('configs are wrong.')

    elif request.method == 'POST':
        return HttpResponse('Method is wrong.')
    else:
        return HttpResponse('What are you doing?')
#莫比乌斯带
u = np.linspace(0, 2 * np.pi, 30)
v = np.linspace(-0.5, 0.5, 8) / 2.0
v, u = np.meshgrid(v, u)

phi = 0.5 * u
phi
r = 1 + v * np.cos(phi)
x = np.ravel(r * np.cos(u))  #范围一维数组
y = np.ravel(r * np.sin(u))
z = np.ravel(v * np.sin(phi))

from matplotlib.tri import Triangulation
#matplotlib.tri专门针对非结构化网络作图的模块,Triangulation实现元素为三角形的非机构化网络
tri = Triangulation(np.ravel(v), np.ravel(u))

ax = plt.axes(projection='3d')
ax.plot_trisurf(x,
                y,
                z,
                triangles=tri.triangles,
                cmap='viridis',
                linewidths=0.2)

ax.set_xlim(-1, 1)
ax.set_ylim(-1, 1)
ax.set_zlim(-1, 1)

# In[42]:
예제 #31
0
    def makeLiftTriangles(self):
        # Inizializzazione liste dei triangoli di sollevamento e relativi vertici.
        VSollTrList = []
        VSollVxList = []
        TSollTrList = []
        TSollVxList = []
        TSollLabels = []  # lista di pedici dei vertici per i triangoli TSoll.
        ESollVxList = []
        ESollLabels = []

        # TSollFinder e' un dizionario tale da associare ad ogni coppia (n,i), dove n e 'un triangolo della triangolazione di partenza e V_i un suo vertice, la posizione in TSollTr del triangolo di sollevamento corrispondente.
        self.TSollFinder = {}

        # Inizializzazione liste dei coefficienti sigma.
        # TSollSigma[m] = sigma_m^t;
        # BESollSigma[i,j] = sigma_(i,j)^e
        self.TSollSigma = {}
        self.ESollSigma = {}

        # Inizializzazione del dizionario dei coefficienti alpha.
        # alpha[i][j] = alpha_i,(j+1) j=0,1,2;
        # alpha[i][j] = alpha^x_i,(j-2) j=3,4,5;
        # alpha[i][j] = alpha^y_i,(j-5) j=6,7,8.
        self.alpha = {}

        # Triangoli di sollevamento associati ai vertici.
        for i in range(len(self.domain.startPoints)):
            # Ricavo il triangolo per il vertice corrente.
            liftTr = self.findVertexLiftTriangle(i)

            # Aggiungo punti e triangolo in lista.
            codTr = []
            for pt in liftTr:
                VSollVxList.append(pt)
                codTr.append(len(VSollVxList) - 1)
            VSollTrList.append(np.array(codTr))

        # Creo la triangolazione contenente i triangoli di sollevamento associati ai vertici.
        self.VSollVx = np.array(VSollVxList)
        self.VSollTr = np.array(VSollTrList)
        self.VSoll = Triangulation(self.VSollVx[:, 0], self.VSollVx[:, 1],
                                   self.VSollTr)

        # Triangoli di sollevamento associati alla triangolazione.
        for n in range(len(self.domain.startTr.triangles)):
            for i in self.domain.startTr.triangles[n]:
                codTr = []

                # Aggiungo il punto S_{i,n}^t.
                TSollVxList.append(2 / 3 * self.domain.startPoints[i] +
                                   1 / 3 * self.domain.incenters[n])
                TSollLabels.append('$S^t_{' + str(i + 1) + ',' + str(n + 1) +
                                   '}$')
                codTr.append(len(TSollVxList) - 1)

                # Ricerca dei triangoli PS m e m' a vertice V_i.
                mList, jList = self.getPSTriangles(n, i)

                # Calcolo i coefficienti sigma^t.
                mx = max(
                    self.domain.xi[n, jList[0]] / self.domain.lamb[jList[0], i]
                    + self.domain.xi[n, jList[1]] /
                    self.domain.lamb[jList[1], i], 1)
                for l in range(2):
                    self.TSollSigma[mList[l]] = self.domain.lamb[jList[l],
                                                                 i] / 2 * mx

                # Aggiunta dei punti Q_m^t e Q_m'^t.
                for l in range(2):
                    TSollVxList.append(TSollVxList[len(TSollVxList) - 1 - l] +
                                       2 / 3 * self.TSollSigma[mList[l]] *
                                       (self.domain.startPoints[jList[l]] -
                                        self.domain.startPoints[i]))
                    TSollLabels.append('$Q^t_{' + str(mList[l] + 1) + '}$')
                    codTr.append(len(TSollVxList) - 1)

                # Aggiunta del triangolo di sollevamento e aggiornamento di TSollFinder.
                TSollTrList.append(np.array(codTr))
                self.TSollFinder[n, i] = len(TSollTrList) - 1

        # Creo la triangolazione contenente i triangoli di sollevamento associati ai vertici.
        self.TSollVx = np.array(TSollVxList)
        self.TSollTr = np.array(TSollTrList)
        self.TSollVxLabels = TSollLabels
        self.TSoll = Triangulation(self.TSollVx[:, 0], self.TSollVx[:, 1],
                                   self.TSollTr)

        # Segmenti di sollevamento associati ai lati di bordo.
        # ESollPos[i,j] memorizza la posizione di S^e_{ij} in ESollVx.
        self.ESollPos = {}
        for edge in self.domain.splitPoints:
            # se il lato edge sta nel bordo si ricavano i punti S^e_ij e Q_{ij}^e
            if self.domain.splitPoints[edge][1]:
                for i in range(2):
                    # punti S^e_{ij}
                    ESollVxList.append(
                        2 / 3 * self.domain.startPoints[edge[i]] +
                        1 / 3 * self.domain.splitPoints[edge][0])
                    ESollLabels.append('$S^e_{' + str(edge[i] + 1) + ',' +
                                       str(edge[(i + 1) % 2] + 1) + '}$')

                    # aggiorno ESollPos
                    self.ESollPos[edge[i],
                                  edge[(i + 1) % 2]] = len(ESollVxList) - 1

                    # coefficienti sigma^e_{ij}
                    self.ESollSigma[edge[i],
                                    edge[(i + 1) % 2]] = self.domain.lamb[edge[
                                        (i + 1) % 2], edge[i]] / 2

                    # punti Q^e_{ij}
                    ESollVxList.append(
                        ESollVxList[-1] +
                        2 / 3 * self.ESollSigma[edge[i], edge[(i + 1) % 2]] *
                        (self.domain.startPoints[edge[
                            (i + 1) % 2]] - self.domain.startPoints[edge[i]]))
                    ESollLabels.append('$Q^e_{' + str(edge[i] + 1) + ',' +
                                       str(edge[(i + 1) % 2] + 1) + '}$')

        # Salvo vertici ed etichette dei segmenti di sollevamento al bordo.
        self.ESollVxLabels = ESollLabels
        self.ESollVx = np.array(ESollVxList)
def scatter_xyc(points, smooth=0, div=10, ax=None, **options):
    """
    Draws a 2D graph (X,Y, color), the color is chosen based on a value *f(x,y)*
    The function requires :epkg:`matploblib` and :epkg:`scipy`.

    @param      points      (x,y, z=f(x,y) )
    @param      smooth      applies n times a smoothing I * M (convolutional)
    @param      div         number of divisions for axis
    @param      options     others options: xlabel, ylabel, title, figsize (if ax is None)
    @return                 fig, ax (fig is None if ax was sent to the function)

    .. plot::
        :include-source:

        import random
        def generate_gauss(x, y, sigma, N=1000):
            res = []
            for i in range(N):
                u = random.gauss(0, 1)
                a = sigma * u + x
                b = sigma * random.gauss(0, 1) + y + u
                res.append((a, b))
            return res
        def f(a, b):
            return (a ** 2 + b ** 2) ** 0.5
        nuage1 = generate_gauss(0, 0, 3)
        nuage2 = generate_gauss(3, 4, 2)
        nuage = [(a, b, f(a, b)) for a, b in nuage1] + [(a, b, f(a, b)) for a, b in nuage2]
        import matplotlib.pyplot as plt
        from ensae_teaching_cs.helpers.matplotlib_helper_xyz import scatter_xyc
        fig, ax = scatter_xyc(nuage, title="example with random observations")
        plt.show()

    The error ``ValueError: Unknown projection '3d'`` is raised when the line
    ``from mpl_toolkits.mplot3d import Axes3D`` is missing.
    """
    if ax is None:
        import matplotlib.pyplot as plt
        fig, ax = plt.subplots(figsize=options.get('figsize', None))
    else:
        fig = None

    x = [_[0] for _ in points]
    y = [_[1] for _ in points]
    z = [_[2] for _ in points]

    tri = Triangulation(x, y)

    plt.tricontour(tri, z, 15, linewidths=0.5, colors='k')
    plt.tricontourf(tri,
                    z,
                    15,
                    cmap=plt.cm.rainbow,
                    norm=Normalize(vmax=numpy.abs(z).max(),
                                   vmin=-numpy.abs(z).max()))
    plt.colorbar(ax=ax)
    ax.scatter(x, y, c='b', s=5, zorder=10)
    ax.set_xlim(min(x), max(x))
    ax.set_ylim(min(y), max(y))

    if "xlabel" in options:
        ax.set_xlabel(options["xlabel"])
    if "ylabel" in options:
        ax.set_ylabel(options["ylabel"])
    if "title" in options:
        ax.set_title(options["title"])
    return fig, ax
    def visualization(self, savename='figure'):

        # --> Sets figure.
        fig = plt.figure()

        # Mesh arrays.
        x = self.x[:self.nde]
        y = self.y[:self.nde]

        # Vorticity array.
        vorticity = self.vorticity[:self.nde]

        # Delaunay triangulation.
        tri = Triangulation(x, y)

        # Mask unwanted triangles.
        radius = 0.5
        xmid = tri.x[tri.triangles].mean(axis=1)
        ymid = tri.y[tri.triangles].mean(axis=1)

        xc1, yc1 = 0, 0.75
        xc2, yc2 = 0, -0.75
        xc3, yc3 = -1.5 * np.sqrt(0.75), 0
        mask = np.where((xmid - xc1)**2 + (ymid - yc1)**2 < radius**2, 1, 0)
        mask += np.where((xmid - xc2)**2 + (ymid - yc2)**2 < radius**2, 1, 0)
        mask += np.where((xmid - xc3)**2 + (ymid - yc3)**2 < radius**2, 1, 0)
        tri.set_mask(mask)

        # Plot the vorticity field.
        ax = fig.gca()
        cmap = plt.cm.RdBu
        h = ax.tripcolor(tri, vorticity, shading='gouraud', cmap=cmap)
        h.set_clim(-4, 4)
        ax.set_aspect('equal')
        ax.set_xlim(-5, 20)
        ax.set_ylim(-4, 4)

        # Set up the colorbar.
        divider = make_axes_locatable(ax)
        cax = divider.append_axes('right', size='5%', pad=0.1)
        cb = plt.colorbar(h, cax=cax)
        tick_locator = ticker.MaxNLocator(nbins=5)
        cb.locator = tick_locator
        cb.update_ticks()

        # Highlight the cylinders.
        xc, yc, r = 0., 0.75, 0.5
        circle = Circle((xc, yc), r, facecolor='None', edgecolor='k')
        ax.add_patch(circle)

        xc, yc, r = 0., -0.75, 0.5
        circle = Circle((xc, yc), r, facecolor='None', edgecolor='k')
        ax.add_patch(circle)

        xc, yc, r = -1.5 * np.sqrt(0.75), 0., 0.5
        circle = Circle((xc, yc), r, facecolor='None', edgecolor='k')
        ax.add_patch(circle)

        # Titles, labels, ...
        ax.set_xlabel(r'$x$')
        ax.locator_params(axis='y', nbins=5)
        ax.set_ylabel(r'$y$', rotation=0)

        # Save the figure.
        fig.savefig(savename + '.png', bbox_inches='tight', dpi=300)

        return fig, ax
예제 #34
0
파일: plot.py 프로젝트: ieshghi/plasmafem
def plottest(choice):
    t = np.loadtxt('./infiles/t.txt')
    p = np.loadtxt('./infiles/p.txt')
    sol = np.loadtxt('./files/sol.dat')
    solx = np.loadtxt('./files/solx.dat')
    soly = np.loadtxt('./files/soly.dat')
    diffx = np.loadtxt('./files/diffx.dat')
    diffy = np.loadtxt('./files/diffy.dat')
    ratx = np.loadtxt('./files/ratx.dat')
    raty = np.loadtxt('./files/raty.dat')
    ex = np.loadtxt('./files/ex.dat')
    ey = np.loadtxt('./files/ey.dat')
    exa = np.loadtxt('./files/exact.dat')
    boundx = np.loadtxt('./files/boundx.dat')
    boundy = np.loadtxt('./files/boundy.dat')
    exbx = np.loadtxt('./files/exbx.dat')
    exby = np.loadtxt('./files/exby.dat')
    tr = Triangulation(p[:, 0], p[:, 1], triangles=t - 1)
    if choice == 's':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, sol, cmap=plt.cm.CMRmap)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'exact':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, exa)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'sx':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, solx)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'sy':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, soly)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'dx':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, diffx)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'dy':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, diffy)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'rx':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, ratx)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'ry':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, raty)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'ex':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, ex)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'ey':
        ax = Axes3D(plt.gcf())
        ax.plot_trisurf(tr, ey)
        ax.set_xlabel('X axis')
        ax.set_ylabel('Y axis')
        ax.set_zlabel('Z axis')
    elif choice == 'boundx':
        x = boundx[:, 1]
        y = boundx[:, 0]
        plt.scatter(x, y, color='red')
        plt.show()
    elif choice == 'boundy':
        x = boundy[:, 1]
        y = boundy[:, 0]
        plt.scatter(x, y, color='red')
        plt.show()
    elif choice == 'exbx':
        x = exbx[:, 1]
        y = exbx[:, 0]
        plt.scatter(x, y)
        plt.show()
    elif choice == 'exby':
        x = exby[:, 1]
        y = exby[:, 0]
        plt.scatter(x, y)
        plt.show()
예제 #35
0
    def slice_to_array(self, slc, offset: float = 0.0, name: str = "Y"):
        """Converts a PolyData slice to a 2D NumPy array.

        It is crucial to have the true normal and origin of
        the slicing plane

        Parameters
        ----------
        slc : PolyData
            Slice as slice through a mesh.

        """

        # Get slice
        if self.debug:
            print("   Getting Slice")
        slctemp = slc.copy(deep=True)
        slctemp.points = (self.rotmat.T @ slctemp.points.T).T

        # Interpolate slices
        if self.debug:
            print("   Creating polydata")

        # Depending on the slice, column 1 or 2 will contain the points
        if offset == 0.0:
            points = np.vstack((slctemp.points[:, 0], slctemp.points[:, 2],
                                np.zeros_like(slctemp.points[:, 2]))).T
        else:
            points = np.vstack((slctemp.points[:, 0], slctemp.points[:, 1],
                                np.zeros_like(slctemp.points[:, 1]))).T

        pc = pv.PolyData(points)

        if self.debug:
            print("   Triangulate")
        mesh = pc.delaunay_2d(alpha=0.5 * 1.5 * lpy.DEG2KM)
        mesh[self.meshname] = slctemp[self.meshname]

        # Get triangles from delauney triangulation to be
        # used for interpolation
        if self.debug:
            print("   Reshape Triangles")
        xy = np.array(mesh.points[:, 0:2])
        r, t = lpy.math.cart2pol(xy[:, 0], xy[:, 1])
        findlimt = t + 4 * np.pi
        mint = np.min(findlimt) - 4 * np.pi
        maxt = np.max(findlimt) - 4 * np.pi
        cells = mesh.faces.reshape(mesh.n_cells, 4)
        triangles = np.array(cells[:, 1:4])

        # Set maximum slice length (makes no sense otherwise)
        if mint < -11.25:
            mint = -11.25
        if maxt > 11.25:
            maxt = 11.25

        # Set up intterpolation values
        dmin = np.min(lpy.base.EARTH_RADIUS_KM - r)
        dmax = np.max(lpy.base.EARTH_RADIUS_KM - r)
        dsamp = np.linspace(dmin, dmax, 1000)
        tsamp = np.linspace(mint, maxt, 1000)
        tt, dd = np.meshgrid(tsamp, dsamp)

        # you can add keyword triangles here if you have the triangle array,
        # size [Ntri,3]
        if self.debug:
            print("   Triangulation 2")
        triObj = Triangulation(t, r, triangles=triangles)

        # linear interpolation
        fz = LinearTriInterpolator(triObj, mesh[self.meshname])
        Z = fz(tt, lpy.base.EARTH_RADIUS_KM - dd)

        # Get aspect of the figure
        aspect = ((maxt - mint) * 180 / np.pi * lpy.DEG2KM) / (dmax - dmin)
        height = 4.0
        width = height * aspect

        if self.debug:
            print("   Plotting")

        # Create figure
        plt.figure(figsize=(width, height))

        plt.imshow(Z,
                   extent=[
                       mint * 180 / np.pi * lpy.DEG2KM,
                       maxt * 180 / np.pi * lpy.DEG2KM, dmax, dmin
                   ],
                   cmap=self.cmapname,
                   vmin=self.clim[0],
                   vmax=self.clim[1],
                   rasterized=True)

        from_north = np.abs(self.rotangle * 180 / np.pi) + offset
        plt.title(rf"$N{from_north:6.2f}^\circ \rightarrow$")
        plt.xlabel('Offset [km]')
        plt.ylabel('Depth [km]')

        if not self.figures_only:
            plt.show(block=False)

        plt.savefig(
            os.path.join(
                self.outputdir, f"slice_{name}_"
                f"lat{int(self.latitude+90.0)}_"
                f"lon{int(self.longitude+180.0)}_"
                f"N{int(from_north)}_{self.meshname}.pdf"))
        """
예제 #36
0
def multiview(data, suptitle='', figsize=(15, 10), **kwds):

    cs = cortex
    vtx = cs.vertices
    tri = cs.triangles
    rm = cs.region_mapping
    x, y, z = vtx.T
    lh_tri = tri[(rm[tri] < 38).any(axis=1)]
    lh_vtx = vtx[rm < 38]
    lh_x, lh_y, lh_z = lh_vtx.T
    lh_tx, lh_ty, lh_tz = lh_vtx[lh_tri].mean(axis=1).T
    rh_tri = tri[(rm[tri] >= 38).any(axis=1)]
    rh_vtx = vtx[rm < 38]
    rh_x, rh_y, rh_z = rh_vtx.T
    rh_tx, rh_ty, rh_tz = vtx[rh_tri].mean(axis=1).T
    tx, ty, tz = vtx[tri].mean(axis=1).T

    views = {
        'lh-lateral': Triangulation(-x, z, lh_tri[argsort(lh_ty)[::-1]]),
        'lh-medial': Triangulation(x, z, lh_tri[argsort(lh_ty)]),
        'rh-medial': Triangulation(-x, z, rh_tri[argsort(rh_ty)[::-1]]),
        'rh-lateral': Triangulation(x, z, rh_tri[argsort(rh_ty)]),
        'both-superior': Triangulation(y, x, tri[argsort(tz)]),
    }

    def plotview(i,
                 j,
                 k,
                 viewkey,
                 z=None,
                 zlim=None,
                 zthresh=None,
                 suptitle='',
                 shaded=True,
                 cmap=plt.cm.coolwarm,
                 viewlabel=False):
        v = views[viewkey]
        ax = subplot(i, j, k)
        if z is None:
            z = rand(v.x.shape[0])
        if not viewlabel:
            axis('off')
        kwargs = {
            'shading': 'gouraud'
        } if shaded else {
            'edgecolors': 'k',
            'linewidth': 0.1
        }
        if zthresh:
            z = z.copy() * (abs(z) > zthresh)
        tc = ax.tripcolor(v, z, cmap=cmap, **kwargs)
        if zlim:
            tc.set_clim(vmin=-zlim, vmax=zlim)
        ax.set_aspect('equal')
        if suptitle:
            ax.set_title(suptitle, fontsize=24)
        if viewlabel:
            xlabel(viewkey)

    figure(figsize=figsize)
    plotview(2, 3, 1, 'lh-lateral', data, **kwds)
    plotview(2, 3, 4, 'lh-medial', data, **kwds)
    plotview(2, 3, 3, 'rh-lateral', data, **kwds)
    plotview(2, 3, 6, 'rh-medial', data, **kwds)
    plotview(1, 3, 2, 'both-superior', data, suptitle=suptitle, **kwds)
    subplots_adjust(left=0.0,
                    right=1.0,
                    bottom=0.0,
                    top=1.0,
                    wspace=0,
                    hspace=0)
예제 #37
0
    update_polygon(tri)
    plt.title('In triangle %i' % tri)
    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)
예제 #38
0
파일: _base.py 프로젝트: jreniel/adcircpy
 def triangulation(self):
     if len(self.tria3) > 0:
         return Triangulation(self.x, self.y, self.tria3)
예제 #39
0
def subdivideMesh(IKLE,MESHX,MESHY):
   """
   Requires the matplotlib.tri package to be loaded.
    - Will use already computed edges or re-create it if necessary.
   This function return a new tuple IKLE,MESHX,MESHY where each triangle has been
      subdivided in 4.
   """
   # ~~> Singling out edges
   from matplotlib.tri import Triangulation
   edges = Triangulation(MESHX,MESHY,IKLE).get_cpp_triangulation().get_edges()

   # ~~> Memory allocation for new MESH
   IELEM = len(IKLE); IPOIN = len(MESHX); IEDGE = len(edges)
   JKLE = np.zeros((IELEM*4,3),dtype=np.int)       # you subdivide every elements by 4
   MESHJ = np.zeros((IEDGE,2),dtype=np.int)        # you add one point on every edges

   # ~~> Lookup tables for node numbering on common edges
   pa,pb = edges.T
   k1b,k1a = np.sort(np.take(IKLE,[0,1],axis=1)).T
   indx1 = np.searchsorted(pa,k1a)
   jndx1 = np.searchsorted(pa,k1a,side='right')
   k2b,k2a = np.sort(np.take(IKLE,[1,2],axis=1)).T
   indx2 = np.searchsorted(pa,k2a)
   jndx2 = np.searchsorted(pa,k2a,side='right')
   k3b,k3a = np.sort(np.take(IKLE,[2,0],axis=1)).T
   indx3 = np.searchsorted(pa,k3a)
   jndx3 = np.searchsorted(pa,k3a,side='right')

   # ~~> Building one triangle at a time /!\ Please get this loop parallelised
   j = 0
   for i in range(IELEM):
      k1 = indx1[i]+np.searchsorted(pb[indx1[i]:jndx1[i]],k1b[i])
      k2 = indx2[i]+np.searchsorted(pb[indx2[i]:jndx2[i]],k2b[i])
      k3 = indx3[i]+np.searchsorted(pb[indx3[i]:jndx3[i]],k3b[i])
      # ~~> New connectivity JKLE
      JKLE[j] = [IKLE[i][0],IPOIN+k1,IPOIN+k3]
      JKLE[j+1] = [IKLE[i][1],IPOIN+k2,IPOIN+k1]
      JKLE[j+2] = [IKLE[i][2],IPOIN+k3,IPOIN+k2]
      JKLE[j+3] = [IPOIN+k1,IPOIN+k2,IPOIN+k3]
      # ~~> New interpolation references for values and coordinates
      MESHJ[k1] = [IKLE[i][0],IKLE[i][1]]
      MESHJ[k2] = [IKLE[i][1],IKLE[i][2]]
      MESHJ[k3] = [IKLE[i][2],IKLE[i][0]]
      j += 4

   # ~~> Reset IPOBO while you are at it
   MESHX = np.resize(MESHX,IPOIN+IEDGE)
   MESHY = np.resize(MESHY,IPOIN+IEDGE)
   MESHX[IPOIN:] = np.sum(MESHX[MESHJ],axis=1)/2.
   MESHY[IPOIN:] = np.sum(MESHY[MESHJ],axis=1)/2.
   neighbours = Triangulation(MESHX,MESHY,JKLE).get_cpp_triangulation().get_neighbors()
   JPOBO = np.zeros(IPOIN+IEDGE,np.int)
   for n in range(IELEM*4):
      s1,s2,s3 = neighbours[n]
      e1,e2,e3 = JKLE[n]
      if s1 < 0:
        JPOBO[e1] = e1+1
        JPOBO[e2] = e2+1
      if s2 < 0:
        JPOBO[e2] = e2+1
        JPOBO[e3] = e3+1
      if s3 < 0:
        JPOBO[e3] = e3+1
        JPOBO[e1] = e1+1

   return JKLE,MESHX,MESHY,JPOBO,MESHJ
예제 #40
0
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)

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

# Mask off unwanted triangles.
triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
                         y[triang.triangles].mean(axis=1))
                < min_radius)

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

#-----------------------------------------------------------------------------
# Computes the electrical field (Ex, Ey) as gradient of electrical potential
#-----------------------------------------------------------------------------
예제 #41
0
def sliceMesh(polyline,IKLE,MESHX,MESHY,tree=None):
   """
   A new method to slice through a triangular mesh (replaces crossMesh)
   """
   from matplotlib.tri import Triangulation
   xys = []
   douplets = []
   # ~~> Calculate the minimum mesh resolution
   dxy = math.sqrt(min(np.square(np.sum(np.fabs(MESHX[IKLE]-MESHX[np.roll(IKLE,1)]),axis=1)/3.0) + \
            np.square(np.sum(np.fabs(MESHY[IKLE]-MESHY[np.roll(IKLE,1)]),axis=1)/3.0)))
   accuracy = np.power(10.0, -8+np.floor(np.log10(dxy)))

   xyo = np.array(polyline[0])
   for i in range(len(polyline)-1):
      xyi = np.array(polyline[i+1])
      dio = math.sqrt(sum(np.square(xyo-xyi)))

      # ~~> Resample the line to that minimum mesh resolution
      rsmpline = np.dstack((np.linspace(xyo[0],xyi[0],num=int(dio/dxy)),np.linspace(xyo[1],xyi[1],num=int(dio/dxy))))[0]
      nbpoints = len(rsmpline)
      nbneighs = min( 8,len(IKLE) )
      # ~~> Filter closest 8 elements (please create a good mesh) as a halo around the polyline
      halo = np.zeros((nbpoints,nbneighs),dtype=np.int)
      for i in range(nbpoints):
         d,e = tree.query(rsmpline[i],nbneighs)
         halo[i] = e
      halo = np.unique(halo)

      # ~~> Get the intersecting halo (on a smaller mesh connectivity)
      edges = Triangulation(MESHX,MESHY,IKLE[halo]).get_cpp_triangulation().get_edges()

      # ~~> Last filter, all nodes that are on the polyline
      olah = []
      nodes = np.unique(edges)
      for node in nodes:  # TODO(jcp): replace by numpy calcs
         if getDistancePointToLine((MESHX[node],MESHY[node]),xyo,xyi) < accuracy: olah.append(node)
      ijsect = zip(olah,olah)
      xysect = [(MESHX[i],MESHY[i]) for i in olah]
      lmsect = [ (1.0,0.0) for i in range(len(ijsect)) ]
      mask = np.zeros((len(edges),2),dtype=bool)
      for i in olah:
         mask = np.logical_or( edges == i  , mask )
      edges = np.compress(np.logical_not(np.any(mask,axis=1)),edges,axis=0)

      # ~~> Intersection with remaining edges
      for edge in edges:
         xyj = getSegmentIntersection( (MESHX[edge[0]],MESHY[edge[0]]),(MESHX[edge[1]],MESHY[edge[1]]),xyo,xyi )
         if xyj != []:
            ijsect.append(edge)     # nodes from the mesh
            xysect.append(tuple(xyj[0]))   # intersection (xo,yo)
            lmsect.append((xyj[1],1.0-xyj[1]))   # weight along each each

      # ~~> Final sorting along keys x and y
      xysect = np.array(xysect, dtype=[('x', '<f4'), ('y', '<f4')])
      xysort = np.argsort(xysect, order=('x','y'))

      # ~~> Move on to next point
      for i in xysort:
         xys.append( xysect[i] )
         douplets.append( (ijsect[i],lmsect[i]) )
      xyo = xyi

   return xys,douplets
def reload(self, imageName, seed, scale):
    try:
        #Let's create a canvas

        #voronoiCircles = []
        self.w.pack()
        self.w.delete("all")
        #Let's create an image
        image = Image.open(imageName)
        colors = []
        pixels = image.load()
        width, height = image.size
        #print(width)
        #Just a testing data structure. Don't use this.
        all_pixels = []
        #Use this one when doing calculations.
        points = []
        xarray = []
        yarray = []
        color = ["red", "orange", "yellow", "green", "blue", "violet"]
        #loop(self, points, pixels, all_pixels, width, height)
        for x in range(width):
            for y in range(height):
                cpixel = pixels[x, y]
                #colors.append(cpixel)
                #print(cpixel)
                foo = random.randint(1, seed)
                #if (round(sum(cpixel)) / float(len(cpixel)) > 127) & (x%foo == 0) & (y%foo == 0):
                if ( x%foo == 0) and (y%foo == 0):
                    all_pixels.append(255)
                    points.append(Point(x*scale, y*scale))
                    xarray.append(x*scale)
                    yarray.append(y*scale)
                    colors.append(cpixel)
                    #self.w.create_oval(x*2, y*2, x*2+1, y*2+1, fill="black")
                #else:
                 #   all_pixels.append(0)                #print(all_pixels)

        triangulation = Triangulation(xarray, yarray)
        triangles = triangulation.get_masked_triangles()
        #triangles = triangulation.triangles()
        #print(triangles)
        for triangle in triangles:
            x1 = xarray[triangle[0]]
            y1 = yarray[triangle[0]]
            x2 = xarray[triangle[1]]
            y2 = yarray[triangle[1]]
            x3 = xarray[triangle[2]]
            y3 = yarray[triangle[2]]
            #print(circumcircle(circle))
            #red= colors[triangle[0]][0]
            try:
                red=colors[triangle[0]][0]
                green= colors[triangle[0]][1]
                blue= colors[triangle[0]][2]
                mycolor = '#%02x%02x%02x' % (red, green, blue)
            except IndexError:
                if colors[triangle[0]][1] > 100:
                    mycolor='black'
                else:
                    mycolor='white'
            self.w.create_polygon([x1, y1], [x2, y2], [x3, y3], fill=mycolor)
            center = circumcenter([x1, y1], [x2, y2], [x3, y3])
            bisector1 = [[(x1+x2)/2], [(y1+y2)/2]]
            bisector2 = [[(x2+x3)/2], [(y2+y3)/2]]
            bisector3 = [[(x3+x1)/2], [(y3+y1)/2]]
            self.w.create_line(center[0], center[1], bisector1[0], bisector1[1])
            self.w.create_line(center[0], center[1], bisector2[0], bisector2[1])
            self.w.create_line(center[0], center[1], bisector3[0], bisector3[1])
            #self.w.create_oval(center[0]-1, center[1]-1, center[0]+1, center[1]+1, fill="black")
            #create_circle(self.w, center[0], center[1], center[2])
            #voronoiCircles.append(center)
    except (AttributeError, IOError, FileNotFoundError):
        pass
        """
예제 #43
0
def hitlist2int_list(x, y):
    """Function that estimates an intensity distribution on a plane from a
    ray hitlist. Returns the intensity samples as an x,y,I list
    """
    from pylab import meshgrid
    from scipy import interpolate
    from scipy.interpolate import griddata

    #if xi.ndim != yi.ndim:
    #    raise TypeError("inputs xi and yi must have same number of dimensions (1 or 2)")
    #if xi.ndim != 1 and xi.ndim != 2:
    #    raise TypeError("inputs xi and yi must be 1D or 2D.")
    #if not len(x)==len(y)==len(z):
    #    raise TypeError("inputs x,y,z must all be 1D arrays of the same length")
    # remove masked points.
    #if hasattr(z,'mask'):
    #    x = x.compress(z.mask == False)
    #    y = y.compress(z.mask == False)
    #    z = z.compressed()

    #if xi.ndim == 1:
    #    xi,yi = meshgrid(xi,yi)

    #triangulate data

    tri = Triangulation(x, y)

    #calculate triangles area
    #ntriangles=tri.circumcenters.shape[0]
    coord = array(zip(tri.x, tri.y))

    #I=zeros((ntriangles, ))
    #xc=zeros((ntriangles, ))
    #yc=zeros((ntriangles, ))
    # for i in range(ntriangles):
    #     i1, i2, i3=tri.triangle_nodes[i]
    #     p1=coord[i1]
    #     p2=coord[i2]
    #     p3=coord[i3]
    #     v1=p1-p2
    #     v2=p3-p2
    #     I[i]=1./(abs(v1[0]*v2[1]-v1[1]*v2[0]))
    #     # the circumcenter data from the triangulation, has some problems so we
    #     # recalculate it
    #     xc[i], yc[i]=(p1+p2+p3)/3.
    # The previous code was replaced by the following code
    ###
    i1 = tri.triangles[:, 0]
    i2 = tri.triangles[:, 1]
    i3 = tri.triangles[:, 2]
    p1 = coord[i1]
    p2 = coord[i2]
    p3 = coord[i3]

    v1 = p1 - p2
    v2 = p3 - p2
    I = abs(1. / (v1[:, 0] * v2[:, 1] - v1[:, 1] * v2[:, 0]))

    c = (p1 + p2 + p3) / 3.
    xc = c[:, 0]
    yc = c[:, 1]
    ###

    # Because of the triangulation algorithm, there are some really high values
    # in the intensity data. To filter these values, remove the 5% points of the
    # higher intensity.
    ni = int(0.1 * len(I))
    j = I.argsort()[:-ni]
    xc = xc[j]
    yc = yc[j]
    I = I[j]
    I = I / I.max()

    #    #print tri.circumcenters[:, 0]
    #    #print tri.circumcenters.shape
    #    print ntriangles,  tri.circumcenters[:, 0].shape,  tri.circumcenters[:, 0].flatten().shape

    #itri=delaunay.Triangulation(xc,yc)
    #inti=itri.linear_interpolator(I)
    #xi,yi = meshgrid(xi,yi)
    #d1=itri(xi, yi)

    #Interpolacion con Splines
    #di=interpolate.SmoothBivariateSpline(xc, yc, I)
    #d1=di(xi,yi)

    return xc, yc, I