/**
  * Operate on the given chromosome with the given mutation rate.
  *
  * @param a_chrom chromosome to operate
  * @param a_rate mutation rate
  * @param a_generator random generator to use (must not be null)
  * @return mutated chromosome of null if no mutation has occured.
  * @author Audrius Meskauskas
  * @author Florian Hafner
  * @since 3.3.2
  */
 protected IChromosome operate(
     final IChromosome a_chrom, final int a_rate, final RandomGenerator a_generator) {
   IChromosome chromosome = null;
   // ----------------------------------------
   for (int j = m_startOffset; j < a_chrom.size(); j++) {
     // Ensure probability of 1/currentRate for applying mutation.
     // ----------------------------------------------------------
     if (a_generator.nextInt(a_rate) == 0) {
       if (chromosome == null) {
         chromosome = (IChromosome) a_chrom.clone();
         // In case monitoring is active, support it.
         // -----------------------------------------
         if (m_monitorActive) {
           chromosome.setUniqueIDTemplate(a_chrom.getUniqueID(), 1);
         }
       }
       Gene[] genes = chromosome.getGenes();
       if (m_range == 0) {
         m_range = genes.length;
       }
       Gene[] mutated = operate(a_generator, j, genes);
       // setGenes is not required for this operator, but it may
       // be needed for the derived operators.
       // ------------------------------------------------------
       try {
         chromosome.setGenes(mutated);
       } catch (InvalidConfigurationException cex) {
         throw new Error("Gene type not allowed by constraint checker", cex);
       }
     }
   }
   return chromosome;
 }
 /**
  * Returns the total number of coins represented by all of the genes in the given potential
  * solution.
  *
  * @param a_potentialsolution the potential solution to evaluate
  * @return total number of coins represented by the given Chromosome
  * @author Neil Rotstan
  * @since 1.0
  */
 public static int getTotalNumberOfCoins(IChromosome a_potentialsolution) {
   int totalCoins = 0;
   int numberOfGenes = a_potentialsolution.size();
   for (int i = 0; i < numberOfGenes; i++) {
     totalCoins += getNumberOfCoinsAtGene(a_potentialsolution, i);
   }
   return totalCoins;
 }
 /**
  * Marshall a Chromosome instance to an XML Element representation, including its contained Genes
  * as sub-elements. This may be useful in scenarios where representation as an entire Document is
  * undesirable, such as when the representation of this Chromosome is to be combined with other
  * elements in a single Document.
  *
  * @param a_subject the chromosome 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 Chromosome
  * @author Neil Rotstan
  * @since 1.0
  * @deprecated use XMLDocumentBuilder instead
  */
 public static Element representChromosomeAsElement(
     final IChromosome a_subject, final Document a_xmlDocument) {
   // Start by creating an element for the chromosome and its size
   // attribute, which represents the number of genes in the chromosome.
   // ------------------------------------------------------------------
   Element chromosomeElement = a_xmlDocument.createElement(CHROMOSOME_TAG);
   chromosomeElement.setAttribute(SIZE_ATTRIBUTE, Integer.toString(a_subject.size()));
   // Next create the genes element with its nested gene elements,
   // which will contain string representations of the alleles.
   // --------------------------------------------------------------
   Element genesElement = representGenesAsElement(a_subject.getGenes(), a_xmlDocument);
   // Add the new genes element to the chromosome element and then
   // return the chromosome element.
   // -------------------------------------------------------------
   chromosomeElement.appendChild(genesElement);
   return chromosomeElement;
 }
  /**
   * 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");
  }
 /**
  * Compares the given Chromosome to this Chromosome. This chromosome is considered to be "less
  * than" the given chromosome if it has a fewer number of genes or if any of its gene values
  * (alleles) are less than their corresponding gene values in the other chromosome.
  *
  * @param other the Chromosome against which to compare this chromosome
  * @return a negative number if this chromosome is "less than" the given chromosome, zero if they
  *     are equal to each other, and a positive number if this chromosome is "greater than" the
  *     given chromosome
  * @author Neil Rotstan
  * @author Klaus Meffert
  * @since 1.0
  */
 public int compareTo(Object other) {
   // First, if the other Chromosome is null, then this chromosome is
   // automatically the "greater" Chromosome.
   // ---------------------------------------------------------------
   if (other == null) {
     return 1;
   }
   int size = size();
   IChromosome otherChromosome = (IChromosome) other;
   Gene[] otherGenes = otherChromosome.getGenes();
   // If the other Chromosome doesn't have the same number of genes,
   // then whichever has more is the "greater" Chromosome.
   // --------------------------------------------------------------
   if (otherChromosome.size() != size) {
     return size() - otherChromosome.size();
   }
   // Next, compare the gene values (alleles) for differences. If
   // one of the genes is not equal, then we return the result of its
   // comparison.
   // ---------------------------------------------------------------
   for (int i = 0; i < size; i++) {
     int comparison = getGene(i).compareTo(otherGenes[i]);
     if (comparison != 0) {
       return comparison;
     }
   }
   // Compare current fitness value.
   // ------------------------------
   if (m_fitnessValue != otherChromosome.getFitnessValueDirectly()) {
     FitnessEvaluator eval = getConfiguration().getFitnessEvaluator();
     if (eval != null) {
       if (eval.isFitter(m_fitnessValue, otherChromosome.getFitnessValueDirectly())) {
         return 1;
       } else {
         return -1;
       }
     } else {
       // undetermined order, but unequal!
       // --------------------------------
       return -1;
     }
   }
   if (m_compareAppData) {
     // Compare application data.
     // -------------------------
     if (getApplicationData() == null) {
       if (otherChromosome.getApplicationData() != null) {
         return -1;
       }
     } else if (otherChromosome.getApplicationData() == null) {
       return 1;
     } else {
       if (getApplicationData() instanceof Comparable) {
         try {
           return ((Comparable) getApplicationData())
               .compareTo(otherChromosome.getApplicationData());
         } catch (ClassCastException cex) {
           /** @todo improve */
           return -1;
         }
       } else {
         return getApplicationData()
             .getClass()
             .getName()
             .compareTo(otherChromosome.getApplicationData().getClass().getName());
       }
     }
   }
   // Everything is equal. Return zero.
   // ---------------------------------
   return 0;
 }