Package Bio :: Package GA :: Package Selection :: Module Tournament
[hide private]
[frames] | no frames]

Source Code for Module Bio.GA.Selection.Tournament

 1  # This code is part of the Biopython distribution and governed by its 
 2  # license.  Please see the LICENSE file that should have been included 
 3  # as part of this package. 
 4  # 
 5   
 6  """Provide Tournament style selection. 
 7   
 8  This implements selection based on a tournament style. In this model of 
 9  selection, two individuals are randomly chosen from the population, and 
10  the organism with the higher fitness is considered the 'winner' and moves 
11  to the next generation. 
12  """ 
13  # standard modules 
14  import random 
15   
16  # local modules 
17  from .Abstract import AbstractSelection 
18   
19   
20 -class TournamentSelection(AbstractSelection):
21 """Implement tournament style selection. 22 """
23 - def __init__(self, mutator, crossover, repairer, num_competitors=2):
24 """Initialize the tournament selector. 25 26 Arguments: 27 28 o num_competitors-- The number of individiuals that should be 29 involved in a selection round. By default we just have two 30 individuals (head to head!). 31 32 See AbstractSelection for a description of the arguments to 33 the initializer. 34 """ 35 AbstractSelection.__init__(self, mutator, crossover, repairer) 36 37 if num_competitors < 2: 38 raise ValueError("Must have at least 2 competitors!") 39 40 self._num_competitors = num_competitors
41
42 - def select(self, population):
43 """Perform selection on the population using the Tournament model. 44 45 Arguments: 46 47 o population -- A population of organisms on which we will perform 48 selection. The individuals are assumed to have fitness values which 49 are due to their current genome (ie. the fitness is up to date). 50 """ 51 # we want to create a new population of the same size as the original 52 new_population = [] 53 54 while len(new_population) < len(population): 55 # select two individuals using tournament selection 56 new_orgs = [] 57 # select for two individuals 58 for round_num in range(2): 59 competitors = [] 60 while len(competitors) < self._num_competitors: 61 new_org = random.choice(population) 62 if new_org not in competitors: 63 competitors.append(new_org) 64 65 # sort the competitors by fitness, this will put them 66 # from lowest to highest 67 competitors.sort(key=lambda org: org.fitness) 68 69 # get the best organism 70 new_orgs.append(competitors[-1]) 71 72 assert len(new_orgs) == 2, "Expected two organisms to be selected" 73 74 # do mutation and crossover to get the new organisms 75 new_org_1, new_org_2 = self.mutate_and_crossover(new_orgs[0], 76 new_orgs[1]) 77 78 new_population.extend([new_org_1, new_org_2]) 79 80 return new_population
81