Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions compressible_flow/Sod_Shock_Tube/compare_exact.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
"""Compare an SU2 Sod shock tube result with the exact Riemann solution.

Exact solver: the standard iterative method for the star-region pressure p*
(Toro, "Riemann Solvers and Numerical Methods for Fluid Dynamics", ch. 4).

Usage: python3 compare_exact.py restart_flow_01000.csv [label]
Output: sod_compare.png, plus the L1 density error printed to the screen.
"""
import sys
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

G = 1.4
X0 = 0.5
T_END = 6.3246e-4
rhoL, uL, pL = 1.0, 0.0, 1.0e5
rhoR, uR, pR = 0.125, 0.0, 1.0e4


def f_side(p, rho, pk):
"""Velocity jump across a left/right wave as a function of star pressure p (Toro eq. 4.6/4.7)."""
a = np.sqrt(G * pk / rho)
if p > pk: # shock
A, B = 2.0 / ((G + 1) * rho), (G - 1) / (G + 1) * pk
return (p - pk) * np.sqrt(A / (p + B))
return 2 * a / (G - 1) * ((p / pk) ** ((G - 1) / (2 * G)) - 1) # rarefaction


def star_pressure():
"""Solve f_L(p) + f_R(p) + (uR - uL) = 0 for p* by bisection (robust, no derivatives)."""
lo, hi = 1e-6 * min(pL, pR), 10 * max(pL, pR)
for _ in range(200):
mid = 0.5 * (lo + hi)
if f_side(mid, rhoL, pL) + f_side(mid, rhoR, pR) + (uR - uL) > 0:
hi = mid
else:
lo = mid
return 0.5 * (lo + hi)


def exact(x, t):
"""Exact (rho, u, p) at positions x and time t for Sod's problem (left rarefaction, right shock)."""
ps = star_pressure()
us = 0.5 * (uL + uR) + 0.5 * (f_side(ps, rhoR, pR) - f_side(ps, rhoL, pL))
aL = np.sqrt(G * pL / rhoL)
rhosL = rhoL * (ps / pL) ** (1 / G) # isentropic through the rarefaction
asL = np.sqrt(G * ps / rhosL)
rhosR = rhoR * ((ps / pR + (G - 1) / (G + 1)) / ((G - 1) / (G + 1) * ps / pR + 1)) # shock jump
S_shock = uR + np.sqrt(G * pR / rhoR) * np.sqrt((G + 1) / (2 * G) * ps / pR + (G - 1) / (2 * G))
s = (x - X0) / t # similarity variable x/t
rho, u, p = np.empty_like(x), np.empty_like(x), np.empty_like(x)
for i, si in enumerate(s):
if si < uL - aL: # undisturbed left state
rho[i], u[i], p[i] = rhoL, uL, pL
elif si < us - asL: # inside the rarefaction fan
u[i] = 2 / (G + 1) * (aL + (G - 1) / 2 * uL + si)
a = 2 / (G + 1) * (aL + (G - 1) / 2 * (uL - si))
rho[i] = rhoL * (a / aL) ** (2 / (G - 1))
p[i] = pL * (a / aL) ** (2 * G / (G - 1))
elif si < us: # left star state (between fan tail and contact)
rho[i], u[i], p[i] = rhosL, us, ps
elif si < S_shock: # right star state (between contact and shock)
rho[i], u[i], p[i] = rhosR, us, ps
else: # undisturbed right state
rho[i], u[i], p[i] = rhoR, uR, pR
return rho, u, p, (ps, us, rhosL, rhosR, S_shock)


def read_su2(fname):
"""Read an SU2 ASCII restart file -> x, rho, u, p along the bottom row of points (the flow is 1-D)."""
df = pd.read_csv(fname)
df.columns = [c.strip().strip('"') for c in df.columns]
df = df[df["y"] < 1e-12].sort_values("x")
x = df["x"].to_numpy()
rho = df["Density"].to_numpy()
u = df["Momentum_x"].to_numpy() / rho
p = (G - 1) * (df["Energy"].to_numpy() - 0.5 * rho * u**2)
return x, rho, u, p


def l1_density_error(x, rho):
"""L1 norm of the density error, sum |rho - rho_exact| * dx (uniform mesh)."""
rho_x, _, _, _ = exact(x, T_END)
return np.sum(np.abs(rho - rho_x)) * (x[1] - x[0])


def main():
fname = sys.argv[1] if len(sys.argv) > 1 else "restart_flow_01000.csv"
label = sys.argv[2] if len(sys.argv) > 2 else "SU2"
x, rho, u, p = read_su2(fname)

xe = np.linspace(0, 1, 2001)
rho_e, u_e, p_e, star = exact(xe, T_END)
print(f"p* = {star[0]:.1f} Pa, u* = {star[1]:.2f} m/s, shock speed = {star[4]:.2f} m/s")
print(f"N = {len(x)-1} cells, L1(density error) = {l1_density_error(x, rho):.4e} kg/m^2")

fig, ax = plt.subplots(2, 2, figsize=(10, 7), sharex=True)
for a, ye, yn, name in [(ax[0, 0], rho_e, rho, "density [kg/m$^3$]"),
(ax[0, 1], u_e, u, "velocity [m/s]"),
(ax[1, 0], p_e / 1e3, p / 1e3, "pressure [kPa]"),
(ax[1, 1], p_e / ((G - 1) * rho_e), p / ((G - 1) * rho), "internal energy [J/kg]")]:
a.plot(xe, ye, "k-", lw=1.2, label="exact")
a.plot(x, yn, "o", ms=2.5, mfc="none", color="tab:blue", label=label)
a.set_ylabel(name)
a.grid(alpha=0.3)
ax[1, 0].set_xlabel("x [m]")
ax[1, 1].set_xlabel("x [m]")
ax[0, 0].legend()
fig.suptitle(f"Sod shock tube, t = {T_END:.4e} s, {len(x)-1} cells")
fig.tight_layout()
fig.savefig("sod_compare.png", dpi=150)
print("saved sod_compare.png")


if __name__ == "__main__":
main()
40 changes: 40 additions & 0 deletions compressible_flow/Sod_Shock_Tube/make_ic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
"""Write the Sod initial condition as an SU2 ASCII restart file (solution_flow_00000.csv).

SU2 has no option for "left state here, right state there", so we write the starting
solution ourselves and start the run as a restart (RESTART_SOL= YES, RESTART_ITER= 0).

File layout (what CSolver::Read_SU2_Restart_ASCII expects): a header line, then one row per
mesh point in the same order as the mesh file:
PointID, x, y, Density, Momentum_x, Momentum_y, Energy
The solution columns are the *conservative* variables: rho, rho*u, rho*v, rho*E,
where rho*E = p/(gamma-1) + 0.5*rho*(u^2+v^2) is the total energy per unit volume.

Usage: python3 make_ic.py sod_400.su2
"""
import sys

GAMMA = 1.4
X0 = 0.5 # diaphragm position (m)
LEFT = (1.0, 1.0e5) # (rho [kg/m^3], p [Pa]), u = 0
RIGHT = (0.125, 1.0e4)

mesh = sys.argv[1] if len(sys.argv) > 1 else "sod_400.su2"

# Read the point coordinates from the NPOIN block of the .su2 file
pts = []
with open(mesh) as f:
lines = f.read().splitlines()
k = next(i for i, l in enumerate(lines) if l.startswith("NPOIN="))
npoin = int(lines[k].split("=")[1].split()[0])
for l in lines[k + 1 : k + 1 + npoin]:
x, y, idx = l.split()
pts.append((int(idx), float(x), float(y)))
pts.sort() # rows must be in global point order

with open("solution_flow_00000.csv", "w") as f:
f.write('"PointID","x","y","Density","Momentum_x","Momentum_y","Energy"\n')
for idx, x, y in pts:
rho, p = LEFT if x < X0 else RIGHT
rhoE = p / (GAMMA - 1.0) # u = v = 0, so no kinetic energy
f.write(f"{idx},{x:.12e},{y:.12e},{rho:.12e},0.0,0.0,{rhoE:.12e}\n")
print(f"wrote solution_flow_00000.csv for {npoin} points")
58 changes: 58 additions & 0 deletions compressible_flow/Sod_Shock_Tube/make_mesh.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Write a structured 1-row quad mesh (a thin strip) for the Sod shock tube in SU2 format.

The domain is x in [0, 1] m. It is one cell high, with square cells (dy = dx), because SU2
needs a 2-D mesh but the physics is 1-D.

Usage: python3 make_mesh.py [nx] (default nx = 400) -> sod_<nx>.su2
"""
import sys

nx = int(sys.argv[1]) if len(sys.argv) > 1 else 400
L = 1.0
dx = L / nx
ny = 1
H = ny * dx

# Points: row j = 0 (bottom) then j = 1 (top). Index = j*(nx+1) + i
def pid(i, j):
return j * (nx + 1) + i

lines = ["NDIME= 2"]

# Elements: VTK type 9 = quadrilateral, nodes listed counter-clockwise
lines.append(f"NELEM= {nx * ny}")
for j in range(ny):
for i in range(nx):
e = i + j * nx
lines.append(f"9 {pid(i,j)} {pid(i+1,j)} {pid(i+1,j+1)} {pid(i,j+1)} {e}")

# Point coordinates
npts = (nx + 1) * (ny + 1)
lines.append(f"NPOIN= {npts}")
for j in range(ny + 1):
for i in range(nx + 1):
lines.append(f"{i*dx:.12f} {j*dx:.12f} {pid(i,j)}")

# Boundary markers: VTK type 3 = line segment
lines.append("NMARK= 4")
lines.append("MARKER_TAG= left")
lines.append(f"MARKER_ELEMS= {ny}")
for j in range(ny):
lines.append(f"3 {pid(0,j)} {pid(0,j+1)}")
lines.append("MARKER_TAG= right")
lines.append(f"MARKER_ELEMS= {ny}")
for j in range(ny):
lines.append(f"3 {pid(nx,j)} {pid(nx,j+1)}")
lines.append("MARKER_TAG= lower")
lines.append(f"MARKER_ELEMS= {nx}")
for i in range(nx):
lines.append(f"3 {pid(i,0)} {pid(i+1,0)}")
lines.append("MARKER_TAG= upper")
lines.append(f"MARKER_ELEMS= {nx}")
for i in range(nx):
lines.append(f"3 {pid(i,ny)} {pid(i+1,ny)}")

fname = f"sod_{nx}.su2"
with open(fname, "w") as f:
f.write("\n".join(lines) + "\n")
print(f"wrote {fname}: {nx*ny} cells, {npts} points, dx = {dx:g} m")
Loading