Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • ostasse/dynamic-graph-python
  • gsaurel/dynamic-graph-python
  • stack-of-tasks/dynamic-graph-python
3 results
Show changes
Showing
with 416 additions and 42 deletions
/* Copyright 2010-2019 LAAS, CNRS
* Thomas Moulard.
*
*/
#define ENABLE_RT_LOG
#include "custom_entity.h"
#include <dynamic-graph/command-bind.h>
#include <dynamic-graph/entity.h>
#include <dynamic-graph/exception-factory.h>
#include <dynamic-graph/factory.h>
#include <dynamic-graph/pool.h>
#include <dynamic-graph/real-time-logger.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <boost/bind.hpp>
namespace dynamicgraph {
CustomEntity::CustomEntity(const std::string n)
: Entity(n),
m_sigdSIN(NULL, "CustomEntity(" + name + ")::input(double)::in_double"),
m_sigdTimeDepSOUT(boost::bind(&CustomEntity::update, this, _1, _2),
m_sigdSIN,
"CustomEntity(" + name + ")::input(double)::out_double")
{
addSignal();
using namespace dynamicgraph::command;
this->addCommand("act",
makeCommandVoid0(*this, &CustomEntity::act,
docCommandVoid0("act on input signal")));
}
void CustomEntity::addSignal() {
signalRegistration(m_sigdSIN << m_sigdTimeDepSOUT);
}
void CustomEntity::rmValidSignal() {
signalDeregistration("in_double");
signalDeregistration("out_double");
}
double &CustomEntity::update(double &res, const int &inTime) {
const double &aDouble = m_sigdSIN(inTime);
res = aDouble;
logger().stream(MSG_TYPE_ERROR) << "start update " << res << '\n';
DYNAMIC_GRAPH_ENTITY_DEBUG(*this)
<< "This is a message of level MSG_TYPE_DEBUG\n";
DYNAMIC_GRAPH_ENTITY_INFO(*this)
<< "This is a message of level MSG_TYPE_INFO\n";
DYNAMIC_GRAPH_ENTITY_WARNING(*this)
<< "This is a message of level MSG_TYPE_WARNING\n";
DYNAMIC_GRAPH_ENTITY_ERROR(*this)
<< "This is a message of level MSG_TYPE_ERROR\n";
DYNAMIC_GRAPH_ENTITY_DEBUG_STREAM(*this)
<< "This is a message of level MSG_TYPE_DEBUG_STREAM\n";
DYNAMIC_GRAPH_ENTITY_INFO_STREAM(*this)
<< "This is a message of level MSG_TYPE_INFO_STREAM\n";
DYNAMIC_GRAPH_ENTITY_WARNING_STREAM(*this)
<< "This is a message of level MSG_TYPE_WARNING_STREAM\n";
DYNAMIC_GRAPH_ENTITY_ERROR_STREAM(*this)
<< "This is a message of level MSG_TYPE_ERROR_STREAM\n";
logger().stream(MSG_TYPE_ERROR) << "end update\n";
return res;
}
void CustomEntity::act() { m_sigdSIN.accessCopy(); }
DYNAMICGRAPH_FACTORY_ENTITY_PLUGIN(CustomEntity, "CustomEntity");
} // namespace dynamicgraph
/* Copyright 2020 LAAS, CNRS
* Joseph Mirabel
*
*/
#define ENABLE_RT_LOG
#include <dynamic-graph/entity.h>
#include <dynamic-graph/signal-ptr.h>
#include <dynamic-graph/signal-time-dependent.h>
#include <sstream>
namespace dynamicgraph {
class CustomEntity : public Entity {
public:
dynamicgraph::SignalPtr<double, int> m_sigdSIN;
dynamicgraph::SignalTimeDependent<double, int> m_sigdTimeDepSOUT;
DYNAMIC_GRAPH_ENTITY_DECL();
CustomEntity(const std::string n);
void addSignal();
void rmValidSignal();
double &update(double &res, const int &inTime);
void act();
};
} // namespace dynamicgraph
#include "custom_entity.h"
typedef boost::mpl::vector<dynamicgraph::CustomEntity> entities_t;
...@@ -2,10 +2,10 @@ ...@@ -2,10 +2,10 @@
* Copyright * Copyright
*/ */
#include "dynamic-graph-python-test.hh"
#include <iostream> #include <iostream>
#include "dynamic-graph-python-test.hh"
GraphTest::GraphTest() GraphTest::GraphTest() {
{
std::cout << "Constructor of unitTesting object of class Graph." << std::endl; std::cout << "Constructor of unitTesting object of class Graph." << std::endl;
} }
/*
* Copyright
*/
#include "dynamic-graph-python-test.hh"
#include <iostream>
GraphTest::GraphTest() {
std::cout << "Constructor of unitTesting object of class Graph." << std::endl;
}
...@@ -5,19 +5,19 @@ ...@@ -5,19 +5,19 @@
#ifndef DYNAMIC_GRAPH_PYTHON_HH #ifndef DYNAMIC_GRAPH_PYTHON_HH
#define DYNAMIC_GRAPH_PYTHON_HH #define DYNAMIC_GRAPH_PYTHON_HH
#include "dynamic-graph-python/dynamic-graph-python.hh" #include "dynamic-graph-python/dynamic-graph-python.hh"
/** /**
\brief UnitTesting class of class Graph \brief UnitTesting class of class Graph
*/ */
class GraphTest class GraphTest {
{ public:
public:
/** /**
\brief Constructor \brief Constructor
*/ */
GraphTest(); GraphTest();
private:
private:
dynamic::Graph graph_; dynamic::Graph graph_;
}; };
......
// The purpose of this unit test is to check the interpreter::runPythonFile
// method
#include <cstring>
#include <iostream>
#include "dynamic-graph/python/interpreter.hh"
bool testFile(const std::string& filename, const std::string& expectedOutput,
int numTest) {
std::string err = "";
dynamicgraph::python::Interpreter interp;
for (int i = 0; i < numTest; ++i) {
interp.runPythonFile(filename, err);
if (err != expectedOutput) {
std::cerr << "At iteration " << i
<< ", the output was not the one expected:" << std::endl;
std::cerr << " expected: " << expectedOutput << std::endl;
std::cerr << " err: " << err << std::endl;
return false;
}
}
return true;
}
bool testInterpreterDestructor(const std::string& filename,
const std::string& expectedOutput) {
std::string err = "";
{
dynamicgraph::python::Interpreter interp;
interp.runPythonFile(filename, err);
}
{
dynamicgraph::python::Interpreter interp;
interp.runPythonFile(filename, err);
if (err != expectedOutput) {
std::cerr << "The output was not the one expected:" << std::endl;
std::cerr << " expected: " << expectedOutput << std::endl;
std::cerr << " err: " << err << std::endl;
return false;
}
}
return true;
}
int main(int argc, char** argv) {
// execute numerous time the same file.
// While running 1025, we can notice a change in the error.
// unfortunately, it can not be shown using a redirection of the streams
int numTest = 1025;
if (argc > 1) numTest = atoi(argv[1]);
bool res = true;
// This test succeeds only because it is launched before "test_python-ok.py"
// because re as been imported in a previous test and it is not
// safe to delete imported module...
res = testFile(PATH "test_python-name_error.py",
std::string(
"Traceback (most recent call last):\n"
" File \"" PATH
"test_python-name_error.py\", line 7, in <module>\n"
" pathList = re.split(\":\", pkgConfigPath) # noqa\n"
"NameError: name 're' is not defined\n"),
numTest) &&
res;
res = testFile(PATH "test_python-ok.py", "", numTest) && res;
res = testFile(PATH "unexistant_file.py",
PATH "unexistant_file.py cannot be open", numTest) &&
res;
res = testFile(PATH "test_python-syntax_error.py",
std::string(" File \"" PATH
"test_python-syntax_error.py\", line 2\n"
" hello world\n"
#if PY_MINOR_VERSION >= 10
" ^^^^^\n"
#elif PY_MINOR_VERSION >= 8
" ^\n"
#else
" ^\n"
#endif
"SyntaxError: invalid syntax\n"),
numTest) &&
res;
res = testInterpreterDestructor(PATH "test_python-restart_interpreter.py",
"") &&
res;
return (res ? 0 : 1);
}
// The purpose of this unit test is to evaluate the memory consumption
// when call the interpreter.
#include "dynamic-graph/python/interpreter.hh"
int main(int argc, char** argv) {
int numTest = 1;
if (argc > 1) numTest = atoi(argv[1]);
dynamicgraph::python::Interpreter interp;
std::string command;
std::string result;
std::string out;
std::string err;
for (int i = 0; i < numTest; ++i) {
// correct input
interp.python("print('I am the interpreter')", result, out, err);
assert(out.compare("I am the interpreter"));
assert(err.length() == 0);
// incorrect input
interp.python("print I am the interpreter", result, out, err);
assert(result.length() == 0);
assert(out.length() == 0);
assert(err.length() > 50);
}
return 0;
}
/*
* Copyright
*/
#include "dynamic-graph-python-test.hh"
int main(int argc, char** argv) { GraphTest testGraph(); }
import unittest
import dynamic_graph as dg
from custom_entity import CustomEntity
ERR = (
"""Python argument types in
dynamic_graph.wrap.plug(%s, %s)
did not match C++ signature:
plug("""
"dynamicgraph::SignalBase<int>* signalOut, "
"dynamicgraph::SignalBase<int>* signalIn)"
)
class BindingsTests(unittest.TestCase):
def test_type_check(self):
"""
test the type checking in signal plugs
"""
first = CustomEntity("first_entity")
second = CustomEntity("second_entity")
# Check that we can connect first.out to second.in
dg.plug(first.signal("out_double"), second.signal("in_double"))
# Check that we can't connect first.out to second
with self.assertRaises(TypeError) as cm_in:
dg.plug(first.signal("out_double"), second)
self.assertEqual(
str(cm_in.exception), ERR % ("SignalTimeDependentDouble", "CustomEntity")
)
# Check that we can't connect first to second.in
with self.assertRaises(TypeError) as cm_out:
dg.plug(first, second.signal("in_double"))
self.assertEqual(
str(cm_out.exception), ERR % ("CustomEntity", "SignalPtrDouble")
)
def test_dg_exc(self):
"""
test that exceptions from dynamic graph are correctly raised
"""
ent = CustomEntity("test_dg_exc")
# check that accessing a non initialized signal raises
with self.assertRaises(RuntimeError) as cm:
ent.act()
self.assertEqual(
str(cm.exception),
"In SignalPtr: SIN ptr not set. "
"(in signal <CustomEntity(test_dg_exc)::input(double)::in_double>)",
)
# check that accessing an initialized signal doesn't raise
ent_2 = CustomEntity("another_entity")
dg.plug(ent_2.signal("out_double"), ent.signal("in_double"))
ent.act()
if __name__ == "__main__":
unittest.main()
# Olivier Stasse
# 2019 CNRS
#
import os
import time
from custom_entity import CustomEntity
from dynamic_graph import (
addLoggerCoutOutputStream,
addLoggerFileOutputStream,
closeLoggerFileOutputStream,
real_time_logger_destroy,
real_time_logger_spin_once,
)
from dynamic_graph.entity import VerbosityLevel
print(os.getcwd())
# Starts the real time logger instance
aCustomEntity = CustomEntity("a_custom_entity")
addLoggerFileOutputStream("/tmp/output.dat")
aCustomEntity.signals()
aCustomEntity.setTimeSample(0.001)
print(aCustomEntity.getTimeSample())
aCustomEntity.setStreamPrintPeriod(0.002)
print(aCustomEntity.getStreamPrintPeriod())
aCustomEntity.setLoggerVerbosityLevel(VerbosityLevel.VERBOSITY_INFO_WARNING_ERROR)
print(aCustomEntity.getLoggerVerbosityLevel())
for i in range(0, 5):
aCustomEntity.in_double.value = i
aCustomEntity.out_double.recompute(i)
real_time_logger_spin_once()
print(i)
time.sleep(1)
aCustomEntity.setLoggerVerbosityLevel(VerbosityLevel.VERBOSITY_WARNING_ERROR)
print(aCustomEntity.getLoggerVerbosityLevel())
for i in range(5, 10):
aCustomEntity.in_double.value = i
aCustomEntity.out_double.recompute(i)
real_time_logger_spin_once()
time.sleep(1)
aCustomEntity.setLoggerVerbosityLevel(VerbosityLevel.VERBOSITY_ERROR)
print(aCustomEntity.getLoggerVerbosityLevel())
for i in range(10, 15):
aCustomEntity.in_double.value = i
aCustomEntity.out_double.recompute(i)
real_time_logger_spin_once()
time.sleep(1)
addLoggerCoutOutputStream()
time.sleep(1)
aCustomEntity.setLoggerVerbosityLevel(VerbosityLevel.VERBOSITY_NONE)
print(aCustomEntity.getLoggerVerbosityLevel())
for i in range(15, 20):
aCustomEntity.in_double.value = i
aCustomEntity.out_double.recompute(i)
real_time_logger_spin_once()
time.sleep(1)
aCustomEntity.setLoggerVerbosityLevel(VerbosityLevel.VERBOSITY_ALL)
print(aCustomEntity.getLoggerVerbosityLevel())
for i in range(20, 25):
aCustomEntity.in_double.value = i
aCustomEntity.out_double.recompute(i)
real_time_logger_spin_once()
# End the real time logger
real_time_logger_destroy()
# Close all the output stream
closeLoggerFileOutputStream()
# flake8: noqa
import os
pkgConfigPath = os.environ.get("PKG_CONFIG_PATH")
if pkgConfigPath is None:
pkgConfigPath = ""
pathList = re.split(":", pkgConfigPath) # noqa
print(pathList)
import os
import re
pkgConfigPath = os.environ.get("PKG_CONFIG_PATH")
if pkgConfigPath is None:
pkgConfigPath = ""
pathList = re.split(":", pkgConfigPath)
print(pathList)
# numpy causes troubles when Py_Finalize is called in Interpreter destructor.
import numpy # noqa
# Make sure the variable is deleted.
if "var" in locals() or "var" in globals():
raise ValueError("Not cleaned")
var = "This string should have been deleted."
# flake8: noqa
hello world
#
# Copyright
#
SET(EXECUTABLE_NAME test${PROJECT_NAME})
ADD_DEFINITIONS(-DDEBUG=2)
# provide path to library libdynamic-graph.so
LINK_DIRECTORIES(${DYNAMIC_GRAPH_LIBRARY_DIRS})
ADD_EXECUTABLE(${EXECUTABLE_NAME}
main.cc
dynamic-graph-python-test.cc)
INCLUDE_DIRECTORIES(${CMAKE_SOURCE_DIR}/include)
LINK_DIRECTORIES(${${PROJECT_NAME}_BINARY_DIR}/src)
TARGET_LINK_LIBRARIES(${EXECUTABLE_NAME}
dynamic-graph-python)
# Add dynamic-graph compilation flags and link to library libdynamic-graph.so
ADD_DEFINITIONS(${DYNAMIC_GRAPH_CFLAGS})
TARGET_LINK_LIBRARIES(${EXECUTABLE_NAME} ${DYNAMIC_GRAPH_LIBRARIES})
/*
* Copyright
*/
#include "dynamic-graph-python-test.hh"
int main (int argc, char** argv)
{
GraphTest testGraph();
}