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. 第25章 SEH结构化异常处理_未处理异常及向量化异常

    25.1 UnhandledExceptionFilter函数详解 25.1.1 BaseProcessStart伪代码(Kernel32内部) void BaseProcessStart(PVOID ...

  2. LYK 快跑!(LYK别打我-)(话说LYK是谁)

    LYK 快跑!(run) Time Limit:5000ms Memory Limit:64MB 题目描述 LYK 陷进了一个迷宫! 这个迷宫是网格图形状的. LYK 一开始在(1,1)位置, 出口在 ...

  3. JMeter中返回Json数据的处理方法

    Json 作为一种数据交换格式在网络开发,特别是 Ajax 与 Restful 架构中应用的越来越广泛.而 Apache 的 JMeter 也是较受欢迎的压力测试工具之一,但是它本身没有提供对于 Js ...

  4. WindowXP与WIN7环境安装、破解、配置AppScan8.0

    ---------------------------------------------------------------------------------------------------- ...

  5. [ORACLE错误]ORA-00001: unique constraint (...) violated并不一定是数据冲突

    遇到这种情况,重建完表和索引后,终于正常INSERT了.  prompt Importing table COUPON_ACTIVITYset feedback offset define offin ...

  6. c#中结构体(struct)和类(class)的区别

    一.类与结构的示例比较: 结构示例: public struct Person { string Name; int height; int weight public bool overWeight ...

  7. Linux下检测IP地址冲突及解决方法

    问题说明:在公司办公网内的一台物理机A上安装了linux系统(ip:192.168.9.120),在上面部署了jenkins,redmine,svn程序.由于是在办公网内,这台机器和同事电脑都是在同一 ...

  8. eval() 函数

    eval() 函数可计算某个字符串,并执行其中的的 JavaScript 代码. var str = '12+45*45'; alert(eval(str))//计算结果 还有一个重要作用可以把字符串 ...

  9. Eclipse调试按钮消失问题

    Window-->Reset Perspective 把Eclipse重置一下,然后 点击红色框圈的向下的箭头,在弹出的菜单里边,点击 show debug toolbar 这个菜单项目,然后奇 ...

  10. C语言 百炼成钢10

    //题目28:有5个人坐在一起,问第五个人多少岁?他说比第4个人大2岁.问第4个人岁数,他说比第 //3个人大2岁.问第三个人,又说比第2人大两岁.问第2个人,说比第一个人大两岁.最后 //问第一个人 ...