TensorIO.h
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 #ifndef EIGEN_CXX11_TENSOR_TENSOR_IO_H
11 #define EIGEN_CXX11_TENSOR_TENSOR_IO_H
12 
13 namespace Eigen {
14 
15 namespace internal {
16 template<>
17 struct significant_decimals_impl<std::string>
18  : significant_decimals_default_impl<std::string, true>
19 {};
20 }
21 
22 
23 template <typename T>
24 std::ostream& operator << (std::ostream& os, const TensorBase<T, ReadOnlyAccessors>& expr) {
25  // Evaluate the expression if needed
26  TensorForcedEvalOp<const T> eval = expr.eval();
27  TensorEvaluator<const TensorForcedEvalOp<const T>, DefaultDevice> tensor(eval, DefaultDevice());
28  tensor.evalSubExprsIfNeeded(NULL);
29 
30  typedef typename internal::remove_const<typename T::Scalar>::type Scalar;
31  typedef typename T::Index Index;
32  typedef typename TensorEvaluator<const TensorForcedEvalOp<const T>, DefaultDevice>::Dimensions Dimensions;
33  const Index total_size = internal::array_prod(tensor.dimensions());
34 
35  // Print the tensor as a 1d vector or a 2d matrix.
36  static const int rank = internal::array_size<Dimensions>::value;
37  if (rank == 0) {
38  os << tensor.coeff(0);
39  } else if (rank == 1) {
40  Map<const Array<Scalar, Dynamic, 1> > array(const_cast<Scalar*>(tensor.data()), total_size);
41  os << array;
42  } else {
43  const Index first_dim = Eigen::internal::array_get<0>(tensor.dimensions());
44  static const int layout = TensorEvaluator<const TensorForcedEvalOp<const T>, DefaultDevice>::Layout;
45  Map<const Array<Scalar, Dynamic, Dynamic, layout> > matrix(const_cast<Scalar*>(tensor.data()), first_dim, total_size/first_dim);
46  os << matrix;
47  }
48 
49  // Cleanup.
50  tensor.cleanup();
51  return os;
52 }
53 
54 } // end namespace Eigen
55 
56 #endif // EIGEN_CXX11_TENSOR_TENSOR_IO_H
Namespace containing all symbols from the Eigen library.
Definition: CXX11Meta.h:13