jenes.tutorials.problem7.KnapsackLoggedProblem

001 /*
002  * JENES
003  * A time and memory efficient Java library for genetic algorithms and more 
004  * Copyright (C) 2011 Intelligentia srl
005  *
006  * This program is free software: you can redistribute it and/or modify
007  * it under the terms of the GNU General Public License as published by
008  * the Free Software Foundation, either version 3 of the License, or
009  * (at your option) any later version.
010  *
011  *  This program is distributed in the hope that it will be useful,
012  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
013  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014  *  GNU General Public License for more details.
015  *
016  *  You should have received a copy of the GNU General Public License
017  *  along with this program.  If not, see <http://www.gnu.org/licenses/>. 
018  */
019 package jenes.tutorials.problem7;
020 
021 import java.io.File;
022 import java.io.FileNotFoundException;
023 import java.io.IOException;
024 import jenes.GenerationEventListener;
025 import jenes.GeneticAlgorithm;
026 import jenes.chromosome.BooleanChromosome;
027 import jenes.utils.Random;
028 import jenes.population.Individual;
029 import jenes.population.Population;
030 import jenes.population.Population.Statistics;
031 import jenes.population.Population.Statistics.Group;
032 import jenes.tutorials.utils.Utils;
033 import jenes.utils.CSVLogger;
034 import jenes.statistics.StatisticsLogger;
035 import jenes.tutorials.problem6.KnapsackGA;
036 import jenes.utils.XLSLogger;
037 
038 /**
039  * A tutorial showing how to log statistics on different media.
040  *
041  @author Luigi Troiano
042  *
043  @version 1.3
044  *
045  @since 1.3
046  */
047 public class KnapsackLoggedProblem  {
048     
049     private static int POPSIZE=20;
050     private static int GENERATION_LIMIT=100;
051     
052     private static final double[] WEIGHTS = {1532864796};
053     private static final double[] UTILITIES = {7271642892};
054     
055     private KnapsackGA algorithm;
056     private double[] utilities;
057     private double[] weights;
058     
059     private StatisticsLogger csvlogger;
060     private StatisticsLogger xlslogge1;
061     private StatisticsLogger xlslogge2;
062     private XLSLogger xlslogge3;
063     private int exec;
064 
065     private final String FOLDER = "files.Tutorial7" + File.separatorChar;
066 
067     public KnapsackLoggedProblem(double[] utilities, double[] weightsthrows IOException {
068         algorithm = new KnapsackGA(POPSIZE, GENERATION_LIMIT, utilities, weights);
069         this.weights = weights;
070         this.utilities = utilities;
071 
072         csvlogger = new StatisticsLogger(
073                     new CSVLogger(new String[]{"LegalHighestScore","LegalScoreAvg","LegalScoreDev"}, FOLDER+"knapsackproblem.csv" ) );
074 
075         xlslogge1 = new StatisticsLogger(
076                     new XLSLogger(new String[]{"LegalHighestScore","LegalScoreAvg","LegalScoreDev"}, FOLDER+"knapsack1.log.xls" ) );
077 
078         xlslogge2 = new StatisticsLogger(
079                     new XLSLogger(new String[]{"LegalHighestScore""LegalScoreAvg" "IllegalScoreAvg"}, FOLDER+"knapsack2.log.xls", FOLDER+"knapsack.tpl.xls" ) );
080 
081         xlslogge3 = new XLSLogger(new String[]{"LegalHighestScore""LegalScoreAvg" "Run"}, FOLDER+"knapsack3.log.xls");
082 
083     }
084     
085     @SuppressWarnings("unchecked")
086     public void run() {
087         this.algorithm.evolve();
088         
089         Statistics stat=algorithm.getCurrentPopulation().getStatistics();
090         Individual solution=stat.getLegalHighestIndividual();
091         System.out.println(solution.getChromosome());
092         System.out.format("W: %f U: %f\n", algorithm.getWeightOf(solution), algorithm.getUtilityOf(solution) );
093     }
094     
095     public double getCapacity() {
096         return this.algorithm.getCapacity();
097     }
098     
099     public void setCapacity(double c) {
100         this.algorithm.setCapacity(c);
101     }
102     
103     public double[] getUtilities() {
104         return utilities;
105     }
106     
107     public double[] getWeights() {
108         return weights;
109     }
110     
111     public static KnapsackLoggedProblem build(int nthrows FileNotFoundException, IOException {
112         
113         Random r = Random.getInstance();
114         
115         double[] utilities = new double[n];
116         forint i = 0; i < n; ++i ) {
117             utilities[i= r.nextInt(10);
118         }
119         
120         double[] weights = new double[n];
121         forint i = 0; i < n; ++i ) {
122             weights[i= r.nextInt(10);
123         }
124         
125         return new KnapsackLoggedProblem(utilities, weights);
126     }
127     
128     public static void main(String[] argsthrows FileNotFoundException, IOException {
129         
130         Utils.printHeader();
131         System.out.println();
132         
133         System.out.println("TUTORIAL 7:");
134         System.out.println("Logging the Knapsack Problem.");
135         System.out.println();
136         
137         final KnapsackLoggedProblem prb = KnapsackLoggedProblem.build(20);
138 
139         System.out.println("Utilities: " + toString(prb.getUtilities()) );
140         System.out.println("  Weights: " + toString(prb.getWeights()) );
141         System.out.println();
142 
143         GenerationEventListener<BooleanChromosome> logger1 = new GenerationEventListener<BooleanChromosome>() {
144 
145             public void onGeneration(GeneticAlgorithm ga, long time) {
146                 Population.Statistics stats = ga.getCurrentPopulation().getStatistics();
147                 
148                 prb.csvlogger.record(stats);
149                 prb.xlslogge1.record(stats);
150                 prb.xlslogge2.record(stats);
151 
152             }
153 
154         };
155 
156         prb.algorithm.addGenerationEventListener(logger1);
157 
158 
159         System.out.println("50 random elements, capacity 50");
160         prb.setCapacity(50);
161         prb.run();
162         System.out.println();
163 
164         System.out.println("Saving the logs ...");
165         prb.csvlogger.close();
166         prb.xlslogge1.close();
167         prb.xlslogge2.close();
168         System.out.println("Done.");
169 
170         prb.algorithm.removeGenerationEventListener(logger1);
171 
172         GenerationEventListener<BooleanChromosome> logger2 = new GenerationEventListener<BooleanChromosome>() {
173             public void onGeneration(GeneticAlgorithm ga, long time) {
174                 Population.Statistics stats = ga.getCurrentPopulation().getStatistics();
175 
176                 Group legals = stats.getGroup(Population.LEGALS);
177                 
178                 prb.xlslogge3.put("LegalHighestScore", legals.getMax());
179                 prb.xlslogge3.put("LegalScoreAvg", legals.getMin());
180                 prb.xlslogge3.put("Run", prb.exec);
181 
182                 prb.xlslogge3.log();
183             }
184 
185         };
186 
187         prb.algorithm.addGenerationEventListener(logger2);
188 
189         System.out.println();
190         System.out.println("Repeating 10 times: 20 random elements, capacity 50");
191         forprb.exec = 0; prb.exec < 10; ++prb.exec) {
192              System.out.println((prb.exec+1" of 10");
193              prb.run();
194         }
195         prb.xlslogge3.close();
196         System.out.println("Done.");
197     }
198     
199     private static String toString(double[] values) {
200         String s = "[";
201         for(int i = 0; i < values.length; ++i ){
202             s += values[i](i < values.length-" " "]");
203         }
204         return s;
205     }
206     
207 }