1 10 package examples.config; 11 12 import org.jgap.*; 13 import org.jgap.data.config.*; 14 import org.jgap.event.*; 15 import org.jgap.impl.*; 16 17 28 public class MaximizingFunction { 29 30 private final static String CVS_REVISION = "$Revision: 1.7 $"; 31 32 37 public MaximizingFunction() { 38 } 39 40 48 public static void main(String args[]) throws Exception { 49 Configuration conf; 50 try { 51 conf = new Configuration("jgapTest.con", false); 52 } 53 catch (Exception ex) { 54 ex.printStackTrace(); 55 return; 56 } 57 Gene[] sampleGenes = new Gene[3]; 59 sampleGenes[0] = new IntegerGene(conf, 60, 100); 60 sampleGenes[1] = new IntegerGene(conf, 1, 50); 61 sampleGenes[2] = new IntegerGene(conf, 100, 150); 62 IChromosome sampleChromosome = new Chromosome(conf, sampleGenes); 63 Genotype population; 64 FitnessFunction fitFunc = new MaximizingFunctionFitnessFunction(); 65 try { 66 conf.setFitnessFunction(fitFunc); 67 conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); 69 conf.setSampleChromosome(sampleChromosome); 70 BestChromosomesSelector bestChromsSelector = new 71 BestChromosomesSelector(conf, 1.0d); 72 bestChromsSelector.setDoubletteChromosomesAllowed(false); 73 conf.addNaturalSelector(bestChromsSelector, true); 74 conf.setRandomGenerator(new StockRandomGenerator()); 75 conf.setEventManager(new EventManager()); 76 conf.addGeneticOperator(new CrossoverOperator(conf)); 77 conf.addGeneticOperator(new MutationOperator(conf, 15)); 78 population = Genotype.randomInitialGenotype(conf); 79 } 80 catch (InvalidConfigurationException icEx) { 81 icEx.printStackTrace(); 82 return; 83 } 84 87 for (int i = 0; i < 10; i++) { 89 population.evolve(); 90 } 91 IChromosome bestSolutionSoFar = population.getFittestChromosome(); 92 System.out.println("The best solution has a fitness value of " + 93 bestSolutionSoFar.getFitnessValue()); 94 Integer aVal = (Integer ) bestSolutionSoFar.getGene(0).getAllele(); 95 Integer bVal = (Integer ) bestSolutionSoFar.getGene(1).getAllele(); 96 Integer cVal = (Integer ) bestSolutionSoFar.getGene(2).getAllele(); 97 System.out.println("a = " + aVal.intValue()); 98 System.out.println("b = " + bVal.intValue()); 99 System.out.println("c = " + cVal.intValue()); 100 } 101 } 102 | Popular Tags |