Function Repository Resource:

FromTensor

Source Notebook

Convert TensorContract expressions into an equivalent form using Dot and Tr

Contributed by: Carl Woll

ResourceFunction["FromTensor"][expr]

converts TensorContract expressions in expr into equivalent forms using Dot and Tr.

Details and Options

Only tensors of rank 1 or 2 are supported.
Transpose operations in the output are represented using Transpose instead of TensorTranspose.
ResourceFunction["FromTensor"] makes no assumptions about the rank of the symbolic tensors involved. Use the Assumptions option or $Assumptions to define rank information for the involved tensors.
The input and output of ResourceFunction["FromTensor"] will evaluate to the same array when given explicit arrays as input.
For numerical tensors, the output of ResourceFunction["FromTensor"] will evaluate much more quickly than the input TensorContract form.

Examples

Basic Examples (4) 

Specify the properties of symbolic arrays:

In[1]:=
$Assumptions = (A | X) \[Element] Matrices[{d, d}];

Create a TensorContract expression:

In[2]:=
e = TensorContract[TensorProduct[A, X], {{1, 3}, {2, 4}}];

Convert to an equivalent form using Tr and Dot:

In[3]:=
f = ResourceFunction["FromTensor"][e]
Out[3]=

Check:

In[4]:=
SeedRandom[1]
Block[{A = RandomReal[1, {3, 3}], X = RandomReal[1, {3, 3}]},
 {e, f}
 ]
Out[5]=

Scope (3) 

Create a tensor with disconnected components:

In[6]:=
e = TensorContract[
   TensorProduct[M, X, M, X], {{1, 3}, {2, 4}, {5, 8}, {6, 7}}];

Convert to an equivalent form using Tr and Dot:

In[7]:=
ResourceFunction["FromTensor"][e, Assumptions -> (M | X) \[Element] Matrices[{d, d}]]
Out[7]=

Check equivalence of forms:

In[8]:=
$Assumptions = (A | B) \[Element] Matrices[{d, d}];

ResourceFunction["FromTensor"][
 A . Transpose[B] == TensorContract[TensorProduct[A, B], {{2, 4}}]]
Out[9]=

Applications (4) 

Tensor forms using Dot and Tr evaluate much more quickly than forms using TensorContract. Consider the following TensorContract expression:

In[10]:=
t = TensorContract[TensorProduct[A, X, A], {{1, 3}, {2, 5}, {4, 6}}]
Out[10]=

The equivalent form using Dot and Tr:

In[11]:=
f = ResourceFunction["FromTensor"][t, Assumptions -> (A | X) \[Element] Matrices[{d, d}]]
Out[11]=

Evaluate the two forms of the tensor using numerical arrays as the tensors:

In[12]:=
SeedRandom[1]
Block[{A = RandomReal[1, {25, 25}], X = RandomReal[1, {25, 25}]},
 {t // AbsoluteTiming, f // AbsoluteTiming}
 ]
Out[13]=

The slowness of the TensorContract version can be ameliorated by judicious use of Inactivate and Activate:

In[14]:=
g = Inactivate[Evaluate[t], TensorProduct]
Out[14]=
In[15]:=
SeedRandom[1]
Block[{A = RandomReal[1, {25, 25}], X = RandomReal[1, {25, 25}]},
 Activate[g] // AbsoluteTiming
 ]
Out[16]=

Publisher

Carl Woll

Version History

  • 2.0.0 – 06 November 2020
  • 1.0.0 – 16 October 2019

Related Resources

License Information