2

I am using Julia/JuMP to implement an algorithm. In one part, I define a model with continues variables and solve the linear model. I do some other calculations based on which I add a couple constraints to the model, and then I want to solve the same problem but with integer variables. I could not use convert() function as it does not take variables.

I tried to define the variable again as integer, but the model did not seem to consider it! I provide a sample code here:

m = Model()
@defVar(m, 0 <= x <= 5)
@setObjective(m, Max, x)
@addConstraint(m, con, x <= 3.1)
solve(m) 
println(getValue(x))
@defVar(m, 0 <= x <= 1, Bin)
solve(m) 
println(getValue(x))

Would you please help me do this conversion?

Ana
  • 1,516
  • 3
  • 15
  • 26

2 Answers2

2

The problem is that the second @variable(m, 0 <= x <= 1, Bin) actually creates a new variable in the model, but with the same name in Julia.

To change a variable from a continuous to a binary, you can do

setcategory(x, :Bin)

to change the variable bounds and class before calling solve again.

IainDunning
  • 11,546
  • 28
  • 43
  • Thanks Iain, my other question is how to change the solver? for the original LP, I use `m=Model(solver=GurobiSolver(PreCrush=1, Cuts=0, Presolve=0, Heuristics=0.0))` so I can add my cuts. For the second problem, which is an IP, I want the solver to only use B&B and no cuts. – Ana Jan 04 '15 at 14:25
  • When I change the type of x, I get an error message `type JuMPArray has no field col`. However, it runs fine on another small sample code! – Ana Jan 05 '15 at 04:20
  • My bad! I should have put it in a for loop: `for j in 1:3 m.colcat[x[j].col] = :Int end`. – Ana Jan 05 '15 at 13:07
  • Any idea how to do this in newer JuMP versions (e.g. v0.21) ? Thanks – Manos Sep 06 '20 at 16:08
0

In newer versions of JuMP, you need to use a different function than setcategory. The methods you are looking for are:

  • set_binary Add binary constraint to variable.
  • unset_binary Remove binary constraint from variable.
  • set_integer Add integer constraint to variable.
  • unset_integer Remove integer constraint from variable.

The documentation on this can be found here.

Alice Ryhl
  • 3,574
  • 1
  • 18
  • 37