Ground-Wing / scripts /plotting /field_screenshots.py
andreacenzato's picture
Added description and analysis files
f355580 verified
Raw History Blame Contribute Delete
6.37 kB
"""Surface-field screenshots of the benchmark predictions on one reference test run.
Renders the surface fields seen from below, looking towards +Z.
One PNG per model per quantity; the panels are composed side by side in the
paper's LaTeX rather than montaged here.
Outputs, under ``outputs/fields/``:
cp_truth.png CFD ground-truth surface C_p
cp_pred_<model>.png predicted C_p, one per model
cp_err_<model>.png signed error (prediction - truth), one per model
ws_truth.png CFD ground-truth |w_s|
ws_pred_<model>.png predicted |w_s|, one per model
Run surface_metrics.py first: the panels are ordered by each model's mean $C_l$ error.
"""
from __future__ import annotations
import sys
from pathlib import Path
import numpy as np
import pyvista as pv
sys.path.insert(0, str(Path(__file__).resolve().parent))
from inference_io import ( # noqa: E402
field_keys,
here,
model_labels,
load_coefficients,
mesh_files,
read_field,
relative_error,
reported_models,
)
pv.OFF_SCREEN = True
reference_run = "0169_7575"
reference_split = "stratified"
output_dir = here / "outputs" / "fields"
output_dir.mkdir(parents=True, exist_ok=True)
cp_field = "MeanPressureCoefficient"
ws_field = "MeanWallShearStress"
assert set(field_keys) == {cp_field, ws_field}, field_keys
colormap = "turbo"
window_size = (1700, 780)
# (colour limits, colourbar title) per rendered quantity
specs = {
"cp": ((-2.0, 1.0), r"$C_p$"),
"cp_err": ((-0.3, 0.3), r"$\Delta C_p$"),
"ws": ((0.0, 25.0), r"$w_s$"),
}
def ranked_models() -> list[str]:
"""Model keys ordered by mean relative Cl error on the stratified split, best first."""
err = {
model: relative_error(load_coefficients("stratified", model), "Cl").mean()
for model in reported_models()
}
return sorted(err, key=err.get)
def attach(mesh, values, name="field"):
"""Attach `values` to the mesh, choosing cell or point association by length."""
if len(values) == mesh.n_cells:
mesh.cell_data[name] = values
elif len(values) == mesh.n_points:
mesh.point_data[name] = values
else:
raise ValueError(
f"{len(values)} values match neither n_cells={mesh.n_cells} "
f"nor n_points={mesh.n_points}"
)
return name
def field_values(mesh, field: str, kind: str) -> np.ndarray:
"""Ground truth, prediction or signed error (prediction - truth) of one field.
The wall shear stress is a vector, and the paper reports its magnitude.
"""
truth = read_field(mesh, field)
pred = read_field(mesh, f"{field}Pred")
if truth.ndim == 2:
truth = np.linalg.norm(truth, axis=1)
pred = np.linalg.norm(pred, axis=1)
return {"truth": truth, "pred": pred, "error": pred - truth}[kind]
def render(mesh, name: str, clim, title: str, path: Path) -> Path:
"""Bottom view of one field: camera below the wing, looking towards +Z."""
plotter = pv.Plotter(off_screen=True, window_size=window_size)
plotter.set_background("white")
plotter.add_mesh(
mesh, scalars=name, cmap=colormap, clim=clim, lighting=False, show_scalar_bar=False
)
plotter.add_scalar_bar(
title=title,
vertical=False,
position_x=0.20,
position_y=0.10,
width=0.60,
height=0.055,
title_font_size=34,
label_font_size=28,
color="black",
n_labels=5,
fmt="%.1f",
)
# +X (chord) points up in the frame, so the span runs horizontally. Parallel projection
# with an explicit scale keeps the framing pixel-identical across every panel.
plotter.view_xy(negative=True)
plotter.camera.up = (1.0, 0.0, 0.0)
plotter.enable_parallel_projection()
bounds = mesh.bounds
scale = ((bounds.y_max - bounds.y_min) / 2) / (window_size[0] / window_size[1]) / 0.96
mid_x = (bounds.x_min + bounds.x_max) / 2
mid_y = (bounds.y_min + bounds.y_max) / 2
mid_z = (bounds.z_min + bounds.z_max) / 2
lift = 0.34 * scale # frees the bottom band of the frame for the colourbar
plotter.camera.parallel_scale = scale
plotter.camera.focal_point = (mid_x - lift, mid_y, mid_z)
plotter.camera.position = (mid_x - lift, mid_y, bounds.z_min - 5.0)
plotter.add_axes(
color="black",
xlabel="x",
ylabel="y",
zlabel="z",
viewport=(0.005, 0.02, 0.095, 0.27),
label_size=(0.20, 0.13),
)
plotter.screenshot(str(path))
plotter.close()
return path
def emit(mesh, field: str, kind: str, spec: str, path: Path) -> Path:
"""Render one panel."""
values = field_values(mesh, field, kind)
clim, title = specs[spec]
render(mesh, attach(mesh, values), clim, title, path)
return path
def main() -> None:
order = ranked_models()
print("reference run :", reference_run, f"({reference_split} split)")
print("model order :", ", ".join(model_labels[m] for m in order))
# Surface C_p: ground truth, the six predictions, and the six signed error fields. The
# ground truth is the same CFD field on the same mesh for every model, so it is rendered
# once, from the best-ranked model's copy.
truth_mesh = pv.read(mesh_files(reference_split, order[0])[reference_run])
emit(truth_mesh, cp_field, "truth", "cp", output_dir / "cp_truth.png")
print("rendered C_p ground truth")
for model in order:
mesh = pv.read(mesh_files(reference_split, model)[reference_run])
emit(mesh, cp_field, "pred", "cp", output_dir / f"cp_pred_{model}.png")
emit(mesh, cp_field, "error", "cp_err", output_dir / f"cp_err_{model}.png")
print(f"rendered C_p {model_labels[model]}")
# Surface wall-shear-stress magnitude: ground truth and the six predictions.
truth_mesh = pv.read(mesh_files(reference_split, order[0])[reference_run])
emit(truth_mesh, ws_field, "truth", "ws", output_dir / "ws_truth.png")
print("rendered |w_s| ground truth")
for model in order:
mesh = pv.read(mesh_files(reference_split, model)[reference_run])
emit(mesh, ws_field, "pred", "ws", output_dir / f"ws_pred_{model}.png")
print(f"rendered |w_s| {model_labels[model]}")
print(f"\nwrote 20 panels to {output_dir}")
if __name__ == "__main__":
main()