I have a constraint that can be either a range or an equality depending upon whether a user passes a range (i.e. two arguments) or a single value as a constraint. I convert the range constraint to an equality using the standard technique, by defining a slack variable
u. I define an abstract type
SPECIAL_CONS with two subtypes
What’s the correct way of generating this constraint and adding it to the model (we don’t know in advance whether a a single value or two values will be passed so that correct constraint is generated)?
using JuMP, Cbc abstract type SPECIAL_CONS end struct Range <: SPECIAL_CONS end struct Equality <: SPECIAL_CONS end function constraint_gen(lb,ub,::Range) @variable(model,0<=u<=ub-lb) return @constraint(model,u+sum(C[i]*x[i] for i in 1:10) == ub) end function constraint_gen(ub,::Equality) return @constraint(model,sum(C[i]*x[i] for i in 1:10) == ub) end function solve_model(constraint_gen::Function) c = rand(10) d = rand(10) model = Model(Cbc.Optimizer) @variable(model, x[1:10] >= 0) @constraint(model,sum(x[i]*c[i] for i=1:10) >=sum(d)) constraint_gen(constraint_gen::Function) optimize!(model) end
If I run the code using the following, it errors as model is not defined, but adding model as argument to the
constraint_gen function also errors.