用于网格旋转的 Numpy einsum()

Chr*_*ris 6 python numpy numpy-einsum

我有一组使用 meshgrid() 生成的 3d 坐标。我希望能够围绕 3 个轴旋转这些。

我尝试解开网格并在每个点上旋转,但网​​格很大并且内存不足。

这个问题使用 einsum() 在 2d 中解决了这个问题,但是在将其扩展到 3d 时我无法弄清楚字符串格式。

我已经阅读了有关 einsum() 及其格式字符串的其他几页,但一直无法弄清楚。

编辑:

我称我的网格轴为 X、Y 和 Z,每个轴的形状为 (213, 48, 37)。此外,当我尝试将结果放回网格时,实际出现了内存错误。

当我试图“解开”它以逐点旋转时,我使用了以下函数:

def mg2coords(X, Y, Z):
    return np.vstack([X.ravel(), Y.ravel(), Z.ravel()]).T
Run Code Online (Sandbox Code Playgroud)

我用以下内容循环了结果:

def rotz(angle, point):
    rad = np.radians(angle)
    sin = np.sin(rad)
    cos = np.cos(rad)
    rot = [[cos, -sin, 0],
           [sin,  cos, 0],
           [0, 0, 1]]

    return np.dot(rot, point)
Run Code Online (Sandbox Code Playgroud)

旋转后,我将使用这些点进行插值。

hpa*_*ulj 6

使用您的定义:

In [840]: def mg2coords(X, Y, Z):
        return np.vstack([X.ravel(), Y.ravel(), Z.ravel()]).T

In [841]: def rotz(angle):
        rad = np.radians(angle)
        sin = np.sin(rad)
        cos = np.cos(rad)
        rot = [[cos, -sin, 0],
               [sin,  cos, 0],
               [0, 0, 1]]
        return np.array(rot)
        # just to the rotation matrix
Run Code Online (Sandbox Code Playgroud)

定义一个样本网格:

In [842]: X,Y,Z=np.meshgrid([0,1,2],[0,1,2,3],[0,1,2],indexing='ij')    
In [843]: xyz=mg2coords(X,Y,Z)
Run Code Online (Sandbox Code Playgroud)

逐行旋转它:

In [844]: xyz1=np.array([np.dot(rot,i) for i in xyz])
Run Code Online (Sandbox Code Playgroud)

等效einsum的逐行计算:

In [845]: xyz2=np.einsum('ij,kj->ki',rot,xyz)
Run Code Online (Sandbox Code Playgroud)

他们匹配:

In [846]: np.allclose(xyz2,xyz1)
Out[846]: True
Run Code Online (Sandbox Code Playgroud)

或者,我可以将 3 个数组收集到一个 4d 数组中,然后使用einsum. 这里np.array在开始时添加了一个维度。所以dot总和j维数是第一个,数组的 3d 如下:

In [871]: XYZ=np.array((X,Y,Z))
In [872]: XYZ2=np.einsum('ij,jabc->iabc',rot,XYZ)

In [873]: np.allclose(xyz2[:,0], XYZ2[0,...].ravel())
Out[873]: True
Run Code Online (Sandbox Code Playgroud)

与之相似的12

或者,我可以分成XYZ23 个组件数组:

In [882]: X2,Y2,Z2 = XYZ2
In [883]: np.allclose(X2,xyz2[:,0].reshape(X.shape))
Out[883]: True
Run Code Online (Sandbox Code Playgroud)

如果要向另一个方向旋转,请使用ji代替ij,即使用rot.T