Genetic Algorithm

Overview

The GeneticAlgorithm class is a versatile implementation of a genetic algorithm, designed to be highly configurable. It allows users to set various parameters such as the initial population, fitness threshold, maximum number of generations, mutation chance, crossover chance, and selection type. The class supports two primary selection methods: roulette-wheel and tournament selection.

Key Components

GeneticAlgorithm Class

The GeneticAlgorithm class is a generic class that operates on a type C, which must conform to the Chromosome interface. This design allows the algorithm to be applied to a wide range of problems by simply defining a suitable chromosome type.

Selection Methods

  • Roulette-Wheel Selection: Also known as fitness proportionate selection, this method gives each chromosome a chance of being selected based on its fitness relative to the rest of the population.
  • Tournament Selection: In this method, a subset of chromosomes is chosen randomly, and the one with the highest fitness is selected.

Configuration

The class constructor (__init__) allows for the configuration of several parameters:

  • initial_population: The starting set of chromosomes.
  • threshold: The fitness level that, when reached, indicates a solution has been found.
  • max_generations: The maximum number of generations to run the algorithm.
  • mutation_chance: The probability of a chromosome undergoing mutation.
  • crossover_chance: The probability that two selected parents will produce offspring that are a mix of their genes.
  • selection_type: The method of selection to use, either roulette or tournament.

Reproduction and Replacement

The _reproduce_and_replace() method is responsible for creating a new generation of chromosomes. It selects parents based on the configured selection method, applies crossover with a certain probability, and replaces the old population with the new one.

Running the Algorithm

The run() method coordinates the entire process, iterating through generations, applying reproduction and mutation, and tracking the best chromosome found. It stops early if a chromosome meets or exceeds the fitness threshold.

Code Listings

Listing 5.2: Initial Setup

from __future__ import annotations
from typing import TypeVar, Generic, List, Tuple, Callable
from enum import Enum
from random import choices, random
from heapq import nlargest
from statistics import mean
from chromosome import Chromosome

C = TypeVar('C', bound=Chromosome) # type of the chromosomes

class GeneticAlgorithm(Generic[C]):
    SelectionType = Enum("SelectionType", "ROULETTE TOURNAMENT")

Listing 5.3: Constructor

def __init__(self, initial_population: List[C], threshold: float, max_
     generations: int = 100, mutation_chance: float = 0.01, crossover_chance:
     float = 0.7, selection_type: SelectionType = SelectionType.TOURNAMENT) -
     > None:
    self._population: List[C] = initial_population
    self._threshold: float = threshold
    self._max_generations: int = max_generations
    self._mutation_chance: float = mutation_chance
    self._crossover_chance: float = crossover_chance
    self._selection_type: GeneticAlgorithm.SelectionType = selection_type
    self._fitness_key: Callable = type(self._population[0]).fitness

Listing 5.6: Reproduction and Replacement

# Replace the population with a new generation of individuals
def _reproduce_and_replace(self) -> None:
    new_population: List[C] = []
    # keep going until we've filled the new generation
    while len(new_population) < len(self._population):
        # pick the 2 parents
        if self._selection_type == GeneticAlgorithm.SelectionType.ROULETTE:
            parents: Tuple[C, C] = self._pick_roulette([x.fitness() for x in
     self._population])
        else:
            parents = self._pick_tournament(len(self._population) // 2)
        # potentially crossover the 2 parents
        if random() < self._crossover_chance:
            new_population.extend(parents[0].crossover(parents[1]))
        else:
            new_population.extend(parents)
    # if we had an odd number, we'll have 1 extra, so we remove it
    if len(new_population) > len(self._population):
        new_population.pop()
    self._population = new_population # replace reference

Listing 5.8: Running the Algorithm

# Run the genetic algorithm for max_generations iterations
# and return the best individual found
def run(self) -> C:
    best: C = max(self._population, key=self._fitness_key)
    for generation in range(self._max_generations):
        # early exit if we beat threshold
        if best.fitness() >= self._threshold: 
            return best
        print(f"Generation {generation} Best {best.fitness()} Avg
     {mean(map(self._fitness_key, self._population))}")
        self._reproduce_and_replace()
        self._mutate()
        highest: C = max(self._population, key=self._fitness_key)
        if highest.fitness() > best.fitness():
            best = highest # found a new best
    return best # best we found in _max_generations

Figure

Figure 5.1. The general outline of a genetic algorithm Figure 5.1. The general outline of a genetic algorithm

This figure illustrates the general outline of a genetic algorithm, highlighting the key steps and decisions involved in the process.