From e575815702e42efe5ba9d2732a1c6ae5dc752585 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 09:15:19 +0300 Subject: publish --- src/evolution-strategy.c | 638 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 638 insertions(+) create mode 100644 src/evolution-strategy.c (limited to 'src') diff --git a/src/evolution-strategy.c b/src/evolution-strategy.c new file mode 100644 index 0000000..8a5042a --- /dev/null +++ b/src/evolution-strategy.c @@ -0,0 +1,638 @@ +// evolution-strategy.c --- evolution strategy +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define POPULATION_CAPACITY 360 +#define CHROMOSOME_SIZE 2 +#define GENERATION_MAX 2000 +#define FITNESS_OPTIMAL -1 +#define FITNESS_TRESHOLD_EPSILON 1e-6 +#define MINMAX -1 +#define X_MIN ((float) -100) +#define X_MAX ((float) +100) +#define Y_MIN X_MIN +#define Y_MAX X_MAX +#define SIGMA_INITIAL 2.0 +#define TAU (1/sqrtf (2*sqrtf (CHROMOSOME_SIZE))) + +#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 1762730873 + +#define MEASUREMENT_RUNS 100 + +struct population_size { int mu, lambda; } population_sizes [] = { + { 10, 70 }, + { 20, 70 }, + { 20, 140 }, + { 40, 140 }, + { 40, 280 }, + { 80, 280 }, +}; + +float initial_sigmas [] = { + 0.1, + 0.2, + 0.4, + 0.8, + 1.0, + 2.0, + 4.0, + 8.0, + 15.0, + 30.0, + 50.0, + 100.0, +}; + +struct { + float min; + float max; +} variable_limits[CHROMOSOME_SIZE] = { + { X_MIN, X_MAX }, + { Y_MIN, Y_MAX }, +}; + +#define ASSERT assert +#define CTZL __builtin_ctzl +#define EPSILON 1e-12 + +#define PRINT_EXP(FMT, ...) printf (#__VA_ARGS__" = "FMT"\n", __VA_ARGS__) + +#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)) \ + +struct gene { + float value; + float sigma; +}; + +struct chromosome { + float fitness; + struct gene genes[CHROMOSOME_SIZE]; +}; + +struct measurement { + float fitness; + float time; + int generations; +}; + +struct chromosome population [POPULATION_CAPACITY]; +struct chromosome generation_bests[GENERATION_MAX + 1]; +float generation_average_fitness[GENERATION_MAX + 1]; + +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 (initial_sigmas )] + [ARRAY_LENGTH (population_sizes)]; + +float +easom (float x1, float x2) +{ + return -(cosf (x1)*cosf (x2)*expf (-((x1 - M_PI)*(x1 - M_PI) + + (x2 - M_PI)*(x2 - M_PI)))); +} + +float +fitness_function (float *values, size_t stride) +{ + float x1 = *values; values += stride / sizeof(*values); + float x2 = *values; + return easom (x1, x2); +} + +float +rand_normal (float mean, float stddev) { + float u1 = ((float) rand () + 1)/((float) RAND_MAX + 1); + float u2 = ((float) rand () + 1)/((float) RAND_MAX + 1); + float z0 = sqrtf (-2.0*logf (u1))*cosf (2*M_PI*u2); + return mean + z0*stddev; +} + +float +rand_from_range (float min, float max) +{ + return min + (max - min)*(rand () /(float) RAND_MAX); +} + +void +create_initial_population (int population_size, float sigma_initial) +{ + ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY); + + for (int i = 0; i < population_size; ++i) { + for (int j = 0; j < CHROMOSOME_SIZE; ++j) { + population[i].genes[j].value = rand_from_range (variable_limits[j].min, + variable_limits[j].max); + population[i].genes[j].sigma = sigma_initial; + } + } +} + +void +measure_fitness (int from, int to) +{ + ASSERT (0 <= from && from <= POPULATION_CAPACITY); + ASSERT (0 <= to && to <= POPULATION_CAPACITY); + ASSERT (from <= to); + + for (int i = from; i < to; ++i) { + population[i].fitness = fitness_function (&population[i].genes[0].value, + sizeof (*population[i].genes)); + } +} + +bool +should_stop (int generation) +{ + if (generation >= GENERATION_MAX) + return true; + + if (fabs (generation_bests[generation].fitness - FITNESS_OPTIMAL) < FITNESS_TRESHOLD_EPSILON) + return true; + + return false; +} + +void +crossover_oprator ( struct chromosome *to, + const struct chromosome *from_a, + const struct chromosome *from_b) +{ + for (int k = 0; k < CHROMOSOME_SIZE; ++k) { + const struct chromosome *from = rand () % 2 ? from_a : from_b; + to->genes[k].value = from->genes[k].value; + to->genes[k].sigma = from->genes[k].sigma; + } +} + +void +crossover (int mu, int lambda) +{ + ASSERT (mu > 0); + ASSERT (lambda > 0); + ASSERT (mu + lambda <= POPULATION_CAPACITY); + + for (int i = 0; i < lambda; ++i) { + crossover_oprator (&population[mu + i], + &population[rand () % mu], + &population[rand () % mu]); + } +} + +float +clamp (float value, float min, float max) +{ + if (value < min) return min; + if (value > max) return max; + return value; +} + +void +mutation_operator (struct chromosome *chromosome) +{ + for (int k = 0; k < CHROMOSOME_SIZE; ++k) { + struct gene *gene = &chromosome->genes[k]; + gene->sigma *= exp (TAU*rand_normal (0, 1)); + gene->value = clamp (gene->value + rand_normal (0, gene->sigma), + variable_limits[k].min, variable_limits[k].max); + } +} + +void +mutation (int mu, int lambda, float probability) +{ + for (int i = 0; i < lambda; ++i) { + if (rand () /(float) RAND_MAX > probability) continue; + mutation_operator (&population[mu + i]); + } +} + +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 pngcairo\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 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].genes[j].value); + fprintf (gp, "%f\n", generation_bests[i].fitness); + } 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].genes[j].value); + fprintf (gp, "%f\ne\n", generation_bests[generation].fitness); + + for (int i = 0; i < population_size; ++i) { + for (int j = 0; j < CHROMOSOME_SIZE; ++j) + fprintf (gp, "%f ", population[i].genes[j].value); + fprintf (gp, "%f\n", population[i].fitness); + } 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); +} + +int +chromosome__compare_fitness (const void *lhs, const void *rhs) +{ + const struct chromosome *lhs_chromosome = lhs; + const struct chromosome *rhs_chromosome = rhs; + + float diff = MINMAX*(rhs_chromosome->fitness - lhs_chromosome->fitness); + if (diff < 0) return -1; + if (diff > 0) return 1; + return 0; +} + +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 pngcairo\n"); + // fprintf (gp, "set output '%s.png'\n", output); + + 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); + fprintf (gp, "set yrange [-1.1:0.1]\n"); + fprintf (gp, "set xlabel '№ поколения'\n"); + fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n"); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines title 'Лучшее значение',"); + fprintf (gp, "'-' with lines title 'Среднее значение',"); + fprintf (gp, "-1 dt 2 title 'Оптимальное значение'\n"); + + for (int i = 0; i <= generations; ++i) { + fprintf (gp, "%d %f\n", i, generation_bests[i].fitness); + } fprintf (gp, "e\n"); + + for (int i = 0; i <= generations; ++i) { + fprintf (gp, "%d %f\n", i, generation_average_fitness[i]); + } fprintf (gp, "e\n"); + + fclose (gp); +} + +void +run_experiment__plot (int mu, int lambda, float probability_mutation) +{ + void + plot_generation (int generation) + { + static char plot_output[256]; + + snprintf (plot_output, sizeof (plot_output), "res/mu%d-lambda%d-mp%4.2f-g%04d", + mu, lambda, probability_mutation, generation); + plot (plot_output, mu, generation, + X_MIN, X_MAX, Y_MIN, Y_MAX, plot_samples); + + snprintf (plot_output, sizeof (plot_output), "res/mu%d-lambda%d-mp%4.2f-g%04d-zoom", + mu, lambda, probability_mutation, generation); + plot (plot_output, mu, generation, + X_MIN_ZOOM, X_MAX_ZOOM, Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom); + } + + create_initial_population (mu, SIGMA_INITIAL); + measure_fitness (0, mu); + int min = 0; + for (int i = 1; i < mu; ++i) { + if (population[i].fitness < population[min].fitness) + min = i; + } memcpy (&generation_bests[0], &population[min], sizeof (struct chromosome)); + int generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + bool stop = should_stop (generation); + + float sum = 0; + for (int i = 1; i < mu; ++i) { + sum += population[i].fitness; + } generation_average_fitness[generation] = sum/mu; + + printf ("generation: %4d, fitness: %g, ", + generation, generation_bests[generation].fitness); + printf ("chromosome:"); + for (int i = 0; i < CHROMOSOME_SIZE; ++i) { + printf (" %g/%g", + generation_bests[generation].genes[i].value, + generation_bests[generation].genes[i].sigma); + } printf ("\n"); + // plot_generation (generation); + + if (stop) break; + crossover (mu, lambda); + mutation (mu, lambda, probability_mutation); + measure_fitness (mu, mu + lambda); + qsort (population, mu + lambda, sizeof (struct chromosome), + chromosome__compare_fitness); + + memcpy (&generation_bests[generation + 1], &population[0], + sizeof (struct chromosome)); + } + + plot__fitness_over_generations ("res/convergence", generation); +} + +struct measurement +run_experiment__measure (int mu, int lambda, float initial_sigma) +{ + 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 (mu, initial_sigma); + int generation = 0; + measure_fitness (0, mu); + int min = 0; + for (int i = 1; i < mu; ++i) { + if (population[i].fitness < population[min].fitness) + min = i; + } memcpy (&generation_bests[generation], &population[min], + sizeof (struct chromosome)); + while (!should_stop (generation++)) { + crossover (mu, lambda); + mutation (mu, lambda, 1); + measure_fitness (mu, mu + lambda); + qsort (population, mu + lambda, sizeof (struct chromosome), + chromosome__compare_fitness); + memcpy (&generation_bests[generation], &population[0], + sizeof (struct chromosome)); + } + + float time = (clock () - begin) /(float) CLOCKS_PER_SEC; + total_time += time; + total_generations += generation; + total_fitness += generation_bests[generation - (generation == GENERATION_MAX)].fitness; + } + + 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 ((float *) samples[i][j], sizeof (float)); + 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); +} + +struct measurement *best_measurement; +int +table_cell (int x, int y, print_function print, void *user) +{ + int p = x - 1; + int s = y - 1; + if (x == 0 && y == 0) return print (user, "\\(\\sigma^0 \\;\\backslash\\; \\mu/\\lambda\\)"); + if ( y == 0) return print (user, "%d/%d", population_sizes[p].mu, population_sizes[p].lambda); + if (x == 0 ) return print (user, "%.2g", initial_sigmas[s]); + + int len = 0; + bool is_best = &measurements[s][p] == best_measurement; + if (is_best) print (user, "*"); + len += print (user, "\\makecell{%.2f (%lu) \\\\ %f}", + measurements[s][p].time*1e+3, + measurements[s][p].generations, + measurements[s][p].fitness); + if (is_best) print (user, "*"); + + return len; +} + +int +main (int argc, char *argv[]) +{ + PRINT_EXP ("%d", POPULATION_CAPACITY); + PRINT_EXP ("%d", CHROMOSOME_SIZE); + PRINT_EXP ("%d", GENERATION_MAX); + PRINT_EXP ("%f", FITNESS_TRESHOLD_EPSILON); + PRINT_EXP ("%+f", MINMAX); + PRINT_EXP ("%+g", X_MIN); + PRINT_EXP ("%+g", X_MAX); + PRINT_EXP ("%+g", Y_MIN); + PRINT_EXP ("%+g", Y_MAX); + PRINT_EXP ("%d", SIGMA_INITIAL); + PRINT_EXP ("%+f", Z_MIN); + PRINT_EXP ("%+f", Z_MAX); + PRINT_EXP ("%+f", X_MIN_ZOOM); + PRINT_EXP ("%+f", X_MAX_ZOOM); + PRINT_EXP ("%+f", Y_MIN_ZOOM); + PRINT_EXP ("%+f", Y_MAX_ZOOM); + PRINT_EXP ("%d", PLOT_SAMPLE_COUNT); + PRINT_EXP ("%lu", SEED); + PRINT_EXP ("%d", MEASUREMENT_RUNS); + + 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 (40, 240, 1); + return 0; + + best_measurement = &measurements[0][0]; + struct measurement *measurement = &measurements[0][0]; + FOR_EACH_ELEMENT (population_size, population_sizes) { + FOR_EACH_ELEMENT (initial_sigma, initial_sigmas) { + printf ("experiment: [%3d/%3d] %7.3f", + population_size->mu, + population_size->lambda, *initial_sigma); + fflush (stdout); + *measurement = run_experiment__measure (population_size->mu, + population_size->lambda, + *initial_sigma); + printf (" @ %+8.6f/%4d (%6.2f ms)\n", measurement->fitness, measurement->generations, measurement->time*1e+3); + if (measurement->time < best_measurement->time) + best_measurement = measurement; + measurement += 1; + } + } + + char *table_filename = NULL; + char *table_name = NULL; + char *table_caption = NULL; + asprintf (&table_filename, "res/results.org"); + asprintf (&table_name, "results"); + asprintf (&table_caption, "Результаты"); + print_org_table (table_filename, table_name, table_caption, "ccc", + 1 + ARRAY_LENGTH (initial_sigmas), + 1 + ARRAY_LENGTH (population_sizes), table_cell); + + return EXIT_SUCCESS; +} + +// evolution-strategy.c ends here -- cgit v1.3.1