Advertisement
franciscominajas

Algoritmo Genetico Simple

Mar 2nd, 2014
164
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.53 KB | None | 0 0
  1. from Tkinter import *
  2. import random
  3. import math
  4. from random import shuffle
  5.  
  6.  
  7. size_population = 10
  8. mutation_probability = 0.1
  9. accuracy = 3
  10. lower_bound = 17
  11. upper_bound = 18
  12. long_string = 0
  13. number_generation = 10
  14. intial_population = [] #almacena los cromosomas
  15. decoded_population = []#almacena el valor de los cromosomas en decimal
  16. evaluated_in_function = [] #alamacena el valor  evaluado en la funcion objetivo
  17. parents1 = []#almacena el numero del primer padre obtenido en el torneo
  18. parents2 = []#almacena el numero del segundo padre obtenido en el torneo
  19. to_next_generation = []#cuando se realiza el cruce aqui se guardaran los hijos y luego la poblacion inicial
  20.                        #sera reemplazada por estos
  21. vacia = [] #para limpiar los valores de las listas y estas vuelvan a llenarse desde el principio
  22.  
  23. def long_string():
  24.  
  25.     return   (int) (math.ceil(math.log(abs(upper_bound - lower_bound) * math.pow(10.0, accuracy) ,2)))
  26. def binary_(bitstring):#funcion deco Paco
  27.  
  28.     aux = 0
  29.     aux1 = 0
  30.     bitstring.reverse()
  31.  
  32.     for i in range (0, long_string):
  33.         aux+= math.pow(2,i)*bitstring[i]
  34.         aux1= lower_bound + ((aux*upper_bound)/(math.pow(2,long_string)-1))
  35.         aux1 ="%0.*f"%(accuracy,aux1)
  36.  
  37.     return (float) (aux1)  
  38. def decode_number(binary):#nueva funcion decodifica
  39.     binary_inside = []
  40.     binary_inside = binary[:]
  41.     binary_inside.reverse()
  42.     decimal_value =0
  43.     for i in range(0,len(binary)):
  44.         decimal_value += math.pow(2,i)*binary_inside[i]
  45.     (int)(decimal_value)
  46.     return (lower_bound+decimal_value*((upper_bound-lower_bound)/(math.pow(2,long_string)-1))) #funcion Paco #nueva funcion decodificar cromosoma
  47. def random_gene():
  48.     gene=[]
  49.     for i in range(0,long_string):
  50.         if random.random()<0.5:  #Uniform population
  51.             gene.append(0)
  52.         else:
  53.             gene.append(1)
  54.     return gene
  55. def FO1(x):
  56.  
  57.     return (x + 5* math.sin(3*x) + 8*math.cos(5*x))
  58. def crossover_2_point(parent1,parent2):
  59.  
  60.     children1 = []
  61.     children2 = []
  62.  
  63.     cross1 = 0
  64.     cross2 = 0
  65.  
  66.     cross1  = (int)(random.random()*long_string)
  67.     cross2  = (int)(random.random()*long_string)
  68.  
  69.     while( cross1 >= cross2):
  70.         cross1  = (int)(random.random()*long_string)
  71.         cross2  = (int)(random.random()*long_string)
  72.         if( cross2 > cross1):
  73.             break
  74.  
  75.     #print("cruce 1",cross1,"cruce 2", cross2)
  76.     for i in range (0,cross1):
  77.         children1.append(parent2[i])
  78.         children2.append(parent1[i])
  79.  
  80.     for i in range (cross1,cross2):
  81.         children1.append(parent1[i])
  82.         children2.append(parent2[i])
  83.    
  84.     for i in range ( cross2,long_string):
  85.         children1.append(parent2[i])
  86.         children2.append(parent1[i])
  87.  
  88.     #print(parent1)
  89.     #print(parent2)
  90.     #print("TERMINA PADRES")
  91.     #print(children1)
  92.     #print(children2)
  93.     to_next_generation.append(children1)
  94.     to_next_generation.append(children2)
  95. def make_pairs(genes):
  96.     rand1 = []
  97.     rand2 = []
  98.     erase = []
  99.     rand1 = range(size_population)
  100.     rand2 = range(size_population)
  101.     shuffle(rand1)
  102.     shuffle(rand2)
  103.     #print(rand1)
  104.     #print(rand2)
  105.     index3 = 1
  106.     index2 = 1
  107.  
  108.     for i in range(0,size_population,2):
  109.  
  110.         if(genes[rand1[i]] >= genes[rand1[index2]]):
  111.             parents1.append(rand1[i])
  112.         else:
  113.             parents1.append(rand1[index2])
  114.         index2 =  index2 + 2
  115.  
  116.     for i in range(0,size_population,2):
  117.  
  118.         if(genes[rand2[i]] >= genes[rand2[index3]]):
  119.             parents2.append(rand2[i])
  120.         else:
  121.             parents2.append(rand2[index3])
  122.         index3 =  index3 + 2
  123.  
  124.     rand1 = erase[:]
  125.     rand2 = erase[:]
  126.     index2 = 1
  127.     index3 = 1
  128.     #print(parents1,"luego",parents2)
  129. def mutation():
  130.  
  131.  
  132.     rand =  random.random()
  133.     if( rand < mutation_probability):
  134.         chromosome = (int)(random.random()* size_population)
  135.         gen = (int)(random.random()* long_string)
  136.         #print("Se mutara el chromosoma ",chromosome,"en la posicion ",gen)
  137.         if(intial_population[chromosome][gen] ==1):
  138.             intial_population[chromosome][gen] = 0
  139.         else:
  140.             intial_population[chromosome][gen] = 1
  141.  
  142.  
  143.  
  144.  
  145. #PRIMEROS PASOS
  146. long_string = long_string()
  147.  
  148. for i in range(0,size_population): #generamos la poblacion aleatoria
  149.     intial_population.append(random_gene())
  150. #print(intial_population)
  151.  
  152. #REPETICION PARA LAS SIGUIENTES GENERACIONES
  153.  
  154.  
  155. for generacion in range(0,number_generation):
  156.     for j in range(0,size_population): #decodificamos la poblacion inicial
  157.         decoded_population.append(decode_number(intial_population[j]))
  158.  
  159.     for k in range(0,size_population): #evaluamos en la funcion objetivo FO1
  160.         evaluated_in_function.append(FO1(decoded_population[k]))
  161.  
  162.     #print(decoded_population)
  163.     make_pairs(evaluated_in_function)#realizamos la seleccion de parejas por torneo
  164.     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
  165.                                          #generacion
  166.         crossover_2_point(intial_population[parents1[l]],intial_population[parents2[l]])
  167.  
  168.     #print(intial_population)
  169.     intial_population = to_next_generation[:]
  170.     mutation()
  171.     #print(intial_population)
  172.     for j in range(0,size_population): #decodificamos la poblacion inicial
  173.         decoded_population.append(decode_number(intial_population[j]))
  174.  
  175.     for k in range(0,size_population): #evaluamos en la funcion objetivo FO1
  176.         evaluated_in_function.append(FO1(decoded_population[k]))
  177.  
  178.     #evaluated_in_function.sort(reverse= True)
  179.  
  180.     for p in range(0,size_population):
  181.         print ("%.3f" % ( evaluated_in_function[p]))
  182.  
  183.     print("end generation number: ",generacion+1)
  184.     funcion_generacion = vacia[:]
  185.     to_next_generation = vacia[:]  
  186.     decoded_population = vacia[:]
  187.     evaluated_in_function = vacia[:]
  188.     parents1 = vacia[:]
  189.     decode_numberparents2 = vacia[:]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement