1 importnumpy as np2 from AFSIndividual importAFSIndividual3 importrandom4 importcopy5 importmatplotlib.pyplot as plt6
7
8 classArtificialFishSwarm:9
10 """class for ArtificialFishSwarm"""
11
12 def __init__(self, sizepop, vardim, bound, MAXGEN, params):13 ‘‘‘
14 sizepop: population sizepop15 vardim: dimension of variables16 bound: boundaries of variables, 2*vardim17 MAXGEN: termination condition18 params: algorithm required parameters, it is a list which is consisting of[visual, step, delta, trynum]19 ‘‘‘
20 self.sizepop =sizepop21 self.vardim =vardim22 self.bound =bound23 self.MAXGEN =MAXGEN24 self.params =params25 self.population =[]26 self.fitness = np.zeros((self.sizepop, 1))27 self.trace = np.zeros((self.MAXGEN, 2))28 self.lennorm = 6000
29
30 definitialize(self):31 ‘‘‘
32 initialize the population of afs33 ‘‘‘
34 for i inxrange(0, self.sizepop):35 ind =AFSIndividual(self.vardim, self.bound)36 ind.generate()37 self.population.append(ind)38
39 defevaluation(self, x):40 ‘‘‘
41 evaluation the fitness of the individual42 ‘‘‘
43 x.calculateFitness()44
45 defforage(self, x):46 ‘‘‘
47 artificial fish foraging behavior48 ‘‘‘
49 newInd =copy.deepcopy(x)50 found =False51 for i in xrange(0, self.params[3]):52 indi =self.randSearch(x, self.params[0])53 if indi.fitness >x.fitness:54 newInd.chrom = x.chrom + np.random.random(self.vardim) * self.params[1] * self.lennorm *(55 indi.chrom - x.chrom) / np.linalg.norm(indi.chrom -x.chrom)56 newInd =indi57 found =True58 break
59 if not(found):60 newInd = self.randSearch(x, self.params[1])61 returnnewInd62
63 defrandSearch(self, x, searLen):64 ‘‘‘
65 artificial fish random search behavior66 ‘‘‘
67 ind =copy.deepcopy(x)68 ind.chrom += np.random.uniform(-1, 1,69 self.vardim) * searLen *self.lennorm70 for j inxrange(0, self.vardim):71 if ind.chrom[j] self.bound[1, j]:74 ind.chrom[j] = self.bound[1, j]75 self.evaluation(ind)76 returnind77
78 defhuddle(self, x):79 ‘‘‘
80 artificial fish huddling behavior81 ‘‘‘
82 newInd =copy.deepcopy(x)83 dist =self.distance(x)84 index =[]85 for i in xrange(1, self.sizepop):86 if dist[i] > 0 and dist[i] < self.params[0] *self.lennorm:87 index.append(i)88 nf =len(index)89 if nf >0:90 xc =np.zeros(self.vardim)91 for i inxrange(0, nf):92 xc +=self.population[index[i]].chrom93 xc = xc /nf94 cind =AFSIndividual(self.vardim, self.bound)95 cind.chrom =xc96 cind.calculateFitness()97 if (cind.fitness / nf) > (self.params[2] *x.fitness):98 xnext = x.chrom +np.random.random(99 self.vardim) * self.params[1] * self.lennorm * (xc - x.chrom) / np.linalg.norm(xc -x.chrom)100 for j inxrange(0, self.vardim):101 if xnext[j] self.bound[1, j]:104 xnext[j] = self.bound[1, j]105 newInd.chrom =xnext106 self.evaluation(newInd)107 #print "hudding"
108 returnnewInd109 else:110 returnself.forage(x)111 else:112 returnself.forage(x)113
114 deffollow(self, x):115 ‘‘‘
116 artificial fish following behivior117 ‘‘‘
118 newInd =copy.deepcopy(x)119 dist =self.distance(x)120 index =[]121 for i in xrange(1, self.sizepop):122 if dist[i] > 0 and dist[i] < self.params[0] *self.lennorm:123 index.append(i)124 nf =len(index)125 if nf >0:126 best = -999999999.127 bestIndex =0128 for i inxrange(0, nf):129 if self.population[index[i]].fitness >best:130 best =self.population[index[i]].fitness131 bestIndex =index[i]132 if (self.population[bestIndex].fitness / nf) > (self.params[2] *x.fitness):133 xnext = x.chrom +np.random.random(134 self.vardim) * self.params[1] * self.lennorm * (self.population[bestIndex].chrom - x.chrom) / np.linalg.norm(self.population[bestIndex].chrom -x.chrom)135 for j inxrange(0, self.vardim):136 if xnext[j] self.bound[1, j]:139 xnext[j] = self.bound[1, j]140 newInd.chrom =xnext141 self.evaluation(newInd)142 #print "follow"
143 returnnewInd144 else:145 returnself.forage(x)146 else:147 returnself.forage(x)148
149 defsolve(self):150 ‘‘‘
151 evolution process for afs algorithm152 ‘‘‘
153 self.t =0154 self.initialize()155 #evaluation the population
156 for i inxrange(0, self.sizepop):157 self.evaluation(self.population[i])158 self.fitness[i] =self.population[i].fitness159 best =np.max(self.fitness)160 bestIndex =np.argmax(self.fitness)161 self.best =copy.deepcopy(self.population[bestIndex])162 self.avefitness =np.mean(self.fitness)163 self.trace[self.t, 0] = (1 - self.best.fitness) /self.best.fitness164 self.trace[self.t, 1] = (1 - self.avefitness) /self.avefitness165 print("Generation %d: optimal function value is: %f; average function value is %f" %(166 self.t, self.trace[self.t, 0], self.trace[self.t, 1]))167 while self.t < self.MAXGEN - 1:168 self.t += 1
169 #newpop = []
170 for i inxrange(0, self.sizepop):171 xi1 =self.huddle(self.population[i])172 xi2 =self.follow(self.population[i])173 if xi1.fitness >xi2.fitness:174 self.population[i] =xi1175 self.fitness[i] =xi1.fitness176 else:177 self.population[i] =xi2178 self.fitness[i] =xi2.fitness179 best =np.max(self.fitness)180 bestIndex =np.argmax(self.fitness)181 if best >self.best.fitness:182 self.best =copy.deepcopy(self.population[bestIndex])183 self.avefitness =np.mean(self.fitness)184 self.trace[self.t, 0] = (1 - self.best.fitness) /self.best.fitness185 self.trace[self.t, 1] = (1 - self.avefitness) /self.avefitness186 print("Generation %d: optimal function value is: %f; average function value is %f" %(187 self.t, self.trace[self.t, 0], self.trace[self.t, 1]))188
189 print("Optimal function value is: %f;" %self.trace[self.t, 0])190 print "Optimal solution is:"
191 printself.best.chrom192 self.printResult()193
194 defdistance(self, x):195 ‘‘‘
196 return the distance array to a individual197 ‘‘‘
198 dist =np.zeros(self.sizepop)199 for i inxrange(0, self.sizepop):200 dist[i] = np.linalg.norm(x.chrom - self.population[i].chrom) / 6000
201 returndist202
203 defprintResult(self):204 ‘‘‘
205 plot the result of afs algorithm206 ‘‘‘
207 x =np.arange(0, self.MAXGEN)208 y1 =self.trace[:, 0]209 y2 = self.trace[:, 1]210 plt.plot(x, y1, ‘r‘, label=‘optimal value‘)211 plt.plot(x, y2, ‘g‘, label=‘average value‘)212 plt.xlabel("Iteration")213 plt.ylabel("function value")214 plt.title("Artificial Fish Swarm algorithm for function optimization")215 plt.legend()216 plt.show()