Download scripts/plotting/coefficient_error.py from andreacenzato/Ground-Wing: direct link, hf CLI and curl.
- Browser
- Download file 25.3 kB
-
https://huggingface.co/datasets/andreacenzato/Ground-Wing/resolve/main/scripts/plotting/coefficient_error.py
- Command line
-
hf download hf://datasets/andreacenzato/Ground-Wing/scripts/plotting/coefficient_error.py
-
curl -L -o coefficient_error.py https://huggingface.co/datasets/andreacenzato/Ground-Wing/resolve/main/scripts/plotting/coefficient_error.py
25.3 kB
| """Benchmark results: every number and figure of the paper's benchmarking section. | |
| Two metrics are calculated: | |
| Integral coefficients: per-simulation absolute percentage error on $C_l$ and $C_d$ plus | |
| two coefficients of determination, $R^2_\\mathrm{fit}$ (squared Pearson correlation, i.e. the | |
| linearity of the predicted-versus-true scatter) and $R^2_{1:1}$ (taken about the $1{:}1$ | |
| line, so it also penalises bias and scale errors). | |
| Surface fields: MSE, relative $L_1$ and relative $L_2$ on $C_p$ and $|\\bm{w_s}|$, | |
| recomputed element by element from the prediction meshes by surface_metrics.py. | |
| Outputs, under outputs/results/: | |
| <split>/results_table.csv <split>/coefficient_error_boxplot.svg | |
| <split>/field_error_table.csv <split>/field_error_bars.svg | |
| <split>/r2_table.csv <split>/parity_grid.svg | |
| <split>/delta_cl_{abupt,xmeshgraphnet}.svg | |
| benchmark_summary.csv split_comparison.svg | |
| directional_accuracy.csv abupt_training_targets.csv | |
| The last section prints the LaTeX rows of tab:results, tab:field_errors, | |
| tab:results_splits and tab:abupt_targets. | |
| Run surface_metrics.py first: both the coefficients and the surface-field tables read its | |
| output. | |
| """ | |
| from __future__ import annotations | |
| import sys | |
| from pathlib import Path | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| from scipy import stats | |
| sys.path.insert(0, str(Path(__file__).resolve().parent)) | |
| from inference_io import ( # noqa: E402 | |
| appendix_model_labels, | |
| field_labels, | |
| metrics_dir, | |
| here, | |
| model_labels, | |
| output_dir, | |
| split_labels, | |
| splits, | |
| load_coefficients, | |
| relative_error, | |
| reported_models, | |
| test_run_ids, | |
| ) | |
| # Text is typeset by LaTeX in the paper's fonts and every figure is drawn at the width at | |
| # which it is included. | |
| text_width_in = 6.5 | |
| plt.rcParams.update({ | |
| "text.usetex": True, | |
| "text.latex.preamble": r"\usepackage{newtxtext,newtxmath}\usepackage{bm}", | |
| "font.family": "serif", | |
| "font.size": 9, | |
| "axes.labelsize": 9, | |
| "axes.titlesize": 9, | |
| "legend.fontsize": 8, | |
| "xtick.labelsize": 8, | |
| "ytick.labelsize": 8, | |
| "figure.dpi": 120, | |
| }) | |
| def save(fig, path: Path) -> Path: | |
| """Write one SVG and close the figure.""" | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| fig.savefig(path, format="svg", bbox_inches="tight") | |
| plt.close(fig) | |
| print(f" wrote {path.relative_to(here)}") | |
| return path | |
| # One colour per model, held fixed across every figure. | |
| model_colors = dict(zip(model_labels, plt.get_cmap("tab10").colors)) | |
| split_colors = dict(zip(splits, ["tab:blue", "tab:orange", "tab:green"])) | |
| coeffs = ("Cl", "Cd") | |
| coeff_labels = {"Cl": "$C_l$", "Cd": "$C_d$"} | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| print(f"figure output: {output_dir}\n") | |
| # --------------------------------------------------------------------------- | |
| # Integral coefficient accuracy | |
| # --------------------------------------------------------------------------- | |
| def coefficient_stats(split: str, model: str) -> dict: | |
| """Every coefficient-level statistic for one split/model.""" | |
| df = load_coefficients(split, model) | |
| row = { | |
| "split": split, | |
| "model_key": model, | |
| "model": model_labels[model], | |
| "samples": len(df), | |
| } | |
| for coeff in coeffs: | |
| key = coeff.lower() | |
| err = relative_error(df, coeff) | |
| true = df[coeff].to_numpy(dtype=float) | |
| pred = df[f"{coeff}Pred"].to_numpy(dtype=float) | |
| fit = stats.linregress(true, pred) | |
| row |= { | |
| f"{key}_mean_pct": err.mean(), | |
| f"{key}_std_pct": err.std(), | |
| f"{key}_median_pct": err.median(), | |
| f"{key}_p95_pct": float(np.percentile(err, 95)), | |
| f"{key}_max_pct": err.max(), | |
| f"{key}_r2_fit": fit.rvalue**2, | |
| f"{key}_r2_1to1": 1.0 | |
| - np.sum((pred - true) ** 2) / np.sum((true - true.mean()) ** 2), | |
| f"{key}_slope": fit.slope, | |
| } | |
| return row | |
| coefficients = pd.DataFrame( | |
| [coefficient_stats(split, model) for split in splits for model in reported_models()] | |
| ) | |
| def ranked_models(split: str) -> list[str]: | |
| """Model keys of one split ordered by mean Cl error, best first.""" | |
| block = coefficients[coefficients["split"] == split].sort_values("cl_mean_pct") | |
| return list(block["model_key"]) | |
| def boxplot_errors(split: str, output_path: Path) -> Path: | |
| """Per-simulation Cd (left) and Cl (right) relative-error distributions.""" | |
| models = ranked_models(split) | |
| frames = {m: load_coefficients(split, m) for m in models} | |
| labels = [model_labels[m] for m in models] | |
| fig, axes = plt.subplots(1, 2, figsize=(text_width_in, 3.1), sharex=True) | |
| for ax, coeff in zip(axes, ("Cd", "Cl")): | |
| box = ax.boxplot( | |
| [relative_error(frames[m], coeff) for m in models], | |
| tick_labels=labels, | |
| patch_artist=True, | |
| widths=0.6, | |
| flierprops=dict(marker=".", markersize=3, markeredgewidth=0.4), | |
| medianprops=dict(color="black", linewidth=1.0), | |
| ) | |
| for patch, model in zip(box["boxes"], models): | |
| patch.set_facecolor(model_colors[model]) | |
| patch.set_alpha(0.55) | |
| patch.set_linewidth(0.6) | |
| ax.set_ylabel(rf"{coeff_labels[coeff]} relative error [\%]") | |
| ax.set_yscale("log") | |
| ax.grid(True, which="both", axis="y", alpha=0.3, linewidth=0.4) | |
| ax.tick_params(axis="x", rotation=35) | |
| for label in ax.get_xticklabels(): | |
| label.set_horizontalalignment("right") | |
| fig.tight_layout() | |
| return save(fig, output_path) | |
| for split in splits: | |
| block = coefficients[coefficients["split"] == split].sort_values("cl_mean_pct") | |
| (output_dir / split).mkdir(parents=True, exist_ok=True) | |
| block.drop(columns="model_key").to_csv(output_dir / split / "results_table.csv", index=False) | |
| print("=" * 96) | |
| print(f"{split_labels[split]} split -- test set: {len(test_run_ids(split))} simulations") | |
| print("=" * 96) | |
| print( | |
| block[[ | |
| "model", "samples", | |
| "cl_mean_pct", "cl_std_pct", "cl_r2_fit", "cl_r2_1to1", | |
| "cd_mean_pct", "cd_std_pct", "cd_r2_fit", "cd_r2_1to1", | |
| ]].to_string(index=False, float_format=lambda v: f"{v:.3f}") | |
| ) | |
| boxplot_errors(split, output_dir / split / "coefficient_error_boxplot.svg") | |
| print() | |
| # Ranking by mean Cl error on the stratified split: the order every table and figure uses. | |
| paper_order = ranked_models("stratified") | |
| print(f"figure/table order (stratified ranking): {[model_labels[m] for m in paper_order]}") | |
| # --------------------------------------------------------------------------- | |
| # Surface field accuracy | |
| # --------------------------------------------------------------------------- | |
| field_stat_columns = [ | |
| "mse_abs", "l1_abs", "l2_abs", "rmse_abs", "srmse", "mse_rel", "l1_rel", "l2_rel", "r2", | |
| ] | |
| def load_field_metrics() -> pd.DataFrame: | |
| """Merged per-run field metrics for every split and model.""" | |
| path = metrics_dir / "field_metrics.csv" | |
| if not path.exists(): | |
| raise FileNotFoundError(f"{path} is missing -- run `python3 surface_metrics.py` first") | |
| merged = pd.read_csv(path, dtype={"run_id": str}) | |
| if merged[field_stat_columns].isna().any().any(): | |
| raise ValueError("field metrics contain NaNs") | |
| return merged | |
| field_metrics = load_field_metrics() | |
| field_summary = ( | |
| field_metrics.groupby(["split", "model", "field"]) | |
| .agg(runs=("run_id", "nunique"), **{ | |
| f"{c}_{stat}": (c, stat) | |
| for c in field_stat_columns | |
| for stat in ("mean", "std", "median") | |
| }) | |
| .reset_index() | |
| ) | |
| field_summary["model_label"] = field_summary["model"].map(model_labels) | |
| def field_error_bars(split: str, output_path: Path) -> Path: | |
| """Relative L2 per model, one panel per surface field, with the 1-sigma spread.""" | |
| models = ranked_models(split) | |
| block = field_summary[field_summary["split"] == split].set_index(["field", "model"]) | |
| fields = list(field_labels) | |
| means_all = { | |
| field: np.array([block.loc[(field, m), "l2_rel_mean"] for m in models]) * 100 | |
| for field in fields | |
| } | |
| spreads = { | |
| field: np.array([block.loc[(field, m), "l2_rel_std"] for m in models]) * 100 | |
| for field in fields | |
| } | |
| # The panels share their y-axis, so the limit has to leave room for the tallest bar of | |
| # either of them plus its label. | |
| top = 1.15 * max((means_all[f] + spreads[f]).max() for f in fields) | |
| fig, axes = plt.subplots(1, len(fields), figsize=(text_width_in, 2.8), sharey=True) | |
| x = np.arange(len(models)) | |
| for ax, field in zip(np.atleast_1d(axes), fields): | |
| means, spread = means_all[field], spreads[field] | |
| ax.bar( | |
| x, means, yerr=spread, capsize=2, | |
| color=[model_colors[m] for m in models], alpha=0.85, | |
| error_kw=dict(elinewidth=0.6, capthick=0.6), | |
| ) | |
| for xi, value, err in zip(x, means, spread): | |
| ax.annotate( | |
| f"{value:.1f}", (xi, value + err), textcoords="offset points", | |
| xytext=(0, 3), ha="center", fontsize=6, | |
| ) | |
| ax.set_ylim(0, top) | |
| ax.set_title(field_labels[field]) | |
| ax.set_xticks(x, [model_labels[m] for m in models], rotation=35, ha="right") | |
| ax.grid(True, axis="y", alpha=0.3, linewidth=0.4) | |
| np.atleast_1d(axes)[0].set_ylabel(r"Relative $L_2$ error [\%]") | |
| fig.tight_layout() | |
| return save(fig, output_path) | |
| paper_field_columns = ["mse_abs_mean", "l1_rel_mean", "l2_rel_mean"] | |
| for split in splits: | |
| block = field_summary[field_summary["split"] == split].copy() | |
| block["rank"] = block["model"].map({m: i for i, m in enumerate(ranked_models(split))}) | |
| block = block.sort_values(["field", "rank"]).drop(columns="rank") | |
| block.to_csv(output_dir / split / "field_error_table.csv", index=False) | |
| print("=" * 96) | |
| print(f"{split_labels[split]} split -- surface field errors") | |
| print("=" * 96) | |
| print( | |
| block[["field", "model_label", "runs", *paper_field_columns]].to_string( | |
| index=False, float_format=lambda v: f"{v:.4f}" | |
| ) | |
| ) | |
| field_error_bars(split, output_dir / split / "field_error_bars.svg") | |
| print() | |
| # --------------------------------------------------------------------------- | |
| # One row per split and model with every reported metric, plus the figure that puts the | |
| # three splits side by side. | |
| # --------------------------------------------------------------------------- | |
| field_wide = field_summary.pivot_table( | |
| index=["split", "model"], | |
| columns="field", | |
| values=["mse_abs_mean", "l1_rel_mean", "l2_rel_mean", "r2_mean", "srmse_mean"], | |
| ) | |
| field_wide.columns = [f"{field}_{metric}" for metric, field in field_wide.columns] | |
| field_wide = field_wide.reset_index() | |
| benchmark_summary = coefficients.merge( | |
| field_wide, left_on=["split", "model_key"], right_on=["split", "model"], | |
| suffixes=("", "_field"), | |
| ).drop(columns="model_field") | |
| benchmark_summary["rank"] = [ | |
| ranked_models(s).index(m) | |
| for s, m in zip(benchmark_summary["split"], benchmark_summary["model_key"]) | |
| ] | |
| benchmark_summary["split_rank"] = benchmark_summary["split"].map( | |
| {s: i for i, s in enumerate(splits)} | |
| ) | |
| benchmark_summary = ( | |
| benchmark_summary.sort_values(["split_rank", "rank"]) | |
| .drop(columns=["rank", "split_rank"]) | |
| .reset_index(drop=True) | |
| ) | |
| benchmark_summary.to_csv(output_dir / "benchmark_summary.csv", index=False) | |
| print(f"wrote {(output_dir / 'benchmark_summary.csv').relative_to(here)}") | |
| for split in splits: | |
| block = benchmark_summary[benchmark_summary["split"] == split] | |
| block.drop(columns="model_key").to_csv(output_dir / split / "r2_table.csv", index=False) | |
| def split_comparison(output_path: Path) -> Path: | |
| """Mean Cl and Cd error per model, grouped by split, with 1-sigma error bars.""" | |
| models = paper_order | |
| indexed = benchmark_summary.set_index(["split", "model_key"]) | |
| fig, axes = plt.subplots(1, 2, figsize=(text_width_in, 3.0), sharex=True) | |
| x = np.arange(len(models)) | |
| width = 0.26 | |
| for ax, coeff in zip(axes, coeffs): | |
| key = coeff.lower() | |
| for i, split in enumerate(splits): | |
| values = [indexed.loc[(split, m), f"{key}_mean_pct"] for m in models] | |
| errs = [indexed.loc[(split, m), f"{key}_std_pct"] for m in models] | |
| ax.bar( | |
| x + (i - 1) * width, values, width, yerr=errs, capsize=2, | |
| label=split_labels[split], color=split_colors[split], alpha=0.85, | |
| error_kw=dict(elinewidth=0.6, capthick=0.6), | |
| ) | |
| ax.set_ylabel(rf"Mean {coeff_labels[coeff]} error [\%]") | |
| ax.set_yscale("log") | |
| ax.set_xticks(x, [model_labels[m] for m in models], rotation=35, ha="right") | |
| ax.grid(True, which="both", axis="y", alpha=0.3, linewidth=0.4) | |
| axes[0].legend(loc="upper left", frameon=False) | |
| fig.tight_layout() | |
| return save(fig, output_path) | |
| split_comparison(output_dir / "split_comparison.svg") | |
| print("\n" + "=" * 96) | |
| print("Mean coefficient error across the three splits [%]") | |
| print("=" * 96) | |
| print( | |
| benchmark_summary.pivot_table( | |
| index="model", columns="split", values=["cl_mean_pct", "cd_mean_pct"] | |
| ).to_string(float_format=lambda v: f"{v:.2f}") | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Predicted-versus-true parity grid: one column per model, Cd on the top row and Cl on the | |
| # bottom, with both coefficients of determination annotated in each panel. | |
| # --------------------------------------------------------------------------- | |
| def parity_grid(split: str, output_path: Path) -> Path: | |
| models = ranked_models(split) | |
| indexed = coefficients.set_index(["split", "model_key"]) | |
| fig, axes = plt.subplots( | |
| 2, len(models), figsize=(text_width_in, 2.9), sharex="row", sharey="row" | |
| ) | |
| for row, coeff in enumerate(("Cd", "Cl")): | |
| frames = {m: load_coefficients(split, m) for m in models} | |
| lo = min(min(df[coeff].min(), df[f"{coeff}Pred"].min()) for df in frames.values()) | |
| hi = max(max(df[coeff].max(), df[f"{coeff}Pred"].max()) for df in frames.values()) | |
| pad = 0.05 * (hi - lo) | |
| lo, hi = lo - pad, hi + pad | |
| for col, model in enumerate(models): | |
| ax = axes[row, col] | |
| df = frames[model] | |
| ax.plot([lo, hi], [lo, hi], "k-", linewidth=0.6, zorder=1) | |
| ax.scatter( | |
| df[coeff], df[f"{coeff}Pred"], s=4, alpha=0.75, zorder=2, | |
| color=model_colors[model], edgecolors="none", | |
| ) | |
| row_stats = indexed.loc[(split, model)] | |
| key = coeff.lower() | |
| ax.annotate( | |
| f"$R^2_{{\\mathrm{{fit}}}}={row_stats[f'{key}_r2_fit']:.3f}$\n" | |
| f"$R^2_{{1{{:}}1}}={row_stats[f'{key}_r2_1to1']:.3f}$", | |
| (0.05, 0.95), xycoords="axes fraction", va="top", fontsize=6, | |
| ) | |
| ax.set_xlim(lo, hi) | |
| ax.set_ylim(lo, hi) | |
| ax.set_aspect("equal") | |
| ax.tick_params(labelsize=6, length=2, pad=1) | |
| ax.grid(True, alpha=0.25, linewidth=0.4) | |
| if row == 0: | |
| ax.set_title(model_labels[model], fontsize=7) | |
| if col == 0: | |
| ax.set_ylabel(rf"Predicted {coeff_labels[coeff]}", fontsize=8) | |
| ax.set_xlabel(rf"True {coeff_labels[coeff]}", fontsize=7) | |
| fig.tight_layout(h_pad=0.6, w_pad=0.3) | |
| return save(fig, output_path) | |
| for split in splits: | |
| parity_grid(split, output_dir / split / "parity_grid.svg") | |
| # --------------------------------------------------------------------------- | |
| # Directional consistency. Every ordered pair of test simulations contributes a true and a | |
| # predicted coefficient delta; a pair counts as a directional match when the two have the | |
| # same sign. Only the half-plane of positive true deltas is evaluated -- the pair (a, b) and | |
| # its mirror (b, a) carry the same information. | |
| # --------------------------------------------------------------------------- | |
| delta_threshold_pct = 0.10 | |
| def delta_pairs(split: str, model: str, coeff: str): | |
| """True and predicted pairwise deltas, plus the tolerance band of one split/model.""" | |
| df = load_coefficients(split, model) | |
| true = df[coeff].to_numpy(dtype=float) | |
| pred = df[f"{coeff}Pred"].to_numpy(dtype=float) | |
| # element (r, i) of the outer difference is the delta of run i against reference r | |
| delta_true = (true[None, :] - true[:, None]).ravel() | |
| delta_pred = (pred[None, :] - pred[:, None]).ravel() | |
| keep = delta_true > 0 | |
| threshold = delta_threshold_pct * abs(true.mean()) | |
| return delta_true[keep], delta_pred[keep], threshold | |
| def delta_stats(split: str, model: str, coeff: str) -> dict: | |
| """Directional-consistency statistics for one split/model/coefficient.""" | |
| delta_true, delta_pred, threshold = delta_pairs(split, model, coeff) | |
| matches = np.sign(delta_true) == np.sign(delta_pred) | |
| within = np.abs(delta_pred - delta_true) <= threshold | |
| fit = stats.linregress(delta_true, delta_pred) | |
| return { | |
| "split": split, | |
| "model": model_labels[model], | |
| "coefficient": coeff, | |
| "pairs": 2 * len(delta_true), | |
| "directional_accuracy_pct": 100 * matches.mean(), | |
| "within_threshold_pct": 100 * within.mean(), | |
| "slope": fit.slope, | |
| "r2": fit.rvalue**2, | |
| } | |
| def plot_delta(split: str, model: str, coeff: str, output_path: Path) -> Path: | |
| """Predicted vs. true pairwise deltas, coloured by directional agreement.""" | |
| delta_true, delta_pred, threshold = delta_pairs(split, model, coeff) | |
| matches = np.sign(delta_true) == np.sign(delta_pred) | |
| row = delta_stats(split, model, coeff) | |
| span = max(delta_true.max(), delta_pred.max()) * 1.05 | |
| floor = min(delta_pred.min(), 0.0) - 0.05 * span | |
| fig, ax = plt.subplots(figsize=(text_width_in * 0.72, 2.9)) | |
| ax.fill_between([0, span], 0, span, color="tab:green", alpha=0.07, linewidth=0) | |
| ax.fill_between([0, span], floor, 0, color="tab:red", alpha=0.07, linewidth=0) | |
| ax.scatter( | |
| delta_true[matches], delta_pred[matches], s=2, alpha=0.35, | |
| color="tab:green", edgecolors="none", label="correct sign", | |
| ) | |
| if (~matches).any(): | |
| ax.scatter( | |
| delta_true[~matches], delta_pred[~matches], s=4, alpha=0.8, | |
| color="tab:red", edgecolors="none", label="wrong sign", | |
| ) | |
| line = np.array([0.0, span]) | |
| ax.plot(line, line, "k-", linewidth=0.8, label="perfect match") | |
| ax.plot(line, line + threshold, "k--", linewidth=0.6, alpha=0.7, | |
| label=rf"$\pm{delta_threshold_pct * 100:.0f}\%$ tolerance") | |
| ax.plot(line, line - threshold, "k--", linewidth=0.6, alpha=0.7) | |
| ax.axhline(0, color="black", linewidth=0.5, alpha=0.5) | |
| ax.set_xlim(0, span) | |
| ax.set_ylim(floor, span) | |
| ax.set_xlabel(rf"True $\Delta {coeff_labels[coeff].strip('$')}$") | |
| ax.set_ylabel(rf"Predicted $\Delta {coeff_labels[coeff].strip('$')}$") | |
| ax.annotate( | |
| rf"correct sign: {row['directional_accuracy_pct']:.1f}\%" | |
| "\n" | |
| rf"within tolerance: {row['within_threshold_pct']:.1f}\%", | |
| (0.97, 0.06), xycoords="axes fraction", fontsize=7, ha="right", | |
| ) | |
| ax.legend(loc="upper left", frameon=False, markerscale=2.5, handlelength=1.4) | |
| ax.grid(True, alpha=0.25, linewidth=0.4) | |
| fig.tight_layout() | |
| return save(fig, output_path) | |
| # Statistics for every model | |
| delta_figure_models = {"abupt": "abupt", "xaeronet": "xmeshgraphnet"} | |
| delta_summary = pd.DataFrame([ | |
| delta_stats(split, model, coeff) | |
| for split in splits | |
| for model in reported_models() | |
| for coeff in coeffs | |
| ]) | |
| delta_summary.to_csv(output_dir / "directional_accuracy.csv", index=False) | |
| for split in splits: | |
| for model, file_name in delta_figure_models.items(): | |
| plot_delta(split, model, "Cl", output_dir / split / f"delta_cl_{file_name}.svg") | |
| print("\n" + "=" * 96) | |
| print("Directional consistency (all ordered pairs)") | |
| print("=" * 96) | |
| print(delta_summary.to_string(index=False, float_format=lambda v: f"{v:.1f}")) | |
| # --------------------------------------------------------------------------- | |
| # Appendix: AB-UPT trained on the surface fields alone (the benchmarked run, `abupt`) | |
| # against the variant additionally trained on the volumetric targets (`abupt_volume`). | |
| # --------------------------------------------------------------------------- | |
| training_targets = { | |
| "abupt": "Surface only", | |
| "abupt_volume": "Surface + volume", | |
| } | |
| assert "abupt_volume" in appendix_model_labels, "abupt_volume must be an appendix model" | |
| fields_by_variant = field_summary.set_index(["split", "model", "field"]) | |
| rows = [] | |
| for split in splits: | |
| for variant, targets in training_targets.items(): | |
| df = load_coefficients(split, variant) | |
| row = { | |
| "split": split, | |
| "split_label": split_labels[split], | |
| "variant": variant, | |
| "targets": targets, | |
| "samples": len(df), | |
| } | |
| for coeff in coeffs: | |
| err = relative_error(df, coeff) | |
| row |= { | |
| f"{coeff.lower()}_mean_pct": err.mean(), | |
| f"{coeff.lower()}_std_pct": err.std(), | |
| } | |
| for field in field_labels: | |
| stat = fields_by_variant.loc[(split, variant, field)] | |
| if stat["runs"] != len(df): | |
| raise ValueError( | |
| f"{split}/{variant}/{field}: {stat['runs']} field rows for {len(df)} runs" | |
| ) | |
| row[f"{field}_l2_rel_mean"] = stat["l2_rel_mean"] | |
| row[f"{field}_mse_abs_mean"] = stat["mse_abs_mean"] | |
| rows.append(row) | |
| abupt_targets = pd.DataFrame(rows) | |
| abupt_targets.to_csv(output_dir / "abupt_training_targets.csv", index=False) | |
| print(f"\nwrote {(output_dir / 'abupt_training_targets.csv').relative_to(here)}\n") | |
| print( | |
| abupt_targets[[ | |
| "split_label", "targets", "samples", | |
| "cl_mean_pct", "cl_std_pct", "cd_mean_pct", "cd_std_pct", | |
| "Cp_l2_rel_mean", "ws_l2_rel_mean", | |
| ]].to_string(index=False, float_format=lambda v: f"{v:.4f}") | |
| ) | |
| # --------------------------------------------------------------------------- | |
| # Paper-ready LaTeX table rows. The paper reports the stratified split in full and the other | |
| # two side by side. | |
| # --------------------------------------------------------------------------- | |
| paper_split = "stratified" | |
| architectures = { | |
| "abupt": "Transformer", | |
| "geotransolver": "Transformer", | |
| "aerojepa": "JEPA", | |
| "gaot": "Transformer", | |
| "xaeronet": "GNN", | |
| "domino": "CNN", | |
| } | |
| indexed = benchmark_summary.set_index(["split", "model_key"]) | |
| fields_indexed = field_summary.set_index(["split", "model", "field"]) | |
| def rule(title: str) -> None: | |
| print("\n" + "=" * 96) | |
| print(title) | |
| print("=" * 96) | |
| rule(f"tab:results rows -- {paper_split} split") | |
| for model in ranked_models(paper_split): | |
| r = indexed.loc[(paper_split, model)] | |
| print( | |
| f"{model_labels[model]} & {architectures[model]} & " | |
| f"{r['cl_mean_pct']:.2f}, {r['cl_std_pct']:.2f} & " | |
| f"{r['cl_r2_fit']:.3f} & {r['cl_r2_1to1']:.3f} & " | |
| f"{r['cd_mean_pct']:.2f}, {r['cd_std_pct']:.2f} & " | |
| f"{r['cd_r2_fit']:.3f} & {r['cd_r2_1to1']:.3f} \\\\" | |
| ) | |
| rule(f"tab:field_errors rows -- {paper_split} split") | |
| for model in ranked_models(paper_split): | |
| cells = [] | |
| for field in field_labels: | |
| r = fields_indexed.loc[(paper_split, model, field)] | |
| cells += [ | |
| f"{r['mse_abs_mean']:.4f}" if field == "Cp" else f"{r['mse_abs_mean']:.3f}", | |
| f"{100 * r['l1_rel_mean']:.2f}", | |
| f"{100 * r['l2_rel_mean']:.2f}", | |
| ] | |
| print(f"{model_labels[model]} & " + " & ".join(cells) + " \\\\") | |
| rule("tab:results_splits rows -- drag-outlier and interpolated") | |
| for model in ranked_models(paper_split): | |
| cells = [] | |
| for split in ("outliers", "interpolated"): | |
| r = indexed.loc[(split, model)] | |
| cells += [ | |
| f"{r['cl_mean_pct']:.2f}, {r['cl_std_pct']:.2f}", | |
| f"{r['cd_mean_pct']:.2f}, {r['cd_std_pct']:.2f}", | |
| f"{100 * r['Cp_l2_rel_mean']:.2f}", | |
| f"{100 * r['ws_l2_rel_mean']:.2f}", | |
| ] | |
| print(f"{model_labels[model]} & " + " & ".join(cells) + " \\\\") | |
| rule("tab:abupt_targets rows") | |
| for split in splits: | |
| for i, variant in enumerate(training_targets): | |
| r = abupt_targets[ | |
| (abupt_targets["split"] == split) & (abupt_targets["variant"] == variant) | |
| ].iloc[0] | |
| # The split name sits on the first row of each pair; no multirow package needed. | |
| label = split_labels[split] if i == 0 else "" | |
| print( | |
| f"{label} & {r['targets']} & " | |
| f"{r['cl_mean_pct']:.2f}, {r['cl_std_pct']:.2f} & " | |
| f"{r['cd_mean_pct']:.2f}, {r['cd_std_pct']:.2f} & " | |
| f"{100 * r['Cp_l2_rel_mean']:.2f} & {100 * r['ws_l2_rel_mean']:.2f} \\\\" | |
| ) | |
| print(r"\midrule" if split != splits[-1] else r"\bottomrule") | |
| rule(f"Directional consistency quoted in the prose -- {paper_split} split") | |
| print( | |
| delta_summary[delta_summary["split"] == paper_split].to_string( | |
| index=False, float_format=lambda v: f"{v:.1f}" | |
| ) | |
| ) | |