1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
|
// simple-ant-colony-optimization.c --- simple ant colony optimization
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include <math.h>
#include <float.h>
#include <time.h>
#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
|