text:
//  (C) Copyright Raffi Enficiaud 2018.
//  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)

//  See http://www.boost.org/libs/test for the library home page.
//
//! @file
//! checking the clashing names, ticket trac #12597
// *****************************************************************************

#define BOOST_TEST_MODULE test_clashing_names
#include <boost/test/unit_test.hpp>
#include <boost/mpl/list.hpp>

void suite1_test1()
{
  BOOST_CHECK(true);
}

BOOST_AUTO_TEST_CASE( test_clashing_suites )
{
    using namespace boost::unit_test;
    test_suite* master_ts = BOOST_TEST_SUITE("local master");
    test_suite* t_suite1 = BOOST_TEST_SUITE( "suite1" );
    test_suite* t_suite2 = BOOST_TEST_SUITE( "suite1" );
    master_ts->add(t_suite1);
    BOOST_CHECK_THROW( master_ts->add(t_suite2),
                       boost::unit_test::framework::setup_error );
}

BOOST_AUTO_TEST_CASE( test_clashing_cases )
{
    using namespace boost::unit_test;
    test_suite* master_ts = BOOST_TEST_SUITE("local master");
    test_suite* t_suite1 = BOOST_TEST_SUITE( "suite1" );
    test_suite* t_suite2 = BOOST_TEST_SUITE( "suite2" );
    master_ts->add(t_suite1);
    master_ts->add(t_suite2);

    t_suite1->add( BOOST_TEST_CASE( suite1_test1 ) );
    BOOST_CHECK_THROW( t_suite1->add( BOOST_TEST_CASE( suite1_test1 ) ),
                       boost::unit_test::framework::setup_error );

    BOOST_CHECK_NO_THROW( t_suite2->add( BOOST_TEST_CASE( suite1_test1 ) ) );
}

BOOST_TEST_CASE_TEMPLATE_FUNCTION( template_test_case, T )
{
    BOOST_TEST( sizeof(T) == 4U );
}

BOOST_AUTO_TEST_CASE( test_clashing_cases_template_test_case )
{
    using namespace boost::unit_test;
    test_suite* master_ts = BOOST_TEST_SUITE("local master");
    test_suite* t_suite1 = BOOST_TEST_SUITE( "suite1" );
    test_suite* t_suite2 = BOOST_TEST_SUITE( "suite2" );
    master_ts->add(t_suite1);
    master_ts->add(t_suite2);

    typedef boost::mpl::list<int, long, unsigned char> test_types1;
    typedef boost::mpl::list<int, long, unsigned char, int> test_types2;

    BOOST_CHECK_NO_THROW( t_suite2->add( BOOST_TEST_CASE_TEMPLATE( template_test_case, test_types1 ) ) );
    BOOST_CHECK_THROW( t_suite1->add( BOOST_TEST_CASE_TEMPLATE( template_test_case, test_types2 ) ),
                       boost::unit_test::framework::setup_error );
}

max_forks_repo_name: ZeroInfinite/turicreate


text:
#ifndef IRODS_SHARED_MEMORY_OBJECT_HPP
#define IRODS_SHARED_MEMORY_OBJECT_HPP

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/sync/interprocess_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>

#include <string>
#include <utility>

namespace irods::experimental::interprocess
{
    template <typename T>
    class shared_memory_object
    {
    private:
        struct ipc_object
        {
            T thing;
            boost::interprocess::interprocess_mutex mtx;
        };

    public:
        template <typename ...Args>
        shared_memory_object(std::string _shm_name, Args&& ..._args)
            : shm_name_{std::move(_shm_name)}
            , shm_{boost::interprocess::open_or_create, shm_name_.c_str(), boost::interprocess::read_write}
            , region_{}
            , object_{}
        {
            boost::interprocess::offset_t size;

            // The shared memory was created if the size is equal to zero.
            if (shm_.get_size(size) && 0 == size) {
                shm_.truncate(sizeof(ipc_object));
                region_ = {shm_, boost::interprocess::read_write};
                object_ = new (region_.get_address()) ipc_object{T{std::forward<Args>(_args)...}, {}};
            }
            else {
                region_ = {shm_, boost::interprocess::read_write};
                object_ = static_cast<ipc_object*>(region_.get_address());
            }
        }

        shared_memory_object(const shared_memory_object&) = delete;
        auto operator=(const shared_memory_object&) -> shared_memory_object& = delete;

        auto remove() -> void
        {
            object_->thing.~T();
            boost::interprocess::shared_memory_object::remove(shm_name_.data());
        }

        template <typename Function>
        auto atomic_exec(Function _func) const
        {
            boost::interprocess::scoped_lock lk{object_->mtx};
            return _func(object_->thing);
        }

        template <typename Function>
        auto exec(Function _func) const
        {
            return _func(object_->thing);
        }

    private:
        const std::string shm_name_;
        boost::interprocess::shared_memory_object shm_;
        boost::interprocess::mapped_region region_;
        ipc_object* object_;
    }; // class shared_memory_object
} // namespace irods::experimental::ipc

#endif // IRODS_SHARED_MEMORY_OBJECT_HPP

ext: hpp

max_stars_repo_name: JustinKyleJames/irods

max_issues_repo_name: JustinKyleJames/irods

max_forks_repo_name: JustinKyleJames/irods


text:
#include "og/core/schema.h"
#include "og/core/mapping.h"
#include "og/core/serializer.h"
#include "og/core/xml_stream.h"
#include "og/core/where_condition.h"
#include "og/core/fetcher.h"
#include <boost/filesystem.hpp>

namespace og
{
namespace core
{

using namespace boost::property_tree;
using namespace boost::property_tree::xml_parser;
namespace pt = boost::posix_time;
namespace fs = boost::filesystem;

const char schema::schema_property_object_type_[] =
  "__SCHEMA_PROPERTY_TYPE__";
const char schema::schema_property_object_name_[] =
  "__SCHEMA_PROPERTY_NAME__";
//const char schema::schema_property_core_revision_[] = "__core_revision__";

schema_object_ptr schema::get_property_object()
{
  list<schema_object_ptr> schem_objs;
  list<string> prop_type_name_list;
  prop_type_name_list.push_back(string(schema_property_object_type_));

  get_object_by_type(prop_type_name_list, &schem_objs);

  if (schem_objs.size() == 0)
  {
    return nullptr;
  }
  else
  {
    return schem_objs.front();
  }
}

schema::schema()
  : session_(NULL)
{ }

schema::~schema()
{ }

void schema::initialize(session* _session)
{
  session_ = _session;

  // build property if not exists
  if (get_property_object() == nullptr)
  { build_property_object(); }

  if (session_->get_property_object() == nullptr)
  {	session_->build_property_object(); }
}

schema_object_ptr schema::create_object(string _otype, string _oname)
{
  //create sequence
  int id_seed;
  *session_->soci_session_ <<
                           "INSERT INTO schema_object_seq(id_seed) VALUES(NULL)";
  *session_->soci_session_ << "SELECT MAX(id_seed) FROM schema_object_seq",
                           soci::into(id_seed);
  string oid(SCHEMA_OBJECT_ID_PREFIX + boost::lexical_cast<string>(id_seed));

  //create object
  schema_object_ptr schm_obj(new schema_object(this, oid, _otype, _oname));

  // set date
  pt::ptime now = pt::microsec_clock::local_time();
  schm_obj->set_create_date(pt::to_simple_string(now));
  schm_obj->set_update_date(pt::to_simple_string(now));

  // set revision
  schm_obj->set_revision(REVISION_INIT_VALUE);

  add_object(schm_obj);

  // drop updated/bulk sync flag
  //schm_obj->set_bulk_revision_up(false);
  //schm_obj->set_bulk_sync(false);

  return schm_obj;
}

void schema::add_object(schema_object_ptr _schm_obj)
{
  //insert record
  *session_->soci_session_
      <<
      "INSERT INTO schema_object(id_, comment, type, "
      "name, revision, create_date, update_date) "
      "values(:id_, :comment, :type, "
      ":name, :revision, :create_date, :update_date)",
      soci::use(*(_schm_obj.get()));
}

schema_relation_ptr schema::create_relation(string _rel_type, string _rel_name,
    string _from_oid, string _to_oid)
{
  return create_relation(_rel_type, _rel_name,
                         _from_oid, _to_oid, multiplicity(), multiplicity());
}

schema_relation_ptr schema::create_relation(string _rel_type, string _rel_name,
    string _from_oid, string _to_oid, multiplicity& _from_mul,
    multiplicity& _to_mul)
{
  //create sequence
  int id_seed;
  *session_->soci_session_ <<
                           "INSERT INTO schema_relation_seq(id_seed) VALUES(NULL)";
  *session_->soci_session_ << "SELECT MAX(id_seed) FROM schema_relation_seq",
                           soci::into(id_seed);
  string rel_id(SCHEMA_RELATION_ID_PREFIX + boost::lexical_cast <string>
                (id_seed));

  //create object
  schema_relation_ptr schm_rel(new schema_relation(this, rel_id, _rel_type,
                               _rel_name,
                               _from_oid, _to_oid, _from_mul, _to_mul));

  // set date
  pt::ptime now = pt::microsec_clock::local_time();
  schm_rel->set_create_date(pt::to_simple_string(now));
  schm_rel->set_update_date(pt::to_simple_string(now));

  // set revision
  schm_rel->set_revision(REVISION_INIT_VALUE);

  add_relation(schm_rel);

  return schm_rel;
}

void schema::add_relation(schema_relation_ptr _schm_rel)
{
  //insert record
  *session_->soci_session_
      <<
      "INSERT INTO schema_relation(id_, from_id, to_id, comment, type, "
      "name, revision, create_date, update_date, "
      "from_multiplicity_min, from_multiplicity_max, to_multiplicity_min, to_multiplicity_max) "
      "VALUES(:id_, :from_id, :to_id, :comment, :type, "
      ":name, :revision, :create_date, :update_date, "
      ":from_multiplicity_min, :from_multiplicity_max, :to_multiplicity_min, :to_multiplicity_max)",
      soci::use(*(_schm_rel.get()));

  // drop updated/bulk sync flag
  //_schm_rel->set_bulk_revision_up(false);
  //_schm_rel->set_bulk_sync(false);
}

//schema_object_ptr schema::copy_object(schema_object _object)
//{
//  return schema_object_ptr();
//}

void schema::delete_object(string _oid,
                           list<boost::tuple<string, schema_parameter_ptr>>* _param_name_types)
{
  for (list<boost::tuple<string, schema_parameter_ptr>>::iterator it =
         _param_name_types->begin(); it != _param_name_types->end(); it++)
  {
    parameter_basetype_enum t =
      schema_parameter::convert_to_parameter_basetype_enum(
        it->get<1>()->get_basetype());

    switch (t)
    {
    case parameter_basetype_enum::integer:
      *session_->soci_session_
          << "DELETE schema_parameter_basetype_integer.* INNER JOIN "
          "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ INNER JOIN"
          "schema_parameter_basetype_integer ON schema_parameter.id_ = schema_parameter_basetype_integer.param_id "
          "WHERE schema_object_parameter.schema_object_id = :_o_id"
          "schema_object_parameter.param_name = :_param_name"
          , soci::use(_oid)
          , soci::use(it->get<0>());
      break;

    case parameter_basetype_enum::real:
      *session_->soci_session_
          << "DELETE schema_parameter_basetype_real.* INNER JOIN "
          "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ INNER JOIN"
          "schema_parameter_basetype_real ON schema_parameter.id_ = schema_parameter_basetype_real.param_id "
          "WHERE schema_object_parameter.schema_object_id = :_o_id"
          "schema_object_parameter.param_name = :_param_name"
          , soci::use(_oid)
          , soci::use(it->get<0>());
      break;

    case parameter_basetype_enum::text:
      *session_->soci_session_
          << "DELETE schema_parameter_basetype_text.* INNER JOIN "
          "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ INNER JOIN"
          "schema_parameter_basetype_text ON schema_parameter.id_ = schema_parameter_basetype_text.param_id "
          "WHERE schema_object_parameter.schema_object_id = :_o_id"
          "schema_object_parameter.param_name = :_param_name"
          , soci::use(_oid)
          , soci::use(it->get<0>());
      break;
    }
  }

  // delete from db
  *session_->soci_session_
      <<
      "DELETE FROM schema_object WHERE id_ = :id_",
      soci::use(_oid);
}

void schema::disconnect(string _rel_id,
                        list<boost::tuple<string, schema_parameter_ptr>>* _param_name_types)
{
  for (list<boost::tuple<string, schema_parameter_ptr>>::iterator it =
         _param_name_types->begin(); it != _param_name_types->end(); it++)
  {
    parameter_basetype_enum t =
      schema_parameter::convert_to_parameter_basetype_enum(
        it->get<1>()->get_basetype());

    switch (t)
    {
    case parameter_basetype_enum::integer:
      *session_->soci_session_
          << "DELETE schema_parameter_basetype_integer.* INNER JOIN "
          "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ INNER JOIN"
          "schema_parameter_basetype_integer ON schema_parameter.id_ = schema_parameter_basetype_integer.param_id "
          "WHERE schema_relation_parameter.schema_relation_id = :_o_id"
          "schema_relation_parameter.param_name = :_param_name"
          , soci::use(_rel_id)
          , soci::use(it->get<0>());
      break;

    case parameter_basetype_enum::real:
      *session_->soci_session_
          << "SELECT schema_parameter_basetype_real.* INNER JOIN "
          "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ INNER JOIN"
          "schema_parameter_basetype_real ON schema_parameter.id_ = schema_parameter_basetype_real.param_id "
          "WHERE schema_relation_parameter.schema_relation_id = :_o_id"
          "schema_relation_parameter.param_name = :_param_name"
          , soci::use(_rel_id)
          , soci::use(it->get<0>());
      break;

    case parameter_basetype_enum::text:
      *session_->soci_session_
          << "SELECT schema_parameter_basetype_text.* INNER JOIN "
          "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ INNER JOIN"
          "schema_parameter_basetype_text ON schema_parameter.id_ = schema_parameter_basetype_text.param_id "
          "WHERE schema_relation_parameter.schema_relation_id = :_o_id"
          "schema_relation_parameter.param_name = :_param_name"
          , soci::use(_rel_id)
          , soci::use(it->get<0>());
      break;

    }
  }

  // delete from db
  *session_->soci_session_
      <<
      "DELETE FROM schema_relation WHERE id_ = :id_",
      soci::use(_rel_id);
}

void schema::sync_object(schema_object* _schm_obj)
{
  *(session_->soci_session_.get())
      <<
      "UPDATE schema_object SET comment = :comment, "
      " type = :type, name = :name, revision = :revision, "
      "create_date = :create_date, update_date = :update_date"
      " WHERE id_ = :id_",
      soci::use(*_schm_obj);
}
void schema::sync_relation(schema_relation* _schm_rel)
{
  *(session_->soci_session_.get())
      <<
      "UPDATE schema_relation SET from_id = :from_id, to_id = :to_id,"
      "comment = :comment, "
      " type = :type, name = :name, revision = :revision, "
      "create_date = :create_date, update_date = :update_date"
      " WHERE id_ = :id_",
      soci::use(*_schm_rel);
}

void schema::revision_up_object(schema_object* _schm_obj)
{
  string rev(_schm_obj->get_revision());
  _schm_obj->set_revision(revision_up_revision(rev));
}

void schema::revision_up_relation(schema_relation* _schm_rel)
{
  string rev(_schm_rel->get_revision());
  _schm_rel->set_revision(revision_up_revision(rev));
}

optional<schema_object_ptr> schema::get_object(string _id)
{
  schema_object_ptr schm_obj(new schema_object(this));
  *session_->soci_session_
      <<
      "SELECT * FROM schema_object WHERE id_ = :id_",
      soci::into(*schm_obj.get()),
      soci::use(_id);

  if (schm_obj->get_id().empty())
  {
    return optional<schema_object_ptr>();
  }

  // drop updated/bulk sync flag
  //schm_obj->set_bulk_revision_up(false);
  //schm_obj->set_bulk_sync(false);

  return optional<schema_object_ptr>(schm_obj);
}

void schema::get_object_type(list<string>* _type_list)
{
  fetcher<string>::fetch(
    *session_->soci_session_
    , "SELECT DISTINCT type FROM schema_object WHERE 1 = 1"
    , _type_list);
}
void schema::get_relation_type(list<string>* _rel_type_list)
{
  fetcher<string>::fetch(
    *session_->soci_session_
    , "SELECT DISTINCT type FROM schema_relation WHERE 1 = 1"
    , _rel_type_list);
}

void schema::get_object(list<string>& _oid_list,
                        list<schema_object_ptr>* _schm_obj_list)
{
  _schm_obj_list->clear();

  for (list<string>::iterator it = _oid_list.begin(); it != _oid_list.end(); ++it)
  {
    optional<schema_object_ptr> obj_ptr_opt = get_object(*it);
    if (obj_ptr_opt.is_initialized())
    {
      _schm_obj_list->push_back(obj_ptr_opt.get());
    }
  }
}

void schema::get_object(list<schema_object_ptr>* _schm_obj_list)
{
  _schm_obj_list->clear();
  get_object_by_query(where_clause<string>("1=1"), _schm_obj_list);
}

void schema::get_object_by_type(list<string>& _otype_list,
                                list<schema_object_ptr>* _schm_obj_list)
{
  get_object_by_query(where_condition<string>(_otype_list, "type"),
                      _schm_obj_list);
}

void schema::get_object_by_name(list<string>& _oname_list,
                                list<schema_object_ptr>* _schm_obj_list)
{
  get_object_by_query(where_condition<string>(_oname_list, "name"),
                      _schm_obj_list);
}

void schema::get_relation_by_type(list<string>& _rel_type_list,
                                  list<schema_relation_ptr>* _schm_rel_list)
{
  get_relation_by_query(where_condition<string>(_rel_type_list, "type"),
                        _schm_rel_list);
}

optional<schema_relation_ptr> schema::get_relation(string _rel_id)
{
  schema_relation_ptr schm_rel(new schema_relation(this));

  *session_->soci_session_
      <<
      "SELECT * FROM schema_relation WHERE id_ = :id_",
      soci::into(*(schm_rel.get())),
      soci::use(_rel_id);

  if (schm_rel->get_id().empty())
  {
    return optional<schema_relation_ptr>();
  }

  // drop updated/bulk sync flag
  //schm_rel->set_bulk_revision_up(false);
  //schm_rel->set_bulk_sync(false);

  return optional<schema_relation_ptr>(schm_rel);

}

void schema::get_relation(list<string>& _rel_id_list,
                          list<schema_relation_ptr>* _schm_rel_list)
{
  _schm_rel_list->clear();

  for (list<string>::iterator it = _rel_id_list.begin(); it != _rel_id_list.end();
       ++it)
  {
    optional<schema_relation_ptr> rel_ptr_opt = get_relation(*it);
    if (rel_ptr_opt.is_initialized())
    {
      _schm_rel_list->push_back(rel_ptr_opt.get());
    }
  }
}

void schema::get_relation(list<schema_relation_ptr>* _schm_rel_list)
{
  _schm_rel_list->clear();
  get_relation_by_query(where_clause<string>("1=1"), _schm_rel_list);
}

void schema::get_connected_object_to(string _from_o_id,
                                     list<string>& _rel_type_list,
                                     list<schema_object_ptr>* _schm_obj_list)
{
  _schm_obj_list->clear();

  get_connected_object_to_by_query(
    _from_o_id,
    where_condition<string>(_rel_type_list, "schema_relation.type"),
    _schm_obj_list);

}
void schema::get_connected_object_from(string _to_o_id,
                                       list<string>& _rel_type_list,
                                       list<schema_object_ptr>* _schm_obj_list)
{
  _schm_obj_list->clear();

  get_connected_object_from_by_query(
    _to_o_id,
    where_condition<string>(_rel_type_list, "schema_relation.type"),
    _schm_obj_list);
}

void schema::get_connected_relation_to(string _from_o_id,
                                       list<string>& _rel_type_list,
                                       list<schema_relation_ptr>* _schm_rel_list)
{
  _schm_rel_list->clear();

  get_relation_by_query(
    where_condition<string>(_rel_type_list, "type"),
    " AND from_id = '" + _from_o_id + "'",
    _schm_rel_list);

}
void schema::get_connected_relation_from(string _to_o_id,
    list<string>& _rel_type_list,
    list<schema_relation_ptr>* _schm_rel_list)
{
  _schm_rel_list->clear();

  get_relation_by_query(
    where_condition<string>(_rel_type_list, "type"),
    " AND to_id = '" + _to_o_id + "'",
    _schm_rel_list);
}

bool schema::validate_connect_by_type(string _otype_from, string _otype_to)
{
  return false;
}

bool schema::validate_connect_by_type_id(string _otype, string _oid_from,
    string _oid_to)
{

  return false;
}

template<class T>
void schema::get_object_by_query(const T& _query,
                                 list<schema_object_ptr>* _schm_obj_list)
{
  list<string> o_id_list;

  fetcher<string>::fetch(
    *session_->soci_session_
    , "SELECT id_ FROM schema_object WHERE 1 = 1" + _query()
    , &o_id_list);

  get_object(o_id_list, _schm_obj_list);
}

template<class T>
void schema::get_connected_object_to_by_query(string _from_o_id,
    const T& _query,
    list<schema_object_ptr>* _schm_obj_list)
{
  list<string> o_id_list;

  fetcher<string>::fetch_use1(
    *session_->soci_session_
    , "SELECT schema_object.id_ FROM schema_object INNER JOIN "
    "schema_relation ON schema_relation.to_id = schema_object.id_"
    " WHERE 1 = 1"
    + _query()
    + " AND schema_relation.from_id = :_from_o_id"
    , soci::use(_from_o_id)
    , &o_id_list);

  get_object(o_id_list, _schm_obj_list);
}

template<class T>
void schema::get_connected_object_from_by_query(string _to_o_id,
    const T& _query,
    list<schema_object_ptr>* _schm_obj_list)
{
  list<string> o_id_list;

  fetcher<string>::fetch_use1(
    *session_->soci_session_
    , "SELECT schema_object.id_ FROM schema_object INNER JOIN "
    "schema_relation ON schema_relation.from_id = schema_object.id_"
    " WHERE 1 = 1"
    + _query()
    + " AND schema_relation.to_id = :_to_o_id"
    , soci::use(_to_o_id)
    , &o_id_list);

  get_object(o_id_list, _schm_obj_list);
}

template<class T>
void schema::get_relation_by_query(const T& _query,
                                   list<schema_relation_ptr>* _schm_rel_list)
{
  get_relation_by_query(_query, "", _schm_rel_list);
}

template<class T>
void schema::get_relation_by_query(const T& _query,
                                   string _query_additional1,
                                   list<schema_relation_ptr>* _schm_rel_list)
{
  list<string> rel_id_list;

  fetcher<string>::fetch(
    *session_->soci_session_
    , "SELECT id_ FROM schema_relation WHERE 1 = 1"
    + _query_additional1
    + _query()
    , &rel_id_list);

  get_relation(rel_id_list, _schm_rel_list);
}

long schema::get_schema_rev_from_file(string _path)
{
  fs::path imp(_path);

  boost::system::error_code error;
  const bool result = fs::exists(imp, error);
  if (!result || error)
  {
    OG_LOG << "import file is not found:" << _path;
    return -1;
  }

  // Create XML document
  boost::property_tree::ptree pt;
  xml_stream().read_from_file(_path, &pt);

  long rev = pt.get<long>("og.schema.<xmlattr>.revision");
  return rev;
}

bool schema::import_from_file(string _path)
{
  fs::path imp(_path);

  boost::system::error_code error;
  const bool result = fs::exists(imp, error);
  if (!result || error)
  {
    OG_LOG << "import file is not found:" << _path;
    return false;
  }

  // delete session property object in advance
  {
    session_object_ptr sesn_prop = session_->get_property_object();
    if (sesn_prop != nullptr) { sesn_prop->delete_object(); }

    schema_object_ptr prop_obj = get_property_object();
    if (prop_obj != nullptr) { prop_obj->delete_object(); }
  }

  // Create XML document
  boost::property_tree::ptree pt;
  xml_stream().read_from_file(_path, &pt);

  // schema parameter
  BOOST_FOREACH(const ptree::value_type & child,
                pt.get_child("og.schema.parameters"))
  {

    // deserialize
    schema_parameter_ptr schm_par(new schema_parameter(this));
    if (serializer<schema_parameter_ptr>::deserialize(child, schm_par))
    {
      transaction tran(*session_);
      insert_schema_param(schm_par, false);
      tran.commit();
    }
  }

  // schema object
  BOOST_FOREACH(const ptree::value_type & child,
                pt.get_child("og.schema.objects"))
  {
    // deserialize
    schema_object_ptr schm_obj(new schema_object(this));

    list<schema_object_parameter> obj_params;
    if (serializer<schema_object_ptr>::deserialize(child, schm_obj, obj_params))
    {
      transaction tran(*session_);
      add_object(schm_obj);

      for (list<schema_object_parameter>::iterator it = obj_params.begin();
           it != obj_params.end(); it++)
      {
        add_object_parameter_definition(schm_obj->get_id(), it->param_name_, it->pid_);
      }
	  tran.commit();
    }
    else
    {
      return false;
    }
  }

  // schema relation
  BOOST_FOREACH(const ptree::value_type & child,
                pt.get_child("og.schema.relations"))
  {
    // deserialize
    schema_relation_ptr schm_rel(new schema_relation(this));
    list<schema_relation_parameter> rel_params;

    if (serializer<schema_relation_ptr>::deserialize(child, schm_rel, rel_params))
    {
      transaction tran(*session_);
      add_relation(schm_rel);

      for (list<schema_relation_parameter>::iterator it = rel_params.begin();
           it != rel_params.end(); it++)
      {
        add_relation_parameter_definition(schm_rel->get_id(), it->param_name_,
                                          it->pid_);
      }
	  tran.commit();
    }
    else
    {
      return false;
    }
  }

  // build property if not exists
  if (get_property_object() == nullptr)
  { build_property_object(); }

  if (session_->get_property_object() == nullptr)
  {	session_->build_property_object(); }

  return true;
}

schema_object_ptr schema::build_property_object()
{
  schema_object_ptr schm_prop;
  list<schema_object_ptr> schem_objs;
  list<string> prop_type_name_list;
  prop_type_name_list.push_back(string(schema_property_object_type_));

  get_object_by_type(prop_type_name_list, &schem_objs);

  if (schem_objs.size() == 0)
  {
    schm_prop = create_object(string(schema_property_object_type_),
                              string(schema_property_object_name_));
    return schm_prop;
  }
  else
  {
    string mes("fatal. schema property object exists.");
    OG_LOG << mes;
    throw og::core::exception() << exception_message(mes);
  }
}

void schema::import_parameter(schema_parameter_ptr _schm_par,
                              const ptree::value_type& _pt)
{
  parameter_basetype_enum t = (parameter_basetype_enum)_schm_par->get_basetype();

  switch (t)
  {
  case parameter_basetype_enum::integer:
  {
    // deserialize
    parameter_basetype_integer base_i;
    if (serializer<parameter_basetype_integer*>::deserialize(_pt, &base_i))
    {
      //insert record
      insert_schema_basetype(_schm_par, base_i);
      //      insert_schema_param(_schm_par, false);
    }
  }
  break;

  case parameter_basetype_enum::real:
  {
    // deserialize
    parameter_basetype_real base_r;
    if (serializer<parameter_basetype_real*>::deserialize(_pt, &base_r))
    {
      //insert record
      insert_schema_basetype(_schm_par, base_r);
      //      insert_schema_param(_schm_par, false);
    }
  }
  break;

  case parameter_basetype_enum::text:
  {
    // deserialize
    parameter_basetype_text base_t;
    if (serializer<parameter_basetype_text*>::deserialize(_pt, &base_t))
    {
      //insert record
      insert_schema_basetype(_schm_par, base_t);
      //      insert_schema_param(_schm_par, false);
    }
  }
  break;
  }

}

void schema::export_to_file(string _path)
{
  // Create XML document
  boost::property_tree::ptree pt;
  ptree& pt_1 = pt.add("og.schema", "");

  std::string rev = get_property_object()->get_revision();
  OG_LOG << "exporting schema revision:" << rev;
  pt_1.put("<xmlattr>.revision", rev);

  // schema parameter
  list<schema_parameter_ptr> schm_par_list;
  get_parameter(&schm_par_list);
  BOOST_FOREACH(schema_parameter_ptr s, schm_par_list)
  {
    // serialize
    serializer<schema_parameter_ptr>::serialize(pt_1, s);
  }

  // schema object
  list<schema_object_ptr> schm_obj_list;
  get_object(&schm_obj_list);
  BOOST_FOREACH(schema_object_ptr s, schm_obj_list)
  {
    // serialize
    serializer<schema_object_ptr>::serialize(pt_1, s);
  }

  // schema relation
  list<schema_relation_ptr> schm_rel_list;
  get_relation(&schm_rel_list);
  BOOST_FOREACH(schema_relation_ptr s, schm_rel_list)
  {
    // serialize
    serializer<schema_relation_ptr>::serialize(pt_1, s);
  }

  xml_stream().write_to_file(_path, pt);
}

void schema::purge()
{
  session_->purge(true);

  *session_->soci_session_ << "DELETE FROM schema_parameter_basetype_integer;";
  *session_->soci_session_ << "DELETE FROM schema_parameter_basetype_real;";
  *session_->soci_session_ << "DELETE FROM schema_parameter_basetype_text;";
  *session_->soci_session_ <<
                           "DELETE FROM schema_parameter_basetype_select_item;";
  *session_->soci_session_ << "DELETE FROM schema_parameter_basetype_select;";

  *session_->soci_session_ << "DELETE FROM schema_relation_parameter;";
  *session_->soci_session_ << "DELETE FROM schema_object_parameter;";

  *session_->soci_session_ << "DELETE FROM schema_parameter;";

  *session_->soci_session_ << "DELETE FROM schema_relation;";
  *session_->soci_session_ << "DELETE FROM schema_object;";

  build_property_object();
  session_->build_property_object();
}

template <>
void schema::insert_schema_basetype<parameter_basetype_integer>
(schema_parameter_ptr _schm_param,
 parameter_basetype_integer& _basetype)
{
  // parameter basetypes var copy
  //_schm_param->basetypes_value_ = _basetype;
  _basetype.id_ = _schm_param->get_id();

  *session_->soci_session_
      <<
      "INSERT INTO schema_parameter_basetype_integer(id_, default_value, system_min, system_max, warn_min, warn_max) "
      "VALUES (:id_, :default_value, :system_min, :system_max, :warn_min, :warn_max)"
      //      , soci::use(_schm_param->get_id())
      , soci::use(_basetype);
}
template <>
void schema::insert_schema_basetype<parameter_basetype_real>
(schema_parameter_ptr _schm_param,
 parameter_basetype_real& _basetype)
{
  // parameter basetypes var copy
  //_schm_param->basetypes_value_ = _basetype;
  _basetype.id_ = _schm_param->get_id();

  *session_->soci_session_
      <<
      "INSERT INTO schema_parameter_basetype_real(id_, default_value, system_min, system_max, warn_min, warn_max) "
      "VALUES (:id_, :default_value, :system_min, :system_max, :warn_min, :warn_max)"
      //	  , soci::use(_schm_param->get_id())
      , soci::use(_basetype);
}
template <>
void schema::insert_schema_basetype<parameter_basetype_text>
(schema_parameter_ptr _schm_param,
 parameter_basetype_text& _basetype)
{
  // parameter basetypes var copy
  //_schm_param->basetypes_value_ = _basetype;
  _basetype.id_ = _schm_param->get_id();

  *session_->soci_session_
      <<
      "INSERT INTO schema_parameter_basetype_text(id_, default_value, system_min, system_max, warn_min, warn_max) "
      "VALUES (:id_, :default_value, :system_min, :system_max, :warn_min, :warn_max)"
      //      , soci::use(_schm_param->get_id())
      , soci::use(_basetype);
}

void schema::delete_parameter(string _param_id)
{
  // delete from db
  *session_->soci_session_
      <<
      "DELETE FROM schema_parameter WHERE id_ = :id_",
      soci::use(_param_id);
}

void schema::insert_schema_param(schema_parameter_ptr _schm_par, bool _initial)
{
  if (_initial)
  {
    //create sequence
    int id_seed;
    *session_->soci_session_ <<
                             "INSERT INTO schema_parameter_seq(id_seed) VALUES(NULL)";
    *session_->soci_session_ << "SELECT MAX(id_seed) FROM schema_parameter_seq",
                             soci::into(id_seed);
    string par_id(SCHEMA_PARAMETER_ID_PREFIX + boost::lexical_cast<string>
                  (id_seed));
    _schm_par->set_id(par_id);

    // set date
    pt::ptime now = pt::microsec_clock::local_time();
    _schm_par->set_create_date(pt::to_simple_string(now));
    _schm_par->set_update_date(pt::to_simple_string(now));

    // set revision
    _schm_par->set_revision(REVISION_INIT_VALUE);
  }

  //insert record
  *session_->soci_session_
      <<
      "INSERT INTO schema_parameter(id_, comment, type, "
      "default_array_size, min_array_size, max_array_size, "
      "revision, create_date, update_date, basetype_name) "
      "values(:id_, :comment, :type,"
      ":default_array_size, :min_array_size, :max_array_size, "
      ":revision, :create_date, :update_date, :basetype_name)",
      soci::use(*(_schm_par.get()));

  parameter_basetype_enum t = (parameter_basetype_enum)_schm_par->get_basetype();

  switch (t)
  {
  case parameter_basetype_enum::integer:
  {
    parameter_basetype_integer* base_i = boost::get<parameter_basetype_integer>
                                         (&_schm_par->basetype_variant_);
    //OG_LOG << "INTEGER:(def)" << base_i->default_value_;

    insert_schema_basetype(_schm_par, *base_i);
  }
  break;
  case parameter_basetype_enum::real:
  {
    parameter_basetype_real* base_r = boost::get<parameter_basetype_real>
                                      (&_schm_par->basetype_variant_);
    //OG_LOG << "REAL:(def)" << base_r->default_value_;

    insert_schema_basetype(_schm_par, *base_r);
  }
  break;
  case parameter_basetype_enum::text:
  {
    parameter_basetype_text* base_t = boost::get<parameter_basetype_text>
                                      (&_schm_par->basetype_variant_);
    //OG_LOG << "TEXT:(def)" << base_t->default_value_;

    insert_schema_basetype(_schm_par, *base_t);
  }
  break;
  }

}

void schema::get_object_parameters(string _o_id,
                                   list<boost::tuple<string, schema_parameter_ptr>>*
                                   _param_name_types)
{
  list<boost::tuple<string, string>> pname_id;

  tuple_fetcher<string, string>::fetch_use1(
    *session_->soci_session_
    , "SELECT schema_object_parameter.param_name, schema_parameter.id_ "
    "FROM schema_object_parameter "
    "INNER JOIN "
    "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ "
    "WHERE schema_object_parameter.schema_object_id = :_o_id "
    , soci::use(_o_id)
    , &pname_id);

  list<boost::tuple<string, string>>::iterator it = pname_id.begin();
  for (; it != pname_id.end(); it++)
  {
    optional<schema_parameter_ptr> p = get_parameter(it->get<1>());
    if (p.is_initialized())
    {
      _param_name_types->push_back(boost::tuple<string, schema_parameter_ptr>
                                   (it->get<0>(),
                                    p.get()));
    }
  }

}

void schema::get_relation_parameters(string _rel_id,
                                     list<boost::tuple<string, schema_parameter_ptr>>*
                                     _param_name_types)
{
  list<boost::tuple<string, string>> pname_id;

  tuple_fetcher<string, string>::fetch_use1(
    *session_->soci_session_
    , "SELECT schema_relation_parameter.param_name, schema_parameter.id_ "
    "FROM schema_relation_parameter "
    "INNER JOIN "
    "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ "
    "WHERE schema_relation_parameter.schema_relation_id = :_o_id "
    , soci::use(_rel_id)
    , &pname_id);

  list<boost::tuple<string, string>>::iterator it = pname_id.begin();
  for (; it != pname_id.end(); it++)
  {
    optional<schema_parameter_ptr> p = get_parameter(it->get<1>());
    if (p.is_initialized())
    {
      _param_name_types->push_back(boost::tuple<string, schema_parameter_ptr>
                                   (it->get<0>(),
                                    p.get()));
    }
  }

}

parameter_basetype_enum
schema::get_object_parameter_basetype_enum_by_param_name(
  string _o_id,
  string _param_name)
{
  int param_name;

  *session_->soci_session_
      << "SELECT schema_parameter.basetype_name FROM "
      "schema_parameter, schema_object_parameter WHERE schema_object_parameter.pid = schema_parameter.id_ AND "
      "schema_object_parameter.schema_object_id = :_o_id AND "
      "schema_object_parameter.param_name = :_param_name"
      , soci::use(_o_id)
      , soci::use(_param_name)
      , soci::into(param_name);

  return schema_parameter::convert_to_parameter_basetype_enum(param_name);
}
parameter_basetype_enum
schema::get_relation_parameter_basetype_enum_by_param_name(
  string _rel_id,
  string _param_name)
{
  int param_name;

  *session_->soci_session_
      << "SELECT schema_parameter.basetype_name FROM "
      "schema_parameter, schema_relation_parameter WHERE schema_relation_parameter.pid = schema_parameter.id_ AND "
      "schema_relation_parameter.schema_relation_id = :_rel_id AND "
      "schema_relation_parameter.param_name = :_param_name"
      , soci::use(_rel_id)
      , soci::use(_param_name)
      , soci::into(param_name);

  return schema_parameter::convert_to_parameter_basetype_enum(param_name);
}

void schema::add_object_parameter_definition(string _o_id, string _param_name,
    schema_parameter_ptr _schm_par)
{
  add_object_parameter_definition(_o_id, _param_name, _schm_par->get_id());
}

void schema::add_object_parameter_definition(string _o_id, string _param_name,
    string _schm_par_id)
{
  schema_object_parameter schm_o_par(
    _o_id, _schm_par_id, _param_name);

  *session_->soci_session_
      <<
      "INSERT INTO schema_object_parameter(schema_object_id, pid, param_name) "
      "VALUES (:schema_object_id, :pid, :param_name)",
      soci::use(schm_o_par);
}
void schema::delete_object_parameter_definition(string _o_id,
    string _param_name,
    schema_parameter_ptr _schm_par)
{
  // delete all parameters in session
  session_->delete_object_parameter_definition(_param_name, _schm_par);

  *session_->soci_session_
      <<
      "DELETE FROM schema_object_parameter WHERE schema_object_id = :schema_object_id AND param_name = "
      " :param_name and pid = :pid",
      soci::use(_o_id), soci::use(_param_name), soci::use(_schm_par->get_id());
}
void schema::add_relation_parameter_definition(string _rel_id,
    string _param_name,
    schema_parameter_ptr _schm_par)
{
  add_relation_parameter_definition(_rel_id, _param_name, _schm_par->get_id());
}
void schema::add_relation_parameter_definition(string _rel_id,
    string _param_name,
    string _schm_par_id)
{
  schema_relation_parameter schm_r_par(
    _rel_id, _schm_par_id, _param_name);

  *session_->soci_session_
      <<
      "INSERT INTO schema_relation_parameter(schema_relation_id, pid, param_name) "
      "VALUES (:schema_relation_id, :pid, :param_name)",
      soci::use(schm_r_par);
}

void schema::delete_relation_parameter_definition(string _rel_id,
    string _param_name,
    schema_parameter_ptr _schm_par)
{
  // delete all parameters in session
  session_->delete_relatoin_parameter_definition(_param_name, _schm_par);

  *session_->soci_session_
      <<
      "DELETE FROM schema_relation_parameter WHERE schema_relation_id = :schema_object_id AND param_name = "
      " :param_name and pid = :pid",
      soci::use(_rel_id), soci::use(_param_name), soci::use(_schm_par->get_id());
}

template <>
void schema::get_object_parameter_definition(string _o_id, string _param_name,
    parameter_basetype_integer* _param_basetype)
{
  *session_->soci_session_
      << "SELECT schema_parameter_basetype_integer.* INNER JOIN "
      "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ INNER JOIN"
      "schema_parameter_basetype_integer ON schema_parameter.id_ = schema_parameter_basetype_integer.param_id "
      "WHERE schema_object_parameter.schema_object_id = :_o_id"
      "schema_object_parameter.param_name = :_param_name"
      , soci::use(_o_id)
      , soci::use(_param_name)
      , soci::into(*_param_basetype);
}
template <>
void schema::get_object_parameter_definition(string _o_id, string _param_name,
    parameter_basetype_real* _param_basetype)
{
  *session_->soci_session_
      << "SELECT schema_parameter_basetype_real.* INNER JOIN "
      "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ INNER JOIN"
      "schema_parameter_basetype_real ON schema_parameter.id_ = schema_parameter_basetype_real.param_id "
      "WHERE schema_object_parameter.schema_object_id = :_o_id"
      "schema_object_parameter.param_name = :_param_name"
      , soci::use(_o_id)
      , soci::use(_param_name)
      , soci::into(*_param_basetype);
}
template <>
void schema::get_object_parameter_definition(string _o_id, string _param_name,
    parameter_basetype_text* _param_basetype)
{
  *session_->soci_session_
      << "SELECT schema_parameter_basetype_text.* INNER JOIN "
      "schema_parameter ON schema_object_parameter.pid = schema_parameter.id_ INNER JOIN"
      "schema_parameter_basetype_text ON schema_parameter.id_ = schema_parameter_basetype_text.param_id "
      "WHERE schema_object_parameter.schema_object_id = :_o_id"
      "schema_object_parameter.param_name = :_param_name"
      , soci::use(_o_id)
      , soci::use(_param_name)
      , soci::into(*_param_basetype);
}

template <>
void schema::get_relation_parameter_definition(string _rel_id,
    string _param_name,
    parameter_basetype_integer* _param_basetype)
{
  *session_->soci_session_
      << "SELECT schema_parameter_basetype_integer.* INNER JOIN "
      "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ INNER JOIN"
      "schema_parameter_basetype_integer ON schema_parameter.id_ = schema_parameter_basetype_integer.param_id "
      "WHERE schema_relation_parameter.schema_relation_id = :_o_id"
      "schema_relation_parameter.param_name = :_param_name"
      , soci::use(_rel_id)
      , soci::use(_param_name)
      , soci::into(*_param_basetype);
}
template <>
void schema::get_relation_parameter_definition(string _rel_id,
    string _param_name,
    parameter_basetype_real* _param_basetype)
{
  *session_->soci_session_
      << "SELECT schema_parameter_basetype_real.* INNER JOIN "
      "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ INNER JOIN"
      "schema_parameter_basetype_real ON schema_parameter.id_ = schema_parameter_basetype_real.param_id "
      "WHERE schema_relation_parameter.schema_relation_id = :_o_id"
      "schema_relation_parameter.param_name = :_param_name"
      , soci::use(_rel_id)
      , soci::use(_param_name)
      , soci::into(*_param_basetype);
}
template <>
void schema::get_relation_parameter_definition(string _rel_id,
    string _param_name,
    parameter_basetype_text* _param_basetype)
{
  *session_->soci_session_
      << "SELECT schema_parameter_basetype_text.* INNER JOIN "
      "schema_parameter ON schema_relation_parameter.pid = schema_parameter.id_ INNER JOIN"
      "schema_parameter_basetype_text ON schema_parameter.id_ = schema_parameter_basetype_text.param_id "
      "WHERE schema_relation_parameter.schema_relation_id = :_o_id"
      "schema_relation_parameter.param_name = :_param_name"
      , soci::use(_rel_id)
      , soci::use(_param_name)
      , soci::into(*_param_basetype);
}

void schema::get_parameter(list<schema_parameter_ptr>* _schm_par_list)
{
  _schm_par_list->clear();
  get_parameter_by_query(where_clause<string>("1=1"), _schm_par_list);
}

template<class T>
void schema::get_parameter_by_query(const T& _query,
                                    list<schema_parameter_ptr>* _schm_par_list)
{
  list<string> p_id_list;

  fetcher<string>::fetch(
    *session_->soci_session_
    , "SELECT schema_parameter.id_ FROM schema_parameter "
    " WHERE 1 = 1"
    + _query()
    , &p_id_list);

  get_parameter(p_id_list, _schm_par_list);
}

void schema::get_parameter(list<string>& _p_id_list,
                           list<schema_parameter_ptr>* _schm_par_list)
{
  _schm_par_list->clear();

  for (list<string>::iterator it = _p_id_list.begin(); it != _p_id_list.end();
       it++)
  {
    optional<schema_parameter_ptr> par_ptr_opt = get_parameter(*it);
    if (par_ptr_opt.is_initialized())
    {
      _schm_par_list->push_back(par_ptr_opt.get());
    }
  }
}

optional<schema_parameter_ptr> schema::get_parameter(string _par_id)
{
  schema_parameter_ptr schm_par(new schema_parameter(this));
  *session_->soci_session_
      <<
      "SELECT * FROM schema_parameter WHERE id_ = :id_",
      soci::into(*(schm_par.get())),
      soci::use(_par_id);

  if (schm_par->get_id().empty())
  {
    return optional<schema_parameter_ptr>();
  }

  switch ((parameter_basetype_enum)schm_par->get_basetype())
  {
  case parameter_basetype_enum::integer:
  {
    parameter_basetype_integer* base(boost::get<parameter_basetype_integer>
                                     (&schm_par->basetype_variant_));

    *session_->soci_session_
        <<
        //		"SELECT id_, default_value, system_min, system_max, warn_min, warn_max FROM schema_parameter_basetype_integer WHERE id_ = :id_",
        "SELECT * FROM schema_parameter_basetype_integer WHERE id_ = :id_",
        soci::into(*base),
        soci::use(schm_par->get_id());
  }
  break;
  case parameter_basetype_enum::real:
  {
    parameter_basetype_real* base(boost::get<parameter_basetype_real>
                                  (&schm_par->basetype_variant_));
    *session_->soci_session_
        <<
        "SELECT * FROM schema_parameter_basetype_real WHERE id_ = :id_",
        soci::into(*base),
        soci::use(schm_par->get_id());
  }
  break;
  case parameter_basetype_enum::text:
  {
    parameter_basetype_text* base(boost::get<parameter_basetype_text>
                                  (&schm_par->basetype_variant_));

    *session_->soci_session_
        <<
        //		"SELECT id_, default_value, system_min, system_max, warn_min, warn_max FROM schema_parameter_basetype_text WHERE id_ = :id_",
        "SELECT * FROM schema_parameter_basetype_text WHERE id_ = :id_",
        soci::into(*base),
        soci::use(schm_par->get_id());
  }
  break;
  }

  return optional<schema_parameter_ptr>(schm_par);
}

string schema::revision_up_revision(const string& _revision)
{
  long rev = boost::lexical_cast<long>(_revision);
  return boost::lexical_cast<string>(++rev);
}

int schema::get_parameter_id_seed()
{
  int id_seed;
  *session_->soci_session_ <<
                           "INSERT INTO schema_parameter_seq(id_seed) VALUES(NULL)";
  *session_->soci_session_ << "SELECT MAX(id_seed) FROM schema_parameter_seq",
                           soci::into(id_seed);

  return id_seed;
}

} // namespace core;
} // namespace og;

ext: cpp

max_stars_repo_name: KouOuchi/ObjectGenoise

max_issues_repo_name: KouOuchi/ObjectGenoise

max_forks_repo_name: KouOuchi/ObjectGenoise


text:
/*
 * @file
 * @author University of Warwick
 * @version 1.0
 *
 * @section LICENSE
 *
 * @section DESCRIPTION
 *
 * Unit Tests for the concrete methods of the CupCfdAoSMeshBoundary class
 */

#define BOOST_TEST_MODULE CupCfdAoSMeshBoundary
#include <boost/test/unit_test.hpp>
#include <boost/test/output_test_stream.hpp>
#include <stdexcept>

#include "CupCfdAoSMeshBoundary.h"
#include "Error.h"

using namespace cupcfd::geometry::mesh;

// === Default Constructor ===
// Test 1: Test that the default values are as expected
BOOST_AUTO_TEST_CASE(constructor_test1)
{
	CupCfdAoSMeshBoundary<int, double> boundary;

	BOOST_CHECK_EQUAL(boundary.faceID, -1);
	BOOST_CHECK_EQUAL(boundary.verticesID[0], -1);
	BOOST_CHECK_EQUAL(boundary.verticesID[1], -1);
	BOOST_CHECK_EQUAL(boundary.verticesID[2], -1);
	BOOST_CHECK_EQUAL(boundary.verticesID[3], -1);
	BOOST_CHECK_EQUAL(boundary.regionID, -1);
	BOOST_CHECK_EQUAL(boundary.distance, 0.0);
	BOOST_CHECK_EQUAL(boundary.yplus, 0.0);
	BOOST_CHECK_EQUAL(boundary.uplus, 0.0);
	BOOST_CHECK_EQUAL(boundary.shear.cmp[0], 0.0);
	BOOST_CHECK_EQUAL(boundary.shear.cmp[1], 0.0);
	BOOST_CHECK_EQUAL(boundary.shear.cmp[2], 0.0);
	BOOST_CHECK_EQUAL(boundary.q, 0.0);
	BOOST_CHECK_EQUAL(boundary.h, 0.0);
	BOOST_CHECK_EQUAL(boundary.t, 0.0);
}

max_stars_repo_name: thorbenlouw/CUP-CFD

max_issues_repo_name: thorbenlouw/CUP-CFD

max_forks_repo_name: thorbenlouw/CUP-CFD


text:
// Copyright (C) 2018-2019 Intel Corporation
// SPDX-License-Identifier: Apache-2.0
//

#pragma once

#include <ie_blob.h>
#include <ie_layers_property.hpp>
#include <inference_engine/precision_utils.h>
#include <inference_engine/parsers.h>
#include <xml_net_builder.hpp>
#include <xml_helper.hpp>
#include <common_layers_params.hpp>

#ifndef USE_BOOST_RE

#include <regex>

#define REPLACE_WITH_STR(SRC, PATTERN, STR) SRC = std::regex_replace(SRC, std::regex(PATTERN), STR)
#define FIND_STR(SRC, PATTERN) std::regex_search(SRC, std::regex(PATTERN))
#else
#include <boost/regex.hpp>
#define REPLACE_WITH_STR(SRC, PATTERN, STR) SRC = boost::regex_replace(SRC, boost::regex(PATTERN), STR)
#define FIND_STR(SRC, PATTERN) boost::regex_search(SRC, boost::regex(PATTERN))
#endif

#define REPLACE_WITH_NUM(SRC, PATTERN, NUM) REPLACE_WITH_STR(SRC, PATTERN, std::to_string(NUM))
#define REPLACE_WITH_NUM_VECTOR(SRC, PATTERN, NUMS) \
	{ std::string result; \
        if (NUMS.size() > 0) { \
            result += std::to_string(NUMS[0]); \
            for (int i = 1; i < NUMS.size(); i++) { \
                    result += "," + std::to_string(NUMS[i]); \
            } \
        } \
	REPLACE_WITH_STR(SRC, PATTERN, result); }
#define REPLACE_WITH_NUM_VECTOR_REVERSE(SRC, PATTERN, NUMS) \
	{ std::string result; \
        auto nums_size = NUMS.size(); \
        if (nums_size > 0) { \
            result += std::to_string(NUMS[nums_size - 1]); \
            for (int i = 2; i <= nums_size; i++) { \
                    result += "," + std::to_string(NUMS[nums_size - i]); \
            } \
        } \
	REPLACE_WITH_STR(SRC, PATTERN, result); }
#define REMOVE_LINE(SRC, PATTERN) REPLACE_WITH_STR(SRC, PATTERN, "")

#define PRETTY_PARAM(name, type)                                                            \
    class name                                                                              \
    {                                                                                \
    public:                                                                                \
        typedef type param_type;                                                            \
        name ( param_type arg = param_type ()) : val_(arg) {}                               \
        operator param_type () const {return val_;}                                         \
    private:                                                                                \
        param_type val_;                                                                    \
    };                                                                                \
    static inline void PrintTo(name param, ::std::ostream* os)                              \
    {                                                                                \
        *os << #name ": " << ::testing::PrintToString((name::param_type)(param));           \
    }

struct MapStrStr {
    std::map<std::string, std::string> data{};

    explicit MapStrStr(std::map<std::string, std::string> _data) : data(std::move(_data)) {}

    MapStrStr() = default;
};

void get_common_dims(const InferenceEngine::Blob &blob,
                     int32_t &dimx,
                     int32_t &dimy,
                     int32_t &dimz);

void get_common_dims(const InferenceEngine::Blob &blob,
                     int32_t &dimx,
                     int32_t &dimy,
                     int32_t &dimz,
                     int32_t &dimn);

template<int Version = 3>
inline InferenceEngine::details::CNNNetworkImplPtr
buildSingleLayerNetworkCommon(InferenceEngine::details::IFormatParser *parser,
                              const std::string &layerType,
                              const testing::InOutShapes &inOutShapes,
                              std::map<std::string, std::string> *params,
                              const std::string &layerDataName = "data",
                              const InferenceEngine::Precision &precision = InferenceEngine::Precision::FP32,
                              size_t weightsSize = 0,
                              size_t biasesSize = 0,
                              const InferenceEngine::TBlob<uint8_t>::Ptr &weights = nullptr) {
    IE_ASSERT(parser);
    testing::XMLHelper xmlHelper(parser);
    std::string precisionStr = precision.name();
    auto netBuilder = testing::XmlNetBuilder<Version>::buildNetworkWithOneInput("Mock", inOutShapes.inDims[0],
                                                                                precisionStr);
    size_t inputsNumber = inOutShapes.inDims.size();
    for (int i = 1; i < inputsNumber; i++) {
        netBuilder.addInputLayer(precisionStr, inOutShapes.inDims[i]);
    }
    netBuilder.addLayer(layerType, precisionStr, params, inOutShapes, weightsSize, biasesSize, layerDataName);
    std::string testContent;
    if (inputsNumber > 1) {
        auto edgeBuilder = netBuilder.havingEdges();
        for (size_t i = 0lu; i < inputsNumber; i++) {
            edgeBuilder.connect(i, inputsNumber);
        }
        testContent = edgeBuilder.finish();
    } else {
        testContent = netBuilder.finish();
    }
    xmlHelper.loadContent(testContent);
    auto result = xmlHelper.parseWithReturningNetwork();
    if (weights) xmlHelper.setWeights(weights);
    return result;
}

void GenRandomDataCommon(InferenceEngine::Blob::Ptr blob);

class BufferWrapper {
    InferenceEngine::Precision precision;
    InferenceEngine::ie_fp16 *fp16_ptr;
    float *fp32_ptr;
public:
    explicit BufferWrapper(const InferenceEngine::Blob::Ptr &blob);

    BufferWrapper(const InferenceEngine::Blob::Ptr &blob, InferenceEngine::Precision precision);

    float operator[](size_t index);

    void insert(size_t index, float value);
};

void
CompareCommon(const InferenceEngine::Blob::Ptr &actual, const InferenceEngine::Blob::Ptr &expected, float tolerance);

void fill_data_common(BufferWrapper &data, size_t size, size_t duty_ratio = 10);

max_stars_repo_name: zhoub/dldt

max_issues_repo_name: zhoub/dldt

max_forks_repo_name: zhoub/dldt


text:
#include <metal.hpp>
#include <boost/pfr.hpp>
#include <iostream>
#include <utility>
#include <tuple>
#include <string>

// Just some quick getting started finger exercises for metal/pfr
// Will remove later on

struct pod_type
{
    // plain pod type with lots of padding internally to test reflection on
    int i1;
    double d1;
    char c1;
    size_t sz1[4];
    void * p1;
    float f1;
    short s1;
    int * ip2[2];
};

// metal mapping from type to python struct character code
// this is just a partial mapping for now. Will need to be extended and will have to
// handle array types also which will require some sort of transform
template <typename T>
using map_to_struct_code = metal::at_key<
metal::map<
    metal::pair<int, metal::number<'i'>>,
    metal::pair<double, metal::number<'d'>>,
    metal::pair<char, metal::number<'c'>>,
    metal::pair<size_t, metal::number<'Q'>>,
    metal::pair<float, metal::number<'f'>>,
    metal::pair<short, metal::number<'h'>>
>, T>;

// To handle array types, initially map out the tuples from pfr into
// scalar and array elements based on the metal mapping
template <typename T>
struct tuple_element
{
    using value = map_to_struct_code<T>;
    static constexpr bool array = false;
};

template <typename T>
struct tuple_element<T*>
{

    using value = metal::number<'p'>;
    static constexpr bool array = false;
};

// Just supports single dim for now. Todo: Generalize to more dimensions
template <typename T, size_t N>
struct tuple_element<T[N]>
{
    using value = map_to_struct_code<T>;
    static constexpr bool array = true;
    static constexpr size_t length = N;
};

template <typename T, size_t N>
struct tuple_element<T*[N]>
{
    using value = metal::number<'p'>;
    static constexpr bool array = true;
    static constexpr size_t length = N;
};

template <typename ...Args>
struct extract_tuple_element_impl
{
    using type = metal::transform<metal::lambda<tuple_element>, metal::list<Args...>>;
};

template <template <typename ...> class T, typename ... Args>
auto extract_tuple_elements(T<Args...> prototype)
{
    return extract_tuple_element_impl<Args...>();
}

template <typename T, bool = T::array>
struct extract_value_impl;

template <typename T>
struct extract_value_impl<T, false>
{
    static std::string extract()
    {
        std::string s;
        s += T::value::value;
        return s;
    }
};

template <typename T>
struct extract_value_impl<T, true>
{
    static std::string extract()
    {
        std::string s;
        using std::to_string;
        s += to_string(T::length);
        s += T::value;
        return s;
    }
};

template <typename T>
std::string extract_value()
{
    return extract_value_impl<T>::extract();
}

template <typename ...Args>
auto realize_tuple(metal::list<Args...> metal_list)
{
    return std::make_tuple(extract_value<Args>()...);
}

int main()
{
    auto s1 = boost::pfr::flat_structure_to_tuple(pod_type());
    using m1 = decltype(extract_tuple_elements(s1))::type;

    // Upto here, the elements of interest are encoded in the type signature of
    // a metal::list. This step now makes a real tuple out of that signature
    auto result = realize_tuple(m1());

    // Now the last bit is to turn that tuple into a string
    // See this stackoverflow post:
    // https://stackoverflow.com/questions/1198260/how-can-you-iterate-over-the-elements-of-an-stdtuple
    // TODO: Figure out what exactly this is doing.
    std::string py_struct_format;
    std::apply([&py_struct_format](auto&&... args) {(py_struct_format += (args +...));}, result);

    std::cout << py_struct_format << std::endl;
    return 0;
}


text:
#pragma once

#include <chrono>
#include <fstream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>

#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>

#include "typedefs.hpp"

enum class LogLevel { trace, debug, info, warning, error, fatal };

class Logger {
 public:
  static Logger& get()
  {
    static Logger S;
    return S;
  }

  void disable();
  void enable();

  void               initLogFile(std::string file, LogLevel lvl = LogLevel::trace);
  const std::string& logFilename() const { return log_filename_; }
  void               closeLogFile();
  void               setLogLevel(LogLevel lvl);

  void updateLog();

  void setTimeMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
  void setResidualMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
  void setSolutionMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);

  const std::vector<std::pair<std::string, double>> getTimeMonitor() const { return time_status_; }
  const std::vector<std::pair<std::string, double>> getResidualMonitor() const { return residual_status_; }
  const std::vector<std::pair<std::string, double>> getSolutionMonitor() const { return solution_status_; }

  void Message(const std::string& str, LogLevel lvl);
  void TraceMessage(std::string str);
  void DebugMessage(std::string str);
  void InfoMessage(std::string str);
  void WarningMessage(std::string str);
  void ErrorMessage(std::string str);
  void FatalMessage(std::string str);
  void WarningAssert(bool, const std::string&);
  void FatalAssert(bool, const std::string&);

  void logDeviceMemoryTransfer(const std::string& description);
  void closeDeviceMemoryTransferLog();

  class Timer {
   public:
    Timer(const std::string& msg, const LogLevel log_level);
    virtual ~Timer();
    real_t elapsed();

   protected:
    const std::chrono::time_point<std::chrono::high_resolution_clock> start_;
    const std::string                                                 msg_;
    const LogLevel                                                    log_level_;
    bool                                                              elapsed_called_;
  };

  Timer timer(const std::string& msg, const LogLevel log_level = LogLevel::trace) { return Timer(msg, log_level); }

 private:
  Logger();
  ~Logger() = default;
  static std::string makeBanner();

  const std::string banner_;
  std::string       log_filename_;

  int_t n_update_calls_;

  bool initialized_;
  bool auto_flush_;
  bool log_level_overridden_ = false;

  std::unique_ptr<std::ofstream> memlog_;
  int_t                          n_device_to_host_copies_ = 0;

  std::vector<std::pair<std::string, double>> time_status_;
  std::vector<std::pair<std::string, double>> residual_status_;
  std::vector<std::pair<std::string, double>> solution_status_;

  boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_file_backend>>    g_file_sink_;
  boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend>> g_console_sink_;
};

max_stars_repo_name: mlohry/maDGiCart-CH

max_issues_repo_name: mlohry/maDGiCart-CH

max_forks_repo_name: mlohry/maDGiCart-CH


text:
//
// Copyright (c) 2015-2018 CNRS
// Copyright (c) 2015-2016 Wandercraft, 86 rue de Paris 91400 Orsay, France.
//

#ifndef __pinocchio_joint_planar_hpp__
#define __pinocchio_joint_planar_hpp__

#include "pinocchio/macros.hpp"
#include "pinocchio/multibody/joint/joint-base.hpp"
#include "pinocchio/spatial/cartesian-axis.hpp"
#include "pinocchio/multibody/constraint.hpp"
#include "pinocchio/spatial/motion.hpp"
#include "pinocchio/spatial/inertia.hpp"

namespace pinocchio
{

  template<typename Scalar, int Options = 0> struct MotionPlanarTpl;
  typedef MotionPlanarTpl<double> MotionPlanar;

  namespace internal
  {
    template<typename Scalar, int Options>
    struct SE3GroupAction< MotionPlanarTpl<Scalar,Options> >
    {
      typedef MotionTpl<Scalar,Options> ReturnType;
    };

    template<typename Scalar, int Options, typename MotionDerived>
    struct MotionAlgebraAction< MotionPlanarTpl<Scalar,Options>, MotionDerived>
    {
      typedef MotionTpl<Scalar,Options> ReturnType;
    };
  }

  template<typename _Scalar, int _Options>
  struct traits< MotionPlanarTpl<_Scalar,_Options> >
  {
    typedef _Scalar Scalar;
    enum { Options = _Options };
    typedef Eigen::Matrix<Scalar,3,1,Options> Vector3;
    typedef Eigen::Matrix<Scalar,6,1,Options> Vector6;
    typedef Eigen::Matrix<Scalar,6,6,Options> Matrix6;
    typedef typename EIGEN_REF_CONSTTYPE(Vector6) ToVectorConstReturnType;
    typedef typename EIGEN_REF_TYPE(Vector6) ToVectorReturnType;
    typedef Vector3 AngularType;
    typedef Vector3 LinearType;
    typedef const Vector3 ConstAngularType;
    typedef const Vector3 ConstLinearType;
    typedef Matrix6 ActionMatrixType;
    typedef MotionTpl<Scalar,Options> MotionPlain;
    enum {
      LINEAR = 0,
      ANGULAR = 3
    };
  }; // traits MotionPlanarTpl

  template<typename _Scalar, int _Options>
  struct MotionPlanarTpl : MotionBase< MotionPlanarTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    MOTION_TYPEDEF_TPL(MotionPlanarTpl);

    typedef CartesianAxis<2> AxisZ;

    MotionPlanarTpl() {}

    MotionPlanarTpl(const Scalar & x_dot, const Scalar & y_dot,
                    const Scalar & theta_dot)
    : m_x_dot(x_dot), m_y_dot(y_dot), m_theta_dot(theta_dot)
    {}

    template<typename Vector3Like>
    MotionPlanarTpl(const Eigen::MatrixBase<Vector3Like> & vj)
    : m_x_dot(vj[0]), m_y_dot(vj[1]), m_theta_dot(vj[2])
    {
      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector3Like,3);
    }

//    operator MotionPlain() const
//    {
//      return MotionPlain(typename MotionPlain::Vector3(m_x_dot,m_y_dot,Scalar(0)),
//                         typename MotionPlain::Vector3(Scalar(0),Scalar(0),m_theta_dot));
//    }

    template<typename Derived>
    void addTo(MotionDense<Derived> & other) const
    {
      other.linear()[0] += m_x_dot;
      other.linear()[1] += m_y_dot;
      other.angular()[2] += m_theta_dot;
    }

    template<typename MotionDerived>
    void setTo(MotionDense<MotionDerived> & other) const
    {
      other.linear()  <<   m_x_dot,   m_y_dot,   (Scalar)0;
      other.angular() << (Scalar)0, (Scalar)0, m_theta_dot;
    }

    template<typename S2, int O2, typename D2>
    void se3Action_impl(const SE3Tpl<S2,O2> & m, MotionDense<D2> & v) const
    {
      v.angular().noalias() = m.rotation().col(2) * m_theta_dot;
      v.linear().noalias() = m.translation().cross(v.angular());
      v.linear() += m.rotation().col(0) * m_x_dot;
      v.linear() += m.rotation().col(1) * m_y_dot;
    }

    template<typename S2, int O2>
    MotionPlain se3Action_impl(const SE3Tpl<S2,O2> & m) const
    {
      MotionPlain res;
      se3Action_impl(m,res);
      return res;
    }

    template<typename S2, int O2, typename D2>
    void se3ActionInverse_impl(const SE3Tpl<S2,O2> & m, MotionDense<D2> & v) const
    {
      // Linear
      // TODO: use v.angular() as temporary variable
      Vector3 v3_tmp;
      AxisZ::alphaCross(m_theta_dot,m.translation(),v3_tmp);
      v3_tmp[0] += m_x_dot; v3_tmp[1] += m_y_dot;
      v.linear().noalias() = m.rotation().transpose() * v3_tmp;

      // Angular
      v.angular().noalias() = m.rotation().transpose().col(2) * m_theta_dot;
    }

    template<typename S2, int O2>
    MotionPlain se3ActionInverse_impl(const SE3Tpl<S2,O2> & m) const
    {
      MotionPlain res;
      se3ActionInverse_impl(m,res);
      return res;
    }

    template<typename M1, typename M2>
    void motionAction(const MotionDense<M1> & v, MotionDense<M2> & mout) const
    {
      // Linear
      AxisZ::alphaCross(-m_theta_dot,v.linear(),mout.linear());

      typename M1::ConstAngularType w_in = v.angular();
      typename M2::LinearType v_out = mout.linear();

      v_out[0] -= w_in[2] * m_y_dot;
      v_out[1] += w_in[2] * m_x_dot;
      v_out[2] += -w_in[1] * m_x_dot + w_in[0] * m_y_dot ;

      // Angular
      AxisZ::alphaCross(-m_theta_dot,v.angular(),mout.angular());
    }

    template<typename M1>
    MotionPlain motionAction(const MotionDense<M1> & v) const
    {
      MotionPlain res;
      motionAction(v,res);
      return res;
    }

    // data
    Scalar m_x_dot;
    Scalar m_y_dot;
    Scalar m_theta_dot;

  }; // struct MotionPlanarTpl

  template<typename Scalar, int Options, typename MotionDerived>
  inline typename MotionDerived::MotionPlain
  operator+(const MotionPlanarTpl<Scalar,Options> & m1, const MotionDense<MotionDerived> & m2)
  {
    typename MotionDerived::MotionPlain result(m2);
    result.linear()[0] += m1.m_x_dot;
    result.linear()[1] += m1.m_y_dot;

    result.angular()[2] += m1.m_theta_dot;

    return result;
  }

  template<typename Scalar, int Options> struct ConstraintPlanarTpl;

  template<typename _Scalar, int _Options>
  struct traits< ConstraintPlanarTpl<_Scalar,_Options> >
  {
    typedef _Scalar Scalar;
    enum { Options = _Options };
    typedef Eigen::Matrix<Scalar,3,1,Options> Vector3;
    typedef Eigen::Matrix<Scalar,4,1,Options> Vector4;
    typedef Eigen::Matrix<Scalar,6,1,Options> Vector6;
    typedef Eigen::Matrix<Scalar,3,3,Options> Matrix3;
    typedef Eigen::Matrix<Scalar,4,4,Options> Matrix4;
    typedef Eigen::Matrix<Scalar,6,6,Options> Matrix6;
    typedef Matrix3 Angular_t;
    typedef Vector3 Linear_t;
    typedef const Matrix3 ConstAngular_t;
    typedef const Vector3 ConstLinear_t;
    typedef Matrix6 ActionMatrix_t;
    typedef Eigen::Quaternion<Scalar,Options> Quaternion_t;
    typedef SE3Tpl<Scalar,Options> SE3;
    typedef ForceTpl<Scalar,Options> Force;
    typedef MotionTpl<Scalar,Options> Motion;
    typedef Symmetric3Tpl<Scalar,Options> Symmetric3;
    enum {
      LINEAR = 0,
      ANGULAR = 3
    };
    typedef MotionPlanarTpl<Scalar,Options> JointMotion;
    typedef Eigen::Matrix<Scalar,3,1,Options> JointForce;
    typedef Eigen::Matrix<Scalar,6,3,Options> DenseBase;
    typedef DenseBase MatrixReturnType;
    typedef const DenseBase ConstMatrixReturnType;
  }; // struct traits ConstraintPlanarTpl

  template<typename _Scalar, int _Options>
  struct ConstraintPlanarTpl : ConstraintBase< ConstraintPlanarTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    SPATIAL_TYPEDEF_TEMPLATE(ConstraintPlanarTpl);

    enum { NV = 3, Options = _Options }; // to check
    typedef typename traits<ConstraintPlanarTpl>::JointMotion JointMotion;
    typedef typename traits<ConstraintPlanarTpl>::JointForce JointForce;
    typedef typename traits<ConstraintPlanarTpl>::DenseBase DenseBase;

    template<typename Vector3Like>
    JointMotion __mult__(const Eigen::MatrixBase<Vector3Like> & vj) const
    {
      EIGEN_STATIC_ASSERT_VECTOR_SPECIFIC_SIZE(Vector3Like,3);
      return JointMotion(vj);
    }

    int nv_impl() const { return NV; }

    struct ConstraintTranspose
    {
      const ConstraintPlanarTpl & ref;
      ConstraintTranspose(const ConstraintPlanarTpl & ref) : ref(ref) {}

      template<typename Derived>
      typename ForceDense<Derived>::Vector3 operator* (const ForceDense<Derived> & phi)
      {
        typedef typename ForceDense<Derived>::Vector3 Vector3;
        return Vector3(phi.linear()[0], phi.linear()[1], phi.angular()[2]);
      }

      /* [CRBA]  MatrixBase operator* (Constraint::Transpose S, ForceSet::Block) */
      template<typename Derived>
      friend typename Eigen::Matrix <typename Eigen::MatrixBase<Derived>::Scalar, 3, Derived::ColsAtCompileTime>
      operator*(const ConstraintTranspose &, const Eigen::MatrixBase<Derived> & F)
      {
        typedef typename Eigen::MatrixBase<Derived>::Scalar Scalar;
        typedef Eigen::Matrix<Scalar, 3, Derived::ColsAtCompileTime> MatrixReturnType;
        assert(F.rows()==6);

        MatrixReturnType result(3, F.cols ());
        result.template topRows<2>() = F.template topRows<2>();
        result.template bottomRows<1>() = F.template bottomRows<1>();
        return result;
      }

    }; // struct ConstraintTranspose

    ConstraintTranspose transpose () const { return ConstraintTranspose(*this); }

    DenseBase matrix_impl() const
    {
      DenseBase S;
      S.template block<3,3>(Inertia::LINEAR, 0).setZero ();
      S.template block<3,3>(Inertia::ANGULAR, 0).setZero ();
      S(Inertia::LINEAR + 0,0) = Scalar(1);
      S(Inertia::LINEAR + 1,1) = Scalar(1);
      S(Inertia::ANGULAR + 2,2) = Scalar(1);
      return S;
    }

    template<typename S1, int O1>
    DenseBase se3Action(const SE3Tpl<S1,O1> & m) const
    {
      DenseBase X_subspace;
      X_subspace.template block <3,2>(Motion::LINEAR, 0) = m.rotation ().template leftCols <2> ();
      X_subspace.template block <3,1>(Motion::LINEAR, 2) = m.translation().cross(m.rotation ().template rightCols<1>());

      X_subspace.template block <3,2>(Motion::ANGULAR, 0).setZero ();
      X_subspace.template block <3,1>(Motion::ANGULAR, 2) = m.rotation ().template rightCols<1>();

      return X_subspace;
    }

    template<typename MotionDerived>
    DenseBase motionAction(const MotionDense<MotionDerived> & m) const
    {
      const typename MotionDerived::ConstLinearType v = m.linear();
      const typename MotionDerived::ConstAngularType w = m.angular();
      DenseBase res(DenseBase::Zero());

      res(0,1) = -w[2]; res(0,2) = v[1];
      res(1,0) = w[2]; res(1,2) = -v[0];
      res(2,0) = -w[1]; res(2,1) = w[0];
      res(3,2) = w[1];
      res(4,2) = -w[0];

      return res;
    }
  }; // struct ConstraintPlanarTpl

  template<typename MotionDerived, typename S2, int O2>
  inline typename MotionDerived::MotionPlain
  operator^(const MotionDense<MotionDerived> & m1, const MotionPlanarTpl<S2,O2> & m2)
  {
    return m2.motionAction(m1);
  }

  /* [CRBA] ForceSet operator* (Inertia Y,Constraint S) */
  template<typename S1, int O1, typename S2, int O2>
  inline typename Eigen::Matrix<S1,6,3,O1>
  operator*(const InertiaTpl<S1,O1> & Y, const ConstraintPlanarTpl<S2,O2> &)
  {
    typedef InertiaTpl<S1,O1> Inertia;
    typedef typename Inertia::Scalar Scalar;
    typedef Eigen::Matrix<S1,6,3,O1> ReturnType;

    ReturnType M;
    const Scalar mass = Y.mass();
    const typename Inertia::Vector3 & com = Y.lever();
    const typename Inertia::Symmetric3 & inertia = Y.inertia();

    M.template topLeftCorner<3,3>().setZero();
    M.template topLeftCorner<2,2>().diagonal().fill(mass);

    const typename Inertia::Vector3 mc(mass * com);
    M.template rightCols<1>().template head<2>() << -mc(1), mc(0);

    M.template bottomLeftCorner<3,2>() << (Scalar)0, -mc(2), mc(2), (Scalar)0, -mc(1), mc(0);
    M.template rightCols<1>().template tail<3>() = inertia.data().template tail<3>();
    M.template rightCols<1>()[3] -= mc(0)*com(2);
    M.template rightCols<1>()[4] -= mc(1)*com(2);
    M.template rightCols<1>()[5] += mass*(com(0)*com(0) + com(1)*com(1));

    return M;
  }

  /* [ABA] Y*S operator (Inertia Y,Constraint S) */
  //  inline Eigen::Matrix<double,6,1>

  template<typename M6Like, typename S2, int O2>
  inline Eigen::Matrix<S2,6,3,O2>
  operator*(const Eigen::MatrixBase<M6Like> & Y,
            const ConstraintPlanarTpl<S2,O2> &)
  {
    EIGEN_STATIC_ASSERT_MATRIX_SPECIFIC_SIZE(M6Like,6,6);
    typedef Eigen::Matrix<S2,6,3,O2> Matrix63;

    Matrix63 IS;
    IS.template leftCols<2>() = Y.template leftCols<2>();
    IS.template rightCols<1>() = Y.template rightCols<1>();

    return IS;
  }

  namespace internal
  {
    template<typename S1, int O1>
    struct SE3GroupAction< ConstraintPlanarTpl<S1,O1> >
    { typedef Eigen::Matrix<S1,6,3,O1> ReturnType; };

    template<typename S1, int O1, typename MotionDerived>
    struct MotionAlgebraAction< ConstraintPlanarTpl<S1,O1>,MotionDerived >
    { typedef Eigen::Matrix<S1,6,3,O1> ReturnType; };
  }

  template<typename Scalar, int Options> struct JointPlanarTpl;

  template<typename _Scalar, int _Options>
  struct traits< JointPlanarTpl<_Scalar,_Options> >
  {
    enum {
      NQ = 4,
      NV = 3
    };
    enum { Options = _Options };
    typedef _Scalar Scalar;
    typedef JointDataPlanarTpl<Scalar,Options> JointDataDerived;
    typedef JointModelPlanarTpl<Scalar,Options> JointModelDerived;
    typedef ConstraintPlanarTpl<Scalar,Options> Constraint_t;
    typedef SE3Tpl<Scalar,Options> Transformation_t;
    typedef MotionPlanarTpl<Scalar,Options> Motion_t;
    typedef BiasZeroTpl<Scalar,Options> Bias_t;
    typedef Eigen::Matrix<Scalar,6,NV,Options> F_t;

    // [ABA]
    typedef Eigen::Matrix<Scalar,6,NV,Options> U_t;
    typedef Eigen::Matrix<Scalar,NV,NV,Options> D_t;
    typedef Eigen::Matrix<Scalar,6,NV,Options> UD_t;

    JOINT_DATA_BASE_ACCESSOR_DEFAULT_RETURN_TYPE

    typedef Eigen::Matrix<Scalar,NQ,1,Options> ConfigVector_t;
    typedef Eigen::Matrix<Scalar,NV,1,Options> TangentVector_t;
  };

  template<typename Scalar, int Options>
  struct traits< JointDataPlanarTpl<Scalar,Options> > { typedef JointPlanarTpl<Scalar,Options> JointDerived; };
  template<typename Scalar, int Options>
  struct traits< JointModelPlanarTpl<Scalar,Options> > { typedef JointPlanarTpl<Scalar,Options> JointDerived; };

  template<typename _Scalar, int _Options>
  struct JointDataPlanarTpl : public JointDataBase< JointDataPlanarTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef JointPlanarTpl<_Scalar,_Options> JointDerived;
    PINOCCHIO_JOINT_DATA_TYPEDEF_TEMPLATE;
    JOINT_DATA_BASE_DEFAULT_ACCESSOR

    Constraint_t S;
    Transformation_t M;
    Motion_t v;
    Bias_t c;

    F_t F; // TODO if not used anymore, clean F_t

    // [ABA] specific data
    U_t U;
    D_t Dinv;
    UD_t UDinv;

    D_t StU;

    JointDataPlanarTpl () : M(1), U(), Dinv(), UDinv() {}

  }; // struct JointDataPlanarTpl

  JOINT_CAST_TYPE_SPECIALIZATION(JointModelPlanarTpl);
  template<typename _Scalar, int _Options>
  struct JointModelPlanarTpl
  : public JointModelBase< JointModelPlanarTpl<_Scalar,_Options> >
  {
    EIGEN_MAKE_ALIGNED_OPERATOR_NEW
    typedef JointPlanarTpl<_Scalar,_Options> JointDerived;
    SE3_JOINT_TYPEDEF_TEMPLATE;

    typedef JointModelBase<JointModelPlanarTpl> Base;
    using Base::id;
    using Base::idx_q;
    using Base::idx_v;
    using Base::setIndexes;

    JointDataDerived createData() const { return JointDataDerived(); }

    template<typename ConfigVector>
    inline void forwardKinematics(Transformation_t & M, const Eigen::MatrixBase<ConfigVector> & q_joint) const
    {
      const Scalar
      & c_theta = q_joint(2),
      & s_theta = q_joint(3);

      M.rotation().template topLeftCorner<2,2>() << c_theta, -s_theta, s_theta, c_theta;
      M.translation().template head<2>() = q_joint.template head<2>();
    }

    template<typename ConfigVector>
    void calc(JointDataDerived & data,
              const typename Eigen::MatrixBase<ConfigVector> & qs) const
    {
      typedef typename ConfigVector::Scalar Scalar;
      typename ConfigVector::template ConstFixedSegmentReturnType<NQ>::Type & q = qs.template segment<NQ>(idx_q());

      const Scalar
      &c_theta = q(2),
      &s_theta = q(3);

      data.M.rotation().template topLeftCorner<2,2>() << c_theta, -s_theta, s_theta, c_theta;
      data.M.translation().template head<2>() = q.template head<2>();

    }

    template<typename ConfigVector, typename TangentVector>
    void calc(JointDataDerived & data,
              const typename Eigen::MatrixBase<ConfigVector> & qs,
              const typename Eigen::MatrixBase<TangentVector> & vs) const
    {
      calc(data,qs.derived());

      typename TangentVector::template ConstFixedSegmentReturnType<NV>::Type & q_dot = vs.template segment<NV>(idx_v ());

      data.v.m_x_dot = q_dot(0);
      data.v.m_y_dot = q_dot(1);
      data.v.m_theta_dot = q_dot(2);
    }

    template<typename Matrix6Like>
    void calc_aba(JointDataDerived & data, const Eigen::MatrixBase<Matrix6Like> & I, const bool update_I) const
    {
      data.U.template leftCols<2>() = I.template leftCols<2>();
      data.U.template rightCols<1>() = I.template rightCols<1>();

      data.StU.template leftCols<2>() = data.U.template topRows<2>().transpose();
      data.StU.template rightCols<1>() = data.U.template bottomRows<1>();

      // compute inverse
      data.Dinv.setIdentity();
      data.StU.llt().solveInPlace(data.Dinv);

      data.UDinv.noalias() = data.U * data.Dinv;

      if (update_I)
        EIGEN_CONST_CAST(Matrix6Like,I) -= data.UDinv * data.U.transpose();
    }

    Scalar finiteDifferenceIncrement() const
    {
      using math::sqrt;
      return 2.*sqrt(sqrt(Eigen::NumTraits<Scalar>::epsilon()));
    }

    static std::string classname() { return std::string("JointModelPlanar");}
    std::string shortname() const { return classname(); }

    /// \returns An expression of *this with the Scalar type casted to NewScalar.
    template<typename NewScalar>
    JointModelPlanarTpl<NewScalar,Options> cast() const
    {
      typedef JointModelPlanarTpl<NewScalar,Options> ReturnType;
      ReturnType res;
      res.setIndexes(id(),idx_q(),idx_v());
      return res;
    }

  }; // struct JointModelPlanarTpl

} // namespace pinocchio

#include <boost/type_traits.hpp>

namespace boost
{
  template<typename Scalar, int Options>
  struct has_nothrow_constructor< ::pinocchio::JointModelPlanarTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};

  template<typename Scalar, int Options>
  struct has_nothrow_copy< ::pinocchio::JointModelPlanarTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};

  template<typename Scalar, int Options>
  struct has_nothrow_constructor< ::pinocchio::JointDataPlanarTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};

  template<typename Scalar, int Options>
  struct has_nothrow_copy< ::pinocchio::JointDataPlanarTpl<Scalar,Options> >
  : public integral_constant<bool,true> {};
}

#endif // ifndef __pinocchio_joint_planar_hpp__

max_stars_repo_name: matthieuvigne/pinocchio

max_issues_repo_name: matthieuvigne/pinocchio

max_forks_repo_name: matthieuvigne/pinocchio


text:
#pragma once
#include "testlib.h"
#include <functional>
#include <boost/any.hpp>

using namespace std;
using namespace boost;

void generate(string title, function<void(stringstream&)> func, int mx = 20) {
  for (int i = 0; i < mx; ++i) {
    stringstream ss;
    func(ss);
    string id = string(to_string(mx - 1).size() - to_string(i).size(), '0') + to_string(i);
    ofstream ofs((title + id + ".in").c_str());
    ofs << ss.str();
  }
}

bool next(map<string, int>& id, const map<string, vector<any>>& args) {
  for (const auto& itr : args) {
    ++id[itr.first];
    if (id[itr.first] < int(itr.second.size())) return true;
    id[itr.first] = 0;
  }
  return false;
}

void generate_combination(string title, function<void(stringstream&, const map<string, any>&)> func, const map<string, vector<any>>& args, int mx = 1) {
  map<string, int> index;
  int mx_ = mx;
  for (const auto& itr : args) {
    index[itr.first] = 0;
    mx_ *= itr.second.size();
  }
  for (int i = 0; ; ++i) {
    for (int j = 0; j < mx; ++j) {
      map<string, any> a;
      for (const auto& itr : args) a[itr.first] = itr.second[index[itr.first]];
      stringstream ss;
      func(ss, a);
      string id = string(to_string(mx_ - 1).size() - to_string(i * mx + j).size(), '0') + to_string(i * mx + j);
      ofstream ofs((title + id + ".in").c_str());
      ofs << ss.str();
    }
    if (!next(index, args)) break;
  }
}


text:
/**
*   AreaOperation.hpp
*
*   Copyright 2015 The Climate Corporation
*   Copyright 2015 Tony Stone
*
*   Licensed 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.
*
*   Created by Tony Stone on 6/11/15.
*
*   MODIFIED 2015 BY Tony Stone. Modifications licensed under Apache License, Version 2.0.
*
*/

#ifndef __AreaOperation_HPP_
#define __AreaOperation_HPP_

#include <boost/variant/variant.hpp>
#include <boost/geometry/strategies/strategies.hpp>
#include <boost/geometry/algorithms/area.hpp>

#include "GFGeometryVariant.hpp"

namespace geofeatures {
    namespace operators {

        namespace detail {

            struct area {

                class Visitor : public  boost::static_visitor<double> {

                public:
                    template <typename T>
                    double operator()(const T * v) const {
                        return boost::geometry::area(*v);
                    }

                    double operator()(const GeometryCollection<> * collection) const {
                        double area = 0.0;

                        for (auto it = collection->begin(); it != collection->end(); ++it ) {
                            area += boost::geometry::area(*it);
                        }
                        return area;
                    }
                };

                template <BOOST_VARIANT_ENUM_PARAMS(typename T1)>
                static inline double apply(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const & variant)
                {
                    return boost::apply_visitor(Visitor(), variant);
                }
            };
        }   // namespace detail

        /**
         * area algorithm.
         */
        template <BOOST_VARIANT_ENUM_PARAMS(typename T1)>
        inline double area(boost::variant<BOOST_VARIANT_ENUM_PARAMS(T1)> const & variant)
        {
            return detail::area::apply(variant);
        }

    }   // namespace operators
}   // namespace geofeatures

#endif //__AreaOperator_HPP_

max_stars_repo_name: tonystone/geofeatures

max_issues_repo_name: tonystone/geofeatures

max_forks_repo_name: tonystone/geofeatures


text:
/*
 * Software License Agreement (Modified BSD License)
 *
 *  Copyright (c) 2016, PAL Robotics, S.L.
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   * Neither the name of PAL Robotics, S.L. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 *  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 *  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 *  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 *  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 *  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
 *  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *  POSSIBILITY OF SUCH DAMAGE.
 */

/** \author Jordi Pages. */

// C++ standard headers
#include <exception>
#include <string>

// Boost headers
#include <boost/shared_ptr.hpp>

// ROS headers
#include <ros/ros.h>
#include <actionlib/client/simple_action_client.h>
#include <play_motion_msgs/PlayMotionAction.h>

// C++ standard headers
#include <cstdlib>

int main(int argc, char** argv)
{
  // Init the ROS node
  ros::init(argc, argv, "run_motion");

  if ( argc < 2 )
  {
      ROS_INFO(" ");
      ROS_INFO("Usage:");
      ROS_INFO(" ");
      ROS_INFO("\trosrun run_motion run_motion MOTION_NAME");
      ROS_INFO(" ");
      ROS_INFO("\twhere MOTION_NAME must be one of the motions listed in: ");
      ROS_INFO_STREAM(std::system("rosparam list /play_motion/motions | grep joints | cut -d'/' -f4"));
      ROS_INFO(" ");
      return EXIT_FAILURE;
  }

  ROS_INFO("Starting run_motion application ...");

  // Precondition: Valid clock
  ros::NodeHandle nh;
  if (!ros::Time::waitForValid(ros::WallDuration(10.0))) // NOTE: Important when using simulated clock
  {
    ROS_FATAL("Timed-out waiting for valid time.");
    return EXIT_FAILURE;
  }

  actionlib::SimpleActionClient<play_motion_msgs::PlayMotionAction> client("/play_motion", true);

  ROS_INFO("Waiting for Action Server ...");
  client.waitForServer();

  play_motion_msgs::PlayMotionGoal goal;

  goal.motion_name = argv[1];
  goal.skip_planning = false;
  goal.priority = 0;

  ROS_INFO_STREAM("Sending goal with motion: " << argv[1]);
  client.sendGoal(goal);

  ROS_INFO("Waiting for result ...");
  bool actionOk = client.waitForResult(ros::Duration(30.0));

  actionlib::SimpleClientGoalState state = client.getState();

  if ( actionOk )
  {
      ROS_INFO_STREAM("Action finished successfully with state: " << state.toString());
  }
  else
  {
      ROS_ERROR_STREAM("Action failed with state: " << state.toString());
  }

  return EXIT_SUCCESS;
}


text:
//---------------------------------------------------------------------------//
//!
//! \file   Utility_SpatialCoordinateConversionPolicy.hpp
//! \author Alex Robinson
//! \brief  Spatial coordinate conversion policy declaration
//!
//---------------------------------------------------------------------------//

#ifndef UTILITY_SPATIAL_COORDINATE_CONVERSION_POLICY_HPP
#define UTILITY_SPATIAL_COORDINATE_CONVERSION_POLICY_HPP

// Boost Includes
#include <boost/serialization/split_member.hpp>

// FRENSIE Includes
#include "Utility_SpatialCoordinateSystemType.hpp"
#include "Utility_SpatialCoordinateSystemTraits.hpp"
#include "Utility_SerializationHelpers.hpp"
#include "Utility_ExplicitSerializationTemplateInstantiationMacros.hpp"

namespace Utility{

//! The spatial coordinate conversion policy class
class SpatialCoordinateConversionPolicy
{

protected:

  //! The global coordinate system traits
  typedef SpatialCoordinateSystemTraits<CARTESIAN_SPATIAL_COORDINATE_SYSTEM> GlobalCSTraits;

public:

  //! Constructor
  SpatialCoordinateConversionPolicy()
  { /* ... */ }

  //! Destructor
  virtual ~SpatialCoordinateConversionPolicy()
  { /* ... */ }

  //! Get the local coordinate system type
  virtual SpatialCoordinateSystemType getLocalSpatialCoordinateSystemType() const = 0;

  //! Check if the primary spatial coordinate is valid
  virtual bool isPrimarySpatialCoordinateValid( const double coordinate ) const = 0;

  //! Check if the secondary spatial coordinate is valid
  virtual bool isSecondarySpatialCoordinateValid( const double coordinate ) const = 0;

  //! Check if the tertiary spatial coordinate is valid
  virtual bool isTertiarySpatialCoordinateValid( const double coordinate ) const = 0;

  //! Convert the spatial coordinates to cartesian coordinates
  virtual void convertToCartesianSpatialCoordinates(
                                          const double primary_spatial_coord,
                                          const double secondary_spatial_coord,
                                          const double tertiary_spatial_coord,
                                          double& x_spatial_coord,
                                          double& y_spatial_coord,
                                          double& z_spatial_coord ) const = 0;

  //! Convert the spatial coordinates to cartesian coordinates
  void convertToCartesianSpatialCoordinates(
                                       const double coordinates[3],
                                       double cartesian_coordinates[3] ) const;

  //! Convert the cartesian coordinates to the spatial coordinate system
  virtual void convertFromCartesianSpatialCoordinates(
                                    const double x_spatial_coord,
                                    const double y_spatial_coord,
                                    const double z_spatial_coord,
                                    double& primary_spatial_coord,
                                    double& secondary_spatial_coord,
                                    double& tertiary_spatial_coord ) const = 0;

  //! Convert the cartesian coordinates to the spatial coordinate system
  void convertFromCartesianSpatialCoordinates(
                                         const double cartesian_coordinates[3],
                                         double coordinates[3] ) const;

protected:

  //! Translate a global Cartesian position to a local Cartesian position
  static void translateGlobalCartesianPositionToLocalCartesianPosition(
                          const double global_x_position,
                          const double global_y_position,
                          const double global_z_position,
                          const double local_origin_wrt_global_coord_system[3],
                          double& local_x_position,
                          double& local_y_position,
                          double& local_z_position );

  //! Translate a local Cartesian position to a global Cartesian position
  static void translateLocalCartesianPositionToGlobalCartesianPosition(
                          const double local_x_position,
                          const double local_y_position,
                          const double local_z_position,
                          const double local_origin_wrt_global_coord_system[3],
                          double& global_x_position,
                          double& global_y_position,
                          double& global_z_position );

private:

  // Save the policy to an archive
  template<typename Archive>
  void serialize( Archive& ar, const unsigned version )
  { /* ... */ }

  // Declare the boost serialization access object as a friend
  friend class boost::serialization::access;
};

//---------------------------------------------------------------------------//
// Inline Definitions
//---------------------------------------------------------------------------//

// Convert the spatial coordinates to cartesian coordinates
inline void SpatialCoordinateConversionPolicy::convertToCartesianSpatialCoordinates(
                                        const double coordinates[3],
                                        double cartesian_coordinates[3] ) const
{
  this->convertToCartesianSpatialCoordinates( coordinates[0],
                                              coordinates[1],
                                              coordinates[2],
                                              cartesian_coordinates[0],
                                              cartesian_coordinates[1],
                                              cartesian_coordinates[2] );
}

// Convert the cartesian coordinates to the spatial coordinate system
inline void SpatialCoordinateConversionPolicy::convertFromCartesianSpatialCoordinates(
                                         const double cartesian_coordinates[3],
                                         double coordinates[3] ) const
{
  this->convertFromCartesianSpatialCoordinates( cartesian_coordinates[0],
                                                cartesian_coordinates[1],
                                                cartesian_coordinates[2],
                                                coordinates[0],
                                                coordinates[1],
                                                coordinates[2] );
}

// Translate a global Cartesian position to a local Cartesian position
inline void SpatialCoordinateConversionPolicy::translateGlobalCartesianPositionToLocalCartesianPosition(
                          const double global_x_position,
                          const double global_y_position,
                          const double global_z_position,
                          const double local_origin_wrt_global_coord_system[3],
                          double& local_x_position,
                          double& local_y_position,
                          double& local_z_position )
{
  local_x_position =
    global_x_position - local_origin_wrt_global_coord_system[0];

  local_y_position =
    global_y_position - local_origin_wrt_global_coord_system[1];

  local_z_position =
    global_z_position - local_origin_wrt_global_coord_system[2];
}

// Translate a local Cartesian position to a global Cartesian position
inline void SpatialCoordinateConversionPolicy::translateLocalCartesianPositionToGlobalCartesianPosition(
                          const double local_x_position,
                          const double local_y_position,
                          const double local_z_position,
                          const double local_origin_wrt_global_coord_system[3],
                          double& global_x_position,
                          double& global_y_position,
                          double& global_z_position )
{
  global_x_position =
    local_x_position + local_origin_wrt_global_coord_system[0];

  global_y_position =
    local_y_position + local_origin_wrt_global_coord_system[1];

  global_z_position =
    local_z_position + local_origin_wrt_global_coord_system[2];
}

} // end Utility namespace

BOOST_SERIALIZATION_ASSUME_ABSTRACT_CLASS( SpatialCoordinateConversionPolicy, Utility )
BOOST_SERIALIZATION_CLASS_VERSION( SpatialCoordinateConversionPolicy, Utility, 0 );
EXTERN_EXPLICIT_CLASS_SERIALIZE_INST( Utility, SpatialCoordinateConversionPolicy );

#endif // end UTILITY_SPATIAL_COORDINATE_CONVERSION_POLICY_HPP

//---------------------------------------------------------------------------//
// end Utility_SpatialCoordinateConversionPolicy.hpp
//---------------------------------------------------------------------------//