Pythonはハエアルゴリズムを実現する

1634 ワード

import numpy as np
import matplotlib.pyplot as plt
#        (   fun1)
def fun1(arr):
    y = 2*arr**2-1
    return y
#######    ######
##       
popsize = 30  #      
maxgen = 100  #        
R = 1        #      
D = 1        #      
X = np.zeros([popsize,D])
Dist = np.zeros([popsize,D])
S = np.zeros([popsize,D])
Smell = np.zeros([popsize,1])
X = np.zeros([popsize,D])
Y = np.zeros([popsize,D])
fitness = np.zeros([maxgen,1])
#          
X_axis = np.random.rand(1,D)
Y_axis = np.random.rand(1,D)
#          
for i in range(popsize):
    X[i,:] = X_axis + R*(2*np.random.rand(1,D)-1)
    Y[i,:] = Y_axis + R*(2*np.random.rand(1,D)-1)
    #    Dist
    Dist[i,:] = np.sqrt(X[i,:]**2+Y[i,:]**2)
    #                  
    S[i,:] = 1/Dist[i,:]
    #                
    Smell[i] = fun1(S[i,:])
#         
Smellbest,index = np.min(Smell),np.argmin(Smell)
bestSmell = Smellbest
#            
X_axis = X[int(index),:]
Y_axis = Y[int(index),:]
#          
for j in range(maxgen):
    for i in range(popsize):
        X[i,:] = X_axis + R*(2*np.random.rand(1,D)-1)
        Y[i,:] = Y_axis + R*(2*np.random.rand(1,D)-1)
        #    Dist
        Dist[i,:] = np.sqrt(X[i,:]**2+Y[i,:]**2)
        #                  
        S[i,:] = 1/Dist[i,:]
        #                
        Smell[i] = fun1(S[i,:])
    Smellbest,index = np.min(Smell),np.argmin(Smell)
    if Smellbest < bestSmell:
        bestSmell = Smellbest
        X_axis = X[int(index),:]
        Y_axis = Y[int(index),:]
    fitness[j] = bestSmell
plt.figure(1)
plt.plot(range(maxgen),fitness)
plt.xlabel('    ')
plt.ylabel('     ')