Example #1
0
    def __init__(self, pde, timeline, n=1):
        self.pde = pde
        box = pde.domain()
        mf = MeshFactory()
        self.mesh = mf.boxmesh2d(box, nx=n, ny=n, meshtype='tri')

        self.uspace = RaviartThomasFiniteElementSpace2d(self.mesh, p=0)
        self.pspace = self.uspace.smspace

        self.timeline = timeline
        NL = timeline.number_of_time_levels()

        # state variable
        self.yh = self.pspace.function(dim=NL)
        self.uh = self.pspace.function(dim=NL)
        self.tph = self.uspace.function(dim=NL)
        self.ph = self.uspace.function()
        bc = self.mesh.entity_barycenter('cell')

        f = cartesian(lambda p: pde.y_solution(p, 0))
        self.yh[:, 0] = self.pspace.local_projection(f)

        # costate variable
        self.zh = self.pspace.function(dim=NL)
        self.tqh = self.uspace.function(dim=NL)
        self.qh = self.uspace.function()

        self.A = self.uspace.stiff_matrix()  # RT 质量矩阵
        self.D = self.uspace.div_matrix()  # (p, \div v)
        self.M = self.pspace.mass_matrix()
Example #2
0
    def show_mesh(self, p=2, plot=True):

        mf = MeshFactory()

        mesh = mf.boxmesh2d([0, 1, 0, 1], nx=2, ny=2, meshtype='tri')
        node = mesh.entity('node')
        cell = mesh.entity('cell')

        ltmesh = LagrangeTriangleMesh(node, cell, p=p)
        NN = ltmesh.number_of_nodes()

        mesh.ds.edge = ltmesh.lds.edge
        mesh.ds.edge2cell = ltmesh.lds.edge2cell

        node = ltmesh.entity('node')
        #ltmesh.print()

        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_node(axes, node=node, showindex=True, fontsize=28)
            mesh.find_edge(axes, showindex=True)
            mesh.find_cell(axes, showindex=True)
            plt.show()
Example #3
0
    def solve_poisson_3d(self, n=2):
        from fealpy.pde.poisson_3d import CosCosCosData as PDE
        from fealpy.mesh import MeshFactory
        from fealpy.functionspace import LagrangeFiniteElementSpace
        from fealpy.boundarycondition import DirichletBC

        pde = PDE()
        mf = MeshFactory()
        m = 2**n
        box = [0, 1, 0, 1, 0, 1]
        mesh = mf.boxmesh3d(box, nx=m, ny=m, nz=m, meshtype='tet')
        space = LagrangeFiniteElementSpace(mesh, p=1)
        gdof = space.number_of_global_dofs()
        NC = mesh.number_of_cells()
        print('gdof:', gdof, 'NC:', NC)
        bc = DirichletBC(space, pde.dirichlet)
        uh = space.function()
        A = space.stiff_matrix()
        A = space.parallel_stiff_matrix(q=1)

        M = space.parallel_mass_matrix(q=2)
        M = space.mass_matrix()

        F = space.source_vector(pde.source)

        A, F = bc.apply(A, F, uh)

        solver = PETScSolver()
        solver.solve(A, F, uh)
        error = space.integralalg.L2_error(pde.solution, uh)
        print(error)
Example #4
0
 def diff_index_test(self, p=3):
     mfactory = MeshFactory()
     mesh = mfactory.one_tetrahedron_mesh()
     space = ScaledMonomialSpace3d(mesh, p=p)
     index = space.diff_index_1()
     print(index)
     index = space.diff_index_2()
     print(index)
Example #5
0
 def space_mesh(self, n=10):
     from fealpy.mesh import MeshFactory
     mf = MeshFactory()
     mesh = mf.boxmesh2d(self.domain, nx=2, ny=2, meshtype='tri')
     for i in range(n):
         isCrossedCell = mesh.is_crossed_cell(self.point, self.segment)
         mesh.bisect(isCrossedCell)
     return mesh
Example #6
0
 def show_frame_test(self):
     fig = plt.figure()
     axes = fig.gca(projection='3d')
     mfactory = MeshFactory()
     mesh = mfactory.one_tetrahedron_mesh()
     space = ScaledMonomialSpace3d(mesh, p=1)
     space.show_frame(axes)
     plt.show()
    def save_mesh(self, p=2, fname='test.vtu'):
        mf = MeshFactory()

        mesh = mf.boxmesh2d([0, 1, 0, 1], nx=2, ny=2, meshtype='quad')
        node = mesh.entity('node')
        cell = mesh.entity('cell')

        mesh = LagrangeQuadrangleMesh(node, cell[:, [0, 3, 1, 2]], p=p)
        mesh.to_vtk(fname=fname)
Example #8
0
 def space_mesh(self, n=10):
     from fealpy.mesh import MeshFactory
     mf = MeshFactory()
     mesh = mf.boxmesh2d(self.domain, nx=1, ny=1, meshtype='tri')
     point = self.fracture['point']
     segment = self.fracture['segment']
     for i in range(n):
         isCutCell = mesh.find_segment_location(point, segment)
         mesh.bisect(isCutCell)
     return mesh
Example #9
0
 def one_tet_mesh_test(self, p, plot=True):
     mfactory = MeshFactory()
     mesh = mfactory.one_tetrahedron_mesh()
     space = ScaledMonomialSpace3d(mesh, p=p)
     if plot:
         fig = plt.figure()
         axes = fig.gca(projection='3d')
         mesh.add_plot(axes)
         axes.set_axis_off()
         plt.show()
Example #10
0
    def cell_basis_test(self):
        mfactory = MeshFactory()
        mesh = mfactory.one_tetrahedron_mesh(ttype='iso')
        space = ScaledMonomialSpace3d(mesh, p=2)

        bc = np.array([[1, 0, 0, 0]])
        point = mesh.bc_to_point(bc, 'cell')
        print(point.shape)
        print(space.cellsize)
        phi = space.basis(point)
        print(phi)
Example #11
0
    def space_mesh(self, n=50):
        """

        Notes
        -----

        最小网格单元尺寸为 1 m
        """
        box = [0, 50, 0, 50]
        mf = MeshFactory()
        mesh = mf.boxmesh2d(box, nx=n, ny=n, meshtype='tri')
        return mesh
Example #12
0
    def face_basis_test(self):
        mfactory = MeshFactory()
        mesh = mfactory.one_tetrahedron_mesh(ttype='iso')
        space = ScaledMonomialSpace3d(mesh, p=1)

        face = mesh.entity('face')
        print(face)
        print('frame:', space.faceframe)
        bc = np.array([[1 / 3, 1 / 3, 1 / 3]])
        bc = np.array([[1, 0, 0]])
        point = mesh.bc_to_point(bc, 'face')
        print(point.shape)
        phi = space.face_basis(point)
        print(phi)
Example #13
0
    def __init__(self):
        self.domain = [0, 50, 0, 50]
        self.mesh = MeshFactory().regular(self.domain, n=50)
        self.timeline = UniformTimeLine(0, 1, 100)
        self.space0 = RaviartThomasFiniteElementSpace2d(self.mesh, p=0)
        self.space1 = ScaledMonomialSpace2d(self.mesh, p=1)  # 线性间断有限元空间

        self.vh = self.space0.function()  # 速度
        self.ph = self.space0.smspace.function()  # 压力
        self.ch = self.space1.function(dim=3)  # 三个组分的摩尔密度
        self.options = {
            'viscosity': 1.0,
            'permeability': 1.0,
            'temperature': 397,
            'pressure': 50,
            'porosity': 0.2,
            'injecttion_rate': 0.1,
            'compressibility': (0.001, 0.001, 0.001),
            'pmv': (1.0, 1.0, 1.0),
            'dt': self.timeline.dt
        }

        c = self.options['viscosity'] / self.options['permeability']
        self.A = c * self.space0.mass_matrix()
        self.B = self.space0.div_matrix()

        phi = self.options['porosity']
        self.M = phi / dt * self.space0.smspace.mass_matrix()  #
        self.MC = self.space1.cell_mass_matrix() / dt
Example #14
0
class FractureRTTest:
    def __init__(self):
        self.mf = MeshFactory()

    def mesh_with_fracture(self, plot=True):

        box = [0, 1, 0, 1]
        mesh = self.mf.boxmesh2d(box, nx=10, ny=10, meshtype='tri')

        def is_fracture(p):
            x = p[..., 0]
            y = p[..., 1]
            flag0 = (x == 0.5) & (y > 0.2) & (y < 0.8)
            flag1 = (y == 0.5) & (x > 0.2) & (x < 0.8)
            return flag0 | flag1

        bc = mesh.entity_barycenter('edge')
        isFEdge = is_fracture(bc)
        mesh.edgedata['fracture'] = isFEdge
        NE = mesh.number_of_edges()
        print('边的个数:', NE)

        space = RaviartThomasFiniteElementSpace2d(mesh, p=0)
        gdof = space.number_of_global_dofs()
        print('gdof:', gdof)

        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes)
            mesh.find_edge(axes, index=isFEdge, color='r')
            plt.show()
Example #15
0
 def show_basis(self):
     h = 0.5
     box = [-h, 1 + h, -h, np.sqrt(3) / 2 + h]
     mesh = MeshFactory.one_triangle_mesh()
     space = FirstKindNedelecFiniteElementSpace2d(mesh, p=0)
     fig = plt.figure()
     space.show_basis(fig, box=box)
     plt.show()
Example #16
0
class HalfEdgeMesh3dTest:

    def __init__(self):
        self.meshfactory = MeshFactory()

    def one_tetrahedron_mesh_test(self):
        tmesh = self.meshfactory.one_tetrahedron_mesh(ttype='equ')
        mesh = HalfEdgeMesh3d.from_mesh(tmesh)
        mesh.print()
Example #17
0
class RaviartThomasFiniteElementSpace3dTest:
    def __init__(self):
        self.meshfactory = MeshFactory()

    def show_basis_test(self, p=0):
        mesh = self.meshfactory.one_tetrahedron_mesh(ttype='equ')
        space = RaviartThomasFiniteElementSpace3d(mesh, p=p, q=2)
        fig = plt.figure()
        space.show_basis(fig)
        plt.show()
Example #18
0
class FirstKindNedelecFiniteElementSpace2dTest:
    def __init__(self):
        self.meshfactory = MeshFactory()

    def show_basis_test(self):
        h = 0.5
        box = [-h, 1 + h, -h, np.sqrt(3) / 2 + h]
        mesh = self.meshfactory.one_triangle_mesh()
        space = FirstKindNedelecFiniteElementSpace2d(mesh, p=0, q=2)
        fig = plt.figure()
        space.show_basis(fig, box=box)
        plt.show()
Example #19
0
class RaviartThomasFiniteElementSpace3dTest:
    def __init__(self):
        self.meshfactory = MeshFactory()

    def show_basis(self, p=0):
        mesh = self.meshfactory.one_tetrahedron_mesh(ttype='equ')
        space = RaviartThomasFiniteElementSpace3d(mesh, p=p, q=2)
        fig = plt.figure()
        space.show_basis(fig)
        plt.show()

    def basis_coefficients(self, n=0, p=0):
        pde = X2Y2Z2Data()
        mesh = pde.init_mesh(n=n, meshtype='tet')
        space = RaviartThomasFiniteElementSpace3d(mesh, p=p)
        C = space.basis_coefficients()

        return C

    def solve_poisson_3d(self, n=0, p=0, plot=True):
        pde = CosCosCosData()
        mesh = pde.init_mesh(n=n, meshtype='tet')
        space = RaviartThomasFiniteElementSpace3d(mesh, p=p, q=p + 4)

        udof = space.number_of_global_dofs()
        pdof = space.smspace.number_of_global_dofs()
        gdof = udof + pdof

        uh = space.function()
        print('uh:', uh.shape)
        ph = space.smspace.function()
        print('ph:', ph.shape)
        A = space.stiff_matrix()
        B = space.div_matrix()
        F1 = space.source_vector(pde.source)
        AA = bmat([[A, -B], [-B.T, None]], format='csr')

        F0 = space.neumann_boundary_vector(pde.dirichlet)
        FF = np.r_['0', F0, F1]
        x = spsolve(AA, FF).reshape(-1)
        uh[:] = x[:udof]
        ph[:] = x[udof:]
        error0 = space.integralalg.L2_error(pde.flux, uh)

        def f(bc):
            xx = mesh.bc_to_point(bc)
            return (pde.solution(xx) - ph(xx))**2

        error1 = space.integralalg.integral(f)
        print(error0, error1)
Example #20
0
class RaviartThomasFiniteElementSpace2dTest:

    def __init__(self):
        self.meshfactory = MeshFactory()

    def show_basis(self):
        h = 0.5
        box = [-h, 1+h, -h, np.sqrt(3)/2+h]
        mesh = self.meshfactory.one_triangle_mesh('equ')
        space = RaviartThomasFiniteElementSpace2d(mesh, p=2, q=2)
        fig = plt.figure()
        space.show_basis(fig, box=box)
        plt.show()

    def solve_poisson_2d(self):

        pde = CosCosData()
        mesh = pde.init_mesh(n=3, methtype='tri')
        space = RaviartThomasFiniteElementSpace2d(mesh, p=0)
Example #21
0
    def init_mesh(self, n=4, meshtype='tri', h=0.1):
        """ generate the initial mesh
        """
        node = np.array([(0, -1), (1, -1), (1, 1), (0, 1)], dtype=np.float64)

        if meshtype == 'quadtree':
            cell = np.array([(0, 1, 2, 3)], dtype=np.int_)
            mesh = Quadtree(node, cell)
            mesh.uniform_refine(n)
            return mesh
        if meshtype == 'quad':
            node = np.array([(0, 0), (1, 0), (1, 1), (0, 1), (0.5, 0),
                             (1, 0.4), (0.3, 1), (0, 0.6), (0.5, 0.45)],
                            dtype=np.float64)
            cell = np.array([(0, 4, 8, 7), (4, 1, 5, 8), (7, 8, 6, 3),
                             (8, 5, 2, 6)],
                            dtype=np.int_)
            mesh = QuadrangleMesh(node, cell)
            mesh.uniform_refine(n)
            return mesh
        elif meshtype == 'tri':
            cell = np.array([(1, 2, 0), (3, 0, 2)], dtype=np.int_)
            mesh = TriangleMesh(node, cell)
            mesh.uniform_refine(n)

            # |--- to test
            box = [0, 1, -1, 1]
            mesh = MF.boxmesh2d(box, nx=10, ny=20, meshtype='tri')
            # |---
            return mesh
        elif meshtype == 'halfedge':
            cell = np.array([(1, 2, 0), (3, 0, 2)], dtype=np.int_)
            mesh = TriangleMesh(node, cell)
            mesh = HalfEdgeMesh2d.from_mesh(mesh)
            mesh.uniform_refine(n)
            return mesh
        elif meshtype == 'squad':
            mesh = StructureQuadMesh([0, 1, 0, 1], h)
            return mesh
        else:
            raise ValueError("".format)
Example #22
0
    def space_mesh(self, p, NS=0):
        from fealpy.mesh import MeshFactory as MF
        mesh = MF.boxmesh2d(self.domain, nx=70, ny=30, p=p, meshtype='quad')
        mesh.uniform_refine(NS)
        NN = mesh.number_of_nodes()
        NE = mesh.number_of_edges()
        NC = mesh.number_of_cells()
        NCN = mesh.number_of_corner_nodes()
        cell = mesh.entity('cell')
        valence = np.zeros(NN, dtype=np.int)
        np.add.at(valence, cell, 1)
        dof = np.zeros(NN, dtype=np.int)
        idx = np.arange(NN)
        flag = (valence == 2) & (idx < NCN)
        dof[flag] = 1
        flag = (valence == 1) & (idx > NCN) & (idx < NCN + (p - 1) * NE)
        dof[flag] = 1
        flag = (valence == 1) & (idx > NCN + (p - 1) * NE)
        dof[flag] = 2
        flag = (valence > 2) & (idx < NCN)
        dof[flag] = 2
        flag = (valence == 2) & (idx > NCN) & (idx < NCN + (p - 1) * NE)
        dof[flag] = 2
        mesh.nodedata['dof'] = dof

        flag = dof == 1
        n = flag.sum()
        en = np.zeros((n, 2), dtype=np.float64)
        node = mesh.entity('node')[flag]
        flag = np.abs(node[:, 0] - 0.0) < 1e-12
        en[flag, 0] = -1.0
        flag = np.abs(node[:, 0] - 7.0) < 1e-12
        en[flag, 0] = 1.0

        flag = np.abs(node[:, 1] - 0.0) < 1e-12
        en[flag, 1] = -1.0
        flag = np.abs(node[:, 1] - 3.0) < 1e-12
        en[flag, 1] = 1.0
        mesh.meshdata['bd_normal'] = en
        return mesh
Example #23
0
    def interpolation(self, n=4, p=0, plot=True):

        box = [-0.5, 1.5, -0.5, 1.5]

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

        mesh = MeshFactory.boxmesh2d([0, 1, 0, 1], nx=n, ny=n, meshtype='tri')
        space = FirstKindNedelecFiniteElementSpace2d(mesh, p=p)
        uI = space.interpolation(u)
        error = space.integralalg.L2_error(u, uI)
        print(error)
        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes, box=box)
            plt.show()
Example #24
0
import numpy as np
import matplotlib.pyplot as plt

from matplotlib import collections as mc

from fealpy.mesh import MeshFactory

mf = MeshFactory()
box = [0, 1, 0, 1]

mesh = mf.boxmesh2d(box, nx=5, ny=5, meshtype='tri')

point = np.array([(0.10, 0.50), (0.90, 0.50), (0.15, 0.10), (0.31, 0.90)],
                 dtype=np.float64)
segment = np.array([(0, 1), (2, 3)], dtype=np.int_)

isCutCell = mesh.find_crossed_cell(point, segment)

mesh.bisect(isCutCell)
#isCutCell = mesh.find_crossed_cell(point, segment)
#mesh.bisect(isCutCell)
#isCutCell = mesh.find_crossed_cell(point, segment)

lc = mc.LineCollection(point[segment], linewidths=2)
cidx, = np.nonzero(isCutCell)
fig = plt.figure()
axes = fig.gca()
mesh.add_plot(axes)
mesh.find_cell(axes, showindex=True)
axes.add_collection(lc)
plt.show()
Example #25
0
 def show_face_basis_index_test(self):
     mfactory = MeshFactory()
     mesh = mfactory.one_tetrahedron_mesh()
     space = ScaledMonomialSpace3d(mesh, p=3)
     space.show_face_basis_index(p=3)
Example #26
0
 def face_index_test(self, p=3):
     mfactory = MeshFactory()
     mesh = mfactory.one_tetrahedron_mesh()
     space = ScaledMonomialSpace3d(mesh, p=p)
     space.face_diff_index_1()
Example #27
0
from fealpy.functionspace.ScaledMonomialSpace2d import ScaledMonomialSpace2d
from fealpy.mesh import MeshFactory
from fealpy.mesh import HalfEdgeMesh2d
from HHOStokesSpace2d import HHOStokesSpace2d
from Stokes2DData import Stokes2DData_0


# --- begin --- #
n = 2
p = 1
nu = 1.0
pde = Stokes2DData_0(nu)  # create pde model

# --- mesh setting --- #
box = [0, 1, 0, 1]  # [0, 1]^2 domain
mf = MeshFactory()
meshtype = 'quad'
mesh = mf.boxmesh2d(box, nx=n, ny=n, meshtype=meshtype)
mesh = HalfEdgeMesh2d.from_mesh(mesh)
mesh.init_level_info()
mesh.uniform_refine(n-2)  # refine the mesh at beginning

# --- plot the mesh --- #
# fig = plt.figure()
# axes = fig.gca()
# mesh.add_plot(axes, cellcolor='w')
# find_entity(axes, mesh, entity='cell', showindex=True, color='b', markersize=10, fontsize=8)
# find_entity(axes, mesh, entity='edge', showindex=True, color='r', markersize=10, fontsize=8)
# find_entity(axes, mesh, entity='node', showindex=True, color='y', markersize=10, fontsize=8)
# plt.show()
# ---- tri mesh ----
# node = np.array([
#     (0, 0),
#     (1, 0),
#     (1, 1),
#     (0, 1)], dtype=np.float)
# cell = np.array([(1, 2, 0), (3, 0, 2)], dtype=np.int)  # tri mesh
# mesh = TriangleMesh(node, cell)
# mesh.uniform_refine(n)
# mesh = HalfEdgeMesh2d.from_mesh(mesh, NV=3)  # 三角形网格的单边数据结构
# ------------------

# |--- other mesh
domain = [0, 1, 0, 1]
nn = 4
mesh = MF.boxmesh2d(domain, nx=nn, ny=nn, meshtype='tri')
# mesh = HalfEdgeMesh2d.from_mesh(mesh, NV=3)  # 三角形网格的单边数据结构

dof = CPLFEMDof2d(mesh, p)

ipoint = dof.interpolation_points()
cell2dof = dof.cell2dof
edge2dof = dof.edge_to_dof()
node = mesh.entity('node')
edge = mesh.entity('edge')

# |--- plot mesh
# fig = plt.figure()
# axes = fig.gca()
# mesh.add_plot(axes, cellcolor='w')
# find_entity(axes, mesh, entity='cell', showindex=True, color='b', fontsize=15)
Example #29
0
 def __init__(self):
     self.meshfactory = MeshFactory()
# --- start for-loop --- #
if hasattr(pde, 'box'):
    box = pde.box
    print('PDE has new domain box = ', box)

for i in range(N_T):
    print(
        '\n# *********************************************************************** # \n'
    )
    print('# ------------ in the time-mesh circle ------------ #')
    print('i = ', i)
    print('# -------------------------------------------------- #')
    # NN = int(1./h_space[i]) + 1
    NN = 128
    print('    In new looping, NN = ', NN)
    mesh = MF.boxmesh2d(box, nx=NN, ny=NN, meshtype='tri')
    if time_scheme == 1:
        ch = FEM_CH_NS_Var_addXi_Model2d(pde, mesh, p, dt_space[i])
        uh_l2err, uh_h1err, vel_l2err, vel_h1err, ph_l2err = ch.CH_NS_addXi_Solver_T1stOrder(
        )
    else:
        raise ValueError("There has no other time-scheme")

    Ndof[i] = ch.number_of_global_dofs()
    errorMatrix[0, i] = uh_l2err
    errorMatrix[1, i] = uh_h1err
    errorMatrix[2, i] = vel_l2err
    errorMatrix[3, i] = vel_h1err
    errorMatrix[4, i] = ph_l2err

# --- get the convergence rate --- #