Linearizing nonlinear 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 nonlinear? Could it be rewritten to be linear?
Thanks.

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 nonlinearity 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 nonlinearily. Now, I understand that the nonlinearity is in the constraints (and not in the objective) and thanks for the link with more information.
Is Gurobi capable of solving this nonlinearity? 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
Please sign in to leave a comment.
Comments
3 comments