Figure 1.10:

Three measured outputs versus time after a step change in inlet flowrate at 10 minutes; n_d=3.

Figure 1.10

Code for Figure 1.10

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
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
# Applies offset-free linear MPC to the nonlinear CSTR.
# See Pannocchia and Rawlings, AIChE J, 2002.

import numpy as np
import mpctools as mpc
from types import SimpleNamespace
import matplotlib.pyplot as plt
import control as ct
from misc import gnuplotsave
import os

# Parameters and sizes for the nonlinear system
Delta = 1
Nx = 3
Nu = 2
Ny = Nx
Np = 1
small = 1e-5 # small number

# Parameters
pars = SimpleNamespace()
pars.T0 = 350                       # K
pars.c0 = 1                         # kmol/m^3
pars.r = 0.219                      # m
pars.k0 = 7.2e10                    # min^-1
pars.E = 8750                       # K
pars.U = 54.94                      # kJ/(min m^2 K)
pars.rho = 1e3                      # kg/m^3
pars.Cp = 0.239                     # kJ / (kg K)
pars.DeltaH = -5e4                  # kJ/kmol
pars.A = np.pi * pars.r ** 2        # m^2
pars.rhoCp = pars.rho * pars.Cp     # kJ / (m^3 K)

def cstrode(x, u, p, pars):
    """
    Nonlinear ODE model for a reactor.
    """
    c, T, h = x
    h += np.finfo(float).eps  # Avoid division by zero

    Tc, F = u
    F0 = p[0]

    k = pars.k0 * np.exp(-pars.E / T)
    rate = k * c

    dcdt = F0 * (pars.c0 - c) / (pars.A * h) - rate
    dTdt = (
        F0 * (pars.T0 - T) / (pars.A * h)
        - pars.DeltaH / pars.rhoCp * rate
        + 2 * pars.U / (pars.r * pars.rhoCp) * (Tc - T)
    )
    dhdt = (F0 - F) / pars.A

    return np.array([dcdt, dTdt, dhdt])

ode_casadi = mpc.getCasadiFunc(lambda x, u, p: cstrode(x, u, p, pars),
                               [Nx, Nu, Np], ['x', 'u', 'p'], 'ode')


cstrsim = mpc.getCasadiIntegrator(lambda x, u, p: cstrode(x, u, p, pars),
                                  Delta, [Nx, Nu, Np], ['x', 'u', 'p'], 'cstr')

# Steady-state values
cs = 0.8778 # kmol/m^3
Ts = 324.5 # K
hs = 0.659 # m
Fs = 0.1 # m^3/min
Tcs = 300 # K
F0s = 0.1 # m^3/min

xs = np.array([cs, Ts, hs])
us = np.array([Tcs, Fs])
ps = np.array([F0s])

CVs = [0, 2] # control concentration and height

# Simulate a few steps so we actually get dx/dt = 0 at steady-state
for i in range(10):
    xs = cstrsim(xs, us, ps).toarray().flatten()

cs = xs[0]
Ts = xs[1]
hs = xs[2]

# Get linearized model and linear controller
model = mpc.getLinearizedModel(ode_casadi, [xs, us, ps],
                               ['A', 'B', 'Bp'], Delta)
# measure only T and h
A = model['A']
B = model['B']
C = np.eye(Ny)
Bp = model['Bp']
Q = np.diag(1/(xs ** 2))
R = np.diag(1/(us ** 2))
K = -ct.dlqr(A, B, Q, R)[0]

# Pick whether to use good distrubance model
disturbancemodels = ['Good', 'Offset', 'Undetectable', 'No']
data = {}

for dmodel in disturbancemodels:
    print('Choosing disturbance model:', dmodel)
    if dmodel == 'Good':
        # distrubance model; no offset
        Nd = 3
        Bd = np.zeros((Nx, Nd))
        Bd[:,2] = B[:,1]
        Cd = np.array([[1, 0, 0],
                      [0, 0, 0],
                      [0, 1, 0]])
    elif dmodel == 'Offset':
        # disturbance model with offset
        Nd = 2
        Bd = np.zeros((Nx, Nd))
        Cd = np.array([[1, 0],
                      [0, 0],
                      [0, 1]])
    elif dmodel == 'Undetectable':
        Nd = 3
        Bd = np.zeros((Nx, Nd))
        Cd = np.eye(Ny, Nd)
    elif dmodel == 'No':
        Nd = 0
        Bd = np.zeros((Nx, Nd))
        Cd = np.zeros((Ny, Nd))
    else:
        raise ValueError('Unknown disturbance model')

    Aaug = np.block([[A, Bd],[np.zeros((Nd, Nx)), np.eye(Nd)]])
    Baug = np.vstack([B,np.zeros((Nd, Nu))])
    Caug = np.hstack([C,Cd])
    Naug = Aaug.shape[0]

    # Detectability test of disturbance model
    detect_matrix = np.vstack([np.eye(Naug) - Aaug, Caug])
    detec = np.linalg.matrix_rank(detect_matrix)

    if detec < Nx + Nd:
        print('***Augmented system is not detectable! \n')
        break

    # Set up state estimator; use Kalman filter
    Qw = np.zeros((Naug, Naug))
    Qw[:Nx, :Nx] = small * np.eye(Nx)
    Qw[Nx:, Nx:] = small * np.eye(Nd)
    Qw[-1, -1] = 1.0
    Rv = small * np.diag(xs ** 2)
    Daug = np.eye(Naug)
    L, Pe, _ = ct.dlqe(Aaug, Daug, Caug, Qw, Rv)
    L = np.linalg.inv(Aaug) @ L  # convert combined gain to corrector gain
    Lx = L[:Nx, :]
    Ld = L[Nx:, :]

    # Closed-loop simulation
    np.random.seed(123)
    Nsim = 50
    x = np.full((Nx, Nsim + 1), np.nan)
    x[:, 0] = 0.0
    y = np.full((Ny, Nsim + 1), np.nan)
    u = np.full((Nu, Nsim), np.nan)
    v = np.zeros((Ny, Nsim + 1))

    xhatm = x.copy()
    dhatm = np.full((Nd, Nsim + 1), np.nan)
    dhatm[:, 0] = 0.0

    xhat = np.full((Nx, Nsim), np.nan)
    dhat = np.full((Nd, Nsim), np.nan)

    xtarg = np.zeros((Nx, Nsim))
    utarg = np.zeros((Nu, Nsim))

    # Distrubance and setpoint
    p = np.zeros((Np, Nsim))
    p[:, 9:] = 0.1 * F0s
    ysp = np.zeros((Ny, Nsim))

    # Steady-state target matrices
    if len(CVs) > Nu:
        raise ValueError('At most 2 CVs can be specified!')
    H = np.eye(Ny)
    H = H[CVs, :]
    Ginv = np.linalg.solve(np.block([[np.eye(Nx) - A, -B], [H @ C, np.zeros((H.shape[0], Nu))]]), np.eye(Nx + Nu))

    # start loop
    for i in range(Nsim):
        # Take measurement
        y[:, i] = C @ x[:, i] + v[:, i]

        # Advance state measurement
        e = y[:, i] - C @ xhatm[:, i] - Cd @ dhatm[:, i]
        xhat[:, i] = xhatm[:, i] + Lx @ e
        dhat[:, i] = dhatm[:, i] + Ld @ e

        # use steady-state target selector
        targ = Ginv @ np.hstack([Bd @ dhat[:, i],H @ (ysp[:, i] - Cd @ dhat[:, i])])
        xtarg[:, i] = targ[:Nx]
        utarg[:, i] = targ[Nx:]

        # Apply control law
        u[:, i] = K @ (xhat[:, i] - xtarg[:, i]) + utarg[:, i]

        # Evolve plant. Out variables are deviation but cstrsim needs positional
        x[:, i + 1] = cstrsim(x[:, i] + xs, u[:, i] + us, p[:, i] + ps).toarray().flatten() - xs

        # Advance state estimate
        xhatm[:, i + 1] = A @ xhat[:, i] + B @ u[:, i] + Bd @ dhat[:, i]
        dhatm[:, i + 1] = dhat[:, i]

    # Convert to positional units
    u = u + us[:, np.newaxis]
    x = x + xs[:, np.newaxis]

    ysp = ysp + C @ xs[:, np.newaxis]
    ysp[[i for i in range(Ny) if i not in CVs], :] = np.nan # Mask out uncontrolled variables
    ysp = np.hstack([ysp, ysp[:, -1:]]) # Duplicate final point

    # Make a plot
    t = np.arange(Nsim + 1) * Delta
    if not os.getenv('OMIT_PLOTS') == 'true':
        mpc.plots.mpcplot(x, u, t, xsp=ysp, xnames=['c', 'T', 'h'],
                      unames=['T_c', 'F'], timefirst=False)
        plt.show()

    data[dmodel] = {}
    data[dmodel]['x'] = np.vstack([t, x]).T
    u = np.hstack([u, u[:, -2:-1]]) # Duplicate final point
    data[dmodel]['u'] = np.vstack([t, u]).T

gnuplotsave('cstr.dat', data)