// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef MTL_TRAITS_ROOT_INCLUDE
#define MTL_TRAITS_ROOT_INCLUDE

#include <boost/numeric/mtl/mtl_fwd.hpp>
#include <boost/numeric/mtl/concept/collection.hpp>

namespace mtl { namespace traits {

/// Type trait to reduce types to their essentials by removing const, reference, ... and gearing derived types to their bases
template <typename T>
struct root
{
    typedef T        type;
};

// ==========================
// Remove language attributes
// ==========================

template <typename T>
struct root<T&>
  : public root<T> {};

template <typename T>
struct root<const T>
  : public root<T> {};

// Redundant specialization to make xlc++ happy
template <typename T, int R, int C>
struct root<const T[R][C]>
  : public root<T[R][C]> {};

// ============
// Base classes
// ============

// Implicit dense matrices

template <typename Value>
struct root<mtl::matrix::ones_matrix<Value> >
{
    typedef mtl::matrix::implicit_dense<mtl::matrix::ones_functor<Value> > type;
};

template <typename Value>
struct root<mtl::matrix::hilbert_matrix<Value> >
{
    typedef mtl::matrix::implicit_dense<mtl::matrix::hilbert_functor<Value> > type;
};

template <typename Vector1, typename Vector2>
struct root<mtl::matrix::outer_product_matrix<Vector1, Vector2> >
{
    typedef mtl::matrix::implicit_dense<mtl::matrix::outer_product_functor<Vector1, Vector2> > type;
};

// Matrix map views

template <typename Scaling, typename Matrix>
struct root< mtl::matrix::scaled_view<Scaling, Matrix> >
{
    typedef mtl::matrix::map_view<tfunctor::scale<Scaling, typename Matrix::value_type>, Matrix> type;
};

template <typename Matrix>
struct root< mtl::matrix::conj_view<Matrix> >
{
    typedef mtl::matrix::map_view<sfunctor::conj<typename Matrix::value_type>, Matrix> type;
};

template <typename Matrix>
struct root< mtl::matrix::negate_view<Matrix> >
{
    typedef mtl::matrix::map_view<sfunctor::negate<typename Matrix::value_type>, Matrix> type;
};

template <typename Matrix>
struct root< mtl::matrix::imag_view<Matrix> >
{
    typedef mtl::matrix::map_view<sfunctor::imag<typename Matrix::value_type>, Matrix> type;
};

template <typename Matrix>
struct root< mtl::matrix::real_view<Matrix> >
{
    typedef mtl::matrix::map_view<sfunctor::real<typename Matrix::value_type>, Matrix> type;
};

template <typename Matrix>
struct root< mtl::matrix::hermitian_view<Matrix> >
{
    typedef mtl::matrix::map_view<sfunctor::conj<typename Matrix::value_type>, mtl::matrix::transposed_view<Matrix> > type;
};

template <typename Matrix, typename RScaling>
struct root< mtl::matrix::rscaled_view<Matrix, RScaling> >
{
    typedef mtl::matrix::map_view<tfunctor::rscale<typename Matrix::value_type, RScaling>, Matrix> type;
};

template <typename Matrix, typename Divisor>
struct root< mtl::matrix::divide_by_view<Matrix, Divisor> >
{
    typedef mtl::matrix::map_view<tfunctor::divide_by<typename Matrix::value_type, Divisor>, Matrix> type;
};

// Matrix operations
template <typename M1, typename M2>
struct root< mtl::matrix::mat_mat_plus_expr<M1, M2> >
{
    typedef mtl::sfunctor::plus<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;
    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;
};

template <typename M1, typename M2>
struct root< mtl::matrix::mv_mv_plus_expr<M1, M2> >
{
    typedef typename root< mtl::matrix::mat_mat_plus_expr<M1, M2> >::type type;
};

template <typename M1, typename M2>
struct root< mtl::matrix::mat_mat_minus_expr<M1, M2> >
{
    typedef mtl::sfunctor::minus<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;
    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;
};

template <typename M1, typename M2>
struct root< mtl::matrix::mv_mv_minus_expr<M1, M2> >
{
    typedef typename root< mtl::matrix::mat_mat_minus_expr<M1, M2> >::type type;
};

template <typename M1, typename M2>
struct root< mtl::matrix::mat_mat_times_expr<M1, M2> >
{
    typedef mtl::sfunctor::times<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;
    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;
};

template <typename M1, typename M2>
struct root< mtl::matrix::mat_mat_ele_times_expr<M1, M2> >
{
    typedef mtl::sfunctor::times<typename Collection<M1>::value_type, typename Collection<M2>::value_type> f_type;
    typedef mtl::matrix::mat_mat_op_expr<M1, M2, f_type> type;
};

// Vector assignment expressions

template <typename E1, typename E2>
struct root< vector::vec_vec_asgn_expr<E1, E2> >
{
    typedef vector::vec_vec_aop_expr< E1, E2, mtl::sfunctor::assign<typename E1::value_type, typename E2::value_type> > type;
};

template <typename E1, typename E2>
struct root< vector::vec_vec_plus_asgn_expr<E1, E2> >
{
    typedef vector::vec_vec_aop_expr< E1, E2, mtl::sfunctor::plus_assign<typename E1::value_type, typename E2::value_type> > type;
};

template <typename E1, typename E2>
struct root< vector::vec_vec_minus_asgn_expr<E1, E2> >
{
    typedef vector::vec_vec_aop_expr< E1, E2, mtl::sfunctor::minus_assign<typename E1::value_type, typename E2::value_type> > type;
};

template <typename E1, typename E2>
struct root< vector::vec_scal_asgn_expr<E1, E2> >
{
    typedef vector::vec_scal_aop_expr< E1, E2, mtl::sfunctor::assign<typename E1::value_type, E2> > type;
};

template <typename E1, typename E2>
struct root< vector::vec_scal_times_asgn_expr<E1, E2> >
{
    typedef vector::vec_scal_aop_expr< E1, E2, mtl::sfunctor::times_assign<typename E1::value_type, E2> > type;
};

template <typename E1, typename E2>
struct root< vector::vec_scal_div_asgn_expr<E1, E2> >
{
    typedef vector::vec_scal_aop_expr< E1, E2, mtl::sfunctor::divide_assign<typename E1::value_type, E2> > type;
};

template <typename Scaling, typename Vector>
struct root< vector::scaled_view<Scaling, Vector> >
{
    typedef vector::map_view<tfunctor::scale<Scaling, typename Vector::value_type>, Vector> type;
};

template <typename Vector, typename RScaling>
struct root< vector::rscaled_view<Vector, RScaling> >
{
    typedef vector::map_view<tfunctor::rscale<typename Vector::value_type, RScaling>, Vector> type;
};

template <typename Vector, typename Divisor>
struct root< vector::divide_by_view<Vector, Divisor> >
{
    typedef vector::map_view<tfunctor::divide_by<typename Vector::value_type, Divisor>, Vector> type;
};

template <typename Vector>
struct root< vector::conj_view<Vector> >
{
    typedef vector::map_view<mtl::sfunctor::conj<typename Vector::value_type>, Vector> type;
};

template <typename Vector>
struct root< vector::negate_view<Vector> >
{
    typedef vector::map_view<mtl::sfunctor::negate<typename Vector::value_type>, Vector> type;
};

template <unsigned BSize, typename Vector>
struct root< vector::unrolled1<BSize, Vector> >
{
    typedef Vector type;
};

#if 0 // template
struct root
{
    typedef  type;
};
#endif

}} // namespace mtl::traits

#endif // MTL_TRAITS_ROOT_INCLUDE


#pragma once

// Include GLM
#include <glm/glm.hpp>

// Include STL
#include <vector>
#include <random>
#include <utility>
#include <iostream>

// Eigen CORE
#include <Eigen/Core>

// Local include
#include "SH.hpp"

/* _Is `a` close to `b` ?_
 *
 * This template function check if a-b is smaller than a fraction of the max
 * between a and b. By default, it checks if it is smaller than 1 percent of
 * the maximum value.
 */
template<typename T>
inline bool closeTo(const T& a, const T&b, const T& Percentage = T(0.01)) {
   if(a == T(0.0) || b == T(0.0)) {
      return std::abs<T>(a-b) < Percentage;
   } else {
      const T c = std::max<T>(std::max<T>(a, b), Percentage);
      return (std::abs<T>(a-b) < Percentage * c);
   }
}

/* _Is `a` inside the confidence interval `[m-s, m+s]?
 *
 * `b` is supposed to be a confidence interval in the form of µ±ε where µ is
 * `b.first` and ε is `b.second`.
 */
template<typename T>
inline bool closeTo(const T& a, const std::pair<T,T>& b) {
   assert(b.second >= T(0));
   return (a < b.first + b.second) && (a > b.first - b.second);
}

struct Vector : public glm::vec3 {

   Vector() : glm::vec3() {}
   Vector(float x, float y, float z) : glm::vec3(x, y, z) {}
   Vector(const glm::vec3& w) : glm::vec3(w) {}

   static inline float Dot(const glm::vec3& a, const glm::vec3& b) {
      return glm::dot<float>(a, b);
   }

   static inline glm::vec3 Cross(const glm::vec3& a, const glm::vec3& b) {
      return glm::cross(a, b);
   }

   static inline glm::vec3 Normalize(const glm::vec3& a) {
      return glm::normalize(a);
   }

   static inline float Length(const glm::vec3& a) {
      return glm::length(a);
   }
};

std::ostream& operator<< (std::ostream& out, const glm::vec3& a) {
   out << "[" << a.x << ", " << a.y << ", " << a.z << "]";
   return out;
}

struct Edge {
   Edge(const Vector& a, const Vector& b) : A(a), B(b) {}
   Vector A, B;
};

/* 'The Triangle' structure represent a spherical triangle of three coordinates
 * A, B and C by storing its Edges in a vcetor.
 *
 * TODO: Extend to the polygon structure
 */
struct Triangle : public std::vector<Edge> {
   Triangle() {
   }
   Triangle(const Vector& A, const Vector& B, const Vector& C) {
     this->push_back(Edge(A, B));
     this->push_back(Edge(B, C));
     this->push_back(Edge(C, A));
   }
};

struct Quad: public std::vector<Edge> {
   Quad() {
   }
   Quad(const Vector& A, const Vector& B,
        const Vector& C, const Vector& D) {
     this->push_back(Edge(A, B));
     this->push_back(Edge(B, C));
     this->push_back(Edge(C, D));
     this->push_back(Edge(D, A));
   }
};

struct Polygon : public std::vector<Edge> {

   // Constructor
   Polygon() {
   }
   Polygon(const Vector& A, const Vector& B, const Vector& C) {
      this->push_back(Edge(A, B));
      this->push_back(Edge(B, C));
      this->push_back(Edge(C, A));
   }
};

std::ostream& operator<<(std::ostream& out, const Polygon& polygon) {
   for(auto& edge : polygon) {
      out << " + " << edge.A << std::endl;
   }
   return out;
}

struct PolygonConstructor : public std::vector<Vector> {

   // Constructor
   PolygonConstructor() {
   }
   PolygonConstructor(const Vector& A, const Vector& B, const Vector& C) {
      this->push_back(A);
      this->push_back(B);
      this->push_back(C);
   }

   Polygon ProjectToHemisphere(const Vector& p) const {
      Polygon P;
#ifdef REMOVE
      std::cout << "A = " << P[0].A << std::endl;
      std::cout << "B = " << P[1].A << std::endl;
      std::cout << "C = " << P[2].A << std::endl;
#endif
      for(unsigned int k=0; k<this->size(); ++k) {
         const Vector& A = this->at(k);
         const Vector& B = (k == this->size()-1) ? this->at(0) : this->at(k+1);

         P.push_back(Edge(Vector::Normalize(A-p), Vector::Normalize(B-p)));
      }
      return P;
   }

   /* Clamp the Polygon with respect to the Shading normal.
    */
   Polygon ProjectToHemisphere(const Vector& p, const Vector& n) const {
      Polygon P;
#ifdef REMOVE
      std::cout << "A = " << P[0].A << std::endl;
      std::cout << "B = " << P[1].A << std::endl;
      std::cout << "C = " << P[2].A << std::endl;
#endif
      // Constant
      const unsigned int size = this->size();

      // Starting vector of the Edge. This vector can be clamped if necessary
      // to account for the shading horizon.
      unsigned int start = 0;
      Vector A, M;
      float dotAn;
      bool condition = true;
      do {
         // Get the current element
         A = Vector::Normalize(this->at(start) - p);

         // Initial condition: the vertex needs to be above the horizon
         dotAn = Vector::Dot(A, n);
         condition = dotAn < 0.0;
         ++start;

      } while(condition && start<size);
      --start;

      // Return the empty polygon in case every vertex is below the horizon
      if(start == size) { return P; }

      for(unsigned int k=1; k<=size; ++k) {
         const unsigned int next = (start + k) % size;
         const Vector B = Vector::Normalize(this->at(next) - p);

         const float dotBn = Vector::Dot(B, n);

         // First case: the beginning of the Edge was below the hemisphere.
         // Then we must create the intermediate point N and create an egde
         // using M and N and another with N and B..
         if(dotAn < 0 && dotBn >= 0) {
            const float alpha = dotAn / (dotAn - dotBn);
            const Vector N  = Vector::Normalize(A + alpha*(B-A));

            if(Vector::Dot(M, N) < 1.0f) {
               P.push_back(Edge(M, N));
            }
            if(alpha > 0 && Vector::Dot(N, B) < 1.0f) {
               P.push_back(Edge(N, B));
            }

         } else if(dotAn >= 0 && dotBn < 0) {
            const float alpha = dotAn / (dotAn - dotBn);
            M = Vector::Normalize(A + alpha*(B-A));
            if(alpha > 0) {
               P.push_back(Edge(A, M));
            }

         // The next point is a valid one (above the horizon). Add the Edge
         // (A,B)
         } else if(dotAn >= 0 && dotBn >= 0) {
            if(Vector::Dot(A, B) < 1.0f) {
               P.push_back(Edge(A, B));
            }
         }

         // Update the loop variables.
         A = B;
         dotAn = dotBn;
      }
      return P;
   }
};

std::mt19937 _test_gen(0);
std::uniform_real_distribution<float> _test_dist(0.0,1.0);

/* 'Sample' generate a random direction on the unit sphere with uniform
 * distribution using _test_gen and _test_dist random number generators..
 */
glm::vec3 Sample() {

   glm::vec3 out;

   // Sample the cosine of the elevation
   const double z = _test_dist(_test_gen);
   out.z = 2.0*z - 1.0;
   const double z2 = out.z*out.z;

   // Sample the azimuth
   const double phi = 2.0*M_PI*_test_dist(_test_gen);
   out.x = sqrt(1.0-z2) * cos(phi);
   out.y = sqrt(1.0-z2) * sin(phi);
   return out;
}

// Sample a spherical triangle using Arvo's stratified method.
// Note: This code is not reliable right now. An error in the computation of the
// solid angle bias the distribution of points. Use the uniform sampling method
// instead.
glm::vec3 SampleSphericalTriangle(const Triangle& triangle, float& pdf) {
   const glm::vec3& A = triangle[0].A;
   const glm::vec3& B = triangle[1].A;
   const glm::vec3& C = triangle[2].A;

   const glm::vec3 ab = glm::normalize(glm::cross(A, B));
   const glm::vec3 ac = glm::normalize(glm::cross(A, C));
   const glm::vec3 ba = glm::normalize(glm::cross(B, A));
   const glm::vec3 bc = glm::normalize(glm::cross(B, C));
   const glm::vec3 cb = glm::normalize(glm::cross(C, B));

   const float alpha = acos(glm::dot(ba, ac));
   const float beta  = acos(glm::dot(cb, ab));
   const float gamma = acos(glm::dot(ac, bc));

   const float area  = alpha + beta + gamma - M_PI;
   pdf = 1.0f / area;

   const float phi = _test_dist(_test_gen)*area - alpha;
   const float t   = cos(phi);
   const float s   = sin(phi);
   const float u   = t - cos(alpha);
   const float v   = s + sin(alpha)*glm::dot(A, B);

   const float q = (v*t - u*s)*cos(alpha) - v / ((v*s + u*t)*sin(alpha));

   glm::vec3 hC = q*A + float(sqrt(1.0f-q*q))*glm::normalize(C-glm::dot(C, A)*A);

   // Select the cos(theta)
   const float z = 1.0f - _test_dist(_test_gen)*(1.0f - glm::dot(hC, B));

   return z*B + float(sqrt(1.0f-z*z))*glm::normalize(hC - glm::dot(hC, B)*B);
}

bool HitTriangle(const Triangle& triangle, const Vector& w) {

   const float Epsilon = 1.0E-6;

   auto& p1 = triangle[0].A;
   auto& p2 = triangle[0].B;
   auto& p3 = triangle[1].B;

   //Find vectors for two edges sharing vertex/point p1
   auto e1 = p2 - p1;
   auto e2 = p3 - p1;

   // calculating determinant
   auto p   = Vector::Cross(w, e2);
   auto det = Vector::Dot(e1, p);

   //if determinant is near zero, ray lies in plane of triangle otherwise not
   if (det > -Epsilon && det < Epsilon) { return false; }
   auto invDet = 1.0f / det;

   //calculate distance from p1 to ray origin
   auto t = - p1;

   //Calculate u parameter
   auto u = Vector::Dot(t, p) * invDet;

   //Check for ray hit
   if (u < 0 || u > 1) { return false; }

   //Prepare to test v parameter
   auto q = glm::cross(t, e1);

   //Calculate v parameter
   auto v = Vector::Dot(w, q) * invDet;

   //Check for ray hit
   if (v < 0 || u + v > 1) { return false; }

   if ((Vector::Dot(e2, q) * invDet) > Epsilon) {
       //ray does intersect
       return true;
   }

   // No hit at all
   return false;
}

/* Spherical Harmonics wrapper for the code in 'SphericalHarmonics.hpp'
 */
struct SH {

   // Inline for FastBasis
   static inline Eigen::VectorXf FastBasis(const Vector& w, int lmax) {
      const auto size = Terms(lmax);
      Eigen::VectorXf res(size);
      SHEvalFast<Vector>(w, lmax, res);
      return res;
   }
   static inline void FastBasis(const Vector& w, int lmax, Eigen::VectorXf& clm) {
      assert(clm.size() == Terms(lmax));
      SHEvalFast<Vector>(w, lmax, clm);
   }

   // Inline for Terms
   static inline int Terms(int band) {
      return SHTerms(band);
   }

   // Inline for Index
   static inline int Index(int l, int m) {
      return SHIndex(l, m);
   }
};


/**
 * Copyright (C) Omar Thor <omarthoro@gmail.com> - All Rights Reserved
 * Unauthorized copying of this file, via any medium is strictly prohibited
 * Proprietary and confidential
 *
 * Written by Omar Thor <omarthoro@gmail.com>, 2017
 */

#ifndef SP_ALGO_NN_OPTIMIZER_GRAD_DESC_HPP
#define SP_ALGO_NN_OPTIMIZER_GRAD_DESC_HPP

#include "optimizer.hpp"

#include <boost/assert.hpp>

SP_ALGO_NN_NAMESPACE_BEGIN

/**
 * \brief Implementation of gradient descent optimizer
 */

/**
 * \brief Gradient Descent Optimizer
 */
template<typename LearningRate = default_learning_rate>
struct gradient_descent_optimizer : optimizer<gradient_descent_optimizer<LearningRate>> {

    constexpr static float_t alpha = static_cast<float_t>(LearningRate::num) / static_cast<float_t>(LearningRate::den);

    static_assert(alpha > 0 && alpha < 1.0, "Alpha is in the range of (0, 1]");

    constexpr static float_t epsilon = 1.0e-8f;

    template<typename Tensor>
    void update_impl(Tensor& dw, Tensor& w) {
        BOOST_ASSERT(dw.size() == w.size());
        BOOST_ASSERT(dw.dimensions() == w.dimensions());
        w -= (alpha * dw);
    }

};

SP_ALGO_NN_NAMESPACE_END

#endif	/* SP_ALGO_NN_OPTIMIZER_GRAD_DESC_HPP */


// Software License for MTL
//
// Copyright (c) 2007 The Trustees of Indiana University.
//               2008 Dresden University of Technology and the Trustees of Indiana University.
//               2010 SimuNova UG (haftungsbeschränkt), www.simunova.com.
// All rights reserved.
// Authors: Peter Gottschling and Andrew Lumsdaine
//
// This file is part of the Matrix Template Library
//
// See also license.mtl.txt in the distribution.

#ifndef MTL_MATRIX_IMPLICIT_DENSE_INCLUDE
#define MTL_MATRIX_IMPLICIT_DENSE_INCLUDE

#include <vector>
#include <boost/numeric/linear_algebra/inverse.hpp>
#include <boost/numeric/mtl/mtl_fwd.hpp>
#include <boost/numeric/mtl/matrix/crtp_base_matrix.hpp>
#include <boost/numeric/mtl/matrix/mat_expr.hpp>
#include <boost/numeric/mtl/concept/std_concept.hpp>
#include <boost/numeric/mtl/concept/collection.hpp>

#ifdef MTL_HAS_MPI
#   include <boost/numeric/mtl/matrix/distributed.hpp>
#   include <boost/numeric/mtl/matrix/inserter.hpp>
#   include <boost/mpi/collectives.hpp>
#endif

namespace mtl { namespace mat {

template <typename Functor>
class implicit_dense
  : public const_crtp_base_matrix< implicit_dense<Functor>,
				   typename Functor::result_type, typename Functor::size_type >,
    public mat_expr< implicit_dense<Functor> >
{
    typedef implicit_dense                             self;
  public:
    typedef mtl::tag::row_major                        orientation; // for completeness
    typedef typename Functor::result_type              value_type;
    typedef typename Functor::result_type              const_reference;
    typedef typename Functor::size_type                size_type;

    // Should not be needed, to be removed after transposed_view is cleaned up
    typedef index::c_index                             index_type;
    typedef mtl::traits::detail::matrix_element_key<self> key_type;
    typedef mtl::non_fixed::dimensions                 dim_type;

    explicit implicit_dense (const Functor& functor) : my_functor(functor) {}

    value_type operator() (size_type r, size_type c) const { return my_functor(r, c); }

    size_type nnz() const { return dim1() * dim2(); }
    size_type dim1() const { return num_rows(my_functor); }
    size_type dim2() const { return num_cols(my_functor); }

    friend size_type inline num_rows(const self& A) { return num_rows(A.my_functor); }
    friend size_type inline num_cols(const self& A) { return num_cols(A.my_functor); }

    Functor& functor() { return my_functor; }
    Functor const& functor() const { return my_functor; }

  private:
    Functor           my_functor;
};

template <typename Functor>
typename Functor::size_type inline size(const implicit_dense<Functor>& A)
{
    return num_rows(A) * num_cols(A);
}

// ==========
// Sub matrix
// ==========

// To do later

}} // namespace mtl::matrix

namespace mtl { namespace traits {

    // ================
    // Range generators
    // For cursors
    // ================

    template <typename Functor>
    struct range_generator<glas::tag::row, mtl::mat::implicit_dense<Functor> >
      : detail::all_rows_range_generator<mtl::mat::implicit_dense<Functor>, complexity_classes::linear>
    {};

    template <typename Functor>
    struct range_generator<glas::tag::major, mtl::mat::implicit_dense<Functor> >
      : range_generator<glas::tag::row, mtl::mat::implicit_dense<Functor> >
    {};

    template <typename Functor>
    struct range_generator<glas::tag::nz,
			   detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::row, 2> >
      : detail::all_cols_in_row_range_generator<detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::row, 2> >
    {};

    template <typename Functor>
    struct range_generator<glas::tag::col, mtl::mat::implicit_dense<Functor> >
      : detail::all_cols_range_generator<mtl::mat::implicit_dense<Functor>, complexity_classes::linear>
    {};

    template <typename Functor>
    struct range_generator<glas::tag::nz,
			   detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::col, 2> >
      : detail::all_rows_in_col_range_generator<detail::sub_matrix_cursor<mtl::mat::implicit_dense<Functor>, glas::tag::col, 2> >
    {};

    template <typename Tag, typename Value>
    struct range_generator<Tag, mtl::mat::ones_matrix<Value> >
      : public range_generator<Tag, mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > >
    {};

    template <typename Value>
    struct range_generator<glas::tag::major, mtl::mat::ones_matrix<Value> >
      : public range_generator<glas::tag::major, mtl::mat::implicit_dense<mtl::mat::ones_functor<Value> > >
    {};

    template <typename Tag, typename Value>
    struct range_generator<Tag, mtl::mat::hilbert_matrix<Value> >
      : public range_generator<Tag, mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > >
    {};

    template <typename Value>
    struct range_generator<glas::tag::major, mtl::mat::hilbert_matrix<Value> >
      : public range_generator<glas::tag::major, mtl::mat::implicit_dense<mtl::mat::hilbert_functor<Value> > >
    {};

    template <typename Tag, typename Vector1, typename Vector2>
    struct range_generator<Tag, mtl::mat::outer_product_matrix<Vector1, Vector2> >
      : public range_generator<Tag, mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > >
    {};

    template <typename Vector1, typename Vector2>
    struct range_generator<glas::tag::major, mtl::mat::outer_product_matrix<Vector1, Vector2> >
      : public range_generator<glas::tag::major, mtl::mat::implicit_dense<mtl::mat::outer_product_functor<Vector1, Vector2> > >
    {};

}} // mtl::traits

// =============
// Some functors
// =============

namespace mtl { namespace mat {

template <typename Value= int>
class ones_functor
{
    typedef ones_functor    self;
  public:
    typedef std::size_t    size_type;
    typedef Value          result_type;

    ones_functor(size_type nr, size_type nc) : nr(nr), nc(nc) {}

    friend size_type inline num_rows(const self& A) { return A.nr; }
    friend size_type inline num_cols(const self& A) { return A.nc; }

    result_type operator()(size_type, size_type) const { return Value(1); }

  private:
    size_type nr, nc;
};

template <typename Value= double>
class hilbert_functor
{
    typedef hilbert_functor    self;
  public:
    typedef std::size_t    size_type;
    typedef Value          result_type;

    hilbert_functor(size_type nr, size_type nc) : nr(nr), nc(nc) {}

    friend size_type inline num_rows(const self& A) { return A.nr; }
    friend size_type inline num_cols(const self& A) { return A.nc; }

    result_type operator()(size_type r, size_type c) const
    {
	using math::reciprocal;
	return reciprocal(Value(r + c + 1));
    }
  private:
    size_type nr, nc;
};

template <typename Vector1, typename Vector2>
class outer_product_functor
{
    typedef outer_product_functor    self;
  public:
    typedef std::size_t              size_type;
    typedef typename Multiplicable<typename Collection<Vector1>::value_type,
				   typename Collection<Vector2>::value_type>::result_type   result_type;

    outer_product_functor(const Vector1& v1, const Vector2& v2) : my_v1(v1), my_v2(v2) {}
    outer_product_functor(size_type r, size_type c) : my_v1(r), my_v2(c) {}

    friend size_type inline num_rows(const self& A) { return mtl::size(A.my_v1); }
    friend size_type inline num_cols(const self& A) { return mtl::size(A.my_v2); }

    result_type operator()(size_type r, size_type c) const { return my_v1[r] * my_v2[c]; }

    Vector1&       v1()       { return my_v1; }
    Vector1 const& v1() const { return my_v1; }
    Vector2&       v2()       { return my_v2; }
    Vector2 const& v2() const { return my_v2; }

  private:
    Vector1  my_v1; // keeps copy
    Vector2  my_v2;
};

// ======================
// Some implicit matrices
// ======================

template <typename Value= int>
class ones_matrix
  : public implicit_dense<ones_functor<Value> >
{
  public:
    typedef ones_functor<Value>                functor_type;
    typedef typename functor_type::size_type  size_type;
    typedef implicit_dense<functor_type>      base;

    ones_matrix(size_type r, size_type c) : base(functor_type(r, c)) {}
};

template <typename Value= double>
class hilbert_matrix
  : public implicit_dense<hilbert_functor<Value> >
{
  public:
    typedef hilbert_functor<Value>            functor_type;
    typedef typename functor_type::size_type  size_type;
    typedef implicit_dense<functor_type>      base;

    hilbert_matrix(size_type r, size_type c) : base(functor_type(r, c)) {}
};

template <typename Vector1, typename Vector2>
class outer_product_matrix
  : public implicit_dense<outer_product_functor<Vector1, Vector2> >
{
    typedef outer_product_matrix self;
  public:
    typedef outer_product_functor<Vector1, Vector2>  functor_type;
    typedef typename functor_type::size_type  size_type;
    typedef implicit_dense<functor_type>      base;

    outer_product_matrix(const Vector1& v1, const Vector2& v2) : base(functor_type(v1, v2)) {}
    outer_product_matrix(size_type r, size_type c) : base(functor_type(r, c)) {}

    Vector1&       v1()       { return this->functor().v1(); }
    Vector1 const& v1() const { return this->functor().v1(); }
    Vector2&       v2()       { return this->functor().v2(); }
    Vector2 const& v2() const { return this->functor().v2(); }
};

}} // namespace mtl::matrix

#endif // MTL_MATRIX_IMPLICIT_DENSE_INCLUDE


// This file is part of the dune-hdd project:
//   http://users.dune-project.org/projects/dune-hdd
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH
#define DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH

#include <memory>

#include <boost/numeric/conversion/cast.hpp>

#include <dune/common/static_assert.hh>
#include <dune/common/timer.hh>

#include <dune/grid/multiscale/provider/cube.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/functions/constant.hh>
#include <dune/stuff/functions/expression.hh>
#include <dune/stuff/playground/functions/indicator.hh>
#include <dune/stuff/grid/provider/cube.hh>
#include <dune/stuff/grid/boundaryinfo.hh>

#include <dune/pymor/functions/default.hh>
#include <dune/pymor/functions/checkerboard.hh>

#include "default.hh"

namespace Dune {
namespace HDD {
namespace LinearElliptic {
namespace Problems {

template< class E, class D, int d, class R, int r = 1 >
class Thermalblock
  : public ProblemInterface< E, D, d, R, r >
{
  Thermalblock() { static_assert(AlwaysFalse< E >::value, "Not available for these dimensions!"); }
};

template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >
class Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
  : public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
  typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;
  typedef Thermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;

public:
  typedef Pymor::Functions::Checkerboard< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
      CheckerboardFunctionType;
  using typename BaseType::DiffusionTensorType;
  using typename BaseType::FunctionType;

  static const bool available = true;

  static std::string static_id()
  {
    return BaseType::BaseType::static_id() + ".thermalblock";
  }

  static Stuff::Common::Configuration default_config(const std::string sub_name = "")
  {
    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
        ConstantFunctionType;
    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >
        ConstantMatrixFunctionType;
    Stuff::Common::Configuration config;
    Stuff::Common::Configuration checkerboard_config = CheckerboardFunctionType::default_config();
    checkerboard_config["name"] = "diffusion_factor";
    checkerboard_config["type"] = CheckerboardFunctionType::static_id();
    checkerboard_config["num_elements"] = "[4 4 4]";
    checkerboard_config["parameter_name"] = "diffusion_factor";
    config.add(checkerboard_config, "diffusion_factor");
    Stuff::Common::Configuration diffusion_tensor_config = ConstantMatrixFunctionType::default_config();
    diffusion_tensor_config["name"] = "diffusion_tensor";
    diffusion_tensor_config["type"] = ConstantMatrixFunctionType::static_id();
    config.add(diffusion_tensor_config, "diffusion_tensor");
    Stuff::Common::Configuration constant_config = ConstantFunctionType::default_config();
    constant_config["type"] = ConstantFunctionType::static_id();
    constant_config["name"] = "force";
    constant_config["value"] = "1";
    config.add(constant_config, "force");
    constant_config["name"] = "dirichlet";
    constant_config["value"] = "0";
    config.add(constant_config, "dirichlet");
    constant_config["name"] = "neumann";
    config.add(constant_config, "neumann");
    if (sub_name.empty())
      return config;
    else {
      Stuff::Common::Configuration tmp;
      tmp.add(config, sub_name);
      return tmp;
    }
  } // ... default_config(...)

  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),
                                            const std::string sub_name = static_id())
  {
    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
    std::shared_ptr< CheckerboardFunctionType >
        checkerboard_function(CheckerboardFunctionType::create(cfg.sub("diffusion_factor")));
    return Stuff::Common::make_unique< ThisType >(checkerboard_function,
                                                  BaseType::create_matrix_function("diffusion_tensor", cfg),
                                                  BaseType::create_vector_function("force", cfg),
                                                  BaseType::create_vector_function("dirichlet", cfg),
                                                  BaseType::create_vector_function("neumann", cfg));
  } // ... create(...)

  Thermalblock(const std::shared_ptr< const CheckerboardFunctionType >& checkerboard_function,
               const std::shared_ptr< const DiffusionTensorType >& diffusion_tensor,
               const std::shared_ptr< const FunctionType >& force,
               const std::shared_ptr< const FunctionType >& dirichlet,
               const std::shared_ptr< const FunctionType >& neumann)
    : BaseType(checkerboard_function, diffusion_tensor, force, dirichlet, neumann)
  {}

  virtual std::string type() const override
  {
    return BaseType::BaseType::static_id() + ".thermalblock";
  }
}; // class Thermalblock< ..., 1 >

template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim = 1 >
class LocalThermalblock
{
  static_assert(AlwaysFalse< EntityImp >::value, "Not available for dimRange > 1!");
};

template< class EntityImp, class DomainFieldImp, int domainDim, class RangeFieldImp >
class LocalThermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
  : public Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
{
  typedef Default< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > BaseType;
  typedef LocalThermalblock< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > ThisType;

  typedef Pymor::Functions::AffinelyDecomposableDefault< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
      AffinelyDecomposableDefaultFunctionType;
  typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim >
      ConstantMatrixFunctionType;
public:
  using typename BaseType::FunctionType;

  static std::string static_id()
  {
    return BaseType::BaseType::static_id() + ".localthermalblock";
  }

  static Stuff::Common::Configuration default_config(const std::string sub_name = "")
  {
    typedef Stuff::Functions::Constant< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 >
        ConstantFunctionType;
    Stuff::Common::Configuration config;
    Stuff::Common::Configuration constant_config = ConstantFunctionType::default_config();
    constant_config["type"] = ConstantFunctionType::static_id();
    constant_config["name"] = "force";
    constant_config["value"] = "1";
    config.add(constant_config, "force");
    constant_config["name"] = "dirichlet";
    constant_config["value"] = "0";
    config.add(constant_config, "dirichlet");
    constant_config["name"] = "neumann";
    config.add(constant_config, "neumann");
    if (sub_name.empty())
      return config;
    else {
      Stuff::Common::Configuration tmp;
      tmp.add(config, sub_name);
      return tmp;
    }
  } // ... default_config(...)

  static std::unique_ptr< ThisType > create(const Stuff::Common::Configuration config = default_config(),
                                            const std::string sub_name = static_id())
  {
    const Stuff::Common::Configuration cfg = config.has_sub(sub_name) ? config.sub(sub_name) : config;
    return Stuff::Common::make_unique< ThisType >(BaseType::create_vector_function("force", cfg),
                                                  BaseType::create_vector_function("dirichlet", cfg),
                                                  BaseType::create_vector_function("neumann", cfg));
  } // ... create(...)

  LocalThermalblock(const std::shared_ptr< const FunctionType >& force,
                    const std::shared_ptr< const FunctionType >& dirichlet,
                    const std::shared_ptr< const FunctionType >& neumann)
    : BaseType(create_diffusion_factor(),
               create_diffusion_tensor(),
               force,
               dirichlet,
               neumann)
  {}

  virtual std::string type() const override
  {
    return BaseType::BaseType::static_id() + ".localthermalblock";
  }

private:
  static std::shared_ptr< AffinelyDecomposableDefaultFunctionType > create_diffusion_factor()
  {
    typedef Stuff::Functions::Indicator< EntityImp, DomainFieldImp, domainDim, RangeFieldImp, 1 > IndicatorFunctionType;
    const Pymor::ParameterType mu("diffusion_factor", 3);

    auto ret = std::make_shared< AffinelyDecomposableDefaultFunctionType >("diffusion_factor");
    ret->register_component(new IndicatorFunctionType({{{{0.0, 0.0}, {0.5, 0.16}}, 1.0},
                                                       {{{0.0, 0.16}, {0.16, 0.33}}, 1.0},
                                                       {{{0.33, 0.16}, {0.5, 0.33}}, 1.0},
                                                       {{{0.0, 0.33}, {0.5, 1.0}}, 1.0}},
                                                      "left_block"),
                            new Pymor::ParameterFunctional(mu, "diffusion_factor[0]"));
    ret->register_component(new IndicatorFunctionType({{{{0.5, 0.0}, {1.0, 1.0}}, 1.0}},
                                                      "right_block"),
                            new Pymor::ParameterFunctional(mu, "diffusion_factor[1]"));
    ret->register_component(new IndicatorFunctionType({{{{0.16, 0.16}, {0.33, 0.33}}, 1.0}},
                                                      "small_block"),
                            new Pymor::ParameterFunctional(mu, "diffusion_factor[2]"));
    return ret;
  } // ... create_diffusion_factor()

  typedef Pymor::Functions::NonparametricDefault
      < EntityImp, DomainFieldImp, domainDim, RangeFieldImp, domainDim, domainDim > NonparametricFunctionType;

  static std::shared_ptr< NonparametricFunctionType > create_diffusion_tensor()
  {
    Stuff::Common::Configuration diffusion_tensor_config = ConstantMatrixFunctionType::default_config();
    diffusion_tensor_config["name"] = "diffusion_tensor";
    return std::make_shared< NonparametricFunctionType >(ConstantMatrixFunctionType::create(diffusion_tensor_config));
  } // ... create_diffusion_tensor()
}; // class LocalThermalblock< ..., 1 >

} // namespace Problems
namespace DiscreteProblems {

template< class GridImp >
class Thermalblock
{
public:
  typedef GridImp GridType;
  typedef Stuff::Grid::Providers::Cube< GridType > GridProviderType;
private:
  typedef Stuff::Grid::BoundaryInfos::AllDirichlet< typename GridType::LeafIntersection > BoundaryInfoType;
  typedef typename GridType::template Codim< 0 >::Entity EntityType;
  typedef typename GridType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridType::dimension;
public:
  typedef double RangeFieldType;
  static const unsigned int dimRange = 1;
  typedef Problems::Thermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;

  static void write_config(const std::string filename, const std::string id)
  {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "filename = " << id << std::endl;
    file << "[logging]" << std::endl;
    file << "info  = true" << std::endl;
    file << "debug = true" << std::endl;
    file << "file  = false" << std::endl;
    file << "[parameter]" << std::endl;
    file << "0.diffusion_factor = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]" << std::endl;
    file << GridProviderType::default_config(GridProviderType::static_id());
    file << ProblemType::default_config(ProblemType::static_id());
    file << "[pymor]" << std::endl;
    file << "training_set = random" << std::endl;
    file << "num_training_samples = 100" << std::endl;
    file << "reductor = generic" << std::endl;
    file << "extension_algorithm = gram_schmidt" << std::endl;
    file << "extension_algorithm_product = h1_semi" << std::endl;
    file << "greedy_error_norm = h1_semi" << std::endl;
    file << "use_estimator = False" << std::endl;
    file << "max_rb_size = 100" << std::endl;
    file << "target_error = 0.01" << std::endl;
    file << "final_compression = False" << std::endl;
    file << "compression_product = None" << std::endl;
    file << "test_set = training" << std::endl;
    file << "num_test_samples = 100" << std::endl;
    file << "test_error_norm = h1_semi" << std::endl;
    file.close();
  } // ... write_config(...)

  Thermalblock(const std::string id, const std::vector< std::string >& arguments, const bool visualize = true)
  {
    // mpi
    int argc = boost::numeric_cast< int >(arguments.size());
    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
    Fem::MPIManager::initialize(argc, argv);
#else
    MPIHelper::instance(argc, argv);
#endif

    // configuration
    config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg");
    if (!config_.has_sub(id))
      DUNE_THROW(Stuff::Exceptions::configuration_error,
                 "Missing sub '" << id << "' in the following Configuration:\n\n" << config_);
    filename_ = config_.get(id + ".filename", id);

    // logger
    const Stuff::Common::Configuration& logger_config = config_.sub("logging");
    int log_flags = Stuff::Common::LOG_CONSOLE;
    debug_logging_ = logger_config.get< bool >("debug", false);
    if (logger_config.get< bool >("info"))
      log_flags = log_flags | Stuff::Common::LOG_INFO;
    if (debug_logging_)
      log_flags = log_flags | Stuff::Common::LOG_DEBUG;
    if (logger_config.get< bool >("file", false))
      log_flags = log_flags | Stuff::Common::LOG_FILE;
    Stuff::Common::Logger().create(log_flags, id, "", "");
    auto& info  = Stuff::Common::Logger().info();

    Timer timer;
    info << "creating grid with '" << GridProviderType::static_id() << "'... " << std::flush;
    grid_provider_ = GridProviderType::create(config_);
    const auto grid_view = grid_provider_->leaf_view();
    info << " done (took " << timer.elapsed()
         << "s, has " << grid_view->indexSet().size(0) << " element";
    if (grid_view->indexSet().size(0) > 1)
      info << "s";
    info << ")" << std::endl;

    boundary_info_ = Stuff::Common::Configuration("type", BoundaryInfoType::static_id());

    info << "setting up ";
    info << "'" << ProblemType::static_id() << "'... " << std::flush;
    timer.reset();
    problem_ = ProblemType::create(config_);
    info << "done (took " << timer.elapsed() << "s)" << std::endl;

    if (visualize) {
      info << "visualizing grid and problem... " << std::flush;
      timer.reset();
      grid_provider_->visualize(boundary_info_, filename_ + ".grid");
      problem_->visualize(*grid_view, filename_ + ".problem");
      info << "done (took " << timer.elapsed() << "s)" << std::endl;
    } // if (visualize)
  } // Thermalblock

  std::string filename() const
  {
    return filename_;
  }

  const Stuff::Common::Configuration& config() const
  {
    return config_;
  }

  bool debug_logging() const
  {
    return debug_logging_;
  }

  GridProviderType& grid_provider()
  {
    return *grid_provider_;
  }

  const GridProviderType& grid_provider() const
  {
    return *grid_provider_;
  }

  const Stuff::Common::Configuration& boundary_info() const
  {
    return boundary_info_;
  }

  const ProblemType& problem() const
  {
    return *problem_;
  }

private:
  std::string filename_;
  Stuff::Common::Configuration config_;
  bool debug_logging_;
  std::unique_ptr< GridProviderType > grid_provider_;
  Stuff::Common::Configuration boundary_info_;
  std::unique_ptr< const ProblemType > problem_;
}; // class Thermalblock

template< class GridImp >
class ThermalblockMultiScale
{
public:
  typedef GridImp GridType;
  typedef grid::Multiscale::Providers::Cube< GridType > GridProviderType;
private:
  typedef typename GridType::template Codim< 0 >::Entity EntityType;
  typedef typename GridType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridType::dimension;
public:
  typedef double RangeFieldType;
  static const unsigned int dimRange = 1;
  typedef Problems::Thermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;

  static void write_config(const std::string filename, const std::string id)
  {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "filename = " << id << std::endl;
    file << "[logging]" << std::endl;
    file << "info  = true" << std::endl;
    file << "debug = false" << std::endl;
    file << "file  = false" << std::endl;
    file << "visualize = false" << std::endl;
    file << "[parameter]" << std::endl;
    file << "0.diffusion_factor = [1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1]" << std::endl;
    file << GridProviderType::default_config(GridProviderType::static_id());
    file << ProblemType::default_config(ProblemType::static_id());
    file << "[pymor]" << std::endl;
    file << "training_set = random" << std::endl;
    file << "num_training_samples = 100" << std::endl;
    file << "reductor = generic" << std::endl;
    file << "extension_algorithm = pod" << std::endl;
    file << "extension_algorithm_product = h1_semi" << std::endl;
    file << "greedy_error_norm = h1_semi" << std::endl;
    file << "use_estimator = False" << std::endl;
    file << "max_rb_size = 100" << std::endl;
    file << "target_error = 0.01" << std::endl;
    file << "final_compression = False" << std::endl;
    file << "compression_product = None" << std::endl;
    file << "test_set = training" << std::endl;
    file << "num_test_samples = 100" << std::endl;
    file << "test_error_norm = h1_semi" << std::endl;
    file.close();
  } // ... write_config(...)

  ThermalblockMultiScale(const std::string id, const std::vector< std::string >& arguments, const bool visualize = true)
  {
    // mpi
    int argc = boost::numeric_cast< int >(arguments.size());
    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
    Fem::MPIManager::initialize(argc, argv);
#else
    MPIHelper::instance(argc, argv);
#endif

    // configuration
    config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg");
    if (!config_.has_sub(id))
      DUNE_THROW(Stuff::Exceptions::configuration_error,
                 "Missing sub '" << id << "' in the following Configuration:\n\n" << config_);
    filename_ = config_.get(id + ".filename", id);

    // logger
    const Stuff::Common::Configuration& logger_config = config_.sub("logging");
    int log_flags = Stuff::Common::LOG_CONSOLE;
    debug_logging_ = logger_config.get< bool >("debug", false);
    if (logger_config.get< bool >("info"))
      log_flags = log_flags | Stuff::Common::LOG_INFO;
    if (debug_logging_)
      log_flags = log_flags | Stuff::Common::LOG_DEBUG;
    if (logger_config.get< bool >("file", false))
      log_flags = log_flags | Stuff::Common::LOG_FILE;
    Stuff::Common::Logger().create(log_flags, id, "", "");
    auto& info  = Stuff::Common::Logger().info();

    Timer timer;
    info << "creating grid with '" << GridProviderType::static_id() << "'... " << std::flush;
    grid_provider_ = GridProviderType::create(config_);
    const auto grid_view = grid_provider_->leaf_view();
    info << " done (took " << timer.elapsed()
         << "s, has " << grid_view.indexSet().size(0) << " element";
    if (grid_view.indexSet().size(0) > 1)
      info << "s";
    info << ")" << std::endl;

    boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::NormalBased::default_config();
    boundary_info_["dirichlet.0"] = "[0.0 -1.0]";
    boundary_info_["dirichlet.1"] = "[0.0 1.0]";
    boundary_info_["neumann.0"] = "[1.0 0.0]";
    boundary_info_["neumann.1"] = "[-1.0 0.0]";

    info << "setting up ";
    info << "'" << ProblemType::static_id() << "'... " << std::flush;
    timer.reset();
    problem_ = ProblemType::create(config_);
    info << "done (took " << timer.elapsed() << "s)" << std::endl;

    if (visualize && logger_config.get("visualize", false)) {
      info << "visualizing grid and problem... " << std::flush;
      timer.reset();
      grid_provider_->visualize(boundary_info_, filename_ + ".grid");
      grid_provider_->visualize(filename_ + ".msgrid");
      problem_->visualize(grid_view, filename_ + ".problem");
      info << "done (took " << timer.elapsed() << "s)" << std::endl;
    } // if (visualize)
  } // Thermalblock

  std::string filename() const
  {
    return filename_;
  }

  const Stuff::Common::Configuration& config() const
  {
    return config_;
  }

  bool debug_logging() const
  {
    return debug_logging_;
  }

  GridProviderType& grid_provider()
  {
    return *grid_provider_;
  }

  const GridProviderType& grid_provider() const
  {
    return *grid_provider_;
  }

  const Stuff::Common::Configuration& boundary_info() const
  {
    return boundary_info_;
  }

  const ProblemType& problem() const
  {
    return *problem_;
  }

private:
  std::string filename_;
  Stuff::Common::Configuration config_;
  bool debug_logging_;
  std::unique_ptr< GridProviderType > grid_provider_;
  Stuff::Common::Configuration boundary_info_;
  std::unique_ptr< const ProblemType > problem_;
}; // class ThermalblockMultiScale

template< class GridImp >
class LocalThermalblockMultiScale
{
public:
  typedef GridImp GridType;
  typedef grid::Multiscale::Providers::Cube< GridType > GridProviderType;
private:
  typedef typename GridType::template Codim< 0 >::Entity EntityType;
  typedef typename GridType::ctype DomainFieldType;
  static const unsigned int dimDomain = GridType::dimension;
public:
  typedef double RangeFieldType;
  static const unsigned int dimRange = 1;
  typedef Problems::LocalThermalblock< EntityType, DomainFieldType, dimDomain, RangeFieldType, dimRange > ProblemType;

  static void write_config(const std::string filename, const std::string id)
  {
    std::ofstream file;
    file.open(filename);
    file << "[" << id << "]" << std::endl;
    file << "filename = " << id << std::endl;
    file << "[logging]" << std::endl;
    file << "info  = true" << std::endl;
    file << "debug = false" << std::endl;
    file << "file  = false" << std::endl;
    file << "visualize = false" << std::endl;
    file << "[parameter]" << std::endl;
    file << "0.diffusion_factor = [1 2 3]" << std::endl;
    file << GridProviderType::default_config(GridProviderType::static_id());
    file << ProblemType::default_config(ProblemType::static_id());
    file << "[pymor]" << std::endl;
    file << "training_set = random" << std::endl;
    file << "num_training_samples = 100" << std::endl;
    file << "reductor = generic" << std::endl;
    file << "extension_algorithm = pod" << std::endl;
    file << "extension_algorithm_product = h1_semi" << std::endl;
    file << "greedy_error_norm = h1_semi" << std::endl;
    file << "use_estimator = False" << std::endl;
    file << "max_rb_size = 100" << std::endl;
    file << "target_error = 5e-3" << std::endl;
    file << "final_compression = False" << std::endl;
    file << "compression_product = None" << std::endl;
    file << "test_set = training" << std::endl;
    file << "num_test_samples = 100" << std::endl;
    file << "test_error_norm = h1_semi" << std::endl;
    file.close();
  } // ... write_config(...)

  LocalThermalblockMultiScale(const std::string id,
                              const std::vector< std::string >& arguments,
                              const bool visualize = true)
  {
    // mpi
    int argc = boost::numeric_cast< int >(arguments.size());
    char** argv = Stuff::Common::String::vectorToMainArgs(arguments);
#if HAVE_DUNE_FEM
    Fem::MPIManager::initialize(argc, argv);
#else
    MPIHelper::instance(argc, argv);
#endif

    // configuration
    config_ = Stuff::Common::Configuration(argc, argv, id + ".cfg");
    if (!config_.has_sub(id))
      DUNE_THROW(Stuff::Exceptions::configuration_error,
                 "Missing sub '" << id << "' in the following Configuration:\n\n" << config_);
    filename_ = config_.get(id + ".filename", id);

    // logger
    const Stuff::Common::Configuration& logger_config = config_.sub("logging");
    int log_flags = Stuff::Common::LOG_CONSOLE;
    debug_logging_ = logger_config.get< bool >("debug", false);
    if (logger_config.get< bool >("info"))
      log_flags = log_flags | Stuff::Common::LOG_INFO;
    if (debug_logging_)
      log_flags = log_flags | Stuff::Common::LOG_DEBUG;
    if (logger_config.get< bool >("file", false))
      log_flags = log_flags | Stuff::Common::LOG_FILE;
    Stuff::Common::Logger().create(log_flags, id, "", "");
    auto& info  = Stuff::Common::Logger().info();

    Timer timer;
    info << "creating grid with '" << GridProviderType::static_id() << "'... " << std::flush;
    grid_provider_ = GridProviderType::create(config_);
    const auto grid_view = grid_provider_->leaf_view();
    info << " done (took " << timer.elapsed()
         << "s, has " << grid_view->indexSet().size(0) << " element";
    if (grid_view->indexSet().size(0) > 1)
      info << "s";
    info << ")" << std::endl;

    boundary_info_ = Stuff::Grid::BoundaryInfoConfigs::NormalBased::default_config();
    boundary_info_["dirichlet.0"] = "[0.0 -1.0]";
    boundary_info_["dirichlet.1"] = "[0.0 1.0]";
    boundary_info_["neumann.0"] = "[1.0 0.0]";
    boundary_info_["neumann.1"] = "[-1.0 0.0]";

    info << "setting up ";
    info << "'" << ProblemType::static_id() << "'... " << std::flush;
    timer.reset();
    problem_ = ProblemType::create(config_);
    info << "done (took " << timer.elapsed() << "s)" << std::endl;

    if (visualize && logger_config.get("visualize", false)) {
      info << "visualizing grid and problem... " << std::flush;
      timer.reset();
      grid_provider_->visualize(boundary_info_, filename_ + ".grid");
      grid_provider_->visualize(filename_ + ".msgrid");
      problem_->visualize(*grid_view, filename_ + ".problem");
      info << "done (took " << timer.elapsed() << "s)" << std::endl;
    } // if (visualize)
  } // Thermalblock

  std::string filename() const
  {
    return filename_;
  }

  const Stuff::Common::Configuration& config() const
  {
    return config_;
  }

  bool debug_logging() const
  {
    return debug_logging_;
  }

  GridProviderType& grid_provider()
  {
    return *grid_provider_;
  }

  const GridProviderType& grid_provider() const
  {
    return *grid_provider_;
  }

  const Stuff::Common::Configuration& boundary_info() const
  {
    return boundary_info_;
  }

  const ProblemType& problem() const
  {
    return *problem_;
  }

private:
  std::string filename_;
  Stuff::Common::Configuration config_;
  bool debug_logging_;
  std::unique_ptr< GridProviderType > grid_provider_;
  Stuff::Common::Configuration boundary_info_;
  std::unique_ptr< const ProblemType > problem_;
}; // class LocalThermalblockMultiScale

} // namespace DiscreteProblems
} // namespace LinearElliptic
} // namespace HDD
} // namespace Dune

#endif // DUNE_HDD_LINEARELLIPTIC_PROBLEMS_THERMALBLOCK_HH


// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2016 Michael Rabinovich
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#include "slim.h"

#include "boundary_loop.h"
#include "cotmatrix.h"
#include "edge_lengths.h"
#include "grad.h"
#include "local_basis.h"
#include "repdiag.h"
#include "vector_area_matrix.h"
#include "arap.h"
#include "cat.h"
#include "doublearea.h"
#include "grad.h"
#include "local_basis.h"
#include "per_face_normals.h"
#include "slice_into.h"
#include "volume.h"
#include "polar_svd.h"
#include "flip_avoiding_line_search.h"
#include "mapping_energy_with_jacobians.h"

#include <iostream>
#include <map>
#include <set>
#include <vector>

#include <Eigen/IterativeLinearSolvers>
#include <Eigen/SparseCholesky>
#include <Eigen/IterativeLinearSolvers>

#include "Timer.h"
#include "sparse_cached.h"
#include "AtA_cached.h"

#ifdef CHOLMOD
#include <Eigen/CholmodSupport>
#endif

namespace igl
{
  namespace slim
  {
    // Definitions of internal functions
    IGL_INLINE void buildRhs(igl::SLIMData& s, const Eigen::SparseMatrix<double> &A);
    IGL_INLINE void add_soft_constraints(igl::SLIMData& s, Eigen::SparseMatrix<double> &L);
    IGL_INLINE double compute_energy(igl::SLIMData& s, Eigen::MatrixXd &V_new);
    IGL_INLINE double compute_soft_const_energy(igl::SLIMData& s,
                                                const Eigen::MatrixXd &V,
                                                const Eigen::MatrixXi &F,
                                                Eigen::MatrixXd &V_o);

    IGL_INLINE void solve_weighted_arap(igl::SLIMData& s,
                                        const Eigen::MatrixXd &V,
                                        const Eigen::MatrixXi &F,
                                        Eigen::MatrixXd &uv,
                                        Eigen::VectorXi &soft_b_p,
                                        Eigen::MatrixXd &soft_bc_p);
    IGL_INLINE void update_weights_and_closest_rotations( igl::SLIMData& s,
                                                          Eigen::MatrixXd &uv);
    IGL_INLINE void compute_jacobians(igl::SLIMData& s, const Eigen::MatrixXd &uv);
    IGL_INLINE void build_linear_system(igl::SLIMData& s, Eigen::SparseMatrix<double> &L);
    IGL_INLINE void pre_calc(igl::SLIMData& s);

    // Implementation

    IGL_INLINE void compute_jacobians(igl::SLIMData& s, const Eigen::MatrixXd &uv)
    {
      if (s.F.cols() == 3)
      {
        // Ji=[D1*u,D2*u,D1*v,D2*v];
        s.Ji.col(0) = s.Dx * uv.col(0);
        s.Ji.col(1) = s.Dy * uv.col(0);
        s.Ji.col(2) = s.Dx * uv.col(1);
        s.Ji.col(3) = s.Dy * uv.col(1);
      }
      else /*tet mesh*/{
        // Ji=[D1*u,D2*u,D3*u, D1*v,D2*v, D3*v, D1*w,D2*w,D3*w];
        s.Ji.col(0) = s.Dx * uv.col(0);
        s.Ji.col(1) = s.Dy * uv.col(0);
        s.Ji.col(2) = s.Dz * uv.col(0);
        s.Ji.col(3) = s.Dx * uv.col(1);
        s.Ji.col(4) = s.Dy * uv.col(1);
        s.Ji.col(5) = s.Dz * uv.col(1);
        s.Ji.col(6) = s.Dx * uv.col(2);
        s.Ji.col(7) = s.Dy * uv.col(2);
        s.Ji.col(8) = s.Dz * uv.col(2);
      }
    }

    IGL_INLINE void update_weights_and_closest_rotations(igl::SLIMData& s, Eigen::MatrixXd &uv)
    {
      compute_jacobians(s, uv);
      slim_update_weights_and_closest_rotations_with_jacobians(s.Ji, s.slim_energy, s.exp_factor, s.W, s.Ri);
    }

    IGL_INLINE void solve_weighted_arap(igl::SLIMData& s,
                                        const Eigen::MatrixXd &V,
                                        const Eigen::MatrixXi &F,
                                        Eigen::MatrixXd &uv,
                                        Eigen::VectorXi &soft_b_p,
                                        Eigen::MatrixXd &soft_bc_p)
    {
      using namespace Eigen;

      Eigen::SparseMatrix<double> L;
      build_linear_system(s,L);

      igl::Timer t;

      //t.start();
      // solve
      Eigen::VectorXd Uc;
#ifndef CHOLMOD
      if (s.dim == 2)
      {
        SimplicialLDLT<Eigen::SparseMatrix<double> > solver;
        Uc = solver.compute(L).solve(s.rhs);
      }
      else
      { // seems like CG performs much worse for 2D and way better for 3D
        Eigen::VectorXd guess(uv.rows() * s.dim);
        for (int i = 0; i < s.v_num; i++) for (int j = 0; j < s.dim; j++) guess(uv.rows() * j + i) = uv(i, j); // flatten vector
        ConjugateGradient<Eigen::SparseMatrix<double>, Lower | Upper> cg;
        cg.setTolerance(1e-8);
        cg.compute(L);
        Uc = cg.solveWithGuess(s.rhs, guess);
      }
#else
        CholmodSimplicialLDLT<Eigen::SparseMatrix<double> > solver;
        Uc = solver.compute(L).solve(s.rhs);
#endif
      for (int i = 0; i < s.dim; i++)
        uv.col(i) = Uc.block(i * s.v_n, 0, s.v_n, 1);

      // t.stop();
      // std::cerr << "solve: " << t.getElapsedTime() << std::endl;

    }

    IGL_INLINE void pre_calc(igl::SLIMData& s)
    {
      if (!s.has_pre_calc)
      {
        s.v_n = s.v_num;
        s.f_n = s.f_num;

        if (s.F.cols() == 3)
        {
          s.dim = 2;
          Eigen::MatrixXd F1, F2, F3;
          igl::local_basis(s.V, s.F, F1, F2, F3);
          Eigen::SparseMatrix<double> G;
          igl::grad(s.V, s.F, G);
          Eigen::SparseMatrix<double> Face_Proj;

          auto face_proj = [](Eigen::MatrixXd& F){
            std::vector<Eigen::Triplet<double> >IJV;
            int f_num = F.rows();
            for(int i=0; i<F.rows(); i++) {
              IJV.push_back(Eigen::Triplet<double>(i, i, F(i,0)));
              IJV.push_back(Eigen::Triplet<double>(i, i+f_num, F(i,1)));
              IJV.push_back(Eigen::Triplet<double>(i, i+2*f_num, F(i,2)));
            }
            Eigen::SparseMatrix<double> P(f_num, 3*f_num);
            P.setFromTriplets(IJV.begin(), IJV.end());
            return P;
          };

          s.Dx = face_proj(F1) * G;
          s.Dy = face_proj(F2) * G;
        }
        else
        {
          s.dim = 3;
          Eigen::SparseMatrix<double> G;
          igl::grad(s.V, s.F, G,
                    s.mesh_improvement_3d /*use normal gradient, or one from a "regular" tet*/);
          s.Dx = G.block(0, 0, s.F.rows(), s.V.rows());
          s.Dy = G.block(s.F.rows(), 0, s.F.rows(), s.V.rows());
          s.Dz = G.block(2 * s.F.rows(), 0, s.F.rows(), s.V.rows());
        }

        s.W.resize(s.f_n, s.dim * s.dim);
        s.Dx.makeCompressed();
        s.Dy.makeCompressed();
        s.Dz.makeCompressed();
        s.Ri.resize(s.f_n, s.dim * s.dim);
        s.Ji.resize(s.f_n, s.dim * s.dim);
        s.rhs.resize(s.dim * s.v_num);

        // flattened weight matrix
        s.WGL_M.resize(s.dim * s.dim * s.f_n);
        for (int i = 0; i < s.dim * s.dim; i++)
          for (int j = 0; j < s.f_n; j++)
            s.WGL_M(i * s.f_n + j) = s.M(j);

        s.first_solve = true;
        s.has_pre_calc = true;
      }
    }

    IGL_INLINE void build_linear_system(igl::SLIMData& s, Eigen::SparseMatrix<double> &L)
    {
      // formula (35) in paper
      std::vector<Eigen::Triplet<double> > IJV;

      #ifdef SLIM_CACHED
      slim_buildA(s.Dx, s.Dy, s.Dz, s.W, IJV);
      if (s.A.rows() == 0)
      {
        s.A = Eigen::SparseMatrix<double>(s.dim * s.dim * s.f_n, s.dim * s.v_n);
        igl::sparse_cached_precompute(IJV,s.A_data,s.A);
      }
      else
        igl::sparse_cached(IJV,s.A_data,s.A);
      #else
      Eigen::SparseMatrix<double> A(s.dim * s.dim * s.f_n, s.dim * s.v_n);
      slim_buildA(s.Dx, s.Dy, s.Dz, s.W, IJV);
      A.setFromTriplets(IJV.begin(),IJV.end());
      A.makeCompressed();
      #endif

      #ifdef SLIM_CACHED
      #else
      Eigen::SparseMatrix<double> At = A.transpose();
      At.makeCompressed();
      #endif

      #ifdef SLIM_CACHED
      Eigen::SparseMatrix<double> id_m(s.A.cols(), s.A.cols());
      #else
      Eigen::SparseMatrix<double> id_m(A.cols(), A.cols());
      #endif

      id_m.setIdentity();

      // add proximal penalty
      #ifdef SLIM_CACHED
      s.AtA_data.W = s.WGL_M;
      if (s.AtA.rows() == 0)
        igl::AtA_cached_precompute(s.A,s.AtA_data,s.AtA);
      else
        igl::AtA_cached(s.A,s.AtA_data,s.AtA);

      L = s.AtA + s.proximal_p * id_m; //add also a proximal
      L.makeCompressed();

      #else
      L = At * s.WGL_M.asDiagonal() * A + s.proximal_p * id_m; //add also a proximal term
      L.makeCompressed();
      #endif

      #ifdef SLIM_CACHED
      buildRhs(s, s.A);
      #else
      buildRhs(s, A);
      #endif

      Eigen::SparseMatrix<double> OldL = L;
      add_soft_constraints(s,L);
      L.makeCompressed();
    }

    IGL_INLINE void add_soft_constraints(igl::SLIMData& s, Eigen::SparseMatrix<double> &L)
    {
      int v_n = s.v_num;
      for (int d = 0; d < s.dim; d++)
      {
        for (int i = 0; i < s.b.rows(); i++)
        {
          int v_idx = s.b(i);
          s.rhs(d * v_n + v_idx) += s.soft_const_p * s.bc(i, d); // rhs
          L.coeffRef(d * v_n + v_idx, d * v_n + v_idx) += s.soft_const_p; // diagonal of matrix
        }
      }
    }

    IGL_INLINE double compute_energy(igl::SLIMData& s, Eigen::MatrixXd &V_new)
    {
      compute_jacobians(s,V_new);
      return mapping_energy_with_jacobians(s.Ji, s.M, s.slim_energy, s.exp_factor) +
             compute_soft_const_energy(s, s.V, s.F, V_new);
    }

    IGL_INLINE double compute_soft_const_energy(igl::SLIMData& s,
                                                const Eigen::MatrixXd &V,
                                                const Eigen::MatrixXi &F,
                                                Eigen::MatrixXd &V_o)
    {
      double e = 0;
      for (int i = 0; i < s.b.rows(); i++)
      {
        e += s.soft_const_p * (s.bc.row(i) - V_o.row(s.b(i))).squaredNorm();
      }
      return e;
    }

    IGL_INLINE void buildRhs(igl::SLIMData& s, const Eigen::SparseMatrix<double> &A)
    {
      Eigen::VectorXd f_rhs(s.dim * s.dim * s.f_n);
      f_rhs.setZero();
      if (s.dim == 2)
      {
        /*b = [W11*R11 + W12*R21; (formula (36))
             W11*R12 + W12*R22;
             W21*R11 + W22*R21;
             W21*R12 + W22*R22];*/
        for (int i = 0; i < s.f_n; i++)
        {
          f_rhs(i + 0 * s.f_n) = s.W(i, 0) * s.Ri(i, 0) + s.W(i, 1) * s.Ri(i, 1);
          f_rhs(i + 1 * s.f_n) = s.W(i, 0) * s.Ri(i, 2) + s.W(i, 1) * s.Ri(i, 3);
          f_rhs(i + 2 * s.f_n) = s.W(i, 2) * s.Ri(i, 0) + s.W(i, 3) * s.Ri(i, 1);
          f_rhs(i + 3 * s.f_n) = s.W(i, 2) * s.Ri(i, 2) + s.W(i, 3) * s.Ri(i, 3);
        }
      }
      else
      {
        /*b = [W11*R11 + W12*R21 + W13*R31;
             W11*R12 + W12*R22 + W13*R32;
             W11*R13 + W12*R23 + W13*R33;
             W21*R11 + W22*R21 + W23*R31;
             W21*R12 + W22*R22 + W23*R32;
             W21*R13 + W22*R23 + W23*R33;
             W31*R11 + W32*R21 + W33*R31;
             W31*R12 + W32*R22 + W33*R32;
             W31*R13 + W32*R23 + W33*R33;];*/
        for (int i = 0; i < s.f_n; i++)
        {
          f_rhs(i + 0 * s.f_n) = s.W(i, 0) * s.Ri(i, 0) + s.W(i, 1) * s.Ri(i, 1) + s.W(i, 2) * s.Ri(i, 2);
          f_rhs(i + 1 * s.f_n) = s.W(i, 0) * s.Ri(i, 3) + s.W(i, 1) * s.Ri(i, 4) + s.W(i, 2) * s.Ri(i, 5);
          f_rhs(i + 2 * s.f_n) = s.W(i, 0) * s.Ri(i, 6) + s.W(i, 1) * s.Ri(i, 7) + s.W(i, 2) * s.Ri(i, 8);
          f_rhs(i + 3 * s.f_n) = s.W(i, 3) * s.Ri(i, 0) + s.W(i, 4) * s.Ri(i, 1) + s.W(i, 5) * s.Ri(i, 2);
          f_rhs(i + 4 * s.f_n) = s.W(i, 3) * s.Ri(i, 3) + s.W(i, 4) * s.Ri(i, 4) + s.W(i, 5) * s.Ri(i, 5);
          f_rhs(i + 5 * s.f_n) = s.W(i, 3) * s.Ri(i, 6) + s.W(i, 4) * s.Ri(i, 7) + s.W(i, 5) * s.Ri(i, 8);
          f_rhs(i + 6 * s.f_n) = s.W(i, 6) * s.Ri(i, 0) + s.W(i, 7) * s.Ri(i, 1) + s.W(i, 8) * s.Ri(i, 2);
          f_rhs(i + 7 * s.f_n) = s.W(i, 6) * s.Ri(i, 3) + s.W(i, 7) * s.Ri(i, 4) + s.W(i, 8) * s.Ri(i, 5);
          f_rhs(i + 8 * s.f_n) = s.W(i, 6) * s.Ri(i, 6) + s.W(i, 7) * s.Ri(i, 7) + s.W(i, 8) * s.Ri(i, 8);
        }
      }
      Eigen::VectorXd uv_flat(s.dim *s.v_n);
      for (int i = 0; i < s.dim; i++)
        for (int j = 0; j < s.v_n; j++)
          uv_flat(s.v_n * i + j) = s.V_o(j, i);

      s.rhs = (f_rhs.transpose() * s.WGL_M.asDiagonal() * A).transpose() + s.proximal_p * uv_flat;
    }

  }
}

IGL_INLINE void igl::slim_update_weights_and_closest_rotations_with_jacobians(const Eigen::MatrixXd &Ji,
                                          igl::MappingEnergyType slim_energy,
                                          double exp_factor,
                                          Eigen::MatrixXd &W,
                                          Eigen::MatrixXd &Ri)
{
  const double eps = 1e-8;
  double exp_f = exp_factor;
  const int dim = (Ji.cols()==4? 2:3);

  if (dim == 2)
  {
    for (int i = 0; i < Ji.rows(); ++i)
    {
      typedef Eigen::Matrix2d Mat2;
      typedef Eigen::Matrix<double, 2, 2, Eigen::RowMajor> RMat2;
      typedef Eigen::Vector2d Vec2;
      Mat2 ji, ri, ti, ui, vi;
      Vec2 sing;
      Vec2 closest_sing_vec;
      RMat2 mat_W;
      Vec2 m_sing_new;
      double s1, s2;

      ji(0, 0) = Ji(i, 0);
      ji(0, 1) = Ji(i, 1);
      ji(1, 0) = Ji(i, 2);
      ji(1, 1) = Ji(i, 3);

      igl::polar_svd(ji, ri, ti, ui, sing, vi);

      s1 = sing(0);
      s2 = sing(1);

      // Update Weights according to energy
      switch (slim_energy)
      {
        case igl::MappingEnergyType::ARAP:
        {
          m_sing_new << 1, 1;
          break;
        }
        case igl::MappingEnergyType::SYMMETRIC_DIRICHLET:
        {
          double s1_g = 2 * (s1 - pow(s1, -3));
          double s2_g = 2 * (s2 - pow(s2, -3));
          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));
          break;
        }
        case igl::MappingEnergyType::LOG_ARAP:
        {
          double s1_g = 2 * (log(s1) / s1);
          double s2_g = 2 * (log(s2) / s2);
          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));
          break;
        }
        case igl::MappingEnergyType::CONFORMAL:
        {
          double s1_g = 1 / (2 * s2) - s2 / (2 * pow(s1, 2));
          double s2_g = 1 / (2 * s1) - s1 / (2 * pow(s2, 2));

          double geo_avg = sqrt(s1 * s2);
          double s1_min = geo_avg;
          double s2_min = geo_avg;

          m_sing_new << sqrt(s1_g / (2 * (s1 - s1_min))), sqrt(s2_g / (2 * (s2 - s2_min)));

          // change local step
          closest_sing_vec << s1_min, s2_min;
          ri = ui * closest_sing_vec.asDiagonal() * vi.transpose();
          break;
        }
        case igl::MappingEnergyType::EXP_CONFORMAL:
        {
          double s1_g = 2 * (s1 - pow(s1, -3));
          double s2_g = 2 * (s2 - pow(s2, -3));

          double geo_avg = sqrt(s1 * s2);
          double s1_min = geo_avg;
          double s2_min = geo_avg;

          double in_exp = exp_f * ((pow(s1, 2) + pow(s2, 2)) / (2 * s1 * s2));
          double exp_thing = exp(in_exp);

          s1_g *= exp_thing * exp_f;
          s2_g *= exp_thing * exp_f;

          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));
          break;
        }
        case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET:
        {
          double s1_g = 2 * (s1 - pow(s1, -3));
          double s2_g = 2 * (s2 - pow(s2, -3));

          double in_exp = exp_f * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2));
          double exp_thing = exp(in_exp);

          s1_g *= exp_thing * exp_f;
          s2_g *= exp_thing * exp_f;

          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1)));
          break;
        }
      }

      if (std::abs(s1 - 1) < eps) m_sing_new(0) = 1;
      if (std::abs(s2 - 1) < eps) m_sing_new(1) = 1;
      mat_W = ui * m_sing_new.asDiagonal() * ui.transpose();

      W.row(i) = Eigen::Map<Eigen::Matrix<double, 1, 4, Eigen::RowMajor>>(mat_W.data());
      // 2) Update local step (doesn't have to be a rotation, for instance in case of conformal energy)
      Ri.row(i) = Eigen::Map<Eigen::Matrix<double, 1,4,Eigen::RowMajor>>(ri.data());
    }
  }
  else
  {
    typedef Eigen::Matrix<double, 3, 1> Vec3;
    typedef Eigen::Matrix<double, 3, 3, Eigen::ColMajor> Mat3;
    typedef Eigen::Matrix<double, 3, 3, Eigen::RowMajor> RMat3;
    Mat3 ji;
    Vec3 m_sing_new;
    Vec3 closest_sing_vec;
    const double sqrt_2 = sqrt(2);
    for (int i = 0; i < Ji.rows(); ++i)
    {
      ji << Ji(i,0), Ji(i,1), Ji(i,2),
      Ji(i,3), Ji(i,4), Ji(i,5),
      Ji(i,6), Ji(i,7), Ji(i,8);

      Mat3 ri, ti, ui, vi;
      Vec3 sing;
      igl::polar_svd(ji, ri, ti, ui, sing, vi);

      double s1 = sing(0);
      double s2 = sing(1);
      double s3 = sing(2);

      // 1) Update Weights
      switch (slim_energy)
      {
        case igl::MappingEnergyType::ARAP:
        {
          m_sing_new << 1, 1, 1;
          break;
        }
        case igl::MappingEnergyType::LOG_ARAP:
        {
          double s1_g = 2 * (log(s1) / s1);
          double s2_g = 2 * (log(s2) / s2);
          double s3_g = 2 * (log(s3) / s3);
          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));
          break;
        }
        case igl::MappingEnergyType::SYMMETRIC_DIRICHLET:
        {
          double s1_g = 2 * (s1 - pow(s1, -3));
          double s2_g = 2 * (s2 - pow(s2, -3));
          double s3_g = 2 * (s3 - pow(s3, -3));
          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));
          break;
        }
        case igl::MappingEnergyType::EXP_SYMMETRIC_DIRICHLET:
        {
          double s1_g = 2 * (s1 - pow(s1, -3));
          double s2_g = 2 * (s2 - pow(s2, -3));
          double s3_g = 2 * (s3 - pow(s3, -3));
          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));

          double in_exp = exp_f * (pow(s1, 2) + pow(s1, -2) + pow(s2, 2) + pow(s2, -2) + pow(s3, 2) + pow(s3, -2));
          double exp_thing = exp(in_exp);

          s1_g *= exp_thing * exp_f;
          s2_g *= exp_thing * exp_f;
          s3_g *= exp_thing * exp_f;

          m_sing_new << sqrt(s1_g / (2 * (s1 - 1))), sqrt(s2_g / (2 * (s2 - 1))), sqrt(s3_g / (2 * (s3 - 1)));

          break;
        }
        case igl::MappingEnergyType::CONFORMAL:
        {
          double common_div = 9 * (pow(s1 * s2 * s3, 5. / 3.));

          double s1_g = (-2 * s2 * s3 * (pow(s2, 2) + pow(s3, 2) - 2 * pow(s1, 2))) / common_div;
          double s2_g = (-2 * s1 * s3 * (pow(s1, 2) + pow(s3, 2) - 2 * pow(s2, 2))) / common_div;
          double s3_g = (-2 * s1 * s2 * (pow(s1, 2) + pow(s2, 2) - 2 * pow(s3, 2))) / common_div;

          double closest_s = sqrt(pow(s1, 2) + pow(s3, 2)) / sqrt_2;
          double s1_min = closest_s;
          double s2_min = closest_s;
          double s3_min = closest_s;

          m_sing_new << sqrt(s1_g / (2 * (s1 - s1_min))), sqrt(s2_g / (2 * (s2 - s2_min))), sqrt(
              s3_g / (2 * (s3 - s3_min)));

          // change local step
          closest_sing_vec << s1_min, s2_min, s3_min;
          ri = ui * closest_sing_vec.asDiagonal() * vi.transpose();
          break;
        }
        case igl::MappingEnergyType::EXP_CONFORMAL:
        {
          // E_conf = (s1^2 + s2^2 + s3^2)/(3*(s1*s2*s3)^(2/3) )
          // dE_conf/ds1 = (-2*(s2*s3)*(s2^2+s3^2 -2*s1^2) ) / (9*(s1*s2*s3)^(5/3))
          // Argmin E_conf(s1): s1 = sqrt(s1^2+s2^2)/sqrt(2)
          double common_div = 9 * (pow(s1 * s2 * s3, 5. / 3.));

          double s1_g = (-2 * s2 * s3 * (pow(s2, 2) + pow(s3, 2) - 2 * pow(s1, 2))) / common_div;
          double s2_g = (-2 * s1 * s3 * (pow(s1, 2) + pow(s3, 2) - 2 * pow(s2, 2))) / common_div;
          double s3_g = (-2 * s1 * s2 * (pow(s1, 2) + pow(s2, 2) - 2 * pow(s3, 2))) / common_div;

          double in_exp = exp_f * ((pow(s1, 2) + pow(s2, 2) + pow(s3, 2)) / (3 * pow((s1 * s2 * s3), 2. / 3)));;
          double exp_thing = exp(in_exp);

          double closest_s = sqrt(pow(s1, 2) + pow(s3, 2)) / sqrt_2;
          double s1_min = closest_s;
          double s2_min = closest_s;
          double s3_min = closest_s;

          s1_g *= exp_thing * exp_f;
          s2_g *= exp_thing * exp_f;
          s3_g *= exp_thing * exp_f;

          m_sing_new << sqrt(s1_g / (2 * (s1 - s1_min))), sqrt(s2_g / (2 * (s2 - s2_min))), sqrt(
              s3_g / (2 * (s3 - s3_min)));

          // change local step
          closest_sing_vec << s1_min, s2_min, s3_min;
          ri = ui * closest_sing_vec.asDiagonal() * vi.transpose();
        }
      }
      if (std::abs(s1 - 1) < eps) m_sing_new(0) = 1;
      if (std::abs(s2 - 1) < eps) m_sing_new(1) = 1;
      if (std::abs(s3 - 1) < eps) m_sing_new(2) = 1;
      RMat3 mat_W;
      mat_W = ui * m_sing_new.asDiagonal() * ui.transpose();

      W.row(i) = Eigen::Map<Eigen::Matrix<double, 1,9,Eigen::RowMajor>>(mat_W.data());
      // 2) Update closest rotations (not rotations in case of conformal energy)
      Ri.row(i) = Eigen::Map<Eigen::Matrix<double, 1,9,Eigen::RowMajor>>(ri.data());
    } // for loop end

  } // if dim end

}

IGL_INLINE void igl::slim_buildA(const Eigen::SparseMatrix<double> &Dx,
          const Eigen::SparseMatrix<double> &Dy,
          const Eigen::SparseMatrix<double> &Dz,
          const Eigen::MatrixXd &W,
std::vector<Eigen::Triplet<double> > & IJV)
{
  const int dim = (W.cols() == 4) ? 2 : 3;
  const int f_n = W.rows();
  const int v_n = Dx.cols();

  // formula (35) in paper
  if (dim == 2)
  {
    IJV.reserve(4 * (Dx.outerSize() + Dy.outerSize()));

    /*A = [W11*Dx, W12*Dx;
          W11*Dy, W12*Dy;
          W21*Dx, W22*Dx;
          W21*Dy, W22*Dy];*/
    for (int k = 0; k < Dx.outerSize(); ++k)
    {
      for (Eigen::SparseMatrix<double>::InnerIterator it(Dx, k); it; ++it)
      {
        int dx_r = it.row();
        int dx_c = it.col();
        double val = it.value();

        IJV.push_back(Eigen::Triplet<double>(dx_r, dx_c, val * W(dx_r, 0)));
        IJV.push_back(Eigen::Triplet<double>(dx_r, v_n + dx_c, val * W(dx_r, 1)));

        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dx_r, dx_c, val * W(dx_r, 2)));
        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dx_r, v_n + dx_c, val * W(dx_r, 3)));
      }
    }

    for (int k = 0; k < Dy.outerSize(); ++k)
    {
      for (Eigen::SparseMatrix<double>::InnerIterator it(Dy, k); it; ++it)
      {
        int dy_r = it.row();
        int dy_c = it.col();
        double val = it.value();

        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, dy_c, val * W(dy_r, 0)));
        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, v_n + dy_c, val * W(dy_r, 1)));

        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dy_r, dy_c, val * W(dy_r, 2)));
        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dy_r, v_n + dy_c, val * W(dy_r, 3)));
      }
    }
  }
  else
  {

    /*A = [W11*Dx, W12*Dx, W13*Dx;
            W11*Dy, W12*Dy, W13*Dy;
            W11*Dz, W12*Dz, W13*Dz;
            W21*Dx, W22*Dx, W23*Dx;
            W21*Dy, W22*Dy, W23*Dy;
            W21*Dz, W22*Dz, W23*Dz;
            W31*Dx, W32*Dx, W33*Dx;
            W31*Dy, W32*Dy, W33*Dy;
            W31*Dz, W32*Dz, W33*Dz;];*/
    IJV.reserve(9 * (Dx.outerSize() + Dy.outerSize() + Dz.outerSize()));
    for (int k = 0; k < Dx.outerSize(); k++)
    {
      for (Eigen::SparseMatrix<double>::InnerIterator it(Dx, k); it; ++it)
      {
        int dx_r = it.row();
        int dx_c = it.col();
        double val = it.value();

        IJV.push_back(Eigen::Triplet<double>(dx_r, dx_c, val * W(dx_r, 0)));
        IJV.push_back(Eigen::Triplet<double>(dx_r, v_n + dx_c, val * W(dx_r, 1)));
        IJV.push_back(Eigen::Triplet<double>(dx_r, 2 * v_n + dx_c, val * W(dx_r, 2)));

        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dx_r, dx_c, val * W(dx_r, 3)));
        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dx_r, v_n + dx_c, val * W(dx_r, 4)));
        IJV.push_back(Eigen::Triplet<double>(3 * f_n + dx_r, 2 * v_n + dx_c, val * W(dx_r, 5)));

        IJV.push_back(Eigen::Triplet<double>(6 * f_n + dx_r, dx_c, val * W(dx_r, 6)));
        IJV.push_back(Eigen::Triplet<double>(6 * f_n + dx_r, v_n + dx_c, val * W(dx_r, 7)));
        IJV.push_back(Eigen::Triplet<double>(6 * f_n + dx_r, 2 * v_n + dx_c, val * W(dx_r, 8)));
      }
    }

    for (int k = 0; k < Dy.outerSize(); k++)
    {
      for (Eigen::SparseMatrix<double>::InnerIterator it(Dy, k); it; ++it)
      {
        int dy_r = it.row();
        int dy_c = it.col();
        double val = it.value();

        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, dy_c, val * W(dy_r, 0)));
        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, v_n + dy_c, val * W(dy_r, 1)));
        IJV.push_back(Eigen::Triplet<double>(f_n + dy_r, 2 * v_n + dy_c, val * W(dy_r, 2)));

        IJV.push_back(Eigen::Triplet<double>(4 * f_n + dy_r, dy_c, val * W(dy_r, 3)));
        IJV.push_back(Eigen::Triplet<double>(4 * f_n + dy_r, v_n + dy_c, val * W(dy_r, 4)));
        IJV.push_back(Eigen::Triplet<double>(4 * f_n + dy_r, 2 * v_n + dy_c, val * W(dy_r, 5)));

        IJV.push_back(Eigen::Triplet<double>(7 * f_n + dy_r, dy_c, val * W(dy_r, 6)));
        IJV.push_back(Eigen::Triplet<double>(7 * f_n + dy_r, v_n + dy_c, val * W(dy_r, 7)));
        IJV.push_back(Eigen::Triplet<double>(7 * f_n + dy_r, 2 * v_n + dy_c, val * W(dy_r, 8)));
      }
    }

    for (int k = 0; k < Dz.outerSize(); k++)
    {
      for (Eigen::SparseMatrix<double>::InnerIterator it(Dz, k); it; ++it)
      {
        int dz_r = it.row();
        int dz_c = it.col();
        double val = it.value();

        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dz_r, dz_c, val * W(dz_r, 0)));
        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dz_r, v_n + dz_c, val * W(dz_r, 1)));
        IJV.push_back(Eigen::Triplet<double>(2 * f_n + dz_r, 2 * v_n + dz_c, val * W(dz_r, 2)));

        IJV.push_back(Eigen::Triplet<double>(5 * f_n + dz_r, dz_c, val * W(dz_r, 3)));
        IJV.push_back(Eigen::Triplet<double>(5 * f_n + dz_r, v_n + dz_c, val * W(dz_r, 4)));
        IJV.push_back(Eigen::Triplet<double>(5 * f_n + dz_r, 2 * v_n + dz_c, val * W(dz_r, 5)));

        IJV.push_back(Eigen::Triplet<double>(8 * f_n + dz_r, dz_c, val * W(dz_r, 6)));
        IJV.push_back(Eigen::Triplet<double>(8 * f_n + dz_r, v_n + dz_c, val * W(dz_r, 7)));
        IJV.push_back(Eigen::Triplet<double>(8 * f_n + dz_r, 2 * v_n + dz_c, val * W(dz_r, 8)));
      }
    }
  }
}
/// Slim Implementation

IGL_INLINE void igl::slim_precompute(
  const Eigen::MatrixXd &V,
  const Eigen::MatrixXi &F,
  const Eigen::MatrixXd &V_init,
  igl::SLIMData &data,
  igl::MappingEnergyType slim_energy,
  Eigen::VectorXi &b,
  Eigen::MatrixXd &bc,
  double soft_p)
{

  data.V = V;
  data.F = F;
  data.V_o = V_init;

  data.v_num = V.rows();
  data.f_num = F.rows();

  data.slim_energy = slim_energy;

  data.b = b;
  data.bc = bc;
  data.soft_const_p = soft_p;

  data.proximal_p = 0.0001;

  igl::doublearea(V, F, data.M);
  data.M /= 2.;
  data.mesh_area = data.M.sum();
  data.mesh_improvement_3d = false; // whether to use a jacobian derived from a real mesh or an abstract regular mesh (used for mesh improvement)
  data.exp_factor = 1.0; // param used only for exponential energies (e.g exponential symmetric dirichlet)

  assert (F.cols() == 3 || F.cols() == 4);

  igl::slim::pre_calc(data);
  data.energy = igl::slim::compute_energy(data,data.V_o) / data.mesh_area;
}

IGL_INLINE Eigen::MatrixXd igl::slim_solve(igl::SLIMData &data, int iter_num)
{
  for (int i = 0; i < iter_num; i++)
  {
    Eigen::MatrixXd dest_res;
    dest_res = data.V_o;

    // Solve Weighted Proxy
    igl::slim::update_weights_and_closest_rotations(data, dest_res);
    igl::slim::solve_weighted_arap(data,data.V, data.F, dest_res, data.b, data.bc);

    double old_energy = data.energy;

    std::function<double(Eigen::MatrixXd &)> compute_energy = [&](
        Eigen::MatrixXd &aaa) { return igl::slim::compute_energy(data,aaa); };

    data.energy = igl::flip_avoiding_line_search(data.F, data.V_o, dest_res, compute_energy,
                                                 data.energy * data.mesh_area) / data.mesh_area;
  }
  return data.V_o;
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
#endif