Advertisement
franciscominajas

Algoritmo Genetico Simple2

Mar 4th, 2014
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 6.60 KB | None | 0 0
  1.  
  2. from Tkinter import *
  3. import random
  4. import math
  5. from random import shuffle
  6.  
  7.  
  8. size_population = 60
  9. mutation_probability = 0.1
  10. accuracy = 3
  11. lower_bound = 0
  12. upper_bound =  20
  13. long_string = 0
  14. number_generation = 20
  15. intial_population = [] #almacena los cromosomas
  16. decoded_population = []#almacena el valor de los cromosomas en decimal
  17. evaluated_in_function = [] #alamacena el valor  evaluado en la funcion objetivo
  18. parents1 = []#almacena el numero del primer padre obtenido en el torneo
  19. parents2 = []#almacena el numero del segundo padre obtenido en el torneo
  20. to_next_generation = []#cuando se realiza el cruce aqui se guardaran los hijos y luego la poblacion inicial
  21.                        #sera reemplazada por estos
  22. thebest = []
  23. vacia = [] #para limpiar los valores de las listas y estas vuelvan a llenarse desde el principio
  24.  
  25. def long_string():
  26.  
  27.     return   (int) (math.ceil(math.log(abs(upper_bound - lower_bound) * math.pow(10.0, accuracy) ,2)))
  28. def decode_number(binary):#nueva funcion decodifica
  29.     binary_inside = []
  30.     binary_inside = binary[:]
  31.     binary_inside.reverse()
  32.     decimal_value =0
  33.     decimal_value2 = 0
  34.  
  35.  
  36.     for i in range(0,long_string):
  37.         decimal_value += math.pow(2,i)*binary_inside[i]
  38.     (int)(decimal_value)
  39.  
  40.     for i in range(0,long_string2):
  41.         decimal_value2 += math.pow(2,i)*binary_inside[i+long_string2]
  42.     (int)(decimal_value2)
  43.  
  44.     value_X = (float)(lower_bound+decimal_value*((upper_bound-lower_bound)/(math.pow(2,long_string)-1)))
  45.     value_Y = (float)(lower_bound+decimal_value2*((upper_bound-lower_bound)/(math.pow(2,long_string)-1)))
  46.  
  47.     return (value_X,value_Y)
  48. def elitism(evaluated, original):
  49.     new_eval = []
  50.     new_ori = []
  51.     valor  = 0
  52.     temp = []
  53.     new_eval = evaluated[:]
  54.     new_ori = original[:]
  55.     temp = evaluated[:]
  56.     temp.sort(reverse = True)
  57.     for i in range(0,size_population):
  58.         if(temp[0] == new_eval[i]):
  59.             valor = i
  60.             break
  61.  
  62.     return new_ori[valor]
  63. def random_gene():
  64.     gene=[]
  65.     for i in range(0,long_string+long_string2):
  66.         if random.random()<0.5:  #Uniform population
  67.             gene.append(0)
  68.         else:
  69.             gene.append(1)
  70.     return gene
  71. def FO1(X,Y):
  72.  
  73.     return ((X + 5*math.sin(3*X)+ 8*math.cos(5*X) + Y + 5*math.sin(3*Y) + 8*math.cos(5*Y))/2 )
  74. def crossover_2_point(parent1,parent2):
  75.  
  76.     children1 = []
  77.     children2 = []
  78.  
  79.     cross1 = 0
  80.     cross2 = 0
  81.  
  82.     cross1  = (int)(random.random()*long_string)
  83.     cross2  = (int)(random.random()*long_string)
  84.  
  85.     while( cross1 >= cross2):
  86.         cross1  = (int)(random.random()*long_string)
  87.         cross2  = (int)(random.random()*long_string)
  88.         if( cross2 > cross1):
  89.             break
  90.  
  91.     #print("cruce 1",cross1,"cruce 2", cross2)
  92.     for i in range (0,cross1):
  93.         children1.append(parent2[i])
  94.         children2.append(parent1[i])
  95.    
  96.     for i in range (cross1,cross2):
  97.         children1.append(parent1[i])
  98.         children2.append(parent2[i])
  99.    
  100.     for i in range ( cross2,long_string+long_string2):
  101.         children1.append(parent2[i])
  102.         children2.append(parent1[i])
  103.  
  104.  
  105.     #print(parent1)
  106.     #print(parent2)
  107.     #print("TERMINA PADRES")
  108.     #print(children1)
  109.     #print(children2)
  110.     to_next_generation.append(children1)
  111.     to_next_generation.append(children2)
  112. def make_pairs(genes):
  113.     rand1 = []
  114.     rand2 = []
  115.     erase = []
  116.     rand1 = range(size_population)
  117.     rand2 = range(size_population)
  118.     shuffle(rand1)
  119.     shuffle(rand2)
  120.     #print(rand1)
  121.     #print(rand2)
  122.     index3 = 1
  123.     index2 = 1
  124.  
  125.     for i in range(0,size_population,2):
  126.  
  127.         if(genes[rand1[i]] >= genes[rand1[index2]]):
  128.             parents1.append(rand1[i])
  129.         else:
  130.             parents1.append(rand1[index2])
  131.         index2 =  index2 + 2
  132.  
  133.     for i in range(0,size_population,2):
  134.  
  135.         if(genes[rand2[i]] >= genes[rand2[index3]]):
  136.             parents2.append(rand2[i])
  137.         else:
  138.             parents2.append(rand2[index3])
  139.         index3 =  index3 + 2
  140.  
  141.     rand1 = erase[:]
  142.     rand2 = erase[:]
  143.     index2 = 1
  144.     index3 = 1
  145.     #print(parents1,"luego",parents2)
  146. def mutation():
  147.  
  148.     gen = 0
  149.     for i in range(0,size_population):
  150.         rand =  random.random()
  151.         if( rand < mutation_probability):
  152.             gen = (int)(random.random()*long_string)
  153.             #print("Se mutara el chromosoma ",i+1,"en la posicion ",gen)
  154.             if(intial_population[i][gen] ==1):
  155.                 intial_population[i][gen] = 0
  156.             else:
  157.                 intial_population[i][gen] = 1
  158.  
  159.  
  160.    
  161. #PRIMEROS PASOS
  162. long_string2 = 0
  163. long_string = long_string()
  164. long_string2 = long_string
  165. aux1 = []
  166. aux2 = []
  167. decoded_populationX = []
  168. decoded_populationY = []
  169.  
  170.  
  171. for i in range(0,size_population): #generamos la poblacion aleatoria
  172.     intial_population.append(random_gene())
  173.    
  174. for hh in range(0,number_generation):
  175.  
  176.     for j in range(0,size_population): #decodificamos la poblacion inicial
  177.         value1 = decode_number(intial_population[j])[0]
  178.         value2 = decode_number(intial_population[j])[1]
  179.         decoded_populationX.append(value1)
  180.         decoded_populationY.append(value2)
  181.  
  182.     for k in range(0,size_population): #evaluamos en la funcion objetivo FO1
  183.                 evaluated_in_function.append(FO1(decoded_populationX[k] ,decoded_populationY[k]))
  184.  
  185.  
  186.  
  187.     thebest.append(elitism(evaluated_in_function,intial_population))
  188.  
  189.     make_pairs(evaluated_in_function)#realizamos la seleccion de parejas por torneo
  190.  
  191.  
  192.     for l in range(0,len(parents1)): #realizamos la cruza de los padres seleccionados y generamos los dos hijos que se iran a la siguiente
  193.                                              #generacion
  194.         crossover_2_point(intial_population[parents1[l]],intial_population[parents2[l]])
  195.     intial_population = to_next_generation[:]
  196.     intial_population[0] = thebest[0] #ya seleccionado el mejor siempre pasa a la siguiente generacion
  197.  
  198.     mutation()
  199.  
  200.     decoded_populationY[:] = []
  201.     decoded_populationX[:] = []
  202.     evaluated_in_function[:] = []
  203.  
  204.  
  205.  
  206.     for j in range(0,size_population): #decodificamos la poblacion inicial
  207.         value1 = decode_number(intial_population[j])[0]
  208.         value2 = decode_number(intial_population[j])[1]
  209.         decoded_populationX.append(value1)
  210.         decoded_populationY.append(value2)
  211.  
  212.     for k in range(0,size_population):
  213.         evaluated_in_function.append(FO1(decoded_populationX[k] ,decoded_populationY[k]))
  214.  
  215.     #print(decoded_population)
  216.     #print(evaluated_in_function)
  217.     #evaluated_in_function.sort(reverse= True)
  218.  
  219.  
  220.  
  221.     for p in range(0,size_population):
  222.         print ("%.3f" % ( evaluated_in_function[p]) , "%.3f" % (decoded_populationX[p]), "%.3f" % (decoded_populationY[p]))
  223.     print("end generation :", hh+1)
  224.  
  225.  
  226.     funcion_generacion = vacia[:]
  227.     to_next_generation = vacia[:]  
  228.     decoded_population = vacia[:]
  229.     evaluated_in_function = vacia[:]
  230.     parents1 = vacia[:]
  231.     parents2 = vacia[:]
  232.     decode_numberparents2 = vacia[:]
  233.     thebest = vacia[:]
  234.     aux1 = vacia[:]
  235.     aux2 = vacia[:]
  236.     decoded_populationY[:] = []
  237.     decoded_populationX[:] = []
  238.     evaluated_in_function[:] = []
  239.     value1 = 0
  240.     value2 = 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement