Allenfenqu/Code.py

68 lines
2.5 KiB
Python

# lenchrom = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
# print(type(lenchrom))
# 假设重复的行为 [1, 2, 3, 4]
# n = 40
# repeated_row = np.array([1, 8])
# bound = np.repeat([repeated_row], n, axis=0)
def Code(lenchrom, bound,final_partitions):
import numpy as np
from test import test
adr = np.load('adr.npy') # load adr
flag = 0 # Initialize flag variable to 0 for controlling the loop
while flag == 0:
# Randomly generate an array a with the length of the first column of bound
# and each element is a random integer between 1 and length(bound[:, 0])
a = np.random.permutation(len(bound[:, 0]))+1
# Truncate the length of a to the number of elements in the second entry of the first row of bound
a = a[:bound[0, 1]]
# Create a zero array ret with the length of the first column of elements in bound
ret = np.zeros(len(bound[:, 0]), dtype=int)
# Calculate the number of 0s in array ret and assign the result to variable x
x = len(np.where(ret == 0)[0])
for i in range(len(a)):
# Assign i to the element of ret with index a[i]
ret[a[i]-1] = i + 1
failed_attempts = 1
while x > 0:
for i in range(len(a)):
try:
# Select rows from adr that satisfy the condition ret == i
add = adr[np.where(ret == i + 1)]
# Find the positions of non-zero elements in add and store them in m and n
m, n = np.where(add != 0)
# Find unique elements in n and store them in add
add = np.unique(n)
# Find the positions of 0 in ret and store them in addc
addc = np.where(ret == 0)[0]
add = np.intersect1d(add, addc)
# Randomly generate a permutation of the length of add and store the result in variable m
m = np.random.permutation(len(add))+1
add = add[m[0]-1]
ret[add] = i + 1
except:
failed_attempts += 1
if failed_attempts==1000:
return print('code failed')
continue
x = len(np.where(ret == 0)[0])
# Test the feasibility of the chromosome
flag = test(lenchrom, bound, ret,final_partitions)
return ret