text:
//=======================================================================
// Copyright (c) 2013 Piotr Smulewicz
//
// 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)
//=======================================================================
/**
 * @file k_cut_test.cpp
 * @brief
 * @author Piotr Smulewicz
 * @version 1.0
 * @date 2013-08-20
 */

#include "test_utils/logger.hpp"
#include "test_utils/test_result_check.hpp"

#include "paal/greedy/k_cut/k_cut.hpp"
#include "paal/utils/irange.hpp"

#include <boost/graph/adjacency_list.hpp>
#include <boost/test/unit_test.hpp>

template <typename Graph>
std::pair<Graph, std::vector<int>> create_instance() {
    std::vector<std::pair<int,int>> edges_p{{1,2},{1,5},{2,3},{2,5},{2,6},
        {3,4},{3,7},{4,7},{4,0},{5,6},{6,7},{7,0}};
    std::vector<int> costs{2,3,3,2,2,4,2,2,2,3,1,3};

    Graph graph(edges_p.begin(), edges_p.end(), costs.begin(), 8);
    std::vector<int> optimal = {4,9,13,16,21,25,29};

    return std::make_pair(graph, optimal);
}

template <typename Graph>
void run_test(const Graph &graph, const std::vector<int> &optimal) {
    using VT = typename boost::graph_traits<Graph>::vertex_descriptor;
    auto index = get(boost::vertex_index, graph);
    auto weight = get(boost::edge_weight, graph);

    for (auto i: paal::irange(2,9)) {
        std::vector<std::pair<VT, int>> vertices_parts;
        int cost_cut = paal::greedy::k_cut(graph, i, back_inserter(vertices_parts),
            boost::weight_map(weight));
        LOGLN("cost cut: " << cost_cut);
        std::vector<int> vertices_to_parts;
        vertices_to_parts.resize(vertices_parts.size());
        for (auto i: vertices_parts){
            LOG(i.first << "(" << i.second << "), ");
            vertices_to_parts[get(index, i.first)] = i.second;
        }
        LOGLN("");

        int cost_cut_verification = 0;
        for (auto v: boost::make_iterator_range(edges(graph))) {
            if (vertices_to_parts[get(index, source(v, graph))]
                    != vertices_to_parts[get(index, target(v, graph))])
                cost_cut_verification += get(weight, v);
        }
        BOOST_CHECK_EQUAL(cost_cut, cost_cut_verification);
        check_result(cost_cut_verification, optimal[i-2], 2.0 - 2.0 / double(i));
    }
}

template <typename VertexList>
using Graph = boost::adjacency_list<boost::vecS, VertexList, boost::undirectedS,
                                    boost::property<boost::vertex_index_t, int>,
                                    boost::property<boost::edge_weight_t, int>>;

BOOST_AUTO_TEST_CASE(KCut) {
    auto instance = create_instance<Graph<boost::vecS>>();
    run_test(instance.first, instance.second);
}

BOOST_AUTO_TEST_CASE(KCut_list) {
    auto instance = create_instance<Graph<boost::listS>>();
    auto graph = instance.first;
    auto optimal = instance.second;

    auto index = get(boost::vertex_index, graph);
    int idx = 0;
    for (auto v : boost::make_iterator_range(vertices(graph))) {
        put(index, v, idx);
        ++idx;
    }

    run_test(graph, optimal);
}

ext: cpp

max_stars_repo_name: Kommeren/AA

max_issues_repo_name: Kommeren/AA

max_forks_repo_name: Kommeren/AA


text:
// Copyright (c) 2014-2021 The Gridcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "gridcoin/cpid.h"
#include "util.h"

#include <algorithm>
#include <boost/variant/apply_visitor.hpp>
#include <openssl/md5.h>

using namespace GRC;

namespace {
//!
//! \brief Gets the string representation of a mining ID object.
//!
struct MiningIdToStringVisitor : boost::static_visitor<std::string>
{
    //!
    //! \brief Call the mining ID variant type's \c ToString() method directly.
    //!
    //! \param variant The object to create a string for.
    //!
    //! \return The string representation of the mining ID.
    //!
    template<typename T>
    std::string operator()(const T& variant) const
    {
        return variant.ToString();
    }
};
} // anonymous namespace

// -----------------------------------------------------------------------------
// Class: Cpid
// -----------------------------------------------------------------------------

Cpid::Cpid(const std::vector<unsigned char>& bytes)
{
    if (bytes.size() == 16) {
        std::copy_n(bytes.begin(), 16, m_bytes.begin());
    } else {
        m_bytes.fill(0x00);
    }
}

Cpid Cpid::Parse(const std::string& hex)
{
    if (hex.size() != 32) {
        return Cpid();
    }

    return Cpid(ParseHex(hex));
}

Cpid Cpid::Hash(const std::string& internal, const std::string& email)
{
    if (internal.empty() || email.empty()) {
        return Cpid();
    }

    Cpid cpid;

    // Even though the internal CPID is hex-encoded, BOINC creates the external
    // CPID hash from the hex string, not from the encoded bytes:
    //
    std::vector<unsigned char> input(internal.begin(), internal.end());
    input.insert(input.end(), email.begin(), email.end());

    MD5(input.data(), input.size(), cpid.m_bytes.data());

    return cpid;
}

bool Cpid::IsZero() const
{
    const auto zero = [](const unsigned char& i) { return i == 0; };

    return std::all_of(m_bytes.begin(), m_bytes.end(), zero);
}

bool Cpid::Matches(const std::string& internal, const std::string& email) const
{
    return m_bytes == Cpid::Hash(internal, email).m_bytes;
}

std::string Cpid::ToString() const
{
    return HexStr(m_bytes.begin(), m_bytes.end());
}

// -----------------------------------------------------------------------------
// Class: MiningId
// -----------------------------------------------------------------------------

MiningId MiningId::Parse(const std::string& input)
{
    if (input.empty()) {
        return MiningId();
    }

    if (input == "INVESTOR" || input == "investor") {
        return MiningId::ForInvestor();
    }

    if (input.size() == 32) {
        std::vector<unsigned char> bytes = ParseHex(input);

        if (bytes.size() == 16) {
            return MiningId(Cpid(bytes));
        }
    }

    return MiningId();
}

std::string MiningId::ToString() const
{
    return boost::apply_visitor(MiningIdToStringVisitor(), m_variant);
}

// -----------------------------------------------------------------------------
// Class: MiningId::Invalid
// -----------------------------------------------------------------------------

std::string MiningId::Invalid::ToString() const
{
    return std::string();
}

// -----------------------------------------------------------------------------
// Class: MiningId::Investor
// -----------------------------------------------------------------------------

std::string MiningId::Investor::ToString() const
{
    return "INVESTOR";
}

max_stars_repo_name: Git-Jiro/Gridcoin-Research

max_issues_repo_name: Git-Jiro/Gridcoin-Research

max_forks_repo_name: Git-Jiro/Gridcoin-Research


text:
// g2o - General Graph Optimization
// Copyright (C) 2011 R. Kuemmerle, G. Grisetti, W. Burgard
// 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.
//
// 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
// HOLDER 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.

#include "solver_slam2d_linear.h"

#include <Eigen/Core>

#include "g2o/core/sparse_block_matrix.h"
#include "g2o/core/sparse_optimizer.h"
#include "g2o/core/hyper_dijkstra.h"

#include "g2o/types/slam2d/edge_se2.h"

#include "g2o/stuff/misc.h"
#include "g2o/stuff/scoped_pointer.h"

#include "g2o/solvers/csparse/linear_solver_csparse.h"

#include "g2o/core/solver.h"

using namespace std;

namespace g2o {

  /**
   * \brief compute the initial guess of theta while travelling along the MST
   */
  class ThetaTreeAction : public HyperDijkstra::TreeAction
  {
    public:
      ThetaTreeAction(double* theta) : HyperDijkstra::TreeAction(), _thetaGuess(theta) {}
      virtual double perform(HyperGraph::Vertex* v, HyperGraph::Vertex* vParent, HyperGraph::Edge* e)
      {
        if (! vParent)
          return 0.;
        EdgeSE2* odom    = static_cast<EdgeSE2*>(e);
        VertexSE2* from  = static_cast<VertexSE2*>(vParent);
        VertexSE2* to    = static_cast<VertexSE2*>(v);
        assert(to->hessianIndex() >= 0);
        double fromTheta = from->hessianIndex() < 0 ? 0. : _thetaGuess[from->hessianIndex()];
        bool direct      = odom->vertices()[0] == from;
        if (direct)
          _thetaGuess[to->hessianIndex()] = fromTheta + odom->measurement().rotation().angle();
        else
          _thetaGuess[to->hessianIndex()] = fromTheta - odom->measurement().rotation().angle();
        return 1.;
      }
    protected:
      double* _thetaGuess;
  };

  SolverSLAM2DLinear::SolverSLAM2DLinear(std::unique_ptr<Solver> solver)
    : OptimizationAlgorithmGaussNewton(std::move(solver))
  {}

  SolverSLAM2DLinear::~SolverSLAM2DLinear()
  {}

  OptimizationAlgorithm::SolverResult SolverSLAM2DLinear::solve(int iteration, bool online)
  {
    if (iteration == 0) {
      bool status = solveOrientation();
      if (! status)
        return OptimizationAlgorithm::Fail;
    }

    return OptimizationAlgorithmGaussNewton::solve(iteration, online);
  }

  bool SolverSLAM2DLinear::solveOrientation()
  {
    assert(_optimizer->indexMapping().size() + 1 == _optimizer->vertices().size() && "Needs to operate on full graph");
    assert(_optimizer->vertex(0)->fixed() && "Graph is not fixed by vertex 0");
    VectorXD b, x; // will be used for theta and x/y update
    b.setZero(_optimizer->indexMapping().size());
    x.setZero(_optimizer->indexMapping().size());

    typedef Eigen::Matrix<double, 1, 1, Eigen::ColMajor> ScalarMatrix;

    ScopedArray<int> blockIndeces(new int[_optimizer->indexMapping().size()]);
    for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i)
      blockIndeces[i] = i+1;

    SparseBlockMatrix<ScalarMatrix> H(blockIndeces.get(), blockIndeces.get(), _optimizer->indexMapping().size(), _optimizer->indexMapping().size());

    // building the structure, diagonal for each active vertex
    for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {
      OptimizableGraph::Vertex* v = _optimizer->indexMapping()[i];
      int poseIdx = v->hessianIndex();
      ScalarMatrix* m = H.block(poseIdx, poseIdx, true);
      m->setZero();
    }

    HyperGraph::VertexSet fixedSet;

    // off diagonal for each edge
    for (SparseOptimizer::EdgeContainer::const_iterator it = _optimizer->activeEdges().begin(); it != _optimizer->activeEdges().end(); ++it) {
#    ifndef NDEBUG
      EdgeSE2* e = dynamic_cast<EdgeSE2*>(*it);
      assert(e && "Active edges contain non-odometry edge"); //
#    else
      EdgeSE2* e = static_cast<EdgeSE2*>(*it);
#    endif
      OptimizableGraph::Vertex* from = static_cast<OptimizableGraph::Vertex*>(e->vertices()[0]);
      OptimizableGraph::Vertex* to   = static_cast<OptimizableGraph::Vertex*>(e->vertices()[1]);

      int ind1 = from->hessianIndex();
      int ind2 = to->hessianIndex();
      if (ind1 == -1 || ind2 == -1) {
        if (ind1 == -1) fixedSet.insert(from); // collect the fixed vertices
        if (ind2 == -1) fixedSet.insert(to);
        continue;
      }

      bool transposedBlock = ind1 > ind2;
      if (transposedBlock){ // make sure, we allocate the upper triangle block
        std::swap(ind1, ind2);
      }

      ScalarMatrix* m = H.block(ind1, ind2, true);
      m->setZero();
    }

    // walk along the Minimal Spanning Tree to compute the guess for the robot orientation
    assert(fixedSet.size() == 1);
    VertexSE2* root = static_cast<VertexSE2*>(*fixedSet.begin());
    VectorXD thetaGuess;
    thetaGuess.setZero(_optimizer->indexMapping().size());
    UniformCostFunction uniformCost;
    HyperDijkstra hyperDijkstra(_optimizer);
    hyperDijkstra.shortestPaths(root, &uniformCost);

    HyperDijkstra::computeTree(hyperDijkstra.adjacencyMap());
    ThetaTreeAction thetaTreeAction(thetaGuess.data());
    HyperDijkstra::visitAdjacencyMap(hyperDijkstra.adjacencyMap(), &thetaTreeAction);

    // construct for the orientation
    for (SparseOptimizer::EdgeContainer::const_iterator it = _optimizer->activeEdges().begin(); it != _optimizer->activeEdges().end(); ++it) {
      EdgeSE2* e = static_cast<EdgeSE2*>(*it);
      VertexSE2* from = static_cast<VertexSE2*>(e->vertices()[0]);
      VertexSE2* to   = static_cast<VertexSE2*>(e->vertices()[1]);

      double omega = e->information()(2,2);

      double fromThetaGuess = from->hessianIndex() < 0 ? 0. : thetaGuess[from->hessianIndex()];
      double toThetaGuess   = to->hessianIndex() < 0 ? 0. : thetaGuess[to->hessianIndex()];
      double error          = normalize_theta(-e->measurement().rotation().angle() + toThetaGuess - fromThetaGuess);

      bool fromNotFixed = !(from->fixed());
      bool toNotFixed   = !(to->fixed());

      if (fromNotFixed || toNotFixed) {
        double omega_r = - omega * error;
        if (fromNotFixed) {
          b(from->hessianIndex()) -= omega_r;
          (*H.block(from->hessianIndex(), from->hessianIndex()))(0,0) += omega;
          if (toNotFixed) {
            if (from->hessianIndex() > to->hessianIndex())
              (*H.block(to->hessianIndex(), from->hessianIndex()))(0,0) -= omega;
            else
              (*H.block(from->hessianIndex(), to->hessianIndex()))(0,0) -= omega;
          }
        }
        if (toNotFixed ) {
          b(to->hessianIndex()) += omega_r;
          (*H.block(to->hessianIndex(), to->hessianIndex()))(0,0) += omega;
        }
      }
    }

    // solve orientation
    typedef LinearSolverCSparse<ScalarMatrix> SystemSolver;
    SystemSolver linearSystemSolver;
    linearSystemSolver.init();
    bool ok = linearSystemSolver.solve(H, x.data(), b.data());
    if (!ok) {
      cerr << __PRETTY_FUNCTION__ << "Failure while solving linear system" << endl;
      return false;
    }

    // update the orientation of the 2D poses and set translation to 0, GN shall solve that
    root->setToOrigin();
    for (size_t i = 0; i < _optimizer->indexMapping().size(); ++i) {
      VertexSE2* v = static_cast<VertexSE2*>(_optimizer->indexMapping()[i]);
      int poseIdx = v->hessianIndex();
      SE2 poseUpdate(0, 0, normalize_theta(thetaGuess(poseIdx) + x(poseIdx)));
      v->setEstimate(poseUpdate);
    }

    return true;
  }

} // end namespace


text:
#ifndef _COMMON_HPP_
#define _COMMON_HPP_

#include "../../core/exceptions.hpp"
#include "../../matrix/blas_wrapper.hpp"
#include "linear_model.hpp"
#include "gradient_descent.hpp"
#include "gradient.hpp"
#include "multinomial_logistic_regression_model.hpp"
#include "softmax_gradient_descent.hpp"
#include "regularizer.hpp"
#include "rms.hpp"
#include "../utility/matrix_conversion.hpp"

#include <boost/lexical_cast.hpp>

#define ITOS boost::lexical_cast<std::string>
#define _ALLOW_CONV_RATE_CHECK_
#define LR_VLEN 1024 // made it same as JDS/ELL

namespace frovedis {

enum MatType {
  CRS = 0,
  JDS,
  ELL,
  HYBRID
};

template <class T>
std::vector<sliced_colmajor_matrix_local<T>>
divide_data_to_minibatch_colmajor(colmajor_matrix_local<T>& data,
                                  double miniBatchFraction) {
  size_t numSamples = data.local_num_row;
  size_t tmp = static_cast<size_t>(ceil(numSamples * miniBatchFraction));
  size_t tmp2 = ceil_div<size_t>(tmp, LR_VLEN) * LR_VLEN;
  size_t miniBatchSize = tmp2 < numSamples ? tmp2 : numSamples;
  size_t numBatches = ceil_div(numSamples, miniBatchSize);
  std::vector<sliced_colmajor_matrix_local<T>> ret(numBatches);
  for(size_t i = 0; i < numBatches; i++) {
    size_t start_row = i * miniBatchSize;
    size_t end_row =  (i + 1) * miniBatchSize;
    if(end_row > data.local_num_row) end_row = data.local_num_row;
    size_t nrow = end_row - start_row;
    size_t ncol = data.local_num_col;
    // the minibatch data would be needed for only gemv() calculation
    // thus simply slicing the input matrix to minibatches, instead of copying
    ret[i] = make_sliced_colmajor_matrix_local<T>(data,start_row,0,nrow,ncol);
  }
  return ret;
}

template <class T, class I, class O>
std::vector<crs_matrix_local<T,I,O>>
divide_data_to_minibatch_crs(crs_matrix_local<T,I,O>& data,
                             double miniBatchFraction) {
  size_t numSamples = data.local_num_row;
  size_t tmp = static_cast<size_t>(ceil(numSamples * miniBatchFraction));
  size_t tmp2 = ceil_div<size_t>(tmp, LR_VLEN) * LR_VLEN;
  size_t miniBatchSize = tmp2 < numSamples ? tmp2 : numSamples;
  size_t numBatches = ceil_div(numSamples, miniBatchSize);
  std::vector<crs_matrix_local<T,I,O>> ret(numBatches);
  T* datavalp = &data.val[0];
  I* dataidxp = &data.idx[0];
  O* dataoffp = &data.off[0];
  for(size_t i = 0; i < numBatches; i++) {
    ret[i].local_num_col = data.local_num_col;
    size_t start_row = i * miniBatchSize;
    size_t end_row =  (i + 1) * miniBatchSize;
    if(end_row > data.local_num_row) end_row = data.local_num_row;
    ret[i].local_num_row = end_row - start_row;
    size_t start_off = dataoffp[start_row];
    size_t end_off = dataoffp[end_row];
    size_t off_size = end_off - start_off;
    ret[i].val.resize(off_size);
    ret[i].idx.resize(off_size);
    ret[i].off.resize(end_row - start_row + 1); // off[0] == 0 by ctor
    T* valp = &ret[i].val[0];
    I* idxp = &ret[i].idx[0];
    O* offp = &ret[i].off[0];
    for(size_t j = 0; j < off_size; j++) {
      valp[j] = datavalp[j + start_off];
      idxp[j] = dataidxp[j + start_off];
    }
    for(size_t j = 0; j < end_row - start_row; j++) {
      offp[j+1] = offp[j] + (dataoffp[start_row + j + 1] -
                             dataoffp[start_row + j]);
    }
  }
  return ret;
}

template <class T>
std::vector<std::vector<T>>
divide_label_to_minibatch(std::vector<T>& label,
                          double miniBatchFraction) {
  size_t numSamples = label.size();
  size_t tmp = static_cast<size_t>(ceil(numSamples * miniBatchFraction));
  size_t tmp2 = ceil_div<size_t>(tmp, LR_VLEN) * LR_VLEN;
  size_t miniBatchSize = tmp2 < numSamples ? tmp2 : numSamples;
  size_t numBatches = ceil_div(numSamples, miniBatchSize);
  std::vector<std::vector<T>> ret(numBatches);
  T* labelp = &label[0];
  size_t cnt = 0;
  for(size_t i = 0; i < numBatches; i++) {
    size_t tmp = numSamples - i * miniBatchSize;
    size_t size = (tmp >= miniBatchSize) ? miniBatchSize : tmp;
    ret[i].resize(size);
    T* retp = &ret[i][0];
    for(size_t j = 0; j < size; j++) {
      retp[j] = labelp[cnt+j];
    }
    cnt += size;
  }
  return ret;
}

template <class T>
inline void release_memory_vector(std::vector<T>& vec) {
  std::vector<T> tmp;
  tmp.swap(vec);
}

template <class T, class I, class O>
inline void clear_data(crs_matrix_local<T,I,O>& data) {
  release_memory_vector<T>(data.val);
  release_memory_vector<I>(data.idx);
  release_memory_vector<O>(data.off);
}

template <class T, class I, class O>
inline void clear_data_vector(std::vector<crs_matrix_local<T,I,O>>& data) {
  for(size_t i = 0; i < data.size(); i++) {
    clear_data(data[i]);
  }
  release_memory_vector<crs_matrix_local<T,I,O>>(data);
}

template <class MODEL>
MODEL calc_diff (MODEL& left_m, MODEL& right_m) {
  MODEL diff;
  diff = left_m - right_m;
  return diff;
}

template <class MODEL>
void calc_diff_inplace (MODEL& left_m, MODEL& right_m) {
  left_m -= right_m;
}

template <class T, class MODEL>
void get_weight(MODEL& m, std::vector<T>& v) {
  v.swap(m.weight);
}

template <class T, class MODEL>
T get_intercept(MODEL& m) {
  return m.intercept;
}

template <class T, class MODEL>
void get_weight_intercept(MODEL& m, std::vector<T>& v) {
  size_t size = m.weight.size();
  v.resize(size + 1);
  T* vp = &v[0];
  T* weightp = &m.weight[0];
  for(size_t i = 0; i < size; i++) vp[i] = weightp[i];
  v[size] = m.intercept;
}

template <class T>
void debug_vector_print(const std::vector<T>& vec) {
  for(int i=0; i<vec.size(); i++) std::cout << " " << vec[i];
  std::cout << std::endl;
}

template <class T>
std::vector<T>
operator-(const std::vector<T>& v1,
          const std::vector<T>& v2) {
  //debug_vector_print(v1);
  //debug_vector_print(v2);
  if (v1.size() != v2.size()) REPORT_ERROR(USER_ERROR,"incompatible vector size!\n");
  size_t size = v1.size();
  std::vector<T> ret(size);
  const T* v1p = &v1[0];
  const T* v2p = &v2[0];
  T* retp = &ret[0];
  for(size_t i=0; i<size; i++) {
    retp[i] = v1p[i] - v2p[i];
  }
  return ret;
}

template <class T, class MODEL>
inline bool is_converged(MODEL& prev_model,
                         MODEL& cur_model,
                         T convergenceTol,
                         size_t iterCount) {

  frovedis::time_spent t(TRACE);
  T RMSE = get_model_rms_error<T,MODEL>(cur_model,prev_model);

  std::string msg = "[Iteration: " + ITOS(iterCount) + "]" +
                    " RMS error: " + ITOS(RMSE) + " elapsed-time: ";
  t.show(msg);

  if (RMSE <= convergenceTol) {
    std::string msg;
    msg = "Convergence achieved in " + ITOS(iterCount) + " iterations.\n";
    REPORT_INFO(msg);
    return true;
  }
  else
    return false;
}

}

#endif

ext: hpp

max_stars_repo_name: wmeddie/frovedis

max_issues_repo_name: wmeddie/frovedis

max_forks_repo_name: wmeddie/frovedis


text:
// Copyright (c) 2014-2017, The Monero Project
// Copyright (c) 2018-2019, The Scala Project
// Copyright (c) 2017 The Masari Project(next_difficulty_v3)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.
//
// Parts of this file are originally copyright (c) 2012-2013 The Cryptonote developers

#include <algorithm>
#include <cassert>
#include <cstddef>
#include <cstdint>
#include "include_base_utils.h"
#include <vector>
#include <boost/math/special_functions/round.hpp>
#include <boost/algorithm/clamp.hpp>

#include "int-util.h"
#include "crypto/hash.h"
#include "cryptonote_config.h"
#include "misc_language.h"
#include "difficulty.h"
#include "warnings.h"

#define MAX_AVERAGE_TIMESPAN          (uint64_t) DIFFICULTY_TARGET*6
#define MIN_AVERAGE_TIMESPAN          (uint64_t) DIFFICULTY_TARGET/24

#undef SCALA_DEFAULT_LOG_CATEGORY
#define SCALA_DEFAULT_LOG_CATEGORY "difficulty"

namespace cryptonote {

using std::size_t;
using std::uint64_t;
using std::vector;

#if defined(__x86_64__)
static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
    low = mul128(a, b, &high);
}

#else

static inline void mul(uint64_t a, uint64_t b, uint64_t &low, uint64_t &high) {
    // __int128 isn't part of the standard, so the previous function wasn't portable. mul128() in Windows is fine,
    // but this portable function should be used elsewhere. Credit for this function goes to latexi95.

    uint64_t aLow = a & 0xFFFFFFFF;
    uint64_t aHigh = a >> 32;
    uint64_t bLow = b & 0xFFFFFFFF;
    uint64_t bHigh = b >> 32;

    uint64_t res = aLow * bLow;
    uint64_t lowRes1 = res & 0xFFFFFFFF;
    uint64_t carry = res >> 32;

    res = aHigh * bLow + carry;
    uint64_t highResHigh1 = res >> 32;
    uint64_t highResLow1 = res & 0xFFFFFFFF;

    res = aLow * bHigh;
    uint64_t lowRes2 = res & 0xFFFFFFFF;
    carry = res >> 32;

    res = aHigh * bHigh + carry;
    uint64_t highResHigh2 = res >> 32;
    uint64_t highResLow2 = res & 0xFFFFFFFF;

    //Addition

    uint64_t r = highResLow1 + lowRes2;
    carry = r >> 32;
    low = (r << 32) | lowRes1;
    r = highResHigh1 + highResLow2 + carry;
    uint64_t d3 = r & 0xFFFFFFFF;
    carry = r >> 32;
    r = highResHigh2 + carry;
    high = d3 | (r << 32);
}

#endif

static inline bool cadd(uint64_t a, uint64_t b) {
    return a + b < a;
}

static inline bool cadc(uint64_t a, uint64_t b, bool c) {
    return a + b < a || (c && a + b == (uint64_t) -1);
}

bool check_hash(const crypto::hash &hash, difficulty_type difficulty) {
    uint64_t low, high, top, cur;
    // First check the highest word, this will most likely fail for a random hash.
    mul(swap64le(((const uint64_t *) &hash)[3]), difficulty, top, high);
    if (high != 0) {
        return false;
    }
    mul(swap64le(((const uint64_t *) &hash)[0]), difficulty, low, cur);
    mul(swap64le(((const uint64_t *) &hash)[1]), difficulty, low, high);
    bool carry = cadd(cur, low);
    cur = high;
    mul(swap64le(((const uint64_t *) &hash)[2]), difficulty, low, high);
    carry = cadc(cur, low, carry);
    carry = cadc(high, top, carry);
    return !carry;
}

difficulty_type next_difficulty(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {

    if(timestamps.size() > DIFFICULTY_WINDOW)
    {
        timestamps.resize(DIFFICULTY_WINDOW);
        cumulative_difficulties.resize(DIFFICULTY_WINDOW);
    }

    size_t length = timestamps.size();
    assert(length == cumulative_difficulties.size());
    if (length <= 1) {
        return 1;
    }
    static_assert(DIFFICULTY_WINDOW >= 2, "Window is too small");
    assert(length <= DIFFICULTY_WINDOW);
    sort(timestamps.begin(), timestamps.end());
    size_t cut_begin, cut_end;
    static_assert(2 * DIFFICULTY_CUT <= DIFFICULTY_WINDOW - 2, "Cut length is too large");
    if (length <= DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT) {
        cut_begin = 0;
        cut_end = length;
    } else {
        cut_begin = (length - (DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT) + 1) / 2;
        cut_end = cut_begin + (DIFFICULTY_WINDOW - 2 * DIFFICULTY_CUT);
    }
    assert(/*cut_begin >= 0 &&*/ cut_begin + 2 <= cut_end && cut_end <= length);
    uint64_t time_span = timestamps[cut_end - 1] - timestamps[cut_begin];
    if (time_span == 0) {
        time_span = 1;
    }
    difficulty_type total_work = cumulative_difficulties[cut_end - 1] - cumulative_difficulties[cut_begin];
    assert(total_work > 0);
    uint64_t low, high;
    mul(total_work, target_seconds, low, high);
    // blockchain errors "difficulty overhead" if this function returns zero.
    // TODO: consider throwing an exception instead
    if (high != 0 || low + time_span - 1 < low) {
        return 0;
    }
    return (low + time_span - 1) / time_span;
}

//Was good but not as good as v3.
difficulty_type next_difficulty_v2(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {

    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V2)
    {
        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V2);
        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V2);
    }

    size_t length = timestamps.size();
    assert(length == cumulative_difficulties.size());
    if (length <= 1) {
        return 1;
    }

    sort(timestamps.begin(), timestamps.end());
    size_t cut_begin, cut_end;
    static_assert(2 * DIFFICULTY_CUT_V2 <= DIFFICULTY_BLOCKS_COUNT_V2 - 2, "Cut length is too large");
    if (length <= DIFFICULTY_BLOCKS_COUNT_V2 - 2 * DIFFICULTY_CUT_V2) {
        cut_begin = 0;
        cut_end = length;
    }
    else {
        cut_begin = (length - (DIFFICULTY_BLOCKS_COUNT_V2 - 2 * DIFFICULTY_CUT_V2) + 1) / 2;
        cut_end = cut_begin + (DIFFICULTY_BLOCKS_COUNT_V2 - 2 * DIFFICULTY_CUT_V2);
    }
    assert(/*cut_begin >= 0 &&*/ cut_begin + 2 <= cut_end && cut_end <= length);
    uint64_t total_timespan = timestamps[cut_end - 1] - timestamps[cut_begin];
    if (total_timespan == 0) {
        total_timespan = 1;
    }

    uint64_t timespan_median = 0;
    if (cut_begin > 0 && length >= cut_begin * 2 + 3) {
        std::vector<std::uint64_t> time_spans;
        for (size_t i = length - cut_begin * 2 - 3; i < length - 1; i++) {
            uint64_t time_span = timestamps[i + 1] - timestamps[i];
            if (time_span == 0) {
                time_span = 1;
            }
            time_spans.push_back(time_span);

            //LOG_PRINT_L3("Timespan " << i << ": " << (time_span / 60) / 60 << ":" << (time_span > 3600 ? (time_span % 3600) / 60 : time_span / 60) << ":" << time_span % 60 << " (" << time_span << ")");
        }
        timespan_median = epee::misc_utils::median(time_spans);
    }

    uint64_t timespan_length = length - cut_begin * 2 - 1;
    //LOG_PRINT_L2("Timespan Median: " << timespan_median << ", Timespan Average: " << total_timespan / timespan_length);

    uint64_t total_timespan_median = timespan_median > 0 ? timespan_median * timespan_length : total_timespan * 7 / 10;
    uint64_t adjusted_total_timespan = (total_timespan * 8 + total_timespan_median * 3) / 10; //  0.8A + 0.3M (the median of a poisson distribution is 70% of the mean, so 0.25A = 0.25/0.7 = 0.285M)
    if (adjusted_total_timespan > MAX_AVERAGE_TIMESPAN * timespan_length) {
        adjusted_total_timespan = MAX_AVERAGE_TIMESPAN * timespan_length;
    }
    if (adjusted_total_timespan < MIN_AVERAGE_TIMESPAN * timespan_length) {
        adjusted_total_timespan = MIN_AVERAGE_TIMESPAN * timespan_length;
    }

    difficulty_type total_work = cumulative_difficulties[cut_end - 1] - cumulative_difficulties[cut_begin];
    assert(total_work > 0);

    uint64_t low, high;
    mul(total_work, target_seconds, low, high);
    if (high != 0) {
        return 0;
    }

    uint64_t next_diff = (low + adjusted_total_timespan - 1) / adjusted_total_timespan;
    if (next_diff < 1) next_diff = 1;
    //LOG_PRINT_L2("Total timespan: " << total_timespan << ", Adjusted total timespan: " << adjusted_total_timespan << ", Total work: " << total_work << ", Next diff: " << next_diff << ", Hashrate (H/s): " << next_diff / target_seconds);

    return next_diff;
}

difficulty_type next_difficulty_v3(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds, bool v4) {

    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V3)
    {
        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V3);
        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V3);
    }

    size_t length = timestamps.size();
    assert(length == cumulative_difficulties.size());
    if (length <= 1) {
        return 1;
    }

    uint64_t weighted_timespans = 0;
    uint64_t target;

    if (true) {
        uint64_t previous_max = timestamps[0];
        for (size_t i = 1; i < length; i++) {
            uint64_t timespan;
            uint64_t max_timestamp;

            if (timestamps[i] > previous_max) {
                max_timestamp = timestamps[i];
            } else {
                max_timestamp = previous_max;
            }

            timespan = max_timestamp - previous_max;
            if (timespan == 0) {
                timespan = 1;
            } else if (timespan > 10 * target_seconds) {
                timespan = 10 * target_seconds;
            }

            weighted_timespans += i * timespan;
            previous_max = max_timestamp;
        }
        // adjust = 0.99 for N=60, leaving the + 1 for now as it's not affecting N
        target = 99 * (((length + 1) / 2) * target_seconds) / 100;
    } else {
        for (size_t i = 1; i < length; i++) {
            uint64_t timespan;
            if (timestamps[i - 1] >= timestamps[i]) {
                timespan = 1;
            } else {
                timespan = timestamps[i] - timestamps[i - 1];
            }
            if (timespan > 10 * target_seconds) {
                timespan = 10 * target_seconds;
            }
            weighted_timespans += i * timespan;
        }
        target = ((length + 1) / 2) * target_seconds;
    }

    uint64_t minimum_timespan = target_seconds * length / 2;
    if (weighted_timespans < minimum_timespan) {
        weighted_timespans = minimum_timespan;
    }

    difficulty_type total_work = cumulative_difficulties.back() - cumulative_difficulties.front();
    assert(total_work > 0);

    uint64_t low, high;
    mul(total_work, target, low, high);

    if (high != 0) {
        return 0;
    }
    return low / weighted_timespans;
}

difficulty_type next_difficulty_v4(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {

    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V4)
    {
        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V4);
        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V4);
    }

    size_t length_cumul_diff = cumulative_difficulties.size();
    if(length_cumul_diff >= DIFFICULTY_BLOCKS_COUNT_V4 - 1) {
        std::vector<difficulty_type> first_diffs;
        std::vector<difficulty_type> mid_diffs;
        std::vector<difficulty_type> last_diffs;
        for (size_t i = 0; i < (DIFFICULTY_BLOCKS_COUNT_V4-30); i++) {
            first_diffs.push_back(cumulative_difficulties[i]);
        }
        for (size_t i = (DIFFICULTY_BLOCKS_COUNT_V4-30); i < (DIFFICULTY_BLOCKS_COUNT_V4-10); i++) {
            mid_diffs.push_back(cumulative_difficulties[i]);
        }
        for (size_t i = (DIFFICULTY_BLOCKS_COUNT_V4*-10); i < DIFFICULTY_BLOCKS_COUNT_V4; i++) {
            last_diffs.push_back(cumulative_difficulties[i]);
        }
        difficulty_type median_first = epee::misc_utils::median(first_diffs);
        difficulty_type median_mid = epee::misc_utils::median(mid_diffs);
        difficulty_type median_last = epee::misc_utils::median(last_diffs);

        if(median_first > (median_mid*6/5) && median_mid > (median_last*10/9))
        {
            timestamps.resize(25);
            cumulative_difficulties.resize(25);
        }
        else if(median_mid > (median_first*6/5) && median_last > (median_mid*10/9)) {
            timestamps.resize(25);
            cumulative_difficulties.resize(25);
        }

    }

    size_t length = timestamps.size();
    assert(length == cumulative_difficulties.size());
    if (length <= 1) {
        return 1;
    }

    uint64_t weighted_timespans = 0;
    uint64_t target;

    int nbShortTsLastNBlocks = 0;
    bool lastTimeWasShort=false;
    int lastShortTimeInARaw = 0;

    int nbLongTsLastNBlocks = 0;
    //bool lastTimeWasLong=false;

    if (true) {
        uint64_t previous_max = timestamps[0];

        for (size_t i = 1; i < length; i++) {
            uint64_t timespan;
            uint64_t max_timestamp;

            if (timestamps[i] > previous_max) {
                max_timestamp = timestamps[i];
            } else {
                max_timestamp = previous_max;
            }

            timespan = max_timestamp - previous_max;
            if (timespan == 0) {
                timespan = 1;
            } else if (timespan > 11 * target_seconds) {
                timespan = 11 * target_seconds;
            }
            if(i>=(length-7)) {
                if(timespan < 30) {
                    nbShortTsLastNBlocks ++;
                    lastTimeWasShort = true;
                    lastShortTimeInARaw ++;
                } else {
                    lastTimeWasShort = false;
                    lastShortTimeInARaw=0;
                }
                if(timespan >100) {
                    nbLongTsLastNBlocks ++;
                    //lastTimeWasLong = true;
                } else {
                    //lastTimeWasLong = false;
                }
            }

            weighted_timespans += i * timespan;
            previous_max = max_timestamp;
        }
        // adjust faster if many blocks fount too fast

        if(lastTimeWasShort) {
            if(nbShortTsLastNBlocks >= 7) {
                weighted_timespans = weighted_timespans *1/2;
            } else if(nbShortTsLastNBlocks == 6) {
                weighted_timespans = weighted_timespans *3/5;
                if(lastShortTimeInARaw ==6) {
                    weighted_timespans = weighted_timespans *7/8;
                }
            } else if(nbShortTsLastNBlocks == 5) {
                weighted_timespans = weighted_timespans *4/5;
                if(lastShortTimeInARaw ==5) {
                    weighted_timespans = weighted_timespans *7/8;
                }
            } else if(nbShortTsLastNBlocks == 4) {
                weighted_timespans = weighted_timespans *9/10;
                if(lastShortTimeInARaw ==4) {
                    weighted_timespans = weighted_timespans *7/8;
                }
            } else if(nbShortTsLastNBlocks == 3  ) {
                weighted_timespans = weighted_timespans *11/12;
                if(lastShortTimeInARaw ==3) {
                    weighted_timespans = weighted_timespans *7/8;
                }
            }
        }

        // adjust = 0.99 for N=60, leaving the + 1 for now as it's not affecting N
        target = 99 * (((length + 1) / 2) * target_seconds) / 100;
    }

    uint64_t minimum_timespan = target_seconds * length / 2;
    if (weighted_timespans < minimum_timespan) {
        weighted_timespans = minimum_timespan;
    }

    difficulty_type total_work = cumulative_difficulties.back() - cumulative_difficulties.front();
    assert(total_work > 0);

    uint64_t low, high;
    mul(total_work, target, low, high);

    if (high != 0) {

        return 0;
    }
    return (low / weighted_timespans);
}

difficulty_type next_difficulty_v5(std::vector<std::uint64_t> timestamps, std::vector<difficulty_type> cumulative_difficulties, size_t target_seconds) {

    if (timestamps.size() > DIFFICULTY_BLOCKS_COUNT_V4)
    {
        timestamps.resize(DIFFICULTY_BLOCKS_COUNT_V4);
        cumulative_difficulties.resize(DIFFICULTY_BLOCKS_COUNT_V4);
    }

    size_t timestamp_count = timestamps.size();
    assert(timestamp_count == cumulative_difficulties.size());
    if (timestamp_count <= 1) {
       return 1;
    }

    uint64_t prev_max_timestamp = timestamps[0];
    uint64_t weighted_timespans = 0;
    uint64_t target;

    int short_time_count = 0;
    bool last_was_short_time = false;

    for (size_t i = 1; i < timestamp_count; i++) {
	uint64_t max_timestamp = std::max(prev_max_timestamp, timestamps[i]);
        uint64_t timespan = boost::algorithm::clamp<uint64_t>(max_timestamp - prev_max_timestamp, 1, 11 * target_seconds);
 	last_was_short_time = false;

        if (i >= (timestamp_count - 7)) {
	    if (timespan < 90) {
                short_time_count++;
                last_was_short_time = true;
            }
        }
        weighted_timespans += i * timespan;
 	prev_max_timestamp = max_timestamp;
    }

    // Adjust faster if many blocks found too fast
    if (last_was_short_time) {
	switch (short_time_count) {
	    case 7: weighted_timespans = weighted_timespans * 3 / 5; break;
	    case 6: weighted_timespans = weighted_timespans * 5 / 7; break;
	    case 5: weighted_timespans = weighted_timespans * 4 / 5; break;
	    case 4: weighted_timespans = weighted_timespans * 9 / 10; break;
	    case 3: weighted_timespans = weighted_timespans * 11 / 12; break;
	}
    }

    // adjust = 0.99 for N=60, leaving the + 1 for now as it's not affecting N
    target = 99 * (((timestamp_count + 1) / 2) * target_seconds) / 100;

    uint64_t minimum_timespan = target_seconds * timestamp_count / 2;
    if (weighted_timespans < minimum_timespan) {
        weighted_timespans = minimum_timespan;
    }

    difficulty_type total_work = cumulative_difficulties.back() - cumulative_difficulties.front();
    assert(total_work > 0);

    uint64_t low, high;
    mul(total_work, target, low, high);

    if (high != 0) {
        return 0;
    }
    return (low / weighted_timespans);
}
}

max_stars_repo_name: blackrangersoftware/brs-scala

max_issues_repo_name: blackrangersoftware/brs-scala

max_forks_repo_name: blackrangersoftware/brs-scala


text:
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

#ifndef DMTR_LIBOS_SPDK_QUEUE_HH_IS_INCLUDED
#define DMTR_LIBOS_SPDK_QUEUE_HH_IS_INCLUDED

#include <boost/optional.hpp>
#include <dmtr/libos/io_queue.hh>
#include <memory>
#include <spdk/env.h>
#include <spdk/nvme.h>
#include <yaml-cpp/yaml.h>

namespace dmtr {

class spdk_queue: public io_queue {
    public: static struct spdk_nvme_ns *ns;
    public: static struct spdk_nvme_qpair *qpair;
    protected: static bool our_spdk_init_flag;

    // Block offset into the log.
    protected: unsigned int logOffset = 0;
    // Namespace ids start at 1 and are numbered consequitively.
    public: static int namespaceId;
    // Number of bytes in the namespace.
    public: static unsigned int namespaceSize;
    public: static unsigned int sectorSize;
    public: static char *partialBlock;
    // How many bytes of data are in partialBlock.
    private: unsigned int partialBlockUsage = 0;
    // processing threads
    protected: std::unique_ptr<task::thread_type> my_push_thread;
    protected: std::unique_ptr<task::thread_type> my_pop_thread;

    // storage functions
    public: int open(const char* pathname, int flags);
    public: int open2(const char* pathname, int flags, mode_t mode);
    public: int creat(const char* pahname, mode_t mode);

    // data path functions
    public: int push(dmtr_qtoken_t qt, const dmtr_sgarray_t &sga);
    public: int pop(dmtr_qtoken_t qt);
    public: int poll(dmtr_qresult_t &qr_out, dmtr_qtoken_t qt);

    public: void start_threads();
    private: int push_thread(task::thread_type::yield_type &yield, task::thread_type::queue_type &tq);
    private: int pop_thread(task::thread_type::yield_type &yield, task::thread_type::queue_type &tq);

    protected: int file_push(const dmtr_sgarray_t *sga, task::thread_type::yield_type &yield);
    protected: int file_pop(dmtr_sgarray_t *sga, task::thread_type::yield_type &yield);
    // spdk functions
    public: static int init_spdk(int argc, char *argv[]);
    public: static int init_spdk(YAML::Node &config, spdk_env_opts *opts);
    private: static int parseTransportId(spdk_nvme_transport_id *trid,
                                     std::string &transportType, std::string &devAddress);

    public: spdk_queue(int qd);
    public: static int new_object(std::unique_ptr<io_queue> &q_out, int qd);

    public: virtual ~spdk_queue() { };

};

} // namespace dmtr

#endif /* DMTR_LIBOS_SPDK_QUEUE_HH_IS_INCLUDED */

ext: hh

max_stars_repo_name: seemk/demikernel

max_issues_repo_name: seemk/demikernel

max_forks_repo_name: seemk/demikernel


text:
/**
 * @file    rpi/src/TCPSession.hpp
 *
 * @brief   TCP session class headers
 *
 * @author  João Borrego
 */

#include <iostream>
#include <ctime>
#include <boost/asio.hpp>
#include <boost/bind.hpp>

using boost::asio::ip::tcp;

#include "debug.hpp"
#include "constants.hpp"
#include "System.hpp"
#include "request.hpp"

/**
 * @brief      Class for TCP session.
 */
class TCPSession
{

private:

    /** TCP Socket */
    tcp::socket socket_;
    /** Request buffer */
    char recv_buffer_[RECV_BUFFER];
    /** Response buffer */
    char send_buffer_[SEND_BUFFER];
    /** System pointer */
    System::ptr system_;

    /* "Real-time" data stream */

    /** Timestamp of last update */
    std::vector< unsigned long > last_update_;
    /** Boolean flags */
    std::vector< bool > flags_;
    /** Timer */
    boost::asio::deadline_timer timer_;
    /** Stream buffer */
    char stream_buffer_[SEND_BUFFER];

public:

    /**
     * @brief      Constructor
     *
     * @param      io_service  The i/o service
     * @param      system      The system shared pointer
     */
    TCPSession(boost::asio::io_service & io_service, System::ptr system)
        :   socket_(io_service),
            flags_(STREAM_FLAGS * system->getNodes()),
            last_update_(system->getNodes()),
            timer_(io_service)
    {
        system_ = system;
    }

    ~TCPSession()
    {
        timer_.cancel();
    }

    /**
     * @brief      Obtains TCP socket.
     *
     * @return     TCP socket
     */
    tcp::socket & socket()
    {
        return socket_;
    }

    /**
     * @brief      Starts the session.
     */
    void start();

private:

    /**
     * @brief      Starts a read.
     */
    void startRead();

    /**
     * @brief      Handles a read.
     *
     * @param[in]  error  The error code
     */
    void handleRead(const boost::system::error_code & error,
        size_t bytes_transferred);

    /**
     * @brief      Starts a write.
     */
    void startWrite();

    /**
     * @brief      Handles a write response.
     *
     * @param[in]  error                The error code
     * @param[in]  bytes_transferred    The bytes transferred
     */
    void handleWrite(const boost::system::error_code & error,
        size_t bytes_transferred);

    /**
     * @brief      Starts a stream write.
     */
    void startStreamWrite();

    /**
     * @brief      Handles a write stream.
     *
     * @param[in]  error              The error code
     * @param[in]  bytes_transferred  The bytes transferred
     */
    void handleStreamWrite(const boost::system::error_code & error,
        size_t bytes_transferred);

    /**
     * @brief      Handles a periodic timer event.
     */
    void handleTimer(const boost::system::error_code & error);

};

max_stars_repo_name: jsbruglie/scdtr

max_issues_repo_name: jsbruglie/scdtr

max_forks_repo_name: jsbruglie/scdtr


text:
//  (C) Copyright Gennadiy Rozental 2011-2015.
//  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.

//[example_code
#define BOOST_TEST_MODULE example
#include <boost/test/included/unit_test.hpp>

#include <cmath>

BOOST_AUTO_TEST_CASE( test )
{
  // sin 45 radians is actually ~ 0.85, sin 45 degrees is ~0.707
  double res = std::sin( 45. );

  BOOST_WARN_MESSAGE( res < 0.71,
                      "sin(45){" << res << "} is > 0.71. Arg is not in radian?" );
}
//]


text:
#include <boost/bind.hpp>
#include "MazeSession.h"

using boost::asio::ip::tcp;

MazeSession::MazeSession(boost::asio::io_service & io_service, uint32_t player_id, MazeManager & maze_mgr) :
	socket_(io_service), player_id_(player_id), maze_mgr_(maze_mgr), started_(false), curr_maze_(0)
{}

MazeSession::~MazeSession()
{
	std::cout << "Session terminated for Player " << player_id_ << "." << std::endl;
}

void MazeSession::start()
{
	boost::asio::async_read(socket_,
		boost::asio::buffer(read_msg_.data(), GameMessage::HEADER_SIZE),
		boost::bind(
			&MazeSession::handleReadHeader, shared_from_this(),
			boost::asio::placeholders::error));
	started_ = true;

	PlayerID game_data(player_id_);
	GameMessage msg(GameMessage::GC_ID_NOTIFY, &game_data);
	write(msg);

	maze_mgr_.broadcastSummaryData();
}

void MazeSession::write(const GameMessage & msg)
{
	boost::mutex::scoped_lock lock(write_mutex_);
	bool write_in_progress = !write_msgs_.empty();
	write_msgs_.push_back(msg);
	if (!write_in_progress)
	{
		boost::asio::async_write(socket_,
			boost::asio::buffer(write_msgs_.front().data(), write_msgs_.front().length()),
			boost::bind(&MazeSession::handleWrite, shared_from_this(),
				boost::asio::placeholders::error));
	}
}

void MazeSession::handleReadHeader(const boost::system::error_code & error)
{
	if (error)
	{
		std::cerr << "ERROR: MazeSession::handleReadHeader [" << error.value() << ": " << error.message() << "]" << std::endl;
		leaveMaze();
		return;
	}

	if (read_msg_.decodeHeader())
	{
		boost::asio::async_read(socket_,
			boost::asio::buffer(read_msg_.body(), read_msg_.bodyLength()),
			boost::bind(&MazeSession::handleReadBody, shared_from_this(),
				boost::asio::placeholders::error));
	}
	else
	{
		std::cerr << "ERROR: MazeSession::handleReadHeader [Decode header failed]" << std::endl;
		leaveMaze();
	}
}

void MazeSession::handleReadBody(const boost::system::error_code & error)
{
	if (error)
	{
		std::cerr << "ERROR: MazeSession::handleReadBody [" << error.value() << ": " << error.message() << "]" << std::endl;
		leaveMaze();
		return;
	}

	processMessage(read_msg_);

	boost::asio::async_read(socket_,
		boost::asio::buffer(read_msg_.data(), GameMessage::HEADER_SIZE),
		boost::bind(&MazeSession::handleReadHeader, shared_from_this(),
			boost::asio::placeholders::error));
}

void MazeSession::handleWrite(const boost::system::error_code & error)
{
	if (error)
	{
		std::cerr << "ERROR: MazeSession::handleWrite [" << error.value() << ": " << error.message() << "]" << std::endl;
		leaveMaze();
		return;
	}

	boost::mutex::scoped_lock lock(write_mutex_);
	write_msgs_.pop_front();
	if (!write_msgs_.empty())
	{
		boost::asio::async_write(socket_,
			boost::asio::buffer(write_msgs_.front().data(),	write_msgs_.front().length()),
			boost::bind(&MazeSession::handleWrite, shared_from_this(),
				boost::asio::placeholders::error));
	}
}

void MazeSession::processMessage(GameMessage & game_msg)
{
	switch (game_msg.getGameCode())
	{
	case GameMessage::GC_CREATE_REQ:
		{
			game_config_ptr game_data = std::dynamic_pointer_cast<GameConfig>(game_msg.decodeBody());
			if (!game_data)
			{
				std::cerr << "ERROR: MazeSession::processMessage [Unexpected message received]" << std::endl << *game_data;
				return;
			}

			maze_mgr_.loadNewMaze(MazeConfig(game_data->getWidth(), game_data->getHeight(), game_data->getLevels()));
		}
		break;
	case GameMessage::GC_SELECT_GAME_REQ:
		{
			game_select_ptr game_data = std::dynamic_pointer_cast<GameSelect>(game_msg.decodeBody());
			if (!game_data)
			{
				std::cerr << "ERROR: MazeSession::processMessage [Unexpected message received]" << std::endl << *game_data;
				return;
			}

			if (!maze_mgr_.joinMaze(shared_from_this(), game_data->getSelection(), game_data->getNumPlayers()))
			{
				GameSelectResp select_resp(GameSelectResp::SR_FAIL);
				GameMessage msg(GameMessage::GC_SELECT_GAME_RESP, &select_resp);
				write(msg);

				std::cerr << "ERROR: MazeSession::processMessage [Failed to join maze]" << std::endl << *game_data;
				return;
			}

			curr_maze_ = game_data->getSelection();
		}
		break;
	case GameMessage::GC_MOVE_REQ:
		{
			move_req_ptr game_data = std::dynamic_pointer_cast<MoveReq>(game_msg.decodeBody());
			if (!game_data)
			{
				std::cerr << "ERROR: MazeSession::processMessage [Unexpected message received]" << std::endl << *game_data;
				return;
			}

			maze_mgr_.movePlayer(curr_maze_ - 1, player_id_, game_data);
		}
		break;
	case GameMessage::GC_CANCEL_REQ:
		{
			leaveMaze();
		}
		break;
	default:
		{
			std::cerr << "ERROR: MazeSession::processMessage [Unexpected message received]" << std::endl;
			game_data_ptr game_data = game_msg.decodeBody();
			if (game_data)
				std::cerr << *game_data;
			else
				std::cerr << "[Code=" << game_msg.getGameCode() << "]" << std::endl;
		}
		break;
	}
}

void MazeSession::leaveMaze()
{
	if (curr_maze_)
	{
		maze_mgr_.leaveMaze(shared_from_this(), (curr_maze_ - 1));
		curr_maze_ = 0;
	}
}


text:
/*
 * Copyright (C) 2012-2015 Open Source Robotics Foundation
 *
 * 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.
 *
 */
#include <string>
#include <boost/filesystem.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string/regex.hpp>
#include <sstream>

#include "gazebo/common/Exception.hh"
#include "gazebo/common/Time.hh"
#include "gazebo/common/Console.hh"

#include "gazebo/gazebo_config.h"

using namespace gazebo;
using namespace common;

FileLogger gazebo::common::Console::log("");
Logger Console::msg("[Msg] ", 32, Logger::STDOUT);
Logger Console::err("[Err] ", 31, Logger::STDERR);
Logger Console::dbg("[Dbg] ", 36, Logger::STDOUT);
Logger Console::warn("[Wrn] ", 33, Logger::STDERR);

bool Console::quiet = true;

//////////////////////////////////////////////////
void Console::SetQuiet(bool _quiet)
{
  quiet = _quiet;
}

//////////////////////////////////////////////////
bool Console::GetQuiet()
{
  return quiet;
}

/////////////////////////////////////////////////
Logger::Logger(const std::string &_prefix, int _color, LogType _type)
  : std::ostream(new Buffer(_type, _color)), color(_color), prefix(_prefix)
{
  this->setf(std::ios_base::unitbuf);
}

/////////////////////////////////////////////////
Logger::~Logger()
{
  delete this->rdbuf();
}

/////////////////////////////////////////////////
Logger &Logger::operator()()
{
  Console::log << "(" << Time::GetWallTime() << ") ";
  (*this) << this->prefix;

  return (*this);
}

/////////////////////////////////////////////////
Logger &Logger::operator()(const std::string &_file, int _line)
{
  int index = _file.find_last_of("/") + 1;

  Console::log << "(" << Time::GetWallTime() << ") ";
  (*this) << this->prefix
    << "[" << _file.substr(index , _file.size() - index) << ":"
    << _line << "] ";

  return (*this);
}

/////////////////////////////////////////////////
Logger::Buffer::Buffer(LogType _type, int _color)
  :  type(_type), color(_color)
{
}

/////////////////////////////////////////////////
Logger::Buffer::~Buffer()
{
  // Can't throw from a destructor
  try
  {
    this->pubsync();
  }
  catch(...)
  {
    std::cerr << "Exception thrown while pubsync'ing Buffer" << std::endl;
  }
}

/////////////////////////////////////////////////
int Logger::Buffer::sync()
{
  // Log messages to disk
  Console::log << this->str();
  Console::log.flush();

  // Output to terminal
  if (!Console::GetQuiet())
  {
    if (this->type == Logger::STDOUT)
    {
      #ifndef _WIN32
      std::cout << "\033[1;" << this->color << "m" << this->str() << "\033[0m";
      #else
      std::cout << this->str();
      #endif
    }
    else
    {
      #ifndef _WIN32
      std::cerr << "\033[1;" << this->color << "m" << this->str() << "\033[0m";
      #else
      std::cerr << this->str();
      #endif
    }
  }

  this->str("");
  return 0;
}

/////////////////////////////////////////////////
FileLogger::FileLogger(const std::string &_filename)
  : std::ostream(new Buffer(_filename)),
    logDirectory("")
{
  this->setf(std::ios_base::unitbuf);
}

/////////////////////////////////////////////////
FileLogger::~FileLogger()
{
  delete this->rdbuf();
}

/////////////////////////////////////////////////
void FileLogger::Init(const std::string &_prefix, const std::string &_filename)
{
  if (!getenv("HOME"))
  {
    gzerr << "Missing HOME environment variable."
          << "No log file will be generated.";
    return;
  }

  FileLogger::Buffer *buf = static_cast<FileLogger::Buffer*>(
      this->rdbuf());

  boost::filesystem::path logPath(getenv("HOME"));

  // Create a subdirectory for the informational log. The name of the directory
  // will be <PREFIX><MASTER_PORT>. E.g.: server-11346. If the environment
  // variable GAZEBO_MASTER_URI is not present or invalid, <MASTER_PORT> will
  // be replaced by "default".
  boost::filesystem::path subdir(_prefix + FileLogger::GetMasterPort());
  logPath = logPath / ".gazebo/" / subdir;

  // Create the log directory if it doesn't exist.
  if (!boost::filesystem::exists(logPath))
    boost::filesystem::create_directories(logPath);

  logPath /= _filename;

  // Check if the Init method has been already called, and if so
  // remove current buffer.
  if (buf->stream)
    delete buf->stream;

  // If the logPath is a directory, just rename it.
  if (boost::filesystem::is_directory(logPath))
  {
    std::string newPath = logPath.string() + ".old";
    boost::system::error_code ec;
    boost::filesystem::rename(logPath, newPath, ec);
    if (ec == 0)
      std::cerr << "Existing log directory [" << logPath
                << "] renamed to [" << newPath << "]" << std::endl;
    else
    {
      std::cerr << "Unable to rename existing log directory [" << logPath
                << "] to [" << newPath << "]. Reason: " << ec.message();
      return;
    }
  }

  buf->stream = new std::ofstream(logPath.string().c_str(), std::ios::out);
  if (!buf->stream->is_open())
    std::cerr << "Error opening log file: " << logPath << std::endl;

  // Output the version of gazebo.
  (*buf->stream) << GAZEBO_VERSION_HEADER << std::endl;

  // Update the log directory name.
  if (boost::filesystem::is_directory(logPath))
    this->logDirectory = logPath.string();
  else
    this->logDirectory = logPath.branch_path().string();
}

/////////////////////////////////////////////////
FileLogger &FileLogger::operator()()
{
  (*this) << "(" << Time::GetWallTime() << ") ";
  return (*this);
}

/////////////////////////////////////////////////
FileLogger &FileLogger::operator()(const std::string &_file, int _line)
{
  int index = _file.find_last_of("/") + 1;
  (*this) << "(" << Time::GetWallTime() << ") ["
    << _file.substr(index , _file.size() - index) << ":" << _line << "]";

  return (*this);
}

/////////////////////////////////////////////////
std::string FileLogger::GetMasterPort()
{
  char *charURI = getenv("GAZEBO_MASTER_URI");

  // Set to default port.
  if (charURI && strlen(charURI) > 0)
  {
    std::string masterURI = charURI;
    size_t lastColon = masterURI.find_last_of(":");
    if (lastColon != std::string::npos && lastColon != masterURI.size() - 1)
      return masterURI.substr(lastColon + 1, std::string::npos);
  }

  return boost::lexical_cast<std::string>(GAZEBO_DEFAULT_MASTER_PORT);
}

/////////////////////////////////////////////////
std::string FileLogger::GetLogDirectory() const
{
  return this->logDirectory;
}

/////////////////////////////////////////////////
FileLogger::Buffer::Buffer(const std::string &_filename)
  : stream(NULL)
{
  if (!_filename.empty())
  {
    this->stream = new std::ofstream(_filename.c_str(), std::ios::out);
  }
}

/////////////////////////////////////////////////
FileLogger::Buffer::~Buffer()
{
  try
  {
    if (this->stream)
      static_cast<std::ofstream*>(this->stream)->close();
  }
  catch(...)
  {
    std::cerr << "Exception thrown while closing Buffer" << std::endl;
  }
}

/////////////////////////////////////////////////
int FileLogger::Buffer::sync()
{
  if (!this->stream)
    return -1;

  *this->stream << this->str();

  this->stream->flush();

  this->str("");
  return !(*this->stream);
}

ext: cc

max_stars_repo_name: horikawahorikawa/gazebo-PR

max_issues_repo_name: shyamalschandra/gazebo-official

max_forks_repo_name: shyamalschandra/gazebo-official


text:
/****************************************************************************
 * Copyright (c) 2012-2020 by the DataTransferKit authors                   *
 * All rights reserved.                                                     *
 *                                                                          *
 * This file is part of the DataTransferKit library. DataTransferKit is     *
 * distributed under a BSD 3-clause license. For the licensing terms see    *
 * the LICENSE file in the top-level directory.                             *
 *                                                                          *
 * SPDX-License-Identifier: BSD-3-Clause                                    *
 ****************************************************************************/
/*!
 * \file
 * \brief C adapter to DTK Maps.
 */
#ifndef DTK_C_API_MAP_HPP
#define DTK_C_API_MAP_HPP

#include <DTK_C_API.h>
#include <DTK_C_API.hpp>
#include <DTK_DBC.hpp>
#include <DTK_MovingLeastSquaresOperator.hpp>
#include <DTK_NearestNeighborOperator.hpp>
#include <DTK_ParallelTraits.hpp>
#include <DTK_PointCloudOperator.hpp>
#include <DTK_UserApplication.hpp>

#include <boost/property_tree/json_parser.hpp>
#include <boost/property_tree/ptree.hpp>

#include <mpi.h>

#include <memory>
#include <string>
#include <tuple>

namespace DataTransferKit
{
//---------------------------------------------------------------------------//
// Map interface base class. This allows us to hide the device template
// parameter in MapImpl when we do the casting in the C interface
// implementation. We won't know what device type we have in a template when
// calling the C interface and we don't need to - the apply function
// implementation details will dispatch to the correct device type based on
// the construction.
struct DTK_Map
{
    virtual ~DTK_Map() = default;

    virtual void apply( const std::string &source_field_name,
                        const std::string &target_field_name ) = 0;
};

//---------------------------------------------------------------------------//
template <class MapExecSpace, class SourceMemSpace, class TargetMemSpace>
struct DTK_MapImpl : public DTK_Map
{
    using map_device_type = typename MapExecSpace::device_type;

    DTK_MapImpl( MPI_Comm comm, DTK_UserApplicationHandle source,
                 DTK_UserApplicationHandle target,
                 boost::property_tree::ptree const &ptree )
        : _source( reinterpret_cast<DTK_Registry *>( source )->_registry )
        , _target( reinterpret_cast<DTK_Registry *>( target )->_registry )
    {
        // FOR NOW JUST CREATE A NEAREST NEIGHBOR OPERATOR FOR DEMONSTRATION
        // PURPOSES. THIS WILL BE REPLACED BY A PROPER FACTORY.

        // Get coordinates from the source and target.
        auto source_nodes = _source.getNodeList().coordinates;
        auto target_nodes = _target.getNodeList().coordinates;

        // For now things are layout left in the interface so copy to a
        // matching layout that is compatible with the operator.
        Kokkos::View<Coordinate **, map_device_type> source_nodes_copy(
            "src_nodes_copy", source_nodes.extent( 0 ),
            source_nodes.extent( 1 ) );
        Kokkos::deep_copy( source_nodes_copy, source_nodes );
        Kokkos::View<Coordinate **, map_device_type> target_nodes_copy(
            "tgt_nodes_copy", target_nodes.extent( 0 ),
            target_nodes.extent( 1 ) );
        Kokkos::deep_copy( target_nodes_copy, target_nodes );

        auto const which_map =
            ptree.get<std::string>( "Map Type", "Undefined" );
        if ( which_map == "Undefined" )
            throw DataTransferKitException(
                R"(Field "Map Type" is not defined in options string argument for map creation)" );
        else if ( which_map == "Nearest Neighbor" || which_map == "NN" )
            _map = std::unique_ptr<NearestNeighborOperator<map_device_type>>(
                new NearestNeighborOperator<map_device_type>(
                    comm, source_nodes_copy, target_nodes_copy ) );
        else if ( which_map == "Moving Least Squares" || which_map == "MLS" )
        {
            // NOTE if field "Order" is misspelled (for instance first letter
            // not capitalized), the default value (linear polynomials) will be
            // picked up without a warning or an error being raised.
            auto const order = ptree.get<std::string>( "Order", "Linear" );
            if ( order == "Linear" || order == "1" )
                _map = std::unique_ptr<MovingLeastSquaresOperator<
                    map_device_type, Wendland<0>,
                    MultivariatePolynomialBasis<Linear, 3>>>(
                    new MovingLeastSquaresOperator<
                        map_device_type, Wendland<0>,
                        MultivariatePolynomialBasis<Linear, 3>>(
                        comm, source_nodes_copy, target_nodes_copy ) );
            else if ( order == "Quadratic" || order == "2" )
                _map = std::unique_ptr<MovingLeastSquaresOperator<
                    map_device_type, Wendland<0>,
                    MultivariatePolynomialBasis<Quadratic, 3>>>(
                    new MovingLeastSquaresOperator<
                        map_device_type, Wendland<0>,
                        MultivariatePolynomialBasis<Quadratic, 3>>(
                        comm, source_nodes_copy, target_nodes_copy ) );
            else
                throw DataTransferKitException(
                    "Invalid order \"" + order +
                    "\" for creating a moving least squares map" );
        }
        else
            throw DataTransferKitException( "Invalid map type \"" + which_map +
                                            "\"" );
    }

    void apply( const std::string &source_field_name,
                const std::string &target_field_name ) override
    {
        // Create fields.
        auto source_field = _source.getField( source_field_name );
        auto target_field = _target.getField( target_field_name );

        // Pull the data from the source.
        _source.pullField( source_field_name, source_field );

        // Copy to a compatible layout. Nearest neighbor operator needs a
        // compatible layout and only 1 dimension
        int num_src = source_field.dofs.extent( 0 );
        Kokkos::View<double *, map_device_type> source_field_copy(
            "source_field_copy", num_src );
        Kokkos::deep_copy(
            source_field_copy,
            Kokkos::subview( source_field.dofs, Kokkos::ALL, 0 ) );
        int num_tgt = target_field.dofs.extent( 0 );
        Kokkos::View<double *, map_device_type> target_field_copy(
            "target_field_copy", num_tgt );

        // Apply the map.
        _map->apply( source_field_copy, target_field_copy );

        // Copy the transferred field back to the original target layout.
        Kokkos::deep_copy( Kokkos::subview( target_field.dofs, Kokkos::ALL, 0 ),
                           target_field_copy );

        // Push the data to the target.
        _target.pushField( target_field_name, target_field );
    }

    UserApplication<double, SourceMemSpace> _source;
    UserApplication<double, TargetMemSpace> _target;
    std::unique_ptr<PointCloudOperator<map_device_type>> _map;
};

//---------------------------------------------------------------------------//
// Execution space validation.
bool validExecutionSpace( DTK_ExecutionSpace space )
{
    switch ( space )
    {
    case DTK_SERIAL:
#if defined( KOKKOS_ENABLE_SERIAL )
        return true;
        break;
#else
        return false;
        break;
#endif

    case DTK_OPENMP:
#if defined( KOKKOS_ENABLE_OPENMP )
        return true;
        break;
#else
        return false;
        break;
#endif

    case DTK_CUDA:
#if defined( KOKKOS_ENABLE_CUDA )
        return true;
        break;
#else
        return false;
        break;
#endif
    default:
        return false;
        break;
    }
}

// Memory space validation.
bool validMemorySpace( DTK_MemorySpace space )
{
    switch ( space )
    {
    case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
        return true;
        break;
#else
        return false;
        break;
#endif
    case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
        return true;
        break;
#else
        return false;
        break;
#endif
    default:
        return false;
        break;
    }
}

// Map space validation.
bool validMapSpaces( DTK_ExecutionSpace map_space, DTK_MemorySpace source_space,
                     DTK_MemorySpace target_space )
{
    return validExecutionSpace( map_space ) &&
           validMemorySpace( source_space ) && validMemorySpace( target_space );
}

//---------------------------------------------------------------------------//
// Create a map.
DTK_Map *createMap( DTK_ExecutionSpace map_space, MPI_Comm comm,
                    DTK_UserApplicationHandle source,
                    DTK_UserApplicationHandle target, const char *options )
{
    // Parse options.
    std::stringstream ss;
    ss.str( options );
    boost::property_tree::ptree ptree;
    // read_json calls seq_index_node which is not compatible with cuda 10 (see
    // https://stackoverflow.com/questions/55143135/error-cannot-call-member-function-impl-of-impl-pointer-in-boost)
    // So we disable reading json file for now
    //  try
    //  {
    //      boost::property_tree::read_json( ss, ptree );
    //  }
    //  catch ( boost::property_tree::json_parser_error )
    //  {
    //      throw DataTransferKitException(
    //          "Error while parsing JSON format in options string argument "
    //          "for map creation" );
    //  }

    // Get the user source and target memory spaces.
    DTK_MemorySpace src_space =
        reinterpret_cast<DataTransferKit::DTK_Registry *>( source )->_space;
    DTK_MemorySpace tgt_space =
        reinterpret_cast<DataTransferKit::DTK_Registry *>( target )->_space;

    // Check up front that we have been asked for execution and memory spaces
    // that are available in the kokkos build. This lets use a little cleaner
    // macro logic below because we know we will get a valid map space
    // already.
    DTK_INSIST( validMapSpaces( map_space, src_space, tgt_space ) );

    DTK_Map *map = nullptr;
    switch ( map_space )
    {
    case DTK_SERIAL:
#if defined( KOKKOS_ENABLE_SERIAL )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Serial, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
                map = new DTK_MapImpl<Serial, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
#endif
                break;
            }
            break;

        case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Serial, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Serial, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;
        }
#endif
        break;

    case DTK_OPENMP:
#if defined( KOKKOS_ENABLE_OPENMP )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<OpenMP, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
                map = new DTK_MapImpl<OpenMP, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
#endif
                break;
            }
            break;

        case DTK_CUDAUVM_SPACE:
#if defined( KOKKOS_ENABLE_CUDA )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<OpenMP, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<OpenMP, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;
        }
#endif
        break;

    case DTK_CUDA:
#if defined( KOKKOS_ENABLE_CUDA )
        switch ( src_space )
        {
        case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
                map = new DTK_MapImpl<Cuda, HostSpace, HostSpace>(
                    comm, source, target, ptree );
                break;

            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Cuda, HostSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
#endif
            break;

        case DTK_CUDAUVM_SPACE:
            switch ( tgt_space )
            {
            case DTK_HOST_SPACE:
#if defined( KOKKOS_ENABLE_SERIAL ) || defined( KOKKOS_ENABLE_OPENMP )
                map = new DTK_MapImpl<Cuda, CudaUVMSpace, HostSpace>(
                    comm, source, target, ptree );
#endif
                break;
            case DTK_CUDAUVM_SPACE:
                map = new DTK_MapImpl<Cuda, CudaUVMSpace, CudaUVMSpace>(
                    comm, source, target, ptree );
                break;
            }
            break;
        }
#endif
        break;
    }

    return map;
}

//---------------------------------------------------------------------------//

} // namespace DataTransferKit

#endif // DTK_C_API_MAP_HPP

max_stars_repo_name: Rombur/DataTransferKit

max_issues_repo_name: Rombur/DataTransferKit

max_forks_repo_name: Rombur/DataTransferKit


text:
#ifndef COMMON_HPP
#define COMMON_HPP
//#include <math.h>
#include <string>
#include <cstring>
#include <cstdlib>
#include <stdexcept>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <list>
#include <vector>
#include <cmath>
#include <boost/smart_ptr.hpp>
#include <boost/numeric/ublas/storage.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <boost/format.hpp>
#include <fstream>
#include <eigen3/Eigen/Dense>
//#include <Eigen/Geometry>
/** configuration */
#include "config.hpp"

/** definitions for printing output */
#define SEP ", "
#define METERS " [m]"
#define MILLIMETERS " [mm]"
#define VELOCITY " [mm/s]"
#define ACCELERATION " [mm/s²]"
#define DEG " [deg]"
#define RAD " [rad]"
#define COLUMN ":"
#define SPACE " "
#define XposSTR "Xpos = "
#define YposSTR "Ypos = "
#define ZposSTR "Zpos = "
#define RollSTR "Roll = "
#define PitchSTR "Pitch = "
#define YawSTR "Yaw = "
#define XsizeSTR "Xsize = "
#define YsizeSTR "Ysize = "
#define ZsizeSTR "Zsize = "
#define VelocitySTR "Velocity = "
#define AccelerationSTR "Acceleration = "
//definition of the macro ASSERT
#ifndef DEBUG
#define ASSERT(x)
#else
#define ASSERT(x) \
    if (! (x)) \
    { \
        cout << "ERROR!! Assert " << #x << " failed\n"; \
        cout << " on line " << __LINE__  << "\n"; \
        cout << " in file " << __FILE__ << "\n";  \
    }
#endif

using namespace std;
using namespace Eigen;

namespace motion_manager
{
#if UR == 0
  const int JOINTS_ARM = 7; /**< number of joints per arm */
#elif UR == 1
  const int JOINTS_ARM = 6; /**< number of joints per arm */
#endif
#if HAND == 0
//*************************************************************************************************
//                                 BARRETT HAND
    const double THETA8_HOME = 0.0; /**< constant of the joint 8 (spread of the hand) in [rad] */
    const double THETA8_FINAL = 0.0; /**< constant of the joint 8 (spread of the hand) in [rad] */
    const double TOL_GRIP = 0.0; /**< tolerance on the grip in [mm] */
    const int firstPartTorqueOvershootCountRequired = 1;/**< number of time that the torque applied to the first phalanx is bigger than firstPartMaxTorque */
    const double firstPartMaxTorque = 0.9f;/**< max torque that can be applied to the first phalanx of the fingers */
    const double closingOpeningTorque = 1.0f;/**< torque applied to the fingers when they are opening/closing */
    const double closingVel = 60.0f * static_cast<double>(M_PI) / 180.0f; /**< joint velocity of the fingers when they are closing */
    const double openingVel = -120.0f * static_cast<double>(M_PI) / 180.0f;/**< joint velocity of the fingers when they are opening */

    const int HAND_FINGERS = 3; /**< number of fingers per hand */
    const int JOINTS_HAND = 4; /**< number of joints per hand */
    const int N_PHALANGE = 3; /**< number of phalanges per finger */
#elif HAND == 1
  //*************************************************************************************************
  //                                 ELECTRIC PARALLEL GRIPPER
    const double TOL_GRIP = 0; /**< tolerance on the grip in [mm] */
    const double TOL_TOOL_GRIP = - 0.315; /**< tolerance on the grip tool in [mm] */
    const int JOINTS_HAND = 1; /**< number of joints per hand */
    const int HAND_FINGERS = 2; /**< number of fingers per hand */

    const int N_PHALANGE = 0; /**< number of phalanges per finger */
#elif HAND == 2
    const double TOL_GRIP = 0; /**< tolerance on the grip in [mm] */
    const double TOL_TOOL_GRIP = - 0.315; /**< tolerance on the grip tool in [mm] */

    const int JOINTS_HAND = 0; /**< number of joints per hand */
    const int HAND_FINGERS = 0; /**< number of fingers per hand */
    const int N_PHALANGE = 0; /**< number of phalanges per finger */

#endif

    /** this struct defines the position in the Cartesian space*/
    typedef struct
    {
        double Xpos; /**< position along the x axis in [mm] */
        double Ypos; /**< position along the y axis in [mm] */
        double Zpos; /**< position along the z axis in [mm] */
    } pos;

    /** this struct defines the orientation in Roll-Pitch-Yaw */
    typedef struct
    {
        double roll; /**< rotarion around the z axis in [rad] */
        double pitch; /**< rotarion around the y axis in [rad] */
        double yaw; /**< rotarion around the x axis in [rad] */
    } orient;

    /** this struct defines the dimention of an object */
    typedef struct
    {
        double Xsize; /**< size of the object along the x axis in [mm] */
        double Ysize; /**< size of the object along the y axis in [mm] */
        double Zsize; /**< size of the object along the z axis in [mm] */
    } dim;

    /** this struct defines the Denavit-Hartenberg kinematic parameters */
    typedef struct
    {
        vector<double> d; /**< distances between consecutive frames along the x axes in [mm] */
        vector<double> a; /**< distances between concecutive frames along the z axes in [mm] */
        vector<double> alpha; /**< angle around the x axes between consecutive z axes in [rad] */
        vector<double> theta; /**< angle around the z axes between consecutive x axes in [rad] */
    } DHparams;

    /** this struct defines the arm */
    typedef struct
    {
        DHparams arm_specs; /**< the Denavit-Hartenberg parameters of the arm */
    } arm;

    /** this struct defines the barrett hand */
    typedef struct
    {
        double maxAperture; /**< [mm] max aperture of the hand in [mm] */
        double Aw; /**< smallest distance between F1 and F2 in [mm] */
        double A1; /**< length of the 1st part of the finger in [mm] */
        double A2; /**< length of the first phalax in [mm] */
        double A3; /**< length of the second phalax in [mm] */
        double D3; /**< depth of the fingertip in [mm] */
        double phi2; /**< angular displacement between the 1st part of the finger and the 1st phalax in [rad] */
        double phi3; /**< angular displacement between the 1st and the 2nd phalax in [rad] */
    } barrett_hand;

    /** this struct defines the electric gripper */
    typedef struct
    {
        double maxAperture; /**< [mm] max aperture of the hand in [mm] */
        double minAperture; /**< [mm] max aperture of the hand in [mm] */
        double A1; /**< length of the finger in [mm] */
        double D3; /**< depth of the fingertip in [mm] */
    } electric_gripper;

    /** this struct defines the vacuum gripper */
    typedef struct
    {
        double D7; /**< length of the vaccum gripper [mm] */
    } vacuum_gripper;

    /** this struct defines a generic part of a robot body */
    typedef struct
    {
        double Xpos; /**< position of the part along the x axis in [mm] */
        double Ypos; /**< position of the part along the y axis in [mm] */
        double Zpos; /**< position of the part along the z axis in [mm] */
        double Roll; /**< orientation of the part around the z axis in [rad] */
        double Pitch; /**< orientation of the part around the y axis in [rad] */
        double Yaw; /**< orientation of the part around the x axis in [rad] */
        double Xsize; /**< size of the part along the x axis in [mm] */
        double Ysize; /**< size of the part along the y axis in [mm] */
        double Zsize; /**< size of the part along the z axis in [mm] */
    } robot_part;

    /** this struct defines a generic part of a robot body with orientation in quaternions*/
    typedef struct
    {
        double Xpos; /**< position of the part along the x axis in [mm] */
        double Ypos; /**< position of the part along the y axis in [mm] */
        double Zpos; /**< position of the part along the z axis in [mm] */
        float q_X;  /** The X value of the vector component of the quaternion. */
        float q_Y;  /** The Y value of the vector component of the quaternion. */
        float q_Z;  /** The Z value of the vector component of the quaternion. */
        float q_W; /** The rotation component of the quaternion. */
        double Xsize; /**< size of the part along the x axis in [mm] */
        double Ysize; /**< size of the part along the y axis in [mm] */
        double Zsize; /**< size of the part along the z axis in [mm] */
    } robot_part_q;

    /** this struct defines the orientation in quaternions
     quaternion \f$ w+xi+yj+zk - four scalar coefficients  w, x, y and z. */
    typedef struct{
        float X;  /** The X value of the vector component of the quaternion. */
        float Y;  /** The Y value of the vector component of the quaternion. */
        float Z;  /** The Z value of the vector component of the quaternion. */
        float W; /** The rotation component of the quaternion. */
    } orient_q;

    /** this struct defines the  waypoint in Operational Space */
    typedef struct{
        pos position;         /** Position X,Y,Z */
        orient_q or_quat;  /** Orientation in Quaternions  */
        orient or_rpy;
        vector <double> velocity; /**< vector of angular velocity of the end effector in the waypoint   */
        vector <double> accelaration; /**< vector of angular accelaration of the end effector in the waypoint */
                                       /** velocity  and acceleration in x,y,z and wx,wy,wz   linear and angular velocity??*/
    } WpOperatSpace;

    /** this struct defines the  waypoint in Joint Space */
    typedef struct{
        vector <double> PosJoints; /** vector of Joints Positions in Joint Space*/
        vector <double> velocity; /**< vector of angular velocity of each joint in the waypoint   */
        vector <double> accelaration; /**< vector of angular accelaration of each joint in the waypoint */
    } WpJointSpace;

    /** this struct defines the waypoint in Joint Space and Operational Space*/
    typedef struct
    {   string name;
        WpJointSpace JointSpace;
        WpOperatSpace OperatSpace;
    } waypoint;

}// namespace motion_manager

#endif // COMMON_HPP