*** Yet another way to parameterize an ODE
:PROPERTIES:
:categories: ODE
:date: 2013/02/27 14:31:44
:updated: 2013/02/27 14:31:44
:END:
[[http://matlab.cheme.cmu.edu/2011/11/06/yet-another-way-to-parameterize-an-ode/][Matlab post]]
index:ODE!parameterized
We previously examined a way to parameterize an ODE. In those methods, we either used an anonymous function to parameterize an ode function, or we used a nested function that used variables from the shared workspace.
We want a convenient way to solve $dCa/dt = -k Ca$ for multiple values of $k$. Here we use a trick to pass a parameter to an ODE through the initial conditions. We expand the ode function definition to include this parameter, and set its derivative to zero, effectively making it a constant.
#+BEGIN_SRC python
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
def ode(F, t):
Ca, k = F
dCadt = -k * Ca
dkdt = 0.0
return [dCadt, dkdt]
tspan = np.linspace(0, 4)
Ca0 = 1;
K = [2.0, 3.0]
for k in K:
F = odeint(ode, [Ca0, k], tspan)
Ca = F[:,0]
plt.plot(tspan, Ca, label='k={0}'.format(k))
plt.xlabel('time')
plt.ylabel('$C_A$')
plt.legend(loc='best')
plt.savefig('images/ode-parameterized-1.png')
plt.show()
#+END_SRC
#+RESULTS:
[[./images/ode-parameterized-1.png]]
I do not think this is a very elegant way to pass parameters around compared to the previous methods, but it nicely illustrates that there is more than one way to do it. And who knows, maybe it will be useful in some other context one day!