aboutsummaryrefslogtreecommitdiff
path: root/src/genetic-programming.c
blob: 258b4df4c8ce59c8c17ba849292728fb75527861 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <limits.h>
#include <time.h>
#include "dynamic-array.h"

// #define SEED time (NULL)
#define SEED 1762482320

#define POPULATION_CAPACITY 25

#define GENERATIONS_MAX 500
#define ELITE_COUNT 3
#define TOURNAMENT_SIZE 2

#define MUTATION_OPERATOR__GROWING__MAX_SIZE 3

#define REAL_SAMPLE_COUNT 5000
#define TRAINING_TESTING_DATA_RATION 3/4.

#define FITNESS_FUNCTION__WEIGHT__MSE        1.
#define FITNESS_FUNCTION__WEIGHT__GENE_COUNT 0.

#define VARIABLE_COUNT 2
struct variable_limit {
  float min, max;
} variable_limits[VARIABLE_COUNT] = {
  { -2, 2 },
  { -2, 2 },
};

#define CONSTANT_MIN -10.
#define CONSTANT_MAX +10.

#define MIN_GENE_COUNT  30
#define MAX_GENE_COUNT 200

#define PLOT_STEPS 200.

#define FUNCTIONS_2NARY                         \
  FUNCTION_2NARY (ADD, "➕",       l + r)        \
  FUNCTION_2NARY (SUB, "➖",       l - r)        \
  FUNCTION_2NARY (MUL, "❌",       l * r)        \
  FUNCTION_2NARY (DIV, "➗",       l / r)        \
  FUNCTION_2NARY (POW, "pow", powf (l,  r))

#define FUNCTIONS_1NARY                         \
  FUNCTION_1NARY  (ABS, "abs", fabs (v))        \
  FUNCTION_1NARY  (SIN, "sin", sinf (v))        \
  FUNCTION_1NARY  (COS, "cos", cosf (v))        \
  FUNCTION_1NARY  (EXP, "exp", expf (v))

#define FUNCTIONS        \
  FUNCTIONS_2NARY        \
  FUNCTIONS_1NARY

#define FUNCTION_2NARY(SYM, STR, EXP) FUNCTION_2NARY_##SYM,
enum function_2nary {
  FUNCTIONS_2NARY
  FUNCTION_2NARY_COUNT
};
#undef FUNCTION_2NARY

#define FUNCTION_1NARY(SYM, STR, EXP) FUNCTION_1NARY_##SYM,
enum function_1nary {
  FUNCTIONS_1NARY
  FUNCTION_1NARY_COUNT
};
#undef FUNCTION_1NARY

#define FUNCTION_2NARY(SYM, STR, EXP) [FUNCTION_2NARY_##SYM] = STR,
const char *function_2nary_labels[] = {
  FUNCTIONS_2NARY
};
#undef FUNCTION_2NARY

#define FUNCTION_1NARY(SYM, STR, EXP) [FUNCTION_1NARY_##SYM] = STR,
const char *function_1nary_labels[] = {
  FUNCTIONS_1NARY
};
#undef FUNCTION_1NARY

#define FUNCTION_2NARY(SYM, STR, EXP) FUNCTION_##SYM,
#define FUNCTION_1NARY( SYM, STR, EXP) FUNCTION_##SYM,
enum function {
  FUNCTIONS
  FUNCTION_COUNT
};
#undef FUNCTION_2NARY
#undef FUNCTION_1NARY

typedef float variables[VARIABLE_COUNT];

struct sample {
  variables variables;
  float output;
} real_samples[REAL_SAMPLE_COUNT];

float
real_function (variables x)
{
  const float x1 = x[0];
  const float x2 = x[1];

  const float a = x1 + x2 + 1;
  const float b = 2*x1 - 3*x2;
  return (( 1 + a*a*(19 - 14*x1 +  3*x1*x1 - 14*x2 +  6*x1*x2 +  3*x2*x2)) *
          (30 + b*b*(18 - 32*x1 + 12*x1*x1 + 48*x2 - 36*x1*x2 + 27*x2*x2)));
}

enum gene_type {
  GENE_TYPE_FUNCTION_2NARY,
  GENE_TYPE_FUNCTION_1NARY,
  GENE_TYPE_CONSTANT,
  GENE_TYPE_VARIABLE,
};
#define GENE_TYPE_FUNCTION(GENE_TYPE) ((GENE_TYPE) < 2)
#define GENE_TYPE_TERMINAL(GENE_TYPE) ((GENE_TYPE) > 1)

struct gene {
  float value;
  uint16_t up;
  uint16_t left_size;
};

struct chromosome {
  uint32_t gene_count;
  struct gene genes[MAX_GENE_COUNT];
};

union uf { uint32_t u; float f; };
#define NUM_TO_NAN(NUM) (  (union uf) ((NUM) + 1 | 0x7FE00000)).f
#define NAN_TO_NUM(NAN) ((((union uf)  (NAN)).u  & 0x001FFFFF) - 1)

struct gene_code {
  enum gene_type type;
  union {
    float    constant;
    uint32_t variable;
    uint32_t function_1nary;
    uint32_t function_2nary;
  };
};

void
gene_code__print (struct gene_code code)
{
  switch (code.type) {
  case GENE_TYPE_FUNCTION_2NARY:
    switch (code.function_2nary) {
#define FUNCTION_2NARY(SYM, STR, EXP) case FUNCTION_2NARY_##SYM: printf (STR); break;
      FUNCTIONS_2NARY
#undef FUNCTION_2NARY
    }
    break;
  case GENE_TYPE_FUNCTION_1NARY:
    switch (code.function_1nary) {
#define FUNCTION_1NARY(SYM, STR, EXP) case FUNCTION_1NARY_##SYM: printf (STR); break;
      FUNCTIONS_1NARY
#undef FUNCTION_1NARY
    }
    break;
  case GENE_TYPE_CONSTANT:
    printf ("%f", code.constant);
    break;
  case GENE_TYPE_VARIABLE:
    printf ("x%d", code.variable);
    break;
  }
}

struct gene_code
gene__decode (float value)
{
  if (!isnan (value))
    return (struct gene_code) { GENE_TYPE_CONSTANT, { .constant = value } };

  int num = NAN_TO_NUM (value);

  if (num >= FUNCTION_COUNT)
    return (struct gene_code) { GENE_TYPE_VARIABLE,
                                { .variable = num - FUNCTION_COUNT } };

  if (num >= FUNCTION_2NARY_COUNT)
    return (struct gene_code) { GENE_TYPE_FUNCTION_1NARY,
                                { .function_1nary = num - FUNCTION_2NARY_COUNT } };

  return (struct gene_code) { GENE_TYPE_FUNCTION_2NARY, { .function_2nary = num } };
}

float
gene__random_terminal (void)
{
  switch (rand () % 2) {
  case 0: return NUM_TO_NAN ((uint32_t) FUNCTION_COUNT + rand () % VARIABLE_COUNT);
  case 1: return interpolate (CONSTANT_MIN, CONSTANT_MAX, rand () /(float) RAND_MAX);
  default: UNREACHABLE ();
  }
}

float
gene__random_function_2nary (void)
{
  return NUM_TO_NAN ((uint32_t) rand () % FUNCTION_2NARY_COUNT);
}

float
gene__random_function_1nary (void)
{
  return NUM_TO_NAN ((uint32_t) FUNCTION_2NARY_COUNT +
                     rand () % FUNCTION_1NARY_COUNT);
}

float
chromosome__evaluate (const struct chromosome *chromosome, const variables variables)
{
  static struct {
    float    *items;
    uint32_t  count;
    uint32_t  capacity;
  } eval_stack = {0};
  DYNAMIC_ARRAY__RESET (eval_stack);

  static struct {
    uint32_t *items;
    uint32_t count;
    uint32_t capacity;
  } traversal_stack = {0};
  DYNAMIC_ARRAY__RESET (traversal_stack);

  DYNAMIC_ARRAY__APPEND (traversal_stack, 0);
  do {
    uint32_t i = DYNAMIC_ARRAY__POP (traversal_stack);
    const struct gene *gene = &chromosome->genes[i];
    struct gene_code code = gene__decode (gene->value);
    switch (code.type) {
      case GENE_TYPE_FUNCTION_2NARY:
        DYNAMIC_ARRAY__APPEND (traversal_stack, i + 1 + gene->left_size);
        __attribute__ ((fallthrough));
      case GENE_TYPE_FUNCTION_1NARY:
        DYNAMIC_ARRAY__APPEND (traversal_stack, i + 1);
        __attribute__ ((fallthrough));
      case GENE_TYPE_CONSTANT:
        DYNAMIC_ARRAY__APPEND (eval_stack, gene->value);
        break;
      case GENE_TYPE_VARIABLE:
        DYNAMIC_ARRAY__APPEND (eval_stack, variables[code.variable]);
        break;
      default: UNREACHABLE ();
    }

    while (eval_stack.count > 0) {
      // for (uint32_t i = 0; i < eval_stack.count; ++i) {
      //   gene_code__print (gene__decode (eval_stack.items[i]));
      //   printf ("\n");
      // } printf ("\n");

      if (eval_stack.count == 1 && !isnan (eval_stack.items[0]))
        return eval_stack.items[0];

      if (eval_stack.count >= 3 &&
           isnan (eval_stack.items[eval_stack.count - 3]) &&
          !isnan (eval_stack.items[eval_stack.count - 2]) &&
          !isnan (eval_stack.items[eval_stack.count - 1])) {
        struct gene_code code = gene__decode (eval_stack.items[eval_stack.count - 3]);
        if (code.type == GENE_TYPE_FUNCTION_2NARY) {
          float l = eval_stack.items[eval_stack.count - 2];
          float r = eval_stack.items[eval_stack.count - 1];
          float v = NAN;
          eval_stack.count -= 3;
          switch (code.function_2nary) {
#define FUNCTION_2NARY(SYM, STR, EXP) case FUNCTION_2NARY_##SYM: v = EXP; break;
            FUNCTIONS_2NARY;
#undef FUNCTION_2NARY
          }
          // printf ("%f %f -> %f\n", l, r, v);
          if (isnan (v)) return FLT_MAX;
          DYNAMIC_ARRAY__APPEND (eval_stack, v);
          continue;
        }
      }

      if (eval_stack.count >= 2 &&
           isnan (eval_stack.items[eval_stack.count - 2]) &&
          !isnan (eval_stack.items[eval_stack.count - 1])) {
        struct gene_code code = gene__decode (eval_stack.items[eval_stack.count - 2]);
        if (code.type == GENE_TYPE_FUNCTION_1NARY) {
          float v = eval_stack.items[eval_stack.count - 1];
          // printf ("%f -> ", v);
          eval_stack.count -= 2;
          switch (code.function_1nary) {
#define FUNCTION_1NARY(SYM, STR, EXP) case FUNCTION_1NARY_##SYM: v = EXP; break;
            FUNCTIONS_1NARY;
#undef FUNCTION_1NARY
          }
          if (isnan (v)) return FLT_MAX;
          // printf ("%f\n", v);
          DYNAMIC_ARRAY__APPEND (eval_stack, v);
          continue;
        }
      }

      break;
    }
  } while (traversal_stack.count > 0);

  UNREACHABLE ();
}

float
fitness_function (const struct chromosome *chromosome, bool training)
{
  float mse = 0;
  const struct sample *real_samples_beg;
  const struct sample *real_samples_end;
  if (training) {
    real_samples_beg = real_samples;
    real_samples_end = real_samples + (int) (REAL_SAMPLE_COUNT*TRAINING_TESTING_DATA_RATION);
  } else {
    real_samples_beg = real_samples + (int) (REAL_SAMPLE_COUNT*TRAINING_TESTING_DATA_RATION);
    real_samples_end = real_samples +        REAL_SAMPLE_COUNT;
  }
  for (const struct sample *real_sample = real_samples_beg;
       real_sample < real_samples_end; ++real_sample) {
    float output = chromosome__evaluate (chromosome, real_sample->variables);
    float error = output - real_sample->output;
    mse += error*error;
  }
  if (training) {
    mse /= REAL_SAMPLE_COUNT*TRAINING_TESTING_DATA_RATION;
    return (FITNESS_FUNCTION__WEIGHT__MSE        * mse +
            FITNESS_FUNCTION__WEIGHT__GENE_COUNT * chromosome->gene_count/MAX_GENE_COUNT);
  } else {
    mse /= REAL_SAMPLE_COUNT*(1 - TRAINING_TESTING_DATA_RATION);
    return mse;
  }
}

#define FULL_TREE_HEIGHT (32 - CLZ (MAX_GENE_COUNT) - 1)

void
chromosome__initialize__full (struct chromosome *chromosome)
{
  chromosome->gene_count = 1;

  // NOTE(cmmm): (memory) could be reused
  static struct {
    struct record {
      uint32_t back;
      uint32_t depth;
    } *items;
    uint32_t count;
    uint32_t capacity;
  } stack = {0};

  uint32_t top = 0;
  DYNAMIC_ARRAY__RESET  (stack);
  DYNAMIC_ARRAY__APPEND (stack, ((struct record) { 0, 0 }));
  while (stack.count) {
    uint32_t i = top++;
    struct record rec = DYNAMIC_ARRAY__POP (stack);
    struct gene *gene = &chromosome->genes[i];

    if (i == 0)                    gene->up = 0;
    else if (rec.back == UINT_MAX) gene->up = 1;
    else {
      gene->up = i - rec.back;
      chromosome->genes[rec.back].left_size = gene->up - 1;
    }

    if (rec.depth == FULL_TREE_HEIGHT ||
        chromosome->gene_count == MAX_GENE_COUNT) { // 0nary
      gene->left_size = 0;
      gene->value = gene__random_terminal ();
      uint32_t count = 1;
      struct gene *up = gene - gene->up;
      do {
        switch (gene__decode (up->value).type) {
        case GENE_TYPE_FUNCTION_2NARY: count += up->left_size + 1; break;
        case GENE_TYPE_FUNCTION_1NARY: gene->left_size = count++; break;
        default: UNREACHABLE ();
        } up -= up->up;
      } while (up->up);
      continue;
    }

    if (chromosome->gene_count < MAX_GENE_COUNT - 1) { // 2nary
      chromosome->gene_count += 2;
      gene->left_size = 0;
      gene->value = gene__random_function_2nary ();
      DYNAMIC_ARRAY__APPEND (stack, ((struct record) { i,        rec.depth + 1 }));
      DYNAMIC_ARRAY__APPEND (stack, ((struct record) { UINT_MAX, rec.depth + 1 }));
      continue;
    }

    // 1nary
    chromosome->gene_count += 1;
    gene->left_size = 0;
    gene->value = gene__random_function_1nary ();
    DYNAMIC_ARRAY__APPEND (stack, ((struct record) { UINT_MAX, rec.depth + 1 }));
  }
}

void
chromosome__initialize__grow (struct chromosome *chromosome)
{
 retry:
  chromosome->gene_count = 1;

  // NOTE(cmmm): (memory) could be reused
  static struct {
    uint32_t *items;
    uint32_t  count;
    uint32_t  capacity;
  } stack = {0};

  uint32_t top = 0;
  DYNAMIC_ARRAY__RESET  (stack);
  DYNAMIC_ARRAY__APPEND (stack, 0);
  while (stack.count) {
    uint32_t i = top++;
    uint32_t back = DYNAMIC_ARRAY__POP (stack);
    struct gene *gene = &chromosome->genes[i];

    if (i == 0)                gene->up = 0;
    else if (back == UINT_MAX) gene->up = 1;
    else {
      gene->up = i - back;
      chromosome->genes[back].left_size = gene->up - 1;
    }

    switch (i == 0 ? rand () % 2 : rand () % 3) {
      case 0:                   // 2nary
        if (chromosome->gene_count < MAX_GENE_COUNT - 1) {
          chromosome->gene_count += 2;
          gene->left_size = 0;
          gene->value = gene__random_function_2nary ();
          DYNAMIC_ARRAY__APPEND (stack, i       );
          DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
          continue;
        } __attribute__ ((fallthrough));

      case 1:                   // 1nary
        if (chromosome->gene_count < MAX_GENE_COUNT) {
          chromosome->gene_count += 1;
          gene->left_size = 0;
          gene->value = gene__random_function_1nary ();
          DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
          continue;
        } __attribute__ ((fallthrough));

    case 2: {                   // 0nary
      gene->left_size = 0;
      uint32_t count = 1;
      struct gene *up = gene - gene->up;
      do {
        switch (gene__decode (up->value).type) {
        case GENE_TYPE_FUNCTION_2NARY: count += up->left_size + 1; break;
        case GENE_TYPE_FUNCTION_1NARY: up->left_size = count++; break;
        default: UNREACHABLE ();
        } up -= up->up;
      } while (up->up);
    } gene->value = gene__random_terminal ();
    }
  }

  if (chromosome->gene_count < MIN_GENE_COUNT)
    goto retry;
}

void
chromosome__initialize (struct chromosome *chromosome)
{
  switch (rand () % 2) {
    case 0: return chromosome__initialize__full (chromosome);
    case 1: return chromosome__initialize__grow (chromosome);
  }
}

void
chromosome__export__dot (struct chromosome *chromosome, const char *filename)
{
  char *command = NULL;
  asprintf (&command, "dot -Tpng -o %s.png", filename);
  FILE *dot = popen (command, "w");
  // FILE *dot = stdout;
  free (command);

  fprintf (dot, "digraph G {\n");
  fprintf (dot, "  node [fontname=\"Aporetic-Bold\", margin=\"0\"]\n");
  fprintf (dot, "  graph [margin=0, nodesep=0.2, ranksep=0.3]\n");
  for (uint32_t i = 0; i < chromosome->gene_count; ++i) {
    struct gene gene = chromosome->genes[i];
    struct gene_code code = gene__decode (gene.value);
    switch (code.type) {
      case GENE_TYPE_CONSTANT:
        // fprintf (dot, "  n%d [label=\"%d (%u/%u): %.2f\"];\n", i, i, gene.up, gene.left_size, code.constant);
        fprintf (dot, "  n%d [label=\"%+.1f\"];\n", i, code.constant);
        break;

      case GENE_TYPE_VARIABLE:
        // fprintf (dot, "  n%d [label=\"%d (%u/%u): x%u\"];\n", i, i, gene.up, gene.left_size, code.variable + 1);
        fprintf (dot, "  n%d [label=\"x%u\"];\n", i, code.variable + 1);
        break;

      case GENE_TYPE_FUNCTION_1NARY:
        // fprintf (dot, "  n%d [label=\"%d (%u/%u): %s\"];\n", i, i, gene.up, gene.left_size,
        //          function_1nary_labels[code.function_1nary]);
        fprintf (dot, "  n%d [label=\"%s\"];\n", i, function_1nary_labels[code.function_1nary]);
        fprintf (dot, "  n%d -> n%d;\n", i, i + 1);
        break;

      case GENE_TYPE_FUNCTION_2NARY:
        // fprintf (dot, "  n%d [label=\"%d (%u/%u): %s\"];\n", i, i, gene.up, gene.left_size,
        //          function_2nary_labels[code.function_2nary]);
        fprintf (dot, "  n%d [label=\"%s\"];\n", i, function_2nary_labels[code.function_2nary]);
        fprintf (dot, "  n%d -> n%d;\n", i, i + 1             );
        fprintf (dot, "  n%d -> n%d;\n", i, i + 1 + gene.left_size);
        break;
    }
  } fprintf (dot, "}\n");
  pclose (dot);
}

void
chromosome__plot (struct chromosome *chromosome, const char *filename)
{
  FILE *gp = popen ("gnuplot", "w");
  fprintf (gp, "set term cairolatex png input blacktext notransparent "
               "nocrop size 14cm,11cm noheader\n");
  fprintf (gp, "set output '%s.tex'\n", filename);
  fprintf (gp, "set pm3d at bs interpolate 0,0 explicit\n");
  fprintf (gp, "unset hidden3d\n");
  fprintf (gp, "set border 4095\n");
  fprintf (gp, "set xlabel '\\(x_1\\)'\n");
  fprintf (gp, "set ylabel '\\(x_2\\)'\n");
  fprintf (gp, "set zlabel '\\(f(x_1, x_2)\\)' rotate parallel\n");
  fprintf (gp, "set ticslevel 0\n");
  fprintf (gp, "unset key\n");
  fprintf (gp, "set xtics offset graph -0.05, graph -0.10\n");
  fprintf (gp, "set ytics offset graph +0.05, graph +0.05\n");
  fprintf (gp, "set  zrange [3:10000000]\n");
  fprintf (gp, "set cbrange [3:10000000]\n");
  fprintf (gp, "set format  z '10^{%%L}'\n");
  fprintf (gp, "set format cb '10^{%%L}'\n");
  fprintf (gp, "set logscale  z\n");
  fprintf (gp, "set logscale cb\n");
  fprintf (gp, "splot ");
  fprintf (gp, "'-' smooth acsplines with pm3d\n");
  variables vars;
  for (int x = 0; x <= PLOT_STEPS; ++x) {
    vars[0] = variable_limits[0].min + x/PLOT_STEPS*(variable_limits[0].max - variable_limits[0].min);
    for (int y = 0; y <= PLOT_STEPS; ++y) {
      vars[1] = variable_limits[1].min + y/PLOT_STEPS*(variable_limits[1].max - variable_limits[1].min);
      float output = chromosome ? chromosome__evaluate (chromosome, vars) : real_function (vars);
      if      (output == FLT_MAX) output = NAN;
      else if (output  <       3) output = 3;
      fprintf (gp, "%f %f %f\n", vars[0], vars[1], output);
    } fprintf (gp, "\n");
  } fprintf (gp, "e\n");
  pclose (gp);
}

struct {
  struct {
    int   index;
    float fitness;
  } elites[ELITE_COUNT];

  struct {
    int   index;
    float fitness;
  } best;

  float             fitness      [POPULATION_CAPACITY];
  struct chromosome chromosomes  [POPULATION_CAPACITY];
  struct chromosome breeding_pool[POPULATION_CAPACITY];
} population;

float generations__fitness[GENERATIONS_MAX + 1];

void
create_initial_population (int population_size)
{
  ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);

  for (int i = 0; i < population_size; ++i) {
    chromosome__initialize__grow (&population.chromosomes[i]);
  }
}

void
measure_fitness (int population_size, int generation, bool testing)
{
  ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);

  population.best.index = 0;
  population.best.fitness = FLT_MAX;
  float fitness_sum = 0;
  for (int i = 0; i < ELITE_COUNT; ++i) {
    population.elites[i].index = i;
    population.elites[i].fitness = FLT_MAX;
  }
  for (int i = 0; i < population_size; ++i) {
    float fitness = fitness_function (&population.chromosomes[i], testing);
    fitness_sum += fitness;
    population.fitness[i] = fitness;

    if (fitness < population.best.fitness) {
      population.best.index   = i;
      population.best.fitness = fitness;
    }

    int worst_elite = 0;
    for (int j = 1; j < ELITE_COUNT; ++j) {
      if (population.elites[          j].fitness >
          population.elites[worst_elite].fitness)
        worst_elite = j;
    }
    if (fitness < population.elites[worst_elite].fitness) {
      population.elites[worst_elite].index   = i;
      population.elites[worst_elite].fitness = fitness;
    }
  }

  generations__fitness[generation] = population.best.fitness;
}

void
selection__tournament (int population_size, int tournament_size)
{
  ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
  ASSERT (tournament_size < population_size);

  for (int i = 0; i < population_size; ++i) {
    int group_beg = rand () % (population_size - tournament_size);
    int j = group_beg;
    for (int k = group_beg + 1; k < group_beg + tournament_size; ++k) {
      if (population.fitness[k] < population.fitness[j])
        j = k;
    }

    memcpy (&population.breeding_pool[i], &population.chromosomes[j],
            sizeof (struct chromosome));
  }
}

uint32_t
gene__depth (const struct gene *gene)
{
  uint32_t depth = 0;
  while (gene->up) {
    depth +=1;
    gene = gene - gene->up;
  }
  return depth;
}

uint32_t
gene__size (const struct gene *root_gene)
{
  ASSERT (root_gene);

  // NOTE(cmmm): (memory) could be reused in other functions
  static struct {
    uint32_t *items;
    uint32_t count;
    uint32_t capacity;
  } stack = {0};

  if (gene__decode (root_gene->value).type != GENE_TYPE_FUNCTION_2NARY)
    return root_gene->left_size + 1;

  uint32_t size = 0;
  DYNAMIC_ARRAY__RESET (stack);
  DYNAMIC_ARRAY__APPEND (stack, 0);
  while (stack.count) {
    size += 1;
    uint32_t index = DYNAMIC_ARRAY__POP (stack);
    struct gene gene = root_gene[index];

    struct gene_code code = gene__decode (gene.value);
    switch (code.type) {
    case GENE_TYPE_FUNCTION_2NARY:
      DYNAMIC_ARRAY__APPEND (stack,  index + 1 + gene.left_size);
      __attribute__ ((fallthrough));
    case GENE_TYPE_FUNCTION_1NARY:
      DYNAMIC_ARRAY__APPEND (stack, index + 1);
      __attribute__ ((fallthrough));
    default: continue;
    }
  }

  return size;
}

void
chromosome__mix_subtree (      struct chromosome *restrict mixed_chromosome,
                         const struct chromosome *restrict a_chromosome,
                         const struct gene       *restrict a_gene,
                         uint32_t                          a_gene_size,
                         const struct chromosome *restrict b_chromosome,
                         const struct gene       *restrict b_gene,
                         uint32_t                          b_gene_size)
{
  struct gene *mixed_gene =
    &mixed_chromosome->genes[a_gene - a_chromosome->genes];

  int32_t gene_count_delta = b_gene_size - a_gene_size;
  mixed_chromosome->gene_count = a_chromosome->gene_count + gene_count_delta;

  memcpy (mixed_chromosome->genes, a_chromosome->genes,
          (a_gene - a_chromosome->genes)*sizeof (struct gene));
  memcpy (mixed_gene, b_gene,
          b_gene_size*sizeof (struct gene));
  memcpy (mixed_gene + b_gene_size, a_gene + a_gene_size,
          ((a_chromosome->genes + a_chromosome->gene_count) -
           (a_gene + a_gene_size))*sizeof (struct gene));

  mixed_gene->up = a_gene->up;
  for (struct gene *gene = mixed_gene; gene->up; gene -= gene->up) {
    if (gene->up > 1) continue; // we came from right, no change needed
    struct gene *up = gene - gene->up;
    up->left_size += gene_count_delta;
    if (gene__decode (up->value).type == GENE_TYPE_FUNCTION_2NARY)
      up[1 + up->left_size].up += gene_count_delta;
  }
}

void
crossover_operator__nodal (int a, int b)
{
  struct chromosome *a_chromosome = &population.chromosomes[a];
  struct chromosome *b_chromosome = &population.chromosomes[b];

  memcpy (a_chromosome, &population.breeding_pool[a], sizeof (*a_chromosome));
  memcpy (b_chromosome, &population.breeding_pool[b], sizeof (*b_chromosome));

  int a_gene_count = a_chromosome->gene_count;
  int b_gene_count = b_chromosome->gene_count;

  struct gene *b_gene, *a_gene = &a_chromosome->genes[rand () % a_gene_count];
  enum gene_type b_gene_type, a_gene_type = gene__decode (a_gene->value).type;
  int attempts = 0;
  do {
    b_gene = &b_chromosome->genes[rand () % b_gene_count];
    b_gene_type = gene__decode (b_gene->value).type;
  } while (attempts++ < 5 &&
           b_gene_type != a_gene_type
           && (a_gene_type > 1 || b_gene_type > 1));

  float tmp = a_gene->value;
  a_gene->value = b_gene->value;
  b_gene->value = tmp;
}

void
crossover_operator__subtree (int a, int b)
{
  struct chromosome *a_chromosome = &population.breeding_pool[a];
  struct chromosome *b_chromosome = &population.breeding_pool[b];

  struct chromosome *a_chromosome_target = &population.chromosomes[a];
  struct chromosome *b_chromosome_target = &population.chromosomes[b];

  uint32_t a_gene_count = a_chromosome->gene_count;
  uint32_t b_gene_count = b_chromosome->gene_count;

  struct gene *b_gene;
  struct gene *a_gene = &a_chromosome->genes[rand () % a_gene_count];

  uint32_t b_gene_size;
  uint32_t a_gene_size = gene__size (a_gene);

  uint32_t a_gene_count_new;
  uint32_t b_gene_count_new;
  int attempts = 0;
  do {
    if (++attempts == 3) {
      memcpy (a_chromosome_target, a_chromosome, sizeof (struct chromosome));
      memcpy (b_chromosome_target, b_chromosome, sizeof (struct chromosome));
      return;
    }
    b_gene = &b_chromosome->genes[rand () % b_gene_count];
    b_gene_size = gene__size (b_gene);
    a_gene_count_new = a_chromosome->gene_count - a_gene_size + b_gene_size;
    b_gene_count_new = b_chromosome->gene_count - b_gene_size + a_gene_size;
  } while (a_gene_count_new < MIN_GENE_COUNT || a_gene_count_new > MAX_GENE_COUNT ||
           b_gene_count_new < MIN_GENE_COUNT || b_gene_count_new > MAX_GENE_COUNT);

  chromosome__mix_subtree (a_chromosome_target,
                           a_chromosome, a_gene, a_gene_size,
                           b_chromosome, b_gene, b_gene_size);
  chromosome__mix_subtree (b_chromosome_target,
                           b_chromosome, b_gene, b_gene_size,
                           a_chromosome, a_gene, a_gene_size);
}

void
crossover_operator__mixed (int a, int b)
{
  switch (rand () % 2) {
  case 0: return crossover_operator__nodal   (a, b);
  case 1: return crossover_operator__subtree (a, b);
  }
}

typedef void (*crossover_operator) (int a, int b);

void
crossover (int population_size, float probability, crossover_operator operator)
{
  ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);

  for (int i = 0; i < population_size; i += 2) {
    int a = i;
    int b = (i + 1) % population_size;

    if (rand () /(float) RAND_MAX > probability) {
      memcpy (&population.chromosomes[a], &population.breeding_pool[a], sizeof (struct chromosome));
      memcpy (&population.chromosomes[b], &population.breeding_pool[b], sizeof (struct chromosome));
    } else operator (a, b);
  }
}

void
mutation_operator__nodal (struct chromosome *chromosome)
{
  struct gene *gene = &chromosome->genes[rand () % chromosome->gene_count];
  struct gene_code code = gene__decode (gene->value);
  switch (code.type) {
  case GENE_TYPE_FUNCTION_2NARY: gene->value = gene__random_function_2nary (); break;
  case GENE_TYPE_FUNCTION_1NARY: gene->value = gene__random_function_1nary (); break;
  case GENE_TYPE_VARIABLE: __attribute__ ((fallthrough));
  case GENE_TYPE_CONSTANT: gene->value = gene__random_terminal (); break;
  }
}

void
mutation_operator__truncating (struct chromosome *chromosome)
{
  int attempts = 0;
 retry:
  struct gene *gene = &chromosome->genes[1 + rand () % (chromosome->gene_count - 1)];
  struct gene_code code = gene__decode (gene->value);
  if (GENE_TYPE_TERMINAL (code.type)) {
    // NOTE(cmmm): could move up and cut single branch or whole subtree
    // gene->value = gene__random_terminal ();
    // return;

    gene -= gene->up;
    code = gene__decode (gene->value);
  }

  uint32_t gene_size = gene__size (gene);
  if (chromosome->gene_count - gene_size < MIN_GENE_COUNT) {
    if (++attempts == 5)
      return;
    goto retry;
  }

  gene->value = gene__random_terminal ();
  gene->left_size = 0;

  memmove (gene + 1, gene + gene_size,
           ((chromosome->genes + chromosome->gene_count) -
            (gene + 1))*sizeof (struct gene));

  chromosome->gene_count -= gene_size - 1;

  for (struct gene *head = gene; head->up; head -= head->up) {
    if (head->up > 1) continue; // we came from right, no change needed
    struct gene *up = head -head->up;
    up->left_size -= gene_size - 1;
    if (gene__decode (up->value).type == GENE_TYPE_FUNCTION_2NARY)
      up[1 + up->left_size].up -= gene_size - 1;
  }
}

void
mutation_operator__growing (struct chromosome *chromosome)
{
  if (chromosome->gene_count == MAX_GENE_COUNT) return;

  struct gene *root_gene = &chromosome->genes[rand () % chromosome->gene_count];
  struct gene_code code = gene__decode (root_gene->value);
  while (GENE_TYPE_FUNCTION (code.type)) {
    root_gene += 1;
    if (code.type == GENE_TYPE_FUNCTION_2NARY && rand () % 2)
      root_gene += root_gene->left_size;
    code = gene__decode (root_gene->value);
  }

  uint32_t size =
    2 + (chromosome->gene_count + 1 != MAX_GENE_COUNT
         ? rand () % (MAX_GENE_COUNT - chromosome->gene_count - 1) : 0);
  size = MIN (size, 1 + MUTATION_OPERATOR__GROWING__MAX_SIZE);

  memmove (root_gene + size, root_gene + 1,
           ((chromosome->genes + chromosome->gene_count) -
            (root_gene + 1))*sizeof (struct gene));

  size -= 1;
  chromosome->gene_count += size;

  for (struct gene *gene = root_gene; gene->up; gene -= gene->up) {
    if (gene->up > 1) continue; // we came from right, no change needed
    struct gene *up = gene -gene->up;
    up->left_size += size;
    if (gene__decode (up->value).type == GENE_TYPE_FUNCTION_2NARY)
      up[1 + up->left_size].up += size;
  }

  static struct {
    uint32_t *items;
    uint32_t  count;
    uint32_t  capacity;
  } stack = {0};

  uint32_t top = 0;
  uint32_t open_slots = 1;
  DYNAMIC_ARRAY__RESET  (stack);
  DYNAMIC_ARRAY__APPEND (stack, 0);
  while (stack.count) {
    uint32_t i = top++;
    uint32_t back = DYNAMIC_ARRAY__POP (stack);
    struct gene *gene = &root_gene[i];

    if (i == 0);
    else if (back == UINT_MAX) gene->up = 1;
    else {
      gene->up = i - back;
      root_gene[back].left_size = gene->up - 1;
    }

    switch (size >= open_slots ? rand () % 2 : rand () % 3) {
      case 0:                   // 2nary
        if (size >= 2) {
          size -= 2;
          open_slots += 1;
          gene->left_size = 0;
          gene->value = gene__random_function_2nary ();
          DYNAMIC_ARRAY__APPEND (stack, i       );
          DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
          continue;
        } __attribute__ ((fallthrough));

      case 1:                   // 1nary
        if (size >= 1) {
          size -= 1;
          gene->left_size = 0;
          gene->value = gene__random_function_1nary ();
          DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
          continue;
        } __attribute__ ((fallthrough));

    case 2: {                   // 0nary
      open_slots -= 1;
      gene->left_size = 0;
      gene->value = gene__random_terminal ();
      if (gene == root_gene) break;
      uint32_t count = 1;
      struct gene *up = gene - gene->up;
      do {
        switch (gene__decode (up->value).type) {
        case GENE_TYPE_FUNCTION_2NARY: count += up->left_size + 1; break;
        case GENE_TYPE_FUNCTION_1NARY: up->left_size = count++; break;
        default: UNREACHABLE ();
        } up -= up->up;
      } while (up != root_gene - root_gene->up);
    }
    }
  }
}

void
mutation_operator__mixed (struct chromosome *chromosome)
{
  if (rand () % 4 == 0) {
    mutation_operator__nodal (chromosome);
  } else if (chromosome->gene_count >= MIN_GENE_COUNT + (MAX_GENE_COUNT - MIN_GENE_COUNT + 1)/2) {
    mutation_operator__truncating (chromosome);
  } else {
    mutation_operator__growing (chromosome);
  }
}

typedef void (*mutation_operator) (struct chromosome *);

void
mutation (int population_size, float probability, mutation_operator operator)
{
  ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);

  for (int i = 0; i < population_size; ++i) {
    if (rand () /(float) RAND_MAX > probability)
      continue;
    operator (&population.chromosomes[i]);
  }
}

float
variable__random_from_limit (struct variable_limit limit)
{
  return limit.min + (limit.max - limit.min)*rand ()/RAND_MAX;
}

void
sample_real_function (void)
{
  for (int i = 0; i < REAL_SAMPLE_COUNT; ++i) {
    for (int j = 0; j < VARIABLE_COUNT; ++j) {
      real_samples[i].variables[j] = variable__random_from_limit (variable_limits[j]);
    } real_samples[i].output = real_function (real_samples[i].variables);
  }
}

void
plot_fitness_over_generations (const char *output, int generations)
{
  FILE *gp = popen ("gnuplot", "w");
  // FILE *gp = fopen ("test.gp", "w");
  fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
               " nocrop size 15cm,10cm noheader\n");
  fprintf (gp, "set output '%s.tex'\n", output);

  // fprintf (gp, "set xrange [0:%d]\n", GENERATIONS_MAX);
  fprintf (gp, "set yrange [*:150000]\n");
  fprintf (gp, "set xlabel '№ поколения'\n");
  fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n");

  fprintf (gp, "plot ");
  fprintf (gp, "'-' with lines title 'Лучшее значение'\n");

  for (int i = 0; i <= generations; ++i) {
    fprintf (gp, "%d %f\n", i, sqrtf (generations__fitness[i]));
  } fprintf (gp, "e\n");

  pclose (gp);
}

int
main (int argc, char *argv[])
{
  PRINT_EXP ("%u", (uint32_t) SEED);
  PRINT_EXP ("%d",  GENERATIONS_MAX);
  PRINT_EXP ("%d",  ELITE_COUNT);
  PRINT_EXP ("%d",  TOURNAMENT_SIZE);
  PRINT_EXP ("%d",  REAL_SAMPLE_COUNT);
  PRINT_EXP ("%f",  TRAINING_TESTING_DATA_RATION);
  PRINT_EXP ("%f",  FITNESS_FUNCTION__WEIGHT__MSE);
  PRINT_EXP ("%f",  FITNESS_FUNCTION__WEIGHT__GENE_COUNT);
  PRINT_EXP ("%+f", CONSTANT_MIN  );
  PRINT_EXP ("%+f", CONSTANT_MAX  );
  PRINT_EXP ("%d",  MIN_GENE_COUNT);
  PRINT_EXP ("%d",  MAX_GENE_COUNT);

  chromosome__plot (NULL, "res/plot-real");

  srand (SEED);
  sample_real_function ();

  struct chromosome elite_buffer[ELITE_COUNT];
  int population_size = POPULATION_CAPACITY;
  create_initial_population (population_size);
  for (int generation = 0; generation < GENERATIONS_MAX; ++generation) {
    measure_fitness (population_size, generation, true);

    if (generation % 10 == 0) {
      printf ("generation: %5d, fitness: %.0f: gene count: %d\n",
              generation, sqrtf (population.best.fitness),
              population.chromosomes[population.best.index].gene_count);
    }

    if (generation % 100 == 0) {
      char *filename = NULL;
      asprintf (&filename, "res/tree-generation%03d", generation);
      chromosome__export__dot (&population.chromosomes[population.best.index], filename);
      free (filename);
      filename = NULL;
      asprintf (&filename, "res/plot-generation%03d", generation);
      chromosome__plot (&population.chromosomes[population.best.index], filename);
      free (filename);
    }

    selection__tournament (population_size, TOURNAMENT_SIZE);
    for (int i = 0; i < ELITE_COUNT; ++i) {
      memcpy (&elite_buffer[i], &population.chromosomes[population.elites[i].index],
              sizeof (struct chromosome));
    } memcpy (&population.chromosomes[population_size - ELITE_COUNT], elite_buffer,
              ELITE_COUNT*sizeof (struct chromosome));
    crossover (population_size - ELITE_COUNT, .8, crossover_operator__subtree);
    mutation  (population_size - ELITE_COUNT, .8, mutation_operator__mixed);
  } measure_fitness (population_size, GENERATIONS_MAX, false);

  printf ("testing:\n");
  for (int i = 0; i < population_size; ++i) {
    printf ("%d %f\n", i, sqrtf (population.fitness[i]));
  } printf ("best: %f\n", sqrtf (population.best.fitness));
  chromosome__export__dot (&population.chromosomes[population.best.index], "res/best-tree");
  chromosome__plot        (&population.chromosomes[population.best.index], "res/best-plot");
  plot_fitness_over_generations ("res/fitness", GENERATIONS_MAX);

  return EXIT_SUCCESS;
}