text:
// Author(s): Camille Wormser, Pierre Alliez
// Example of an AABB tree used with indexed triangle set

#include <iostream>
#include <list>
#include <boost/iterator/iterator_adaptor.hpp>

#include <CGAL/Simple_cartesian.h>
#include <CGAL/AABB_tree.h>
#include <CGAL/AABB_traits.h>

typedef CGAL::Simple_cartesian<double> K;

// My own point type:
struct My_point {
    double x;
    double y;
    double z;

    My_point (double _x, double _y, double _z)
        : x(_x), y(_y), z(_z) {}
};

// The triangles are stored in a flat array of indices
// referring to an array of points: three consecutive
// indices represent a triangle.
typedef std::vector<size_t>::const_iterator Point_index_iterator;

// Let us now define the iterator on triangles that the tree needs:
class Triangle_iterator
    : public boost::iterator_adaptor<
    Triangle_iterator               // Derived
    , Point_index_iterator            // Base
    , boost::use_default              // Value
    , boost::forward_traversal_tag    // CategoryOrTraversal
    >
{
public:
    Triangle_iterator()
        : Triangle_iterator::iterator_adaptor_() {}

    explicit Triangle_iterator(Point_index_iterator p)
        : Triangle_iterator::iterator_adaptor_(p) {}

private:
    friend class boost::iterator_core_access;
    void increment() { this->base_reference() += 3; }
};

// The following primitive provides the conversion facilities between
// my own triangle and point types and the CGAL ones
struct My_triangle_primitive {
public:
    typedef Triangle_iterator    Id;

    // the CGAL types returned
    typedef K::Point_3    Point;
    typedef K::Triangle_3 Datum;

    // a static pointer to the vector containing the points
    // is needed to build the triangles on the fly:
    static const std::vector<My_point>* point_container;

private:
    Id m_it; // this is what the AABB tree stores internally

public:
    My_triangle_primitive() {} // default constructor needed

    // the following constructor is the one that receives the iterators from the
    // iterator range given as input to the AABB_tree
    My_triangle_primitive(Triangle_iterator a)
        : m_it(a) {}

    Id id() const { return m_it; }

    // on the fly conversion from the internal data to the CGAL types
    Datum datum() const
    {
        Point_index_iterator p_it = m_it.base();
        const My_point& mp = (*point_container)[*p_it];
        Point p(mp.x, mp.y, mp.z);
        ++p_it;
        const My_point& mq = (*point_container)[*p_it];
        Point q(mq.x, mq.y, mq.z);
        ++p_it;
        const My_point& mr = (*point_container)[*p_it];
        Point r(mr.x, mr.y, mr.z);

        return Datum(p, q, r); // assembles triangle from three points
    }

    // one point which must be on the primitive
    Point reference_point() const
    {
        const My_point& mp = (*point_container)[*m_it];
        return Point(mp.x, mp.y, mp.z);
    }
};

// types
typedef CGAL::AABB_traits<K, My_triangle_primitive> My_AABB_traits;
typedef CGAL::AABB_tree<My_AABB_traits> Tree;
const std::vector<My_point>* My_triangle_primitive::point_container = 0;

int main()
{
    // generates point set
    My_point a(1.0, 0.0, 0.0);
    My_point b(0.0, 1.0, 0.0);
    My_point c(0.0, 0.0, 1.0);
    My_point d(0.0, 0.0, 0.0);

    std::vector<My_point> points;
    My_triangle_primitive::point_container = &points;
    points.push_back(a);
    points.push_back(b);
    points.push_back(c);
    points.push_back(d);

    // generates indexed triangle set
    std::vector<size_t> triangles;
    triangles.push_back(0); triangles.push_back(1); triangles.push_back(2);
    triangles.push_back(0); triangles.push_back(1); triangles.push_back(3);
    triangles.push_back(0); triangles.push_back(3); triangles.push_back(2);

    // constructs AABB tree
    Tree tree(Triangle_iterator(triangles.begin()),
        Triangle_iterator(triangles.end()));

    // counts #intersections
    K::Ray_3 ray_query(K::Point_3(0.2, 0.2, 0.2), K::Point_3(0.0, 1.0, 0.0));
    std::cout << tree.number_of_intersected_primitives(ray_query)
        << " intersections(s) with ray query" << std::endl;

    // computes closest point
    K::Point_3 point_query(2.0, 2.0, 2.0);
    K::Point_3 closest_point = tree.closest_point(point_query);

    std::cerr << "closest point is: " << closest_point << std::endl;
    return EXIT_SUCCESS;
}

ext: cpp

max_stars_repo_name: gaschler/cgal

max_issues_repo_name: gaschler/cgal

max_forks_repo_name: gaschler/cgal


text:
/*************************************************************************
    > File Name: LayoutDB.cpp
    > Author: Yibo Lin
    > Mail: yibolin@utexas.edu
    > Created Time: Sat 29 Aug 2015 11:45:41 AM CDT
 ************************************************************************/

#include "LayoutDB.h"
#include <boost/dynamic_bitset.hpp>

SIMPLEMPL_BEGIN_NAMESPACE

namespace gtl = boost::polygon;
namespace bg = boost::geometry;
namespace bgi = bg::index;

LayoutDB::LayoutDB()
    : LayoutDB::base_type()
{
    initialize();
}
LayoutDB::LayoutDB(LayoutDB::coordinate_type xl, LayoutDB::coordinate_type yl, LayoutDB::coordinate_type xh, LayoutDB::coordinate_type yh)
    : LayoutDB::base_type(xl, yl, xh, yh)
{
    initialize();
}
LayoutDB::LayoutDB(LayoutDB const& rhs)
    : LayoutDB::base_type(rhs)
{
    copy(rhs);
}
LayoutDB::~LayoutDB()
{
    // recycle
    for (std::vector<rectangle_pointer_type>::iterator it = vPatternBbox.begin(), ite = vPatternBbox.end(); it != ite; ++it)
        delete *it;
}
LayoutDB& LayoutDB::operator=(LayoutDB const& rhs)
{
    if (this != &rhs)
    {
        this->base_type::operator=(rhs);
        copy(rhs);
    }
    return *this;
}
void LayoutDB::initialize()
{
    strname                  = "TOPCELL";
    unit                     = 0.001;
    coloring_distance        = 0;
}
void LayoutDB::copy(LayoutDB const& rhs)
{
    hPath    = rhs.hPath;
    strname  = rhs.strname;
    unit     = rhs.unit;
    coloring_distance = rhs.coloring_distance;
    // options
    parms    = rhs.parms;
    // layout information
    tPatternBbox = rhs.tPatternBbox;
    vPatternBbox = rhs.vPatternBbox;
}
void LayoutDB::add(int32_t layer, std::vector<point_type> const& vPoint)
{
    // classify features
    // sometimes path may be defined as boundary
    if (parms.sPathLayer.count(layer))
        this->add_path(layer, vPoint);
    else
        this->add_pattern(layer, vPoint);
}
void LayoutDB::add_path(int32_t layer, std::vector<point_type> const& vPoint)
{
    if (vPoint.size() < 2) return;

    path_type p;
    if (vPoint.size() == 2) // initialized by path
        p = gtl::construct<path_type>(vPoint.front(), vPoint.back());
    else if (vPoint.size() == 4) // probably it is initialized from boundary
    {
        gtl::coordinate_traits<coordinate_type>::coordinate_distance dist[] = {
            gtl::euclidean_distance(vPoint[0], vPoint[1]),
            gtl::euclidean_distance(vPoint[1], vPoint[2])
        };
        // simply check if one edge is much longer than the other and choose the longer one
        int32_t offset = -1;
        if (dist[0] > 10*dist[1])
            offset = 0;
        else if (10*dist[0] < dist[1])
            offset = 1;
        if (offset >= 0)
            p = gtl::construct<path_type>(vPoint[offset], vPoint[offset+1]);
        else return;
    }
    if (hPath.count(layer))
        hPath[layer].push_back(p);
    else mplAssert(hPath.insert(make_pair(layer, std::vector<path_type>(1, p))).second);
}
void LayoutDB::initialize_data()
{
    // remember to set coloring_distance from coloring_distance_nm and unit
    coloring_distance = (coordinate_difference)round(coloring_distance_nm()/(unit*1e+9));
}
void LayoutDB::report_data_kernel() const
{
    mplPrint(kINFO, "Total patterns # = %lu\n", vPatternBbox.size());
    mplPrint(kINFO, "Shape mode = %s\n", std::string(shape_mode()).c_str());
    mplPrint(kINFO, "Coloring distance = %lld db ( %g nm )\n", coloring_distance, coloring_distance_nm());
    mplPrint(kINFO, "Color num = %d\n", color_num());
    mplPrint(kINFO, "Simplification level = %u\n", simplify_level());
    mplPrint(kINFO, "Thread num = %u\n", thread_num());
    mplPrint(kINFO, "Uncolored layer # = %lu", parms.sUncolorLayer.size());
    if (!parms.sUncolorLayer.empty())
    {
        mplPrint(kNONE, " ( ");
        for (std::set<int32_t>::const_iterator it = parms.sUncolorLayer.begin(), ite = parms.sUncolorLayer.end(); it != ite; ++it)
            mplPrint(kNONE, "%d ", *it);
        mplPrint(kNONE, ")");
    }
    mplPrint(kNONE, "\n");
    mplPrint(kINFO, "Precolored layer # = %lu", parms.sPrecolorLayer.size());
    if (!parms.sPrecolorLayer.empty())
    {
        mplPrint(kNONE, " ( ");
        for (std::set<int32_t>::const_iterator it = parms.sPrecolorLayer.begin(), ite = parms.sPrecolorLayer.end(); it != ite; ++it)
            mplPrint(kNONE, "%d ", *it);
        mplPrint(kNONE, ")");
    }
    mplPrint(kNONE, "\n");
    mplPrint(kINFO, "Path layer # = %lu", parms.sPathLayer.size());
    if (!parms.sPathLayer.empty())
    {
        mplPrint(kNONE, " ( ");
        for (std::set<int32_t>::const_iterator it = parms.sPathLayer.begin(), ite = parms.sPathLayer.end(); it != ite; ++it)
            mplPrint(kNONE, "%d ", *it);
        mplPrint(kNONE, ")");
    }
    mplPrint(kNONE, "\n");
    mplPrint(kINFO, "Algorithm = %s\n", std::string(algo()).c_str());

    // if defined sPathLayer, then hPath must not be empty
    mplAssertMsg(parms.sPathLayer.empty() == hPath.empty(), "defined %lu path layers, but no path read from input\n", parms.sPathLayer.size());

}
void LayoutDB::update_bbox(base_type const& bbox)
{
    // LayoutDB is an abstract class
    // under g++ 4.8, it complains construction of abstract class in gtl::construct<T>()
    // actually we only want to call gtl::assign<base_type, base_type>() and gtl::encompass<base_type, base_type>()
    // so simply specialize it
    if (vPatternBbox.empty())
        gtl::assign<base_type>(*this, bbox);
    else
        gtl::encompass<base_type>(*this, bbox);
}
void LayoutDB::check_layer_and_color(int32_t layer, bool& pattern_layer_flag, int8_t& color) const
{
    pattern_layer_flag = true;
    color = -1;
    if (parms.sPrecolorLayer.count(layer))
    {
        // for precolored patterns
        // set colors
        color = layer-*parms.sPrecolorLayer.begin();
    }
    else if (parms.sUncolorLayer.count(layer))
    {
        // for uncolored patterns
    }
    else pattern_layer_flag = false;
}
/// remove overlapping patterns
/// based on scanline approach, horizontal sort and then vertical sort
/// O(nlogn)
void LayoutDB::remove_overlap(std::vector<LayoutDB::rectangle_pointer_type>& vTargetPattern)
{
    // do nothing if empty
    if (vTargetPattern.empty()) return;
    std::sort(vTargetPattern.begin(), vTargetPattern.end(), compare_rectangle_type());
    // only duplicate is removed so far
    // TO DO: remove overlapping patterns
    boost::dynamic_bitset<uint32_t, std::allocator<uint32_t> > vValid (vTargetPattern.size()); // use a bit set to record validity
    vValid.set(); // set all to 1
#ifdef DEBUG
    mplAssert(vValid[0] && vValid[vTargetPattern.size()-1]);
#endif
    uint32_t duplicate_cnt = 0;
    for (std::vector<rectangle_pointer_type>::iterator it1 = vTargetPattern.begin(), it2 = vTargetPattern.begin();
            it2 != vTargetPattern.end(); ++it2)
    {
        if (it2 != vTargetPattern.begin())
        {
            rectangle_pointer_type& pPattern1 = *it1;
            rectangle_pointer_type& pPattern2 = *it2;

            if (gtl::equivalence(*pPattern1, *pPattern2))
            {
#ifdef DEBUG
                mplPrint(kWARN, "%s duplicates with %s ignored %u\n", std::string(*pPattern1).c_str(), std::string(*pPattern2).c_str(), duplicate_cnt);
#endif
                vValid[pPattern2->pattern_id()] = false;
                duplicate_cnt += 1;
                continue;
            }
        }
        it1 = it2;
    }
    mplPrint(kINFO, "Ignored %u duplicate patterns\n", duplicate_cnt);

    // erase invalid patterns
    uint32_t invalid_cnt = 0;
    for (uint32_t i = 0; i < vTargetPattern.size(); )
    {
        if (!vValid[vTargetPattern[i]->pattern_id()])
        {
            std::swap(vTargetPattern[i], vTargetPattern.back());
            delete vTargetPattern.back(); // recycle
            vTargetPattern.pop_back();
            invalid_cnt += 1;
        }
        else ++i;
    }
    mplAssert(duplicate_cnt == invalid_cnt);
#ifdef DEBUG
    for (uint32_t i = 0; i != vTargetPattern.size(); ++i)
        mplAssert(vValid[vTargetPattern[i]->pattern_id()]);
#endif
    // update pattern_id
    for (uint32_t i = 0; i != vTargetPattern.size(); ++i)
        vTargetPattern[i]->pattern_id(i);
}

SIMPLEMPL_END_NAMESPACE

max_stars_repo_name: wadmes/OpenMPL

max_issues_repo_name: wadmes/OpenMPL

max_forks_repo_name: wadmes/OpenMPL


text:
/*
 * Copyright (c) 2015-2016 Spotify AB
 *
 * 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 <vector>

#include <boost/test/unit_test.hpp>

#include <spotify/json/codec/any_value.hpp>
#include <spotify/json/codec/array.hpp>
#include <spotify/json/codec/boolean.hpp>
#include <spotify/json/codec/number.hpp>
#include <spotify/json/codec/omit.hpp>
#include <spotify/json/decode.hpp>
#include <spotify/json/encode.hpp>

BOOST_AUTO_TEST_SUITE(spotify)
BOOST_AUTO_TEST_SUITE(json)
BOOST_AUTO_TEST_SUITE(codec)

namespace {

template <typename Parsed = std::vector<bool>>
Parsed array_parse(const char *not_array) {
  const auto codec = default_codec<Parsed>();
  auto ctx = decode_context(not_array, not_array + strlen(not_array));
  const auto result = codec.decode(ctx);

  BOOST_CHECK_EQUAL(ctx.position, ctx.end);
  return result;
}

template <typename Parsed = std::vector<bool>>
void array_parse_should_fail(const char *not_array) {
  const auto codec = default_codec<Parsed>();
  auto ctx = decode_context(not_array, not_array + strlen(not_array));
  BOOST_CHECK_THROW(codec.decode(ctx), decode_exception);
}

}  // namespace

/*
 * Constructing
 */

BOOST_AUTO_TEST_CASE(json_codec_array_should_construct_with_helper) {
  array<std::vector<bool>>(boolean());
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_construct_vector_with_default_codec) {
  default_codec<std::vector<bool>>();
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_construct_array_with_default_codec) {
  default_codec<std::array<bool, 3>>();
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_construct_deque_with_default_codec) {
  default_codec<std::deque<bool>>();
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_construct_set_with_default_codec) {
  default_codec<std::set<bool>>();
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_construct_unordered_set_with_default_codec) {
  default_codec<std::unordered_set<bool>>();
}

/*
 * Vector Decoding
 */

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_empty_vector) {
  BOOST_CHECK(array_parse("[]").empty());
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_single_element_vector) {
  BOOST_CHECK(array_parse("[true]") == std::vector<bool>({ true }));
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_two_elements_vector) {
  BOOST_CHECK(array_parse("[true,false]") == std::vector<bool>({ true, false }));
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_encoded_value_elements_vector) {
  auto decoded = array_parse<std::vector<encoded_value>>("[true,false]");
  std::vector<encoded_value> expected =
      { encoded_value("true"), encoded_value("false") };
  BOOST_CHECK(decoded == expected);
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_not_decode_otherwise_vector) {
  array_parse_should_fail("");
  array_parse_should_fail("[");
  array_parse_should_fail("[[");
  array_parse_should_fail("[false");
  array_parse_should_fail("[false,true,]");
  array_parse_should_fail("[false,true,");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_accept_inner_codec_vector) {
  const auto inner_codec(boolean());
  const auto array_codec(array<std::vector<bool>>(inner_codec));
  BOOST_CHECK(decode(array_codec, "[]").empty());
}

/*
 * Array Decoding
 */

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_empty_array) {
  const auto res = array_parse<std::array<int, 0>>("[]");
  BOOST_CHECK(res.empty());
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_single_element_array) {
  const auto res = array_parse<std::array<bool, 1>>("[true]");
  const auto expected = std::array<bool, 1>{{ true }};
  BOOST_CHECK(res == expected);
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_two_elements_array) {
  const auto res = array_parse<std::array<bool, 2>>("[true,false]");
  const auto expected = std::array<bool, 2>{{ true, false }};
  BOOST_CHECK(res == expected);
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_not_decode_otherwise_array) {
  array_parse_should_fail<std::array<bool, 1>>("[]");
  array_parse_should_fail<std::array<bool, 0>>("[true]");

  array_parse_should_fail<std::array<bool, 0>>("");
  array_parse_should_fail<std::array<bool, 1>>("");
  array_parse_should_fail<std::array<bool, 0>>("[");
  array_parse_should_fail<std::array<bool, 1>>("[");
  array_parse_should_fail<std::array<bool, 0>>("[[");
  array_parse_should_fail<std::array<bool, 1>>("[[");
  array_parse_should_fail<std::array<bool, 0>>("[false");
  array_parse_should_fail<std::array<bool, 1>>("[false");
  array_parse_should_fail<std::array<bool, 0>>("[false,true,]");
  array_parse_should_fail<std::array<bool, 1>>("[false,true,]");
  array_parse_should_fail<std::array<bool, 0>>("[false,true,");
  array_parse_should_fail<std::array<bool, 1>>("[false,true,");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_accept_inner_codec_array) {
  const auto inner_codec(boolean());
  const auto array_codec(array<std::vector<bool>>(inner_codec));
  BOOST_CHECK(decode(array_codec, "[]").empty());
}

/*
 * Vector Encoding
 */

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_empty_vector) {
  const std::vector<bool> vec;
  BOOST_CHECK_EQUAL(encode(vec), "[]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_single_element_vector) {
  const std::vector<bool> vec = { true };
  BOOST_CHECK_EQUAL(encode(vec), "[true]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_two_elements_vector) {
  const std::vector<bool> vec = { false, true };
  BOOST_CHECK_EQUAL(encode(vec), "[false,true]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_encoded_value_elements_vector) {
  const std::vector<encoded_value> vec = {
      encoded_value("false"), encoded_value("true") };
  BOOST_CHECK_EQUAL(encode(vec), "[false,true]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_not_encode_omitted_elements_vector) {
  const std::vector<bool> vec = { false, true };
  const auto codec = array<std::vector<bool>>(omit<bool>());
  BOOST_CHECK_EQUAL(encode(codec, vec), "[]");
}

/*
 * Array Encoding
 */

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_empty_array) {
  const std::array<int, 0> arr = {};
  BOOST_CHECK_EQUAL(encode(arr), "[]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_single_element_array) {
  const std::array<int, 1> arr{{ 7 }};
  BOOST_CHECK_EQUAL(encode(arr), "[7]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_encode_two_elements_array) {
  const std::array<int, 2> arr{{ 4, 9 }};
  BOOST_CHECK_EQUAL(encode(arr), "[4,9]");
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_not_encode_omitted_elements_array) {
  const std::array<bool, 2> arr{{ false, true }};
  const auto codec = array<std::array<bool, 2>>(omit<bool>());
  BOOST_CHECK_EQUAL(encode(codec, arr), "[]");
}

/*
 * Set Decoding
 */

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_empty_set) {
  BOOST_CHECK(array_parse<std::set<bool>>("[]").empty());
}

BOOST_AUTO_TEST_CASE(json_codec_array_should_decode_empty_unordered_set) {
  BOOST_CHECK(array_parse<std::unordered_set<bool>>("[]").empty());
}

BOOST_AUTO_TEST_SUITE_END()  // codec
BOOST_AUTO_TEST_SUITE_END()  // json
BOOST_AUTO_TEST_SUITE_END()  // spotify

max_stars_repo_name: ivangalkin/spotify-json

max_issues_repo_name: ivangalkin/spotify-json

max_forks_repo_name: ivangalkin/spotify-json


text:
#include "scheme/nest/pmap/UnitMap.hh"
#include "scheme/nest/pmap/ScaleMap.hh"
#include "scheme/nest/NEST.hh"
#include <gtest/gtest.h>
#include <boost/assign/std/vector.hpp> // for 'operator+=()'
#include <random>
#include <boost/foreach.hpp>

namespace scheme {
namespace nest {
namespace pmap {

using std::cout;
using std::endl;

TEST(ParamMap,UnitMap_get_neighboring_cells){
	{
		typedef UnitMap<2> MapType;
		MapType umap(1);
		std::vector<size_t> cnb;
		std::back_insert_iterator<std::vector<size_t> > biter(cnb);

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(1.5,0.5), 0, 0.4, biter );
		EXPECT_EQ( cnb.size(), 0 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(-0.5,0.5), 0, 0.4, biter );
		EXPECT_EQ( cnb.size(), 0 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(-0.39,0.5), 0, 0.4, biter );
		EXPECT_EQ( cnb.size(), 1 );
		EXPECT_EQ( cnb[0], 0 );

		// cout << "size: "<< cnb.size() << endl;
		// BOOST_FOREACH(size_t i,cnb) cout << "val " << i << std::endl;

	}
	{
		typedef UnitMap<2> MapType;
		MapType umap(100);
		std::vector<size_t> cnb;
		std::back_insert_iterator<std::vector<size_t> > biter(cnb);

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(1.5,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 1 );
		ASSERT_EQ( cnb[0], 1 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(10.5,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 1 );
		ASSERT_EQ( cnb[0], 10 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(10.3,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 2 );
		ASSERT_EQ( cnb[0],  9 );
		ASSERT_EQ( cnb[1], 10 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(0.3,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 1 );
		ASSERT_EQ( cnb[0],  0 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(0.3,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 1 );
		ASSERT_EQ( cnb[0],  0 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(101.0,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 0 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(100.3,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 1 );
		ASSERT_EQ( cnb[0],  99 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(-0.5,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 0 );

		cnb.clear();
		umap.get_neighboring_cells( MapType::ValueType(-0.3,0.5), 0, 0.4, biter );
		ASSERT_EQ( cnb.size(), 1 );
		ASSERT_EQ( cnb[0], 0 );
	}
}

TEST(ScaleMap,ScaleMap_cellindices){
	util::SimpleArray<1,size_t> bs(3); ScaleMap<1> m1(bs);
	for(size_t i = 0; i < 3; ++i) ASSERT_EQ( i, m1.indices_to_cellindex(m1.cellindex_to_indices(i)) );
	ScaleMap<2> m2(util::SimpleArray<2,size_t>(3,4));
	for(size_t i = 0; i < 3*4; ++i) ASSERT_EQ( i, m2.indices_to_cellindex(m2.cellindex_to_indices(i)) );
	ScaleMap<3> m3(util::SimpleArray<3,size_t>(3,4,8));
	for(size_t i = 0; i < 3*4*8; ++i) ASSERT_EQ( i, m3.indices_to_cellindex(m3.cellindex_to_indices(i)) );
	ScaleMap<4> m4(util::SimpleArray<4,size_t>(3,4,8,17));
	for(size_t i = 0; i < 3*4*8*17; ++i) ASSERT_EQ( i, m4.indices_to_cellindex(m4.cellindex_to_indices(i)) );
}

TEST(ScaleMap,ScaleMap_get_neighboring_cells_244){
	typedef ScaleMap<2> MapType;
	MapType umap(
		MapType::Params(0,0),
		MapType::Params(4,4),
		MapType::Indices(4,4)
	);
	std::vector<size_t> cnb;
	std::back_insert_iterator<std::vector<size_t> > biter(cnb);
	int i;

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.5,0.5), 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.5,0.5), 0, 0.6, biter );
	ASSERT_EQ( cnb.size(), 6 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );
	ASSERT_EQ( cnb[i++], 2 );
	ASSERT_EQ( cnb[i++], 4 );
	ASSERT_EQ( cnb[i++], 5 );
	ASSERT_EQ( cnb[i++], 6 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.5,1.5), 0, 0.6, biter );
	ASSERT_EQ( cnb.size(), 9 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );
	ASSERT_EQ( cnb[i++], 2 );
	ASSERT_EQ( cnb[i++], 4 );
	ASSERT_EQ( cnb[i++], 5 );
	ASSERT_EQ( cnb[i++], 6 );
	ASSERT_EQ( cnb[i++], 8 );
	ASSERT_EQ( cnb[i++], 9 );
	ASSERT_EQ( cnb[i++], 10 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(4.5,4.5), 0, 0.6, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 15 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(2.5,1.5), 0, 0.2, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 6 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(2.1,1.5), 0, 0.2, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 5 );
	ASSERT_EQ( cnb[i++], 6 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(2.1,1.9), 0, 0.2, biter );
	ASSERT_EQ( cnb.size(), 4 );
	ASSERT_EQ( cnb[i++], 5 );
	ASSERT_EQ( cnb[i++], 6 );
	ASSERT_EQ( cnb[i++], 9 );
	ASSERT_EQ( cnb[i++], 10 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(4.4,4.4), 0, 0.3, biter );
	ASSERT_EQ( cnb.size(), 0 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(4.4,4.2), 0, 0.3, biter );
	ASSERT_EQ( cnb.size(), 0 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(4.2,4.4), 0, 0.3, biter );
	ASSERT_EQ( cnb.size(), 0 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(4.2,4.2), 0, 0.3, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 15 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(4.2,3.2), 0, 0.3, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 11 );
	ASSERT_EQ( cnb[i++], 15 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(3.2,4.2), 0, 0.3, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 14 );
	ASSERT_EQ( cnb[i++], 15 );

}

TEST(ScaleMap,ScaleMap_get_neighboring_cells_433){
	typedef ScaleMap<4> MapType;
	MapType umap(
		MapType::Params(0,0,0,0),
		MapType::Params(3,3,3,3),
		MapType::Indices(3,3,3,3)
	);
	std::vector<size_t> cnb;
	std::back_insert_iterator<std::vector<size_t> > biter(cnb);
	int i;

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.5,0.5,0.5,0.5), 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.5,0.5,0.5), 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,0.5), 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,1.3), 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 4 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );
	ASSERT_EQ( cnb[i++], 27 );
	ASSERT_EQ( cnb[i++], 28 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(2.3,1.8,2.1,1.8), 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 16 );
	ASSERT_EQ( cnb[i++], 40 );
	ASSERT_EQ( cnb[i++], 41 );
	ASSERT_EQ( cnb[i++], 43  );
	ASSERT_EQ( cnb[i++], 44  );
	ASSERT_EQ( cnb[i++], 49 );
	ASSERT_EQ( cnb[i++], 50 );
	ASSERT_EQ( cnb[i++], 52  );
	ASSERT_EQ( cnb[i++], 53  );
	ASSERT_EQ( cnb[i++], 67 );
	ASSERT_EQ( cnb[i++], 68 );
	ASSERT_EQ( cnb[i++], 70  );
	ASSERT_EQ( cnb[i++], 71  );
	ASSERT_EQ( cnb[i++], 76 );
	ASSERT_EQ( cnb[i++], 77 );
	ASSERT_EQ( cnb[i++], 79  );
	ASSERT_EQ( cnb[i++], 80  );

	// cout << "size: "<< cnb.size() << endl;
	// BOOST_FOREACH(size_t i,cnb) cout << "val " << i << " : " << umap.cellindex_to_indices(i).transpose() << std::endl;
}

TEST(ScaleMap,ScaleMap_get_neighboring_cells_433_m1){
	typedef ScaleMap<4> MapType;
	MapType umap(
		MapType::Params(0,0,0,0)-1.0,
		MapType::Params(3,3,3,3)-1.0,
		MapType::Indices(3,3,3,3)
	);
	std::vector<size_t> cnb;
	std::back_insert_iterator<std::vector<size_t> > biter(cnb);
	int i;

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.5,0.5,0.5,0.5)-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.5,0.5,0.5)-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,0.5)-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,1.3)-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 4 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );
	ASSERT_EQ( cnb[i++], 27 );
	ASSERT_EQ( cnb[i++], 28 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(2.3,1.8,2.1,1.8)-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 16 );
	ASSERT_EQ( cnb[i++], 40 );
	ASSERT_EQ( cnb[i++], 41 );
	ASSERT_EQ( cnb[i++], 43  );
	ASSERT_EQ( cnb[i++], 44  );
	ASSERT_EQ( cnb[i++], 49 );
	ASSERT_EQ( cnb[i++], 50 );
	ASSERT_EQ( cnb[i++], 52  );
	ASSERT_EQ( cnb[i++], 53  );
	ASSERT_EQ( cnb[i++], 67 );
	ASSERT_EQ( cnb[i++], 68 );
	ASSERT_EQ( cnb[i++], 70  );
	ASSERT_EQ( cnb[i++], 71  );
	ASSERT_EQ( cnb[i++], 76 );
	ASSERT_EQ( cnb[i++], 77 );
	ASSERT_EQ( cnb[i++], 79  );
	ASSERT_EQ( cnb[i++], 80  );

	// cout << "size: "<< cnb.size() << endl;
	// BOOST_FOREACH(size_t i,cnb) cout << "val " << i << " : " << umap.cellindex_to_indices(i).transpose() << std::endl;
}

TEST(ScaleMap,ScaleMap_get_neighboring_cells_433_o2){
	typedef ScaleMap<4> MapType;
	MapType umap(
		MapType::Params(0,0,0,0)/2.0,
		MapType::Params(3,3,3,3)/2.0,
		MapType::Indices(3,3,3,3)
	);
	std::vector<size_t> cnb;
	std::back_insert_iterator<std::vector<size_t> > biter(cnb);
	int i;

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.5,0.5,0.5,0.5)/2.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.5,0.5,0.5)/2.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,0.5)/2.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,1.3)/2.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 4 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );
	ASSERT_EQ( cnb[i++], 27 );
	ASSERT_EQ( cnb[i++], 28 );

	cnb.clear(); i = 0;
	umap.get_neighboring_cells( MapType::ValueType(2.3,1.8,2.1,1.8)/2.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 16 );
	ASSERT_EQ( cnb[i++], 40 );
	ASSERT_EQ( cnb[i++], 41 );
	ASSERT_EQ( cnb[i++], 43  );
	ASSERT_EQ( cnb[i++], 44  );
	ASSERT_EQ( cnb[i++], 49 );
	ASSERT_EQ( cnb[i++], 50 );
	ASSERT_EQ( cnb[i++], 52  );
	ASSERT_EQ( cnb[i++], 53  );
	ASSERT_EQ( cnb[i++], 67 );
	ASSERT_EQ( cnb[i++], 68 );
	ASSERT_EQ( cnb[i++], 70  );
	ASSERT_EQ( cnb[i++], 71  );
	ASSERT_EQ( cnb[i++], 76 );
	ASSERT_EQ( cnb[i++], 77 );
	ASSERT_EQ( cnb[i++], 79  );
	ASSERT_EQ( cnb[i++], 80  );

	// cout << "size: "<< cnb.size() << endl;
	// BOOST_FOREACH(size_t i,cnb) cout << "val " << i << " : " << umap.cellindex_to_indices(i).transpose() << std::endl;
}

TEST(ScaleMap,ScaleMap_get_neighboring_cells_433_o5m1){
	typedef ScaleMap<4> MapType;
	MapType smap(
		MapType::Params(0,0,0,0)/5.0-1.0,
		MapType::Params(3,3,3,3)/5.0-1.0,
		MapType::Indices(3,3,3,3)
	);
	std::vector<size_t> cnb;
	std::back_insert_iterator<std::vector<size_t> > biter(cnb);
	int i;

	cnb.clear(); i = 0;
	smap.get_neighboring_cells( MapType::ValueType(1.5,0.5,0.5,0.5)/5.0-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 1 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	smap.get_neighboring_cells( MapType::ValueType(1.3,0.5,0.5,0.5)/5.0-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	smap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,0.5)/5.0-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 2 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );

	cnb.clear(); i = 0;
	smap.get_neighboring_cells( MapType::ValueType(1.3,0.1,0.1,1.3)/5.0-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 4 );
	ASSERT_EQ( cnb[i++], 0 );
	ASSERT_EQ( cnb[i++], 1 );
	ASSERT_EQ( cnb[i++], 27 );
	ASSERT_EQ( cnb[i++], 28 );

	cnb.clear(); i = 0;
	smap.get_neighboring_cells( MapType::ValueType(2.3,1.8,2.1,1.8)/5.0-1.0, 0, 0.4, biter );
	ASSERT_EQ( cnb.size(), 16 );
	ASSERT_EQ( cnb[i++], 40 );
	ASSERT_EQ( cnb[i++], 41 );
	ASSERT_EQ( cnb[i++], 43  );
	ASSERT_EQ( cnb[i++], 44  );
	ASSERT_EQ( cnb[i++], 49 );
	ASSERT_EQ( cnb[i++], 50 );
	ASSERT_EQ( cnb[i++], 52  );
	ASSERT_EQ( cnb[i++], 53  );
	ASSERT_EQ( cnb[i++], 67 );
	ASSERT_EQ( cnb[i++], 68 );
	ASSERT_EQ( cnb[i++], 70  );
	ASSERT_EQ( cnb[i++], 71  );
	ASSERT_EQ( cnb[i++], 76 );
	ASSERT_EQ( cnb[i++], 77 );
	ASSERT_EQ( cnb[i++], 79  );
	ASSERT_EQ( cnb[i++], 80  );

	// cout << "size: "<< cnb.size() << endl;
	// BOOST_FOREACH(size_t i,cnb) cout << "val " << i << " : " << smap.cellindex_to_indices(i).transpose() << std::endl;
}

}
}
}

ext: cc

max_stars_repo_name: YaoYinYing/rifdock

max_issues_repo_name: YaoYinYing/rifdock

max_forks_repo_name: YaoYinYing/rifdock


text:
/*

Copyright (c) 2015, Project OSRM contributors
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.

*/

#ifndef DESCRIPTION_FACTORY_HPP
#define DESCRIPTION_FACTORY_HPP

#include "../algorithms/douglas_peucker.hpp"
#include "../data_structures/phantom_node.hpp"
#include "../data_structures/segment_information.hpp"
#include "../data_structures/turn_instructions.hpp"

#include <boost/assert.hpp>

#include <osrm/coordinate.hpp>
#include <osrm/json_container.hpp>

#include <cmath>

#include <limits>
#include <vector>

struct PathData;
/* This class is fed with all way segments in consecutive order
 *  and produces the description plus the encoded polyline */

class DescriptionFactory
{
    DouglasPeucker polyline_generalizer;
    PhantomNode start_phantom, target_phantom;

    double DegreeToRadian(const double degree) const;
    double RadianToDegree(const double degree) const;

    std::vector<unsigned> via_indices;

    double entire_length;

  public:
    struct RouteSummary
    {
        unsigned distance;
        EdgeWeight duration;
        unsigned source_name_id;
        unsigned target_name_id;
        RouteSummary() : distance(0), duration(0), source_name_id(0), target_name_id(0) {}

        void BuildDurationAndLengthStrings(const double raw_distance, const unsigned raw_duration)
        {
            // compute distance/duration for route summary
            distance = static_cast<unsigned>(std::round(raw_distance));
            duration = static_cast<EdgeWeight>(std::round(raw_duration / 10.));
        }
    } summary;

    // I know, declaring this public is considered bad. I'm lazy
    std::vector<SegmentInformation> path_description;
    DescriptionFactory();
    void AppendSegment(const FixedPointCoordinate &coordinate, const PathData &data);
    void BuildRouteSummary(const double distance, const unsigned time);
    void SetStartSegment(const PhantomNode &start_phantom, const bool traversed_in_reverse);
    void SetEndSegment(const PhantomNode &start_phantom,
                       const bool traversed_in_reverse,
                       const bool is_via_location = false);
    osrm::json::Value AppendGeometryString(const bool return_encoded);
    std::vector<unsigned> const &GetViaIndices() const;

    double get_entire_length() const { return entire_length; }

    void Run(const unsigned zoom_level);
};

#endif /* DESCRIPTION_FACTORY_HPP */

ext: hpp

max_stars_repo_name: smartyw/organicmaps

max_issues_repo_name: smartyw/organicmaps

max_forks_repo_name: smartyw/organicmaps


text:
// Boost.Polygon library voronoi_graphic_utils.hpp header file

//          Copyright Andrii Sydorchuk 2010-2012.
// 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 for updates, documentation, and revision history.

#ifndef BOOST_POLYGON_VORONOI_VISUAL_UTILS
#define BOOST_POLYGON_VORONOI_VISUAL_UTILS

#include <stack>
#include <vector>

#include <boost/polygon/isotropy.hpp>
#include <boost/polygon/point_concept.hpp>
#include <boost/polygon/segment_concept.hpp>
#include <boost/polygon/rectangle_concept.hpp>

namespace boost {
namespace polygon {
// Utilities class, that contains set of routines handful for visualization.
template <typename CT>
class voronoi_visual_utils {
 public:
  // Discretize parabolic Voronoi edge.
  // Parabolic Voronoi edges are always formed by one point and one segment
  // from the initial input set.
  //
  // Args:
  //   point: input point.
  //   segment: input segment.
  //   max_dist: maximum discretization distance.
  //   discretization: point discretization of the given Voronoi edge.
  //
  // Template arguments:
  //   InCT: coordinate type of the input geometries (usually integer).
  //   Point: point type, should model point concept.
  //   Segment: segment type, should model segment concept.
  //
  // Important:
  //   discretization should contain both edge endpoints initially.
  template <class InCT1, class InCT2,
            template<class> class Point,
            template<class> class Segment>
  static
  typename enable_if<
    typename gtl_and<
      typename gtl_if<
        typename is_point_concept<
          typename geometry_concept< Point<InCT1> >::type
        >::type
      >::type,
      typename gtl_if<
        typename is_segment_concept<
          typename geometry_concept< Segment<InCT2> >::type
        >::type
      >::type
    >::type,
    void
  >::type discretize(
      const Point<InCT1>& point,
      const Segment<InCT2>& segment,
      const CT max_dist,
      std::vector< Point<CT> >* discretization) {
    // Apply the linear transformation to move start point of the segment to
    // the point with coordinates (0, 0) and the direction of the segment to
    // coincide the positive direction of the x-axis.
    CT segm_vec_x = cast(x(high(segment))) - cast(x(low(segment)));
    CT segm_vec_y = cast(y(high(segment))) - cast(y(low(segment)));
    CT sqr_segment_length = segm_vec_x * segm_vec_x + segm_vec_y * segm_vec_y;

    // Compute x-coordinates of the endpoints of the edge
    // in the transformed space.
    CT projection_start = sqr_segment_length *
        get_point_projection((*discretization)[0], segment);
    CT projection_end = sqr_segment_length *
        get_point_projection((*discretization)[1], segment);

    // Compute parabola parameters in the transformed space.
    // Parabola has next representation:
    // f(x) = ((x-rot_x)^2 + rot_y^2) / (2.0*rot_y).
    CT point_vec_x = cast(x(point)) - cast(x(low(segment)));
    CT point_vec_y = cast(y(point)) - cast(y(low(segment)));
    CT rot_x = segm_vec_x * point_vec_x + segm_vec_y * point_vec_y;
    CT rot_y = segm_vec_x * point_vec_y - segm_vec_y * point_vec_x;

    // Save the last point.
    Point<CT> last_point = (*discretization)[1];
    discretization->pop_back();

    // Use stack to avoid recursion.
    std::stack<CT> point_stack;
    point_stack.push(projection_end);
    CT cur_x = projection_start;
    CT cur_y = parabola_y(cur_x, rot_x, rot_y);

    // Adjust max_dist parameter in the transformed space.
    const CT max_dist_transformed = max_dist * max_dist * sqr_segment_length;
    while (!point_stack.empty()) {
      CT new_x = point_stack.top();
      CT new_y = parabola_y(new_x, rot_x, rot_y);

      // Compute coordinates of the point of the parabola that is
      // furthest from the current line segment.
      CT mid_x = (new_y - cur_y) / (new_x - cur_x) * rot_y + rot_x;
      CT mid_y = parabola_y(mid_x, rot_x, rot_y);

      // Compute maximum distance between the given parabolic arc
      // and line segment that discretize it.
      CT dist = (new_y - cur_y) * (mid_x - cur_x) -
          (new_x - cur_x) * (mid_y - cur_y);
      dist = dist * dist / ((new_y - cur_y) * (new_y - cur_y) +
          (new_x - cur_x) * (new_x - cur_x));
      if (dist <= max_dist_transformed) {
        // Distance between parabola and line segment is less than max_dist.
        point_stack.pop();
        CT inter_x = (segm_vec_x * new_x - segm_vec_y * new_y) /
            sqr_segment_length + cast(x(low(segment)));
        CT inter_y = (segm_vec_x * new_y + segm_vec_y * new_x) /
            sqr_segment_length + cast(y(low(segment)));
        discretization->push_back(Point<CT>(inter_x, inter_y));
        cur_x = new_x;
        cur_y = new_y;
      } else {
        point_stack.push(mid_x);
      }
    }

    // Update last point.
    discretization->back() = last_point;
  }

 private:
  // Compute y(x) = ((x - a) * (x - a) + b * b) / (2 * b).
  static CT parabola_y(CT x, CT a, CT b) {
    return ((x - a) * (x - a) + b * b) / (b + b);
  }

  // Get normalized length of the distance between:
  //   1) point projection onto the segment
  //   2) start point of the segment
  // Return this length divided by the segment length. This is made to avoid
  // sqrt computation during transformation from the initial space to the
  // transformed one and vice versa. The assumption is made that projection of
  // the point lies between the start-point and endpoint of the segment.
  template <class InCT,
            template<class> class Point,
            template<class> class Segment>
  static
  typename enable_if<
    typename gtl_and<
      typename gtl_if<
        typename is_point_concept<
          typename geometry_concept< Point<int> >::type
        >::type
      >::type,
      typename gtl_if<
        typename is_segment_concept<
          typename geometry_concept< Segment<long> >::type
        >::type
      >::type
    >::type,
    CT
  >::type get_point_projection(
      const Point<CT>& point, const Segment<InCT>& segment) {
    CT segment_vec_x = cast(x(high(segment))) - cast(x(low(segment)));
    CT segment_vec_y = cast(y(high(segment))) - cast(y(low(segment)));
    CT point_vec_x = x(point) - cast(x(low(segment)));
    CT point_vec_y = y(point) - cast(y(low(segment)));
    CT sqr_segment_length =
        segment_vec_x * segment_vec_x + segment_vec_y * segment_vec_y;
    CT vec_dot = segment_vec_x * point_vec_x + segment_vec_y * point_vec_y;
    return vec_dot / sqr_segment_length;
  }

  template <typename InCT>
  static CT cast(const InCT& value) {
    return static_cast<CT>(value);
  }
};
}
}

#endif  // BOOST_POLYGON_VORONOI_VISUAL_UTILS


text:
/*******************************************************************************
 Author: Bogdan Nicolae
 Copyright (C) 2013 IBM Corp.

 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.
*******************************************************************************/

#ifndef __COW_ALLOCATOR
#define __COW_ALLOCATOR

#include <cstdlib>
#include <boost/thread/mutex.hpp>

//#define __DEBUG
#include "common/debug.hpp"

struct no_reclaim_allocator {
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    static char *region;
    static size_t current_size, max_size;
    static boost::mutex alloc_lock;

    static void init(size_type max_size);
    static void destroy();
    static char *malloc(const size_type size);
    static void free(char *const addr);
};

struct simple_sweep_allocator {
    typedef std::size_t size_type;
    typedef std::ptrdiff_t difference_type;

    static char *region, *alloc_bitmap;
    static size_t max_size, page_size;
    static boost::mutex alloc_lock;

    static void init(size_type page_size, size_type extra_mem);
    static void destroy();
    static char *malloc(const size_type size);
    static void free(char *const addr);
    static size_t get_page_size();
};

#endif

max_stars_repo_name: bnicolae/ac-fte

max_issues_repo_name: bnicolae/ac-fte

max_forks_repo_name: bnicolae/ac-fte


text:
#ifndef BLUB_ASYNC_UPDATER_HPP
#define BLUB_ASYNC_UPDATER_HPP

#include "blub/core/globals.hpp"
#include "blub/core/signal.hpp"
#include "blub/async/dispatcher.hpp"

#include <boost/chrono/system_clocks.hpp>

namespace blub
{
namespace async
{

    class updater : public dispatcher
    {
    public:
        updater(const blub::string& threadName);
        virtual ~updater();

        void stop();

        typedef blub::signal<void (real)> t_sigFrameListener;
        t_sigFrameListener* signalFrame();

        void run(const real &frames = 60.0, const bool &threaded = false); // change from frames to millis-wait

    protected:
        bool runOneFrame(const real& delta);
        void frame();

    private:
        const blub::string m_threadName;

        t_sigFrameListener m_sigFrame;

        boost::thread *m_thread;
        deadlineTimer *m_frameDeadline;

        boost::chrono::system_clock::time_point m_start;

        real m_frames;
        bool m_stop;
    };

}
}

#endif // BLUB_ASYNC_UPDATER_HPP


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

#ifndef __pinocchio_multibody_data_hxx__
#define __pinocchio_multibody_data_hxx__

#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/multibody/model.hpp"
#include "pinocchio/utils/string-generator.hpp"
#include "pinocchio/multibody/liegroup/liegroup-algo.hpp"

#include <boost/bind.hpp>
#include <boost/utility.hpp>

/// @cond DEV

namespace pinocchio
{

  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  inline DataTpl<Scalar,Options,JointCollectionTpl>::
  DataTpl(const Model & model)
  : joints(0)
  , a((std::size_t)model.njoints,Motion::Zero())
  , oa((std::size_t)model.njoints,Motion::Zero())
  , a_gf((std::size_t)model.njoints,Motion::Zero())
  , oa_gf((std::size_t)model.njoints,Motion::Zero())
  , v((std::size_t)model.njoints,Motion::Zero())
  , ov((std::size_t)model.njoints,Motion::Zero())
  , f((std::size_t)model.njoints,Force::Zero())
  , of((std::size_t)model.njoints,Force::Zero())
  , h((std::size_t)model.njoints,Force::Zero())
  , oh((std::size_t)model.njoints,Force::Zero())
  , oMi((std::size_t)model.njoints,SE3::Identity())
  , liMi((std::size_t)model.njoints,SE3::Identity())
  , tau(VectorXs::Zero(model.nv))
  , nle(VectorXs::Zero(model.nv))
  , g(VectorXs::Zero(model.nv))
  , oMf((std::size_t)model.nframes,SE3::Identity())
  , Ycrb((std::size_t)model.njoints,Inertia::Zero())
  , dYcrb((std::size_t)model.njoints,Inertia::Zero())
  , M(MatrixXs::Zero(model.nv,model.nv))
  , Minv(MatrixXs::Zero(model.nv,model.nv))
  , C(MatrixXs::Zero(model.nv,model.nv))
  , dHdq(Matrix6x::Zero(6,model.nv))
  , dFdq(Matrix6x::Zero(6,model.nv))
  , dFdv(Matrix6x::Zero(6,model.nv))
  , dFda(Matrix6x::Zero(6,model.nv))
  , SDinv(Matrix6x::Zero(6,model.nv))
  , UDinv(Matrix6x::Zero(6,model.nv))
  , IS(MatrixXs::Zero(6,model.nv))
  , vxI((std::size_t)model.njoints,Inertia::Matrix6::Zero())
  , Ivx((std::size_t)model.njoints,Inertia::Matrix6::Zero())
  , oYcrb((std::size_t)model.njoints,Inertia::Zero())
  , doYcrb((std::size_t)model.njoints,Inertia::Matrix6::Zero())
  , ddq(VectorXs::Zero(model.nv))
  , Yaba((std::size_t)model.njoints,Inertia::Matrix6::Zero())
  , u(VectorXs::Zero(model.nv))
  , Ag(Matrix6x::Zero(6,model.nv))
  , dAg(Matrix6x::Zero(6,model.nv))
  , hg(Force::Zero())
  , dhg(Force::Zero())
  , Ig(Inertia::Zero())
  , Fcrb((std::size_t)model.njoints,Matrix6x::Zero(6,model.nv))
  , lastChild((std::size_t)model.njoints,-1)
  , nvSubtree((std::size_t)model.njoints,-1)
  , start_idx_v_fromRow((std::size_t)model.nv,-1)
  , end_idx_v_fromRow((std::size_t)model.nv,-1)
  , U(MatrixXs::Identity(model.nv,model.nv))
  , D(VectorXs::Zero(model.nv))
  , Dinv(VectorXs::Zero(model.nv))
  , tmp(VectorXs::Zero(model.nv))
  , parents_fromRow((std::size_t)model.nv,-1)
  , supports_fromRow((std::size_t)model.nv)
  , nvSubtree_fromRow((std::size_t)model.nv,-1)
  , J(Matrix6x::Zero(6,model.nv))
  , dJ(Matrix6x::Zero(6,model.nv))
  , dVdq(Matrix6x::Zero(6,model.nv))
  , dAdq(Matrix6x::Zero(6,model.nv))
  , dAdv(Matrix6x::Zero(6,model.nv))
  , dtau_dq(MatrixXs::Zero(model.nv,model.nv))
  , dtau_dv(MatrixXs::Zero(model.nv,model.nv))
  , ddq_dq(MatrixXs::Zero(model.nv,model.nv))
  , ddq_dv(MatrixXs::Zero(model.nv,model.nv))
  , iMf((std::size_t)model.njoints,SE3::Identity())
  , com((std::size_t)model.njoints,Vector3::Zero())
  , vcom((std::size_t)model.njoints,Vector3::Zero())
  , acom((std::size_t)model.njoints,Vector3::Zero())
  , mass((std::size_t)model.njoints,(Scalar)(-1))
  , Jcom(Matrix3x::Zero(3,model.nv))
  , kinetic_energy((Scalar)-1)
  , potential_energy((Scalar)-1)
  , JMinvJt()
  , llt_JMinvJt()
  , lambda_c()
  , sDUiJt(MatrixXs::Zero(model.nv,model.nv))
  , torque_residual(VectorXs::Zero(model.nv))
  , dq_after(VectorXs::Zero(model.nv))
  , impulse_c()
  , staticRegressor(Matrix3x::Zero(3,4*(model.njoints-1)))
  , bodyRegressor(BodyRegressorType::Zero())
  , jointTorqueRegressor(MatrixXs::Zero(model.nv,10*(model.njoints-1)))
#if EIGEN_VERSION_AT_LEAST(3,2,90) && !EIGEN_VERSION_AT_LEAST(3,2,93)
  , kinematic_hessians(6,std::max(1,model.nv),std::max(1,model.nv)) // the minimum size should be 1 for compatibility reasons
#else
  , kinematic_hessians(6,model.nv,model.nv)
#endif
  {
    typedef typename Model::JointIndex JointIndex;

    /* Create data structure associated to the joints */
    for(JointIndex i=0;i<(JointIndex)(model.njoints);++i)
      joints.push_back(CreateJointData<Scalar,Options,JointCollectionTpl>::run(model.joints[i]));

    /* Init for CRBA */
    M.setZero(); Minv.setZero();
    for(JointIndex i=0;i<(JointIndex)(model.njoints);++i)
    { Fcrb[i].resize(6,model.nv); }

    computeLastChild(model);

    /* Init for Coriolis */

    /* Init for Cholesky */
    computeParents_fromRow(model);
    computeSupports_fromRow(model);

    /* Init universe states relatively to itself */
    a_gf[0] = -model.gravity;

    kinematic_hessians.setZero();
  }

  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  inline void DataTpl<Scalar,Options,JointCollectionTpl>::
  computeLastChild(const Model & model)
  {
    typedef typename Model::Index Index;

    std::fill(lastChild.begin(),lastChild.end(),-1);
    for( int i=model.njoints-1;i>=0;--i )
    {
      if(lastChild[(Index)i] == -1) lastChild[(Index)i] = i;
      const Index & parent = model.parents[(Index)i];
      lastChild[parent] = std::max(lastChild[(Index)i],lastChild[parent]);

      nvSubtree[(Index)i]
      = idx_v(model.joints[(Index)lastChild[(Index)i]]) + nv(model.joints[(Index)lastChild[(Index)i]])
      - idx_v(model.joints[(Index)i]);
    }
  }

  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  inline void DataTpl<Scalar,Options,JointCollectionTpl>
  ::computeParents_fromRow(const Model & model)
  {
    typedef typename Model::Index Index;

    for(Index joint=1;joint<(Index)(model.njoints);joint++)
    {
      const Index & parent = model.parents[joint];
      const int nvj    = nv   (model.joints[joint]);
      const int idx_vj = idx_v(model.joints[joint]);

      assert(idx_vj >= 0 && idx_vj < model.nv);

      if(parent>0) parents_fromRow[(size_t)idx_vj] = idx_v(model.joints[parent])+nv(model.joints[parent])-1;
      else         parents_fromRow[(size_t)idx_vj] = -1;
      nvSubtree_fromRow[(size_t)idx_vj] = nvSubtree[joint];

      start_idx_v_fromRow[(size_t)idx_vj] = idx_vj;
      end_idx_v_fromRow[(size_t)idx_vj] = idx_vj+nvj-1;
      for(int row=1;row<nvj;++row)
      {
        parents_fromRow[(size_t)(idx_vj+row)] = idx_vj+row-1;
        nvSubtree_fromRow[(size_t)(idx_vj+row)] = nvSubtree[joint]-row;
        start_idx_v_fromRow[(size_t)(idx_vj+row)] = start_idx_v_fromRow[(size_t)idx_vj];
        end_idx_v_fromRow[(size_t)(idx_vj+row)] = end_idx_v_fromRow[(size_t)idx_vj];
      }
    }
  }

  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  inline void DataTpl<Scalar,Options,JointCollectionTpl>
  ::computeSupports_fromRow(const Model & model)
  {
    typedef typename Model::JointIndex JointIndex;

    for(JointIndex joint_id = 1;
        joint_id < (JointIndex)(model.njoints);
        joint_id++)
    {
      const int nvj    = nv   (model.joints[joint_id]);
      const int idx_vj = idx_v(model.joints[joint_id]);

      assert(idx_vj >= 0 && idx_vj < model.nv);

      const int parent_fromRow = parents_fromRow[(size_t)idx_vj];

      if(parent_fromRow >= 0)
        supports_fromRow[(size_t)idx_vj] = supports_fromRow[(size_t)parent_fromRow];

      supports_fromRow[(size_t)idx_vj].push_back(idx_vj);

      for(int row = 1; row < nvj; ++row)
      {
        supports_fromRow[(size_t)(idx_vj+row)] = supports_fromRow[(size_t)(idx_vj+row-1)];
        supports_fromRow[(size_t)(idx_vj+row)].push_back(idx_vj+row);
      }
    }
  }

  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  bool operator==(const DataTpl<Scalar,Options,JointCollectionTpl> & data1,
                  const DataTpl<Scalar,Options,JointCollectionTpl> & data2)
  {
    bool value =
       data1.joints == data2.joints
    && data1.a == data2.a
    && data1.oa == data2.oa
    && data1.a_gf == data2.a_gf
    && data1.oa_gf == data2.oa_gf
    && data1.v == data2.v
    && data1.ov == data2.ov
    && data1.f == data2.f
    && data1.of == data2.of
    && data1.h == data2.h
    && data1.oh == data2.oh
    && data1.oMi == data2.oMi
    && data1.liMi == data2.liMi
    && data1.tau == data2.tau
    && data1.nle == data2.nle
    && data1.g == data2.g
    && data1.oMf == data2.oMf
    && data1.Ycrb == data2.Ycrb
    && data1.dYcrb == data2.dYcrb
    && data1.M == data2.M
    && data1.Minv == data2.Minv
    && data1.C == data2.C
    && data1.dHdq == data2.dHdq
    && data1.dFdq == data2.dFdq
    && data1.dFdv == data2.dFdv
    && data1.dFda == data2.dFda
    && data1.SDinv == data2.SDinv
    && data1.UDinv == data2.UDinv
    && data1.IS == data2.IS
    && data1.vxI == data2.vxI
    && data1.Ivx == data2.Ivx
    && data1.oYcrb == data2.oYcrb
    && data1.doYcrb == data2.doYcrb
    && data1.ddq == data2.ddq
    && data1.Yaba == data2.Yaba
    && data1.u == data2.u
    && data1.Ag == data2.Ag
    && data1.dAg == data2.dAg
    && data1.hg == data2.hg
    && data1.dhg == data2.dhg
    && data1.Ig == data2.Ig
    && data1.Fcrb == data2.Fcrb
    && data1.lastChild == data2.lastChild
    && data1.nvSubtree == data2.nvSubtree
    && data1.start_idx_v_fromRow == data2.start_idx_v_fromRow
    && data1.end_idx_v_fromRow == data2.end_idx_v_fromRow
    && data1.U == data2.U
    && data1.D == data2.D
    && data1.Dinv == data2.Dinv
    && data1.parents_fromRow == data2.parents_fromRow
    && data1.supports_fromRow == data2.supports_fromRow
    && data1.nvSubtree_fromRow == data2.nvSubtree_fromRow
    && data1.J == data2.J
    && data1.dJ == data2.dJ
    && data1.dVdq == data2.dVdq
    && data1.dAdq == data2.dAdq
    && data1.dAdv == data2.dAdv
    && data1.dtau_dq == data2.dtau_dq
    && data1.dtau_dv == data2.dtau_dv
    && data1.ddq_dq == data2.ddq_dq
    && data1.ddq_dv == data2.ddq_dv
    && data1.iMf == data2.iMf
    && data1.com == data2.com
    && data1.vcom == data2.vcom
    && data1.acom == data2.acom
    && data1.mass == data2.mass
    && data1.Jcom == data2.Jcom
    && data1.kinetic_energy == data2.kinetic_energy
    && data1.potential_energy == data2.potential_energy
    && data1.JMinvJt == data2.JMinvJt
    && data1.lambda_c == data2.lambda_c
    && data1.torque_residual == data2.torque_residual
    && data1.dq_after == data2.dq_after
    && data1.impulse_c == data2.impulse_c
    && data1.staticRegressor == data2.staticRegressor
    && data1.bodyRegressor == data2.bodyRegressor
    && data1.jointTorqueRegressor == data2.jointTorqueRegressor
    ;

    // operator== for Eigen::Tensor provides an Expression which might be not evaluated as a boolean
    typedef DataTpl<Scalar,Options,JointCollectionTpl> Data;
    typedef Eigen::Map<const typename Data::VectorXs> MapVectorXs;
    value &=
       MapVectorXs(data1.kinematic_hessians.data(),data1.kinematic_hessians.size())
    == MapVectorXs(data2.kinematic_hessians.data(),data2.kinematic_hessians.size());

    return value;
  }

  template<typename Scalar, int Options, template<typename,int> class JointCollectionTpl>
  bool operator!=(const DataTpl<Scalar,Options,JointCollectionTpl> & data1,
                  const DataTpl<Scalar,Options,JointCollectionTpl> & data2)
  {
    return !(data1 == data2);
  }

} // namespace pinocchio

/// @endcond

#endif // ifndef __pinocchio_multibody_data_hxx__

ext: hxx

max_stars_repo_name: ikalevatykh/pinocchio

max_issues_repo_name: ikalevatykh/pinocchio

max_forks_repo_name: ikalevatykh/pinocchio


text:
/*
 * interface.cc
 *
 *  Copyright (C) 2013 Diamond Light Source
 *
 *  Author: James Parkhurst
 *
 *  This code is distributed under the BSD license, a copy of which is
 *  included in the root directory of this package.
 */
#include <boost/python.hpp>
#include <boost/python/def.hpp>
#include <dials/algorithms/integration/processor.h>
#include <dials/algorithms/integration/integrator.h>
#include <dials/algorithms/integration/manager.h>

using namespace boost::python;

namespace dials { namespace algorithms { namespace boost_python {

  /**
   * Split the reflection table where the blocks are given.
   */
  inline void job_list_split(const JobList &self, af::reflection_table data) {
    // Check the input
    DIALS_ASSERT(data.is_consistent());
    DIALS_ASSERT(data.contains("bbox"));
    DIALS_ASSERT(data.contains("id"));
    DIALS_ASSERT(self.size() > 0);
    DIALS_ASSERT(data.size() > 0);

    // Get the bounding boxes
    af::const_ref<int6> bbox = data["bbox"];
    af::const_ref<int> id = data["id"];

    // Check all the reflections are in range
    for (std::size_t i = 0; i < bbox.size(); ++i) {
      DIALS_ASSERT(id[i] >= 0);
      DIALS_ASSERT(bbox[i][1] > bbox[i][0]);
      DIALS_ASSERT(bbox[i][3] > bbox[i][2]);
      DIALS_ASSERT(bbox[i][5] > bbox[i][4]);
    }

    // Create the lookup
    JobRangeLookup lookup(self);

    // Split the reflections
    af::shared<int6> bbox_new;
    af::shared<std::size_t> indices;
    for (std::size_t i = 0; i < bbox.size(); ++i) {
      int z0 = bbox[i][4];
      int z1 = bbox[i][5];
      std::size_t eid = id[i];
      std::size_t j0 = lookup.first(eid, z0);
      std::size_t j1 = lookup.last(eid, z1 - 1);
      DIALS_ASSERT(j0 < self.size());
      DIALS_ASSERT(j1 < self.size());
      DIALS_ASSERT(j1 >= j0);
      DIALS_ASSERT(z0 >= self[j0].frames()[0]);
      DIALS_ASSERT(z1 <= self[j1].frames()[1]);
      bool inside = false;
      for (std::size_t j = j0; j <= j1; ++j) {
        int jz0 = self[j].frames()[0];
        int jz1 = self[j].frames()[1];
        if (z0 >= jz0 && z1 <= jz1) {
          inside = true;
          break;
        }
      }
      if (inside) {
        bbox_new.push_back(bbox[i]);
        indices.push_back(i);
      } else {
        int6 b = bbox[i];
        std::vector<int> divisions;
        for (std::size_t j = j0; j <= j1; ++j) {
          divisions.push_back(self[j].frames()[0]);
          divisions.push_back(self[j].frames()[1]);
        }
        std::size_t k = 1;
        for (std::size_t j = 1; j < divisions.size(); ++j) {
          if (divisions[j] > divisions[j - 1]) {
            divisions[k] = divisions[j];
            k++;
          } else if (divisions[j] == divisions[j - 1]) {
            continue;
          } else {
            int a = divisions[j];
            int b = divisions[j - 1];
            int c = (a + b) / 2;
            DIALS_ASSERT(c >= a);
            DIALS_ASSERT(c < b);
            divisions[k] = c;
          }
        }
        divisions.resize(k);
        divisions[0] = b[4];
        k = 1;
        for (std::size_t j = 1; j < divisions.size(); ++j) {
          if (divisions[j] >= b[5]) {
            break;
          } else if (divisions[j] > divisions[j - 1]) {
            k++;
          } else {
            continue;
          }
        }
        divisions[k++] = b[5];
        divisions.resize(k);
        for (std::size_t j = 1; j < divisions.size(); ++j) {
          DIALS_ASSERT(divisions[j] > divisions[j - 1]);
        }
        for (std::size_t j = 1; j < divisions.size(); ++j) {
          b[5] = divisions[j];
          DIALS_ASSERT(b[5] > b[4]);
          bbox_new.push_back(b);
          indices.push_back(i);
          b[4] = b[5];
        }
      }
    }

    // Resize the reflection table
    DIALS_ASSERT(bbox_new.size() == indices.size());
    data.resize(bbox_new.size());

    // Reorder the reflections
    af::boost_python::flex_table_suite::reorder(data, indices.const_ref());

    // Set the new bounding boxes
    af::boost_python::flex_table_suite::setitem_column(
      data, "bbox", bbox_new.const_ref());
    af::boost_python::flex_table_suite::setitem_column(
      data, "partial_id", indices.const_ref());
  }

  /**
   * Compute the memory for each job
   */
  af::shared<std::size_t> job_list_shoebox_memory(const JobList &self,
                                                  af::reflection_table data,
                                                  bool flatten) {
    // Check the input
    DIALS_ASSERT(data.is_consistent());
    DIALS_ASSERT(data.contains("bbox"));
    DIALS_ASSERT(data.contains("id"));
    DIALS_ASSERT(data.contains("flags"));
    DIALS_ASSERT(self.size() > 0);
    DIALS_ASSERT(data.size() > 0);

    // Get the bounding boxes
    af::const_ref<int6> bbox = data["bbox"];
    af::const_ref<int> id = data["id"];
    af::const_ref<std::size_t> flags = data["flags"];

    // Check all the reflections are in range
    for (std::size_t i = 0; i < bbox.size(); ++i) {
      DIALS_ASSERT(id[i] >= 0);
      DIALS_ASSERT(bbox[i][1] > bbox[i][0]);
      DIALS_ASSERT(bbox[i][3] > bbox[i][2]);
      DIALS_ASSERT(bbox[i][5] > bbox[i][4]);
    }

    // Create the lookup
    ReflectionLookup lookup(id, flags, bbox, self);

    // Compute the memory for each job
    af::shared<std::size_t> result(lookup.size());
    for (std::size_t i = 0; i < result.size(); ++i) {
      int frame0 = lookup.job(i).frames()[0];
      int frame1 = lookup.job(i).frames()[1];
      DIALS_ASSERT(frame1 > frame0);
      af::const_ref<std::size_t> indices = lookup.indices(i);
      af::shared<std::size_t> memory_to_alloc(frame1 - frame0, 0);
      af::shared<std::size_t> memory_to_free(frame1 - frame0, 0);
      for (std::size_t j = 0; j < indices.size(); ++j) {
        DIALS_ASSERT(indices[j] < bbox.size());
        int6 b = bbox[indices[j]];
        DIALS_ASSERT(b[4] >= frame0);
        DIALS_ASSERT(b[5] <= frame1);
        DIALS_ASSERT(b[5] > b[4]);
        DIALS_ASSERT(b[3] > b[2]);
        DIALS_ASSERT(b[1] > b[0]);
        std::size_t xsize = b[1] - b[0];
        std::size_t ysize = b[3] - b[2];
        std::size_t zsize = b[5] - b[4];
        std::size_t size = xsize * ysize;
        if (!flatten) {
          size *= zsize;
        }
        std::size_t nbytes = size
                             * (sizeof(Shoebox<>::float_type)
                                + sizeof(Shoebox<>::float_type) + sizeof(int));
        memory_to_alloc[b[4] - frame0] += nbytes;
        memory_to_free[b[5] - frame0 - 1] += nbytes;
      }
      std::size_t max_memory_usage = 0;
      std::size_t cur_memory_usage = 0;
      for (int frame = frame0; frame < frame1; ++frame) {
        std::size_t j = frame - frame0;
        cur_memory_usage += memory_to_alloc[j];
        DIALS_ASSERT(memory_to_free[j] <= cur_memory_usage);
        max_memory_usage = std::max(max_memory_usage, cur_memory_usage);
        cur_memory_usage -= memory_to_free[j];
      }
      DIALS_ASSERT(cur_memory_usage == 0);
      result[i] = max_memory_usage;
    }

    // Return the result
    return result;
  }

  /**
   * Wrapper class to allow python function to inherit
   */
  struct ExecutorWrapper : Executor, wrapper<Executor> {
    void process(int frame, af::reflection_table data) {
      this->get_override("process")(frame, data);
    }
  };

  BOOST_PYTHON_MODULE(dials_algorithms_integration_integrator_ext) {
    class_<GroupList::Group>("Group", no_init)
      .def("index", &GroupList::Group::index)
      .def("nindex", &GroupList::Group::nindex)
      .def("expr", &GroupList::Group::expr)
      .def("nexpr", &GroupList::Group::nexpr)
      .def("frames", &GroupList::Group::frames)
      .def("nframes", &GroupList::Group::nframes);

    class_<GroupList>("GroupList")
      .def("__len__", &GroupList::size)
      .def("__getitem__", &GroupList::operator[], return_internal_reference<>());

    class_<JobList::Job>("Job", no_init)
      .def("index", &JobList::Job::index)
      .def("expr", &JobList::Job::expr)
      .def("nexpr", &JobList::Job::nexpr)
      .def("frames", &JobList::Job::frames)
      .def("nframes", &JobList::Job::nframes);

    class_<JobList>("JobList")
      .def(init<tiny<int, 2>, const af::const_ref<tiny<int, 2> > &>())
      .def("add", &JobList::add)
      .def("__len__", &JobList::size)
      .def("__getitem__", &JobList::operator[], return_internal_reference<>())
      .def("split", &job_list_split)
      .def("shoebox_memory", &job_list_shoebox_memory);

    class_<ReflectionManager>("ReflectionManager", no_init)
      .def(init<const JobList &, af::reflection_table>((arg("jobs"), arg("data"))))
      .def("__len__", &ReflectionManager::size)
      .def("finished", &ReflectionManager::finished)
      .def("accumulate", &ReflectionManager::accumulate)
      .def("split", &ReflectionManager::split)
      .def("job", &ReflectionManager::job, return_internal_reference<>())
      .def("data", &ReflectionManager::data)
      .def("num_reflections", &ReflectionManager::num_reflections);

    class_<ReflectionManagerPerImage>("ReflectionManagerPerImage", no_init)
      .def(init<int2, af::reflection_table>((arg("frames"), arg("data"))))
      .def("__len__", &ReflectionManagerPerImage::size)
      .def("finished", &ReflectionManagerPerImage::finished)
      .def("accumulate", &ReflectionManagerPerImage::accumulate)
      .def("split", &ReflectionManagerPerImage::split)
      .def("frames", &ReflectionManagerPerImage::frames)
      .def("data", &ReflectionManagerPerImage::data)
      .def("num_reflections", &ReflectionManagerPerImage::num_reflections);

    class_<ExecutorWrapper, boost::noncopyable>("Executor")
      .def("process", pure_virtual(&Executor::process))
      .enable_pickling();

    class_<ShoeboxProcessor>("ShoeboxProcessor", no_init)
      .def(init<af::reflection_table, std::size_t, int, int, bool>())
      .def("next", &ShoeboxProcessor::next<double>)
      .def("next", &ShoeboxProcessor::next<int>)
      .def("frame0", &ShoeboxProcessor::frame0)
      .def("frame1", &ShoeboxProcessor::frame1)
      .def("frame", &ShoeboxProcessor::frame)
      .def("nframes", &ShoeboxProcessor::nframes)
      .def("npanels", &ShoeboxProcessor::npanels)
      .def("finished", &ShoeboxProcessor::finished)
      .def("extract_time", &ShoeboxProcessor::extract_time)
      .def("process_time", &ShoeboxProcessor::process_time);
  }

}}}  // namespace dials::algorithms::boost_python

max_stars_repo_name: TiankunZhou/dials

max_issues_repo_name: TiankunZhou/dials

max_forks_repo_name: TiankunZhou/dials


text:
#ifndef __MASTERPROXY
#define __MASTERPROXY

#include <boost/thread/mutex.hpp>
#include "bdproxy.hpp"
#include <string>
#include <netdb.h>  //address structs
#include <string.h> //memset
#include <unistd.h> //close

#include <boost/function.hpp>
// class NBDProxy:public BDProxy<boost::function<void (Request&, NBDProxy&)> >,private boost::noncopyable
namespace ilrd
{
//slaveproxy must change to bdproxy
class MasterProxy:public BDProxyFunction,private boost::noncopyable
{
public:
    MasterProxy(u_int64_t size, std::string port);
    ~MasterProxy();

    void OnSocketReady();
    void Done(struct Request &req);

    int GetFd();

private:
    int m_socket;
    struct sockaddr_in m_clientaddr; /* client addr */
    addrinfo *m_res;
};
//master proxy act as a udp server and located on each one of the slaves

// struct MasterRWReq:public Request
// {
//     MasterRWReq(struct Request, char* data = 0);
//     ~MasterRWReq();
//     int m_size;
//     int m_offset;
//     char m_handle[8];
//     char* m_data;
// };

MasterProxy::MasterProxy(u_int64_t size, std::string port):BDProxyFunction(size)
{
    struct addrinfo hints;
    memset(&hints, 0, sizeof hints);
    hints.ai_family = AF_UNSPEC;        //use IPv4 or IPv6, whichever
    hints.ai_socktype = SOCK_DGRAM;     //udp stream socket
    hints.ai_flags = AI_PASSIVE;        //fill in my IP for me

    getaddrinfo(NULL, port.c_str(), &hints, &m_res);
    m_socket = socket(m_res->ai_family, m_res->ai_socktype, m_res->ai_protocol);
    bind(m_socket, m_res->ai_addr, m_res->ai_addrlen);
}

MasterProxy::~MasterProxy()
{
    freeaddrinfo(m_res);
    close(m_socket);
}

int MasterProxy::GetFd()
{
    return m_socket;
}

//reads data from slave
void MasterProxy::OnSocketReady()
{
    //read from socket on slave to request
    //push the request to thread pool
    //the slave handler will take care of this type of task
    // the handler write to file and calls done
    //read from socket to a NBDRWReq(with changed type!)
    //push the request to thread pool -> (changes the type to network read/write)
    //the network handler will take care of this type of task
    std::cout << "on socket ready" << '\n';
    struct NBDRWReq request;
    read_all(m_socket, (char*)&request, sizeof(NBDRWReq));
  // read(m_socket_fd[0], &request, sizeof(nbd_request));

    if(ntohl(request.type) == NBD_CMD_WRITE)
    {
      //ex:nbd asked to read-> buffer was filled on the slave side->
      // request returns with filled buffer

      // slave must change the type since the handler is gonna be different
      // type = factory key
      // NBD_CMD_READ_R = filled buffer
      // NBD_CMD_WRITE_R = the data was written on

      char *temp = new char[ntohl(request.len)];
      read_all(m_socket, temp, ntohl(request.len));
      request.m_data = temp;
    }

    std::cout << "nbd_proxy: calling m_cb(my_nbd_request, *this)" << '\n';
    (m_cb)(*request, *this);

}

//after data was sent
void MasterProxy::Done(struct Request &req)
{
    //writes the reply socket
}

}//namespaceilrd

#endif

max_stars_repo_name: zrora/DistributedNAS

max_issues_repo_name: zrora/DistributedNAS

max_forks_repo_name: zrora/DistributedNAS


text:
/** mldb_plugin_test.cc
    Jeremy Barnes, 13 December 2014
    Copyright (c) 2014 Datacratic Inc.  All rights reserved.

    This file is part of MLDB. Copyright 2015 Datacratic. All rights reserved.
*/

#include "mldb/plugins/html/css.h"

#define BOOST_TEST_MAIN
#define BOOST_TEST_DYN_LINK

#include <boost/test/unit_test.hpp>

using namespace std;

using namespace MLDB;

BOOST_AUTO_TEST_CASE( test_css_selector_parsing )
{
    using namespace Css;
    BOOST_CHECK_EQUAL(Selector::parse("")->toString(), "*");
    BOOST_CHECK_EQUAL(Selector::parse("*")->toString(), "*");
    BOOST_CHECK_EQUAL(Selector::parse("h1")->toString(), "h1");
    BOOST_CHECK_EQUAL(Selector::parse("h1 a")->toString(), "h1 a");

    auto sel2 = Selector::parse("h1 h2");
    auto sel3 = Selector::parse("h1>h2");

    auto p1 = Path::parse("h1 h2");
    auto p2 = Path::parse("h1");
    auto p3 = Path::parse("h1 h1");
    auto p4 = Path::parse("h2 h1");
    auto p5 = Path::parse("");
    auto p6 = Path::parse("h1 h2 h3");

    auto sel = Selector::parse("h1");
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h2")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h2 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("")), false);

    sel = Selector::parse("h1 h2");
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h2")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h3 h1 h2")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h2 h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("")), false);

    sel = Selector::parse("h1 *");
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h2")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h3 h1 h2")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h2 h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h3 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("")), false);

    sel = Selector::parse("h1>*");
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h2")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h3 h1 h2")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h2 h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h1 h1")), true);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("h1 h3 h1")), false);
    BOOST_CHECK_EQUAL(sel->match(Path::parse("")), false);
}

max_stars_repo_name: kstepanmpmg/mldb

max_issues_repo_name: tomzhang/mldb

max_forks_repo_name: matebestek/mldb


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

#include <boost/outbuf.hpp>
#include <boost/outbuf/streambuf.hpp>
#include <boost/outbuf/string.hpp>
#include "char_array_streambuf.hpp"
#include <chrono>
#include <iostream>
#include <iomanip>
#include <string>
#include <vector>

struct element_123
{
    std::string field_a;
    std::string field_b;
    std::string field_c;
};

struct element_abc
{
    std::string field_1;
    std::string field_2;
    std::vector<element_123> field_3;
};

void to_json(boost::outbuf& dest, const element_abc& data)
{
    write(dest, "{\n  \"field_1\" : \"");
    write(dest, data.field_1.data(), data.field_1.size());
    write(dest, "\",\n  \"field_2\" : \"");
    write(dest, data.field_2.data(), data.field_2.size());
    write(dest, "\",\n  \"field_3\" : [\n");
    for (auto it = data.field_3.begin(); it != data.field_3.end(); ++it) {
        const auto& elm = *it;
        write(dest, "    {\n      \"field_a\" : \"");
        write(dest, elm.field_a.data(), elm.field_a.size());
        write(dest, "\",\n      \"field_b\" : \"");
        write(dest, elm.field_b.data(), elm.field_b.size());
        write(dest, "\",\n      \"field_c\" : \"");
        write(dest, elm.field_c.data(), elm.field_c.size());
        if (it + 1 == data.field_3.end()) {
            write(dest, "\"\n    }\n");
        } else {
            write(dest, "\"\n    },\n");
        }
    }
    write(dest, "  ]\n}\n");
}

inline void write(std::streambuf& dest, const char* str)
{
    dest.sputn(str, strlen(str));
}

inline void write(std::streambuf& dest, const char* str, std::size_t len)
{
    dest.sputn(str, len);
}

void to_json(std::streambuf& dest, const element_abc& data)
{
    write(dest, "{\n  \"field_1\" : \"");
    write(dest, data.field_1.data(), data.field_1.size());
    write(dest, "\",\n  \"field_2\" : \"");
    write(dest, data.field_2.data(), data.field_2.size());
    write(dest, "\",\n  \"field_3\" : [\n");
    for (auto it = data.field_3.begin(); it != data.field_3.end(); ++it) {
        const auto& elm = *it;
        write(dest, "    {\n      \"field_a\" : \"");
        write(dest, elm.field_a.data(), elm.field_a.size());
        write(dest, "\",\n      \"field_b\" : \"");
        write(dest, elm.field_b.data(), elm.field_b.size());
        write(dest, "\",\n      \"field_c\" : \"");
        write(dest, elm.field_c.data(), elm.field_c.size());
        if (it + 1 == data.field_3.end()) {
            write(dest, "\"\n    }\n");
        } else {
            write(dest, "\"\n    },\n");
        }
    }
    write(dest, "  ]\n}\n");

}

element_abc create_sample_data()
{
    element_abc data;
    data.field_1 = "blah blah blah";
    data.field_2 = "bleh bleh bleh";
    for (int i = 0; i < 5; ++i)
    {
        char buff[40];
        element_123 e;
        sprintf(buff, "qwert %d", i);
        e.field_a = buff;
        sprintf(buff, "asdfg %d", i);
        e.field_b = buff;
        sprintf(buff, "zxcvb %d", i);
        e.field_c = buff;

        data.field_3.push_back(e);
    }

    return data;
}

int main()
{
    auto data = create_sample_data();
    constexpr std::size_t buff_size = 1000;
    char buff[buff_size];
    char* const buff_end = buff + buff_size;

    constexpr long long loop_size = 20000000;

#if 1

    {
        auto t1 = std::chrono::steady_clock::now();
        for (long long i = 0; i < loop_size; ++i)
        {
            boost::cstr_writer writer(buff);
            to_json(writer, data);
            writer.finish();
        }
        auto t2 = std::chrono::steady_clock::now();

        std::chrono::steady_clock::duration  dt = (t2 - t1);
        std::cout << dt.count() << " , " << std::flush;
    }

#else

    {
        auto t1 = std::chrono::steady_clock::now();
        for (long long i = 0; i < loop_size; ++i)
        {
            char_array_streambuf writer(buff, buff_size);
            to_json(writer, data);
        }
        auto t2 = std::chrono::steady_clock::now();

        std::chrono::steady_clock::duration  dt = (t2 - t1);
        std::cout << dt.count() << " , " << std::flush;
    }

#endif

    return 0;
}


text:
/*
 * Copyright (c) 2019 Jonas Deyson
 *
 * This software is released under the MIT License.
 *
 * You should have received a copy of the MIT License
 * along with this program. If not, see <https://opensource.org/licenses/MIT>
 */

#include "fbksd/client/BenchmarkClient.h"
#include <boost/python.hpp>
#include <boost/python/numpy.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>
#include <boost/make_shared.hpp>
#include <memory>
using namespace fbksd;
namespace bp = boost::python;
namespace np = bp::numpy;

bool SceneInfo_has(const SceneInfo& info, const std::string& key)
{
    return info.has<int64_t>(key) || info.has<float>(key) || info.has<bool>(key) || info.has<std::string>(key);
}

bp::object SceneInfo_get(const SceneInfo& info, const std::string& key)
{
    if(info.has<int64_t>(key))
        return bp::long_(info.get<int64_t>(key));
    if(info.has<float>(key))
        return bp::make_tuple(info.get<float>(key));
    if(info.has<bool>(key))
        return bp::make_tuple(info.get<bool>(key));
    if(info.has<std::string>(key))
        return bp::make_tuple(info.get<std::string>(key));
    throw std::runtime_error("key \"" + key + "\" does not exist");
}

std::shared_ptr<BenchmarkClient> BenchmarkClient_ctor()
{
    bp::object sys = bp::object(bp::handle<>(PyImport_ImportModule("sys")));
    bp::list list = bp::extract<bp::list>(sys.attr("argv"));
      // Convert Python argv into C-style argc/argv.
    int argc = bp::extract<int>(list.attr("__len__")());
    char** argv = new char*[argc];
    for (int arg = 0; arg < argc; ++arg)
        argv[arg] = strdup(bp::extract<const char*>(list[arg]));

    return std::make_shared<BenchmarkClient>(argc, argv);
}

void BenchmarkClient_evaluateSamples(BenchmarkClient& self, int spp, bp::object consumer)
{
    self.evaluateSamples(SPP(spp), [&](const BufferTile& tile) {
        auto data = *tile.begin();
        auto array = np::from_data(data, np::dtype::get_builtin<float>(),
                                   bp::make_tuple(tile.height(), tile.width(), tile.getSPP(), tile.getSampleSize()),
                                   bp::make_tuple(sizeof(float)*tile.width()*tile.getSPP()*tile.getSampleSize(),
                                                  sizeof(float)*tile.getSPP()*tile.getSampleSize(),
                                                  sizeof(float)*tile.getSampleSize(),
                                                  sizeof(float)),
                                   bp::object());
        consumer(array, bp::make_tuple(tile.beginX(), tile.beginY()));
    });
}

void BenchmarkClient_setSampleLayout(BenchmarkClient& self, bp::list list, float roughness = 0.1f)
{
    SampleLayout layout;
    auto len = bp::len(list);
    for(long i = 0; i < len; ++i)
    {
        auto str_extract = bp::extract<bp::str>(list[i]);
        if(str_extract.check())
            layout(bp::extract<std::string>(str_extract()));
        else
        {
            auto tuple_extract = bp::extract<bp::tuple>(list[i]);
            if(tuple_extract.check())
            {
                auto tup = tuple_extract();
                layout(bp::extract<std::string>(tup[0]))[bp::extract<int>(tup[1])];
            }
        }
    }
    layout.setRoughnessThreshold(roughness);
    self.setSampleLayout(layout);
}

np::ndarray BenchmarkClient_getResultBuffer(BenchmarkClient& self)
{
    auto data = self.getResultBuffer();
    auto info = self.getSceneInfo();
    auto w = info.get<int64_t>("width");
    auto h = info.get<int64_t>("height");
    return np::from_data(data, np::dtype::get_builtin<float>(),
                         bp::make_tuple(h, w, 3),
                         bp::make_tuple(sizeof(float)*w*3, sizeof(float)*3, sizeof(float)),
                         bp::object());
}

BOOST_PYTHON_MODULE(client)
{
    using namespace boost::python;
    Py_Initialize();
    np::initialize();

    bp::docstring_options doc;
    doc.disable_cpp_signatures();

    class_<SceneInfo>("SceneInfo",
                      "Contains information about the scene being rendered.\n\n"
                      "The list of available information can be found in the "
                      "`C++ API reference <https://fbksd.github.io/fbksd/docs/latest/classfbksd_1_1SceneInfo.html#details>`__.\n")
        .def("has", &SceneInfo_has, "Returns `True` if the given key exists.",
             args("key"))
        .def("get", &SceneInfo_get,
             "Returns the value for a given key. Throws an error if the key does not exists.",
             args("key"))
    ;

    class_<BenchmarkClient, boost::noncopyable>("BenchmarkClient",
        "The BenchmarkClient class is used to communicate with the benchmark server")
        .def("__init__", make_constructor(BenchmarkClient_ctor))
        .def("get_scene_info", &BenchmarkClient::getSceneInfo, args(""),
             ":return: Returns information about the scene being rendered.\n"
             ":rtype: :class:`~SceneInfo`.")
        .def("set_sample_layout", &BenchmarkClient_setSampleLayout, (arg("self"), arg("layout"), arg("roughness") = 0.1f),
             "Sets the sample layout.\n\n"
             "The layout is the way to inform the FBKSD server "
             "what data your technique requires for each sample, and how the data should "
             "be laid out in memory. "
             "Common data includes, for example, color RGB and (x,y) image plane position.\n\n"
             ":param list layout: List of sample components.\n"
             "    A component can be a string (Ex: ``'COLOR_R'``), or a pair with a string and a number indicating"
             "    the enumeration value (Ex: ``('NORMAL_X', 1)``, indication the x normal value for the second intersection point).\n"
             "    The list of available components can be found in the `C++ API reference <https://fbksd.github.io/fbksd/docs/latest/classfbksd_1_1SampleLayout.html#details>`__.\n"
             ":param float roughness: Beckmann roughness threshold used to decompose the diffuse sample radiance values.")
        .def("evaluate_samples", &BenchmarkClient_evaluateSamples, args("self", "spp", "consumer"),
             "Request samples.\n\n"
             "The samples are computed by the renderer and sent in tiles. For each tile, the consumer callback\n"
             "function is called so you can consume the samples.\n\n"
             ":param spp: number of samples per pixel to evaluate.\n"
             ":param consumer: Consumer callback function.\n"
             "    The callback should accept two parameters: ``tile`` and ``offset``.\n\n"
             "    The ``tile`` is a `numpy.ndarray <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray>`__ "
             "containing the tile data. It has 4 dimensions, in this order:\n"
             "    ``height``, ``width``, ``spp``, and ``sample_size``, where ``sample_size`` is the number of components\n"
             "    of the sample specified in the :func:`~set_sample_layout` method.\n\n"
             "    The ``offset`` is a tuple containing the :math:`(x, y)` pixel coordinates of the result image, corresponding to the"
             "    upper-left corner of the tile.\n\n"
             "    .. Note:: Your callback function should return as fast as possible."
             "       So, try to avoid raw loops when consuming the samples whenever possible.\n\n")
        .def("get_result_buffer", &BenchmarkClient_getResultBuffer, args("self"),
             "Returns a pointer to the buffer where the result image is stored.\n\n"
             "The user should write the final reconstructed image to this buffer before calling :func:`~send_result`.\n\n"
             ":return: A RGB image as a `numpy.ndarray <https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.html#numpy.ndarray>`__ "
             "with shape ``(height, width, 3)`` .\n")
        .def("send_result", &BenchmarkClient::sendResult, args("self"), "Sends the final result.")
    ;
}

max_stars_repo_name: fbksd/fbksd

max_issues_repo_name: fbksd/fbksd

max_forks_repo_name: fbksd/fbksd


text:
#ifndef TINY_DB_ENGINE_EXTMEM_DEVICE_HPP
#define TINY_DB_ENGINE_EXTMEM_DEVICE_HPP

#include "../basic/fs_error.hpp"
#include "../basic/dev.hpp"
#include "util.hpp"
#include <optional>
#include <valarray>
#include <string>
#include <memory>
#include <cmath>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/filesystem.hpp>
#include <cassert>
#include <list>

extern "C" {
typedef struct tagBuffer {
    unsigned long numIO; /* Number of IO's*/
    size_t bufSize; /* Buffer size*/
    size_t blkSize; /* Block size */
    size_t numAllBlk; /* Number of blocks that can be kept in the buffer */
    size_t numFreeBlk; /* Number of available blocks in the buffer */
    unsigned char *data; /* Starting address of the buffer */
    char* name;
} Buffer;

Buffer *initBuffer(const char* name,size_t bufSize, size_t blkSize, Buffer *buf);
void freeBuffer(Buffer *buf);
unsigned char *getNewBlockInBuffer(Buffer *buf);
void freeBlockInBuffer(unsigned char *blk, Buffer *buf);
int dropBlockOnDisk(unsigned int addr, Buffer *buf);
unsigned char *readBlockFromDisk(unsigned char* blkPtr, unsigned int addr, Buffer *buf);
int writeBlockToDisk(unsigned char *blkPtr, unsigned int addr, Buffer *buf);

}

namespace tinydb::extmem {
    using std::valarray;
    using std::slice;
    using std::byte;
    using std::optional;
    using std::string;
    using std::unique_ptr;
    using std::list;
    using tinydb::filesystem::util::sys_time_spec;
    using tinydb::filesystem::block_stream_device;
    using tinydb::filesystem::fs_error;
    using tinydb::filesystem::util::current_sys_time_spec;

    class extmem_device final : public block_stream_device {
    private:
        using extmem_cache_id_t = size_t;
        using extmem_block_id_t = size_t;
        struct extmem_device_index {
            extmem_block_id_t block_id;
            extmem_cache_id_t cache_id;
            sys_time_spec time;
        };
        using extmem_cache_index_t = typename boost::multi_index::multi_index_container<extmem_device_index,
                boost::multi_index::indexed_by<
                        boost::multi_index::hashed_non_unique<boost::multi_index::member<
                                extmem_device_index, extmem_block_id_t,
                                &extmem_device_index::block_id>>,
                        boost::multi_index::hashed_unique<boost::multi_index::member<extmem_device_index, extmem_cache_id_t,
                                &extmem_device_index::cache_id>>,
                        boost::multi_index::ordered_non_unique<boost::multi_index::member<extmem_device_index, sys_time_spec,
                                &extmem_device_index::time>>
                >>;
        Buffer *buf_;
        size_t block_num_;
        extmem_cache_index_t cache_index_;

        friend class extmem_device_manager;

        extmem_device(const size_t block_num, Buffer *buf) :
                buf_{buf}, block_num_{block_num},
                cache_index_{} {
            for (size_t i = 0; i < cache_num(); i++) {
                cache_index_.insert(extmem_device_index{0, i, current_sys_time_spec()});
            }
        }

        inline size_t cal_cache_offset(const size_t idx) const {
            return idx * cache_size();
        }

        inline void valarray_to_cache(const valarray<byte> &source, const slice &s, size_t target) {
            // assert(s.size() >= block_size());
            // skip flag byte
            target = target + sizeof(unsigned char);
            for (auto i = s.start(); i < s.size() * s.stride(); i += s.stride(), target += sizeof(unsigned char)) {
                buf_->data[target] = static_cast<unsigned char>(source[i]);
            }
        }

        inline void cache_to_valarray(valarray<byte> &target, const slice &s, size_t source) const {
            // assert(s.size() >= block_size());
            // skip flag byte
            source = source + sizeof(unsigned char);
            for (auto i = s.start(); i < s.size() * s.stride(); i += s.stride(), source += sizeof(unsigned char)) {
                target[i] = static_cast<byte>(buf_->data[source]);
            }
        }

    public:
        extmem_device(const extmem_device &rhs) = delete;

        extmem_device(extmem_device &&rhs) noexcept :
                buf_(rhs.buf_), block_num_{rhs.block_num_},
                cache_index_{std::move(rhs.cache_index_)} {
            rhs.block_num_ = 0;
            rhs.buf_ = nullptr;
            rhs.cache_index_ = {};
        }

        extmem_device &operator=(const extmem_device &rhs) = delete;

        extmem_device &operator=(extmem_device &&rhs) noexcept {
            std::swap(block_num_, rhs.block_num_);
            std::swap(buf_, rhs.buf_);
            std::swap(cache_index_, rhs.cache_index_);
            return *this;
        }

        inline size_t block_num() const {
            return block_num_;
        }

        inline size_t block_size() const override {
            return buf_->blkSize;
        }

        inline size_t cache_count() const {
			return cache_num() - buf_->numFreeBlk;
        }

        inline size_t cache_header_size() const {
            return 1;
        }

        inline size_t cache_size() const {
            return block_size() + cache_header_size();
        }

        inline size_t cache_num() const {
            return buf_->numAllBlk;
        }

        inline bool cache_empty() const {
			return cache_count() == 0;
        }

        inline bool cache_full() const {
            return cache_count() == cache_num();
        }

        ~extmem_device() override {
            if(buf_!= nullptr) {
                freeBuffer(buf_);
            }
        }

		bool read_at_b(const size_t block_id, valarray<byte>& buf, const slice& s) override;

		bool write_at_b(size_t block_id, const valarray<byte>& buf, const slice& s) override;
    };

    class extmem_device_manager {
    public:
		static optional<extmem_device> make(const string& name, const size_t block_num, const size_t block_size,
			const size_t buffer_size);
    };
}

#endif // TINY_DB_ENGINE_EXTMEM_DEVICE_HPP

max_stars_repo_name: lonelyhentai/workspace

max_issues_repo_name: lonelyhentai/workspace

max_forks_repo_name: lonelyhentai/workspace


text:
/*<-
Copyright (c) 2016 Barrett Adair

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

#include <boost/callable_traits/detail/config.hpp>
#ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS
int main(){ return 0; }
#else

//[ args
#include <type_traits>
#include <memory>
#include <boost/callable_traits.hpp>

namespace ct = boost::callable_traits;

template<typename T, typename Expect>
void test(){
    using args_t = ct::args_t<T>;
    static_assert(std::is_same<args_t, Expect>::value, "");
}

int main() {

    {
        auto lamda = [](int, float&, const char*){};
        using lam = decltype(lamda);
        using expect = std::tuple<int, float&, const char*>;

        test<lam, expect>();
    }

    {
        struct foo;
        using pmf = void(foo::*)(int, float&, const char*);
        using expect = std::tuple<foo&, int, float&, const char*>;

        test<pmf, expect>();
    }

    {
        using function_ptr = void(*)(int, float&, const char*);
        using expect = std::tuple<int, float&, const char*>;
        test<function_ptr, expect>();
    }

    {
        using function_ref = void(&)(int, float&, const char*);
        using expect = std::tuple<int, float&, const char*>;
        test<function_ref, expect>();
    }

    {
        using function = void(int, float&, const char*);
        using expect = std::tuple<int, float&, const char*>;
        test<function, expect>();
    }

    {
        using abominable = void(int, float&, const char*) const;
        using expect = std::tuple<int, float&, const char*>;
        test<abominable, expect>();
    }
}
//]
#endif //#ifdef BOOST_CLBL_TRTS_DISABLE_ABOMINABLE_FUNCTIONS