class SimpleDemoGA: def __init__(self, numberOfIndividuals, numberOfGenes): self.numberOfGenes = numberOfGenes self.population = Population(numberOfIndividuals, numberOfGenes) self.generationCount = 0 def crossover(self): # Swap values up to crossoverIndex between fittest and secondFittest # This creates a child genome that has a combination of genes from the parents # It is not a completely random selection, this function treats each bit as a gene in a sequence crossoverIndex = random.randrange(self.numberOfGenes) offspring = Individual(self.numberOfGenes) tempOffspringGenes = self.population.fittest.genes[0:crossoverIndex] for i in range(crossoverIndex, self.numberOfGenes): tempOffspringGenes.append(self.population.secondFittest.genes[i]) # ENHANCEMENT: Add a function to Individual to make a new Individual with specific genes # rather than create a new random one and set the genes offspring.genes = tempOffspringGenes return offspring def mutation(self, offspring): mutationIndex = random.randrange(self.numberOfGenes) # Bitflip the mutated index using XOR offspring.genes[mutationIndex] ^= 1 # def getFittestOffspring(self): # return self.offspring def addFittestOffspring(self, offspring): self.population.removeLeastFit() self.population.addToPopulation(offspring) def showGeneticPool(self): print("==Genetic Pool==") for individual in self.population.individuals: print("Individual: {0} Fit: {1} {2}".format( self.population.individuals.index(individual), individual.fitness, individual.genes)) print("================")