Esempio n. 1
0
    def poisson_fem_2d_neuman_test(self, p=1):
        pde = CosCosData()
        mesh = pde.init_mesh(n=2)
        for i in range(4):
            space = LagrangeFiniteElementSpace(mesh, p=p)
            A = space.stiff_matrix()
            b = space.source_vector(pde.source)
            uh = space.function()
            bc = BoundaryCondition(space, neuman=pde.neuman)
            bc.apply_neuman_bc(b)
            c = space.integral_basis()
            AD = bmat([[A, c.reshape(-1, 1)], [c, None]], format='csr')
            bb = np.r_[b, 0]
            x = spsolve(AD, bb)
            uh[:] = x[:-1]

            area = np.sum(space.integralalg.cellmeasure)
            ubar = space.integralalg.integral(pde.solution,
                                              barycenter=False) / area

            def solution(p):
                return pde.solution(p) - ubar

            error = space.integralalg.L2_error(solution, uh)
            print(error)
            mesh.uniform_refine()
Esempio n. 2
0
def test_poisson_fem_2d():
    degree = 1  
    dim = 2
    nrefine = 4 
    maxit = 4 

    from fealpy.pde.poisson_2d import CosCosData as PDE

    pde = PDE()
    mesh = pde.init_mesh(n=nrefine)

    errorMatrix = np.zeros((2, maxit), dtype=np.float64)
    NDof = np.zeros(maxit, dtype=np.int64)

    for i in range(maxit):
        space = LagrangeFiniteElementSpace(mesh, p=degree)
        NDof[i] = space.number_of_global_dofs()
        bc = DirichletBC(space, pde.dirichlet) 

        uh = space.function()
        A = space.stiff_matrix()

        F = space.source_vector(pde.source)

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

        uh[:] = spsolve(A, F).reshape(-1)

        errorMatrix[0, i] = space.integralalg.L2_error(pde.solution, uh)
        errorMatrix[1, i] = space.integralalg.L2_error(pde.gradient, uh.grad_value)

        if i < maxit-1:
            mesh.uniform_refine()
Esempio n. 3
0
    def interpolation(self, n=0, p=0):
        pde = CosCosData()
        mesh = pde.init_mesh(n=n, meshtype='tri')
        space = RaviartThomasFiniteElementSpace2d(mesh, p=p)
        uI = space.interpolation(pde.flux)
        print(space.basis.coordtype)
        u = Function(space)
        u[:] = uI

        qf = mesh.integrator(3, 'cell')
        bcs, ws = qf.get_quadrature_points_and_weights()
        error = space.integralalg.L2_error(pde.source, u.div_value)
        print('error:', error)
        print(dir(u))
class QuadBilinearFiniteElementSpaceTest:
    def __init__(self):
        self.pde = CosCosData()
        self.mesh = self.pde.init_mesh(meshtype='quad')
        self.space = QuadBilinearFiniteElementSpace(self.mesh)

    def test_intetpolation(self):
        pass

    def test_projection(self):
        pass

    def test_sovle_poisson_equation(self):
        pass
Esempio n. 5
0
 def poisson_fem_2d_test(self, p=1):
     pde = CosCosData()
     mesh = pde.init_mesh(n=3)
     for i in range(4):
         space = LagrangeFiniteElementSpace(mesh, p=p)
         A = space.stiff_matrix()
         b = space.source_vector(pde.source)
         uh = space.function()
         bc = BoundaryCondition(space, dirichlet=pde.dirichlet)
         A, b = bc.apply_dirichlet_bc(A, b, uh)
         uh[:] = spsolve(A, b).reshape(-1)
         error = space.integralalg.L2_error(pde.solution, uh)
         print(error)
         mesh.uniform_refine()
Esempio n. 6
0
    def interpolation(self, n=0, p=0, plot=True):

        box = [-0.5, 1.5, -0.5, 1.5]
        pde = CosCosData()
        mesh = pde.init_mesh(n=n, meshtype='tri')
        space = RaviartThomasFiniteElementSpace2d(mesh, p=p)
        uI = space.interpolation(pde.flux)
        error = space.integralalg.L2_error(pde.flux, uI)
        print(error)
        if plot:
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes, box=box)
            plt.show()
Esempio n. 7
0
def plane_pmesh():
    pde = CosCosData()
    mesh = pde.init_mesh(n=0)
    node = mesh.entity('node')
    cell = mesh.entity('cell')
    NN = mesh.number_of_nodes()
    pnode = np.zeros((2 * NN, 3), dtype=mesh.ftype)
    pnode[:NN, 0:2] = node
    pnode[NN:, 0:2] = node
    pnode[NN:, 2] = 1
    pcell = np.r_['1', cell, cell + NN]

    pmesh = PrismMesh(pnode, pcell)
    return pmesh
Esempio n. 8
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)
    def test_space_on_triangle(self, p=3):
        pde = CosCosData()
        mesh = pde.init_mesh(0)
        space = LagrangeFiniteElementSpace(mesh, p=p)
        ips = space.interpolation_points()
        face2dof = space.dof.face_to_dof()
        print(face2dof)
        print(mesh.entity('cell'))
        print('cell2dof:', space.cell_to_dof())

        fig = plt.figure()
        axes = fig.gca()
        mesh.add_plot(axes)
        mesh.find_node(axes, node=ips, showindex=True)
        mesh.find_edge(axes, showindex=True)
        plt.show()
Esempio n. 10
0
    def print_method(self, n=0, p=0): 
        pde = CosCosData()
        mesh = pde.init_mesh(n=n, meshtype='tri')
        space = LagrangeFiniteElementSpace(mesh, p=p)

        array = space.array(dim=2)

        uI = Function(space, array=array)
        qf = mesh.integrator(3, 'cell')
        bcs, ws = qf.get_quadrature_points_and_weights()

        print("__call__:", uI(bcs))
        print("value:", uI.value(bcs))
        print(uI[1:2])
        print(uI.index(0))
        print(uI.__dict__)
Esempio n. 11
0
    def sympy_compute(self, plot=True):
        import sympy as sp
        from sympy.abc import x, y, z

        if plot:
            pde = CosCosData()
            mesh = pde.init_mesh(n=0, meshtype='tri')
            n = mesh.edge_unit_normal()
            print("n:\n", n)
            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()
Esempio n. 12
0
def test_poisson():

    p = 1  # 有限元空间次数, 可以增大 p, 看输出结果的变化
    n = 4  # 初始网格加密次数
    maxit = 4  # 最大迭代次数

    pde = PDE()
    mesh = pde.init_mesh(n=n)

    errorMatrix = np.zeros((2, maxit), dtype=np.float)
    NDof = np.zeros(maxit, dtype=np.float)

    for i in range(maxit):
        space = LagrangeFiniteElementSpace(mesh, p=p)  # 建立有限元空间

        NDof[i] = space.number_of_global_dofs()  # 有限元空间自由度的个数
        bc = DirichletBC(space, pde.dirichlet)  # DirichletBC 条件

        uh = space.function()  # 有限元函数
        A = space.stiff_matrix()  # 刚度矩阵
        F = space.source_vector(pde.source)  # 载荷向量

        A, F = bc.apply(A, F, uh)  # 处理边界条件

        uh[:] = spsolve(A, F).reshape(-1)  # 稀疏矩阵直接解法器

        # ml = pyamg.ruge_stuben_solver(A)  # 代数多重网格解法器
        # uh[:] = ml.solve(F, tol=1e-12, accel='cg').reshape(-1)

        errorMatrix[0, i] = space.integralalg.L2_error(
            pde.solution, uh
        )  # 计算 L2 误差
        errorMatrix[1, i] = space.integralalg.L2_error(
            pde.gradient, uh.grad_value
        )  # 计算 H1 误差

        if i < maxit - 1:
            mesh.uniform_refine()  # 一致加密网格

    assert (errorMatrix < 1.0).all()
Esempio n. 13
0
def simulation(queue=None):
    pde = CosCosData()
    mesh = pde.init_mesh(n=3, meshtype='tri')
    if queue is not None:
        queue.put({'mesh': mesh})
    return mesh
Esempio n. 14
0
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

from fealpy.pde.poisson_2d import CosCosData as PDE
from fealpy.functionspace import LagrangeFiniteElementSpace

pde = PDE()

mesh = pde.init_mesh(n=4, meshtype='tri')

space = LagrangeFiniteElementSpace(mesh, 2)

uI = space.interpolation(pde.solution)  # 有限元空间的函数,同地它也是一个数组

bc = np.array([1 / 3, 1 / 3, 1 / 3], dtype=np.float64)
val = uI(bc)  # (NC, )
val = uI.value(bc)  # (NC, )
gval = uI.grad_value(bc)  #(NC, GD)

L2error = space.integralalg.error(pde.solution, uI, q=5, power=2)
H1error = space.integralalg.error(pde.gradient, uI.grad_value, q=5, power=2)
print(H1error)

fig = plt.figure()
axes = fig.add_subplot(projection='3d')
uI.add_plot(axes, cmap='rainbow')
plt.show()
Esempio n. 15
0
import numpy as np
import matplotlib.pyplot as plt

from fealpy.pde.poisson_2d import CosCosData
from fealpy.functionspace import ConformingVirtualElementSpace2d, ScaledMonomialSpace2d
p = 1

pde = CosCosData()
quadtree = pde.init_mesh(n=5, meshtype='quadtree')
options = quadtree.adaptive_options(method='numrefine', maxsize=1, HB=True)

pmesh = quadtree.to_pmesh()

space0 = ConformingVirtualElementSpace2d(pmesh, p=p)
uh0 = space0.interpolation(pde.solution)
sh0 = space0.project_to_smspace(uh0)
error = space0.integralalg.L2_error(pde.solution, sh0.value)
print(error)

axes0 = plt.subplot(1, 2, 1)
pmesh.add_plot(axes0)
pmesh.find_cell(axes0, showindex=True)

NC = pmesh.number_of_cells()
eta = -1 * np.ones(NC, dtype=np.int)

quadtree.adaptive(eta, options)
pmesh = quadtree.to_pmesh()

space1 = ConformingVirtualElementSpace2d(pmesh, p=p)
uI = space1.interpolation(sh0, options['HB'])
Esempio n. 16
0
    def solve_poisson_2d(self):

        pde = CosCosData()
        mesh = pde.init_mesh(n=3, methtype='tri')
        space = RaviartThomasFiniteElementSpace2d(mesh, p=0)
Esempio n. 17
0
    def solve_poisson_2d(self, n=3, p=0, plot=True):
        pde = CosCosData()

        mesh = pde.init_mesh(n=n, meshtype='tri')
        space = RaviartThomasFiniteElementSpace2d(mesh, p=p)

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

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

        if True:
            F0 = -space.set_neumann_bc(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)
        else:
            isBdDof = -space.set_dirichlet_bc(uh, pde.neumann)
            x = np.r_['0', uh, ph]
            isBdDof = np.r_['0', isBdDof, np.zeros(pdof, dtype=np.bool_)]

            FF = np.r_['0', np.zeros(udof, dtype=np.float64), F1]

            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:]

            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)

        if plot:
            box = [-0.5, 1.5, -0.5, 1.5]
            fig = plt.figure()
            axes = fig.gca()
            mesh.add_plot(axes, box=box)
            #mesh.find_node(axes, showindex=True)
            #mesh.find_edge(axes, showindex=True)
            #mesh.find_cell(axes, showindex=True)
            node = ps.reshape(-1, 2)
            uv = uh.reshape(-1, 2)
            axes.quiver(node[:, 0], node[:, 1], uv[:, 0], uv[:, 1])
            plt.show()
Esempio n. 18
0
from fealpy.tools.show import showmultirate, show_error_table
from fealpy.pde.poisson_2d import CosCosData as PDE

n = 3
maxit = 4
pde = PDE()  # 创建 pde 模型

# 误差类型与误差存储数组
errorType = ['$|| u - u_h||_0$', '$||\\nabla u - \\nabla u_h||_0$']
errorMatrix = np.zeros((len(errorType), maxit), dtype=np.float)

# 自由度数组
Ndof = np.zeros(maxit, dtype=np.int)

# 创建初始网格对象
mesh = pde.init_mesh(n, meshtype='quad')

for i in range(maxit):
    fem = PoissonQBFEMModel(pde, mesh, q=3)  # 创建 Poisson 有限元模型
    ls = fem.solve()  # 求解
    Ndof[i] = fem.space.number_of_global_dofs()  # 获得空间自由度个数
    errorMatrix[0, i] = fem.L2_error()  # 计算 L2 误差
    errorMatrix[1, i] = fem.H1_semi_error()  # 计算 H1 误差
    if i < maxit - 1:
        mesh.uniform_refine()  # 一致加密网格

# 显示误差
show_error_table(Ndof, errorType, errorMatrix)
# 可视化误差收敛阶
showmultirate(plt, 0, Ndof, errorMatrix, errorType)
Esempio n. 19
0
import numpy as np
import matplotlib.pyplot as plt
import sys

from fealpy.functionspace import ConformingVirtualElementSpace2d
from fealpy.pde.poisson_2d import CosCosData

n = int(sys.argv[1])
p = int(sys.argv[2])
pde = CosCosData()

mesh = pde.init_mesh(n=n, meshtype='quadtree')

pmesh = mesh.to_pmesh()

space = ConformingVirtualElementSpace2d(pmesh, p=p)
uI = space.interpolation(pde.solution)
S = space.project_to_smspace(uI)

error = space.integralalg.L2_error(pde.solution, S.value)
print(error)
uh = space.grad_recovery(uI)
S = space.project_to_smspace(uh)


def f(x, cellidx):
    val = S.value(x, cellidx)
    return np.sum(val**2, axis=-1)


a = space.integralalg.integral(f, celltype=True)
Esempio n. 20
0
from fealpy.solver import MatlabSolver
from fealpy.pde.poisson_2d import CosCosData
from fealpy.functionspace import LagrangeFiniteElementSpace
from fealpy.boundarycondition import DirichletBC

p = int(sys.argv[1])
maxit = int(sys.argv[2])

start = timer()
solver = MatlabSolver()
end = timer()

print("The matalb start time:", end - start)

pde = CosCosData()
mesh = pde.init_mesh(4)

for i in range(maxit):
    space = LagrangeFiniteElementSpace(mesh, p=1)
    gdof = space.number_of_global_dofs()
    print("The num of dofs:", gdof)
    A = space.stiff_matrix()
    b = space.source_vector(pde.source)
    bc = DirichletBC(space, pde.dirichlet)
    AD, b = bc.apply(A, b)
    uh0 = solver.divide(AD, b)
    start = timer()
    uh1 = spsolve(AD, b)
    end = timer()
    print("The spsolver time:", end - start)
Esempio n. 21
0
from fealpy.boundarycondition import NeumannBC
from fealpy.tools.show import showmultirate

p = 1
n = 2
maxit = 3
d = 4

if d == 2:
    from fealpy.pde.poisson_2d import CosCosData as PDE
elif d == 3:
    from fealpy.pde.poisson_3d import CosCosCosData as PDE

#pde = PDE()
pde = CosCosData()
mesh = pde.init_mesh(n=3)

errorType = [
    '$|| u - u_h||_{\Omega,0}$', '$||\\nabla u - \\nabla u_h||_{\Omega, 0}$'
]
errorMatrix = np.zeros((2, maxit), dtype=np.float)
NDof = np.zeros(maxit, dtype=np.float)

for i in range(maxit):
    space = LagrangeFiniteElementSpace(mesh, p=p)
    NDof[i] = space.number_of_global_dofs()

    uh = space.function()
    A = space.stiff_matrix()
    F = space.source_vector(pde.source)
Esempio n. 22
0
        help='默认网格加密求解的次数, 默认加密求解 4 次')

args = parser.parse_args()

degree = args.degree
dim = args.dim
nrefine = args.nrefine
maxit = args.maxit

if dim == 2:
    from fealpy.pde.poisson_2d import CosCosData as PDE
elif dim == 3:
    from fealpy.pde.poisson_3d import CosCosCosData as PDE

pde = PDE()
mesh = pde.init_mesh(n=nrefine)

errorType = ['$|| u - u_h||_{\Omega,0}$',
             '$||\\nabla u - \\nabla u_h||_{\Omega, 0}$'
             ]
errorMatrix = np.zeros((2, maxit), dtype=np.float64)
NDof = np.zeros(maxit, dtype=np.float64)

for i in range(maxit):
    space = LagrangeFiniteElementSpace(mesh, p=degree)
    NDof[i] = space.number_of_global_dofs()

    uh = space.function()
    A = space.stiff_matrix()
    F = space.source_vector(pde.source)