예제 #1
0
 /**
  * Test the method, returns the sum of all differences between the required and obtained excange
  * amount. One exception counts as 1000 on the error score.
  */
 public int test() {
   int s = 0;
   int e;
   for (int amount = 20; amount < 100; amount++) {
     try {
       if (REPORT_ENABLED) {
         System.out.println("EXCHANGING " + amount + " ");
       }
       // Do not solve cases without solutions
       if (EXISTING_SOLUTIONS_ONLY) {
         if (!Force.solve(amount)) {
           continue;
         }
       }
       // Need to reset the configuration because it needs to be changed each
       // time when looping.
       // -------------------------------------------------------------------
       DefaultConfiguration.reset();
       e = makeChangeForAmount(amount);
       if (REPORT_ENABLED) {
         System.out.println(" err " + e);
         System.out.println("---------------");
       }
       s = s + e;
     } catch (Exception ex) {
       ex.printStackTrace();
       s += 1000;
     }
   }
   if (REPORT_ENABLED) {
     System.out.println("Sum of errors " + s);
   }
   return s;
 }
 public void run() {
   Configuration conf = new Configuration();
   try {
     conf.setEventManager(new EventManager());
     Thread.sleep(100);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
 public void run() {
   Configuration conf = new Configuration();
   try {
     conf.setBulkFitnessFunction(new TestBulkFitnessFunction());
     Thread.sleep(100);
   } catch (Exception ex) {
     ex.printStackTrace();
   }
 }
 /**
  * Main method. A single command-line argument is expected, which is the volume to create (in
  * other words, 75 would be equal to 75 ccm).
  *
  * @param args first and single element in the array = volume of the knapsack to fill as a double
  *     value
  * @author Klaus Meffert
  * @since 2.3
  */
 public static void main(String[] args) {
   if (args.length != 1) {
     System.out.println("Syntax: " + KnapsackMain.class.getName() + " <volume>");
   } else {
     try {
       double volume = Double.parseDouble(args[0]);
       if (volume < 1 || volume >= KnapsackFitnessFunction.MAX_BOUND) {
         System.out.println(
             "The <volume> argument must be between 1 and "
                 + (KnapsackFitnessFunction.MAX_BOUND - 1)
                 + " and can be a decimal.");
       } else {
         try {
           findItemsForVolume(volume);
         } catch (Exception e) {
           e.printStackTrace();
         }
       }
     } catch (NumberFormatException e) {
       System.out.println("The <volume> argument must be a valid double value");
     }
   }
 }
  /**
   * 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
   * @throws InvalidConfigurationException
   * @since 2.3
   */
  public static void findeBesteParameter() throws InvalidConfigurationException {
    // Start with a DefaultConfiguration, which comes setup with the
    // most common settings.
    // -------------------------------------------------------------
    Configuration conf = new myConfiguration();
    conf.setPreservFittestIndividual(true);

    // TODO: check: viel Mehraufwand?? ja!
    // conf.setAlwaysCaculateFitness(true);

    // Set the fitness function we want to use. We construct it with
    // the target volume passed in to this method.
    // ---------------------------------------------------------
    FitnessFunction myFunc = new EAmyTeamFitnessFunction();
    conf.setFitnessFunction(myFunc);

    // --> myConfiguration
    // conf.addGeneticOperator(new MutationOperator(conf,2));
    // conf.addGeneticOperator(new CrossoverOperator(conf, .2));

    // 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.

    myTeamParameters dummyParam = new myTeamParameters(); // nur fuer min/max

    Gene[] sampleGenes = new Gene[myTeamParameters.ANZAHL_PARAMETER];
    for (int i = 0; i < sampleGenes.length; i++) {
      sampleGenes[i] = new DoubleGene(conf, dummyParam.getMin(i), dummyParam.getMax(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(POPULATION_SIZE);

    // 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(XML_FILENAME));
      population = XMLManager.getGenotypeFromDocument(conf, doc);
      // TODO mit zufaelligen auffuellen??
      System.out.println("Alte Population aus Datei gelesen!");
    } catch (Exception fex) {
      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++) {
      System.out.println("\nPopulation Nr. " + i + ":");
      printPopulation(population);

      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
    // ------------------------------------------------------------
    try {
      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(XML_FILENAME));
    } catch (Exception e) {
      e.printStackTrace();
    }
    // Display the best solution we found.
    // -----------------------------------
    IChromosome bestSolutionSoFar = population.getFittestChromosome();
    System.out.println(
        "The best solution has a fitness value of "
            + bestSolutionSoFar.getFitnessValueDirectly()
            + " mit folgenden Parametern:");
    printChromosom(bestSolutionSoFar, true);
  }