[Numpy-discussion] Programmatically contracting multiple tensors

Michael Lamparski diagonaldevice at gmail.com
Fri Mar 12 19:24:08 EST 2021


I have something in my code where I can receive an array M of unknown
dimensionality and a list of "labels" for each axis.  E.g. perhaps I might
get an array of shape (2, 47, 3, 47, 3) with labels ['spin', 'atom',
'coord', 'atom', 'coord'].

For every axis that is labeled "coord", I want to multiply in some rotation
matrix R.  So, for the above example, this could be done with the following
handwritten line:

return np.einsum('Cc,Ee,abcde->abCdE', R, R, M)

But since I want to do this programmatically, I find myself in the awkward
situation of having to construct this string (and e.g. having to
arbitrarily limit the number of axes to 26 or something like that).  Is
there a more idiomatic way to do this that would let me supply integer
labels for summation indices?  Or should I just bite the bullet and start
generating strings?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.python.org/pipermail/numpy-discussion/attachments/20210312/da7e99e0/attachment.html>

More information about the NumPy-Discussion mailing list