def test_poisson_equation(self, p=1, maxit=4): h = 0.1 pde = CosCosData() domain = pde.domain() error = np.zeros((maxit,), dtype=np.float) for i in range(maxit): mesh = triangle(domain, h, meshtype='polygon') dmodel = SobolevEquationWGModel2d(self.pde, mesh, p=p) uh = dmodel.space.function() dmodel.space.set_dirichlet_bc(uh, pde.dirichlet) S = dmodel.space.stabilizer_matrix() A = dmodel.G + S F = dmodel.space.source_vector(pde.source) F -= A@uh isBdDof = dmodel.space.boundary_dof() gdof = dmodel.space.number_of_global_dofs() bdIdx = np.zeros(gdof, dtype=np.int) bdIdx[isBdDof] = 1 Tbd = spdiags(bdIdx, 0, gdof, gdof) T = spdiags(1-bdIdx, 0, gdof, gdof) A = T@A@T + Tbd F[isBdDof] = uh[isBdDof] uh[:] = spsolve(A, F) integralalg = dmodel.space.integralalg error[i] = integralalg.L2_error(pde.solution, uh) h /= 2 print(error) print(error[0:-1]/error[1:])
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()
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()
def test_polation_interoperator(self): pde = CosCosData() maxit = 4 errorType = ['$|u_I - u_h|_{max}$'] Maxerror = np.zeros((len(errorType), maxit), dtype=np.float) NE = np.zeros(maxit, ) for i in range(maxit): start3 = time.time() mesh = self.mesh isBDEdge = mesh.ds.boundary_edge_flag() NE[i] = mesh.number_of_edges() h = mesh.hx bc = mesh.entity_barycenter('cell') ec = mesh.entity_barycenter('edge') uI = mesh.polation_interoperator(pde.solution(bc)) uh = pde.solution(ec) Maxerror[0, i] = np.sqrt(np.sum(h**2 * (uh - uI)**2)) # Maxerror[0, i] = max(abs(uh - uI)) end3 = time.time() print('time of %d iteration' % i, end3 - start3) if i < maxit - 1: mesh.uniform_refine() showmultirate(plt, 0, NE, Maxerror, errorType) print('Maxerror', Maxerror) plt.show()
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()
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()
def test_cbar(self): dt = 0 start4 = time.time() mesh = self.mesh pde = CosCosData() bc = mesh.entity_barycenter('cell') ch = pde.solution(bc) NC = mesh.number_of_cells() cellidx = np.arange(NC) xbar = bc - dt cbar = mesh.cbar_interpolation(ch, cellidx, xbar) end4 = time.time() print('test_cbar time', end4 - start4) print('cbar', sum(cbar - ch))
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
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))
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()
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()
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__)
def interpolation(self, n=2, plot=True): from fealpy.pde.poisson_2d import CosCosData from fealpy.functionspace import ConformingVirtualElementSpace2d pde = CosCosData() node = np.array([(0, 0), (1, 0), (1, 1), (0, 1)], dtype=np.float64) cell = np.array([(0, 1, 2, 3)], dtype=np.int_) mesh = QuadrangleMesh(node, cell) #mesh = PolygonMesh.from_mesh(mesh) mesh = HalfEdgeMesh2d.from_mesh(mesh) mesh.uniform_refine(n=n) #mesh.print() space = ConformingVirtualElementSpace2d(mesh, p=1) uI = space.interpolation(pde.solution) up = space.project_to_smspace(uI) error = space.integralalg.L2_error(pde.solution, up) print(error) if plot: fig = plt.figure() axes = fig.gca() #mesh.add_halfedge_plot(axes, showindex=True) mesh.add_plot(axes) mesh.find_node(axes, showindex=True) mesh.find_edge(axes, showindex=True) mesh.find_cell(axes, showindex=True) plt.show()
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()
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
def test_interpolation(self): start2 = time.time() pde = CosCosData() F0 = self.mesh.interpolation(pde.solution, intertype='node') print(F0.shape) F1 = self.mesh.interpolation(pde.solution, intertype='edge') print(F1.shape) F2 = self.mesh.interpolation(pde.solution, intertype='edgex') print(F2.shape) F3 = self.mesh.interpolation(pde.solution, intertype='edgey') print(F3.shape) F4 = self.mesh.interpolation(pde.solution, intertype='cell') print(F4.shape) end2 = time.time() print('time of interpolation', end2 - start2)
def plane_quad_interpolation(self, p=2, fname='plane.vtu'): from fealpy.pde.poisson_2d import CosCosData from fealpy.mesh import LagrangeQuadrangleMesh pde = CosCosData() node = np.array([(0, 0), (0, 1), (1, 0), (1, 1)], dtype=np.float64) cell = np.array([(0, 1, 2, 3)], dtype=np.int_) mesh = LagrangeQuadrangleMesh(node, cell, p=p) for i in range(4): space = ParametricLagrangeFiniteElementSpace(mesh, p=p) uI = space.interpolation(pde.solution) mesh.nodedata['uI'] = uI[:] error0 = space.integralalg.error(pde.solution, uI.value) error1 = space.integralalg.error(pde.gradient, uI.grad_value) print(error0, error1) if i < 3: mesh.uniform_refine() mesh.to_vtk(fname=fname)
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()) np.savetxt('A.txt', A.toarray(), fmt='%.2e') np.savetxt('A0.txt', A0.toarray(), fmt='%.2e') np.savetxt('S0.txt', S0.toarray(), fmt='%.2e') if False: h = 0.1 maxit = 1 pde = CosCosData() box = pde.domain() for i in range(maxit): mesh = triangle(box, h / 2**(i - 1), meshtype='polygon') space = ConformingVirtualElementSpace2d(mesh, p=1) uh = space.function() bc = BoundaryCondition(space, dirichlet=pde.dirichlet) A0, S0 = space.chen_stability_term() A0 = A0.toarray() S0 = S0.toarray() A = space.stiff_matrix() F = space.source_vector(pde.source)
scale=1) axes.quiver(space.ccenter[:, 0], space.ccenter[:, 1], A0[:, 0], A0[:, 1], angles='xy', scale_units='xy', scale=1) plt.show() 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.float) cell = np.array([(0, 4, 8, 7), (4, 1, 5, 8), (7, 8, 6, 3), (8, 5, 2, 6)], dtype=np.int) pde = CosCosData() mesh = QuadrangleMesh(node, cell) mesh.uniform_refine(7) space = QuadBilinearFiniteElementSpace(mesh) uI = space.interpolation(pde.solution) L2 = space.integralalg.L2_error(pde.solution, uI.value) print("L2:", L2) H1 = space.integralalg.L2_error(pde.gradient, uI.grad_value) print("H1:", H1)
import matplotlib.pyplot as plt from scipy.sparse import csr_matrix import sys import sympy from mpl_toolkits.mplot3d import Axes3D from fealpy.decorator import cartesian from scipy.sparse.linalg import spsolve from fealpy.boundarycondition import DirichletBC from fealpy.pde.poisson_2d import CosCosData as PDE from fealpy.tools.show import showmultirate, show_error_table n = 10 p = 4 mf = MeshFactory() mesh = mf.boxmesh2d([0, 1, 0, 1], nx=n, ny=n, meshtype='tri') pde = PDE() domain = pde.domain() maxit = 4 errorType = [ '$|| u - u_h||_{\Omega,0}$', # L2 误差 '$||\\nabla u - \\nabla u_h||_{\Omega, 0}$' ] # H1 误差 errorMatrix = np.zeros((2, maxit), dtype=np.float) NDof = np.zeros(maxit, dtype=np.float) for i in range(maxit): print('Step:', i) space = LagrangeFiniteElementSpace(mesh, p=p) NDof[i] = space.number_of_global_dofs() uh = space.function() a = np.array([(10.0, -1.0), (-1.0, 2.0)], dtype=np.float64)
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()
from scipy.sparse.linalg import spsolve from fealpy.pde.poisson_2d import CosCosData from fealpy.mesh import MeshFactory from fealpy.decorator import cartesian, barycentric from fealpy.functionspace import RaviartThomasFiniteElementSpace2d from fealpy.solver import SaddlePointFastSolver p = int(sys.argv[1]) # RT 空间的次数 n = int(sys.argv[2]) # 初始网格部分段数 maxit = int(sys.argv[3]) # 迭代求解次数 pde = CosCosData() # pde 模型 box = pde.domain() # 模型区域 mf = MeshFactory() # 网格工场 for i in range(maxit): mesh = mf.boxmesh2d(box, nx=n, ny=n, meshtype='tri') space = RaviartThomasFiniteElementSpace2d(mesh, p=p) udof = space.number_of_global_dofs() pdof = space.smspace.number_of_global_dofs() gdof = udof + pdof print("step ", i, " with number of dofs:", gdof) uh = space.function() ph = space.smspace.function()
#!/usr/bin/env python3 # import sys import numpy as np from scipy.sparse.linalg import spsolve import matplotlib.pyplot as plt from fealpy.pde.poisson_2d import CosCosData from fealpy.functionspace import LagrangeFiniteElementSpace from fealpy.boundarycondition import BoundaryCondition pde = CosCosData() print('test') mesh = pde.init_mesh(n=7, meshtype='tri') print('test') space = LagrangeFiniteElementSpace(mesh, p=1) print('test') A = space.stiff_matrix() print('test') b = space.source_vector(pde.source) print('test') uh = space.function() bc = BoundaryCondition(space, robin=pde.robin) bc.apply_robin_bc(A, b) uh[:] = spsolve(A, b).reshape(-1) error = space.integralalg.L2_error(pde.solution, uh)
from fealpy.pde.poisson_2d import CosCosData as PDE import numpy as np from ShowCls import ShowCls from PoissonDGModel2d import PoissonDGModel2d from fealpy.mesh import MeshFactory as mf from fealpy.mesh import HalfEdgeMesh2d # from fealpy.mesh.mesh_tools import find_entity # import matplotlib.pyplot as plt # --- begin setting --- # d = 2 # the dimension p = 1 # the polynomial order n = 1 # the number of refine mesh maxit = 5 # the max iteration of the mesh pde = PDE() # create pde model pde.epsilon = -1 # setting the DG-scheme parameter # # epsilon may take -1, 0, 1, # # the corresponding DG-scheme is called symmetric interior penalty Galerkin (SIPG), # # incomplete interior penalty Galerkin (IIPG) and nonsymmetric interior penalty Galerkin (NIPG) pde.eta = 16 # setting the penalty parameter # # To get the optimal rate, one should choose the appropriate 'eta' # # according to the polynomial order 'p', 'epsilon' and mesh. # # error settings 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) # the array to store the number of dofs
def __init__(self): self.pde = CosCosData() self.mesh = self.pde.init_mesh(meshtype='quad') self.space = QuadBilinearFiniteElementSpace(self.mesh)
from fealpy.functionspace import LagrangeFiniteElementSpace from fealpy.boundarycondition import RobinBC from fealpy.tools.show import showmultirate p = int(sys.argv[1]) n = int(sys.argv[2]) maxit = int(sys.argv[3]) d = int(sys.argv[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() mesh = pde.init_mesh(n=n) 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()
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()
from fealpy.functionspace import LagrangeFiniteElementSpace 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)
def __init__(self, p=2, h=0.2): self.pde = CosCosData()