variable.hpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Copyright 2015-2018 Hans Dembinski
  2. //
  3. // Distributed under the Boost Software License, Version 1.0.
  4. // (See accompanying file LICENSE_1_0.txt
  5. // or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. #ifndef BOOST_HISTOGRAM_AXIS_VARIABLE_HPP
  7. #define BOOST_HISTOGRAM_AXIS_VARIABLE_HPP
  8. #include <algorithm>
  9. #include <boost/core/nvp.hpp>
  10. #include <boost/histogram/axis/interval_view.hpp>
  11. #include <boost/histogram/axis/iterator.hpp>
  12. #include <boost/histogram/axis/metadata_base.hpp>
  13. #include <boost/histogram/axis/option.hpp>
  14. #include <boost/histogram/detail/convert_integer.hpp>
  15. #include <boost/histogram/detail/detect.hpp>
  16. #include <boost/histogram/detail/limits.hpp>
  17. #include <boost/histogram/detail/relaxed_equal.hpp>
  18. #include <boost/histogram/detail/replace_type.hpp>
  19. #include <boost/histogram/fwd.hpp>
  20. #include <boost/throw_exception.hpp>
  21. #include <cassert>
  22. #include <cmath>
  23. #include <limits>
  24. #include <memory>
  25. #include <stdexcept>
  26. #include <string>
  27. #include <type_traits>
  28. #include <utility>
  29. #include <vector>
  30. namespace boost {
  31. namespace histogram {
  32. namespace axis {
  33. /** Axis for non-equidistant bins on the real line.
  34. Binning is a O(log(N)) operation. If speed matters and the problem domain
  35. allows it, prefer a regular axis, possibly with a transform.
  36. If the axis has an overflow bin (the default), a value on the upper edge of the last
  37. bin is put in the overflow bin. The axis range represents a semi-open interval.
  38. If the overflow bin is deactivated, then a value on the upper edge of the last bin is
  39. still counted towards the last bin. The axis range represents a closed interval. This
  40. is the desired behavior for random numbers drawn from a bounded interval, which is
  41. usually closed.
  42. @tparam Value input value type, must be floating point.
  43. @tparam MetaData type to store meta data.
  44. @tparam Options see boost::histogram::axis::option.
  45. @tparam Allocator allocator to use for dynamic memory management.
  46. */
  47. template <class Value, class MetaData, class Options, class Allocator>
  48. class variable : public iterator_mixin<variable<Value, MetaData, Options, Allocator>>,
  49. public metadata_base_t<MetaData> {
  50. // these must be private, so that they are not automatically inherited
  51. using value_type = Value;
  52. using metadata_base = metadata_base_t<MetaData>;
  53. using metadata_type = typename metadata_base::metadata_type;
  54. using options_type =
  55. detail::replace_default<Options, decltype(option::underflow | option::overflow)>;
  56. using allocator_type = Allocator;
  57. using vector_type = std::vector<Value, allocator_type>;
  58. public:
  59. constexpr variable() = default;
  60. explicit variable(allocator_type alloc) : vec_(alloc) {}
  61. /** Construct from forward iterator range of bin edges.
  62. @param begin begin of edge sequence.
  63. @param end end of edge sequence.
  64. @param meta description of the axis (optional).
  65. @param options see boost::histogram::axis::option (optional).
  66. @param alloc allocator instance to use (optional).
  67. The constructor throws `std::invalid_argument` if iterator range is invalid, if less
  68. than two edges are provided or if bin edges are not in ascending order.
  69. The arguments meta and alloc are passed by value. If you move either of them into the
  70. axis and the constructor throws, their values are lost. Do not move if you cannot
  71. guarantee that the bin description is not valid.
  72. */
  73. template <class It, class = detail::requires_iterator<It>>
  74. variable(It begin, It end, metadata_type meta = {}, options_type options = {},
  75. allocator_type alloc = {})
  76. : metadata_base(std::move(meta)), vec_(std::move(alloc)) {
  77. // static_asserts were moved here from class scope to satisfy deduction in gcc>=11
  78. static_assert(
  79. std::is_floating_point<value_type>::value,
  80. "current version of variable axis requires floating point type; "
  81. "if you need a variable axis with an integral type, please submit an issue");
  82. static_assert((!options.test(option::circular) && !options.test(option::growth)) ||
  83. (options.test(option::circular) ^ options.test(option::growth)),
  84. "circular and growth options are mutually exclusive");
  85. const auto n = std::distance(begin, end);
  86. if (n < 0)
  87. BOOST_THROW_EXCEPTION(
  88. std::invalid_argument("end must be reachable by incrementing begin"));
  89. if (n < 2) BOOST_THROW_EXCEPTION(std::invalid_argument("bins > 1 required"));
  90. vec_.reserve(n);
  91. vec_.emplace_back(*begin++);
  92. bool strictly_ascending = true;
  93. for (; begin != end; ++begin) {
  94. strictly_ascending &= vec_.back() < *begin;
  95. vec_.emplace_back(*begin);
  96. }
  97. if (!strictly_ascending)
  98. BOOST_THROW_EXCEPTION(
  99. std::invalid_argument("input sequence must be strictly ascending"));
  100. }
  101. // kept for backward compatibility; requires_allocator is a workaround for deduction
  102. // guides in gcc>=11
  103. template <class It, class A, class = detail::requires_iterator<It>,
  104. class = detail::requires_allocator<A>>
  105. variable(It begin, It end, metadata_type meta, A alloc)
  106. : variable(begin, end, std::move(meta), {}, std::move(alloc)) {}
  107. /** Construct variable axis from iterable range of bin edges.
  108. @param iterable iterable range of bin edges.
  109. @param meta description of the axis (optional).
  110. @param options see boost::histogram::axis::option (optional).
  111. @param alloc allocator instance to use (optional).
  112. */
  113. template <class U, class = detail::requires_iterable<U>>
  114. variable(const U& iterable, metadata_type meta = {}, options_type options = {},
  115. allocator_type alloc = {})
  116. : variable(std::begin(iterable), std::end(iterable), std::move(meta), options,
  117. std::move(alloc)) {}
  118. // kept for backward compatibility; requires_allocator is a workaround for deduction
  119. // guides in gcc>=11
  120. template <class U, class A, class = detail::requires_iterable<U>,
  121. class = detail::requires_allocator<A>>
  122. variable(const U& iterable, metadata_type meta, A alloc)
  123. : variable(std::begin(iterable), std::end(iterable), std::move(meta), {},
  124. std::move(alloc)) {}
  125. /** Construct variable axis from initializer list of bin edges.
  126. @param list `std::initializer_list` of bin edges.
  127. @param meta description of the axis (optional).
  128. @param options see boost::histogram::axis::option (optional).
  129. @param alloc allocator instance to use (optional).
  130. */
  131. template <class U>
  132. variable(std::initializer_list<U> list, metadata_type meta = {},
  133. options_type options = {}, allocator_type alloc = {})
  134. : variable(list.begin(), list.end(), std::move(meta), options, std::move(alloc)) {}
  135. // kept for backward compatibility; requires_allocator is a workaround for deduction
  136. // guides in gcc>=11
  137. template <class U, class A, class = detail::requires_allocator<A>>
  138. variable(std::initializer_list<U> list, metadata_type meta, A alloc)
  139. : variable(list.begin(), list.end(), std::move(meta), {}, std::move(alloc)) {}
  140. /// Constructor used by algorithm::reduce to shrink and rebin (not for users).
  141. variable(const variable& src, index_type begin, index_type end, unsigned merge)
  142. : metadata_base(src), vec_(src.get_allocator()) {
  143. assert((end - begin) % merge == 0);
  144. if (options_type::test(option::circular) && !(begin == 0 && end == src.size()))
  145. BOOST_THROW_EXCEPTION(std::invalid_argument("cannot shrink circular axis"));
  146. vec_.reserve((end - begin) / merge);
  147. const auto beg = src.vec_.begin();
  148. for (index_type i = begin; i <= end; i += merge) vec_.emplace_back(*(beg + i));
  149. }
  150. /// Return index for value argument.
  151. index_type index(value_type x) const noexcept {
  152. if (options_type::test(option::circular)) {
  153. const auto a = vec_[0];
  154. const auto b = vec_[size()];
  155. x -= std::floor((x - a) / (b - a)) * (b - a);
  156. }
  157. // upper edge of last bin is inclusive if overflow bin is not present
  158. if (!options_type::test(option::overflow) && x == vec_.back()) return size() - 1;
  159. return static_cast<index_type>(std::upper_bound(vec_.begin(), vec_.end(), x) -
  160. vec_.begin() - 1);
  161. }
  162. std::pair<index_type, index_type> update(value_type x) noexcept {
  163. const auto i = index(x);
  164. if (std::isfinite(x)) {
  165. if (0 <= i) {
  166. if (i < size()) return std::make_pair(i, 0);
  167. const auto d = value(size()) - value(size() - 0.5);
  168. x = std::nextafter(x, (std::numeric_limits<value_type>::max)());
  169. x = (std::max)(x, vec_.back() + d);
  170. vec_.push_back(x);
  171. return {i, -1};
  172. }
  173. const auto d = value(0.5) - value(0);
  174. x = (std::min)(x, value(0) - d);
  175. vec_.insert(vec_.begin(), x);
  176. return {0, -i};
  177. }
  178. return {x < 0 ? -1 : size(), 0};
  179. }
  180. /// Return value for fractional index argument.
  181. value_type value(real_index_type i) const noexcept {
  182. if (options_type::test(option::circular)) {
  183. auto shift = std::floor(i / size());
  184. i -= shift * size();
  185. double z;
  186. const auto k = static_cast<index_type>(std::modf(i, &z));
  187. const auto a = vec_[0];
  188. const auto b = vec_[size()];
  189. return (1.0 - z) * vec_[k] + z * vec_[k + 1] + shift * (b - a);
  190. }
  191. if (i < 0) return detail::lowest<value_type>();
  192. if (i == size()) return vec_.back();
  193. if (i > size()) return detail::highest<value_type>();
  194. const auto k = static_cast<index_type>(i); // precond: i >= 0
  195. const real_index_type z = i - k;
  196. // check z == 0 needed to avoid returning nan when vec_[k + 1] is infinity
  197. return (1.0 - z) * vec_[k] + (z == 0 ? 0 : z * vec_[k + 1]);
  198. }
  199. /// Return bin for index argument.
  200. auto bin(index_type idx) const noexcept { return interval_view<variable>(*this, idx); }
  201. /// Returns the number of bins, without over- or underflow.
  202. index_type size() const noexcept { return static_cast<index_type>(vec_.size()) - 1; }
  203. /// Returns the options.
  204. static constexpr unsigned options() noexcept { return options_type::value; }
  205. template <class V, class M, class O, class A>
  206. bool operator==(const variable<V, M, O, A>& o) const noexcept {
  207. const auto& a = vec_;
  208. const auto& b = o.vec_;
  209. return std::equal(a.begin(), a.end(), b.begin(), b.end()) &&
  210. detail::relaxed_equal{}(this->metadata(), o.metadata());
  211. }
  212. template <class V, class M, class O, class A>
  213. bool operator!=(const variable<V, M, O, A>& o) const noexcept {
  214. return !operator==(o);
  215. }
  216. /// Return allocator instance.
  217. auto get_allocator() const { return vec_.get_allocator(); }
  218. template <class Archive>
  219. void serialize(Archive& ar, unsigned /* version */) {
  220. ar& make_nvp("seq", vec_);
  221. ar& make_nvp("meta", this->metadata());
  222. }
  223. private:
  224. vector_type vec_;
  225. template <class V, class M, class O, class A>
  226. friend class variable;
  227. };
  228. #if __cpp_deduction_guides >= 201606
  229. template <class T>
  230. variable(std::initializer_list<T>)
  231. -> variable<detail::convert_integer<T, double>, null_type>;
  232. template <class T, class M>
  233. variable(std::initializer_list<T>, M)
  234. -> variable<detail::convert_integer<T, double>,
  235. detail::replace_type<std::decay_t<M>, const char*, std::string>>;
  236. template <class T, class M, unsigned B>
  237. variable(std::initializer_list<T>, M, const option::bitset<B>&)
  238. -> variable<detail::convert_integer<T, double>,
  239. detail::replace_type<std::decay_t<M>, const char*, std::string>,
  240. option::bitset<B>>;
  241. template <class Iterable, class = detail::requires_iterable<Iterable>>
  242. variable(Iterable) -> variable<
  243. detail::convert_integer<
  244. std::decay_t<decltype(*std::begin(std::declval<Iterable&>()))>, double>,
  245. null_type>;
  246. template <class Iterable, class M>
  247. variable(Iterable, M) -> variable<
  248. detail::convert_integer<
  249. std::decay_t<decltype(*std::begin(std::declval<Iterable&>()))>, double>,
  250. detail::replace_type<std::decay_t<M>, const char*, std::string>>;
  251. template <class Iterable, class M, unsigned B>
  252. variable(Iterable, M, const option::bitset<B>&) -> variable<
  253. detail::convert_integer<
  254. std::decay_t<decltype(*std::begin(std::declval<Iterable&>()))>, double>,
  255. detail::replace_type<std::decay_t<M>, const char*, std::string>, option::bitset<B>>;
  256. #endif
  257. } // namespace axis
  258. } // namespace histogram
  259. } // namespace boost
  260. #endif