ECF 1.5
knapsack-sga.c
1/* knapsack-sga.c
2 *
3 * (C) 2018 Carlos M. Fonseca <cmfonsec@dei.uc.pt>
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or (at
8 * your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program; if not, write to the Free Software Foundation,
17 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 */
19
20#include <stdlib.h>
21#include <stdio.h>
22#include <time.h>
23#include <gsl/gsl_rng.h>
24#include "knapsack.h"
25#include "sga.h"
26
27gsl_rng *rng; /* The single rng instance used by the whole code */
28
29int main(int argc, char **argv) {
30 struct problem *p;
31 struct solverState *ss;
32 int max_iter, pop_size, i;
33 double cost, mincost;
34
35 if (argc < 4) {
36 fprintf(stderr, "Usage: %s <file name> <pop size> <max iter>\n", argv[0]);
37 return 0;
38 }
39
40 /* Set up random number generation */
41 rng = gsl_rng_alloc(gsl_rng_mt19937);
42 gsl_rng_set(rng, time(0));
43
44 /* Input arguments */
45 pop_size = atoi(argv[2]);
46 max_iter = atoi(argv[3]);
47
48 /* Problem and solver instantiation */
49 p = newProblem(argv[1]);
50 if (p != NULL) {
51 ss = newSolver(p, pop_size);
52
53#if 0
54 /* Custom parameters */
55 setRecombinationRate(ss, 0.);
56 setMutationRate(ss, (1.-1./getSelectivePressure(ss))*.8);
57#endif
58
59 /* Run */
60 mincost = getObjectiveValue(getSolverSolution(ss));
61 printf("iter = 0, obj = %.0f\n", mincost);
62 for (i = 0; i < max_iter; i++) {
63 nextSolverState(ss);
64 cost = getObjectiveValue(getSolverSolution(ss));
65 if (cost < mincost) {
66 mincost = cost;
67 printf("iter = %d, obj = %.0f\n", i+1, mincost);
68 }
69 }
70
71 /* Report result */
72 printSolution(getSolverSolution(ss));
73
74 /* Clean up */
75 freeSolver(ss);
76 freeProblem(p);
77 }
78 gsl_rng_free(rng);
79 return 0;
80}
81