From 7ac9c048bb7c00d614230997df520b9319f0a030 Mon Sep 17 00:00:00 2001 From: Martin Michalec Date: Tue, 10 Nov 2026 09:37:40 +0300 Subject: publish --- src/simple-ant-colony-optimization.c | 379 +++++++++++++++++++++++++++++++++++ 1 file changed, 379 insertions(+) create mode 100644 src/simple-ant-colony-optimization.c (limited to 'src/simple-ant-colony-optimization.c') 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 @@ +// simple-ant-colony-optimization.c --- simple ant colony optimization + +#include +#include +#include +#include +#include +#include +#include + +#include "utils.h" +#include "data.h" +#include "dynamic-array.h" + +#define ANT_COUNT 100 +#define I_START 0 +#define I_END 0 +#define NODE_COUNT ((int) (sizeof (*distances)/sizeof (**distances))) +#define ALPHA 1 +#define BETA 3.5 +#define RHO .4 +#define MAX_GENERATIONS 100 +#define MAX_GENERATIONS_NO_IMPROVEMENT 30 +#define SEED 1763499947 // 7967 +// #define SEED time (NULL) +// #define PLOT_PNG +#define X_MIN ( 25 - 100) +#define X_MAX (1740 + 100) +#define Y_MIN ( 5 - 100) +#define Y_MAX (1175 + 100) + +struct path { + u8 *items; + u32 count; + u32 capacity; +} path = {0}; + +struct crdf { + struct crdf_entry { + f32 c; + u32 j; + } *items; + u32 count; + u32 capacity; +} crdf = {0}; + +f32 pheromones1[NODE_COUNT][NODE_COUNT]; +f32 pheromones2[NODE_COUNT][NODE_COUNT]; + +f32 (*pheromones_current)[NODE_COUNT] = pheromones1; +f32 (*pheromones_next )[NODE_COUNT] = pheromones2; + +u8 shortest_path[NODE_COUNT]; +float shortest_path_length = FLT_MAX; +int shortest_path_generation = 0; + +static u64 visited = 1; + +static f32 distances[NODE_COUNT][NODE_COUNT]; + +f32 +build_crdf (u8 i) +{ + f32 sum = 0; + + if (path.count == NODE_COUNT) { + u8 j = I_END; + + sum += (powf (pheromones_current[i][j], ALPHA) * + powf ( 1/distances[i][j], BETA )); + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (crdf, ((struct crdf_entry) { sum, j })); + return sum; + } + + for (u8 j = 0; j < NODE_COUNT; ++j) { + if (j == I_END) continue; + if (j == i) continue; + if (visited & (u64) 1 << j) continue; + + sum += (powf (pheromones_current[i][j], ALPHA) * + powf ( 1/distances[i][j], BETA )); + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (crdf, ((struct crdf_entry) { sum, j })); + } + + return sum; +} + +f32 +measure_path (void) +{ + f32 distance = 0; + + u8 prev = I_START; + for (u32 i = 1; i < path.count; ++i) { + u8 curr = path.items[i]; + distance += distances[prev][curr]; + prev = curr; + } + + return distance; +} + +int +sort_crdf (const void *lhs, const void *rhs) +{ + const struct crdf_entry *lhs_e = lhs; + const struct crdf_entry *rhs_e = rhs; + + if (lhs_e->c < rhs_e->c) return -1; + if (lhs_e->c > rhs_e->c) return +1; + return 0; +} + +u8 +select_j (u8 i) +{ + DYNAMIC_ARRAY__RESET (crdf); + f32 r = build_crdf (i); + + // NOTE(cmmm): might cause infinite loop + if (crdf.count == 0) { + path.count -= 1; + return DYNAMIC_ARRAY__POP (path); + } + + qsort (crdf.items, crdf.count, sizeof (*crdf.items), sort_crdf); + r *= rand () /(float) RAND_MAX; + + DYNAMIC_ARRAY__FOREACH (e, crdf) { + if (e->c >= r) + return e->j; + } + + UNREACHABLE (); +} + +f32 +remap (f32 value, f32 input_start, f32 input_end, f32 output_start, f32 output_end) +{ + return ((value - input_start) / + ( input_end - input_start) * + (output_end - output_start) + + output_start); +} + +void +plot (const char *output, u8 path[NODE_COUNT], float path_length, int generation, bool pheromones) +{ + FILE *gp = popen ("gnuplot", "w"); + // FILE *gp = fopen ("test.gp", "w"); +#ifdef PLOT_PNG + fprintf (gp, "set term pngcairo\n"); + fprintf (gp, "set output '%s-%02d.png'\n", output, generation); +#else + fprintf (gp, "set term cairolatex pdf input blacktext notransparent" + " nocrop size 15cm,10cm noheader\n"); + fprintf (gp, "set output '%s-%02d.tex'\n", output, generation); +#endif + + fprintf (gp, "set title 'Поколение №%d, \\quad Лучшая особь: %f'\n", + generation, path_length); + fprintf (gp, "set xlabel '\\(x\\)'\n"); + fprintf (gp, "set ylabel '\\(y\\)' norotate\n"); + fprintf (gp, "set xrange [%hd:%hd]\n", X_MIN, X_MAX); + fprintf (gp, "set yrange [%hd:%hd]\n", Y_MIN, Y_MAX); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines lw 9.0 lc 'gray' title '\\small{Оптимальный путь}',"); + fprintf (gp, "'-' with lines lw 3.0 lc 'red' title '\\small{Лучшая особь}',"); + if (pheromones) + fprintf (gp, "'-' with lines lw 1.5 lc rgb var title '\\small{Феромоны}',"); + fprintf (gp, "'-' with points ps 0.5 pt 2 lc 'blue' title '\\small{Координаты}'\n"); + + for (int i = 0; i < NODE_COUNT; ++i) { + struct point p = buildings[optimal_path[i] - 1]; + fprintf (gp, "%hd %hd\n", p.x, p.y); + } fprintf (gp, "%hd %hd\ne\n", + buildings[optimal_path[0] - 1].x, + buildings[optimal_path[0] - 1].y); + + for (int i = 0; i <= NODE_COUNT; ++i) { + struct point p = buildings[path[i]]; + fprintf (gp, "%hd %hd\n", p.x, p.y); + } fprintf (gp, "e\n"); + + if (pheromones) { + f32 min = FLT_MAX; + f32 max = FLT_MIN; + for (int i = 0; i < NODE_COUNT; ++i) { + for (int j = i; j < NODE_COUNT; ++j) { + f32 c = pheromones_current[i][j]; + if (c < min) min = c; + if (c > max) max = c; + } + } + for (int i = 0; i < NODE_COUNT; ++i) { + for (int j = i; j < NODE_COUNT; ++j) { + struct point from = buildings[i]; + struct point to = buildings[j]; + u8 s = remap (pheromones_current[i][j], min, max, 255, 63); + u32 c = s << 24 | 0x000000; + fprintf (gp, "%hd %hd %u\n%hd %hd %u\n\n", from.x, from.y, c, to.x, to.y, c); + } + } fprintf (gp, "e\n"); + } + + for (int i = 0; i < NODE_COUNT; ++i) { + struct point p = buildings[i]; + fprintf (gp, "%hd %hd\n", p.x, p.y); + } fprintf (gp, "e\n"); + + pclose (gp); +} + +struct { + f32 min, average; +} generation_fitness[MAX_GENERATIONS]; + +void +plot__fitness_over_generations (const char *output, int generations) +{ + FILE *gp = popen ("gnuplot", "w"); + // FILE *gp = fopen ("test.gp", "w"); +#ifdef PLOT_PNG + fprintf (gp, "set term pngcairo\n"); + fprintf (gp, "set output '%s.png'\n", output); +#else + fprintf (gp, "set term cairolatex pdf input blacktext notransparent" + " nocrop size 15cm,10cm noheader\n"); + fprintf (gp, "set output '%s.tex'\n", output); +#endif + + fprintf (gp, "set xrange [0:%d]\n", MAX_GENERATIONS); + fprintf (gp, "set yrange [7000:13000]\n"); + fprintf (gp, "set xlabel '№ поколения'\n"); + fprintf (gp, "set ylabel 'Значение фитнесс-функции' offset graph -0.02,0\n"); + fprintf (gp, "set y2range [7000:13000]\n"); + fprintf (gp, "set y2tics ('7498.270020' 7498.270020, '7966.763184' 7966.763184)\n"); + fprintf (gp, "set xtics (%d, %d)\n", shortest_path_generation, generations); + fprintf (gp, "set x2tics\n"); + 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); + 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); + fprintf (gp, "set arrow from %d, graph 0 to %d, graph 1 nohead lc 4 dt 3\n", generations, generations); + + fprintf (gp, "plot "); + fprintf (gp, "'-' with lines title 'Лучшее значение',"); + fprintf (gp, "'-' with lines title 'Среднее значение',"); + fprintf (gp, "7498.270020 title 'Оптимальное значение'\n"); + + for (int i = 0; i <= generations; ++i) { + fprintf (gp, "%d %f\n", i, generation_fitness[i].min); + } fprintf (gp, "e\n"); + + for (int i = 0; i <= generations; ++i) { + fprintf (gp, "%d %f\n", i, generation_fitness[i].average); + } fprintf (gp, "e\n"); + + pclose (gp); +} + +int +main (void) +{ + printf ("%u\n", (u32) SEED); + srand (SEED); + + DYNAMIC_ARRAY__ENSURE_CAPACITY (crdf, NODE_COUNT); + DYNAMIC_ARRAY__ENSURE_CAPACITY (path, NODE_COUNT); + + // init pheromones + for (u16 i = 0; i < NODE_COUNT; ++i) { + for (u16 j = i; j < NODE_COUNT; ++j) { + f32 c = rand () /(float) RAND_MAX; + pheromones_current[i][j] = c; + pheromones_current[j][i] = c; + } + } + + u8 last_improvement = 0; + int generation; + for (generation = 0; generation < MAX_GENERATIONS; ++generation) { + u8 generation_shortest_path[NODE_COUNT]; + float generation_shortest_path_length = FLT_MAX; + + printf ("generation: %4d ", generation); + + // prepare next pheromones + memcpy (pheromones_next, pheromones_current, + NODE_COUNT*NODE_COUNT*sizeof (**pheromones_next)); + for (u16 i = 0; i < NODE_COUNT*NODE_COUNT; ++i) + (*pheromones_next)[i] *= 1 - RHO; + + f32 path_length_sum = 0; + // for each ant build path + DYNAMIC_ARRAY__APPEND__KNOWN_CAPACITY (path, I_START); + for (u16 k = 0; k < ANT_COUNT; ++k) { + visited = 1; + u8 i = I_START; // ants current location + path.count = 1; + while (i != I_END || path.count == 1) { + u8 j = select_j (i); + DYNAMIC_ARRAY__APPEND (path, j); + visited |= (u64) 1 << j; + i = j; + } + + // eliminate loops + eliminate_loop: + for (u32 i = 0; i < path.count; ++i) { + for (u32 j = i + 1; j < path.count - 1; ++j) { + if (path.items[j] == path.items[i]) { + memmove (&path.items[i + 1], &path.items[j + 1], + (path.count - j)*sizeof (*path.items)); + path.count -= j - i; + goto eliminate_loop; + } + } + } + + f32 path_length = measure_path (); + path_length_sum += path_length; + if (path_length < shortest_path_length) { + shortest_path_length = path_length; + memcpy (shortest_path, path.items, sizeof (shortest_path)); + last_improvement = generation; + shortest_path_generation = generation; + } + if (path_length < generation_shortest_path_length) { + generation_shortest_path_length = path_length; + memcpy (generation_shortest_path, path.items, + sizeof (generation_shortest_path)); + } + + // print path + if (k == 0) { + DYNAMIC_ARRAY__FOREACH (point, path) { + if (point == path.items) printf ("%d", *point); + else printf (" -> %d", *point); + } printf (" %5.f\n", path_length); + } + + // update pheromones + i = I_START; + f32 delta_tau = 1./path_length; + for (const u8 *jp = &path.items[1]; jp < path.items + path.count; ++jp) { + u8 j = *jp; + pheromones_next[i][j] += delta_tau; + pheromones_next[j][i] += delta_tau; + i = j; + } + } + // plot best of generation + plot ("./res/path", generation_shortest_path, + generation_shortest_path_length, generation, generation >= 10); + + generation_fitness[generation].min = generation_shortest_path_length; + generation_fitness[generation].average = path_length_sum/ANT_COUNT; + + SWAP_PTR (pheromones_current, pheromones_next); + + if (generation - last_improvement > MAX_GENERATIONS_NO_IMPROVEMENT) + break; + } + + printf ("shortest-at: %3d ", shortest_path_generation); + DYNAMIC_ARRAY__FOREACH (point, path) { + if (point == path.items) printf ("%d", *point); + else printf (" -> %d", *point); + } printf (" %5.f\n", shortest_path_length); + + plot ("./res/best-path", shortest_path, shortest_path_length, + shortest_path_generation, false); + + plot__fitness_over_generations ("./res/convergence", generation); + + return EXIT_SUCCESS; +} + +// simple-ant-colony-optimization.c ends here -- cgit v1.3.1