-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathLQR_planning.py
311 lines (210 loc) · 8.4 KB
/
LQR_planning.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
import math
import random
import matplotlib.pyplot as plt
import numpy as np
import scipy
import time
from CBFsteer import CBF_RRT
import env, plotting, utils
SHOW_ANIMATION = False
class LQRPlanner:
def __init__(self):
self.MAX_TIME = 100.0 # Maximum simulation time
self.DT = 0.05 # Time tick
self.GOAL_DIST = 0.1
self.MAX_ITER = 150
self.EPS = 0.01
# Linear system model
self.A, self.B = self.get_system_model()
# LQR gain is invariant
self.K = self.lqr_control(self.A, self.B)
# initialize CBF
self.env = env.Env()
self.obs_circle = self.env.obs_circle
self.obs_rectangle = self.env.obs_rectangle
self.obs_boundary = self.env.obs_boundary
self.cbf_rrt_simulation = CBF_RRT(self.obs_circle)
def lqr_planning(self, sx, sy, gx, gy, test_LQR = False, show_animation = True, cbf_check = True, solve_QP = False):
self.cbf_rrt_simulation.set_initial_state(np.array([[sx],[sy]]))
rx, ry = [sx], [sy]
error = []
u_sequence = []
x = np.array([sx - gx, sy - gy]).reshape(2, 1) # State vector
found_path = False
time = 0.0
while time <= self.MAX_TIME:
time += self.DT
u = self.K @ x
# check if LQR control is safe with respect to CBF constraint
if cbf_check and not test_LQR and not solve_QP:
if not self.cbf_rrt_simulation.QP_constraint([x[0, 0] + gx, x[1, 0] + gy],u):
print('CBF constraint violated')
break
u_sequence.append(u)
if solve_QP:
try:
u = self.cbf_rrt_simulation.QP_controller(x, u, model="linear")
except:
print('infeasible')
break
x = self.A @ x + self.B @ u
rx.append(x[0, 0] + gx)
ry.append(x[1, 0] + gy)
d = math.sqrt((gx - rx[-1]) ** 2 + (gy - ry[-1]) ** 2)
error.append(d)
if d <= self.GOAL_DIST:
found_path = True
# print('errors ', d)
break
# animation
if show_animation: # pragma: no cover
# for stopping simulation with the esc key.
plt.gcf().canvas.mpl_connect('key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plt.plot(sx, sy, "or")
plt.plot(gx, gy, "ob")
plt.plot(rx, ry, "-r")
plt.axis("equal")
plt.pause(1.0)
if not found_path:
return rx, ry, error,found_path, u_sequence
return rx, ry, error,found_path, u_sequence
def dlqr(self, A,B,Q,R):
"""
Solve the discrete time lqr controller.
x[k+1] = A x[k] + B u[k]
cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
"""
# first, solve the ricatti equation
P = np.matrix(scipy.linalg.solve_discrete_are(A, B, Q, R))
# compute the LQR gain
K = np.matrix(scipy.linalg.inv(B.T*P*B+R)*(B.T*P*A))
eigVals, eigVecs = scipy.linalg.eig(A-B*K)
return -K
def get_system_model(self):
A = np.matrix([[1, 0],[0 , 1]])
B = np.matrix([[self.DT, 0], [0, self.DT]])
return A, B
def lqr_control(self, A, B):
Q = np.matrix("1 0; 0 1")
R = np.matrix("0.01 0; 0 0.01")
Kopt = self.dlqr(A, B, Q, R)
return Kopt
class LQRPlanner_acceleration:
def __init__(self):
self.MAX_TIME = 100.0 # Maximum simulation time
self.DT = 0.05 # Time tick
self.GOAL_DIST = 0.1
self.MAX_ITER = 150
self.EPS = 0.01
# Linear system model
self.A, self.B = self.get_system_model()
# LQR gain is invariant
self.K = self.lqr_control(self.A, self.B)
# initialize CBF
self.env = env.Env()
self.obs_circle = self.env.obs_circle
self.obs_rectangle = self.env.obs_rectangle
self.obs_boundary = self.env.obs_boundary
self.cbf_rrt_simulation = CBF_RRT(self.obs_circle)
def lqr_planning(self, sx, sy, svx, svy, gx, gy, gvx, gvy, test_LQR = False, show_animation = True, cbf_check = True):
self.cbf_rrt_simulation.set_initial_state(np.array([[sx],[sy]]))
rx, ry, rvx, rvy = [sx], [sy], [svx], [svy]
error = []
u_sequence = []
x = np.array([sx - gx, sy - gy, svx - gvx, svy - gvy]).reshape(4, 1) # State vector
found_path = False
time = 0.0
while time <= self.MAX_TIME:
time += self.DT
u = self.K @ x
# check if LQR control is safe with respect to CBF constraint
if cbf_check and not test_LQR:
if not self.cbf_rrt_simulation.QP_constraint([x[0, 0] + gx, x[1, 0] + gy, x[2, 0] + gvx, x[3, 0] + gvy], u, system_type = "linear_acceleration_control"):
print("violation")
# exit(0)
break
u_sequence.append(u)
x = self.A @ x + self.B @ u
rx.append(x[0, 0] + gx)
ry.append(x[1, 0] + gy)
d = math.sqrt((gx - rx[-1]) ** 2 + (gy - ry[-1]) ** 2)
error.append(d)
if d <= self.GOAL_DIST:
found_path = True
# print('errors ', d)
break
# animation
if show_animation: # pragma: no cover
# for stopping simulation with the esc key.
plt.gcf().canvas.mpl_connect('key_release_event',
lambda event: [exit(0) if event.key == 'escape' else None])
plt.plot(sx, sy, "or")
plt.plot(gx, gy, "ob")
plt.plot(rx, ry, "-r")
plt.axis("equal")
plt.pause(1.0)
if not found_path:
#print("Cannot found path")
return rx, ry, error,found_path, u_sequence
return rx, ry, error,found_path, u_sequence
def dlqr(self, A,B,Q,R):
"""
Solve the discrete time lqr controller.
x[k+1] = A x[k] + B u[k]
cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
"""
# first, solve the ricatti equation
P = np.matrix(scipy.linalg.solve_discrete_are(A, B, Q, R))
# compute the LQR gain
K = np.matrix(scipy.linalg.inv(B.T*P*B+R)*(B.T*P*A))
eigVals, eigVecs = scipy.linalg.eig(A-B*K)
return -K
def get_system_model(self):
A = np.matrix([[1, 0, self.DT, 0],[0 , 1, 0, self.DT], [0, 0, 1, 0], [0, 0, 0, 1]])
B = np.matrix([[0, 0], [0, 0], [self.DT, 0], [0, self.DT]])
return A, B
def lqr_control(self, A, B):
Q = np.matrix("1 0 0 0; 0 1 0 0; 0 0 0.1 0; 0 0 0 0.1")
R = np.matrix("0.01 0; 0 0.01")
Kopt = self.dlqr(A, B, Q, R)
return Kopt
def main():
print(__file__ + " start!!")
ntest = 1 # number of goal
area = 50.0 # sampling area
acceleration_model = True
if not acceleration_model:
lqr_planner = LQRPlanner()
else:
lqr_planner = LQRPlanner_acceleration()
for i in range(ntest):
start_time = time.time()
sx = 6.0
sy = 6.0
gx = random.uniform(-area, area)
gy = random.uniform(-area, area)
print("goal", gy, gx)
if not acceleration_model:
rx, ry, error, foundpath, u_sequence = lqr_planner.lqr_planning(sx, sy, gx, gy, test_LQR = True, show_animation=SHOW_ANIMATION)
else:
svx, svy, gvx, gvy = 0, 0, 0, 0
rx, ry, error, foundpath, u_sequence = lqr_planner.lqr_planning(sx, sy, svx, svy, gx, gy, gvx, gvy, test_LQR = True, show_animation=SHOW_ANIMATION)
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
print("time of running LQR: ", time.time() - start_time)
ax1.plot(sx, sy, "or")
ax1.plot(gx, gy, "ob")
ax1.plot(rx, ry, "-r")
ax1.grid()
ax2.plot(error, label="errors")
ax2.legend(loc='upper right')
ax2.grid()
plt.show()
if SHOW_ANIMATION: # pragma: no cover
plt.plot(sx, sy, "or")
plt.plot(gx, gy, "ob")
plt.plot(rx, ry, "-r")
plt.axis("equal")
plt.pause(1.0)
if __name__ == '__main__':
main()