amaity
amaity

Reputation: 267

How to include derivative inside scipy odeint?

I am keep getting a long list of errors when I include a derivative function in a simple differential equation as illustrated in the following code. What am I doing wrong?

import numpy as np
from scipy.misc import derivative
from scipy.integrate import odeint

Imag = 16000.
w = 2*np.pi*60
tau = .05
theta = 1.52
phi = theta - np.radians(90)
t = np.linspace(0,.1,10000)
Ip = np.sqrt(2)*Imag*(np.sin(w*t+phi-theta)-np.exp(-t/tau)*np.sin(phi-theta))

def dI(t):
    return derivative(Ip,t)

def f(y,t):
    Rb = 8.
    N = 240.
    Is = y[0]
    f0 = (dI(t)/N)-Rb*y[0]
    return [f0]

yinit = [0]
sol = odeint(f,yinit,t)
print sol[:,0]

A small fragment of the error output that seems to be repeated several times is as follows:

val += weights[k]*func(x0+(k-ho)*dx,*args)
TypeError: 'numpy.ndarray' object is not callable
odepack.error: Error occurred while calling the Python function named f

Edit: The above code runs without errors in scipy 0.9.0 but gives the above error in 0.12.0

Edit2: Now that the error has been taken care of, I need to add a second function into the integrator as follows:

B = lambda Ip: Ip/(53.05+0.55*abs(Ip))
L = lambda Ip: derivative(B,Ip)*377.2

def f(y,t):
    Rb = 8.
    N = 240.
    Is = y[0]
    f0 = (1/(L+0.002))*((dI(t)*L/N)-Rb*y[0])
    return [f0]

How do I do it?

Upvotes: 0

Views: 2123

Answers (1)

Holger
Holger

Reputation: 2175

The first argument of derivative has to be a function not an ndarray. So you have to replace the ndarray Ip with a function Ip.

Following exapmple works with Python3:

import numpy as np
from scipy.misc import derivative
from scipy.integrate import odeint

def Ip(t):
    return np.sqrt(2)*Imag*(np.sin(w*t+phi-theta)-np.exp(-t/tau)*np.sin(phi-theta))

Imag = 16000.
w = 2*np.pi*60
tau = .05
theta = 1.52
phi = theta - np.radians(90)
t = np.linspace(0,.1,10000)

def dI(t):
    return derivative(Ip,t)

def f(y,t):
    Rb = 8.
    N = 240.
    Is = y[0]
    f0 = (dI(t)/N)-Rb*y[0]
    return [f0]

yinit = [0]
sol = odeint(f,yinit,t)
print(sol[:,0])

Upvotes: 1

Related Questions