Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
RHistEngine.hxx
Go to the documentation of this file.
1/// \file
2/// \warning This is part of the %ROOT 7 prototype! It will change without notice. It might trigger earthquakes.
3/// Feedback is welcome!
4
5#ifndef ROOT_RHistEngine
6#define ROOT_RHistEngine
7
8#include "RAxes.hxx"
9#include "RAxisVariant.hxx"
10#include "RBinIndex.hxx"
12#include "RHistUtils.hxx"
13#include "RLinearizedIndex.hxx"
14#include "RRegularAxis.hxx"
16#include "RSliceSpec.hxx"
17#include "RWeight.hxx"
18
19#include <array>
20#include <atomic>
21#include <cassert>
22#include <cstddef>
23#include <cstdint>
24#include <cstring>
25#include <initializer_list>
26#include <stdexcept>
27#include <tuple>
28#include <type_traits>
29#include <utility>
30#include <vector>
31
32class TBuffer;
33
34namespace ROOT {
35namespace Experimental {
36
37// forward declaration for friend declaration
38template <typename T>
39class RHist;
40
41/**
42A histogram data structure to bin data along multiple dimensions.
43
44Every call to \ref Fill(const A &... args) "Fill" bins the data according to the axis configuration and increments the
45bin content:
46\code
47ROOT::Experimental::RHistEngine<int> hist(10, {5, 15});
48hist.Fill(8.5);
49// hist.GetBinContent(ROOT::Experimental::RBinIndex(3)) will return 1
50\endcode
51
52The class is templated on the bin content type. For counting, as in the example above, it may be an integral type such
53as `int` or `long`. Narrower types such as `unsigned char` or `short` are supported, but may overflow due to their
54limited range and must be used with care. For weighted filling, the bin content type must not be an integral type, but
55a floating-point type such as `float` or `double`, or the special type RBinWithError. Note that `float` has a limited
56significand precision of 24 bits.
57
58An object can have arbitrary dimensionality determined at run-time. The axis configuration is passed as a vector of
59RAxisVariant:
60\code
61std::vector<ROOT::Experimental::RAxisVariant> axes;
62axes.push_back(ROOT::Experimental::RRegularAxis(10, {5, 15}));
63axes.push_back(ROOT::Experimental::RVariableBinAxis({1, 10, 100, 1000}));
64ROOT::Experimental::RHistEngine<int> hist(axes);
65// hist.GetNDimensions() will return 2
66\endcode
67
68\warning This is part of the %ROOT 7 prototype! It will change without notice. It might trigger earthquakes.
69Feedback is welcome!
70*/
71template <typename BinContentType>
72class RHistEngine final {
73 // For conversion, all other template instantiations must be a friend.
74 template <typename U>
75 friend class RHistEngine;
76
77 // For slicing, RHist needs to call SliceImpl.
78 friend class RHist<BinContentType>;
79
80 friend class RProfile;
81 friend class RProfileFillContext;
82
83 /// The axis configuration for this histogram. Relevant methods are forwarded from the public interface.
85 /// The bin contents for this histogram
86 std::vector<BinContentType> fBinContents;
87
88 /// Flag to pause filling while a snapshot is ongoing
89 mutable std::atomic<bool> fSnapshotInProgress{false}; //!
90
91public:
92 /// Construct a histogram engine.
93 ///
94 /// \param[in] axes the axis objects, must have size > 0
95 explicit RHistEngine(std::vector<RAxisVariant> axes) : fAxes(std::move(axes))
96 {
98 }
99
100 /// Construct a histogram engine.
101 ///
102 /// Note that there is no perfect forwarding of the axis objects. If that is needed, use the
103 /// \ref RHistEngine(std::vector<RAxisVariant> axes) "overload accepting a std::vector".
104 ///
105 /// \param[in] axes the axis objects, must have size > 0
106 explicit RHistEngine(std::initializer_list<RAxisVariant> axes) : RHistEngine(std::vector(axes)) {}
107
108 /// Construct a histogram engine.
109 ///
110 /// Note that there is no perfect forwarding of the axis objects. If that is needed, use the
111 /// \ref RHistEngine(std::vector<RAxisVariant> axes) "overload accepting a std::vector".
112 ///
113 /// \param[in] axis1 the first axis object
114 /// \param[in] axes the remaining axis objects
115 template <typename... Axes>
116 explicit RHistEngine(const RAxisVariant &axis1, const Axes &...axes)
117 : RHistEngine(std::vector<RAxisVariant>{axis1, axes...})
118 {
119 }
120
121 /// Construct a one-dimensional histogram engine with a regular axis.
122 ///
123 /// \param[in] nNormalBins the number of normal bins, must be > 0
124 /// \param[in] interval the axis interval (lower end inclusive, upper end exclusive)
125 /// \par See also
126 /// the \ref RRegularAxis::RRegularAxis(std::uint64_t nNormalBins, std::pair<double, double> interval, bool
127 /// enableFlowBins) "constructor of RRegularAxis"
128 RHistEngine(std::uint64_t nNormalBins, std::pair<double, double> interval)
129 : RHistEngine(std::vector<RAxisVariant>{RRegularAxis(nNormalBins, interval)})
130 {
131 }
132
133 /// The copy constructor is deleted.
134 ///
135 /// Copying all bin contents can be an expensive operation, depending on the number of bins. If required, users can
136 /// explicitly call Clone().
137 RHistEngine(const RHistEngine &) = delete;
138 /// Efficiently move construct a histogram engine.
139 ///
140 /// After this operation, the moved-from object is invalid.
141 RHistEngine(RHistEngine &&rhs) noexcept : fAxes(std::move(rhs.fAxes)), fBinContents(std::move(rhs.fBinContents)) {}
142
143 /// The copy assignment operator is deleted.
144 ///
145 /// Copying all bin contents can be an expensive operation, depending on the number of bins. If required, users can
146 /// explicitly call Clone().
148 /// Efficiently move a histogram engine.
149 ///
150 /// After this operation, the moved-from object is invalid.
152 {
153 std::swap(fAxes, rhs.fAxes);
154 std::swap(fBinContents, rhs.fBinContents);
155 return *this;
156 }
157
158 ~RHistEngine() = default;
159
160 /// \name Accessors
161 /// \{
162
163 const std::vector<RAxisVariant> &GetAxes() const { return fAxes.Get(); }
164 std::size_t GetNDimensions() const { return fAxes.GetNDimensions(); }
165 std::uint64_t GetTotalNBins() const { return fBinContents.size(); }
166
167 /// Get the content of a single bin.
168 ///
169 /// \code
170 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
171 /// std::array<ROOT::Experimental::RBinIndex, 2> indices = {3, 5};
172 /// int content = hist.GetBinContent(indices);
173 /// \endcode
174 ///
175 /// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
176 /// values. See also the class documentation of RBinIndex.
177 ///
178 /// Throws an exception if the number of indices does not match the axis configuration or the bin is not found.
179 ///
180 /// \param[in] indices the array of indices for each axis
181 /// \return the bin content
182 /// \par See also
183 /// the \ref GetBinContent(const A &... args) const "variadic function template overload" accepting arguments
184 /// directly
185 template <std::size_t N>
186 const BinContentType &GetBinContent(const std::array<RBinIndex, N> &indices) const
187 {
188 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
189 // be confusing for users.
190 if (N != GetNDimensions()) {
191 throw std::invalid_argument("invalid number of indices passed to GetBinContent");
192 }
194 if (!index.fValid) {
195 throw std::invalid_argument("bin not found in GetBinContent");
196 }
197 assert(index.fIndex < fBinContents.size());
198 return fBinContents[index.fIndex];
199 }
200
201 /// Get the content of a single bin.
202 ///
203 /// \code
204 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
205 /// std::vector<ROOT::Experimental::RBinIndex> indices = {3, 5};
206 /// int content = hist.GetBinContent(indices);
207 /// \endcode
208 ///
209 /// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
210 /// values. See also the class documentation of RBinIndex.
211 ///
212 /// Throws an exception if the number of indices does not match the axis configuration or the bin is not found.
213 ///
214 /// \param[in] indices the vector of indices for each axis
215 /// \return the bin content
216 /// \par See also
217 /// the \ref GetBinContent(const A &... args) const "variadic function template overload" accepting arguments
218 /// directly
219 const BinContentType &GetBinContent(const std::vector<RBinIndex> &indices) const
220 {
221 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
222 // be confusing for users.
223 if (indices.size() != GetNDimensions()) {
224 throw std::invalid_argument("invalid number of indices passed to GetBinContent");
225 }
227 if (!index.fValid) {
228 throw std::invalid_argument("bin not found in GetBinContent");
229 }
230 assert(index.fIndex < fBinContents.size());
231 return fBinContents[index.fIndex];
232 }
233
234 /// Get the content of a single bin.
235 ///
236 /// \code
237 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
238 /// int content = hist.GetBinContent(ROOT::Experimental::RBinIndex(3), ROOT::Experimental::RBinIndex(5));
239 /// // ... or construct the RBinIndex arguments implicitly from integers:
240 /// content = hist.GetBinContent(3, 5);
241 /// \endcode
242 ///
243 /// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
244 /// values. See also the class documentation of RBinIndex.
245 ///
246 /// Throws an exception if the number of arguments does not match the axis configuration or the bin is not found.
247 ///
248 /// \param[in] args the arguments for each axis
249 /// \return the bin content
250 /// \par See also
251 /// the function overloads accepting \ref GetBinContent(const std::array<RBinIndex, N> &indices) const "`std::array`"
252 /// or \ref GetBinContent(const std::vector<RBinIndex> &indices) const "`std::vector`"
253 template <typename... A>
254 const BinContentType &GetBinContent(const A &...args) const
255 {
256 std::array<RBinIndex, sizeof...(A)> indices{args...};
257 return GetBinContent(indices);
258 }
259
260 /// Get the multidimensional range of all bins.
261 ///
262 /// \return the multidimensional range
264
265 /// Set the content of a single bin.
266 ///
267 /// \code
268 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
269 /// std::array<ROOT::Experimental::RBinIndex, 2> indices = {3, 5};
270 /// int value = /* ... */;
271 /// hist.SetBinContent(indices, value);
272 /// \endcode
273 ///
274 /// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
275 /// values. See also the class documentation of RBinIndex.
276 ///
277 /// Throws an exception if the number of indices does not match the axis configuration or the bin is not found.
278 ///
279 /// \param[in] indices the array of indices for each axis
280 /// \param[in] value the new value of the bin content
281 /// \par See also
282 /// the \ref SetBinContent(const A &... args) "variadic function template overload" accepting arguments directly
283 template <std::size_t N, typename V>
284 void SetBinContent(const std::array<RBinIndex, N> &indices, const V &value)
285 {
286 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
287 // be confusing for users.
288 if (N != GetNDimensions()) {
289 throw std::invalid_argument("invalid number of indices passed to SetBinContent");
290 }
292 if (!index.fValid) {
293 throw std::invalid_argument("bin not found in SetBinContent");
294 }
295 assert(index.fIndex < fBinContents.size());
296 // To allow conversion, we have to accept value with a template type V to capture any argument. Otherwise it would
297 // select the variadic function template...
298 fBinContents[index.fIndex] = value;
299 }
300
301 /// Set the content of a single bin.
302 ///
303 /// \code
304 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
305 /// std::vector<ROOT::Experimental::RBinIndex> indices = {3, 5};
306 /// int value = /* ... */;
307 /// hist.SetBinContent(indices, value);
308 /// \endcode
309 ///
310 /// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
311 /// values. See also the class documentation of RBinIndex.
312 ///
313 /// Throws an exception if the number of indices does not match the axis configuration or the bin is not found.
314 ///
315 /// \param[in] indices the vector of indices for each axis
316 /// \param[in] value the new value of the bin content
317 /// \par See also
318 /// the \ref SetBinContent(const A &... args) "variadic function template overload" accepting arguments directly
319 template <typename V>
320 void SetBinContent(const std::vector<RBinIndex> &indices, const V &value)
321 {
322 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
323 // be confusing for users.
324 if (indices.size() != GetNDimensions()) {
325 throw std::invalid_argument("invalid number of indices passed to SetBinContent");
326 }
328 if (!index.fValid) {
329 throw std::invalid_argument("bin not found in SetBinContent");
330 }
331 assert(index.fIndex < fBinContents.size());
332 // To allow conversion, we have to accept value with a template type V to capture any argument. Otherwise it would
333 // select the variadic function template...
334 fBinContents[index.fIndex] = value;
335 }
336
337 /// \}
338 // End the group to ensure that all contained member functions are public.
339
340private:
341 template <typename... A, std::size_t... I>
342 void SetBinContentImpl(const std::tuple<A...> &args, std::index_sequence<I...>)
343 {
344 std::array<RBinIndex, sizeof...(A) - 1> indices{std::get<I>(args)...};
345 SetBinContent(indices, std::get<sizeof...(A) - 1>(args));
346 }
347
348public:
349 /// \name Accessors
350 /// \{
351
352 /// Set the content of a single bin.
353 ///
354 /// \code
355 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
356 /// int value = /* ... */;
357 /// hist.SetBinContent(ROOT::Experimental::RBinIndex(3), ROOT::Experimental::RBinIndex(5), value);
358 /// // ... or construct the RBinIndex arguments implicitly from integers:
359 /// hist.SetBinContent(3, 5, value);
360 /// \endcode
361 ///
362 /// \note Compared to TH1 conventions, the first normal bin has index 0 and underflow and overflow bins are special
363 /// values. See also the class documentation of RBinIndex.
364 ///
365 /// Throws an exception if the number of arguments does not match the axis configuration or the bin is not found.
366 ///
367 /// \param[in] args the arguments for each axis and the new value of the bin content
368 /// \par See also
369 /// the function overloads accepting
370 /// \ref SetBinContent(const std::array<RBinIndex, N> &indices, const V &value) const "`std::array`" or
371 /// \ref SetBinContent(const std::vector<RBinIndex> &indices, const V &value) const "`std::vector`"
372 template <typename... A>
373 void SetBinContent(const A &...args)
374 {
375 auto t = std::forward_as_tuple(args...);
376 SetBinContentImpl(t, std::make_index_sequence<sizeof...(A) - 1>());
377 }
378
379 /// \}
380
381 /// Whether this histogram engine type supports weighted filling.
382 static constexpr bool SupportsWeightedFilling = !std::is_integral_v<BinContentType>;
383
384 // SupportsWeightedFilling is not included because it is static, which would mess up the subgrouping below "Public
385 // Member Functions".
386 /// \name Filling
387 /// \{
388
389 /// Fill an entry into the histogram.
390 ///
391 /// \code
392 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
393 /// auto args = std::make_tuple(8.5, 10.5);
394 /// hist.Fill(args);
395 /// \endcode
396 ///
397 /// If one of the arguments is outside the corresponding axis and flow bins are disabled, the entry will be silently
398 /// discarded.
399 ///
400 /// Throws an exception if the number of arguments does not match the axis configuration, or if an argument cannot be
401 /// converted for the axis type at run-time.
402 ///
403 /// \param[in] args the arguments for each axis
404 /// \par See also
405 /// the \ref Fill(const A &... args) "variadic function template overload" accepting arguments directly and the
406 /// \ref Fill(const std::tuple<A...> &args, RWeight weight) "overload for weighted filling"
407 template <typename... A>
408 void Fill(const std::tuple<A...> &args)
409 {
410 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
411 // be confusing for users.
412 if (sizeof...(A) != GetNDimensions()) {
413 throw std::invalid_argument("invalid number of arguments to Fill");
414 }
416 if (index.fValid) {
417 assert(index.fIndex < fBinContents.size());
418 fBinContents[index.fIndex]++;
419 }
420 }
421
422 /// Fill an entry into the histogram with a weight.
423 ///
424 /// This overload is not available for integral bin content types (see \ref SupportsWeightedFilling).
425 ///
426 /// \code
427 /// ROOT::Experimental::RHistEngine<float> hist({/* two dimensions */});
428 /// auto args = std::make_tuple(8.5, 10.5);
429 /// hist.Fill(args, ROOT::Experimental::RWeight(0.8));
430 /// \endcode
431 ///
432 /// If one of the arguments is outside the corresponding axis and flow bins are disabled, the entry will be silently
433 /// discarded.
434 ///
435 /// Throws an exception if the number of arguments does not match the axis configuration, or if an argument cannot be
436 /// converted for the axis type at run-time.
437 ///
438 /// \param[in] args the arguments for each axis
439 /// \param[in] weight the weight for this entry
440 /// \par See also
441 /// the \ref Fill(const A &... args) "variadic function template overload" accepting arguments directly and the
442 /// \ref Fill(const std::tuple<A...> &args) "overload for unweighted filling"
443 template <typename... A>
444 void Fill(const std::tuple<A...> &args, RWeight weight)
445 {
446 static_assert(SupportsWeightedFilling, "weighted filling is not supported for integral bin content types");
447
448 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
449 // be confusing for users.
450 if (sizeof...(A) != GetNDimensions()) {
451 throw std::invalid_argument("invalid number of arguments to Fill");
452 }
454 if (index.fValid) {
455 assert(index.fIndex < fBinContents.size());
456 fBinContents[index.fIndex] += weight.fValue;
457 }
458 }
459
460 /// \}
461 // End the group to ensure that all contained member functions are public.
462
463private:
464 // Also used by RProfile::Fill(const A &...args) - similar to the variadic RHistEngine::Fill(const A &...args) below,
465 // is has all arguments in the forwarded std::tuple and needs to explicitly specify how many of them should be used
466 // by RAxes::ComputeGlobalIndexImpl<N>(args).
467 template <std::size_t N, typename... A, typename W>
468 void FillImpl(const std::tuple<A...> &args, const W &weight)
469 {
471 if (index.fValid) {
472 assert(index.fIndex < fBinContents.size());
473 fBinContents[index.fIndex] += weight;
474 }
475 }
476
477public:
478 /// \name Filling
479 /// \{
480
481 /// Fill an entry into the histogram with a user-defined weight.
482 ///
483 /// This overload is only available for user-defined bin content types.
484 ///
485 /// If one of the arguments is outside the corresponding axis and flow bins are disabled, the entry will be silently
486 /// discarded.
487 ///
488 /// Throws an exception if the number of arguments does not match the axis configuration, or if an argument cannot be
489 /// converted for the axis type at run-time.
490 ///
491 /// \param[in] args the arguments for each axis
492 /// \param[in] weight the weight for this entry
493 template <typename... A, typename W>
494 void Fill(const std::tuple<A...> &args, const W &weight)
495 {
496 static_assert(std::is_class_v<BinContentType>,
497 "user-defined weight types are only supported for user-defined bin content types");
498
499 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
500 // be confusing for users.
501 if (sizeof...(A) != GetNDimensions()) {
502 throw std::invalid_argument("invalid number of arguments to Fill");
503 }
504 FillImpl<sizeof...(A)>(args, weight);
505 }
506
507 /// Fill an entry into the histogram.
508 ///
509 /// \code
510 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
511 /// hist.Fill(8.5, 10.5);
512 /// \endcode
513 ///
514 /// For weighted filling, pass an RWeight as the last argument:
515 /// \code
516 /// ROOT::Experimental::RHistEngine<float> hist({/* two dimensions */});
517 /// hist.Fill(8.5, 10.5, ROOT::Experimental::RWeight(0.8));
518 /// \endcode
519 /// This is not available for integral bin content types (see \ref SupportsWeightedFilling).
520 ///
521 /// If one of the arguments is outside the corresponding axis and flow bins are disabled, the entry will be silently
522 /// discarded.
523 ///
524 /// Throws an exception if the number of arguments does not match the axis configuration, or if an argument cannot be
525 /// converted for the axis type at run-time.
526 ///
527 /// \param[in] args the arguments for each axis
528 /// \par See also
529 /// the function overloads accepting `std::tuple` \ref Fill(const std::tuple<A...> &args) "for unweighted filling"
530 /// and \ref Fill(const std::tuple<A...> &args, RWeight) "for weighted filling"
531 template <typename... A>
532 void Fill(const A &...args)
533 {
534 static_assert(sizeof...(A) >= 1, "need at least one argument to Fill");
535 if constexpr (sizeof...(A) >= 1) {
536 auto t = std::forward_as_tuple(args...);
537 if constexpr (std::is_same_v<typename Internal::LastType<A...>::type, RWeight>) {
538 static_assert(SupportsWeightedFilling, "weighted filling is not supported for integral bin content types");
539 static constexpr std::size_t N = sizeof...(A) - 1;
540 if (N != GetNDimensions()) {
541 throw std::invalid_argument("invalid number of arguments to Fill");
542 }
543 RWeight weight = std::get<N>(t);
545 if (index.fValid) {
546 assert(index.fIndex < fBinContents.size());
547 fBinContents[index.fIndex] += weight.fValue;
548 }
549 } else {
550 Fill(t);
551 }
552 }
553 }
554
555 /// Fill an entry into the histogram using atomic instructions.
556 ///
557 /// \param[in] args the arguments for each axis
558 /// \see Fill(const std::tuple<A...> &args)
559 template <typename... A>
560 void FillAtomic(const std::tuple<A...> &args)
561 {
562 while (fSnapshotInProgress.load(std::memory_order_relaxed)) {
563 // Spin while a snapshot is running
564 }
565
566 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
567 // be confusing for users.
568 if (sizeof...(A) != GetNDimensions()) {
569 throw std::invalid_argument("invalid number of arguments to Fill");
570 }
572 if (index.fValid) {
573 assert(index.fIndex < fBinContents.size());
575 }
576 }
577
578 /// Fill an entry into the histogram with a weight using atomic instructions.
579 ///
580 /// This overload is not available for integral bin content types (see \ref SupportsWeightedFilling).
581 ///
582 /// \param[in] args the arguments for each axis
583 /// \param[in] weight the weight for this entry
584 /// \see Fill(const std::tuple<A...> &args, RWeight weight)
585 template <typename... A>
586 void FillAtomic(const std::tuple<A...> &args, RWeight weight)
587 {
588 static_assert(SupportsWeightedFilling, "weighted filling is not supported for integral bin content types");
589
590 while (fSnapshotInProgress.load(std::memory_order_relaxed)) {
591 // Spin while a snapshot is running
592 }
593
594 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
595 // be confusing for users.
596 if (sizeof...(A) != GetNDimensions()) {
597 throw std::invalid_argument("invalid number of arguments to Fill");
598 }
600 if (index.fValid) {
601 assert(index.fIndex < fBinContents.size());
603 }
604 }
605
606 /// \}
607 // End the group to ensure that all contained member functions are public.
608
609private:
610 // Also used by RProfileFillContext::Fill(const A &...args) - similar to the variadic
611 // RHistEngine::FillAtomic(const A &...args) below, is has all arguments in the forwarded std::tuple and needs to
612 // explicitly specify how many of them should be used by RAxes::ComputeGlobalIndexImpl<N>(args).
613 template <std::size_t N, typename... A, typename W>
614 void FillAtomicImpl(const std::tuple<A...> &args, const W &weight)
615 {
617 if (index.fValid) {
618 assert(index.fIndex < fBinContents.size());
620 }
621 }
622
623public:
624 /// \name Filling
625 /// \{
626
627 /// Fill an entry into the histogram with a user-defined weight using atomic instructions.
628 ///
629 /// This overload is only available for user-defined bin content types.
630 ///
631 /// \param[in] args the arguments for each axis
632 /// \param[in] weight the weight for this entry
633 /// \see Fill(const std::tuple<A...> &args, const W &weight)
634 template <typename... A, typename W>
635 void FillAtomic(const std::tuple<A...> &args, const W &weight)
636 {
637 static_assert(std::is_class_v<BinContentType>,
638 "user-defined weight types are only supported for user-defined bin content types");
639
640 while (fSnapshotInProgress.load(std::memory_order_relaxed)) {
641 // Spin while a snapshot is running
642 }
643
644 // We could rely on RAxes::ComputeGlobalIndex to check the number of arguments, but its exception message might
645 // be confusing for users.
646 if (sizeof...(A) != GetNDimensions()) {
647 throw std::invalid_argument("invalid number of arguments to Fill");
648 }
649 FillAtomicImpl<sizeof...(A)>(args, weight);
650 }
651
652 /// Fill an entry into the histogram using atomic instructions.
653 ///
654 /// \param[in] args the arguments for each axis
655 /// \see Fill(const A &...args)
656 template <typename... A>
657 void FillAtomic(const A &...args)
658 {
659 static_assert(sizeof...(A) >= 1, "need at least one argument to Fill");
660 if constexpr (sizeof...(A) >= 1) {
661 while (fSnapshotInProgress.load(std::memory_order_relaxed)) {
662 // Spin while a snapshot is running
663 }
664
665 auto t = std::forward_as_tuple(args...);
666 if constexpr (std::is_same_v<typename Internal::LastType<A...>::type, RWeight>) {
667 static_assert(SupportsWeightedFilling, "weighted filling is not supported for integral bin content types");
668 static constexpr std::size_t N = sizeof...(A) - 1;
669 if (N != GetNDimensions()) {
670 throw std::invalid_argument("invalid number of arguments to Fill");
671 }
672 RWeight weight = std::get<N>(t);
674 if (index.fValid) {
675 assert(index.fIndex < fBinContents.size());
677 }
678 } else {
679 FillAtomic(t);
680 }
681 }
682 }
683
684 /// \}
685 /// \name Operations
686 /// \{
687
688 /// Add all bin contents of another histogram.
689 ///
690 /// Throws an exception if the axes configurations are not identical.
691 ///
692 /// \param[in] other another histogram
693 void Add(const RHistEngine &other)
694 {
695 if (fAxes != other.fAxes) {
696 throw std::invalid_argument("axes configurations not identical in Add");
697 }
698 for (std::size_t i = 0; i < fBinContents.size(); i++) {
699 fBinContents[i] += other.fBinContents[i];
700 }
701 }
702
703 /// Add all bin contents of another histogram using atomic instructions.
704 ///
705 /// Throws an exception if the axes configurations are not identical.
706 ///
707 /// \param[in] other another histogram that must not be modified during the operation
708 void AddAtomic(const RHistEngine &other)
709 {
710 if (fAxes != other.fAxes) {
711 throw std::invalid_argument("axes configurations not identical in AddAtomic");
712 }
713 for (std::size_t i = 0; i < fBinContents.size(); i++) {
715 }
716 }
717
718 /// Clear all bin contents.
719 void Clear()
720 {
721 for (std::size_t i = 0; i < fBinContents.size(); i++) {
722 fBinContents[i] = {};
723 }
724 }
725
726 /// Clone this histogram engine.
727 ///
728 /// Copying all bin contents can be an expensive operation, depending on the number of bins.
729 ///
730 /// \return the cloned object
732 {
734 for (std::size_t i = 0; i < fBinContents.size(); i++) {
735 h.fBinContents[i] = fBinContents[i];
736 }
737 return h;
738 }
739
740 /// Convert this histogram engine to a different bin content type.
741 ///
742 /// There is no bounds checking to make sure that the converted values can be represented. Note that it is not
743 /// possible to convert to RBinWithError since the information about individual weights has been lost since filling.
744 ///
745 /// Converting all bin contents can be an expensive operation, depending on the number of bins.
746 ///
747 /// \return the converted object
748 template <typename U>
750 {
752 for (std::size_t i = 0; i < fBinContents.size(); i++) {
753 h.fBinContents[i] = static_cast<U>(fBinContents[i]);
754 }
755 return h;
756 }
757
758 /// Scale all histogram bin contents.
759 ///
760 /// This method is not available for integral bin content types.
761 ///
762 /// \param[in] factor the scale factor
763 void Scale(double factor)
764 {
765 static_assert(!std::is_integral_v<BinContentType>, "scaling is not supported for integral bin content types");
766 for (std::size_t i = 0; i < fBinContents.size(); i++) {
767 fBinContents[i] *= factor;
768 }
769 }
770
771 /// \}
772 // End the group to ensure that all contained member functions are public.
773
774private:
775 RHistEngine SliceImpl(const std::vector<RSliceSpec> &sliceSpecs, bool &dropped) const
776 {
777 if (sliceSpecs.size() != GetNDimensions()) {
778 throw std::invalid_argument("invalid number of specifications passed to Slice");
779 }
780
781 // Slice the axes.
782 std::vector<RAxisVariant> axes;
783 for (std::size_t i = 0; i < sliceSpecs.size(); i++) {
784 // A sum operation makes the dimension disappear.
785 if (sliceSpecs[i].GetOperationSum() == nullptr) {
786 axes.push_back(fAxes.Get()[i].Slice(sliceSpecs[i]));
787 }
788 }
789 if (axes.empty()) {
790 throw std::invalid_argument("summing across all dimensions is not supported");
791 }
792
793 RHistEngine sliced(std::move(axes));
794
795 // Create the helper objects to map the bin contents to the sliced histogram.
796 Internal::RSliceBinIndexMapper mapper(sliceSpecs);
797 assert(mapper.GetMappedDimensionality() == sliced.GetNDimensions());
798 std::vector<RBinIndex> mappedIndices(mapper.GetMappedDimensionality());
799
800 auto origRange = fAxes.GetFullMultiDimRange();
801 auto origRangeIt = origRange.begin();
802
803 for (std::size_t i = 0; i < fBinContents.size(); i++) {
804 const auto &origIndices = *origRangeIt;
805#ifndef NDEBUG
806 // Verify that the original indices correspond to the iteration variable.
807 RLinearizedIndex origIndex = fAxes.ComputeGlobalIndex(origIndices);
808 assert(origIndex.fValid);
809 assert(origIndex.fIndex == i);
810#endif
811
812 bool success = mapper.Map(origIndices, mappedIndices);
813 if (success) {
814 RLinearizedIndex mappedIndex = sliced.fAxes.ComputeGlobalIndex(mappedIndices);
815 assert(mappedIndex.fValid);
816 sliced.fBinContents[mappedIndex.fIndex] += fBinContents[i];
817 } else {
818 dropped = true;
819 }
820 ++origRangeIt;
821 }
822
823 return sliced;
824 }
825
826public:
827 /// \name Operations
828 /// \{
829
830 /// Slice this histogram with an RSliceSpec per dimension.
831 ///
832 /// With a range, only the specified bins are retained. All other bin contents are transferred to the underflow and
833 /// overflow bins:
834 /// \code
835 /// ROOT::Experimental::RHistEngine<int> hist(/* one dimension */);
836 /// // Fill the histogram with a number of entries...
837 /// auto sliced = hist.Slice({hist.GetAxes()[0].GetNormalRange(1, 5)});
838 /// // The returned histogram will have 4 normal bins, an underflow and an overflow bin.
839 /// \endcode
840 ///
841 /// Slicing can also perform operations per dimension, see RSliceSpec. RSliceSpec::ROperationRebin allows to rebin
842 /// the histogram axis, grouping a number of normal bins into a new one:
843 /// \code
844 /// ROOT::Experimental::RHistEngine<int> hist(/* one dimension */);
845 /// // Fill the histogram with a number of entries...
846 /// auto rebinned = hist.Slice(ROOT::Experimental::RSliceSpec::ROperationRebin(2));
847 /// // The returned histogram has groups of two normal bins merged.
848 /// \endcode
849 ///
850 /// RSliceSpec::ROperationSum sums the bin contents along that axis, which allows to project to a lower-dimensional
851 /// histogram:
852 /// \code
853 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
854 /// // Fill the histogram with a number of entries...
855 /// auto projected = hist.Slice(ROOT::Experimental::RSliceSpec{}, ROOT::Experimental::RSliceSpec::ROperationSum{});
856 /// // The returned histogram has one dimension, with bin contents summed along the second axis.
857 /// \endcode
858 /// Note that it is not allowed to sum along all histogram axes because the return value would be a scalar.
859 ///
860 /// Ranges and operations can be combined. In that case, the range is applied before the operation.
861 ///
862 /// \param[in] sliceSpecs the slice specifications for each axis
863 /// \return the sliced histogram
864 /// \par See also
865 /// the \ref Slice(const A &... args) const "variadic function template overload" accepting arguments directly
866 RHistEngine Slice(const std::vector<RSliceSpec> &sliceSpecs) const
867 {
868 bool dropped = false;
869 return SliceImpl(sliceSpecs, dropped);
870 }
871
872 /// Slice this histogram with an RSliceSpec per dimension.
873 ///
874 /// With a range, only the specified bins are retained. All other bin contents are transferred to the underflow and
875 /// overflow bins:
876 /// \code
877 /// ROOT::Experimental::RHistEngine<int> hist(/* one dimension */);
878 /// // Fill the histogram with a number of entries...
879 /// auto sliced = hist.Slice(hist.GetAxes()[0].GetNormalRange(1, 5));
880 /// // The returned histogram will have 4 normal bins, an underflow and an overflow bin.
881 /// \endcode
882 ///
883 /// Slicing can also perform operations per dimension, see RSliceSpec. RSliceSpec::ROperationRebin allows to rebin
884 /// the histogram axis, grouping a number of normal bins into a new one:
885 /// \code
886 /// ROOT::Experimental::RHistEngine<int> hist(/* one dimension */);
887 /// // Fill the histogram with a number of entries...
888 /// auto rebinned = hist.Slice(ROOT::Experimental::RSliceSpec::ROperationRebin(2));
889 /// // The returned histogram has groups of two normal bins merged.
890 /// \endcode
891 ///
892 /// RSliceSpec::ROperationSum sums the bin contents along that axis, which allows to project to a lower-dimensional
893 /// histogram:
894 /// \code
895 /// ROOT::Experimental::RHistEngine<int> hist({/* two dimensions */});
896 /// // Fill the histogram with a number of entries...
897 /// auto projected = hist.Slice(ROOT::Experimental::RSliceSpec{}, ROOT::Experimental::RSliceSpec::ROperationSum{});
898 /// // The returned histogram has one dimension, with bin contents summed along the second axis.
899 /// \endcode
900 /// Note that it is not allowed to sum along all histogram axes because the return value would be a scalar.
901 ///
902 /// Ranges and operations can be combined. In that case, the range is applied before the operation.
903 ///
904 /// \param[in] args the arguments for each axis
905 /// \return the sliced histogram
906 /// \par See also
907 /// the \ref Slice(const std::vector<RSliceSpec> &sliceSpecs) const "function overload" accepting `std::vector`
908 template <typename... A>
909 RHistEngine Slice(const A &...args) const
910 {
911 std::vector<RSliceSpec> sliceSpecs{args...};
912 return Slice(sliceSpecs);
913 }
914
915 /// Create an atomic snapshot of this histogram engine.
916 ///
917 /// A snapshot is a consistent copy of the histogram, during concurrent filling. It is guaranteed that the returned
918 /// copy represents a state between the begin and end of the snapshot operation.
919 ///
920 /// Snapshotting a histogram engine with many bins can be an expensive operation.
921 ///
922 /// \return the atomic snapshot
924 {
925 static_assert(std::is_trivially_copyable_v<BinContentType>,
926 "snapshotting requires a trivially copyable bin content type");
927
928 do {
929 while (fSnapshotInProgress.load(std::memory_order_relaxed)) {
930 // Spin while another snapshot is running
931 }
932 } while (fSnapshotInProgress.exchange(true, std::memory_order_relaxed));
933
934 RHistEngine snapshot(fAxes.Get());
935 // Do a first collect.
936 for (std::size_t i = 0; i < fBinContents.size(); i++) {
938 }
939
940 // Now do another collect. If no change is detected, the snapshot is consistent. Otherwise update the bin contents
941 // and try again.
942 BinContentType tmp;
943 bool changed;
944 do {
945 // To guarantee correctness, we let the release operation(s) in FillAtomic synchronize with this acquire fence.
946 // This ensures that all previous writes become visible side-effects and the atomic loads will see them.
947 std::atomic_thread_fence(std::memory_order_acquire);
948
949 changed = false;
950 for (std::size_t i = 0; i < fBinContents.size(); i++) {
952 if (std::memcmp(&tmp, &snapshot.fBinContents[i], sizeof(BinContentType))) {
953 std::memcpy(&snapshot.fBinContents[i], &tmp, sizeof(BinContentType));
954 changed = true;
955 }
956 }
957 } while (changed);
958
959 fSnapshotInProgress.store(false, std::memory_order_relaxed);
960
961 return snapshot;
962 }
963
964 /// \}
965
966 /// %ROOT Streamer function to throw when trying to store an object of this class.
967 void Streamer(TBuffer &) { throw std::runtime_error("unable to store RHistEngine"); }
968};
969
970} // namespace Experimental
971} // namespace ROOT
972
973#endif
#define h(i)
Definition RSha256.hxx:106
#define N
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t index
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
Bin configurations for all dimensions of a histogram.
Definition RAxes.hxx:40
std::size_t GetNDimensions() const
Definition RAxes.hxx:55
RLinearizedIndex ComputeGlobalIndexImpl(std::size_t index, const std::tuple< A... > &args) const
Definition RAxes.hxx:77
RLinearizedIndex ComputeGlobalIndex(const std::tuple< A... > &args) const
Compute the global index for all axes.
Definition RAxes.hxx:131
RBinIndexMultiDimRange GetFullMultiDimRange() const
Get the multidimensional range of all bins.
Definition RAxes.hxx:195
std::uint64_t ComputeTotalNBins() const
Compute the total number of bins for all axes.
Definition RAxes.hxx:66
std::vector< RAxisVariant > fAxes
Definition RAxes.hxx:44
const std::vector< RAxisVariant > & Get() const
Definition RAxes.hxx:56
Mapper of bin indices for slice operations.
bool Map(const std::vector< RBinIndex > &original, std::vector< RBinIndex > &mapped) const
Map a vector of RBinIndex according to the slice specifications.
A variant of all supported axis types.
A multidimensional range of bin indices.
A bin index with special values for underflow and overflow bins.
Definition RBinIndex.hxx:23
A histogram data structure to bin data along multiple dimensions.
RHistEngine Slice(const std::vector< RSliceSpec > &sliceSpecs) const
Slice this histogram with an RSliceSpec per dimension.
RHistEngine & operator=(RHistEngine &&rhs) noexcept
Efficiently move a histogram engine.
RHistEngine(const RAxisVariant &axis1, const Axes &...axes)
Construct a histogram engine.
void Fill(const A &...args)
Fill an entry into the histogram.
const std::vector< RAxisVariant > & GetAxes() const
RHistEngine(RHistEngine &&rhs) noexcept
Efficiently move construct a histogram engine.
RBinIndexMultiDimRange GetFullMultiDimRange() const
Get the multidimensional range of all bins.
RHistEngine Clone() const
Clone this histogram engine.
void FillImpl(const std::tuple< A... > &args, const W &weight)
void SetBinContent(const A &...args)
Set the content of a single bin.
void Scale(double factor)
Scale all histogram bin contents.
RHistEngine SnapshotAtomic() const
Create an atomic snapshot of this histogram engine.
void Fill(const std::tuple< A... > &args)
Fill an entry into the histogram.
void FillAtomic(const std::tuple< A... > &args)
Fill an entry into the histogram using atomic instructions.
void SetBinContent(const std::vector< RBinIndex > &indices, const V &value)
Set the content of a single bin.
RHistEngine(std::uint64_t nNormalBins, std::pair< double, double > interval)
Construct a one-dimensional histogram engine with a regular axis.
RHistEngine & operator=(const RHistEngine &)=delete
The copy assignment operator is deleted.
const BinContentType & GetBinContent(const std::vector< RBinIndex > &indices) const
Get the content of a single bin.
RHistEngine(const RHistEngine &)=delete
The copy constructor is deleted.
const BinContentType & GetBinContent(const std::array< RBinIndex, N > &indices) const
Get the content of a single bin.
const BinContentType & GetBinContent(const A &...args) const
Get the content of a single bin.
RHistEngine SliceImpl(const std::vector< RSliceSpec > &sliceSpecs, bool &dropped) const
void SetBinContent(const std::array< RBinIndex, N > &indices, const V &value)
Set the content of a single bin.
void AddAtomic(const RHistEngine &other)
Add all bin contents of another histogram using atomic instructions.
std::size_t GetNDimensions() const
void Fill(const std::tuple< A... > &args, const W &weight)
Fill an entry into the histogram with a user-defined weight.
void Add(const RHistEngine &other)
Add all bin contents of another histogram.
void FillAtomic(const std::tuple< A... > &args, RWeight weight)
Fill an entry into the histogram with a weight using atomic instructions.
static constexpr bool SupportsWeightedFilling
Whether this histogram engine type supports weighted filling.
void Clear()
Clear all bin contents.
RHistEngine Slice(const A &...args) const
Slice this histogram with an RSliceSpec per dimension.
std::uint64_t GetTotalNBins() const
void FillAtomic(const std::tuple< A... > &args, const W &weight)
Fill an entry into the histogram with a user-defined weight using atomic instructions.
void SetBinContentImpl(const std::tuple< A... > &args, std::index_sequence< I... >)
RHistEngine(std::vector< RAxisVariant > axes)
Construct a histogram engine.
void FillAtomic(const A &...args)
Fill an entry into the histogram using atomic instructions.
Internal::RAxes fAxes
The axis configuration for this histogram. Relevant methods are forwarded from the public interface.
void Fill(const std::tuple< A... > &args, RWeight weight)
Fill an entry into the histogram with a weight.
void FillAtomicImpl(const std::tuple< A... > &args, const W &weight)
std::atomic< bool > fSnapshotInProgress
Flag to pause filling while a snapshot is ongoing.
RHistEngine(std::initializer_list< RAxisVariant > axes)
Construct a histogram engine.
void Streamer(TBuffer &)
ROOT Streamer function to throw when trying to store an object of this class.
std::vector< BinContentType > fBinContents
The bin contents for this histogram.
RHistEngine< U > Convert() const
Convert this histogram engine to a different bin content type.
A histogram for aggregation of data along multiple dimensions.
Definition RHist.hxx:66
A context to concurrently fill an RProfile.
A profile histogram, computing statistical quantities of an additional variable per bin.
Definition RProfile.hxx:58
A regular axis with equidistant bins in the interval .
Buffer base class used for serializing objects.
Definition TBuffer.h:43
std::enable_if_t< std::is_arithmetic_v< T > > AtomicIncRelease(T *ptr)
std::enable_if_t< std::is_arithmetic_v< T > > AtomicLoad(const T *ptr, T *ret)
std::enable_if_t< std::is_integral_v< T > > AtomicAdd(T *ptr, T val)
std::enable_if_t< std::is_integral_v< T > > AtomicAddRelease(T *ptr, T val)
A linearized index that can be invalid.
A weight for filling histograms.
Definition RWeight.hxx:17