Logo ROOT  
Reference Guide
 
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Modules Pages
Loading...
Searching...
No Matches
Util.h
Go to the documentation of this file.
1// @(#)root/mathcore:$Id$
2// Author: L. Moneta Tue Nov 14 15:44:38 2006
3
4/**********************************************************************
5 * *
6 * Copyright (c) 2006 LCG ROOT Math Team, CERN/PH-SFT *
7 * *
8 * *
9 **********************************************************************/
10
11// Utility functions for all ROOT Math classes
12
13#ifndef ROOT_Math_Util
14#define ROOT_Math_Util
15
16#include <chrono>
17#include <cmath>
18#include <functional>
19#include <limits>
20#include <numeric>
21#include <sstream>
22#include <string>
23
24
25// This can be protected against by defining ROOT_Math_VecTypes
26// This is only used for the R__HAS_VECCORE define
27// and a single VecCore function in EvalLog
28#ifndef ROOT_Math_VecTypes
29#include "Types.h"
30#endif
31
32
33// for defining unused variables in the interfaces
34// and have still them in the documentation
35#define MATH_UNUSED(var) (void)var
36
37
38namespace ROOT {
39
40namespace Math {
41
42/**
43 namespace defining Utility functions needed by mathcore
44*/
45namespace Util {
46
48
49public:
50 TimingScope(std::function<void(std::string const&)> printer, std::string const &message);
51
53
54private:
55 std::chrono::steady_clock::time_point fBegin;
56 std::function<void(std::string const&)> fPrinter;
57 const std::string fMessage;
58};
59
60 /**
61 Utility function for conversion to strings
62 */
63 template <class T>
64 std::string ToString(const T &val)
65 {
66 std::ostringstream buf;
67 buf << val;
68
69 std::string ret = buf.str();
70 return ret;
71 }
72
73 /// safe evaluation of log(x) with a protections against negative or zero argument to the log
74 /// smooth linear extrapolation below function values smaller than epsilon
75 /// (better than a simple cut-off)
76
77 template<class T>
78 inline T EvalLog(T x) {
79 static const T epsilon = T(2.0 * std::numeric_limits<double>::min());
80#ifdef R__HAS_VECCORE
81 T logval = vecCore::Blend<T>(x <= epsilon, x / epsilon + std::log(epsilon) - T(1.0), std::log(x));
82#else
83 T logval = x <= epsilon ? x / epsilon + std::log(epsilon) - T(1.0) : std::log(x);
84#endif
85 return logval;
86 }
87
88 } // end namespace Util
89
90 /// \class KahanSum
91 /// The Kahan summation is a compensated summation algorithm, which significantly reduces numerical errors
92 /// when adding a sequence of finite-precision floating point numbers.
93 /// This is done by keeping a separate running compensation (a variable to accumulate small errors).
94 ///
95 /// ### Auto-vectorisable accumulation
96 /// This class can internally use multiple accumulators (template parameter `N`).
97 /// When filled from a collection that supports index access from a *contiguous* block of memory,
98 /// compilers such as gcc, clang and icc can auto-vectorise the accumulation. This happens by cycling
99 /// through the internal accumulators based on the value of "`index % N`", so `N` accumulators can be filled from a block
100 /// of `N` numbers in a single instruction.
101 ///
102 /// The usage of multiple accumulators might slightly increase the precision in comparison to the single-accumulator version
103 /// with `N = 1`.
104 /// This depends on the order and magnitude of the numbers being accumulated. Therefore, in rare cases, the accumulation
105 /// result can change *in dependence of N*, even when the data are identical.
106 /// The magnitude of such differences is well below the precision of the floating point type, and will therefore mostly show
107 /// in the compensation sum(see Carry()). Increasing the number of accumulators therefore only makes sense to
108 /// speed up the accumulation, but not to increase precision.
109 ///
110 /// \param T The type of the values to be accumulated.
111 /// \param N Number of accumulators. Defaults to 1. Ideal values are the widths of a vector register on the relevant architecture.
112 /// Depending on the instruction set, good values are:
113 /// - AVX2-float: 8
114 /// - AVX2-double: 4
115 /// - AVX512-float: 16
116 /// - AVX512-double: 8
117 ///
118 /// ### Examples
119 ///
120 /// ~~~{.cpp}
121 /// std::vector<double> numbers(1000);
122 /// for (std::size_t i=0; i<1000; ++i) {
123 /// numbers[i] = rand();
124 /// }
125 ///
126 /// ROOT::Math::KahanSum<double, 4> k;
127 /// k.Add(numbers.begin(), numbers.end());
128 /// // or
129 /// k.Add(numbers);
130 /// ~~~
131 /// ~~~{.cpp}
132 /// double offset = 10.;
133 /// auto result = ROOT::Math::KahanSum<double, 4>::Accumulate(numbers.begin(), numbers.end(), offset);
134 /// ~~~
135 template<typename T = double, unsigned int N = 1>
136 class KahanSum {
137 public:
138 /// Initialise the sum.
139 /// \param[in] initialValue Initialise with this value. Defaults to 0.
140 explicit KahanSum(T initialValue = T{}) {
141 fSum[0] = initialValue;
142 std::fill(std::begin(fSum)+1, std::end(fSum), 0.);
143 std::fill(std::begin(fCarry), std::end(fCarry), 0.);
144 }
145
146 /// Initialise with a sum value and a carry value.
147 /// \param[in] initialSumValue Initialise the sum with this value.
148 /// \param[in] initialCarryValue Initialise the carry with this value.
152 std::fill(std::begin(fSum)+1, std::end(fSum), 0.);
153 std::fill(std::begin(fCarry)+1, std::end(fCarry), 0.);
154 }
155
156 /// Initialise the sum with a pre-existing state.
157 /// \param[in] sumBegin Begin of iterator range with values to initialise the sum with.
158 /// \param[in] sumEnd End of iterator range with values to initialise the sum with.
159 /// \param[in] carryBegin Begin of iterator range with values to initialise the carry with.
160 /// \param[in] carryEnd End of iterator range with values to initialise the carry with.
161 template<class Iterator>
162 KahanSum(Iterator sumBegin, Iterator sumEnd, Iterator carryBegin, Iterator carryEnd) {
163 assert(std::distance(sumBegin, sumEnd) == N);
164 assert(std::distance(carryBegin, carryEnd) == N);
165 std::copy(sumBegin, sumEnd, std::begin(fSum));
166 std::copy(carryBegin, carryEnd, std::begin(fCarry));
167 }
168
169 /// Constructor to create a KahanSum from another KahanSum with a different number of accumulators
170 template <unsigned int M>
172 fSum[0] = other.Sum();
173 fCarry[0] = other.Carry();
174 std::fill(std::begin(fSum)+1, std::end(fSum), 0.);
175 std::fill(std::begin(fCarry)+1, std::end(fCarry), 0.);
176 }
177
178 /// Single-element accumulation. Will not vectorise.
179 void Add(T x) {
180 auto y = x - fCarry[0];
181 auto t = fSum[0] + y;
182 fCarry[0] = (t - fSum[0]) - y;
183 fSum[0] = t;
184 }
185
186
187 /// Accumulate from a range denoted by iterators.
188 ///
189 /// This function will auto-vectorise with random-access iterators.
190 /// \param[in] begin Beginning of a range. Needs to be a random access iterator for automatic
191 /// vectorisation, because a contiguous block of memory needs to be read.
192 /// \param[in] end End of the range.
193 template <class Iterator>
194 void Add(Iterator begin, Iterator end) {
195 static_assert(std::is_floating_point<
196 typename std::remove_reference<decltype(*begin)>::type>::value,
197 "Iterator needs to point to floating-point values.");
198 const std::size_t n = std::distance(begin, end);
199
200 for (std::size_t i=0; i<n; ++i) {
201 AddIndexed(*(begin++), i);
202 }
203 }
204
205
206 /// Fill from a container that supports index access.
207 /// \param[in] inputs Container with index access such as std::vector or array.
208 template<class Container_t>
209 void Add(const Container_t& inputs) {
210 static_assert(std::is_floating_point<typename Container_t::value_type>::value,
211 "Container does not hold floating-point values.");
212 for (std::size_t i=0; i < inputs.size(); ++i) {
213 AddIndexed(inputs[i], i);
214 }
215 }
216
217
218 /// Iterate over a range and return an instance of a KahanSum.
219 ///
220 /// See Add(Iterator,Iterator) for details.
221 /// \param[in] begin Beginning of a range.
222 /// \param[in] end End of the range.
223 /// \param[in] initialValue Optional initial value.
224 template <class Iterator>
225 static KahanSum<T, N> Accumulate(Iterator begin, Iterator end,
226 T initialValue = T{}) {
228 theSum.Add(begin, end);
229
230 return theSum;
231 }
232
233
234 /// Add `input` to the sum.
235 ///
236 /// Particularly helpful when filling from a for loop.
237 /// This function can be inlined and auto-vectorised if
238 /// the index parameter is used to enumerate *consecutive* fills.
239 /// Use Add() or Accumulate() when no index is available.
240 /// \param[in] input Value to accumulate.
241 /// \param[in] index Index of the value. Determines internal accumulator that this
242 /// value is added to. Make sure that consecutive fills have consecutive indices
243 /// to make a loop auto-vectorisable. The actual value of the index does not matter,
244 /// as long as it is consecutive.
245 void AddIndexed(T input, std::size_t index) {
246 const unsigned int i = index % N;
247 const T y = input - fCarry[i];
248 const T t = fSum[i] + y;
249 fCarry[i] = (t - fSum[i]) - y;
250 fSum[i] = t;
251 }
252
253 /// \return Compensated sum.
254 T Sum() const {
255 return std::accumulate(std::begin(fSum), std::end(fSum), 0.);
256 }
257
258 /// \return Compensated sum.
259 T Result() const {
260 return Sum();
261 }
262
263 /// \return The sum used for compensation.
264 T Carry() const {
265 return std::accumulate(std::begin(fCarry), std::end(fCarry), 0.);
266 }
267
268 /// Add `arg` into accumulator. Does not vectorise.
270 Add(arg);
271 return *this;
272 }
273
274 /// Add other KahanSum into accumulator. Does not vectorise.
275 ///
276 /// Based on KahanIncrement from:
277 /// Y. Tian, S. Tatikonda and B. Reinwald, "Scalable and Numerically Stable Descriptive Statistics in SystemML," 2012 IEEE 28th International Conference on Data Engineering, 2012, pp. 1351-1359, doi: 10.1109/ICDE.2012.12.
278 /// Note that while Tian et al. add the carry in the first step, we subtract
279 /// the carry, in accordance with the Add(Indexed) implementation(s) above.
280 /// This is purely an implementation choice that has no impact on performance.
281 ///
282 /// \note Take care when using += (and -=) to add other KahanSums into a zero-initialized
283 /// KahanSum. The operator behaves correctly in this case, but the result may be slightly
284 /// off if you expect 0 + x to yield exactly x (where 0 is the zero-initialized KahanSum
285 /// and x another KahanSum). In particular, x's carry term may get lost. This doesn't
286 /// just happen with zero-initialized KahanSums; see the SubtractWithABitTooSmallCarry
287 /// test case in the testKahan unittest for other examples. This behavior is internally
288 /// consistent: the carry also gets lost if you switch the operands and it also happens with
289 /// other KahanSum operators.
290 template<typename U, unsigned int M>
292 U corrected_arg_sum = other.Sum() - (fCarry[0] + other.Carry());
293 U sum = fSum[0] + corrected_arg_sum;
295 fSum[0] = sum;
296 fCarry[0] = correction;
297 return *this;
298 }
299
300 /// Subtract other KahanSum. Does not vectorise.
301 ///
302 /// Based on KahanIncrement from: Tian et al., 2012 (see operator+= documentation).
303 template<typename U, unsigned int M>
305 U corrected_arg_sum = -other.Sum() - (fCarry[0] - other.Carry());
306 U sum = fSum[0] + corrected_arg_sum;
308 fSum[0] = sum;
309 fCarry[0] = correction;
310 return *this;
311 }
312
314 {
315 return {-this->fSum[0], -this->fCarry[0]};
316 }
317
318 template<typename U, unsigned int M>
319 bool operator ==(KahanSum<U, M> const& other) const {
320 return (this->Sum() == other.Sum()) && (this->Carry() == other.Carry());
321 }
322
323 template<typename U, unsigned int M>
324 bool operator !=(KahanSum<U, M> const& other) const {
325 return !(*this == other);
326 }
327
328 private:
329 T fSum[N];
331 };
332
333 /// Add two non-vectorized KahanSums.
334 template<typename T, unsigned int N, typename U, unsigned int M>
336 KahanSum<T, N> sum(left);
337 sum += right;
338 return sum;
339 }
340
341 /// Subtract two non-vectorized KahanSums.
342 template<typename T, unsigned int N, typename U, unsigned int M>
344 KahanSum<T, N> sum(left);
345 sum -= right;
346 return sum;
347 }
348
349 } // end namespace Math
350
351} // end namespace ROOT
352
353
354#endif /* ROOT_Math_Util */
ROOT::Detail::TRangeCast< T, true > TRangeDynCast
TRangeDynCast is an adapter class that allows the typed iteration through a TCollection.
#define N
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
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
The Kahan summation is a compensated summation algorithm, which significantly reduces numerical error...
Definition Util.h:136
T Sum() const
Definition Util.h:254
bool operator==(KahanSum< U, M > const &other) const
Definition Util.h:319
KahanSum< T, N > operator-()
Definition Util.h:313
static KahanSum< T, N > Accumulate(Iterator begin, Iterator end, T initialValue=T{})
Iterate over a range and return an instance of a KahanSum.
Definition Util.h:225
T Result() const
Definition Util.h:259
void Add(Iterator begin, Iterator end)
Accumulate from a range denoted by iterators.
Definition Util.h:194
void Add(const Container_t &inputs)
Fill from a container that supports index access.
Definition Util.h:209
KahanSum(KahanSum< T, M > const &other)
Constructor to create a KahanSum from another KahanSum with a different number of accumulators.
Definition Util.h:171
bool operator!=(KahanSum< U, M > const &other) const
Definition Util.h:324
T Carry() const
Definition Util.h:264
void AddIndexed(T input, std::size_t index)
Add input to the sum.
Definition Util.h:245
KahanSum< T, N > & operator+=(T arg)
Add arg into accumulator. Does not vectorise.
Definition Util.h:269
KahanSum< T, N > & operator+=(const KahanSum< U, M > &other)
Add other KahanSum into accumulator.
Definition Util.h:291
KahanSum(T initialValue=T{})
Initialise the sum.
Definition Util.h:140
KahanSum(T initialSumValue, T initialCarryValue)
Initialise with a sum value and a carry value.
Definition Util.h:149
void Add(T x)
Single-element accumulation. Will not vectorise.
Definition Util.h:179
KahanSum< T, N > & operator-=(KahanSum< U, M > const &other)
Subtract other KahanSum.
Definition Util.h:304
KahanSum(Iterator sumBegin, Iterator sumEnd, Iterator carryBegin, Iterator carryEnd)
Initialise the sum with a pre-existing state.
Definition Util.h:162
std::chrono::steady_clock::time_point fBegin
Definition Util.h:55
const std::string fMessage
Definition Util.h:57
std::function< void(std::string const &) fPrinter)
Definition Util.h:56
TimingScope(std::function< void(std::string const &)> printer, std::string const &message)
Definition Util.cxx:3
Double_t y[n]
Definition legend1.C:17
Double_t x[n]
Definition legend1.C:17
const Int_t n
Definition legend1.C:16
Namespace for new Math classes and functions.
T EvalLog(T x)
safe evaluation of log(x) with a protections against negative or zero argument to the log smooth line...
Definition Util.h:78
std::string ToString(const T &val)
Utility function for conversion to strings.
Definition Util.h:64
DisplacementVector2D< CoordSystem1, U > operator+(DisplacementVector2D< CoordSystem1, U > v1, const DisplacementVector2D< CoordSystem2, U > &v2)
Addition of DisplacementVector2D vectors.
DisplacementVector2D< CoordSystem1, U > operator-(DisplacementVector2D< CoordSystem1, U > v1, DisplacementVector2D< CoordSystem2, U > const &v2)
Difference between two DisplacementVector2D vectors.
tbb::task_arena is an alias of tbb::interface7::task_arena, which doesn't allow to forward declare tb...
static uint64_t sum(uint64_t i)
Definition Factory.cxx:2345