Best practices for passing JuMP decision variables and data to a function for adding constraints

I have an integer optimization problem of the form:

{\text{minimize}}_{x_{1},\ldots,x_{r}} \quad c_{1}^{\top}x_{1}+c_{2}^{\top}x_{2}+\ldots+c_{r}^{\top}x_{r}\\​\text{subject to} \quad B_{1}x_{1}+B_{2}x_{2}+\ldots+B_{r}x_{r}\leq d\\​\quad \quad\quad\;\; A_{i}x_{i}\leq b_{i},\quad i\in\{1,2,\ldots,r\}\\​\quad \quad\quad\;\; x_{i}\in\mathbb{Z}^{d_{i}},\quad i\in\{1,2,\ldots,r\}.

I would like to model each the uncoupled constraints A_{i}x_{i}\leq b_{i} by passing the data \{A_{i},b_{i}\} and decision variable \{x_{i}\} to a function, say add_A_b_constraintand then implementing these constraints by calling the function add_A_b_constraint r times in a loop. In the JuMP documentation I see an example at https://jump.dev/JuMP.jl/stable/tutorials/getting_started/design_patterns_for_larger_models/#Generalize-constraints-and-objectives where we can access each registered variable by passing the JuMP model, say model itself to the function add_A_b_constraint and then accessing the registered variable in the function by calling syntax such as model[:x_i], but then this does not work for all x_i uniformly.

My question is in such a situation what would be the best practice to pass the data \{A_{i},b_{i}\} and decision variable \{x_{i}\} to a JuMP function to model A_{i}x_{i}\leq b_{i}? Thanks in advance.

Just do something like this? You don’t have to follow the one-true-way to use JuMP. Just do whatever is most convenient.

function add_A_b_constraint(model, A, b, x)
    @constraint(model, A * x <= b)
end
A = [rand(2, 3) for _ in 1:2]
b = [rand(2) for _ in 1:2]
model = Model()
@variable(model, x[1:3, 1:2])
for i in 1:2
    add_A_b_constraint(model, A[i], b[i], x[:, i])
end
1 Like

Okay sounds good, thanks Oscar!

1 Like