Finite differences II: hyperbolic equations, CFL and finite volumes
Study transport and nonlinear conservation laws through characteristics, CFL, numerical diffusion and dispersion, conservative finite volumes and TVD-limited Godunov methods.
After this lesson you can
- State CFL as a necessary domain-of-dependence condition and apply it to choose Δt.
- Derive modified equations for upwind and Lax–Wendroff and predict numerical diffusion or dispersion.
- Formulate a conservative finite-volume scheme and solve Burgers Riemann problems.
- Explain Godunov's theorem and construct a TVD-limited MUSCL scheme.
- Simulate traffic and shallow-water shocks and rarefactions with mass conservation.
Before you start
Information travels
A disturbance in a channel, a traffic front or a pressure wave does not instantly affect the whole domain. Propagation speeds determine which data can influence a solution. Increasing arithmetic precision cannot fix a mesh that cannot transmit that information in one step. Start from the transport equation with : the characteristic ending at comes from and carries the value of unchanged.
The CFL condition requires the numerical domain of dependence to contain the physical one under refinement for a local scheme to converge for general data. For a stencil reaching one cell per step and advection at speed , this requires . It is necessary, not sufficient: unstable schemes can satisfy it. Von Neumann stability analyzes mode amplification for linear schemes with constant coefficients; it does not prove absence of oscillations near a shock.
Three approximations to the same translation
With , upwind for uses
It is a convex combination of and if : it creates no new extrema in that step. Lax–Friedrichs replaces the central value with the neighbor average; Lax–Wendroff adds the centered second-order correction,
For constant advection all three are stable in the corresponding CFL range, but their errors differ. The upwind and Lax–Wendroff family shows the diffusion–dispersion trade-off that matters when transporting an edge.
Lax–Friedrichs writes . For a mode , the respective amplification factors of upwind, Lax–Friedrichs and Lax–Wendroff are
Requiring for every gives for this upwind scheme and for the other two. Magnitude measures amplification, but the argument of measures phase displacement: a magnitude bound does not prevent frequencies traveling at different speeds. Beam–Warming is another second-order scheme, biased toward the inflow side; it can also oscillate at jumps.
The modified equation explains these signatures. For a smooth solution and proportional to , Taylor expansion and , give, for upwind,
The positive coefficient in acts as numerical viscosity. For Lax–Wendroff the leading term is , dispersive in character. The expansion assumes smoothness and is not a pointwise proof at a discontinuity: there it helps interpret trends, not guarantee a bound. Truncation error and consistency are insufficient without stability; the Lax equivalence theorem concerns well-posed linear problems under its hypotheses.
To recover viscosity without memorizing it, substitute and into upwind. After dividing by this leaves . The factor comes from the time expansion and explains why leading viscosity vanishes when : then the scheme copies exactly one cell to the right per step for this equation.
Dispersion affects phase: components of different frequencies no longer travel at the same speed. A square wave can therefore develop overshoots even if . Stability prevents unlimited mode growth in the analyzed norm; it does not turn update coefficients into positive weights. A visual result within the physical range is a useful check, but not a proof of monotonicity for all inputs.
Shocks, entropy and traffic
For a law , integrating across a moving front gives the Rankine–Hugoniot condition . In Burgers , so when states differ. For an initial jump at , characteristics have speed : if they converge and the shock satisfies . If , they separate and a rarefaction appears with between both speeds.
A weak solution may not be unique. The entropy condition selects the admissible solution; for convex Burgers the shock above satisfies the Lax condition and an expansion shock does not. Derivations and examples in the Clawpack Riemann book show why jump sign changes the pattern. Form is equivalent to only when is sufficiently smooth: a nonconservative discretization can converge to a front with incorrect speed.
The jump rule follows by tracking an interval enclosing the front and letting its width tend to zero. Mass change from interval movement balances the difference of fluxes at its endpoints. In example , , left flux is 2 and right flux 0: the front moves at speed 1, between characteristic speeds 2 and 0. Reversing states would give an expansion shock also satisfying algebraic balance, but not entropy; balance is necessary and does not alone select the physical solution.
In LWR traffic, uses density normalized between 0 and 1. The flux is concave and characteristic speed is . Unlike Burgers, an upward density jump produces a shock. In the figure compare a Riemann jump or draw a profile: extended characteristic lines cease to describe a classical solution when they cross.
One flux per face, one mass
The finite-volume method evolves the average in each cell. Integrating balance in it and approximating face fluxes gives
Summing over cells cancels interior fluxes exactly: only boundary fluxes remain. In a periodic domain the sum of averages is conserved up to rounding. This identity holds regardless of solution smoothness; it is why neighboring cells share one flux evaluation.
On a mesh of cells, multiply each update by and sum: . Each cell need not conserve its own mass; mass is exchanged with neighbors. For free outflow, the two boundary fluxes may differ and mass must change according to that formula. For periodic boundaries, both faces represent the same interface and their fluxes agree. A check imposing constant mass with an open boundary could reject a correct simulation.
The Godunov flux solves the Riemann problem formed by states on both sides and evaluates at the interface. For Burgers, a rarefaction crossing zero has zero flux; an approximation always choosing an outer state can select a non-entropic shock. Rusanov uses a bound on characteristic speeds:
HLL uses two bounds and approximates all waves by an intermediate state:
If both speeds have the same sign, use the inflow-side flux. Bounds must cover relevant waves; evaluating only endpoints is not a guarantee for every nonconvex flux. The Lax–Wendroff theorem for conservative consistent schemes states, under convergence and its boundedness hypotheses, that the limit satisfies the weak law. It does not itself guarantee convergence or select entropy.
High resolution without pretending linearity
Godunov’s theorem says a linear monotone translation scheme in the scalar case, except exact integer translations, cannot be higher than first order. To see the obstacle, write a monotone update as combination with and . Second order would require and . The variance of those weights would be zero, so weight can occur only at ; if , no integer index satisfies this. The guided proof revisits each assumption.
MUSCL reconstructs linear states per cell and applies a nonlinear slope limiter. The TVD limiter reduces slope near an extremum or discontinuity; minmod is more diffusive, while MC and superbee are other choices. SSP-RK3 combines Euler steps in a way that preserves a convex property when each Euler step satisfies it under the appropriate CFL. TVD does not mean every reconstruction, flux, step or system automatically preserves positivity: check assumptions and extreme states.
For example, with differences and , minmod returns zero if signs differ and otherwise the smaller magnitude with that sign. Reconstructed traces are and . Each interface flux uses the trace of its left cell and right cell. With the conservative derivative, SSP-RK3 computes , and . Each sum preserves periodic mass because every evaluation of sums to zero.
Discrete total variation on a periodic mesh is . A TVD update satisfies under its analysis hypotheses. A limiter reduces slope at extrema to avoid oscillations, and that reduction can also lower local order there. The square-wave comparison reveals sharpness and possible overshoots; sine refinement in the lab also examines a smooth case, with a different metric and question.
A system: dam break
For shallow water without friction or topography, and . Characteristic speeds are if . The initial height jump produces waves that can include a shock and rarefaction; HLL and Rusanov replace exact resolution with approximate fluxes. The figure’s reflective walls have zero mass flux, so total mass should remain constant; there is no dry-bed or friction model here.
The example keeps initial heights positive and uses CFL 0.35. Mass conservation does not prove exact shock position or method validity near a dry shore. For real systems, verify positivity, balance with topography and boundary conditions. Clawpack offers more complete solvers and Riemann problems; the interactive is a reduced deterministic model, not a run of that library.
In this demonstration HLL speeds are estimated from endpoints and . This is a particular choice for these states, not proof those estimates bound all intermediate waves in every problem. For other states, especially near dryness, choose and verify appropriate bounds and positivity treatment.
Lab: conservative solver from scratch
The implementation below uses scalar cell averages, limited reconstruction, Rusanov by default, optional Godunov flux and SSP-RK3. max_speed must supply a valid bound on characteristic speed across the state interval. The scalar solver supports periodic or free-outflow boundaries; the auxiliary HLL flux accepts vector states and wave bounds. For other boundary conditions or diffusion, construct and verify an adapter rather than assuming the solver implements them.
"""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))}The first check uses a periodic Burgers square wave. Mass is computed before and after; the extrema check applies to this case and CFL, not an arbitrary flux universally.
import numpy as np
n=200; dx=1/n; x=(np.arange(n)+.5)*dx
u0=np.where(x<.5,1.,0.)
burgers=lambda u:u*u/2
speed=lambda u:np.abs(u)
u,meta=solve_fv(u0,dx,.2,burgers,speed,cfl=.4,limiter='mc',numerical_flux=godunov_burgers)
print('masa inicial y final:', meta['initial_mass'], meta['final_mass'])
print('mínimo y máximo:', u.min(),u.max(), 'pasos:',meta['steps'])Now compare a Burgers shock and rarefaction with their Riemann solutions before boundaries influence them. Error integrates average error; for the exact solution a fine quadrature is used inside each cell, so a shock is not compared only at the cell center.
def exact_burgers(x,t,L,R):
z=x/t
if L>R: return np.where(z<(L+R)/2,L,R)
return np.where(z<L,L,np.where(z>R,R,z))
def riemann_error(n,L,R):
dx=2/n; x=-1+(np.arange(n)+.5)*dx; t=.2
initial=np.where(x<0,L,R)
numerical,_=solve_fv(initial,dx,t,burgers,speed,cfl=.4,limiter='mc',bc='outflow',numerical_flux=godunov_burgers)
sub=(np.arange(40)+.5)/40-.5
truth=exact_burgers(x[:,None]+dx*sub[None,:],t,L,R).mean(axis=1)
return dx*np.sum(np.abs(numerical-truth))
for case in [(1.,0.),(-1.,1.)]:
errors=[riemann_error(n,*case) for n in (100,200,400)]
print('estados',case,'errores L1',np.round(errors,7))Refinement near a shock need not give global second order in , and error near a discontinuity is not a suitable measure of pointwise convergence. In a smooth region away from fronts, reconstruction accuracy can be studied separately. For traffic replace the flux and its Riemann solution with and godunov_lwr, keeping .
For shock , exact position at is . Now separate error in a fixed window around that position and its complement. This partition is spatial, not an estimate of pointwise order; outside the window the exact solution in this case is constant.
for n in (100,200,400):
dx=2/n; x=-1+(np.arange(n)+.5)*dx; t=.2
initial=np.where(x<0,1.,0.)
numerical,_=solve_fv(initial,dx,t,burgers,speed,cfl=.4,limiter='mc',bc='outflow',numerical_flux=godunov_burgers)
sub=(np.arange(40)+.5)/40-.5
truth=exact_burgers(x[:,None]+dx*sub[None,:],t,1.,0.).mean(axis=1)
near=np.abs(x-.1)<.1
print(n,'L1 cerca:',dx*np.abs(numerical-truth)[near].sum(),'L1 lejos:',dx*np.abs(numerical-truth)[~near].sum())errors=[]
for n in (50,100,200):
dx=1/n; x=(np.arange(n)+.5)*dx
initial=np.sin(2*np.pi*x)*np.sinc(dx)
numerical,_=solve_fv(initial,dx,.1,lambda z:z,lambda z:np.ones_like(z),limiter='mc')
truth=np.sin(2*np.pi*(x-.1))*np.sinc(dx)
errors.append(np.mean(np.abs(numerical-truth)))
print('errores medios:',errors)
print('razones de refinamiento:',errors[0]/errors[1],errors[1]/errors[2])Here the solution is smooth across the periodic domain; observed refinement factors are evidence for these meshes and this case, not a uniform guarantee at discontinuities. Factor np.sinc(dx) converts sine values into exact cell averages.
n=200; dx=2/n; x=-1+(np.arange(n)+.5)*dx
rho0=np.where(x<0,.2,.8)
rho,traffic_meta=solve_fv(rho0,dx,.1,lambda z:z*(1-z),lambda z:np.ones_like(z),bc='outflow',numerical_flux=godunov_lwr)
print('choque teórico:',1-.2-.8,'rango:',rho.min(),rho.max())
print('masa inicial y final:',traffic_meta['initial_mass'],traffic_meta['final_mass'])The two exterior fluxes in this case are equal, so mass changes only by rounding. At a general outflow boundary mass can vary: that change must match the flux balance, not be forced to zero.
left,right=.8,.2; t=.1
rho0=np.where(x<0,left,right)
rho,_=solve_fv(rho0,dx,t,lambda z:z*(1-z),lambda z:np.ones_like(z),bc='outflow',numerical_flux=godunov_lwr)
sub=(np.arange(40)+.5)/40-.5
z=(x[:,None]+dx*sub[None,:])/t
truth=np.where(z<1-2*left,left,np.where(z>1-2*right,right,(1-z)/2)).mean(axis=1)
print('error L1 de rarefacción:',dx*np.abs(rho-truth).sum())The last cell implements a first-order shallow-water step with reflective walls. It compares Rusanov and HLL with the same heights and checks mass. It does not use the scalar solver for a vector state: it reuses the HLL formula and makes the system adapter explicit.
def shallow_flux(U):
h,m=U[...,0],U[...,1]
return np.stack((m,m*m/h+h*h/2),axis=-1)
def dam_run(method, n=100, end=.1):
dx=1/n
U=np.column_stack((np.where(np.arange(n)<n//2,2.,1.),np.zeros(n)))
mass0=dx*U[:,0].sum(); t=0.
while t<end:
vel=U[:,1]/U[:,0]; c=np.sqrt(U[:,0])
dt=min(end-t,.35*dx/np.max(np.abs(vel)+c))
ghost_l=np.array([U[0,0],-U[0,1]])
ghost_r=np.array([U[-1,0],-U[-1,1]])
L=np.vstack((ghost_l,U)); R=np.vstack((U,ghost_r))
vl=L[:,1]/L[:,0]; vr=R[:,1]/R[:,0]
cl=np.sqrt(L[:,0]); cr=np.sqrt(R[:,0])
if method=='HLL':
F=hll_flux(L,R,shallow_flux,np.minimum(vl-cl,vr-cr),np.maximum(vl+cl,vr+cr))
else:
a=np.maximum(np.abs(vl)+cl,np.abs(vr)+cr)[:,None]
F=(shallow_flux(L)+shallow_flux(R)-a*(R-L))/2
U=U-dt/dx*(F[1:]-F[:-1]); t+=dt
assert np.all(U[:,0]>0)
return mass0,dx*U[:,0].sum(),U[:,0].min()
for name in ['Rusanov','HLL']:
print(name,dam_run(name))Exercises
Step 1 of 3. Which time term appears in the expansion?
muscl_step(u, flux, max_speed, dx, dt, limiter): one periodic scalar MUSCL step with Rusanov flux and SSP-RK3. u contains cell averages, flux and max_speed are vectorized functions and limiter is 'minmod' or 'mc'. Tests use a stable CFL.import numpy as np
def muscl_step(u, flux, max_speed, dx, dt, limiter):
passStep 1 of 3. What moment conditions does second order impose?
Closing
Before trusting a figure, check mass and boundary fluxes, recalculate wave speed as time advances and compare with a Riemann solution. Linear stability alone does not guarantee monotonicity, positivity or correct shock speed.