Figure 2.5:

Closed-loop economic MPC versus tracking MPC starting at x=(-8,8) with optimal steady state (8,4). Both controllers asymptotically stabilize the steady state. Dashed contours show cost functions for each controller.

Figure 2.5

Code for Figure 2.5

Text of the GNU GPL.

main.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
# Compare economic vs. tracking mpc.
# [makes] econvstracking.mat

import numpy as np
import scipy.io as sio
import matplotlib.pyplot as plt
import mpctools as mpc
from scipy.linalg import solve_discrete_lyapunov
import os

Nx = 2
Ny = Nx
Nu = 1
hor = 50

N = {}
N['x'] = Nx
N['y'] = Ny
N['u'] = Nu
N['t'] = hor

# Linear model
A = np.array([[0.5, 1], [0, 0.75]])
B = np.array([[0], [1]])
f = mpc.getCasadiFunc(lambda x, u: A @ x + B @ u, [Nx, Nu], ['x', 'u'], 'f')

# Objective function
q = np.array([[-2], [2]])
r = -10 * np.eye(Nu)
lecon = mpc.getCasadiFunc(lambda x, u: q.T @ x + r @ u, [Nx, Nu], ['x', 'u'], 'lecon')

Q = np.array([[10, 0], [0, 10]])
R = np.array([[1]])
ltrack = mpc.getCasadiFunc(lambda x, u, x_sp, u_sp: (x - x_sp).T @ Q @ (x - x_sp) + (u - u_sp).T @ R @ (u - u_sp),
    [Nx, Nu, Nx, Nu], ['x', 'u', 'x_sp', 'u_sp'], 'ltrack')

# Bounds
lb, ub = {}, {}
lb['u'] = -np.ones(Nu)
ub['u'] = np.ones(Nu)
lb['x'] = np.ones(Nx) * -10
ub['x'] = np.ones(Nx) * 10


# Target finder
target = mpc.sstarg(f=f,
                    h=None,
                    l=lecon,
                    N=N,
                    lb=lb,
                    ub=ub,
                    verbosity=0,
                    inferargs=True)
target.solve()
xs = np.squeeze(target.var['x', 0])
us = np.squeeze(target.var['u', 0])
ls = target.obj

# Set-up controllers
init = {}
init['xs'] = xs
init['us'] = us

# Define equality constraint for terminal state xf
# NOTE: keep some wiggle room, may encounter solver problems otherwise
wiggle = 1e-5
lb['xf'] = xs * (1 - wiggle)
ub['xf'] = xs * (1 + wiggle)

econ = mpc.nmpc(f=f,
                l=lecon,
                N=N,
                lb=lb, ub=ub,
                verbosity=0,
                inferargs=True)

track = mpc.nmpc(f=f,
                l=ltrack,
                N=N,
                par={'xsp': xs, 'usp': us},
                lb=lb, ub=ub,
                verbosity=0,
                inferargs=True)

# Simulate both
Nsim = 25
x0 = np.array([-8, 8])
controllers = [econ, track]
names = ['econ', 'track']
data = {}
for i, controller in enumerate(controllers):
    print(f'Simulating {names[i]} MPC\n')
    x = np.zeros((Nx, Nsim + 1))
    x[:, 0] = x0 # Initial condition
    u = np.zeros((Nu, Nsim))
    for t in range(Nsim):
        controller.fixvar('x', 0, x[:, t])
        controller.solve()
        u[:, t] = np.squeeze(controller.var['u', 0])
        x[:, t + 1] = np.squeeze(controller.var['x', 1])
        controller.saveguess()
    data[names[i]] = {}
    data[names[i]]['x'] = x
    data[names[i]]['u'] = u

# get data for objective function contours
x1 = np.linspace(-10, 15, 251)
x2 = np.linspace(0, 10, 101)

xx1, xx2 = np.meshgrid(x1, x2)
dx1 = xx1 - xs[0]
dx2 = xx2 - xs[1]
Vecon = q[0] * dx1 + q[1] * dx2
Vtrack = Q[0, 0] * (dx1 ** 2) + 2 * Q[1, 0] * dx1 * dx2 + Q[1, 1] * (dx2 ** 2)
data['contours'] = {}
data['contours']['x1'] = x1
data['contours']['x2'] = x2
data['contours']['Vecon'] = Vecon
data['contours']['Vtrack'] = Vtrack

if not os.getenv('OMIT_PLOTS') == 'true':
    plt.figure()
    plt.contour(xx1, xx2, Vecon, levels=10)
    plt.contour(xx1, xx2, Vtrack, levels=10)
    colors = ['blue', 'red']
    for i, name in enumerate(names):
        plt.plot(data[name]['x'][0, :], data[name]['x'][1, :], '-o', color=colors[i], mfc='none')

    plt.xlabel(r'$x_1$')
    plt.ylabel(r'$x_2$', rotation=0)
    plt.show()

# Find rotated cost function
mu = -np.linalg.solve((np.eye(Nx) - A).T, q)
alpha = 0.01
Mu = solve_discrete_lyapunov(A.T, alpha * np.eye(Nx))

lam = lambda x: mu.T @ (x - xs) + (x - xs).T @ Mu @ (x - xs)

lrot = lambda x, u: q.T @ (x - xs) + r @ (u - us) + lam(x) - lam(A@x + B@u) - alpha * (x - xs).T @ (x - xs)

x1_vals = np.linspace(lb['x'][0], ub['x'][0], 21)
x2_vals = np.linspace(lb['x'][1], ub['x'][1], 21)
u_vals = np.linspace(lb['u'], ub['u'], 21)
x1, x2, u = np.meshgrid(x1_vals, x2_vals, u_vals, indexing='ij')
l = np.empty_like(x1)
for i in range(21):
    for j in range(21):
        for k in range(21):
            x = np.array([x1[i, j, k], x2[i, j, k]])
            l[i, j, k] = lrot(x, np.array([u[i, j, k]])).item()
print(f"Minimum of dissipation inequality: {l.min():.6g}")

# Simulate multiple economic MPC trajectories
econ.saveguess(default=True)
Nx0 = 16
colors = plt.cm.jet(np.linspace(0, 1, Nx0))
theta = np.linspace(0, 2 * np.pi, Nx0 + 1)[1:]
x0 = np.vstack((8 * np.cos(theta), 8 * np.sin(theta)))
Nsim = 21
x = np.full((Nx, Nsim, Nx0), np.nan)
u = np.full((Nu, Nsim, Nx0), np.nan)
V = np.full((Nsim, Nx0), np.nan)
if not os.getenv('OMIT_PLOTS') == 'true':
    fig, axs = plt.subplots(2, 2, figsize=(10, 6))
t = np.arange(Nsim)
print('Simulating more economic MPC', end='', flush=True)
for j in range(Nx0):
    x[:, 0, j] = x0[:, j]
    for i in range(Nsim):
        econ.fixvar('x', 0, x[:, i, j])
        econ.solve()
        if econ.stats['status'] != 'Solve_Succeeded':
            print(f'Controller failed at time {i} with controller status {econ.stats["status"]}')
            break
        u[:, i, j] = np.squeeze(econ.var['u', 0])
        V[i, j] = econ.obj + lam(x[:, i,j]).item() - N['t'] * ls
        if i < Nsim-1:
            x[:, i + 1, j] = np.squeeze(econ.var['x', 1])
    print('.', end='', flush=True)

    if not os.getenv('OMIT_PLOTS') == 'true':
        axs[0, 0].plot(t, x[0, :, j], color=colors[j])
        axs[0, 0].set_ylabel(r'$x_1$', rotation=0)

        axs[0, 1].plot(t, u[0, :, j], color=colors[j])
        axs[0, 1].set_ylabel(r'$u$', rotation=0)

        axs[1, 0].plot(t, x[1, :, j], color=colors[j])
        axs[1, 0].set_ylabel(r'$x_2$', rotation=0)
        axs[1, 0].set_xlabel('Time')

        axs[1, 1].plot(t, V[:Nsim, j], color=colors[j])
        axs[1, 1].set_ylabel(r'$V$', rotation=0)
        axs[1, 1].set_xlabel('Time')

if not os.getenv('OMIT_PLOTS') == 'true':
    plt.tight_layout()
    plt.show()

data['phase'] = {}
data['phase']['x'] = x
data['phase']['u'] = u
data['phase']['V'] = V