Main MRPT website > C++ reference for MRPT 1.9.9
base/include/mrpt/math/utils.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-2017, 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_H
10 #define MRPT_MATH_H
11 
12 #include <mrpt/utils/utils_defs.h>
13 #include <cstdarg>
14 #include <cstdio>
15 #include <mrpt/math/eigen_frwds.h>
16 #include <map>
17 
18 namespace mrpt
19 {
20 /** This base provides a set of functions for maths stuff.
21  * \ingroup mrpt_base_grp
22  */
23 namespace math
24 {
25 /**\brief Compare 2 floats and determine whether they are equal
26  * \return True if equal, false otherwise
27  * \param a Fist num
28  * \param b Second num
29  * \param epsilon Difference below which a, b are considered equal
30  */
31 template <class T1, class T2>
32 bool approximatelyEqual(T1 a, T1 b, T2 epsilon)
33 {
34  return fabs(a - b) <= ((fabs(a) > fabs(b) ? fabs(b) : fabs(a)) * epsilon);
35 }
36 
37 /**\brief Compare 2 floats and determine whether they are equal
38  * \return True if equal, false otherwise
39  * \param a Fist num
40  * \param b Second num
41  */
42 template <class T>
44 {
45  return approximatelyEqual(a, b, std::numeric_limits<T>::epsilon());
46 }
47 
48 /**\brief Absolute difference between two numbers.
49  *
50  */
51 template <class T>
52 T absDiff(const T& lhs, const T& rhs)
53 {
54  return lhs > rhs ? lhs - rhs : rhs - lhs;
55 }
56 
57 /** \addtogroup container_ops_grp
58  * @{ */
59 
60 /** Loads one row of a text file as a numerical std::vector.
61  * \return false on EOF or invalid format.
62  * The body of the function is implemented in MATH.cpp
63  */
64 bool loadVector(utils::CFileStream& f, std::vector<int>& d);
65 
66 /** Loads one row of a text file as a numerical std::vector.
67  * \return false on EOF or invalid format.
68  * The body of the function is implemented in MATH.cpp
69  */
70 bool loadVector(utils::CFileStream& f, std::vector<double>& d);
71 
72 void medianFilter(
73  const std::vector<double>& inV, std::vector<double>& outV,
74  const int& winSize, const int& numberOfSigmas = 2);
75 
76 /** Generates an equidistant sequence of numbers given the first one, the last
77  one and the desired number of points.
78  \sa sequence */
79 template <typename T, typename VECTOR>
80 void linspace(T first, T last, size_t count, VECTOR& out_vector)
81 {
82  if (count < 2)
83  {
84  out_vector.assign(count, last);
85  return;
86  }
87  else
88  {
89  out_vector.resize(count);
90  const T incr = (last - first) / T(count - 1);
91  T c = first;
92  for (size_t i = 0; i < count; i++, c += incr) out_vector[i] = c;
93  }
94 }
95 
96 /** Generates a sequence of values [first,first+STEP,first+2*STEP,...] \sa
97  * linspace, sequence */
98 template <class T, T STEP>
99 inline std::vector<T> sequenceStdVec(T first, size_t length)
100 {
101  std::vector<T> ret(length);
102  if (!length) return ret;
103  size_t i = 0;
104  while (length--)
105  {
106  ret[i++] = first;
107  first += STEP;
108  }
109  return ret;
110 }
111 
112 /** Normalize a vector, such as its norm is the unity.
113  * If the vector has a null norm, the output is a null vector.
114  */
115 template <class VEC1, class VEC2>
116 void normalize(const VEC1& v, VEC2& out_v)
117 {
118  typename VEC1::Scalar total = 0;
119  const size_t N = v.size();
120  for (size_t i = 0; i < N; i++) total += square(v[i]);
121  total = std::sqrt(total);
122  if (total)
123  {
124  out_v = v * (1.0 / total);
125  }
126  else
127  out_v.assign(v.size(), 0);
128 }
129 
130 /** Extract a column from a vector of vectors, and store it in another vector.
131  * - Input data can be: std::vector<mrpt::math::CVectorDouble>,
132  * std::deque<std::list<double> >, std::list<CArrayDouble<5> >, etc. etc.
133  * - Output is the sequence: data[0][idx],data[1][idx],data[2][idx], etc..
134  *
135  * For the sake of generality, this function does NOT check the limits in
136  * the number of column, unless it's implemented in the [] operator of each of
137  * the "rows".
138  */
139 template <class VECTOR_OF_VECTORS, class VECTORLIKE>
141  const size_t colIndex, const VECTOR_OF_VECTORS& data,
142  VECTORLIKE& out_column)
143 {
144  const size_t N = data.size();
145  out_column.resize(N);
146  for (size_t i = 0; i < N; i++) out_column[i] = data[i][colIndex];
147 }
148 
149 /** Computes the factorial of an integer number and returns it as a 64-bit
150  * integer number.
151  */
152 uint64_t factorial64(unsigned int n);
153 
154 /** Computes the factorial of an integer number and returns it as a double value
155  * (internally it uses logarithms for avoiding overflow).
156  */
157 double factorial(unsigned int n);
158 
159 /** Round up to the nearest power of two of a given number
160  */
161 template <class T>
163 {
164  T n = 1;
165  while (n < val)
166  {
167  n <<= 1;
168  if (n <= 1) THROW_EXCEPTION("Overflow!");
169  }
170  return n;
171 }
172 
173 /** Generates a string with the MATLAB commands required to plot an confidence
174  * interval (ellipse) for a 2D Gaussian ('float' version)..
175  * \param cov22 The 2x2 covariance matrix
176  * \param mean The 2-length vector with the mean
177  * \param stdCount How many "quantiles" to get into the area of the ellipse:
178  * 2: 95%, 3:99.97%,...
179  * \param style A matlab style string, for colors, line styles,...
180  * \param nEllipsePoints The number of points in the ellipse to generate
181  * \ingroup stats_grp
182  */
184  const CMatrixFloat& cov22, const CVectorFloat& mean, const float& stdCount,
185  const std::string& style = std::string("b"),
186  const size_t& nEllipsePoints = 30);
187 
188 /** Generates a string with the MATLAB commands required to plot an confidence
189  * interval (ellipse) for a 2D Gaussian ('double' version).
190  * \param cov22 The 2x2 covariance matrix
191  * \param mean The 2-length vector with the mean
192  * \param stdCount How many "quantiles" to get into the area of the ellipse:
193  * 2: 95%, 3:99.97%,...
194  * \param style A matlab style string, for colors, line styles,...
195  * \param nEllipsePoints The number of points in the ellipse to generate
196  * \ingroup stats_grp
197  */
199  const CMatrixDouble& cov22, const CVectorDouble& mean,
200  const float& stdCount, const std::string& style = std::string("b"),
201  const size_t& nEllipsePoints = 30);
202 
203 /** Assignment operator for initializing a std::vector from a C array (The
204  *vector will be automatically set to the correct size).
205  * \code
206  * CVectorDouble v;
207  * const double numbers[] = { 1,2,3,5,6,7,8,9,10 };
208  * loadVector( v, numbers );
209  * \endcode
210  * \note This operator performs the appropiate type castings, if required.
211  */
212 template <typename EIGEN_VECTOR, typename At, size_t N>
213 EIGEN_VECTOR& loadVector(EIGEN_VECTOR& v, At (&theArray)[N])
214 {
216  v.derived().resize(N);
217  for (size_t i = 0; i < N; i++)
218  (v.derived())[i] =
219  static_cast<typename EIGEN_VECTOR::Scalar>(theArray[i]);
220  return v;
221 }
222 //! \overload
223 template <typename T, typename At, size_t N>
224 std::vector<T>& loadVector(std::vector<T>& v, At (&theArray)[N])
225 {
227  v.resize(N);
228  for (size_t i = 0; i < N; i++) v[i] = static_cast<T>(theArray[i]);
229  return v;
230 }
231 
232 /** @} */ // end of grouping container_ops_grp
233 
234 /** \defgroup mrpt_math_io Custom I/O for math containers
235  * \ingroup mrpt_base_grp */
236 /** \addtogroup mrpt_math_io
237  * @{ */
238 
239 /** Saves to a plain-text file the nonzero entries of a Eigen sparse matrix,
240  * represented as a vector of triplets.
241  * Output format is one line per entry with the format: "i j val", i:row,
242  * j:col, val:value.
243  * \tparam TRIPLET should be Eigen::Triplet<T>
244  */
245 template <class TRIPLET>
247  const std::string& sFile, std::vector<TRIPLET>& tri)
248 {
249 #if defined(_MSC_VER) && \
250  (_MSC_VER >= 1400) // Use a secure version in Visual Studio 2005+
251  FILE* f;
252  if (0 != ::fopen_s(&f, sFile.c_str(), "wt")) f = nullptr;
253 #else
254  FILE* f = ::fopen(sFile.c_str(), "wt");
255 #endif
256 
257  if (!f) return false;
258 
259  for (size_t i = 0; i < tri.size(); i++)
260  fprintf(
261  f, "%u %u %e\n", 1 + tri[i].row(), 1 + tri[i].col(),
262  tri[i].value());
263 
264  fclose(f);
265  return true;
266 }
267 
268 /** @} */ // End of mrpt_math_io
269 
270 } // End of MATH namespace
271 
272 } // End of namespace
273 
274 #endif
double Scalar
Definition: KmUtils.h:44
This CStream derived class allow using a file as a read/write binary stream, creating it if the file ...
Definition: CFileStream.h:42
GLenum GLsizei n
Definition: glext.h:5074
GLenum GLenum GLvoid * row
Definition: glext.h:3576
const GLdouble * v
Definition: glext.h:3678
const GLubyte * c
Definition: glext.h:6313
GLsizei GLsizei GLenum GLenum const GLvoid * data
Definition: glext.h:3547
GLuint GLsizei GLsizei * length
Definition: glext.h:4064
GLuint GLuint GLsizei count
Definition: glext.h:3528
GLubyte GLubyte b
Definition: glext.h:6279
GLint * first
Definition: glext.h:3827
GLubyte GLubyte GLubyte a
Definition: glext.h:6279
GLsizei const GLfloat * value
Definition: glext.h:4117
GLsizei const GLchar ** string
Definition: glext.h:4101
bool loadVector(utils::CFileStream &f, std::vector< int > &d)
Loads one row of a text file as a numerical std::vector.
void extractColumnFromVectorOfVectors(const size_t colIndex, const VECTOR_OF_VECTORS &data, VECTORLIKE &out_column)
Extract a column from a vector of vectors, and store it in another vector.
std::vector< T > sequenceStdVec(T first, size_t length)
Generates a sequence of values [first,first+STEP,first+2*STEP,...].
void medianFilter(const std::vector< double > &inV, std::vector< double > &outV, const int &winSize, const int &numberOfSigmas=2)
Definition: math.cpp:1999
void normalize(const VEC1 &v, VEC2 &out_v)
Normalize a vector, such as its norm is the unity.
void linspace(T first, T last, size_t count, VECTOR &out_vector)
Generates an equidistant sequence of numbers given the first one, the last one and the desired number...
double factorial(unsigned int n)
Computes the factorial of an integer number and returns it as a double value (internally it uses loga...
Definition: math.cpp:1024
uint64_t factorial64(unsigned int n)
Computes the factorial of an integer number and returns it as a 64-bit integer number.
Definition: math.cpp:1012
T round2up(T val)
Round up to the nearest power of two of a given number.
bool saveEigenSparseTripletsToFile(const std::string &sFile, std::vector< TRIPLET > &tri)
Saves to a plain-text file the nonzero entries of a Eigen sparse matrix, represented as a vector of t...
int void fclose(FILE *f)
An OS-independent version of fclose.
Definition: os.cpp:272
FILE * fopen(const char *fileName, const char *mode) noexcept
An OS-independent version of fopen.
Definition: os.cpp:254
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
Definition: os.cpp:405
std::string MATLAB_plotCovariance2D(const CMatrixFloat &cov22, const CVectorFloat &mean, const float &stdCount, const std::string &style=std::string("b"), const size_t &nEllipsePoints=30)
Generates a string with the MATLAB commands required to plot an confidence interval (ellipse) for a 2...
Definition: math.cpp:1840
int val
Definition: mrpt_jpeglib.h:955
#define MRPT_COMPILE_TIME_ASSERT(f)
Definition: mrpt_macros.h:315
#define THROW_EXCEPTION(msg)
Definition: mrpt_macros.h:111
double mean(const CONTAINER &v)
Computes the mean value of a vector.
dynamic_vector< float > CVectorFloat
Column vector, like Eigen::MatrixXf, but automatically initialized to zeros since construction.
Definition: eigen_frwds.h:42
dynamic_vector< double > CVectorDouble
Column vector, like Eigen::MatrixXd, but automatically initialized to zeros since construction.
Definition: eigen_frwds.h:44
CMatrixTemplateNumeric< float > CMatrixFloat
Declares a matrix of float numbers (non serializable).
CMatrixTemplateNumeric< double > CMatrixDouble
Declares a matrix of double numbers (non serializable).
bool approximatelyEqual(T1 a, T1 b, T2 epsilon)
Compare 2 floats and determine whether they are equal.
T absDiff(const T &lhs, const T &rhs)
Absolute difference between two numbers.
T square(const T x)
Inline function for the square of a number.
Definition: bits.h:55
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
unsigned __int64 uint64_t
Definition: rptypes.h:50



Page generated by Doxygen 1.9.1 for MRPT 1.9.9 Git: 63ea9d1f1 Thu Nov 23 00:06:53 2017 +0100 at mar 26 may 2026 12:19:29 CEST