/* +---------------------------------------------------------------------------+
   |          The Mobile Robot Programming Toolkit (MRPT) C++ library          |
   |                                                                           |
   |                   http://mrpt.sourceforge.net/                            |
   |                                                                           |
   |   Copyright (C) 2005-2008  University of Malaga                           |
   |                                                                           |
   |    This software was written by the Perception and Robotics               |
   |      research group, University of Malaga (Spain).                        |
   |    Contact: Jose-Luis Blanco  <jlblanco@ctima.uma.es>                     |
   |                                                                           |
   |  This file is part of the MRPT project.                                   |
   |                                                                           |
   |     MRPT is free software: you can redistribute it and/or modify          |
   |     it under the terms of the GNU General Public License as published by  |
   |     the Free Software Foundation, either version 3 of the License, or     |
   |     (at your option) any later version.                                   |
   |                                                                           |
   |   MRPT is distributed in the hope that it will be useful,                 |
   |     but WITHOUT ANY WARRANTY; without even the implied warranty of        |
   |     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         |
   |     GNU General Public License for more details.                          |
   |                                                                           |
   |     You should have received a copy of the GNU General Public License     |
   |     along with MRPT.  If not, see <http://www.gnu.org/licenses/>.         |
   |                                                                           |
   +---------------------------------------------------------------------------+ */
#ifndef CPose3DPDFGaussian_H
#define CPose3DPDFGaussian_H

#include <MRPT/MRML/CPose3DPDF.h>
#include <MRPT/UTILS/CMatrixD.h>

namespace MRML
{
	class CPosePDFGaussian;

	/** Declares a class that represents a Probability Density function (PDF) of a 3D pose \f$ p(\mathbf{x}) = [x ~ y ~ z ~ yaw ~ pitch ~ roll]^t \f$.
	 *
	 *   This class implements that PDF using a mono-modal Gaussian distribution. See MRML::CPose3DPDF for more details.
	 *
	 *  The formulas used for pose/uncertainty composition in the "CPose3DPDFGaussian::operator+=" and "CPose3DPDFGaussian::jacobiansPoseComposition":
	 *
	 *  We compose the pose "x" by adding "u" to it, obtaining "y":
	 *
	 *   \f[ y = x \oplus u \f]
	 *
	 * The mean of "y" is:
	 *
\f[ \hat{y} = \left(
\begin{array}{l}
\hat{x}_x + R_{11}\hat{u}_x + R_{12}\hat{u}_y + R_{13}\hat{u}_z \\
\hat{x}_y + R_{21}\hat{u}_x + R_{22}\hat{u}_y + R_{23}\hat{u}_z \\
\hat{x}_z + R_{31}\hat{u}_x + R_{32}\hat{u}_y + R_{33}\hat{u}_z \\
\hat{x}_{yaw} + \hat{u}_{yaw} \\
\hat{x}_p + \hat{u}_p \\
\hat{x}_r + \hat{u}_r
\end{array} \right)
\f]

	 * And its covariance:

\f[
\Sigma_y = \frac{df}{dx} \Sigma_x \frac{df}{dx}^\top + \frac{df}{du} \Sigma_u \frac{df}{du}^\top
\f]

	 * With the Jacobians being computed by CPose3DPDFGaussian::jacobiansPoseComposition (check the source code for the exact formulas).
     *
	 * \sa CPose3D, CPose3DPDF, CPose3DPDFParticles
	 */
	class CPose3DPDFGaussian : public CPose3DPDF
	{
		// This must be added to any CSerializable derived class:
		DEFINE_SERIALIZABLE( CPose3DPDFGaussian )

	protected:
		/** Assures the symmetry of the covariance matrix (eventually certain operations in the math-coprocessor lead to non-symmetric matrixes!)
		  */
		void  assureSymmetry();

	 public:
		/** Default constructor
		  */
		CPose3DPDFGaussian();

		/** Constructor
		  */
		CPose3DPDFGaussian( const CPose3D &init_Mean );

		/** Constructor
		  */
		CPose3DPDFGaussian( const CPose3D &init_Mean, const CMatrixD &init_Cov );

		/** Constructor from a Gaussian 2D pose PDF (sets to 0 the missing variables z,pitch, and roll).
		  */
		CPose3DPDFGaussian( const CPosePDFGaussian &o );

		/** The mean value
		 */
		CPose3D		mean;

		/** The 6x6 covariance matrix
		 */
		CMatrixD	cov;

		 /** Returns an estimate of the pose, (the mean, or mathematical expectation of the PDF)
		  */
		CPose3D  getEstimatedPose() const;

		 /** Returns an estimate of the pose covariance matrix (6x6 cov.matrix for x,y,z,yaw,pitch,and roll variables)
		  */
		CMatrixD  getEstimatedCovariance() const;

		/** Copy operator, translating if necesary (for example, between particles and gaussian representations)
		  */
		void  copyFrom(const CPose3DPDF &o);

		/** Save PDF's particles to a text file, containing the 3D pose in the first line, then the covariance matrix in next 3 lines.
		 */
		void  saveToTextFile(const std::string &file) const;

		/** This can be used to convert a PDF from local coordinates to global, providing the point (newReferenceBase) from which
		  *   "to project" the current pdf. Result PDF substituted the currently stored one in the object.
		  */
		void  changeCoordinatesReference(  const CPose3D &newReferenceBase );

		/** Rotate the covariance matrix by replacing it by \f$ \mathbf{R}~\mathbf{COV}~\mathbf{R}^t \f$, where \f$ \mathbf{R} = ...  \f$.
		  */
		void  rotateCov(const double &ang);

		/** Draws a single sample from the distribution
		  */
		void  drawSingleSample( CPose3D &outPart ) const;

		/** Draws a number of samples from the distribution, and saves as a list of 1x6 vectors, where each row contains a (x,y,phi) datum.
		  */
		void  drawManySamples( size_t N, std::vector<vector_double> & outSamples ) const;

		/** Bayesian fusion of two points gauss. distributions, then save the result in this object.
		  *  The process is as follows:<br>
		  *		- (x1,S1): Mean and variance of the p1 distribution.
		  *		- (x2,S2): Mean and variance of the p2 distribution.
		  *		- (x,S): Mean and variance of the resulting distribution.
		  *
		  *    S = (S1<sup>-1</sup> + S2<sup>-1</sup>)<sup>-1</sup>;
		  *    x = S * ( S1<sup>-1</sup>*x1 + S2<sup>-1</sup>*x2 );
		  */
		void  bayesianFusion( CPose3DPDF &p1, CPose3DPDF &p2 );

		/** Returns a new PDF such as: NEW_PDF = (0,0,0) - THIS_PDF
		  */
		void	 inverse(CPose3DPDF &o) const;

		/** Makes: thisPDF = thisPDF + Ap, where "+" is pose composition (both the mean, and the covariance matrix are updated).
		  */
		void  operator += ( const CPose3D &Ap);

		/** Makes: thisPDF = thisPDF + Ap, where "+" is pose composition (both the mean, and the covariance matrix are updated) (see formulas on the top of this page).
		  */
		void  operator += ( const CPose3DPDFGaussian &Ap);

		/** Evaluates the PDF at a given point.
		  */
		double  evaluatePDF( const CPose3D &x ) const;

		/** Evaluates the ratio PDF(x) / PDF(MEAN), that is, the normalized PDF in the range [0,1].
		  */
		double  evaluateNormalizedPDF( const CPose3D &x ) const;

		/** Computes the Mahalanobis distance between the centers of two Gaussians.
		  */
		double  mahalanobisDistanceTo( const CPose3DPDFGaussian& theOther );

		/** This static method computes the pose composition Jacobians (see formulas on the top of this page).
		  */
		static void jacobiansPoseComposition(
			const CPose3DPDFGaussian &x,
			const CPose3DPDFGaussian &u,
			CMatrixDouble			 &df_dx,
			CMatrixDouble			 &df_du);


		/** Returns a 3x3 matrix with submatrix of the covariance for the variables (x,y,yaw) only.
		  */
		void getCovSubmatrix2D( CMatrixDouble &out_cov ) const;


	}; // End of class def.

	DEFINE_SERIALIZABLE_POST( CPose3DPDFGaussian )

	/** Pose composition for two 3D pose Gaussians (see formulas on the top of this page).
	  * \sa CPose3DPDFGaussian::operator +=
	  */
	CPose3DPDFGaussian operator +( const CPose3DPDFGaussian &x, const CPose3DPDFGaussian &u );

	/** Dumps the mean and covariance matrix to a text stream.
	  */
	std::ostream &  operator << (std::ostream & out, const CPose3DPDFGaussian& obj);

} // End of namespace

#endif
