PANOC-ALM  quadratic-penalty
Nonconvex constrained optimization
bicycle-obstacle-avoidance-mpc.py
Go to the documentation of this file.
1 
3 
4 #%% Import necessary libraries and generate the MPC problem
5 
6 import casadi as cs
7 import numpy as np
8 import time
9 import matplotlib.pyplot as plt
10 from datetime import timedelta
11 import os
12 import sys
13 
14 sys.path.append(os.path.dirname(__file__))
15 
16 from bicycle_model import generate_problem
17 
18 Ts = 0.05 # Sampling time
19 N_hor = 18 # Horizon length
20 N_sim = 80 # Length of the simulation
21 
22 multipleshooting = False
23 R_obstacle = 2
24 
25 f, nlp, bounds, n_states, n_inputs, first_input_idx = generate_problem(
26  Ts, N_hor, R_obstacle, multipleshooting
27 )
28 
29 # %% Build the problem for PANOC+ALM
30 
31 import panocpy as pa
32 from tempfile import TemporaryDirectory
33 
34 name = "mpcproblem"
35 f_prob = cs.Function("f", [nlp["x"], nlp["p"]], [nlp["f"]])
36 g_prob = cs.Function("g", [nlp["x"], nlp["p"]], [nlp["g"]])
37 cgen, n, m, num_p = pa.generate_casadi_problem(f_prob, g_prob, name=name)
38 
39 with TemporaryDirectory(prefix="") as tmpdir:
40  cfile = cgen.generate(os.path.join(tmpdir, ''))
41  sofile = os.path.join(tmpdir, f"{name}.so")
42  os.system(f"cc -fPIC -shared -O3 -march=native {cfile} -o {sofile}")
43  print(sofile)
44  prob = pa.load_casadi_problem_with_param(sofile, n, m)
45 
46 prob.C.lowerbound = bounds["lbx"]
47 prob.C.upperbound = bounds["ubx"]
48 prob.D.lowerbound = bounds["lbg"]
49 prob.D.upperbound = bounds["ubg"]
50 
51 #%% PANOC params
52 
53 lbfgsmem = N_hor
54 tol = 1e-5
55 verbose = False
56 
57 panocparams = {
58  "max_iter": 1000,
59  "max_time": timedelta(seconds=0.5),
60  "print_interval": 10 if verbose else 0,
61  "stop_crit": pa.PANOCStopCrit.ProjGradUnitNorm,
62  "update_lipschitz_in_linesearch": True,
63 }
64 
65 innersolver = pa.PANOCSolver(
66  pa.PANOCParams(**panocparams),
67  pa.LBFGSParams(memory=lbfgsmem),
68 )
69 
70 almparams = pa.ALMParams(
71  max_iter=20,
72  max_time=timedelta(seconds=1),
73  print_interval=1 if verbose else 0,
74  preconditioning=False,
75  ε=tol,
76  δ=tol,
77  Δ=5,
78  Σ_0=4e5,
79  Σ_max=1e12,
80 )
81 
82 #%% Simulate MPC
83 
84 solver = pa.ALMSolver(almparams, innersolver)
85 
86 state = np.array([-5, 0, 0, 0])
87 dest = np.array([5, 0.1, 0, 0])
88 
89 if multipleshooting:
90  x_sol = np.concatenate((np.tile(state, N_hor), np.zeros((n_inputs * N_hor,))))
91 else:
92  x_sol = np.zeros((n,))
93 assert x_sol.size == n
94 y_sol = np.zeros((m,))
95 
96 
97 def solve_ocp(state, y_sol, x_sol):
98  state = np.reshape(state, (n_states,))
99  prob.param = np.concatenate((state, dest))
100  t0 = time.perf_counter()
101  x_sol, y_sol, stats = solver(problem=prob, x=x_sol, y=y_sol)
102  t1 = time.perf_counter()
103  return t1 - t0, stats, state, y_sol, x_sol
104 
105 
106 xs = np.zeros((N_sim, n_states))
107 times = np.zeros((N_sim,))
108 for k in range(N_sim):
109  t, stats, state, y_sol, x_sol = solve_ocp(state, y_sol, x_sol)
110  times[k] = t
111  xs[k] = state
112  print(
113  stats["status"],
114  stats["elapsed_time"],
115  stats["outer_iterations"],
116  stats["inner"]["iterations"],
117  )
118  input = x_sol[first_input_idx : first_input_idx + n_inputs]
119  state += Ts * f(state, input)
120 
121 #%% Plot
122 
123 fig_trajectory, ax = plt.subplots(1, 1)
124 c = plt.Circle((0, 0), R_obstacle)
125 ax.set_aspect(1)
126 ax.add_artist(c)
127 ax.plot(xs[:, 0], xs[:, 1], "r.-")
128 ax.set_title('Trajectory')
129 
130 fig_time, ax = plt.subplots(1, 1)
131 ax.plot(times)
132 ax.set_title("Run time")
133 ax.set_xlabel("MPC time step")
134 ax.set_ylabel("Run time [s]")
135 
136 plt.show()
137 
138 # %%
bicycle-obstacle-avoidance-mpc.f
f
Definition: bicycle-obstacle-avoidance-mpc.py:25
bicycle-obstacle-avoidance-mpc.solve_ocp
def solve_ocp(state, y_sol, x_sol)
Definition: bicycle-obstacle-avoidance-mpc.py:97
pa::ALMSolver
Augmented Lagrangian Method solver.
Definition: decl/alm.hpp:82
pa::PANOCParams
Tuning parameters for the PANOC algorithm.
Definition: inner/decl/panoc.hpp:20
bicycle-obstacle-avoidance-mpc.solver
solver
Definition: bicycle-obstacle-avoidance-mpc.py:84
pa::ALMParams
Parameters for the Augmented Lagrangian solver.
Definition: decl/alm.hpp:13
pa::LBFGSParams
Parameters for the LBFGS and SpecializedLBFGS classes.
Definition: decl/lbfgs.hpp:12
bicycle_model.generate_problem
def generate_problem(Ts, N_hor, R_obstacle, multipleshooting)
Definition: bicycle_model.py:148
pa::PANOCSolver
PANOC solver for ALM.
Definition: inner/decl/panoc.hpp:88