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

using namespace std;
using namespace Eigen;

namespace StOpt
{
LocalDiscrLastDimRegression::LocalDiscrLastDimRegression(const ArrayXi   &p_nbMesh,
        const bool &p_bRotationAndRecale):
    LocalAdaptCellRegression(p_nbMesh, p_bRotationAndRecale) {}

LocalDiscrLastDimRegression::LocalDiscrLastDimRegression(const bool &p_bZeroDate,
        const ArrayXXd  &p_particles,
        const ArrayXi   &p_nbMesh,
        const bool &p_bRotationAndRecale):
    LocalAdaptCellRegression(p_bZeroDate, p_particles, p_nbMesh, p_bRotationAndRecale)
{
    if ((!m_bZeroDate) && (p_nbMesh.size() != 0))
    {
        meshCalculationLocalRegressionDiscrLastDim(m_particles, m_nbMesh, m_simToCell, m_mesh, m_mesh1D);
    }
    else
    {
        m_simToCell.setConstant(0);
        m_nbMeshTotal = 1;
    }
}

LocalDiscrLastDimRegression::LocalDiscrLastDimRegression(const bool &p_bZeroDate,
        const  ArrayXi &p_nbMesh,
        const  Array< array< double, 2>, Dynamic, Dynamic >   &p_mesh,
        const vector< shared_ptr< ArrayXd > > &p_mesh1D, const   ArrayXd &p_meanX,
        const   ArrayXd   &p_etypX, const   MatrixXd   &p_svdMatrix, const  bool &p_bRotationAndRecale) :
    LocalAdaptCellRegression(p_bZeroDate,  p_nbMesh, p_mesh, p_meanX,  p_etypX,  p_svdMatrix, p_bRotationAndRecale)
{
    if ((!m_bZeroDate) && (p_mesh1D.size() > 0))
    {
        m_mesh1D = p_mesh1D;
    }
}

LocalDiscrLastDimRegression::LocalDiscrLastDimRegression(const LocalDiscrLastDimRegression   &p_object) : LocalAdaptCellRegression(p_object)
{
    const vector< shared_ptr< ArrayXd > > &mesh1D = p_object.getMesh1D();
    m_mesh1D.resize(mesh1D.size());
    for (size_t i = 0 ; i < m_mesh1D.size(); ++i)
        m_mesh1D[i] = make_shared< ArrayXd>(*mesh1D[i]);
}

int LocalDiscrLastDimRegression:: particleToMesh(const ArrayXd &p_oneParticle)const
{
    int nBase = p_oneParticle.size() + 1;
    int iCell = 0 ;
    int idecCell = 1;
    for (int id = 0 ; id < nBase - 1 ; id++)
    {
        int iMesh = 1 ;
        while ((p_oneParticle(id) > (*m_mesh1D[id])(iMesh)) && (iMesh < m_mesh1D[id]->size() - 1)) iMesh++;
        iCell += (iMesh - 1) * idecCell;
        idecCell *= m_mesh1D[id]->size() - 1;
    }
    return iCell ;
}

}
