-
Notifications
You must be signed in to change notification settings - Fork 28
/
mpc_mlp_example.py
244 lines (190 loc) · 6.32 KB
/
mpc_mlp_example.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
import casadi as cs
import numpy as np
import torch
import l4casadi as l4c
from acados_template import AcadosSimSolver, AcadosOcpSolver, AcadosSim, AcadosOcp, AcadosModel
import time
import os
os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'
class PyTorchModel(torch.nn.Module):
def __init__(self):
super().__init__()
self.input_layer = torch.nn.Linear(2, 512)
hidden_layers = []
for i in range(5):
hidden_layers.append(torch.nn.Linear(512, 512))
self.hidden_layer = torch.nn.ModuleList(hidden_layers)
self.out_layer = torch.nn.Linear(512, 2)
# Model is not trained -- setting output to zero
with torch.no_grad():
self.out_layer.bias.fill_(0.)
self.out_layer.weight.fill_(0.)
def forward(self, x):
x = self.input_layer(x)
for layer in self.hidden_layer:
x = torch.tanh(layer(x))
x = self.out_layer(x)
return x
class DoubleIntegratorWithLearnedDynamics:
def __init__(self, learned_dyn):
self.learned_dyn = learned_dyn
def model(self):
s = cs.MX.sym('s', 1)
s_dot = cs.MX.sym('s_dot', 1)
s_dot_dot = cs.MX.sym('s_dot_dot', 1)
u = cs.MX.sym('u', 1)
x = cs.vertcat(s, s_dot)
x_dot = cs.vertcat(s_dot, s_dot_dot)
res_model = self.learned_dyn(x)
p = self.learned_dyn.get_sym_params()
parameter_values = self.learned_dyn.get_params(np.array([0, 0]))
f_expl = cs.vertcat(
s_dot,
u
) + res_model
x_start = np.zeros((2))
# store to struct
model = cs.types.SimpleNamespace()
model.x = x
model.xdot = x_dot
model.u = u
model.z = cs.vertcat([])
model.p = p
model.parameter_values = parameter_values
model.f_expl = f_expl
model.x_start = x_start
model.constraints = cs.vertcat([])
model.name = "wr"
return model
class MPC:
def __init__(self, model, N):
self.N = N
self.model = model
@property
def simulator(self):
return AcadosSimSolver(self.sim())
@property
def solver(self):
return AcadosOcpSolver(self.ocp())
def sim(self):
model = self.model
t_horizon = 1.
N = self.N
# Get model
model_ac = self.acados_model(model=model)
model_ac.p = model.p
# Dimensions
nx = 2
nu = 1
ny = 1
# Create OCP object to formulate the optimization
sim = AcadosSim()
sim.model = model_ac
sim.dims.N = N
sim.dims.nx = nx
sim.dims.nu = nu
sim.dims.ny = ny
sim.solver_options.tf = t_horizon
# Solver options
sim.solver_options.Tsim = 1./ 10.
sim.solver_options.qp_solver = 'FULL_CONDENSING_HPIPM'
sim.solver_options.hessian_approx = 'GAUSS_NEWTON'
sim.solver_options.integrator_type = 'ERK'
# ocp.solver_options.print_level = 0
sim.solver_options.nlp_solver_type = 'SQP_RTI'
return sim
def ocp(self):
model = self.model
t_horizon = 1.
N = self.N
# Get model
model_ac = self.acados_model(model=model)
model_ac.p = model.p
# Dimensions
nx = 2
nu = 1
ny = 1
# Create OCP object to formulate the optimization
ocp = AcadosOcp()
ocp.model = model_ac
ocp.dims.N = N
ocp.dims.nx = nx
ocp.dims.nu = nu
ocp.dims.ny = ny
ocp.solver_options.tf = t_horizon
# Initialize cost function
ocp.cost.cost_type = 'LINEAR_LS'
ocp.cost.cost_type_e = 'LINEAR_LS'
ocp.cost.W = np.array([[1.]])
ocp.cost.Vx = np.zeros((ny, nx))
ocp.cost.Vx[0, 0] = 1.
ocp.cost.Vu = np.zeros((ny, nu))
ocp.cost.Vz = np.array([[]])
ocp.cost.Vx_e = np.zeros((ny, nx))
ocp.cost.W_e = np.array([[0.]])
ocp.cost.yref_e = np.array([0.])
# Initial reference trajectory (will be overwritten)
ocp.cost.yref = np.zeros(1)
# Initial state (will be overwritten)
ocp.constraints.x0 = model.x_start
# Set constraints
a_max = 10
ocp.constraints.lbu = np.array([-a_max])
ocp.constraints.ubu = np.array([a_max])
ocp.constraints.idxbu = np.array([0])
# Solver options
ocp.solver_options.qp_solver = 'FULL_CONDENSING_HPIPM'
ocp.solver_options.hessian_approx = 'GAUSS_NEWTON'
ocp.solver_options.integrator_type = 'ERK'
ocp.solver_options.nlp_solver_type = 'SQP_RTI'
ocp.parameter_values = model.parameter_values
return ocp
def acados_model(self, model):
model_ac = AcadosModel()
model_ac.f_impl_expr = model.xdot - model.f_expl
model_ac.f_expl_expr = model.f_expl
model_ac.x = model.x
model_ac.xdot = model.xdot
model_ac.u = model.u
model_ac.name = model.name
return model_ac
def run():
N = 10
learned_dyn_model = l4c.realtime.RealTimeL4CasADi(PyTorchModel(), approximation_order=1)
model = DoubleIntegratorWithLearnedDynamics(learned_dyn_model)
solver = MPC(model=model.model(), N=N).solver
print('Warming up model...')
x_l = []
for i in range(N):
x_l.append(solver.get(i, "x"))
for i in range(20):
learned_dyn_model.get_params(np.stack(x_l, axis=0))
print('Warmed up!')
x = []
x_ref = []
ts = 1. / N
xt = np.array([1., 0.])
opt_times = []
for i in range(50):
now = time.time()
t = np.linspace(i * ts, i * ts + 1., 10)
yref = np.sin(0.5 * t + np.pi / 2)
x_ref.append(yref[0])
for t, ref in enumerate(yref):
solver.set(t, "yref", ref)
solver.set(0, "lbx", xt)
solver.set(0, "ubx", xt)
solver.solve()
xt = solver.get(1, "x")
x.append(xt)
x_l = []
for i in range(N):
x_l.append(solver.get(i, "x"))
params = learned_dyn_model.get_params(np.stack(x_l, axis=0))
for i in range(N):
solver.set(i, "p", params[i])
elapsed = time.time() - now
opt_times.append(elapsed)
print(f'Mean iteration time: {1000*np.mean(opt_times):.1f}ms -- {1/np.mean(opt_times):.0f}Hz)')
if __name__ == '__main__':
run()