Ground-Wing / scripts /plotting /inference_io.py
andreacenzato's picture
Added description and analysis files
f355580 verified
Raw History Blame Contribute Delete
4.6 kB
"""Shared utilities for reading the benchmark inference results.
Inference outputs are read from the directory specified by the inference_dir variable, laid out
as <inference_dir>/<split>/<model>/ with one prediction mesh per test run, named <run_id>.vtp
Each mesh is expected to contain both the CFD ground truth and the prediction for every surface field.
"""
from __future__ import annotations
from pathlib import Path
import numpy as np
import pandas as pd
import yaml
here = Path(__file__).resolve().parent
data_dir = here.parents[1] / "dataset_composition"
# Directory holding the inference results. Change this to point at your own results.
inference_dir = here / "inference"
output_dir = here / "outputs" / "results"
metrics_dir = here / "outputs" / "metrics"
splits = ["stratified", "outliers", "interpolated"]
# split key -> label used in the paper
split_labels = {
"stratified": "Stratified",
"outliers": "Drag-outlier",
"interpolated": "Interpolated",
}
# model directory name -> label used in the paper
model_labels = {
"abupt": "AB-UPT",
"geotransolver": "GeoTransolver",
"aerojepa": "AeroJEPA",
"gaot": "GAOT",
"xaeronet": "X-MeshGraphNet",
"domino": "DoMINO",
}
# Variants reported in an appendix only.
appendix_model_labels = {
"abupt_volume": "AB-UPT (volume-trained)",
}
all_model_labels = {**model_labels, **appendix_model_labels}
coeff_columns = ["Cd", "Cl", "CdPred", "ClPred"]
# surface fields carried by every prediction mesh, as <truth array> -> <short key>
field_keys = {
"MeanPressureCoefficient": "Cp",
"MeanWallShearStress": "ws",
}
field_labels = {"Cp": r"$C_p$", "ws": r"$|\bm{w_s}|$"}
def reported_models() -> list[str]:
"""Model keys in reporting order (every model of the main benchmark)."""
return list(model_labels)
def mesh_models() -> list[str]:
"""Model keys whose prediction meshes are swept by ``surface_metrics.py``."""
return reported_models() + list(appendix_model_labels)
def test_run_ids(split: str) -> list[str]:
"""Run IDs ('XXXX_YYYY') of a split's test set, from split_<split>.yaml."""
with (data_dir / f"split_{split}.yaml").open() as fh:
return [str(run) for run in yaml.safe_load(fh)["test"]]
def read_field(mesh, name: str) -> np.ndarray:
"""Return one surface array of a prediction mesh as float64."""
for arrays in (mesh.cell_data, mesh.point_data):
if name in arrays:
return np.asarray(arrays[name], dtype=np.float64)
raise KeyError(f"array {name!r} is not on the mesh")
def mesh_files(split: str, model: str) -> dict[str, Path]:
"""Map run ID -> prediction mesh path for one split/model, in test-list order.
Raises when the directory does not hold a mesh for every test run of the split.
"""
directory = inference_dir / split / model
if not directory.is_dir():
raise FileNotFoundError(f"no inference directory for {split}/{model}: {directory}")
found = {path.stem: path for path in directory.glob("*.vtp")}
expected = test_run_ids(split)
absent = [run for run in expected if run not in found]
if absent:
raise FileNotFoundError(
f"{directory} is missing {len(absent)} of {len(expected)} test meshes: "
f"{', '.join(absent)}"
)
return {run: found[run] for run in expected}
def load_coefficients(split: str, model: str) -> pd.DataFrame:
"""Load one model's integral coefficients for one split, in test-list order.
Returns columns Run_ID, Cd, Cl, CdPred, ClPred.
"""
path = metrics_dir / "coefficients.csv"
if not path.exists():
raise FileNotFoundError(f"{path} is missing -- run `python3 surface_metrics.py` first")
df = pd.read_csv(path, dtype={"run_id": str})
block = df[(df["split"] == split) & (df["model"] == model)]
if block.empty:
raise ValueError(f"{path} holds no rows for {split}/{model}")
return _in_test_order(block.rename(columns={"run_id": "Run_ID"}), split)
def _in_test_order(df: pd.DataFrame, split: str) -> pd.DataFrame:
"""Restrict to the split's test runs and order them as the split file lists them."""
rank = {run: i for i, run in enumerate(test_run_ids(split))}
df = df[df["Run_ID"].isin(rank)].sort_values("Run_ID", key=lambda s: s.map(rank))
return df[["Run_ID", *coeff_columns]].reset_index(drop=True)
def relative_error(df: pd.DataFrame, coeff: str) -> pd.Series:
"""Absolute percentage error per run: |pred - true| / |true| * 100."""
return (df[f"{coeff}Pred"] - df[coeff]).abs() / df[coeff].abs() * 100