#include <fstream>
#include <vector>
#include "RegressionTreeNode.hpp"

#include <boost/spirit/include/qi.hpp>
#include <boost/spirit/include/phoenix_core.hpp>
#include <boost/spirit/include/phoenix_operator.hpp>

namespace qi = boost::spirit::qi;
namespace phoenix = boost::phoenix;

struct Test_tuple
{
   int date;
   int store;
   int item;
   double unit_sales;
   int onpromotion;
   double oilprize;
   Test_tuple(const std::string& tuple)
   {
         qi::phrase_parse(tuple.begin(),tuple.end(),
            qi::int_[phoenix::ref(date) = qi::_1]>>
            qi::int_[phoenix::ref(store) = qi::_1]>>
            qi::int_[phoenix::ref(item) = qi::_1]>>
            qi::double_[phoenix::ref(unit_sales) = qi::_1]>>
            qi::int_[phoenix::ref(onpromotion) = qi::_1]>>
            qi::double_[phoenix::ref(oilprize) = qi::_1],
            '|');
   }
};

void loadTestDataset(std::vector<Test_tuple>& TestDataset)
{
   std::ifstream input;
   std::string line;
   input.open("/Users/yuhao/LMFAO/data/favorita-small-2tbl/test_data.tbl");
   if (!input)
   {
      std::cerr << "TestDataset.tbl does is not exist.\n";
      exit(1);
   }
   while(getline(input, line))
      TestDataset.push_back(Test_tuple(line));
   input.close();
}

double findPrediction(const RegTreeNode* node, const Test_tuple& tuple)
{
   if (node->isLeaf)
      return node->prediction;

   bool goLeft = true;
   const Condition& c = node->condition;
   switch (c.variable)
   {
         case 0 : goLeft = (tuple.date <= c.threshold); break;
         case 1 : goLeft = (tuple.store == c.threshold); break;
         case 2 : goLeft = (tuple.item <= c.threshold); break;
         case 3 : goLeft = (tuple.unit_sales <= c.threshold); break;
         case 4 : goLeft = (tuple.onpromotion == c.threshold); break;
         case 5 : goLeft = (tuple.oilprize <= c.threshold); break;
   }
   if (goLeft)
      return findPrediction(node->lchild, tuple);
   else
      return findPrediction(node->rchild, tuple);
}

void evaluateModel(const RegTreeNode* root)
{
   std::vector<Test_tuple> TestDataset;
   loadTestDataset(TestDataset);
   double pred, diff, error = 0.0;
   for (const Test_tuple& tuple : TestDataset)
      {
      pred = findPrediction(root, tuple);
      diff = tuple.unit_sales-pred;
      error += diff * diff;
   }
   error /= TestDataset.size();
   std::cout << "RMSE: " << sqrt(error) << std::endl;
}

void generateDynamicFunctions(std::vector<Condition>& conditions)
{
   std::string variableMap[] = {"date","store","item","unit_sales","onpromotion","oilprize"};
   std::string variableList[] = {"int date,int store,int item,double unit_sales,int onpromotion","int date,double oilprize"};
   size_t relationMap[] = {0,0,0,0,0,1};
   std::string relationName[] = {"Sales","Oil"};
   std::string conditionStr[] = {"",""};
   for (Condition& c : conditions)
      conditionStr[relationMap[c.variable]] += variableMap[c.variable] + c.op + std::to_string(c.threshold) + "&&";
   std::ofstream ofs("DynamicFunctions.cpp", std::ofstream::out);
   ofs << "#include \"DynamicFunctions.h\"\nnamespace lmfao\n{\n";
   for (size_t rel = 0; rel < 2; ++rel)
   {
      if (!conditionStr[rel].empty())
      {
         conditionStr[rel].pop_back();
         conditionStr[rel].pop_back();
         ofs << "double f_"+relationName[rel]+"("+variableList[rel]+")\n{\n	return ("+conditionStr[rel]+" ? 1.0 : 0.0);\n}\n";
      }
      else
      {
         ofs << "double f_"+relationName[rel]+"("+variableList[rel]+")\n{\n\treturn 1.0;\n}\n";
      }
   }
   ofs << "}\n";
   ofs.close();
}


#ifndef BRASS_GAZEBO_BATTERY_BATTERY_DISCHARGE_H
#define BRASS_GAZEBO_BATTERY_BATTERY_DISCHARGE_H

#include <map>
#include <string>
#include "gazebo/common/Plugin.hh"
#include "gazebo/common/CommonTypes.hh"
#include "gazebo/physics/physics.hh"
#include "ros/ros.h"
#include "ros/subscribe_options.h"
#include "ros/callback_queue.h"
#include <boost/thread/mutex.hpp>
#include "std_msgs/Bool.h"
#include "brass_gazebo_battery/SetCharge.h"
#include "brass_gazebo_battery/SetCharging.h"
#include "brass_gazebo_battery/SetCoef.h"
#include "brass_gazebo_battery/SetChargingRate.h"

// #define BATTERY_DEBUG
#define DBG_INTERVAL 5.0

namespace gazebo
{
/// \brief A plugin that simulate BRASS CP1 battery model: discharge and charge according to power models
class GAZEBO_VISIBLE BatteryPlugin : public ModelPlugin
{
  /// \brief Constructor
public:
  BatteryPlugin();

public:
  ~BatteryPlugin();

  // Inherited.
public:
  virtual void Load(physics::ModelPtr _model, sdf::ElementPtr _sdf);

public:
  virtual void Init();

public:
  virtual void Reset();

private:
  double OnUpdateVoltage(const common::BatteryPtr& _battery);

public:
  bool SetCharging(brass_gazebo_battery::SetCharging::Request& req, brass_gazebo_battery::SetCharging::Response& res);

public:
  bool SetCharge(brass_gazebo_battery::SetCharge::Request& req, brass_gazebo_battery::SetCharge::Response& res);

public:
  bool SetModelCoefficients(brass_gazebo_battery::SetCoef::Request& req, brass_gazebo_battery::SetCoef::Response& res);

public:
  bool SetChargingRate(brass_gazebo_battery::SetChargingRate::Request& req,
                       brass_gazebo_battery::SetChargingRate::Response& res);

  // Connection to the World Update events.
protected:
  event::ConnectionPtr updateConnection;

protected:
  physics::WorldPtr world;

protected:
  physics::PhysicsEnginePtr physics;

protected:
  physics::ModelPtr model;

protected:
  physics::LinkPtr link;

protected:
  common::BatteryPtr battery;

protected:
  sdf::ElementPtr sdf;

  // E(t) = e0 + e1* Q(t)/c
protected:
  double et;

protected:
  double e0;

protected:
  double e1;

  // Initial battery charge in Ah.
protected:
  double q0;

  // Charge rate in A
  // More description about charge rate: http://batteriesbyfisher.com/determining-charge-time
protected:
  double qt;

  // Battery capacity in Ah.
protected:
  double c;

  // Battery inner resistance in Ohm
protected:
  double r;

  // Current low-pass filter characteristic time in seconds.
protected:
  double tau;

  // Raw battery current in A.
protected:
  double iraw;

  // Smoothed battery current in A.
protected:
  double ismooth;

  // Instantaneous battery charge in Ah.
protected:
  double q;

  // This node is for ros communications
protected:
  std::unique_ptr<ros::NodeHandle> rosNode;

protected:
  ros::Publisher charge_state_pub;

protected:
  ros::Publisher charge_state_mwh_pub;

protected:
  ros::Publisher motor_power_pub;

protected:
  ros::Publisher charge_current_pub;

protected:
  ros::Publisher battery_voltage_pub;

protected:
  ros::Publisher battery_remaining_pub;

protected:
  ros::ServiceServer set_charging_srv;

protected:
  ros::ServiceServer set_charge_srv;

protected:
  ros::ServiceServer set_coefficients_srv;

protected:
  ros::ServiceServer set_charging_rate_srv;

protected:
  boost::mutex lock;

protected:
  bool charging;

protected:
  bool battery_full;

protected:
  double sim_time_now;
};
}  // namespace gazebo

#endif  // BRASS_GAZEBO_BATTERY_BATTERY_DISCHARGE_H


#pragma once

#include <armadillo>
#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>
#include <vector>

namespace py = pybind11;

using pyarray = py::array_t<double, py::array::c_style | py::array::forcecast>;

arma::mat pymat(pyarray &array) {
  unsigned nc = 1, nr = array.shape()[0];;
  if (array.ndim()==2) {
    nc = array.shape()[1];
  }
  arma::mat x(&array.data()[0], nc, nr); //, true);
  return x.t();
}

pyarray matpy(arma::mat &x) {
  ssize_t              ndim    = 2;
  std::vector<ssize_t> shape   = { (ssize_t)x.n_rows , (ssize_t)x.n_cols };
  std::vector<ssize_t> strides = { (ssize_t)(sizeof(double)) , (ssize_t)(sizeof(double)*x.n_rows) };
  // return 2-D NumPy array
  return py::array(py::buffer_info(
    &x[0],                                   /* data as contiguous array  */
    sizeof(double),                          /* size of one scalar        */
    py::format_descriptor<double>::format(), /* data type                 */
    ndim,                                    /* number of dimensions      */
    shape,                                   /* shape of the matrix       */
    strides                                  /* strides for each axis     */
  ));
}


#pragma once
// Utility libraries
#include "utils/imu.hpp"
#include "utils/joint_state.hpp"
#include "utils/contacts.hpp"
#include "utils/measurement.h"
#include "sensor_msgs/JointState.h"
// #include "inekf_msgs/ContactArray.h"
// #include "inekf_msgs/KinematicsArray.h"

#include <memory>
#include <queue>

#include <boost/circular_buffer.hpp>

struct cheetah_lcm_data_t {
    cheetah_lcm_data_t() {}

    // std::queue<cheetah_inekf_lcm::ImuMeasurement<double>* > imu_q;
    // std::queue<cheetah_inekf_lcm::ContactsMeasurement* > contact_q;

    std::queue<std::shared_ptr<cheetah_inekf_lcm::ImuMeasurement<double>>> imu_q;
    std::queue<std::shared_ptr<cheetah_inekf_lcm::JointStateMeasurement>> joint_state_q;
    std::queue<std::shared_ptr<cheetah_inekf_lcm::ContactsMeasurement>> contact_q;
    std::queue<double> timestamp_q;

};

class cheetah_lcm_packet_t {
    public:
        // cheetah_lcm_packet_t(): joint_state(12) {}
        // cheetah_inekf_lcm::ImuMeasurement<double> imu;
        // cheetah_inekf_lcm::JointStateMeasurement joint_state;
        // cheetah_inekf_lcm::ContactsMeasurement contact;

        cheetah_lcm_packet_t() {};
        std::shared_ptr<cheetah_inekf_lcm::ImuMeasurement<double>> imu;
        std::shared_ptr<cheetah_inekf_lcm::JointStateMeasurement> joint_state;
        std::shared_ptr<cheetah_inekf_lcm::ContactsMeasurement> contact;

        // Setters
        MeasurementType getType() const { return mtype_; }
        double getTime() { return time_; }
        void setType(MeasurementType type) { mtype_ = type; }
        void setTime(double time) { time_ = time; }
    private:
        double time_;
        MeasurementType mtype_;
};


#include <boost/graph/adjacency_list.hpp>
#include <utility>
#include <algorithm>
#include <iterator>
#include <iostream>

int main()
{
  boost::adjacency_list<> g;

  boost::adjacency_list<>::vertex_descriptor v1 = boost::add_vertex(g);
  boost::adjacency_list<>::vertex_descriptor v2 = boost::add_vertex(g);
  boost::add_vertex(g);
  boost::add_vertex(g);

  std::pair<boost::adjacency_list<>::edge_descriptor, bool> p =
    boost::add_edge(v1, v2, g);
  std::cout.setf(std::ios::boolalpha);
  std::cout << p.second << '\n';

  p = boost::add_edge(v1, v2, g);
  std::cout << p.second << '\n';

  p = boost::add_edge(v2, v1, g);
  std::cout << p.second << '\n';

  std::pair<boost::adjacency_list<>::edge_iterator,
    boost::adjacency_list<>::edge_iterator> es = boost::edges(g);

  std::copy(es.first, es.second,
    std::ostream_iterator<boost::adjacency_list<>::edge_descriptor>{
      std::cout, "\n"});
}


// (C) Copyright Jeremy Siek 2002.
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#include <boost/iterator/iterator_concepts.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/operators.hpp>

struct new_random_access
  : std::random_access_iterator_tag
  , boost::random_access_traversal_tag
{};

struct new_iterator
  : public boost::iterator< new_random_access, int >
{
  int& operator*() const { return *m_x; }
  new_iterator& operator++() { return *this; }
  new_iterator operator++(int) { return *this; }
  new_iterator& operator--() { return *this; }
  new_iterator operator--(int) { return *this; }
  new_iterator& operator+=(std::ptrdiff_t) { return *this; }
  new_iterator operator+(std::ptrdiff_t) { return *this; }
  new_iterator& operator-=(std::ptrdiff_t) { return *this; }
  std::ptrdiff_t operator-(const new_iterator&) const { return 0; }
  new_iterator operator-(std::ptrdiff_t) const { return *this; }
  bool operator==(const new_iterator&) const { return false; }
  bool operator!=(const new_iterator&) const { return false; }
  bool operator<(const new_iterator&) const { return false; }
  int* m_x;
};
new_iterator operator+(std::ptrdiff_t, new_iterator x) { return x; }

struct old_iterator
  : public boost::iterator<std::random_access_iterator_tag, int>
{
  int& operator*() const { return *m_x; }
  old_iterator& operator++() { return *this; }
  old_iterator operator++(int) { return *this; }
  old_iterator& operator--() { return *this; }
  old_iterator operator--(int) { return *this; }
  old_iterator& operator+=(std::ptrdiff_t) { return *this; }
  old_iterator operator+(std::ptrdiff_t) { return *this; }
  old_iterator& operator-=(std::ptrdiff_t) { return *this; }
  old_iterator operator-(std::ptrdiff_t) const { return *this; }
  std::ptrdiff_t operator-(const old_iterator&) const { return 0; }
  bool operator==(const old_iterator&) const { return false; }
  bool operator!=(const old_iterator&) const { return false; }
  bool operator<(const old_iterator&) const { return false; }
  int* m_x;
};
old_iterator operator+(std::ptrdiff_t, old_iterator x) { return x; }

int
main()
{
  boost::iterator_traversal<new_iterator>::type tc;
  boost::random_access_traversal_tag derived = tc;
  (void)derived;

  boost::function_requires<
    boost_concepts::WritableIteratorConcept<int*> >();
  boost::function_requires<
    boost_concepts::LvalueIteratorConcept<int*> >();
  boost::function_requires<
    boost_concepts::RandomAccessTraversalConcept<int*> >();

  boost::function_requires<
    boost_concepts::ReadableIteratorConcept<const int*> >();
  boost::function_requires<
    boost_concepts::LvalueIteratorConcept<const int*> >();
  boost::function_requires<
    boost_concepts::RandomAccessTraversalConcept<const int*> >();

  boost::function_requires<
    boost_concepts::WritableIteratorConcept<new_iterator> >();
  boost::function_requires<
    boost_concepts::LvalueIteratorConcept<new_iterator> >();
  boost::function_requires<
    boost_concepts::RandomAccessTraversalConcept<new_iterator> >();

  boost::function_requires<
    boost_concepts::WritableIteratorConcept<old_iterator> >();
  boost::function_requires<
    boost_concepts::LvalueIteratorConcept<old_iterator> >();
  boost::function_requires<
    boost_concepts::RandomAccessTraversalConcept<old_iterator> >();

  boost::function_requires<
    boost_concepts::InteroperableIteratorConcept<int*, int const*> >();

  return 0;
}


//
// Created by jianping on 17-8-31.
//

#ifndef DEPTHPROBABILITY_COMMON_HPP
#define DEPTHPROBABILITY_COMMON_HPP

#include <Eigen/Dense>
#include <boost/python.hpp>
#include "mvs.h"
#include <stdio.h>

namespace common{
    //u,sigma,n
    boost::python::list RandomGaussion(double mu,double sigma, unsigned int n);

    boost::python::list RandomUniform(double min,double max, unsigned int n);

    boost::python::list GetGaussionSamples(const double& mu, const double& sigma, const boost::python::list& sample_Xs);

    boost::python::list solveParams(const boost::python::list& data);

}

BOOST_PYTHON_MODULE(libdepthProb)
{
    boost::python::def("RandomGaussion", common::RandomGaussion);
    boost::python::def("RandomUniform", common::RandomUniform);
    boost::python::def("GetGaussionSamples", common::GetGaussionSamples);

    boost::python::def("solveParams", common::solveParams);

    boost::python::class_<mvs>("mvs", boost::python::init<int>())
            .def("readScene", &mvs::readScene)
            .def("getImage", &mvs::getImage)
            .def("estimateDepthMap",&mvs::estimateDepthMap)
            .def("getDepth",&mvs::getDepth)
            ;
}

#endif //DEPTHPROBABILITY_COMMON_HPP


#include <boost/geometry/algorithms/is_valid.hpp>


//
// Copyright (c) 2009 Rutger ter Borg
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//

#ifndef BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_OPTION_HPP
#define BOOST_NUMERIC_BINDINGS_BLAS_DETAIL_CBLAS_OPTION_HPP

#include <boost/numeric/bindings/blas/detail/cblas.h>
#include <boost/numeric/bindings/tag.hpp>

namespace boost {
namespace numeric {
namespace bindings {
namespace blas {
namespace detail {

template< typename Tag >
struct cblas_option {};

template<>
struct cblas_option< tag::row_major > {
    static const CBLAS_ORDER value = CblasRowMajor;
};

template<>
struct cblas_option< tag::column_major > {
    static const CBLAS_ORDER value = CblasColMajor;
};

template<>
struct cblas_option< tag::transpose > {
    static const CBLAS_TRANSPOSE value = CblasTrans;
};

template<>
struct cblas_option< tag::no_transpose > {
    static const CBLAS_TRANSPOSE value = CblasNoTrans;
};

template<>
struct cblas_option< tag::conjugate > {
    static const CBLAS_TRANSPOSE value = CblasConjTrans;
};

template<>
struct cblas_option< tag::upper > {
    static const CBLAS_UPLO value = CblasUpper;
};

template<>
struct cblas_option< tag::lower > {
    static const CBLAS_UPLO value = CblasLower;
};

template<>
struct cblas_option< tag::unit > {
    static const CBLAS_DIAG value = CblasUnit;
};

template<>
struct cblas_option< tag::non_unit > {
    static const CBLAS_DIAG value = CblasNonUnit;
};

template<>
struct cblas_option< tag::left > {
    static const CBLAS_SIDE value = CblasLeft;
};

template<>
struct cblas_option< tag::right > {
    static const CBLAS_SIDE value = CblasRight;
};

} // namespace detail
} // namespace blas
} // namespace bindings
} // namespace numeric
} // namespace boost

#endif


/*
 * VarHost_test.cpp
 *
 *  Created on: 25 авг. 2017 г.
 *      Author: sergejkrivonos
 */
#define BOOST_TEST_MODULE Varhost test
#include "VarHost.h"

#include <boost/test/unit_test.hpp>
#include "SymmetricDouble.h"
#include "Polyfit.h"
#include "Variable.h"

using namespace std;
using namespace boost::unit_test;
using namespace omnn::math;

BOOST_AUTO_TEST_CASE(Varhost_test)
{
    auto vh = VarHost::make<int>();
    auto v = vh->New();
    BOOST_TEST(v.getMaxVaExp() == 1);
    auto v1 = vh->New();
    BOOST_TEST(v!=v1);

    Variable a, b;
    BOOST_TEST(a!=b);
    BOOST_TEST(a==a);
    BOOST_TEST(b==b);
    BOOST_TEST(a.getCommonVars()!=b.getCommonVars());

    {
    Variable t(a);
    BOOST_TEST(t==a);
    t = a;
    BOOST_TEST(t==a);
    }

    {
        Valuable t(a.Clone());
        BOOST_TEST(t==a);

        t = a;
        BOOST_TEST(t==a);

        Valuable tt(const_cast<Variable*>(Variable::cast(t))->Move());
        BOOST_TEST(tt==a);
    }

    {
        Valuable t(a);
        BOOST_TEST(t==a);

        t = a;
        BOOST_TEST(t==a);

        Valuable tt(const_cast<Variable*>(Variable::cast(t))->Move());
        BOOST_TEST(tt==a);
    }

    BOOST_CHECK_THROW(a!=v, const char*);

    {
        std::string s = "any str";
        boost::any a = s;
        auto _ = a;
        auto host = VarHost::make<std::string>();
        v1 = host->New(s);
        auto v2 = host->New(s);
        BOOST_TEST(v1==v2);
        auto host2 = VarHost::make<std::string>();
        v1 = host2->New(s);
        BOOST_CHECK_THROW(v1!=v2, const char*);
        v1 = host->New(std::string("t"));
        BOOST_TEST(v1!=v2);
    }

}


#define BOOST_TEST_MODULE collectivev

#include <boost/test/included/unit_test.hpp>
#include <mpl/mpl.hpp>

template<typename T>
bool scatterv_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  const int N = (comm_world.size() * comm_world.size() + comm_world.size()) / 2;
  std::vector<T> v1(N), v2(N);
  std::iota(begin(v1), end(v1), 1);
  mpl::layouts<T> l;
  for (int i = 0, i_end = comm_world.size(), offset = 0; i < i_end; ++i) {
    l.push_back(mpl::indexed_layout<T>({{i + 1, offset}}));
    offset += i + 1;
  }
  if (comm_world.rank() == 0) {
    comm_world.scatterv(0, v1.data(), l, v2.data(), l[0]);
  } else {
    comm_world.scatterv(0, v2.data(), l[comm_world.rank()]);
  }
  for (int i = 0, i_end = comm_world.size(), k = 0; i < i_end; ++i)
    for (int j = 0, j_end = i + 1; j < j_end; ++j, ++k)
      if (i == comm_world.rank())
        if (v1[k] != v2[k])
          return false;
  return true;
}

template<typename T>
bool gatherv_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  const int N = (comm_world.size() * comm_world.size() + comm_world.size()) / 2;
  std::vector<T> v1(N), v2(N);
  std::iota(begin(v1), end(v1), 1);
  mpl::layouts<T> l;
  for (int i = 0, i_end = comm_world.size(), offset = 0; i < i_end; ++i) {
    l.push_back(mpl::indexed_layout<T>({{i + 1, offset}}));
    offset += i + 1;
  }
  if (comm_world.rank() == 0) {
    comm_world.gatherv(0, v1.data(), l[0], v2.data(), l);
    if (v1 != v2)
      return false;
  } else {
    comm_world.gatherv(0, v1.data(), l[comm_world.rank()]);
  }
  return true;
}

template<typename T>
bool allgatherv_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  const int N = (comm_world.size() * comm_world.size() + comm_world.size()) / 2;
  std::vector<T> v1(N), v2(N);
  std::iota(begin(v1), end(v1), 1);
  mpl::layouts<T> l;
  for (int i = 0, i_end = comm_world.size(), offset = 0; i < i_end; ++i) {
    l.push_back(mpl::indexed_layout<T>({{i + 1, offset}}));
    offset += i + 1;
  }
  comm_world.allgatherv(v1.data(), l[comm_world.rank()], v2.data(), l);
  return v1 == v2;
}

template<typename T>
bool alltoallv_test() {
  const mpl::communicator &comm_world = mpl::environment::comm_world();
  std::vector<T> v_send,
      v_recv((comm_world.size() * comm_world.size() + comm_world.size()) / 2), v_expected;
  mpl::layouts<T> l_send, l_recv;
  for (int i = 0, i_end = comm_world.size(); i < i_end; ++i)
    for (int j = 0, j_end = comm_world.rank() + 1; j < j_end; ++j)
      v_send.push_back(comm_world.rank() + 1 + i);
  for (int i = 0, i_end = comm_world.size(); i < i_end; ++i) {
    l_send.push_back(
        mpl::indexed_layout<T>({{comm_world.rank() + 1, (comm_world.rank() + 1) * i}}));
    l_recv.push_back(mpl::indexed_layout<T>({{i + 1, (i * i + i) / 2}}));
  }
  comm_world.alltoallv(v_send.data(), l_send, v_recv.data(), l_recv);
  for (int i = 0, i_end = comm_world.size(); i < i_end; ++i)
    for (int j = 0, j_end = i + 1; j < j_end; ++j)
      v_expected.push_back(i + 1 + comm_world.rank());
  return v_recv == v_expected;
}

BOOST_AUTO_TEST_CASE(collectivev) {
  BOOST_TEST(scatterv_test<double>());
  BOOST_TEST(gatherv_test<double>());
  BOOST_TEST(allgatherv_test<double>());
  BOOST_TEST(alltoallv_test<double>());
}


//Copyright (c) 2008-2016 Emil Dotchevski and Reverge Studios, Inc.

//Distributed under the Boost Software License, Version 1.0. (See accompanying
//file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/qvm/mat_index.hpp>
#include "test_qvm_matrix.hpp"

int
main()
    {
    using namespace boost::qvm;

    test_qvm::matrix<M1,2,3> m;
    m.a[0][0]=42.0f;
    m.a[0][1]=43.0f;
    m.a[0][2]=44.0f;
    m.a[1][0]=45.0f;
    m.a[1][1]=46.0f;
    m.a[1][2]=47.0f;
    BOOST_TEST(mat_index_read(m,0,0)==m.a[0][0]);
    BOOST_TEST(mat_index_read(m,0,1)==m.a[0][1]);
    BOOST_TEST(mat_index_read(m,0,2)==m.a[0][2]);
    BOOST_TEST(mat_index_read(m,1,0)==m.a[1][0]);
    BOOST_TEST(mat_index_read(m,1,1)==m.a[1][1]);
    BOOST_TEST(mat_index_read(m,1,2)==m.a[1][2]);
    BOOST_TEST(&mat_index_write(m,0,0)==&m.a[0][0]);
    BOOST_TEST(&mat_index_write(m,0,1)==&m.a[0][1]);
    BOOST_TEST(&mat_index_write(m,0,2)==&m.a[0][2]);
    BOOST_TEST(&mat_index_write(m,1,0)==&m.a[1][0]);
    BOOST_TEST(&mat_index_write(m,1,1)==&m.a[1][1]);
    BOOST_TEST(&mat_index_write(m,1,2)==&m.a[1][2]);
    return boost::report_errors();
    }


/*
==============================================================================
KratosIncompressibleFluidApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).

Copyright 2007
Pooyan Dadvand, Riccardo Rossi
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain

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 condition:

Distribution of this code for  any  commercial purpose  is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.

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.

==============================================================================
*/

//
//   Project Name:        Kratos
//   Last modified by:    $Author: rrossi $
//   Date:                $Date: 2008-10-13 08:17:41 $
//   Revision:            $Revision: 1.20 $
//
//

// System includes

// External includes
#include <boost/python.hpp>

// Project includes
#include "includes/define.h"
#include "processes/process.h"
#include "custom_python/add_custom_utilities_to_python.h"
#include "custom_utilities/calculate_forces_utilities.h"
#include "custom_utilities/level_set_utilities.h"
#include "custom_utilities/level_set_utilities_implicitextrapolation.h"
#include "custom_utilities/edge_data.h"
#include "custom_utilities/fluid_solver.h"
#include "custom_utilities/levelset_fluid_solver.h"
#include "custom_utilities/Turbolence_Smagorinsky.h"
#include "custom_utilities/pure_convection_edgebased.h"
#include "custom_utilities/elementbased_navierstokes_solver.h"

#include "spaces/ublas_space.h"
#include "linear_solvers/linear_solver.h"

namespace Kratos
{

namespace Python
{
  void  AddCustomUtilitiesToPython()
  {
	using namespace boost::python;

	  class_<CalculateForcesUtils>("CalculateForcesUtils", init<>())
		.def("CalculateForces3D",&CalculateForcesUtils::CalculateForces3D)
		.def("CalculateForces2D",&CalculateForcesUtils::CalculateForces2D)
		.def("CalculatePressureForces2D",&CalculateForcesUtils::CalculatePressureForces2D)
		;

	  class_<SmagorinskyTurbulentModel>("SmagorinskyTurbulentModel", init<>())
	    .def("CalculateTurbulentViscosity2D",&SmagorinskyTurbulentModel::CalculateTurbulentViscosity<2>)
	    .def("CalculateTurbulentViscosity3D",&SmagorinskyTurbulentModel::CalculateTurbulentViscosity<3>)
	    ;

	  class_<LevelSetUtilities>("LevelSetUtilities", init<>())
			  .def("RegenerateFluidModelPart",&LevelSetUtilities::RegenerateFluidModelPart)
			  .def("MarkNodesAsVisited",&LevelSetUtilities::MarkNodesAsVisited)
			  .def("SetDistanceToNegative",&LevelSetUtilities::SetDistanceToNegative)
			  .def("ExtrapolateVelocities",&LevelSetUtilities::ExtrapolateVelocities)
			  .def("ExtrapolateVelocitiesByLayer",&LevelSetUtilities::ExtrapolateVelocitiesByLayer)
			  .def("GenerateModelPart",&LevelSetUtilities::GenerateModelPart)
			  .def("ImplicitExtrapolation_PreProcess",&LevelSetUtilities::ImplicitExtrapolation_PreProcess)
			  .def("ImplicitExtrapolation_PostProcess",&LevelSetUtilities::ImplicitExtrapolation_PostProcess)
			  .def("PrepareForInternalFluidDistanceComputation",&LevelSetUtilities::PrepareForInternalFluidDistanceComputation)
			  .def("FluidDistanceComputation_FromBoundary",&LevelSetUtilities::FluidDistanceComputation_FromBoundary)
			  .def("ApplyMinimumExtrapolationPressureFix",&LevelSetUtilities::ApplyMinimumExtrapolationPressureFix)
			  ;

	  class_<LevelSetUtilitiesImplicitExtrapolation>("LevelSetUtilitiesImplicitExtrapolation", init<>())
			  .def("RegenerateFluidModelPart",&LevelSetUtilitiesImplicitExtrapolation::RegenerateFluidModelPart)
			  .def("MarkNodesAsVisited",&LevelSetUtilitiesImplicitExtrapolation::MarkNodesAsVisited)
			  .def("SetDistanceToNegative",&LevelSetUtilitiesImplicitExtrapolation::SetDistanceToNegative)
			  .def("ExtrapolateVelocities",&LevelSetUtilitiesImplicitExtrapolation::ExtrapolateVelocities)
			  .def("PrepareForInternalFluidDistanceComputation",&LevelSetUtilitiesImplicitExtrapolation::PrepareForInternalFluidDistanceComputation)
			  .def("FluidDistanceComputation_FromBoundary",&LevelSetUtilitiesImplicitExtrapolation::FluidDistanceComputation_FromBoundary)
			  .def("ApplyFluidProperties",&LevelSetUtilitiesImplicitExtrapolation::ApplyFluidProperties)
			  ;

          typedef UblasSpace<double, CompressedMatrix, Vector> SparseSpaceType;
          typedef UblasSpace<double, Matrix, Vector> LocalSpaceType;
          typedef LinearSolver<SparseSpaceType, LocalSpaceType > LinearSolverType;
          // 	class_< ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("ElementBasedNavierStokesSolver2D", init<ModelPart&>() )
//                           .def("ConstructSystemStructure",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::ConstructSystemStructure)
//                           .def("Clear",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::Clear)
//                           .def("SolveStep1",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::SolveStep1)
//                           .def("SolveStep2",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::SolveStep2)
//                           .def("SolveStep3",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::SolveStep3)
//                         ;
          class_< MatrixContainer< 2, SparseSpaceType>,  boost::noncopyable >   ("MatrixContainer2D", init<     >() )
                          .def("ConstructCSRVector",&MatrixContainer< 2, SparseSpaceType >::ConstructCSRVector)
                          .def("BuildCSRData",&MatrixContainer< 2, SparseSpaceType >::BuildCSRData)
                          .def("Clear",&MatrixContainer< 2, SparseSpaceType >::Clear)
                        ;

          class_< MatrixContainer< 3, SparseSpaceType>,  boost::noncopyable >   ("MatrixContainer3D", init<     >() )
                          .def("ConstructCSRVector",&MatrixContainer< 3, SparseSpaceType >::ConstructCSRVector)
                          .def("BuildCSRData",&MatrixContainer< 3, SparseSpaceType >::BuildCSRData)
                          .def("Clear",&MatrixContainer< 3, SparseSpaceType >::Clear)
                        ;

	  class_< FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("FluidSolver2D", init<MatrixContainer< 2, SparseSpaceType>&, ModelPart&, bool, bool >() )
                          .def("Initialize",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Initialize)
                          .def("SetFreeFlowConditions",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SetFreeFlowConditions)
                          .def("ComputeTimeStep",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
                          .def("SolveStep1",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep1)
                          .def("SolveStep2",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep2)
                          .def("SolveStep3",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep3)
                          .def("SolveStep4",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep4)
                          .def("ComputeTimeStep",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
                          .def("CalculateNormals",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateNormals)
                          .def("CalculateCoefficients",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateCoefficients)
                          .def("SetSpeedOfSound",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SetSpeedOfSound)
                          .def("SetDissipationLength",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SetDissipationLength)
			  .def("CalculateForces",&FluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateForces)
                        ;

	  class_< FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("FluidSolver3D", init<MatrixContainer< 3, SparseSpaceType>&, ModelPart&, bool, bool >() )
                          .def("Initialize",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Initialize)
                          .def("SetFreeFlowConditions",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SetFreeFlowConditions)
                          .def("ComputeTimeStep",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
                          .def("SolveStep1",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep1)
                          .def("SolveStep2",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep2)
                          .def("SolveStep3",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep3)
                          .def("SolveStep4",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep4)
                          .def("CalculateNormals",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateNormals)
                          .def("CalculateCoefficients",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateCoefficients)
                          .def("SetSpeedOfSound",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SetSpeedOfSound)
                          .def("SetDissipationLength",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SetDissipationLength)
			  .def("CalculateForces",&FluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateForces)
                        ;

	  class_< LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("LevelSetFluidSolver2D", init<MatrixContainer< 2, SparseSpaceType>&, ModelPart&, bool, bool >() )
			  .def("Initialize",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Initialize)
			  .def("ComputeTimeStep",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
			  .def("SolveStep1",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep1)
			  .def("SolveStep2",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep2)
			  .def("SolveStep3",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep3)
			  .def("SolveStep4",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep4)
			  .def("ExtrapolateVelocities",&LevelSetFluidSolver< 2,MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ExtrapolateVelocities)
			  .def("MarkExternalAndMixedNodes",&LevelSetFluidSolver< 2,MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::MarkExternalAndMixedNodes)
			  .def("MarkInternalAndMixedNodes",&LevelSetFluidSolver< 2,MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::MarkInternalAndMixedNodes)
			  .def("SaveScalarVariableToOldStep",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SaveScalarVariableToOldStep)
			  .def("ChangeSignToDistance",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ChangeSignToDistance)
			  .def("MarkNodesByDistance",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::MarkNodesByDistance)
			  .def("CalculateForces",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateForces)
			  .def("CalculateVariablesDistribution",&LevelSetFluidSolver< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateVariablesDistribution)
			  ;

	  class_< LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("LevelSetFluidSolver3D", init<MatrixContainer< 3, SparseSpaceType>&, ModelPart&, bool, bool >() )
			  .def("Initialize",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Initialize)
			  .def("ComputeTimeStep",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
			  .def("SolveStep1",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep1)
			  .def("SolveStep2",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep2)
			  .def("SolveStep3",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep3)
			  .def("SolveStep4",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SolveStep4)
			  .def("ExtrapolateVelocities",&LevelSetFluidSolver< 3,MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ExtrapolateVelocities)
			  .def("MarkExternalAndMixedNodes",&LevelSetFluidSolver< 3,MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::MarkExternalAndMixedNodes)
			  .def("MarkInternalAndMixedNodes",&LevelSetFluidSolver< 3,MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::MarkInternalAndMixedNodes)
			  .def("SaveScalarVariableToOldStep",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::SaveScalarVariableToOldStep)
			  .def("ChangeSignToDistance",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ChangeSignToDistance)
			  .def("MarkNodesByDistance",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::MarkNodesByDistance)
			  .def("CalculateForces",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateForces)
			  .def("CalculateVariablesDistribution",&LevelSetFluidSolver< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::CalculateVariablesDistribution)
			;

	 class_< PureConvectionEdgeBased< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("PureConvectionEdgeBased2D", init<MatrixContainer< 2, SparseSpaceType>&, ModelPart& >() )
                          .def("Initialize",&PureConvectionEdgeBased< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Initialize)
                          .def("Solve",&PureConvectionEdgeBased< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Solve)
			  .def("ComputeTimeStep",&PureConvectionEdgeBased< 2, MatrixContainer< 2, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
                        ;

	 class_< PureConvectionEdgeBased< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("PureConvectionEdgeBased3D", init<MatrixContainer< 3, SparseSpaceType>&, ModelPart& >() )
                          .def("Initialize",&PureConvectionEdgeBased< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Initialize)
                          .def("Solve",&PureConvectionEdgeBased< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::Solve)
			  .def("ComputeTimeStep",&PureConvectionEdgeBased< 3, MatrixContainer< 3, SparseSpaceType>, SparseSpaceType, LinearSolverType >::ComputeTimeStep)
                        ;

	class_< ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>,  boost::noncopyable >       ("ElementBasedNavierStokesSolver2D", init<ModelPart&>() )
                          .def("ConstructSystemStructure",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::ConstructSystemStructure)
                          .def("Clear",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::Clear)
                          .def("SolveStep1",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::SolveStep1)
                          .def("SolveStep2",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::SolveStep2)
                          .def("SolveStep3",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::SolveStep3)
			  .def("CalculateProjection",&ElementBasedNavierStokesSolver< 2, SparseSpaceType, LinearSolverType>::CalculateProjection)
			;

  }

}  // namespace Python.

} // Namespace Kratos


// Copyright (c) <2016> <Marco Stocchi, UNICA>
// 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 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.

// testing the case study - benchmark SVM

#include "stdafx.h"
#include "DSPX_ann_def.h"
#include "DSPX_ann_helper.h"
#include "DSPX_financial_convert.h"
#include "DSPX_financial_bar.h"
#include "DSPX_financial_data.h"
#include "DSPX_help.h"

#include <dlib-18.18\dlib\svm.h>

#define BARSFILE		"DATA\\H1_13_15.txt" // 2013.01.01 00:00 -> 2015.06.30 22:00

template <class engine_type, class _Init>
inline void _Train(engine_type& _Engine, const size_t& PATSIZE, const _Init& _Beg, const _Init& _End)
{
	typedef ann::real_type							real_type;
	typedef ann::real_vector_type					real_vector_type;
    typedef dlib::matrix<real_type,1,1>				sample_type;
	typedef dlib::radial_basis_kernel<sample_type>	kernel_type;

	sample_type m;

	cout << "training machines\n";

	// main loop
	for (auto I = _Beg; I != _End; ++I)
	{
		std::vector<sample_type> samples;
		real_vector_type targets;

		for (size_t i=0; i<PATSIZE; ++i)
		{
			m(0) = i;

			samples.push_back(m);

			targets.push_back(*(I+i));
		}

		// ignore results
		_Engine.train(samples, targets);

		cout << (I-_Beg) << "\r";
	}

	cout << "\nNetwork trained\n";
}

template <class engine_type, class _Init>
inline void _Test(engine_type& _Engine, const size_t& PATSIZE,
	const _Init& _Beg, const _Init& _End,
		bool _BdumpFcast)
{
	typedef ann::real_type							real_type;
	typedef ann::real_vector_type					real_vector_type;
    typedef dlib::matrix<real_type,1,1>				sample_type;
	typedef dlib::radial_basis_kernel<sample_type>	kernel_type;

	const size_t _PredictionAttempts(std::distance(_Beg, _End));

	cout << "test and retrain, " << _PredictionAttempts << " prediction attempts\n";

	// prep streams
	std::ofstream fout;

	if (_BdumpFcast) { fout.open("bench_results_SVM.txt"); predictor_system::set_stream(fout); }

	sample_type m;

	real_type _MAE(0.0);

	real_type _LastKnown(0.0);

	// main testing loop
	for (auto I = _Beg; I != _End; ++I)
	{

		std::vector<sample_type> samples;

		real_vector_type targets;

		for (size_t i=0; i<PATSIZE; ++i)
		{
			m(0) = i;

			samples.push_back(m);

			targets.push_back(*(I+i-1));
		}

		// training
		dlib::decision_function<kernel_type> df = _Engine.train(samples, targets);

		// get real value forecast
		m(0)=PATSIZE;

		real_type _Fcast = df(m);

		// retrieve and store last series value
		_LastKnown = *(I+PATSIZE-1);

		// find last absolute error
		const real_type _AbsErr(std::abs(_LastKnown - _Fcast));

		_MAE += _AbsErr;

		// dump results...

		if (_BdumpFcast) fout << _LastKnown << "\t" << _Fcast << "\t" << _AbsErr << "\n";

		if ((I-_Beg)%10==0)cout << (I-_Beg) << "\r";
	}

	_MAE /= _PredictionAttempts;

	cout << "\nMAE:" << _MAE << "\n";
}

int main()
{
	// import typenames ...
	typedef ann::real_type							real_type;
	typedef ann::real_vector_type					vector_type;
    typedef dlib::matrix<double,1,1>				sample_type;
    typedef dlib::radial_basis_kernel<sample_type>	kernel_type;

	// source file paths
	const path_type P(BARSFILE);

	// constants
	const size_t MARGIN(128);			// constant used to benchmark purposes
	const size_t INPUTSIZE(32);			// input size
	const real_type _SVMK(0.1);			// SVM kernel
	const real_type	_SVMC(10);			// SVM regularization
	const real_type	_SVME(0.001);		// SVM epsilon insensitivity

	const size_t _TrainingIterations(MARGIN);

	// create data obj, load data
	financials::data DATA(P);

	// retrieve iterators, Bitcoin close price hourly (see DSPX_include.h)
	const auto _01_01_13 = DATA.close_it("2013.01.01 00:00"); // yy mm dd hh mm
	const auto _01_01_14 = DATA.close_it("2014.01.01 00:00"); // yy mm dd hh mm
	const auto _01_01_15 = DATA.close_it("2015.01.01 00:00"); // yy mm dd hh mm

	const auto CLOSEBEG = DATA.close_begin();
	const auto CLOSEEND = DATA.close_end();

	const auto CLOSETRAINBEG = CLOSEBEG;
	const auto CLOSETRAINEND = _01_01_15;

	const auto CLOSETESTBEG = CLOSETRAINEND;
	const auto CLOSETESTEND = CLOSEEND;

	// check data loaded correctly or abort
	if (financials::_Failure(DATA)) return 0;

	cout << "DATASET size:" << DATA.size() << "\n";

    dlib::svr_trainer<kernel_type> _Engine;

    _Engine.set_kernel(kernel_type(_SVMK));

    // This parameter is the usual regularization parameter.  It determines the trade-off
    // between trying to reduce the training error or allowing more errors but hopefully
    // improving the generalization of the resulting function.  Larger values encourage exact
    // fitting while smaller values of C may encourage better generalization.
    _Engine.set_c(_SVMC);
    // Epsilon-insensitive regression means we do regression but stop trying to fit a data
    // point once it is "close enough" to its target value.  This parameter is the value that
    // controls what we mean by "close enough".
    _Engine.set_epsilon_insensitivity(_SVME);

	vector_type::const_iterator BEG = CLOSETRAINEND - _TrainingIterations;
	vector_type::const_iterator END = CLOSETRAINEND;

	_Train(_Engine, INPUTSIZE, BEG, END); // trains networks

	BEG = END;
	//END = BEG + 20*QSIZE;
	END = CLOSETESTEND - INPUTSIZE;

	// test and retrain predictor
	// ... dump forecast results
	_Test(_Engine, INPUTSIZE, BEG, END, true /*results output*/);

	return 0;
}


#include <algorithm>
#include <utility>
#include <boost/utility.hpp>
#include <iostream>
#include <utilities/log.h>
#include <utilities/counter.h>
#include <utilities/indirect.h>
#include <boost/iterator/counting_iterator.hpp>
#include <functional>

#ifdef LOGGING
static rlog::RLogChannel* rlRips =                  DEF_CHANNEL("rips/info", rlog::Log_Debug);
static rlog::RLogChannel* rlRipsDebug =             DEF_CHANNEL("rips/debug", rlog::Log_Debug);
#endif // LOGGING

#ifdef COUNTERS
static Counter*  cClique =                          GetCounter("rips/clique");
#endif // COUNTERS

template<class D, class S>
template<class Functor, class Iterator>
void
Rips<D,S>::
generate(Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const
{
    rLog(rlRipsDebug,       "Entered generate with %d indices", distances().size());

    WithinDistance neighbor(distances(), max);

    // current      = empty
    // candidates   = everything
    VertexContainer current;
    VertexContainer candidates(bg, end);
    // 2018-04-27
    // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
    // and change logic accordingly
    // bron_kerbosch(current, candidates, boost::prior(candidates.begin()), k, neighbor, f);
    bron_kerbosch(current, candidates, candidates.begin(), k, neighbor, f);
}

template<class D, class S>
template<class Functor, class Iterator>
void
Rips<D,S>::
vertex_cofaces(IndexType v, Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const
{
    WithinDistance neighbor(distances(), max);

    // current      = [v]
    // candidates   = everything - [v]
    VertexContainer current; current.push_back(v);
    VertexContainer candidates;
    for (Iterator cur = bg; cur != end; ++cur)
        if (*cur != v && neighbor(v, *cur))
            candidates.push_back(*cur);
    // 2018-04-27
    // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
    // and change logic accordingly
    // bron_kerbosch(current, candidates, boost::prior(candidates.begin()), k, neighbor, f);
    bron_kerbosch(current, candidates, candidates.begin(), k, neighbor, f);
}

template<class D, class S>
template<class Functor, class Iterator>
void
Rips<D,S>::
edge_cofaces(IndexType u, IndexType v, Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const
{
    rLog(rlRipsDebug,   "In edge_cofaces(%d, %d)", u, v);

    WithinDistance neighbor(distances(), max);
    AssertMsg(neighbor(u,v), "The new edge must be in the complex");

    // current      = [u,v]
    // candidates   = everything - [u,v]
    VertexContainer current; current.push_back(u); current.push_back(v);

    VertexContainer candidates;
    for (Iterator cur = bg; cur != end; ++cur)
        if (*cur != u && *cur != v && neighbor(v,*cur) && neighbor(u,*cur))
        {
            candidates.push_back(*cur);
            rLog(rlRipsDebug,   "  added candidate: %d", *cur);
        }

    // 2018-04-27
    // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
    // and change logic accordingly
    // bron_kerbosch(current, candidates, boost::prior(candidates.begin()), k, neighbor, f);
    bron_kerbosch(current, candidates, candidates.begin(), k, neighbor, f);
}

template<class D, class S>
template<class Functor, class Iterator>
void
Rips<D,S>::
cofaces(const Simplex& s, Dimension k, DistanceType max, const Functor& f, Iterator bg, Iterator end) const
{
    rLog(rlRipsDebug,   "In cofaces(%s)", tostring(s).c_str());

    WithinDistance neighbor(distances(), max);

    // current      = s.vertices()
    VertexContainer current(s.vertices().begin(), s.vertices().end());

    // candidates   = everything - s.vertices()     that is a neighbor() of every vertex in the simplex
    VertexContainer candidates;
    typedef difference_iterator<Iterator,
                                typename VertexContainer::const_iterator,
                                std::less<Vertex> >                     DifferenceIterator;
    for (DifferenceIterator cur =  DifferenceIterator(bg, end, s.vertices().begin(), s.vertices().end());
                            cur != DifferenceIterator(end, end, s.vertices().end(), s.vertices().end());
                            ++cur)
    {
        bool nghbr = true;
        for (typename VertexContainer::const_iterator v = s.vertices().begin(); v != s.vertices().end(); ++v)
            if (!neighbor(*v, *cur))        { nghbr = false; break; }

        if (nghbr)
        {
            candidates.push_back(*cur);
            rLog(rlRipsDebug,   "  added candidate: %d", *cur);
        }
    }

    // 2018-04-27
    // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
    // and change logic accordingly
    // bron_kerbosch(current, candidates, boost::prior(candidates.begin()), k, neighbor, f, false);
    bron_kerbosch(current, candidates, candidates.begin(), k, neighbor, f, false);
}

template<class D, class S>
template<class Functor, class NeighborTest>
void
Rips<D,S>::
bron_kerbosch(VertexContainer&                          current,
              const VertexContainer&                    candidates,
              // 2018-04-27
              // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
              // and change logic accordingly
              // typename VertexContainer::const_iterator  excluded,
              typename VertexContainer::const_iterator  excludedNext,
              Dimension                                 max_dim,
              const NeighborTest&                       neighbor,
              const Functor&                            functor,
              bool                                      check_initial) const
{
    rLog(rlRipsDebug,       "Entered bron_kerbosch");

    if (check_initial && !current.empty())
    {
        Simplex s(current);
        rLog(rlRipsDebug,   "Reporting simplex: %s", tostring(s).c_str());
        functor(s);
    }

    if (current.size() == static_cast<size_t>(max_dim) + 1)
        return;

    // 2018-04-27
    // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
    // and change logic accordingly
    // rLog(rlRipsDebug,       "Traversing %d vertices", candidates.end() - boost::next(excluded));
    rLog(rlRipsDebug,       "Traversing %d vertices", candidates.end() - excludedNext);
    // 2018-04-27
    // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
    // and change logic accordingly
    // for (typename VertexContainer::const_iterator cur = boost::next(excluded); cur != candidates.end(); ++cur)
    for (typename VertexContainer::const_iterator cur = excludedNext; cur != candidates.end(); ++cur)
    {
        current.push_back(*cur);
        rLog(rlRipsDebug,   "  current.size() = %d, current.back() = %d", current.size(), current.back());

        VertexContainer new_candidates;
        for (typename VertexContainer::const_iterator ccur = candidates.begin(); ccur != cur; ++ccur)
            if (neighbor(*ccur, *cur))
                new_candidates.push_back(*ccur);
        size_t ex = new_candidates.size();
        for (typename VertexContainer::const_iterator ccur = boost::next(cur); ccur != candidates.end(); ++ccur)
            if (neighbor(*ccur, *cur))
                new_candidates.push_back(*ccur);
        // 2018-04-27
        // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
        // and change logic accordingly
        // excluded  = new_candidates.begin() + (ex - 1);
        excludedNext = new_candidates.begin() + ex;

        // 2018-04-27
        // change 'excluded' to 'excludedNext' (where excludedNext = excluded + 1) to prevent overflow
        // and change logic accordingly
        // bron_kerbosch(current, new_candidates, excluded, max_dim, neighbor, functor);
        bron_kerbosch(current, new_candidates, excludedNext, max_dim, neighbor, functor);
        current.pop_back();
    }
}

template<class Distances_, class Simplex_>
typename Rips<Distances_, Simplex_>::DistanceType
Rips<Distances_, Simplex_>::
distance(const Simplex& s1, const Simplex& s2) const
{
    DistanceType mx = 0;
    for (typename Simplex::VertexContainer::const_iterator      a = s1.vertices().begin();   a != s1.vertices().end();    ++a)
        for (typename Simplex::VertexContainer::const_iterator  b = s2.vertices().begin();   b != s2.vertices().end();    ++b)
            mx = std::max(mx, distances_(*a,*b));
    return mx;
}

template<class Distances_, class Simplex_>
typename Rips<Distances_, Simplex_>::DistanceType
Rips<Distances_, Simplex_>::
max_distance() const
{
    DistanceType mx = 0;
    for (IndexType a = distances_.begin(); a != distances_.end(); ++a)
        for (IndexType b = boost::next(a); b != distances_.end(); ++b)
            mx = std::max(mx, distances_(a,b));
    return mx;
}

template<class Distances_, class Simplex_>
typename Rips<Distances_, Simplex_>::DistanceType
Rips<Distances_, Simplex_>::Evaluator::
operator()(const Simplex& s) const
{
    DistanceType mx = 0;
    for (typename Simplex::VertexContainer::const_iterator      a = s.vertices().begin();   a != s.vertices().end();    ++a)
        for (typename Simplex::VertexContainer::const_iterator  b = boost::next(a);         b != s.vertices().end();    ++b)
            mx = std::max(mx, distances_(*a,*b));
    return mx;
}


#ifndef PARSE_UTIL_HPP
#define PARSE_UTIL_HPP

#include <skelly_sim.hpp>

#include <Eigen/Geometry>
#include <iostream>

namespace parse_util {

template <typename T = Eigen::VectorXd>
inline T convert_array(const toml::array &src) {
    if constexpr (std::is_same_v<T, Eigen::Quaterniond>) {
        double tmp[4];
        for (size_t i = 0; i < src.size(); ++i)
            tmp[i] = src.at(i).as_floating();

        return Eigen::Quaterniond(tmp);
    } else {
        T trg(src.size());
        for (size_t i = 0; i < src.size(); ++i)
            trg[i] = src.at(i).as_floating();

        return trg;
    }
}

} // namespace parse_util
#endif


#include <cmath>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <algorithm>
#include <boost/range/algorithm.hpp>
#include <boost/integer/common_factor_rt.hpp>
#define MAX 100000000

using namespace std;

int N;

int main()
{
    while (cin >> N)
    {
        int p, cnt = 0;
        for (int i = 1; i <= N; i++)
        {
            cin >> p;
            if (p != i)
            {
                cnt++;
            }
        }
        if (cnt == 0 || cnt == 2)
        {
            cout << "YES" << endl;
        }
        else
        {
            cout << "NO" << endl;
        }
    }

    return 0;
}


// Copyright Matt Overby 2021.
// Distributed under the MIT License.

#ifndef MCL_BVHLEAF_HPP
#define MCL_BVHLEAF_HPP 1

#include <Eigen/Geometry>

namespace mcl
{

template<typename T, int DIM>
class BoundingBox : public Eigen::AlignedBox<T,DIM>
{
public:
    bool active;

    // Box at t=0 and t=1
    Eigen::AlignedBox<T,DIM> t0, t1;

    BoundingBox() :
        Eigen::AlignedBox<T,DIM>(),
        active(true)
        {}

    virtual ~BoundingBox() {}

    BoundingBox merged(const BoundingBox& b) const;
};

template<typename T, int DIM>
class BVHLeaf
{
public:
    typedef BoundingBox<T,DIM> BoxType;

    // Index of the primitive
    int idx;

    // If rep-triangle, boolean indicator that v/e is represented
    Eigen::Vector3i v, e;

    BoxType box;

    BVHLeaf() :
        idx(-1),
        v(1,1,1),
        e(1,1,1)
        {}

    virtual ~BVHLeaf() {}
};

} // ns mcl

// Used for Eigen's BVH module
namespace Eigen
{
    template<typename T, int DIM>
    static inline typename mcl::BVHLeaf<T,DIM>::BoxType
    bounding_box(const mcl::BVHLeaf<T,DIM> &n)
    {
        return n.box;
    }
}

#endif


// Copyright 2021 Pavel A. Lebedev
// Licensed under the Apache License, Version 2.0.
// (See accompanying file LICENSE.txt or copy at
//  http://www.apache.org/licenses/LICENSE-2.0)
// SPDX-License-Identifier: Apache-2.0

#ifndef UUID_243592E6_7E51_446A_BAC3_91630AF5C76B
#define UUID_243592E6_7E51_446A_BAC3_91630AF5C76B

#include <boost/container_hash/hash.hpp>

#include <chrono>

template<typename Clock,typename Duration>
struct boost::hash<std::chrono::time_point<Clock,Duration>>
{
    std::size_t operator()(std::chrono::time_point<Clock,Duration> tp) const noexcept
    {
        auto c = tp.time_since_epoch().count();
        return boost::hash<decltype(c)>{}(c);
    }
};

template<typename Clock,typename Duration>
struct std::hash<std::chrono::time_point<Clock,Duration>>
    : boost::hash<std::chrono::time_point<Clock,Duration>> {};

#endif


/*
==============================================================================
KratosMultiScaleApplication
A library based on:
Kratos
A General Purpose Software for Multi-Physics Finite Element Analysis
Version 1.0 (Released on march 05, 2007).

Copyright 2007
Pooyan Dadvand, Riccardo Rossi, Janosch Stascheit, Felix Nagel
pooyan@cimne.upc.edu
rrossi@cimne.upc.edu
janosch.stascheit@rub.de
nagel@sd.rub.de
- CIMNE (International Center for Numerical Methods in Engineering),
Gran Capita' s/n, 08034 Barcelona, Spain
- Ruhr-University Bochum, Institute for Structural Mechanics, Germany

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 condition:

Distribution of this code for  any  commercial purpose  is permissible
ONLY BY DIRECT ARRANGEMENT WITH THE COPYRIGHT OWNERS.

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.

==============================================================================
*/
//
//   Project Name:        Kratos
//   Last Modified by:    $Author: Massimo Petracca $
//   Date:                $Date: 2013-10-03 19:37:00 $
//   Revision:            $Revision: 1.00 $
//
//

// System includes

// External includes
#include <boost/python.hpp>
#include "includes/constitutive_law.h"
#include "includes/properties.h"

// Project includes
#include "add_constitutive_laws_to_python.h"
#include "constitutive_laws/linear_elastic_no_tension_plane_stress_2d_law.h"
#include "constitutive_laws/linear_elastic_thick_shell_law.h"
#include "constitutive_laws/conv_diff_constitutive_law_3d.h"
#include "constitutive_laws/conv_diff_anisotropic_3d_law.h"
#include "constitutive_laws/conv_diff_plane_stress_2d_law.h"
#include "constitutive_laws/conv_diff_anisotropic_2d_law.h"
#include "constitutive_laws/j2_constitutive_law_3d.h"
#include "constitutive_laws/damage_iso_plane_stress_2d_law.h"
#include "constitutive_laws/damage_tc_plane_stress_2d_law.h"
#include "constitutive_laws/damage_tc_3d_law.h"
#include "constitutive_laws/scalar_damage_interface_2d_law.h"
#include "constitutive_laws/scalar_damage_interface_3d_law.h"
#include "constitutive_laws/conv_diff_interface_2d_law.h"
#include "constitutive_laws/conv_diff_interface_3d_law.h"
#include "constitutive_laws/plastic_damage_interface_2d_law.h"
#include "constitutive_laws/shell_from_3d_constitutive_law_adapter.h"
#include "constitutive_laws/planestress_from_3d_constitutive_law_adapter.h"
#include "constitutive_laws/planestrain_from_3d_constitutive_law_adapter.h"
#include "constitutive_laws/interpolated_constitutive_law_2d.h"
#include "multiscale_application_variables.h"

namespace Kratos
{
namespace Python
{

using namespace boost::python;

void AddConstitutiveLawsToPython()
{
	class_< InterpolatedConstitutiveLaw2D, bases< ConstitutiveLaw >, boost::noncopyable >(
		"InterpolatedConstitutiveLaw2D",
		init<const RveMaterialDatabase::Pointer&>())
		;

	class_< LinearElasticNoTensionPlaneStress2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"LinearElasticNoTensionPlaneStress2DLaw",
		init<>())
		;

	class_< ConvDiffConstitutiveLaw3D, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ConvDiffConstitutiveLaw3D",
		init<>())
		;

	class_< ConvDiffAnisotropic3DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ConvDiffAnisotropic3DLaw",
		init<>())
		;

	class_< ConvDiffPlaneStress2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ConvDiffPlaneStress2DLaw",
		init<>())
		;

	class_< ConvDiffAnisotropic2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ConvDiffAnisotropic2DLaw",
		init<>())
		;

	class_< LinearElasticThickShellLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"LinearElasticThickShellLaw",
		init<>())
		;

	class_< J2ConstitutiveLaw3D, bases< ConstitutiveLaw >, boost::noncopyable >(
		"J2ConstitutiveLaw3D",
		init<>())
		;

	class_< DamageIsoPlaneStress2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"DamageIsoPlaneStress2DLaw",
		init<>())
		;

	class_< DamageTCPlaneStress2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"DamageTCPlaneStress2DLaw",
		init<>())
		;

	class_< DamageTC3DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"DamageTC3DLaw",
		init<>())
		;

	class_< ScalarDamageInterface2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ScalarDamageInterface2DLaw",
		init<>())
		;

	class_< ScalarDamageInterface3DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ScalarDamageInterface3DLaw",
		init<>())
		;

	class_< ConvDiffInterface2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ConvDiffInterface2DLaw",
		init<>())
		;

	class_< ConvDiffInterface3DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"ConvDiffInterface3DLaw",
		init<>())
		;

	class_< PlasticDamageInterface2DLaw, bases< ConstitutiveLaw >, boost::noncopyable >(
		"PlasticDamageInterface2DLaw",
		init<>())
		;

	typedef ShellFrom3DConstitutiveLawAdapter<ConstitutiveLaw> ShellFrom3DConstitutiveLawAdapterType;
	class_< ShellFrom3DConstitutiveLawAdapterType, ShellFrom3DConstitutiveLawAdapterType::Pointer,
		    bases< ConstitutiveLaw >, boost::noncopyable >(
			"ShellFrom3DConstitutiveLawAdapter",
			init<const ConstitutiveLaw::Pointer&>())
			;

	typedef PlaneStressFrom3DConstitutiveLawAdapter<ConstitutiveLaw> PlaneStressFrom3DConstitutiveLawAdapterType;
	class_< PlaneStressFrom3DConstitutiveLawAdapterType, PlaneStressFrom3DConstitutiveLawAdapterType::Pointer,
		    bases< ConstitutiveLaw >, boost::noncopyable >(
			"PlaneStressFrom3DConstitutiveLawAdapter",
			init<const ConstitutiveLaw::Pointer&>())
			;

	typedef PlaneStrainFrom3DConstitutiveLawAdapter<ConstitutiveLaw> PlaneStrainFrom3DConstitutiveLawAdapterType;
	class_< PlaneStrainFrom3DConstitutiveLawAdapterType, PlaneStrainFrom3DConstitutiveLawAdapterType::Pointer,
		    bases< ConstitutiveLaw >, boost::noncopyable >(
			"PlaneStrainFrom3DConstitutiveLawAdapter",
			init<const ConstitutiveLaw::Pointer&>())
			;

}

}

}


#ifndef ComputeHistogram_hpp
#define ComputeHistogram_hpp

#include <QAlgorithm.hpp>
#include <armadillo>

namespace UMF {
	class ComputeHistogram;
}

class UMF::ComputeHistogram : public QAlgorithm {

	Q_OBJECT

	QA_INPUT_VEC(double, Values)
	QA_OUTPUT(QVector<double>, HistX)
	QA_OUTPUT(QVector<double>, HistY)
	QA_PARAMETER(double, BarStep, 0.02)
	QA_PARAMETER(double, MinimumValue, 0.0)
	QA_PARAMETER(double, MaximumValue, 2.0)
	QA_PARAMETER(bool, SuppressZeroCount, true)

	QA_CTOR_INHERIT
	QA_IMPL_CREATE(ComputeHistogram)

public:
	void run();

Q_SIGNALS:
	Q_SIGNAL void histogramReady(QVector<double> Bin, QVector<double> Count);
};

#endif /* ComputeHistogram_hpp */


// Copyright Louis Dionne 2013-2017
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

#include <boost/hana/integral_constant.hpp>
namespace hana = boost::hana;
using namespace hana::literals;

static constexpr auto x = 4'321'000_c;
static_assert(decltype(x)::value == 4'321'000, "");

int main() { }


#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE netlistDB_large_query_test

#include <boost/test/unit_test.hpp>
#include <functional>
#include <iostream>
#include <fstream>
#include <stdint.h>
#include <random>

#include <netlistDB/netlist.h>
#include <netlistDB/statement_if.h>
#include <netlistDB/hw_type/common.h>
#include <netlistDB/query/query_match.h>
#include <netlistDB/operator_defs.h>
#include <netlistDB/query/query_traverse.h>
#include <netlistDB/utils/timer.h>

#include "test_graphs.h"

using namespace netlistDB;
using namespace netlistDB::query;
using namespace netlistDB::hw_type;
using namespace netlistDB::utils;

BOOST_AUTO_TEST_SUITE( netlistDB_testsuite )
auto & t = hw_int32;
std::vector<FunctionCall*> find_ops(Netlist & ctx, FunctionDef & op) {
	// traverse and count the number of the add operators
	QueryTraverse q(ctx.nodes.size());
	std::vector<iNode*> inputs;
	for (auto n : ctx.nets) {
		if (n->direction == Direction::DIR_IN) {
			inputs.push_back(n);
		}
	}

	boost::mutex mx;

	std::vector<FunctionCall*> ops;
	auto cb = [&ops, &op, &mx] (iNode& n,
			const std::function<void(iNode &)> & select) {
		auto _n = dynamic_cast<FunctionCall*>(&n);
		if (_n and &_n->fn == &op) {
			boost::mutex::scoped_lock lock(mx);
			ops.push_back(_n);
		}
		QueryTraverse::dummy_callback(n, select);
	};
	q.traverse(inputs, cb);

	return ops;
}

BOOST_AUTO_TEST_CASE( query_add ) {
	Netlist ctx("test");
	std::mt19937 rand(0);
	build_random_circuit(ctx, 10, 10, 10, 10, rand);

	QueryMatch query_add;

	auto &r = query_add.sig_in("a", t) + query_add.sig_in("b", t);
	r.direction = Direction::DIR_OUT;

	auto qres = query_add.search(ctx);
	BOOST_CHECK_EQUAL(qres.size(), 29);

	// search from different end
	std::reverse(ctx.nets.begin(), ctx.nets.end());
	qres = query_add.search(ctx);
	BOOST_CHECK_EQUAL(qres.size(), 29);

	auto adds = find_ops(ctx, OpAdd);
	BOOST_CHECK_EQUAL(qres.size(), 29);
}

BOOST_AUTO_TEST_CASE( query_mac ) {
	size_t N = 100;

	Netlist ctx("test");
	std::mt19937 rand(0);
	build_random_circuit(ctx, N, N, N, N, rand);

	QueryMatch query_mac;
	auto &r = query_mac.sig_in("a", t)
			+ (query_mac.sig_in("b", t) * query_mac.sig_in("c", t));
	r.direction = Direction::DIR_OUT;

	auto t = new Timer(std::string("query_mac size:") + std::to_string(N));
	auto qres = query_mac.search(ctx);
	delete t;

	BOOST_CHECK_EQUAL(qres.size(), 479);
}

//____________________________________________________________________________//

BOOST_AUTO_TEST_SUITE_END()


// This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// 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 "writeDMAT.h"
#include "list_to_matrix.h"
#include <Eigen/Core>

#include <cstdio>

template <typename DerivedW>
IGL_INLINE bool igl::writeDMAT(
  const std::string file_name,
  const Eigen::MatrixBase<DerivedW> & W,
  const bool ascii)
{
  FILE * fp = fopen(file_name.c_str(),"wb");
  if(fp == NULL)
  {
    fprintf(stderr,"IOError: writeDMAT() could not open %s...",file_name.c_str());
    return false;
  }
  if(ascii)
  {
    // first line contains number of rows and number of columns
    fprintf(fp,"%d %d\n",(int)W.cols(),(int)W.rows());
    // Loop over columns slowly
    for(int j = 0;j < W.cols();j++)
    {
      // loop over rows (down columns) quickly
      for(int i = 0;i < W.rows();i++)
      {
        fprintf(fp,"%0.17lg\n",(double)W(i,j));
      }
    }
  }else
  {
    // write header for ascii
    fprintf(fp,"0 0\n");
    // first line contains number of rows and number of columns
    fprintf(fp,"%d %d\n",(int)W.cols(),(int)W.rows());
    // reader assumes the binary part is double precision
    Eigen::MatrixXd Wd = W.template cast<double>();
    fwrite(Wd.data(),sizeof(double),Wd.size(),fp);
    //// Loop over columns slowly
    //for(int j = 0;j < W.cols();j++)
    //{
    //  // loop over rows (down columns) quickly
    //  for(int i = 0;i < W.rows();i++)
    //  {
    //    double d = (double)W(i,j);
    //    fwrite(&d,sizeof(double),1,fp);
    //  }
    //}
  }
  fclose(fp);
  return true;
}

template <typename Scalar>
IGL_INLINE bool igl::writeDMAT(
  const std::string file_name,
  const std::vector<std::vector<Scalar> > & W,
  const bool ascii)
{
  Eigen::Matrix<Scalar,Eigen::Dynamic,Eigen::Dynamic> mW;
  list_to_matrix(W,mW);
  return igl::writeDMAT(file_name,mW,ascii);
}

template <typename Scalar>
IGL_INLINE bool igl::writeDMAT(
  const std::string file_name,
  const std::vector<Scalar > & W,
  const bool ascii)
{
  Eigen::Matrix<Scalar,Eigen::Dynamic,1> mW;
  list_to_matrix(W,mW);
  return igl::writeDMAT(file_name,mW,ascii);
}

#ifdef IGL_STATIC_LIBRARY
// Explicit template instantiation
template bool igl::writeDMAT<Eigen::Matrix<double, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::MatrixBase<Eigen::Matrix<double, -1, -1, 0, -1, -1> > const&, bool);
template bool igl::writeDMAT<Eigen::Matrix<double, 1, 3, 1, 1, 3> >(std::string, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, bool);
template bool igl::writeDMAT<Eigen::Matrix<float, 1, 3, 1, 1, 3> >(std::string, Eigen::MatrixBase<Eigen::Matrix<float, 1, 3, 1, 1, 3> > const&, bool);
template bool igl::writeDMAT<Eigen::Matrix<int, -1, -1, 0, -1, -1> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::MatrixBase<Eigen::Matrix<int, -1, -1, 0, -1, -1> > const&, bool);
template bool igl::writeDMAT<Eigen::Matrix<int, -1, 2, 0, -1, 2> >(std::basic_string<char, std::char_traits<char>, std::allocator<char> >, Eigen::MatrixBase<Eigen::Matrix<int, -1, 2, 0, -1, 2> > const&, bool);
#endif


// Copyright (C) 2014-2015,2018 Vicente J. Botet Escriba
//
//  Distributed under the Boost Software License, Version 1.0. (See accompanying
//  file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#include <boost/detail/lightweight_test.hpp>

#include <functional>
#include <iostream>

#include <experimental/fundamental/v2/callable_wrapper.hpp>
#include <experimental/optional.hpp>

template <class T>
struct is_optional : std::false_type {};
template <class T>
struct is_optional<std::experimental::optional<T>> : std::true_type {};

template <class R>
R f_fptr(R (&c)(int)) { return c(0); }

//int f_fptr(int (&c)(int)) { return c(0); }

template <class C>
typename std::result_of<C(int)>::type f_orig(C  c) { return c(0); }

template <class R, class C >
R f_aux(std::experimental::callable_wrapper<C, R(int)> c) { return c(0); }

template <class C>
auto f(C c)
    -> decltype( f_aux(std::experimental::make_callable_wrapper<int>(c)) )
{
    return f_aux(std::experimental::make_callable_wrapper<int>(c)) ;
}

template <class T, class U, class C >
std::experimental::optional<U> mbind_aux(std::experimental::optional<T> o, std::experimental::callable_wrapper<C, std::experimental::optional<U>(T)> c) {
    if (o) return c(*o);
    else return std::experimental::nullopt;
}

// auto mbind(std::experimental::optional<T>, (T -> optional<U>) ) -> optional<U>

template <class T, class C, typename = typename std::enable_if<
    //std::experimental::meta::is_callable_v<C(T)> &&
    is_optional<typename std::result_of<C(T)>::type>::value
    >::type >
auto mbind(std::experimental::optional<T> o, C c)
    -> decltype( mbind_aux(o, std::experimental::make_callable_wrapper<T>(c)) )
{
    return mbind_aux(o, std::experimental::make_callable_wrapper<T>(c)) ;
}

template <class T, class U, class C >
std::experimental::optional<U> fmap_aux(std::experimental::callable_wrapper<C, U(T)> c, std::experimental::optional<T> o) {
    if (o) return std::experimental::make_optional(c(*o));
    else return std::experimental::nullopt;
}

// auto fmap((T -> U), std::experimental::optional<T> ) -> optional<U>

template <class T, class C, typename = typename std::enable_if<true
    //&& std::experimental::meta::is_callable_v<C(T)>
>::type >
auto fmap(C c, std::experimental::optional<T> o)
    -> decltype( fmap_aux(std::experimental::make_callable_wrapper<T>(c), o) )
{
    return fmap_aux(std::experimental::make_callable_wrapper<T>(c), o) ;
}

struct X {
  X() {}
    int operator()(int i) const  { return i; }
    short operator()(short i) const { return 2*i; }
};

// fixme when
#if 0
static_assert(std::experimental::meta::is_callable_v<X(int)>, "");
#endif
struct XO {
    std::experimental::optional<int> operator()(int i) const { return i; }
};

int fX(int i) { return 2*i; }
std::experimental::optional<int> fXo(int i) { return 2*i; }

template <class T>
struct check{};

int main() {
  using namespace std;
  namespace stde = std::experimental;

    BOOST_TEST(f_fptr(fX) == 0);

    X x;
    BOOST_TEST(f_orig(x) == 0);

    static_assert(is_same<typename result_of<X(int)>::type, int>::value, "");
    BOOST_TEST(x(1) == 1);

    stde::callable_wrapper<X, typename result_of<X(int)>::type(int)>c {x};
    BOOST_TEST(c(1) == 1);
    BOOST_TEST(f_aux(c) == 0);
    BOOST_TEST(f(x) == 0);
    BOOST_TEST(f(c) == 0);
    BOOST_TEST(f(fX) == 0);

    {
    static_assert(is_optional<typename result_of<XO(int)>::type>::value, "");
    XO xo;
    stde::optional<int> o{1};
    BOOST_TEST(*mbind(o, xo) == 1);
    BOOST_TEST(*mbind(o, fXo) == 2);
    }
    {
    stde::optional<int> o;
    BOOST_TEST(mbind(o, fXo) == stde::nullopt);
    }
    {
    stde::optional<int> o{1};
    BOOST_TEST(*fmap(x, o) == 1);
    BOOST_TEST(*fmap(fX, o) == 2);
    }
    {
    stde::optional<short> o{1};
    BOOST_TEST(*fmap(x, o) == 2);
    }
    {
    const X xc;
    stde::optional<short> o{1};
    BOOST_TEST(*fmap(xc, o) == 2);
    }
    {
    stde::optional<int> o;
    BOOST_TEST(fmap(x, o) == stde::nullopt);
    }

    {
    XO xo;
    stde::optional<int> o{1};
    auto r  = fmap(xo, o);
    static_assert(is_same<decltype(r), stde::optional<stde::optional<int>>>::value, "");

    }
    {
    // uncomment the following lines like to see the kind of compile erors
    //X x;
    //stde::optional<int> o{1};
    //auto r  = mbind(o, x);
    }
    {
    // uncomment the following like to see the kind of compile erors
    //int i=0;
    //stde::optional<int> o{1};
    //auto r  = fmap(i, o);
    }
    return ::boost::report_errors();

}


/*
 * ============================================================================
 *
 *       Filename:  test_graphcontainer.cc
 *
 *         Author:  Prashant Pandey (), ppandey2@cs.cmu.edu
 *   Organization:  Carnegie Mellon University
 *
 * ============================================================================
 */

#include <stdlib.h>
#include <assert.h>

#include <iostream>
#include <string>
#include <openssl/rand.h>

#include <boost/graph/graph_traits.hpp>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/dijkstra_shortest_paths.hpp>

#include "graph.h"

using namespace variantstore;
std::shared_ptr<spdlog::logger> console;

int test_correctness(const Graph& graph, std::unordered_map<uint32_t,
											std::unordered_set<uint32_t>>& adj_list,
											std::set<std::pair<uint32_t, uint32_t>>& edge_list) {
	// check graph correctness by iterating over @adj_list
	for (auto it = adj_list.begin(); it != adj_list.end(); ++it) {
		Graph::vertex_set neighbors = graph.out_neighbors(it->first);

		if (it->second != neighbors) {
			std::cout << it->first << " - ";
			std::cout << '\n';
			for (auto const n : neighbors) {
				std::cout << n << " ";
			}

			std::cout << '\n';
			for (auto const n : it->second) {
				std::cout << n << " ";
			}
			std::cout << '\n';
			ERROR("correctness test failed!");
			return EXIT_FAILURE;
		}
	}
	PRINT("Correctness check passed: by iterating over @adj_list!");

	// check graph correctness by iterating over Graph::VertexIterator
	Graph::VertexIterator vitr = graph.begin_vertices();
	while (!vitr.done()) {
		Graph::vertex v = *vitr;
		Graph::vertex_set neighbors = graph.out_neighbors(v);

		if (adj_list[v] != neighbors) {
			std::cout << v << " - ";
			std::cout << '\n';
			for (auto const n : neighbors) {
				std::cout << n << " ";
			}

			std::cout << '\n';
			for (auto const n : adj_list[v]) {
				std::cout << n << " ";
			}
			std::cout << '\n';
			ERROR("correctness test failed!");
			return EXIT_FAILURE;
		}
		//assert(adj_list[v] == neighbors);
		++vitr;
	}
	PRINT("Correctness check passed: by iterating over Graph::VertexIterator!");

	// check graph correctness by iterating over @edge_list
	for (auto it = edge_list.begin(); it != edge_list.end(); ++it) {
		if (!graph.is_edge(*it)) {
			PRINT("Graph edge: " << (*it).first << " - " << (*it).second);
			ERROR("correctness test failed!");
			return EXIT_FAILURE;
		}
	}
	PRINT("Correctness check passed: by iterating over @edge_list!");

	// check graph correctness by iterating over Graph::EdgeIterator
	Graph::EdgeIterator eitr = graph.begin_edges();
	while(!eitr.done()) {
		Graph::edge e = *eitr;
		if (edge_list.find(e) == edge_list.end()) {
			PRINT("Graph edge: " << e.first << " - " << e.second);
			ERROR("correctness test failed!");
			return EXIT_FAILURE;
		}
		++eitr;
	}
	PRINT("Correctness check passed: by iterating over Graph::EdgeIterator!");

	return EXIT_SUCCESS;
}

/*
 * ===  FUNCTION  =============================================================
 *         Name:  main
 *  Description:
 * ============================================================================
 */
	int
main ( int argc, char *argv[] )
{
	if (argc < 2) {
		fprintf(stderr, "Please specify the log of the number of slots in the CQF.\n");
		exit(1);
	}
	uint64_t qbits = atoi(argv[1]);
	uint64_t nslots = (1ULL << qbits);
	uint64_t nvals = 95*nslots/100;
	//nslots *= 16;

	// create a typedef for the Graph type
	//typedef boost::adjacency_list<boost::setS, boost::vecS, boost::directedS>
		//BoostGraph;

	console = spdlog::default_logger();
	Graph graph(nslots);
	//BoostGraph bg(nslots);

	/* Generate random values */
	uint32_t *vals = (uint32_t*)malloc(nvals*sizeof(vals[0]));
	RAND_bytes((unsigned char *)vals, sizeof(*vals) * nvals);
	for (uint32_t i = 0; i < nvals; i++) {
		vals[i] = (1 * vals[i]) % nvals + 1;
	}

	srand(time(NULL));
	// to check the correctness of our graph implementation.
	std::unordered_map<uint32_t, std::unordered_set<uint32_t>> adj_list;
	std::set<std::pair<uint32_t, uint32_t>> edge_list;
	for (uint32_t i = 0; i < nvals; i++) {
		uint32_t key = vals[i];
		uint32_t nedges = rand() % 4 + 1;		// up to 4 outgoing edges from a node

		//if (nedges > 1)
			//PRINT("Higher degree node: " << key << " " << nedges);
		//else if (nedges == 1)
			//PRINT("Single degree node: " << key);

		std::unordered_set<uint32_t> vec;
		for (uint32_t j = 0; j < nedges; j++) {
			uint32_t tonode = vals[rand() % nvals];
			graph.add_edge(key, tonode);
			//boost::add_edge(key, tonode, bg);
			vec.insert(tonode);
			edge_list.insert(std::make_pair(key, tonode));
		}
		adj_list[key].merge(vec);
	}

	PRINT("Num vertices: " << graph.get_num_vertices());
	PRINT("Num edges: " << graph.get_num_edges());

	if (test_correctness(graph, adj_list, edge_list) == EXIT_FAILURE)
		return EXIT_FAILURE;

	PRINT("Serializing graph");
	graph.serialize("./ser");

	PRINT("Loading graph from disk");
	Graph file_graph("./ser");

	PRINT("Testing correctness for file graph");
	if (test_correctness(file_graph, adj_list, edge_list) == EXIT_FAILURE)
		return EXIT_FAILURE;

	return EXIT_SUCCESS;
}				/* ----------  end of function main  ---------- */