text:
/*
** Copyright (C) 2015 Aldebaran Robotics
*/

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include <qi/property.hpp>
#include <qi/anyobject.hpp>
#include <qi/type/proxyproperty.hpp>
#include <qi/signalspy.hpp>
#include <qi/testutils/testutils.hpp>
#include <boost/container/flat_map.hpp>
#include <boost/container/flat_set.hpp>
#include <boost/container/static_vector.hpp>
#include <boost/container/stable_vector.hpp>
#include <boost/container/small_vector.hpp>
#include <thread>
#include <chrono>
#include <deque>
#include <unordered_map>
#include <unordered_set>
#include <queue>
#include <stack>

qiLogCategory("qi.test.property");

using namespace qi;

namespace test
{
  template< template< class ... > class PropertyType >
  void setDuringCreation()
  {
    PropertyType<int> prop(4);
    qi::AnyValue val = prop.value().value();
    ASSERT_EQ(4, val.to<int>());
  }

  template< template< class ... > class PropertyType >
  void signalOfProperty()
  {
    PropertyType<int> prop(4);
    qi::SignalSpy spy(prop);
    prop.setValue(2);
    std::this_thread::sleep_for(std::chrono::seconds{ 1 });
    qi::AnyValue val = prop.value().value();
    ASSERT_EQ(2, val.to<int>());
    ASSERT_EQ(1u, spy.recordCount());
  }

  template< template< class ... > class PropertyType >
  void keepValue()
  {
    PropertyType<int> k;
    k.set(42);
    EXPECT_EQ(42, k.get().value());
  }

  template< class T >
  struct Setter
  {
    qi::Promise<T> result;
    Setter(qi::Promise<T> result)
      : result(result)
    {}

    void operator()(const T& value)
    {
      result.setValue(value);
    }
  };

  template< template< class ... > class PropertyType >
  void dispatchValue()
  {
    PropertyType<int> k;
    qi::Promise<int> object;
    k.connect(Setter<int>(object));
    k.set(42);
    qi::Future<int> result = object.future();
    EXPECT_EQ(42, result.value());
    EXPECT_EQ(42, k.get().value());
  }

  template< template< class ... > class PropertyType >
  void dispatchAssignedValue()
  {
    PropertyType<int> k;
    qi::Promise<int> object;
    k.connect(Setter<int>(object));
    k = 42;
    qi::Future<int> result = object.future();
    EXPECT_EQ(42, result.value());
    EXPECT_EQ(42, k.get().value());
  }

  template< template< class ... > class PropertyType >
  void asyncAccessors()
  {
    Promise<int> prom;
    const auto getter = [=](int val){ return val * 3; };
    PropertyType<int> prop(
      42,
      [=](const int&){
        return prom.future().andThen(getter);
      },
      [=](int&, const int& newValue) mutable {
        return async([=]() mutable {
          try
          {
            prom.setValue(newValue);
            return true;
          }
          catch(...)
          {
            return false;
          }
        });
      });

    // Still running until the set.
    auto getFut = prop.get();
    EXPECT_TRUE(test::isStillRunning(getFut));

    auto setFut = prop.set(15);
    EXPECT_TRUE(test::finishesWithValue(setFut));

    int getResult = 0;
    EXPECT_TRUE(test::finishesWithValue(getFut, test::willAssignValue(getResult)));
    EXPECT_EQ(getter(15), getResult);
  }
}

TEST(TestPropertyIsNowhereDefined, EmptyBoostFunction)
{
  boost::function<void()> func;
  EXPECT_TRUE(qi::details_property::isNowhereDefined(func));
}

TEST(TestPropertyIsNowhereDefined, NonEmptyBoostFunction)
{
  boost::function<void()> func = []{ /* does nothing */ };
  EXPECT_FALSE(qi::details_property::isNowhereDefined(func));
}

TEST(TestPropertyIsNowhereDefined, EmptyStdFunction)
{
  std::function<void()> func;
  EXPECT_TRUE(qi::details_property::isNowhereDefined(func));
}

TEST(TestPropertyIsNowhereDefined, NonEmptyStdFunction)
{
  std::function<void()> func = []{ /* does nothing */ };
  EXPECT_FALSE(qi::details_property::isNowhereDefined(func));
}

namespace
{
  void doesNothing() {}
}

TEST(TestPropertyIsNowhereDefined, NullFunctionPtr)
{
  EXPECT_TRUE(qi::details_property::isNowhereDefined(nullptr));
}

TEST(TestPropertyIsNowhereDefined, FunctionPtr)
{
  EXPECT_FALSE(qi::details_property::isNowhereDefined(&doesNothing));
}

TEST(TestPropertyIsNowhereDefined, Lambda)
{
  const auto func = []{ /* does nothing */ };
  EXPECT_FALSE(qi::details_property::isNowhereDefined(func));
}

TEST(TestPropertyIsNowhereDefined, FunctionObject)
{
  const auto func = ka::constant_function();
  EXPECT_FALSE(qi::details_property::isNowhereDefined(func));
}

TEST(TestUnsafeProperty, SetDuringCreation)
{
  test::setDuringCreation<qi::UnsafeProperty>();
}

TEST(TestUnsafeProperty, SignalOfProperty)
{
  test::signalOfProperty<qi::UnsafeProperty>();
}

TEST(TestUnsafeProperty, keepValue)
{
  test::keepValue<qi::UnsafeProperty>();
}

TEST(TestUnsafeProperty, dispatchValue)
{
  test::dispatchValue<qi::UnsafeProperty>();
}

TEST(TestUnsafeProperty, dispatchAssignedValue)
{
  test::dispatchAssignedValue<qi::UnsafeProperty>();
}

TEST(TestUnsafeProperty, WithAsyncAccessors)
{
  test::asyncAccessors<qi::UnsafeProperty>();
}

TEST(TestProperty, SetDuringCreation)
{
  test::setDuringCreation<qi::Property>();
}

TEST(TestProperty, SignalOfProperty)
{
  test::signalOfProperty<qi::Property>();
}

TEST(TestProperty, keepValue)
{
  test::keepValue<qi::Property>();
}

TEST(TestProperty, dispatchValue)
{
  test::dispatchValue<qi::Property>();
}

TEST(TestProperty, dispatchAssignedValue)
{
  test::dispatchAssignedValue<qi::Property>();
}

TEST(TestProperty, WithAsyncAccessors)
{
  test::asyncAccessors<qi::Property>();
}

TEST(TestProperty, customSetter)
{
  qi::Property<int> property{12, qi::Property<int>::Getter{}, [](int& storage, const int& value)
  {
    storage = value;
    return true;
  }};
  const int expected = 42;
  property.set(expected);
  EXPECT_EQ(expected, property.get().value());
}

TEST(TestProperty, customSetterStranded)
{
  const auto strand = std::make_shared<qi::Strand>();
  std::weak_ptr<qi::Strand> weakStrand = strand;
  qi::Property<int> property{ 12, qi::Property<int>::Getter{},
                              [=](int& storage, const int& value) {
                                if (auto strand = weakStrand.lock())
                                  return strand->async([&] {
                                    storage = value;
                                    return true;
                                  }).value();
                                return false;
                              } };
  const int expected = 42;
  property.set(expected);
  EXPECT_EQ(expected, property.get().value());
}

TEST(TestProperty, customSetterReturningFalseFailsButDoesNotThrow)
{
  const int initialValue = 12;
  qi::Property<int> property{initialValue, qi::Property<int>::Getter{}, [](int&, const int&)
  {
    return false;
  }};
  const int newValue = 42;
  property.set(newValue);
  EXPECT_EQ(initialValue, property.get().value());
}

using CustomException = std::exception;

TEST(TestProperty, customSetterThrowIsTransmitted)
{
  const int initialValue = 12;
  qi::Property<int> property{initialValue, qi::Property<int>::Getter{}, [](int&, const int&)->bool
  {
    throw CustomException{};
  }};
  const int newValue = 42;
  ASSERT_THROW(property.set(newValue), CustomException);
  EXPECT_EQ(initialValue, property.get().value());
}

TEST(TestProperty, WithStrandCallsGetterSetterFromIt)
{
  qi::Strand strand;
  qi::Property<int> property{ 42, strand,
                              [&](const int& v) {
                                EXPECT_TRUE(strand.isInThisContext());
                                return v;
                              },
                              [&](int& val, int newVal) {
                                EXPECT_TRUE(strand.isInThisContext());
                                val = newVal;
                                return true;
                              } };
  auto newVal = 13;
  EXPECT_NO_THROW(property.set(newVal).value());
  EXPECT_EQ(newVal, property.get().value());

  newVal = 8392;
  EXPECT_NO_THROW(property.set(newVal).value());
  EXPECT_EQ(newVal, property.get().value());
}

using Containers = testing::Types<
  std::array<int, 2>,
  std::vector<int>,
  std::deque<int>,
  std::forward_list<int>,
  std::list<int>,
  std::set<int>,
  std::map<int, int>,
  std::multiset<int>,
  std::multimap<int, int>,
  std::unordered_set<int>,
  std::unordered_map<int, int>,
  std::stack<int>,
  std::queue<int>,
  std::priority_queue<int>,
  boost::container::flat_map<int, int>,
  boost::container::flat_set<int>,
  boost::container::static_vector<int, 2>,
  boost::container::small_vector<int, 2>,
  boost::container::stable_vector<int>
>;

template<typename T>
struct TestPropertyWithContainerType : testing::Test {};
TYPED_TEST_SUITE(TestPropertyWithContainerType, Containers);

TYPED_TEST(TestPropertyWithContainerType, CanBeInstanciatedWithContainer)
{
  qi::Property<TypeParam> p;
  SUCCEED();
}

TEST(TestReadOnlyProperty, Get)
{
  Property<int> source{ 42 };
  ReadOnlyProperty<int> prop{ source };
  EXPECT_EQ(42, prop.get().value());
  EXPECT_EQ(42, prop.value().value().to<int>());
}

TEST(TestReadOnlyProperty, SetThroughAdaptedProperty)
{
  Property<int> source{ 42 };
  ReadOnlyProperty<int> prop{ source };
  EXPECT_EQ(42, prop.get().value());
  source.set(51).value();
  EXPECT_EQ(51, prop.get().value());
}

struct ObjectWithProperty
{
  ObjectWithProperty()
    : prop(AnyReference::from(0),
           [&](int v){ return getter.Call(v); },
           [&](int& v, int nv) { return setter.Call(v, nv); })
  {
  }

  testing::MockFunction<Future<int>(int)> getter;
  testing::MockFunction<Future<bool>(int&, int)> setter;
  Property<int> prop;
};

QI_REGISTER_OBJECT(ObjectWithProperty, prop)

TEST(TestProxyProperty, CallsSourceGetter)
{
  using namespace testing;
  auto* const objectImpl = new ObjectWithProperty;
  Object<ObjectWithProperty> object(objectImpl);
  ProxyProperty<int> proxyProp(object, "prop");

  EXPECT_CALL(objectImpl->getter, Call(0)).WillOnce(Return(futurize(42)));
  const auto futRes = proxyProp.get();
  ASSERT_TRUE(test::finishesWithValue(futRes));
  EXPECT_EQ(42, futRes.value());
}

TEST(TestProxyProperty, CallsSourceSetter)
{
  using namespace testing;
  auto* const objectImpl = new ObjectWithProperty;
  Object<ObjectWithProperty> object(objectImpl);
  ProxyProperty<int> proxyProp(object, "prop");

  EXPECT_CALL(objectImpl->setter, Call(_, _))
    .WillOnce(DoAll(Invoke([](int& v, int nv){ v = nv; }), Return(futurize(true))));
  const auto futSet = object->prop.setValue(32);
  ASSERT_TRUE(test::finishesWithValue(futSet));

  auto refToIntEqualTo32 = SafeMatcherCast<int&>(Eq(32));
  EXPECT_CALL(objectImpl->setter, Call(refToIntEqualTo32, 12))
    .WillOnce(Return(futurize(true)));
  const auto futRes = proxyProp.set(12);
  ASSERT_TRUE(test::finishesWithValue(futRes));
}

ext: cpp

max_stars_repo_name: Maelic/libqi

max_issues_repo_name: Maelic/libqi

max_forks_repo_name: Maelic/libqi


text:
#include "../../algorithms/graph_compressor.hpp"
#include "../../data_structures/compressed_edge_container.hpp"
#include "../../data_structures/restriction_map.hpp"
#include "../../data_structures/node_based_graph.hpp"
#include "../../extractor/speed_profile.hpp"
#include "../../typedefs.h"

#include <boost/test/unit_test.hpp>
#include <boost/test/test_case_template.hpp>

#include <iostream>

BOOST_AUTO_TEST_SUITE(graph_compressor)

BOOST_AUTO_TEST_CASE(long_road_test)
{
    //
    // 0---1---2---3---4
    //
    SpeedProfileProperties speed_profile;
    GraphCompressor compressor(speed_profile);

    std::unordered_set<NodeID> barrier_nodes;
    std::unordered_set<NodeID> traffic_lights;
    RestrictionMap map;
    CompressedEdgeContainer container;

    using InputEdge = NodeBasedDynamicGraph::InputEdge;
    std::vector<InputEdge> edges = {
        // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, travel_mode
        {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {3, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {3, 4, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {4, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT}
    };

    BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[2].data));
    BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[4].data));
    BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[6].data));

    NodeBasedDynamicGraph graph(5, edges);
    compressor.Compress(barrier_nodes, traffic_lights, map, graph, container);

    BOOST_CHECK_EQUAL(graph.FindEdge(0, 1), SPECIAL_EDGEID);
    BOOST_CHECK_EQUAL(graph.FindEdge(1, 2), SPECIAL_EDGEID);
    BOOST_CHECK_EQUAL(graph.FindEdge(2, 3), SPECIAL_EDGEID);
    BOOST_CHECK_EQUAL(graph.FindEdge(3, 4), SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(0, 4) != SPECIAL_EDGEID);
}

BOOST_AUTO_TEST_CASE(loop_test)
{
    //
    // 0---1---2
    // |       |
    // 5---4---3
    //
    SpeedProfileProperties speed_profile;
    GraphCompressor compressor(speed_profile);

    std::unordered_set<NodeID> barrier_nodes;
    std::unordered_set<NodeID> traffic_lights;
    RestrictionMap map;
    CompressedEdgeContainer container;

    using InputEdge = NodeBasedDynamicGraph::InputEdge;
    std::vector<InputEdge> edges = {
        // source, target, distance, edge_id, name_id, access_restricted, forward, backward, roundabout, travel_mode
        {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {0, 5, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {3, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {3, 4, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {4, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {4, 5, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {5, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {5, 4, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
    };

    BOOST_ASSERT(edges.size() == 12);
    BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[1].data));
    BOOST_ASSERT(edges[1].data.IsCompatibleTo(edges[2].data));
    BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[3].data));
    BOOST_ASSERT(edges[3].data.IsCompatibleTo(edges[4].data));
    BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[5].data));
    BOOST_ASSERT(edges[5].data.IsCompatibleTo(edges[6].data));
    BOOST_ASSERT(edges[6].data.IsCompatibleTo(edges[7].data));
    BOOST_ASSERT(edges[7].data.IsCompatibleTo(edges[8].data));
    BOOST_ASSERT(edges[8].data.IsCompatibleTo(edges[9].data));
    BOOST_ASSERT(edges[9].data.IsCompatibleTo(edges[10].data));
    BOOST_ASSERT(edges[10].data.IsCompatibleTo(edges[11].data));

    NodeBasedDynamicGraph graph(6, edges);
    compressor.Compress(barrier_nodes, traffic_lights, map, graph, container);

    BOOST_CHECK_EQUAL(graph.FindEdge(5, 0), SPECIAL_EDGEID);
    BOOST_CHECK_EQUAL(graph.FindEdge(0, 1), SPECIAL_EDGEID);
    BOOST_CHECK_EQUAL(graph.FindEdge(1, 2), SPECIAL_EDGEID);
    BOOST_CHECK_EQUAL(graph.FindEdge(2, 3), SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(5, 3) != SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(3, 4) != SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(4, 5) != SPECIAL_EDGEID);
}

BOOST_AUTO_TEST_CASE(t_intersection)
{
    //
    // 0---1---2
    //     |
    //     3
    //
    SpeedProfileProperties speed_profile;
    GraphCompressor compressor(speed_profile);

    std::unordered_set<NodeID> barrier_nodes;
    std::unordered_set<NodeID> traffic_lights;
    RestrictionMap map;
    CompressedEdgeContainer container;

    using InputEdge = NodeBasedDynamicGraph::InputEdge;
    std::vector<InputEdge> edges = {
        // source, target, distance, edge_id, name_id, access_restricted, reversed, roundabout, travel_mode
        {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 3, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {3, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
    };

    BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[1].data));
    BOOST_ASSERT(edges[1].data.IsCompatibleTo(edges[2].data));
    BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[3].data));
    BOOST_ASSERT(edges[3].data.IsCompatibleTo(edges[4].data));
    BOOST_ASSERT(edges[4].data.IsCompatibleTo(edges[5].data));

    NodeBasedDynamicGraph graph(4, edges);
    compressor.Compress(barrier_nodes, traffic_lights, map, graph, container);

    BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(1, 2) != SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(1, 3) != SPECIAL_EDGEID);
}

BOOST_AUTO_TEST_CASE(street_name_changes)
{
    //
    // 0---1---2
    //
    SpeedProfileProperties speed_profile;
    GraphCompressor compressor(speed_profile);

    std::unordered_set<NodeID> barrier_nodes;
    std::unordered_set<NodeID> traffic_lights;
    RestrictionMap map;
    CompressedEdgeContainer container;

    using InputEdge = NodeBasedDynamicGraph::InputEdge;
    std::vector<InputEdge> edges = {
        // source, target, distance, edge_id, name_id, access_restricted, forward, backward, roundabout, travel_mode
        {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 0, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 2, 1, SPECIAL_EDGEID, 1, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 1, 1, SPECIAL_EDGEID, 1, false, false, false, true, TRAVEL_MODE_DEFAULT},
    };

    BOOST_ASSERT(edges[0].data.IsCompatibleTo(edges[1].data));
    BOOST_ASSERT(edges[2].data.IsCompatibleTo(edges[3].data));

    NodeBasedDynamicGraph graph(5, edges);
    compressor.Compress(barrier_nodes, traffic_lights, map, graph, container);

    BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(1, 2) != SPECIAL_EDGEID);
}

BOOST_AUTO_TEST_CASE(direction_changes)
{
    //
    // 0-->1---2
    //
    SpeedProfileProperties speed_profile;
    GraphCompressor compressor(speed_profile);

    std::unordered_set<NodeID> barrier_nodes;
    std::unordered_set<NodeID> traffic_lights;
    RestrictionMap map;
    CompressedEdgeContainer container;

    using InputEdge = NodeBasedDynamicGraph::InputEdge;
    std::vector<InputEdge> edges = {
        // source, target, distance, edge_id, name_id, access_restricted, reverse, roundabout, travel_mode
        {0, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {1, 0, 1, SPECIAL_EDGEID, 0, false, true,  false, true, TRAVEL_MODE_DEFAULT},
        {1, 2, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
        {2, 1, 1, SPECIAL_EDGEID, 0, false, false, false, true, TRAVEL_MODE_DEFAULT},
    };

    NodeBasedDynamicGraph graph(5, edges);
    compressor.Compress(barrier_nodes, traffic_lights, map, graph, container);

    BOOST_CHECK(graph.FindEdge(0, 1) != SPECIAL_EDGEID);
    BOOST_CHECK(graph.FindEdge(1, 2) != SPECIAL_EDGEID);
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: aaronbenz/osrm-backend

max_issues_repo_name: aaronbenz/osrm-backend

max_forks_repo_name: aaronbenz/osrm-backend


text:
//
// Copyright (c) 2019 INRIA
//

#include "pinocchio/autodiff/casadi.hpp"

#include "pinocchio/algorithm/kinematics.hpp"
#include "pinocchio/algorithm/frames.hpp"
#include "pinocchio/algorithm/jacobian.hpp"
#include "pinocchio/algorithm/crba.hpp"
#include "pinocchio/algorithm/rnea.hpp"
#include "pinocchio/algorithm/aba.hpp"
#include "pinocchio/algorithm/joint-configuration.hpp"

#include "pinocchio/parsers/sample-models.hpp"

#include <boost/test/unit_test.hpp>
#include <boost/utility/binary.hpp>

BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)

BOOST_AUTO_TEST_CASE(test_jacobian)
{
  typedef double Scalar;
  typedef casadi::SX ADScalar;

  typedef pinocchio::ModelTpl<Scalar> Model;
  typedef Model::Data Data;

  typedef pinocchio::ModelTpl<ADScalar> ADModel;
  typedef ADModel::Data ADData;

  Model model;
  pinocchio::buildModels::humanoidRandom(model);
  model.lowerPositionLimit.head<3>().fill(-1.);
  model.upperPositionLimit.head<3>().fill(1.);
  Data data(model);

  typedef Model::ConfigVectorType ConfigVector;
  typedef Model::TangentVectorType TangentVector;
  ConfigVector q(model.nq);
  q = pinocchio::randomConfiguration(model);
  TangentVector v(TangentVector::Random(model.nv));

  typedef ADModel::ConfigVectorType ConfigVectorAD;
  typedef ADModel::TangentVectorType TangentVectorAD;
  ADModel ad_model = model.cast<ADScalar>();
  ADData ad_data(ad_model);

  Model::Index joint_id = model.existJointName("rarm2")?model.getJointId("rarm2"):(Model::Index)(model.njoints-1);
  Data::Matrix6x jacobian_local(6,model.nv), jacobian_world(6,model.nv);
  jacobian_local.setZero(); jacobian_world.setZero();

  BOOST_CHECK(jacobian_local.isZero() && jacobian_world.isZero());

  pinocchio::computeJointJacobians(model,data,q);
  pinocchio::getJointJacobian(model,data,joint_id,pinocchio::WORLD,jacobian_world);
  pinocchio::getJointJacobian(model,data,joint_id,pinocchio::LOCAL,jacobian_local);

  casadi::SX cs_q = casadi::SX::sym("q", model.nq);
  ConfigVectorAD q_ad(model.nq);
  for(Eigen::DenseIndex k = 0; k < model.nq; ++k)
  {
    q_ad[k] = cs_q(k);
  }
  std::cout << "q =\n " << q_ad << std::endl;

  casadi::SX cs_v = casadi::SX::sym("v", model.nv);
  TangentVectorAD v_ad(model.nv);
  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)
  {
    v_ad[k] = cs_v(k);
  }
  std::cout << "v =\n " << v_ad << std::endl;

  pinocchio::forwardKinematics(ad_model, ad_data, q_ad, v_ad);
  typedef pinocchio::MotionTpl<ADScalar> MotionAD;
  MotionAD & v_local = ad_data.v[(size_t)joint_id];
  MotionAD v_world = ad_data.oMi[(size_t)joint_id].act(v_local);

  casadi::SX cs_v_local(6,1), cs_v_world(6,1);
  for(Eigen::DenseIndex k = 0; k < 6; ++k)
  {
    cs_v_local(k) = v_local.toVector()[k];
    cs_v_world(k) = v_world.toVector()[k];
  }
  std::cout << "v_local = " << cs_v_local << std::endl;
  std::cout << "v_world = " << cs_v_world << std::endl;

  casadi::Function eval_velocity_local("eval_velocity_local",
                                       casadi::SXVector {cs_q, cs_v},
                                       casadi::SXVector {cs_v_local});
  std::cout << "eval_velocity_local = " << eval_velocity_local << std::endl;

  casadi::Function eval_velocity_world("eval_velocity_world",
                                       casadi::SXVector {cs_q, cs_v},
                                       casadi::SXVector {cs_v_world});
  std::cout << "eval_velocity_world = " << eval_velocity_world << std::endl;

  casadi::SX dv_dv_local = jacobian(cs_v_local, cs_v);
  casadi::Function eval_jacobian_local("eval_jacobian_local",
                                       casadi::SXVector {cs_q,cs_v},
                                       casadi::SXVector {dv_dv_local});
  std::cout << "eval_jacobian_local = " << eval_jacobian_local << std::endl;

  casadi::SX dv_dv_world = jacobian(cs_v_world, cs_v);
  casadi::Function eval_jacobian_world("eval_jacobian_world",
                                       casadi::SXVector {cs_q,cs_v},
                                       casadi::SXVector {dv_dv_world});

  std::vector<double> q_vec((size_t)model.nq);
  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;

  std::vector<double> v_vec((size_t)model.nv);
  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;

  casadi::DMVector v_local_res = eval_velocity_local(casadi::DMVector {q_vec,v_vec});
  casadi::DMVector J_local_res = eval_jacobian_local(casadi::DMVector {q_vec,v_vec});
  std::cout << "J_local_res:" << J_local_res << std::endl;

  std::vector<double> v_local_vec(static_cast< std::vector<double> >(v_local_res[0]));
  BOOST_CHECK((jacobian_local*v).isApprox(Eigen::Map<pinocchio::Motion::Vector6>(v_local_vec.data())));

  casadi::DMVector v_world_res = eval_velocity_world(casadi::DMVector {q_vec,v_vec});
  casadi::DMVector J_world_res = eval_jacobian_world(casadi::DMVector {q_vec,v_vec});

  std::vector<double> v_world_vec(static_cast< std::vector<double> >(v_world_res[0]));
  BOOST_CHECK((jacobian_world*v).isApprox(Eigen::Map<pinocchio::Motion::Vector6>(v_world_vec.data())));

  Data::Matrix6x J_local_mat(6,model.nv), J_world_mat(6,model.nv);

  std::vector<double> J_local_vec(static_cast< std::vector<double> >(J_local_res[0]));
  J_local_mat = Eigen::Map<Data::Matrix6x>(J_local_vec.data(),6,model.nv);
  BOOST_CHECK(jacobian_local.isApprox(J_local_mat));

  std::vector<double> J_world_vec(static_cast< std::vector<double> >(J_world_res[0]));
  J_world_mat = Eigen::Map<Data::Matrix6x>(J_world_vec.data(),6,model.nv);
  BOOST_CHECK(jacobian_world.isApprox(J_world_mat));
}

  BOOST_AUTO_TEST_CASE(test_fk)
  {
    typedef double Scalar;
    typedef casadi::SX ADScalar;

    typedef pinocchio::ModelTpl<Scalar> Model;
    typedef Model::Data Data;

    typedef pinocchio::ModelTpl<ADScalar> ADModel;
    typedef ADModel::Data ADData;

    Model model;
    pinocchio::buildModels::humanoidRandom(model);
    model.lowerPositionLimit.head<3>().fill(-1.);
    model.upperPositionLimit.head<3>().fill(1.);
    Data data(model);

    typedef Model::ConfigVectorType ConfigVector;
    typedef Model::TangentVectorType TangentVector;
    ConfigVector q(model.nq);
    q = pinocchio::randomConfiguration(model);
    TangentVector v(TangentVector::Random(model.nv));
    TangentVector a(TangentVector::Random(model.nv));

    pinocchio::forwardKinematics(model,data,q);

    typedef ADModel::ConfigVectorType ConfigVectorAD;
    typedef ADModel::TangentVectorType TangentVectorAD;
    ADModel ad_model = model.cast<ADScalar>();
    ADData ad_data(ad_model);

    casadi::SX cs_q = casadi::SX::sym("q", model.nq);
    ConfigVectorAD q_ad(model.nq);
    pinocchio::casadi::copy(cs_q,q_ad);

    casadi::SX cs_v = casadi::SX::sym("v", model.nv);
    TangentVectorAD v_ad(model.nv);
    pinocchio::casadi::copy(cs_v,v_ad);

    casadi::SX cs_a = casadi::SX::sym("a", model.nv);
    TangentVectorAD a_ad(model.nv);
    pinocchio::casadi::copy(cs_a,a_ad);

    pinocchio::forwardKinematics(ad_model, ad_data, q_ad, v_ad, a_ad);
    pinocchio::updateGlobalPlacements(ad_model, ad_data);
    pinocchio::updateFramePlacements(ad_model, ad_data);
//    typedef pinocchio::MotionTpl<ADScalar> MotionAD;
  }

BOOST_AUTO_TEST_CASE(test_rnea)
{
  typedef double Scalar;
  typedef casadi::SX ADScalar;

  typedef pinocchio::ModelTpl<Scalar> Model;
  typedef Model::Data Data;

  typedef pinocchio::ModelTpl<ADScalar> ADModel;
  typedef ADModel::Data ADData;

  Model model;
  pinocchio::buildModels::humanoidRandom(model);
  model.lowerPositionLimit.head<3>().fill(-1.);
  model.upperPositionLimit.head<3>().fill(1.);
  Data data(model);

  typedef Model::ConfigVectorType ConfigVector;
  typedef Model::TangentVectorType TangentVector;
  ConfigVector q(model.nq);
  q = pinocchio::randomConfiguration(model);
  TangentVector v(TangentVector::Random(model.nv));
  TangentVector a(TangentVector::Random(model.nv));

  typedef ADModel::ConfigVectorType ConfigVectorAD;
  typedef ADModel::TangentVectorType TangentVectorAD;
  ADModel ad_model = model.cast<ADScalar>();
  ADData ad_data(ad_model);

  pinocchio::rnea(model,data,q,v,a);

  casadi::SX cs_q = casadi::SX::sym("q", model.nq);
  ConfigVectorAD q_ad(model.nq);
  q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);

  casadi::SX cs_v = casadi::SX::sym("v", model.nv);
  TangentVectorAD v_ad(model.nv);
  v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);

  casadi::SX cs_a = casadi::SX::sym("a", model.nv);
  TangentVectorAD a_ad(model.nv);
  a_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_a).data(),model.nv,1);

  rnea(ad_model,ad_data,q_ad,v_ad,a_ad);
  casadi::SX tau_ad(model.nv,1);
  //    Eigen::Map<TangentVectorAD>(tau_ad->data(),model.nv,1)
  //    = ad_data.tau;
  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)
    tau_ad(k) = ad_data.tau[k];
  casadi::Function eval_rnea("eval_rnea",
                             casadi::SXVector {cs_q, cs_v, cs_a},
                             casadi::SXVector {tau_ad});

  std::vector<double> q_vec((size_t)model.nq);
  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;

  std::vector<double> v_vec((size_t)model.nv);
  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;

  std::vector<double> a_vec((size_t)model.nv);
  Eigen::Map<TangentVector>(a_vec.data(),model.nv,1) = a;
  casadi::DM tau_res = eval_rnea(casadi::DMVector {q_vec,v_vec,a_vec})[0];
  std::cout << "tau_res = " << tau_res << std::endl;
  Data::TangentVectorType tau_vec = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(tau_res).data(),model.nv,1);

  BOOST_CHECK(data.tau.isApprox(tau_vec));
}

BOOST_AUTO_TEST_CASE(test_crba)
{
  typedef double Scalar;
  typedef casadi::SX ADScalar;

  typedef pinocchio::ModelTpl<Scalar> Model;
  typedef Model::Data Data;

  typedef pinocchio::ModelTpl<ADScalar> ADModel;
  typedef ADModel::Data ADData;

  Model model;
  pinocchio::buildModels::humanoidRandom(model);
  model.lowerPositionLimit.head<3>().fill(-1.);
  model.upperPositionLimit.head<3>().fill(1.);
  Data data(model);

  typedef Model::ConfigVectorType ConfigVector;
  typedef Model::TangentVectorType TangentVector;
  ConfigVector q(model.nq);
  q = pinocchio::randomConfiguration(model);
  TangentVector v(TangentVector::Random(model.nv));
  TangentVector a(TangentVector::Random(model.nv));

  typedef ADModel::ConfigVectorType ConfigVectorAD;
  typedef ADModel::TangentVectorType TangentVectorAD;
  ADModel ad_model = model.cast<ADScalar>();
  ADData ad_data(ad_model);

  pinocchio::crba(model,data,q);
  data.M.triangularView<Eigen::StrictlyLower>()
  = data.M.transpose().triangularView<Eigen::StrictlyLower>();
  pinocchio::rnea(model,data,q,v,a);

  casadi::SX cs_q = casadi::SX::sym("q", model.nq);
  ConfigVectorAD q_ad(model.nq);
  q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);

  casadi::SX cs_v = casadi::SX::sym("v", model.nv);
  TangentVectorAD v_ad(model.nv);
  v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);

  casadi::SX cs_a = casadi::SX::sym("a", model.nv);
  TangentVectorAD a_ad(model.nv);
  a_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_a).data(),model.nv,1);

  // RNEA
  rnea(ad_model,ad_data,q_ad,v_ad,a_ad);
  casadi::SX cs_tau(model.nv,1);
  //    Eigen::Map<TangentVectorAD>(tau_ad->data(),model.nv,1)
  //    = ad_data.tau;
  for(Eigen::DenseIndex k = 0; k < model.nv; ++k)
    cs_tau(k) = ad_data.tau[k];
  casadi::Function eval_rnea("eval_rnea",
                             casadi::SXVector {cs_q, cs_v, cs_a},
                             casadi::SXVector {cs_tau});
  // CRBA
  crba(ad_model,ad_data,q_ad);
  ad_data.M.triangularView<Eigen::StrictlyLower>()
  = ad_data.M.transpose().triangularView<Eigen::StrictlyLower>();
  casadi::SX M_ad(model.nv,model.nv);
  for(Eigen::DenseIndex j = 0; j < model.nv; ++j)
  {
    for(Eigen::DenseIndex i = 0; i < model.nv; ++i)
    {
      M_ad(i,j) = ad_data.M(i,j);
    }
  }

  std::vector<double> q_vec((size_t)model.nq);
  Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;

  std::vector<double> v_vec((size_t)model.nv);
  Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;

  std::vector<double> a_vec((size_t)model.nv);
  Eigen::Map<TangentVector>(a_vec.data(),model.nv,1) = a;

  casadi::Function eval_crba("eval_crba",
                             casadi::SXVector {cs_q},
                             casadi::SXVector {M_ad});
  casadi::DM M_res = eval_crba(casadi::DMVector {q_vec})[0];
  Data::MatrixXs M_mat = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(M_res).data(),
                                                    model.nv,model.nv);

  BOOST_CHECK(data.M.isApprox(M_mat));

  casadi::SX dtau_da = jacobian(cs_tau,cs_a);
  casadi::Function eval_dtau_da("eval_dtau_da",
                                casadi::SXVector {cs_q,cs_v,cs_a},
                                casadi::SXVector {dtau_da});
  casadi::DM dtau_da_res = eval_dtau_da(casadi::DMVector {q_vec, v_vec, a_vec})[0];
  Data::MatrixXs dtau_da_mat = Eigen::Map<Data::MatrixXs>(static_cast< std::vector<double> >(dtau_da_res).data(),
                                                          model.nv,model.nv);
  BOOST_CHECK(data.M.isApprox(dtau_da_mat));
}

  BOOST_AUTO_TEST_CASE(test_aba)
  {
    typedef double Scalar;
    typedef casadi::SX ADScalar;

    typedef pinocchio::ModelTpl<Scalar> Model;
    typedef Model::Data Data;

    typedef pinocchio::ModelTpl<ADScalar> ADModel;
    typedef ADModel::Data ADData;

    Model model;
    pinocchio::buildModels::humanoidRandom(model);
    model.lowerPositionLimit.head<3>().fill(-1.);
    model.upperPositionLimit.head<3>().fill(1.);
    Data data(model);

    typedef Model::ConfigVectorType ConfigVector;
    typedef Model::TangentVectorType TangentVector;
    ConfigVector q(model.nq);
    q = pinocchio::randomConfiguration(model);
    TangentVector v(TangentVector::Random(model.nv));
    TangentVector tau(TangentVector::Random(model.nv));

    typedef ADModel::ConfigVectorType ConfigVectorAD;
    typedef ADModel::TangentVectorType TangentVectorAD;
    ADModel ad_model = model.cast<ADScalar>();
    ADData ad_data(ad_model);

    pinocchio::aba(model,data,q,v,tau);

    casadi::SX cs_q = casadi::SX::sym("q", model.nq);
    ConfigVectorAD q_ad(model.nq);
    q_ad = Eigen::Map<ConfigVectorAD>(static_cast< std::vector<ADScalar> >(cs_q).data(),model.nq,1);

    casadi::SX cs_v = casadi::SX::sym("v", model.nv);
    TangentVectorAD v_ad(model.nv);
    v_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_v).data(),model.nv,1);

    casadi::SX cs_tau = casadi::SX::sym("tau", model.nv);
    TangentVectorAD tau_ad(model.nv);
    tau_ad = Eigen::Map<TangentVectorAD>(static_cast< std::vector<ADScalar> >(cs_tau).data(),model.nv,1);

    // ABA
    aba(ad_model,ad_data,q_ad,v_ad,tau_ad);
    casadi::SX cs_ddq(model.nv,1);
    for(Eigen::DenseIndex k = 0; k < model.nv; ++k)
      cs_ddq(k) = ad_data.ddq[k];
    casadi::Function eval_aba("eval_aba",
                              casadi::SXVector {cs_q, cs_v, cs_tau},
                              casadi::SXVector {cs_ddq});

    std::vector<double> q_vec((size_t)model.nq);
    Eigen::Map<ConfigVector>(q_vec.data(),model.nq,1) = q;

    std::vector<double> v_vec((size_t)model.nv);
    Eigen::Map<TangentVector>(v_vec.data(),model.nv,1) = v;

    std::vector<double> tau_vec((size_t)model.nv);
    Eigen::Map<TangentVector>(tau_vec.data(),model.nv,1) = tau;

    casadi::DM ddq_res = eval_aba(casadi::DMVector {q_vec, v_vec, tau_vec})[0];
    Data::TangentVectorType ddq_mat = Eigen::Map<Data::TangentVectorType>(static_cast< std::vector<double> >(ddq_res).data(),
                                                            model.nv,1);

    BOOST_CHECK(ddq_mat.isApprox(data.ddq));
  }

BOOST_AUTO_TEST_SUITE_END()


text:
//
// Copyright (c) 2013-2017 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// 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 BEAST_WEBSOCKET_DETAIL_DEBUG_HPP
#define BEAST_WEBSOCKET_DETAIL_DEBUG_HPP

#include <boost/asio/buffer.hpp>
#include <iomanip>
#include <sstream>
#include <string>

namespace beast {
namespace websocket {
namespace detail {

template<class = void>
std::string
to_hex(boost::asio::const_buffer b)
{
    using namespace boost::asio;
    std::stringstream ss;
    auto p = buffer_cast<std::uint8_t const*>(b);
    auto n = buffer_size(b);
    while(n--)
    {
        ss <<
            std::setfill('0') <<
            std::setw(2) <<
            std::hex << int(*p++) << " ";
    }
    return ss.str();
}

template<class Buffers>
std::string
to_hex(Buffers const& bs)
{
    std::string s;
    for(auto const& b : bs)
        s.append(to_hex(boost::asio::const_buffer(b)));
    return s;
}

template<class Buffers>
std::string
buffers_to_string(Buffers const& bs)
{
    using namespace boost::asio;
    std::string s;
    s.reserve(buffer_size(bs));
    for(auto const& b : bs)
        s.append(buffer_cast<char const*>(b),
            buffer_size(b));
    return s;
}

template<class = void>
std::string
format(std::string s)
{
    auto const w = 84;
    for(int n = w*(s.size()/w); n>0; n-=w)
        s.insert(n, 1, '\n');
    return s;
}

} // detail
} // websocket
} // beast

#endif

ext: hpp

max_stars_repo_name: MassICTBV/casinocoind

max_issues_repo_name: MassICTBV/casinocoind

max_forks_repo_name: MassICTBV/casinocoind


text:
//
// Copyright (C) 2011-2017 Denis V Chapligin, Martin Hrabovsky
// 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 <iostream>

#define BOOST_TEST_MODULE "STLCacheInsertPerformance"
#include <boost/test/unit_test.hpp>
#include <iostream>

#ifdef _WIN32
#include "timeval.h"
#else
#include <sys/time.h>
#endif /* _WIN32 */

#include <stlcache/stlcache.hpp>

using namespace std;
using namespace stlcache;

BOOST_AUTO_TEST_SUITE(STLCacheSuite)

const unsigned int noItems = 65536;

BOOST_AUTO_TEST_CASE(insertNone) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_none> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_none cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertLRU) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_lru> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_lru cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertMRU) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_mru> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_mru cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertLFU) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_lfu> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_lfu cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertLFUMulti) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_lfu_multi> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_lfu_multi cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertLFUStar) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_lfustar> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_lfustar cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertLFUAging) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_lfuaging<3600> > c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_lfuaging cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertLFUAgingStar) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_lfuagingstar<3600> > c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_lfuagingstar cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_CASE(insertAdaptive) {
    struct timeval start,stop;

    gettimeofday(&start, NULL);

    cache<unsigned int,unsigned int,policy_adaptive> c(noItems);
    for(unsigned int indx = 0; indx<noItems; indx++) {
        c.insert(indx,indx);
    }

    gettimeofday(&stop, NULL);

    std::cout<<"Insertion of "<<noItems<<" items into policy_adaptive cache took "<<((stop.tv_sec-start.tv_sec)*1000)+((stop.tv_usec-start.tv_usec)/1000)<<" milliseconds"<<endl;
}

BOOST_AUTO_TEST_SUITE_END();

max_stars_repo_name: ueberaccelerate/stlcache

max_issues_repo_name: ueberaccelerate/stlcache

max_forks_repo_name: ueberaccelerate/stlcache


text:
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#ifndef _MSC_VER
    #define BOOST_TEST_DYN_LINK
#endif

#include <sstream>

#include <boost/test/unit_test.hpp>

#include "ignite/impl/utils.h"
#include "ignite/cache/cache.h"
#include "ignite/cache/query/query_cursor.h"
#include "ignite/cache/query/query_sql.h"
#include "ignite/cache/query/query_text.h"
#include "ignite/ignite.h"
#include "ignite/ignition.h"

using namespace boost::unit_test;

using namespace ignite;
using namespace ignite::cache;
using namespace ignite::cache::query;
using namespace ignite::impl::utils;

/**
 * Person class for query tests.
 */
class IGNITE_IMPORT_EXPORT QueryPerson
{
public:
    /**
     * Constructor.
     */
    QueryPerson() : name(NULL), age(0)
    {
        // No-op.
    }

    /**
     * Constructor.
     *
     * @param name Name.
     * @param age Age.
     */
    QueryPerson(std::string name, int age) : name(CopyChars(name.c_str())), age(age)
    {
        // No-op.
    }

    /**
     * Copy constructor.
     *
     * @param other Other instance.
     */
    QueryPerson(const QueryPerson& other)
    {
        name = CopyChars(other.name);
        age = other.age;
    }

    /**
     * Assignment operator.
     *
     * @param other Other instance.
     * @return This instance.
     */
    QueryPerson& operator=(const QueryPerson& other)
    {
        if (&other != this)
        {
            QueryPerson tmp(other);

            char* name0 = name;
            int age0 = age;

            name = tmp.name;
            age = tmp.age;

            tmp.name = name0;
            tmp.age = age0;
        }

        return *this;
    }

    /**
     * Destructor.
     */
    ~QueryPerson()
    {
        ReleaseChars(name);
    }

    /**
     * Get name.
     *
     * @return Name.
     */
    std::string GetName()
    {
        return name ? std::string(name) : std::string();
    }

    /**
     * Get age.
     *
     * @return Age.
     */
    int32_t GetAge()
    {
        return age;
    }

private:
    /** Name. */
    char* name;

    /** Age. */
    int age;
};

namespace ignite
{
    namespace portable
    {
        /**
         * Portable type definition.
         */
        IGNITE_PORTABLE_TYPE_START(QueryPerson)
            IGNITE_PORTABLE_GET_TYPE_ID_AS_HASH(QueryPerson)
            IGNITE_PORTABLE_GET_TYPE_NAME_AS_IS(QueryPerson)
            IGNITE_PORTABLE_GET_FIELD_ID_AS_HASH
            IGNITE_PORTABLE_GET_HASH_CODE_ZERO(QueryPerson)
            IGNITE_PORTABLE_IS_NULL_FALSE(QueryPerson)
            IGNITE_PORTABLE_GET_NULL_DEFAULT_CTOR(QueryPerson)

            void Write(PortableWriter& writer, QueryPerson obj)
            {
                writer.WriteString("name", obj.GetName());
                writer.WriteInt32("age", obj.GetAge());
            }

            QueryPerson Read(PortableReader& reader)
            {
                std::string name = reader.ReadString("name");
                int age = reader.ReadInt32("age");

                return QueryPerson(name, age);
            }

        IGNITE_PORTABLE_TYPE_END
    }
}

/** Node started during the test. */
Ignite grid = Ignite();

/** Cache accessor. */
Cache<int, QueryPerson> GetCache()
{
    return grid.GetCache<int, QueryPerson>("cache");
}

/**
 * Test setup fixture.
 */
struct CacheQueryTestSuiteFixture {
    /**
     * Constructor.
     */
    CacheQueryTestSuiteFixture()
    {
        IgniteConfiguration cfg;

        IgniteJvmOption opts[5];

        opts[0] = IgniteJvmOption("-Xdebug");
        opts[1] = IgniteJvmOption("-Xnoagent");
        opts[2] = IgniteJvmOption("-Djava.compiler=NONE");
        opts[3] = IgniteJvmOption("-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=5005");
        opts[4] = IgniteJvmOption("-XX:+HeapDumpOnOutOfMemoryError");

        cfg.jvmOptsLen = 5;
        cfg.jvmOpts = opts;

        cfg.jvmInitMem = 1024;
        cfg.jvmMaxMem = 4096;

        char* cfgPath = getenv("IGNITE_NATIVE_TEST_CPP_CONFIG_PATH");

        std::string cfgPathStr = std::string(cfgPath).append("/").append("cache-query.xml");

        cfg.springCfgPath = const_cast<char*>(cfgPathStr.c_str());

        IgniteError err;

        Ignite grid0 = Ignition::Start(cfg, &err);

        if (err.GetCode() != IgniteError::IGNITE_SUCCESS)
            BOOST_ERROR(err.GetText());

        grid = grid0;
    }

    /**
     * Destructor.
     */
    ~CacheQueryTestSuiteFixture()
    {
        Ignition::Stop(grid.GetName(), true);
    }
};

/**
 * Ensure that HasNext() fails.
 *
 * @param cur Cursor.
 */
void CheckHasNextFail(QueryCursor<int, QueryPerson>& cur)
{
    try
    {
        cur.HasNext();

        BOOST_FAIL("Must fail.");
    }
    catch (IgniteError& err)
    {
        BOOST_REQUIRE(err.GetCode() == IgniteError::IGNITE_ERR_GENERIC);
    }
}

/**
 * Ensure that GetNext() fails.
 *
 * @param cur Cursor.
 */
void CheckGetNextFail(QueryCursor<int, QueryPerson>& cur)
{
    try
    {
        cur.GetNext();

        BOOST_FAIL("Must fail.");
    }
    catch (IgniteError& err)
    {
        BOOST_REQUIRE(err.GetCode() == IgniteError::IGNITE_ERR_GENERIC);
    }
}

/**
 * Ensure that GetAll() fails.
 *
 * @param cur Cursor.
 */
void CheckGetAllFail(QueryCursor<int, QueryPerson>& cur)
{
    try
    {
        std::vector<CacheEntry<int, QueryPerson>> res;

        cur.GetAll(res);

        BOOST_FAIL("Must fail.");
    }
    catch (IgniteError& err)
    {
        BOOST_REQUIRE(err.GetCode() == IgniteError::IGNITE_ERR_GENERIC);
    }
}

/**
 * Check empty result through iteration.
 *
 * @param cur Cursor.
 */
void CheckEmpty(QueryCursor<int, QueryPerson>& cur)
{
    BOOST_REQUIRE(!cur.HasNext());

    CheckGetNextFail(cur);
    CheckGetAllFail(cur);
}

/**
 * Check empty result through GetAll().
 *
 * @param cur Cursor.
 */
void CheckEmptyGetAll(QueryCursor<int, QueryPerson>& cur)
{
    std::vector<CacheEntry<int, QueryPerson>> res;

    cur.GetAll(res);

    BOOST_REQUIRE(res.size() == 0);

    CheckHasNextFail(cur);
    CheckGetNextFail(cur);
}

/**
 * Check single result through iteration.
 *
 * @param cur Cursor.
 * @param key1 Key.
 * @param name1 Name.
 * @param age1 Age.
 */
void CheckSingle(QueryCursor<int, QueryPerson>& cur, int key, std::string name, int age)
{
    BOOST_REQUIRE(cur.HasNext());

    CheckGetAllFail(cur);

    CacheEntry<int, QueryPerson> entry = cur.GetNext();

    CheckGetAllFail(cur);

    BOOST_REQUIRE(entry.GetKey() == key);
    BOOST_REQUIRE(entry.GetValue().GetName().compare(name) == 0);
    BOOST_REQUIRE(entry.GetValue().GetAge() == age);

    BOOST_REQUIRE(!cur.HasNext());

    CheckGetNextFail(cur);
    CheckGetAllFail(cur);
}

/**
 * Check single result through GetAll().
 *
 * @param cur Cursor.
 * @param key1 Key.
 * @param name1 Name.
 * @param age1 Age.
 */
void CheckSingleGetAll(QueryCursor<int, QueryPerson>& cur, int key, std::string name, int age)
{
    std::vector<CacheEntry<int, QueryPerson>> res;

    cur.GetAll(res);

    CheckHasNextFail(cur);
    CheckGetNextFail(cur);
    CheckGetAllFail(cur);

    BOOST_REQUIRE(res.size() == 1);

    BOOST_REQUIRE(res[0].GetKey() == 1);
    BOOST_REQUIRE(res[0].GetValue().GetName().compare(name) == 0);
    BOOST_REQUIRE(res[0].GetValue().GetAge() == age);

    CheckHasNextFail(cur);
    CheckGetNextFail(cur);
    CheckGetAllFail(cur);
}

/**
 * Check multiple results through iteration.
 *
 * @param cur Cursor.
 * @param key1 Key 1.
 * @param name1 Name 1.
 * @param age1 Age 1.
 * @param key2 Key 2.
 * @param name2 Name 2.
 * @param age2 Age 2.
 */
void CheckMultiple(QueryCursor<int, QueryPerson>& cur, int key1, std::string name1,
    int age1, int key2, std::string name2, int age2)
{
    for (int i = 0; i < 2; i++)
    {
        BOOST_REQUIRE(cur.HasNext());

        CheckGetAllFail(cur);

        CacheEntry<int, QueryPerson> entry = cur.GetNext();

        CheckGetAllFail(cur);

        if (entry.GetKey() == key1)
        {
            BOOST_REQUIRE(entry.GetValue().GetName().compare(name1) == 0);
            BOOST_REQUIRE(entry.GetValue().GetAge() == age1);
        }
        else if (entry.GetKey() == key2)
        {
            BOOST_REQUIRE(entry.GetValue().GetName().compare(name2) == 0);
            BOOST_REQUIRE(entry.GetValue().GetAge() == age2);
        }
        else
            BOOST_FAIL("Unexpected entry.");
    }

    BOOST_REQUIRE(!cur.HasNext());

    CheckGetNextFail(cur);
    CheckGetAllFail(cur);
}

/**
 * Check multiple results through GetAll().
 *
 * @param cur Cursor.
 * @param key1 Key 1.
 * @param name1 Name 1.
 * @param age1 Age 1.
 * @param key2 Key 2.
 * @param name2 Name 2.
 * @param age2 Age 2.
 */
void CheckMultipleGetAll(QueryCursor<int, QueryPerson>& cur, int key1, std::string name1, int age1,
    int key2, std::string name2, int age2)
{
    std::vector<CacheEntry<int, QueryPerson>> res;

    cur.GetAll(res);

    CheckHasNextFail(cur);
    CheckGetNextFail(cur);
    CheckGetAllFail(cur);

    BOOST_REQUIRE(res.size() == 2);

    for (int i = 0; i < 2; i++)
    {
        CacheEntry<int, QueryPerson> entry = res[i];

        if (entry.GetKey() == key1)
        {
            BOOST_REQUIRE(entry.GetValue().GetName().compare(name1) == 0);
            BOOST_REQUIRE(entry.GetValue().GetAge() == age1);
        }
        else if (entry.GetKey() == key2)
        {
            BOOST_REQUIRE(entry.GetValue().GetName().compare(name2) == 0);
            BOOST_REQUIRE(entry.GetValue().GetAge() == age2);
        }
        else
            BOOST_FAIL("Unexpected entry.");
    }
}

BOOST_FIXTURE_TEST_SUITE(CacheQueryTestSuite, CacheQueryTestSuiteFixture)

/**
 * Test SQL query.
 */
BOOST_AUTO_TEST_CASE(TestSqlQuery)
{
    Cache<int, QueryPerson> cache = GetCache();

    // Test query with no results.
    SqlQuery qry("QueryPerson", "age < 20");

    QueryCursor<int, QueryPerson> cursor = cache.Query(qry);
    CheckEmpty(cursor);

    cursor = cache.Query(qry);
    CheckEmptyGetAll(cursor);

    // Test simple query.
    cache.Put(1, QueryPerson("A1", 10));
    cache.Put(2, QueryPerson("A2", 20));

    cursor = cache.Query(qry);
    CheckSingle(cursor, 1, "A1", 10);

    cursor = cache.Query(qry);
    CheckSingleGetAll(cursor, 1, "A1", 10);

    // Test simple local query.
    qry.SetLocal(true);

    cursor = cache.Query(qry);
    CheckSingle(cursor, 1, "A1", 10);

    cursor = cache.Query(qry);
    CheckSingleGetAll(cursor, 1, "A1", 10);

    // Test query with arguments.
    qry.SetSql("age < ? AND name = ?");
    qry.AddArgument<int>(20);
    qry.AddArgument<std::string>("A1");

    cursor = cache.Query(qry);
    CheckSingle(cursor, 1, "A1", 10);

    cursor = cache.Query(qry);
    CheckSingleGetAll(cursor, 1, "A1", 10);

    // Test query returning multiple entries.
    qry = SqlQuery("QueryPerson", "age < 30");

    cursor = cache.Query(qry);
    CheckMultiple(cursor, 1, "A1", 10, 2, "A2", 20);

    cursor = cache.Query(qry);
    CheckMultipleGetAll(cursor, 1, "A1", 10, 2, "A2", 20);
}

/**
 * Test text query.
 */
BOOST_AUTO_TEST_CASE(TestTextQuery)
{
    Cache<int, QueryPerson> cache = GetCache();

    // Test query with no results.
    TextQuery qry("QueryPerson", "A1");

    QueryCursor<int, QueryPerson> cursor = cache.Query(qry);
    CheckEmpty(cursor);

    cursor = cache.Query(qry);
    CheckEmptyGetAll(cursor);

    // Test simple query.
    cache.Put(1, QueryPerson("A1", 10));
    cache.Put(2, QueryPerson("A2", 20));

    cursor = cache.Query(qry);
    CheckSingle(cursor, 1, "A1", 10);

    cursor = cache.Query(qry);
    CheckSingleGetAll(cursor, 1, "A1", 10);

    // Test simple local query.
    qry.SetLocal(true);

    cursor = cache.Query(qry);
    CheckSingle(cursor, 1, "A1", 10);

    cursor = cache.Query(qry);
    CheckSingleGetAll(cursor, 1, "A1", 10);

    // Test query returning multiple entries.
    qry = TextQuery("QueryPerson", "A*");

    cursor = cache.Query(qry);
    CheckMultiple(cursor, 1, "A1", 10, 2, "A2", 20);

    cursor = cache.Query(qry);
    CheckMultipleGetAll(cursor, 1, "A1", 10, 2, "A2", 20);
}

/**
 * Test scan query.
 */
BOOST_AUTO_TEST_CASE(TestScanQuery)
{
    // Test simple query.
    Cache<int, QueryPerson> cache = GetCache();

    // Test query with no results.
    ScanQuery qry;

    QueryCursor<int, QueryPerson> cursor = cache.Query(qry);
    CheckEmpty(cursor);

    cursor = cache.Query(qry);
    CheckEmptyGetAll(cursor);

    // Test simple query.
    cache.Put(1, QueryPerson("A1", 10));

    cursor = cache.Query(qry);
    CheckSingle(cursor, 1, "A1", 10);

    cursor = cache.Query(qry);
    CheckSingleGetAll(cursor, 1, "A1", 10);

    // Test query returning multiple entries.
    cache.Put(2, QueryPerson("A2", 20));

    cursor = cache.Query(qry);
    CheckMultiple(cursor, 1, "A1", 10, 2, "A2", 20);

    cursor = cache.Query(qry);
    CheckMultipleGetAll(cursor, 1, "A1", 10, 2, "A2", 20);
}

/**
 * Test scan query over partitions.
 */
BOOST_AUTO_TEST_CASE(TestScanQueryPartitioned)
{
    // Populate cache with data.
    Cache<int, QueryPerson> cache = GetCache();

    int32_t partCnt = 256;   // Defined in configuration explicitly.
    int32_t entryCnt = 1000; // Should be greater than partCnt.

    for (int i = 0; i < entryCnt; i++)
    {
        std::stringstream stream;

        stream << "A" << i;

        cache.Put(i, QueryPerson(stream.str(), i * 10));
    }

    // Iterate over all partitions and collect data.
    std::set<int> keys;

    for (int i = 0; i < partCnt; i++)
    {
        ScanQuery qry(i);

        QueryCursor<int, QueryPerson> cur = cache.Query(qry);

        while (cur.HasNext())
        {
            CacheEntry<int, QueryPerson> entry = cur.GetNext();

            int key = entry.GetKey();

            keys.insert(key);

            std::stringstream stream;
            stream << "A" << key;
            BOOST_REQUIRE(entry.GetValue().GetName().compare(stream.str()) == 0);

            BOOST_REQUIRE(entry.GetValue().GetAge() == key * 10);
        }
    }

    // Ensure that all keys were read.
    BOOST_REQUIRE(keys.size() == entryCnt);
}

BOOST_AUTO_TEST_SUITE_END()


text: #include <boost/compute/lambda.hpp>

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <boost/ut.hpp>
#include <iostream>
#include <pqrs/dispatcher.hpp>

namespace {
class when_hardware_time_source_test final : public pqrs::dispatcher::extra::dispatcher_client {
public:
  when_hardware_time_source_test(std::weak_ptr<pqrs::dispatcher::dispatcher> weak_dispatcher,
                                 size_t& count,
                                 pqrs::dispatcher::duration duration) : dispatcher_client(weak_dispatcher) {
    enqueue_to_dispatcher(
        [&count] {
          std::cout << "." << std::flush;
          ++count;
        },
        when_now() + duration);
  }

  virtual ~when_hardware_time_source_test(void) {
    detach_from_dispatcher([] {
    });
  }
};
} // namespace

void run_hardware_time_source_test(void) {
  using namespace boost::ut;
  using namespace boost::ut::literals;

  "dispatcher.when_hardware_time_source"_test = [] {
    std::cout << "dispatcher.when_hardware_time_source" << std::endl;

    auto time_source = std::make_shared<pqrs::dispatcher::hardware_time_source>();

    {
      size_t count = 0;

      {
        auto d = std::make_shared<pqrs::dispatcher::dispatcher>(time_source);

        std::vector<std::unique_ptr<when_hardware_time_source_test>> objects;
        for (int i = 0; i < 10; ++i) {
          objects.push_back(std::make_unique<when_hardware_time_source_test>(
              d,
              count,
              std::chrono::milliseconds(i * 100)));
        }

        std::this_thread::sleep_for(std::chrono::milliseconds(500));

        expect(count > 2);
        expect(count < 8);

        d->terminate();

        std::cout << std::endl;
      }
    }
  };
}

max_stars_repo_name: tekezo/dispatcher

max_issues_repo_name: tekezo/dispatcher

max_forks_repo_name: tekezo/dispatcher


text:
// 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.

#undef MTL_ASSERT_FOR_THROW // Don't wont to abort program when one solver fail

#include <boost/numeric/mtl/mtl.hpp>
#include <boost/numeric/itl/itl.hpp>

// #include <boost/test/minimal.hpp>

#define MTL_RUN_SOLVER( name, solver, args)				\
    {									\
	std::cout << "\n\n" << name << "\n";				\
	xs= 0.01;							\
        int codes= 0;							\
        itl::cyclic_iteration<double> iters(bs, 150, 1.e-4, 0.0, 10);     \
        try {								\
	    codes= solver args;						\
	} catch (const itl::unexpected_orthogonality&) {		\
	    std::cerr << "Unexpected_Orthogonality in solver!\n";	\
	}								\
        if (codes != 0) {						\
	    std::cerr << "Solver doesn't converge!!!\n";		\
	    failed++;							\
        } else								\
	    succeed++;							\
    }

int main(int, char**)
{
    // For a more realistic example set size to 1000 or larger
    const int size = 4, N = size * size;
    int       succeed= 0, failed= 0;

    typedef mtl::compressed2D<double>  matrix_s_type;
    matrix_s_type                                           As(N, N);
    laplacian_setup(As, size, size);
    mtl::dense_vector<double>                               xs(N, 1.0), bs(N);
    bs= As * xs;
    itl::pc::identity<matrix_s_type>                        I(As);
    itl::pc::ic_0<matrix_s_type>                            IC(As);
    itl::pc::ilu_0<matrix_s_type>                           ILU(As);
    const unsigned                                          ell= 6, restart= 8, s= ell;

    MTL_RUN_SOLVER("Bi-Conjugate Gradient", bicg, (As, xs, bs, I, iters));
    MTL_RUN_SOLVER("Bi-Conjugate Gradient Stabilized", bicgstab, (As, xs, bs, ILU, iters));
    MTL_RUN_SOLVER("Bi-Conjugate Gradient Stabilized(2)", bicgstab_2, (As, xs, bs, ILU, iters));
    MTL_RUN_SOLVER("Bi-Conjugate Gradient Stabilized(ell)", bicgstab_ell, (As, xs, bs, ILU, I, iters, ell));
    MTL_RUN_SOLVER("Conjugate Gradient", cg, (As, xs, bs, IC, iters));
    MTL_RUN_SOLVER("Conjugate Gradient Squared", cgs, (As, xs, bs, ILU, iters));
//     MTL_RUN_SOLVER("Generalized Minimal Residual method (without restart)", gmres_full, (As, xs, bs, I, I, iters, size));  //only N iterations
    MTL_RUN_SOLVER("Generalized Minimal Residual method with restart", gmres, (As, xs, bs, I, I, iters, restart));
    MTL_RUN_SOLVER("Induced Dimension Reduction on s dimensions (IDR(s))", idr_s, (As, xs, bs, ILU, I, iters, s));
    MTL_RUN_SOLVER("Quasi-minimal residual", qmr, (As, xs, bs, ILU, I, iters));
    MTL_RUN_SOLVER("Transposed-free Quasi-minimal residual", tfqmr, (As, xs, bs, ILU, I, iters));
    std::cout << succeed << " solvers succeeded and " << failed << " solvers failed.\n";

    return 0;
}


text:
//  GetCurrentThread.hpp  --------------------------------------------------------------//

//  Copyright 2010 Vicente J. Botet Escriba

//  Distributed under the Boost Software License, Version 1.0.
//  See http://www.boost.org/LICENSE_1_0.txt

#ifndef BOOST_DETAIL_WIN_GETCURRENTTHREAD_HPP
#define BOOST_DETAIL_WIN_GETCURRENTTHREAD_HPP

#include <boost/detail/win/basic_types.hpp>

namespace boost {
namespace detail {
namespace win32 {
#if defined( UNDER_CE )
// Windows CE define GetCurrentThread as an inline function in kfuncs.h
inline HANDLE_ GetCurrentThread()
{
  return ::GetCurrentThread();
}
#else
#if defined( BOOST_USE_WINDOWS_H )
    using ::GetCurrentThread;
#else
    extern "C" __declspec(dllimport) HANDLE_ WINAPI GetCurrentThread();
#endif
#endif
}
}
}

#endif // BOOST_DETAIL_WIN_TIME_HPP

max_stars_repo_name: PXLVision/opengv

max_issues_repo_name: isuhao/klib

max_forks_repo_name: isuhao/klib


text:
#ifndef _jsc_util_interval_hpp_included_
#define _jsc_util_interval_hpp_included_

#include <boost/config.hpp>

#include <math.h>

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

#include <boost/lambda/bind.hpp>
#include <boost/lambda/lambda.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/tokenizer.hpp>

#include <jsc/util/log.hpp>

using namespace std;
using namespace boost;
using namespace boost::lambda;

namespace jsc
{
namespace util
{

//! A function which checks whether two intervals overlap.
/*!
 * \return whether [a, b) and [c, d) overlap.
 */
template<class T, class Compare>
bool interval_overlap(T const & a, T const & b, T const & c, T const & d, Compare comp = Compare())
{
	return (!(comp(b, c) || comp(d, a)));
}

//! A function which computes the overlapping length of two intervals.
/*!
 * \return the overlapping length of [a, b) and [c, d).
 */
template<class T, class Compare>
double compute_interval_overlap(T const & a, T const & b, T const & c, T const & d, Compare comp = Compare())
{
	double length = 0;
	if (!(comp(b, c) || comp(d, a)))
	{
		if (comp(a, c))
		{
			if (comp(b, d))
			{
				length = b - c;
			}
			else
			{
				length = d - c;
			}
		}
		else
		{
			if (comp(b, d))
			{
				length = b - a;
			}
			else
			{
				length = d - a;
			}
		}
	}
	return length;
}

//! A class representing a list of intervals.
/*!
 * The intervals in the list are sorted according to their start positions and do not overlap with each other.
 */
template <class T, class Compare = less<T> >
class interval_list
{
private:
	//! The comparator.
	Compare comp;
	//! The internal representation of the list of intervals: [starts[0], end[0]), [starts[1], end[1]), ...
	vector<T> starts;
	//! The internal representation of the list of intervals: [starts[0], end[0]), [starts[1], end[1]), ...
	vector<T> ends;

public:
	//! A constructor.
	interval_list()
		: comp(Compare())
	{
	}

	//! A constructor taking an explicit comparator.
	explicit
	interval_list(Compare const & c)
		: comp(c)
	{
	}

	//! Copy constructor.
	interval_list(interval_list<T, Compare> const & il)
		: comp(il.comp), starts(il.starts), ends(il.ends)
	{
	}

	//! Gets the number of intervals.
	unsigned long get_num_intervals() const
	{
		return starts.size();
	}

	//! Gets the starts vector.
	vector<T> const & get_starts() const
	{
		return starts;
	}

	//! Gets the ends vector.
	vector<T> const & get_ends() const
	{
		return ends;
	}

	//! Counts the number of intervals in the list that overlap with the given interval.
	/*!
	 * \sa count_overlap_il().
	 */
	long count_overlap(T const & start, T const & end) const
	{
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return 0;	// always return 0 in this case
		}

		typename vector<T>::const_iterator s_starts_itr, e_ends_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);
		e_ends_itr = lower_bound(ends.begin(), ends.end(), end);

		long s_starts_idx, e_ends_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		e_ends_idx = distance(ends.begin(), e_ends_itr);
		long i;
		long total_count = 0;
		for (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)
		{
			if (interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp))
			{
				total_count++;
			}
		}

		return total_count;
	}

	//! Counts the number of intervals in the list that overlap with the given interval list.
	/*!
	 * \sa count_overlap().
	 */
	long count_overlap_il(interval_list<T, Compare> const & il) const
	{
		long total_count = 0;
		int n = starts.size();

		for (int i = 0; i < n; ++i)
		{
			if (il.check_overlap(starts[i], ends[i]))
			{
				total_count++;
			}
		}
		return total_count;
	}

	//! Checks whether the interval list overlaps with the interval [start, end).
	bool check_overlap(T const & start, T const & end) const
	{
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return false;	// always return false in this case
		}

		typename vector<T>::const_iterator s_starts_itr, e_ends_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);
		e_ends_itr = lower_bound(ends.begin(), ends.end(), end);

		long s_starts_idx, e_ends_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		e_ends_idx = distance(ends.begin(), e_ends_itr);
		long i;
		for (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)
		{
			if (interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp))
			{
				return true;
			}
		}

		return false;
	}

	static interval_list<T> get_interval_overlap(T const & a, T const & b, T const & c, T const & d, Compare comp = Compare())
	{
		interval_list<T> il;
		if (!(comp(b, c) || comp(d, a)))
		{
			if (comp(a, c))
			{
				if (comp(b, d))
				{
					il.add_interval(c, b);
				}
				else
				{
					il.add_interval(c, d);
				}
			}
			else
			{
				if (comp(b, d))
				{
					il.add_interval(a, b);
				}
				else
				{
					il.add_interval(a, d);
				}
			}
		}
		return il;
	}

	//! Gets the overlap of the interval list with the interval [start, end).
	interval_list<T> get_overlap_il(T const & start, T const & end) const
	{
		interval_list<T> il;
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return il;	// always return 0 in this case
		}

		typename vector<T>::const_iterator s_starts_itr, e_ends_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);
		e_ends_itr = lower_bound(ends.begin(), ends.end(), end);

		long s_starts_idx, e_ends_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		e_ends_idx = distance(ends.begin(), e_ends_itr);
		long i;
		for (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)
		{
			il.add_interval_list(
					get_interval_overlap(starts[i], ends[i], start, end, comp));
		}

		return il;
	}

	//! Get the overlap of the interval list with another interval list.
	interval_list<T> get_overlap_il(interval_list<T, Compare> const & il) const
	{
		interval_list<T> rst_il;
		int n = il.starts.size();
		for (int i = 0; i < n; i++)
		{
			rst_il.add_interval_list(get_overlap_il(il.starts[i], il.ends[i]));
		}
		return rst_il;
	}

	//! Computes the overlap of the interval list with the interval [start, end).
	/*!
	 * \sa compute_overlap_il().
	 */
	double compute_overlap(T const & start, T const & end) const
	{
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return 0;	// always return 0 in this case
		}

		typename vector<T>::const_iterator s_starts_itr, e_ends_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);
		e_ends_itr = lower_bound(ends.begin(), ends.end(), end);

		long s_starts_idx, e_ends_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		e_ends_idx = distance(ends.begin(), e_ends_itr);
		long i;
		double total_length = 0;
		for (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)
		{
			total_length += compute_interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp);
		}

		return total_length;
	}

	bool check_single_overlap(T const & start, T const & end, double const & threshold) const
	{
		bool found = false;
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return false;	// always return false in this case
		}

		typename vector<T>::const_iterator s_starts_itr, e_ends_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);
		e_ends_itr = lower_bound(ends.begin(), ends.end(), end);

		long s_starts_idx, e_ends_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		e_ends_idx = distance(ends.begin(), e_ends_itr);
		long i;
		for (i = max((long)0, s_starts_idx - 1); i <= min((long)starts.size() - 1, e_ends_idx); ++i)
		{
			if (threshold <= compute_interval_overlap<T, Compare>(starts[i], ends[i], start, end, comp)) {
				found = true;
				break;
			}
		}

		return found;
	}

	//! Computes the overlap of the interval list with another interval list.
	/*!
	 * \sa compute_overlap().
	 */
	double compute_overlap_il(interval_list<T, Compare> const & il) const
	{
		double total_length = 0;
		int n = il.starts.size();
		for (int i = 0; i < n; i++)
		{
			total_length += compute_overlap(il.starts[i], il.ends[i]);
		}
		return total_length;
	}

	//! Computes the total length of the intervals in this interval list.
	double compute_total_length() const
	{
		double total_length = 0;
		int n = starts.size();
		for (int i = 0; i < n; i++)
		{
			total_length += ends[i] - starts[i];
		}
		return total_length;
	}

	//! Finds in the interval list the index of the interval which contains the given interval [start, end).
	/*!
	 * \return the index of the interval containing [start, end); otherwise starts.size().
	 * \sa contains_interval(T const & start, T const & end)
	 */
	long idx_containing_interval(T const & start, T const & end) const
	{
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return 0;	// always return 0 in this case
		}

		typename vector<T>::const_iterator s_starts_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);

		long s_starts_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		if (s_starts_idx >= 0 && s_starts_idx < (long)starts.size() &&
				!comp(start, starts[s_starts_idx]) &&
				!comp(ends[s_starts_idx], end))
		{
			return s_starts_idx;
		}
		if (s_starts_idx - 1 >= 0 && s_starts_idx - 1 < (long)starts.size() &&
				!comp(start, starts[s_starts_idx - 1]) &&
				!comp(ends[s_starts_idx - 1], end))
		{
			return s_starts_idx - 1;
		}

		return starts.size();
	}

	//! Checks whether the interval list contains [start, end).
	/*!
	 * \sa idx_containing_interval()
	 */
	bool contains_interval(T const & start, T const & end) const
	{
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return true;
		}

		typename vector<T>::const_iterator s_starts_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);

		long s_starts_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		if (s_starts_idx >= 0 && s_starts_idx < (long)starts.size() &&
				!comp(start, starts[s_starts_idx]) &&
				!comp(ends[s_starts_idx], end))
		{
			return true;
		}
		if (s_starts_idx - 1 >= 0 && s_starts_idx - 1 < (long)starts.size() &&
				!comp(start, starts[s_starts_idx - 1]) &&
				!comp(ends[s_starts_idx - 1], end))
		{
			return true;
		}

		return false;
	}

	//! Fill in gaps if their length is less than the given threshold
	void fill_in_gaps(double const & threshold)
	{
		int n = starts.size();
		if (n == 0)
		{
			return;
		}

		vector<T> new_starts, new_ends;
		T last_end;
		new_starts.push_back(starts[0]);
		last_end = ends[0];
		for (int i = 1; i < n; ++i)
		{
			if (starts[i] - last_end < threshold)
			{
				// fill in the gap
			}
			else
			{
				// copy the last end and current start
				new_ends.push_back(last_end);
				new_starts.push_back(starts[i]);
			}
			// update last end
			last_end = ends[i];
		}
		new_ends.push_back(last_end);
		starts = new_starts;
		ends = new_ends;
	}

	//! Add [start, end) to the interval list.
	/*!
	 * Overlapping intervals in the list will be merged.
	 * \sa add_starts_sizes() and add_interval_list()
	 */
	interval_list<T> & add_interval(T const & start, T const & end)
	{
		if (!comp(start, end))	/* [start, end) == nil */
		{
			return *this;
		}

		typename vector<T>::iterator s_starts_itr, s_ends_itr, e_starts_itr, e_ends_itr;
		s_starts_itr = lower_bound(starts.begin(), starts.end(), start);
		s_ends_itr = lower_bound(ends.begin(), ends.end(), start);
		e_starts_itr = lower_bound(starts.begin(), starts.end(), end);
		e_ends_itr = lower_bound(ends.begin(), ends.end(), end);

		int s_starts_idx, s_ends_idx, e_starts_idx, e_ends_idx;
		s_starts_idx = distance(starts.begin(), s_starts_itr);
		s_ends_idx = distance(ends.begin(), s_ends_itr);
		e_starts_idx = distance(starts.begin(), e_starts_itr);
		e_ends_idx = distance(ends.begin(), e_ends_itr);
		bool s_on_interval = (s_starts_idx - s_ends_idx == 1);
		bool e_on_interval = (e_starts_idx - e_ends_idx == 1);

		typename vector<T>::iterator starts_itr = starts.erase(s_starts_itr, e_starts_itr);
		typename vector<T>::iterator ends_itr = ends.erase(s_ends_itr, e_ends_itr);
		if (s_on_interval && e_on_interval)
		{
		}
		else if (!s_on_interval && !e_on_interval)
		{
			starts.insert(starts_itr, start);
			ends.insert(ends_itr, end);
		}
		else if (s_on_interval && !e_on_interval)
		{
			ends.insert(ends_itr, end);
		}
		else
		{
			starts.insert(starts_itr, start);
		}

		return *this;
	}

	//! Add another interval list to the interval list.
	/*!
	 * \sa add_starts_sizes() and add_interval()
	 */
	void add_interval_list(interval_list<T, Compare> const & il)
	{
		int n = il.starts.size();
		for (int i = 0; i < n; i++)
		{
			add_interval(il.starts[i], il.ends[i]);
		}
	}

	//! Add another interval list to the interval list.
	/*!
	 * \param starts the starts vector of the interval list to be added.
	 * \param sizes  the sizes vector of the interval list to be added.
	 * \sa add_interval_list() and add_interval()
	 */
	void add_starts_sizes(vector<T> const & starts, vector<T> const & sizes)
	{
		int n = starts.size();
		for (int i = 0; i < n; i++)
		{
			add_interval(starts[i], starts[i] + sizes[i]);
		}
	}

	//! Add another interval list to the interval list.
	/*!
	 * \param starts the starts vector of the interval list to be added.
	 * \param ends the ends vector of the interval list to be added.
	 * \sa add_interval_list() and add_interval()
	 */
	void add_starts_ends(vector<T> const & starts, vector<T> const & ends)
	{
		int n = starts.size();
		for (int i = 0; i < n; i++)
		{
			add_interval(starts[i], ends[i]);
		}
	}

	//! Checks whether the total coverage of the interval list overlaps with that of another interval list.
	/*!
	 * coverage = [min(starts), (max(ends))
	 */
	bool coverage_overlap(interval_list<T, Compare> const & il2)
	{
		int n1 = starts.size();
		int n2 = il2.starts.size();
		if (n1 == 0 || n2 == 0)
		{
			return false;
		}
		return interval_overlap<T, Compare>(starts[0], ends[n1 - 1], il2.starts[0], il2.ends[n2 - 1], comp);
	}

	T find_min_uncovered(T start_from) const {
		if (get_num_intervals() == 0) {
			return start_from;
		} else {
			typename vector<T>::const_iterator s_starts_itr;
			s_starts_itr = lower_bound(starts.begin(), starts.end(), start_from);

			long s_starts_idx;
			s_starts_idx = distance(starts.begin(), s_starts_itr);
			long i;
			for (i = max((long)0, (long)s_starts_idx - 1);
					i < (long)get_num_intervals(); ++i)
			{
				if (starts[i] > start_from) {
					return start_from;
				} else if (ends[i] > start_from) {
					start_from = ends[i];
				} else {
					continue;
				}
			}
			return start_from;
		}
	}
};

//! Default printing of an interval_list.
template<class T, class Compare>
ostream & operator << (ostream& os, interval_list<T, Compare> const & il)
{
	int n = il.get_starts().size();
	for (int i = 0; i < n; i++)
	{
		os << "[" << il.get_starts()[i] << "," << il.get_ends()[i] << "), ";
	}
	return os;
}

} /* end of util */

} /* end of jsc */

#endif

max_stars_repo_name: gersteinlab/LESSeq

max_issues_repo_name: gersteinlab/LESSeq

max_forks_repo_name: gersteinlab/LESSeq


text:
#ifndef LIBSTORE_IMPL_HDF5_HIGHFIVE_ARMA_H_
#define LIBSTORE_IMPL_HDF5_HIGHFIVE_ARMA_H_

#include <highfive/H5File.hpp>
#include <armadillo>

namespace HighFive {
namespace details {

//// Col<T>

template <typename T>
struct inspector<arma::Col<T>> {
    using type = arma::Col<T>;
    using value_type = T;
    using base_type = typename inspector<value_type>::base_type;

    static const size_t ndim = 2;
    static const size_t recursive_ndim = ndim + inspector<value_type>::recursive_ndim;

    static std::array<size_t, recursive_ndim> getDimensions(const type &val) {
        std::array<size_t, recursive_ndim> sizes{val.n_elem, 1};
        return sizes;
    }
};

template <typename T>
struct data_converter<arma::Col<T>>
    : public container_converter<arma::Col<T>> {

    using container_type = arma::Col<T>;
    using value_type = typename inspector<T>::base_type;

    inline data_converter(const DataSpace &space)
        : container_converter<container_type>(space), _space(space) {

        const std::vector<size_t> dims = _space.getDimensions();
        assert(dims.size() == 2);
        assert(dims[1] == 1);
    }

    inline value_type * transform_read(container_type &container) {
        const std::vector<size_t> dims = _space.getDimensions();
        container.set_size(dims[0]);
        return container.memptr();
    }

    inline const value_type * transform_write(const container_type &container) const noexcept {
        return container.memptr();
    }

    const DataSpace& _space;
};

//// Row<T>

template <typename T>
struct inspector<arma::Row<T>> {
    using type = arma::Row<T>;
    using value_type = T;
    using base_type = typename inspector<value_type>::base_type;

    static const size_t ndim = 2;
    static const size_t recursive_ndim = ndim + inspector<value_type>::recursive_ndim;

    static std::array<size_t, recursive_ndim> getDimensions(const type &val) {
        std::array<size_t, recursive_ndim> sizes{1, val.n_elem};
        return sizes;
    }
};

template <typename T>
struct data_converter<arma::Row<T>>
    : public container_converter<arma::Row<T>> {

    using container_type = arma::Row<T>;
    using value_type = typename inspector<T>::base_type;

    inline data_converter(const DataSpace &space)
        : container_converter<container_type>(space), _space(space) {

        const std::vector<size_t> dims = _space.getDimensions();
        assert(dims.size() == 2);
        assert(dims[0] == 1);
    }

    inline value_type * transform_read(container_type &container) {
        const std::vector<size_t> dims = _space.getDimensions();
        container.set_size(dims[1]);
        return container.memptr();
    }

    inline const value_type * transform_write(const container_type &container) const noexcept {
        return container.memptr();
    }

    const DataSpace& _space;
};

//// Mat<T>

template <typename T>
struct inspector<arma::Mat<T>> {
    using type = arma::Mat<T>;
    using value_type = T;
    using base_type = typename inspector<value_type>::base_type;

    static const size_t ndim = 2;
    static const size_t recursive_ndim = ndim + inspector<value_type>::recursive_ndim;

    static std::array<size_t, recursive_ndim> getDimensions(const type &val) {
        std::array<size_t, recursive_ndim> sizes{val.n_rows, val.n_cols};
        return sizes;
    }
};

template <typename T>
struct data_converter<arma::Mat<T>> {

    using container_type = arma::Mat<T>;
    using value_type = typename inspector<T>::base_type;

    inline data_converter(const DataSpace &space)
        : _space(space) {

        const std::vector<size_t> dims = _space.getDimensions();
        assert(dims.size() == 2);
    }

    inline value_type * transform_read(container_type &container) {
        const std::vector<size_t> dims = _space.getDimensions();
        container.set_size(dims[1], dims[0]);
        return container.memptr();
    }

    inline const value_type * transform_write(const container_type &container) noexcept {
        // This is to write out in row-major order and get the data to
        // live long enough.
        _container_st = container_type(container.st());
        return _container_st.memptr();
    }

    inline void process_result(container_type &container) {
        container = container_type(container.st());
    }

    const DataSpace& _space;
    container_type _container_st;
};

//// Cube<T>

template <typename T>
struct inspector<arma::Cube<T>> {
    using type = arma::Cube<T>;
    using value_type = T;
    using base_type = typename inspector<value_type>::base_type;

    static const size_t ndim = 3;
    static const size_t recursive_ndim = ndim + inspector<value_type>::recursive_ndim;

    static std::array<size_t, recursive_ndim> getDimensions(const type &val) {
        std::array<size_t, recursive_ndim> sizes{val.n_slices, val.n_rows, val.n_cols};
        return sizes;
    }
};

template <typename T>
struct data_converter<arma::Cube<T>> {

    using container_type = arma::Cube<T>;
    using value_type = typename inspector<T>::base_type;

    inline data_converter(const DataSpace &space)
        : _space(space) {

        const std::vector<size_t> dims = _space.getDimensions();
        assert(dims.size() == 3);
    }

    inline value_type * transform_read(container_type &container) {
        const std::vector<size_t> dims = _space.getDimensions();
        // The row/col dims need to be flipped here, but the actual data will
        // be flipped in process_result.  We can't do it here because the read
        // happens in row-major order.
        container.set_size(dims[2], dims[1], dims[0]);
        return container.memptr();
    }

    inline const value_type * transform_write(const container_type &container) noexcept {
        _buffer.resize(container.n_elem);
        size_t offset;
        for (size_t k = 0; k < container.n_slices; k++) {
            for (size_t j = 0; j < container.n_cols; j++) {
                for (size_t i = 0; i < container.n_rows; i++) {
                    // Transpose row and column indices
                    offset = j + (container.n_cols * i) + (container.n_rows * container.n_cols * k);
                    _buffer[offset] = container(i, j, k);
                }
            }
        }
        return _buffer.data();
    }

    inline void process_result(container_type &container) noexcept {
        arma::Cube<value_type> ret(container.n_cols, container.n_rows, container.n_slices);
        for (size_t k = 0; k < container.n_slices; k++) {
            ret.slice(k) = container.slice(k).st();
        }
        container = ret;
    }

    const DataSpace& _space;
    std::vector<value_type> _buffer;
};

} // end namespace details
} // end namespace HighFive

#endif // LIBSTORE_IMPL_HDF5_HIGHFIVE_ARMA_H_

max_stars_repo_name: berquist/eg

max_issues_repo_name: berquist/eg

max_forks_repo_name: berquist/eg


text:
#include <iostream>

#include <Eigen/Sparse>
#include <Eigen/Dense>

#include <unsupported/Eigen/SparseExtra> // For reading MatrixMarket files

#include <amgcl/backend/eigen.hpp>
#include <amgcl/make_solver.hpp>
#include <amgcl/solver/bicgstab.hpp>
#include <amgcl/amg.hpp>
#include <amgcl/coarsening/smoothed_aggregation.hpp>
#include <amgcl/relaxation/spai0.hpp>

int main(int argc, char *argv[]) {
    if (argc < 2) {
        std::cerr << "Usage: " << argv[0] << " <matrix.mm>" << std::endl;
        return 1;
    }

    // Read sparse matrix from MatrixMarket format.
    // In general this should come pre-assembled.
    Eigen::SparseMatrix<double, Eigen::RowMajor> A;
    Eigen::loadMarket(A, argv[1]);

    // Use vector of ones as RHS for simplicity:
    Eigen::VectorXd f = Eigen::VectorXd::Constant(A.rows(), 1.0);

    // Zero initial approximation:
    Eigen::VectorXd x = Eigen::VectorXd::Zero(A.rows());

    // Setup the solver:
    typedef amgcl::make_solver<
        amgcl::amg<
            amgcl::backend::eigen<double>,
            amgcl::coarsening::smoothed_aggregation,
            amgcl::relaxation::spai0
            >,
        amgcl::solver::bicgstab<amgcl::backend::eigen<double> >
        > Solver;

    Solver solve(A);
    std::cout << solve << std::endl;

    // Solve the system for the given RHS:
    int    iters;
    double error;
    std::tie(iters, error) = solve(f, x);

    std::cout << iters << " " << error << std::endl;
}


text:
#include <boost/bind.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>

#include "StdAfx.h"
#include "ServerConnection.h"

ServerConnection::ServerConnection(boost::asio::io_service& io_service)
	:Connection(io_service),
	m_tickTimer(io_service)
{
}

ServerConnection::~ServerConnection()
{

}

void ServerConnection::init(std::string ip, int port)
{
	m_ip	= ip;
	m_port	= port;

	this->setErrHandler(boost::bind(&ServerConnection::errHandler, this, boost::asio::placeholders::error, _2, _3));
	tryConnect();
	/*
	m_tickTimer.expires_from_now(boost::posix_time::seconds(CONNECT_INTERVAL));
	m_tickTimer.async_wait(boost::bind(&ServerConnection::tick, this, boost::asio::placeholders::error));*/
}

void ServerConnection::update()
{
	switch(m_status)
	{
	//case CONN_STATUS_INIT:
	//	break;
	////case CONN_STATUS_CONNECTING:
	////	// wait
	////	break;
	//case CONN_STATUS_CONNECTED:
	//	// handle command
	//	handlePacket();
	//	break;
	//case CONN_STATUS_DISCONNECT:
	//	{
	//		tryConnect();
	//	}
	//	break;
	}
}

void ServerConnection::connectHandler(const boost::system::error_code& e)
{
	if(!e)
	{
		LOGNORMAL() << "connect " << m_ip.c_str() << " " << m_port << " OK" << LOGEND();
		//m_status = CONN_STATUS_CONNECTED;
		start();
		// send handshake message

		// trigger read
		//tryRead();

	}
	else
	{
		m_status = CONN_STATUS_DISCONNECT;
		LOGERROR() << "connect error " << m_ip.c_str() << " " << m_port << LOGEND();
		tryConnect();
	}
}

void ServerConnection::tick(const boost::system::error_code& e)
{
	//if(boost::asio::error::operation_aborted != e)
	//{
	//	if (CONN_STATUS_DISCONNECT == m_status)
	//	{
	//		tryConnect();
	//		m_tickTimer.expires_at(m_tickTimer.expires_at()+boost::posix_time::seconds(CONNECT_INTERVAL));
	//		m_tickTimer.async_wait(boost::bind(&ServerConnection::tick, this, boost::asio::placeholders::error));
	//	}
	//	else if (CONN_STATUS_CONNECTED == m_status)
	//	{
	//		//// send msg hear beat
	//		//OPSSHeartBeat msg;
	//		//sendMsg(&msg);

	//		//LOGNORMAL() << "send ss heartbeat " << m_ip << " " << m_port << LOGEND();
	//		m_tickTimer.expires_at(m_tickTimer.expires_at()+boost::posix_time::seconds(HEARTBEAT_INTERVAL));
	//		m_tickTimer.async_wait(boost::bind(&ServerConnection::tick, this, boost::asio::placeholders::error));
	//	}
	//	else
	//	{
	//		// just wait
	//	}
	//}
}

void ServerConnection::errHandler(const boost::system::error_code& e, Connection*, std::string dummy)
{
	LOGERROR() << "serverconnection error"
				<<"ip"<<m_ip.c_str()
				<<"port"<<m_port
				<<"dummy"<<dummy
				<<LOGEND();
	tryConnect();
}
// just trying to connect
void ServerConnection::tryConnect()
{
	this->clear();

	ip::tcp::endpoint point(ip::address_v4::from_string(m_ip.c_str()), m_port);
	m_sock.async_connect(point, boost::bind(&ServerConnection::connectHandler, this, boost::asio::placeholders::error));
	m_status = CONN_STATUS_CONNECTING;
	LOGNORMAL() << "trying to connect " << m_ip.c_str() << " " << m_port << LOGEND();
}

max_stars_repo_name: zhuzhonghua/Episode


text:
//
// Created by Harold on 2021/4/12.
//

#ifndef M_MATH_M_CIRCSHIFT_EIGEN_HPP
#define M_MATH_M_CIRCSHIFT_EIGEN_HPP

// code from https://stackoverflow.com/questions/46077242/eigen-modifyable-custom-expression/46301503#46301503
// modified by Harold to meet Cpp11

#include <Eigen/Core>
#include <type_traits>

template <bool B> using bool_constant = std::integral_constant<bool, B>;

namespace helper
{
    namespace detail
    {
        template <typename T>
        constexpr std::true_type is_matrix(Eigen::MatrixBase<T>);
        std::false_type constexpr is_matrix(...);

        template <typename T>
        constexpr std::true_type is_array(Eigen::ArrayBase<T>);
        std::false_type constexpr is_array(...);
    }

    template <typename T>
    struct is_matrix : decltype(detail::is_matrix(std::declval<typename std::remove_cv<T>::type>()))
    {
    };

    template <typename T>
    struct is_array : decltype(detail::is_array(std::declval<typename std::remove_cv<T>::type>()))
    {
    };

    template <typename T>
    using is_matrix_or_array = bool_constant<is_array<T>::value || is_matrix<T>::value>;

/*
 * Index something if it's not an scalar
 */
    template <typename T, typename std::enable_if<is_matrix_or_array<T>::value, int>::type = 0>
    auto index_if_necessary(T&& thing, Eigen::Index idx) -> decltype(thing)
    {
        return thing(idx);
    }

/*
 * Overload for scalar.
 */
    template <typename T, typename std::enable_if<std::is_scalar<typename std::decay<T>::type>::value, int>::type = 0>
    auto index_if_necessary(T&& thing, Eigen::Index) -> decltype(thing)
    {
        return thing;
    }
}

namespace Eigen
{
    template <typename XprType, typename RowIndices, typename ColIndices>
    class CircShiftedView;

    namespace internal
    {
        template <typename XprType, typename RowIndices, typename ColIndices>
        struct traits<CircShiftedView<XprType, RowIndices, ColIndices>>
                : traits<XprType>
        {
            enum
            {
                RowsAtCompileTime = traits<XprType>::RowsAtCompileTime,
                ColsAtCompileTime = traits<XprType>::ColsAtCompileTime,
                MaxRowsAtCompileTime = (RowsAtCompileTime != Dynamic
                                        ? int(RowsAtCompileTime)
                                        : int(traits<XprType>::MaxRowsAtCompileTime)),
                MaxColsAtCompileTime = (ColsAtCompileTime != Dynamic
                                        ? int(ColsAtCompileTime)
                                        : int(traits<XprType>::MaxColsAtCompileTime)),
                XprTypeIsRowMajor = (int(traits<XprType>::Flags) & RowMajorBit) != 0,
                IsRowMajor = ((MaxRowsAtCompileTime == 1 && MaxColsAtCompileTime != 1) ? 1
                                                                                : (MaxColsAtCompileTime == 1 && MaxRowsAtCompileTime != 1) ? 0
                                                                                : XprTypeIsRowMajor),
                FlagsRowMajorBit = IsRowMajor ? RowMajorBit : 0,
                FlagsLvalueBit = is_lvalue<XprType>::value ? LvalueBit : 0,
                Flags = (traits<XprType>::Flags & HereditaryBits) | FlagsLvalueBit | FlagsRowMajorBit
            };
        };
    }

    template <typename XprType, typename RowShift, typename ColShift, typename StorageKind>
    class CircShiftedViewImpl;

    template <typename XprType, typename RowShift, typename ColShift>
    class CircShiftedView : public CircShiftedViewImpl<XprType, RowShift, ColShift,
            typename internal::traits<XprType>::StorageKind>
    {
    public:
        typedef typename CircShiftedViewImpl<XprType, RowShift, ColShift,
                typename internal::traits<XprType>::StorageKind>::Base Base;
        EIGEN_GENERIC_PUBLIC_INTERFACE(CircShiftedView)
        EIGEN_INHERIT_ASSIGNMENT_OPERATORS(CircShiftedView)

        typedef typename internal::ref_selector<XprType>::non_const_type MatrixTypeNested;
        typedef typename internal::remove_all<XprType>::type NestedExpression;

        template <typename T0, typename T1>
        CircShiftedView(XprType& xpr, const T0& rowShift, const T1& colShift)
                : m_xpr(xpr), m_rowShift(rowShift), m_colShift(colShift)
        {
            for (auto c = 0; c < xpr.cols(); ++c)
                assert(std::abs(helper::index_if_necessary(m_rowShift, c)) < m_xpr.rows()); // row shift must be within +- rows()-1
            for (auto r = 0; r < xpr.rows(); ++r)
                assert(std::abs(helper::index_if_necessary(m_colShift, r)) < m_xpr.cols()); // col shift must be within +- cols()-1
        }

        /** \returns number of rows */
        Index rows() const { return m_xpr.rows(); }

        /** \returns number of columns */
        Index cols() const { return m_xpr.cols(); }

        /** \returns the nested expression */
        const typename internal::remove_all<XprType>::type&
        nestedExpression() const { return m_xpr; }

        /** \returns the nested expression */
        typename internal::remove_reference<XprType>::type&
        nestedExpression() { return m_xpr.const_cast_derived(); }

        EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
        Index getRowIdx(Index row, Index col) const
        {
            Index R = m_xpr.rows();
            assert(row >= 0 && row < R && col >= 0 && col < m_xpr.cols());
            Index r = row - helper::index_if_necessary(m_rowShift, col);
            if (r >= R)
                return r - R;
            if (r < 0)
                return r + R;
            return r;
        }

        EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
        Index getColIdx(Index row, Index col) const
        {
            Index C = m_xpr.cols();
            assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < C);
            Index c = col - helper::index_if_necessary(m_colShift, row);
            if (c >= C)
                return c - C;
            if (c < 0)
                return c + C;
            return c;
        }

    protected:
        MatrixTypeNested m_xpr;
        RowShift m_rowShift;
        ColShift m_colShift;
    };

// Generic API dispatcher
    template <typename XprType, typename RowIndices, typename ColIndices, typename StorageKind>
    class CircShiftedViewImpl
            : public internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type
    {
    public:
        typedef typename internal::generic_xpr_base<CircShiftedView<XprType, RowIndices, ColIndices>>::type Base;
    };

    namespace internal
    {
        template <typename ArgType, typename RowIndices, typename ColIndices>
        struct unary_evaluator<CircShiftedView<ArgType, RowIndices, ColIndices>, IndexBased>
                : evaluator_base<CircShiftedView<ArgType, RowIndices, ColIndices>>
        {
            typedef CircShiftedView<ArgType, RowIndices, ColIndices> XprType;

            enum
            {
                CoeffReadCost = (evaluator<ArgType>::CoeffReadCost
                                 + NumTraits<Index>::AddCost  /* for comparison */
                                 + NumTraits<Index>::AddCost) /* for addition */,
                Flags = (evaluator<ArgType>::Flags & HereditaryBits),
                Alignment = 0
            };

            EIGEN_DEVICE_FUNC explicit unary_evaluator(const XprType& xpr) : m_argImpl(xpr.nestedExpression()), m_xpr(xpr)
            {
                EIGEN_INTERNAL_CHECK_COST_VALUE(CoeffReadCost);
            }

            typedef typename XprType::Scalar Scalar;
            typedef typename XprType::CoeffReturnType CoeffReturnType;

            EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
            CoeffReturnType coeff(Index row, Index col) const
            {
                return m_argImpl.coeff(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col));
            }

            EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
            CoeffReturnType coeff(Index idx) const
            {
                if (m_xpr.cols() == 1)
                    return m_argImpl.coeff(m_xpr.getRowIdx(idx, 1), 1);
                if (m_xpr.rows() == 1)
                    return m_argImpl.coeff(1, m_xpr.getColIdx(1, idx));
                assert(m_xpr.cols() == 1 || m_xpr.rows() == 1);
                // default no-assert case - assume col vector
                return m_argImpl.coeff(m_xpr.getRowIdx(idx, 1), 1);
            }

            EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE
            Scalar& coeffRef(Index row, Index col)
            {
                assert(row >= 0 && row < m_xpr.rows() && col >= 0 && col < m_xpr.cols());

                return m_argImpl.coeffRef(m_xpr.getRowIdx(row, col), m_xpr.getColIdx(row, col));
            }

        protected:

            evaluator<ArgType> m_argImpl;
            const XprType& m_xpr;
        };
    } // end namespace internal
} // end namespace Eigen

#endif //M_MATH_M_CIRCSHIFT_EIGEN_HPP