1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.sat4j.csp.encodings;
20
21 import java.util.HashMap;
22 import java.util.Map;
23
24 import org.sat4j.core.VecInt;
25 import org.sat4j.csp.Encoding;
26 import org.sat4j.csp.Evaluable;
27 import org.sat4j.csp.Var;
28 import org.sat4j.specs.ContradictionException;
29 import org.sat4j.specs.ISolver;
30 import org.sat4j.specs.IVec;
31 import org.sat4j.specs.IVecInt;
32 import org.sat4j.specs.IteratorInt;
33
34 public class BinarySupportEncoding implements Encoding {
35
36 private final Map<Integer, IVecInt> supportsa = new HashMap<Integer, IVecInt>();
37
38 private final Map<Integer, IVecInt> supportsb = new HashMap<Integer, IVecInt>();
39
40 private static final Encoding INSTANCE = new BinarySupportEncoding();
41
42 private BinarySupportEncoding() {
43
44 }
45
46 public static Encoding instance() {
47 return INSTANCE;
48 }
49
50 public void onFinish(ISolver solver, IVec<Var> scope)
51 throws ContradictionException {
52 generateClauses(scope.get(0), supportsa, solver);
53 generateClauses(scope.get(1), supportsb, solver);
54
55 }
56
57 public void onInit(ISolver solver, IVec<Var> scope) {
58 supportsa.clear();
59 supportsb.clear();
60 }
61
62 public void onNogood(ISolver solver, IVec<Var> scope,
63 Map<Evaluable, Integer> tuple) throws ContradictionException {
64 }
65
66 public void onSupport(ISolver solver, IVec<Var> scope,
67 Map<Evaluable, Integer> tuple) throws ContradictionException {
68 Var vara = scope.get(0);
69 Integer va = tuple.get(vara);
70 Var varb = scope.get(1);
71 Integer vb = tuple.get(varb);
72 addSupport(va, varb, vb, supportsa);
73 addSupport(vb, vara, va, supportsb);
74 }
75
76 private void addSupport(Integer head, Evaluable v, Integer value,
77 Map<Integer, IVecInt> supports) {
78 IVecInt sup = supports.get(head);
79 if (sup == null) {
80 sup = new VecInt();
81 supports.put(head, sup);
82 }
83 sup.push(v.translate(value.intValue()));
84 }
85
86 private void generateClauses(Evaluable v, Map<Integer, IVecInt> supports,
87 ISolver solver) throws ContradictionException {
88 IVecInt clause = new VecInt();
89 for (IteratorInt it = v.domain().iterator() ; it.hasNext();) {
90 int key = it.next();
91 clause.clear();
92 IVecInt support = supports.get(key);
93 clause.push(-v.translate(key));
94 if (support != null) {
95 for (IteratorInt iterator = support.iterator() ; iterator.hasNext();)
96 clause.push(iterator.next());
97 }
98 solver.addClause(clause);
99 }
100 }
101
102 }