#include "entropy.hpp"
#include <armadillo>
#include <stdlib.h>
using namespace arma;
using namespace std;

// von Neumann entropy of the first k qubits
double vNentropy(unsigned int k, cx_dvec &psi)
{
  int d = psi.size();
  cx_dmat sqrtrho = reshape(psi, 1<<k, d/(1<<k));
  vec s = svd(sqrtrho);
  psi.reshape(size(psi));
  double sum = 0.0;
  for (int i=0; i<(1<<k); i++)
    {
      double ent_sq = norm(s(i));
      sum -= log2(ent_sq) * ent_sq;
    }
  return sum;
}

// Diagonal entropy of the first k qubits
double diagentropy(unsigned int k, cx_dvec &psi)
{
  int d = psi.size();
  double sum = 0.0;
  for (int i=0; i<(1<<k); i++)
    {
      double ent_sq = 0.0;
      for (int j=0; j<(d/(1<<k)); j++)
	{
	  ent_sq += norm(psi(i + (j<<k)));
	}
      sum -= log2(ent_sq) * ent_sq;
    }
  return sum;
}


/*
Part of the Fluid Corpus Manipulation Project (http://www.flucoma.org/)
Copyright 2017-2019 University of Huddersfield.
Licensed under the BSD-3 License.
See license.md file in the project root for full license information.
This project has received funding from the European Research Council (ERC)
under the European Union’s Horizon 2020 research and innovation programme
(grant agreement No 725899).
*/

#pragma once

#include "../util/FluidEigenMappings.hpp"
#include "../../data/TensorTypes.hpp"
#include <Eigen/Core>
#include <Eigen/SVD>
#include <cassert>
#include <cmath>

namespace fluid {
namespace algorithm {

class PCA
{
public:
  using MatrixXd = Eigen::MatrixXd;
  using VectorXd = Eigen::VectorXd;
  using ArrayXd = Eigen::ArrayXd;

  void init(RealMatrixView in)
  {
    using namespace Eigen;
    using namespace _impl;
    MatrixXd input = asEigen<Matrix>(in);
    mNumDataPoints = input.rows();
    mMean = input.colwise().mean();
    MatrixXd         X = (input.rowwise() - mMean.transpose());
    BDCSVD<MatrixXd> svd(X.matrix(), ComputeThinV | ComputeThinU);
    mBases = svd.matrixV();
    mValues = svd.singularValues();
    mExplainedVariance = mValues.array().square() / (mNumDataPoints - 1);
    mInitialized = true;
  }

  void init(RealMatrixView bases, RealVectorView values, RealVectorView mean,
            index numDataPoints = 2)
  {
    mBases = _impl::asEigen<Eigen::Matrix>(bases);
    mValues = _impl::asEigen<Eigen::Matrix>(values);
    mMean = _impl::asEigen<Eigen::Matrix>(mean);
    mNumDataPoints = numDataPoints;
    mExplainedVariance = mValues.array().square() / (mNumDataPoints - 1);
    mInitialized = true;
  }

  void processFrame(const RealVectorView in, RealVectorView out, index k,
                    bool whiten = false) const
  {
    using namespace Eigen;
    using namespace _impl;
    if (k > mBases.cols()) return;
    VectorXd input = asEigen<Matrix>(in);
    input = input - mMean;
    VectorXd result = input.transpose() * mBases.block(0, 0, mBases.rows(), k);

    if (whiten)
    {
      ArrayXd norm = mExplainedVariance.segment(0, k).max(epsilon).rsqrt();
      result.array() *= norm;
    }
     out <<= _impl::asFluid(result);
  }

  void inverseProcessFrame(RealVectorView in, RealVectorView out, bool whiten = false) const
  {
    using namespace Eigen;
    using namespace _impl;

    if(!whiten)
    {
      asEigen<Matrix>(out) =
          mMean +
          (asEigen<Matrix>(in).transpose() * mBases.transpose()).transpose();
    }
    else
    {
      asEigen<Matrix>(out) = mMean +  (asEigen<Matrix>(in).transpose() *
            (mExplainedVariance.sqrt().matrix().asDiagonal() * mBases.transpose())).transpose();
    }
  }

  double process(const RealMatrixView in, RealMatrixView out, index k,
                 bool whiten = false) const
  {
    using namespace Eigen;
    using namespace _impl;

    if (k > mBases.cols()) return 0;
    MatrixXd input = asEigen<Matrix>(in);
    MatrixXd result = (input.rowwise() - mMean.transpose()) *
                      mBases.block(0, 0, mBases.rows(), k);
    if (whiten)
    {
      ArrayXd norm = mExplainedVariance.segment(0, k).max(epsilon).rsqrt();
      result = result.array().rowwise() * norm.transpose().max(epsilon);
    }
    double variance = 0;

    double total = mExplainedVariance.sum();
    for (index i = 0; i < k; i++) variance += mExplainedVariance[i];
    out <<= _impl::asFluid(result);

    return variance / total;
  }

  void inverseProcess(RealMatrixView in, RealMatrixView out, bool whiten = false) const
  {
    using namespace Eigen;

    if (in.cols() > dims()) return;
    if (out.cols() < in.cols()) return;

    if (!whiten)
      _impl::asEigen<Matrix>(out) =
          (_impl::asEigen<Matrix>(in) * mBases.transpose()).rowwise() +
          mMean.transpose();

    else
    {
      _impl::asEigen<Matrix>(out) =
          (_impl::asEigen<Matrix>(in) *
           (mExplainedVariance.sqrt().matrix().asDiagonal() *
            mBases.transpose()))
              .rowwise() +
          mMean.transpose();
    }
  }

  bool  initialized() const { return mInitialized; }

  void  getBases(RealMatrixView out) const { out <<= _impl::asFluid(mBases); }
  void  getValues(RealVectorView out) const { out <<= _impl::asFluid(mValues); }
  void  getMean(RealVectorView out) const { out <<= _impl::asFluid(mMean); }
  index getNumDataPoints() const { return mNumDataPoints; }

  index dims() const { return mBases.rows(); }
  index size() const { return mBases.cols(); }
  void  clear()
  {
    mBases.setZero();
    mMean.setZero();
    mInitialized = false;
  }

  MatrixXd mBases;
  VectorXd mValues;
  ArrayXd  mExplainedVariance;
  VectorXd mMean;
  index    mNumDataPoints;
  bool     mInitialized{false};
};
}// namespace algorithm
}// namespace fluid


#include "stats/asphericity.h"
#include <Eigen/Core>
#include <Eigen/SVD>
#include <xmd/utils/convert.h>

namespace xmd {
    void compute_asphericity::operator()() const {
        vec3r center_of_mass = vec3r::Zero();
        real total_mass = 0.0;
        for (int idx = 0; idx < num_particles; ++idx) {
            center_of_mass += mass[idx] * r[idx];
            total_mass += mass[idx];
        }
        center_of_mass /= total_mass;

        using matrix_t = Eigen::Matrix<real, 3, Eigen::Dynamic>;
        matrix_t R = matrix_t::Zero(3, num_particles);
        for (int idx = 0; idx < num_particles; ++idx) {
            R.col(idx) = convert(r[idx] - center_of_mass);
        }

        auto lambda = Eigen::JacobiSVD<decltype(R)>(R).singularValues();
        *asphericity = (real)1.5 * pow(lambda.z(), 2.0)
            - (real)0.5 * lambda.squaredNorm();
    }
}


/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */

/*
Copyright (C) 2015 Andres Hernandez

This file is part of QuantLib, a free-software/open-source library
for financial quantitative analysts and developers - http://quantlib.org/

QuantLib is free software: you can redistribute it and/or modify it
under the terms of the QuantLib license.  You should have received a
copy of the license along with this program; if not, please email
<quantlib-dev@lists.sf.net>. The license is also available online at
<http://quantlib.org/license.shtml>.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE.  See the license for more details.
*/

/*! \file particleswarmoptimization.hpp
\brief Implementation based on:
Clerc, M., Kennedy, J. (2002) The particle swarm-explosion, stability and
convergence in a multidimensional complex space. IEEE Transactions on Evolutionary
Computation, 6(2): 58–73.
*/

#ifndef quantlib_optimization_particleswarmoptimization_hpp
#define quantlib_optimization_particleswarmoptimization_hpp

#include <ql/qldefines.hpp>

#if BOOST_VERSION >= 104700

#include <ql/math/optimization/problem.hpp>
#include <ql/math/optimization/constraint.hpp>
#include <ql/math/randomnumbers/mt19937uniformrng.hpp>
#include <ql/experimental/math/isotropicrandomwalk.hpp>
#include <ql/experimental/math/levyflightdistribution.hpp>

#include <boost/random/mersenne_twister.hpp>
typedef boost::mt19937 base_generator_type;

#include <boost/random/uniform_int_distribution.hpp>
typedef boost::random::uniform_int_distribution<QuantLib::Size> uniform_integer;

namespace QuantLib {

    /*! The process is as follows:
    M individuals are used to explore the N-dimensional parameter space
    X_{i}^k = (X_{i, 1}^k, X_{i, 2}^k, \ldots, X_{i, N}^k) is the kth-iteration for the ith-individual
    X is updated via the rule
    X_{i, j}^{k+1} = X_{i, j}^k + V_{i, j}^{k+1}
    with V being the "velocity" that updates the position:
    V_{i, j}^{k+1} = \chi\left(V_{i, j}^k + c_1 r_{i, j}^k (P_{i, j}^k - X_{i, j}^k)
    + c_2 R_{i, j}^k (G_{i, j}^k - X_{i, j}^k)\right)
    where c are constants, r and R are uniformly distributed random numbers in the range [0, 1], and
    P_{i, j} is the personal best parameter set for individual i up to iteration k
    G_{i, j} is the global best parameter set for the swarm up to iteration k.
    c_1 is the self recognition coefficient
    c_2 is the social recognition coefficient

    This version is known as the PSO with constriction factor (PSO-Co).
    PSO with inertia factor (PSO-In) updates the velocity according to:
    V_{i, j}^{k+1} = \omega V_{i, j}^k + \hat{c}_1 r_{i, j}^k (P_{i, j}^k - X_{i, j}^k)
    + \hat{c}_2 R_{i, j}^k (G_{i, j}^k - X_{i, j}^k)
    and is accessible from PSO-Co by setting \omega = \chi, and \hat{c}_{1,2} = \chi c_{1,2}

    These two versions of PSO are normally referred to as canonical PSO.

    Convergence of PSO-Co is improved if \chi is chosen as
    \chi = \frac{2}{\vert 2-\phi-\sqrt{\phi^2 - 4\phi}\vert}, with \phi = c_1 + c_2
    Stable convergence is achieved if \phi >= 4. Clerc and Kennedy recommend
    c_1 = c_2 = 2.05 and \phi = 4.1

    Different topologies can be chosen for G, e.g. instead of it being the best
    of the swarm, it is the best of the nearest neighbours, or some other form.

    In the canonical PSO, the inertia function is trivial. It is simply a
    constant (the inertia) multiplying the previous iteration's velocity. The
    value of the inertia constant determines the weight of a global search over
    local search. Like in the case of the topology, other possibilities for the
    inertia function are also possible, e.g. a function that interpolates between a
    high inertia at the beginning of the optimization (hence prioritizing a global
    search) and a low inertia towards the end of the optimization (hence prioritizing
    a local search).

    The optimization stops either because the number of iterations has been reached
    or because the stationary function value limit has been reached.
    */
    class ParticleSwarmOptimization : public OptimizationMethod {
      public:
        class Inertia;
        class Topology;
        friend class Inertia;
        friend class Topology;
        ParticleSwarmOptimization(Size M,
            boost::shared_ptr<Topology> topology,
            boost::shared_ptr<Inertia> inertia,
            Real c1 = 2.05, Real c2 = 2.05,
            unsigned long seed = 0);
        ParticleSwarmOptimization(const Size M,
            boost::shared_ptr<Topology> topology,
            boost::shared_ptr<Inertia> inertia,
            Real omega, Real c1, Real c2,
            unsigned long seed = 0);
        void startState(Problem &P, const EndCriteria &endCriteria);
        EndCriteria::Type minimize(Problem &P, const EndCriteria &endCriteria);

      protected:
        std::vector<Array> X_, V_, pBX_, gBX_;
        Array pBF_, gBF_;
        Array lX_, uX_;
        Size M_, N_;
        Real c0_, c1_, c2_;
        MersenneTwisterUniformRng rng_;
        boost::shared_ptr<Topology> topology_;
        boost::shared_ptr<Inertia> inertia_;
    };

    //! Base inertia class used to alter the PSO state
    /*! This pure virtual base class provides the access to the PSO state
    which the particular inertia algorithm will change upon each iteration.
    */
    class ParticleSwarmOptimization::Inertia {
        friend class ParticleSwarmOptimization;
      public:
        virtual ~Inertia() {}
        //! initialize state for current problem
        virtual void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) = 0;
        //! produce changes to PSO state for current iteration
        virtual void setValues() = 0;
      protected:
        ParticleSwarmOptimization *pso_;
        std::vector<Array> *X_, *V_, *pBX_, *gBX_;
        Array *pBF_, *gBF_;
        Array *lX_, *uX_;
      private:
        void init(ParticleSwarmOptimization *pso) {
            pso_ = pso;
            X_ = &pso_->X_;
            V_ = &pso_->V_;
            pBX_ = &pso_->pBX_;
            gBX_ = &pso_->gBX_;
            pBF_ = &pso_->pBF_;
            gBF_ = &pso_->gBF_;
            lX_ = &pso_->lX_;
            uX_ = &pso_->uX_;
        }
    };

    //! Trivial Inertia
    /*     Inertia is a static value
    */
    class TrivialInertia : public ParticleSwarmOptimization::Inertia {
      public:
        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {
            c0_ = c0;
            M_ = M;
        }
        inline void setValues() {
            for (Size i = 0; i < M_; i++) {
                (*V_)[i] *= c0_;
            }
        }
      private:
        Real c0_;
        Size M_;
    };

    //! Simple Random Inertia
    /*     Inertia value gets multiplied with a random number
    between (threshhold, 1)
    */
    class SimpleRandomInertia : public ParticleSwarmOptimization::Inertia {
      public:
        SimpleRandomInertia(Real threshhold = 0.5, unsigned long seed = 0)
            : threshhold_(threshhold), rng_(seed) {
            QL_REQUIRE(threshhold_ >= 0.0 && threshhold_ < 1.0, "Threshhold must be a Real in [0, 1)");
        }
        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {
            M_ = M;
            c0_ = c0;
        }
        inline void setValues() {
            for (Size i = 0; i < M_; i++) {
                Real val = c0_*(threshhold_ + (1.0 - threshhold_)*rng_.nextReal());
                (*V_)[i] *= val;
            }
        }
      private:
        Real c0_, threshhold_;
        Size M_;
        MersenneTwisterUniformRng rng_;
    };

    //! Decreasing Inertia
    /*     Inertia value gets decreased every iteration until it reaches
    a value of threshhold when iteration reaches the maximum level
    */
    class DecreasingInertia : public ParticleSwarmOptimization::Inertia {
      public:
        DecreasingInertia(Real threshhold = 0.5)
            : threshhold_(threshhold) {
            QL_REQUIRE(threshhold_ >= 0.0 && threshhold_ < 1.0, "Threshhold must be a Real in [0, 1)");
        }
        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {
            N_ = N;
            c0_ = c0;
            iteration_ = 0;
            maxIterations_ = endCriteria.maxIterations();
        }
        inline void setValues() {
            Real c0 = c0_*(threshhold_ + (1.0 - threshhold_)*(maxIterations_ - iteration_) / maxIterations_);
            for (Size i = 0; i < M_; i++) {
                (*V_)[i] *= c0;
            }
        }
      private:
        Real c0_, threshhold_;
        Size M_, N_, maxIterations_, iteration_;
    };

    //! AdaptiveInertia
    /*    Alen Lukic, Approximating Kinetic Parameters Using Particle
    Swarm Optimization.
    */
    class AdaptiveInertia : public ParticleSwarmOptimization::Inertia {
      public:
        AdaptiveInertia(Real minInertia, Real maxInertia, Size sh = 5, Size sl = 2)
            :minInertia_(minInertia), maxInertia_(maxInertia),
            sh_(sh), sl_(sl) {};
        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {
            M_ = M;
            c0_ = c0;
            adaptiveCounter = 0;
            best_ = QL_MAX_REAL;
            started_ = false;
        }
        void setValues();
      private:
        Real c0_, best_;
        Real minInertia_, maxInertia_;
        Size M_;
        Size sh_, sl_;
        Size adaptiveCounter;
        bool started_;
    };

    //! Levy Flight Inertia
    /*    As long as the particle keeps getting frequent updates to its
    personal best value, the inertia behaves like a SimpleRandomInertia,
    but after a number of iterations without improvement, the behaviour
    changes to that of a Levy flight ~ u^{-1/\alpha}
    */
    class LevyFlightInertia : public ParticleSwarmOptimization::Inertia {
      public:
        typedef IsotropicRandomWalk<LevyFlightDistribution, base_generator_type> IsotropicLevyFlight;
        LevyFlightInertia(Real alpha, Size threshhold,
                          unsigned long seed = 0)
            :flight_(base_generator_type(seed), LevyFlightDistribution(1.0, alpha),
                1, Array(1, 1.0), seed),
            threshhold_(threshhold) {};
        inline void setSize(Size M, Size N, Real c0, const EndCriteria &endCriteria) {
            M_ = M;
            N_ = N;
            c0_ = c0;
            personalBestF_ = *pBF_;
            adaptiveCounter_ = std::vector<Size>(M_, 0);
            flight_.setDimension(N_, *lX_, *uX_);
        }
        inline void setValues() {
            for (Size i = 0; i < M_; i++) {
                if ((*pBF_)[i] < personalBestF_[i]) {
                    personalBestF_[i] = (*pBF_)[i];
                    adaptiveCounter_[i] = 0;
                }
                else {
                    adaptiveCounter_[i]++;
                }
                if (adaptiveCounter_[i] <= threshhold_) {
                    //Simple Random Inertia
                    (*V_)[i] *= c0_*(0.5 + 0.5*rng_.nextReal());
                }
                else {
                    //If particle has not found a new personal best after threshhold_ iterations
                    //then trigger a Levy flight pattern for the speed
                    flight_.nextReal<Real *>(&(*V_)[i][0]);
                }
            }
        }
      private:
        MersenneTwisterUniformRng rng_;
        IsotropicLevyFlight flight_;
        Array personalBestF_;
        std::vector<Size> adaptiveCounter_;
        Real c0_;
        Size M_, N_;
        Size threshhold_;
    };

    //! Base topology class used to determine the personal and global best
    /*! This pure virtual base class provides the access to the PSO state
    which the particular topology algorithm will change upon each iteration.
    */
    class ParticleSwarmOptimization::Topology {
        friend class ParticleSwarmOptimization;
      public:
        virtual ~Topology() {}
        //! initialize state for current problem
        virtual void setSize(Size M) = 0;
        //! produce changes to PSO state for current iteration
        virtual void findSocialBest() = 0;
      protected:
        ParticleSwarmOptimization *pso_;
        std::vector<Array> *X_, *V_, *pBX_, *gBX_;
        Array *pBF_, *gBF_;
      private:
        void init(ParticleSwarmOptimization *pso) {
            pso_ = pso;
            X_ = &pso_->X_;
            V_ = &pso_->V_;
            pBX_ = &pso_->pBX_;
            gBX_ = &pso_->gBX_;
            pBF_ = &pso_->pBF_;
            gBF_ = &pso_->gBF_;
        }
    };

    //! Global Topology
    /*  The global best as seen by each particle is the best from amongst
    all particles
    */
    class GlobalTopology : public ParticleSwarmOptimization::Topology {
      public:
        inline void setSize(Size M) { M_ = M; }
        inline void findSocialBest() {
            Real bestF = (*pBF_)[0];
            Size bestP = 0;
            for (Size i = 1; i < M_; i++) {
                if (bestF < (*pBF_)[i]) {
                    bestF = (*pBF_)[i];
                    bestP = i;
                }
            }
            Array& x = (*pBX_)[bestP];
            for (Size i = 0; i < M_; i++) {
                if (i != bestP) {
                    (*gBX_)[i] = x;
                    (*gBF_)[i] = bestF;
                }
            }
        }

      private:
        Size M_;
    };

    //! K-Neighbor Topology
    /*  The global best as seen by each particle is the best from amongst
    the previous K and next K neighbors. For particle I, the best is
    then taken from amongst the [I - K, I + K] particles.
    */
    class KNeighbors : public ParticleSwarmOptimization::Topology {
      public:
        KNeighbors(Size K = 1) :K_(K) {
            QL_REQUIRE(K > 0, "Neighbors need to be larger than 0");
        }
        inline void setSize(Size M) {
            M_ = M;
            if (M_ < 2 * K_ + 1)
                K_ = (M_ - 1) / 2;
        }
        void findSocialBest();

      private:
        Size K_, M_;
    };

    //! Clubs Topology
    /*  H.M. Emara,  Adaptive Clubs-based Particle Swarm Optimization
    Each particle is originally assigned to a default number of clubs
    from among the total set. The best as seen by each particle is the
    best from amongst the clubs to which the particle belongs.
    Underperforming particles join more clubs randomly (up to a maximum
    number) to widen the particles that influence them, while
    overperforming particles leave clubs randomly (down to a minimum
    number) to avoid early convergence to local minima.
    */
    class ClubsTopology : public ParticleSwarmOptimization::Topology {
      public:
        ClubsTopology(Size defaultClubs, Size totalClubs,
            Size maxClubs, Size minClubs,
            Size resetIteration, unsigned long seed = 0);
        void setSize(Size M);
        void findSocialBest();

      private:
        Size totalClubs_, maxClubs_, minClubs_, defaultClubs_;
        Size iteration_, resetIteration_;
        Size M_;
        std::vector<std::vector<bool> > clubs4particles_;
        std::vector<std::vector<bool> > particles4clubs_;
        std::vector<Size> bestByClub_;
        std::vector<Size> worstByClub_;
        base_generator_type generator_;
        uniform_integer distribution_;

        void leaveRandomClub(Size particle, Size currentClubs);
        void joinRandomClub(Size particle, Size currentClubs);
    };

}

#endif

#endif


//==================================================================================================
/*!
  @file

  @copyright 2016 NumScale SAS

  Distributed under the Boost Software License, Version 1.0.
  (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
*/
//==================================================================================================
#ifndef BOOST_SIMD_CONSTANT_GOLD_HPP_INCLUDED
#define BOOST_SIMD_CONSTANT_GOLD_HPP_INCLUDED

/*!
  @ingroup group-constant
  @defgroup constant-Gold Gold (function template)

  Generates the Golden Ratio \f$\phi

  @headerref{<boost/simd/constant/gold.hpp>}

  @par Description

  1.  @code
      template<typename T> T Gold();
      @endcode

  2.  @code
      template<typename T> T Gold( boost::simd::as_<T> const& target );
      @endcode

  Generates a constant that evaluate to the [Golden Ratio](http://mathworld.wolfram.com/GoldenRatio.html)
  defined as \f$\frac{1}{2}(1 + \sqrt{5})\f$.

  @par Parameters

  | Name                | Description                                                         |
  |--------------------:|:--------------------------------------------------------------------|
  | **target**          | a [placeholder](@ref type-as) value encapsulating the constant type |

  @par Return Value
  A value of type @c T that evaluates to `T(1.61803398874989484820458683436563811772)`.

  @par Requirements
  - **T** models IEEEValue
**/

#include <boost/simd/constant/scalar/gold.hpp>
#include <boost/simd/constant/simd/gold.hpp>

#endif


/*
This file covers basics about using eigen such as initializing a matrix, operations, and functions.

How to Install / Use Eigen:
1. go to desired install folder
2. git clone https://gitlab.com/libeigen/eigen
3. add path/to/eigen to include directories: Project >> PROJECT Properties >>
    VC++ Directories >> Include Directories >> (add path here)
4. start using Eigen

things to add:
  * append new row(s)
  * append new col(s)

*/

#include <iostream>
#include <Eigen/Dense>
using namespace std;
int main() {
  namespace eig = Eigen;
  // create a matrix: can either be a dynamic or static matrix:

  //dynamic matrix (note the "X" in the name)
  eig::MatrixX<double> x1(2, 2);
  x1 << 0, 1, 2, 3;

  // static matrix (note the delimiting of dimensions in the template)
  eig::Matrix<double, 2, 2> x2;
  x2 << 5,2,3,1;

  eig::MatrixX<double> x3(2, 5);
  x3 << 0, 1, 2, 3, 4, 5, 6, 7, 8, 9;

  // alternative to matrices are arrays, which function a little bit more like numpy arrays
  eig::ArrayXX<double> y1(2, 2); // having two 'X's is correct
  y1 << 2, 3, 4, 5;
  eig::Array<double, 2, 2> y2; // also has a static option
  y2 << 5, 6, 7, 8;

  // conversion between the two:
  eig::MatrixX<double> xtemp = y1.matrix();

  // note there are also vectors, but used to a far lesser extent
  eig::VectorX<double> v(6);
  v << 1, 2, 3, 4, 5, 6;
  cout << "vector: " << v << endl;

  // basic per-element operations:
  cout << "scalar addition \n" << (x1.array() + 10).matrix() << endl; // note: need to be in array
  cout << "scalar subtraction \n" << (x1.array() - 10).matrix() << endl;
  cout << "scalar multiplication \n" << x1 * 10 << endl;
  cout << "scalar division \n" << x1 / 10 << endl;

  // matrix operations
  cout << "matrix addition \n" << x1 + x2 << endl;
  cout << "matrix subtraction \n" << x1 - x2 << endl;
  cout << "transpose \n" << x1.transpose() << endl;
  cout << "inverse \n" << x1.inverse() << endl;
  cout << "matmult \n" << x1 * x2 << endl;
  cout << "conjugation \n" << x1.conjugate() << endl;

  // WARNING: AVOID TRANSPOSITION ISSUES, WHICH OCCUR WHEN TRANSPOSING IN-PLACE:
  // a=a.transpose() // DO NOT DO THIS
  x1.transposeInPlace();
  x1.transposeInPlace();

  // arithmetic reduction operations:
  cout << "sum the matrix: " << x1.sum() << endl;
  cout << "mult the matrix: " << x1.prod() << endl;
  cout << "matrix mean: " << x1.mean() << endl;
  cout << "matrix min: " << x1.minCoeff() << endl;
  cout << "matrix max: " << x1.maxCoeff() << endl;

  // matrix properties
  cout << "diagonal: " << x1.diagonal().transpose() << endl;
  cout << "shape (should be 2,5): " << x3.rows() << ',' << x3.cols() << endl;

  // matrix manipulation
  eig::Map < eig::MatrixX<double>> x4(x1.data(), 1,x1.size());
  cout << "reshape: " << x4 << endl;
  // append a row
  eig::MatrixX<double> x6(2,2);
  x6 << 0, 1, 2, 3;
  x6.conservativeResize(x6.cols() + 1, eig::NoChange); // shortcut
  x6(2, 0) = 5;
  x6(2, 1) = 6;
  cout << "append row: \n" << x6 << endl;

  // taking part of matrix:
  eig::MatrixX<double> x5(5, 5);
  for (int i = 0; i < x5.size(); i++) x5(i) = i;
  cout << "initial \n" << x5 << endl;

  cout << "arbitrary block \n" << x5.block(1, 1, 2, 2) << endl;
  cout << "column1 \n" << x5.block(0, 1, x5.rows(), 1) << endl;
  cout << "row3 \n" << x5.block(3, 0, 1,x5.cols()) << endl;

  // special matrices. dynamic or static, can be whatever dimensions needed
  cout << "identity matrix \n" << eig::Matrix<double,3,3>::Identity() << endl;
  cout << "zeros \n" << eig::Matrix<double, 3, 3>::Zero() << endl;
  cout << "ones\n" << eig::Matrix<double, 3, 3>::Ones() << endl;
  cout << "random\n" << eig::MatrixX<double>::Random(3,3) << endl;

}


/**
 * Munkres.hpp
 * @author : koide
 * 14/11/03
 **/
#ifndef KKL_MUNKRES_HPP
#define KKL_MUNKRES_HPP

#include <cfloat>
#include <vector>
#include <iostream>
#include <Eigen/Dense>

namespace kkl {
	namespace alg {

template<typename T>
bool isZero(T value) {
	return value == 0;
}
template<>
bool isZero(float value) {
	return abs(value) <= FLT_EPSILON;
}
template<>
bool isZero(double value) {
	return abs(value) <= DBL_EPSILON;
}

/************************************************
 * Munkres
 * http://csclab.murraystate.edu/bob.pilgrim/445/munkres.html
 *
 * Munkres<int> munkres
 * auto ans = munkres.solve( cost )
************************************************/
template<typename T>
class Munkres {
public:
	/*********************************************************
	 * solve
   * cost : cost matrix (cost.rows <= cost.cols)
   * ret : solution
	********************************************************/
	Eigen::VectorXi solve(const Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic>& cost_) {
		assert( cost_.rows() <= cost_.cols() );
		cost = cost_;
		K = std::min(cost.rows(), cost.cols());

		starred = Eigen::MatrixXi::Zero(cost.rows(), cost.cols());
		primed = Eigen::MatrixXi::Zero(cost.rows(), cost.cols());
		covered_rows = Eigen::VectorXi::Zero(cost.rows());
		covered_cols = Eigen::VectorXi::Zero(cost.cols());

		// step 1
		cost.colwise() -= cost.rowwise().minCoeff();

		// step 2
		for (int i = 0; i < cost.rows(); i++) {
			for (int j = 0; j < cost.cols(); j++) {
				if (isZero(cost(i, j)) && starred.row(i).count() == 0 && starred.col(j).count() == 0){
					starred(i, j) = 1;
				}
			}
		}

		// step3 ~ step 6
		step3();

		// done, find the starred zeros
		Eigen::VectorXi ret(K);
		for (int i = 0; i < K; i++) {
			for (int j = 0; j < cost.cols(); j++) {
				if (starred(i, j)) {
					ret(i) = j;
					break;
				}
			}
		}

		return ret;
	}

	EIGEN_MAKE_ALIGNED_OPERATOR_NEW
private:
	/*****************************
	 * step3
	*****************************/
	void step3() {
		for (int i = 0; i < cost.cols(); i++) {
			if (starred.col(i).count() != 0) {
				covered_cols[i] = 1;
			}
		}
		// if K columns are covered, go to done
		if (covered_cols.count() == K) {
			return;
		}
		// otherwise, go to step 4
		return step4();
	}

	/*****************************
	 * step4
	*****************************/
	void step4() {
		for (int i = 0; i < cost.rows(); i++) {
			for (int j = 0; j < cost.cols(); j++){
				// find a noncovered zero and prime it
				if (!covered_rows[i] && !covered_cols[j] && isZero(cost(i, j))){
					primed(i, j) = 1;

					// if there is no starred zero in the row, go to step 5
					if (starred.row(i).count() == 0) {
						return step5(i, j);
					}
					// otherwise, cover this row and uncover the column containing the starred zero
					covered_rows[i] = 1;
					for (int k = 0; k < cost.cols(); k++) {
						if (starred(i, k)) {
							covered_cols[k] = 0;
						}
					}
				}
			}
		}

		T smallest = -1;
		// continue in this manner until there are no uncovered zeros left
		// save the smallest uncovered value and go to step 6
		for (int i = 0; i < cost.rows(); i++){
			for (int j = 0; j < cost.cols(); j++) {
				if (!covered_rows[i] && !covered_cols[j] && isZero(cost(i, j))){
					return step4();
				}

				if (!covered_rows[i] && !covered_cols[j] &&
					(smallest > cost(i, j) || smallest < 0.0)) {
					smallest = cost(i, j);
				}
			}
		}

		return step6(smallest);
	}

	/*****************************
	 * step5
	*****************************/
	void step5(int z0_row, int z0_col) {
		std::vector<std::pair<int, int>> series(1);
		series[0] = std::make_pair(z0_row, z0_col);

		bool done = false;
		while (!done) {
			// z1 : the starred zero in the column of z0
			bool added = false;
			const auto& z0 = series.back();
			for (int i = 0; i < cost.rows(); i++) {
				if (starred(i, z0.second)) {
					added = true;
					series.push_back(std::make_pair(i, z0.second));
					break;
				}
			}
			if (!added) {
				break;
			}

			const auto& z1 = series.back();
			// z2 : the primed zero in the rows of z1
			for (int i = 0; i < cost.cols(); i++) {
				if (primed(z1.first, i)){
					series.push_back(std::make_pair(z1.first, i));
					break;
				}
			}

			done = true;
			const auto& z2 = series.back();
			for (int i = 0; i < cost.rows(); i++){
				if (starred(i, z2.second)) {
					done = false;
				}
			}
		}

		for (int i = 0; i < series.size(); i++) {
			if (i % 2 == 0) {
				starred(series[i].first, series[i].second) = 1;
			}
			else {
				starred(series[i].first, series[i].second) = 0;
			}
		}

		primed.setZero();
		covered_rows.setZero();
		covered_cols.setZero();

		return step3();
	}

	/*****************************
	 * step6
	*****************************/
	void step6(T smallest) {
		for (int i = 0; i < cost.rows(); i++) {
			if (covered_rows[i]) {
				cost.row(i).array() += smallest;
			}
		}
		for (int i = 0; i < cost.cols(); i++) {
			if (!covered_cols[i]) {
				cost.col(i).array() -= smallest;
			}
		}

		return step4();
	}

	/*****************************
	 * showState
	 * show all matrices
	*****************************/
	void showState() const {
		std::cout << "--- cost ---" << std::endl << cost << std::endl;
		std::cout << "--- starred ---" << std::endl << starred << std::endl;
		std::cout << "--- primed ---" << std::endl << primed << std::endl;

		Eigen::MatrixXi covered(covered_rows.size(), covered_cols.size());
		for (int i = 0; i < covered.rows(); i++) {
			for (int j = 0; j < covered.cols(); j++) {
				covered(i, j) = covered_rows[i] + covered_cols[j];
			}
		}
		std::cout << "--- covered ---" << std::endl << covered << std::endl;
	}

private:
	int K;
	Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic> cost;

	Eigen::MatrixXi starred;
	Eigen::MatrixXi primed;

	Eigen::VectorXi covered_rows;
	Eigen::VectorXi covered_cols;
};

	}
}

#endif


// Implementing the class that is defined in the header file: Option.hpp
//
// (c) Sudhansh Dua

#include "Option.hpp"
#include <cmath>
#include <boost/math/distributions.hpp>

using namespace std;
using namespace boost::math;

//	Gaussian functions using boost libraries
double Option::N(double x) const
{
	normal_distribution<> Standard_normal(0.0, 1.0);
	return cdf(Standard_normal, x);
}

double Option::n(double x) const
{
	normal_distribution<> Standard_normal(0.0, 1.0);
	return pdf(Standard_normal, x);
}

//	Kernel functions
double Option::CallPrice() const
{
	return ::CallPrice(S, K, T, r, sig, b);
}

double Option::PutPrice() const
{
	return ::PutPrice(S, K, T, r, sig, b);
}

//	Initialising all the default values
void Option::init()
{
	//	Default values
	r = 0.03;
	sig = 0.2;
	K = 100;
	S = 95;				//	Default stock price
	T = 1;
	b = r;				//	Black - Scholes(1973) stock option model : b = r
	type = "C";			//	Call option as the default
}

void Option::copy(const Option& option)
{
	S = option.S;
	K = option.K;
	T = option.T;
	r = option.r;
	sig = option.sig;
	b = option.b;
	type = option.type;
}

//	Constructors and destructor
Option::Option()						//	Default constructor
{
	init();
}

Option::Option(const Option& option)				//	Copy constructor
{
	copy(option);
}

//	Constructor that accepts values
Option::Option(const double& S1, const double& K1, const double& T1, const double& r1,
	const double& sig1, const double& b1, const string type1) : S(S1), K(K1), T(T1), r(r1), sig(sig1), b(b1), type(type1) {}

Option::~Option() {}						//	Destructor

//	Assignment operator
Option& Option::operator = (const Option& option)
{
	if (this == &option)
	{
		return *this;
	}
	copy(option);
	return *this;
}

//	Functions that calculate option price and sensitivities
double Option::Price() const
{
	if (type == "C")
	{
		return CallPrice();

	}
	else
	{
		return PutPrice();
	}
}

// Modifier functions
void Option::toggle()				//	Change the option type
{
	type = ((type == "C") ? "P" : "C");
}

//	Global Functions
double CallPrice(const double S, const double K, const double T, const double r, const double sig, const double b)
{
	double d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));
	double d2 = d1 - (sig * sqrt(T));
	normal_distribution<> standard_normal(0.0, 1.0);

	return (S * exp((b - r) * T) * cdf(standard_normal, d1)) - (K * exp(-r * T) * cdf(standard_normal, d2));
}

double PutPrice(const double S, const double K, const double T, const double r, const double sig, const double b)
{
	double d1 = (log(S / K) + (b + (sig * sig) * 0.5) * T) / (sig * sqrt(T));
	double d2 = d1 - (sig * sqrt(T));
	normal_distribution<> standard_normal(0.0, 1.0);

	return (K * exp(-r * T) * cdf(standard_normal, -d2)) - (S * exp((b - r) * T) * cdf(standard_normal, -d1));
}


#include <iostream>
#include <vector>
#include <fstream>
#include <string>
#include <algorithm>
#include <boost/numeric/ublas/vector.hpp>
#include <boost/numeric/ublas/matrix.hpp>
#include <boost/numeric/ublas/vector_proxy.hpp>
#include <boost/numeric/ublas/matrix_proxy.hpp>
#include <boost/numeric/ublas/triangular.hpp>
#include <boost/numeric/ublas/io.hpp>

using namespace boost::numeric;

template<class type>
inline static void rotate(type c, type s, type &r, type &h)
{
    type tmp = c * r + s * h;
    h        = c * h - s * r;
    r        = tmp;
}

template<class type>
int gmres(ublas::vector<type> &y, ublas::matrix<type> &A, ublas::vector<type> &x, type tol, size_t m)
{
    using namespace ublas;

    typedef vector<type> Vec;
    typedef matrix<type> Mat;

    int size = y.size();
    unit_vector<type> e_1(size + 1, 0);

    m = (m > size) ?size :m;

    // Lower case name for vector
    Vec x_i(x);
    Vec r_i = y - prod(A, x);
    Vec v_i = r_i / norm_2(r_i);
    Vec e_i = e_1 * norm_2(r_i);

    // Givens rotation args
    Vec c(m + 1, 0);
    Vec s(m + 1, 0);

    // Upper case name for matrix, V = V^t, R = Q^t * H
    Mat V(m, size, 0);
    Mat R(size + 1, m, 0);

    for(int i = 0; i < size; i++)
    {
        type beta = norm_2(r_i);
        Vec  v_i  = r_i / beta;
        Vec  e_i  = e_1 * beta;

        int dim = 0;
        V.clear();
        for(int j = 0; j < m; j++)
        {
            row(V, j) = v_i;
            v_i       = prod(A, v_i);
            for(int k = 0; k <= j; k++)
            {
                R(k, j) = inner_prod(v_i, row(V, k));
                v_i    -= R(k, j) * row(V, k);
            }

            // Re-orthogonalization
            #pragma omp parallel for
            for(int k = 0; k <= j; k++)
            {
                type tmp   = inner_prod(v_i, row(V, k));
                row(V, k) -= tmp * v_i;
            }

            R(j + 1, j) = norm_2(v_i);

            dim++;
            if(R(j + 1, j) > tol)
            {
                v_i /= R(j + 1, j);
            }
            else
            {
                R(j + 1, j) = (type) 0;
                v_i.clear();
                break;
            }
        }

        // Apply givens rotation
        for(int j = 0; j < m; j++)
        {
            type r = std::sqrt(R(j, j) * R(j, j) + R(j + 1, j) * R(j + 1, j));
            if(r > tol)
            {
                c(j)   = R(j, j)     / r;
                s(j)   = R(j + 1, j) / r;
            }
            else
            {
                c(j) = (type) 1;
                s(j) = (type) 0;
            }

            rotate(c(j), s(j), R(j, j), R(j + 1, j));
            rotate(c(j), s(j), e_i(j), e_i(j + 1));
        }

        // Solve for y_i
        Vec y_i(solve(subrange(R, 0, dim, 0, dim), subrange(e_i, 0, dim), upper_tag()));

        // Update x
        x_i += prod(y_i, subrange(V, 0, dim, 0, size));
        r_i  = y - prod(A, x_i);

        if(norm_2(r_i) < tol) break;
    }

    x = x_i;
    return 0;
}

int main(int argc, char **argv)
{
    std::cout.precision(15);

    int size, nnz;
    std::string filename;
    if(argc == 2) filename = argv[1];
    else filename = "prob.mtx";

    std::ifstream prob(filename);
    if(!prob.is_open()) exit(0);
    prob >> size;
    prob >> size >> nnz;

    std::cout << "Problem size : " << size << std::endl;

    ublas::vector<double> x(size, 0.0);
    ublas::vector<double> y(size, 1.0);
    ublas::matrix<double> A(size, size, 0.0);

    // Set up problem
    for(int i = 0; i < nnz; i++)
    {
        int tmpRow, tmpCol;
        double tmpVal;

        prob >> tmpRow >> tmpCol >> tmpVal;
        A(tmpRow - 1, tmpCol - 1) = tmpVal;
    }

    // GMRES
    if(gmres(y, A, x, 1e-12, y.size()) != 0)
    {
        std::cout << "GMRES not converged" << std::endl;
    }
    else
    {
        double r = norm_2(y - prod(A, x));
        std::cout << "r   = " << r << std::endl;
        std::cout << "err = " << r / norm_2(y) << std::endl;
    }

    std::cout << x << std::endl;

    return 0;
}


/*
This file implements a simple neural network class and wrapppers to access it fom Python.
We use the mean square error as loss function and a sigmoid as activation function.
(We use that, if f is the sigmoid, f' = (1-f)*f.)
We assume that
	* the number of neurons in the first layer is equal to the number of inputs,
	* there is exactly one neuron in the last layer.
*/

#include <iostream>
#include <fstream>
#include <math.h>
#include <random>
#include <vector>
#include <boost/python.hpp>

using namespace std;
using namespace boost::python;

template <typename T>
vector<T> python_list_to_vector(list& l, T x){ // second argument used for template deduction
	vector<T> res;
	for(int i=0; i < len(l); i++){
		res.push_back(extract<T>(l[i]));
	}
	return res;
}

template <typename T>
list vector_to_python_list(vector<T> v){
	list res;
	for(int i=0; i<v.size(); i++){
		res.append(v[i]);
	}
	return res;
}

template <typename T>
vector<vector<T>> python_list_of_lists_to_vector(list& l, T x){ // second argument used for template deduction
	vector<vector<T>> res;
	for(int i=0; i < len(l); i++){
		vector<T> line;
		for(int j=0; j < len(l[i]); j++){
			line.push_back(extract<T>(l[i][j]));
		}
		res.push_back(line);
	}
	return res;
}

double sigmoid(double x){
	return (1. / (1. + exp(-x)));
}

class NeuralNetwork1{

	private:

		int N_layers;
		vector<int> layers;
		vector<vector<vector<double>>> weights;
		vector<vector<double>> bias;

	public:

		// constructor with random weights and bias

		void build_network(vector<int> layers_){
			N_layers = layers_.size();
			default_random_engine generator(time(0));
			normal_distribution<double> distribution(0.,1.);
			int N_k;
			for(int i=0; i<N_layers; i++){
				layers.push_back(layers_[i]);
				vector<vector<double>> weights_layer;
				vector<double> bias_layer;
				for(int j=0; j<layers[i]; j++){
					vector<double> weights_neuron;
					if(i > 0){
						N_k = layers[i-1];
					}
					else{
						N_k = layers[0]; // assume the first layer as as many neurons as there are inputs
					}
					for(int k=0; k<N_k; k++){
						weights_neuron.push_back(distribution(generator));
					}
					weights_layer.push_back(weights_neuron);
					bias_layer.push_back(distribution(generator));
				}
				weights.push_back(weights_layer);
				bias.push_back(bias_layer);
			}
		}

		NeuralNetwork1(vector<int> layers_){
			build_network(layers);
		}

		// constructor with random weights and bias - python case
		NeuralNetwork1(list& layers_l){
			build_network(python_list_to_vector(layers_l, 0));
		}

		// constructor with given weights and bias
		NeuralNetwork1(vector<int> layers_,
			          vector<vector<vector<double>>> weights_,
		              vector<vector<double>> bias_){
			N_layers = layers_.size();
			layers = layers_;
			weights = weights_;
			bias = bias_;
		}

		// constructor accepting Python lists instead of vectors
		NeuralNetwork1(list& layers_,
			          list& weights_,
		              list& bias_){
			N_layers = len(layers_);
			for(int i=0; i<N_layers; i++){
				layers.push_back(extract<int>(layers_[i]));
				vector<vector<double>> weights_layer;
				vector<double> bias_layer;
				for(int j=0; j<layers[i]; j++){
					vector<double> weights_neuron;
					for(int k=0; k<len(weights_[i][j]); k++){
						weights_neuron.push_back(extract<double>(weights_[i][j][k]));
					}
					weights_layer.push_back(weights_neuron);
					bias_layer.push_back(extract<double>(bias_[i][j]));
				}
				weights.push_back(weights_layer);
				bias.push_back(bias_layer);
			}
		}

		vector<double> feedforward(vector<double> x){
			for(int i=0; i<N_layers; i++){
				vector<double> y;
				for(int j=0; j<layers[i]; j++){
					double z = bias[i][j];
					for(int k=0; k<x.size(); k++){
						z += weights[i][j][k]*x[k];
					}
					y.push_back(sigmoid(z));
				}
				x = y;
			}
			return x;
		}

		// feedforward using a Python list as input
		list feedforward_python(list& x){
			vector<double> y = feedforward(python_list_to_vector(x, 0.));
			return vector_to_python_list(y);
		}

		// evaluating the loss function
		double loss(vector<vector<double>> data, vector<double> y_true_all){
			double res = 0.;
			for(int i=0; i<y_true_all.size(); i++){
				res += pow(feedforward(data[i])[0] - y_true_all[i], 2);
			}
			return res / y_true_all.size();
		}

		// evaluating the loss function - Python
		double loss_python(list& data, list& y_true_all){
			return loss(python_list_of_lists_to_vector(data ,0.), python_list_to_vector(y_true_all, 0.));
		}

		// training function
		void train(vector<vector<double>> data, vector<double> y_true_all, double learn_rate, long epochs){
			for(long epoch = 0; epoch < epochs; epoch++){
				for(int index_data = 0; index_data < y_true_all.size(); index_data++){
					vector<double> x = data[index_data];
					double y_true = y_true_all[index_data];

					// feedforward, retaining the state of each neuron
					vector<vector<double>> states;
					states.push_back(x);
					for(int i=0; i<N_layers; i++){
						vector<double> y;
						for(int j=0; j<layers[i]; j++){
							double z = bias[i][j];
							for(int k=0; k<x.size(); k++){
								z += weights[i][j][k]*x[k];
							}
							y.push_back(sigmoid(z));
						}
						states.push_back(y);
						x = y;
					}

					//predicted value: state of the last neuron (the last layer is assumed to contain only one neuron)
					double y_pred = states[N_layers][0];

					// derivative of the loss function with respect to y_pred
					double d_L_d_ypred = 2.*(y_pred - y_true);

					// partial derivatives
					vector<vector<vector<double>>> d_ypred_d_x;
					vector<vector<vector<double>>> d_ypred_d_weights;
					vector<vector<double>> d_ypred_d_bias;

					//partial derivatives - output layer
					double state = states[N_layers][0];
					vector<vector<double>> d_ypred_d_x_layer;
					vector<double> d_ypred_d_x_neuron;
					vector<vector<double>> d_ypred_d_weights_layer;
					vector<double> d_ypred_d_weights_neuron;
					vector<double> d_ypred_d_bias_layer;
					for(int k=0; k<layers[N_layers-2]; k++){
						d_ypred_d_x_neuron.push_back(weights[N_layers-1][0][k]*state*(1.-state));
						d_ypred_d_weights_neuron.push_back(states[N_layers-1][k]*state*(1.-state));
					}
					d_ypred_d_x_layer.push_back(d_ypred_d_x_neuron);
					d_ypred_d_weights_layer.push_back(d_ypred_d_weights_neuron);
					d_ypred_d_bias_layer.push_back(state*(1.-state));

					d_ypred_d_x.insert(d_ypred_d_x.begin(), d_ypred_d_x_layer);
					d_ypred_d_weights.insert(d_ypred_d_weights.begin(), d_ypred_d_weights_layer);
					d_ypred_d_bias.insert(d_ypred_d_bias.begin(), d_ypred_d_bias_layer);

					//partial derivatives - other layers
					for(int i=2; i<N_layers+1; i++){
						vector<vector<double>> d_ypred_d_x_layer;
						vector<vector<double>> d_ypred_d_weights_layer;
						vector<double> d_ypred_d_bias_layer;
						for(int j=0; j<layers[N_layers - i]; j++){
							double d_ypred_d_yint = 0.;
							for(int k=0; k<layers[N_layers-i+1]; k++){
								d_ypred_d_yint += d_ypred_d_x[0][k][j];
							}
							double state = states[N_layers-i+1][j];
							vector<double> d_ypred_d_x_neuron;
							vector<double> d_ypred_d_weights_neuron;
							for(int k=0; k<weights[N_layers-i][j].size(); k++){
								d_ypred_d_x_neuron.push_back(weights[N_layers-i][j][k]*state*(1.-state)*d_ypred_d_yint);
								d_ypred_d_weights_neuron.push_back(states[N_layers-i][k]*state*(1.-state)*d_ypred_d_yint);
							}
							d_ypred_d_x_layer.push_back(d_ypred_d_x_neuron);
							d_ypred_d_weights_layer.push_back(d_ypred_d_weights_neuron);
							d_ypred_d_bias_layer.push_back(state*(1.-state)*d_ypred_d_yint);
						}
						d_ypred_d_x.insert(d_ypred_d_x.begin(), d_ypred_d_x_layer);
						d_ypred_d_weights.insert(d_ypred_d_weights.begin(), d_ypred_d_weights_layer);
						d_ypred_d_bias.insert(d_ypred_d_bias.begin(), d_ypred_d_bias_layer);
					}

					// update weights and bias
					for(int i=0; i<N_layers; i++){
						for(int j=0; j<layers[i]; j++){
							for(int k=0; k<weights[i][j].size(); k++){
								weights[i][j][k] -= learn_rate * d_L_d_ypred * d_ypred_d_weights[i][j][k];
							}
							bias[i][j] -= learn_rate * d_L_d_ypred * d_ypred_d_bias[i][j];
						}
					}
				}
			}
		}

		// training function - Python
		void train_python(list& data, list& y_true_all, double learn_rate, long epochs){
			train(python_list_of_lists_to_vector(data ,0.), python_list_to_vector(y_true_all, 0.), learn_rate, epochs);
		}

		// save the neural network to a file
		void save(char* filename){
			ofstream file;
			file.open(filename);
			file << N_layers << '\n';
			for(int i=0; i<N_layers; i++){
				file << layers[i] << '\t';
			}
			file << '\n';
			for(int i=0; i<N_layers; i++){
				for(int j=0; j<layers[i]; j++){
					file << weights[i][j].size() << '\t';
					for(int k=0; k<weights[i][j].size(); k++){
						file << weights[i][j][k] << '\t';
					}
					file << bias[i][j] << '\t';
				}
			}
			file.close();
		}

		// load the neural network from a file
		void load(char* filename){
			ifstream file;
			file.open(filename);
			file >> N_layers;
			layers.clear();
			long n_neurons;
			long n_weights;
			double weight_;
			double bias_;
			for(int i=0; i<N_layers; i++){
				file >> n_neurons;
				layers.push_back(n_neurons);
			}
			weights.clear();
			bias.clear();
			for(int i=0; i<N_layers; i++){
				vector<vector<double>> weights_layer;
				vector<double> bias_layer;
				for(int j=0; j<layers[i]; j++){
					vector<double> weights_neuron;
					file >> n_weights;
					for(int k=0; k<n_weights; k++){
						file >> weight_;
						weights_neuron.push_back(weight_);
					}
					file >> bias_;
					bias_layer.push_back(bias_);
					weights_layer.push_back(weights_neuron);
				}
				weights.push_back(weights_layer);
				bias.push_back(bias_layer);
			}
			file.close();
		}

		// implement load
};

BOOST_PYTHON_MODULE(NN1)
{
    class_<NeuralNetwork1>("NeuralNetwork1", init<list&>())
		.def(init<list&, list&, list&>())
		.def("feedforward", &NeuralNetwork1::feedforward_python)
		.def("loss", &NeuralNetwork1::loss_python)
		.def("train", &NeuralNetwork1::train_python)
		.def("save", &NeuralNetwork1::save)
		.def("load", &NeuralNetwork1::load)
	;
}


#pragma once
/*!
* \file GrapheneFloquet.hpp
*
* \brief Functions associated to Floquet Hamiltonian calculations
*
* \author Author: D. Gagnon <denisg6@hotmail.com>
*/
// Include some headers
#include <complex>
#include <armadillo>
#include <boost/numeric/odeint.hpp>

using namespace std::complex_literals; // Complex literals

typedef std::complex<double> c_state_type; // Type of container used to hold the state vector
typedef boost::numeric::odeint::runge_kutta_cash_karp54< c_state_type > error_stepper_type; // Error stepper for odeint

/// Real part of gamma factor appearing in the tight-binding Hamiltonian
double Re_Gamma (double kx, double ky)
{
    return 1.0 + 2.0*cos(0.5*sqrt(3.0)*kx)*cos(0.5*3.0*ky);
}

/// Imaginary part of gamma factor appearing in the tight-binding Hamiltonian
double Im_Gamma (double kx, double ky)
{
    return 2.0*cos(0.5*sqrt(3.0)*kx)*sin(0.5*3.0*ky);
}

/*!
* \class gamma_integrand
*
* \brief Base class for the integrand used in gamma factor calculations
*
* \author Author: D. Gagnon <denisg6@hotmail.com>
*/
class gamma_integrand {

    // Parameters of the Hamiltonian
    double m_kx,m_ky,m_omega,m_E0,m_index;

private:

    // Physical constants definitions
    double hbar = 6.5821195140e-16;                             // Planck constant over 2 pi in eV s
    double lat_constant = 2.4e-10/sqrt(3.0);                    // Lattice constant in meters
    double v_Fermi = 0.003646*2.9979245800e+08;                 // Fermi velocity in graphene

public:

    /// Constructor taking as input the parameters of the Hamiltonian
    /// @param kx float, x-component of the momentum
    /// @param ky float, y-component of the momentum
    /// @param omega float, angular frequency of the field in rad/s
    /// @param E0 float, electric field peak value in V/m
    /// @param index int, index of Fourier coefficients
    gamma_integrand(double kx, double ky, double omega, double E0, int index)
        : m_kx(kx)
        , m_ky(ky)
        , m_omega(omega)
        , m_E0(E0)
        , m_index(index) { }

    /// Overload of operator() for ODE integration
    void operator() ( const c_state_type &z, c_state_type &dzdt, const double t)
    {

        // Conversion factor
        double factor = lat_constant*m_E0/(hbar*m_omega);

        // Peierls substitution
        double kx_field = m_kx + factor*std::cos(t);
        double ky_field = m_ky;

        // Compute gamma factors
        double Re_Gamma_t = Re_Gamma(kx_field, ky_field);
        double Im_Gamma_t = Im_Gamma(kx_field, ky_field);

        // Rhs of the ODE system
        dzdt = (Re_Gamma_t + 1i*Im_Gamma_t)*std::exp(-1i*m_index*t);

    }

    /// Function updating the value of the index
    void SetIndex(int m)
    {
        this->m_index = m;
    }

};

/// Function returning the Fourier coefficients to be used in Floquet Hamiltonian
std::vector< c_state_type > GammaValues(double kx, double ky, double omega, double E0, int max_index)
{
    std::vector< c_state_type > Gamma(2*max_index + 1, 0.0);

    for (int vec_index = 0; vec_index < 2*max_index + 1; vec_index ++)
    {

        // State variable to solve result
        c_state_type z(0.0,0.0);

        // Define integrand
        gamma_integrand integrand(kx,ky,omega,E0, vec_index - max_index);

        // Adaptive integration
        boost::numeric::odeint::integrate_adaptive(
            boost::numeric::odeint::make_controlled< error_stepper_type >( 1.0e-10, 1.0e-6 ),
            integrand,
            z, 0.0, 2.0*M_PI, 2.0*M_PI/10000.0 );

        // Assign value to "Gamma" vector
        Gamma[vec_index] = (0.5/M_PI)*z;

    }

    return Gamma;
}

/// Compute Floquet eigen-energies and probabilities
arma::vec QuasiEnergies(double kx, double ky, double omega, double E0,
                        int blocks, double &prob, double &prob_sigma)
{

    // Physical constants definitions
    double hbar = 6.5821195140e-16;                             // Planck constant over 2 pi in eV s
    double lat_constant = 2.4e-10/sqrt(3.0);                    // Lattice constant in meters
    double v_Fermi = 0.003646*2.9979245800e+08;                 // Fermi velocity in graphene

    double freq = hbar*omega;                        // Frequency in eV
    double tb = - 2*(hbar*v_Fermi)/(3.0*lat_constant); // Tight-binding energy of graphene

    // Total number of blocks including
    // zeroth block
    int totalblocks = 2*blocks + 1;

    // Pre-calculate Fourier coefficients of Hamiltonian
    auto Gamma = GammaValues(kx,ky,omega,E0,2*blocks);

    // Initialize Tmatrix which is to be filled by [totalblocks] 2 x 2 matrices
    arma::Mat<double> zeromat(2*totalblocks,2*totalblocks, arma::fill::zeros);
    arma::cx_mat Ham(zeromat,zeromat); // Hamiltonian

    // FILL MAIN DIAGONAL OF HAMILTONIAN
    // Initialize index m
    int m = -blocks;

    for (int j_= 0; j_ < 2*totalblocks; j_ = j_ + 2)
    {
        Ham.diag(0)[j_] = m*freq;
        Ham.diag(0)[j_ + 1] = m*freq;

        // Increment m
        m++;
    }

    // FILL UPPER AND LOWER DIAGONAL OF HAMILTONIAN

    int nm = 0; // Initialize index (n-m)
    int index_shift = 2*blocks; // Index shift (for gamma vector)

    for (int i_= 1; i_ < 2*totalblocks; i_ = i_ + 2) // Loop on diagonals
    {
        int index0 = nm;
        int index1 = nm + 1;

        //std::cout << i_ << std::endl;

        for (int j_ = 0; j_ < 2*totalblocks - i_; j_ ++) // Loop on elements of diagonals
        {

            //std::cout << j_ << std::endl;

            if (j_ % 2 == 0) // If j_ is even do
            {
                Ham.diag( i_)[j_] = tb*std::conj(Gamma[-index0 + index_shift]);
                Ham.diag(-i_)[j_] = tb*Gamma[index0 + index_shift];

                //std::cout << "Even j" << std::endl;
                //std::cout << Ham.diag( i_)[j_] << std::endl;
                //std::cout << Ham.diag( -i_)[j_] << std::endl;

            }
            else // If j_ is odd do
            {
                Ham.diag( i_)[j_] = tb*Gamma[-index1 + index_shift];
                Ham.diag(-i_)[j_] = tb*std::conj(Gamma[index1 + index_shift]);

                //std::cout << "Odd j" << std::endl;
                //std::cout << Ham.diag( i_)[j_] << std::endl;
                //std::cout << Ham.diag( -i_)[j_] << std::endl;
            }
        }

        nm++; // Increment (n-m) as we shift to the next non-zero diagonal

    }

    // std::cout << Ham << std::endl;

    // arma::mat realpart = arma::real(Ham);
    // arma::mat imagpart = arma::imag(Ham);

    // realpart.save("Hamreal.dat",arma::raw_ascii);
    // imagpart.save("Hamimag.dat",arma::raw_ascii);

    // Initialize eigenvalue vector and eigenvector matrix and
    arma::vec eigval;
    arma::cx_mat eigvec;

    // Compute eigenvalues
    bool status = arma::eig_sym(eigval, eigvec, Ham);
    if (status == false)
    {
        std::cout << "Eigenvalue decomposition failed" << std::endl;
    }

    // std::cout << eigvec << std::endl;

    // COMPUTE TRANSITION PROBABILITY

    // Variables to be used in loop
    prob = 0.0;
    prob_sigma = 0.0; // Passed by reference, will change
    std::complex<double> alphazero, betazero; // Ground state amplitude
    std::complex<double> alphan, betan; // Excited state amplitude
    std::complex<double> pos; // Positive energy state amplitude
    std::complex<double> neg; // Negative energy state amplitude
    arma::cx_vec the_eigenvec;

    // Compute "no-field" phase factor
    double angle = std::atan2(Im_Gamma(kx,ky), Re_Gamma(kx,ky) );
    std::complex<double> phase_factor = std::exp(1i*angle);

    // Loop on every eigenvector
    for (size_t i_= 0; i_ < eigvec.n_cols; i_ ++)
    {
        the_eigenvec = eigvec.col(i_); // Slice eigenvectors

        alphazero = the_eigenvec[the_eigenvec.n_elem/2 - 1];
        betazero = the_eigenvec[the_eigenvec.n_elem/2];

        // Negative energy state
        neg = 0.5*std::sqrt(2.0)*(alphazero - phase_factor*betazero);

        // Loop on elements
        for (size_t j_= 0; j_ < the_eigenvec.n_elem; j_ ++)
        {

            if (j_ % 2 != 0) // If j is odd do, else do nothing
            {
                alphan = the_eigenvec[j_ - 1];
                betan  = the_eigenvec[j_];

                // Positive energy state
                pos = 0.5*std::sqrt(2.0)*(alphan + phase_factor*betan);

                // Fermi's rule
                prob += std::norm(std::conj(pos)*neg); // Transition between eigenstates
                prob_sigma += std::norm(std::conj(betan)*alphazero); // Transition between sigma_z eigenstates
            }
        }
    }

    return eigval;

}


#include <iostream>
#include <vector>
#include <Eigen/Dense>
#include "../simple_lib/include/simple_activation.h"

using namespace Eigen;

double cross_entropy_error(MatrixXd &, MatrixXd &); // プロトタイプ宣言

class simpleNet
{
private:
    MatrixXd W = MatrixXd::Random(2, 3); // 乱数で初期化(本来はXavierの初期値とかにしたい？)

public:
    simpleNet(); // コンストラクタ
    MatrixXd predict(MatrixXd &);
    double loss(MatrixXd &, MatrixXd &);
    MatrixXd gradient(MatrixXd&, MatrixXd&);

    void print_W(void);
};

int main(){
    using std::cout;
    using std::endl;

    simpleNet net;
    net.print_W();

    MatrixXd X = MatrixXd::Zero(2, 1);
    MatrixXd P;

    X << 0.6, 0.9;

    P = net.predict(X);
    cout << "--- predict result ---" << endl;
    cout << P << endl;
    cout << "--- softmax ---" << endl;
    cout << MyDL::softmax(P) << endl;

    MatrixXd t = MatrixXd::Zero(1, 3);
    t << 0, 0, 1; // この書き方をするには、上記のようにメモリ確保をしておく必要がある(でないとセグフォになる)

    double loss;
    loss = net.loss(X, t);

    cout << "--- loss ---" << endl;
    cout << loss << endl;

    MatrixXd dW = MatrixXd::Zero(2, 3);

    dW = net.gradient(X, t);

    cout << "--- dW ---" << endl;
    cout << dW << endl; // 0.2, 0.2, -0.4; 0.3, 0.3, -0.6 (Wをすべて1で初期化した場合)が正解

    return 0;
}

simpleNet::simpleNet(){
    // W << 0.47355232, 0.9977393, 0.84668094, 0.85557411, 0.03563661, 0.69422093;
    W << 1,1,1,1,1,1;
}

MatrixXd simpleNet::predict(MatrixXd& X){
    return X.transpose() * W;
}

double simpleNet::loss(MatrixXd& X, MatrixXd& t){
    MatrixXd Y, Z;
    Z = simpleNet::predict(X);
    Y = MyDL::softmax(Z);

    double loss;
    loss = cross_entropy_error(Y, t);

    return loss;
}

void simpleNet::print_W(void){
    using std::cout;
    using std::endl;

    cout << " --- simpleNet parameter W --- " << endl;
    cout << "W = " << W << endl;
}

MatrixXd simpleNet::gradient(MatrixXd& x, MatrixXd& t)
{
    double h = 1e-4;
    MatrixXd grad = MatrixXd::Zero(2, 3);

    for (int i = 0; i < 6; i++)
    {
        double tmp_val = W(i);
        double f_xh1;
        double f_xh2;
        // f(x+h) の計算
        W(i) = tmp_val + h; // 変数xのi番目の要素だけ増分を取った形に変更
        f_xh1 = simpleNet::loss(x, t);
        // f(x-h)の計算
        W(i) = tmp_val - h;
        f_xh2 = simpleNet::loss(x, t);

        grad(i) = (f_xh1 - f_xh2) / (2 * h);
        W(i) = tmp_val; // 元の値に戻す
    }

    return grad;
}

// one-hot labelバージョンの のミニバッチ実装
double cross_entropy_error(MatrixXd &y, MatrixXd &t)
{
    int batch_size = y.rows();
    double ret = (t.array() * y.array().log()).sum() / batch_size;
    return -ret;
}


#include <cmath>
#include <unordered_map>
#include <vector>
#include <string>
#include <armadillo>
#include <algorithm>

using std::vector;
using arma::dmat;

// input peakDays check: they cant be on day 0 or _dOI by definition (debugging)
bool PeakCheck(const int peak, const int dOI) {
	if ((peak<=0)||(peak>=dOI)) return 1;
	else return 0;
}

// Finds the closest boundary between end and beginning of illnes and
// peak day
int MinDist(const int dOI, const int peakDay) { return std::min(peakDay, dOI-peakDay); }

// Finds the gaussian integral between -inf and x
double CumGauss(const double& x) {
    double PAYLOAD;
    PAYLOAD = 0.5*(erf(10) + erf(x));
    return PAYLOAD;
}

// Cretes a square matrix of zeros setting the first row equal to the
// vector<double> given as argument (broadcast).
// NB: it converts std::vectors tu arma::dmat-s
dmat CastVecMat(const vector<double>& vec) {
	// we need to make vec a row vector first
	arma::drowvec temp(vec);

	// building the payload
	int size = temp.n_elem;
	dmat PAYLOAD(temp);
	PAYLOAD.resize(size, size);

	// initializing setting to zero the zero elements
	PAYLOAD(1,0,arma::size(size-1,size)) = arma::zeros(size-1,size);
	return PAYLOAD;
}

// Very specific function, build the propagation matrix of a status change
// given its discrete cumulative function.
dmat BuildDistribMat(vector<double> vec) {

	// calculate the distribution from a cumulative
	for (int i= vec.size()-1; i!=0; i--) vec[i] -= vec[i-1];

	// insert a zero at the beginning (as the model requires it)
	vec.insert(vec.begin(),0);

	// now add the zeroes underneath to make it a matrix
	dmat PAYLOAD(CastVecMat(vec));

	return PAYLOAD;
}

// Computes the discrete cumulative probability function of a status change given
// its parameters
vector<double> CumProbFunc(const int dOI, const int peakDay, const double finalProb,const std::string type) {

	// Dictionary {1 = Gaussian, 2 = Uniform}
	std::unordered_map<std::string, int> Map;
		Map["Gaussian"] = 1;
		Map["Uniform"] = 2;

	vector<double> PAYLOAD(dOI);

    // switch depending on what type the distribution is
	switch(Map[type]) {
                case 1: {
						// we assume that the distance between end/beginning of illness and
						// the peak day of a status change is 5 sigma
                        double sigma = static_cast<double>(MinDist(dOI, peakDay))/5;
                        // filling the gaussian cumulative
                        for (int i=0; i<dOI; i++)
                            PAYLOAD[i] = finalProb*CumGauss((i-peakDay+1)/sqrt(2)/sigma);
                        break;
                }
                case 2: {
						// slope
                        double distrValue = 1./static_cast<double>(dOI)*finalProb;
                        // filling the uniform cumulative
						for (int i=0; i<dOI; i++)
							PAYLOAD[i] = distrValue*static_cast<double>(i+1);
                        break;
                }
	};

	return PAYLOAD;
}


#include <iostream>
#include <Eigen/Dense>

using namespace std;
using namespace Eigen;

int main()
{
   MatrixXd A = MatrixXd::Random(100,100);
   MatrixXd b = MatrixXd::Random(100,50);
   MatrixXd x = A.fullPivLu().solve(b);
   double relative_error = (A*x - b).norm() / b.norm(); // norm() is L2 norm
   cout << "The relative error is:\n" << relative_error << endl;
}


// smooth: Lie Theory for Robotics
// https://github.com/pettni/smooth
//
// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
//
// Copyright (c) 2021 Petter Nilsson
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.

#ifndef SMOOTH__SE3_HPP_
#define SMOOTH__SE3_HPP_

#include <Eigen/Core>
#include <Eigen/Geometry>

#include <complex>

#include "internal/lie_group_base.hpp"
#include "internal/macro.hpp"
#include "internal/se3.hpp"
#include "lie_group.hpp"
#include "map.hpp"
#include "so3.hpp"

namespace smooth {

template<typename Scalar>
class SE2;

/**
 * @brief Base class for SE3 Lie group types.
 *
 * Internally represented as \f$\mathbb{S}^3 \times \mathbb{R}^3\f$.
 *
 * Memory layout
 * -------------
 *
 * - Group:    \f$ \mathbf{x} = [x, y, z, q_x, q_y, q_z, q_w] \f$
 * - Tangent:  \f$ \mathbf{a} = [v_x, v_y, v_z, \omega_x, \omega_y, \omega_z] \f$
 *
 * Constraints
 * -----------
 *
 * - Group:   \f$q_x^2 + q_y^2 + q_z^2 + q_w^2 = 1 \f$
 * - Tangent: \f$ -\pi < \omega_x, \omega_y, \omega_z \leq \pi \f$
 *
 * Lie group matrix form
 * ---------------------
 *
 * \f[
 * \mathbf{X} =
 * \begin{bmatrix}
 *   R & T \\
 *   0 & 1
 * \end{bmatrix} \in \mathbb{R}^{4 \times 4}
 * \f]
 *
 * where \f$R\f$ is a 3x3 rotation matrix and \f$ T = [x, y, z]^T \f$.
 *
 *
 * Lie algebra matrix form
 * -----------------------
 *
 * \f[
 * \mathbf{a}^\wedge =
 * \begin{bmatrix}
 *   0        & -\omega_z & \omega_y  & v_x \\
 *  \omega_z  & 0         & -\omega_x & v_y \\
 *  -\omega_y & \omega_x  & 0         & v_y \\
 *  0         & 0         & 0         & 0
 * \end{bmatrix} \in \mathbb{R}^{4 \times 4}
 * \f]
 */
template<typename _Derived>
class SE3Base : public LieGroupBase<_Derived>
{
  using Base = LieGroupBase<_Derived>;

protected:
  SE3Base() = default;

public:
  SMOOTH_INHERIT_TYPEDEFS;

  /**
   * @brief Access SO(3) part.
   */
  Map<SO3<Scalar>> so3() requires is_mutable
  {
    return Map<SO3<Scalar>>(static_cast<_Derived &>(*this).data() + 3);
  }

  /**
   * @brief Const access SO(3) part.
   */
  Map<const SO3<Scalar>> so3() const
  {
    return Map<const SO3<Scalar>>(static_cast<const _Derived &>(*this).data() + 3);
  }

  /**
   * @brief Access R3 part.
   */
  Eigen::Map<Eigen::Vector3<Scalar>> r3() requires is_mutable
  {
    return Eigen::Map<Eigen::Vector3<Scalar>>(static_cast<_Derived &>(*this).data());
  }

  /**
   * @brief Const access R3 part.
   */
  Eigen::Map<const Eigen::Vector3<Scalar>> r3() const
  {
    return Eigen::Map<const Eigen::Vector3<Scalar>>(static_cast<const _Derived &>(*this).data());
  }

  /**
   * @brief Return as 3D Eigen transform.
   */
  Eigen::Transform<Scalar, 3, Eigen::Isometry> isometry() const
  {
    return Eigen::Translation<Scalar, 3>(r3()) * so3().quat();
  }

  /**
   * @brief Tranformation action on 3D vector.
   */
  template<typename EigenDerived>
  Eigen::Vector3<Scalar> operator*(const Eigen::MatrixBase<EigenDerived> & v) const
  {
    return so3() * v + r3();
  }

  /**
   * @brief Project to SE2.
   *
   * @note SE2 header must be included.
   */
  SE2<Scalar> project_se2() const
  {
    return SE2<Scalar>(so3().project_so2(), r3().template head<2>());
  }
};

// \cond
template<typename _Scalar>
class SE3;
// \endcond

// \cond
template<typename _Scalar>
struct liebase_info<SE3<_Scalar>>
{
  static constexpr bool is_mutable = true;

  using Impl   = SE3Impl<_Scalar>;
  using Scalar = _Scalar;

  template<typename NewScalar>
  using PlainObject = SE3<NewScalar>;
};
// \endcond

/**
 * @brief Storage implementation of SE3 Lie group.
 *
 * @see SE3Base for memory layout.
 */
template<typename _Scalar>
class SE3 : public SE3Base<SE3<_Scalar>>
{
  using Base = SE3Base<SE3<_Scalar>>;

  SMOOTH_GROUP_API(SE3);

public:
  /**
   * @brief Construct from SO3 and translation.
   *
   * @param so3 orientation component.
   * @param r3 translation component.
   */
  template<typename SO3Derived, typename T3Derived>
  SE3(const SO3Base<SO3Derived> & so3, const Eigen::MatrixBase<T3Derived> & r3)
  {
    Base::so3() = static_cast<const SO3Derived &>(so3);
    Base::r3()  = static_cast<const T3Derived &>(r3);
  }

  /**
   * @brief Construct from Eigen transform.
   */
  SE3(const Eigen::Transform<Scalar, 3, Eigen::Isometry> & t)
  {
    Base::so3() = smooth::SO3<Scalar>(Eigen::Quaternion<Scalar>(t.rotation()));
    Base::r3()  = t.translation();
  }
};

// \cond
template<typename _Scalar>
struct liebase_info<Map<SE3<_Scalar>>> : public liebase_info<SE3<_Scalar>>
{};
// \endcond

/**
 * @brief Memory mapping of SE3 Lie group.
 *
 * @see SE3Base for memory layout.
 */
template<typename _Scalar>
class Map<SE3<_Scalar>> : public SE3Base<Map<SE3<_Scalar>>>
{
  using Base = SE3Base<Map<SE3<_Scalar>>>;

  SMOOTH_MAP_API();
};

// \cond
template<typename _Scalar>
struct liebase_info<Map<const SE3<_Scalar>>> : public liebase_info<SE3<_Scalar>>
{
  static constexpr bool is_mutable = false;
};
// \endcond

/**
 * @brief Const memory mapping of SE3 Lie group.
 *
 * @see SE3Base for memory layout.
 */
template<typename _Scalar>
class Map<const SE3<_Scalar>> : public SE3Base<Map<const SE3<_Scalar>>>
{
  using Base = SE3Base<Map<const SE3<_Scalar>>>;

  SMOOTH_CONST_MAP_API();
};

using SE3f = SE3<float>;   ///< SE3 with float
using SE3d = SE3<double>;  ///< SE3 with double

}  // namespace smooth

#endif  // SMOOTH__SE3_HPP_


/*
Author: Rohan Chetan Thanki
Date created: 16-Oct-2021
*/

// This file contains the 'main' function. Program execution begins and ends there.

#include "Hedging_Portfolio.hpp"
#include "Utilities.cpp"
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
#include<boost/tokenizer.hpp>
#include <boost/date_time.hpp>
#include<boost/tokenizer.hpp>
#include <boost/date_time.hpp>

/*********************************************** PART 1 ******************************************************/
inline void run_part_1(void)
{
    cout << "\nStart of part 1\n";
    // creating variables
    unsigned int numPaths = 1000;
    unsigned int N = 100;
    double T = 0.4;
    double u = 0.05;
    double sigma = 0.24;
    double r = 0.025;
    double S0 = 100;
    double K = 105;
    char optionFlag = 'c';

    vector<vector<double>> stockPrices = simulateStockPrices(numPaths, N, S0, T, u, sigma);
    vector<vector<Hedging_Portfolio>> hedgedPortfolioAllStates = computeHedgingErrors(stockPrices, K, r, T, sigma, 'c');

    vector<vector<double>> callOptionPrices = getHedgedPortfolioParam(hedgedPortfolioAllStates, "V");
    vector<vector<double>> deltas = getHedgedPortfolioParam(hedgedPortfolioAllStates, "DELTA");
    vector<vector<double>> B = getHedgedPortfolioParam(hedgedPortfolioAllStates, "B");
    vector<vector<double>> hedgingErrors = getHedgedPortfolioParam(hedgedPortfolioAllStates, "HE");

    write2DVectorToCSV(stockPrices, "Output_Files/Part1/Stock_Prices.csv");
    write2DVectorToCSV(callOptionPrices, "Output_Files/Part1/Call_Option_Prices.csv");
    write2DVectorToCSV(deltas, "Output_Files/Part1/Call_Option_Deltas.csv");
    write2DVectorToCSV(B, "Output_Files/Part1/B.csv");
    write2DVectorToCSV(hedgingErrors, "Output_Files/Part1/Hedging_Errors.csv");

    cout << "End of part 1\n\n";
}

/*********************************************** PART 2 ******************************************************/
inline void run_part_2(void)
{
    // reading interest rate data
    vector<vector<string>> interestRateData = readCSV("Data/interest.csv", 1, 2);
    //vector<boost::gregorian::date> interestRateDateVec = stringtoDateVect(interestRateData[0]);
    vector<string> interestRateDateVec = interestRateData[0];
    vector<double> interestRateVec = stringToDoubleVect(interestRateData[1]);

    // reading stock data
    vector<vector<string>> stockData = readCSV("Data/sec_GOOG.csv", 1, 2);
    //vector<boost::gregorian::date> stockDateVec = stringtoDateVect(stockData[0]);
    vector<string> stockDateVec = stockData[0];
    vector<double> stockPriceVec = stringToDoubleVect(stockData[1]);

    // reading option data
    //vector<vector<string>> optionData = readCSV("Data/op_GOOG.csv", 1, 6);
    string optionFilePath = "Data/op_GOOG.csv";
    ifstream infile(optionFilePath);
    string line;
    vector<vector<string>> csvData;

    // get user input
    string startDateUser, endDateUser, expDateUser;
    char optionFlagUser;
    double strikePriceUser;

    /*startDateUser = "2011-07-05";
    endDateUser = "2011-07-29";
    expDateUser = "2011-09-17";
    optionFlagUser = 'c';
    strikePriceUser = 500;*/

    std::cout << "Enter start date in YYYY-MM-DD format: "; cin >> startDateUser;
    std::cout << "Enter end date in YYYY-MM-DD format: "; cin >> endDateUser;
    std::cout << "Enter maturity date in YYYY-MM-DD format: "; cin >> expDateUser;
    std::cout << "Enter option Flag: "; cin >> optionFlagUser;
    std::cout << "Enter strike price of the option: "; cin >> strikePriceUser;

    // Read options data line by line
    getline(infile, line);                              // skipping the first line
    vector<Hedging_Portfolio> allHedgingPortfolios;     // creating a vector to store the hedging portfolio at each date
    while (getline(infile, line))
    {
        // tokenising the row data
        vector<string> rowData = string_splitter(line, ',');

        // reading data in each row
        string date = rowData[0];
        string expDate = rowData[1];
        char flag = toupper(rowData[2][0]);
        double strikePrice = stod(rowData[3]);
        double bidPrice = stod(rowData[4]);
        double askPrice = stod(rowData[5]);
        double marketPrice = (bidPrice + askPrice) / 2;

        // skipping the loop if the details donot match user input
        if (!(strikePrice == strikePriceUser && expDate == expDateUser && flag == toupper(optionFlagUser) && date >= startDateUser && date <= endDateUser))
            continue;

        // creating a hedging portfolio object
        Hedging_Portfolio rowobj;

        //setting values in the object
        rowobj.setDate(date);                               // setting date
        rowobj.setExpDate(rowData[1]);                      // setting expiration date
        rowobj.setFlag(rowData[2][0]);                      // setting flag of the option
        rowobj.setStrikePrice(stod(rowData[3]));            // setting strike price
        rowobj.setOptionPrice(marketPrice);                 // setting market price

        // setting the interest rate
        try
        {
            double rate = findVal(interestRateDateVec, interestRateVec, rowobj.getDate()) / 100;
            rowobj.setRiskFreeRate(rate);
        }
        catch (...)
        {
            std::cout << "No interest rate found for date " << rowobj.getDate() << endl;
        }

        // setting the stock price
        try
        {
            double spotPrice = findVal(stockDateVec, stockPriceVec, rowobj.getDate());
            rowobj.setSpotPrice(spotPrice);
        }
        catch (...)
        {
            std::cout << "No interest rate found for date " << rowobj.getDate() << endl;
        }

        // setting time to maturity
        rowobj.setTimeToMaturity(countWeekDays(rowobj.getDate(), rowobj.getDate()) * 1.0 / 252);

        // setting implied volatility
        double maxVol = 100;
        double impliedVol = rowobj.computeImpliedVol(maxVol);
        rowobj.setVolatility(impliedVol);
        //cout << date << "\t" << expDate << "\t" << flag << "\t" << strikePrice << "\t" << rowobj.getRiskFreeRate() << "\t" << rowobj.getSpotPrice() << "\t" << impliedVol << endl;

        // setting delta
        double delta = rowobj.computeDelta();
        rowobj.setDelta(delta);

        // add the object to the vector
        allHedgingPortfolios.push_back(rowobj);
    }
    infile.close();

    // creating a filestream object to write to a csv file
    string outputFilePath = "Output_Files/Part2/Real_Market_Data_Hedging.csv";
    vector<string> outputFileHeaders{ "Date", "Stock Price", "Option Price", "Implied Volatility", "Option Delta", "Hedging Error", "PNL Naked Short Call", "PNL Hedged Portfolio" };
    std::ofstream outfile(outputFilePath);
    for (int i = 0; i <= outputFileHeaders.size() - 1; i++)
        outfile << outputFileHeaders[i] << ",";
    outfile << "\n";

    // iterating through the vector to compute hedging errors
    for (int j = 0; j <= allHedgingPortfolios.size() - 1; j++)
    {
        // creating variables
        double S = allHedgingPortfolios[j].getSpotPrice();
        double TMat = allHedgingPortfolios[j].getTimeToMaturity();
        double delta = allHedgingPortfolios[j].getDelta();
        double V = allHedgingPortfolios[j].getOptionPrice();
        double dt = 1.0 / 252;
        double deltaPrev, BPrev, rPrev, B, HE;

        // setting B
        if (j == 0)
            B = V - delta * S;
        else
        {
            rPrev = allHedgingPortfolios[j - 1].getRiskFreeRate();
            deltaPrev = allHedgingPortfolios[j - 1].getDelta();
            BPrev = allHedgingPortfolios[j - 1].getB();
            B = ((deltaPrev - delta) * S) + BPrev * exp(rPrev * dt);
        }
        allHedgingPortfolios[j].setB(B);

        // setting Hedging Error
        if (j == 0)
            HE = 0;
        else
            HE = deltaPrev * S + BPrev * exp(rPrev * dt) - V;

        allHedgingPortfolios[j].setHedgingError(HE);

        // Setting PNL for naked short call
        double pnlNaked =  allHedgingPortfolios[0].getOptionPrice() - allHedgingPortfolios[j].getOptionPrice();
        allHedgingPortfolios[j].setpnlNaked(pnlNaked);

        // Setting PNL for hedged portfolio
        double pnlHedged = HE;
        allHedgingPortfolios[j].setpnlHedged(pnlHedged);

        // writing to output file
        outfile << allHedgingPortfolios[j].getDate() << ",";
        outfile << allHedgingPortfolios[j].getSpotPrice() << ",";
        outfile << allHedgingPortfolios[j].getOptionPrice() << ",";
        outfile << allHedgingPortfolios[j].getVolatility() << ",";
        outfile << allHedgingPortfolios[j].getDelta() << ",";
        outfile << allHedgingPortfolios[j].getHedgingError() << ",";
        outfile << allHedgingPortfolios[j].getpnlNaked() << ",";
        outfile << allHedgingPortfolios[j].getpnlHedged() << endl;
    }

    outfile.close();
    cout << "\nEnd of part 2\n";
}