1 |
| package org.sat4j.reader.csp; |
2 |
| |
3 |
| import java.util.HashMap; |
4 |
| import java.util.Map; |
5 |
| |
6 |
| import org.sat4j.core.VecInt; |
7 |
| import org.sat4j.specs.ContradictionException; |
8 |
| import org.sat4j.specs.ISolver; |
9 |
| import org.sat4j.specs.IVecInt; |
10 |
| |
11 |
| public class BinarySupportsACEncoding extends SupportsDirectEncoding { |
12 |
| |
13 |
0
| public BinarySupportsACEncoding(int[] domains, int nbtuples) {
|
14 |
0
| super(domains, nbtuples);
|
15 |
0
| if (domains.length != 2)
|
16 |
0
| throw new UnsupportedOperationException(
|
17 |
| "Works only for binary constraints"); |
18 |
| } |
19 |
| |
20 |
0
| @Override
|
21 |
| public void toClause(ISolver solver, Var[] vars) |
22 |
| throws ContradictionException { |
23 |
0
| Map<Integer, IVecInt> supportsa = new HashMap<Integer, IVecInt>();
|
24 |
0
| Map<Integer, IVecInt> supportsb = new HashMap<Integer, IVecInt>();
|
25 |
| |
26 |
0
| for (int i = 0; i < tuples.length; i++) {
|
27 |
| assert domains.length == 2; |
28 |
0
| int va = tuples[i][0];
|
29 |
0
| int vb = tuples[i][1];
|
30 |
0
| addSupport(va, vars[1], vb, supportsa);
|
31 |
0
| addSupport(vb, vars[0], va, supportsb);
|
32 |
| } |
33 |
| |
34 |
0
| generateClauses(vars[0], supportsa, solver);
|
35 |
0
| generateClauses(vars[1], supportsb, solver);
|
36 |
| } |
37 |
| |
38 |
0
| private void addSupport(int head, Var v, int value,
|
39 |
| Map<Integer, IVecInt> supports) { |
40 |
0
| IVecInt sup = supports.get(head);
|
41 |
0
| if (sup == null) {
|
42 |
0
| sup = new VecInt();
|
43 |
0
| supports.put(head, sup);
|
44 |
| } |
45 |
0
| sup.push(v.translate(value));
|
46 |
| } |
47 |
| |
48 |
0
| private void generateClauses(Var v, Map<Integer, IVecInt> supports,
|
49 |
| ISolver solver) throws ContradictionException { |
50 |
0
| IVecInt clause = new VecInt();
|
51 |
0
| for (int key : v.domain()) {
|
52 |
0
| clause.clear();
|
53 |
0
| IVecInt support = supports.get(key);
|
54 |
0
| clause.push(-v.translate(key));
|
55 |
0
| if (support != null) {
|
56 |
0
| for (int i : support)
|
57 |
0
| clause.push(i);
|
58 |
| } |
59 |
0
| solver.addClause(clause);
|
60 |
| } |
61 |
| } |
62 |
| } |