/** * Marshall a Genotype instance into an XML Element representation, including its population of * Chromosome instances as sub-elements. This may be useful in scenarios where representation as * an entire Document is undesirable, such as when the representation of this Genotype is to be * combined with other elements in a single Document. * * @param a_subject the genotype to represent as an XML element * @param a_xmlDocument a Document instance that will be used to create the Element instance. Note * that the element will NOT be added to the document by this method * @return an Element object representing the given Genotype * @author Neil Rotstan * @since 1.0 * @deprecated use XMLDocumentBuilder instead */ public static Element representGenotypeAsElement( final Genotype a_subject, final Document a_xmlDocument) { Population population = a_subject.getPopulation(); // Start by creating the genotype element and its size attribute, // which represents the number of chromosomes present in the // genotype. // -------------------------------------------------------------- Element genotypeTag = a_xmlDocument.createElement(GENOTYPE_TAG); genotypeTag.setAttribute(SIZE_ATTRIBUTE, Integer.toString(population.size())); // Next, add nested elements for each of the chromosomes in the // genotype. // ------------------------------------------------------------ for (int i = 0; i < population.size(); i++) { Element chromosomeElement = representChromosomeAsElement(population.getChromosome(i), a_xmlDocument); genotypeTag.appendChild(chromosomeElement); } return genotypeTag; }
/** * 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"); }
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()); } }