Genetic Algorithms Example

 

public class MaxOnesExperiment {

    public static void main(String[] args) {


        // Build a exemplar individual

        Individual ex = new Individual();

        for (int i = 0; i < 100; i++) {

            ex.addGene(new BitGene());  // true or false gene

        }


        // Create genetic operators, selection mechanism and fitness function.

        MutationOperator mu = new FixedRateMutation(0.001);

        CrossoverOperator co = new OnePointCrossover();

        ParentSelector ps = new RouletteWheel();

        FitnessFunction ff = new MaxOnesFitnessFunction();


        // Create a population of 500 individuals.

        Population pop = new FixedSizePopulation(500, ex, ps, mu, co, ff, null);


        // Print the average population fitness every 5 generations.

        pop.addStatTracker(new AveFitnessTracker(5));


        // Run the simulation for 500 generations.

        for (int gen = 0; gen < 500; gen++) {

            pop.nextGeneration();

        }

    }


    private class MaxOnesFitnessFunction implements IndividualFitnessFunction {

        // Fitness is given by the number of true genes.

        public double evaluate(Individual ind) {

            double fitness = 0;

            for (Gene g : ind) {

                if (((BitGene) g).getValue()) {

                    fitness += 1;

                }

            }

            return fitness;

        }

    }

}

The example below illustrates how to create a genetic algorithm in dLife.  This genetic algorithm evolves individuals with 100 1-bit genes. An individual’s fitness is given by the number of bit genes with the value true.