Advertisement
franciscominajas

Algoritmo Genetico Simple1

Mar 2nd, 2014
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.62 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 = 20
  9. mutation_probability = 0.1
  10. accuracy = 3
  11. lower_bound = 0
  12. upper_bound = 20
  13. long_string = 0
  14. number_generation = 100
  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.     for i in range(0,len(binary)):
  34.         decimal_value += math.pow(2,i)*binary_inside[i]
  35.     (int)(decimal_value)
  36.     return (lower_bound+decimal_value*((upper_bound-lower_bound)/(math.pow(2,long_string)-1))) #funcion Paco #nueva funcion decodificar cromosoma
  37. def elitism(evaluated, original):
  38.     new_eval = []
  39.     new_ori = []
  40.     valor  = 0
  41.     temp = []
  42.     new_eval = evaluated[:]
  43.     new_ori = original[:]
  44.     temp = evaluated[:]
  45.     temp.sort(reverse = True)
  46.     for i in range(0,size_population):
  47.         if(temp[0] == new_eval[i]):
  48.             valor = i
  49.             break
  50.  
  51.     return new_ori[valor]
  52. def random_gene():
  53.     gene=[]
  54.     for i in range(0,long_string):
  55.         if random.random()<0.5:  #Uniform population
  56.             gene.append(0)
  57.         else:
  58.             gene.append(1)
  59.     return gene
  60. def FO1(x):
  61.  
  62.     return (x + 5* math.sin(3*x) + 8*math.cos(5*x))
  63. def crossover_2_point(parent1,parent2):
  64.  
  65.     children1 = []
  66.     children2 = []
  67.  
  68.     cross1 = 0
  69.     cross2 = 0
  70.  
  71.     cross1  = (int)(random.random()*long_string)
  72.     cross2  = (int)(random.random()*long_string)
  73.  
  74.     while( cross1 >= cross2):
  75.         cross1  = (int)(random.random()*long_string)
  76.         cross2  = (int)(random.random()*long_string)
  77.         if( cross2 > cross1):
  78.             break
  79.  
  80.     #print("cruce 1",cross1,"cruce 2", cross2)
  81.     for i in range (0,cross1):
  82.         children1.append(parent2[i])
  83.         children2.append(parent1[i])
  84.  
  85.     for i in range (cross1,cross2):
  86.         children1.append(parent1[i])
  87.         children2.append(parent2[i])
  88.    
  89.     for i in range ( cross2,long_string):
  90.         children1.append(parent2[i])
  91.         children2.append(parent1[i])
  92.  
  93.     #print(parent1)
  94.     #print(parent2)
  95.     #print("TERMINA PADRES")
  96.     #print(children1)
  97.     #print(children2)
  98.     to_next_generation.append(children1)
  99.     to_next_generation.append(children2)
  100. def make_pairs(genes):
  101.     rand1 = []
  102.     rand2 = []
  103.     erase = []
  104.     rand1 = range(size_population)
  105.     rand2 = range(size_population)
  106.     shuffle(rand1)
  107.     shuffle(rand2)
  108.     #print(rand1)
  109.     #print(rand2)
  110.     index3 = 1
  111.     index2 = 1
  112.  
  113.     for i in range(0,size_population,2):
  114.  
  115.         if(genes[rand1[i]] >= genes[rand1[index2]]):
  116.             parents1.append(rand1[i])
  117.         else:
  118.             parents1.append(rand1[index2])
  119.         index2 =  index2 + 2
  120.  
  121.     for i in range(0,size_population,2):
  122.  
  123.         if(genes[rand2[i]] >= genes[rand2[index3]]):
  124.             parents2.append(rand2[i])
  125.         else:
  126.             parents2.append(rand2[index3])
  127.         index3 =  index3 + 2
  128.  
  129.     rand1 = erase[:]
  130.     rand2 = erase[:]
  131.     index2 = 1
  132.     index3 = 1
  133.     #print(parents1,"luego",parents2)
  134. def mutation():
  135.  
  136.     gen = 0
  137.     for i in range(0,size_population):
  138.         rand =  random.random()
  139.         if( rand < mutation_probability):
  140.             gen = (int)(random.random()*long_string)
  141.             print("Se mutara el chromosoma ",i+1,"en la posicion ",gen)
  142.             if(intial_population[i][gen] ==1):
  143.                 intial_population[i][gen] = 0
  144.             else:
  145.                 intial_population[i][gen] = 1
  146.  
  147.  
  148.    
  149. #PRIMEROS PASOS
  150. long_string = long_string()
  151.  
  152. for i in range(0,size_population): #generamos la poblacion aleatoria
  153.     intial_population.append(random_gene())
  154. #print(intial_population)
  155.  
  156. #REPETICION PARA LAS SIGUIENTES GENERACIONES
  157.  
  158.  
  159. for generacion in range(0,number_generation):
  160.     for j in range(0,size_population): #decodificamos la poblacion inicial
  161.         decoded_population.append(decode_number(intial_population[j]))
  162.  
  163.     for k in range(0,size_population): #evaluamos en la funcion objetivo FO1
  164.         evaluated_in_function.append(FO1(decoded_population[k]))
  165.  
  166.     thebest.append(elitism(evaluated_in_function,intial_population))
  167.  
  168.     #print(decoded_population)
  169.     make_pairs(evaluated_in_function)#realizamos la seleccion de parejas por torneo
  170.    
  171.  
  172.     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
  173.                                          #generacion
  174.         crossover_2_point(intial_population[parents1[l]],intial_population[parents2[l]])
  175.     intial_population = to_next_generation[:]
  176.     intial_population[0] = thebest[0] #ya seleccionado el mejor siempre pasa a la siguiente generacion
  177.     mutation()
  178.     for j in range(0,size_population): #decodificamos la poblacion inicial
  179.         decoded_population.append(decode_number(intial_population[j]))
  180.     for k in range(0,size_population): #evaluamos en la funcion objetivo FO1
  181.         evaluated_in_function.append(FO1(decoded_population[k]))
  182.     #evaluated_in_function.sort(reverse= True)
  183.     for p in range(0,size_population):
  184.         print ("%.3f" % ( evaluated_in_function[p]))
  185.  
  186.     print("end generation number: ",generacion+1)
  187.     funcion_generacion = vacia[:]
  188.     to_next_generation = vacia[:]  
  189.     decoded_population = vacia[:]
  190.     evaluated_in_function = vacia[:]
  191.     parents1 = vacia[:]
  192.     decode_numberparents2 = vacia[:]
  193.     thebest = vacia[:]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement