Algorithmresearch
Real-time iteration
Also called RTI scheme.
Solves nonlinear MPC by one sequential quadratic programming step per sample, with the expensive part prepared before the state is measured.
- Time
- O(N^3 m^2 n + N^2 n^2 m + N n^2 (n + m) + I N^3 m^3) worst
- Space
- O(N^2 m (n + m)) extra
- Where
- I = the number of active set iterations of the QP; N = the number of shooting intervals; m = the number of inputs; n = the number of states
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Moritz Diehl, Hans Georg Bock, Johannes P. Schlöder, 2005
The real-time iteration (RTI) is a way to run nonlinear MPC fast enough for a real plant. Exact nonlinear MPC solves a nonlinear program to convergence at every sample, which takes several iterations and causes a delay. The RTI does only one Gauss-Newton step of sequential quadratic programming per sample, and it starts each step from the shifted solution of the previous sample. The step is split into two phases. The preparation phase integrates the model, computes the derivatives and condenses the problem into a small quadratic program, all before the new state is known. The feedback phase starts when the state is measured and only solves that quadratic program. So the delay between the measurement and the input is the time of one small QP, and the controller follows the exact nonlinear MPC solution closely as the plant moves.
In plain words
A full nonlinear plan is too slow to compute again from the start at every moment. So keep the plan from the last moment, slide it one step forward, and improve it a little each time instead of solving it completely. Most of the work for that improvement does not need the newest measurement, so do it while you wait. When the measurement comes, only a small and fast correction is left, and the input goes out almost at once. Because the plan changes only a little between two moments, one improvement per moment is usually enough to stay close to the best plan.
The problem
Input: a model with twice continuously differentiable and its Jacobians, a sample time , a horizon of intervals, weights and symmetric positive semidefinite and symmetric positive definite, an input bound , an initial guess of nodes and controls , and a stream of measured states.
At each sample with measured state , the nonlinear MPC problem in multiple shooting form is
where is one Runge-Kutta 4 step of length .
Output: at each sample, an input within the bounds, with the least possible delay after the measurement.
The algorithm
RTI(f, h, N, Q, R, P, ū, s, q)- 1
for each sample do - 2
for k = 0, ..., N-1: (F_k, A_k, B_k) ← RK4 step at (s_k, q_k) with derivatives; c_k ← F_k - s_{k+1} ▷ prepare - 3
condense: Δs_k = M_k Δs₀ + Γ_k Δq + d_k, and from it H, g, G of the QP ▷ prepare - 4
measure x₀; Δs₀ ← x₀ - s₀ ▷ feedback - 5
Δq ← argmin ½ Δqᵀ H Δq + (g + G Δs₀)ᵀ Δq subject to -ū ≤ q + Δq ≤ ū - 6
apply u = q₀ + Δq₀ - 7
Δs_{k+1} ← A_k Δs_k + B_k Δq_k + c_k; s ← s + Δs; q ← q + Δq - 8
shift s and q by one interval and repeat the last node and control
Line L2 integrates each shooting interval with one RK4 step and propagates the derivatives through the four stages by the chain rule, so and are the exact Jacobians of the discrete map. The gaps are the defects of the multiple shooting guess. They need not be zero during the iteration.
Line L3 eliminates the node variables. With , and , the recursion , , and with block column replaced by , gives the node steps as a linear function of and . With for and , the condensed data are , and . None of this uses the measured state.
Line L4 is the initial value embedding: the measured state enters the QP only through the linear constraint , so it changes only the gradient .
Line L5 solves a QP with a positive definite Hessian and box constraints. The implementation uses a primal active set method, which is warm-started cheaply in practice.
Line L8 makes the result of this sample the guess for the next one. The shifted guess is close to the next solution when the plant moves as predicted.
Example
Take the inverted pendulum with state , upright at . Without input it falls: from the angle is after 2 seconds and after 3 seconds. Use , , , , and the zero initial guess.
The exact problem. From with , iterating the Gauss-Newton step at the same state gives:
| iteration | largest control step | largest gap | cost of the simulated controls |
|---|---|---|---|
| 1 | 10 | 0.188 | 866.58 |
| 2 | 3.71 | 8.7e-4 | 398.881 |
| 3 | 0.0134 | 2.0e-8 | 398.873 |
| 4 | 5.8e-5 | 6e-13 | 398.873 |
| 5 | 3.2e-7 | below 1e-15 | 398.873 |
The steps shrink by a roughly constant factor, which is the linear convergence of Gauss-Newton. The gaps close much faster.
The RTI loop. From with , exact nonlinear MPC needs 5 iterations at the first sample and 3 or 4 at the later samples. The RTI does one at each sample. Its first input is , against for the converged solution. Compare the two at the same states, along the RTI trajectory:
| sample | 0 | 1 | 2 and later |
|---|---|---|---|
| difference from the converged input | 0.144 | 2.8e-5 | below 1e-6 |
Only the first sample, which starts from the poor zero guess, shows a visible error. After that, the shifted guess is so good that one step is enough. The state is below after 20 samples.
Saturation. With from , the input stays at for the first 12 samples or more, the box QP keeps every input within its bound, and the state is below after 35 samples. The RTI inputs agree with the converged ones within after 10 samples.
Correctness
The proof is in proofs/correctness.md. The RK4 derivatives are exact by the chain rule through the four stages. By induction over the intervals, the condensed QP has the same cost as the linearized multiple shooting problem, for every and . The box QP solver returns only at a point that meets the KKT conditions, and the Hessian is positive definite, so it returns the unique solution. So each sample performs one exact Gauss-Newton SQP step. If the step is zero at some guess, the guess has no gaps, its nodes are the simulated trajectory, and its controls meet the KKT conditions of the nonlinear MPC problem. How close the RTI stays to the exact solution along the closed loop depends on the contraction of the Gauss-Newton step and on how far the plant moves between samples. Diehl, Bock and Schlöder (2005) give the contraction analysis and Diehl and coauthors (2005) the nominal stability of the closed loop. These results are cited and not proved here.
Proof: Each sample of the code performs one exact Gauss-Newton SQP step of the multiple shooting problem, and its fixed points are KKT pointsfull
Setting. The discrete model is , one Runge-Kutta 4 step of length for with twice continuously differentiable. The optimal control problem for the measured state is
with , symmetric positive semidefinite and symmetric positive definite. The cost is quadratic in , so its Hessian is constant. The Gauss-Newton SQP step at a guess keeps this cost and replaces each constraint by its linearization, which drops the curvature of the constraints from the Hessian of the Lagrangian:
with , at and the gaps . The new guess is .
Part 1: the derivatives of the RK4 step
Lemma 1. rk4 returns and its exact Jacobians and .
Proof. The RK4 step is , , , , . Let be the point at which is evaluated. By the chain rule,
with , , and for . The loop in rk4 computes exactly these matrices in this order (dxs, dus, kx, ku), and then and with .
Part 2: condensing
Lemma 2. For every and , the solution of the recursion in (QP) is , where , , , , , and equals except that its block column is .
Proof. By induction. At it holds. If it holds at , then . Block column of is 0 (inputs at step or later do not affect ), so adding sets that block column to .
Lemma 3. With for , , and , the cost of (QP) as a function of is
with , and . These are the quantities that prepare returns, and they do not depend on .
Proof. By Lemma 2, . Expanding gives , using . Expanding gives . Summing and collecting the terms that are linear in gives .
is positive definite, since is, so the condensed QP has a unique solution. Its feasible set is the box , which is what feedback passes to box_qp, and its gradient uses the measured state only through .
Part 3: the box QP
Lemma 4. If box_qp returns , then is the unique minimizer of over .
Proof. The iterate is feasible at all times: it starts at the projection of 0 onto the box, a step moves only the free variables and is cut at the first bound that it would cross (that variable is then fixed at its bound), and removing a variable from the working set does not move it. The method returns only when the step on the free set is zero, so the free variables minimize the objective with the fixed variables held, which means for every free . It also checks that for every variable at its lower bound and for every variable at its upper bound. These are the KKT conditions of the box QP, with multipliers . The problem is convex, so KKT points are minimizers, and the minimizer is unique because is positive definite.
The method is the primal active set method for a strictly convex QP, which ends after finitely many steps when no step has length zero for ever; the code stops with an error after max_iter iterations in any case.
Part 4: one sample
Theorem 1. prepare followed by feedback returns the exact Gauss-Newton SQP step of (NLP) at for the measured : the new controls with the solution of (QP), the new nodes from the recursion of (QP), and the first control .
Proof. Lemma 1 gives , and (line L2). Lemma 2 and Lemma 3 show that (QP), after the substitution of , is the condensed QP with data , and the box (lines L3 to L5). Lemma 4 shows that box_qp solves it. Line L6 returns . Line L7 runs the recursion of (QP) from , so the new is , and the new nodes are .
Theorem 2. If is a fixed point of the step for , that is and , then is a KKT point of the reduced problem subject to , where is the cost of the trajectory simulated from , and is that trajectory.
Proof. gives . With and , the recursion gives for all , so and is the trajectory of from . The map from to the simulated trajectory is differentiable, and by the chain rule its derivative at is of Lemma 2 (with and , is the linearized trajectory). So the gradient of at is the derivative at of the cost of Lemma 3, which is . Since solves the box QP, it meets its KKT conditions at 0 with gradient ; these are exactly the KKT conditions of over the box at .
So iterating the step at a fixed (solve_nmpc) converges, when it converges, to a KKT point of (NLP). The RTI does not iterate: line L8 shifts the result and uses it as the guess for the next sample. How close the RTI inputs stay to the exact NMPC inputs is a question of contraction of the Gauss-Newton step together with the motion of the plant; Diehl, Bock and Schlöder (2005) give its contraction analysis, and Diehl, Findeisen, Allgöwer, Bock and Schlöder (2005) give conditions under which the closed loop of the RTI is stable. That analysis is not reproduced here.
Part 5: what the code computes
- Line L1 is the loop over the samples in
rti_loop. - Line L2 integrates each interval with its sensitivities (Lemma 1) and forms the gaps.
- Line L3 condenses (Lemmas 2 and 3). Lines L2 and L3 make up the preparation phase and use only .
- Lines L4 to L6 are the feedback phase: , the box QP, and the first control.
- Line L7 expands the solution to the new nodes.
- Line L8 shifts the nodes and controls by one interval for the next sample.
Complexity
The preparation phase does RK4 steps with derivatives, for dense Jacobians, and dense condensing. Building all costs , and forming from them . The feedback phase solves the box QP with variables, and each active set iteration solves a dense system in . Condensed storage is . Variants that keep the sparse structure and use a Riccati recursion bring both phases down to linear in . The main gain is not the operation count but the delay: only the QP lies between the measurement and the input.
Properties
- One SQP step per sample, always the same amount of work, so the timing is predictable.
- Small feedback delay, since the integration, the derivatives and the condensing are done before the measurement.
- Exact Gauss-Newton step for a least squares cost, with no Hessian of the model.
- Initial value embedding. The measured state enters linearly, so the feedback is a linear prediction of the exact solution even when the guess was prepared for a different state. From a converged guess the prediction is first-order correct with an exact Hessian; the Gauss-Newton Hessian drops the curvature of the model, so with it the prediction has a first-order error that is small when that curvature or its multipliers are small.
- Approximate. The input is not the exact solution of the nonlinear program. The error is small when the guess is good and the sampling is fast compared to the plant.
- Fixed points are KKT points. If the iteration stands still, it stands at a KKT point of the nonlinear MPC problem.
Variants and improvements
- Sparse QP. Keep the node variables and solve the QP with a structure-exploiting solver, for long horizons or many states.
- Inexact sensitivities. Reuse old Jacobians and correct only the gradient, which makes the preparation cheaper.
- Several iterations. When time allows, do more than one SQP step per sample, which moves toward exact nonlinear MPC.
- General Hessians. For costs that are not least squares, use an exact or quasi-Newton Hessian of the Lagrangian, with a regularization to keep the QP convex.
- Estimation. The same idea runs moving horizon estimation, with one Gauss-Newton step per sample.
- Code generation. Toolkits such as ACADO Code Generation and acados generate the RTI as plain C code for embedded processors.
When to use it
Use the RTI when a nonlinear model is needed and the sample time is short, for example in vehicles, drones, robots or engines. It is the standard method for embedded nonlinear MPC. It assumes that the guess from the last sample is good, so the sample time must be short compared to the time in which the plant changes. When the plant can change abruptly, for example after a large disturbance, more iterations or a globalization strategy are needed. For a linear model, plain linear MPC or explicit MPC is simpler.
Pitfalls
- A poor first guess. The first sample starts from whatever guess is given, and one step may not be enough. In the example the first input is off by 0.144. Warm-start from a simulation, or iterate to convergence at the first sample.
- No globalization. The full step is taken without a line search. Far from the solution the step can make things worse.
- Using the state too early. Anything that uses the measured state belongs to the feedback phase. If the preparation uses it, the delay comes back.
- Wrong derivatives. The method needs the exact Jacobians of the discrete map, not of the continuous model. Check them against finite differences.
- Indefinite Hessians. The Gauss-Newton Hessian is positive semidefinite only for a least squares cost. With other costs, the QP can be nonconvex.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/real-time-iteration/. The authors are listed in prov/RM47HC.jsonl.
"""The real-time iteration (RTI) for nonlinear MPC.
The model is x' = f(x, u), discretized by one Runge-Kutta 4 step of length h
per shooting interval. The optimal control problem is
min sum_(k < N) (x_k' Q x_k + u_k' R u_k) + x_N' P x_N
s.t. x_0 = measured state, x_(k+1) = F(x_k, u_k), |u_k| <= u_max,
in multiple shooting form with nodes s_0..s_N and controls q_0..q_(N-1).
The cost is a sum of squares, so the Gauss-Newton Hessian is exact for it.
Each sample does one Gauss-Newton SQP step: the preparation phase
linearizes and condenses before x_0 is known, and the feedback phase solves
one box-constrained QP when x_0 arrives.
A model is a tuple (f, fx, fu) of the right side and its Jacobians. Matrices
are lists of rows and vectors flat lists.
"""
import math
__all__ = ["PENDULUM", "rk4", "box_qp", "prepare", "feedback", "shift", "rti_loop", "solve_nmpc",
"simulate_cost"]
def _f_pend(x, u):
return [x[1], math.sin(x[0]) + u[0]]
def _fx_pend(x, u):
return [[0.0, 1.0], [math.cos(x[0]), 0.0]]
def _fu_pend(x, u):
return [[0.0], [1.0]]
# The inverted pendulum theta'' = sin(theta) + u, upright at theta = 0.
PENDULUM = (_f_pend, _fx_pend, _fu_pend)
def _mm(A, B):
return [[sum(A[i][k] * B[k][j] for k in range(len(B))) for j in range(len(B[0]))] for i in range(len(A))]
def _mv(A, x):
return [sum(a * b for a, b in zip(row, x)) for row in A]
def _madd(A, B, s=1.0):
return [[a + s * b for a, b in zip(ra, rb)] for ra, rb in zip(A, B)]
def _tr(A):
return [list(r) for r in zip(*A)]
def _solve(A, b):
"""Solve A x = b by Gaussian elimination with partial pivoting."""
n = len(A)
M = [list(A[i]) + [b[i]] for i in range(n)]
for c in range(n):
p = max(range(c, n), key=lambda r: abs(M[r][c]))
M[c], M[p] = M[p], M[c]
for r in range(c + 1, n):
f = M[r][c] / M[c][c]
if f:
M[r] = [x - f * y for x, y in zip(M[r], M[c])]
x = [0.0] * n
for i in range(n - 1, -1, -1):
x[i] = (M[i][n] - sum(M[i][j] * x[j] for j in range(i + 1, n))) / M[i][i]
return x
def rk4(model, x, u, h):
"""One RK4 step and its exact derivatives: returns (x_next, A, B)."""
f, fx, fu = model
n, m = len(x), len(u)
eye = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
zero_u = [[0.0] * m for _ in range(n)]
ks, kxs, kus = [], [], []
xs, dxs, dus = x, eye, zero_u
for c in (0.5, 0.5, 1.0, None):
k = f(xs, u)
J = fx(xs, u)
kx = _mm(J, dxs)
ku = _madd(_mm(J, dus), fu(xs, u))
ks.append(k)
kxs.append(kx)
kus.append(ku)
if c is not None:
xs = [a + c * h * b for a, b in zip(x, k)]
dxs = _madd(eye, kx, c * h)
dus = [[c * h * v for v in r] for r in ku]
w = (1.0, 2.0, 2.0, 1.0)
xn = [x[i] + h / 6 * sum(wj * k[i] for wj, k in zip(w, ks)) for i in range(n)]
A = [[eye[i][j] + h / 6 * sum(wj * kx[i][j] for wj, kx in zip(w, kxs)) for j in range(n)] for i in range(n)]
B = [[h / 6 * sum(wj * ku[i][j] for wj, ku in zip(w, kus)) for j in range(m)] for i in range(n)]
return xn, A, B
def box_qp(H, g, lo, hi, tol=1e-12, max_iter=500):
"""Minimize 0.5 x'Hx + g'x subject to lo <= x <= hi, for H positive definite (primal active set)."""
n = len(g)
x = [min(hi[i], max(lo[i], 0.0)) for i in range(n)]
bound = {i: (lo[i] if x[i] == lo[i] else hi[i]) for i in range(n) if x[i] in (lo[i], hi[i])}
for _ in range(max_iter):
free = [i for i in range(n) if i not in bound]
xf = [x[i] for i in free]
if free:
rhs = [-(g[i] + sum(H[i][j] * x[j] for j in bound)) for i in free]
target = _solve([[H[i][j] for j in free] for i in free], rhs)
else:
target = []
p = [t - v for t, v in zip(target, xf)]
if max((abs(v) for v in p), default=0.0) <= tol * (1 + max((abs(v) for v in xf), default=0.0)):
grad = [sum(H[i][j] * x[j] for j in range(n)) + g[i] for i in range(n)]
# Multiplier of a lower bound is grad_i, of an upper bound -grad_i; both must be >= 0.
worst, wi = -tol, None
for i, b in bound.items():
lam = grad[i] if b == lo[i] else -grad[i]
if lam < worst:
worst, wi = lam, i
if wi is None:
return x
del bound[wi]
continue
alpha, block = 1.0, None
for k, i in enumerate(free):
if p[k] > 0 and xf[k] + p[k] > hi[i]:
a = (hi[i] - xf[k]) / p[k]
if a < alpha:
alpha, block = a, (i, hi[i])
elif p[k] < 0 and xf[k] + p[k] < lo[i]:
a = (lo[i] - xf[k]) / p[k]
if a < alpha:
alpha, block = a, (i, lo[i])
for k, i in enumerate(free):
x[i] = xf[k] + alpha * p[k]
if block is not None:
x[block[0]] = block[1]
bound[block[0]] = block[1]
raise RuntimeError("box_qp did not converge")
def prepare(model, s, q, h, Q, R, P):
"""Preparation phase: linearize at (s, q) and condense; x_0 is not needed yet."""
N, n, m = len(q), len(s[0]), len(q[0])
As, Bs, cs = [], [], []
for k in range(N): # @line L2
xn, A, B = rk4(model, s[k], q[k], h)
As.append(A)
Bs.append(B)
cs.append([a - b for a, b in zip(xn, s[k + 1])])
# @line L3
# Delta s_k = M_k Delta s_0 + sum_j Gam_k[j] Delta q_j + d_k.
M = [[[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]]
Gam = [[[[0.0] * m for _ in range(n)] for _ in range(N)]]
d = [[0.0] * n]
for k in range(N):
M.append(_mm(As[k], M[k]))
Gk = [_mm(As[k], Gam[k][j]) for j in range(N)]
Gk[k] = Bs[k]
Gam.append(Gk)
d.append([a + c for a, c in zip(_mv(As[k], d[k]), cs[k])])
nq = N * m
H = [[0.0] * nq for _ in range(nq)]
g = [0.0] * nq
G = [[0.0] * n for _ in range(nq)]
for k in range(N + 1):
Wk = P if k == N else Q
Gk = [[Gam[k][j][i][c] for j in range(N) for c in range(m)] for i in range(n)] # n x nq
WG = _mm(Wk, Gk)
GtW = _tr(WG) # nq x n, equals Gk' W since W is symmetric
lin = [a + b for a, b in zip(s[k], d[k])]
H = _madd(H, _mm(GtW, Gk), 2.0)
g = [a + 2.0 * b for a, b in zip(g, _mv(GtW, lin))]
G = _madd(G, _mm(GtW, M[k]), 2.0)
for k in range(N):
for a in range(m):
for b in range(m):
H[k * m + a][k * m + b] += 2.0 * R[a][b]
g[k * m + a] += 2.0 * sum(R[a][b] * q[k][b] for b in range(m))
return {"A": As, "B": Bs, "c": cs, "H": H, "g": g, "G": G}
def feedback(prep, s, q, x0, u_max):
"""Feedback phase: one QP for the measured x0. Returns (u0, s_new, q_new)."""
N, m = len(q), len(q[0])
ds0 = [a - b for a, b in zip(x0, s[0])] # @line L4
gx = [gi + sum(Gi[j] * ds0[j] for j in range(len(ds0))) for gi, Gi in zip(prep["g"], prep["G"])]
lo = [-u_max[c] - q[k][c] for k in range(N) for c in range(m)]
hi = [u_max[c] - q[k][c] for k in range(N) for c in range(m)]
dq = box_qp(prep["H"], gx, lo, hi) # @line L5
q_new = [[q[k][c] + dq[k * m + c] for c in range(m)] for k in range(N)]
u0 = q_new[0] # @line L6
# @line L7
s_new, ds = [list(x0)], ds0
for k in range(N):
ds = [a + b + c for a, b, c in zip(_mv(prep["A"][k], ds), _mv(prep["B"][k], dq[k * m:(k + 1) * m]), prep["c"][k])]
s_new.append([a + b for a, b in zip(s[k + 1], ds)])
return u0, s_new, q_new
def shift(s, q):
"""Shift the trajectory by one interval and repeat the last node and control."""
return s[1:] + [list(s[-1])], q[1:] + [list(q[-1])]
def rti_loop(model, x0, s, q, steps, h, Q, R, P, u_max, plant=None):
"""Closed loop with one RTI per sample. plant(x, u) gives the next state (default: the model).
Returns (xs, us).
"""
plant = plant or (lambda x, u: rk4(model, x, u, h)[0])
x, xs, us = list(x0), [list(x0)], []
for _ in range(steps): # @line L1
prep = prepare(model, s, q, h, Q, R, P)
u, s, q = feedback(prep, s, q, x, u_max)
x = plant(x, u)
xs.append(x)
us.append(u)
s, q = shift(s, q) # @line L8
return xs, us
def solve_nmpc(model, x0, s, q, h, Q, R, P, u_max, tol=1e-10, max_iter=100):
"""Iterate the Gauss-Newton SQP step at a fixed x0 until it converges. Returns (s, q, iterations)."""
for it in range(1, max_iter + 1):
prep = prepare(model, s, q, h, Q, R, P)
_, s_new, q_new = feedback(prep, s, q, x0, u_max)
step = max(abs(a - b) for qa, qb in zip(q_new, q) for a, b in zip(qa, qb))
step = max(step, max(abs(a - b) for sa, sb in zip(s_new, s) for a, b in zip(sa, sb)))
s, q = s_new, q_new
if step < tol:
return s, q, it
raise RuntimeError("the SQP iteration did not converge")
def simulate_cost(model, x0, q, h, Q, R, P):
"""Cost of the control sequence q from x0, by single shooting."""
x, J = list(x0), 0.0
for u in q:
J += sum(x[i] * Q[i][j] * x[j] for i in range(len(x)) for j in range(len(x)))
J += sum(u[i] * R[i][j] * u[j] for i in range(len(u)) for j in range(len(u)))
x = rk4(model, x, u, h)[0]
return J + sum(x[i] * P[i][j] * x[j] for i in range(len(x)) for j in range(len(x)))
test_real_time_iteration.py 167 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/real-time-iteration/. The authors are listed in prov/RM47HC.jsonl.
import itertools
import random
from real_time_iteration import (PENDULUM, box_qp, feedback, prepare, rk4, rti_loop, shift, simulate_cost,
solve_nmpc)
# The example of the page.
H_STEP = 0.1
N = 20
Q = [[10.0, 0.0], [0.0, 1.0]]
R = [[0.1]]
P = [[50.0, 10.0], [10.0, 10.0]]
def zero_guess():
return [[0.0, 0.0] for _ in range(N + 1)], [[0.0] for _ in range(N)]
def test_rk4_derivatives_match_finite_differences():
rng = random.Random(1)
eps = 1e-6
for _ in range(10):
x = [rng.uniform(-3, 3), rng.uniform(-3, 3)]
u = [rng.uniform(-2, 2)]
_, A, B = rk4(PENDULUM, x, u, 0.2)
for j in range(2):
xp, xm = list(x), list(x)
xp[j] += eps
xm[j] -= eps
col = [(a - b) / (2 * eps) for a, b in zip(rk4(PENDULUM, xp, u, 0.2)[0], rk4(PENDULUM, xm, u, 0.2)[0])]
assert all(abs(col[i] - A[i][j]) < 1e-7 for i in range(2))
col = [(a - b) / (2 * eps) for a, b in zip(rk4(PENDULUM, x, [u[0] + eps], 0.2)[0],
rk4(PENDULUM, x, [u[0] - eps], 0.2)[0])]
assert all(abs(col[i] - B[i][0]) < 1e-7 for i in range(2))
def test_rk4_is_the_fourth_order_taylor_step_on_a_linear_model():
lam = -1.7
model = (lambda x, u: [lam * x[0] + u[0]], lambda x, u: [[lam]], lambda x, u: [[1.0]])
for h in (0.1, 0.5):
z = lam * h
xn, A, B = rk4(model, [1.0], [0.0], h)
assert abs(xn[0] - (1 + z + z * z / 2 + z ** 3 / 6 + z ** 4 / 24)) < 1e-14
assert abs(A[0][0] - xn[0]) < 1e-14
def test_box_qp_against_kkt_enumeration():
rng = random.Random(2)
for _ in range(60):
n = rng.randint(1, 4)
L = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
H = [[sum(L[i][k] * L[j][k] for k in range(n)) + (0.1 if i == j else 0.0) for j in range(n)] for i in range(n)]
g = [rng.uniform(-2, 2) for _ in range(n)]
lo = [rng.uniform(-1.5, 0.2) for _ in range(n)]
hi = [v + rng.uniform(0.1, 2) for v in lo]
x = box_qp(H, g, lo, hi)
found = 0
for pattern in itertools.product((-1, 0, 1), repeat=n):
fixed = {i: (lo[i] if p < 0 else hi[i]) for i, p in enumerate(pattern) if p}
free = [i for i in range(n) if i not in fixed]
y = [fixed.get(i, 0.0) for i in range(n)]
if free:
# Solve H_FF y_F = -(g_F + H_FB y_B) by Cramer-free elimination.
M = [[H[i][j] for j in free] + [-(g[i] + sum(H[i][j] * y[j] for j in fixed))] for i in free]
k = len(free)
for c in range(k):
p = max(range(c, k), key=lambda r: abs(M[r][c]))
M[c], M[p] = M[p], M[c]
for r in range(k):
if r != c:
f = M[r][c] / M[c][c]
M[r] = [a - f * b for a, b in zip(M[r], M[c])]
for c, i in enumerate(free):
y[i] = M[c][k] / M[c][c]
grad = [sum(H[i][j] * y[j] for j in range(n)) + g[i] for i in range(n)]
ok = all(lo[i] - 1e-12 <= y[i] <= hi[i] + 1e-12 for i in free)
ok = ok and all((grad[i] >= -1e-12) if fixed[i] == lo[i] else (grad[i] <= 1e-12) for i in fixed)
if ok:
found += 1
assert max(abs(a - b) for a, b in zip(x, y)) < 1e-9
assert found >= 1
def test_condensed_qp_is_the_linearized_cost():
rng = random.Random(3)
n_int = 4
s = [[rng.uniform(-1, 1), rng.uniform(-1, 1)] for _ in range(n_int + 1)]
q = [[rng.uniform(-1, 1)] for _ in range(n_int)]
prep = prepare(PENDULUM, s, q, H_STEP, Q, R, P)
def lin_cost(ds0, dq):
ds, J = ds0, 0.0
for k in range(n_int + 1):
x = [a + b for a, b in zip(s[k], ds)]
W = P if k == n_int else Q
J += sum(x[i] * W[i][j] * x[j] for i in range(2) for j in range(2))
if k < n_int:
u = q[k][0] + dq[k]
J += R[0][0] * u * u
ds = [sum(prep["A"][k][i][j] * ds[j] for j in range(2)) + prep["B"][k][i][0] * dq[k] + prep["c"][k][i]
for i in range(2)]
return J
for _ in range(5):
ds0 = [rng.uniform(-0.5, 0.5), rng.uniform(-0.5, 0.5)]
dq = [rng.uniform(-1, 1) for _ in range(n_int)]
gx = [gi + sum(Gi[j] * ds0[j] for j in range(2)) for gi, Gi in zip(prep["g"], prep["G"])]
model = 0.5 * sum(dq[i] * prep["H"][i][j] * dq[j] for i in range(n_int) for j in range(n_int))
model += sum(a * b for a, b in zip(gx, dq))
assert abs(lin_cost(ds0, dq) - lin_cost(ds0, [0.0] * n_int) - model) < 1e-9
def test_sqp_converges_to_a_local_minimum():
s0, q0 = zero_guess()
x0 = [1.0, 0.0]
s, q, it = solve_nmpc(PENDULUM, x0, s0, q0, H_STEP, Q, R, P, [10.0])
assert it <= 10
# No gaps: the nodes are the simulated trajectory.
for k in range(N):
assert max(abs(a - b) for a, b in zip(rk4(PENDULUM, s[k], q[k], H_STEP)[0], s[k + 1])) < 1e-9
J = simulate_cost(PENDULUM, x0, q, H_STEP, Q, R, P)
rng = random.Random(4)
for _ in range(20):
d = [[rng.uniform(-1e-3, 1e-3)] for _ in range(N)]
assert simulate_cost(PENDULUM, x0, [[a[0] + b[0]] for a, b in zip(q, d)], H_STEP, Q, R, P) >= J - 1e-12
assert abs(q[0][0] + 8.4348) < 1e-4
def test_rti_follows_the_converged_solution():
s0, q0 = zero_guess()
x0 = [1.0, 0.0]
xs, us = rti_loop(PENDULUM, x0, s0, q0, 20, H_STEP, Q, R, P, [10.0])
s, q, diffs = s0, q0, []
for k in range(6):
# The fully converged NMPC input at the same state as the RTI loop.
s, q, _ = solve_nmpc(PENDULUM, xs[k], s, q, H_STEP, Q, R, P, [10.0])
diffs.append(abs(q[0][0] - us[k][0]))
s, q = shift(s, q)
assert 0.1 < diffs[0] < 0.2
assert diffs[1] < 1e-4 and max(diffs[2:]) < 1e-5
assert max(abs(v) for v in xs[-1]) < 1e-2
def test_saturated_loop_keeps_bounds_and_stabilizes():
s0, q0 = zero_guess()
xs, us = rti_loop(PENDULUM, [2.5, 0.0], s0, q0, 35, H_STEP, Q, R, P, [2.0])
assert all(abs(u[0]) <= 2.0 + 1e-12 for u in us)
assert max(abs(v) for v in xs[-1]) < 1e-2
# The plant alone falls: without input the angle grows from 0.1 to almost 1 in 3 seconds.
x = [0.1, 0.0]
for _ in range(30):
x = rk4(PENDULUM, x, [0.0], H_STEP)[0]
assert x[0] > 0.9
def test_preparation_does_not_use_the_state():
# The feedback for two different measured states uses the same prepared data.
s0, q0 = zero_guess()
prep = prepare(PENDULUM, s0, q0, H_STEP, Q, R, P)
u1, _, _ = feedback(prep, s0, q0, [0.2, 0.0], [10.0])
u2, _, _ = feedback(prep, s0, q0, [0.4, 0.0], [10.0])
# Linearized at 0 and unconstrained, the first input is linear in x0.
u4, _, _ = feedback(prep, s0, q0, [0.0, 0.0], [10.0])
assert abs(u4[0]) < 1e-12 and abs(u2[0] - 2 * u1[0]) < 1e-9
History
Diehl, Bock and Schlöder developed the real-time iteration in Heidelberg, on top of the direct multiple shooting method of Bock and Plitt (1984) for optimal control. The key ideas are the initial value embedding, which puts the measured state into the QP as a linear constraint, and the split into a preparation phase and a feedback phase. In 2005 Diehl, Bock and Schlöder published the contraction analysis of the scheme, and Diehl, Findeisen, Allgöwer, Bock and Schlöder proved the nominal stability of the closed loop. The method spread to fast mechatronic and automotive applications through code generation tools, and it is now a standard way to run nonlinear MPC on embedded hardware.
References
- Moritz Diehl, Hans Georg Bock and Johannes P. Schlöder, A real-time iteration scheme for nonlinear optimization in optimal feedback control, SIAM Journal on Control and Optimization 43(5), 1714-1736, 2005, the real-time iteration with the initial value embedding, and its contraction analysis
- Moritz Diehl, Rolf Findeisen, Frank Allgöwer, Hans Georg Bock and Johannes P. Schlöder, Nominal stability of real-time iteration scheme for nonlinear model predictive control, IEE Proceedings Control Theory and Applications 152(3), 296-308, 2005, the nominal stability of the closed loop of the real-time iteration with shifted initial guesses
- James B. Rawlings, David Q. Mayne and Moritz M. Diehl, Model Predictive Control, Theory, Computation, and Design, 2nd edition, Nob Hill Publishing, 2017, the chapter on numerical optimal control, the real-time iteration
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag RM47HC Edit this page History Report an error Markdown