4 N.B.: standard SCIP XOR constraint works differently from AND/OR by design.
5 The constraint is set with a boolean rhs instead of an integer resultant.
6 cf. http://listserv.zib.de/pipermail/scip/2018-May/003392.html
7 A workaround to get the resultant as variable is here proposed.
9 Public Domain, WTFNMFPL Public Licence
11 from pyscipopt
import Model
12 from pyscipopt
import quicksum
17 x = model.addVar(
"x",
"B")
18 y = model.addVar(
"y",
"B")
19 z = model.addVar(
"z",
"B")
22 def _optimize(name, m):
24 print(
"* %s constraint *" % name)
25 objSet = bool(m.getObjective().terms.keys())
26 print(
"* Is objective set? %s" % objSet)
28 print(
"* Sense: %s" % m.getObjectiveSense())
29 status = m.getStatus()
30 print(
"* Model status: %s" % status)
31 if status ==
'optimal':
34 print(
"%s: %d" % (v, round(m.getVal(v))))
36 print(
"* No variable is printed if model status is not optimal")
40 """ AND constraint """
41 assert v
in [0,1],
"v must be 0 or 1 instead of %s" % v.__repr__()
42 model, x, y, z = _init()
43 r = model.addVar(
"r",
"B")
44 model.addConsAnd([x,y,z], r)
46 model.setObjective(r, sense=sense)
47 _optimize(
"AND", model)
52 assert v
in [0,1],
"v must be 0 or 1 instead of %s" % v.__repr__()
53 model, x, y, z = _init()
54 r = model.addVar(
"r",
"B")
55 model.addConsOr([x,y,z], r)
57 model.setObjective(r, sense=sense)
58 _optimize(
"OR", model)
61 """ XOR (r as boolean) standard constraint"""
62 assert v
in [0,1],
"v must be 0 or 1 instead of %s" % v.__repr__()
63 model, x, y, z = _init()
65 model.addConsXor([x,y,z], r)
67 _optimize(
"Standard XOR (as boolean)", model)
70 """ XOR (r as variable) custom constraint"""
71 assert v
in [0,1],
"v must be 0 or 1 instead of %s" % v.__repr__()
72 model, x, y, z = _init()
73 r = model.addVar(
"r",
"B")
74 n = model.addVar(
"n",
"I")
75 model.addCons(r+
quicksum([x,y,z]) == 2*n)
77 model.setObjective(r, sense=sense)
78 _optimize(
"Custom XOR (as variable)", model)
80 if __name__ ==
"__main__":