/
breeder.py
57 lines (43 loc) · 1.34 KB
/
breeder.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
from population import Population
from individual import Individual
from attribute import Attribute
import random
class Breeder:
uniformRate = 0.5
mutationRate = 0.1
tourneySize = 5
elitism = False
def __init__(self, population):
self.pop = population
def evolve(self):
newPop = Population(self.pop.size(), False)
i = 0
while i < self.pop.size():
ind1 = self.tourney()
ind2 = self.tourney()
newInd = self.breed(ind1, ind2)
newPop.addIndividual(newInd)
i += 1
return newPop
def breed(self, ind1, ind2):
newInd = Individual(False)
for i in xrange(Individual.numAtts):
parentInd = None
if random.random() > Breeder.uniformRate:
parentInd = ind1
else:
parentInd = ind2
newVal = parentInd[i]
newInd.attributeVector += [newVal]
self.mutate(newInd)
return newInd
def mutate(self, ind):
for index in xrange(len(ind.attributeVector)):
if random.random() < Breeder.mutationRate:
# ind.attributeVector[index] += (random.random() * 2 - 1) * (Population.fit.maxFitness() - Population.fit.getFitness(ind))
ind.attributeVector[index] = random.random() * 2 - 1
def tourney(self):
tourneyPop = Population(Breeder.tourneySize, False)
for i in xrange(self.pop.size()):
tourneyPop.addIndividual( self.pop.individuals[random.randrange(0,self.pop.size())] )
return tourneyPop.getFittest()