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. android stuio eclipse映射下的快捷键

    转:关于 android stuio eclipse映射下的快捷键 http://www.cnblogs.com/0616--ataozhijia/p/3870064.html 会持续更新)这边讲的常 ...

  2. sublime配置全攻略

    大家好,今天给大家分享一款编辑器:sublime text2     我用过很多编辑器, EditPlus.EmEditor.Notepad++.Notepad2.UltraEdit.Editra.V ...

  3. 关于URL编码/javascript/js url 编码

    一.问题的由来 URL就是网址,只要上网,就一定会用到. 一般来说,URL只能使用英文字母.阿拉伯数字和某些标点符号,不能使用其他文字和符号.比如,世界上有英文字母的网址 “http://www.ab ...

  4. Netty5-应答服务器

    需求: 服务端:接收客户端请求,返回当前系统时间 客户端:发起时间请求 服务端 package org.zln.netty.five.timer; import io.netty.bootstrap. ...

  5. 19SpringMvc_在业务控制方法中收集List集合中包含JavaBean参数

    本文要实现的功能是给一张表单:

  6. Qt——右键菜单

    所谓“右键菜单”,我们可以这样来看:右键+菜单.所以我们可以定义一个菜单,然后重写鼠标点击事件,令菜单在鼠标右击的时候弹出来.这种方法是可以的,但是Qt提供了一种专门用于右键菜单的方法,且看下面这个属 ...

  7. 构建基于WCF Restful Service的服务

    前言 传统的Asmx服务,由于遵循SOAP协议,所以返回内容以xml方式组织.并且客户端需要添加服务端引用才能使用(虽然看到网络上已经提供了这方面的Dynamic Proxy,但是没有这种方式简便), ...

  8. [CareerCup] 11.8 The Rank of Number 数的排行

    11.8 Imagine you are reading in a stream of integers. Periodically, you wish to be able to look up t ...

  9. 20135202闫佳歆--week 9 期中总结

    期中总结 前半学期的主要学习内容是学习mooc课程<Linux内核分析>以及课本<Linux内核设计与实现>. 所涉及知识点总结如下: 1. Linux内核启动的过程--以Me ...

  10. Opencv step by step - 图像融合

    两个图像的融合就是像素的融合了,其实手动操作即可,用函数操作更方便了. 下面代码的作用是融合阿狸和doctor,很和谐有木有! #include <cv.h> #include <h ...