Wikunia / ConstraintSolver.jl

ConstraintSolver in Julia: Blog posts ->
https://opensourc.es/blog/constraint-solver-1
MIT License
136 stars 13 forks source link

Comparing `x[1] <= x[i]` throws BoundsError #215

Closed hakank closed 3 years ago

hakank commented 3 years ago

The following code yields an BoundsError: LoadError: BoundsError: attempt to access 0-element Array{ConstraintSolver.Variable,1} at index [1]

   #  ....  
    for i in 1:length(x)
        @constraint(model, x[1] <= x[i])
    end
    # ...

Starting i from 2 instead works without any problems, so it seems that it's not allowed to compare a variable with itself.

Here's a simple model showing this:

using ConstraintSolver, JuMP
const CS = ConstraintSolver
function min_test(n)
    model = Model(optimizer_with_attributes(CS.Optimizer,    "logging"=>[]))
    @variable(model, 1 <= x[1:n] <= n, Int)
    for i in 1:n
        @constraint(model, x[1] <= x[i])
    end

    optimize!(model)
    status = JuMP.termination_status(model)
    if status == MOI.OPTIMAL
        xx = convert.(Integer,JuMP.value.(x))
        println("x:$xx")
    end
end
@time min_test(4)

[I discovered this when I tried a decomposition of min(model,x,min_val) for symmetry breaking.]

Wikunia commented 3 years ago

Oh good catch. I'll check whether this is a problem in other constraints as well. Should be fairly easy to fix.

I appreciate your test cases 😊

Btw this should work as well:

@constraint(model, x[1] .<= x)

When this is fixed of course 😂 just wanted to show you the broadcasting way in Julia.

hakank commented 3 years ago

Thanks.

I've not used broadcasting especially much in my models but I'll try to use them more. scalar_product is nice in Julia:

function scalar_product(model,s,x,v)
    @constraint(model, s == sum(x.*v))
end
hakank commented 3 years ago

Thanks! This works.

It's used - for example - as a symmetry breaking constraint in my de Bruijn sequence model (http://hakank.org/julia/constraints/debruijn.jl ). The definition of my_min is in http://hakank.org/julia/constraints/constraints_utils.jl .