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

namespace StOpt
{
/**
 * \addtogroup LocalLinear
 * @{
 */
/// \brief Regression matrix calculation for local linear functions
/// \param p_particles   Particles used for regression
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_mesh        Description of the mesh coordinates for each mesh
/// \return             Regression matrix to calculate
Eigen::ArrayXXd localLinearMatrixCalculation(const Eigen::ArrayXXd &p_particles,
        const Eigen::ArrayXi &p_simToCell,
        const Eigen::Array< std::array< double, 2>, Eigen::Dynamic, Eigen::Dynamic > &p_mesh);

/// \brief Calculate the second member of the normal problem \f$ A^t b \f$
/// \param p_particles   Particles used for regression
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_mesh        Description of the mesh coordinates for each mesh
/// \param p_fToRegress  simulations to regress
/// \return parameters of the regressed function  (
Eigen::ArrayXXd localLinearSecondMemberCalculation(const Eigen::ArrayXXd &p_particles,
        const Eigen::ArrayXi &p_simToCell,
        const Eigen::Array< std::array< double, 2>, Eigen::Dynamic, Eigen::Dynamic > &p_mesh,
        const Eigen::ArrayXXd &p_fToRegress);

/// \brief Calculate the second member of the normal problem \f$ A^t b \f$
/// \param p_particles   Particles used for regression
/// \param p_SimulBelongingToCell  simulations belonging to the cell
/// \param p_mesh        Description of coordinates of the cell
/// \param p_fToRegress  simulations to regress corresponding to particles belonging to the cell
/// \return parameters of the regressed function  (
Eigen::ArrayXXd localLinearSecondMemberCalculationOneCell(const Eigen::ArrayXXd &p_particles,
        const std::vector<int>   &p_SimulBelongingToCell,
        const Eigen::Ref<const Eigen::Array< std::array<double, 2 >, Eigen::Dynamic, 1 > >  &p_mesh,
        const Eigen::ArrayXXd &p_fToRegress);

/// \brief Choleski factorization for linear per cell representation of regressions
/// \param p_mat  matrix is factorized \f$ LL^T = \f$ p_mat using superior part of p_mat. The \f$L\f$ part is put in p_mat except for diagonal
/// \param p_diag diagonal part of factorization
/// \param p_bSingular true for a cell is the corresponding matrix is singular
void localLinearCholeski(Eigen::ArrayXXd   &p_mat, Eigen::ArrayXXd   &p_diag, Eigen::Array<bool, Eigen::Dynamic, 1> &p_bSingular);

/// \brief Inversion using Choleski factorization (factorized matrix by localLinearCholeski)
/// \param p_mat        Factorized matrix by Choleski ($L$ in lower part of p_mat)
/// \param p_diag       diagonal of the factorized matrix
/// \param p_secMember  Second member fo invert
/// \return solution of the inversion
Eigen::ArrayXd  localLinearCholeskiInversion(const Eigen::ArrayXXd   &p_mat, const Eigen::ArrayXXd   &p_diag,  const Eigen::ArrayXd &p_secMember);

/// \brief Reconstruct the conditional expectation for the simulations used in the optimization part (multiple functions possible)
/// \param p_particles   Particles used for regression
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_mesh        Description of the mesh coordinates for each mesh
/// \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  localLinearReconstruction(const Eigen::ArrayXXd &p_particles, const Eigen::ArrayXi &p_simToCell,
        const Eigen::Array< std::array< double, 2>, Eigen::Dynamic, Eigen::Dynamic > &p_mesh,
        const Eigen::ArrayXXd   &p_foncBasisCoef);

/// \brief Reconstruct the conditional expectation for a given simulation  used in the optimization part
/// \param p_isim        Particle number used
/// \param p_particles   Particles used for regression
/// \param p_simToCell   To each particle associates the cell it belongs to.
/// \param p_mesh        Description of the mesh coordinates for each mesh
/// \param p_foncBasisCoef Coefficients associated to the  function basis
/// \return  Reconstructed conditional expectation for the current simulation
double  localLinearReconstructionASim(const int &p_isim, const Eigen::ArrayXXd &p_particles, const Eigen::ArrayXi &p_simToCell,
                                      const Eigen::Array< std::array< double, 2>, Eigen::Dynamic, Eigen::Dynamic > &p_mesh,
                                      const Eigen::ArrayXd   &p_foncBasisCoef);

/// \brief Inversion using Choleski factorization (factorized matrix by localLinearCholeski) for only one cell
/// \param p_iCell      Inversion for one cell
/// \param p_mat        Factorized matrix by Choleski ($L$ in lower part of p_mat)
/// \param p_diag       diagonal of the factorized matrix
/// \param p_secMember  Second member to invert
/// \return solution of the inversion
Eigen::ArrayXd  localLinearCholeskiInversionOneCell(const int &p_iCell, const Eigen::ArrayXXd   &p_mat, const Eigen::ArrayXXd   &p_diag,  const Eigen::ArrayXd &p_secMember);


/// \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
Eigen::ArrayXd  localLinearReconstructionOnePoint(const Eigen::ArrayXd &p_oneParticle,
        const std::vector< std::shared_ptr< Eigen::ArrayXd >  > &p_mesh1D,
        const Eigen::ArrayXXd   &p_foncBasisCoef);

/// \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)
double  localLinearReconsOnePointSimStock(const Eigen::ArrayXd &p_oneParticle, const Eigen::ArrayXd &p_stock,
        const std::vector< std::shared_ptr<InterpolatorSpectral> > &p_interpBaseFunc,
        const std::vector< std::shared_ptr< Eigen::ArrayXd >  > &p_mesh1D);

/// \brief Given a particle and the coordinates of the mesh it belongs to, reconstruct the regressed value
/// \param p_oneParticle  The particle generated
/// \param p_mesh  the mesh it belongs to (each coordinate of the particle should be inside the low and max coordinate of the cell in each dimension)
///                In each dimension  gives the low and high coordinates values
/// \param p_foncBasisCoef  function basis on the current cell (the row is the number of reconstruction to achieve, the columns the number of function basis)
/// \return send back the array of reconstructed values
Eigen::ArrayXd  localLinearReconstructionOnePointOneCell(const Eigen::ArrayXd &p_oneParticle,
        const Eigen::Array< std::array< double, 2>, Eigen::Dynamic, 1 > &p_mesh,
        const Eigen::ArrayXXd   &p_foncBasisCoef);


/// \brief Calculate for each particule the cell it belongs too such that
///        on this cell the value regressed is above all linear reconstruction
///        using the linear representation on others cells : first step of a
///        convex representation of the conditional expectation
///        (see "Convex piecewise-linear fitting" by Alessandro Magnani · Stephen P. Boyd, Optim Eng (2009))
/// \param p_particles   Particles used for regression
/// \param p_mesh        Description of the mesh coordinates for each mesh
/// \param p_foncBasisCoef Coefficients associated to each function basis (first dimension is the function number)
/// \param p_nbCell        number of regression cells for the process
/// \param p_simToCell   To each particle associates the cell it belongs to.
void  localLinearConvexHull(const Eigen::ArrayXXd &p_particles,
                            const Eigen::Array< std::array< double, 2>, Eigen::Dynamic, Eigen::Dynamic > &p_mesh,
                            const Eigen::ArrayXXd   &p_foncBasisCoef,
                            const int &p_nbCell,
                            Eigen::ArrayXi   &p_simToCell);

/**@}*/
}
#endif /*LOCALLINEARMATRIXOPERATION_H*/
