细菌觅食算法-python实现

BFOIndividual.py

 1 import numpy as np
 2 import ObjFunction
 3 
 4 
 5 class BFOIndividual:
 6 
 7     '''
 8     individual of baterial clony foraging algorithm
 9     '''
10 
11     def __init__(self,  vardim, bound):
12         '''
13         vardim: dimension of variables
14         bound: boundaries of variables
15         '''
16         self.vardim = vardim
17         self.bound = bound
18         self.fitness = 0.
19         self.trials = 0
20 
21     def generate(self):
22         '''
23         generate a random chromsome for baterial clony foraging algorithm
24         '''
25         len = self.vardim
26         rnd = np.random.random(size=len)
27         self.chrom = np.zeros(len)
28         for i in xrange(0, len):
29             self.chrom[i] = self.bound[0, i] + \
30                 (self.bound[1, i] - self.bound[0, i]) * rnd[i]
31 
32     def calculateFitness(self):
33         '''
34         calculate the fitness of the chromsome
35         '''
36         # self.fitness = ObjFunction.GrieFunc(
37         #     self.vardim, self.chrom, self.bound)
38         s1 = 0.
39         s2 = 1.
40         for i in range(1, self.vardim + 1):
41             s1 = s1 + self.chrom[i - 1] ** 2
42             s2 = s2 * np.cos(self.chrom[i - 1] / np.sqrt(i))
43         y = (1. / 4000.) * s1 - s2 + 1
44         self.fitness = y

BFO.py

  1 import numpy as np
  2 from BFOIndividual import BFOIndividual
  3 import random
  4 import copy
  5 import matplotlib.pyplot as plt
  6 import math
  7 
  8 
  9 class BacterialForagingOptimization:
 10 
 11     '''
 12     The class for baterial foraging optimization algorithm
 13     '''
 14 
 15     def __init__(self, sizepop, vardim, bound, params):
 16         '''
 17         sizepop: population sizepop
 18         vardim: dimension of variables
 19         bound: boundaries of variables
 20         param: algorithm required parameters, it is a list which is consisting of [Ned, Nre, Nc, Ns, C, ped, d_attract, w_attract, d_repellant, w_repellant]
 21         '''
 22         self.sizepop = sizepop
 23         self.vardim = vardim
 24         self.bound = bound
 25         self.population = []
 26         self.bestPopulation = []
 27         self.accuFitness = np.zeros(self.sizepop)
 28         self.fitness = np.zeros(self.sizepop)
 29         self.params = params
 30         self.trace = np.zeros(
 31             (self.params[0] * self.params[1] * self.params[2], 2))
 32 
 33     def initialize(self):
 34         '''
 35         initialize the population
 36         '''
 37         for i in xrange(0, self.sizepop):
 38             ind = BFOIndividual(self.vardim, self.bound)
 39             ind.generate()
 40             self.population.append(ind)
 41 
 42     def evaluate(self):
 43         '''
 44         evaluation of the population fitnesses
 45         '''
 46         for i in xrange(0, self.sizepop):
 47             self.population[i].calculateFitness()
 48             self.fitness[i] = self.population[i].fitness
 49 
 50     def sortPopulation(self):
 51         '''
 52         sort population according descending order
 53         '''
 54         sortedIdx = np.argsort(self.accuFitness)
 55         newpop = []
 56         newFitness = np.zeros(self.sizepop)
 57         for i in xrange(0, self.sizepop):
 58             ind = self.population[sortedIdx[i]]
 59             newpop.append(ind)
 60             self.fitness[i] = ind.fitness
 61         self.population = newpop
 62 
 63     def solve(self):
 64         '''
 65         evolution process of baterial clony foraging algorithm
 66         '''
 67         self.t = 0
 68         self.initialize()
 69         self.evaluate()
 70         bestIndex = np.argmin(self.fitness)
 71         self.best = copy.deepcopy(self.population[bestIndex])
 72 
 73         for i in xrange(0, self.params[0]):
 74             for j in xrange(0, self.params[1]):
 75                 for k in xrange(0, self.params[2]):
 76                     self.t += 1
 77                     self.chemotaxls()
 78                     self.evaluate()
 79                     best = np.min(self.fitness)
 80                     bestIndex = np.argmin(self.fitness)
 81                     if best < self.best.fitness:
 82                         self.best = copy.deepcopy(self.population[bestIndex])
 83                     self.avefitness = np.mean(self.fitness)
 84                     self.trace[self.t - 1, 0] = self.best.fitness
 85                     self.trace[self.t - 1, 1] = self.avefitness
 86                     print("Generation %d: optimal function value is: %f; average function value is %f" % (
 87                         self.t, self.trace[self.t - 1, 0], self.trace[self.t - 1, 1]))
 88                 self.reproduction()
 89             self.eliminationAndDispersal()
 90 
 91         print("Optimal function value is: %f; " %
 92               self.trace[self.t - 1, 0])
 93         print "Optimal solution is:"
 94         print self.best.chrom
 95         self.printResult()
 96 
 97     def chemotaxls(self):
 98         '''
 99         chemotaxls behavior of baterials
100         '''
101         for i in xrange(0, self.sizepop):
102             tmpInd = copy.deepcopy(self.population[i])
103             self.fitness[i] += self.communication(tmpInd)
104             Jlast = self.fitness[i]
105             rnd = np.random.uniform(low=-1, high=1.0, size=self.vardim)
106             phi = rnd / np.linalg.norm(rnd)
107             tmpInd.chrom += self.params[4] * phi
108             for k in xrange(0, self.vardim):
109                 if tmpInd.chrom[k] < self.bound[0, k]:
110                     tmpInd.chrom[k] = self.bound[0, k]
111                 if tmpInd.chrom[k] > self.bound[1, k]:
112                     tmpInd.chrom[k] = self.bound[1, k]
113             tmpInd.calculateFitness()
114             m = 0
115             while m < self.params[3]:
116                 if tmpInd.fitness < Jlast:
117                     Jlast = tmpInd.fitness
118                     self.population[i] = copy.deepcopy(tmpInd)
119                     # print m, Jlast
120                     tmpInd.fitness += self.communication(tmpInd)
121                     tmpInd.chrom += self.params[4] * phi
122                     for k in xrange(0, self.vardim):
123                         if tmpInd.chrom[k] < self.bound[0, k]:
124                             tmpInd.chrom[k] = self.bound[0, k]
125                         if tmpInd.chrom[k] > self.bound[1, k]:
126                             tmpInd.chrom[k] = self.bound[1, k]
127                     tmpInd.calculateFitness()
128                     m += 1
129                 else:
130                     m = self.params[3]
131             self.fitness[i] = Jlast
132             self.accuFitness[i] += Jlast
133 
134     def communication(self, ind):
135         '''
136         cell to cell communication
137         '''
138         Jcc = 0.0
139         term1 = 0.0
140         term2 = 0.0
141         for j in xrange(0, self.sizepop):
142             term = 0.0
143             for k in xrange(0, self.vardim):
144                 term += (ind.chrom[k] -
145                          self.population[j].chrom[k]) ** 2
146             term1 -= self.params[6] * np.exp(-1 * self.params[7] * term)
147             term2 += self.params[8] * np.exp(-1 * self.params[9] * term)
148         Jcc = term1 + term2
149 
150         return Jcc
151 
152     def reproduction(self):
153         '''
154         reproduction of baterials
155         '''
156         self.sortPopulation()
157         newpop = []
158         for i in xrange(0, self.sizepop / 2):
159             newpop.append(self.population[i])
160         for i in xrange(self.sizepop / 2, self.sizepop):
161             self.population[i] = newpop[i - self.sizepop / 2]
162 
163     def eliminationAndDispersal(self):
164         '''
165         elimination and dispersal of baterials
166         '''
167         for i in xrange(0, self.sizepop):
168             rnd = random.random()
169             if rnd < self.params[5]:
170                 self.population[i].generate()
171 
172     def printResult(self):
173         '''
174         plot the result of the baterial clony foraging algorithm
175         '''
176         x = np.arange(0, self.t)
177         y1 = self.trace[:, 0]
178         y2 = self.trace[:, 1]
179         plt.plot(x, y1, 'r', label='optimal value')
180         plt.plot(x, y2, 'g', label='average value')
181         plt.xlabel("Iteration")
182         plt.ylabel("function value")
183         plt.title(
184             "Baterial clony foraging algorithm for function optimization")
185         plt.legend()
186         plt.show()

 运行程序:

1 if __name__ == "__main__":
2 
3     bound = np.tile([[-600], [600]], 25)
4     bfo = BFO(60, 25, bound,  [2, 2, 50, 4, 50, 0.25, 0.1, 0.2, 0.1, 10])
5     bfo.solve()

 

ObjFunction见简单遗传算法-python实现

posted on 2015-10-06 22:39  Alex Yu  阅读(3527)  评论(2编辑  收藏  举报

导航