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