JuMP constraints independent of a particular model

Is there a way to represent a JuMP constraint independently of a specific model (even if it is purely syntactic)? The macros for creating variables and constraints require a model, of course… What would be a convenient model-independent representation of constraints?

The manual has a section on constructing constraints without adding them to the model.

No. You cannot create a JuMP constraint independently of a model.

p.s. You should use the Optimization domain for JuMP-related questions: https://discourse.julialang.org/c/domain/opt/13

Thanks, that gets me closer to what I want. Two follow-up questions:

(1) The variables in the constraint are still tied to the model, though; any way to avoid this? (In the worst case, I could represent the constraint with a string, but don’t know how to parse it… Was also thinking of a Julia Expr.)

(2) How do I add one of these constraints to a model?

A better question is: why do you want to do this? @build_constraint is mainly used for callbacks (https://www.juliaopt.org/JuMP.jl/stable/callbacks/).

Sorry, thought the “jump” tag would be enough (first time using discourse). Any way to move a question over?

If you click the pencil by the title, there is an option to choose the category. I just moved it for you :slight_smile:

1 Like

I want to pick and choose which constraints go into a model.

One way to achieve that is as follows:

function build_model(flag::Bool)
    model = Model()
    @variable(model, x)
    if flag
        @constraint(model, x >= 0)
    end
    @objective(model, Min, x)
    return model
end

Projects like PowerModels.jl very successfully use this approach to automatically build JuMP models that depend on the context.

1 Like

One other option could be to use expressions:
One can define different expressions
e.g. ex = @expression(model, 2x + y - 1)
and then generate the constraint from one of these expressions.
@constraint(m, ex + y >= 5)