BFOIndividual.py

 import numpy as np
import ObjFunction class BFOIndividual: '''
individual of baterial clony foraging algorithm
''' def __init__(self, vardim, bound):
'''
vardim: dimension of variables
bound: boundaries of variables
'''
self.vardim = vardim
self.bound = bound
self.fitness = 0.
self.trials = 0 def generate(self):
'''
generate a random chromsome for baterial clony foraging algorithm
'''
len = self.vardim
rnd = np.random.random(size=len)
self.chrom = np.zeros(len)
for i in xrange(0, len):
self.chrom[i] = self.bound[0, i] + \
(self.bound[1, i] - self.bound[0, i]) * rnd[i] def calculateFitness(self):
'''
calculate the fitness of the chromsome
'''
# self.fitness = ObjFunction.GrieFunc(
# self.vardim, self.chrom, self.bound)
s1 = 0.
s2 = 1.
for i in range(1, self.vardim + 1):
s1 = s1 + self.chrom[i - 1] ** 2
s2 = s2 * np.cos(self.chrom[i - 1] / np.sqrt(i))
y = (1. / 4000.) * s1 - s2 + 1
self.fitness = y

BFO.py

 import numpy as np
from BFOIndividual import BFOIndividual
import random
import copy
import matplotlib.pyplot as plt
import math class BacterialForagingOptimization: '''
The class for baterial foraging optimization algorithm
''' def __init__(self, sizepop, vardim, bound, params):
'''
sizepop: population sizepop
vardim: dimension of variables
bound: boundaries of variables
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]
'''
self.sizepop = sizepop
self.vardim = vardim
self.bound = bound
self.population = []
self.bestPopulation = []
self.accuFitness = np.zeros(self.sizepop)
self.fitness = np.zeros(self.sizepop)
self.params = params
self.trace = np.zeros(
(self.params[0] * self.params[1] * self.params[2], 2)) def initialize(self):
'''
initialize the population
'''
for i in xrange(0, self.sizepop):
ind = BFOIndividual(self.vardim, self.bound)
ind.generate()
self.population.append(ind) def evaluate(self):
'''
evaluation of the population fitnesses
'''
for i in xrange(0, self.sizepop):
self.population[i].calculateFitness()
self.fitness[i] = self.population[i].fitness def sortPopulation(self):
'''
sort population according descending order
'''
sortedIdx = np.argsort(self.accuFitness)
newpop = []
newFitness = np.zeros(self.sizepop)
for i in xrange(0, self.sizepop):
ind = self.population[sortedIdx[i]]
newpop.append(ind)
self.fitness[i] = ind.fitness
self.population = newpop def solve(self):
'''
evolution process of baterial clony foraging algorithm
'''
self.t = 0
self.initialize()
self.evaluate()
bestIndex = np.argmin(self.fitness)
self.best = copy.deepcopy(self.population[bestIndex]) for i in xrange(0, self.params[0]):
for j in xrange(0, self.params[1]):
for k in xrange(0, self.params[2]):
self.t += 1
self.chemotaxls()
self.evaluate()
best = np.min(self.fitness)
bestIndex = np.argmin(self.fitness)
if best < self.best.fitness:
self.best = copy.deepcopy(self.population[bestIndex])
self.avefitness = np.mean(self.fitness)
self.trace[self.t - 1, 0] = self.best.fitness
self.trace[self.t - 1, 1] = self.avefitness
print("Generation %d: optimal function value is: %f; average function value is %f" % (
self.t, self.trace[self.t - 1, 0], self.trace[self.t - 1, 1]))
self.reproduction()
self.eliminationAndDispersal() print("Optimal function value is: %f; " %
self.trace[self.t - 1, 0])
print "Optimal solution is:"
print self.best.chrom
self.printResult() def chemotaxls(self):
'''
chemotaxls behavior of baterials
'''
for i in xrange(0, self.sizepop):
tmpInd = copy.deepcopy(self.population[i])
self.fitness[i] += self.communication(tmpInd)
Jlast = self.fitness[i]
rnd = np.random.uniform(low=-1, high=1.0, size=self.vardim)
phi = rnd / np.linalg.norm(rnd)
tmpInd.chrom += self.params[4] * phi
for k in xrange(0, self.vardim):
if tmpInd.chrom[k] < self.bound[0, k]:
tmpInd.chrom[k] = self.bound[0, k]
if tmpInd.chrom[k] > self.bound[1, k]:
tmpInd.chrom[k] = self.bound[1, k]
tmpInd.calculateFitness()
m = 0
while m < self.params[3]:
if tmpInd.fitness < Jlast:
Jlast = tmpInd.fitness
self.population[i] = copy.deepcopy(tmpInd)
# print m, Jlast
tmpInd.fitness += self.communication(tmpInd)
tmpInd.chrom += self.params[4] * phi
for k in xrange(0, self.vardim):
if tmpInd.chrom[k] < self.bound[0, k]:
tmpInd.chrom[k] = self.bound[0, k]
if tmpInd.chrom[k] > self.bound[1, k]:
tmpInd.chrom[k] = self.bound[1, k]
tmpInd.calculateFitness()
m += 1
else:
m = self.params[3]
self.fitness[i] = Jlast
self.accuFitness[i] += Jlast def communication(self, ind):
'''
cell to cell communication
'''
Jcc = 0.0
term1 = 0.0
term2 = 0.0
for j in xrange(0, self.sizepop):
term = 0.0
for k in xrange(0, self.vardim):
term += (ind.chrom[k] -
self.population[j].chrom[k]) ** 2
term1 -= self.params[6] * np.exp(-1 * self.params[7] * term)
term2 += self.params[8] * np.exp(-1 * self.params[9] * term)
Jcc = term1 + term2 return Jcc def reproduction(self):
'''
reproduction of baterials
'''
self.sortPopulation()
newpop = []
for i in xrange(0, self.sizepop / 2):
newpop.append(self.population[i])
for i in xrange(self.sizepop / 2, self.sizepop):
self.population[i] = newpop[i - self.sizepop / 2] def eliminationAndDispersal(self):
'''
elimination and dispersal of baterials
'''
for i in xrange(0, self.sizepop):
rnd = random.random()
if rnd < self.params[5]:
self.population[i].generate() def printResult(self):
'''
plot the result of the baterial clony foraging algorithm
'''
x = np.arange(0, self.t)
y1 = self.trace[:, 0]
y2 = self.trace[:, 1]
plt.plot(x, y1, 'r', label='optimal value')
plt.plot(x, y2, 'g', label='average value')
plt.xlabel("Iteration")
plt.ylabel("function value")
plt.title(
"Baterial clony foraging algorithm for function optimization")
plt.legend()
plt.show()

运行程序:

 if __name__ == "__main__":

     bound = np.tile([[-600], [600]], 25)
bfo = BFO(60, 25, bound, [2, 2, 50, 4, 50, 0.25, 0.1, 0.2, 0.1, 10])
bfo.solve()

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

细菌觅食算法-python实现的更多相关文章

  1. pageRank算法 python实现

    一.什么是pagerank PageRank的Page可是认为是网页,表示网页排名,也可以认为是Larry Page(google 产品经理),因为他是这个算法的发明者之一,还是google CEO( ...

  2. 常见排序算法-Python实现

    常见排序算法-Python实现 python 排序 算法 1.二分法     python    32行 right = length-  :  ]   ):  test_list = [,,,,,, ...

  3. kmp算法python实现

    kmp算法python实现 kmp算法 kmp算法用于字符串的模式匹配,也就是找到模式字符串在目标字符串的第一次出现的位置比如abababc那么bab在其位置1处,bc在其位置5处我们首先想到的最简单 ...

  4. KMP算法-Python版

                               KMP算法-Python版 传统法: 从左到右一个个匹配,如果这个过程中有某个字符不匹配,就跳回去,将模式串向右移动一位.这有什么难的? 我们可以 ...

  5. 压缩感知重构算法之IRLS算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  6. 压缩感知重构算法之OLS算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  7. 压缩感知重构算法之CoSaMP算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  8. 压缩感知重构算法之IHT算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

  9. 压缩感知重构算法之SP算法python实现

    压缩感知重构算法之OMP算法python实现 压缩感知重构算法之CoSaMP算法python实现 压缩感知重构算法之SP算法python实现 压缩感知重构算法之IHT算法python实现 压缩感知重构 ...

随机推荐

  1. MongoDB学习(五)Linux环境安装MongoDB

    一.   下载 从http://www.mongodb.org/downloads地址中下载:mongodb-linux-x86_64-2.4.11.tar 二.  安装 1>设置mongoDB ...

  2. 最常用的DOS命令

    ping:利用它可以检查网络是否能够连通,用好它可以很好地帮助我们分析判定网络故障,如ping 127.0.0.1tracert:跟踪路由,查询到相应网站的服务器之间所需经过的路由器个数,如trace ...

  3. java9-4 包

    面试题: package,import,class有没有顺序关系? 有. package > import > class Package:只能有一个 import:可以有多个 class ...

  4. [转] Centos 6.4 python 2.6 升级到 2.7

    http://blog.csdn.net/jcjc918/article/details/11022345

  5. f2fs解析(八)node 管理器中的node_info

    free_info 功成身退,node_info顺利接班. // 这里还是蛮复杂的一件事,如果不搞清除的话,这个历史性的接班工作我们就接不上 上面说到 alloc_nid 和 alloc_nid_do ...

  6. WebApi 消息拦截

    最近公司要求对WebApi 实现服务端信息的监控(服务端信息拦截),由于本人之前没有做过这方便的相关项目所以在做的过程中也是困难重重,探索的过程也是非常痛苦的,好歹最终也算实现了这个功能.所以将这个分 ...

  7. The Skyline Problem

    A city's skyline is the outer contour of the silhouette formed by all the buildings in that city whe ...

  8. js 中常用的方法

    1..call() 将.call()点之前的属性或方法,继承给括号中的对象. 2.(function(){xxx})() 解释:包围函数(function(){})的第一对括号向脚本返回未命名的函数, ...

  9. 完成一个MVC+Nhibernate+Jquery-EasyUI信息发布系统

    一.最近学习了Jquery-EasyUI框架,结合之前用过的MVC3+Nhibernate做一个信息发布系统,对工作一年半的自己做一个总结吧!(也正好 供初学者学习!) 二.先上截图(系统简介),让大 ...

  10. Tuple的用法

    1经常有些类型只用一次,不想添加新类,可以使用Tuple. 例子: List<Tuple<string, string>> list = new List<Tuple&l ...