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 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 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 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 __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, 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)
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, # ngs.BND, definedon=mesh.Boundaries('anode'))
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)
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)) ### Heaviside function
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 inv = a.mat.Inverse(freedofs) w = gf_psi.vec.CreateVector()
# $$ # \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. # In[9]:
## 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))
with ngs.TaskManager(): mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.15)) fes = ngs.H1(mesh, dirichlet=[1, 2, 3], order=1, complex=True) 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) + 1j * u * v) c = ngs.Preconditioner(a, 'h1amg2') # c = ngs.Preconditioner(a, 'direct') 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()
""" Simulate the time-dependent Schrödinger Equation""" import ngsolve as ngs from ngsolve import exp, x, y, grad from netgen.geom2d import unit_square mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.005)) fes = ngs.H1(mesh, order=1, dirichlet=[1,2,3,4], complex=True) u = fes.TrialFunction() v = fes.TestFunction() a = ngs.BilinearForm(fes) a += ngs.SymbolicBFI(1/2 * grad(u) * grad(v)) a.Assemble() m = ngs.BilinearForm(fes) m += ngs.SymbolicBFI(1j * u * v) m.Assemble() ## Initial condition delta_x = 0.05 x0 = 0.2 y0 = 0.5 kx = 0 ky = 0 wave_packet = ngs.CoefficientFunction( exp(1j * (kx * x + ky * y)) * exp(-((x-x0)**2+(y-y0)**2)/4/delta_x**2))
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)
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() ngs.Draw(gfu, mesh, 'solution')
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) #ngbem.NgOperator(fem_prec,A);