1 from individual import INDIVIDUAL 2 import copy 3 import random 4 import constants as c 5 6 class POPULATION: 7 def __init__(self, popSize): 8 self.p = {} 9 self.popSize = popSize 10 11 def Print(self): 12 print('\n') 13 for i in self.p: 14 if i in self.p: 15 self.p[i].Print() 16 17 def Evaluate(self, envs, pp, pb): 18 for i in self.p: 19 self.p[i].Fitness = 0 20 for e in range(0, c.numEnvs): 21 for i in self.p: 22 self.p[i].Start_Evaluation(envs.envs[e], pp, pb) 23 for i in self.p: 24 self.p[i].Compute_Fitness() 25 for z in self.p: 26 self.p[z].fitness = self.p[z].fitness/c.numEnvs 27 28 29 def Mutate(self): 30 for i in self.p: 31 self.p[i].Mutate() 32 33 def Initialize(self): 34 for i in range(0, self.popSize): 35 self.p[i] = INDIVIDUAL(i=i) 36 37 def Copy_Best_From(self, other): 38 39 c = [0] * len(other.p) 40 for i in other.p: 41 c[i] = copy.deepcopy(other.p[i].fitness) 42 self.p[0] = other.p[c.index(max(c))] 43 44 def Fill_From(self, other): 45 self.Copy_Best_From(other) 46 self.Collect_Children_From(other) 47 48 def Collect_Children_From(self, other): 49 for j in range(1, len(other.p)): 50 #self.p[j+1] = copy.deepcopy(other.p[j]) 51 winner = other.Winner_Of_Tournament_Selection() 52 self.p[j] = copy.deepcopy(winner) 53 self.p[j].Mutate() 54 55 def Winner_Of_Tournament_Selection(other): 56 p1 = random.randint(1, len(other.p) - 1) 57 p2 = random.randint(1, len(other.p) - 1) 58 while p2 == p1: 59 p2 = random.randint(1, len(other.p) - 1) 60 if other.p[p1].fitness > other.p[p2].fitness: 61 return other.p[p1] 62 elif other.p[p1].fitness < other.p[p2].fitness: 63 return other.p[p2] 64 65 def ReplaceWith(self, other): 66 for i in self.p: 67 if self.p[i].fitness < other.p[i].fitness: 68 self.p[i] = other.p[i] 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90