الگوریتم بهینه سازی BBO به زبان پایتون
دانلود
حجم: 2.9 کیلوبایت
# ------------------------ Objective Function= e(-x)*sin(2*pi*x)---------------------
import numpy as np
import random
import datetime
import math
a = datetime.datetime.now();
Xmax=6*np.ones((1,5) ,dtype=float);
Xmin=0*np.ones((1,5) ,dtype=float);
n=Xmax.size;
N=200;cc=0;ccc=0;
Iter_max=500;
miu=0.1;
MU=np.linspace(0,1,N);
alpha=0.9;
Cost_new=np.zeros((N,1),dtype=float);
#-------------------------------- create initial population---- start
Ipop=(Xmax-Xmin)*np.random.uniform(0,1,(N,n))+Xmin;
#--------------------------------objective Function------ Start
Cost=((np.exp(-Ipop)*np.sin(2*math.pi*Ipop)).sum(axis=1)).reshape(N,1);
#--------------------------------objective Function------ End
Ipop_mix=np.concatenate((Ipop, Cost), axis=1)
ind=np.argsort(Ipop_mix[:,-1])
Ipop_sort=Ipop_mix[ind];
Best1=Ipop_sort[0,:];
Best=Best1.copy();
ccc=ccc+1;
Ipop_select=Ipop_sort[0:N/2,:];
Ipop=np.zeros((N,n) ,dtype=float);
Ipop=Ipop_sort[0:N,0:n];
#-------------------------------- create initial population---- End
for Iter in range(0,Iter_max):
print(Iter)
Ipop_new=Ipop.copy();
for i in range(0,N):
for j in range(0,n):
if (1-MU[i])>=np.random.uniform(0,1,(1,1)):
EP=MU.copy();
EP[i]=0;
EP=EP/EP.sum();
EP=EP.cumsum(axis=0);
k=np.where((np.where(EP>np.random.uniform(0,1),1,0))==1)[0][0];
Ipop_new[i,j]=Ipop[i,j]+alpha*(Ipop[k,j]-Ipop[i,j]);
# ------------------- Mutation -------- start
kk=max(0,round(n*np.random.uniform(0,1))-1);
Xmax1=1.1*Ipop_new[i,:];
Xmin1=0.9*Ipop_new[i,:];
d=np.random.normal(0,1)*(Xmax1-Xmin1);
Ipop_new[i,kk]=Ipop_new[i,kk]+d[kk];
# ------------------- Mutation -------- End
Ipop_new=np.maximum(Xmin,Ipop_new);
Ipop_new=np.minimum(Xmax,Ipop_new);
#--------------------------------objective Function------ Start
Cost_new[i]=((np.exp(-Ipop_new[i,:])*np.sin(2*math.pi*Ipop_new[i,:])).sum(axis=0));
#--------------------------------objective Function------ End
Ipop_mix=np.zeros((N,n+1) ,dtype=float);
Ipop_mix=np.concatenate((Ipop_new, Cost_new), axis=1)
Ipop_mix=np.concatenate((Ipop_select, Ipop_mix), axis=0)
Ipop_sort=np.zeros((1.5*N,n+1) ,dtype=float);
ind=np.argsort(Ipop_mix[:,-1])
Ipop_sort=Ipop_mix[ind];
if Best[n]>Ipop_sort[0,n]:
cc=cc+1;
Best1=Ipop_sort[0,:];
Best=Best1.copy();
print(Best[n])
Ipop_select=np.zeros((N/2,n+1) ,dtype=float);
Ipop_select=Ipop_sort[0:N/2,:];
Ipop=np.zeros((N,n) ,dtype=float);
Ipop=Ipop_sort[0:N,0:n];
print('Final Best--------------')
print(Best.reshape(n+1,1))
print('cc:',cc)
b=datetime.datetime.now();
c=b-a;
print('Run Time (msec) : ',int(c.total_seconds()*1000));