aboutsummaryrefslogtreecommitdiff
path: root/src/real-genetic-algorithm.c
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 05:42:14 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 05:42:14 +0000
commit2499640c7149f34f5bed38fc93c586b78d514140 (patch)
tree22152316777718f802b8646bc8e2fb4724e74c1a /src/real-genetic-algorithm.c
downloadlab-02-2499640c7149f34f5bed38fc93c586b78d514140.tar.gz
publishHEADmaster
Diffstat (limited to 'src/real-genetic-algorithm.c')
-rw-r--r--src/real-genetic-algorithm.c541
1 files changed, 541 insertions, 0 deletions
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 @@
1// real-genetic-algorithm.c --- real genetic algorithm
2#include <stdlib.h>
3#include <stdio.h>
4#include <stdint.h>
5#include <stdbool.h>
6#include <stdarg.h>
7#include <math.h>
8#include <time.h>
9#include <float.h>
10#include <string.h>
11#include <assert.h>
12
13#define POPULATION_CAPACITY 500
14#define CHROMOSOME_SIZE 2
15#define GENERATION_MAX 2000
16#define FITNESS_TRESHOLD_EPSILON 1e-3
17#define FITNESS_OPTIMAL -1
18#define MINMAX -1
19#define X_MIN ((float) -100)
20#define X_MAX ((float) +100)
21#define Y_MIN X_MIN
22#define Y_MAX X_MAX
23#define Z_MIN ((float) -1.0)
24#define Z_MAX ((float) +0.5)
25#define X_MIN_ZOOM ((float) M_PI - 2)
26#define X_MAX_ZOOM ((float) M_PI + 2)
27#define Y_MIN_ZOOM X_MIN_ZOOM
28#define Y_MAX_ZOOM X_MAX_ZOOM
29#define PLOT_SAMPLE_COUNT 100
30// #define SEED time (NULL)
31#define SEED 1760564672
32#define MEASUREMENT_RUNS 10
33
34int population_sizes [] = { 50, 100, 200, 500 };
35float probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 };
36float probabilities_mutation [] = { 0.01, 0.05, 0.1, 0.2, 0.3 };
37
38float mutation_limits[CHROMOSOME_SIZE][2] = { { X_MIN, X_MAX },
39 { Y_MIN, Y_MAX } };
40
41#define ASSERT assert
42#define CTZL __builtin_ctzl
43#define EPSILON 1e-12
44
45#define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T)))
46#define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \
47 for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \
48 (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \
49
50typedef float gene;
51typedef gene chromosome[CHROMOSOME_SIZE];
52
53struct measurement {
54 float fitness;
55 float time;
56 int generations;
57};
58
59chromosome population [POPULATION_CAPACITY];
60chromosome population_breeding_pool [POPULATION_CAPACITY];
61float population_fitness [POPULATION_CAPACITY];
62float population_fitness_normalized [POPULATION_CAPACITY];
63float population_fitness_normalized_min;
64float population_cdf [POPULATION_CAPACITY];
65chromosome generation_bests [GENERATION_MAX];
66float generation_bests_fitness [GENERATION_MAX];
67float plot_samples [PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3];
68float plot_samples_zoom [PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3];
69struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)]
70 [ARRAY_LENGTH (probabilities_mutation )];
71
72float
73fitness_function (chromosome x)
74{
75 return -(cosf (x[0]) *
76 cosf (x[1]) *
77 expf (-((x[0] - M_PI)*(x[0] - M_PI) +
78 (x[1] - M_PI)*(x[1] - M_PI))));
79}
80
81void
82create_initial_population (int population_size)
83{
84 ASSERT (population_size > 0);
85 ASSERT (population_size <= POPULATION_CAPACITY);
86
87 for (int i = 0; i < population_size; ++i) {
88 for (int j = 0; j < CHROMOSOME_SIZE; ++j) {
89 population[i][j] = X_MIN + (X_MAX - X_MIN)*(rand () /(float) RAND_MAX);
90 }
91 }
92}
93
94bool
95measure_fitness (int population_size, int generation)
96{
97 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
98
99 population_fitness_normalized_min = DBL_MAX;
100 int population_best_i = 0;
101 float population_best_fitness = DBL_MAX;
102 for (int i = 0; i < population_size; ++i) {
103 float fitness = fitness_function (population[i]);
104 float fitness_normalized = MINMAX*fitness;
105 population_fitness [i] = fitness;
106 population_fitness_normalized [i] = fitness_normalized;
107 if (fitness_normalized < population_fitness_normalized_min)
108 population_fitness_normalized_min = fitness_normalized;
109 if (MINMAX*(fitness - population_best_fitness) > 0) {
110 population_best_i = i;
111 population_best_fitness = fitness;
112 }
113 }
114 population_fitness_normalized_min -= 1e-12;
115
116 memcpy (generation_bests[generation], population[population_best_i], sizeof (chromosome));
117 generation_bests_fitness[generation] = population_best_fitness;
118
119 return fabsf (population_best_fitness - FITNESS_OPTIMAL) < FITNESS_TRESHOLD_EPSILON;
120}
121
122void
123selection__fitness_proportionate (int population_size)
124{
125 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
126
127 float population_fitness_sum = 0;
128 for (int i = 0; i < population_size; ++i) {
129 population_fitness_sum +=
130 population_fitness_normalized[i] -= population_fitness_normalized_min;
131 }
132
133 float last = 0;
134 for (int i = 0; i < population_size; ++i) {
135 last = population_cdf[i] =
136 last + population_fitness_normalized[i]/population_fitness_sum;
137 }
138
139 for (int i = 0; i < population_size; ++i) {
140 float a = rand () /(float) RAND_MAX;
141 int j = 0;
142 // TODO(cmmm): use binary search
143 while (j < population_size) {
144 if (population_cdf[j] > a) break;
145 j += 1;
146 }
147
148 memcpy (population_breeding_pool[i], population[j],
149 sizeof (population_breeding_pool[i]));
150 }
151}
152
153void
154crossover__sbx (int population_size, float probability, float n)
155{
156 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
157 ASSERT (2 <= n && n <= 5);
158
159 for (int i = 0; i < population_size; i += 2) {
160 int i_a = i;
161 int i_b = (i + 1) % population_size;
162
163 gene *a = &population_breeding_pool[i_a][0];
164 gene *b = &population_breeding_pool[i_b][0];
165
166 if (rand () /(float) RAND_MAX > probability) {
167 memcpy (population[i_a], a, sizeof (chromosome));
168 memcpy (population[i_b], b, sizeof (chromosome));
169 } else {
170 for (int k = 0; k < CHROMOSOME_SIZE; ++k) {
171 float u = rand () /(float) RAND_MAX;
172 float beta = powf (u <= 0.5 ? 2*u : (0.5/(1 - u)), 1/(n + 1));
173
174 population[i_a][k] = ((1 - beta)*a[k] + (1 + beta)*b[k])/2;
175 population[i_b][k] = ((1 + beta)*a[k] + (1 - beta)*b[k])/2;
176 // NOTE(cmmm): uses X limits for all dimensions...
177 population[i_a][k] = fmin (X_MAX, fmax (X_MIN, population[i][k]));
178 population[i_b][k] = fmin (X_MAX, fmax (X_MIN, population[i][k]));
179 }
180 }
181 }
182}
183
184void
185mutation__uniform (int population_size, float probability)
186{
187 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
188
189 for (int i = 0; i < population_size; ++i) {
190 if (rand () /(float) RAND_MAX > probability)
191 continue;
192
193 int k = rand () % CHROMOSOME_SIZE;
194 float d = mutation_limits[k][rand () % 2] - population[i][k];
195 float r = rand () /(float) RAND_MAX;
196 population[i][k] += d*r;
197 }
198}
199
200void
201mutation__non_uniform (int population_size, float probability,
202 int generation, float generation_relation)
203{
204 ASSERT (0 < population_size && population_size <= POPULATION_CAPACITY);
205
206 for (int i = 0; i < population_size; ++i) {
207 if (rand () /(float) RAND_MAX > probability)
208 continue;
209
210 int k = rand () % CHROMOSOME_SIZE;
211 float r = rand () /(float) RAND_MAX;
212 float y = mutation_limits[k][rand () % 2] - population[i][k];
213
214 population[i][k] += y*(1 - powf (r, powf (1 - generation /(float) GENERATION_MAX,
215 generation_relation)));
216 }
217}
218
219void
220plot (const char *output, int population_size, int generation,
221 float x_min, float x_max, float y_min, float y_max,
222 float samples[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3])
223{
224 const char *ext = "tex";
225 FILE *gp = popen ("gnuplot", "w");
226 // FILE *gp = fopen ("test.gp", "w");
227 // fprintf (gp, "set term png\n");
228 fprintf (gp, "set term cairolatex png input blacktext notransparent"
229 " nocrop size 9cm,9cm noheader\n");
230 fprintf (gp, "set output '%s.%s'\n", output, ext);
231
232 fprintf (gp, "set lmargin at screen 0.30\n");
233 fprintf (gp, "set rmargin at screen 0.83\n");
234 fprintf (gp, "set bmargin at screen 0.05\n");
235 fprintf (gp, "set tmargin at screen 1.00\n");
236
237 // fprintf (gp, "set title 'Поколение №%d, \\quad Лучшая особь: \\num{%g}'\n",
238 // generation, generation_bests_fitness[generation]);
239 fprintf (gp, "set xlabel '\\(x_1\\)'\n");
240 fprintf (gp, "set ylabel '\\(x_2\\)'\n");
241 fprintf (gp, "set zlabel '\\(f(x_1, x_2)\\)' offset graph -0.1, 0 rotate by 90\n");
242 fprintf (gp, "set xrange [%f:%f]\n", x_min, x_max);
243 fprintf (gp, "set yrange [%f:%f]\n", y_min, y_max);
244 fprintf (gp, "set zrange [%f:%f]\n", Z_MIN, Z_MAX);
245 fprintf (gp, "set xtics offset graph -0.05, graph -0.10\n");
246 fprintf (gp, "set ytics offset graph +0.05, graph +0.05\n");
247 fprintf (gp, "set ztics offset graph +0.02, graph +0.05\n");
248 fprintf (gp, "unset key\n");
249
250 fprintf (gp, "set pm3d at bs interpolate 0,0 explicit\n");
251 fprintf (gp, "set ticslevel 0\n");
252
253 fprintf (gp, "set view equal xy\n");
254 fprintf (gp, "unset colorbox\n");
255 fprintf (gp, "splot ");
256 fprintf (gp, "'-' smooth acsplines with pm3d title '%s', ", "\\small{Целевая функция}");
257 if (generation > 0)
258 fprintf (gp, "'-' with points pt 3 ps 1 lc 'yellow' title '\\small{Лучшие особи}',");
259 fprintf (gp, "'-' with points pt 3 ps 1.2 lc 'magenta' title '\\small{Минимум}',");
260 fprintf (gp, "'-' with points pt 7 ps 1 lc 'green' title '\\small{Лучшая особь поколения}',");
261 fprintf (gp, "'-' with points pt 7 ps 0.5 lc 'red' title '\\small{Популяция}'\n");
262 for (int x = 0; x < PLOT_SAMPLE_COUNT; ++x) {
263 for (int y = 0; y < PLOT_SAMPLE_COUNT; ++y) {
264 fprintf (gp, "%f %f %f\n",
265 samples[x][y][0],
266 samples[x][y][1],
267 samples[x][y][2]);
268 } fprintf (gp, "\n");
269 } fprintf (gp, "e\n");
270 if (generation > 0) {
271 for (int i = 0; i < generation; ++i) {
272 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
273 fprintf (gp, "%f ", generation_bests[i][j]);
274 fprintf (gp, "%f\n", generation_bests_fitness[i]);
275 } fprintf (gp, "e\n");
276 }
277 fprintf (gp, "%f %f %f\ne\n", M_PI, M_PI, -1.);
278 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
279 fprintf (gp, "%f ", generation_bests[generation][j]);
280 fprintf (gp, "%f\ne\n", generation_bests_fitness[generation]);
281 for (int i = 0; i < population_size; ++i) {
282 for (int j = 0; j < CHROMOSOME_SIZE; ++j)
283 fprintf (gp, "%f ", population[i][j]);
284 fprintf (gp, "%f\n", population_fitness[i]);
285 } fprintf (gp, "e\n");
286
287 fprintf (gp, "set term cairolatex png input blacktext notransparent"
288 " nocrop size 7cm,7cm noheader\n");
289 fprintf (gp, "set output '%s-map.%s'\n", output, ext);
290 fprintf (gp, "set lmargin at screen 0.15\n");
291 fprintf (gp, "set rmargin at screen 0.85\n");
292 fprintf (gp, "set bmargin at screen 0.15\n");
293 fprintf (gp, "set tmargin at screen 0.90\n");
294 fprintf (gp, "set xtics offset graph 0, graph +0.02\n");
295 fprintf (gp, "set ytics nooffset\n");
296 fprintf (gp, "set xlabel offset graph 0, graph +0.05\n");
297 // fprintf (gp, "set title offset 0,-1\n");
298 fprintf (gp, "set view map\n");
299 fprintf (gp, "unset key\n");
300 fprintf (gp, "set colorbox\n");
301 fprintf (gp, "refresh\n");
302
303 fclose (gp);
304}
305
306void
307run_experiment__plot (int population_size,
308 float probability_crossover,
309 float probability_mutation)
310{
311 void
312 plot_generation (int generation)
313 {
314 static char plot_output[256];
315
316 snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u",
317 population_size, probability_crossover,
318 probability_mutation, generation);
319 plot (plot_output, population_size, generation,
320 X_MIN, X_MAX, Y_MIN, Y_MAX, plot_samples);
321
322 snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u-zoom",
323 population_size, probability_crossover,
324 probability_mutation, generation);
325 plot (plot_output, population_size, generation,
326 X_MIN_ZOOM, X_MAX_ZOOM, Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom);
327 }
328
329 create_initial_population (population_size);
330 int generation;
331 for (generation = 0; generation < GENERATION_MAX; ++generation) {
332 if (measure_fitness (population_size, generation)) break;
333
334 printf ("generation: %d, fitness: %g, ",
335 generation, generation_bests_fitness[generation]);
336 printf ("chromosome:");
337 for (int i = 0; i < CHROMOSOME_SIZE; ++i) {
338 printf (" %f", generation_bests[generation][i]);
339 } printf ("\n");
340 if (generation % 10 == 0 || generation < 10)
341 plot_generation (generation);
342
343 selection__fitness_proportionate (population_size);
344 crossover__sbx (population_size, probability_crossover, 2);
345 mutation__non_uniform (population_size, probability_mutation, generation, 1);
346 }
347 if (generation == GENERATION_MAX)
348 measure_fitness (population_size, generation);
349 printf ("generation: %lu, fitness: %lf, ",
350 generation, generation_bests_fitness[generation]);
351 printf ("chromosome:");
352 for (int i = 0; i < CHROMOSOME_SIZE; ++i) {
353 printf (" %f", generation_bests[generation][i]);
354 } printf ("\n");
355 plot_generation (generation);
356}
357
358struct measurement
359run_experiment__measure (int population_size,
360 float probability_crossover,
361 float probability_mutation)
362{
363 float total_fitness = 0;
364 float total_time = 0;
365 int total_generations = 0;
366 for (int run = 0; run < MEASUREMENT_RUNS; ++run) {
367 clock_t begin = clock ();
368 create_initial_population (population_size);
369 int generation;
370 for (generation = 0; generation < GENERATION_MAX; ++generation) {
371 if (measure_fitness (population_size, generation)) break;
372 selection__fitness_proportionate (population_size);
373 crossover__sbx (population_size, probability_crossover, 2);
374 mutation__uniform (population_size, probability_mutation);
375 }
376 float time = (clock () - begin) /(float) CLOCKS_PER_SEC;
377 total_time += time;
378 total_generations += generation;
379 total_fitness += generation_bests_fitness[generation - (generation == GENERATION_MAX)];
380 }
381
382 return (struct measurement) {
383 .fitness = total_fitness/MEASUREMENT_RUNS,
384 .time = total_time/MEASUREMENT_RUNS,
385 .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS,
386 };
387}
388
389void
390sample_fitness_function (float x_min, float x_max,
391 float y_min, float y_max,
392 float samples[PLOT_SAMPLE_COUNT][PLOT_SAMPLE_COUNT][3])
393{
394 float x = x_min;
395 float dx = (x_max - x_min)/(PLOT_SAMPLE_COUNT - 1);
396 for (int i = 0; i < PLOT_SAMPLE_COUNT; ++i) {
397 float y = y_min;
398 float dy = (y_max - y_min)/(PLOT_SAMPLE_COUNT - 1);
399 for (int j = 0; j < PLOT_SAMPLE_COUNT; ++j) {
400 samples[i][j][0] = x;
401 samples[i][j][1] = y;
402 samples[i][j][2] = fitness_function ((chromosome) { x, y });
403 y += dy;
404 } x += dx;
405 }
406}
407
408typedef int (*print_function)(void *user, const char *template, ...);
409typedef int (*cell_function)(int x, int y, print_function, void *);
410
411int
412print__measure (void *user, const char *template, ...)
413{
414 va_list ap;
415 va_start (ap, template);
416 int len = vsnprintf (NULL, 0, template, ap);
417 va_end (ap);
418 return len;
419}
420
421int
422print__stream (void *stream, const char *template, ...)
423{
424 va_list ap;
425 va_start (ap, template);
426 int len = vfprintf (stream, template, ap);
427 va_end (ap);
428 return len;
429}
430
431void
432print_org_table (const char *filename, const char *name, const char *caption,
433 const char *align, int rows, int cols, cell_function cell)
434{
435 int cell_widths[rows][cols];
436 int column_widths[cols];
437 memset (column_widths, 0, sizeof (column_widths));
438 for (int y = 0; y < rows; ++y) {
439 for (int x = 0; x < cols; ++x) {
440 cell_widths[y][x] = cell (x, y, print__measure, NULL);
441 if (cell_widths[y][x] > column_widths[x])
442 column_widths[x] = cell_widths[y][x];;
443 }
444 }
445
446 FILE *stream = fopen (filename, "w");
447 if (name ) fprintf (stream, "#+name: %s\n", name);
448 if (caption) fprintf (stream, "#+caption: %s\n", caption);
449 if (align ) fprintf (stream, "#+attr_latex: :align %s\n", align);
450 for (int y = 0; y < rows; ++y) {
451 fprintf (stream, "|");
452 for (int x = 0; x < cols; ++x) {
453 fprintf (stream, " ");
454 if (x == 0) {
455 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
456 fprintf (stream, " ");
457 }
458 cell (x, y, print__stream, stream);
459 if (x > 0) {
460 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
461 fprintf (stream, " ");
462 }
463 fprintf (stream, " |");
464 } fprintf (stream, "\n");
465 if (y == 0) {
466 fprintf (stream, "|");
467 for (int x = 0; x < cols; ++x) {
468 for (int i = 0; i < column_widths[x] + 2; ++i)
469 fprintf (stream, "-");
470 fprintf (stream, "|");
471 } fprintf (stream, "\n");
472 }
473 }
474
475 fclose (stream);
476}
477
478int
479main (int argc, char *argv[])
480{
481 printf ("SEED: %u\n", SEED);
482 srand (SEED);
483
484 // sample_fitness_function (X_MIN, X_MAX,
485 // Y_MIN, Y_MAX, plot_samples);
486 // sample_fitness_function (X_MIN_ZOOM, X_MAX_ZOOM,
487 // Y_MIN_ZOOM, Y_MAX_ZOOM, plot_samples_zoom);
488 // run_experiment__plot (200, .8, .4);
489 // return 0;
490
491 struct measurement *best_measurement = &measurements[0][0];
492 FOR_EACH_ELEMENT (population_size, population_sizes) {
493 struct measurement *measurement = &measurements[0][0];
494 FOR_EACH_ELEMENT (probability_crossover, probabilities_crossover) {
495 FOR_EACH_ELEMENT (probability_mutation, probabilities_mutation) {
496 printf ("experiment: %4d %.3f %.3f", *population_size,
497 *probability_crossover, *probability_mutation);
498 fflush (stdout);
499 *measurement = run_experiment__measure (*population_size,
500 *probability_crossover,
501 *probability_mutation);
502 printf (" @ %6.2f ms\n", measurement->time*1e+3);
503 if (measurement->time < best_measurement->time)
504 best_measurement = measurement;
505 measurement += 1;
506 }
507 }
508
509 char *table_filename, *table_name, *table_caption;
510 asprintf (&table_filename, "res/results-%03lu.org", *population_size);
511 asprintf (&table_name, "results-%lu", *population_size);
512 asprintf (&table_caption, "Результаты для \\(N = %lu\\)",
513 *population_size);
514 int table_cell (int x, int y, print_function print, void *user)
515 {
516 int m = x - 1;
517 int c = y - 1;
518 if (x == 0 && y == 0) return print (user, "\\(P_c \\;\\backslash\\; P_m\\)");
519 if ( y == 0) return print (user, "%.3g", probabilities_mutation [m]);
520 if (x == 0 ) return print (user, "%.1g", probabilities_crossover[c]);
521
522 int len = 0;
523 bool is_best = &measurements[c][m] == best_measurement;
524 if (is_best) print (user, "*");
525 len += print (user, "\\makecell{%.2f (%lu) \\\\ %f}",
526 measurements[c][m].time*1e+3,
527 measurements[c][m].generations,
528 measurements[c][m].fitness);
529 if (is_best) print (user, "*");
530
531 return len;
532 }
533 print_org_table (table_filename, table_name, table_caption, "cccccc",
534 1 + ARRAY_LENGTH (probabilities_crossover),
535 1 + ARRAY_LENGTH (probabilities_mutation), table_cell);
536 }
537
538 return EXIT_SUCCESS;
539}
540
541// real-genetic-algorithm.c ends here