0

The gyration tensor of a set of N points in 3d space is defined as

Gyration tensor

assuming the condition

enter image description here.

How do I compute this in numpy without using an explicit for loop? I know that I can just do something like

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)

but this quickly becomes inefficient for large N, because of the for loop. Is there a better way to do it?

Ferdinando Randisi
  • 4,068
  • 6
  • 32
  • 43

1 Answers1

1

You can do with np.einsum like this:

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)    

Output:

array([[107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25],
       [107.25, 107.25, 107.25]])
Quang Hoang
  • 146,074
  • 10
  • 56
  • 74