// Copyright (C) 2016 EDF
// All Rights Reserved
// This code is published under the GNU Lesser General Public License (GNU LGPL)
#ifndef LOCALCONSTMATRIXOPERATION_H
#define LOCALCONSTMATRIXOPERATION_H
/** \file localConstMatrixOperation.h
 *  \brief  Develop the normal operators for regression, permits inversion of \f$ A^tA  x = A^t b \f$  and reconstruct the solution
 *  \author Xavier Warin
 */
#include <vector>
#include <array>
#include <Eigen/Dense>
#include "StOpt/core/grids/InterpolatorSpectral.h"

namespace StOpt
{
/**
 * \addtogroup LocalConst
 * @{
 */
/// \brief Regression matrix calculation for local constant functions per mesh
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_nbCell      Number of cells
/// \return             Diagonal regression matrix to calculate
Eigen::ArrayXd localConstMatrixCalculation(const Eigen::ArrayXi &p_simToCell,
        const int  &p_nbCell);

/// \brief Calculate the second member of the normal problem \f$ A^t b \f$
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_nbCell      Number of cells
/// \param p_fToRegress  simulations to regress
/// \return parameters of the regressed function  (
Eigen::ArrayXXd localConstSecondMemberCalculation(const Eigen::ArrayXi &p_simToCell,
        const int &p_nbCell,
        const Eigen::ArrayXXd &p_fToRegress);


/// \brief Reconstruct the conditional expectation for the simulations used in the optimization part (multiple functions possible)
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_foncBasisCoef Coefficients associated to each function basis (first dimension is the function number)
/// \return  Reconstructed conditional expectation for each simulation (first dimension is the function number)
Eigen::ArrayXXd  localConstReconstruction(const Eigen::ArrayXi &p_simToCell,  const Eigen::ArrayXXd   &p_foncBasisCoef);


/// \brief  Calculate conditional expectation for one particular particle
/// \param p_oneParticle  One point where to calculate the conditional expectation (multiple functions possible)
/// \param p_mesh1D        Discretization of the domain in each dimension
/// \param p_foncBasisCoef   Coefficients associated to each function basis (first dimension is the function number)
/// \return  Solution calculated for each function
 template< typename T>
Eigen::Array<T, Eigen::Dynamic,1>   localConstReconstructionOnePoint(const  Eigen::Array<T, Eigen::Dynamic,1> &p_oneParticle,
                                                                      const std::vector< std::shared_ptr< Eigen::ArrayXd >  > &p_mesh1D,
                                                                      const Eigen::Array<T, Eigen::Dynamic, Eigen::Dynamic>   &p_foncBasisCoef)
   {
     using StOpt::toDouble;
    // Values of the functon basis and position of the  particle in the mesh
    int iCell = 0 ;
    int idecCell = 1;
    for (int id = 0 ; id < p_oneParticle.size() ; id++)
    {
        int iMesh = 1 ;
        double oneParticle = toDouble(p_oneParticle(id));
        while ((oneParticle > (*p_mesh1D[id])(iMesh)) && (iMesh < p_mesh1D[id]->size() - 1)) iMesh++;
        iCell += (iMesh - 1) * idecCell;
        idecCell *= p_mesh1D[id]->size() - 1;
    }
    // reconstruction
    Eigen::Array<T, Eigen::Dynamic,1> solution = Eigen::Array<T, Eigen::Dynamic,1>::Zero(p_foncBasisCoef.rows());
    for (int isecMem = 0; isecMem < solution.size(); ++isecMem)
        solution(isecMem) = p_foncBasisCoef(isecMem, iCell) ;
    return solution;
   }

/// \brief  Permit to reconstruct a value  for a state (pt_stock, uncertainty) : the uncertainty  and pt_stock are
///         given and interpolator are given to interpolate function basis at pt_stock
/// \param p_oneParticle      One uncertainty point where to calculate the function (using regression)
/// \param p_stock            One stock point where to calculate the function
/// \param p_interpBaseFunc   spectral interpolator to interpolate the basis functions used in regression at p_stock
/// \param p_mesh1D          Discretization of the domain in each dimension
/// \return  Solution calculated  at  (pt_stock, uncertainty)
template< typename T> 
T  localConstReconsOnePointSimStock(const Eigen::Array<T, Eigen::Dynamic,1> &p_oneParticle, const Eigen::Array<T, Eigen::Dynamic,1> &p_stock,
                                    const std::vector< std::shared_ptr<InterpolatorSpectral<T>> > &p_interpBaseFunc,
                                    const std::vector< std::shared_ptr< Eigen::ArrayXd >  > &p_mesh1D)
{
    using StOpt::toDouble;
    // Values of the functon basis and position of the  particle in the mesh
    int iCell = 0 ;
    int idecCell = 1;
    for (int id = 0 ; id < p_oneParticle.size() ; id++)
    {
        int iMesh = 1 ;
        double oneParticle = toDouble(p_oneParticle(id));
        while ((oneParticle > (*p_mesh1D[id])(iMesh)) && (iMesh < p_mesh1D[id]->size() - 1)) iMesh++;
        iCell += (iMesh - 1) * idecCell;
        idecCell *= p_mesh1D[id]->size() - 1;
    }
    // reconstruction
    return  p_interpBaseFunc[iCell]->apply(p_stock);
}

/**@}*/
}
#endif /*LOCALCONSTMATRIXOPERATION_H*/
