Software tutorial/Integration of ODEs
In our course we have learned several ways of integrating a single equation
However, we only coded Euler's method (because it was simple!), but not the others. These other methods have been (reliably) coded in software packages and sophisticated error correction tools built into their algorithms. You should always use these toolbox functions to integrate your differential equation models. In this section we will show how to use MATLAB and Python's built-in functions to integrate:
- a single differential equation
- a system of differential and algebraic equations.
We will only look at initial value problems (IVPs) in this tutorial.
MATLAB
MATLAB's has several ODE solvers available. You can read up more about the implementation details in this technical document.
Python
Like MATLAB, several integrators are available in Python. The integrator I will use in this tutorial is one of the most recent additions to SciPy - the VODE integrator developed at Lawrence Livermore National Laboratories in 1988. It is a good general-purpose solver for both stiff and non-stiff systems.
Example problem
The example we will work with is a common modelling reaction: a liquid-based stirred tank reactor, with (initially) constant physical properties, a second order chemical reaction where species A is converted to B according to
where
In the code below we will integrate the ODE from
MATLAB
In a file called tank.m: function dydt = tank(t, y)
% Dynamic balance for a CSTR
%
% C_A = y(1) = the concentration of A in the tank, mol/L
%
% Returns dy/dt = F/V*(C_{A,in} - C_A) - k*C_A^2
F = 20; % L/min
CA_in = 5.5; % mol/L
V = 100; % L
k = 0.24; % 1/min
% Assign some variables for convenience of notation
CA = y(1);
n = 1; % A single, first-order ODE
% The output from the ODE function must be a COLUMN vector, with n rows
dydt = zeros(n,1);
dydt(1) = F/V*(CA_in - CA) - k *CA^2;
In a separate file (any name), for example: ode_driver.m, which will "drive" the ODE solver: % Integrate the ODE
% -----------------
% Set the time range:
t_start = 0;
t_final = 5.0;
%options = odeset('RelTol',1e-4,'AbsTol',[1e-4 1e-4 1e-5]);
% Set the initial condition(s):
CA_t_zero = 3.2;
% Integrate the ODE(s):
[t, y] = ode45(@tank,[t_start, t_final], [CA_t_zero]);
% Plot the results:
clf;
plot(t, y)
grid('on')
xlabel('Time [minutes]')
ylabel('Concentration of A [mol/L]')
|
Python |
---|---|