aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-09 21:45:29 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 04:53:46 +0000
commite932f4212d50dfbbf7e7601f1b217793f2a31a87 (patch)
tree5ea72f1a5c5a02e6d2cdaf55084b599086fef1ec /src
downloadlab-01-e932f4212d50dfbbf7e7601f1b217793f2a31a87.tar.gz
publishHEADmaster
Diffstat (limited to 'src')
-rw-r--r--src/simple-genetic-algorithm.c480
1 files changed, 480 insertions, 0 deletions
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 @@
1// simple-genetic-algorithm.c --- simple 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 100
14#define CHROMOSOME_SIZE 16
15#define GENERATION_MAX 200
16#define FITNESS_TRESHOLD_AVERAGE -0.411
17#define FITNESS_TRESHOLD_VARIANCE -1
18#define FITNESS_TRESHOLD_BEST FITNESS_TRESHOLD_AVERAGE
19#define DIGITS_AFTER_DECIMAL 3
20#define MINMAX -1
21#define X_MIN ((double) -10)
22#define X_MAX ((double) +10)
23#define Y_MIN ((double) -0.5)
24#define Y_MAX ((double) +2.0)
25#define PLOT_SAMPLE_COUNT 400
26// #define SEED time (NULL)
27#define SEED 1760052039
28#define MEASUREMENT_RUNS 100
29
30size_t population_sizes [] = { 10, 25, 50, 100 };
31double probabilities_crossover [] = { 0.3, 0.4, 0.5, 0.6, 0.7, 0.8 };
32double probabilities_mutation [] = { 0.001, 0.01, 0.05, 0.1, 0.2 };
33
34#define ASSERT assert
35#define CTZL __builtin_ctzl
36#define EPSILON 1e-12
37
38#define ARRAY_LENGTH(T) (sizeof (T)/sizeof (*(T)))
39#define FOR_EACH_ELEMENT(ELEMENT, ARRAY) \
40 for (typeof (*(ARRAY)) *(ELEMENT) = (ARRAY); \
41 (ELEMENT) < (ARRAY) + ARRAY_LENGTH (ARRAY); ++(ELEMENT)) \
42
43#if CHROMOSOME_SIZE < 2
44#error "CHROMOSOME_SIZE smaller than 2"
45#elif CHROMOSOME_SIZE <= 8
46 typedef uint8_t chromosome;
47#elif CHROMOSOME_SIZE <= 16
48 typedef uint16_t chromosome;
49#elif CHROMOSOME_SIZE <= 32
50 typedef uint32_t chromosome;
51#else
52#error "CHROMOSOME_SIZE larger than 32"
53#endif
54
55#define CHROMOSOME_MAX ((chromosome) -1 >> (8*sizeof (chromosome) - CHROMOSOME_SIZE))
56
57struct sample {
58 double x, y;
59};
60struct measurement {
61 double time;
62 size_t generations;
63};
64
65chromosome population [POPULATION_CAPACITY];
66chromosome population_breeding_pool [POPULATION_CAPACITY];
67double population_fitness [POPULATION_CAPACITY];
68double population_fitness_normalized [POPULATION_CAPACITY];
69double population_fitness_normalized_min;
70double population_cdf [POPULATION_CAPACITY];
71size_t population_best_i;
72double population_best_fitness;
73chromosome generation_bests [GENERATION_MAX];
74double generation_bests_fitness [GENERATION_MAX];
75struct sample plot_samples [PLOT_SAMPLE_COUNT];
76struct measurement measurements [ARRAY_LENGTH (probabilities_crossover)]
77 [ARRAY_LENGTH (probabilities_mutation )];
78
79double
80decode (chromosome chromosome)
81{
82 return X_MIN + chromosome*(X_MAX - X_MIN)/CHROMOSOME_MAX;
83}
84
85double
86fitness_function (double x)
87{
88 return cos (x - 0.5)/fabs (x);
89}
90
91uint8_t
92bits_for_precision (int digits_after_decimal)
93{
94 ASSERT (digits_after_decimal < 18);
95
96 uint64_t interval_count_min = ceil ((X_MAX - X_MIN)*pow (10, digits_after_decimal));
97 uint64_t interval_count = 1;
98 while (interval_count < interval_count_min)
99 interval_count <<= 1;
100 return CTZL (interval_count);
101}
102
103void
104create_initial_population (size_t population_size)
105{
106 ASSERT (population_size > 0);
107 ASSERT (population_size <= POPULATION_CAPACITY);
108
109 for (size_t i = 0; i < population_size; ++i) {
110 population[i] = rand () % (1 << CHROMOSOME_SIZE);
111 }
112}
113
114bool
115measure_fitness (size_t population_size)
116{
117 ASSERT (population_size > 0);
118 ASSERT (population_size <= POPULATION_CAPACITY);
119
120 population_fitness_normalized_min = DBL_MAX;
121 // double fitness_average = 0;
122 // double fitness_variance = 0;
123 population_best_i = 0;
124 population_best_fitness = DBL_MAX;
125 for (size_t i = 0; i < population_size; ++i) {
126 double fitness = fitness_function (decode (population[i]));
127 double fitness_normalized = MINMAX*fitness;
128 population_fitness [i] = fitness;
129 population_fitness_normalized [i] = fitness_normalized;
130 if (fitness_normalized < population_fitness_normalized_min)
131 population_fitness_normalized_min = fitness_normalized;
132 // fitness_average += fitness;
133 // fitness_variance += fitness*fitness;
134 if (MINMAX*(fitness - population_best_fitness) > 0) {
135 population_best_i = i;
136 population_best_fitness = fitness;
137 }
138 }
139 population_fitness_normalized_min -= 1e-12;
140 // fitness_average /= population_size;
141 // fitness_variance = fitness_variance/population_size -
142 // fitness_average*fitness_average;
143 // printf ("%lg\n", fitness_average);
144 // if (fitness_average - FITNESS_TRESHOLD_AVERAGE < EPSILON) return true;
145 // if (fitness_variance - FITNESS_TRESHOLD_VARIANCE < EPSILON) return true;
146 // printf ("%lg\n", population_best_fitness);
147 if (MINMAX*(population_best_fitness - FITNESS_TRESHOLD_BEST) > 0) return true;
148 return false;
149}
150
151void
152fitness_proportionate_selection (size_t population_size)
153{
154 ASSERT (population_size > 0);
155 ASSERT (population_size <= POPULATION_CAPACITY);
156
157 double population_fitness_sum = 0;
158 for (size_t i = 0; i < population_size; ++i) {
159 population_fitness_sum +=
160 population_fitness_normalized[i] -= population_fitness_normalized_min;
161 }
162
163 double last = 0;
164 for (size_t i = 0; i < population_size; ++i) {
165 last = population_cdf[i] =
166 last + population_fitness_normalized[i]/population_fitness_sum;
167 }
168
169 for (size_t i = 0; i < population_size; ++i) {
170 double a = rand () /(double) RAND_MAX;
171 size_t j = 0;
172 // TODO(cmmm): use binary search
173 while (j < population_size) {
174 if (population_cdf[j] > a) break;
175 j += 1;
176 }
177
178 population_breeding_pool[i] = population[j];
179 }
180}
181
182void
183crossover (size_t population_size, double probability)
184{
185 ASSERT (population_size > 0);
186 ASSERT (population_size <= POPULATION_CAPACITY);
187
188 for (size_t i = 0; i < population_size; i += 2) {
189 size_t i_a = i;
190 size_t i_b = (i + 1) % population_size;
191
192 chromosome a = population_breeding_pool[i_a];
193 chromosome b = population_breeding_pool[i_b];
194
195 if (rand () /(double) RAND_MAX > probability) {
196 population[i_a] = a;
197 population[i_b] = b;
198 } else {
199 size_t k = rand () % (CHROMOSOME_SIZE - 1) + 1;
200 chromosome mask_left = (1 << k) - 1;
201 chromosome mask_right = -1 << k;
202 population[i_a] = a & mask_left | b & mask_right;
203 population[i_b] = b & mask_left | a & mask_right;
204 }
205 }
206}
207
208void
209mutation (size_t population_size, double probability)
210{
211 ASSERT (population_size > 0);
212 ASSERT (population_size <= POPULATION_CAPACITY);
213
214 for (size_t i = 0; i < population_size; ++i) {
215 if (rand () /(double) RAND_MAX > probability)
216 continue;
217
218 size_t k = rand () % CHROMOSOME_SIZE;
219 population[i] ^= 1 << k;
220 }
221}
222
223void
224plot (const char *output, size_t population_size, size_t generation)
225{
226 // FILE *gp = popen ("gnuplot", "w");
227 FILE *gp = fopen ("test.gp", "w");
228 // fprintf (gp, "set term png\n");
229 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
230 " nocrop size 15cm,10cm noheader\n");
231 fprintf (gp, "set output '%s'\n", output);
232
233 fprintf (gp, "set size ratio 0.66\n");
234 fprintf (gp, "set lmargin at screen 0.1\n");
235 fprintf (gp, "set rmargin at screen 0.9\n");
236 fprintf (gp, "set bmargin at screen 0.1\n");
237 fprintf (gp, "set tmargin at screen 0.9\n");
238
239 fprintf (gp, "set title 'Поколение №%lu, \\quad Лучшая особь: %lf'\n",
240 generation, population_best_fitness);
241 fprintf (gp, "set xlabel '\\(x\\)'\n");
242 fprintf (gp, "set ylabel '\\(f(x)\\)'\n");
243 fprintf (gp, "set xrange [%lf:%lf]\n", X_MIN, X_MAX);
244 fprintf (gp, "set yrange [%lf:%lf]\n", Y_MIN, Y_MAX);
245
246 fprintf (gp, "plot ");
247 fprintf (gp, "'-' with lines title '%s',", "\\small{Целевая функция}");
248 if (generation > 0)
249 fprintf (gp, "'-' with points pt 7 ps 1 lc 'yellow' title '\\small{Лучшие особи}',");
250 fprintf (gp, "'-' with points pt 7 ps 1 lc 'green' title '\\small{Лучшая особь поколения}',");
251 fprintf (gp, "'-' with points pt 7 ps 0.5 lc 'red' title '\\small{Популяция}'\n");
252 for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) {
253 fprintf (gp, "%lf %lf\n", plot_samples[i].x, plot_samples[i].y);
254 } fprintf (gp, "e\n");
255 if (generation > 0) {
256 for (size_t i = 0; i < generation; ++i) {
257 double x = decode (generation_bests[i]);
258 fprintf (gp, "%lf %lf\n", x, generation_bests_fitness[i]);
259 } fprintf (gp, "e\n");
260 }
261 fprintf (gp, "%lf %lf\ne\n",
262 decode (population[population_best_i]),
263 population_best_fitness);
264 for (size_t i = 0; i < population_size; ++i) {
265 double x = decode (population[i]);
266 fprintf (gp, "%lf %lf\n", x, population_fitness[i]);
267 } fprintf (gp, "e\n");
268 fclose (gp);
269}
270
271void
272run_experiment__plot (size_t population_size,
273 double probability_crossover,
274 double probability_mutation)
275{
276 void
277 plot_generation (size_t generation)
278 {
279 static char plot_output[256];
280
281 snprintf (plot_output, sizeof (plot_output), "res/p%llu-c%4.2lf-m%4.2lf-g%03u.tex",
282 population_size, probability_crossover,
283 probability_mutation, generation);
284
285 plot (plot_output, population_size, generation);
286 }
287
288 create_initial_population (population_size);
289 measure_fitness (population_size);
290 size_t generation;
291 for (generation = 0; generation < GENERATION_MAX; ++generation) {
292 if (measure_fitness (population_size)) break;
293
294 generation_bests [generation] = population[population_best_i];
295 generation_bests_fitness [generation] = population_best_fitness;
296 printf ("fitness: %lf\n", population_best_fitness);
297 plot_generation (generation);
298
299 fitness_proportionate_selection (population_size);
300 crossover (population_size, probability_crossover);
301 mutation (population_size, probability_mutation);
302 }
303 if (generation == GENERATION_MAX)
304 measure_fitness (population_size);
305 printf ("fitness: %lf\n", population_best_fitness);
306 printf ("chromosome: %0*b\n", CHROMOSOME_SIZE, population[population_best_i]);
307 plot_generation (generation);
308}
309
310struct measurement
311run_experiment__measure (size_t population_size,
312 double probability_crossover,
313 double probability_mutation)
314{
315 double total_time = 0;
316 size_t total_generations = 0;
317 for (int run = 0; run < MEASUREMENT_RUNS; ++run) {
318 clock_t begin = clock ();
319 create_initial_population (population_size);
320 size_t generation;
321 for (generation = 0; generation < GENERATION_MAX; ++generation) {
322 if (measure_fitness (population_size)) break;
323 fitness_proportionate_selection (population_size);
324 crossover (population_size, probability_crossover);
325 mutation (population_size, probability_mutation);
326 }
327 double time = (clock () - begin) /(double) CLOCKS_PER_SEC;
328 total_time += time;
329 total_generations += generation;
330 }
331
332 return (struct measurement) {
333 .time = total_time/MEASUREMENT_RUNS,
334 .generations = (total_generations + MEASUREMENT_RUNS/2)/MEASUREMENT_RUNS,
335 };
336}
337
338void
339sample_fitness_function ()
340{
341 double x = X_MIN;
342 double dx = (X_MAX - X_MIN)/PLOT_SAMPLE_COUNT;
343 for (size_t i = 0; i < PLOT_SAMPLE_COUNT; ++i) {
344 plot_samples[i].x = x;
345 plot_samples[i].y = fitness_function (x);
346 x += dx;
347 }
348}
349
350typedef int (*print_function)(void *user, const char *template, ...);
351typedef int (*cell_function)(int x, int y, print_function, void *);
352
353int
354print__measure (void *user, const char *template, ...)
355{
356 va_list ap;
357 va_start (ap, template);
358 int len = vsnprintf (NULL, 0, template, ap);
359 va_end (ap);
360 return len;
361}
362
363int
364print__stream (void *stream, const char *template, ...)
365{
366 va_list ap;
367 va_start (ap, template);
368 int len = vfprintf (stream, template, ap);
369 va_end (ap);
370 return len;
371}
372
373void
374print_org_table (const char *filename, const char *name, const char *caption,
375 int rows, int cols, cell_function cell)
376{
377 int cell_widths[rows][cols];
378 int column_widths[cols];
379 memset (column_widths, 0, sizeof (column_widths));
380 for (int y = 0; y < rows; ++y) {
381 for (int x = 0; x < cols; ++x) {
382 cell_widths[y][x] = cell (x, y, print__measure, NULL);
383 if (cell_widths[y][x] > column_widths[x])
384 column_widths[x] = cell_widths[y][x];;
385 }
386 }
387
388 FILE *stream = fopen (filename, "w");
389 fprintf (stream, "#+name: %s\n", name);
390 fprintf (stream, "#+caption: %s\n", caption);
391 for (int y = 0; y < rows; ++y) {
392 fprintf (stream, "|");
393 for (int x = 0; x < cols; ++x) {
394 fprintf (stream, " ");
395 if (x == 0) {
396 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
397 fprintf (stream, " ");
398 }
399 cell (x, y, print__stream, stream);
400 if (x > 0) {
401 for (int i = 0; i < column_widths[x] - cell_widths[y][x]; ++i)
402 fprintf (stream, " ");
403 }
404 fprintf (stream, " |");
405 } fprintf (stream, "\n");
406 if (y == 0) {
407 fprintf (stream, "|");
408 for (int x = 0; x < cols; ++x) {
409 for (int i = 0; i < column_widths[x] + 2; ++i)
410 fprintf (stream, "-");
411 fprintf (stream, "|");
412 } fprintf (stream, "\n");
413 }
414 }
415
416 fclose (stream);
417}
418
419int
420main (int argc, char *argv[])
421{
422 ASSERT (CHROMOSOME_SIZE >= bits_for_precision (DIGITS_AFTER_DECIMAL));
423
424 printf ("SEED: %u\n", SEED);
425 srand (SEED);
426 sample_fitness_function ();
427
428 run_experiment__plot (25, .5, .1);
429 return 0;
430
431 struct measurement *best_measurement = &measurements[0][0];
432 FOR_EACH_ELEMENT (population_size, population_sizes) {
433 struct measurement *measurement = &measurements[0][0];
434 FOR_EACH_ELEMENT (probability_crossover, probabilities_crossover) {
435 FOR_EACH_ELEMENT (probability_mutation, probabilities_mutation) {
436 *measurement = run_experiment__measure (*population_size,
437 *probability_crossover,
438 *probability_mutation);
439 if (measurement->time < best_measurement->time)
440 best_measurement = measurement;
441 measurement += 1;
442 }
443 }
444
445 char *table_filename, *table_name, *table_caption;
446 asprintf (&table_filename, "res/results-%03lu.org", *population_size);
447 asprintf (&table_name, "results-%lu", *population_size);
448 asprintf (&table_caption, "Результаты для \\(N = %lu\\)",
449 *population_size);
450 int table_cell (int x, int y, print_function print, void *user)
451 {
452 int m = x - 1;
453 int c = y - 1;
454 if (x == 0 && y == 0) return print (user, "\\(P_c \\;\\backslash\\; P_m\\)");
455 if ( y == 0) return print (user, "%.3lg", probabilities_mutation [m]);
456 if (x == 0 ) return print (user, "%.1lg", probabilities_crossover[c]);
457
458 int len = 0;
459 bool max_generation_reached =
460 measurements[c][m].generations == GENERATION_MAX;
461 bool is_best = &measurements[c][m] == best_measurement;
462 if (max_generation_reached) len += print (user, "\\st{");
463 if (is_best) print (user, "*");
464 len += print (user, "%.2lf (%lu)",
465 measurements[c][m].time*1000000,
466 measurements[c][m].generations);
467 if (is_best) print (user, "*");
468 if (max_generation_reached) len += print (user, "}");
469
470 return len;
471 }
472 print_org_table (table_filename, table_name, table_caption,
473 1 + ARRAY_LENGTH (probabilities_crossover),
474 1 + ARRAY_LENGTH (probabilities_mutation), table_cell);
475 }
476
477 return EXIT_SUCCESS;
478}
479
480// simple-genetic-algorithm.c ends here