【问题标题】:How to include derivative inside scipy odeint?如何在 scipy odeint 中包含导数?
【发布时间】:2013-11-16 01:25:00
【问题描述】:

当我在一个简单的微分方程中包含一个导函数时,我不断收到一长串错误,如下面的代码所示。我做错了什么?

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]

错误输出中似乎重复了好几次的小片段如下:

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

编辑:上述代码在 scipy 0.9.0 中运行没有错误,但在 0.12.0 中出现上述错误

Edit2:既然错误已经解决,我需要在积分器中添加第二个函数,如下所示:

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]

我该怎么做?

【问题讨论】:

标签: python odeint


【解决方案1】:

derivative 的第一个参数必须是函数,而不是 ndarray。所以你必须用函数Ip替换ndarrayIp

以下示例适用于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])

【讨论】:

  • 感谢您的回复。这对我不起作用(python 2.7,scipy 0.9.0)。我收到以下错误: Traceback(最近一次调用最后一次):文件“C:\Windows\system32\config\systemprofile\Desktop\ct_example.py”,第 53 行,在 f f0 = (dI(t)/N) -Rb*y[0] TypeError: unsupported operand type(s) for /: 'NoneType' and 'float' odepack.error: 调用名为 f 的 Python 函数时发生错误
  • 奇怪,在我的机器上它也运行 python 2.7 和 scipy 0.9。你的 numpy 版本是什么?也许,您应该将 numpy 和 scipy 都更新到最新版本。
  • 我下载了最新版本的WinPython,代码运行良好。谢谢。
  • 对不起,我不明白,你想达到什么目的。我想你应该为你的第二次编辑创建一个新问题,因为这个问题已经被标记为已解决,没有人会再看它了。
  • 按照@Holger 的建议,我已经将它作为一个新问题发布了here
猜你喜欢
  • 1970-01-01
  • 2015-12-03
  • 2019-01-22
  • 1970-01-01
  • 1970-01-01
  • 2013-10-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-18
相关资源
最近更新 更多