Search code examples
pythonoptimizationsolvergurobi

How to implement an "or" logic in gurobipy


I'm a beginner in gurobipy so I'm trying to understand how to state my problem with it, I have a variable in the model that has to be either zero or greater than a parameter.

#If total is not zero then this constraint has to hold
model.addConstrs(
    (total[sup] >= mins[sup] for sup in suppliers), "CheckMin"
)

I tried creating a binary var for each supplier that had to be True if the total for that supplier was greater than 0, as this:

model.addConstrs(
(bool(gp.quicksum(total[sup] for sup in suppliers)) == binary_buy[sup]
  for sup in suppliers), "BinaryConst"
)

This is leading to infeasible solution, apparently this second constraint is forcing every binary_buy[sup] to be True, while what I want is for it to be True only when total[sup] is greater than 0. It would be nice if someone could help to state this properly, I also accept suggestions of other solvers in python, thanks!


Solution

  • I could solve it by simply multiplying the binaries in the totals constraint:

    model.addConstrs(
        (gp.quicksum(prices[sup, item]*buys[sup, item] for item in items)
         == total[sup]*binary_buy[sup] for sup in suppliers), "TotalFornecedor" 
        )
    

    I hope this helps someone who crosses this problem! Thanks.