用 scipy 解决一个 odes 系统 - 如何引用不同的索引?
Solve a system of odes with scipy - how to reference different indexes?
我有一个依赖于数据矩阵的 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
,依此类推。
函数 dfdt
将状态和导数分别作为数组(或其他可迭代对象)和 returns。因此,您所要做的就是遍历所有索引并相应地应用您的操作。例如:
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 的 component-wise 操作(更快)来编写此代码:
def dfdt(t,f):
return f**2 * coeffs.sum(axis=1) - 2*f*coeffs.sum()
最后请注意,使用 f
作为您的状态可能会有些混乱,因为这是 ode
表示导数(您称之为 dfdt
)的方式。
我有一个依赖于数据矩阵的 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
,依此类推。
函数 dfdt
将状态和导数分别作为数组(或其他可迭代对象)和 returns。因此,您所要做的就是遍历所有索引并相应地应用您的操作。例如:
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 的 component-wise 操作(更快)来编写此代码:
def dfdt(t,f):
return f**2 * coeffs.sum(axis=1) - 2*f*coeffs.sum()
最后请注意,使用 f
作为您的状态可能会有些混乱,因为这是 ode
表示导数(您称之为 dfdt
)的方式。