Added README.md
[dyncnn.git] / flatland.cc
1
2 /*
3  *  dyncnn is a deep-learning algorithm for the prediction of
4  *  interacting object dynamics
5  *
6  *  Copyright (c) 2016 Idiap Research Institute, http://www.idiap.ch/
7  *  Written by Francois Fleuret <francois.fleuret@idiap.ch>
8  *
9  *  This file is part of dyncnn.
10  *
11  *  dyncnn is free software: you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License version 3 as
13  *  published by the Free Software Foundation.
14  *
15  *  dyncnn is distributed in the hope that it will be useful, but
16  *  WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *  General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with dyncnn.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include <iostream>
26 #include <fstream>
27 #include <cmath>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <stdint.h>
31 #include <errno.h>
32 #include <string.h>
33 #include <sys/stat.h>
34 #include <sys/time.h>
35
36 using namespace std;
37
38 #include "misc.h"
39 #include "universe.h"
40 #include "canvas_cairo.h"
41
42 FILE *safe_fopen(const char *name, const char *mode) {
43   FILE *file = fopen(name, mode);
44   if(!file) {
45     cerr << "Cannot open " << name << endl;
46     exit(1);
47   }
48   return file;
49 }
50
51 void print_help(const char *command) {
52   cerr << command << " <nb sequences to generate> [--dir <dir>] [--seed <seed>]]" << endl;
53   exit(1);
54 }
55
56 //////////////////////////////////////////////////////////////////////
57
58 void draw_universe_on_canvas(CanvasCairo *canvas, scalar_t scaling,
59                              Universe *universe) {
60   canvas->set_line_width(1.0 / scaling);
61   universe->draw(canvas);
62 }
63
64 void draw_grabbing_point_on_canvas(CanvasCairo *canvas, scalar_t scaling,
65                                    scalar_t xg, scalar_t yg,
66                                    scalar_t r, scalar_t g, scalar_t b) {
67   scalar_t radius = 1/scaling;
68   int n = 36;
69   scalar_t xp[n], yp[n];
70   for(int k = 0; k < n; k++) {
71     scalar_t alpha = 2 * M_PI * scalar_t(k) / scalar_t(n);
72     xp[k] = xg + radius * cos(alpha);
73     yp[k] = yg + radius * sin(alpha);
74   }
75   canvas->set_drawing_color(r, g, b);
76   canvas->set_line_width(2.0);
77   canvas->draw_polygon(1, n, xp, yp);
78 }
79
80 //////////////////////////////////////////////////////////////////////
81
82 int main(int argc, char **argv) {
83   const scalar_t world_width = 400;
84   const scalar_t world_height = 400;
85   const scalar_t scaling = 0.16; // So that 400 * 0.16 = 64
86
87   const scalar_t dt = 0.1;
88   const int nb_iterations_per_steps = 5;
89
90   //////////////////////////////////////////////////////////////////////
91
92   // We will generate images { 0, every_nth, 2 * every_nth, ..., k * every_nth < nb_frames }
93
94   // The framerate every_nth may be set to smaller value to generate
95   // nice materials for presentations or papers.
96
97   int every_nth = 4;
98   int nb_frames = 5;
99   int random_grasp = 0;
100   int random_shape_size = 0;
101   int nb_shapes = 1;
102   char data_dir[1024] = "/tmp/";
103   int multi_images = 0;
104   int show_grabbing_point = 0;
105   int skip = -1;
106
107   //////////////////////////////////////////////////////////////////////
108
109   if(argc < 2) {
110     print_help(argv[0]);
111   }
112
113   int nb_sequences = atoi(argv[1]);
114
115   int i = 2;
116   while(i < argc) {
117     if(strcmp(argv[i], "--dir") == 0) {
118       i++;
119       if(i == argc) { print_help(argv[0]);}
120       strncpy(data_dir, argv[i], sizeof(data_dir) / sizeof(char) - 1);
121       i++;
122     }
123
124     else if(strcmp(argv[i], "--seed") == 0) {
125       i++;
126       if(i == argc) { print_help(argv[0]); }
127       srand48(atoi(argv[i]));
128       i++;
129     }
130
131     else if(strcmp(argv[i], "--nb_shapes") == 0) {
132       i++;
133       if(i == argc) { print_help(argv[0]);}
134       nb_shapes = atoi(argv[i]);
135       i++;
136     }
137
138     else if(strcmp(argv[i], "--random_grasp") == 0) {
139       random_grasp = 1;
140       i++;
141     }
142
143     else if(strcmp(argv[i], "--random_shape_size") == 0) {
144       random_shape_size = 1;
145       i++;
146     }
147
148     else if(strcmp(argv[i], "--every_nth") == 0) {
149       i++;
150       if(i == argc) { print_help(argv[0]);}
151       every_nth = atoi(argv[i]);
152       i++;
153     }
154
155     else if(strcmp(argv[i], "--nb_frames") == 0) {
156       i++;
157       if(i == argc) { print_help(argv[0]);}
158       nb_frames = atoi(argv[i]);
159       i++;
160     }
161
162     else if(strcmp(argv[i], "--multi_images") == 0) {
163       multi_images = 1;
164       i++;
165     }
166
167     else if(strcmp(argv[i], "--show_grabbing_point") == 0) {
168       show_grabbing_point = 1;
169       i++;
170     }
171
172     else if(strcmp(argv[i], "--skip") == 0) {
173       i++;
174       if(i == argc) { print_help(argv[0]);}
175       skip = atoi(argv[i]);
176       i++;
177     }
178
179     else {
180       cerr << "Unknown option " << argv[i] << "." << endl;
181       abort();
182     }
183   }
184
185   if(nb_shapes < 1 || nb_shapes > 10) {
186     cerr << "nb_shapes has to be in {1, ..., 10}" << endl;
187     abort();
188   }
189
190   if(nb_frames < 0 || nb_frames > 50) {
191     cerr << "nb_frames has to be in {0, ..., 50}" << endl;
192     abort();
193   }
194
195   struct timeval start_time, current_time;
196
197   gettimeofday(&start_time, 0);
198
199   for(int n = 0; n < nb_sequences; n++) {
200
201     Universe *universe;
202     Polygon *grabbed_polygon;
203
204     universe = new Universe(nb_shapes, world_width, world_height);
205
206     const int nb_saved_frames = (nb_frames + every_nth - 1) / every_nth;
207
208     CanvasCairo *canvases[nb_saved_frames * 2];
209
210     for(int s = 0; s < 2 * nb_saved_frames; s++) {
211       canvases[s] = new CanvasCairo(scaling, universe->width(), universe->height());
212     }
213
214     scalar_t grab_start_x, grab_start_y;
215
216     if(random_grasp) {
217       grab_start_x = world_width * (0.1 + 0.8 * drand48());
218       grab_start_y = world_height * (0.1 + 0.8 * drand48());
219     } else {
220       grab_start_x = world_width * 0.5;
221       grab_start_y = world_height * 0.75;
222     }
223
224     if((n+1)%100 == 0) {
225       gettimeofday(&current_time, 0);
226       int estimated_remaining_time =
227         ((nb_sequences - n) * (current_time.tv_sec - start_time.tv_sec)) / n;
228       cout << "Created "
229            << n+1 << "/" << nb_sequences << " sequences in "
230            << data_dir
231            << " (~"
232            << estimated_remaining_time/60 << "min"
233            << estimated_remaining_time%60 << "s remaining)."
234            << endl;
235     }
236
237     do {
238       universe->clear();
239
240       const int nb_attempts_max = 100;
241       int nb_attempts = 0;
242
243       for(int u = 0; u < nb_shapes; u++) {
244         Polygon *pol = 0;
245
246         nb_attempts = 0;
247
248         scalar_t shape_size;
249
250         if(random_shape_size) {
251           shape_size = 40 + 80 * drand48();
252         } else {
253           shape_size = 80;
254         }
255
256         do {
257           scalar_t x[] = { - shape_size * 0.4, + shape_size * 0.4,
258                            + shape_size * 0.4, - shape_size * 0.4 };
259
260           scalar_t y[] = { - shape_size * 0.6, - shape_size * 0.6,
261                            + shape_size * 0.6, + shape_size * 0.6 };
262
263           scalar_t delta = shape_size / sqrt(2.0);
264
265           scalar_t object_center_x = delta + (world_width - 2 * delta) * drand48();
266           scalar_t object_center_y = delta + (world_height - 2 * delta) * drand48();
267
268           delete pol;
269           pol = new Polygon(0.5, 1.0, 1.0, 1.0, x, y, sizeof(x)/sizeof(scalar_t));
270           pol->set_position(object_center_x, object_center_y, M_PI * 2 * drand48());
271           pol->set_speed(0, 0, 0);
272
273           universe->initialize_polygon(pol);
274
275           nb_attempts++;
276         } while(nb_attempts < nb_attempts_max && universe->collide(pol));
277
278         if(nb_attempts == nb_attempts_max) {
279           delete pol;
280           u = -1;
281           universe->clear();
282           nb_attempts = 0;
283         } else {
284           universe->add_polygon(pol);
285         }
286       }
287
288       grabbed_polygon = universe->pick_polygon(grab_start_x, grab_start_y);
289     } while(!grabbed_polygon);
290
291     if(n%1000 == 0) {
292       char buffer[1024];
293       sprintf(buffer, "%s/%03d/", data_dir, n / 1000);
294       mkdir(buffer, 0777);
295     }
296
297     if(skip < 0 || n >= skip) {
298
299       scalar_t grab_relative_x = grabbed_polygon->relative_x(grab_start_x, grab_start_y);
300       scalar_t grab_relative_y = grabbed_polygon->relative_y(grab_start_x, grab_start_y);
301
302       for(int s = 0; s < nb_frames; s++) {
303         if(s % every_nth == 0) {
304           int t = s / every_nth;
305           scalar_t xf = grabbed_polygon->absolute_x(grab_relative_x, grab_relative_y);
306           scalar_t yf = grabbed_polygon->absolute_y(grab_relative_x, grab_relative_y);
307
308           canvases[2 * t + 0]->clear();
309           draw_grabbing_point_on_canvas(canvases[2 * t + 0], scaling,
310                                         xf, yf, 0.0, 0.0, 0.0);
311           canvases[2 * t + 1]->clear();
312           draw_universe_on_canvas(canvases[2 * t + 1], scaling, universe);
313
314           if(show_grabbing_point) {
315             draw_grabbing_point_on_canvas(canvases[2 * t + 1], scaling,
316                                           xf, yf, 1.0, 0.0, 0.0);
317           }
318         }
319
320         if(s < nb_frames - 1) {
321           // Run the simulation
322           for(int i = 0; i < nb_iterations_per_steps; i++) {
323             scalar_t xf = grabbed_polygon->absolute_x(grab_relative_x, grab_relative_y);
324             scalar_t yf = grabbed_polygon->absolute_y(grab_relative_x, grab_relative_y);
325             grabbed_polygon->apply_force(dt, xf, yf, 0.0, -1.0);
326             universe->update(dt);
327           }
328         }
329       }
330
331       char buffer[1024];
332
333       if(multi_images) {
334         for(int j = 0; j < nb_saved_frames; j++) {
335           FILE *file;
336           sprintf(buffer, "%s/%03d/dyn_%06d_grab_%02d.png", data_dir, n / 1000, n, j);
337           file = safe_fopen(buffer, "w");
338           canvases[j * 2 + 0]->write_png(file);
339           fclose(file);
340           sprintf(buffer, "%s/%03d/dyn_%06d_state_%02d.png", data_dir, n / 1000, n, j);
341           file = safe_fopen(buffer, "w");
342           canvases[j * 2 + 1]->write_png(file);
343           fclose(file);
344         }
345       } else {
346         CanvasCairo main_canvas(scaling, nb_saved_frames, 2, canvases);
347         sprintf(buffer, "%s/%03d/dyn_%06d.png", data_dir, n / 1000, n);
348         FILE *file = safe_fopen(buffer, "w");
349         main_canvas.write_png(file);
350         fclose(file);
351       }
352     }
353
354     for(int t = 0; t < 2 * nb_saved_frames; t++) {
355       delete canvases[t];
356     }
357
358     delete universe;
359   }
360 }