def test_4(self, presets_load_coefficientfunction_into_gridfunction): """ Check that the coefficientfunction and gridfunction dimensions must agree. Check 2D and 3D. """ mesh_2d, fes_scalar_2d, fes_vector_2d, fes_mixed_2d, mesh_3d, fes_scalar_3d, fes_vector_3d, fes_mixed_3d = presets_load_coefficientfunction_into_gridfunction cfu_scalar = ngs.CoefficientFunction(ngs.x + ngs.y) gfu_mixed_2d = ngs.GridFunction(fes_mixed_2d) cfu_vector_2d = ngs.CoefficientFunction((ngs.x, ngs.y)) gfu_mixed_3d = ngs.GridFunction(fes_mixed_3d) cfu_vector_3d = ngs.CoefficientFunction((ngs.x, ngs.y, ngs.z)) # Check 2D. with pytest.raises(netgen.libngpy._meshing.NgException): coef_dict = {1: cfu_vector_2d} # Vector coefficientfunction but scalar gridfunction. load_coefficientfunction_into_gridfunction(gfu_mixed_2d, coef_dict) with pytest.raises(netgen.libngpy._meshing.NgException): coef_dict = {0: cfu_scalar} # Scalar coefficientfunction but vector gridfunction. load_coefficientfunction_into_gridfunction(gfu_mixed_2d, coef_dict) # Check 3D. with pytest.raises(netgen.libngpy._meshing.NgException): coef_dict = {1: cfu_vector_3d} # Vector coefficientfunction but scalar gridfunction. load_coefficientfunction_into_gridfunction(gfu_mixed_3d, coef_dict) with pytest.raises(netgen.libngpy._meshing.NgException): coef_dict = {0: cfu_scalar} # Scalar coefficientfunction but vector gridfunction. load_coefficientfunction_into_gridfunction(gfu_mixed_3d, coef_dict)
def test_2(self, presets_load_coefficientfunction_into_gridfunction): """ Check that coefficientfunctions can be loaded into different component of a gridfunction correctly. Check 2D and 3D. Also check scalar and vector coefficientfunctions. """ mesh_2d, fes_scalar_2d, fes_vector_2d, fes_mixed_2d, mesh_3d, fes_scalar_3d, fes_vector_3d, fes_mixed_3d = presets_load_coefficientfunction_into_gridfunction cfu_scalar = ngs.CoefficientFunction(ngs.x + ngs.y) gfu_mixed_2d = ngs.GridFunction(fes_mixed_2d) cfu_vector_2d = ngs.CoefficientFunction((ngs.x, ngs.y)) coef_dict_2d = {0: cfu_vector_2d, 1: cfu_scalar} gfu_mixed_3d = ngs.GridFunction(fes_mixed_3d) cfu_vector_3d = ngs.CoefficientFunction((ngs.x, ngs.y, ngs.z)) coef_dict_3d = {0: cfu_vector_3d, 1: cfu_scalar} # Check 2D load_coefficientfunction_into_gridfunction(gfu_mixed_2d, coef_dict_2d) err_scalar_2d = ngs.Integrate((cfu_scalar - gfu_mixed_2d.components[1]) * (cfu_scalar - gfu_mixed_2d.components[1]), mesh_2d) err_vector_2d = ngs.Integrate((cfu_vector_2d - gfu_mixed_2d.components[0]) * (cfu_vector_2d - gfu_mixed_2d.components[0]), mesh_2d) assert math.isclose(err_scalar_2d, 0.0, abs_tol=1e-16) assert math.isclose(err_vector_2d, 0.0, abs_tol=1e-16) # Check 3D load_coefficientfunction_into_gridfunction(gfu_mixed_3d, coef_dict_3d) err_scalar_3d = ngs.Integrate((cfu_scalar - gfu_mixed_3d.components[1]) * (cfu_scalar - gfu_mixed_3d.components[1]), mesh_3d) err_vector_3d = ngs.Integrate((cfu_vector_3d - gfu_mixed_3d.components[0]) * (cfu_vector_3d - gfu_mixed_3d.components[0]), mesh_3d) assert math.isclose(err_scalar_3d, 0.0, abs_tol=1e-16) assert math.isclose(err_vector_3d, 0.0, abs_tol=1e-16)
def getPair(self, fes, s): xr, xi = self.A.createVecs() lam = self.E.getEigenpair(s, xr, xi) vecmap = VectorMapping(fes.ParallelDofs(), fes.FreeDofs()) vr = ngs.GridFunction(fes) vecmap.P2N(xr, vr.vec) vi = ngs.GridFunction(fes) vecmap.P2N(xi, vi.vec) return lam, vr, vi
def getPairs(self, fes): vr = ngs.GridFunction(fes, multidim=self.N) vi = ngs.GridFunction(fes, multidim=self.N) lam = [] for s in range(self.N): xr, xi = self.A.createVecs() lam.append(self.E.getEigenpair(s, xr, xi)) vecmap = VectorMapping(fes.ParallelDofs(), fes.FreeDofs()) vecmap.P2N(xr, vr.vecs[s]) vecmap.P2N(xi, vi.vecs[s]) return lam, vr, vi
def __init__(self, domain, form): assert isinstance(domain, NgsSpace) if isinstance(form, ngs.BilinearForm): assert domain.fes == form.space form.Assemble() mat = form.mat elif isinstance(form, ngs.BaseMatrix): mat = form else: raise TypeError('Invalid type: {}'.format(type(form))) self.mat = mat """The assembled matrix.""" super().__init__(domain, domain, linear=True) self._gfu_in = ngs.GridFunction(domain.fes) self._gfu_out = ngs.GridFunction(domain.fes) self._inverse = None
def Solve(a, f, c, ms=100, tol=1e-12, nocb=True): ngs.ngsglobals.msg_level = 5 gfu = ngs.GridFunction(a.space) with ngs.TaskManager(): a.Assemble() f.Assemble() ngs.ngsglobals.msg_level = 1 c.Test() cb = None if a.space.mesh.comm.rank != 0 or nocb else lambda k, x: print( "it =", k, ", err =", x) cg = ngs.krylovspace.CGSolver(mat=a.mat, pre=c, callback=cb, maxsteps=ms, tol=tol) ngs.mpi_world.Barrier() ts = ngs.mpi_world.WTime() cg.Solve(sol=gfu.vec, rhs=f.vec) ngs.mpi_world.Barrier() ts = ngs.mpi_world.WTime() - ts if ngs.mpi_world.rank == 0: print("---") print("multi-dim ", a.space.dim) print("(vectorial) ndof ", a.space.ndofglobal) print("(scalar) ndof ", a.space.dim * a.space.ndofglobal) print("used nits = ", cg.iterations) print("(vec) dofs / (sec * np) = ", a.space.ndofglobal / (ts * max(ngs.mpi_world.size - 1, 1))) print("(scal) dofs / (sec * np) = ", (a.space.ndofglobal * a.space.dim) / (ts * max(ngs.mpi_world.size - 1, 1))) print("---") assert cg.errors[-1] < tol * cg.errors[0] assert cg.iterations < ms return gfu
def test_h1_real(): """Test h1 amg for real example.""" with ngs.TaskManager(): mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.2)) fes = ngs.H1(mesh, dirichlet=[1, 2, 3], order=1) u = fes.TrialFunction() v = fes.TestFunction() # rhs f = ngs.LinearForm(fes) f += ngs.SymbolicLFI(v) f.Assemble() # lhs a = ngs.BilinearForm(fes, symmetric=True) a += ngs.SymbolicBFI(grad(u) * grad(v)) c = ngs.Preconditioner(a, 'h1amg2') a.Assemble() solver = ngs.CGSolver(mat=a.mat, pre=c.mat) gfu = ngs.GridFunction(fes) gfu.vec.data = solver * f.vec assert_greater(solver.GetSteps(), 0) assert_less_equal(solver.GetSteps(), 4)
def test_parallel(): mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.2)) fes = ngs.L2(mesh, order=5, complex=True) g1 = ngs.GridFunction(fes) g2 = ngs.GridFunction(fes) for order in range(10): functions = [(f(ngs.x + 1j * ngs.y, order)) for f in fs_ng] for f in functions: g1.Set(f) with ngs.TaskManager(): g2.Set(f) error = ngs.Integrate(g1 - g2, mesh) assert error == 0j
def load_bc_gridfunctions(self, bc_dict: Dict, fes: ngs.FESpace, model_components: Dict[str, int]) -> Dict: """ Function to load any saved gridfunctions that should be used to specify BCs. Args: bc_dict: Dict specifying the BCs and their mesh markers for each variable. fes: The finite element space of the model. model_components: Maps between variable names and their component in the finite element space. Returns: bc_dict: The same dict now, where appropriate, holding gridfunctions in place of strings holding the paths to those gridfunctions """ for bc_type in bc_dict.keys(): for var in bc_dict[bc_type].keys(): if var in ['u', 'p']: component = model_components[var] else: # For things like stress, no_backflow, all... component = None for marker, val in bc_dict[bc_type][var].items(): if isinstance(val, str): # Need to load a gridfunction from file. # Check that the file exists. val = self._find_rel_path_for_file(val) if component is None: # Use the full finite element space. gfu_val = ngs.GridFunction(fes) gfu_val.Load(val) else: # Use a component of the finite element space. gfu_val = ngs.GridFunction( fes.components[component]) gfu_val.Load(val) # Replace the value in the BC dictionary. bc_dict[bc_type][var][marker] = gfu_val else: # Already parsed pass return bc_dict
def test_1(self, presets_load_coefficientfunction_into_gridfunction): """ Check that a coefficientfunction can be loaded into a full gridfunction correctly. Check 2D and 3D. """ mesh_2d, fes_scalar_2d, fes_vector_2d, fes_mixed_2d, mesh_3d, fes_scalar_3d, fes_vector_3d, fes_mixed_3d = presets_load_coefficientfunction_into_gridfunction gfu_scalar_2d = ngs.GridFunction(fes_scalar_2d) gfu_scalar_3d = ngs.GridFunction(fes_scalar_3d) cfu_scalar = ngs.CoefficientFunction(ngs.x + ngs.y) coef_dict = {None: cfu_scalar} # Check 2D load_coefficientfunction_into_gridfunction(gfu_scalar_2d, coef_dict) err_2d = ngs.Integrate((cfu_scalar - gfu_scalar_2d) * (cfu_scalar - gfu_scalar_2d), mesh_2d) assert math.isclose(err_2d, 0.0, abs_tol=1e-16) # Check 3D load_coefficientfunction_into_gridfunction(gfu_scalar_3d, coef_dict) err_3d = ngs.Integrate((cfu_scalar - gfu_scalar_3d) * (cfu_scalar - gfu_scalar_3d), mesh_3d) assert math.isclose(err_3d, 0.0, abs_tol=1e-16)
def _l_inf(sol: GridFunction, ref_sol: Union[GridFunction, CoefficientFunction], mesh: Mesh, fes: FESpace) -> float: """ L-infinity norm """ gfu_tmp = ngs.GridFunction(fes) gfu_tmp.Set(sol - ref_sol) # NGSolve has no builtin method for evalutating the L-infinity norm and recommends using numpy arr = gfu_tmp.vec.FV().NumPy() return np.max(np.abs(arr))
def construct_gfu(self) -> ngs.GridFunction: """ Function to construct a solution GridFunction. Returns: ~: A GridFunction initialized on the finite element space of the model """ gfu = ngs.GridFunction(self.fes) return gfu
def test_3(self, presets_load_coefficientfunction_into_gridfunction): """ Check that passing in a coef_dict with multiple keys, one of which is None raises an error. """ mesh_2d, fes_scalar_2d, fes_vector_2d, fes_mixed_2d, mesh_3d, fes_scalar_3d, fes_vector_3d, fes_mixed_3d = presets_load_coefficientfunction_into_gridfunction gfu = ngs.GridFunction(fes_scalar_2d) cfu_1 = ngs.CoefficientFunction(ngs.x + ngs.y) cfu_2 = ngs.CoefficientFunction(ngs.x * ngs.y) coef_dict = {None: cfu_1, 0: cfu_2} with pytest.raises(AssertionError): load_coefficientfunction_into_gridfunction(gfu, coef_dict)
def inital_span(X): # Coefficient funtions in the span. coeffs = (ng.CoefficientFunction([1]), ng.x, ng.y) # The span as a list. span = [ng.GridFunction(X) for k in range(len(coeffs))] # Set the values of each GridFunction. for k in range(len(coeffs)): span[k].Set(coeffs[k]) return span
def rbms(dim, V, rots): if rots: tups = [(1, 0, 0), (0, 1, 0), (y, -x, 1)] else: tups = [(1, 0), (0, 1), (y, -x)] cfs = [ngsolve.CoefficientFunction(x) for x in tups] gf = ngsolve.GridFunction(V) kvecs = [gf.vec.CreateVector() for c in cfs] for vec, cf in zip(kvecs, cfs): gf.Set(cf) vec.data = gf.vec return kvecs
def GetData(self, set_minmax=True): import json d = BuildRenderData(self.mesh, self.cf, self.order, draw_surf=self.draw_surf, draw_vol=self.draw_vol, deformation=self.deformation) if isinstance(self.cf, ngs.GridFunction) and len(self.cf.vecs)>1: # multidim gridfunction - generate data for each component gf = ngs.GridFunction(self.cf.space) dim = len(self.cf.vecs) data = [] for i in range(1,dim): gf.vec.data = self.cf.vecs[i] data.append(BuildRenderData(self.mesh, gf, self.order, draw_surf=self.draw_surf, draw_vol=self.draw_vol, deformation=self.deformation)) d['multidim_data'] = data d['multidim_interpolate'] = self.interpolate_multidim d['multidim_animate'] = self.animate if set_minmax: if self.min is not None: d['funcmin'] = self.min if self.max is not None: d['funcmax'] = self.max d['autoscale'] = self.autoscale if self.clipping is not None: d['clipping'] = True if isinstance(self.clipping, dict): allowed_args = ("x", "y", "z", "dist", "function", "pnt", "vec") if "vec" in self.clipping: vec = self.clipping["vec"] self.clipping["x"] = vec[0] self.clipping["y"] = vec[1] self.clipping["z"] = vec[2] if "pnt" in self.clipping: d['mesh_center'] = list(self.clipping["pnt"]) for name, val in self.clipping.items(): if not (name in allowed_args): raise Exception('Only {} allowed as arguments for clipping!'.format(", ".join(allowed_args))) d['clipping_' + name] = val if self.vectors is not None: d['vectors'] = True if isinstance(self.vectors, dict): for name, val in self.vectors.items(): if not (name in ("grid_size", "offset")): raise Exception('Only "grid_size" and "offset" allowed as arguments for vectors!') d['vectors_' + name] = val return d
def mean_to_zero(gfu: GridFunction, fes: FESpace, mesh: Mesh) -> GridFunction: """ Function to bias a gridfunction so its mean is zero. Args: gfu: The gridfunction to modify (or a component of a gridfunction). fes: The finite element space the gridfunction is defined on. mesh: The mesh the gridfunction is defined on. Returns: gfu_biased: The modified gridfunction. """ avg = mean(gfu, mesh) gfu_biased = ngs.GridFunction(fes) gfu_biased.Set(gfu - avg) return gfu_biased
def linear_combo(v, W): """ Method that multiplies the list v containing the span of our vectors to the matrix W that solved the eigenproblem vAv*W = vBv*W*E, where E is the diagonal matrix of eigenvalues. """ # Create an array of new eigenfunctions. q = [] for k in range(len(v)): q += [ng.GridFunction(v[k].space)] q[k].Set(ng.CoefficientFunction(0)) # Now set the values of each new grid function. for k in range(len(q)): for m in range(len(v)): q[k].vec.data += np.complex(W[m, k]) * v[m].vec return q
def GetData(self, set_minmax=True): import json d = BuildRenderData(self.mesh, self.cf, self.order, draw_surf=self.draw_surf, draw_vol=self.draw_vol, deformation=self.deformation) if isinstance(self.cf, ngs.GridFunction) and len(self.cf.vecs) > 1: # multidim gridfunction - generate data for each component gf = ngs.GridFunction(self.cf.space) dim = len(self.cf.vecs) data = [] for i in range(1, dim): gf.vec.data = self.cf.vecs[i] data.append( BuildRenderData(self.mesh, gf, self.order, draw_surf=self.draw_surf, draw_vol=self.draw_vol, deformation=self.deformation)) d['multidim_data'] = data d['multidim_interpolate'] = self.interpolate_multidim d['multidim_animate'] = self.animate if set_minmax: if self.min is not None: d['funcmin'] = self.min if self.max is not None: d['funcmax'] = self.max d['autoscale'] = self.autoscale return d
def apply_spectral_projector(ng_comm, X, zbas, precs, Bq, w, P_q0): # Create a scratch grid function for this computation. tmp = ng.GridFunction(X) for k in range(len(zbas)): for m in range(len(Bq)): tmp.Set(0.0 + 0.0j) # Run the conjugate gradient method. This step computes the # solution w = (zB - A)^{-1} B*f[m] for each of the m # right-hand-sides f[m]. MyGMRes(A=zbas[k].mat, b=Bq[m], pre=precs[k], freedofs=None, x=tmp.vec, maxsteps=2000, tol=1e-14, innerproduct=None, restart=None, printrates=False) P_q0[m].vec.data += np.complex(w[k]) * tmp.vec
def poisson_solve(): fes = H1(mesh, order=3, dirichlet="left|right|bottom|top") u = fes.TrialFunction() v = fes.TestFunction() f = LinearForm(fes) f += -((4 * x**2 - 2) * ng.exp(-x**2) + (4 * y**2 - 2) * ng.exp(-y**2)) * v * dx a = BilinearForm(fes) a += grad(u) * grad(v) * dx a.Assemble() f.Assemble() uₕ = ng.GridFunction(fes) uₕ.Set(uexact, ng.BND) α = f.vec.CreateVector() α.data = f.vec - a.mat * uₕ.vec uₕ.vec.data += a.mat.Inverse(freedofs=fes.FreeDofs()) * α return uₕ
fes = ngs.H1(mesh, dirichlet=[1, 2, 3], order=1) u = fes.TrialFunction() v = fes.TestFunction() # rhs f = ngs.LinearForm(fes) f += ngs.SymbolicLFI(v) # lhs a = ngs.BilinearForm(fes, symmetric=True) a += ngs.SymbolicBFI(grad(u) * grad(v)) c = ngs.Preconditioner(a, 'h1amg', test=True) gfu = ngs.GridFunction(fes) bvp = ngs.BVP(bf=a, lf=f, gf=gfu, pre=c) while True: fes.Update() gfu.Update() a.Assemble() f.Assemble() bvp.Do() ngs.Draw(gfu, mesh, 'solution') input('Hit enter for refinement') mesh.Refine()
codomain = NgsSpace(fes_codomain) rhs = 10 * ngs.sin(ngs.x) * ngs.sin(ngs.y) op = Coefficient(domain, rhs, codomain=codomain, bc_left=0, bc_right=0, bc_bottom=0, bc_top=0, diffusion=False, reaction=True, dim=2) exact_solution_coeff = ngs.x + 1 gfu_exact_solution = ngs.GridFunction(op.fes_domain) gfu_exact_solution.Set(exact_solution_coeff) exact_solution = gfu_exact_solution.vec.FV().NumPy() exact_data = op(exact_solution) fes_noise = ngs.L2(fes_codomain.mesh, order=1) gfu_noise_order1 = ngs.GridFunction(fes_noise) gfu_noise_order1.vec.FV().NumPy()[:] = 0.0001 * np.random.randn(fes_noise.ndof) gfu_noise = ngs.GridFunction(fes_codomain) gfu_noise.Set(gfu_noise_order1) noise = gfu_noise.vec.FV().NumPy() data = exact_data + noise init = 1 + ngs.x**2 init_gfu = ngs.GridFunction(op.fes_domain)
#pc_opts = { "ngs_amg_reg_rmats" : True } pc_opts = { "ngs_amg_reg_rmats": True, "ngs_amg_rots": False, "mgs_amg_max_levels": 2, #"ngs_amg_aaf" : 0.25, "ngs_amg_max_coarse_size": 20, #"ngs_amg_max_levels" : 4, "ngs_amg_log_level": "extra", "ngs_amg_enable_sp": True, "ngs_amg_sp_max_per_row": 4, "ngs_amg_enable_redist": True, "ngs_amg_first_aaf": 0.025 } gfu = ngsolve.GridFunction(V) a.Assemble() f.Assemble() gfu.vec.data = a.mat.Inverse(V.FreeDofs()) * f.vec #ngsolve.Draw(mesh, deformation = ngsolve.CoefficientFunction((gfu[0], gfu[1], gfu[2])), name="defo") ngsolve.Draw(mesh, deformation=ngsolve.CoefficientFunction((gfu[0], gfu[1])), name="defo") ngsolve.Draw(gfu[2], mesh, name="rot") # for i in range(6): # ngsolve.Draw(gfu[i], mesh, name="comp_"+str(i)) # ngsolve.Draw(gfu, name="sol") # # c = ngsolve.Preconditioner(a, "ngs_amg.elast3d", **pc_opts)
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()
def _copy_data(self): new_impl = ngs.GridFunction(self.impl.space) new_impl.vec.data = self.impl.vec self.impl = new_impl
def __init__(self, domain, g, codomain=None): codomain = codomain or domain self.g = g # self.pts=pts # Define mesh and finite element space # geo=SplineGeometry() # geo.AddCircle((0,0), 1, bc="circle") # ngmesh = geo.GenerateMesh() # ngmesh.Save('ngmesh') # self.mesh=MakeQuadMesh(10) # self.mesh=Mesh(ngmesh) self.fes_domain = domain.fes self.fes_codomain = codomain.fes # Variables for setting of boundary values later # self.ind=[v.point in pts for v in self.mesh.vertices] self.pts = [v.point for v in self.fes_codomain.mesh.vertices] self.ind = [np.linalg.norm(np.array(p)) > 0.95 for p in self.pts] self.pts_bdr = np.array(self.pts)[self.ind] self.fes_in = ngs.H1(self.fes_codomain.mesh, order=1) self.gfu_in = ngs.GridFunction(self.fes_in) # grid functions for later use self.gfu = ngs.GridFunction( self.fes_codomain) # solution, return value of _eval self.gfu_bdr = ngs.GridFunction( self.fes_codomain ) # grid function holding boundary values, g/sigma=du/dn self.gfu_integrator = ngs.GridFunction( self.fes_domain ) # grid function for defining integrator (bilinearform) self.gfu_integrator_codomain = ngs.GridFunction(self.fes_codomain) self.gfu_rhs = ngs.GridFunction( self.fes_codomain ) # grid function for defining right hand side (linearform), f self.gfu_inner_domain = ngs.GridFunction( self.fes_domain ) # grid function for reading in values in derivative self.gfu_inner = ngs.GridFunction( self.fes_codomain ) # grid function for inner computation in derivative and adjoint self.gfu_deriv = ngs.GridFunction( self.fes_codomain) # gridd function return value of derivative self.gfu_toret = ngs.GridFunction( self.fes_domain ) # grid function for returning values in adjoint and derivative self.gfu_dir = ngs.GridFunction( self.fes_domain ) # grid function for solving the dirichlet problem in adjoint self.gfu_error = ngs.GridFunction( self.fes_codomain ) # grid function used in _target to compute the error in forward computation self.gfu_tar = ngs.GridFunction( self.fes_codomain ) # grid function used in _target, holding the arguments self.gfu_adjtoret = ngs.GridFunction(self.fes_domain) self.Number = ngs.NumberSpace(self.fes_codomain.mesh) r, s = self.Number.TnT() u = self.fes_codomain.TrialFunction() # symbolic object v = self.fes_codomain.TestFunction() # symbolic object # Define Bilinearform, will be assembled later self.a = ngs.BilinearForm(self.fes_codomain, symmetric=True) self.a += ngs.SymbolicBFI( ngs.grad(u) * ngs.grad(v) * self.gfu_integrator_codomain) ########new self.a += ngs.SymbolicBFI( u * s + v * r, definedon=self.fes_codomain.mesh.Boundaries("cyc")) self.fes1 = ngs.H1(self.fes_codomain.mesh, order=2, definedon=self.fes_codomain.mesh.Boundaries("cyc")) self.gfu_getbdr = ngs.GridFunction(self.fes1) self.gfu_setbdr = ngs.GridFunction(self.fes_codomain) # Define Linearform, will be assembled later self.f = ngs.LinearForm(self.fes_codomain) self.f += ngs.SymbolicLFI(self.gfu_rhs * v) self.r = self.f.vec.CreateVector() self.b = ngs.LinearForm(self.fes_codomain) self.gfu_b = ngs.GridFunction(self.fes_codomain) self.b += ngs.SymbolicLFI( self.gfu_b * v.Trace(), definedon=self.fes_codomain.mesh.Boundaries("cyc")) self.f_deriv = ngs.LinearForm(self.fes_codomain) self.f_deriv += ngs.SymbolicLFI(self.gfu_rhs * ngs.grad(self.gfu) * ngs.grad(v)) # self.b2=LinearForm(self.fes) # self.b2+=SymbolicLFI(div(v*grad(self.gfu)) super().__init__(domain, codomain)
def __init__(self, domain, g, codomain=None): codomain = codomain or domain self.g = g self.fes_domain = domain.fes self.fes_codomain = codomain.fes self.fes_in = ngs.H1(self.fes_codomain.mesh, order=1) self.gfu_in = ngs.GridFunction(self.fes_in) # grid functions for later use self.gfu = ngs.GridFunction( self.fes_codomain) # solution, return value of _eval # self.gfu_bdr=ngs.GridFunction(self.fes_codomain) #grid function holding boundary values, g/sigma=du/dn self.gfu_bilinearform = ngs.GridFunction( self.fes_domain ) # grid function for defining integrator (bilinearform) self.gfu_bilinearform_codomain = ngs.GridFunction( self.fes_codomain ) # grid function for defining integrator of bilinearform self.gfu_linearform_domain = ngs.GridFunction( self.fes_codomain) # grid function for defining linearform self.gfu_linearform_codomain = ngs.GridFunction(self.fes_domain) self.gfu_deriv_toret = ngs.GridFunction( self.fes_codomain) # grid function: return value of derivative self.gfu_adj = ngs.GridFunction( self.fes_domain) # grid function for inner computation in adjoint self.gfu_adj_toret = ngs.GridFunction( self.fes_domain) # grid function: return value of adjoint self.gfu_b = ngs.GridFunction( self.fes_codomain) # grid function for defining the boundary term u = self.fes_codomain.TrialFunction() # symbolic object v = self.fes_codomain.TestFunction() # symbolic object # Define Bilinearform, will be assembled later self.a = ngs.BilinearForm(self.fes_codomain, symmetric=True) self.a += ngs.SymbolicBFI(-ngs.grad(u) * ngs.grad(v) + u * v * self.gfu_bilinearform_codomain) # Interaction with Trace self.fes_bdr = ngs.H1( self.fes_codomain.mesh, order=self.fes_codomain.globalorder, definedon=self.fes_codomain.mesh.Boundaries("cyc")) self.gfu_getbdr = ngs.GridFunction(self.fes_bdr) self.gfu_setbdr = ngs.GridFunction(self.fes_codomain) # Boundary term self.b = ngs.LinearForm(self.fes_codomain) self.b += ngs.SymbolicLFI( -self.gfu_b * v.Trace(), definedon=self.fes_codomain.mesh.Boundaries("cyc")) # Linearform (only appears in derivative) self.f_deriv = ngs.LinearForm(self.fes_codomain) self.f_deriv += ngs.SymbolicLFI(-self.gfu_linearform_codomain * self.gfu * v) super().__init__(domain, codomain)
def real_zero_vector(self): impl = ngs.GridFunction(self.V) return NGSolveVector(impl)
def __init__(self, domain, rhs, bc_left=None, bc_right=None, bc_top=None, bc_bottom=None, codomain=None, diffusion=True, reaction=False, dim=1): assert dim in (1, 2) assert diffusion or reaction codomain = codomain or domain self.rhs = rhs self.diffusion = diffusion self.reaction = reaction self.dim = domain.fes.mesh.dim bc_left = bc_left or 0 bc_right = bc_right or 0 bc_top = bc_top or 0 bc_bottom = bc_bottom or 0 # Define mesh and finite element space self.fes_domain = domain.fes # self.mesh=self.fes.mesh self.fes_codomain = codomain.fes # if dim==1: # self.mesh = Make1DMesh(meshsize) # self.fes = H1(self.mesh, order=2, dirichlet="left|right") # elif dim==2: # self.mesh = MakeQuadMesh(meshsize) # self.fes = H1(self.mesh, order=2, dirichlet="left|top|right|bottom") # grid functions for later use self.gfu = ngs.GridFunction( self.fes_codomain) # solution, return value of _eval self.gfu_bdr = ngs.GridFunction( self.fes_codomain) # grid function holding boundary values self.gfu_integrator = ngs.GridFunction( self.fes_domain ) # grid function for defining integrator (bilinearform) self.gfu_integrator_codomain = ngs.GridFunction(self.fes_codomain) self.gfu_rhs = ngs.GridFunction( self.fes_codomain ) # grid function for defining right hand side (Linearform) self.gfu_inner_domain = ngs.GridFunction( self.fes_domain ) # grid function for reading in values in derivative self.gfu_inner = ngs.GridFunction( self.fes_codomain ) # grid function for inner computation in derivative and adjoint self.gfu_deriv = ngs.GridFunction( self.fes_codomain) # return value of derivative self.gfu_toret = ngs.GridFunction( self.fes_domain ) # grid function for returning values in adjoint and derivative u = self.fes_codomain.TrialFunction() # symbolic object v = self.fes_codomain.TestFunction() # symbolic object # Define Bilinearform, will be assembled later self.a = ngs.BilinearForm(self.fes_codomain, symmetric=True) if self.diffusion: self.a += ngs.SymbolicBFI( ngs.grad(u) * ngs.grad(v) * self.gfu_integrator_codomain) elif self.reaction: self.a += ngs.SymbolicBFI( ngs.grad(u) * ngs.grad(v) + u * v * self.gfu_integrator_codomain) # Define Linearform, will be assembled later self.f = ngs.LinearForm(self.fes_codomain) self.f += ngs.SymbolicLFI(self.gfu_rhs * v) if diffusion: self.f_deriv = ngs.LinearForm(self.fes_codomain) self.f_deriv += ngs.SymbolicLFI(-self.gfu_rhs * ngs.grad(self.gfu) * ngs.grad(v)) # Precompute Boundary values and boundary valued corrected rhs if self.dim == 1: self.gfu_bdr.Set( [bc_left, bc_right], definedon=self.fes_codomain.mesh.Boundaries("left|right")) elif self.dim == 2: self.gfu_bdr.Set([bc_left, bc_top, bc_right, bc_bottom], definedon=self.fes_codomain.mesh.Boundaries( "left|top|right|bottom")) self.r = self.f.vec.CreateVector() super().__init__(domain, codomain)