Skip to main content
 首页 » 编程设计

python之Scipy ode 根据解决方案的大小集成到 t 的未知限制

2025年01月19日11artech

我正在模拟在电磁场中移动的带电粒子并使用 scipy ode。显然,此处的代码已简化,但仅作为示例使用。我遇到的问题是我想在限制 r 而不是 t 之后结束集成。因此,将 dx/dt 积分到 norm(x) > r 的点。

但是,我不想只更改函数以对 r 求积分,因为位置是 t 的函数。我可以对不相关的变量做定积分吗?

import numpy as np 
import matplotlib.pyplot as plt 
from scipy.integrate import odeint 
 
def RHS(state, t, Efield, q, mp): 
 
    ds0 = state[3] 
    ds1 = state[4] 
    ds2 = state[5] 
    ds3 = q/mp * Efield*state[0] 
    ds4 = q/mp * Efield*state[1] 
    ds5 = q/mp * Efield*state[2] 
 
    r = np.linalg.norm((state[0], state[1], state[2])) 
 
    # if r > 30000 then do stop integration.....? 
 
    # return the two state derivatives 
    return [ds0, ds1, ds2, ds3, ds4, ds5] 
 
 
ts = np.arange(0.0, 10.0, 0.1) 
state0 = [1.0, 2.0, 3.0, 0.0, 0.0, 0.0] 
 
Efield=1.0 
q=1.0 
mp=1.0 
 
stateFinal = odeint(RHS, state0, ts, args=(Efield, q, mp)) 
print(np.linalg.norm(stateFinal[-1,0:2])) 

请您参考如下方法:

您可以通过使用 scipy.integrate.ode 逐步执行集成来控制流程.示例:

from scipy.integrate import ode 
t_initial = 0 
dt = 0.1 
t_max = 10 
r = ode(RHS).set_initial_value(state0, t_initial).set_f_params(Efield, q, mp) 
solution = [state0] 
while r.successful() and r.t < t_max: 
    new_val = r.integrate(r.t + dt) 
    solution.append(new_val) 
    if np.linalg.norm((new_val[0], new_val[1], new_val[2])) > 30000: 
        break 
print(solution) 

注意RHS的签名要改成def RHS(t, state, Efield, q, mp):对于ode,自变量来了首先,与 odeint 不同。

输出是以自变量的 dt 增量计算的解,直到循环结束的时间(因为达到 t_max,或者积分器失败,或者遇到了 break 的条件)。