3

This function multiplies each of the n rows of pose by a different rotation matrix. Is it possible to avoid the loop by maybe using a 3d tensor of rotation matrices?

def transform(ref, pose):
    n, d = pose.shape
    p = ref[:, :d].copy()
    c = np.cos(ref[:, 2])
    s = np.sin(ref[:, 2])

    for i in range(n):
        p[i,:2] += pose[i,:2].dot(np.array([[c[i], s[i]], [-s[i], c[i]]]))

    return p
Divakar
  • 218,885
  • 19
  • 262
  • 358
Manuel Schmidt
  • 2,429
  • 1
  • 19
  • 32

1 Answers1

2

Here's one with np.einsum -

# Setup 3D rotation matrix
cs = np.empty((n,2,2))
cs[:,0,0] = c
cs[:,1,1] = c
cs[:,0,1] = s
cs[:,1,0] = -s

# Perform 3D matrix multiplications with einsum
p_out = ref[:, :d].copy()
p_out[:,:2] += np.einsum('ij,ijk->ik',pose[:,:2],cs)

Alternatively, replace the two assigning steps for c with one involving one more einsum -

np.einsum('ijj->ij',cs)[...] = c[:,None]

Use optimize flag with True value in np.einsum to leverage BLAS.

Alternatively, we can use np.matmul/@ operator in Python 3.x to replace the einsum part -

p_out[:,:2] += np.matmul(pose[:,None,:2],cs)[:,0]
Divakar
  • 218,885
  • 19
  • 262
  • 358