You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pulp库的Python线性规划:添加生产触发成本约束问题

线性规划中添加产量非零时的固定成本约束(Pulp实现方案)

问题背景

需要最小化12个月的产品生产成本,其中x[i]为第i个月的产量变量。要求实现:当x[i] > 0时,目标函数增加固定成本A(示例中为1000)。由于Pulp变量无法直接用布尔表达式判断,需通过线性规划的常用技巧建模。

核心思路

引入二进制辅助变量y[i](取值0或1),用来标记当月是否进行生产:

  • 当x[i] > 0时,y[i]必须等于1,此时目标函数加上固定成本A
  • 当y[i] = 0时,x[i]必须等于0,不产生固定成本

通过以下约束实现逻辑关联:
x[i] ≤ M * y[i]
其中M是x[i]的最大可能取值(需足够大,不限制正常生产的上限),可通过每月可用工时计算:M = 最大可用工时 / 单位产品工时,示例中取750(250小时 / (1/3小时/单位))。

修改后的完整代码

from pulp import LpProblem, LpVariable, LpMinimize

# 初始化模型,目标为最小化成本
model = LpProblem("Production_Cost_Minimization", LpMinimize)

# 产量变量:x[i]为第i+1个月的产量,非负
x = [LpVariable(name=f"x{i}", lowBound=0) for i in range(12)]
# 二进制辅助变量:y[i]=1表示第i+1个月有生产,y[i]=0表示无生产
y = [LpVariable(name=f"y{i}", cat='Binary') for i in range(12)]

# 参数定义
manufacturing_time_per_unit = 1/3
cost_of_hour = 12
storage_cost_per_unit = 3
fixed_production_cost = 1000  # 固定成本A
# 修正原材料成本为12个月的数据
cost_of_raw_materials_per_unit = [11, 10, 13, 9, 8, 7,
                                  10, 12, 12, 10, 9, 8]
demand = [150, 200, 100, 300, 200,
          400, 300, 250, 150, 200, 300, 350]
avalaible_hours = [250, 250, 200, 150, 200, 200,
                   150, 200, 250, 150, 150, 200]
# 计算产量上限M:最大可用工时能生产的最大数量
max_possible_production = max(avalaible_hours) / manufacturing_time_per_unit

cost_sum = 0
stored = [100]  # 初始库存

for i in range(1, 13):
    month_idx = i - 1
    # 1. 生产工时约束:当月生产耗时不超过可用工时
    model += manufacturing_time_per_unit * x[month_idx] <= avalaible_hours[month_idx]
    # 2. 需求满足约束:当月产量+上月库存 >= 当月需求
    model += x[month_idx] + stored[-1] >= demand[month_idx]
    # 3. 库存更新:当月库存 = 上月库存 + 当月产量 - 当月需求
    current_storage = stored[-1] + x[month_idx] - demand[month_idx]
    stored.append(current_storage)
    # 4. 库存非负约束(原代码缺失,需补充)
    model += current_storage >= 0
    # 5. 产量与二进制变量的关联约束:有产量则y=1
    model += x[month_idx] <= max_possible_production * y[month_idx]
    
    # 计算当月变动成本:生产工时成本 + 原材料成本 + 库存成本
    production_cost = (manufacturing_time_per_unit * cost_of_hour + cost_of_raw_materials_per_unit[month_idx]) * x[month_idx]
    inventory_cost = storage_cost_per_unit * current_storage
    cost_sum += production_cost + inventory_cost
    # 加上当月固定成本(仅当生产时)
    cost_sum += fixed_production_cost * y[month_idx]

# 设置目标函数
model += cost_sum

# 求解模型
model.solve()

# 输出结果
print("生产计划:")
for var in x:
    print(f"{var.name}: {var.varValue}")
print("\n是否生产:")
for var in y:
    print(f"{var.name}: {var.varValue}")
print(f"\n最小总成本:{model.objective.value()}")

关键说明

  • 二进制变量y[i]:精准标记生产状态,避免了直接判断Pulp变量的布尔值
  • 约束x[i] ≤ M*y[i]:确保逻辑关联的严谨性,M的取值需覆盖所有可能的产量情况,不能过小导致生产上限被错误限制
  • 成本计算修正:原代码遗漏了原材料成本和工时成本的乘积,补充后变动成本计算更准确;同时添加了库存非负约束,符合实际生产逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 10:25:20