The code below is based on the “Hello World” toy genetic algorithm that has been dancing around the internet for a few years now. We implement in a few of the scienctific computing and problem solving classes I teach. Its fun because it is so interdisciplinary. A link to the idea can be found here:
https://github.com/jsvazic/GAHelloWorld
Here is my code as we discussed in this year’s (2024) class
import matplotlib.pyplot as plt
import numpy as np
#set target
Target = "Joeys poopy ducks"
TargetDNA = [ord(each) for each in Target]
#find number of random charcters to choose from
numRands = 255
#specify length of random string to generate
nLetters = len(Target)
#people in population
nPeople = 100
#Mating Parent Number
nParents = 40
#Set the Mutate Rate
MutateRate = 0.3
#Number of Trials
ntrials = 1000
pop = []
#generate random string
for ii in range(0,nPeople):
DNA = np.random.randint(low=0,high=numRands,size=(nLetters))
pop.append(DNA)
for qq in range(0,ntrials):
# Determine how fit everyone is
fitness = np.zeros(nPeople)
cc = 0
for DNA in pop:
#fitness
diff = DNA - TargetDNA
res = np.sum(np.abs(diff))
fitness[cc] = res
cc = cc + 1
# Select the parents for the next generation
indices = np.argsort(fitness)
parent = []
for ii in range(0,nParents):
MyIndex = indices[ii]
#print (MyIndex)
peep = pop[MyIndex]
parent.append(peep)
# Mate Parents
newpop = parent
for ii in range(nParents,nPeople):
peep1 = parent[np.random.randint(nParents)]
peep2 = parent[np.random.randint(nParents)]
mark = np.random.randint(nLetters)
DNAL = peep1[0:mark]
DNAR = peep2[mark:nLetters]
baby = np.hstack((DNAL,DNAR))
#Mutate
while np.random.rand() < MutateRate:
baby[np.random.randint(nLetters)] = np.random.randint(numRands)
newpop.append(baby)
# Show Best
DNABest = parent[0]
peep = ''.join(chr(i) for i in DNABest)
print (qq, peep)
pop = newpop

