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

Pulp约束配置错误致求解失败,请求问题排查与修正

问题描述

尝试用Pulp模拟Excel中的规划求解问题,框架逻辑已搭建,但约束条件可能配置错误。核心需求是将每个航班的需求与依赖求解器变量的预估需求做对比,运行求解后出现报错,Pulp未完成求解。

现有代码

import pulp
import pandas as pd
import numpy as np
data_flight = pd.read_csv('data_flight.csv')
resource = pd.read_csv('Resource_Requirement.csv')

seat_capacity = pd.read_csv('seat_capacity.csv')

products = list(data_flight['Product j'])
flight_capacity = list(seat_capacity["Type"])

dict_price = dict(zip(products,data_flight['Price']))
dict_demand = dict(zip(products,data_flight['Exp. Demand']))
dict_y = dict(zip(products,list(np.arange(0,14))))

resource_req = {}
for i in flight_capacity:
    resource_req[i] = resource[i]


phasing = pulp.LpProblem("Maximise",pulp.LpMaximize)
phasing += pulp.lpSum(Selection[idx]*data_flight.loc[idx, 'Price'] for idx in data_flight.index)

from pulp import lpDot
constraint_seats = []
for i in flight_capacity:
    constraint_seats.append(lpDot(resource_req[i], Selection))

for i, j in zip(seat_capacity['Seat Capacity'], constraint_seats):
    phasing += j <= i

for i,j in zip(data_flight['Exp. Demand'],Selection):
    phasing += j <= i

phasing.solve()

错误回溯信息

Traceback (most recent call last)
Cell In[30], line 1
----> 1 phasing.solve()

File ~/.python/current/lib/python3.10/site-packages/pulp/pulp.py:1913, in LpProblem.solve(self, solver, **kwargs)
   1911 # time it
   1912 self.startClock()
-> 1913 status = solver.actualSolve(self, **kwargs)
   1914 self.stopClock()
   1915 self.restoreObjective(wasNone, dummyVar)

File ~/.python/current/lib/python3.10/site-packages/pulp/apis/coin_api.py:137, in COIN_CMD.actualSolve(self, lp, **kwargs)
    135 def actualSolve(self, lp, **kwargs):
    136     """Solve a well formulated lp problem"""
-> 137     return self.solve_CBC(lp, **kwargs)

File ~/.python/current/lib/python3.10/site-packages/pulp/apis/coin_api.py:206, in COIN_CMD.solve_CBC(self, lp, use_mps)
    204     if pipe:
    205         pipe.close()
-> 206     raise PulpSolverError(
    207         "Pulp: Error while trying to execute, use msg=True for more details"
    208         + self.path
    209     )
    210 if pipe:
    211     pipe.close()

PulpSolverError: Pulp: Error while trying to execute, use msg=True for more details/home/codespace/.python/current/lib/python3.10/site-packages/pulp/solverdir/cbc/linux/64/cbc

问题排查与修复方案

核心错误点

  1. 决策变量未定义:代码中直接使用Selection变量,但未通过Pulp创建对应的LpVariable对象,这是导致求解失败的首要原因。
  2. 约束维度不匹配:资源需求与变量的迭代逻辑存在偏差,可能导致约束中向量长度不一致。
  3. 需求约束遍历错误:直接迭代Selection字典会拿到产品名称而非变量本身,无法正确关联需求数据。

修复后的完整代码

import pulp
import pandas as pd
import numpy as np

# 读取数据
data_flight = pd.read_csv('data_flight.csv')
resource = pd.read_csv('Resource_Requirement.csv')
seat_capacity = pd.read_csv('seat_capacity.csv')

# 定义核心维度
products = list(data_flight['Product j'])
flight_types = list(seat_capacity["Type"])

# 构建映射字典
dict_price = dict(zip(products, data_flight['Price']))
dict_demand = dict(zip(products, data_flight['Exp. Demand']))

# 整理资源需求:转为列表确保与变量维度匹配
resource_req = {}
for flight_type in flight_types:
    resource_req[flight_type] = resource[flight_type].tolist()

# 1. 创建决策变量:每个产品的售卖量,按需选择连续/整数类型
Selection = pulp.LpVariable.dicts(
    "Selection", 
    products, 
    lowBound=0, 
    cat='Continuous'  # 若需求为整数,改为cat='Integer'
)

# 2. 初始化最大化问题
phasing = pulp.LpProblem("Maximise_Revenue", pulp.LpMaximize)

# 3. 设置目标函数:总收益最大化
phasing += pulp.lpSum(Selection[prod] * dict_price[prod] for prod in products)

# 4. 座位容量约束:每个航班类型的资源消耗不超过容量
from pulp import lpDot
for flight_type, capacity in zip(flight_types, seat_capacity['Seat Capacity']):
    phasing += lpDot(
        resource_req[flight_type], 
        [Selection[prod] for prod in products]
    ) <= capacity, f"Seat_Capacity_{flight_type}"

# 5. 需求约束:每个产品的售卖量不超过预估需求
for prod in products:
    phasing += Selection[prod] <= dict_demand[prod], f"Demand_Limit_{prod}"

# 6. 求解并输出详细日志
phasing.solve(pulp.PULP_CBC_CMD(msg=True))

# 打印结果
print(f"求解状态: {pulp.LpStatus[phasing.status]}")
for prod in products:
    print(f"{prod}: {pulp.value(Selection[prod])}")
print(f"总收益: {pulp.value(phasing.objective)}")

关键修复说明

  • 新增决策变量Selection的定义,确保每个产品对应一个求解变量。
  • 调整资源需求的存储格式,转为列表保证与变量列表维度完全匹配。
  • 修正约束循环逻辑,确保变量与对应数据正确关联。
  • 添加msg=True参数,求解时输出CBC solver的详细日志,便于后续排查问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 05:15:22