11#ifndef EIGEN_TENSOR_TENSOR_IO_H
12#define EIGEN_TENSOR_TENSOR_IO_H
15#include "./InternalHeaderCheck.h"
22template <
typename Tensor, std::
size_t rank,
typename Format,
typename EnableIf =
void>
26template <
typename Derived_>
27struct TensorIOFormatBase {
28 using Derived = Derived_;
29 TensorIOFormatBase(
const std::vector<std::string>& separator,
const std::vector<std::string>& prefix,
30 const std::vector<std::string>& suffix,
int precision = StreamPrecision,
int flags = 0,
31 const std::string& tenPrefix =
"",
const std::string& tenSuffix =
"",
const char fill =
' ')
32 : tenPrefix(tenPrefix),
44 if (flags & DontAlignCols)
return;
45 spacer.resize(prefix.size());
47 int i = int(tenPrefix.length()) - 1;
48 while (i >= 0 && tenPrefix[i] !=
'\n') {
53 for (std::size_t k = 1; k < prefix.size(); k++) {
54 int j = int(prefix[k].length()) - 1;
55 while (j >= 0 && prefix[k][j] !=
'\n') {
62 std::string tenPrefix;
63 std::string tenSuffix;
64 std::vector<std::string> prefix;
65 std::vector<std::string> suffix;
66 std::vector<std::string> separator;
70 std::vector<std::string> spacer{};
73struct TensorIOFormatNumpy :
public TensorIOFormatBase<TensorIOFormatNumpy> {
74 using Base = TensorIOFormatBase<TensorIOFormatNumpy>;
76 : Base({
" ",
"\n"}, {
"",
"["}, {
"",
"]"}, StreamPrecision,
80struct TensorIOFormatNative :
public TensorIOFormatBase<TensorIOFormatNative> {
81 using Base = TensorIOFormatBase<TensorIOFormatNative>;
82 TensorIOFormatNative()
83 : Base({
", ",
",\n",
"\n"}, {
"",
"{"}, {
"",
"}"},
84 StreamPrecision, 0,
"{",
"}") {}
87struct TensorIOFormatPlain :
public TensorIOFormatBase<TensorIOFormatPlain> {
88 using Base = TensorIOFormatBase<TensorIOFormatPlain>;
90 : Base({
" ",
"\n",
"\n",
""}, {
""}, {
""}, StreamPrecision,
94struct TensorIOFormatLegacy :
public TensorIOFormatBase<TensorIOFormatLegacy> {
95 using Base = TensorIOFormatBase<TensorIOFormatLegacy>;
96 TensorIOFormatLegacy()
97 : Base({
", ",
"\n"}, {
"",
"["}, {
"",
"]"}, StreamPrecision,
101struct TensorIOFormat :
public TensorIOFormatBase<TensorIOFormat> {
102 using Base = TensorIOFormatBase<TensorIOFormat>;
103 TensorIOFormat(
const std::vector<std::string>& separator,
const std::vector<std::string>& prefix,
104 const std::vector<std::string>& suffix,
int precision = StreamPrecision,
int flags = 0,
105 const std::string& tenPrefix =
"",
const std::string& tenSuffix =
"",
const char fill =
' ')
106 : Base(separator, prefix, suffix, precision, flags, tenPrefix, tenSuffix, fill) {}
108 static inline const TensorIOFormatNumpy Numpy() {
return TensorIOFormatNumpy{}; }
110 static inline const TensorIOFormatPlain Plain() {
return TensorIOFormatPlain{}; }
112 static inline const TensorIOFormatNative Native() {
return TensorIOFormatNative{}; }
114 static inline const TensorIOFormatLegacy Legacy() {
return TensorIOFormatLegacy{}; }
117template <
typename T,
int Layout,
int rank,
typename Format>
118class TensorWithFormat;
120template <
typename T,
int rank,
typename Format>
121class TensorWithFormat<T,
RowMajor, rank, Format> {
123 TensorWithFormat(
const T& tensor,
const Format& format) : t_tensor(tensor), t_format(format) {}
125 friend std::ostream& operator<<(std::ostream& os,
const TensorWithFormat<T, RowMajor, rank, Format>& wf) {
127 using Evaluator = TensorEvaluator<const TensorForcedEvalOp<const T>, DefaultDevice>;
128 TensorForcedEvalOp<const T> eval = wf.t_tensor.eval();
129 Evaluator tensor(eval, DefaultDevice());
130 tensor.evalSubExprsIfNeeded(
nullptr);
131 internal::TensorPrinter<Evaluator, rank, Format>::run(os, tensor, wf.t_format);
142template <
typename T,
int rank,
typename Format>
143class TensorWithFormat<T,
ColMajor, rank, Format> {
145 TensorWithFormat(
const T& tensor,
const Format& format) : t_tensor(tensor), t_format(format) {}
147 friend std::ostream& operator<<(std::ostream& os,
const TensorWithFormat<T, ColMajor, rank, Format>& wf) {
149 using IndexType =
typename T::Index;
150 std::array<IndexType, rank> shuffle;
151 std::array<IndexType, rank> id;
152 std::iota(
id.begin(),
id.end(), IndexType(0));
153 std::copy(
id.begin(),
id.end(), shuffle.rbegin());
154 auto tensor_row_major = wf.t_tensor.swap_layout().shuffle(shuffle);
157 using Evaluator = TensorEvaluator<
const TensorForcedEvalOp<
const decltype(tensor_row_major)>, DefaultDevice>;
158 TensorForcedEvalOp<
const decltype(tensor_row_major)> eval = tensor_row_major.eval();
159 Evaluator tensor(eval, DefaultDevice());
160 tensor.evalSubExprsIfNeeded(
nullptr);
161 internal::TensorPrinter<Evaluator, rank, Format>::run(os, tensor, wf.t_format);
172template <
typename T,
typename Format>
173class TensorWithFormat<T,
ColMajor, 0, Format> {
175 TensorWithFormat(
const T& tensor,
const Format& format) : t_tensor(tensor), t_format(format) {}
177 friend std::ostream& operator<<(std::ostream& os,
const TensorWithFormat<T, ColMajor, 0, Format>& wf) {
179 using Evaluator = TensorEvaluator<const TensorForcedEvalOp<const T>, DefaultDevice>;
180 TensorForcedEvalOp<const T> eval = wf.t_tensor.eval();
181 Evaluator tensor(eval, DefaultDevice());
182 tensor.evalSubExprsIfNeeded(
nullptr);
183 internal::TensorPrinter<Evaluator, 0, Format>::run(os, tensor, wf.t_format);
197template <
typename Scalar,
typename Format,
typename EnableIf =
void>
198struct ScalarPrinter {
199 static void run(std::ostream& stream,
const Scalar& scalar,
const Format&) { stream << scalar; }
202template <
typename Scalar>
203struct ScalarPrinter<Scalar, TensorIOFormatNumpy, std::enable_if_t<NumTraits<Scalar>::IsComplex>> {
204 static void run(std::ostream& stream,
const Scalar& scalar,
const TensorIOFormatNumpy&) {
205 stream << numext::real(scalar) <<
"+" << numext::imag(scalar) <<
"j";
209template <
typename Scalar>
210struct ScalarPrinter<Scalar, TensorIOFormatNative, std::enable_if_t<NumTraits<Scalar>::IsComplex>> {
211 static void run(std::ostream& stream,
const Scalar& scalar,
const TensorIOFormatNative&) {
212 stream <<
"{" << numext::real(scalar) <<
", " << numext::imag(scalar) <<
"}";
216template <
typename Tensor, std::
size_t rank,
typename Format,
typename EnableIf>
217struct TensorPrinter {
218 using Scalar = std::remove_const_t<typename Tensor::Scalar>;
220 static void run(std::ostream& s,
const Tensor& tensor,
const Format& fmt) {
221 using IndexType =
typename Tensor::Index;
223 eigen_assert(Tensor::Layout ==
RowMajor);
225 std::conditional_t<std::is_same<Scalar, char>::value || std::is_same<Scalar, unsigned char>::value ||
226 std::is_same<Scalar, numext::int8_t>::value ||
227 std::is_same<Scalar, numext::uint8_t>::value,
229 std::conditional_t<std::is_same<Scalar, std::complex<char>>::value ||
230 std::is_same<Scalar, std::complex<unsigned char>>::value ||
231 std::is_same<Scalar, std::complex<numext::int8_t>>::value ||
232 std::is_same<Scalar, std::complex<numext::uint8_t>>::value,
233 std::complex<int>,
const Scalar&>>;
234 using PrintScalar = std::remove_const_t<std::remove_reference_t<PrintType>>;
236 const IndexType total_size = array_prod(tensor.dimensions());
238 std::streamsize explicit_precision;
239 if (fmt.precision == StreamPrecision) {
240 explicit_precision = 0;
241 }
else if (fmt.precision == FullPrecision) {
242 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsInteger) {
243 explicit_precision = 0;
245 explicit_precision = significant_decimals_impl<Scalar>::run();
248 explicit_precision = fmt.precision;
251 std::streamsize old_precision = 0;
252 if (explicit_precision) old_precision = s.precision(explicit_precision);
255 bool align_cols = !(fmt.flags & DontAlignCols);
258 for (IndexType i = 0; i < total_size; i++) {
259 std::stringstream sstr;
261 ScalarPrinter<PrintScalar, Format>::run(sstr,
static_cast<PrintType
>(tensor.data()[i]), fmt);
262 width = std::max<IndexType>(width, IndexType(sstr.str().length()));
266 for (IndexType i = 0; i < total_size; i++) {
267 std::array<bool, rank> is_at_end{};
268 std::array<bool, rank> is_at_begin{};
271 for (std::size_t k = 0; k < rank; k++) {
272 if ((i + 1) % (std::accumulate(tensor.dimensions().rbegin(), tensor.dimensions().rbegin() + k, 1,
273 std::multiplies<IndexType>())) ==
280 for (std::size_t k = 0; k < rank; k++) {
281 if (i % (std::accumulate(tensor.dimensions().rbegin(), tensor.dimensions().rbegin() + k, 1,
282 std::multiplies<IndexType>())) ==
284 is_at_begin[k] =
true;
289 bool is_at_begin_after_newline =
false;
290 for (std::size_t k = 0; k < rank; k++) {
291 if (is_at_begin[k]) {
292 std::size_t separator_index = (k < fmt.separator.size()) ? k : fmt.separator.size() - 1;
293 if (fmt.separator[separator_index].find(
'\n') != std::string::npos) {
294 is_at_begin_after_newline =
true;
299 bool is_at_end_before_newline =
false;
300 for (std::size_t k = 0; k < rank; k++) {
302 std::size_t separator_index = (k < fmt.separator.size()) ? k : fmt.separator.size() - 1;
303 if (fmt.separator[separator_index].find(
'\n') != std::string::npos) {
304 is_at_end_before_newline =
true;
309 std::stringstream suffix, prefix, separator;
310 for (std::size_t k = 0; k < rank; k++) {
311 std::size_t suffix_index = (k < fmt.suffix.size()) ? k : fmt.suffix.size() - 1;
313 suffix << fmt.suffix[suffix_index];
316 for (std::size_t k = 0; k < rank; k++) {
317 std::size_t separator_index = (k < fmt.separator.size()) ? k : fmt.separator.size() - 1;
319 (!is_at_end_before_newline || fmt.separator[separator_index].find(
'\n') != std::string::npos)) {
320 separator << fmt.separator[separator_index];
323 for (std::size_t k = 0; k < rank; k++) {
324 std::size_t spacer_index = (k < fmt.spacer.size()) ? k : fmt.spacer.size() - 1;
325 if (i != 0 && is_at_begin_after_newline && (!is_at_begin[k] || k == 0)) {
326 prefix << fmt.spacer[spacer_index];
329 for (
int k = rank - 1; k >= 0; k--) {
330 std::size_t prefix_index = (
static_cast<std::size_t
>(k) < fmt.prefix.size()) ? k : fmt.prefix.size() - 1;
331 if (is_at_begin[k]) {
332 prefix << fmt.prefix[prefix_index];
338 std::stringstream sstr;
340 ScalarPrinter<PrintScalar, Format>::run(sstr,
static_cast<PrintType
>(tensor.data()[i]), fmt);
341 std::string scalar_str = sstr.str();
342 IndexType scalar_width = scalar_str.length();
343 if (width && scalar_width < width) {
345 for (IndexType j = scalar_width; j < width; ++j) {
346 filler.push_back(fmt.fill);
352 if (i < total_size - 1) {
353 s << separator.str();
357 if (explicit_precision) s.precision(old_precision);
361template <
typename Tensor, std::
size_t rank>
362struct TensorPrinter<Tensor, rank, TensorIOFormatLegacy, std::enable_if_t<rank != 0>> {
363 using Format = TensorIOFormatLegacy;
364 using Scalar = std::remove_const_t<typename Tensor::Scalar>;
366 static void run(std::ostream& s,
const Tensor& tensor,
const Format&) {
367 using IndexType =
typename Tensor::Index;
370 const IndexType total_size = internal::array_prod(tensor.dimensions());
371 if (total_size > 0) {
372 const IndexType first_dim = Eigen::internal::array_get<0>(tensor.dimensions());
373 Map<const Array<Scalar, Dynamic, Dynamic, Tensor::Layout>> matrix(tensor.data(), first_dim,
374 total_size / first_dim);
381template <
typename Tensor,
typename Format>
382struct TensorPrinter<Tensor, 0, Format> {
383 static void run(std::ostream& s,
const Tensor& tensor,
const Format& fmt) {
384 using Scalar = std::remove_const_t<typename Tensor::Scalar>;
386 std::streamsize explicit_precision;
387 if (fmt.precision == StreamPrecision) {
388 explicit_precision = 0;
389 }
else if (fmt.precision == FullPrecision) {
390 EIGEN_IF_CONSTEXPR (NumTraits<Scalar>::IsInteger) {
391 explicit_precision = 0;
393 explicit_precision = significant_decimals_impl<Scalar>::run();
396 explicit_precision = fmt.precision;
399 std::streamsize old_precision = 0;
400 if (explicit_precision) old_precision = s.precision(explicit_precision);
402 ScalarPrinter<Scalar, Format>::run(s, tensor.coeff(0), fmt);
404 if (explicit_precision) s.precision(old_precision);
411 s << t.format(TensorIOFormat::Plain());
The tensor base class.
Definition TensorForwardDeclarations.h:69
Namespace containing all symbols from the Eigen library.