Repository navigation
Expand file tree
/
Copy pathmpc_controller.py
More file actions
170 lines (139 loc) · 4.67 KB
/
Copy pathmpc_controller.py
File metadata and controls
170 lines (139 loc) · 4.67 KB
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
import time
import casadi
import numpy as np
class MPCController:
"""Nonlinear MPC using CasADi multiple shooting with IPOPT.
The NLP is built entirely in CasADi SX for efficient exact Hessians.
"""
def __init__(self, model, f_dynamics, N=30, dt=0.02):
self.model = model
self.N = N
self.dt = dt
self.nq = model.nq
self.nv = model.nv
self.nx = self.nq + self.nv
self.nu = self.nq - 1
self.w_pend = 200.0
self.w_vel = 1.0
self.w_u = 0.01
self.w_terminal = 5.0
self._torque_limits = model.effortLimit[: self.nu]
self._build_nlp(f_dynamics)
self._warm_X = np.zeros((N + 1, self.nx))
self._warm_U = np.zeros((N, self.nu))
def _build_nlp(self, f_dynamics):
N, nx, nu = self.N, self.nx, self.nu
nq = self.nq
q_lb = self.model.lowerPositionLimit
q_ub = self.model.upperPositionLimit
v_max = self.model.velocityLimit
w = []
lbw = []
ubw = []
J = 0
g = []
x_init = casadi.MX.sym("x_init", nx)
X_vars = []
U_vars = []
for k in range(N + 1):
xk = casadi.MX.sym(f"X_{k}", nx)
w.append(xk)
X_vars.append(xk)
lbw += list(q_lb) + list(-v_max)
ubw += list(q_ub) + list(v_max)
if k < N:
uk = casadi.MX.sym(f"U_{k}", nu)
w.append(uk)
U_vars.append(uk)
lbw += list(-self._torque_limits)
ubw += list(self._torque_limits)
g.append(X_vars[0] - x_init)
for k in range(N):
xk, uk, xk1 = X_vars[k], U_vars[k], X_vars[k + 1]
g.append(xk1 - f_dynamics(xk, uk))
theta = xk[nq - 1]
v = xk[nq:]
wt = self.w_terminal if k == N - 1 else 1.0
J += wt * self.w_pend * theta ** 2
J += wt * self.w_vel * casadi.dot(v, v)
J += self.w_u * casadi.dot(uk, uk)
xN = X_vars[N]
J += self.w_terminal * self.w_pend * xN[nq - 1] ** 2
J += self.w_terminal * self.w_vel * casadi.dot(xN[nq:], xN[nq:])
w_flat = casadi.vertcat(*w)
g_flat = casadi.vertcat(*g)
n_g = g_flat.shape[0]
n_w = w_flat.shape[0]
nlp = {"f": J, "x": w_flat, "g": g_flat, "p": x_init}
opts = {
"ipopt.print_level": 0,
"ipopt.sb": "yes",
"print_time": 0,
"ipopt.warm_start_init_point": "yes",
"ipopt.max_iter": 200,
"ipopt.tol": 1e-4,
"ipopt.acceptable_tol": 1e-3,
"ipopt.linear_solver": "mumps",
"expand": True,
}
self._solver = casadi.nlpsol("mpc_solver", "ipopt", nlp, opts)
self._lbw = np.array(lbw)
self._ubw = np.array(ubw)
self._lbg = np.zeros(n_g)
self._ubg = np.zeros(n_g)
self._w0 = np.zeros(n_w)
self._nx = nx
self._nu = nu
self._n_vars = n_w
def solve(self, x_current):
"""Solve the MPC NLP and return the first optimal control input."""
w0 = self._pack_warm_start()
t0 = time.perf_counter()
sol = self._solver(
x0=w0,
lbx=self._lbw,
ubx=self._ubw,
lbg=self._lbg,
ubg=self._ubg,
p=x_current,
)
solve_time = (time.perf_counter() - t0) * 1000.0
w_opt = np.asarray(sol["x"]).flatten()
cost = float(sol["f"])
X_opt, U_opt = self._unpack_solution(w_opt)
self._shift_warm_start(X_opt, U_opt)
info = {
"solve_time_ms": solve_time,
"cost": cost,
"pendulum_angle": x_current[self.nq - 1],
}
return U_opt[0], info
def _pack_warm_start(self):
N, nx, nu = self.N, self._nx, self._nu
w = np.zeros(self._n_vars)
idx = 0
for k in range(N + 1):
w[idx : idx + nx] = self._warm_X[k]
idx += nx
if k < N:
w[idx : idx + nu] = self._warm_U[k]
idx += nu
return w
def _unpack_solution(self, w):
N, nx, nu = self.N, self._nx, self._nu
X = np.zeros((N + 1, nx))
U = np.zeros((N, nu))
idx = 0
for k in range(N + 1):
X[k] = w[idx : idx + nx]
idx += nx
if k < N:
U[k] = w[idx : idx + nu]
idx += nu
return X, U
def _shift_warm_start(self, X_opt, U_opt):
N = self.N
self._warm_X[:-1] = X_opt[1:]
self._warm_X[-1] = X_opt[-1]
self._warm_U[:-1] = U_opt[1:]
self._warm_U[-1] = U_opt[-1]