Absolute value, abs(), on Gurobi solver

Hi all, is there a way to use absolute value e.g. abs(x) with JuMP/Gurobi?
It seems like Gurobi supports it (see: https://www.gurobi.com/documentation/9.1/refman/py_abs_.html), but abs(x) is linked with a NLconstraint which is not compatible with Gurobi Solver.
Is there a way to bypass it? Any comments would be appreciated. Thanks!

using JuMP, Gurobi, Ipopt
m = Model(Ipopt.Optimizer)
@variable(m, x)
@NLconstraint(m, abs(x) <= 5)
@objective(m, Min, x)
JuMP.optimize!(m)
@show JuMP.termination_status(m)
@show value.(x)

Hi all, is there a way to use absolute value e.g. abs(x) with JuMP/Gurobi?

No. You will need to use a reformulation as a linear program.

Try this:

using JuMP, Gurobi
m = Model(Gurobi.Optimizer)
@variable(m, x)
@constraint(m,   x <= 5)
@constraint(m, - x <= 5)
@objective(m, Min, x)
JuMP.optimize!(m)
@show JuMP.termination_status(m)
@show value.(x)

or use a function

function add_abs_constraint(model::JuMP.Model, expr::GenericAffExpr, rhs)
    @constraint(model,     expr <= rhs)
    @constraint(model,   - expr <= rhs)

   return nothing
end

e.g.

expr = JuMP.@expression(m,  2x - 4)
add_abs_constraint(m, expr, 2)
JuMP.optimize!(m)

should return something from Gurobi like

Solved in 1 iterations and 0.00 seconds
Optimal objective  1.000000000e+00
2 Likes

Thank you for providing this! This helps a lot.

2 Likes