Ali Zoghi
Ali Zoghi

Reputation: 21

How to use VariableRef as indices in Julia JuMP

In Julia when I do:

model = Model();
set_optimizer(model, Cbc.Optimizer);

N=11;

model = Model();
set_optimizer(model, Cbc.Optimizer);
@variable(model, X[1:N,1:N,1:N], Bin);
@variable(model, 1<=K<=10, Int);

for k in K
    @constraint(model, (sum(X[1,j,k] for j= 1:N)) ==1 )
end 

I get this error:

ArgumentError: invalid index: K of type VariableRef

Because I used a variable reference(k) as index for a vector (X).

How could I fix that?

Upvotes: 2

Views: 670

Answers (1)

Przemyslaw Szufel
Przemyslaw Szufel

Reputation: 42244

If you want to K to interact with other variables you need to make it a binary vector with the sum of 1 and then use multiplication for modelling the interaction.

@variable(model, K[1:10], Bin);
@constraint(model, sum(K) == 1)

Now I am not exactly shure what you want to accomplish. If you want to turn off and on equations depending on the value of K this would look like this:

@constraint(model,con[k in 1:10], sum(X[1,j,k] for j= 1:N)*K[k] == K[k] )

This however makes the model non-linear and you would need to use a non-linear solver for it. Depending on your use case having sums simply up to 1 could be enough (and this yields a model much easier for solvers but might your business needs or not):

@constraint(model,con[k in 1:10], sum(X[1,j,k] for j= 1:N) == K[k] )

Upvotes: 2

Related Questions