aboutsummaryrefslogtreecommitdiff
path: root/src/simple-ant-colony-optimization.c
diff options
context:
space:
mode:
authorLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 06:37:40 +0000
committerLibravatar Martin Michalec <martin@michalec.dev>2026-11-10 06:37:40 +0000
commit7ac9c048bb7c00d614230997df520b9319f0a030 (patch)
tree74e016451f0c344508f621b12ebc6ea6d96ca25d /src/simple-ant-colony-optimization.c
downloadlab-06-master.tar.gz
publishHEADmaster
Diffstat (limited to 'src/simple-ant-colony-optimization.c')
-rw-r--r--src/simple-ant-colony-optimization.c379
1 files changed, 379 insertions, 0 deletions
diff --git a/src/simple-ant-colony-optimization.c b/src/simple-ant-colony-optimization.c
new file mode 100644
index 0000000..9e19feb
--- /dev/null
+++ b/src/simple-ant-colony-optimization.c
@@ -0,0 +1,379 @@
1// simple-ant-colony-optimization.c --- simple ant colony optimization
2
3#include <stdio.h>
4#include <stdlib.h>
5#include <stdbool.h>
6#include <string.h>
7#include <math.h>
8#include <float.h>
9#include <time.h>
10
11#include "utils.h"
12#include "data.h"
13#include "dynamic-array.h"
14
15#define ANT_COUNT 100
16#define I_START 0
17#define I_END 0
18#define NODE_COUNT ((int) (sizeof (*distances)/sizeof (**distances)))
19#define ALPHA 1
20#define BETA 3.5
21#define RHO .4
22#define MAX_GENERATIONS 100
23#define MAX_GENERATIONS_NO_IMPROVEMENT 30
24#define SEED 1763499947 // 7967
25// #define SEED time (NULL)
26// #define PLOT_PNG
27#define X_MIN ( 25 - 100)
28#define X_MAX (1740 + 100)
29#define Y_MIN ( 5 - 100)
30#define Y_MAX (1175 + 100)
31
32struct path {
33 u8 *items;
34 u32 count;
35 u32 capacity;
36} path = {0};
37
38struct crdf {
39 struct crdf_entry {
40 f32 c;
41 u32 j;
42 } *items;
43 u32 count;
44 u32 capacity;
45} crdf = {0};
46
47f32 pheromones1[NODE_COUNT][NODE_COUNT];
48f32 pheromones2[NODE_COUNT][NODE_COUNT];
49
50f32 (*pheromones_current)[NODE_COUNT] = pheromones1;
51f32 (*pheromones_next )[NODE_COUNT] = pheromones2;
52
53u8 shortest_path[NODE_COUNT];
54float shortest_path_length = FLT_MAX;
55int shortest_path_generation = 0;
56
57static u64 visited = 1;
58
59static f32 distances[NODE_COUNT][NODE_COUNT];
60
61f32
62build_crdf (u8 i)
63{
64 f32 sum = 0;
65
66 if (path.count == NODE_COUNT) {
67 u8 j = I_END;
68
69 sum += (powf (pheromones_current[i][j], ALPHA) *
70 powf ( 1/distances[i][j], BETA ));
71 DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (crdf, ((struct crdf_entry) { sum, j }));
72 return sum;
73 }
74
75 for (u8 j = 0; j < NODE_COUNT; ++j) {
76 if (j == I_END) continue;
77 if (j == i) continue;
78 if (visited & (u64) 1 << j) continue;
79
80 sum += (powf (pheromones_current[i][j], ALPHA) *
81 powf ( 1/distances[i][j], BETA ));
82 DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (crdf, ((struct crdf_entry) { sum, j }));
83 }
84
85 return sum;
86}
87
88f32
89measure_path (void)
90{
91 f32 distance = 0;
92
93 u8 prev = I_START;
94 for (u32 i = 1; i < path.count; ++i) {
95 u8 curr = path.items[i];
96 distance += distances[prev][curr];
97 prev = curr;
98 }
99
100 return distance;
101}
102
103int
104sort_crdf (const void *lhs, const void *rhs)
105{
106 const struct crdf_entry *lhs_e = lhs;
107 const struct crdf_entry *rhs_e = rhs;
108
109 if (lhs_e->c < rhs_e->c) return -1;
110 if (lhs_e->c > rhs_e->c) return +1;
111 return 0;
112}
113
114u8
115select_j (u8 i)
116{
117 DYNAMIC_ARRAY__RESET (crdf);
118 f32 r = build_crdf (i);
119
120 // NOTE(cmmm): might cause infinite loop
121 if (crdf.count == 0) {
122 path.count -= 1;
123 return DYNAMIC_ARRAY__POP (path);
124 }
125
126 qsort (crdf.items, crdf.count, sizeof (*crdf.items), sort_crdf);
127 r *= rand () /(float) RAND_MAX;
128
129 DYNAMIC_ARRAY__FOREACH (e, crdf) {
130 if (e->c >= r)
131 return e->j;
132 }
133
134 UNREACHABLE ();
135}
136
137f32
138remap (f32 value, f32 input_start, f32 input_end, f32 output_start, f32 output_end)
139{
140 return ((value - input_start) /
141 ( input_end - input_start) *
142 (output_end - output_start) +
143 output_start);
144}
145
146void
147plot (const char *output, u8 path[NODE_COUNT], float path_length, int generation, bool pheromones)
148{
149 FILE *gp = popen ("gnuplot", "w");
150 // FILE *gp = fopen ("test.gp", "w");
151#ifdef PLOT_PNG
152 fprintf (gp, "set term pngcairo\n");
153 fprintf (gp, "set output '%s-%02d.png'\n", output, generation);
154#else
155 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
156 " nocrop size 15cm,10cm noheader\n");
157 fprintf (gp, "set output '%s-%02d.tex'\n", output, generation);
158#endif
159
160 fprintf (gp, "set title 'Поколение №%d, \\quad Лучшая особь: %f'\n",
161 generation, path_length);
162 fprintf (gp, "set xlabel '\\(x\\)'\n");
163 fprintf (gp, "set ylabel '\\(y\\)' norotate\n");
164 fprintf (gp, "set xrange [%hd:%hd]\n", X_MIN, X_MAX);
165 fprintf (gp, "set yrange [%hd:%hd]\n", Y_MIN, Y_MAX);
166
167 fprintf (gp, "plot ");
168 fprintf (gp, "'-' with lines lw 9.0 lc 'gray' title '\\small{Оптимальный путь}',");
169 fprintf (gp, "'-' with lines lw 3.0 lc 'red' title '\\small{Лучшая особь}',");
170 if (pheromones)
171 fprintf (gp, "'-' with lines lw 1.5 lc rgb var title '\\small{Феромоны}',");
172 fprintf (gp, "'-' with points ps 0.5 pt 2 lc 'blue' title '\\small{Координаты}'\n");
173
174 for (int i = 0; i < NODE_COUNT; ++i) {
175 struct point p = buildings[optimal_path[i] - 1];
176 fprintf (gp, "%hd %hd\n", p.x, p.y);
177 } fprintf (gp, "%hd %hd\ne\n",
178 buildings[optimal_path[0] - 1].x,
179 buildings[optimal_path[0] - 1].y);
180
181 for (int i = 0; i <= NODE_COUNT; ++i) {
182 struct point p = buildings[path[i]];
183 fprintf (gp, "%hd %hd\n", p.x, p.y);
184 } fprintf (gp, "e\n");
185
186 if (pheromones) {
187 f32 min = FLT_MAX;
188 f32 max = FLT_MIN;
189 for (int i = 0; i < NODE_COUNT; ++i) {
190 for (int j = i; j < NODE_COUNT; ++j) {
191 f32 c = pheromones_current[i][j];
192 if (c < min) min = c;
193 if (c > max) max = c;
194 }
195 }
196 for (int i = 0; i < NODE_COUNT; ++i) {
197 for (int j = i; j < NODE_COUNT; ++j) {
198 struct point from = buildings[i];
199 struct point to = buildings[j];
200 u8 s = remap (pheromones_current[i][j], min, max, 255, 63);
201 u32 c = s << 24 | 0x000000;
202 fprintf (gp, "%hd %hd %u\n%hd %hd %u\n\n", from.x, from.y, c, to.x, to.y, c);
203 }
204 } fprintf (gp, "e\n");
205 }
206
207 for (int i = 0; i < NODE_COUNT; ++i) {
208 struct point p = buildings[i];
209 fprintf (gp, "%hd %hd\n", p.x, p.y);
210 } fprintf (gp, "e\n");
211
212 pclose (gp);
213}
214
215struct {
216 f32 min, average;
217} generation_fitness[MAX_GENERATIONS];
218
219void
220plot__fitness_over_generations (const char *output, int generations)
221{
222 FILE *gp = popen ("gnuplot", "w");
223 // FILE *gp = fopen ("test.gp", "w");
224#ifdef PLOT_PNG
225 fprintf (gp, "set term pngcairo\n");
226 fprintf (gp, "set output '%s.png'\n", output);
227#else
228 fprintf (gp, "set term cairolatex pdf input blacktext notransparent"
229 " nocrop size 15cm,10cm noheader\n");
230 fprintf (gp, "set output '%s.tex'\n", output);
231#endif
232
233 fprintf (gp, "set xrange [0:%d]\n", MAX_GENERATIONS);
234 fprintf (gp, "set yrange [7000:13000]\n");
235 fprintf (gp, "set xlabel '№ поколения'\n");
236 fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n");
237 fprintf (gp, "set y2range [7000:13000]\n");
238 fprintf (gp, "set y2tics ('7498.270020' 7498.270020, '7966.763184' 7966.763184)\n");
239 fprintf (gp, "set xtics (%d, %d)\n", shortest_path_generation, generations);
240 fprintf (gp, "set x2tics\n");
241 fprintf (gp, "set arrow from %d, graph 0 to %d,%f nohead lc 1 dt 2\n", shortest_path_generation, shortest_path_generation, shortest_path_length);
242 fprintf (gp, "set arrow from %d,%f to %d,%f nohead lc 1 dt 2\n", shortest_path_generation, shortest_path_length, MAX_GENERATIONS, shortest_path_length);
243 fprintf (gp, "set arrow from %d, graph 0 to %d, graph 1 nohead lc 4 dt 3\n", generations, generations);
244
245 fprintf (gp, "plot ");
246 fprintf (gp, "'-' with lines title 'Лучшее значение',");
247 fprintf (gp, "'-' with lines title 'Среднее значение',");
248 fprintf (gp, "7498.270020 title 'Оптимальное значение'\n");
249
250 for (int i = 0; i <= generations; ++i) {
251 fprintf (gp, "%d %f\n", i, generation_fitness[i].min);
252 } fprintf (gp, "e\n");
253
254 for (int i = 0; i <= generations; ++i) {
255 fprintf (gp, "%d %f\n", i, generation_fitness[i].average);
256 } fprintf (gp, "e\n");
257
258 pclose (gp);
259}
260
261int
262main (void)
263{
264 printf ("%u\n", (u32) SEED);
265 srand (SEED);
266
267 DYNAMIC_ARRAY__ENSURE_CAPACITY (crdf, NODE_COUNT);
268 DYNAMIC_ARRAY__ENSURE_CAPACITY (path, NODE_COUNT);
269
270 // init pheromones
271 for (u16 i = 0; i < NODE_COUNT; ++i) {
272 for (u16 j = i; j < NODE_COUNT; ++j) {
273 f32 c = rand () /(float) RAND_MAX;
274 pheromones_current[i][j] = c;
275 pheromones_current[j][i] = c;
276 }
277 }
278
279 u8 last_improvement = 0;
280 int generation;
281 for (generation = 0; generation < MAX_GENERATIONS; ++generation) {
282 u8 generation_shortest_path[NODE_COUNT];
283 float generation_shortest_path_length = FLT_MAX;
284
285 printf ("generation: %4d ", generation);
286
287 // prepare next pheromones
288 memcpy (pheromones_next, pheromones_current,
289 NODE_COUNT*NODE_COUNT*sizeof (**pheromones_next));
290 for (u16 i = 0; i < NODE_COUNT*NODE_COUNT; ++i)
291 (*pheromones_next)[i] *= 1 - RHO;
292
293 f32 path_length_sum = 0;
294 // for each ant build path
295 DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (path, I_START);
296 for (u16 k = 0; k < ANT_COUNT; ++k) {
297 visited = 1;
298 u8 i = I_START; // ants current location
299 path.count = 1;
300 while (i != I_END || path.count == 1) {
301 u8 j = select_j (i);
302 DYNAMIC_ARRAY__APPEND (path, j);
303 visited |= (u64) 1 << j;
304 i = j;
305 }
306
307 // eliminate loops
308 eliminate_loop:
309 for (u32 i = 0; i < path.count; ++i) {
310 for (u32 j = i + 1; j < path.count - 1; ++j) {
311 if (path.items[j] == path.items[i]) {
312 memmove (&path.items[i + 1], &path.items[j + 1],
313 (path.count - j)*sizeof (*path.items));
314 path.count -= j - i;
315 goto eliminate_loop;
316 }
317 }
318 }
319
320 f32 path_length = measure_path ();
321 path_length_sum += path_length;
322 if (path_length < shortest_path_length) {
323 shortest_path_length = path_length;
324 memcpy (shortest_path, path.items, sizeof (shortest_path));
325 last_improvement = generation;
326 shortest_path_generation = generation;
327 }
328 if (path_length < generation_shortest_path_length) {
329 generation_shortest_path_length = path_length;
330 memcpy (generation_shortest_path, path.items,
331 sizeof (generation_shortest_path));
332 }
333
334 // print path
335 if (k == 0) {
336 DYNAMIC_ARRAY__FOREACH (point, path) {
337 if (point == path.items) printf ("%d", *point);
338 else printf (" -> %d", *point);
339 } printf (" %5.f\n", path_length);
340 }
341
342 // update pheromones
343 i = I_START;
344 f32 delta_tau = 1./path_length;
345 for (const u8 *jp = &path.items[1]; jp < path.items + path.count; ++jp) {
346 u8 j = *jp;
347 pheromones_next[i][j] += delta_tau;
348 pheromones_next[j][i] += delta_tau;
349 i = j;
350 }
351 }
352 // plot best of generation
353 plot ("./res/path", generation_shortest_path,
354 generation_shortest_path_length, generation, generation >= 10);
355
356 generation_fitness[generation].min = generation_shortest_path_length;
357 generation_fitness[generation].average = path_length_sum/ANT_COUNT;
358
359 SWAP_PTR (pheromones_current, pheromones_next);
360
361 if (generation - last_improvement > MAX_GENERATIONS_NO_IMPROVEMENT)
362 break;
363 }
364
365 printf ("shortest-at: %3d ", shortest_path_generation);
366 DYNAMIC_ARRAY__FOREACH (point, path) {
367 if (point == path.items) printf ("%d", *point);
368 else printf (" -> %d", *point);
369 } printf (" %5.f\n", shortest_path_length);
370
371 plot ("./res/best-path", shortest_path, shortest_path_length,
372 shortest_path_generation, false);
373
374 plot__fitness_over_generations ("./res/convergence", generation);
375
376 return EXIT_SUCCESS;
377}
378
379// simple-ant-colony-optimization.c ends here