// Copyright (C) 2018 EDF
// All Rights Reserved
// This code is published under the GNU Lesser General Public License (GNU LGPL)
#ifndef LAPLACIANLINEARKERNELREGRESSION_H
#define LAPLACIANLINEARKERNELREGRESSION_H
#include <vector>
#include <memory>
#include <Eigen/Dense>
#include <Eigen/SVD>
#include "StOpt/regression/BaseRegression.h"
#include "StOpt/core/utils/KDTree.h"


/** \file LaplacianLinearKernelRegression.h
 * \brief Computation conditional expectation using the Laplacian kernel
  *   \f$
 *   k(x) = \frac{1}{2^d h^d}   e^{ -\sum_{i=1}^d \frac{|x_i|}{h}}
 *   \f$
 *  Algorithm by Langrene, Warin 2020 using divide and conquer
 * The estimation :
 *  \f$ E[ y/x ]=  \frac{1}{M}  \sum_{j=1}^M  k(x-x^j) (y^j - a x^j -b)
 * \f$
 * where $(a,b) =  \argmin_{c,d}  \sum_{j=1}^M  k(x-x^j) (y^j - c x^j -d)^2
 * \author  Xavier Warin
 */
namespace StOpt
{
class LaplacianLinearKernelRegression : public BaseRegression
{
private:

    bool m_bZeroDate ;                    ///< Is the regression date zero ?
    Eigen::ArrayXd m_h ; ///< Kernel width
    KDTree m_tree; ///< KD tree to find nearest point from a given point


    /// \brief regress one functon
    /// \param  p_fToRegress  function to regress associated to each simulation used in optimization (size :  number of function to regress  \times number of grids points  )
    Eigen::ArrayXXd regressFunction(const Eigen::ArrayXXd &p_fToRegress) const ;


public :


    /// \brief Constructor for grid kernel regression
    /// \param  p_bZeroDate          first date is 0?
    /// \param  p_particles          particles used for the meshes.
    ///                              First dimension  : dimension of the problem,
    ///                              second dimension : the  number of particles
    /// \param  p_h                  size of bandwidth in each direction
    LaplacianLinearKernelRegression(const bool &p_bZeroDate,
                                    const Eigen::ArrayXXd  &p_particles,
                                    const Eigen::ArrayXd   &p_h);

    /// \brief Constructor for grid kernel regression
    /// \param  p_h                  size of bandwidth in each direction
    LaplacianLinearKernelRegression(const Eigen::ArrayXd   &p_h);


    ///\brief default  constructor
    LaplacianLinearKernelRegression(): BaseRegression(false) {}



    /// \brief Last  constructor only used for out of sample simulations
    /// \param  p_bZeroDate          first date is 0?
    /// \param  p_particles          particles used for the meshes.
    LaplacianLinearKernelRegression(const bool &p_bZeroDate,
                                    const Eigen::ArrayXXd  &p_particles);


    /// \brief update the particles used in regression  and construct the matrices
    /// \param  p_bZeroDate    first date is 0?
    /// \param  p_particles    particles used for the meshes.
    ///                        First dimension  : dimension of the problem,
    ///                        second dimension : the  number of particles
    void updateSimulations(const bool &p_bZeroDate, const Eigen::ArrayXXd  &p_particles);

    /// \brief  For this kernel method get back the regressed values on a deterministic grid with coordinates given by m_z
    /// \param  p_fToRegress  function to regress associated to each simulation used in optimization
    /// \return regressed values on the grid
    /// @{
    Eigen::ArrayXd getCoordBasisFunction(const Eigen::ArrayXd &p_fToRegress) const;
    ///@}
    /// \brief  For this kernel method get back the regressed values on a deterministic grid with coordinates given by m_z
    /// \param  p_fToRegress  function to regress associated to each simulation used in optimization (size : number of functions to regress \times the number of Monte Carlo simulations)
    /// \return regressed values on the grid  (size :  number of function to regress  \times number of grids points  )
    /// @{
    Eigen::ArrayXXd getCoordBasisFunctionMultiple(const Eigen::ArrayXXd &p_fToRegress) const ;
    ///@}

    /// \brief conditional expectation calculation
    /// \param  p_fToRegress  simulations  to regress used in optimization
    /// \return regressed value function
    /// @{
    Eigen::ArrayXd getAllSimulations(const Eigen::ArrayXd &p_fToRegress) const ;
    Eigen::ArrayXXd getAllSimulationsMultiple(const Eigen::ArrayXXd &p_fToRegress) const;
    ///@}


    /// \brief Use basis functions to reconstruct the solution
    /// \param p_basisCoefficients basis coefficients
    ///@{
    Eigen::ArrayXd reconstruction(const Eigen::ArrayXd   &p_basisCoefficients) const;
    Eigen::ArrayXXd reconstructionMultiple(const Eigen::ArrayXXd   &p_basisCoefficients) const;
    /// @}
    /// \brief use basis function to reconstruct a given simulation
    /// \param p_isim               simulation number
    /// \param p_basisCoefficients  basis coefficients to reconstruct a given conditional expectation
    double reconstructionASim(const int &p_isim, const Eigen::ArrayXd   &p_basisCoefficients) const ;

    /// \brief conditional expectation reconstruction
    /// \param  p_coordinates        coordinates to interpolate (uncertainty sample)
    /// \param  p_coordBasisFunction regression coordinates on the basis  (size: number of meshes multiplied by the dimension plus one)
    /// \return regressed value function reconstructed for each simulation
    double getValue(const Eigen::ArrayXd   &p_coordinates,
                    const Eigen::ArrayXd   &p_coordBasisFunction) const ;


    /// \brief permits to reconstruct a function with basis functions coefficients values given on a grid
    /// \param  p_coordinates          coordinates  (uncertainty sample)
    /// \param  p_ptOfStock            grid point
    /// \param  p_interpFuncBasis      spectral interpolator to interpolate the basis functions  coefficients used in regression on the grid (given for each basis function)
    double getAValue(const Eigen::ArrayXd &p_coordinates,  const Eigen::ArrayXd &p_ptOfStock,
                     const std::vector< std::shared_ptr<InterpolatorSpectral> > &p_interpFuncBasis) const;


    /// \brief get the number of basis functions
    inline int getNumberOfFunction() const
    {
        if (m_bZeroDate)
            return 1;
        else
        {
            return m_particles.cols();
        }
    }

    /// \brief Clone the regressor
    virtual std::shared_ptr<BaseRegression> clone() const
    {
        return std::static_pointer_cast<BaseRegression>(std::make_shared<LaplacianLinearKernelRegression>(*this));
    }

};
}

#endif /*   LAPLACIANGRIDKERNELREGRESSION_H  */
