/**
   * 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) {
    int i = 0, j, k;

    for (j = 0; j < EvolvingSubsumptionForRobocode.numberOfEvents; j++) {
      eventPriority[j] = ((Integer) a_subject.getGene(i++).getAllele()).intValue();
    }
    for (j = 0; j < EvolvingSubsumptionForRobocode.numberOfBehaviours; j++) {
      behaviourOverwrite[j] = ((Integer) a_subject.getGene(i++).getAllele()).intValue() > 50;
    }
    for (j = 0; j < EvolvingSubsumptionForRobocode.numberOfBehaviours; j++) {
      for (k = 0; k < EvolvingSubsumptionForRobocode.behaviourSize; k++) {
        behaviourActions[j][k] = ((Integer) a_subject.getGene(i++).getAllele()).intValue();
      }
    }

    double tempFitness;
    double fitness = 0;
    for (j = 0; j < otherRobots.length; j++) {
      RobotSpecification[] tempRobots = new RobotSpecification[2];
      tempRobots[0] = evolvable;
      tempRobots[1] = otherRobots[j];
      battleSpecs = new BattleSpecification(1, new BattlefieldSpecification(800, 600), tempRobots);
      tempFitness = 0;
      System.out.println("Testing against " + otherRobots[j].getName() + "...");
      for (i = 0; i < EvolvingSubsumptionForRobocode.numberOfBattles; i++) {
        engine.runBattle(battleSpecs, true);
        tempFitness += battleObserver.getScoreRobot() / 500;
      }
      tempFitness /= EvolvingSubsumptionForRobocode.numberOfBattles;
      fitness += tempFitness;
    }
    fitness /= otherRobots.length;

    return Math.min(1.0d, fitness);
  }
  /**
   * 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");
  }
 /**
  * Retrieves the number of coins represented by the given potential solution at the given gene
  * position.
  *
  * @param a_potentialSolution the potential solution to evaluate
  * @param a_position the gene position to evaluate
  * @return the number of coins represented by the potential solution at the given gene position
  * @author Neil Rotstan
  * @since 1.0
  */
 public static int getNumberOfCoinsAtGene(IChromosome a_potentialSolution, int a_position) {
   Integer numCoins = (Integer) a_potentialSolution.getGene(a_position).getAllele();
   return numCoins.intValue();
 }