Repository navigation
Expand file tree
/
Copy pathplot_force_torque.py
More file actions
349 lines (307 loc) · 12.2 KB
/
Copy pathplot_force_torque.py
File metadata and controls
349 lines (307 loc) · 12.2 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
#!/usr/bin/env python3
"""Plot PWM/RPM relationships to forces and torques for ESC thrust stand logs."""
from __future__ import annotations
import argparse
import csv
from collections import defaultdict
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Iterable, List, Tuple
import matplotlib.pyplot as plt
import numpy as np
FORCE_FIELDS = ("Fx", "Fy", "Fz")
TORQUE_FIELDS = ("Tx", "Ty", "Tz")
MIN_PWM_DEFAULT = 1000.0
@dataclass
class Dataset:
name: str
columns: Dict[str, List[float]]
def values(self, key: str) -> List[float]:
return self.columns.get(key, [])
def read_dataset(path: Path, min_pwm: float, max_rpm: float | None = None) -> Dataset:
"""Return a Dataset with samples filtered by PWM."""
columns: Dict[str, List[float]] = {field: [] for field in ("t_ms", "pwm", "rpm", *FORCE_FIELDS, *TORQUE_FIELDS)}
with path.open(newline="") as handle:
reader = csv.DictReader(handle)
if not {"pwm", "rpm", "Fx", "Fy", "Fz", "Tx", "Ty", "Tz"}.issubset(reader.fieldnames or []):
cols = ", ".join(reader.fieldnames or [])
raise ValueError(f"{path} missing required columns (need pwm,rpm,F*,T*). Found: {cols}")
for row in reader:
try:
pwm = float(row["pwm"])
except (KeyError, ValueError):
continue
if pwm <= min_pwm:
continue
try:
t_ms = float(row.get("t_ms", 0.0))
rpm = float(row["rpm"])
fx = float(row["Fx"])
fy = float(row["Fy"])
fz = float(row["Fz"])
tx = float(row["Tx"])
ty = float(row["Ty"])
tz = float(row["Tz"])
except (KeyError, ValueError):
continue
if max_rpm is not None and rpm > max_rpm:
continue
columns["t_ms"].append(t_ms)
columns["pwm"].append(pwm)
columns["rpm"].append(rpm)
columns["Fx"].append(fx)
columns["Fy"].append(fy)
columns["Fz"].append(fz)
columns["Tx"].append(tx)
columns["Ty"].append(ty)
columns["Tz"].append(tz)
# Drop keys that stayed empty to keep downstream logic simple
columns = {k: v for k, v in columns.items() if v}
return Dataset(name=path.name, columns=columns)
def compute_average_curve(xs: List[float], ys: List[float]) -> tuple[List[float], List[float]]:
buckets: Dict[float, List[float]] = defaultdict(lambda: [0.0, 0])
for x, y in zip(xs, ys):
bucket = buckets[x]
bucket[0] += y
bucket[1] += 1
items = sorted(buckets.items(), key=lambda kv: kv[0])
avg_x: List[float] = []
avg_y: List[float] = []
for x, (total, count) in items:
if count <= 0:
continue
avg_x.append(x)
avg_y.append(total / count)
return avg_x, avg_y
def compute_x_limits(datasets: List[Dataset], field: str) -> tuple[float, float] | None:
vals = [x for d in datasets for x in d.values(field)]
if not vals:
return None
xmin = min(vals)
xmax = max(vals)
if xmin == xmax:
margin = max(5.0, abs(xmin) * 0.05)
return xmin - margin, xmax + margin
span = xmax - xmin
margin = span * 0.05
return xmin - margin, xmax + margin
def rpm_squared_fit_curve(xs: List[float], ys: List[float]) -> tuple[np.ndarray, np.ndarray] | None:
"""Fit y = a*(RPM^2) + b and return a smooth curve in RPM space."""
if len(xs) < 2 or len(ys) < 2:
return None
x_arr = np.asarray(xs, dtype=float)
y_arr = np.asarray(ys, dtype=float)
finite = np.isfinite(x_arr) & np.isfinite(y_arr)
x_arr = x_arr[finite]
y_arr = y_arr[finite]
if x_arr.size < 2:
return None
coeff = np.polyfit(x_arr * x_arr, y_arr, 1)
x_fit = np.linspace(float(np.min(x_arr)), float(np.max(x_arr)), 200)
y_fit = coeff[0] * (x_fit * x_fit) + coeff[1]
return x_fit, y_fit
def plot_axis_grid(
datasets: List[Dataset],
x_field: str,
y_fields: Iterable[str],
title: str,
y_label: str,
) -> plt.Figure:
y_fields = list(y_fields)
fig, axes = plt.subplots(1, len(y_fields), figsize=(5.5 * len(y_fields), 4.5), sharex=False)
if isinstance(axes, np.ndarray):
axes = axes.ravel().tolist()
elif not isinstance(axes, (list, tuple)):
axes = [axes]
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
x_limits = compute_x_limits(datasets, x_field) if x_field == "pwm" else None
for idx, (field, ax) in enumerate(zip(y_fields, axes)):
for d_index, dataset in enumerate(datasets):
xs = dataset.values(x_field)
ys = dataset.values(field)
if not xs or not ys:
continue
avg_x, avg_y = compute_average_curve(xs, ys)
if not avg_x or not avg_y:
continue
ax.scatter(
avg_x,
avg_y,
marker="D",
s=42,
color=colors[d_index % len(colors)],
edgecolors="k",
linewidths=0.4,
label=dataset.name if idx == 0 else None,
)
if x_field == "rpm" and field in ("Fz", "Tz"):
fit = rpm_squared_fit_curve(avg_x, avg_y)
if fit is not None:
ax.plot(
fit[0],
fit[1],
linestyle="--",
linewidth=1.2,
color=colors[d_index % len(colors)],
alpha=0.9,
)
ax.set_title(f"{field} vs {x_field.upper()}")
ax.set_xlabel(f"{x_field.upper()} value")
if idx == 0:
ax.set_ylabel(y_label)
else:
ax.set_ylabel("")
ax.grid(True, alpha=0.3, linestyle="--", linewidth=0.7)
if x_field == "rpm" and field in ("Fz", "Tz"):
ax.text(0.02, 0.97, "Dashed line: RPM^2 fit", transform=ax.transAxes, va="top", fontsize=8)
if x_limits:
ax.set_xlim(*x_limits)
if idx == 0 and datasets:
ax.legend(loc="best", fontsize=8)
fig.suptitle(title)
fig.tight_layout()
return fig
def plot_z_axes_vs_rpm_squared(datasets: List[Dataset]) -> plt.Figure:
"""Plot z-axis force/torque against squared RPM to show near-linear trends."""
fig, axes = plt.subplots(1, 2, figsize=(11, 4.5), sharex=False)
if isinstance(axes, np.ndarray):
axes = axes.ravel().tolist()
elif not isinstance(axes, (list, tuple)):
axes = [axes]
colors = plt.rcParams["axes.prop_cycle"].by_key()["color"]
fields = [("Fz", "Force (N)"), ("Tz", "Torque (Nm)")]
for idx, ((field, y_label), ax) in enumerate(zip(fields, axes)):
for d_index, dataset in enumerate(datasets):
rpm = dataset.values("rpm")
ys = dataset.values(field)
if not rpm or not ys:
continue
rpm_sq = [x * x for x in rpm]
avg_x, avg_y = compute_average_curve(rpm_sq, ys)
if not avg_x or not avg_y:
continue
ax.scatter(
avg_x,
avg_y,
marker="D",
s=42,
color=colors[d_index % len(colors)],
edgecolors="k",
linewidths=0.4,
label=dataset.name if idx == 0 else None,
)
ax.set_title(f"{field} vs RPM^2")
ax.set_xlabel("RPM^2")
ax.set_ylabel(y_label if idx == 0 else "")
ax.grid(True, alpha=0.3, linestyle="--", linewidth=0.7)
if idx == 0 and datasets:
ax.legend(loc="best", fontsize=8)
fig.suptitle("Z-axis thrust/torque vs RPM^2")
fig.tight_layout()
return fig
def summarize_force_torque(dataset: Dataset, fields: Iterable[str]) -> Dict[str, float]:
averages: Dict[str, float] = {}
for field in fields:
vals = dataset.values(field)
if vals:
averages[field] = sum(vals) / len(vals)
return averages
def plot_summary_comparison(
primary: Dataset,
secondary: Dataset,
fields: Iterable[str],
) -> plt.Figure | None:
labels = [field for field in fields if primary.values(field) and secondary.values(field)]
if not labels:
return None
primary_avg = summarize_force_torque(primary, labels)
secondary_avg = summarize_force_torque(secondary, labels)
x = np.arange(len(labels))
width = 0.35
fig, ax = plt.subplots(figsize=(10, 4.5), constrained_layout=True)
ax.bar(x - width / 2, [primary_avg[l] for l in labels], width, label=primary.name, color="#1f77b4")
ax.bar(x + width / 2, [secondary_avg[l] for l in labels], width, label=secondary.name, color="#ff7f0e")
ax.set_xticks(x, labels)
ax.set_ylabel("Average value")
ax.set_title("Average force/torque comparison")
ax.grid(axis="y", alpha=0.3, linestyle="--", linewidth=0.7)
ax.legend()
print("\nAverage force/torque values")
print("Axis | Primary | Secondary | Difference")
print("-----+---------+-----------+-----------")
for label in labels:
main_val = primary_avg[label]
sec_val = secondary_avg[label]
diff = main_val - sec_val
print(f"{label:>4} | {main_val:7.3f} | {sec_val:9.3f} | {diff:9.3f}")
return fig
def parse_args(argv: Iterable[str] | None = None) -> argparse.Namespace:
parser = argparse.ArgumentParser(description="Plot PWM/RPM vs force/torque for thrust stand CSV logs.")
parser.add_argument("csv_files", nargs="+", help="One or more CSV files to analyze.")
parser.add_argument(
"--min-pwm",
type=float,
default=MIN_PWM_DEFAULT,
help="Ignore samples at or below this PWM (default 1000).",
)
parser.add_argument(
"--max-rpm",
type=float,
help="Ignore samples whose RPM exceeds this threshold.",
)
parser.add_argument(
"--save-prefix",
type=Path,
help="Optional prefix path to save all generated figures instead of only showing them.",
)
parser.add_argument(
"--compare-summary",
action="store_true",
help="Print and plot averaged force/torque comparisons between two files.",
)
return parser.parse_args(argv)
def main(argv: Iterable[str] | None = None) -> None:
args = parse_args(argv)
datasets: List[Dataset] = []
for csv_path in args.csv_files:
path = Path(csv_path).expanduser().resolve()
if not path.exists():
print(f"[WARN] {path} not found; skipping.")
continue
dataset = read_dataset(path, min_pwm=args.min_pwm, max_rpm=args.max_rpm)
if not dataset.columns:
print(f"[WARN] {path} produced no samples above PWM {args.min_pwm}.")
continue
datasets.append(dataset)
if not datasets:
raise SystemExit("No datasets loaded. Check file paths or PWM threshold.")
plt.style.use("seaborn-v0_8-colorblind")
figs = [
(plot_axis_grid(datasets, "pwm", FORCE_FIELDS, "PWM vs Force", "Force (N)"), "pwm_force"),
(plot_axis_grid(datasets, "pwm", TORQUE_FIELDS, "PWM vs Torque", "Torque (Nm)"), "pwm_torque"),
(plot_axis_grid(datasets, "rpm", FORCE_FIELDS, "RPM vs Force", "Force (N)"), "rpm_force"),
(plot_axis_grid(datasets, "rpm", TORQUE_FIELDS, "RPM vs Torque", "Torque (Nm)"), "rpm_torque"),
]
summary_fig = None
if args.compare_summary and len(datasets) >= 2:
primary, secondary = datasets[0], datasets[1]
summary_fig = plot_summary_comparison(primary, secondary, FORCE_FIELDS + TORQUE_FIELDS)
outputs: List[Tuple[plt.Figure | None, str]] = figs[:]
if summary_fig:
outputs.append((summary_fig, "summary"))
if args.save_prefix:
prefix = args.save_prefix
for fig, slug in outputs:
if fig is None:
continue
out_path = (
prefix.with_name(f"{prefix.name}_{slug}{prefix.suffix}")
if prefix.suffix
else Path(f"{prefix}_{slug}.png")
)
fig.savefig(out_path, dpi=300)
print(f"Saved {out_path}")
else:
plt.show()
if __name__ == "__main__":
main()