"""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()