MRPT  1.9.9
ops_containers.h
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | http://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
6  | See: http://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See details in http://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 #ifndef mrpt_math_container_ops_H
10 #define mrpt_math_container_ops_H
11 
12 #include <mrpt/math/types_math.h>
13 
14 #include <mrpt/math/lightweight_geom_data.h> // forward declarations
15 
16 #include <functional>
17 #include <algorithm>
18 #include <cmath>
19 
20 /** \addtogroup container_ops_grp Vector and matrices mathematical operations
21  * and other utilities
22  * \ingroup mrpt_math_grp
23  * @{ */
24 
25 /** \file ops_containers.h
26  * This file implements several operations that operate element-wise on
27  * individual or pairs of containers.
28  * Containers here means any of: mrpt::math::CVectorTemplace,
29  * mrpt::math::CArray, mrpt::math::CMatrixFixedNumeric,
30  * mrpt::math::CMatrixTemplate.
31  *
32  * In general, any container having a type "mrpt_autotype" self-referencing to
33  * the type itself, and a dummy struct mrpt_container<>
34  * which is only used as a way to force the compiler to assure that BOTH
35  * containers are valid ones in binary operators.
36  * This restrictions
37  * have been designed as a way to provide "polymorphism" at a template level,
38  * so the "+,-,..." operators do not
39  * generate ambiguities for ANY type, and limiting them to MRPT containers.
40  *
41  * In some cases, the containers provide specializations of some operations,
42  * for increased performance.
43  */
44 
45 #include <algorithm>
46 #include <numeric>
47 #include <functional>
48 
49 #include <mrpt/math/CHistogram.h> // Used in ::histogram()
50 
51 #include "ops_vectors.h"
52 
53 namespace mrpt::math
54 {
55 /** Computes the normalized or normal histogram of a sequence of numbers given
56  * the number of bins and the limits.
57  * In any case this is a "linear" histogram, i.e. for matrices, all the
58  * elements are taken as if they were a plain sequence, not taking into account
59  * they were in columns or rows.
60  * If desired, out_bin_centers can be set to receive the bins centers.
61  */
62 template <class CONTAINER>
63 std::vector<double> histogram(
64  const CONTAINER& v, double limit_min, double limit_max, size_t number_bins,
65  bool do_normalization = false,
66  std::vector<double>* out_bin_centers = nullptr)
67 {
68  mrpt::math::CHistogram H(limit_min, limit_max, number_bins);
69  std::vector<double> ret(number_bins);
70  std::vector<double> dummy_ret_bins;
71  H.add(v);
72  if (do_normalization)
74  out_bin_centers ? *out_bin_centers : dummy_ret_bins, ret);
75  else
76  H.getHistogram(
77  out_bin_centers ? *out_bin_centers : dummy_ret_bins, ret);
78  return ret;
79 }
80 
81 template <class EIGEN_CONTAINER>
82 void resizeLike(EIGEN_CONTAINER& trg, const EIGEN_CONTAINER& src)
83 {
84  trg.resizeLike(src);
85 }
86 template <typename T>
87 void resizeLike(std::vector<T>& trg, const std::vector<T>& src)
88 {
89  trg.resize(src.size());
90 }
91 
92 /** Computes the cumulative sum of all the elements, saving the result in
93  * another container.
94  * This works for both matrices (even mixing their types) and vectores/arrays
95  * (even mixing types),
96  * and even to store the cumsum of any matrix into any vector/array, but not
97  * in opposite direction.
98  * \sa sum */
99 template <class CONTAINER1, class CONTAINER2, typename VALUE>
100 inline void cumsum_tmpl(const CONTAINER1& in_data, CONTAINER2& out_cumsum)
101 {
102  resizeLike(out_cumsum, in_data);
103  VALUE last = 0;
104  const size_t N = in_data.size();
105  for (size_t i = 0; i < N; i++) last = out_cumsum[i] = last + in_data[i];
106 }
107 
108 template <class CONTAINER1, class CONTAINER2>
109 inline void cumsum(const CONTAINER1& in_data, CONTAINER2& out_cumsum)
110 {
111  cumsum_tmpl<CONTAINER1, CONTAINER2,
113  in_data, out_cumsum);
114 }
115 
116 /** Computes the cumulative sum of all the elements
117  * \sa sum */
118 template <class CONTAINER>
119 inline CONTAINER cumsum(const CONTAINER& in_data)
120 {
121  CONTAINER ret;
122  cumsum(in_data, ret);
123  return ret;
124 }
125 
126 template <class CONTAINER>
127 inline typename CONTAINER::Scalar norm_inf(const CONTAINER& v)
128 {
129  return v.norm_inf();
130 }
131 template <class CONTAINER>
132 inline typename CONTAINER::Scalar norm(const CONTAINER& v)
133 {
134  return v.norm();
135 }
136 template <class CONTAINER>
137 inline typename CONTAINER::Scalar maximum(const CONTAINER& v)
138 {
139  return v.maxCoeff();
140 }
141 template <class CONTAINER>
142 inline typename CONTAINER::Scalar minimum(const CONTAINER& v)
143 {
144  return v.minimum();
145 }
146 
147 template <typename T>
148 inline T maximum(const std::vector<T>& v)
149 {
150  ASSERT_(!v.empty());
151  T m = v[0];
152  for (size_t i = 0; i < v.size(); i++) mrpt::keep_max(m, v[i]);
153  return m;
154 }
155 template <typename T>
156 inline T minimum(const std::vector<T>& v)
157 {
158  ASSERT_(!v.empty());
159  T m = v[0];
160  for (size_t i = 0; i < v.size(); i++) mrpt::keep_min(m, v[i]);
161  return m;
162 }
163 
164 /** \name Generic container element-wise operations - Miscelaneous
165  * @{
166  */
167 
168 /** Accumulate the squared-norm of a vector/array/matrix into "total" (this
169  * function is compatible with std::accumulate). */
170 template <class CONTAINER, typename VALUE>
171 VALUE squareNorm_accum(const VALUE total, const CONTAINER& v)
172 {
173  return total + v.squaredNorm();
174 }
175 
176 /** Compute the square norm of anything implementing [].
177  \sa norm */
178 template <size_t N, class T, class U>
179 inline T squareNorm(const U& v)
180 {
181  T res = 0;
182  for (size_t i = 0; i < N; i++) res += square(v[i]);
183  return res;
184 }
185 
186 /** v1*v2: The dot product of two containers (vectors/arrays/matrices) */
187 template <class CONTAINER1, class CONTAINER2>
189  const CONTAINER1& v1, const CONTAINER1& v2)
190 {
191  return v1.dot(v2);
192 }
193 
194 /** v1*v2: The dot product of any two objects supporting [] */
195 template <size_t N, class T, class U, class V>
196 inline T dotProduct(const U& v1, const V& v2)
197 {
198  T res = 0;
199  for (size_t i = 0; i < N; i++) res += v1[i] * v2[i];
200  return res;
201 }
202 
203 /** Computes the sum of all the elements.
204  * \note If used with containers of integer types (uint8_t, int, etc...) this
205  could overflow. In those cases, use sumRetType the second argument RET to
206  specify a larger type to hold the sum.
207  \sa cumsum */
208 template <class CONTAINER>
209 inline typename CONTAINER::Scalar sum(const CONTAINER& v)
210 {
211  return v.sum();
212 }
213 
214 /// \overload
215 template <typename T>
216 inline T sum(const std::vector<T>& v)
217 {
218  return std::accumulate(v.begin(), v.end(), T(0));
219 }
220 
221 /** Computes the sum of all the elements, with a custom return type.
222  \sa sum, cumsum */
223 template <class CONTAINER, typename RET>
224 inline RET sumRetType(const CONTAINER& v)
225 {
226  return v.template sumRetType<RET>();
227 }
228 
229 /** Computes the mean value of a vector \return The mean, as a double number.
230  * \sa math::stddev,math::meanAndStd */
231 template <class CONTAINER>
232 inline double mean(const CONTAINER& v)
233 {
234  if (v.empty())
235  return 0;
236  else
237  return sum(v) / static_cast<double>(v.size());
238 }
239 
240 /** Return the maximum and minimum values of a std::vector */
241 template <typename T>
242 inline void minimum_maximum(const std::vector<T>& V, T& curMin, T& curMax)
243 {
244  ASSERT_(V.size() != 0);
245  const size_t N = V.size();
246  curMin = curMax = V[0];
247  for (size_t i = 1; i < N; i++)
248  {
249  mrpt::keep_min(curMin, V[i]);
250  mrpt::keep_max(curMax, V[i]);
251  }
252 }
253 
254 /** Return the maximum and minimum values of a Eigen-based vector or matrix */
255 template <class Derived>
256 inline void minimum_maximum(
258  typename Eigen::MatrixBase<Derived>::Scalar& curMin,
259  typename Eigen::MatrixBase<Derived>::Scalar& curMax)
260 {
261  V.minimum_maximum(curMin, curMax);
262 }
263 
264 /** Counts the number of elements that appear in both STL-like containers
265  * (comparison through the == operator)
266  * It is assumed that no repeated elements appear within each of the
267  * containers. */
268 template <class CONTAINER1, class CONTAINER2>
269 size_t countCommonElements(const CONTAINER1& a, const CONTAINER2& b)
270 {
271  size_t ret = 0;
272  for (typename CONTAINER1::const_iterator it1 = a.begin(); it1 != a.end();
273  ++it1)
274  for (typename CONTAINER2::const_iterator it2 = b.begin();
275  it2 != b.end(); ++it2)
276  if ((*it1) == (*it2)) ret++;
277  return ret;
278 }
279 
280 /** Adjusts the range of all the elements such as the minimum and maximum values
281  * being those supplied by the user. */
282 template <class CONTAINER>
284  CONTAINER& m, const typename CONTAINER::Scalar minVal,
285  const typename CONTAINER::Scalar maxVal)
286 {
287  if (size_t(m.size()) == 0) return;
288  typename CONTAINER::Scalar curMin, curMax;
289  minimum_maximum(m, curMin, curMax);
290  const typename CONTAINER::Scalar curRan = curMax - curMin;
291  m -= (curMin + minVal);
292  if (curRan != 0) m *= (maxVal - minVal) / curRan;
293 }
294 
295 /** Computes the standard deviation of a vector
296  * \param v The set of data
297  * \param out_mean The output for the estimated mean
298  * \param out_std The output for the estimated standard deviation
299  * \param unbiased If set to true or false the std is normalized by "N-1" or
300  * "N", respectively.
301  * \sa math::mean,math::stddev
302  */
303 template <class VECTORLIKE>
305  const VECTORLIKE& v, double& out_mean, double& out_std,
306  bool unbiased = true)
307 {
308  if (v.size() < 2)
309  {
310  out_std = 0;
311  out_mean = (v.size() == 1) ? *v.begin() : 0;
312  }
313  else
314  {
315  // Compute the mean:
316  const size_t N = v.size();
317  out_mean = mrpt::math::sum(v) / static_cast<double>(N);
318  // Compute the std:
319  double vector_std = 0;
320  for (size_t i = 0; i < N; i++)
321  vector_std += mrpt::square(v[i] - out_mean);
322  out_std =
323  std::sqrt(vector_std / static_cast<double>(N - (unbiased ? 1 : 0)));
324  }
325 }
326 
327 /** Computes the standard deviation of a vector
328  * \param v The set of data
329  * \param unbiased If set to true or false the std is normalized by "N-1" or
330  * "N", respectively.
331  * \sa math::mean,math::meanAndStd
332  */
333 template <class VECTORLIKE>
334 inline double stddev(const VECTORLIKE& v, bool unbiased = true)
335 {
336  double m, s;
337  meanAndStd(v, m, s, unbiased);
338  return s;
339 }
340 
341 /** Computes the mean vector and covariance from a list of values given as a
342  * vector of vectors, where each row is a sample.
343  * \param v The set of data, as a vector of N vectors of M elements.
344  * \param out_mean The output M-vector for the estimated mean.
345  * \param out_cov The output MxM matrix for the estimated covariance matrix.
346  * \sa mrpt::math::meanAndCovMat, math::mean,math::stddev, math::cov
347  */
348 template <class VECTOR_OF_VECTOR, class VECTORLIKE, class MATRIXLIKE>
350  const VECTOR_OF_VECTOR& v, VECTORLIKE& out_mean, MATRIXLIKE& out_cov)
351 {
352  const size_t N = v.size();
353  ASSERTMSG_(N > 0, "The input vector contains no elements");
354  const double N_inv = 1.0 / N;
355 
356  const size_t M = v[0].size();
357  ASSERTMSG_(M > 0, "The input vector contains rows of length 0");
358 
359  // First: Compute the mean
360  out_mean.assign(M, 0);
361  for (size_t i = 0; i < N; i++)
362  for (size_t j = 0; j < M; j++) out_mean[j] += v[i][j];
363 
364  for (size_t j = 0; j < M; j++)
365  out_mean[j] *= N_inv;
366 
367  // Second: Compute the covariance
368  // Save only the above-diagonal part, then after averaging
369  // duplicate that part to the other half.
370  out_cov.zeros(M, M);
371  for (size_t i = 0; i < N; i++)
372  {
373  for (size_t j = 0; j < M; j++)
374  out_cov.get_unsafe(j, j) += square(v[i][j] - out_mean[j]);
375 
376  for (size_t j = 0; j < M; j++)
377  for (size_t k = j + 1; k < M; k++)
378  out_cov.get_unsafe(j, k) +=
379  (v[i][j] - out_mean[j]) * (v[i][k] - out_mean[k]);
380  }
381  for (size_t j = 0; j < M; j++)
382  for (size_t k = j + 1; k < M; k++)
383  out_cov.get_unsafe(k, j) = out_cov.get_unsafe(j, k);
384  out_cov *= N_inv;
385 }
386 
387 /** Computes the covariance matrix from a list of values given as a vector of
388  * vectors, where each row is a sample.
389  * \param v The set of data, as a vector of N vectors of M elements.
390  * \param out_cov The output MxM matrix for the estimated covariance matrix.
391  * \tparam RETURN_MATRIX The type of the returned matrix, e.g. Eigen::MatrixXd
392  * \sa math::mean,math::stddev, math::cov, meanAndCovVec
393  */
394 template <class VECTOR_OF_VECTOR, class RETURN_MATRIX>
395 inline RETURN_MATRIX covVector(const VECTOR_OF_VECTOR& v)
396 {
397  std::vector<double> m;
398  RETURN_MATRIX C;
399  meanAndCovVec(v, m, C);
400  return C;
401 }
402 
403 /** Normalised Cross Correlation between two vector patches
404  * The Matlab code for this is
405  * a = a - mean2(a);
406  * b = b - mean2(b);
407  * r = sum(sum(a.*b))/sqrt(sum(sum(a.*a))*sum(sum(b.*b)));
408  */
409 template <class CONT1, class CONT2>
410 double ncc_vector(const CONT1& patch1, const CONT2& patch2)
411 {
412  ASSERT_(patch1.size() == patch2.size());
413 
414  double numerator = 0, sum_a = 0, sum_b = 0, result, a_mean, b_mean;
415  a_mean = patch1.mean();
416  b_mean = patch2.mean();
417 
418  const size_t N = patch1.size();
419  for (size_t i = 0; i < N; ++i)
420  {
421  numerator += (patch1[i] - a_mean) * (patch2[i] - b_mean);
422  sum_a += mrpt::square(patch1[i] - a_mean);
423  sum_b += mrpt::square(patch2[i] - b_mean);
424  }
425  ASSERTMSG_(sum_a * sum_b != 0, "Divide by zero when normalizing.");
426  result = numerator / std::sqrt(sum_a * sum_b);
427  return result;
428 }
429 
430 /** @} Misc ops */
431 
432 }
433 /** @} */ // end of grouping
434 
435 #endif
436 
437 
void cumsum_tmpl(const CONTAINER1 &in_data, CONTAINER2 &out_cumsum)
Computes the cumulative sum of all the elements, saving the result in another container.
This class provides an easy way of computing histograms for unidimensional real valued variables...
Definition: CHistogram.h:33
double Scalar
Definition: KmUtils.h:44
size_t countCommonElements(const CONTAINER1 &a, const CONTAINER2 &b)
Counts the number of elements that appear in both STL-like containers (comparison through the == oper...
double stddev(const VECTORLIKE &v, bool unbiased=true)
Computes the standard deviation of a vector.
T squareNorm(const U &v)
Compute the square norm of anything implementing [].
void keep_min(T &var, const K test_val)
If the second argument is below the first one, set the first argument to this lower value...
void resizeLike(EIGEN_CONTAINER &trg, const EIGEN_CONTAINER &src)
GLdouble s
Definition: glext.h:3676
GLuint src
Definition: glext.h:7278
T square(const T x)
Inline function for the square of a number.
CONTAINER::Scalar minimum(const CONTAINER &v)
#define ASSERT_(f)
Defines an assertion mechanism.
Definition: exceptions.h:113
This base provides a set of functions for maths stuff.
void keep_max(T &var, const K test_val)
If the second argument is above the first one, set the first argument to this higher value...
void add(const double x)
Add an element to the histogram.
Definition: CHistogram.cpp:42
CONTAINER::Scalar sum(const CONTAINER &v)
Computes the sum of all the elements.
GLubyte GLubyte b
Definition: glext.h:6279
#define ASSERTMSG_(f, __ERROR_MSG)
Defines an assertion mechanism.
Definition: exceptions.h:101
VALUE squareNorm_accum(const VALUE total, const CONTAINER &v)
Accumulate the squared-norm of a vector/array/matrix into "total" (this function is compatible with s...
CONTAINER::Scalar maximum(const CONTAINER &v)
void getHistogram(std::vector< double > &x, std::vector< double > &hits) const
Returns the list of bin centers & hit counts.
Definition: CHistogram.cpp:77
void minimum_maximum(const std::vector< T > &V, T &curMin, T &curMax)
Return the maximum and minimum values of a std::vector.
void cumsum(const CONTAINER1 &in_data, CONTAINER2 &out_cumsum)
CONTAINER::Scalar norm_inf(const CONTAINER &v)
const GLdouble * v
Definition: glext.h:3678
void meanAndStd(const VECTORLIKE &v, double &out_mean, double &out_std, bool unbiased=true)
Computes the standard deviation of a vector.
double ncc_vector(const CONT1 &patch1, const CONT2 &patch2)
Normalised Cross Correlation between two vector patches The Matlab code for this is a = a - mean2(a);...
GLfloat GLfloat v1
Definition: glext.h:4105
typename CONTAINER::value_type element_t
Definition: math_frwds.h:92
RETURN_MATRIX covVector(const VECTOR_OF_VECTOR &v)
Computes the covariance matrix from a list of values given as a vector of vectors, where each row is a sample.
RET sumRetType(const CONTAINER &v)
Computes the sum of all the elements, with a custom return type.
CONTAINER1::Scalar dotProduct(const CONTAINER1 &v1, const CONTAINER1 &v2)
v1*v2: The dot product of two containers (vectors/arrays/matrices)
std::vector< double > histogram(const CONTAINER &v, double limit_min, double limit_max, size_t number_bins, bool do_normalization=false, std::vector< double > *out_bin_centers=nullptr)
Computes the normalized or normal histogram of a sequence of numbers given the number of bins and the...
double mean(const CONTAINER &v)
Computes the mean value of a vector.
void meanAndCovVec(const VECTOR_OF_VECTOR &v, VECTORLIKE &out_mean, MATRIXLIKE &out_cov)
Computes the mean vector and covariance from a list of values given as a vector of vectors...
GLfloat GLfloat GLfloat v2
Definition: glext.h:4107
GLuint res
Definition: glext.h:7268
void adjustRange(CONTAINER &m, const typename CONTAINER::Scalar minVal, const typename CONTAINER::Scalar maxVal)
Adjusts the range of all the elements such as the minimum and maximum values being those supplied by ...
GLubyte GLubyte GLubyte a
Definition: glext.h:6279
const Scalar * const_iterator
Definition: eigen_plugins.h:27
void getHistogramNormalized(std::vector< double > &x, std::vector< double > &hits) const
Returns the list of bin centers & hit counts, normalized such as the integral of the histogram...
Definition: CHistogram.cpp:86
CONTAINER::Scalar norm(const CONTAINER &v)



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 7d5e6d718 Fri Aug 24 01:51:28 2018 +0200 at lun nov 2 08:35:50 CET 2020