KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > examples > audit > CoinsExample


1 /*
2  * This file is part of JGAP.
3  *
4  * JGAP offers a dual license model containing the LGPL as well as the MPL.
5  *
6  * For licencing information please see the file license.txt included with JGAP
7  * or have a look at the top of class org.jgap.Chromosome which representatively
8  * includes the JGAP license policy applicable for any file delivered with JGAP.
9  */

10 package examples.audit;
11
12 //Uncomment imports and code below to use JFreeChart functionality
13
//import java.io.*;
14
//import java.awt.image.*;
15

16 //import org.jfree.chart.*;
17
//import org.jfree.chart.plot.*;
18
//import org.jfree.data.category.*;
19
import org.jgap.*;
20 import org.jgap.impl.*;
21 import org.jgap.audit.*;
22
23 /**
24  * Same logic as in MinimizingMakeChange except that we are using the new
25  * audit capabilities provided by JGAP 2.2
26  *
27  * @author Klaus Meffert
28  * @since 2.2
29  */

30 public class CoinsExample {
31   /** String containing the CVS revision. Read out via reflection!*/
32   private final static String JavaDoc CVS_REVISION = "$Revision: 1.22 $";
33
34   /**
35    * The total number of times we'll let the population evolve.
36    */

37   private static final int MAX_ALLOWED_EVOLUTIONS = 80;
38
39   /**
40    * Executes the genetic algorithm to determine the minimum number of
41    * coins necessary to make up the given target amount of change. The
42    * solution will then be written to System.out.
43    *
44    * @param a_targetChangeAmount the target amount of change for which this
45    * method is attempting to produce the minimum number of coins
46    * @throws Exception
47    *
48    * @author Neil Rotstan
49    * @author Klaus Meffert
50    * @since 1.0
51    */

52   public static void makeChangeForAmount(int a_targetChangeAmount)
53       throws Exception JavaDoc {
54     // Start with a DefaultConfiguration, which comes setup with the
55
// most common settings.
56
// -------------------------------------------------------------
57
Configuration conf = new DefaultConfiguration();
58     conf.setPreservFittestIndividual(true);
59     // Set the fitness function we want to use, which is our
60
// MinimizingMakeChangeFitnessFunction. We construct it with
61
// the target amount of change passed in to this method.
62
// ---------------------------------------------------------
63
FitnessFunction myFunc =
64         new CoinsExampleFitnessFunction(a_targetChangeAmount);
65     conf.setFitnessFunction(myFunc);
66     // Now we need to tell the Configuration object how we want our
67
// Chromosomes to be setup. We do that by actually creating a
68
// sample Chromosome and then setting it on the Configuration
69
// object. As mentioned earlier, we want our Chromosomes to each
70
// have four genes, one for each of the coin types. We want the
71
// values (alleles) of those genes to be integers, which represent
72
// how many coins of that type we have. We therefore use the
73
// IntegerGene class to represent each of the genes. That class
74
// also lets us specify a lower and upper bound, which we set
75
// to sensible values for each coin type.
76
// --------------------------------------------------------------
77
Gene[] sampleGenes = new Gene[4];
78     sampleGenes[0] = new IntegerGene(conf, 0, 3 * 10); // Quarters
79
sampleGenes[1] = new IntegerGene(conf, 0, 2 * 10); // Dimes
80
sampleGenes[2] = new IntegerGene(conf, 0, 1 * 10); // Nickels
81
sampleGenes[3] = new IntegerGene(conf, 0, 4 * 10); // Pennies
82
Chromosome sampleChromosome = new Chromosome(conf, sampleGenes);
83     conf.setSampleChromosome(sampleChromosome);
84     // Finally, we need to tell the Configuration object how many
85
// Chromosomes we want in our population. The more Chromosomes,
86
// the larger number of potential solutions (which is good for
87
// finding the answer), but the longer it will take to evolve
88
// the population (which could be seen as bad).
89
// ------------------------------------------------------------
90
conf.setPopulationSize(50);
91     // Added here for demonstrating purposes is a permuting configuration.
92
// It allows for evaluating which configuration could work best for
93
// the given problem.
94
// -------------------------------------------------------------------
95
PermutingConfiguration pconf = new PermutingConfiguration(conf);
96     pconf.addGeneticOperatorSlot(new CrossoverOperator(conf));
97     pconf.addGeneticOperatorSlot(new MutationOperator(conf));
98     pconf.addNaturalSelectorSlot(new BestChromosomesSelector(conf));
99     pconf.addNaturalSelectorSlot(new WeightedRouletteSelector(conf));
100     pconf.addRandomGeneratorSlot(new StockRandomGenerator());
101     RandomGeneratorForTest rn = new RandomGeneratorForTest();
102     rn.setNextDouble(0.7d);
103     rn.setNextInt(2);
104     pconf.addRandomGeneratorSlot(rn);
105     pconf.addRandomGeneratorSlot(new GaussianRandomGenerator());
106     pconf.addFitnessFunctionSlot(new CoinsExampleFitnessFunction(
107         a_targetChangeAmount));
108     Evaluator eval = new Evaluator(pconf);
109     /**@todo class Evaluator:
110      * input:
111      * + PermutingConfiguration
112      * + Number of evaluation runs pers config (to turn off randomness
113      * as much as possible)
114      * + output facility (data container)
115      * + optional: event subscribers
116      * output:
117      * + averaged curve of fitness value thru all generations
118      * + best fitness value accomplished
119      * + average number of performance improvements for all generations
120      */

121     int permutation = 0;
122     while (eval.hasNext()) {
123       // Create random initial population of Chromosomes.
124
// ------------------------------------------------
125
Genotype population = Genotype.randomInitialGenotype(eval.next());
126       for (int run = 0; run < 10; run++) {
127         // Evolve the population. Since we don't know what the best answer
128
// is going to be, we just evolve the max number of times.
129
// ---------------------------------------------------------------
130
for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) {
131           population.evolve();
132           // add current best fitness to chart
133
double fitness = population.getFittestChromosome().getFitnessValue();
134           if (i % 3 == 0) {
135             String JavaDoc s = String.valueOf(i);
136 // Number n = eval.getValue("Fitness " + permutation, s);
137
// double d;
138
// if (n != null) {
139
// // calculate historical average
140
// d = n.doubleValue() + fitness/(run+1);
141
// }
142
// else {
143
// d = fitness;
144
// }
145
eval.setValue(permutation, run, fitness, "" + permutation, s);
146             eval.storeGenotype(permutation, run, population);
147 // eval.setValue(permutation,run,fitness, new Integer(0), s);
148
}
149         }
150       }
151       // Display the best solution we found.
152
// -----------------------------------
153
IChromosome bestSolutionSoFar = population.getFittestChromosome();
154       System.out.println("The best solution has a fitness value of " +
155                          bestSolutionSoFar.getFitnessValue());
156       System.out.println("It contained the following: ");
157       System.out.println("\t" +
158                          CoinsExampleFitnessFunction.
159                          getNumberOfCoinsAtGene(
160           bestSolutionSoFar, 0) + " quarters.");
161       System.out.println("\t" +
162                          CoinsExampleFitnessFunction.
163                          getNumberOfCoinsAtGene(
164           bestSolutionSoFar, 1) + " dimes.");
165       System.out.println("\t" +
166                          CoinsExampleFitnessFunction.
167                          getNumberOfCoinsAtGene(
168           bestSolutionSoFar, 2) + " nickels.");
169       System.out.println("\t" +
170                          CoinsExampleFitnessFunction.
171                          getNumberOfCoinsAtGene(
172           bestSolutionSoFar, 3) + " pennies.");
173       System.out.println("For a total of " +
174                          CoinsExampleFitnessFunction.amountOfChange(
175           bestSolutionSoFar) + " cents in " +
176                          CoinsExampleFitnessFunction.
177                          getTotalNumberOfCoins(
178           bestSolutionSoFar) + " coins.");
179       permutation++;
180     }
181     // Create chart: fitness values average over all permutations.
182
// -----------------------------------------------------------
183

184     // construct JFreeChart Dataset.
185
// -----------------------------
186
// DefaultKeyedValues2D myDataset = eval.calcAvgFitness(-1);//eval.getData();
187
// DefaultCategoryDataset dataset = new DefaultCategoryDataset();
188
// for (int ii=0;ii<myDataset.getColumnCount();ii++) {
189
// for (int jj=0;jj<myDataset.getRowCount();jj++) {
190
// dataset.setValue(myDataset.getValue(myDataset.getRowKey(jj),
191
// myDataset.getColumnKey(ii)),
192
// "Perm "+myDataset.getRowKey(jj), myDataset.getColumnKey(ii));
193
// }
194
// }
195

196 // PlotOrientation or = PlotOrientation.VERTICAL;
197
// JFreeChart chart = ChartFactory.createLineChart(
198
// "JGAP: Evolution progress",
199
// "Evolution cycle", "Fitness value", dataset, or, true /*legend*/,
200
// true
201
// /*tooltips*/
202
// , false /*urls*/);
203
// BufferedImage image = chart.createBufferedImage(640, 480);
204
// FileOutputStream fo = new FileOutputStream("c:\\JGAP_chart_fitness_values.jpg");
205
// ChartUtilities.writeBufferedImageAsJPEG(fo, 0.7f, image);
206

207     // Performance metrics for each single permutation.
208
// ------------------------------------------------
209
int maxPerm = permutation - 1;
210     double avgBestFitness = 0.0d;
211     int avgBestGen = 0;
212     double avgAvgFitness = 0.0d;
213     double avgAvgDiv = 0.0d;
214     double avgAvgBestD = 0.0d;
215     for (int i = 0; i < maxPerm; i++) {
216 // myDataset = eval.calcAvgFitness(i);
217
Evaluator.GenotypeDataAvg dataAvg = eval.calcPerformance(i);
218       System.err.println("-----------------------------");
219       System.err.println("Perm " + i);
220       System.err.println("Best Fitness " + dataAvg.bestFitnessValue);
221       System.err.println(" Generation " + dataAvg.bestFitnessValueGeneration);
222       System.err.println(" BestFit/Gen " +
223                          dataAvg.bestFitnessValue / dataAvg.bestFitnessValueGeneration);
224       System.err.println("Avg. Fitness " + dataAvg.avgFitnessValue);
225       System.err.println("Avg. Div. " + dataAvg.avgDiversityFitnessValue);
226       System.err.println("Avg. BestD " + dataAvg.avgBestDeltaFitnessValue);
227       avgBestFitness += dataAvg.bestFitnessValue;
228       avgBestGen += dataAvg.bestFitnessValueGeneration;
229       avgAvgFitness += dataAvg.avgFitnessValue;
230       avgAvgDiv += dataAvg.avgDiversityFitnessValue;
231       avgAvgBestD += dataAvg.avgBestDeltaFitnessValue;
232     }
233     // Performance metrics for all permutations.
234
// -----------------------------------------
235
System.err.println("\nOverall Statistics for all permutations");
236     System.err.println("----------------------------------------");
237     System.err.println("Avg. Best Fitness " + avgBestFitness / maxPerm);
238     System.err.println("Avg. Best Generation " + avgBestGen / maxPerm);
239     System.err.println("Avg. Avg. Fitness " + avgAvgFitness / maxPerm);
240     System.err.println("Avg. Avg. Diversity " + avgAvgDiv / maxPerm);
241     System.err.println("Avg. Avg. BestD " + avgAvgBestD / maxPerm);
242     // Create chart: performance metrics for all permutations.
243
// -----------------------------------------------------------
244

245 // dataset = new DefaultCategoryDataset();
246
// for (int ii=0;ii<myDataset.getColumnCount();ii++) {
247
// for (int jj=0;jj<myDataset.getRowCount();jj++) {
248
// dataset.setValue(myDataset.getValue(myDataset.getRowKey(jj),
249
// myDataset.getColumnKey(ii)),
250
// myDataset.getRowKey(jj), myDataset.getColumnKey(ii));
251
// }
252
// }
253
//
254
// chart = ChartFactory.createLineChart(
255
// "JGAP: Evolution progress",
256
// "Evolution cycle", "Fitness value", dataset, or, true /*legend*/,
257
// true
258
// /*tooltips*/
259
// , false /*urls*/);
260
// image = chart.createBufferedImage(640, 480);
261
// fo = new FileOutputStream("c:\\JGAP_chart_fitness_values_1.jpg");
262
// ChartUtilities.writeBufferedImageAsJPEG(fo, 0.7f, image);
263
}
264
265   public static void main(String JavaDoc[] args) {
266     if (args.length != 1) {
267       System.out.println("Syntax: CoinsExample <amount>");
268     }
269     else {
270       try {
271         int amount = Integer.parseInt(args[0]);
272         if (amount < 1 ||
273             amount >= CoinsExampleFitnessFunction.MAX_BOUND) {
274           System.out.println("The <amount> argument must be between 1 and "
275                              +
276                              (CoinsExampleFitnessFunction.MAX_BOUND - 1)
277                              + ".");
278         }
279         else {
280           try {
281             makeChangeForAmount(amount);
282           }
283           catch (Exception JavaDoc e) {
284             e.printStackTrace();
285           }
286         }
287       }
288       catch (NumberFormatException JavaDoc e) {
289         System.out.println(
290             "The <amount> argument must be a valid integer value");
291       }
292     }
293   }
294 }
295
Popular Tags