<commit_before>#include "narf/console.h"
#include "narf/path.h"

#if defined(__unix__) || defined(__APPLE__)
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#endif

#ifdef _MSC_VER
#include <direct.h>
#endif

#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

#ifdef _WIN32

#include <windows.h>
#include <direct.h>
#include <shlobj.h>
#include "narf/utf.h"

const std::string narf::util::DirSeparator("\\");
#else
const std::string narf::util::DirSeparator("/");
#endif

#ifdef linux

static std::string readLink(const std::string &path) {
	size_t len = 1024;
	size_t lenStep = 1024;
	size_t maxLen = 1024 * 4096;

	do {
		char *buf = new char[len + 1];
		if (!buf) {
			return std::string("");
		}

		auto bytes = readlink(path.c_str(), buf, len + 1);
		if (bytes < 0) {
			return std::string("");
		}

		if (static_cast<size_t>(bytes) > len) {
			// try again with larger buffer
			len += lenStep;
			delete [] buf;
		} else {
			buf[bytes] = '\0';
			auto s = std::string(buf);
			delete [] buf;
			return s;
		}
	} while (len <= maxLen);

	return std::string("");
}

std::string narf::util::exeName() {
	return readLink("/proc/self/exe");
}

#endif // linux

#if defined(__unix__) && !defined(linux)
std::string narf::util::exeName() {
	return "";
}
#endif // unix && !linux

#if defined(__unix__) || defined(__APPLE__)

bool narf::util::dirExists(const std::string& path) {
	struct stat st;
	if (stat(path.c_str(), &st) == -1) {
		return false;
	}
	return (st.st_mode & S_IFMT) == S_IFDIR;
}

#endif // unix

#ifdef _WIN32

std::string narf::util::exeName() {
	const DWORD len = 32768; // max NT-style name length + terminator
	wchar_t buffer[len];

	DWORD ret = GetModuleFileNameW(NULL, buffer, len);
	if (ret == 0 || ret >= len) {
		return ""; // error
	}

	std::string result;
	narf::toUTF8(buffer, result);
	return result;
}

bool narf::util::dirExists(const std::string& path) {
	std::wstring pathW;
	narf::toUTF16(path, pathW);
	DWORD attrs = GetFileAttributesW(pathW.c_str());
	return (attrs != INVALID_FILE_ATTRIBUTES) && (attrs & FILE_ATTRIBUTE_DIRECTORY);
}

std::string narf::util::dirName(const std::string& path) {
	char* s = new char[path.size() + 1];
	std::strcpy(s, path.c_str());
	PathRemoveFileSpec(s);
	return std::string(s);
}

#endif // _WIN32

#ifdef __APPLE__

std::string narf::util::exeName() {
	char buffer[32768];
	uint32_t len = sizeof(buffer);

	if (_NSGetExecutablePath(buffer, &len) == 0) {
		return std::string(buffer);
	}

	return ""; // error
}

#endif // __APPLE__

std::string narf::util::exeDir() {
	return dirName(exeName());
}

std::string narf::util::appendPath(const std::string& path, const std::string& append) {
	if (path.back() == DirSeparator[0]) {
		return path + append;
	} else {
		return path + DirSeparator + append;
	}
}

bool narf::util::createDir(const std::string& path) {
#ifdef _MSC_VER
	std::wstring pathW;
	narf::toUTF16(path, pathW);
	return _wmkdir(pathW.c_str()) == 0;
#else
	return mkdir(path.c_str(), 0755) == 0;
#endif
}

bool narf::util::createDirs(const std::string& path) {
	if (isDir(path)) {
		return true; // We're already a directory
	}
	if (!createDirs(dirName(path))) {
		return false; // Failed to create one of the parent directories
	}
	return createDir(path);
}

bool narf::util::exists(const std::string& path) {
	struct stat st;
	return (stat(path.c_str(), &st) == 0);
}

void narf::util::rename(const std::string& path, const std::string& newPath) {
	::rename(path.c_str(), newPath.c_str());
}

bool narf::util::isDir(const std::string& path) {
	struct stat st;
	if (stat(path.c_str(), &st) != 0) {
		return false;
	}
	return S_ISDIR(st.st_mode);
}

// TODO: These will be broken on Windows when given the root directory
std::string narf::util::dirName(const std::string& path) {
	size_t len = path.length();
	while (len > 0 && path[len - 1] == DirSeparator[0]) {
		len--;
	}
	auto lastSlash = path.rfind(narf::util::DirSeparator, len - 1);
	if (lastSlash != std::string::npos) {
		return path.substr(0, lastSlash == 0 ? 1 : lastSlash);
	}
	return path;
}

std::string narf::util::baseName(const std::string& path) {
	size_t len = path.length();
	while (len > 0 && path[len - 1] == DirSeparator[0]) {
		len--;
	}
	size_t lastSlash = path.rfind(DirSeparator, len - 1);
	if (len > 1 && lastSlash != std::string::npos) {
		return path.substr(lastSlash + 1, len - lastSlash - 1);
	}
	return path;
}
<commit_msg>Hopefully this should fix the Windows build finally.<commit_after>#include "narf/console.h"
#include "narf/path.h"

#include <sys/types.h>
#include <sys/stat.h>

#if defined(__unix__) || defined(__APPLE__)
#include <unistd.h>
#include <stdlib.h>
#endif

#ifdef __APPLE__
#include <mach-o/dyld.h>
#endif

#ifdef _WIN32

#include <windows.h>
#include <direct.h>
#include <shlobj.h>
#include "narf/utf.h"

#define S_ISDIR(mode)  (((mode) & S_IFMT) == S_IFDIR)

const std::string narf::util::DirSeparator("\\");
#else
const std::string narf::util::DirSeparator("/");
#endif

#ifdef linux

static std::string readLink(const std::string &path) {
	size_t len = 1024;
	size_t lenStep = 1024;
	size_t maxLen = 1024 * 4096;

	do {
		char *buf = new char[len + 1];
		if (!buf) {
			return std::string("");
		}

		auto bytes = readlink(path.c_str(), buf, len + 1);
		if (bytes < 0) {
			return std::string("");
		}

		if (static_cast<size_t>(bytes) > len) {
			// try again with larger buffer
			len += lenStep;
			delete [] buf;
		} else {
			buf[bytes] = '\0';
			auto s = std::string(buf);
			delete [] buf;
			return s;
		}
	} while (len <= maxLen);

	return std::string("");
}

std::string narf::util::exeName() {
	return readLink("/proc/self/exe");
}

#endif // linux

#if defined(__unix__) && !defined(linux)
std::string narf::util::exeName() {
	return "";
}
#endif // unix && !linux

#if defined(__unix__) || defined(__APPLE__)

bool narf::util::dirExists(const std::string& path) {
	struct stat st;
	if (stat(path.c_str(), &st) == -1) {
		return false;
	}
	return (st.st_mode & S_IFMT) == S_IFDIR;
}

#endif // unix

#ifdef _WIN32

std::string narf::util::exeName() {
	const DWORD len = 32768; // max NT-style name length + terminator
	wchar_t buffer[len];

	DWORD ret = GetModuleFileNameW(NULL, buffer, len);
	if (ret == 0 || ret >= len) {
		return ""; // error
	}

	std::string result;
	narf::toUTF8(buffer, result);
	return result;
}

bool narf::util::dirExists(const std::string& path) {
	std::wstring pathW;
	narf::toUTF16(path, pathW);
	DWORD attrs = GetFileAttributesW(pathW.c_str());
	return (attrs != INVALID_FILE_ATTRIBUTES) && (attrs & FILE_ATTRIBUTE_DIRECTORY);
}

#endif // _WIN32

#ifdef __APPLE__

std::string narf::util::exeName() {
	char buffer[32768];
	uint32_t len = sizeof(buffer);

	if (_NSGetExecutablePath(buffer, &len) == 0) {
		return std::string(buffer);
	}

	return ""; // error
}

#endif // __APPLE__

std::string narf::util::exeDir() {
	return dirName(exeName());
}

std::string narf::util::appendPath(const std::string& path, const std::string& append) {
	if (path.back() == DirSeparator[0]) {
		return path + append;
	} else {
		return path + DirSeparator + append;
	}
}

bool narf::util::createDir(const std::string& path) {
#ifdef _WIN32
	std::wstring pathW;
	narf::toUTF16(path, pathW);
	return _wmkdir(pathW.c_str()) == 0;
#else
	return mkdir(path.c_str(), 0755) == 0;
#endif
}

bool narf::util::createDirs(const std::string& path) {
	if (isDir(path)) {
		return true; // We're already a directory
	}
	if (!createDirs(dirName(path))) {
		return false; // Failed to create one of the parent directories
	}
	return createDir(path);
}

bool narf::util::exists(const std::string& path) {
	struct stat st;
	return (stat(path.c_str(), &st) == 0);
}

void narf::util::rename(const std::string& path, const std::string& newPath) {
	::rename(path.c_str(), newPath.c_str());
}

bool narf::util::isDir(const std::string& path) {
#ifdef _WIN32
	std::wstring pathW;
	narf::toUTF16(path, pathW);
	struct _stat st;
	if (_wstat(path.c_str(), &st) != 0) {
		return false;
	}
#else
	struct stat st;
	if (stat(path.c_str(), &st) != 0) {
		return false;
	}
#endif
	return S_ISDIR(st.st_mode);
}

// TODO: These will be broken on Windows when given the root directory
std::string narf::util::dirName(const std::string& path) {
	size_t len = path.length();
	while (len > 0 && path[len - 1] == DirSeparator[0]) {
		len--;
	}
	auto lastSlash = path.rfind(narf::util::DirSeparator, len - 1);
	if (lastSlash != std::string::npos) {
		return path.substr(0, lastSlash == 0 ? 1 : lastSlash);
	}
	return path;
}

std::string narf::util::baseName(const std::string& path) {
	size_t len = path.length();
	while (len > 0 && path[len - 1] == DirSeparator[0]) {
		len--;
	}
	size_t lastSlash = path.rfind(DirSeparator, len - 1);
	if (len > 1 && lastSlash != std::string::npos) {
		return path.substr(lastSlash + 1, len - lastSlash - 1);
	}
	return path;
}
<|endoftext|>


<commit_before><commit_msg>Bugfix: `class Material`: always initialize `openGL_textureID`.<commit_after><|endoftext|>


<commit_before><commit_msg>Bugfix: added missing `#include` line.<commit_after><|endoftext|>


<commit_before>/*
 * A node that produces creates string messages based on various
 * factors (events, velocity, etc.)
 *
 * Created by Christian Onuogu
 */

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/Odometry.h"
#include "move_base_msgs/MoveBaseActionGoal.h"
#include <math.h>

ros::Publisher T2S_pub;
std_msgs::String msg;
geometry_msgs::Twist velocity;
bool moving = false;
bool heardGoal = false;
double xPos;
double yPos;
double goalX;
double goalY;

/*
 * The cb function that turns received velocity into strings
 */
void cmd_vel_cb(const geometry_msgs::Twist::ConstPtr& vel)
{
        velocity = *vel;
	if(moving == false && velocity.linear.x > 0) {
		moving = true;
		ROS_INFO("Hello?");
		msg.data = "Started movement";
		T2S_pub.publish(msg);
	}
	else if(moving == true && velocity.linear.x == 0) {
		moving = false;
		ROS_INFO("Bye?");
		msg.data = "Stopped movement";
		T2S_pub.publish(msg);
	}
}

/*
 * The cb function that gets the position of the robot's goal
 */
void goal_cb(const move_base_msgs::MoveBaseActionGoal::ConstPtr& gl)
{
	move_base_msgs::MoveBaseActionGoal goal = *gl;
	goalX = goal.goal.target_pose.pose.position.x;
	goalY = goal.goal.target_pose.pose.position.y;
	heardGoal = true;
}

/*
 * The cb function that gets the position of the robot and
 * checks if it has reached its goal
 */
void pos_cb(const nav_msgs::Odometry::ConstPtr& odom)
{
	nav_msgs::Odometry odometer = *odom;
	xPos = odometer.pose.pose.position.x;
	yPos = odometer.pose.pose.position.y;
	if(heardGoal){
		if(fabs(xPos-goalX) < .5 && fabs(yPos-goalY) < .5) {
			ROS_INFO("Please");
			heardGoal = false;
			msg.data = "Destination reached";
			T2S_pub.publish(msg);
		}
	}
}

int main(int argc, char** argv) {
	ros::init(argc, argv, "listener");
	ros::NodeHandle n;

	T2S_pub = n.advertise<std_msgs::String>("T2S", 1000);
	ros::Subscriber sub = n.subscribe("/cmd_vel", 1, cmd_vel_cb );
	ros::Subscriber sub2 = n.subscribe("/move_base/goal", 1, goal_cb );
	ros::Subscriber sub3 = n.subscribe("/odom", 1, pos_cb );

	while(ros::ok()) {
		ros::spinOnce();
	}

	return 0;
}
<commit_msg>Removed debugging code<commit_after>/*
 * A node that produces creates string messages based on various
 * factors (events, velocity, etc.)
 *
 * Created by Christian Onuogu
 */

#include "ros/ros.h"
#include "std_msgs/String.h"
#include "geometry_msgs/Twist.h"
#include "nav_msgs/Odometry.h"
#include "move_base_msgs/MoveBaseActionGoal.h"
#include <math.h>

ros::Publisher T2S_pub;
std_msgs::String msg;
geometry_msgs::Twist velocity;
bool moving = false;
bool heardGoal = false;
double xPos;
double yPos;
double goalX;
double goalY;

/*
 * The cb function that turns received velocity into strings
 */
void cmd_vel_cb(const geometry_msgs::Twist::ConstPtr& vel)
{
        velocity = *vel;
	if(moving == false && velocity.linear.x > 0) {
		moving = true;
		msg.data = "Started movement";
		T2S_pub.publish(msg);
	}
	else if(moving == true && velocity.linear.x == 0) {
		moving = false;
		msg.data = "Stopped movement";
		T2S_pub.publish(msg);
	}
}

/*
 * The cb function that gets the position of the robot's goal
 */
void goal_cb(const move_base_msgs::MoveBaseActionGoal::ConstPtr& gl)
{
	move_base_msgs::MoveBaseActionGoal goal = *gl;
	goalX = goal.goal.target_pose.pose.position.x;
	goalY = goal.goal.target_pose.pose.position.y;
	heardGoal = true;
}

/*
 * The cb function that gets the position of the robot and
 * checks if it has reached its goal
 */
void pos_cb(const nav_msgs::Odometry::ConstPtr& odom)
{
	nav_msgs::Odometry odometer = *odom;
	xPos = odometer.pose.pose.position.x;
	yPos = odometer.pose.pose.position.y;
	if(heardGoal){
		if(fabs(xPos-goalX) < .5 && fabs(yPos-goalY) < .5) {
			heardGoal = false;
			msg.data = "Destination reached";
			T2S_pub.publish(msg);
		}
	}
}

int main(int argc, char** argv) {
	ros::init(argc, argv, "listener");
	ros::NodeHandle n;

	T2S_pub = n.advertise<std_msgs::String>("T2S", 1000);
	ros::Subscriber sub = n.subscribe("/cmd_vel", 1, cmd_vel_cb );
	ros::Subscriber sub2 = n.subscribe("/move_base/goal", 1, goal_cb );
	ros::Subscriber sub3 = n.subscribe("/odom", 1, pos_cb );

	while(ros::ok()) {
		ros::spinOnce();
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2009 Toni Gundogdu.
 *
 * This file is part of cclive.
 *
 * cclive 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.
 *
 * cclive 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
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "hosthandler.h"
#include "curl.h"

LiveleakHandler::LiveleakHandler()
    : HostHandler()
{
    props.setHost   ("lleak");
    props.setDomain ("liveleak.com");
    props.setFormats("flv");
}

void
LiveleakHandler::parseId() {
    std::string id;
    partialMatch("(?i)token=(.*?)'", &id);
    props.setId(id);
}

void
LiveleakHandler::parseTitle() {
    std::string title;
    partialMatch("(?i)<title>(.*?)</", &title);
    Util::subStrReplace(title, "LiveLeak.com - ", "");
    props.setTitle(title);
}

void
LiveleakHandler::parseLink() {

    std::string confPath;
    partialMatch("(?i)'config','(.*?)'", &confPath);
    curlmgr.unescape(confPath);

    const std::string config =
        curlmgr.fetchToMem(confPath, "config");

    std::string plPath;
    partialMatch("(?i)<file>(.*?)</", &plPath, config);
    curlmgr.unescape(plPath);

    const std::string playlist =
        curlmgr.fetchToMem(plPath, "playlist");

    std::string lnk;
    partialMatch("(?i)<location>(.*?)</", &lnk, playlist);
    props.setLink(lnk);
}

<commit_msg>hostid lleak -> liveleak.<commit_after>/*
 * Copyright (C) 2009 Toni Gundogdu.
 *
 * This file is part of cclive.
 *
 * cclive 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.
 *
 * cclive 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
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "hosthandler.h"
#include "curl.h"

LiveleakHandler::LiveleakHandler()
    : HostHandler()
{
    props.setHost   ("liveleak");
    props.setDomain ("liveleak.com");
    props.setFormats("flv");
}

void
LiveleakHandler::parseId() {
    std::string id;
    partialMatch("(?i)token=(.*?)'", &id);
    props.setId(id);
}

void
LiveleakHandler::parseTitle() {
    std::string title;
    partialMatch("(?i)<title>(.*?)</", &title);
    Util::subStrReplace(title, "LiveLeak.com - ", "");
    props.setTitle(title);
}

void
LiveleakHandler::parseLink() {

    std::string confPath;
    partialMatch("(?i)'config','(.*?)'", &confPath);
    curlmgr.unescape(confPath);

    const std::string config =
        curlmgr.fetchToMem(confPath, "config");

    std::string plPath;
    partialMatch("(?i)<file>(.*?)</", &plPath, config);
    curlmgr.unescape(plPath);

    const std::string playlist =
        curlmgr.fetchToMem(plPath, "playlist");

    std::string lnk;
    partialMatch("(?i)<location>(.*?)</", &lnk, playlist);
    props.setLink(lnk);
}

<|endoftext|>


<commit_before>#include <ros/ros.h>

#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/planning_scene/planning_scene.h>

#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>

#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>

#include <boost/program_options.hpp>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "playback");
  ros::NodeHandle node_handle;
  ros::AsyncSpinner spinner(1);
  spinner.start();

  sleep(20); // to let RVIZ come up

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");

  boost::program_options::variables_map vm;
  boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
  boost::program_options::store(po, vm);
  boost::program_options::notify(vm);

  if (vm.count("help") || argc == 1) // show help if no parameters passed
  {
    std::cout << desc << std::endl;
    return 1;
  }
  try
  {
    //connect to the DB
    std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
    size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
    moveit_warehouse::PlanningSceneStorage pss(host, port);

    ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);

    ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
    moveit_msgs::DisplayTrajectory display_trajectory;

    //ask the warehouse for the scene
    std::vector<std::string> ps_names;
    pss.getPlanningSceneNames( ps_names );
    ros::Publisher ps_pub = node_handle.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
    while(ps_pub.getNumSubscribers() < 1)
    {
      ros::WallDuration sleep_t(0.5);
      ROS_INFO("Not enough subscribers to \"%s\" topic... ", "planning_scene");
      sleep_t.sleep();
    }

    ROS_INFO("%d available scenes to display", (int)ps_names.size());

    std::vector<std::string>::iterator scene_it = ps_names.begin();
    for(; scene_it!=ps_names.end(); ++scene_it)
    {
      ROS_INFO("Retrieving scene %s", scene_it->c_str());
      moveit_warehouse::PlanningSceneWithMetadata pswm;
      pss.getPlanningScene(pswm, *scene_it);

      // visualize the scene_it
      ROS_INFO("Publishing scene...");
      ps_pub.publish(static_cast<const moveit_msgs::PlanningScene&>(*pswm));

      moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);

      // get query list
      std::vector<std::string> pq_names;
      pss.getPlanningQueriesNames( pq_names, *scene_it);

      ROS_INFO("%d available queries to display", (int)pq_names.size());
      std::string first_query = pq_names.at(0);

      //get trajectory list
      std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
      pss.getPlanningResults(planning_results, *scene_it, first_query);

      ROS_INFO("Loaded %d trajectories for query %s", (int)planning_results.size(), first_query.c_str());

      // animate the first trajectory
      size_t ind = planning_results.size()-1;

      moveit_msgs::RobotTrajectory rt_msg;
      rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(*(planning_results[ind]));

          // trajectory_processing::IterativeParabolicTimeParameterization traj_retimer;
          // //make Robot Trajetory object
          // robot_trajectory::RobotTrajectory rt(planning_scene_->getRobotModel(), motion_plan_req.group_name);
          // moveit::core::RobotState rs(planning_scene_->getRobotModel());

          // //retime the trajectory
          // rs.setVariableValues(motion_plan_req.start_state.joint_state);
          // rt.setRobotTrajectoryMsg(rs, *traj_it);
          // bool success_retime = traj_retimer.computeTimeStamps(rt);
          // ROS_INFO("Retimed trajectory successfully: %s", success_retime ? "yes" : "no" );
          // rt.getRobotTrajectoryMsg(*traj_it);

      // get the start point
      moveit_warehouse::MotionPlanRequestWithMetadata planning_query;
      pss.getPlanningQuery(planning_query, *scene_it, first_query);
      moveit_msgs::MotionPlanRequest mpr = static_cast<const moveit_msgs::MotionPlanRequest&>(*planning_query);

      // publish
      if(1)
      {
        display_trajectory.trajectory_start = mpr.start_state;
        display_trajectory.trajectory.push_back(rt_msg);
        display_publisher.publish(display_trajectory);
        sleep(5.0);
      }
    }
  }
  catch(mongo_ros::DbConnectException &ex)
  {
    ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
        << std::endl << ex.what());
  }

  ros::spin();

  ROS_INFO("Successfully performed trajectory playback");
  ros::shutdown();
  return 0;
}
<commit_msg>added trajectory retiming support for visualizing trajectories<commit_after>#include <ros/ros.h>

#include <moveit/move_group_interface/move_group.h>
#include <moveit/planning_scene_interface/planning_scene_interface.h>
#include <moveit/planning_scene/planning_scene.h>

#include <moveit_msgs/DisplayRobotState.h>
#include <moveit_msgs/DisplayTrajectory.h>

#include <moveit/warehouse/planning_scene_storage.h>
#include <moveit/planning_scene_monitor/planning_scene_monitor.h>

#include <moveit/trajectory_processing/iterative_time_parameterization.h>

#include <boost/program_options.hpp>

int main(int argc, char** argv)
{
  ros::init(argc, argv, "playback");
  ros::NodeHandle node_handle;
  ros::AsyncSpinner spinner(1);
  spinner.start();

  sleep(20); // to let RVIZ come up

  boost::program_options::options_description desc;
  desc.add_options()
    ("help", "Show help message")
    ("host", boost::program_options::value<std::string>(), "Host for the MongoDB.")
    ("port", boost::program_options::value<std::size_t>(), "Port for the MongoDB.");

  boost::program_options::variables_map vm;
  boost::program_options::parsed_options po = boost::program_options::parse_command_line(argc, argv, desc);
  boost::program_options::store(po, vm);
  boost::program_options::notify(vm);

  if (vm.count("help") || argc == 1) // show help if no parameters passed
  {
    std::cout << desc << std::endl;
    return 1;
  }
  try
  {
    //connect to the DB
    std::string host = vm.count("host") ? vm["host"].as<std::string>() : "";
    size_t port = vm.count("port") ? vm["port"].as<std::size_t>() : 0;
    moveit_warehouse::PlanningSceneStorage pss(host, port);

    ROS_INFO("Connected to Warehouse DB at host (%s) and port (%d)", host.c_str(), (int)port);

    ros::Publisher display_publisher = node_handle.advertise<moveit_msgs::DisplayTrajectory>("/move_group/display_planned_path", 1, true);
    moveit_msgs::DisplayTrajectory display_trajectory;

    //ask the warehouse for the scene
    std::vector<std::string> ps_names;
    pss.getPlanningSceneNames( ps_names );
    ros::Publisher ps_pub = node_handle.advertise<moveit_msgs::PlanningScene>("planning_scene", 1);
    while(ps_pub.getNumSubscribers() < 1)
    {
      ros::WallDuration sleep_t(0.5);
      ROS_INFO("Not enough subscribers to \"%s\" topic... ", "planning_scene");
      sleep_t.sleep();
    }

    ROS_INFO("%d available scenes to display", (int)ps_names.size());

    std::vector<std::string>::iterator scene_it = ps_names.begin();
    for(; scene_it!=ps_names.end(); ++scene_it)
    {
      ROS_INFO("Retrieving scene %s", scene_it->c_str());
      moveit_warehouse::PlanningSceneWithMetadata pswm;
      pss.getPlanningScene(pswm, *scene_it);

      // visualize the scene
      ROS_INFO("Publishing scene...");
      moveit_msgs::PlanningScene ps_msg = static_cast<const moveit_msgs::PlanningScene&>(*pswm);
      ps_pub.publish(ps_msg);

      // get query
      std::vector<std::string> pq_names;
      pss.getPlanningQueriesNames( pq_names, *scene_it);

      ROS_INFO("%d available queries to display", (int)pq_names.size());
      std::string first_query = pq_names.at(0);
      moveit_warehouse::MotionPlanRequestWithMetadata mprwm;
      pss.getPlanningQuery(mprwm, *scene_it, first_query);
      moveit_msgs::MotionPlanRequest mpr_msg = static_cast<const moveit_msgs::MotionPlanRequest&>(*mprwm);

      //get trajectory list
      std::vector<moveit_warehouse::RobotTrajectoryWithMetadata> planning_results;
      pss.getPlanningResults(planning_results, *scene_it, first_query);

      ROS_INFO("Loaded %d trajectories for query %s", (int)planning_results.size(), first_query.c_str());

      // animate the first trajectory
      size_t ind = 0;

      moveit_msgs::RobotTrajectory rt_msg;
      rt_msg = static_cast<const moveit_msgs::RobotTrajectory&>(*(planning_results[ind]));

      // retime the trajectory
      trajectory_processing::IterativeParabolicTimeParameterization traj_retimer;
      planning_scene_monitor::PlanningSceneMonitor psm("robot_description");
      planning_scene::PlanningScenePtr ps = psm.getPlanningScene();
      ps->setPlanningSceneMsg( ps_msg );

      robot_trajectory::RobotTrajectory rt(ps->getRobotModel(), mpr_msg.group_name);
      moveit::core::RobotState rs(ps->getRobotModel());

      rs.setVariableValues(mpr_msg.start_state.joint_state); //ref state
      rt.setRobotTrajectoryMsg(rs, rt_msg);
      bool success_retime = traj_retimer.computeTimeStamps(rt);
      ROS_INFO("Retimed trajectory successfully: %s", success_retime ? "yes" : "no" );
      rt.getRobotTrajectoryMsg(rt_msg);

      // publish
      if(1)
      {
        display_trajectory.trajectory_start = mpr_msg.start_state;
        display_trajectory.trajectory.push_back(rt_msg);
        display_publisher.publish(display_trajectory);
        sleep(5.0);
      }
    }
  }
  catch(mongo_ros::DbConnectException &ex)
  {
    ROS_ERROR_STREAM("Unable to connect to warehouse. If you just created the database, it could take a while for initial setup. Please try to run the benchmark again."
        << std::endl << ex.what());
  }

  ros::spin();

  ROS_INFO("Successfully performed trajectory playback");
  ros::shutdown();
  return 0;
}
<|endoftext|>


<commit_before>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD (revised)
license as described in the file LICENSE.
 */
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "gd.h"

struct oaa{
  size_t k;
  vw* all; // for raw
  float*ret;
};

template <bool is_learn, bool print_all>
void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) {
  MULTICLASS::label_t mc_label_data = ec.l.multi;
  if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1))
    cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl;

  stringstream outputStringStream;
  uint32_t prediction = 1;

  ec.l.simple = {0.f, mc_label_data.weight, 0.f};
  float score = INT_MIN;
  for (uint32_t i = 1; i <= o.k; i++) {
    if (is_learn) {
      ec.l.simple.label = (mc_label_data.label == i) ? 1 : -1;
      base.learn(ec, i-1);
    } else
      base.predict(ec, i-1);

    if (ec.partial_prediction > score) {
      score = ec.partial_prediction;
      prediction = i;
    }

    if (print_all) {
      if (i > 1) outputStringStream << ' ';
      outputStringStream << i << ':' << ec.partial_prediction;
    }
  }

  ec.pred.multiclass = prediction;
  ec.l.multi = mc_label_data;

  if (print_all)
    o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag);
}

LEARNER::base_learner* oaa_setup(vw& all)
{
  if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels"))
    return NULL;

  oaa& data = calloc_or_die<oaa>();
  data.k = all.vm["oaa"].as<size_t>();
  data.all = &all;
  data.ret = (float*)malloc(sizeof(float)*data.k);

  LEARNER::learner<oaa>* l;
  if (all.raw_prediction > 0)
    l = &LEARNER::init_multiclass_learner(&data, setup_base(all), predict_or_learn<true, true>,
					  predict_or_learn<false, true>, all.p, data.k);
  else
    l = &LEARNER::init_multiclass_learner(&data, setup_base(all),predict_or_learn<true, false>,
					  predict_or_learn<false, false>, all.p, data.k);

  return make_base(*l);
}
<commit_msg>cleaned up oaa.cc<commit_after>/*
Copyright (c) by respective owners including Yahoo!, Microsoft, and
individual contributors. All rights reserved.  Released under a BSD (revised)
license as described in the file LICENSE.
 */
#include <sstream>
#include <float.h>
#include "reductions.h"
#include "gd.h"

struct oaa{
  size_t k;
  vw* all; // for raw
};

template <bool is_learn, bool print_all>
void predict_or_learn(oaa& o, LEARNER::base_learner& base, example& ec) {
  MULTICLASS::label_t mc_label_data = ec.l.multi;
  if (mc_label_data.label == 0 || (mc_label_data.label > o.k && mc_label_data.label != (uint32_t)-1))
    cout << "label " << mc_label_data.label << " is not in {1,"<< o.k << "} This won't work right." << endl;

  stringstream outputStringStream;
  uint32_t prediction = 1;

  ec.l.simple = {0.f, mc_label_data.weight, 0.f};
  float score = INT_MIN;
  for (uint32_t i = 1; i <= o.k; i++) {
    if (is_learn) {
      ec.l.simple.label = (mc_label_data.label == i) ? 1 : -1;
      base.learn(ec, i-1);
    } else
      base.predict(ec, i-1);

    if (ec.partial_prediction > score) {
      score = ec.partial_prediction;
      prediction = i;
    }

    if (print_all) {
      if (i > 1) outputStringStream << ' ';
      outputStringStream << i << ':' << ec.partial_prediction;
    }
  }

  ec.pred.multiclass = prediction;
  ec.l.multi = mc_label_data;

  if (print_all)
    o.all->print_text(o.all->raw_prediction, outputStringStream.str(), ec.tag);
}

LEARNER::base_learner* oaa_setup(vw& all)
{
  if (missing_option<size_t, true>(all, "oaa", "One-against-all multiclass with <k> labels"))
    return NULL;

  oaa& data = calloc_or_die<oaa>();
  data.k = all.vm["oaa"].as<size_t>();
  data.all = &all;

  LEARNER::learner<oaa>* l;
  if (all.raw_prediction > 0)
    l = &LEARNER::init_multiclass_learner(&data, setup_base(all), predict_or_learn<true, true>,
					  predict_or_learn<false, true>, all.p, data.k);
  else
    l = &LEARNER::init_multiclass_learner(&data, setup_base(all),predict_or_learn<true, false>,
					  predict_or_learn<false, false>, all.p, data.k);

  return make_base(*l);
}
<|endoftext|>


<commit_before>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <memory>
#include <utility>
// Linux headers
#include <libgen.h>
#include <signal.h>

#include "handler/feed_document_handler.h"
#include "handler/query_handler.h"
#include "handler/test_handler.h"
#include "index/document_index_manager.h"
#include "parser/document_parser.h"
#include "parser/feature_cache_parser.h"
#include "parser/query_request_parser.h"
#include "pipeline/feed_document_pipeline.h"
#include "query/simple_query_executor.h"
#include "ranking/default_model.h"
#include "ranking/feature_mapping_model.h"
#include "ranking/model_manager.h"
#include "ranking/ranking_model.h"
#include "service/server.h"
#include "third_party/rapidjson/document.h"
#include "third_party/rapidjson/filereadstream.h"
#include "utils/logger.h"
#include "utils/logger-inl.h"
#include "utils/scope_guard.h"

using std::string;

namespace redgiant {

DECLARE_LOGGER(logger, __FILE__);

static const unsigned int kParseFlags = rapidjson::kParseCommentsFlag | rapidjson::kParseTrailingCommasFlag;
static const char CONF_LOGGER_CONFIG  [] = "logger_config";
static const char CONF_FEATURES       [] = "feature_spaces";
static const char CONF_INDEX          [] = "index";
static const char CONF_RANKING        [] = "ranking";
static const char CONF_PIPELINE       [] = "pipeline";
static const char CONF_SERVER         [] = "server";

static volatile int g_exit_signal = 0;

static void new_handler_abort() {
  std::abort();
}

void ignore_signal(int signal) {
  (void) signal;
}

void exit_on_signal(int signal) {
  (void) signal;
  g_exit_signal = signal;
}

static int read_config_file(const char* file_name, rapidjson::Document& config) {
  std::FILE* fp = std::fopen(file_name, "r");
  if (!fp) {
    fprintf(stderr, "Cannot open config file %s.\n", file_name);
    return -1;
  }

  char readBuffer[8192];
  rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
  if (config.ParseStream<kParseFlags>(is).HasParseError()) {
    fprintf(stderr, "Config file parse error %d at offset %zu.\n",
        (int)config.GetParseError(), config.GetErrorOffset());
    return -1;
  }

  std::fclose(fp);
  return 0;
}

static int init_log_config(const char* file_name, const rapidjson::Value& config) {
  if (!config.HasMember(CONF_LOGGER_CONFIG) || !config[CONF_LOGGER_CONFIG].IsString()) {
    fprintf(stderr, "No log file configured!");
    return init_logger(NULL);
  }

  // Copy the file name to a temporary buffer to call "dirname"
  size_t file_name_len = strlen(file_name);
  std::unique_ptr<char[]> file_name_buf(new char[file_name_len + 1]);
  strncpy(file_name_buf.get(), file_name, file_name_len);
  file_name_buf[file_name_len] = 0;
  std::string dir = dirname(file_name_buf.get());
  if (dir.back() != '/') {
    dir += "/";
  }

  // get the file name relative to the configuration file.
  std::string logger_file_name = dir + config[CONF_LOGGER_CONFIG].GetString();
  return init_logger(logger_file_name.c_str());
}

static int server_main(rapidjson::Value& config) {
  /*
   * Initialize signal handler
   */
  signal(SIGPIPE, ignore_signal);
  signal(SIGHUP, ignore_signal);
  signal(SIGTERM, exit_on_signal);
  signal(SIGINT, exit_on_signal);

  /*
   * Initialization:
   * Features initialization
   */
  if (!config.HasMember(CONF_FEATURES)) {
    LOG_ERROR(logger, "features configuration does not exist!");
    return -1;
  }

  std::shared_ptr<FeatureCache> feature_cache = std::make_shared<FeatureCache>();
  FeatureCacheParser feature_cache_parser;
  if (feature_cache_parser.parse_json(config[CONF_FEATURES], *feature_cache) < 0) {
    LOG_ERROR(logger, "feature cache parsing failed!");
    return -1;
  }

  /*
   * Initialization:
   * Index initialization
   */
  int document_index_initial_buckets    = 100000;
  int document_index_max_size           = 5000000;
  int document_index_maintain_interval  = 300;

  if (config.HasMember(CONF_INDEX)) {
    auto& index_config = config[CONF_INDEX];
    if (index_config.HasMember("initial_buckets") && index_config["initial_buckets"].IsInt()) {
      document_index_initial_buckets = index_config["initial_buckets"].GetInt();
    }
    if (index_config.HasMember("max_size") && index_config["max_size"].IsInt()) {
      document_index_max_size = index_config["max_size"].GetInt();
    }
    if (index_config.HasMember("maintain_interval") && index_config["maintain_interval"].IsInt()) {
      document_index_maintain_interval = index_config["max_size"].GetInt();
    }
  }

  DocumentIndexManager document_index(document_index_initial_buckets, document_index_max_size);
  document_index.start_maintain(document_index_maintain_interval, document_index_maintain_interval);
  ScopeGuard feed_document_index_guard([&document_index] {
    LOG_INFO(logger, "document index maintain thread stopping...");
    document_index.stop_maintain();
  });

  size_t feed_document_thread_num = 4;
  size_t feed_document_queue_size = 2048;
  if (config.HasMember(CONF_PIPELINE)) {
    auto& pipeline_config = config[CONF_PIPELINE];
    if (pipeline_config.HasMember("thread_num") && pipeline_config["thread_num"].IsInt()) {
      feed_document_thread_num = pipeline_config["thread_num"].GetInt();
    }
    if (pipeline_config.HasMember("queue_size") && pipeline_config["queue_size"].IsInt()) {
      feed_document_queue_size = pipeline_config["queue_size"].GetInt();
    }
  }

  FeedDocumentPipeline feed_document(feed_document_thread_num, feed_document_queue_size, &document_index);
  feed_document.start();
  ScopeGuard feed_document_pipeline_guard([&feed_document] {
    LOG_INFO(logger, "feed document pipeline stopping...");
    feed_document.stop();
  });

  /*
   * Initialization
   * Query and ranking models
   */
  ModelManagerFactory model_manager_factory;
  model_manager_factory.register_model_factory(std::make_shared<DefaultModelFactory>());
  model_manager_factory.register_model_factory(std::make_shared<FeatureMappingModelFactory>(feature_cache));

  if (!config.HasMember(CONF_RANKING)) {
    LOG_ERROR(logger, "ranking model config does not exist!");
    return -1;
  }

  std::unique_ptr<RankingModel> model = model_manager_factory.create_model(config[CONF_RANKING]);
  if (!model) {
    LOG_ERROR(logger, "ranking model initialization failed!");
    return -1;
  }

  /*
   * Initialization:
   * Server initialization
   */
  LOG_INFO(logger, "server initializing ...");
  int server_port = 19980;
  size_t server_thread_num = 4;
  size_t max_req_per_thread = 0;
  if (config.HasMember(CONF_SERVER)) {
    auto& server_config = config[CONF_SERVER];
    if (server_config.HasMember("port") && server_config["port"].IsInt()) {
      server_port = server_config["port"].GetInt();
    }
    if (server_config.HasMember("thread_num") && server_config["thread_num"].IsInt()) {
      server_thread_num = server_config["thread_num"].GetInt();
    }
    if (server_config.HasMember("max_request_per_thread") && server_config["max_request_per_thread"].IsInt()) {
      max_req_per_thread = server_config["max_request_per_thread"].GetInt();
    }
  }

  Server test_server(server_port, server_thread_num, max_req_per_thread);
  test_server.bind("/test", std::make_shared<TestHandlerFactory>());
  test_server.bind("/document", std::make_shared<FeedDocumentHandlerFactory>(
      std::make_shared<DocumentParserFactory>(feature_cache),
      &feed_document, 0));
  test_server.bind("/query", std::make_shared<QueryHandlerFactory>(
      std::make_shared<QueryRequestParserFactory>(feature_cache),
      std::make_shared<SimpleQueryExecutorFactory>(&document_index, model.get())));

  if (test_server.initialize() < 0) {
    LOG_ERROR(logger, "test server initialization failed!");
    return -1;
  }

  ScopeGuard test_server_guard([&test_server] {
    LOG_INFO(logger, "test server exiting...");
    test_server.stop();
  });

  if (test_server.start() < 0) {
    LOG_ERROR(logger, "failed to start test server!");
    return -1;
  }

  LOG_INFO(logger, "test server stared.");

  /*
   * Main loop: wait for exit signal.
   */
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGINT);

  sigset_t orig_mask;
  sigprocmask(SIG_BLOCK, &mask, &orig_mask);
  g_exit_signal = 0;
  while (!g_exit_signal) {
    sigsuspend(&orig_mask);
  }

  /*
   * Exit: everything exits elegantly
   */
  LOG_INFO(logger, "received signal %d. exiting.", g_exit_signal);
  return 0;
}

int main(int argc, char** argv) {
  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);
  std::set_new_handler(new_handler_abort);

  if (argc != 2) {
    fprintf(stderr, "Usage: %s config_file\n", argv[0]);
    return -1;
  }

  rapidjson::Document config;
  if (read_config_file(argv[1], config) < 0) {
    fprintf(stderr, "Failed to open config file %s.\n", argv[1]);
    return -1;
  }

  if (init_log_config(argv[1], config) < 0) {
    fprintf(stderr, "Failed to initialize log config.\n");
    return -1;
  }

  int ret = -1;
  try {
    ret = server_main(config);
  } catch (...) {
    // don't make this happen
    ret = -1;
    LOG_ERROR(logger, "unkown error happened");
  }

  if (ret >= 0) {
    LOG_INFO(logger, "server exit ALL OK.");
  } else {
    LOG_INFO(logger, "server exit OK with failure.");
  }
  return ret;
}

} /* namespace redgiant */

int main(int argc, char** argv) {
  return redgiant::main(argc, argv);
}
<commit_msg>rename configuration constants<commit_after>#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <exception>
#include <memory>
#include <utility>
// Linux headers
#include <libgen.h>
#include <signal.h>

#include "handler/feed_document_handler.h"
#include "handler/query_handler.h"
#include "handler/test_handler.h"
#include "index/document_index_manager.h"
#include "parser/document_parser.h"
#include "parser/feature_cache_parser.h"
#include "parser/query_request_parser.h"
#include "pipeline/feed_document_pipeline.h"
#include "query/simple_query_executor.h"
#include "ranking/default_model.h"
#include "ranking/feature_mapping_model.h"
#include "ranking/model_manager.h"
#include "ranking/ranking_model.h"
#include "service/server.h"
#include "third_party/rapidjson/document.h"
#include "third_party/rapidjson/filereadstream.h"
#include "utils/logger.h"
#include "utils/logger-inl.h"
#include "utils/scope_guard.h"

using std::string;

namespace redgiant {

DECLARE_LOGGER(logger, __FILE__);

// constants used by configuration files
static const unsigned int kConfigParseFlags =
    rapidjson::kParseCommentsFlag | rapidjson::kParseTrailingCommasFlag;
static const char kConfigKeyLoggerConfig    [] = "logger_config";
static const char kConfigKeyFeatureSpaces   [] = "feature_spaces";
static const char kConfigKeyIndex           [] = "index";
static const char kConfigKeyRanking         [] = "ranking";
static const char kConfigKeyPipeline        [] = "pipeline";
static const char kConfigKeyServer          [] = "server";

static volatile int g_exit_signal = 0;

static void new_handler_abort() {
  std::abort();
}

void ignore_signal(int signal) {
  (void) signal;
}

void exit_on_signal(int signal) {
  (void) signal;
  g_exit_signal = signal;
}

static int read_config_file(const char* file_name, rapidjson::Document& config) {
  std::FILE* fp = std::fopen(file_name, "r");
  if (!fp) {
    fprintf(stderr, "Cannot open config file %s.\n", file_name);
    return -1;
  }

  char readBuffer[8192];
  rapidjson::FileReadStream is(fp, readBuffer, sizeof(readBuffer));
  if (config.ParseStream<kConfigParseFlags>(is).HasParseError()) {
    fprintf(stderr, "Config file parse error %d at offset %zu.\n",
        (int)config.GetParseError(), config.GetErrorOffset());
    return -1;
  }

  std::fclose(fp);
  return 0;
}

static int init_log_config(const char* file_name, const rapidjson::Value& config) {
  if (!config.HasMember(kConfigKeyLoggerConfig) || !config[kConfigKeyLoggerConfig].IsString()) {
    fprintf(stderr, "No log file configured!");
    return init_logger(NULL);
  }

  // Copy the file name to a temporary buffer to call "dirname"
  size_t file_name_len = strlen(file_name);
  std::unique_ptr<char[]> file_name_buf(new char[file_name_len + 1]);
  strncpy(file_name_buf.get(), file_name, file_name_len);
  file_name_buf[file_name_len] = 0;
  std::string dir = dirname(file_name_buf.get());
  if (dir.back() != '/') {
    dir += "/";
  }

  // get the file name relative to the configuration file.
  std::string logger_file_name = dir + config[kConfigKeyLoggerConfig].GetString();
  return init_logger(logger_file_name.c_str());
}

static int server_main(rapidjson::Value& config) {
  /*
   * Initialize signal handler
   */
  signal(SIGPIPE, ignore_signal);
  signal(SIGHUP, ignore_signal);
  signal(SIGTERM, exit_on_signal);
  signal(SIGINT, exit_on_signal);

  /*
   * Initialization:
   * Features initialization
   */
  if (!config.HasMember(kConfigKeyFeatureSpaces)) {
    LOG_ERROR(logger, "features configuration does not exist!");
    return -1;
  }

  std::shared_ptr<FeatureCache> feature_cache = std::make_shared<FeatureCache>();
  FeatureCacheParser feature_cache_parser;
  if (feature_cache_parser.parse_json(config[kConfigKeyFeatureSpaces], *feature_cache) < 0) {
    LOG_ERROR(logger, "feature cache parsing failed!");
    return -1;
  }

  /*
   * Initialization:
   * Index initialization
   */
  int document_index_initial_buckets    = 100000;
  int document_index_max_size           = 5000000;
  int document_index_maintain_interval  = 300;

  if (config.HasMember(kConfigKeyIndex)) {
    auto& index_config = config[kConfigKeyIndex];
    if (index_config.HasMember("initial_buckets") && index_config["initial_buckets"].IsInt()) {
      document_index_initial_buckets = index_config["initial_buckets"].GetInt();
    }
    if (index_config.HasMember("max_size") && index_config["max_size"].IsInt()) {
      document_index_max_size = index_config["max_size"].GetInt();
    }
    if (index_config.HasMember("maintain_interval") && index_config["maintain_interval"].IsInt()) {
      document_index_maintain_interval = index_config["max_size"].GetInt();
    }
  }

  DocumentIndexManager document_index(document_index_initial_buckets, document_index_max_size);
  document_index.start_maintain(document_index_maintain_interval, document_index_maintain_interval);
  ScopeGuard feed_document_index_guard([&document_index] {
    LOG_INFO(logger, "document index maintain thread stopping...");
    document_index.stop_maintain();
  });

  size_t feed_document_thread_num = 4;
  size_t feed_document_queue_size = 2048;
  if (config.HasMember(kConfigKeyPipeline)) {
    auto& pipeline_config = config[kConfigKeyPipeline];
    if (pipeline_config.HasMember("thread_num") && pipeline_config["thread_num"].IsInt()) {
      feed_document_thread_num = pipeline_config["thread_num"].GetInt();
    }
    if (pipeline_config.HasMember("queue_size") && pipeline_config["queue_size"].IsInt()) {
      feed_document_queue_size = pipeline_config["queue_size"].GetInt();
    }
  }

  FeedDocumentPipeline feed_document(feed_document_thread_num, feed_document_queue_size, &document_index);
  feed_document.start();
  ScopeGuard feed_document_pipeline_guard([&feed_document] {
    LOG_INFO(logger, "feed document pipeline stopping...");
    feed_document.stop();
  });

  /*
   * Initialization
   * Query and ranking models
   */
  ModelManagerFactory model_manager_factory;
  model_manager_factory.register_model_factory(std::make_shared<DefaultModelFactory>());
  model_manager_factory.register_model_factory(std::make_shared<FeatureMappingModelFactory>(feature_cache));

  if (!config.HasMember(kConfigKeyRanking)) {
    LOG_ERROR(logger, "ranking model config does not exist!");
    return -1;
  }

  std::unique_ptr<RankingModel> model = model_manager_factory.create_model(config[kConfigKeyRanking]);
  if (!model) {
    LOG_ERROR(logger, "ranking model initialization failed!");
    return -1;
  }

  /*
   * Initialization:
   * Server initialization
   */
  LOG_INFO(logger, "server initializing ...");
  int server_port = 19980;
  size_t server_thread_num = 4;
  size_t max_req_per_thread = 0;
  if (config.HasMember(kConfigKeyServer)) {
    auto& server_config = config[kConfigKeyServer];
    if (server_config.HasMember("port") && server_config["port"].IsInt()) {
      server_port = server_config["port"].GetInt();
    }
    if (server_config.HasMember("thread_num") && server_config["thread_num"].IsInt()) {
      server_thread_num = server_config["thread_num"].GetInt();
    }
    if (server_config.HasMember("max_request_per_thread") && server_config["max_request_per_thread"].IsInt()) {
      max_req_per_thread = server_config["max_request_per_thread"].GetInt();
    }
  }

  Server test_server(server_port, server_thread_num, max_req_per_thread);
  test_server.bind("/test", std::make_shared<TestHandlerFactory>());
  test_server.bind("/document", std::make_shared<FeedDocumentHandlerFactory>(
      std::make_shared<DocumentParserFactory>(feature_cache),
      &feed_document, 0));
  test_server.bind("/query", std::make_shared<QueryHandlerFactory>(
      std::make_shared<QueryRequestParserFactory>(feature_cache),
      std::make_shared<SimpleQueryExecutorFactory>(&document_index, model.get())));

  if (test_server.initialize() < 0) {
    LOG_ERROR(logger, "test server initialization failed!");
    return -1;
  }

  ScopeGuard test_server_guard([&test_server] {
    LOG_INFO(logger, "test server exiting...");
    test_server.stop();
  });

  if (test_server.start() < 0) {
    LOG_ERROR(logger, "failed to start test server!");
    return -1;
  }

  LOG_INFO(logger, "test server stared.");

  /*
   * Main loop: wait for exit signal.
   */
  sigset_t mask;
  sigemptyset(&mask);
  sigaddset(&mask, SIGTERM);
  sigaddset(&mask, SIGINT);

  sigset_t orig_mask;
  sigprocmask(SIG_BLOCK, &mask, &orig_mask);
  g_exit_signal = 0;
  while (!g_exit_signal) {
    sigsuspend(&orig_mask);
  }

  /*
   * Exit: everything exits elegantly
   */
  LOG_INFO(logger, "received signal %d. exiting.", g_exit_signal);
  return 0;
}

int main(int argc, char** argv) {
  setvbuf(stdout, NULL, _IONBF, 0);
  setvbuf(stderr, NULL, _IONBF, 0);
  std::set_new_handler(new_handler_abort);

  if (argc != 2) {
    fprintf(stderr, "Usage: %s config_file\n", argv[0]);
    return -1;
  }

  rapidjson::Document config;
  if (read_config_file(argv[1], config) < 0) {
    fprintf(stderr, "Failed to open config file %s.\n", argv[1]);
    return -1;
  }

  if (init_log_config(argv[1], config) < 0) {
    fprintf(stderr, "Failed to initialize log config.\n");
    return -1;
  }

  int ret = -1;
  try {
    ret = server_main(config);
  } catch (...) {
    // don't make this happen
    ret = -1;
    LOG_ERROR(logger, "unkown error happened");
  }

  if (ret >= 0) {
    LOG_INFO(logger, "server exit ALL OK.");
  } else {
    LOG_INFO(logger, "server exit OK with failure.");
  }
  return ret;
}

} /* namespace redgiant */

int main(int argc, char** argv) {
  return redgiant::main(argc, argv);
}
<|endoftext|>


<commit_before>#include <test/unit/math/test_ad.hpp>
#include <vector>

TEST(mathMixMatFun, acosh) {
  auto f = [](const auto& x1) {
    using stan::math::acosh;
    return acosh(x1);
  };
  for (double x : stan::test::internal::common_args())
    stan::test::expect_unary_vectorized(x);
  stan::test::expect_unary_vectorized(f, 1.5, 3.2, 5, 10, 12.9);
  // avoid pole at complex zero that can't be autodiffed
  for (double re : std::vector<double>{-0.2, 0, 0.3}) {
    for (double im : std::vector<double>{-0.3, 0.2}) {
      stan::test::expect_ad(f, std::complex<double>{re, im});
    }
  }
}

TEST(mathMixMatFun, acosh_varmat) {
  using stan::math::vec_concat;
  using stan::test::expect_ad_vector_matvar;
  using stan::test::internal::common_args;
  auto f = [](const auto& x1) {
    using stan::math::acosh;
    return acosh(x1);
  };
  std::vector<double> com_args = common_args();
  std::vector<double> args{1.5, 3.2, 5, 10, 12.9};
  auto all_args = vec_concat(com_args, args);
  Eigen::VectorXd A(all_args.size());
  for (int i = 0; i < all_args.size(); ++i) {
    A(i) = all_args[i];
  }
  expect_ad_vector_matvar(f, A);
}
<commit_msg>fix acosh<commit_after>#include <test/unit/math/test_ad.hpp>
#include <vector>

TEST(mathMixMatFun, acosh) {
  auto f = [](const auto& x1) {
    using stan::math::acosh;
    return acosh(x1);
  };
  for (double x : stan::test::internal::common_args())
    stan::test::expect_unary_vectorized(f, x);
  stan::test::expect_unary_vectorized(f, 1.5, 3.2, 5, 10, 12.9);
  // avoid pole at complex zero that can't be autodiffed
  for (double re : std::vector<double>{-0.2, 0, 0.3}) {
    for (double im : std::vector<double>{-0.3, 0.2}) {
      stan::test::expect_ad(f, std::complex<double>{re, im});
    }
  }
}

TEST(mathMixMatFun, acosh_varmat) {
  using stan::math::vec_concat;
  using stan::test::expect_ad_vector_matvar;
  using stan::test::internal::common_args;
  auto f = [](const auto& x1) {
    using stan::math::acosh;
    return acosh(x1);
  };
  std::vector<double> com_args = common_args();
  std::vector<double> args{1.5, 3.2, 5, 10, 12.9};
  auto all_args = vec_concat(com_args, args);
  Eigen::VectorXd A(all_args.size());
  for (int i = 0; i < all_args.size(); ++i) {
    A(i) = all_args[i];
  }
  expect_ad_vector_matvar(f, A);
}
<|endoftext|>


<commit_before>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "protocol.h"

#include "chainparams.h"
#include "util.h"

#ifndef WIN32
# include <arpa/inet.h>
#endif

static const char* ppszTypeName[] =
{
    "ERROR",
    "tx",
    "block",
    "filtered block"
};

CMessageHeader::CMessageHeader()
{
    memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    pchCommand[1] = 1;
    nMessageSize = -1;
    nChecksum = 0;
}

CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
{
    memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
    strncpy(pchCommand, pszCommand, COMMAND_SIZE);
    nMessageSize = nMessageSizeIn;
    nChecksum = 0;
}

std::string CMessageHeader::GetCommand() const
{
    if (pchCommand[COMMAND_SIZE-1] == 0)
        return std::string(pchCommand, pchCommand + strlen(pchCommand));
    else
        return std::string(pchCommand, pchCommand + COMMAND_SIZE);
}

bool CMessageHeader::IsValid() const
{
    // Check start string
    if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        LogPrintf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
        return false;
    }

    return true;
}

CAddress::CAddress() : CService()
{
    Init();
}

CAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)
{
    Init();
    nServices = nServicesIn;
}

void CAddress::Init()
{
    nServices = NODE_NETWORK;
    nTime = 100000000;
    nLastTry = 0;
}

CInv::CInv()
{
    type = 0;
    hash = 0;
}

CInv::CInv(int typeIn, const uint256& hashIn)
{
    type = typeIn;
    hash = hashIn;
}

CInv::CInv(const std::string& strType, const uint256& hashIn)
{
    unsigned int i;
    for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
    {
        if (strType == ppszTypeName[i])
        {
            type = i;
            break;
        }
    }
    if (i == ARRAYLEN(ppszTypeName))
        throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType));
    hash = hashIn;
}

bool operator<(const CInv& a, const CInv& b)
{
    return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}

bool CInv::IsKnownType() const
{
    return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));
}

const char* CInv::GetCommand() const
{
    if (!IsKnownType())
        throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
    return ppszTypeName[type];
}

std::string CInv::ToString() const
{
    return strprintf("%s %s", GetCommand(), hash.ToString());
}
<commit_msg>CMessageHeader sanity changes<commit_after>// Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.

#include "protocol.h"

#include "chainparams.h"
#include "util.h"

#ifndef WIN32
# include <arpa/inet.h>
#endif

static const char* ppszTypeName[] =
{
    "ERROR",
    "tx",
    "block",
    "filtered block"
};

CMessageHeader::CMessageHeader()
{
    memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    nMessageSize = -1;
    nChecksum = 0;
}

CMessageHeader::CMessageHeader(const char* pszCommand, unsigned int nMessageSizeIn)
{
    memcpy(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE);
    memset(pchCommand, 0, sizeof(pchCommand));
    strncpy(pchCommand, pszCommand, COMMAND_SIZE);
    nMessageSize = nMessageSizeIn;
    nChecksum = 0;
}

std::string CMessageHeader::GetCommand() const
{
    return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}

bool CMessageHeader::IsValid() const
{
    // Check start string
    if (memcmp(pchMessageStart, Params().MessageStart(), MESSAGE_START_SIZE) != 0)
        return false;

    // Check the command string for errors
    for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
    {
        if (*p1 == 0)
        {
            // Must be all zeros after the first zero
            for (; p1 < pchCommand + COMMAND_SIZE; p1++)
                if (*p1 != 0)
                    return false;
        }
        else if (*p1 < ' ' || *p1 > 0x7E)
            return false;
    }

    // Message size
    if (nMessageSize > MAX_SIZE)
    {
        LogPrintf("CMessageHeader::IsValid() : (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
        return false;
    }

    return true;
}

CAddress::CAddress() : CService()
{
    Init();
}

CAddress::CAddress(CService ipIn, uint64_t nServicesIn) : CService(ipIn)
{
    Init();
    nServices = nServicesIn;
}

void CAddress::Init()
{
    nServices = NODE_NETWORK;
    nTime = 100000000;
    nLastTry = 0;
}

CInv::CInv()
{
    type = 0;
    hash = 0;
}

CInv::CInv(int typeIn, const uint256& hashIn)
{
    type = typeIn;
    hash = hashIn;
}

CInv::CInv(const std::string& strType, const uint256& hashIn)
{
    unsigned int i;
    for (i = 1; i < ARRAYLEN(ppszTypeName); i++)
    {
        if (strType == ppszTypeName[i])
        {
            type = i;
            break;
        }
    }
    if (i == ARRAYLEN(ppszTypeName))
        throw std::out_of_range(strprintf("CInv::CInv(string, uint256) : unknown type '%s'", strType));
    hash = hashIn;
}

bool operator<(const CInv& a, const CInv& b)
{
    return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}

bool CInv::IsKnownType() const
{
    return (type >= 1 && type < (int)ARRAYLEN(ppszTypeName));
}

const char* CInv::GetCommand() const
{
    if (!IsKnownType())
        throw std::out_of_range(strprintf("CInv::GetCommand() : type=%d unknown type", type));
    return ppszTypeName[type];
}

std::string CInv::ToString() const
{
    return strprintf("%s %s", GetCommand(), hash.ToString());
}
<|endoftext|>


<commit_before>#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <pybind11/operators.h>
#include <pybind11/functional.h>

#include <core.h>
#include <space.h>
#include <move.h>
#include <analysis.h>
#include <potentials.h>
#include <regions.h>
#include <montecarlo.h>
#include <energy.h>

namespace py = pybind11;
using namespace Faunus;

typedef typename Space::GroupType Tgroup;
typedef Energy::Hamiltonian Thamiltonian;
typedef MetropolisMonteCarlo Tmcsimulation;

inline json dict2json(py::dict dict) {
    py::object dumps = py::module::import("json").attr("dumps");
    return json::parse( dumps(dict).cast<std::string>() );
} // python dict --> c++ json

inline json list2json(py::list list) {
    py::object dumps = py::module::import("json").attr("dumps");
    return json::parse(dumps(list).cast<std::string>());
} // python list --> c++ json

inline py::dict json2dict(const json &j) {
    py::object loads = py::module::import("json").attr("loads");
    return loads( j.dump() ) ;
}

template<class T>
std::unique_ptr<T> from_dict(py::dict dict) {
    auto ptr = new T();
    *ptr = dict2json(dict);
    return std::unique_ptr<T>(ptr);
} // convert py::dict to T through Faunus::json

PYBIND11_MODULE(pyfaunus, m)
{
    using namespace pybind11::literals;

    // json
    py::class_<json>(m, "json")
        .def(py::init( [](std::string arg) {
                    return std::unique_ptr<json>(new json(json::parse(arg)));
                    } ) )
    .def(py::init([](py::dict dict) {
                py::object dumps = py::module::import("json").attr("dumps");
                std::string s = dumps(dict).cast<std::string>();
                return std::unique_ptr<json>(new json(json::parse(s)));
                } ) );

    // Random
    py::class_<Random>(m, "Random")
        .def(py::init<>())
        .def("__call__", [](Random &self){ return self(); } ); // function operator

    m.attr("random") = &Faunus::random; // global instance

    // Geometries
    py::enum_<Geometry::VolumeMethod>(m, "VolumeMethod")
        .value("ISOTROPIC", Geometry::VolumeMethod::ISOTROPIC)
        .value("ISOCHORIC", Geometry::VolumeMethod::ISOCHORIC)
        .value("XY", Geometry::VolumeMethod::XY)
        .value("Z", Geometry::VolumeMethod::Z)
        .export_values();

    py::class_<Geometry::GeometryBase>(m, "Geometrybase")
        .def("getVolume", &Geometry::GeometryBase::getVolume, "Get container volume", "dim"_a = 3)
        .def("setVolume", &Geometry::GeometryBase::setVolume, "Set container volume", "volume"_a,
             "method"_a = Geometry::VolumeMethod::ISOTROPIC)
        .def("collision", &Geometry::GeometryBase::collision, "pos"_a, "Checks if point is inside container")
        .def("getLength", &Geometry::GeometryBase::getLength, "Get cuboid sidelengths")
        .def("vdist", &Geometry::GeometryBase::vdist, "Minimum vector distance, a-b", "a"_a, "b"_a)
        .def("randompos",
             [](Geometry::GeometryBase& g, Random& rnd) {
                 Point pos;
                 g.randompos(pos, rnd);
                 return pos;
             })
        .def(
            "boundary",
            [](Geometry::GeometryBase& g, const Point& pos) {
                Point a = pos; // we cannot modify `pos` directly
                g.boundary(a); // as in c++
                return a;
            },
            R"(
                    Apply periodic boundaries

                    If applicable for the geometry type, this will apply
                    periodic boundaries to a coordinate.

                    Args:
                       pos (array): coordinate

                    Returns:
                       array: position with wrapped coordinate
                )");

    py::class_<Geometry::Chameleon, Geometry::GeometryBase>(m, "Chameleon")
        .def(py::init<>())
        .def(py::init([](py::dict dict) {
            auto ptr = std::make_unique<Geometry::Chameleon>();
            Faunus::Geometry::from_json(dict2json(dict), *ptr);
            return ptr;
        }))
        .def("sqdist", &Geometry::Chameleon::sqdist, "Squared minimum distance, |a-b|^2", "a"_a, "b"_a);

    // Particle properties
    py::class_<Charge>(m, "Charge")
        .def(py::init<>())
        .def_readwrite("charge", &Charge::charge, "Particle charge (monopole)");

    py::class_<Particle>(m, "Particle")
        .def(py::init<>())
        .def("traits", &Particle::traits)
        .def_readwrite("id", &Particle::id, "Particle ID")
        .def_readwrite("pos", &Particle::pos, "Particle position")
        .def_readwrite("charge", &Particle::charge, "Particle charge (monopole)");

    // Particle vector and it's iterator
    py::class_<ParticleVector::iterator>(m, "ParticleVectorIterator")
        .def("__add__", [](ParticleVector::iterator it, int i) { return it + i; })
        .def("__sub__", [](ParticleVector::iterator it, int i) { return it - i; });

    auto _pvec = py::bind_vector<ParticleVector>(m, "ParticleVector");
    _pvec.def("positions", [](ParticleVector& p) { return asEigenMatrix(p.begin(), p.end(), &Particle::pos); })
        .def("charges", [](ParticleVector& p) { return asEigenVector(p.begin(), p.end(), &Particle::charge); })
        .def("begin", [](ParticleVector& p) { return p.begin(); })
        .def("end", [](ParticleVector& p) { return p.end(); });

    // Group
    py::class_<Tgroup>(m, "Group")
        .def(py::init<MoleculeData::index_type, ParticleVector::iterator, ParticleVector::iterator>())
        .def_readwrite("groups", &Tgroup::id, "Molecule id")
        .def_readwrite("id", &Tgroup::id, "Molecule id")
        .def_readwrite("cm", &Tgroup::mass_center, "Center of mass")
        .def("__len__", [](Tgroup& self) { return self.size(); })
        .def(
            "__iter__", [](Tgroup& v) { return py::make_iterator(v.begin(), v.end()); }, py::keep_alive<0, 1>())
        .def("isAtomic", &Tgroup::isAtomic)
        .def("isMolecular", &Tgroup::isMolecular)
        .def("traits", &Tgroup::traits)
        .def("contains", &Tgroup::contains)
        .def("capacity", &Tgroup::capacity)
        .def("deactivate", &Tgroup::deactivate)
        .def("activate", &Tgroup::activate)
        .def("begin", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::begin)
        .def("end", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::end);

    py::bind_vector<std::vector<Tgroup>>(m, "GroupVector");

    // Region
    py::enum_<Region::RegionBase::RegionType>(m, "RegionType")
        .value("SPHERE", Region::RegionBase::RegionType::SPHERE)
        .value("CUBOID", Region::RegionBase::RegionType::CUBOID)
        .value("WITHIN", Region::RegionBase::RegionType::WITHIN)
        .value("NONE", Region::RegionBase::RegionType::NONE)
        .export_values();

    py::class_<Region::RegionBase>(m, "RegionBase")
        .def_readwrite("name", &Region::RegionBase::name)
        .def_readwrite("type", &Region::RegionBase::type)
        .def("volume", &Region::RegionBase::isInside)
        .def("isInside", &Region::RegionBase::isInside);

    // AtomData
    py::class_<AtomData>(m, "AtomData")
        .def(py::init<>())
        .def_property(
            "eps", [](const AtomData& a) { return a.interaction.at("eps"); },
            [](AtomData& a, double val) { a.interaction.at("eps") = val; })
        .def_property(
            "sigma", [](const AtomData& a) { return a.interaction.at("sigma"); },
            [](AtomData& a, double val) { a.interaction.at("sigma") = val; })
        .def_readwrite("name", &AtomData::name)
        .def_readwrite("activity", &AtomData::activity, "Activity = chemical potential in log scale (mol/l)")
        .def("id", (const AtomData::index_type& (AtomData::*)() const) &
                       AtomData::id); // explicit signature due to overload in c++

    auto _atomdatavec = py::bind_vector<std::vector<AtomData>>(m, "AtomDataVector");
    _atomdatavec
        .def("from_list", [](std::vector<AtomData> &a, py::list list) {
                Faunus::from_json(list2json(list), a); } );

    m.attr("atoms") = &Faunus::atoms; // global instance

    // Temperature and other globals etc.
    m.def("getTemperature", []() { return pc::temperature; } );
    m.def("setTemperature", [](double T) { pc::temperature = T; } );

    // --------- Pair Potentials ---------

    // Base
    py::class_<Potential::PairPotentialBase>(m, "PairPotentialBase")
        .def_readwrite("name", &Potential::PairPotentialBase::name)
        .def_readwrite("cite", &Potential::PairPotentialBase::cite)
        .def_readwrite("isotropic", &Potential::PairPotentialBase::isotropic)
        .def_readwrite("selfEnergy", &Potential::PairPotentialBase::selfEnergy)
        .def("force", &Potential::PairPotentialBase::force)
        .def("energy", [](Potential::PairPotentialBase &pot, const Particle &a, const Particle &b, double r2,
                          const Point &r) { return pot(a, b, r2, r); });

    // Potentials::FunctorPotential
    py::class_<Potential::FunctorPotential, Potential::PairPotentialBase>(m, "FunctorPotential")
        .def(py::init([](py::dict dict) { return from_dict<Potential::FunctorPotential>(dict); }));

    // Change::Data
    py::class_<Change::GroupChange>(m, "ChangeData")
        .def(py::init<>())
        .def_readwrite("dNatomic", &Change::GroupChange::dNatomic)
        .def_readwrite("dNswap", &Change::GroupChange::dNswap)
        .def_readwrite("index", &Change::GroupChange::group_index)
        .def_readwrite("internal", &Change::GroupChange::internal)
        .def_readwrite("all", &Change::GroupChange::all)
        .def_readwrite("atoms", &Change::GroupChange::relative_atom_indices);

    py::bind_vector<std::vector<Change::GroupChange>>(m, "ChangeDataVec");

    // Change
    py::class_<Change>(m, "Change")
        .def(py::init<>())
        .def_readwrite("everything", &Change::everything)
        .def_readwrite("volume_change", &Change::volume_change)
        .def_readwrite("matter_change", &Change::matter_change)
        .def_readwrite("groups", &Change::groups);

    // Space
    py::class_<Space>(m, "Space")
        .def(py::init<>())
        .def_readwrite("geo", &Space::geometry)
        .def_readwrite("particles", &Space::particles)
        .def_readwrite("groups", &Space::groups)
        // https://stackoverflow.com/questions/65812046/disambiguate-non-const-and-const-access-methods-pybind11
        // .def("findMolecules", &Space::findMolecules)
        .def("from_dict", [](Space& spc, py::dict dict) { from_json(dict2json(dict), spc); });

    // Hamiltonian
    py::class_<Thamiltonian>(m, "Hamiltonian")
        .def(py::init<Space &, const json &>())
        .def(py::init([](Space &spc, py::list list) {
            json j = list2json(list);
            return std::unique_ptr<Thamiltonian>(new Thamiltonian(spc, j));
        }))
        .def("init", &Thamiltonian::init)
        .def("energy", &Thamiltonian::energy);

    // TranslationalEntropy
    py::class_<TranslationalEntropy>(m, "TranslationalEntropy")
        .def(py::init<Space &, Space &>())
        .def("energy", &TranslationalEntropy::energy);

    // MCSimulation
    py::class_<Tmcsimulation>(m, "MetropolisMonteCarlo")
        .def(py::init([](py::dict dict) {
            json j = dict2json(dict);
            return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
        }))
        .def(py::init([](py::dict dict) {
            json j = dict2json(dict);
            return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
        }));

    // Analysisbase
    py::class_<Analysis::Analysisbase>(m, "Analysisbase")
        .def_readonly("name", &Analysis::Analysisbase::name)
        .def_readwrite("cite", &Analysis::Analysisbase::cite)
        .def("to_disk", &Analysis::Analysisbase::to_disk)
        .def("sample", &Analysis::Analysisbase::sample)
        .def("to_dict", [](Analysis::Analysisbase &self) {
            json j;
            Analysis::to_json(j, self);
            return json2dict(j);
        });

    py::bind_vector<std::vector<std::shared_ptr<Analysis::Analysisbase>>>(m, "AnalysisVector");

    // CombinedAnalysis
    py::class_<Analysis::CombinedAnalysis>(m, "Analysis")
        .def(py::init([](Space &spc, Thamiltonian &pot, py::list list) {
            json j = list2json(list);
            return std::unique_ptr<Analysis::CombinedAnalysis>(new Analysis::CombinedAnalysis(j, spc, pot));
        }))
        .def_readwrite("vector", &Analysis::CombinedAnalysis::vec)
        .def("to_dict",
             [](Analysis::CombinedAnalysis &self) {
                 json j;
                 Faunus::to_json(j, self);
                 return json2dict(j);
             })
        .def("sample", &Analysis::CombinedAnalysis::sample);
}
<commit_msg>Fix regions in pyfaunus<commit_after>#include <pybind11/pybind11.h>
#include <pybind11/stl_bind.h>
#include <pybind11/numpy.h>
#include <pybind11/eigen.h>
#include <pybind11/operators.h>
#include <pybind11/functional.h>

#include <core.h>
#include <space.h>
#include <move.h>
#include <analysis.h>
#include <potentials.h>
#include <regions.h>
#include <montecarlo.h>
#include <energy.h>

namespace py = pybind11;
using namespace Faunus;

typedef typename Space::GroupType Tgroup;
typedef Energy::Hamiltonian Thamiltonian;
typedef MetropolisMonteCarlo Tmcsimulation;

inline json dict2json(py::dict dict) {
    py::object dumps = py::module::import("json").attr("dumps");
    return json::parse( dumps(dict).cast<std::string>() );
} // python dict --> c++ json

inline json list2json(py::list list) {
    py::object dumps = py::module::import("json").attr("dumps");
    return json::parse(dumps(list).cast<std::string>());
} // python list --> c++ json

inline py::dict json2dict(const json &j) {
    py::object loads = py::module::import("json").attr("loads");
    return loads( j.dump() ) ;
}

template<class T>
std::unique_ptr<T> from_dict(py::dict dict) {
    auto ptr = new T();
    *ptr = dict2json(dict);
    return std::unique_ptr<T>(ptr);
} // convert py::dict to T through Faunus::json

PYBIND11_MODULE(pyfaunus, m)
{
    using namespace pybind11::literals;

    // json
    py::class_<json>(m, "json")
        .def(py::init( [](std::string arg) {
                    return std::unique_ptr<json>(new json(json::parse(arg)));
                    } ) )
    .def(py::init([](py::dict dict) {
                py::object dumps = py::module::import("json").attr("dumps");
                std::string s = dumps(dict).cast<std::string>();
                return std::unique_ptr<json>(new json(json::parse(s)));
                } ) );

    // Random
    py::class_<Random>(m, "Random")
        .def(py::init<>())
        .def("__call__", [](Random &self){ return self(); } ); // function operator

    m.attr("random") = &Faunus::random; // global instance

    // Geometries
    py::enum_<Geometry::VolumeMethod>(m, "VolumeMethod")
        .value("ISOTROPIC", Geometry::VolumeMethod::ISOTROPIC)
        .value("ISOCHORIC", Geometry::VolumeMethod::ISOCHORIC)
        .value("XY", Geometry::VolumeMethod::XY)
        .value("Z", Geometry::VolumeMethod::Z)
        .export_values();

    py::class_<Geometry::GeometryBase>(m, "Geometrybase")
        .def("getVolume", &Geometry::GeometryBase::getVolume, "Get container volume", "dim"_a = 3)
        .def("setVolume", &Geometry::GeometryBase::setVolume, "Set container volume", "volume"_a,
             "method"_a = Geometry::VolumeMethod::ISOTROPIC)
        .def("collision", &Geometry::GeometryBase::collision, "pos"_a, "Checks if point is inside container")
        .def("getLength", &Geometry::GeometryBase::getLength, "Get cuboid sidelengths")
        .def("vdist", &Geometry::GeometryBase::vdist, "Minimum vector distance, a-b", "a"_a, "b"_a)
        .def("randompos",
             [](Geometry::GeometryBase& g, Random& rnd) {
                 Point pos;
                 g.randompos(pos, rnd);
                 return pos;
             })
        .def(
            "boundary",
            [](Geometry::GeometryBase& g, const Point& pos) {
                Point a = pos; // we cannot modify `pos` directly
                g.boundary(a); // as in c++
                return a;
            },
            R"(
                    Apply periodic boundaries

                    If applicable for the geometry type, this will apply
                    periodic boundaries to a coordinate.

                    Args:
                       pos (array): coordinate

                    Returns:
                       array: position with wrapped coordinate
                )");

    py::class_<Geometry::Chameleon, Geometry::GeometryBase>(m, "Chameleon")
        .def(py::init<>())
        .def(py::init([](py::dict dict) {
            auto ptr = std::make_unique<Geometry::Chameleon>();
            Faunus::Geometry::from_json(dict2json(dict), *ptr);
            return ptr;
        }))
        .def("sqdist", &Geometry::Chameleon::sqdist, "Squared minimum distance, |a-b|^2", "a"_a, "b"_a);

    // Particle properties
    py::class_<Charge>(m, "Charge")
        .def(py::init<>())
        .def_readwrite("charge", &Charge::charge, "Particle charge (monopole)");

    py::class_<Particle>(m, "Particle")
        .def(py::init<>())
        .def("traits", &Particle::traits)
        .def_readwrite("id", &Particle::id, "Particle ID")
        .def_readwrite("pos", &Particle::pos, "Particle position")
        .def_readwrite("charge", &Particle::charge, "Particle charge (monopole)");

    // Particle vector and it's iterator
    py::class_<ParticleVector::iterator>(m, "ParticleVectorIterator")
        .def("__add__", [](ParticleVector::iterator it, int i) { return it + i; })
        .def("__sub__", [](ParticleVector::iterator it, int i) { return it - i; });

    auto _pvec = py::bind_vector<ParticleVector>(m, "ParticleVector");
    _pvec.def("positions", [](ParticleVector& p) { return asEigenMatrix(p.begin(), p.end(), &Particle::pos); })
        .def("charges", [](ParticleVector& p) { return asEigenVector(p.begin(), p.end(), &Particle::charge); })
        .def("begin", [](ParticleVector& p) { return p.begin(); })
        .def("end", [](ParticleVector& p) { return p.end(); });

    // Group
    py::class_<Tgroup>(m, "Group")
        .def(py::init<MoleculeData::index_type, ParticleVector::iterator, ParticleVector::iterator>())
        .def_readwrite("groups", &Tgroup::id, "Molecule id")
        .def_readwrite("id", &Tgroup::id, "Molecule id")
        .def_readwrite("cm", &Tgroup::mass_center, "Center of mass")
        .def("__len__", [](Tgroup& self) { return self.size(); })
        .def(
            "__iter__", [](Tgroup& v) { return py::make_iterator(v.begin(), v.end()); }, py::keep_alive<0, 1>())
        .def("isAtomic", &Tgroup::isAtomic)
        .def("isMolecular", &Tgroup::isMolecular)
        .def("traits", &Tgroup::traits)
        .def("contains", &Tgroup::contains)
        .def("capacity", &Tgroup::capacity)
        .def("deactivate", &Tgroup::deactivate)
        .def("activate", &Tgroup::activate)
        .def("begin", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::begin)
        .def("end", (ParticleVector::iterator & (Tgroup::*)()) & Tgroup::end);

    py::bind_vector<std::vector<Tgroup>>(m, "GroupVector");

    // Region
    py::enum_<Region::RegionType>(m, "RegionType")
        .value("WITHIN_PARTICLE", Region::RegionType::WITHIN_PARTICLE)
        .value("WITHIN_MOLID", Region::RegionType::WITHIN_MOLID)
        .value("NONE", Region::RegionType::INVALID)
        .export_values();

    py::class_<Region::RegionBase>(m, "RegionBase")
        .def_readonly("type", &Region::RegionBase::type)
        .def("volume", &Region::RegionBase::isInside)
        .def("isInside", &Region::RegionBase::isInside);

    // AtomData
    py::class_<AtomData>(m, "AtomData")
        .def(py::init<>())
        .def_property(
            "eps", [](const AtomData& a) { return a.interaction.at("eps"); },
            [](AtomData& a, double val) { a.interaction.at("eps") = val; })
        .def_property(
            "sigma", [](const AtomData& a) { return a.interaction.at("sigma"); },
            [](AtomData& a, double val) { a.interaction.at("sigma") = val; })
        .def_readwrite("name", &AtomData::name)
        .def_readwrite("activity", &AtomData::activity, "Activity = chemical potential in log scale (mol/l)")
        .def("id", (const AtomData::index_type& (AtomData::*)() const) &
                       AtomData::id); // explicit signature due to overload in c++

    auto _atomdatavec = py::bind_vector<std::vector<AtomData>>(m, "AtomDataVector");
    _atomdatavec
        .def("from_list", [](std::vector<AtomData> &a, py::list list) {
                Faunus::from_json(list2json(list), a); } );

    m.attr("atoms") = &Faunus::atoms; // global instance

    // Temperature and other globals etc.
    m.def("getTemperature", []() { return pc::temperature; } );
    m.def("setTemperature", [](double T) { pc::temperature = T; } );

    // --------- Pair Potentials ---------

    // Base
    py::class_<Potential::PairPotentialBase>(m, "PairPotentialBase")
        .def_readwrite("name", &Potential::PairPotentialBase::name)
        .def_readwrite("cite", &Potential::PairPotentialBase::cite)
        .def_readwrite("isotropic", &Potential::PairPotentialBase::isotropic)
        .def_readwrite("selfEnergy", &Potential::PairPotentialBase::selfEnergy)
        .def("force", &Potential::PairPotentialBase::force)
        .def("energy", [](Potential::PairPotentialBase &pot, const Particle &a, const Particle &b, double r2,
                          const Point &r) { return pot(a, b, r2, r); });

    // Potentials::FunctorPotential
    py::class_<Potential::FunctorPotential, Potential::PairPotentialBase>(m, "FunctorPotential")
        .def(py::init([](py::dict dict) { return from_dict<Potential::FunctorPotential>(dict); }));

    // Change::Data
    py::class_<Change::GroupChange>(m, "ChangeData")
        .def(py::init<>())
        .def_readwrite("dNatomic", &Change::GroupChange::dNatomic)
        .def_readwrite("dNswap", &Change::GroupChange::dNswap)
        .def_readwrite("index", &Change::GroupChange::group_index)
        .def_readwrite("internal", &Change::GroupChange::internal)
        .def_readwrite("all", &Change::GroupChange::all)
        .def_readwrite("atoms", &Change::GroupChange::relative_atom_indices);

    py::bind_vector<std::vector<Change::GroupChange>>(m, "ChangeDataVec");

    // Change
    py::class_<Change>(m, "Change")
        .def(py::init<>())
        .def_readwrite("everything", &Change::everything)
        .def_readwrite("volume_change", &Change::volume_change)
        .def_readwrite("matter_change", &Change::matter_change)
        .def_readwrite("groups", &Change::groups);

    // Space
    py::class_<Space>(m, "Space")
        .def(py::init<>())
        .def_readwrite("geo", &Space::geometry)
        .def_readwrite("particles", &Space::particles)
        .def_readwrite("groups", &Space::groups)
        // https://stackoverflow.com/questions/65812046/disambiguate-non-const-and-const-access-methods-pybind11
        // .def("findMolecules", &Space::findMolecules)
        .def("from_dict", [](Space& spc, py::dict dict) { from_json(dict2json(dict), spc); });

    // Hamiltonian
    py::class_<Thamiltonian>(m, "Hamiltonian")
        .def(py::init<Space &, const json &>())
        .def(py::init([](Space &spc, py::list list) {
            json j = list2json(list);
            return std::unique_ptr<Thamiltonian>(new Thamiltonian(spc, j));
        }))
        .def("init", &Thamiltonian::init)
        .def("energy", &Thamiltonian::energy);

    // TranslationalEntropy
    py::class_<TranslationalEntropy>(m, "TranslationalEntropy")
        .def(py::init<Space &, Space &>())
        .def("energy", &TranslationalEntropy::energy);

    // MCSimulation
    py::class_<Tmcsimulation>(m, "MetropolisMonteCarlo")
        .def(py::init([](py::dict dict) {
            json j = dict2json(dict);
            return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
        }))
        .def(py::init([](py::dict dict) {
            json j = dict2json(dict);
            return std::unique_ptr<Tmcsimulation>(new Tmcsimulation(j));
        }));

    // Analysisbase
    py::class_<Analysis::Analysisbase>(m, "Analysisbase")
        .def_readonly("name", &Analysis::Analysisbase::name)
        .def_readwrite("cite", &Analysis::Analysisbase::cite)
        .def("to_disk", &Analysis::Analysisbase::to_disk)
        .def("sample", &Analysis::Analysisbase::sample)
        .def("to_dict", [](Analysis::Analysisbase &self) {
            json j;
            Analysis::to_json(j, self);
            return json2dict(j);
        });

    py::bind_vector<std::vector<std::shared_ptr<Analysis::Analysisbase>>>(m, "AnalysisVector");

    // CombinedAnalysis
    py::class_<Analysis::CombinedAnalysis>(m, "Analysis")
        .def(py::init([](Space &spc, Thamiltonian &pot, py::list list) {
            json j = list2json(list);
            return std::unique_ptr<Analysis::CombinedAnalysis>(new Analysis::CombinedAnalysis(j, spc, pot));
        }))
        .def_readwrite("vector", &Analysis::CombinedAnalysis::vec)
        .def("to_dict",
             [](Analysis::CombinedAnalysis &self) {
                 json j;
                 Faunus::to_json(j, self);
                 return json2dict(j);
             })
        .def("sample", &Analysis::CombinedAnalysis::sample);
}
<|endoftext|>


<commit_before>/*
Resembla
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

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 RESEMBLA_RERANKER_HPP
#define RESEMBLA_RERANKER_HPP

#include <vector>
#include <algorithm>
#include <string>

#ifdef DEBUG
#include "string_util.hpp"
#include <iostream>
#endif

namespace resembla {

template<typename Original>
class Reranker
{
public:
    using output_type = std::pair<Original, double>;

    template<
        typename Iterator,
        typename ScoreFunction
    >
    std::vector<output_type> rerank(
        const typename std::iterator_traits<Iterator>::value_type& target,
        const Iterator begin,
        const Iterator end,
        const ScoreFunction& score_func,
        double threshold = 0.0,
        size_t max_output = 0
    ) const
    {
#ifdef DEBUG
        std::cerr << "DEBUG: " << "target=" << cast_string<std::string>(target.first) << std::endl;
        std::cerr << "DEBUG: " << "===========before reranking=============" << std::endl;
        for(auto i = begin; i != end; ++i){
            std::cerr << "DEBUG: " << cast_string<std::string>(i->first) << std::endl;
        }
        std::cerr << "DEBUG: " << "start reranking: threshold==" << threshold << ", max_output=" << max_output << std::endl;
#endif
        std::vector<output_type> result;
        for(auto i = begin; i != end; ++i){
            auto score = score_func(target.second, i->second);
            if(threshold == 0.0 || score >= threshold){
                result.push_back(std::make_pair(i->first, score));
            }
        }
        std::sort(std::begin(result), std::end(result), Sorter());
        if(max_output != 0 && result.size() > max_output){
            result.erase(std::begin(result) + max_output, std::end(result));
        }
#ifdef DEBUG
        std::cerr << "DEBUG: " << "===========after reranking=============" << std::endl;
        for(auto i = std::begin(result); i != std::end(result); ++i){
            std::cerr << "DEBUG: " << "text=" << cast_string<std::string>(i->first) << ", score=" << i->second << std::endl;
        }
#endif
        return result;
    }

protected:
    struct Sorter
    {
        bool operator()(const output_type& a, const output_type& b) const
        {
            return a.second > b.second;
        }
    };
};

}
#endif
<commit_msg>use partial_sort<commit_after>/*
Resembla
https://github.com/tuem/resembla

Copyright 2017 Takashi Uemura

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 RESEMBLA_RERANKER_HPP
#define RESEMBLA_RERANKER_HPP

#include <vector>
#include <algorithm>

#ifdef DEBUG
#include <string>
#include <iostream>
#include "string_util.hpp"
#endif

namespace resembla {

template<typename Original>
class Reranker
{
public:
    using output_type = std::pair<Original, double>;

    template<typename Iterator, typename ScoreFunction>
    std::vector<output_type> rerank(
        const typename std::iterator_traits<Iterator>::value_type& target,
        const Iterator begin, const Iterator end,
        const ScoreFunction& score_func,
        double threshold = 0.0, size_t max_output = 0
    ) const
    {
#ifdef DEBUG
        std::cerr << "DEBUG: " << "target=" << cast_string<std::string>(target.first) << std::endl;
        std::cerr << "DEBUG: " << "===========before reranking=============" << std::endl;
        for(auto i = begin; i != end; ++i){
            std::cerr << "DEBUG: " << cast_string<std::string>(i->first) << std::endl;
        }
        std::cerr << "DEBUG: " << "start reranking: threshold==" << threshold << ", max_output=" << max_output << std::endl;
#endif
        std::vector<output_type> result;
        for(auto i = begin; i != end; ++i){
            auto score = score_func(target.second, i->second);
            if(threshold == 0.0 || score >= threshold){
                result.push_back(std::make_pair(i->first, score));
            }
        }

        if(max_output != 0 && result.size() > max_output){
            std::partial_sort(result.begin(), result.begin() + max_output, result.end(), Sorter());
            result.erase(std::begin(result) + max_output, std::end(result));
        }
        else{
            std::sort(result.begin(), result.end(), Sorter());
        }
#ifdef DEBUG
        std::cerr << "DEBUG: " << "===========after reranking=============" << std::endl;
        for(const auto& r: result){
            std::cerr << "DEBUG: " << "text=" << cast_string<std::string>(r.first) << ", score=" << r.second << std::endl;
        }
#endif
        return result;
    }

protected:
    struct Sorter
    {
        bool operator()(const output_type& a, const output_type& b) const
        {
            return a.second > b.second;
        }
    };
};

}
#endif
<|endoftext|>