/** * @throws Exception * @author Klaus Meffert */ public void testGetPopulationSize_0() throws Exception { Configuration conf = new Configuration(); assertEquals(0, conf.getPopulationSize()); final int SIZE = 22; conf.setPopulationSize(SIZE); assertEquals(SIZE, conf.getPopulationSize()); }
/** * @throws Exception * @author Klaus Meffert */ public void testGetter_0() throws Exception { Configuration conf = new Configuration(); Genotype.setStaticConfiguration(conf); assertEquals(false, conf.isLocked()); FitnessFunction fitFunc = new StaticFitnessFunction(2); conf.setFitnessFunction(fitFunc); Gene gene = new BooleanGene(conf); Chromosome sample = new Chromosome(conf, gene, 55); conf.setSampleChromosome(sample); NaturalSelector natSel = new WeightedRouletteSelector(); conf.addNaturalSelector(natSel, false); RandomGenerator randGen = new StockRandomGenerator(); conf.setRandomGenerator(randGen); IEventManager evMan = new EventManager(); conf.setEventManager(evMan); GeneticOperator mutOp = new MutationOperator(conf); conf.addGeneticOperator(mutOp); GeneticOperator croOp = new CrossoverOperator(conf); conf.addGeneticOperator(croOp); conf.setPopulationSize(7); assertEquals(fitFunc, conf.getFitnessFunction()); assertEquals(natSel, conf.getNaturalSelectors(false).get(0)); assertEquals(randGen, conf.getRandomGenerator()); assertEquals(sample, conf.getSampleChromosome()); assertEquals(evMan, conf.getEventManager()); assertEquals(7, conf.getPopulationSize()); assertEquals(2, conf.getGeneticOperators().size()); assertEquals(mutOp, conf.getGeneticOperators().get(0)); assertEquals(croOp, conf.getGeneticOperators().get(1)); }
/** * @throws Exception * @author Klaus Meffert */ public void testSetPopulationSize_1() throws Exception { Configuration conf = new Configuration(); try { conf.setPopulationSize(0); fail(); } catch (InvalidConfigurationException invex) {; // this is OK } }
/** * Configuration with sample chromosome that has a gene with allele value null. * * @throws Exception * @author Klaus Meffert * @since 2.6 */ public void testVerifyStateIsValid_9() throws Exception { Configuration conf = new DefaultConfiguration(); conf.setFitnessFunction(new TestFitnessFunction()); BooleanGene gene = new BooleanGene(conf); gene.setAllele(null); Chromosome sample = new Chromosome(conf, gene, 55); conf.setSampleChromosome(sample); conf.setPopulationSize(5); conf.verifyStateIsValid(); }
/** * Configuration with sample chromosome that contains no genes. * * @throws Exception * @author Klaus Meffert * @since 2.6 */ public void testVerifyStateIsValid_8() throws Exception { Configuration conf = new DefaultConfiguration(); conf.setFitnessFunction(new TestFitnessFunction()); Chromosome sample = new Chromosome(conf); conf.setSampleChromosome(sample); conf.setPopulationSize(5); try { conf.verifyStateIsValid(); fail(); } catch (InvalidConfigurationException illex) {; // this is OK } }
/** * @throws Exception * @author Klaus Meffert */ public void testVerifyStateIsValid_6() throws Exception { Configuration conf = new Configuration(); assertEquals(false, conf.isLocked()); conf.setFitnessFunction(new StaticFitnessFunction(2)); Gene gene = new BooleanGene(conf); conf.setSampleChromosome(new Chromosome(conf, gene, 5)); conf.addNaturalSelector(new WeightedRouletteSelector(conf), true); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); conf.addGeneticOperator(new MutationOperator(conf)); conf.setPopulationSize(1); conf.verifyStateIsValid(); }
/** * @throws Exception * @author Klaus Meffert */ public void testVerifyStateIsValid_7() throws Exception { Configuration conf = new Configuration(); assertEquals(false, conf.isLocked()); conf.setFitnessFunction(new StaticFitnessFunction(2)); Gene gene = new BooleanGene(conf); conf.setSampleChromosome(new Chromosome(conf, gene, 5)); conf.addNaturalSelector(new WeightedRouletteSelector(conf), true); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.addGeneticOperator(new MutationOperator(conf)); conf.setPopulationSize(1); try { conf.verifyStateIsValid(); fail(); } catch (IllegalArgumentException illex) {; // this is OK } }
/** * Cloning multiple times in a row must be possible. * * @throws Exception * @author Klaus Meffert * @since 3.2 */ public void testClone_1() throws Exception { Configuration conf = new Configuration(); conf.setFitnessFunction(new StaticFitnessFunction(2)); Gene gene = new BooleanGene(conf); conf.setSampleChromosome(new Chromosome(conf, gene, 5)); conf.addNaturalSelector(new WeightedRouletteSelector(conf), true); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); conf.addGeneticOperator(new MutationOperator(conf)); conf.setPopulationSize(1); Configuration theClone1 = (Configuration) conf.clone(); Configuration theClone2 = (Configuration) conf.clone(); assertEquals(conf, theClone1); assertEquals(conf, theClone2); assertEquals(theClone1, theClone2); }
/** * Clone after settings locked. * * @throws Exception * @author Klaus Meffert * @since 3.2 */ public void testClone_2() throws Exception { Configuration conf = new Configuration(); conf.setFitnessFunction(new StaticFitnessFunction(2)); Gene gene = new BooleanGene(conf); conf.setSampleChromosome(new Chromosome(conf, gene, 5)); conf.addNaturalSelector(new WeightedRouletteSelector(conf), true); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); conf.addGeneticOperator(new MutationOperator(conf)); conf.addGeneticOperator(new CrossoverOperator(conf, 2)); conf.setPopulationSize(1); conf.lockSettings(); Configuration theClone = (Configuration) conf.clone(); assertEquals(conf, theClone); assertEquals(2, theClone.getGeneticOperators().size()); assertEquals(MutationOperator.class, theClone.getGeneticOperators().get(0).getClass()); assertEquals(CrossoverOperator.class, theClone.getGeneticOperators().get(1).getClass()); }
/** * @throws Exception * @author Klaus Meffert */ public void testLock_1() throws Exception { Configuration conf = new Configuration(); conf.setFitnessFunction(new TestFitnessFunction()); Gene gene = new BooleanGene(conf); Chromosome sample = new Chromosome(conf, gene, 55); conf.setSampleChromosome(sample); conf.addNaturalSelector(new WeightedRouletteSelector(conf), false); conf.setRandomGenerator(new GaussianRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); conf.addGeneticOperator(new MutationOperator(conf)); conf.setPopulationSize(1); conf.lockSettings(); assertEquals(true, conf.isLocked()); try { conf.verifyChangesAllowed(); fail(); } catch (InvalidConfigurationException invex) {; // this is OK } }
/** * Find and print the solution, return the solution error. * * @param a_conf the configuration to use * @return absolute difference between the required and computed change */ protected int solve( Configuration a_conf, int a_targetChangeAmount, SupergeneChangeFitnessFunction a_fitnessFunction, Gene[] a_sampleGenes) throws InvalidConfigurationException { IChromosome sampleChromosome = new Chromosome(a_conf, a_sampleGenes); a_conf.setSampleChromosome(sampleChromosome); // Finally, we need to tell the Configuration object how many // Chromosomes we want in our population. The more Chromosomes, // the larger number of potential solutions (which is good for // finding the answer), but the longer it will take to evolve // the population (which could be seen as bad). We'll just set // the population size to 500 here. // ------------------------------------------------------------ a_conf.setPopulationSize(POPULATION_SIZE); // Create random initial population of Chromosomes. // ------------------------------------------------ Genotype population = Genotype.randomInitialGenotype(a_conf); int s; Evolution: // Evolve the population, break if the the change solution is found. // ----------------------------------------------------------------- for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) { population.evolve(); s = Math.abs( a_fitnessFunction.amountOfChange(population.getFittestChromosome()) - a_targetChangeAmount); if (s == 0) { break Evolution; } } // Display the best solution we found. // ----------------------------------- IChromosome bestSolutionSoFar = report(a_fitnessFunction, population); return Math.abs(a_fitnessFunction.amountOfChange(bestSolutionSoFar) - a_targetChangeAmount); }
/** * Executes the genetic algorithm to determine the minimum number of items necessary to make up * the given target volume. The solution will then be written to the console. * * @param a_knapsackVolume the target volume for which this method is attempting to produce the * optimal list of items * @throws Exception * @author Klaus Meffert * @since 2.3 */ public static void findItemsForVolume(double a_knapsackVolume) throws Exception { // Start with a DefaultConfiguration, which comes setup with the // most common settings. // ------------------------------------------------------------- Configuration conf = new DefaultConfiguration(); conf.setPreservFittestIndividual(true); // Set the fitness function we want to use. We construct it with // the target volume passed in to this method. // --------------------------------------------------------- FitnessFunction myFunc = new KnapsackFitnessFunction(a_knapsackVolume); conf.setFitnessFunction(myFunc); // Now we need to tell the Configuration object how we want our // Chromosomes to be setup. We do that by actually creating a // sample Chromosome and then setting it on the Configuration // object. As mentioned earlier, we want our Chromosomes to each // have as many genes as there are different items available. We want the // values (alleles) of those genes to be integers, which represent // how many items of that type we have. We therefore use the // IntegerGene class to represent each of the genes. That class // also lets us specify a lower and upper bound, which we set // to senseful values (i.e. maximum possible) for each item type. // -------------------------------------------------------------- Gene[] sampleGenes = new Gene[itemVolumes.length]; for (int i = 0; i < itemVolumes.length; i++) { sampleGenes[i] = new IntegerGene(conf, 0, (int) Math.ceil(a_knapsackVolume / itemVolumes[i])); } IChromosome sampleChromosome = new Chromosome(conf, sampleGenes); conf.setSampleChromosome(sampleChromosome); // Finally, we need to tell the Configuration object how many // Chromosomes we want in our population. The more Chromosomes, // the larger number of potential solutions (which is good for // finding the answer), but the longer it will take to evolve // the population (which could be seen as bad). // ------------------------------------------------------------ conf.setPopulationSize(50); // Create random initial population of Chromosomes. // Here we try to read in a previous run via XMLManager.readFile(..) // for demonstration purpose! // ----------------------------------------------------------------- Genotype population; try { Document doc = XMLManager.readFile(new File("knapsackJGAP.xml")); population = XMLManager.getGenotypeFromDocument(conf, doc); } catch (FileNotFoundException fex) { population = Genotype.randomInitialGenotype(conf); } population = Genotype.randomInitialGenotype(conf); // Evolve the population. Since we don't know what the best answer // is going to be, we just evolve the max number of times. // --------------------------------------------------------------- for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) { population.evolve(); } // Save progress to file. A new run of this example will then be able to // resume where it stopped before! // --------------------------------------------------------------------- // represent Genotype as tree with elements Chromomes and Genes // ------------------------------------------------------------ DataTreeBuilder builder = DataTreeBuilder.getInstance(); IDataCreators doc2 = builder.representGenotypeAsDocument(population); // create XML document from generated tree // --------------------------------------- XMLDocumentBuilder docbuilder = new XMLDocumentBuilder(); Document xmlDoc = (Document) docbuilder.buildDocument(doc2); XMLManager.writeFile(xmlDoc, new File("knapsackJGAP.xml")); // Display the best solution we found. // ----------------------------------- IChromosome bestSolutionSoFar = population.getFittestChromosome(); System.out.println( "The best solution has a fitness value of " + bestSolutionSoFar.getFitnessValue()); System.out.println("It contained the following: "); int count; double totalVolume = 0.0d; for (int i = 0; i < bestSolutionSoFar.size(); i++) { count = ((Integer) bestSolutionSoFar.getGene(i).getAllele()).intValue(); if (count > 0) { System.out.println("\t " + count + " x " + itemNames[i]); totalVolume += itemVolumes[i] * count; } } System.out.println("\nFor a total volume of " + totalVolume + " ccm"); System.out.println("Expected volume was " + a_knapsackVolume + " ccm"); System.out.println("Volume difference is " + Math.abs(totalVolume - a_knapsackVolume) + " ccm"); }
/** * Executes the genetic algorithm to determine the minimum number of coins necessary to make up * the given target amount of change. The solution will then be written to System.out. * * @param a_targetChangeAmount the target amount of change for which this method is attempting to * produce the minimum number of coins * @param a_doMonitor true: turn on monitoring for later evaluation of evolution progress * @throws Exception * @author Neil Rotstan * @author Klaus Meffert * @since 1.0 */ public static void makeChangeForAmount(int a_targetChangeAmount, boolean a_doMonitor) throws Exception { // Start with a DefaultConfiguration, which comes setup with the // most common settings. // ------------------------------------------------------------- Configuration conf = new DefaultConfiguration(); // Care that the fittest individual of the current population is // always taken to the next generation. // Consider: With that, the pop. size may exceed its original // size by one sometimes! // ------------------------------------------------------------- conf.setPreservFittestIndividual(true); conf.setKeepPopulationSizeConstant(false); // Set the fitness function we want to use, which is our // MinimizingMakeChangeFitnessFunction. We construct it with // the target amount of change passed in to this method. // --------------------------------------------------------- FitnessFunction myFunc = new SampleFitnessFunction(a_targetChangeAmount); conf.setFitnessFunction(myFunc); if (a_doMonitor) { // Turn on monitoring/auditing of evolution progress. // -------------------------------------------------- m_monitor = new EvolutionMonitor(); conf.setMonitor(m_monitor); } // Now we need to tell the Configuration object how we want our // Chromosomes to be setup. We do that by actually creating a // sample Chromosome and then setting it on the Configuration // object. As mentioned earlier, we want our Chromosomes to each // have four genes, one for each of the coin types. We want the // values (alleles) of those genes to be integers, which represent // how many coins of that type we have. We therefore use the // IntegerGene class to represent each of the genes. That class // also lets us specify a lower and upper bound, which we set // to sensible values for each coin type. // -------------------------------------------------------------- Gene[] sampleGenes = new Gene[4]; sampleGenes[0] = new IntegerGene(conf, 0, 98); // Wasser sampleGenes[1] = new IntegerGene(conf, 0, 98); // Zucker sampleGenes[2] = new IntegerGene(conf, 0, 98); // Saft1 sampleGenes[3] = new IntegerGene(conf, 0, 98); // Saft2 IChromosome sampleChromosome = new Chromosome(conf, sampleGenes); conf.setSampleChromosome(sampleChromosome); // Finally, we need to tell the Configuration object how many // Chromosomes we want in our population. The more Chromosomes, // the larger number of potential solutions (which is good for // finding the answer), but the longer it will take to evolve // the population (which could be seen as bad). // ------------------------------------------------------------ conf.setPopulationSize(80); // Now we initialize the population randomly, anyway (as an example only)! // If you want to load previous results from file, remove the next line! // ----------------------------------------------------------------------- Genotype population = Genotype.randomInitialGenotype(conf); // Evolve the population. Since we don't know what the best answer // is going to be, we just evolve the max number of times. // --------------------------------------------------------------- long startTime = System.currentTimeMillis(); for (int i = 0; i < MAX_ALLOWED_EVOLUTIONS; i++) { if (!uniqueChromosomes(population.getPopulation())) { throw new RuntimeException("Invalid state in generation " + i); } if (m_monitor != null) { population.evolve(m_monitor); } else { population.evolve(); } } long endTime = System.currentTimeMillis(); System.out.println("Total evolution time: " + (endTime - startTime) + " ms"); // Save progress to file. A new run of this example will then be able to // resume where it stopped before! --> this is completely optional. // --------------------------------------------------------------------- // Display the best solution we found. // ----------------------------------- IChromosome bestSolutionSoFar = population.getFittestChromosome(); double v1 = bestSolutionSoFar.getFitnessValue(); System.out.println( "The best solution has a fitness value of " + bestSolutionSoFar.getFitnessValue()); bestSolutionSoFar.setFitnessValueDirectly(-1); System.out.println("It contains the following: "); System.out.println( "\t" + SampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 0) + " ml water."); System.out.println( "\t" + SampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 1) + " ml sugar."); System.out.println( "\t" + SampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 2) + " ml juice 1."); System.out.println( "\t" + SampleFitnessFunction.getNumberOfCoinsAtGene(bestSolutionSoFar, 3) + " ml juice 2."); System.out.println( "For a total of " + SampleFitnessFunction.amountOfChange(bestSolutionSoFar) + " ml."); }
public static void main(String[] args) throws InvalidConfigurationException { // Reading data from xml try { new InputData().readFromFile(XML_TEST_FILENAME); } catch (SAXException e) { System.out.println(e.getMessage()); } catch (IOException e) { System.out.println(e.getMessage()); } catch (ParserConfigurationException e) { System.out.println(e.getMessage()); } // Configuration conf = new DefaultConfiguration(); Configuration conf = new Configuration("myconf"); TimetableFitnessFunction fitnessFunction = new TimetableFitnessFunction(); InitialConstraintChecker timetableConstraintChecker = new InitialConstraintChecker(); // Creating genes Gene[] testGenes = new Gene[CHROMOSOME_SIZE]; for (int i = 0; i < CHROMOSOME_SIZE; i++) { testGenes[i] = new GroupClassTeacherLessonTimeSG( conf, new Gene[] { new GroupGene(conf, 1), new ClassGene(conf, 1), new TeacherGene(conf, 1), new LessonGene(conf, 1), new TimeGene(conf, 1) }); } System.out.println("=================================="); // Creating chromosome Chromosome testChromosome; testChromosome = new Chromosome(conf, testGenes); testChromosome.setConstraintChecker(timetableConstraintChecker); // Setup configuration conf.setSampleChromosome(testChromosome); conf.setPopulationSize(POPULATION_SIZE); conf.setFitnessFunction(fitnessFunction); // add fitness function BestChromosomesSelector myBestChromosomesSelector = new BestChromosomesSelector(conf); conf.addNaturalSelector(myBestChromosomesSelector, false); conf.setRandomGenerator(new StockRandomGenerator()); conf.setEventManager(new EventManager()); conf.setFitnessEvaluator(new DefaultFitnessEvaluator()); CrossoverOperator myCrossoverOperator = new CrossoverOperator(conf); conf.addGeneticOperator(myCrossoverOperator); TimetableMutationOperator myMutationOperator = new TimetableMutationOperator(conf); conf.addGeneticOperator(myMutationOperator); conf.setKeepPopulationSizeConstant(false); // Creating genotype // Population pop = new Population(conf, testChromosome); // Genotype population = new Genotype(conf, pop); Genotype population = Genotype.randomInitialGenotype(conf); System.out.println("Our Chromosome: \n " + testChromosome.getConfiguration().toString()); System.out.println("------------evolution-----------------------------"); // Begin evolution Calendar cal = Calendar.getInstance(); start_t = cal.getTimeInMillis(); for (int i = 0; i < MAX_EVOLUTIONS; i++) { System.out.println( "generation#: " + i + " population size:" + (Integer) population.getPopulation().size()); if (population.getFittestChromosome().getFitnessValue() >= THRESHOLD) break; population.evolve(); } cal = Calendar.getInstance(); finish_t = cal.getTimeInMillis(); System.out.println("--------------end of evolution--------------------"); Chromosome fittestChromosome = (Chromosome) population.getFittestChromosome(); System.out.println( "-------------The best chromosome---fitness=" + fittestChromosome.getFitnessValue() + "---"); System.out.println(" Group Class Time"); for (int i = 0; i < CHROMOSOME_SIZE; i++) { GroupClassTeacherLessonTimeSG s = (GroupClassTeacherLessonTimeSG) fittestChromosome.getGene(i); System.out.println( "Gene " + i + " contains: " + (Integer) s.geneAt(GROUP).getAllele() + " " + (Integer) s.geneAt(CLASS).getAllele() + " " + (Integer) s.geneAt(TEACHER).getAllele() + " " + (Integer) s.geneAt(LESSON).getAllele() + " " + (Integer) s.geneAt(TIME).getAllele()); // GroupGene gg = (GroupGene)s.geneAt(GROUP); // System.out.println("gg's idGroup"+gg.getAllele()+" gg.getGroupSize()"+ gg.getGroupSize() ); } System.out.println("Elapsed time:" + (double) (finish_t - start_t) / 1000 + "s"); // Display the best solution OutputData od = new OutputData(); od.printToConsole(fittestChromosome); // Write population to the disk try { od.printToFile(population, GENOTYPE_FILENAME, BEST_CHROMOSOME_FILENAME); } catch (IOException e) { System.out.println("IOException raised! " + e.getMessage()); } }