0

I want to write a conditional constraint using docplex. The constraint is:

if:
y[(i, j,k)]  == 1 or y[(j, i,k)]  == 1 

then:
g[i,j,k]==1

I implemented the code in docplex in this way:

mdl.add(mdl.if_then(mdl.logical_or(y[(i, j,k)]  == 1 ,y[(j, i,k)]  == 1 ),g[i,j,k]==1))

But when I run I get this error:

DOcplexException: Expecting linear constraint, got: docplex.mp.LogicalOrExpr(y_13_16_14 == 1,y_16_13_14 == 1)

How can I resolve the error?

Sana.Nz
  • 81
  • 11

2 Answers2

0

instead of if_then that needs linear constraints you could use truth values.

Let me give you a tiny example out of the bus example

from docplex.mp.model import Model

mdl = Model(name='buses')
nbbus40 = mdl.integer_var(name='nbBus40')
nbbus30 = mdl.integer_var(name='nbBus30')
mdl.add_constraint(nbbus40*40 + nbbus30*30 >= 300, 'kids')
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

for v in mdl.iter_integer_vars():
   print(v," = ",v.solution_value)



#if then constraint
mdl.add(mdl.logical_or(nbbus40<=2,nbbus30<=2 )<=(nbbus30>=7))
mdl.minimize(nbbus40*500 + nbbus30*400)

mdl.solve()

 

for v in mdl.iter_integer_vars():
    print(v," = ",v.solution_value) 
Alex Fleischer
  • 9,276
  • 2
  • 12
  • 15
0

Model.logical_or returns an expression , equal to 1 if one of the argument is true; Model.if_then expects a linear constraint, so you need to convert the expression into a constraint, for example, write (Model.logical_or(a,b) ==1)

In this small example, I state that c equals 1 when either a or b equal 1 (Note that logical operators such as logical_or or logical_and accept binary variables, no need to add '==1' there:

m = Model()
[a,b,c] = m.binary_var_list(keys=['a', 'b', 'c'], name=str)
# if a or b then c
m.add(m.if_then(m.logical_or(a,b) == 1, c==1))
m.maximize(a+b)
m.solve()
m.print_solution()

and the result is:

objective: 2
  "a"=1
  "b"=1
  "c"=1
Philippe Couronne
  • 826
  • 1
  • 5
  • 6