Linearizing non-linear constraint
AnsweredHello,
We have a continuous variable:
u = m.addVars(items, vtype=GRB.CONTINUOUS, name ="U")
#Weights of the items
And we want to maximize this difference:
mayorU = max_(u)
menorU = min_(u)
m.setObjective(mayorU - menorU, GRB.MAXIMIZE)
This works. But, is the objective function non-linear? Could it be rewritten to be linear?
Thanks.
-
Official comment
This post is more than three years old. Some information may not be up to date. For current information, please check the Gurobi Documentation or Knowledge Base. If you need more help, please create a new post in the community forum. Or why not try our AI Gurobot?. -
Hi Ana,
Testing out your code I get the following error
TypeError: unsupported operand type(s) for -: 'GenExpr' and 'GenExpr'
Note that the functions min_ and max_ are Constraint Helper Functions and should be used in conjunction with overloaded operators and Model.addConstr or Model.addConstrs.
A working example would be to replace your last three lines of code by
mayorU = m.addVar(vtype=GRB.CONTINUOUS)
menorU = m.addVar(vtype=GRB.CONTINUOUS)
m.addConstr(mayorU == max_(u))
m.addConstr(menorU == min_(u))
m.setObjective(mayorU - menorU, GRB.MAXIMIZE)Concerning your question about linearity: with this substitution you are creating a model with a linear objective function but note that you are simply moving the non-linearity into the constraints. Perhaps you'll find this article How to linearize max, min and abs functions useful to rewrite your model to be linear.Best regards,Elisabeth0 -
Thanks, Elisabeth.
Yes, you are totally right, I simplified the code but yours is the correct one.
Thanks for solving the question of non-linearily. Now, I understand that the non-linearity is in the constraints (and not in the objective) and thanks for the link with more information.
Is Gurobi capable of solving this non-linearity? Because it gives me correct results.
Thanks again.
Best,
Ana
0 -
Hi Ana,
Happy to read that this answer helped.
Indeed, Gurobi is capable of handling some types of general constraints, you can find more information on the types of constraints that Gurobi can handle on the Constraints documentation page.
Best regards,
Elisabeth
0
Post is closed for comments.
Comments
4 comments