Using adaptive time step for scipy.integrate.ode when solving ODE systems
<p>I have to just read <a href="http://stackoverflow.com/questions/12926393/using-adaptive-step-sizes-with-scipy-integrate-ode">Using adaptive step sizes with scipy.integrate.ode</a> and the accepted solution to that problem, and have even reproduced the results by copy-and-paste in my Python interpreter. </p>

<p>My problem is that when I try and adapt the solution code to my own code I only get flat lines.</p>

<p>My code is as follows:</p>

<pre><code>from scipy.integrate import ode
from matplotlib.pyplot import plot, show

initials = [1,1,1,1,1]
integration_range = (0, 100)

f = lambda t,y: [1.0*y[0]*y[1], -1.0*y[0]*y[1], 1.0*y[2]*y[3] - 1.0*y[2], -1.0*y[2]*y[3], 1.0*y[2], ]

y_solutions = []
t_solutions = []
def solution_getter(t,y): 
   t_solutions.append(t)
   y_solutions.append(y) 


backend = "dopri5"
ode_solver = ode(f).set_integrator(backend)
ode_solver.set_solout(solution_getter)
ode_solver.set_initial_value(y=initials, t=0)

ode_solver.integrate(integration_range[1])

plot(t_solutions,y_solutions)
show()
</code></pre>

<p>And the plot it yields:
<a href="http://i.stack.imgur.com/9Aki3.png" rel="nofollow"><img src="http://i.stack.imgur.com/9Aki3.png" alt="enter image description here"></a></p>

<p>In the line </p>

<pre><code>   y_solutions.append(y) 
</code></pre>

<p>you think that you are appending the current vector. What actally happens is that you are appending the object reference to <code>y</code>. Since apparently the integrator reuses the vector <code>y</code> during the integration loop, you are always appending the same object reference. Thus at the end, each position of the list is filled by the same reference pointing to the vector of the last state of <code>y</code>.</p>

<p>Long story short: replace with</p>

<pre><code>    y_solutions.append(y.copy()) 
</code></pre>

<p>and everything is fine.</p>

python python-3.x scipy ode