Hanging Chain#

In this example, a mode predictive controller (MPC) is used to stabilize a system of weights connected by springs. The rightmost weight is fixed in place at the origin, whereas the velocity of the leftmost weight can be controlled by an actuator. The six weights in the middle move under the influence of gravity and the forces of the springs between them.

The goal of the controller is to stabilize the system (i.e. drive the velocity of all weights to zero) with the rightmost weight at position \((1, 0)\). Additionally, a non-convex cubic constraint on the weights’ position is imposed, shown in green on the figure below.

  1# %% Hanging chain MPC example
  2
  3import casadi as cs
  4import numpy as np
  5from os.path import dirname
  6import sys
  7
  8sys.path.append(dirname(__file__))
  9from hanging_chain_dynamics import HangingChain
 10
 11# %% Build the model
 12
 13Ts = 0.05  # Time step [s]
 14N = 6  # Number of balls
 15dim = 2  # Dimension (2D or 3D)
 16
 17model = HangingChain(N, dim, Ts)
 18y_null, u_null = model.initial_state()  # Initial states and control inputs
 19
 20param = [0.03, 1.6, 0.033 / N]  # Concrete parameters m, D, L
 21
 22# %% Apply an initial control input to disturb the system
 23
 24N_dist = 3  # Number of time steps to apply the disturbance for
 25u_dist = [-0.5, 0.5, 0.5] if dim == 3 else [-0.5, 0.5]  # Disturbance input
 26y_dist = model.simulate(N_dist, y_null, u_dist, param)  # Model states
 27y_dist = np.hstack((np.array([y_null]).T, y_dist))  # (including initial state)
 28
 29# %% Simulate the system without a controller
 30
 31N_sim = 180  # Number of time steps to simulate for
 32y_sim = model.simulate(N_sim, y_dist[:, -1], u_null, param)  # Model states
 33y_sim = np.hstack((y_dist, y_sim))  # (including disturbed and initial states)
 34
 35# %% Define MPC cost and constraints
 36
 37N_horiz = 12  # MPC horizon length (number of time steps)
 38
 39y_init = cs.MX.sym("y_init", *y_null.shape)  # Initial state
 40model_params = cs.MX.sym("params", *model.params.shape)  # Parameters
 41U = cs.MX.sym("U", dim * N_horiz)  # Control signals over horizon
 42U_mat = model.input_to_matrix(U)  # Input as dim by N_horiz matrix
 43constr_param = cs.MX.sym("c", 3)  # Coefficients of cubic constraint function
 44mpc_param = cs.vertcat(y_init, model_params, constr_param)  # All parameters
 45
 46# Cost
 47
 48# Stage costs for states and input
 49stage_y_cost, stage_u_cost = model.generate_cost_funcs()
 50# Simulate the model with the input over the horizon
 51mpc_sim = model.simulate(N_horiz, y_init, U_mat, model_params)
 52# Accumulate the cost of the outputs and inputs
 53mpc_y_cost = cs.sum2(stage_y_cost.map(N_horiz)(mpc_sim))
 54mpc_u_cost = cs.sum2(stage_u_cost.map(N_horiz)(U_mat))
 55mpc_cost_fun = cs.Function('f_mpc', [U, mpc_param], [mpc_y_cost + mpc_u_cost])
 56
 57# Constraints
 58
 59# Cubic constraint function for a single ball in one dimension
 60g_constr = lambda c, x: c[0] * x**3 + c[1] * x**2 + c[2] * x
 61# Constraint function for one stage (N balls)
 62y_c = cs.MX.sym("y_c", y_dist.shape[0])
 63constr = []
 64for i in range(N):  # for each ball in the stage except the last,
 65    yx_n = y_c[dim * i]  # constrain the x, y position of the ball
 66    yy_n = y_c[dim * i + dim - 1]
 67    constr += [yy_n - g_constr(constr_param, yx_n)]
 68constr += [y_c[-1] - g_constr(constr_param, y_c[-dim])]  # Ball N+1
 69constr_fun = cs.Function("c", [y_c, constr_param], [cs.vertcat(*constr)])
 70# Constraint function for all stages in the horizon
 71mpc_constr = constr_fun.map(N_horiz)(mpc_sim, constr_param)
 72mpc_constr_fun = cs.Function("g_mpc", [U, mpc_param], [cs.vec(mpc_constr)])
 73# Fill in the constraint coefficients c(x-a)³ + d(x-a) + b
 74a, b, c, d = 0.6, -1.4, 5, 2.2
 75constr_coeff = [c, -3 * a * c, 3 * a * a * c + d]
 76constr_lb = b - c * a**3 - d * a
 77
 78# %% NLP formulation
 79
 80import alpaqa.casadi_loader as cl
 81
 82# Generate C code for the cost and constraint function, compile them, and load
 83# them as an alpaqa problem description:
 84problem = cl.generate_and_compile_casadi_problem(
 85    f=mpc_cost_fun,
 86    g=mpc_constr_fun,
 87    sym=cs.MX.sym,
 88)
 89# Box constraints on actuator:
 90problem.C.lowerbound = -1 * np.ones((dim * N_horiz, ))
 91problem.C.upperbound = +1 * np.ones((dim * N_horiz, ))
 92# Constant term of the cubic state constraints:
 93problem.D.lowerbound = constr_lb * np.ones((problem.m, ))
 94
 95# %% NLP solver
 96
 97import alpaqa as pa
 98from datetime import timedelta
 99
100# Configure an alpaqa solver:
101solver = pa.ALMSolver(
102    alm_params={
103        'tolerance': 1e-4,
104        'dual_tolerance': 1e-4,
105        'initial_penalty': 1e4,
106        'max_iter': 100,
107        'max_time': timedelta(seconds=0.2),
108        'max_total_num_retries': 0,
109    },
110    inner_solver=pa.PANOCSolver(
111        panoc_params={
112            'stop_crit': pa.ProjGradNorm2,
113            'max_time': timedelta(seconds=0.02),
114        },
115        lbfgs_params={'memory': N_horiz},
116    ),
117)
118
119# %% MPC controller
120
121
122# Wrap the solver in a class that solves the optimal control problem at each
123# time step, implementing warm starting:
124class MPCController:
125
126    def __init__(self, model: HangingChain, problem: pa.CasADiProblem):
127        self.model = model
128        self.problem = problem
129        self.tot_it = 0
130        self.tot_time = timedelta()
131        self.max_time = timedelta()
132        self.failures = 0
133        self.U = np.zeros((N_horiz * dim, ))
134        self.λ = np.zeros(((N + 1) * N_horiz, ))
135
136    def __call__(self, y_n):
137        y_n = np.array(y_n).ravel()
138        # Set the current state as the initial state
139        self.problem.param[:y_n.shape[0]] = y_n
140        # Shift over the previous solution and Lagrange multipliers
141        self.U = np.concatenate((self.U[dim:], self.U[-dim:]))
142        self.λ = np.concatenate((self.λ[N + 1:], self.λ[-N - 1:]))
143        # Solve the optimal control problem
144        # (warm start using the shifted previous solution and multipliers)
145        self.U, self.λ, stats = solver(self.problem, self.U, self.λ)
146        # Print some solver statistics
147        print(stats['status'], stats['outer_iterations'],
148              stats['inner']['iterations'], stats['elapsed_time'],
149              stats['inner_convergence_failures'])
150        self.tot_it += stats['inner']['iterations']
151        self.failures += stats['status'] != pa.SolverStatus.Converged
152        self.tot_time += stats['elapsed_time']
153        self.max_time = max(self.max_time, stats['elapsed_time'])
154        # Print the Lagrange multipliers, shows that constraints are active
155        print(np.linalg.norm(self.λ))
156        # Return the optimal control signal for the first time step
157        return self.model.input_to_matrix(self.U)[:, 0]
158
159
160# %% Simulate the system using the MPC controller
161
162y_n = np.array(y_dist[:, -1]).ravel()  # Initial state for controller
163n_state = y_n.shape[0]
164problem.param = np.concatenate((y_n, param, constr_coeff))
165
166y_mpc = np.empty((n_state, N_sim))
167controller = MPCController(model, problem)
168for n in range(N_sim):
169    # Solve the optimal control problem:
170    u_n = controller(y_n)
171    # Apply the first optimal control input to the system and simulate for
172    # one time step, then update the state:
173    y_n = model.simulate(1, y_n, u_n, param).T
174    y_mpc[:, n] = y_n
175y_mpc = np.hstack((y_dist, y_mpc))
176
177print(f"{controller.tot_it} iterations, {controller.failures} failures")
178print(f"time: {controller.tot_time} (total), {controller.max_time} (max), "
179      f"{controller.tot_time / N_sim} (avg)")
180
181# %% Visualize the results
182
183import matplotlib.pyplot as plt
184import matplotlib as mpl
185from matplotlib import animation, patheffects
186
187mpl.rcParams['animation.frame_format'] = 'svg'
188
189# Plot the chains
190fig, ax = plt.subplots()
191x, y, z = model.state_to_pos(y_null)
192line, = ax.plot(x, y, '-o', label='Without MPC')
193line_ctrl, = ax.plot(x, y, '-o', label='With MPC')
194plt.legend()
195plt.ylim([-2.5, 1])
196plt.xlim([-0.25, 1.25])
197
198# Plot the state constraints
199x = np.linspace(-0.25, 1.25, 256)
200y = np.linspace(-2.5, 1, 256)
201X, Y = np.meshgrid(x, y)
202Z = g_constr(constr_coeff, X) + constr_lb - Y
203fx = [patheffects.withTickedStroke(spacing=7, linewidth=0.8)]
204cgc = plt.contour(X, Y, Z, [0], colors='tab:green', linewidths=0.8)
205plt.setp(cgc.collections, path_effects=fx)
206
207
208class Animation:
209    points = []
210
211    def __call__(self, i):
212        x, y, z = model.state_to_pos(y_sim[:, i])
213        for p in self.points:
214            p.remove()
215        self.points = []
216        line.set_xdata(x)
217        line.set_ydata(y)
218        viol = y - g_constr(constr_coeff, x) + 1e-5 < constr_lb
219        if np.sum(viol):
220            self.points += ax.plot(x[viol], y[viol], 'rx', markersize=12)
221        x, y, z = model.state_to_pos(y_mpc[:, i])
222        line_ctrl.set_xdata(x)
223        line_ctrl.set_ydata(y)
224        viol = y - g_constr(constr_coeff, x) + 1e-5 < constr_lb
225        if np.sum(viol):
226            self.points += ax.plot(x[viol], y[viol], 'rx', markersize=12)
227        return [line, line_ctrl] + self.points
228
229
230ani = animation.FuncAnimation(fig,
231                              Animation(),
232                              interval=1000 * Ts,
233                              blit=True,
234                              repeat=True,
235                              frames=1 + N_dist + N_sim)
236
237# Show the animation
238plt.show()

hanging_chain_dynamics.py

  1from typing import Union
  2import casadi as cs
  3import numpy as np
  4from casadi import vertcat as vc
  5
  6
  7class HangingChain:
  8
  9    def __init__(self, N: int, dim: int, Ts: float = 0.05):
 10        self.N = N
 11        self.dim = dim
 12
 13        self.y1 = cs.SX.sym("y1", dim * N, 1)  # state: balls 1→N positions
 14        self.y2 = cs.SX.sym("y2", dim * N, 1)  # state: balls 1→N velocities
 15        self.y3 = cs.SX.sym("y3", dim, 1)  # state: ball  1+N position
 16        self.u = cs.SX.sym("u", dim, 1)  # input: ball  1+N velocity
 17        self.y = vc(self.y1, self.y2, self.y3)  # full state vector
 18
 19        self.m = cs.SX.sym("m")  # mass
 20        self.D = cs.SX.sym("D")  # spring constant
 21        self.L = cs.SX.sym("L")  # spring length
 22        self.params = vc(self.m, self.D, self.L)
 23
 24        self.g = np.array([0, 0, -9.81] if dim == 3 else [0, -9.81])  # gravity
 25        self.x0 = np.zeros((dim, ))  # ball 0 position
 26        self.x_end = np.eye(1, dim, 0).ravel()  # ball N+1 reference position
 27
 28        self._build_dynamics(Ts)
 29
 30    def _build_dynamics(self, Ts):
 31        y, y1, y2, y3, u = self.y, self.y1, self.y2, self.y3, self.u
 32        dist = lambda xa, xb: cs.norm_2(xa - xb)
 33        N, d = self.N, self.dim
 34        p = self.params
 35
 36        # Continuous-time dynamics y' = f(y, u; p)
 37
 38        f1 = [y2]
 39        f2 = []
 40        for i in range(N):
 41            xi = y1[d * i:d * i + d]
 42            xip1 = y1[d * i + d:d * i + d * 2] if i < N - 1 else y3
 43            Fiip1 = self.D * (1 - self.L / dist(xip1, xi)) * (xip1 - xi)
 44            xim1 = y1[d * i - d:d * i] if i > 0 else self.x0
 45            Fim1i = self.D * (1 - self.L / dist(xi, xim1)) * (xi - xim1)
 46            fi = (Fiip1 - Fim1i) / self.m + self.g
 47            f2 += [fi]
 48        f3 = [u]
 49
 50        f_expr = vc(*f1, *f2, *f3)
 51        self.f = cs.Function("f", [y, u, p], [f_expr], ["y", "u", "p"], ["y'"])
 52
 53        # Discretize dynamics y[k+1] = f_d(y[k], u[k]; p)
 54
 55        # 4th order Runge-Kutta integrator
 56        k1 = self.f(y, u, p)
 57        k2 = self.f(y + Ts * k1 / 2, u, p)
 58        k3 = self.f(y + Ts * k2 / 2, u, p)
 59        k4 = self.f(y + Ts * k3, u, p)
 60
 61        # Discrete-time dynamics
 62        f_d_expr = y + (Ts / 6) * (k1 + 2 * k2 + 2 * k3 + k4)
 63        self.f_d = cs.Function("f", [y, u, p], [f_d_expr])
 64
 65        return self.f_d
 66
 67    def state_to_pos(self, y):
 68        N, d = self.N, self.dim
 69        rav = lambda x: np.array(x).ravel()
 70        xdim = lambda y, i: np.concatenate(
 71            ([0], rav(y[i:d * N:d]), rav(y[-d + i])))
 72        if d == 3:
 73            return (xdim(y, 0), xdim(y, 1), xdim(y, 2))
 74        else:
 75            return (xdim(y, 0), xdim(y, 1), np.zeros((N + 1, )))
 76
 77    def input_to_matrix(self, u):
 78        """
 79        Reshape the input signal from a vector into a dim × N_horiz matrix (note
 80        that CasADi matrices are stored column-wise and NumPy arrays row-wise)
 81        """
 82        if isinstance(u, np.ndarray):
 83            return u.reshape((self.dim, u.shape[0] // self.dim), order='F')
 84        else:
 85            return u.reshape((self.dim, u.shape[0] // self.dim))
 86
 87    def simulate(self, N_sim: int, y_0: np.ndarray,
 88                 u: Union[np.ndarray, list, cs.SX.sym, cs.MX.sym],
 89                 p: Union[np.ndarray, list, cs.SX.sym, cs.MX.sym]):
 90        if isinstance(u, list):
 91            u = np.array(u)
 92        if isinstance(u, np.ndarray):
 93            if u.ndim == 1 or (u.ndim == 2 and u.shape[1] == 1):
 94                if u.shape[0] == self.dim:
 95                    u = np.tile(u, (N_sim, 1)).T
 96        return self.f_d.mapaccum(N_sim)(y_0, u, p)
 97
 98    def initial_state(self):
 99        N, d = self.N, self.dim
100        y1_0 = np.zeros((d * N))
101        y1_0[0::d] = np.arange(1, N + 1) / (N + 1)
102        y2_0 = np.zeros((d * N))
103        y3_0 = np.zeros((d, ))
104        y3_0[0] = 1
105
106        y_null = np.concatenate((y1_0, y2_0, y3_0))
107        u_null = np.zeros((d, ))
108
109        return y_null, u_null
110
111    def generate_cost_funcs(self, α=25, β=1, γ=0.01):
112        N, d = self.N, self.dim
113        y1t = cs.SX.sym("y1t", d * N, 1)
114        y2t = cs.SX.sym("y2t", d * N, 1)
115        y3t = cs.SX.sym("y3t", d, 1)
116        ut = cs.SX.sym("ut", d, 1)
117        yt = cs.vertcat(y1t, y2t, y3t)
118
119        L_cost_x = α * cs.sumsqr(y3t - self.x_end)
120        for i in range(N):
121            xdi = y2t[d * i:d * i + d]
122            L_cost_x += β * cs.sumsqr(xdi)
123        L_cost_u = γ * cs.sumsqr(ut)
124        return cs.Function("L_cost_x", [yt], [L_cost_x]), \
125            cs.Function("L_cost_u", [ut], [L_cost_u])