jenes.tutorials.old.problem7.KnapsackLoggedProblem.java

001 /*
002  * JENES
003  * A time asnd 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.old.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.tutorials.utils.Utils;
032 import jenes.utils.CSVLogger;
033 import jenes.statistics.StatisticsLogger;
034 import jenes.tutorials.old.problem6.KnapsackGA;
035 import jenes.utils.XLSLogger;
036 
037 /**
038  * A tutorial showing how to log statistics on different media.
039  *
040  @author Luigi Troiano
041  *
042  @version 1.3
043  *
044  @since 1.3
045  */
046 public class KnapsackLoggedProblem  {
047     
048     private static int POPSIZE=20;
049     private static int GENERATION_LIMIT=100;
050     
051     private static final double[] WEIGHTS = {1532864796};
052     private static final double[] UTILITIES = {7271642892};
053     
054     private KnapsackGA algorithm;
055     private double[] utilities;
056     private double[] weights;
057     
058     private StatisticsLogger csvlogger;
059     private StatisticsLogger xlslogge1;
060     private StatisticsLogger xlslogge2;
061     private XLSLogger xlslogge3;
062     private int exec;
063 
064     private final String FOLDER = "files.Tutorial7" + File.separatorChar;
065 
066     public KnapsackLoggedProblem(double[] utilities, double[] weightsthrows IOException {
067         algorithm = new KnapsackGA(POPSIZE, GENERATION_LIMIT, utilities, weights);
068         this.weights = weights;
069         this.utilities = utilities;
070 
071         csvlogger = new StatisticsLogger(
072                     new CSVLogger(new String[]{"LegalHighestScore","LegalScoreAvg","LegalScoreDev"}, FOLDER+"knapsackproblem.csv" ) );
073 
074         xlslogge1 = new StatisticsLogger(
075                     new XLSLogger(new String[]{"LegalHighestScore","LegalScoreAvg","LegalScoreDev"}, FOLDER+"knapsack1.log.xls" ) );
076 
077         xlslogge2 = new StatisticsLogger(
078                     new XLSLogger(new String[]{"LegalHighestScore""LegalScoreAvg" "IllegalScoreAvg"}, FOLDER+"knapsack2.log.xls", FOLDER+"knapsack.tpl.xls" ) );
079 
080         xlslogge3 = new XLSLogger(new String[]{"LegalHighestScore""LegalScoreAvg" "Run"}, FOLDER+"knapsack3.log.xls");
081 
082     }
083     
084     @SuppressWarnings("unchecked")
085     public void run() {
086         this.algorithm.evolve();
087         
088         Statistics stat=algorithm.getCurrentPopulation().getStatistics();
089         Individual solution=stat.getLegalHighestIndividual();
090         System.out.println(solution.getChromosome());
091         System.out.format("W: %f U: %f\n", algorithm.getWeightOf(solution), algorithm.getUtilityOf(solution) );
092     }
093     
094     public double getCapacity() {
095         return this.algorithm.getCapacity();
096     }
097     
098     public void setCapacity(double c) {
099         this.algorithm.setCapacity(c);
100     }
101     
102     public double[] getUtilities() {
103         return utilities;
104     }
105     
106     public double[] getWeights() {
107         return weights;
108     }
109     
110     public static KnapsackLoggedProblem build(int nthrows FileNotFoundException, IOException {
111         
112         Random r = Random.getInstance();
113         
114         double[] utilities = new double[n];
115         forint i = 0; i < n; ++i ) {
116             utilities[i= r.nextInt(10);
117         }
118         
119         double[] weights = new double[n];
120         forint i = 0; i < n; ++i ) {
121             weights[i= r.nextInt(10);
122         }
123         
124         return new KnapsackLoggedProblem(utilities, weights);
125     }
126     
127     public static void main(String[] argsthrows FileNotFoundException, IOException {
128         
129         Utils.printHeader();
130         System.out.println();
131         
132         System.out.println("TUTORIAL 7:");
133         System.out.println("Logging the Knapsack Problem.");
134         System.out.println();
135         
136         final KnapsackLoggedProblem prb = KnapsackLoggedProblem.build(20);
137 
138         System.out.println("Utilities: " + toString(prb.getUtilities()) );
139         System.out.println("  Weights: " + toString(prb.getWeights()) );
140         System.out.println();
141 
142         GenerationEventListener<BooleanChromosome> logger1 = new GenerationEventListener<BooleanChromosome>() {
143 
144             public void onGeneration(GeneticAlgorithm ga, long time) {
145                 Population.Statistics stats = ga.getCurrentPopulation().getStatistics();
146                 
147                 prb.csvlogger.record(stats);
148                 prb.xlslogge1.record(stats);
149                 prb.xlslogge2.record(stats);
150 
151             }
152 
153         };
154 
155         prb.algorithm.addGenerationEventListener(logger1);
156 
157 
158         System.out.println("50 random elements, capacity 50");
159         prb.setCapacity(50);
160         prb.run();
161         System.out.println();
162 
163         System.out.println("Saving the logs ...");
164         prb.csvlogger.close();
165         prb.xlslogge1.close();
166         prb.xlslogge2.close();
167         System.out.println("Done.");
168 
169         prb.algorithm.removeGenerationEventListener(logger1);
170 
171         GenerationEventListener<BooleanChromosome> logger2 = new GenerationEventListener<BooleanChromosome>() {
172             public void onGeneration(GeneticAlgorithm ga, long time) {
173                 Population.Statistics stats = ga.getCurrentPopulation().getStatistics();
174 
175                 prb.xlslogge3.put("LegalHighestScore", stats.getLegalHighestScore());
176                 prb.xlslogge3.put("LegalScoreAvg", stats.getLegalScoreAvg());
177                 prb.xlslogge3.put("Run", prb.exec);
178 
179                 prb.xlslogge3.log();
180             }
181 
182         };
183 
184         prb.algorithm.addGenerationEventListener(logger2);
185 
186         System.out.println();
187         System.out.println("Repeating 10 times: 20 random elements, capacity 50");
188         forprb.exec = 0; prb.exec < 10; ++prb.exec) {
189              System.out.println((prb.exec+1" of 10");
190              prb.run();
191         }
192         prb.xlslogge3.close();
193         System.out.println("Done.");
194     }
195     
196     private static String toString(double[] values) {
197         String s = "[";
198         for(int i = 0; i < values.length; ++i ){
199             s += values[i](i < values.length-" " "]");
200         }
201         return s;
202     }
203     
204 }