[英]Passing large time dependent data to solve differential equation in python,
Consider this simple first-order differential equation:考虑这个简单的一阶微分方程:
Where k is a constant with value 0.5 and其中 k 是一个常数,值为 0.5 和
is a variable that changes with time.
是随时间变化的变量。
I used the following code to input the values of y_bar at different times which works perfectly.我使用以下代码在不同时间输入 y_bar 的值,效果很好。
import numpy as np
from scipy.integrate import odeint
from matplotlib import pyplot as plt
def get_y_bar(t):
if t>=0 and t<=1:
return 0.0
elif t<=2:
return 1.0
elif t<=3:
return 2.0
elif t<=4:
return 3.0
elif t<=5:
return 4.0
else:
return 5.0
def ode(y,t):
k=0.5
y_bar=get_y_bar(t)
dy=k*(y_bar-y)
return dy
y0=0.0
t0=np.linspace(0,10,100)
sol=odeint(ode,y0,t0)
plt.plot(t0,sol)
plt.show()
But, this method is feasible only when I have a small data and can enter it using if.. elif..else loop manually.但是,这种方法只有在我有少量数据并且可以手动使用 if.. elif..else 循环输入时才可行。 What can I do if I have large values of y_bar in smaller time steps (eg, t= 0.01, 0.025, 0.03,..., 5.0)??
如果在较小的时间步长(例如 t= 0.01、0.025、0.03、...、5.0)中有较大的 y_bar 值,我该怎么办?
I have the data in CSV format and tried looping through the data but got stuck??我有 CSV 格式的数据并尝试遍历数据但卡住了? Is there any simple way to do this??
有什么简单的方法可以做到这一点吗?
def get_y_bar(t):
data=np.genfromtxt('data.csv',delimiter=',')
time=data[:,0]
y_bar=data[:,1]
for i in range(len(time)):
if t>=time[i] and t<=time[i=1]:
return y_bar[i]
else:
I am not sure if I understood your question completely.我不确定我是否完全理解你的问题。 But if you want to replace the numerous
elif
loops in get_y_bar
, try this:但是,如果您想替换
get_y_bar
中的众多elif
循环,请尝试以下操作:
import math
def get_y_bar(t):
return math.floor(t)
That is, math.floor(4.2)
will return 4
, which is the largest integer smaller than 4.2
即
math.floor(4.2)
将返回4
,即小于4.2
的最大 integer
With that approach you would load your file every time odeint
does a call to your ode
function, which will be highly inefficient.使用这种方法,您将在每次
odeint
调用您的ode
function 时加载文件,这将非常低效。
A more convenient way to solve your problem is to replace your get_y_bar
function by using scipy.interpolate.interp1d
instead, with kind = zero
, ie constant interpolation .解决您的问题的更方便的方法是使用
scipy.interpolate.interp1d
替换您的get_y_bar
function ,而kind = zero
,即constant interpolation 。 You should do this interpolation outside of your ode
function, so you only do it once.你应该在你的
ode
function 之外做这个插值,所以你只做一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.