iCub-main
Loading...
Searching...
No Matches
test.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 <algorithm>
20#include <string>
21#include <vector>
22#include <cmath>
23#include <iostream>
24#include <sstream>
25#include <fstream>
26#include <stdexcept>
27#include <cassert>
28
29#include <yarp/os/Network.h>
30#include <yarp/os/ResourceFinder.h>
31#include <yarp/os/RFModule.h>
32#include <yarp/sig/Vector.h>
33#include <yarp/os/Port.h>
34#include <yarp/os/BufferedPort.h>
35#include <yarp/os/Time.h>
36#include <yarp/os/Vocab.h>
37
39
40#define TWOPI 6.283185307179586
41
42using namespace yarp::os;
43using namespace yarp::sig;
44
45namespace iCub {
46namespace learningmachine {
47namespace test {
48
49// Prediction and training samples use the same two-vector wire format.
51
52// it's 2011 and I still have to implement a double to string conversion? come on!
53std::string doubletostring(double d) {
54 std::ostringstream output;
55 output << d;
56 return output.str();
57}
58
59std::string inttostring(int i) {
60 std::ostringstream output;
61 output << i;
62 return output.str();
63}
64
65std::string printVector(const std::vector<int>& v) {
66 std::ostringstream output;
67 output << "[";
68 for(unsigned int i = 0; i < v.size(); i++) {
69 if(i > 0) output << ", ";
70 output << v[i];
71 }
72 output << "]";
73 return output.str();
74}
75
76std::string printVector(const Vector& v) {
77 std::ostringstream output;
78 output << "[";
79 for(size_t i = 0; i < v.size(); i++) {
80 if(i > 0) output << ",";
81 output << v[i];
82 }
83 output << "]";
84 return output.str();
85}
86
88 std::ostringstream output;
89 Vector v = p.head;
90 output << "[";
91 for(size_t i = 0; i < v.size(); i++) {
92 if(i > 0) output << ",";
93 output << v[i];
94 }
95 v = p.body;
96 if(v.size() > 0) {
97 output << " +/- ";
98 for(size_t i = 0; i < v.size(); i++) {
99 if(i > 0) output << ",";
100 output << v[i];
101 }
102 }
103 output << "]";
104 return output.str();
105}
106
107
108class Dataset {
109private:
110 int samplesRead;
111 std::ifstream file;
112 std::string filename;
113 std::vector<int> inputCols;
114 std::vector<int> outputCols;
115
116
117public:
119 this->inputCols.resize(1);
120 this->outputCols.resize(1);
121
122 this->inputCols.clear();
123 this->outputCols.clear();
124 }
125
126 // manage input and output columns
127 void addInputColumn(int col) {
128 this->inputCols.push_back(col);
129 }
130
131 void addOutputColumn(int col) {
132 this->outputCols.push_back(col);
133 }
134
135 std::vector<int> getInputColumns() {
136 return this->inputCols;
137 }
138
139 std::vector<int> getOutputColumns() {
140 return this->outputCols;
141 }
142
143 // gets the filename of the open dataset
144 std::string getFilename() {
145 return this->filename;
146 }
147
148 // sets the filename for the dataset
149 void setFilename(std::string filename) {
150 this->filename = filename;
151 }
152
153 // manage file datastream
154 void open() {
155 this->open(this->filename);
156 }
157
158 // open a datafile
159 void open(std::string filename) {
160 // close previous file
161 if(this->file.is_open()) {
162 this->file.close();
163 }
164
165 this->file.open(filename.c_str());
166 if(!file.is_open() || file.fail()) {
167 std::string msg("could not open file '" + filename + "'");
168 this->setFilename("");
169 throw std::runtime_error(msg);
170 return; // will not be reached anyways...
171 }
172 this->setFilename(filename);
173 this->reset();
174 }
175
177 return !this->file.eof() && this->file.good();
178 }
179
180 void reset() {
181 this->samplesRead = 0;
182 this->file.clear();
183 this->file.seekg(0, std::ios::beg);
184 }
185
186 // retrieve new sample from datastream
187 std::pair<Vector,Vector> getNextSample() {
188 Vector input;
189 Vector output;
190
191 int currentCol = 1;
192 double val = 0.0;
193
194 std::string lineString;
195
196 if(!this->hasNextSample()) {
197 throw std::runtime_error("at end of dataset");
198 }
199
200 // find first valid string that does not start with #
201 do {
202 getline(file, lineString);
203 } while(lineString[0] == '#' && !file.eof());
204
205 if(!this->hasNextSample()) {
206 throw std::runtime_error("at end of dataset");
207 }
208
209 // read string as stream buffer
210 std::istringstream lineStream(lineString);
211 while(!lineStream.eof()) {
212 lineStream >> val;
213
214 // add to input sample if appropriate
215 std::vector<int>::iterator inputFind = std::find(this->inputCols.begin(), this->inputCols.end(), currentCol);
216 if(inputFind != this->inputCols.end()) {
217 input.push_back(val);
218 }
219
220 // add to output sample if appropriate
221 std::vector<int>::iterator outputFind = std::find(this->outputCols.begin(), this->outputCols.end(), currentCol);
222 if(outputFind != this->outputCols.end()) {
223 output.push_back(val);
224 }
225 currentCol++;
226 }
227
228 std::pair<Vector,Vector> sample(input, output);
229 return sample;
230 }
231};
232
241
242class MachineLearnerTestModule : public RFModule {
243private:
244 BufferedPort<VectorPair> train_out;
245 Port predict_inout;
246
247 std::string portPrefix;
248
249 Dataset dataset;
250
251 int frequency; // in Hz
252
253 void registerPort(Contactable& port, std::string name) {
254 if(port.open(name.c_str()) != true) {
255 std::string msg("could not register port ");
256 msg+=name;
257 throw std::runtime_error(msg);
258 }
259 }
260
261 void registerAllPorts() {
262 this->registerPort(this->train_out, this->portPrefix + "/train:o");
263 this->train_out.setStrict();
264 this->registerPort(this->predict_inout, this->portPrefix + "/predict:io");
265 }
266
267 void unregisterAllPorts() {
268 this->train_out.close();
269 this->predict_inout.close();
270 }
271
272public:
273 MachineLearnerTestModule(std::string pp = "/lm/test") : portPrefix(pp) {
274
275 }
276
277 void printOptions(std::string error = "") {
278 if(error != "") {
279 std::cout << "Error: " << error << std::endl;
280 }
281 std::cout << "Available options" << std::endl;
282 std::cout << "--help Display this help message" << std::endl;
283 std::cout << "--trainport port Data port for the training samples" << std::endl;
284 std::cout << "--predictport port Data port for the prediction samples" << std::endl;
285 std::cout << "--datafile file Filename containing the dataset" << std::endl;
286 std::cout << "--inputs (idx1, ..) List of indices to use as inputs" << std::endl;
287 std::cout << "--outputs (idx1, ..) List of indices to use as outputs" << std::endl;
288 std::cout << "--port pfx Prefix for registering the ports" << std::endl;
289 std::cout << "--frequency f Sampling frequency in Hz" << std::endl;
290 }
291
292 void printConfig() {
293 std::cout << "* - Configuration -" << std::endl;
294 std::cout << "* Datafile: " << this->dataset.getFilename() << std::endl;
295 std::cout << "* Input columns: " << printVector(this->dataset.getInputColumns()) << std::endl;
296 std::cout << "* Output columns: " << printVector(this->dataset.getOutputColumns()) << std::endl;
297 }
298
299
300 virtual bool configure(ResourceFinder& opt) {
301 // read for the general specifiers:
302 Value* val;
303
304 // check for help request
305 if(opt.check("help")) {
306 this->printOptions();
307 return false;
308 }
309
310 // check for port specifier: portSuffix
311 if(opt.check("port", val)) {
312 this->portPrefix = val->asString().c_str();
313 }
314
315 std::cout << "* Registering ports...";
316 this->registerAllPorts();
317 std::cout << "Done!" << std::endl;
318
319 // check for train data port
320 if(opt.check("trainport", val)) {
321 Network::connect(this->train_out.where().getName().c_str(), val->asString().c_str());
322 } else {
323 // add message here if necessary
324 }
325
326 // check for predict data port
327 if(opt.check("predictport", val)) {
328 Network::connect(this->predict_inout.where().getName().c_str(), val->asString().c_str());
329 } else {
330 // add message here if necessary
331 }
332
333 // check for filename of the dataset
334 if(opt.check("datafile", val)) {
335 //this->dataset.setFilename(val->asString().c_str());
336 this->dataset.open(val->asString().c_str());
337 }
338
339 // check for the columns of the dataset that should be used for inputs
340 if(opt.check("inputs", val)) {
341 // if it's a list,
342 if(val->isList()) {
343 Bottle* inputs = val->asList();
344 for(int i = 0; i < inputs->size(); i++) {
345 if(inputs->get(i).isInt32()) {
346 this->dataset.addInputColumn(inputs->get(i).asInt32());
347 }
348 }
349 } else if(val->isInt32()) {
350 this->dataset.addInputColumn(val->asInt32());
351 }
352 } else {
353 this->dataset.addInputColumn(1);
354 }
355
356 // check for the columns of the dataset that should be used for outputs
357 if(opt.check("outputs", val)) {
358 // if it's a list,
359 if(val->isList()) {
360 Bottle* outputs = val->asList();
361 for(int i = 0; i < outputs->size(); i++) {
362 if(outputs->get(i).isInt32()) {
363 this->dataset.addOutputColumn(outputs->get(i).asInt32());
364 }
365 }
366 } else if(val->isInt32()) {
367 this->dataset.addOutputColumn(val->asInt32());
368 }
369 } else {
370 this->dataset.addOutputColumn(2);
371 }
372
373 // check for port specifier: portSuffix
374 if(opt.check("frequency", val)) {
375 this->frequency = val->asInt32();
376 } else {
377 this->frequency = 0;
378 }
379
380 this->printConfig();
381
382 this->attachTerminal();
383
384 return true;
385 }
386
387 void sendTrainSample(Vector input, Vector output) {
388 VectorPair& sample = this->train_out.prepare();
389 sample.head = input;
390 sample.body = output;
391 this->train_out.writeStrict();
392 }
393
395 Prediction prediction;
396 this->predict_inout.write(input, prediction);
397 return prediction;
398 }
399
401 Time::delay(1.);
402 return true;
403 }
404
405 bool respond(const Bottle& cmd, Bottle& reply) {
406 bool success = false;
407
408 try {
409 switch(cmd.get(0).asVocab32()) {
410 case yarp::os::createVocab32('h','e','l','p'): // print help information
411 success = true;
412 reply.add(Value::makeVocab32("help"));
413
414 reply.addString("Testing module configuration options");
415 reply.addString(" help Displays this message");
416 reply.addString(" conf Print configuration");
417 reply.addString(" train [n] Send training samples");
418 reply.addString(" predict [n] Send testing samples");
419 reply.addString(" skip [n] Skip samples");
420 reply.addString(" reset Reset dataset");
421 reply.addString(" shoot v1 ... vn Shoot a single prediction sample");
422 reply.addString(" open fname Opens a datafile");
423 reply.addString(" freq f Sampling frequency in Hertz (0 for disabled)");
424 break;
425 case yarp::os::createVocab32('c','o','n','f'): // print the configuration
426 {
427 success = true;
428 this->printConfig();
429 break;
430 }
431
432 case yarp::os::createVocab32('s','k','i','p'): // skip some training sample(s)
433 {
434 success = true;
435 int noSamples = 1;
436 if(cmd.get(1).isInt32()) {
437 noSamples = cmd.get(1).asInt32();
438 }
439
440 for(int i = 0; i < noSamples; i++) {
441 std::pair<Vector,Vector> sample = this->dataset.getNextSample();
442 // now do nothing with it... poor sample!
443 }
444 reply.addString("Done!");
445
446 break;
447 }
448
449 case yarp::os::createVocab32('t','r','a','i'): // send training sample(s)
450 {
451 reply.add(Value::makeVocab32("help"));
452 success = true;
453 int noSamples = 1;
454 if(cmd.get(1).isInt32()) {
455 noSamples = cmd.get(1).asInt32();
456 }
457
458 //double start = yarp::os::Time::now();
459 for(int i = 0; i < noSamples; i++) {
460 std::pair<Vector,Vector> sample = this->dataset.getNextSample();
461 this->sendTrainSample(sample.first, sample.second);
462
463 // sleep
464 if(this->frequency > 0)
465 yarp::os::Time::delay(1. / this->frequency);
466 }
467 // this timing only measures how fast the module can dump the samples on the network
468 //double end = yarp::os::Time::now();
469 //std::string reply_str = "Timing: " + doubletostring(noSamples / (end - start)) + " samples per second";
470 //reply.addString(reply_str.c_str());
471 reply.addString("Done!");
472
473 break;
474 }
475
476 case yarp::os::createVocab32('p','r','e','d'): // send prediction sample(s)
477 {
478 reply.add(Value::makeVocab32("help"));
479 success = true;
480 int noSamples = 1;
481 if(cmd.get(1).isInt32()) {
482 noSamples = cmd.get(1).asInt32();
483 }
484
485 // initiate error vector (not completely failsafe!)
486 Vector error(this->dataset.getOutputColumns().size());
487 Vector nmlp(this->dataset.getOutputColumns().size());
488 error = 0.0;
489 nmlp = 0.0;
490
491 // make predictions and keep track of errors (MSE)
492 double start = yarp::os::Time::now();
493 for(int i = 0; i < noSamples; i++) {
494 std::pair<Vector,Vector> sample = this->dataset.getNextSample();
495 Prediction prediction = this->sendPredictSample(sample.first);
496
497 //std::cout << "head[" << prediction.head.size() << "]: " << prediction.head.toString() << std::endl;
498 //std::cout << "variance[" << prediction.body.size() << "]: " << prediction.body.toString() << std::endl;
499
500 Vector expected = prediction.head;
501 if(expected.size() != sample.second.size()) {
502 std::string msg("incoming prediction has incorrect dimension");
503 throw std::runtime_error(msg);
504 }
505 for(size_t j = 0; j < error.size(); j++) {
506 double dist = sample.second[j] - expected[j];
507 error[j] += (dist * dist);
508 }
509
510 Vector variance = prediction.body;
511 if(variance.size() > 0 && variance.size() != sample.second.size()) {
512 std::string msg("incoming predictive variance has invalid dimension");
513 throw std::runtime_error(msg);
514 }
515 for(size_t j = 0; j < nmlp.size(); j++) {
516 double normdist = (sample.second[j] - expected[j]) / variance[j];
517 nmlp[j] += 0.5 * ((normdist * normdist) + log(TWOPI) + 2 * log(variance[j]));
518 }
519
520 // sleep
521 if(this->frequency > 0)
522 yarp::os::Time::delay(1. / this->frequency);
523 }
524 double end = yarp::os::Time::now();
525 std::string reply_str = "Timing: " + doubletostring(noSamples / (end - start)) + " samples per second";
526 reply.addString(reply_str.c_str());
527
528 // take mean of cumulated errors
529 for(size_t i = 0; i < error.size(); i++) {
530 error[i] = error[i] / double(noSamples);
531 }
532 for(size_t i = 0; i < error.size(); i++) {
533 nmlp[i] = nmlp[i] / double(noSamples);
534 }
535
536 reply_str = "MSE: " + printVector(error);
537 reply.addString(reply_str.c_str());
538
539 reply_str = "NMLP: " + printVector(nmlp);
540 reply.addString(reply_str.c_str());
541
542 break;
543 }
544
545 case yarp::os::createVocab32('s','h','o','o'):
546 {
547 success = true;
548 Vector input;
549 for(int i = 1; i <= cmd.size(); i++) {
550 if(cmd.get(i).isFloat64() || cmd.get(i).isInt32()) {
551 input.push_back(cmd.get(i).asFloat64());
552 }
553 }
554 Prediction prediction = this->sendPredictSample(input);
555 std::string reply_str = printVector(input) + " -> " + printPrediction(prediction);
556 reply.addString(reply_str.c_str());
557
558 break;
559 }
560
561 case yarp::os::createVocab32('o','p','e','n'):
562 success = true;
563 if(cmd.get(1).isString()) {
564 std::cout << "Open..." << std::endl;
565 this->dataset.open(cmd.get(1).asString().c_str());
566 }
567 reply.addString((std::string("Opened dataset: ") + cmd.get(1).asString().c_str()).c_str());
568 break;
569
570 case yarp::os::createVocab32('r','e','s','e'):
571 case yarp::os::createVocab32('r','s','t'):
572 success = true;
573 this->dataset.reset();
574 reply.addString("Dataset reset to beginning");
575 break;
576
577 case yarp::os::createVocab32('f','r','e','q'): // set sampling frequency
578 {
579 if(cmd.size() > 1 && cmd.get(1).isInt32()) {
580 success = true;
581 this->frequency = cmd.get(1).asInt32();
582 reply.addString((std::string("Current frequency: ") + inttostring(this->frequency)).c_str());
583 }
584 break;
585 }
586
587 case yarp::os::createVocab32('s','e','t'): // set some configuration options
588 // implement some options
589 break;
590
591 default:
592 break;
593 }
594 } catch(const std::exception& e) {
595 success = true; // to make sure YARP prints the error message
596 std::string msg = std::string("Error: ") + e.what();
597 reply.addString(msg.c_str());
598 } catch(...) {
599 success = true; // to make sure YARP prints the error message
600 std::string msg = std::string("Error. (something bad happened, but I wouldn't know what!)");
601 reply.addString(msg.c_str());
602 }
603
604 return success;
605 }
606
607 bool close() {
608 this->unregisterAllPorts();
609 return true;
610 }
611
612};
613
614} // test
615} // learningmachine
616} // iCub
617
618using namespace iCub::learningmachine::test;
619
620int main(int argc, char *argv[]) {
621 Network yarp;
622 int ret;
623
624 ResourceFinder rf;
625 rf.setDefaultContext("learningMachine");
626 rf.configure(argc, argv);
627
629 try {
630 ret = module.runModule(rf);
631 //module.attachTerminal();
632 } catch(const std::exception& e) {
633 std::cerr << "Error: " << e.what() << std::endl;
634 module.close();
635 return 1;
636 } catch(char* msg) {
637 std::cerr << "Error: " << msg << std::endl;
638 module.close();
639 return 1;
640 }
641 return ret;
642}
#define TWOPI
A pair of vectors using the wire format formerly provided by yarp::os::PortablePair<yarp::sig::Vector...
Definition VectorPair.h:28
void open(std::string filename)
Definition test.cpp:159
std::vector< int > getOutputColumns()
Definition test.cpp:139
std::pair< Vector, Vector > getNextSample()
Definition test.cpp:187
std::vector< int > getInputColumns()
Definition test.cpp:135
void setFilename(std::string filename)
Definition test.cpp:149
The MachineLearnerTestModule is used to feed datasets loaded from a file to the learning machines and...
Definition test.cpp:242
virtual bool configure(ResourceFinder &opt)
Definition test.cpp:300
void sendTrainSample(Vector input, Vector output)
Definition test.cpp:387
bool respond(const Bottle &cmd, Bottle &reply)
Definition test.cpp:405
MachineLearnerTestModule(std::string pp="/lm/test")
Definition test.cpp:273
cmd
Definition dataTypes.h:30
bool error
int main()
Definition main.cpp:67
std::string printPrediction(Prediction &p)
Definition test.cpp:87
std::string printVector(const std::vector< int > &v)
Definition test.cpp:65
std::string doubletostring(double d)
Definition test.cpp:53
std::string inttostring(int i)
Definition test.cpp:59
This file contains the definition of unique IDs for the body parts and the skin parts of the robot.
Copyright (C) 2008 RobotCub Consortium.