def select(self, population, fitness):
'''
Select a pair of parent individuals using linear ranking method.
'''
# Individual number.
NP = len(population)
# Add rank to all individuals in population.
all_fits = population.all_fits(fitness)
indvs = population.individuals
sorted_indvs = sorted(indvs,
key=lambda indv: all_fits[indvs.index(indv)])
# Assign selection probabilities linearly.
# NOTE: Here the rank i belongs to {1, ..., N}
p = lambda i: (self.pmin + (self.pmax - self.pmin)*(i-1)/(NP-1))
probabilities = [self.pmin] + [p(i) for i in range(2, NP)] + [self.pmax]
# Normalize probabilities.
psum = sum(probabilities)
wheel = list(accumulate([p/psum for p in probabilities]))
# Select parents.
father_idx = bisect_right(wheel, random())
father = sorted_indvs[father_idx]
mother_idx = (father_idx + 1) % len(wheel)
mother = sorted_indvs[mother_idx]
return father, mother
评论列表
文章目录