You are on page 1of 6

PiE Matlab assessment

For Chemical Engineers.

General instructions
Report and codes: You must hand in individual reports. Present your results in a
report that includes short explanations of your approach, your answers to the questions
listed in this exam, and your interpretations of the plots and other output generated by
your codes. Please do not include full-length source code in the report; instead, use the
relevant segment(s) of the code to illustrate your point. The report should be a single
pdf file, containing all plots, tables and their captions. You are requested to write your
report, and the comments in your code, in English. We also want to receive your final
m-files, to test the performance of your codes. Do not forget to include your name and
student number in your report and all m-files. Please combine the report and m-files into
a single compressed archive file. Please submit you solution to canvas before the deadline
of Monday 29rd October 2018, 9:00. Each question is worth 5 marks, so to get a 6 or
higher most question must be attempted.

Grading: Your grade will be determined by the quality of your code, the quality of your
report, and the answer to the questions. Top grades are only awarded for perfect solutions
to all questions and very well organised and documented code.
Problem 1 : Solving chemical reactions
Solving ordinary differential equations is an often recurring task in engineering, as in most
quantitative sciences. Hence, a wide range of numerical techniques have been developed
to calculate approximate solutions to ordinary differential equations (ODE). Several of
these methods are briefly described in the hand-outs accompanying the lecture, including
a discussion of their strengths and weaknesses. In this exercise, you will program and
apply two algorithms to get a feeling of how they perform. It is good practice to try out
unfamiliar algorithms on familiar problems, so one can verify the results and assess their
accuracy. We here opt for chemical reactions.

Background
Consider the pair of chemical reactions that converts products, P, into reactants, R, and
vice versa,
kr
−−
P)−−*
− R.
− (1)
kf

The rate constants kf and kr of the forward and reverse reactions, respectively, determine
the fractions of products (reactants) turned into reactants (products) per unit of time,
dP
= −kf P + kr R, (2)
dt
dR
= kf P − kr R, (3)
dt
where P and R denote the concentrations (molars) of products and reactants, respectively,
and t is the time. Given the initial concentrations P (0) and R(0), the coupled solutions
P (t) and R(t) are in principle fully determined.
For the numerical approximation of the exact evolution, we will make use of two arrays1
for the calculated concentrations P[i] and R[i] of the mixture at a series of points in
time, t = i∆t, where ∆t denotes the time step and i an integer, 0 ≤ i ≤ MaxStep. The
evolving composition is calculated, step by step, using a numerical algorithm based on
the analytical expressions. This requires ‘discretization’ of these equations; that is, rather
than the infinitesimal time steps of differential calculus, we use a finite time step ∆t. By
discretizing Eqs (2) and (3), we arrive at

P[i + 1] = P[i] + (−kf ∗ P[i] + kr ∗ R[i]) ∗ DeltaT (4)


R[i + 1] = R[i] + (−kr ∗ R[i] + kf ∗ P[i]) ∗ DeltaT (5)

This is the first order forward Euler method.

Given: kf = 3 · 105 M/s and kr = 2 · 104 M/s. The temperature, and hence the rate
constants, are assumed constant. You are free to chose all other relevant quantities.

1
For clarity we will use the notational convention:
• Italics for analytical expressions and typewriter for (quasi-)program code.
• Numerical quantities always have a value that is equivalent, either exactly or approximately, to
that of the matching analytical quantity, e.g. DeltaT = ∆t and P[i] ≈ P (i∆t). Note that in some
languages arrays start at 1; in those cases, P[i + 1] ≈ P (i∆t).
• Functions have their argument between round brackets (. . .), arrays have their (integer) index
between square brackets [...].
Questions
1 Discuss how Eqs (4) and (5) follow from Eqs (2) and (3), and in what limit(s) these
discretizations can be applied.

2 The calculation of the concentrations requires a time step ∆t and a total simulation
length T = MaxStap ∗ ∆t. Make motivated orders of magnitude estimates for both,
based on the physical parameters of the problem.

3 It is good practice to think, in advance, of methods to test the correctness of your


numerical results.2 Propose at least one criterion to test the calculated trajectory.

4 Write a program to simulate the reaction mixture, based on Eqs (4) and (5).

5 Does the program pass the test(s) you proposed in question (3)? Did the test
criterion(s) make sense? Explore what happens when you vary the time step over
several orders of magnitude.

6 The only line that is readily recognize with the naked eye is a straight line. Plot
your data such that you get a straight line, without solving the reaction equations
analytically. Can you explain what happens at large times?
Fit this line (in the figure window under <tools> <basic fitting>, or use the fit
command) to extract the mixture’s relaxation rate.3 Do you recognize this value?

The so-called Runge-Kutta algorithms solve an ODE, like dy/dt = f (y, t), by calculating
y and f at several points within a time step ∆t. The idea is that the extra function
evaluations per time step increase the accuracy of the calculation for a given ∆t. Reversely,
the gain may also be used to increase the time step at a given accuracy.

7 Simulate the reaction mixture using matlab’s standard solver ode45. (You may want
to consult the provided brief examples on how to invoke this solver.) What strikes
you in the time array returned by this algorithm?

Consider a mixture containing the four components A, B, X and Y, subject to the reactions
X*
) A,
A*
) Y, (6)
A*
) B,

where all rates are set at k = 1 m/s exception kA→B = kB→A = 104 m/s and kY →A =
10−1 m/s. At t = 0 the system contains component X only. Equilibrium is reached at
about t = 30 s.
2
A code that fails the test is clearly incorrect. Note that, depending on the test, your program might
pass the test but still be at fault...
3
The quality of a fit can vary strongly with the approach taken. Do you minimize the absolute or the
relative differences between the set of data and fit curve? Matlab can fit any function through any set of
data, but does that imply that the data actually follow the function? The safest way is to manipulate the
data such that the fit function is a straight line – that is the only readily recognizable curve. It is always
wise to have a look at the differences between data and fit, to see whether they follow a pattern. When
using a complex fit function, be aware that the returned best-fit parameters might depend on the initial
values of these parameters.
8 How much time does it take ode45 to simulate this equilibration process?4 Create a
plot of the concentrations versus time, using markers, and zoom in on the lines for
A and B until you can cleary identify the individual markers. Can you explain what
you observe?

9 How much time does it take ode23s to simulate the same process? Create a plot of
the concentrations versus time, using markers, and discuss the difference with the
previous plot.

The analytic solution to this reaction system is obtained by constructing a column vector
C of all concentrations and a matrix K of all reaction rates, such that

Ċ = KC. (7)

This equation is solved by diagonalizing K, yielding four eigenvalues λi and a matrix S


whose columns are the corresponding eigenvectors. Then

C(t) = SΛ(t)S−1 C(0), (8)

where Λ(t) is a diagonal matrix containing exp(λi t).

10 Overlay the two numerical curves for A(t) with their theoretical counterpart, and
verify whether they agree by zooming in strongly. The analytic solution of the
equilibrium reads as

X : A : B : Y = 1 : 1 : 1 : 10. (9)

How much do the two numerical methods differ from this result? And how well do
they conserve the sum concentration?

Consider a mixture containing the five components A, B, X, Y and Z, subject to the


reactions
A → X,
2X + Y → 3X,
(10)
B + X → Y + B,
X → Z,
where for simplicity all forward rates are set at kf = 1 and the reverse reactions are
very slow, kr = 0. Assuming large surpluses of A and B,5 their concentrations remains
constant. Then
dX
= A + X 2 Y − BX − X, (11)
dt
dY
= − X 2 Y + BX. (12)
dt
11 Simulate the evolution of X and Y in this reaction mixture for A = 1 and for B
ranging form 1 to 3, and X(0) = Y (0) = 0. Create graphs of x and y versus t and
of X versus Y , and discuss what you conclude from these graphs.
4
Matlab provides tic and toc to measure elapsed time.
5
Please ignore that, due to the selected numerical values, the calculated concentrations are not in
agreement with this assumption.
12 Turn your program in to a function taking B as the argument and generate a plot
containing several curves of the relaxation to equilibrium, for 1 ≤ B ≤ 3, A = 1
and X(0) = Y (0) = 0. A convenient quantity to use is the Pythagorean distance in
the (X, Y ) plane to the equilibrium point, (A, B/A). How does the convergence rate
vary with B?

13 Explore what happens for A = 1 and B = 2.5 when the simulation is started at the
equilbrium point, (X, Y ) = (A, B/A). What happens when you slightly perturb this
starting point?

Problem 2 : Simulating atoms


Background
For this assessment you simulate the interaction of some simple atoms on a computer in the
context of N-body simulation; using the so-called Molecular Dynamics (MD) simulation
method. In MD, the atoms interact for a period of time, giving a view of the motion
of the atoms. The trajectories of atoms and molecules are determined by numerically
solving the Newton’s equations of motion for a system of interacting particles, where
forces between the particles and potential energy are defined by interatomic potentials or
molecular mechanics force fields. The method was originally conceived within theoretical
physics in the late 1950s but is applied today mostly in chemical physics, materials science
and the modelling of biomolecules.
Consider the particles (atoms) defined in the txt files Input1D-1.txt and Input1D-
2.txt. The input data files store information about particles: The format is initial x
location, initial u velocity, mass. For this assessment you will use the Lennard-Jones
potential to model the interactions between the particles. The Lennard-Jones potential
is a mathematically simple model that approximates the interaction between a pair of
neutral atoms or molecules.
For the Lennard-Jones potential the interaction between the particles i and j is mod-
elled using "   6 #
σ 12 σ
V (rij ) = 4 −
rij rij
where σ is the particle diameter. Set the materials parameters  = 1 and σ = 1. Moreover
rij denotes the distance between the particles i and j.

The interaction force acting between the particles i and j, fij , is obtained as the derivative
of the potential V (rij ) with respect to rij i.e.

dV (rij )
fij = − n̂ij
drij

where n̂ij is the unit vector between the particles. Thus the equation that defines the
motion for the particle i is given by
N
X
mi ẍi = fij , (13)
j=1 j6=i

where N is the total number of particles.


Questions
1. Plot the potential Vij as a function of the distance rij . Plot separately both the
attractive and repulsive contribution.

2. Use symbolic differentiation from the matlab symbolic toolbox to derive the magni-
tude of the force as a function of rij .

3. Plot the force fij as a function of the distance rij .

4. Write two matlab functions that solve the differential equations, for a 1D system of
particles, using Euler Forward algorithm and the Verlet algorithm. Euler Forward

x(t + ∆t) = x(t) + ẋ(t)∆t

ẋ(t + ∆t) = ẋ(t) + ẍ(t)∆t


Verlet algorithm

x(t + ∆t) = −x(t − ∆t) + 2x(t) + ẍ(t)∆t2

x(−∆t) = x(0) − ẋ(0)∆t


The functions should accept any of the input files and produce the following output:

(a) Determine the position of the particles during the time interval [0,20] using
∆t = 0.005. Print to a file the position and velocity of all particles at each time
step.
(b) Compute both the kinetic and potential energy of the system at each time step
and print the data to a file. Also compute the total (kinetic + potential) energy.
Note, potential energy is per interaction, not per atom.
(c) Comment on which algorithm you prefer and state why?

5. Write a MATLAB file that

(a) Reads in the data you printed in the files and plot the energies as a function of
time.
(b) Read in the data you printed in the files and make movies where you visualise
the positions of all the particles overtime. The colour of the particles should
change according to their current speed. Plot particles with physical size. Hint
patch or fill command.

You might also like