问题描述
在Numpy中使用odeint
模拟过程中保存中间变量的最简单方法是什么?
What is the easiest way to save intermediate variables during simulation with odeint
in Numpy?
例如:
def dy(y,t)
x = np.rand(3,1)
return y + x.sum()
sim = odeint(dy,0,np.arange(0,1,0.1))
在模拟过程中保存x
中存储的数据的最简单方法是什么?理想情况下,在传递给odeint
的t
参数中指定的点上.
What would be the easiest way to save the data stored in x
during simulation? Ideally at the points specified in the t
argument passed to odeint
.
推荐答案
破解odeint的一种简便方法,有一些警告,是将对odeint的调用包装在类中的方法中,而将dy
作为另一种方法,并且将self
作为参数传递给dy
函数.例如,
A handy way to hack odeint, with some caveats, is to wrap your call to odeint in method in a class, with dy
as another method, and pass self
as an argument to your dy
function. For example,
class WrapODE(object):
def __init__(self):
self.y_0 = 0.
self.L_x = []
self.timestep = 0
self.times = np.arange(0., 1., 0.1)
def run(self):
self.L_y = odeint(
self.dy,
self.y_0, self.times,
args=(self,))
@staticmethod
def dy(y, t, self):
""""
Discretized application of dudt
Watch out! Because this is a staticmethod, as required by odeint, self
is the third argument
"""
x = np.random.rand(3,1)
if t >= self.times[self.timestep]:
self.timestep += 1
self.L_x.append(x)
else:
self.L_x[-1] = x
return y + x.sum()
需要明确的是,这是一个容易陷入陷阱的hack.例如,除非odeint正在执行Euler步进,否则dy被调用的次数将超过您指定的时间步数.为了确保每个y
都得到一个x
,if t >= self.times[self.timestep]:
块中的猴子业务从times
向量中选择一个数组中的一个点来存储每个时间值的数据.您的特定应用程序可能会导致其他疯狂的问题.确保为您的应用程序彻底验证此方法.
To be clear, this is a hack that is prone to pitfalls. For example, unless odeint is doing Euler stepping, dy is going to get called more times than the number of timesteps you specify. To make sure you get one x
for each y
, the monkey business in the if t >= self.times[self.timestep]:
block picks a spot in an array for storing data for each time value from the times
vector. Your particular application might lead to other crazy problems. Be sure to thoroughly validate this method for your application.
这篇关于NumPy odeint输出额外的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!