Commit c573696d authored by Guilhem Saurel's avatar Guilhem Saurel
Browse files

Format

parent 60240642
...@@ -17,24 +17,22 @@ namespace bp = boost::python; ...@@ -17,24 +17,22 @@ namespace bp = boost::python;
namespace dynamicgraph { namespace dynamicgraph {
namespace python { namespace python {
template <typename Iterator> inline template <typename Iterator>
bp::list to_py_list(Iterator begin, Iterator end) { inline bp::list to_py_list(Iterator begin, Iterator end) {
typedef typename Iterator::value_type T; typedef typename Iterator::value_type T;
bp::list lst; bp::list lst;
std::for_each(begin, end, [&](const T& t) { lst.append(t); }); std::for_each(begin, end, [&](const T& t) { lst.append(t); });
return lst; return lst;
} }
template <typename Iterator> inline template <typename Iterator>
bp::tuple to_py_tuple(Iterator begin, Iterator end) { inline bp::tuple to_py_tuple(Iterator begin, Iterator end) {
return bp::tuple(to_py_list(begin, end)); return bp::tuple(to_py_list(begin, end));
} }
template<typename T> inline template <typename T>
std::vector< T > to_std_vector( const bp::object& iterable ) inline std::vector<T> to_std_vector(const bp::object& iterable) {
{ return std::vector<T>(bp::stl_input_iterator<T>(iterable), bp::stl_input_iterator<T>());
return std::vector< T >( bp::stl_input_iterator< T >( iterable ),
bp::stl_input_iterator< T >( ) );
} }
void exposeSignals(); void exposeSignals();
...@@ -50,7 +48,7 @@ void addCommands(boost::python::object obj); ...@@ -50,7 +48,7 @@ void addCommands(boost::python::object obj);
void addSignals(boost::python::object obj); void addSignals(boost::python::object obj);
Entity* create(const char* type, const char* name); Entity* create(const char* type, const char* name);
bp::object executeCmd (bp::tuple args, bp::dict); bp::object executeCmd(bp::tuple args, bp::dict);
} // namespace entity } // namespace entity
namespace factory { namespace factory {
......
...@@ -10,41 +10,40 @@ ...@@ -10,41 +10,40 @@
namespace dynamicgraph { namespace dynamicgraph {
namespace python { namespace python {
constexpr int AddSignals = 1; constexpr int AddSignals = 1;
constexpr int AddCommands = 2; constexpr int AddCommands = 2;
namespace internal { namespace internal {
template<typename T, int Options = AddCommands | AddSignals> template <typename T, int Options = AddCommands | AddSignals>
bp::object makeEntity1(const char* name) { bp::object makeEntity1(const char* name) {
Entity* ent = entity::create(T::CLASS_NAME.c_str(), name); Entity* ent = entity::create(T::CLASS_NAME.c_str(), name);
assert(dynamic_cast<T*>(ent) != NULL); assert(dynamic_cast<T*>(ent) != NULL);
bp::object obj(bp::ptr(static_cast<T*>(ent))); bp::object obj(bp::ptr(static_cast<T*>(ent)));
if (Options & AddCommands) entity::addCommands(obj); if (Options & AddCommands) entity::addCommands(obj);
if (Options & AddSignals) entity::addSignals(obj); if (Options & AddSignals) entity::addSignals(obj);
return obj; return obj;
} }
template<typename T, int Options = AddCommands | AddSignals> template <typename T, int Options = AddCommands | AddSignals>
bp::object makeEntity2() { return makeEntity1<T, Options>(""); } bp::object makeEntity2() {
return makeEntity1<T, Options>("");
} }
} // namespace internal
/// \tparam Options by default, all the signals and commands are added as /// \tparam Options by default, all the signals and commands are added as
/// attribute to the Python object. This behaviour works fine for /// attribute to the Python object. This behaviour works fine for
/// entities that have static commands and signals. /// entities that have static commands and signals.
/// If some commands or signals are added or removed dynamiccally, then /// If some commands or signals are added or removed dynamiccally, then
/// it is better to disable the default behaviour and handle it /// it is better to disable the default behaviour and handle it
/// specifically. /// specifically.
template<typename T, template <typename T, typename bases = boost::python::bases<dynamicgraph::Entity>,
typename bases = boost::python::bases<dynamicgraph::Entity>, int Options = AddCommands | AddSignals>
int Options = AddCommands | AddSignals> inline auto exposeEntity() {
inline auto exposeEntity () // std::string hiddenClassName ("_" + T::CLASS_NAME);
{ std::string hiddenClassName(T::CLASS_NAME);
//std::string hiddenClassName ("_" + T::CLASS_NAME);
std::string hiddenClassName (T::CLASS_NAME);
namespace bp = boost::python; namespace bp = boost::python;
bp::class_<T, bases, boost::noncopyable > obj (hiddenClassName.c_str(), bp::class_<T, bases, boost::noncopyable> obj(hiddenClassName.c_str(), bp::init<std::string>());
bp::init<std::string>());
/* TODO at the moment, I couldn't easily find a way to define a Python constructor /* TODO at the moment, I couldn't easily find a way to define a Python constructor
* that would create the entity via the factory and then populate the * that would create the entity via the factory and then populate the
* python object with its commands. * python object with its commands.
...@@ -69,7 +68,7 @@ inline auto exposeEntity () ...@@ -69,7 +68,7 @@ inline auto exposeEntity ()
return obj; return obj;
} }
} // namespace python } // namespace python
} // namespace dynamicgraph } // namespace dynamicgraph
#endif // DYNAMIC_GRAPH_PYTHON_MODULE_HH #endif // DYNAMIC_GRAPH_PYTHON_MODULE_HH
...@@ -39,7 +39,7 @@ class SignalWrapper : public Signal<T, Time> { ...@@ -39,7 +39,7 @@ class SignalWrapper : public Signal<T, Time> {
this->setFunction(f); this->setFunction(f);
} }
virtual ~SignalWrapper() {}; virtual ~SignalWrapper(){};
private: private:
T& call(T& value, Time t) { T& call(T& value, Time t) {
......
...@@ -80,13 +80,11 @@ bp::object fromValue(const command::Value& value) { ...@@ -80,13 +80,11 @@ bp::object fromValue(const command::Value& value) {
return bp::object(value.matrixXdValue()); return bp::object(value.matrixXdValue());
case (Value::MATRIX4D): case (Value::MATRIX4D):
return bp::object(value.matrix4dValue()); return bp::object(value.matrix4dValue());
case (Value::VALUES): case (Value::VALUES): {
{ bp::list list;
bp::list list; for (const Value& v : value.constValuesValue()) list.append(fromValue(v));
for(const Value& v : value.constValuesValue()) return list;
list.append(fromValue(v)); }
return list;
}
case (Value::NONE): case (Value::NONE):
default: default:
return bp::object(); return bp::object();
......
...@@ -24,8 +24,7 @@ namespace debug { ...@@ -24,8 +24,7 @@ namespace debug {
std::map<std::string, ofstreamShrPtr> mapOfFiles_; std::map<std::string, ofstreamShrPtr> mapOfFiles_;
void addLoggerFileOutputStream(const char* filename) void addLoggerFileOutputStream(const char* filename) {
{
std::ofstream* aofs = new std::ofstream; std::ofstream* aofs = new std::ofstream;
ofstreamShrPtr ofs_shrptr = boost::shared_ptr<std::ofstream>(aofs); ofstreamShrPtr ofs_shrptr = boost::shared_ptr<std::ofstream>(aofs);
aofs->open(filename, std::ofstream::out); aofs->open(filename, std::ofstream::out);
...@@ -35,31 +34,17 @@ void addLoggerFileOutputStream(const char* filename) ...@@ -35,31 +34,17 @@ void addLoggerFileOutputStream(const char* filename)
mapOfFiles_[filename] = ofs_shrptr; mapOfFiles_[filename] = ofs_shrptr;
} }
void closeLoggerFileOutputStream() void closeLoggerFileOutputStream() {
{ for (const auto& el : mapOfFiles_) el.second->close();
for (const auto& el : mapOfFiles_)
el.second->close();
} }
void addLoggerCoutOutputStream() void addLoggerCoutOutputStream() { dgADD_OSTREAM_TO_RTLOG(std::cout); }
{
dgADD_OSTREAM_TO_RTLOG(std::cout);
}
void realTimeLoggerDestroy() void realTimeLoggerDestroy() { RealTimeLogger::destroy(); }
{
RealTimeLogger::destroy();
}
void realTimeLoggerSpinOnce() void realTimeLoggerSpinOnce() { RealTimeLogger::instance().spinOnce(); }
{
RealTimeLogger::instance().spinOnce();
}
void realTimeLoggerInstance() void realTimeLoggerInstance() { RealTimeLogger::instance(); }
{
RealTimeLogger::instance();
}
} // namespace debug } // namespace debug
} // namespace python } // namespace python
......
...@@ -33,13 +33,9 @@ namespace python { ...@@ -33,13 +33,9 @@ namespace python {
/** /**
\brief plug a signal into another one. \brief plug a signal into another one.
*/ */
void plug(SignalBase<int>* signalOut, SignalBase<int>* signalIn) void plug(SignalBase<int>* signalOut, SignalBase<int>* signalIn) { signalIn->plug(signalOut); }
{
signalIn->plug(signalOut);
}
void enableTrace(bool enable, const char* filename) void enableTrace(bool enable, const char* filename) {
{
if (enable) if (enable)
DebugTrace::openFile(filename); DebugTrace::openFile(filename);
else else
...@@ -63,200 +59,175 @@ struct MapOfEntitiesPairToPythonConverter { ...@@ -63,200 +59,175 @@ struct MapOfEntitiesPairToPythonConverter {
} }
}; };
MapOfEntities* getEntityMap() { MapOfEntities* getEntityMap() { return const_cast<MapOfEntities*>(&dg::PoolStorage::getInstance()->getEntityMap()); }
return const_cast<MapOfEntities*>(&dg::PoolStorage::getInstance()->getEntityMap());
}
dg::SignalBase<int>* getSignal(dg::Entity& e, const std::string& name) { dg::SignalBase<int>* getSignal(dg::Entity& e, const std::string& name) { return &e.getSignal(name); }
return &e.getSignal(name);
}
class PythonEntity : public dg::Entity class PythonEntity : public dg::Entity {
{ DYNAMIC_GRAPH_ENTITY_DECL();
DYNAMIC_GRAPH_ENTITY_DECL();
public: public:
using dg::Entity::Entity; using dg::Entity::Entity;
void signalRegistration(dg::SignalBase<int> &signal) void signalRegistration(dg::SignalBase<int>& signal) { dg::Entity::signalRegistration(signal); }
{ void signalDeregistration(const std::string& name) { dg::Entity::signalDeregistration(name); }
dg::Entity::signalRegistration(signal);
}
void signalDeregistration(const std::string &name)
{
dg::Entity::signalDeregistration(name);
}
}; };
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(PythonEntity, "PythonEntity"); DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(PythonEntity, "PythonEntity");
void exposeEntityBase() void exposeEntityBase() {
{
using namespace dynamicgraph; using namespace dynamicgraph;
bp::enum_<LoggerVerbosity> ("LoggerVerbosity") bp::enum_<LoggerVerbosity>("LoggerVerbosity")
.value("VERBOSITY_ALL" , VERBOSITY_ALL) .value("VERBOSITY_ALL", VERBOSITY_ALL)
.value("VERBOSITY_INFO_WARNING_ERROR", VERBOSITY_INFO_WARNING_ERROR) .value("VERBOSITY_INFO_WARNING_ERROR", VERBOSITY_INFO_WARNING_ERROR)
.value("VERBOSITY_WARNING_ERROR" , VERBOSITY_WARNING_ERROR) .value("VERBOSITY_WARNING_ERROR", VERBOSITY_WARNING_ERROR)
.value("VERBOSITY_ERROR" , VERBOSITY_ERROR) .value("VERBOSITY_ERROR", VERBOSITY_ERROR)
.value("VERBOSITY_NONE" , VERBOSITY_NONE) .value("VERBOSITY_NONE", VERBOSITY_NONE)
.export_values(); .export_values();
bp::class_<Entity, boost::noncopyable>("Entity", bp::no_init) bp::class_<Entity, boost::noncopyable>("Entity", bp::no_init)
.add_property ("name", .add_property("name", bp::make_function(&Entity::getName, bp::return_value_policy<bp::copy_const_reference>()))
bp::make_function(&Entity::getName, bp::return_value_policy<bp::copy_const_reference>())) .add_property("className",
.add_property ("className", bp::make_function(&Entity::getClassName, bp::return_value_policy<bp::copy_const_reference>()),
bp::make_function(&Entity::getClassName, bp::return_value_policy<bp::copy_const_reference>()), "the class name of the Entity")
"the class name of the Entity") .add_property("__doc__", &Entity::getDocString)
.add_property ("__doc__", &Entity::getDocString)
.def("setLoggerVerbosityLevel", &Entity::setLoggerVerbosityLevel)
.def("setLoggerVerbosityLevel", &Entity::setLoggerVerbosityLevel) .def("getLoggerVerbosityLevel", &Entity::getLoggerVerbosityLevel)
.def("getLoggerVerbosityLevel", &Entity::getLoggerVerbosityLevel) .add_property("loggerVerbosityLevel", &Entity::setLoggerVerbosityLevel, &Entity::getLoggerVerbosityLevel,
.add_property("loggerVerbosityLevel", &Entity::setLoggerVerbosityLevel, "the verbosity level of the entity")
&Entity::getLoggerVerbosityLevel, "the verbosity level of the entity") .def("setTimeSample", &Entity::setTimeSample)
.def("setTimeSample", &Entity::setTimeSample) .def("getTimeSample", &Entity::getTimeSample)
.def("getTimeSample", &Entity::getTimeSample) .add_property("timeSample", &Entity::getTimeSample, &Entity::setTimeSample,
.add_property("timeSample", &Entity::getTimeSample, &Entity::setTimeSample, "the time sample for printing debugging information")
"the time sample for printing debugging information") .def("setStreamPrintPeriod", &Entity::setStreamPrintPeriod)
.def("setStreamPrintPeriod", &Entity::setStreamPrintPeriod) .def("getStreamPrintPeriod", &Entity::getStreamPrintPeriod)
.def("getStreamPrintPeriod", &Entity::getStreamPrintPeriod) .add_property("streamPrintPeriod", &Entity::getStreamPrintPeriod, &Entity::setStreamPrintPeriod,
.add_property("streamPrintPeriod", &Entity::getStreamPrintPeriod, "set the period at which debugging information are printed")
&Entity::setStreamPrintPeriod,
"set the period at which debugging information are printed") .def("__str__",
+[](const Entity& e) -> std::string {
.def("__str__", +[](const Entity& e) -> std::string { std::ostringstream os;
std::ostringstream os; e.display(os);
e.display(os); return os.str();
return os.str(); })
}) .def("signals",
.def("signals", +[](const Entity& e) -> bp::list { +[](const Entity& e) -> bp::list {
bp::list ret; bp::list ret;
for (auto& el : e.getSignalMap()) for (auto& el : e.getSignalMap()) ret.append(bp::ptr(el.second));
ret.append(bp::ptr(el.second)); return ret;
return ret; },
}, "Return the list of signals.") "Return the list of signals.")
//.def("signal", +[](Entity& e, const std::string &name) { return &e.getSignal(name); }, //.def("signal", +[](Entity& e, const std::string &name) { return &e.getSignal(name); },
//reference_existing_object()) // reference_existing_object())
.def("signal", &getSignal, reference_existing_object(), .def("signal", &getSignal, reference_existing_object(), "get signal by name from an Entity", bp::arg("name"))
"get signal by name from an Entity", bp::arg("name")) .def("hasSignal", &Entity::hasSignal, "return True if the entity has a signal with the given name")
.def("hasSignal", &Entity::hasSignal,
"return True if the entity has a signal with the given name") .def("displaySignals",
+[](const Entity& e) {
.def("displaySignals", +[](const Entity& e) { Entity::SignalMap signals(e.getSignalMap());
Entity::SignalMap signals (e.getSignalMap()); std::cout << "--- <" << e.getName();
std::cout << "--- <" << e.getName(); if (signals.empty())
if (signals.empty()) std::cout << "> has no signal\n";
std::cout << "> has no signal\n"; else
else std::cout << "> signal list:\n";
std::cout << "> signal list:\n"; for (const auto& el : signals) el.second->display(std::cout << " |-- <") << '\n';
for(const auto& el : signals) },
el.second->display(std::cout << " |-- <") << '\n'; "Print the list of signals into standard output: temporary.")
},
"Print the list of signals into standard output: temporary.") /*
.def("__getattr__", +[](Entity& e, const std::string &name) -> SignalBase<int>* { return &e.getSignal(name); },
/* reference_existing_object())
.def("__getattr__", +[](Entity& e, const std::string &name) -> SignalBase<int>* { return &e.getSignal(name); }, def __getattr__(self, name):
reference_existing_object()) try:
def __getattr__(self, name): return self.signal(name)
try: except Exception:
return self.signal(name) try:
except Exception: object.__getattr__(self, name)
try: except AttributeError:
object.__getattr__(self, name) raise AttributeError("'%s' entity has no attribute %s\n" % (self.name, name) +
except AttributeError: ' entity attributes are usually either\n' + ' - commands,\n' +
raise AttributeError("'%s' entity has no attribute %s\n" % (self.name, name) + ' - signals or,\n' + ' - user defined attributes')
' entity attributes are usually either\n' + ' - commands,\n' + */
' - signals or,\n' + ' - user defined attributes') /*
*/ .def("__setattr__", +[](bp::object self, const std::string &name, bp::object value) {
/* Entity& e = bp::extract<Entity&> (self);
.def("__setattr__", +[](bp::object self, const std::string &name, bp::object value) { if (e.hasSignal(name))
Entity& e = bp::extract<Entity&> (self); throw std::invalid_argument(name + " already designates a signal. "
if (e.hasSignal(name)) "It is not advised to set a new attribute of the same name.");
throw std::invalid_argument(name + " already designates a signal. " // TODO How do you do that ? I am sure it is possible.
"It is not advised to set a new attribute of the same name."); //object.__setattr__(self, name, value)
// TODO How do you do that ? I am sure it is possible. })
//object.__setattr__(self, name, value) */
})
*/ /* TODO ?
def boundNewCommand(self, cmdName):
/* TODO ? """
def boundNewCommand(self, cmdName): At construction, all existing commands are bound directly in the class.
""" This method enables to bound new commands dynamically. These new bounds
At construction, all existing commands are bound directly in the class. are not made with the class, but directly with the object instance.
This method enables to bound new commands dynamically. These new bounds """
are not made with the class, but directly with the object instance. def boundAllNewCommands(self):
""" """
def boundAllNewCommands(self): For all commands that are not attribute of the object instance nor of the
""" class, a new attribute of the instance is created to bound the command.
For all commands that are not attribute of the object instance nor of the """
class, a new attribute of the instance is created to bound the command. */
"""
*/ // For backward compat
.add_static_property("entities", bp::make_function(&getEntityMap, reference_existing_object()));
// For backward compat
.add_static_property ("entities", bp::make_function(&getEntityMap, reference_existing_object())) python::exposeEntity<PythonEntity, bp::bases<Entity>, 0>()
;
python::exposeEntity<PythonEntity, bp::bases<Entity>, 0>()
.def("signalRegistration", &PythonEntity::signalRegistration) .def("signalRegistration", &PythonEntity::signalRegistration)
.def("signalDeregistration", &PythonEntity::signalDeregistration) .def("signalDeregistration", &PythonEntity::signalDeregistration);
;
python::exposeEntity<python::PythonSignalContainer, bp::bases<Entity>, 0>().def(
python::exposeEntity<python::PythonSignalContainer, bp::bases<Entity>, 0>() "rmSignal", &python::PythonSignalContainer::rmSignal, "Remove a signal", bp::arg("signal_name"));
.def("rmSignal", &python::PythonSignalContainer::rmSignal, "Remove a signal", bp::arg("signal_name"))
;
} }
void exposeCommand() void exposeCommand() {
{
using dg::command::Command; using dg::command::Command;
bp::class_<Command, boost::noncopyable> ("Command", bp::no_init) bp::class_<Command, boost::noncopyable>("Command", bp::no_init)
.def ("__call__", bp::raw_function(dg::python::entity::executeCmd, 1), "execute the command") .def("__call__", bp::raw_function(dg::python::entity::executeCmd, 1), "execute the command")
.add_property ("__doc__", &Command::getDocstring) .add_property("__doc__", &Command::getDocstring);
;
} }
void exposeOldAPI() void exposeOldAPI() {
{ bp::def("plug", dynamicgraph::python::plug, "plug an output signal into an input signal",
bp::def ("plug", dynamicgraph::python::plug, "plug an output signal into an input signal", (bp::arg("signalOut"), "signalIn")); (bp::arg("signalOut"), "signalIn"));
bp::def ("enableTrace", dynamicgraph::python::enableTrace, "Enable or disable tracing debug info in a file"); bp::def("enableTrace", dynamicgraph::python::enableTrace, "Enable or disable tracing debug info in a file");
// Signals // Signals
bp::def ("create_signal_wrapper", dynamicgraph::python::signalBase::createSignalWrapper, bp::def("create_signal_wrapper", dynamicgraph::python::signalBase::createSignalWrapper, reference_existing_object(),
reference_existing_object(), "create a SignalWrapper C++ object"); "create a SignalWrapper C++ object");
// Entity // Entity
bp::def ("factory_get_entity_class_list", dynamicgraph::python::factory::getEntityClassList, bp::def("factory_get_entity_class_list", dynamicgraph::python::factory::getEntityClassList,
"return the list of entity classes"); "return the list of entity classes");
bp::def ("writeGraph", dynamicgraph::python::pool::writeGraph, "Write the graph of entities in a filename."); bp::def("writeGraph", dynamicgraph::python::pool::writeGraph, "Write the graph of entities in a filename.");
bp::def ("get_entity_list", dynamicgraph::python::pool::getEntityList, bp::def("get_entity_list", dynamicgraph::python::pool::getEntityList, "return the list of instanciated entities");
"return the list of instanciated entities"); bp::def("addLoggerFileOutputStream", dynamicgraph::python::debug::addLoggerFileOutputStream,
bp::def ("addLoggerFileOutputStream", dynamicgraph::python::debug::addLoggerFileOutputStream, "add a output file stream to the logger by filename");
"add a output file stream to the logger by filename"); bp::def("addLoggerCoutOutputStream", dynamicgraph::python::debug::addLoggerCoutOutputStream,
bp::def ("addLoggerCoutOutputStream", dynamicgraph::python::debug::addLoggerCoutOutputStream, "add std::cout as output stream to the logger");
"add std::cout as output stream to the logger"); bp::def("closeLoggerFileOutputStream", dynamicgraph::python::debug::closeLoggerFileOutputStream,
bp::def ("closeLoggerFileOutputStream", dynamicgraph::python::debug::closeLoggerFileOutputStream, "close all the loggers file output streams.");
"close all the loggers file output streams."); bp::def("real_time_logger_destroy", dynamicgraph::python::debug::realTimeLoggerDestroy,
bp::def ("real_time_logger_destroy", dynamicgraph::python::debug::realTimeLoggerDestroy, "Destroy the real time logger.");
"Destroy the real time logger."); bp::def("real_time_logger_spin_once", dynamicgraph::python::debug::realTimeLoggerSpinOnce,
bp::def ("real_time_logger_spin_once", dynamicgraph::python::debug::realTimeLoggerSpinOnce, "Destroy the real time logger.");
"Destroy the real time logger."); bp::def("real_time_logger_instance", dynamicgraph::python::debug::realTimeLoggerInstance,
bp::def ("real_time_logger_instance", dynamicgraph::python::debug::realTimeLoggerInstance, "Starts the real time logger.");
"Starts the real time logger.");
} }
void enableEigenPy() void enableEigenPy() {
{
eigenpy::enableEigenPy(); eigenpy::enableEigenPy();
if(!eigenpy::register_symbolic_link_to_registered_type<Eigen::Quaterniond>()) if (!eigenpy::register_symbolic_link_to_registered_type<Eigen::Quaterniond>()) eigenpy::exposeQuaternion();