gpt4 book ai didi

python - scipy.integrate.solve_ivp 矢量化

转载 作者:行者123 更新时间:2023-12-01 08:15:42 29 4
gpt4 key购买 nike

尝试使用solve_ivp的矢量化选项,奇怪的是它会抛出一个错误,即y0必须是一维的。MWE:

from scipy.integrate import solve_ivp
import numpy as np
import math

def f(t, y):
theta = math.pi/4
ham = np.array([[1,0],[1,np.exp(-1j*theta*t)]])
return-1j * np.dot(ham,y)


def main():

y0 = np.eye(2,dtype= np.complex128)
t0 = 0
tmax = 10**(-6)
sol=solve_ivp( lambda t,y :f(t,y),(t0,tmax),y0,method='RK45',vectorized=True)
print(sol.y)

if __name__ == '__main__':
main()

The calling signature is fun(t, y). Here t is a scalar, and there are two options for the ndarray y: It can either have shape (n,); then fun must return array_like with shape (n,). Alternatively it can have shape (n, k); then fun must return an array_like with shape (n, k), i.e. each column corresponds to a single column in y. The choice between the two options is determined by vectorized argument (see below). The vectorized implementation allows a faster approximation of the Jacobian by finite differences (required for stiff solvers).

错误:

ValueError: y0 must be 1-dimensional.

Python 3.6.8

scipy.版本'1.2.1'

最佳答案

这里vectorize的含义有点令人困惑。这并不意味着 y0 可以是 2d,而是意味着传递给函数的 y 可以是 2d。换句话说,如果求解器需要的话,func 可以同时在多个点进行计算。多少分取决于求解器,而不是您。

更改 f 以在每次调用时显示形状 y:

def f(t, y):
print(y.shape)
theta = math.pi/4
ham = np.array([[1,0],[1,np.exp(-1j*theta*t)]])
return-1j * np.dot(ham,y)

示例调用:

In [47]: integrate.solve_ivp(f,(t0,tmax),[1j,0],method='RK45',vectorized=False) 
(2,)
(2,)
(2,)
(2,)
(2,)
(2,)
(2,)
(2,)
Out[47]:
message: 'The solver successfully reached the end of the integration interval.'
nfev: 8
njev: 0
nlu: 0
sol: None
status: 0
success: True
t: array([0.e+00, 1.e-06])
t_events: None
y: array([[0.e+00+1.e+00j, 1.e-06+1.e+00j],
[0.e+00+0.e+00j, 1.e-06-1.e-12j]])

相同的调用,但使用vectorize=True:

In [48]: integrate.solve_ivp(f,(t0,tmax),[1j,0],method='RK45',vectorized=True)  
(2, 1)
(2, 1)
(2, 1)
(2, 1)
(2, 1)
(2, 1)
(2, 1)
(2, 1)
Out[48]:
message: 'The solver successfully reached the end of the integration interval.'
nfev: 8
njev: 0
nlu: 0
sol: None
status: 0
success: True
t: array([0.e+00, 1.e-06])
t_events: None
y: array([[0.e+00+1.e+00j, 1.e-06+1.e+00j],
[0.e+00+0.e+00j, 1.e-06-1.e-12j]])

如果为 False,则传递给 fy 为 (2,), 1d; True 则为 (2,1)。我猜如果求解器方法需要的话,它可能是 (2,2) 甚至 (2,3)。这可以加快执行速度,同时减少对 f 的调用。在这种情况下,这并不重要。

quadrature 有一个类似的 vec_func bool 参数:

Numerical Quadrature of scalar valued function with vector input using scipy

相关错误/问题讨论:

https://github.com/scipy/scipy/issues/8922

关于python - scipy.integrate.solve_ivp 矢量化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54991056/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com