PySCIPOpt  5.1.1
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 
21 def printFunc(name, m):
22  """prints results"""
23  print("* %s *" % name)
24  objSet = bool(m.getObjective().terms.keys())
25  print("* Is objective set? %s" % objSet)
26  if objSet:
27  print("* Sense: %s" % m.getObjectiveSense())
28  for v in m.getVars():
29  if v.name != "n":
30  print("%s: %d" % (v, round(m.getVal(v))))
31  print("\n")
32 
33 
34 # AND
35 model = Model()
36 model.hideOutput()
37 x = model.addVar("x", "B")
38 y = model.addVar("y", "B")
39 z = model.addVar("z", "B")
40 r = model.addVar("r", "B")
41 model.addConsAnd([x, y, z], r)
42 model.addCons(x == 1)
43 model.setObjective(r, sense="minimize")
44 model.optimize()
45 printFunc("AND", model)
46 
47 # OR
48 model = Model()
49 model.hideOutput()
50 x = model.addVar("x", "B")
51 y = model.addVar("y", "B")
52 z = model.addVar("z", "B")
53 r = model.addVar("r", "B")
54 model.addConsOr([x, y, z], r)
55 model.addCons(x == 0)
56 model.setObjective(r, sense="maximize")
57 model.optimize()
58 printFunc("OR", model)
59 
60 # XOR (r as boolean, standard)
61 model = Model()
62 model.hideOutput()
63 x = model.addVar("x", "B")
64 y = model.addVar("y", "B")
65 z = model.addVar("z", "B")
66 r = True
67 model.addConsXor([x, y, z], r)
68 model.addCons(x == 1)
69 model.optimize()
70 printFunc("Standard XOR (as boolean)", model)
71 
72 # XOR (r as variable, custom)
73 model = Model()
74 model.hideOutput()
75 x = model.addVar("x", "B")
76 y = model.addVar("y", "B")
77 z = model.addVar("z", "B")
78 r = model.addVar("r", "B")
79 n = model.addVar("n", "I") # auxiliary
80 model.addCons(r + quicksum([x, y, z]) == 2 * n)
81 model.addCons(x == 0)
82 model.setObjective(r, sense="maximize")
83 model.optimize()
84 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:21