-
Notifications
You must be signed in to change notification settings - Fork 19
/
lqr.py
215 lines (159 loc) · 4.74 KB
/
lqr.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
"""
Linear-Quadratic Regulator sample code
author Atsushi Sakai
"""
import time
import matplotlib.pyplot as plt
import numpy as np
import scipy.linalg as la
simTime = 3.0
dt = 0.1
# x[k+1] = Ax[k] + Bu[k]
# A = np.matrix([[1, 1.0], [0, 1]])
# B = np.matrix([0.0, 1]).T
# Q = np.matrix([[1.0, 0.0], [0.0, 0.0]])
# R = np.matrix([[1.0]])
Kopt = None
def process(x, u):
x = A * x + B * u
return (x)
def solve_DARE_with_iteration(A, B, Q, R):
"""
solve a discrete time_Algebraic Riccati equation (DARE)
"""
X = Q
maxiter = 150
eps = 0.01
for i in range(maxiter):
Xn = A.T * X * A - A.T * X * B * \
la.inv(R + B.T * X * B) * B.T * X * A + Q
if (abs(Xn - X)).max() < eps:
X = Xn
break
X = Xn
return Xn
def dlqr_with_iteration(Ad, Bd, Q, R):
"""Solve the discrete time lqr controller.
x[k+1] = Ad x[k] + Bd u[k]
cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
# ref Bertsekas, p.151
"""
# first, try to solve the ricatti equation
X = solve_DARE_with_iteration(Ad, Bd, Q, R)
# compute the LQR gain
K = np.matrix(la.inv(Bd.T * X * Bd + R) * (Bd.T * X * Ad))
return K
def dlqr_with_arimoto_potter(Ad, Bd, Q, R):
"""Solve the discrete time lqr controller.
x[k+1] = Ad x[k] + Bd u[k]
cost = sum x[k].T*Q*x[k] + u[k].T*R*u[k]
# ref Bertsekas, p.151
"""
n = len(Bd)
# continuous
Ac = (Ad - np.eye(n)) / dt
Bc = Bd / dt
# Hamiltonian
Ham = np.vstack(
(np.hstack((Ac, - Bc * la.inv(R) * Bc.T)),
np.hstack((-Q, -Ac.T))))
eigVals, eigVecs = la.eig(Ham)
V1 = None
V2 = None
for i in range(2 * n):
if eigVals[i].real < 0:
if V1 is None:
V1 = eigVecs[0:n, i]
V2 = eigVecs[n:2 * n, i]
else:
V1 = np.vstack((V1, eigVecs[0:n, i]))
V2 = np.vstack((V2, eigVecs[n:2 * n, i]))
V1 = np.matrix(V1.T)
V2 = np.matrix(V2.T)
P = (V2 * la.inv(V1)).real
K = la.inv(R) * Bc.T * P
return K
def lqr_regulator_k(A,B,Q,R):
Kopt = dlqr_with_arimoto_potter(A, B, Q, R)
return Kopt
def lqr_regulator(x):
global Kopt
if Kopt is None:
start = time.time()
# Kopt = dlqr_with_iteration(A, B, np.eye(2), np.eye(1))
Kopt = dlqr_with_arimoto_potter(A, B, np.eye(2), np.eye(1))
elapsed_time = time.time() - start
print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
u = -Kopt * x
return u
def lqr_ref_tracking(x, xref, uref):
global Kopt
if Kopt is None:
# start = time.time()
# Kopt = dlqr_with_iteration(A, B, np.eye(2), np.eye(1))
Kopt = dlqr_with_arimoto_potter(A, B, Q, R)
# elapsed_time = time.time() - start
# print("elapsed_time:{0}".format(elapsed_time) + "[sec]")
u = -uref - Kopt * (x - xref)
return u
def main_regulator():
t = 0.0
x = np.matrix([3, 1]).T
u = np.matrix([0])
time_history = [0.0]
x1_history = [x[0, 0]]
x2_history = [x[1, 0]]
u_history = [0.0]
while t <= simTime:
u = lqr_regulator(x)
u0 = float(u[0, 0])
x = process(x, u0)
x1_history.append(x[0, 0])
x2_history.append(x[1, 0])
u_history.append(u0)
time_history.append(t)
t += dt
plt.plot(time_history, u_history, "-r", label="input")
plt.plot(time_history, x1_history, "-b", label="x1")
plt.plot(time_history, x2_history, "-g", label="x2")
plt.grid(True)
plt.xlim([0, simTime])
plt.title("LQR Regulator")
plt.legend()
plt.show()
def main_reference_tracking():
t = 0.0
x = np.matrix([3, 1]).T
u = np.matrix([0])
xref = np.matrix([1, 0]).T
uref = 0.0
time_history = [0.0]
x1_history = [x[0, 0]]
x2_history = [x[1, 0]]
u_history = [0.0]
while t <= simTime:
u = lqr_ref_tracking(x, xref, uref)
u0 = float(u[0, 0])
x = process(x, u0)
x1_history.append(x[0, 0])
x2_history.append(x[1, 0])
u_history.append(u0)
time_history.append(t)
t += dt
plt.plot(time_history, u_history, "-r", label="input")
plt.plot(time_history, x1_history, "-b", label="x1")
plt.plot(time_history, x2_history, "-g", label="x2")
xref0_h = [xref[0, 0] for i in range(len(time_history))]
xref1_h = [xref[1, 0] for i in range(len(time_history))]
plt.plot(time_history, xref0_h, "--b", label="target x1")
plt.plot(time_history, xref1_h, "--g", label="target x2")
plt.grid(True)
plt.xlim([0, simTime])
plt.title("LQR Tracking")
plt.legend()
plt.show()
if __name__ == '__main__':
print("Start")
# main_regulator()
main_reference_tracking()
print("Done")