// Copyright (C) 2019 EDF
// All Rights Reserved
// This code is published under the GNU Lesser General Public License (GNU LGPL)
#include "StOpt/regression/LocalAdaptCellRegression.h"

using namespace std;
using namespace Eigen;

namespace StOpt
{
LocalAdaptCellRegression::LocalAdaptCellRegression(const ArrayXi   &p_nbMesh,
        const bool &p_bRotationAndRecale):
    BaseRegression(false, p_bRotationAndRecale),
    m_nbMesh(p_nbMesh),
    m_nbMeshTotal(m_nbMesh.prod()) {}

LocalAdaptCellRegression::LocalAdaptCellRegression(const bool &p_bZeroDate,
        const ArrayXXd  &p_particles,
        const ArrayXi   &p_nbMesh,
        const bool &p_bRotationAndRecale):
    BaseRegression(p_bZeroDate, p_particles, p_bRotationAndRecale),
    m_nbMesh(p_nbMesh),
    m_nbMeshTotal(m_nbMesh.prod()),
    m_simToCell(p_particles.cols())
{}

LocalAdaptCellRegression::LocalAdaptCellRegression(const bool &p_bZeroDate,
        const  ArrayXi &p_nbMesh,
        const  Array< array< double, 2>, Dynamic, Dynamic >   &p_mesh,
        const   ArrayXd &p_meanX,
        const   ArrayXd   &p_etypX, const   MatrixXd   &p_svdMatrix, const  bool &p_bRotationAndRecale) :
    BaseRegression(p_bZeroDate, p_meanX,  p_etypX,  p_svdMatrix, p_bRotationAndRecale), m_nbMesh(p_nbMesh), m_mesh(p_mesh)
{
    if ((!m_bZeroDate) && (p_nbMesh.size() > 0))
    {
        m_nbMeshTotal = m_nbMesh.prod();

        if (!p_bRotationAndRecale)
        {
            m_meanX = ArrayXd::Zero(p_nbMesh.size());
            m_etypX = ArrayXd::Constant(p_nbMesh.size(), 1.);
            m_svdMatrix = MatrixXd::Identity(p_nbMesh.size(), p_nbMesh.size());
        }
    }
    else
        m_nbMeshTotal = 1;
}

LocalAdaptCellRegression::LocalAdaptCellRegression(const LocalAdaptCellRegression   &p_object) : BaseRegression(p_object), m_nbMesh(p_object.getNbMesh()),
    m_nbMeshTotal(p_object.getNbMeshTotal()), m_mesh(p_object.getMesh()),
    m_simToCell(p_object.getSimToCell()),
    m_simulBelongingToCell(p_object.getSimulBelongingToCell())
{
}


void  LocalAdaptCellRegression::evaluateSimulBelongingToCell()
{
    int nbCells = getNumberOfCells();
    m_simulBelongingToCell.resize(nbCells);
    if (m_particles.cols() > 0)
    {
        for (int icell = 0; icell < nbCells; ++icell)
        {
            m_simulBelongingToCell[icell] = make_shared< vector< int> >();
            m_simulBelongingToCell[icell]->reserve(2 * m_particles.cols() / nbCells);
        }
        for (int is = 0; is <  m_simToCell.size(); ++is)
            m_simulBelongingToCell[m_simToCell(is)]->push_back(is);
    }
    else
    {
        m_simulBelongingToCell[0] = make_shared< vector< int> >(1);
        (*m_simulBelongingToCell[0])[0] = 0;
    }
}

}
