如何在 Gurobi 的约束中使用 'or'

How to use 'or' in constraint in Gurobi

我正在使用 Gurobi,在我的代码的一部分中,我定义了一个可以接受两个不同值的约束。例如 1 或 2。下面是我实现的半代码:

m = Model("mip1")
Edges = tuplelist([(1,2),(1,3),(3,4),(3,5),(3,6),(5,6),(6,7),
                   (1,1),(2,2),(3,3),(4,4),(5,5),(6,6),(7,7),
                   (1,8),(2,8),(3,8),(4,8),(5,8),(6,8),(7,8),
                   (8,1),(8,2),(8,3),(8,4),(8,5),(8,6),(8,7),
                   ])

x = m.addVars(Edges, lb=0.0, ub=1.0, name = "x")

m.setObjective(quicksum(x[w,s] for w,s in Edges), GRB.MAXIMIZE)

m.addConstr(quicksum(x.select(8,'*')) ==1 or 2 , "constraint1")

但是我不知道如何在Gurobi中定义约束'or'!

让我们添加两个二进制变量 y_0 和 y_1:

y = m.addVars(2, vtype=GRB.BINARY, name="y")

现在您可以添加两个 indicator constraints:

# If y[0] == 1, then quicksum(x.select(8, '*')) == 2
m.addConstr((y[0] == 1) >> (quicksum(x.select(8, '*')) == 2))
# If y[1] == 1, then quicksum(x.select(8, '*')) == 3
m.addConstr((y[1] == 1) >> (quicksum(x.select(8, '*')) == 3))

接下来添加约束

m.addConstr(y[0] + y[1] == 1)

这确保这两个变量中只有一个可以为 1,因此总和为 2 或 3。