-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathmodels.py
967 lines (865 loc) · 33.4 KB
/
models.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
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
"""
Python module models.py for various vehicle models.
Author: Joshua A. Marshall <[email protected]>
GitHub: https://github.com/botprof/agv-examples
This module contains classes for various vehicle models, including:
* 1D vehicle class (i.e., a simple cart) [Cart]
* Differential-drive vehicle class [DiffDrive]
* Tricycle or planar bicycle vehicle class [Tricycle]
* Ackermann steered vehicle class [Ackermann]
* Four-wheel steering vehicle class [FourWheelSteering]
"""
import numpy as np
from mobotpy import graphics
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from scipy.stats import chi2
from matplotlib import patches
class Cart:
"""1D vehicle class (i.e., a simple cart).
Parameters
----------
length : float
Length of the cart [m].
"""
def __init__(self, length):
"""Constructor method."""
self.d = length
def draw(self, x):
"""Finds the points to draw simple rectangular cart.
The cart has position x and length d. The resulting cart has a height
that is half the length.
"""
X = np.array(5)
Y = np.array(5)
X = [
x - self.d / 2,
x - self.d / 2,
x + self.d / 2,
x + self.d / 2,
x - self.d / 2,
]
Y = [-self.d / 4, self.d / 4, self.d / 4, -self.d / 4, -self.d / 4]
return X, Y
def animate(self, x, T, save_ani=False, filename="animate_cart.gif"):
"""Create an animation of a simple 1D cart.
Returns animation object for array of 1D cart positions x with time
increments T [s], cart width d [m].
To save the animation to a GIF file, set save_ani to True and give a
filename (default filename is 'animate_cart.gif').
"""
fig, ax = plt.subplots()
plt.plot([np.min(x) - self.d, np.max(x) + self.d], [0, 0], "k--")
plt.xlabel(r"$x$ [m]")
ax.set_xlim([np.min(x) - self.d, np.max(x) + self.d])
plt.yticks([])
plt.axis("equal")
(polygon,) = ax.fill([], [], "C0", alpha=0.5)
(line,) = plt.plot([], [], "ko")
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
# Initialization function
def init():
polygon.set_xy(np.empty([5, 2]))
line.set_data([], [])
time_text.set_text("")
return polygon, line, time_text
# Function to draw cart
def movie(k):
X, Y = self.draw(x[k])
a = [X, Y]
polygon.set_xy(np.transpose(a))
line.set_data([x[k]], [0])
time_text.set_text(r"$t$ = %.1f s" % (k * T))
return polygon, line, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
# Save to a file if requested
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani
class DiffDrive:
"""Differential-drive vehicle class.
Parameters
----------
ell : float
The track length of the vehicle [m].
"""
def __init__(self, ell):
"""Constructor method."""
self.ell = ell
def f(self, x, u):
"""Differential drive kinematic vehicle kinematic model.
Parameters
----------
x : ndarray of length 3
The vehicle's state (x, y, theta).
u : ndarray of length 2
The left and right wheel speeds (v_L, v_R).
Returns
-------
f : ndarray of length 3
The rate of change of the vehicle states.
"""
f = np.zeros(3)
f[0] = 0.5 * (u[0] + u[1]) * np.cos(x[2])
f[1] = 0.5 * (u[0] + u[1]) * np.sin(x[2])
f[2] = 1.0 / self.ell * (u[1] - u[0])
return f
def uni2diff(self, u_in):
"""
Convert speed and angular rate inputs to differential drive wheel speeds.
Parameters
----------
u_in : ndarray of length 2
The speed and turning rate of the vehicle (v, omega).
Returns
-------
u_out : ndarray of length 2
The left and right wheel speeds (v_L, v_R).
"""
v = u_in[0]
omega = u_in[1]
v_L = v - self.ell / 2 * omega
v_R = v + self.ell / 2 * omega
u_out = np.array([v_L, v_R])
return u_out
def draw(self, x, y, theta):
"""
Finds points that draw a differential drive vehicle.
The centre of the wheel axle is (x, y), the vehicle has orientation
theta, and the vehicle's track length is ell.
Returns X_L, Y_L, X_R, Y_R, X_BD, Y_BD, X_C, Y_C, where L is for the
left wheel, R for the right wheel, B for the body, and C for the caster.
"""
# Left and right wheels
X_L, Y_L = graphics.draw_rectangle(
x - 0.5 * self.ell * np.sin(theta),
y + 0.5 * self.ell * np.cos(theta),
0.5 * self.ell,
0.25 * self.ell,
theta,
)
X_R, Y_R = graphics.draw_rectangle(
x + 0.5 * self.ell * np.sin(theta),
y - 0.5 * self.ell * np.cos(theta),
0.5 * self.ell,
0.25 * self.ell,
theta,
)
# Body
X_BD, Y_BD = graphics.draw_circle(x, y, self.ell)
# Caster
X_C, Y_C = graphics.draw_circle(
x + 0.5 * self.ell * np.cos(theta),
y + 0.5 * self.ell * np.sin(theta),
0.125 * self.ell,
)
# Return the arrays of points
return X_L, Y_L, X_R, Y_R, X_BD, Y_BD, X_C, Y_C
def animate(self, x, T, save_ani=False, filename="animate_diffdrive.gif"):
"""Create an animation of a differential drive vehicle.
Returns animation object for array of vehicle positions x with time
increments T [s], track ell [m].
To save the animation to a GIF file, set save_ani to True and provide a
filename (default 'animate_diffdrive.gif').
"""
fig, ax = plt.subplots()
plt.xlabel(r"$x$ [m]")
plt.ylabel(r"$y$ [m]")
plt.axis("equal")
(line,) = ax.plot([], [], "C0")
(leftwheel,) = ax.fill([], [], color="k")
(rightwheel,) = ax.fill([], [], color="k")
(body,) = ax.fill([], [], color="C0", alpha=0.5)
(castor,) = ax.fill([], [], color="k")
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
def init():
"""Function that initializes the animation."""
line.set_data([], [])
leftwheel.set_xy(np.empty([5, 2]))
rightwheel.set_xy(np.empty([5, 2]))
body.set_xy(np.empty([36, 2]))
castor.set_xy(np.empty([36, 2]))
time_text.set_text("")
return line, leftwheel, rightwheel, body, castor, time_text
def movie(k):
"""Function called at each step of the animation."""
# Draw the path followed by the vehicle
line.set_data(x[0, 0 : k + 1], x[1, 0 : k + 1])
# Draw the differential drive vehicle
X_L, Y_L, X_R, Y_R, X_B, Y_B, X_C, Y_C = self.draw(
x[0, k], x[1, k], x[2, k]
)
leftwheel.set_xy(np.transpose([X_L, Y_L]))
rightwheel.set_xy(np.transpose([X_R, Y_R]))
body.set_xy(np.transpose([X_B, Y_B]))
castor.set_xy(np.transpose([X_C, Y_C]))
# Add the simulation time
time_text.set_text(r"$t$ = %.1f s" % (k * T))
# Dynamically set the axis limits
ax.set_xlim(x[0, k] - 10 * self.ell, x[0, k] + 10 * self.ell)
ax.set_ylim(x[1, k] - 10 * self.ell, x[1, k] + 10 * self.ell)
ax.figure.canvas.draw()
# Return the objects to animate
return line, leftwheel, rightwheel, body, castor, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x[0, :]), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani
def animate_trajectory(
self, x, xd, T, save_ani=False, filename="animate_diffdrive.gif"
):
"""Create an animation of a differential drive vehicle with plots of
actual and desired trajectories.
Returns animation object for array of vehicle positions and desired
positions x with time increments T [s], track ell [m].
To save the animation to a GIF file, set save_ani to True and provide a
filename (default 'animate_diffdrive.gif').
"""
fig, ax = plt.subplots()
plt.xlabel(r"$x$ [m]")
plt.ylabel(r"$y$ [m]")
plt.axis("equal")
(desired,) = ax.plot([], [], "--C1")
(line,) = ax.plot([], [], "C0")
(leftwheel,) = ax.fill([], [], color="k")
(rightwheel,) = ax.fill([], [], color="k")
(body,) = ax.fill([], [], color="C0", alpha=0.5)
(castor,) = ax.fill([], [], color="k")
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
def init():
"""Function that initializes the animation."""
desired.set_data([], [])
line.set_data([], [])
leftwheel.set_xy(np.empty([5, 2]))
rightwheel.set_xy(np.empty([5, 2]))
body.set_xy(np.empty([36, 2]))
castor.set_xy(np.empty([36, 2]))
time_text.set_text("")
return desired, line, leftwheel, rightwheel, body, castor, time_text
def movie(k):
"""Function called at each step of the animation."""
# Draw the desired trajectory
desired.set_data(xd[0, 0 : k + 1], xd[1, 0 : k + 1])
# Draw the path followed by the vehicle
line.set_data(x[0, 0 : k + 1], x[1, 0 : k + 1])
# Draw the differential drive vehicle
X_L, Y_L, X_R, Y_R, X_B, Y_B, X_C, Y_C = self.draw(
x[0, k], x[1, k], x[2, k]
)
leftwheel.set_xy(np.transpose([X_L, Y_L]))
rightwheel.set_xy(np.transpose([X_R, Y_R]))
body.set_xy(np.transpose([X_B, Y_B]))
castor.set_xy(np.transpose([X_C, Y_C]))
# Add the simulation time
time_text.set_text(r"$t$ = %.1f s" % (k * T))
# Dynamically set the axis limits
ax.set_xlim(x[0, k] - 10 * self.ell, x[0, k] + 10 * self.ell)
ax.set_ylim(x[1, k] - 10 * self.ell, x[1, k] + 10 * self.ell)
ax.figure.canvas.draw()
# Return the objects to animate
return desired, line, leftwheel, rightwheel, body, castor, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x[0, :]), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani
def animate_estimation(
self,
x,
x_hat,
P_hat,
alpha,
T,
save_ani=False,
filename="animate_diffdrive.gif",
):
"""Create an animation of a differential drive vehicle with plots of
estimation uncertainty.
Returns animation object for array of vehicle positions x with time
increments T [s], track ell [m].
To save the animation to a GIF file, set save_ani to True and provide a
filename (default 'animate_diffdrive.gif').
"""
fig, ax = plt.subplots()
plt.xlabel(r"$x$ [m]")
plt.ylabel(r"$y$ [m]")
plt.axis("equal")
(estimated,) = ax.plot([], [], "--C1")
(line,) = ax.plot([], [], "C0")
(leftwheel,) = ax.fill([], [], color="k")
(rightwheel,) = ax.fill([], [], color="k")
(body,) = ax.fill([], [], color="C0", alpha=0.5)
(castor,) = ax.fill([], [], color="k")
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
s2 = chi2.isf(alpha, 2)
def init():
"""Function that initializes the animation."""
estimated.set_data([], [])
line.set_data([], [])
leftwheel.set_xy(np.empty([5, 2]))
rightwheel.set_xy(np.empty([5, 2]))
body.set_xy(np.empty([36, 2]))
castor.set_xy(np.empty([36, 2]))
time_text.set_text("")
return estimated, line, leftwheel, rightwheel, body, castor, time_text
def movie(k):
"""Function called at each step of the animation."""
# Draw the desired trajectory
estimated.set_data(x_hat[0, 0 : k + 1], x_hat[1, 0 : k + 1])
# Draw the path followed by the vehicle
line.set_data(x[0, 0 : k + 1], x[1, 0 : k + 1])
# Draw the differential drive vehicle
X_L, Y_L, X_R, Y_R, X_B, Y_B, X_C, Y_C = self.draw(
x[0, k], x[1, k], x[2, k]
)
leftwheel.set_xy(np.transpose([X_L, Y_L]))
rightwheel.set_xy(np.transpose([X_R, Y_R]))
body.set_xy(np.transpose([X_B, Y_B]))
castor.set_xy(np.transpose([X_C, Y_C]))
# Compute eigenvalues and eigenvectors to find axes for covariance ellipse
W, V = np.linalg.eig(P_hat[0:2, 0:2, k])
# Find the index of the largest and smallest eigenvalues
j_max = np.argmax(W)
j_min = np.argmin(W)
ell = patches.Ellipse(
(x_hat[0, k], x_hat[1, k]),
2 * np.sqrt(s2 * W[j_max]),
2 * np.sqrt(s2 * W[j_min]),
angle=np.arctan2(V[j_max, 1], V[j_max, 0]) * 180 / np.pi,
alpha=0.2,
color="C1",
)
ax.add_artist(ell)
# Add the simulation time
time_text.set_text(r"$t$ = %.1f s" % (k * T))
# Dynamically set the axis limits
ax.set_xlim(x[0, k] - 10 * self.ell, x[0, k] + 10 * self.ell)
ax.set_ylim(x[1, k] - 10 * self.ell, x[1, k] + 10 * self.ell)
ax.figure.canvas.draw()
# Return the objects to animate
return estimated, line, leftwheel, rightwheel, body, castor, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x[0, :]), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani
class Tricycle:
"""Tricycle or planar bicycle vehicle class.
Parameters
----------
ell_W : float
The wheelbase of the vehicle [m].
ell_T : float
The vehicle's track length [m].
"""
def __init__(self, ell_W, ell_T):
"""Constructor method."""
self.ell_W = ell_W
self.ell_T = ell_T
def f(self, x, u):
"""Tricycle or planar bicycle vehicle kinematic model.
Parameters
----------
x : ndarray of length 4
The vehicle's state (x, y, theta, phi).
u : ndarray of length 2
Returns
-------
f : ndarray of length 4
The rate of change of the vehicle states.
"""
f = np.zeros(4)
f[0] = u[0] * np.cos(x[2])
f[1] = u[0] * np.sin(x[2])
f[2] = u[0] * 1.0 / self.ell_W * np.tan(x[3])
f[3] = u[1]
return f
def draw(self, x, y, theta, phi):
"""Finds points that draw a tricycle vehicle.
The centre of the rear wheel axle is (x, y), the body has orientation
theta, steering angle phi, wheelbase ell_W and track length ell_T.
Returns X_L, Y_L, X_R, Y_R, X_F, Y_F, X_B, Y_B, where L is for the left
wheel, R is for the right wheel, F is for the single front wheel, and
BD is for the vehicle's body.
"""
# Left and right back wheels
X_L, Y_L = graphics.draw_rectangle(
x - 0.5 * self.ell_T * np.sin(theta),
y + 0.5 * self.ell_T * np.cos(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta,
)
X_R, Y_R = graphics.draw_rectangle(
x + 0.5 * self.ell_T * np.sin(theta),
y - 0.5 * self.ell_T * np.cos(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta,
)
# Front wheel
X_F, Y_F = graphics.draw_rectangle(
x + self.ell_W * np.cos(theta),
y + self.ell_W * np.sin(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta + phi,
)
# Body
X_BD, Y_BD = graphics.draw_rectangle(
x + self.ell_W / 2.0 * np.cos(theta),
y + self.ell_W / 2.0 * np.sin(theta),
2.0 * self.ell_W,
2.0 * self.ell_T,
theta,
)
# Return the arrays of points
return X_L, Y_L, X_R, Y_R, X_F, Y_F, X_BD, Y_BD
def animate(
self,
x,
T,
save_ani=False,
filename="animate_tricycle.gif",
):
"""Create an animation of a tricycle vehicle.
Returns animation object for array of vehicle positions x with time
increments T [s], wheelbase ell_W [m], and track ell_T [m].
To save the animation to a GIF file, set save_ani to True and give a
filename (default 'animate_tricycle.gif').
"""
fig, ax = plt.subplots()
plt.xlabel(r"$x$ [m]")
plt.ylabel(r"$y$ [m]")
plt.axis("equal")
(line,) = ax.plot([], [], "C0")
(leftwheel,) = ax.fill([], [], color="k")
(rightwheel,) = ax.fill([], [], color="k")
(frontwheel,) = ax.fill([], [], color="k")
(body,) = ax.fill([], [], color="C0", alpha=0.5)
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
def init():
"""A function that initializes the animation."""
line.set_data([], [])
leftwheel.set_xy(np.empty([5, 2]))
rightwheel.set_xy(np.empty([5, 2]))
frontwheel.set_xy(np.empty([5, 2]))
body.set_xy(np.empty([5, 2]))
time_text.set_text("")
return line, leftwheel, rightwheel, frontwheel, body, time_text
def movie(k):
"""The function called at each step of the animation."""
# Draw the path followed by the vehicle
line.set_data(x[0, 0 : k + 1], x[1, 0 : k + 1])
# Draw the tricycle vehicle
X_L, Y_L, X_R, Y_R, X_F, Y_F, X_B, Y_B = self.draw(
x[0, k], x[1, k], x[2, k], x[3, k]
)
leftwheel.set_xy(np.transpose([X_L, Y_L]))
rightwheel.set_xy(np.transpose([X_R, Y_R]))
frontwheel.set_xy(np.transpose([X_F, Y_F]))
body.set_xy(np.transpose([X_B, Y_B]))
# Add the simulation time
time_text.set_text(r"$t$ = %.1f s" % (k * T))
# Dynamically set the axis limits
ax.set_xlim(x[0, k] - 10 * self.ell_W, x[0, k] + 10 * self.ell_W)
ax.set_ylim(x[1, k] - 10 * self.ell_W, x[1, k] + 10 * self.ell_W)
ax.figure.canvas.draw()
# Return the objects to animate
return line, leftwheel, rightwheel, frontwheel, body, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x[0, :]), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani
class Ackermann:
"""Ackermann steered vehicle class.
Parameters
----------
ell_W : float
The wheelbase of the vehicle [m].
ell_T : float
The vehicle's track length [m].
"""
def __init__(self, ell_W, ell_T):
"""Constructor method."""
self.ell_W = ell_W
self.ell_T = ell_T
def f(self, x, u):
"""Ackermann steered vehicle kinematic model.
Parameters
----------
x : ndarray of length 4
The vehicle's state (x, y, theta, phi).
u : ndarray of length 2
The vehicle's speed and steering angle rate.
Returns
-------
f : ndarray of length 4
The rate of change of the vehicle states.
"""
f = np.zeros(4)
f[0] = u[0] * np.cos(x[2])
f[1] = u[0] * np.sin(x[2])
f[2] = u[0] * 1.0 / self.ell_W * np.tan(x[3])
f[3] = u[1]
return f
def ackermann(self, x):
"""Computes the Ackermann steering angles.
Parameters
----------
x : ndarray of length 4
The vehicle's state (x, y, theta, phi).
Returns
-------
ackermann_angles : ndarray of length 2
The left and right wheel angles (phi_L, phi_R).
"""
phi_L = np.arctan(
2 * self.ell_W * np.tan(x[3]) / (2 * self.ell_W - self.ell_T * np.tan(x[3]))
)
phi_R = np.arctan(
2 * self.ell_W * np.tan(x[3]) / (2 * self.ell_W + self.ell_T * np.tan(x[3]))
)
ackermann_angles = np.array([phi_L, phi_R])
return ackermann_angles
def draw(self, x, y, theta, phi_L, phi_R):
"""Finds points that draw an Ackermann steered (car-like) vehicle.
The centre of the rear wheel axle is (x, y), the body has orientation
theta, effective steering angle phi, wheelbase ell_W and track length
ell_T.
Returns X_BL, Y_BL, X_BR, Y_BR, X_FL, Y_FL, X_FR, Y_FR, X_BD, Y_BD,
where L denotes left, R denotes right, B denotes back, F denotes front,
and BD denotes the vehicle's body.
"""
# Left and right back wheels
X_BL, Y_BL = graphics.draw_rectangle(
x - 0.5 * self.ell_T * np.sin(theta),
y + 0.5 * self.ell_T * np.cos(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta,
)
X_BR, Y_BR = graphics.draw_rectangle(
x + 0.5 * self.ell_T * np.sin(theta),
y - 0.5 * self.ell_T * np.cos(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta,
)
# Left and right front wheels
X_FL, Y_FL = graphics.draw_rectangle(
x + self.ell_W * np.cos(theta) - self.ell_T / 2 * np.sin(theta),
y + self.ell_W * np.sin(theta) + self.ell_T / 2 * np.cos(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta + phi_L,
)
X_FR, Y_FR = graphics.draw_rectangle(
x + self.ell_W * np.cos(theta) + self.ell_T / 2 * np.sin(theta),
y + self.ell_W * np.sin(theta) - self.ell_T / 2 * np.cos(theta),
0.5 * self.ell_T,
0.25 * self.ell_T,
theta + phi_R,
)
# Body
X_BD, Y_BD = graphics.draw_rectangle(
x + self.ell_W / 2.0 * np.cos(theta),
y + self.ell_W / 2.0 * np.sin(theta),
2.0 * self.ell_W,
2.0 * self.ell_T,
theta,
)
# Return the arrays of points
return X_BL, Y_BL, X_BR, Y_BR, X_FL, Y_FL, X_FR, Y_FR, X_BD, Y_BD
def animate(
self,
x,
T,
phi_L,
phi_R,
save_ani=False,
filename="animate_ackermann.gif",
):
"""Create an animation of an Ackermann steered (car-like) vehicle.
Returns animation object for array of vehicle positions x with time
increments T [s], wheelbase ell_W [m], and track ell_T [m].
To save the animation to a GIF file, set save_ani to True and give a
filename (default 'animate_ackermann.gif').
"""
fig, ax = plt.subplots()
plt.xlabel(r"$x$ [m]")
plt.ylabel(r"$y$ [m]")
plt.axis("equal")
(line,) = ax.plot([], [], "C0")
(BLwheel,) = ax.fill([], [], color="k")
(BRwheel,) = ax.fill([], [], color="k")
(FLwheel,) = ax.fill([], [], color="k")
(FRwheel,) = ax.fill([], [], color="k")
(body,) = ax.fill([], [], color="C0", alpha=0.5)
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
def init():
"""A function that initializes the animation."""
line.set_data([], [])
BLwheel.set_xy(np.empty([5, 2]))
BRwheel.set_xy(np.empty([5, 2]))
FLwheel.set_xy(np.empty([5, 2]))
FRwheel.set_xy(np.empty([5, 2]))
body.set_xy(np.empty([5, 2]))
time_text.set_text("")
return line, BLwheel, BRwheel, FLwheel, FRwheel, body, time_text
def movie(k):
"""The function called at each step of the animation."""
# Draw the path followed by the vehicle
line.set_data(x[0, 0 : k + 1], x[1, 0 : k + 1])
# Draw the Ackermann steered drive vehicle
X_BL, Y_BL, X_BR, Y_BR, X_FL, Y_FL, X_FR, Y_FR, X_BD, Y_BD = self.draw(
x[0, k], x[1, k], x[2, k], phi_L[k], phi_R[k]
)
BLwheel.set_xy(np.transpose([X_BL, Y_BL]))
BRwheel.set_xy(np.transpose([X_BR, Y_BR]))
FLwheel.set_xy(np.transpose([X_FL, Y_FL]))
FRwheel.set_xy(np.transpose([X_FR, Y_FR]))
body.set_xy(np.transpose([X_BD, Y_BD]))
# Add the simulation time
time_text.set_text(r"$t$ = %.1f s" % (k * T))
# Dynamically set the axis limits
ax.set_xlim(x[0, k] - 10 * self.ell_W, x[0, k] + 10 * self.ell_W)
ax.set_ylim(x[1, k] - 10 * self.ell_W, x[1, k] + 10 * self.ell_W)
ax.figure.canvas.draw()
# Return the objects to animate
return line, BLwheel, BRwheel, FLwheel, FRwheel, body, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x[0, :]), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani
class FourWheelSteered:
"""Four-wheel steered vehicle class.
Parameters
----------
ell_W : float
The wheelbase of the vehicle [m].
ell_T : float
The vehicle's track length [m].
"""
def __init__(self, ell_W, ell_T):
"""Constructor method."""
self.ell_W = ell_W
self.ell_T = ell_T
def f(self, x, u):
"""Four-wheel steered vehicle kinematic model.
Parameters
----------
x : ndarray of length 4
The vehicle's state (x, y, theta, phi).
u : ndarray of length 2
The vehicle's front wheel speed and steering angle rate.
Returns
-------
f : ndarray of length 4
The rate of change of the vehicle states.
"""
f = np.zeros(4)
f[0] = u[0] * np.cos(x[2]) * np.cos(x[3])
f[1] = u[0] * np.sin(x[2]) * np.cos(x[3])
f[2] = u[0] * 1.0 / (0.5 * self.ell_W) * np.sin(x[3])
f[3] = u[1]
return f
def ackermann(self, x):
"""Computes the Ackermann steering angles.
Parameters
----------
x : ndarray of length 4
The vehicle's state (x, y, theta, phi).
Returns
-------
ackermann_angles : ndarray of length 2
The left and right wheel angles (phi_L, phi_R).
"""
phi_L = np.arctan(
2 * self.ell_W * np.tan(x[3]) / (2 * self.ell_W - self.ell_T * np.tan(x[3]))
)
phi_R = np.arctan(
2 * self.ell_W * np.tan(x[3]) / (2 * self.ell_W + self.ell_T * np.tan(x[3]))
)
ackermann_angles = np.array([phi_L, phi_R])
return ackermann_angles
def draw(self, x):
"""Finds points that draw a four-wheel steered vehicle.
Parameters
----------
x : ndarray of length 4
The vehicle's state (x, y, theta, phi).
The geometric centre of the vehicle is (x, y), the body has orientation
theta, effective steering angle phi, wheelbase ell_W and track length
ell_T.
Returns X_BL, Y_BL, X_BR, Y_BR, X_FL, Y_FL, X_FR, Y_FR, X_BD, Y_BD,
where L denotes left, R denotes right, B denotes back, F denotes front,
and BD denotes the vehicle's body.
"""
# Left and right back wheels
X_BL, Y_BL = graphics.draw_rectangle(
x[0] - 0.5 * self.ell_W * np.cos(x[2]) - 0.5 * self.ell_T * np.sin(x[2]),
x[1] - 0.5 * self.ell_W * np.sin(x[2]) + 0.5 * self.ell_T * np.cos(x[2]),
0.5 * self.ell_T,
0.25 * self.ell_T,
x[2] - self.ackermann(x)[0],
)
X_BR, Y_BR = graphics.draw_rectangle(
x[0] - 0.5 * self.ell_W * np.cos(x[2]) + 0.5 * self.ell_T * np.sin(x[2]),
x[1] - 0.5 * self.ell_W * np.sin(x[2]) - 0.5 * self.ell_T * np.cos(x[2]),
0.5 * self.ell_T,
0.25 * self.ell_T,
x[2] - self.ackermann(x)[1],
)
# Left and right front wheels
X_FL, Y_FL = graphics.draw_rectangle(
x[0] + 0.5 * self.ell_W * np.cos(x[2]) - self.ell_T / 2 * np.sin(x[2]),
x[1] + 0.5 * self.ell_W * np.sin(x[2]) + self.ell_T / 2 * np.cos(x[2]),
0.5 * self.ell_T,
0.25 * self.ell_T,
x[2] + self.ackermann(x)[0],
)
X_FR, Y_FR = graphics.draw_rectangle(
x[0] + 0.5 * self.ell_W * np.cos(x[2]) + self.ell_T / 2 * np.sin(x[2]),
x[1] + 0.5 * self.ell_W * np.sin(x[2]) - self.ell_T / 2 * np.cos(x[2]),
0.5 * self.ell_T,
0.25 * self.ell_T,
x[2] + self.ackermann(x)[1],
)
# Body
X_BD, Y_BD = graphics.draw_rectangle(
x[0],
x[1],
2.0 * self.ell_W,
2.0 * self.ell_T,
x[2],
)
# Return the arrays of points
return X_BL, Y_BL, X_BR, Y_BR, X_FL, Y_FL, X_FR, Y_FR, X_BD, Y_BD
def animate(
self,
x,
T,
save_ani=False,
filename="animate_fourwheelsteered.gif",
):
"""Create an animation of an Ackermann steered (car-like) vehicle.
Returns animation object for array of vehicle positions x with time
increments T [s], wheelbase ell_W [m], and track ell_T [m].
To save the animation to a GIF file, set save_ani to True and give a
filename (default 'animate_ackermann.gif').
"""
fig, ax = plt.subplots()
plt.xlabel(r"$x$ [m]")
plt.ylabel(r"$y$ [m]")
plt.axis("equal")
(line,) = ax.plot([], [], "C0")
(BLwheel,) = ax.fill([], [], color="k")
(BRwheel,) = ax.fill([], [], color="k")
(FLwheel,) = ax.fill([], [], color="k")
(FRwheel,) = ax.fill([], [], color="k")
(body,) = ax.fill([], [], color="C0", alpha=0.5)
time_text = ax.text(0.05, 0.9, "", transform=ax.transAxes)
def init():
"""A function that initializes the animation."""
line.set_data([], [])
BLwheel.set_xy(np.empty([5, 2]))
BRwheel.set_xy(np.empty([5, 2]))
FLwheel.set_xy(np.empty([5, 2]))
FRwheel.set_xy(np.empty([5, 2]))
body.set_xy(np.empty([5, 2]))
time_text.set_text("")
return line, BLwheel, BRwheel, FLwheel, FRwheel, body, time_text
def movie(k):
"""The function called at each step of the animation."""
# Draw the path followed by the vehicle
line.set_data(x[0, 0 : k + 1], x[1, 0 : k + 1])
# Draw the Ackermann steered drive vehicle
X_BL, Y_BL, X_BR, Y_BR, X_FL, Y_FL, X_FR, Y_FR, X_BD, Y_BD = self.draw(
x[:, k]
)
BLwheel.set_xy(np.transpose([X_BL, Y_BL]))
BRwheel.set_xy(np.transpose([X_BR, Y_BR]))
FLwheel.set_xy(np.transpose([X_FL, Y_FL]))
FRwheel.set_xy(np.transpose([X_FR, Y_FR]))
body.set_xy(np.transpose([X_BD, Y_BD]))
# Add the simulation time
time_text.set_text(r"$t$ = %.1f s" % (k * T))
# Dynamically set the axis limits
ax.set_xlim(x[0, k] - 10 * self.ell_W, x[0, k] + 10 * self.ell_W)
ax.set_ylim(x[1, k] - 10 * self.ell_W, x[1, k] + 10 * self.ell_W)
ax.figure.canvas.draw()
# Return the objects to animate
return line, BLwheel, BRwheel, FLwheel, FRwheel, body, time_text
# Create the animation
ani = animation.FuncAnimation(
fig,
movie,
np.arange(1, len(x[0, :]), max(1, int(1 / T / 10))),
init_func=init,
interval=T * 1000,
blit=True,
repeat=False,
)
if save_ani is True:
ani.save(filename, fps=min(1 / T, 10))
# Return the figure object
return ani