MRPT  1.9.9
CPose3DQuatPDFGaussian.cpp
Go to the documentation of this file.
1 /* +------------------------------------------------------------------------+
2  | Mobile Robot Programming Toolkit (MRPT) |
3  | https://www.mrpt.org/ |
4  | |
5  | Copyright (c) 2005-2020, Individual contributors, see AUTHORS file |
6  | See: https://www.mrpt.org/Authors - All rights reserved. |
7  | Released under BSD License. See: https://www.mrpt.org/License |
8  +------------------------------------------------------------------------+ */
9 
10 #include "poses-precomp.h" // Precompiled headers
11 
15 #include <mrpt/poses/CPose3D.h>
17 #include <mrpt/poses/CPose3DQuat.h>
21 #include <mrpt/system/os.h>
22 #include <Eigen/Dense>
23 
24 using namespace mrpt;
25 using namespace mrpt::poses;
26 using namespace mrpt::math;
27 using namespace mrpt::random;
28 using namespace mrpt::system;
29 using namespace std;
30 
32 
34 {
36 }
38 {
40 }
41 
43 
44 /** Default constructor - set all values to zero. */
46 // Un-initialized constructor:
48  TConstructorFlags_Quaternions constructor_dummy_param)
50 {
51  MRPT_UNUSED_PARAM(constructor_dummy_param);
52 }
53 
54 /** Constructor from a default mean value, covariance equals to zero. */
56  : mean(init_Mean), cov()
57 {
58 }
59 
60 /** Constructor with mean and covariance. */
62  const CPose3DQuat& init_Mean, const CMatrixDouble77& init_Cov)
63  : mean(init_Mean), cov(init_Cov)
64 {
65 }
66 
67 /** Constructor from a Gaussian 2D pose PDF (sets to 0 the missing variables).
68  */
71 {
72  this->copyFrom(CPose3DPDFGaussian(o));
73 }
74 
75 /** Constructor from an equivalent Gaussian in Euler angles representation. */
78 {
79  this->copyFrom(o);
80 }
81 
83 
84 uint8_t CPose3DQuatPDFGaussian::serializeGetVersion() const { return 0; }
87 {
88  out << mean;
90 }
92  mrpt::serialization::CArchive& in, uint8_t version)
93 {
94  switch (version)
95  {
96  case 0:
97  {
98  in >> mean;
100  }
101  break;
102  default:
104  };
105 }
106 
108 {
109  if (this == &o) return; // It may be used sometimes
110 
111  // Convert to gaussian pdf:
113 }
114 
116 {
117  CPose3DPDFGaussian aux;
118  aux.copyFrom(o);
119  this->copyFrom(aux);
120 }
121 
123  const CVectorFixedDouble<6>& x, const double& dummy,
125 {
126  MRPT_UNUSED_PARAM(dummy);
127  y[0] = x[0];
128  y[1] = x[1];
129  y[2] = x[2];
130 
131  CPose3D p(0, 0, 0, x[3], x[4], x[5]);
133  p.getAsQuaternion(q);
134  y[3] = q[0];
135  y[4] = q[1];
136  y[5] = q[2];
137  y[6] = q[3];
138 }
139 
141 {
143  { // Use Jacobians
145 
146  // Mean:
147  mean.x(o.mean.x());
148  mean.y(o.mean.y());
149  mean.z(o.mean.z());
150 
151  o.mean.getAsQuaternion(mean.quat(), dq_dr_sub);
152 
153  // Cov:
155  dq_dr(0, 0) = dq_dr(1, 1) = dq_dr(2, 2) = 1;
156  dq_dr.insertMatrix(3, 3, dq_dr_sub);
157  // Now for the covariance:
158  this->cov = mrpt::math::multiply_HCHt(dq_dr, o.cov);
159  }
160  else
161  {
162  // Use UT transformation:
163  // f: R^6 => R^7
164  const CVectorFixedDouble<6> x_mean(o.mean);
165 
166  const double dummy = 0;
168  x_mean, o.cov, &aux_poseypr2posequat, dummy, this->mean, this->cov);
169  }
170 }
171 
172 /*---------------------------------------------------------------
173  saveToTextFile
174  ---------------------------------------------------------------*/
175 bool CPose3DQuatPDFGaussian::saveToTextFile(const string& file) const
176 {
177  FILE* f = os::fopen(file.c_str(), "wt");
178  if (!f) return false;
179 
180  os::fprintf(
181  f, "%e %e %e %e %e %e %e\n", mean.x(), mean.y(), mean.z(),
182  mean.quat()[0], mean.quat()[1], mean.quat()[2], mean.quat()[3]);
183 
184  for (unsigned int i = 0; i < 7; i++)
185  os::fprintf(
186  f, "%e %e %e %e %e %e %e\n", cov(i, 0), cov(i, 1), cov(i, 2),
187  cov(i, 3), cov(i, 4), cov(i, 5), cov(i, 6));
188 
189  os::fclose(f);
190  return true;
191 }
192 
193 /*---------------------------------------------------------------
194  changeCoordinatesReference
195  ---------------------------------------------------------------*/
197  const CPose3D& newReferenceBase)
198 {
199  MRPT_START
200  changeCoordinatesReference(CPose3DQuat(newReferenceBase));
201  MRPT_END
202 }
203 
204 /*---------------------------------------------------------------
205  changeCoordinatesReference
206  ---------------------------------------------------------------*/
208  const CPose3DQuat& newReferenceBaseQuat)
209 {
210  MRPT_START
211 
212  // COV:
213  const CMatrixDouble77 OLD_COV = this->cov;
215 
217  newReferenceBaseQuat, // x
218  this->mean, // u
219  df_dx, df_du,
220  &this->mean // Output: newReferenceBaseQuat + this->mean;
221  );
222 
223  // this->cov = H1*this->cov*H1' + H2*Ap.cov*H2';
224  // df_dx: not used, since its COV are all zeros...
225  cov = mrpt::math::multiply_HCHt(df_du, OLD_COV);
226 
227  MRPT_END
228 }
229 
230 /*---------------------------------------------------------------
231  drawSingleSample
232  ---------------------------------------------------------------*/
234 {
235  MRPT_START
237  MRPT_END
238 }
239 
240 /*---------------------------------------------------------------
241  drawManySamples
242  ---------------------------------------------------------------*/
244  size_t N, vector<CVectorDouble>& outSamples) const
245 {
246  MRPT_START
247 
249 
250  for (auto& outSample : outSamples)
251  for (unsigned int k = 0; k < 7; k++) outSample[k] += mean[k];
252 
253  MRPT_END
254 }
255 
256 /*---------------------------------------------------------------
257  inverse
258  ---------------------------------------------------------------*/
260 {
262  auto& out = dynamic_cast<CPose3DQuatPDFGaussian&>(o);
263 
264  // COV:
266  double lx, ly, lz;
267  mean.inverseComposePoint(0, 0, 0, lx, ly, lz, nullptr, &df_dpose);
268 
270  jacob.insertMatrix(0, 0, df_dpose);
271  jacob(3, 3) = 1;
272  jacob(4, 4) = -1;
273  jacob(5, 5) = -1;
274  jacob(6, 6) = -1;
275 
276  // C(0:2,0:2): H C H^t
277  out.cov = mrpt::math::multiply_HCHt(jacob, this->cov);
278 
279  // Mean:
280  out.mean.x(lx);
281  out.mean.y(ly);
282  out.mean.z(lz);
283  this->mean.quat().conj(out.mean.quat());
284 }
285 
286 /*---------------------------------------------------------------
287  +=
288  ---------------------------------------------------------------*/
290 {
291  // COV:
292  const CMatrixDouble77 OLD_COV = this->cov;
294 
296  this->mean, // x
297  Ap, // u
298  df_dx, df_du,
299  &this->mean // Output: this->mean + Ap;
300  );
301 
302  // this->cov = H1*this->cov*H1' + H2*Ap.cov*H2';
303  cov = mrpt::math::multiply_HCHt(df_dx, OLD_COV);
304  // df_du: Nothing to do, since COV(Ap) = zeros
305 }
306 
307 /*---------------------------------------------------------------
308  +=
309  ---------------------------------------------------------------*/
311 {
312  // COV:
313  const CMatrixDouble77 OLD_COV = this->cov;
315 
317  this->mean, // x
318  Ap.mean, // u
319  df_dx, df_du,
320  &this->mean // Output: this->mean + Ap.mean;
321  );
322 
323  // this->cov = H1*this->cov*H1' + H2*Ap.cov*H2';
324  cov = mrpt::math::multiply_HCHt(df_dx, OLD_COV);
325  cov += mrpt::math::multiply_HCHt(df_du, Ap.cov);
326 }
327 
328 /*---------------------------------------------------------------
329  -=
330  ---------------------------------------------------------------*/
332 {
333  // THIS = THIS (-) Ap -->
334  // THIS = inverse(Ap) (+) THIS
335  CPose3DQuatPDFGaussian inv_Ap = -Ap;
336  *this = inv_Ap + *this;
337 }
338 
339 /*---------------------------------------------------------------
340  evaluatePDF
341  ---------------------------------------------------------------*/
343 {
344  return mrpt::math::normalPDF(
345  CMatrixDouble71(x), CMatrixDouble71(this->mean), this->cov);
346 }
347 
348 /*---------------------------------------------------------------
349  evaluateNormalizedPDF
350  ---------------------------------------------------------------*/
352 {
353  return mrpt::math::normalPDF(
354  CMatrixDouble71(x), CMatrixDouble71(this->mean), this->cov, true);
355 }
356 
357 /*---------------------------------------------------------------
358  enforceCovSymmetry
359  ---------------------------------------------------------------*/
361 {
362  // Differences, when they exist, appear in the ~15'th significant
363  // digit, so... just take one of them arbitrarily!
364  for (int i = 0; i < cov.rows() - 1; i++)
365  for (int j = i + 1; j < cov.rows(); j++) cov(i, j) = cov(j, i);
366 }
367 
368 /*---------------------------------------------------------------
369  mahalanobisDistanceTo
370  ---------------------------------------------------------------*/
372  const CPose3DQuatPDFGaussian& theOther)
373 {
374  MRPT_START
375  const CMatrixDouble77 COV2 = cov + theOther.cov;
377  CMatrixDouble71(this->mean) - CMatrixDouble71(theOther.mean), COV2);
378  MRPT_END
379 }
380 
381 /*---------------------------------------------------------------
382  operator <<
383  ---------------------------------------------------------------*/
385  ostream& out, const CPose3DQuatPDFGaussian& obj)
386 {
387  out << "Mean: " << obj.mean << "\n";
388  out << "Covariance:\n" << obj.cov << "\n";
389  return out;
390 }
391 
393  const CPose3DQuatPDFGaussian& p1, const CPose3DQuatPDFGaussian& p2)
394 {
395  return p1.mean == p2.mean && p1.cov == p2.cov;
396 }
397 
400 {
401  CPose3DQuatPDFGaussian res(x);
402  res += u;
403  return res;
404 }
405 
408 {
409  CPose3DQuatPDFGaussian res(x);
410  res -= u;
411  return res;
412 }
A namespace of pseudo-random numbers generators of diferent distributions.
void changeCoordinatesReference(const CPose3DQuat &newReferenceBase)
this = p (+) this.
mrpt::math::CQuaternionDouble & quat()
Read/Write access to the quaternion representing the 3D rotation.
Definition: CPose3DQuat.h:58
void drawManySamples(size_t N, std::vector< mrpt::math::CVectorDouble > &outSamples) const override
Draws a number of samples from the distribution, and saves as a list of 1x7 vectors, where each row contains a (x,y,z,qr,qx,qy,qz) datum.
A compile-time fixed-size numeric matrix container.
Definition: CMatrixFixed.h:33
void serializeSymmetricMatrixTo(MAT &m, mrpt::serialization::CArchive &out)
Binary serialization of symmetric matrices, saving the space of duplicated values.
#define MRPT_START
Definition: exceptions.h:241
CPose3D mean
The mean value.
CMatrixFixed< double, 7, 1 > CMatrixDouble71
Definition: CMatrixFixed.h:379
void copyFrom(const CPose3DPDF &o) override
Copy operator, translating if necesary (for example, between particles and gaussian representations) ...
TConstructorFlags_Quaternions
Definition: CQuaternion.h:20
int void fclose(FILE *f)
An OS-independent version of fclose.
Definition: os.cpp:275
#define IMPLEMENTS_SERIALIZABLE(class_name, base, NameSpace)
To be added to all CSerializable-classes implementation files.
mrpt::math::TPoint2D operator+(const CPose2D &pose, const mrpt::math::TPoint2D &pnt)
Compose a 2D point from a new coordinate base given by a 2D pose.
Definition: CPose2D.cpp:394
std::ostream & operator<<(std::ostream &o, const CPoint2D &p)
Dumps a point as a string (x,y)
Definition: CPoint2D.cpp:102
double mahalanobisDistanceTo(const CPose3DQuatPDFGaussian &theOther)
Computes the Mahalanobis distance between the centers of two Gaussians.
void insertMatrix(const int row_start, const int col_start, const OTHERMATVEC &submat)
Copies the given input submatrix/vector into this matrix/vector, starting at the given top-left coord...
Definition: MatrixBase.h:210
mrpt::math::CMatrixDouble77 cov
The 7x7 covariance matrix.
void serializeFrom(mrpt::serialization::CArchive &in, uint8_t serial_version) override
Pure virtual method for reading (deserializing) from an abstract archive.
double evaluatePDF(const CPose3DQuat &x) const
Evaluates the PDF at a given point.
STL namespace.
void operator+=(const CPose3DQuat &Ap)
Makes: thisPDF = thisPDF + Ap, where "+" is pose composition (both the mean, and the covariance matri...
Declares a class that represents a Probability Density function (PDF) of a 3D pose using a quaternion...
void getAsQuaternion(mrpt::math::CQuaternionDouble &q, mrpt::optional_ref< mrpt::math::CMatrixDouble43 > out_dq_dr=std::nullopt) const
Returns the quaternion associated to the rotation of this object (NOTE: XYZ translation is ignored) ...
Definition: CPose3D.cpp:517
void USE_SUT_EULER2QUAT_CONVERSION(bool value)
If set to true (default), a Scaled Unscented Transform is used instead of a linear approximation with...
#define MRPT_THROW_UNKNOWN_SERIALIZATION_VERSION(__V)
For use in CSerializable implementations.
Definition: exceptions.h:97
#define ASSERT_(f)
Defines an assertion mechanism.
Definition: exceptions.h:120
double evaluateNormalizedPDF(const CPose3DQuat &x) const
Evaluates the ratio PDF(x) / PDF(MEAN), that is, the normalized PDF in the range [0,1].
This base provides a set of functions for maths stuff.
void inverseComposePoint(const double gx, const double gy, const double gz, double &lx, double &ly, double &lz, mrpt::math::CMatrixFixed< double, 3, 3 > *out_jacobian_df_dpoint=nullptr, mrpt::math::CMatrixFixed< double, 3, 7 > *out_jacobian_df_dpose=nullptr) const
Computes the 3D point L such as .
#define CLASS_ID(T)
Access to runtime class ID for a defined class name.
Definition: CObject.h:102
Declares a class that represents a Probability Density function (PDF) of a 2D pose ...
void enforceCovSymmetry()
Assures the symmetry of the covariance matrix (eventually certain operations in the math-coprocessor ...
void conj(CQuaternion &q_out) const
Return the conjugate quaternion.
Definition: CQuaternion.h:412
void drawGaussianMultivariateMany(VECTOR_OF_VECTORS &ret, size_t desiredSamples, const COVMATRIX &cov, const typename VECTOR_OF_VECTORS::value_type *mean=nullptr)
Generate a given number of multidimensional random samples according to a given covariance matrix...
CPose2D operator-(const CPose2D &p)
Unary - operator: return the inverse pose "-p" (Note that is NOT the same than a pose with negative x...
Definition: CPose2D.cpp:356
virtual const mrpt::rtti::TRuntimeClassId * GetRuntimeClass() const override
Returns information about the class of an object in runtime.
void serializeTo(mrpt::serialization::CArchive &out) const override
Pure virtual method for writing (serializing) to an abstract archive.
void deserializeSymmetricMatrixFrom(MAT &m, mrpt::serialization::CArchive &in)
Binary serialization of symmetric matrices, saving the space of duplicated values.
void drawSingleSample(CPose3DQuat &outPart) const override
Draws a single sample from the distribution.
double x() const
Common members of all points & poses classes.
Definition: CPoseOrPoint.h:143
void copyFrom(const CPose3DQuatPDF &o) override
Copy operator, translating if necesary (for example, between particles and gaussian representations) ...
A class used to store a 3D pose as a translation (x,y,z) and a quaternion (qr,qx,qy,qz).
Definition: CPose3DQuat.h:45
CMatrixDouble cov(const MATRIX &v)
Computes the covariance matrix from a list of samples in an NxM matrix, where each row is a sample...
Definition: ops_matrices.h:149
void transform_gaussian_unscented(const VECTORLIKE1 &x_mean, const MATLIKE1 &x_cov, void(*functor)(const VECTORLIKE1 &x, const USERPARAM &fixed_param, VECTORLIKE3 &y), const USERPARAM &fixed_param, VECTORLIKE2 &y_mean, MATLIKE2 &y_cov, const bool *elem_do_wrap2pi=nullptr, const double alpha=1e-3, const double K=0, const double beta=2.0)
Scaled unscented transformation (SUT) for estimating the Gaussian distribution of a variable Y=f(X) f...
Declares a class that represents a probability density function (pdf) of a 2D pose (x...
Definition: CPosePDF.h:38
Classes for 2D/3D geometry representation, both of single values and probability density distribution...
constexpr size_type rows() const
Number of rows in the matrix.
Definition: CMatrixFixed.h:227
int fprintf(FILE *fil, const char *format,...) noexcept MRPT_printf_format_check(2
An OS-independent version of fprintf.
Definition: os.cpp:410
bool saveToTextFile(const std::string &file) const override
Save the PDF to a text file, containing the 3D pose in the first line (x y z qr qx qy qz)...
mrpt::math::CMatrixDouble66 cov
The 6x6 covariance matrix.
This is the global namespace for all Mobile Robot Programming Toolkit (MRPT) libraries.
bool operator==(const CPoint< DERIVEDCLASS, DIM > &p1, const CPoint< DERIVEDCLASS, DIM > &p2)
Definition: CPoint.h:119
void aux_poseypr2posequat(const CVectorFixedDouble< 6 > &x, const double &dummy, CVectorFixedDouble< 7 > &y)
Virtual base class for "archives": classes abstracting I/O streams.
Definition: CArchive.h:54
void drawGaussianMultivariate(std::vector< T > &out_result, const MATRIX &cov, const std::vector< T > *mean=nullptr)
Generate multidimensional random samples according to a given covariance matrix.
virtual std::tuple< cov_mat_t, type_value > getCovarianceAndMean() const =0
Returns an estimate of the pose covariance matrix (STATE_LENxSTATE_LEN cov matrix) and the mean...
CPose3DQuatPDFGaussian()
Default constructor - set all values to zero.
Declares a class that represents a Probability Density Function (PDF) of a 3D pose (6D actually)...
A class used to store a 3D pose (a 3D translation + a rotation in 3D).
Definition: CPose3D.h:85
mrpt::vision::TStereoCalibResults out
bool USE_SUT_EULER2QUAT_CONVERSION_value
void operator-=(const CPose3DQuatPDFGaussian &Ap)
Makes: thisPDF = thisPDF - Ap, where "-" is pose inverse composition (both the mean, and the covariance matrix are updated).
This file implements matrix/vector text and binary serialization.
VECTORLIKE1::Scalar mahalanobisDistance(const VECTORLIKE1 &X, const VECTORLIKE2 &MU, const MAT &COV)
Computes the mahalanobis distance of a vector X given the mean MU and the covariance inverse COV_inv ...
Definition: data_utils.h:57
#define MRPT_END
Definition: exceptions.h:245
double mean(const CONTAINER &v)
Computes the mean value of a vector.
Declares a class that represents a Probability Density function (PDF) of a 3D pose ...
FILE * fopen(const char *fileName, const char *mode) noexcept
An OS-independent version of fopen.
Definition: os.cpp:257
void inverse(CPose3DQuatPDF &o) const override
Returns a new PDF such as: NEW_PDF = (0,0,0) - THIS_PDF.
void getMean(CPose3DQuat &mean_pose) const override
uint8_t serializeGetVersion() const override
Must return the current versioning number of the object.
A quaternion, which can represent a 3D rotation as pair , with a real part "r" and a 3D vector ...
Definition: CQuaternion.h:44
static void jacobiansPoseComposition(const CPose3DQuat &x, const CPose3DQuat &u, mrpt::math::CMatrixDouble77 &df_dx, mrpt::math::CMatrixDouble77 &df_du, CPose3DQuat *out_x_oplus_u=nullptr)
This static method computes the two Jacobians of a pose composition operation $f(x,u)= x u$.
CRandomGenerator & getRandomGenerator()
A static instance of a CRandomGenerator class, for use in single-thread applications.
double normalPDF(double x, double mu, double std)
Evaluates the univariate normal (Gaussian) distribution at a given point "x".
Definition: math.cpp:33
#define MRPT_UNUSED_PARAM(a)
Determines whether this is an X86 or AMD64 platform.
Definition: common.h:186
void multiply_HCHt(const MAT_H &H, const MAT_C &C, MAT_R &R, bool accumResultInOutput=false)
R = H * C * H^t.
Definition: ops_matrices.h:28



Page generated by Doxygen 1.8.14 for MRPT 1.9.9 Git: 3a26b90fd Wed Mar 25 20:17:03 2020 +0100 at miƩ mar 25 23:05:41 CET 2020