def create_mesh(ng_comm, maxh=0.2, nrefinements=0):
    sequential = ng_comm.size == 1
    output_directory = 'outputs'

    if sequential:
        path_to_mesh = Path(output_directory + '/mesh.vol')

        if path_to_mesh.exists():
            print(
                'Sequential: Loading mesh from {0}.'.format(output_directory))
            mesh = ng.Mesh(output_directory + '/mesh.vol')
        else:
            print('Sequential: Creating and saving mesh to {0}.'.format(
                output_directory))
            ngmesh = unit_square.GenerateMesh(maxh=maxh)

            for k in range(nrefinements):
                ngmesh.Refine()

            ngmesh.Save(output_directory + '/mesh.vol')

            mesh = ng.Mesh(ngmesh)
    else:
        if ng_comm.rank == 0:
            print('Rank {0}: Loading mesh from {1}.'.format(
                ng_comm.rank, output_directory))

        mesh = ng.Mesh(output_directory + '/mesh.vol')

    return mesh
Example #2
0
 def loadMeshFile():
     filename, filt = QtWidgets.QFileDialog.getOpenFileName(caption = "Load Mesh",
                                                            filter = "Netgen mesh file (*.vol *.vol.gz);; Neutral format (*.mesh *.emt);; Surface format (*.surf);; Universal format (*.unv);; Olaf format (*.emt);; TET format (*.tet);; STL format (*.stl *.stlb);; Pro/ENGINEER neutral format (*.fnf)")
     if filename:
         if filename.endswith(".vol") or filename.endswith(".vol.gz"):
             mesh = ngsolve.Mesh(filename)
         else:
             from netgen.meshing import ImportMesh
             mesh = ngsolve.Mesh(ImportMesh(filename))
         ngsolve.Draw(mesh)
         if not self._flags.noConsole:
             self.console.pushVariables({"mesh" : mesh})
Example #3
0
def load_mesh(config: ConfigParser) -> Mesh:
    """
    Loads an NGSolve mesh from a .sol file whose file path is specified in the given config file.

    Args:
        config: A ConfigParser object containing the information from the config file.

    Returns:
        mesh: The NGSolve mesh pointed to in the config file.
    """

    assert type(config) is ConfigParser

    try:
        mesh_filename = config['MESH']['filename']
    except:
        raise ValueError(
            'No default available for MESH, filename. Please specify a value in the config file.'
        )

    # Check that the file exists.
    if not os.path.isfile(mesh_filename):
        raise FileNotFoundError(
            'The given mesh file \"{}\" does not exist.'.format(mesh_filename))

    # Mesh can be a Netgen mesh or a GMSH mesh.
    if mesh_filename.endswith('.msh'):
        ngmesh = ReadGmsh(mesh_filename)
        mesh = ngs.Mesh(ngmesh)
    elif mesh_filename.endswith('.vol'):
        ngmesh = ngmsh.Mesh()
        ngmesh.Load(mesh_filename)

        mesh = ngs.Mesh(ngmesh)
    else:
        raise TypeError(
            'Only .vol (Netgen) and .msh (GMSH) meshes can be used.'
            'Your specified filename was \"{}\"'.format(mesh_filename))

    # Suppressing the warning about using the default value for curved_elements.
    curved_elements = config.get_item(['MESH', 'curved_elements'],
                                      bool,
                                      quiet=True)
    if curved_elements:
        interp_ord = config.get_item(
            ['FINITE ELEMENT SPACE', 'interpolant_order'], int)
        mesh.Curve(interp_ord)

    return mesh
Example #4
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
Example #5
0
    def ngsolve_vector_array_factory(length, dim, seed):

        if dim not in NGSOLVE_spaces:
            mesh = ngmsh.Mesh(dim=1)
            if dim > 0:
                pids = []
                for i in range(dim + 1):
                    pids.append(
                        mesh.Add(ngmsh.MeshPoint(ngmsh.Pnt(i / dim, 0, 0))))
                for i in range(dim):
                    mesh.Add(ngmsh.Element1D([pids[i], pids[i + 1]], index=1))

            NGSOLVE_spaces[dim] = NGSolveVectorSpace(
                ngs.L2(ngs.Mesh(mesh), order=0))

        U = NGSOLVE_spaces[dim].zeros(length)
        np.random.seed(seed)
        for v, a in zip(U._list, np.random.random((length, dim))):
            v.to_numpy()[:] = a
        if np.random.randint(2):
            UU = NGSOLVE_spaces[dim].zeros(length)
            for v, a in zip(UU._list, np.random.random((length, dim))):
                v.real_part.to_numpy()[:] = a
            for u, uu in zip(U._list, UU._list):
                u.imag_part = uu.real_part
        return U
Example #6
0
    def _generate_DIM_mesh(self) -> None:
        """
        Function to get the nonconformal mesh. This mesh is a simple rectangle or rectangular prism, is constructed of
        quadrilateral/hexahedral elements and has exterior boundaries "left", "right", "top", "bottom" (and
        "front" and "back" for 3D). See get_Netgen_nonconformal in mesh_helpers for more details.
        """

        self.ngmesh = mesh_helpers.get_Netgen_nonconformal(
            self.N_mesh, self.scale, self.offset, self.dim)
        self.mesh = ngs.Mesh(self.ngmesh)

        # Also create a refined mesh to calculate Grad(phi) and |Grad(phi)| on before projecting onto the coarse
        # simulation mesh.
        self.ngmesh_refined = mesh_helpers.get_Netgen_nonconformal(
            self.N, self.scale, self.offset, self.dim)
        self.mesh_refined = ngs.Mesh(self.ngmesh_refined)
Example #7
0
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)
Example #8
0
def Hex():
    m = Mesh()
    m.dim = 3
    pnums = []
    pnums.append (m.Add (MeshPoint (Pnt(0,0,0))))
    pnums.append (m.Add (MeshPoint (Pnt(1,0,0))))
    pnums.append (m.Add (MeshPoint (Pnt(1,1,0))))
    pnums.append (m.Add (MeshPoint (Pnt(0,1,0))))
    pnums.append (m.Add (MeshPoint (Pnt(0,0,1))))
    pnums.append (m.Add (MeshPoint (Pnt(1,0,1))))
    pnums.append (m.Add (MeshPoint (Pnt(1,1,1))))
    pnums.append (m.Add (MeshPoint (Pnt(0,1,1))))


    for i in range(1,7):
        m.Add (FaceDescriptor(surfnr=i,domin=1,bc=i))
        m.SetBCName(i, str(i))
    m.SetMaterial(1, "mat")

    m.Add (Element2D (1,[pnums[0],pnums[1], pnums[2], pnums[3]]))
    m.Add (Element2D (2,[pnums[0],pnums[1], pnums[5], pnums[4]]))
    m.Add (Element2D (3,[pnums[1],pnums[2], pnums[6], pnums[5]]))
    m.Add (Element2D (4,[pnums[2],pnums[3], pnums[7], pnums[6]]))
    m.Add (Element2D (5,[pnums[3],pnums[0], pnums[4], pnums[7]]))
    m.Add (Element2D (6,[pnums[4],pnums[5], pnums[6], pnums[7]]))

    m.Add (Element3D (1,pnums))
    return ngsolve.Mesh(m)
Example #9
0
def domain2_mesh_2d():
    import netgen.geom2d as g2d
    import ngsolve as ngs
    geo = g2d.SplineGeometry()
    geo.AddRectangle((-2, -2), (2, 2))
    geo.AddRectangle((-1, -1), (1, 1), leftdomain=2, rightdomain=1)
    geo.SetMaterial(1, "outer")
    geo.SetMaterial(2, "inner")
    return ngs.Mesh(geo.GenerateMesh(maxh=0.5))
Example #10
0
def test_code_generation():
    mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.2))
    for order in range(10):
        functions = [f(ngs.x + 1j * ngs.y, order) for f in fs_ng]

        for f in functions:
            f_err = f - f.Compile(True, wait=True)
            f_err = f_err * ngs.Conj(f_err)
            error = ngs.Integrate(f_err, mesh)
            assert abs(error) < 1e-13
Example #11
0
 def _create_ngsolve_space(dim):
     if dim not in _NGSOLVE_spaces:
         mesh = ngmsh.Mesh(dim=1)
         if dim > 0:
             pids = []
             for i in range(dim + 1):
                 pids.append(mesh.Add(ngmsh.MeshPoint(ngmsh.Pnt(i / dim, 0, 0))))
             for i in range(dim):
                 mesh.Add(ngmsh.Element1D([pids[i], pids[i + 1]], index=1))
         _NGSOLVE_spaces[dim] = NGSolveVectorSpace(ngs.L2(ngs.Mesh(mesh), order=0))
     return _NGSOLVE_spaces[dim]
Example #12
0
def test_evaluate():
    from netgen.geom2d import unit_square
    import ngsolve as ngs
    import numpy as np
    mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.2))
    pnts = np.linspace(0.1, 0.9, 9)
    cf = ngs.CoefficientFunction((ngs.x, ngs.y))
    cf2 = ngs.CoefficientFunction((ngs.y, ngs.x * 1J))
    mips = mesh(pnts, 0.5)
    vals = cf(mips)
    vals2 = cf2(mips)
    assert np.linalg.norm(vals - np.array(list(zip(pnts, [0.5] * 10)))) < 1e-10
    assert np.linalg.norm(
        vals2 - np.array(list(zip([0.5 + 0J] * 10, pnts * 1J)))) < 1e-10
    assert ngs.x(mesh(0.5, 0.5)) - 0.5 < 1e-10
Example #13
0
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
Example #14
0
def test_bessel():
    mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.2))
    for order in range(10):
        functions = [(f1(ngs.x + 1j * ngs.y, order), f2)
                     for f1, f2 in zip(fs_ng, fs_py)]

        for f_ng, f_py in functions:
            for x in numpy.linspace(0.1, 0.9, 20):
                for y in numpy.linspace(0.1, 0.9, 20):
                    z = x + 1j * y
                    v1 = f_ng(mesh(x, y))
                    v2 = f_py(order, z)
                    error = abs(f_ng(mesh(x, y)) - f_py(order, z))
                    if abs(v2) > 1:
                        error = abs(error / v2)
                    assert error < 1e-13
Example #15
0
def test_errfns():
    efng = [ng_sp.erf, ng_sp.erfc, ng_sp.wofz, ng_sp.erfcx, ng_sp.erfi]
    efsc = [sp.erf, sp.erfc, sp.wofz, sp.erfcx, sp.erfi]

    mesh = ngs.Mesh(unit_square.GenerateMesh(maxh=0.2))
    functions = [(f1(ngs.x + 1j*ngs.y), f2)
                 for f1, f2 in zip(efng, efsc)]

    for f_ng, f_py in functions:
        for x in numpy.linspace(0.1, 0.9, 20):
            for y in numpy.linspace(0.1, 0.9, 20):
                v1 = f_ng(mesh(x, y))
                v2 = f_py(x+1j*y)
                error = abs(v1 - v2)
                if abs(v2) > 1:
                    error = abs(error/v2)
                assert error < 1e-13
Example #16
0
def Make1DMesh(n, mapping=None, periodic=False):
    """
    Generate an equidistant 1D mesh with N cells

    Parameters
    ----------
    n : int
      Number of cells.

    mapping: lamda
      Mapping to transform the generated points. If None, the identity mapping is used.

    periodic: bool
      If True, the endpoints are identified to generate a periodic mesh.

    Returns
    -------
    (ngsolve.mesh)
      Returns generated 1D NGSolve mesh

    """
    mesh = Mesh(dim=1)
    pids = []
    for i in range(n + 1):
        x = i / n
        if mapping:
            x = mapping(x)
        pids.append(mesh.Add(MeshPoint(Pnt(x, 0, 0))))

    idx_inner = mesh.AddRegion("dom", dim=1)
    idx_left = mesh.AddRegion("left", dim=0)
    idx_right = mesh.AddRegion("right", dim=0)

    for i in range(n):
        mesh.Add(Element1D([pids[i], pids[i + 1]], index=idx_inner))
    mesh.Add(Element0D(pids[0], index=idx_left))
    mesh.Add(Element0D(pids[n], index=idx_right))
    if periodic:
        mesh.AddPointIdentification(pids[0], pids[n], 1, 2)
    ngsmesh = ngsolve.Mesh(mesh)
    return ngsmesh
Example #17
0
def MakeStructured2DMesh(quads=True,
                         nx=10,
                         ny=10,
                         secondorder=False,
                         periodic_x=False,
                         periodic_y=False,
                         mapping=None):
    """
    Generate a structured 2D mesh

    Parameters
    ----------
    quads : bool
      If True, a quadrilateral mesh is generated. If False, the quads are split to triangles.

    nx : int
      Number of cells in x-direction.

    ny : int
      Number of cells in y-direction.

    periodic_x: bool
      If True, the left and right boundaries are identified to generate a periodic mesh in x-direction.

    periodic_y: bool
      If True, the top and bottom boundaries are identified to generate a periodic mesh in y-direction.

    mapping: lamda
      Mapping to transform the generated points. If None, the identity mapping is used.
    

    Returns
    -------
    (ngsolve.mesh)
      Returns generated 2D NGSolve mesh

    """
    mesh = Mesh()
    mesh.dim = 2

    pids = []
    if periodic_y:
        slavei = []
        masteri = []
    if periodic_x:
        slavej = []
        masterj = []
    for i in range(ny + 1):
        for j in range(nx + 1):
            x, y = j / nx, i / ny
            # if mapping:
            #    x,y = mapping(x,y)
            pids.append(mesh.Add(MeshPoint(Pnt(x, y, 0))))
            if periodic_y:
                if i == 0:
                    slavei.append(pids[-1])
                if i == ny:
                    masteri.append(pids[-1])
            if periodic_x:
                if j == 0:
                    slavej.append(pids[-1])
                if j == nx:
                    masterj.append(pids[-1])
    if periodic_y:
        for i in range(len(slavei)):
            mesh.AddPointIdentification(masteri[i],
                                        slavei[i],
                                        identnr=1,
                                        type=2)
    if periodic_x:
        for j in range(len(slavej)):
            mesh.AddPointIdentification(masterj[j],
                                        slavej[j],
                                        identnr=2,
                                        type=2)

    mesh.Add(FaceDescriptor(surfnr=1, domin=1, bc=1))

    for i in range(ny):
        for j in range(nx):
            base = i * (nx + 1) + j
            if quads:
                pnum = [base, base + 1, base + nx + 2, base + nx + 1]
                elpids = [pids[p] for p in pnum]
                el = Element2D(1, elpids)
                if not mapping:
                    el.curved = False
                mesh.Add(el)
            else:
                pnum1 = [base, base + 1, base + nx + 1]
                pnum2 = [base + 1, base + nx + 2, base + nx + 1]
                elpids1 = [pids[p] for p in pnum1]
                elpids2 = [pids[p] for p in pnum2]
                mesh.Add(Element2D(1, elpids1))
                mesh.Add(Element2D(1, elpids2))

    for i in range(nx):
        mesh.Add(Element1D([pids[i], pids[i + 1]], index=1))
    for i in range(ny):
        mesh.Add(
            Element1D([pids[i * (nx + 1) + nx], pids[(i + 1) * (nx + 1) + nx]],
                      index=2))
    for i in range(nx):
        mesh.Add(
            Element1D([pids[ny * (nx + 1) + i + 1], pids[ny * (nx + 1) + i]],
                      index=3))
    for i in range(ny):
        mesh.Add(
            Element1D([pids[(i + 1) * (nx + 1)], pids[i * (nx + 1)]], index=4))

    mesh.SetBCName(0, "bottom")
    mesh.SetBCName(1, "right")
    mesh.SetBCName(2, "top")
    mesh.SetBCName(3, "left")

    mesh.Compress()

    if secondorder:
        mesh.SecondOrder()

    if mapping:
        for p in mesh.Points():
            x, y, z = p.p
            x, y = mapping(x, y)
            p[0] = x
            p[1] = y

    ngsmesh = ngsolve.Mesh(mesh)
    return ngsmesh
Example #18
0
def MakeStructured3DMesh(hexes=True,
                         nx=10,
                         ny=None,
                         nz=None,
                         secondorder=False,
                         periodic_x=False,
                         periodic_y=False,
                         periodic_z=False,
                         mapping=None,
                         cuboid_mapping=False):
    """
    Generate a structured quadrilateral 2D mesh

    Parameters
    ----------
    hexes: bool
      If True, a mesh consisting of hexahedra is generated.

    nx : int
      Number of cells in x-direction.

    ny : int
      Number of cells in y-direction.

    nz : int
      Number of cells in z-direction.

    periodic_x: bool
      If True, the left and right boundaries are identified to generate a periodic mesh in x-direction.

    periodic_y: bool
      If True, the top and bottom boundaries are identified to generate a periodic mesh in y-direction.

    periodic_z: bool
      If True, the top and bottom boundaries are identified to generate a periodic mesh in z-direction.

    mapping: lambda
      Mapping to transform the generated points. If None, the identity mapping is used.
    
    cuboid_mapping: bool
      If True, a straight geometry is assumed.


    Returns
    -------
    (ngsolve.mesh)
      Returns generated 3D NGSolve mesh

    """
    if nz == None:
        if ny == None:
            nz = nx
        else:
            raise (
                "MakeStructured3DMesh: No default value for nz if nx and ny are provided"
            )
    if ny == None:
        ny = nx

    netmesh = Mesh()
    netmesh.dim = 3

    if cuboid_mapping:
        P1 = (0, 0, 0)
        P2 = (1, 1, 1)
        if mapping:
            P1 = mapping(*P1)
            P2 = mapping(*P2)
        cube = OrthoBrick(Pnt(P1[0], P1[1], P1[2]), Pnt(P2[0], P2[1],
                                                        P2[2])).bc(1)
        geom = CSGeometry()
        geom.Add(cube)
        netmesh.SetGeometry(geom)

    pids = []
    if periodic_x:
        slavei = []
        masteri = []
    if periodic_y:
        slavej = []
        masterj = []
    if periodic_z:
        slavek = []
        masterk = []
    for i in range(nx + 1):
        for j in range(ny + 1):
            for k in range(nz + 1):
                # x,y,z = mapping(i / nx, j / ny, k / nz)
                x, y, z = i / nx, j / ny, k / nz
                # if mapping:
                #   x,y,z = mapping(x,y,z)
                pids.append(netmesh.Add(MeshPoint(Pnt(x, y, z))))
                if periodic_x:
                    if i == 0:
                        slavei.append(pids[-1])
                    if i == nx:
                        masteri.append(pids[-1])
                if periodic_y:
                    if j == 0:
                        slavej.append(pids[-1])
                    if j == ny:
                        masterj.append(pids[-1])
                if periodic_z:
                    if k == 0:
                        slavek.append(pids[-1])
                    if k == nz:
                        masterk.append(pids[-1])
    if periodic_x:
        for i in range(len(slavei)):
            netmesh.AddPointIdentification(masteri[i],
                                           slavei[i],
                                           identnr=1,
                                           type=2)
    if periodic_y:
        for j in range(len(slavej)):
            netmesh.AddPointIdentification(masterj[j],
                                           slavej[j],
                                           identnr=2,
                                           type=2)
    if periodic_z:
        for k in range(len(slavek)):
            netmesh.AddPointIdentification(masterk[k],
                                           slavek[k],
                                           identnr=3,
                                           type=2)

    for i in range(nx):
        for j in range(ny):
            for k in range(nz):
                base = i * (ny + 1) * (nz + 1) + j * (nz + 1) + k
                baseup = base + (ny + 1) * (nz + 1)
                pnum = [
                    base, base + 1, base + (nz + 1) + 1, base + (nz + 1),
                    baseup, baseup + 1, baseup + (nz + 1) + 1,
                    baseup + (nz + 1)
                ]
                if hexes:
                    elpids = [pids[p] for p in pnum]
                    el = Element3D(1, elpids)
                    if not mapping:
                        el.curved = False
                    netmesh.Add(el)
                else:
                    #  a poor mans kuhn triangulation of a cube
                    for qarr in [[0, 4, 5, 6], [0, 6, 7, 4], [0, 3, 7, 6],
                                 [0, 1, 6, 5], [0, 1, 2, 6], [0, 3, 6, 2]]:
                        elpids = [pids[p] for p in [pnum[q] for q in qarr]]
                        netmesh.Add(Element3D(1, elpids))

    def AddSurfEls(p1, dxi, nxi, deta, neta, facenr):
        def add_seg(i, j, os):
            base = p1 + i * dxi + j * deta
            pnum = [base, base + os]
            elpids = [pids[p] for p in pnum]
            netmesh.Add(Element1D(elpids, index=facenr))

        for i in range(nxi):
            for j in [0, neta]:
                add_seg(i, j, dxi)
        for i in [0, nxi]:
            for j in range(neta):
                add_seg(i, j, deta)
        for i in range(nxi):
            for j in range(neta):
                base = p1 + i * dxi + j * deta
                pnum = [base, base + dxi, base + dxi + deta, base + deta]
                if hexes:
                    elpids = [pids[p] for p in pnum]
                    netmesh.Add(Element2D(facenr, elpids))
                else:
                    qarrs = [[0, 1, 2], [0, 2, 3]]
                    for qarr in qarrs:
                        elpids = [pids[p] for p in [pnum[q] for q in qarr]]
                        netmesh.Add(Element2D(facenr, elpids))

    #order is important!
    netmesh.Add(FaceDescriptor(surfnr=4, domin=1, bc=1))
    netmesh.Add(FaceDescriptor(surfnr=2, domin=1, bc=2))
    netmesh.Add(FaceDescriptor(surfnr=5, domin=1, bc=3))
    netmesh.Add(FaceDescriptor(surfnr=3, domin=1, bc=4))
    netmesh.Add(FaceDescriptor(surfnr=0, domin=1, bc=5))
    netmesh.Add(FaceDescriptor(surfnr=1, domin=1, bc=6))

    # y-z-plane, smallest x-coord: ("back")
    AddSurfEls(0, 1, nz, nz + 1, ny, facenr=1)  # y-z-plane
    # x-z-plane, smallest y-coord: ("left")
    AddSurfEls(0, (ny + 1) * (nz + 1), nx, 1, nz, facenr=2)
    # y-z-plane, largest x-coord: ("front")
    AddSurfEls((nx + 1) * (ny + 1) * (nz + 1) - 1,
               -(nz + 1),
               ny,
               -1,
               nz,
               facenr=3)
    # x-z-plane, largest y-coord: ("right")
    AddSurfEls((nx + 1) * (ny + 1) * (nz + 1) - 1,
               -1,
               nz,
               -(ny + 1) * (nz + 1),
               nx,
               facenr=4)
    # x-y-plane, smallest z-coord: ("bottom")
    AddSurfEls(0, nz + 1, ny, (ny + 1) * (nz + 1), nx, facenr=5)
    # x-y-plane, largest z-coord: ("top")
    AddSurfEls((nx + 1) * (ny + 1) * (nz + 1) - 1,
               -(ny + 1) * (nz + 1),
               nx,
               -(nz + 1),
               ny,
               facenr=6)

    if cuboid_mapping:
        netmesh.SetBCName(0, "back")
        netmesh.SetBCName(1, "left")
        netmesh.SetBCName(2, "front")
        netmesh.SetBCName(3, "right")
        netmesh.SetBCName(4, "bottom")
        netmesh.SetBCName(5, "top")

    netmesh.Compress()

    if secondorder:
        netmesh.SecondOrder()

    if mapping:
        for p in netmesh.Points():
            x, y, z = p.p
            x, y, z = mapping(x, y, z)
            p[0] = x
            p[1] = y
            p[2] = z

    ngsmesh = ngsolve.Mesh(netmesh)
    # ngsmesh.ngmesh.Save("tmp.vol.gz")
    # ngsmesh = ngsolve.Mesh("tmp.vol.gz")
    return ngsmesh
Example #19
0
ns = []
errs = []
err2s = []

import netgen.csg
import ngsolve as ngs
cube = netgen.csg.OrthoBrick(netgen.csg.Pnt(0, 0, 0), netgen.csg.Pnt(1, 1, 1))

geo = netgen.csg.CSGeometry()
geo.Add(cube)

bempp.api.global_parameters.hmat.eps = 1E-05
bempp.api.global_parameters.hmat.max_rank = 4096

for n in range(1, 12):
    mesh = ngs.Mesh(geo.GenerateMesh(maxh=1 / n))

    epsilon = 1.
    mu = 1.
    mu_inv = 1. / mu
    omega = k / np.sqrt(mu * epsilon)

    def incident_field(x):
        return np.array([np.exp(1j * k * x[2]), 0. * x[2], 0. * x[2]])

    def curl_incident_field(x):
        return np.array([0. * x[2], np.exp(1j * k * x[2]), 0. * x[2]])

    def tangential_trace(x, n, domain_index, result):
        result[:] = np.cross(incident_field(x), n, axis=0)
Example #20
0
def MakeStructuredSurfaceMesh(quads=True,
                              nx=10,
                              ny=10,
                              mapping=None,
                              secondorder=False,
                              bbbpts=None,
                              bbbnames=None,
                              flip_triangles=False):
    """
    Generate a structured 2D surface mesh in 3D

    Parameters
    ----------
    quads : bool
      If True, a quadrilateral mesh is generated. If False, the quads are split to triangles.

    nx : int
      Number of cells in x-direction.

    ny : int
      Number of cells in y-direction.

    mapping : lamda
      Mapping to transform the generated points. If None, the identity mapping is used.
    
    secondorder : bool
      If True, use quadratic elements, else linear elements are used.

    bbbpts : list
      List of points which should be handled as BBBND and are named with bbbnames. The mesh (nx, ny and mapping) must be constructed in such a way that the bbbpts coincide with generated points. Otherwise an Exception is thrown.

    bbbnames : list
      List of bbbnd names as strings. Size must coincide with size of bbbpts. Otherwise an Exception is thrown.

    flip_triangles : bool
      If set tot True together with quads=False the quads are cut the other way round

    Returns
    -------
    (ngsolve.mesh)
      Returns generated NGSolve mesh

    """
    mesh = Mesh(dim=3)

    if (bbbpts and bbbnames) and len(bbbpts) != len(bbbnames):
        raise Exception(
            "Lenght of bbbnames does not coincide with length of bbbpts!")

    found = []
    indbbbpts = []
    if bbbpts:
        for i in range(len(bbbpts)):
            found.append(False)
            indbbbpts.append(None)

    pids = []
    for i in range(ny + 1):
        for j in range(nx + 1):
            x, y, z = j / nx, i / ny, 0
            pids.append(mesh.Add(MeshPoint(Pnt(x, y, z))))

    mesh.Add(FaceDescriptor(surfnr=1, domin=1, bc=1))

    for i in range(ny):
        for j in range(nx):
            base = i * (nx + 1) + j
            if quads:
                pnum = [base, base + 1, base + nx + 2, base + nx + 1]
                elpids = [pids[p] for p in pnum]
                el = Element2D(1, elpids)
                if not mapping:
                    el.curved = False
                mesh.Add(el)
            else:
                if flip_triangles:
                    pnum1 = [base, base + 1, base + nx + 2]
                    pnum2 = [base, base + nx + 2, base + nx + 1]
                else:
                    pnum1 = [base, base + 1, base + nx + 1]
                    pnum2 = [base + 1, base + nx + 2, base + nx + 1]
                elpids1 = [pids[p] for p in pnum1]
                elpids2 = [pids[p] for p in pnum2]
                mesh.Add(Element2D(1, elpids1))
                mesh.Add(Element2D(1, elpids2))

    for i in range(nx):
        mesh.Add(Element1D([pids[i], pids[i + 1]], index=1))
    for i in range(ny):
        mesh.Add(
            Element1D([pids[i * (nx + 1) + nx], pids[(i + 1) * (nx + 1) + nx]],
                      index=2))
    for i in range(nx):
        mesh.Add(
            Element1D([pids[ny * (nx + 1) + i + 1], pids[ny * (nx + 1) + i]],
                      index=3))
    for i in range(ny):
        mesh.Add(
            Element1D([pids[(i + 1) * (nx + 1)], pids[i * (nx + 1)]], index=4))

    mesh.SetCD2Name(1, "bottom")
    mesh.SetCD2Name(2, "right")
    mesh.SetCD2Name(3, "top")
    mesh.SetCD2Name(4, "left")

    if secondorder:
        mesh.SecondOrder()

    if mapping:
        for p in mesh.Points():
            x, y, z = p.p
            x, y, z = mapping(x, y, z)
            p[0], p[1], p[2] = x, y, z

    for k in range(len(found)):
        i = 0
        for p in mesh.Points():
            if abs(p.p[0] - bbbpts[k][0]) + abs(p.p[1] - bbbpts[k][1]) + abs(
                    p.p[2] - bbbpts[k][2]) < 1e-6:
                indbbbpts[k] = pids[i]
                found[k] = True
            i += 1
    for k in range(len(found)):
        if found[k] == False:
            raise Exception("bbbpnt[", k, "] not in structured mesh!")

    for i in range(len(indbbbpts)):
        mesh.Add(Element0D(indbbbpts[i], index=i + 1))
        mesh.SetCD3Name(i + 1, bbbnames[i])

    mesh.Compress()
    ngsmesh = ngsolve.Mesh(mesh)
    return ngsmesh
Example #21
0
def MakeStructured2DMesh(quads=True,
                         nx=10,
                         ny=10,
                         secondorder=False,
                         periodic_x=False,
                         periodic_y=False,
                         mapping=None,
                         bbpts=None,
                         bbnames=None,
                         flip_triangles=False):
    """
    Generate a structured 2D mesh

    Parameters
    ----------
    quads : bool
      If True, a quadrilateral mesh is generated. If False, the quads are split to triangles.

    nx : int
      Number of cells in x-direction.

    ny : int
      Number of cells in y-direction.

    secondorder : bool
      If True, second order curved elements are used.

    periodic_x: bool
      If True, the left and right boundaries are identified to generate a periodic mesh in x-direction.

    periodic_y: bool
      If True, the top and bottom boundaries are identified to generate a periodic mesh in y-direction.

    mapping: lamda
      Mapping to transform the generated points. If None, the identity mapping is used.
    
    bbpts : list
      List of points which should be handled as BBND and are named with bbnames. The mesh (nx, ny and mapping) must be constructed in such a way that the bbpts coincide with generated points. Otherwise an Exception is thrown.

    bbnames : list
      List of bbnd names as strings. Size must coincide with size of bbpts. Otherwise an Exception is thrown.

    flip_triangles : bool
      If set tot True together with quads=False the quads are cut the other way round

    Returns
    -------
    (ngsolve.mesh)
      Returns generated 2D NGSolve mesh

    """
    mesh = Mesh()
    mesh.dim = 2

    if (bbpts and bbnames) and len(bbpts) != len(bbnames):
        raise Exception(
            "Lenght of bbnames does not coincide with length of bbpts!")

    found = []
    indbbpts = []
    if bbpts:
        for i in range(len(bbpts)):
            found.append(False)
            indbbpts.append(None)

    pids = []
    if periodic_y:
        slavei = []
        masteri = []
    if periodic_x:
        slavej = []
        masterj = []
    for i in range(ny + 1):
        for j in range(nx + 1):
            x, y = j / nx, i / ny
            # if mapping:
            #    x,y = mapping(x,y)
            pids.append(mesh.Add(MeshPoint(Pnt(x, y, 0))))
            if periodic_y:
                if i == 0:
                    slavei.append(pids[-1])
                if i == ny:
                    masteri.append(pids[-1])
            if periodic_x:
                if j == 0:
                    slavej.append(pids[-1])
                if j == nx:
                    masterj.append(pids[-1])
    if periodic_y:
        for i in range(len(slavei)):
            mesh.AddPointIdentification(masteri[i],
                                        slavei[i],
                                        identnr=1,
                                        type=2)
    if periodic_x:
        for j in range(len(slavej)):
            mesh.AddPointIdentification(masterj[j],
                                        slavej[j],
                                        identnr=2,
                                        type=2)

    # mesh.Add(FaceDescriptor(surfnr=1,domin=1,bc=1))
    idx_dom = mesh.AddRegion("dom", dim=2)
    idx_bottom = mesh.AddRegion("bottom", dim=1)
    idx_right = mesh.AddRegion("right", dim=1)
    idx_top = mesh.AddRegion("top", dim=1)
    idx_left = mesh.AddRegion("left", dim=1)

    for i in range(ny):
        for j in range(nx):
            base = i * (nx + 1) + j
            if quads:
                pnum = [base, base + 1, base + nx + 2, base + nx + 1]
                elpids = [pids[p] for p in pnum]
                el = Element2D(idx_dom, elpids)
                if not mapping:
                    el.curved = False
                mesh.Add(el)
            else:
                if flip_triangles:
                    pnum1 = [base, base + 1, base + nx + 2]
                    pnum2 = [base, base + nx + 2, base + nx + 1]
                else:
                    pnum1 = [base, base + 1, base + nx + 1]
                    pnum2 = [base + 1, base + nx + 2, base + nx + 1]
                elpids1 = [pids[p] for p in pnum1]
                elpids2 = [pids[p] for p in pnum2]
                mesh.Add(Element2D(idx_dom, elpids1))
                mesh.Add(Element2D(idx_dom, elpids2))

    for i in range(nx):
        mesh.Add(Element1D([pids[i], pids[i + 1]], index=idx_bottom))
    for i in range(ny):
        mesh.Add(
            Element1D([pids[i * (nx + 1) + nx], pids[(i + 1) * (nx + 1) + nx]],
                      index=idx_right))
    for i in range(nx):
        mesh.Add(
            Element1D([pids[ny * (nx + 1) + i + 1], pids[ny * (nx + 1) + i]],
                      index=idx_top))
    for i in range(ny):
        mesh.Add(
            Element1D([pids[(i + 1) * (nx + 1)], pids[i * (nx + 1)]],
                      index=idx_left))

    # mesh.SetBCName(0, "bottom")
    # mesh.SetBCName(1, "right")
    # mesh.SetBCName(2, "top")
    # mesh.SetBCName(3, "left")

    mesh.Compress()

    if secondorder:
        mesh.SecondOrder()

    if mapping:
        for p in mesh.Points():
            x, y, z = p.p
            x, y = mapping(x, y)
            p[0] = x
            p[1] = y

    for k in range(len(found)):
        i = 0
        for p in mesh.Points():
            if abs(p.p[0] - bbpts[k][0]) + abs(p.p[1] - bbpts[k][1]) < 1e-6:
                indbbpts[k] = pids[i]
                found[k] = True
            i += 1
    for k in range(len(found)):
        if found[k] == False:
            raise Exception("bbpnt[", k, "] not in structured mesh!")

    for i in range(len(indbbpts)):
        mesh.Add(Element0D(indbbpts[i], index=i + 1))
        mesh.SetCD2Name(i + 1, bbnames[i])

    ngsmesh = ngsolve.Mesh(mesh)
    return ngsmesh
Example #22
0
xs = []
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)
Example #23
0
    mesh.Add(Element2D(1, [pnts[0]] + pnts[2:4]))
    mesh.Add(Element3D(1, pnts))
    return mesh


def Prism():
    mesh = Mesh(3)
    mesh.AddRegion("", 2)
    mesh.AddRegion("", 3)
    pnts = [
        mesh.Add(MeshPoint(Pnt(0, 0, 0))),
        mesh.Add(MeshPoint(Pnt(1, 0, 0))),
        mesh.Add(MeshPoint(Pnt(0, 1, 0))),
        mesh.Add(MeshPoint(Pnt(0, 0, 1))),
        mesh.Add(MeshPoint(Pnt(1, 0, 1))),
        mesh.Add(MeshPoint(Pnt(0, 1, 1)))
    ]
    mesh.Add(Element2D(1, list(reversed(pnts[:3]))))
    mesh.Add(Element2D(1, pnts[3:]))
    mesh.Add(Element2D(1, pnts[:2] + list(reversed(pnts[3:5]))))
    mesh.Add(Element2D(1, pnts[1:3] + list(reversed(pnts[4:6]))))
    mesh.Add(Element2D(1, [pnts[2], pnts[0], pnts[3], pnts[5]]))
    mesh.Add(Element3D(1, list(reversed(pnts[:3])) + list(reversed(pnts[3:]))))
    return mesh


if __name__ == "__main__":
    mesh = Prism()
    import ngsolve
    ngsolve.Draw(ngsolve.Mesh(mesh))
Example #24
0
    return 1 / (1 + ng.exp(-x))


# vectorize the logistic function for component-wise application
vσ = np.vectorize(σ)

# NNet coefficient function
u_net = W3.dot(vσ(W2.dot(vσ(Wx.dot(ng.x) + Wy.dot(ng.y) + b1)) + b2)) + b3

# unit square domain
#mesh = Mesh(unit_square.GenerateMesh(maxh=0.2))
ngmesh = unit_square.GenerateMesh(maxh=0.2)
ngmesh.Refine()
#ngmesh.Refine()

mesh = ng.Mesh(ngmesh)
mesh.ngmesh.SetGeometry(unit_square)
ng.Draw(mesh)

uₕ = poisson_solve()
ΔFEM = uₕ - uexact
ΔNET = u_net - uexact

FEM_error = ng.sqrt(ng.Integrate(ng.InnerProduct(ΔFEM, ΔFEM), mesh))
NET_error = ng.sqrt(ng.Integrate(ng.InnerProduct(ΔNET, ΔNET), mesh))
print('FEM error = ', FEM_error)
print('NET_error = ', NET_error)

ng.Draw(uₕ)
ng.Draw(u_net, mesh, "u_net")
Example #25
0
    import ngsolve as ngs
    import netgen
    from netgen.meshing import *

    from netgen.geom2d import unit_square
    #import netgen.libngpy as libng
    from netgen.csg import *

    geo = CSGeometry()

    block = OrthoBrick(Pnt(0, -a, -b), Pnt(L, a, b))
    geo.Add(block)

    #Draw (geo)

    mesh = ngs.Mesh(geo.GenerateMesh(maxh=h))
    mesh.Curve(1)

    if False:  #set this to true, if you want to visualize the mesh inside netgen/ngsolve
        # import netgen
        import netgen.gui
        ngs.Draw(mesh)
        netgen.Redraw()

    #%%+++++++++++++++++++++++++++++++++++++++++++++++++++++
    #Use fem to import FEM model and create FFRFreducedOrder object
    fem.ImportMeshFromNGsolve(mesh,
                              density=rho,
                              youngsModulus=Emodulus,
                              poissonsRatio=nu)
    fem.SaveToFile(fileName)
Example #26
0
    import ngsolve as ngs
    import netgen
    from netgen.meshing import *

    from netgen.geom2d import unit_square
    #import netgen.libngpy as libng
    from netgen.csg import *

    geo = CSGeometry()

    #plate
    block = OrthoBrick(Pnt(0, -0.5 * h, -0.5 * w), Pnt(L, 0.5 * h, 0.5 * w))

    geo.Add(block)

    mesh = ngs.Mesh(geo.GenerateMesh(maxh=meshH))
    mesh.Curve(1)

    if False:  #set this to true, if you want to visualize the mesh inside netgen/ngsolve
        # import netgen
        import netgen.gui
        ngs.Draw(mesh)
        netgen.Redraw()

    #%%+++++++++++++++++++++++++++++++++++++++++++++++++++++
    #Use femInterface to import femInterface model and create FFRFreducedOrder object
    eigenModesComputed = False
    femInterface.ImportMeshFromNGsolve(mesh,
                                       density=rho,
                                       youngsModulus=Emodulus,
                                       poissonsRatio=nu,
Example #27
0
    return F * reaction_rate * li_factor


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()])

Example #28
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()
Example #29
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)
Example #30
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]))