The fastest way to find the square of the magnitude (length) of a vector field

I have a large vector field, where a large field (for example, 512 ^ 3, but not necessarily square), and the vectors are either 2D or 3D (for example, figures [512, 512, 512, 2] or [512, 512, 512, 3]).

What is the fastest way to calculate the scalar field of the squared magnitude of vectors?

I could just cross all directions, i.e.

import numpy as np
shp = [256,256,256,3]                       # Shape of vector field
vf = np.arange(3*(256**3)).reshape(shp)     # Create vector field
sf = np.zeros(shp[:3])                      # Create scalar field for result

for ii in range(shp[0]):
    for jj in range(shp[1]):
        for kk in range(shp[2]):
            sf[ii,jj,kk] = np.dot( vf[ii,jj,kk,:] , vf[ii,jj,kk,:] )

but it's pretty slow, is there anything faster?

+4
source share
1 answer

The fastest will probably be np.einsum:

np.einsum('...j,...j->...', vf, vf)

numpy, , . , 32- , np.arange. , dtype, np.int64, np.double:

>>> np.einsum('...j,...j->...', vf,vf)[-1, -1, -1]
-603979762
>>> np.einsum('...j,...j->...', vf,vf).dtype
dtype('int32')

>>> np.einsum('...j,...j->...', vf,vf, dtype=np.int64)[-1, -1, -1]
7599823767207950
>>> np.einsum('...j,...j->...', vf,vf, dtype=np.double)[-1, -1, -1]
7599823767207950.0
+5

All Articles