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