Module contents
Lesson 9 of 27Core 120 min

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 Ω⊂R2\Omega\subset\R^2 be a bounded Lipschitz domain with boundary divided into Dirichlet, Neumann and Robin parts. Consider

−∇⋅(k∇u)+cu=f,u=uD en ΓD,k∂nu=g en ΓN,k∂nu+αu=r en ΓR.-\nabla\cdot(k\nabla u)+cu=f,\quad u=u_D\ \text{en }\Gamma_D,\quad k\partial_nu=g\ \text{en }\Gamma_N,\quad k\partial_nu+\alpha u=r\ \text{en }\Gamma_R.

The normal points outward. If the physical heat flux is q=−k∇u\vb q=-k\nabla u, its outward flux is −g-g on the Neumann part under this convention. Assume kk bounded and uniformly positive, c≥0c\ge0 and α≥0\alpha\ge0; in the lab they are constant per element or edge.

Multiply by a test function vv with zero trace on ΓD\Gamma_D and integrate. The divergence theorem transfers a derivative from uu to vv and leaves the boundary term. Substituting natural conditions,

∫Ωk∇u⋅∇v+cuv  ⁣dx+∫ΓRαuv  ⁣ds⏟a(u,v)=∫Ωfv  ⁣dx+∫ΓNgv  ⁣ds+∫ΓRrv  ⁣ds⏟ℓ(v).\underbrace{\int_\Omega k\nabla u\cdot\nabla v+cu v\,\dd x+\int_{\Gamma_R}\alpha uv\,\dd s}_{a(u,v)} =\underbrace{\int_\Omega fv\,\dd x+\int_{\Gamma_N}gv\,\dd s+\int_{\Gamma_R}rv\,\dd s}_{\ell(v)}.

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 uD≠0u_D\ne0 choose a lift u0u_0 with that trace and seek w=u−u0w=u-u_0 in the zero-trace space, with right-hand side ℓ(v)−a(u0,v)\ell(v)-a(u_0,v).

The space H1(Ω)H^1(\Omega) contains functions in L2L^2 whose first weak derivatives are also in L2L^2. A weak derivative wiw_i satisfies ∫u∂iφ=−∫wiφ\int u\partial_i\varphi=-\int w_i\varphi for smooth test functions with interior support. Continuous P1 functions linear on each triangle belong to H1H^1 even though their gradients jump between elements. On a Lipschitz domain the trace is well defined; with a sufficiently large Dirichlet part, Poincaré controls ∥v∥L2\norm v_{L^2} using ∥∇v∥L2\norm{\nabla v}_{L^2} for zero-trace functions.

Why a solution exists

Proof

By Riesz, there is a bounded operator AA such that a(u,v)=⟨Au,v⟩a(u,v)=\inner{Au}{v}, and a vector gg representing ℓ\ell. The map T(u)=u−η(Au−g)T(u)=u-\eta(Au-g) is contractive if, for example, η=α0/M2\eta=\alpha_0/M^2: for d=u−vd=u-v,

∥T(u)−T(v)∥2≤(1−2ηα0+η2M2)∥d∥2.\norm{T(u)-T(v)}^2\le(1-2\eta\alpha_0+\eta^2M^2)\norm d^2.

The factor is less than 1. The fixed point satisfies Au=gAu=g and is unique; applying coercivity with v=uv=u gives the bound. This argument does not require aa 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, k≥k0>0k\ge k_0>0 and c,α≥0c,\alpha\ge0, continuity follows from Cauchy–Schwarz, coefficient bounds and trace; Poincaré turns k0∥∇v∥2k_0\norm{\nabla v}^2 into a bound on the norm H1H^1. Diffusion–reaction −Δu+u-\Delta u+u is coercive even without Dirichlet because ∥∇v∥2+∥v∥2=∥v∥H12\norm{\nabla v}^2+\norm v^2=\norm v_{H^1}^2. 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 Vh⊂VV_h\subset V and seeks uh∈Vhu_h\in V_h such that a(uh,vh)=ℓ(vh)a(u_h,v_h)=\ell(v_h) for every vh∈Vhv_h\in V_h. Subtracting the continuous equation gives orthogonality a(u−uh,vh)=0a(u-u_h,v_h)=0. Céa’s lemma quantifies the result:

∥u−uh∥V≤Mα0inf⁡vh∈Vh∥u−vh∥V.\norm{u-u_h}_V\le\frac{M}{\alpha_0}\inf_{v_h\in V_h}\norm{u-v_h}_V.

To prove it, write e=u−uhe=u-u_h and any vh∈Vhv_h\in V_h. Orthogonality gives a(e,e)=a(e,u−vh)a(e,e)=a(e,u-v_h); coercivity and continuity give α0∥e∥V2≤M∥e∥V∥u−vh∥V\alpha_0\norm e_V^2\le M\norm e_V\norm{u-v_h}_V. Divide if e≠0e\ne0 and take the infimum. If aa 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 12a(v,v)−ℓ(v)\tfrac12a(v,v)-\ell(v) in the admissible affine space.

InteractiveGalerkin as energy projection
  • Exact solution
  • P1 Galerkin and interpolant
4
Energy-norm error0.4985
The equation is −u′′=π2sin⁡(πx)-u''=\pi^2\sin(\pi x) on (0,1), with zero endpoints. Change the number of intervals or drag interior nodes. Here the P1 solution agrees with the interpolant of sin⁡(πx)\sin(\pi x) at the nodes; the readout is exactly integrated energy error.

This nodal agreement has a special explanation, not a general 2D rule. On a 1D mesh, vh′v_h' is constant on each interval and ∫(u−Ihu)′vh′=vh′[(u−Ihu)(b)−(u−Ihu)(a)]=0\int (u-I_hu)'v_h'=v_h'[(u-I_hu)(b)-(u-I_hu)(a)]=0. 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 uh=∑iUiϕiu_h=\sum_i U_i\phi_i; choosing each ϕj\phi_j in turn as a test gives ∑ia(ϕi,ϕj)Ui=ℓ(ϕj)\sum_i a(\phi_i,\phi_j)U_i=\ell(\phi_j). This equation explains both matrix entries and why only neighboring nodes interact.

Céa separates equation stability, contained in M/α0M/\alpha_0, 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 hh; with additional regularity assumptions the L2L^2 error has order h2h^2. 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 (0,0),(1,0),(0,1)(0,0),(1,0),(0,1), the P1 bases are ϕ^1=1−ξ−η\hat\phi_1=1-\xi-\eta, ϕ^2=ξ\hat\phi_2=\xi and ϕ^3=η\hat\phi_3=\eta. For a physical element TT with vertices p1,p2,p3p_1,p_2,p_3, the affine map is x=p1+J(ξ,η)⊤x=p_1+\mat J(\xi,\eta)\T, with J=[p2−p1,p3−p1]\mat J=[p_2-p_1,p_3-p_1]. The chain rule gives ∇xϕi=J− ⁣T∇ξϕ^i\nabla_x\phi_i=\mat J^{-\!T}\nabla_{\xi}\hat\phi_i and  ⁣dx=∣det⁡J∣ ⁣dξ ⁣dη\dd x=|\det\mat J|\dd\xi\dd\eta. The determinant’s absolute value gives positive area for both orientations.

InteractiveFrom reference to physical element

Reference: vertices (0,0), (1,0), (0,1).

Physical: arrows are gradients on a common scale.

Transformation Jacobian:

2.000.500.001.80

The local matrix has a constant direction with zero energy; the ratio uses only its two positive eigenvalues.

0.76−0.35−0.42−0.350.48−0.14−0.42−0.140.56
Signed determinant3.600
Area1.800
Condition in nonzero subspace1.77
Drag the physical vertices. Each vertex color identifies its basis gradient; arrows share a scale to fit. The determinant preserves orientation while area uses absolute value. As the triangle flattens, observe the conditioning of the two nonconstant modes.

If k,ck,c are constant on TT, the local matrices are KijT=k∣T∣∇ϕi⋅∇ϕjK_{ij}^T=k|T|\nabla\phi_i\cdot\nabla\phi_j and CT=c∣T∣(I+11⊤)/12C^T=c|T|(\mat I+\vb 1\vb 1\T)/12. Rows of KTK^T 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 k=1k=1, the expressions explicitly give

KT=12(2−1−1−110−101),CT=124(211121112)(c=1).K^T=\frac12\begin{pmatrix}2&-1&-1\\-1&1&0\\-1&0&1\end{pmatrix},\qquad C^T=\frac1{24}\begin{pmatrix}2&1&1\\1&2&1\\1&1&2\end{pmatrix}\quad(c=1).

The sign of one entry does not by itself measure energy: for any local vector zz, z⊤KTz=∫Tk∣∇(∑iziϕi)∣2≥0z\T K^Tz=\int_T k|\nabla(\sum_i z_i\phi_i)|^2\ge0. 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.

InteractiveAssembling two elements
1

Global matrix, rows and columns in node order 1 to 4:

0.50−0.500.000.00−0.501.00−0.500.000.00−0.500.500.000.000.000.000.00
Accumulated elements1 / 2
Advance the number of accumulated elements. Each triangle contributes a 3×3 matrix to the global positions of its three vertices; shared nodes accumulate contributions from both.
InteractiveA domain with holes

Uniform source 1, conductivity 1; Dirichlet fixes temperature 0, Neumann fixes flux 0 and Robin uses coefficient 1 and ambient 0. Arrows represent flux on a common scale; color ranges from 0 to the maximum. The stepped boundary approximates the drawing, so refinement also changes geometry.

Interaction
Edge condition
12
Nodes120
Triangles192
Maximum temperature0.0421
Maximum flux0.2261
Algebraic residual2.35e-10
Draw an outer contour and add holes with ordered points; select an edge and its condition. Refine the mesh and compare temperature, flux and residual. Geometry is approximated by stepped cells, not an exact fitted triangulation of the polygon.

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 (n,2)(n,2) and triangles (m,3)(m,3), 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.

[ ]P1 assembly and boundary conditionsBrowser
"""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 out
[ ]Reference element and eliminationBrowser
points=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 KK, weighted mass CC and load bb 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.

[ ]Natural boundaries and Dirichlet liftingBrowser
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 AfDuDA_{fD}u_D 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 uhu_h 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.

[ ]Triangular mesh and exact linear solutionBrowser
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 u=sin⁡(πx)sin⁡(πy)u=\sin(\pi x)\sin(\pi y) and f=2π2uf=2\pi^2u on the square with homogeneous Dirichlet conditions. Compute L2L^2 and seminorm H1H^1 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.

[ ]Manufactured errors in L2 and H1Browser
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 L2L^2 and 2 in H1H^1 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.

[ ]Our assembly versus scikit-femBrowser
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 aa and ℓ\ell 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

ProofQuasi-optimality
Prove: Prove Céa's lemma under continuity and coercivity.
0
u is the continuous solution, u_h the Galerkin solution and v_h arbitrary in V_h.

Step 1 of 3. What does orthogonality give?

ProofDiffusion–reaction coercivity
Prove: Verify Lax–Milgram for -u''+u=f on (0,1), with homogeneous Dirichlet endpoints.
0
V=H¹₀(0,1), with H¹ norm, and a(u,v)=∫u'v'+uv.

Step 1 of 3. Why is it continuous?

NumericA local entry
For the triangle with vertices (0,0), (1,0), (0,1), with k=1 and P1 bases in that order, calculate entry K₁₂ of the stiffness matrix.
CodeTriangular stiffness
Implement 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
Shift+Enter to run
QuizEssential or natural
One boundary part has fixed temperature and another prescribed normal flux. How do they appear in the weak formulation?

Errors to look for

Key idea
The weak form incorporates balance and natural boundaries; Galerkin seeks the best available energy approximation when the form is symmetric and coercive. Assembly sums local contributions without losing geometry or boundary conditions.