如何有效地计算numpy中的旋转张量?

如何有效地计算numpy中的旋转张量?,numpy,rigid-bodies,Numpy,Rigid Bodies,三维空间中一组N个点的距离定义为 假设条件 在不使用显式for循环的情况下,如何在numpy中计算此值?我知道我可以做一些像 import numpy as np def calculate_gyration_tensor(points): ''' Calculates the gyration tensor of a set of points. ''' COM = centre_of_mass(points) gyration_tensor =

三维空间中一组N个点的距离定义为

假设条件

在不使用显式for循环的情况下,如何在
numpy
中计算此值?我知道我可以做一些像

import numpy as np

def calculate_gyration_tensor(points):
    '''
    Calculates the gyration tensor of a set of points.
    '''
    COM = centre_of_mass(points)
    gyration_tensor = np.zeros((3, 3))
    for p in points:
        gyration_tensor += np.outer(p-COM, p-COM)
    return gyration_tensor / len(points)

但是,由于for循环,对于较大的N,这很快变得效率低下。有更好的方法吗?

您可以使用
np.einsum
这样做:

def gyration(points):
    '''
    Calculate the gyrason tensor
    points : numpy array of shape N x 3
    '''

    center = points.mean(0)

    # normalized points
    normed_points = points - center[None,:]

    return np.einsum('im,in->mn', normed_points,normed_points)/len(points)


# test
points = np.arange(36).reshape(12,3)

gyration(points)    
输出:

array([[107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25]])

谢谢-你能解释一下einsum是做什么的吗,尤其是那个字符串的意思吗?你可以继续阅读。基本上,您的操作就是
normed_points.T@normed_points