Exemple #1
0
    def __init__(self, coroutine, in_topic, in_typeneme,
                 out_topic, out_typename, *args, **kwargs):
        super(ChainWith, self).__init__()
        self.coroutine = coroutine
        self.in_topic = in_topic
        self.in_typeneme = in_typeneme
        self.out_topic = out_topic
        self.out_typename = out_typename

        pipe = co.pipe([coroutine(*args, **kwargs),
                        co.publisher(self.out_topic, self.out_type)])
        co.PipedSubscriber(self.in_topic, self.in_type, pipe)
Exemple #2
0
    def __init__(self, db_filename):
        """
        Constructor.

        Args:
            db_filename (str): Filename of the Object DB to load.
        """
        super(UncertaintyPublisher, self).__init__()
        self.db_filename = db_filename
        self.db = odbm.ObjectDBHelper(self.db_filename)
        self.numeric_keys = self.numerize_db_keys()
        rospy.on_shutdown(self.shutdown)

        self.summary_pipe = \
            co.pipe([co.mapper(self.summarize_results),
                     co.publisher('prediction_summary', PredictionSummary)])

        # self.entropy_pipe = \
        #     co.pipe([co.mapper(calc_entropy),
        #              co.publisher('predictions_entropy', Uncertainty)])
        # self.margin_pipe = \
        #     co.pipe([co.starmapper(calc_margin, None, self.numerize_array),
        #              co.publisher('predictions_margin', Uncertainty)])
        # self.estimator_pipe = \
        #     co.pipe([co.starmapper(estimate, None, self.numerize_array),
        #              co.publisher('predicted_object', Prediction)])

        # self.pipes = co.splitter(self.entropy_pipe,
        #                          self.margin_pipe,
        #                          self.estimator_pipe,
        #                          self.summary_pipe)

        # co.PipedSubscriber('named_predictions', NamedPredictions, self.pipes)
        co.PipedSubscriber('named_predictions', NamedPredictions,
                           self.summary_pipe)
        rospy.Subscriber('object_database_updated', Bool, self.callback)
from ocular_interaction import ocular_atom_translators as tr
from ocular_interaction import utils

from ocular_msgs.msg import UncertaintyMetric
from dialog_manager_msgs.msg import AtomMsg


def _log_atom(atom_msg):
    """Log an atom message."""
    utils.log_atom(atom_msg, logger=rospy.logdebug)


if __name__ == '__main__':
    try:
        rospy.init_node('ocular_predicted_object_translator')
        rospy.loginfo("Initializing {} Node".format(rospy.get_name()))

        translator = co.starmapper(tr.generic_atom_translator,
                                   atom_name='uncertainty_metric')
        pipe = co.pipe(
            [translator,
             co.do(_log_atom),
             co.publisher('im_atom', AtomMsg)])

        co.PipedSubscriber('predictions_entropy', UncertaintyMetric, pipe)
        co.PipedSubscriber('predictions_margin', UncertaintyMetric, pipe)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
    Returns
    -------
    bool
        A bool indicating whether to ask a question or not.
    """
    randvalue = random.random()
    should_ask = randvalue < jsd_value
    rospy.logdebug("JSD: {}, Randval: {}, Going to Ask?: {}".format(
        jsd_value, randvalue, should_ask))
    return should_ask


pipe = co.pipe([
    co.mapper(jensen_shannon_divergence),
    co.filterer(should_ask_question),
    co.do(lambda _: rospy.loginfo("Going to ask")),
    co.publisher("should_ask_question", Bool)
])

_DEFAULT_NAME = 'al_asker_node'

if __name__ == '__main__':
    try:
        rospy.init_node(_DEFAULT_NAME)
        rospy.loginfo("Initializing {} Node".format(rospy.get_name()))
        co.PipedSubscriber('prediction_summary', PredictionSummary, pipe)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
Exemple #5
0
"""
import roslib
roslib.load_manifest('ocular_interaction')

from functools import partial

import rospy
from rospy_utils import coroutines as co

from ocular_interaction import ocular_action_translators as tr
from dialog_manager_msgs.msg import ActionMsg
from etts_msgs.msg import Utterance

is_action_valid = partial(tr.should_process_action,
                          actor_name="etts",
                          action_name="say_text")

if __name__ == '__main__':
    try:
        rospy.init_node('ocular_etts_translator')
        rospy.loginfo("Initializing {} Node".format(rospy.get_name()))
        pipe = co.pipe([
            co.filterer(is_action_valid),
            co.transformer(tr.action_to_etts),
            co.publisher('etts', Utterance)
        ])
        co.PipedSubscriber('im_action', ActionMsg, pipe)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
    """
    msg_package, msg_name = msg_typename.split('/')
    msg_full_typename = '.'.join([msg_package, 'msg', msg_name])
    return rpyu.load_class(msg_full_typename)


if __name__ == '__main__':
    # TODO: This is highly replicable for filter_node, accumulator, etc.
    #       At some point I will separate all the repeteable parts to a class

    my_args = rospy.myargv(sys.argv)[1:]
    f, in_topic, in_typename, out_topic, out_typename = parse_arguments(
        my_args)
    func = rpyu.load_class(f)
    in_type = get_msg_type(in_typename)
    out_type = get_msg_type(out_typename)

    try:
        rospy.init_node('topic_mapper')
        pipe = co.pipe(
            [co.transformer(func),
             co.publisher(out_topic, out_type)])
        subscriber = co.PipedSubscriber(in_topic, in_type, pipe)
        rospy.loginfo("Node {} successfully started\nIt will map: {}\n"
                      "From: {} ({}) --> To: {} ({})".format(
                          rospy.get_name(), f, in_topic, in_typename,
                          out_topic, out_typename))
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
def _init_node(node_name):
    """Common routines for start a node."""
    rospy.init_node(node_name)
    rospy.loginfo("Initializing {} Node".format(rospy.get_name()))


def _log_predictions(predictions, logger=rospy.loginfo):
    """Log predictions msg to logger."""
    logger("Predictions RGB: {}".format(utils.blue(str(predictions.rgb))))
    logger("Predictions PCloud: {}".format(utils.blue(str(
        predictions.pcloud))))


_DEFAULT_NAME = 'predictions_namer'

if __name__ == '__main__':
    db_filename = rospy.myargv(argv=sys.argv)[1]
    rospy.loginfo("Object Database file: {}".format(utils.blue(db_filename)))
    try:
        _init_node(_DEFAULT_NAME)
        pipe = co.pipe([
            match_names(db_filename),
            co.do(_log_predictions),
            co.publisher('named_predictions', NamedPredictions)
        ])
        co.PipedSubscriber('predictions', Predictions, pipe)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
import rospy
from rospy_utils import coroutines as co

from asr_msgs.msg import open_grammar_recog_results as ASRmsg
from std_msgs.msg import String
from dialog_manager_msgs.msg import AtomMsg
from ocular_interaction import ocular_atom_translators as tr
from ocular_interaction import utils

atom_logger = partial(utils.log_atom, logger=rospy.loginfo)

translator_pipe = co.pipe([
    co.transformer(tr.asr_first_noun_to_atom),
    co.do(atom_logger),
    co.publisher('im_atom', AtomMsg)
])

splitter = co.splitter(co.publisher('nouns_from_asr', String), translator_pipe)


def get_asr_content(asr_msg):
    """
    Return the content of an ASR Msg.

    Example:

    >>> asrmsg = ASRmsg(content='Hello World', confidence=100.0, languageID=0)
    >>> get_asr_content(asrmsg)
    'Hello World'
    """
    >>> msg(data='Hello World!')
    data: Hello World!
    """
    msg_package, msg_name = msg_typename.split('/')
    msg_full_typename = '.'.join([msg_package, 'msg', msg_name])
    return rpyu.load_class(msg_full_typename)

if __name__ == '__main__':
    # TODO: This is highly replicable for filter_node, accumulator, etc.
    #       At some point I will separate all the repeteable parts to a class

    my_args = rospy.myargv(sys.argv)[1:]
    f, in_topic, in_typename, out_topic, out_typename = parse_arguments(my_args)
    func = rpyu.load_class(f)
    in_type = get_msg_type(in_typename)
    out_type = get_msg_type(out_typename)

    try:
        rospy.init_node('topic_mapper')
        pipe = co.pipe([co.transformer(func),
                        co.publisher(out_topic, out_type)])
        subscriber = co.PipedSubscriber(in_topic, in_type, pipe)
        rospy.loginfo("Node {} successfully started\nIt will map: {}\n"
                      "From: {} ({}) --> To: {} ({})"
                      .format(rospy.get_name(),
                              f, in_topic, in_typename,
                              out_topic, out_typename))
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
    try:
        bagy.write(msg)
    except ValueError:
        bname = bagy.name
        rospy.logdebug("Trying to write on closed bagy: {}".format(bname))


def _init_node(node_name):
    """Common routines for start a node."""
    rospy.init_node(node_name)
    rospy.loginfo("Initializing {} Node".format(rospy.get_name()))

_DEFAULT_NAME = 'robot_wardrive'

if __name__ == '__main__':
    bagy_name = rospy.myargv(argv=sys.argv)[1]
    rospy.loginfo("Bagy name is: {}".format(bagy_name))
    bagy = Bagy(bagy_name, 'w', SignalLocation)
    bagy_logger = partial(write_to_bagy, bagy=bagy)
    try:
        _init_node(_DEFAULT_NAME)
        pipe = co.pipe([co.mapper(make_signal_location_msg),
                        co.do(bagy_logger),
                        co.publisher('signal_location', SignalLocation)])
        co.PipedSubscriber('amcl_pose', PoseWithCovarianceStamped, pipe)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
    finally:
        bagy.close()  # Close Bagy no mather how the program ends
Exemple #11
0
 def test_publisher(self, mock_pub):
     co.publisher('my_topic', String).send('Hello World!')
     mock_pub.assert_called()
Exemple #12
0
                          actor_name="object_name_translator",
                          action_name="object_name")


def __get_object_name(string_msg):
    """Get the object name from a std_msgs/String."""
    return String(data=utils.get_first_noun(string_msg.data))


def __log_object_name(string_msg):
    """Log to screen the object name."""
    object_name = utils.normalize_word(string_msg.data)
    rospy.logwarn("Object Name is: {}".format(object_name))


if __name__ == '__main__':
    try:
        rospy.init_node('ocular_object_name_translator')
        rospy.loginfo("Initializing {} Node".format(rospy.get_name()))
        pipe = co.pipe([
            co.filterer(is_action_valid),
            co.transformer(tr.action_to_object_name),
            co.transformer(__get_object_name),
            co.do(__log_object_name),
            co.publisher('object_name', String)
        ])
        co.PipedSubscriber('im_action', ActionMsg, pipe)
        rospy.spin()
    except rospy.ROSInterruptException:
        pass
Exemple #13
0
 def test_publisher(self, mock_pub):
     co.publisher('my_topic', String).send('Hello World!')
     mock_pub.assert_called()
from itertools import ifilter
import rospy
from rospy_utils import coroutines as co
from rospy_utils import param_utils as pu
from asr_msgs.msg import open_grammar_recog_results as ASRmsg
from std_msgs.msg import String
from dialog_manager_msgs.msg import AtomMsg
from ocular_interaction import ocular_atom_translators as tr
from ocular_interaction import utils

atom_logger = partial(utils.log_atom, logger=rospy.loginfo)

translator_pipe = co.pipe([
    co.transformer(tr.user_command_to_atom),
    co.do(atom_logger),
    co.publisher('im_atom', AtomMsg)
])

splitter = co.splitter(co.publisher('asr_command', String), translator_pipe)


def get_command(word, commands):
    """Check wether word is a command from the commands dictionary."""
    try:
        return commands.get(utils.to_infinitive(word), None)
    except UnicodeDecodeError:
        rospy.logwarn(
            "UnicodeDecodeError while stemming word: {}".format(word))


def parse_sentence(sentence, commands):