Finite elements I: weak form, Galerkin and assembly
Derive the finite-element weak form, establish well-posedness with Lax–Milgram and Galerkin quasi-optimality with Céa's lemma, and build a complete 2D P1 solver with triangular elements, sparse assembly and boundary conditions.
After this lesson you can
- Derive weak formulations of elliptic problems with Dirichlet, Neumann and Robin conditions.
- State Lax–Milgram and verify continuity and coercivity for Poisson and diffusion–reaction.
- Prove Céa's lemma and interpret Galerkin as an energy-norm orthogonal projection.
- Implement a 2D P1 solver with reference-element transformations, local stiffness and mass matrices, and vectorized sparse assembly.
- Impose essential and natural boundary conditions and verify convergence using a manufactured solution.
Before you start
From a plate to a function space
A plate with a hole, one insulated edge and another held at fixed temperature is not conveniently described by one rectangular stencil. The finite element method (FEM) replaces the continuous problem with one in a piecewise function space associated with a mesh. The mesh approximates geometry and the space approximates the solution: both errors matter. We start from the conservation law and finite-difference stencils, but shift from derivatives evaluated at nodes to balances against test functions.
Weak form and boundaries
Let be a bounded Lipschitz domain with boundary divided into Dirichlet, Neumann and Robin parts. Consider
The normal points outward. If the physical heat flux is , its outward flux is on the Neumann part under this convention. Assume bounded and uniformly positive, and ; in the lab they are constant per element or edge.
Multiply by a test function with zero trace on and integrate. The divergence theorem transfers a derivative from to and leaves the boundary term. Substituting natural conditions,
This is the weak formulation. Dirichlet is an essential condition: it enters the solution space through the trace. Neumann and Robin are natural: they appear in boundary integrals. With choose a lift with that trace and seek in the zero-trace space, with right-hand side .
The space contains functions in whose first weak derivatives are also in . A weak derivative satisfies for smooth test functions with interior support. Continuous P1 functions linear on each triangle belong to even though their gradients jump between elements. On a Lipschitz domain the trace is well defined; with a sufficiently large Dirichlet part, Poincaré controls using for zero-trace functions.
Why a solution exists
Proof
By Riesz, there is a bounded operator such that , and a vector representing . The map is contractive if, for example, : for ,
The factor is less than 1. The fixed point satisfies and is unique; applying coercivity with gives the bound. This argument does not require to be symmetric. That is the guarantee of the Lax–Milgram theorem, not a property to assume for every PDE.
∎For Poisson with a positive-measure Dirichlet part, and , continuity follows from Cauchy–Schwarz, coefficient bounds and trace; Poincaré turns into a bound on the norm . Diffusion–reaction is coercive even without Dirichlet because . For purely Neumann Poisson, constants have zero energy and source–flux compatibility is required as well as fixing a constant: the previous coercivity cannot be applied unchanged.
Galerkin and the remaining error
The Galerkin method chooses a finite subspace and seeks such that for every . Subtracting the continuous equation gives orthogonality . Céa’s lemma quantifies the result:
To prove it, write and any . Orthogonality gives ; coercivity and continuity give . Divide if and take the infimum. If is symmetric and coercive, it defines an energy inner product: Galerkin is the orthogonal projection and exactly minimizes error in that norm. It also minimizes in the admissible affine space.
This nodal agreement has a special explanation, not a general 2D rule. On a 1D mesh, is constant on each interval and . With diffusion coefficient constant per interval, the interpolant satisfies the same discrete equation if integrals are exact. Approximate quadrature, a coefficient varying within an interval or higher dimension can break the identity.
The basis functions on this mesh are “hats”: each is one at its node, zero at the others and linear on adjacent intervals. In 2D the basis associated with a vertex extends only across triangles sharing it. A discrete function is written ; choosing each in turn as a test gives . This equation explains both matrix entries and why only neighboring nodes interact.
Céa separates equation stability, contained in , from the space’s approximation ability, contained in the infimum. For a sufficiently regular solution and a family of shape-controlled triangular meshes, P1 interpolation has gradient error of order ; with additional regularity assumptions the error has order . A corner singularity or increasingly flat elements can violate those assumptions. Rates observed in one sequence are evidence for that case, not a universal certificate.
From reference triangle to sparse matrix
On the reference triangle with vertices , the P1 bases are , and . For a physical element with vertices , the affine map is , with . The chain rule gives and . The determinant’s absolute value gives positive area for both orientations.
If are constant on , the local matrices are and . Rows of sum to zero because basis functions sum to one and their gradients sum to zero. That local matrix has a zero eigenvalue: its ordinary condition number is infinite. The ratio shown excludes that constant mode and compares only the two positive eigenvalues; a flattened element worsens the ratio.
On the reference element, with , the expressions explicitly give
The sign of one entry does not by itself measure energy: for any local vector , . After imposing enough essential conditions, the global diffusion matrix is positive definite. To solve with conjugate gradients, preserve symmetry and choose a suitable preconditioner; a small residual measures the discrete system and does not eliminate discretization error.
FEM assembly adds each local contribution at its vertices’ global indices. COO permits repeated entries and sums them when converted to CSR; sparsity comes from connectivity, not an approximation discarding terms. Sparse representation allows systems to be solved without storing a full dense matrix.
The interactive classifies cells by their centers and triangulates selected ones: this guarantees a conforming mesh for the stepped domain, but that domain changes on refinement. Draw simple contours with interior holes that do not cross or overlap; invalid configurations are rejected. Each stepped edge receives the condition of the nearest drawn segment, an additional approximation especially visible near corners. Restarting a contour resets its edge conditions. A hole or detail smaller than the mesh can disappear. For exact geometry or quality control, use a conforming mesh generated by tools such as gmsh and inspect angles and areas. Boundary approximation can dominate error even with a small algebraic residual. With all-zero Neumann boundaries and a positive source, compatibility fails and the interactive does not present a fictitious solution.
Lab: P1 assembly
Nodes have shape and triangles , with zero-based indices. The code returns stiffness, weighted mass and load, separating Dirichlet elimination with lifting from reconstruction. Natural conditions are assembled by edges.
"""Ensamblaje P1 triangular para difusión-reacción y condiciones de borde.
Índices desde cero; nodos (n,2), triángulos (m,3). k y c son constantes
por elemento o escalares. f(x,y), g(x,y), alpha(x,y), r(x,y) son funciones
vectorizadas o escalares. Se admiten triángulos en ambas orientaciones.
"""
import numpy as np
from scipy.sparse import coo_matrix, csr_matrix
def _field(value, x, y):
result=value(x,y) if callable(value) else value
return np.broadcast_to(np.asarray(result,dtype=float),np.shape(x))
def element_geometry(nodes, triangles):
nodes=np.asarray(nodes,dtype=float); tri=np.asarray(triangles,dtype=int)
if nodes.ndim!=2 or nodes.shape[1]!=2 or tri.ndim!=2 or tri.shape[1]!=3 or len(tri)==0 or not np.all(np.isfinite(nodes)):
raise ValueError('nodos (n,2), triángulos (m,3)')
if np.any(tri<0) or np.any(tri>=len(nodes)):
raise ValueError('índice de nodo fuera de rango')
p=nodes[tri]
J=np.stack((p[:,1]-p[:,0],p[:,2]-p[:,0]),axis=-1)
det=np.linalg.det(J)
scale=np.max(np.abs(J),axis=(1,2))
if np.any(np.abs(det)<=np.finfo(float).eps*scale*scale):
raise ValueError('triángulo degenerado')
ref=np.array([[-1.,-1.],[1.,0.],[0.,1.]])
gradients=np.einsum('ij,ejk->eik',ref,np.linalg.inv(J))
return p,np.abs(det)/2,gradients
def assemble_p1(nodes, triangles, k_elem=1.0, c_elem=0.0, f=0.0):
"""Devuelve (K,C,b): rigidez, masa ponderada y carga volumétrica.
K_ij = integral k grad(phi_i).grad(phi_j), C_ij = integral c phi_i phi_j.
k,c son constantes por elemento; la carga usa cuadratura triangular de
grado 2. No incorpora automáticamente condiciones de contorno.
"""
nodes=np.asarray(nodes,dtype=float); tri=np.asarray(triangles,dtype=int)
p,area,grad=element_geometry(nodes,tri); m=len(tri); n=len(nodes)
k=np.broadcast_to(np.asarray(k_elem,dtype=float),(m,))
c=np.broadcast_to(np.asarray(c_elem,dtype=float),(m,))
if np.any(k<=0) or np.any(c<0) or not np.all(np.isfinite(k)) or not np.all(np.isfinite(c)):
raise ValueError('se requiere k positivo y c no negativo y finitos')
klocal=area[:,None,None]*k[:,None,None]*np.einsum('eik,ejk->eij',grad,grad)
mass=np.ones((3,3))+np.eye(3)
clocal=(area*c)[:,None,None]*mass[None,:,:]/12
rows=np.broadcast_to(tri[:,:,None],(m,3,3)).ravel()
cols=np.broadcast_to(tri[:,None,:],(m,3,3)).ravel()
K=coo_matrix((klocal.ravel(),(rows,cols)),shape=(n,n)).tocsr()
C=coo_matrix((clocal.ravel(),(rows,cols)),shape=(n,n)).tocsr()
bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
points=np.einsum('qi,eid->eqd',bary,p)
values=_field(f,points[:,:,0],points[:,:,1])
local=(area[:,None]/3)*np.einsum('eq,qi->ei',values,bary)
b=np.zeros(n); np.add.at(b,tri.ravel(),local.ravel())
return K,C,b
def assemble_boundary(nodes, edges, g=0.0, alpha=0.0, r=0.0):
"""Retorna (R,b): Neumann g y Robin k du/dn+alpha*u=r.
Los bordes deben ser disjuntos si no se desea sumar ambas contribuciones.
Cuadratura Gauss de dos puntos por arista.
"""
nodes=np.asarray(nodes,dtype=float); edges=np.asarray(edges,dtype=int)
if edges.ndim!=2 or edges.shape[1]!=2 or np.any(edges<0) or np.any(edges>=len(nodes)):
raise ValueError('aristas (m,2) con índices válidos')
p=nodes[edges]; length=np.linalg.norm(p[:,1]-p[:,0],axis=1)
if np.any(length<=0): raise ValueError('arista degenerada')
z=np.array([(1-1/np.sqrt(3))/2,(1+1/np.sqrt(3))/2])
basis=np.stack((1-z,z),axis=1)
points=np.einsum('qi,eid->eqd',basis,p); x,y=points[:,:,0],points[:,:,1]
ga=_field(g,x,y); ra=_field(r,x,y); aa=_field(alpha,x,y)
local_b=(length[:,None]/2)*np.einsum('eq,qi->ei',ga+ra,basis)
local_R=(length[:,None,None]/2)*np.einsum('eq,qi,qj->eij',aa,basis,basis)
m=len(edges); rows=np.broadcast_to(edges[:,:,None],(m,2,2)).ravel()
cols=np.broadcast_to(edges[:,None,:],(m,2,2)).ravel()
R=coo_matrix((local_R.ravel(),(rows,cols)),shape=(len(nodes),len(nodes))).tocsr()
b=np.zeros(len(nodes));np.add.at(b,edges.ravel(),local_b.ravel())
return R,b
def apply_dirichlet(A, b, ids, values):
"""Devuelve (A_ff,b_f,free,lift); b_f incluye -A_fD u_D."""
A=csr_matrix(A); b=np.asarray(b,dtype=float); ids=np.asarray(ids,dtype=int)
if A.shape[0]!=A.shape[1] or b.shape!=(A.shape[0],): raise ValueError('formas incompatibles')
if ids.ndim!=1 or np.any(ids<0) or np.any(ids>=len(b)) or len(np.unique(ids))!=len(ids):
raise ValueError('índices Dirichlet inválidos o repetidos')
values=np.broadcast_to(np.asarray(values,dtype=float),ids.shape)
lift=np.zeros(len(b));lift[ids]=values
mask=np.ones(len(b),dtype=bool);mask[ids]=False;free=np.flatnonzero(mask)
return A[free][:,free],(b-A@lift)[free],free,lift
def reconstruct(u_free, free, lift):
"""Inserta la solución reducida en el levantamiento y devuelve todos los nodos."""
out=np.asarray(lift,dtype=float).copy();out[np.asarray(free,dtype=int)]=u_free
return outpoints=np.array([[0.,0.],[1.,0.],[0.,1.]])
cells=np.array([[0,1,2]])
K,C,b=assemble_p1(points,cells,c_elem=1.,f=1.)
Kflip,Cflip,bflip=assemble_p1(points,cells[:,[0,2,1]],c_elem=1.,f=1.)
print('rigidez:',K.toarray())
print('masa:',C.toarray())
print('carga:',b)
print('invariante al invertir orientación:',np.allclose(K.toarray(),Kflip.toarray()) and np.allclose(b,bflip))The cell assembles , weighted mass and load using a three-point degree-2 triangular rule for the source. k_elem and c_elem are scalars or constant-per-element vectors, not nodal values. The edge function uses two Gauss points, exact for polynomials up to degree 3 on an edge. A nonpolynomial source or coefficient is integrated approximately; increased quadrature accuracy may be necessary. Python indices start at zero.
R,edge_b=assemble_boundary(points,np.array([[0,1]]),g=2.,alpha=3.,r=1.)
print('matriz Robin:',R.toarray())
print('carga Neumann más Robin:',edge_b)
Af,bf,free,lift=apply_dirichlet(K+C,b,np.array([0,1]),np.array([1.,2.]))
print('libres:',free,'lado reducido:',bf,'levantamiento:',lift)The cell explicitly adds Neumann and Robin contributions because both were supplied on the same edge to check assembly. In a physical problem with disjoint partition, call separately for the corresponding edges. Lifting subtracts from the free side before solving. Zeroing only the Dirichlet row while leaving the column intact breaks symmetry and can invalidate conjugate gradients even if a number is still produced.
Another option penalizes the difference between and the Dirichlet datum with a boundary term multiplied by a large parameter. This approximates the condition instead of imposing it exactly: a larger penalty reduces violation but can worsen conditioning. We do not use it in the solver, which eliminates known degrees of freedom. The prescribed value at a corner shared by essential edges must be consistent; where essential and natural edges meet, the essential value prevails at that node while the natural integral applies to designated edges.
from scipy.spatial import Delaunay
from scipy.sparse.linalg import spsolve
def square_mesh(n):
grid=np.linspace(0,1,n+1)
xx,yy=np.meshgrid(grid,grid,indexing='ij')
nodes=np.column_stack((xx.ravel(),yy.ravel()))
triangles=Delaunay(nodes).simplices
boundary=np.flatnonzero(np.any(np.isclose(nodes,0)|np.isclose(nodes,1),axis=1))
return nodes,triangles,boundary
nodes,triangles,boundary=square_mesh(8)
K,C,b=assemble_p1(nodes,triangles)
exact=1+nodes[:,0]+2*nodes[:,1]
Af,bf,free,lift=apply_dirichlet(K,b,boundary,exact[boundary])
u=reconstruct(spsolve(Af,bf),free,lift)
print('error máximo de la solución lineal:',np.max(np.abs(u-exact)))
print('asimetría máxima:',np.max(np.abs((K-K.T).data),initial=0))The linear solution belongs to the P1 space, so this test verifies assembly, orientation and lifting without needing a fine mesh. Delaunay triangulation of a point set does not automatically represent holes or guarantee a mesh conforming to a concave polygon: that requires boundary constraints and appropriate meshing tools.
To measure convergence use and on the square with homogeneous Dirichlet conditions. Compute and seminorm by quadrature; the value obtained approximates the integral and is not an exact bound. Halving mesh size should show expected rates under sufficient regularity and a uniformly good-quality mesh family.
from scipy.spatial import Delaunay
from scipy.sparse.linalg import spsolve
def square_mesh(n):
grid=np.linspace(0,1,n+1)
xx,yy=np.meshgrid(grid,grid,indexing='ij')
nodes=np.column_stack((xx.ravel(),yy.ravel()))
triangles=Delaunay(nodes).simplices
boundary=np.flatnonzero(np.any(np.isclose(nodes,0)|np.isclose(nodes,1),axis=1))
return nodes,triangles,boundary
def manufactured_errors(n):
nodes,triangles,boundary=square_mesh(n)
exact=lambda x,y:np.sin(np.pi*x)*np.sin(np.pi*y)
rhs=lambda x,y:2*np.pi**2*exact(x,y)
K,C,b=assemble_p1(nodes,triangles,f=rhs)
Af,bf,free,lift=apply_dirichlet(K,b,boundary,0.)
u=reconstruct(spsolve(Af,bf),free,lift)
p,area,grad=element_geometry(nodes,triangles)
bary=np.array([[2/3,1/6,1/6],[1/6,2/3,1/6],[1/6,1/6,2/3]])
q=np.einsum('qi,eid->eqd',bary,p); x,y=q[:,:,0],q[:,:,1]
uh=np.einsum('qi,ei->eq',bary,u[triangles])
gh=np.einsum('ei,eid->ed',u[triangles],grad)
gx=np.pi*np.cos(np.pi*x)*np.sin(np.pi*y)
gy=np.pi*np.sin(np.pi*x)*np.cos(np.pi*y)
l2=np.sqrt(np.sum(area[:,None]/3*(uh-exact(x,y))**2))
h1=np.sqrt(np.sum(area[:,None]/3*((gh[:,0,None]-gx)**2+(gh[:,1,None]-gy)**2)))
return l2,h1
errors=np.array([manufactured_errors(n) for n in (8,16,32)])
print('errores L2, H1:',errors)
print('razones al refinar:',errors[:-1]/errors[1:])A ratio near 4 in and 2 in is consistent with orders 2 and 1 for P1 in this case. It does not guarantee those rates at singular corners, on degenerate meshes or for less regular sources. The experiment checks this combination of mesh, quadrature and solver.
Comparison with scikit-fem
The following block uses scikit-fem 12.0.2, included in the local Pyodide runtime. It compares stiffness, mass and load term by term and solves the same problem on a mesh with one interior node. It does not depend on temporary lesson files.
import numpy as np
from scipy.sparse import coo_matrix
from scipy.sparse.linalg import spsolve
from skfem import MeshTri, Basis, ElementTriP1, asm, LinearForm
from skfem.models.poisson import laplace, mass
nodes=np.array([[0.,0.],[1.,0.],[1.,1.],[0.,1.],[.5,.5]])
triangles=np.array([[0,1,4],[1,2,4],[2,3,4],[3,0,4]])
verts=nodes[triangles]
J=np.stack((verts[:,1]-verts[:,0],verts[:,2]-verts[:,0]),axis=-1)
area=np.abs(np.linalg.det(J))/2
ref=np.array([[-1.,-1.],[1.,0.],[0.,1.]])
grad=np.einsum('ij,ejk->eik',ref,np.linalg.inv(J))
localK=area[:,None,None]*np.einsum('eik,ejk->eij',grad,grad)
localC=area[:,None,None]*(np.ones((3,3))+np.eye(3))[None,:,:]/12
m=len(triangles);n=len(nodes)
rows=np.broadcast_to(triangles[:,:,None],(m,3,3)).ravel()
cols=np.broadcast_to(triangles[:,None,:],(m,3,3)).ravel()
Kown=coo_matrix((localK.ravel(),(rows,cols)),shape=(n,n)).tocsr()
Cown=coo_matrix((localC.ravel(),(rows,cols)),shape=(n,n)).tocsr()
bown=np.zeros(n);np.add.at(bown,triangles.ravel(),np.repeat(area/3,3))
mesh=MeshTri(nodes.T,triangles.T);basis=Basis(mesh,ElementTriP1(),intorder=2)
@LinearForm
def load(v,w): return v
Ks,Cs,bs=asm(laplace,basis),asm(mass,basis),asm(load,basis)
print('diferencias máximas K,C,b:',np.max(np.abs((Kown-Ks).toarray())),np.max(np.abs((Cown-Cs).toarray())),np.max(np.abs(bown-bs)))
free=np.array([4]) # los cuatro vértices exteriores tienen Dirichlet cero
uown=spsolve((Kown+Cown)[free][:,free],bown[free])
usk=spsolve((Ks+Cs)[free][:,free],bs[free])
print('temperatura interior propia y scikit-fem:',uown,usk)Our part uses the same transformation and assembly as the previous cell, repeated here so this comparison can run independently. The scikit-fem API expresses forms and assembles the same matrices. For FEniCSx, the official Poisson example creates functionspace(msh, ("Lagrange", 1)), defines and in UFL, locates boundary degrees of freedom and solves with LinearProblem and PETSc. That path requires local DOLFINx and was not executed in this lesson.
Exercises
Step 1 of 3. What does orthogonality give?
Step 1 of 3. Why is it continuous?
assemble_stiffness(nodes, triangles) for P1, k=1. nodes has shape (n,2), triangles has shape (m,3), with zero-based indices and nondegenerate elements of either orientation. Return a CSR matrix. Use vectorized element operations and COO assembly.import numpy as np
from scipy.sparse import coo_matrix
def assemble_stiffness(nodes, triangles):
pass