aboutsummaryrefslogtreecommitdiff
path: root/src/genetic-programming.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/genetic-programming.c')
-rw-r--r--src/genetic-programming.c1109
1 files changed, 1109 insertions, 0 deletions
diff --git a/src/genetic-programming.c b/src/genetic-programming.c
new file mode 100644
index 0000000..258b4df
--- /dev/null
+++ b/src/genetic-programming.c
@@ -0,0 +1,1109 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <stdint.h>
4#include <string.h>
5#include <math.h>
6#include <float.h>
7#include <limits.h>
8#include <time.h>
9#include "dynamic-array.h"
10
11// #define SEED time (NULL)
12#define SEED 1762482320
13
14#define POPULATION_CAPACITY 25
15
16#define GENERATIONS_MAX 500
17#define ELITE_COUNT 3
18#define TOURNAMENT_SIZE 2
19
20#define MUTATION_OPERATOR__GROWING__MAX_SIZE 3
21
22#define REAL_SAMPLE_COUNT 5000
23#define TRAINING_TESTING_DATA_RATION 3/4.
24
25#define FITNESS_FUNCTION__WEIGHT__MSE 1.
26#define FITNESS_FUNCTION__WEIGHT__GENE_COUNT 0.
27
28#define VARIABLE_COUNT 2
29struct variable_limit {
30 float min, max;
31} variable_limits[VARIABLE_COUNT] = {
32 { -2, 2 },
33 { -2, 2 },
34};
35
36#define CONSTANT_MIN -10.
37#define CONSTANT_MAX +10.
38
39#define MIN_GENE_COUNT 30
40#define MAX_GENE_COUNT 200
41
42#define PLOT_STEPS 200.
43
44#define FUNCTIONS_2NARY \
45 FUNCTION_2NARY (ADD, "➕", l + r) \
46 FUNCTION_2NARY (SUB, "➖", l - r) \
47 FUNCTION_2NARY (MUL, "❌", l * r) \
48 FUNCTION_2NARY (DIV, "➗", l / r) \
49 FUNCTION_2NARY (POW, "pow", powf (l, r))
50
51#define FUNCTIONS_1NARY \
52 FUNCTION_1NARY (ABS, "abs", fabs (v)) \
53 FUNCTION_1NARY (SIN, "sin", sinf (v)) \
54 FUNCTION_1NARY (COS, "cos", cosf (v)) \
55 FUNCTION_1NARY (EXP, "exp", expf (v))
56
57#define FUNCTIONS \
58 FUNCTIONS_2NARY \
59 FUNCTIONS_1NARY
60
61#define FUNCTION_2NARY(SYM, STR, EXP) FUNCTION_2NARY_##SYM,
62enum function_2nary {
63 FUNCTIONS_2NARY
64 FUNCTION_2NARY_COUNT
65};
66#undef FUNCTION_2NARY
67
68#define FUNCTION_1NARY(SYM, STR, EXP) FUNCTION_1NARY_##SYM,
69enum function_1nary {
70 FUNCTIONS_1NARY
71 FUNCTION_1NARY_COUNT
72};
73#undef FUNCTION_1NARY
74
75#define FUNCTION_2NARY(SYM, STR, EXP) [FUNCTION_2NARY_##SYM] = STR,
76const char *function_2nary_labels[] = {
77 FUNCTIONS_2NARY
78};
79#undef FUNCTION_2NARY
80
81#define FUNCTION_1NARY(SYM, STR, EXP) [FUNCTION_1NARY_##SYM] = STR,
82const char *function_1nary_labels[] = {
83 FUNCTIONS_1NARY
84};
85#undef FUNCTION_1NARY
86
87#define FUNCTION_2NARY(SYM, STR, EXP) FUNCTION_##SYM,
88#define FUNCTION_1NARY( SYM, STR, EXP) FUNCTION_##SYM,
89enum function {
90 FUNCTIONS
91 FUNCTION_COUNT
92};
93#undef FUNCTION_2NARY
94#undef FUNCTION_1NARY
95
96typedef float variables[VARIABLE_COUNT];
97
98struct sample {
99 variables variables;
100 float output;
101} real_samples[REAL_SAMPLE_COUNT];
102
103float
104real_function (variables x)
105{
106 const float x1 = x[0];
107 const float x2 = x[1];
108
109 const float a = x1 + x2 + 1;
110 const float b = 2*x1 - 3*x2;
111 return (( 1 + a*a*(19 - 14*x1 + 3*x1*x1 - 14*x2 + 6*x1*x2 + 3*x2*x2)) *
112 (30 + b*b*(18 - 32*x1 + 12*x1*x1 + 48*x2 - 36*x1*x2 + 27*x2*x2)));
113}
114
115enum gene_type {
116 GENE_TYPE_FUNCTION_2NARY,
117 GENE_TYPE_FUNCTION_1NARY,
118 GENE_TYPE_CONSTANT,
119 GENE_TYPE_VARIABLE,
120};
121#define GENE_TYPE_FUNCTION(GENE_TYPE) ((GENE_TYPE) < 2)
122#define GENE_TYPE_TERMINAL(GENE_TYPE) ((GENE_TYPE) > 1)
123
124struct gene {
125 float value;
126 uint16_t up;
127 uint16_t left_size;
128};
129
130struct chromosome {
131 uint32_t gene_count;
132 struct gene genes[MAX_GENE_COUNT];
133};
134
135union uf { uint32_t u; float f; };
136#define NUM_TO_NAN(NUM) ( (union uf) ((NUM) + 1 | 0x7FE00000)).f
137#define NAN_TO_NUM(NAN) ((((union uf) (NAN)).u & 0x001FFFFF) - 1)
138
139struct gene_code {
140 enum gene_type type;
141 union {
142 float constant;
143 uint32_t variable;
144 uint32_t function_1nary;
145 uint32_t function_2nary;
146 };
147};
148
149void
150gene_code__print (struct gene_code code)
151{
152 switch (code.type) {
153 case GENE_TYPE_FUNCTION_2NARY:
154 switch (code.function_2nary) {
155#define FUNCTION_2NARY(SYM, STR, EXP) case FUNCTION_2NARY_##SYM: printf (STR); break;
156 FUNCTIONS_2NARY
157#undef FUNCTION_2NARY
158 }
159 break;
160 case GENE_TYPE_FUNCTION_1NARY:
161 switch (code.function_1nary) {
162#define FUNCTION_1NARY(SYM, STR, EXP) case FUNCTION_1NARY_##SYM: printf (STR); break;
163 FUNCTIONS_1NARY
164#undef FUNCTION_1NARY
165 }
166 break;
167 case GENE_TYPE_CONSTANT:
168 printf ("%f", code.constant);
169 break;
170 case GENE_TYPE_VARIABLE:
171 printf ("x%d", code.variable);
172 break;
173 }
174}
175
176struct gene_code
177gene__decode (float value)
178{
179 if (!isnan (value))
180 return (struct gene_code) { GENE_TYPE_CONSTANT, { .constant = value } };
181
182 int num = NAN_TO_NUM (value);
183
184 if (num >= FUNCTION_COUNT)
185 return (struct gene_code) { GENE_TYPE_VARIABLE,
186 { .variable = num - FUNCTION_COUNT } };
187
188 if (num >= FUNCTION_2NARY_COUNT)
189 return (struct gene_code) { GENE_TYPE_FUNCTION_1NARY,
190 { .function_1nary = num - FUNCTION_2NARY_COUNT } };
191
192 return (struct gene_code) { GENE_TYPE_FUNCTION_2NARY, { .function_2nary = num } };
193}
194
195float
196gene__random_terminal (void)
197{
198 switch (rand () % 2) {
199 case 0: return NUM_TO_NAN ((uint32_t) FUNCTION_COUNT + rand () % VARIABLE_COUNT);
200 case 1: return interpolate (CONSTANT_MIN, CONSTANT_MAX, rand () /(float) RAND_MAX);
201 default: UNREACHABLE ();
202 }
203}
204
205float
206gene__random_function_2nary (void)
207{
208 return NUM_TO_NAN ((uint32_t) rand () % FUNCTION_2NARY_COUNT);
209}
210
211float
212gene__random_function_1nary (void)
213{
214 return NUM_TO_NAN ((uint32_t) FUNCTION_2NARY_COUNT +
215 rand () % FUNCTION_1NARY_COUNT);
216}
217
218float
219chromosome__evaluate (const struct chromosome *chromosome, const variables variables)
220{
221 static struct {
222 float *items;
223 uint32_t count;
224 uint32_t capacity;
225 } eval_stack = {0};
226 DYNAMIC_ARRAY__RESET (eval_stack);
227
228 static struct {
229 uint32_t *items;
230 uint32_t count;
231 uint32_t capacity;
232 } traversal_stack = {0};
233 DYNAMIC_ARRAY__RESET (traversal_stack);
234
235 DYNAMIC_ARRAY__APPEND (traversal_stack, 0);
236 do {
237 uint32_t i = DYNAMIC_ARRAY__POP (traversal_stack);
238 const struct gene *gene = &chromosome->genes[i];
239 struct gene_code code = gene__decode (gene->value);
240 switch (code.type) {
241 case GENE_TYPE_FUNCTION_2NARY:
242 DYNAMIC_ARRAY__APPEND (traversal_stack, i + 1 + gene->left_size);
243 __attribute__ ((fallthrough));
244 case GENE_TYPE_FUNCTION_1NARY:
245 DYNAMIC_ARRAY__APPEND (traversal_stack, i + 1);
246 __attribute__ ((fallthrough));
247 case GENE_TYPE_CONSTANT:
248 DYNAMIC_ARRAY__APPEND (eval_stack, gene->value);
249 break;
250 case GENE_TYPE_VARIABLE:
251 DYNAMIC_ARRAY__APPEND (eval_stack, variables[code.variable]);
252 break;
253 default: UNREACHABLE ();
254 }
255
256 while (eval_stack.count > 0) {
257 // for (uint32_t i = 0; i < eval_stack.count; ++i) {
258 // gene_code__print (gene__decode (eval_stack.items[i]));
259 // printf ("\n");
260 // } printf ("\n");
261
262 if (eval_stack.count == 1 && !isnan (eval_stack.items[0]))
263 return eval_stack.items[0];
264
265 if (eval_stack.count >= 3 &&
266 isnan (eval_stack.items[eval_stack.count - 3]) &&
267 !isnan (eval_stack.items[eval_stack.count - 2]) &&
268 !isnan (eval_stack.items[eval_stack.count - 1])) {
269 struct gene_code code = gene__decode (eval_stack.items[eval_stack.count - 3]);
270 if (code.type == GENE_TYPE_FUNCTION_2NARY) {
271 float l = eval_stack.items[eval_stack.count - 2];
272 float r = eval_stack.items[eval_stack.count - 1];
273 float v = NAN;
274 eval_stack.count -= 3;
275 switch (code.function_2nary) {
276#define FUNCTION_2NARY(SYM, STR, EXP) case FUNCTION_2NARY_##SYM: v = EXP; break;
277 FUNCTIONS_2NARY;
278#undef FUNCTION_2NARY
279 }
280 // printf ("%f %f -> %f\n", l, r, v);
281 if (isnan (v)) return FLT_MAX;
282 DYNAMIC_ARRAY__APPEND (eval_stack, v);
283 continue;
284 }
285 }
286
287 if (eval_stack.count >= 2 &&
288 isnan (eval_stack.items[eval_stack.count - 2]) &&
289 !isnan (eval_stack.items[eval_stack.count - 1])) {
290 struct gene_code code = gene__decode (eval_stack.items[eval_stack.count - 2]);
291 if (code.type == GENE_TYPE_FUNCTION_1NARY) {
292 float v = eval_stack.items[eval_stack.count - 1];
293 // printf ("%f -> ", v);
294 eval_stack.count -= 2;
295 switch (code.function_1nary) {
296#define FUNCTION_1NARY(SYM, STR, EXP) case FUNCTION_1NARY_##SYM: v = EXP; break;
297 FUNCTIONS_1NARY;
298#undef FUNCTION_1NARY
299 }
300 if (isnan (v)) return FLT_MAX;
301 // printf ("%f\n", v);
302 DYNAMIC_ARRAY__APPEND (eval_stack, v);
303 continue;
304 }
305 }
306
307 break;
308 }
309 } while (traversal_stack.count > 0);
310
311 UNREACHABLE ();
312}
313
314float
315fitness_function (const struct chromosome *chromosome, bool training)
316{
317 float mse = 0;
318 const struct sample *real_samples_beg;
319 const struct sample *real_samples_end;
320 if (training) {
321 real_samples_beg = real_samples;
322 real_samples_end = real_samples + (int) (REAL_SAMPLE_COUNT*TRAINING_TESTING_DATA_RATION);
323 } else {
324 real_samples_beg = real_samples + (int) (REAL_SAMPLE_COUNT*TRAINING_TESTING_DATA_RATION);
325 real_samples_end = real_samples + REAL_SAMPLE_COUNT;
326 }
327 for (const struct sample *real_sample = real_samples_beg;
328 real_sample < real_samples_end; ++real_sample) {
329 float output = chromosome__evaluate (chromosome, real_sample->variables);
330 float error = output - real_sample->output;
331 mse += error*error;
332 }
333 if (training) {
334 mse /= REAL_SAMPLE_COUNT*TRAINING_TESTING_DATA_RATION;
335 return (FITNESS_FUNCTION__WEIGHT__MSE * mse +
336 FITNESS_FUNCTION__WEIGHT__GENE_COUNT * chromosome->gene_count/MAX_GENE_COUNT);
337 } else {
338 mse /= REAL_SAMPLE_COUNT*(1 - TRAINING_TESTING_DATA_RATION);
339 return mse;
340 }
341}
342
343#define FULL_TREE_HEIGHT (32 - CLZ (MAX_GENE_COUNT) - 1)
344
345void
346chromosome__initialize__full (struct chromosome *chromosome)
347{
348 chromosome->gene_count = 1;
349
350 // NOTE(cmmm): (memory) could be reused
351 static struct {
352 struct record {
353 uint32_t back;
354 uint32_t depth;
355 } *items;
356 uint32_t count;
357 uint32_t capacity;
358 } stack = {0};
359
360 uint32_t top = 0;
361 DYNAMIC_ARRAY__RESET (stack);
362 DYNAMIC_ARRAY__APPEND (stack, ((struct record) { 0, 0 }));
363 while (stack.count) {
364 uint32_t i = top++;
365 struct record rec = DYNAMIC_ARRAY__POP (stack);
366 struct gene *gene = &chromosome->genes[i];
367
368 if (i == 0) gene->up = 0;
369 else if (rec.back == UINT_MAX) gene->up = 1;
370 else {
371 gene->up = i - rec.back;
372 chromosome->genes[rec.back].left_size = gene->up - 1;
373 }
374
375 if (rec.depth == FULL_TREE_HEIGHT ||
376 chromosome->gene_count == MAX_GENE_COUNT) { // 0nary
377 gene->left_size = 0;
378 gene->value = gene__random_terminal ();
379 uint32_t count = 1;
380 struct gene *up = gene - gene->up;
381 do {
382 switch (gene__decode (up->value).type) {
383 case GENE_TYPE_FUNCTION_2NARY: count += up->left_size + 1; break;
384 case GENE_TYPE_FUNCTION_1NARY: gene->left_size = count++; break;
385 default: UNREACHABLE ();
386 } up -= up->up;
387 } while (up->up);
388 continue;
389 }
390
391 if (chromosome->gene_count < MAX_GENE_COUNT - 1) { // 2nary
392 chromosome->gene_count += 2;
393 gene->left_size = 0;
394 gene->value = gene__random_function_2nary ();
395 DYNAMIC_ARRAY__APPEND (stack, ((struct record) { i, rec.depth + 1 }));
396 DYNAMIC_ARRAY__APPEND (stack, ((struct record) { UINT_MAX, rec.depth + 1 }));
397 continue;
398 }
399
400 // 1nary
401 chromosome->gene_count += 1;
402 gene->left_size = 0;
403 gene->value = gene__random_function_1nary ();
404 DYNAMIC_ARRAY__APPEND (stack, ((struct record) { UINT_MAX, rec.depth + 1 }));
405 }
406}
407
408void
409chromosome__initialize__grow (struct chromosome *chromosome)
410{
411 retry:
412 chromosome->gene_count = 1;
413
414 // NOTE(cmmm): (memory) could be reused
415 static struct {
416 uint32_t *items;
417 uint32_t count;
418 uint32_t capacity;
419 } stack = {0};
420
421 uint32_t top = 0;
422 DYNAMIC_ARRAY__RESET (stack);
423 DYNAMIC_ARRAY__APPEND (stack, 0);
424 while (stack.count) {
425 uint32_t i = top++;
426 uint32_t back = DYNAMIC_ARRAY__POP (stack);
427 struct gene *gene = &chromosome->genes[i];
428
429 if (i == 0) gene->up = 0;
430 else if (back == UINT_MAX) gene->up = 1;
431 else {
432 gene->up = i - back;
433 chromosome->genes[back].left_size = gene->up - 1;
434 }
435
436 switch (i == 0 ? rand () % 2 : rand () % 3) {
437 case 0: // 2nary
438 if (chromosome->gene_count < MAX_GENE_COUNT - 1) {
439 chromosome->gene_count += 2;
440 gene->left_size = 0;
441 gene->value = gene__random_function_2nary ();
442 DYNAMIC_ARRAY__APPEND (stack, i );
443 DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
444 continue;
445 } __attribute__ ((fallthrough));
446
447 case 1: // 1nary
448 if (chromosome->gene_count < MAX_GENE_COUNT) {
449 chromosome->gene_count += 1;
450 gene->left_size = 0;
451 gene->value = gene__random_function_1nary ();
452 DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
453 continue;
454 } __attribute__ ((fallthrough));
455
456 case 2: { // 0nary
457 gene->left_size = 0;
458 uint32_t count = 1;
459 struct gene *up = gene - gene->up;
460 do {
461 switch (gene__decode (up->value).type) {
462 case GENE_TYPE_FUNCTION_2NARY: count += up->left_size + 1; break;
463 case GENE_TYPE_FUNCTION_1NARY: up->left_size = count++; break;
464 default: UNREACHABLE ();
465 } up -= up->up;
466 } while (up->up);
467 } gene->value = gene__random_terminal ();
468 }
469 }
470
471 if (chromosome->gene_count < MIN_GENE_COUNT)
472 goto retry;
473}
474
475void
476chromosome__initialize (struct chromosome *chromosome)
477{
478 switch (rand () % 2) {
479 case 0: return chromosome__initialize__full (chromosome);
480 case 1: return chromosome__initialize__grow (chromosome);
481 }
482}
483
484void
485chromosome__export__dot (struct chromosome *chromosome, const char *filename)
486{
487 char *command = NULL;
488 asprintf (&command, "dot -Tpng -o %s.png", filename);
489 FILE *dot = popen (command, "w");
490 // FILE *dot = stdout;
491 free (command);
492
493 fprintf (dot, "digraph G {\n");
494 fprintf (dot, " node [fontname=\"Aporetic-Bold\", margin=\"0\"]\n");
495 fprintf (dot, " graph [margin=0, nodesep=0.2, ranksep=0.3]\n");
496 for (uint32_t i = 0; i < chromosome->gene_count; ++i) {
497 struct gene gene = chromosome->genes[i];
498 struct gene_code code = gene__decode (gene.value);
499 switch (code.type) {
500 case GENE_TYPE_CONSTANT:
501 // fprintf (dot, " n%d [label=\"%d (%u/%u): %.2f\"];\n", i, i, gene.up, gene.left_size, code.constant);
502 fprintf (dot, " n%d [label=\"%+.1f\"];\n", i, code.constant);
503 break;
504
505 case GENE_TYPE_VARIABLE:
506 // fprintf (dot, " n%d [label=\"%d (%u/%u): x%u\"];\n", i, i, gene.up, gene.left_size, code.variable + 1);
507 fprintf (dot, " n%d [label=\"x%u\"];\n", i, code.variable + 1);
508 break;
509
510 case GENE_TYPE_FUNCTION_1NARY:
511 // fprintf (dot, " n%d [label=\"%d (%u/%u): %s\"];\n", i, i, gene.up, gene.left_size,
512 // function_1nary_labels[code.function_1nary]);
513 fprintf (dot, " n%d [label=\"%s\"];\n", i, function_1nary_labels[code.function_1nary]);
514 fprintf (dot, " n%d -> n%d;\n", i, i + 1);
515 break;
516
517 case GENE_TYPE_FUNCTION_2NARY:
518 // fprintf (dot, " n%d [label=\"%d (%u/%u): %s\"];\n", i, i, gene.up, gene.left_size,
519 // function_2nary_labels[code.function_2nary]);
520 fprintf (dot, " n%d [label=\"%s\"];\n", i, function_2nary_labels[code.function_2nary]);
521 fprintf (dot, " n%d -> n%d;\n", i, i + 1 );
522 fprintf (dot, " n%d -> n%d;\n", i, i + 1 + gene.left_size);
523 break;
524 }
525 } fprintf (dot, "}\n");
526 pclose (dot);
527}
528
529void
530chromosome__plot (struct chromosome *chromosome, const char *filename)
531{
532 FILE *gp = popen ("gnuplot", "w");
533 fprintf (gp, "set term cairolatex png input blacktext notransparent "
534 "nocrop size 14cm,11cm noheader\n");
535 fprintf (gp, "set output '%s.tex'\n", filename);
536 fprintf (gp, "set pm3d at bs interpolate 0,0 explicit\n");
537 fprintf (gp, "unset hidden3d\n");
538 fprintf (gp, "set border 4095\n");
539 fprintf (gp, "set xlabel '\\(x_1\\)'\n");
540 fprintf (gp, "set ylabel '\\(x_2\\)'\n");
541 fprintf (gp, "set zlabel '\\(f(x_1, x_2)\\)' rotate parallel\n");
542 fprintf (gp, "set ticslevel 0\n");
543 fprintf (gp, "unset key\n");
544 fprintf (gp, "set xtics offset graph -0.05, graph -0.10\n");
545 fprintf (gp, "set ytics offset graph +0.05, graph +0.05\n");
546 fprintf (gp, "set zrange [3:10000000]\n");
547 fprintf (gp, "set cbrange [3:10000000]\n");
548 fprintf (gp, "set format z '10^{%%L}'\n");
549 fprintf (gp, "set format cb '10^{%%L}'\n");
550 fprintf (gp, "set logscale z\n");
551 fprintf (gp, "set logscale cb\n");
552 fprintf (gp, "splot ");
553 fprintf (gp, "'-' smooth acsplines with pm3d\n");
554 variables vars;
555 for (int x = 0; x <= PLOT_STEPS; ++x) {
556 vars[0] = variable_limits[0].min + x/PLOT_STEPS*(variable_limits[0].max - variable_limits[0].min);
557 for (int y = 0; y <= PLOT_STEPS; ++y) {
558 vars[1] = variable_limits[1].min + y/PLOT_STEPS*(variable_limits[1].max - variable_limits[1].min);
559 float output = chromosome ? chromosome__evaluate (chromosome, vars) : real_function (vars);
560 if (output == FLT_MAX) output = NAN;
561 else if (output < 3) output = 3;
562 fprintf (gp, "%f %f %f\n", vars[0], vars[1], output);
563 } fprintf (gp, "\n");
564 } fprintf (gp, "e\n");
565 pclose (gp);
566}
567
568struct {
569 struct {
570 int index;
571 float fitness;
572 } elites[ELITE_COUNT];
573
574 struct {
575 int index;
576 float fitness;
577 } best;
578
579 float fitness [POPULATION_CAPACITY];
580 struct chromosome chromosomes [POPULATION_CAPACITY];
581 struct chromosome breeding_pool[POPULATION_CAPACITY];
582} population;
583
584float generations__fitness[GENERATIONS_MAX + 1];
585
586void
587create_initial_population (int population_size)
588{
589 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
590
591 for (int i = 0; i < population_size; ++i) {
592 chromosome__initialize__grow (&population.chromosomes[i]);
593 }
594}
595
596void
597measure_fitness (int population_size, int generation, bool testing)
598{
599 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
600
601 population.best.index = 0;
602 population.best.fitness = FLT_MAX;
603 float fitness_sum = 0;
604 for (int i = 0; i < ELITE_COUNT; ++i) {
605 population.elites[i].index = i;
606 population.elites[i].fitness = FLT_MAX;
607 }
608 for (int i = 0; i < population_size; ++i) {
609 float fitness = fitness_function (&population.chromosomes[i], testing);
610 fitness_sum += fitness;
611 population.fitness[i] = fitness;
612
613 if (fitness < population.best.fitness) {
614 population.best.index = i;
615 population.best.fitness = fitness;
616 }
617
618 int worst_elite = 0;
619 for (int j = 1; j < ELITE_COUNT; ++j) {
620 if (population.elites[ j].fitness >
621 population.elites[worst_elite].fitness)
622 worst_elite = j;
623 }
624 if (fitness < population.elites[worst_elite].fitness) {
625 population.elites[worst_elite].index = i;
626 population.elites[worst_elite].fitness = fitness;
627 }
628 }
629
630 generations__fitness[generation] = population.best.fitness;
631}
632
633void
634selection__tournament (int population_size, int tournament_size)
635{
636 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
637 ASSERT (tournament_size < population_size);
638
639 for (int i = 0; i < population_size; ++i) {
640 int group_beg = rand () % (population_size - tournament_size);
641 int j = group_beg;
642 for (int k = group_beg + 1; k < group_beg + tournament_size; ++k) {
643 if (population.fitness[k] < population.fitness[j])
644 j = k;
645 }
646
647 memcpy (&population.breeding_pool[i], &population.chromosomes[j],
648 sizeof (struct chromosome));
649 }
650}
651
652uint32_t
653gene__depth (const struct gene *gene)
654{
655 uint32_t depth = 0;
656 while (gene->up) {
657 depth +=1;
658 gene = gene - gene->up;
659 }
660 return depth;
661}
662
663uint32_t
664gene__size (const struct gene *root_gene)
665{
666 ASSERT (root_gene);
667
668 // NOTE(cmmm): (memory) could be reused in other functions
669 static struct {
670 uint32_t *items;
671 uint32_t count;
672 uint32_t capacity;
673 } stack = {0};
674
675 if (gene__decode (root_gene->value).type != GENE_TYPE_FUNCTION_2NARY)
676 return root_gene->left_size + 1;
677
678 uint32_t size = 0;
679 DYNAMIC_ARRAY__RESET (stack);
680 DYNAMIC_ARRAY__APPEND (stack, 0);
681 while (stack.count) {
682 size += 1;
683 uint32_t index = DYNAMIC_ARRAY__POP (stack);
684 struct gene gene = root_gene[index];
685
686 struct gene_code code = gene__decode (gene.value);
687 switch (code.type) {
688 case GENE_TYPE_FUNCTION_2NARY:
689 DYNAMIC_ARRAY__APPEND (stack, index + 1 + gene.left_size);
690 __attribute__ ((fallthrough));
691 case GENE_TYPE_FUNCTION_1NARY:
692 DYNAMIC_ARRAY__APPEND (stack, index + 1);
693 __attribute__ ((fallthrough));
694 default: continue;
695 }
696 }
697
698 return size;
699}
700
701void
702chromosome__mix_subtree ( struct chromosome *restrict mixed_chromosome,
703 const struct chromosome *restrict a_chromosome,
704 const struct gene *restrict a_gene,
705 uint32_t a_gene_size,
706 const struct chromosome *restrict b_chromosome,
707 const struct gene *restrict b_gene,
708 uint32_t b_gene_size)
709{
710 struct gene *mixed_gene =
711 &mixed_chromosome->genes[a_gene - a_chromosome->genes];
712
713 int32_t gene_count_delta = b_gene_size - a_gene_size;
714 mixed_chromosome->gene_count = a_chromosome->gene_count + gene_count_delta;
715
716 memcpy (mixed_chromosome->genes, a_chromosome->genes,
717 (a_gene - a_chromosome->genes)*sizeof (struct gene));
718 memcpy (mixed_gene, b_gene,
719 b_gene_size*sizeof (struct gene));
720 memcpy (mixed_gene + b_gene_size, a_gene + a_gene_size,
721 ((a_chromosome->genes + a_chromosome->gene_count) -
722 (a_gene + a_gene_size))*sizeof (struct gene));
723
724 mixed_gene->up = a_gene->up;
725 for (struct gene *gene = mixed_gene; gene->up; gene -= gene->up) {
726 if (gene->up > 1) continue; // we came from right, no change needed
727 struct gene *up = gene - gene->up;
728 up->left_size += gene_count_delta;
729 if (gene__decode (up->value).type == GENE_TYPE_FUNCTION_2NARY)
730 up[1 + up->left_size].up += gene_count_delta;
731 }
732}
733
734void
735crossover_operator__nodal (int a, int b)
736{
737 struct chromosome *a_chromosome = &population.chromosomes[a];
738 struct chromosome *b_chromosome = &population.chromosomes[b];
739
740 memcpy (a_chromosome, &population.breeding_pool[a], sizeof (*a_chromosome));
741 memcpy (b_chromosome, &population.breeding_pool[b], sizeof (*b_chromosome));
742
743 int a_gene_count = a_chromosome->gene_count;
744 int b_gene_count = b_chromosome->gene_count;
745
746 struct gene *b_gene, *a_gene = &a_chromosome->genes[rand () % a_gene_count];
747 enum gene_type b_gene_type, a_gene_type = gene__decode (a_gene->value).type;
748 int attempts = 0;
749 do {
750 b_gene = &b_chromosome->genes[rand () % b_gene_count];
751 b_gene_type = gene__decode (b_gene->value).type;
752 } while (attempts++ < 5 &&
753 b_gene_type != a_gene_type
754 && (a_gene_type > 1 || b_gene_type > 1));
755
756 float tmp = a_gene->value;
757 a_gene->value = b_gene->value;
758 b_gene->value = tmp;
759}
760
761void
762crossover_operator__subtree (int a, int b)
763{
764 struct chromosome *a_chromosome = &population.breeding_pool[a];
765 struct chromosome *b_chromosome = &population.breeding_pool[b];
766
767 struct chromosome *a_chromosome_target = &population.chromosomes[a];
768 struct chromosome *b_chromosome_target = &population.chromosomes[b];
769
770 uint32_t a_gene_count = a_chromosome->gene_count;
771 uint32_t b_gene_count = b_chromosome->gene_count;
772
773 struct gene *b_gene;
774 struct gene *a_gene = &a_chromosome->genes[rand () % a_gene_count];
775
776 uint32_t b_gene_size;
777 uint32_t a_gene_size = gene__size (a_gene);
778
779 uint32_t a_gene_count_new;
780 uint32_t b_gene_count_new;
781 int attempts = 0;
782 do {
783 if (++attempts == 3) {
784 memcpy (a_chromosome_target, a_chromosome, sizeof (struct chromosome));
785 memcpy (b_chromosome_target, b_chromosome, sizeof (struct chromosome));
786 return;
787 }
788 b_gene = &b_chromosome->genes[rand () % b_gene_count];
789 b_gene_size = gene__size (b_gene);
790 a_gene_count_new = a_chromosome->gene_count - a_gene_size + b_gene_size;
791 b_gene_count_new = b_chromosome->gene_count - b_gene_size + a_gene_size;
792 } while (a_gene_count_new < MIN_GENE_COUNT || a_gene_count_new > MAX_GENE_COUNT ||
793 b_gene_count_new < MIN_GENE_COUNT || b_gene_count_new > MAX_GENE_COUNT);
794
795 chromosome__mix_subtree (a_chromosome_target,
796 a_chromosome, a_gene, a_gene_size,
797 b_chromosome, b_gene, b_gene_size);
798 chromosome__mix_subtree (b_chromosome_target,
799 b_chromosome, b_gene, b_gene_size,
800 a_chromosome, a_gene, a_gene_size);
801}
802
803void
804crossover_operator__mixed (int a, int b)
805{
806 switch (rand () % 2) {
807 case 0: return crossover_operator__nodal (a, b);
808 case 1: return crossover_operator__subtree (a, b);
809 }
810}
811
812typedef void (*crossover_operator) (int a, int b);
813
814void
815crossover (int population_size, float probability, crossover_operator operator)
816{
817 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
818
819 for (int i = 0; i < population_size; i += 2) {
820 int a = i;
821 int b = (i + 1) % population_size;
822
823 if (rand () /(float) RAND_MAX > probability) {
824 memcpy (&population.chromosomes[a], &population.breeding_pool[a], sizeof (struct chromosome));
825 memcpy (&population.chromosomes[b], &population.breeding_pool[b], sizeof (struct chromosome));
826 } else operator (a, b);
827 }
828}
829
830void
831mutation_operator__nodal (struct chromosome *chromosome)
832{
833 struct gene *gene = &chromosome->genes[rand () % chromosome->gene_count];
834 struct gene_code code = gene__decode (gene->value);
835 switch (code.type) {
836 case GENE_TYPE_FUNCTION_2NARY: gene->value = gene__random_function_2nary (); break;
837 case GENE_TYPE_FUNCTION_1NARY: gene->value = gene__random_function_1nary (); break;
838 case GENE_TYPE_VARIABLE: __attribute__ ((fallthrough));
839 case GENE_TYPE_CONSTANT: gene->value = gene__random_terminal (); break;
840 }
841}
842
843void
844mutation_operator__truncating (struct chromosome *chromosome)
845{
846 int attempts = 0;
847 retry:
848 struct gene *gene = &chromosome->genes[1 + rand () % (chromosome->gene_count - 1)];
849 struct gene_code code = gene__decode (gene->value);
850 if (GENE_TYPE_TERMINAL (code.type)) {
851 // NOTE(cmmm): could move up and cut single branch or whole subtree
852 // gene->value = gene__random_terminal ();
853 // return;
854
855 gene -= gene->up;
856 code = gene__decode (gene->value);
857 }
858
859 uint32_t gene_size = gene__size (gene);
860 if (chromosome->gene_count - gene_size < MIN_GENE_COUNT) {
861 if (++attempts == 5)
862 return;
863 goto retry;
864 }
865
866 gene->value = gene__random_terminal ();
867 gene->left_size = 0;
868
869 memmove (gene + 1, gene + gene_size,
870 ((chromosome->genes + chromosome->gene_count) -
871 (gene + 1))*sizeof (struct gene));
872
873 chromosome->gene_count -= gene_size - 1;
874
875 for (struct gene *head = gene; head->up; head -= head->up) {
876 if (head->up > 1) continue; // we came from right, no change needed
877 struct gene *up = head -head->up;
878 up->left_size -= gene_size - 1;
879 if (gene__decode (up->value).type == GENE_TYPE_FUNCTION_2NARY)
880 up[1 + up->left_size].up -= gene_size - 1;
881 }
882}
883
884void
885mutation_operator__growing (struct chromosome *chromosome)
886{
887 if (chromosome->gene_count == MAX_GENE_COUNT) return;
888
889 struct gene *root_gene = &chromosome->genes[rand () % chromosome->gene_count];
890 struct gene_code code = gene__decode (root_gene->value);
891 while (GENE_TYPE_FUNCTION (code.type)) {
892 root_gene += 1;
893 if (code.type == GENE_TYPE_FUNCTION_2NARY && rand () % 2)
894 root_gene += root_gene->left_size;
895 code = gene__decode (root_gene->value);
896 }
897
898 uint32_t size =
899 2 + (chromosome->gene_count + 1 != MAX_GENE_COUNT
900 ? rand () % (MAX_GENE_COUNT - chromosome->gene_count - 1) : 0);
901 size = MIN (size, 1 + MUTATION_OPERATOR__GROWING__MAX_SIZE);
902
903 memmove (root_gene + size, root_gene + 1,
904 ((chromosome->genes + chromosome->gene_count) -
905 (root_gene + 1))*sizeof (struct gene));
906
907 size -= 1;
908 chromosome->gene_count += size;
909
910 for (struct gene *gene = root_gene; gene->up; gene -= gene->up) {
911 if (gene->up > 1) continue; // we came from right, no change needed
912 struct gene *up = gene -gene->up;
913 up->left_size += size;
914 if (gene__decode (up->value).type == GENE_TYPE_FUNCTION_2NARY)
915 up[1 + up->left_size].up += size;
916 }
917
918 static struct {
919 uint32_t *items;
920 uint32_t count;
921 uint32_t capacity;
922 } stack = {0};
923
924 uint32_t top = 0;
925 uint32_t open_slots = 1;
926 DYNAMIC_ARRAY__RESET (stack);
927 DYNAMIC_ARRAY__APPEND (stack, 0);
928 while (stack.count) {
929 uint32_t i = top++;
930 uint32_t back = DYNAMIC_ARRAY__POP (stack);
931 struct gene *gene = &root_gene[i];
932
933 if (i == 0);
934 else if (back == UINT_MAX) gene->up = 1;
935 else {
936 gene->up = i - back;
937 root_gene[back].left_size = gene->up - 1;
938 }
939
940 switch (size >= open_slots ? rand () % 2 : rand () % 3) {
941 case 0: // 2nary
942 if (size >= 2) {
943 size -= 2;
944 open_slots += 1;
945 gene->left_size = 0;
946 gene->value = gene__random_function_2nary ();
947 DYNAMIC_ARRAY__APPEND (stack, i );
948 DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
949 continue;
950 } __attribute__ ((fallthrough));
951
952 case 1: // 1nary
953 if (size >= 1) {
954 size -= 1;
955 gene->left_size = 0;
956 gene->value = gene__random_function_1nary ();
957 DYNAMIC_ARRAY__APPEND (stack, UINT_MAX);
958 continue;
959 } __attribute__ ((fallthrough));
960
961 case 2: { // 0nary
962 open_slots -= 1;
963 gene->left_size = 0;
964 gene->value = gene__random_terminal ();
965 if (gene == root_gene) break;
966 uint32_t count = 1;
967 struct gene *up = gene - gene->up;
968 do {
969 switch (gene__decode (up->value).type) {
970 case GENE_TYPE_FUNCTION_2NARY: count += up->left_size + 1; break;
971 case GENE_TYPE_FUNCTION_1NARY: up->left_size = count++; break;
972 default: UNREACHABLE ();
973 } up -= up->up;
974 } while (up != root_gene - root_gene->up);
975 }
976 }
977 }
978}
979
980void
981mutation_operator__mixed (struct chromosome *chromosome)
982{
983 if (rand () % 4 == 0) {
984 mutation_operator__nodal (chromosome);
985 } else if (chromosome->gene_count >= MIN_GENE_COUNT + (MAX_GENE_COUNT - MIN_GENE_COUNT + 1)/2) {
986 mutation_operator__truncating (chromosome);
987 } else {
988 mutation_operator__growing (chromosome);
989 }
990}
991
992typedef void (*mutation_operator) (struct chromosome *);
993
994void
995mutation (int population_size, float probability, mutation_operator operator)
996{
997 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
998
999 for (int i = 0; i < population_size; ++i) {
1000 if (rand () /(float) RAND_MAX > probability)
1001 continue;
1002 operator (&population.chromosomes[i]);
1003 }
1004}
1005
1006float
1007variable__random_from_limit (struct variable_limit limit)
1008{
1009 return limit.min + (limit.max - limit.min)*rand ()/RAND_MAX;
1010}
1011
1012void
1013sample_real_function (void)
1014{
1015 for (int i = 0; i < REAL_SAMPLE_COUNT; ++i) {
1016 for (int j = 0; j < VARIABLE_COUNT; ++j) {
1017 real_samples[i].variables[j] = variable__random_from_limit (variable_limits[j]);
1018 } real_samples[i].output = real_function (real_samples[i].variables);
1019 }
1020}
1021
1022void
1023plot_fitness_over_generations (const char *output, int generations)
1024{
1025 FILE *gp = popen ("gnuplot", "w");
1026 // FILE *gp = fopen ("test.gp", "w");
1027 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
1028 " nocrop size 15cm,10cm noheader\n");
1029 fprintf (gp, "set output '%s.tex'\n", output);
1030
1031 // fprintf (gp, "set xrange [0:%d]\n", GENERATIONS_MAX);
1032 fprintf (gp, "set yrange [*:150000]\n");
1033 fprintf (gp, "set xlabel '№ поколения'\n");
1034 fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n");
1035
1036 fprintf (gp, "plot ");
1037 fprintf (gp, "'-' with lines title 'Лучшее значение'\n");
1038
1039 for (int i = 0; i <= generations; ++i) {
1040 fprintf (gp, "%d %f\n", i, sqrtf (generations__fitness[i]));
1041 } fprintf (gp, "e\n");
1042
1043 pclose (gp);
1044}
1045
1046int
1047main (int argc, char *argv[])
1048{
1049 PRINT_EXP ("%u", (uint32_t) SEED);
1050 PRINT_EXP ("%d", GENERATIONS_MAX);
1051 PRINT_EXP ("%d", ELITE_COUNT);
1052 PRINT_EXP ("%d", TOURNAMENT_SIZE);
1053 PRINT_EXP ("%d", REAL_SAMPLE_COUNT);
1054 PRINT_EXP ("%f", TRAINING_TESTING_DATA_RATION);
1055 PRINT_EXP ("%f", FITNESS_FUNCTION__WEIGHT__MSE);
1056 PRINT_EXP ("%f", FITNESS_FUNCTION__WEIGHT__GENE_COUNT);
1057 PRINT_EXP ("%+f", CONSTANT_MIN );
1058 PRINT_EXP ("%+f", CONSTANT_MAX );
1059 PRINT_EXP ("%d", MIN_GENE_COUNT);
1060 PRINT_EXP ("%d", MAX_GENE_COUNT);
1061
1062 chromosome__plot (NULL, "res/plot-real");
1063
1064 srand (SEED);
1065 sample_real_function ();
1066
1067 struct chromosome elite_buffer[ELITE_COUNT];
1068 int population_size = POPULATION_CAPACITY;
1069 create_initial_population (population_size);
1070 for (int generation = 0; generation < GENERATIONS_MAX; ++generation) {
1071 measure_fitness (population_size, generation, true);
1072
1073 if (generation % 10 == 0) {
1074 printf ("generation: %5d, fitness: %.0f: gene count: %d\n",
1075 generation, sqrtf (population.best.fitness),
1076 population.chromosomes[population.best.index].gene_count);
1077 }
1078
1079 if (generation % 100 == 0) {
1080 char *filename = NULL;
1081 asprintf (&filename, "res/tree-generation%03d", generation);
1082 chromosome__export__dot (&population.chromosomes[population.best.index], filename);
1083 free (filename);
1084 filename = NULL;
1085 asprintf (&filename, "res/plot-generation%03d", generation);
1086 chromosome__plot (&population.chromosomes[population.best.index], filename);
1087 free (filename);
1088 }
1089
1090 selection__tournament (population_size, TOURNAMENT_SIZE);
1091 for (int i = 0; i < ELITE_COUNT; ++i) {
1092 memcpy (&elite_buffer[i], &population.chromosomes[population.elites[i].index],
1093 sizeof (struct chromosome));
1094 } memcpy (&population.chromosomes[population_size - ELITE_COUNT], elite_buffer,
1095 ELITE_COUNT*sizeof (struct chromosome));
1096 crossover (population_size - ELITE_COUNT, .8, crossover_operator__subtree);
1097 mutation (population_size - ELITE_COUNT, .8, mutation_operator__mixed);
1098 } measure_fitness (population_size, GENERATIONS_MAX, false);
1099
1100 printf ("testing:\n");
1101 for (int i = 0; i < population_size; ++i) {
1102 printf ("%d %f\n", i, sqrtf (population.fitness[i]));
1103 } printf ("best: %f\n", sqrtf (population.best.fitness));
1104 chromosome__export__dot (&population.chromosomes[population.best.index], "res/best-tree");
1105 chromosome__plot (&population.chromosomes[population.best.index], "res/best-plot");
1106 plot_fitness_over_generations ("res/fitness", GENERATIONS_MAX);
1107
1108 return EXIT_SUCCESS;
1109}