能不能教教我怎么改
import pandas as pd
import numpy as np
from deap import base, creator, tools, algorithms
# 读取Excel文件
data_structure = pd.read_excel('1_CaseStructure.xls')
data_cost = pd.read_excel('1_CaseCost.xls')
# 提取相关数据
CostMH = data_cost[['Receiving', 'Stockkeeping', 'Picking', 'Shipping']].values
CostFixed = data_cost[['Facil/Maint', 'Sq. Feet', 'Fixed Labor', 'Salary']].values
CostTran1 = data_cost[['Truck', 'Rail', 'cost']].values
CostTran2 = data_cost[['Fixed', 'Routes', 'Short Trip', 'Regular Trip']].values
ThruInv = data_cost[['Thru$ (000)', 'Inv$ (000)', 'ThruPc (000)', 'InvPc (000)']].values
# 定义地理位置范围
X_RANGE = (0, 1000)
Y_RANGE = (0, 1000)
# 创建适应度函数
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
# 初始化工具集
toolbox = base.Toolbox()
toolbox.register("attr_float", np.random.uniform, X_RANGE[0], X_RANGE[1])
toolbox.register("attr_float_y", np.random.uniform, Y_RANGE[0], Y_RANGE[1])
toolbox.register("individual", tools.initCycle, creator.Individual, (toolbox.attr_float, toolbox.attr_float_y), n=len(data_structure))
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
# 计算各项成本的函数
def calculate_costs(individual):
x_coords = [ind[0] for ind in individual]
y_coords = [ind[1] for ind in individual]
# 1. 材料处理成本
MH_cost = np.zeros(len(x_coords))
for i in range(len(x_coords)):
MH_cost[i] = np.sum(CostMH[i] * [data_structure.loc[i, 'Receiving'], data_structure.loc[i, 'Stockkeeping'],
data_structure.loc[i, 'Picking'], data_structure.loc[i, 'Shipping']]) * 21
# 2. 固定建立成本
Fixed_cost = np.sum(CostFixed[:, 0] + CostFixed[:, 1] * np.array(x_coords) + CostFixed[:, 2] * np.array(y_coords) + CostFixed[:, 3])
# 3. 入境运输成本
Tran1_cost = 0
for i in range(len(data_structure)):
from_idx = np.where(data_structure['ID'] == data_structure.loc[i, 'FromID'])[0][0]
to_idx = np.where(data_structure['ID'] == data_structure.loc[i, 'ToID'])[0][0]
distance = np.sqrt((x_coords[from_idx] - x_coords[to_idx])**2 + (y_coords[from_idx] - y_coords[to_idx])**2)
Tran1_cost += CostTran1[i]['cost'] * distance * data_structure.loc[i, 'demand']
# 4. 库存持有成本(DCs)
Inv_cost = np.sum(ThruInv * np.array(x_coords))
# 5. 运输途中库存成本(假设与运输距离相关,此处简单计算为距离乘以单位成本)
Transit_inv_cost = 0
for i in range(len(data_structure)):
from_idx = np.where(data_structure['ID'] == data_structure.loc[i, 'FromID'])[0][0]
to_idx = np.where(data_structure['ID'] == data_structure.loc[i, 'ToID'])[0][0]
distance = np.sqrt((x_coords[from_idx] - x_coords[to_idx])**2 + (y_coords[from_idx] - y_coords[to_idx])**2)
Transit_inv_cost += distance * 10 # 假设单位距离的库存成本为10
# 6. 出境运输成本
Tran2_cost = 0
for i in range(len(data_structure)):
from_idx = np.where(data_structure['ID'] == data_structure.loc[i, 'FromID'])[0][0]
to_idx = np.where(data_structure['ID'] == data_structure.loc[i, 'ToID'])[0][0]
distance = np.sqrt((x_coords[from_idx] - x_coords[to_idx])**2 + (y_coords[from_idx] - y_coords[to_idx])**2)
Tran2_cost += (CostTran2[i]['Fixed'] + CostTran2[i]['Routes'] * distance * (CostTran2[i]['Short Trip'] + CostTran2[i]['Regular Trip']))
total_cost = MH_cost + Fixed_cost + Tran1_cost + Inv_cost + Transit_inv_cost + Tran2_cost
return total_cost,
# 注册操作
toolbox.register("evaluate", calculate_costs)
toolbox.register("mate", tools.cxTwoPoint)
toolbox.register("mutate", tools.mutGaussian, mu=0, sigma=10, indpb=0.1)
toolbox.register("select", tools.selTournament, tournsize=3)
def main():
# 初始化种群
pop = toolbox.population(n=100)
# 定义遗传算法参数
num_generations = 100
crossover_prob = 0.8
mutation_prob = 0.2
# 运行遗传算法
for generation in range(num_generations):
offspring = algorithms.varAnd(pop, toolbox, cxpb=crossover_prob, mutpb=mutation_prob)
fits = toolbox.map(toolbox.evaluate, offspring)
for fit, ind in zip(fits, offspring):
ind.fitness.values = fit
pop = toolbox.select(offspring, len(pop))
# 找到最优解
best_individual = tools.selBest(pop, 1)[0]
x_coords = [ind[0] for ind in best_individual]
y_coords = [ind[1] for ind in best_individual]
# 计算最优成本
best_cost = calculate_costs(best_individual)[0]
print("最优仓库位置:")
for i in range(len(x_coords)):
print(f"仓库 {i + 1}: x = {x_coords[i]}, y = {y_coords[i]}")
print("最小总成本:", best_cost)
if __name__ == "__main__":
main()