5de42846cba08e76b17f48be05e2f02d5944c9e4
[sort-networks.git] / src / sn-markov.c
1 /**
2  * libsortnetwork - src/sn-markov.c
3  * Copyright (C) 2008-2010  Florian octo Forster
4  *
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.
8  *
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.
13  *
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
17  *
18  * Authors:
19  *   Florian octo Forster <ff at octo.it>
20  **/
21
22 #ifndef _ISOC99_SOURCE
23 # define _ISOC99_SOURCE
24 #endif
25 #ifndef _POSIX_C_SOURCE
26 # define _POSIX_C_SOURCE 200809L
27 #endif
28 #ifndef _XOPEN_SOURCE
29 # define _XOPEN_SOURCE 700
30 #endif
31
32 #include <stdlib.h>
33 #include <stdio.h>
34 #include <stdint.h>
35 #include <inttypes.h>
36 #include <string.h>
37
38 #include <unistd.h>
39 #include <signal.h>
40 #include <assert.h>
41 #include <limits.h>
42 #include <errno.h>
43
44 #include "sn_network.h"
45 #include "sn_random.h"
46 #include "histogram.h"
47
48 #if !defined(__GNUC__) || !__GNUC__
49 # define __attribute__(x) /**/
50 #endif
51
52 static int inputs_num = 16;
53
54 static char *initial_input_file = NULL;
55 static char *best_output_file = NULL;
56
57 static sn_network_t *best_solution = NULL;
58 static int best_rating = INT_MAX;
59
60 static _Bool do_loop = 1;
61 static uint64_t max_iterations = 0;
62
63 static histogram_t *histogram;
64
65 static void sigint_handler (int signal __attribute__((unused)))
66 {
67   do_loop = 0;
68 } /* void sigint_handler */
69
70 static void exit_usage (const char *name, int status)
71 {
72   printf ("Usage: %s [options]\n"
73       "\n"
74       "Valid options are:\n"
75       "  -i <file>     Initial input file (REQUIRED)\n"
76       "  -o <file>     Write the current best solution to <file>\n"
77       "  -n <number>   Maximum number of steps (iterations) to perform\n"
78       "  -h            Display usage information (this message)\n"
79       "\n",
80       name);
81   exit (status);
82 } /* void exit_usage */
83
84 int read_options (int argc, char **argv)
85 {
86   int option;
87
88   while ((option = getopt (argc, argv, "i:o:n:h")) != -1)
89   {
90     switch (option)
91     {
92       case 'i':
93       {
94         if (initial_input_file != NULL)
95           free (initial_input_file);
96         initial_input_file = strdup (optarg);
97         break;
98       }
99
100       case 'o':
101       {
102         if (best_output_file != NULL)
103           free (best_output_file);
104         best_output_file = strdup (optarg);
105         break;
106       }
107
108       case 'n':
109       {
110         errno = 0;
111         max_iterations = (uint64_t) strtoull (optarg,
112             /* endptr = */ NULL,
113             /* base   = */ 0);
114         if (errno != 0)
115         {
116           fprintf (stderr, "Parsing integer argument failed: %s\n",
117               strerror (errno));
118           exit_usage (argv[0], EXIT_FAILURE);
119         }
120         break;
121       }
122
123       case 'h':
124       default:
125         exit_usage (argv[0], EXIT_SUCCESS);
126     }
127   }
128
129   return (0);
130 } /* int read_options */
131
132 static int rate_network (const sn_network_t *n)
133 {
134   int rate;
135
136   rate = SN_NETWORK_STAGE_NUM (n) * SN_NETWORK_INPUT_NUM (n);
137   rate += sn_network_get_comparator_num (n);
138
139   return (rate);
140 } /* int rate_network */
141
142 static sn_network_t *get_next (sn_network_t *n)
143 {
144   sn_network_t *nleft;
145   sn_network_t *nright;
146   sn_network_t *nret;
147
148   if (n == NULL)
149     return (NULL);
150
151   nleft = sn_network_clone (n);
152   nright = sn_network_clone (n);
153
154   assert (nleft != NULL);
155   assert (nright != NULL);
156
157   /* combine the two parents */
158   nret = sn_network_combine (nleft, nright);
159
160   sn_network_destroy (nleft);
161   sn_network_destroy (nright);
162
163   /* randomly chose an input and do a min- or max-cut. */
164   while (SN_NETWORK_INPUT_NUM (nret) > inputs_num)
165   {
166     int pos;
167     enum sn_network_cut_dir_e dir;
168
169     pos = sn_bounded_random (0, SN_NETWORK_INPUT_NUM (nret) - 1);
170     dir = (sn_bounded_random (0, 1) == 0) ? DIR_MIN : DIR_MAX;
171
172     assert ((pos >= 0) && (pos < SN_NETWORK_INPUT_NUM (nret)));
173
174     sn_network_cut_at (nret, pos, dir);
175   }
176
177   /* compress the network to get a compact representation */
178   sn_network_compress (nret);
179
180   assert (SN_NETWORK_INPUT_NUM (nret) == inputs_num);
181   return (nret);
182 } /* sn_network_t *get_next */
183
184 static void random_walk (sn_network_t *n)
185 {
186   uint64_t iteration_counter = 0;
187
188   while (do_loop)
189   {
190     sn_network_t *next = get_next (n);
191     int rating;
192
193     if (next == NULL)
194     {
195       fprintf (stderr, "get_next() failed.\n");
196       return;
197     }
198
199     rating = rate_network (next);
200     if (rating < best_rating)
201     {
202       printf ("New best rating (%i) after %"PRIu64" iterations.\n",
203           rating, iteration_counter);
204
205       best_rating = rating;
206       sn_network_destroy (best_solution);
207       best_solution = sn_network_clone (next);
208     }
209
210     hist_account (histogram, sn_network_get_comparator_num (next));
211
212     sn_network_destroy (n);
213     n = next;
214     iteration_counter++;
215
216     if ((max_iterations > 0) && (iteration_counter >= max_iterations))
217       break;
218   } /* while (do_loop) */
219
220   sn_network_destroy (n);
221
222   printf ("Exiting after %"PRIu64" iterations.\n", iteration_counter);
223 } /* void random_walk */
224
225 int main (int argc, char **argv)
226 {
227   sn_network_t *start_network;
228
229   struct sigaction sigint_action;
230   struct sigaction sigterm_action;
231
232   histogram = hist_create ();
233
234   read_options (argc, argv);
235   if (initial_input_file == NULL)
236     exit_usage (argv[0], EXIT_FAILURE);
237
238   memset (&sigint_action, '\0', sizeof (sigint_action));
239   sigint_action.sa_handler = sigint_handler;
240   sigaction (SIGINT, &sigint_action, NULL);
241
242   memset (&sigterm_action, '\0', sizeof (sigterm_action));
243   sigterm_action.sa_handler = sigint_handler;
244   sigaction (SIGTERM, &sigterm_action, NULL);
245
246   start_network = sn_network_read_file (initial_input_file);
247   if (start_network == NULL)
248   {
249     printf ("start_network == NULL\n");
250     exit (EXIT_FAILURE);
251   }
252
253   inputs_num = SN_NETWORK_INPUT_NUM(start_network);
254
255   printf ("Current configuration:\n"
256       "  Initial network:  %s\n"
257       "  Number of inputs: %3i\n"
258       "=======================\n",
259       initial_input_file, inputs_num);
260
261   random_walk (start_network);
262   start_network = NULL;
263
264   hist_print (histogram);
265   hist_destroy (histogram);
266   histogram = NULL;
267
268   if (best_solution != NULL)
269   {
270     if (best_output_file != NULL)
271       sn_network_write_file (best_solution, best_output_file);
272
273     printf ("=== Best solution (rating: %i) ===\n", best_rating);
274     sn_network_normalize (best_solution);
275     sn_network_show (best_solution);
276     sn_network_destroy (best_solution);
277   }
278
279   exit (EXIT_SUCCESS);
280   return (0);
281 } /* int main */
282
283 /* vim: set shiftwidth=2 softtabstop=2 : */