HDK
Statistics.h
Go to the documentation of this file.
1 // Copyright Contributors to the OpenVDB Project
3 //
4 /// @file Statistics.h
5 ///
6 /// @brief Functions to efficiently compute histograms, extremas
7 /// (min/max) and statistics (mean, variance, etc.) of grid values
8
9 #ifndef OPENVDB_TOOLS_STATISTICS_HAS_BEEN_INCLUDED
10 #define OPENVDB_TOOLS_STATISTICS_HAS_BEEN_INCLUDED
11
12 #include <openvdb/Types.h>
13 #include <openvdb/Exceptions.h>
14 #include <openvdb/math/Stats.h>
15 #include "ValueTransformer.h"
16
17
18 namespace openvdb {
20 namespace OPENVDB_VERSION_NAME {
21 namespace tools {
22
23 /// @brief Iterate over a scalar grid and compute a histogram of the values
24 /// of the voxels that are visited, or iterate over a vector-valued grid
25 /// and compute a histogram of the magnitudes of the vectors.
26 /// @param iter an iterator over the values of a grid or its tree
27 /// (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
28 /// @param minVal the smallest value that can be added to the histogram
29 /// @param maxVal the largest value that can be added to the histogram
30 /// @param numBins the number of histogram bins
31 /// @param threaded if true, iterate over the grid in parallel
32 template<typename IterT>
33 inline math::Histogram
34 histogram(const IterT& iter, double minVal, double maxVal,
35  size_t numBins = 10, bool threaded = true);
36
37 /// @brief Iterate over a scalar grid and compute extrema (min/max) of the
38 /// values of the voxels that are visited, or iterate over a vector-valued grid
39 /// and compute extrema of the magnitudes of the vectors.
40 /// @param iter an iterator over the values of a grid or its tree
41 /// (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
42 /// @param threaded if true, iterate over the grid in parallel
43 template<typename IterT>
44 inline math::Extrema
45 extrema(const IterT& iter, bool threaded = true);
46
47 /// @brief Iterate over a scalar grid and compute statistics (mean, variance, etc.)
48 /// of the values of the voxels that are visited, or iterate over a vector-valued grid
49 /// and compute statistics of the magnitudes of the vectors.
50 /// @param iter an iterator over the values of a grid or its tree
51 /// (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
52 /// @param threaded if true, iterate over the grid in parallel
53 template<typename IterT>
54 inline math::Stats
55 statistics(const IterT& iter, bool threaded = true);
56
57 /// @brief Iterate over a grid and compute extrema (min/max) of
58 /// the values produced by applying the given functor at each voxel that is visited.
59 /// @param iter an iterator over the values of a grid or its tree
60 /// (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
61 /// @param op a functor of the form <tt>void op(const IterT&, math::Stats&)</tt>,
62 /// where @c IterT is the type of @a iter, that inserts zero or more
63 /// floating-point values into the provided @c math::Stats object
64 /// @param threaded if true, iterate over the grid in parallel
65 /// @note When @a threaded is true, each thread gets its own copy of the functor.
66 ///
67 /// @par Example:
68 /// Compute statistics of just the active and positive-valued voxels of a scalar,
69 /// floating-point grid.
70 /// @code
71 /// struct Local {
72 /// static inline
73 /// void addIfPositive(const FloatGrid::ValueOnCIter& iter, math::Extrema& ex)
74 /// {
75 /// const float f = *iter;
76 /// if (f > 0.0) {
79 /// }
80 /// }
81 /// };
82 /// FloatGrid grid = ...;
83 /// math::Extrema stats =
85 /// @endcode
86 template<typename IterT, typename ValueOp>
87 inline math::Extrema
88 extrema(const IterT& iter, const ValueOp& op, bool threaded);
89
90 /// @brief Iterate over a grid and compute statistics (mean, variance, etc.) of
91 /// the values produced by applying the given functor at each voxel that is visited.
92 /// @param iter an iterator over the values of a grid or its tree
93 /// (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
94 /// @param op a functor of the form <tt>void op(const IterT&, math::Stats&)</tt>,
95 /// where @c IterT is the type of @a iter, that inserts zero or more
96 /// floating-point values into the provided @c math::Stats object
97 /// @param threaded if true, iterate over the grid in parallel
98 /// @note When @a threaded is true, each thread gets its own copy of the functor.
99 ///
100 /// @par Example:
101 /// Compute statistics of just the active and positive-valued voxels of a scalar,
102 /// floating-point grid.
103 /// @code
104 /// struct Local {
105 /// static inline
106 /// void addIfPositive(const FloatGrid::ValueOnCIter& iter, math::Stats& stats)
107 /// {
108 /// const float f = *iter;
109 /// if (f > 0.0) {
112 /// }
113 /// }
114 /// };
115 /// FloatGrid grid = ...;
116 /// math::Stats stats =
118 /// @endcode
119 template<typename IterT, typename ValueOp>
120 inline math::Stats
121 statistics(const IterT& iter, const ValueOp& op, bool threaded);
122
123
124 /// @brief Iterate over a grid and compute statistics (mean, variance, etc.)
125 /// of the values produced by applying a given operator (see math/Operators.h)
126 /// at each voxel that is visited.
127 /// @param iter an iterator over the values of a grid or its tree
128 /// (@c Grid::ValueOnCIter, @c Tree::ValueOffIter, etc.)
129 /// @param op an operator object with a method of the form
130 /// <tt>double result(Accessor&, const Coord&)</tt>
131 /// @param threaded if true, iterate over the grid in parallel
132 /// @note World-space operators, whose @c result() methods are of the form
133 /// <tt>double result(const Map&, Accessor&, const Coord&)</tt>, must be wrapped
135 /// @note Vector-valued operators like math::Gradient must be wrapped in an adapter
136 /// such as math::OpMagnitude.
137 ///
138 /// @par Example:
139 /// Compute statistics of the magnitude of the gradient at the active voxels of
140 /// a scalar, floating-point grid. (Note the use of the math::MapAdapter and
142 /// @code
143 /// FloatGrid grid = ...;
144 ///
145 /// // Assume that we know that the grid has a uniform scale map.
146 /// using MapType = math::UniformScaleMap;
147 /// // Specify a world-space gradient operator that uses first-order differencing.
149 /// // Wrap the operator with an adapter that computes the magnitude of the gradient.
150 /// using MagnitudeOp = math::OpMagnitude<GradientOp, MapType>;
151 /// // Wrap the operator with an adapter that associates a map with it.
153 ///
154 /// if (MapType::Ptr map = grid.constTransform().constMap<MapType>()) {
155 /// math::Stats stats = tools::opStatistics(grid.cbeginValueOn(), CompoundOp(*map));
156 /// }
157 /// @endcode
158 ///
159 /// @par Example:
160 /// Compute statistics of the divergence at the active voxels of a vector-valued grid.
161 /// @code
162 /// Vec3SGrid grid = ...;
163 ///
164 /// // Assume that we know that the grid has a uniform scale map.
165 /// using MapType = math::UniformScaleMap;
166 /// // Specify a world-space divergence operator that uses first-order differencing.
167 /// using DivergenceOp = math::Divergence<MapType, math::FD_1ST>;
168 /// // Wrap the operator with an adapter that associates a map with it.
169 /// using CompoundOp = math::MapAdapter<MapType, DivergenceOp, double>;
170 ///
171 /// if (MapType::Ptr map = grid.constTransform().constMap<MapType>()) {
172 /// math::Stats stats = tools::opStatistics(grid.cbeginValueOn(), CompoundOp(*map));
173 /// }
174 /// @endcode
175 ///
176 /// @par Example:
177 /// As above, but computing the divergence in index space.
178 /// @code
179 /// Vec3SGrid grid = ...;
180 ///
181 /// // Specify an index-space divergence operator that uses first-order differencing.
182 /// using DivergenceOp = math::ISDivergence<math::FD_1ST>;
183 ///
184 /// math::Stats stats = tools::opStatistics(grid.cbeginValueOn(), DivergenceOp());
185 /// @endcode
186 template<typename OperatorT, typename IterT>
187 inline math::Stats
188 opStatistics(const IterT& iter, const OperatorT& op = OperatorT(), bool threaded = true);
189
190 /// @brief Same as opStatistics except it returns a math::Extrema vs a math::Stats
191 template<typename OperatorT, typename IterT>
192 inline math::Extrema
193 opExtrema(const IterT& iter, const OperatorT& op = OperatorT(), bool threaded = true);
194
195 ////////////////////////////////////////
196
197
198 namespace stats_internal {
199
200 /// @todo This traits class is needed because tree::TreeValueIteratorBase uses
201 /// the name ValueT for the type of the value to which the iterator points,
202 /// whereas node-level iterators use the name ValueType.
203 template<typename IterT, typename AuxT = void>
204 struct IterTraits {
205  using ValueType = typename IterT::ValueType;
206 };
207
208 template<typename TreeT, typename ValueIterT>
209 struct IterTraits<tree::TreeValueIteratorBase<TreeT, ValueIterT> > {
211 };
212
213
214 // Helper class to compute a scalar value from either a scalar or a vector value
215 // (the latter by computing the vector's magnitude)
216 template<typename T, bool IsVector> struct GetValImpl;
217
218 template<typename T>
219 struct GetValImpl<T, /*IsVector=*/false> {
220  static inline double get(const T& val) { return double(val); }
221 };
222
223 template<typename T>
224 struct GetValImpl<T, /*IsVector=*/true> {
225  static inline double get(const T& val) { return val.length(); }
226 };
227
228
229 // Helper class to compute a scalar value from a tree or node iterator
230 // that points to a value in either a scalar or a vector grid, and to
231 // add that value to a math::Stats object.
232 template<typename IterT, typename StatsT>
233 struct GetVal
234 {
237
238  inline void operator()(const IterT& iter, StatsT& stats) const {
241  }
242 };
243
244 // Helper class to accumulate scalar voxel values or vector voxel magnitudes
245 // into a math::Stats object
246 template<typename IterT, typename ValueOp, typename StatsT>
247 struct StatsOp
248 {
249  StatsOp(const ValueOp& op): getValue(op) {}
250
251  // Accumulate voxel and tile values into this functor's Stats object.
252  inline void operator()(const IterT& iter) { getValue(iter, stats); }
253
254  // Accumulate another functor's Stats object into this functor's.
255  inline void join(StatsOp& other) { stats.add(other.stats); }
256
257  StatsT stats;
258  ValueOp getValue;
259 };
260
261
262 // Helper class to accumulate scalar voxel values or vector voxel magnitudes
263 // into a math::Histogram object
264 template<typename IterT, typename ValueOp>
265 struct HistOp
266 {
267  HistOp(const ValueOp& op, double vmin, double vmax, size_t bins):
268  hist(vmin, vmax, bins), getValue(op)
269  {}
270
271  // Accumulate voxel and tile values into this functor's Histogram object.
272  inline void operator()(const IterT& iter) { getValue(iter, hist); }
273
274  // Accumulate another functor's Histogram object into this functor's.
275  inline void join(HistOp& other) { hist.add(other.hist); }
276
278  ValueOp getValue;
279 };
280
281
282 // Helper class to apply an operator such as math::Gradient or math::Laplacian
283 // to voxels and accumulate the scalar results or the magnitudes of vector results
284 // into a math::Stats object
285 template<typename IterT, typename OpT, typename StatsT>
286 struct MathOp
287 {
288  using TreeT = typename IterT::TreeT;
289  using ValueT = typename TreeT::ValueType;
291
292  // Each thread gets its own accessor and its own copy of the operator.
294  OpT mOp;
295  StatsT mStats;
296
297  template<typename TreeT>
298  static inline TreeT* THROW_IF_NULL(TreeT* ptr) {
299  if (ptr == nullptr) OPENVDB_THROW(ValueError, "iterator references a null tree");
300  return ptr;
301  }
302
303  MathOp(const IterT& iter, const OpT& op):
304  mAcc(*THROW_IF_NULL(iter.getTree())), mOp(op)
305  {}
306
307  // Accumulate voxel and tile values into this functor's Stats object.
308  void operator()(const IterT& it)
309  {
310  if (it.isVoxelValue()) {
311  // Add the magnitude of the gradient at a single voxel.
313  } else {
314  // Iterate over the voxels enclosed by a tile and add the results
315  // of applying the operator at each voxel.
316  /// @todo This could be specialized to be done more efficiently for some operators.
317  /// For example, all voxels in the interior of a tile (i.e., not on the borders)
318  /// have gradient zero, so there's no need to apply the operator to every voxel.
319  CoordBBox bbox = it.getBoundingBox();
320  Coord xyz;
321  int &x = xyz.x(), &y = xyz.y(), &z = xyz.z();
322  for (x = bbox.min().x(); x <= bbox.max().x(); ++x) {
323  for (y = bbox.min().y(); y <= bbox.max().y(); ++y) {
324  for (z = bbox.min().z(); z <= bbox.max().z(); ++z) {
326  }
327  }
328  }
329  }
330  }
331
332  // Accumulate another functor's Stats object into this functor's.
333  inline void join(MathOp& other) { mStats.add(other.mStats); }
334 }; // struct MathOp
335
336 } // namespace stats_internal
337
338
339 template<typename IterT>
340 inline math::Histogram
341 histogram(const IterT& iter, double vmin, double vmax, size_t numBins, bool threaded)
342 {
344  ValueOp valOp;
345  stats_internal::HistOp<IterT, ValueOp> op(valOp, vmin, vmax, numBins);
347  return op.hist;
348 }
349
350 template<typename IterT>
351 inline math::Extrema
352 extrema(const IterT& iter, bool threaded)
353 {
356 }
357
358 template<typename IterT>
359 inline math::Stats
360 statistics(const IterT& iter, bool threaded)
361 {
364 }
365
366 template<typename IterT, typename ValueOp>
367 inline math::Extrema
368 extrema(const IterT& iter, const ValueOp& valOp, bool threaded)
369 {
372  return op.stats;
373 }
374
375 template<typename IterT, typename ValueOp>
376 inline math::Stats
377 statistics(const IterT& iter, const ValueOp& valOp, bool threaded)
378 {
381  return op.stats;
382 }
383
384
385 template<typename OperatorT, typename IterT>
386 inline math::Extrema
387 opExtrema(const IterT& iter, const OperatorT& op, bool threaded)
388 {
391  return func.mStats;
392 }
393
394 template<typename OperatorT, typename IterT>
395 inline math::Stats
396 opStatistics(const IterT& iter, const OperatorT& op, bool threaded)
397 {
400  return func.mStats;
401 }
402
403 } // namespace tools
404 } // namespace OPENVDB_VERSION_NAME
405 } // namespace openvdb
406
407 #endif // OPENVDB_TOOLS_STATISTICS_HAS_BEEN_INCLUDED
math::Stats opStatistics(const IterT &iter, const OperatorT &op=OperatorT(), bool threaded=true)
Iterate over a grid and compute statistics (mean, variance, etc.) of the values produced by applying ...
Definition: Statistics.h:396
math::Stats statistics(const IterT &iter, bool threaded=true)
Iterate over a scalar grid and compute statistics (mean, variance, etc.) of the values of the voxels ...
Definition: Statistics.h:360
GLuint const GLfloat * val
Definition: glew.h:2794
typename tree::ValueAccessor< const TreeT > ConstAccessor
Definition: Statistics.h:290
#define OPENVDB_USE_VERSION_NAMESPACE
Definition: version.h:166
HistOp(const ValueOp &op, double vmin, double vmax, size_t bins)
Definition: Statistics.h:267
GLdouble GLdouble z
Definition: glew.h:1559
Classes to compute statistics and histograms.
GLint GLint GLint GLint GLint x
Definition: glew.h:1252
GLint GLint GLint GLint GLint GLint y
Definition: glew.h:1252
typename IterTraits< IterT >::ValueType ValueT
Definition: Statistics.h:235
This class computes statistics (minimum value, maximum value, mean, variance and standard deviation) ...
Definition: Stats.h:182
typename ValueIterT::NonConstValueType ValueT
Definition: TreeIterator.h:622
void operator()(const IterT &iter, StatsT &stats) const
Definition: Statistics.h:238
This class computes a histogram, with a fixed interval width, of a population of floating-point value...
Definition: Stats.h:279
void accumulate(const IterT &iter, XformOp &op, bool threaded=true)
GLenum func
Definition: glcorearb.h:782
const void * ptr(const T *p)
Definition: format.h:3292
math::Extrema opExtrema(const IterT &iter, const OperatorT &op=OperatorT(), bool threaded=true)
Same as opStatistics except it returns a math::Extrema vs a math::Stats.
Definition: Statistics.h:387
math::Histogram histogram(const IterT &iter, double minVal, double maxVal, size_t numBins=10, bool threaded=true)
Iterate over a scalar grid and compute a histogram of the values of the voxels that are visited...
Definition: Statistics.h:341
#define OPENVDB_VERSION_NAME
The version namespace name for this library version.
Definition: version.h:112