/*
* Copyright 2019 © Centre Interdisciplinaire de développement en Cartographie des Océans (CIDCO), Tous droits réservés
*/

 /*
 * \author Christian Bouchard
 */

#ifndef HULLOVERLAP_HPP
#define HULLOVERLAP_HPP

#include <iostream>
#include <cstdint>

#include <vector>

#include <utility>      // std::pair, std::make_pair

#include <limits>       // std::numeric_limits

#include <pcl/common/common_headers.h>

#include <pcl/point_types.h>
#include <pcl/surface/concave_hull.h>

#include <pcl/PointIndices.h>

#include <pcl/ModelCoefficients.h>
#include <pcl/filters/project_inliers.h>

#include <pcl/segmentation/extract_polygonal_prism_data.h>

#include <Eigen/Dense>
#include <Eigen/Geometry> // For cross product

//-----------------------------------------------------------------------------------
// Andrew's monotone chain convex hull algorithm
// Adapted from
// https://en.wikibooks.org/wiki/Algorithm_Implementation/Geometry/Convex_hull/Monotone_chain#C++

typedef float coord_t;      // coordinate type (Use float because pcl::PointXYZ's coordinates are float)
typedef double coord2_t;    // must be big enough to hold 2*max(|coordinate|)^2

struct PointAndrews
{
	coord_t x;
    coord_t y;
    uint64_t index;

	bool operator <( const PointAndrews &p ) const
    {
		return x < p.x || (x == p.x && y < p.y);
	}
};

// 3D cross product of OA and OB vectors, (i.e z-component of their "2D" cross product,
// but remember that it is not defined in "2D").
// Returns a positive value, if OAB makes a counter-clockwise turn,
// negative for clockwise turn, and zero if the points are collinear.
coord2_t cross( const PointAndrews &O, const PointAndrews &A, const PointAndrews &B )
{
	return (A.x - O.x) * (B.y - O.y) - (A.y - O.y) * (B.x - O.x);
}

// Returns a list of points on the convex hull in counter-clockwise order.
// Note: the last point in the returned list is the same as the first one.
// CB: vector points is modified by getting sorted.
void AndrewsConvex_hull( std::vector<PointAndrews> & hull, std::vector<PointAndrews> & points )
{
	size_t n = points.size(), k = 0;

    hull.clear();

    if ( n <= 3 )
    {
        hull.reserve( n );

        for ( int count = 0; count < n; count++ )
            hull.push_back( points[ count ] );

        return;
    }

    hull.resize( 2 * n );

	// Sort points lexicographically
	sort(points.begin(), points.end());

	// Build lower hull
	for (size_t i = 0; i < n; ++i)
    {
		while (k >= 2 && cross(hull[k-2], hull[k-1], points[i]) <= 0)
            k--;

		hull[k++] = points[i];
	}

	// Build upper hull
	for (size_t i = n-1, t = k+1; i > 0; --i)
    {
		while (k >= t && cross(hull[k-2], hull[k-1], points[i-1]) <= 0)
            k--;

		hull[k++] = points[i-1];
	}

	hull.resize(k-1);

}

//-----------------------------------------------------------------------------------

class HullOverlap
{

public:

	/**
	* Creates a HullOverlap
	*
	* @param line1In Point cloud for line #1
	* @param line2In Point cloud for line #2
    * @param a projection plane coefficient 'a' in ax + by + cz + d = 0
    * @param b projection plane coefficient 'b' in ax + by + cz + d = 0
    * @param c projection plane coefficient 'c' in ax + by + cz + d = 0
    * @param d projection plane coefficient 'd' in ax + by + cz + d = 0
    * @param hullMethod Method to find the hulls, possible values: "PCL ConcaveHull", "Andrew's"
    * @param alpha1 Concave hull computation parameter to use with line #1
    * @param alpha2 Concave hull computation parameter to use with line #2
	*/
    HullOverlap( pcl::PointCloud<pcl::PointXYZ>::ConstPtr line1In,
                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr line2In,
                    double a, double b, double c, double d, std::string hullMethod = "Andrew's",
                    double alphaLine1 = 1.0, double alphaLine2 = 1.0 )
                    :   line1( line1In ), line2( line2In ),
                        a( a ), b( b ), c( c ), d( d ),
                        hullMethod( hullMethod ),

                        alphaLine1( alphaLine1 ), alphaLine2( alphaLine2 ),

                        coefficients ( new pcl::ModelCoefficients() ),

                        line1InPlane (new pcl::PointCloud<pcl::PointXYZ>),
                        line2InPlane (new pcl::PointCloud<pcl::PointXYZ>),

                        line1InPlane2D (new pcl::PointCloud<pcl::PointXYZ>),
                        line2InPlane2D (new pcl::PointCloud<pcl::PointXYZ>),

                        hull1Vertices (new pcl::PointCloud<pcl::PointXYZ>),
                        hull2Vertices (new pcl::PointCloud<pcl::PointXYZ>),

                       // Initialize to dummy values
                       vector1( 1, 0, 0 ), vector2( 0, 1, 0 ), refPoint( 0.0, 0.0, 0.0 )

    {
        coefficients->values.resize(4);
        coefficients->values[0] = a;
        coefficients->values[1] = b;
        coefficients->values[2] = c;
        coefficients->values[3] = d;

        if ( hullMethod != "PCL ConcaveHull" && hullMethod != "Andrew's" )
        {
            std::cerr << "\n\nHullOverlap::HullOverlap(), method \""<<  hullMethod
                << "\" is not a valid method to find the hull.\n\n" << std::endl;
            exit( 1 );
        }

    }

	/**
	* Returns a pair with the number of points in line #1 and in line #2 that are in the overlap area of the two lines.
	* The points are place in the point clouds pointed to by line1InBothHull and line2InBothHull
    *
	* @param[out] line1InBothHull Point cloud of points in line #1 in the overlap area of the two lines
	* @param[out] line2InBothHull Point cloud of points in line #2 in the overlap area of the two lines
	*/
    std::pair< uint64_t, uint64_t > computePointsInBothHulls( pcl::PointCloud<pcl::PointXYZ>::Ptr line1InBothHull,
                                                              pcl::PointCloud<pcl::PointXYZ>::Ptr line2InBothHull )
    {
        return computeHullsAndPointsInBothHulls( line1InBothHull, line2InBothHull, true );
    }

	/**
	* Returns a pair with the number of points in line #1 and in line #2 that are in the overlap area of the two lines,
	* the points are place in the point clouds pointed to by line1InBothHull and line2InBothHull
    *
	* @param[out] line1InBothHull Point cloud of points in line #1 in the overlap area of the two lines
	* @param[out] line2InBothHull Point cloud of points in line #2 in the overlap area of the two lines
    * @param[in] line2InBothHull minimalMemory bool variable, true to specify to try and minimize the memory usage
	*/
    // Put back to public to be able to get indices to the points
    std::pair< uint64_t, uint64_t > computeHullsAndPointsInBothHulls(
                                                pcl::PointCloud<pcl::PointXYZ>::Ptr line1InBothHull = nullptr,
                                                pcl::PointCloud<pcl::PointXYZ>::Ptr line2InBothHull = nullptr,
                                                const bool minimalMemory = false )
    {

        if ( line1InBothHull != nullptr )
            line1InBothHull->clear();

        if ( line2InBothHull != nullptr )
            line2InBothHull->clear();

        std::cout << "\nProjecting line 1 in plane\n" << std::endl;

        // Project line 1 in plane
        createCloudFromProjectionInPlane( line1, line1InPlane );

        std::cout << "line1InPlane->points.size(): " << line1InPlane->points.size() << "\n" << std::endl;

        computeTwoVectorsAndRefPoint();

        std::cout << "\nExpressing points of line 1 in the projection plane using a 2D coordinate system\n" << std::endl;

        createCloudInPlane2D( line1InPlane, line1InPlane2D );

        if ( minimalMemory )
        {
            // Delete the dynamically allocated memory
            line1InPlane.reset();
            line1InPlane = nullptr;
        }

        std::cout << "line1InPlane2D->points.size(): " << line1InPlane2D->points.size() << "\n" << std::endl;

        std::cout << "\nProjecting line 2 in plane\n" << std::endl;

        // Project line 2 in plane
        createCloudFromProjectionInPlane( line2, line2InPlane );

        std::cout << "line2InPlane->points.size(): " << line2InPlane->points.size() << "\n" << std::endl;

        std::cout << "\nExpressing points of line 2 in the projection plane using a 2D coordinate system\n" << std::endl;

        createCloudInPlane2D( line2InPlane, line2InPlane2D );

        if ( minimalMemory )
        {
            // Delete the dynamically allocated memory
            line2InPlane.reset();
            line2InPlane = nullptr;
        }

        std::cout << "line2InPlane2D->points.size(): " << line2InPlane2D->points.size() << "\n" << std::endl;

        // const std::string method = "Andrew's";

        if ( hullMethod == "PCL ConcaveHull" )
        {
            //http://www.pointclouds.org/documentation/tutorials/hull_2d.php

            std::cout << "\nFinding Hull 1\n" << std::endl;

            // Create a Concave Hull for line 1
            computeVerticesOfConcaveHull( line1InPlane2D, alphaLine1, hull1Vertices, hull1PointIndices, ! minimalMemory );

            std::cout << "Finding Hull 2\n" << std::endl;

            // Create a Concave Hull for line 2
            computeVerticesOfConcaveHull( line2InPlane2D, alphaLine2, hull2Vertices, hull2PointIndices, ! minimalMemory );
        }
        else if ( hullMethod == "Andrew's" )
        {
            std::cout << "\nFinding Hull 1\n" << std::endl;

            // Create a Hull for line 1
            computeVerticesOfHullAndrews( line1InPlane2D, hull1Vertices, hull1PointIndices, ! minimalMemory );

            std::cout << "Finding Hull 2\n" << std::endl;

            // Create a Concave Hull for line 2
            computeVerticesOfHullAndrews( line2InPlane2D, hull2Vertices, hull2PointIndices, ! minimalMemory );
        }
        else
        {
            std::cerr << "\n\nHullOverlap::computeHullsAndPointsInBothHulls(), method \""<<  hullMethod
                << "\" is not a valid method to find the hull.\n\n" << std::endl;
            exit( 1 );
        }

        std::cout << "hull1Vertices->points.size(): " << hull1Vertices->points.size() << "\n"
            << "hull2Vertices->points.size(): " << hull2Vertices->points.size() << "\n" << std::endl;

        // If the hulls of the lines where found correctly, points of line 1 are within the hull of line 1.
        // So only need to check that a point of line 1 is part of hull 2 to know that it is part of both hulls.
        // Same idea for points of line 2.

        if ( line1InBothHull != nullptr && line2InBothHull != nullptr )
        {
            if ( minimalMemory )
            {
                std::cout << "Finding points of Line 1 inside Hull 2\n\n" << std::endl;

                findPointsInHullOnlyPoints( line1, line1InPlane2D, line1InBothHull, hull2Vertices );

                // Delete the dynamically allocated memory
                line1InPlane2D.reset();
                line1InPlane2D = nullptr;

                hull2Vertices.reset();
                hull2Vertices = nullptr;

                std::cout << "Finding points of Line 2 inside Hull 1\n\n" << std::endl;

                findPointsInHullOnlyPoints( line2, line2InPlane2D, line2InBothHull, hull1Vertices );

                // Delete the dynamically allocated memory
                line2InPlane2D.reset();
                line2InPlane2D = nullptr;

                hull1Vertices.reset();
                hull1Vertices = nullptr;

                std::cout << "line1InBothHull->points.size(): " << line1InBothHull->points.size() << "\n"
                    << "line2InBothHull->points.size(): " << line2InBothHull->points.size() << "\n" << std::endl;

                return std::make_pair( line1InBothHull->size(), line2InBothHull->size() );

            }
            else
            {

                std::cout << "Finding points of Line 1 inside Hull 2 (and the indices)\n\n" << std::endl;

                findPointsInHull( line1, line1InPlane2D, line1InBothHull, line1InBothHullPointIndices, hull2Vertices );

                std::cout << "Finding points of Line 2 inside Hull 1 (and the indices)\n\n" << std::endl;

                findPointsInHull( line2, line2InPlane2D, line2InBothHull, line2InBothHullPointIndices, hull1Vertices );

                std::cout << "line1InBothHull->points.size(): " << line1InBothHull->points.size() << "\n"
                    << "line2InBothHull->points.size(): " << line2InBothHull->points.size() << "\n" << std::endl;

                return std::make_pair( line1InBothHull->size(), line2InBothHull->size() );

            }

        }
        else
        {
            std::cout << "Finding indices of points of Line 1 inside Hull 2\n\n" << std::endl;

            findPointsInHullOnlyPointIndices( line1InPlane2D, line1InBothHullPointIndices, hull2Vertices );

            std::cout << "Finding indices of points of Line 2 inside Hull 1\n\n" << std::endl;

            findPointsInHullOnlyPointIndices( line2InPlane2D, line2InBothHullPointIndices, hull1Vertices );

            std::cout << "line1InBothHullPointIndices.size(): " << line1InBothHullPointIndices.size() << "\n"
                << "line2InBothHullPointIndices.size(): " << line2InBothHullPointIndices.size() << "\n" << std::endl;

            return std::make_pair( line1InBothHullPointIndices.size(), line2InBothHullPointIndices.size() );
        }

    }

    // Uncommented to get access to the point indices
    // const std::vector< uint64_t > * getConstPtrlineInBothHullPointIndices( const bool isLine1 )
    const std::vector< uint64_t > * getConstPtrlineInBothHullPointIndices( const int lineNumber ) const
    {

        if ( lineNumber < 0 || lineNumber > 1 )
        {
            std::cout << "\n\n----- Function HullOverlap::getConstPtrlineInBothHullPointIndices(): lineNumber parameter: "
                << lineNumber << ".\nIt must be either 0 or 1. Returning nullptr\n" << std::endl;
            return nullptr;
        }

        if ( lineNumber == 0 )
            return & ( line1InBothHullPointIndices );
        else
            return & ( line2InBothHullPointIndices );

        // if ( isLine1 )
        //     return & ( line1InBothHullPointIndices );
        // else
        //     return & ( line2InBothHullPointIndices );
    }

    // pcl::PointCloud< pcl::PointXYZ >::ConstPtr getConstPtrlineInPlane2D( const bool isLine1 )
    pcl::PointCloud< pcl::PointXYZ >::ConstPtr getConstPtrlineInPlane2D( const int lineNumber  ) const
    {

        if ( lineNumber < 0 || lineNumber > 1 )
        {
            std::cout << "\n\n----- Function HullOverlap::getConstPtrlineInPlane2D(): lineNumber parameter: "
                << lineNumber << ".\nIt must be either 0 or 1. Returning nullptr\n" << std::endl;
            return nullptr;
        }

        if ( lineNumber == 0 )
            return line1InPlane2D;
        else
            return line2InPlane2D;

        // if ( isLine1 )
        //     return line1InPlane2D;
        // else
        //     return line2InPlane2D;
    }

    pcl::PointCloud< pcl::PointXYZ >::ConstPtr getConstPtrlineInPlane3D( const int lineNumber  ) const
    {

        if ( lineNumber < 0 || lineNumber > 1 )
        {
            std::cout << "\n\n----- Function HullOverlap::getConstPtrlineInPlane3D(): lineNumber parameter: "
                << lineNumber << ".\nIt must be either 0 or 1. Returning nullptr\n" << std::endl;
            return nullptr;
        }

        if ( lineNumber == 0 )
            return line1InPlane;
        else
            return line2InPlane;
    }

    const std::vector< int > * getConstPtrVerticesIndices( const int lineNumber ) const
    {
        if ( lineNumber < 0 || lineNumber > 1 )
        {
            std::cout << "\n\n----- Function HullOverlap::getConstPtrVerticesIndices(): lineNumber parameter: "
                << lineNumber << ".\nIt must be either 0 or 1. Returning nullptr\n" << std::endl;
            return nullptr;
        }

        if ( lineNumber == 0 )
            return & ( hull1PointIndices.indices );
        else
            return & ( hull2PointIndices.indices );
    }

    bool getMinMaxPointsInOverlapPlane2D( pcl::PointXYZ & minPt, pcl::PointXYZ &maxPt )
    {
        bool OK = false;

        // if there are points in both lines in the overlap
        if ( line1InBothHullPointIndices.size() > 0 && line2InBothHullPointIndices.size() > 0 )
        {

            double xMin = std::numeric_limits<double>::max();
            double xMax = std::numeric_limits<double>::min();

            double yMin = std::numeric_limits<double>::max();
            double yMax = std::numeric_limits<double>::min();

            for ( uint64_t count = 0; count < line1InBothHullPointIndices.size(); count++ )
            {
                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x < xMin )
                    xMin = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x;

                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x > xMax )
                    xMax = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].x;

                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y < yMin )
                    yMin = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y;

                if ( line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y > yMax )
                    yMax = line1InPlane2D->points[ line1InBothHullPointIndices[ count ] ].y;
            }

            for ( uint64_t count = 0; count < line2InBothHullPointIndices.size(); count++ )
            {
                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x < xMin )
                    xMin = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x;

                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x > xMax )
                    xMax = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].x;

                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y < yMin )
                    yMin = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y;

                if ( line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y > yMax )
                    yMax = line2InPlane2D->points[ line2InBothHullPointIndices[ count ] ].y;
            }

            minPt.x = xMin;
            minPt.y = yMin;
            minPt.z = 0;

            maxPt.x = xMax;
            maxPt.y = yMax;
            maxPt.z = 0;

            OK = true;

        }

        return OK;
    }

    bool getMinMaxPointsInOverlapPlane3D( pcl::PointXYZ & minPt, pcl::PointXYZ &maxPt )
    {
        bool OK = false;

        // if there are points in both lines in the overlap
        if ( line1InBothHullPointIndices.size() > 0 && line2InBothHullPointIndices.size() > 0 )
        {

            double xMin = std::numeric_limits<double>::max();
            double xMax = std::numeric_limits<double>::min();

            double yMin = std::numeric_limits<double>::max();
            double yMax = std::numeric_limits<double>::min();

            double zMin = std::numeric_limits<double>::max();
            double zMax = std::numeric_limits<double>::min();

            for ( uint64_t count = 0; count < line1InBothHullPointIndices.size(); count++ )
            {
                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x < xMin )
                    xMin = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x;

                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x > xMax )
                    xMax = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].x;

                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y < yMin )
                    yMin = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y;

                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y > yMax )
                    yMax = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].y;

                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z < zMin )
                    zMin = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z;

                if ( line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z > zMax )
                    zMax = line1InPlane->points[ line1InBothHullPointIndices[ count ] ].z;

            }

            for ( uint64_t count = 0; count < line2InBothHullPointIndices.size(); count++ )
            {
                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x < xMin )
                    xMin = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x;

                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x > xMax )
                    xMax = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].x;

                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y < yMin )
                    yMin = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y;

                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y > yMax )
                    yMax = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].y;

                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z < zMin )
                    zMin = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z;

                if ( line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z > zMax )
                    zMax = line2InPlane->points[ line2InBothHullPointIndices[ count ] ].z;

            }

            minPt.x = xMin;
            minPt.y = yMin;
            minPt.z = zMin;

            maxPt.x = xMax;
            maxPt.y = yMax;
            maxPt.z = zMax;

            OK = true;

        }

        return OK;
    }

    uint64_t getNbPointsInOverlap( const int lineNumber ) const
    {
        if ( lineNumber < 0 || lineNumber > 1 )
        {
            std::cout << "\n\n----- Function HullOverlap::getNbPointsInOverlap(): lineNumber parameter: "
                << lineNumber << ".\nIt must be either 0 or 1. Returning 0\n" << std::endl;
            return 0;
        }

        if ( lineNumber == 0 )
            return line1InBothHullPointIndices.size();
        else
            return line2InBothHullPointIndices.size();
    }

//---------------------------------------------------------------------------------------------------------------------

private:

    // These functions were public when wanted to look at details of projection, etc
    // pcl::PointCloud<pcl::PointXYZ>::ConstPtr getConstPtrLineInPlane( const bool isLine1 )
    // {
    //     if ( isLine1 )
    //         return line1InPlane;
    //     else
    //         return line2InPlane;
    // }

	/**
	* Computes the projection of a point cloud onto a plane
    *
    * @param[in] cloudIn Point cloud to project on the plane
    * @param[out] cloudOut Point cloud resulting from the projection
	*/
    void createCloudFromProjectionInPlane( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut )
    {
        cloudOut->clear();
        cloudOut->reserve( cloudIn->points.size() );

        // Create the filtering object
        pcl::ProjectInliers<pcl::PointXYZ> proj;
        proj.setModelType( pcl::SACMODEL_PLANE );

        proj.setInputCloud( cloudIn );
        proj.setModelCoefficients( coefficients );

        proj.filter( *cloudOut );
    }

	/**
	* Computes two vectors and sets a reference point used to express point positions on the
    * projection plane using only two dimensions
	*/
    void computeTwoVectorsAndRefPoint()
    {

        // Two vectors and a reference point to span the projection plane
        // so that points in the projection plane can be expressed in
        // a coordinate system with vector1, vector2, and refPoint.

        refPoint = line1InPlane->points[ 0 ];

        // Vector #1: from first point in line to last point in line, normalized

        const uint64_t nbPointLine1 = line1InPlane->points.size();

        vector1 << line1InPlane->points[ nbPointLine1 - 1 ].x - line1InPlane->points[ 0 ].x,
                    line1InPlane->points[ nbPointLine1 - 1 ].y - line1InPlane->points[ 0 ].y,
                    line1InPlane->points[ nbPointLine1 - 1 ].z - line1InPlane->points[ 0 ].z;

        std::cout << "vector1 before normalization:\n" << vector1 << "\n\n";

        vector1 = vector1 / vector1.norm();

        std::cout << "vector1 after normalization:\n" << vector1 << "\n\n";

        Eigen::Vector3d normalToPlane;

        normalToPlane <<  a, b, c;

        // Vector #2: perpendicular to the normal to the plane and to vector #1
        vector2 = normalToPlane.cross( vector1 );

        std::cout << "vector2 before normalization:\n" << vector2 << "\n\n";

        vector2 = vector2 / vector2.norm();

        std::cout << "vector2 after normalization:\n" << vector2 << "\n\n";

        // Sanity check
        std::cout << "vector1 dot vector2: " << vector1.dot( vector2 ) << "    (should be 0)\n\n";
    }

	/**
	* Computes a 2D representation of points on the projection plane
    *
    * @param[in] cloudIn Point cloud on the projection plane expressed in 3D
    * @param[out] cloudOut Point cloud on the projection plane expressed in 2D
	*/
    void createCloudInPlane2D( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                            pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut )
    {
        // Build a point cloud where points in the projection plane are expressed in
        // the coordinate system with vector1, vector2, and refPoint.

        cloudOut->clear();
        cloudOut->reserve( cloudIn->points.size() );

        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )
        {
            pcl::PointXYZ point;

            // projection along vector 1
            point.x = ( cloudIn->points[ count ].x - refPoint.x ) * vector1( 0 )
                        + ( cloudIn->points[ count ].y - refPoint.y ) * vector1( 1 )
                        + ( cloudIn->points[ count ].z - refPoint.z ) * vector1( 2 );

            // projection along vector 2
            point.y = ( cloudIn->points[ count ].x - refPoint.x ) * vector2( 0 )
                        + ( cloudIn->points[ count ].y - refPoint.y ) * vector2( 1 )
                        + ( cloudIn->points[ count ].z - refPoint.z ) * vector2( 2 );

            point.z = 0;

            cloudOut->push_back( point );

        }
    }

	/**
	* Computes the vertices of a concave hull for points on the projection plane
    *
    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D
    * @param[in] alpha Concave hull computation parameter to use
    * @param[out] hullVertices Computed vertices of the concave hull
    * @param[out] hullPointIndices Indices of the points in cloudIn making up the hull
    * @param[in] keepInformation bool variable, true to specify to put the indices of the points in cloudIn in hullPointIndices
	*/
    void computeVerticesOfConcaveHull( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                                        const double alpha,
                                        pcl::PointCloud<pcl::PointXYZ>::Ptr hullVertices,
                                        pcl::PointIndices & hullPointIndices, const bool keepInformation = true )
    {
        hullVertices->clear();

        pcl::ConcaveHull<pcl::PointXYZ> concaveHull;

        if ( keepInformation )
            concaveHull.setKeepInformation( true ); // To be able to use function getHullPointIndices()

        concaveHull.setInputCloud( cloudIn );
        concaveHull.setAlpha( alpha );
        concaveHull.reconstruct( * hullVertices );

        if ( keepInformation )
            // Get indices of points making the hull
            concaveHull.getHullPointIndices( hullPointIndices );
    }

	/**
	* Computes the vertices of a hull for points on the projection plane, using Andrew's monotone chain
    *
    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D
    * @param[out] hullVertices Computed vertices of the concave hull
    * @param[out] hullPointIndices Indices of the points in cloudIn making up the hull
    * @param[in] keepInformation bool variable, true to specify to put the indices of the points in cloudIn in hullPointIndices
	*/
    void computeVerticesOfHullAndrews( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                                        pcl::PointCloud<pcl::PointXYZ>::Ptr hullVertices,
                                        pcl::PointIndices & hullPointIndices, const bool keepInformation = true )
    {

        std::cout << "\nBefore building vector for Andrews\n" << std::endl;

        std::vector< PointAndrews > points;
        points.reserve( cloudIn->size() );

        for ( uint64_t count = 0; count < cloudIn->size(); count++ )
        {
            PointAndrews point;

            point.x = cloudIn->points[ count ].x;
            point.y = cloudIn->points[ count ].y;
            point.index = count;

            points.push_back( point );
        }

        std::cout << "\nBefore calling Andrews\n" << std::endl;

        std::vector< PointAndrews > hullAndrews;
        AndrewsConvex_hull( hullAndrews, points );

        hullVertices->clear();
        hullVertices->reserve( hullAndrews.size() );

        std::cout << "\nAfter calling Andrews\n" << std::endl;

        for ( uint64_t count = 0; count < hullAndrews.size(); count++ )
        {
            pcl::PointXYZ point;

            point.x = hullAndrews[ count ].x;
            point.y = hullAndrews[ count ].y;
            point.z = 0;
            hullVertices->push_back( point );

        }

        if ( keepInformation )
        {
            // Get indices of points making the hull

            hullPointIndices.indices.clear();
            hullPointIndices.indices.reserve( hullAndrews.size() );

            for ( uint64_t count = 0; count < hullAndrews.size(); count++ )
                hullPointIndices.indices.push_back( static_cast< int >( hullAndrews[ count ].index ) );

        }

    }

	/**
	* Find points that are within a concave hull.
    * Provides the points and their indices within the original line
    *
    * @param[in] lineOriginal Point cloud of points on the line
    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D
    * @param[out] cloudOut Point cloud of points on the line that are within the hull
    * @param[out] indexPointInHull Indices of the points on the line that are within the hull
    * @param[in] hullVertices Vertices of the concave hull
	*/
    void findPointsInHull( pcl::PointCloud<pcl::PointXYZ>::ConstPtr lineOriginal,
                                pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                                pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut,
                                std::vector< uint64_t > & indexPointInHull,
                                pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )
    {
        cloudOut->clear();
        indexPointInHull.clear();

        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )
        {
            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )
            {
                cloudOut->push_back( lineOriginal->points[ count ] );
                indexPointInHull.push_back( count );
            }
        }

    }

	/**
	* Find indices of points that are within a concave hull.
    *
    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D
    * @param[out] indexPointInHull Indices of the points on the line that are within the hull
    * @param[in] hullVertices Vertices of the concave hull
	*/
    void findPointsInHullOnlyPointIndices( pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                                    std::vector< uint64_t > & indexPointInHull,
                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )
    {
        indexPointInHull.clear();

        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )
        {
            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )
                indexPointInHull.push_back( count );
        }

    }

	/**
	* Find points that are within a concave hull.
    *
    * @param[in] lineOriginal Point cloud of points on the line
    * @param[in] cloudIn Point cloud on the projection plane expressed in 2D
    * @param[out] cloudOut Point cloud of points on the line that are within the hull
    * @param[in] hullVertices Vertices of the concave hull
	*/
    void findPointsInHullOnlyPoints( pcl::PointCloud<pcl::PointXYZ>::ConstPtr lineOriginal,
                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr cloudIn,
                                    pcl::PointCloud<pcl::PointXYZ>::Ptr cloudOut,
                                    pcl::PointCloud<pcl::PointXYZ>::ConstPtr hullVertices )
    {
        cloudOut->clear();

        for ( uint64_t count = 0; count < cloudIn->points.size(); count++ )
        {
            if ( pcl::isXYPointIn2DXYPolygon( cloudIn->points[ count ], *hullVertices ) )
                cloudOut->push_back( lineOriginal->points[ count ] );
        }

    }

// ----------------------------- Variables ------------------------------------------------

    /**Point cloud for line #1*/
    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr line1;

    /**Point cloud for line #2*/
    const pcl::PointCloud<pcl::PointXYZ>::ConstPtr line2;

    /**Projection plane coefficient 'a' in ax + by + cz + d = 0*/
    const double a;

    /**Projection plane coefficient 'b' in ax + by + cz + d = 0*/
    const double b;

    /**Projection plane coefficient 'c' in ax + by + cz + d = 0*/
    const double c;

    /**Projection plane coefficient 'd' in ax + by + cz + d = 0*/
    const double d;

    //** Method to find the hulls, possible values: "PCL ConcaveHull", "Andrew's"*/
    std::string hullMethod;

    /**Concave hull computation parameter to use with line #1*/
    double alphaLine1; // Alpha value to compute the concave hull for line #1

    /**Concave hull computation parameter to use with line #2*/
    double alphaLine2; // Alpha value to compute the concave hull for line #2

    /**Coefficients for the plane, ax + by + cz + d = 0 */
    pcl::ModelCoefficients::Ptr coefficients;

    /**Point cloud of the projection of line #1 on the plane, expressed in 3D*/
    pcl::PointCloud<pcl::PointXYZ>::Ptr line1InPlane;

    /**Point cloud of the projection of line #2 on the plane, expressed in 3D*/
    pcl::PointCloud<pcl::PointXYZ>::Ptr line2InPlane;

    /**Point cloud of the projection of line #1 on the plane, expressed in 2D*/
    pcl::PointCloud<pcl::PointXYZ>::Ptr line1InPlane2D;

    /**Point cloud of the projection of line #2 on the plane, expressed in 2D*/
    pcl::PointCloud<pcl::PointXYZ>::Ptr line2InPlane2D;

    /**Vertices of the concave hull for line #1*/
    pcl::PointCloud<pcl::PointXYZ>::Ptr hull1Vertices;

    /**Vertices of the concave hull for line #2*/
    pcl::PointCloud<pcl::PointXYZ>::Ptr hull2Vertices;

    /**Indices of the points in line #1 whose projection on the plane makes up its hull*/
    pcl::PointIndices hull1PointIndices;

    /**Indices of the points in line #2 whose projection on the plane makes up its hull*/
    pcl::PointIndices hull2PointIndices;

    /**Indices of the points in line #1 that are within both hulls*/
    std::vector< uint64_t > line1InBothHullPointIndices;

    /**Indices of the points in line #2 that are within both hulls*/
    std::vector< uint64_t > line2InBothHullPointIndices;

    /**First computed orthonormal vector used to express points on the projection plane in 2D*/
    Eigen::Vector3d vector1;

    /**Second computed orthonormal vector used to express points on the projection plane in 2D*/
    Eigen::Vector3d vector2;

    /**Referenced point used to express points on the projection plane in 2D*/
    pcl::PointXYZ refPoint;

};

#endif


#ifndef GMM_FIT_H
#define GMM_FIT_H

#include <Eigen/Dense>
#include <math.h>
#include <time.h>
#include <stdlib.h>
#include <iostream>
#include <avatar_locomanipulation/helpers/pseudo_inverse.hpp>

class GMMFit{
public:
  int dim;
  int num_clus;
  double num_data;
  double pi = M_PI; //3.14159265358979323846; // M_PI;

  std::vector<Eigen::VectorXd> list_of_datums_raw;
  std::vector<Eigen::VectorXd> list_of_datums;
  std::vector<Eigen::VectorXd> list_of_mus;
  std::vector<Eigen::MatrixXd> list_of_Sigmas;

  std::vector<Eigen::MatrixXd> list_of_Sigma_inverses;
  std::vector<double> list_of_Sigma_determinants;

  Eigen::VectorXd alphs;
  Eigen::MatrixXd gam;
  Eigen::VectorXd n;

  Eigen::VectorXd data_mean;
  Eigen::VectorXd data_mean_sum;
  Eigen::VectorXd data_min;
  Eigen::VectorXd data_max;
  Eigen::VectorXd data_std_dev;
  Eigen::VectorXd data_std_dev_sqrd;
  Eigen::VectorXd data_std_dev_sum;

  Eigen::VectorXd mu_sum;
  Eigen::MatrixXd sig_sum;

  double error_init = 1000.0;
  double tol = 1e-4;
  double error = 1000;
  double llh_init = 0;
  double llh_prev_init = 0;
  double num_iter = 100;
  double svd_tol = 1e-4;// Tolerance for the SVD when finding the pseudoinverse and the determinant

  double gmm_scaling_factor_sum = 0.0;

  GMMFit();
  GMMFit(const std::vector<Eigen::VectorXd> & data_in, const int & num_clus_in);

  ~GMMFit();

  void setData(const std::vector<Eigen::VectorXd> & data_in); // This function lets you input a list of datums yourself, it does not work with the normalization routine (so don't use this one if you can avoid it)
  double multivariateGuassian(const Eigen::VectorXd & x, const Eigen::VectorXd & mu, const Eigen::MatrixXd & Sigma); //This function is just the multivariate gaussian calc.
  double multivariateGuassian(const Eigen::VectorXd & x, const int cluster_index);

  void expectStep(); // expect step of the EM alg
  void setIter(const int & iter_in);
  void setTol(const double & tol_in);
  void setSVDTol(const double & svd_tol_in); // Sets the singular value threshold to use when computing the pseudo inverse and determinant
  void maxStep(); // maximization step of the EM alg
  double logLike(); // calculates the log likelihood for the EM alg
  void expectationMax(); // runs the full EM alg after being given data
  void setDim(const int & dim_in); // Sets the dimension of the problem, must be run in the beginning
  void setNumClusters(const int & num_clus_in); // sets the number of clusters to be found or input, must be run in the beginning
  void setMu(const std::vector<Eigen::VectorXd> & list_of_mus_in); // allows you to input a list of mus if you already have a trained model
  void setSigma(const std::vector<Eigen::MatrixXd> & list_of_Sigmas_in); // allows you to input a list of sigmas if you already have a trained model
  void setAlpha(const Eigen::VectorXd & alphs_in); // allows you to input an eigen vector of weights if you already have a trained model
  void randInitialGuess(); // initializes the random guess for the initial means of the clusters between -1 and 1
  void addData(const Eigen::VectorXd & datum); // adds one single datum and adds it to the normalization variables
  void prepData(); // calculates the norm and the standard deviation of the data
  void initializeNormalization(); //Initializes normalization variables. Run after setting dimension
  void normalizeData(); // normalizes the data after it has been added using addData and you have run prepData
  void useRawData(); // lets you use the data without normalization
  double mixtureModelProb(const Eigen::VectorXd & x_in); // given a particular state vector, outputs its "probability" given a mixture model.
  void normalizeInputCalculate(const Eigen::VectorXd & x_in, Eigen::VectorXd & x_normalized); // lets you input an unnormalized vector and you get a normalized vector
  void setDataParams(const Eigen::VectorXd & mean_in, const Eigen::VectorXd & std_dev_in); // allows you to input the data norm and standard deviation
  void normalizeInputInverse(const Eigen::VectorXd & x_in, Eigen::VectorXd & x_unnormalized); // allows you to input a normalized datum and it returns the unnormalized vector

  double mixtureDenominator(const int & cluster_index); // returns the denominator value of the specified cluster index
  void computeScalingFactorSum(); // computes the sum of the scaling factors of the GMM
  double getScalingFactorSum(); // returns the sum of the scaling factors of the GMM

  double logCost(const Eigen::VectorXd & x_in); // computes and returns the logCost (AKA feasibility cost) defined as f(x) = log(gmm_scaling_factor_sum) -log(p(x)) which is always non-zero

};

#endif


//  (C) Copyright Eric Niebler 2005.
//  Use, modification and distribution are subject to the
//  Boost Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

// Test case for extended_p_square.hpp

#include <iostream>
#include <boost/random.hpp>
#include <boost/test/unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include <boost/accumulators/numeric/functional/vector.hpp>
#include <boost/accumulators/numeric/functional/complex.hpp>
#include <boost/accumulators/numeric/functional/valarray.hpp>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics/stats.hpp>
#include <boost/accumulators/statistics/extended_p_square.hpp>

using namespace boost;
using namespace unit_test;
using namespace boost::accumulators;

///////////////////////////////////////////////////////////////////////////////
// test_stat
//
void test_stat()
{
    typedef accumulator_set<double, stats<tag::extended_p_square> > accumulator_t;

    // tolerance
    double epsilon = 3;

    // a random number generator
    boost::lagged_fibonacci607 rng;

    std::vector<double> probs;

    probs.push_back(0.001);
    probs.push_back(0.01 );
    probs.push_back(0.1  );
    probs.push_back(0.25 );
    probs.push_back(0.5  );
    probs.push_back(0.75 );
    probs.push_back(0.9  );
    probs.push_back(0.99 );
    probs.push_back(0.999);

    accumulator_t acc(extended_p_square_probabilities = probs);

    for (int i=0; i<10000; ++i)
        acc(rng());

    BOOST_CHECK_GE(extended_p_square(acc)[0], 0.0005);
    BOOST_CHECK_LE(extended_p_square(acc)[0], 0.0015);
    BOOST_CHECK_CLOSE(extended_p_square(acc)[1], probs[1], 15);
    BOOST_CHECK_CLOSE(extended_p_square(acc)[2], probs[2], 5);

    for (std::size_t i=3; i<probs.size(); ++i)
    {
        BOOST_CHECK_CLOSE(extended_p_square(acc)[i], probs[i], epsilon);
    }
}

///////////////////////////////////////////////////////////////////////////////
// init_unit_test_suite
//
test_suite* init_unit_test_suite( int argc, char* argv[] )
{
    test_suite *test = BOOST_TEST_SUITE("extended_p_square test");

    test->add(BOOST_TEST_CASE(&test_stat));

    return test;
}


// Boost.Geometry (aka GGL, Generic Geometry Library)

// Copyright (c) 2007-2015 Barend Gehrels, Amsterdam, the Netherlands.
// Copyright (c) 2008-2015 Bruno Lalande, Paris, France.
// Copyright (c) 2009-2015 Mateusz Loskot, London, UK.

// This file was modified by Oracle on 2015.
// Modifications copyright (c) 2015 Oracle and/or its affiliates.

// Contributed and/or modified by Menelaos Karavelas, on behalf of Oracle

// Parts of Boost.Geometry are redesigned from Geodan's Geographic Library
// (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP
#define BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP

#include <cstddef>

// Remove the ublas checking, otherwise the inverse might fail
// (while nothing seems to be wrong)
#define BOOST_UBLAS_TYPE_CHECK 0

#include <boost/numeric/conversion/cast.hpp>

#if defined(__clang__)
// Avoid warning about unused UBLAS function: boost_numeric_ublas_abs
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-function"
#endif

#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>

#if defined(__clang__)
#pragma clang diagnostic pop
#endif

#include <boost/geometry/core/access.hpp>
#include <boost/geometry/core/coordinate_dimension.hpp>
#include <boost/geometry/core/cs.hpp>
#include <boost/geometry/util/math.hpp>
#include <boost/geometry/util/promote_floating_point.hpp>
#include <boost/geometry/util/select_coordinate_type.hpp>
#include <boost/geometry/util/select_most_precise.hpp>

namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry
{

namespace strategy { namespace transform
{

/*!
\brief Affine transformation strategy in Cartesian system.
\details The strategy serves as a generic definition of affine transformation matrix
         and procedure of application it to given point.
\see http://en.wikipedia.org/wiki/Affine_transformation
     and http://www.devmaster.net/wiki/Transformation_matrices
\ingroup strategies
\tparam Dimension1 number of dimensions to transform from
\tparam Dimension2 number of dimensions to transform to
 */
template
<
    typename CalculationType,
    std::size_t Dimension1,
    std::size_t Dimension2
>
class ublas_transformer
{
};

template <typename CalculationType>
class ublas_transformer<CalculationType, 2, 2>
{
protected :
    typedef CalculationType ct;
    typedef geofeatures_boost::numeric::ublas::matrix<ct> matrix_type;
    matrix_type m_matrix;

public :

    inline ublas_transformer(
                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2,
                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2,
                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2)
        : m_matrix(3, 3)
    {
        m_matrix(0,0) = m_0_0;   m_matrix(0,1) = m_0_1;   m_matrix(0,2) = m_0_2;
        m_matrix(1,0) = m_1_0;   m_matrix(1,1) = m_1_1;   m_matrix(1,2) = m_1_2;
        m_matrix(2,0) = m_2_0;   m_matrix(2,1) = m_2_1;   m_matrix(2,2) = m_2_2;
    }

    inline ublas_transformer(matrix_type const& matrix)
        : m_matrix(matrix)
    {}

    inline ublas_transformer() : m_matrix(3, 3) {}

    template <typename P1, typename P2>
    inline bool apply(P1 const& p1, P2& p2) const
    {
        assert_dimension_greater_equal<P1, 2>();
        assert_dimension_greater_equal<P2, 2>();

        ct const& c1 = get<0>(p1);
        ct const& c2 = get<1>(p1);

        ct p2x = c1 * m_matrix(0,0) + c2 * m_matrix(0,1) + m_matrix(0,2);
        ct p2y = c1 * m_matrix(1,0) + c2 * m_matrix(1,1) + m_matrix(1,2);

        typedef typename geometry::coordinate_type<P2>::type ct2;
        set<0>(p2, geofeatures_boost::numeric_cast<ct2>(p2x));
        set<1>(p2, geofeatures_boost::numeric_cast<ct2>(p2y));

        return true;
    }

    matrix_type const& matrix() const { return m_matrix; }
};

// It IS possible to go from 3 to 2 coordinates
template <typename CalculationType>
class ublas_transformer<CalculationType, 3, 2> : public ublas_transformer<CalculationType, 2, 2>
{
    typedef CalculationType ct;

public :
    inline ublas_transformer(
                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2,
                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2,
                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2)
        : ublas_transformer<CalculationType, 2, 2>(
                    m_0_0, m_0_1, m_0_2,
                    m_1_0, m_1_1, m_1_2,
                    m_2_0, m_2_1, m_2_2)
    {}

    inline ublas_transformer()
        : ublas_transformer<CalculationType, 2, 2>()
    {}
};

template <typename CalculationType>
class ublas_transformer<CalculationType, 3, 3>
{
protected :
    typedef CalculationType ct;
    typedef geofeatures_boost::numeric::ublas::matrix<ct> matrix_type;
    matrix_type m_matrix;

public :
    inline ublas_transformer(
                ct const& m_0_0, ct const& m_0_1, ct const& m_0_2, ct const& m_0_3,
                ct const& m_1_0, ct const& m_1_1, ct const& m_1_2, ct const& m_1_3,
                ct const& m_2_0, ct const& m_2_1, ct const& m_2_2, ct const& m_2_3,
                ct const& m_3_0, ct const& m_3_1, ct const& m_3_2, ct const& m_3_3
                )
        : m_matrix(4, 4)
    {
        m_matrix(0,0) = m_0_0; m_matrix(0,1) = m_0_1; m_matrix(0,2) = m_0_2; m_matrix(0,3) = m_0_3;
        m_matrix(1,0) = m_1_0; m_matrix(1,1) = m_1_1; m_matrix(1,2) = m_1_2; m_matrix(1,3) = m_1_3;
        m_matrix(2,0) = m_2_0; m_matrix(2,1) = m_2_1; m_matrix(2,2) = m_2_2; m_matrix(2,3) = m_2_3;
        m_matrix(3,0) = m_3_0; m_matrix(3,1) = m_3_1; m_matrix(3,2) = m_3_2; m_matrix(3,3) = m_3_3;
    }

    inline ublas_transformer() : m_matrix(4, 4) {}

    template <typename P1, typename P2>
    inline bool apply(P1 const& p1, P2& p2) const
    {
        ct const& c1 = get<0>(p1);
        ct const& c2 = get<1>(p1);
        ct const& c3 = get<2>(p1);

        typedef typename geometry::coordinate_type<P2>::type ct2;

        set<0>(p2, geofeatures_boost::numeric_cast<ct2>(
            c1 * m_matrix(0,0) + c2 * m_matrix(0,1) + c3 * m_matrix(0,2) + m_matrix(0,3)));
        set<1>(p2, geofeatures_boost::numeric_cast<ct2>(
            c1 * m_matrix(1,0) + c2 * m_matrix(1,1) + c3 * m_matrix(1,2) + m_matrix(1,3)));
        set<2>(p2, geofeatures_boost::numeric_cast<ct2>(
            c1 * m_matrix(2,0) + c2 * m_matrix(2,1) + c3 * m_matrix(2,2) + m_matrix(2,3)));

        return true;
    }

    matrix_type const& matrix() const { return m_matrix; }
};

/*!
\brief Strategy of translate transformation in Cartesian system.
\details Translate moves a geometry a fixed distance in 2 or 3 dimensions.
\see http://en.wikipedia.org/wiki/Translation_%28geometry%29
\ingroup strategies
\tparam Dimension1 number of dimensions to transform from
\tparam Dimension2 number of dimensions to transform to
 */
template
<
    typename CalculationType,
    std::size_t Dimension1,
    std::size_t Dimension2
>
class translate_transformer
{
};

template<typename CalculationType>
class translate_transformer<CalculationType, 2, 2> : public ublas_transformer<CalculationType, 2, 2>
{
public :
    // To have translate transformers compatible for 2/3 dimensions, the
    // constructor takes an optional third argument doing nothing.
    inline translate_transformer(CalculationType const& translate_x,
                CalculationType const& translate_y,
                CalculationType const& = 0)
        : ublas_transformer<CalculationType, 2, 2>(
                1, 0, translate_x,
                0, 1, translate_y,
                0, 0, 1)
    {}
};

template <typename CalculationType>
class translate_transformer<CalculationType, 3, 3> : public ublas_transformer<CalculationType, 3, 3>
{
public :
    inline translate_transformer(CalculationType const& translate_x,
                CalculationType const& translate_y,
                CalculationType const& translate_z)
        : ublas_transformer<CalculationType, 3, 3>(
                1, 0, 0, translate_x,
                0, 1, 0, translate_y,
                0, 0, 1, translate_z,
                0, 0, 0, 1)
    {}

};

/*!
\brief Strategy of scale transformation in Cartesian system.
\details Scale scales a geometry up or down in all its dimensions.
\see http://en.wikipedia.org/wiki/Scaling_%28geometry%29
\ingroup strategies
\tparam Dimension1 number of dimensions to transform from
\tparam Dimension2 number of dimensions to transform to
*/
template
<
    typename CalculationType,
    std::size_t Dimension1,
    std::size_t Dimension2
>
class scale_transformer
{
};

template <typename CalculationType>
class scale_transformer<CalculationType, 2, 2> : public ublas_transformer<CalculationType, 2, 2>
{

public :
    inline scale_transformer(CalculationType const& scale_x,
                CalculationType const& scale_y,
                CalculationType const& = 0)
        : ublas_transformer<CalculationType, 2, 2>(
                scale_x, 0,       0,
                0,       scale_y, 0,
                0,       0,       1)
    {}

    inline scale_transformer(CalculationType const& scale)
        : ublas_transformer<CalculationType, 2, 2>(
                scale, 0,     0,
                0,     scale, 0,
                0,     0,     1)
    {}
};

template <typename CalculationType>
class scale_transformer<CalculationType, 3, 3> : public ublas_transformer<CalculationType, 3, 3>
{
public :
    inline scale_transformer(CalculationType const& scale_x,
                CalculationType const& scale_y,
                CalculationType const& scale_z)
        : ublas_transformer<CalculationType, 3, 3>(
                scale_x, 0,       0,       0,
                0,       scale_y, 0,       0,
                0,       0,       scale_z, 0,
                0,       0,       0,       1)
    {}

    inline scale_transformer(CalculationType const& scale)
        : ublas_transformer<CalculationType, 3, 3>(
                scale, 0,     0,     0,
                0,     scale, 0,     0,
                0,     0,     scale, 0,
                0,     0,     0,     1)
    {}
};

#ifndef DOXYGEN_NO_DETAIL
namespace detail
{

template <typename DegreeOrRadian>
struct as_radian
{};

template <>
struct as_radian<radian>
{
    template <typename T>
    static inline T get(T const& value)
    {
        return value;
    }
};

template <>
struct as_radian<degree>
{
    template <typename T>
    static inline T get(T const& value)
    {
        typedef typename promote_floating_point<T>::type promoted_type;
        return value * math::d2r<promoted_type>();
    }

};

template
<
    typename CalculationType,
    std::size_t Dimension1,
    std::size_t Dimension2
>
class rad_rotate_transformer
    : public ublas_transformer<CalculationType, Dimension1, Dimension2>
{
public :
    inline rad_rotate_transformer(CalculationType const& angle)
        : ublas_transformer<CalculationType, Dimension1, Dimension2>(
                 cos(angle), sin(angle), 0,
                -sin(angle), cos(angle), 0,
                 0,          0,          1)
    {}
};

} // namespace detail
#endif // DOXYGEN_NO_DETAIL

/*!
\brief Strategy for rotate transformation in Cartesian coordinate system.
\details Rotate rotates a geometry of specified angle about a fixed point (e.g. origin).
\see http://en.wikipedia.org/wiki/Rotation_%28mathematics%29
\ingroup strategies
\tparam DegreeOrRadian degree/or/radian, type of rotation angle specification
\note A single angle is needed to specify a rotation in 2D.
      Not yet in 3D, the 3D version requires special things to allow
      for rotation around X, Y, Z or arbitrary axis.
\todo The 3D version will not compile.
 */
template
<
    typename DegreeOrRadian,
    typename CalculationType,
    std::size_t Dimension1,
    std::size_t Dimension2
>
class rotate_transformer : public detail::rad_rotate_transformer<CalculationType, Dimension1, Dimension2>
{

public :
    inline rotate_transformer(CalculationType const& angle)
        : detail::rad_rotate_transformer
            <
                CalculationType, Dimension1, Dimension2
            >(detail::as_radian<DegreeOrRadian>::get(angle))
    {}
};

}} // namespace strategy::transform

}} // namespace geofeatures_boost::geometry

#endif // BOOST_GEOMETRY_STRATEGIES_TRANSFORM_MATRIX_TRANSFORMERS_HPP


/* Copyright (c) 2017, Waterloo Autonomous Vehicles Laboratory (WAVELab),
 * Waterloo Intelligent Systems Engineering Lab (WISELab),
 * University of Waterloo.
 *
 * Refer to the accompanying LICENSE file for license information.
 *
 * ############################################################################
 ******************************************************************************
 |                                                                            |
 |                         /\/\__/\_/\      /\_/\__/\/\                       |
 |                         \          \____/          /                       |
 |                          '----________________----'                        |
 |                              /                \                            |
 |                            O/_____/_______/____\O                          |
 |                            /____________________\                          |
 |                           /    (#UNIVERSITY#)    \                         |
 |                           |[**](#OFWATERLOO#)[**]|                         |
 |                           \______________________/                         |
 |                            |_""__|_,----,_|__""_|                          |
 |                            ! !                ! !                          |
 |                            '-'                '-'                          |
 |       __    _   _  _____  ___  __  _  ___  _    _  ___  ___   ____  ____   |
 |      /  \  | | | ||_   _|/ _ \|  \| |/ _ \| \  / |/ _ \/ _ \ /     |       |
 |     / /\ \ | |_| |  | |  ||_||| |\  |||_|||  \/  |||_||||_|| \===\ |====   |
 |    /_/  \_\|_____|  |_|  \___/|_| \_|\___/|_|\/|_|\___/\___/ ____/ |____   |
 |                                                                            |
 ******************************************************************************
 * ############################################################################
 *
 * File: pose_cov_comp.hpp
 * Desc: File containing the function for pose composition with uncertainty.
 *
 * References:
 *       [1] J. Blanco, “A tutorial on se (3) transformation parameterizations
 *           and on-manifold optimization,” Univ. Malaga, Tech. Rep, no. 3,
 *           pp. 1–56, 2014.
 * Auth: Chunshang Li and Jordan Hu
 *
 * ############################################################################
 */

#ifndef WAVE_UTILS_POSE_COV_COMP_HPP_
#define WAVE_UTILS_POSE_COV_COMP_HPP_

#include <Eigen/Dense>

namespace wave {

typedef Eigen::Matrix<double, 7, 1> Vector7;
typedef Eigen::Matrix<double, 6, 1> Vector6;
typedef Eigen::Matrix<double, 4, 1> Vector4;
typedef Eigen::Matrix<double, 3, 1> Vector3;
typedef Eigen::Matrix<double, 6, 6, Eigen::RowMajor> Matrix6x6;
typedef Eigen::Matrix<double, 6, 7, Eigen::RowMajor> Matrix6x7;
typedef Eigen::Matrix<double, 7, 6, Eigen::RowMajor> Matrix7x6;
typedef Eigen::Matrix<double, 4, 4, Eigen::RowMajor> Matrix4x4;
typedef Eigen::Matrix<double, 3, 4, Eigen::RowMajor> Matrix3x4;
typedef Eigen::Matrix<double, 7, 7, Eigen::RowMajor> Matrix7x7;
typedef Eigen::Matrix<double, 3, 7, Eigen::RowMajor> Matrix3x7;
typedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> Matrix3x3;

struct PoseWithCovariance {
    Vector3 position;
    Matrix3x3 rotation_matrix;
    Matrix6x6 covariance;

    PoseWithCovariance();
    PoseWithCovariance(Vector6 &p, Matrix6x6 &q);
    PoseWithCovariance(Vector3 &p, Matrix3x3 &r, Matrix6x6 &q);
    Vector3 getPosition() const;
    Vector3 getYPR() const;
    Eigen::Quaterniond getQuaternion() const;
    Vector7 getPoseQuaternion() const;
    Eigen::Affine3d getTransformMatrix() const;
};

/** Calculates the pose composition of two poses and the estimated covariance.
 *  Based on [1].
 *
 *  @param p1 first pose with covariance
 *  @param p2 second pose with covariance
 *
 *  @return composed pose with predicted covariance
 *
 */
PoseWithCovariance composePose(PoseWithCovariance &p1, PoseWithCovariance &p);

/** The Jacobian of quaternion normalization function. Quaternion in the form of
 *  [qr, qx, qt, qz]
 *  Equation (1.7)
 *
 *  @param q quaternion vector
 *
 *  @return quaternion normal wrt q Jacobian
 */
Matrix4x4 jacobian_Quat_Norm_wrt_q(const Vector4 &q);

/** The Jacobian of normalized quaternion to rpy function.
 *  Equation (2.9) to Equation (2.10)
 *
 *  @param q quaternion vector
 *
 *  @return quaternion normal to roll pitch yaw wrt q Jacobian
 */
Matrix3x4 jacobian_Quat_Norm_to_Rpy_wrt_q(const Vector4 &q);

/** The Jacobian of p7 to p6 conversion.
 *  Equation (2.12)
 *
 *  @param p pose with position and quaternion
 *
 *  @return p7 to p6 wrt p Jacobian
 */
Matrix6x7 jacobian_p7_to_p6_wrt_p(const Vector7 &p);

/** Jacobian of composing a point to a p7.
 *  Equation (3.8)
 *
 *  @param p pose with position and quaternion
 *  @param a position
 *  @return p7 point composition wrt p Jacobian
 */
Matrix3x7 jacobian_p7_Point_Composition_wrt_p(const Vector7 &p,
                                              const Vector3 &a);
/** Jacobian of the composition of p7 poses.
 *  Equation (5.8)
 *
 *  @param p1 pose with position and quaternion
 *  @param p2 pose with position and quaternion
 *  @return p7 p7 composition wrt p1 Jacobian
 */
Matrix7x7 jacobian_p7_p7_Composition_wrt_p1(const Vector7 &p1,
                                            const Vector7 &p2);

/** Jacobian of composing a point to a p7.
 *  Equation (3.10)
 *
 *  @param p pose with position and quaternion
 *  @param a position
 *  @return p7 point composition wrt a Jacobian
 */
Matrix3x3 jacobian_p7_Point_Composition_wrt_a(const Vector7 &p,
                                              const Vector3 &a);

/** Jacobian of the composition of p7 poses.
 *  Equation (5.9)
 *
 *  @param p1 pose with position and quaternion
 *  @param p2 pose with position and quaternion
 *
 *  @return p7 p7 composition wrt p2 Jacobian
 */
Matrix7x7 jacobian_p7_p7_Composition_wrt_p2(const Vector7 &p1,
                                            const Vector7 &p2);

/** Jacobian of converting a p6 to a p7.
 *  Equation (2.8)
 *
 *  @param p pose with position and ypr
 *  @return p6 to p7 wrt p Jacobian
 */
Matrix7x6 jacobian_p6_to_p7_wrt_p(const Vector6 &p);
}  // namespace wave

namespace wave {

/** NOTE: wave_geometry/ has a similar implementation of the following functions
 *  but these are made to match the methods proposed in [1]. These functions
 *  should ONLY be used for pose composition based on [1].
 *
 */
namespace pose_comp {

/** Converts Quaternion to Yaw Pitch Roll angles.
 *  Note v(0) is yaw, v(1) is pitch, v(2) is roll
 *  Equation(2.9) and Equation(2.10)
 *
 *  @param q quaternion vector
 *
 *  @return yaw pitch roll angles in rad
 */
Vector3 quatToYPR(const Eigen::Quaterniond &q);

/** Converts Yaw Pitch Roll angles to Quaternion.
 *  Equation(2.3), Equation(2.4), Equation(2.5), Equation(2.6)
 *
 *  @param ypr yaw pitch roll angles in rad
 *
 *  @return quaternion vector
 */
Eigen::Quaterniond yprToQuat(const Vector3 &ypr);

/** Converts Yaw Pitch Roll angles to Rotation Matrix.
 *  Equation(2.18)
 *
 *  @param ypr yaw pitch roll angles in rad
 *
 *  @return rotation matrix
 */
Matrix3x3 yprToRotMatrix(const Vector3 &ypr);

/** Converts Rotation Matrix to Yaw Pitch Roll angles.
 *  Equation(2.20), Equation(2.21), Equation(2.22), and Equation(2.23)
 *
 *  @param p rotation matrix
 *
 *  @return yaw pitch roll angles in rad
 */
Vector3 rotMatrixToYPR(const Matrix3x3 &p);

/** Converts Rotation Matrix to Quaternion. According to [1], fastest way to
 *  convert from Rotation Matrix to Quat is to convert
 *  Quaternion -> Euler Angles -> Rotation Matrix
 *
 *  @param p rotation matrix
 *
 *  @return: Quaternion vector
 */
Eigen::Quaterniond rotMatrixToQuat(const Matrix3x3 &p);
}  // namespace pose_comp
}  // namespace wave

#endif  // WAVE_UTILS_POSE_COV_COMP_HPP_


#define CATCH_CONFIG_ENABLE_BENCHMARKING

#include <Eigen/Dense>
#include <catch2/catch.hpp>
#include <unsupported/Eigen/CXX11/Tensor>

using Point3 = Eigen::Matrix<float, 3, 1>;

template <int IP, int TP>
Eigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>> DistSq(Point3 const p)
{
  using KTensor = Eigen::TensorFixedSize<float, Eigen::Sizes<IP, IP, TP>>;
  using KArray = Eigen::TensorFixedSize<float, Eigen::Sizes<IP>>;
  using FixOne = Eigen::type2index<1>;
  using FixIn = Eigen::type2index<IP>;
  KArray indices;
  std::iota(indices.data(), indices.data() + IP, -IP / 2); // Note INTEGER division
  KTensor k;
  if constexpr (TP > 1) {
    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> rshX;
    constexpr Eigen::IndexList<FixOne, FixIn, FixIn> brdX;
    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> rshY;
    constexpr Eigen::IndexList<FixIn, FixOne, FixIn> brdY;
    constexpr Eigen::IndexList<FixOne, FixOne, FixIn> rshZ;
    constexpr Eigen::IndexList<FixIn, FixIn, FixOne> brdZ;
    auto const kx = (indices.constant(p[0]) - indices).square().reshape(rshX).broadcast(brdX);
    auto const ky = (indices.constant(p[1]) - indices).square().reshape(rshY).broadcast(brdY);
    auto const kz = (indices.constant(p[2]) - indices).square().reshape(rshZ).broadcast(brdZ);
    k = kx + ky + kz;
  } else {
    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> rshX;
    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> brdX;
    constexpr Eigen::IndexList<FixOne, FixIn, FixOne> rshY;
    constexpr Eigen::IndexList<FixIn, FixOne, FixOne> brdY;
    auto const kx = (indices.constant(p[0]) - indices).square().reshape(rshX).broadcast(brdX);
    auto const ky = (indices.constant(p[1]) - indices).square().reshape(rshY).broadcast(brdY);
    k = kx + ky;
  }
  return k;
}

TEST_CASE("DistSq")
{
  auto const z = Point3::Zero();

  BENCHMARK("3-1")
  {
    DistSq<3, 1>(z);
  };

  BENCHMARK("3-3")
  {
    DistSq<3, 3>(z);
  };

  BENCHMARK("5-1")
  {
    DistSq<5, 1>(z);
  };

  BENCHMARK("5-5")
  {
    DistSq<5, 5>(z);
  };
}


#include <iostream>
#include <functional>
#include <cstring>
#include <vector>
#include <utility>
#include <unordered_map>

#include <El.hpp>
#include <boost/mpi.hpp>

#define SKYLARK_NO_ANY
#include <skylark.hpp>

#include "utilities.hpp"
#include "parser.hpp"

/*******************************************/
namespace bmpi =  boost::mpi;
namespace skys =  skylark::sketch;
namespace skyb =  skylark::base;
/*******************************************/

/* These were declared as extern in utilities.hpp --- defining it here */
int int_params [NUM_INT_PARAMETERS];
char* chr_params[NUM_CHR_PARAMETERS];

/** Typedef DistMatrix and Matrix */
typedef std::vector<int> IntContainer;
typedef std::vector<double> DblContainer;
typedef El::DistMatrix<double, El::CIRC, El::CIRC> MatrixType;
typedef El::DistMatrix<double, El::VC, El::STAR> DistMatrixType;

int main (int argc, char** argv) {
    /* Initialize Elemental */
    El::Initialize (argc, argv);

    /* MPI sends argc and argv everywhere --- parse everywhere */
    parse_parameters (argc,argv);

    /* Initialize skylark */
    skyb::context_t context (int_params[RAND_SEED_INDEX]);

    /* Create matrices A and B */
    bmpi::communicator world;
    MPI_Comm mpi_world(world);
    El::Grid grid (mpi_world);
    El::DistMatrix<double, El::VR, El::STAR> A(grid);
    El::DistMatrix<double, El::VR, El::STAR> B(grid);

    /** Only randomization is supported for now */
    if (0==int_params[USE_RANDOM_INDEX]) {
        /** TODO: Read the entries! */
        std::cout << "We don't support reading --- yet --" << std::endl;
    } else {
        El::Uniform (A, int_params[M_INDEX], int_params[N_INDEX]);
        El::Uniform (B, int_params[M_INDEX], int_params[N_RHS_INDEX]);
    }

    /**
     * Depending on which sketch is requested, do the sketching.
     */
    if (0==strcmp("JLT", chr_params[TRANSFORM_INDEX]) ) {

        if (SKETCH_LEFT == int_params[SKETCH_DIRECTION_INDEX]) {

            /* 1. Create the sketching matrix */
            skys::JLT_t<DistMatrixType, MatrixType> JLT (int_params[M_INDEX],
                int_params[S_INDEX], context);

            /* 2. Create space for the sketched matrix */
            MatrixType sketch_A(int_params[S_INDEX], int_params[N_INDEX]);

            /* 3. Apply the transform */
            try {
                JLT.apply (A, sketch_A, skys::columnwise_tag());
            } catch (skylark::base::skylark_exception ex) {
                SKYLARK_PRINT_EXCEPTION_DETAILS(ex);
                SKYLARK_PRINT_EXCEPTION_TRACE(ex);
                errno = *(boost::get_error_info<skylark::base::error_code>(ex));
                std::cout << "Caught exception, exiting with error " << errno << std::endl;
                std::cout << skylark_strerror(errno) << std::endl;
                return errno;
            }

            /* 4. Print and see the result (if small enough) */
            if (int_params[S_INDEX] * int_params[N_INDEX] < 100 &&
                world.rank() == 0)
                El::Display(sketch_A);

            /** TODO: Do that same to B, and solve the system! */

        } else {
            std::cout << "We only have left sketching. Please retry" << std::endl;
        }
    } else if (0==strcmp("FJLT", chr_params[TRANSFORM_INDEX]) ) {
        if (SKETCH_LEFT == int_params[SKETCH_DIRECTION_INDEX]) {
            /* 1. Create the sketching matrix */
            skys::FJLT_t<DistMatrixType, MatrixType> FJLT (int_params[M_INDEX],
                int_params[S_INDEX], context);

            /* 2. Create space for the sketched matrix */
            MatrixType sketch_A(int_params[S_INDEX], int_params[N_INDEX]);

            /* 3. Apply the transform */
            FJLT.apply (A, sketch_A, skys::columnwise_tag());

            /* 4. Print and see the result */
            if (int_params[S_INDEX] * int_params[M_INDEX] < 100 &&
                world.rank() == 0)
                El::Display(sketch_A);

            /** TODO: Do that same to B, and solve the system! */

        }
    } else if (0==strcmp("CWT", chr_params[TRANSFORM_INDEX]) ) {
        if (SKETCH_LEFT == int_params[SKETCH_DIRECTION_INDEX]) {

            /* 1. Create the sketching matrix */
            skys::CWT_t<DistMatrixType, MatrixType>
                Sparse (int_params[M_INDEX], int_params[S_INDEX], context);

            /* 2. Create space for the sketched matrix */
            MatrixType sketch_A(int_params[S_INDEX], int_params[N_INDEX]);

            /* 3. Apply the transform */
            SKYLARK_BEGIN_TRY()
                Sparse.apply (A, sketch_A, skys::columnwise_tag());
            SKYLARK_END_TRY()
            SKYLARK_CATCH_AND_RETURN_ERROR_CODE();

            /* 4. Print and see the result */
            if (int_params[S_INDEX] * int_params[M_INDEX] < 100 &&
                world.rank() == 0)
                El::Display(sketch_A);

            /** TODO: Do that same to B, and solve the system! */

        }
    } else {
        std::cout << "We only have JLT/FJLT/Sparse sketching. Please retry" <<
            std::endl;
    }

    El::Finalize();

    return 0;

}


#pragma once
#include "rigid_body.hpp"

#include <Eigen/Geometry>

#include <autodiff/autodiff_types.hpp>
#include <utils/not_implemented_error.hpp>

namespace ipc::rigid {

template <typename T>
MatrixX<T>
RigidBody::world_vertices(const MatrixMax3<T>& R, const VectorMax3<T>& p) const
{
    return (vertices * R.transpose()).rowwise() + p.transpose();
}

template <typename T>
VectorMax3<T> RigidBody::world_vertex(
    const MatrixMax3<T>& R, const VectorMax3<T>& p, const int vertex_idx) const
{
    // compute X[i] = R(θ) * rᵢ + X
    return (vertices.row(vertex_idx) * R.transpose()) + p.transpose();
}

template <typename DScalar>
Eigen::MatrixXd RigidBody::world_vertices_diff(
    const PoseD& pose,
    long rb_v0_i,
    Eigen::MatrixXd& V,
    Eigen::MatrixXd& jac,
    Eigen::MatrixXd& hess) const
{
    // We will only use auto diff to compute the derivatives of the rotation
    // matrix.
    typedef AutodiffType<Eigen::Dynamic, /*maxN=*/3> Diff;
    // Activate autodiff with the correct number of variables.
    Diff::activate(rot_ndof());

    assert(rb_v0_i >= 0 && rb_v0_i <= V.rows() - vertices.rows());
    assert(V.cols() == dim());
    assert(rb_v0_i <= jac.rows() - vertices.size());
    assert(jac.cols() == ndof());
    bool compute_hess = hess.size() >= vertices.size() * ndof()
        && std::is_base_of<Diff::DDouble2, DScalar>();
    assert(
        !compute_hess || rb_v0_i <= (hess.size() / ndof()) - vertices.size());

    auto R = construct_rotation_matrix(
        VectorMax3<DScalar>(Diff::dTvars<DScalar>(0, pose.rotation)));
    MatrixX<DScalar> V_diff = vertices * R.transpose();

    for (int i = 0; i < V_diff.rows(); i++) {
        for (int j = 0; j < V_diff.cols(); j++) {
            V(rb_v0_i + i, j) = get_value(V_diff(i, j)) + pose.position(j);

            // Fill in gradient of V(i, j) (∈ R⁶ for 3D)
            int vij_flat = (rb_v0_i + i) * V.cols() + j;
            jac.row(vij_flat).head(pos_ndof()).setZero();
            jac(vij_flat, j) = 1; // ∇p V = I
            jac.row(vij_flat).tail(rot_ndof()) = get_gradient(V_diff(i, j));

            if (compute_hess) {
                // Fill in hessian of V(i, j) (∈ R⁶ˣ⁶ for 3D)
                // Hessian of position is zero
                // ∇²_p V = ∇_p∇_r V = ∇_r∇_p V = 0
                assert(hess.cols() == ndof());
                hess.middleRows(ndof() * vij_flat, ndof()).setZero();
                hess.block(
                    /*i=*/ndof() * vij_flat + pos_ndof(), /*j=*/pos_ndof(),
                    /*p=*/rot_ndof(), /*q=*/rot_ndof()) =
                    get_hessian(V_diff(i, j));
            }
        }
    }

    return V;
}

} // namespace ipc::rigid


/* test_bernoulli_distribution.cpp
 *
 * Copyright Steven Watanabe 2010
 * Distributed under the Boost Software License, Version 1.0. (See
 * accompanying file LICENSE_1_0.txt or copy at
 * http://www.boost.org/LICENSE_1_0.txt)
 *
 * $Id$
 *
 */

#include <boost/random/bernoulli_distribution.hpp>

#define BOOST_RANDOM_DISTRIBUTION boost::random::bernoulli_distribution<>
#define BOOST_RANDOM_ARG1 p
#define BOOST_RANDOM_ARG1_DEFAULT 0.5
#define BOOST_RANDOM_ARG1_VALUE 0.25

#define BOOST_RANDOM_DIST0_MIN false
#define BOOST_RANDOM_DIST0_MAX true
#define BOOST_RANDOM_DIST1_MIN false
#define BOOST_RANDOM_DIST1_MAX true

#define BOOST_RANDOM_TEST1_PARAMS (0.0)
#define BOOST_RANDOM_TEST1_MIN false
#define BOOST_RANDOM_TEST1_MAX false

#define BOOST_RANDOM_TEST2_PARAMS (1.0)
#define BOOST_RANDOM_TEST2_MIN true
#define BOOST_RANDOM_TEST2_MAX true

#include "test_distribution.ipp"


#include <armadillo>
#include "sargparse/Parameter.h"

namespace
{

arma::mat44 makeTransform(double dx, double dy, double dz, double alphaX, double alphaY, double alphaZ) {
	arma::mat44 translation = arma::eye(4, 4);
	translation(0, 3) = dx;
	translation(1, 3) = dy;
	translation(2, 3) = dz;

	/* align z axis to current joint this might incorporate two rotations (first the rotation around x-axis is performed, then around the y axis and around the z axis) */
	arma::mat44 rotX = arma::eye(4, 4);
	arma::mat44 rotY = arma::eye(4, 4);
	arma::mat44 rotZ = arma::eye(4, 4);

	if (std::abs(alphaX) >= std::numeric_limits<double>::epsilon())
	{
		const double cRotX = std::cos(alphaX);
		const double sRotX = std::sin(alphaX);
		rotX(1, 1) = cRotX;
		rotX(1, 2) = -sRotX;
		rotX(2, 1) = sRotX;
		rotX(2, 2) = cRotX;
	}

	if (std::abs(alphaY) >= std::numeric_limits<double>::epsilon())
	{
		const double cRotY = std::cos(alphaY);
		const double sRotY = std::sin(alphaY);
		rotY(0, 0) = cRotY;
		rotY(0, 2) = sRotY;
		rotY(2, 0) = -sRotY;
		rotY(2, 2) = cRotY;
	}

	if (std::abs(alphaZ) >= std::numeric_limits<double>::epsilon())
	{
		const double cRotZ = std::cos(alphaZ);
		const double sRotZ = std::sin(alphaZ);
		rotZ(0, 0) = cRotZ;
		rotZ(0, 1) = -sRotZ;
		rotZ(1, 0) = sRotZ;
		rotZ(1, 1) = cRotZ;
	}

	return translation * rotX * rotY * rotZ;
}

arma::mat44 transform = arma::eye(4,4);

sargp::Parameter<double> rotX {1., "rotX", "how much to rotate around the x axis (degrees)", []{ transform = makeTransform(0, 0, 0, *rotX * M_PI/180., 0, 0) * transform; }};
sargp::Parameter<double> rotY {1., "rotY", "how much to rotate around the y axis (degrees)", []{ transform = makeTransform(0, 0, 0, 0, *rotY * M_PI/180., 0) * transform; }};
sargp::Parameter<double> rotZ {1., "rotZ", "how much to rotate around the z axis (degrees)", []{ transform = makeTransform(0, 0, 0, 0, 0, *rotZ * M_PI/180.) * transform; }};

sargp::Parameter<double> movX {1., "movX", "how much to move along the x axis (degrees)", []{ transform = makeTransform(*movX, 0, 0, 0, 0, 0) * transform; }};
sargp::Parameter<double> movY {1., "movY", "how much to move along the y axis (degrees)", []{ transform = makeTransform(0, *movY, 0, 0, 0, 0) * transform; }};
sargp::Parameter<double> movZ {1., "movZ", "how much to move along the z axis (degrees)", []{ transform = makeTransform(0, 0, *movZ, 0, 0, 0) * transform; }};

sargp::Parameter<double> scale {1., "scale", "scale the STL", []{ transform = arma::mat44{{*scale, 0, 0, 0}, {0, *scale, 0, 0}, {0, 0, *scale, 0}, {0, 0, 0, 1}} * transform;}};

sargp::Parameter<double> scaleX {1., "scaleX", "scale the x components of the STL", []{ transform = arma::mat44{{*scaleX, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} * transform;}};
sargp::Parameter<double> scaleY {1., "scaleY", "scale the y components of the STL", []{ transform = arma::mat44{{1, 0, 0, 0}, {0, *scaleY, 0, 0}, {0, 0, 1, 0}, {0, 0, 0, 1}} * transform;}};
sargp::Parameter<double> scaleZ {1., "scaleZ", "scale the z components of the STL", []{ transform = arma::mat44{{1, 0, 0, 0}, {0, 1, 0, 0}, {0, 0, *scaleZ, 0}, {0, 0, 0, 1}} * transform;}};

}

arma::mat44 const& getTransform() {
    return transform;
}


#include <cmath>
#include <complex>
#include <vector>
#include <iostream>

#include <Eigen/Geometry>
#include <Magick++.h>

#include "Constants.h"
#include "ImageGenerator.h"
#include "FractalInstance.h"

using namespace std;
using namespace Eigen;
using namespace Magick;

vector<FractalInstance> fractals;

// user literal for millions (i.e. 1_m = 10000000)
constexpr unsigned long long operator "" _m(unsigned long long l) {
  return l * 1000 * 1000;
}

int main(int argc, char** argv)
{
  InitializeMagick(*argv);

  auto theta(0.0);
  auto delta(2 * M_PI / NUM_FRAMES);

  auto offset1(0.0);
  auto offset2(0.0);
  auto offset3(0.0);

  Vector3f axis1(1, 0, 0);
  Vector3f axis2(0, 1, 0);
  Vector3f axis3(0, 0, 1);

  axis1.normalize();
  axis2.normalize();
  axis3.normalize();

  Vector3f vec(-1/6.0, 1/120.0, -1/5040.0);
  auto vec1(vec);
  auto vec2(vec);
  auto vec3(vec);

  FractalInstance::num_points = 10_m;
  FractalInstance::complex_range = 6.0;
  FractalInstance::default_iterations = 1e2;

  /* FractalInstance fi( */
  /*   {1, vec1.x(), vec1.y(), vec1.z()}, */
  /*   {1, 2, 4, 6}, */
  /*   {0, 0, 3.0, 3.0} */
  /* ); */

  /* ImageGenerator::generate(fi); */

  for (auto frame(1); frame <= NUM_FRAMES; ++frame)
  {
    FractalInstance rfi(
      {1, vec1.x(), vec1.y(), vec1.z()},
      {1, 2, 4, 6},
      {0, 0, 4.0, 4.0}
    );

    FractalInstance gfi(
      {1, vec2.x(), vec2.y(), vec2.z()},
      {1, 2, 4, 6},
      {0, 0, 4.0, 4.0}
    );

    FractalInstance bfi(
      {1, vec3.x(), vec3.y(), vec3.z()},
      {1, 2, 4, 6},
      {0, 0, 4.0, 4.0}
    );

    ImageGenerator::generate({rfi, gfi, bfi}, frame);

    theta += delta;
    auto t1(AngleAxis<float>(theta + offset1, axis1));
    vec1 = t1 * vec;
    auto t2(AngleAxis<float>(theta + offset2, axis2));
    vec2 = t2 * vec;
    auto t3(AngleAxis<float>(theta + offset3, axis3));
    vec3 = t3 * vec;
  }

  return 0;
}


//////////////////////////////////////////////////////////////////////////////////
// distribution::survival::models::importance_sampling::cg.hpp 					//
//                                                                           	//
//  Copyright 2009 Erwann Rogard. Distributed under the Boost                	//
//  Software License, Version 1.0. (See accompanying file                    	//
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)         	//
//////////////////////////////////////////////////////////////////////////////////
#ifndef BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_CG_HPP_ER_2009
#define BOOST_STATISTICS_DETAIL_DISTRIBUTION_SURVIVAL_MODELS_IMPORTANCE_SAMPLING_CG_HPP_ER_2009
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>
#include <boost/accumulators/framework/extractor.hpp>
#include <boost/statistics/detail/accumulator/statistics/proportion_less_than.hpp>
#include <boost/statistics/detail/importance_sampling/statistics/percentage_effective_sample_size.hpp>

namespace boost{
namespace statistics{
namespace detail{
namespace distribution{
namespace survival{

	// cook-gelman statistic
    template<typename It_t,typename T>
    T cg(It_t b_target,It_t e_target,const T& threshold){

        typedef accumulator::tag::proportion_less_than tag_plt_;
        typedef boost::accumulators::stats<tag_plt_> stats_;
        typedef boost::accumulators::accumulator_set<T,stats_> acc_;
        acc_ a = std::for_each(
            b_target,
            e_target,
            acc_(( accumulator::keyword::threshold = threshold ))
        );
		return boost::accumulators::extract_result<tag_plt_>(a);
	}

}// survival
}// distribution
}// detail
}// statistics
}// boost

#endif


//=======================================================================
// Copyright 2001 Jeremy G. Siek, Andrew Lumsdaine, Lie-Quan Lee,
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <boost/config.hpp>
#include <vector>
#include <deque>
#include <iostream>
#include <boost/graph/topological_sort.hpp>
#include <boost/graph/adjacency_list.hpp>
int
main()
{
  using namespace boost;
  const char *tasks[] = {
    "pick up kids from school",
    "buy groceries (and snacks)",
    "get cash at ATM",
    "drop off kids at soccer practice",
    "cook dinner",
    "pick up kids from soccer",
    "eat dinner"
  };
  const int n_tasks = sizeof(tasks) / sizeof(char *);

  adjacency_list < listS, vecS, directedS > g(n_tasks);

  add_edge(0, 3, g);
  add_edge(1, 3, g);
  add_edge(1, 4, g);
  add_edge(2, 1, g);
  add_edge(3, 5, g);
  add_edge(4, 6, g);
  add_edge(5, 6, g);

  std::deque < int >topo_order;

  topological_sort(g, std::front_inserter(topo_order),
                   vertex_index_map(identity_property_map()));

  int n = 1;
  for (std::deque < int >::iterator i = topo_order.begin();
       i != topo_order.end(); ++i, ++n)
    std::cout << tasks[*i] << std::endl;

  return EXIT_SUCCESS;
}


/*
 *  Created by Andrea Bedini on 21/Nov/2008.
 *  Copyright 2008-2014 Andrea Bedini <andrea@andreabedini.com>
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *
 */

#ifndef POLYNOMIAL_HPP_
#define POLYNOMIAL_HPP_

#include <boost/operators.hpp>

#include <iosfwd>
#include <vector>

template<typename T>
class polynomial
  : boost::ring_operators1< polynomial<T>
  , boost::ring_operators2< polynomial<T>, T
  , boost::equality_comparable< polynomial<T>
  , boost::left_shiftable<polynomial<T>, unsigned int
  > > > >
{
  /// Coefficients { c_0; ...; c_n } :
  std::vector<T> impl_;

  /// remove leading zero coefficients
  void normalize()
  {
    std::size_t i = order();
    // do not remove the constant term, even if it's zero
    while (impl_[i] == 0 and i > 1)
      i--;
    order(i);
  }

public:
  // default constructor
  explicit polynomial(const T& a = T(0))
    : impl_{a}
  {
  }

  polynomial(std::initializer_list<T> list)
    : impl_(list)
  {
  }

  // copy constructor
  polynomial(polynomial<T> const& rhs)
    : impl_(rhs.impl_)
  {
  }

  // move constructor
  polynomial(polynomial<T>&& rhs)
    : impl_(std::move(rhs.impl_))
  {
  }

  // assignemnt
  polynomial<T>& operator=(polynomial<T> const& rhs)
  {
    impl_ = rhs.impl_;
    return *this;
  }

  polynomial<T>& operator=(polynomial<T>&& rhs)
  {
    impl_ = std::move(rhs.impl_);
    return *this;
  }

  // conversions
  template<typename T2>
  friend class polynomial;

  template<class T2>
  explicit polynomial(T2 const& a)
    : impl_{T(a)}
  {
  }

  template<class T2>
  explicit polynomial(polynomial<T2> const& rhs)
  {
    for (auto const& c : rhs.impl_) {
      impl_.push_back(T(c));
    }
  }
  template<class T2>
  polynomial<T>& operator=(T2 const& rhs)
  {
    impl_ = {T(rhs)};
    return *this;
  }

  template<class T2>
  polynomial<T>& operator=(polynomial<T2> const& rhs)
  {
    impl_.clear();
    for (auto const& c : rhs.impl_) {
      impl_.push_back(T(c));
    }
    return *this;
  }

  std::size_t order() const
  {
    return impl_.size() - 1;
  }

  void order(std::size_t n)
  {
    impl_.resize(n + 1);
  }

  // iterators
  decltype(impl_.begin()) begin() { return impl_.begin(); }
  decltype(impl_.end())   end()   { return impl_.end(); }

  decltype(impl_.cbegin()) begin() const { return impl_.begin(); }
  decltype(impl_.cend())   end()   const { return impl_.end(); }

  // indexing
  T& operator[](std::size_t i)
  {
    return impl_[i];
  }

  const T& operator[](std::size_t i) const
  {
    return impl_[i];
  }

  // comparison
  bool operator==(const polynomial<T>& rhs) const
  {
    return impl_ == rhs.impl_;
  }

  /// arithmetic
  polynomial<T>& operator+=(const T& rhs)
  {
    impl_[0] += rhs;
    return *this;
  }

  polynomial<T>& operator-=(const T& rhs)
  {
    impl_[0] -= rhs;
    return *this;
  }

  polynomial<T>& operator*=(const T& rhs)
  {
    for (auto& c : impl_)
      c *= rhs;
    normalize();
    return *this;
  }

  polynomial<T>& operator+=(const polynomial<T>& rhs)
  {
    order(std::max(order(), rhs.order()));
    for (std::size_t i = 0; i <= rhs.order(); i++)
      impl_[i] += rhs.impl_[i];
    normalize();
    return *this;
  }

  polynomial<T>& operator-=(const polynomial<T>& rhs)
  {
    order(std::max(order(), rhs.order()));
    for (std::size_t i = 0; i <= rhs.order(); i++)
      impl_[i] -= rhs.impl_[i];
    normalize();
    return *this;
  }

  polynomial<T>& operator*=(const polynomial<T>& rhs)
  {
    polynomial<T> product;
    product.order(order() + rhs.order());
    for (std::size_t i = 0; i <= order(); i++) {
      for (std::size_t j = 0; j <= rhs.order(); j++)
        product.impl_[i + j] += impl_[i] * rhs.impl_[j];
    }
    impl_.swap(product.impl_);
    return *this;
  }

  // left_shiftable
  polynomial<T>& operator<<=(std::size_t rhs)
  {
    impl_.insert(impl_.begin(), rhs, T(0));
    return *this;
  }

  const polynomial<T> operator-() const
  {
    polynomial<T> y;
    y.order(order());
    for (std::size_t i = 0; i <= order(); i++)
      y.impl_[i] = -impl_[i];
    return y;
  }

};

template<class T>
std::ostream& operator<<(std::ostream& o, const polynomial<T>& p)
{
  for (auto i = 0u; i <= p.order(); i++) {
    if (p[i] == T(0))
      continue;
    auto c = p[i];
    if (c < 0) {
      o << "- ";
      c = -c;
    } else if (i > 0) {
      o << "+ ";
    }
    if (c != 1 or i == 0) {
      o << c << " ";
    }
    if (i > 0) {
      o << "x";
      if (i > 1)
        o << "^" << i;
      o << " ";
    }
  }
  return o;
}

#endif // POLYNOMIAL_HPP_


#include "LogPoissonSplit.hh"
#include "TypeClasses.hh"
using namespace TypeClasses;
#include "TMath.h"
#include <Eigen/Core>
#include <cmath>

using namespace Eigen;

LogPoissonSplit::LogPoissonSplit(bool ln_approx) {
  transformation_("poisson_const")
    .output("const")
    .types(new CheckSameTypesT<double>({0,-1}, "shape"))
    .types(&LogPoissonSplit::checkTypesConst)
    .func(ln_approx ? &LogPoissonSplit::calcPoissonConstApprox : &LogPoissonSplit::calcPoissonConst)
    ;

  transformation_("poisson")
    .output("poisson")
    .types(&LogPoissonSplit::checkTypes)
    .func(&LogPoissonSplit::calcPoisson)
    ;

  auto poisson = transformations["poisson"];
  auto out = transformations["poisson_const"].outputs[0];
  poisson.input(out);

  m_transform = t_["poisson"];
}

void LogPoissonSplit::add(SingleOutput &theory, SingleOutput &data) {
  auto poisson_const = transformations["poisson_const"];
  poisson_const.input(data);

  auto poisson = transformations["poisson"];
  poisson.input(theory);
  poisson.input(data);
}

void LogPoissonSplit::checkTypesConst(TypesFunctionArgs fargs) {
  auto& rets=fargs.rets;
  rets[0] = DataType().points().shape(1);
}

void LogPoissonSplit::checkTypes(TypesFunctionArgs fargs) {
  auto& args=fargs.args;
  auto& rets=fargs.rets;
  if (args.size()%2 != 1) {
    throw args.undefined();
  }
  if (args[0].kind!=DataKind::Undefined && args[0].size() != 1) {
    throw rets.error(rets[0], "lnPoisson const term size should be 1");
  }
  for (size_t i = 1; i < args.size(); i+=2) {
    if (args[i+1].shape != args[i+0].shape) {
      throw rets.error(rets[0], "data and theory have different shape");
    }
  }
  rets[0] = DataType().points().shape(1);
}

double lnPi(double num)
{
  return TMath::LnGamma(num + 1);
}

double lnFactorialStirling(double x)
{
  if (!(x == 0.0 || x == 1.0))
  {
    return x * std::log(x);
  }
  else
    return 0;
}

void LogPoissonSplit::calcPoisson(FunctionArgs fargs) {
  /***************************************************************************
   *       Formula: log of Poisson
   *        -2 * ln(Poisson) =
   *             2 * sum(theory_j - data_i * log(theory_j) + ln data_i! )
   *
   ****************************************************************************/
  auto& args=fargs.args;

  double res=args[0].arr(0);
  for (size_t i = 1; i < args.size(); i+=2) {
    auto& theory=args[i+0].arr;
    auto& data=args[i+1].arr;
    res += (theory - data*theory.log()).sum();
  }
  fargs.rets[0].arr(0) = 2*res;
}

void LogPoissonSplit::calcPoissonConstApprox(FunctionArgs fargs) {
  /***************************************************************************
   *       Formula: log of Poisson
   *        -2 * ln(Poisson) =
   *            -2 * sum(data_i * log(theory_j) -  theory_j  - ln data_i! )
   *
   *       Compute: ln data_i! ≈ data_i ln data_i
   *
   ****************************************************************************/
  auto& args=fargs.args;

  double res(0.0);
  for (size_t i = 0; i < args.size(); ++i) {
    res += (args[i].arr.unaryExpr(&lnFactorialStirling)).sum();
  }
  fargs.rets[0].arr(0) = res;
}

void LogPoissonSplit::calcPoissonConst(FunctionArgs fargs) {
  /***************************************************************************
   *       Formula: log of Poisson
   *
   *        -2 * ln(Poisson) =
   *               -2 * sum(data_i * log(theory_j) -  theory_j  - ln data_i! )
   *
   *       Compute: ln data_i!
   *
   ****************************************************************************/
  auto& args=fargs.args;

  double res(0.0);
  for (size_t i = 0; i < args.size(); ++i) {
    res += args[i].arr.unaryExpr(&lnPi).sum();
  }
  fargs.rets[0].arr(0) = res;
}