text:
/***************************************************************************************************************************
 * circular.cpp
 *
 * Author: Ydm
 *
 * Update Time: 2020.8.14
 *
 * descripation: demostration of circular flying using mavros
 *      1.
 *      2.
 *      3.
***************************************************************************************************************************/

#include <ros/ros.h>
#include <fstream>
#include <math.h>
#include <cmath>
#include <string>
#include <time.h>
#include <queue>
#include <vector>
#include <cstdlib>
#include <stdlib.h>
#include <iostream>
#include <stdio.h>
#include <iostream>
#include <math_utils.h>
#include <Eigen/Eigen>

#include <std_msgs/Bool.h>
#include <std_msgs/String.h>
#include <geometry_msgs/PoseStamped.h>
#include <geometry_msgs/TwistStamped.h>
#include <sensor_msgs/Imu.h>
#include <mavros_msgs/AttitudeTarget.h>
#include <mavros_msgs/PositionTarget.h>
#include <mavros_msgs/ActuatorControl.h>
#include <mavros_msgs/CommandBool.h>
#include <mavros_msgs/SetMode.h>
#include <mavros_msgs/State.h>

#include <nlink_parser/LinktrackNode2.h>		//target information from Ground station

//#include <circular.h>

using namespace std;

float desire_z = 10.0;				//desired altitude
float desire_Radius = 10.0;		//desired radius of circle
float MoveTimeCnt = 0.0;
float priod = 2000.0;			//to change velocity of flying using it

float DESIRE_V = 10;

Eigen::Vector3d P_T0 = {200, 100, 50};		//initial position of Target
Eigen::Vector3d P_M0 = {0, 0, 5};			//initial position of Missile
Eigen::Vector3d V_T = {-3, 0, 0};			//velocity of Target
Eigen::Vector3d V_M = {0, 0, 0};
float VM = 1;						//velocity of Missile

float K1 = 4;						//proportion of guidance
float K2 = 4;

double sita = 0.0;
double psi_v = 0.0;
double phi = 0;
double psi = 0;
double gamma_vehicle = 0;

mavros_msgs::State current_state;
mavros_msgs::State target_state;
Eigen::Vector3d position_get;
Eigen::Vector3d attitude_get;
Eigen::Vector3d velocity_get;
Eigen::Vector3d att_rate_get;

Eigen::Vector3d pos_target; 	//desired value in offboard mode
Eigen::Vector3d pos_drone;
Eigen::Vector3d temp_pos_drone;
Eigen::Vector3d temp_pos_target;
Eigen::Vector3d velocity_sp;
Eigen::Vector2d Actuator_sp;

mavros_msgs::SetMode mode_cmd;
ros::Publisher setpoint_raw_local_pub;
ros::Publisher actuator_setpoint_pub;
ros::ServiceClient set_mode_client;

enum
{
	WATTING,
	CHECKING,
	PREPARE,
	REST,
	FLY,
	FLYOVER,
}FlyState = WATTING;		//the initial state

Eigen::Matrix3d L;
Eigen::Vector3d P_r;
Eigen::Vector3d P_T = P_T0;
Eigen::Vector3d P_M = P_M0;
double x_r = 1;
double y_r = 1;
double z_r = 1;
double x_r_last = 0;
double y_r_last = 0;
double z_r_last = 0;
double q_lambda = 0;
double q_gamma = 0;
double q_lambda_last = 0;
double q_gamma_last= 0;
double q_lambda_delta = 0;
double q_gamma_delta = 0;
double delta_sita = 0.0;
double delta_psi_v = 0.0;
double yaw_target = 0.0;

//receive the current position of drone from controller

void state_cb(const mavros_msgs::State::ConstPtr& msg)
{
	current_state = *msg;
}

float str2float(string str)
{
  float result;
  stringstream stream(str);
  stream >> result;
  return result;
}

void target_cb(const std_msgs::String::ConstPtr& msg)
{
  int num = msg->data.size();
  P_T[0] = str2float(msg->data.substr(8,15));
  P_T[1] = str2float(msg->data.substr(18,25));
  P_T[2] = str2float(msg->data.substr(28,35));

  P_M[0] = str2float(msg->data.substr(43,50));
  P_M[1] = str2float(msg->data.substr(53,60));
  P_M[2] = str2float(msg->data.substr(63,70));
  //东北天坐标系
  //printf("the size of string is %d\n",num);
  //printf("%f\n", P_M[0]);
  //printf("%f\n", P_M[1]);
  //printf("%f\n", P_M[2]);
}

void pos_cb(const geometry_msgs::PoseStamped::ConstPtr &msg)
{
	//read the drone postion from the Mavros Package [Frame: ENU]
	Eigen::Vector3d pos_drone_fcu_enu(msg->pose.position.x, msg->pose.position.y, msg->pose.position.z);

	pos_drone = pos_drone_fcu_enu;

}

void vel_cb(const geometry_msgs::TwistStamped::ConstPtr &msg)
{

    velocity_get[0] = msg->twist.linear.x;
    velocity_get[1] = msg->twist.linear.y;
	velocity_get[2] = msg->twist.linear.z;
}

void att_cb(const sensor_msgs::Imu::ConstPtr& msg)
{
	Eigen::Quaterniond q_fcu = Eigen::Quaterniond(msg->orientation.w, msg->orientation.x, msg->orientation.y, msg->orientation.z);
      //Transform the Quaternion to euler Angles
      Eigen::Vector3d euler_fcu = quaternion_to_euler(q_fcu);

      attitude_get = euler_fcu;

	att_rate_get[0] = msg->angular_velocity.x;
    att_rate_get[1] = msg->angular_velocity.y;
    att_rate_get[2] = msg->angular_velocity.z;

 }

//send the desired position to controller (vx, vy, vz)
void send_vel_setpoint(const Eigen::Vector3d& vel_sp)
{
	mavros_msgs::PositionTarget pos_setpoint;
	pos_setpoint.type_mask = 0b110111000111;	//0b 110 111 000 111  velocity

	//Bitmask to indicate which dimensions should be ignored (1 means ignore, 0 means not ignore; Bit 10 must set to 0)
	//Bit 1:x, bit 2:y, bit 3:z, bit 4:vx, bit 5:vy, bit 6:vz, bit 7: ax, bit 8:ay, bit 9:az, bit 10:is_force_sp, bit 11: yaw, bit 12:yaw_rate
	//Bit 10 should set to 0, means no force sp

	pos_setpoint.coordinate_frame = 1;

	pos_setpoint.velocity.x = vel_sp[0];
	pos_setpoint.velocity.y = vel_sp[1];
	pos_setpoint.velocity.z = vel_sp[2];

	pos_setpoint.yaw = yaw_target;

	setpoint_raw_local_pub.publish(pos_setpoint);
}

//send the desired position to controller (xyz, yaw)
void send_pos_setpoint(const Eigen::Vector3d& pos_sp, float yaw_sp)
{
	mavros_msgs::PositionTarget pos_setpoint;
	pos_setpoint.type_mask = 0b100111111000;	//0b 100 111 111 000 xyz + yaw

	//Bitmask to indicate which dimensions should be ignored (1 means ignore, 0 means not ignore; Bit 10 must set to 0)
	//Bit 1:x, bit 2:y, bit 3:z, bit 4:vx, bit 5:vy, bit 6:vz, bit 7: ax, bit 8:ay, bit 9:az, bit 10:is_force_sp, bit 11: yaw, bit 12:yaw_rate
	//Bit 10 should set to 0, means no force sp

	pos_setpoint.coordinate_frame = 1;

	pos_setpoint.position.x = pos_sp[0];
	pos_setpoint.position.y = pos_sp[1];
	pos_setpoint.position.z = pos_sp[2];

	pos_setpoint.yaw = yaw_sp;

	setpoint_raw_local_pub.publish(pos_setpoint);
}

// 【发布】底层控制量（Mx My Mz 及 F） [0][1][2][3]分别对应 roll pitch yaw控制量 及 油门推力 注意 这里是NED系的！！
void send_actuator_setpoint(const Eigen::Vector2d& actuator_sp)
{
    mavros_msgs::ActuatorControl actuator_setpoint;

    actuator_setpoint.group_mix = 0;
    actuator_setpoint.controls[0] = 0.0;
    actuator_setpoint.controls[1] = 0.0;
    actuator_setpoint.controls[2] = actuator_sp(1);		//偏航
    actuator_setpoint.controls[3] = actuator_sp(0);		//油门
    actuator_setpoint.controls[4] = 0.0;
    actuator_setpoint.controls[5] = 0.0;
    actuator_setpoint.controls[6] = 0.0;
    actuator_setpoint.controls[7] = 0.0;

    actuator_setpoint_pub.publish(actuator_setpoint);

    // // 检查飞控是否收到控制量
    // cout <<">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>command_to_mavros<<<<<<<<<<<<<<<<<<<<<<<<<<<" <<endl;
    // //ned to enu
    // cout << "actuator_target [0 1 2 3] : " << actuator_target.controls[0] << " [ ] "<< -actuator_target.controls[1] <<" [ ] "<<-actuator_target.controls[2]<<" [ ] "<<actuator_target.controls[3] <<" [ ] "<<endl;

    // cout << "actuator_target [4 5 6 7] : " << actuator_target.controls[4] << " [ ] "<< actuator_target.controls[5] <<" [ ] "<<actuator_target.controls[6]<<" [ ] "<<actuator_target.controls[7] <<" [ ] "<<endl;

}
void Guidance_Update(void)
{

	P_r = P_T - P_M;
	x_r = P_r[0];
	y_r = P_r[1];
	z_r = P_r[2];

	psi = atan2(y_r , x_r);			//psi is defined to the angle of T-M line and x axis(East orientation)
	double yaw_fcu = attitude_get[2];		//实际偏航角 东北天坐标系 【-pi - pi】
	//yaw_target = psi + M_PI * 3 / 2;
	//if (yaw_target > 2 * M_PI)
	//{
	//	yaw_target = yaw_target - 2 * M_PI;
	//}
	yaw_target = psi;
	//double yaw_control = -10 * (yaw_target - yaw_fcu) / 2 / M_PI;
	//Actuator_sp[0] = 0.8;				//throttle
	//Actuator_sp[1] = yaw_control;		//yaw
	cout << "psi = " << psi << endl;
	cout << "yaw_fcu = " << yaw_fcu << endl;
	cout << "yaw_target = " << yaw_target << endl;
	//cout << "yaw_control = " << yaw_control << endl;
	V_M << VM * cos(psi), VM * sin(psi), 0;

}

void FlyState_update(void)
{
	switch(FlyState)
	{
		case WATTING:
			if(current_state.mode != "OFFBOARD")	//waitting for offboard mode
			{
				pos_target[0] = pos_drone[0];
				pos_target[1] = pos_drone[1];
				pos_target[2] = pos_drone[2];
				temp_pos_drone[0] = pos_drone[0];
				temp_pos_drone[1] = pos_drone[1];
				temp_pos_drone[2] = pos_drone[2];
				send_pos_setpoint(pos_target, 0);
			}
			else
			{
				pos_target[0] = temp_pos_drone[0];
				pos_target[1] = temp_pos_drone[1];
				pos_target[2] = temp_pos_drone[2];
				send_pos_setpoint(pos_target, 0);
				FlyState = CHECKING;
			}
			//cout << "WATTING" << endl;
			break;

		case CHECKING:
			if(pos_drone[0] == 0 && pos_drone[1] == 0)	//no position information, land
			{
				cout << "Check error, make sure have local location" <<endl;
				mode_cmd.request.custom_mode = "AUTO.LAND";
				set_mode_client.call(mode_cmd);
				FlyState = WATTING;
			}
			else
			{
				FlyState = PREPARE;
				MoveTimeCnt = 0;
			}
			//cout << "CHECKING" << endl;
			break;
		case PREPARE:									//fly to the first point located in x negative axis

			FlyState = REST;
			//cout << "PREPARE" << endl;
			break;
		case REST:
			pos_target[0] = pos_drone[0];				//fly to 10 m
			pos_target[1] = pos_drone[1];
			pos_target[2] = desire_z;
			send_pos_setpoint(pos_target, 0);
			MoveTimeCnt += 1;
			if(MoveTimeCnt >= 100)
			{
				MoveTimeCnt = 0;
				FlyState = FLY;
			}
			if(current_state.mode != "OFFBOARD")			//if it is switched to "onboard" mode, jump to the "WATTING"
			{
				FlyState = WATTING;
			}
			//cout << "REST" << endl;
			break;
		case FLY:
			{

				//Guidance_Update();
				//velocity_sp = V_M;
				velocity_sp = {0.4,0.4,0};
				//send_actuator_setpoint(Actuator_sp);
				send_vel_setpoint(velocity_sp);
				//cout << "I am here!!! " << endl;
				if(current_state.mode != "OFFBOARD")			//if it is switched to "onboard" mode, jump to the "WATTING"
				{
					FlyState = WATTING;
				}
				if(abs(P_r[0]*P_r[0] + P_r[1]*P_r[1] + P_r[2]*P_r[2]) < 0.5)
				{
					cout << "I hit it !!!" << endl;
					FlyState = FLYOVER;
				}
			}
			//cout << "FLY" << endl;
			break;
		case FLYOVER:
			{
				mode_cmd.request.custom_mode = "AUTO.LAND";
				set_mode_client.call(mode_cmd);
				FlyState = WATTING;
			}
			//cout << "FLYOVER" << endl;
			break;
		default:
			cout << "ERROR!!!" << endl;
	}
}

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

   	ros::Subscriber target_sub = nh.subscribe<std_msgs::String>("/nlink_linktrack_data_transmission", 100, target_cb);
	ros::Subscriber state_sub = nh.subscribe<mavros_msgs::State>("/mavros/state", 10, state_cb);			//handle return function
    ros::Subscriber position_sub = nh.subscribe<geometry_msgs::PoseStamped>("/mavros/local_position/pose", 100, pos_cb);
	ros::Subscriber attitude_sub = nh.subscribe<sensor_msgs::Imu>("/mavros/imu/data", 10, att_cb);

	setpoint_raw_local_pub = nh.advertise<mavros_msgs::PositionTarget>("/mavros/setpoint_raw/local", 10);
	actuator_setpoint_pub = nh.advertise<mavros_msgs::ActuatorControl>("/mavros/actuator_control", 10);

	set_mode_client = nh.serviceClient<mavros_msgs::SetMode>("/mavros/set_mode");			//little question
		nh.param<float>("desire_z", desire_z, 10.0);
		nh.param<float>("desire_Radius", desire_Radius, 10.0);

	cout << "guidance node started!!!" << endl;
	ros::Rate rate(20.0);
	while(ros::ok())
	{

		FlyState_update();
		Guidance_Update();
		ros::spinOnce();
		rate.sleep();

		cout << "P_T=" << "\t" << "\t" << "P_M="<< "\t"<< endl;
		cout << "\t" << P_T[0] << "\t" << P_M[0] << endl;
		cout << "\t" << P_T[1] << "\t" << P_M[1] << endl;
		cout << "\t" << P_T[2] << "\t" << P_M[2] << endl;

		cout << "vx = " << V_M[0] << endl;
		cout << "vy = " << V_M[1] << endl;
		cout << "vz = " << V_M[2] << endl;

	}
	return 0;
}

max_stars_repo_name: YANG-DEMIN/Prometheus

max_issues_repo_name: YANG-DEMIN/Prometheus

max_forks_repo_name: YANG-DEMIN/Prometheus


text:
//==================================================================================================
/*!
  @file

    @copyright 2016 NumScale SAS

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

#if defined(DOXYGEN_ONLY)
namespace boost { namespace simd
{

  /*!
    @ingroup group-trigonometric
    This function object returns the inverse sine in degree.

    @par Header <boost/simd/function/asind.hpp>

    @par Note

      For every parameter of floating type `asind(x)`
      returns the arc @c r in the interval  \f$[-90, 90[\f$ such that
      <tt>sin(r) == x</tt>.  If @c x is outside \f$[-1, 1[\f$ the result is Nan.

    @see asin,  asinpi

    @par Example:

      @snippet asind.cpp asind

    @par Possible output:

      @snippet asind.txt asind

  **/
  IEEEValue asind(IEEEValue const & x);
} }
#endif

#include <boost/simd/function/scalar/asind.hpp>
#include <boost/simd/function/simd/asind.hpp>

#endif

ext: hpp

max_stars_repo_name: SylvainCorlay/pythran

max_issues_repo_name: SylvainCorlay/pythran

max_forks_repo_name: SylvainCorlay/pythran


text:
/*=============================================================================
    Copyright (c) 2001-2003 Joel de Guzman
    http://spirit.sourceforge.net/

  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)
=============================================================================*/
#if !defined(BOOST_SPIRIT_NIL_HPP)
#define BOOST_SPIRIT_NIL_HPP

#include <boost/spirit/home/classic/namespace.hpp>

namespace lslboost { namespace spirit {

BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN

    struct nil_t {};

BOOST_SPIRIT_CLASSIC_NAMESPACE_END

}}

#endif


text:
//
//  Copyright (c) 2009-2011 Artyom Beilis (Tonkikh)
//
//  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_LOCALE_IMPL_WIN32_LCID_HPP
#define BOOST_LOCALE_IMPL_WIN32_LCID_HPP

#include <string>
#include <boost/locale/config.hpp>

namespace boost {
    namespace locale {
        namespace impl_win {

            BOOST_LOCALE_DECL unsigned locale_to_lcid(std::string const &locale_name);

        } // impl_win
    } // locale
} // boost

#endif
// vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4

max_stars_repo_name: randolphwong/mcsema

max_issues_repo_name: randolphwong/mcsema

max_forks_repo_name: randolphwong/mcsema


text:
#pragma once

#include <boost/type_traits/add_pointer.hpp>
#include <boost/mpl/transform.hpp>
#include <boost/mpl/for_each.hpp>
#include <boost/fusion/include/as_vector.hpp>
#include <boost/fusion/include/mpl.hpp>
#include <boost/fusion/include/for_each.hpp>
#include <libv/lma/ttt/traits/functor_trait.hpp>
#include <libv/lma/ttt/traits/wrap.hpp>

#include <vector>
#include <Eigen/Core>

template<class T> using AlignedVector = std::vector<T,Eigen::aligned_allocator<T>>;

namespace lma
{

  template<class Solver, class Functors> struct SolverAdd
  {
    Solver& solver;
    Functors& functors;
    SolverAdd(Solver& solver_, Functors& functors_):solver(solver_),functors(functors_){}
    template<class Key> void operator()(const ttt::wrap<Key>&)
    {
      auto& v = *boost::fusion::find<Key>(functors);
      for(auto& pair : v) solver.add(pair.first,pair.second);
    }
  };

  template<class L> class FunctorsContainer
  {
    private:
      template<class F> struct F2type
      {
        typedef typename ttt::Extract<decltype(&F::operator())>::Args args_;
        typedef typename boost::mpl::transform<args_,boost::add_pointer<boost::mpl::_1>>::type args;
        typedef typename boost::fusion::result_of::as_vector<args>::type v_args;
        typedef AlignedVector<std::pair<F,v_args>> type;
      };

      typedef typename boost::mpl::transform<L, F2type<boost::mpl::_1> >::type Types;
      typedef typename boost::fusion::result_of::as_vector<Types>::type Functors;

      Functors functors;

    public:
      template<class F, class ... P> FunctorsContainer& add(const F& f, const P& ... p)
      {
        typedef typename F2type<F>::type Container;
        typedef typename F2type<F>::v_args v_args;
        (*boost::fusion::find<Container>(functors)).emplace_back(f,v_args(p...));
        return *this;
      }

      void clear()
      {
        boost::fusion::for_each(functors,[](auto& v){v.clear();});
      }

      template<class Solver> void fill(Solver& solver)
      {
        boost::mpl::for_each<Types,ttt::wrap_>(SolverAdd<Solver,Functors>(solver,functors));
      }
  };

}

max_stars_repo_name: bezout/LMA

max_issues_repo_name: ayumizll/LMA

max_forks_repo_name: bezout/LMA


text:
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation.  All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------

#include "stdafx.h"

#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"

namespace Common
{
    using namespace std;

    Common::StringLiteral const TraceType("ComponentRootTest");

    class ComponentRootTest :  TextTraceComponent<Common::TraceTaskCodes::Common>
    {
    };

    class MockComponentRoot : public ComponentRoot
    {
    public:
        ~MockComponentRoot() { }

        void SetTraceId(string const & value, size_t capacity) { ComponentRoot::SetTraceId(value, capacity); }
        bool TryPutReservedTraceId(string const & value) { return ComponentRoot::TryPutReservedTraceId(value); }
    };

    BOOST_FIXTURE_TEST_SUITE(ComponentRootTestSuite,ComponentRootTest)

    BOOST_AUTO_TEST_CASE(TraceIdTest)
    {
        Trace.WriteInfo(TraceType, "*** TraceIdTest");

        auto root = make_shared<MockComponentRoot>();

        // Reserve capacity: this will result in memory allocation

        string traceId1("TraceId1");
        size_t capacity = 32;
        root->SetTraceId(traceId1, capacity);

        size_t oldSize = root->TraceId.size();
        size_t oldCapacity = root->TraceId.capacity();
        void const * oldAddress = static_cast<void const *>(root->TraceId.c_str());

        VERIFY_IS_TRUE_FMT(traceId1 == root->TraceId, "{0}, {1}", traceId1, root->TraceId)
        VERIFY_IS_TRUE_FMT(oldSize == traceId1.size(), "{0}, {1}", oldSize, traceId1.size())
        VERIFY_IS_TRUE_FMT(oldCapacity >= capacity, "{0}, {1}", oldCapacity, capacity)

        // Put longer string: should overwrite old string in-place

        string traceId2("LongerTraceId");
        bool success = root->TryPutReservedTraceId(traceId2);
        VERIFY_IS_TRUE(success);

        size_t newSize = root->TraceId.size();
        size_t newCapacity = root->TraceId.capacity();
        void const * newAddress = static_cast<void const *>(root->TraceId.c_str());

        VERIFY_IS_TRUE_FMT(traceId2 == root->TraceId, "{0}, {1}", traceId2, root->TraceId)
        VERIFY_IS_TRUE_FMT(newSize == traceId2.size(), "{0}, {1}", newSize, traceId2.size())
        VERIFY_IS_TRUE_FMT(newCapacity == oldCapacity, "{0}, {1}", newCapacity, oldCapacity)
        VERIFY_IS_TRUE_FMT(newAddress == oldAddress, "{0}, {1}", newAddress, oldAddress);

        // Put shorter string: should overwrite old string in-place

        string traceId3("sTraceId");
        success = root->TryPutReservedTraceId(traceId3);
        VERIFY_IS_TRUE(success);

        newSize = root->TraceId.size();
        newCapacity = root->TraceId.capacity();
        newAddress = static_cast<void const *>(root->TraceId.c_str());

        VERIFY_IS_TRUE_FMT(traceId3 == root->TraceId, "{0}, {1}", traceId3, root->TraceId);
        VERIFY_IS_TRUE_FMT(newSize == traceId3.size(), "{0}, {1}", newSize, traceId3.size());
        VERIFY_IS_TRUE_FMT(newCapacity == oldCapacity, "{0}, {1}", newCapacity, oldCapacity);
        VERIFY_IS_TRUE_FMT(newAddress == oldAddress, "{0}, {1}", newAddress, oldAddress);

        // Put string that is greater than capacity: should fail and leave traceId unchanged

        string traceId4;
        for (size_t ix = 0; ix <= oldCapacity; ++ix)
        {
            traceId4.push_back('X');
        }

        success = root->TryPutReservedTraceId(traceId4);
        VERIFY_IS_FALSE(success);

        newSize = root->TraceId.size();
        newCapacity = root->TraceId.capacity();
        newAddress = static_cast<void const *>(root->TraceId.c_str());

        VERIFY_IS_TRUE_FMT(traceId3 == root->TraceId, "{0}, {1}", traceId3, root->TraceId);
        VERIFY_IS_TRUE_FMT(newSize == traceId3.size(), "{0}, {1}", newSize, traceId3.size());
        VERIFY_IS_TRUE_FMT(newCapacity == oldCapacity, "{0}, {1}", newCapacity, oldCapacity);
        VERIFY_IS_TRUE_FMT(newAddress == oldAddress, "{0}, {1}", newAddress, oldAddress);

        // Put string that is equal to capacity: should succeed

        string traceId5;
        for (size_t ix = 0; ix < oldCapacity; ++ix)
        {
            traceId5.push_back('Y');
        }

        success = root->TryPutReservedTraceId(traceId5);
        VERIFY_IS_TRUE(success);

        newSize = root->TraceId.size();
        newCapacity = root->TraceId.capacity();
        newAddress = static_cast<void const *>(root->TraceId.c_str());

        VERIFY_IS_TRUE_FMT(traceId5 == root->TraceId, "{0}, {1}", traceId5, root->TraceId);
        VERIFY_IS_TRUE_FMT(newSize == traceId5.size(), "{0}, {1}", newSize, traceId5.size());
        VERIFY_IS_TRUE_FMT(newCapacity == oldCapacity, "{0}, {1}", newCapacity, oldCapacity);
        VERIFY_IS_TRUE_FMT(newAddress == oldAddress, "{0}, {1}", newAddress, oldAddress);
    }

    BOOST_AUTO_TEST_SUITE_END()
}

ext: cpp

max_stars_repo_name: leikong/service-fabric

max_issues_repo_name: leikong/service-fabric

max_forks_repo_name: leikong/service-fabric


text:
/**
 * @file
 * @copyright This code is licensed under the 3-clause BSD license.\n
 *            Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
 *            See LICENSE.txt for details.
 */

#include "Files/tests_file_location.h"
#include <Swoose/MolecularMechanics/GAFF/GaffCalculatorSettings.h>
#include <Swoose/MolecularMechanics/GAFF/GaffMolecularMechanicsCalculator.h>
#include <Swoose/MolecularMechanics/SFAM/SfamCalculatorSettings.h>
#include <Swoose/MolecularMechanics/SFAM/SfamMolecularMechanicsCalculator.h>
#include <Swoose/QMMM/InteractionTermEliminator.h>
#include <Utils/IO/ChemicalFileFormats/ChemicalFileHandler.h>
#include <Utils/IO/FormattedIOUtils.h>
#include <gmock/gmock.h>
#include <boost/filesystem.hpp>
#include <numeric>

using namespace testing;
namespace Scine {
using namespace Qmmm;
using namespace MolecularMechanics;
namespace Tests {

/**
 * @class SfamInteractionTermEliminatorTest InteractionTermEliminatorTest.cpp
 * @brief Tests the functionality of the InteractionTermEliminator class applied in QM/MM with SFAM as MM.
 * @test
 */
class SfamInteractionTermEliminatorTest : public Test {
 public:
  std::shared_ptr<SfamMolecularMechanicsCalculator> calculator;
  Core::Log silentLogger = Core::Log::silent();
  void SetUp() override {
    calculator = std::make_shared<SfamMolecularMechanicsCalculator>();
    calculator->setLog(silentLogger);
  }
};

/**
 * @class GaffInteractionTermEliminatorTest InteractionTermEliminatorTest.cpp
 * @brief Tests the functionality of the InteractionTermEliminator class applied in QM/MM with GAFF as MM.
 * @test
 */
class GaffInteractionTermEliminatorTest : public Test {
 public:
  std::shared_ptr<GaffMolecularMechanicsCalculator> calculator;
  Core::Log silentLogger = Core::Log::silent();
  std::string atomicChargesFile = "atomic_charges_for_gaff_test.dat";
  void SetUp() override {
    calculator = std::make_shared<GaffMolecularMechanicsCalculator>();
    calculator->setLog(silentLogger);
  }
  void TearDown() override {
    boost::filesystem::remove_all(atomicChargesFile);
  }
};

TEST_F(SfamInteractionTermEliminatorTest, SfamInteractionTermsAreCompletelyDisabledForMelatonin) {
  Utils::AtomCollection testStructure = Utils::ChemicalFileHandler::read(melatonin_xyz_file).first;

  calculator->settings().modifyString(SwooseUtilities::SettingsNames::parameterFilePath, melatonin_param_file);
  calculator->settings().modifyString(SwooseUtilities::SettingsNames::connectivityFilePath, melatonin_connectivity_file);
  calculator->settings().modifyDouble(SwooseUtilities::SettingsNames::nonCovalentCutoffRadius, 20.0); // basically no
                                                                                // cutoff radius

  calculator->setStructure(testStructure);

  auto results = calculator->calculate("test calculation 1");
  double initialEnergy = results.get<Utils::Property::Energy>();

  // When no interaction terms are eliminated, then the absolute value of the energy should be larger than zero.
  ASSERT_TRUE(std::abs(initialEnergy) > 1e-3);

  std::vector<int> qmAtoms(testStructure.size());
  std::iota(qmAtoms.begin(), qmAtoms.end(), 0);

  // Next line not needed (see test below), but it should work, too.
  auto baseCalcPtr = std::static_pointer_cast<MolecularMechanicsCalculator>(calculator);

  InteractionTermEliminator completeEliminator(qmAtoms, baseCalcPtr);
  completeEliminator.eliminateInteractionTerms(true);

  // Calculation with completely disabling all interaction terms.
  results = calculator->calculate("test calculation 2");
  ASSERT_THAT(results.get<Utils::Property::Energy>(), DoubleNear(0.0, 1e-6));

  completeEliminator.reset();
  results = calculator->calculate("test calculation 3");

  // After reverting to the initial state, the energy should equal the initial energy.
  ASSERT_THAT(results.get<Utils::Property::Energy>(), DoubleNear(initialEnergy, 1e-6));

  completeEliminator.eliminateInteractionTerms(false);
  results = calculator->calculate("test calculation 4");
  ASSERT_THAT(results.get<Utils::Property::Energy>(), DoubleNear(0.0, 1e-6));
}

TEST_F(SfamInteractionTermEliminatorTest, SfamInteractionTermsArePartiallyDisabledForMelatonin) {
  Utils::AtomCollection testStructure = Utils::ChemicalFileHandler::read(melatonin_xyz_file).first;

  calculator->settings().modifyString(SwooseUtilities::SettingsNames::parameterFilePath, melatonin_param_file);
  calculator->settings().modifyString(SwooseUtilities::SettingsNames::connectivityFilePath, melatonin_connectivity_file);
  calculator->settings().modifyDouble(SwooseUtilities::SettingsNames::nonCovalentCutoffRadius, 20.0); // basically no
                                                                                // cutoff radius

  calculator->setStructure(testStructure);

  std::vector<int> qmAtoms = {30, 31, 32, 23, 22, 29, 21, 28, 20, 26, 27, 19, 24, 25};

  InteractionTermEliminator partialEliminator(qmAtoms, calculator);
  partialEliminator.eliminateInteractionTerms(true); // electrostatic embedding: on

  auto results = calculator->calculate("test calculation 1");
  auto energy1 = results.get<Utils::Property::Energy>();
  ASSERT_TRUE(std::abs(energy1 * Utils::Constants::kCalPerMol_per_hartree) > 1.0);

  partialEliminator.reset();
  partialEliminator.eliminateInteractionTerms(false); // electrostatic embedding: off

  results = calculator->calculate("test calculation 2");
  auto energy2 = results.get<Utils::Property::Energy>();
  ASSERT_TRUE(std::abs(energy2 * Utils::Constants::kCalPerMol_per_hartree) > 1.0);

  ASSERT_TRUE(std::abs(energy2 - energy1) * Utils::Constants::kCalPerMol_per_hartree > 0.5);
}

TEST_F(GaffInteractionTermEliminatorTest, GaffInteractionTermsAreCompletelyDisabledForAlanine) {
  Utils::AtomCollection testStructure = Utils::ChemicalFileHandler::read(alanine_xyz_file).first;

  calculator->settings().modifyString(SwooseUtilities::SettingsNames::parameterFilePath, gaff_parameter_file);
  calculator->settings().modifyBool(SwooseUtilities::SettingsNames::detectBondsWithCovalentRadii, true);
  calculator->settings().modifyDouble(SwooseUtilities::SettingsNames::nonCovalentCutoffRadius, 20.0); // basically no
                                                                                // cutoff radius

  calculator->setStructure(testStructure);

  auto results = calculator->calculate("test calculation 1");
  double initialEnergy = results.get<Utils::Property::Energy>();

  // When no interaction terms are eliminated, then the absolute value of the energy should be larger than zero.
  ASSERT_TRUE(std::abs(initialEnergy) > 1e-3);

  std::vector<int> qmAtoms(testStructure.size());
  std::iota(qmAtoms.begin(), qmAtoms.end(), 0);

  // Next line not needed (see test below), but it should work, too.
  auto baseCalcPtr = std::static_pointer_cast<MolecularMechanicsCalculator>(calculator);

  InteractionTermEliminator completeEliminator(qmAtoms, baseCalcPtr);
  completeEliminator.eliminateInteractionTerms(true);

  // Calculation with completely disabling all interaction terms.
  results = calculator->calculate("test calculation 2");
  ASSERT_THAT(results.get<Utils::Property::Energy>(), DoubleNear(0.0, 1e-6));

  completeEliminator.reset();
  results = calculator->calculate("test calculation 3");

  // After reverting to the initial state, the energy should equal the initial energy.
  ASSERT_THAT(results.get<Utils::Property::Energy>(), DoubleNear(initialEnergy, 1e-6));

  completeEliminator.eliminateInteractionTerms(false);
  results = calculator->calculate("test calculation 4");
  ASSERT_THAT(results.get<Utils::Property::Energy>(), DoubleNear(0.0, 1e-6));
}

TEST_F(GaffInteractionTermEliminatorTest, GaffInteractionTermsArePartiallyDisabledForAlanine) {
  Utils::AtomCollection testStructure = Utils::ChemicalFileHandler::read(alanine_xyz_file).first;

  calculator->settings().modifyString(SwooseUtilities::SettingsNames::parameterFilePath, gaff_parameter_file);
  calculator->settings().modifyBool(SwooseUtilities::SettingsNames::detectBondsWithCovalentRadii, true);
  calculator->settings().modifyDouble(SwooseUtilities::SettingsNames::nonCovalentCutoffRadius, 20.0); // basically no
                                                                                // cutoff radius

  /*
   * Add atomic charges file.
   * These charges are taken from OpenBabel.
   */
  Eigen::VectorXd atomicCharges(13);
  atomicCharges << 0.118947, -0.318620, 0.118947, 0.100400, 0.057106, -0.039491, 0.024991, 0.024991, 0.024991, 0.321440,
      -0.249265, -0.479541, 0.295103;
  /*
   * Artificially double charges such that the effect measured below is more pronounced
   * and can be measured against the same thresholds as in the SFAM test example.
   */
  atomicCharges *= 2.0;
  std::ofstream file(atomicChargesFile);
  Utils::matrixToCsv(file, atomicCharges, ',');
  file.close();
  calculator->settings().modifyString(SwooseUtilities::SettingsNames::gaffAtomicChargesFile, atomicChargesFile);

  calculator->setStructure(testStructure);

  std::vector<int> qmAtoms = {3, 4, 5, 6, 7, 8};

  InteractionTermEliminator partialEliminator(qmAtoms, calculator);
  partialEliminator.eliminateInteractionTerms(true); // electrostatic embedding: on

  auto results = calculator->calculate("test calculation 1");
  auto energy1 = results.get<Utils::Property::Energy>();
  ASSERT_TRUE(std::abs(energy1 * Utils::Constants::kCalPerMol_per_hartree) > 1.0);

  partialEliminator.reset();
  partialEliminator.eliminateInteractionTerms(false); // electrostatic embedding: off

  results = calculator->calculate("test calculation 2");
  auto energy2 = results.get<Utils::Property::Energy>();
  ASSERT_TRUE(std::abs(energy2 * Utils::Constants::kCalPerMol_per_hartree) > 1.0);

  ASSERT_TRUE(std::abs(energy2 - energy1) * Utils::Constants::kCalPerMol_per_hartree > 0.5);
}

} // namespace Tests
} // namespace Scine

max_stars_repo_name: qcscine/swoose

max_issues_repo_name: qcscine/swoose

max_forks_repo_name: qcscine/swoose


text:
#include "dispatcher.hpp"
#include "utility.hpp"

#include <iostream>
#include <string>
using namespace std;

#include <logcpp/logger.hpp>
#include <logcpp/helpers/exception.hpp>
#include <logcpp/logger/filerotatelogger.hpp>
#include <logcpp/logger/consolelogger.hpp>
using namespace logcpp;
using namespace logcpp::helpers;

#include <boost/program_options.hpp>
namespace po = boost::program_options;

int main(int argc, char *argv[])
{
    po::options_description desc;
    po::positional_options_description p;
    po::variables_map vm;

    desc.add_options()
        ("config,c",    po::value<string>(), "Configuration directory")
        ("logfile,f",   po::value<string>(), "Print log message to file")
        ("loglevel,l",  po::value<string>()->default_value("critical"), "Logging level")
        ("pidfile,p",   po::value<string>(), "Daemon pid file path")
        ("timeout,t",   po::value<int>()->default_value(1000), "Polling timeout")
        ("daemonize,d", "Run as a daemon")
        ("console,o",   "Print log messages to screen")
        ("help,h",      "Help message")
    ;

    try {

        po::store(po::command_line_parser(argc, argv).options(desc).run(),vm);

        po::notify(vm);

    } catch(const po::error &e) {
        cerr << "ParserError: " << e.what() << endl;
        return EXIT_FAILURE;
    }

    if (vm.count("help")) {
        cout << endl
             << "sproxyd - Serial port proxy daemon" << endl << endl
             << "USAGE" << endl << endl
             << "\tsproxyd [OPTIONS]" << endl << endl
             << "OPTIONS" << endl << endl
             << desc << endl;
        return EXIT_SUCCESS;
    }

    if (vm.count("daemonize")) {
        if (!vm.count("pidfile")) {
            cerr << "ParserError: 'pidfile' is required when daemonize supplied."
                << endl;
            return EXIT_FAILURE;
        }

        Utility::Daemonize(vm["pidfile"].as<string>());
    }

    if (!vm.count("config")) {
        cerr << "ParserError: 'config' is required" << endl;
        return EXIT_FAILURE;
    }

    LogSeverity level;

    try {
        level = Logger::StringToSeverity(vm["loglevel"].as<string>());
    } catch (const LogcppException &e) {
        cerr << "LoggerError: " << e.what() << endl;
        return EXIT_FAILURE;
    }

    if (vm.count("logfile")) {
        FileRotateLogger::Ptr logger =
            FileRotateLogger::Ptr(new FileRotateLogger());
        logger->SetPath(vm["logfile"].as<string>());
        logger->SetMaxBackup(5);
        logger->SetMaxSize(25000);
        logger->SetAppend(true);
        logger->SetSeverity(level);
        Logger::AddLogger(logger);
    }

    if (vm.count("console")) {
        ConsoleLogger::Ptr logger = ConsoleLogger::Ptr(new ConsoleLogger());
        logger->SetSeverity(level);
        Logger::AddLogger(logger);
    }

    return Dispatcher(vm["config"].as<string>(), vm["timeout"].as<int>()).Run();
}

max_stars_repo_name: darcyg/serial-proxy

max_issues_repo_name: darcyg/serial-proxy

max_forks_repo_name: darcyg/serial-proxy


text:
#include "full_hash.hpp"

#include <boost/filesystem.hpp>
#include <boost/system/error_code.hpp>

#include "configdir.hpp"

using namespace Crowd;

void FullHash::save_full_hash_to_file(std::string& full_hash)
{
    ConfigDir cd;
    std::string file = "full_hash";
    cd.CreateFileInConfigDir(file, full_hash);
}

std::string FullHash::get_full_hash_from_file()
{
    std::string fh;

    // read full_hash file
    ConfigDir cd;
    if (boost::filesystem::exists(cd.GetConfigDir() + "full_hash"))
    {
        std::ifstream stream(cd.GetConfigDir() + "full_hash", std::ios::in | std::ios::binary);
        std::string contents((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());
        fh = contents;
    }
    else
    {
        std::cout << "Full_hash file doesn't exist!!" << std::endl;
        fh = "";
    }

    return fh;
}

max_stars_repo_name: nvrrdt/onzecurrency

max_issues_repo_name: nvrrdt/onzecurrency

max_forks_repo_name: nvrrdt/onzecurrency


text:
// Copyright (c) 2019-2020 Intel Corporation
//
// This work is licensed under the terms of the MIT license.
// For a copy, see <https://opensource.org/licenses/MIT>.

#include <carla/rss/RssRestrictor.h>
#include <carla/rss/RssSensor.h>
#include <carla/sensor/data/RssResponse.h>

#include <ad/physics/python/AdPhysicsPython.hpp>
#include <ad/map/python/AdMapAccessPython.hpp>
#include <ad/rss/python/AdRssPython.hpp>
#include <ad/rss/python/AdRssMapIntegrationPython.hpp>
#include <ad/rss/world/RssDynamics.hpp>
#include <boost/python/suite/indexing/vector_indexing_suite.hpp>

namespace carla {
namespace rss {

std::ostream &operator<<(std::ostream &out, const RssRestrictor &) {
  out << "RssRestrictor()";
  return out;
}

}  // namespace rss

namespace sensor {
namespace data {

std::ostream &operator<<(std::ostream &out, const RssResponse &resp) {
  out << "RssResponse(frame=" << resp.GetFrame() << ", timestamp=" << resp.GetTimestamp()
      << ", valid=" << resp.GetResponseValid() << ", proper_response=" << resp.GetProperResponse()
      << ", rss_state_snapshot=" << resp.GetRssStateSnapshot() << ", situation_snapshot=" << resp.GetSituationSnapshot()
      << ", world_model=" << resp.GetWorldModel() << ", ego_dynamics_on_route=" << resp.GetEgoDynamicsOnRoute() << ')';
  return out;
}

}  // namespace data
}  // namespace sensor
}  // namespace carla

static auto GetEgoVehicleDynamics(const carla::client::RssSensor &self) {
  ad::rss::world::RssDynamics ego_dynamics(self.GetEgoVehicleDynamics());
  return ego_dynamics;
}

static auto GetOtherVehicleDynamics(const carla::client::RssSensor &self) {
  ad::rss::world::RssDynamics other_dynamics(self.GetOtherVehicleDynamics());
  return other_dynamics;
}

static auto GetPedestrianDynamics(const carla::client::RssSensor &self) {
  ad::rss::world::RssDynamics pedestrian_dynamics(self.GetPedestrianDynamics());
  return pedestrian_dynamics;
}

static auto GetRoadBoundariesMode(const carla::client::RssSensor &self) {
  carla::rss::RoadBoundariesMode road_boundaries_mode(self.GetRoadBoundariesMode());
  return road_boundaries_mode;
}

static auto GetRoutingTargets(const carla::client::RssSensor &self) {
  std::vector<carla::geom::Transform> routing_targets(self.GetRoutingTargets());
  return routing_targets;
}

static void RegisterActorConstellationCallback(carla::client::RssSensor &self, boost::python::object callback) {
  namespace py = boost::python;
  // Make sure the callback is actually callable.
  if (!PyCallable_Check(callback.ptr())) {
    PyErr_SetString(PyExc_TypeError, "callback argument must be callable!");
    py::throw_error_already_set();
  }

  // We need to delete the callback while holding the GIL.
  using Deleter = carla::PythonUtil::AcquireGILDeleter;
  auto callback_ptr = carla::SharedPtr<py::object>{new py::object(callback), Deleter()};

  // Make a lambda callback.
  auto callback_function = [callback = std::move(callback_ptr)](
                               carla::SharedPtr<::carla::rss::ActorConstellationData> actor_constellation_data)
                               ->::carla::rss::ActorConstellationResult {
    carla::PythonUtil::AcquireGIL lock;
    ::carla::rss::ActorConstellationResult actor_constellation_result;
    try {
      actor_constellation_result =
          py::call<::carla::rss::ActorConstellationResult>(callback->ptr(), py::object(actor_constellation_data));
    } catch (const py::error_already_set &) {
      PyErr_Print();
    }
    return actor_constellation_result;
  };
  self.RegisterActorConstellationCallback(callback_function);
}

static void Stop(carla::client::RssSensor &self) {
  // ensure the RssSensor is stopped with GIL released to sync on processing lock
  carla::PythonUtil::ReleaseGIL unlock;
  self.Stop();
}

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

  // create/import the ad module scope
  object ad_module(handle<>(borrowed(PyImport_AddModule("ad"))));
  scope().attr("ad") = ad_module;
  scope submodule_scope = ad_module;
  scope().attr("__doc__") = "Python binding of ad namespace C++ code";
  scope().attr("__copyright__") = "Copyright (C) 2019-2020 Intel Corporation";

  export_ad_physics_python();
  export_ad_map_access_python();
  export_ad_rss_python();
  export_ad_rss_map_integration_python();
}

void export_ad_rss() {

  export_ad();

  using namespace boost::python;
  namespace cc = carla::client;
  namespace cs = carla::sensor;
  namespace csd = carla::sensor::data;

  class_<carla::rss::EgoDynamicsOnRoute>("RssEgoDynamicsOnRoute")
      .def_readwrite("timestamp", &carla::rss::EgoDynamicsOnRoute::timestamp)
      .def_readwrite("time_since_epoch_check_start_ms",
                     &carla::rss::EgoDynamicsOnRoute::time_since_epoch_check_start_ms)
      .def_readwrite("time_since_epoch_check_end_ms", &carla::rss::EgoDynamicsOnRoute::time_since_epoch_check_end_ms)
      .def_readwrite("ego_speed", &carla::rss::EgoDynamicsOnRoute::ego_speed)
      .def_readwrite("min_stopping_distance", &carla::rss::EgoDynamicsOnRoute::min_stopping_distance)
      .def_readwrite("ego_center", &carla::rss::EgoDynamicsOnRoute::ego_center)
      .def_readwrite("ego_heading", &carla::rss::EgoDynamicsOnRoute::ego_heading)
      .def_readwrite("ego_center_within_route", &carla::rss::EgoDynamicsOnRoute::ego_center_within_route)
      .def_readwrite("crossing_border", &carla::rss::EgoDynamicsOnRoute::crossing_border)
      .def_readwrite("route_heading", &carla::rss::EgoDynamicsOnRoute::route_heading)
      .def_readwrite("route_nominal_center", &carla::rss::EgoDynamicsOnRoute::route_nominal_center)
      .def_readwrite("heading_diff", &carla::rss::EgoDynamicsOnRoute::heading_diff)
      .def_readwrite("route_speed_lat", &carla::rss::EgoDynamicsOnRoute::route_speed_lat)
      .def_readwrite("route_speed_lon", &carla::rss::EgoDynamicsOnRoute::route_speed_lon)
      .def_readwrite("route_accel_lat", &carla::rss::EgoDynamicsOnRoute::route_accel_lat)
      .def_readwrite("route_accel_lon", &carla::rss::EgoDynamicsOnRoute::route_accel_lon)
      .def_readwrite("avg_route_accel_lat", &carla::rss::EgoDynamicsOnRoute::avg_route_accel_lat)
      .def_readwrite("avg_route_accel_lon", &carla::rss::EgoDynamicsOnRoute::avg_route_accel_lon)
      .def(self_ns::str(self_ns::self));

  class_<carla::rss::ActorConstellationResult>("RssActorConstellationResult")
      .def_readwrite("rss_calculation_mode", &carla::rss::ActorConstellationResult::rss_calculation_mode)
      .def_readwrite("restrict_speed_limit_mode", &carla::rss::ActorConstellationResult::restrict_speed_limit_mode)
      .def_readwrite("ego_vehicle_dynamics", &carla::rss::ActorConstellationResult::ego_vehicle_dynamics)
      .def_readwrite("actor_object_type", &carla::rss::ActorConstellationResult::actor_object_type)
      .def_readwrite("actor_dynamics", &carla::rss::ActorConstellationResult::actor_dynamics)
      .def(self_ns::str(self_ns::self));

  class_<carla::rss::ActorConstellationData, boost::noncopyable, boost::shared_ptr<carla::rss::ActorConstellationData>>(
      "RssActorConstellationData", no_init)
      .def_readonly("ego_match_object", &carla::rss::ActorConstellationData::ego_match_object)
      .def_readonly("ego_route", &carla::rss::ActorConstellationData::ego_route)
      .def_readonly("ego_dynamics_on_route", &carla::rss::ActorConstellationData::ego_dynamics_on_route)
      .def_readonly("other_match_object", &carla::rss::ActorConstellationData::other_match_object)
      .def_readonly("other_actor", &carla::rss::ActorConstellationData::other_actor)
      .def(self_ns::str(self_ns::self));

  enum_<spdlog::level::level_enum>("RssLogLevel")
      .value("trace", spdlog::level::trace)
      .value("debug", spdlog::level::debug)
      .value("info", spdlog::level::info)
      .value("warn", spdlog::level::warn)
      .value("err", spdlog::level::err)
      .value("critical", spdlog::level::critical)
      .value("off", spdlog::level::off);

  enum_<carla::rss::RoadBoundariesMode>("RssRoadBoundariesMode")
      .value("Off", carla::rss::RoadBoundariesMode::Off)
      .value("On", carla::rss::RoadBoundariesMode::On);

  class_<csd::RssResponse, bases<cs::SensorData>, boost::noncopyable, boost::shared_ptr<csd::RssResponse>>(
      "RssResponse", no_init)
      .add_property("response_valid", &csd::RssResponse::GetResponseValid)
      .add_property("proper_response", CALL_RETURNING_COPY(csd::RssResponse, GetProperResponse))
      .add_property("rss_state_snapshot", CALL_RETURNING_COPY(csd::RssResponse, GetRssStateSnapshot))
      .add_property("situation_snapshot", CALL_RETURNING_COPY(csd::RssResponse, GetSituationSnapshot))
      .add_property("world_model", CALL_RETURNING_COPY(csd::RssResponse, GetWorldModel))
      .add_property("ego_dynamics_on_route", CALL_RETURNING_COPY(csd::RssResponse, GetEgoDynamicsOnRoute))
      .def(self_ns::str(self_ns::self));

  class_<cc::RssSensor, bases<cc::Sensor>, boost::noncopyable, boost::shared_ptr<cc::RssSensor>>("RssSensor", no_init)
      .add_property("ego_vehicle_dynamics", &GetEgoVehicleDynamics, &cc::RssSensor::SetEgoVehicleDynamics)
      .add_property("other_vehicle_dynamics", &GetOtherVehicleDynamics, &cc::RssSensor::SetOtherVehicleDynamics)
      .add_property("pedestrian_dynamics", &GetPedestrianDynamics, &cc::RssSensor::SetPedestrianDynamics)
      .add_property("road_boundaries_mode", &GetRoadBoundariesMode, &cc::RssSensor::SetRoadBoundariesMode)
      .add_property("routing_targets", &GetRoutingTargets)
      .def("stop", &Stop)
      .def("register_actor_constellation_callback", &RegisterActorConstellationCallback, (arg("callback")))
      .def("append_routing_target", &cc::RssSensor::AppendRoutingTarget, (arg("routing_target")))
      .def("reset_routing_targets", &cc::RssSensor::ResetRoutingTargets)
      .def("drop_route", &cc::RssSensor::DropRoute)
      .def("set_log_level", &cc::RssSensor::SetLogLevel, (arg("log_level")))
      .def("set_map_log_level", &cc::RssSensor::SetMapLogLevel, (arg("map_log_level")))
      .def(self_ns::str(self_ns::self));

  class_<carla::rss::RssRestrictor, boost::noncopyable, boost::shared_ptr<carla::rss::RssRestrictor>>("RssRestrictor",
                                                                                no_init)
      .def(init<>())
      .def("restrict_vehicle_control", &carla::rss::RssRestrictor::RestrictVehicleControl,
           (arg("vehicle_control"), arg("proper_response"), arg("ego_dynamics_on_route"), arg("vehicle_physics")))
      .def("set_log_level", &carla::rss::RssRestrictor::SetLogLevel, (arg("log_level")))
      .def(self_ns::str(self_ns::self));
}