Example usage for org.apache.commons.math3.genetics Population nextGeneration

List of usage examples for org.apache.commons.math3.genetics Population nextGeneration

Introduction

In this page you can find the example usage for org.apache.commons.math3.genetics Population nextGeneration.

Prototype

Population nextGeneration();

Source Link

Document

Start the population for the next generation.

Usage

From source file:eu.tsp.sal.SensorGeneticAlgorithm.java

/**
 * Evolve the given population into the next generation.
 * <p>//from  w  ww. jav a 2s. c om
 * <ol>
 *  <li>Get nextGeneration population to fill from <code>current</code>
 *      generation, using its nextGeneration method</li>
 *  <li>Loop until new generation is filled:</li>
 *  <ul><li>Apply configured SelectionPolicy to select a pair of parents
 *          from <code>current</code></li>
 *      <li>With probability = {@link #getCrossoverRate()}, apply
 *          configured {@link CrossoverPolicy} to parents</li>
 *      <li>With probability = {@link #getMutationRate()}, apply
 *          configured {@link MutationPolicy} to each of the offspring</li>
 *      <li>Add offspring individually to nextGeneration,
 *          space permitting</li>
 *  </ul>
 *  <li>Return nextGeneration</li>
 * </ol>
 *
 * @param current the current population.
 * @return the population for the next generation.
 */
public Population nextGeneration(final Population current) {
    Population nextGeneration = current.nextGeneration();

    RandomGenerator randGen = getRandomGenerator();

    while (nextGeneration.getPopulationSize() < nextGeneration.getPopulationLimit()) {
        // select parent chromosomes
        ChromosomePair pair = getSelectionPolicy().select(current);
        //System.out.println("*****" + pair);

        // crossover?
        if (randGen.nextDouble() < getCrossoverRate()) {
            // apply crossover policy to create two offspring
            pair = getCrossoverPolicy().crossover(pair.getFirst(), pair.getSecond());
        }

        // mutation?
        if (randGen.nextDouble() < getMutationRate()) {
            // apply mutation policy to the chromosomes
            pair = new ChromosomePair(getMutationPolicy().mutate(pair.getFirst()),
                    getMutationPolicy().mutate(pair.getSecond()));
        }

        // add the first chromosome to the population
        nextGeneration.addChromosome(pair.getFirst());
        // is there still a place for the second chromosome?
        if (nextGeneration.getPopulationSize() < nextGeneration.getPopulationLimit()) {
            // add the second chromosome to the population
            nextGeneration.addChromosome(pair.getSecond());
        }
    }

    System.out.println("\nGeneration (iteration): " + (generationsEvolved + 1));
    WSN.printPopulation(nextGeneration);

    return nextGeneration;
}