Advertisement
New_T

AG

Apr 6th, 2018
192
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.76 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. Created on Sat Dec  1 19:35:25 2018
  4.  
  5. @author: Dinopc
  6. """
  7. import time
  8. import numpy as np
  9. import matplotlib.pyplot as plt
  10. import pandas as pd
  11. from bitstring import BitArray
  12. # Para 11 gerações usar o seed 83312
  13. np.random.seed()
  14. def muda(x):
  15.     if x == 0:
  16.         x = 1
  17.     else:
  18.         x=0
  19.     return x    
  20.  
  21. def gera_pop(pop1 = 30,cromossomo = 36):
  22.     pop_ = np.random.randint(2,size = [pop1,cromossomo])
  23.     pop_ = np.c_[pop_,np.zeros([pop1,4])]
  24.     return pop_
  25.  
  26. def mutacao(bebe,taxa_mutacao = 0.3):
  27.     for i in range(len(bebe)):
  28.         r =np.random.random()
  29.         if r < taxa_mutacao:
  30.            
  31.            
  32.            
  33.             bit = np.random.randint(35,dtype=int)
  34.             for ii in range(bit,bit+1):
  35.                 bebe[i,ii]= muda(bebe[i,ii])
  36.     return bebe          
  37.    
  38. def fitnes(a):
  39.     for i in range(len(a)):
  40.         a[i][36]= ((9 + a[i,2-1]*a[i,5-1] - a[i,23-1]*a[i,14-1] +
  41.                 a[i,24-1]*a[i,4-1] - a[i,21-1]*a[i,10-1] +
  42.                 a[i,36-1]*a[i,15-1] - a[i,11-1]*a[i,26-1] +
  43.                 a[i,16-1]*a[i,17-1] + a[i,3-1]*a[i,33-1] +
  44.                 a[i,28-1]*a[i,19-1] + a[i,12-1]*a[i,34-1] -
  45.                 a[i,31-1]*a[i,32-1] - a[i,22-1]*a[i,25-1] +
  46.                 a[i,35-1]*a[i,27-1] - a[i,29-1]*a[i,7-1] +
  47.                 a[i,8-1]*a[i,13-1] - a[i,6-1]*a[i,9-1] +
  48.                 a[i,18-1]*a[i,20-1] - a[i,1-1]*a[i,30-1] +
  49.                 a[i,23-1]*a[i,4-1] + a[i,21-1]*a[i,15-1] +
  50.                 a[i,26-1]*a[i,16-1] +a[i,31-1]*a[i,12-1] +
  51.                 a[i,25-1]*a[i,19-1] + a[i,7-1]*a[i,8-1] +
  52.                 a[i,9-1]*a[i,18-1] + a[i,1-1]*a[i,33-1])/27)
  53.     hordenado = a[a[:,36].argsort(),]
  54.     return(hordenado)
  55.    
  56.  
  57. def cruzamento(pai,taxa_cruzamento = 0.8):
  58.     filhos = []
  59.    
  60.     for i in range(len(pai)-1):
  61.  
  62.         if i != len(pai):
  63.             if i%2 == 0:
  64.                 r =np.random.random()
  65.                 if r < taxa_cruzamento:
  66.                      corte = np.random.randint(36,dtype=int)
  67.                      b = np.copy(pai[i,:]).reshape(1,40)
  68.                      c = np.copy(pai[i+1,:]).reshape(1,40)
  69.                      b[:,corte:] = np.copy(pai[i+1,corte:])
  70.                      c[:,corte:] = np.copy(pai[i,corte:])
  71.                      c[:,36] = 0
  72.                      b[:,36] = 0
  73.                      c = c.T
  74.                      b = b.T
  75.                      b = np.c_[b,c]
  76.                      b = b.T
  77.                      filhos.append(b)                
  78.     filhos = np.array(filhos).reshape([len(filhos)*2,40])
  79.     filhos = mutacao(filhos)
  80.     filhos = fitnes(filhos)              
  81.     return  filhos  
  82.  
  83. def mescle (pais):
  84.  
  85.    
  86.     pais_ = fitnes(pais)
  87.    
  88.    
  89.  
  90.     filhos = cruzamento(pais)
  91.  
  92.     filhos = pd.DataFrame(filhos)
  93.     pais = pd.DataFrame(pais_)
  94.    
  95.     pop_ = pd.concat([pais,filhos])
  96.     pop_[37] = ((pop_[36])/pop_[36].sum())*100
  97.     pop_ = np.array(pop_)
  98.     pop_ = pop_[pop_[:,36].argsort(),]
  99.     return pop_    
  100. def Range_roleta(pop__):
  101.     i=0
  102.     soma = 0
  103.     for i in range(len(pop__)):
  104.         if i == 0:
  105.             soma = soma + pop__[i,37]
  106.             pop__[i,38] = 0
  107.             pop__[i,39] = soma
  108.         elif i == len(pop__)-1:
  109.             pop[i,38] = soma
  110.             pop[i,39] = 100
  111.         else:
  112.             pop__[i,38] = soma
  113.             pop__[i,39] = soma + pop__[i,37]
  114.             soma =  soma + pop__[i,37]
  115.    
  116.     return pop        
  117.  
  118.  
  119. def roleta (pop___,elitismo = False):
  120.     global pop_size
  121.     ind = []
  122.     if elitismo == False:
  123.         for i in range(pop_size):
  124.             r =np.random.random()*100
  125.             for ii in range(len(pop___)):
  126.                 if (r >= pop___[ii,38]) & (r <= pop___[ii,39]):
  127.                     ind.append(pop___[ii,:])
  128.     else:
  129.         for i in range(len(pop___)-1,len(pop___)-6,-1):
  130.                 ind.append(pop___[i,:])
  131.         for j in range(pop_size-5):
  132.            
  133.             r =np.random.random()*100    
  134.             for ii in range(len(pop___)):
  135.                 if (r >= pop___[ii,38]) & (r <= pop___[ii,39]):
  136.                     ind.append(pop___[ii,:])                
  137.     return np.array(ind)        
  138.  
  139.  
  140. def selecao(pop____,elitismo = False):
  141.     pop____ = Range_roleta(pop____)
  142.     nextgen_ = roleta(pop____,elitismo)
  143.     return nextgen_
  144.  
  145. def melhor (popu):
  146.     melhor = -1
  147.     for i in range(len(popu)):
  148.         if  np.all(popu[i,36].max() >= melhor):
  149.              melhor = popu[i,:]
  150.     melhor = melhor.reshape(1,40)        
  151.     return melhor,melhor[0,36].max()        
  152.  
  153.  
  154.  
  155.  
  156.  
  157.  
  158.  
  159.  
  160.  
  161.  
  162.  
  163. geracoes = 1000
  164. inicio = time.time()
  165. pop_size = 100
  166. best = []
  167. mediaglobal =[]
  168. besti = 0
  169. newpop = gera_pop(pop_size)
  170. bad=[]    
  171. for i in range(geracoes):
  172.    
  173.     if besti >= 1:
  174.         break
  175.     pop = mescle(newpop)
  176.     best.append(pop[:,36].max())
  177.     bad.append(pop[:,36].min())
  178.     mediapop = pop[:,36].mean()
  179.     mediaglobal.append(mediapop)
  180.     print("Geracoes: " +str(i))
  181.     print("Media Global: "+ str(mediapop))
  182.     newpop = selecao(pop,1)
  183.     indm,besti = melhor(newpop)
  184.  
  185.  
  186. bad = np.array(bad).T
  187. best = np.array(best).T
  188. media = np.array(mediaglobal).T
  189. x = np.arange(media.size)
  190. fig1,ax1 = plt.subplots()
  191. ax1.grid(True)
  192. plt.title('AG')
  193. plt.xlabel('Geração')
  194. plt.ylabel('Media')
  195. ax1.plot(x,media,"r",x,best,"b",x,bad,"k")
  196. ax1.legend(('Media Global', 'Melhor Individuo',"Pior Individuo"), shadow=True)
  197. plt.show()
  198.  
  199. final=indm.reshape(10,4)
  200.  
  201. botoes=[BitArray(final[0,:]).uint,BitArray(final[1,:]).uint,BitArray(final[2,:]).uint,
  202.         BitArray(final[3,:]).uint,BitArray(final[4,:]).uint,BitArray(final[5,:]).uint,
  203.         BitArray(final[6,:]).uint,BitArray(final[7,:]).uint,BitArray(final[8,:]).uint]
  204.  
  205. fim = time.time()
  206. print("Tempo final: " +str(fim - inicio))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement