Figure 7.8:

Solution times for explicit and implicit MPC for N = 20.

Figure 7.8

Code for Figure 7.8

Text of the GNU GPL.

solvempqp.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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import os
import numpy as np
from scipy import linalg
import matplotlib.pyplot as plt
from datetime import datetime
import time

from removeredundantcon import removeredundantcon
from findinteriorpoint import findinteriorpoint
from halfspace2vertex import halfspace2vertex

# Module-level log file (persistent state across calls).
_logfile = [None]

def log_(msg=None, *args):
    """Write to log. Pass a file object to open it; call with no args to close."""
    if hasattr(msg, 'write'):
        _logfile[0] = msg
    elif msg is None:
        if _logfile[0] is not None:
            _logfile[0].close()
            _logfile[0] = None
    elif _logfile[0] is not None:
        _logfile[0].write(msg % args if args else msg)
        _logfile[0].flush()


def viridiscolors(n):
    """Returns n colors from the viridis colormap as an (n, 3) RGB array."""
    cmap = plt.cm.get_cmap('viridis', n)
    return np.array([cmap(i)[:3] for i in range(n)])


def bin2hex(bits):
    """Converts a boolean vector to a hexadecimal string."""
    hexchars = '0123456789ABCDEF'
    bits = np.asarray(bits, dtype=float).flatten()
    Npad = (-len(bits)) % 4
    bits = np.concatenate([np.zeros(Npad), bits])
    Nhex = len(bits) // 4
    digits = np.array([8, 4, 2, 1]) @ bits.reshape(4, Nhex)
    return ''.join(hexchars[int(d)] for d in digits)


def getcrid(active):
    """Returns the string ID of the given set of active constraints."""
    return 'CR_' + bin2hex(active)


def scalerows(A, b, zerotol=1e-12):
    """Scales rows of [A, b] to unit norm; zeros trivial rows."""
    b = np.asarray(b, dtype=float).flatten()
    Z = np.hstack([A, b[:, None]])
    scale = np.sqrt(np.sum(Z**2, axis=1))
    trivrows = (scale == 0)
    scale[trivrows] = 1.0
    A = A / scale[:, None]
    b = b / scale
    b[trivrows] = 1.0
    A[np.abs(A) < zerotol] = 0.0
    return A, b, scale


def checkcrfullrank(dmpqp, activecon):
    """Checks whether the active-constraint submatrix of H is positive definite."""
    i = activecon
    Hii = dmpqp['H'][np.ix_(np.where(i)[0], np.where(i)[0])]
    if Hii.size == 0:
        return True, Hii
    try:
        Hiihalf = linalg.cholesky(Hii, lower=False)  # upper triangular
        fullrank = bool(np.all(np.diag(Hiihalf) > 1e-6))
    except linalg.LinAlgError:
        Hiihalf = np.zeros_like(Hii)
        fullrank = False
    return fullrank, Hiihalf


def getcriticalregion(pmpqp, dmpqp, crset):
    """Returns the critical region and optimal control law for a given active set."""
    activecon = crset['active']
    if 'Hiihalf' in crset:
        Hiihalf = crset['Hiihalf']
        okay = True
    else:
        okay, Hiihalf = checkcrfullrank(dmpqp, activecon)

    cr = {}
    if not okay:
        return cr, False

    i = activecon
    j = ~activecon
    i_idx = np.where(i)[0]
    j_idx = np.where(j)[0]

    # Solve for dual variable as affine function of parameters:
    # Y * [p; 1] = lambda*(p), using Hiihalf (upper Cholesky of H[i,i]).
    RHS = np.column_stack([dmpqp['D'][i_idx, :], dmpqp['d'][i_idx]])
    Y = -linalg.cho_solve((Hiihalf, False), RHS)  # (Ni, Np+1)

    # Complementary slackness for inactive constraints.
    W = dmpqp['H'][np.ix_(j_idx, i_idx)] @ Y + \
        np.column_stack([dmpqp['D'][j_idx, :], dmpqp['d'][j_idx]])  # (Nj, Np+1)

    P = np.vstack([W, Y])        # (Nj+Ni, Np+1)
    A = -P[:, :-1]               # critical region: A*p <= b
    b = P[:, -1]

    # Screen out near-zero rows.
    Anorms = np.max(np.abs(A), axis=1)
    badrows = (Anorms < 1e-10)
    if np.any(b[badrows] < 0):
        return cr, False
    A[badrows, :] = 0.0
    b[badrows] = 1.0

    # Append parameter bounding region.
    Ne = len(pmpqp['e'])
    A = np.vstack([A, pmpqp['E']])
    b = np.concatenate([b, pmpqp['e']])
    A, b, _ = scalerows(A, b)

    x, okay, _, _ = findinteriorpoint(A, b)
    if not okay:
        return cr, False

    cr['A'] = A
    cr['b'] = b
    cr['cind'] = np.concatenate([j_idx, i_idx, -np.arange(1, Ne + 1)]).astype(int)
    cr['ctype'] = np.array(['w'] * len(j_idx) + ['y'] * len(i_idx) + ['e'] * Ne)
    cr['x'] = np.asarray(x).flatten()

    # Optimal control law: z*(p) = Z*p + z0.
    G_i = pmpqp['G'][i_idx, :]
    inner = G_i.T @ Y + np.column_stack([pmpqp['F'], pmpqp['c']])  # (Nu, Np+1)
    law = -linalg.cho_solve((pmpqp['Qhalf'], False), inner)         # (Nu, Np+1)
    cr['Z'] = law[:, :-1]
    cr['z0'] = law[:, -1]

    return cr, True


def solveprimalqp(x, pmpqp):
    """Solves the primal QP at a given parameter value x."""
    from scipy.optimize import minimize
    Q = pmpqp['Q']
    f = (pmpqp['F'] @ np.asarray(x).flatten()).flatten()
    A_ineq = pmpqp['G']
    b_ineq = (pmpqp['S'] @ np.asarray(x).flatten() + pmpqp['W']).flatten()
    n = Q.shape[0]

    result = minimize(
        fun=lambda z: 0.5 * z @ Q @ z + f @ z,
        jac=lambda z: Q @ z + f,
        x0=np.zeros(n),
        method='SLSQP',
        constraints={'type': 'ineq',
                     'fun': lambda z: b_ineq - A_ineq @ z,
                     'jac': lambda z: -A_ineq},
        options={'ftol': 1e-10, 'maxiter': 500, 'disp': False},
    )
    z = result.x if result.success else np.full(n, np.nan)
    feas = result.success
    slack = A_ineq @ z - b_ineq
    active = np.abs(slack) < 1e-5
    return z, feas, slack, active


def addcr(opensets, nopen, newcr):
    """Adds a new candidate critical region to the open set."""
    nopen += 1
    opensets[f'N{nopen}'] = newcr
    log_(f"        Adding {newcr['id']}\n")
    return opensets, nopen


def findadjacentcr(cr, pmpqp):
    """Finds an adjacent CR by stepping across the given facet and solving the QP."""
    ineq = np.ones(cr['A'].shape[0], dtype=bool)
    ineq[cr['facet']] = False
    Aeq = cr['A'][[cr['facet']], :]
    beq = cr['b'][[cr['facet']]]
    x0, okay, _, _ = findinteriorpoint(cr['A'][ineq, :], cr['b'][ineq], Aeq, beq)
    if okay:
        normal = cr['A'][cr['facet'], :]
        x0p = np.asarray(x0).flatten() + 1e-4 * normal / np.linalg.norm(normal)
        _, feas, _, newactive = solveprimalqp(x0p, pmpqp)
    else:
        feas = False
        newactive = np.array([], dtype=bool)
    if not okay or not feas:
        newactive = np.array([], dtype=bool)
    return newactive, feas


def solvempqp(prob, **kwargs):
    """
    Solves the multiparametric QP:

        min  0.5*z'*Q*z + p'*C'*z
         z
        s.t. A*z <= b + S*p

    for all p satisfying E*p <= e.

    prob must contain Q, C, A, b, S. E and e are optional.
    """
    defaults = {
        'display': True,
        'logfile': '',
        'vertices': np.nan,
        'plot': False,
        'maxiter': np.inf,
        'ascell': True,
        'maxtime': np.inf,
        'printevery': 100,
    }
    options = {**defaults, **kwargs}

    if options['logfile']:
        log_(open(options['logfile'], 'w'))
    log_(f"Log started {datetime.now()}\n")

    # Convert to Bemporad (2015) nomenclature.
    pmpqp = {}
    pmpqp['G'] = np.asarray(prob['A'])
    pmpqp['W'] = np.asarray(prob['b']).flatten()
    pmpqp['S'] = np.asarray(prob['S'])
    pmpqp['Q'] = np.asarray(prob['Q'])
    pmpqp['Q'] = 0.5 * (pmpqp['Q'] + pmpqp['Q'].T)
    pmpqp['F'] = np.asarray(prob['C'])
    pmpqp['c'] = np.zeros(pmpqp['F'].shape[0])
    pmpqp['Qhalf'] = linalg.cholesky(pmpqp['Q'], lower=False)  # upper triangular

    pmpqp['E'] = np.asarray(prob.get('E', np.zeros((0, pmpqp['S'].shape[1]))))
    if pmpqp['E'].size == 0:
        pmpqp['e'] = np.zeros(0)
    else:
        if 'e' not in prob:
            raise ValueError('prob["e"] must be provided if prob["E"] is given!')
        pmpqp['e'] = np.asarray(prob['e']).flatten()

    if np.isnan(options['vertices']):
        options['vertices'] = (pmpqp['S'].shape[1] == 2)

    # Dual problem matrices.
    Qinv_G = linalg.cho_solve((pmpqp['Qhalf'], False), pmpqp['G'].T)  # Q^{-1} G'
    dmpqp = {}
    dmpqp['H'] = pmpqp['G'] @ Qinv_G
    dmpqp['D'] = pmpqp['G'] @ linalg.cho_solve((pmpqp['Qhalf'], False), pmpqp['F']) + pmpqp['S']
    dmpqp['d'] = pmpqp['G'] @ linalg.cho_solve((pmpqp['Qhalf'], False), pmpqp['c']) + pmpqp['W']

    # qhull options (passed as dict to ConvexHull via removeredundantcon).
    qhullstr = 'Qt QbB Pp'
    if pmpqp['S'].shape[1] >= 5:
        qhullstr += ' Qx'
    qhullopts = {'qhull_options': qhullstr}

    # Initialise: no constraints active at the origin.
    Ncon = dmpqp['D'].shape[0]
    init_active = np.zeros(Ncon, dtype=bool)
    opensets = {'N1': {'active': init_active, 'id': getcrid(init_active)}}
    nopen = 1
    nfound = 0
    regions = {}
    probedregions = {opensets['N1']['id']: []}

    niter = 0
    starttime = time.time()
    maxtime = options['maxtime'] + starttime

    while nopen > 0 and niter < options['maxiter'] and time.time() < maxtime:
        niter += 1
        if options['display'] and niter % options['printevery'] == 0:
            print(f"Iteration {niter} ({nfound} found, {nopen} left to search).")
        log_(f"Iteration {niter}\n")

        activestr = f'N{nopen}'
        nopen -= 1
        currentset = opensets.pop(activestr)
        crid = currentset['id']

        log_(f"    Getting {crid}\n")
        cr, okay = getcriticalregion(pmpqp, dmpqp, currentset)

        if okay:
            log_("    Found representation\n")
            nonredundant, cr['A'], cr['b'], _, _ = removeredundantcon(
                cr['A'], cr['b'], cr['x'], None, qhullopts)
            cr['cind'] = cr['cind'][nonredundant]
            cr['ctype'] = cr['ctype'][nonredundant]

            if options['vertices']:
                cr['V'], _ = halfspace2vertex(cr['A'], cr['b'], cr['x'])

            regions[crid] = cr
            nfound += 1

            log_("    Searching for adjacent regions\n")
            for k in range(len(nonredundant)):
                n = cr['cind'][k]
                newactive = currentset['active'].copy()

                tryqpsearch = True
                if cr['ctype'][k] == 'w':
                    newactive[n] = True
                elif cr['ctype'][k] == 'y':
                    newactive[n] = False
                    tryqpsearch = False
                else:
                    continue

                keepgoing = True
                while keepgoing:
                    newcrid = getcrid(newactive)
                    if newcrid not in probedregions:
                        probedregions[newcrid] = []
                        newfullrank, newHiihalf = checkcrfullrank(dmpqp, newactive)
                        if newfullrank:
                            newcr = {'active': newactive, 'id': newcrid,
                                     'Hiihalf': newHiihalf}
                            opensets, nopen = addcr(opensets, nopen, newcr)
                            keepgoing = False
                        else:
                            log_(f"        {newcrid} is not full-rank\n")
                            if tryqpsearch:
                                tryqpsearch = False
                                log_("        Trying QP neighbor search\n")
                                cr['facet'] = k
                                newactive, keepgoing = findadjacentcr(cr, pmpqp)
                                if not keepgoing:
                                    log_("        No neighbor found\n")
                            else:
                                keepgoing = False
                    else:
                        keepgoing = False
        else:
            log_(f"    {crid} is infeasible\n")

        log_(f"    {nopen} regions open\n")

    log_(f"Finished with {nopen} open regions\n")
    log_()

    if options['display']:
        elapsed = time.time() - starttime
        print(f"Found {nfound} regions ({nopen} left to search) after "
              f"{niter} iterations (in {elapsed:.1f} s).")

    # Optional plot.
    if options['plot'] and pmpqp['S'].shape[1] == 2 and not os.getenv('OMIT_PLOTS') == 'true':
        print("Making plot (may take some time).")
        plt.figure()
        fields = list(regions.keys())
        colors = viridiscolors(len(fields))
        cperm = np.argsort(np.sin(np.arange(1, len(fields) + 1)))
        colors = colors[cperm]
        for i, f in enumerate(fields):
            plt.fill(regions[f]['V'][:, 0], regions[f]['V'][:, 1],
                     color=colors[i])
        plt.xlabel('p_1')
        plt.ylabel('p_2', rotation=0)

    # Return as list (mimicking MATLAB cell array).
    if options['ascell']:
        result = []
        for f, r in regions.items():
            region = r.copy()
            region['id'] = f
            result.append(region)
        return result

    return regions

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
# Example explicit MPC for a 2D system From "Optimal control of constrained
# piecewise affine discrete-time systems" (Mayne and Rakovic, 2002).
# [depends] functions/solvempqp.py
# [makes] explicitvsimplicit.mat
## [rule] copymat
import os
import sys
import numpy as np
from scipy.linalg import solve_discrete_are
from scipy.optimize import minimize
import time
import matplotlib.pyplot as plt
from scipy.io import savemat

sys.path.append('functions/')

from findXn import findXn
from ss2mpqp import ss2mpqp
from solvempqp import solvempqp
from hyperrectangle import hyperrectangle

def _dlqr(A, B, Q, R):
    """Discrete-time LQR: returns (K, P) where u = K*x (negative gain)."""
    P = solve_discrete_are(A, B, Q, R)
    K = np.linalg.solve(R + B.T @ P @ B, B.T @ P @ A)
    return -K, P

# Choose system.
A = np.array([[1., 0.1], [0., 1.]])
B = np.array([[0.], [0.0787]])
Q = np.array([[1., 0.], [0., 0.]])
R = 0.1
ulb = np.array([-1.])
uub = np.array([1.])
xlb = -np.inf * np.ones(2)
xub = np.inf * np.ones(2)
N = 20
Nx, Nu = B.shape

# Find LQR terminal set.
K, P = _dlqr(A, B, Q, R)
Xn, Xnverts, _ = findXn(A, B, K, N, xlb, xub, ulb, uub, 'lqr', doplot=False)
A_lqr = Xn[0]['A']
b_lqr = Xn[0]['b']
feas = Xn[-1]   # X_N feasible set
feas['b'] = np.asarray(feas['b']).flatten()

# Get mpQP and solve.
mpqp, _ = ss2mpqp({'A': A, 'B': B, 'Q': Q, 'R': R, 'P': P, 'N': N,
                   'ulb': ulb, 'uub': uub, 'Af': A_lqr, 'bf': b_lqr})
regions = solvempqp(mpqp, plot=False)

def pwalookup(x, regions, feas=None):
    """Returns optimal first control z (or None if infeasible)."""
    z = None
    id_ = ''
    if feas is None or np.all(feas['A'] @ x - feas['b'] <= 0):
        for region in regions:
            if np.all(region['A'] @ x <= region['b']):
                z = region['Z'] @ x + region['z0']
                id_ = region['id']
                break
    return z, id_

def solve_qp(H, q, A_ineq, b_ineq):
    """Solve QP: min 0.5 z'Hz + q'z  s.t. A_ineq*z <= b_ineq."""
    H = 0.5 * (H + H.T)
    n = H.shape[0]
    res = minimize(
        fun=lambda z: 0.5 * z @ H @ z + q @ z,
        jac=lambda z: H @ z + q,
        x0=np.zeros(n),
        method='SLSQP',
        constraints={'type': 'ineq',
                     'fun': lambda z: b_ineq - A_ineq @ z,
                     'jac': lambda z: -A_ineq},
        options={'ftol': 1e-12, 'maxiter': 500, 'disp': False},
    )
    return res.x, res.success

# Sample feasible points and measure lookup vs QP times.
xbox = np.array([[-6., 6.], [-3., 3.]])
Npts = 10000
Nmax = 20000
xpts = np.full((Nx, Npts), np.nan)
lookuptimes = np.full(Npts, np.nan)
qptimes = np.full(Npts, np.nan)
jx = 0

np.random.seed(917)
for i in range(Nmax):
    xmin = xbox[:, 0]
    dx = xbox[:, 1] - xbox[:, 0]
    xtry = xmin + dx * np.random.rand(Nx)

    if np.all(feas['A'] @ xtry - feas['b'] <= 0):
        jx += 1
        if jx % 500 == 1:
            print(f'Point {jx} of {Npts}')

        xpts[:, jx - 1] = xtry

        # PWA lookup timing.
        t0 = time.perf_counter()
        zlookup, _ = pwalookup(xtry, regions, feas)
        lookuptimes[jx - 1] = time.perf_counter() - t0

        # QP solve timing.
        t0 = time.perf_counter()
        H_qp = mpqp['Q']
        q_qp = (mpqp['C'] @ xtry).flatten()
        A_qp = mpqp['A']
        b_qp = (mpqp['b'] + mpqp['S'] @ xtry).flatten()
        zqp, qp_ok = solve_qp(H_qp, q_qp, A_qp, b_qp)
        qptimes[jx - 1] = time.perf_counter() - t0

        if not qp_ok:
            print(f'QP failed at step {jx}!')

        if zlookup is not None and np.max(np.abs(zqp - zlookup)) > 1e-5:
            print(f'Warning: Mismatch for point {jx}!')

        if jx == Npts:
            break

print(f'Sampled {jx} points.')
xpts = xpts[:, :jx]
lookuptimes = 1000. * lookuptimes[:jx]   # convert to ms
qptimes = 1000. * qptimes[:jx]           # convert to ms

def kerneldensity(xsamples, sigma, x):
    """Gaussian kernel density estimate."""
    xsamples = xsamples.flatten()
    x = x.reshape(1, -1)
    den = np.sqrt(2 * np.pi) * sigma * len(xsamples)
    return np.sum(np.exp(-(x - xsamples.reshape(-1, 1))**2 / (2 * sigma**2)) / den, axis=0)

sig = 1.   # kernel width in ms
tplot = np.linspace(0, 100, 1001)

lookupdensity = kerneldensity(lookuptimes, sig, tplot)
qpdensity = kerneldensity(qptimes, sig, tplot)

if not os.getenv('OMIT_PLOTS') == 'true':
    plt.figure()
    plt.plot(tplot, lookupdensity, '-r', tplot, qpdensity, '-g')
    plt.legend(['Explicit', 'Implicit'], loc='upper right')
    plt.title(f'{xpts.shape[1]} Samples')
    plt.xlabel('Solution Time (ms)')
    plt.ylabel('Samples')