*** empty log message ***
[universe.git] / main.cc
1
2 // Written and (C) by Francois Fleuret
3 // Contact <francois.fleuret@idiap.ch> for comments & bug reports
4
5 #include <iostream>
6 #include <fstream>
7 #include <cmath>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <stdint.h>
11 #include <errno.h>
12 #include <string.h>
13
14 using namespace std;
15
16 #include "misc.h"
17 #include "task.h"
18 #include "simple_window.h"
19 #include "universe.h"
20 #include "retina.h"
21 #include "manipulator.h"
22 #include "intelligence.h"
23
24 // To train
25 // ./main --task hit_shape.task 0 --action-mode=random --nb-ticks=5000 --proportion-for-training=0.5 --save-file=dump.mem --no-window
26
27 // To test
28 // ./main --task hit_shape.task 0 --action-mode=intelligent --load-file=dump.mem
29
30 //////////////////////////////////////////////////////////////////////
31
32 void check_opt(int argc, char **argv, int n_opt, int n, const char *help) {
33   if(n_opt + n >= argc) {
34     cerr << "Missing argument for " << argv[n_opt] << "." << endl;
35     cerr << "Expecting " << help << "." << endl;
36     exit(1);
37   }
38 }
39
40 void print_help_and_exit(int e) {
41   cout << "Arguments:" << endl;
42   cout << "  --no-window" << endl;
43   cout << "  --nb-ticks=<int: number of ticks>" << endl;
44   cout << "  --nb-training-iterations=<int: number of training iterations>" << endl;
45   cout << "  --load-file=<filename: dump file>" << endl;
46   cout << "  --save-file=<filename: dump file>" << endl;
47   cout << "  --proportion-for-training=<float: proportion of samples for training>" << endl;
48   cout << "  --action-mode=<idle|random|intelligent>" << endl;
49   cout << "  --task <filename: task to load> <int: degree>" << endl;
50   exit(e);
51 }
52
53 //////////////////////////////////////////////////////////////////////
54
55 int main(int argc, char **argv) {
56
57   const int buffer_size = 256;
58   char intelligence_load_file[buffer_size] = "", intelligence_save_file[buffer_size] = "";
59
60   Task *task = 0;
61   int task_degree = 0;
62
63   int nb_ticks = 10000;
64   int nb_training_iterations = 10;
65   scalar_t proportion_for_training = -1;
66
67   Polygon *grabbed_polygon = 0;
68   scalar_t relative_grab_x = 0, relative_grab_y = 0;
69
70   bool quit = false;
71   bool press_shift = false;
72   enum { IDLE, RANDOM, INTELLIGENT } action_mode = IDLE;
73   bool got_event = true;
74   int current_action = 0;
75
76   scalar_t last_hand_x = 0, last_hand_y = 0;
77   Polygon *last_grabbing = 0;
78   bool no_window = false;
79
80   //////////////////////////////////////////////////////////////////////
81   //                    Parsing the shell arguments
82   //////////////////////////////////////////////////////////////////////
83
84   int i = 1;
85   while(i < argc) {
86     if(argc == 1 || strcmp(argv[i], "--help") == 0) print_help_and_exit(0);
87
88     else if(strcmp(argv[i], "--test") == 0) {
89       test_approximer();
90       exit(0);
91     }
92
93     else if(strcmp(argv[i], "--task") == 0) {
94       check_opt(argc, argv, i, 2, "<filename: task to load> <int: degree>");
95       if(task) {
96         cerr << "Can not load two tasks." << endl;
97         exit(1);
98       }
99       task = load_task(argv[i+1]);
100       task_degree = atoi(argv[i+2]);
101       i += 3;
102
103     } else if(strncmp(argv[i], "--", 2) == 0) {
104       char variable_name[buffer_size] = "", variable_value[buffer_size] = "";
105       char *o = argv[i]+2, *s = variable_name, *u = variable_value;
106       while(*o && *o != '=') *s++ = *o++;
107       if(*o) {
108         o++;
109         while(*o) *u++ = *o++;
110       }
111
112       if(strcmp(variable_name, "nb-ticks") == 0)
113         nb_ticks = atoi(variable_value);
114       else if(strcmp(variable_name, "nb-training-iterations") == 0)
115         nb_training_iterations = atoi(variable_value);
116       else if(strcmp(variable_name, "proportion-for-training") == 0)
117         proportion_for_training = atof(variable_value);
118       else if(strcmp(variable_name, "no-window") == 0)
119         no_window = true;
120       else if(strcmp(variable_name, "save-file") == 0)
121         strcpy(intelligence_save_file, variable_value);
122       else if(strcmp(variable_name, "load-file") == 0)
123         strcpy(intelligence_load_file, variable_value);
124       else if(strcmp(variable_name, "action-mode") == 0) {
125         if(strcmp(variable_value, "idle") == 0) action_mode = IDLE;
126         else if(strcmp(variable_value, "random") == 0) action_mode = RANDOM;
127         else if(strcmp(variable_value, "intelligent") == 0) action_mode = INTELLIGENT;
128         else {
129           cerr << "The only known modes are idle, random and intelligent" << endl;
130           exit(1);
131         }
132       } else {
133         cerr << "Unknown option " << argv[i] << endl;
134         print_help_and_exit(1);
135       }
136       i++;
137     } else {
138       cerr << "Unknown option " << argv[i] << endl;
139       print_help_and_exit(1);
140     }
141   }
142
143   cout << "FlatLand, a toy universe for goal-planning experiments." << endl;
144   cout << "$Id: main.cc,v 1.89 2007-06-16 13:51:53 fleuret Exp $" << endl;
145
146   if(!task) {
147     task = load_task("dummy.task");
148     task_degree = 0;
149   }
150
151   cout << "Loaded task " << task->name()
152        << " with degree " << task_degree << "/" << task->nb_degrees()
153        << endl;
154
155   if(task_degree < 0 || task_degree >= task->nb_degrees()) {
156     cout << "Invalid degree: " << task_degree << "." << endl;
157     exit(1);
158   }
159
160   //////////////////////////////////////////////////////////////////////
161   //                      Various initializations
162   //////////////////////////////////////////////////////////////////////
163
164   Universe universe(100, task->width(), task->height());
165   task->init(&universe, task_degree);
166   Retina retina(&universe);
167   Manipulator manipulator(task);
168   manipulator.force_move(task->width()/2, task->height()/2);
169   retina.set_location(manipulator.hand_x(), manipulator.hand_y());
170
171   SimpleWindow *window_main = 0, *window_brain = 0;
172
173   int winfd = -1;
174
175   MapConcatener sensory_map(2);
176   sensory_map.add_map(&retina);
177   sensory_map.add_map(&manipulator);
178   sensory_map.init();
179
180   MapExpander expanded_map(1000);
181   expanded_map.set_input(&sensory_map);
182   expanded_map.init();
183
184   Intelligence intelligence(&expanded_map, &manipulator, nb_ticks + 1, nb_training_iterations);
185   intelligence.update(0, 0.0);
186
187   if(intelligence_load_file[0]) {
188     cout << "Loading from " << intelligence_load_file << " ... " ;
189     cout.flush();
190     ifstream in(intelligence_load_file);
191     if(in.fail()) {
192       cerr << "error reading " << intelligence_load_file << "." << endl;
193       exit(1);
194     }
195     intelligence.load(in);
196     cout << "done." << endl ;
197   }
198
199   if(!no_window) {
200     window_main = new SimpleWindow("Universe (main window)", 4, 4, task->width(), task->height());
201     winfd = window_main->file_descriptor();
202     window_main->map();
203     cout << "When the main window has the focus, press `q' to quit and click and drag to move" << endl
204          << "objects." << endl;
205     window_brain = new SimpleWindow("Universe (brain)",
206                                      12 + task->width(), 4,
207                                      retina.width(), retina.height() + manipulator.parameter_height());
208     window_brain->map();
209   } else {
210     cout << "Started without windows." << endl;
211   }
212
213   int tick = 0;
214   time_t last_t = 0;
215   scalar_t sum_reward = 0;
216
217   //////////////////////////////////////////////////////////////////////
218   //                         The main loop
219   //////////////////////////////////////////////////////////////////////
220
221   while(!quit && tick != nb_ticks) {
222
223     int r;
224     fd_set fds;
225
226
227     if(window_main) {
228       struct timeval tv;
229       FD_ZERO (&fds);
230       FD_SET (winfd, &fds);
231       tv.tv_sec = 0;
232       tv.tv_usec = 5000; // 0.05s
233       r = select(winfd + 1, &fds, 0, 0, &tv);
234     } else r = 0;
235
236     time_t t = time(0);
237
238     if(t > last_t) {
239       last_t = t;
240       cout << tick << " " << sum_reward << "              \r"; cout.flush();
241     }
242
243     if(r == 0) { // No window event, thus it's the clock tick
244
245         int nb_it = 10;
246
247         bool changed = got_event;
248         got_event = false;
249
250         switch(action_mode) {
251         case IDLE:
252           break;
253         case RANDOM:
254           current_action = manipulator.random_action();
255           break;
256         case INTELLIGENT:
257           current_action = intelligence.best_action();
258           //           if(drand48() < 0.5) current_action = intelligence.best_action();
259           //           else                current_action = manipulator.random_action();
260           break;
261         }
262
263         manipulator.do_action(current_action);
264
265         scalar_t dt = 1.0/scalar_t(nb_it);
266         for(int k = 0; k < nb_it; k++) {
267           manipulator.update(dt, &universe);
268           task->update(dt, &universe, &manipulator);
269           changed |= universe.update(dt);
270         }
271
272         tick++;
273
274         changed |= manipulator.hand_x() != last_hand_x ||
275           manipulator.hand_y() != last_hand_y ||
276           manipulator.grabbing() != last_grabbing;
277
278         scalar_t reward = task->reward(&universe, &manipulator);
279         sum_reward += abs(reward);
280         intelligence.update(current_action, reward);
281         expanded_map.update_map();
282
283         if(changed) {
284           last_hand_x = manipulator.hand_x();
285           last_hand_y = manipulator.hand_y();
286           last_grabbing = manipulator.grabbing();
287           retina.set_location(manipulator.hand_x(), manipulator.hand_y());
288
289           if(window_main) {
290             window_main->color(0.0, 0.0, 0.0);
291             window_main->fill();
292             task->draw(window_main);
293             universe.draw(window_main);
294             manipulator.draw_on_universe(window_main);
295             retina.draw_on_universe(window_main);
296
297             if(grabbed_polygon) {
298               int x, y, delta = 3;
299               x = int(grabbed_polygon->absolute_x(relative_grab_x, relative_grab_y));
300               y = int(grabbed_polygon->absolute_y(relative_grab_x, relative_grab_y));
301               window_main->color(0.0, 0.0, 0.0);
302               window_main->draw_line(x - delta, y, x + delta, y);
303               window_main->draw_line(x, y - delta, x, y + delta);
304             }
305
306             window_main->show();
307
308             if(window_brain) {
309               retina.draw_parameters(0, 0, window_brain);
310               manipulator.draw_parameters(0, retina.height() + 1, window_brain);
311               window_brain->show();
312             }
313           }
314         }
315
316     } else if(r > 0) { // We got window events, let's process them
317
318       got_event = true;
319
320       if(FD_ISSET(winfd, &fds)) {
321
322         SimpleEvent se;
323
324         do {
325           se = window_main->event();
326
327           switch(se.type) {
328
329           case SimpleEvent::MOUSE_CLICK_PRESS:
330             {
331               switch(se.button) {
332
333               case 1:
334                 if(press_shift) {
335                   manipulator.force_move(se.x, se.y);
336                   manipulator.do_action(Manipulator::ACTION_GRAB);
337                 } else {
338                   grabbed_polygon = universe.pick_polygon(se.x, se.y);
339                   if(grabbed_polygon) {
340                     relative_grab_x = grabbed_polygon->relative_x(se.x, se.y);
341                     relative_grab_y = grabbed_polygon->relative_y(se.x, se.y);
342                   }
343                 }
344                 break;
345               case 4:
346                 {
347                   Polygon *g = universe.pick_polygon(se.x, se.y);
348                   if(g) g->_theta += M_PI/32;
349                 }
350                 break;
351               case 5:
352                 {
353                   Polygon *g = universe.pick_polygon(se.x, se.y);
354                   if(g) g->_theta -= M_PI/32;
355                 }
356                 break;
357               }
358             }
359             break;
360
361           case SimpleEvent::MOUSE_CLICK_RELEASE:
362             switch(se.button) {
363             case 1:
364               if(press_shift) manipulator.do_action(Manipulator::ACTION_RELEASE);
365               else            grabbed_polygon = 0;
366               break;
367             default:
368               break;
369             }
370
371           case SimpleEvent::MOUSE_MOTION:
372             {
373               if(press_shift) manipulator.force_move(se.x, se.y);
374               else {
375                 if(grabbed_polygon) {
376                   scalar_t xf, yf, force_x, force_y, f, fmax = 100;
377                   xf = grabbed_polygon->absolute_x(relative_grab_x, relative_grab_y);
378                   yf = grabbed_polygon->absolute_y(relative_grab_x, relative_grab_y);
379                   force_x = se.x - xf;
380                   force_y = se.y - yf;
381                   f = sqrt(sq(force_x) + sq(force_y));
382                   if(f > fmax) { force_x = (force_x * fmax)/f; force_y = (force_y * fmax)/f; }
383                   grabbed_polygon->apply_force(0.1, xf, yf, force_x, force_y);
384                 }
385               }
386               break;
387             }
388             break;
389
390           case SimpleEvent::KEY_PRESS:
391             {
392               if(strcmp(se.key, "q") == 0) quit = true;
393               else if(strcmp(se.key, "s") == 0) {
394                 retina.save_as_ppm("/tmp/retina.ppm");
395                 cout << "Retina screen shot saved in /tmp/retina.ppm" << endl;
396                 {
397                   ofstream out("/tmp/universe.fig");
398                   universe.print_fig(out);
399                 }
400               }
401               else if(strcmp(se.key, "Shift_L") == 0 || strcmp(se.key, "Shift_R") == 0) press_shift = true;
402
403               else if(strcmp(se.key, "Up") == 0) manipulator.do_action(Manipulator::ACTION_MOVE_UP);
404               else if(strcmp(se.key, "Right") == 0) manipulator.do_action(Manipulator::ACTION_MOVE_RIGHT);
405               else if(strcmp(se.key, "Down") == 0) manipulator.do_action(Manipulator::ACTION_MOVE_DOWN);
406               else if(strcmp(se.key, "Left") == 0) manipulator.do_action(Manipulator::ACTION_MOVE_LEFT);
407               else if(strcmp(se.key, "g") == 0) manipulator.do_action(Manipulator::ACTION_GRAB);
408               else if(strcmp(se.key, "r") == 0) manipulator.do_action(Manipulator::ACTION_RELEASE);
409
410               else if(strcmp(se.key, "space") == 0) {
411                 switch(action_mode) {
412                 case IDLE:
413                   action_mode = RANDOM;
414                   cout << "Switched to random mode" << endl;
415                   break;
416                 case RANDOM:
417                   action_mode = INTELLIGENT;
418                   cout << "Switched to intelligent mode" << endl;
419                   break;
420                 case INTELLIGENT:
421                   cout << "Switched to idle mode" << endl;
422                   action_mode = IDLE;
423                   break;
424                 }
425               }
426
427               else cout << "Undefined key " << se.key << endl;
428             }
429             break;
430
431           case SimpleEvent::KEY_RELEASE:
432             {
433               if(strcmp(se.key, "Shift_L") == 0 || strcmp(se.key, "Shift_R") == 0) press_shift = false;
434             }
435             break;
436
437           default:
438             break;
439
440           }
441         } while(se.type != SimpleEvent::NO_EVENT);
442       } else {
443         cerr << "Error on select: " << strerror(errno) << endl;
444         exit(1);
445       }
446     }
447   }
448
449   if(proportion_for_training > 0) {
450     cout << "Learning ... "; cout.flush();
451     intelligence.learn(proportion_for_training);
452     cout << "done." << endl;
453   }
454
455   if(intelligence_save_file[0]) {
456     cout << "Saving to " << intelligence_save_file << endl; cout.flush();
457     ofstream os(intelligence_save_file);
458     if(os.fail()) {
459       cerr << "error writing " << intelligence_save_file << "." << endl;
460       exit(1);
461     }
462     cout << "done." << endl;
463     intelligence.save(os);
464   }
465
466   delete window_brain;
467   delete window_main;
468
469 }