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.maxsat.reader;
31
32 import java.io.IOException;
33 import java.math.BigInteger;
34
35 import org.sat4j.maxsat.WeightedMaxSatDecorator;
36 import org.sat4j.reader.DimacsReader;
37 import org.sat4j.reader.ParseFormatException;
38 import org.sat4j.specs.ContradictionException;
39
40
41
42
43
44
45
46 public class WDimacsReader extends DimacsReader {
47
48 protected BigInteger weight;
49 protected BigInteger top;
50
51 @Override
52 protected void flushConstraint() throws ContradictionException {
53 try {
54 this.decorator.addSoftClause(this.weight, this.literals);
55 } catch (IllegalArgumentException ex) {
56 if (isVerbose()) {
57 System.err.println("c Skipping constraint " + this.literals);
58 }
59 }
60
61 }
62
63 @Override
64 protected boolean handleLine() throws ContradictionException, IOException,
65 ParseFormatException {
66 this.weight = this.scanner.nextBigInteger();
67 return super.handleLine();
68 }
69
70
71
72
73 private static final long serialVersionUID = 1L;
74
75 private final WeightedMaxSatDecorator decorator;
76
77 public WDimacsReader(WeightedMaxSatDecorator solver) {
78 super(solver, "wcnf");
79 this.decorator = solver;
80 }
81
82 public WDimacsReader(WeightedMaxSatDecorator solver, String format) {
83 super(solver, format);
84 this.decorator = solver;
85 }
86
87 @Override
88 protected void readProblemLine() throws IOException, ParseFormatException {
89 String line = this.scanner.nextLine().trim();
90
91 if (line == null) {
92 throw new ParseFormatException(
93 "premature end of file: <p cnf ...> expected");
94 }
95 String[] tokens = line.split("\\s+");
96 if (tokens.length < 4 || !"p".equals(tokens[0])
97 || !this.formatString.equals(tokens[1])) {
98 throw new ParseFormatException("problem line expected (p cnf ...)");
99 }
100
101 int vars;
102
103
104 vars = Integer.parseInt(tokens[2]);
105 assert vars > 0;
106 this.solver.newVar(vars);
107
108 this.expectedNbOfConstr = Integer.parseInt(tokens[3]);
109 assert this.expectedNbOfConstr > 0;
110 this.solver.setExpectedNumberOfClauses(this.expectedNbOfConstr);
111
112 if ("wcnf".equals(this.formatString)) {
113
114 if (tokens.length == 5) {
115 this.top = new BigInteger(tokens[4]);
116 } else {
117 this.top = WeightedMaxSatDecorator.SAT4J_MAX_BIG_INTEGER;
118 }
119 this.decorator.setTopWeight(this.top);
120 }
121 }
122
123 }