Let's start with a simple problem. Given a search space made of boolean variables, we aim at finding a solution made entirely of true values (or false values). This problem is faced by designing a genetic algorithm working on boolean chromosomes. The fitness function is computed by counting the number of true values within the chromosome. So in order to find the solution with all true values we can maximize the fitness function, whilst we minimize the fitness function in order to find a solution made of all false values.
This tutorial will give the opportunity of understanding how a genetic algorithm is structured and taylored to an optimization problem. Moreover, we will see how listeners can be used to capture the algorithms events.
Choosing a suitable chromosome representation is the most important task
to do before running a genetic algorithm. Which representation to use
depends on the structure of problem solutions. In our case, solutions
are made of boolean arrays. Thus, BooleanChromosome looks to be the
approppriate choice. Chromosomes represent the key component of
solutions (i.e. Individuals). For building the initial population we
need a prototype of solutions (sample), as shown by the following code.
Any algorithm in jenes is based on GeneticAlgorithm, an abstract class whose only abstract method is evaluateIndividual that is problem dependant. The code to subclass GeneticAlgorithm and to evaluate an individual in our problem is shown below.
After the genetic algorithm is defined, we need to specify the sequence of operators population will pass through. The simplest scheme contains only three operators in sequence: one selector, one crossover and one mutator. However it is possible to create a more complex pipe having paralleles and sequences. For the purpose of this tutorial we will adopt the simple structure.
It is possible to customize the genetic algorithm setting the elitism
value and the optimization goal before to run the evolution. The elitism
is the number of best individuals to hold in the next generation (1 in
Finally, we can make the algorithm running.
Jenes provides statistics for both the algorithm and the population.
The first refer to statistics concerning the algorithm run, namely the
times of initialization, starting, evolution, and generations. The
second to the distribution of solutions and related fitness values, such
as the individuals ordered by decreasing fitness function, the mean
max, and min of fitness values. They can be retrieved at any moment. We
will use them when the algorithm has finished.