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
18 x = model.addVar(
"x",
"B")
19 y = model.addVar(
"y",
"B")
20 z = model.addVar(
"z",
"B")
24 def _optimize(name, m):
26 print(
"* %s constraint *" % name)
27 objSet = bool(m.getObjective().terms.keys())
28 print(
"* Is objective set? %s" % objSet)
30 print(
"* Sense: %s" % m.getObjectiveSense())
31 status = m.getStatus()
32 print(
"* Model status: %s" % status)
33 if status ==
'optimal':
36 print(
"%s: %d" % (v, round(m.getVal(v))))
38 print(
"* No variable is printed if model status is not optimal")
43 """ AND constraint """
44 assert v
in [0, 1],
"v must be 0 or 1 instead of %s" % v.__repr__()
45 model, x, y, z = _init()
46 r = model.addVar(
"r",
"B")
47 model.addConsAnd([x, y, z], r)
49 model.setObjective(r, sense=sense)
50 _optimize(
"AND", model)
55 assert v
in [0, 1],
"v must be 0 or 1 instead of %s" % v.__repr__()
56 model, x, y, z = _init()
57 r = model.addVar(
"r",
"B")
58 model.addConsOr([x, y, z], r)
60 model.setObjective(r, sense=sense)
61 _optimize(
"OR", model)
65 """ XOR (r as boolean) standard constraint"""
66 assert v
in [0, 1],
"v must be 0 or 1 instead of %s" % v.__repr__()
67 model, x, y, z = _init()
69 model.addConsXor([x, y, z], r)
71 _optimize(
"Standard XOR (as boolean)", model)
75 """ XOR (r as variable) custom constraint"""
76 assert v
in [0, 1],
"v must be 0 or 1 instead of %s" % v.__repr__()
77 model, x, y, z = _init()
78 r = model.addVar(
"r",
"B")
79 n = model.addVar(
"n",
"I")
80 model.addCons(r +
quicksum([x, y, z]) == 2 * n)
82 model.setObjective(r, sense=sense)
83 _optimize(
"Custom XOR (as variable)", model)
86 if __name__ ==
"__main__":