1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 package org.sat4j.reader;
31
32 import java.io.IOException;
33
34 import org.sat4j.specs.ContradictionException;
35 import org.sat4j.specs.IGroupSolver;
36
37 public class GroupedCNFReader extends DimacsReader {
38
39
40
41
42 private static final long serialVersionUID = 1L;
43
44 private int numberOfComponents;
45
46 private final IGroupSolver groupSolver;
47
48 private int currentComponentIndex;
49
50 public GroupedCNFReader(IGroupSolver solver) {
51 super(solver, "gcnf");
52 this.groupSolver = solver;
53 }
54
55
56
57
58
59
60
61
62
63
64 @Override
65 protected void readProblemLine() throws IOException, ParseFormatException {
66
67 String line = this.scanner.nextLine();
68 assert line != null;
69 line = line.trim();
70 String[] tokens = line.split("\\s+");
71 if (tokens.length < 5 || !"p".equals(tokens[0])
72 || !this.formatString.equals(tokens[1])) {
73 throw new ParseFormatException("problem line expected (p "
74 + this.formatString + " ...)");
75 }
76
77 int vars;
78
79
80 vars = Integer.parseInt(tokens[2]);
81 assert vars > 0;
82 this.solver.newVar(vars);
83
84 this.expectedNbOfConstr = Integer.parseInt(tokens[3]);
85 assert this.expectedNbOfConstr > 0;
86 this.numberOfComponents = Integer.parseInt(tokens[4]);
87 this.solver.setExpectedNumberOfClauses(this.expectedNbOfConstr);
88 }
89
90
91
92
93 @Override
94 protected boolean handleLine() throws ContradictionException, IOException,
95 ParseFormatException {
96 int lit;
97 boolean added = false;
98 String component = this.scanner.next();
99 if (!component.startsWith("{") || !component.endsWith("}")) {
100 throw new ParseFormatException(
101 "Component index required at the beginning of the clause");
102 }
103 this.currentComponentIndex = Integer.valueOf(component.substring(1,
104 component.length() - 1));
105 if (this.currentComponentIndex < 0
106 || this.currentComponentIndex > this.numberOfComponents) {
107 throw new ParseFormatException("wrong component index: "
108 + this.currentComponentIndex);
109 }
110 while (!this.scanner.eof()) {
111 lit = this.scanner.nextInt();
112 if (lit == 0) {
113 if (this.literals.size() > 0) {
114 flushConstraint();
115 this.literals.clear();
116 added = true;
117 }
118 break;
119 }
120 this.literals.push(lit);
121 }
122 return added;
123 }
124
125
126
127
128
129
130 @Override
131 protected void flushConstraint() throws ContradictionException {
132 try {
133 if (this.currentComponentIndex == 0) {
134 this.groupSolver.addClause(this.literals);
135 } else {
136 this.groupSolver.addClause(this.literals,
137 this.currentComponentIndex);
138 }
139 } catch (IllegalArgumentException ex) {
140 if (isVerbose()) {
141 System.err.println("c Skipping constraint " + this.literals);
142 }
143 }
144 }
145 }