Python's numpy
has einsum function, which allows to express wide range of combinations of ND-arrays multiplications, transposings, convolutions etc in one short expression. It is based on Einstein's notation for tensor algebra.
It is much easier to unserstand einsum
expression even for just matrix product.
In Mathematica
I can't find any equivalent, and even simple linear matrix transform appeared in my code as follows:
modif = Sum[e[[chart, j]] * a[[j]], {j, 1, Dimensions[e][[2]]}];
A lot of indexings and complex Sum
expression.
Is there still einsum
equivalent in Mathematica? If there isn't, how could I implement a similarly convenient notation myself, without sacrificing too much performance?
UPDATE
The benefits of einsum
it has in my opinion are following:
1) You should not think about order of operands and should not transpose them to correct shape.
For example, suppose you want to multiply matrix $A$ of (5,5)
by vector of $X$ which you would write in math as $AX$. But suppose your vector $X$ is transposed to row (1, 5)
which made $AX$ illegal.
You can compute
$(X(A^T))^T$
which can be easily miskaten as
$(XA)^T$
if you forget one transpose and it will work.
With einsum you would write
$a_{ij} x_{kj}$
where repeating of $j$ automatically means contraction and since it is in second position, it goes along row.
With einsum
notaion you can even transpose result as you want:
np.einsum("ij,kj->ik", a, x)
will give column, while
np.einsum("ij,kj->ki", a, x)
will give row.
But you are not need to worry about it, because einsum
can take any transpose.
2) You can easily deal with stacks of matrices and vectors and you should not think about how to extract them.
Suppose that now a
is 10
matrices of compound shape of (10,5,5)
and you want to multiple all of them by the same x
and get 10
results stacked. Then I'd write
np.einsum("ijk,lk->ijl", a, x)
Or suppose x
is also a stack of vectors and I want to multiply each matrix to corresponding x
. The I would write
np.einsum("ijk,ilk->ijl", a, x)
Now the presense of i
in output pattern also means no contraction.
3) einsum
can be used to multiply more that 2
tensors in one expression.
You will NEVER use any other matrix operations, once you learn einsum
and have efficient implementation of it!
Listability
ofTimes
to doTotal[e[[chart, All]] a]
, which gives the same result as your sum (assuminga
has the appropriate dimensions). $\endgroup$TensorProduct
and TensorContract`. $\endgroup$einsum
is something so specific that it is very unlikely that any other system would have it. The answer to your literal question is that no, Mathematica doesn't have einsum. But writing such an answer is not very useful to anyone. That is why I edited your question and asked how to implement it. $\endgroup$