在 scipy.integrate.solve_ivp 中进行事件检测的第 n 次交叉

问题描述 投票:0回答:1

我想知道是否有任何方法可以在检测到特定数量的事件后停止 ODE 集成。我知道 scipy.integrate.solve_ivp 允许使事件终止或不终止,但我想知道是否可以使其在第 n 个事件处终止,其中 n 是大于 1 的整数。

例如,是否可以仅计算与事件的前三个交互,然后停止集成?如果这是不可能的,是否有替代库可以做到这一点?

我阅读了与ODE集成相关的scipy官方文档,但我没有找到任何东西。

python events scipy ode
1个回答
0
投票

好的,这是一个示例 hack:


import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate

def f(t, y):
    return [y[1], -y[0]]

def event(t, y, n_events):
    if event.count < n_events - 1:
        new_sign = np.sign(y[0])
        if new_sign == -event.sign:
            event.count += 1
            event.sign = new_sign
        return 1
    return y[0] * (-1)**(n_events + 1)
event.count = 0
event.sign = np.sign(y0[0])

ti = 0
tf = 100
y0 = [1, 0]

n_events = 3
def wrapped_event(t, y):
    return event(t, y, n_events)
wrapped_event.terminal = True

sol = integrate.solve_ivp(f, (0, tf), y0, dense_output=True, 
                          events=wrapped_event)
t = np.linspace(sol.t[0], sol.t[-1], 300)
x = sol.sol(t)
plt.plot(t, x[0])

© www.soinside.com 2019 - 2024. All rights reserved.