From 2499640c7149f34f5bed38fc93c586b78d514140 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 08:42:14 +0300 Subject: publish --- src/real-genetic-algorithm.c | 541 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 541 insertions(+) create mode 100644 src/real-genetic-algorithm.c (limited to 'src') diff --git a/src/real-genetic-algorithm.c b/src/real-genetic-algorithm.c new file mode 100644 index 0000000..172c97c --- /dev/null +++ b/src/real-genetic-algorithm.c @@ -0,0 +1,541 @@ +// real-genetic-algorithm.c --- real genetic algorithm +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define POPULATION_CAPACITY 500 +#define CHROMOSOME_SIZE 2 +#define GENERATION_MAX 2000 +#define FITNESS_TRESHOLD_EPSILON 1e-3 +#define FITNESS_OPTIMAL -1 +#define MINMAX -1 +#define X_MIN ((float) -100) +#define X_MAX ((float) +100) +#define Y_MIN X_MIN +#define Y_MAX X_MAX +#define Z_MIN ((float) -1.0) +#define Z_MAX ((float) +0.5) +#define X_MIN_ZOOM ((float) M_PI - 2) +#define X_MAX_ZOOM ((float) M_PI + 2) +#define Y_MIN_ZOOM X_MIN_ZOOM +#define Y_MAX_ZOOM X_MAX_ZOOM +#define PLOT_SAMPLE_COUNT 100 +// #define SEED time (NULL) +#define SEED 1760564672 +#define MEASUREMENT_RUNS 10 + +int population_sizes [] = { 50, 100, 200, 500 }; +float probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 }; +float probabilities_mutation [] = { 0.01, 0.05, 0.1, 0.2, 0.3 }; + +float mutation_limits[CHROMOSOME_SIZE][2] = { { X_MIN, X_MAX }, + { Y_MIN, Y_MAX } }; + +#define ASSERT assert +#define CTZL __builtin_ctzl +#define EPSILON 1e-12 + +#define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T))) +#define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \ + for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \ + (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \ + +typedef float gene; +typedef gene chromosome[CHROMOSOME_SIZE]; + +struct measurement { + float fitness; + float time; + int generations; +}; + +chromosome population [POPULATION_CAPACITY]; +chromosome population_breeding_pool [POPULATION_CAPACITY]; +float population_fitness [POPULATION_CAPACITY]; +float population_fitness_normalized [POPULATION_CAPACITY]; +float population_fitness_normalized_min; +float population_cdf [POPULATION_CAPACITY]; +chromosome generation_bests [GENERATION_MAX]; +float generation_bests_fitness [GENERATION_MAX]; +float plot_samples [PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3]; +float plot_samples_zoom [PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3]; +struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)] + [ARRAY_LENGTH (probabilities_mutation )]; + +float +fitness_function (chromosome x) +{ + return -(cosf (x[0]) * + cosf (x[1]) * + expf (-((x[0] - M_PI)*(x[0] - M_PI) + + (x[1] - M_PI)*(x[1] - M_PI)))); +} + +void +create_initial_population (int population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (int i = 0; i < population_size; ++i) { + for (int j = 0; j < CHROMOSOME_SIZE; ++j) { + population[i][j] = X_MIN + (X_MAX - X_MIN)*(rand () /(float) RAND_MAX); + } + } +} + +bool +measure_fitness (int population_size, int generation) +{ + ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY); + + population_fitness_normalized_min = DBL_MAX; + int population_best_i = 0; + float population_best_fitness = DBL_MAX; + for (int i = 0; i < population_size; ++i) { + float fitness = fitness_function (population[i]); + float fitness_normalized = MINMAX*fitness; + population_fitness [i] = fitness; + population_fitness_normalized [i] = fitness_normalized; + if (fitness_normalized < population_fitness_normalized_min) + population_fitness_normalized_min = fitness_normalized; + if (MINMAX*(fitness - population_best_fitness) > 0) { + population_best_i = i; + population_best_fitness = fitness; + } + } + population_fitness_normalized_min -= 1e-12; + + memcpy (generation_bests[generation], population[population_best_i], sizeof (chromosome)); + generation_bests_fitness[generation] = population_best_fitness; + + return fabsf (population_best_fitness - FITNESS_OPTIMAL) < FITNESS_TRESHOLD_EPSILON; +} + +void +selection__fitness_proportionate (int population_size) +{ + ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY); + + float population_fitness_sum = 0; + for (int i = 0; i < population_size; ++i) { + population_fitness_sum += + population_fitness_normalized[i] -= population_fitness_normalized_min; + } + + float last = 0; + for (int i = 0; i < population_size; ++i) { + last = population_cdf[i] = + last + population_fitness_normalized[i]/population_fitness_sum; + } + + for (int i = 0; i < population_size; ++i) { + float a = rand () /(float) RAND_MAX; + int j = 0; + // TODO(cmmm): use binary search + while (j < population_size) { + if (population_cdf[j] > a) break; + j += 1; + } + + memcpy (population_breeding_pool[i], population[j], + sizeof (population_breeding_pool[i])); + } +} + +void +crossover__sbx (int population_size, float probability, float n) +{ + ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY); + ASSERT (2 <= n && n <= 5); + + for (int i = 0; i < population_size; i += 2) { + int i_a = i; + int i_b = (i + 1) % population_size; + + gene *a = &population_breeding_pool[i_a][0]; + gene *b = &population_breeding_pool[i_b][0]; + + if (rand () /(float) RAND_MAX > probability) { + memcpy (population[i_a], a, sizeof (chromosome)); + memcpy (population[i_b], b, sizeof (chromosome)); + } else { + for (int k = 0; k < CHROMOSOME_SIZE; ++k) { + float u = rand () /(float) RAND_MAX; + float beta = powf (u <= 0.5 ? 2*u : (0.5/(1 - u)), 1/(n + 1)); + + population[i_a][k] = ((1 - beta)*a[k] + (1 + beta)*b[k])/2; + population[i_b][k] = ((1 + beta)*a[k] + (1 - beta)*b[k])/2; + // NOTE(cmmm): uses X limits for all dimensions... + population[i_a][k] = fmin (X_MAX, fmax (X_MIN, population[i][k])); + population[i_b][k] = fmin (X_MAX, fmax (X_MIN, population[i][k])); + } + } + } +} + +void +mutation__uniform (int population_size, float probability) +{ + ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY); + + for (int i = 0; i < population_size; ++i) { + if (rand () /(float) RAND_MAX > probability) + continue; + + int k = rand () % CHROMOSOME_SIZE; + float d = mutation_limits[k][rand () % 2] - population[i][k]; + float r = rand () /(float) RAND_MAX; + population[i][k] += d*r; + } +} + +void +mutation__non_uniform (int population_size, float probability, + int generation, float generation_relation) +{ + ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY); + + for (int i = 0; i < population_size; ++i) { + if (rand () /(float) RAND_MAX > probability) + continue; + + int k = rand () % CHROMOSOME_SIZE; + float r = rand () /(float) RAND_MAX; + float y = mutation_limits[k][rand () % 2] - population[i][k]; + + population[i][k] += y*(1 - powf (r, powf (1 - generation /(float) GENERATION_MAX, + generation_relation))); + } +} + +void +plot (const char *output, int population_size, int generation, + float x_min, float x_max, float y_min, float y_max, + float samples[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3]) +{ + const char *ext = "tex"; + FILE *gp = popen ("gnuplot", "w"); + // FILE *gp = fopen ("test.gp", "w"); + // fprintf (gp, "set term png\n"); + fprintf (gp, "set term cairolatex png input blacktext notransparent" + " nocrop size 9cm,9cm noheader\n"); + fprintf (gp, "set output '%s.%s'\n", output, ext); + + fprintf (gp, "set lmargin at screen 0.30\n"); + fprintf (gp, "set rmargin at screen 0.83\n"); + fprintf (gp, "set bmargin at screen 0.05\n"); + fprintf (gp, "set tmargin at screen 1.00\n"); + + // fprintf (gp, "set title 'Поколение №%d, \\quad Лучшая особь: \\num{%g}'\n", + // generation, generation_bests_fitness[generation]); + fprintf (gp, "set xlabel '\\(x_1\\)'\n"); + fprintf (gp, "set ylabel '\\(x_2\\)'\n"); + fprintf (gp, "set zlabel '\\(f(x_1, x_2)\\)' offset graph -0.1, 0 rotate by 90\n"); + fprintf (gp, "set xrange [%f:%f]\n", x_min, x_max); + fprintf (gp, "set yrange [%f:%f]\n", y_min, y_max); + fprintf (gp, "set zrange [%f:%f]\n", Z_MIN, Z_MAX); + 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 ztics offset graph +0.02, graph +0.05\n"); + fprintf (gp, "unset key\n"); + + fprintf (gp, "set pm3d at bs interpolate 0,0 explicit\n"); + fprintf (gp, "set ticslevel 0\n"); + + fprintf (gp, "set view equal xy\n"); + fprintf (gp, "unset colorbox\n"); + fprintf (gp, "splot "); + fprintf (gp, "'-' smooth acsplines with pm3d title '%s', ", "\\small{Целевая функция}"); + if (generation > 0) + fprintf (gp, "'-' with points pt 3 ps 1 lc 'yellow' title '\\small{Лучшие особи}',"); + fprintf (gp, "'-' with points pt 3 ps 1.2 lc 'magenta' title '\\small{Минимум}',"); + fprintf (gp, "'-' with points pt 7 ps 1 lc 'green' title '\\small{Лучшая особь поколения}',"); + fprintf (gp, "'-' with points pt 7 ps 0.5 lc 'red' title '\\small{Популяция}'\n"); + for (int x = 0; x < PLOT_SAMPLE_COUNT; ++x) { + for (int y = 0; y < PLOT_SAMPLE_COUNT; ++y) { + fprintf (gp, "%f %f %f\n", + samples[x][y][0], + samples[x][y][1], + samples[x][y][2]); + } fprintf (gp, "\n"); + } fprintf (gp, "e\n"); + if (generation > 0) { + for (int i = 0; i < generation; ++i) { + for (int j = 0; j < CHROMOSOME_SIZE; ++j) + fprintf (gp, "%f ", generation_bests[i][j]); + fprintf (gp, "%f\n", generation_bests_fitness[i]); + } fprintf (gp, "e\n"); + } + fprintf (gp, "%f %f %f\ne\n", M_PI, M_PI, -1.); + for (int j = 0; j < CHROMOSOME_SIZE; ++j) + fprintf (gp, "%f ", generation_bests[generation][j]); + fprintf (gp, "%f\ne\n", generation_bests_fitness[generation]); + for (int i = 0; i < population_size; ++i) { + for (int j = 0; j < CHROMOSOME_SIZE; ++j) + fprintf (gp, "%f ", population[i][j]); + fprintf (gp, "%f\n", population_fitness[i]); + } fprintf (gp, "e\n"); + + fprintf (gp, "set term cairolatex png input blacktext notransparent" + " nocrop size 7cm,7cm noheader\n"); + fprintf (gp, "set output '%s-map.%s'\n", output, ext); + fprintf (gp, "set lmargin at screen 0.15\n"); + fprintf (gp, "set rmargin at screen 0.85\n"); + fprintf (gp, "set bmargin at screen 0.15\n"); + fprintf (gp, "set tmargin at screen 0.90\n"); + fprintf (gp, "set xtics offset graph 0, graph +0.02\n"); + fprintf (gp, "set ytics nooffset\n"); + fprintf (gp, "set xlabel offset graph 0, graph +0.05\n"); + // fprintf (gp, "set title offset 0,-1\n"); + fprintf (gp, "set view map\n"); + fprintf (gp, "unset key\n"); + fprintf (gp, "set colorbox\n"); + fprintf (gp, "refresh\n"); + + fclose (gp); +} + +void +run_experiment__plot (int population_size, + float probability_crossover, + float probability_mutation) +{ + void + plot_generation (int generation) + { + static char plot_output[256]; + + snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u", + population_size, probability_crossover, + probability_mutation, generation); + plot (plot_output, population_size, generation, + X_MIN, X_MAX, Y_MIN, Y_MAX, plot_samples); + + snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u-zoom", + population_size, probability_crossover, + probability_mutation, generation); + plot (plot_output, population_size, generation, + X_MIN_ZOOM, X_MAX_ZOOM, Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom); + } + + create_initial_population (population_size); + int generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + if (measure_fitness (population_size, generation)) break; + + printf ("generation: %d, fitness: %g, ", + generation, generation_bests_fitness[generation]); + printf ("chromosome:"); + for (int i = 0; i < CHROMOSOME_SIZE; ++i) { + printf (" %f", generation_bests[generation][i]); + } printf ("\n"); + if (generation % 10 == 0 || generation < 10) + plot_generation (generation); + + selection__fitness_proportionate (population_size); + crossover__sbx (population_size, probability_crossover, 2); + mutation__non_uniform (population_size, probability_mutation, generation, 1); + } + if (generation == GENERATION_MAX) + measure_fitness (population_size, generation); + printf ("generation: %lu, fitness: %lf, ", + generation, generation_bests_fitness[generation]); + printf ("chromosome:"); + for (int i = 0; i < CHROMOSOME_SIZE; ++i) { + printf (" %f", generation_bests[generation][i]); + } printf ("\n"); + plot_generation (generation); +} + +struct measurement +run_experiment__measure (int population_size, + float probability_crossover, + float probability_mutation) +{ + float total_fitness = 0; + float total_time = 0; + int total_generations = 0; + for (int run = 0; run < MEASUREMENT_RUNS; ++run) { + clock_t begin = clock (); + create_initial_population (population_size); + int generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + if (measure_fitness (population_size, generation)) break; + selection__fitness_proportionate (population_size); + crossover__sbx (population_size, probability_crossover, 2); + mutation__uniform (population_size, probability_mutation); + } + float time = (clock () - begin) /(float) CLOCKS_PER_SEC; + total_time += time; + total_generations += generation; + total_fitness += generation_bests_fitness[generation - (generation == GENERATION_MAX)]; + } + + return (struct measurement) { + .fitness = total_fitness/MEASUREMENT_RUNS, + .time = total_time/MEASUREMENT_RUNS, + .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS, + }; +} + +void +sample_fitness_function (float x_min, float x_max, + float y_min, float y_max, + float samples[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3]) +{ + float x = x_min; + float dx = (x_max - x_min)/(PLOT_SAMPLE_COUNT - 1); + for (int i = 0; i < PLOT_SAMPLE_COUNT; ++i) { + float y = y_min; + float dy = (y_max - y_min)/(PLOT_SAMPLE_COUNT - 1); + for (int j = 0; j < PLOT_SAMPLE_COUNT; ++j) { + samples[i][j][0] = x; + samples[i][j][1] = y; + samples[i][j][2] = fitness_function ((chromosome) { x, y }); + y += dy; + } x += dx; + } +} + +typedef int (*print_function)(void *user, const char *template, ...); +typedef int (*cell_function)(int x, int y, print_function, void *); + +int +print__measure (void *user, const char *template, ...) +{ + va_list ap; + va_start (ap, template); + int len = vsnprintf (NULL, 0, template, ap); + va_end (ap); + return len; +} + +int +print__stream (void *stream, const char *template, ...) +{ + va_list ap; + va_start (ap, template); + int len = vfprintf (stream, template, ap); + va_end (ap); + return len; +} + +void +print_org_table (const char *filename, const char *name, const char *caption, + const char *align, int rows, int cols, cell_function cell) +{ + int cell_widths[rows][cols]; + int column_widths[cols]; + memset (column_widths, 0, sizeof (column_widths)); + for (int y = 0; y < rows; ++y) { + for (int x = 0; x < cols; ++x) { + cell_widths[y][x] = cell (x, y, print__measure, NULL); + if (cell_widths[y][x] > column_widths[x]) + column_widths[x] = cell_widths[y][x];; + } + } + + FILE *stream = fopen (filename, "w"); + if (name ) fprintf (stream, "#+name: %s\n", name); + if (caption) fprintf (stream, "#+caption: %s\n", caption); + if (align ) fprintf (stream, "#+attr_latex: :align %s\n", align); + for (int y = 0; y < rows; ++y) { + fprintf (stream, "|"); + for (int x = 0; x < cols; ++x) { + fprintf (stream, " "); + if (x == 0) { + for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i) + fprintf (stream, " "); + } + cell (x, y, print__stream, stream); + if (x > 0) { + for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i) + fprintf (stream, " "); + } + fprintf (stream, " |"); + } fprintf (stream, "\n"); + if (y == 0) { + fprintf (stream, "|"); + for (int x = 0; x < cols; ++x) { + for (int i = 0; i < column_widths[x] + 2; ++i) + fprintf (stream, "-"); + fprintf (stream, "|"); + } fprintf (stream, "\n"); + } + } + + fclose (stream); +} + +int +main (int argc, char *argv[]) +{ + printf ("SEED: %u\n", SEED); + srand (SEED); + + // sample_fitness_function (X_MIN, X_MAX, + // Y_MIN, Y_MAX, plot_samples); + // sample_fitness_function (X_MIN_ZOOM, X_MAX_ZOOM, + // Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom); + // run_experiment__plot (200, .8, .4); + // return 0; + + struct measurement *best_measurement = &measurements[0][0]; + FOR_EACH_ELEMENT (population_size, population_sizes) { + struct measurement *measurement = &measurements[0][0]; + FOR_EACH_ELEMENT (probability_crossover, probabilities_crossover) { + FOR_EACH_ELEMENT (probability_mutation, probabilities_mutation) { + printf ("experiment: %4d %.3f %.3f", *population_size, + *probability_crossover, *probability_mutation); + fflush (stdout); + *measurement = run_experiment__measure (*population_size, + *probability_crossover, + *probability_mutation); + printf (" @ %6.2f ms\n", measurement->time*1e+3); + if (measurement->time < best_measurement->time) + best_measurement = measurement; + measurement += 1; + } + } + + char *table_filename, *table_name, *table_caption; + asprintf (&table_filename, "res/results-%03lu.org", *population_size); + asprintf (&table_name, "results-%lu", *population_size); + asprintf (&table_caption, "Результаты для \\(N = %lu\\)", + *population_size); + int table_cell (int x, int y, print_function print, void *user) + { + int m = x - 1; + int c = y - 1; + if (x == 0 && y == 0) return print (user, "\\(P_c \\;\\backslash\\; P_m\\)"); + if ( y == 0) return print (user, "%.3g", probabilities_mutation [m]); + if (x == 0 ) return print (user, "%.1g", probabilities_crossover[c]); + + int len = 0; + bool is_best = &measurements[c][m] == best_measurement; + if (is_best) print (user, "*"); + len += print (user, "\\makecell{%.2f (%lu) \\\\ %f}", + measurements[c][m].time*1e+3, + measurements[c][m].generations, + measurements[c][m].fitness); + if (is_best) print (user, "*"); + + return len; + } + print_org_table (table_filename, table_name, table_caption, "cccccc", + 1 + ARRAY_LENGTH (probabilities_crossover), + 1 + ARRAY_LENGTH (probabilities_mutation), table_cell); + } + + return EXIT_SUCCESS; +} + +// real-genetic-algorithm.c ends here -- cgit v1.3.1