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