From 46ca10dd122b52374272f636d09ca0831c3378e7 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 08:58:05 +0300 Subject: publish --- src/genetic-programming.c | 1109 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1109 insertions(+) create mode 100644 src/genetic-programming.c (limited to 'src/genetic-programming.c') 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 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#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; +} -- cgit v1.3.1