Genetic algorithm library for binary and custom chromosome
matplotlib library is needed
The atributes of a GeneticAlgorithm object are: population size, chromosome len, mutation probability, crossover probability, max number of generations, tournament elements, crossover policy, mutation policy.
tournament elements: Its default value is a random number between 0.1 and 1, indicates the percentage of population that will joint the tournament for parent selection.
crossover_policy: Values: point_crossover, multi_crossover, uniform_crossover
mutation_policy: Values: swap_mutation, scramble_mutation, inversion_mutation
mutation and crossover policy must be introduced as key, value pair
There are two different types of avaliable chromosome: binary and custom. Custom chromosome has two additional attributes: chromosome_values and gen_duplication, first one is a list with the possible values for the chromosome, second one is a boolean argument to allow chromosome's gen duplicate.
The simplest instance has population size, chromosome len, mutation probability, crossover probability and max generations arguments. The rest are will take their default values:
genetic1 = GA.GA(10, 6, 0.3, 0.1, 500)
To set mutation and crossover policy follow the next example:
genetic6 = GA.GA(10, 6, 0.3, 0.1, 500, crossover_policy = "multi_crossover", mutation_policy = "swap_mutation")
To create a binary chromosome instance, use GA.Binary:
genetic5 = GA.GABinary(10, 6, 0.3, 0.1, 500, crossover_policy = "uniform_crossover")
To create a custom chromosome instance use GA.Custom:
genetic10 = GA.GACustom(5, 5, 0.2, 0.6, 500, crossover_policy = "multi_crossover", mutation_policy = "inversion_mutation", chromosome_values = ["UP", "DOWN", "LEFT", "RIGHT", "WAIT"], gen_duplication = True)
To define and add the fitness function to a instance, first we define the function:
def fitness_example(chromosome):
res = 0
for a, b in zip(chromosome, chromosome[1:]):
if b >= a:
res += b
else:
res -= (a - b) * a
return res
Next we update original fitness function (that is None) for our new function:
genetic5.fitness = fitness_example
For using the algorithm and show fitness value chart, use .solve() and .fitnessPlot() methods:
sol = genetic5.solve()
print("\nSolution: ", sol, " fitness: ", str(genetic5.fitness(sol)))
genetic5.fitnessPlot()
The example folder contains several files with different examples of ussage for this algorithm.
in order to run the examples, dont forget to place geneticAlgorithm.py in the same folder as examples
simple: Collection of genetic instantiation examples and simple list sorting using the algorithm.
movement: This example shows how the algorithm calculates a path (secuence of angles) to pass through a set of selected points. The triangle will move forwards depending on the given angle, when the triangle hits one of the selected points, this will change the color. (pygame library needed)