1 // Copyright 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 
7 #ifndef BOOST_HISTOGRAM_AXIS_TRAITS_HPP
8 #define BOOST_HISTOGRAM_AXIS_TRAITS_HPP
9 
10 #include <boost/histogram/axis/option.hpp>
11 #include <boost/histogram/detail/args_type.hpp>
12 #include <boost/histogram/detail/detect.hpp>
13 #include <boost/histogram/detail/priority.hpp>
14 #include <boost/histogram/detail/static_if.hpp>
15 #include <boost/histogram/detail/try_cast.hpp>
16 #include <boost/histogram/detail/type_name.hpp>
17 #include <boost/histogram/fwd.hpp>
18 #include <boost/mp11/algorithm.hpp>
19 #include <boost/mp11/list.hpp>
20 #include <boost/mp11/utility.hpp>
21 #include <boost/throw_exception.hpp>
22 #include <boost/variant2/variant.hpp>
23 #include <stdexcept>
24 #include <string>
25 #include <utility>
26 
27 namespace boost {
28 namespace histogram {
29 namespace detail {
30 
31 template <class Axis>
32 struct value_type_deducer {
33   using type =
34       std::remove_cv_t<std::remove_reference_t<detail::arg_type<decltype(&Axis::index)>>>;
35 };
36 
37 template <class Axis>
38 auto traits_options(priority<2>) -> axis::option::bitset<Axis::options()>;
39 
40 template <class Axis>
41 auto traits_options(priority<1>) -> decltype(&Axis::update, axis::option::growth_t{});
42 
43 template <class Axis>
44 auto traits_options(priority<0>) -> axis::option::none_t;
45 
46 template <class Axis>
47 auto traits_is_inclusive(priority<1>) -> std::integral_constant<bool, Axis::inclusive()>;
48 
49 template <class Axis>
50 auto traits_is_inclusive(priority<0>)
51     -> decltype(traits_options<Axis>(priority<2>{})
52                     .test(axis::option::underflow | axis::option::overflow));
53 
54 template <class Axis>
55 auto traits_is_ordered(priority<1>) -> std::integral_constant<bool, Axis::ordered()>;
56 
57 template <class Axis, class ValueType = typename value_type_deducer<Axis>::type>
58 auto traits_is_ordered(priority<0>) -> typename std::is_arithmetic<ValueType>::type;
59 
60 template <class I, class D, class A,
61           class J = std::decay_t<arg_type<decltype(&A::value)>>>
value_method_switch(I && i,D && d,const A & a,priority<1>)62 decltype(auto) value_method_switch(I&& i, D&& d, const A& a, priority<1>) {
63   return static_if<std::is_same<J, axis::index_type>>(std::forward<I>(i),
64                                                       std::forward<D>(d), a);
65 }
66 
67 template <class I, class D, class A>
value_method_switch(I &&,D &&,const A &,priority<0>)68 double value_method_switch(I&&, D&&, const A&, priority<0>) {
69   // comma trick to make all compilers happy; some would complain about
70   // unreachable code after the throw, others about a missing return
71   return BOOST_THROW_EXCEPTION(
72              std::runtime_error(type_name<A>() + " has no value method")),
73          double{};
74 }
75 
76 struct variant_access {
77   template <class T, class Variant>
get_ifboost::histogram::detail::variant_access78   static auto get_if(Variant* v) noexcept {
79     using T0 = mp11::mp_first<std::decay_t<Variant>>;
80     return static_if<std::is_pointer<T0>>(
81         [](auto* vptr) {
82           using TP = mp11::mp_if<std::is_const<std::remove_pointer_t<T0>>, const T*, T*>;
83           auto ptp = variant2::get_if<TP>(vptr);
84           return ptp ? *ptp : nullptr;
85         },
86         [](auto* vptr) { return variant2::get_if<T>(vptr); }, &(v->impl));
87   }
88 
89   template <class T0, class Visitor, class Variant>
visit_implboost::histogram::detail::variant_access90   static decltype(auto) visit_impl(mp11::mp_identity<T0>, Visitor&& vis, Variant&& v) {
91     return variant2::visit(std::forward<Visitor>(vis), v.impl);
92   }
93 
94   template <class T0, class Visitor, class Variant>
visit_implboost::histogram::detail::variant_access95   static decltype(auto) visit_impl(mp11::mp_identity<T0*>, Visitor&& vis, Variant&& v) {
96     return variant2::visit(
97         [&vis](auto&& x) -> decltype(auto) { return std::forward<Visitor>(vis)(*x); },
98         v.impl);
99   }
100 
101   template <class Visitor, class Variant>
visitboost::histogram::detail::variant_access102   static decltype(auto) visit(Visitor&& vis, Variant&& v) {
103     using T0 = mp11::mp_first<std::decay_t<Variant>>;
104     return visit_impl(mp11::mp_identity<T0>{}, std::forward<Visitor>(vis),
105                       std::forward<Variant>(v));
106   }
107 };
108 
109 template <class A>
110 decltype(auto) metadata_impl(A&& a, decltype(a.metadata(), 0)) {
111   return std::forward<A>(a).metadata();
112 }
113 
114 template <class A>
metadata_impl(A &&,float)115 axis::null_type& metadata_impl(A&&, float) {
116   static axis::null_type null_value;
117   return null_value;
118 }
119 
120 } // namespace detail
121 
122 namespace axis {
123 namespace traits {
124 
125 /** Value type for axis type.
126 
127   Doxygen does not render this well. This is a meta-function (template alias), it accepts
128   an axis type and returns the value type.
129 
130   The value type is deduced from the argument of the `Axis::index` method. Const
131   references are decayed to the their value types, for example, the type deduced for
132   `Axis::index(const int&)` is `int`.
133 
134   The deduction always succeeds if the axis type models the Axis concept correctly. Errors
135   come from violations of the concept, in particular, an index method that is templated or
136   overloaded is not allowed.
137 
138   @tparam Axis axis type.
139 */
140 template <class Axis>
141 #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
142 using value_type = typename detail::value_type_deducer<Axis>::type;
143 #else
144 struct value_type;
145 #endif
146 
147 /** Whether axis is continuous or discrete.
148 
149   Doxygen does not render this well. This is a meta-function (template alias), it accepts
150   an axis type and returns a compile-time boolean.
151 
152   If the boolean is true, the axis is continuous (covers a continuous range of values).
153   Otherwise it is discrete (covers discrete values).
154 */
155 template <class Axis>
156 #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
157 using is_continuous = typename std::is_floating_point<traits::value_type<Axis>>::type;
158 #else
159 struct is_continuous;
160 #endif
161 
162 /** Meta-function to detect whether an axis is reducible.
163 
164   Doxygen does not render this well. This is a meta-function (template alias), it accepts
165   an axis type and represents compile-time boolean which is true or false, depending on
166   whether the axis can be reduced with boost::histogram::algorithm::reduce().
167 
168   An axis can be made reducible by adding a special constructor, see Axis concept for
169   details.
170 
171   @tparam Axis axis type.
172  */
173 template <class Axis>
174 #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
175 using is_reducible = std::is_constructible<Axis, const Axis&, axis::index_type,
176                                            axis::index_type, unsigned>;
177 #else
178 struct is_reducible;
179 #endif
180 
181 /** Get axis options for axis type.
182 
183   Doxygen does not render this well. This is a meta-function (template alias), it accepts
184   an axis type and returns the boost::histogram::axis::option::bitset.
185 
186   If Axis::options() is valid and constexpr, get_options is the corresponding
187   option type. Otherwise, it is boost::histogram::axis::option::growth_t, if the
188   axis has a method `update`, else boost::histogram::axis::option::none_t.
189 
190   @tparam Axis axis type
191 */
192 template <class Axis>
193 #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
194 using get_options = decltype(detail::traits_options<Axis>(detail::priority<2>{}));
195 
196 template <class Axis>
197 using static_options [[deprecated("use get_options instead")]] = get_options<Axis>;
198 
199 #else
200 struct get_options;
201 #endif
202 
203 /** Meta-function to detect whether an axis is inclusive.
204 
205   Doxygen does not render this well. This is a meta-function (template alias), it accepts
206   an axis type and represents compile-time boolean which is true or false, depending on
207   whether the axis is inclusive or not.
208 
209   An axis with underflow and overflow bins is always inclusive, but an axis may be
210   inclusive under other conditions. The meta-function checks for the method `constexpr
211   static bool inclusive()`, and uses the result. If this method is not present, it uses
212   get_options<Axis> and checks whether the underflow and overflow bits are present.
213 
214   An inclusive axis has a bin for every possible input value. A histogram which consists
215   only of inclusive axes can be filled more efficiently, since input values always
216   end up in a valid cell and there is no need to keep track of input tuples that need to
217   be discarded.
218 
219   @tparam Axis axis type
220 */
221 template <class Axis>
222 #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
223 using is_inclusive = decltype(detail::traits_is_inclusive<Axis>(detail::priority<1>{}));
224 
225 template <class Axis>
226 using static_is_inclusive [[deprecated("use is_inclusive instead")]] = is_inclusive<Axis>;
227 
228 #else
229 struct is_inclusive;
230 #endif
231 
232 /** Meta-function to detect whether an axis is ordered.
233 
234   Doxygen does not render this well. This is a meta-function (template alias), it accepts
235   an axis type and returns a compile-time boolean. If the boolean is true, the axis is
236   ordered.
237 
238   The meta-function checks for the method `constexpr static bool ordered()`, and uses the
239   result. If this method is not present, it returns true if the value type of the Axis is
240   arithmetic and false otherwise.
241 
242   An ordered axis has a value type that is ordered, which means that indices i <
243   j < k implies either value(i) < value(j) < value(k) or value(i) > value(j) > value(k)
244   for all i,j,k. For example, the integer axis is ordered, but the category axis is not.
245   Axis which are not ordered must not have underflow bins, because they only have an
246   "other" category, which is identified with the overflow bin if it is available.
247 
248   @tparam Axis axis type
249 */
250 template <class Axis>
251 #ifndef BOOST_HISTOGRAM_DOXYGEN_INVOKED
252 using is_ordered = decltype(detail::traits_is_ordered<Axis>(detail::priority<1>{}));
253 #else
254 struct is_ordered;
255 #endif
256 
257 /** Returns axis options as unsigned integer.
258 
259   See get_options for details.
260 
261   @param axis any axis instance
262 */
263 template <class Axis>
options(const Axis & axis)264 constexpr unsigned options(const Axis& axis) noexcept {
265   (void)axis;
266   return get_options<Axis>::value;
267 }
268 
269 // specialization for variant
270 template <class... Ts>
options(const variant<Ts...> & axis)271 unsigned options(const variant<Ts...>& axis) noexcept {
272   return axis.options();
273 }
274 
275 /** Returns true if axis is inclusive or false.
276 
277   See is_inclusive for details.
278 
279   @param axis any axis instance
280 */
281 template <class Axis>
inclusive(const Axis & axis)282 constexpr bool inclusive(const Axis& axis) noexcept {
283   (void)axis;
284   return is_inclusive<Axis>::value;
285 }
286 
287 // specialization for variant
288 template <class... Ts>
inclusive(const variant<Ts...> & axis)289 bool inclusive(const variant<Ts...>& axis) noexcept {
290   return axis.inclusive();
291 }
292 
293 /** Returns true if axis is ordered or false.
294 
295   See is_ordered for details.
296 
297   @param axis any axis instance
298 */
299 template <class Axis>
ordered(const Axis & axis)300 constexpr bool ordered(const Axis& axis) noexcept {
301   (void)axis;
302   return is_ordered<Axis>::value;
303 }
304 
305 // specialization for variant
306 template <class... Ts>
ordered(const variant<Ts...> & axis)307 bool ordered(const variant<Ts...>& axis) noexcept {
308   return axis.ordered();
309 }
310 
311 /** Returns true if axis is continuous or false.
312 
313   See is_continuous for details.
314 
315   @param axis any axis instance
316 */
317 template <class Axis>
continuous(const Axis & axis)318 constexpr bool continuous(const Axis& axis) noexcept {
319   (void)axis;
320   return is_continuous<Axis>::value;
321 }
322 
323 // specialization for variant
324 template <class... Ts>
continuous(const variant<Ts...> & axis)325 bool continuous(const variant<Ts...>& axis) noexcept {
326   return axis.continuous();
327 }
328 
329 /** Returns axis size plus any extra bins for under- and overflow.
330 
331   @param axis any axis instance
332 */
333 template <class Axis>
extent(const Axis & axis)334 index_type extent(const Axis& axis) noexcept {
335   const auto opt = options(axis);
336   return axis.size() + (opt & option::underflow ? 1 : 0) +
337          (opt & option::overflow ? 1 : 0);
338 }
339 
340 /** Returns reference to metadata of an axis.
341 
342   If the expression x.metadata() for an axis instance `x` (maybe const) is valid, return
343   the result. Otherwise, return a reference to a static instance of
344   boost::histogram::axis::null_type.
345 
346   @param axis any axis instance
347 */
348 template <class Axis>
metadata(Axis && axis)349 decltype(auto) metadata(Axis&& axis) noexcept {
350   return detail::metadata_impl(std::forward<Axis>(axis), 0);
351 }
352 
353 /** Returns axis value for index.
354 
355   If the axis has no `value` method, throw std::runtime_error. If the method exists and
356   accepts a floating point index, pass the index and return the result. If the method
357   exists but accepts only integer indices, cast the floating point index to int, pass this
358   index and return the result.
359 
360   @param axis any axis instance
361   @param index floating point axis index
362 */
363 template <class Axis>
value(const Axis & axis,real_index_type index)364 decltype(auto) value(const Axis& axis, real_index_type index) {
365   return detail::value_method_switch(
366       [index](const auto& a) { return a.value(static_cast<index_type>(index)); },
367       [index](const auto& a) { return a.value(index); }, axis, detail::priority<1>{});
368 }
369 
370 /** Returns axis value for index if it is convertible to target type or throws.
371 
372   Like boost::histogram::axis::traits::value, but converts the result into the requested
373   return type. If the conversion is not possible, throws std::runtime_error.
374 
375   @tparam Result requested return type
376   @tparam Axis axis type
377   @param axis any axis instance
378   @param index floating point axis index
379 */
380 template <class Result, class Axis>
381 Result value_as(const Axis& axis, real_index_type index) {
382   return detail::try_cast<Result, std::runtime_error>(
383       axis::traits::value(axis, index)); // avoid conversion warning
384 }
385 
386 /** Returns axis index for value.
387 
388   Throws std::invalid_argument if the value argument is not implicitly convertible.
389 
390   @param axis any axis instance
391   @param value argument to be passed to `index` method
392 */
393 template <class Axis, class U>
index(const Axis & axis,const U & value)394 axis::index_type index(const Axis& axis, const U& value) noexcept(
395     std::is_convertible<U, value_type<Axis>>::value) {
396   return axis.index(detail::try_cast<value_type<Axis>, std::invalid_argument>(value));
397 }
398 
399 // specialization for variant
400 template <class... Ts, class U>
index(const variant<Ts...> & axis,const U & value)401 axis::index_type index(const variant<Ts...>& axis, const U& value) {
402   return axis.index(value);
403 }
404 
405 /** Return axis rank (how many arguments it processes).
406 
407   @param axis any axis instance
408 */
409 // gcc workaround: must use unsigned int not unsigned as return type
410 template <class Axis>
rank(const Axis & axis)411 constexpr unsigned int rank(const Axis& axis) {
412   (void)axis;
413   using T = value_type<Axis>;
414   // cannot use mp_eval_or since T could be a fixed-sized sequence
415   return mp11::mp_eval_if_not<detail::is_tuple<T>, mp11::mp_size_t<1>, mp11::mp_size,
416                               T>::value;
417 }
418 
419 // specialization for variant
420 // gcc workaround: must use unsigned int not unsigned as return type
421 template <class... Ts>
rank(const axis::variant<Ts...> & axis)422 unsigned int rank(const axis::variant<Ts...>& axis) {
423   return detail::variant_access::visit(
424       [](const auto& a) { return axis::traits::rank(a); }, axis);
425 }
426 
427 /** Returns pair of axis index and shift for the value argument.
428 
429   Throws `std::invalid_argument` if the value argument is not implicitly convertible to
430   the argument expected by the `index` method. If the result of
431   boost::histogram::axis::traits::get_options<decltype(axis)> has the growth flag set,
432   call `update` method with the argument and return the result. Otherwise, call `index`
433   and return the pair of the result and a zero shift.
434 
435   @param axis any axis instance
436   @param value argument to be passed to `update` or `index` method
437 */
438 template <class Axis, class U>
update(Axis & axis,const U & value)439 std::pair<index_type, index_type> update(Axis& axis, const U& value) noexcept(
440     std::is_convertible<U, value_type<Axis>>::value) {
441   return detail::static_if_c<get_options<Axis>::test(option::growth)>(
442       [&value](auto& a) {
443         return a.update(detail::try_cast<value_type<Axis>, std::invalid_argument>(value));
444       },
445       [&value](auto& a) -> std::pair<index_type, index_type> {
446         return {axis::traits::index(a, value), 0};
447       },
448       axis);
449 }
450 
451 // specialization for variant
452 template <class... Ts, class U>
update(variant<Ts...> & axis,const U & value)453 std::pair<index_type, index_type> update(variant<Ts...>& axis, const U& value) {
454   return visit([&value](auto& a) { return a.update(value); }, axis);
455 }
456 
457 /** Returns bin width at axis index.
458 
459   If the axis has no `value` method, throw std::runtime_error. If the method exists and
460   accepts a floating point index, return the result of `axis.value(index + 1) -
461   axis.value(index)`. If the method exists but accepts only integer indices, return 0.
462 
463   @param axis any axis instance
464   @param index bin index
465  */
466 template <class Axis>
width(const Axis & axis,index_type index)467 decltype(auto) width(const Axis& axis, index_type index) {
468   return detail::value_method_switch(
469       [](const auto&) { return 0; },
470       [index](const auto& a) { return a.value(index + 1) - a.value(index); }, axis,
471       detail::priority<1>{});
472 }
473 
474 /** Returns bin width at axis index.
475 
476   Like boost::histogram::axis::traits::width, but converts the result into the requested
477   return type. If the conversion is not possible, throw std::runtime_error.
478 
479   @param axis any axis instance
480   @param index bin index
481  */
482 template <class Result, class Axis>
483 Result width_as(const Axis& axis, index_type index) {
484   return detail::value_method_switch(
__anonddf6d9e90d02(const auto&) 485       [](const auto&) { return Result{}; },
__anonddf6d9e90e02(const auto& a) 486       [index](const auto& a) {
487         return detail::try_cast<Result, std::runtime_error>(a.value(index + 1) -
488                                                             a.value(index));
489       },
__anonddf6d9e90f02(const auto& a) 490       axis, detail::priority<1>{});
491 }
492 
493 } // namespace traits
494 } // namespace axis
495 } // namespace histogram
496 } // namespace boost
497 
498 #endif
499