KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > examples > equalDistribution > MainClass


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.equalDistribution;
11
12 import java.util.*;
13 import org.jgap.*;
14 import org.jgap.impl.*;
15
16 /**
17  * Given 64 vents with different weights. Try to make 8 group with each
18  * groups having (nearly) the same weight as the other groups.<p>
19  * Here, each vent has a similar weight with a small deviation. But the
20  * deviation could also be significant (then, good solutions are harder to
21  * find).<p>
22  * The proposed way of solving this problem is quite easy in its structure.
23  * There is potential for optimzations!
24  *
25  * @author Klaus Meffert
26  * @since 3.2
27  */

28 public class MainClass {
29   /** String containing the CVS revision. Read out via reflection!*/
30   private final static String JavaDoc CVS_REVISION = "$Revision: 1.1 $";
31
32   /**
33    * Holds the available vents, each with a specific weight
34    */

35   private Vent[] m_vents;
36
37   private int m_numEvolutions;
38
39   /**
40    * Constructor.
41    *
42    * @throws Exception
43    *
44    * @author Klaus Meffert
45    * @since 3.2
46    */

47   public MainClass()
48       throws Exception JavaDoc {
49     makeVents();
50     Genotype genotype = configureJGAP();
51     doEvolution(genotype);
52   }
53
54   /**
55    * Sets up the configuration for the problem.
56    *
57    * @throws Exception
58    *
59    * @author Klaus Meffert
60    * @since 3.2
61    */

62   protected Genotype configureJGAP()
63       throws Exception JavaDoc {
64     m_numEvolutions = 50;
65     Configuration gaConf = new DefaultConfiguration();
66     gaConf.resetProperty(Configuration.PROPERTY_FITEVAL_INST);
67     gaConf.setFitnessEvaluator(new DeltaFitnessEvaluator());
68     // Just use a swapping operator instead of mutation and others.
69
// ------------------------------------------------------------
70
gaConf.getGeneticOperators().clear();
71     SwappingMutationOperator swapper = new SwappingMutationOperator(gaConf);
72     gaConf.addGeneticOperator(swapper);
73     // Setup some other parameters.
74
// ----------------------------
75
gaConf.setPreservFittestIndividual(true);
76     gaConf.setKeepPopulationSizeConstant(false);
77     // Set number of individuals (=tries) per generation.
78
// --------------------------------------------------
79
gaConf.setPopulationSize(50);
80     int chromeSize = m_vents.length;
81     Genotype genotype = null;
82     try {
83       // Setup the structure with which to evolve the
84
// solution of the problem.
85
// --------------------------------------------
86
IChromosome sampleChromosome = new Chromosome(gaConf,
87           new IntegerGene(gaConf), chromeSize);
88       gaConf.setSampleChromosome(sampleChromosome);
89       // Setup the important fitness function!
90
// -------------------------------------
91
gaConf.setFitnessFunction(new SampleFitnessFunction(m_vents));
92       //
93
genotype = Genotype.randomInitialGenotype(gaConf);
94       // Now ensure that each number from 1..64 (representing the
95
// indices of the vents) is represented by exactly one gene.
96
// --> Suboptimal here, as randomized initialization becomes
97
// obsolete (other solution would be more complicated).
98
// ---------------------------------------------------------
99
List chromosomes = genotype.getPopulation().getChromosomes();
100       for (int i = 0; i < chromosomes.size(); i++) {
101         IChromosome chrom = (IChromosome) chromosomes.get(i);
102         for (int j = 0; j < chrom.size(); j++) {
103           Gene gene = (Gene) chrom.getGene(j);
104           gene.setAllele(new Integer JavaDoc(j));
105         }
106       }
107     } catch (InvalidConfigurationException e) {
108       e.printStackTrace();
109       System.exit( -2);
110     }
111     return genotype;
112   }
113
114   /**
115    * Does the evolution until finished.
116    *
117    * @author Klaus Meffert
118    * @since 3.2
119    */

120   public void doEvolution(Genotype genotype) {
121     int progress = 0;
122     int percentEvolution = m_numEvolutions / 100;
123     for (int i = 0; i < m_numEvolutions; i++) {
124       genotype.evolve();
125       // Print progress.
126
// ---------------
127
if (percentEvolution > 0 && i % percentEvolution == 0) {
128         progress++;
129         IChromosome fittest = genotype.getFittestChromosome();
130         double fitness = fittest.getFitnessValue();
131         System.out.println("Currently best solution has fitness " +
132                            fitness);
133         printSolution(fittest);
134       }
135     }
136     // Print summary.
137
// --------------
138
IChromosome fittest = genotype.getFittestChromosome();
139     System.out.println("Best solution has fitness " +
140                        fittest.getFitnessValue());
141     printSolution(fittest);
142   }
143
144   /**
145    * @param a_solution a solution to print to the console
146    *
147    * @author Klaus Meffert
148    * @since 3.2
149    */

150   public void printSolution(IChromosome a_solution) {
151     double groupWeights = 0.0d;
152     for (int i = 0; i < 8; i++) {
153       System.out.println("\nGroup " + i);
154       System.out.println("-------");
155       double groupWeight = 0.0d;
156       for (int j = 0; j < 8; j++) {
157         IntegerGene ventIndex = (IntegerGene) a_solution.getGene( (i * 8 + j));
158         Vent vent = (Vent) m_vents[ventIndex.intValue()];
159         double weight = vent.getWeight();
160         groupWeight += weight;
161         System.out.println(" Vent at index "
162                            + ventIndex.intValue()
163                            + " with weight "
164                            + weight);
165       }
166       groupWeights += groupWeight;
167       System.out.println(" --> Group weight: " + groupWeight);
168     }
169     System.out.println("\n Average group weight: " + groupWeights / 8);
170   }
171
172   /**
173    * Create vents with different weights.
174    *
175    * @author Klaus Meffert
176    * @since 3.2
177    */

178   public void makeVents() {
179     m_vents = new Vent[64];
180     for (int i = 0; i < m_vents.length; i++) {
181       // Set a weight between 290 and 310
182
double weight = 290 + Math.random() * 20;
183       Vent vent = new Vent(weight);
184       m_vents[i] = vent;
185     }
186   }
187
188   /**
189    * Start the example
190    * @param args ignored
191    *
192    * @author Klaus Meffert
193    * @since 3.2
194    */

195   public static void main(String JavaDoc[] args) {
196     try {
197       new MainClass();
198     } catch (Throwable JavaDoc t) {
199       t.printStackTrace();
200       System.exit(1);
201     }
202   }
203 }
204
Popular Tags