Algorithm Search⌘K

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.

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
Properties
not basis functions computeddeterministiciterativeneeds stabilizationpasses patch testpolygonal meshessymmetric positive definite
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 kk 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 k=1k = 1 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 k=1k = 1 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 Ω\Omega in the plane, a mesh of Ω\Omega by ee polygons that meet edge to edge (each polygon star shaped with respect to a disc, with vertices listed counterclockwise), a source ff and boundary values gg.

Output. Values uIu_I at the nn vertices of the mesh and, on each polygon EE, a linear polynomial ΠE∇uh\Pi^\nabla_E u_h, which approximate the solution of −Δu=f-\Delta u = f in Ω\Omega with u=gu = g on ∂Ω\partial\Omega.

The local space. For k=1k = 1,

VE={v∈H1(E):Δv=0 in E, v is continuous on ∂E and linear on each edge}.V_E = \{v \in H^1(E) : \Delta v = 0 \text{ in } E,\ v \text{ is continuous on } \partial E \text{ and linear on each edge}\}.

A function in VEV_E is fixed by its values at the vertices of EE, because the harmonic function with given boundary values is unique. VEV_E contains the linear polynomials. On a triangle VEV_E is exactly the set of linear polynomials. On other polygons the basis functions φi\varphi_i (with φi(vj)=δij\varphi_i(v_j) = \delta_{ij}) are not polynomials and the method does not compute them.

The projection. ΠE∇v\Pi^\nabla_E v is the linear polynomial with

∫E∇ΠE∇v⋅∇p dx=∫E∇v⋅∇p dx  for all linear p,1m∑i=1mΠE∇v(vi)=1m∑i=1mv(vi).\int_E \nabla \Pi^\nabla_E v \cdot \nabla p\,dx = \int_E \nabla v \cdot \nabla p\,dx \ \text{ for all linear } p, \qquad \frac1m \sum_{i=1}^m \Pi^\nabla_E v(v_i) = \frac1m \sum_{i=1}^m v(v_i).

The right side is computable: since Δp=0\Delta p = 0 and ∇p\nabla p is constant, ∫E∇v⋅∇p=∫∂Ev ∇p⋅n ds\int_E \nabla v \cdot \nabla p = \int_{\partial E} v\,\nabla p \cdot n\,ds, and vv is linear on each edge, so the trapezoid rule on each edge is exact.

The algorithm

Use the scaled monomials m1=1m_1 = 1, m2=(x−xE)/hEm_2 = (x - x_E)/h_E and m3=(y−yE)/hEm_3 = (y - y_E)/h_E, where hEh_E is the diameter and (xE,yE)(x_E, y_E) the average of the vertices. Write eie_i for the edge from vertex ii to vertex i+1i + 1, ∣ei∣|e_i| for its length and nin_i for its outward unit normal.

  1. VEM-1(points, polygons, f, g, tau)
  2. 1for each polygon E with vertices v_1, ..., v_m: h <- diameter, (x_E, y_E) <- average of the vertices
  3. 2D[i, a] <- m_a(v_i) for i = 1..m, a = 1..3
  4. 3B[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
  5. 4G <- B D; P* <- G^{-1} B; P <- D P* ▷ P* gives the coefficients of the projection
  6. 5K_E <- (P*)^T G~ P* + tau (I - P)^T (I - P); F_E[i] <- integral over E of f times (P* e_i) . m
  7. 6add K_E and F_E into the global matrix K and vector F
  8. 7set u = g at the boundary vertices and solve K u = F for the others by conjugate gradients
  9. 8return the vertex values u and the projections P* u_E on each polygon

Here G~\tilde G is GG with its first row set to zero, so G~ab=∫E∇ma⋅∇mb\tilde G_{ab} = \int_E \nabla m_a \cdot \nabla m_b, which is ∣E∣/hE2|E|/h_E^2 on the diagonal for a,b≥2a, b \ge 2 and zero elsewhere. Row a≥2a \ge 2 of BB holds ∫E∇φi⋅∇ma\int_E \nabla\varphi_i \cdot \nabla m_a, computed from the boundary integral above: the trapezoid rule gives vertex ii half of each of its two edges. The load uses ΠE∇φi\Pi^\nabla_E \varphi_i, a known linear function, in place of the unknown φi\varphi_i, 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 τ\tau times the Euclidean inner product of the vertex values of (I−Π)v(I - \Pi)v and (I−Π)w(I - \Pi)w. In 2D with k=1k = 1 it has the right scaling for any polygon size, and τ=1\tau = 1 is the common choice.

Example

The unit square. Take the vertices (0,0)(0, 0), (1,0)(1, 0), (1,1)(1, 1) and (0,1)(0, 1). Then h=2h = \sqrt 2, the centre is (12,12)(\tfrac12, \tfrac12), and with s=1/(22)s = 1/(2\sqrt 2)

D=(1−s−s1s−s1ss1−ss),B=(14141414−sss−s−s−sss),G=BD=(10001200012).D = \begin{pmatrix} 1 & -s & -s \\ 1 & s & -s \\ 1 & s & s \\ 1 & -s & s \end{pmatrix}, \qquad B = \begin{pmatrix} \frac14 & \frac14 & \frac14 & \frac14 \\ -s & s & s & -s \\ -s & -s & s & s \end{pmatrix}, \qquad G = BD = \begin{pmatrix} 1 & 0 & 0 \\ 0 & \frac12 & 0 \\ 0 & 0 & \frac12 \end{pmatrix}.

For vertex 1, the edges e4e_4 and e1e_1 have ∣e∣ n=(−1,0)|e|\,n = (-1, 0) and (0,−1)(0, -1), and half their sum dotted with ∇m2=(1/h,0)\nabla m_2 = (1/h, 0) is −1/(2h)=−s-1/(2h) = -s. The diagonal of GG is ∣E∣/h2=12|E|/h^2 = \tfrac12. So P∗=G−1BP^* = G^{-1}B has the rows 14(1,1,1,1)\tfrac14(1, 1, 1, 1), 2s(−1,1,1,−1)2s(-1, 1, 1, -1) and 2s(−1,−1,1,1)2s(-1, -1, 1, 1). The consistency part is

(P∗)⊤G~P∗=12(10−10010−1−10100−101).(P^*)^\top \tilde G P^* = \frac12\begin{pmatrix} 1 & 0 & -1 & 0 \\ 0 & 1 & 0 & -1 \\ -1 & 0 & 1 & 0 \\ 0 & -1 & 0 & 1 \end{pmatrix}.

It does not see the hourglass mode w=(1,−1,1,−1)w = (1, -1, 1, -1): the projection of ww is zero. So I−P=14ww⊤I - P = \tfrac14 w w^\top, and with τ=1\tau = 1 the stabilization adds 14ww⊤\tfrac14 w w^\top. The result has 34\tfrac34 on the diagonal and −14-\tfrac14 in every other entry. The bilinear element on the same square has 23\tfrac23 on the diagonal, −16-\tfrac16 for neighbours and −13-\tfrac13 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 (0,0)(0, 0), (1,0)(1, 0), (0,1)(0, 1), P=IP = I, so the stabilization is zero for every τ\tau and KEK_E is the linear finite element matrix with rows (1,−12,−12)(1, -\tfrac12, -\tfrac12), (−12,12,0)(-\tfrac12, \tfrac12, 0) and (−12,0,12)(-\tfrac12, 0, \tfrac12). The reference test checks this with τ=7\tau = 7.

Convergence. The reference tests solve −Δu=2π2sin⁡πxsin⁡πy-\Delta u = 2\pi^2 \sin\pi x \sin\pi y with u=0u = 0 on the boundary of the unit square. The meshes have n×nn \times n cells. On the distorted mesh the interior grid nodes move by up to 0.2/n0.2/n in each direction, and each cell edge gets a midpoint node with probability 12\tfrac12, so the cells have 4 to 8 vertices with collinear ones. The errors are those of the projections.

cells per side squares, L2L^2 squares, H1H^1 distorted, vertices distorted, L2L^2 distorted, H1H^1
4 0.04920.0492 0.6990.699 39 0.05290.0529 0.7200.720
8 0.01230.0123 0.3540.354 153 0.01320.0132 0.3620.362
16 0.003070.00307 0.1780.178 575 0.003360.00336 0.1840.184
32 0.0007670.000767 0.08900.0890 2146 0.0008450.000845 0.09210.0921

The observed orders at the finest step are 2.002.00 in L2L^2 and 1.001.00 in H1H^1 on squares. On the distorted polygons they are between 1.971.97 and 2.012.01 in L2L^2 and between 0.970.97 and 1.001.00 in H1H^1. These are the orders of linear finite elements. The largest vertex error on the distorted meshes converges with order between 1.61.6 and 1.81.8.

The stabilization changes the answer. On the distorted mesh with 8 cells per side, τ=0.25\tau = 0.25, 11 and 44 give H1H^1 errors 0.3690.369, 0.3680.368 and 0.3960.396 and L2L^2 errors 0.00920.0092, 0.01350.0135 and 0.03800.0380. The rates do not depend on τ\tau, but the constants do.

Correctness

The proof shows four facts. First, GG is nonsingular, and P∗P^* gives the exact coefficients of ΠE∇v\Pi^\nabla_E v from the vertex values of vv, because the boundary integral with the trapezoid rule is exact for functions that are linear on each edge. Second (consistency), aEh(v,p)=∫E∇v⋅∇pa^h_E(v, p) = \int_E \nabla v \cdot \nabla p for every v∈VEv \in V_E and every linear pp: the stabilization vanishes on pp, and the consistency part is the energy of the projection, which equals the energy of vv against pp. Third (stability), for τ>0\tau > 0, aEh(v,v)=0a^h_E(v, v) = 0 only for constants, so the global matrix is symmetric positive definite on the free vertices. Fourth (the patch test), if f=0f = 0 and gg is linear, the vertex values of gg 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 hh in H1H^1 and h2h^2 in L2L^2, 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 Ω\Omega be a polygon and let the mesh Th\mathcal T_h cover Ω\Omega by polygons EE that meet edge to edge. Each polygon EE has the vertices v1,…,vmv_1, \dots, v_m in counterclockwise order, with indices taken modulo mm. The edge eie_i goes from viv_i to vi+1v_{i+1}, ∣ei∣|e_i| is its length and nin_i is its outward unit normal. Collinear vertices are allowed. The local space is

VE={v∈H1(E):Δv=0 in E, v∣∂E is continuous and linear on each edge},V_E = \{v \in H^1(E) : \Delta v = 0 \text{ in } E,\ v|_{\partial E} \text{ is continuous and linear on each edge}\},

P1P_1 is the set of linear polynomials, h=hEh = h_E is the diameter of EE, (xE,yE)(x_E, y_E) is the average of the vertices, and m1=1m_1 = 1, m2=(x−xE)/hm_2 = (x - x_E)/h, m3=(y−yE)/hm_3 = (y - y_E)/h. The matrices DD, BB, GG, P∗P^*, PP and KEK_E are those of lines L2 to L5. The local form is

aEh(v,w)=∫E∇ΠE∇v⋅∇ΠE∇w dx+τ∑i=1m((I−ΠE∇)v)(vi) ((I−ΠE∇)w)(vi),a^h_E(v, w) = \int_E \nabla \Pi^\nabla_E v \cdot \nabla \Pi^\nabla_E w\,dx + \tau \sum_{i=1}^m \big((I - \Pi^\nabla_E) v\big)(v_i)\,\big((I - \Pi^\nabla_E) w\big)(v_i),

and the global form is ah(v,w)=∑EaEh(v,w)a^h(v, w) = \sum_E a^h_E(v, w) on the space VhV_h of functions on Ω\Omega whose restriction to each EE is in VEV_E.

Lemma 1 (degrees of freedom)

The map from v∈VEv \in V_E to its vertex values (v(v1),…,v(vm))(v(v_1), \dots, v(v_m)) is a bijection onto Rm\mathbb R^m, and P1⊂VEP_1 \subset V_E.

Proof. Given values c1,…,cmc_1, \dots, c_m, there is exactly one continuous function gg on ∂E\partial E that is linear on each edge and has g(vi)=cig(v_i) = c_i. The Dirichlet problem Δv=0\Delta v = 0 in EE, v=gv = g on ∂E\partial E has exactly one solution v∈H1(E)v \in H^1(E), because gg is the trace of an H1H^1 function (it is Lipschitz on ∂E\partial E) and the Dirichlet form is coercive on H01(E)H^1_0(E). So each vector of values gives exactly one v∈VEv \in V_E, and the values of vv give back cc. A linear pp has Δp=0\Delta p = 0 and is linear on each edge, so p∈VEp \in V_E. □\square

Lemma 2 (the matrix B)

For v∈VEv \in V_E and a=2,3a = 2, 3, ∫E∇v⋅∇ma dx=∑i=1mBai v(vi)\int_E \nabla v \cdot \nabla m_a\,dx = \sum_{i=1}^m B_{ai}\,v(v_i).

Proof. ∇ma\nabla m_a is a constant vector and Δma=0\Delta m_a = 0, so Green's formula gives

∫E∇v⋅∇ma dx=∫∂Ev ∇ma⋅n ds=∑i=1m(∇ma⋅ni)∫eiv ds.\int_E \nabla v \cdot \nabla m_a\,dx = \int_{\partial E} v\,\nabla m_a \cdot n\,ds = \sum_{i=1}^m (\nabla m_a \cdot n_i) \int_{e_i} v\,ds.

On eie_i the function vv is linear, so the trapezoid rule is exact: ∫eiv ds=12∣ei∣(v(vi)+v(vi+1))\int_{e_i} v\,ds = \tfrac12 |e_i| (v(v_i) + v(v_{i+1})). Collect the terms of v(vi)v(v_i). It gets half of ei−1e_{i-1} and half of eie_i, so its coefficient is 12(∣ei−1∣ni−1+∣ei∣ni)⋅∇ma\tfrac12 (|e_{i-1}| n_{i-1} + |e_i| n_i) \cdot \nabla m_a, which is line L3. For a counterclockwise polygon and the edge from pp to qq, ∣e∣ n=(qy−py, px−qx)|e|\,n = (q_y - p_y,\ p_x - q_x). So 12(∣ei−1∣ni−1+∣ei∣ni)=12(yi+1−yi−1, xi−1−xi+1)\tfrac12(|e_{i-1}| n_{i-1} + |e_i| n_i) = \tfrac12 (y_{i+1} - y_{i-1},\ x_{i-1} - x_{i+1}), and with ∇m2=(1/h,0)\nabla m_2 = (1/h, 0) and ∇m3=(0,1/h)\nabla m_3 = (0, 1/h) this is the formula of the reference code. □\square

Lemma 3 (the projection)

G=BD=diag⁡(1,∣E∣/h2,∣E∣/h2)G = BD = \operatorname{diag}(1, |E|/h^2, |E|/h^2), so GG is nonsingular. For v∈VEv \in V_E with vertex values v\mathbf v, the vector P∗vP^* \mathbf v holds the coefficients of ΠE∇v\Pi^\nabla_E v in the basis m1,m2,m3m_1, m_2, m_3, and P∗D=IP^* D = I.

Proof. Column aa of DD holds the vertex values of mam_a. Row 1 of BB is the vertex average, so (BD)1a(BD)_{1a} is the vertex average of mam_a. This is 11 for a=1a = 1 and 00 for a=2,3a = 2, 3, because (xE,yE)(x_E, y_E) is the vertex average. For a=2,3a = 2, 3, Lemma 2 applied to mb∈VEm_b \in V_E gives (BD)ab=∫E∇mb⋅∇ma dx(BD)_{ab} = \int_E \nabla m_b \cdot \nabla m_a\,dx. This is 00 for b=1b = 1, ∣E∣/h2|E|/h^2 for b=ab = a and 00 for b≠ab \ne a, b≥2b \ge 2, because ∇m2⋅∇m3=0\nabla m_2 \cdot \nabla m_3 = 0. So GG is diagonal with positive entries when ∣E∣>0|E| > 0, which holds for a counterclockwise polygon.

Write ΠE∇v=∑bcbmb\Pi^\nabla_E v = \sum_b c_b m_b. The two conditions that define ΠE∇\Pi^\nabla_E, tested with p=m2,m3p = m_2, m_3 and with the vertex average, are the three equations ∑b(BD)abcb=(Bv)a\sum_b (BD)_{ab} c_b = (B \mathbf v)_a: for a=2,3a = 2, 3 the left side is ∫E∇ΠE∇v⋅∇ma\int_E \nabla \Pi^\nabla_E v \cdot \nabla m_a and the right side is ∫E∇v⋅∇ma\int_E \nabla v \cdot \nabla m_a by Lemma 2, and for a=1a = 1 both sides are vertex averages. A general linear pp is a combination of m1,m2,m3m_1, m_2, m_3, and ∇m1=0\nabla m_1 = 0, so these equations are all the conditions. Hence Gc=BvG c = B \mathbf v and c=G−1Bv=P∗vc = G^{-1} B \mathbf v = P^* \mathbf v. Finally P∗D=G−1BD=G−1G=IP^* D = G^{-1} B D = G^{-1} G = I. □\square

So P=DP∗P = D P^* maps the vertex values of vv to the vertex values of ΠE∇v\Pi^\nabla_E v, and PP is a projection: P2=DP∗DP∗=DP∗=PP^2 = D P^* D P^* = D P^* = P.

Lemma 4 (consistency)

For every v∈VEv \in V_E and every p∈P1p \in P_1, aEh(v,p)=∫E∇v⋅∇p dxa^h_E(v, p) = \int_E \nabla v \cdot \nabla p\,dx. In matrix form, v⊤KE p=∫E∇v⋅∇p dx\mathbf v^\top K_E\, \mathbf p = \int_E \nabla v \cdot \nabla p\,dx where p=Dc\mathbf p = D c holds the vertex values of pp.

Proof. ΠE∇p=p\Pi^\nabla_E p = p, because pp satisfies both defining conditions. So (I−ΠE∇)p=0(I - \Pi^\nabla_E) p = 0, and the stabilization term vanishes. In matrix form, (I−P)p=(I−DP∗)Dc=Dc−Dc=0(I - P)\mathbf p = (I - D P^*) D c = D c - D c = 0. The consistency part is ∫E∇ΠE∇v⋅∇p dx\int_E \nabla \Pi^\nabla_E v \cdot \nabla p\,dx. By the definition of ΠE∇\Pi^\nabla_E with the test polynomial pp, ∫E∇ΠE∇v⋅∇p=∫E∇v⋅∇p\int_E \nabla \Pi^\nabla_E v \cdot \nabla p = \int_E \nabla v \cdot \nabla p. In matrix form, G~\tilde G is GG with the first row set to zero, and since ∇m1=0\nabla m_1 = 0 its entries are G~ab=∫E∇ma⋅∇mb\tilde G_{ab} = \int_E \nabla m_a \cdot \nabla m_b for all a,ba, b. So (P∗v)⊤G~(P∗p)=∫E∇ΠE∇v⋅∇ΠE∇p(P^* \mathbf v)^\top \tilde G (P^* \mathbf p) = \int_E \nabla \Pi^\nabla_E v \cdot \nabla \Pi^\nabla_E p, which is the consistency part. □\square

Lemma 5 (stability of the local matrix)

KEK_E is symmetric and positive semidefinite. For τ>0\tau > 0, v⊤KEv=0\mathbf v^\top K_E \mathbf v = 0 only if v\mathbf v is a constant vector.

Proof. Both parts of KEK_E have the form M⊤SMM^\top S M with SS symmetric positive semidefinite (G~\tilde G restricted to rows and columns 2 and 3 is diag⁡(∣E∣/h2,∣E∣/h2)\operatorname{diag}(|E|/h^2, |E|/h^2), and its first row and column are zero), so KEK_E is symmetric positive semidefinite. Suppose v⊤KEv=0\mathbf v^\top K_E \mathbf v = 0. Both terms are nonnegative, so both vanish. The stabilization term is τ∣(I−P)v∣2\tau |(I - P)\mathbf v|^2, so v=Pv=DP∗v\mathbf v = P \mathbf v = D P^* \mathbf v, and v\mathbf v holds the vertex values of the linear polynomial q=ΠE∇vq = \Pi^\nabla_E v. The consistency term is ∫E∣∇q∣2=0\int_E |\nabla q|^2 = 0, so qq is constant, and v\mathbf v is a constant vector. Constants do give zero, because their projection is the same constant. □\square

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 τ>0\tau > 0 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 K=∑EAE⊤KEAEK = \sum_E A_E^\top K_E A_E, where AEA_E picks the vertex values of EE from the global vector, is symmetric positive semidefinite by Lemma 5. Let u\mathbf u be zero at the boundary vertices and u⊤Ku=0\mathbf u^\top K \mathbf u = 0. Then every term uE⊤KEuE\mathbf u_E^\top K_E \mathbf u_E is zero, so u\mathbf u 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 u\mathbf u is one constant everywhere. It is zero at a boundary vertex, so u=0\mathbf u = 0. The restriction of KK to the free vertices is therefore positive definite. The statement about conjugate gradients is the standard finite termination property for symmetric positive definite systems. □\square

Theorem 2 (the patch test)

Let f=0f = 0 and g=pg = p for a linear pp. Then the vertex values of pp solve the global system of line L7, so the method returns uI=p(vI)u_I = p(v_I) at every vertex and ΠE∇uh=p\Pi^\nabla_E u_h = p on every polygon. This holds on every mesh that satisfies the assumptions of Theorem 1, for every τ>0\tau > 0, and convexity of the polygons is not used.

Proof. With f=0f = 0 the load FF is zero. The free rows of Kp=FK\mathbf p = F say that ah(p,φI)=0a^h(p, \varphi_I) = 0 for every free vertex II, where φI∈Vh\varphi_I \in V_h has the value 11 at vertex II and 00 at the others. Edge conformity means that two polygons that share an edge list the same vertices on it, so the traces of φI\varphi_I from the two sides are the same piecewise linear function on the edge, and φI\varphi_I is continuous across the edge. Hence φI∈H1(Ω)\varphi_I \in H^1(\Omega), and it vanishes on ∂Ω\partial \Omega because II is a free vertex. By Lemma 4 on each polygon,

ah(p,φI)=∑EaEh(φI,p)=∑E∫E∇φI⋅∇p dx=∫Ω∇φI⋅∇p dx=−∫ΩφI Δp dx=0,a^h(p, \varphi_I) = \sum_E a^h_E(\varphi_I, p) = \sum_E \int_E \nabla \varphi_I \cdot \nabla p\,dx = \int_\Omega \nabla \varphi_I \cdot \nabla p\,dx = -\int_\Omega \varphi_I\, \Delta p\,dx = 0,

by integration by parts with φI=0\varphi_I = 0 on ∂Ω\partial\Omega and Δp=0\Delta p = 0. So p\mathbf p solves the free rows, and it has the right boundary values. By Theorem 1 the solution is unique, so the method returns p\mathbf p. By Lemma 3 the projection of pp on each polygon is pp. □\square

On a triangle P1=VEP_1 = V_E by Lemma 1, since both have dimension 3. Then P=IP = I, the stabilization vanishes for every τ\tau, and KEK_E 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 u∈H1(Ω)u \in H^1(\Omega) solve −Δu=f-\Delta u = f with u=gu = g on ∂Ω\partial\Omega, and let uh∈Vhu_h \in V_h be the discrete solution, with uh=uIu_h = u_I at the boundary vertices for an interpolant uI∈Vhu_I \in V_h of uu. Assume stability: there are constants 0<α≤α∗0 < \alpha \le \alpha^* such that for every polygon EE and every v∈VEv \in V_E,

α ∣v∣1,E2≤aEh(v,v)≤α∗∣v∣1,E2.\alpha\, |v|_{1,E}^2 \le a^h_E(v, v) \le \alpha^* |v|_{1,E}^2.

Let uπu_\pi be any function that is linear on each polygon (it need not be continuous), and write ∣w∣1,h2=∑E∣w∣1,E2|w|_{1,h}^2 = \sum_E |w|_{1,E}^2 for such functions. Let FhF_h be the discrete load, with ∥F−Fh∥Vh′=sup⁡v∈Vh0∣(f,v)−Fh(v)∣/∣v∣1\|F - F_h\|_{V_h'} = \sup_{v \in V_h^0} |(f, v) - F_h(v)| / |v|_1, where Vh0V_h^0 is the subspace of VhV_h that vanishes on ∂Ω\partial\Omega. Then

∣u−uh∣1≤C (∣u−uI∣1+∣u−uπ∣1,h+∥F−Fh∥Vh′),|u - u_h|_1 \le C\,\big(|u - u_I|_1 + |u - u_\pi|_{1,h} + \|F - F_h\|_{V_h'}\big),

with CC depending only on α\alpha and α∗\alpha^*.

Proof. Let δ=uh−uI∈Vh0\delta = u_h - u_I \in V_h^0. By the lower stability bound and the discrete equation ah(uh,δ)=Fh(δ)a^h(u_h, \delta) = F_h(\delta),

α∣δ∣12≤ah(δ,δ)=Fh(δ)−∑EaEh(uI,δ).\alpha |\delta|_1^2 \le a^h(\delta, \delta) = F_h(\delta) - \sum_E a^h_E(u_I, \delta).

On each EE, add and subtract uπ∣E∈P1u_\pi|_E \in P_1 and use Lemma 4 with the polynomial uπu_\pi:

aEh(uI,δ)=aEh(uI−uπ,δ)+∫E∇uπ⋅∇δ=aEh(uI−uπ,δ)+∫E∇(uπ−u)⋅∇δ+∫E∇u⋅∇δ.a^h_E(u_I, \delta) = a^h_E(u_I - u_\pi, \delta) + \int_E \nabla u_\pi \cdot \nabla \delta = a^h_E(u_I - u_\pi, \delta) + \int_E \nabla (u_\pi - u) \cdot \nabla \delta + \int_E \nabla u \cdot \nabla \delta.

The sum over EE of the last terms is ∫Ω∇u⋅∇δ=(f,δ)\int_\Omega \nabla u \cdot \nabla \delta = (f, \delta), since δ∈H01(Ω)\delta \in H^1_0(\Omega) by edge conformity. So

α∣δ∣12=(Fh(δ)−(f,δ))−∑EaEh(uI−uπ,δ)−∑E∫E∇(uπ−u)⋅∇δ.\alpha |\delta|_1^2 = \big(F_h(\delta) - (f, \delta)\big) - \sum_E a^h_E(u_I - u_\pi, \delta) - \sum_E \int_E \nabla(u_\pi - u) \cdot \nabla \delta.

The local form is symmetric and positive semidefinite, so Cauchy-Schwarz and the upper bound give ∣aEh(w,δ)∣≤α∗∣w∣1,E∣δ∣1,E|a^h_E(w, \delta)| \le \alpha^* |w|_{1,E} |\delta|_{1,E} for w,δ∈VEw, \delta \in V_E. The function uI−uπu_I - u_\pi is in VEV_E on each EE, since P1⊂VEP_1 \subset V_E. Hence

α∣δ∣12≤(∥F−Fh∥Vh′+α∗∣uI−uπ∣1,h+∣u−uπ∣1,h)∣δ∣1.\alpha |\delta|_1^2 \le \Big(\|F - F_h\|_{V_h'} + \alpha^* |u_I - u_\pi|_{1,h} + |u - u_\pi|_{1,h}\Big) |\delta|_1.

Divide by ∣δ∣1|\delta|_1 (the case δ=0\delta = 0 is trivial) and use ∣uI−uπ∣1,h≤∣uI−u∣1+∣u−uπ∣1,h|u_I - u_\pi|_{1,h} \le |u_I - u|_1 + |u - u_\pi|_{1,h}. This gives ∣δ∣1≤(∥F−Fh∥Vh′+α∗∣u−uI∣1+(1+α∗)∣u−uπ∣1,h)/α|\delta|_1 \le \big(\|F - F_h\|_{V_h'} + \alpha^* |u - u_I|_1 + (1 + \alpha^*) |u - u_\pi|_{1,h}\big)/\alpha. Then ∣u−uh∣1≤∣u−uI∣1+∣δ∣1|u - u_h|_1 \le |u - u_I|_1 + |\delta|_1 gives the bound with the common constant C=1+(1+α∗)/αC = 1 + (1 + \alpha^*)/\alpha. □\square

Remark 1 (what the reference code computes)

The code builds KEK_E from lines L2 to L5 with exactly the matrices of Lemmas 2 and 3, and the load from FE[i]=∫Ef ΠE∇φiF_E[i] = \int_E f\, \Pi^\nabla_E \varphi_i with a quadrature rule. With f=0f = 0 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 P∗D=IP^* D = I on random polygons with 3 to 9 vertices, Lemma 4 as v⊤KEp=∣E∣ ∇ΠE∇v⋅∇p\mathbf v^\top K_E \mathbf p = |E|\,\nabla \Pi^\nabla_E v \cdot \nabla p, the symmetry of KEK_E 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 τ=0.1\tau = 0.1, 11 and 1010.

Remark 2 (rates, cited)

Theorem 3 reduces the convergence rate to three approximation results: an interpolation estimate in VhV_h, 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 EE star shaped with respect to a disc of radius at least ρhE\rho h_E, and each edge of length at least ρhE\rho h_E, for a fixed ρ>0\rho > 0), these give ∣u−uh∣1=O(h)|u - u_h|_1 = O(h) for u∈H2(Ω)u \in H^2(\Omega), and on convex Ω\Omega a duality argument gives O(h2)O(h^2) in L2L^2. The same assumptions give the stability bounds α\alpha and α∗\alpha^* for the dofi-dofi stabilization, with constants that depend on ρ\rho and τ\tau. 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 mm vertices, lines L2 to L4 cost Θ(m)\Theta(m), the products in line L5 cost Θ(m2)\Theta(m^2), and the load with 7m7m quadrature points costs Θ(m2)\Theta(m^2). Assembly therefore costs Θ(em2)\Theta(e m^2) time, and the global matrix has Θ(em2)\Theta(e m^2) nonzero entries. Each conjugate gradient iteration costs one product with it, so the total time is Θ((i+1) e m2)\Theta((i + 1)\,e\,m^2). On quasi uniform meshes the condition number grows like h−2h^{-2}, so ii grows like n\sqrt n for a fixed tolerance, and a direct sparse solver or a multigrid preconditioner does better on large problems. The memory is Θ(n+em2)\Theta(n + e m^2).

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 τ>0\tau > 0, 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 k=1k = 1 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 kk, the unknowns are the vertex values, k−1k - 1 values on each edge and the moments against polynomials of degree k−2k - 2 inside. The projection then also needs these moments.
  • Enhanced spaces. A modified local space makes the L2L^2 projection onto polynomials of degree kk 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 k=1k = 1, 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 τ=0\tau = 0 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 τ\tau. In the reference test, τ=4\tau = 4 gives an L2L^2 error 4 times larger than τ=0.25\tau = 0.25. Do not tune τ\tau to the test problem. Use a recipe with a fixed scaling.
  • Errors of the virtual function. uhu_h is not known inside a polygon. Measure errors with Π∇uh\Pi^\nabla u_h 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 BB and of the block of GG that holds ∣E∣/h2|E|/h^2, so P∗P^* stays the same but the consistency part changes sign and KEK_E 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.

scimat.pyI0RawGitHub
# 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

  1. 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
  2. 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
  3. 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
  4. 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
  5. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of correctness
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example