Allenfenqu/crossnew.py

77 lines
2.9 KiB
Python

import numpy as np
from test import test
def crossnew(pcross, lenchrom, chrom, sizepop, bound,final_partitions):
# 本函数完成交叉操作
# pcorss input : 交叉概率
# lenchrom input : 染色体的长度
# chrom input : 染色体群
# sizepop input : 种群规模
# ret output : 交叉后的染色体
#chrom=individuals.chrom
chrom = chrom.reshape(sizepop,-1)
for i in range(sizepop):
# 随机选择1个染色体进行交叉
# 交叉概率决定是否进行交叉
pick = np.random.rand()
while pick == 0:
pick = np.random.rand()
if pick > pcross:
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]
t = ek[a]
m = np.array(np.where(chrom[int(index), :] == ek[a]))
m = m[m != pick]
a = round(np.random.rand() * len(m))-1
while a == -1:
a = round(np.random.rand() * len(m))-1
chrom[int(index), m[a]] = exchangel
# 交叉结束
# test实现了对染色体编码值的可行性检验
# 具体来说,它通过检查每个变量的取值
flag1 = test(lenchrom, bound, chrom[int(index), :],final_partitions)
# Check the feasibility of chromosome 2
# flag2 = test(lenchrom, bound, chrom[index[1], :])
# If flag1 is 0
if flag1 == 0:
flag = 0
chrom[int(index), pick] = exchangel
chrom[int(index), m[a]] = t
# chrom[index[1], pos] = v2
else:
flag = 1
return chrom