Einstein summation of a matrix in a tensor and another tensor in Julia

Viewed 89

W is a 5×5 matrix and the items are 2×2 matrices, for example:

S0=reshape([2,2,4,4], (2, 2))
W=reshape(Any[S0 for i in 1:25],(5,5))

A is a 2×2×2 tensor, for example:

A= reshape([1,1,1,1,3,3,3,3], (2, 2, 2))

I want to sum second index of S0 in W and second index of A, I mean,

using Einsum
@einsum ans[a,b,c,d,e]:=W[a,b][c,i]*A[d,i,e]

but an error happens: MethodError: Cannot `convert` an object of type Expr to an object of type Symbol. Is there any way to calculate this Einstein summation in Julia?

1 Answers

That's not an elegant error message, but Einsum.jl doesn't try to handle arrays of arrays. However:

julia> using Tullio

julia> @tullio out[a,b,c,d,e] := W[a,b][c,i] * A[d,i,e]
5×5×2×2×2 Array{Int64, 5}:
[:, :, 1, 1, 1] =
 6  6  6  6  6
 6  6  6  6  6
...

Note also that it's not necessary to have eltype Any to contain other arrays, for instance this has eltype(W2) == Matrix{Int64}:

julia> W |> summary
"5×5 Matrix{Any}"

julia> W2 = [copy(S0) for i in 1:5, j in 1:5]
5×5 Matrix{Matrix{Int64}}:
 [2 4; 2 4]  [2 4; 2 4]  [2 4; 2 4]  [2 4; 2 4]  [2 4; 2 4]
...
Related