Search code examples
c++eigentensoreigen3

Tensor-contraction, how do i choose the indexes which should be contracted over?


I would like to perform simple Tensorcontractions with the Eigen::Tensor module, but so far, i dont understand the way you adress the right dimensions.

Here is my current code:

Eigen::Tensor<double, 3> B(3,4,3); B.setRandom();
Eigen::Tensor<double, 3> C(3,4,3); C.setRandom();

// Eigen::array<Eigen::IndexList<int,int,int>,1> idx = 
//                      {Eigen::IndexList<int,int,int>(1,0,0)}; 
//                       also does not seem to be the way
Eigen::array<int,3> idx({0,0,1});
Eigen::Tensor<double, 4> D = B.contract(C, idx);

I would just like to contract over the last dimension of B and the first dimension of C. But i dont understand how the system works and the documentation only gives you an example for 2D-Tensors.

//the first element of IDXPair is the choosen index in B and the second the idx for C
Eigen::array<Eigen::IndexPair<int>,1> idx = {Eigen::IndexPair<int>(2,0)};

Here the second index would be multiplied with the zeroth of the second tensor.


Solution

  • The IndexPair stands for exactly what is says: The first Index in the tensor-dimensions is mapped to the second index in the second tensor.

    IdxPair(a,b) => A(1,2,3,4,x) * B(x,5,6,7,8,9) where a is the index of the last dimension, in this case x and b the index of the dimension in the second tensor