Number = 100 # population size
Genome = 100 # genome size
Mutate = 0.1 # mutation probability from 1 to 0
Beneficial = 0.0001 # chance of 0 flipping to 1
Generations = 2000 # number of generations to simulate
EachStep = 1 # print fitness at each step?
StartValue = 1 # begin with max fitness
Children = 4 # number of offspring to 2 parents
# Each 1 simulates the presence of a functioning adaptation.
# Each 0 simulates its absence.
# Individuals are paired up randomly before they reproduce.
# The next generation is sorted by fitness
# and the bottom half is perfectly eliminated.
# The fitness reported is the average number of 1s in the population.
from random import *
def initPop():
pop = []
for i in range(Number):
pop.append([StartValue] * Genome)
return pop
def mutatePop(pop):
for i in pop:
mutateInd(i)
def mutateInd(i):
for j in range(len(i)):
if random() < Mutate:
if (i[j]):
i[j] = 0
elif random() < Beneficial:
i[j] = 1
def breed(i1, i2):
kid = []
for j in range(len(i1)):
if getrandbits(1):
kid.append(i1[j])
else:
kid.append(i2[j])
return kid
def compare(i1, i2):
return sum(i1) - sum(i2)
def nextgen(pop):
mutatePop(pop)
shuffle(pop)
kids = []
for j in range(len(pop) / 2):
for l in range(Children):
kids.append(breed(pop[j*2], pop[j*2+1]))
kids.sort(compare)
return kids[(-len(pop))-1:-1]
def fitness(pop):
total = 0
for i in pop:
total += sum(i)
return (total * 1.0) / len(pop)
def run(steps):
pool = initPop()
print "Running."
q = 0
while q < steps:
if EachStep:
print "Fitness in generation " + `q` + ": " + `fitness(pool)`
pool = nextgen(pool)
q += 1
print "Final fitness: ", fitness(pool)
run(Generations)