将动态函数应用于相位 space 中的每个点(由二维矩阵表示)

Apply dynamical function to each point in phase space (represented by a 2D matrix)

我有一个整数矩阵,phase_space,形状为 (n,n),其中每个条目代表 space 中该位置的点数。我还有两个更新矩阵 u_x, u_y 也具有 (n,n) 的形状,整数在 0,...,n 范围内指定我的动力系统在 space 中获取每个对应点的位置。 我想 "apply" 迭代更新矩阵到 space 阶段。

例如,如果

>>>u_x
array([[1, 2, 1],
       [0, 1, 2],
       [0, 0, 0]])
>>>u_y
array([[2, 1, 2],
       [1, 0, 1],
       [2, 2, 0]])
>>>phase_space 
array([[1, 1, 1],
       [1, 1, 1],
       [1, 1, 1]])

我要

>>>new_phase_space
array([[1., 1., 2.],
       [1., 0., 2.],
       [0., 2., 0.]])

我目前的(工作)解决方案是循环如下

for i in range(n):
    for j in range(n):
        new_phase_space[u_x[i, j], u_y[i, j]] += phase_space[i,j] 

有什么方法可以对其进行矢量化吗?

我们可以使用np.bincount-

M,N = u_x.max()+1,u_y.max()+1
ids = u_x*N+u_y
out = np.bincount(ids.ravel(),phase_space.ravel(),minlength=M*N).reshape(M,N)

样本 运行 在更通用的设置上 -

In [14]: u_x
Out[14]: 
array([[1, 2, 1],
       [0, 1, 4],
       [0, 0, 0]])

In [15]: u_y
Out[15]: 
array([[2, 1, 2],
       [6, 0, 1],
       [2, 6, 0]])

In [17]: phase_space
Out[17]: 
array([[1, 1, 1],
       [5, 1, 1],
       [1, 1, 1]])

In [18]: out
Out[18]: 
array([[1., 0., 1., 0., 0., 0., 6.],
       [1., 0., 2., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0.],
       [0., 0., 0., 0., 0., 0., 0.],
       [0., 1., 0., 0., 0., 0., 0.]])

我们也可以使用稀疏矩阵,尤其是在内存不足的情况下 -

from scipy.sparse import csr_matrix,coo_matrix

out = coo_matrix( (phase_space.ravel(), (u_x.ravel(), u_y.ravel())), shape = (M,N))

输出将是一个稀疏矩阵。要转换为密集型,请使用 out.toarray().

您可以使用pandas.DataFrame.groupby()来累积phase_space中具有相同坐标的所有移动:

new_phase_space + (pd.DataFrame(phase_space)
           .stack()
           .groupby([u_x.ravel(), u_y.ravel()])
           .sum()
           .unstack(fill_value=0)
           .values
)

输出:

array([[2., 2., 4.],
       [2., 0., 4.],
       [0., 4., 0.]])