Genetic Algorithm


SUBMITTED BY: Guest

DATE: May 19, 2013, 1:22 a.m.

FORMAT: Python

SIZE: 9.8 kB

HITS: 2354

  1. import pygame, sys
  2. from pygame.locals import *
  3. import time
  4. import random
  5. from operator import *
  6. import traceback
  7. import os
  8. import getpass
  9. import cPickle as pickle
  10. class GA:
  11. def __init__(self,
  12. num_samples = 1,
  13. num_selected = 1,
  14. mutation_factor = 4):
  15. pygame.init()
  16. pygame.display.init()
  17. self.screen = pygame.display.set_mode((152, 200), 0, 32)
  18. while True:
  19. try:
  20. print "128 and 256 are good choices. 256 is better but also slower."
  21. self.ncircles = input("Enter number of circles you want to use: ")
  22. break
  23. except NameError:
  24. print "Must enter an integer!"
  25. except SyntaxError:
  26. print "Must enter an integer!"
  27. grayscale = raw_input("Is this picture grayscale? Y/N\n")
  28. accept = ["y", "Y", "n", "N"]
  29. while grayscale not in accept:
  30. grayscale = raw_input("Is this picture grayscale? Y/N\n")
  31. if grayscale == "y" or grayscale == "Y":
  32. self.grayscale = True
  33. else:
  34. self.grayscale = False
  35. self.imgpath = raw_input("Enter full path of file, including file name and extension.\n")
  36. while os.path.exists(self.imgpath) is False:
  37. print "Path/file does not exist!"
  38. self.imgpath = raw_input("Enter full path of file, including file name and extension.\n")
  39. self.bg = pygame.image.load(self.imgpath).convert()
  40. self.width = self.bg.get_width()
  41. self.height = self.bg.get_height()
  42. self.path = "C:/users/" + str(getpass.getuser()) + "/desktop/imgs/"
  43. self.num_samples = num_samples
  44. self.num_selected = num_selected
  45. self.mutation_factor = mutation_factor
  46. self.target = self.get_target()
  47. def get_target(self):
  48. x = self.width
  49. y = self.height
  50. pixelData = []
  51. for ypixel in xrange(0, y):
  52. for xpixel in xrange(0, x):
  53. pixelData.append(self.bg.get_at((xpixel, ypixel)))
  54. for event in pygame.event.get():
  55. if event.type == QUIT:
  56. pygame.quit()
  57. sys.exit()
  58. pygame.display.update()
  59. pygame.quit()
  60. return pixelData
  61. def get_state(self, screen):
  62. x = self.width
  63. y = self.height
  64. pixelData = []
  65. for ypixel in xrange(0, y):
  66. for xpixel in xrange(0, x):
  67. pixelData.append(screen.get_at((xpixel, ypixel)))
  68. return pixelData
  69. def generate_random_chromosome(self):
  70. chromo = []
  71. for n in xrange(1, self.ncircles+1):
  72. a = random.randint(0, 255)
  73. if self.grayscale:
  74. randcolor = (a,a,a,
  75. random.randint(0, 255))
  76. else:
  77. randcolor = (random.randint(0, 255),
  78. random.randint(0, 255),
  79. random.randint(0, 255),
  80. random.randint(0, 255))
  81. randpos = (random.randint(0, self.height),
  82. random.randint(0, self.width))
  83. randradius = random.randint(1, self.height/3)
  84. chromo.append((n, randcolor, randpos, randradius))
  85. print "Random chromosome generated."
  86. return chromo
  87. def fitness(self, chromo):
  88. pygame.init()
  89. s = pygame.Surface((self.width, self.height), flags=pygame.SRCALPHA)
  90. total_fitness = 0
  91. for args in chromo:
  92. s.lock()
  93. pygame.draw.circle(s, args[1], args[2], args[3])
  94. s.unlock()
  95. state = self.get_state(s)
  96. s.fill((0, 0, 0))
  97. cpix = 0
  98. for pixel in self.target:
  99. if self.grayscale:
  100. current_fitness = abs(pixel[0]-state[cpix][0])
  101. else:
  102. current_fitness = abs(pixel[0]-state[cpix][0])+abs(pixel[1]-state[cpix][1])+abs(pixel[2]-state[cpix][2])
  103. cpix += 1
  104. total_fitness += current_fitness
  105. return total_fitness
  106. def mutate(self, chromo):
  107. mutations = 0
  108. mutateTo = random.randint(1, self.mutation_factor)
  109. mutateChoice = ["color", "opacity", "pos", "radius", "swap"]
  110. while mutations < mutateTo:
  111. argchange = random.choice(mutateChoice)
  112. if argchange == "swap":
  113. swap1 = random.randint(0, len(chromo)-1)
  114. swap2 = random.randint(0, len(chromo)-1)
  115. while swap1 == swap2:
  116. swap2 = random.randint(0, len(chromo)-1)
  117. swapvalue1 = chromo[swap1]
  118. swapvalue2 = chromo[swap2]
  119. chromo[swap1] = swapvalue2
  120. chromo[swap2] = swapvalue1
  121. mutations += 1
  122. else:
  123. argint = random.randint(0, len(chromo)-1)
  124. args = list(chromo[argint])
  125. args[1] = list(args[1])
  126. args[2] = list(args[2])
  127. a = random.randint(0, 255)
  128. if argchange == "color":
  129. if self.grayscale:
  130. args[1][0] = a
  131. args[1][1] = a
  132. args[1][2] = a
  133. else:
  134. args[1][0] = random.randint(0, 255)
  135. args[1][1] = random.randint(0, 255)
  136. args[1][2] = random.randint(0, 255)
  137. elif argchange == "opacity":
  138. args[1][3] = random.randint(0, 255)
  139. elif argchange == "pos":
  140. args[2][0] = random.randint(0, self.width)
  141. args[2][1] = random.randint(0, self.height)
  142. elif argchange == "radius":
  143. args[3] = random.randint(1, self.height/3)
  144. args[2] = tuple(args[2])
  145. args[1] = tuple(args[1])
  146. args = tuple(args)
  147. chromo[argint] = args
  148. mutations += 1
  149. return chromo
  150. def display(self, data, gen):
  151. bif = "C:/users/justin/pictures/charles-darwin.jpg"
  152. mif = "C:/users/justin/pictures/mouse.png"
  153. path = self.path + str(gen) + "-" + str(self.fitness(data)/10000) + ".png"
  154. pygame.init()
  155. screen = pygame.display.set_mode((self.width, self.height), 0, 32)
  156. s = pygame.Surface((self.width, self.height), flags=pygame.SRCALPHA)
  157. s.fill((0, 0, 0))
  158. a = 0
  159. while True:
  160. for event in pygame.event.get():
  161. if event.type == QUIT:
  162. pygame.quit()
  163. sys.exit()
  164. for args in data:
  165. s.lock()
  166. pygame.draw.circle(s, args[1], args[2], args[3])
  167. s.unlock()
  168. screen.blit(s, (0, 0))
  169. pygame.display.update()
  170. pygame.image.save(screen, path)
  171. screen.fill((0, 0, 0))
  172. pygame.quit()
  173. break
  174. def run(self):
  175. #Creates a random chromosome
  176. sample = self.generate_random_chromosome()
  177. load_pickle = raw_input("Would you like to load the previous genome? Y/N\n")
  178. accept = ["y", "Y", "n", "N"]
  179. while load_pickle not in accept:
  180. load_pickle = raw_input("Would you like to load the previous genome? Y/N\n")
  181. if load_pickle == "y" or load_pickle == "Y":
  182. generation = pickle.load(open("ge.neration", "rb"))-1
  183. mother = pickle.load(open("ge.nome", "rb"))
  184. else:
  185. generation = -1
  186. mother = sample
  187. try:
  188. while self.fitness(sample) != 0:
  189. generation += 1
  190. os.system("title Genetic Algorithm: Generation " + str(generation))
  191. #Mutate the chromo
  192. temp = []
  193. for args in mother:
  194. temp.append(args)
  195. daughter = self.mutate(mother)
  196. if self.fitness(temp) <= self.fitness(daughter):
  197. mother = temp
  198. new = False
  199. else:
  200. mother = daughter
  201. new = True
  202. print "The best chromosome of generation %s is %s" %(
  203. generation, self.fitness(mother))
  204. if new:
  205. self.display(mother, generation)
  206. new = False
  207. if self.fitness(mother) <= 800000:
  208. self.mutation_factor = 1
  209. except:
  210. pickle.dump(mother, open("ge.nome", "w"))
  211. pickle.dump(generation, open("ge.neration", "w"))
  212. raw_input("Press enter to quit...\n")
  213. if __name__ == "__main__":
  214. os.system("title Genetic Algorithm")
  215. print "You MUST have a folder called \"imgs\" without the quotes on your desktop."
  216. raw_input("Press enter to start the program.\n")
  217. ga = GA()
  218. ga.run()

comments powered by Disqus