variable.hpp 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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/assert.hpp>
  10. #include <boost/core/nvp.hpp>
  11. #include <boost/histogram/axis/interval_view.hpp>
  12. #include <boost/histogram/axis/iterator.hpp>
  13. #include <boost/histogram/axis/metadata_base.hpp>
  14. #include <boost/histogram/axis/option.hpp>
  15. #include <boost/histogram/detail/convert_integer.hpp>
  16. #include <boost/histogram/detail/detect.hpp>
  17. #include <boost/histogram/detail/limits.hpp>
  18. #include <boost/histogram/detail/replace_type.hpp>
  19. #include <boost/histogram/fwd.hpp>
  20. #include <boost/throw_exception.hpp>
  21. #include <cmath>
  22. #include <limits>
  23. #include <memory>
  24. #include <stdexcept>
  25. #include <string>
  26. #include <type_traits>
  27. #include <utility>
  28. #include <vector>
  29. namespace boost {
  30. namespace histogram {
  31. namespace axis {
  32. /**
  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. @tparam Value input value type, must be floating point.
  37. @tparam MetaData type to store meta data.
  38. @tparam Options see boost::histogram::axis::option (all values allowed).
  39. @tparam Allocator allocator to use for dynamic memory management.
  40. */
  41. template <class Value, class MetaData, class Options, class Allocator>
  42. class variable : public iterator_mixin<variable<Value, MetaData, Options, Allocator>>,
  43. public metadata_base<MetaData> {
  44. // these must be private, so that they are not automatically inherited
  45. using value_type = Value;
  46. using metadata_type = typename metadata_base<MetaData>::metadata_type;
  47. using options_type =
  48. detail::replace_default<Options, decltype(option::underflow | option::overflow)>;
  49. using allocator_type = Allocator;
  50. using vector_type = std::vector<Value, allocator_type>;
  51. static_assert(
  52. std::is_floating_point<value_type>::value,
  53. "current version of variable axis requires floating point type; "
  54. "if you need a variable axis with an integral type, please submit an issue");
  55. static_assert(
  56. (!options_type::test(option::circular) && !options_type::test(option::growth)) ||
  57. (options_type::test(option::circular) ^ options_type::test(option::growth)),
  58. "circular and growth options are mutually exclusive");
  59. public:
  60. constexpr variable() = default;
  61. explicit variable(allocator_type alloc) : vec_(alloc) {}
  62. /** Construct from iterator range of bin edges.
  63. *
  64. * \param begin begin of edge sequence.
  65. * \param end end of edge sequence.
  66. * \param meta description of the axis.
  67. * \param alloc allocator instance to use.
  68. */
  69. template <class It, class = detail::requires_iterator<It>>
  70. variable(It begin, It end, metadata_type meta = {}, allocator_type alloc = {})
  71. : metadata_base<MetaData>(std::move(meta)), vec_(std::move(alloc)) {
  72. if (std::distance(begin, end) < 2)
  73. BOOST_THROW_EXCEPTION(std::invalid_argument("bins > 0 required"));
  74. vec_.reserve(std::distance(begin, end));
  75. vec_.emplace_back(*begin++);
  76. bool strictly_ascending = true;
  77. while (begin != end) {
  78. if (*begin <= vec_.back()) strictly_ascending = false;
  79. vec_.emplace_back(*begin++);
  80. }
  81. if (!strictly_ascending)
  82. BOOST_THROW_EXCEPTION(
  83. std::invalid_argument("input sequence must be strictly ascending"));
  84. }
  85. /** Construct variable axis from iterable range of bin edges.
  86. *
  87. * \param iterable iterable range of bin edges.
  88. * \param meta description of the axis.
  89. * \param alloc allocator instance to use.
  90. */
  91. template <class U, class = detail::requires_iterable<U>>
  92. variable(const U& iterable, metadata_type meta = {}, allocator_type alloc = {})
  93. : variable(std::begin(iterable), std::end(iterable), std::move(meta),
  94. std::move(alloc)) {}
  95. /** Construct variable axis from initializer list of bin edges.
  96. *
  97. * @param list `std::initializer_list` of bin edges.
  98. * @param meta description of the axis.
  99. * @param alloc allocator instance to use.
  100. */
  101. template <class U>
  102. variable(std::initializer_list<U> list, metadata_type meta = {},
  103. allocator_type alloc = {})
  104. : variable(list.begin(), list.end(), std::move(meta), std::move(alloc)) {}
  105. /// Constructor used by algorithm::reduce to shrink and rebin (not for users).
  106. variable(const variable& src, index_type begin, index_type end, unsigned merge)
  107. : metadata_base<MetaData>(src), vec_(src.get_allocator()) {
  108. BOOST_ASSERT((end - begin) % merge == 0);
  109. if (options_type::test(option::circular) && !(begin == 0 && end == src.size()))
  110. BOOST_THROW_EXCEPTION(std::invalid_argument("cannot shrink circular axis"));
  111. vec_.reserve((end - begin) / merge);
  112. const auto beg = src.vec_.begin();
  113. for (index_type i = begin; i <= end; i += merge) vec_.emplace_back(*(beg + i));
  114. }
  115. /// Return index for value argument.
  116. index_type index(value_type x) const noexcept {
  117. if (options_type::test(option::circular)) {
  118. const auto a = vec_[0];
  119. const auto b = vec_[size()];
  120. x -= std::floor((x - a) / (b - a)) * (b - a);
  121. }
  122. return static_cast<index_type>(std::upper_bound(vec_.begin(), vec_.end(), x) -
  123. vec_.begin() - 1);
  124. }
  125. std::pair<index_type, index_type> update(value_type x) noexcept {
  126. const auto i = index(x);
  127. if (std::isfinite(x)) {
  128. if (0 <= i) {
  129. if (i < size()) return std::make_pair(i, 0);
  130. const auto d = value(size()) - value(size() - 0.5);
  131. x = std::nextafter(x, (std::numeric_limits<value_type>::max)());
  132. x = (std::max)(x, vec_.back() + d);
  133. vec_.push_back(x);
  134. return {i, -1};
  135. }
  136. const auto d = value(0.5) - value(0);
  137. x = (std::min)(x, value(0) - d);
  138. vec_.insert(vec_.begin(), x);
  139. return {0, -i};
  140. }
  141. return {x < 0 ? -1 : size(), 0};
  142. }
  143. /// Return value for fractional index argument.
  144. value_type value(real_index_type i) const noexcept {
  145. if (options_type::test(option::circular)) {
  146. auto shift = std::floor(i / size());
  147. i -= shift * size();
  148. double z;
  149. const auto k = static_cast<index_type>(std::modf(i, &z));
  150. const auto a = vec_[0];
  151. const auto b = vec_[size()];
  152. return (1.0 - z) * vec_[k] + z * vec_[k + 1] + shift * (b - a);
  153. }
  154. if (i < 0) return detail::lowest<value_type>();
  155. if (i == size()) return vec_.back();
  156. if (i > size()) return detail::highest<value_type>();
  157. const auto k = static_cast<index_type>(i); // precond: i >= 0
  158. const real_index_type z = i - k;
  159. return (1.0 - z) * vec_[k] + z * vec_[k + 1];
  160. }
  161. /// Return bin for index argument.
  162. auto bin(index_type idx) const noexcept { return interval_view<variable>(*this, idx); }
  163. /// Returns the number of bins, without over- or underflow.
  164. index_type size() const noexcept { return static_cast<index_type>(vec_.size()) - 1; }
  165. /// Returns the options.
  166. static constexpr unsigned options() noexcept { return options_type::value; }
  167. template <class V, class M, class O, class A>
  168. bool operator==(const variable<V, M, O, A>& o) const noexcept {
  169. const auto& a = vec_;
  170. const auto& b = o.vec_;
  171. return std::equal(a.begin(), a.end(), b.begin(), b.end()) &&
  172. metadata_base<MetaData>::operator==(o);
  173. }
  174. template <class V, class M, class O, class A>
  175. bool operator!=(const variable<V, M, O, A>& o) const noexcept {
  176. return !operator==(o);
  177. }
  178. /// Return allocator instance.
  179. auto get_allocator() const { return vec_.get_allocator(); }
  180. template <class Archive>
  181. void serialize(Archive& ar, unsigned /* version */) {
  182. ar& make_nvp("seq", vec_);
  183. ar& make_nvp("meta", this->metadata());
  184. }
  185. private:
  186. vector_type vec_;
  187. template <class V, class M, class O, class A>
  188. friend class variable;
  189. };
  190. #if __cpp_deduction_guides >= 201606
  191. template <class T>
  192. variable(std::initializer_list<T>)
  193. ->variable<detail::convert_integer<T, double>, null_type>;
  194. template <class T, class M>
  195. variable(std::initializer_list<T>, M)
  196. ->variable<detail::convert_integer<T, double>,
  197. detail::replace_type<std::decay_t<M>, const char*, std::string>>;
  198. template <class Iterable, class = detail::requires_iterable<Iterable>>
  199. variable(Iterable)
  200. ->variable<
  201. detail::convert_integer<
  202. std::decay_t<decltype(*std::begin(std::declval<Iterable&>()))>, double>,
  203. null_type>;
  204. template <class Iterable, class M>
  205. variable(Iterable, M)
  206. ->variable<
  207. detail::convert_integer<
  208. std::decay_t<decltype(*std::begin(std::declval<Iterable&>()))>, double>,
  209. detail::replace_type<std::decay_t<M>, const char*, std::string>>;
  210. #endif
  211. } // namespace axis
  212. } // namespace histogram
  213. } // namespace boost
  214. #endif