def test_mesh_dist_sub1(): comm = MPI_Init() groups = [[0, 1, 3, 4]] assert comm.size >= 5 sub_comm = comm.SubComm(find_group(comm, groups)) import netgen.meshing ngmesh2d = netgen.meshing.Mesh(dim=2) if sub_comm.rank == 0: from netgen.geom2d import unit_square ngmesh2d = unit_square.GenerateMesh(maxh=0.1) ngmesh2d.Distribute(sub_comm) assert ngmesh2d.comm.size == sub_comm.size assert ngmesh2d.comm.rank == sub_comm.rank mesh2d = Mesh(ngmesh2d) assert mesh2d.comm.size == sub_comm.size assert mesh2d.comm.rank == sub_comm.rank ngmesh3d = netgen.meshing.Mesh(dim=3) if sub_comm.rank == 0: from netgen.csg import unit_cube ngmesh3d = unit_cube.GenerateMesh(maxh=0.2) ngmesh3d.Distribute(sub_comm) assert ngmesh3d.comm.size == sub_comm.size assert ngmesh3d.comm.rank == sub_comm.rank mesh3d = Mesh(ngmesh3d) assert mesh3d.comm.size == sub_comm.size assert mesh3d.comm.rank == sub_comm.rank comm.Barrier()
def test_mesh_size_cf(): for mesh in [ Mesh(unit_cube.GenerateMesh(maxh=0.2)), Mesh(unit_square.GenerateMesh(maxh=0.2)) ]: dim = mesh.dim fes = L2(mesh, order=0) gfu = GridFunction(fes) cf = specialcf.mesh_size if dim == 2: gfu.Set(cf * cf / 2) else: gfu.Set(cf * cf * cf / 6) assert abs(sum(gfu.vec) - 1) < 1e-12 bfi = BilinearForm(fes) bfi += SymbolicBFI(fes.TrialFunction() * (specialcf.mesh_size - specialcf.mesh_size.Compile(True, wait=True)) * fes.TestFunction(), element_boundary=True) bfi.Assemble() v = bfi.mat.AsVector().FV() for val in v: assert abs(val) < 1e-14
def test_code_generation_volume_terms_complex(): mesh = Mesh(unit_cube.GenerateMesh(maxh=0.2)) fes = L2(mesh, order=5, complex=True) gfu = GridFunction(fes) functions = [ 1J * x, 1j * y, 1J * x * y + y, sin(1J * x) * y + x, exp(x + 1J * y) + y * y * y * sin(1J * x), 1J * specialcf.mesh_size ] functions = functions[:1] for cf in functions: gfu.Set(cf) print("norm gfu.vec = ", Norm(gfu.vec)) # should all give the same results cfs = [ cf.Compile(), cf.Compile(True, wait=True), gfu, gfu.Compile(), gfu.Compile(True, wait=True) ] for f in cfs: print("integral f =", Integrate(f, mesh)) print("integral cf =", Integrate(cf, mesh)) print("integral cf-f =", Integrate(cf - f, mesh)) print("integral Conj(cf-f) =", Integrate(Conj(cf - f), mesh)) error = (cf - f) * Conj(cf - f) assert (abs(Integrate(error, mesh)) < 1e-13)
def test_fes_timing(dimension=2, stdfes=True, quad_dominated=False, order=1): if dimension == 2: mesh = Mesh( unit_square.GenerateMesh(maxh=0.2, quad_dominated=quad_dominated)) else: mesh = Mesh( unit_cube.GenerateMesh(maxh=0.2, quad_dominated=quad_dominated)) Vhs = H1(mesh, order=order, dirichlet=[1, 2, 3, 4]) lsetp1 = GridFunction(H1(mesh, order=1)) InterpolateToP1((sqrt(sqrt(x * x + y * y)) - 1.0), lsetp1) if stdfes: Vh = Vhs else: Vhx = XFESpace(Vhs, lsetp1) Vh = Vhx container = Vh.__timing__() ts = time.time() steps = 5 for i in range(steps): Vh.Update() te = time.time() return 1e9 * (te - ts) / steps
def test_pickle_multidim(): mesh = Mesh(unit_cube.GenerateMesh(maxh=0.4)) fes = H1(mesh,order=3,dim=3) u = GridFunction(fes) u.Set((1,2,3)) pickled = pickle.dumps((u,grad(u))) u2, gradu2 = pickle.loads(pickled) assert numpy.linalg.norm(u.vec.FV().NumPy() - u2.vec.FV().NumPy()) < 1e-14 assert Integrate(Norm(grad(u)-gradu2), mesh) < 1e-14
def test_3DGetFE(): mesh = Mesh(unit_cube.GenerateMesh()) for spacename in spaces3d.keys(): for order in spaces3d[spacename]["order"]: space = FESpace(type=spacename,mesh=mesh,order=order) for vb in spaces3d[spacename]["vorb"]: for el in space.Elements(vb): assert space.GetFE(el).ndof == len(space.GetDofNrs(el)), [spacename,vb,order] return
def test_pickle_secondorder_mesh(): m = unit_cube.GenerateMesh(maxh=0.4) m.SecondOrder() mesh = Mesh(m) fes = H1(mesh, order=3) u = GridFunction(fes) u.Set(x) pickled = pickle.dumps(u) u2 = pickle.loads(pickled) assert numpy.linalg.norm(u.vec.FV().NumPy() - u2.vec.FV().NumPy()) < 1e-14
def test_pickle_allsamespace(): mesh = Mesh(unit_cube.GenerateMesh(maxh=0.2)) fes1 = H1(mesh, order=1) fes = fes1**3 gfu = GridFunction(fes) gfu.Set ( (x,y,z) ) data = pickle.dumps(gfu) gfu2 = pickle.loads(data) assert Integrate(Norm(gfu - gfu2), mesh) < 1e-14
def test_code_generation_boundary_terms(): mesh = Mesh(unit_cube.GenerateMesh(maxh=0.2)) functions = [x,y,x*y, sin(x)*y, exp(x)+y*y*y, specialcf.mesh_size] functions = [0.1*f for f in functions] for cf in functions: # should all give the same results cfs = [ cf.Compile(), cf.Compile(True, wait=True)] for f in cfs: print(Integrate ( (cf-f)*(cf-f), mesh, BND)) assert (Integrate ( (cf-f)*(cf-f), mesh, BND)<1e-13)
def test_code_generation_volume_terms(): mesh = Mesh(unit_cube.GenerateMesh(maxh=0.2)) fes = L2(mesh, order=5) gfu = GridFunction(fes) functions = [x,y,x*y, sin(x)*y, exp(x)+y*y*y, specialcf.mesh_size] for cf in functions: gfu.Set(cf) # should all give the same results cfs = [ cf.Compile(), cf.Compile(True, wait=True), gfu, gfu.Compile(), gfu.Compile(True, wait=True) ] for f in cfs: assert (Integrate ( (cf-f)*(cf-f), mesh)<1e-13)
def test_mpi4py(): comm = mpi4py.MPI.COMM_WORLD if comm.rank == 0: from netgen.csg import unit_cube m = unit_cube.GenerateMesh(maxh=0.1) m.Save("mpimesh") comm.Barrier() mesh = netgen.meshing.Mesh(3, comm) mesh.Load("mpimesh.vol.gz") if comm.rank == 0: assert mesh.ne == 0
def test_mesh_dist(): comm = MPI_Init() import netgen.meshing if comm.rank == 0: from netgen.geom2d import unit_square ngmesh2d = unit_square.GenerateMesh(maxh=0.1) ngmesh2d.Distribute(comm) else: ngmesh2d = netgen.meshing.Mesh.Receive(comm) mesh2d = Mesh(ngmesh2d) if comm.rank == 0: from netgen.csg import unit_cube ngmesh3d = unit_cube.GenerateMesh(maxh=0.2) ngmesh3d.Distribute(comm) else: ngmesh3d = netgen.meshing.Mesh.Receive(comm) mesh3d = Mesh(ngmesh3d) comm.Barrier()
def test_mass_l2(): mesh2 = Mesh(unit_square.GenerateMesh(maxh=2)) mesh3 = Mesh(unit_cube.GenerateMesh(maxh=2)) meshes = [mesh2, mesh3] for mesh in meshes: l2 = L2(mesh, order=3) c1 = FESpace([l2, l2]) fes = FESpace([l2, FESpace([l2, l2])]) mass = BilinearForm(fes) u = fes.TrialFunction() v = fes.TestFunction() mass += SymbolicBFI(u[0] * v[0] + u[1][0] * v[1][0] + u[1][1] * v[1][1]) mass.Assemble() m = mass.mat # check if m is diagonal for d in range(fes.ndof): m[d, d] = 0.0 assert Norm(m.AsVector()) / fes.ndof < 1e-15
def test_maxwell(): ngsglobals.msg_level = 1 # Set a "manufactured" exact solution and RHS using sympy: X, Y, Z = sm.symbols('X Y Z') Es = ((1 - Y) * Y * Z * (1 - Z), (1 - X) * X * (1 - Z) * Z, (1 - X) * X * (1 - Y) * Y) def smcurl(M): # symbolic curl return (sm.diff(M[2], Y) - sm.diff(M[1], Z), sm.diff(M[0], Z) - sm.diff(M[2], X), sm.diff(M[1], X) - sm.diff(M[0], Y)) def str2coef(symbol): # symbolic string to ngsolve coefficient function print(symbol) return CoefficientFunction( eval( str(symbol).replace("X", "x").replace("Y", "y").replace("Z", "z"))) Eexact = str2coef(Es) curlcurlEexact = str2coef(smcurl(smcurl(Es))) k = 1 # wave number & RHS: F = curlcurlEexact - k * k * Eexact # Compute numerical solution using DPG forms mesh = Mesh(unit_cube.GenerateMesh(maxh=0.5)) p = 3 Xo = HCurl(mesh, order=p + 1, dirichlet=[1, 2, 3, 4, 5, 6], complex=True) Xh = HCurl(mesh, order=p, complex=True, orderinner=1) Y = HCurl(mesh, order=p + 4, complex=True, discontinuous=True) XY = FESpace([Xo, Xh, Y], complex=True) E, M, e = XY.TrialFunction() G, W, d = XY.TestFunction() def cross(G, N): return CoefficientFunction( (G[1] * N[2] - G[2] * N[1], G[2] * N[0] - G[0] * N[2], G[0] * N[1] - G[1] * N[0])) n = specialcf.normal(mesh.dim) # Set bilinear and linear forms using NGSpy's symbolic forms a = BilinearForm(XY, symmetric=False, eliminate_internal=True) a += SymbolicBFI(curl(E) * curl(d) - k * k * E * d) a += SymbolicBFI(curl(e) * curl(G) - k * k * e * G) a += SymbolicBFI(M * cross(d, n), element_boundary=True) a += SymbolicBFI(cross(e, n) * W, element_boundary=True) a += SymbolicBFI(curl(e) * curl(d) + e * d) f = LinearForm(XY) f += SymbolicLFI(F * d) EMe = GridFunction(XY) # Solve the linear system cdirect = Preconditioner(a, type="direct") SetHeapSize(int(1e8)) a.Assemble() f.Assemble() bvp = BVP(bf=a, lf=f, gf=EMe, pre=cdirect).Do() return EMe # Compare with exact solution l2error = sqrt( Integrate((EMe.components[0] - Eexact) * (EMe.components[0] - Eexact), mesh)) assert l2error < 5.e-13
from ngsolve import * import numpy as np from netgen.csg import unit_cube from ngsolve.krylovspace import CGSolver import petsc4py.PETSc as psc def masterprint(*args, comm=MPI.COMM_WORLD): if comm.rank == 0: print(*args) comm = MPI.COMM_WORLD if comm.rank == 0: ngmesh = unit_cube.GenerateMesh(maxh=0.1).Distribute(comm) else: ngmesh = netgen.meshing.Mesh.Receive(comm) for l in range(0): ngmesh.Refine() mesh = Mesh(ngmesh) fes = H1(mesh, order=1) u, v = fes.TnT() a = BilinearForm(grad(u) * grad(v) * dx + u * v * ds).Assemble() f = LinearForm(x * v * dx).Assemble() gfu = GridFunction(fes) inv = CGSolver(a.mat, freedofs=fes.FreeDofs(), printing=False,
return gfu if __name__ == "__main__": eps = 0 D = 2 order = 4 quads = True ratio = 2 tau = 7 shift = 1.5 scale = 2.5 * shift freq = 1 if D is 3: mesh = Mesh(unit_cube.GenerateMesh(maxh=0.5, quad_dominated=quads)) bndcond = exp(-2 * (freq * pi)**2 * z / tau) * cos( freq * pi * x) * cos(freq * pi * y) else: mesh = Mesh(unit_square.GenerateMesh(maxh=0.5, quad_dominated=quads)) bndcond = exp(-(freq * pi)**2 * y / tau) * cos(freq * pi * x) bndcondscale = (bndcond + shift) / scale Maxh = [1 / 2**i for i in range(1, 7)] errorold = 0 for i, maxh in enumerate(Maxh): if quads and D is 3: meshx = Mesh(unit_square.GenerateMesh(maxh=maxh)) mesht = Mesh(SegMesh(round(1 / (maxh)), 0, 1, periodic=False)) mesh = Mesh(TensorProdMesh(meshx, mesht)) if quads and D is 2:
from netgen.csg import unit_cube # from netgen.geom2d import unit_square from ngsolve import * ngsglobals.msg_level = 1 mesh = Mesh(unit_cube.GenerateMesh(maxh=0.1)) # for k in range(5): # mesh.Refine() order = 3 fes1 = L2(mesh, order=order) fes2 = FacetFESpace(mesh, order=order, dirichlet=[1, 2, 3]) print("element dofs: ", fes1.ndof) print("facet dofs: ", fes2.ndof) fes = FESpace([fes1, fes2]) u, uhat = fes.TrialFunction() v, vhat = fes.TestFunction() grad_u = u.Deriv() grad_v = v.Deriv() n = specialcf.normal(mesh.dim) h = specialcf.mesh_size a = BilinearForm(fes, symmetric=True, eliminate_internal=True) a += SymbolicBFI(grad(u) * grad(v)) a += SymbolicBFI(grad(u) * n * (vhat - v) + grad(v) * n * (uhat - u) + 10 * order * order / h * (u - uhat) * (v - vhat), element_boundary=True)
from ngsolve import * import ngs_petsc as petsc from netgen.meshing import Mesh as NGMesh from time import time comm = mpi_world petsc.Initialize() if comm.rank == 0: from netgen.csg import unit_cube ngm = unit_cube.GenerateMesh(maxh=0.1) ngm.Distribute(comm) else: ngm = NGMesh.Receive(comm) ngm.Refine() mesh = Mesh(ngm) V = H1(mesh, order=5, dirichlet='.*', wb_withoutedges=True) u, v = V.TnT() a = BilinearForm(V) a += SymbolicBFI(grad(u) * grad(v)) if True: c = Preconditioner( a, "bddc", coarsetype="petsc_pc", petsc_pc_petsc_options=[ "pc_type ksp", # "ksp_ksp_monitor", # "ksp_ksp_view_converged_reason",
# ngsolve-imports from ngsolve import * # initialize MPI comm = mpi_world rank = comm.rank np = comm.size do_vtk = False print("Hello from rank " + str(rank) + " of " + str(np)) if rank == 0: # master-proc generates mesh mesh = unit_cube.GenerateMesh(maxh=0.3) # and saves it to file mesh.Save("some_mesh.vol") # wait for master to be done meshing comm.Barrier() # now load mesh from file ngmesh = netgen.meshing.Mesh(dim=3, comm=comm) ngmesh.Load("some_mesh.vol") #refine once? # ngmesh.Refine() mesh = Mesh(ngmesh)
def SolveProblem(h=0.5, p=1, levels=1, condense=False, precond="local"): """ Solve Poisson problem on l refinement levels. h: coarse mesh size p: polynomial degree l: number of refinement levels precond: name of a built-in preconditioner condense: if true, perform static condensations OUTPUT: List of tuples of ndofs and iterations """ #mesh = Mesh(unit_square.GenerateMesh(maxh=h)) mesh = Mesh(unit_cube.GenerateMesh(maxh=h)) fes = H1(mesh, order=p, dirichlet="bottom|left") u, v = fes.TnT() a = BilinearForm(fes, eliminate_internal=condense) a += SymbolicBFI(grad(u) * (grad(v))) f = LinearForm(fes) f += SymbolicLFI(1 * v) gfu = GridFunction(fes) Draw(gfu) if precond != "gs" and precond != "blockjacobi": c = Preconditioner(a, precond) # 'Register' c to a BEFORE assembly steps = [] for l in range(levels): if l > 0: mesh.Refine() fes.Update() a.Assemble() f.Assemble() gfu.Update() if precond == "gs": preJpoint = a.mat.CreateSmoother(fes.FreeDofs()) c = SymmetricGS(preJpoint) if precond == "blockjacobi": blocks = [] freedofs = fes.FreeDofs() for v in mesh.vertices: vdofs = set() for el in mesh[v].elements: vdofs |= set(d for d in fes.GetDofNrs(el) if freedofs[d]) blocks.append(vdofs) c = a.mat.CreateBlockSmoother(blocks) lams = EigenValues_Preconditioner(mat=a.mat, pre=c.mat) print("Condition: ") print(max(lams) / min(lams)) # Conjugate gradient solver inv = CGSolver(a.mat, c.mat, maxsteps=1000) # Solve steps depend on condense if condense: f.vec.data += a.harmonic_extension_trans * f.vec gfu.vec.data = inv * f.vec if condense: gfu.vec.data += a.harmonic_extension * gfu.vec gfu.vec.data += a.inner_solve * f.vec steps.append((fes.ndof, inv.GetSteps())) #inv.GetStep() Redraw() return steps
parser.add_argument('-p', '--parallel', action="store_true", help='Do parallel timings') parser.add_argument( '-a', '--append_data', action="store_true", help='Instead of generating new output file, append data to existing one') args = parser.parse_args() if not (args.parallel or args.sequential): parser.error("No timings requested, specify either -s or -p") mesh2 = Mesh(unit_square.GenerateMesh(maxh=0.03)) mesh3 = Mesh(unit_cube.GenerateMesh(maxh=0.1)) meshes = [mesh2, mesh3] orders = [1, 4] fes_types = [H1, L2, HDiv, HCurl] fes_names = ["H1", "L2", "HDiv", "HCurl"] if args.append_data: results = json.load(open('results.json', 'r')) timings = results['timings'] else: results = {"timings": {}} if "CI_BUILD_REF" in os.environ: results['commit'] = os.environ["CI_BUILD_REF"] results['version'] = -1
hs.append(h) e, *rest = solvewavedirect(mesh, p, F, q_zero, mu_zero, cwave, exactu) # e, *rest = solvewave(mesh, p, F, q_zero, mu_zero, cwave, exactu) er.append(e) mesh.Refine() print_rates(er, hs) elif example == '3d_tetrahedral': maxr = 4 # max refinement h0 = 1.0 # coarsest mesh size p = 0 # polynomial degree mesh = ngs.Mesh(unit_cube.GenerateMesh(maxh=h0)) q_zero = 'bottom' # mesh boundary parts where q = 0, mu_zero = 'bottom|right|left|front|back' # where mu = 0. x = ngs.x y = ngs.y t = ngs.z cwave = 1 F = CoefficientFunction( (0, 0, sin(pi * y) * sin(pi * x) * (2 + 2 * pi * pi * t * t))) exactu = CoefficientFunction((pi * cos(pi * x) * sin(pi * y) * t * t, pi * cos(pi * y) * sin(pi * x) * t * t, 2 * sin(pi * x) * sin(pi * y) * t)) hs = [] er = [] for l in range(maxr):