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

Pyomo调用Gurobi判断求解状态报错及不可行解处理咨询

Pyomo+Gurobi 不可行解判断与处理方案

问题背景

使用Pyomo搭配Gurobi求解器循环处理多时间步优化模型时,尝试在模型返回不可行解时保存DataFrame,但代码执行时报错:

AttributeError: 'GUROBISHELL' object has no attribute 'termination_condition'

错误原因

GUROBISHELL(Gurobi命令行接口实例)本身不具备termination_condition属性,该终止状态信息需要从求解返回的结果对象中获取,而非直接从求解器实例读取。

正确处理方案

核心修改逻辑

  • 从求解返回的model_results对象中提取终止状态,而非求解器实例
  • 结合solver status与termination condition双重判断,排除求解中断等异常场景

修正后的代码示例

from pyomo.environ import *
from pyomo.opt import SolverStatus, TerminationCondition
from pyomo.util.infeasible import log_infeasible_constraints
import os

# 初始化求解器
opt_options = {'solver': 'gurobi'}
solver = SolverFactory(opt_options['solver'])

# 求解模型
model_results = solver.solve(
    model_1stlayer,
    options=solver_options,
    tee=True
)

# 精准判断不可行状态
if (model_results.solver.status == SolverStatus.ok and 
    model_results.solver.termination_condition == TerminationCondition.infeasible):
    # 保存目标DataFrame
    filename = os.path.join(output_path, 'df_operation.xlsx')
    df_operation.to_excel(filename)
    filename = os.path.join(output_path, 'df_operation_2ndLayer.xlsx')
    df_operation_2ndLayer.to_excel(filename)
    
    # 可选:输出不可行约束日志,辅助问题排查
    log_infeasible_constraints(model_1stlayer, logfile=os.path.join(output_path, 'infeasible_constraints.log'))

额外说明

  • SolverStatus.ok用于确认求解器正常完成计算,避免误判求解中断、异常退出等情况
  • log_infeasible_constraints工具可输出导致模型不可行的具体约束,帮助快速定位问题
  • 若使用Gurobi直接Python接口(SolverFactory('gurobi_direct')),上述判断逻辑同样适用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 17:17:05