检查pyomo模型和生成的LP文件格式是否有效并捕获错误/异常

时间:2019-01-02 11:11:00

标签: linear-programming pyomo

我有一个pyomo ConcreteModel(),我在另一个随机优化过程中反复求解,而在模型上更改了一个或多个参数。

基本过程可以描述如下:

# model is created as a pyomo.ConcreteModel()
for i in range(0, 10):    
    # change some parameter on the model
    opt = SolverFactory('gurobi', solver_io='lp')
    # how can I check here if the changed model/lp-file is valid?
    results = opt.solve(model)

现在,在某些情况下,模型和LP file (see gist)似乎包含NaN值时会出现错误:

ERROR: Solver (gurobi) returned non-zero return code (1)
ERROR: Solver log: Academic license - for non-commercial use only Error
    reading LP format file /tmp/tmp8agg07az.pyomo.lp at line 1453 Unrecognized
    constraint RHS or sense Neighboring tokens: " <= nan c_u_x1371_: +1 x434
    <= nan "

    Unable to read file Traceback (most recent call last):
      File "<stdin>", line 5, in <module> File
      "/home/cord/.anaconda3/lib/python3.6/site-
      packages/pyomo/solvers/plugins/solvers/GUROBI_RUN.py", line 61, in
      gurobi_run
        model = read(model_file)
      File "gurobi.pxi", line 2652, in gurobipy.read
      (../../src/python/gurobipy.c:127968) File "gurobi.pxi", line 72, in
      gurobipy.gurobi.read (../../src/python/gurobipy.c:125753)
    gurobipy.GurobiError: Unable to read model Freed default Gurobi
    environment

当然,第一个想法是防止设置这些NaN值。但是我不知道为什么会这样发生,并且想弄清楚何时由于NaNs引起的结构错误而导致模型破裂。

我知道我可以从SolverFactory()对象中获取求解器状态和终止条件。但是由于更改的值无效,错误显然发生在求解过程之前。

在求解i之前,如何为不同的求解器捕获此类错误。 e。在应用求解器之前检查模型/ lp文件是否有效?是否有一些方法例如check_model()会提供TrueFalse,如果模型有效(或无效)或类似?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您知道更改参数值时发生错误,则可以进行测试以查看所有相关参数值的总和是否为有效数字。毕竟,NaN + 3 = NaN

由于您获得NaN,因此我猜您正在使用从Excel电子表格中的Pandas导入参数值?有一种方法可以将所有NaN转换为默认数字。

用于参数检查的代码示例:

>>> from pyomo.environ import *
>>> m = ConcreteModel()
>>> m.p1 = Param(initialize=1)
>>> m.p2 = Param(initialize=2)
>>> for p in m.component_data_objects(ctype=Param):
...     print(p.name)
... 
p1
p2
>>> import numpy
>>> m.p3 = Param(initialize=numpy.nan)
>>> import math
>>> math.isnan(value(sum(m.component_data_objects(ctype=Param))))
True

带索引的可变参数:

>>> from pyomo.environ import *
>>> m = ConcreteModel()
>>> m.i = RangeSet(2)
>>> m.p = Param(m.i, initialize={1: 1, 2:2}, mutable=True)
>>> import math
>>> import numpy
>>> math.isnan(value(sum(m.component_data_objects(ctype=Param))))
False
>>> m.p[1] = numpy.nan
>>> math.isnan(value(sum(m.component_data_objects(ctype=Param))))
True