Function Repository Resource:

ToTensor

Source Notebook

Convert an expression involving Dot, Tr and MatrixPower into an equivalent expression using TensorContract

Contributed by: Carl Woll

ResourceFunction["ToTensor"][expr]

converts Dot,Tr and MatrixPower subexpressions into equivalent forms using TensorContract.

Details and Options

ResourceFunction["ToTensor"] 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["ToTensor"] will evaluate to the same array when given explicit arrays as input.
Only Tr expressions representing traces of the first two levels of an array have equivalent TensorContract representations.

Examples

Basic Examples (4) 

Specify the properties of symbolic arrays:

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

A tensor built using Tr and Dot:

In[2]:=
e = Tr[Transpose[A] . X]
Out[2]=

Convert to an equivalent form using TensorContract:

In[3]:=
t = ResourceFunction["ToTensor"][e]
Out[3]=

Check:

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

Scope (2) 

Check equivalence of forms, assuming the two matrices A and B are square:

In[6]:=
$Assumptions = (A | B) \[Element] Matrices[{d, d}];
ResourceFunction["ToTensor"][
 A . Transpose[B] == TensorContract[TensorProduct[A, B], {{2, 4}}]
 ]
Out[6]=

A tensor consisting of Dot, Tr and MatrixPower:

In[7]:=
t = Tr[A . MatrixPower[B, 2]] A . MatrixPower[B, 2]
Out[7]=

Evaluate, assuming the two matrices are square:

In[8]:=
ResourceFunction["ToTensor"][t, Assumptions -> (A | B) \[Element] Matrices[{d, d}]]
Out[8]=

Applications (2) 

TensorReduce is unable to reduce some mixed expressions consisting of both TensorContract and Dot:

In[9]:=
$Assumptions = (R | r) \[Element] Vectors[{d}];
expr = R . r - TensorContract[R\[TensorProduct]r, {{1, 2}}];

TensorReduce[expr]
Out[11]=

Using ToTensor trivially simplifies the expression:

In[12]:=
ResourceFunction["ToTensor"][expr]
Out[12]=

Possible Issues (2) 

Rank information for symbolic tensors must be specified using the Assumptions option or using $Assumptions:

In[13]:=
$Assumptions = True;
ResourceFunction["ToTensor"][MatrixPower[A, 2]]
Out[14]=

Here the assumptions are added correctly:

In[15]:=
ResourceFunction["ToTensor"][MatrixPower[A, 2], Assumptions -> A \[Element] Arrays[{4, 4, 4}]]
Out[15]=

Only Tr expression representing traces of the first two levels of an array have equivalent TensorContract representations:

In[16]:=
ResourceFunction["ToTensor"][Tr[A] . A, Assumptions -> A \[Element] Arrays[{d, d, d}]]
Out[16]=

Publisher

Carl Woll

Version History

  • 1.1.0 – 14 December 2021
  • 1.0.0 – 16 October 2019

Related Resources

License Information