HDK
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Stats.h
Go to the documentation of this file.
1 ///////////////////////////////////////////////////////////////////////////
2 //
3 // Copyright (c) 2012-2018 DreamWorks Animation LLC
4 //
5 // All rights reserved. This software is distributed under the
6 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
7 //
8 // Redistributions of source code must retain the above copyright
9 // and license notice and the following restrictions and disclaimer.
10 //
11 // * Neither the name of DreamWorks Animation nor the names of
12 // its contributors may be used to endorse or promote products derived
13 // from this software without specific prior written permission.
14 //
15 // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
16 // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
17 // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
18 // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
19 // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY INDIRECT, INCIDENTAL,
20 // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
21 // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
25 // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 // IN NO EVENT SHALL THE COPYRIGHT HOLDERS' AND CONTRIBUTORS' AGGREGATE
27 // LIABILITY FOR ALL CLAIMS REGARDLESS OF THEIR BASIS EXCEED US$250.00.
28 //
29 ///////////////////////////////////////////////////////////////////////////
30 //
31 /// @file Stats.h
32 ///
33 /// @author Ken Museth
34 ///
35 /// @brief Classes to compute statistics and histograms
36 
37 #ifndef OPENVDB_MATH_STATS_HAS_BEEN_INCLUDED
38 #define OPENVDB_MATH_STATS_HAS_BEEN_INCLUDED
39 
40 #include <iosfwd> // for ostringstream
41 #include <openvdb/version.h>
42 #include <openvdb/Exceptions.h>
43 #include <iostream>
44 #include <iomanip>
45 #include <sstream>
46 #include <vector>
47 #include <functional>// for std::less
48 #include "Math.h"
49 
50 namespace openvdb {
52 namespace OPENVDB_VERSION_NAME {
53 namespace math {
54 
55 /// @brief Templated class to compute the minimum and maximum values.
56 template <typename ValueType, typename Less = std::less<ValueType> >
57 class MinMax
58 {
59  using Limits = std::numeric_limits<ValueType>;
60 public:
61 
62  /// @brief Empty constructor
63  ///
64  /// @warning Only use this constructor with POD types
65  MinMax() : mMin(Limits::max()), mMax(Limits::lowest())
66  {
67  static_assert(std::numeric_limits<ValueType>::is_specialized,
68  "openvdb::math::MinMax default constructor requires a std::numeric_limits specialization");
69  }
70 
71  /// @brief Constructor
72  MinMax(const ValueType &min, const ValueType &max) : mMin(min), mMax(max)
73  {
74  }
75 
76  /// @brief Default copy constructor
77  MinMax(const MinMax &other) = default;
78 
79  /// Add a single sample.
80  inline void add(const ValueType &val, const Less &less = Less())
81  {
82  if (less(val, mMin)) mMin = val;
83  if (less(mMax, val)) mMax = val;
84  }
85 
86  /// Return the minimum value.
87  inline const ValueType& min() const { return mMin; }
88 
89  /// Return the maximum value.
90  inline const ValueType& max() const { return mMax; }
91 
92  /// Add the samples from the other Stats instance.
93  inline void add(const MinMax& other, const Less &less = Less())
94  {
95  if (less(other.mMin, mMin)) mMin = other.mMin;
96  if (less(mMax, other.mMax)) mMax = other.mMax;
97  }
98 
99  /// @brief Print MinMax to the specified output stream.
100  void print(const std::string &name= "", std::ostream &strm=std::cout, int precision=3) const
101  {
102  // Write to a temporary string stream so as not to affect the state
103  // (precision, field width, etc.) of the output stream.
104  std::ostringstream os;
105  os << std::setprecision(precision) << std::setiosflags(std::ios::fixed);
106  os << "MinMax ";
107  if (!name.empty()) os << "for \"" << name << "\" ";
108  os << " Min=" << mMin << ", Max=" << mMax << std::endl;
109  strm << os.str();
110  }
111 
112 protected:
113 
114  ValueType mMin, mMax;
115 };//end MinMax
116 
117 /// @brief This class computes the minimum and maximum values of a population
118 /// of floating-point values.
119 class Extrema
120 {
121 public:
122 
123  /// @brief Constructor
124  /// @warning The min/max values are initiated to extreme values
126  : mSize(0)
127  , mMin(std::numeric_limits<double>::max())
128  , mMax(-mMin)
129  {
130  }
131 
132  /// Add a single sample.
133  void add(double val)
134  {
135  ++mSize;
136  mMin = std::min<double>(val, mMin);
137  mMax = std::max<double>(val, mMax);
138  }
139 
140  /// Add @a n samples with constant value @a val.
141  void add(double val, uint64_t n)
142  {
143  mSize += n;
144  mMin = std::min<double>(val, mMin);
145  mMax = std::max<double>(val, mMax);
146  }
147 
148  /// Return the size of the population, i.e., the total number of samples.
149  inline uint64_t size() const { return mSize; }
150 
151  /// Return the minimum value.
152  inline double min() const { return mMin; }
153 
154  /// Return the maximum value.
155  inline double max() const { return mMax; }
156 
157  /// Return the range defined as the maximum value minus the minimum value.
158  inline double range() const { return mMax - mMin; }
159 
160  /// Add the samples from the other Stats instance.
161  void add(const Extrema& other)
162  {
163  if (other.mSize > 0) this->join(other);
164  }
165 
166  /// @brief Print extrema to the specified output stream.
167  void print(const std::string &name= "", std::ostream &strm=std::cout, int precision=3) const
168  {
169  // Write to a temporary string stream so as not to affect the state
170  // (precision, field width, etc.) of the output stream.
171  std::ostringstream os;
172  os << std::setprecision(precision) << std::setiosflags(std::ios::fixed);
173  os << "Extrema ";
174  if (!name.empty()) os << "for \"" << name << "\" ";
175  if (mSize>0) {
176  os << "with " << mSize << " samples:\n"
177  << " Min=" << mMin
178  << ", Max=" << mMax
179  << ", Range="<< this->range() << std::endl;
180  } else {
181  os << ": no samples were added." << std::endl;
182  }
183  strm << os.str();
184  }
185 
186 protected:
187 
188  inline void join(const Extrema& other)
189  {
190  assert(other.mSize > 0);
191  mSize += other.mSize;
192  mMin = std::min<double>(mMin, other.mMin);
193  mMax = std::max<double>(mMax, other.mMax);
194  }
195 
196  uint64_t mSize;
197  double mMin, mMax;
198 };//end Extrema
199 
200 
201 /// @brief This class computes statistics (minimum value, maximum
202 /// value, mean, variance and standard deviation) of a population
203 /// of floating-point values.
204 ///
205 /// @details variance = Mean[ (X-Mean[X])^2 ] = Mean[X^2] - Mean[X]^2,
206 /// standard deviation = sqrt(variance)
207 ///
208 /// @note This class employs incremental computation and double precision.
209 class Stats : public Extrema
210 {
211 public:
213  : Extrema()
214  , mAvg(0.0)
215  , mAux(0.0)
216  {
217  }
218 
219  /// Add a single sample.
220  void add(double val)
221  {
222  Extrema::add(val);
223  const double delta = val - mAvg;
224  mAvg += delta/double(mSize);
225  mAux += delta*(val - mAvg);
226  }
227 
228  /// Add @a n samples with constant value @a val.
229  void add(double val, uint64_t n)
230  {
231  const double denom = 1.0/double(mSize + n);
232  const double delta = val - mAvg;
233  mAvg += denom * delta * double(n);
234  mAux += denom * delta * delta * double(mSize) * double(n);
235  Extrema::add(val, n);
236  }
237 
238  /// Add the samples from the other Stats instance.
239  void add(const Stats& other)
240  {
241  if (other.mSize > 0) {
242  const double denom = 1.0/double(mSize + other.mSize);
243  const double delta = other.mAvg - mAvg;
244  mAvg += denom * delta * double(other.mSize);
245  mAux += other.mAux + denom * delta * delta * double(mSize) * double(other.mSize);
246  Extrema::join(other);
247  }
248  }
249 
250  //@{
251  /// Return the arithmetic mean, i.e. average, value.
252  inline double avg() const { return mAvg; }
253  inline double mean() const { return mAvg; }
254  //@}
255 
256  //@{
257  /// @brief Return the population variance.
258  /// @note The unbiased sample variance = population variance *
259  //num/(num-1)
260  inline double var() const { return mSize<2 ? 0.0 : mAux/double(mSize); }
261  inline double variance() const { return this->var(); }
262  //@}
263 
264  //@{
265  /// @brief Return the standard deviation (=Sqrt(variance)) as
266  /// defined from the (biased) population variance.
267  inline double std() const { return sqrt(this->var()); }
268  inline double stdDev() const { return this->std(); }
269  //@}
270 
271  /// @brief Print statistics to the specified output stream.
272  void print(const std::string &name= "", std::ostream &strm=std::cout, int precision=3) const
273  {
274  // Write to a temporary string stream so as not to affect the state
275  // (precision, field width, etc.) of the output stream.
276  std::ostringstream os;
277  os << std::setprecision(precision) << std::setiosflags(std::ios::fixed);
278  os << "Statistics ";
279  if (!name.empty()) os << "for \"" << name << "\" ";
280  if (mSize>0) {
281  os << "with " << mSize << " samples:\n"
282  << " Min=" << mMin
283  << ", Max=" << mMax
284  << ", Ave=" << mAvg
285  << ", Std=" << this->stdDev()
286  << ", Var=" << this->variance() << std::endl;
287  } else {
288  os << ": no samples were added." << std::endl;
289  }
290  strm << os.str();
291  }
292 
293 protected:
294  using Extrema::mSize;
295  using Extrema::mMin;
296  using Extrema::mMax;
297  double mAvg, mAux;
298 }; // end Stats
299 
300 
301 ////////////////////////////////////////
302 
303 
304 /// @brief This class computes a histogram, with a fixed interval width,
305 /// of a population of floating-point values.
307 {
308 public:
309  /// Construct with given minimum and maximum values and the given bin count.
310  Histogram(double min, double max, size_t numBins = 10)
311  : mSize(0), mMin(min), mMax(max + 1e-10),
312  mDelta(double(numBins)/(max-min)), mBins(numBins)
313  {
314  if ( mMax <= mMin ) {
315  OPENVDB_THROW(ValueError, "Histogram: expected min < max");
316  } else if ( numBins == 0 ) {
317  OPENVDB_THROW(ValueError, "Histogram: expected at least one bin");
318  }
319  for (size_t i=0; i<numBins; ++i) mBins[i]=0;
320  }
321 
322  /// @brief Construct with the given bin count and with minimum and maximum values
323  /// taken from a Stats object.
324  Histogram(const Stats& s, size_t numBins = 10):
325  mSize(0), mMin(s.min()), mMax(s.max()+1e-10),
326  mDelta(double(numBins)/(mMax-mMin)), mBins(numBins)
327  {
328  if ( mMax <= mMin ) {
329  OPENVDB_THROW(ValueError, "Histogram: expected min < max");
330  } else if ( numBins == 0 ) {
331  OPENVDB_THROW(ValueError, "Histogram: expected at least one bin");
332  }
333  for (size_t i=0; i<numBins; ++i) mBins[i]=0;
334  }
335 
336  /// @brief Add @a n samples with constant value @a val, provided that the
337  /// @a val falls within this histogram's value range.
338  /// @return @c true if the sample value falls within this histogram's value range.
339  inline bool add(double val, uint64_t n = 1)
340  {
341  if (val<mMin || val>mMax) return false;
342  mBins[size_t(mDelta*(val-mMin))] += n;
343  mSize += n;
344  return true;
345  }
346 
347  /// @brief Add all the contributions from the other histogram, provided that
348  /// it has the same configuration as this histogram.
349  bool add(const Histogram& other)
350  {
351  if (!isApproxEqual(mMin, other.mMin) || !isApproxEqual(mMax, other.mMax) ||
352  mBins.size() != other.mBins.size()) return false;
353  for (size_t i=0, e=mBins.size(); i!=e; ++i) mBins[i] += other.mBins[i];
354  mSize += other.mSize;
355  return true;
356  }
357 
358  /// Return the number of bins in this histogram.
359  inline size_t numBins() const { return mBins.size(); }
360  /// Return the lower bound of this histogram's value range.
361  inline double min() const { return mMin; }
362  /// Return the upper bound of this histogram's value range.
363  inline double max() const { return mMax; }
364  /// Return the minimum value in the <i>n</i>th bin.
365  inline double min(int n) const { return mMin+n/mDelta; }
366  /// Return the maximum value in the <i>n</i>th bin.
367  inline double max(int n) const { return mMin+(n+1)/mDelta; }
368  /// Return the number of samples in the <i>n</i>th bin.
369  inline uint64_t count(int n) const { return mBins[n]; }
370  /// Return the population size, i.e., the total number of samples.
371  inline uint64_t size() const { return mSize; }
372 
373  /// Print the histogram to the specified output stream.
374  void print(const std::string& name = "", std::ostream& strm = std::cout) const
375  {
376  // Write to a temporary string stream so as not to affect the state
377  // (precision, field width, etc.) of the output stream.
378  std::ostringstream os;
379  os << std::setprecision(6) << std::setiosflags(std::ios::fixed) << std::endl;
380  os << "Histogram ";
381  if (!name.empty()) os << "for \"" << name << "\" ";
382  if (mSize > 0) {
383  os << "with " << mSize << " samples:\n";
384  os << "==============================================================\n";
385  os << "|| # | Min | Max | Frequency | % ||\n";
386  os << "==============================================================\n";
387  for (int i = 0, e = int(mBins.size()); i != e; ++i) {
388  os << "|| " << std::setw(4) << i << " | " << std::setw(14) << this->min(i) << " | "
389  << std::setw(14) << this->max(i) << " | " << std::setw(9) << mBins[i] << " | "
390  << std::setw(3) << (100*mBins[i]/mSize) << " ||\n";
391  }
392  os << "==============================================================\n";
393  } else {
394  os << ": no samples were added." << std::endl;
395  }
396  strm << os.str();
397  }
398 
399 private:
400  uint64_t mSize;
401  double mMin, mMax, mDelta;
402  std::vector<uint64_t> mBins;
403 };// end Histogram
404 
405 } // namespace math
406 } // namespace OPENVDB_VERSION_NAME
407 } // namespace openvdb
408 
409 #endif // OPENVDB_MATH_STATS_HAS_BEEN_INCLUDED
410 
411 // Copyright (c) 2012-2018 DreamWorks Animation LLC
412 // All rights reserved. This software is distributed under the
413 // Mozilla Public License 2.0 ( http://www.mozilla.org/MPL/2.0/ )
GLsizei const GLchar *const * string
Definition: glcorearb.h:813
double stdDev() const
Return the standard deviation (=Sqrt(variance)) as defined from the (biased) population variance...
Definition: Stats.h:268
bool add(const Histogram &other)
Add all the contributions from the other histogram, provided that it has the same configuration as th...
Definition: Stats.h:349
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:189
void add(const Extrema &other)
Add the samples from the other Stats instance.
Definition: Stats.h:161
void add(const ValueType &val, const Less &less=Less())
Add a single sample.
Definition: Stats.h:80
void print(const std::string &name="", std::ostream &strm=std::cout) const
Print the histogram to the specified output stream.
Definition: Stats.h:374
png_uint_32 i
Definition: png.h:2877
uint64_t size() const
Return the population size, i.e., the total number of samples.
Definition: Stats.h:371
void add(const MinMax &other, const Less &less=Less())
Add the samples from the other Stats instance.
Definition: Stats.h:93
uint64_t count(int n) const
Return the number of samples in the nth bin.
Definition: Stats.h:369
GLdouble n
Definition: glcorearb.h:2007
double mean() const
Return the arithmetic mean, i.e. average, value.
Definition: Stats.h:253
double min(int n) const
Return the minimum value in the nth bin.
Definition: Stats.h:365
General-purpose arithmetic and comparison routines, most of which accept arbitrary value types (or at...
size_t numBins() const
Return the number of bins in this histogram.
Definition: Stats.h:359
double variance() const
Return the population variance.
Definition: Stats.h:261
double max(int n) const
Return the maximum value in the nth bin.
Definition: Stats.h:367
void join(const Extrema &other)
Definition: Stats.h:188
const ValueType & max() const
Return the maximum value.
Definition: Stats.h:90
double range() const
Return the range defined as the maximum value minus the minimum value.
Definition: Stats.h:158
This class computes statistics (minimum value, maximum value, mean, variance and standard deviation) ...
Definition: Stats.h:209
void add(double val)
Add a single sample.
Definition: Stats.h:220
double avg() const
Return the arithmetic mean, i.e. average, value.
Definition: Stats.h:252
uint64_t size() const
Return the size of the population, i.e., the total number of samples.
Definition: Stats.h:149
GLuint const GLchar * name
Definition: glcorearb.h:785
Templated class to compute the minimum and maximum values.
Definition: Stats.h:57
void print(const std::string &name="", std::ostream &strm=std::cout, int precision=3) const
Print statistics to the specified output stream.
Definition: Stats.h:272
MinMax(const ValueType &min, const ValueType &max)
Constructor.
Definition: Stats.h:72
void add(double val, uint64_t n)
Add n samples with constant value val.
Definition: Stats.h:229
double min() const
Return the minimum value.
Definition: Stats.h:152
bool isApproxEqual(const Type &a, const Type &b)
Return true if a is equal to b to within the default floating-point comparison tolerance.
Definition: Math.h:358
double min() const
Return the lower bound of this histogram's value range.
Definition: Stats.h:361
GLenum GLint GLint * precision
Definition: glcorearb.h:1924
This class computes a histogram, with a fixed interval width, of a population of floating-point value...
Definition: Stats.h:306
void add(double val, uint64_t n)
Add n samples with constant value val.
Definition: Stats.h:141
void add(const Stats &other)
Add the samples from the other Stats instance.
Definition: Stats.h:239
double var() const
Return the population variance.
Definition: Stats.h:260
const ValueType & min() const
Return the minimum value.
Definition: Stats.h:87
void print(const std::string &name="", std::ostream &strm=std::cout, int precision=3) const
Print MinMax to the specified output stream.
Definition: Stats.h:100
GLuint GLfloat * val
Definition: glcorearb.h:1607
void print(const std::string &name="", std::ostream &strm=std::cout, int precision=3) const
Print extrema to the specified output stream.
Definition: Stats.h:167
double max() const
Return the upper bound of this histogram's value range.
Definition: Stats.h:363
Histogram(const Stats &s, size_t numBins=10)
Construct with the given bin count and with minimum and maximum values taken from a Stats object...
Definition: Stats.h:324
Histogram(double min, double max, size_t numBins=10)
Construct with given minimum and maximum values and the given bin count.
Definition: Stats.h:310
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition: version.h:135
bool add(double val, uint64_t n=1)
Add n samples with constant value val, provided that the val falls within this histogram's value rang...
Definition: Stats.h:339
double max() const
Return the maximum value.
Definition: Stats.h:155
double std() const
Return the standard deviation (=Sqrt(variance)) as defined from the (biased) population variance...
Definition: Stats.h:267
void add(double val)
Add a single sample.
Definition: Stats.h:133
#define OPENVDB_THROW(exception, message)
Definition: Exceptions.h:109
This class computes the minimum and maximum values of a population of floating-point values...
Definition: Stats.h:119