-
Notifications
You must be signed in to change notification settings - Fork 4
/
example_racecar.py
193 lines (165 loc) · 7.19 KB
/
example_racecar.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
"""
Please contact the author(s) of this library if you have any questions.
Author: Haimin Hu (haiminh@princeton.edu)
Reference: ECE346@Princeton (Zixu Zhang, Kai-Chieh Hsu, Duy P. Nguyen)
"""
import os, jax, argparse
import numpy as np
from matplotlib import cm
from matplotlib import pyplot as plt
from matplotlib.transforms import Affine2D
from IPython.display import Image
import imageio.v2 as imageio
jax.config.update('jax_platform_name', 'cpu')
jax.config.update('jax_enable_x64', True)
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman'] + plt.rcParams['font.serif']
from iLQR.utils import *
from iLQR.ilqr import iLQR
from iLQR.shielding import ILQshielding, NaiveSwerving
from iLQR.ellipsoid_obj import EllipsoidObj
def main(config_file):
# Loads the config and track file.
config = load_config(config_file)
track = load_track(config)
# Constructs static obstacles.
static_obs_list = []
obs_a = config.LENGTH / 2.0
obs_b = config.WIDTH / 2.0
obs_q1 = np.array([0, 5.6])[:, np.newaxis]
obs_Q1 = np.diag([obs_a**2, obs_b**2])
static_obs1 = EllipsoidObj(q=obs_q1, Q=obs_Q1)
static_obs_list.append([static_obs1 for _ in range(config.N)])
obs_q2 = np.array([-2.15, 4.0])[:, np.newaxis]
obs_Q2 = np.diag([obs_b**2, obs_a**2])
static_obs2 = EllipsoidObj(q=obs_q2, Q=obs_Q2)
static_obs_list.append([static_obs2 for _ in range(config.N)])
obs_q3 = np.array([-2.4, 2.0])[:, np.newaxis]
obs_Q3 = np.diag([obs_b**2, obs_a**2])
static_obs3 = EllipsoidObj(q=obs_q3, Q=obs_Q3)
static_obs_list.append([static_obs3 for _ in range(config.N)])
static_obs_heading_list = [-np.pi, -np.pi / 2, -np.pi / 2]
# Initialization.
solver = iLQR(track, config, safety=False) # Nominal racing iLQR
solver_sh = iLQR(track, config, safety=True) # Shielding safety backup iLQR
# max_deacc = config.A_MIN / 3 # config.A_MIN, config.A_MIN / 2, config.A_MIN / 3
# shielding = NaiveSwerving(
# config, [static_obs1, static_obs2, static_obs3], solver.dynamics,
# max_deacc=max_deacc, N_sh=15
# )
shielding = ILQshielding(
config, solver_sh, [static_obs1, static_obs2, static_obs3], static_obs_list, N_sh=15
)
pos0, psi0 = track.interp([2]) # Position and yaw on the track.
x_cur = np.array([3.3, 4.0, 0, np.pi / 2]) # Initial state.
# x_cur = np.array([pos0[0], pos0[1], 0, psi0[-1]])
init_control = np.zeros((2, config.N))
t_total = 0.
plot_cover = False
itr_receding = config.MAX_ITER_RECEDING # The number of receding iterations.
state_hist = np.zeros((4, itr_receding))
control_hist = np.zeros((2, itr_receding))
plan_hist = np.zeros((6, config.N, itr_receding))
K_hist = np.zeros((2, 4, config.N - 1, itr_receding))
fx_hist = np.zeros((4, 4, config.N, itr_receding))
fu_hist = np.zeros((4, 2, config.N, itr_receding))
# Specifies the folder to save figures.
fig_prog_folder = os.path.join(config.OUT_FOLDER, "progress")
os.makedirs(fig_prog_folder, exist_ok=True)
ego = plt.imread('misc/ego.png', format="png")
alter = plt.imread('misc/alter.png', format="png")
# Define disturbances.
sigma = np.array([config.SIGMA_X, config.SIGMA_Y, config.SIGMA_V, config.SIGMA_THETA])
# iLQR Planning.
for i in range(itr_receding):
# Plans the trajectory using iLQR.
states, controls, t_process, status, _, K_closed_loop, fx, fu = (
solver.solve(x_cur, controls=init_control, obs_list=static_obs_list)
)
# Shielding.
control_sh = shielding.run(x=x_cur, u_nominal=controls[:, 0])
# Executes the control.
x_cur = solver.dynamics.forward_step(x_cur, control_sh, step=1, noise=sigma)[0]
print("[{}]: solver returns status {} and uses {:.3f}.".format(i, status, t_process), end='\r')
if i > 0: # Excludes JAX compilation time at the first time step.
t_total += t_process
# Records planning history, states and controls.
plan_hist[:4, :, i] = states
plan_hist[4:, :, i] = controls
state_hist[:, i] = states[:, 0]
control_hist[:, i] = controls[:, 0]
K_hist[:, :, :, i] = K_closed_loop
fx_hist[:, :, :, i] = fx
fu_hist[:, :, :, i] = fu
# Updates the nominal control signal for warmstart of next receding horizon.
init_control[:, :-1] = controls[:, 1:]
# Plots the current progress.
plt.clf()
track.plot_track()
for static_obs in static_obs_list:
plot_ellipsoids(
plt.gca(), static_obs[0:1], arg_list=[dict(c='k', linewidth=1.)], dims=[0, 1], N=50,
plot_center=False, use_alpha=False
)
if plot_cover: # plot circles that cover the footprint.
static_obs[0].plot_circ(plt.gca())
solver.cost.soft_constraints.ego_ell[0].plot_circ(plt.gca())
if shielding.sh_flag:
plot_ellipsoids(
plt.gca(), [solver.cost.soft_constraints.ego_ell[0]], arg_list=[dict(c='r')], dims=[0, 1],
N=50, plot_center=False
)
else:
plot_ellipsoids(
plt.gca(), [solver.cost.soft_constraints.ego_ell[0]], arg_list=[dict(c='b')], dims=[0, 1],
N=50, plot_center=False
)
plt.plot(states[0, :], states[1, :], linewidth=2, c='b')
if shielding.sh_flag:
plt.plot(shielding.states[0, :], shielding.states[1, :], linewidth=2, c='r')
sc = plt.scatter(
state_hist[0, :i + 1], state_hist[1, :i + 1], s=24, c=state_hist[2, :i + 1], cmap=cm.jet,
vmin=0, vmax=config.V_MAX, edgecolor='none', marker='o'
)
# plot ego car figure
transform_data = Affine2D().rotate_deg_around(*(x_cur[0], x_cur[1]),
x_cur[3] / np.pi * 180) + plt.gca().transData
plt.imshow(
ego, transform=transform_data, interpolation='none', origin='lower',
extent=[x_cur[0] - 0.25, x_cur[0] + 0.25, x_cur[1] - 0.1,
x_cur[1] + 0.1], alpha=1.0, zorder=10.0, clip_on=True
)
# plot alter cars figure
for j in range(len(static_obs_list)):
_static_obs = static_obs_list[j][0]
transform_data = Affine2D().rotate_deg_around(
*(_static_obs.q[0, 0], _static_obs.q[1, 0]), static_obs_heading_list[j] / np.pi * 180
) + plt.gca().transData
plt.imshow(
alter, transform=transform_data, interpolation='none', origin='lower', extent=[
_static_obs.q[0, 0] - 0.25, _static_obs.q[0, 0] + 0.25, _static_obs.q[1, 0] - 0.1,
_static_obs.q[1, 0] + 0.1
], alpha=1.0, zorder=10.0, clip_on=True
)
cbar = plt.colorbar(sc)
cbar.set_label(r"velocity [$m/s$]", size=20)
plt.axis('equal')
plt.savefig(os.path.join(fig_prog_folder, str(i) + ".png"), dpi=200)
plt.close('All')
print("Planning uses {:.3f}.".format(t_total))
# Makes an animation.
gif_path = os.path.join(config.OUT_FOLDER, 'rollout.gif')
with imageio.get_writer(gif_path, mode='I', loop=0) as writer:
for i in range(itr_receding):
filename = os.path.join(fig_prog_folder, str(i) + ".png")
image = imageio.imread(filename)
writer.append_data(image)
Image(open(gif_path, 'rb').read(), width=400)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-cf", "--config_file", help="config file path", type=str,
default=os.path.join("", "example_racecar.yaml")
)
args = parser.parse_args()
main(args.config_file)