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