-
Notifications
You must be signed in to change notification settings - Fork 0
/
AnalyzeData.py
491 lines (443 loc) · 14.9 KB
/
AnalyzeData.py
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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import os
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.lines import Line2D
import numpy as np
import scipy.optimize as spo
from bicycleparameters.parameter_sets import Meijaard2007ParameterSet
from data import (
balance_assist_without_rider,
benchmark,
balance_assist_with_rider,
rigid_bike_without_rider,
rigid_bike_with_rider,
)
from model import SteerControlModel, Meijaard2007Model
TU_COLORS = {
"blue": (0 / 255, 166 / 255, 214 / 255),
"red": (224 / 255, 60 / 255, 49 / 255),
"orange": (237 / 255, 104 / 255, 66 / 255),
"yellow": (255 / 255, 184 / 255, 28 / 255),
}
def main():
plt.rc("xtick", labelsize=16)
plt.rc("ytick", labelsize=16)
font = {"size": 16}
plt.rc("font", **font)
mpl.rcParams["lines.linewidth"] = 3
parameter_set_bas = Meijaard2007ParameterSet(balance_assist_without_rider, False)
speeds = np.linspace(0.0, 6.0, num=61)
velocities = [6, 8, 10, 12, 14, 16, 18]
velocities_ms = [vel / 3.6 for vel in velocities]
colors_measured = [TU_COLORS["blue"], TU_COLORS["blue"], TU_COLORS["yellow"]]
colors_theoretical = ["lightgray", "gray", "black"]
# plot benchmark + controller and measured
# parameter_set_benchmark = Meijaard2007ParameterSet(benchmark, False)
# model_benchmark_control = SteerControlModel(parameter_set_benchmark)
# fig = plot_measured_eigenvalues(
# speeds,
# model_benchmark_control,
# colors_theoretical,
# colors_measured,
# velocities_ms,
# )
# fig.set_size_inches(16, 9)
# fig.suptitle(
# "Theoretical eigenvalues of riderless benchmark bicycle with controller compared to measured eigenvalues at gain of -6, -8 and -10",
# wrap=True,
# )
# plt.savefig("figures/all-gains-benchmark-control-no-rider", dpi=300)
# plot theoretical balance-assist with controller and measured
model_bas_control = SteerControlModel(parameter_set_bas)
plot_measured_eigenvalues(
speeds, model_bas_control, colors_theoretical, colors_measured, velocities_ms
)
# plot theoretical balance-assist without controller
speeds10 = np.linspace(0.0, 10.0, num=101)
model_bas_normal = Meijaard2007Model(parameter_set_bas)
fig, ax = plt.subplots()
ax = model_bas_normal.plot_eigenvalue_parts(
ax=ax,
v=speeds10,
colors=[
colors_theoretical[-1],
colors_theoretical[-1],
colors_theoretical[-1],
colors_theoretical[-1],
],
)
legend_elements = []
legend_elements.append(
Line2D(
[0],
[0],
color=colors_theoretical[-1],
lw=4,
label="Real",
)
)
legend_elements.append(
Line2D(
[0],
[0],
color=colors_theoretical[-1],
linestyle="--",
lw=4,
label="Imaginary",
)
)
fig.set_size_inches(16, 9)
ax.set_xlabel("velocity [m/s]")
ax.set_ylim(-7.5, 7.5)
ax.set_ylabel("Magnitude of eigenvalue [1/s]")
plt.legend(handles=legend_elements)
# fig.show()
fig.suptitle(
"Theoretical eigenvalues of riderless balance-assist bicycle without controller",
wrap=True,
)
plt.savefig("figures/theoretical-bas-no-control-no-rider", dpi=300)
# fig.waitforbuttonpress()
# plot theoretical balance-assist with rider without controller
parameter_set_bas_rider = Meijaard2007ParameterSet(balance_assist_with_rider, True)
model_bas_rider = Meijaard2007Model(parameter_set_bas_rider)
fig, ax = plt.subplots()
ax = model_bas_rider.plot_eigenvalue_parts(
ax=ax,
v=speeds10,
colors=[
colors_theoretical[-1],
colors_theoretical[-1],
"blue",
"blue",
],
)
fig.set_size_inches(16, 9)
for line in ax.get_lines():
if line.get_color() == "blue":
line.remove()
# plt.legend(handles=legend_elements)
# # fig.show()
# fig.suptitle(
# "Theoretical eigenvalues of balance-assist bicycle with rigid rider and without controller",
# wrap=True,
# )
# plt.savefig("figures/theoretical-bas-no-control-with-rider", dpi=300)
# # fig.waitforbuttonpress()
# plot balance assist with rider with controller
parameter_set_bas_rider = Meijaard2007ParameterSet(balance_assist_with_rider, True)
model_bas_rider_control = SteerControlModel(parameter_set_bas_rider)
for i, gain in enumerate([8]):
speed, kphi, kphidots = controller(speeds, gain)
ax = model_bas_rider_control.plot_eigenvalue_parts(
ax=ax,
v=speeds,
kphi=kphi,
kphidot=kphidots,
colors=[
colors_measured[i],
colors_measured[i],
"blue",
"blue",
],
)
for line in ax.get_lines():
if line.get_color() == "blue":
line.remove()
ax.plot(speeds, np.zeros(speeds.shape), color="black", linewidth=1.5, zorder=0)
fig.set_size_inches(16, 9)
legend_elements = [
Line2D(
[0],
[0],
color=colors_theoretical[-1],
lw=4,
label="Real eigenvalues, without controller",
),
Line2D(
[0],
[0],
color=colors_theoretical[-1],
lw=4,
linestyle="--",
label="Imaginary eigenvalues, without controller",
),
]
gains = ["-6", "-8", "-10"]
legend_elements.append(
Line2D(
[0],
[0],
color=colors_measured[0],
lw=4,
label="Real eigenvalues, with controller",
)
)
legend_elements.append(
Line2D(
[0],
[0],
color=colors_measured[0],
lw=4,
linestyle="--",
label="Imaginary eigenvalues, with controller",
)
)
plt.legend(handles=legend_elements)
# fig.show()
ax.grid()
ax.set_xlabel("Speed [m/s]")
ax.set_ylim(-7.5, 7.5)
ax.set_ylabel("Magnitude of eigenvalue [1/s]")
ax.set_title(
"Weave mode of the balance-assist bicycle model with rigid rider, with and without controller",
wrap=True,
)
plt.savefig("figures/theoretical-bas-with-control-with-rider", dpi=300)
# fig.waitforbuttonpress()
def plot_measured_eigenvalues(
speeds, model, colors_theoretical, colors_measured, velocities_ms
):
legend_elements = []
gains = ["-6", "-8", "-10"]
marker_shapes = ["o", "^", "s"]
for i, gain in enumerate([6, 8, 10]):
if gain == 6:
prefix = "12-May-2023-10-11-04-bas-on-gain-6-speed-"
else:
prefix = "12-May-2023-10-39-32-bas-on-gain-" + str(gain) + "-speed-"
real, img, r_squared = fit_curve(gain, prefix, show_plots=False)
fig, ax = plt.subplots()
ax.set_xlabel("velocity [m/s]")
ax.set_ylabel("Magnitude of eigenvalue [1/s]")
ax.set_ylim(-12.5, 12.5)
fig.set_size_inches(16, 9)
ax.set_title(
"Theoretical eigenvalues of riderless balance-assist bicycle with controller compared to measured eigenvalues",
wrap=True,
)
speed, kphi, kphidots = controller(speeds, gain)
ax = model.plot_eigenvalue_parts(
ax=ax,
v=speed,
kphi=kphi,
kphidot=kphidots,
colors=[
"black",
"black",
"black",
"black",
],
)
for line in ax.get_lines():
if line.get_linestyle() == "--":
line.remove()
legend_elements = []
legend_elements.append(
Line2D(
[0],
[0],
color="black",
lw=4,
label="Real eigenvalues of the model",
)
)
ax.legend(handles=legend_elements, loc="lower left")
plt.savefig("figures/eigenvalues-model-real-" + str(gain) + ".png", dpi=300)
plt.plot(
velocities_ms,
real,
marker_shapes[i],
label="Measured real eigenvalues",
color=colors_measured[i],
markersize=12,
)
legend_elements.append(
Line2D(
[0],
[0],
marker=marker_shapes[i],
markerfacecolor=colors_measured[i],
color="w",
markersize=15,
label="Measured real eigenvalues",
)
)
ax.legend(handles=legend_elements, loc="lower left")
plt.savefig(
"figures/eigenvalues-model-and-measured-real-" + str(gain) + ".png", dpi=300
)
for line in ax.get_lines():
line.remove()
ax = model.plot_eigenvalue_parts(
ax=ax,
v=speed,
kphi=kphi,
kphidot=kphidots,
colors=[
"black",
"black",
"black",
"black",
],
)
ax.grid()
plt.plot(
velocities_ms,
real,
marker_shapes[i],
label="Measured real eigenvalues",
color=colors_measured[i],
markersize=12,
)
legend_elements.append(
Line2D(
[0],
[0],
color="black",
lw=4,
linestyle="--",
label="Imaginary eigenvalues of the model",
)
)
ax.legend(handles=legend_elements, loc="lower left")
plt.savefig(
"figures/eigenvalues-model-and-measured-real-and-imaginary"
+ str(gain)
+ ".png",
dpi=300,
)
plt.plot(
velocities_ms,
img,
marker_shapes[0],
label="Measured imaginary eigenvalues",
color=colors_measured[i],
markersize=12,
)
legend_elements.append(
Line2D(
[0],
[0],
marker=marker_shapes[0],
markerfacecolor=colors_measured[i],
color="w",
markersize=15,
label="Measured imaginary eigenvalues",
)
)
ax.legend(handles=legend_elements, loc="lower left")
# for line in ax.get_lines():
# if line.get_linestyle() == "--":
# line.remove()
# if line.get_color() == "black":
# line.remove()
ax.set_xlabel("Speed [m/s]")
print(
f"R-squared values for gain {gain}: Mean: {np.mean(r_squared)}, Max: {np.max(r_squared)}, Min: {np.min(r_squared)}"
)
plt.savefig(
"figures/all-gains-bas-control-no-rider-gain-" + str(gain) + ".png", dpi=300
)
def fit_curve(gain: int, prefix: str, show_plots: bool = False):
dir = os.path.join("finalized_logs", "bas-on-gain-" + str(gain))
number_of_files = 3
velocities = [6, 8, 10, 12, 14, 16, 18]
avg_eigenvalues_real = []
avg_eigenvalues_img = []
r_squared = []
for j, vel in enumerate(velocities):
eigenvalues_real = []
eigenvalues_img = []
for i in np.linspace(1, number_of_files, number_of_files, dtype=int):
path = os.path.join(dir, prefix + str(vel))
df_gyro = pd.read_csv(path + "-gyro-" + str(i) + ".csv")
popt, pcov = spo.curve_fit(
kooijman_func,
df_gyro.loc[:, "time"],
df_gyro.loc[:, "gyro_x"],
p0=(-1.0, -1.0, 1.0, 3.0, 1.0),
)
eigenvalues_real.append(popt[1])
eigenvalues_img.append(popt[3])
# Calculate r-squared
residuals = df_gyro.loc[:, "gyro_x"] - kooijman_func(
df_gyro.loc[:, "time"], *popt
)
ss_res = np.sum(residuals**2)
ss_tot = np.sum(
(df_gyro.loc[:, "gyro_x"] - np.mean(df_gyro.loc[:, "gyro_x"])) ** 2
)
r_squared.append(1 - (ss_res / ss_tot))
if show_plots:
fig, ax = plt.subplots(1, 1)
ax.plot(
df_gyro.loc[:, "time"],
df_gyro.loc[:, "gyro_x"],
".",
label="Measured data",
color="black",
zorder=10,
)
ax.set_xlabel("Time since perturbation [s]")
ax.set_ylabel("Roll rate [rad/s]")
ax.set_title("Example of measured roll rate data")
ax.legend()
fig.set_size_inches(16, 9)
fig.savefig(
"figures/roll_rate_fits/gain-"
+ str(gain)
+ "-vel-"
+ str(vel)
+ "-file-"
+ str(i)
+ "-measured.png",
dpi=300,
)
ax.plot(
df_gyro.loc[:, "time"],
kooijman_func(
df_gyro.loc[:, "time"],
popt[0],
popt[1],
popt[2],
popt[3],
popt[4],
),
label="Fitted equation",
color=TU_COLORS["blue"],
zorder=5,
)
ax.set_title("Example of measured roll rate data and fitted equation")
ax.legend()
fig.set_size_inches(16, 9)
fig.set_dpi(300)
fig.savefig(
"figures/roll_rate_fits/gain-"
+ str(gain)
+ "-vel-"
+ str(vel)
+ "-file-"
+ str(i)
+ "fitted.png",
dpi=300,
)
avg_eigenvalues_real.append(sum(eigenvalues_real) / np.size(eigenvalues_real))
avg_eigenvalues_img.append(sum(eigenvalues_img) / np.size(eigenvalues_img))
return avg_eigenvalues_real, avg_eigenvalues_img, r_squared
def kooijman_func(t, c1, d, c2, omega, c3):
return c1 + np.exp(d * t) * (c2 * np.cos(omega * t) + c3 * np.sin(omega * t))
def controller(speeds, kv: int, kc: float = -0.7, vmin: float = 1.5, vmax: float = 4.7):
kphi = np.zeros(speeds.shape)
kphidots = np.zeros(speeds.shape)
for i, speed in enumerate(speeds):
# if speed < vmin:
# kphidots[i] = -kv * ((vmax - vmin) / vmin) * speed
if speed <= vmax:
kphidots[i] = -kv * (vmax - speed)
elif speed > vmax:
kphi[i] = kc * (speed - vmax)
return speeds, kphi, kphidots
if __name__ == "__main__":
main()