]> mj.ucw.cz Git - leo.git/blob - labeller.c
a747552c0b6004ac82123dfa25a52ae01d4ba137
[leo.git] / labeller.c
1 #include <ucw/lib.h>
2 #include <ucw/gary.h>
3 #include <ucw/mempool.h>
4 #include <ucw/eltpool.h>
5
6 #include "leo.h"
7 #include "sym.h"
8 #include "map.h"
9 #include "labeller.h"
10
11 #define HASH_NODE struct graph_node
12 #define HASH_PREFIX(x) hash_##x
13 #define HASH_KEY_ATOMIC id
14 #define HASH_WANT_FIND
15 #define HASH_WANT_NEW
16 #define HASH_WANT_CLEANUP
17 #include <ucw/hashtable.h>
18
19 #include <stdio.h>
20 #include <stdlib.h>
21 #include <math.h>
22 #include <fcntl.h>
23 #include <limits.h>
24
25 #define BLOCK_SIZE 4096
26
27 static struct request_point *requests_point;
28 static struct request_line *requests_line;
29 static struct request_area *requests_area;
30
31 static struct graph_edge **bfs_queue;
32 static struct longline *longlines; int num_longlines;
33 static struct buffer_line *buffer_line;
34 static struct buffer_linelabel *buffer_linelabel;
35
36 struct eltpool *ep_individuals;
37
38 struct individual **population1;
39 struct individual **population2;
40
41 int dbg_segments = VERBOSITY_NONE;
42 int dbg_plan = VERBOSITY_NONE;
43 int dbg_requests = VERBOSITY_NONE;
44 int dbg_graph = VERBOSITY_NONE;
45 int dbg_bfs = VERBOSITY_NONE;
46 int dbg_map_parts = VERBOSITY_NONE;
47 int dbg_movement = VERBOSITY_NONE;
48 int dbg_init = VERBOSITY_NONE;
49 int dbg_overlaps = VERBOSITY_NONE;
50 int dbg_rank = VERBOSITY_NONE;
51 int dbg_evolution = VERBOSITY_INDIVIDUAL;
52 int dbg_mutation = VERBOSITY_NONE;
53 int dbg_breeding = VERBOSITY_NONE;
54
55 int page_width_int;
56 int page_height_int;
57
58 int num_nodes;
59 int num_edges = 0;
60 int dbg_num_hits = 0;
61
62 int conf_pop_size = 50;
63 int conf_fit_size = 1;
64
65 int conf_penalty_bound = 0;
66 int conf_stagnation_bound = 0;
67 int conf_iteration_limit = 100;
68
69 int conf_term_cond = TERM_COND_ITERATIONS;
70
71 double conf_breed_pop_size = 0.4;
72 double conf_breed_rbest = 0.2;
73
74 int breed_pop_size;
75 int breed_rbest_size;
76
77 bool conf_mutate_children = 1;
78 double conf_mutate_children_prob = 1.0;
79
80 double conf_mutate_pop_size = 0.4;
81 double conf_mutate_rbest = 0.2;
82
83 double conf_mutate_move_bound = 0.1;
84 double conf_mutate_regen_bound = 0.0;
85 double conf_mutate_chvar_bound = 0.0;
86
87 int mutate_pop_size;
88 int mutate_rbest_size;
89
90 double conf_elite_pop_size = 0.2;
91 int elite_pop_size;
92
93 double conf_max_section_length = 100;
94 double conf_max_section_overlay = 10;
95
96 int old_best = INT_MAX;
97 int iteration = 0;
98 int pop2_ind;
99
100 // In milimeters
101 int move_min = 0;
102 int move_max = 5;
103
104 int num_requests = 0;
105 int num_placements = 0;
106
107 // In milimeters
108 int conf_map_part_width = 5;
109 int conf_map_part_height = 5;
110
111 uns num_map_parts_row;
112 uns num_map_parts_col;
113 uns num_map_parts;
114
115 void compute_sizes(void);
116
117 void make_population(void);
118 bool shall_terminate(void);
119 void breed(void);
120 void mutate(void);
121 void elite(void);
122 void rank_population(void);
123 void plan_individual(struct individual *individual);
124
125 int overlaps(struct placement *p1, struct placement *p2);
126 int get_overlap(struct placement *p);
127 int individual_overlap(struct individual *individual);
128
129 double get_distance(struct placement *p);
130 double individual_distances(struct individual *individual);
131
132 double get_omittment(struct placement *p);
133 double individual_omittment(struct individual *individual);
134
135 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2);
136 void perform_mutation(struct individual *individual);
137 void init_placement(struct placement *p, struct individual *individual, struct request *r);
138 void init_individual(struct individual *i);
139 void copy_individual(struct individual *src, struct individual *dest);
140 int cmp_individual(const void *a, const void *b);
141
142 void clear_individual(struct individual *individual);
143 void clear_population(struct individual **pop);
144
145 void make_bitmap(struct variant *v, struct symbol *sym);
146 void make_bitmap_icon(struct variant *v, struct sym_icon *si);
147 void make_bitmap_point(struct variant *v, struct sym_point *sp);
148 void make_bitmap_label(struct variant *v, struct sym_text *text);
149
150 double gen_movement(void);
151 double gen_movement_uniform(void);
152 void move_symbol(struct placement *p);
153 void move_symbol_point(struct placement *p);
154 void move_symbol_segment(struct placement *p);
155 void hide_segment_labels(struct individual *individual);
156
157 void gen_coords(struct placement *p);
158 void gen_coords_point(struct placement *p);
159 void gen_coords_segment(struct placement *p);
160 void gen_coords_area(struct placement *p);
161
162 struct map_part **get_map_parts(struct placement *p);
163 void update_map_parts(struct placement *p);
164 struct placement **get_closure(struct placement *placement);
165 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr);
166 struct placement **get_overlapping(struct placement *p);
167 struct placement **filter(struct placement **list, bool **pred_ptr);
168
169
170 void make_graph(void);
171 void label_graph(void);
172 void bfs_wrapper(void);
173 void bfs(uns longline);
174 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir);
175 void make_segments(void);
176
177 void cut_edge(struct graph_edge *e, double dist);
178 struct request_line *make_new_line(void);
179 struct request_section *make_new_section(struct request_line *rl);
180 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym);
181
182 void dump_bitmaps(struct individual *individual);
183 void dump_graph(void);
184 void dump_longlines(void);
185 void dump_linelabel_requests(void);
186 void dump_individual(struct individual *individual);
187 void dump_label(struct symbol *sym);
188 void dump_penalties(struct individual **population);
189
190 int randint(int min, int max);
191 int flip(int a, int b);
192 double randdouble(void);
193
194 int max2(int a, int b);
195 int min2(int a, int b);
196 int max4(int a, int b, int c, int d);
197 int min4(int a, int b, int c, int d);
198
199 struct placement dummy_placement;
200
201 int max2(int a, int b)
202 {
203   return (a > b ? a : b);
204 }
205
206 int min2(int a, int b)
207 {
208   return (a < b ? a : b);
209 }
210
211 int max4(int a, int b, int c, int d)
212 {
213   return max2(max2(a, b), max2(c, d));
214 }
215
216 int min4(int a, int b, int c, int d)
217 {
218   return min2(min2(a, b), min2(c, d));
219 }
220
221 void dump_label(struct symbol *sym)
222 {
223   switch (sym->type)
224   {
225     case SYMBOLIZER_TEXT: ;
226       struct sym_text *st = (struct sym_text *) sym;
227       printf("%s\n", osm_val_decode(st->text));
228     default:
229       // FIXME
230       ;
231   }
232 }
233
234 void labeller_init(void)
235 {
236   GARY_INIT(requests_point, 0);
237   GARY_INIT(requests_line, 0);
238   GARY_INIT(requests_area, 0);
239   GARY_INIT(buffer_line, 0);
240   GARY_INIT(buffer_linelabel, 0);
241   ep_individuals = ep_new(sizeof(struct individual), 1);
242
243   compute_sizes();
244 }
245
246 void make_bitmap(struct variant *v, struct symbol *sym)
247 {
248   v->offset_x = v->offset_y = 0;
249
250   switch (sym->type)
251   {
252     case SYMBOLIZER_POINT:
253       make_bitmap_point(v, (struct sym_point *) sym);
254       break;
255     case SYMBOLIZER_ICON:
256       make_bitmap_icon(v, (struct sym_icon *) sym);
257       break;
258     case SYMBOLIZER_TEXT:
259       make_bitmap_label(v, (struct sym_text *) sym);
260       break;
261     default:
262       ASSERT(sym->type != SYMBOLIZER_INVALID);
263   }
264 }
265
266 void make_bitmap_icon(struct variant *v, struct sym_icon *si)
267 {
268   v->width = si->sir.width + 1;
269   v->height = si->sir.height + 1;
270   v->bitmap = malloc(v->width * v->height * sizeof(bool));
271   for (int i=0; i<v->width*v->height; i++) v->bitmap[i] = 1;
272 }
273
274 void make_bitmap_point(struct variant *v, struct sym_point *sp)
275 {
276   v->width = v->height = sp->size + 1;
277   v->bitmap = malloc(v->width * v->height * sizeof(bool));
278   // FIXME: Okay, memset would be much nicer here
279   for (int i=0; i<sp->size*sp->size; i++) v->bitmap[i] = 1;
280 }
281
282 void make_bitmap_label(struct variant *v, struct sym_text *text)
283 {
284   int tw = ceil(text->tw);
285   int th = ceil(text->th);
286
287   double rotate_rad = text->rotate / (-180 / M_PI);
288
289   // Initially, ll = [0; 0], lr = [tw, 0], ul = [0, th], ur = [tw, th]
290   // They could be declared before but should not be initialized in code
291   // as reassigning x-coordinate affects computation of y-cordinate
292   int llx = 0;
293   int lly = 0;
294
295   int lrx = tw * cos(rotate_rad);
296   int lry = tw * sin(rotate_rad);
297
298   int ulx = th * sin(rotate_rad);
299   int uly = th * cos(rotate_rad);
300
301   int urx = tw * cos(rotate_rad) + th * sin(rotate_rad);
302   int ury = tw * sin(rotate_rad) + th * cos(rotate_rad);
303
304   int min_x = min4(llx, lrx, ulx, urx);
305   int min_y = min4(lly, lry, uly, ury);
306   int max_x = max4(llx, lrx, ulx, urx);
307   int max_y = max4(lly, lry, uly, ury);
308
309   v->width = max_x - min_x + 1;
310   v->height = max_y - min_y + 1;
311   v->bitmap = malloc(v->width * v->height * sizeof(bool));
312   memset(v->bitmap, 0, v->width * v->height * sizeof(bool));
313
314   for (int i=0; i<th; i++)
315   {
316     for (int j=0; j<tw; j++)
317     {
318       int nx = j*cos(rotate_rad) + i*sin(rotate_rad);
319       int ny = j*sin(rotate_rad) + i*cos(rotate_rad);
320       v->bitmap[(ny-min_y)*v->width + (nx-min_x)] = 1;
321     }
322   }
323 }
324
325 void labeller_add_point(struct symbol *sym, struct osm_object *object, z_index_t zindex)
326 {
327   if (dbg_requests >= VERBOSITY_PLACEMENT)
328     printf("Adding point\n");
329   if (object->type != OSM_TYPE_NODE)
330   {
331     printf("Warning: Point label requested on non-point object\n");
332     return;
333   }
334
335   struct request_point *r = GARY_PUSH(requests_point);
336
337   r->request.type = REQUEST_POINT;
338   r->request.ind = num_requests++;
339
340   r->sym = sym;
341   r->zindex = zindex;
342
343   r->offset_x = 0;
344   r->offset_y = 0;
345
346   r->num_variants = 1;
347   GARY_INIT(r->request.variants, 0);
348
349   struct variant *v = GARY_PUSH(r->request.variants);
350
351   struct osm_node *n = (struct osm_node *) object; // FIXME: Compiler warning
352   r->x = n->x;
353   r->y = n->y;
354   make_bitmap(v, sym);
355   switch (sym->type)
356   {
357     case SYMBOLIZER_ICON:
358       // FIXME: Really?
359       r->x = ((struct sym_icon *)sym)->sir.x;
360       r->y = ((struct sym_icon *)sym)->sir.y;
361       break;
362     default:
363       // FIXME
364       return;
365   }
366
367   if (dbg_requests >= VERBOSITY_PLACEMENT)
368     printf("Inited point to [%.2f; %.2f] on %u\n", r->x, r->y, r->zindex);
369 }
370
371 void labeller_add_line(struct symbol *sym, z_index_t zindex)
372 {
373   if (dbg_requests >= VERBOSITY_PLACEMENT)
374     printf("Adding line on %u\n", zindex);
375   struct buffer_line *b = GARY_PUSH(buffer_line);
376   b->line = (struct sym_line *) sym;
377   b->zindex = zindex;
378   sym_plan(sym, zindex);
379 }
380
381 void labeller_add_linelabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
382 {
383   if (o->type != OSM_TYPE_WAY)
384   {
385     printf("Linelabel request on object which is not way\n");
386     return;
387   }
388
389   if (dbg_requests >= VERBOSITY_PLACEMENT)
390     printf("Labelling way %ju on %u\n", o->id, zindex);
391   struct buffer_linelabel *ll = GARY_PUSH(buffer_linelabel);
392   ll->way = (struct osm_way *) o;
393   ll->label = sym;
394   ll->zindex = zindex;
395 }
396
397 void labeller_add_arealabel(struct symbol *sym, struct osm_object *o, z_index_t zindex)
398 {
399   if (dbg_requests >= VERBOSITY_PLACEMENT)
400     printf("Adding area on %u\n", zindex);
401   struct request_area *r = GARY_PUSH(requests_area);
402
403   r->request.type = REQUEST_AREA;
404   r->request.ind = num_requests++;
405
406   r->o = (struct osm_multipolygon *) o;
407   r->zindex = zindex;
408   r->label = sym;
409
410   osm_obj_center(o, &(r->cx), &(r->cy));
411
412   GARY_INIT(r->request.variants, 0);
413   struct variant *v = GARY_PUSH(r->request.variants);
414   make_bitmap(v, sym);
415 }
416
417 void make_graph(void)
418 {
419   hash_init();
420   struct mempool *mp_edges = mp_new(BLOCK_SIZE);
421
422   if (dbg_graph >= VERBOSITY_GENERAL)
423     printf("Extracting nodes, will iterate over %lld ways\n", GARY_SIZE(buffer_line));
424   for (uns i=0; i<GARY_SIZE(buffer_line); i++)
425   {
426     struct osm_way *way = (struct osm_way *) buffer_line[i].line->s.o;
427     struct graph_node *g_prev = NULL;
428     struct osm_node *o_prev = NULL;
429
430     CLIST_FOR_EACH(struct osm_ref *, ref, way->nodes)
431     {
432       // FIXME: Shall osm_object's type be checked here?
433       struct osm_node *o_node = (struct osm_node *) ref->o;
434
435       struct graph_node *g_node = hash_find(ref->o->id);
436       if (!g_node)
437       {
438         g_node = hash_new(ref->o->id);
439         GARY_INIT(g_node->edges, 0);
440         g_node->o = o_node;
441         g_node->id = ref->o->id;
442         g_node->num = num_nodes++;
443       }
444
445       if (! g_prev)
446       {
447         g_prev = g_node;
448         o_prev = o_node;
449         continue;
450       }
451
452       struct graph_edge *e = mp_alloc(mp_edges, sizeof(struct graph_edge));
453       e->num = num_edges++;
454       e->id = buffer_line[i].line->s.o->id;
455       e->color = buffer_line[i].line->color;
456       e->length = hypot(abs(o_prev->x - o_node->x), abs(o_prev->y - o_node->y));
457       e->visited = -1;
458       e->prev = NULL;
459       e->next = NULL;
460       e->n1 = g_prev;
461       e->n2 = g_node;
462       e->longline = (uns) -1;
463       e->line = buffer_line[i].line;
464       e->dir = DIR_UNSET;
465       e->label = NULL;
466
467       struct graph_edge **edge = GARY_PUSH(g_prev->edges);
468       *edge = e;
469       edge = GARY_PUSH(g_node->edges);
470       *edge = e;
471
472       g_prev = g_node;
473       o_prev = o_node;
474     }
475   }
476 }
477
478 void dump_graph(void)
479 {
480   HASH_FOR_ALL(hash, node)
481   {
482     printf("* Node: (%d) #%ju [%.2f; %.2f]\n", node->num, node->id, node->o->x, node->o->y);
483     for (uns i=0; i<GARY_SIZE(node->edges); i++)
484     {
485       struct graph_edge *e = node->edges[i];
486       printf("\t edge (%d) #%ju to ", e->num, e->id);
487       if (node->edges[i]->n1->id == node->id)
488         printf("(%d) #%ju [%.2f; %.2f]\n", e->n2->num, e->n2->id, e->n2->o->x, e->n2->o->y);
489       else if (node->edges[i]->n2->id == node->id)
490         printf("(%d) #%ju [%.2f; %.2f]\n", e->n1->num, e->n1->id, e->n1->o->x, e->n1->o->y);
491       else
492       {
493         // This shouldn't ever happen
494         printf("BEWARE! Edge is associated with a node it doesn't belongs to!\n");
495       }
496
497       printf("\t\t");
498
499       if ((node->edges[i]->label) && (node->edges[i]->label->type == SYMBOLIZER_TEXT)) printf(" labelled %s;", osm_val_decode(((struct sym_text *) node->edges[i]->label)->text));
500       else if ((node->edges[i]->label)) printf("Labelled\n");
501
502       printf(" colored %d;", node->edges[i]->color);
503       printf("   length %.2f", node->edges[i]->length);
504       printf("\n");
505     }
506   }
507   HASH_END_FOR;
508 }
509
510 void label_graph(void)
511 {
512   if (dbg_graph >= VERBOSITY_GENERAL)
513     printf("There are %u line labels requested\n", GARY_SIZE(buffer_linelabel));
514   for (uns i=0; i<GARY_SIZE(buffer_linelabel); i++)
515   {
516     if (buffer_linelabel[i].label->type == SYMBOLIZER_TEXT)
517     if (dbg_graph >= VERBOSITY_INDIVIDUAL)
518       printf("Labelling nodes of way %s\n", osm_val_decode(((struct sym_text *) buffer_linelabel[i].label)->text));
519     CLIST_FOR_EACH(struct osm_ref *, ref, buffer_linelabel[i].way->nodes)
520     {
521       if (dbg_graph >= VERBOSITY_PLACEMENT)
522         printf("Looking for node %ju\n", ref->o->id);
523       struct graph_node *n = hash_find(ref->o->id);
524       if (n == NULL)
525       {
526         printf("BEWARE! Requested node couldn't be found.\n");
527       }
528       else
529       {
530         if (dbg_graph >= VERBOSITY_ALL)
531           printf("Searching among %u edges\n", GARY_SIZE(n->edges));
532         for (uns j=0; j<GARY_SIZE(n->edges); j++)
533         {
534           if (n->edges[j]->id == buffer_linelabel[i].way->o.id)
535           {
536             if (dbg_graph >= VERBOSITY_ALL)
537               printf("Labelling node %ju\n", n->id);
538             n->edges[j]->label = buffer_linelabel[i].label;
539             n->edges[j]->zindex = buffer_linelabel[i].zindex;
540           }
541         }
542       }
543     }
544   }
545 }
546
547 void bfs_edge(struct graph_edge *e, struct graph_node *node, struct graph_node *anode, enum edge_dir dir)
548 {
549   if (dbg_bfs >= VERBOSITY_PLACEMENT)
550     printf("BFS edge called for edge %d (going %d) in direction %d\n", e->num, e->dir, dir);
551   struct graph_edge *candidate = NULL;
552
553   for (uns i=0; i<GARY_SIZE(node->edges); i++)
554   {
555     struct graph_edge *other = node->edges[i];
556     if ((other->longline != (uns) -1) && (other->longline != e->longline)) continue;
557
558     if ((uns) other->visited != e->longline) {
559     if (dbg_bfs >= VERBOSITY_PLACEMENT)
560       printf("Pushing new edge %d / %ju\n", other->num, other->id);
561     struct graph_edge **e_ptr = GARY_PUSH(bfs_queue);
562     *e_ptr = other;
563     other->visited = e->longline;
564     }
565
566     if (((other->n1->id == node->id) && (other->n2->id == anode->id)) ||
567         ((other->n2->id == node->id) && (other->n1->id == anode->id)))
568         continue;
569
570     if (((other->n1->id == node->id) || (other->n2->id == node->id)) &&
571         (e->label) && (other->label) &&
572         (e->label->type == SYMBOLIZER_TEXT) && (other->label->type == SYMBOLIZER_TEXT) &&
573         (((struct sym_text *) e->label)->text == ((struct sym_text *) other->label)->text))
574     {
575       if (! candidate || (other->length > candidate->length))
576       candidate = other;
577     }
578   }
579
580   if (candidate)
581   {
582     if (dbg_bfs >= VERBOSITY_PLACEMENT)
583       printf("New line in longline %u\n", e->longline);
584     struct graph_edge *other = candidate;
585       other->longline = e->longline;
586       other->dir = dir;
587       if (((dir == DIR_BWD) && (other->n1->id == node->id)) ||
588           ((dir == DIR_FWD) && (other->n2->id == node->id)))
589       {
590         struct graph_node *swp = other->n2;
591         other->n2 = other->n1;
592         other->n1 = swp;
593       }
594
595       switch (dir)
596       {
597         case DIR_BWD:
598           e->prev = other;
599           other->next = e;
600           longlines[other->longline].first = other;
601           break;
602         case DIR_FWD:
603           e->next = other;
604           other->prev = e;
605           break;
606         default:
607           printf("Oops\n");
608           ASSERT(0);
609       }
610   }
611 }
612
613 void bfs(uns longline)
614 {
615   if (dbg_bfs >= VERBOSITY_INDIVIDUAL)
616   {
617     printf("BFS called for longline %u\n", longline);
618     printf("%d longlines are believed to exist, %d exist\n", num_longlines, GARY_SIZE(longlines));
619   }
620
621   for (uns i=0; i<GARY_SIZE(bfs_queue); i++)
622   {
623     struct graph_edge *cur = bfs_queue[i];
624     if (dbg_bfs >= VERBOSITY_PLACEMENT)
625       printf("Exploring new edge %d; %d remaining\n", cur->num, GARY_SIZE(bfs_queue));
626
627     cur->visited = longline;
628
629     if (cur->longline == (uns) -1)
630       continue;
631
632     if (cur->dir == DIR_UNSET)
633     {
634       cur->dir = DIR_CENTER;
635       bfs_edge(cur, cur->n1, cur->n2, DIR_BWD);
636       bfs_edge(cur, cur->n2, cur->n1, DIR_FWD);
637     }
638     else
639     {
640       switch (cur->dir)
641       {
642         case DIR_BWD:
643           bfs_edge(cur, cur->n1, cur->n2, cur->dir);
644           break;
645         case DIR_FWD:
646           bfs_edge(cur, cur->n2, cur->n1, cur->dir);
647           break;
648         default:
649           // FIXME
650           ;
651       }
652     }
653   }
654 }
655
656 void bfs_wrapper(void)
657 {
658   GARY_INIT(bfs_queue, 0);
659   GARY_INIT(longlines, 0);
660
661   HASH_FOR_ALL(hash, node)
662   {
663     for (uns i=0; i<GARY_SIZE(node->edges); i++)
664     {
665       if ((node->edges[i]->label) && (node->edges[i]->longline == (uns) -1))
666       {
667         GARY_PUSH(longlines);
668         longlines[num_longlines].first = node->edges[i];
669
670         if (dbg_bfs >= VERBOSITY_INDIVIDUAL)
671         {
672           printf("Running new BFS\n");
673           printf("Creating longline %u\n", num_longlines);
674         }
675
676         GARY_RESIZE(bfs_queue, 0);
677         struct graph_edge **e = GARY_PUSH(bfs_queue);
678         *e = node->edges[i];
679         node->edges[i]->longline = num_longlines;
680         bfs(node->edges[i]->longline);
681
682         if (dbg_bfs >= VERBOSITY_INDIVIDUAL)
683         {
684           printf("Joined %d edges\n", dbg_num_hits); dbg_num_hits = 0;
685           printf("Planned %u edges\n", GARY_SIZE(bfs_queue));
686         }
687         num_longlines++;
688       }
689     }
690   }
691   HASH_END_FOR;
692
693   GARY_FREE(bfs_queue);
694 }
695
696 void dump_longlines(void)
697 {
698   printf("*** Longlines dump\n");
699   for (uns i=0; i<GARY_SIZE(longlines); i++)
700   {
701     printf("Longline %u:", i);
702     struct graph_edge *e = longlines[i].first;
703     if ((e->label) && (e->label->type == SYMBOLIZER_TEXT))
704       printf(" labelled %s", osm_val_decode(((struct sym_text *) e->label)->text));
705     printf("\n");
706
707     while (e)
708     {
709       printf("\t#%ju (%d): [%.2f; %.2f] -- [%.2f; %.2f] (dir %d)\n",
710              e->id, e->num, e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->dir);
711
712       e = e->next;
713     }
714   }
715 }
716
717 struct request_line *make_new_line(void)
718 {
719   struct request_line *rl = GARY_PUSH(requests_line);
720   rl->request.ind = num_requests++;
721   rl->request.type = REQUEST_LINE;
722   GARY_INIT(rl->sections, 0);
723   GARY_INIT(rl->request.variants, 0);
724
725   return rl;
726 }
727
728 struct request_section *make_new_section(struct request_line *rl)
729 {
730   struct request_section *rls = GARY_PUSH(rl->sections);
731   rls->request.ind = num_requests++;
732   rls->request.type = REQUEST_SECTION;
733   rls->num_segments = 0;
734   GARY_INIT(rls->segments, 0);
735   GARY_INIT(rls->request.variants, 0);
736
737   return rls;
738 }
739
740 struct request_segment *make_new_segment(struct request_section *rls, struct symbol *sym)
741 {
742   struct request_segment *rs = GARY_PUSH(rls->segments);
743   rls->num_segments++;
744
745   rs->request.ind = num_requests++;
746   rs->request.type = REQUEST_SEGMENT;
747
748   GARY_INIT(rs->request.variants, 0);
749   if (sym)
750   {
751     struct variant *v = GARY_PUSH(rs->request.variants);
752     make_bitmap(v, sym);
753   }
754
755   return rs;
756 }
757
758 void cut_edge(struct graph_edge *e, double dist)
759 {
760   if (dbg_segments >= VERBOSITY_PLACEMENT)
761     printf("Cutting [%.2f; %.2f] -- [%.2f; %.2f] to dist %.2f\n", e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, dist);
762
763   struct graph_edge *new = malloc(sizeof(struct graph_edge));
764   *new = *e;
765   e->next = new;
766
767   switch (e->label->type)
768   {
769     case SYMBOLIZER_TEXT:
770       new->label = malloc(sizeof(struct sym_text));
771       *((struct sym_text *) new->label) = *((struct sym_text *) e->label);
772       break;
773     default:
774       ;
775   }
776
777   struct osm_node *n1 = e->n1->o;
778   struct osm_node *n2 = e->n2->o;
779
780   if ((n1->x == n2->x) && (n1->y == n2->y))
781   {
782     printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", n1->x, n1->y, n2->x, n2->y);
783     if (dbg_segments >= VERBOSITY_PLACEMENT)
784       printf("Won't cut point\n");
785     return;
786   }
787
788   struct osm_node *n11 = malloc(sizeof(struct osm_node));
789   struct graph_node *gn = malloc(sizeof(struct graph_node));
790   gn->o = n11;
791   double vsize = sqrt(pow(n1->x - n2->x, 2) + pow(n1->y - n2->y, 2));
792   n11->x = n1->x + (n2->x - n1->x) / vsize * dist;
793   n11->y = n1->y + (n2->y - n1->y) / vsize * dist;
794
795   e->n2 = new->n1 = gn;
796
797   e->length = hypot(abs(n1->x - n11->x), abs(n1->y - n11->y));
798   new->length = hypot(abs(n11->x - n2->x), abs(n11->y - n2->y));
799   new->visited = 0;
800 }
801
802 void make_segments(void)
803 {
804   for (uns i=0; i<GARY_SIZE(longlines); i++)
805   {
806     // Skip lines which are not labelled
807     if (! (longlines[i].first && longlines[i].first->label))
808       continue;
809
810     struct request_line *request = make_new_line();
811     struct request_section *rls = make_new_section(request);
812     struct request_segment *rs = NULL;
813
814     struct graph_edge *e = longlines[i].first;
815     double cur_length = 0;
816
817     struct sym_text *st = NULL;
818     if (e->label->type == SYMBOLIZER_TEXT)
819     {
820       st = (struct sym_text *) e->label;
821     }
822     else
823     {
824       // FIXME: Should other label types be supported in future?
825       if (dbg_segments >= VERBOSITY_PLACEMENT)
826         printf("Warning: Skipping line\n");
827       continue;
828     }
829
830     if (dbg_segments >= VERBOSITY_INDIVIDUAL)
831       printf("New longline\n");
832
833     while (e)
834     {
835       if (e->visited < 0)
836       {
837         if (dbg_segments >= VERBOSITY_PLACEMENT)
838           printf("BEWARE: Edge cycle\n");
839         break;
840       }
841       e->visited = -1;
842
843       if (dbg_segments >= VERBOSITY_PLACEMENT)
844         printf("Taking edge from [%.2f; %.2f] to [%.2f; %.2f] of length %.2f\n", e->n1->o->x, e->n1->o->y, e->n2->o->x, e->n2->o->y, e->length);
845
846       if (st && (e->length < st->tw))
847       {
848         e = e->next;
849         if (dbg_segments >= VERBOSITY_PLACEMENT)
850           printf("Warning: Skipping segment\n");
851         continue;
852       }
853
854       if (cur_length + e->length > conf_max_section_length + conf_max_section_overlay)
855       {
856         if (dbg_segments >= VERBOSITY_PLACEMENT)
857           printf("Edge too long, length is %.2f; %.2f - %.2f = %.2f\n", e->length, conf_max_section_length, cur_length, conf_max_section_length - cur_length);
858         // HACK to prevent cutting to 0 lenght
859         cut_edge(e, max2(conf_max_section_length - cur_length, 2));
860       }
861
862       rs = make_new_segment(rls, NULL);
863       rs->label = malloc(sizeof(struct sym_text));
864       *((struct sym_text *) rs->label) = *((struct sym_text *) e->label);
865
866       rs->x1 = e->n1->o->x;
867       rs->y1 = e->n1->o->y;
868       rs->x2 = e->n2->o->x;
869       rs->y2 = e->n2->o->y;
870
871       rs->slope = (rs->y2 - rs->y1) / (rs->x2 - rs->x1);
872       ((struct sym_text *) rs->label)->rotate = atan(rs->slope) * (-180 / M_PI);
873       struct variant *v = GARY_PUSH(rs->request.variants);
874       printf("Request %d\n", rs->request.ind);
875       make_bitmap(v, rs->label);
876
877       rs->zindex = e->zindex;
878
879       cur_length += e->length;
880       if (cur_length > conf_max_section_length)
881       {
882         if (dbg_segments >= VERBOSITY_PLACEMENT)
883           printf("Making new section, new length would be %f, allowed is %.2f / %.2f\n", cur_length + e->length, conf_max_section_length, conf_max_section_overlay);
884
885         rls = make_new_section(request);
886         cur_length = 0;
887       }
888
889       e = e->next;
890     }
891
892     if (request->sections[0].num_segments == 0)
893     {
894       if (dbg_segments >= VERBOSITY_INDIVIDUAL)
895         printf("WARNING: Longline without any segment, skipped\n");
896
897       struct request_section *rls = &request->sections[0];
898       GARY_FREE(rls->segments);
899       GARY_FREE(rls->request.variants);
900
901       struct request_line *rl = &requests_line[GARY_SIZE(requests_line)-1];
902       GARY_FREE(rl->sections);
903       GARY_FREE(rl->request.variants);
904
905       GARY_POP(requests_line);
906       num_requests -= 2;
907     }
908   }
909 }
910
911 void dump_linelabel_requests(void)
912 {
913   for (uns i=0; i<GARY_SIZE(requests_line); i++)
914   {
915     if (requests_line[i].sections[0].num_segments == 0)
916     {
917       if (dbg_segments >= VERBOSITY_INDIVIDUAL)
918         printf("Beware: Longline without any segment\n");
919       continue;
920     }
921
922     printf("Request for linelabel, %d sections\n", GARY_SIZE(requests_line[i].sections));
923     dump_label(requests_line[i].sections[0].segments[0].label);
924     for (uns j=0; j<GARY_SIZE(requests_line[i].sections); j++)
925     {
926       printf("%d section, %d segments\n", j, GARY_SIZE(requests_line[i].sections[j].segments));
927       for (uns k=0; k<GARY_SIZE(requests_line[i].sections[j].segments); k++)
928       {
929         struct request_segment *rs = &requests_line[i].sections[j].segments[k];
930         printf("[%.2f; %.2f] -- [%.2f; %.2f]\n", rs->x1, rs->y1, rs->x2, rs->y2);
931       }
932     }
933     printf("\n");
934   }
935 }
936
937 void dump_bitmaps(struct individual *individual)
938 {
939   bool *bitmap = malloc(page_width_int * page_height_int * sizeof(bool));
940   printf("Bitmap size is %d\n", page_width_int * page_height_int);
941   for (int i=0; i<page_height_int; i++)
942     for (int j=0; j<page_width_int; j++)
943       bitmap[i*page_width_int + j] = 0;
944
945   int total = 0;
946   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
947   {
948     if (individual->placements[i].variant_used == -1) continue;
949
950     struct placement *p = &(individual->placements[i]);
951     struct variant *v = NULL;
952
953     switch (p->request->type)
954     {
955       case REQUEST_SEGMENT: ;
956       case REQUEST_POINT: ;
957       case REQUEST_AREA: ;
958         v = &(p->request->variants[p->variant_used]);
959         break;
960       default:
961         ASSERT(p->request->type != REQUEST_INVALID);
962         continue;
963     }
964
965     int base_x = p->x; int base_y = p->y;
966     for (int dr = max2(0, 0-p->y); dr < v->height; dr++)
967     {
968       for (int dc = max2(0, 0-p->x); dc < v->width; dc++)
969       {
970         if (v->bitmap[dr * v->width + dc])
971         {
972           if (bitmap[(base_y + dr) * page_width_int + (base_x + dc)]) total += 1;
973           bitmap[(base_y + dr) * page_width_int + (base_x + dc)] = 1;
974         }
975       }
976     }
977   }
978   if (dbg_overlaps >= VERBOSITY_GENERAL)
979     printf("There were %d collisions during bitmap dump\n", total);
980
981   FILE *fd_dump = fopen("dump.pbm", "w");
982   fprintf(fd_dump, "P1\n");
983   fprintf(fd_dump, "%d %d\n", page_width_int, page_height_int);
984   for (int i=0; i<page_height_int; i++)
985   {
986     for (int j=0; j<page_width_int; j++)
987     {
988       fprintf(fd_dump, "%d", bitmap[(int) (i*page_width_int + j)] ? 1 : 0);
989     }
990     fprintf(fd_dump, "\n");
991   }
992   fclose(fd_dump);
993
994   free(bitmap);
995 }
996
997 void dump_individual(struct individual *individual)
998 {
999   printf("*** Individual dump\n");
1000   printf("(There are %d requests)\n", num_requests);
1001
1002   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1003   {
1004     struct placement *p = &(individual->placements[i]);
1005
1006     switch (p->request->type)
1007     {
1008       case REQUEST_POINT:
1009         printf("Point at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_point *) p->request)->zindex);
1010         break;
1011       case REQUEST_LINE: ;
1012         struct request_line *rl = (struct request_line *) p->request;
1013         printf("Line: ");
1014         dump_label(rl->sections[0].segments[0].label);
1015         break;
1016       case REQUEST_SECTION: ;
1017         printf("*");
1018         break;
1019       case REQUEST_SEGMENT: ;
1020         if (p->variant_used >= 0)
1021           printf("Segment placed at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_segment *) p->request)->zindex);
1022         else
1023           printf("Segment not placed\n");
1024         break;
1025       case REQUEST_AREA: ;
1026         struct request_area *ra = (struct request_area *) p->request;
1027         printf("Area label ");
1028         dump_label(ra->label);
1029         printf(" at [%.2f; %.2f] on %u\n", p->x, p->y, ((struct request_area *) p->request)->zindex);
1030         break;
1031       default:
1032         ASSERT(p->request->type != 0);
1033     }
1034   }
1035   printf("\nTotal penalty: %d\n", individual->penalty);
1036 }
1037
1038 void plan_individual(struct individual *individual)
1039 {
1040   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1041   {
1042     struct symbol *s = NULL;
1043     z_index_t zindex = 0;
1044     if (individual->placements[i].variant_used < 0) continue;
1045     switch (individual->placements[i].request->type)
1046     {
1047       case REQUEST_POINT: ;
1048         struct request_point *rp = (struct request_point *) individual->placements[i].request;
1049         s = rp->sym;
1050         zindex = rp->zindex;
1051         break;
1052       case REQUEST_SEGMENT: ;
1053         struct request_segment *rs = (struct request_segment *) individual->placements[i].request;
1054         s = rs->label;
1055         zindex = rs->zindex;
1056         break;
1057       case REQUEST_LINE: ;
1058         break;
1059       case REQUEST_AREA: ;
1060         struct request_area *ra = (struct request_area *) individual->placements[i].request;
1061         s = ra->label;
1062         zindex = ra->zindex;
1063         break;
1064       default:
1065         ASSERT(individual->placements[i].request != REQUEST_INVALID);
1066         continue;
1067     }
1068
1069   if (dbg_plan >= VERBOSITY_PLACEMENT)
1070     printf("Will plan symbol at [%.2f; %.2f] on %u\n", individual->placements[i].x, individual->placements[i].y, zindex);
1071
1072     if (s) switch (s->type)
1073     {
1074       case SYMBOLIZER_POINT: ;
1075         struct sym_point *sp = (struct sym_point *) s;
1076         sp->x = individual->placements[i].x;
1077         sp->y = individual->placements[i].y;
1078         sym_plan((struct symbol *) sp, zindex);
1079         break;
1080       case SYMBOLIZER_ICON: ;
1081         struct sym_icon *si = (struct sym_icon *) s;
1082         si->sir.x = individual->placements[i].x;
1083         si->sir.y = individual->placements[i].y;
1084         sym_plan((struct symbol *) si, zindex);
1085         break;
1086       case SYMBOLIZER_TEXT: ;
1087         struct sym_text *st = (struct sym_text *) s;
1088         st->x = individual->placements[i].x;
1089         st->y = individual->placements[i].y;
1090         st->next_duplicate = NULL;
1091         if (dbg_plan >= VERBOSITY_PLACEMENT)
1092           printf("Planning text %s at [%.2f; %.2f] on %u, with rotation %.2f\n", osm_val_decode(st->text), st->x, st->y, zindex, st->rotate);
1093         sym_plan((struct symbol *) st, zindex);
1094         break;
1095       default:
1096         ASSERT(s->type != SYMBOLIZER_INVALID);
1097     }
1098   }
1099 }
1100
1101 void dump_penalties(struct individual **population)
1102 {
1103   for (int i=0; i<conf_pop_size; i++)
1104   {
1105     printf("Individual %d has penalty %d\n", i, population[i]->penalty);
1106   }
1107 }
1108
1109 void compute_sizes(void)
1110 {
1111   page_width_int = floor(page_width);
1112   page_height_int = floor(page_height);
1113
1114   num_map_parts_row = (page_width_int + conf_map_part_width) / conf_map_part_width;
1115   num_map_parts_col = (page_height_int + conf_map_part_height) / conf_map_part_height;
1116   num_map_parts = num_map_parts_row * num_map_parts_col;
1117
1118   breed_pop_size = conf_breed_pop_size * conf_pop_size;
1119   breed_rbest_size = conf_breed_rbest * conf_pop_size;
1120   if (dbg_evolution >= VERBOSITY_GENERAL)
1121   {
1122     printf("Breeding parameters:\n");
1123     printf(" %d individuals are created\n", breed_pop_size);
1124     printf(" %d best individuals in old population are considered\n", breed_rbest_size);
1125   }
1126
1127   mutate_pop_size = conf_mutate_pop_size * conf_pop_size;
1128   mutate_rbest_size = conf_mutate_rbest * conf_pop_size;
1129   if (dbg_evolution >= VERBOSITY_GENERAL)
1130   {
1131     printf("Mutation parameters:\n");
1132     printf(" %d individuals are created\n", mutate_pop_size);
1133     printf(" %d best individuals in old population are considered\n", mutate_rbest_size);
1134   }
1135
1136   elite_pop_size = conf_elite_pop_size * conf_pop_size;
1137   if (dbg_evolution >= VERBOSITY_GENERAL)
1138   {
1139     printf("Elitism parameters:\n");
1140     printf(" %d best individuals are copied\n", elite_pop_size);
1141   }
1142
1143   if (breed_pop_size + mutate_pop_size + elite_pop_size != conf_pop_size)
1144   {
1145     if (conf_fit_size)
1146     {
1147       elite_pop_size += conf_pop_size - (breed_pop_size + mutate_pop_size + elite_pop_size);
1148     }
1149     else
1150     {
1151       fprintf(stderr, "Breeding + mutation + elitism won't create correct number of individuals\n");
1152       fprintf(stderr, "Please fix conf_breed_pop_size, conf_mutate_pop_size and conf_elite_pop_size parameters\n");
1153       exit(2);
1154     }
1155   }
1156 }
1157
1158 void labeller_label(void)
1159 {
1160   make_graph();
1161   label_graph();
1162   bfs_wrapper();
1163   make_segments();
1164
1165   GARY_INIT(population1, conf_pop_size);
1166   GARY_INIT(population2, conf_pop_size);
1167   make_population();
1168   rank_population();
1169   qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1170
1171   if (dbg_evolution >= VERBOSITY_GENERAL)
1172   {
1173     printf("Penalties after initialization\n");
1174     dump_penalties(population1);
1175   }
1176
1177   while (! shall_terminate())
1178   {
1179     iteration++;
1180     if (dbg_evolution)
1181       printf("\n*** Iteration %d ***\n", iteration);
1182
1183     breed();
1184     mutate();
1185     elite();
1186
1187     struct individual **swp = population1;
1188     population1 = population2;
1189     population2 = swp;
1190     pop2_ind = 0;
1191     clear_population(population2);
1192
1193     rank_population();
1194
1195     if (dbg_evolution >= VERBOSITY_GENERAL)
1196       printf("Sorting population\n");
1197     qsort(population1, conf_pop_size, sizeof(struct individual *), cmp_individual);
1198
1199     if (dbg_evolution >= VERBOSITY_GENERAL)
1200     {
1201       printf("Penalties after sort\n");
1202       dump_penalties(population1);
1203     }
1204
1205     old_best = population1[0]->penalty;
1206   }
1207
1208   if (dbg_overlaps >= VERBOSITY_GENERAL)
1209     dump_bitmaps(population1[0]);
1210
1211   plan_individual(population1[0]);
1212
1213   labeller_cleanup();
1214
1215   return;
1216 }
1217
1218 void labeller_cleanup(void)
1219 {
1220   hash_cleanup();
1221   GARY_FREE(requests_point);
1222   GARY_FREE(requests_line);
1223   GARY_FREE(requests_area);
1224 }
1225
1226 void make_population(void)
1227 {
1228   for (int i=0; i<conf_pop_size; i++)
1229   {
1230     num_placements = 0; // FIXME: This IS a terrible HACK
1231     struct individual *i2 = ep_alloc(ep_individuals);
1232     init_individual(i2);
1233     population2[i] = i2;
1234
1235     if (dbg_init >= VERBOSITY_INDIVIDUAL)
1236       printf("Making individual %d\n", i);
1237     struct individual *individual = ep_alloc(ep_individuals); init_individual(individual);
1238     population1[i] = individual;
1239
1240     int p = 0;
1241     for (uns j=0; j<GARY_SIZE(requests_point); j++)
1242     {
1243       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_point[j]);
1244     }
1245
1246     for (uns j=0; j<GARY_SIZE(requests_line); j++)
1247     {
1248       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j]);
1249
1250       for (uns k=0; k<GARY_SIZE(requests_line[j].sections); k++)
1251       {
1252         init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k]);
1253
1254         for (uns l=0; l<GARY_SIZE(requests_line[j].sections[k].segments); l++)
1255         {
1256           init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_line[j].sections[k].segments[l]);
1257         }
1258       }
1259     }
1260
1261     for (uns j=0; j<GARY_SIZE(requests_area); j++)
1262     {
1263       init_placement(&(individual->placements[p++]), individual, (struct request *) &requests_area[j]);
1264     }
1265
1266     hide_segment_labels(individual);
1267
1268     ASSERT(p == num_requests);
1269   }
1270 }
1271
1272 bool shall_terminate(void)
1273 {
1274   switch (conf_term_cond)
1275   {
1276     case TERM_COND_PENALTY:
1277       return (population1[0]->penalty < conf_penalty_bound);
1278     case TERM_COND_STAGNATION:
1279       return (abs(old_best - population1[0]->penalty) < conf_stagnation_bound);
1280     case TERM_COND_ITERATIONS:
1281       return (iteration >= conf_iteration_limit);
1282     default:
1283       fprintf(stderr, "Warning: No termination condition is set, terminating\n");
1284       return 1;
1285   }
1286 }
1287
1288 void breed(void)
1289 {
1290   int i=0;
1291
1292   struct individual **breed_buffer;
1293   while (i < breed_pop_size)
1294   {
1295     int parent1 = randint(0, breed_rbest_size);
1296     int parent2 = randint(0, breed_rbest_size);
1297     if (dbg_breeding >= VERBOSITY_INDIVIDUAL)
1298       printf("Will breed %d and %d\n", parent1, parent2);
1299
1300     breed_buffer = perform_crossover(population1[parent1], population1[parent2]);
1301     population2[pop2_ind++] = breed_buffer[0];
1302     population2[pop2_ind++] = breed_buffer[1];
1303     free(breed_buffer);
1304     i += 2;
1305   }
1306
1307   return;
1308 }
1309
1310 struct individual **perform_crossover(struct individual *parent1, struct individual *parent2)
1311 {
1312   struct individual **buffer = malloc(2*sizeof(struct individual));
1313   struct individual *child1 = ep_alloc(ep_individuals); init_individual(child1);
1314   struct individual *child2 = ep_alloc(ep_individuals); init_individual(child2);
1315
1316   bool *processed;
1317   GARY_INIT_ZERO(processed, GARY_SIZE(parent1->placements));
1318
1319   for (uns i=0; i<GARY_SIZE(parent1->placements); i++)
1320   {
1321     if (! processed[parent1->placements[i].ind])
1322     {
1323       if (dbg_breeding >= VERBOSITY_PLACEMENT)
1324         printf("Creating symbol closure for placement %u\n", i);
1325
1326       struct placement **clos_symbols = get_closure(&(parent1->placements[i]));
1327       int x = randint(0, 2);
1328
1329       if (x == 0)
1330       {
1331         if (dbg_breeding >= VERBOSITY_PLACEMENT)
1332           printf("Copying parent->child 1->1 and 2->2\n");
1333         copy_symbols(clos_symbols, parent1, child1, &processed);
1334         copy_symbols(clos_symbols, parent2, child2, &processed);
1335       }
1336       else
1337       {
1338         if (dbg_breeding >= VERBOSITY_PLACEMENT)
1339           printf("Copying parent->child 2->1 and 1->2\n");
1340         copy_symbols(clos_symbols, parent2, child1, &processed);
1341         copy_symbols(clos_symbols, parent1, child2, &processed);
1342       }
1343
1344       GARY_FREE(clos_symbols);
1345     }
1346   }
1347
1348   GARY_FREE(processed);
1349
1350   if (conf_mutate_children)
1351   {
1352     if (randdouble() < conf_mutate_children_prob) perform_mutation(child1);
1353     if (randdouble() < conf_mutate_children_prob) perform_mutation(child2);
1354   }
1355
1356   buffer[0] = child1;
1357   buffer[1] = child2;
1358   return buffer;
1359 }
1360
1361 void mutate(void)
1362 {
1363   for (int i=0; i < mutate_pop_size; i++)
1364   {
1365     if (dbg_mutation >= VERBOSITY_INDIVIDUAL)
1366       printf("Creating %d-th individual by mutation\n", i);
1367     int ind = randint(0, mutate_rbest_size);
1368     if (dbg_mutation >= VERBOSITY_INDIVIDUAL)
1369       printf("Mutating %d-th individual of original population\n", ind);
1370     population2[pop2_ind] = ep_alloc(ep_individuals);
1371     copy_individual(population1[ind], population2[pop2_ind]);
1372     if (dbg_mutation >= VERBOSITY_INDIVIDUAL)
1373       printf("Individual %d in pop2 inited from individual %d in pop1\n", pop2_ind, ind);
1374     perform_mutation(population2[pop2_ind]);
1375     pop2_ind++;
1376   }
1377 }
1378
1379 void perform_mutation(struct individual *individual)
1380 {
1381   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1382   {
1383     double x = randdouble();
1384     double acc = 0;
1385
1386     if (x <= acc + conf_mutate_move_bound)
1387     {
1388       if (dbg_mutation >= VERBOSITY_PLACEMENT)
1389         printf("Mutation: Moving symbol in placement %u\n", i);
1390       move_symbol(&(individual->placements[i]));
1391       continue;
1392     }
1393     acc += conf_mutate_move_bound;
1394
1395     if (x <= acc + conf_mutate_regen_bound)
1396     {
1397       gen_coords(&(individual->placements[i]));
1398       continue;
1399     }
1400     acc += conf_mutate_regen_bound;
1401
1402     if (x <= acc + conf_mutate_chvar_bound)
1403     {
1404       struct placement *p = &(individual->placements[i]);
1405       switch (p->request->type)
1406       {
1407         case REQUEST_POINT:
1408         case REQUEST_SEGMENT:
1409         case REQUEST_AREA:
1410           // Does nothing when there are 0 variants... does it mind?
1411           p->variant_used = randint(-1, GARY_SIZE(p->request->variants));
1412           break;
1413         case REQUEST_SECTION:
1414           p->variant_used = randint(0, GARY_SIZE(((struct request_section *) p->request)->segments));
1415           break;
1416         default:
1417           ;
1418       }
1419     }
1420   }
1421
1422   hide_segment_labels(individual);
1423 }
1424
1425 void elite(void)
1426 {
1427   for (int i=0; i<elite_pop_size; i++)
1428   {
1429     population2[pop2_ind] = ep_alloc(ep_individuals);
1430     copy_individual(population1[i], population2[pop2_ind++]);
1431   }
1432 }
1433
1434 int overlaps(struct placement *p1, struct placement *p2)
1435 {
1436   if (p1->request->type != REQUEST_POINT &&
1437       p1->request->type != REQUEST_SEGMENT &&
1438       p1->request->type != REQUEST_AREA)
1439     return 0;
1440
1441   if (p2->request->type != REQUEST_POINT &&
1442       p2->request->type != REQUEST_SEGMENT &&
1443       p2->request->type != REQUEST_AREA)
1444     return 0;
1445
1446   if (p1->variant_used == -1 || p2->variant_used == -1)
1447     return 0;
1448
1449   struct variant *v1, *v2;
1450
1451   v1 = &(p1->request->variants[p1->variant_used]);
1452   v2 = &(p2->request->variants[p2->variant_used]);
1453
1454   // FIXME: This doesn't fully respect offset which it probably should
1455   int p1x = p1->x; int p1y = p1->y;
1456   int p2x = p2->x; int p2y = p2->y;
1457
1458   int overlap = 0;
1459   for (int y=max2(0, max2(p1y, p2y)); y<min2(page_height_int, min2(p1y+v1->height, p2y+v2->height)); y++)
1460     for (int x=max2(0, max2(p1x, p2x)); x<min2(page_width_int, min2(p1x+v1->width, p2x+v2->width)); x++)
1461     {
1462       if (v1->bitmap[(y-p1y)*v1->width + (x-p1x)] &&
1463           v2->bitmap[(y-p2y)*v2->width + (x-p2x)])
1464         overlap++;
1465     }
1466
1467   return overlap;
1468 }
1469
1470 int get_overlap(struct placement *p)
1471 {
1472   if (p->variant_used == -1) return 0;
1473
1474   struct map_part **parts = get_map_parts(p);
1475   if (! parts)
1476   {
1477     if (dbg_overlaps >= VERBOSITY_PLACEMENT)
1478       printf("Placement of request %d seems not to be placed\n", p->request->ind);
1479     return 0;
1480   }
1481
1482   struct placement **others;
1483   bool *planned;
1484
1485   GARY_INIT_ZERO(planned, num_requests);
1486   planned[p->request->ind] = 1;
1487   GARY_INIT(others, 0);
1488
1489   for (uns i=0; i<GARY_SIZE(parts); i++)
1490   {
1491     struct map_placement *mp = parts[i]->placement->next_in_map;
1492     while (mp)
1493     {
1494       if (! planned[mp->placement->request->ind])
1495       {
1496         struct placement **p = GARY_PUSH(others);
1497         *p = mp->placement;
1498         planned[mp->placement->request->ind] = true;
1499       }
1500       mp = mp->next_in_map;
1501     }
1502   }
1503
1504   int overlap = 0;
1505   for (uns i=0; i<GARY_SIZE(others); i++)
1506   {
1507     overlap += overlaps(p, others[i]);
1508   }
1509
1510   GARY_FREE(planned);
1511   GARY_FREE(parts);
1512   GARY_FREE(others);
1513
1514   if (dbg_overlaps >= VERBOSITY_PLACEMENT)
1515     printf("Placement of request %d add %d to overlaps\n", p->request->ind, overlap);
1516
1517   if (p->x < 0) overlap += 0 - p->x;
1518   if (p->x + p->request->variants[p->variant_used].width > page_width_int)
1519     overlap += p->x + p->request->variants[p->variant_used].width - page_width_int;
1520
1521   if (p->y < 0) overlap += 0 - p->y;
1522   if (p->y + p->request->variants[p->variant_used].height > page_height_int)
1523     overlap += p->y + p->request->variants[p->variant_used].height - page_height_int;
1524
1525   return overlap;
1526 }
1527
1528 int individual_overlap(struct individual *individual)
1529 {
1530   int overlap = 0;
1531
1532   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1533   {
1534     overlap += get_overlap(&individual->placements[i]);
1535   }
1536
1537   return overlap;
1538 }
1539
1540 double get_distance(struct placement *p)
1541 {
1542   if (p->variant_used < 0) return 0;
1543   struct variant *v = &p->request->variants[p->variant_used];
1544
1545   double dx, dy, distance;
1546   switch (p->request->type)
1547   {
1548     case REQUEST_POINT: ;
1549       struct request_point *rp = (struct request_point *) p->request;
1550       dx = rp->x + v->offset_x - p->x;
1551       dy = rp->y + v->offset_y - p->y;
1552       distance = sqrt(dx*dx + dy*dy);
1553       if (dbg_rank >= VERBOSITY_PLACEMENT)
1554         printf("Point placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, rp->x, rp->y);
1555       break;
1556     case REQUEST_AREA: ;
1557       struct request_area *ra = (struct request_area *) p->request;
1558       dx = ra->cx + v->offset_x - p->x;
1559       dy = ra->cy + v->offset_y - p->y;
1560       distance = sqrt(dx*dx + dy*dy);
1561       if (dbg_rank >= VERBOSITY_PLACEMENT)
1562         printf("Area placed at [%.2f; %.2f], expected at [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1563       break;
1564     default:
1565       return 0;
1566   }
1567
1568   if (dbg_rank >= VERBOSITY_PLACEMENT)
1569     printf("Placement %d has distance %.2f\n", p->ind, distance);
1570   return distance;
1571 }
1572
1573 double individual_distances(struct individual *individual)
1574 {
1575   int distances = 0;
1576
1577   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1578   {
1579     distances += get_distance(&individual->placements[i]);
1580   }
1581
1582   return distances;
1583 }
1584
1585 double get_omittment(struct placement *p)
1586 {
1587   if (p->variant_used >= 0) return 0;
1588
1589   // FIX ME :)
1590   switch (p->request->type)
1591   {
1592     case REQUEST_POINT:
1593     case REQUEST_AREA:
1594       return 10;
1595       break;
1596     default:
1597       return 0;
1598   }
1599 }
1600
1601 double individual_omittment(struct individual *individual)
1602 {
1603   int omittment = 0;
1604
1605   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1606   {
1607     omittment += get_omittment(&individual->placements[i]);
1608   }
1609
1610   return omittment;
1611 }
1612
1613 int cmp_individual(const void *a, const void *b)
1614 {
1615   struct individual **ia = (struct individual **) a;
1616   struct individual **ib = (struct individual **) b;
1617
1618   return (*ia)->penalty - (*ib)->penalty;
1619 }
1620
1621 void rank_population(void)
1622 {
1623   int penalty;
1624
1625   for (int i=0; i<conf_pop_size; i++)
1626   {
1627     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1628       printf("Individual %d\n", i);
1629     population1[i]->penalty = 0;
1630
1631     penalty = individual_omittment(population1[i]);
1632     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1633       printf("Increasing penalty by %d for omittment\n", penalty);
1634     population1[i]->penalty += penalty;
1635
1636     penalty = individual_overlap(population1[i]);
1637     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1638       printf("Increasing penalty by %d for overlap\n", penalty);
1639     population1[i]->penalty += penalty;
1640
1641     penalty = individual_distances(population1[i]);
1642     if (dbg_rank >= VERBOSITY_INDIVIDUAL)
1643       printf("Increasing penalty by %d for distances\n", penalty);
1644     population1[i]->penalty += penalty;
1645   }
1646 }
1647
1648 struct map_part **get_map_parts(struct placement *p)
1649 {
1650   if (p->variant_used < 0) return NULL;
1651
1652   struct map_part **buffer;
1653   GARY_INIT(buffer, 0);
1654
1655   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1656     printf("Looking for map parts containing placement of request %d, placed at [%.2f; %.2f]\n", p->request->ind, p->x, p->y);
1657
1658   struct variant v;
1659   switch (p->request->type)
1660   {
1661     case REQUEST_POINT:
1662     case REQUEST_SEGMENT:
1663     case REQUEST_AREA:
1664       v = p->request->variants[p->variant_used];
1665       break;
1666     default:
1667       if (dbg_map_parts >= VERBOSITY_ALL)
1668         printf("Skipping unsupported request type (%d)\n", p->request->type);
1669       return NULL;
1670   }
1671
1672   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1673     printf("Bitmap is %d x %d\n", v.width, v.height);
1674
1675   int x_min = max2(0, p->x) / conf_map_part_width;
1676   // CHECK ME: Is rounding needed?
1677   int x_max = min2(page_width_int, (p->x + v.width)) / conf_map_part_width;
1678   int y_min = max2(0, p->y) / conf_map_part_height;
1679   // CHECK ME: Is rounding needed?
1680   int y_max = min2(page_height_int, (p->y + v.height)) / conf_map_part_height;
1681
1682   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1683     printf("Cells between [%d; %d] and [%d; %d] generated\n", x_min, y_min, x_max, y_max);
1684
1685   for (int y=y_min; y<=y_max; y++)
1686     for (int x=x_min; x<=x_max; x++)
1687     {
1688       struct map_part **m = GARY_PUSH(buffer);
1689       if (dbg_map_parts >= VERBOSITY_ALL)
1690         printf("Asking for %d of %u\n", y * num_map_parts_row + x, GARY_SIZE(p->individual->map));
1691       *m = p->individual->map[y * num_map_parts_row + x];
1692     }
1693
1694   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
1695     printf("Returning %u map parts potentially containing the symbol\n", GARY_SIZE(buffer));
1696
1697   return buffer;
1698 }
1699
1700 void update_map_parts_delete(struct placement *p)
1701 {
1702   struct map_placement *mp = p->map_links;
1703   while (mp)
1704   {
1705     mp->prev_in_map->next_in_map = mp->next_in_map;
1706     if (mp->next_in_map)
1707       mp->next_in_map->prev_in_map = mp->prev_in_map;
1708
1709     struct map_placement *tmp = mp;
1710     mp = mp->next_in_placement;
1711     free(tmp);
1712   }
1713   p->map_links = NULL;
1714 }
1715
1716 void update_map_parts_create(struct placement *p)
1717 {
1718   struct map_part **parts = get_map_parts(p);
1719   if (parts == NULL) return;
1720
1721   for (uns i=0; i<GARY_SIZE(parts); i++)
1722   {
1723     struct map_placement *mp = malloc(sizeof(struct map_placement));
1724     mp->placement = p;
1725     mp->part = parts[i];
1726
1727     mp->next_in_map = parts[i]->placement->next_in_map;
1728     mp->prev_in_map = parts[i]->placement;
1729     parts[i]->placement->next_in_map = mp;
1730     if (mp->next_in_map) mp->next_in_map->prev_in_map = mp;
1731
1732     mp->next_in_placement = p->map_links;
1733     mp->prev_in_placement = NULL;
1734     p->map_links = mp;
1735   }
1736
1737   GARY_FREE(parts);
1738 }
1739
1740 void update_map_parts(struct placement *p)
1741 {
1742   update_map_parts_delete(p);
1743   update_map_parts_create(p);
1744 }
1745
1746 void gen_coords(struct placement *p)
1747 {
1748   switch(p->request->type)
1749   {
1750     case REQUEST_POINT:
1751       gen_coords_point(p);
1752       break;
1753     case REQUEST_AREA:
1754       gen_coords_area(p);
1755       break;
1756     case REQUEST_SEGMENT:
1757       gen_coords_segment(p);
1758       break;
1759     case REQUEST_LINE:
1760       if (dbg_movement)
1761         printf("Not yet implemented\n");
1762       break;
1763     default:
1764       if (dbg_movement >= VERBOSITY_ALL)
1765         printf("Testing request type\n");
1766       ASSERT(p->request->type != REQUEST_INVALID);
1767   }
1768
1769   update_map_parts(p);
1770 }
1771
1772 double gen_movement(void)
1773 {
1774   double m = (random() % 100000) / 10000;
1775   m = pow(m, 1.0/3) * flip(1, -1);
1776   if (dbg_movement >= VERBOSITY_ALL)
1777     printf("Movement %.2f\n", m);
1778   return m;
1779 }
1780
1781 double gen_movement_uniform(void)
1782 {
1783   return (move_max - move_min) * randdouble() * flip(1, -1);
1784 }
1785
1786 void gen_coords_point(struct placement *p)
1787 {
1788   p->x = p->x + gen_movement();
1789 }
1790
1791 void gen_coords_segment(struct placement *p)
1792 {
1793   struct request_segment *rs = (struct request_segment *) p->request;
1794   int a = flip(1, 2);
1795   p->x = (a == 1 ? rs->x1 : rs->x2);
1796   p->y = (a == 1 ? rs->y1 : rs->y2);
1797 }
1798
1799 void gen_coords_area(struct placement *p)
1800 {
1801   struct request_area *ra = (struct request_area *) p->request;
1802
1803   p->x = p->x + gen_movement();
1804   p->y = p->y + gen_movement();
1805
1806   if (dbg_movement >= VERBOSITY_PLACEMENT)
1807     printf("Moved label to [%.2f; %.2f] from [%.2f; %.2f]\n", p->x, p->y, ra->cx, ra->cy);
1808 }
1809
1810 int randint(int min, int max)
1811 {
1812   if (min == max) return min;
1813   int r = random();
1814   return min + (r % (max - min));
1815 }
1816
1817 struct placement **get_closure(struct placement *placement)
1818 {
1819   struct placement **closure;
1820   GARY_INIT(closure, 0);
1821   bool *chosen = malloc(GARY_SIZE(placement->individual->placements) * sizeof(bool));
1822   for (uns i=0; i<GARY_SIZE(placement->individual->placements); i++) { chosen[i] = 0; }
1823   chosen[placement->request->ind] = 1;
1824
1825   struct placement **p = GARY_PUSH(closure); *p = placement;
1826
1827   uns first = 0;
1828   while (first < GARY_SIZE(closure))
1829   {
1830     if (dbg_breeding >= VERBOSITY_ALL)
1831       printf("Iterating, first is %d of current %u\n", first, GARY_SIZE(closure));
1832     struct placement **overlapping = get_overlapping(placement);
1833     if (! overlapping) { first++; continue; }
1834
1835     struct placement **filtered = filter(overlapping, &chosen);
1836     if (dbg_breeding >= VERBOSITY_ALL)
1837       printf("There are %u new overlapping symbols\n", GARY_SIZE(filtered));
1838     GARY_FREE(overlapping);
1839     overlapping = filtered;
1840     for (uns j=0; j<GARY_SIZE(overlapping); j++)
1841     {
1842       if (! chosen[overlapping[j]->request->ind])
1843       {
1844         if (overlaps(*p, overlapping[j]))
1845         {
1846           p = GARY_PUSH(closure); *p = overlapping[j];
1847           if (dbg_breeding >= VERBOSITY_ALL)
1848             printf("Adding placement of request %d (in fact at [%.2f; %.2f] of size %d x %d)\n", overlapping[j]->request->ind, overlapping[j]->x, overlapping[j]->y, overlapping[j]->request->variants[overlapping[j]->variant_used].width, overlapping[j]->request->variants[overlapping[j]->variant_used].height);
1849           chosen[overlapping[j]->request->ind] = 1;
1850         }
1851       }
1852     }
1853     GARY_FREE(overlapping);
1854     first++;
1855   }
1856
1857   free(chosen);
1858
1859   return closure;
1860 }
1861
1862 void copy_symbols(struct placement **closure, struct individual *parent, struct individual *child, bool **processed_ptr)
1863 {
1864   bool *processed = *processed_ptr;
1865   if (dbg_breeding >= VERBOSITY_ALL)
1866     printf("Will copy %u symbols\n", GARY_SIZE(closure));
1867
1868   for (uns i=0; i<GARY_SIZE(closure); i++)
1869   {
1870     processed[closure[i]->ind] = 1;
1871     int ind = closure[i]->ind;
1872     child->placements[ind] = parent->placements[ind];
1873     child->placements[ind].individual = child;
1874     child->placements[ind].processed = 0;
1875     child->placements[ind].map_links = NULL;
1876     update_map_parts(&child->placements[ind]);
1877   }
1878 }
1879
1880 void move_symbol(struct placement *p)
1881 {
1882   switch (p->request->type)
1883   {
1884     case REQUEST_POINT:
1885     case REQUEST_AREA:
1886       move_symbol_point(p);
1887       break;
1888     case REQUEST_SEGMENT:
1889       move_symbol_segment(p);
1890       break;
1891     default:
1892       ASSERT(p->request->type != REQUEST_INVALID);
1893   }
1894 }
1895
1896 void move_symbol_point(struct placement *p)
1897 {
1898   p->x += gen_movement_uniform();
1899   p->y += gen_movement_uniform();
1900 }
1901
1902 void move_symbol_segment(struct placement *p)
1903 {
1904   double m = gen_movement_uniform();
1905   // CHECK ME
1906   p->x += m;
1907   p->y += m * ((struct request_segment *) p->request)->slope;
1908 }
1909
1910 void hide_segment_labels(struct individual *individual)
1911 {
1912   // BEWARE: This fully depends on current genetic encoding
1913
1914   int used = -1, num = -1;
1915   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
1916   {
1917     switch (individual->placements[i].request->type)
1918     {
1919       case REQUEST_SECTION:
1920         used = individual->placements[i].variant_used;
1921         num = 0;
1922         break;
1923       case REQUEST_SEGMENT:
1924         if (num == used)
1925           individual->placements[i].variant_used = 0;
1926         else
1927           individual->placements[i].variant_used = -1;
1928         num++;
1929         break;
1930       default:
1931         ;
1932     }
1933   }
1934 }
1935
1936 void init_placement(struct placement *p, struct individual *individual, struct request *r)
1937 {
1938   p->ind = num_placements++;
1939   p->request = r;
1940   p->processed = 0;
1941   p->x = p->y = 0; // To prevent valgrind from complaining
1942   p->variant_used = 0;
1943   p->map_links = NULL;
1944   p->individual = individual;
1945   switch (r->type)
1946   {
1947     case REQUEST_POINT: ;
1948       struct request_point *rp = (struct request_point *) r;
1949       p->x = rp->x;
1950       p->y = rp->y;
1951       break;
1952     case REQUEST_LINE: ;
1953       break;
1954     case REQUEST_SECTION: ;
1955       struct request_section *rls = (struct request_section *) r;
1956       p->variant_used = randint(0, rls->num_segments);
1957       break;
1958     case REQUEST_SEGMENT: ;
1959       struct request_segment *rs = (struct request_segment *) r;
1960       p->x = rs->x2;
1961       p->y = rs->y2;
1962       break;
1963     case REQUEST_AREA: ;
1964       struct request_area *ra = (struct request_area *) r;
1965       p->x = ra->cx;
1966       p->y = ra->cy;
1967       p->variant_used = 0;
1968       break;
1969     default:
1970       ASSERT(p->request->type != REQUEST_INVALID);
1971   }
1972
1973   gen_coords(p);
1974   if (dbg_init >= VERBOSITY_PLACEMENT)
1975     printf("Inited placement to [%.2f; %.2f]\n", p->x, p->y);
1976 }
1977
1978 void reset_individual_map(struct individual *i)
1979 {
1980   for (uns j=0; j<num_map_parts; j++)
1981   {
1982     struct map_placement *mp = i->map[j]->placement;
1983     while (mp)
1984     {
1985       struct map_placement *tmp = mp;
1986       mp = mp->next_in_map;
1987       free(tmp);
1988     }
1989
1990     free(i->map[j]);
1991     struct map_part *part = malloc(sizeof(struct map_part));
1992     part->ind = j;
1993
1994     mp = malloc(sizeof(struct map_placement));
1995     part->placement = mp;
1996     mp->placement = &dummy_placement;
1997     mp->next_in_map = mp->prev_in_map = NULL;
1998     mp->next_in_placement = mp->prev_in_placement = NULL;
1999     i->map[j] = part;
2000   }
2001 }
2002
2003 void update_individual(struct individual *individual)
2004 {
2005   for (uns i=0; i<GARY_SIZE(individual->placements); i++)
2006   {
2007     update_map_parts_delete(&individual->placements[i]);
2008   }
2009 }
2010
2011 void clear_individual(struct individual *individual)
2012 {
2013   for (uns j=0; j<num_map_parts; j++)
2014   {
2015     struct map_placement *mp = individual->map[j]->placement;
2016     while (mp)
2017     {
2018       struct map_placement *tmp = mp;
2019       mp = mp->next_in_map;
2020       free(tmp);
2021     }
2022
2023     free(individual->map[j]);
2024   }
2025
2026   GARY_FREE(individual->map);
2027   GARY_FREE(individual->placements);
2028   ep_free(ep_individuals, individual);
2029 }
2030
2031 void clear_population(struct individual **pop)
2032 {
2033   for (uns i=0; i<GARY_SIZE(pop); i++)
2034   {
2035     clear_individual(pop[i]);
2036   }
2037 }
2038
2039 struct placement **get_overlapping(struct placement *p)
2040 {
2041   struct placement **buffer;
2042   GARY_INIT(buffer, 0);
2043
2044   struct map_part **parts = get_map_parts(p);
2045   if (! parts) return NULL;
2046
2047   for (uns i=0; i<GARY_SIZE(parts); i++)
2048   {
2049     struct map_placement *mp = parts[i]->placement->next_in_map;
2050     while (mp)
2051     {
2052       if (p->variant_used >= 0)
2053       {
2054         struct placement **p = GARY_PUSH(buffer);
2055         *p = mp->placement;
2056       }
2057       mp = mp->next_in_map;
2058     }
2059   }
2060   GARY_FREE(parts);
2061
2062   if (dbg_map_parts >= VERBOSITY_PLACEMENT)
2063     printf("Returning %u potentially overlapping placements\n", GARY_SIZE(buffer));
2064
2065   return buffer;
2066 }
2067
2068 struct placement **filter(struct placement **list, bool **pred_ptr)
2069 {
2070   bool *pred = *pred_ptr; // As GARY can't be passed directly
2071   struct placement **filtered;
2072   GARY_INIT(filtered, 0);
2073
2074   for (uns i=0; i<GARY_SIZE(list); i++)
2075   {
2076     if (pred[list[i]->request->ind])
2077       continue;
2078
2079     struct placement **p = GARY_PUSH(filtered);
2080     *p = list[i];
2081   }
2082
2083   return filtered;
2084 }
2085
2086 int flip(int a, int b)
2087 {
2088   return (random() % 2 ? a : b);
2089 }
2090
2091 double randdouble(void)
2092 {
2093   return ((double) rand() / (double) RAND_MAX);
2094 }
2095
2096 void init_individual(struct individual *individual)
2097 {
2098   GARY_INIT(individual->placements, num_requests);
2099   GARY_INIT(individual->map, 0);
2100   for (uns j=0; j<num_map_parts; j++)
2101   {
2102     GARY_PUSH(individual->map);
2103     struct map_part *part = malloc(sizeof(struct map_part));
2104     struct map_placement *mp = malloc(sizeof(struct map_placement));
2105     part->placement = mp;
2106     part->ind = j;
2107     mp->placement = &dummy_placement;
2108     mp->next_in_map = mp->prev_in_map = NULL;
2109     mp->next_in_placement = mp->prev_in_placement = NULL;
2110     individual->map[j] = part;
2111   }
2112   individual->penalty = 0;
2113 }
2114
2115 void copy_individual(struct individual *src, struct individual *dest)
2116 {
2117   init_individual(dest);
2118   dest->penalty = src->penalty;
2119
2120   for (uns i=0; i<GARY_SIZE(src->placements); i++)
2121   {
2122     dest->placements[i] = src->placements[i];
2123     dest->placements[i].map_links = NULL;
2124     dest->placements[i].individual = dest;
2125
2126     update_map_parts_create(&dest->placements[i]);
2127   }
2128 }