Module contents
Lesson 12 of 27Core 90 min

Verification and validation: solving the right equation right

Distinguish code verification, solution verification and validation; use manufactured solutions, Richardson extrapolation and grid convergence indices, then compare predictions with observations and uncertainty.

After this lesson you can

  • Distinguish code verification, solution verification and validation and classify error sources.
  • Construct manufactured solutions with SymPy to detect solver defects and observed order.
  • Estimate discretization error using Richardson extrapolation and calculate GCI.
  • Define and calculate validation metrics accounting for numerical, experimental and parameter uncertainty.
  • Design simulation-code regression tests.

Before you start

Three different questions

A convincing image does not measure error. Verification and validation separate questions requiring different evidence. Code verification: does the implementation reproduce the equations and expected order on controlled problems? Solution verification: how much numerical error may affect this specific result? Validation: does the model predict relevant observations within stated uncertainties? Calibration fits parameters to data; reserving independent observations evaluates prediction without confusing fitting and validation.

Error is the difference from a defined reference, which may be unknown. Uncertainty describes incomplete knowledge or variability quantified by an interval, distribution or set. The uncertainty taxonomy distinguishes random variability, parameter and model-form uncertainty, numerical errors, and measurement errors or biases. Categories can depend on context: an unknown physical variable may be modeled as random or treated as an uncertain parameter. Reducing hh does not fix omitted physics or a poorly calibrated sensor.

Manufacture a solution to test code

The method of manufactured solutions chooses a smooth function u∗u_* and computes the source and boundary conditions making it an exact solution. For example, if

Lu=−∇⋅(k(x,y)∇u)+c(x,y)u,\mathcal L u=-\nabla\cdot(k(x,y)\nabla u)+c(x,y)u,

take f=Lu∗f=\mathcal L u_*, u∗u_* on Dirichlet and flux k∇u∗⋅nk\nabla u_*\cdot n on Neumann. A symbolic tool can differentiate the expression, but the test still needs signs, units and normals checked. Choosing constant u∗u_* may eliminate diffusion and leave that term untested. A function independent of yy also does not exercise the full 2D implementation. The original report by Salari and Knupp develops this code-verification method.

InteractiveBug hunt with MMS

Horizontal axis: meshes of 16, 32, 64 and 128 intervals; vertical axis: log₁₀ maximum error with floor 10⁻¹⁵. The case changes deterministically; a solution can hide a defect by canceling the affected term.

Manufactured solution
Diagnosis
Case1
Order between fine meshesnear rounding
Diagnosishidden
Cases change deterministically. Try several solutions before revealing the defect; if error is near rounding, no order is calculated.

The figure solves −u′′=f-u''=f with left Dirichlet and normal derivative at the right endpoint. A wrong-sign Neumann condition is hidden if the correct derivative is zero; shifting source evaluation does not affect a constant source. Several complementary solutions and boundary tests are therefore more informative than one favorable example. Observed error near machine precision does not permit a reliable order inference.

Order and extrapolation

For a quantity of interest Q(h)=Q∗+Chp+o(hp)Q(h)=Q_*+Ch^p+o(h^p), the observed order with three meshes of constant ratio r=hgruesa/hmedia=hmedia/hfina>1r=h_{\rm gruesa}/h_{\rm media}=h_{\rm media}/h_{\rm fina}>1 is

pobs=log⁡∣(Qg−Qm)/(Qm−Qf)∣log⁡r,Qext=Qf+Qf−Qmrpobs−1.p_{\rm obs}=\frac{\log |(Q_g-Q_m)/(Q_m-Q_f)|}{\log r}, \qquad Q_{\rm ext}=Q_f+\frac{Q_f-Q_m}{r^{p_{\rm obs}}-1}.

The fine grid convergence index is GCIf=Fs∣(Qf−Qm)/Qf∣/(rpobs−1)GCI_f=F_s |(Q_f-Q_m)/Q_f|/(r^{p_{\rm obs}}-1), here with Fs=1.25F_s=1.25. Report it as a fraction or multiply by 100 for a percentage. If QfQ_f is near zero, use an appropriate absolute scale rather than dividing by it. This GCI is not a probabilistic confidence interval and does not cover model error; interpretation depends on a suitable sequence and asymptotic regime.

InteractiveA layer and three meshes

The curve shows log₁₀ true error versus log₂ number of intervals; only in this example is the exact solution known. GCI assumes positive order, monotone differences and an asymptotic regime; these checks do not alone prove the last assumption.

0
Intervals coarse, medium, fine10, 20, 40
Observed order10.311
Fine relative GCI0.00002 %
Interpretationanomalous order: check regime
The quantity is u(0.8) for advection–diffusion; true error is known in this manufactured case. Nonmonotone differences are declared unreliable.

In the boundary layer, coarse refinement can oscillate and change sign; a mechanically calculated ratio or apparent order does not certify the asymptotic regime. Even positive order and three monotone values are necessary for this simple formula, not sufficient to prove its assumptions. Compare more meshes, iterative error, time step and rounding. The exact example solution is known only to check the estimator.

Compare prediction and observations

A validation metric must match the observable and use. For one-dimensional distributions with finite first moment, the area between cumulative functions ∫∣Fpred(x)−Fobs(x)∣ dx\int |F_{\rm pred}(x)-F_{\rm obs}(x)|\,\mathrm dx is a first-order Wasserstein distance: it has units of xx. With finite samples the empirical CDF has sampling uncertainty; if measurements are independent and identically distributed, the DKW band with ϵ=log⁡(2/α)/(2n)\epsilon=\sqrt{\log(2/\alpha)/(2n)} simultaneously covers the true CDF with probability at least 1−α1-\alpha.

InteractiveDistributions and sampling uncertainty
  • Observations
  • Normal prediction
  • DKW band

Area is approximated by trapezoids only on [−5,5], in the variable’s units; CDFs are drawn on a grid. DKW quantifies sampling uncertainty for independent observations; the band excludes systematic errors and does not validate a model fitted to these same data. The percentage is descriptive, not an acceptance test.

0.00
1.00
50
Truncated area between CDFs0.3877
95% DKW band±0.192
Fraction of points within band99.3 %
Synthetic normal observations with a fixed seed; area is truncated to [−5,5] and the DKW band represents sampling uncertainty only.

Parameter uncertainty can be propagated to a predictive distribution; numerical and experimental uncertainty need their own treatment. A DKW band excludes instrument bias, model uncertainty and uncertainty of parameters estimated from those same data. The visible percentage of CDF points inside the band is descriptive; it does not alone decide validity. Define tolerance, held-out data and application domain in advance. Validating mean temperature does not automatically certify extremes, future times or untested conditions.

In a hypothetical scalar comparison, suppose prediction 10.210.2 with standard deviation 0.30.3 and observation 10.010.0 with deviation 0.40.4, in the same units. If uncertainties are independent and describe the compared quantities, contrast deviation is 0.32+0.42=0.5\sqrt{0.3^2+0.4^2}=0.5 and standardized difference is 0.40.4. With dependence include −2Cov⁡(Qpred,Qobs)-2\operatorname{Cov}(Q_{\rm pred},Q_{\rm obs}); if uncertainty is a bound rather than a standard deviation, this combination needs an additional model. The example is not a measurement and excludes structural model discrepancy.

Organize experiments by increasing complexity: first a controlled property or component, then a subsystem, finally the system under operating conditions. Record calibration, boundary conditions, units, data preparation and criteria before comparing. Favorable validation in one parameter-space region does not automatically extend to another. A discrepancy persisting under refinement suggests examining inputs, boundaries, measurements or omitted physics without assigning a cause before testing it.

Lab: manufacture, estimate and test

The symbolic function receives an operator acting on an expression and returns source, Dirichlet value and normal derivative; to get diffusive flux multiply the latter by kk. Operator and solution symbols are x,yx,y without additional assumptions. The GCI function rejects nonmonotone sequences or nonpositive order.

[ ]Verification toolsBrowser
"""Soluciones manufacturadas y extrapolación para datos monótonos."""
import numpy as np
import sympy as sp
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve

def manufacture(u_exact,operator):
    """operator recibe la expresión SymPy y devuelve la expresión fuente.

    Devuelve funciones NumPy fuente, valor Dirichlet y derivada normal.
    Las fronteras se evalúan en puntos elegidos por el llamador; para flujo
    difusivo k∂u/∂n se multiplica la derivada normal por k.
    """
    x,y,nx,ny=sp.symbols('x y nx ny');f=sp.simplify(operator(u_exact))
    normal=nx*sp.diff(u_exact,x)+ny*sp.diff(u_exact,y)
    return sp.lambdify((x,y),f,'numpy'),sp.lambdify((x,y),u_exact,'numpy'),sp.lambdify((x,y,nx,ny),normal,'numpy')

def richardson(coarse,medium,fine,r=2,fs=1.25):
    if not np.all(np.isfinite([coarse,medium,fine,r,fs])) or r<=1 or fs<=0:raise ValueError('datos, razón o factor inválidos')
    a=coarse-medium;b=medium-fine
    if a*b<=0 or abs(b)<1e-15 or abs(a)<=abs(b) or abs(fine)<1e-15:
        raise ValueError('datos no monótonos o sin orden positivo; GCI no fiable')
    p=np.log(abs(a/b))/np.log(r)
    ext=fine+(fine-medium)/(r**p-1)
    gci=fs*abs((fine-medium)/fine)/(r**p-1)
    return p,ext,gci

def manufactured_1d(kind,n,bug='none'):
    """-u''=f; Dirichlet izquierdo y Neumann derecho, segundas diferencias."""
    x=np.linspace(0,1,n+1);h=1/n
    if kind=='linear':exact=x;f=np.zeros_like(x);g=1.
    elif kind=='quadratic':exact=x*x;f=np.full_like(x,-2.);g=2.
    elif kind=='sine':exact=np.sin(np.pi*x/2);f=(np.pi/2)**2*exact;g=0.
    elif kind=='mixed':exact=x+x*x+np.sin(np.pi*x/2);f=-2+(np.pi/2)**2*np.sin(np.pi*x/2);g=3.
    else:raise ValueError('solución desconocida')
    if bug not in ('none','neumann','coefficient','source'):raise ValueError('error desconocido')
    from scipy.sparse import lil_matrix
    A=lil_matrix((n,n));rhs=np.zeros(n)
    for i in range(1,n):
        row=i-1;A[row,i-1]=2/h**2
        if i>1:A[row,i-2]=-1/h**2
        A[row,i]=-1/h**2
        rhs[row]=f[i]
    if bug=='coefficient':A[:n-1,:]*=1.1
    if bug=='source':
        xx=x[1:n]+h/2
        rhs[:n-1]=0 if kind=='linear' else -2 if kind=='quadratic' else (np.pi/2)**2*np.sin(np.pi*xx/2) if kind=='sine' else -2+(np.pi/2)**2*np.sin(np.pi*xx/2)
    A[n-1,n-1]=3/(2*h);A[n-1,n-2]=-4/(2*h)
    if n>2:A[n-1,n-3]=1/(2*h)
    rhs[-1]=-g if bug=='neumann' else g
    u=np.r_[0.,spsolve(A.tocsr(),rhs)]
    return x,u,float(np.max(np.abs(u-exact)))
[ ]MMS and extrapolationBrowser
x,y=sp.symbols('x y')
u=sp.sin(sp.pi*x)*sp.sin(sp.pi*y)+x*y
k=1+x+y;c=2
operator=lambda v:-sp.diff(k*sp.diff(v,x),x)-sp.diff(k*sp.diff(v,y),y)+c*v
source,boundary,normal=manufacture(u,operator)
print('fuente en (0.3,0.4):',source(.3,.4))
print('Dirichlet y derivada normal en (0,0.4), n=(-1,0):',boundary(0,.4),normal(0,.4,-1,0))
print('orden, extrapolación, GCI fracción:',richardson(.9713,.9682,.9674))
for bug in ('none','neumann','coefficient','source'):
    errors=[manufactured_1d('mixed',n,bug)[2] for n in (16,32,64)]
    print(bug,errors)

The next layer solves steady advection–diffusion with centered differences. The quantity of interest is u(0.8)u(0.8) and mesh counts are divisible by five, so that point is a node. The exact solution permits measuring true error in this example.

[ ]Boundary-layer meshesBrowser
"""Advección-difusión estacionaria: datos para estudiar régimen asintótico."""
import numpy as np
from scipy.sparse import diags
from scipy.sparse.linalg import spsolve

def boundary_layer(n,epsilon=.02,xq=.8):
    h=1/n;x=np.linspace(0,1,n+1)
    A=diags([np.full(n-2,-epsilon/h**2-1/(2*h)),np.full(n-1,2*epsilon/h**2),np.full(n-2,-epsilon/h**2+1/(2*h))],[-1,0,1],format='csr')
    u=np.r_[0.,spsolve(A,np.ones(n-1)),0.]
    exact=x-(np.exp((x-1)/epsilon)-np.exp(-1/epsilon))/(1-np.exp(-1/epsilon))
    return x,u,exact,float(np.interp(xq,x,u)),float(xq-(np.exp((xq-1)/epsilon)-np.exp(-1/epsilon))/(1-np.exp(-1/epsilon)))
for n in (10,20,40,80,160,320,640):
    _,_,_,q,exact=boundary_layer(n)
    print(n,'Q',q,'error absoluto',abs(q-exact))

The next three cells reproduce functions from earlier labs: finite differences from m29-l07, finite volumes from m29-l08 and P1 FEM from m29-l09. They are copied here because each lesson opens its own environment; this page’s tests do not depend on running other pages.

[ ]Finite-difference operatorBrowser
"""Laplaciano 2D y esquemas de calor con convenciones explícitas de malla."""
import numpy as np
from scipy.sparse import diags,eye,kron,csr_matrix
from scipy.sparse.linalg import spsolve,factorized

def laplacian_2d(nx,ny,hx,hy,bc='dirichlet'):
    """Devuelve Δh CSR; x varía más rápido. Neumann homogéneo con nodos fantasma.

    Dirichlet: nx×ny incógnitas interiores y valores exteriores cero.
    Neumann: nx×ny nodos incluidos ambos extremos, con derivada normal cero.
    """
    if nx<3 or ny<3 or hx<=0 or hy<=0 or bc not in ('dirichlet','neumann'): raise ValueError('malla o frontera inválida')
    def one(n,h):
        D=diags([np.ones(n-1),-2*np.ones(n),np.ones(n-1)],[-1,0,1],format='lil')
        if bc=='neumann':D[0,1]=2;D[-1,-2]=2
        return D.tocsr()/h**2
    Dx,Dy=one(nx,hx),one(ny,hy)
    return (kron(eye(ny,format='csr'),Dx,format='csr')+kron(Dy,eye(nx,format='csr'),format='csr')).tocsr()

def neumann_poisson(f,nx,ny,hx,hy,tol=1e-10):
    """Resuelve -Δh u=f con media trapezoidal cero y compatibilidad ponderada."""
    rhs=np.asarray(f,dtype=float).reshape(-1)
    if rhs.size!=nx*ny:raise ValueError('forma incompatible')
    wx=np.ones(nx);wx[[0,-1]]=.5;wy=np.ones(ny);wy[[0,-1]]=.5
    weights=np.outer(wy,wx).ravel();weights/=weights.sum()
    if abs(weights@rhs)>tol*max(1,np.max(np.abs(rhs))):raise ValueError('fuente incompatible con flujo nulo')
    A=(-laplacian_2d(nx,ny,hx,hy,'neumann')).tolil();A[0,:]=weights
    rhs=rhs.copy();rhs[0]=0.;return spsolve(A.tocsr(),rhs)

def heat_integrate(L,u0,kappa,dt,n_steps,method='explicit',rannacher=False):
    """Calor semidiscreto; Rannacher sustituye primer paso CN por dos IE de dt/2."""
    if kappa<0 or dt<=0 or n_steps<0 or method not in ('explicit','implicit','cn'):raise ValueError('parámetros inválidos')
    u=np.asarray(u0,dtype=float).copy();L=csr_matrix(L);I=eye(L.shape[0],format='csc')
    if L.shape!=(u.size,u.size):raise ValueError('forma incompatible')
    if rannacher and method!='cn':raise ValueError('arranque solo para CN')
    if method=='implicit':solve=factorized((I-dt*kappa*L).tocsc())
    if method=='cn':
        solve=factorized((I-.5*dt*kappa*L).tocsc());B=I+.5*dt*kappa*L
        if rannacher:half=factorized((I-.5*dt*kappa*L).tocsc())
    for step in range(n_steps):
        if method=='explicit':u=u+dt*kappa*(L@u)
        elif method=='implicit':u=solve(u)
        elif rannacher and step==0:u=half(half(u))
        else:u=solve(B@u)
    return u
print('FD listo')
[ ]Finite-volume solverBrowser
"""Volúmenes finitos escalares 1D: MUSCL, Rusanov o Godunov, SSP-RK3.

Las entradas son medias de celda. `speed(u)` debe acotar la velocidad
característica en el intervalo relevante de estados; para un flujo no
convexo, usar una cota global válida, no solo el valor en el estado.
"""
import numpy as np


def minmod(a, b):
    return np.where(a*b > 0, np.sign(a)*np.minimum(np.abs(a), np.abs(b)), 0.0)


def slope_limited(left, u, right, limiter):
    dl, dr = u-left, right-u
    if limiter == 'first':
        return np.zeros_like(u)
    if limiter == 'minmod':
        return minmod(dl, dr)
    if limiter == 'mc':
        return minmod((dl+dr)/2, minmod(2*dl,2*dr))
    if limiter == 'superbee':
        p, q = minmod(2*dl,dr), minmod(dl,2*dr)
        return np.where(np.abs(p)>=np.abs(q),p,q)
    raise ValueError('limitador desconocido')


def godunov_burgers(left, right):
    """Flujo exacto para f(u)=u²/2: choque o rarefacción de entropía."""
    left, right = np.asarray(left), np.asarray(right)
    fl, fr = left*left/2, right*right/2
    rare = np.where(left >= 0, fl, np.where(right <= 0, fr, 0.0))
    shock = np.where((left+right)/2 >= 0, fl, fr)
    return np.where(left <= right, rare, shock)


def godunov_lwr(left, right):
    """Flujo exacto para f(rho)=rho(1-rho), con rho en [0,1]."""
    left, right = np.asarray(left), np.asarray(right)
    fl, fr = left*(1-left), right*(1-right)
    increasing_interval = np.minimum(fl,fr)
    decreasing_interval = np.where((right<=.5)&(left>=.5), .25, np.maximum(fl,fr))
    return np.where(left <= right, increasing_interval, decreasing_interval)


def hll_flux(left, right, flux, s_left, s_right):
    """Flujo HLL para estados vectoriales (..., nvar) y cotas de ondas (...)."""
    left=np.asarray(left,dtype=float); right=np.asarray(right,dtype=float)
    sl=np.asarray(s_left,dtype=float)[...,None]; sr=np.asarray(s_right,dtype=float)[...,None]
    if np.any(sl>sr):
        raise ValueError('las cotas de ondas deben estar ordenadas')
    fl,fr=flux(left),flux(right)
    den=np.where(sr-sl>0,sr-sl,1.0)
    middle=(sr*fl-sl*fr+sl*sr*(right-left))/den
    return np.where(sl>=0,fl,np.where(sr<=0,fr,middle))


def fv_rhs(u, dx, flux, speed, limiter='mc', bc='periodic', numerical_flux=None):
    """Derivada semidiscreta conservativa. Frontera periódica o salida libre."""
    u=np.asarray(u,dtype=float)
    if u.ndim != 1 or len(u)<3 or dx<=0:
        raise ValueError('u debe ser vector de al menos tres celdas y dx positivo')
    if bc not in ('periodic','outflow'):
        raise ValueError('frontera desconocida')
    left=np.roll(u,1); right=np.roll(u,-1)
    if bc == 'outflow':
        left[0]=u[0]; right[-1]=u[-1]
    slope=slope_limited(left,u,right,limiter)
    L=np.empty(len(u)+1); R=np.empty(len(u)+1)
    L[1:-1]=u[:-1]+slope[:-1]/2; R[1:-1]=u[1:]-slope[1:]/2
    if bc == 'periodic':
        L[0]=L[-1]=u[-1]+slope[-1]/2
        R[0]=R[-1]=u[0]-slope[0]/2
    else:
        L[0]=R[0]=u[0]; L[-1]=R[-1]=u[-1]
    if numerical_flux is None:
        alpha=np.maximum(np.asarray(speed(L)),np.asarray(speed(R)))
        faces=(flux(L)+flux(R))/2-alpha*(R-L)/2
    else:
        faces=numerical_flux(L,R)
    return -(faces[1:]-faces[:-1])/dx


def solve_fv(u0, dx, tf, flux, max_speed, cfl=.4, limiter='mc', bc='periodic', numerical_flux=None):
    """SSP-RK3 hasta tf; devuelve (medias finales, metadatos).

    `max_speed` puede devolver un escalar o un vector no negativo. La masa
    cambia por los flujos de frontera en salida libre, y se conserva en
    periódico. El CFL se recalcula en cada paso completo.
    """
    if not np.isfinite(tf) or not np.isfinite(dx) or not 0<cfl<=.5 or tf<0 or dx<=0:
        raise ValueError('se requiere 0 < cfl <= 0.5 y tf >= 0')
    u=np.asarray(u0,dtype=float).copy(); t=0.0; steps=0
    if u.ndim != 1 or len(u)<3 or not np.all(np.isfinite(u)):
        raise ValueError('u debe contener al menos tres valores finitos')
    initial_mass=float(dx*np.sum(u))
    while t < tf:
        speeds=np.asarray(max_speed(u),dtype=float)
        if not np.all(np.isfinite(speeds)) or np.any(speeds<0):
            raise ValueError('velocidad característica inválida')
        a=float(np.max(speeds))
        dt=min(tf-t,cfl*dx/a) if a>0 else tf-t
        L=lambda z: fv_rhs(z,dx,flux,max_speed,limiter,bc,numerical_flux)
        u1=u+dt*L(u)
        u2=.75*u+.25*(u1+dt*L(u1))
        u=u/3+(2/3)*(u2+dt*L(u2))
        t+=dt; steps+=1
    return u, {'time':t,'steps':steps,'initial_mass':initial_mass,'final_mass':float(dx*np.sum(u))}
print('FV listo')
[ ]P1 FEM assemblyBrowser
"""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
print('FEM listo')

The suite compares FD and FEM with a manufactured sine solution, and FV with exact periodic advection averages. FEM measurements are nodal RMS error, not integrated L2L^2 norm; FV balance checks mass and the mesh study uses the same final time.

[ ]Three-discretization reportBrowser
results={'fd':[],'fv':[],'fem':[],'mass':[]}
for n in (15,31,63):
    h=1/(n+1);x=np.arange(1,n+1)*h;X,Y=np.meshgrid(x,x)
    exact=(np.sin(np.pi*X)*np.sin(np.pi*Y)).ravel()
    u=spsolve(-laplacian_2d(n,n,h,h),2*np.pi**2*exact)
    results['fd'].append(float(np.max(abs(u-exact))))
for n in (40,80,160):
    h=1/n;x=(np.arange(n)+.5)*h;sinc=np.sin(np.pi*h)/(np.pi*h)
    initial=1+.2*sinc*np.sin(2*np.pi*x)
    u,meta=solve_fv(initial,h,.1,lambda u:u,lambda u:np.ones_like(u),limiter='mc')
    exact=1+.2*sinc*np.sin(2*np.pi*(x-.1))
    results['fv'].append(float(np.mean(abs(u-exact))))
    results['mass'].append(abs(meta['final_mass']-meta['initial_mass']))
for n in (8,16,32):
    x=np.linspace(0,1,n+1);X,Y=np.meshgrid(x,x);nodes=np.column_stack((X.ravel(),Y.ravel()));tri=[]
    for j in range(n):
        for i in range(n):
            a=j*(n+1)+i;b=a+1;c=a+n+1;d=c+1
            tri.extend([[a,b,d],[a,d,c]])
    tri=np.array(tri);exact=np.sin(np.pi*nodes[:,0])*np.sin(np.pi*nodes[:,1])
    K,_,b=assemble_p1(nodes,tri,f=lambda x,y:2*np.pi**2*np.sin(np.pi*x)*np.sin(np.pi*y))
    ids=np.flatnonzero((nodes[:,0]==0)|(nodes[:,0]==1)|(nodes[:,1]==0)|(nodes[:,1]==1))
    A,rhs,free,lift=apply_dirichlet(K,b,ids,0)
    numerical=reconstruct(spsolve(A,rhs),free,lift)
    results['fem'].append(float(np.sqrt(np.mean((exact-numerical)**2))))
for name,errors in results.items():print(name,errors)

First run the three solver cells and “Three-discretization report” on this page: the next cell uses object results generated in the same session. The pytest tests check that error decreases in all three studies and periodic mass is conserved. Regression also compares versions, parameters, tolerances and environment; a passing test covers only the chosen cases.

[ ]Regression tests with pytestBrowser
import builtins,pytest
from pathlib import Path
builtins.vvresults=results
Path('/tmp/test_oryon_vv.py').write_text("""import builtins
def test_refinamiento():
    r=builtins.vvresults
    for name in ('fd','fv','fem'):
        e=r[name]
        assert e[0]>e[1]>e[2]
        assert min(e[0]/e[1],e[1]/e[2])>3
def test_masa_periodica():
    assert max(builtins.vvresults['mass'])<1e-12
""",encoding='utf8')
code=pytest.main(['-q','/tmp/test_oryon_vv.py','-p','no:cacheprovider'])
print('código pytest:',int(code))
assert int(code)==0

Exercises

NumericObserved order
For coarse Q=0.9713, medium Q=0.9682 and fine Q=0.9674, with ratio 2, what is the observed order?
NumericExtrapolation
With the same data, what is extrapolated Q?
NumericRelative GCI
With the same data and factor 1.25, what is the fine GCI as a percentage?
CodeManufacture source and boundary
Implement manufacture(u_exact,operator). Use SymPy symbols x,y without assumptions and return three NumPy functions: source f(x,y), value u(x,y) and normal derivative ∇u·n(x,y,nx,ny). operator receives an expression and returns the source. A flux k∂u/∂n is computed by multiplying the normal derivative by k.
import sympy as sp
def manufacture(u_exact,operator):
  pass
Shift+Enter to run
QuizClassifying discrepancies
An uncertain conductivity estimate produces different predictions without changing code or mesh. Which source best describes this?
QuizA wrong sign
The program implements a term with the opposite sign to the correctly written equation. How is this classified?
QuizEffect of refinement
A value changes when a mesh is systematically refined while equations and data stay fixed. What effect is being studied?
QuizOmitted physics
An equation neglects a heat transfer present in the experiment. What discrepancy does this introduce?
QuizBiased instrument
A thermometer systematically reads one degree too high. Which source should be examined?
QuizA test that is too easy
A solver passes a quadratic polynomial but shows first order on trigonometric functions. What should be investigated first?
Key idea
Verify implementation with controlled references, estimate error in the specific computation and compare the model against independent observations and their uncertainties.