Skip to content

Commit 6168588

Browse files
committed
Allow user to have already created the disjunction binary variable before calling the disjunction macro #24
1 parent 8af4258 commit 6168588

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

examples/ex5.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ using DisjunctiveProgramming
33

44
m = Model()
55
@variable(m, -10 x 10)
6+
@variable(m, z[1:2], Bin) #create binary variable for disjunction
67

78
nl_con1 = @NLconstraint(m, exp(x) >= 1)
89
nl_con2 = @NLconstraint(m, exp(x) <= 2)

src/disjunction.jl

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,20 @@ function add_disjunction(m::Model,disj...;reformulation,M=missing,eps=1e-6,name=
44
@assert length(disj) > 1 "At least 2 disjuncts must be included."
55
#create binary indicator variables for each disjunction
66
disj_name = ismissing(name) ? Symbol("disj",gensym()) : name
7-
@assert isnothing(variable_by_name(m,string(disj_name))) "Name for disjunction binary cannot be the same as an existing variable."
8-
eval(:(@variable($m, $disj_name[i = 1:length($disj)], Bin)))
7+
#check if indicator variable with that name already exists
8+
if disj_name in keys(object_dictionary(m))
9+
#check that the existing name is for a valid binary variable that can be used for the disjunction
10+
type_check = m[disj_name] isa Vector{VariableRef} #check it is a variable
11+
type_check2 = all([is_binary(disj_var_i) for disj_var_i in m[disj_name]]) #check it is binary
12+
dim_check = length(m[disj_name]) >= length(disj) #check the number of indices is at least the number of disjuncts
13+
@assert type_check && dim_check && type_check2 "An object of name $name is already attached to this model, but is not valid for use in the disjunction. $name must be a Vector of binary variables with dimension greater than or equal to that of the disjunction."
14+
else #create variable if it doesn't exist
15+
eval(:(@variable($m, $disj_name[i = 1:length($disj)], Bin)))
16+
end
17+
918
#enforce exclussive OR
10-
eval(:(@constraint($m,sum($disj_name[i] for i = 1:length($disj)) == 1)))
19+
disj_var = m[disj_name]
20+
eval(:(@constraint($m,sum($disj_var[i] for i = 1:length($disj)) == 1)))
1121
#apply reformulation
1222
param = reformulation == :BMR ? M : eps
1323
reformulate(m, disj, disj_name, reformulation, param)

0 commit comments

Comments
 (0)