0
$\begingroup$

I have a question about Gurobi. How do I define a constraint that can accept multiple different values? For example, a sample constraint is shown as follows:

f = [1.0, 1.0, 1.0, 1.0]
x = m.addVars(4, lb=0, ub=15, vtype=GRB.INTEGER)
m.addConstr(x.prod(f) == 10 or 15, name="")

This constraint can be equal to multiple values, such as 10 or 15. Is this constraint possible in Gurobi based on the Python language? If so, how should I write the code?

$\endgroup$
0
2
$\begingroup$

You can do something like this:

possible_values = [10, 15]

# add binary variables
b = m.addVars(len(possible_values), vtype="B")

# b[0] + b[1] == 1
m.addConstr(b.sum() == 1)

# add indicator constraints:
for i, val in enumerate(possible_values):
    # if b[i] == 1, then x.prod(f) == val
    m.addConstr((b[i] == 1) >> (x.prod(f) == val))

Here, we ensure that only one of the variables $b_i$ can be equal to 1. Hence, x.prod(f) can only be equal to possible_values[i]. See the docs for more details regarding indicator constraints.

$\endgroup$
2
  • $\begingroup$ If a model has two different variables x and b, how do I output the value of the variable x I want?The code I wrote is as follows:for e in range(nSolutions): part = [] m.setParam(GRB.Param.SolutionNumber, e) for v in range(m.NumVars): part.append(int(x[v].Xn)) solution.append(part)According to the code you gave, the code I wrote seems to report an error, originally it worked fine. $\endgroup$
    – Zying
    Jul 9 at 7:36
  • $\begingroup$ You can obtain the variable value in the current solution by the .X attribute, i.e. x[i].X gives you the value of the variable x[i] and b[i].X the value of the variable b[i]. However, I don't see how this should be related to your original question or my answer. My code is based on the example you provided in the question and it's impossible to answer your new question based on the incomplete code snippet in your comment. So please ask a separate question and provide a minimal reproducible example. $\endgroup$
    – joni
    Jul 9 at 8:32

Not the answer you're looking for? Browse other questions tagged or ask your own question.