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 gram(self): u, v = self.discr.fes.TnT() form = ngs.BilinearForm(self.discr.fes, symmetric=True) form += ngs.SymbolicBFI( u.Trace() * v.Trace() + u.Trace().Deriv() * v.Trace().Deriv(), definedon=self.discr.fes.mesh.Boundaries("cyc")) return Matrix(self.discr, form)
def systems_and_preconditioners(mesh, X, z, order=1): # Create a real analogue of our vector space for the wrapper preconditioner. dirichlet = 'top|right|bottom|left' X_real = ng.H1(mesh, order=order, dirichlet=dirichlet, complex=False) # Test and trial functions for the original space. u, v = X.TnT() # Real trial and test functions. ur, vr = X_real.TnT() # Create a real analogue of the bilinear form a. a_real = ng.BilinearForm(X_real) a_real += ng.SymbolicBFI(ng.grad(ur) * ng.grad(vr)) a_real.Assemble() # Initialize petsc prior to conswtructing preconditioners. petsc.Initialize() # Create a bilinear form and a preconditioner for each z. zbas = [] precs = [] for k in range(len(z)): # Create a bilinear form for the given z-value. zba = ng.BilinearForm(X) zba += ng.SymbolicBFI(z[k] * u * v - ng.grad(u) * ng.grad(v)) # Create a preconditioner for the given z-value. mat_convert = petsc.PETScMatrix(a_real.mat, freedofs=X_real.FreeDofs()) real_pc = petsc.PETSc2NGsPrecond(mat=mat_convert, name="real_pc", petsc_options={"pc_type": "gamg"}) prec = WrapperPrec(real_pc) # Assemble the given bilinear form. zba.Assemble() # Tack the bilinear forms and preconditioners onto their respective lists. zbas += [zba] precs += [prec] return zbas, precs
def spaces_and_forms(mesh, order=1): # Create a distributed finite element space. dirichlet = 'top|right|bottom|left' X = ng.H1(mesh, order=order, dirichlet=dirichlet, complex=True) # Create the test and trial functions. u, v = X.TnT() # Create the bilinear form for the left-hand-side. a = ng.BilinearForm(X) a += ng.SymbolicBFI(ng.grad(u) * ng.grad(v)) a.Assemble() # Create the second needed bilinear form as is needed for FEAST. b = ng.BilinearForm(X) b += ng.SymbolicBFI(u * v) b.Assemble() return X, a, b
def SBDF(model: Model, gfu_0: List[ngs.GridFunction], U: List[ProxyFunction], V: List[ProxyFunction], dt: List[ngs.Parameter]) -> Tuple[ngs.BilinearForm, ngs.LinearForm]: """ Third order semi-implicit backwards differencing time integration scheme. This function constructs the final bilinear and linear forms for the time integration scheme by adding the necessary time-dependent terms to the model's stationary terms. The returned bilinear and linear forms have NOT been assembled. Args: model: The model to solve. gfu_0: List of the solutions of previous time steps ordered from most recent to oldest. U: List of trial functions for the model. V: List of test (weighting) functions. dt: List of timestep sizes ordered from most recent to oldest. Returns: a: The final bilinear form (as a ngs.BilinearForm but not assembled). L: The final linear form (as a ngs.LinearForm but not assembled). """ # Separate out the various components of each gridfunction solution to a previous timestep. # gfu_lst = [[component 0, component 1...] at t^n, [component 0, component 1...] at t^n-1, ...] gfu_lst = [] for i in range(len(gfu_0)): if (len(gfu_0[i].components) > 0): gfu_lst.append([ gfu_0[i].components[j] for j in range(len(gfu_0[i].components)) ]) else: gfu_lst.append([gfu_0[i]]) # Construct the bilinear form a = ngs.BilinearForm(model.fes) a += model.construct_bilinear(U, V, dt[0]) # Construct the linear form L = ngs.LinearForm(model.fes) L += 3.0 * model.construct_linear(V, gfu_lst[0], dt[0]) L += -3.0 * model.construct_linear(V, gfu_lst[1], dt[0]) L += model.construct_linear(V, gfu_lst[2], dt[0]) a_dt, L_dt = model.time_derivative_terms(gfu_lst, 'SBDF') # When adding the time discretization term, multiply by the phase field if using the diffuse interface method. if model.DIM: a_dt *= model.DIM_solver.phi_gfu L_dt *= model.DIM_solver.phi_gfu a += a_dt * dx L += L_dt * dx return a, L
def setup_poisson(mesh, alpha=1, beta=0, f=1, diri=".*", order=1, fes_opts=dict(), blf_opts=dict(), lf_opts=dict()): V = ngs.H1(mesh, order=order, dirichlet=diri, **fes_opts) u, v = V.TnT() a = ngs.BilinearForm(V, **blf_opts) a += ngs.SymbolicBFI(alpha * ngs.grad(u) * ngs.grad(v)) if beta != 0: a += ngs.SymbolicBFI(beta * u * v) lf = ngs.LinearForm(V) lf += ngs.SymbolicLFI(f * v) return V, a, lf
def setup_norot_elast(mesh, mu=1, lam=0, f_vol=None, multidim=True, reorder=False, diri=".*", order=1, fes_opts=dict(), blf_opts=dict(), lf_opts=dict()): dim = mesh.dim if multidim: V = ngs.H1(mesh, order=order, dirichlet=diri, **fes_opts, dim=mesh.dim) else: V = ngs.VectorH1(mesh, order=order, dirichlet=diri, **fes_opts) if reorder: raise Exception( "reordered does not work anymore (now ordered by elements)!!") V = ngs.comp.Reorder(V) u, v = V.TnT() sym = lambda X: 0.5 * (X + X.trans) grd = lambda X: ngs.CoefficientFunction(tuple( ngs.grad(X)[i, j] for i in range(dim) for j in range(dim)), dims=(dim, dim)) eps = lambda X: sym(grd(X)) a = ngs.BilinearForm(V, symmetric=False, **blf_opts) a += mu * ngs.InnerProduct(eps(u), eps(v)) * ngs.dx if lam != 0: div = lambda U: sum([ngs.grad(U)[i, i] for i in range(1, dim)], start=ngs.grad(U)[0, 0]) a += lam * div(u) * div(v) * ngs.dx lf = ngs.LinearForm(V) lf += f_vol * v * ngs.dx return V, a, lf
cf_diffusivity = ngs.CoefficientFunction([diffusivity[mat] for mat in mesh.GetMaterials()]) cf_conductivity = ngs.CoefficientFunction([conductivity[mat] for mat in mesh.GetMaterials()]) cf_valence = ngs.CoefficientFunction([valence[mat] for mat in mesh.GetMaterials()]) def material_overpotential_cathode(concentr, pot): """Return material overpotential for cathode Li_yMn2O4 particles""" return pot - open_circuit_manganese(concentr) + ohmic_contact_pot # V def material_overpotential_anode(concentr, pot): """Return material overpotential for Li_xC6 anode""" return pot - open_circuit_carbon(concentr) + ohmic_contact_pot # V mass = ngs.BilinearForm(V) mass += ngs.SymbolicBFI(u * v) a = ngs.BilinearForm(V) a += ngs.SymbolicBFI(-cf_diffusivity * grad(u) * grad(v)) a += ngs.SymbolicBFI(cf_diffusivity * discharge_rate / F * v, ngs.BND, definedon=mesh.Boundaries('anode')) a += ngs.SymbolicBFI(-cf_diffusivity * cf_valence * F / R / temperature * u * grad(p) * grad(v)) # a += ngs.SymbolicBFI(-charge_flux_prefactor_cathode(u) * (alpha_a + alpha_c) # * material_overpotential_cathode(u, p) * cf_diffusivity # * cf_valence * F**2 / R**2 / temperature**2 / conductivity['particle'] * u * v, # ngs.BND, definedon=mesh.Boundaries('particle')) # a += ngs.SymbolicBFI(-charge_flux_prefactor_anode(u) * (alpha_a + alpha_c) # * material_overpotential_anode(u, p) * cf_diffusivity # * cf_valence * F**2 / R**2 / temperature**2 / cf_conductivity * u * v,
def gram(self): u, v = self.discr.fes.TnT() form = ngs.BilinearForm(self.discr.fes, symmetric=True) form += ngs.SymbolicBFI(u * v + ngs.grad(u) * ngs.grad(v)) return Matrix(self.discr, form)
print(mesh.GetMaterials()) print(mesh.GetBoundaries()) fes = ngs.H1(mesh, dirichlet='dirichlet', order=1) print('Dofs:', fes.ndof) u = fes.TrialFunction() v = fes.TestFunction() # rhs f = ngs.LinearForm(fes) f += ngs.SymbolicLFI(x*x*x*x * v) f.Assemble() # lhs a = ngs.BilinearForm(fes, symmetric=False) a += ngs.SymbolicBFI(grad(u) * grad(v) + u * v) c = h1amg.H1AMG(a) 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')
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 __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 setup_rot_elast(mesh, mu=1, lam=0, f_vol=None, multidim=True, reorder=False, diri=".*", order=1, fes_opts=dict(), blf_opts=dict(), lf_opts=dict()): dim = mesh.dim mysum = lambda x: sum(x[1:], x[0]) if dim == 2: to_skew = lambda x: ngs.CoefficientFunction( (0, -x[0], x[0], 0), dims=(2, 2)) else: # to_skew = lambda x : ngs.CoefficientFunction( ( 0 , x[2], -x[1], \ # -x[2], 0 , x[0], \ # x[1], -x[0], 0), dims = (3,3) ) to_skew = lambda x : ngs.CoefficientFunction( ( 0 , -x[2], x[1], \ x[2], 0 , -x[0], \ -x[1], x[0], 0), dims = (3,3) ) if multidim: mdim = dim + ((dim - 1) * dim) // 2 V = ngs.H1(mesh, order=order, dirichlet=diri, **fes_opts, dim=mdim) if reorder: V = ngs.comp.Reorder(V) trial, test = V.TnT() u = ngs.CoefficientFunction(tuple(trial[x] for x in range(dim))) gradu = ngs.CoefficientFunction(tuple( ngs.Grad(trial)[i, j] for i in range(dim) for j in range(dim)), dims=(dim, dim)) divu = mysum([ngs.Grad(trial)[i, i] for i in range(dim)]) w = to_skew([trial[x] for x in range(dim, mdim)]) ut = ngs.CoefficientFunction(tuple(test[x] for x in range(dim))) gradut = ngs.CoefficientFunction(tuple( ngs.Grad(test)[i, j] for i in range(dim) for j in range(dim)), dims=(dim, dim)) divut = mysum([ngs.Grad(test)[i, i] for i in range(dim)]) wt = to_skew([test[x] for x in range(dim, mdim)]) else: Vu = ngs.VectorH1(mesh, order=order, dirichlet=diri, **fes_opts) if reorder == "sep": Vu = ngs.comp.Reorder(Vu) if dim == 3: Vw = Vu else: Vw = ngs.H1(mesh, order=order, dirichlet=diri, **fes_opts) if reorder == "sep": Vw = ngs.comp.Reorder(Vw) V = ngs.FESpace([Vu, Vw]) # print("free pre RO: ", V.FreeDofs()) if reorder is True: V = ngs.comp.Reorder(V) # print("free post RO: ", V.FreeDofs()) (u, w), (ut, wt) = V.TnT() gradu = ngs.Grad(u) divu = mysum([ngs.Grad(u)[i, i] for i in range(dim)]) w = to_skew(w) gradut = ngs.Grad(ut) divut = mysum([ngs.Grad(ut)[i, i] for i in range(dim)]) wt = to_skew(wt) a = ngs.BilinearForm(V, **blf_opts) a += (mu * ngs.InnerProduct(gradu - w, gradut - wt)) * ngs.dx #a += ngs.InnerProduct(w,wt) * ngs.dx #trial, test = V.TnT() #a += 0.1 * ngs.InnerProduct(trial,test) * ngs.dx if lam != 0: a += lam * divu * divut * ngs.dx lf = ngs.LinearForm(V) lf += f_vol * ut * ngs.dx return V, a, lf
initial_concentration = 1e3 * 1e-18 # mol µm^-3 ## Material Properties diffusivity = 2.66e-5 * 1e8 # µm^2 s^-1 with ngs.TaskManager(): mesh = ngs.Mesh('mesh.vol') V = ngs.H1(mesh, order=1) print(V.ndof) u = V.TrialFunction() v = V.TestFunction() mass = ngs.BilinearForm(V) mass += ngs.SymbolicBFI(u * v) mass.Assemble() a = ngs.BilinearForm(V) a += ngs.SymbolicBFI(diffusivity * grad(u) * grad(v)) a.Assemble() f = ngs.LinearForm(V) f += ngs.SymbolicLFI(discharge_current_density / F * v.Trace(), ngs.BND, definedon=mesh.Boundaries('anode')) f.Assemble() # Initial conditions gfu = ngs.GridFunction(V) gfu.Set(ngs.CoefficientFunction(initial_concentration))
def _create_linear_and_bilinear_forms(self) -> None: self.a = ngs.BilinearForm(self.model.fes) self.a += self.model.construct_bilinear(self.U, self.V) self.L = ngs.LinearForm(self.model.fes) self.L += self.model.construct_linear(self.V)
def adaptive_IMEX_pred( model: Model, gfu_0: List[ngs.GridFunction], U: List[ProxyFunction], V: List[ProxyFunction], dt: List[ngs.Parameter]) -> Tuple[ngs.BilinearForm, ngs.LinearForm]: """ Predictor for the adaptive time-stepping IMEX time integration scheme. This function constructs the final bilinear and linear forms for the time integration scheme by adding the necessary time-dependent terms to the model's stationary terms. The returned bilinear and linear forms have NOT been assembled. Args: model: The model to solve. gfu_0: List of the solutions of previous time steps ordered from most recent to oldest. U: List of trial functions for the model. V: List of test (weighting) functions. dt: List of timestep sizes ordered from most recent to oldest. Returns: a: The final bilinear form (as a ngs.BilinearForm but not assembled). L: The final linear form (as a ngs.LinearForm but not assembled). """ # Separate out the various components of each gridfunction solution to a previous timestep. # gfu_lst = [[component 0, component 1...] at t^n, [component 0, component 1...] at t^n-1, ...] gfu_lst = [] for i in range(len(gfu_0)): if (len(gfu_0[i].components) > 0): gfu_lst.append([ gfu_0[i].components[j] for j in range(len(gfu_0[i].components)) ]) else: gfu_lst.append([gfu_0[i]]) # Operators specific to this time integration scheme. w = dt[0] / dt[1] E = model.construct_gfu().components[0] E_expr = (1.0 + w) * gfu_lst[0][0] - w * gfu_lst[1][0] E.Set(E_expr) # Construct the bilinear form a = ngs.BilinearForm(model.fes) a += model.construct_bilinear(U, V, dt[0]) # Construct the linear form L = ngs.LinearForm(model.fes) L += model.construct_linear( V, [gfu_lst[0][0], 0.0], dt[0]) # TODO: Why doesn't using E work? Numerical error? a_dt, L_dt = model.time_derivative_terms(gfu_lst, 'crank nicolson') # When adding the time discretization term, multiply by the phase field if using the diffuse interface method. if model.DIM: a_dt *= model.DIM_solver.phi_gfu L_dt *= model.DIM_solver.phi_gfu a += a_dt * dx L += L_dt * dx return a, L
# We are now ready to create a ``BlockedLinearOperator`` containing all four parts of the discretisation of # $$ # \begin{bmatrix} # \mathsf{A}-k^2 \mathsf{M} & -\mathsf{M}_\Gamma\\ # \tfrac{1}{2}\mathsf{Id}-\mathsf{K} & \mathsf{V} # \end{bmatrix}. # $$ # In[8]: from scipy.sparse.linalg.interface import LinearOperator blocks = [[None, None], [None, None]] trace_op = LinearOperator(trace_matrix.shape, lambda x: trace_matrix * x) blfA = ngs.BilinearForm(ng_space) blfA += ngs.SymbolicBFI(ngs.grad(u) * ngs.grad(v) - k**2 * n**2 * u * v) c = ngs.Preconditioner(blfA, type="direct") blfA.Assemble() blocks[0][0] = NgOperator(blfA) blocks[0][1] = -trace_matrix.T * mass.weak_form().sparse_operator blocks[1][0] = (.5 * id_op - dlp).weak_form() * trace_op blocks[1][1] = slp.weak_form() blocked = bempp.api.BlockedDiscreteOperator(np.array(blocks)) # Next, we solve the system, then split the solution into the parts assosiated with u and λ. For an efficient solve, preconditioning is required.
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)
fun=tangential_trace) e_N_inc = bempp.api.GridFunction(bc_space, dual_space=nc_space, fun=neumann_trace) print(1) f_upper = 1j * k / mu * trace_matrix.T * (Id.weak_form() * e_N_inc.coefficients) print(2) f_lower = (.5 * Id2 + H).weak_form() * e_inc.coefficients print(3) f_0 = np.concatenate([f_upper, f_lower]) # Build BlockedLinearOperator blocks = [[None, None], [None, None]] A = ngs.BilinearForm(fem_space) A += ngs.SymbolicBFI(mu_inv * ngs.curl(tu) * ngs.curl(tv)) A += ngs.SymbolicBFI(-omega**2 * epsilon * tu * tv) A.Assemble() blocks[0][0] = ngbem.NgOperator(A, isComplex=True) print("done assembling fem") blocks[0][1] = -1j * k / mu * trace_op_adj * Id.weak_form() blocks[1][0] = (.5 * Id2 + H).weak_form() * trace_op blocks[1][1] = E.weak_form() precond_blocks = [[None, None], [None, None]] precond_blocks[0][0] = np.identity(fem_size)
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)
vT = VT.TestFunction() # Time-stepping t = 0 # write initial temperature datafile.write("%f\t%f\n" % (t, T_n(mesh(0., 0.25)))) psi = ng.GridFunction(V, "pot") # solution for potential psi.Set(bc_cf_pot, ng.BND) T_n1 = ng.GridFunction(VT, "T") # solution for T T_n1.Set(bc_cf_T, ng.BND) ng.Draw(psi) ng.Draw(T_n1) # weak forms # potential a = ng.BilinearForm(V) a += sigma_T(T_n) * ng.grad(psi_T) * ng.grad(v) * ng.dx L = ng.LinearForm(V) L += f * v * ng.dx # keep in mind: f=0 # temperature a_1 = ng.BilinearForm(VT) a_1 += (rho * C_p * T_n1_T * vT * ng.dx + k_iso * dt * ng.grad(T_n1_T) * ng.grad(vT) * ng.dx) L_1 = ng.LinearForm(VT) L_1 += (rho * C_p * T_n + dt * sigma_T(T_n) * (ng.grad(psi) * ng.grad(psi))) * v * ng.dx for n in range(num_steps): # assemble EM problem
CDLL('libh1amg.so') 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) # 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()
### Potential barrier barrier_w = 2 barrier_h = 1 potential = ngs.CoefficientFunction( ngs.IfPos(x, barrier_h, 0) - ngs.IfPos(x - barrier_w, barrier_h, 0)) ### Square potential # potential = ngs.CoefficientFunction(1/2*x*x-10) ### Zero potential # potential = ngs.CoefficientFunction(0) gf_potential = ngs.GridFunction(fes) gf_potential.Set(potential) a = ngs.BilinearForm(fes) a += ngs.SymbolicBFI(1 / 2 * grad(u) * grad(v) + potential * u * v) a.Assemble() m = ngs.BilinearForm(fes) m += ngs.SymbolicBFI(1j * u * v) m.Assemble() ## Initial condition ### Gaussian wave packet delta_x = 2 x0 = -20 kx = 2 wave_packet = ngs.CoefficientFunction( exp(1j * (kx * x)) * exp(-((x - x0)**2) / 4 / delta_x**2))