Download scripts/plotting/dataset_description.py from andreacenzato/Ground-Wing: direct link, hf CLI and curl.
- Browser
- Download file 26.1 kB
-
https://huggingface.co/datasets/andreacenzato/Ground-Wing/resolve/main/scripts/plotting/dataset_description.py
- Command line
-
hf download hf://datasets/andreacenzato/Ground-Wing/scripts/plotting/dataset_description.py
-
curl -L -o dataset_description.py https://huggingface.co/datasets/andreacenzato/Ground-Wing/resolve/main/scripts/plotting/dataset_description.py
26.1 kB
| """Dataset description figures. | |
| Generates the descriptive figures of the dataset section and of Appendices C, D and E: | |
| parameter distributions with the sensitivity function, the $C_d$/$C_l$ envelope, the mesh base | |
| size study, the ride height sweep behind the choking assessment, the old-vs-new sensitivity | |
| comparison, and the geometric-parameter interaction heatmap. | |
| Run entries are read from the split files in dataset_composition/: | |
| - split_stratified.yaml: the main benchmark split (690 entries, 174 geometries, | |
| profiles P = 1-12), used for the parameter distributions. | |
| - split_interpolated.yaml: same train/validation, with its test set replaced by the 80 | |
| interpolated-profile entries (20 geometries, profiles P = 13-27). Together with the above | |
| this gives the 770 simulations of the full dataset, used for the $C_d$/$C_l$ envelope. | |
| Geometry parameters and coefficients for each entry come from run_db.csv | |
| Outputs, under outputs/dataset/: | |
| parameter_distributions.svg base_size_cl_conv.svg base_size_cd_conv.svg | |
| cd_cl_scatter_all.svg base_size_cl_err.svg base_size_cd_err.svg | |
| ride_height_sweep.svg interaction_heatmap.svg | |
| new_sensitivity_comparison.svg new_sensitivity_comparison.csv | |
| """ | |
| from __future__ import annotations | |
| from itertools import combinations | |
| from pathlib import Path | |
| import matplotlib as mpl | |
| import matplotlib.pyplot as plt | |
| import numpy as np | |
| import pandas as pd | |
| import yaml | |
| from scipy import interpolate | |
| from scipy.interpolate import interp1d | |
| from scipy.stats import gaussian_kde | |
| from sklearn.linear_model import LinearRegression | |
| from sklearn.preprocessing import PolynomialFeatures | |
| here = Path(__file__).resolve().parent | |
| data_dir = here.parents[1] / "dataset_composition" | |
| output_dir = here / "outputs" / "dataset" | |
| output_dir.mkdir(parents=True, exist_ok=True) | |
| # All text is typeset by LaTeX with the same fonts as the paper, and | |
| # every figure is drawn at the width at which it is included. | |
| text_width_in = 6.5 | |
| mpl.rcParams.update({ | |
| "text.usetex": True, | |
| "text.latex.preamble": r"\usepackage{newtxtext,newtxmath}", | |
| "font.family": "serif", | |
| "font.size": 9, | |
| "axes.labelsize": 9, | |
| "axes.titlesize": 9, | |
| "legend.fontsize": 8, | |
| "xtick.labelsize": 8, | |
| "ytick.labelsize": 8, | |
| }) | |
| color_dist = "tab:blue" # sample distribution: bars and KDE fills | |
| color_sens = "tab:red" # sensitivity function | |
| color_sens_new = "tab:green" # sensitivity function of the profile-12 sweep | |
| param_cols = ["P", "CA", "OA", "CS", "OS", "AF"] | |
| param_labels = { | |
| "P": "Profile, $P$", | |
| "CA": r"Centerline AoA, $\alpha_c$ [°]", | |
| "OA": r"Tip Twist, $\theta_t$ [°]", | |
| "CS": "Centerline Chord, $c_c$ [mm]", | |
| "OS": "Tip Chord, $c_t$ [mm]", | |
| "AF": r"Sweep Angle, $\Lambda$ [°]", | |
| } | |
| param_symbols = { | |
| "P": "$P$", "CA": r"$\alpha_c$", "OA": r"$\theta_t$", | |
| "CS": "$c_c$", "OS": "$c_t$", "AF": r"$\Lambda$", | |
| } | |
| param_bounds = { | |
| "CA": (-10.0, 5.0), | |
| "OA": (-10.0, 10.0), | |
| "CS": (550.0, 700.0), | |
| "OS": (350.0, 700.0), | |
| "AF": (-8.5, 20.0), | |
| } | |
| sens_params = ["CA", "OA", "CS", "OS", "AF"] | |
| split_file = data_dir / "split_stratified.yaml" | |
| interpolated_split_file = data_dir / "split_interpolated.yaml" | |
| run_db_file = data_dir / "run_db.csv" | |
| split_order = ["train", "validation", "test"] | |
| # --------------------------------------------------------------------------- | |
| # Dataset entries: split files joined against the run database | |
| # --------------------------------------------------------------------------- | |
| def read_split(path: Path) -> dict[str, list[str]]: | |
| """Subset name -> run IDs, from one split file, in split_order.""" | |
| with path.open() as fh: | |
| sections = yaml.safe_load(fh) | |
| return {name: [str(run) for run in sections[name]] for name in split_order} | |
| def load_run_db(path: Path) -> pd.DataFrame: | |
| """The run database, with Cd/Cl derived from the integral force coefficients.""" | |
| db = pd.read_csv(path, sep=";", dtype={"Run #": str}) | |
| db["Cd"] = db["SCx"] | |
| db["Cl"] = -db["SCz"] | |
| return db | |
| db = load_run_db(run_db_file) | |
| splits = read_split(split_file) | |
| primary_ids = {entry for ids in splits.values() for entry in ids} | |
| interpolated_ids = sorted( | |
| {entry for ids in read_split(interpolated_split_file).values() for entry in ids} | |
| - primary_ids | |
| ) | |
| entries = [(entry, name, "primary") for name, ids in splits.items() for entry in ids] | |
| entries += [(entry, "test", "interpolated") for entry in interpolated_ids] | |
| lookup = { | |
| (row["Run #"], int(row["FRH"]), int(row["RRH"])): row | |
| for _, row in db.iterrows() | |
| } | |
| records, unmatched = [], [] | |
| for entry, split_name, sampling in entries: | |
| run_no, rh = entry.split("_") | |
| frh, rrh = int(rh[:2]), int(rh[2:]) | |
| info = lookup.get((run_no, frh, rrh)) | |
| if info is None: | |
| unmatched.append(entry) | |
| continue | |
| rec = {col: float(info[col]) for col in param_cols} | |
| rec.update(run_id=entry, split=split_name, sampling=sampling, frh=frh, rrh=rrh, | |
| Cd=info["Cd"], Cl=info["Cl"]) | |
| records.append(rec) | |
| df = pd.DataFrame(records) | |
| df_primary = df[df["sampling"] == "primary"] | |
| print(f"Matched {len(df)} / {len(entries)} run entries ({len(unmatched)} unmatched)") | |
| print(f" primary sampling: {len(df_primary)} entries, " | |
| f"{df_primary['run_id'].str.split('_').str[0].nunique()} geometries, " | |
| f"profiles {int(df_primary['P'].min())}-{int(df_primary['P'].max())}") | |
| print(f" interpolated: {(df['sampling'] == 'interpolated').sum()} entries, " | |
| f"profiles {int(df[df['sampling'] == 'interpolated']['P'].min())}-" | |
| f"{int(df[df['sampling'] == 'interpolated']['P'].max())}") | |
| # --------------------------------------------------------------------------- | |
| # Sensitivity function S(p) = |dCl/dp| + |dCd/dp| | |
| # --------------------------------------------------------------------------- | |
| # CFD sweeps around the baseline geometry CA0 OA0 CS600 OS455 AF10, as | |
| # (parameter values, Cl, Cd). Taken from the `Sensitivity Analysis - <parameter>` rows of | |
| # run_db.csv (SCzav and SCxav): CA runs 0090-0098, OA runs 0099-0106 and 0129-0131, CS runs | |
| # 0107-0112, OS runs 0113-0119, AF runs 0120-0127, with run 0128 the CA = 0 baseline shared by | |
| # the CS and OS sweeps. The sweep was run on the proprietary profile 0, whose geometry is | |
| # not distributed with the dataset, so the values are reproduced here directly. | |
| _sens_data = { | |
| "CA": ( | |
| np.array([-10, -8, -6, -4, -2, 0, 2, 4, 5]), | |
| np.array([2.71597, 2.59168, 2.38756, 2.11036, 1.79931, 1.46873, 1.13276, 0.79852, 0.63399]), | |
| np.array([0.19559, 0.16673, 0.13793, 0.11181, 0.08745, 0.06607, 0.04852, 0.03574, 0.03121]), | |
| ), | |
| "OA": ( | |
| np.array([-10, -8, -6, -4, -2, 0, 2, 4, 6, 8, 10]), | |
| np.array([2.11753, 2.00106, 1.87441, 1.74326, 1.60771, 1.46873, 1.32822, 1.18505, 1.03937, 0.88601, 0.72393]), | |
| np.array([0.12137, 0.10840, 0.09681, 0.08580, 0.07550, 0.06607, 0.05760, 0.05028, 0.04426, 0.04071, 0.04110]), | |
| ), | |
| "CS": ( | |
| np.array([550, 575, 600, 625, 650, 675, 700]), | |
| np.array([1.39120, 1.43109, 1.46873, 1.50281, 1.53579, 1.56641, 1.59557]), | |
| np.array([0.06179, 0.06395, 0.06607, 0.06806, 0.07008, 0.07200, 0.07392]), | |
| ), | |
| "OS": ( | |
| np.array([350, 400, 455, 500, 550, 600, 650, 700]), | |
| np.array([1.29316, 1.37725, 1.46873, 1.53883, 1.60908, 1.67319, 1.72398, 1.76696]), | |
| np.array([0.05588, 0.06063, 0.06607, 0.07047, 0.07517, 0.07981, 0.08379, 0.08746]), | |
| ), | |
| "AF": ( | |
| np.array([-8.5, -4, 0, 4, 8, 12, 16, 20]), | |
| np.array([1.31019, 1.35985, 1.39354, 1.42229, 1.45279, 1.48344, 1.50923, 1.53197]), | |
| np.array([0.05940, 0.06138, 0.06270, 0.06387, 0.06528, 0.06673, 0.06792, 0.06904]), | |
| ), | |
| } | |
| def _make_sensitivity_func(param_values, lift, drag): | |
| lift_deriv = interpolate.make_interp_spline(param_values, lift, k=3).derivative() | |
| drag_deriv = interpolate.make_interp_spline(param_values, drag, k=3).derivative() | |
| return lambda p: np.abs(lift_deriv(p)) + np.abs(drag_deriv(p)) | |
| sens_funcs = {param: _make_sensitivity_func(*data) for param, data in _sens_data.items()} | |
| for param, (values, _, _) in _sens_data.items(): | |
| print(f"{param}: {len(values)} sweep points, range [{values.min()}, {values.max()}]") | |
| # --------------------------------------------------------------------------- | |
| # Parameter distributions with S(p) overlaid | |
| # --------------------------------------------------------------------------- | |
| fig, axes = plt.subplots(2, 3, figsize=(text_width_in, 4.4)) | |
| legend_handles, legend_labels = [], [] | |
| for ax, col in zip(axes.flat, param_cols): | |
| if col == "P": | |
| counts = df_primary[col].astype(int).value_counts().sort_index() | |
| ax.bar(counts.index, counts.values, color=color_dist, alpha=0.6, | |
| edgecolor=color_dist, linewidth=1.5) | |
| ax.set_xticks(counts.index) | |
| ax.tick_params(axis="x", labelsize=6) | |
| ax.set_ylabel("Count", color=color_dist) | |
| ax.tick_params(axis="y", labelcolor=color_dist) | |
| else: | |
| lo, hi = param_bounds[col] | |
| x_vals = np.linspace(lo, hi, 200) | |
| density_vals = gaussian_kde(df_primary[col])(x_vals) | |
| ax.fill_between(x_vals, density_vals, alpha=0.6, color=color_dist, | |
| label="Sample distribution") | |
| ax.plot(x_vals, density_vals, color=color_dist, linewidth=1.5) | |
| ax.set_ylabel("Density", color=color_dist) | |
| ax.tick_params(axis="y", labelcolor=color_dist) | |
| ax.set_xlim(lo, hi) | |
| # S(p) normalized to its maximum over this parameter's range, so the shape is | |
| # comparable across subplots despite the differing units of p. | |
| sens_vals = sens_funcs[col](x_vals) | |
| ax2 = ax.twinx() | |
| ax2.plot(x_vals, 100.0 * sens_vals / sens_vals.max(), color=color_sens, linewidth=1.5, | |
| label="$S(p)$") | |
| ax2.set_ylim(0, 105) | |
| ax2.set_ylabel(r"$S(p)$ [\% of max]", color=color_sens) | |
| ax2.tick_params(axis="y", labelcolor=color_sens) | |
| if not legend_handles: | |
| l1, lb1 = ax.get_legend_handles_labels() | |
| l2, lb2 = ax2.get_legend_handles_labels() | |
| legend_handles, legend_labels = l1 + l2, lb1 + lb2 | |
| ax.set_xlabel(param_labels[col]) | |
| ax.grid(True, alpha=0.3) | |
| fig.legend(legend_handles, legend_labels, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 1.04), | |
| frameon=False) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / "parameter_distributions.svg", bbox_inches="tight") | |
| plt.close(fig) | |
| # --------------------------------------------------------------------------- | |
| # Aerodynamic envelope: Cd vs Cl over every simulated sample | |
| # --------------------------------------------------------------------------- | |
| geom_ids = df["run_id"].str.split("_").str[0] | |
| unique_geoms = geom_ids.unique() | |
| prop_colors = plt.rcParams["axes.prop_cycle"].by_key()["color"] | |
| rng = np.random.default_rng(42) | |
| colors = rng.choice(prop_colors, size=len(unique_geoms)) | |
| geom_to_color = dict(zip(unique_geoms, colors)) | |
| point_colors = geom_ids.map(geom_to_color).tolist() | |
| fig, ax = plt.subplots(figsize=(0.75 * text_width_in, 3.4)) | |
| ax.scatter(df["Cd"], df["Cl"], s=12, alpha=0.75, c=point_colors, edgecolor="none") | |
| ax.set_xlabel("$C_d$") | |
| ax.set_ylabel("$C_l$") | |
| ax.grid(True, alpha=0.3) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / "cd_cl_scatter_all.svg", bbox_inches="tight") | |
| plt.close(fig) | |
| # --------------------------------------------------------------------------- | |
| # Ride height sweep (Appendix E) | |
| # --------------------------------------------------------------------------- | |
| # Flat ride height sweep of a development geometry, used to verify that the four dataset ride | |
| # heights lie outside the nonlinear "choking" regime. Source: run_db.csv, the | |
| # `Flat setup sweep` rows (run 0076), flat setups only. | |
| profile_offset_mm = 57.0 # lowest point of the profile above the lower edge of the endplate | |
| sweep_chord_mm = 600.0 # centerline chord of the development geometry | |
| dataset_rh = [30, 45, 60, 75] # the four ride heights of the dataset | |
| sweep = db[(db["Description"] == "Flat setup sweep") & (db["FRH"] == db["RRH"])] | |
| sweep = sweep.sort_values("FRH")[["FRH", "Cd", "Cl"]].reset_index(drop=True) | |
| sweep = sweep.rename(columns={"FRH": "RH"}) | |
| on_grid = sweep["RH"].isin(dataset_rh) | |
| fig, axes = plt.subplots(1, 2, figsize=(text_width_in, 2.9)) | |
| for ax, col, label in zip(axes, ["Cl", "Cd"], ["$C_l$", "$C_d$"]): | |
| ax.axvspan(min(dataset_rh), max(dataset_rh), color=color_dist, alpha=0.10, | |
| label="Dataset Range") | |
| ax.plot(sweep["RH"], sweep[col], "-o", color=color_dist, markersize=4, linewidth=1, | |
| markerfacecolor="white", label="Sweep") | |
| ax.plot(sweep.loc[on_grid, "RH"], sweep.loc[on_grid, col], "o", color=color_dist, | |
| markersize=4, linestyle="none", label="Dataset Ride Heights") | |
| ax.set_xlabel("Ride Height [mm]") | |
| ax.set_ylabel(label) | |
| ax.grid(True, alpha=0.3) | |
| # Secondary axis: clearance of the lowest point of the profile from the ground, over the | |
| # centerline chord, i.e. the h/c used in the ground-effect literature. A different datum | |
| # from the ride height on the primary axis, which is taken at the endplate. | |
| sec = ax.secondary_xaxis( | |
| "top", | |
| functions=(lambda h: (h + profile_offset_mm) / sweep_chord_mm, | |
| lambda r: r * sweep_chord_mm - profile_offset_mm), | |
| ) | |
| sec.set_xlabel("Profile Ground Clearance, $h/c_c$") | |
| sec.set_xticks([0.15, 0.20, 0.25]) | |
| handles, labels_list = axes[0].get_legend_handles_labels() | |
| fig.legend(handles, labels_list, loc="upper center", ncol=3, bbox_to_anchor=(0.5, 1.1), | |
| frameon=True) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / "ride_height_sweep.svg", bbox_inches="tight") | |
| plt.close(fig) | |
| lo, hi = sweep.iloc[0], sweep.iloc[-1] # lowest and highest ride height | |
| print(f"\n{len(sweep)} flat ride heights: {list(sweep['RH'])}") | |
| print(f" |Cl| {abs(hi['Cl']):.4f} -> {abs(lo['Cl']):.4f} " | |
| f"({abs(lo['Cl']) / abs(hi['Cl']) - 1:+.1%})") | |
| print(f" Cd {hi['Cd']:.4f} -> {lo['Cd']:.4f} ({lo['Cd'] / hi['Cd'] - 1:+.1%})") | |
| print(f" |Cl|/Cd {abs(hi['Cl']) / hi['Cd']:.1f} -> {abs(lo['Cl']) / lo['Cd']:.1f}") | |
| print(f" h/c_c {(lo['RH'] + profile_offset_mm) / sweep_chord_mm:.3f} -> " | |
| f"{(hi['RH'] + profile_offset_mm) / sweep_chord_mm:.3f}") | |
| # --------------------------------------------------------------------------- | |
| # Mesh base size study | |
| # --------------------------------------------------------------------------- | |
| # Coefficient sensitivity to mesh refinement, relative to the 28M-cell configuration used for | |
| # the dataset. Coefficients are the SCxav/SCzav of the `Mesh convergence - <base size>` rows of | |
| # run_db.csv -- runs 0071, 0072, 0069, 0073, 0074 in the array order below. | |
| base_sizes_mm = np.array([1125, 1000, 875, 750, 625]) | |
| n_cells = np.array([9978496, 16452008, 28456075, 44988206, 77560011]) | |
| n_cells_m = n_cells / 1e6 | |
| scx_avg = np.array([0.07826645, 0.07791031, 0.07736745, 0.07753006, 0.07671507]) # Cd | |
| scz_avg = np.array([1.647213, 1.639564, 1.645484, 1.653249, 1.629673]) # Cl | |
| baseline_idx = 2 # the 28M-cell configuration (875 mm base size) | |
| scx_error = (scx_avg - scx_avg[baseline_idx]) / scx_avg[baseline_idx] * 100 | |
| scz_error = (scz_avg - scz_avg[baseline_idx]) / scz_avg[baseline_idx] * 100 | |
| cell_to_base = interp1d(n_cells_m, base_sizes_mm, fill_value="extrapolate") | |
| base_to_cell = interp1d(base_sizes_mm, n_cells_m, fill_value="extrapolate") | |
| color_blue_line = "#1f77b4" | |
| color_blue_marker = "#08519c" | |
| color_red_line = "#d62728" | |
| color_red_marker = "#a50f15" | |
| plot_specs = [ | |
| ("base_size_cl_conv.svg", scz_avg, False, r"$C_l$", (1.62, 1.66)), | |
| ("base_size_cl_err.svg", scz_error, True, r"$\Delta C_l \: [\%]$", (-1.5, 1.5)), | |
| ("base_size_cd_conv.svg", scx_avg, False, r"$C_d$", (0.075, 0.080)), | |
| ("base_size_cd_err.svg", scx_error, True, r"$\Delta C_d \: [\%]$", (-1.5, 1.5)), | |
| ] | |
| for filename, y_vals, is_error, y_label, y_lims in plot_specs: | |
| fig, ax = plt.subplots(figsize=(0.48 * text_width_in, 2.5)) | |
| if is_error: | |
| line_col, marker_col = color_red_line, color_red_marker | |
| ax.axhspan(-1, 1, color=color_red_line, alpha=0.10) | |
| else: | |
| line_col, marker_col = color_blue_line, color_blue_marker | |
| ax.plot(n_cells_m, y_vals, "-o", color=line_col, markersize=4, linewidth=1, | |
| markerfacecolor="white", markeredgecolor=marker_col, markeredgewidth=1) | |
| ax.plot(n_cells_m[baseline_idx], y_vals[baseline_idx], "o", color=marker_col, | |
| markersize=5, linestyle="none") | |
| ax.set_xlabel(r"Number of Cells [$\times 10^6$]") | |
| ax.set_ylabel(y_label) | |
| ax.set_ylim(*y_lims) | |
| ax.grid(True, alpha=0.3) | |
| sec = ax.secondary_xaxis("top", functions=(cell_to_base, base_to_cell)) | |
| sec.set_xlabel("Mesh Base Size [mm]") | |
| sec.set_xticks([625, 875, 1125]) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / filename, bbox_inches="tight") | |
| plt.close(fig) | |
| print("\nMesh independence relative to the 28M-cell configuration (875 mm base size):") | |
| print(f" 77.6M cells (625 mm): Cl error = {scz_error[-1]:+.2f}%, " | |
| f"Cd error = {scx_error[-1]:+.2f}%") | |
| # --------------------------------------------------------------------------- | |
| # Appendix C: profile-12 sensitivity sweep against the original profile-0 sweep | |
| # --------------------------------------------------------------------------- | |
| # The sensitivity functions above were built on profile 0, a proprietary internal design that | |
| # is not part of the distributed dataset. This section validates them against an equivalent | |
| # sweep on profile 12 (s1223), at the identical baseline and ride height: the `New Sensitivity` | |
| # rows of run_db.csv. Run 0398 is the baseline and run 0399 is the AF = 0 point of that sweep. | |
| new_sweep = db[db["Description"] == "New Sensitivity"].copy() | |
| new_sweep = new_sweep.sort_values("Run #").reset_index(drop=True) | |
| baseline_vals = {"CA": 0.0, "OA": 0.0, "CS": 600.0, "OS": 455.0, "AF": 10.0} | |
| is_baseline = np.all([new_sweep[p] == v for p, v in baseline_vals.items()], axis=0) | |
| assert is_baseline.sum() == 1, f"expected exactly one baseline run, found {is_baseline.sum()}" | |
| baseline_row = new_sweep[is_baseline].iloc[0] | |
| print(f"\nNew sweep: {len(new_sweep)} runs, profile P={int(baseline_row['P'])}, " | |
| f"ride height {int(baseline_row['FRH'])}/{int(baseline_row['RRH'])} mm") | |
| print(f" baseline Cd={baseline_row['Cd']:.5f}, Cl={baseline_row['Cl']:.5f} " | |
| f"(run {baseline_row['Run #']})") | |
| for param in sens_params: | |
| other = [p for p in sens_params if p != param] | |
| mask = np.all([new_sweep[p] == baseline_vals[p] for p in other], axis=0) | |
| swept = new_sweep[mask] | |
| print(f" {param}: {mask.sum()} points (incl. baseline), " | |
| f"range [{swept[param].min()}, {swept[param].max()}]") | |
| def finite_diff_derivative(x, y): | |
| """Non-uniform-grid, 2nd-order accurate 3-point derivative estimate at every point. | |
| Interior points use the symmetric 3-point (Lagrange) formula, which reduces to | |
| (f(x+h)-f(x-h))/(2h) on a uniform grid; the two endpoints use the matching one-sided | |
| 3-point formula, also 2nd-order accurate. | |
| """ | |
| n = len(x) | |
| d = np.empty(n) | |
| for i in range(1, n - 1): | |
| h1, h2 = x[i] - x[i - 1], x[i + 1] - x[i] | |
| d[i] = (-h2 / (h1 * (h1 + h2))) * y[i - 1] + ((h2 - h1) / (h1 * h2)) * y[i] \ | |
| + (h1 / (h2 * (h1 + h2))) * y[i + 1] | |
| h1, h2 = x[1] - x[0], x[2] - x[1] | |
| d[0] = (-(2 * h1 + h2) / (h1 * (h1 + h2))) * y[0] + ((h1 + h2) / (h1 * h2)) * y[1] \ | |
| - (h1 / (h2 * (h1 + h2))) * y[2] | |
| h1, h2 = x[-2] - x[-3], x[-1] - x[-2] | |
| d[-1] = (h2 / (h1 * (h1 + h2))) * y[-3] - ((h1 + h2) / (h1 * h2)) * y[-2] \ | |
| + ((h1 + 2 * h2) / (h2 * (h1 + h2))) * y[-1] | |
| return d | |
| # Exact for a quadratic on a non-uniform grid. | |
| _check_x = np.array([0.0, 1.0, 3.0, 4.0, 8.0]) | |
| _check_err = np.abs(finite_diff_derivative(_check_x, _check_x**2) - 2 * _check_x).max() | |
| assert _check_err < 1e-12, f"finite_diff_derivative failed the quadratic sanity check ({_check_err})" | |
| print(f"Sanity check passed: max error {_check_err:.2e} on f(x)=x^2") | |
| def central_diff_sens(data): | |
| values, lift, drag = data | |
| return values, (np.abs(finite_diff_derivative(values, lift)) | |
| + np.abs(finite_diff_derivative(values, drag))) | |
| # The new sweep's per-parameter (values, lift, drag) tuples, same structure as _sens_data. | |
| _new_sens_data = {} | |
| for param in sens_params: | |
| other = [p for p in sens_params if p != param] | |
| mask = np.all([new_sweep[p] == baseline_vals[p] for p in other], axis=0) | |
| subset = new_sweep[mask].sort_values(param) | |
| _new_sens_data[param] = ( | |
| subset[param].to_numpy(), subset["Cl"].to_numpy(), subset["Cd"].to_numpy() | |
| ) | |
| cd_old = {param: central_diff_sens(data) for param, data in _sens_data.items()} | |
| cd_new = {param: central_diff_sens(data) for param, data in _new_sens_data.items()} | |
| # Overlay of the old (profile 0) and new (profile 12) sensitivity functions over each | |
| # parameter's full bound. Both curves share the same units, so no normalization is needed. | |
| fig, axes = plt.subplots(2, 3, figsize=(text_width_in, 4.4)) | |
| for ax, col in zip(axes.flat, sens_params): | |
| lo_b, hi_b = param_bounds[col] | |
| xo, so = cd_old[col] | |
| xn, sn = cd_new[col] | |
| ax.plot(xo, so, "o-", color=color_sens, markersize=4, markerfacecolor="white", | |
| label="$S(p)$, old (profile 0)") | |
| ax.plot(xn, sn, "s--", color=color_sens_new, markersize=4, markerfacecolor="white", | |
| label="$S(p)$, new (profile 12)") | |
| ax.set_xlabel(param_labels[col]) | |
| ax.set_ylabel("$S(p)$") | |
| ax.set_xlim(lo_b, hi_b) | |
| ax.grid(True, alpha=0.3) | |
| axes.flat[-1].axis("off") | |
| handles, labels_list = axes.flat[0].get_legend_handles_labels() | |
| fig.legend(handles, labels_list, loc="upper center", ncol=2, bbox_to_anchor=(0.5, 1.04), | |
| frameon=False) | |
| fig.tight_layout() | |
| fig.savefig(output_dir / "new_sensitivity_comparison.svg", bbox_inches="tight") | |
| plt.close(fig) | |
| # Each central-difference point set is reconstructed as a piecewise-linear function and | |
| # evaluated on a shared fine grid per parameter, then compared by correlation, relative L2 | |
| # difference, and the resulting importance ranking of the five parameters. | |
| rows = [] | |
| for param in sens_params: | |
| lo_b, hi_b = param_bounds[param] | |
| x_vals = np.linspace(lo_b, hi_b, 500) | |
| s_old = np.interp(x_vals, *cd_old[param]) | |
| s_new = np.interp(x_vals, *cd_new[param]) | |
| rows.append({ | |
| "param": param, | |
| "mean_old": s_old.mean(), "mean_new": s_new.mean(), | |
| "max_old": s_old.max(), "max_new": s_new.max(), | |
| "correlation": np.corrcoef(s_old, s_new)[0, 1], | |
| "rel_l2_diff": np.linalg.norm(s_new - s_old) / np.linalg.norm(s_old), | |
| }) | |
| comparison = pd.DataFrame(rows).set_index("param") | |
| comparison["mean_ratio_new_over_old"] = comparison["mean_new"] / comparison["mean_old"] | |
| comparison["rank_old"] = comparison["mean_old"].rank(ascending=False).astype(int) | |
| comparison["rank_new"] = comparison["mean_new"].rank(ascending=False).astype(int) | |
| comparison.to_csv(output_dir / "new_sensitivity_comparison.csv") | |
| print() | |
| print(comparison.round(4).to_string()) | |
| print() | |
| print("Importance ranking (1 = most sensitive, by mean S(p) over the parameter's bounds):") | |
| print(f" old (profile 0): {list(comparison.sort_values('rank_old').index)}") | |
| print(f" new (profile 12): {list(comparison.sort_values('rank_new').index)}") | |
| # --------------------------------------------------------------------------- | |
| # Appendix D: geometric parameter interaction | |
| # --------------------------------------------------------------------------- | |
| # Checks the independence assumption behind the sensitivity-weighted sampling (each parameter | |
| # varied one at a time) by fitting a standardized polynomial regression with pairwise | |
| # interaction terms to the full primary-sampled geometry set at the flat 45 mm/45 mm ride | |
| # height. | |
| df_interaction = df_primary[(df_primary["frh"] == 45) & (df_primary["rrh"] == 45)] | |
| print(f"\nInteraction analysis subset: {len(df_interaction)} geometries at 45 mm/45 mm") | |
| X_raw = df_interaction[param_cols].to_numpy(dtype=float) | |
| X_std = (X_raw - X_raw.mean(axis=0)) / X_raw.std(axis=0) | |
| poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False) | |
| X_poly = poly.fit_transform(X_std) | |
| pair_indices = list(combinations(range(len(param_cols)), 2)) | |
| interaction_matrices = {} | |
| for target in ["Cl", "Cd"]: | |
| reg = LinearRegression().fit(X_poly, df_interaction[target].to_numpy(dtype=float)) | |
| pair_coefs = reg.coef_[len(param_cols):] | |
| mat = np.full((len(param_cols), len(param_cols)), np.nan) | |
| for (i, j), beta in zip(pair_indices, pair_coefs): | |
| mat[i, j] = mat[j, i] = abs(beta) | |
| interaction_matrices[target] = mat | |
| param_ticks = [param_symbols[c] for c in param_cols] | |
| fig, axes = plt.subplots(1, 2, figsize=(text_width_in, 3.6)) | |
| for ax, target, title in zip(axes, ["Cl", "Cd"], ["$C_l$", "$C_d$"]): | |
| mat = interaction_matrices[target] | |
| im = ax.imshow(mat, cmap="viridis") | |
| ax.set_xticks(range(len(param_cols))) | |
| ax.set_xticklabels(param_ticks, rotation=45, ha="right") | |
| ax.set_yticks(range(len(param_cols))) | |
| ax.set_yticklabels(param_ticks) | |
| ax.set_title(title) | |
| vmax = np.nanmax(mat) | |
| for i in range(len(param_cols)): | |
| for j in range(len(param_cols)): | |
| if not np.isnan(mat[i, j]): | |
| ax.text(j, i, f"{mat[i, j]:.3f}", ha="center", va="center", fontsize=6, | |
| color="white" if mat[i, j] < vmax / 2 else "black") | |
| fig.colorbar(im, ax=ax, fraction=0.046, pad=0.04, label=r"$|\beta_{ij}|$") | |
| fig.tight_layout() | |
| fig.savefig(output_dir / "interaction_heatmap.svg", bbox_inches="tight") | |
| plt.close(fig) | |
| for target in ["Cl", "Cd"]: | |
| mat = interaction_matrices[target] | |
| pairs_sorted = sorted( | |
| ((mat[i, j], param_cols[i], param_cols[j]) for i, j in pair_indices), | |
| reverse=True, | |
| ) | |
| print(f"{target}: ranked interactions (top 5 of 15):") | |
| for val, pi, pj in pairs_sorted[:5]: | |
| print(f" {pi}-{pj}: {val:.4f}") | |
| print(f"\nwrote {len(list(output_dir.iterdir()))} files to {output_dir}") | |