Allenfenqu/mutationnew.py

62 lines
2.3 KiB
Python

import numpy as np
from test import test
def mutationnew(pmutation, lenchrom, chrom, sizepop, bound,final_partitions):
# 本函数完成交叉操作
# pcorss input : 交叉概率
# lenchrom input : 染色体的长度
# chrom input : 染色体群
# sizepop input : 种群规模
# ret output : 交叉后的染色体
#chrom=individuals.chrom
for i in range(sizepop):
# 随机选择1个染色体进行交叉
# 交叉概率决定是否进行交叉
pick = np.random.rand()
while pick == 0:
pick = np.random.rand()
if pick > pmutation:
continue
flag = 0
m = 0
while flag == 0:
pick = np.random.rand()
while np.prod(pick) == 0:
pick = np.random.rand()
index = np.ceil(pick * sizepop)-1
adr = np.load('adr.npy')
m += 1
# 随机选择交叉位置
lo = []
for d in range(len(adr)):
for e in range(len(adr)):
if adr[d, e] != 0:
adr[d, e] = chrom[int(index), e]
if len(np.unique(adr[d, :])) > 2:
lo.append(d)
a = round(np.random.rand() * len(lo))-1
while a == -1:
a = round(np.random.rand() * len(lo))-1
pick = lo[a] # 交叉位置
# 随机选择进行交叉的位置,即选择第几个变量进行交叉,注意:两个染色体交叉的位置相同
exchangel = chrom[int(index), pick] # 交叉位置所属区域
ek = np.unique(adr[pick, :]) # 交叉开始
ek = ek[ek != exchangel]
ek = ek[ek != 0]
a = round(np.random.rand() * len(ek))-1
while a == -1:
a = round(np.random.rand() * len(ek))-1
chrom[int(index), pick] = ek[a]
flag1 = test(lenchrom, bound, chrom[int(index), :],final_partitions)
# If flag1 is 0
if flag1 == 0:
flag = 0
chrom[int(index), pick] = exchangel
# chrom[index[1], pos] = v2
else:
flag = 1
return chrom