//== INCLUDES =================================================================


#include "Energy_term_pca_landmarks.h"
#include <graphene/surface_mesh/algorithms/templatefitting/utility/my_helper.h>

#include "../settings.h"


//== NAMESPACE ================================================================


namespace graphene {
namespace surface_mesh {


//== IMPLEMENTATION ===========================================================


Energy_term_pca_landmarks::
Energy_term_pca_landmarks(const Energy_term_data& energy_term_data, double weight)
: Energy_term(energy_term_data, weight, "PCA Landmarks")
{
}


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


Energy_term_pca_landmarks::
~Energy_term_pca_landmarks()
{}


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


void
Energy_term_pca_landmarks::
pre_minimize_action()
{
    // skin landmarks from Scanpose to TPose

    // mesh: energy_term_data_.template_mesh
    // pointset: energy_term_data_.point_set
    // landmarks: energy_term_data_.landmarks_manager
    // skinned landmarks (output): skinned_landmarks_pointset_
    // inverse_transform: true, i.e., skin from Scanpose to TPose
    // skinning mode: linear blend skinning
    skin_pointset_landmarks(energy_term_data_.template_mesh,
                            energy_term_data_.point_set,
                            energy_term_data_.landmarks_manager,
                            skinned_landmarks_pointset_,
                            energy_term_data_.landmark_property_name,
                            true);
}


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


double
Energy_term_pca_landmarks::
evaluate()
{
    const Landmarks_manager& landmarks_manager = energy_term_data_.landmarks_manager;
    const PCA& pca = energy_term_data_.pca;
    const Point_set* point_set = energy_term_data_.point_set;
    const Surface_mesh* template_mesh = energy_term_data_.template_mesh;

    const std::string& lm_prop_name = energy_term_data_.landmark_property_name;
    const std::string& lm_weight_prop_name = energy_term_data_.landmark_weight_property_name;

    std::vector<Point> lm_ps;
    lm_ps.resize(point_set->landmarks_.size());
    unsigned int i = 0;
    for (auto v : point_set->landmarks_)
    {
        lm_ps[i] = point_set->points_[v];
        ++i;
    }
    Surface_mesh::Mesh_property< std::vector<Surface_mesh::Vertex> > lm_prop = template_mesh->get_mesh_property< std::vector<Surface_mesh::Vertex> >(lm_prop_name);
    if (!lm_prop)
    {
        std::cerr << "Energy_term_pca_landmarks::evaluate(): [ERROR] !lm_prop." << std::endl;
        return DBL_MAX;
    }
    const std::vector<Surface_mesh::Vertex>& tm_landmarks = lm_prop[0];
    Surface_mesh::Vertex_property<double> local_landmark_weight = template_mesh->get_vertex_property<double>(lm_weight_prop_name);

    // check dimensions
    if (tm_landmarks.size() != lm_ps.size())
    {
        std::cerr << "Energy_term_pca_landmarks::evaluate(): [ERROR] Number of landmarks do not match." << std::endl;
        return DBL_MAX;
    }

    double error_reg_pca_ff = 0.0;

    const unsigned int L(lm_ps.size());

    double local_weight = 1.0;
    for (unsigned int i = 0; i < L; ++i)
    {
        if (local_landmark_weight)
        {
            local_weight = local_landmark_weight[tm_landmarks[i]];
            if (local_weight < 1e-5)
                continue;
            local_weight = sqrt(local_weight);
        }

        const int idx = tm_landmarks[i].idx();

        double mi_x = pca.m_pca_(3*idx    );
        double mi_y = pca.m_pca_(3*idx + 1);
        double mi_z = pca.m_pca_(3*idx + 2);
        const Point  mi(mi_x, mi_y, mi_z); // TODO EVTL. SCHNELLER ?!

        Point  Pid(0.0, 0.0, 0.0);
        for (unsigned int j = 0; j < 3; ++j)
        {
            for (unsigned int dcount = 0; dcount < pca.dim_pca_model_; ++dcount)
            {
                Pid[j] += pca.P_pca_(3*idx + j, dcount) * pca.d_pca_(dcount);
            }
        }

        double u = norm( Pid + mi - lm_ps[i] );
        if ( robustness_parameters_.solver_type == SOLVER_TYPE_L2 )
        {
            error_reg_pca_ff += u * u * local_weight;
        }
        else if ( robustness_parameters_.solver_type == SOLVER_TYPE_L1 )
        {
            error_reg_pca_ff += std::pow( u, robustness_parameters_.parameter) * local_weight;
        }
        else if ( robustness_parameters_.solver_type == SOLVER_TYPE_HUBER )
        {
            double huber_thr = robustness_parameters_.parameter;
            if ( u > huber_thr )
            {
                error_reg_pca_ff += ( huber_thr*u - huber_thr*huber_thr/2.0 ) * local_weight;
            }
            else
            {
                error_reg_pca_ff += ( u*u/2.0 ) * local_weight;
            }
        }
        else if ( robustness_parameters_.solver_type == SOLVER_TYPE_GEMANMCCLURE )
        {
            double scale_parameter = robustness_parameters_.parameter;
//                error_reg_pca_ff += ( u*u / (scale_parameter*scale_parameter + u*u) ); // VERSION 2
              error_reg_pca_ff += ( ( u*u / ( 2.0 * ( 1.0 + (u*u/(scale_parameter*scale_parameter)) ) ) ) ) * local_weight; // VERSION 3
        }
        else // default to L2
        {
            error_reg_pca_ff += u * u * local_weight;
        }
    }
    error_reg_pca_ff *= (weight_ / L);

    return error_reg_pca_ff;
}


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


void
Energy_term_pca_landmarks::
add_rows_big_lse( std::vector<Tripl>& coeffs,
                  Eigen::VectorXd& b,
                  unsigned int& r )
{
    //std::cout << "[INFO] Energy_term_pca_landmarks::add_rows_big_lse(): weight_: " << weight_ << std::endl;

    const Column_offsets& column_offsets = energy_term_data_.column_offsets;
    const unsigned int offset_nrd_w_pca = column_offsets.offset_nrd_w_pca;
    const PCA& pca = energy_term_data_.pca;
    const Landmarks_manager& landmarks_manager = energy_term_data_.landmarks_manager;
    const geometry::Point_set* point_set = energy_term_data_.point_set;
    const Surface_mesh* template_mesh = energy_term_data_.template_mesh;

    const std::string& lm_prop_name = energy_term_data_.landmark_property_name;
    const std::string& lm_weight_prop_name = energy_term_data_.landmark_weight_property_name;

    std::vector<Point> lm_ps;
    lm_ps.resize(point_set->landmarks_.size());
    unsigned int i = 0;
    for (auto v : point_set->landmarks_)
    {
        lm_ps[i] = point_set->points_[v];
        ++i;
    }
    Surface_mesh::Mesh_property< std::vector<Surface_mesh::Vertex> > lm_prop = template_mesh->get_mesh_property< std::vector<Surface_mesh::Vertex> >(lm_prop_name);
    if (!lm_prop)
    {
        std::cerr << "Energy_term_pca_landmarks::add_rows_big_lse(): [ERROR] !lm_prop." << std::endl;
        return;
    }
    const std::vector<Surface_mesh::Vertex>& tm_landmarks = lm_prop[0];

    double local_weight = 1.0;
    Surface_mesh::Vertex_property<double> local_landmark_weight = template_mesh->get_vertex_property<double>(lm_weight_prop_name);

    // check dimensions
    if (tm_landmarks.size() != lm_ps.size())
    {
        std::cerr << "Energy_term_pca_landmarks::add_rows_big_lse(): [ERROR] Number of landmarks do not match." << std::endl;
        return;
    }

    const unsigned int L(lm_ps.size());


    //choose either the skinnend landmarks or the "normal" ones based on whether skinned landmarks exist or not
    const std::vector<Point>& landmarks_pointset = skinned_landmarks_pointset_.empty() ? lm_ps : skinned_landmarks_pointset_;

    const double weight_model = sqrt(weight_ / L);
    //std::cout << "[INFO] Energy_term_pca_landmarks::add_rows_big_lse(): weight_model: " << weight_model << std::endl;
    for (unsigned int i = 0; i < L; ++i)
    {
        int idx = tm_landmarks[i].idx();

        if (local_landmark_weight)
        {
            local_weight = local_landmark_weight[tm_landmarks[i]];
            if (local_weight < 1e-5)
            {
                continue;
            }
            local_weight = sqrt(local_weight);
        }

        // right hand side
        b(r) = local_weight * weight_model * ( landmarks_pointset[i][0] - pca.m_pca_(3*idx + 0) );

        // begin_row
        for (unsigned int dcount = 0; dcount < pca.dim_pca_model_; ++dcount)
        {
            coeffs.push_back( Tripl(r, offset_nrd_w_pca + dcount, pca.P_pca_(3*idx, dcount) * local_weight * weight_model) ); // d's
        }
        ++r;

        // right hand side
        b(r) = local_weight * weight_model * ( landmarks_pointset[i][1] - pca.m_pca_(3*idx + 1) );

        // begin_row
        for (unsigned int dcount = 0; dcount < pca.dim_pca_model_; ++dcount)
        {
            coeffs.push_back( Tripl(r, offset_nrd_w_pca + dcount, pca.P_pca_(3*idx + 1, dcount) * local_weight * weight_model) ); // d's
        }
        ++r;

        // right hand side
        b(r) = local_weight * weight_model * ( landmarks_pointset[i][2] - pca.m_pca_(3*idx + 2) );

        // begin_row
        for (unsigned int dcount = 0; dcount < pca.dim_pca_model_; ++dcount)
        {
            coeffs.push_back( Tripl(r, offset_nrd_w_pca + dcount, pca.P_pca_(3*idx + 2, dcount) * local_weight * weight_model) ); // d's
        }
        ++r;
    }
}

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


unsigned int
Energy_term_pca_landmarks::
n_rows_big_sle()
{
    //std::cout << "[INFO] Energy_term_pca_landmarks::n_rows_big_sle()" << std::endl;
    const std::string& lm_prop_name = energy_term_data_.landmark_property_name;
    const std::string& lm_weight_prop_name = energy_term_data_.landmark_weight_property_name;

    unsigned int c=0;
    const Surface_mesh* template_mesh = energy_term_data_.template_mesh;
    Surface_mesh::Mesh_property< std::vector<Surface_mesh::Vertex> > lm_prop = template_mesh->get_mesh_property< std::vector<Surface_mesh::Vertex> >(lm_prop_name);
    if (lm_prop)
    {
        const std::vector<Surface_mesh::Vertex>& tm_landmarks = lm_prop[0];
        Surface_mesh::Vertex_property<double> local_landmark_weight = template_mesh->get_vertex_property<double>(lm_weight_prop_name);

        if (local_landmark_weight)
        {
            for (size_t i=0; i < tm_landmarks.size(); ++i)
            {
                if (local_landmark_weight[tm_landmarks[i]] >= 1e-5)
                {
                    ++c;
                }
                else
                {
                    //std::cout << "landmark ignored " << tm_landmarks[i] << std::endl;
                }
            }
        }
        else
        {
            c = (unsigned int) tm_landmarks.size();
        }
    }

    return c*3;
}


//=============================================================================
} // namespace surface_mesh
} // namespace graphene
//=============================================================================
