SOS1 example

Solve the following optimization problem: $$\begin{aligned} \text{maximize}\quad & 3x_1 + 4x_2 + x_3 + 5x_4 \\ \text{subject to}\quad & 0 \le x_i \le 5 \\ & \text{at most one of the $x_i$ can be nonzero} \end{aligned}$$

In [4]:
# using binary constraint

using JuMP, Cbc
m = Model(solver = CbcSolver())
@variable(m, 0 <= x[1:4] <= 5)
@variable(m, z[1:4], Bin)
@constraint(m, sum(z[i] for i=1:4) == 1)
@constraint(m, x .<= 5z)
@objective(m, Max, 3x[1]+4x[2]+1x[3]+5x[4])

solve(m)
getvalue(x)
Out[4]:
4-element Array{Float64,1}:
 0.0
 0.0
 0.0
 5.0
In [7]:
# using SOS1 constraint

using JuMP, Cbc
m = Model(solver = CbcSolver())
@variable(m, 0 <= x[1:4] <= 5)
addSOS1(m, x)
@objective(m, Max, 3x[1]+4x[2]+1x[3]+5x[4])

solve(m)
getvalue(x)
Out[7]:
4-element Array{Float64,1}:
 0.0
 0.0
 0.0
 5.0

SOS2 example

Solve the following optimization problem: $$\begin{aligned} \text{maximize}\quad & 3x_1 + 4x_2 + x_3 + 5x_4 \\ \text{subject to}\quad & 0 \le x_i \le 5 \\ & \text{at most two of the $x_i$ can be nonzero} \\ & \text{and the nonzero $x_i$ must be consecutive} \end{aligned}$$

In [8]:
# using binary constraint

using JuMP, Cbc
m = Model(solver = CbcSolver())
@variable(m, 0 <= x[1:4] <= 5)
@variable(m, z[1:3] >= 0)
@constraint(m, sum(z[i] for i=1:3) == 1)
@constraint(m, x[1] <= 5z[1])
@constraint(m, x[2] <= 5z[1] + 5z[2])
@constraint(m, x[3] <= 5z[2] + 5z[3])
@constraint(m, x[4] <= 5z[3])
@objective(m, Max, 3x[1]+4x[2]+1x[3]+5x[4])

solve(m)
getvalue(x)
Out[8]:
4-element Array{Float64,1}:
 5.0
 5.0
 0.0
 0.0
In [10]:
# using SOS2 constraint

using JuMP, Cbc
m = Model(solver = CbcSolver())
@variable(m, 0 <= x[1:4] <= 5)
addSOS2(m, x)
@objective(m, Max, 3x[1]+4x[2]+1x[3]+5x[4])

solve(m)
getvalue(x)
Out[10]:
4-element Array{Float64,1}:
 5.0
 5.0
 0.0
 0.0
In [ ]: