在Python中集成耦合微分方程

时间:2015-12-15 17:22:39

标签: python scipy ode integrate

我有耦合的ODE,但是当我运行此代码时,我收到此错误:     TypeError:'float'对象不可订阅

错误发生在^返回数组([ - si * p [0], 这是我的代码:

from scipy.integrate import ode
import matplotlib.pyplot as plt
import warnings
si = 1/25 #0.053
fi = 1/23 #0.05
def deriv(p,t): 
    return array([-si* p[0], 
              si * p[0] - fi * p[1], 
              fi * p[1] - fi * p[2], 
              fi * p[2] - fi * p[3], 
              fi * p[3] - fi * p[4], 
              fi * p[4] - fi * p[5], 
              fi * p[5] - si * p[6], 
              si * p[6]])

backend = 'dopri5'

t0 = 0
t1 = 2000.0
p_init = array([1, 0, 0, 0, 0, 0, 0, 0])
r = .01

solver = ode(deriv).set_integrator(backend, nsteps=1)
solver.set_initial_value(p_init, t0).set_f_params(r)
solver._integrator.iwork[2] = -1
sol = []
warnings.filterwarnings("ignore", category=UserWarning)
while solver.t < t1:
solver.integrate(t1, step=True)
sol.append([solver.t, solver.p])
warnings.resetwarnings()
sol = array(sol)

plt.plot(sol[:,0], sol[:,1], 'b.-')
plt.show()

错误在哪里?

1 个答案:

答案 0 :(得分:1)

因此,错误是由deriv中输入变量的错误顺序引起的。 这是正确的代码:

from scipy.integrate import ode
from pylab import *
import seaborn
import numpy as np
import pandas as pd
import warnings

si = 1/25 #0.053
fi = 1/23 #0.05
def deriv(t,y,r): #correct order of input variables
    return np.array([-si* y[0], 
              si * y[0] - fi * y[1], 
              fi * y[1] - fi * y[2], 
              fi * y[2] - fi * y[3], 
              fi * y[3] - fi * y[4], 
              fi * y[4] - fi * y[5], 
              fi * y[5] - si * y[6], 
              si * y[6]])

backend = 'dopri5'
t0 = 0
t1 = 400.0
y_init = np.array([1, 0, 0, 0, 0, 0, 0, 0])
r = .01

solver = ode(deriv).set_integrator(backend, nsteps=1)
solver.set_initial_value(y_init, t0).set_f_params(r)
solver._integrator.iwork[2] = -1

ans = []
warnings.filterwarnings("ignore", category=UserWarning)
while solver.t < t1:
    solver.integrate(t1, step=True)
    ans.append(np.append(solver.t, solver.y)) #collect the answer on every slice of time

df = pd.DataFrame(ans)
df.columns = ['t', 'y0', 'y1','y2', 'y3', 'y4', 'y5', 'y6', 'y7'] #create DataFrame 

for i in df.columns.values[1:]:
    plot(df['t'], df[i]) #plotting