Convert a VariableRef in JuMP objective function or constraint

I have a model with decision variables like this

model = Model(Cbc.Optimizer)

@variable(model, x[1:num_groups, 1:size(data, 1)], Bin)

and I need to be able to use the values of x to return a submatrix from another matrix dm. I’ve tried like this

@objective(model, Min, sum(sum(dm[BitArray(x[i,:]), BitArray(x[i,:])]) for i in 1:3))

but I get:

julia> @objective(model, Min, sum(sum(dm[BitArray(x[i,:]), BitArray(x[i,:])]) for i in 1:3))
ERROR: MethodError: Cannot `convert` an object of type VariableRef to an object of type Bool

I thought I had tricked it into working with this monstrosity because it didn’t throw an error but the objective value always turns out to be 0.0 this way:

sum([sum(dm[[i for i in 1:size(data,1) if value.(x)[j,:][i] == 1.0], [i for i in 1:size(data,1) if value.(x)[j,:][i] == 1.0]]) for j in 1:num_groups])

Is there a way to convert the values of x so that I can use them in the same way one would use a BitArray?

JuMP Variables cannot be used as Bool’s.
You cannot use them to access arrays.
Once you optimize! the problem you might get their optimal value by using the value method.
If you call value prior to optimization its either an error or a meaningless number.

4 Likes