Figure 5.17:

Deterministic simulation of reaction A + B <-> C compared to stochastic simulation.

Code for Figure 5.17

Text of the GNU GPL.

main.m


 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
% Copyright (C) 2001, James B. Rawlings and John G. Ekerdt
%
% This program is free software; you can redistribute it and/or
% modify it under the terms of the GNU General Public License as
% published by the Free Software Foundation; either version 2, or (at
% your option) any later version.
%
% This program is distributed in the hope that it will be useful, but
% WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
% General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program; see the file COPYING.  If not, write to
% the Free Software Foundation, 59 Temple Place - Suite 330, Boston,
% MA 02111-1307, USA.

%
% add a stochastic simulation using Gillespie's algorithm
%
% example 1: A + B  --> C
%            C      --> A + B
%
nmolec = 400;
k1 = 1;
k2 = 1;
k(1) = k1/(nmolec);
k(2) = k2;
stoi = [-1 -1 1; 1 1 -1];
[nrxs,nspec]=size(stoi);
clear x
x(1,1)= nmolec;
x(2,1)= 0.9*nmolec;
x(3,1)= 0*nmolec;
stoiT = stoi';
nsim = nmolec*4;
clear time;
time = zeros(nsim+1,1);
time(1) = 0;
rng(0);
for n=1:nsim
  r(1) = k(1)*x(1,n)*x(2,n);
  r(2) = k(2)*x(3,n);
  rtot = sum(r);
  p=rand(2,1);
  tau = -log(p(1))/rtot;
  time(n+1)=time(n)+tau;
  %
  % determine which reaction (mth) is likely to occur
  %
  rcum = 0;
  m = 0;
  while ( rcum <= p(2)*rtot)
    m = m + 1;
    rcum = rcum + r(m);
  end
  x(:,n+1) = x(:,n) + stoiT(:,m);
end
%
% scale  so ca0=1;
%
xscale = x ./ x(1,1);
%plot(time,xscale')
%
% make a deterministic comparison for nonlinear example 1.
%
ca0 = x(1,1)/x(1,1);
cb0 = x(2,1)/x(1,1);
cc0 = x(3,1)/x(1,1);
timedet = [0; (logspace (-4,1,100)')];
k1det = k1;
k2det = k2;
p = struct();
p.ca0 = ca0; p.cb0=cb0; p.cc0=cc0; p.k1det=k1det; p.k2det=k2det;

%
% analytical if k2det = 0
%
% delc = ca0-cb0;
% ca = delc ./ ( 1 - cb0/ca0 .* exp(-delc*k1det .* timedet));
% cb = ca - delc;
% cc = - ca + ( cc0 + ca0);
ca = lsode(@(x, t) f(x, t, p), ca0, time);
cb = ca - ca0 + cb0;
cc = cc0 + ca0 - ca;
%plot(timedet, [ca,cb,cc])
table = [time xscale' ca cb cc];
save stochnon.dat table;

plot(table(:,1),table(:,2:7));
axis ([0,5,0,1])

f.m


1
2
3
4
5
function xdot = f(x, t, p)
  ca = x(1);
  cb = ca - p.ca0 + p.cb0;
  cc = p.cc0 + p.ca0 - ca;
  xdot(1) = - p.k1det*ca*cb + p.k2det*cc;