Dynamically setting the constraint sense in JuMP

Hello!

I was wondering if it is possible to specify different types (i.e. <=, == and >=) constraints within the same JuMP container. For example

@constraint(model, con[i = 1:3], i * x <= i + 1)

So that whether <=, == or >= is specified depends on i?

I was wondering if it is possible to specify different types (i.e. <=, == and >=) constraints within the same JuMP container.

Not easily*.

Why do you want to do this? Why not just write out different constraints?

*By not easily, I mean you could do the following, but it’s probably a sign that you could restructure your code some other way to avoid this.

julia> using JuMP

julia> model = Model()
A JuMP Model
Feasibility problem with:
Variables: 0
Model mode: AUTOMATIC
CachingOptimizer state: NO_OPTIMIZER
Solver name: No optimizer attached.

julia> @variable(model, x)
x

julia> s = [MOI.LessThan{Float64}, MOI.GreaterThan{Float64}, MOI.EqualTo{Float64}]
3-element Vector{DataType}:
 MathOptInterface.LessThan{Float64}
 MathOptInterface.GreaterThan{Float64}
 MathOptInterface.EqualTo{Float64}

julia> @constraint(model, con[i=1:3], i * x in s[i](i + 1))
3-element Vector{ConstraintRef{Model, C, ScalarShape} where C}:
 con[1] : x ≤ 2.0
 con[2] : 2 x ≥ 3.0
 con[3] : 3 x = 4.0
3 Likes

Suppose the user gives these constraints, e.g. empirical constraints for a chemical process. It feels artificial to first group them according to the constraint sense.

Your solution looks good. I improved the readability like this:

function sense_constraint(sense::Symbol, rhs)

    if sense == :>=
        return ( MOI.GreaterThan{Float64}(rhs) )
    elseif sense == :<=
        return (MOI.LessThan{Float64}(rhs) )
    else
        return (MOI.EqualTo{Float64}(rhs) )
    end
end



  

#constraints
@constraint(mymod, q_1[i=1:3], i*x in sense_constraint(:<=, i+1) )
print(q_1)