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