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