Advertisement
Guest User

Untitled

a guest
May 17th, 2019
286
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 4.13 KB | None | 0 0
  1. from multiprocessing.pool import ThreadPool
  2. import multiprocessing as mpc
  3. from time import time as timer
  4. import math
  5.  
  6. import array
  7. import numpy
  8. import random
  9.  
  10. from deap import base
  11. from deap import creator
  12. from deap import tools
  13. from deap import algorithms
  14.  
  15. import argparse
  16. import os
  17.  
  18.  
  19. parser = argparse.ArgumentParser(description='Executes GA')
  20. parser.add_argument('--gens',
  21. help='Number of generations to run.',
  22. type=int,
  23. default=2)
  24. parser.add_argument('--pop_size',
  25. help='Population size per generation.',
  26. type=int,
  27. default=5)
  28. parser.add_argument('--save_frames',
  29. help='Write frames to file.',
  30. action='store_true')
  31.  
  32. args = parser.parse_args()
  33. from bouncing_balls import BouncyBalls
  34.  
  35. # Draw two random lines with the intent of maximizing the number of balls
  36. # on the screen
  37. def eval2DPhysics(individual, last=False): #TBD - do something with indiv!
  38. if not last:
  39. os.environ['SDL_VIDEODRIVER'] = 'dummy' # Run pygame headless
  40. else:
  41. os.environ['SDL_VIDEODRIVER'] = 'x11' # Run pygame headfull
  42.  
  43. l1 = (individual[0],individual[1],individual[2],individual[3])
  44. l2 = (individual[4],individual[5],individual[6],individual[7])
  45. game = BouncyBalls(l1,l2)
  46. return game.run(),
  47.  
  48. creator.create("FitnessMax", base.Fitness, weights=(1.0,))
  49. creator.create("Individual", list, fitness=creator.FitnessMax)
  50.  
  51. toolbox = base.Toolbox()
  52.  
  53. toolbox.register("attr_int", random.randint, 0, 600) #make pair if not square resolution
  54. toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_int, 8)
  55. toolbox.register("population", tools.initRepeat, list, toolbox.individual)
  56.  
  57.  
  58. pool = mpc.Pool()
  59. toolbox.register("map", pool.map)
  60. toolbox.register("evaluate", eval2DPhysics)
  61. toolbox.register("mate", tools.cxTwoPoint)
  62. toolbox.register("mutate", tools.mutUniformInt, low=0, up=600, indpb=0.2)
  63. #toolbox.register("mutate", tools.mutGaussian, mu=0.0, sigma=0.2, indpb=0.2)
  64. toolbox.register("select", tools.selTournament, tournsize=3)
  65.  
  66. def main(gens, pop_size, save_frames=False):
  67. pop = toolbox.population(n=pop_size)
  68. CXPB, MUTPB = 0.5, 0.2
  69.  
  70. fitnesses = toolbox.map(toolbox.evaluate, pop)
  71.  
  72. # Copy fitnesses to population
  73. for ind, fit in zip(pop, fitnesses):
  74. ind.fitness.values = fit
  75. fits = [ind.fitness.values[0] for ind in pop]
  76.  
  77. gen = 0
  78. while gen < gens:
  79. gen += 1
  80. print("Generation %d" % gen)
  81.  
  82. offspring = toolbox.select(pop, len(pop))
  83. offspring = list(map(toolbox.clone, offspring))
  84.  
  85. # Crossover
  86. for c1, c2 in zip(offspring[::2], offspring[1::2]):
  87. if random.random() < CXPB:
  88. toolbox.mate(c1, c2)
  89. del c1.fitness.values
  90. del c2.fitness.values
  91.  
  92. # Mutation
  93. for mutant in offspring:
  94. if random.random() < MUTPB:
  95. toolbox.mutate(mutant)
  96. for m in mutant:
  97. if m < 0.0: m = 0.0
  98. if m > 600.0: m = 600.0
  99. del mutant.fitness.values
  100.  
  101. invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
  102.  
  103. # Evaluation
  104. fitnesses = toolbox.map(toolbox.evaluate, invalid_ind)
  105.  
  106. for ind, fit in zip(invalid_ind, fitnesses):
  107. ind.fitness.values = fit
  108.  
  109. pop[:] = offspring
  110. fits = [ind.fitness.values[0] for ind in pop]
  111.  
  112. print("%d invalid indices evaluated" % len(invalid_ind))
  113.  
  114. # Print statistics
  115. length = len(pop)
  116. mean = sum(fits) / length
  117. sum2 = sum(x*x for x in fits)
  118. std = abs(sum2/length - mean**2)**0.5
  119.  
  120. print("* Min: %s" % min(fits))
  121. print("* Max: %s" % max(fits))
  122. print("* Avg: %s" % mean)
  123. print("* Std: %s" % std)
  124. best = tools.selBest(pop, 1)[0]
  125. print("* Best: %s, %s" % (best, best.fitness.values))#, eval2DPhysics(best, True)))
  126.  
  127. print("Done.")
  128. best_ind = tools.selBest(pop, 1)[0]
  129. print("Best individual: %s, %s, %s" % (best_ind, best_ind.fitness.values, eval2DPhysics(best_ind, True)))
  130.  
  131. if __name__ == '__main__':
  132. assert sys.version_info >= (3, 7), "Requires Python 3.7+"
  133. main(args.gens, args.pop_size, args.save_frames)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement