# 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 :
# 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+4x+1x+5x)

solve(m)
getvalue(x)

Out:
4-element Array{Float64,1}:
0.0
0.0
0.0
5.0
In :
# using SOS1 constraint

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

solve(m)
getvalue(x)

Out:
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 :
# 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 <= 5z)
@constraint(m, x <= 5z + 5z)
@constraint(m, x <= 5z + 5z)
@constraint(m, x <= 5z)
@objective(m, Max, 3x+4x+1x+5x)

solve(m)
getvalue(x)

Out:
4-element Array{Float64,1}:
5.0
5.0
0.0
0.0
In :
# using SOS2 constraint

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

solve(m)
getvalue(x)

Out:
4-element Array{Float64,1}:
5.0
5.0
0.0
0.0
In [ ]: