ostream.hpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. // Copyright 2015-2019 Hans Dembinski
  2. // Copyright 2019 Przemyslaw Bartosik
  3. //
  4. // Distributed under the Boost Software License, Version 1.0.
  5. // (See accompanying file LICENSE_1_0.txt
  6. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #ifndef BOOST_HISTOGRAM_OSTREAM_HPP
  8. #define BOOST_HISTOGRAM_OSTREAM_HPP
  9. #include <boost/histogram/accumulators/ostream.hpp>
  10. #include <boost/histogram/axis/ostream.hpp>
  11. #include <boost/histogram/detail/counting_streambuf.hpp>
  12. #include <boost/histogram/detail/priority.hpp>
  13. #include <boost/histogram/indexed.hpp>
  14. #include <cmath>
  15. #include <iomanip>
  16. #include <ios>
  17. #include <limits>
  18. #include <numeric>
  19. #include <ostream>
  20. #include <streambuf>
  21. #include <type_traits>
  22. /**
  23. \file boost/histogram/ostream.hpp
  24. A simple streaming operator for the histogram type. The text representation is
  25. rudimentary and not guaranteed to be stable between versions of Boost.Histogram. This
  26. header is not included by any other header and must be explicitly included to use the
  27. streaming operator.
  28. To use your own, simply include your own implementation instead of this header.
  29. */
  30. namespace boost {
  31. namespace histogram {
  32. namespace detail {
  33. template <class OStream, unsigned N>
  34. class tabular_ostream_wrapper : public std::array<int, N> {
  35. using base_t = std::array<int, N>;
  36. using char_type = typename OStream::char_type;
  37. using traits_type = typename OStream::traits_type;
  38. public:
  39. template <class T>
  40. tabular_ostream_wrapper& operator<<(const T& t) {
  41. if (collect_) {
  42. if (static_cast<unsigned>(iter_ - base_t::begin()) == size_) {
  43. ++size_;
  44. assert(size_ <= N);
  45. assert(iter_ != end());
  46. *iter_ = 0;
  47. }
  48. count_ = 0;
  49. os_ << t;
  50. *iter_ = std::max(*iter_, static_cast<int>(count_));
  51. } else {
  52. assert(iter_ != end());
  53. os_ << std::setw(*iter_) << t;
  54. }
  55. ++iter_;
  56. return *this;
  57. }
  58. tabular_ostream_wrapper& operator<<(decltype(std::setprecision(0)) t) {
  59. os_ << t;
  60. return *this;
  61. }
  62. tabular_ostream_wrapper& operator<<(decltype(std::fixed) t) {
  63. os_ << t;
  64. return *this;
  65. }
  66. tabular_ostream_wrapper& row() {
  67. iter_ = base_t::begin();
  68. return *this;
  69. }
  70. explicit tabular_ostream_wrapper(OStream& os)
  71. : os_(os), cbuf_(count_), orig_(os_.rdbuf(&cbuf_)) {}
  72. auto end() { return base_t::begin() + size_; }
  73. auto end() const { return base_t::begin() + size_; }
  74. auto cend() const { return base_t::cbegin() + size_; }
  75. void complete() {
  76. assert(collect_); // only call this once
  77. collect_ = false;
  78. os_.rdbuf(orig_);
  79. }
  80. private:
  81. typename base_t::iterator iter_ = base_t::begin();
  82. unsigned size_ = 0;
  83. std::streamsize count_ = 0;
  84. bool collect_ = true;
  85. OStream& os_;
  86. counting_streambuf<char_type, traits_type> cbuf_;
  87. std::basic_streambuf<char_type, traits_type>* orig_;
  88. };
  89. template <class OStream, class T>
  90. void ostream_value_impl(OStream& os, const T& t,
  91. decltype(static_cast<double>(t), priority<1>{})) {
  92. // a value from histogram cell
  93. const auto d = static_cast<double>(t);
  94. if (std::numeric_limits<int>::min() <= d && d <= std::numeric_limits<int>::max()) {
  95. const auto i = static_cast<int>(d);
  96. if (i == d) {
  97. os << i;
  98. return;
  99. }
  100. }
  101. os << std::defaultfloat << std::setprecision(4) << d;
  102. }
  103. template <class OStream, class T>
  104. void ostream_value_impl(OStream& os, const T& t, priority<0>) {
  105. os << t;
  106. }
  107. template <class OStream, class T>
  108. void ostream_value(OStream& os, const T& t) {
  109. ostream_value_impl(os << std::left, t, priority<1>{});
  110. }
  111. template <class OStream, class Axis>
  112. auto ostream_bin(OStream& os, const Axis& ax, axis::index_type i, std::true_type,
  113. priority<1>) -> decltype((void)ax.value(i)) {
  114. auto a = ax.value(i), b = ax.value(i + 1);
  115. os << std::right << std::defaultfloat << std::setprecision(4);
  116. // round edges to zero if deviation from zero is small
  117. const auto eps = 1e-8 * std::abs(b - a);
  118. if (std::abs(a) < 1e-14 && std::abs(a) < eps) a = 0;
  119. if (std::abs(b) < 1e-14 && std::abs(b) < eps) b = 0;
  120. os << "[" << a << ", " << b << ")";
  121. }
  122. template <class OStream, class Axis>
  123. auto ostream_bin(OStream& os, const Axis& ax, axis::index_type i, std::false_type,
  124. priority<1>) -> decltype((void)ax.value(i)) {
  125. os << std::right;
  126. os << ax.value(i);
  127. }
  128. template <class OStream, class... Ts>
  129. void ostream_bin(OStream& os, const axis::category<Ts...>& ax, axis::index_type i,
  130. std::false_type, priority<1>) {
  131. os << std::right;
  132. if (i < ax.size())
  133. os << ax.value(i);
  134. else
  135. os << "other";
  136. }
  137. template <class OStream, class Axis, class B>
  138. void ostream_bin(OStream& os, const Axis&, axis::index_type i, B, priority<0>) {
  139. os << std::right;
  140. os << i;
  141. }
  142. template <class CharT>
  143. struct line_t {
  144. CharT ch;
  145. int size;
  146. };
  147. template <class CharT>
  148. auto line(CharT c, int n) {
  149. return line_t<CharT>{c, n};
  150. }
  151. template <class C, class T>
  152. std::basic_ostream<C, T>& operator<<(std::basic_ostream<C, T>& os, line_t<C>&& l) {
  153. for (int i = 0; i < l.size; ++i) os << l.ch;
  154. return os;
  155. }
  156. template <class OStream, class Axis>
  157. void ostream_head(OStream& os, const Axis& ax, int index, double val) {
  158. axis::visit(
  159. [&](const auto& ax) {
  160. using A = std::decay_t<decltype(ax)>;
  161. ostream_bin(os, ax, index, axis::traits::is_continuous<A>{}, priority<1>{});
  162. os << ' ';
  163. ostream_value(os, val);
  164. },
  165. ax);
  166. }
  167. // cannot display generalized histograms yet; line not reachable by coverage tests
  168. template <class OStream, class Histogram>
  169. void ascii_plot(OStream&, const Histogram&, int, std::false_type) {} // LCOV_EXCL_LINE
  170. template <class OStream, class Histogram>
  171. void ascii_plot(OStream& os, const Histogram& h, int w_total, std::true_type) {
  172. if (w_total == 0) w_total = 78; // TODO detect actual width of terminal
  173. const auto& ax = h.axis();
  174. // value range; can be integer or float, positive or negative
  175. double vmin = 0;
  176. double vmax = 0;
  177. tabular_ostream_wrapper<OStream, 7> tos(os);
  178. // first pass to get widths
  179. for (auto&& v : indexed(h, coverage::all)) {
  180. ostream_head(tos.row(), ax, v.index(), *v);
  181. vmin = std::min(vmin, static_cast<double>(*v));
  182. vmax = std::max(vmax, static_cast<double>(*v));
  183. }
  184. tos.complete();
  185. if (vmax == 0) vmax = 1;
  186. // calculate width useable by bar (notice extra space at top)
  187. // <-- head --> |<--- bar ---> |
  188. // w_head + 2 + 2
  189. const auto w_head = std::accumulate(tos.begin(), tos.end(), 0);
  190. const auto w_bar = w_total - 4 - w_head;
  191. if (w_bar < 0) return;
  192. // draw upper line
  193. os << '\n' << line(' ', w_head + 1) << '+' << line('-', w_bar + 1) << "+\n";
  194. const int zero_offset = static_cast<int>(std::lround((-vmin) / (vmax - vmin) * w_bar));
  195. for (auto&& v : indexed(h, coverage::all)) {
  196. ostream_head(tos.row(), ax, v.index(), *v);
  197. // rest uses os, not tos
  198. os << " |";
  199. const int k = static_cast<int>(std::lround(*v / (vmax - vmin) * w_bar));
  200. if (k < 0) {
  201. os << line(' ', zero_offset + k) << line('=', -k) << line(' ', w_bar - zero_offset);
  202. } else {
  203. os << line(' ', zero_offset) << line('=', k) << line(' ', w_bar - zero_offset - k);
  204. }
  205. os << " |\n";
  206. }
  207. // draw lower line
  208. os << line(' ', w_head + 1) << '+' << line('-', w_bar + 1) << "+\n";
  209. }
  210. template <class OStream, class Histogram>
  211. void ostream(OStream& os, const Histogram& h, const bool show_values = true) {
  212. os << "histogram(";
  213. unsigned iaxis = 0;
  214. const auto rank = h.rank();
  215. h.for_each_axis([&](const auto& ax) {
  216. if ((show_values && rank > 0) || rank > 1) os << "\n ";
  217. ostream_any(os, ax);
  218. });
  219. if (show_values && rank > 0) {
  220. tabular_ostream_wrapper<OStream, (BOOST_HISTOGRAM_DETAIL_AXES_LIMIT + 1)> tos(os);
  221. for (auto&& v : indexed(h, coverage::all)) {
  222. tos.row();
  223. for (auto i : v.indices()) tos << std::right << i;
  224. ostream_value(tos, *v);
  225. }
  226. tos.complete();
  227. const int w_item = std::accumulate(tos.begin(), tos.end(), 0) + 4 + h.rank();
  228. const int nrow = std::max(1, 65 / w_item);
  229. int irow = 0;
  230. for (auto&& v : indexed(h, coverage::all)) {
  231. os << (irow == 0 ? "\n (" : " (");
  232. tos.row();
  233. iaxis = 0;
  234. for (auto i : v.indices()) {
  235. tos << std::right << i;
  236. os << (++iaxis == h.rank() ? "):" : " ");
  237. }
  238. os << ' ';
  239. ostream_value(tos, *v);
  240. ++irow;
  241. if (nrow > 0 && irow == nrow) irow = 0;
  242. }
  243. os << '\n';
  244. }
  245. os << ')';
  246. }
  247. } // namespace detail
  248. #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
  249. template <class CharT, class Traits, class A, class S>
  250. std::basic_ostream<CharT, Traits>& operator<<(std::basic_ostream<CharT, Traits>& os,
  251. const histogram<A, S>& h) {
  252. // save fmt
  253. const auto flags = os.flags();
  254. os.flags(std::ios::dec | std::ios::left);
  255. const auto w = static_cast<int>(os.width());
  256. os.width(0);
  257. using value_type = typename histogram<A, S>::value_type;
  258. // must be non-const to avoid a msvc warning about possible use of if constexpr
  259. bool show_ascii = std::is_convertible<value_type, double>::value && h.rank() == 1;
  260. if (show_ascii) {
  261. detail::ostream(os, h, false);
  262. detail::ascii_plot(os, h, w, std::is_convertible<value_type, double>{});
  263. } else {
  264. detail::ostream(os, h);
  265. }
  266. // restore fmt
  267. os.flags(flags);
  268. return os;
  269. }
  270. } // namespace histogram
  271. } // namespace boost
  272. #endif // BOOST_HISTOGRAM_DOXYGEN_INVOKED
  273. #endif