Guest User

Untitled

a guest
Feb 2nd, 2017
193
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.78 KB | None | 0 0
  1. from graphics import *
  2. from random import randint,random
  3. from time import *
  4. from pyeasyga import pyeasyga
  5.  
  6.  
  7.  
  8. arrivo = (10,3)
  9.  
  10. def distEuclidea(p1,p2):
  11.     x1=p1[0]
  12.     y1=p1[1]
  13.     x2=p2[0]
  14.     y2=p2[1]
  15.    
  16.     return ((x2-x1)**2+(y2-y1)**2)**(1/2)
  17.  
  18.  
  19. def create_individual(data):
  20.     a = [(randint(0,5),randint(0,5)) for n in range(len(data))]
  21.     print(a)
  22.     return a
  23.  
  24. def fitness(individual, data):
  25.     totX=0
  26.     totY=0
  27.     for elem in individual:
  28.        
  29.         totX+=elem[0]
  30.         totY+=elem[1]
  31.  
  32.     tot = (totX,totY)
  33.    
  34.     return distEuclidea(arrivo,tot)
  35.  
  36. def mutate(individual):
  37.     mutate_index = randint(0,len(individual)-1)
  38.     individual[mutate_index] = (randint(0,5),randint(0,5))
  39.  
  40.  
  41.  
  42. colori = ["red","green","blue","grey","brown","black"]
  43.  
  44. win = GraphWin("GeneticGraphics",500,500)
  45. win.setCoords(0,0,100,100)
  46.  
  47.  
  48.  
  49. arrivoC = Circle(Point(arrivo[0],arrivo[1]),1)
  50. arrivoC.draw(win)
  51.  
  52.  
  53. data=[(0,0),(0,0),(0,0),(0,0)]
  54. ga = pyeasyga.GeneticAlgorithm(data,maximise_fitness=False,generations=10,population_size=5)
  55. ga.create_individual = create_individual
  56. ga.fitness_function = fitness
  57. ga.mutate_function = mutate
  58.  
  59. ga.run()
  60.  
  61. for elem in ga.logGenerations:
  62.    
  63.     colore = colori[randint(0,len(colori)-1)]
  64.    
  65.     for vect in elem:
  66.         print(vect)
  67.         vect = vect[1]
  68.         #--------------
  69.         #print(str(vect)+"    "+str(fitness(p1,arrivo,vect))+"   "+colore)
  70.         #print(str(fitness(p1,arrivo,vect)))
  71.         rect =  Rectangle(Point(0,0), Point(1,1))
  72.  
  73.         rect.setOutline(colore)
  74.         rect.draw(win)
  75.        
  76.         #--------------
  77.         for elem in vect:
  78.            
  79.             rect.move(elem[0],elem[1])
  80.             sleep(0.1)
  81.  
  82. for elem in ga.last_generation():
  83.     print(elem[0])
Add Comment
Please, Sign In to add comment