2 * libsortnetwork - src/sn-evolution.c
3 * Copyright (C) 2008-2010 Florian octo Forster
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms of the GNU General Public License as published by the
7 * Free Software Foundation; only version 2 of the License is applicable.
9 * This program is distributed in the hope that it will be useful, but
10 * WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 * General Public License for more details.
14 * You should have received a copy of the GNU General Public License along
15 * with this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
19 * Florian octo Forster <ff at octo.it>
22 #ifndef _ISOC99_SOURCE
23 # define _ISOC99_SOURCE
25 #ifndef _POSIX_C_SOURCE
26 # define _POSIX_C_SOURCE 200809L
29 # define _XOPEN_SOURCE 700
37 #include <sys/types.h>
49 #include <population.h>
51 #include "sn_network.h"
52 #include "sn_random.h"
54 #if !defined(__GNUC__) || !__GNUC__
55 # define __attribute__(x) /**/
58 #define SNE_MIN(a,b) ((a) < (b) ? (a) : (b))
59 #define SNE_MAX(a,b) ((a) > (b) ? (a) : (b))
61 static uint64_t iteration_counter = 0;
62 static int inputs_num = -1;
64 static int comparators_num = -1;
66 static char *initial_input_file = NULL;
67 static char *best_output_file = NULL;
69 static int stats_interval = 0;
71 static int max_population_size = 128;
72 static population_t *population;
74 static int evolution_threads_num = 4;
76 static int do_loop = 0;
78 static int weight_overall = 50;
79 static int weight_fails = 2;
80 static int weight_stages = 1;
82 static void sigint_handler (__attribute__((unused)) int signal)
85 } /* void sigint_handler */
87 static void exit_usage (const char *name)
89 printf ("Usage: %s [options]\n"
91 "Valid options are:\n"
92 " -i <inputs> Number of inputs\n"
93 " -c <comparators> Number of comparators\n"
94 " -I <file> Initial input file\n"
95 " -o <file> Write the current best solution to <file>\n"
96 " -p <num> Size of the population (default: 128)\n"
97 " -P <peer> Send individuals to <peer> (may be repeated)\n"
98 " -t <num> Number of threads (default: 4)\n"
102 } /* void exit_usage */
104 int read_options (int argc, char **argv)
108 while ((option = getopt (argc, argv, "i:c:I:o:p:P:s:t:h")) != -1)
126 comparators_num = tmp;
132 if (initial_input_file != NULL)
133 free (initial_input_file);
134 initial_input_file = strdup (optarg);
140 if (best_output_file != NULL)
141 free (best_output_file);
142 best_output_file = strdup (optarg);
148 int tmp = atoi (optarg);
151 max_population_size = tmp;
152 population_set_size (population, (size_t) max_population_size);
161 status = population_add_peer (population, optarg, /* port = */ NULL);
164 fprintf (stderr, "population_add_peer failed with status %i.\n",
172 int tmp = atoi (optarg);
174 stats_interval = tmp;
180 int tmp = atoi (optarg);
182 evolution_threads_num = tmp;
188 exit_usage (argv[0]);
193 } /* int read_options */
195 static int rate_network (sn_network_t *n) /* {{{ */
197 int test_pattern[n->inputs_num];
198 int values[n->inputs_num];
200 int patterns_sorted = 0;
201 int patterns_failed = 0;
203 memset (test_pattern, 0, sizeof (test_pattern));
211 /* Copy the current pattern and let the network sort it */
212 memcpy (values, test_pattern, sizeof (values));
213 status = sn_network_sort (n, values);
217 /* Check if the array is now sorted. */
218 previous = values[0];
220 for (i = 1; i < n->inputs_num; i++)
222 if (previous > values[i])
228 previous = values[i];
234 /* Generate the next test pattern */
236 for (i = 0; i < n->inputs_num; i++)
238 if (test_pattern[i] == 0)
251 /* Break out of the while loop if we tested all possible patterns */
256 /* All tests successfull */
257 return (weight_overall + (weight_stages * SN_NETWORK_STAGE_NUM (n)) + (weight_fails * patterns_failed));
258 } /* }}} int rate_network */
260 static sn_comparator_t get_random_comparator (void) /* {{{ */
264 c.min = sn_bounded_random (0, inputs_num - 1);
266 while (c.max == c.min)
267 c.max = sn_bounded_random (0, inputs_num - 1);
270 } /* }}} sn_comparator_t get_random_comparator */
272 static int mutate_network (sn_comparator_t *comparators, int comparators_num)
274 static int old_comparators_num = -1;
275 static double mutate_probability = 0.0;
279 if (old_comparators_num != comparators_num)
281 /* Probability that NO mutation takes place: 1/3 */
282 mutate_probability = powl (1.0 / 3.0, (1.0 / ((double) comparators_num)));
283 old_comparators_num = comparators_num;
286 /* `mutate_probability' actually holds 1-p, i. e. it is close to one */
287 for (i = 0; i < comparators_num; i++)
288 if (sn_double_random () >= mutate_probability)
289 comparators[i] = get_random_comparator ();
292 } /* int mutate_network */
294 static int create_offspring (void)
297 sn_comparator_t p0_comparators[comparators_num];
298 int p0_comparators_num;
301 sn_comparator_t p1_comparators[comparators_num];
302 int p1_comparators_num;
305 sn_comparator_t n_comparators[comparators_num];
306 int n_comparators_num;
310 p0 = population_get_random (population);
311 p1 = population_get_random (population);
316 p0_comparators_num = 0;
317 for (i = 0; i < SN_NETWORK_STAGE_NUM (p0); i++)
322 s = SN_NETWORK_STAGE_GET (p0, i);
324 for (j = 0; j < SN_STAGE_COMP_NUM (s); j++)
328 c = SN_STAGE_COMP_GET (s, j);
329 p0_comparators[p0_comparators_num] = *c;
330 p0_comparators_num++;
333 while (p0_comparators_num < comparators_num)
335 p0_comparators[p0_comparators_num] = get_random_comparator ();
336 p0_comparators_num++;
338 sn_network_destroy (p0);
341 p1_comparators_num = 0;
342 for (i = 0; i < SN_NETWORK_STAGE_NUM (p1); i++)
347 s = SN_NETWORK_STAGE_GET (p1, i);
349 for (j = 0; j < SN_STAGE_COMP_NUM (s); j++)
353 c = SN_STAGE_COMP_GET (s, j);
354 p1_comparators[p1_comparators_num] = *c;
355 p1_comparators_num++;
358 while (p1_comparators_num < comparators_num)
360 p1_comparators[p1_comparators_num] = get_random_comparator ();
361 p1_comparators_num++;
363 sn_network_destroy (p1);
366 n_comparators_num = sn_bounded_random (SNE_MIN (p0_comparators_num, p1_comparators_num),
367 SNE_MAX (p0_comparators_num, p1_comparators_num));
369 for (i = 0; i < n_comparators_num; i++)
371 if (i >= p0_comparators_num)
372 n_comparators[i] = p1_comparators[i];
373 else if (i >= p1_comparators_num)
374 n_comparators[i] = p0_comparators[i];
375 else if (sn_bounded_random (0, 1) == 0)
376 n_comparators[i] = p1_comparators[i];
378 n_comparators[i] = p0_comparators[i];
382 mutate_network (n_comparators, n_comparators_num);
384 n = sn_network_create (inputs_num);
385 for (i = 0; i < n_comparators_num; i++)
386 sn_network_comparator_add (n, &n_comparators[i]);
388 /* compress the network to get a compact representation */
389 sn_network_compress (n);
391 assert (SN_NETWORK_INPUT_NUM (n) == inputs_num);
393 population_insert (population, n);
395 sn_network_destroy (n);
398 } /* int create_offspring */
400 static void *evolution_thread (__attribute__((unused)) void *arg)
405 /* XXX: Not synchronized! */
410 } /* int start_evolution */
412 static int evolution_start (int threads_num)
414 pthread_t threads[threads_num]; /* C99 ftw! */
417 for (i = 0; i < threads_num; i++)
421 status = pthread_create (&threads[i], /* attr = */ NULL,
422 evolution_thread, /* arg = */ NULL);
425 fprintf (stderr, "evolution_start: pthread_create[%i] failed "
445 iter = iteration_counter;
447 n = population_get_fittest (population);
449 rating = rate_network (n);
451 stages_num = SN_NETWORK_STAGE_NUM (n);
453 for (i = 0; i < stages_num; i++)
457 s = SN_NETWORK_STAGE_GET (n, i);
458 comparators_num += SN_STAGE_COMP_NUM (s);
461 sn_network_destroy (n);
463 printf ("Best after approximately %i iterations: "
464 "%i comparators in %i stages. Rating: %i (%i not sorted).\n",
465 iter, comparators_num, stages_num, rating,
466 (rating - (weight_overall + (weight_stages * stages_num))) / weight_fails);
470 for (i = 0; i < threads_num; i++)
474 pthread_join (threads[i], /* value_ptr = */ NULL);
478 } /* int evolution_start */
480 int main (int argc, char **argv)
482 struct sigaction sigint_action;
483 struct sigaction sigterm_action;
485 population = population_create ((pi_rate_f) rate_network,
486 (pi_copy_f) sn_network_clone,
487 (pi_free_f) sn_network_destroy);
488 if (population == NULL)
490 fprintf (stderr, "population_create failed.\n");
494 population_set_serialization (population,
495 (pi_serialize_f) sn_network_serialize,
496 (pi_unserialize_f) sn_network_unserialize);
498 read_options (argc, argv);
500 if ((inputs_num <= 0) || (comparators_num <= 0))
501 exit_usage (argv[0]);
503 memset (&sigint_action, '\0', sizeof (sigint_action));
504 sigint_action.sa_handler = sigint_handler;
505 sigaction (SIGINT, &sigint_action, NULL);
507 memset (&sigterm_action, '\0', sizeof (sigterm_action));
508 sigterm_action.sa_handler = sigint_handler;
509 sigaction (SIGTERM, &sigterm_action, NULL);
511 population_start_listen_thread (population, NULL, NULL);
513 if (initial_input_file != NULL)
517 n = sn_network_read_file (initial_input_file);
520 fprintf (stderr, "Cannot read network from `%s'.\n",
525 if (n->inputs_num != inputs_num)
527 fprintf (stderr, "Network `%s' has %i inputs, but %i were configured "
528 "on the command line.\n",
529 initial_input_file, n->inputs_num, inputs_num);
533 population_insert (population, n);
534 sn_network_destroy (n);
536 else /* if (initial_input_file == NULL) */
541 n = sn_network_create (inputs_num);
542 for (i = 0; i < comparators_num; i++)
546 c = get_random_comparator ();
547 sn_network_comparator_add (n, &c);
550 population_insert (population, n);
551 sn_network_destroy (n);
554 printf ("Current configuration:\n"
555 " Number of inputs: %3i\n"
556 " Number of comparators: %3i\n"
557 " Population size: %3i\n"
558 "=======================\n",
559 inputs_num, comparators_num, max_population_size);
561 evolution_start (evolution_threads_num);
563 printf ("Exiting after %llu iterations.\n",
564 (unsigned long long) iteration_counter);
569 n = population_get_fittest (population);
572 if (best_output_file != NULL)
573 sn_network_write_file (n, best_output_file);
575 sn_network_destroy (n);
579 population_destroy (population);
584 /* vim: set shiftwidth=2 softtabstop=2 : */