private double computeFitness(IGPProgram a_program, Variable vx) { double error = 0.0f; Object[] noargs = new Object[0]; // Initialize local stores. // ------------------------ a_program.getGPConfiguration().clearStack(); a_program.getGPConfiguration().clearMemory(); // Compute fitness for each program. // --------------------------------- for (int i = 2; i < 15; i++) { for (int j = 0; j < a_program.size(); j++) { vx.set(new Integer(i)); try { try { // Only evaluate after whole GP program was run. // --------------------------------------------- if (j == a_program.size() - 1) { double result = a_program.execute_int(j, noargs); error += Math.abs(result - fib_iter(i)); } else { a_program.execute_void(j, noargs); } } catch (IllegalStateException iex) { error = Double.MAX_VALUE / 2; break; } } catch (ArithmeticException ex) { System.out.println("Arithmetic Exception with x = " + i); System.out.println(a_program.getChromosome(j)); throw ex; } } } return error; }
/** * Determine the fitness of the given Chromosome instance. The higher the return value, the more * fit the instance. This method should always return the same fitness value for two equivalent * Chromosome instances. * * @param a_subject the Chromosome instance to evaluate * @return positive double reflecting the fitness rating of the given Chromosome * @since 2.0 (until 1.1: return type int) * @author Neil Rotstan, Klaus Meffert, John Serri */ public double evaluate(IChromosome a_subject) { // Take care of the fitness evaluator. It could either be weighting higher // fitness values higher (e.g.DefaultFitnessEvaluator). Or it could weight // lower fitness values higher, because the fitness value is seen as a // defect rate (e.g. DeltaFitnessEvaluator) boolean defaultComparation = a_subject.getConfiguration().getFitnessEvaluator().isFitter(2, 1); // The fitness value measures both how close the value is to the // target amount supplied by the user and the total number of coins // represented by the solution. We do this in two steps: first, // we consider only the represented amount of change vs. the target // amount of change and return higher fitness values for amounts // closer to the target, and lower fitness values for amounts further // away from the target. Then we go to step 2, which returns a higher // fitness value for solutions representing fewer total coins, and // lower fitness values for solutions representing more total coins. // ------------------------------------------------------------------ int changeAmount = amountOfChange(a_subject); int totalCoins = getTotalNumberOfCoins(a_subject); int changeDifference = Math.abs(m_targetAmount - changeAmount); double fitness; if (defaultComparation) { fitness = 0.0d; } else { fitness = MAX_BOUND / 2; } // Step 1: Determine distance of amount represented by solution from // the target amount. If the change difference is greater than zero we // will divide one by the difference in change between the // solution amount and the target amount. That will give the desired // effect of returning higher values for amounts closer to the target // amount and lower values for amounts further away from the target // amount. // In the case where the change difference is zero it means that we have // the correct amount and we assign a higher fitness value. // --------------------------------------------------------------------- if (defaultComparation) { fitness += changeDifferenceBonus(MAX_BOUND / 2, changeDifference); } else { fitness -= changeDifferenceBonus(MAX_BOUND / 2, changeDifference); } // Step 2: We divide the fitness value by a penalty based on the number of // coins. The higher the number of coins the higher the penalty and the // smaller the fitness value. // And inversely the smaller number of coins in the solution the higher // the resulting fitness value. // ----------------------------------------------------------------------- if (defaultComparation) { fitness -= computeCoinNumberPenalty(MAX_BOUND / 2, totalCoins); } else { fitness += computeCoinNumberPenalty(MAX_BOUND / 2, totalCoins); } // Make sure fitness value is always positive. // ------------------------------------------- return Math.max(1.0d, fitness); }
/** * 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"); }