File size: 10,701 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""Compute the surface field errors and the integral force coefficients from the meshes.

Every prediction mesh should contain both the CFD ground truth and the prediction of each surface
field.

Field errors
    Computed per run for the pressure coefficient Cp and the wall shear stress magnitude |ws|.
    With ground truth t, prediction p, error e = p - t and N surface elements, an absolute and
    a relative family of metrics is stored:

        mse_abs = mean(e^2)                  l1_abs = mean(|e|)
        l2_abs  = sqrt(sum(e^2))             rmse_abs = sqrt(mse_abs)
        srmse   = rmse_abs / std(t)

        mse_rel = sum(e^2) / sum(t^2)        l1_rel = sum(|e|) / sum(|t|)
        l2_rel  = sqrt(sum(e^2) / sum(t^2))
        r2      = 1 - sum(e^2) / sum((t - mean(t))^2)

Force coefficients
    Drag and lift are integrated over the surface from the cell areas A, the cell normals n and
    the dynamic pressure q:

        F/q = sum(Cp * n * A) + sum(tau * A) / q
        Cd  = (F/q)_x / reference_area
        Cl  = (F/q)_z / reference_area


Writes outputs per split and per model under outputs/metrics/, merged into field_metrics.csv 
and coefficients.csv. 
Existing files are reused unless --force is given. 
Run this before coefficient_error.py and field_screenshots.py, which read its output.

Examples:
    python3 surface_metrics.py                                  # everything, 8 workers
    python3 surface_metrics.py --splits stratified --models abupt
    python3 surface_metrics.py --force --workers 6
"""

from __future__ import annotations

import argparse
import multiprocessing as mp
import os
import sys
from pathlib import Path

import numpy as np
import pandas as pd

sys.path.insert(0, str(Path(__file__).resolve().parent))

from inference_io import (  # noqa: E402
    all_model_labels,
    coeff_columns,
    field_keys,
    mesh_files,
    mesh_models,
    metrics_dir,
    read_field,
    splits as all_splits,
)

# Flow conditions of the dataset, as configured for every model's training run.
air_density = 1.18858
stream_velocity = 50.0
reference_area = 1.0
dynamic_pressure = 0.5 * air_density * stream_velocity**2

metric_columns = [
    "n",
    "t_mean",
    "t_std",
    "p_mean",
    "p_std",
    "mse_abs",
    "l1_abs",
    "l2_abs",
    "rmse_abs",
    "srmse",
    "mse_rel",
    "l1_rel",
    "l2_rel",
    "r2",
]
field_columns = ["split", "model", "run_id", "field", *metric_columns]
coefficient_columns = ["split", "model", "run_id", *coeff_columns]


def _magnitude(values: np.ndarray) -> np.ndarray:
    """Collapse a vector field to its magnitude; scalars pass through."""
    return np.linalg.norm(values, axis=1) if values.ndim == 2 else values


def _metrics(truth: np.ndarray, pred: np.ndarray) -> dict[str, float]:
    error = pred - truth
    sq_error = float(np.sum(error**2))
    sq_truth = float(np.sum(truth**2))
    n = truth.size
    variance = float(np.sum((truth - truth.mean()) ** 2))
    mse_abs = sq_error / n
    return {
        "n": n,
        "t_mean": float(truth.mean()),
        "t_std": float(truth.std()),
        "p_mean": float(pred.mean()),
        "p_std": float(pred.std()),
        "mse_abs": mse_abs,
        "l1_abs": float(np.abs(error).mean()),
        "l2_abs": float(np.sqrt(sq_error)),
        "rmse_abs": float(np.sqrt(mse_abs)),
        "srmse": float(np.sqrt(mse_abs) / truth.std()) if truth.std() > 0 else np.nan,
        "mse_rel": sq_error / sq_truth if sq_truth > 0 else np.nan,
        "l1_rel": float(np.abs(error).sum() / np.abs(truth).sum())
        if np.abs(truth).sum() > 0
        else np.nan,
        "l2_rel": float(np.sqrt(sq_error / sq_truth)) if sq_truth > 0 else np.nan,
        "r2": 1.0 - sq_error / variance if variance > 0 else np.nan,
    }


def _coefficients(mesh) -> dict[str, float]:
    """Drag and lift of the ground truth and of the prediction, by surface integration."""
    # The fields are cell data for most models and point data for X-MeshGraphNet; the integral
    # needs one value per cell either way.
    if "MeanPressureCoefficient" in mesh.point_data:
        mesh = mesh.point_data_to_cell_data(pass_point_data=False)

    areas = np.asarray(
        mesh.compute_cell_sizes(length=False, area=True, volume=False).cell_data["Area"],
        dtype=np.float64,
    )
    normals = np.asarray(
        mesh.compute_normals(
            cell_normals=True,
            point_normals=False,
            consistent_normals=False,
            auto_orient_normals=False,
        ).cell_data["Normals"],
        dtype=np.float64,
    )

    arrays = {
        f"{name}{suffix}": read_field(mesh, f"{name}{suffix}")
        for name in field_keys
        for suffix in ("", "Pred")
    }

    # One mask for all four arrays, so the truth and the prediction are integrated over exactly
    # the same cells even when a prediction is non-finite on one of them.
    finite = np.ones(len(areas), dtype=bool)
    for values in arrays.values():
        finite &= np.isfinite(values).all(axis=1) if values.ndim == 2 else np.isfinite(values)

    out = {}
    for suffix in ("", "Pred"):
        cp = arrays[f"MeanPressureCoefficient{suffix}"][finite]
        shear = arrays[f"MeanWallShearStress{suffix}"][finite]
        force = (cp[:, None] * normals[finite] * areas[finite, None]).sum(axis=0)
        force += (shear * areas[finite, None]).sum(axis=0) / dynamic_pressure
        out[f"Cd{suffix}"] = float(force[0] / reference_area)
        out[f"Cl{suffix}"] = float(force[2] / reference_area)
    return out


def _process(task: tuple[str, str, str, str]) -> tuple[list[dict], dict]:
    """Worker: read one mesh and return its field rows and its coefficient row."""
    import pyvista as pv

    split, model, run_id, path = task
    mesh = pv.read(path)

    rows = []
    for array, field in field_keys.items():
        truth = _magnitude(read_field(mesh, array))
        pred = _magnitude(read_field(mesh, f"{array}Pred"))
        if truth.shape != pred.shape:
            raise ValueError(
                f"{path}: {array} shape {truth.shape} != prediction {pred.shape}"
            )
        # Non-finite elements are dropped so the run still yields a metric; `n` records how
        # many elements were actually used.
        finite = np.isfinite(truth) & np.isfinite(pred)
        if not finite.all():
            print(f"    {run_id} {field}: dropped {int((~finite).sum())} "
                  f"non-finite element(s) of {finite.size}", flush=True)
            truth, pred = truth[finite], pred[finite]
        rows.append(
            {"split": split, "model": model, "run_id": run_id, "field": field,
             **_metrics(truth, pred)}
        )

    coefficients = {"split": split, "model": model, "run_id": run_id, **_coefficients(mesh)}
    return rows, coefficients


def _shard_paths(split: str, model: str) -> tuple[Path, Path]:
    return (
        metrics_dir / f"{split}__{model}__fields.csv",
        metrics_dir / f"{split}__{model}__coefficients.csv",
    )


def compute_shard(split: str, model: str, workers: int, force: bool) -> None:
    """Compute (or reuse) the field metrics and coefficients for one split/model."""
    field_path, coeff_path = _shard_paths(split, model)
    if field_path.exists() and coeff_path.exists() and not force:
        print(f"  {split}/{model}: cached ({field_path.name})", flush=True)
        return

    meshes = mesh_files(split, model)
    tasks = [(split, model, run_id, str(p)) for run_id, p in meshes.items()]
    print(f"  {split}/{model}: {len(tasks)} meshes on {workers} workers", flush=True)

    field_rows: list[dict] = []
    coeff_rows: list[dict] = []
    with mp.Pool(processes=workers) as pool:
        for i, (rows, coefficients) in enumerate(
            pool.imap_unordered(_process, tasks, chunksize=1), 1
        ):
            field_rows.extend(rows)
            coeff_rows.append(coefficients)
            if i % 10 == 0 or i == len(tasks):
                print(f"    {i}/{len(tasks)}", flush=True)

    metrics_dir.mkdir(parents=True, exist_ok=True)
    (
        pd.DataFrame(field_rows, columns=field_columns)
        .sort_values(["run_id", "field"])
        .reset_index(drop=True)
        .to_csv(field_path, index=False)
    )
    (
        pd.DataFrame(coeff_rows, columns=coefficient_columns)
        .sort_values("run_id")
        .reset_index(drop=True)
        .to_csv(coeff_path, index=False)
    )


def _merge(pattern: str, sort_by: list[str], out_name: str) -> pd.DataFrame:
    """Concatenate every shard matching `pattern` into one file under outputs/metrics/."""
    paths = sorted(metrics_dir.glob(pattern))
    if not paths:
        raise FileNotFoundError(f"no shards matching {pattern} under {metrics_dir}")
    merged = pd.concat(
        [pd.read_csv(p, dtype={"run_id": str}) for p in paths], ignore_index=True
    )
    split_order = {name: i for i, name in enumerate(all_splits)}
    model_order = {name: i for i, name in enumerate(all_model_labels)}
    merged = merged.sort_values(
        sort_by,
        key=lambda s: s.map(split_order) if s.name == "split"
        else (s.map(model_order) if s.name == "model" else s),
    ).reset_index(drop=True)
    out = metrics_dir / out_name
    merged.to_csv(out, index=False)
    print(f"wrote {out} ({len(merged)} rows)")
    return merged


def merge_shards() -> pd.DataFrame:
    """Merge both shard families; returns the field metrics."""
    print()
    _merge("*__coefficients.csv", ["split", "model", "run_id"], "coefficients.csv")
    return _merge(
        "*__fields.csv", ["split", "model", "run_id", "field"], "field_metrics.csv"
    )


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    parser.add_argument("--splits", nargs="+", default=all_splits, choices=all_splits)
    parser.add_argument("--models", nargs="+", default=mesh_models(),
                        choices=list(all_model_labels))
    parser.add_argument("--workers", type=int,
                        default=max(1, min(8, (os.cpu_count() or 4) - 2)))
    parser.add_argument("--force", action="store_true",
                        help="recompute shards that already exist")
    args = parser.parse_args()

    for split in args.splits:
        print(f"{split}:")
        for model in args.models:
            compute_shard(split, model, args.workers, args.force)

    merged = merge_shards()
    summary = (
        merged.groupby(["split", "model", "field"], sort=False)
        .agg(runs=("run_id", "nunique"), l2_rel=("l2_rel", "mean"), mse=("mse_abs", "mean"))
        .reset_index()
    )
    print(summary.to_string(index=False))


if __name__ == "__main__":
    main()