Conditionnal constraint


I need help to implement a constraint.

The goal is to assign students to courses. Some courses can have a maximum of 8 students, others can have a maximum of 12.

I first wrote my constraint like this:

For j in 1:s
if (ws2[j+1,3]==1)
    @constraint(TB, contrainte2a[j=1:s],  sum(x[i,j] for i in 1:e) <= 8)
    @constraint(TB, contrainte2b[j=1:s],  sum(x[i,j] for i in 1:e) <= 12)

The “ws2[j+1,3]==1” refers to a column in an excel table.

I get this error message:

LoadError: An object of name contrainte2a is already attached to this model. If this
    is intended, consider using the anonymous construction syntax, e.g.,
    `x = @variable(model, [1:N], ...)` where the name of the object does
    not appear inside the macro.
    Alternatively, use `unregister(model, :contrainte2a)` to first unregister
    the existing name from the model. Note that this will not delete the
    object; it will just remove the reference at `model[:contrainte2a]`.

I think the error comes from putting a constraint in an if.

Does anyone know how to fix this problem?

Thank you in advance for your help :slight_smile:

Your code had a couple of issues:

  • It has an outer loop over j
    • But then each constraint was indexed over j as well [j=1:s]
  • Each constraint was named with connstrainte2a
    • But then you were trying to add these in a loop

Do instead:

for j in 1:s
    if ws2[j+1, 3] == 1
        @constraint(TB, sum(x[i, j] for i in 1:e) <= 8)
        @constraint(TB, sum(x[i, j] for i in 1:e) <= 12)
1 Like

It works, thank you very much!

Now I would like to tell the program that if the box in the excel document is equal to 1, it must return that x[i,j]=1.

Is it correct to implement it this way?

for i in 1:e, j in 1:s
    if (ws[i+1,3]==1)
    @constraint(TB, x[i,j]==1)

Yes. You could also use the more compact syntax:

@constraint(TB, [i=1:e, j=1:s; ws[i+1,3]==1], x[i,j] == 1)

Thank you for your answer.

I copied what you told me but I get the following message:

Do you know why?

You didn’t copy exactly what I wrote :laughing: