PySCIPOpt  4.3.0
Python Interface for the SCIP Optimization Suite
logical.py
Go to the documentation of this file.
1 
3 
4 from pyscipopt import Model
5 from pyscipopt import quicksum
6 
7 """
8 
9  AND/OR/XOR CONSTRAINTS
10 
11  Tutorial example on how to use AND/OR/XOR constraints.
12 
13  N.B.: standard SCIP XOR constraint works differently from AND/OR by design.
14  The constraint is set with a boolean rhs instead of an integer resultant.
15  cf. http://listserv.zib.de/pipermail/scip/2018-May/003392.html
16  A workaround to get the resultant as variable is here proposed.
17 
18 """
19 
20 def printFunc(name,m):
21  """prints results"""
22  print("* %s *" % name)
23  objSet = bool(m.getObjective().terms.keys())
24  print("* Is objective set? %s" % objSet)
25  if objSet:
26  print("* Sense: %s" % m.getObjectiveSense())
27  for v in m.getVars():
28  if v.name != "n":
29  print("%s: %d" % (v, round(m.getVal(v))))
30  print("\n")
31 
32 # AND
33 model = Model()
34 model.hideOutput()
35 x = model.addVar("x","B")
36 y = model.addVar("y","B")
37 z = model.addVar("z","B")
38 r = model.addVar("r","B")
39 model.addConsAnd([x,y,z],r)
40 model.addCons(x==1)
41 model.setObjective(r,sense="minimize")
42 model.optimize()
43 printFunc("AND",model)
44 
45 # OR
46 model = Model()
47 model.hideOutput()
48 x = model.addVar("x","B")
49 y = model.addVar("y","B")
50 z = model.addVar("z","B")
51 r = model.addVar("r","B")
52 model.addConsOr([x,y,z],r)
53 model.addCons(x==0)
54 model.setObjective(r,sense="maximize")
55 model.optimize()
56 printFunc("OR",model)
57 
58 # XOR (r as boolean, standard)
59 model = Model()
60 model.hideOutput()
61 x = model.addVar("x","B")
62 y = model.addVar("y","B")
63 z = model.addVar("z","B")
64 r = True
65 model.addConsXor([x,y,z],r)
66 model.addCons(x==1)
67 model.optimize()
68 printFunc("Standard XOR (as boolean)",model)
69 
70 # XOR (r as variable, custom)
71 model = Model()
72 model.hideOutput()
73 x = model.addVar("x","B")
74 y = model.addVar("y","B")
75 z = model.addVar("z","B")
76 r = model.addVar("r","B")
77 n = model.addVar("n","I") #auxiliary
78 model.addCons(r+quicksum([x,y,z]) == 2*n)
79 model.addCons(x==0)
80 model.setObjective(r,sense="maximize")
81 model.optimize()
82 printFunc("Custom XOR (as variable)",model)
pyscipopt.expr.quicksum
def quicksum(termlist)
Definition: expr.pxi:357
logical.printFunc
def printFunc(name, m)
Definition: logical.py:20