import os
import re
import shutil
import subprocess
import tempfile
import time
import zipfile
from pathlib import Path
import numpy as np
image = os.environ.get("ML_CFD_IMAGE")
if not image or not Path(image).is_file():
raise RuntimeError("Pull the course image using Step 8, Route A, then source setup-env.")
work = Path(tempfile.mkdtemp(prefix="podi-airfoil-")).resolve()
base = work / "base"
container = ["apptainer", "run", "--cleanenv", "--bind", f"{work}:{work}", image]
archive = Path(os.environ["ML_CFD_BASE"]) / "downloads" / "airFoil2D-v2606.zip"
with zipfile.ZipFile(archive) as tutorial:
tutorial.extractall(base)
shutil.copytree(base / "constant/polyMesh.orig", base / "constant/polyMesh")
shutil.copytree(base / "0.orig", base / "0")
def run(case, *args):
log = case / ("log." + args[0])
with log.open("w") as stream:
subprocess.run([*container, *args], cwd=case, stdout=stream, stderr=subprocess.STDOUT, check=True)
return log.read_text()
run(base, "renumberMesh", "-overwrite")
assert "Mesh OK." in run(base, "checkMesh")
run(base, "foamDictionary", "system/controlDict", "-entry", "endTime", "-set", "1500")
run(base, "foamDictionary", "system/controlDict", "-entry", "writeInterval", "-set", "1500")POD with interpolation for steady airfoil flow
Reduced-order modeling — code companion
We predict both in-plane velocity components and the kinematic pressure at an intermediate angle of attack. The lecture develops the equations.
Follow Setting up your system, Step 4 and Step 8, Route A, to prepare the course Python environment and pull the OpenFOAM image into the repository root. From that root, run:
source ml-cfd/bin/activate
source setup-env
cd notebooks
export PODI_RENDERER=mathtext # Use Matplotlib’s built-in math renderer.
python reduced_order_modeling_code.pyPython assembles the snapshots and runs the POD on the host. Apptainer runs the OpenFOAM commands. The plotting cells use Matplotlib and write the five light/dark figure pairs to media/. For the lecture’s LaTeX typography on a TeX-equipped host, set PODI_RENDERER=latex.
Download Python source Download figure style Download figure utilities
Prepare a common mesh
The repository includes the case inputs from the OpenFOAM.com v2606 tutorial incompressible/simpleFoam/airFoil2D. We unpack the mesh and dictionaries into a fresh temporary directory, renumber it once to order the faces, then use that identical mesh and cell numbering for every snapshot.
We identify the mesh leading and trailing edges from the wall vertices. Their connecting line sets the zero of incidence for every case.
mesh = base / "constant/polyMesh"
points = np.array([row.split() for row in re.findall(r"^\(([^()\n]+)\)$",
(mesh/"points").read_text(), re.M)], dtype=float)
faces = np.array([row.split() for row in re.findall(r"^4\(([^)]+)\)$",
(mesh/"faces").read_text(), re.M)], dtype=int)
def patch_faces(name):
block = re.search(rf"\b{name}\s*\{{([^}}]+)", (mesh/"boundary").read_text())[1]
start = int(re.search(r"startFace\s+(\d+)", block)[1])
count = int(re.search(r"nFaces\s+(\d+)", block)[1])
return np.arange(start, start+count)
segments = np.array([np.unique(points[f, :2], axis=0) for f in faces[patch_faces("walls")]])
ends = segments.reshape(-1, 2)
le, te = ends[ends[:, 0].argmin()], ends[ends[:, 0].argmax()]
chord = np.linalg.norm(te-le)
chord_angle = np.degrees(np.arctan2(*(te-le)[::-1]))
print("Mesh chord (m), inclination (deg):", chord, chord_angle)Run one steady calculation per angle
We vary the direction of the freestream velocity at fixed speed (26 m/s) and kinematic viscosity. We set both freestream patches explicitly because renumbering expands the original references to $internalField. The no-slip wall, turbulence settings and freestream pressure reference stay the same. Mach number is absent from this incompressible model. Each column will be the converged field for one angle. Intermediate SIMPLE iterations have no role as time snapshots.
def solve(angle):
# Each invocation starts from the prepared mesh, including notebook reruns.
case = Path(tempfile.mkdtemp(prefix=f"angle_{angle:g}_", dir=work))
shutil.copytree(base, case, dirs_exist_ok=True)
radians = np.deg2rad(angle + chord_angle)
ux, uy = speed * np.cos(radians), speed * np.sin(radians)
velocity = f"uniform ({ux:.12g} {uy:.12g} 0)"
entries = ["internalField"]
for patch in ("inlet", "outlet"):
entries.extend([f"boundaryField/{patch}/freestreamValue", f"boundaryField/{patch}/value"])
for entry in entries:
run(case, "foamDictionary", "0/U", "-entry", entry, "-set", velocity)
start = time.perf_counter()
log = run(case, "simpleFoam", "-noFunctionObjects")
elapsed = time.perf_counter() - start
match = re.search(r"SIMPLE solution converged in (\d+) iterations", log)
if not match:
raise RuntimeError(f"No residual convergence at {angle:g} degrees. See {case}.")
iteration = match.group(1)
print(f"{angle:g} degrees: {iteration} iterations, {elapsed:.2f} s")
return case / iteration
speed = 26.0
angles = np.array([0., 2., 4., 6., 8.])
fields = [solve(angle) for angle in angles]
test_angle = 5.Stack the dimensionless fields and compute a weighted POD
The three blocks follow the same cell order. Each receives the same cell-volume fractions. Dividing by total volume makes the squared norm a volume average and leaves the relative weighting of cells unchanged.
def internal_field(path, components):
kind = {1: "scalar", 3: "vector"}[components]
pattern = rf"internalField\s+nonuniform\s+List<{kind}>\s+(\d+)\s*\((.*?)\n\)\s*;"
match = re.search(pattern, path.read_text(), re.S)
if not match:
raise ValueError(f"Expected an ASCII {kind} list in {path}")
values = np.fromstring(match[2].replace("(", " ").replace(")", " "), sep=" ")
values = values.reshape(int(match[1]), components)
assert np.isfinite(values).all()
return values
def snapshot(folder):
velocity = internal_field(folder / "U", 3)
assert np.allclose(velocity[:, 2], 0)
pressure = internal_field(folder / "p", 1)[:, 0]
return np.concatenate([velocity[:, 0]/speed, velocity[:, 1]/speed, pressure/speed**2])
first = fields[0]
run(first.parent, "postProcess", "-func", "writeCellVolumes", "-time", first.name)
volumes = internal_field(first / "V", 1)[:, 0]
assert np.all(volumes > 0)
weights = np.tile(volumes / volumes.sum(), 3)
sqrt_w = np.sqrt(weights)
X = np.column_stack([snapshot(field) for field in fields])
def pod(matrix, rank=2):
mean = matrix.mean(axis=1)
Q, sigma, Vt = np.linalg.svd(sqrt_w[:, None] * (matrix - mean[:, None]),
full_matrices=False)
modes = Q[:, :rank] / sqrt_w[:, None]
coeff = sigma[:rank, None] * Vt[:rank]
# Choose reproducible signs for the displayed coefficients and mode fields.
for i, row in enumerate(coeff):
if row[np.argmax(abs(row))] < 0:
modes[:, i] *= -1
coeff[i] *= -1
assert np.allclose(modes.T @ (weights[:, None]*modes), np.eye(rank))
return mean, modes, coeff, sigma
mean, modes, coeff, sigma = pod(X)
print("Singular values:", sigma)
print("Retained variance fraction:", sum(sigma[:2]**2)/sum(sigma**2))
print("Training coefficients:", coeff)Choose a coefficient model using the training angles
We compare piecewise linear interpolation with a quadratic least-squares fit. We omit each interior training angle in turn, refit the mean, POD and coefficient model, and compare the reconstruction with the omitted field. Holding out an endpoint would test extrapolation.
def amplitudes(method, training_angles, coordinates, query):
if method == "linear":
return np.array([np.interp(query, training_angles, row) for row in coordinates])
return np.array([np.polynomial.Polynomial.fit(training_angles, row, 2)(query)
for row in coordinates])
methods = ["linear", "quadratic"]
scores = {}
for method in methods:
fold_errors = []
for j in range(1, len(angles)-1):
keep = np.arange(len(angles)) != j
center, basis, coords, _ = pod(X[:, keep])
estimate = center + basis @ amplitudes(method, angles[keep], coords, angles[j])
fold_errors.append(np.linalg.norm(sqrt_w * (estimate-X[:, j])))
scores[method] = np.mean(fold_errors)
print("Mean omitted-angle errors:", scores)
selected = min(scores, key=scores.get)Predict and evaluate the independent case
We compare the three reconstructed blocks directly with the dimensionless reference snapshot. The difference uses the same normalization as each field.
z_hat = amplitudes(selected, angles, coeff, test_angle)
prediction = (mean + modes @ z_hat).reshape(3, -1)
reference = snapshot(solve(test_angle)).reshape(3, -1)
difference = prediction - reference
relative = np.sqrt((difference**2 @ volumes) / (reference**2 @ volumes))
print("Relative component errors:", relative)Draw fields on the finite-volume mesh
One face on the front plane supplies the actual polygon of each cell. We color these faces directly, keeping the solid airfoil empty. Wall-face endpoints give the airfoil outline and the chord of the discretized profile.
from io import BytesIO
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection, PolyCollection
from matplotlib.patches import Arc
from figure_style import WIDTH_MM, figure_style
from figure_utils import save_theme_variants
owner_text = re.search(r"\n\s*\d+\s*\(([^()]*)\)", (mesh/"owner").read_text())[1]
owners = np.fromstring(owner_text, sep=" ", dtype=int)
assert len(faces) == len(owners)
segments = (segments-le)/chord
ids = patch_faces("frontAndBack")
ids = ids[np.all(points[faces[ids], 2] == points[:, 2].min(), axis=1)]
ids = ids[np.argsort(owners[ids])]
assert np.array_equal(owners[ids], np.arange(len(volumes)))
polygons = (points[faces[ids], :2]-le)/chord
centers = polygons.mean(axis=1)
window = (abs(centers[:, 0]-.5)<.95) & (abs(centers[:, 1])<.7)
labels = [r"$u_x/U_\infty$", r"$u_y/U_\infty$", r"$p/U_\infty^2$"]
media = Path(os.getenv("PODI_MEDIA", "media"))
width = WIDTH_MM["double"]/25.4
renderer = os.environ.get("PODI_RENDERER", "latex")
if renderer not in ("mathtext", "latex"):
raise ValueError("PODI_RENDERER must be mathtext or latex.")
plot_style = figure_style(use_tex=renderer == "latex")
def style():
mpl.rcParams.update(plot_style)
mpl.rcParams["axes.prop_cycle"] = mpl.rcParamsDefault["axes.prop_cycle"]
def sketch():
style()
fig, ax = plt.subplots(figsize=(width, 2.15), layout="constrained")
ax.add_collection(LineCollection(segments, colors=mpl.rcParams["text.color"], linewidths=1.5))
tip = (te-le)/chord
ax.plot([-.68, tip[0]], [-.68*tip[1]/tip[0], tip[1]], "--", color="C7", lw=1)
# The angle is exaggerated for readability.
origin = np.array([-.65, -.65*tip[1]/tip[0]])
direction = np.deg2rad(22)
ax.annotate("", origin+.52*np.array([np.cos(direction), np.sin(direction)]), origin,
arrowprops=dict(arrowstyle="->", color="C0", lw=2))
ax.add_patch(Arc(origin, .42, .42, theta1=chord_angle, theta2=22, color="C1"))
ax.text(-.4,.035,r"$\alpha$", fontsize=13)
ax.text(-.62,.21,r"$U_\infty=26\,\mathrm{m/s}$")
ax.annotate("", (tip[0],-.15), (0,-.15), arrowprops=dict(arrowstyle="<->"))
for x in [0,tip[0]]:
ax.plot([x,x],[-.17,-.03],":", color="C7")
ax.text(.5,-.19,r"Chord length $c$",ha="center",va="top")
ax.set(xlim=(-.72,1.08),ylim=(-.25,.32),aspect="equal")
ax.axis("off")
return fig
def curves():
style()
fig, (spectrum, *trends) = plt.subplots(1,3,figsize=(width,2.4), layout="constrained")
spectrum.semilogy(range(1,5), sigma[:4], "o-", color="C0")
spectrum.set(xlabel="Mode index", ylabel=r"Singular value $\sigma_i$", xticks=range(1,5))
grid = np.linspace(angles[0],angles[-1],161)
for i, (trend, marker) in enumerate(zip(trends, ["o","s"])):
trend.plot(grid, amplitudes(selected,angles,coeff,grid)[i], color=f"C{i}",
linestyle=["-","--"][i], label=f"Mode {i+1}")
trend.plot(angles, coeff[i], marker, color=f"C{i}")
trend.set(xlabel=r"$\alpha$ (deg)", title=rf"Coefficient $z_{i+1}$", xticks=angles)
trend.ticklabel_format(axis="y",style="sci",scilimits=(-2,2))
return fig
def field_grid(rows, row_labels, titles, shared_columns=0):
style()
fig, axes = plt.subplots(len(rows), len(titles), figsize=(width, 1.65*len(rows)+.28),
layout="constrained", squeeze=False)
for i,(values, axes_row) in enumerate(zip(rows,axes)):
for j,(field,ax) in enumerate(zip(values,axes_row)):
scale = (max(np.max(abs(v[window])) for v in values[:shared_columns])
if j < shared_columns else np.max(abs(field[window])))
artist = PolyCollection(polygons[window], array=field[window], cmap="RdBu_r",
edgecolors="face", linewidths=.15, clim=(-scale,scale))
ax.add_collection(artist)
ax.set(xlim=(-.15,1.15),ylim=(-.32,.32),aspect="equal",xticks=[0,.5,1],
yticks=[-.25,0,.25])
if i==0:
ax.set_title(titles[j])
if j==0:
ax.set_ylabel(row_labels[i]+"\n"+r"$y/c$")
if i==len(rows)-1:
ax.set_xlabel(r"$x/c$")
cb = fig.colorbar(artist, ax=ax, location="bottom", shrink=.9, pad=.04,
format="%.2g", ticks=[-scale,0,scale])
cb.ax.tick_params(labelsize=8)
return fig
# Each mode column is reshaped into three blocks, in the same order used to
# assemble X. Comparisons use dimensionless fields and full-domain error metrics.
modal_fields = modes.T.reshape(2, 3, -1)
with mpl.rc_context(plot_style):
smoke = plt.figure()
smoke.text(.1,.5,r"$p/U_\infty^2$")
smoke.savefig(BytesIO(),format="png")
plt.close(smoke)
for stem, draw in [
("setup", sketch), ("coefficients", curves),
("modes", lambda: field_grid(modal_fields.transpose(1,0,2), labels, ["Mode 1","Mode 2"])),
("incidence", lambda: field_grid(X[:, ::2].T.reshape(3, 3, -1).transpose(1, 0, 2),
labels, [rf"$\alpha={a:g}^\circ$" for a in angles[::2]],
shared_columns=3)),
("comparison", lambda: field_grid(np.stack([reference,prediction,difference],axis=1),
labels, ["CFD","PODI","PODI minus CFD"], shared_columns=2)),
]:
save_theme_variants(draw, media/f"podi-{stem}.png", dpi=300)