Repository navigation
Expand file tree
/
Copy pathpublication_compare_plot.py
More file actions
412 lines (369 loc) · 12.5 KB
/
Copy pathpublication_compare_plot.py
File metadata and controls
412 lines (369 loc) · 12.5 KB
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
#!/usr/bin/env python3
"""Create publication-style comparison plots against UIUC and Mejzlik references."""
from __future__ import annotations
import argparse
from pathlib import Path
from typing import Iterable
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
from all_plot import (
DEFAULT_AIR_DENSITY,
DEFAULT_FORCE_AXIS,
DEFAULT_MIN_SYSTEM_EFF_RPM,
DEFAULT_PROP_DIAMETER_IN,
DEFAULT_RPM_OUTLIER_Z,
DEFAULT_SUPPLY_V,
DEFAULT_TORQUE_AXIS,
G,
MEJZLIK_POINTS,
REFERENCE_PROPELLER_DATA,
_interval_means,
load_folder_data,
)
def _configure_style() -> None:
mpl.rcParams.update(
{
"font.family": "serif",
"font.serif": ["DejaVu Serif", "Times New Roman", "Times"],
"mathtext.fontset": "dejavuserif",
"axes.labelsize": 10,
"axes.titlesize": 11,
"axes.titleweight": "bold",
"axes.linewidth": 0.9,
"axes.facecolor": "#d9d9d9",
"axes.edgecolor": "#505050",
"grid.color": "#9a9a9a",
"grid.linewidth": 0.5,
"xtick.labelsize": 9,
"ytick.labelsize": 9,
"xtick.top": True,
"ytick.right": True,
"xtick.direction": "in",
"ytick.direction": "in",
"legend.fontsize": 8,
"savefig.facecolor": "#d9d9d9",
"figure.facecolor": "#d9d9d9",
}
)
def _finite_xy(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
mask = np.isfinite(x) & np.isfinite(y)
return x[mask], y[mask]
def _sorted_pair(x: np.ndarray, y: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
if x.size == 0:
return x, y
order = np.argsort(x)
return x[order], y[order]
def _mae_on_overlap(x_user: np.ndarray, y_user: np.ndarray, x_ref: np.ndarray, y_ref: np.ndarray) -> float:
xu, yu = _finite_xy(x_user, y_user)
xr, yr = _finite_xy(x_ref, y_ref)
if xu.size < 2 or xr.size < 2:
return float("nan")
xu, yu = _sorted_pair(xu, yu)
xr, yr = _sorted_pair(xr, yr)
lo = max(float(np.min(xu)), float(np.min(xr)))
hi = min(float(np.max(xu)), float(np.max(xr)))
if lo >= hi:
return float("nan")
mask = (xu >= lo) & (xu <= hi)
if np.count_nonzero(mask) < 2:
return float("nan")
ref_interp = np.interp(xu[mask], xr, yr)
return float(np.mean(np.abs(yu[mask] - ref_interp)))
def _panel_label(ax: plt.Axes, text: str) -> None:
ax.text(
-0.14,
1.05,
text,
transform=ax.transAxes,
fontsize=12,
fontweight="bold",
va="top",
)
def _plot_metric_vs_mejzlik(
ax: plt.Axes,
rpm_user: np.ndarray,
metric_user: np.ndarray,
rpm_ref: np.ndarray,
metric_ref: np.ndarray,
ylabel: str,
title: str,
color_user: str,
color_ref: str,
) -> float:
xu, yu = _finite_xy(rpm_user, metric_user)
xr, yr = _sorted_pair(*_finite_xy(rpm_ref, metric_ref))
if xu.size:
ax.scatter(
xu,
yu,
s=10,
alpha=0.25,
color=color_user,
edgecolors="none",
label="Measured samples",
zorder=2,
)
centers, means = _interval_means(xu, yu)
if centers.size:
centers, means = _sorted_pair(centers, means)
ax.plot(
centers,
means,
color=color_user,
linewidth=1.4,
marker="s",
markersize=4.2,
markerfacecolor="none",
markeredgewidth=0.8,
label="Measured interval mean",
zorder=3,
)
mae = _mae_on_overlap(centers, means, xr, yr)
else:
mae = _mae_on_overlap(xu, yu, xr, yr)
else:
mae = float("nan")
if xr.size:
ax.plot(
xr,
yr,
color=color_ref,
linewidth=1.4,
marker="v",
markersize=4.2,
markerfacecolor="none",
markeredgewidth=0.8,
label="Mejzlik reference",
zorder=4,
)
ax.set_title(title)
ax.set_ylabel(ylabel)
ax.grid(True, linestyle="-", alpha=0.35)
ax.tick_params(direction="in", length=3.5, width=0.8)
return mae
def _plot_coeff_vs_uiuc(
ax: plt.Axes,
rpm_user: np.ndarray,
coeff_user: np.ndarray,
rpm_uiuc: np.ndarray,
coeff_uiuc: np.ndarray,
ylabel: str,
title: str,
color_user: str,
color_uiuc: str,
) -> float:
xu, yu = _finite_xy(rpm_user, coeff_user)
xr, yr = _sorted_pair(*_finite_xy(rpm_uiuc, coeff_uiuc))
if xu.size:
ax.scatter(
xu,
yu,
s=10,
alpha=0.24,
color=color_user,
edgecolors="none",
label="Measured samples",
)
centers, means = _interval_means(xu, yu)
if centers.size:
centers, means = _sorted_pair(centers, means)
ax.plot(
centers,
means,
color=color_user,
linewidth=1.4,
marker="s",
markersize=4.2,
markerfacecolor="none",
markeredgewidth=0.8,
label="Measured interval mean",
)
mae = _mae_on_overlap(centers, means, xr, yr)
else:
mae = _mae_on_overlap(xu, yu, xr, yr)
else:
mae = float("nan")
if xr.size:
ax.plot(
xr,
yr,
color=color_uiuc,
linewidth=1.4,
marker="v",
markersize=4.2,
markerfacecolor="none",
markeredgewidth=0.8,
label="UIUC reference",
)
ax.set_title(title)
ax.set_ylabel(ylabel)
ax.grid(True, linestyle="-", alpha=0.35)
ax.tick_params(direction="in", length=3.5, width=0.8)
return mae
def _get_uiuc_reference() -> tuple[np.ndarray, np.ndarray, np.ndarray]:
for name, rows in REFERENCE_PROPELLER_DATA:
if "UIUC" in name.upper():
rpm = np.asarray([r[0] for r in rows], dtype=float)
ct = np.asarray([r[1] for r in rows], dtype=float)
cp = np.asarray([r[2] for r in rows], dtype=float)
return rpm, ct, cp
raise ValueError("UIUC reference data not found in REFERENCE_PROPELLER_DATA.")
def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Generate publication-style comparison figure.")
parser.add_argument(
"source",
type=Path,
nargs="?",
default=Path("data_20260202_121539.csv"),
help="CSV file (or folder) to analyze.",
)
parser.add_argument(
"--out",
type=Path,
default=Path("publication_comparison_121539_uiuc_mejzlik.png"),
help="Output figure path (PNG/PDF/SVG).",
)
parser.add_argument("--dpi", type=int, default=600, help="Output DPI (default: 600).")
parser.add_argument("--title", default="Propulsion Performance vs UIUC and Mejzlik References")
parser.add_argument("--force-axis", default=DEFAULT_FORCE_AXIS)
parser.add_argument("--torque-axis", default=DEFAULT_TORQUE_AXIS)
parser.add_argument("--supply-voltage", type=float, default=DEFAULT_SUPPLY_V)
parser.add_argument("--air-density", type=float, default=DEFAULT_AIR_DENSITY)
parser.add_argument("--prop-diameter-in", type=float, default=DEFAULT_PROP_DIAMETER_IN)
parser.add_argument("--min-rpm", type=float, default=0.0)
parser.add_argument("--min-pwm", type=float, default=1000.0)
parser.add_argument("--min-system-eff-rpm", type=float, default=DEFAULT_MIN_SYSTEM_EFF_RPM)
parser.add_argument("--rpm-outlier-z", type=float, default=DEFAULT_RPM_OUTLIER_Z)
parser.add_argument("--recursive", action="store_true")
return parser.parse_args(argv)
def main(argv: Iterable[str] | None = None) -> None:
args = parse_args(argv)
_configure_style()
source = args.source.expanduser().resolve()
data = load_folder_data(
source=source,
force_axis=args.force_axis,
torque_axis=args.torque_axis,
supply_v=args.supply_voltage,
air_density=args.air_density,
prop_diameter_in=args.prop_diameter_in,
min_rpm=args.min_rpm,
min_pwm=args.min_pwm,
min_system_eff_rpm=args.min_system_eff_rpm,
recursive=args.recursive,
rpm_outlier_z=args.rpm_outlier_z,
)
rpm = np.asarray(data.rpm, dtype=float)
thrust_kgf = np.asarray(data.fz_n, dtype=float) / G
torque_nm = np.asarray(data.tz_nm, dtype=float)
mech_pow = np.asarray(data.mechanical_power, dtype=float)
ct = np.asarray(data.ct, dtype=float)
cp = np.asarray(data.cp, dtype=float)
ref_rpm = np.asarray([row[0] for row in MEJZLIK_POINTS], dtype=float)
ref_thrust = np.asarray([row[1] for row in MEJZLIK_POINTS], dtype=float)
ref_torque = np.asarray([row[2] for row in MEJZLIK_POINTS], dtype=float)
ref_mech = np.asarray([row[3] for row in MEJZLIK_POINTS], dtype=float)
uiuc_rpm, uiuc_ct, uiuc_cp = _get_uiuc_reference()
fig = plt.figure(figsize=(13.4, 9.2), constrained_layout=True)
gs = fig.add_gridspec(3, 2)
ax_a = fig.add_subplot(gs[0, 0])
ax_b = fig.add_subplot(gs[1, 0], sharex=ax_a)
ax_c = fig.add_subplot(gs[2, 0], sharex=ax_a)
ax_d = fig.add_subplot(gs[0, 1])
ax_e = fig.add_subplot(gs[1, 1], sharex=ax_d)
ax_f = fig.add_subplot(gs[2, 1])
ax_f.axis("off")
mae_thrust = _plot_metric_vs_mejzlik(
ax_a,
rpm,
thrust_kgf,
ref_rpm,
ref_thrust,
ylabel="Thrust (kgf)",
title="Measured vs Mejzlik: Thrust",
color_user="#000000",
color_ref="#1b5e9a",
)
mae_torque = _plot_metric_vs_mejzlik(
ax_b,
rpm,
torque_nm,
ref_rpm,
ref_torque,
ylabel="Torque (Nm)",
title="Measured vs Mejzlik: Torque",
color_user="#000000",
color_ref="#1b5e9a",
)
mae_mech = _plot_metric_vs_mejzlik(
ax_c,
rpm,
mech_pow,
ref_rpm,
ref_mech,
ylabel="Mechanical power (W)",
title="Measured vs Mejzlik: Mechanical Power",
color_user="#000000",
color_ref="#1b5e9a",
)
mae_ct = _plot_coeff_vs_uiuc(
ax_d,
rpm,
ct,
uiuc_rpm,
uiuc_ct,
ylabel=r"Thrust coefficient $C_T$",
title="Measured vs UIUC: CT",
color_user="#000000",
color_uiuc="#1b5e9a",
)
mae_cp = _plot_coeff_vs_uiuc(
ax_e,
rpm,
cp,
uiuc_rpm,
uiuc_cp,
ylabel=r"Power coefficient $C_P$",
title="Measured vs UIUC: CP",
color_user="#000000",
color_uiuc="#1b5e9a",
)
ax_c.set_xlabel("RPM")
ax_e.set_xlabel("RPM")
ax_a.tick_params(labelbottom=False)
ax_b.tick_params(labelbottom=False)
ax_d.tick_params(labelbottom=False)
_panel_label(ax_a, "A")
_panel_label(ax_b, "B")
_panel_label(ax_c, "C")
_panel_label(ax_d, "D")
_panel_label(ax_e, "E")
handles, labels = ax_a.get_legend_handles_labels()
if handles:
ax_a.legend(handles, labels, loc="upper left", frameon=False)
handles, labels = ax_d.get_legend_handles_labels()
if handles:
ax_d.legend(handles, labels, loc="upper left", frameon=False)
report_lines = [
"Comparison summary (MAE on overlap):",
f"Thrust vs Mejzlik: {mae_thrust:.4f} kgf" if np.isfinite(mae_thrust) else "Thrust vs Mejzlik: n/a",
f"Torque vs Mejzlik: {mae_torque:.4f} Nm" if np.isfinite(mae_torque) else "Torque vs Mejzlik: n/a",
f"Power vs Mejzlik: {mae_mech:.2f} W" if np.isfinite(mae_mech) else "Power vs Mejzlik: n/a",
f"CT vs UIUC: {mae_ct:.4f}" if np.isfinite(mae_ct) else "CT vs UIUC: n/a",
f"CP vs UIUC: {mae_cp:.4f}" if np.isfinite(mae_cp) else "CP vs UIUC: n/a",
f"Rows used: {data.rows_used} from {data.files_used} file(s)",
f"RPM outliers removed: {data.outliers_removed}",
]
ax_f.text(0.0, 0.98, "\n".join(report_lines), va="top", ha="left", fontsize=9.3)
fig.suptitle(args.title, fontsize=14, fontweight="bold")
out_path = args.out.expanduser().resolve()
out_path.parent.mkdir(parents=True, exist_ok=True)
fig.savefig(out_path, dpi=args.dpi, bbox_inches="tight")
print(
f"Loaded {data.rows_used} rows from {data.files_used} file(s); "
f"removed {data.outliers_removed} RPM outliers"
)
print(f"Saved figure to {out_path}")
if __name__ == "__main__":
main()