Algorithm Search⌘K

Algorithmcore

Dynamic matrix control

Also called DMC.

An early industrial MPC that predicts the output from a step response model and solves a least squares problem for the input moves.

Time
O(P L) worstO(P M^2 + M^3) offline
Space
O(P M + L) extra
Where
L = the length of the step response model; M = the number of future moves; P = the prediction horizon
Properties
deterministicexactonlineiterative
Origin
C. R. Cutler, B. L. Ramaker, 1980

Dynamic matrix control (DMC) is one of the first model predictive control methods that spread in industry. Its model is the measured step response of the plant: sis_i is the output ii samples after a unit step of the input. With this model, the future outputs are a linear function of the future input moves Δu(k)=u(k)−u(k−1)\Delta u(k) = u(k) - u(k-1), and the matrix of that function is the dynamic matrix SS that gives the method its name. At each sampling instant DMC takes the difference between the measured and the model output as a constant output disturbance, predicts the outputs over PP samples, chooses MM moves by regularized least squares, and applies the first move. Without constraints the result is a fixed linear controller with integral action.

In plain words

Step the input of the plant once and record how the output moves. That record is the whole model. Now, at each tick, ask: if I make no more changes, where will the output go? Shift the recorded responses of all past input changes forward in time and add them up. The model is never perfect, so the controller also adds the present gap between the measured output and the model output, and assumes that gap stays the same. Then it picks a few future input changes so that the predicted output comes close to the setpoint, with a penalty on large changes. This is a least squares problem. Only the first change is applied, and the whole process is done again at the next tick.

The problem

Input: a step response model s1,…,sLs_1, \dots, s_L of a single input, single output plant whose step response settles by sample LL (so si=sLs_i = s_L for i>Li > L); a prediction horizon P<LP < L; a number of moves M≤PM \le P; a move weight λ≥0\lambda \ge 0; at each sampling instant kk, the measured output y(k)y(k) and the setpoint rr. Output: the input u(k)u(k).

The model. By superposition, a plant with this step response has the output

y^(k)=∑j≥1sj Δu(k−j),\hat y(k) = \sum_{j \ge 1} s_j\, \Delta u(k - j),

with sj=sLs_j = s_L for j>Lj > L. A move made jj samples ago contributes sjs_j times its size.

The prediction. With the disturbance estimate d(k)=y(k)−y^(k)d(k) = y(k) - \hat y(k) held constant, the predicted outputs are

y^(k+i)=fi+∑j=1MSij Δu(k+j−1),fi=∑j≥1si+j Δu(k−j)+d(k),\hat y(k + i) = f_i + \sum_{j = 1}^{M} S_{ij}\, \Delta u(k + j - 1), \qquad f_i = \sum_{j \ge 1} s_{i + j}\, \Delta u(k - j) + d(k),

for i=1,…,Pi = 1, \dots, P. The free response fif_i is the effect of the past moves; the P×MP \times M dynamic matrix Sij=si−j+1S_{ij} = s_{i - j + 1} for i≥ji \ge j (and 0 above the diagonal) is the effect of the future moves.

The move. DMC minimizes ∥r1−f−S ΔU∥2+λ∥ΔU∥2\|r \mathbf{1} - f - S\, \Delta U\|^2 + \lambda \|\Delta U\|^2 over ΔU=(Δu(k),…,Δu(k+M−1))\Delta U = (\Delta u(k), \dots, \Delta u(k + M - 1)). This is a ridge regression, and its normal equations give

ΔU∗=(STS+λI)−1ST(r1−f).\Delta U^* = (S^T S + \lambda I)^{-1} S^T (r \mathbf{1} - f).

The algorithm

  1. DMC-SETUP(s, P, M, λ) ▷ offline
  2. 1S ← the P × M matrix with S_ij = s_(i-j+1) for i ≥ j, 0 otherwise
  3. 2K ← first row of (Sᵀ S + λ I)⁻¹ Sᵀ
  4. DMC-STEP(y, r) ▷ online, at each sampling instant
  5. 3compute the free response f of the past moves:
  6. 4d ← y - Σ_(j ≥ 1) s_j Δu(k - j) ▷ model mismatch, held constant
  7. 5f_i ← Σ_(j ≥ 1) s_(i+j) Δu(k - j) + d for i = 1, …, P
  8. 6Δu(k) ← K (r 1 - f) ▷ first move of the least squares plan
  9. 7store Δu(k) in the move history; u(k) ← u(k - 1) + Δu(k); return u(k)

Lines L1 and L2 run once. Line L2 needs only the first row KK, because only the first move is applied. Lines L4 and L5 use the last LL moves one by one and the sum of all older moves, which all have the same weight sLs_L. Line L6 is one inner product of length PP. The implementation stores all MM rows of the gain for the tests, and keeps the history in a list of the last LL moves.

Example

The plant is y(k+1)=0.8 y(k)+0.2 u(k−1)y(k+1) = 0.8\, y(k) + 0.2\, u(k-1), a first order lag with gain 1 and one extra sample of delay. Its step response is si=1−0.8i−1s_i = 1 - 0.8^{i-1}:

ii 1 2 3 4 5 6
sis_i 0 0.2 0.36 0.488 0.5904 0.6723

The tuning is L=30L = 30, P=10P = 10, M=2M = 2, λ=0.1\lambda = 0.1. Lines L1 and L2 give

K=(0, 0.6807, 0.4973, 0.3505, 0.2331, 0.1392, 0.0641, 0.0040, −0.0441, −0.0826),∑iKi=1.8422.K = (0,\ 0.6807,\ 0.4973,\ 0.3505,\ 0.2331,\ 0.1392,\ 0.0641,\ 0.0040,\ -0.0441,\ -0.0826), \qquad \textstyle\sum_i K_i = 1.8422.

The first entry is 0 because s1=0s_1 = 0: the input cannot move the next output, so the first row of SS is zero.

A setpoint step. From rest with r=1r = 1, the free response is f=0f = 0 and the first move is ∑iKi=1.8422\sum_i K_i = 1.8422. The closed loop (measurement with the implementation):

kk 0 1 2 3 4 5 6 7
u(k)u(k) 1.8422 2.0335 1.7048 1.3556 1.1295 1.0202 0.9830 0.9791
y(k+1)y(k+1) 0 0.3684 0.7015 0.9021 0.9928 1.0202 1.0202 1.0127

The output overshoots by about 2 percent and settles at 1.

An output disturbance. A step of 0.3 is added to the measured output from k=25k = 25. Because of the delay, the outputs at k=25k = 25 and k=26k = 26 are both 1.2999. Then the output returns: 1.1894, 1.0896, 1.0295, 1.0025, 0.9946, and it converges to 1 with no offset. The tests repeat this with a step of 0.5 and with plant gains 0.7 and 1.3 against the model gain 1, and the output still converges to the setpoint.

Tuning. ∑iKi\sum_i K_i is the first move after a unit setpoint step from rest, so it measures how hard the controller acts. With M=1M = 1 and λ=0\lambda = 0 it is 1.4496; with P=15P = 15, M=3M = 3 and λ=1\lambda = 1 it is 0.7596. In the tests, a larger λ\lambda gives a smaller first move for λ=0,0.1,1,10\lambda = 0, 0.1, 1, 10.

Correctness

The proofs are in proofs/correctness.md.

  1. The prediction is exact for a step response plant. If the plant output is y^(k)+d\hat y(k) + d with a constant dd, then y^(k+i)\hat y(k + i) of the formula above equals the true future output for any future moves (superposition, Lemma 1).
  2. The move is the least squares optimum. For λ>0\lambda > 0, or λ=0\lambda = 0 with SS of full column rank, the cost is strictly convex and ΔU∗\Delta U^* is its unique minimizer (Lemma 2). With a dead time of τ\tau samples, full rank holds when P≥M+τP \ge M + \tau and sτ+1≠0s_{\tau + 1} \ne 0.
  3. Unconstrained DMC is linear and time invariant. KK is fixed and ff is linear in y(k)y(k) and the past moves, so Δu(k)\Delta u(k) is a fixed linear function of rr, y(k)y(k) and the past moves (Lemma 3).
  4. Zero offset (theorem). If rr and the disturbance are constant from some time on, the closed loop with a linear plant is asymptotically stable, and ∑iKi≠0\sum_i K_i \ne 0, then y(k)→ry(k) \to r. The plant may differ from the model: the mismatch goes into d(k)d(k). In the limit Δu=0=(∑iKi)(r−y∞)\Delta u = 0 = (\sum_i K_i)(r - y_\infty).
Proof: The DMC prediction is exact for a step-response plant with a constant output disturbance, the move is the least-squares optimum, and a convergent loop has no offsetfull

The model is the step response s1,…,sNss_1, \dots, s_{N_s}, extended by si=sNss_i = s_{N_s} for i>Nsi > N_s. Write Δu(k)=u(k)−u(k−1)\Delta u(k) = u(k) - u(k-1) and assume the input was constant before time 0, so only finitely many moves are nonzero. The model output is

y^(k)=∑j≥1sj Δu(k−j).\hat y(k) = \sum_{j \ge 1} s_j \, \Delta u(k - j).

This is exactly the output of a linear time-invariant plant whose step response is the extended sequence: a step of size Δu(k−j)\Delta u(k-j) at time k−jk - j adds sjΔu(k−j)s_j \Delta u(k-j) at time kk, by superposition. A stable plant whose step response has settled after NsN_s samples is of this form up to the truncation error ∣si−sNs∣|s_i - s_{N_s}| for i>Nsi > N_s.

Lemma 1: the prediction

Suppose the plant output is y(k)=y^(k)+dy(k) = \hat y(k) + d with a constant dd (the model is exact up to a constant output disturbance). Let fif_i be computed as in lines L4 and L5:

d(k)=y(k)−y^(k),fi=∑j≥1si+j Δu(k−j)+d(k),i=1,…,P.d(k) = y(k) - \hat y(k), \qquad f_i = \sum_{j \ge 1} s_{i + j} \, \Delta u(k - j) + d(k), \qquad i = 1, \dots, P.

Then for any future moves Δu(k),…,Δu(k+M−1)\Delta u(k), \dots, \Delta u(k + M - 1), with Δu(k+j)=0\Delta u(k + j) = 0 for j≥Mj \ge M,

y(k+i)=fi+∑j=0M−1Si,j+1 Δu(k+j),Si,j=si−j+1 (i≥j), Si,j=0 (i<j).y(k + i) = f_i + \sum_{j=0}^{M-1} S_{i, j+1} \, \Delta u(k + j), \qquad S_{i,j} = s_{i - j + 1} \ (i \ge j), \ S_{i, j} = 0 \ (i < j).

Proof. d(k)=dd(k) = d by the assumption. Split the sum for y(k+i)=y^(k+i)+dy(k+i) = \hat y(k+i) + d into the moves before time kk and the moves from time kk on. A past move Δu(k−j)\Delta u(k - j), j≥1j \ge 1, is i+ji + j samples old at time k+ik + i, so it contributes si+jΔu(k−j)s_{i+j} \Delta u(k-j); these terms and dd make up fif_i. A future move Δu(k+j)\Delta u(k + j) is i−ji - j samples old at time k+ik + i; it contributes si−jΔu(k+j)s_{i-j} \Delta u(k+j) if i−j≥1i - j \ge 1 and nothing otherwise. With the column index j+1j + 1 this is Si,j+1S_{i, j+1}. □\square

The code stores the last NsN_s moves and the sum of the older ones. A move older than NsN_s samples has the coefficient sNss_{N_s} at every horizon, so the stored sum times sNss_{N_s} is its exact contribution.

Lemma 2: the move

Let e=r−fe = r - f with rr the setpoint vector. For λ>0\lambda > 0, or for λ=0\lambda = 0 when SS has full column rank, the cost

J(ΔU)=∥e−SΔU∥2+λ∥ΔU∥2J(\Delta U) = \|e - S \Delta U\|^2 + \lambda \|\Delta U\|^2

has the unique minimizer ΔU∗=(STS+λI)−1STe\Delta U^* = (S^T S + \lambda I)^{-1} S^T e.

Proof. JJ is a quadratic with Hessian 2(STS+λI)2(S^T S + \lambda I), which is positive definite under either condition: vT(STS+λI)v=∥Sv∥2+λ∥v∥2>0v^T (S^T S + \lambda I) v = \|S v\|^2 + \lambda \|v\|^2 > 0 for v≠0v \ne 0. So JJ is strictly convex, and its unique minimizer is the zero of the gradient 2(STS+λI)ΔU−2STe2(S^T S + \lambda I) \Delta U - 2 S^T e. □\square

Lines L1 and L2 compute the matrix (STS+λI)−1ST(S^T S + \lambda I)^{-1} S^T column by column, and line L6 applies its first row KK to ee. So the first move is the first entry of ΔU∗\Delta U^*, and by Lemma 1 it is the first move of the sequence that minimizes the predicted tracking error plus the move penalty.

The full-rank condition holds when s1≠0s_1 \ne 0. If the plant has a dead time of τ\tau samples, so s1=⋯=sτ=0s_1 = \dots = s_\tau = 0, then SS has full column rank when P≥M+τP \ge M + \tau and sτ+1≠0s_{\tau + 1} \ne 0, because the rows τ+1,…,τ+M\tau + 1, \dots, \tau + M form a lower triangular block with sτ+1s_{\tau+1} on the diagonal.

Lemma 3: unconstrained DMC is a linear time-invariant controller

KK does not depend on kk. ff is a fixed linear function of y(k)y(k) and of the past moves, so Δu(k)\Delta u(k) is a fixed linear function of rr, y(k)y(k) and the past moves. The controller is therefore a linear time-invariant system from (r,y)(r, y) to uu, with Δu(k)=K(r1−f)\Delta u(k) = K (r \mathbf{1} - f). Its stability with the plant is a property of the tuning (P,M,λ)(P, M, \lambda) and must be checked; DMC itself gives no guarantee.

Theorem: zero offset

Assume the setpoint rr and the output disturbance are constant from some time on, the plant is linear (not necessarily equal to the model), and the closed loop is asymptotically stable, so every signal converges. Assume also K1=∑iKi≠0K \mathbf{1} = \sum_i K_i \ne 0. Then y(k)→ry(k) \to r.

Proof. The input converges, so Δu(k)→0\Delta u(k) \to 0. Since the controller uses only the last NsN_s moves individually and the sum of the older ones, and the moves tend to 0 while their running sum u(k)−u(−1)u(k) - u(-1) converges, the model output y^(k)\hat y(k) converges to some y^∞\hat y_\infty, and every term ∑j≥1si+jΔu(k−j)\sum_{j \ge 1} s_{i+j} \Delta u(k-j) of the free response converges to the same limit y^∞\hat y_\infty (the difference between them involves only the last NsN_s moves, which tend to 0). The measured output converges to some y∞y_\infty, so d(k)→y∞−y^∞d(k) \to y_\infty - \hat y_\infty, and therefore fi→y∞f_i \to y_\infty for every ii. Passing to the limit in line L6,

0=lim⁡Δu(k)=K(r1−y∞1)=(K1)(r−y∞).0 = \lim \Delta u(k) = K (r \mathbf{1} - y_\infty \mathbf{1}) = (K \mathbf{1}) (r - y_\infty).

Since K1≠0K \mathbf{1} \ne 0, y∞=ry_\infty = r. □\square

The argument does not use the plant model: any mismatch of gain or dynamics is absorbed into d(k)d(k). This is the integral action of DMC. For M=1M = 1 the condition K1≠0K \mathbf{1} \ne 0 is ∑i=1Psi≠0\sum_{i=1}^P s_i \ne 0, which holds for every step response with nonnegative entries that are not all 0. For M>1M > 1 it is read off the computed gain; in the example of the page K1=1.8422K \mathbf{1} = 1.8422.

Complexity

Costs are in the real-RAM model, with PP the prediction horizon, MM the number of moves and LL the model length, for one input and one output.

  • Offline. STSS^T S costs O(PM2)O(P M^2), a Cholesky factorization of STS+λIS^T S + \lambda I costs O(M3)O(M^3), and the first row of the gain needs one more solve and a product with STS^T, O(M2+PM)O(M^2 + P M). Total O(PM2+M3)O(P M^2 + M^3). The implementation solves one system per column of the gain with Gaussian elimination, O(PM3)O(P M^3), which is the same for the small MM of practice.
  • Online, per sampling instant. The free response costs O(L)O(L) for each of the PP horizons, so O(PL)O(P L). With a shift register of the free response, updated by one column of the step response per sample, this drops to O(P)O(P). Line L6 costs O(P)O(P).
  • Space. O(PM)O(P M) for SS and the gain, and O(L)O(L) for the move history.
  • Multivariable plants. With mm inputs and pp outputs, SS has PpP p rows and MmM m columns, and the costs grow accordingly: O(PpM2m2+M3m3)O(P p M^2 m^2 + M^3 m^3) offline.

Properties

  • Linear time-invariant controller when there are no constraints. Its stability with the plant depends on PP, MM and λ\lambda and must be checked. DMC itself gives no stability guarantee.
  • Integral action. The constant output disturbance model removes steady-state error for constant setpoints and disturbances, as long as the loop converges (theorem above).
  • Only for plants with a settling step response. A finite step response model needs an asymptotically stable plant, with all poles strictly inside the unit circle (Schur). Integrating and unstable plants need another model.
  • Same as GPC for setpoint changes. For a plant with an exact step model and no disturbance, and the GPC horizons N1=1N_1 = 1, N2=PN_2 = P, Nu=MN_u = M, the predictions of DMC and of GPC agree, so the gains and the setpoint response are equal. They differ in the disturbance model.

Variants and improvements

  • QDMC (García and Morshedi 1986): input, move and output limits are added, and each step solves a quadratic program instead of a least squares problem. This is DMC as a special case of linear MPC with a step response model.
  • Multivariable DMC. Each input and output pair has its own step response, and SS becomes a block matrix with one block per pair.
  • Output weights and move weights per output and per input, and a reference trajectory instead of a constant setpoint (the code accepts a list r1,…,rPr_1, \dots, r_P).
  • Model predictive heuristic control (Richalet et al. 1978) uses an impulse response model instead of a step response model.
  • GPC uses a transfer function model and a different disturbance model; see generalized predictive control.
  • State-space disturbance models. Offset-free MPC generalizes the constant output disturbance of DMC to state-space models with input or state disturbances.

When to use it

Use DMC for plants that are open-loop asymptotically stable and easy to test with a step, when a model from first principles is not available. It is common in process control, where the plants are slow and the step tests are routine. For plants with integrators or unstable modes, or for strong disturbance rejection, use a state-space form such as linear MPC with an offset-free disturbance model. If there are limits on the inputs, use the QP form.

Pitfalls

  • Model too short. If LL is shorter than the settling time, the truncation si=sLs_i = s_L is wrong and the predictions drift. The implementation rejects P≥LP \ge L.
  • Slow rejection of input disturbances. The model assumes a constant output disturbance. A disturbance that enters at the input passes through the plant dynamics. Rule of thumb: DMC removes it slowly, at about the speed of the open-loop plant; when this matters, use a disturbance model that matches the real disturbance.
  • Clipping the move. Clipping uu at a limit after line L6 gives a feasible input but not the optimal one, and the move history then differs from the applied input unless it stores the clipped move. Store the applied move, or use QDMC. See integrator windup.
  • λ=0\lambda = 0 with MM close to PP makes the first move very large and the loop sensitive to model error.
  • No stability check. Some choices of PP, MM and λ\lambda give an unstable loop. Check the closed-loop poles with the model, and test with model error.

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.

dynamic_matrix_control.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-matrix-control/. The authors are listed in prov/078WY3.jsonl.

"""Dynamic matrix control (DMC) for a single input and a single output.

The model is the truncated step response s_1, ..., s_Ns of the plant: s_i is
the output i samples after a unit step of the input, and s_i = s_Ns for
i >= Ns. With the input moves du(k) = u(k) - u(k-1), the model output is

    yhat(k) = sum_(j >= 1) s_min(j, Ns) du(k - j).

At each sample the controller:

1. compares the measured output with the model output and takes the
   difference d(k) = y(k) - yhat(k) as a constant output disturbance over
   the horizon;
2. computes the free response f_i, i = 1..P: the predicted output if no
   more moves are made, plus d(k);
3. chooses the next M moves to minimize
       sum_(i=1)^P (r - f_i - (S du)_i)^2 + lam sum_(j=0)^(M-1) du(k+j)^2,
   where S is the P x M dynamic matrix, S_ij = s_(i-j+1) for i >= j and 0
   otherwise; the minimizer is du = (S^T S + lam I)^-1 S^T (r - f);
4. applies only the first move.

Without constraints the first row of (S^T S + lam I)^-1 S^T is a constant
vector, so DMC is a linear time-invariant controller.
"""

__all__ = ["dynamic_matrix", "dmc_gain", "DMC", "step_response"]


def _solve(a, b):
    n = len(a)
    m = [list(map(float, r)) + [float(v)] for r, v in zip(a, b)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(m[r][c]))
        if m[p][c] == 0.0:
            raise ValueError("singular matrix")
        m[c], m[p] = m[p], m[c]
        for r in range(n):
            if r != c and m[r][c] != 0.0:
                f = m[r][c] / m[c][c]
                m[r] = [x - f * y for x, y in zip(m[r], m[c])]
    return [m[i][n] / m[i][i] for i in range(n)]


def step_response(plant_step, Ns):
    """Return [s_1, ..., s_Ns] by running plant_step(u) from rest with u = 1.

    plant_step takes the input of sample k and returns the output of sample
    k + 1; it must start at rest.
    """
    return [plant_step(1.0) for _ in range(Ns)]


def dynamic_matrix(s, P, M):
    """Return the P x M dynamic matrix S_ij = s_(i-j+1) (0 above the diagonal)."""
    Ns = len(s)
    return [[s[min(i - j, Ns - 1)] if i >= j else 0.0 for j in range(M)] for i in range(P)]


def dmc_gain(s, P, M, lam):
    """Return all M rows of (S^T S + lam I)^-1 S^T, as a list of rows of length P."""
    S = dynamic_matrix(s, P, M)  # @line L1
    StS = [[sum(S[i][a] * S[i][b] for i in range(P)) + (lam if a == b else 0.0) for b in range(M)]
           for a in range(M)]
    cols = []
    for i in range(P):  # column i of the gain solves (S^T S + lam I) g = S^T e_i
        cols.append(_solve(StS, [S[i][a] for a in range(M)]))  # @line L2
    return [[cols[i][a] for i in range(P)] for a in range(M)]


class DMC:
    """Unconstrained DMC controller with the step model s and the tuning P, M, lam."""

    def __init__(self, s, P, M, lam, u0=0.0):
        if P > len(s) - 1:
            raise ValueError("the step model must be longer than the prediction horizon")
        self.s, self.P, self.M, self.lam = [float(v) for v in s], P, M, lam
        self.Ns = len(s)
        self.K = dmc_gain(self.s, P, M, lam)[0]
        self.u = float(u0)
        self.moves = [0.0] * self.Ns  # du(k-1), ..., du(k-Ns)
        self.older = 0.0  # sum of the moves older than Ns samples
        self.d = 0.0

    def _s(self, i):
        return self.s[min(i, self.Ns) - 1]

    def model_output(self, ahead=0):
        """Model output at k + ahead with no future moves (without d)."""
        y = sum(self._s(ahead + j) * dj for j, dj in enumerate(self.moves, start=1))
        return y + self.s[-1] * self.older

    def free_response(self, y_meas):
        """Return f_1..f_P and set d(k) = y_meas - yhat(k)."""
        self.d = y_meas - self.model_output(0)  # @line L4
        return [self.model_output(i) + self.d for i in range(1, self.P + 1)]  # @line L5

    def step(self, y_meas, r):
        """Return the input u(k) for the measured y(k) and the setpoint r."""
        f = self.free_response(y_meas)  # @line L3
        rr = r if isinstance(r, list) else [r] * self.P
        du = sum(k * (ri - fi) for k, ri, fi in zip(self.K, rr, f))  # @line L6
        self.older += self.moves[-1]  # @line L7
        self.moves = [du] + self.moves[:-1]
        self.u += du
        return self.u

    def predict(self, y_meas, du_future):
        """Predicted outputs y(k+1..k+P) for the future moves du_future (length M)."""
        f = self.free_response(y_meas)
        S = dynamic_matrix(self.s, self.P, self.M)
        return [fi + sum(S[i][j] * du_future[j] for j in range(self.M)) for i, fi in enumerate(f)]
test_dynamic_matrix_control.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dynamic-matrix-control/. The authors are listed in prov/078WY3.jsonl.

import random

import pytest

from dynamic_matrix_control import DMC, dmc_gain, dynamic_matrix, step_response


def make_plant(a=0.8, b=0.2):
    """y(k+1) = a y(k) + b u(k-1): a first order lag with one extra sample of delay."""
    st = {"y": 0.0, "u1": 0.0}

    def plant(u):
        st["y"], st["u1"] = a * st["y"] + b * st["u1"], u
        return st["y"]
    return plant


S30 = step_response(make_plant(), 30)


def run(ctrl, plant, refs, dist=lambda k: 0.0):
    y, ys, us = 0.0, [], []
    for k, r in enumerate(refs):
        u = ctrl.step(y + dist(k), r)
        y = plant(u)
        ys.append(y + dist(k + 1))
        us.append(u)
    return ys, us


def test_step_response_of_the_example_plant():
    for i, si in enumerate(S30, start=1):
        assert abs(si - (1 - 0.8 ** (i - 1))) < 1e-12


def test_dynamic_matrix_is_lower_triangular_toeplitz():
    s = [0.1 * i for i in range(1, 8)]
    S = dynamic_matrix(s, 5, 3)
    for i in range(5):
        for j in range(3):
            assert S[i][j] == (s[i - j] if i >= j else 0.0)


def test_gain_solves_the_least_squares_problem():
    rng = random.Random(31)
    P, M, lam = 10, 3, 0.4
    S = dynamic_matrix(S30, P, M)
    Kall = dmc_gain(S30, P, M, lam)
    for _ in range(20):
        e = [rng.uniform(-1, 1) for _ in range(P)]
        du = [sum(Kall[a][i] * e[i] for i in range(P)) for a in range(M)]
        res = [sum(S[i][j] * du[j] for j in range(M)) - e[i] for i in range(P)]
        grad = [sum(S[i][a] * res[i] for i in range(P)) + lam * du[a] for a in range(M)]
        assert max(abs(g) for g in grad) < 1e-12
        cost = sum(v * v for v in res) + lam * sum(v * v for v in du)
        for _ in range(10):  # any other move sequence costs more
            other = [v + rng.uniform(-0.1, 0.1) for v in du]
            r2 = [sum(S[i][j] * other[j] for j in range(M)) - e[i] for i in range(P)]
            assert sum(v * v for v in r2) + lam * sum(v * v for v in other) >= cost - 1e-12


def test_prediction_is_exact_for_a_step_model_plant():
    rng = random.Random(32)
    s = S30[:12]
    Ns = len(s)

    def fir_output(moves, k):  # y(k) = sum_(j>=1) s_min(j, Ns) du(k - j)
        return sum(s[min(k - i, Ns) - 1] * moves[i] for i in range(k)) + 0.4  # constant output offset

    ctrl = DMC(s, 8, 3, 0.2)
    moves = []
    for k in range(15):  # closed loop for a while with random setpoints
        u_before = ctrl.u
        ctrl.step(fir_output(moves, k), rng.uniform(-1, 1))
        moves.append(ctrl.u - u_before)
    k = len(moves)
    future = [rng.uniform(-1, 1) for _ in range(3)]
    pred = ctrl.predict(fir_output(moves, k), future)
    allm = moves + future + [0.0] * 8
    for i in range(1, 9):
        assert abs(pred[i - 1] - fir_output(allm, k + i)) < 1e-12


def test_example_closed_loop():
    ctrl = DMC(S30, 10, 2, 0.1)
    assert ctrl.K[0] == 0.0  # s_1 = 0: the first output cannot move
    assert abs(sum(ctrl.K) - 1.8422) < 5e-5
    ys, us = run(ctrl, make_plant(), [1.0] * 40)
    assert abs(us[0] - sum(ctrl.K)) < 1e-12
    assert ys[0] == 0.0 and abs(ys[1] - 0.2 * us[0]) < 1e-12
    assert abs(ys[-1] - 1.0) < 1e-4


def test_no_offset_with_model_error_and_output_disturbance():
    for b in (0.14, 0.2, 0.26):  # plant gain 0.7, 1 and 1.3 against a model gain of 1
        ctrl = DMC(S30, 10, 2, 0.1)
        ys, us = run(ctrl, make_plant(0.8, b), [1.0] * 120, dist=lambda k: 0.5 if k >= 40 else 0.0)
        assert abs(ys[-1] - 1.0) < 1e-6
        assert abs(us[-1] - 0.5 * 0.2 / b) < 1e-5  # u = (r - d) / plant gain


def test_unconstrained_dmc_is_linear():
    rng = random.Random(33)
    r1 = [rng.uniform(-1, 1) for _ in range(30)]
    r2 = [rng.uniform(-1, 1) for _ in range(30)]
    y1, _ = run(DMC(S30, 10, 2, 0.1), make_plant(), r1)
    y2, _ = run(DMC(S30, 10, 2, 0.1), make_plant(), r2)
    y3, _ = run(DMC(S30, 10, 2, 0.1), make_plant(), [2 * a - 3 * b for a, b in zip(r1, r2)])
    assert max(abs(c - (2 * a - 3 * b)) for a, b, c in zip(y1, y2, y3)) < 1e-12


def test_larger_move_weight_gives_smaller_first_move():
    first = [sum(DMC(S30, 10, 2, lam).K) for lam in (0.0, 0.1, 1.0, 10.0)]
    assert all(a > b for a, b in zip(first, first[1:]))


def test_model_shorter_than_horizon_is_rejected():
    with pytest.raises(ValueError):
        DMC(S30[:5], 10, 2, 0.1)

History

Richalet, Rault, Testud and Papon (1978) described model predictive heuristic control, with an impulse response model, and its use on industrial processes. Cutler and Ramaker, engineers at Shell Oil, presented dynamic matrix control in 1980 at the Joint Automatic Control Conference. García and Morshedi (1986) wrote the constrained version as a quadratic program, QDMC. Qin and Badgwell (2003) describe how these methods became the base of industrial MPC products.

References

  1. C. R. Cutler and B. L. Ramaker, Dynamic matrix control: a computer control algorithm, Proceedings of the Joint Automatic Control Conference, San Francisco, 1980, paper WP5-B, the step response model, the dynamic matrix, and the least squares move calculation
  2. J. Richalet, A. Rault, J. L. Testud and J. Papon, Model predictive heuristic control, applications to industrial processes, Automatica 14(5), 413-428, 1978, the earlier predictive scheme with an impulse response model
  3. Carlos E. García and A. M. Morshedi, Quadratic programming solution of dynamic matrix control (QDMC), Chemical Engineering Communications 46(1-3), 73-87, 1986, the constrained form of DMC as a quadratic program
  4. S. Joe Qin and Thomas A. Badgwell, A survey of industrial model predictive control technology, Control Engineering Practice 11(7), 733-764, 2003, the history of DMC, IDCOM and QDMC in industry

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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.offline
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example