From e932f4212d50dfbbf7e7601f1b217793f2a31a87 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 00:45:29 +0300 Subject: publish --- src/simple-genetic-algorithm.c | 480 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 480 insertions(+) create mode 100644 src/simple-genetic-algorithm.c (limited to 'src') diff --git a/src/simple-genetic-algorithm.c b/src/simple-genetic-algorithm.c new file mode 100644 index 0000000..728fc78 --- /dev/null +++ b/src/simple-genetic-algorithm.c @@ -0,0 +1,480 @@ +// simple-genetic-algorithm.c --- simple genetic algorithm +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define POPULATION_CAPACITY 100 +#define CHROMOSOME_SIZE 16 +#define GENERATION_MAX 200 +#define FITNESS_TRESHOLD_AVERAGE -0.411 +#define FITNESS_TRESHOLD_VARIANCE -1 +#define FITNESS_TRESHOLD_BEST FITNESS_TRESHOLD_AVERAGE +#define DIGITS_AFTER_DECIMAL 3 +#define MINMAX -1 +#define X_MIN ((double) -10) +#define X_MAX ((double) +10) +#define Y_MIN ((double) -0.5) +#define Y_MAX ((double) +2.0) +#define PLOT_SAMPLE_COUNT 400 +// #define SEED time (NULL) +#define SEED 1760052039 +#define MEASUREMENT_RUNS 100 + +size_t population_sizes [] = { 10, 25, 50, 100 }; +double probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 }; +double probabilities_mutation [] = { 0.001, 0.01, 0.05, 0.1, 0.2 }; + +#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)) \ + +#if CHROMOSOME_SIZE < 2 +#error "CHROMOSOME_SIZE smaller than 2" +#elif CHROMOSOME_SIZE <= 8 + typedef uint8_t chromosome; +#elif CHROMOSOME_SIZE <= 16 + typedef uint16_t chromosome; +#elif CHROMOSOME_SIZE <= 32 + typedef uint32_t chromosome; +#else +#error "CHROMOSOME_SIZE larger than 32" +#endif + +#define CHROMOSOME_MAX ((chromosome) -1 >> (8*sizeof (chromosome) - CHROMOSOME_SIZE)) + +struct sample { + double x, y; +}; +struct measurement { + double time; + size_t generations; +}; + +chromosome population [POPULATION_CAPACITY]; +chromosome population_breeding_pool [POPULATION_CAPACITY]; +double population_fitness [POPULATION_CAPACITY]; +double population_fitness_normalized [POPULATION_CAPACITY]; +double population_fitness_normalized_min; +double population_cdf [POPULATION_CAPACITY]; +size_t population_best_i; +double population_best_fitness; +chromosome generation_bests [GENERATION_MAX]; +double generation_bests_fitness [GENERATION_MAX]; +struct sample plot_samples [PLOT_SAMPLE_COUNT]; +struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)] + [ARRAY_LENGTH (probabilities_mutation )]; + +double +decode (chromosome chromosome) +{ + return X_MIN + chromosome*(X_MAX - X_MIN)/CHROMOSOME_MAX; +} + +double +fitness_function (double x) +{ + return cos (x - 0.5)/fabs (x); +} + +uint8_t +bits_for_precision (int digits_after_decimal) +{ + ASSERT (digits_after_decimal < 18); + + uint64_t interval_count_min = ceil ((X_MAX - X_MIN)*pow (10, digits_after_decimal)); + uint64_t interval_count = 1; + while (interval_count < interval_count_min) + interval_count <<= 1; + return CTZL (interval_count); +} + +void +create_initial_population (size_t population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (size_t i = 0; i < population_size; ++i) { + population[i] = rand () % (1 << CHROMOSOME_SIZE); + } +} + +bool +measure_fitness (size_t population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + population_fitness_normalized_min = DBL_MAX; + // double fitness_average = 0; + // double fitness_variance = 0; + population_best_i = 0; + population_best_fitness = DBL_MAX; + for (size_t i = 0; i < population_size; ++i) { + double fitness = fitness_function (decode (population[i])); + double 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; + // fitness_average += fitness; + // fitness_variance += fitness*fitness; + if (MINMAX*(fitness - population_best_fitness) > 0) { + population_best_i = i; + population_best_fitness = fitness; + } + } + population_fitness_normalized_min -= 1e-12; + // fitness_average /= population_size; + // fitness_variance = fitness_variance/population_size - + // fitness_average*fitness_average; + // printf ("%lg\n", fitness_average); + // if (fitness_average - FITNESS_TRESHOLD_AVERAGE < EPSILON) return true; + // if (fitness_variance - FITNESS_TRESHOLD_VARIANCE < EPSILON) return true; + // printf ("%lg\n", population_best_fitness); + if (MINMAX*(population_best_fitness - FITNESS_TRESHOLD_BEST) > 0) return true; + return false; +} + +void +fitness_proportionate_selection (size_t population_size) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + double population_fitness_sum = 0; + for (size_t i = 0; i < population_size; ++i) { + population_fitness_sum += + population_fitness_normalized[i] -= population_fitness_normalized_min; + } + + double last = 0; + for (size_t i = 0; i < population_size; ++i) { + last = population_cdf[i] = + last + population_fitness_normalized[i]/population_fitness_sum; + } + + for (size_t i = 0; i < population_size; ++i) { + double a = rand () /(double) RAND_MAX; + size_t j = 0; + // TODO(cmmm): use binary search + while (j < population_size) { + if (population_cdf[j] > a) break; + j += 1; + } + + population_breeding_pool[i] = population[j]; + } +} + +void +crossover (size_t population_size, double probability) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (size_t i = 0; i < population_size; i += 2) { + size_t i_a = i; + size_t i_b = (i + 1) % population_size; + + chromosome a = population_breeding_pool[i_a]; + chromosome b = population_breeding_pool[i_b]; + + if (rand () /(double) RAND_MAX > probability) { + population[i_a] = a; + population[i_b] = b; + } else { + size_t k = rand () % (CHROMOSOME_SIZE - 1) + 1; + chromosome mask_left = (1 << k) - 1; + chromosome mask_right = -1 << k; + population[i_a] = a & mask_left | b & mask_right; + population[i_b] = b & mask_left | a & mask_right; + } + } +} + +void +mutation (size_t population_size, double probability) +{ + ASSERT (population_size > 0); + ASSERT (population_size <= POPULATION_CAPACITY); + + for (size_t i = 0; i < population_size; ++i) { + if (rand () /(double) RAND_MAX > probability) + continue; + + size_t k = rand () % CHROMOSOME_SIZE; + population[i] ^= 1 << k; + } +} + +void +plot (const char *output, size_t population_size, size_t generation) +{ + // FILE *gp = popen ("gnuplot", "w"); + FILE *gp = fopen ("test.gp", "w"); + // fprintf (gp, "set term png\n"); + fprintf (gp, "set term cairolatex pdf input blacktext notransparent" + " nocrop size 15cm,10cm noheader\n"); + fprintf (gp, "set output '%s'\n", output); + + fprintf (gp, "set size ratio 0.66\n"); + fprintf (gp, "set lmargin at screen 0.1\n"); + fprintf (gp, "set rmargin at screen 0.9\n"); + fprintf (gp, "set bmargin at screen 0.1\n"); + fprintf (gp, "set tmargin at screen 0.9\n"); + + fprintf (gp, "set title 'Поколение №%lu, \\quad Лучшая особь: %lf'\n", + generation, population_best_fitness); + fprintf (gp, "set xlabel '\\(x\\)'\n"); + fprintf (gp, "set ylabel '\\(f(x)\\)'\n"); + fprintf (gp, "set xrange [%lf:%lf]\n", X_MIN, X_MAX); + fprintf (gp, "set yrange [%lf:%lf]\n", Y_MIN, Y_MAX); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines title '%s',", "\\small{Целевая функция}"); + if (generation > 0) + fprintf (gp, "'-' with points pt 7 ps 1 lc 'yellow' 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 (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) { + fprintf (gp, "%lf %lf\n", plot_samples[i].x, plot_samples[i].y); + } fprintf (gp, "e\n"); + if (generation > 0) { + for (size_t i = 0; i < generation; ++i) { + double x = decode (generation_bests[i]); + fprintf (gp, "%lf %lf\n", x, generation_bests_fitness[i]); + } fprintf (gp, "e\n"); + } + fprintf (gp, "%lf %lf\ne\n", + decode (population[population_best_i]), + population_best_fitness); + for (size_t i = 0; i < population_size; ++i) { + double x = decode (population[i]); + fprintf (gp, "%lf %lf\n", x, population_fitness[i]); + } fprintf (gp, "e\n"); + fclose (gp); +} + +void +run_experiment__plot (size_t population_size, + double probability_crossover, + double probability_mutation) +{ + void + plot_generation (size_t generation) + { + static char plot_output[256]; + + snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u.tex", + population_size, probability_crossover, + probability_mutation, generation); + + plot (plot_output, population_size, generation); + } + + create_initial_population (population_size); + measure_fitness (population_size); + size_t generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + if (measure_fitness (population_size)) break; + + generation_bests [generation] = population[population_best_i]; + generation_bests_fitness [generation] = population_best_fitness; + printf ("fitness: %lf\n", population_best_fitness); + plot_generation (generation); + + fitness_proportionate_selection (population_size); + crossover (population_size, probability_crossover); + mutation (population_size, probability_mutation); + } + if (generation == GENERATION_MAX) + measure_fitness (population_size); + printf ("fitness: %lf\n", population_best_fitness); + printf ("chromosome: %0*b\n", CHROMOSOME_SIZE, population[population_best_i]); + plot_generation (generation); +} + +struct measurement +run_experiment__measure (size_t population_size, + double probability_crossover, + double probability_mutation) +{ + double total_time = 0; + size_t total_generations = 0; + for (int run = 0; run < MEASUREMENT_RUNS; ++run) { + clock_t begin = clock (); + create_initial_population (population_size); + size_t generation; + for (generation = 0; generation < GENERATION_MAX; ++generation) { + if (measure_fitness (population_size)) break; + fitness_proportionate_selection (population_size); + crossover (population_size, probability_crossover); + mutation (population_size, probability_mutation); + } + double time = (clock () - begin) /(double) CLOCKS_PER_SEC; + total_time += time; + total_generations += generation; + } + + return (struct measurement) { + .time = total_time/MEASUREMENT_RUNS, + .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS, + }; +} + +void +sample_fitness_function () +{ + double x = X_MIN; + double dx = (X_MAX - X_MIN)/PLOT_SAMPLE_COUNT; + for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) { + plot_samples[i].x = x; + plot_samples[i].y = fitness_function (x); + 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, + 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"); + fprintf (stream, "#+name: %s\n", name); + fprintf (stream, "#+caption: %s\n", caption); + 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[]) +{ + ASSERT (CHROMOSOME_SIZE >= bits_for_precision (DIGITS_AFTER_DECIMAL)); + + printf ("SEED: %u\n", SEED); + srand (SEED); + sample_fitness_function (); + + run_experiment__plot (25, .5, .1); + 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) { + *measurement = run_experiment__measure (*population_size, + *probability_crossover, + *probability_mutation); + 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, "%.3lg", probabilities_mutation [m]); + if (x == 0 ) return print (user, "%.1lg", probabilities_crossover[c]); + + int len = 0; + bool max_generation_reached = + measurements[c][m].generations == GENERATION_MAX; + bool is_best = &measurements[c][m] == best_measurement; + if (max_generation_reached) len += print (user, "\\st{"); + if (is_best) print (user, "*"); + len += print (user, "%.2lf (%lu)", + measurements[c][m].time*1000000, + measurements[c][m].generations); + if (is_best) print (user, "*"); + if (max_generation_reached) len += print (user, "}"); + + return len; + } + print_org_table (table_filename, table_name, table_caption, + 1 + ARRAY_LENGTH (probabilities_crossover), + 1 + ARRAY_LENGTH (probabilities_mutation), table_cell); + } + + return EXIT_SUCCESS; +} + +// simple-genetic-algorithm.c ends here -- cgit v1.3.1