示例#1
0
def test_new_integrateX_via_straight_cutted_quad3D_polynomial(order, domain, quad_dominated, alpha, dim):
    ngsglobals.msg_level = 0

    if (quad_dominated):
        mesh = MakeUniform3DGrid(quads = True, N=1, P1=(0,0,0),P2=(1,1,1))
    else:
        cube = OrthoBrick( Pnt(0,0,0), Pnt(1,1,1) ).bc(1)
        geom = CSGeometry()
        geom.Add (cube)
        ngmesh = geom.GenerateMesh(maxh=1.3, quad_dominated=quad_dominated)
        mesh = Mesh(ngmesh)
        
    levelset = 1 - 2*x- 2*y - 2*z
    val_pos = pow(2,-alpha-3)/(pow(alpha,3)+6*alpha*alpha + 11*alpha+6)
    referencevals = {POS: val_pos, NEG: 1./(alpha+1) - val_pos}
    
    lset_approx = GridFunction(H1(mesh,order=1))
    InterpolateToP1(levelset,lset_approx)
    
    f = dim**alpha
    
    integral = Integrate(levelset_domain = { "levelset" : lset_approx, "domain_type" : domain},
                         cf=f, mesh=mesh, order = order)
    error = abs(integral - referencevals[domain])
    
    assert error < 5e-15*(order+1)*(order+1)
示例#2
0
def test_new_integrateX_via_straight_cutted_quad3D(order, domain,
                                                   quad_dominated):
    if (quad_dominated):
        mesh = MakeUniform3DGrid(quads=True, N=1, P1=(0, 0, 0), P2=(1, 1, 1))
    else:
        cube = OrthoBrick(Pnt(0, 0, 0), Pnt(1, 1, 1)).bc(1)
        geom = CSGeometry()
        geom.Add(cube)
        ngmesh = geom.GenerateMesh(maxh=1.3, quad_dominated=quad_dominated)
        mesh = Mesh(ngmesh)

    levelset = 1 - 2 * x - 2 * y - 2 * z
    referencevals = {POS: 1. / 48, NEG: 47. / 48, IF: sqrt(3) / 8}

    lset_approx = GridFunction(H1(mesh, order=1))
    InterpolateToP1(levelset, lset_approx)

    f = CoefficientFunction(1)

    integral = Integrate(levelset_domain={
        "levelset": lset_approx,
        "domain_type": domain
    },
                         cf=f,
                         mesh=mesh,
                         order=order)
    print("Integral: ", integral)
    error = abs(integral - referencevals[domain])

    assert error < 5e-15 * (order + 1) * (order + 1)
示例#3
0
 def _generateMesh(self, *args):
     from netgen.csg import CSGeometry, Sphere, Pnt
     from ngsolve import Mesh
     r = self.getRadius()
     geometry = CSGeometry()
     sphere = Sphere(Pnt(0, 0, 0), r).bc("sphere")
     geometry.Add(sphere)
     self.geometry = geometry
     self.mesh = Mesh(geometry.GenerateMesh(maxh=r / 5))
     ngsolve.Draw(self.mesh)
示例#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
示例#5
0
def test_new_integrateX_TPMC_case_quad3D2(order, quad_dominated, high_order):
    if quad_dominated:
        mesh = MakeUniform3DGrid(quads=True, N=10, P1=(0, 0, 0), P2=(1, 1, 1))
    else:
        geom = CSGeometry()
        geom.Add(OrthoBrick(Pnt(0, 0, 0), Pnt(1, 1, 1)).bc(1))
        ngmesh = geom.GenerateMesh(maxh=0.2134981)
        for i in range(4):
            ngmesh.Refine()
        mesh = Mesh(ngmesh)

    #phi = -4*(1-x)*(1-y)*(1-z) + 4*(1-x)*(1-y)*z -1*(1-x)*y*(1-z) - 1*(1-x)*y*z + 2*x*(1-y)*(1-z) -3 *x*(1-y)*z + 5 * x * y * (1-z) -1 *x *y*z
    phi = x * ((7 * y - 13) * z + 6) + y * (3 - 8 * z) + 8 * z - 4

    if high_order:
        print("Creating LevelSetMeshAdaptation class")
        lsetmeshadap = LevelSetMeshAdaptation(mesh,
                                              order=order,
                                              threshold=0.2,
                                              discontinuous_qn=True)
        lsetp1 = lsetmeshadap.lset_p1
        deformation = lsetmeshadap.CalcDeformation(phi)

        mesh.SetDeformation(deformation)
    else:
        lsetp1 = GridFunction(H1(mesh, order=1))
        lsetp1.Set(phi)

    f = CoefficientFunction(1)

    print("Doing integration")
    for domain in [POS, NEG, IF]:
        integral = Integrate(levelset_domain={
            "levelset": lsetp1,
            "domain_type": domain
        },
                             cf=f,
                             mesh=mesh,
                             order=order)
        print("Integral: ", integral, " ; domain = ", domain)

        if domain == IF:
            assert abs(integral - 1.82169) < 5e-3
        elif domain == NEG:
            assert abs(integral - 0.51681) < 1e-3
        else:
            assert abs(integral - 0.48319) < 1e-3
示例#6
0
def test_new_integrateX_via_straight_cutted_quad3D(order, domain, quad):
    cube = OrthoBrick(Pnt(0, 0, 0), Pnt(1, 1, 1)).bc(1)
    geom = CSGeometry()
    geom.Add(cube)
    ngmesh = geom.GenerateMesh(maxh=1.3, quad_dominated=quad)
    mesh = Mesh(ngmesh)

    levelset = 1 - 2 * x - 2 * y - 2 * z
    referencevals = {POS: 1. / 48, NEG: 47. / 48, IF: sqrt(3) / 8}

    f = CoefficientFunction(1)

    integral = Integrate(levelset_domain={
        "levelset": levelset,
        "domain_type": domain
    },
                         cf=f,
                         mesh=mesh,
                         order=order)
    error = abs(integral - referencevals[domain])

    assert error < 5e-15 * (order + 1) * (order + 1)
def discretize_ngsolve():
    from ngsolve import (ngsglobals, Mesh, H1, CoefficientFunction, LinearForm,
                         SymbolicLFI, BilinearForm, SymbolicBFI, grad,
                         TaskManager)
    from netgen.csg import CSGeometry, OrthoBrick, Pnt
    import numpy as np

    ngsglobals.msg_level = 1

    geo = CSGeometry()
    obox = OrthoBrick(Pnt(-1, -1, -1), Pnt(1, 1, 1)).bc("outer")

    b = []
    b.append(
        OrthoBrick(Pnt(-1, -1, -1), Pnt(0.0, 0.0,
                                        0.0)).mat("mat1").bc("inner"))
    b.append(
        OrthoBrick(Pnt(-1, 0, -1), Pnt(0.0, 1.0, 0.0)).mat("mat2").bc("inner"))
    b.append(
        OrthoBrick(Pnt(0, -1, -1), Pnt(1.0, 0.0, 0.0)).mat("mat3").bc("inner"))
    b.append(
        OrthoBrick(Pnt(0, 0, -1), Pnt(1.0, 1.0, 0.0)).mat("mat4").bc("inner"))
    b.append(
        OrthoBrick(Pnt(-1, -1, 0), Pnt(0.0, 0.0, 1.0)).mat("mat5").bc("inner"))
    b.append(
        OrthoBrick(Pnt(-1, 0, 0), Pnt(0.0, 1.0, 1.0)).mat("mat6").bc("inner"))
    b.append(
        OrthoBrick(Pnt(0, -1, 0), Pnt(1.0, 0.0, 1.0)).mat("mat7").bc("inner"))
    b.append(
        OrthoBrick(Pnt(0, 0, 0), Pnt(1.0, 1.0, 1.0)).mat("mat8").bc("inner"))
    box = (obox - b[0] - b[1] - b[2] - b[3] - b[4] - b[5] - b[6] - b[7])

    geo.Add(box)
    for bi in b:
        geo.Add(bi)
    # domain 0 is empty!

    mesh = Mesh(geo.GenerateMesh(maxh=0.3))

    # H1-conforming finite element space
    V = H1(mesh, order=NGS_ORDER, dirichlet="outer")
    v = V.TestFunction()
    u = V.TrialFunction()

    # Coeff as array: variable coefficient function (one CoefFct. per domain):
    sourcefct = CoefficientFunction([1 for i in range(9)])

    with TaskManager():
        # the right hand side
        f = LinearForm(V)
        f += SymbolicLFI(sourcefct * v)
        f.Assemble()

        # the bilinear-form
        mats = []
        coeffs = [[0, 1, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 1, 0],
                  [0, 0, 0, 1, 0, 0, 1, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0]]
        for c in coeffs:
            diffusion = CoefficientFunction(c)
            a = BilinearForm(V, symmetric=False)
            a += SymbolicBFI(diffusion * grad(u) * grad(v),
                             definedon=(np.where(np.array(c) == 1)[0] +
                                        1).tolist())
            a.Assemble()
            mats.append(a.mat)

    from pymor.bindings.ngsolve import NGSolveVectorSpace, NGSolveMatrixOperator, NGSolveVisualizer

    space = NGSolveVectorSpace(V)
    op = LincombOperator(
        [NGSolveMatrixOperator(m, space, space) for m in mats], [
            ProjectionParameterFunctional('diffusion', (len(coeffs), ), (i, ))
            for i in range(len(coeffs))
        ])

    h1_0_op = op.assemble([1] * len(coeffs)).with_(name='h1_0_semi')

    F = space.zeros()
    F._list[0].real_part.impl.vec.data = f.vec
    F = VectorOperator(F)

    return StationaryModel(op,
                           F,
                           visualizer=NGSolveVisualizer(mesh, V),
                           products={'h1_0_semi': h1_0_op},
                           parameter_space=CubicParameterSpace(
                               op.parameter_type, 0.1, 1.))
示例#8
0
"""
from math import pi
# ngsolve stuff
from ngsolve import *
# visualization stuff
from ngsolve.internal import *
# basic xfem functionality
from xfem import *
from xfem.lsetcurv import *

# from netgen.geom2d import SplineGeometry
from netgen.csg import CSGeometry, OrthoBrick, Pnt

# geometry
cube = CSGeometry()
cube.Add (OrthoBrick(Pnt(-1.41,-1.41,-1.41), Pnt(1.41,1.41,1.41)))
mesh = Mesh (cube.GenerateMesh(maxh=0.6, quad_dominated=False))

levelset = sqrt(x*x+y*y+z*z)-1

for i in range(1):
   lsetp1 = GridFunction(H1(mesh,order=1))
   InterpolateToP1(levelset,lsetp1)
   RefineAtLevelSet(lsetp1)
   mesh.Refine()
   
order = 3

# class to compute the mesh transformation needed for higher order accuracy
#  * order: order of the mesh deformation function
示例#9
0
# integration on lset domains

from math import pi
# ngsolve stuff
from ngsolve import *
# basic xfem functionality
from xfem import *

from netgen.csg import CSGeometry, OrthoBrick, Pnt
cube = OrthoBrick(Pnt(0, 0, 0), Pnt(1, 1, 1)).bc(1)
geom = CSGeometry()
geom.Add(cube)
ngmesh = geom.GenerateMesh(maxh=1, quad_dominated=True)
mesh = Mesh(ngmesh)


def binary_pow(x, a):
    if a == 0:
        return 0 * x + 1
    elif a == 1:
        return x
    else:
        print("Invalid argument a")


#levelset coefficients
c = [[[1, -2], [-2, 0]], [[-2, 0], [0, 0]]]

#levelset = 1-2*x-2*y-2*z #(sqrt(x*x+y*y+z*z)-0.5)
levelset = sum([
    c[alpha][beta][gamma] * binary_pow(x, alpha) * binary_pow(y, beta) *
示例#10
0
from netgen.csg import CSGeometry, OrthoBrick, Point3d


n_layers = 5
max_h = 0.1

geo = CSGeometry()

regs = ['even', 'odd']
l = 1
c = 1/n_layers
d = 1/n_layers
brick0 = OrthoBrick(Point3d(-c, -c, -c), Point3d(c, c, c)).bc('inner_bnd')
geo.Add(brick0.mat(regs[l]))
l = 1-l

last_brick = brick0
for layer in range(n_layers-1):
    c = c+d
    if layer < n_layers-2:
        brick = OrthoBrick(Point3d(-c, -c, -c), Point3d(c, c, c)).bc('inner_bnd')
    else:
        brick = OrthoBrick(Point3d(-c, -c, -c), Point3d(c, c, c)).bc('ext_bnd')
    geo.Add((brick-last_brick).mat(regs[l]))
    l = 1-l
    last_brick = brick

mesh = geo.GenerateMesh(maxh=max_h)

mesh.Save('3d_matrioshka_l'+str(n_layers)+'_h0_1.vol')
示例#11
0
from ngsolve import *
from netgen.csg import CSGeometry
from math import pi
from numpy import log
from ctypes import CDLL

libDPG = CDLL("../libDPG.so")

ngsglobals.msg_level = 1

# This mesh consists of a cylindrical magnet inside a bounding box
# I think it should be possible to recreate this mesh, adding boundary labels
geo = CSGeometry("../pde/magnet.geo")
mesh = Mesh("../pde/magnet.vol.gz")
print(mesh.GetBoundaries())
print(mesh.GetMaterials())
geometryorder = 3

# So far, haven't found documentation on pde file coefficent functions with this syntax
# I think it may represent a pair of vectors since it's used by the curledge integrator
# another thought is it might be a list of two vectors, one per domain or boundary condition?
#F = CoefficientFunction( (0,10,0), (0, 0, 0) )
#F = CoefficientFunction( (0,10,0,0, 0, 0), dims=(2,3))
#F = CoefficientFunction( ((0,10,0), (0, 0, 0)) )
#F = CoefficientFunction( [0,10,0, 0, 0, 0] )
F = CoefficientFunction([
    (0, 10, 0), (0, 0, 0)
])  # this is the only construction that doesn't give any errors
# however, the solution is not visible and when I change the variable for viewing it seg faults

# TODO: Maybe we could make a new mesh with periodic boundaries
示例#12
0
from netgen.meshing import MeshingParameters

# from ngsolve.internal import *
# viewoptions.clipping.enable=1
# viewoptions.clipping.nx = 0.0
# viewoptions.clipping.ny = 1
# viewoptions.clipping.nz = 0.0
# visoptions.mminval=0.0
# visoptions.mmaxval=0.0
# visoptions.autoscale = False
# visoptions.isosurf = 1
# visoptions.numiso = 1
# visoptions.subdivisions = 1

for lsetgeom in ["cheese", "torus", "dziukelliott", "dziuk88", "sphere"]:
    geom = CSGeometry()
    geom.Add(BoundingBoxes[lsetgeom])
    mesh = Mesh(geom.GenerateMesh(maxh=1.0))
    levelset = LevelsetExamples[lsetgeom]

    order = 2
    lsetmeshadap = LevelSetMeshAdaptation(mesh,
                                          order=order,
                                          threshold=100,
                                          discontinuous_qn=True)

    Draw(levelset, mesh, "levelset")
    Draw(lsetmeshadap.deform, mesh, "deformation")
    Draw(lsetmeshadap.lset_p1, mesh, "levelset(P1)")

    distances = []
示例#13
0
def MakeUniform3DGrid(quads = False, N=5, P1=(0,0,0),P2=(1,1,1)):

  if not quads:
    raise BaseException("Only hex cube so far...")
  
  
  Lx = P2[0]-P1[0]
  Ly = P2[1]-P1[1]
  Lz = P2[2]-P1[2]

  cube = OrthoBrick( Pnt(P1[0],P1[1],P1[2]), Pnt(P2[0],P2[1],P2[2]) ).bc(1)
  geom = CSGeometry()
  geom.Add (cube)
  netmesh = NetMesh()
  netmesh.SetGeometry(geom)
  netmesh.dim = 3
  
  pids = []
  for i in range(N+1):
      for j in range(N+1):
          for k in range(N+1):
              pids.append (netmesh.Add (MeshPoint(Pnt(P1[0] + Lx * i / N,
                                                   P1[1] + Ly * j / N,
                                                   P1[2] + Lz * k / N))))
              
  for i in range(N):
      for j in range(N):
          for k in range(N):
              base = i * (N+1)*(N+1) + j*(N+1) + k
              baseup = base+(N+1)*(N+1)
              pnum = [base,base+1,base+(N+1)+1,base+(N+1),
                      baseup, baseup+1, baseup+(N+1)+1, baseup+(N+1)]
              elpids = [pids[p] for p in pnum]
              netmesh.Add (Element3D(1,elpids))
  
  
  
  def AddSurfEls (p1, dx, dy, facenr):
      for i in range(N):
          for j in range(N):
              base = p1 + i*dx+j*dy
              pnum = [base, base+dx, base+dx+dy, base+dy]
              elpids = [pids[p] for p in pnum]
              netmesh.Add (Element2D(facenr,elpids))
  
                          
  netmesh.Add (FaceDescriptor(surfnr=1,domin=1,bc=1))
  AddSurfEls (0, 1, N+1, facenr=1)
  
  netmesh.Add (FaceDescriptor(surfnr=2,domin=1,bc=1))
  AddSurfEls (0, (N+1)*(N+1), 1, facenr=2)
  
  netmesh.Add (FaceDescriptor(surfnr=3,domin=1,bc=1))
  AddSurfEls (0, N+1, (N+1)*(N+1), facenr=3)
  
  
  netmesh.Add (FaceDescriptor(surfnr=4,domin=1,bc=1))
  AddSurfEls ((N+1)**3-1, -(N+1), -1, facenr=1)
  
  netmesh.Add (FaceDescriptor(surfnr=5,domin=1,bc=1))
  AddSurfEls ((N+1)**3-1, -(N+1)*(N+1), -(N+1), facenr=1)
  
  netmesh.Add (FaceDescriptor(surfnr=6,domin=1,bc=1))
  AddSurfEls ((N+1)**3-1, -1, -(N+1)*(N+1), facenr=1)
  
  
  netmesh.Compress()
  mesh = NGSMesh(netmesh)
  mesh.ngmesh.Save("tmp.vol.gz")
  mesh = NGSMesh("tmp.vol.gz")
  return mesh 
示例#14
0
#      - Delta u - k*k u = f    on Omega
#       n.grad u - i*k u = g    on bdry
#
# on a 3D domain.

from ngsolve import *
from netgen.csg import CSGeometry
from math import pi
from numpy import log
from ctypes import CDLL

libDPG = CDLL("../libDPG.so")

#ngsglobals.msg_level = 1

geo = CSGeometry("../pde/cube6bc.geo")

mesh = Mesh("../pde/cube6bc4.vol.gz")

SetHeapSize(int(1e7))

one = CoefficientFunction(1)
minus = CoefficientFunction(-1.0)
dd = CoefficientFunction(1.0)
cc = CoefficientFunction(1.0)

# number of waves in a unit-sized domain
nwav = 2

# propagation angle
theta = (pi / 11.0)