TensorOperations.jl icon indicating copy to clipboard operation
TensorOperations.jl copied to clipboard

Best way to tensor reshaping

Open ho-oto opened this issue 7 years ago • 2 comments

I often use @tensor macro and reshape together, e.g.:

@tensor A[a,e,c,g,f] := B[a,b] * C[b,c,d] * D[d,e,f,g]
A = reshape(A, size(A)[1]*size(A)[2]*size(A)[3], size(A)[4]*size(A)[5]) 

I think this code is inelegant and wasting memory. I want to use more elegant format like

@tensor A[(a,e,c),(g,f)] := B[a,b] * C[b,c,d] * D[d,e,f,g]

instead. Or, some good way just I don't know already exists?

ho-oto avatar Jun 11 '18 03:06 ho-oto

This would indeed be a possibility which I have also considered, but I have not implemented it yet. Maybe at some point. One issue that holds me back is how to do/specify the reverse reshaping, i.e. where a single dimension of the tensor gets split into two or more, with easy syntax.

Jutho avatar Jun 12 '18 22:06 Jutho

I made a package which does this, and some other things. The notation you suggest works, as does the more compact \ for combining indices:

using TensorOperations; using TensorSlice
B = rand(2,3); C = rand(3,4,5); D = rand(5,6,7,8);
@tensor A[a,e,c,g,f] := B[a,b] * C[b,c,d] * D[d,e,f,g];

@shape Z[a\e\c, g\f] := A[a,e,c,g,f];

Unlike @tensor it doesn’t do any of the work, it just writes the same reshape() command you did. Which I believe should not allocate much memory.

mcabbott avatar Jan 08 '19 20:01 mcabbott