1 10 package examples.knapsack; 11 12 import org.jgap.*; 13 14 20 public class KnapsackFitnessFunction 21 extends FitnessFunction { 22 23 private final static String CVS_REVISION = "$Revision: 1.4 $"; 24 25 private final double m_knapsackVolume; 26 27 public static final double MAX_BOUND = 1000000000.0d; 28 29 private static final double ZERO_DIFFERENCE_FITNESS = Math.sqrt(MAX_BOUND); 30 31 public KnapsackFitnessFunction(double a_knapsackVolume) { 32 if (a_knapsackVolume < 1 || a_knapsackVolume >= MAX_BOUND) { 33 throw new IllegalArgumentException ( 34 "Knapsack volumen must be between 1 and " + MAX_BOUND + "."); 35 } 36 m_knapsackVolume = a_knapsackVolume; 37 } 38 39 51 public double evaluate(IChromosome a_subject) { 52 double totalVolume = getTotalVolume(a_subject); 63 int numberOfItems = getTotalNumberOfItems(a_subject); 64 double volumeDifference = Math.abs(m_knapsackVolume - totalVolume); 65 double fitness = 0.0d; 66 fitness += volumeDifferenceBonus(MAX_BOUND, volumeDifference); 77 fitness -= computeItemNumberPenalty(MAX_BOUND, numberOfItems); 84 return Math.max(1.0d, fitness); 87 } 88 89 98 protected double volumeDifferenceBonus(double a_maxFitness, 99 double a_volumeDifference) { 100 if (a_volumeDifference == 0) { 101 return a_maxFitness; 102 } 103 else { 104 return a_maxFitness / 2 - (a_volumeDifference * a_volumeDifference); 107 } 108 } 109 110 121 protected double computeItemNumberPenalty(double a_maxFitness, int a_items) { 122 if (a_items == 0) { 123 return 0; 126 } 127 else { 128 return (Math.min(a_maxFitness, a_items * a_items)); 133 } 134 } 135 136 147 public static double getTotalVolume(IChromosome a_potentialSolution) { 148 double volume = 0.0d; 149 for (int i = 0; i < a_potentialSolution.size(); i++) { 150 volume += getNumberOfItemsAtGene(a_potentialSolution, i) * 151 KnapsackMain.itemVolumes[i]; 152 } 153 return volume; 154 } 155 156 168 public static int getNumberOfItemsAtGene(IChromosome a_potentialSolution, 169 int a_position) { 170 Integer numItems = 171 (Integer ) a_potentialSolution.getGene(a_position).getAllele(); 172 return numItems.intValue(); 173 } 174 175 185 public static int getTotalNumberOfItems(IChromosome a_potentialSolution) { 186 int totalItems = 0; 187 int numberOfGenes = a_potentialSolution.size(); 188 for (int i = 0; i < numberOfGenes; i++) { 189 totalItems += getNumberOfItemsAtGene(a_potentialSolution, i); 190 } 191 return totalItems; 192 } 193 } 194 | Popular Tags |