Ejemplo n.º 1
0
def complex_mesh(r, filename, n):
    import meshio
    mesh = meshio.read(filename)
    node = mesh.points
    node = node[:,0:2]*r
    cell = mesh.cells
    mesh.node = node
    mesh.cell = cell
    cell = cell['triangle']
    isUsingNode = np.zeros(node.shape[0], dtype=np.bool)
    isUsingNode[cell] = True
    NN = isUsingNode.sum()
    idxmap = np.zeros(node.shape[0], dtype=np.int32)
    idxmap[isUsingNode] = range(NN)
    cell = idxmap[cell]
    node = node[isUsingNode]
    #cell = cell[:,::-1]
    mesh = TriangleMesh(node,cell)
    nmesh = TriangleMeshWithInfinityNode(mesh)
    ppoint, pcell, pcellLocation =  nmesh.to_polygonmesh()
    pmesh = PolygonMesh(ppoint, pcell, pcellLocation)
    hmesh = HalfEdgeMesh2d.from_mesh(pmesh)
    hmesh.init_level_info()
    hmesh.convexity()
    hmesh.uniform_refine(n=n)
    mesh = PolygonMesh.from_halfedgemesh(hmesh)
    return mesh
    def verify_matrix(self, u, p=2, mtype=0, plot=True):
        from fealpy.mesh.simple_mesh_generator import triangle
        if mtype == 0:
            node = np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)],
                            dtype=np.float)
            cell = np.array([0, 1, 2, 3], dtype=np.int)
            cellLocation = np.array([0, 4], dtype=np.int)
            mesh = PolygonMesh(node, cell, cellLocation)
        elif mtype == 1:
            node = np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)],
                            dtype=np.float)
            cell = np.array([0, 1, 2, 3, 0, 2], dtype=np.int)
            cellLocation = np.array([0, 3, 6], dtype=np.int)
            mesh = PolygonMesh(node, cell, cellLocation)
        elif mtype == 2:
            h = 0.1
            mesh = triangle([-1, 1, -1, 1], h, meshtype='polygon')
        elif mtype == 3:
            node = np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)],
                            dtype=np.float)
            cell = np.array([[0, 1, 2, 3]], dtype=np.int)
            mesh = QuadrangleMesh(node, cell)
            mesh.uniform_refine()
            mesh = PolygonMesh.from_mesh(mesh)

        uspace = ReducedDivFreeNonConformingVirtualElementSpace2d(mesh, p)
        uspace.verify_matrix()
        up = uspace.project(u)
        up = uspace.project_to_smspace(up)
Ejemplo n.º 3
0
    def polyMesh(self):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgeMesh2d.from_mesh(mesh)
        mesh.init_level_info()

        return mesh
def load_mesh(f):
    data = sio.loadmat('../meshdata/' + f)
    point = data['point']
    cell = np.array(data['cell'].reshape(-1), dtype=np.int)
    cellLocation = np.array(data['cellLocation'].reshape(-1), dtype=np.int)
    mesh = PolygonMesh(point, cell, cellLocation)
    return mesh
Ejemplo n.º 5
0
 def init_mesh(self, n=1, meshtype='tri'):
     node = np.array([
         (-1, -1),
         ( 0, -1),
         ( 1, -1),
         (-1,  0),
         ( 0,  0),
         ( 1,  0),
         (-1,  1),
         ( 0,  1)], dtype=np.float)
     if meshtype == 'tri':
         cell = np.array([
             (3, 0, 4),
             (1, 4, 0),
             (4, 1, 5),
             (2, 5, 1),
             (6, 3, 7),
             (4, 7, 3)], dtype=np.int)
         mesh = TriangleMesh(node, cell)
         mesh.uniform_refine(n)
         return mesh
     elif meshtype == 'poly':
         cell = np.array([
             (3, 0, 4),
             (1, 4, 0),
             (4, 1, 5),
             (2, 5, 1),
             (6, 3, 7),
             (4, 7, 3)], dtype=np.int)
         mesh = TriangleMesh(node, cell)
         mesh.uniform_refine(n)
         nmesh = TriangleMeshWithInfinityNode(mesh)
         pnode, pcell, pcellLocation = nmesh.to_polygonmesh()
         pmesh = PolygonMesh(pnode, pcell, pcellLocation)
         return pmesh
Ejemplo n.º 6
0
    def init_mesh(self, n=1, meshtype='tri'):
        node = np.array([
            (0, 0),
            (1, 0),
            (1, 1),
            (0, 1)], dtype=np.float)

        if meshtype == 'tri':
            cell = np.array([
                (1, 2, 0),
                (3, 0, 2)], dtype=np.int)
            mesh = TriangleMesh(node, cell)
            mesh.uniform_refine(n)
            return mesh
        elif meshtype == 'quad':
            nx = 4
            ny = 4
            mesh = StructureQuadMesh(self.box, nx, ny)
            mesh.uniform_refine(n)
            return mesh
        elif meshtype == 'poly':
            cell = np.array([
                (1, 2, 0),
                (3, 0, 2)], dtype=np.int)
            mesh = TriangleMesh(node, cell)
            mesh.uniform_refine(n)
            nmesh = TriangleMeshWithInfinityNode(mesh)
            pnode, pcell, pcellLocation = nmesh.to_polygonmesh()
            pmesh = PolygonMesh(pnode, pcell, pcellLocation)
            return pmesh
Ejemplo n.º 7
0
    def matrix_test(self, p=2):
        """
        node = np.array([
            (-1.0, -1.0),
            ( 0.0, -1.0),
            ( 1.0, -1.0),
            (-1.0, 0.0),
            ( 1.0, 0.0),
            (-1.0, 1.0),
            ( 0.0, 1.0),
            ( 1.0, 1.0)], dtype=np.float)
        cell = np.array([0, 1, 2, 4, 7, 6, 5, 3], dtype=np.int)
        cellLocation = np.array([0, 8], dtype=np.int)
        mesh = PolygonMesh(node, cell, cellLocation)
        """

        node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                        dtype=np.float)
        cell = np.array([0, 1, 2, 3], dtype=np.int)
        cellLocation = np.array([0, 4], dtype=np.int)
        mesh = PolygonMesh(node, cell, cellLocation)
        space = DivFreeNonConformingVirtualElementSpace2d(mesh, p)
        print("G:", space.G)
        print("B:", space.B)
        print("R:", space.R)
        print("J:", space.J)
        print("Q:", space.Q)
        print("L:", space.L)
        print("D:", space.D)
Ejemplo n.º 8
0
    def boundary_edge_to_edge_test(self, plot=True):

        node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                        dtype=np.float)
        cell = np.array([0, 1, 2, 3], dtype=np.int)
        cellLocation = np.array([0, 4], dtype=np.int)
        mesh = PolygonMesh(node, cell, cellLocation)
        mesh.ds.boundary_edge_to_edge()
        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_edge(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)
            plt.show()
Ejemplo n.º 9
0
    def one_cell_test_0(self, p=2):
        from fealpy.pde.stokes_model_2d import StokesModelData_7
        pde = StokesModelData_7()
        node = np.array([(-1, -1), (1, -1), (1, 1), (-1, 1)], dtype=np.float)
        cell = np.array([0, 1, 2, 3], dtype=np.int)
        cellLocation = np.array([0, 4], dtype=np.int)
        mesh = PolygonMesh(node, cell, cellLocation)

        uspace = DivFreeNonConformingVirtualElementSpace2d(mesh, p)
        pspace = ScaledMonomialSpace2d(mesh, p - 1)
        ldof = pspace.number_of_local_dofs()

        isBdDof = uspace.boundary_dof()

        udof = uspace.number_of_global_dofs()
        pdof = pspace.number_of_global_dofs()

        uh = uspace.function()
        ph = pspace.function()
        uspace.set_dirichlet_bc(uh, pde.dirichlet)

        A = uspace.matrix_A()
        P = uspace.matrix_P()
        C = uspace.CM[:, 0, :ldof].reshape(-1)
        F = uspace.source_vector(pde.source)

        AA = bmat([[A, P.T, None], [P, None, C[:, None]], [None, C, None]],
                  format='csr')
        FF = np.block([F, np.zeros(pdof + 1, dtype=uspace.ftype)])
        x = np.block([uh, ph, np.zeros((1, ), dtype=uspace.ftype)])
        isBdDof = np.r_['0', isBdDof, np.zeros(pdof + 1, dtype=np.bool)]
        gdof = udof + pdof + 1

        FF -= AA @ x
        bdIdx = np.zeros(gdof, dtype=np.int)
        bdIdx[isBdDof] = 1
        Tbd = spdiags(bdIdx, 0, gdof, gdof)
        T = spdiags(1 - bdIdx, 0, gdof, gdof)
        AA = T @ AA @ T + Tbd
        FF[isBdDof] = x[isBdDof]
        x[:] = spsolve(AA, FF)
        uh[:] = x[:udof]
        ph[:] = x[udof:-1]
        print('ph:', ph)

        print('uh:', uh)
        up = uspace.project_to_smspace(uh)
        print('up:', up)
        integralalg = uspace.integralalg
        error = integralalg.L2_error(pde.velocity, up)
        print(error)

        uv = uspace.project(pde.velocity)
        print('uproject:', uv)
        up = uspace.project_to_smspace(uv)
        print('up', up)

        error = integralalg.L2_error(pde.velocity, up)
        print(error)
Ejemplo n.º 10
0
 def matrix_A_test(self, p=2):
     node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                     dtype=np.float)
     cell = np.array([0, 1, 2, 3], dtype=np.int)
     cellLocation = np.array([0, 4], dtype=np.int)
     mesh = PolygonMesh(node, cell, cellLocation)
     space = DivFreeNonConformingVirtualElementSpace2d(mesh, p)
     A = space.matrix_A()
     print(A)
Ejemplo n.º 11
0
 def index2_test(self, p=2):
     node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                     dtype=np.float)
     cell = np.array([0, 1, 2, 3], dtype=np.int)
     cellLocation = np.array([0, 4], dtype=np.int)
     mesh = PolygonMesh(node, cell, cellLocation)
     space = DivFreeNonConformingVirtualElementSpace2d(mesh, 3)
     idx = space.index2(p=p)
     print("p=", p, idx)
Ejemplo n.º 12
0
 def index2_test(self, p=2):
     node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                     dtype=np.float)
     cell = np.array([0, 1, 2, 3], dtype=np.int)
     cellLocation = np.array([0, 4], dtype=np.int)
     mesh = PolygonMesh(node, cell, cellLocation)
     space = ScaledMonomialSpace2d(mesh, 3)
     idx = space.index2(p=p)
     print("p=", p, "\n", idx)
Ejemplo n.º 13
0
    def run(self, estimator='mix'):
        problem = self.problem
        options = self.optoptions
        model = problem['objective']

        optalg = SteepestDescentAlg(problem, options)
        x, f, g, diff = optalg.run(maxit=1)
        while True:
            mesh = problem['mesh']
            hmesh = HalfEdgeMesh2d.from_mesh(mesh)
            cell, cellLocation = hmesh.entity('cell')
            print('2', cellLocation)
            aopts = hmesh.adaptive_options(method='mean',
                                           maxcoarsen=3,
                                           HB=True)
            print('NN', mesh.number_of_nodes())
            mu = problem['x0']
            if estimator == 'mix':
                eta = model.mix_estimate(mu, w=1)
            if estimator == 'grad':
                eta = model.estimate(q)

            aopts['data'] = {'mu': mu}
            S0 = model.vemspace.project_to_smspace(aopts['data']['mu'][:, 0])
            S1 = model.vemspace.project_to_smspace(aopts['data']['mu'][:, 1])

            hmesh.adaptive(eta, aopts)
            #fig = plt.figure()
            #axes = fig.gca()
            #hmesh.add_plot(axes)
            #hmesh.find_cell(axes, showindex=True)
            #plt.show()

            cell, cellLocation = hmesh.entity('cell')
            print('3', cellLocation)
            mesh = PolygonMesh.from_halfedgemesh(hmesh)

            model.reinit(mesh)
            aopts['data']['mu'] = np.zeros((model.gdof, 2))
            aopts['data']['mu'][:, 0] = model.vemspace.interpolation(
                S0, aopts['HB'])
            aopts['data']['mu'][:, 1] = model.vemspace.interpolation(
                S1, aopts['HB'])
            problem['x0'] = aopts['data']['mu']

            optalg = SteepestDescentAlg(problem, options)
            x, f, g, diff = optalg.run(maxit=1)
            problem['mesh'] = mesh
            problem['x0'] = x
            problem['rho'] = model.rho
            self.problem = problem

            if diff < options['FunValDiff']:
                if (np.max(problem['rho'][:, 0]) < 1) and (np.min(
                        problem['rho'][:, 0]) > 0):
                    break
            pass
Ejemplo n.º 14
0
    def edge_mass_matrix_test(self, p=2):

        node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                        dtype=np.float)
        cell = np.array([0, 1, 2, 3], dtype=np.int)
        cellLocation = np.array([0, 4], dtype=np.int)
        mesh = PolygonMesh(node, cell, cellLocation)
        space = ScaledMonomialSpace2d(mesh, 3)
        print("new: p=", p, "\n", space.edge_mass_matrix(p=p))
        print("old: p=", p, "\n", space.edge_mass_matrix_1(p=p))
Ejemplo n.º 15
0
    def show_solution_test(self):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float) / 2.0
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgePolygonMesh.from_polygonmesh(mesh)

        def u(p):
            pi = np.pi
            x = p[..., 0]
            y = p[..., 1]
            return np.sin(pi * x) * np.sin(pi * y)

        node = mesh.entity('node')
        solution = u(node)

        plot = MatlabShow()
        plot.show_solution(mesh, solution)
Ejemplo n.º 16
0
 def project_test(self, p=2, m=0):
     if m == 0:
         node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                         dtype=np.float)
         cell = np.array([0, 1, 2, 3], dtype=np.int)
         cellLocation = np.array([0, 4], dtype=np.int)
         mesh = PolygonMesh(node, cell, cellLocation)
     elif m == 1:
         pde = CosCosData()
         qtree = pde.init_mesh(n=4, meshtype='quadtree')
         mesh = qtree.to_polygonmesh()
     points = np.array([[(0.5, 0.5), (0.6, 0.6)]], dtype=np.float)
     space = ScaledMonomialSpace2d(mesh, p)
     gphi = space.grad_basis(points)
     print(gphi)
Ejemplo n.º 17
0
def halfedgemesh(h=4, n=4):
    """
    半边数据结构的网格
    """
    node = h * np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
    cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                    dtype=np.int)
    cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

    mesh = PolygonMesh(node, cell, cellLocation)
    mesh = HalfEdgeMesh2d.from_mesh(mesh)
    #mesh.uniform_refine(n)
    return mesh
Ejemplo n.º 18
0
def complex_mesh(r, filename):
    import meshio
    mesh = meshio.read(filename)
    node = mesh.points
    node = node[:, 0:2] * r
    cell = mesh.cells
    mesh.node = node
    mesh.cell = cell
    cell = cell['triangle']
    isUsingNode = np.zeros(node.shape[0], dtype=np.bool)
    isUsingNode[cell] = True
    NN = isUsingNode.sum()
    idxmap = np.zeros(node.shape[0], dtype=np.int32)
    idxmap[isUsingNode] = range(NN)
    cell = idxmap[cell]
    node = node[isUsingNode]
    #cell = cell[:,::-1]
    mesh = TriangleMesh(node, cell)
    nmesh = TriangleMeshWithInfinityNode(mesh)
    ppoint, pcell, pcellLocation = nmesh.to_polygonmesh()
    pmesh = PolygonMesh(ppoint, pcell, pcellLocation)
    return pmesh
Ejemplo n.º 19
0
    def refine_test(self, plot=True):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgePolygonMesh.from_polygonmesh(mesh)
        isMarkedCell = np.zeros(5, dtype=np.bool)
        isMarkedCell[-1] = True
        isMarkedCell[-2] = True
        mesh.refine(isMarkedCell)

        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC, dtype=np.bool)
            isMarkedCell[2] = True
            mesh.refine(isMarkedCell)

        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC, dtype=np.bool)
            isMarkedCell[1] = True
            mesh.refine(isMarkedCell)

        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC, dtype=np.bool)
            isMarkedCell[13] = True
            mesh.refine(isMarkedCell)

        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_edge(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)
            plt.show()
Ejemplo n.º 20
0
    def from_polygonmesh_test(self, plot=True):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        a = mesh.entity_measure('cell')

        mesh = HalfEdgePolygonMesh.from_polygonmesh(mesh)
        a = mesh.entity_measure('cell')
        mesh.print()

        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_edge(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)
            plt.show()
Ejemplo n.º 21
0
    def refine_with_flag_test(self, plot=True):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgePolygonMesh.from_polygonmesh(mesh)

        NE = mesh.number_of_edges()
        NC = mesh.number_of_cells()

        name = 'rflag'
        val = np.zeros(2 * NE, dtype=np.int)
        mesh.set_data(name, val, 'halfedge')

        isMarkedCell = np.zeros(NC + 1, dtype=np.bool)
        isMarkedCell[2] = True
        mesh.refine_with_flag(isMarkedCell, rflag=name, dflag=False)

        NC = mesh.number_of_cells()
        isMarkedCell = np.zeros(NC + 1, dtype=np.bool)
        isMarkedCell[6] = True
        mesh.refine_with_flag(isMarkedCell, rflag=name, dflag=False)

        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC + 1, dtype=np.bool)
            isMarkedCell[3] = True
            mesh.refine_with_flag(isMarkedCell, rflag=name, dflag=False)

        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC + 1, dtype=np.bool)
            isMarkedCell[1] = True
            mesh.refine_with_flag(isMarkedCell, rflag=name, dflag=False)

        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC + 1, dtype=np.bool)
            isMarkedCell[5] = True
            isMarkedCell[13] = True
            mesh.refine_with_flag(isMarkedCell, rflag=name, dflag=False)
        if True:
            NC = mesh.number_of_cells()
            isMarkedCell = np.zeros(NC + 1, dtype=np.bool)
            isMarkedCell[0] = True
            isMarkedCell[1] = True
            mesh.refine_with_flag(isMarkedCell, rflag=name, dflag=False)

        print("rflag:\n")
        for i, val in enumerate(mesh.halfedgedata[name]):
            print(i, ':', val, mesh.ds.halfedge[i, 0:2])

        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            #mesh.find_edge(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)
            plt.show()
Ejemplo n.º 22
0
    def run(self, estimator='mix'):
        problem = self.problem
        options = self.optoptions
        moptions = self.moptions
        model = problem['objective']

        optalg = SteepestDescentAlg(problem, options)
        x, f, g, diff = optalg.run(maxit=10)

        q = np.zeros(model.rho.shape)
        q[:, 0] = model.q0[:, -1]
        q[:, 1] = model.q1[:, -1]
        problem['x0'] = x
        while True:
            print('chiN', moptions['chiN'])
            while True:
                mesh = problem['mesh']  ##多边形网格
                hmesh = HalfEdgeMesh2d.from_mesh(mesh)  ##半边网格
                aopts = hmesh.adaptive_options(method='mean',
                                               maxcoarsen=3,
                                               HB=True)
                print('NN', mesh.number_of_nodes())

                mu = problem['x0']
                if estimator == 'mix':
                    eta = model.mix_estimate(q, w=1)
                if estimator == 'grad':
                    eta = model.estimate(q)

                aopts['data'] = {'mu': mu}
                S0 = model.vemspace.project_to_smspace(aopts['data']['mu'][:,
                                                                           0])
                S1 = model.vemspace.project_to_smspace(aopts['data']['mu'][:,
                                                                           1])

                hmesh.adaptive(eta, aopts)  ###半边网格做自适应
                mesh = PolygonMesh.from_halfedgemesh(hmesh)  ###多边形网格

                model.reinit(mesh)  ###多边形网格给进空间
                aopts['data']['mu'] = np.zeros((model.gdof, 2))
                aopts['data']['mu'][:, 0] = model.vemspace.interpolation(
                    S0, aopts['HB'])
                aopts['data']['mu'][:, 1] = model.vemspace.interpolation(
                    S1, aopts['HB'])
                problem['x0'] = aopts['data']['mu']

                optalg = SteepestDescentAlg(problem, options)
                x, f, g, diff = optalg.run(maxit=200)
                problem['mesh'] = mesh  ###多边形网格
                problem['x0'] = x
                problem['rho'] = model.rho
                self.problem = problem
                q = np.zeros(model.rho.shape)

                q[:, 0] = model.q0[:, -1]
                q[:, 1] = model.q1[:, -1]

                if diff < options['FunValDiff']:
                    if (np.max(problem['rho'][:, 0]) < 1) and (np.min(
                            problem['rho'][:, 0]) > 0):
                        break

            myfile = open(
                moptions['rdir'] + '/' + str(int(moptions['chiN'])) +
                'mesh.bin', 'wb')
            import pickle
            pickle.dump(problem['mesh'], myfile)
            myfile.close()
            model.save_data(moptions['rdir'] + '/' +
                            str(int(moptions['chiN'])) + '.mat')

            moptions['chiN'] += 5
            if moptions['chiN'] > 60:
                break
import matplotlib.pyplot as plt
from fealpy.functionspace.vector_vem_space import VectorScaledMonomialSpace2d
from fealpy.mesh import PolygonMesh

from fealpy.vem.integral_alg import PolygonMeshIntegralAlg

p = 1
point = np.array([(0.5, 0.5)], dtype=np.float)
point = np.array([(1, 1)], dtype=np.float)

node = np.array([ (0, 0), (1, 0), (1, 1), (0, 1)], dtype=np.float)
cell = np.array([0, 1, 2, 3], dtype=np.int)
cellLocation = np.array([0, 4], dtype=np.int)

pmesh = PolygonMesh(node, cell, cellLocation)

space = VectorScaledMonomialSpace2d(pmesh, p)

phi = space.basis(point)
print('phi', phi)
gphi = space.grad_basis(point)
print('gphi', gphi)
dphi = space.div_basis(point)
print('dphi', dphi)
gdphi = space.grad_div_basis(point)
print('gdphi', gdphi)
sphi = space.strain_basis(point)
print('sphi', sphi)
dsphi = space.div_strain_basis(point)
print('dsphi', dsphi)
Ejemplo n.º 24
0
#    (0.0, 1.0),
#    (0.5, 1.0),
#    (1.0, 1.0)], dtype=np.float)
#
#cell = np.array(
#        [1, 4, 0, 3, 0, 4, 1, 2, 5, 4, 3, 4, 7, 6, 4, 5, 8, 7], dtype=np.int)
#cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)
#
#mesh = PolygonMesh(node, cell, cellLocation)

node = np.array([(-1.0, -1.0), (1.0, -1.0), (1.0, 1.0), (-1.0, 1.0)],
                dtype=np.float)

cell = np.array([0, 1, 2, 3], dtype=np.int)
cellLocation = np.array([0, 4], dtype=np.int)
mesh = PolygonMesh(node, cell, cellLocation)
qf = mesh.integrator(7)

space = NonConformingVirtualElementSpace2d(mesh, p=2)
print("Cell2dof:\n", space.cell_to_dof())
print("Interpolation points:\n", space.interpolation_points())
print("H:\n", space.H)
print("D:\n", space.D)
print("G:\n", space.G)
print("B:\n", space.B)

integralalg = PolygonMeshIntegralAlg(qf,
                                     mesh,
                                     barycenter=space.smspace.barycenter)
G = space.matrix_G_test(integralalg)
print("G:\n", G)
Ejemplo n.º 25
0
import matplotlib.pyplot as plt

from fealpy.pde.poisson_2d import CosCosData
from fealpy.mesh.simple_mesh_generator import triangle
from fealpy.mesh import PolygonMesh
from fealpy.functionspace import ConformingVirtualElementSpace2d
from fealpy.boundarycondition import BoundaryCondition

node = 0.5 * np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                       (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                       (2.0, 2.0)],
                      dtype=np.float)
cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                dtype=np.int)
cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)
mesh = PolygonMesh(node, cell, cellLocation)

if False:
    node = np.array([(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)],
                    dtype=np.float)
    cell = np.array([0, 1, 2, 3], dtype=np.int)
    cellLocation = np.array([0, 4], dtype=np.int)
    mesh = PolygonMesh(node, cell, cellLocation)

space = ConformingVirtualElementSpace2d(mesh, p=1)
A0, S0 = space.chen_stability_term()
A = space.stiff_matrix()

print("A:", A.toarray())
print("A0:", A0.toarray())
print("S0:", S0.toarray())
Ejemplo n.º 26
0
    def adaptive_poly_test(self, plot=True):
        """"
        initial mesh
        """
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgeMesh.from_mesh(mesh)

        fig = plt.figure()
        axes = fig.gca()
        mesh.add_plot(axes)
        mesh.find_node(axes, showindex=True)
        mesh.find_cell(axes, showindex=True)

        NE = mesh.number_of_edges()
        nC = mesh.number_of_cells()
        """
        refined mesh
        """
        aopts = mesh.adaptive_options(method='numrefine',
                                      maxcoarsen=3,
                                      HB=True)
        eta = [0, 0, 1, 1, 1]

        mesh.adaptive(eta, aopts)
        print('r', aopts['HB'])

        fig = plt.figure()
        axes = fig.gca()
        mesh.add_plot(axes)
        mesh.find_node(axes, showindex=True)
        mesh.find_cell(axes, showindex=True)
        plt.show()

        mesh.from_mesh(mesh)
        """
        coarsened mesh
        """
        eta = [0, 0, 0, 0, 0, 0, 0, -1, 0, -1, 0, -1, 0, -1]
        #eta = [0,0,0,0,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2,-2]

        mesh.adaptive(eta, aopts)

        fig = plt.figure()
        axes = fig.gca()
        mesh.add_plot(axes)
        mesh.find_node(axes, showindex=True)
        mesh.find_cell(axes, showindex=True)
        plt.show()

        if plot:

            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)

            NAC = mesh.number_of_all_cells()  # 包括外部区域和洞
            cindex = range(mesh.ds.cellstart, NAC)
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_cell(axes, showindex=True, multiindex=cindex)

            NN = mesh.number_of_nodes()
            nindex = np.zeros(NN, dtype=np.int)
            halfedge = mesh.ds.halfedge
            nindex[halfedge[:, 0]] = mesh.get_data('halfedge', 'level')
            cindex = mesh.get_data('cell', 'level')
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True, multiindex=nindex)
            mesh.find_cell(axes, showindex=True, multiindex=cindex)
            plt.show()
        else:
            return mesh
Ejemplo n.º 27
0
    def refine_poly_test(self, plot=True):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgeMesh.from_mesh(mesh)

        fig = plt.figure()
        axes = fig.gca()
        mesh.add_plot(axes)
        mesh.find_node(axes, showindex=True)
        mesh.find_cell(axes, showindex=True)
        clevel = mesh.celldata['level']
        print(clevel)
        NE = mesh.number_of_edges()
        NC = mesh.number_of_cells()

        if True:
            isMarkedCell = mesh.mark_helper([2])
            mesh.refine_poly(isMarkedCell, dflag=False)

        if False:
            isMarkedCell = mesh.mark_helper([6])
            mesh.refine_poly(isMarkedCell, dflag=False)

        if False:
            isMarkedCell = mesh.mark_helper([3])
            mesh.refine_poly(isMarkedCell, dflag=False)

        if 1:
            isMarkedCell = mesh.mark_helper([1, 5])
            mesh.refine_poly(isMarkedCell, dflag=False)

        if False:
            isMarkedCell = mesh.mark_helper([1, 12])
            mesh.refine_poly(isMarkedCell, dflag=False)

        if False:
            isMarkedCell = mesh.mark_helper([0, 21])
            mesh.refine_poly(isMarkedCell, dflag=False)
        clevel = mesh.celldata['level']
        print(clevel)

        #print("halfedge level:\n")
        #for i, val in enumerate(mesh.halfedgedata['level']):
        #    print(i, ':', val, mesh.ds.halfedge[i, 0:2])

        #print("cell level:\n")
        #for i, val in enumerate(mesh.celldata['level']):
        #    print(i, ':', val)

        if plot:

            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)

            NAC = mesh.number_of_all_cells()  # 包括外部区域和洞
            cindex = range(mesh.ds.cellstart, NAC)
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.add_halfedge_plot(axes, showindex=True)
            mesh.find_cell(axes, showindex=True, multiindex=cindex)

            NN = mesh.number_of_nodes()
            nindex = np.zeros(NN, dtype=np.int)
            halfedge = mesh.ds.halfedge
            nindex[halfedge[:, 0]] = mesh.get_data('halfedge', 'level')
            cindex = mesh.get_data('cell', 'level')
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True, multiindex=nindex)
            mesh.find_cell(axes, showindex=True, multiindex=cindex)
            plt.show()
        else:
            return mesh
Ejemplo n.º 28
0
    def edge_to_cell_test(self, plot=True):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        mesh = PolygonMesh(node, cell, cellLocation)
        mesh = HalfEdgePolygonMesh.from_polygonmesh(mesh)

        NE = mesh.number_of_edges()
        edge = mesh.entity('edge')
        edge2cell = mesh.ds.edge_to_cell()
        print('edge:')
        for i in range(NE):
            print(i, ":", edge[i], edge2cell[i])

        NC = mesh.number_of_cells()
        cell, cellLocation = mesh.entity('cell')
        cell2edge = mesh.ds.cell_to_edge()
        for i in range(NC):
            print(i, ":", cell[cellLocation[i]:cellLocation[i + 1]])
            print(i, ":", cell2edge[cellLocation[i]:cellLocation[i + 1]])

        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, showindex=True)
            mesh.find_edge(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)
            plt.show()
Ejemplo n.º 29
0
    def animation_plot(self, method='quad', plot=True):

        if method == 'quad':
            cell = np.array([[0, 1, 2, 3], [1, 4, 5, 2]], dtype=np.int)
            node = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [2, 0], [2, 1]],
                            dtype=np.float)
            mesh = QuadrangleMesh(node, cell)
            mesh = HalfEdgeMesh2d.from_mesh(mesh)
            mesh.init_level_info()
            halfedge = mesh.ds.halfedge
            cstart = mesh.ds.cellstart
            NE = mesh.ds.NE
            color = 3 * np.ones(NE * 2, dtype=np.int_)
            color[1] = 1
            while (color == 3).any():
                red = color == 1
                gre = color == 0
                color[halfedge[red][:, [2, 3, 4]]] = 0
                color[halfedge[gre][:, [2, 3, 4]]] = 1
            colorlevel = ((color == 1) | (color == 2)).astype(np.int_)
            mesh.hedgecolor = {'color': color, 'level': colorlevel}
            mesh.ds.NV = 4
        elif method == 'rg':
            cell = np.array([[0, 1, 2], [0, 2, 3], [1, 4, 5], [2, 1, 5]],
                            dtype=np.int)
            node = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [2, 0], [2, 1]],
                            dtype=np.float)
            mesh = TriangleMesh(node, cell)
            mesh = HalfEdgeMesh2d.from_mesh(mesh)
            mesh.init_level_info()
            halfedge = mesh.ds.halfedge
            cstart = mesh.ds.cellstart
            NE = mesh.ds.NE
            color = np.zeros(NE * 2, dtype=np.int_)
            mesh.hedgecolor = color
            #mesh.ds.NV = 3
        elif method == 'nvb':
            cell = np.array([[0, 1, 2], [0, 2, 3], [1, 4, 5], [2, 1, 5]],
                            dtype=np.int)
            node = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [2, 0], [2, 1]],
                            dtype=np.float)
            mesh = TriangleMesh(node, cell)
            mesh = HalfEdgeMesh2d.from_mesh(mesh)
            mesh.init_level_info()
            halfedge = mesh.ds.halfedge
            cstart = mesh.ds.cellstart
            NE = mesh.ds.NE
            color = np.zeros(NE * 2, dtype=np.int_)
            color[[2, 3, 10, 11]] = 1
            mesh.hedgecolor = color
        elif method == 'poly':
            node = np.array([
                (0.0, 0.0),
                (0.0, 1.0),
                (1.0, 0.0),
                (1.0, 1.0),
            ],
                            dtype=np.float)
            cell = np.array([0, 2, 3, 0, 3, 1], dtype=np.int)
            cellLocation = np.array([0, 3, 6], dtype=np.int)

            mesh = PolygonMesh(node, cell, cellLocation)
            mesh = HalfEdgeMesh2d.from_mesh(mesh)
            mesh.init_level_info()
            halfedge = mesh.ds.halfedge
            cstart = mesh.ds.cellstart
        r = 0.5
        h = 1e-2
        k = 0
        N = 19
        fig = plt.figure()
        axes = fig.gca()
        plt.ion()
        for i in range(N):
            c = np.array([i * (2 / N), 0.8])
            k = 0
            sta1 = time.time()
            while True:
                halfedge = mesh.ds.halfedge
                pre = halfedge[:, 3]
                node = mesh.entity('node')
                flag = np.linalg.norm(node - c, axis=1) < r
                flag1 = flag[halfedge[:, 0]].astype(int)
                flag2 = flag[halfedge[pre, 0]].astype(int)
                isMarkedHEdge = flag1 + flag2 == 1
                NC = mesh.number_of_all_cells()
                isMarkedCell = np.zeros(NC, dtype=np.bool_)
                isMarkedCell[halfedge[isMarkedHEdge, 1]] = True
                isMarkedCell[cstart:] = isMarkedCell[cstart:] & (
                    mesh.cell_area() > h**2)
                if (~isMarkedCell[cstart:]).all():
                    break
                if method == 'quad':
                    mesh.refine_quad(isMarkedCell)
                elif method == 'rg':
                    mesh.refine_triangle_rg(isMarkedCell)
                elif method == 'nvb':
                    mesh.refine_triangle_nvb(isMarkedCell)
                elif method == 'poly':
                    mesh.refine_poly(isMarkedCell)
                k += 1
                print('加密', k, i, '次***************************')
            k = 0
            sta2 = time.time()

            aa = 2 * i
            bb = 2 * i + 1
            plt.cla()
            mesh.add_plot(axes, linewidths=0.4)
            #fig.savefig('%f.png' %aa, dpi=600, bbox_inches='tight')
            plt.pause(0.01)

            while k < 10:
                halfedge = mesh.ds.halfedge
                pre = halfedge[:, 3]
                node = mesh.entity('node')
                flag = np.linalg.norm(node - c, axis=1) < r
                flag1 = flag[halfedge[:, 0]].astype(int)
                flag2 = flag[halfedge[pre, 0]].astype(int)
                isMarkedHEdge = flag1 + flag2 == 1
                NC = mesh.number_of_all_cells()
                isMarkedCell = np.zeros(NC, dtype=np.bool_)
                isMarkedCell[halfedge[isMarkedHEdge, 1]] = True
                isMarkedCell[cstart:] = ~isMarkedCell[cstart:] & (
                    mesh.cell_area() < 0.5)
                if method == 'quad':
                    mesh.coarsen_quad(isMarkedCell)
                elif method == 'rg':
                    mesh.coarsen_triangle_rg(isMarkedCell)
                elif method == 'nvb':
                    mesh.coarsen_triangle_nvb(isMarkedCell)
                elif method == 'poly':
                    mesh.coarsen_poly(isMarkedCell)
                if (~isMarkedCell).all():
                    break
                k += 1
                print('循环', k, '次***************************')
            plt.cla()
            mesh.add_plot(axes, linewidths=0.4)
            #fig.savefig('%f.png' %bb, dpi=600, bbox_inches='tight')
            sta3 = time.time()
            plt.pause(0.01)
            print('加密时间:', sta2 - sta1)
            print('粗化时间:', sta3 - sta2)
        plt.ioff()
        plt.show()
Ejemplo n.º 30
0
    def cell_to_node(self):
        node = np.array([(0.0, 0.0), (0.0, 1.0), (0.0, 2.0), (1.0, 0.0),
                         (1.0, 1.0), (1.0, 2.0), (2.0, 0.0), (2.0, 1.0),
                         (2.0, 2.0)],
                        dtype=np.float)
        cell = np.array([0, 3, 4, 4, 1, 0, 1, 4, 5, 2, 3, 6, 7, 4, 4, 7, 8, 5],
                        dtype=np.int)
        cellLocation = np.array([0, 3, 6, 10, 14, 18], dtype=np.int)

        print('node:', node)
        print('cell:', cell)
        print('cellLocation:', cellLocation)
        mesh = PolygonMesh(node, cell, cellLocation)

        fig = plt.figure()
        axes = fig.gca()
        mesh.add_plot(axes)
        mesh.find_node(axes, showindex=True)
        mesh.find_cell(axes, showindex=True)

        mesh = HalfEdgeMesh2d.from_mesh(mesh)
        mesh.print()
        cell, cellLocation = mesh.entity('cell')
        print('cell:', cell)
        print('cellLocation:', cellLocation)
        plt.show()