# 飞蛾扑火优化算法

MFO的过程如下：
1.初始化飞蛾种群
2.对飞蛾种群进行适应度评价
3.重复如下过程直到达到停止标准：

3.1自适应更新火焰个数n，当迭代次数为1时，飞蛾个数即为火焰个数
3.2对飞蛾种群适应度进行排序，取出适应度较好的n个飞蛾作为火焰
3.3更新飞蛾的搜索参数。
3.4根据每只飞蛾对应的火焰与飞行参数更新飞蛾的位置
4.输出所得最优解(火焰)

# Moth-flame optimization algorithm
import random as rd
from math import exp, cos, pi
from copy import deepcopy

def ini(n, d):
population, fitness = [], []
for i in range(n):
moth = []
for j in range(d):
moth.append(rd.uniform(-10, 10))
population.append(moth)
return population

def getFitness(moths):
fitness = []
for i in range(len(moths)):
fitness.append(objFunction(moths[i]))
return fitness

def objFunction(moth):
objFunctionValue = 0
for i in range(len(moth)):
objFunctionValue += moth[i] ** 2
return objFunctionValue

def run():
number, dimension = 10, 10
b = 1
mothPopulation = ini(number, dimension)
iterx, maxIterx = 0, 100
while iterx < maxIterx:
mothFitness = getFitness(mothPopulation)
if iterx > 90:
elif iterx == 0:
else:
flameNumber = int((maxIterx - iterx) / 10) + 1
flamePopulation, flameFitness = getFlame(mothPopulation, mothFitness, flameNumber)

for i in range(number):
for j in range(dimension):
r = -1 - 0.01 * iterx
t = rd.uniform(r, 1)
if i < len(flamePopulation):
distance = abs(flamePopulation[i][j] - mothPopulation[i][j])
mothPopulation[i][j] = distance * exp(b * t) * cos(2 * pi * t) + flamePopulation[i][j]
mothPopulation[i][j] = check(mothPopulation[i][j])
else:
distance = abs(flamePopulation[0][j] - mothPopulation[i][j])
mothPopulation[i][j] = distance * exp(b * t) * cos(2 * pi * t) + flamePopulation[0][j]
mothPopulation[i][j] = check(mothPopulation[i][j])
iterx += 1
print(flamePopulation, flameFitness)

flamePopulation, flameFitness = [], []
fitness = deepcopy(mothFitness)
fitness.sort()
flameFitness.append(fitness[i])
flamePopulation.append(mothPopulation[mothFitness.index(fitness[i])])
return flamePopulation, flameFitness

def check(x):
if x < -10:
return -10
elif x > 10:
return 10
else:
return x

if __name__ == '__main__':
run()



Mirjalili S. Moth-flame optimization algorithm: A novel nature-inspired heuristic paradigm[J]. Knowledge-based systems, 2015, 89: 228-249.

05-30
04-21
04-22
05-26
10-12
01-09
04-20
12-04 2556