2

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?

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Ali Zoghi
  • 21
  • 1

1 Answers1

2

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] )
Przemyslaw Szufel
  • 40,002
  • 3
  • 32
  • 62
  • Thanks a lot, I want to solve a classic vehicle routing problem. K is the number of vehicles (routes). The objective is to minimize K. In this FOR statement (in the question) I wanted to use the amount of variable K as an index. – Ali Zoghi Apr 05 '21 at 15:04
  • And another question, howis it possible to use condition (if then) statement for constraints? – Ali Zoghi Apr 05 '21 at 15:10
  • 1
    For TSP look at the great book "Julia Programming for Operations Research, 2nd Edition". Heuristics work here well - try the package TravellingSalesmenHeuristics.jl – Przemyslaw Szufel Apr 05 '21 at 21:09
  • You can build `IF` conditions via binary variables - very similarly to the way I have shown you. – Przemyslaw Szufel Apr 05 '21 at 21:09