def test_component_keeps_alive(): mesh = Mesh(unit_square.GenerateMesh(maxh=2)) assert mesh.ne == 2 fes1 = H1(mesh) fes = FESpace([fes1, fes1]) gf = GridFunction(fes) gf.vec[:] = 1 gf1, gf2 = gf.components gf11 = gf.components[0] assert gf1 == gf11 # should return the same object assert len(gf.vec) == 8 assert len(gf1.vec) == 4 mesh.Refine() gf.Update() # check if gf update calls gf1 update as well assert len(gf.vec) == 18 assert len(gf1.vec) == 9 del gf # check if vec is still alive assert len(gf1.vec) == 9 gf1.Set(0) for val in gf1.vec: assert val == 0.0
def solvedpg(p, h, U = 16*x*(1-x)*y*(1-y), minusDeltaU = 32*(y*(1-y)+x*(1-x))) : mesh = Mesh(unit_square.GenerateMesh(quad_dominated=True, maxh=h)) X = H1(mesh, order=p+1, dirichlet=[1,2,3,4]) Q = HDiv(mesh, order=p, orderinner=0) Y = L2(mesh, order=p+2) XY = FESpace( [X,Q,Y]) u,q,e = XY.TrialFunction() w,r,d = XY.TestFunction() n = specialcf.normal(mesh.dim) a = BilinearForm(XY, symmetric=True, eliminate_internal=True) a+= SymbolicBFI(grad(u) * grad(d)) a+= SymbolicBFI(grad(e) * grad(w)) a+= SymbolicBFI(q*n*d, element_boundary=True) a+= SymbolicBFI(e*r*n, element_boundary=True) a.components[2] += Laplace(1.0) a.components[2] += Mass(1.0) f = LinearForm(XY) f.components[2] += Source(minusDeltaU) c = Preconditioner(a, type="direct") uqe = GridFunction(XY) a.Assemble() f.Assemble() bvp = BVP(bf=a, lf=f, gf=uqe, pre=c).Do() Uh = uqe.components[0] l2err = sqrt(Integrate((Uh - U)*(Uh-U), mesh)) print ("L2-error:", l2err) return l2err
def test_spacetime_set(order): ngmesh = unit_square.GenerateMesh(maxh=0.8, quad_dominated=False) mesh = Mesh(ngmesh) coef_told = Parameter(0) delta_t = 1 tref = ReferenceTimeVariable() t = coef_told + delta_t * tref k_s = k_t = order fes1 = H1(mesh, order=k_s) tfe = ScalarTimeFE(k_t) tfe_i = ScalarTimeFE(k_t, skip_first_node=True) # interior tfe_e = ScalarTimeFE(k_t, only_first_node=True) # exterior (inital values) st_fes = SpaceTimeFESpace(fes1, tfe, flags={"dgjumps": True}) st_fes_i = SpaceTimeFESpace(fes1, tfe_i, flags={"dgjumps": True}) st_fes_e = SpaceTimeFESpace(fes1, tfe_e, flags={"dgjumps": True}) gfu_slice = GridFunction(fes1) gfu = GridFunction(st_fes) gfu_i = GridFunction(st_fes_i) gfu_e = GridFunction(st_fes_e) for gf in [gfu, gfu_i, gfu_e]: V = gf.space gf.Set(1 + t) for i, that in enumerate(V.TimeFE_nodes()): if V.IsTimeNodeActive(i): val = 1 + that else: val = 0 RestrictGFInTime(gf, that, gfu_slice) avg = Integrate(gfu_slice, mesh) assert (abs(avg - val) < 1e-12)
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_fes_timing(dimension=2, stdfes=True, quad=False, order=1): if dimension == 2: mesh = Mesh(unit_square.GenerateMesh(maxh=0.2, quad_dominated=quad)) else: mesh = Mesh(unit_cube.GenerateMesh(maxh=0.2, quad_dominated=quad)) 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() container.append(("Update", 1e9 * (te - ts) / steps)) return container
def solve(self): # disable garbage collector # --------------------------------------------------------------------# gc.disable() while (gc.isenabled()): time.sleep(0.1) # --------------------------------------------------------------------# # measure how much memory is used until here process = psutil.Process() memstart = process.memory_info().vms # starts timer tstart = time.time() if self.show_gui: import netgen.gui # create mesh with initial size 0.1 self._mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.1)) #create finite element space self._fes = ngs.H1(self._mesh, order=2, dirichlet=".*", autoupdate=True) # test and trail function u = self._fes.TrialFunction() v = self._fes.TestFunction() # create bilinear form and enable static condensation self._a = ngs.BilinearForm(self._fes, condense=True) self._a += ngs.grad(u) * ngs.grad(v) * ngs.dx # creat linear functional and apply RHS self._f = ngs.LinearForm(self._fes) self._f += (-4) * v * ngs.dx # preconditioner: multigrid - what prerequisits must the problem have? self._c = ngs.Preconditioner(self._a, "multigrid") # create grid function that holds the solution and set the boundary to 0 self._gfu = ngs.GridFunction(self._fes, autoupdate=True) # solution self._g = self._ngs_ex self._gfu.Set(self._g, definedon=self._mesh.Boundaries(".*")) # draw grid function in gui if self.show_gui: ngs.Draw(self._gfu) # create Hcurl space for flux calculation and estimate error self._space_flux = ngs.HDiv(self._mesh, order=2, autoupdate=True) self._gf_flux = ngs.GridFunction(self._space_flux, "flux", autoupdate=True) # TaskManager starts threads that (standard thread nr is numer of cores) with ngs.TaskManager(): # this is the adaptive loop while self._fes.ndof < self.max_ndof: self._solveStep() self._estimateError() self._mesh.Refine() # since the adaptive loop stopped with a mesh refinement, the gfu must be # calculated one last time self._solveStep() if self.show_gui: ngs.Draw(self._gfu) # set measured exectution time self._exec_time = time.time() - tstart # set measured used memory memstop = process.memory_info().vms - memstart self._mem_consumption = memstop # enable garbage collector # --------------------------------------------------------------------# gc.enable() gc.collect()
from mpi4py import MPI from ngsolve import * from netgen.geom2d import unit_square comm = MPI.COMM_WORLD if comm.rank == 0: ngmesh = unit_square.GenerateMesh(maxh=0.1).Distribute(comm) else: ngmesh = netgen.meshing.Mesh.Receive(comm) for l in range(3): ngmesh.Refine() mesh = Mesh(ngmesh) fes = H1(mesh, order=3, dirichlet=".*") u, v = fes.TnT() a = BilinearForm(grad(u) * grad(v) * dx) pre = Preconditioner(a, "local") a.Assemble() f = LinearForm(1 * v * dx).Assemble() gfu = GridFunction(fes) inv = CGSolver(a.mat, pre.mat) gfu.vec.data = inv * f.vec ip = InnerProduct(gfu.vec, f.vec) if comm.rank == 0: print("(u,f) =", ip)
from ngsolve import * from netgen.geom2d import unit_square from xfem import * from math import pi from xfem.lset_spacetime import * ngmesh = unit_square.GenerateMesh(maxh=0.1, quad_dominated=False) mesh = Mesh(ngmesh) coef_told = Parameter(0) coef_delta_t = Parameter(0) tref = ReferenceTimeVariable() t = coef_told + coef_delta_t * tref k_s = k_t = 2 fes1 = H1(mesh, order=k_s) tfe = ScalarTimeFE(k_t) tfe_i = ScalarTimeFE(k_t, skip_first_node=True) # interior tfe_e = ScalarTimeFE(k_t, only_first_node=True) # exterior (inital values) st_fes = SpaceTimeFESpace(fes1, tfe, flags={"dgjumps": True}) st_fes_i = SpaceTimeFESpace(fes1, tfe_i, flags={"dgjumps": True}) st_fes_e = SpaceTimeFESpace(fes1, tfe_e, flags={"dgjumps": True}) gfu = GridFunction(st_fes) gfu_i = GridFunction(st_fes_i) gfu_e = GridFunction(st_fes_e) gfu_to_test = gfu_e
import ngsolve as ngs from ngsolve import VTKOutput, sqrt, Mesh, exp, x, GridFunction from netgen.geom2d import unit_square from wave import vec, waveA, makeforms # PARAMETERS: p = 3 # polynomial degree h0 = 1 # coarse mesh size for unit square domain markprm = 0.5 # percentage of max total error for marking # SET UP: mesh = Mesh(unit_square.GenerateMesh(maxh=h0)) q_zero = 'bottom' # Mesh boundary parts where q and mu_zero = 'bottom|right|left' # mu has essential b.c u00 = exp(-1000 * ((x - 0.5) * (x - 0.5))) # Nonzero initial condition cwave = 1. # wave speed F = ngs.CoefficientFunction((0, 0)) # Zero source a, f, X, sep = makeforms(mesh, p, F, q_zero, mu_zero, cwave, epsil=1.e-10) euz = GridFunction(X) # Contains solution at each adaptive step q = euz.components[sep[0]] # Volume (L2) components mu = euz.components[sep[0]+1] zq = euz.components[sep[1]] # Interface components zmu = euz.components[sep[1]+1] zq.Set(u00, definedon='bottom')
def CompareCfs2D(c1, c2): mesh = Mesh(unit_square.GenerateMesh(maxh=0.2)) c_err = c1 - c2 error = Integrate(c_err * c_err, mesh) return abs(error) < 1e-14
""" Simulate the time-independent Schrödinger Equation""" from scipy.constants import m_e, hbar import ngsolve as ngs from ngsolve import grad from netgen.geom2d import unit_square from random import random mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.05)) fes = ngs.H1(mesh, order=2, dirichlet=[1,2,3,4], complex=True) u = fes.TrialFunction() v = fes.TestFunction() a = ngs.BilinearForm(fes) a += ngs.SymbolicBFI(hbar / 2 / m_e * grad(u) * grad(v)) a.Assemble() m = ngs.BilinearForm(fes) m += ngs.SymbolicBFI(u * v) m.Assemble() gf_psi = ngs.GridFunction(fes) freedofs = fes.FreeDofs() for i in range(len(gf_psi.vec)): gf_psi.vec[i] = random() if freedofs[i] else 0
def test_fespaces_2d(): n_2d = specialcf.normal(2) Ptau_2d = Id(2) - OuterProduct(n_2d, n_2d) Pn_2d = OuterProduct(n_2d, n_2d) # unstructured trig mesh mesh = Mesh(unit_square.GenerateMesh(maxh=0.3, quad_dominated=False)) Test(mesh=mesh, space=H1, order=2, trace=lambda cf: cf, diffops=["hesse", "Grad"], vb=VOL, set_dual=[True, False]) Test(mesh=mesh, space=VectorH1, order=2, trace=lambda cf: cf, diffops=["hesse", "div", "Grad"], vb=VOL, set_dual=[True, False]) Test(mesh=mesh, space=L2, order=2, diffops=["Grad", "hesse"], vb=VOL, set_dual=[False]) Test(mesh=mesh, space=VectorL2, order=2, diffops=["Grad"], vb=VOL, set_dual=[False]) Test(mesh=mesh, space=HCurl, order=2, trace=lambda cf: Ptau_2d * cf, diffops=["curl", "Grad"], vb=VOL, set_dual=[True, False]) Test(mesh=mesh, space=HDiv, order=2, trace=lambda cf: Pn_2d * cf, diffops=["div", "Grad"], vb=VOL, set_dual=[True, False]) Test(mesh=mesh, space=HDivDiv, order=2, trace=lambda cf: Pn_2d * cf * Pn_2d, diffops=["div"], vb=VOL, set_dual=[False], sym=True) Test(mesh=mesh, space=HCurlCurl, order=2, trace=lambda cf: Ptau_2d * cf * Ptau_2d, diffops=["curl", "inc", "christoffel", "christoffel2"], vb=VOL, set_dual=[False], sym=True) Test(mesh=mesh, space=HCurlDiv, order=2, trace=lambda cf: Ptau_2d * cf * Pn_2d, diffops=["div", "curl"], vb=VOL, set_dual=[False], dev=True) Test(mesh=mesh, space=FacetFESpace, order=2, trace=lambda cf: cf, vb=VOL, set_dual=[True], facet=True) Test(mesh=mesh, space=VectorFacetFESpace, order=2, trace=lambda cf: cf, vb=VOL, set_dual=[True], facet=True) Test( mesh=mesh, space=NormalFacetFESpace, order=2, trace=lambda cf: Pn_2d * cf, vb=VOL, set_dual=[], facet=True ) # dual=True: netgen.libngpy._meshing.NgException: normal-facet element evaluated not at BND #Test(mesh=mesh, space=TangentialFacetFESpace, order=2, idop = lambda cf : Ptau_2d*cf, trace = lambda cf : Ptau_2d*cf, vb=VOL, set_dual=[True], facet=True) #idop not Ptau*cf? """ # unstructured (= non-affine) quad mesh mesh = MakeStructured2DMesh(quads=True, nx=3,ny=3, mapping = lambda x,y : (1.3*x*(0.4+0.4*y)**2, 0.75*y)) #Test(mesh=mesh, space=H1, order=2, trace = lambda cf : cf, diffops=["hesse", "Grad"], vb=VOL, set_dual=[True,False], addorder=1) # unstructured trig/quad mixed mesh (boundary could be curved?) geo = SplineGeometry() geo.AddRectangle((0,0), (1,1)) geo.AddCircle( (0.7,0.5), r=0.1, leftdomain=0, rightdomain=1) mesh = Mesh(geo.GenerateMesh(quad_dominated=True,maxh=0.5)) #Test(mesh=mesh, space=H1, order=2, trace = lambda cf : cf, diffops=["hesse", "Grad"], vb=VOL, set_dual=[True,False], addorder=1) """ return
from ngsolve import * import petsc4py as psc import ngs_petsc as ngp from netgen.meshing import Mesh as NGMesh import sys comm = mpi_world if comm.rank == 0: from netgen.geom2d import unit_square ngm = unit_square.GenerateMesh(maxh=0.05) if comm.size > 1: ngm.Distribute(comm) else: ngm = NGMesh.Receive(comm) mesh = Mesh(ngm) V = H1(mesh, order=1, dirichlet='.*') u, v = V.TnT() a = BilinearForm(V) a += SymbolicBFI(InnerProduct(grad(u), grad(v))) f = LinearForm(V) f += SymbolicLFI(v) f.Assemble() gfu = GridFunction(V) # c = Preconditioner(a, 'bddc') a.Assemble() ngp.Initialize() wrapped_mat = ngp.PETScMatrix(a.mat,
def solve(initial_temperature, end_time, time_step): mesh = Mesh(unit_square.GenerateMesh(maxh=0.1)) Draw(mesh) space = H1(mesh, order=10, dirichlet='bottom|right|top|left') print(space) Draw(initial_temperature, mesh, "initial_temperature") trial_function = space.TrialFunction() test_function = space.TestFunction() diffusion_term = grad(trial_function) * grad(test_function) diffusion = BilinearForm(space) diffusion += diffusion_term * dx mass_term = trial_function * test_function mass = BilinearForm(space) mass += mass_term * dx heat = BilinearForm(space) heat += mass_term * dx + time_step * diffusion_term * dx source_term = 0 * test_function source = LinearForm(space) source += source_term * dx diffusion.Assemble() mass.Assemble() heat.Assemble() source.Assemble() temperature = GridFunction(space, "temperature") temperature.Set(initial_temperature) for i in range(space.ndof): if not space.FreeDofs()[i]: temperature.vec[i] = 0 Draw(temperature) residual = temperature.vec.CreateVector() heat_inverse = heat.mat.Inverse(space.FreeDofs()) subspace_dimension = 5 dt = time_step / subspace_dimension runge_kutta_weights = ImplicitRungeKuttaMethodWeights(10) time = 0 print(f"time={time}") with (TaskManager()): while time < end_time: time += time_step print(f"time={time}") timer = Timer("exponential integrators timer") timer.Start() subspace_basis = [temperature.vec.Copy()] initial_condition_norm = Norm(temperature.vec) subspace_basis_assembling_timer = Timer( "subspace basis assembling") subspace_basis_assembling_timer.Start() for i in range(1, subspace_dimension): residual.data = diffusion.mat * temperature.vec temperature.vec.data -= dt * heat_inverse * residual subspace_basis.append(temperature.vec.Copy()) subspace_basis = orthonormalize(subspace_basis) subspace_basis_assembling_timer.Stop() subspace_matrix_assembling_timer = Timer( "subspace matrix assembling") subspace_matrix_assembling_timer.Start() subspace_diffusion = Matrix(subspace_dimension, subspace_dimension) subspace_mass = Matrix(subspace_dimension, subspace_dimension) for col in range(subspace_dimension): residual.data = diffusion.mat * subspace_basis[col] for row in range(subspace_dimension): subspace_diffusion[row, col] = InnerProduct( subspace_basis[row], residual) residual.data = mass.mat * subspace_basis[col] for row in range(subspace_dimension): subspace_mass[row, col] = InnerProduct(subspace_basis[row], residual) subspace_mass_inverse = Matrix(subspace_dimension, subspace_dimension) subspace_mass.Inverse(subspace_mass_inverse) evolution_matrix = -subspace_mass_inverse * subspace_diffusion subspace_matrix_assembling_timer.Stop() large_timestep_timer = Timer("large timestep") large_timestep_timer.Start() subspace_temperature = Vector(subspace_dimension) subspace_temperature[:] = 0 subspace_temperature[0] = initial_condition_norm next_temperature = linear_implicit_runge_kutta_step( runge_kutta_weights, evolution_matrix, subspace_temperature, time_step) temperature.vec[:] = 0 for i, basis_vector in enumerate(subspace_basis): temperature.vec.data += next_temperature[i] * basis_vector large_timestep_timer.Stop() timer.Stop() Redraw() return (temperature, mesh, time)
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: # mesh = CartSquare(round(1/(maxh*2)),round(1/(maxh))) mesh = CartSquare(2**i, 2**(i + 1)) gfu = SolveHeat(order, eps, mesh, bndcondscale)
from ngsolve.TensorProductTools import * from ngsolve.comp import * from ngsolve import * from netgen.geom2d import unit_square mesh1 = Mesh(SegMesh(20, 0, 1)) mesh2 = Mesh(unit_square.GenerateMesh(maxh=0.15)) tpmesh = Mesh(MakeTensorProductMesh(mesh1, mesh2)) Draw(tpmesh) n = 3 m = 3 fesx = L2(mesh1, order=n) fesy = L2(mesh2, order=m) tpfes = TensorProductFESpace([fesx, fesy]) fes = L2(tpmesh, order=n) u = tpfes.TrialFunction() v = tpfes.TestFunction() vx = v.Operator("gradx") vy = v.Operator("grady") b = CoefficientFunction((ProlongateCoefficientFunction(x - 0.5, 0, tpfes), ProlongateCoefficientFunction(0.5 - x, 1, tpfes), 0)) uin = CoefficientFunction(0.0)
def test_real(): mesh = Mesh(unit_square.GenerateMesh(maxh=0.2)) cf = CoefficientFunction(1 + 2j) assert cf.real(mesh(0.4, 0.4)) == 1 assert cf.imag(mesh(0.2, 0.6)) == 2
def mk_2d_mesh(): return Mesh(unit_square.GenerateMesh(maxh=0.5))
from math import pi ngsglobals.msg_level = 1 # -------------------------------- PARAMETERS --------------------------------- # Space finite element order order = 1 # Time finite element order k_t = 1 # Final simulation time tend = 1.0 # Time step delta_t = 1 / 32 # ----------------------------------- MAIN ------------------------------------ mesh = Mesh(unit_square.GenerateMesh(maxh=0.05, quad_dominated=False)) V = H1(mesh, order=order, dirichlet=".*") tfe = ScalarTimeFE(k_t) st_fes = tfe * V # Fitted heat equation example tnew = 0 told = Parameter(0) t = told + delta_t * tref u_exact = sin(pi * t) * sin(pi * x)**2 * sin(pi * y)**2 coeff_f = u_exact.Diff(t) - (u_exact.Diff(x).Diff(x) + u_exact.Diff(y).Diff(y)) coeff_f = coeff_f.Compile()
help='Do sequential timings') 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
from netgen.geom2d import unit_square from ngsolve import * m = Mesh(unit_square.GenerateMesh(maxh=0.3)) V = H1(m, order=3, dirichlet=[1, 2, 3, 4]) u = V.TrialFunction() v = V.TestFunction() a = BilinearForm(V) a += SymbolicBFI(grad(u) * grad(v) + 5 * u * u * v - 1 * v) u = GridFunction(V) r = u.vec.CreateVector() w = u.vec.CreateVector() for it in range(5): print("Iteration", it) a.Apply(u.vec, r) a.AssembleLinearization(u.vec) w.data = a.mat.Inverse(V.FreeDofs()) * r.data print("|w| =", w.Norm()) u.vec.data -= w Draw(u) input("<press a key>")
def test_integrate_xy(): mesh = Mesh(unit_square.GenerateMesh(maxh=0.2)) intR = Integrate(x * y, mesh) intC = Integrate(1j * x * y, mesh) assert abs(intR - 1. / 4) < 1e-14 assert abs(intC - 1j * 1. / 4) < 1e-14
def test_hidden(): mesh = Mesh(unit_square.GenerateMesh(maxh=0.3)) elim_options = [False, True] bddc_options = [False, True] hidden_options = [False, True] compress_options = [False, True] solutions = {} ndof = {} nze = {} nze_total = {} i = 0 option_tuples = [] for elim_internal in elim_options: for use_bddc in bddc_options: if not elim_internal and use_bddc: continue for use_hidden in hidden_options: for compress in compress_options: current_tuple = (elim_internal, use_bddc, use_hidden, compress) option_tuples.append(current_tuple) for elim_internal, use_bddc, use_hidden, compress in option_tuples: current_tuple = (elim_internal, use_bddc, use_hidden, compress) i += 1 order = 4 fes1 = HDiv(mesh, order=order, discontinuous=True, hide_all_dofs=use_hidden) fes2 = L2(mesh, order=order - 1) fes3 = FacetFESpace(mesh, order=order, dirichlet=[1, 2, 3]) fes = FESpace([fes1, fes2, fes3]) if compress: fes = CompressCompound(fes) sigma, u, uhat = fes.TrialFunction() tau, v, vhat = fes.TestFunction() n = specialcf.normal(mesh.dim) a = BilinearForm(fes, symmetric=False, eliminate_hidden=use_hidden, eliminate_internal=elim_internal) a += SymbolicBFI(sigma * tau + div(sigma) * v + div(tau) * u) a += SymbolicBFI(sigma * n * vhat + tau * n * uhat, element_boundary=True) if use_bddc: c = Preconditioner(type="bddc", bf=a) else: c = Preconditioner(type="direct", bf=a) a.Assemble() f = LinearForm(fes) f += SymbolicLFI(-1 * v) f.Assemble() gfu = GridFunction(fes) BVP(bf=a, lf=f, gf=gfu, pre=c).Do() solutions[current_tuple] = gfu ndof[current_tuple] = fes.ndof nze[current_tuple] = a.mat.nze if (elim_internal): nze_total[ current_tuple] = a.mat.nze + a.harmonic_extension.nze + a.harmonic_extension_trans.nze + a.inner_solve.nze else: nze_total[current_tuple] = a.mat.nze for elim_internal, use_bddc, use_hidden, compress in option_tuples: print("({:1},{:1},{:1},{:1}), nze A(Schur) {:7}".format( elim_internal, use_bddc, use_hidden, compress, nze[(elim_internal, use_bddc, use_hidden, compress)])) for elim_internal, use_bddc, use_hidden, compress in option_tuples: print("({:1},{:1},{:1},{:1}), nze A(Schur) {:7}".format( elim_internal, use_bddc, use_hidden, compress, nze[(elim_internal, use_bddc, use_hidden, compress)])) for elim_internal, use_bddc, use_hidden, compress in option_tuples: print("({:1},{:1},{:1}), nze A(total) {:7}".format( elim_internal, use_bddc, use_hidden, compress, nze_total[(elim_internal, use_bddc, use_hidden, compress)])) for elim_internal, use_bddc, use_hidden, compress in option_tuples: print("({:1},{:1},{:1}), nze A(total) {:7}".format( elim_internal, use_bddc, use_hidden, compress, ndof[(elim_internal, use_bddc, use_hidden, compress)])) for elim_internal, use_bddc, use_hidden, compress in option_tuples: my = solutions[(elim_internal, use_bddc, use_hidden, compress)].components[1].vec diff = my.CreateVector() for elim_internal2, use_bddc2, use_hidden2, compress2 in option_tuples: diff.data = my - solutions[(elim_internal2, use_bddc2, use_hidden2, compress2)].components[1].vec error = Norm(diff) print( "comparing ({:1},{:1},{:1},{:1}) with ({:1},{:1},{:1},{:1}), difference is {}" .format(elim_internal, use_bddc, use_hidden, compress, elim_internal2, use_bddc2, use_hidden2, compress2, error)) assert error < 1e-9
def test_detect_symmetric(): deg = 3 mesh = Mesh(unit_square.GenerateMesh(maxh=0.4)) def dxx(u): return hess(u)[0, 0] def dxy(u): return hess(u)[0, 1] def dyx(u): return hess(u)[1, 0] def dyy(u): return hess(u)[1, 1] def dxxavg(u): return 0.5 * (dxx(u) + dxx(u.Other())) def dxyavg(u): return 0.5 * (dxy(u) + dxy(u.Other())) def dyxavg(u): return 0.5 * (dyx(u) + dyx(u.Other())) def dyyavg(u): return 0.5 * (dyy(u) + dyy(u.Other())) def jumpdn(u): return (grad(u) - grad(u).Other()) * n def hess(u): return u.Operator("hesse") def Lap(u): return dxx(u) + dyy(u) def signfct(a): return a / sqrt(a * a) d2udxx = -pi * pi * sin(pi * x) * sin(pi * y) d2udxy = pi * pi * cos(pi * x) * cos(pi * y) d2udyy = -pi * pi * sin(pi * x) * sin(pi * y) A00 = 2.0 A01 = signfct((x - 0.5) * (y - 0.5)) A11 = 2.0 fsource = A00 * d2udxx + 2 * A01 * d2udxy + A11 * d2udyy fes = H1(mesh, order=deg, dirichlet=[1, 2, 3, 4], autoupdate=True, dgjumps=True) n = specialcf.normal(2) h = specialcf.mesh_size mu = 100 / h def J_h_inner(u, v): return mu * (jumpdn(u) * jumpdn(v)) * dx(bonus_intorder=10, skeleton=True) def B_star_1(u, v): Bstar1 = (dxx(u) * dxx(v) + dyx(u) * dyx(v) + dxy(u) * dxy(v) + dyy(u) * dyy(v)) * dx(bonus_intorder=10) return Bstar1 def B_star_2(u, v): Bstar2 = (dxxavg(u)+dyyavg(u)\ -dxxavg(u)*n[0]*n[0]\ -dxyavg(u)*n[0]*n[1]\ -dyxavg(u)*n[1]*n[0]\ -dyyavg(u)*n[1]*n[1])\ * \ jumpdn(v)\ * dx(skeleton=True)\ +jumpdn(u)*\ (dxxavg(v)+dyyavg(v)\ -dxxavg(v)*n[0]*n[0]\ -dxyavg(v)*n[0]*n[1]\ -dyxavg(v)*n[1]*n[0]\ -dyyavg(v)*n[1]*n[1])\ * dx(skeleton=True) return Bstar2 def B_star(u, v): Bstar = B_star_1(u, v) + B_star_2(u, v) return Bstar def Deltainner(u, v): delt = Lap(u) * Lap(v) * dx(bonus_intorder=10) return delt def B(u, v): B = 0.5 * B_star(u, v) + 0.5 * Deltainner(u, v) return B #renormalisation parameter gamma = (A00 + A11) / (A00**2 + 2 * A01**2 + A11**2) u = fes.TrialFunction() v = fes.TestFunction() # the right hand side f = LinearForm(fes) f += fsource * gamma * Lap(v) * dx # the bilinear-forms with orders changed a1 = BilinearForm(fes, symmetric=False) a1 += B(u, v) - Deltainner( u, v) + gamma * (A00 * dxx(u) + 2 * A01 * dxy(u) + A11 * dyy(u)) * Lap(v) * dx + J_h_inner(u, v) a2 = BilinearForm(fes, symmetric=False) a2 += gamma * (A00 * dxx(u) + 2 * A01 * dxy(u) + A11 * dyy(u)) * Lap(v) * dx + B(u, v) - Deltainner( u, v) + J_h_inner(u, v) a3 = BilinearForm(fes, symmetric=False) a1.Assemble() a2.Assemble() gfu1 = GridFunction(fes, autoupdate=True) gfu2 = GridFunction(fes, autoupdate=True) f.Assemble() gfu1.vec.data = a1.mat.Inverse(fes.FreeDofs()) * f.vec gfu2.vec.data = a2.mat.Inverse(fes.FreeDofs()) * f.vec #### value should be zero but it is not L2err = sqrt(Integrate((gfu1 - gfu2) * (gfu1 - gfu2), mesh)) print(L2err) assert L2err < 1e-13
if __name__ == "__main__": m = 2 eps = 0 steps = 1 acoeff = 1 k = (m - 1) / acoeff fu = CoefficientFunction(pow(k * x + k * y + 0.5, 1 / (m - 1))) A = 5 B = 5 fu = CoefficientFunction(((x - A) * (x - A) / (2 * m * (m + 1) * (B - y)))) nbndc = [CoefficientFunction((x - A) / (m * (m + 1) * (B - y)))] nbnd = "left||right" shift = 0 scale = 1 tscale = 1 order = 4 errorold = 1 for h in range(1, 7): mesh = Mesh( unit_square.GenerateMesh(maxh=1 / 2**h, quad_dominated=False)) usol = SolPorousM(mesh, order, fu, m, eps, steps, nbndc, nbnd, 0, acoeff) error = sqrt(Integrate((fu - usol.components[0])**2, mesh)) rate = log(errorold / error) / log(2) errorold = error print("===== order: ", order, ' error: ', error, ' rate: ', rate) input()
# logistic activation function def σ(x): return 1 / (1 + ng.exp(-x)) # vectorize the logistic function for component-wise application vσ = np.vectorize(σ) # NNet coefficient function u_net = W3.dot(vσ(W2.dot(vσ(Wx.dot(ng.x) + Wy.dot(ng.y) + b1)) + b2)) + b3 # unit square domain #mesh = Mesh(unit_square.GenerateMesh(maxh=0.2)) ngmesh = unit_square.GenerateMesh(maxh=0.2) ngmesh.Refine() #ngmesh.Refine() mesh = ng.Mesh(ngmesh) mesh.ngmesh.SetGeometry(unit_square) ng.Draw(mesh) uₕ = poisson_solve() ΔFEM = uₕ - uexact ΔNET = u_net - uexact FEM_error = ng.sqrt(ng.Integrate(ng.InnerProduct(ΔFEM, ΔFEM), mesh)) NET_error = ng.sqrt(ng.Integrate(ng.InnerProduct(ΔNET, ΔNET), mesh)) print('FEM error = ', FEM_error) print('NET_error = ', NET_error)
from ngsolve import * from netgen.geom2d import unit_square mesh = Mesh (unit_square.GenerateMesh(maxh=0.2)) V = H1(mesh, order=4, dirichlet="left|right|top|bottom") u = V.TrialFunction() a = BilinearForm (V, symmetric=False) a += Variation( (0.05*grad(u)*grad(u) + u*u*u*u - 100*u)*dx ) u = GridFunction (V) u.vec[:] = 0 res = u.vec.CreateVector() w = u.vec.CreateVector() Draw(u,sd=4) for it in range(20): print ("Newton iteration", it) print ("energy = ", a.Energy(u.vec)) a.Apply (u.vec, res) a.AssembleLinearization (u.vec) inv = a.mat.Inverse(V.FreeDofs()) w.data = inv * res print ("w*r =", InnerProduct(w,res))
ngs.ngsglobals.msg_level = 1 demos = [ '2d_triangular', '2d_rectangular', '3d_tetrahedral', '3d_hexahedral' ] example = demos[3] # Choose the demo to run if example[:3] == '2d_': maxr = 5 # max refinement h0 = 0.25 # coarsest mesh size p = 1 # polynomial degree if example[3:] == 'triangular': mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=h0)) elif example[3:] == 'rectangular': mesh = ngs.Mesh( unit_square.GenerateMesh(maxh=h0, quad_dominated=True)) q_zero = 'bottom' # mesh boundary parts where q = 0, mu_zero = 'bottom|right|left' # where mu = 0. x = ngs.x t = ngs.y cwave = 1 f = 2 * pi * pi * sin(pi * x) * cos(2 * pi * t) + pi * pi * sin( pi * x) * sin(pi * t) * sin(pi * t) F = CoefficientFunction((0, f)) exactu = CoefficientFunction( (pi * cos(pi * x) * sin(pi * t) * sin(pi * t),