用scipy解决一个颂歌系统 - 如何引用不同的索引?

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

我有一个依赖于数据矩阵的ODE系统。每个ODE应在其评估中引用不同的数据列。

import numpy as np
n_eqns = 20
coeffs = np.random.normal(0, 1, (n_eqns, 20))
def dfdt(_, f, idx):
    return (f ** 2) * coeffs[idx, :].sum() - 2 * f * coeffs.sum()

from scipy.integrate import ode
f0 = np.random.uniform(-1, 1, n_eqns)
t0 = 0
tf = 1
dt = 0.001

r = ode(dfdt)
r.set_initial_value(f0, t0).set_f_params(range(n_eqns))

while r.successful() and r.t < tf:
    print(r.t+dt, r.integrate(r.t+dt))

如何指定每个ODE应该在ODE系统中使用与其索引关联的idx值?第一个等式应该通过idx=0,第二个idx=1,依此类推。

python scipy differential-equations
1个回答
2
投票

函数dfdt分别作为数组(或其他迭代)获取并返回状态和导数。因此,您所要做的就是遍历所有索引并相应地应用您的操作。例如:

def dfdt(t,f):
    output = np.empty_like(f)
    for i,entry in enumerate(f)
        output[i] = f[i]**2 * coeffs[i,:].sum() - 2*f[i]*coeffs.sum()
    return output

您也可以使用NumPy的组件操作(更快)来编写它:

def dfdt(t,f):
    return f**2 * coeffs.sum(axis=1) - 2*f*coeffs.sum()

最后请注意,使用f作为你的状态可能有点令人困惑,因为这是ode表示衍生物(你称之为dfdt)的方式。

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