Computational Methods: A.1 Linear Algebra and Least Squares
Computational Methods: A.1 Linear Algebra and Least Squares
Computational Methods
www.nobhillpublishing.com
www.che.wisc.edu/~jbraw/chemreacfun
In this section we briefly introduce Octave and MATLAB, and show how to
enter reaction networks quickly and perform linear algebra operations
of interest.
After starting an Octave session, type doc and select menu item
Introduction at the Octave prompt or demo at the MATLAB prompt
for information on how to enter matrices and perform matrix multi-
plication. Consider again the water gas shift reaction chemistry, for
634
A.1 Linear Algebra and Least Squares 635
example,
H
H2
0 1 0 −1 −1 1 0
OH
−1 1 1 −1 0 0 = 0
H2 O
1 0 −1 0 −1 1 0
CO
CO2
octave:1> stoi=[0 1 0 -1 -1 1; -1 1 1 -1 0 0; \
1 0 -1 0 -1 1];
octave:2> rank(stoi)
ans = 2
octave:3> r=[1;2;3];
octave:4> R=stoi’*r
R =
1
3
-1
-3
-4
4
r = (ν νT )−1 νR
r = stoi’ \ R
2.1
2.05
r2 2
1.95
1.9
0.9 0.95 1 1.05 1.1
r1
Solution
The Octave commands to generate these results are
stoi = [0 1 0 -1 -1 1; -1 1 1 -1 0 0];
[nr, nspec] = size(stoi);
r = [1;2];
R = stoi’*r;
nmeas = 2000;
for i = 1:nmeas
R_meas(:,i) = 0.05*randn(nspec, 1) + R;
end
r_est = stoi’ \ R_meas;
A.2 Nonlinear Algebraic Equations and Optimization 637
Figure A.1 shows the estimates. We know from Chapter 9 that the
distribution of estimates is a multivariate normal. We also know how
to calculate the α-level confidence intervals.
function y = f(x)
y = x*x;
endfunction
The first line states that the value of the variable y is returned by in-
voking the function named f with the input value x. The body of the
function, then, is the calculation of the value of y to be returned. As
the computational complexity of the function increases, we would like
638 Computational Methods
to store our work so that it does not need to be reentered at the be-
ginning of each subsequent Octave session. Storing, documenting and
maintaining the calculations performed in solving complex industrial
problems is one of the significant challenges facing practicing chemical
engineers. Even for our purposes, we should be able to store and edit
our computational problems. Octave commands and function defini-
tions can be stored in text files, called m-files; the naming convention
is filename.m. Editing these files with a text editor during an inter-
active Octave session provides a convenient means for debugging new
calculations.
P K1 yI yB − yP1 = 0
P K2 yI yB − yP2 = 0
in which yI , yB , yP1 , yP2 are defined in terms of the two reaction extents
in Equations 3.66. An Octave function defining these two equations is
The fsolve function requires the name of the function, following the @
sign, and an initial guess for the unknown extents, provided in the vari-
able x0, and returns the solution in x and a flag info indicating if the
calculation was successful. It is highly recommended to examine these
information flags after all calculations. Reactor equilibrium problems
can be numerically challenging, and even the best software can run into
problems. After the function dgdx is defined, the following is a typical
session to compute the solution given in Example 3.5
octave:1> x0=[0.2;0.2];
octave:2> [x,info] = fsolve(@dgdx,x0)
x =
0.13317
0.35087
info = 1
The value of info = 1 indicates that the solution has converged.
The minimization of this function of εi0 then determines the two equi-
librium extents. Figure A.2 shows the lines of constant Gibbs energy
determined by Equation A.2 as a function of the two reaction extents.
We see immediately that the minimum is unique. Notice that G̃ is not
defined for all reaction extents, and the following constraints are re-
quired to ensure nonnegative concentrations
0 ≤ ε10 0 ≤ ε20 ε10 + ε20 ≤ 0.5
We proceed to translate this version of the equilibrium condition
into a computational procedure. First we define a function that evalu-
ates G̃ given the two reaction extents.
640 Computational Methods
0.5
−2.559
-2.55
-2.53
0.4 -2.5
-2
-1
0
0.3
ε20
0.2
0.1
0
0 0.1 0.2 0.3 0.4 0.5
ε10
function retval=gibbs(x)
dg1= -3.72e3; dg2= -4.49e3; T=400; R=1.987; P=2.5;
K1 = exp(-deltag1/(R*T)); K2 = exp(-deltag2/(R*T));
yI0 = 0.5; yB0 = 0.5; yP10 = 0; yP20 = 0;
d = 1 - x(1) - x(2);
yI = (yI0 - x(1) - x(2)) / d;
yB = (yB0 - x(1) - x(2)) / d;
yP1 = (yP10 + x(1)) / d;
yP2 = (yP20 + x(2)) / d;
retval = - (x(1)*log(K1)+x(2)*log(K2)) + ...
(1-x(1)-x(2))*log(P) + yI*d*log(yI) + ...
yB*d*log(yB) + yP1*d*log(yP1) + yP2*d*log(yP2);
endfunction
in which x0 is the initial guess as before and the new variables are
used to define the constraints (if any). The variable lb provides lower
A.3 Differential Equations 641
bounds for the extents and ub provides upper bounds for the extents.
These are required to prevent the optimizer from “guessing” reaction
extent values for which the Gibbs energy function is not defined. For
example, consider what the gibbs function returns given negative re-
action extents. Finally, we specify the sum of extents is less than 0.5
with the A and b arguments, which define linear inequality constraints
of the form
Ax ≤ b
Aeq x = beq
0.13317
0.35087
obj = -2.5593
info = 2
In this case, the value of info = 2 indicates that the solution has con-
verged, and the results are in good agreement with those computed
using the algebraic approach, and the Gibbs energy contours depicted
in Figure A.2.
Optimization is a powerful tool for solving many types of engineer-
ing modeling and design problems. We also rely heavily on optimiza-
tion tools in Chapter 9 on parameter estimation.
dx
= f (x)
dt
x(0) = x0
doc
Differential Equations
help ode15s
dx
= f (x, t)
dt
644 Computational Methods
In MATLAB on the other hand, the function defining the right-hand side
for ode15s has to be of the form
Notice that the order of the time argument, volume, and state argu-
ment, ext, have been reversed compared to the Octave convention.
Even though the function seldom requires the argument volume, it
must be present in the argument list in MATLAB.
We can enhance compatibility by defining an interface (or wrapper)
in Octave with the name ode15s. The octave interface ode15s allows
the user to follow the MATLAB convention for the right-hand side func-
tion, and calls lsode to solve the differential equations. The advan-
tage is that the same user’s code works correctly inside Octave and
MATLAB. But the user should be aware that the solver lsode, which is a
variable order predictor/corrector method, is being invoked when call-
ing ode15s in Octave while the solver ode15s in MATLAB is a different
method [7]. The choice of solution method should be transparent to the
user as long as both methods are solving the problem accurately. But
when the user encounters numerical difficulties on challenging prob-
lems, which is expected no matter what numerical tools one is using,
knowing what is actually underneath the hood becomes important in
diagnosing and fixing the problem. If we wish to solve the ODEs by
calling the wrapper instead of lsode directly, then we change the line
to
Notice that ode15s returns the times (volumes) at which the solution
was found vsolver in the first argument and the solution x as the
second argument in the output. Comparing lsode and ode15s input
A.3 Differential Equations 645
argument lists, we also see that the initial condition x0 and times (vol-
umes) at which output is desired vout are also switched. The code
posted at www.che.wisc.edu/~jbraw/chemreacfun for Figures 4.20
or 4.21 show the complete solution for Example 4.5 using ode15s.
Table A.1 provides a list of some Octave compatibility functions that
are available. Notice that the nonlinear optimizer fmincon already dis-
cussed is a wrapper of the successive quadratic programming method
sqp provided in Octave by John Eaton.
Some reactor models require a more general structure than the ODE,
dx/dt = f (x, t). The nonconstant density, nonconstant volume semi-
batch and CSTR reactors in Chapter 4 are more conveniently expressed
as differential-algebraic equations (DAEs). To address these models,
consider the more general form of ODEs
0 = f (dx/dt, x, t) (A.3)
These are known as implicit ODEs because one may not be able to solve
this model for dx/dt explicitly. Differential algebraic equations (DAEs)
are of the form
dx
= f (x, y)
dt
0 = g(x, y)
Notice that when this function returns zero for res, the variables extdot
and ext satisfy the differential equation. With this function defined,
we then solve the model by calling daspk
x0=[0;0]; xdot0 = [0;0];
vout = linspace(0,1600,50)’;
[x, xdot] = daspk(@benz_pyrol, x0, xdot0, vout);
Notice that both the state x and state time (volume) derivative xdot are
returned at the specified times (volumes) vout.
For compatibility with MATLAB’s implicit ODE solver, ode15i, Octave
provides a wrapper function with this name. The differences are that
arguments are in a different order in the function defining the residual
function resid = benz pyrol mat(volume, x, xdot)
We often need to stop ODE solvers when certain conditions are met.
Two examples are when we have reached a certain conversion, and
when we have created a new phase of matter and need to change the
ODEs governing the system. The program dasrt enables us to stop
when specified conditions are met exactly. The following code illus-
trates how to find the PFR volume at which 50% conversion of benzene
is achieved. The user provides one new function, stop, which the ODE
solver checks while marching forward until the function reaches the
value zero. The PFR volume is found to be VR = 403.25 L, in good
agreement with Figure 4.20.
function val = stop(ext, volume)
global NBf xBstop
NB = NBf - 2*ext(1) - ext(2);
xB = 1 - NB/NBf;
val = xBstop - xB;
endfunction
with
opts = odeset (’Events’, @stop_mat);
[vstop,x] = ode15i(@benz_pyrol_mat,vout,x0,xdot0,opts);
The opts flag ’Events’ tells ode15i to look for stopping conditions as
zeros of function stop mat. Note that the function stop mat requires
the arguments in the following order
function val = stop(volume, ext)
The sensitivities, S, are defined as the change in the solution with re-
spect to the model parameters
!
∂xi
Sij =
∂θj θk≠j
∂x
S= T
∂θ
We can differentiate the Sij to obtain
" #
dSij d ∂xi ∂ dxi ∂
= = = fi (x; θ)
dt dt ∂θj ∂θj dt ∂θj
Using the chain rule to perform the final differentiation gives
! ! !
∂fi X ∂fi ∂xk ∂fi
= + (A.4)
∂θj θk≠j k
∂xk xl≠k ,θj ∂θj θk≠j ∂θj xl ,θk≠j
Substituting this back into Equation A.4 and writing the sum as a matrix
multiply yields
dS
= fx S + fθ
dt
in which the subscript denotes differentiation with respect to that vari-
able. Notice the sensitivity differential equation is linear in the un-
known S. The initial conditions for this matrix differential equation is
easily derived from the definition of S
∂xi (0) ∂gi
Sij (0) = =
∂θj ∂θj
dS
= fx S + fθ
dt
S(0) = gθ
A.4 Sensitivities of Differential Equations (paresto) 649
Notice that if none of the initial conditions are parameters for which
one is computing sensitivities, then S(0) = 0.
Solution
1. Equation A.5 is our standard, first-order linear equation, whose
solution is
cA = cA0 e−kt
fx = −k fθ = −cA gθ = 0
dS1
= −kS1 − cA
dt
S1 (0) = 0
650 Computational Methods
1.5
1
cA
0.5
S2
0
−0.5 S1
−1
0 1 2 3 4 5
t
This equation is linear and can be solved with the method used in
the series reactions in Chapter 4, or with Laplace transforms as
in Exercise 4.6. The result is
which agrees with Equation A.6. The functions cA (t), S1 (t) are
shown in Figure A.3.
dS2
= −kS2
dt
S2 (0) = 1
ca0 = 2; k = 1; tfinal = 5;
nts = 100; tout = linspace(0,tfinal,nts)’;
model = struct;
model.x = {’ca’};
model.p = {’k’};
model.d = {’dummy’};
model.tout = tout;
model.ode = @(t, y, p) {-p.k*y.ca};
% dummy objective function; just finding sensitivities
model.lsq = @(t, y, p) {y.ca};
pe = paresto(model);
theta0 = thetaac;
lbtheta = theta0;
ubtheta = theta0;
c
dc
X
= Aij cj
dr ri
j
r1 r2 r3 r4 r5
Figure A.4: Function c(r ) and its values at five collocation points.
Derivatives and integrals of the polynomial interpolant
are linear combinations of the function values at the
points.
The strings ’left’ and ’right’ specify that we would like to have col-
location points at the endpoints of the interval in addition to the zeros
of the orthogonal polynomial. We solve for the concentration profile
for the reaction-diffusion problem in a catalyst pellet to illustrate the
collocation method.
c = 1, r =3
dc
= 0, r =0
dr
2. Plot the concentration profile for nc = 5, 10, 30 and 50. How many
collocation points are required to reach accuracy in the concen-
tration profile for this value of Φ.
654 Computational Methods
1
nc = 50
nc = 30
0.8 nc = 10
nc =5
0.6
0.4
c
0.2
-0.2
-0.4
0 0.5 1 1.5 2 2.5 3
r
Solution
First we perform the differentiation in Equation A.8 to obtain
d2 c 2 dc
+ − Φ2 c = 0
dr 2 r dr
We define the following Octave function to evaluate this equation at the
interior collocation points. At the two collocation endpoints, we satisfy
the boundary conditions dc/dr = 0 at r = 0 and c = 1 at r = 3. The
function is therefore
100
10−2
10−4
10−6
η error
10−8
10−10
10−12
10−14
5 10 15 20 25 30
nc
2
A -→ B r = kcA
656 Computational Methods
10
7
NA (mol/s)
1 1 1
5 η= −
Φ tanh 3Φ 3Φ
1
4 η=
Φ
3
2
0 50 100 150 200 250 300 350 400
VR (L)
2.8
2.6
NA (mol/s)
2.4
2.2
2
300 320 340 360 380 400
VR (L)
Solve the model exactly and compare the numerical solution to the so-
lution obtained with the approximate Thiele modulus and effectiveness
factor approaches shown in Figure 7.26.
Solution
The model for the fluid and particle phases can be written from Equa-
tions 7.67–7.77
dNA Sp dceA
= RA = −(1 − B ) DA
dV Vp dr r =R
d2 ceA 2 dceA R
eA
2
+ + =0
dr r dr DA
ceA = cA r =R
dceA
=0 r =0
dr
The collocation method produces algebraic equations for the pellet pro-
file as for the previous example. We use a DAE solver to integrate the
differential equation for NA and these coupled algebraic equations.
The results for NA versus reactor length using 25 collocation points
for the pellet are shown in Figure A.7. Also shown are the simplified
effectiveness factor calculations for this problem from Example 7.5. A
magnified view is shown in Figure A.8. Notice the effectiveness factor
approach gives a good approximation for the bed performance. It is
not exact because the reaction is second order.
0.8
0.6
cA
cj cB
cC
0.4
0.2
0 1 2 3 4 5
t
0.8
0.6
cA
cj cB
cC
0.4
0.2
0 1 2 3 4 5
t
Solution
For this problem we require only the following simple paresto options.
model.ode = @massbal_ode;
model.lsq = @(t, y, p) {y.ca-y.m_ca, y.cb-y.m_cb, y.cc-y.m_cc};
tfinal = 6;
nplot = 75;
tplot = linspace(0, tfinal, nplot)’;
y_noisy(isnan(y_noisy)) = 0.;
% use index of measurement times in objective
model.lsq_ind = meas_ind’;
We also require the function massbal ode to define the right-hand side
of the differential equations
Running the ABC.m file produces the following parameter estimates and
confidence intervals.
" # " # " #
2.02 0.0977 2
θ=
b ± θ0 =
0.998 0.0357 1
The estimates are close to the true values θ0 used to generate the data.
The confidence intervals are reasonably tight given the three species
measurements with the noise level indicated in Figure A.9. The fit of
the model using the estimated parameters is shown in Figure A.10.
A.7 Exercises 661
A.7 Exercises
-* CO2 + H2
H2 O + CO )-
-* H2 + OH
H2 O + H )-
-* CO2 + H
OH + CO )-
Take the second and third reactions as an independent set and estimate the reaction
rates from the same 2000 production-rate measurements used in Example A.1.
(a) What value of [r2 r3 ] produces the error-free production rate corresponding to
[r1 r2 ] = [1 2]
(b) Create 2000 production-rate data points with measurement noise as in Exam-
ple A.1. Estimate [r2 r3 ] from these data and plot the result. Compare to Fig-
ure A.1. Explain the differences and similarities in the two figures.
(b) Calculate the solution for both addition policies and compare your numerical
result to the analytical result in Figures 4.15-4.18.
dcA 2
= −kcA
dt
cA (0) = cA0
Note: instead of solving the sensitivity differential equation, show only that the sen-
sitivity computed by taking the partial derivative of the solution to the differential
equation, cA (t), satisfies the sensitivity differential equation and initial condition.
1.2
A
1
0.8
B
0.6
c
0.4
γ = 30
β = 0.6
Φ = 0.001
0.2 C
-0.2
0 0.5 1 1.5 2 2.5 3
(b) Compare and contrast your c(r ) solutions to those in Figure A.11.
c = 1, r =q+1
dc
= 0, r =0
dr
(a) Solve the problem with the shooting method for the first-order reaction in a
spherical geometry, n = 1, q = 2, using Φ = 0.1, 1, 10, 50. Compare c(r ) from
the shooting method with the analytical solution.
A.7 Exercises 663
(b) Solve the problem using the collocation method. Which method do you prefer
and why?
w = ln(c)
Write the model and boundary conditions in the new variable, w. Solve the trans-
formed model with the collocation method. Compare the collocation solution
of the transformed model to the solution of the original model.
[4] J. W. Eaton. Octave: Past, present and future. In K. Hornik and F. Leisch,
editors, Proceedings of the 2nd International Workshop on Distributed
Statistical Computing, March 15-17, 2001, Technische Universität Wien,
Vienna, Austria, 2001. http://www.ci.tuwien.ac.at/Conferences/DSC-
2001/Proceedings/, ISSN 1609-395X.
[7] L. F. Shampine and M. W. Reichelt. The Matlab ODE suite. SIAM J. Sci.
Comp., 18(1):1–22, January 1997.
664