python - 使用 Python PyDDE 求解器求解微分方程

标签 python differential-equations

我正在尝试使用 python 包 PyDDE 求解以下微分方程:

dy[i]/dt = w[i] + K/N * \sum{j=1toN} sin(y[j] -y[i]), where i = 1,2,3,4...N=50

下面是求解这个方程的python代码

from numpy import random, sin, arange, pi, array, zeros
import PyDDE.pydde as p

def odegrad(s, c, t):
    global N
    K = c[0]
    theta = s[0]
    w = random.standard_cauchy(N)
    for i in range(N):
        coup_sum = 0.0
        for j in range(N):
            coup_sum += sin(theta[j] - theta[i])
        theta[i] = w[i] + (K*coup_sum)/(float (N))
    return array([theta])

# constant parameters
global N
N = 50
K = 1.0
# initial values for state theta
theta0 = zeros(N, float)
for i in range(N):
    theta0[i] = random.uniform(0, 2*pi)

odecons = array([K])
odeist = array([theta0])
odestsc = array([0.0])

ode_eg = p.dde()
ode_eg.dde(y=odeist, times=arange(0.0, 300.0, 1.0), 
       func=odegrad, parms=odecons, 
       tol=0.000005, dt=1.0, hbsize=0, nlag=0, ssc=odestsc)
ode_eg.solve()
print ode_eg.data

我收到以下错误:

DDE 错误:出了点问题:可能提供的变量之一的类型错误?

DDE 错误:问题初始化失败!

DDE 错误:DDE 未正确初始化!

最佳答案

所以我查看了内部发生的情况,以及两个错误

DDE Error: Something is wrong: perhaps one of the supplied variables has the wrong type?
DDE Error: Problem initialisation failed!

来自以下操作失败:map(float,initstate)(参见 source ,第 162 行)。这是因为 Y 和您的其他变量是向量。这主要意味着你不应该使用 array([theta]) 但你应该使用 theta

完整脚本:

from numpy import random, sin, arange, pi, array, zeros
import PyDDE.pydde as p

def odegrad(s, c, t):
    global N
    K = c[0]
    #Change here
    theta = s
    w = random.standard_cauchy(N)
    for i in range(N):
        coup_sum = 0.0
        for j in range(N):
            coup_sum += sin(theta[j] - theta[i])
        theta[i] = w[i] + (K*coup_sum)/(float (N))
    #Change here
    return theta

# constant parameters
global N
N = 50
K = 1.0
# initial values for state theta
theta0 = zeros(N, float)
for i in range(N):
    theta0[i] = random.uniform(0, 2*pi)

odecons = array([K])
#Change here
odeist = theta0
odestsc = array([0.0])

ode_eg = p.dde()
ode_eg.dde(y=odeist, times=arange(0.0, 300.0, 1.0), 
       func=odegrad, parms=odecons, 
       tol=0.000005, dt=1.0, hbsize=0, nlag=0, ssc=odestsc)

#You should not use this line, as the last step in ode_eg.dde() is solve.
#ode_eg.solve()
print ode_eg.data

关于python - 使用 Python PyDDE 求解器求解微分方程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25926957/

相关文章:

python - Pandas 在多列上搜索子字符串

python - 将 pyaudio 安装到 docker 容器

python - 使用 scipysolve_ivp 作为带有额外参数的函数

plot - 一张图中的方向场、微分方程和解

python - 将 python 对象 __str__ 写入文件

python - 从 HDF5 文件中序列化和检索大量 numpy 数组的快速有效的方法

python - 如何用Python访问网络?

c++ - 停止与推力一起使用的 odeint 集成

performance - numpy:评估矩阵中的函数,使用前一个数组作为计算下一个数组的参数

python - Scipy 的 solve_bvp 和耦合微分方程的性能问题