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