/* +---------------------------------------------------------------------------+
   |          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 CPosePDFSOG_H
#define CPosePDFSOG_H

#include <MRPT/MRML/CPosePDF.h>
#include <MRPT/UTILS/CMatrix.h>
#include <MRPT/UTILS/CMatrixD.h>


namespace UTILS
{
	namespace OPENGL
	{
		class CSetOfObjects;
	}
}

namespace MRML
{
	/** Declares a class that represents a Probability Density  function (PDF) of a 2D pose \f$ p(\mathbf{x}) = [x ~ y ~ \phi ]^t \f$.
	 *   This class implements that PDF as the following multi-modal Gaussian distribution:
	 *
	 * \f$ p(\mathbf{x}) = \sum\limits_{i=1}^N \omega^i \mathcal{N}( \mathbf{x} ; \bar{\mathbf{x}}^i, \mathbf{\Sigma}^i )  \f$
	 *
	 *  Where the number of modes N is the size of CPosePDFSOG::m_modes
	 *
	 *  See MRML::CPosePDF for more details.
     *
	 * \sa CPose2D, CPosePDF, CPosePDFParticles
	 */
	class CPosePDFSOG : public CPosePDF
	{
		// This must be added to any CSerializable derived class:
		DEFINE_SERIALIZABLE( CPosePDFSOG )

	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
		  * \param nModes The initial size of CPosePDFSOG::m_modes
		  */
		CPosePDFSOG( size_t nModes = 1 );

		/** The struct for each mode:
		 */
		struct TGaussianMode
		{
			TGaussianMode() :
				mean(),
				cov(3,3),
				log_w(0)
			{ }

			CPose2D		mean;
			CMatrixD	cov;

			/** The log-weight
			  */
			double		log_w;
		};

		/** Access directly to this array for modify the modes as desired.
		  *  Note that no weight can be zero!!
		  */
		std::deque<TGaussianMode>	m_modes;

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

		 /** Returns an estimate of the pose covariance matrix (3x3 cov.matrix  for x,y,phi variables)
		  */
		CMatrixD  getEstimatedCovariance() const;

		/** Normalize the weights in m_modes such as the maximum log-weight is 0.
		  */
		void  normalizeWeights();

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

		/** Save the density to a text file, with the following format:
		  *  There is one row per Gaussian "mode", and each row contains 10 elements:
		  *   - w (The weight)
		  *   - x_mean (gaussian mean value)
		  *   - y_mean (gaussian mean value)
		  *   - phi_mean (gaussian mean value)
		  *   - C11 (Covariance elements)
		  *   - C22 (Covariance elements)
		  *   - C33 (Covariance elements)
		  *   - C12 (Covariance elements)
		  *   - C13 (Covariance elements)
		  *   - C23 (Covariance elements)
		  *
		 */
		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 CPose2D &newReferenceBase );

		/** Rotate all the covariance matrixes by replacing them by \f$ \mathbf{R}~\mathbf{COV}~\mathbf{R}^t \f$, where \f$ \mathbf{R} = \left[ \begin{array}{ccc} \cos\alpha & -\sin\alpha & 0 \\ \sin\alpha & \cos\alpha & 0 \\ 0 & 0 & 1 \end{array}\right] \f$.
		  */
		void  rotateAllCovariances(const double &ang);

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

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

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

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

		/** Evaluates the PDF at a given point.
		  */
		double  evaluatePDF( const CPose2D &x, bool sumOverAllPhis = false ) const;

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

		/** Evaluates the PDF within a rectangular grid (and a fixed orientation) and saves the result in a matrix (each row contains values for a fixed y-coordinate value).
		  */
		void  evaluatePDFInArea(
			const double &		x_min,
			const double &		x_max,
			const double &		y_min,
			const double &		y_max,
			const double &		resolutionXY,
			const double &		phi,
			CMatrixD	&outMatrix,
			bool		sumOverAllPhis = false );

		/** Bayesian fusion of two pose distributions, then save the result in this object (WARNING: Currently p1 must be a MRML::CPosePDFSOG object and p2 a MRML::CPosePDFGaussian object)
		  */
		void  bayesianFusion( CPosePDF &p1, CPosePDF &p2, const double &minMahalanobisDistToDrop=0 );


		/** Returns a 3D object representation of all the ellipses in the SoG.
		  */
		void  getAs3DObject( UTILS::OPENGL::CSetOfObjects	&outObj ) const;


	}; // End of class def.

	// This must be added to any CSerializable derived class:
	DEFINE_SERIALIZABLE_POST( CPosePDFSOG )


} // End of namespace

#endif
