File size: 4,599 Bytes
f355580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""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