コード例 #1
0
def presets_load_coefficientfunction_into_gridfunction():
    # 2D
    mesh_2d = ngs.Mesh(unit_square.GenerateMesh(maxh=0.1))
    fes_scalar_2d = ngs.H1(mesh_2d, order=2)
    fes_vector_2d = ngs.HDiv(mesh_2d, order=2)
    fes_mixed_2d = ngs.FESpace([fes_vector_2d, fes_scalar_2d])

    # 3D
    geo_3d = CSGeometry()
    geo_3d.Add(OrthoBrick(Pnt(-1, 0, 0), Pnt(1, 1, 1)).bc('outer'))
    mesh_3d = ngs.Mesh(geo_3d.GenerateMesh(maxh=0.3))
    fes_scalar_3d = ngs.H1(mesh_3d, order=2)
    fes_vector_3d = ngs.HDiv(mesh_3d, order=2)
    fes_mixed_3d = ngs.FESpace([fes_vector_3d, fes_scalar_3d])

    return mesh_2d, fes_scalar_2d, fes_vector_2d, fes_mixed_2d, mesh_3d, fes_scalar_3d, fes_vector_3d, fes_mixed_3d
コード例 #2
0
ファイル: test_h1.py プロジェクト: bschwb/h1amg
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)
コード例 #3
0
ファイル: amg_utils.py プロジェクト: LukasKogler/NgsAMG
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
コード例 #4
0
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
コード例 #5
0
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
コード例 #6
0
ファイル: amg_utils.py プロジェクト: LukasKogler/NgsAMG
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
コード例 #7
0
k_iso = ng.CoefficientFunction(384.)  # thermal conductivity [W/(m*K)]
alpha = ng.CoefficientFunction(
    3.9e-3)  # coefficient for T-dependent resistivity [1/K]

t_max = 2000.  # time in s
dt = 50.  # time step
num_steps = int(t_max / dt)


# temperature-dependent resistivity
def sigma_T(Temp):
    return ng.CoefficientFunction(1. / (rho_0 * (1. + alpha * (Temp - T_0))))


# declare function space
V = ng.H1(mesh, order=order, dirichlet="left|right")
VT = ng.H1(mesh, order=order, dirichlet="left|right|circle")
print("Number of DOFs: {}".format(V.ndof))

# boundary conditions
# Dirichlet for assigned electric potential
bc_values_pot = {"top": V0, "bottom": f, "circle": 0, "left": V0, "right": f}
bc_cf_pot = ng.CoefficientFunction(
    [bc_values_pot[bc] for bc in mesh.GetBoundaries()])

# Dirichlet for assigned temperature
bc_values_T = {
    "top": T_0,
    "bottom": T_0,
    "circle": T_0,
    "left": T_0,
コード例 #8
0
    def get_DIM_gridfunctions(self, mesh: ngs.Mesh, interp_ord: int):
        """
        Function to get all of the phase fields and masks as gridfunctions. This is either done by loading them from
        files or by constructing the numpy arrays and then converting those into gridfunctions.

        Args:
            mesh: The mesh for the gridfunctions.
            interp_ord: The interpolant order for the finite element space for the gridfunctions.
        """

        if self.load_method == 'file':
            # The phase field and masks have already been created and saved as gridfunctions.
            fes = ngs.H1(mesh, order=interp_ord)

            phi_filename = self.config.get_item(
                ['PHASE FIELDS', 'phi_filename'], str)
            self.phi_gfu = create_and_load_gridfunction_from_file(
                phi_filename, fes)

            if self.multiple_bcs:
                # There are BC masks that must be loaded.
                for marker, filename in self.vertices.items():
                    mask_gfu = create_and_load_gridfunction_from_file(
                        filename, fes)
                    self.mask_gfu_dict[marker] = mask_gfu
            else:
                # One single mask that is just a grid function of ones.
                mask_gfu = ngs.GridFunction(fes)
                mask_gfu.Set(1.0)
                self.mask_gfu_dict['all'] = mask_gfu

            # Construct Grad(phi) and |Grad(phi)|.
            self.grad_phi_gfu = ngs.Grad(self.phi_gfu)
            self.mag_grad_phi_gfu = ngs.Norm(ngs.Grad(self.phi_gfu))

        else:
            # The phase field and masks must be generated as numpy arrays and then converted into gridfunctions.
            # The phase field array has already been generated because it is needed to generate the mesh.
            # Construct the phase field, Grad(phi), and |Grad(phi)|.
            if self.N == self.N_mesh:
                # phi was generated on the simulation mesh, so just load phi into a gridfunction and compute Grad(phi)
                # and |Grad(phi)|.
                self.phi_gfu = numpy_to_NGSolve(self.mesh, interp_ord,
                                                self.phi_arr, self.scale,
                                                self.offset, self.dim)
                self.grad_phi_gfu = ngs.Grad(self.phi_gfu)
                self.mag_grad_phi_gfu = ngs.Norm(ngs.Grad(self.phi_gfu))
            else:
                # phi was generated on a refined mesh, so load it into a refined mesh gridfunction, compute Grad(phi)
                # and |Grad(phi)|, then project all three into gridfunctions defined on the simulation mesh.
                phi_gfu_tmp = numpy_to_NGSolve(self.mesh_refined, interp_ord,
                                               self.phi_arr, self.scale,
                                               self.offset, self.dim)
                grad_phi_gfu_tmp = ngs.Grad(phi_gfu_tmp)
                mag_grad_phi_gfu_tmp = ngs.Norm(ngs.Grad(phi_gfu_tmp))

                # Now project onto the coarse simulation mesh.
                fes = ngs.H1(mesh, order=interp_ord)
                vec_fes = ngs.VectorH1(mesh, order=interp_ord)
                self.phi_gfu = ngs.GridFunction(fes)
                self.grad_phi_gfu = ngs.GridFunction(vec_fes)
                self.mag_grad_phi_gfu = ngs.GridFunction(fes)

                self.phi_gfu.Set(phi_gfu_tmp)
                self.grad_phi_gfu.Set(grad_phi_gfu_tmp)
                self.mag_grad_phi_gfu.Set(mag_grad_phi_gfu_tmp)

            if self.multiple_bcs:
                # There are multiple BC masks that must be generated and loaded.
                for marker, mask_arr in self.mask_arr_dict.items():
                    mask_gfu = numpy_to_NGSolve(mesh, interp_ord, mask_arr,
                                                self.scale, self.offset,
                                                self.dim)
                    self.mask_gfu_dict[marker] = mask_gfu
            else:
                # One single mask that is just a grid function of ones.
                mask_arr = np.ones(tuple([int(n + 1) for n in self.N]))
                mask_gfu = numpy_to_NGSolve(mesh, interp_ord, mask_arr,
                                            self.scale, self.offset, self.dim)
                self.mask_gfu_dict['all'] = mask_gfu

            # Save the gridfunctions if desired.
            save_to_file = self.config.get_item(
                ['PHASE FIELDS', 'save_to_file'], bool)
            if save_to_file:
                self.phi_gfu.Save(self.DIM_dir + '/phi.sol')
                self.ngmesh.Save(self.DIM_dir + '/mesh.vol')

                for marker, gfu in self.mask_gfu_dict.items():
                    # Save the BC masks inside the DIM bc_dir.
                    gfu.Save(self.DIM_dir +
                             '/bc_dir/{}_mask.sol'.format(marker))
コード例 #9
0
from regpy.hilbert import L2
from regpy.discrs.ngsolve import NgsSpace

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(name)-40s :: %(message)s')

meshsize_domain = 100
meshsize_codomain = 100

mesh = Make1DMesh(meshsize_domain)
fes_domain = ngs.L2(mesh, order=2, dirichlet="left|right")
domain = NgsSpace(fes_domain)

mesh = Make1DMesh(meshsize_codomain)
fes_codomain = ngs.H1(mesh, order=2, dirichlet="left|right")
codomain = NgsSpace(fes_codomain)

rhs = 10 * ngs.x**2
op = Coefficient(domain,
                 codomain=codomain,
                 rhs=rhs,
                 bc_left=1,
                 bc_right=1.1,
                 diffusion=False,
                 reaction=True)

N_domain = op.fes_domain.ndof
N_codomain = op.fes_codomain.ndof

exact_solution_coeff = 1 + ngs.x
コード例 #10
0
from regpy.hilbert import L2, Sobolev
from regpy.discrs.ngsolve import NgsSpace

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(name)-40s :: %(message)s')

meshsize_domain = 10
meshsize_codomain = 10

mesh = MakeQuadMesh(meshsize_domain)
fes_domain = ngs.L2(mesh, order=2)
domain = NgsSpace(fes_domain)

mesh = MakeQuadMesh(meshsize_codomain)
fes_codomain = ngs.H1(mesh, order=3, dirichlet="left|top|right|bottom")
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
コード例 #11
0
    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)
コード例 #12
0
"""
A small script that loads the results of sequential and parallel FEAST
using NGSolve.
"""

import ngsolve as ng

if __name__ == '__main__':
    try:
        # Load the mesh from file.
        mesh = ng.Mesh('outputs/mesh.vol')

        # Create our H1 finite element space.
        order = 2
        dirichlet = 'top|right|bottom|left'
        X = ng.H1(mesh, order=order, dirichlet=dirichlet, complex=True)

        # Create an index array for the gridfunctions.
        idx = list(range(0, 3))

        gf_sequential = []
        gf_mpi = []

        middlename = 'gridfunction'

        for k in range(len(idx)):
            # Create two grid functions: One for the sequential solve, and one
            # for the MPI solve.
            sequential_name = 'sequential_' + middlename + '_{0:02d}'
            gf_sequential += [
                ng.GridFunction(X, name=sequential_name.format(idx[k]))
コード例 #13
0
from netgen.csg import *
geo1 = CSGeometry()
geo1.Add(OrthoBrick(Pnt(0, 0, 0), Pnt(1, 1, 1)))
m1 = geo1.GenerateMesh(maxh=0.1)

mesh = ngs.Mesh(m1)

# Next, we make the NGSolve and Bempp function spaces.
#
# The function ``p1_trace`` will extract the trace space from the ngsovle space and create the matrix ``trace_matrix``, which maps between the dofs (degrees of freedom) in NGSolve and Bempp.

# In[4]:

from simple_ngbem import *
ng_space = ngs.H1(mesh, order=1, complex=True)

trace_space, trace_matrix = p1_trace(ng_space)
bempp_space = bempp.api.function_space(trace_space.grid, "DP", 0)

print("FEM dofs: {0}".format(mesh.nv))
print("BEM dofs: {0}".format(bempp_space.global_dof_count))

# We create the boundary operators that we need.

# In[5]:

id_op = bempp.api.operators.boundary.sparse.identity(trace_space, bempp_space,
                                                     bempp_space)
mass = bempp.api.operators.boundary.sparse.identity(bempp_space, bempp_space,
                                                    trace_space)
コード例 #14
0
ファイル: battery.py プロジェクト: bschwb/ngs_lithium_battery
## Model Parameters
battery_capacity =  2 * 1e-3 * 3600 * 1e-8  # A s µm^-2
discharge_current_density = 1 * battery_capacity  # A µm^-2

## Initial values
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,
コード例 #15
0
"""Solve complex equation on a square."""
# pylint: disable=no-member

from ctypes import CDLL

from netgen.geom2d import unit_square

import ngsolve as ngs
from ngsolve import grad

CDLL('libh1amg.so')

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')
コード例 #16
0
for i in range(0, n_elems + 1):
    pnt_x = x_min + length * i / n_elems
    xs.append(pnt_x)
    pnums.append(m.Add(ngm.MeshPoint(ngm.Pnt(pnt_x, 0, 0))))

for i in range(0, n_elems):
    m.Add(ngm.Element1D([pnums[i], pnums[i + 1]], index=1))

m.SetMaterial(1, 'material')

m.Add(ngm.Element0D(pnums[0], index=1))
m.Add(ngm.Element0D(pnums[n_elems], index=2))

## NGSolve
mesh = ngs.Mesh(m)
fes = ngs.H1(mesh, order=1, dirichlet=[1, 2], complex=True)

u = fes.TrialFunction()
v = fes.TestFunction()

## Potentials
### 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
コード例 #17
0
ファイル: battery.py プロジェクト: bschwb/ngs_lithium_battery
def charge_flux_prefactor_anode(concentration):
    """Return prefactor for Butler-Volmer relation in anode

    params: concentration - Lithium concentration
    """
    # TODO: use power empirical constants here instead of sqrt
    solubility_difference = ngs.IfPos(solubility_limit_anode - concentration,
                                      solubility_limit_anode - concentration, 0)
    li_factor = sqrt(solubility_difference) * sqrt(concentration)
    return F * reaction_rate * li_factor


mesh = ngs.Mesh('mesh.vol')

n_lithium_space = ngs.H1(mesh, order=1)
potential_space = ngs.H1(mesh, order=1, dirichlet='anode')
V = ngs.FESpace([n_lithium_space, potential_space])
print(V.ndof)

u, p = V.TrialFunction()
v, q = V.TestFunction()

# Coefficient functions
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"""
コード例 #18
0
        print(k, V.FreeDofs()[k], len(pds.Dof2Proc(k)) > 0)

    if ngsolve.mpi_world.rank == 1:
        hfl = len(hofrees_loc)
        print('hfl:', hfl)
        print('set free:', hofrees_loc[6])
        print('hofrees_loc:', hofrees_loc)
        print('hofrees_ex:', hofrees_ex)
        V.FreeDofs()[10 + 15] = True
        #for k in hofrees_loc[0:1]:
        #    V.FreeDofs()[k] = True

    import sys
    sys.stdout.flush()

    W = ngsolve.H1(mesh, order=order)
    gfbf = ngsolve.GridFunction(W)
    gfbf.vec[:] = 0
    if ngsolve.mpi_world.rank == 1:
        gfbf.vec[10 + 15] = 1

    ngsolve.Draw(mesh, name="mesh")
    ngsolve.Draw(gfbf, mesh, name="bf")

dobft = False
if dobft:
    while True:
        bf_nr = int(0)
        if ngsolve.mpi_world.rank == 0:
            bf_nr = int(input('nr ?'))
            print('got nr', bf_nr)
コード例 #19
0
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
コード例 #20
0
    geo.Append(['line', p1, p2], leftdomain=1, rightdomain=0, bc='dirichlet')
    geo.Append(['line', p2, p3], leftdomain=1, rightdomain=0, bc='dirichlet')
    geo.Append(['line', p3, p4], leftdomain=1, rightdomain=0, bc='dirichlet')
    geo.Append(['line', p4, p1], leftdomain=1, rightdomain=0)

    geo.AddRectangle((0.2, 0.6), (0.8, 0.7), leftdomain=2, rightdomain=1)
    return geo


with ngs.TaskManager():

    square_conductivity = square_conductivity_geo()
    mesh = ngs.Mesh(square_conductivity.GenerateMesh(maxh=0.05))

    fes = ngs.H1(mesh, dirichlet='dirichlet', order=1)

    u = fes.TrialFunction()
    v = fes.TestFunction()

    # rhs
    f = ngs.LinearForm(fes)
    f += ngs.SymbolicLFI(v)

    # lhs
    lam = ngs.DomainConstantCF([1, 1000])
    a = ngs.BilinearForm(fes, symmetric=True)
    a += ngs.SymbolicBFI(lam * grad(u) * grad(v))
    c = ngs.Preconditioner(a, 'h1amg', flags={'test': True, 'levels': 10})

    gfu = ngs.GridFunction(fes)
コード例 #21
0
    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)
コード例 #22
0
    for n in names:
        p = pv.Plotter()
        p.add_mesh(mesh.warp_by_scalar(n), scalars=n)
        panels[n] = p.show(use_panel=True)
    return panels


noiselevel = 0.01

geo = SplineGeometry()
geo.AddRectangle((0.4, 0.45), (0.6, 0.55), leftdomain=0, rightdomain=1)
geo.AddRectangle((0, 0), (1, 1),
                 bcs=["bottom", "right", "top", "left"],
                 leftdomain=1)

domain = NgsSpace(ngs.H1(ngs.Mesh(geo.GenerateMesh(maxh=0.4)), order=1))
codomain = NgsSpace(
    ngs.H1(ngs.Mesh(geo.GenerateMesh(maxh=0.1)),
           order=1,
           dirichlet="left|top|right|bottom"))

cfu_exact_solution = 1 + ngs.x
exact_solution = domain.from_ngs(cfu_exact_solution)

op = Coefficient(domain=domain,
                 codomain=codomain,
                 rhs=10 * ngs.sin(ngs.x) * ngs.sin(ngs.y),
                 bc_left=0,
                 bc_right=0,
                 bc_bottom=0,
                 bc_top=0,
コード例 #23
0
    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()
コード例 #24
0
""" 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
コード例 #25
0
"""Solve simple laplace equation on a square."""
# pylint: disable=no-member

from ctypes import CDLL

import ngsolve as ngs
from ngsolve import grad
from netgen.geom2d import unit_square

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)
コード例 #26
0
import regpy.stoprules as rules
from regpy.operators.ngsolve import ReactionBoundary
from regpy.solvers import HilbertSpaceSetting
from regpy.solvers.landweber import Landweber
from regpy.hilbert import L2, SobolevBoundary
from regpy.discrs.ngsolve import NgsSpace

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s %(levelname)s %(name)-40s :: %(message)s')

geo = SplineGeometry()
geo.AddCircle((0, 0), r=1, bc="cyc", maxh=0.2)
mesh = ngs.Mesh(geo.GenerateMesh())

fes_domain = ngs.H1(mesh, order=2)
domain = NgsSpace(fes_domain)

fes_codomain = ngs.H1(mesh, order=2)
codomain = NgsSpace(fes_codomain)

g = ngs.x**2 * ngs.y
op = ReactionBoundary(domain, g, codomain=codomain)

exact_solution_coeff = ngs.sin(ngs.y) + 2
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)