1
#genetic algorithm selection routines
3
#exception - these classes only work on the scaled fitness
7
from ga_util import GAError
10
class selector(object):
14
raise GAError('selector.select() must be overridden')
18
class uniform_selector(selector):
19
def select(self,pop,cnt = 1):
21
return prng.choice(pop)
24
res.append(prng.choice(pop))
27
#class rank_selector(selector):
28
# def select(self,pop,cnt = 1):
30
# studliest = pop[0].fitness()
32
# tied_for_first = [x for x in pop if x.fitness() == y]
34
# return prng.choice(tied_for_first)
36
# for i in range(cnt):
37
# res.append(prng.choice(tied_for_first))
40
#scores must all be positive
41
class roulette_selector(selector):
46
raise GAError('srs_selector - the pop size is 0!')
47
f =self.pop.fitnesses()
48
f_max = max(f); f_min = min(f)
49
if not ( (f_max >= 0 and f_min >= 0) or
50
(f_max <= 0 and f_min <= 0)):
51
raise GAError('srs_selector requires all fitnesses values to be either strictly positive or strictly negative')
54
self.dart_board = np.add.accumulate(f / sum(f,axis=0))
56
def select(self,pop,cnt = 1):
61
#binary search would be faster
62
while dart > self.dart_board[idx]:
64
returns.append(self.pop[idx])
73
#scores must all be positive
74
class srs_selector(selector):
78
raise GAError('srs_selector - the pop size is 0!')
80
f_max = max(f); f_min = min(f)
81
if not ( (f_max >= 0. and f_min >= 0.) or
82
(f_max <= 0. and f_min <= 0.)):
83
raise GAError('srs_selector requires all fitnesses values to be either strictly positive or strictly negative - min %f, max %f' %(f_min,f_max))
84
f_avg = sum(f,axis=0)/sz
88
if pop.min_or_max() == 'max':
91
e = (-f+f_max+f_min)/f_avg
92
self.expected_value = e
93
garauntee,chance = divmod(e,1.)
94
# garauntee = floor(e)
95
# chance = remainder(e,1)
98
choices = choices + [pop[i]] * int(garauntee[i])
99
#now deal with the remainder
100
dart_board = np.add.accumulate(chance / sum(chance,axis=0))
101
for i in range(len(choices),sz):
104
while dart > dart_board[idx]:
106
choices.append(pop[idx])
107
self.choices = choices
109
def select(self,pop,cnt = 1): #ignore the past in pop
112
res.append(prng.choice(self.choices))
113
# for chosen in res: self.choices.remove(chosen)
119
if hasattr(self,'choices'):