【问题标题】:Invalid constraint expression error in PyomoPyomo中的无效约束表达式错误
【发布时间】:2020-12-23 12:59:00
【问题描述】:

我正在使用 pyomo 库解决旅行商问题 (TSP),但出现错误。模型主要部分如下:

model.set_I = range(lendist, 1) # The set related to the distance matrix
model.set_J = range(nStops, 1) # nStop is the number of cities and set_J is the related set.
model.trips = Var(model.set_I, domain=NonNegativeReals, bounds=(0, 1)) # trips is the decision variable

def obj_expression(model): # Objective function
    return sum(model.dist[i]*model.trips[i] for i in model.set_I)
model.OBJ = Objective(rule=obj_expression)

# Constraint 1:
def constraint_1(model):
    return sum(model.trips[i] for i in model.set_I) == nStops
model.constraint_1 = Constraint(rule=constraint_1)

# Constraint 2:
def constraint_2(model, j):
    return sum(model.trips[whichIdxs[i, j]] for i in model.set_I) == 2
model.constraint_2 = Constraint(model.set_J, rule=constraint_2)

产生的错误如下:

错误:从 data=None 构造组件“constraint_1”失败:

ValueError: Invalid constraint expression. The constraint expression resolved to a trivial Boolean (False) instead of a Pyomo object. Please modify your rule to return Constraint. Infeasible instead of False.

ValueError:无效的约束表达式。约束表达式解析为一个普通的布尔值 (False) 而不是 Pyomo 对象。请修改您的规则以返回约束。不可行而不是 False。

为约束约束_1 引发错误

约束 1 只有索引 i,并且总和超过它。因此,规则定义后没有索引。问题出在这里吗?事实上,类似的情况对目标函数也是有效的,但是这并没有错误。

【问题讨论】:

    标签: python pyomo


    【解决方案1】:

    lendist 的值是多少?

    看起来model.set_I 是空的(如果lendist>=1 会发生这种情况)。当 Python 对一个空的可迭代对象求和时,它会返回整数常量 0。假设您有 nStops != 0 ,那么 Python 在 constraint_1 函数中计算表达式,导致它返回 False (而不是 Pyomo 表达式对象)。由于False 不是一个有效的 Pyomo 表达式(并且非常不可行),Pyomo 会引发错误。

    请记住,当您将两个参数传递给 Python range() 函数时,参数指定了起始值和结束值:range(start, end) 仅返回从 start 开始的整数,但不包括 end.

    【讨论】:

      猜你喜欢
      • 2018-01-18
      • 2022-11-04
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      相关资源
      最近更新 更多