import random
population_size = 2000 # 基因種群大小
chromosome_length = 10 # 基因染色體長度
num_orders = 10 # 訂單數
mutation_rate = 0.01 # 基因突變率
max_generations = 1000 # 最大迭代次數
# 生成初始種群
def generate_initial_population():
population = []
for _ in range(population_size):
chromosome = []
selected_orders = set() # 用于跟踪已选择的订单
for _ in range(chromosome_length):
order = random.randint(1, num_orders) # 随机选择一个订单
while order in selected_orders: # 如果订单已被选择过,则重新选择
order = random.randint(1, num_orders)
selected_orders.add(order) # 将已选择的订单添加到集合中
machine = random.randint(1, 2) # 选择机台1或机台2
chromosome.append((order, machine))
population.append(chromosome)
return population
# 基因交配
def crossover(parent1, parent2):
point = random.randint(1, chromosome_length - 1)
child1 = parent1[:point] + parent2[point:]
child2 = parent2[:point] + parent1[point:]
return child1, child2
# 基因突變
def mutate(chromosome):
for i in range(chromosome_length):
order, machine = chromosome[i]
if random.random() < mutation_rate:
order = random.randint(1, num_orders) # 根据实际订单数量设定范围
if random.random() < mutation_rate:
machine = random.randint(1, 2)
chromosome[i] = (order, machine)
return chromosome
# 解碼染色體為排程
def decode_chromosome(chromosome):
order_sequence = []
machine_selection = []
for gene in chromosome:
order, machine = gene
order_sequence.append(order)
machine_selection.append(machine)
return order_sequence, machine_selection
# 修改後的 genetic_algorithm 函數
def genetic_algorithm():
population = generate_initial_population()
# 執行基因演算法的主循環
generation = 0 # 迭代計數器
while generation < max_generations:
# 選擇交配的父母
parent1 = random.choice(population)
parent2 = random.choice(population)
# 基因交配
child1, child2 = crossover(parent1, parent2)
# 基因突變
child1 = mutate(child1)
child2 = mutate(child2)
# 更新種群
population.append(child1)
population.append(child2)
# 缩减種群大小至原始規模
population = population[:population_size]
# 增加迭代計數器
generation += 1
best_chromosome = population[0] # 取第一个染色体作为最佳染色体
return best_chromosome
# 執行基因算法
best_chromosome = genetic_algorithm()
# 解碼最佳染色體
decoded_best_chromosome = decode_chromosome(best_chromosome)
# 輸出最佳排程结果
print("Best Chromosome:", decoded_best_chromosome)