Algorithmresearch
Virtual element method
Also called VEM.
A Galerkin method on general polygonal meshes whose basis functions are never computed; projections onto polynomials give the stiffness matrix.
- Solves
- Poisson equation
- Time
- Θ((i + 1) e m^2) worst
- Space
- Θ(n + e m^2) extra
- Where
- e = the number of polygons; i = the number of conjugate gradient iterations; m = the largest number of vertices of a polygon; n = the number of vertices
- Model
- Real RAM
- Properties
- not basis functions computeddeterministiciterativeneeds stabilizationpasses patch testpolygonal meshessymmetric positive definite
- Evidence
- Proof sketchCode in 1 languages
- Origin
- L. Beirão da Veiga, F. Brezzi, A. Cangiani, G. Manzini, L. D. Marini, A. Russo, 2013
The virtual element method (VEM) is a Galerkin method on meshes of general polygons in 2D or polyhedra in 3D. On each polygon, the local space contains the polynomials of degree and other functions that are defined as solutions of a local partial differential equation, so their values inside the polygon are never known. The method needs only the degrees of freedom, which for are the values at the vertices. From them it computes exactly the projection of each function onto the polynomials, and builds the stiffness matrix from two parts. The consistency part is the energy of the projections and is exact when one of the arguments is a polynomial. The stability part is a cheap symmetric form that controls the rest. The method passes the patch test on any polygonal mesh, it accepts nonconvex polygons and collinear vertices (hanging nodes), and on a triangle with it is the standard linear finite element.
In plain words
Standard finite elements need simple shapes such as triangles and squares, because each needs a formula for its basis functions. A mesh of general polygons, with any number of sides, is easier to make and to change, but formulas for its basis functions are hard to find. The virtual element method avoids them. It never asks what a basis function looks like inside a polygon. It only asks for a best straight fit of each function, and this fit comes from the values at the corners. The energy of the fits gives most of the stiffness matrix. A small extra term stops the parts that the fit cannot see from going free.
The problem
Input. A polygon in the plane, a mesh of by polygons that meet edge to edge (each polygon star shaped with respect to a disc, with vertices listed counterclockwise), a source and boundary values .
Output. Values at the vertices of the mesh and, on each polygon , a linear polynomial , which approximate the solution of in with on .
The local space. For ,
A function in is fixed by its values at the vertices of , because the harmonic function with given boundary values is unique. contains the linear polynomials. On a triangle is exactly the set of linear polynomials. On other polygons the basis functions (with ) are not polynomials and the method does not compute them.
The projection. is the linear polynomial with
The right side is computable: since and is constant, , and is linear on each edge, so the trapezoid rule on each edge is exact.
The algorithm
Use the scaled monomials , and , where is the diameter and the average of the vertices. Write for the edge from vertex to vertex , for its length and for its outward unit normal.
VEM-1(points, polygons, f, g, tau)- 1
for each polygon E with vertices v_1, ..., v_m: h <- diameter, (x_E, y_E) <- average of the vertices - 2
D[i, a] <- m_a(v_i) for i = 1..m, a = 1..3 - 3
B[1, i] <- 1/m; B[a, i] <- (|e_{i-1}| n_{i-1} + |e_i| n_i) . grad m_a / 2 for a = 2, 3 - 4
G <- B D; P* <- G^{-1} B; P <- D P* ▷ P* gives the coefficients of the projection - 5
K_E <- (P*)^T G~ P* + tau (I - P)^T (I - P); F_E[i] <- integral over E of f times (P* e_i) . m - 6
add K_E and F_E into the global matrix K and vector F - 7
set u = g at the boundary vertices and solve K u = F for the others by conjugate gradients - 8
return the vertex values u and the projections P* u_E on each polygon
Here is with its first row set to zero, so , which is on the diagonal for and zero elsewhere. Row of holds , computed from the boundary integral above: the trapezoid rule gives vertex half of each of its two edges. The load uses , a known linear function, in place of the unknown , and the reference code integrates it with a 7 point rule on the triangles from the vertex average to each edge. The dofi-dofi stabilization of line L5 is times the Euclidean inner product of the vertex values of and . In 2D with it has the right scaling for any polygon size, and is the common choice.
Example
The unit square. Take the vertices , , and . Then , the centre is , and with
For vertex 1, the edges and have and , and half their sum dotted with is . The diagonal of is . So has the rows , and . The consistency part is
It does not see the hourglass mode : the projection of is zero. So , and with the stabilization adds . The result has on the diagonal and in every other entry. The bilinear element on the same square has on the diagonal, for neighbours and for the opposite vertex. Both matrices give the same energy to every linear field, which is what the patch test needs, and differ only on the hourglass mode.
A triangle. On the triangle , , , , so the stabilization is zero for every and is the linear finite element matrix with rows , and . The reference test checks this with .
Convergence. The reference tests solve with on the boundary of the unit square. The meshes have cells. On the distorted mesh the interior grid nodes move by up to in each direction, and each cell edge gets a midpoint node with probability , so the cells have 4 to 8 vertices with collinear ones. The errors are those of the projections.
| cells per side | squares, | squares, | distorted, vertices | distorted, | distorted, |
|---|---|---|---|---|---|
| 4 | 39 | ||||
| 8 | 153 | ||||
| 16 | 575 | ||||
| 32 | 2146 |
The observed orders at the finest step are in and in on squares. On the distorted polygons they are between and in and between and in . These are the orders of linear finite elements. The largest vertex error on the distorted meshes converges with order between and .
The stabilization changes the answer. On the distorted mesh with 8 cells per side, , and give errors , and and errors , and . The rates do not depend on , but the constants do.
Correctness
The proof shows four facts. First, is nonsingular, and gives the exact coefficients of from the vertex values of , because the boundary integral with the trapezoid rule is exact for functions that are linear on each edge. Second (consistency), for every and every linear : the stabilization vanishes on , and the consistency part is the energy of the projection, which equals the energy of against . Third (stability), for , only for constants, so the global matrix is symmetric positive definite on the free vertices. Fourth (the patch test), if and is linear, the vertex values of solve the discrete system, so the method is exact on any mesh. The proof also gives the abstract error estimate, which bounds the energy error by interpolation and polynomial approximation errors. The bounds on these errors for star shaped polygons, which give order in and in , are cited from the 2013 paper and the 2023 survey.
Proof: The order 1 virtual element method is computable, consistent and stable, and it passes the patch testpartial
Setting
Let be a polygon and let the mesh cover by polygons that meet edge to edge. Each polygon has the vertices in counterclockwise order, with indices taken modulo . The edge goes from to , is its length and is its outward unit normal. Collinear vertices are allowed. The local space is
is the set of linear polynomials, is the diameter of , is the average of the vertices, and , , . The matrices , , , , and are those of lines L2 to L5. The local form is
and the global form is on the space of functions on whose restriction to each is in .
Lemma 1 (degrees of freedom)
The map from to its vertex values is a bijection onto , and .
Proof. Given values , there is exactly one continuous function on that is linear on each edge and has . The Dirichlet problem in , on has exactly one solution , because is the trace of an function (it is Lipschitz on ) and the Dirichlet form is coercive on . So each vector of values gives exactly one , and the values of give back . A linear has and is linear on each edge, so .
Lemma 2 (the matrix B)
For and , .
Proof. is a constant vector and , so Green's formula gives
On the function is linear, so the trapezoid rule is exact: . Collect the terms of . It gets half of and half of , so its coefficient is , which is line L3. For a counterclockwise polygon and the edge from to , . So , and with and this is the formula of the reference code.
Lemma 3 (the projection)
, so is nonsingular. For with vertex values , the vector holds the coefficients of in the basis , and .
Proof. Column of holds the vertex values of . Row 1 of is the vertex average, so is the vertex average of . This is for and for , because is the vertex average. For , Lemma 2 applied to gives . This is for , for and for , , because . So is diagonal with positive entries when , which holds for a counterclockwise polygon.
Write . The two conditions that define , tested with and with the vertex average, are the three equations : for the left side is and the right side is by Lemma 2, and for both sides are vertex averages. A general linear is a combination of , and , so these equations are all the conditions. Hence and . Finally .
So maps the vertex values of to the vertex values of , and is a projection: .
Lemma 4 (consistency)
For every and every , . In matrix form, where holds the vertex values of .
Proof. , because satisfies both defining conditions. So , and the stabilization term vanishes. In matrix form, . The consistency part is . By the definition of with the test polynomial , . In matrix form, is with the first row set to zero, and since its entries are for all . So , which is the consistency part.
Lemma 5 (stability of the local matrix)
is symmetric and positive semidefinite. For , only if is a constant vector.
Proof. Both parts of have the form with symmetric positive semidefinite ( restricted to rows and columns 2 and 3 is , and its first row and column are zero), so is symmetric positive semidefinite. Suppose . Both terms are nonnegative, so both vanish. The stabilization term is , so , and holds the vertex values of the linear polynomial . The consistency term is , so is constant, and is a constant vector. Constants do give zero, because their projection is the same constant.
Theorem 1 (the global system)
Let the mesh be connected (every two polygons are joined by a chain of polygons that share edges) and let at least one vertex carry a boundary value. For the global matrix restricted to the free vertices is symmetric positive definite. So line L7 has a unique solution, and conjugate gradients converge to it in exact arithmetic in at most as many steps as there are free vertices.
Proof. The global matrix , where picks the vertex values of from the global vector, is symmetric positive semidefinite by Lemma 5. Let be zero at the boundary vertices and . Then every term is zero, so is constant on the vertices of each polygon, by Lemma 5. Two polygons that share an edge share its end vertices, so the constants agree, and by connectedness is one constant everywhere. It is zero at a boundary vertex, so . The restriction of to the free vertices is therefore positive definite. The statement about conjugate gradients is the standard finite termination property for symmetric positive definite systems.
Theorem 2 (the patch test)
Let and for a linear . Then the vertex values of solve the global system of line L7, so the method returns at every vertex and on every polygon. This holds on every mesh that satisfies the assumptions of Theorem 1, for every , and convexity of the polygons is not used.
Proof. With the load is zero. The free rows of say that for every free vertex , where has the value at vertex and at the others. Edge conformity means that two polygons that share an edge list the same vertices on it, so the traces of from the two sides are the same piecewise linear function on the edge, and is continuous across the edge. Hence , and it vanishes on because is a free vertex. By Lemma 4 on each polygon,
by integration by parts with on and . So solves the free rows, and it has the right boundary values. By Theorem 1 the solution is unique, so the method returns . By Lemma 3 the projection of on each polygon is .
On a triangle by Lemma 1, since both have dimension 3. Then , the stabilization vanishes for every , and is the stiffness matrix of the linear Lagrange element. So on a triangle mesh the method is the linear finite element method.
Theorem 3 (abstract error estimate)
Let solve with on , and let be the discrete solution, with at the boundary vertices for an interpolant of . Assume stability: there are constants such that for every polygon and every ,
Let be any function that is linear on each polygon (it need not be continuous), and write for such functions. Let be the discrete load, with , where is the subspace of that vanishes on . Then
with depending only on and .
Proof. Let . By the lower stability bound and the discrete equation ,
On each , add and subtract and use Lemma 4 with the polynomial :
The sum over of the last terms is , since by edge conformity. So
The local form is symmetric and positive semidefinite, so Cauchy-Schwarz and the upper bound give for . The function is in on each , since . Hence
Divide by (the case is trivial) and use . This gives . Then gives the bound with the common constant .
Remark 1 (what the reference code computes)
The code builds from lines L2 to L5 with exactly the matrices of Lemmas 2 and 3, and the load from with a quadrature rule. With this load is zero, so Theorem 2 applies to the code up to rounding and the stopping test of conjugate gradients. The tests check the hand computed matrix of the unit square, the identity on random polygons with 3 to 9 vertices, Lemma 4 as , the symmetry of and the constants in its kernel, the reduction to the linear element on a triangle, and the patch test on a jittered mesh with hanging nodes for , and .
Remark 2 (rates, cited)
Theorem 3 reduces the convergence rate to three approximation results: an interpolation estimate in , a polynomial approximation estimate on each polygon, and a bound for the load error. Under the mesh assumptions of the 2013 paper of Beirão da Veiga, Brezzi, Cangiani, Manzini, Marini and Russo (each star shaped with respect to a disc of radius at least , and each edge of length at least , for a fixed ), these give for , and on convex a duality argument gives in . The same assumptions give the stability bounds and for the dofi-dofi stabilization, with constants that depend on and . This proof does not reproduce these estimates. They are taken from the 2013 paper and the 2023 survey in Acta Numerica, and the reference tests only observe them numerically. That is why the status of this proof is partial.
Complexity
For a polygon with vertices, lines L2 to L4 cost , the products in line L5 cost , and the load with quadrature points costs . Assembly therefore costs time, and the global matrix has nonzero entries. Each conjugate gradient iteration costs one product with it, so the total time is . On quasi uniform meshes the condition number grows like , so grows like for a fixed tolerance, and a direct sparse solver or a multigrid preconditioner does better on large problems. The memory is .
Properties
- Any polygon. The same code handles triangles, quadrilaterals, Voronoi cells, nonconvex star shaped cells and cells with collinear vertices. A hanging node is just one more vertex.
- Exact on linear fields. The patch test holds on every mesh and for every , because the consistency part is exact and the stabilization vanishes on polynomials.
- No basis functions. Only vertex coordinates and values enter the matrices. No mapping to a reference element and no quadrature of the unknown basis functions is needed for the stiffness.
- Reduces to finite elements on triangles. For on a triangle, the local space is linear, the stabilization vanishes and the method is the linear Lagrange element.
- The stabilization is a choice. The consistency part fixes the matrix on polynomials only. The stabilization changes the matrix on the other functions and the error constants, but not the rates, as long as it is bounded above and below by the energy on the functions with zero projection.
Variants and improvements
- Higher order. For degree , the unknowns are the vertex values, values on each edge and the moments against polynomials of degree inside. The projection then also needs these moments.
- Enhanced spaces. A modified local space makes the projection onto polynomials of degree computable, which gives a better load term and is needed for reaction and time dependent terms.
- Other stabilizations. The trace stabilization integrates the tangential derivative along the boundary, and the diagonal recipe scales each vertex term by the diagonal of the consistency part. These are more robust for elements with very short edges or high aspect ratios.
- Other equations. Linear and nonlinear elasticity, plates, Stokes flow, Maxwell equations and mixed forms have virtual elements. The H(div) and H(curl) versions connect with the mixed finite element method.
- Related methods. Mimetic finite differences have the same algebra for , and polygonal finite elements with generalized barycentric coordinates compute the basis functions that VEM avoids. The discontinuous Galerkin method also works on polygons but has more unknowns.
When to use it
Use it when the mesh is naturally polygonal: Voronoi meshes of Voronoi diagrams, agglomerated or coarsened meshes, meshes of fractured or layered media, meshes that are cut by an interface, and adaptive meshes with hanging nodes. It is also useful in fracture and topology optimization, where elements are cut or merged during the computation. On simplex meshes, standard finite elements are simpler and do the same job.
Pitfalls
- Polygons that are not star shaped. The theory needs each polygon to be star shaped with respect to a disc of radius comparable to its diameter. Very thin polygons, or tiny edges next to long ones, can make the default stabilization too weak or too strong.
- Forgetting the stabilization. With the matrix is singular on the functions with zero projection, such as the hourglass mode of a square. The global matrix can then be singular or very badly conditioned.
- The answer depends on . In the reference test, gives an error 4 times larger than . Do not tune to the test problem. Use a recipe with a fixed scaling.
- Errors of the virtual function. is not known inside a polygon. Measure errors with or with the vertex values, and say which. Post processing that needs pointwise values must use the projection.
- Clockwise polygons. The formulas of line L3 assume counterclockwise vertices. A clockwise polygon flips the sign of rows 2 and 3 of and of the block of that holds , so stays the same but the consistency part changes sign and is indefinite. Check the sign of the polygon area first.
- Edge conformity. Two neighbouring polygons must list the same vertices on their common edge. A hanging node that only one polygon lists makes the method nonconforming and the patch test fails.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and error norms for the scientific-computing pages.
A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.
API (fixed; other pages copy this file byte for byte):
zeros(m, n=None) m by n zero matrix (n = m if not given)
eye(n) n by n identity
add(A, B), sub(A, B) entrywise sum and difference (vectors or matrices)
scale(c, A) c times A (vector or matrix)
matmul(A, B) matrix product
matvec(A, x) matrix times vector
transpose(A) transpose
dot(x, y) inner product of two vectors
norm2(x) Euclidean norm of a vector, as a float
outer(x, y) outer product x y^T
solve(A, b) Gaussian elimination with partial pivoting;
b is a vector or a matrix of right sides
inv(A) inverse of A
det(A) determinant of A
cholesky(A) lower triangular L with A = L L^T (floats)
cholesky_solve(L, b) solve L L^T x = b for a vector b
err_l1(e, dx=1) sum |e_j| dx
err_l2(e, dx=1) sqrt(sum e_j^2 dx), as a float
err_linf(e, dx=1) max |e_j| (dx is not used)
observed_order(errors) [log2(E_i / E_(i+1)) for successive errors]
"""
import math
def zeros(m, n=None):
"""Return an m by n matrix of zeros (n = m if n is None)."""
if n is None:
n = m
return [[0] * n for _ in range(m)]
def eye(n):
"""Return the n by n identity matrix."""
out = zeros(n, n)
for i in range(n):
out[i][i] = 1
return out
def _is_matrix(a):
return len(a) > 0 and isinstance(a[0], list)
def add(a, b):
"""Return a + b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x + y for x, y in zip(a, b)]
def sub(a, b):
"""Return a - b for two vectors or two matrices of the same shape."""
if _is_matrix(a):
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
return [x - y for x, y in zip(a, b)]
def scale(c, a):
"""Return c times a, for a vector or a matrix a."""
if _is_matrix(a):
return [[c * x for x in row] for row in a]
return [c * x for x in a]
def transpose(a):
"""Return the transpose of the matrix a."""
return [list(col) for col in zip(*a)]
def matmul(a, b):
"""Return the matrix product a b."""
bt = transpose(b)
return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]
def matvec(a, x):
"""Return the product of the matrix a and the vector x."""
return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]
def dot(x, y):
"""Return the inner product of the vectors x and y."""
return sum(a * b for a, b in zip(x, y))
def norm2(x):
"""Return the Euclidean norm of the vector x, as a float."""
return math.sqrt(float(dot(x, x)))
def outer(x, y):
"""Return the outer product x y^T as a matrix."""
return [[a * b for b in y] for a in x]
def _eliminate(a, rhs):
"""Reduce a to upper triangular form with partial pivoting.
a is a copy of the square matrix, rhs a list of right side rows (one
row per row of a) that receives the same row operations. Return the
number of row swaps. Raise ValueError if a pivot is zero.
"""
n = len(a)
swaps = 0
for k in range(n):
p = max(range(k, n), key=lambda i: abs(a[i][k]))
if a[p][k] == 0:
raise ValueError("matrix is singular")
if p != k:
a[k], a[p] = a[p], a[k]
rhs[k], rhs[p] = rhs[p], rhs[k]
swaps += 1
for i in range(k + 1, n):
f = a[i][k] / a[k][k]
if f == 0:
continue
for j in range(k, n):
a[i][j] -= f * a[k][j]
for j in range(len(rhs[i])):
rhs[i][j] -= f * rhs[k][j]
return swaps
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a vector (the result is a vector) or a matrix with one column per
right side (the result is a matrix). Fraction entries stay exact.
Raise ValueError if a is singular.
"""
n = len(a)
work = [list(row) for row in a]
vector = not _is_matrix(b)
rhs = [[v] for v in b] if vector else [list(row) for row in b]
_eliminate(work, rhs)
m = len(rhs[0]) if n else 0
x = [[0] * m for _ in range(n)]
for i in range(n - 1, -1, -1):
for j in range(m):
s = rhs[i][j]
for k in range(i + 1, n):
s -= work[i][k] * x[k][j]
x[i][j] = s / work[i][i]
if vector:
return [row[0] for row in x]
return x
def inv(a):
"""Return the inverse of the square matrix a."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of the square matrix a (0 if singular)."""
work = [list(row) for row in a]
rhs = [[] for _ in a]
try:
swaps = _eliminate(work, rhs)
except ValueError:
return 0
d = -1 if swaps % 2 else 1
for i in range(len(a)):
d *= work[i][i]
return d
def cholesky(a):
"""Return the lower triangular L with a = L L^T, in floats.
Raise ValueError if a is not symmetric positive definite.
"""
n = len(a)
low = [[0.0] * n for _ in range(n)]
for j in range(n):
s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
if s <= 0.0:
raise ValueError("matrix is not positive definite")
low[j][j] = math.sqrt(s)
for i in range(j + 1, n):
t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
low[i][j] = t / low[j][j]
return low
def cholesky_solve(low, b):
"""Solve L L^T x = b, with L from cholesky, for a vector b."""
n = len(low)
y = [0.0] * n
for i in range(n):
y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
return x
def err_l1(e, dx=1):
"""Return the discrete L1 norm sum |e_j| dx."""
return sum(abs(v) for v in e) * dx
def err_l2(e, dx=1):
"""Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
return math.sqrt(float(sum(v * v for v in e) * dx))
def err_linf(e, dx=1):
"""Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
return max(abs(v) for v in e)
def observed_order(errors):
"""Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
virtual_element_method.py 197 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/virtual-element-method/. The authors are listed in prov/EYHGHZ.jsonl.
"""Virtual element method of order 1 for -Laplace(u) = f in two dimensions.
The mesh is a list of polygons, each a counterclockwise list of vertex
indices. A polygon may have any number of vertices, collinear vertices
(hanging nodes) included. The local space has one unknown per vertex, the
value there. The basis functions are harmonic inside the polygon and are
never computed: the element matrices come from the elliptic projection onto
linear polynomials, which only needs the vertex values.
"""
import math
import random
import scimat
# Dunavant's 7 point rule on the reference triangle, exact up to degree 5 (barycentric, weight)
_T7 = [((1 / 3, 1 / 3, 1 / 3), 0.225)]
for _a, _b, _w in ((0.059715871789770, 0.470142064105115, 0.132394152788506),
(0.797426985353087, 0.101286507323456, 0.125939180544827)):
_T7 += [((_a, _b, _b), _w), ((_b, _a, _b), _w), ((_b, _b, _a), _w)]
def polygon_area(pts):
"""Return the signed area of a polygon (positive when counterclockwise), by the shoelace formula."""
m = len(pts)
return sum(pts[i][0] * pts[(i + 1) % m][1] - pts[(i + 1) % m][0] * pts[i][1] for i in range(m)) / 2
def polygon_quadrature(pts):
"""Return (point, weight) pairs on a polygon that is star shaped with respect to its vertex centroid."""
m = len(pts)
cx, cy = sum(p[0] for p in pts) / m, sum(p[1] for p in pts) / m
out = []
for i in range(m):
(x1, y1), (x2, y2) = pts[i], pts[(i + 1) % m]
area = ((x1 - cx) * (y2 - cy) - (x2 - cx) * (y1 - cy)) / 2
for (l0, l1, l2), w in _T7:
out.append(((l0 * cx + l1 * x1 + l2 * x2, l0 * cy + l1 * y1 + l2 * y2), w * area))
return out
def element_matrices(pts, tau=1.0):
"""Return (K, pstar, centre, h) for one polygon with counterclockwise vertices pts.
pstar is the 3 x m matrix of the projection onto the scaled monomials
1, (x - xc) / h, (y - yc) / h; K is the m x m local stiffness matrix.
"""
m = len(pts)
h = max(math.dist(p, q) for p in pts for q in pts)
xc, yc = sum(p[0] for p in pts) / m, sum(p[1] for p in pts) / m # @line L1
d = [[1.0, (x - xc) / h, (y - yc) / h] for x, y in pts] # @line L2
b = [[1 / m] * m, [0.0] * m, [0.0] * m]
for i in range(m):
# (|e_{i-1}| n_{i-1} + |e_i| n_i) / 2, where |e| n of the edge from p to q is (q_y - p_y, p_x - q_x)
(xp, yp), (xn, yn) = pts[i - 1], pts[(i + 1) % m]
nx, ny = (yn - yp) / 2, (xp - xn) / 2
b[1][i] = nx / h
b[2][i] = ny / h # @line L3
g = scimat.matmul(b, d)
pstar = scimat.solve(g, b)
proj = scimat.matmul(d, pstar) # @line L4
gt = [[0.0] * 3] + g[1:]
cons = scimat.matmul(scimat.transpose(pstar), scimat.matmul(gt, pstar))
ip = scimat.sub(scimat.eye(m), proj)
stab = scimat.matmul(scimat.transpose(ip), ip)
k = scimat.add(cons, scimat.scale(tau, stab)) # @line L5
return k, pstar, (xc, yc), h
def _projected(pstar, centre, h, values, x):
"""Return (value, gradient) at x of the linear projection of the given vertex values."""
c = [sum(pstar[a][i] * v for i, v in enumerate(values)) for a in range(3)]
return c[0] + c[1] * (x[0] - centre[0]) / h + c[2] * (x[1] - centre[1]) / h, (c[1] / h, c[2] / h)
def solve_vem(points, polygons, boundary, f, g, tau=1.0, tol=1e-14):
"""Assemble and solve the order 1 VEM system. Return (u, elements).
u holds the vertex values; elements holds (pstar, centre, h) per polygon.
boundary is the set of vertex indices where u = g(x, y) is imposed.
"""
n = len(points)
rows = [dict() for _ in range(n)]
rhs = [0.0] * n
elements = []
for poly in polygons:
pts = [points[i] for i in poly]
k, pstar, centre, h = element_matrices(pts, tau)
elements.append((pstar, centre, h))
for (xq, wq) in polygon_quadrature(pts):
fq = f(*xq) * wq
for i, gi in enumerate(poly):
phi = pstar[0][i] + pstar[1][i] * (xq[0] - centre[0]) / h + pstar[2][i] * (xq[1] - centre[1]) / h
rhs[gi] += fq * phi
for i, gi in enumerate(poly):
for j, gj in enumerate(poly):
rows[gi][gj] = rows[gi].get(gj, 0.0) + k[i][j] # @line L6
u = [g(*points[i]) if i in boundary else 0.0 for i in range(n)]
free = [i for i in range(n) if i not in boundary]
index = {gi: r for r, gi in enumerate(free)}
a = [{index[j]: v for j, v in rows[i].items() if j in index} for i in free]
b = [rhs[i] - sum(v * u[j] for j, v in rows[i].items() if j in boundary) for i in free]
x = conjugate_gradient(a, b, tol) # @line L7
for r, gi in enumerate(free):
u[gi] = x[r]
return u, elements # @line L8
def conjugate_gradient(a, b, tol=1e-14, maxit=None):
"""Solve a x = b for a symmetric positive definite matrix stored as a list of row dicts."""
n = len(b)
x = [0.0] * n
r = list(b)
p = list(r)
rr = scimat.dot(r, r)
stop = tol * tol * max(rr, 1e-300)
for _ in range(maxit or 10 * n + 10):
if rr <= stop:
break
ap = [sum(v * p[j] for j, v in row.items()) for row in a]
alpha = rr / scimat.dot(p, ap)
x = [xi + alpha * pi for xi, pi in zip(x, p)]
r = [ri - alpha * api for ri, api in zip(r, ap)]
rr_new = scimat.dot(r, r)
p = [ri + rr_new / rr * pi for ri, pi in zip(r, p)]
rr = rr_new
return x
def errors(points, polygons, u, elements, exact, grad):
"""Return (L2 error, H1 seminorm error) of the projections of u_h, and the largest vertex error."""
e0 = e1 = 0.0
for poly, (pstar, centre, h) in zip(polygons, elements):
pts = [points[i] for i in poly]
vals = [u[i] for i in poly]
for xq, wq in polygon_quadrature(pts):
v, (gx, gy) = _projected(pstar, centre, h, vals, xq)
ex, (ux, uy) = exact(*xq), grad(*xq)
e0 += wq * (v - ex) ** 2
e1 += wq * ((gx - ux) ** 2 + (gy - uy) ** 2)
emax = max(abs(u[i] - exact(*p)) for i, p in enumerate(points))
return math.sqrt(e0), math.sqrt(e1), emax
def polygon_mesh(n, seed=0, jitter=0.0, midpoint_prob=0.0):
"""Return (points, polygons, boundary) for the unit square.
The square is cut into n x n cells, the interior grid nodes move by up to
jitter * (1 / n) in each direction, and each cell edge gets a midpoint
node with probability midpoint_prob. A cell then has 4 to 8 vertices.
"""
rng = random.Random(seed)
h = 1 / n
points = []
for j in range(n + 1):
for i in range(n + 1):
x, y = i * h, j * h
if 0 < i < n and 0 < j < n:
x += rng.uniform(-jitter, jitter) * h
y += rng.uniform(-jitter, jitter) * h
points.append((x, y))
boundary = {i + j * (n + 1) for j in range(n + 1) for i in range(n + 1) if i in (0, n) or j in (0, n)}
mids = {}
def node(i, j):
return i + j * (n + 1)
def midpoint(p, q, on_boundary):
key = (min(p, q), max(p, q))
if key not in mids:
if rng.random() < midpoint_prob:
(x1, y1), (x2, y2) = points[p], points[q]
points.append(((x1 + x2) / 2, (y1 + y2) / 2))
mids[key] = len(points) - 1
if on_boundary:
boundary.add(mids[key])
else:
mids[key] = None
return mids[key]
polygons = []
for j in range(n):
for i in range(n):
corners = [node(i, j), node(i + 1, j), node(i + 1, j + 1), node(i, j + 1)]
sides = [j == 0, i == n - 1, j == n - 1, i == 0]
poly = []
for s in range(4):
p, q = corners[s], corners[(s + 1) % 4]
poly.append(p)
mid = midpoint(p, q, sides[s])
if mid is not None:
poly.append(mid)
polygons.append(poly)
return points, polygons, boundary
test_virtual_element_method.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/virtual-element-method/. The authors are listed in prov/EYHGHZ.jsonl.
import math
import random
import scimat
from virtual_element_method import (
conjugate_gradient,
element_matrices,
errors,
polygon_area,
polygon_mesh,
polygon_quadrature,
solve_vem,
)
SQUARE = [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0)]
def u_sin(x, y):
return math.sin(math.pi * x) * math.sin(math.pi * y)
def grad_sin(x, y):
return (math.pi * math.cos(math.pi * x) * math.sin(math.pi * y), math.pi * math.sin(math.pi * x) * math.cos(math.pi * y))
def f_sin(x, y):
return 2 * math.pi ** 2 * u_sin(x, y)
def random_polygon(rng, m):
"""A convex polygon: m sorted angles on a jittered ellipse."""
angles = sorted(rng.uniform(0, 2 * math.pi) for _ in range(m))
a, b = rng.uniform(0.5, 2), rng.uniform(0.5, 2)
return [(3 + a * math.cos(t), -1 + b * math.sin(t)) for t in angles]
def test_unit_square_hand_example():
k, pstar, centre, h = element_matrices(SQUARE)
expected = [[0.75 if i == j else -0.25 for j in range(4)] for i in range(4)]
assert all(abs(k[i][j] - expected[i][j]) < 1e-14 for i in range(4) for j in range(4))
assert centre == (0.5, 0.5) and abs(h - math.sqrt(2)) < 1e-15
# without stabilization the hourglass mode costs no energy
k0, _, _, _ = element_matrices(SQUARE, tau=0.0)
hourglass = [1.0, -1.0, 1.0, -1.0]
assert max(abs(v) for v in scimat.matvec(k0, hourglass)) < 1e-14
assert max(abs(v) for v in scimat.matvec(k, hourglass)) > 0.9
def test_quadrature_is_exact_to_degree_5():
pts = [(0.0, 0.0), (2.0, 0.0), (2.0, 1.0), (0.0, 1.0)]
q = polygon_quadrature(pts)
for p in range(6):
for r in range(6 - p):
exact = 2 ** (p + 1) / (p + 1) / (r + 1)
assert abs(sum(w * x ** p * y ** r for (x, y), w in q) - exact) < 1e-12
def test_projection_reproduces_linear_polynomials():
rng = random.Random(5)
for m in range(3, 10):
pts = random_polygon(rng, m)
assert polygon_area(pts) > 0
k, pstar, centre, h = element_matrices(pts)
for c0, c1, c2 in ((1, 0, 0), (0, 1, 0), (0, 0, 1), (0.3, -2, 1.5)):
vals = [c0 + c1 * x + c2 * y for x, y in pts]
coef = scimat.matvec(pstar, vals)
# the projection is the polynomial itself
for x, y in pts:
p = coef[0] + coef[1] * (x - centre[0]) / h + coef[2] * (y - centre[1]) / h
assert abs(p - (c0 + c1 * x + c2 * y)) < 1e-12
# consistency: v^T K p is the exact energy of the projections
v = [rng.uniform(-1, 1) for _ in range(m)]
gv = scimat.matvec(pstar, v)
exact = polygon_area(pts) * (gv[1] / h * c1 + gv[2] / h * c2)
assert abs(scimat.dot(v, scimat.matvec(k, vals)) - exact) < 1e-11
def test_element_matrix_is_symmetric_with_constants_in_the_kernel():
rng = random.Random(6)
for m in (3, 5, 8):
k, _, _, _ = element_matrices(random_polygon(rng, m))
assert all(abs(k[i][j] - k[j][i]) < 1e-14 for i in range(m) for j in range(m))
assert all(abs(sum(row)) < 1e-13 for row in k)
def test_triangle_gives_the_linear_finite_element_matrix():
tri = [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)]
k, _, _, _ = element_matrices(tri, tau=7.0)
p1 = [[1.0, -0.5, -0.5], [-0.5, 0.5, 0.0], [-0.5, 0.0, 0.5]]
assert all(abs(k[i][j] - p1[i][j]) < 1e-14 for i in range(3) for j in range(3))
def test_patch_test_on_polygons_with_hanging_nodes():
pts, polys, bnd = polygon_mesh(6, seed=2, jitter=0.25, midpoint_prob=0.6)
assert max(len(p) for p in polys) >= 7
def lin(x, y):
return 1 + 2 * x - 3 * y
for tau in (0.1, 1.0, 10.0):
u, elements = solve_vem(pts, polys, bnd, lambda x, y: 0.0, lin, tau=tau)
assert max(abs(u[i] - lin(*p)) for i, p in enumerate(pts)) < 1e-11
e0, e1, _ = errors(pts, polys, u, elements, lin, lambda x, y: (2.0, -3.0))
assert e0 < 1e-11 and e1 < 1e-10
def test_convergence_on_square_cells():
errs = []
for n in (4, 8, 16):
pts, polys, bnd = polygon_mesh(n)
u, elements = solve_vem(pts, polys, bnd, f_sin, lambda x, y: 0.0)
errs.append(errors(pts, polys, u, elements, u_sin, grad_sin))
r0 = scimat.observed_order([e[0] for e in errs])
r1 = scimat.observed_order([e[1] for e in errs])
assert abs(r0[-1] - 2) < 0.05 and abs(r1[-1] - 1) < 0.05
def test_convergence_on_distorted_polygons():
errs = []
for n in (4, 8, 16):
pts, polys, bnd = polygon_mesh(n, seed=3, jitter=0.2, midpoint_prob=0.5)
u, elements = solve_vem(pts, polys, bnd, f_sin, lambda x, y: 0.0)
errs.append(errors(pts, polys, u, elements, u_sin, grad_sin))
r0 = scimat.observed_order([e[0] for e in errs])
r1 = scimat.observed_order([e[1] for e in errs])
assert r0[-1] > 1.9 and r1[-1] > 0.9
def test_stabilization_changes_the_answer_but_not_the_accuracy():
pts, polys, bnd = polygon_mesh(8, seed=1, jitter=0.2, midpoint_prob=0.5)
results = []
for tau in (0.25, 1.0, 4.0):
u, elements = solve_vem(pts, polys, bnd, f_sin, lambda x, y: 0.0, tau=tau)
results.append((u, errors(pts, polys, u, elements, u_sin, grad_sin)))
diff = max(abs(a - b) for a, b in zip(results[0][0], results[2][0]))
assert diff > 1e-4
assert all(r[1][1] < 0.45 for r in results)
def test_conjugate_gradient_on_a_small_system():
a = [{0: 4.0, 1: 1.0}, {0: 1.0, 1: 3.0}]
x = conjugate_gradient(a, [1.0, 2.0])
assert abs(x[0] - 1 / 11) < 1e-14 and abs(x[1] - 7 / 11) < 1e-14
History
Mimetic finite difference methods for diffusion on polyhedral meshes, developed in the 2000s by Brezzi, Lipnikov, Shashkov, Manzini and others, already had the algebra of the order 1 method. Beirão da Veiga, Brezzi, Cangiani, Manzini, Marini and Russo in 2013 recast it as a Galerkin method with a virtual local space and called it the virtual element method. The hitchhiker's guide of 2014 gave the matrix formulas for implementation, and Sutton in 2017 published a short MATLAB code that made the method widely known. The survey of Beirão da Veiga, Brezzi, Marini and Russo in Acta Numerica 2023 describes the theory and the many extensions.
References
- F. Brezzi, K. Lipnikov and M. Shashkov, Convergence of the mimetic finite difference method for diffusion problems on polyhedral meshes, SIAM Journal on Numerical Analysis 43(5) (2005) 1872-1896, the mimetic finite difference method for diffusion on polyhedral meshes that the order 1 virtual element method grew out of
- L. Beirão da Veiga, F. Brezzi, A. Cangiani, G. Manzini, L. D. Marini and A. Russo, Basic principles of virtual element methods, Mathematical Models and Methods in Applied Sciences 23(1) (2013) 199-214, the local virtual space, the degrees of freedom, the consistency and stability conditions and the abstract error estimate
- L. Beirão da Veiga, F. Brezzi, L. D. Marini and A. Russo, The hitchhiker's guide to the virtual element method, Mathematical Models and Methods in Applied Sciences 24(8) (2014) 1541-1573, the matrices D, B and G, the projection, the dofi-dofi stabilization and the load term, written for implementation
- O. J. Sutton, The virtual element method in 50 lines of MATLAB, Numerical Algorithms 75(4) (2017) 1141-1159, a complete implementation of the order 1 method on polygonal meshes with the same matrices and stabilization
- L. Beirão da Veiga, F. Brezzi, L. D. Marini and A. Russo, The virtual element method, Acta Numerica 32 (2023) 123-202, the survey of the theory, the error estimates on star shaped polygons, the choices of stabilization and the extensions
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag EYHGHZ Edit this page History Report an error Markdown