Example usage for org.apache.commons.math3.genetics Chromosome fitness

List of usage examples for org.apache.commons.math3.genetics Chromosome fitness

Introduction

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

Prototype

double fitness

To view the source code for org.apache.commons.math3.genetics Chromosome fitness.

Click Source Link

Document

Cached value of the fitness of this chromosome.

Usage

From source file:com.dlej.Main.java

public static void main(String[] args) {
    long startTime = System.currentTimeMillis();

    // initialize a new genetic algorithm
    GeneticAlgorithm ga = new GeneticAlgorithm(new OnePointCrossover<Character>(), CROSSOVER_RATE,
            new RandomCharacterMutation(), MUTATION_RATE, new TournamentSelection(TOURNAMENT_ARITY));

    // initial population
    Population initial = getInitialPopulation();

    // stopping condition
    StoppingCondition stoppingCondition = new StoppingCondition() {

        int generation = 0;

        @Override/*  w ww. j  a  v a2 s. c o m*/
        public boolean isSatisfied(Population population) {
            Chromosome fittestChromosome = population.getFittestChromosome();

            if (generation == 1 || generation % 10 == 0) {
                System.out.println("Generation " + generation + ": " + fittestChromosome.toString());
            }
            generation++;

            double fitness = fittestChromosome.fitness();
            if (Precision.equals(fitness, 0.0, 1e-6)) {
                return true;
            } else {
                return false;
            }
        }
    };

    System.out.println("Starting evolution ...");

    // run the algorithm
    Population finalPopulation = ga.evolve(initial, stoppingCondition);

    // Get the end time for the simulation.
    long endTime = System.currentTimeMillis();

    // best chromosome from the final population
    Chromosome best = finalPopulation.getFittestChromosome();
    System.out.println("Generation " + ga.getGenerationsEvolved() + ": " + best.toString());
    System.out.println("Total execution time: " + (endTime - startTime) + "ms");
}