能不能教教我怎么改

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()

全部评论
哥们,这样一大坨谁都不想看呀
点赞 回复 分享
发布于 2024-10-28 02:14 广东

相关推荐

不愿透露姓名的神秘牛友
07-11 12:31
以前小时候我最痛恨出轨、偷情的人,无论男女,为什么会出轨?现在我成了自己最讨厌的人,没想到分享的东西在牛客会被这么多人看,大家的评价都很中肯,我也认同,想过一一回复,但我还是收声了,我想我应该说说这件事,这件事一直压在我心里,是个很大的心结,上面说了人为什么出轨,我大概能明白了。我们大一下半年开始恋爱,开始恋爱,我给出了我铭记3年的承诺,我对她好一辈子,我永远不会背叛,我责任心太重,我觉得跟了我,我就要照顾她一辈子,我们在一起3年我都没有碰过她,她说往东我就往东,她说什么我做什么,她要我干什么,我就干什么!在学校很美好,中途也出过一些小插曲,比如男闺蜜、男闺蜜2号等等等。但我都强迫她改掉了,我...
牛客刘北:两个缺爱的人是没有办法好好在一起的,但世界上哪有什么是非对错?你后悔你们在一起了,但是刚刚在一起的美好也是真的呀,因为其他人的出现,你开始想要了最开始的自己,你的确对不起自己,21岁的你望高物远,你完全可以不谈恋爱,去过你想要的生活,你向往自由,在一起之后,你要想的不是一个人,而是两个人,你不是变心了,就像你说的,你受够了,你不想包容了,冷静几天是你最优的选择,爱人先爱己。
社会教会你的第一课
点赞 评论 收藏
分享
今天 12:15
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务