Algorithm Search⌘K

Algorithmcore

Exact Riemann solver for the Euler equations

Finds the star-region pressure by Newton iteration on the shock and rarefaction relations, then samples the self-similar solution.

Time
O(k) worst
Space
O(1) extra
Where
k = the number of Newton iterations for the star pressure
Properties
detects vacuumdeterministicexactiterative
Origin
S. K. Godunov, E. F. Toro, 1959

The exact Riemann solver computes the exact solution of the Riemann problem for the Euler equations of an ideal gas: two constant gas states that meet at x=0x = 0 at time 00. The Riemann problem page states the problem and its wave structure; this page is the algorithm that solves it for gas dynamics. The solver reduces the problem to one scalar equation f(p)=0f(p) = 0 for the pressure p∗p^* between the two outer waves, solves it by Newton iteration, and then evaluates the solution at any point x/tx/t. Godunov's method uses it to get the flux at each cell face. The Roe, HLL and HLLC solvers are approximate solvers that replace the iteration by a closed form.

In plain words

Put a thin wall in a long tube. On one side there is gas at high pressure, and on the other side gas at low pressure. Remove the wall. Three waves move away from the wall position. On the outside there is a shock or a smooth expansion on each side, and in the middle there is a contact surface that separates the two gases. Between the outer waves, the pressure and the speed are the same on both sides of the contact. The solver finds this middle pressure first. For a trial pressure, the shock rules and the expansion rules each give the speed that the gas on each side would have. The solver adjusts the trial pressure until the two speeds agree. Then it knows every wave, and it can give the gas state at any place and time.

The problem

Given γ>1\gamma > 1 and two primitive states WL=(ρL,uL,pL)W_L = (\rho_L, u_L, p_L) and WR=(ρR,uR,pR)W_R = (\rho_R, u_R, p_R) with positive density and pressure, find the entropy solution of

Ut+F(U)x=0,U=(ρ,ρu,E),F(U)=(ρu,ρu2+p,u(E+p)),E=pγ−1+12ρu2,U_t + F(U)_x = 0, \qquad U = (\rho, \rho u, E), \quad F(U) = (\rho u, \rho u^2 + p, u(E + p)), \quad E = \frac{p}{\gamma - 1} + \frac12\rho u^2,

with U=ULU = U_L for x<0x < 0 and U=URU = U_R for x>0x > 0 at t=0t = 0. The solution is self-similar, U(x,t)=W(x/t)U(x, t) = W(x/t), so the output is a procedure that returns W(ξ)W(\xi) for any ξ=x/t\xi = x/t. The sound speed is c=γp/ρc = \sqrt{\gamma p/\rho}.

The algorithm

Let z=(γ−1)/(2γ)z = (\gamma - 1)/(2\gamma). For each side K∈{L,R}K \in \{L, R\} the wave function is

fK(p)={(p−pK)AKp+BK,p>pK (shock),2cKγ−1((ppK)z−1),p≤pK (rarefaction),AK=2(γ+1)ρK,BK=γ−1γ+1pK.f_K(p) = \begin{cases} (p - p_K)\sqrt{\dfrac{A_K}{p + B_K}}, & p > p_K \text{ (shock)}, \\[2mm] \dfrac{2c_K}{\gamma - 1}\Big(\big(\tfrac{p}{p_K}\big)^{z} - 1\Big), & p \le p_K \text{ (rarefaction)}, \end{cases} \qquad A_K = \frac{2}{(\gamma + 1)\rho_K}, \quad B_K = \frac{\gamma - 1}{\gamma + 1}p_K.

The star pressure is the root of f(p)=fL(p)+fR(p)+uR−uLf(p) = f_L(p) + f_R(p) + u_R - u_L.

  1. EXACT-RIEMANN(W_L, W_R, γ, tol)
  2. 1if (2/(γ-1))(c_L + c_R) ≤ u_R - u_L then report a vacuum and stop
  3. 2p ← ((c_L + c_R - (γ-1)(u_R - u_L)/2) / (c_L/p_L^z + c_R/p_R^z))^(1/z) ▷ the two-rarefaction guess
  4. 3repeat
  5. 4compute f(p) and f'(p) from f_L and f_R
  6. 5p_new ← p - f(p)/f'(p)
  7. 6if p_new ≤ 0 then p_new ← tol · min(p_L, p_R)
  8. 7δ ← 2|p_new - p|/(p_new + p); p ← p_new
  9. 8until δ < tol
  10. 9u* ← (u_L + u_R)/2 + (f_R(p) - f_L(p))/2
  11. 10for each side K with p > p_K: star density ρ*_K = ρ_K (p/p_K + g)/(g p/p_K + 1) with g = (γ-1)/(γ+1), and shock speed u_K ∓ c_K sqrt(((γ+1)/(2γ)) p/p_K + z)
  12. 11for each side K with p ≤ p_K: ρ*_K = ρ_K (p/p_K)^(1/γ), head speed u_K ∓ c_K, tail speed u* ∓ c_K (p/p_K)^z
  13. SAMPLE(ξ)
  14. 12K ← L if ξ ≤ u*, else K ← R
  15. 13if ξ is outside the K wave then return W_K
  16. 14if ξ is between the K wave and the contact then return (ρ*_K, u*, p)
  17. 15return the state inside the K fan at ξ

The upper sign in ∓\mp is for the left side. Inside the left fan the state is c=cLwc = c_Lw with w=2γ+1+γ−1(γ+1)cL(uL−ξ)w = \frac{2}{\gamma + 1} + \frac{\gamma - 1}{(\gamma + 1)c_L}(u_L - \xi), u=2γ+1(cL+γ−12uL+ξ)u = \frac{2}{\gamma + 1}\big(c_L + \frac{\gamma - 1}{2}u_L + \xi\big), ρ=ρLw2/(γ−1)\rho = \rho_Lw^{2/(\gamma - 1)} and p=pLw2γ/(γ−1)p = p_Lw^{2\gamma/(\gamma - 1)}. The right fan is the mirror image.

Example

Sod's shock tube, γ=1.4\gamma = 1.4, WL=(1,0,1)W_L = (1, 0, 1) and WR=(0.125,0,0.1)W_R = (0.125, 0, 0.1). The sound speeds are cL=1.18322c_L = 1.18322 and cR=1.05830c_R = 1.05830. The vacuum test passes, because 20.4(cL+cR)=11.2\frac{2}{0.4}(c_L + c_R) = 11.2 is larger than uR−uL=0u_R - u_L = 0. The guess of line L2 is p0=0.306767p_0 = 0.306767. The Newton iterates are 0.3031130.303113, 0.303130180.30313018 and 0.30313017810.3031301781, with relative changes 1.2×10−21.2 \times 10^{-2}, 5.6×10−55.6 \times 10^{-5} and 1.2×10−91.2 \times 10^{-9}, and the fourth step stops the loop.

You can check the root by hand. At p=0.30313p = 0.30313 the left side is a rarefaction, because p<pL=1p < p_L = 1: fL=5.91608 (0.303131/7−1)=5.91608×(0.84323−1)=−0.92746f_L = 5.91608\,(0.30313^{1/7} - 1) = 5.91608 \times (0.84323 - 1) = -0.92746. The right side is a shock, because p>pR=0.1p > p_R = 0.1: AR=6.6667A_R = 6.6667, BR=0.016667B_R = 0.016667, and fR=0.203136.6667/0.31980=0.92745f_R = 0.20313\sqrt{6.6667/0.31980} = 0.92745. So f(p)≈0f(p) \approx 0, and u∗=12(0.92745+0.92746)=0.92745u^* = \frac12(0.92745 + 0.92746) = 0.92745.

The solution at t=1t = 1:

ξ=x/t\xi = x/t region ρ\rho uu pp
−1.5-1.5 left state 1 0 1
−1.0-1.0 left fan 0.877453 0.152680 0.832747
−0.5-0.5 left fan 0.602938 0.569347 0.492472
0.00.0 left star 0.426319 0.927453 0.303130
1.01.0 right star 0.265574 0.927453 0.303130
2.02.0 right state 0.125 0 0.1

The fan runs from ξ=−1.18322\xi = -1.18322 to −0.07027-0.07027, the contact moves at u∗=0.92745u^* = 0.92745, and the shock moves at 1.752161.75216. The Godunov flux at x=0x = 0 is F(W(0))=(0.395391,0.669837,1.154038)F(W(0)) = (0.395391, 0.669837, 1.154038).

Toro's five tests (Toro 2009, Section 4.3.3), computed with the code on this page. The iteration counts are measurements with tol =10−12= 10^{-12}.

test waves p∗p^* u∗u^* iterations
1 (Sod) rarefaction, shock 0.30313 0.92745 4
2 (123 problem) two rarefactions 0.001894 0 1
3 rarefaction, shock 460.894 19.5975 6
4 shock, rarefaction 46.0950 −6.19633-6.19633 6
5 two shocks 1691.65 8.68977 5

In test 2 the guess of line L2 is already exact, because that guess is the exact root when both waves are rarefactions.

Correctness

The proof is in proofs/correctness.md. Theorem: the Rankine-Hugoniot conditions across a shock and the isentropic relation with the Riemann invariant across a rarefaction give u∗=uL−fL(p∗)u^* = u_L - f_L(p^*) and u∗=uR+fR(p∗)u^* = u_R + f_R(p^*). So p∗p^* is a root of ff, and line L9 gives u∗u^*. Each fKf_K is C1C^1, strictly increasing and concave on (0,∞)(0, \infty), and the two branches meet with the same slope 1/(ρKcK)1/(\rho_Kc_K) at pKp_K. So ff has exactly one positive root when the vacuum test of line L1 fails, and none when it passes. For a concave increasing function, every Newton iterate after the first lies at or below the root, and the iterates then increase to it with quadratic convergence. The sampling formulas follow from the wave order and from the fan relations u−c=ξu - c = \xi and $u + 2c/(\gamma - 1) = $ const.

Proof: The exact Riemann solver finds the unique star pressure and samples the exact solutionfull

Setting. The data are WL=(ρL,uL,pL)W_L = (\rho_L, u_L, p_L) and WR=(ρR,uR,pR)W_R = (\rho_R, u_R, p_R) with positive densities and pressures, γ>1\gamma > 1, cK=γpK/ρKc_K = \sqrt{\gamma p_K/\rho_K} and z=(γ−1)/(2γ)z = (\gamma - 1)/(2\gamma). The solution of the Riemann problem for the Euler equations of an ideal gas is self-similar and has three waves: a left wave (shock or rarefaction), a contact discontinuity, and a right wave. Pressure and velocity are continuous across the contact, so the two star states between the outer waves share p∗p^* and u∗u^* and differ only in density (LeVeque 2002, Section 14.11; Toro 2009, Section 4.1). For K∈{L,R}K \in \{L, R\} let

fK(p)={(p−pK)AKp+BK,p>pK,2cKγ−1((ppK)z−1),p≤pK,AK=2(γ+1)ρK,BK=γ−1γ+1pK,f_K(p) = \begin{cases} (p - p_K)\sqrt{\dfrac{A_K}{p + B_K}}, & p > p_K, \\[2mm] \dfrac{2c_K}{\gamma - 1}\Big(\big(\tfrac{p}{p_K}\big)^{z} - 1\Big), & p \le p_K, \end{cases} \qquad A_K = \frac{2}{(\gamma + 1)\rho_K}, \quad B_K = \frac{\gamma - 1}{\gamma + 1}p_K,

and f(p)=fL(p)+fR(p)+uR−uLf(p) = f_L(p) + f_R(p) + u_R - u_L. Lines L4 and L5 compute ff and f′f' with these formulas.

Lemma 1 (wave relations). A left wave connects WLW_L to a star state with pressure pp and velocity uu exactly when u=uL−fL(p)u = u_L - f_L(p). A right wave connects a star state (p,u)(p, u) to WRW_R exactly when u=uR+fR(p)u = u_R + f_R(p).

Proof. Take the left side; the right side is the mirror image x→−xx \to -x, u→−uu \to -u. If p≤pLp \le p_L the wave is a rarefaction. Across it the entropy is constant, so p/ργp/\rho^\gamma is constant and c/cL=(p/pL)zc/c_L = (p/p_L)^z, and the Riemann invariant u+2c/(γ−1)u + 2c/(\gamma - 1) of the 1-family is constant (LeVeque 2002, Section 14.10). So u=uL+2γ−1(cL−c)=uL−fL(p)u = u_L + \frac{2}{\gamma - 1}(c_L - c) = u_L - f_L(p).

If p>pLp > p_L the wave is a shock with speed SS. Let Q=ρL(uL−S)=ρ(u−S)Q = \rho_L(u_L - S) = \rho(u - S) be the mass flux through it, from the first Rankine-Hugoniot condition. The second condition gives Q2=(p−pL)/(1/ρL−1/ρ)Q^2 = (p - p_L)/(1/\rho_L - 1/\rho), and the third gives the Hugoniot density ratio ρ/ρL=(r+g)/(gr+1)\rho/\rho_L = (r + g)/(g r + 1) with r=p/pLr = p/p_L and g=(γ−1)/(γ+1)g = (\gamma - 1)/(\gamma + 1) (Toro 2009, Sections 3.1.3 and 4.2.1). Then 1/ρL−1/ρ=(1−g)(r−1)/(ρL(r+g))1/\rho_L - 1/\rho = (1 - g)(r - 1)/(\rho_L(r + g)), and since 1−g=2/(γ+1)1 - g = 2/(\gamma + 1),

Q2=ρLpL(r+g)1−g=γ+12ρL(p+BL)=p+BLAL.Q^2 = \frac{\rho_L p_L(r + g)}{1 - g} = \frac{\gamma + 1}{2}\rho_L(p + B_L) = \frac{p + B_L}{A_L}.

Since uL−S=Q/ρLu_L - S = Q/\rho_L and u−S=Q/ρu - S = Q/\rho, with Q>0Q > 0 for a left shock, u−uL=−Q(1/ρL−1/ρ)=−(p−pL)/Qu - u_L = -Q(1/\rho_L - 1/\rho) = -(p - p_L)/Q. So u=uL−(p−pL)AL/(p+BL)=uL−fL(p)u = u_L - (p - p_L)\sqrt{A_L/(p + B_L)} = u_L - f_L(p). □\square

Subtracting the two relations of Lemma 1 gives f(p∗)=0f(p^*) = 0, and adding them gives u∗=12(uL+uR)+12(fR(p∗)−fL(p∗))u^* = \frac12(u_L + u_R) + \frac12(f_R(p^*) - f_L(p^*)), which is line L9.

Lemma 2 (shape of ff). On (0,∞)(0, \infty) each fKf_K is C1C^1, strictly increasing and concave. So ff is too.

Proof. On the rarefaction branch fK′(p)=1ρKcK(p/pK)−(γ+1)/(2γ)f_K'(p) = \frac{1}{\rho_K c_K}(p/p_K)^{-(\gamma + 1)/(2\gamma)}, which is positive and decreasing. On the shock branch, with q=AK/(p+BK)q = \sqrt{A_K/(p + B_K)},

fK′(p)=q(1−p−pK2(p+BK)),fK′′(p)=−AK (p+BK)−5/2(p4+BK+3pK4).f_K'(p) = q\Big(1 - \frac{p - p_K}{2(p + B_K)}\Big), \qquad f_K''(p) = -\sqrt{A_K}\,(p + B_K)^{-5/2}\Big(\frac{p}{4} + B_K + \frac{3p_K}{4}\Big).

The bracket in fK′f_K' is positive because p−pK<2(p+BK)p - p_K < 2(p + B_K), and fK′′<0f_K'' < 0. At p=pKp = p_K the shock branch gives fK′(pK)=AK/(pK+BK)=1/(γρKpK)=1/(ρKcK)f_K'(p_K) = \sqrt{A_K/(p_K + B_K)} = \sqrt{1/(\gamma\rho_K p_K)} = 1/(\rho_K c_K), the same value as the rarefaction branch, and both branches give fK(pK)=0f_K(p_K) = 0. So fK′f_K' is continuous, positive, and decreasing on each branch, hence decreasing on (0,∞)(0, \infty). □\square

Lemma 3 (existence and the vacuum test). ff has a positive root exactly when 2γ−1(cL+cR)>uR−uL\frac{2}{\gamma - 1}(c_L + c_R) > u_R - u_L, and then the root is unique.

Proof. As p→0+p \to 0^+ both sides are on the rarefaction branch and f(p)→uR−uL−2γ−1(cL+cR)f(p) \to u_R - u_L - \frac{2}{\gamma - 1}(c_L + c_R). As p→∞p \to \infty both sides are on the shock branch, where fK(p)f_K(p) grows like p\sqrt{p}, so f(p)→∞f(p) \to \infty. By Lemma 2, ff is continuous and strictly increasing, so it has a positive root if and only if its limit at 0+0^+ is negative, and the root is unique. □\square

So line L1 reports a vacuum exactly when no star pressure exists. The guess of line L2 is the exact root when both waves are rarefactions, because then f(p)=2γ−1(cL((p/pL)z−1)+cR((p/pR)z−1))+uR−uLf(p) = \frac{2}{\gamma - 1}\big(c_L((p/p_L)^z - 1) + c_R((p/p_R)^z - 1)\big) + u_R - u_L is linear in pzp^z. It is positive by the test of line L1.

Theorem (Newton iteration). Let p∗p^* be the root and ε=tol⋅min⁡(pL,pR)\varepsilon = \mathrm{tol}\cdot\min(p_L, p_R), and assume p∗≥εp^* \ge \varepsilon. From any p0>0p_0 > 0, the iterates of lines L3 to L8 satisfy 0<p1≤p∗0 < p_1 \le p^*, then increase monotonically to p∗p^*, and the convergence is quadratic.

Proof. Concavity gives f(q)≤f(p)+f′(p)(q−p)f(q) \le f(p) + f'(p)(q - p) for all p,q>0p, q > 0. With q=p−f(p)/f′(p)q = p - f(p)/f'(p) the right side is 00, so f(q)≤0f(q) \le 0 and q≤p∗q \le p^* by Lemma 2, whenever q>0q > 0. If q≤0q \le 0, line L6 replaces it by ε≤p∗\varepsilon \le p^*. So every iterate after the first lies in (0,p∗](0, p^*]. For such an iterate f(p)≤0f(p) \le 0 and f′(p)>0f'(p) > 0, so the next iterate is at least pp, and it is positive and at most p∗p^* by the first argument, so line L6 never fires again. The sequence is nondecreasing and bounded by p∗p^*, so it has a limit ℓ≤p∗\ell \le p^*. On [p1,p∗][p_1, p^*] the derivative f′f' is continuous with minimum f′(p∗)>0f'(p^*) > 0, so passing to the limit in pk+1=pk−f(pk)/f′(pk)p_{k+1} = p_k - f(p_k)/f'(p_k) gives f(ℓ)=0f(\ell) = 0 and ℓ=p∗\ell = p^*. The derivative f′f' has bounded one-sided derivatives on [p1,p∗][p_1, p^*], so it is Lipschitz there with some constant MM, and the usual Newton estimate gives p∗−pk+1≤M2f′(p∗)(p∗−pk)2p^* - p_{k+1} \le \frac{M}{2f'(p^*)}(p^* - p_k)^2. □\square

Stopping test. Write ek=p∗−pke_k = p^* - p_k and C=M/(2f′(p∗))C = M/(2f'(p^*)). Once Cek≤12Ce_k \le \frac12, we have ek=(pk+1−pk)+ek+1≤(pk+1−pk)+12eke_k = (p_{k+1} - p_k) + e_{k+1} \le (p_{k+1} - p_k) + \frac12e_k, so ek≤2(pk+1−pk)e_k \le 2(p_{k+1} - p_k) and ek+1≤4C(pk+1−pk)2e_{k+1} \le 4C(p_{k+1} - p_k)^2. So when line L8 stops on a relative change below tol, the relative error of the returned pressure is of order tol2\mathrm{tol}^2 times a constant of the problem. Because the iterates increase, the loop ends after finitely many steps; the code raises an error if maxit steps are not enough.

Star densities and wave speeds (lines L10 and L11). On a shock side, ρK∗\rho^*_K is the Hugoniot density ratio of Lemma 1 times ρK\rho_K, and the shock speed follows from QQ: SL=uL−Q/ρL=uL−cLγ+12γp∗pL+zS_L = u_L - Q/\rho_L = u_L - c_L\sqrt{\frac{\gamma + 1}{2\gamma}\frac{p^*}{p_L} + z}, and the mirror formula with a plus sign on the right. On a rarefaction side, ρK∗=ρK(p∗/pK)1/γ\rho^*_K = \rho_K(p^*/p_K)^{1/\gamma} by isentropy, the head moves at uK∓cKu_K \mp c_K and the tail at u∗∓cK∗u^* \mp c^*_K with cK∗=cK(p∗/pK)zc^*_K = c_K(p^*/p_K)^z. The waves are ordered: the left wave lies at ξ<u∗\xi < u^* and the right wave at ξ>u∗\xi > u^* (Toro 2009, Section 4.4).

Sampling (lines L12 to L15). Take ξ≤u∗\xi \le u^*, the left side; the right side is the mirror image. Outside the left wave the solution is WLW_L (line L13). Between the tail of the wave and the contact it is the left star state (line L14). Inside a left fan, the characteristic through the origin gives u−c=ξu - c = \xi, the Riemann invariant gives u+2cγ−1=uL+2cLγ−1u + \frac{2c}{\gamma - 1} = u_L + \frac{2c_L}{\gamma - 1}, and the isentropic relation gives ρ∝c2/(γ−1)\rho \propto c^{2/(\gamma - 1)} and p∝c2γ/(γ−1)p \propto c^{2\gamma/(\gamma - 1)}. Solving the two linear equations,

ccL=w=2γ+1+γ−1(γ+1)cL(uL−ξ),u=2γ+1(cL+γ−12uL+ξ),\frac{c}{c_L} = w = \frac{2}{\gamma + 1} + \frac{\gamma - 1}{(\gamma + 1)c_L}(u_L - \xi), \qquad u = \frac{2}{\gamma + 1}\Big(c_L + \frac{\gamma - 1}{2}u_L + \xi\Big),

ρ=ρLw2/(γ−1)\rho = \rho_Lw^{2/(\gamma - 1)} and p=pLw2γ/(γ−1)p = p_Lw^{2\gamma/(\gamma - 1)}, which is line L15. At the head ξ=uL−cL\xi = u_L - c_L this gives w=1w = 1, and at the tail it gives the star state, so the sampled solution is continuous across the fan. ■\blacksquare

What the tests check independently. The Rankine-Hugoniot conditions S(U∗−UK)=F(U∗)−F(UK)S(U^* - U_K) = F(U^*) - F(U_K) across every computed shock, the isentropic relation and the Riemann invariant at eleven points of the Sod fan, the root against 200 steps of bisection on ff for 200 random data sets, and the integral form of the conservation law on [−4,4][-4, 4] at t=1t = 1.

Complexity

Theorem: with kk Newton iterations, the star state costs O(k)O(k) arithmetic operations, square roots and powers, and each later sample costs O(1)O(1). The memory is O(1)O(1). Measurement: on Toro's five tests, kk is between 1 and 6 with tol =10−12= 10^{-12}. In Godunov's method with MM cells and NN time steps, the solver runs N(M+1)N(M + 1) times. That cost, with its powers and square roots, is the main reason why codes use approximate solvers.

Properties

  • Exact. Up to the stopping tolerance, the result is the exact entropy solution, with the correct shock speeds and an exact contact.
  • Robust root finding. Newton on a concave increasing function cannot overshoot after the first step, so no bracketing is necessary when p∗p^* is not extremely small.
  • Vacuum detection. The test of line L1 is exact. When it passes, the solution has a vacuum region between two rarefactions, and the formulas for that case are different (Toro 2009, Section 4.6).
  • Entropy satisfying. A shock forms only where p∗>pKp^* > p_K, which is the Lax entropy condition for the genuinely nonlinear fields 1 and 3.

Variants and improvements

  • Other initial guesses. Toro (2009, Section 4.3) also gives the linearised guess and the two-shock guess, and switches between them by the pressure ratio. Fewer iterations result, but the root does not change.
  • Bisection or a safeguarded method. Because ff is increasing, bisection on [ε,pmax⁡][\varepsilon, p_{\max}] always works. The tests on this page use it as an independent check.
  • Other equations of state. For a stiffened gas or a covolume gas the same plan works with different wave functions. For a general equation of state the shock relations need an inner iteration.
  • Shallow water. For the shallow water equations the same plan applies to the depth h∗h^*, with the wave function (h−hK)g(h+hK)/(2hhK)(h - h_K)\sqrt{g(h + h_K)/(2hh_K)} for a shock and 2(gh−ghK)2(\sqrt{gh} - \sqrt{gh_K}) for a rarefaction.
  • Approximate solvers. Roe, HLL, HLLC and the Rusanov flux replace the iteration by a closed form. They are cheaper, and each one gives up some exactness.

When to use it

Use the exact solver to make reference solutions for tests of numerical schemes, such as Sod's tube and Toro's tests. Use it also inside Godunov's method when the cost is acceptable, or as a check on an approximate solver. In large production codes, use an approximate solver for the face fluxes, and keep the exact solver for verification.

Pitfalls

  • A non-positive iterate. From a large starting pressure, a Newton step can give p≤0p \le 0. Line L6 resets it to a small positive value. Without that line the next power pzp^z fails.
  • Near-vacuum data. When p∗p^* is very small, the iteration needs many steps, and the reset of line L6 can be above the root. Detect a vacuum with line L1 first, and use bisection as a fallback.
  • A wrong sampling side. The side is chosen by the contact speed u∗u^*, not by x=0x = 0. A sample at ξ=0\xi = 0 can be in the right star region when u∗<0u^* < 0.
  • Confusing sound speeds. The tail of a rarefaction moves at u∗∓cK∗u^* \mp c^*_K with the star sound speed cK∗=cK(p∗/pK)zc^*_K = c_K(p^*/p_K)^z, not with cKc_K.
  • Conserved and primitive variables. The solver works on (ρ,u,p)(\rho, u, p). Convert conserved cell averages to primitive states before the call, and convert the sampled state back to a flux after it.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

exact_riemann_solver.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/exact-riemann-solver/. The authors are listed in prov/P7B1QH.jsonl.

"""Exact Riemann solver for the 1D Euler equations of an ideal gas (Toro 2009, Chapter 4).

States are primitive triples (rho, u, p). The solver finds the star pressure p* by
Newton iteration on the pressure function, starting from the two-rarefaction guess,
then samples the self-similar solution at xi = x / t.
"""

from math import sqrt


class VacuumError(ValueError):
    """The data generate a vacuum: the pressure function has no positive root."""


def sound_speed(rho: float, p: float, gamma: float) -> float:
    return sqrt(gamma * p / rho)


def wave_function(p: float, rho_k: float, p_k: float, c_k: float, gamma: float) -> tuple[float, float]:
    """The function f_K(p) of Toro, Section 4.2, and its derivative, for the side K."""
    if p > p_k:  # shock: the Rankine-Hugoniot relation
        a = 2.0 / ((gamma + 1.0) * rho_k)
        b = (gamma - 1.0) / (gamma + 1.0) * p_k
        q = sqrt(a / (p + b))
        return (p - p_k) * q, q * (1.0 - 0.5 * (p - p_k) / (p + b))
    z = (gamma - 1.0) / (2.0 * gamma)  # rarefaction: the isentropic relation
    r = p / p_k
    return 2.0 * c_k / (gamma - 1.0) * (r**z - 1.0), r ** (-(gamma + 1.0) / (2.0 * gamma)) / (rho_k * c_k)


def pressure_function(p: float, left: tuple, right: tuple, gamma: float) -> tuple[float, float]:
    """f(p) = f_L(p) + f_R(p) + u_R - u_L and f'(p). The root of f is p*."""
    rl, ul, pl = left
    rr, ur, pr = right
    fl, dl = wave_function(p, rl, pl, sound_speed(rl, pl, gamma), gamma)
    fr, dr = wave_function(p, rr, pr, sound_speed(rr, pr, gamma), gamma)
    return fl + fr + ur - ul, dl + dr


def star_state(left: tuple, right: tuple, gamma: float = 1.4, tol: float = 1e-12, maxit: int = 100) -> dict:
    """Return p*, u*, the two star densities, the wave speeds and the Newton iteration count."""
    rl, ul, pl = left
    rr, ur, pr = right
    cl, cr = sound_speed(rl, pl, gamma), sound_speed(rr, pr, gamma)
    if 2.0 / (gamma - 1.0) * (cl + cr) <= ur - ul:  # @line L1
        raise VacuumError("the data generate a vacuum")
    z = (gamma - 1.0) / (2.0 * gamma)
    p = ((cl + cr - 0.5 * (gamma - 1.0) * (ur - ul)) / (cl / pl**z + cr / pr**z)) ** (1.0 / z)  # @line L2
    its = 0
    for its in range(1, maxit + 1):  # @line L3
        f, df = pressure_function(p, left, right, gamma)  # @line L4
        p_new = p - f / df  # @line L5
        if p_new <= 0.0:  # @line L6
            p_new = tol * min(pl, pr)
        change = 2.0 * abs(p_new - p) / (p_new + p)  # @line L7
        p = p_new
        if change < tol:  # @line L8
            break
    else:
        raise RuntimeError("Newton iteration did not converge")
    fl, _ = wave_function(p, rl, pl, cl, gamma)
    fr, _ = wave_function(p, rr, pr, cr, gamma)
    u = 0.5 * (ul + ur) + 0.5 * (fr - fl)  # @line L9
    g1 = (gamma - 1.0) / (gamma + 1.0)
    out = {"p": p, "u": u, "iterations": its}
    for side, (rk, uk, pk, ck, sgn) in (("L", (rl, ul, pl, cl, -1.0)), ("R", (rr, ur, pr, cr, 1.0))):
        if p > pk:  # @line L10: a shock on this side
            out["rho_" + side] = rk * (p / pk + g1) / (g1 * p / pk + 1.0)
            s = uk + sgn * ck * sqrt((gamma + 1.0) / (2.0 * gamma) * p / pk + z)
            out["shock_" + side] = s
            out["head_" + side] = out["tail_" + side] = s
        else:  # @line L11: a rarefaction on this side
            out["rho_" + side] = rk * (p / pk) ** (1.0 / gamma)
            out["head_" + side] = uk + sgn * ck
            out["tail_" + side] = u + sgn * ck * (p / pk) ** z
    return out


def sample(xi: float, left: tuple, right: tuple, gamma: float = 1.4, star: dict | None = None) -> tuple[float, float, float]:
    """The primitive state (rho, u, p) of the exact solution at xi = x / t (Toro, Section 4.5)."""
    if star is None:
        star = star_state(left, right, gamma)
    p, u = star["p"], star["u"]
    if xi <= u:  # @line L12: left of the contact
        rk, uk, pk, sgn, side = left[0], left[1], left[2], 1.0, "L"
    else:
        rk, uk, pk, sgn, side = right[0], right[1], right[2], -1.0, "R"
    ck = sound_speed(rk, pk, gamma)
    head, tail = star["head_" + side], star["tail_" + side]
    # sgn = +1 on the left: the left wave lies at xi < u. Mirror the right side.
    if sgn * (xi - head) <= 0.0:  # @line L13: outside the wave, the data state
        return (rk, uk, pk)
    if sgn * (xi - tail) >= 0.0:  # @line L14: between the wave and the contact
        return (star["rho_" + side], u, p)
    # @line L15: inside a rarefaction fan
    g = gamma
    w = 2.0 / (g + 1.0) + sgn * (g - 1.0) / ((g + 1.0) * ck) * (uk - xi)
    rho = rk * w ** (2.0 / (g - 1.0))
    vel = 2.0 / (g + 1.0) * (sgn * ck + 0.5 * (g - 1.0) * uk + xi)
    return (rho, vel, pk * w ** (2.0 * g / (g - 1.0)))


def euler_flux(state: tuple, gamma: float = 1.4) -> tuple[float, float, float]:
    """Physical flux (rho u, rho u^2 + p, u (E + p)) of a primitive state."""
    rho, u, p = state
    e = p / (gamma - 1.0) + 0.5 * rho * u * u
    return (rho * u, rho * u * u + p, u * (e + p))


def godunov_flux(left: tuple, right: tuple, gamma: float = 1.4) -> tuple[float, float, float]:
    """The flux of the exact solution on the line x = 0, as used by Godunov's method."""
    return euler_flux(sample(0.0, left, right, gamma), gamma)
test_exact_riemann_solver.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/exact-riemann-solver/. The authors are listed in prov/P7B1QH.jsonl.

import random

import pytest

from exact_riemann_solver import (
    VacuumError,
    euler_flux,
    godunov_flux,
    pressure_function,
    sample,
    sound_speed,
    star_state,
)

G = 1.4
SOD = ((1.0, 0.0, 1.0), (0.125, 0.0, 0.1))

# The five standard tests of Toro 2009, Section 4.3.3, with p* and u* to the digits printed there.
TORO = [
    ((1.0, 0.0, 1.0), (0.125, 0.0, 0.1), 0.30313, 0.92745),
    ((1.0, -2.0, 0.4), (1.0, 2.0, 0.4), 0.00189, 0.0),
    ((1.0, 0.0, 1000.0), (1.0, 0.0, 0.01), 460.894, 19.5975),
    ((1.0, 0.0, 0.01), (1.0, 0.0, 100.0), 46.0950, -6.19633),
    ((5.99924, 19.5975, 460.894), (5.99242, -6.19633, 46.0950), 1691.64, 8.68975),
]


def conserved(w):
    rho, u, p = w
    return (rho, rho * u, p / (G - 1.0) + 0.5 * rho * u * u)


def test_sod_check_values() -> None:
    s = star_state(*SOD)
    assert abs(s["p"] - 0.30313) < 5e-6
    assert abs(s["u"] - 0.92745) < 5e-6
    assert abs(s["rho_L"] - 0.42632) < 5e-6
    assert abs(s["rho_R"] - 0.26557) < 5e-6
    assert abs(s["shock_R"] - 1.75216) < 5e-6
    assert s["iterations"] <= 5


def test_toro_table() -> None:
    for left, right, p, u in TORO:
        s = star_state(left, right)
        assert abs(s["p"] - p) <= 5e-5 * max(1.0, p) + 5e-6
        assert abs(s["u"] - u) <= 5e-5 * max(1.0, abs(u))


def test_root_against_bisection() -> None:
    rng = random.Random(7)
    for _ in range(200):
        left = (rng.uniform(0.1, 5), rng.uniform(-1, 1), rng.uniform(0.1, 5))
        right = (rng.uniform(0.1, 5), rng.uniform(-1, 1), rng.uniform(0.1, 5))
        p = star_state(left, right)["p"]
        lo, hi = 1e-12, 1e3
        for _ in range(200):
            mid = 0.5 * (lo + hi)
            if pressure_function(mid, left, right, G)[0] < 0:
                lo = mid
            else:
                hi = mid
        assert abs(p - lo) <= 1e-9 * max(1.0, p)


def test_shocks_satisfy_rankine_hugoniot() -> None:
    for left, right, _, _ in TORO:
        s = star_state(left, right)
        for side, data in (("L", left), ("R", right)):
            if "shock_" + side not in s:
                continue
            star = (s["rho_" + side], s["u"], s["p"])
            sp = s["shock_" + side]
            uq, ud = conserved(star), conserved(data)
            fq, fd = euler_flux(star), euler_flux(data)
            for k in range(3):
                jump = sp * (uq[k] - ud[k]) - (fq[k] - fd[k])
                assert abs(jump) <= 1e-9 * (1.0 + abs(fq[k]) + abs(fd[k]))


def test_rarefaction_invariants() -> None:
    left, right = SOD
    s = star_state(left, right)
    ent = left[2] / left[0] ** G
    inv = left[1] + 2.0 * sound_speed(left[0], left[2], G) / (G - 1.0)
    for k in range(11):
        xi = s["head_L"] + (s["tail_L"] - s["head_L"]) * k / 10
        rho, u, p = sample(xi, left, right, star=s)
        assert abs(p / rho**G - ent) < 1e-12
        assert abs(u + 2.0 * sound_speed(rho, p, G) / (G - 1.0) - inv) < 1e-12
        assert abs(u - sound_speed(rho, p, G) - xi) < 1e-12


def test_integral_form_of_the_conservation_law() -> None:
    # Over [-a, a] at t = 1: integral of U = a (U_L + U_R) - (F(U_R) - F(U_L)).
    for left, right, _, _ in TORO[:2]:
        a, n = 4.0, 20000
        s = star_state(left, right)
        total = [0.0, 0.0, 0.0]
        dx = 2 * a / n
        for i in range(n):
            q = conserved(sample(-a + (i + 0.5) * dx, left, right, star=s))
            for k in range(3):
                total[k] += q[k] * dx
        ul, ur = conserved(left), conserved(right)
        fl, fr = euler_flux(left), euler_flux(right)
        for k in range(3):
            assert abs(total[k] - (a * (ul[k] + ur[k]) - (fr[k] - fl[k]))) < 2e-3


def test_mirror_symmetry() -> None:
    left, right = (1.0, 0.3, 2.0), (0.5, -0.2, 0.4)
    s = star_state(left, right)
    m = star_state((right[0], -right[1], right[2]), (left[0], -left[1], left[2]))
    assert abs(s["p"] - m["p"]) < 1e-12
    assert abs(s["u"] + m["u"]) < 1e-12
    for xi in (-2.0, -0.7, 0.1, 0.9, 2.5):
        a = sample(xi, left, right)
        b = sample(-xi, (right[0], -right[1], right[2]), (left[0], -left[1], left[2]))
        assert abs(a[0] - b[0]) < 1e-12 and abs(a[1] + b[1]) < 1e-12 and abs(a[2] - b[2]) < 1e-12


def test_vacuum_is_detected() -> None:
    with pytest.raises(VacuumError):
        star_state((1.0, -5.0, 0.4), (1.0, 5.0, 0.4))


def test_godunov_flux_of_equal_states() -> None:
    w = (0.7, 0.4, 1.3)
    f = godunov_flux(w, w)
    e = euler_flux(w)
    assert all(abs(x - y) < 1e-12 for x, y in zip(f, e))

History

Godunov (1959) used exact solutions of the gas dynamics Riemann problem at the cell faces of his scheme. Sod (1978) compared finite difference schemes on the shock tube problem that now has his name, with the exact solution as the reference. The form on this page, one pressure function with Newton iteration and a choice of initial guesses, is the one set out in Toro's book (Toro 2009, Chapter 4), which also gives a FORTRAN program.

References

  1. Eleuterio F. Toro, Riemann Solvers and Numerical Methods for Fluid Dynamics, third edition, Springer, 2009, Chapter 4 (Sections 4.2 equations for pressure and particle velocity, 4.3 numerical solution for pressure, 4.4 the complete solution, 4.5 sampling the solution, 4.6 vacuum)
  2. Randall J. LeVeque, Finite Volume Methods for Hyperbolic Problems, Cambridge University Press, 2002, Chapter 14 (Sections 14.8 to 14.13, the Riemann problem for the Euler equations, Riemann invariants, the structure of rarefaction waves, shock tubes)
  3. S. K. Godunov, A difference method for numerical calculation of discontinuous solutions of the equations of hydrodynamics, Matematicheskii Sbornik 47(89) (1959) 271-306, the scheme with exact Riemann solutions at the cell faces

Where this leads

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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