iCub-main
Loading...
Searching...
No Matches
PredictModule.cpp
Go to the documentation of this file.
1/*
2 * Copyright (C) 2007-2010 RobotCub Consortium, European Commission FP6 Project IST-004370
3 * author: Arjan Gijsberts
4 * email: arjan.gijsberts@iit.it
5 * website: www.robotcub.org
6 * Permission is granted to copy, distribute, and/or modify this program
7 * under the terms of the GNU General Public License, version 2 or any
8 * later version published by the Free Software Foundation.
9 *
10 * A copy of the license can be found at
11 * http://www.robotcub.org/icub/license/gpl.txt
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
16 * Public License for more details
17 */
18
19#include <iostream>
20#include <stdexcept>
21#include <cassert>
22
23#include <yarp/os/Network.h>
24#include <yarp/os/Vocab.h>
25
30
31namespace iCub {
32namespace learningmachine {
33
34bool PredictProcessor::read(yarp::os::ConnectionReader& connection) {
35 if(!this->getMachinePortable().hasWrapped()) {
36 return false;
37 }
38
39 yarp::sig::Vector input;
40 Prediction prediction;
41 bool ok = input.read(connection);
42 if(!ok) {
43 return false;
44 }
45 try {
46 prediction = this->getMachine().predict(input);
47
48 // Event Code
49 if(EventDispatcher::instance().hasListeners()) {
50 PredictEvent pe(input, prediction);
52 }
53 // Event Code
54 } catch(const std::exception& e) {
55 std::cerr << "Error: " << e.what() << std::endl;
56 return false;
57 }
58
59 yarp::os::ConnectionWriter* replier = connection.getWriter();
60 if(replier != (yarp::os::ConnectionWriter*) 0) {
61 prediction.write(*replier);
62 }
63 return true;
64}
65
66
68 if(error != "") {
69 std::cout << "Error: " << error << std::endl;
70 }
71 std::cout << "Available options for prediction module" << std::endl;
72 std::cout << "--help Display this help message" << std::endl;
73 std::cout << "--load file Load serialized machine from a file" << std::endl;
74 std::cout << "--port pfx Prefix for registering the ports" << std::endl;
75 std::cout << "--modelport port Model port of the training module" << std::endl;
76 std::cout << "--commands file Load configuration commands from a file" << std::endl;
77}
78
80 this->registerPort(this->model_in, this->portPrefix + "/model:i");
81 this->registerPort(this->predict_inout, this->portPrefix + "/predict:io");
82 this->predict_inout.setStrict();
83 this->registerPort(this->cmd_in, this->portPrefix + "/cmd:i");
84}
85
87 this->model_in.close();
88 this->cmd_in.close();
89 this->predict_inout.close();
90}
91
93 this->cmd_in.interrupt();
94 this->predict_inout.interrupt();
95 this->model_in.interrupt();
96 return true;
97}
98
99bool PredictModule::configure(yarp::os::ResourceFinder& opt) {
100 // read for the general specifiers:
101 yarp::os::Value* val;
102
103 // cache resource finder
104 this->setResourceFinder(&opt);
105
106 // check for help request
107 if(opt.check("help")) {
108 this->printOptions();
109 return false;
110 }
111
112 // check for port specifier: portSuffix
113 if(opt.check("port", val)) {
114 this->portPrefix = val->asString().c_str();
115 }
116
117 // check for filename to load machine from
118 if(opt.check("load", val)) {
119 this->getMachinePortable().readFromFile(val->asString().c_str());
120 }
121
122 // register ports before connecting
123 this->registerAllPorts();
124
125 // check for model input port specifier and connect if found
126 if(opt.check("modelport", val)) {
127 yarp::os::Network::connect(val->asString().c_str(),
128 this->model_in.where().getName().c_str());
129 }
130
131 // add reader for models
132 this->model_in.setReader(this->machinePortable);
133
134 // add replier for incoming data (prediction requests)
135 this->predict_inout.setReplier(this->predictProcessor);
136
137 // and finally load command file
138 if(opt.check("commands", val)) {
139 this->loadCommandFile(val->asString().c_str());
140 }
141
142 // attach to the incoming command port and terminal
143 this->attach(cmd_in);
144 this->attachTerminal();
145
146 return true;
147}
148
149
150
151bool PredictModule::respond(const yarp::os::Bottle& cmd, yarp::os::Bottle& reply) {
152 bool success = false;
153
154 try {
155 switch(cmd.get(0).asVocab32()) {
156 case yarp::os::createVocab32('h','e','l','p'): // print help information
157 {
158 reply.addVocab32("help");
159
160 reply.addString("Training module configuration options");
161 reply.addString(" help Displays this message");
162 reply.addString(" reset Resets the machine to its current state");
163 reply.addString(" info Outputs information about the machine");
164 reply.addString(" load fname Loads a machine from a file");
165 reply.addString(" cmd fname Loads commands from a file");
166 //reply.addString(this->getMachine()->getConfigHelp().c_str());
167 success = true;
168 break;
169 }
170
171 case yarp::os::createVocab32('c','l','e','a'): // clear the machine
172 case yarp::os::createVocab32('c','l','r'):
173 case yarp::os::createVocab32('r','e','s','e'):
174 case yarp::os::createVocab32('r','s','t'):
175 {
176 this->getMachine().reset();
177 reply.addString("Machine reset.");
178 success = true;
179 break;
180 }
181
182 case yarp::os::createVocab32('i','n','f','o'): // information
183 case yarp::os::createVocab32('s','t','a','t'): // print statistics
184 {
185 reply.addVocab32("help");
186 reply.addString("Machine Information: ");
187 reply.addString(this->getMachine().getInfo().c_str());
188 success = true;
189 break;
190 }
191
192 case yarp::os::createVocab32('l','o','a','d'): // load
193 { // prevent identifier initialization to cross borders of case
194 reply.add(yarp::os::Value::makeVocab32("help"));
195 std::string replymsg = std::string("Loading machine from '") +
196 cmd.get(1).asString().c_str() + "'... " ;
197 if(!cmd.get(1).isString()) {
198 replymsg += "failed";
199 } else {
200 this->getMachinePortable().readFromFile(cmd.get(1).asString().c_str());
201 replymsg += "succeeded";
202 }
203 reply.addString(replymsg.c_str());
204 success = true;
205 break;
206 }
207
208 case yarp::os::createVocab32('c','m','d'): // cmd
209 case yarp::os::createVocab32('c','o','m','m'): // command
210 { // prevent identifier initialization to cross borders of case
211 reply.add(yarp::os::Value::makeVocab32("help"));
212 std::string replymsg;
213 if(!cmd.get(1).isString()) {
214 replymsg = "Please supply a valid filename.";
215 } else {
216 std::string full_fname = this->findFile(cmd.get(1).asString().c_str());
217 replymsg = std::string("Loading commands from '") +
218 full_fname + "'... " ;
219 this->loadCommandFile(full_fname, &reply);
220 replymsg += "succeeded";
221 }
222 reply.addString(replymsg.c_str());
223 success = true;
224 break;
225 }
226
227 default:
228 break;
229
230 }
231 } catch(const std::exception& e) {
232 std::string msg = std::string("Error: ") + e.what();
233 reply.addString(msg.c_str());
234 success = true;
235 }
236 return success;
237}
238
239} // learningmachine
240} // iCub
virtual void raise(IEvent &event)
Raises an IEvent, causing it to be dispatched to each registered IEventListener.
static EventDispatcher & instance()
An instance retrieval method that follows the Singleton pattern.
std::string portPrefix
A prefix path for the ports that will be registered.
virtual void setResourceFinder(yarp::os::ResourceFinder *rf)
Mutator for the locally stored ResourceFinder.
std::string findFile(std::string fname)
Finds the full path to a specified filename using the ResourceFinder.
void registerPort(yarp::os::Contactable &port, std::string name)
Register a port with a given name.
yarp::os::Port cmd_in
An input port for commands.
virtual void loadCommandFile(std::string fname, yarp::os::Bottle *out=(yarp::os::Bottle *) 0)
Reads bottles from a file and sends these one by one to the respond method.
virtual void reset()=0
Forget everything and start over.
virtual Prediction predict(const yarp::sig::Vector &input)=0
Ask the learning machine to predict the output for a given input.
virtual MachinePortable & getMachinePortable()
Retrieve the machine portable machine wrapper.
virtual IMachineLearner & getMachine()
Convenience function to quickly retrieve the machine that is wrapped in the portable machine wrapper.
bool readFromFile(std::string filename)
Reads a wrapped object from a file.
Definition PortableT.h:182
void unregisterAllPorts()
Unregisters all ports used by this module.
yarp::os::BufferedPort< yarp::sig::Vector > predict_inout
Buffered port for the incoming samples and corresponding replies.
MachinePortable machinePortable
A concrete wrapper around a learning machine.
yarp::os::Port model_in
Incoming port for the models from the train module.
void printOptions(std::string error="")
Prints the accepted command line options with an optional error message.
virtual IMachineLearner & getMachine()
Retrieve the machine that is wrapped in the portable machine wrapper.
void registerAllPorts()
Registers all ports used by this module.
virtual bool respond(const yarp::os::Bottle &cmd, yarp::os::Bottle &reply)
virtual bool configure(yarp::os::ResourceFinder &opt)
virtual MachinePortable & getMachinePortable()
Retrieve the machine portable.
PredictProcessor predictProcessor
The processor handling prediction requests.
virtual bool read(yarp::os::ConnectionReader &connection)
A class that represents a prediction result.
Definition Prediction.h:44
bool write(yarp::os::ConnectionWriter &connection) const
Definition Prediction.h:166
bool read(yarp::os::ConnectionReader &connection)
Definition Prediction.h:186
cmd
Definition dataTypes.h:30
bool error
This file contains the definition of unique IDs for the body parts and the skin parts of the robot.