用Python解决动态ODE系统

时间:2018-11-18 14:19:12

标签: python ode solver

我试图用三个状态变量V1,V2,I3求解动力学系统,然后将其绘制在3d图中。到目前为止,我的代码如下:

from scipy.integrate import ode
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import math
def ID(V,a,b):
    return a*(math.exp(b*V)-math.exp(-b*V))


def dynamical_system(t,z,C1,C2,L,R1,R2,R3,RN,a,b):

    V1,V2,I3 = z
    f = [(1/C1)*(V1*(1/RN-1/R1)-ID(V1-V2,a,b)-(V1-V2)/R2),(1/C2)*(ID(V1-V2,a,b)+(V1-V2)/R2-I3),(1/L)*(-I3*R3+V2)]
    return f 

# Create an `ode` instance to solve the system of differential
# equations defined by `dynamical_system`, and set the solver method to 'dopri5'.
solver = ode(dynamical_system)
solver.set_integrator('dopri5')

# Set the initial value z(0) = z0.
C1=10
C2=100
L=0.32
R1=22
R2=14.5
R3=100
RN=6.9
a=2.295*10**(-5)
b=3.0038
solver.set_f_params(C1,C2,L,R1,R2,R3,RN,a,b)
t0 = 0.0
z0 = [-3, 0.5, 0.25] #here you can set the inital values V1,V2,I3
solver.set_initial_value(z0, t0)


# Create the array `t` of time values at which to compute
# the solution, and create an array to hold the solution.
# Put the initial value in the solution array.
t1 = 25
N = 200 #number of iterations
t = np.linspace(t0, t1, N)
sol = np.empty((N, 3))
sol[0] = z0

# Repeatedly call the `integrate` method to advance the
# solution to time t[k], and save the solution in sol[k].
k = 1
while solver.successful() and solver.t < t1:
    solver.integrate(t[k])
    sol[k] = solver.y
    k += 1


xlim = (-4,1)
ylim= (-1,1)
zlim=(-1,1)
fig=plt.figure()
ax=fig.gca(projection='3d')
#ax.view_init(35,-28)
ax.set_xlim(xlim)
ax.set_ylim(ylim)
ax.set_zlim(zlim)

print sol[:,0]
print sol[:,1]
print sol[:,2]
ax.plot3D(sol[:,0], sol[:,1], sol[:,2], 'gray')

plt.show()

打印应该包含解决方案sol [:,0]等的数组,这显然表明它不断地用初始值填充它。有人可以帮忙吗?谢谢!

1 个答案:

答案 0 :(得分:0)

使用from __future__ import division


我无法重现您的问题:我看到从-3到-2.46838127,从0.5到0.38022886,从0.25到0.00380239逐渐变化(第一步是从0.25到0.00498674的急剧变化)。这是Python 3.7.0,NumPy 1.15.3和SciPy 1.1.0的版本。

鉴于您使用的是Python 2.7,整数除法可能是此处的罪魁祸首。您的常数中有很多是整数,方程中有一堆1/<constant>整数除法。

实际上,如果我在我的版本(对于Python 3)中将/替换为//,则可以重现您的问题。

只需在脚本顶部添加from __future__ import division即可解决问题。


还要在顶部添加from __future__ import print_function,将print <something>替换为print(<something>),并且您的脚本与Python 3 2完全兼容)。