This page was generated from unit-8.2-intlset/intlset.ipynb.
8.2 Integration on level set domains¶
This unit gives a basic introduction to a few fundamental concepts in ngsxfem. Especially, we treat:
level set geometries and its (P1) approximation
Cut differential symbols to conveniently define integrals on cut domain
higher order level set geometry approximations: the isoparametric mapping and the Algoim-based quadrature
simple example: calculate area of the unit circle using level set representations
background domain: \([-1.5, 1.5]^2 \subset \mathbb{R}^2\).
Let \(\phi\) be a continuous level set function. We recall:
[1]:
# basic geometry features (for the background mesh)
from netgen.geom2d import SplineGeometry
# ngsolve
from netgen.occ import *
# basic xfem functionality
from xfem import *
# for isoparametric mapping
from xfem.lsetcurv import *
# visualisation
from ngsolve.webgui import *
# the contant pi
from math import pi
importing ngsxfem-2.2.2609.dev0
We generate the background mesh of the domain and use a simplicial triangulation
[2]:
geo = OCCGeometry(unit_square_shape.Scale((0,0,0),3).Move((-1.5,-1.5,0)), dim=2)
mesh = Mesh(geo.GenerateMesh(maxh=0.8,quad_dominated=False))
Draw(mesh)
[2]:
WebGLScene
On the background mesh we define the level set function. In this example we choose a levelset function which measures the distance to the origin and substracts a constant \(r\), resulting in an circle of radius \(r\) as \(\Omega_{-}\):
[3]:
r = 1
levelset = sqrt(x**2+y**2) - r
DrawDC(levelset, -3.5, 2.5, mesh, 'levelset')
[3]:
WebGLScene
Area of the unit circle:
\[A = \pi = \int_{\Omega_-(\phi)} 1 \, \mathrm{d}x\]
Piecewise linear geometry approximation¶
The standard quadrature rules of ngsxfem on implicitly defined geometries handle level set functions \(\phi\) which are in \(\mathcal{P}^1(T)\) for all \(T\) of the triangulation (the cut of an element is straight).
Therefore we replace the levelset function \(\phi\) with an approximation \(\phi^\ast \in \mathcal{P}^1(T), T \subset \Omega\).
Higher order level set functions can also be treated directly, with the quadrature of the Algoim library, see the last section of this notebook.
[4]:
V = H1(mesh,order=1,autoupdate=True)
lset_approx = GridFunction(V,autoupdate=True)
InterpolateToP1(levelset, lset_approx)
DrawDC(lset_approx, -3.5, 2.5, mesh, 'levelset_p1')
[4]:
WebGLScene
Notice that this replacement \(\phi \mapsto \phi^\ast\) will introduce a geometry error of order \(h^2\). We will investigate this numerically later on in this notebook.
As a next step we need to define the integrand:
[5]:
f = CoefficientFunction(1)
As in NGSolve, we integrate by using the Integrate function. For this to be aware of the fact that we are integration over a level set domain we use the dCut differential symbol, to which we need to pass:
levelset: level set function which describes the geometry (a P1-GridFunction for the standard rules; other level set functions are treated with Algoim, see below)domain_type: decision on which part of the geometry the integration should take place (NEG/POS/IF)order: The order of integration rule to be used
[6]:
order = 2
integral = Integrate(f * dCut(levelset=lset_approx, domain_type=NEG, order=order), mesh=mesh)
error = abs(integral - pi)
print("Result of the integration: ", integral)
print("Error of the integration: ", error)
Result of the integration: 2.8083924720125975
Error of the integration: 0.33320018157719566
Convergence study¶
To get more accurate results
save the previous error and execute a refinement
repeat the steps from above
Repeatedly execute the lower block to add more refinement steps.
[7]:
errors = []
def AppendResultAndPostProcess(integral):
error = abs(integral - pi)
print("Result of the integration: ", integral)
print("Error of the integration: ", error)
errors.append(error)
eoc = [log(errors[i+1]/errors[i])/log(0.5) for i in range(len(errors)-1)]
print("Collected errors:", errors)
print("experimental order of convergence (L2):", eoc)
AppendResultAndPostProcess(integral)
Result of the integration: 2.8083924720125975
Error of the integration: 0.33320018157719566
Collected errors: [0.33320018157719566]
experimental order of convergence (L2): []
[8]:
scene = Draw(lset_approx, mesh, "lsetp1", min=0, max=0.0)
def RefineAndIntegrate():
# refine cut elements only:
RefineAtLevelSet(gf=lset_approx)
mesh.Refine()
InterpolateToP1(levelset,lset_approx)
scene.Redraw()
integral = Integrate(f * dCut(levelset=lset_approx, domain_type=NEG, order=order), mesh=mesh)
AppendResultAndPostProcess(integral)
[9]:
RefineAndIntegrate()
Result of the integration: 3.0330101786865753
Error of the integration: 0.10858247490321782
Collected errors: [0.33320018157719566, 0.10858247490321782]
experimental order of convergence (L2): [1.617597914424262]
We observe only a second order convergence which results from the piecewise linear geometry approximation.
Higher order geometry approximation with an isoparametric mapping¶
In order to get higher order convergence we can use the isoparametric mapping functionality of xfem.
We apply a mesh transformation technique in the spirit of isoparametric finite elements: 
Video of the mesh transformation
[10]:
%%html
<iframe width=100% height=600px src="https://www.youtube.com/embed/Mst_LvfgPCg?rel=0" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
To compute the corresponding mapping we use the LevelSetMeshAdaptation class
[11]:
mesh = Mesh(geo.GenerateMesh(maxh=0.4,quad_dominated=False))
lsetmeshadap = LevelSetMeshAdaptation(mesh, order=2, threshold=1000, discontinuous_qn=True)
deformation = lsetmeshadap.CalcDeformation(levelset)
Draw(deformation,mesh,"deformation")
[11]:
WebGLScene
We can observe the geometrical improvement in the following sequence:
[12]:
scene1 = Draw(deformation, mesh, "deformation", autoscale=False, min=0.0, max=0.028)
[13]:
scene2 = DrawDC(lsetmeshadap.lset_p1, -3.5, 2.5, mesh, "lsetp1_ho", deformation=deformation)
[14]:
N=100
deformation.vec.data = 1.0/N*deformation.vec
for i in range (1, N+1):
deformation.vec.data = (i+1)/i * deformation.vec
scene1.Redraw()
scene2.Redraw()
Convergence study with isoparametric mapping applied¶
We now apply the mesh deformation (2nd order mapping) to improve the accuracy of the integration problem.
error tables:
[15]:
order = 2
mesh = Mesh(geo.GenerateMesh(maxh=0.7,quad_dominated=False))
levelset = sqrt(x*x+y*y)-1
referencevals = { POS : 9-pi, NEG : pi, IF : 2*pi }
lsetmeshadap = LevelSetMeshAdaptation(mesh, order=order, threshold=0.2, discontinuous_qn=True)
lsetp1 = lsetmeshadap.lset_p1
errors_uncurved = dict()
errors_curved = dict()
eoc_uncurved = dict()
eoc_curved = dict()
for key in [NEG,POS,IF]:
errors_curved[key] = []
errors_uncurved[key] = []
eoc_curved[key] = []
eoc_uncurved[key] = []
refinements:
[16]:
f = CoefficientFunction (1.0)
refinements = 5
for reflevel in range(refinements):
if(reflevel > 0):
mesh.Refine()
for key in [NEG,POS,IF]:
# Applying the mesh deformation
deformation = lsetmeshadap.CalcDeformation(levelset)
integrals_uncurved = Integrate(f * dCut(levelset=lsetp1, domain_type=key, order=order), mesh=mesh)
# dCut deals with the mesh deformation internally
integrals_curved = Integrate(f * dCut(levelset=lsetp1, domain_type=key, order=order, deformation=deformation), mesh=mesh)
errors_curved[key].append(abs(integrals_curved - referencevals[key]))
errors_uncurved[key].append(abs(integrals_uncurved - referencevals[key]))
# refine cut elements:
RefineAtLevelSet(gf=lsetmeshadap.lset_p1)
Convergence rates:
[17]:
for key in [NEG,POS,IF]:
eoc_curved[key] = [log(a/b)/log(2) for (a,b) in zip (errors_curved[key][0:-1],errors_curved[key][1:]) ]
eoc_uncurved[key] = [log(a/b)/log(2) for (a,b) in zip (errors_uncurved[key][0:-1],errors_uncurved[key][1:]) ]
print("errors ( curved): \n{}\n".format( errors_curved))
print(" eoc ( curved): \n{}\n".format( eoc_curved))
errors ( curved):
{<DOMAIN_TYPE.NEG: 0>: [0.002623846980058797, 0.004094950733926073, 7.135146727010877e-05, 1.2278813619204243e-06, 3.903148240169685e-07], <DOMAIN_TYPE.POS: 1>: [0.11521035815285341, 0.004094950733926517, 7.135146726788832e-05, 1.2278813859012416e-06, 3.903148151351843e-07], <DOMAIN_TYPE.IF: 2>: [1.8559620157176937e-05, 0.003400851847715103, 8.951479695973319e-05, 2.096390674388715e-06, 4.51022538427992e-07]}
eoc ( curved):
{<DOMAIN_TYPE.NEG: 0>: [-0.642162509022614, 5.842759187222148, 5.860700018412044, 1.6534610120625763], <DOMAIN_TYPE.POS: 1>: [4.814280524952578, 5.842759187267201, 5.860699990190969, 1.6534610730679122], <DOMAIN_TYPE.IF: 2>: [-7.51758516420767, 5.24762616643155, 5.416146680707624, 2.216636161873123]}
Note: The integration on level set domains (and the mapping) can be extended to bilinear and linear form integrators with the same syntax.
Higher order geometry approximation without mesh deformation: Algoim¶
As an alternative to the isoparametric mapping, ngsxfem can compute quadrature rules directly with respect to a higher order level set function. To this end, ngsxfem bundles the quadrature algorithms of the Algoim library by R. I. Saye [1]:
On every cut element the level set function is represented as a polynomial: exactly for a level set
GridFunctionof order \(k\), by interpolation of degreengsxfemglobals.algoim_lset_order(default: 4) for a generalCoefficientFunction.Algoim constructs a high order quadrature rule for the sub-domains \(\{\phi < 0\}\), \(\{\phi > 0\}\) and the zero level \(\{\phi = 0\}\) of this polynomial on the element.
The mesh stays as it is: no piecewise linear approximation and no mesh deformation is involved.
Which quadrature is applied is decided by the option cut_quadrature:
"auto"(default): the standard rules for a P1 level setGridFunction(as above, also with the isoparametric mapping), Algoim for all other level set functions."standard": always the standard rules. A level set function that is not a P1GridFunctionraises an exception."algoim": Algoim wherever it is available, also for P1 level set functions.
The option can be set
globally:
ngsxfemglobals.cut_quadrature = "auto",for a single integral:
dCut(..., cut_quadrature="algoim"),for the element markers:
CutInfo(mesh, lset, cut_quadrature="algoim")(use the same method as in the integrals).
With the default setting all we have to do is to pass a higher order level set function to dCut:
[18]:
mesh = Mesh(geo.GenerateMesh(maxh=0.7,quad_dominated=False))
k = 3
lset_ho = GridFunction(H1(mesh,order=k), autoupdate=True)
lset_ho.Set(levelset)
integral = Integrate(f * dCut(levelset=lset_ho, domain_type=NEG, order=k), mesh=mesh)
print("Result of the integration: ", integral)
print("Error of the integration: ", abs(integral - pi))
ngsxfem: the quadrature on cut elements uses Algoim by R. I. Saye (https://algoim.github.io/), chosen automatically (cut_quadrature 'auto': for level sets that are not piecewise linear GridFunctions and for cases that the standard rules do not support; set ngsxfemglobals.cut_quadrature or dCut(..., cut_quadrature=...) to choose explicitly). If you publish results, please also cite R. I. Saye, J. Comput. Phys. 448, 110720, 2022, https://doi.org/10.1016/j.jcp.2021.110720
Result of the integration: 3.1455463851138603
Error of the integration: 0.003953731524067194
The first Algoim-based quadrature rule in a session prints a message with the reference to cite [1] (and tells you if Algoim has been chosen automatically).
A level set CoefficientFunction can be passed as well (it is interpolated on every element with degree ngsxfemglobals.algoim_lset_order):
[19]:
integral = Integrate(f * dCut(levelset=levelset, domain_type=NEG, order=k), mesh=mesh)
print("Error of the integration: ", abs(integral - pi))
Error of the integration: 9.760434715122557e-06
With cut_quadrature="standard" the same level set function is rejected: the standard rules need a P1 level set GridFunction.
[20]:
try:
Integrate(f * dCut(levelset=lset_ho, domain_type=NEG, order=k, cut_quadrature="standard"), mesh=mesh)
except Exception as e:
print(e)
The standard cut quadrature (cut_quadrature = 'standard') requires the level set function as a piecewise linear GridFunction, but a higher order GridFunction or a general CoefficientFunction was given. Use cut_quadrature = 'auto' or 'algoim' (Algoim-based quadrature w.r.t. the level set function itself), interpolate the level set function piecewise linearly (InterpolateToP1, e.g. for the isoparametric approach) or set subdivlvl > 0 (only for element integrals).
Convergence study with Algoim¶
We repeat the convergence study from above, now with the level set function of order \(k\) on the undeformed mesh:
[21]:
errors_algoim = dict()
eoc_algoim = dict()
for key in [NEG,POS,IF]:
errors_algoim[key] = []
for reflevel in range(refinements):
if(reflevel > 0):
mesh.Refine()
lset_ho.Set(levelset)
for key in [NEG,POS,IF]:
integral = Integrate(f * dCut(levelset=lset_ho, domain_type=key, order=k), mesh=mesh)
errors_algoim[key].append(abs(integral - referencevals[key]))
for key in [NEG,POS,IF]:
eoc_algoim[key] = [log(a/b)/log(2) for (a,b) in zip (errors_algoim[key][0:-1],errors_algoim[key][1:]) ]
print("errors ( algoim): \n{}\n".format( errors_algoim))
print(" eoc ( algoim): \n{}\n".format( eoc_algoim))
errors ( algoim):
{<DOMAIN_TYPE.NEG: 0>: [0.003953731524067194, 7.013020222590427e-05, 4.880738761148251e-06, 1.1626605944670132e-07, 4.5565062833929915e-10], <DOMAIN_TYPE.POS: 1>: [0.003953731524081405, 7.013020224899691e-05, 4.8807387873495145e-06, 1.1626611762238781e-07, 4.555040789000486e-10], <DOMAIN_TYPE.IF: 2>: [0.004053619850799883, 5.02721748549817e-05, 4.878310093658911e-06, 1.1297829782819235e-07, 3.9113068339702295e-10]}
eoc ( algoim):
{<DOMAIN_TYPE.NEG: 0>: [5.817035210625631, 3.8448644486866073, 5.391597624544147, 7.995286232388368], <DOMAIN_TYPE.POS: 1>: [5.817035210155764, 3.8448644414168434, 5.391596910412316, 7.995751038244159], <DOMAIN_TYPE.IF: 2>: [6.333306885035598, 3.365306731468042, 5.432263892207813, 8.174179237480939]}
The error decays (at least) with order \(k+1\), the order of the interpolation error of the level set function.
The same works on quadrilateral (and in 3D on hexahedral and prismatic) meshes:
[22]:
from ngsolve.meshes import MakeStructured2DMesh
quadmesh = MakeStructured2DMesh(quads=True, nx=12, ny=12, mapping=lambda x,y: (3*x-1.5, 3*y-1.5))
lset_quad = GridFunction(H1(quadmesh,order=k))
lset_quad.Set(levelset)
for key in [NEG,POS,IF]:
integral = Integrate(f * dCut(levelset=lset_quad, domain_type=key, order=k), mesh=quadmesh)
print(key, "error:", abs(integral - referencevals[key]))
DOMAIN_TYPE.NEG error: 2.8858348155580416e-08
DOMAIN_TYPE.POS error: 2.8858347711491206e-08
DOMAIN_TYPE.IF error: 2.1766402902301252e-08
Isoparametric mapping or Algoim?¶
Both approaches give a higher order accurate geometry approximation, and both are used with the same dCut syntax, also in bilinear and linear forms.
Isoparametric mapping: P1 level set function and cheap standard rules, but everything lives on a deformed mesh: the
deformationhas to be passed to (or set for) all integrals, and for moving domains functions have to be transferred between differently deformed meshes.Algoim: the mesh is not changed and the level set function can have any order (or be a
CoefficientFunction); quadrilaterals, hexahedra and prisms are supported; the same holds for facet integrals (skeleton=True,element_boundary=True), boundary integrals (vb=BND), multiple level sets (see mlset_basic.ipynb) and space-time integrals (see spacetime_unfitted.ipynb). The price is the cost of the quadrature: the rules have considerably more points, especially in 3D (several hundred points per cut element), and their construction is more expensive.
Further remarks:
orderis the polynomial degree of the integrand for which the rule is exact on domains with planar cuts. The (curved) geometry is resolved with at least \(k+1\) Gauss points per direction, also fororder=0.On meshes that are coarse compared to the curvature of the interface,
subdivlvl=nsubdivides every cut element \(n\) times before Algoim is applied.In 3D, level set polynomials of degree 4 and higher can become too expensive on coarse meshes (an exception tells you if this is the case). Then use a lower degree, a finer mesh or
subdivlvl.A CutFEM discretization with Algoim-based quadrature is shown in
demos/fictdom_algoim.py.
Literature:
[1]: R. I. Saye. High-order quadrature on multi-component domains implicitly defined by multivariate polynomials. Journal of Computational Physics, 448:110720, 2022. doi: 10.1016/j.jcp.2021.110720