geneticAlgorithm.py
1    from population import POPULATION 
2    import constants as c 
3    from environments import ENVIRONMENTS 
4    import pickle 
5     
6    envs = ENVIRONMENTS() 
7    envs.Initialize() 
8    parents = POPULATION(c.popSize) 
9    parents.Initialize() 
10   parents.Evaluate(envs, pp=False, pb=True) 
11   parents.Print() 
12    
13    
14    
15   # for loop that creates n iterations 
16   for g in range(1, c.numGens): 
17    
18       # create the child population 
19       children = POPULATION(c.popSize) 
20       # fill the children popualtion from the parents keeping best in first place and 
21       # filling the rest with mutations 
22       children.Fill_From(parents) 
23       # evaluate the children 
24       children.Evaluate(envs, pp=False, pb=True) 
25       # print the fitness values 
26       print(g, end='  ') 
27       children.Print() 
28       #replace parents with stronger children 
29       parents.ReplaceWith(children) 
30    
31    
32    
33   # save structure of child that fares well 
34       f = open('robot1.p', 'wb') 
35       pickle.dump(children, f) 
36       f.close() 
37    
38    
39    
40    
41   f = open('robot1.p', 'rb') 
42    
43   best = pickle.load(f) 
44   f.close() 
45    
46   best.Evaluate(envs, pp=True, pb=False) 
47    
48    
49    
50    
51    
52    
53    
54    
55    
56    
57    
58    
59