[SciPy-user] integrate.odeint and event handling

Christopher W. MacMinn cmac@mit....
Wed Jan 21 11:44:02 CST 2009

Hello -

I was wondering if integrate.odeint offers any event handling  

For example, say that I want to solve the simple ODE df/dt=f-2 with  
f(t=0)=1.  Also, say that I want to stop the integration when f=0,  
maybe because I don't care about negative values of f, or maybe  
because what I really want to know is the value of t when f=0.  (The  
analytical solution is f(t) = 2-exp(t), and f=0 at t=ln(2).)

The MATLAB code below will produce the desired solution.  It will stop  
integration when f=0, and I believe it will also integrate with some  
care near f=0.  Additionally, MATLAB returns the vector of times at  
which the solution is evaluated, so I can easily grab the value of t  
when f=0.

% ---------------------------------------------------------
function [ts,fs] = ode_with_events()

    function dfdt = df(t,f)
        dfdt = f-2.;

    function [value,isterminal,direction] = df_events(t,f)
        value = f;
        isterminal = 1;
        direction = 0;

    f0 = 1.;
    t0 = 0.;
    t_max = 5.;
    options = odeset('events',@df_events);
    [ts,fs] = ode45(@df,[t0,t_max],f0,options);

% ---------------------------------------------------------

The Python code below integrates the ODE just fine, but is there a way  
to get the "event" functionality described above?

# ---------------------------------------------------------
import numpy as np
from scipy import integrate

def ode_with_events():

    def df(f,t):
        return f-2.

    f0 = 1.
    t0 = 0.
    t_max = 5.
    ts = np.linspace(t0,t_max,100)
    fs = integrate.odeint(df,f0,ts)

    return ts,fs
# ---------------------------------------------------------


Best, Chris

More information about the SciPy-user mailing list