-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathoptimizer.py
368 lines (314 loc) · 11.7 KB
/
optimizer.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
from config import VehicleConfig, OptimizeConfig
from gridmap import GridMap
from geometry import get_polygon_halfspaces, Polygon
import casadi as ca
from casadi import numpy as canp
from se2state import SE2State
from typing import List
class Optimizer:
def __init__(self, veh_cfg=VehicleConfig(), opti_cfg=OptimizeConfig()) -> None:
self.veh_cfg = veh_cfg
self.opti_cfg = opti_cfg
self.opts = opti_cfg.solver_opts
self.offset = veh_cfg.length / 2 - veh_cfg.baselink_to_rear
self.n_states = 6
self.n_actions = 2
self.MU_LIST = []
self.LAMBDA_list = []
self.n_dual_variables_list = [] # lambda , mu
self.constraints = []
self.lbg = [] # lbx < x <ubx
self.ubg = []
self.lbx = [] # lbg < g(x) <ubg
self.ubx = []
self.max_x = 99999
self.max_y = 99999
self.min_x = -99999
self.min_y = -99999
self.variables = []
self.N = -1
self.x0 = []
self.obstacles: List[Polygon] = []
self.G = ca.DM(
[
[1, 0],
[0, 1],
[-1, 0],
[0, -1],
]
)
self.g = ca.DM(
[
[veh_cfg.length / 2],
[veh_cfg.width / 2],
[veh_cfg.length / 2],
[veh_cfg.width / 2],
]
)
self.DT = veh_cfg.T
self.Q = ca.SX(opti_cfg.Q)
self.R = ca.SX(opti_cfg.R)
self.obj = 0
self.se2trajectory = []
def initialize(
self,
init_se2guess: List[SE2State],
obstacles_list: List[Polygon],
gridmap: GridMap,
):
self.N = len(init_se2guess)
if self.N < 5:
raise ValueError("init trajectory too short.")
self.DT = abs(init_se2guess[1].t - init_se2guess[0].t)
self.obstacles = obstacles_list
for obstacle in obstacles_list:
self.n_dual_variables_list += [len(obstacle.vertexes)]
for se2state in init_se2guess:
self.x0 += [
[
se2state.x,
se2state.y,
se2state.heading,
se2state.v,
se2state.a,
se2state.delta,
]
]
# self.x0 += [[0] * (self.n_actions * (self.N - 1))] zeros init inputs.
for i in range(self.N - 1):
self.x0 += [[init_se2guess[i].jerk], [init_se2guess[i].delta_dot]]
for i in range(self.N):
for n_dual_variables in self.n_dual_variables_list:
self.x0 += [[0.1] * (n_dual_variables * 2)] # 2 for lambda and MU
self.max_x = gridmap.max_x
self.max_y = gridmap.max_y
self.min_x = gridmap.min_x
self.min_y = gridmap.min_y
# self.x0 += [[0.1] * (self.N - 1)] # for optimize t.
def build_model(self):
x = ca.SX.sym("x")
y = ca.SX.sym("y")
heading = ca.SX.sym("heading")
v = ca.SX.sym("v")
a = ca.SX.sym("a")
delta = ca.SX.sym("delta")
state = ca.vertcat(x, y, heading, v, a, delta)
jerk = ca.SX.sym("j")
delta_dot = ca.SX.sym("delta_dot")
action = ca.vertcat(jerk, delta_dot)
beta = ca.arctan(self.veh_cfg.lf * delta / self.veh_cfg.wheel_base)
xdot = v * ca.cos(heading + beta)
ydot = v * ca.sin(heading + beta)
vdot = a
adot = jerk
headingdot = v * ca.cos(beta) / self.veh_cfg.wheel_base * ca.tan(delta)
deltadot = delta_dot
statedot = ca.vertcat(xdot, ydot, headingdot, vdot, adot, deltadot)
self.f = ca.Function(
"f", [state, action], [statedot], ["state", "action"], ["statedot"]
)
state = ca.SX.sym("state", 6)
action = ca.SX.sym("action", 2)
dt = ca.SX.sym("dt", 1)
k1 = self.f(state=state, action=action)["statedot"]
k2 = self.f(state=state + dt * k1, action=action)["statedot"]
next_state = state + dt / 2 * (k1 + k2)
self.runge_kutta = ca.Function(
"runge_kutta",
[state, action, dt],
[next_state],
)
def generate_variable(self):
self.X = ca.SX.sym("X", self.n_states, self.N)
self.U = ca.SX.sym("U", self.n_actions, self.N - 1)
# self.DT = ca.SX.sym("DT", self.N - 1)
for i in range(self.N):
self.variables += [self.X[:, i]]
self.lbx += [
self.min_x,
self.min_y,
-ca.pi,
-self.veh_cfg.max_v,
-self.veh_cfg.max_acc,
-self.veh_cfg.max_front_wheel_angle,
]
self.ubx += [
self.max_x,
self.max_y,
ca.pi,
self.veh_cfg.max_v,
self.veh_cfg.max_acc,
self.veh_cfg.max_front_wheel_angle,
]
for i in range(self.N - 1):
self.variables += [self.U[:, i]]
self.lbx += [-self.veh_cfg.max_jerk, -self.veh_cfg.max_delta_dot]
self.ubx += [self.veh_cfg.max_jerk, self.veh_cfg.max_delta_dot]
for i in range(self.N):
for n_dual_variables in self.n_dual_variables_list:
# num_lines = len(obstacle.lines)
MU = ca.SX.sym("MU", n_dual_variables, 1)
self.variables += [MU]
self.MU_LIST += [MU]
self.lbx += [0.0, 0.0, 0.0, 0.0]
self.ubx += [1e6, 1e6, 1e6, 1e6]
LAMBDA = ca.SX.sym("LAMBDA", n_dual_variables, 1)
self.variables += [LAMBDA]
self.LAMBDA_list += [LAMBDA]
self.lbx += [0.0, 0.0, 0.0, 0.0]
self.ubx += [1e6, 1e6, 1e6, 1e6]
def generate_objective(self):
R = ca.SX(self.R)
Q = ca.SX(self.Q)
for i in range(self.N - 1):
state = self.X[:, i]
ref_state = self.x0[i]
error = state - ref_state
action = self.U[:, i]
self.obj += action.T @ R @ action
self.obj += error.T @ Q @ error
def generate_constraints(self):
self.constraints += [self.X[:, 0] - self.x0[0]]
self.lbg += [0, 0, 0, 0, 0, 0]
self.ubg += [0, 0, 0, 0, 0, 0]
for i in range(self.N - 1):
next_state = self.runge_kutta(self.X[:, i], self.U[:, i], self.DT)
self.constraints += [self.X[:, i + 1] - next_state]
self.lbg += [0, 0, 0, 0, 0, 0]
self.ubg += [0, 0, 0, 0, 0, 0]
self.constraints += [self.X[:, -1] - self.x0[self.N - 1]]
self.lbg += [0, 0, 0, 0, 0, 0]
self.ubg += [0, 0, 0, 0, 0, 0]
obstacle_number = len(self.obstacles)
for i in range(self.N):
index = 0
st = self.X[:, i]
heading = st[2]
x = st[0]
y = st[1]
t = ca.vertcat(
x + self.offset * ca.cos(heading), y + self.offset * ca.sin(heading)
)
rot = canp.array(
[
[ca.cos(heading), -ca.sin(heading)],
[ca.sin(heading), ca.cos(heading)],
]
)
for obstacle in self.obstacles:
A, b = get_polygon_halfspaces(obstacle)
lamb = ca.vertcat(self.LAMBDA_list[obstacle_number * i + index])
mu = ca.vertcat(self.MU_LIST[obstacle_number * i + index])
index += 1
self.constraints += [ca.dot(A.T @ lamb, A.T @ lamb)]
self.lbg += [0]
self.ubg += [1]
self.constraints += [self.G.T @ mu + (rot.T @ A.T) @ lamb]
self.lbg += [0, 0]
self.ubg += [0, 0]
self.constraints += [(-ca.dot(self.g, mu) + ca.dot(A @ t - b, lamb))]
self.lbg += [0.001]
self.ubg += [100000]
def solve(self):
if self.N == -1:
raise ValueError("Give optimizer a initial guess.")
self.build_model()
self.generate_variable()
self.generate_objective()
self.generate_constraints()
nlp_prob = {
"f": self.obj,
"x": ca.vertcat(*self.variables),
"g": ca.vertcat(*self.constraints),
}
# opts = {"print_time": True, "verbose": False, "ipopt.print_level": 0}
solver = ca.nlpsol("solver", "ipopt", nlp_prob, self.opti_cfg.solver_opts)
sol = solver(
x0=ca.vertcat(*self.x0),
lbx=self.lbx,
ubx=self.ubx,
lbg=self.lbg,
ubg=self.ubg,
)
solution = sol["x"]
self.x_opt = solution[0 : self.n_states * (self.N) : self.n_states]
self.y_opt = solution[1 : self.n_states * (self.N) : self.n_states]
self.theta_opt = solution[2 : self.n_states * (self.N) : self.n_states]
self.v_opt = solution[3 : self.n_states * (self.N) : self.n_states]
self.a_opt = solution[4 : self.n_states * (self.N) : self.n_states]
self.delta_opt = solution[5 : self.n_states * (self.N) : self.n_states]
self.j_opt = solution[
self.n_states * (self.N) : self.n_states * (self.N)
+ self.n_actions * (self.N - 1) : self.n_actions
]
self.deltadot_opt = solution[
self.n_states * (self.N)
+ 1 : self.n_states * (self.N)
+ self.n_actions * (self.N - 1) : self.n_actions
]
def extract_result(self, current_time: float = 0):
for i in range(self.N - 1):
x = float(self.x_opt[i])
y = float(self.y_opt[i])
h = float(self.theta_opt[i])
se2state = SE2State(x, y, h)
se2state.t = float(self.DT * i) + current_time
se2state.v = float(self.v_opt[i])
se2state.a = float(self.a_opt[i])
se2state.delta = float(self.delta_opt[i])
se2state.jerk = float(self.j_opt[i])
se2state.delta_dot = float(self.deltadot_opt[i])
self.se2trajectory += [se2state]
if len(self.se2trajectory) < 2:
raise ValueError("Solve Failed.")
return self.se2trajectory
TASK_NUM = 1
def test():
from settings import (
generate_obstacle_and_parking_polygon,
)
import matplotlib.pyplot as plt
import pickle
import utils
from search import upsample_smooth, downsample_smooth
from gridmap import GridMap, generate_gridmap_from_polygon
(
obstacle_polygon_list,
parking_polygon_list,
) = generate_obstacle_and_parking_polygon()
file_name = "se2path" + str(TASK_NUM) + ".pickle"
with open(file_name, "rb") as f:
path = pickle.load(f)
start_se2state = path[0]
goal_se2state = path[-1]
plt.figure(0, figsize=[8, 8])
utils.plot_task(obstacle_polygon_list, start_se2state, goal_se2state)
utils.plot_path(path, "searchpath")
plt.draw()
plt.pause(0.1)
us_path = upsample_smooth(path, 3)
utils.plot_path(us_path, "us_path")
plt.draw()
plt.pause(0.1)
gridmap = generate_gridmap_from_polygon(
obstacle_polygon_list, parking_polygon_list, start_se2state
)
opti = Optimizer()
opti.initialize(us_path, obstacle_polygon_list, gridmap)
opti.solve()
opti_path = opti.extract_result()
utils.plot_path(opti_path, "opti_path")
plt.draw()
plt.pause(0.1)
ds_opti_path = downsample_smooth(opti_path, 5)
utils.plot_trajectory_animation(ds_opti_path)
plt.draw()
plt.pause(0.1)
plt.figure(1, figsize=[8, 8])
utils.plot_control(opti_path)
plt.show()
# file_name = "se2opti_path" + str(TASK_NUM) + ".pickle"
# with open(file_name, "wb") as f:
# pickle.dump(opti_path, f)
if __name__ == "__main__":
test()