forked from 7ossam81/EvoloPy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BAT.py
108 lines (75 loc) · 2.59 KB
/
BAT.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# -*- coding: utf-8 -*-
"""
Created on Thu May 26 02:00:55 2016
@author: hossam
"""
import math
import numpy
import random
import time
from solution import solution
def BAT(objf,lb,ub,dim,N,Max_iteration):
n=N; # Population size
#lb=-50
#ub=50
N_gen=Max_iteration # Number of generations
A=0.5; # Loudness (constant or decreasing)
r=0.5; # Pulse rate (constant or decreasing)
Qmin=0 # Frequency minimum
Qmax=2 # Frequency maximum
d=dim # Number of dimensions
# Initializing arrays
Q=numpy.zeros(n) # Frequency
v=numpy.zeros((n,d)) # Velocities
Convergence_curve=[];
# Initialize the population/solutions
Sol=numpy.random.rand(n,d)*(ub-lb)+lb
S=numpy.zeros((n,d))
S=numpy.copy(Sol)
Fitness=numpy.zeros(n)
# initialize solution for the final results
s=solution()
print("BAT is optimizing \""+objf.__name__+"\"")
# Initialize timer for the experiment
timerStart=time.time()
s.startTime=time.strftime("%Y-%m-%d-%H-%M-%S")
#Evaluate initial random solutions
for i in range(0,n):
Fitness[i]=objf(Sol[i,:])
# Find the initial best solution
fmin = min(Fitness)
I=numpy.argmin(fmin)
best=Sol[I,:]
# Main loop
for t in range (0,N_gen):
# Loop over all bats(solutions)
for i in range (0,n):
Q[i]=Qmin+(Qmin-Qmax)*random.random()
v[i,:]=v[i,:]+(Sol[i,:]-best)*Q[i]
S[i,:]=Sol[i,:]+v[i,:]
# Check boundaries
Sol=numpy.clip(Sol,lb,ub)
# Pulse rate
if random.random()>r:
S[i,:]=best+0.001*numpy.random.randn(d)
# Evaluate new solutions
Fnew=objf(S[i,:])
# Update if the solution improves
if ((Fnew<=Fitness[i]) and (random.random()<A) ):
Sol[i,:]=numpy.copy(S[i,:])
Fitness[i]=Fnew;
# Update the current best solution
if Fnew<=fmin:
best=S[i,:]
fmin=Fnew
#update convergence curve
Convergence_curve.append(fmin)
if (t%1==0):
print(['At iteration '+ str(t)+ ' the best fitness is '+ str(fmin)])
timerEnd=time.time()
s.endTime=time.strftime("%Y-%m-%d-%H-%M-%S")
s.executionTime=timerEnd-timerStart
s.convergence=Convergence_curve
s.optimizer="BAT"
s.objfname=objf.__name__
return s