3

What is the easiest way to save intermediate variables during simulation with odeint in Numpy?

For example:

def dy(y,t)
    x = np.rand(3,1)
    return y + x.sum()

sim = odeint(dy,0,np.arange(0,1,0.1))

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.

4

1 回答 1

7

破解 odeint 的一种方便方法(有一些注意事项)是将您对 odeint 的调用包装在一个类中的方法中,dy作为另一种方法,并self作为参数传递给您的dy函数。例如,

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()

需要明确的是,这是一个容易陷入陷阱的黑客攻击。例如,除非 odeint 正在执行 Euler 步进,否则 dy 将被调用的次数超过您指定的时间步数。为了确保x每个得到一个,块y中的猴子业务在if t >= self.times[self.timestep]:数组中选择一个点,用于存储times向量中每个时间值的数据。您的特定应用程序可能会导致其他疯狂的问题。请务必为您的应用程序彻底验证此方法。

于 2013-06-04T15:38:00.590 回答