【问题标题】:How do I efficiently compute the gyration tensor in numpy?如何有效地计算 numpy 中的回转张量?
【发布时间】:2020-06-02 14:01:32
【问题描述】:

3d空间中一组N个点的gyration tensor定义为

假设条件

.

如何在不使用显式 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)

但这对于大 N 来说很快就会变得低效,因为 for 循环。有没有更好的方法?

【问题讨论】:

    标签: numpy rigid-bodies


    【解决方案1】:

    您可以像这样使用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 是做什么的,特别是那个字符串是什么意思吗?
    • 您可以阅读this excellent answer。基本上你的操作就是normed_points.T @ normed_points
    猜你喜欢
    • 2019-05-10
    • 1970-01-01
    • 2014-09-06
    • 1970-01-01
    • 2012-03-11
    • 2014-07-26
    • 1970-01-01
    • 2015-04-15
    • 2016-12-11
    相关资源
    最近更新 更多