text:
//
//  AssimpParser.cpp
//  Kuplung
//
//  Created by Sergey Petrov on 1/2/16.
//  Copyright © 2016 supudo.net. All rights reserved.
//

#include "AssimpParser.hpp"
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>

AssimpParser::~AssimpParser() {
}

void AssimpParser::init(const std::function<void(float)>& doProgress) {
    this->funcProgress = doProgress;

    this->parserUtils = std::make_unique<ParserUtils>();
}

std::vector<MeshModel> AssimpParser::parse(const FBEntity& file, const std::vector<std::string>&) {
    this->file = file;
    this->models.clear();
    const aiScene* scene = this->parser.ReadFile(file.path, aiProcess_Triangulate | aiProcess_FlipUVs | aiProcess_CalcTangentSpace);
    if (!scene || scene->mFlags == AI_SCENE_FLAGS_INCOMPLETE || !scene->mRootNode) {
        Settings::Instance()->funcDoLog("[Assimp] Parse error : " + std::string(this->parser.GetErrorString()));
        return this->models;
    }

    this->indexModel = -1;
    this->indexFace = -1;
    this->indexMaterial = -1;
    this->indicesCounter = 0;
    this->meshCounter = 0;
    this->modelID = 1;
    this->faceID = 1;
    this->vectorsVertices = {};
    this->vectorsTextureCoordinates = {};
    this->vectorsTextureCoordinates = {};

    this->processNode(scene->mRootNode, scene);

    return this->models;
}

void AssimpParser::processNode(aiNode* node, const aiScene* scene) {
    for (GLuint i=0; i<node->mNumMeshes; i++) {
        aiMesh* mesh = scene->mMeshes[node->mMeshes[i]];
        std::string modelTitle = std::string(node->mName.C_Str());
        this->models.push_back(this->processMesh(mesh, scene, modelTitle));
        this->meshCounter += 1;
        this->funcProgress((float(this->meshCounter) / float(scene->mNumMeshes)) * 100.0f);
    }
    for (GLuint i=0; i<node->mNumChildren; i++) {
        this->processNode(node->mChildren[i], scene);
    }
}

MeshModel AssimpParser::processMesh(aiMesh* mesh, const aiScene* scene, const std::string& modelTitle) {
    MeshModel entityModel;
    entityModel.ID = this->indexModel;
    entityModel.File = this->file;
    entityModel.ModelTitle = modelTitle;
    entityModel.countVertices = 0;
    entityModel.countTextureCoordinates = 0;
    entityModel.countNormals = 0;
    entityModel.countIndices = 0;

    // Walk through each of the mesh's vertices
    for (GLuint i=0; i<mesh->mNumVertices; i++) {
        // vertices
        entityModel.vertices.push_back(glm::vec3(mesh->mVertices[i].x, mesh->mVertices[i].y, mesh->mVertices[i].z));
        entityModel.countVertices += 3;

        // Normals
        entityModel.normals.push_back(glm::vec3(mesh->mNormals[i].x, mesh->mNormals[i].y, mesh->mNormals[i].z));
        entityModel.countNormals += 3;

        // Texture coordinates
        if (mesh->mTextureCoords[0]) {
            entityModel.texture_coordinates.push_back(glm::vec2(mesh->mTextureCoords[0][i].x, mesh->mTextureCoords[0][i].y));
            entityModel.countTextureCoordinates += 2;
        }
    }

    // Indices
    for (GLuint i=0; i<mesh->mNumFaces; i++) {
        aiFace face = mesh->mFaces[i];
        for (GLuint j=0; j<face.mNumIndices; j++) {
            entityModel.indices.push_back(face.mIndices[j]);
            entityModel.countIndices += 1;
        }
    }

    // Materials
    if (mesh->mMaterialIndex > 0) {
        aiMaterial* material = scene->mMaterials[mesh->mMaterialIndex];

        aiString materialName;
        material->Get(AI_MATKEY_NAME, materialName);
        entityModel.MaterialTitle = std::string(materialName.C_Str());

        MeshModelMaterial entityMaterial = {};
        this->indexMaterial += 1;
        entityMaterial.MaterialID = this->indexMaterial;
        entityMaterial.MaterialTitle = std::string(materialName.C_Str());

        float shininess = 0.0f;
        material->Get(AI_MATKEY_SHININESS, shininess); // Ns
        entityMaterial.SpecularExp = shininess / 4.0f; // Assimp still multiples the exp 4 times ...

        material->Get(AI_MATKEY_REFRACTI, entityMaterial.OpticalDensity); // Ni
        material->Get(AI_MATKEY_OPACITY, entityMaterial.Transparency);
        material->Get(AI_MATKEY_SHADING_MODEL, entityMaterial.IlluminationMode);
        // Assimp ignores the "illum" in the obj file for some reason ...
        entityMaterial.IlluminationMode = 2;

        aiColor3D color;

        material->Get(AI_MATKEY_COLOR_AMBIENT, color);
        entityMaterial.AmbientColor = glm::vec3(color.r, color.g, color.b);

        material->Get(AI_MATKEY_COLOR_DIFFUSE, color);
        entityMaterial.DiffuseColor = glm::vec3(color.r, color.g, color.b);

        material->Get(AI_MATKEY_COLOR_SPECULAR, color);
        entityMaterial.SpecularColor = glm::vec3(color.r, color.g, color.b);

        material->Get(AI_MATKEY_COLOR_EMISSIVE, color);
        entityMaterial.EmissionColor = glm::vec3(color.r, color.g, color.b);

        // ambient
        std::vector<MeshMaterialTextureImage> ambientMaps = this->loadMaterialTextures(material, aiTextureType_AMBIENT);
        if (ambientMaps.size() > 0)
            entityMaterial.TextureAmbient = ambientMaps[0];

        // diffuse
        std::vector<MeshMaterialTextureImage> diffuseMaps = this->loadMaterialTextures(material, aiTextureType_DIFFUSE);
        if (diffuseMaps.size() > 0)
            entityMaterial.TextureDiffuse = diffuseMaps[0];

        // specular
        std::vector<MeshMaterialTextureImage> specularMaps = this->loadMaterialTextures(material, aiTextureType_SPECULAR);
        if (specularMaps.size() > 0)
            entityMaterial.TextureSpecular = specularMaps[0];

        // specular exp
        std::vector<MeshMaterialTextureImage> specularExpMaps = this->loadMaterialTextures(material, aiTextureType_SHININESS);
        if (specularExpMaps.size() > 0)
            entityMaterial.TextureSpecularExp = specularExpMaps[0];

        // dissolve
        std::vector<MeshMaterialTextureImage> dissolveMaps = this->loadMaterialTextures(material, aiTextureType_OPACITY);
        if (dissolveMaps.size() > 0)
            entityMaterial.TextureDissolve = dissolveMaps[0];

        // normal/bump
        std::vector<MeshMaterialTextureImage> normalMaps = this->loadMaterialTextures(material, aiTextureType_HEIGHT);
        if (normalMaps.size() > 0)
            entityMaterial.TextureBump = normalMaps[0];

        // displacement
        std::vector<MeshMaterialTextureImage> displacementMaps = this->loadMaterialTextures(material, aiTextureType_DISPLACEMENT);
        if (displacementMaps.size() > 0)
            entityMaterial.TextureDisplacement = displacementMaps[0];

        entityModel.ModelMaterial = entityMaterial;
    }
    else {
        MeshModelMaterial entityMaterial = {};
        entityMaterial.MaterialID = 1;
        entityMaterial.MaterialTitle.clear();
        entityMaterial.DiffuseColor = glm::vec3(0.7, 0.7, 0.7);
        entityMaterial.Transparency = 1.0f;
        entityMaterial.IlluminationMode = 2;
        entityModel.ModelMaterial = entityMaterial;
    }

    this->indexModel += 1;

    return entityModel;
}

std::vector<MeshMaterialTextureImage> AssimpParser::loadMaterialTextures(aiMaterial* mat, aiTextureType type) {
    std::vector<MeshMaterialTextureImage> textures;
    for (GLuint i = 0; i < mat->GetTextureCount(type); i++) {
        aiString str;
        mat->GetTexture(type, i, &str);
        GLboolean skip = false;
        for (GLuint j = 0; j < this->textures_loaded.size(); j++) {
            if (this->textures_loaded[j].Filename == std::string(str.C_Str())) {
                textures.push_back(this->textures_loaded[j]);
                skip = true;
                break;
            }
        }
        if (!skip) {
            MeshMaterialTextureImage texture = {};
            texture.Filename = std::string(str.C_Str());
            texture.Image = std::string(str.C_Str());

            std::string folderPath = this->file.path;
            boost::replace_all(folderPath, this->file.title, "");
            if (!boost::filesystem::exists(texture.Image) && !boost::filesystem::path(texture.Image).is_absolute())
                texture.Image = folderPath + texture.Image;

            texture.Height = 0;
            texture.Width = 0;
            texture.UseTexture = true;
            texture.Commands = {};
            textures.push_back(texture);
            this->textures_loaded.push_back(texture);  // Store it as texture loaded for entire model, to ensure we won't unnecesery load duplicate textures.
        }
    }
    return textures;
}

max_stars_repo_name: supudo/Kuplung

max_issues_repo_name: supudo/Kuplung

max_forks_repo_name: supudo/Kuplung


text:
// Boost.Geometry (aka GGL, Generic Geometry Library)
// Unit Test

// Copyright (c) 2011 Barend Gehrels, Amsterdam, the Netherlands.

// Use, modification and distribution is subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)

#ifndef GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_POLYGON_HPP
#define GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_POLYGON_HPP

#include <cstddef>

#include <boost/range.hpp>

#include <boost/geometry/core/mutable_range.hpp>
#include <boost/geometry/core/tag.hpp>
#include <boost/geometry/core/tags.hpp>

#include <test_geometries/all_custom_container.hpp>
#include <test_geometries/all_custom_ring.hpp>

template <typename P>
class all_custom_polygon
{
public :
    typedef all_custom_ring<P> custom_ring_type;
    typedef all_custom_container<custom_ring_type> custom_int_type;

    custom_ring_type& custom_ext() { return m_ext; }
    custom_int_type& custom_int() { return m_int; }

    custom_ring_type const& custom_ext() const { return m_ext; }
    custom_int_type const& custom_int() const { return m_int; }

private :
    custom_ring_type m_ext;
    custom_int_type m_int;
};

namespace boost { namespace geometry
{

namespace traits
{

template <typename Point>
struct tag<all_custom_polygon<Point> >
{
    typedef polygon_tag type;
};

template <typename Point>
struct ring_const_type<all_custom_polygon<Point> >
{
    typedef typename all_custom_polygon<Point>::custom_ring_type const& type;
};

template <typename Point>
struct ring_mutable_type<all_custom_polygon<Point> >
{
    typedef typename all_custom_polygon<Point>::custom_ring_type& type;
};

template <typename Point>
struct interior_const_type<all_custom_polygon<Point> >
{
    typedef typename all_custom_polygon<Point>::custom_int_type const& type;
};

template <typename Point>
struct interior_mutable_type<all_custom_polygon<Point> >
{
    typedef typename all_custom_polygon<Point>::custom_int_type& type;
};

template <typename Point>
struct exterior_ring<all_custom_polygon<Point> >
{
    typedef all_custom_polygon<Point> polygon_type;
    typedef typename polygon_type::custom_ring_type ring_type;

    static inline ring_type& get(polygon_type& p)
    {
        return p.custom_ext();
    }

    static inline ring_type const& get(polygon_type const& p)
    {
        return p.custom_ext();
    }
};

template <typename Point>
struct interior_rings<all_custom_polygon<Point> >
{
    typedef all_custom_polygon<Point> polygon_type;
    typedef typename polygon_type::custom_int_type int_type;

    static inline int_type& get(polygon_type& p)
    {
        return p.custom_int();
    }

    static inline int_type const& get(polygon_type const& p)
    {
        return p.custom_int();
    }
};

} // namespace traits

}} // namespace boost::geometry

#endif // GEOMETRY_TEST_TEST_GEOMETRIES_ALL_CUSTOM_POLYGON_HPP

ext: hpp

max_stars_repo_name: olegshnitko/libboost

max_issues_repo_name: olegshnitko/libboost

max_forks_repo_name: olegshnitko/libboost


text:
#include <ros/ros.h>

#include <Eigen/Core>

#include <moveit_msgs/GetCartesianPath.h>
#include <trajectory_msgs/JointTrajectoryPoint.h>
#include <moveit_visual_tools/moveit_visual_tools.h>
#include <simple_moveit_wrapper/industrial_robot.h>

#include <ocpl_tsr/task_space_regions.h>
#include <ocpl_planning/acro_planner.h>
#include <ocpl_planning/cost_functions.h>
#include <ocpl_ros/io.h>

namespace smw = simple_moveit_wrapper;

class PlanningServer
{
    ros::ServiceServer plan_service_;
    ros::NodeHandle node_handle_;

    // visualization
    moveit_visual_tools::MoveItVisualToolsPtr visual_tools_;

    // ocpl interface
    std::shared_ptr<smw::Robot> robot_;
    std::shared_ptr<ocpl::Planner> planner_;
    ocpl::PlannerSettings planner_settings_;

  public:
    /********************
     * Setup
     ********************/
    PlanningServer(const std::string& base_link_name = "world")
    {
        plan_service_ = node_handle_.advertiseService("ocpl_get_cartesian_path", &PlanningServer::callback, this);

        // initialize MoveIt visual tools
        visual_tools_.reset(new moveit_visual_tools::MoveItVisualTools(base_link_name, "/visualization_marker_array"));
        visual_tools_->loadMarkerPub(true);
        visual_tools_->loadRobotStatePub("/display_robot_state", true);
        ros::Duration(0.2).sleep();  // delay to make sure al the messages got where they had to be

        // initialize simple moveit wrapper
        robot_ = std::make_shared<smw::IndustrialRobot>("manipulator", "tool_tip");

        // Translate robot kinematics to solver interface
        ocpl::JointLimits joint_limits;
        for (auto bound : robot_->getJointPositionLimits())
        {
            joint_limits.push_back(ocpl::Bounds{ bound.lower, bound.upper });
            ROS_INFO_STREAM("Joint limits: " << bound.lower << ", " << bound.upper);
        }

        ocpl::Robot bot{ robot_->getNumDof(),
                         robot_->getNumRedDof(),
                         joint_limits,
                         [this](const ocpl::JointPositions& q) { return robot_->fk(q); },
                         [this](const ocpl::Transform& tf, const ocpl::JointPositions& /*q_fixed*/) {
                             return robot_->ik(tf);
                         },
                         [this](const ocpl::JointPositions& q) { return !robot_->isColliding(q); } };

        std::string PLANNER_SETTINGS_FILE{ "kuka/kuka_gpq.yaml" };
        planner_settings_ = ocpl::loadSettingsFromFile(PLANNER_SETTINGS_FILE);

        planner_ = std::make_shared<ocpl::UnifiedPlanner>(bot, planner_settings_);

        ROS_INFO("Ready to receive planning requests.");
    }

    bool callback(moveit_msgs::GetCartesianPath::Request& req, moveit_msgs::GetCartesianPath::Response& res)
    {
        ROS_INFO_STREAM("OCPL planning server received planning request.\n" << req);
        clearRvizMarkers();
        plotWaypoints(req.waypoints);

        auto task = msgToTask(req);

        auto latest_settings = ocpl::loadSettingsFromFile("kuka/kuka_gpq.yaml");
        planner_->changeSettings(latest_settings);

        // make sure recently published collision objects are known
        robot_->updatePlanningScene();

        auto solution = planner_->solve(task, ocpl::L2NormDiff2, ocpl::zeroStateCost);

        robot_->animatePath(visual_tools_, solution.path);

        res.fraction = (double) solution.path.size() / (double) task.size();
        res.solution.joint_trajectory.points.clear();
        double time{0.0}, time_step{0.1};
        for (auto qi : solution.path)
        {
            trajectory_msgs::JointTrajectoryPoint pt;
            pt.positions = qi;
            pt.time_from_start = ros::Duration(time);
            time += time_step;
            res.solution.joint_trajectory.points.push_back(pt);
        }

        return true;
    }
    /********************
     * The Planner
     ********************/
    std::vector<ocpl::TSR> msgToTask(const moveit_msgs::GetCartesianPath::Request& req)
    {
        // only parse orientation constraints for now
        // assume they are the tolerances represent a symmetric interval around the nominal orientation
        // that's the only thing the orientation constraint message supports

        ocpl::TSRBounds bounds{ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 } };
        if (!req.path_constraints.orientation_constraints.empty())
        {
            double x_tol = req.path_constraints.orientation_constraints.at(0).absolute_x_axis_tolerance;
            double y_tol = req.path_constraints.orientation_constraints.at(0).absolute_y_axis_tolerance;
            double z_tol = req.path_constraints.orientation_constraints.at(0).absolute_z_axis_tolerance;
            bounds.rx = { -x_tol / 2.0, x_tol / 2.0 };
            bounds.ry = { -y_tol / 2.0, y_tol / 2.0 };
            bounds.rz = { -z_tol / 2.0, z_tol / 2.0 };
        }

        for (auto bound : bounds.asVector())
        {
            ROS_INFO_STREAM("Tolerance: " << bound.lower << ", " << bound.upper);
        }

        std::vector<ocpl::TSR> task;
        for (auto wp : req.waypoints)
        {
            Eigen::Isometry3d tf =
                Eigen::Translation3d(wp.position.x, wp.position.y, wp.position.z) *
                Eigen::Quaterniond(wp.orientation.w, wp.orientation.x, wp.orientation.y, wp.orientation.z);

            task.push_back(ocpl::TSR{ tf, bounds });
        }
        return task;
    }

    /********************
     * Visualization
     ********************/
    void plotWaypoints(const std::vector<geometry_msgs::Pose>& waypoints)
    {
        for (auto wp : waypoints)
        {
            visual_tools_->publishAxis(wp);
        }
        visual_tools_->trigger();
        ros::Duration(0.2).sleep();
    }

    void clearRvizMarkers()
    {
        visual_tools_->deleteAllMarkers();
        visual_tools_->trigger();
        ros::Duration(0.2).sleep();
    }
};

int main(int argc, char** argv)
{
    ros::init(argc, argv, "ocpl_cart_planning_server");

    PlanningServer server;

    ros::AsyncSpinner spinner(1);
    spinner.start();
    ros::waitForShutdown();

    return 0;
}

ext: cpp

max_stars_repo_name: JeroenDM/ocpl

max_issues_repo_name: JeroenDM/ocpl

max_forks_repo_name: JeroenDM/ocpl


text:
#include <iostream>

#include <boost/asio.hpp>

int main()
{
    using namespace std::literals;

    boost::asio::io_service ioservice;

    boost::asio::steady_timer timer1{ioservice, 3s};
    timer1.async_wait([](auto) { std::cout << "3 sec\n"; });

    boost::asio::steady_timer timer2{ioservice, 4s};
    timer2.async_wait([](auto) { std::cout << "4 sec\n"; });

    ioservice.run();
}

max_stars_repo_name: cvlabmiet/master-programming

max_issues_repo_name: cvlabmiet/master-programming

max_forks_repo_name: cvlabmiet/master-programming


text:
/*
  Copyright (C) 2020-2022 Xilinx, Inc

  Licensed under the Apache License, Version 2.0 (the "License"). You may
  not use this file except in compliance with the License. A copy of the
  License is located 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.
 */

// ------ I N C L U D E   F I L E S -------------------------------------------
// Local - Include Files
#include "ReportAie.h"
#include "core/common/info_aie.h"
#include <boost/algorithm/string/split.hpp>
#include <boost/algorithm/string.hpp>

#define fmtCommon(x) boost::format("    %-22s: " x "\n")
#define fmt4(x) boost::format("%4s%-22s: " x "\n") % " "
#define fmt8(x) boost::format("%8s%-22s: " x "\n") % " "
#define fmt12(x) boost::format("%12s%-22s: " x "\n") % " "
#define fmt16(x) boost::format("%16s%-22s: " x "\n") % " "

boost::property_tree::ptree
populate_aie(const xrt_core::device * _pDevice, const std::string& desc)
{
  xrt::device device(_pDevice->get_device_id());
  boost::property_tree::ptree pt_aie;
  pt_aie.put("description", desc);
  std::stringstream ss;
  ss << device.get_info<xrt::info::device::aie>();
  boost::property_tree::read_json(ss, pt_aie);

  return pt_aie;
}

void
ReportAie::getPropertyTreeInternal(const xrt_core::device * _pDevice,
                                   boost::property_tree::ptree &_pt) const
{
  // Defer to the 20202 format.  If we ever need to update JSON data,
  // Then update this method to do so.
  getPropertyTree20202(_pDevice, _pt);
}

void
ReportAie::getPropertyTree20202(const xrt_core::device * _pDevice,
                                boost::property_tree::ptree &_pt) const
{
  _pt.add_child("aie_metadata", populate_aie(_pDevice, "Aie_Metadata"));
}

void
ReportAie::writeReport(const xrt_core::device* /*_pDevice*/,
                       const boost::property_tree::ptree& _pt,
                       const std::vector<std::string>& _elementsFilter,
                       std::ostream & _output) const
{
  boost::property_tree::ptree empty_ptree;
  std::vector<std::string> aieCoreList;
  bool is_less = false;

  // Loop through all the parameters given under _elementsFilter i.e. -e option
  for (auto it = _elementsFilter.begin(); it != _elementsFilter.end(); ++it) {
    // Only show certain selected cores from aie that are passed under cores
    // Ex. -r aie -e cores 0,3,5
    if(*it == "cores") {
      auto core_list = std::next(it);
      if (core_list != _elementsFilter.end())
        boost::split(aieCoreList, *core_list, boost::is_any_of(","));
    }
    // Show less information (core Status, Program Counter, Link Register, Stack
    // Pointer) for each cores.
    // Ex. -r aie -e less
    if(*it == "less") {
      is_less = true;
    }
  }

  // validate and print aie metadata by checking schema_version node
  if(!_pt.get_child_optional("aie_metadata.schema_version"))
    return;

  _output << "Aie\n";
  _output << boost::format("  %-10s\n") % _pt.get<std::string>("aie_metadata.description");

  try {
    for (auto& gr: _pt.get_child("aie_metadata.graphs")) {
      const boost::property_tree::ptree& graph = gr.second;
      _output << boost::format("  GRAPH[%2d] %-10s: %s\n") % graph.get<std::string>("id")
           % "Name" % graph.get<std::string>("name");
      _output << boost::format("            %-10s: %s\n") % "Status" % graph.get<std::string>("status");
      _output << boost::format("    SNo.  %-20s%-30s%-30s\n") % "Core [C:R]"
           % "Iteration_Memory [C:R]" % "Iteration_Memory_Addresses";
      int count = 0;
      for (auto& node : graph.get_child("tile")) {
        const boost::property_tree::ptree& tile = node.second;
        _output << boost::format("    [%2d]   %-20s%-30s%-30d\n") % count
            % (tile.get<std::string>("column") + ":" + tile.get<std::string>("row"))
            % (tile.get<std::string>("memory_column") + ":" + tile.get<std::string>("memory_row"))
            % node.second.get<uint16_t>("memory_address");
        count++;
      }
      _output << std::endl;
      count = 0;
      for (auto& tile : graph.get_child("tile")) {
        int curr_core = count++;
        if(aieCoreList.size() && (std::find(aieCoreList.begin(), aieCoreList.end(),
		     std::to_string(curr_core)) == aieCoreList.end()))
          continue;

        _output << boost::format("Core [%2d]\n") % curr_core;
        _output << fmt4("%d") % "Column" % tile.second.get<int>("column");
        _output << fmt4("%d") % "Row" % tile.second.get<int>("row");

        _output << boost::format("    %s:\n") % "Core";
        _output << fmt8("%s") % "Status" % tile.second.get<std::string>("core.status");
        _output << fmt8("%s") % "Program Counter" % tile.second.get<std::string>("core.program_counter");
        _output << fmt8("%s") % "Link Register" % tile.second.get<std::string>("core.link_register");
        _output << fmt8("%s") % "Stack Pointer" % tile.second.get<std::string>("core.stack_pointer");

	if(is_less) {
	  _output << std::endl;
	  continue;
	}

	if(tile.second.find("dma") != tile.second.not_found()) {
          _output << boost::format("    %s:\n") % "DMA";

          _output << boost::format("%12s:\n") % "FIFO";
          for(auto& node : tile.second.get_child("dma.fifo.counters")) {
            _output << fmt16("%s") % node.second.get<std::string>("index")
		    % node.second.get<std::string>("count");
          }

          _output << boost::format("        %s:\n") % "MM2S";

          _output << boost::format("            %s:\n") % "Channel";
          for(auto& node : tile.second.get_child("dma.mm2s.channel")) {
            _output << fmt16("%s") % "Id" % node.second.get<std::string>("id");
            _output << fmt16("%s") % "Channel Status" % node.second.get<std::string>("channel_status");
            _output << fmt16("%s") % "Queue Size" % node.second.get<std::string>("queue_size");
            _output << fmt16("%s") % "Queue Status" % node.second.get<std::string>("queue_status");
            _output << fmt16("%s") % "Current BD" % node.second.get<std::string>("current_bd");
            _output << std::endl;
          }

          _output << boost::format("        %s:\n") % "S2MM";

          _output << boost::format("            %s:\n") % "Channel";
          for(auto& node : tile.second.get_child("dma.s2mm.channel")) {
            _output << fmt16("%s") % "Id" % node.second.get<std::string>("id");
            _output << fmt16("%s") % "Channel Status" % node.second.get<std::string>("channel_status");
            _output << fmt16("%s") % "Queue Size" % node.second.get<std::string>("queue_size");
            _output << fmt16("%s") % "Queue Status" % node.second.get<std::string>("queue_status");
            _output << fmt16("%s") % "Current BD" % node.second.get<std::string>("current_bd");
            _output << std::endl;
          }
        }

        if(tile.second.find("locks") != tile.second.not_found()) {
          _output << boost::format("    %s:\n") % "Locks";
          for(auto& node : tile.second.get_child("locks",empty_ptree)) {
            _output << fmt8("%s")  % node.second.get<std::string>("name")
                                   % node.second.get<std::string>("value");
          }
          _output << std::endl;
        }

        if(tile.second.find("errors") != tile.second.not_found()) {
          _output << boost::format("    %s:\n") % "Errors";
          for(auto& node : tile.second.get_child("errors",empty_ptree)) {
            _output << boost::format("        %s:\n") % node.second.get<std::string>("module");
            for(auto& enode : node.second.get_child("error",empty_ptree)) {
              _output << fmt12("%s")  % enode.second.get<std::string>("name")
                                     % enode.second.get<std::string>("value");
            }
          }
          _output << std::endl;
        }

        if(tile.second.find("events") != tile.second.not_found()) {
          _output << boost::format("    %s:\n") % "Events";
          for(auto& node : tile.second.get_child("events",empty_ptree)) {
            _output << fmt8("%s")  % node.second.get<std::string>("name")
                                   % node.second.get<std::string>("value");
          }
          _output << std::endl;
        }
      }
      _output << boost::format("    %s\n") % "Pl Kernel Instances in Graph:";
      for (auto& node : graph.get_child("pl_kernel")) {
        _output << boost::format("      %s\n") % node.second.data();
      }
      _output << std::endl;
    }

    int count = 0;
    for (auto& rtp_node : _pt.get_child("aie_metadata.rtps")) {
      _output << boost::format("  %-3s:[%2d]\n") % "RTP" % count;
      _output << fmtCommon("%s") % "Port Name" % rtp_node.second.get<std::string>("port_name");
      _output << fmtCommon("%d") % "Selector Row" % rtp_node.second.get<uint16_t>("selector_row");
      _output << fmtCommon("%d") % "Selector Column" % rtp_node.second.get<uint16_t>("selector_column");
      _output << fmtCommon("%d") % "Selector Lock Id" % rtp_node.second.get<uint16_t>("selector_lock_id");
      _output << fmtCommon("0x%x") % "Selector Address" %  rtp_node.second.get<uint64_t>("selector_address");
      _output << fmtCommon("%d") % "Ping Buffer Row" % rtp_node.second.get<uint16_t>("ping_buffer_row");
      _output << fmtCommon("%d") % "Ping Buffer Column" % rtp_node.second.get<uint16_t>("ping_buffer_column");
      _output << fmtCommon("%d") % "Ping Buffer Lock Id" % rtp_node.second.get<uint16_t>("ping_buffer_lock_id");
      _output << fmtCommon("0x%x") % "Ping Buffer Address" % rtp_node.second.get<uint64_t>("ping_buffer_address");
      _output << fmtCommon("%d") % "Pong Buffer Row" % rtp_node.second.get<uint16_t>("pong_buffer_row");
      _output << fmtCommon("%d") % "Pong Buffer Column" % rtp_node.second.get<uint16_t>("pong_buffer_column");
      _output << fmtCommon("%d") % "Pong Buffer Lock Id" % rtp_node.second.get<uint16_t>("pong_buffer_lock_id");
      _output << fmtCommon("0x%x") % "Pong Buffer Address" % rtp_node.second.get<uint64_t>("pong_buffer_address");
      _output << fmtCommon("%b") % "Is Plrtp" % rtp_node.second.get<bool>("is_pl_rtp");
      _output << fmtCommon("%b") % "Is Input" % rtp_node.second.get<bool>("is_input");
      _output << fmtCommon("%b") % "Is Async" % rtp_node.second.get<bool>("is_asynchronous");
      _output << fmtCommon("%b") % "Is Connected" % rtp_node.second.get<bool>("is_connected");
      _output << fmtCommon("%b") % "Require Lock" % rtp_node.second.get<bool>("requires_lock");
      count++;
      _output << std::endl;
    }
    _output << std::endl;

    count = 0;
    for (auto& gmio_node : _pt.get_child("aie_metadata.gmios")) {
      _output << boost::format("  %-4s: [%2d]\n") % "GMIO" % count;
      _output << fmtCommon("%s") % "Id" % gmio_node.second.get<std::string>("id");
      _output << fmtCommon("%s") % "Name" %gmio_node.second.get<std::string>("name");
      _output << fmtCommon("%s") % "Logical Name" % gmio_node.second.get<std::string>("logical_name");
      _output << fmtCommon("%d") % "Type" % gmio_node.second.get<uint16_t>("type");
      _output << fmtCommon("%d") % "Shim column" % gmio_node.second.get<uint16_t>("shim_column");
      _output << fmtCommon("%d") % "Channel Number" % gmio_node.second.get<uint16_t>("channel_number");
      _output << fmtCommon("%d") % "Stream Id" % gmio_node.second.get<uint16_t>("stream_id");
      _output << fmtCommon("%d") % "Burst Length in 16byte" % gmio_node.second.get<uint16_t>("burst_length_in_16byte");
      _output << fmtCommon("%s") % "PL Port Name" % gmio_node.second.get<std::string>("pl_port_name");
      _output << fmtCommon("%s") % "PL Parameter Name" % gmio_node.second.get<std::string>("pl_parameter_name");
      count++;
      _output << std::endl;
    }

  } catch(std::exception const& e) {
    _output <<  e.what() << std::endl;
  }
  _output << std::endl;
}

max_stars_repo_name: davidbiancolin/XRT

max_issues_repo_name: kbhardwa-xilinx/XRT

max_forks_repo_name: kbhardwa-xilinx/XRT


text:
#ifndef SHIFT_TASK_TASK_HPP
#define SHIFT_TASK_TASK_HPP

#include <memory>
#include <functional>
#include <shift/core/boost_disable_warnings.hpp>
#include <boost/coroutine2/detail/forced_unwind.hpp>
#include <shift/core/boost_restore_warnings.hpp>
#include "shift/task/types.hpp"
#include "shift/task/promise.hpp"
#include "shift/task/task_create_info.hpp"
#include "shift/task/this_task.hpp"

namespace shift::task
{
/// Base class for all tasks.
class task_base
{
public:
  ///
  task_base(const task_create_info& create_info,
            std::function<void()> wrapped_function);

  task_base(const task_base&) = delete;
  task_base(task_base&&) = delete;

  /// Destructor.
  virtual ~task_base();

  task_base& operator=(const task_base&) = delete;
  task_base& operator=(task_base&&) = delete;

  ///
  void yield();

  ///
  task_id_t id() const;

  /// Forces the task to be processed only by specific worker threads.
  void worker_affinity(worker_affinity_t affinity);

  /// Returns the worker affinity mask.
  worker_affinity_t worker_affinity() const;

private:
  friend class task_system;

  struct impl;
  std::unique_ptr<impl> _impl;
};

template <typename Result>
class task_result : public task_base
{
public:
  using result_t = Result;

  ///
  task_result(const task_create_info& create_info,
              std::function<void()> wrapped_function)
  : task_base(create_info, std::move(wrapped_function))
  {
  }

  ///
  auto get_future()
  {
    return _promise.get_future();
  }

protected:
  promise<result_t> _promise;
};

/// Explicit task providing a promise about the result of the task function.
template <typename Function, typename... Args>
class task
: public task_result<std::result_of_t<std::decay_t<Function>(Args...)>>
{
public:
  using base_t = task_result<std::result_of_t<std::decay_t<Function>(Args...)>>;

  /// Constructor.
  task(const task_create_info& create_info, Function&& function, Args&&... args)
  : base_t(create_info,
           [&]() {
             try
             {
               base_t::_promise.set_value(
                 call_function(_function, std::index_sequence_for<Args...>{}));
             }
             catch (const boost::coroutines2::detail::forced_unwind&)
             {
               // Ignore this type of exception.
             }
             catch (...)
             {
               base_t::_promise.set_exception(std::current_exception());
             }
           }),
    _function(std::forward<Function>(function)),
    _args(std::move(args)...)
  {
  }

  /// Destructor.
  ~task() override = default;

private:
  ///
  template <std::size_t... Is>
  typename base_t::result_t call_function(Function function,
                                          std::index_sequence<Is...> /*unused*/)
  {
    return function(std::forward<std::tuple_element_t<Is, std::tuple<Args...>>>(
      std::get<Is>(_args))...);
  }

  Function _function;
  std::tuple<std::remove_reference_t<Args>...> _args;
};
}

#endif

max_stars_repo_name: cspanier/shift

max_issues_repo_name: cspanier/shift

max_forks_repo_name: cspanier/shift


text:
#include <algorithm>
#include <cstring>
#include <limits>
#include <memory>
#include <queue>

#include <android/log.h>

#include <boost/foreach.hpp>
#include <boost/integer_traits.hpp>

#include <tbb/blocked_range2d.h>
#include <tbb/parallel_for.h>
#include <tbb/task_scheduler_init.h>

#include "body_parts_recognizer.h"
#include "cloud.h"
#include "stopwatch.h"

const Depth BACKGROUND_DEPTH = std::numeric_limits<Depth>::max();

template <typename Format> void
applyThreshold(ChannelRef<Format> & channel, Format threshold, Format bgValue)
{
  for (int i = 0; i < channel.size; ++i)
    if (channel.data[i] > threshold)
      channel.data[i] = bgValue;
}

template <typename Format> Format
selectThreshold(const ChannelRef<Format> & channel)
{
  // We use Otsu's method here.
  const int num_bins = boost::integer_traits<Format>::const_max + 1;
  int bins[num_bins] = { 0 };
  int count = 0;

  for (int i = 0; i < channel.size; ++i)
    if (channel.data[i] != BACKGROUND_DEPTH)
    {
      ++bins[channel.data[i]];
      ++count;
    }

  double scale = 1. / count;
  double mu = 0;

  for (int i = 0; i < num_bins; ++i) mu += i * bins[i] * scale;

  double mu1 = 0, mu2, p1 = 0, p2;
  double max_var = 0;
  Format thresh = 0;

  for (int i = 0; i < num_bins; ++i)
  {
    p1 += bins[i] * scale;
    p2 = 1 - p1;

    mu1 += i * bins[i] * scale;
    mu2 = mu - mu1;

    double var = p1 * p2 * (mu1 - mu2) * (mu1 - mu2);
    if (var > max_var)
    {
      max_var = var;
      thresh = i;
    }
  }

  return thresh;
}

template <typename Format> Format
replaceZeroes(ChannelRef<Format> & channel, Format replacement)
{
  std::replace(channel.data, channel.data + channel.size, Format(), replacement);
}

DECLARE_CLOUD_TAG(TagVisited, bool)

struct Component
{
  int y, x, surface;
};

struct ComponentSurfaceCompare
{
  bool operator() (const Component & c1, const Component & c2)
  { return c1.surface < c2.surface; }
};

template <typename Format> int
calcComponentSurface(const ChannelRef<Format> channel, ChannelRef<bool> visited, Format empty, int startY, int startX)
{
  std::queue<std::pair<int, int> > to_visit;
  to_visit.push(std::make_pair(startY, startX));
  int surface = 0;

  while (!to_visit.empty())
  {
    const std::pair<int, int> yx = to_visit.front();
    to_visit.pop();

    int y = yx.first, x = yx.second;

    if (x < 0 || x >= channel.width || y < 0 || y >= channel.height || visited.at(y, x) || channel.at(y, x) == empty) continue;

    visited.at(y, x) = true;
    ++surface;

    to_visit.push(std::make_pair(y, x + 1));
    to_visit.push(std::make_pair(y, x - 1));
    to_visit.push(std::make_pair(y + 1, x));
    to_visit.push(std::make_pair(y - 1, x));
  }

  return surface;
}

template <typename Format> void
eraseComponent(ChannelRef<Format> channel, Format empty, int y, int x)
{
  std::queue<std::pair<int, int> > to_visit;
  to_visit.push(std::make_pair(y, x));

  while (!to_visit.empty())
  {
    const std::pair<int, int> yx = to_visit.front();
    to_visit.pop();

    int y = yx.first, x = yx.second;

    if (x < 0 || x >= channel.width || y < 0 || y >= channel.height || channel.at(y, x) == empty) continue;

    channel.at(y, x) = empty;

    to_visit.push(std::make_pair(y, x + 1));
    to_visit.push(std::make_pair(y, x - 1));
    to_visit.push(std::make_pair(y + 1, x));
    to_visit.push(std::make_pair(y - 1, x));
  }
}

template <typename Format> Format
keepBiggestComponent(const ChannelRef<Format> channel, Format empty)
{
  Cloud temp;
  temp.resize(channel.width, channel.height);

  ChannelRef<bool> visited = temp.get<TagVisited>();
  std::fill_n(visited.data, visited.size, false);

  std::vector<Component> components;

  for (int i = 0; i < channel.height; ++i)
    for (int j = 0; j < channel.width; ++j)
      if (channel.at(i, j) != empty && !visited.at(i, j))
      {
        Component component = { i, j, calcComponentSurface(channel, visited, empty, i, j) };
        components.push_back(component);
      }

  const Component & biggest = *std::max_element(components.begin(), components.end(), ComponentSurfaceCompare());

  int with = 0;

  BOOST_FOREACH(const Component & c, components)
    if (c.surface < biggest.surface)
      eraseComponent(channel, empty, c.y, c.x);
}

struct DecisionTreeCPU
{
  tbb::task_scheduler_init tbb_init;

  struct Offsets
  {
    boost::int16_t du1, dv1, du2, dv2;
  };

  struct Node
  {
    Offsets offsets;
    boost::int16_t threshold;
  };

  boost::uint16_t depth;
  std::vector<Node> nodes;
  std::vector<Label> leaves;

  explicit DecisionTreeCPU(const char * data)
  {
    std::memcpy (&depth, data, sizeof depth);
    data += sizeof depth;

    nodes.resize ((1 << depth) - 1);
    std::memcpy (&nodes.front (), data, nodes.size () * sizeof (Node));
    data += nodes.size () * sizeof (Node);

    leaves.resize (1 << depth);
    std::memcpy (&leaves.front (), data, leaves.size () * sizeof (Label));
    data += leaves.size () * sizeof (Label);
  }

  Label
  walk(const ChannelRef<Depth> & depthChannel, int x, int y) const
  {
    unsigned nid = 0;
    Depth d0 = depthChannel.at(y, x);
    float scale = 1000.0f / d0;

    for(int node_depth = 0; node_depth < depth; ++node_depth)
    {
      const Node & node = nodes[nid];

      Depth d1 = depthChannel.atDef(y + node.offsets.dv1 * scale, x + node.offsets.du1 * scale, BACKGROUND_DEPTH);
      Depth d2 = depthChannel.atDef(y + node.offsets.dv2 * scale, x + node.offsets.du2 * scale, BACKGROUND_DEPTH);

      int feature = int (d1) - int (d2);

      if (feature > node.threshold)
        nid = nid * 2 + 2;
      else
        nid = nid * 2 + 1;
    }

    return leaves[nid - nodes.size()];
  }

  struct WalkHelper
  {
  private:
    const DecisionTreeCPU & tree;
    const ChannelRef<Depth> depth;
    std::vector<Label> & labels;

  public:
    WalkHelper(const DecisionTreeCPU & tree, Cloud & cloud, std::vector<Label> & labels)
      : tree(tree), depth(cloud.get<TagDepth>()), labels(labels)
    {
    }

    void
    operator () (const tbb::blocked_range2d<unsigned> & range) const
    {
      for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)
        for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)
          labels[x + y * depth.width] = depth.at(y, x) == BACKGROUND_DEPTH ?
                Labels::Background : tree.walk(depth, x, y);
    }
  };

  void
  eval(Cloud & cloud, std::vector<Label> & labels) const
  {
    tbb::parallel_for(
          tbb::blocked_range2d<unsigned>(0, cloud.getHeight(), 0, cloud.getWidth()),
          WalkHelper(*this, cloud, labels)
    );
  }
};

int maxElementNoTie(int num, unsigned * elements)
{
  int max_element = 0;
  unsigned max = elements[max_element];

  for (int i = 1; i < num; ++i)
  {
    unsigned val = elements[i];
    if (max < val) { max_element = i; max = val; }
    else if (max == val) { max_element = -1; }
  }

  return max_element;
}

struct FilterHelper
{
private:
  ChannelRef<Label> noisy, good;
  int radius;

public:
  FilterHelper(ChannelRef<Label> noisy, ChannelRef<Label> good, int radius)
    : noisy(noisy), good(good), radius(radius)
  { }

  void
  operator ()(const tbb::blocked_range2d<int> & range) const
  {
    int width = noisy.width, height = noisy.height;

    for (int i = range.rows().begin(); i < range.rows().end(); ++i)
      for (int j = range.cols().begin(); j < range.cols().end(); ++j)
      {
        int idx = i * width + j;

        if (i < radius || i >= height - radius || j < radius || j >= width - radius || noisy.data[idx] == Labels::Background)
        {
          good.data[idx] = Labels::Background;
          continue;
        }

        int bins[Labels::NUM_LABELS] = { 0 };
        Label mode = -1;
        Label mode_count = 0;

        for (int dy = -radius; dy <= radius; ++dy)
          for (int dx = -radius; dx <= radius; ++dx)
          {
            Label current = noisy.data[idx + dx + dy * width];
            ++bins[current];
            if (bins[current] > mode_count) {
              mode_count = bins[current];
              mode = current;
            }
          }

        good.data[idx] = mode;
      }
  }
};

void filterLabels(Cloud & noisy, Cloud & output, int radius)
{
  int width = noisy.getWidth(), height = noisy.getHeight();
  ChannelRef<Label> noisy_labels = noisy.get<TagBPLabel>();
  ChannelRef<Label> good_labels = output.get<TagBPLabel>();

  tbb::parallel_for(
        tbb::blocked_range2d<int>(0, noisy.getHeight(), 0, noisy.getWidth()),
        FilterHelper(noisy_labels, good_labels, radius)
  );
}

struct ConsensusHelper
{
private:
  const std::vector<std::vector<Label> > & multi_labels;
  ChannelRef<Label> labels;
  const ChannelRef<Depth> depths;

public:
  ConsensusHelper(
      const std::vector<std::vector<Label> > & multi_labels,
      Cloud & cloud
  )
    : multi_labels(multi_labels), labels(cloud.get<TagBPLabel>()), depths(cloud.get<TagDepth>())
  { }

  void
  operator ()(const tbb::blocked_range2d<unsigned> & range) const
  {
    for (unsigned y = range.rows().begin(); y < range.rows().end(); ++y)
      for (unsigned x = range.cols().begin(); x < range.cols().end(); ++x)
      {
        std::size_t i = &depths.at(y, x) - depths.data;

        bool background = true;
        for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
          if (multi_labels[ti][i] != Labels::Background) background = false;

        if (background)
        {
          labels.data[i] = Labels::Background;
          continue;
        }

        unsigned bins[Labels::NUM_LABELS] = { 0 };

        for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
          ++bins[multi_labels[ti][i]];

        int consensus = maxElementNoTie(Labels::NUM_LABELS, bins);

        if (consensus == -1)
        {
          std::fill (bins, bins + Labels::NUM_LABELS, 0);
          Depth d = depths.at(y, x);

          for (int off_x = -1; off_x <= 1; ++off_x)
            for (int off_y = -1; off_y <= 1; ++off_y)
            {
              Depth off_d = depths.atDef(y + off_y, x + off_x, BACKGROUND_DEPTH);

              if (std::abs (d - off_d) < 50)
                for (std::size_t ti = 0; ti < multi_labels.size (); ++ti)
                  ++bins[multi_labels[ti][i]];
            }

          labels.data[i] = std::max_element (bins, bins + Labels::NUM_LABELS) - bins;
        }
        else
        {
          labels.data[i] = consensus;
        }
      }
  }
};

void
findConsensus(const std::vector<std::vector<Label> > & multi_labels, Cloud & cloud)
{
  tbb::parallel_for(
        tbb::blocked_range2d<unsigned>(0, cloud.getHeight(), 0, cloud.getWidth()),
        ConsensusHelper(multi_labels, cloud)
  );
}

BodyPartsRecognizer::BodyPartsRecognizer(std::size_t num_trees, const char * trees[])
{
  this->trees.resize(num_trees);

  for (std::size_t i = 0; i < num_trees; ++i)
    this->trees[i].reset(new Tree(trees[i]));
}

void
BodyPartsRecognizer::recognize(Cloud & cloud) const
{
  ChannelRef<Depth> depth = cloud.get<TagDepth>();

  Stopwatch watch_threshold;

  replaceZeroes(depth, BACKGROUND_DEPTH);
  applyThreshold(depth, selectThreshold(depth), BACKGROUND_DEPTH);
  keepBiggestComponent(depth, BACKGROUND_DEPTH);

  __android_log_print(ANDROID_LOG_INFO, "BPR", "Thresholding: %d ms", watch_threshold.elapsedMs());

  std::vector<std::vector<Label> > multi_labels (trees.size ());

  for (std::size_t ti = 0; ti < trees.size (); ++ti)
  {
    Stopwatch watch_evaluation;

    multi_labels[ti].resize (cloud.getHeight() * cloud.getWidth());
    trees[ti]->eval (cloud, multi_labels[ti]);

    __android_log_print(ANDROID_LOG_INFO, "BPR", "Evaluating tree %d: %d ms", ti, watch_evaluation.elapsedMs());
  }

  Stopwatch watch_consensus;

  Cloud noisy;
  noisy.resize(cloud.getWidth(), cloud.getHeight());

  findConsensus(multi_labels, noisy);

  __android_log_print(ANDROID_LOG_INFO, "BPR", "Finding consensus: %d ms", watch_consensus.elapsedMs());

  Stopwatch watch_filtering;

  filterLabels(noisy, cloud, 2);

  __android_log_print(ANDROID_LOG_INFO, "BPR", "Filtering labels: %d ms", watch_consensus.elapsedMs());

}

max_stars_repo_name: PointCloudLibrary/mobile


text:
/***********************************************************************
 *                      Kuramoto oscillators                           *
 *             Copyright (c) 2014-2015 Alex Khrabrov                   *
 ***********************************************************************
 * This program is free software. It comes without any warranty, to    *
 * the extent permitted by applicable law. You can redistribute it     *
 * and/or modify it under the terms of the Do What The Fuck You Want   *
 * To Public License, Version 2, as published by Sam Hocevar. See      *
 * license text below.                                                 *
 ***********************************************************************
 *                                                                     *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE              *
 *                    Version 2, December 2004                         *
 *                                                                     *
 * Copyright (C) 2004 Sam Hocevar <sam@hocevar.net>                    *
 *                                                                     *
 * Everyone is permitted to copy and distribute verbatim or modified   *
 * copies of this license document, and changing it is allowed as long *
 * as the name is changed.                                             *
 *                                                                     *
 *            DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE              *
 *   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION   *
 *                                                                     *
 *  0. You just DO WHAT THE FUCK YOU WANT TO.                          *
 *                                                                     *
 ***********************************************************************/

typedef double fp_type;

#define _USE_MATH_DEFINES
#include <cmath>
static const fp_type TWO_PI = 2.0 * M_PI;
#undef _USE_MATH_DEFINES

#include <iostream>
#include <iomanip>
#include <fstream>
#include <string>
#include <map>
#include <random>
#include <algorithm>
#include <numeric>

#include <cassert>
#include <cstdint>
#include <cstdlib>

#include <boost/filesystem.hpp>
#include <boost/program_options.hpp>

#if defined(WIN32) || defined(_WIN32)
#define PATH_SEPARATOR "\\"
#else
#define PATH_SEPARATOR "/"
#endif

#ifdef _MSC_VER
#define FORCE_INLINE __forceinline
#else
#define FORCE_INLINE inline
#endif

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

template<typename T>
FORCE_INLINE T mean(const std::vector<T> & v)
{
    const auto size = v.size();
    assert(size != 0);
    T sum(0);
    for(typename std::vector<T>::size_type i = 0; i < size; i++)
        sum += v[i];
    return sum / T(size);
}

static std::vector<fp_type> tmp_s;
static std::vector<fp_type> tmp_c;

template<typename T>
T calc_order_parameter(const std::vector<T> & phases)
{
    using namespace std;
    const auto size = phases.size();
    tmp_s.resize(size);
    tmp_c.resize(size);
    for(typename std::vector<T>::size_type i = 0; i < size; i++)
    {
        const T p = phases[i];
        tmp_s[i] = sin(p);
        tmp_c[i] = cos(p);
    }
    const T mean_sin = mean(tmp_s);
    const T mean_cos = mean(tmp_c);
    return sqrt(mean_cos * mean_cos + mean_sin * mean_sin);
}

template<typename T>
FORCE_INLINE T rand_range(T min, T max)
{
    assert(max > min);
    return ((T(rand()) / T(RAND_MAX)) * (max - min)) + min;
}

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

template<typename T>
FORCE_INLINE T wrap_phase_1(T p)
{
    if(p > T(TWO_PI))
        p -= T(TWO_PI);
    else if(p < 0.0)
        p += T(TWO_PI);
    return p;
}

template<typename T>
FORCE_INLINE T wrap_phase_2(T p)
{
    while(p < 0.0 || p > T(TWO_PI))
    {
        if(p > T(TWO_PI))
            p -= T(TWO_PI);
        else if(p < 0.0)
            p += T(TWO_PI);
    }
}

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

template<typename T>
FORCE_INLINE T kuramoto_classic(const T phi)
{
    return std::sin(phi);
}

template<int n, typename T>
FORCE_INLINE T kuramoto_n(const T phi)
{
    return std::sin(T(n) * phi);
}

template<typename T>
FORCE_INLINE T daido_original(const T phi)
{
    return std::sin(phi) +
        T(0.2) * std::cos(phi) -
        T(0.3) * std::sin(T(2.0) * phi) +
        T(0.6) * std::cos(T(2.0) * phi) +
        T(0.7) * std::sin(T(3.0) * phi) -
        T(0.4) * std::cos(T(3.0) * phi);
}

template<typename T>
FORCE_INLINE T coupling_1(const T phi)
{
    return std::sin(phi) + std::sin(T(3.0) * phi);
}

template<typename T>
FORCE_INLINE T coupling_2(const T phi)
{
    return std::sin(phi) +
           std::sin(T(3.0) * phi) +
           std::sin(T(6.0) * phi);
}

template<typename T>
FORCE_INLINE T coupling_3(const T phi)
{
    return std::sin(phi) + std::cos(T(3.0) * phi);
}

template<typename T>
FORCE_INLINE T coupling_4(const T phi)
{
    return std::cos(phi) + std::cos(T(3.0) * phi);
}

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

template<typename T>
void write_vector(std::ostream & os, const std::vector<T> & vec)
{
    for(const auto x : vec)
        os << x << ' ';
}

template<typename T>
void dump_state
(
    const std::string & out_file_name,
    const std::vector<T> & phase,
    const std::vector<T> & vel,
    const unsigned int step,
    const unsigned int N,
    const T r,
    const T mean_phase
)
{
    using namespace std;
    ofstream out(out_file_name, ofstream::trunc);
    out << step << ' ' << N << ' ' << r << ' ' << mean_phase << '\n';
    write_vector(out, phase);
    out << '\n';
    write_vector(out, vel);
}

template<typename T, T(*H)(T)>
void run_simulation
(
    const bool quiet,                    // if true produce no output to console

    const unsigned int N,                // number of oscillators
    const unsigned int N_steps,          // simulations steps

    const T dt,                          // time step

    std::vector<T> phase,                // initial phases
    const std::vector<T> freq,           // oscillator's frequencies
    const std::vector<T> k,              // coupling matrix

    const std::string & name,            // current working set name

    const T noise,                       // noise amplitude

    const T forcing_strength,            // when != 0 all oscillators are forced by external field
    const T forcing_freq,                // external forcing frequency

    const unsigned int dump_interval,    // how often to dump frame snapshots

    const bool r_history_enabled,        // write r values to file
    const bool mean_history_enabled,     // write mean values to file
    const bool mean_vel_history_enabled, // write mean velocity values to file

    const bool freq_modulation_enabled,  // is oscillator frequency modulation enabled
    const std::vector<T> freq_ampl,      // frequency modulation amplitude
    const std::vector<T> freq_freq,      // frequency modulation frequency
    const std::vector<T> freq_offset,    // frequency modulation offset

    const bool k_modulation_enabled,     // is coupling coefficient modulation enabled
    const std::vector<T> k_ampl,         // coupling coefficient modulation amplitude
    const std::vector<T> k_freq,         // coupling coefficient modulation frequency
    const std::vector<T> k_offset,       // coupling coefficient modulation offset

    const std::string & out_dir_name,      // MUST end with directory separator (/ or \)
    const std::string & r_file_path,       // if specified r history will be written to this file
    const std::string & mean_file_path,    // if specified mean phase will be written to this file
    const std::string & mean_vel_file_path // if specified mean velocity will be written to this file
)
{
    using namespace std;

    assert(N > 0 && dt > 0 && phase.size() == N && freq.size() == N && k.size() == N*N);
    assert(freq_modulation_enabled ? (freq_ampl.size() == N && freq_freq.size() == N && freq_offset.size() == N) : true);
    assert(k_modulation_enabled ? (k_ampl.size() == N && k_freq.size() == N*N && k_offset.size() == N*N) : true);

    const T two_dt = T(2.0) * dt;

    const bool add_noise = (noise != 0.0);
    const bool forcing_enabled = (forcing_strength != 0.0);
    const bool dump_enabled = (dump_interval != 0);

    // collect global statistics during simulation
    vector<T> r_hist(N_steps);
    vector<T> mean_hist(N_steps);
    vector<T> mean_vel_hist(N_steps);

    vector<T> phase_old = phase;
    vector<T> phase_old_old = phase;

    vector<T> vel(N);

    unsigned int dump_counter = 0;

    for(unsigned int step = 0; step < N_steps; step++)
    {
        const T t = T(step) * dt;
        for(unsigned int i = 0; i < N; i++)
        {
            T f;
            if(!freq_modulation_enabled)
                f = freq[i];
            else
                f = freq[i] + freq_ampl[i] * sin(T(TWO_PI) * freq_freq[i] * t + freq_offset[i]);

            // NOTE: k[i*N + j] can be interpreted as k[i][j]
            if(!k_modulation_enabled)
            {
                const unsigned int offset = i * N;
                const T phase_old_i = phase_old[i];
                for(unsigned int j = 0; j < N; j++)
                    f += k[offset + j] * H(phase_old[j] - phase_old_i);
            }
            else
            {
                const unsigned int offset = i * N;
                const T phase_old_i = phase_old[i];
                for(unsigned int j = 0; j < N; j++)
                {
                    const unsigned int idx = offset + j;
                    f += (k[idx] + k_ampl[i] * sin(T(TWO_PI) * k_freq[idx] * t + k_offset[idx]))
                        * H(phase_old[j] - phase_old_i);
                }
            }

            if(forcing_enabled)
                f += forcing_strength * sin(forcing_freq * t - phase_old[i]);

            if(add_noise)
                f += rand_range<T>(-noise, noise);

            // calculate new phase
            const T p = phase_old[i] + f * dt;
            phase[i] = wrap_phase_1(p);
        }

        for(unsigned int i = 0; i < N; i++)
            vel[i] = (phase[i] - phase_old_old[i]) / two_dt;

        const T r = calc_order_parameter(phase);
        r_hist[step] = r;

        const T mean_phase = mean(phase);
        mean_hist[step] = mean_phase;

        mean_vel_hist[step] = mean(vel);

        if(dump_enabled)
        {
            if(dump_counter == 0)
            {
                dump_counter = dump_interval;
                const string out_file_name(out_dir_name + to_string(step) + ".txt");
                if(!quiet)
                    cout << "Saving at step: " << step << endl;
                dump_state(out_file_name, phase, vel, step, N, r, mean_phase);
            }
            dump_counter--;
        }
        else if(!(step % 100))
            if(!quiet)
                cout << "Step: " << step << endl;

        phase_old_old = phase_old;
        phase_old = phase;
    }

    if(r_history_enabled)
    {
        ofstream r_out(r_file_path, ofstream::trunc);
        write_vector(r_out, r_hist);
    }

    if(mean_history_enabled)
    {
        ofstream mean_out(mean_file_path, ofstream::trunc);
        write_vector(mean_out, mean_hist);
    }

    if(mean_vel_history_enabled)
    {
        ofstream mean_vel_out(mean_vel_file_path, ofstream::trunc);
        write_vector(mean_vel_out, mean_vel_hist);
    }
}

void read_preset(std::ifstream & input,
                 unsigned int & N,
                 std::vector<double> & freq,
                 std::vector<double> & phase,
                 std::vector<double> & k)
{
    using namespace std;

    uint32_t N_;
    input.read(reinterpret_cast<char*>(&N_), sizeof(N_));
    N = N_;

    freq.resize(N);
    phase.resize(N);
    k.resize(N*N);

    input.read(reinterpret_cast<char*>(freq.data()), N*sizeof(double));
    input.read(reinterpret_cast<char*>(phase.data()), N*sizeof(double));
    input.read(reinterpret_cast<char*>(k.data()), N*N*sizeof(double));
}

void read_freq_modulation_data(std::ifstream & input,
                               unsigned int N,
                               std::vector<double> & freq_ampl,
                               std::vector<double> & freq_freq,
                               std::vector<double> & freq_offset)
{
    using namespace std;

    freq_ampl.resize(N);
    freq_freq.resize(N);
    freq_offset.resize(N);

    input.read(reinterpret_cast<char*>(freq_ampl.data()), N*sizeof(double));
    input.read(reinterpret_cast<char*>(freq_freq.data()), N*sizeof(double));
    input.read(reinterpret_cast<char*>(freq_offset.data()), N*sizeof(double));
}

void read_k_modulation_data(std::ifstream & input,
                            unsigned int N,
                            std::vector<double> & k_ampl,
                            std::vector<double> & k_freq,
                            std::vector<double> & k_offset)
{
    using namespace std;

    k_ampl.resize(N);
    k_freq.resize(N*N);
    k_offset.resize(N*N);

    input.read(reinterpret_cast<char*>(k_ampl.data()), N*sizeof(double));
    input.read(reinterpret_cast<char*>(k_freq.data()), N*N*sizeof(double));
    input.read(reinterpret_cast<char*>(k_offset.data()), N*N*sizeof(double));
}

int main(int argc, char * argv[])
{
    using namespace std;

    ios_base::sync_with_stdio(false);

    try
    {
        namespace po = boost::program_options;
        po::options_description desc("Options");
        desc.add_options()
            ("help,h", "print help message")
            ("quiet,q", "produce no output to console")

            ("preset,p", po::value<std::string>()->required(), "preset name")
            ("steps,s", po::value<unsigned int>()->default_value(1000), "simulation steps")
            ("dump-interval,di", po::value<unsigned int>()->default_value(100), "data dump interval")
            ("dt", po::value<double>()->default_value(0.01), "simulation time step")

            ("noise", po::value<double>()->default_value(0.0), "noise level")

            ("coupling,c", po::value<std::string>()->default_value("kuramoto"), "coupling type")

            ("forcing-strength,fs", po::value<double>()->default_value(0.0), "forcing strength")
            ("forcing-freq,ff", po::value<double>()->default_value(0.0), "forcing frequency")

            ("enable-k-modulation", "enable coupling coefficient modulation")
            ("enable-freq-modulation", "enable frequency modulation")

            ("r-file", po::value<std::string>()->implicit_value(""), "r file path")
            ("mean-phase-file", po::value<std::string>()->implicit_value(""), "mean phase file path")
            ("mean-vel-file", po::value<std::string>()->implicit_value(""), "mean velocity file path");

        po::variables_map vm;

        try
        {
            po::store(po::parse_command_line(argc, argv, desc), vm);

            if(vm.count("help"))
            {
                std::cout << std::endl
                          << "kuramoto_simulation - versatile Kuramoto simulation program" << std::endl
                          << std::endl
                          << desc << std::endl;
                return EXIT_SUCCESS;
            }
        }
        catch(const po::error & e)
        {
            std::cerr << "ERROR: " << e.what() << std::endl << std::endl;
            std::cerr << desc << std::endl;
            return EXIT_FAILURE;
        }

        if(!vm.count("preset"))
        {
            std::cerr << "Preset name is required!" << std::endl
                      << "Hint: use -h option to display help." << std::endl;
            return EXIT_FAILURE;
        }

        const bool quiet = vm.count("quiet");

        const string preset_name = vm["preset"].as<std::string>();

        const unsigned int N_steps = vm["steps"].as<unsigned int>();
        unsigned int dump_interval = vm["dump-interval"].as<unsigned int>();
        const fp_type dt = vm["dt"].as<double>();
        const string coupling_type = vm["coupling"].as<std::string>();

        const fp_type noise = vm["noise"].as<double>();

        const fp_type forcing_strength = vm["forcing-strength"].as<double>();
        const fp_type forcing_freq = vm["forcing-freq"].as<double>();

        const bool freq_modulation_enabled = vm.count("enable-freq-modulation");
        const bool k_modulation_enabled = vm.count("enable-k-modulation");

        unsigned int N;
        vector<fp_type> freq;
        vector<fp_type> phase;
        vector<fp_type> k;

        // read preset data
        {
            ifstream input(preset_name + ".preset", ifstream::in | ifstream::binary);

            if(!input)
            {
                cerr << "Unable to open input file: " << preset_name << ".preset" << endl;
                return EXIT_FAILURE;
            }

            input.exceptions(ifstream::failbit | ifstream::badbit);

            read_preset(input, N, freq, phase, k);
        }

        vector<fp_type> freq_ampl;
        vector<fp_type> freq_freq;
        vector<fp_type> freq_offset;

        vector<fp_type> k_ampl;
        vector<fp_type> k_freq;
        vector<fp_type> k_offset;

        if(freq_modulation_enabled)
        {
            if(!quiet)
                cout << "freq_modulation_enabled" << endl;
            ifstream input_s(preset_name + ".fm.preset", ifstream::in | ifstream::binary);
            if (!input_s)
            {
                cerr << "Unable to open frequency modulation data file: " << preset_name << ".fm.preset" << endl;
                return EXIT_FAILURE;
            }
            input_s.exceptions(ifstream::failbit | ifstream::badbit);
            read_freq_modulation_data(input_s, N, freq_ampl, freq_freq, freq_offset);
        }

        if(k_modulation_enabled)
        {
            if(!quiet)
                cout << "k_modulation_enabled" << endl;
            ifstream input_s(preset_name + ".km.preset", ifstream::in | ifstream::binary);
            if (!input_s)
            {
                cerr << "Unable to open k modulation data file: " << preset_name << ".km.preset" << endl;
                return EXIT_FAILURE;
            }
            input_s.exceptions(ifstream::failbit | ifstream::badbit);
            read_k_modulation_data(input_s, N, k_ampl, k_freq, k_offset);
        }

        if(!quiet)
            std::cout << "Data loaded." << std::endl;

        const bool r_history_enabled = vm.count("r-file");
        const bool mean_history_enabled = vm.count("mean-phase-file");
        const bool mean_vel_history_enabled = vm.count("mean-vel-file");

        string r_file_path;
        string mean_file_path;
        string mean_vel_file_path;

        string out_dir_name;

        // initialize dump directory
        if(dump_interval > 0)
        {
            out_dir_name = "dump_" + preset_name + PATH_SEPARATOR + "steps" + PATH_SEPARATOR;
            // std::cout << "Creating steps dir: " << out_dir_name << std::endl;
            boost::filesystem::create_directories(out_dir_name);
        }

        if(r_history_enabled)
        {
            r_file_path = vm["r-file"].as<std::string>();
            if(r_file_path.empty())
                r_file_path = out_dir_name + "r.txt";
            const string path_str = boost::filesystem::path(r_file_path).parent_path().string();
            if(!path_str.empty())
                boost::filesystem::create_directories(path_str);
        }

        if(mean_history_enabled)
        {
            mean_file_path = vm["mean-phase-file"].as<std::string>();
            if(mean_file_path.empty())
                mean_file_path = out_dir_name + "mean.txt";
            const string path_str = boost::filesystem::path(mean_file_path).parent_path().string();
            if(!path_str.empty())
                boost::filesystem::create_directories(path_str);
        }

        if(mean_vel_history_enabled)
        {
            mean_vel_file_path = vm["mean-vel-file"].as<std::string>();
            if(mean_vel_file_path.empty())
                mean_vel_file_path = out_dir_name + "mean_vel.txt";
            const string path_str = boost::filesystem::path(mean_vel_file_path).parent_path().string();
            if(!path_str.empty())
                boost::filesystem::create_directories(path_str);
        }

        //std::cout << "r_file_path: " << r_file_path << std::endl;
        //std::cout << "mean_file_path: " << mean_file_path << std::endl;
        //std::cout << "mean_vel_file_path: " << mean_vel_file_path << std::endl;

#define RUN_SIMUL(coupling)                  \
        run_simulation<fp_type, coupling>(   \
            quiet,                           \
            N, N_steps, dt,                  \
            phase, freq, k, preset_name,     \
            noise,                           \
            forcing_strength, forcing_freq,  \
            dump_interval,                   \
            r_history_enabled,               \
            mean_history_enabled,            \
            mean_vel_history_enabled,        \
            freq_modulation_enabled,         \
            freq_ampl,                       \
            freq_freq,                       \
            freq_offset,                     \
            k_modulation_enabled,            \
            k_ampl,                          \
            k_freq,                          \
            k_offset,                        \
            out_dir_name,                    \
            r_file_path,                     \
            mean_file_path,                  \
            mean_vel_file_path               \
        )

        if(coupling_type == "kuramoto")
            RUN_SIMUL(kuramoto_classic);
        else if(coupling_type == "kuramoto_2")
            RUN_SIMUL(kuramoto_n<2>);
    	else if(coupling_type == "kuramoto_3")
    		RUN_SIMUL(kuramoto_n<3>);
    	else if(coupling_type == "kuramoto_4")
    		RUN_SIMUL(kuramoto_n<4>);
    	else if(coupling_type == "kuramoto_5")
    		RUN_SIMUL(kuramoto_n<5>);
    	else if(coupling_type == "kuramoto_6")
    		RUN_SIMUL(kuramoto_n<6>);
    	else if(coupling_type == "kuramoto_7")
    		RUN_SIMUL(kuramoto_n<7>);
    	else if(coupling_type == "kuramoto_8")
    		RUN_SIMUL(kuramoto_n<8>);
    	else if(coupling_type == "kuramoto_9")
    		RUN_SIMUL(kuramoto_n<9>);
    	else if(coupling_type == "kuramoto_10")
    		RUN_SIMUL(kuramoto_n<10>);
    	else if(coupling_type == "daido")
            RUN_SIMUL(daido_original);
        else if(coupling_type == "coupling_1")
            RUN_SIMUL(coupling_1);
        else if(coupling_type == "coupling_2")
            RUN_SIMUL(coupling_2);
        else if(coupling_type == "coupling_3")
            RUN_SIMUL(coupling_3);
        else if(coupling_type == "coupling_4")
            RUN_SIMUL(coupling_4);
        else
        {
            std::cerr << "Unknown coupling type: " << coupling_type << std::endl;
            return EXIT_FAILURE;
        }
    }
    catch(std::exception& e)
    {
        std::cerr << "Unhandled Exception reached the top of main: "
                  << e.what() << ", application will now exit." << std::endl;
        return EXIT_FAILURE;
    }

    return EXIT_SUCCESS;
}

max_stars_repo_name: mroja/kuramoto

max_issues_repo_name: mroja/kuramoto

max_forks_repo_name: mroja/kuramoto


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)
 *
 * Copyright (c) 2014 Andrey Semashev
 */
/*!
 * \file   atomic/detail/operations.hpp
 *
 * This header defines atomic operations, including the emulated version.
 */

#ifndef BOOST_ATOMIC_DETAIL_OPERATIONS_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_OPERATIONS_HPP_INCLUDED_

#include <boost_1_56_0/atomic/detail/operations_lockfree.hpp>
#include <boost_1_56_0/atomic/detail/ops_emulated.hpp>

#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif

#endif // BOOST_ATOMIC_DETAIL_OPERATIONS_HPP_INCLUDED_


text:
#include <cctbx/boost_python/flex_fwd.h>

#include <boost/python/class.hpp>
#include <boost/python/def.hpp>
#include <boost/python/args.hpp>
#include <boost/python/return_value_policy.hpp>
#include <boost/python/return_by_value.hpp>
#include <cctbx/xray/minimization.h>

namespace cctbx { namespace xray { namespace boost_python {

  struct apply_shifts_wrappers
  {
    typedef minimization::apply_shifts<scatterer<>, double> w_t;

    static void
    wrap()
    {
      using namespace boost::python;
      typedef return_value_policy<return_by_value> rbv;
      class_<w_t>("minimization_apply_shifts", no_init)
        .def(init<
          uctbx::unit_cell const&,
          af::const_ref<scatterer<> > const&,
          af::const_ref<double> const& >((
            arg("unit_cell"),
            arg("scatterers"),
            arg("shifts"))))
        .add_property("shifted_scatterers",
          make_getter(&w_t::shifted_scatterers, rbv()))
        .add_property("u_iso_refinable_params",
          make_getter(&w_t::u_iso_refinable_params, rbv()))
      ;
    }
  };

  void wrap_minimization()
  {
    using namespace boost::python;

    def("damp_shifts",
      (void(*)(
        af::const_ref<double> const&,
        af::ref<double>,
        double const&)) minimization::damp_shifts, (
          arg("previous"),
          arg("current"),
          arg("max_value")));

    def("truncate_shifts",
      (void(*)(
        af::ref<double>,
        double const&,
        double const&)) minimization::truncate_shifts, (
          arg("shifts"),
          arg("min_value"),
          arg("max_value")));

    def("minimization_shift_scales",
      (af::shared<double>(*)(
        af::const_ref<scatterer<> > const&,
        std::size_t,
        double const&,
        double const&,
        double const&,
        double const&,
        double const&,
        double const&)) minimization::shift_scales, (
          arg("scatterers"),
          arg("n_parameters"),
          arg("site_cart"),
          arg("u_iso"),
          arg("u_cart"),
          arg("occupancy"),
          arg("fp"),
          arg("fdp")));

    apply_shifts_wrappers::wrap();

    def("minimization_add_gradients",
      (void(*)(
        af::const_ref<scatterer<> > const&,
        af::ref<double> const&,
        af::const_ref<scitbx::vec3<double> > const&,
        af::const_ref<double> const&,
        af::const_ref<scitbx::sym_mat3<double> > const&,
        af::const_ref<double> const&))
          minimization::add_gradients, (
      arg("scatterers"),
      arg("xray_gradients"),
      arg("site_gradients"),
      arg("u_iso_gradients"),
      arg("u_aniso_gradients"),
      arg("occupancy_gradients")));
    def("minimization_extract_site_gradients",
      (af::shared<scitbx::vec3<double> >(*)(
        af::const_ref<scatterer<> > const&,
        af::const_ref<double> const&))
          minimization::extract_site_gradients, (
      arg("scatterers"),
      arg("xray_gradients")));
  }

}}} // namespace cctbx::xray::boost_python


text:
///////////////////////////////////////////////////////////////////////////////
/// \file boyer_moore.hpp
///   Contains the boyer-moore implementation. Note: this is *not* a general-
///   purpose boyer-moore implementation. It truncates the search string at
///   256 characters, but it is sufficient for the needs of xpressive.
//
//  Copyright 2007 Eric Niebler. Distributed under the Boost
//  Software License, Version 1.0. (See accompanying file
//  LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)

#ifndef BOOST_XPRESSIVE_DETAIL_BOYER_MOORE_HPP_EAN_10_04_2005
#define BOOST_XPRESSIVE_DETAIL_BOYER_MOORE_HPP_EAN_10_04_2005

// MS compatible compilers support #pragma once
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma once
# pragma warning(push)
# pragma warning(disable : 4100) // unreferenced formal parameter
#endif

#include <climits>  // for UCHAR_MAX
#include <cstddef>  // for std::ptrdiff_t
#include <utility>  // for std::max
#include <vector>
#include <boost/mpl/bool.hpp>
#include <boost/noncopyable.hpp>
#include <boost/iterator/iterator_traits.hpp>
#include <boost/type_traits/is_convertible.hpp>
#include <boost/xpressive/detail/detail_fwd.hpp>

namespace boost { namespace xpressive { namespace detail
{

///////////////////////////////////////////////////////////////////////////////
// boyer_moore
//
template<typename BidiIter, typename Traits>
struct boyer_moore
  : noncopyable
{
    typedef typename iterator_value<BidiIter>::type char_type;
    typedef Traits traits_type;
    typedef has_fold_case<Traits> case_fold;
    typedef typename Traits::string_type string_type;

    // initialize the Boyer-Moore search data structure, using the
    // search sub-sequence to prime the pump.
    boyer_moore(char_type const *begin, char_type const *end, Traits const &traits, bool icase)
      : begin_(begin)
      , last_(begin)
      , fold_()
      , find_fun_(
              icase
            ? (case_fold() ? &boyer_moore::find_nocase_fold_ : &boyer_moore::find_nocase_)
            : &boyer_moore::find_
        )
    {
        std::ptrdiff_t const uchar_max = UCHAR_MAX;
        std::ptrdiff_t diff = std::distance(begin, end);
        this->length_  = static_cast<unsigned char>((std::min)(diff, uchar_max));
        std::fill_n(static_cast<unsigned char *>(this->offsets_), uchar_max + 1, this->length_);
        --this->length_;

        icase ? this->init_(traits, case_fold()) : this->init_(traits, mpl::false_());
    }

    BidiIter find(BidiIter begin, BidiIter end, Traits const &traits) const
    {
        return (this->*this->find_fun_)(begin, end, traits);
    }

private:

    void init_(Traits const &traits, mpl::false_)
    {
        for(unsigned char offset = this->length_; offset; --offset, ++this->last_)
        {
            this->offsets_[traits.hash(*this->last_)] = offset;
        }
    }

    void init_(Traits const &traits, mpl::true_)
    {
        this->fold_.reserve(this->length_ + 1);
        for(unsigned char offset = this->length_; offset; --offset, ++this->last_)
        {
            this->fold_.push_back(traits.fold_case(*this->last_));
            for(typename string_type::const_iterator beg = this->fold_.back().begin(), end = this->fold_.back().end();
                beg != end; ++beg)
            {
                this->offsets_[traits.hash(*beg)] = offset;
            }
        }
        this->fold_.push_back(traits.fold_case(*this->last_));
    }

    // case-sensitive Boyer-Moore search
    BidiIter find_(BidiIter begin, BidiIter end, Traits const &traits) const
    {
        typedef typename boost::iterator_difference<BidiIter>::type diff_type;
        diff_type const endpos = std::distance(begin, end);
        diff_type offset = static_cast<diff_type>(this->length_);

        for(diff_type curpos = offset; curpos < endpos; curpos += offset)
        {
            std::advance(begin, offset);

            char_type const *pat_tmp = this->last_;
            BidiIter str_tmp = begin;

            for(; traits.translate(*str_tmp) == *pat_tmp; --pat_tmp, --str_tmp)
            {
                if(pat_tmp == this->begin_)
                {
                    return str_tmp;
                }
            }

            offset = this->offsets_[traits.hash(traits.translate(*begin))];
        }

        return end;
    }

    // case-insensitive Boyer-Moore search
    BidiIter find_nocase_(BidiIter begin, BidiIter end, Traits const &traits) const
    {
        typedef typename boost::iterator_difference<BidiIter>::type diff_type;
        diff_type const endpos = std::distance(begin, end);
        diff_type offset = static_cast<diff_type>(this->length_);

        for(diff_type curpos = offset; curpos < endpos; curpos += offset)
        {
            std::advance(begin, offset);

            char_type const *pat_tmp = this->last_;
            BidiIter str_tmp = begin;

            for(; traits.translate_nocase(*str_tmp) == *pat_tmp; --pat_tmp, --str_tmp)
            {
                if(pat_tmp == this->begin_)
                {
                    return str_tmp;
                }
            }

            offset = this->offsets_[traits.hash(traits.translate_nocase(*begin))];
        }

        return end;
    }

    // case-insensitive Boyer-Moore search with case-folding
    BidiIter find_nocase_fold_(BidiIter begin, BidiIter end, Traits const &traits) const
    {
        typedef typename boost::iterator_difference<BidiIter>::type diff_type;
        diff_type const endpos = std::distance(begin, end);
        diff_type offset = static_cast<diff_type>(this->length_);

        for(diff_type curpos = offset; curpos < endpos; curpos += offset)
        {
            std::advance(begin, offset);

            string_type const *pat_tmp = &this->fold_.back();
            BidiIter str_tmp = begin;

            for(; pat_tmp->end() != std::find(pat_tmp->begin(), pat_tmp->end(), *str_tmp);
                --pat_tmp, --str_tmp)
            {
                if(pat_tmp == &this->fold_.front())
                {
                    return str_tmp;
                }
            }

            offset = this->offsets_[traits.hash(*begin)];
        }

        return end;
    }

private:

    char_type const *begin_;
    char_type const *last_;
    std::vector<string_type> fold_;
    BidiIter (boyer_moore::*const find_fun_)(BidiIter, BidiIter, Traits const &) const;
    unsigned char length_;
    unsigned char offsets_[UCHAR_MAX + 1];
};

}}} // namespace boost::xpressive::detail

#if defined(_MSC_VER) && (_MSC_VER >= 1020)
# pragma warning(pop)
#endif

#endif

max_stars_repo_name: foxostro/CheeseTesseract

max_issues_repo_name: foxostro/CheeseTesseract

max_forks_repo_name: foxostro/CheeseTesseract


text:
// Copyright (c) 2013
// Nathanael Fillmore (University of Wisconsin-Madison)
// nathanae@cs.wisc.edu
//
// This file is part of REF-EVAL.
//
// REF-EVAL is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// REF-EVAL is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with REF-EVAL.  If not, see <http://www.gnu.org/licenses/>.

#pragma once
#include <set>
#include <vector>
#include <queue>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>

// Pairset concept:
//
// General notes:
// - All pairs are of the form (i,j) where i <= j.
// - In other words, the pairs (i,j) and (j,i) are considered equivalent and
//       are not counted twice.
// - "Pairs between (l,l) and (h,h)" means all pairs (i,j) such that i and j
//       are both in the interval [l,h] and i <= j.
//
// Interface:
// - Pairset(size_t top) - constructs a new pairset with possible pairs (0,0),
//       (0,1), and (top-1,top-1), inclusive.
//
// - size_t size() - returns how many pairs are in the pairset
//
// - void add_square_with_exceptions(size_t lo, size_t hi, ConstIterator
//       exceptions_begin, ConstIterator exceptions_end) - adds all pairs
//       between (lo,lo) and (hi,hi), except all pairs (i,x) or (x,i) such that
//       x is an exception and i is between lo and hi. Note that the iterators
//       are over exceptional coordinates, not pairs.

class brute_force_pairset
{
public:
  brute_force_pairset(size_t /*top*/) {}

  size_t size() { return set.size(); }

  template<typename ConstIterator>
  void add_square_with_exceptions(size_t lo, size_t hi, ConstIterator exceptions_begin, ConstIterator exceptions_end)
  {
    if (lo > hi)
      std::swap(lo, hi);

    std::set<std::pair<size_t,size_t> > exceptions;
    for (ConstIterator x = exceptions_begin; x != exceptions_end; ++x) {
      for (size_t i = lo; i <= hi; ++i) {
        if (*x <= i)
          exceptions.insert(std::make_pair(*x, i));
        else
          exceptions.insert(std::make_pair(i, *x));
      }
    }

    for (size_t i = lo; i <= hi; ++i)
      for (size_t j = i; j <= hi; ++j)
        if (exceptions.count(std::make_pair(i,j)) == 0)
          set.insert(std::make_pair(i,j));
  }

private:
  std::set<std::pair<size_t,size_t> > set;
};

class big_matrix_pairset
{
public:
  big_matrix_pairset(size_t top) : top(top), sz(0), data(top*top, false) {}

  size_t size() { return sz; }

  template<typename ConstIterator>
  void add_square_with_exceptions(size_t lo, size_t hi, ConstIterator exceptions_begin, ConstIterator exceptions_end)
  {
    if (lo > hi)
      std::swap(lo, hi);

    std::set<size_t> exceptions;
    for (ConstIterator x = exceptions_begin; x != exceptions_end; ++x)
      exceptions.insert(*x);

    for (size_t i = lo; i <= hi; ++i)
      for (size_t j = i; j <= hi; ++j)
        if (exceptions.count(i) == 0 && exceptions.count(j) == 0)
          assign(i, j, true);
  }

private:
  size_t top, sz;
  std::vector<bool> data;

  void assign(size_t x, size_t y, bool val)
  {
    if (x >= top)
      throw std::runtime_error("x = " + boost::lexical_cast<std::string>(x) + " is not in range [0, " + boost::lexical_cast<std::string>(top) + ").");
    if (y >= top)
      throw std::runtime_error("y = " + boost::lexical_cast<std::string>(y) + " is not in range [0, " + boost::lexical_cast<std::string>(top) + ").");

    bool old = data[x*top + y];
    if (!old && val)       // excluded -> included => increment size
      ++sz;
    else if (old && !val)  // included -> excluded => decrement size
      --sz;

    data[x*top + y] = val;
  }
};

namespace detail
{
  inline size_t choose_2(size_t n) { return n*(n-1)/2; }

  struct coord
  {
    size_t x, y;
    coord(size_t x, size_t y) : x(x), y(y) {}
  };

  struct rect
  {
    coord lo, hi;
    rect(coord lo, coord hi) : lo(lo), hi(hi) {}
  };
}

namespace std
{
  template<>
  struct less<detail::coord>
  {
    bool operator()(const detail::coord& a,
                    const detail::coord& b) const
    {
      return (a.x < b.x) || (a.x == b.x && a.y < b.y);
    }
  };

  template<>
  struct less<detail::rect>
  {
    bool operator()(const detail::rect& a,
                    const detail::rect& b) const
    {
      return (a.lo.x <  b.lo.x)
          || (a.lo.x == b.lo.x && a.lo.y <  b.lo.y)
          || (a.lo.x == b.lo.x && a.lo.y == b.lo.y && a.hi.x <  b.hi.x)
          || (a.lo.x == b.lo.x && a.lo.y == b.lo.y && a.hi.x == b.hi.x && a.hi.y < b.hi.y);
    }
  };
}

class smart_pairset
{
public:
  smart_pairset(size_t /*top*/) {}

  size_t size() const
  {
    // Make a copy of the squares so that we can modify it.
    std::list<detail::rect> rects(squares.begin(), squares.end());

    // Remove any squares that are completely contained inside another one.
    std::list<detail::rect>::iterator A, B, end = rects.end();
    for (A = rects.begin(); A != end; ) {
      bool did_erase = false;
      for (B = rects.begin(); B != end; ++B) {
        if (A != B && B->lo.x <= A->lo.x && A->hi.x <= B->hi.x) { // B contains A
          assert(B->lo.y <= A->lo.y && A->hi.y <= B->hi.y);
          rects.erase(A++);
          did_erase = true;
          break;
        }
      }
      if (!did_erase)
        ++A;
    }

    // We now know that if square B starts before square A starts, then B ends
    // before A ends too. (This holds because all squares are on the diagonal
    // and none is contained inside another.)

    // Go from left to right, and if a square overlaps a predecessor, chop it
    // off on the left, so that they no longer overlap. (Remember that pair
    // (i,j) is equivalent to (j,i), so we don't have to worry about what
    // happens "above the diagonal".) We can go from left to right by just
    // iterating over rects, because the sorting criterion says that "B < A"
    // if, first of all, B starts to the left of where A starts.
    for (A = rects.begin(); A != end; ++A) {
      for (B = rects.begin(); B != A; ++B) { // iterate over all B such that B starts before A
        if (A->lo.x <= B->hi.x) {            // - if they overlap, i.e., B ends after (or =) A starts
          A->lo.x = B->hi.x + 1;             //   - truncate A so they don't overlap
          assert(A->lo.x <= A->hi.x);
        }
      }
    }

    // Count how many pairs each rectangle contributes. On the "diagonal
    // square" of the rectangle, it contributes (n+1) choose 2 pairs, where n
    // is the side length of the diagonal square. On the rest of the rectangle,
    // it contributes n*m pairs, where n and m are the side lengths of the rest
    // of the rectangle.
    size_t sz = 0;
    for (A = rects.begin(); A != end; ++A) {
      size_t diagonal_side_length = A->hi.x - A->lo.x + 1;
      size_t remainder_side_length_1 = A->lo.x - A->lo.y;
      size_t remainder_side_length_2 = diagonal_side_length;
      sz += detail::choose_2(diagonal_side_length+1) + remainder_side_length_1*remainder_side_length_2;
    }

    // Subtract the exceptions
    sz -= excepted_pairs.size();

    return sz;
  }

  template<typename ConstIterator>
  void add_square_with_exceptions(size_t lo, size_t hi, ConstIterator exceptions_begin, ConstIterator exceptions_end)
  {
    if (lo > hi)
      std::swap(lo, hi);

    // First make a set of the new exceptions for easy lookup.
    std::set<size_t> exceptions;
    for (ConstIterator x = exceptions_begin; x != exceptions_end; ++x)
      exceptions.insert(*x);

    // Remove any exceptions (x,y) from the main list (i.e., existing, "old"
    // exceptions) that are covered by the new square and are not new
    // exceptions.
    for (std::set<detail::coord>::const_iterator it = excepted_pairs.begin(), end = excepted_pairs.end(); it != end;) {
      if (lo <= it->x && it->x <= hi &&     // (x,y) is in the new square,
          lo <= it->y && it->y <= hi &&     // and
          exceptions.count(it->x) == 0 &&   // (x,y) is not a new exception
          exceptions.count(it->y) == 0) {
        excepted_pairs.erase(it++);
      } else {
        ++it;
      }
    }

    // Add any new exceptions that are not covered by an old square to the main
    // list. Skip old exceptions, since no change would be made by adding them
    // again.
    for (ConstIterator i = exceptions_begin; i != exceptions_end; ++i) {
      for (size_t j = lo; j <= hi; ++j) {
        size_t x, y;
        if (*i <= j) {
          x = *i;
          y =  j;
        } else {
          x =  j;
          y = *i;
        }
        if (excepted_pairs.count(detail::coord(x, y))) // already an exception
          continue;
        else {
          // check if the exception is covered by some square
          bool is_covered = false;
          BOOST_FOREACH(const detail::rect& sq, squares) {
            if (sq.lo.x <= x && x <= sq.hi.x &&
                sq.lo.y <= y && y <= sq.hi.y) {
              is_covered = true;
              break;
            }
          }
          // if not, then the exception is truly an exception, so add it
          if (!is_covered)
            excepted_pairs.insert(detail::coord(x, y));
        }
      }
    }

    // Add the square itself. The square may overlap with existing squares.
    squares.insert(detail::rect(detail::coord(lo, lo), detail::coord(hi, hi)));
  }

private:
  std::set<detail::rect> squares;
  std::set<detail::coord> excepted_pairs;
};

ext: hh

max_stars_repo_name: fmaguire/BayeHem

max_issues_repo_name: fmaguire/BayeHem

max_forks_repo_name: fmaguire/BayeHem


text:
/*
 * Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
 *
 * This file is part of Orfeo Toolbox
 *
 *     https://www.orfeo-toolbox.org/
 *
 * 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 otbOGRFeatureWrapper_hxx
#define otbOGRFeatureWrapper_hxx

/*===========================================================================*/
/*===============================[ Includes ]================================*/
/*===========================================================================*/
#include "otbOGRFeatureWrapper.h"
#include <cassert>
#include <boost/version.hpp>
#if BOOST_VERSION >= 104800
#   include <boost/move/move.hpp> // since 1.48
#else
#   include <boost/interprocess/detail/move.hpp>
#endif

namespace otb
{
#if BOOST_VERSION >= 104800
using boost::move;
#else
using boost::interprocess::move;
#endif
}

/*===========================================================================*/
/*================================[ Feature ]================================*/
/*===========================================================================*/
inline
void otb::ogr::Feature::CheckInvariants() const
{
  assert(m_Feature && "OGRFeature can't be null");
}

inline
otb::ogr::Feature otb::ogr::Feature::Clone() const
{
  CheckInvariants();
  return UncheckedClone();
}

inline
void otb::ogr::Feature::SetFrom(Feature const& rhs, bool mustForgive)
{
  CheckInvariants();
  UncheckedSetFrom(rhs, mustForgive);
}

inline
void otb::ogr::Feature::SetFrom(Feature const& rhs, int * map, bool mustForgive)
{
  CheckInvariants();
  UncheckedSetFrom(rhs, map, mustForgive);
}

/*===========================================================================*/
/*================================[ Fields ]=================================*/
/*===========================================================================*/
inline
otb::ogr::Field otb::ogr::Feature::operator[](int index)
{
  assert(index < GetSize() && "out of range field-index."); // also calls CheckInvariants();
  return UncheckedGetElement(index);
}

inline
otb::ogr::Field const otb::ogr::Feature::operator[](int index) const
{
  return const_cast<Feature*>(this)->operator[](index);
}

inline
otb::ogr::Field otb::ogr::Feature::operator[](std::string const& name)
{
  CheckInvariants();
  return UncheckedGetElement(name);
}

inline
otb::ogr::Field const otb::ogr::Feature::operator[](std::string const& name) const
{
  return const_cast<Feature*>(this)->operator[](name);
}

inline
otb::ogr::FieldDefn otb::ogr::Feature::GetFieldDefn(int index) const
{
  assert(index < GetSize() && "out of range field-index."); // also calls CheckInvariants();
  return UncheckedGetFieldDefn(index);
}

inline
otb::ogr::FieldDefn otb::ogr::Feature::GetFieldDefn(std::string const& name) const
{
  CheckInvariants();
  return UncheckedGetFieldDefn(name);
}

inline
int otb::ogr::Feature::GetFieldIndex(std::string const& name) const
{
  CheckInvariants();
  return UncheckedGetFieldIndex(name);
}

/*===========================================================================*/
/*==============================[ Properties ]===============================*/
/*===========================================================================*/
inline
long otb::ogr::Feature::GetFID() const
{
  CheckInvariants();
  return UncheckedGetFID();
}

inline
void otb::ogr::Feature::SetFID(long fid)
{
  CheckInvariants();
  UncheckedSetFID(fid);
}

inline
OGRFeatureDefn&  otb::ogr::Feature::GetDefn() const
{
  CheckInvariants();
  return UncheckedGetDefn();
}

/*===========================================================================*/
/*==============================[ Geometries ]===============================*/
/*===========================================================================*/
inline
void otb::ogr::Feature::SetGeometryDirectly(UniqueGeometryPtr geometry)
{
  CheckInvariants();
#if !defined(NDEBUG)
  OGRGeometry * g = geometry.get();
#endif
  UncheckedSetGeometryDirectly(otb::move(geometry));
  assert((m_Feature->GetGeometryRef() == g) && "The new geometry hasn't been set as expected");
  assert(!geometry && "UniqueGeometryPtr hasn't released its pointer");
}

inline
otb::ogr::UniqueGeometryPtr otb::ogr::Feature::StealGeometry()
{
  CheckInvariants();
  UniqueGeometryPtr res = UncheckedStealGeometry();
  itkAssertOrThrowMacro(!m_Feature->GetGeometryRef(), "Geometry hasn't been properly stolen");
  return otb::move(res);
}

inline
void otb::ogr::Feature::SetGeometry(OGRGeometry const* geometry)
{
  CheckInvariants();
  UncheckedSetGeometry(geometry);
}

inline
OGRGeometry const* otb::ogr::Feature::GetGeometry() const
{
  CheckInvariants();
  return UncheckedGetGeometry();
}

/*===========================================================================*/
/*=================================[ Misc ]==================================*/
/*===========================================================================*/
inline
OGRFeature & otb::ogr::Feature::ogr() const
{ // not returning a OGRFeature const& because OGR is not const-correct
  CheckInvariants();
  return *m_Feature;
}

inline
OGRFeature & otb::ogr::Feature::ogr()
{
  CheckInvariants();
  return *m_Feature;
}

inline
void otb::ogr::Feature::PrintSelf(std::ostream & os, itk::Indent indent) const
{
  CheckInvariants();
  UncheckedPrintSelf(os, indent);
}

#endif // otbOGRFeatureWrapper_hxx

ext: hxx

max_stars_repo_name: xcorail/OTB

max_issues_repo_name: xcorail/OTB

max_forks_repo_name: xcorail/OTB


text:
// Copyright 2020 <LinkIvan333>

#pragma once
#include <iostream>
#include <string>
#include <random>
#include <utility>
#include <thread>
#include <boost/filesystem.hpp>
#include <boost/log/trivial.hpp>
#include <boost/unordered_map.hpp>
#include <rocksdb/db.h>
#include <rocksdb/slice.h>
#include <rocksdb/options.h>
#include <boost/thread.hpp>
#include <boost/program_options.hpp>
#include <mutex>
#include <vector>
#include <list>
#include <picosha2.hpp>
#include <constants.hpp>

using FContainer =
        std::list<std::unique_ptr<rocksdb::ColumnFamilyHandle>>;
using FDescriptorContainer =
        std::vector<rocksdb::ColumnFamilyDescriptor>;
using FHandlerContainer =
        std::list<std::unique_ptr<rocksdb::ColumnFamilyHandle>>;
using StrContainer = boost::unordered_map<std::string, std::string>;
namespace po = boost::program_options;

class DBHashCreator {
public:
    DBHashCreator(std::string &new_path, std::string &path,
            std::size_t &threadCount,
            int logLVL) :
            _new_path(new_path),
            _path(path),
            _logLVL(logLVL),  _threadCountHash(threadCount){
      options.create_if_missing = true;
      startThreads();
    }

    FDescriptorContainer getFamilyDescriptors();

    FHandlerContainer openDB(const FDescriptorContainer &);

    StrContainer getStrs(rocksdb::ColumnFamilyHandle *);

    void getHash(rocksdb::ColumnFamilyHandle *, StrContainer);

    void startHash(FHandlerContainer *, std::list<StrContainer> *);

    void startThreads();

private:
    rocksdb::Options options;
    std::string _new_path;
    std::string _path;
    int _logLVL;
    std::unique_ptr<rocksdb::DB> _db, _new_db;
    std::size_t _threadCountHash;
    std::recursive_mutex _mutex;
};