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")
124 changes: 124 additions & 0 deletions compressible_flow/Sod_Shock_Tube/plot_study.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,124 @@
"""Plots for the Sod scheme/limiter/mesh study (reads study/results.csv and the per-case restart files).

Figures:
study_schemes.png density near the contact and shock for ROE/HLLC/AUSM/SLAU2/JST (400 cells)
study_limiters.png same, for the limiters (ROE + MUSCL), plus velocity at the shock
study_order.png 1st vs 2nd order ROE over the whole tube (400 cells)
study_convergence.png L1 density error vs cell size, with the observed order of accuracy
"""
import os
import numpy as np
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from compare_exact import read_su2, exact, T_END

HERE = os.path.dirname(os.path.abspath(__file__))
res = pd.read_csv(os.path.join(HERE, "study", "results.csv"))
xe = np.linspace(0, 1, 4001)
rho_e, u_e, p_e, _ = exact(xe, T_END)


def load(case):
nx = int(res.loc[res.case == case, "nx"].iloc[0])
steps = 1000 * nx // 400
return read_su2(os.path.join(HERE, "study", case, f"restart_flow_{steps:05d}.csv"))


def zoom_plot(cases, labels, fname, title):
"""Density zoomed on the contact (left) and the shock (right), plus velocity at the shock."""
fig, ax = plt.subplots(1, 4, figsize=(18, 4.2))
windows = [(0.44, 0.60, "density at the rarefaction tail"), (0.62, 0.74, "density at the contact"),
(0.80, 0.90, "density at the shock")]
for a, (x0, x1, t) in zip(ax[:3], windows):
m = (xe > x0) & (xe < x1)
a.plot(xe[m], rho_e[m], "k-", lw=1.5, label="exact")
a.set_title(t)
a.set_xlabel("x [m]")
a.set_ylabel("density [kg/m$^3$]")
m = (xe > 0.80) & (xe < 0.90)
ax[3].plot(xe[m], u_e[m], "k-", lw=1.5, label="exact")
ax[3].set_title("velocity at the shock")
ax[3].set_xlabel("x [m]")
ax[3].set_ylabel("velocity [m/s]")
for case, lab in zip(cases, labels):
x, rho, u, p = load(case)
L1 = res.loc[res.case == case, "L1_density"].iloc[0]
for a, (x0, x1, _) in zip(ax[:3], windows):
m = (x > x0) & (x < x1)
a.plot(x[m], rho[m], ".-", ms=4, lw=0.8, label=f"{lab} (L1 = {L1:.2e})")
m = (x > 0.80) & (x < 0.90)
ax[3].plot(x[m], u[m], ".-", ms=4, lw=0.8, label=lab)
for a in ax:
a.grid(alpha=0.3)
ax[1].legend(fontsize=8)
fig.suptitle(title)
fig.tight_layout()
fig.savefig(os.path.join(HERE, fname), dpi=150)
print("saved", fname)


zoom_plot(["roe", "hllc", "ausm", "slau2", "jst"],
["ROE", "HLLC", "AUSM", "SLAU2", "JST (central)"],
"study_schemes.png", "Convective schemes, 400 cells (upwind: MUSCL + Venkatakrishnan-Wang)")
zoom_plot(["lim_none", "lim_vanalb", "lim_venkat", "lim_barth", "lim_wang"],
["no limiter", "van Albada", "Venkatakrishnan", "Barth-Jespersen", "Venkatakrishnan-Wang"],
"study_limiters.png", "Slope limiters, ROE + MUSCL, 400 cells")

# Limiter threshold: HLLC with plain Venkatakrishnan (fixed eps) vs Venkatakrishnan-Wang (range-scaled eps)
fig, ax = plt.subplots(figsize=(8, 4.5))
m = (xe > 0.44) & (xe < 0.62)
ax.plot(xe[m], rho_e[m], "k-", lw=1.5, label="exact")
for case, lab in [("hllc_venkat", "HLLC + Venkatakrishnan, 400 cells"),
("hllc_venkat_800", "HLLC + Venkatakrishnan, 800 cells"),
("hllc_wang", "HLLC + Venkatakrishnan-Wang, 400 cells")]:
x, rho, u, p = load(case)
m = (x > 0.44) & (x < 0.62)
ax.plot(x[m], rho[m], ".-", ms=4, lw=0.8, label=lab)
ax.set_xlabel("x [m]")
ax.set_ylabel("density [kg/m$^3$]")
ax.grid(alpha=0.3)
ax.legend(fontsize=8)
ax.set_title("Behind the rarefaction tail: effect of the limiter threshold")
fig.tight_layout()
fig.savefig(os.path.join(HERE, "study_threshold.png"), dpi=150)
print("saved study_threshold.png")

# 1st vs 2nd order over the whole tube
fig, ax = plt.subplots(figsize=(8, 4.5))
ax.plot(xe, rho_e, "k-", lw=1.5, label="exact")
for case, lab in [("roe_1st", "ROE 1st order"), ("roe_2nd", "ROE 2nd order (MUSCL + Venkatakrishnan-Wang)")]:
x, rho, u, p = load(case)
ax.plot(x, rho, "o", ms=2.5, mfc="none", label=lab)
ax.set_xlabel("x [m]")
ax.set_ylabel("density [kg/m$^3$]")
ax.grid(alpha=0.3)
ax.legend()
ax.set_title("1st vs 2nd order, 400 cells")
fig.tight_layout()
fig.savefig(os.path.join(HERE, "study_order.png"), dpi=150)
print("saved study_order.png")

# Mesh convergence
fig, ax = plt.subplots(figsize=(6.5, 5))
for prefix, lab, mk in [("mesh_1st_", "ROE 1st order", "s"), ("mesh_2nd_", "ROE 2nd order (MUSCL)", "o")]:
d = res[res.case.str.startswith(prefix)].sort_values("nx")
h = 1.0 / d.nx.to_numpy()
e = d.L1_density.to_numpy()
order = np.polyfit(np.log(h), np.log(e), 1)[0] # slope of log(error) vs log(h)
local = np.log(e[:-1] / e[1:]) / np.log(2) # order between successive meshes
print(f"{lab}: least-squares order = {order:.2f}, successive orders = {np.round(local, 2)}")
ax.loglog(h, e, mk + "-", label=f"{lab}, observed order {order:.2f}")
href = np.array([1 / 1600, 1 / 100])
for p_, e0, ls in [(1, 4e-4, "--"), (0.5, 2e-3, ":")]: # reference lines e = e0 * (h/h0)^p
ax.loglog(href, e0 * (href / href[0]) ** p_, "k" + ls, lw=0.8, label=f"reference slope {p_}")
ax.set_xlabel("cell size h [m]")
ax.set_ylabel("L1 density error [kg/m$^2$]")
ax.grid(alpha=0.3, which="both")
ax.legend(fontsize=8)
ax.set_title("Mesh convergence (100 to 1600 cells)")
fig.tight_layout()
fig.savefig(os.path.join(HERE, "study_convergence.png"), dpi=150)
print("saved study_convergence.png")
Loading