1 // This file is part of Eigen, a lightweight C++ template library
2 // for linear algebra.
3 //
4 // Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
5 //
6 // This Source Code Form is subject to the terms of the Mozilla
7 // Public License v. 2.0. If a copy of the MPL was not distributed
8 // with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 
10 #include "main.h"
11 
12 #include <Eigen/Core>
13 #include <Eigen/CXX11/Tensor>
14 
15 using Eigen::MatrixXf;
16 using Eigen::Tensor;
17 
test_simple()18 static void test_simple()
19 {
20   MatrixXf m1(3,3);
21   MatrixXf m2(3,3);
22   m1.setRandom();
23   m2.setRandom();
24 
25   TensorMap<Tensor<float, 2> > mat1(m1.data(), 3,3);
26   TensorMap<Tensor<float, 2> > mat2(m2.data(), 3,3);
27 
28   Tensor<float, 2> mat3(3,3);
29   mat3 = mat1;
30 
31   typedef Tensor<float, 1>::DimensionPair DimPair;
32   Eigen::array<DimPair, 1> dims;
33   dims[0] = DimPair(1, 0);
34 
35   mat3 = mat3.contract(mat2, dims).eval();
36 
37   VERIFY_IS_APPROX(mat3(0, 0), (m1*m2).eval()(0,0));
38   VERIFY_IS_APPROX(mat3(0, 1), (m1*m2).eval()(0,1));
39   VERIFY_IS_APPROX(mat3(0, 2), (m1*m2).eval()(0,2));
40   VERIFY_IS_APPROX(mat3(1, 0), (m1*m2).eval()(1,0));
41   VERIFY_IS_APPROX(mat3(1, 1), (m1*m2).eval()(1,1));
42   VERIFY_IS_APPROX(mat3(1, 2), (m1*m2).eval()(1,2));
43   VERIFY_IS_APPROX(mat3(2, 0), (m1*m2).eval()(2,0));
44   VERIFY_IS_APPROX(mat3(2, 1), (m1*m2).eval()(2,1));
45   VERIFY_IS_APPROX(mat3(2, 2), (m1*m2).eval()(2,2));
46 }
47 
48 
test_const()49 static void test_const()
50 {
51   MatrixXf input(3,3);
52   input.setRandom();
53   MatrixXf output = input;
54   output.rowwise() -= input.colwise().maxCoeff();
55 
56   Eigen::array<int, 1> depth_dim;
57   depth_dim[0] = 0;
58   Tensor<float, 2>::Dimensions dims2d;
59   dims2d[0] = 1;
60   dims2d[1] = 3;
61   Eigen::array<int, 2> bcast;
62   bcast[0] = 3;
63   bcast[1] = 1;
64   const TensorMap<Tensor<const float, 2> > input_tensor(input.data(), 3, 3);
65   Tensor<float, 2> output_tensor= (input_tensor - input_tensor.maximum(depth_dim).eval().reshape(dims2d).broadcast(bcast));
66 
67   for (int i = 0; i < 3; ++i) {
68     for (int j = 0; j < 3; ++j) {
69       VERIFY_IS_APPROX(output(i, j), output_tensor(i, j));
70     }
71   }
72 }
73 
74 
test_cxx11_tensor_forced_eval()75 void test_cxx11_tensor_forced_eval()
76 {
77   CALL_SUBTEST(test_simple());
78   CALL_SUBTEST(test_const());
79 }
80