What kind of functions can be accepted into Model.setObjective method?
AnsweredHello,
I have the following code where I am trying to find the value of 'x' for which the function below will be at a minimum:

from gurobipy import Model, GRB
model = Model()
x = model.addVar(0, float('inf'), name = 'x')
def square_of_x(x):
if x >= 0:
return x * x
else:
return x
model.setObjective(square_of_x(x), GRB.MINIMIZE)
model.optimize()

When I run this I get the following error:
GurobiError: Constraint has no bool value (are you trying "lb <= expr <= ub"?)
In a more general problem, I would like to create a function, have the Gurobi variable as an argument in that function, and then minimize the value of that function via an LP optimization, to find the value of the variable that would make the function minimal.
A few questions:
1) Is the 'if statement' the issue in the function? The answer to the optimization should be x = 0.
2) What kinds of functions can Model.setObjective() method accept as an argument?
Thanks.

Hi Vadim,
1) Is the 'if statement' the issue in the function? The answer to the optimization should be x = 0.
Yes, the if statement is causing the issue. Note that \(x\) is a Var object which does not have any value. You can access the variable solution point value via its X attribute after a solution point is available. In your case, you would have to run optimize first in order to make \(x\) have a solution point value available.
In Mathemtical Programming, you can model \(\texttt{if}\)statements via additional binary variables and constraints, cf. How do I model conditional statements in Gurobi? In your case, it is much easier. You can just set the objective function to \(x^2\) via
model.setObjective(x*x, GRB.MINIMIZE)
2) What kinds of functions can Model.setObjective() method accept as an argument?
According to the documentation of the setObjective method, it accepts linear and quadratic expressions.
Best regards,
Jaromił0
Please sign in to leave a comment.
Comments
1 comment