You need to enable JavaScript to run this app. PuLP二级仓配优化模型SKU分配决策变量与目标函数编写问题
优惠活动
大模型
产品
解决方案
定价
更多

PuLP二级仓配优化模型SKU分配决策变量与目标函数编写问题

第二级SKU层级PuLP线性规划模型实现

决策变量定义

KeyError: 'Fac-2'通常由变量遍历范围和参数字典Key不匹配、错误使用全量仓库列表而非第一级输出的chosen_facilities导致,正确变量定义如下:

import pulp

# 初始化最小化模型
model = pulp.LpProblem("SecondStage_SKU_Allocation", pulp.LpMinimize)

# 1. 决策变量1:各选中仓库的各SKU备货量 单位:件
# 维度:(选中仓库, SKU),下界为0
qty_sku_fac = pulp.LpVariable.dicts(
    "SKU_Stock",
    [(f, p) for f in chosen_facilities for p in Products],
    lowBound=0,
    cat="Continuous" # 若要求整数库存改为Integer
)

# 2. 决策变量2:各选中仓库向各客户供应的各SKU数量 单位:件
# 维度:(选中仓库, 客户, SKU),下界为0
qty_serv_customer = pulp.LpVariable.dicts(
    "SKU_Supply",
    [(f, c, p) for f in chosen_facilities for c in Customer for p in Products],
    lowBound=0,
    cat="Continuous" # 若要求整数供货量改为Integer
)

目标函数定义

目标为最小化总运输成本 + 小额备货固定成本(用于控制多仓备货阈值,实现就近优先存放),写法如下:

# 1. 运输成本求和:仓库到客户的单位运输成本 * 对应SKU供货量
transport_total = pulp.lpSum(
    [transportation_cost[(f, c)] * qty_serv_customer[(f, c, p)]
     for f in chosen_facilities
     for c in Customer
     for p in Products]
)

# 2. 备货固定成本计算(可选,不需要控制多仓阈值可直接删除)
# 辅助0/1变量:是否在某仓备货某SKU
is_sku_stocked = pulp.LpVariable.dicts(
    "IsStocked",
    [(f, p) for f in chosen_facilities for p in Products],
    cat="Binary"
)
# 关联约束需后续加入模型:备货量大于0时is_sku_stocked必须为1
for f in chosen_facilities:
    for p in Products:
        model += qty_sku_fac[(f, p)] <= total_product_demand[p] * is_sku_stocked[(f, p)]
        # 若要设置单SKU单仓备货阈值,比如最少备货100件才开仓存储,放开下一行即可
        # model += qty_sku_fac[(f, p)] >= 100 * is_sku_stocked[(f, p)]

# 固定成本求和,可将fixed_cost设为和仓库到SKU主要客户的距离正相关,实现就近存放优先
fixed_total = pulp.lpSum(
    [fixed_cost[(f, p)] * is_sku_stocked[(f, p)]
     for f in chosen_facilities
     for p in Products]
)

# 总目标函数加入模型
model += transport_total + fixed_total, "TotalCost"

常见KeyError: 'Fac-2'排查点

  • 确认决策变量定义时,仓库维度遍历的是chosen_facilities而非全量Facility列表
  • 确认transportation_cost/fixed_cost等参数字典的key包含所有chosen_facilities里的仓库,key格式和代码调用时的顺序完全一致
  • 确认Products/Customer列表里的所有值,都对应存在于各参数字典的key组合中

内容的提问来源于stack exchange,提问作者Phil

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.08 07:15:04