View Javadoc

1   /*******************************************************************************
2   * SAT4J: a SATisfiability library for Java Copyright (C) 2004-2008 Daniel Le Berre
3   *
4   * All rights reserved. This program and the accompanying materials
5   * are made available under the terms of the Eclipse Public License v1.0
6   * which accompanies this distribution, and is available at
7   * http://www.eclipse.org/legal/epl-v10.html
8   *
9   * Alternatively, the contents of this file may be used under the terms of
10  * either the GNU Lesser General Public License Version 2.1 or later (the
11  * "LGPL"), in which case the provisions of the LGPL are applicable instead
12  * of those above. If you wish to allow use of your version of this file only
13  * under the terms of the LGPL, and not to allow others to use your version of
14  * this file under the terms of the EPL, indicate your decision by deleting
15  * the provisions above and replace them with the notice and other provisions
16  * required by the LGPL. If you do not delete the provisions above, a recipient
17  * may use your version of this file under the terms of the EPL or the LGPL.
18  * 
19  * Based on the pseudo boolean algorithms described in:
20  * A fast pseudo-Boolean constraint solver Chai, D.; Kuehlmann, A.
21  * Computer-Aided Design of Integrated Circuits and Systems, IEEE Transactions on
22  * Volume 24, Issue 3, March 2005 Page(s): 305 - 317
23  * 
24  * and 
25  * Heidi E. Dixon, 2004. Automating Pseudo-Boolean Inference within a DPLL 
26  * Framework. Ph.D. Dissertation, University of Oregon.
27  *******************************************************************************/
28  package org.sat4j.pb.reader;
29  
30  import java.io.IOException;
31  import java.io.LineNumberReader;
32  import java.io.PrintWriter;
33  import java.io.Serializable;
34  import java.math.BigInteger;
35  import java.util.HashMap;
36  import java.util.Map;
37  import java.util.Scanner;
38  
39  import org.sat4j.core.Vec;
40  import org.sat4j.core.VecInt;
41  import org.sat4j.pb.IPBSolver;
42  import org.sat4j.reader.ParseFormatException;
43  import org.sat4j.reader.Reader;
44  import org.sat4j.specs.ContradictionException;
45  import org.sat4j.specs.IProblem;
46  import org.sat4j.specs.IVec;
47  import org.sat4j.specs.IVecInt;
48  
49  /**
50   * This class is a quick hack to read opb formatted files. The reader skip
51   * commented lines (beginning with COMMENT_SYMBOL) and expect constraints of the
52   * form: [name :] [[+|-]COEF] [*] [+|-]LIT >=|<=|= DEGREE where COEF and DEGREE
53   * are plain integer and LIT is an identifier.
54   * 
55   * @author leberre
56   */
57  public class GoodOPBReader extends Reader implements Serializable {
58  
59      /**
60       * Comment for <code>serialVersionUID</code>
61       */
62      private static final long serialVersionUID = 1L;
63  
64      private static final String COMMENT_SYMBOL = "*";
65  
66      private final IPBSolver solver;
67  
68      private final Map<String, Integer> map = new HashMap<String, Integer>();
69  
70      private final IVec<String> decode = new Vec<String>();
71  
72      /**
73       * 
74       */
75      public GoodOPBReader(IPBSolver solver) {
76          this.solver = solver;
77      }
78  
79      @Override
80      public final IProblem parseInstance(final java.io.Reader in)
81              throws ParseFormatException, ContradictionException, IOException {
82          return parseInstance(new LineNumberReader(in));
83      }
84  
85      private IProblem parseInstance(LineNumberReader in)
86              throws ContradictionException, IOException {
87          solver.reset();
88          String line;
89          while ((line = in.readLine()) != null) {
90              // cannot trim is line is null
91              line = line.trim();
92              if (line.endsWith(";")) {
93                  line = line.substring(0, line.length() - 1);
94              }
95              parseLine(line);
96          }
97          return solver;
98      }
99  
100     void parseLine(String line) throws ContradictionException {
101         // Skip commented line
102         if (line.startsWith(COMMENT_SYMBOL))
103             return;
104         if (line.startsWith("p")) // ignore p cnf with pbchaff format
105             return;
106         if (line.startsWith("min:") || line.startsWith("min :"))
107             return; // we will use that case later
108         if (line.startsWith("max:") || line.startsWith("max :"))
109             return; // we will use that case later
110 
111         // skip name of constraints:
112         int index = line.indexOf(":");
113         if (index != -1) {
114             line = line.substring(index + 1);
115         }
116 
117         IVecInt lits = new VecInt();
118         IVec<BigInteger> coeffs = new Vec<BigInteger>();
119         Scanner stk = new Scanner(line)
120                 .useDelimiter("\\s*\\*\\s*|\\s*\\+\\s*|\\s+");
121         while (stk.hasNext()) {
122             String token = stk.next();
123             if (">=".equals(token) || "<=".equals(token) || "=".equals(token)) {
124                 assert stk.hasNext();
125                 String tok = stk.next();
126                 // we need to remove + from the integer
127                 if (tok.startsWith("+")) {
128                     tok = tok.substring(1);
129                 }
130                 BigInteger d = new BigInteger(tok);
131 
132                 try {
133                     if (">=".equals(token) || "=".equals(token)) {
134                         solver.addPseudoBoolean(lits, coeffs, true, d);
135                     }
136                     if ("<=".equals(token) || "=".equals(token)) {
137                         solver.addPseudoBoolean(lits, coeffs, false, d);
138                     }
139                 } catch (ContradictionException ce) {
140                     throw ce;
141                 }
142             } else {
143                 // on est toujours en train de lire la partie gauche de la
144                 // contrainte
145                 if ("+".equals(token)) {
146                     assert stk.hasNext();
147                     token = stk.next();
148                 } else if ("-".equals(token)) {
149                     assert stk.hasNext();
150                     token = token + stk.next();
151                 }
152                 BigInteger coef;
153                 // should contain a coef and a literal
154                 try {
155                     // we need to remove + from the integer
156                     if (token.startsWith("+")) {
157                         token = token.substring(1);
158                     }
159                     coef = new BigInteger(token);
160                     assert stk.hasNext();
161                     token = stk.next();
162                 } catch (NumberFormatException nfe) {
163                     // its only an identifier
164                     coef = BigInteger.ONE;
165                 }
166                 if ("-".equals(token) || "~".equals(token)) {
167                     assert stk.hasNext();
168                     token = token + stk.next();
169                 }
170                 boolean negative = false;
171                 if (token.startsWith("+")) {
172                     token = token.substring(1);
173                 } else if (token.startsWith("-")) {
174                     token = token.substring(1);
175                     assert coef.equals(BigInteger.ONE);
176                     coef = BigInteger.ONE.negate();
177                 } else if (token.startsWith("~")) {
178                     token = token.substring(1);
179                     negative = true;
180                 }
181                 Integer id = map.get(token);
182                 if (id == null) {
183                 	id = decode.size()+1;
184                     map.put(token, id);
185                     decode.push(token);
186                 }
187                 coeffs.push(coef);
188                 int lid = (negative ? -1 : 1) * id.intValue();
189                 lits.push(lid);
190                 assert coeffs.size() == lits.size();
191             }
192         }
193     }
194 
195     @Override
196     public String decode(int[] model) {
197         StringBuffer stb = new StringBuffer();
198         for (int i = 0; i < model.length; i++) {
199             if (model[i] < 0) {
200                 stb.append("-");
201                 stb.append(decode.get(-model[i] - 1));
202             } else {
203                 stb.append(decode.get(model[i] - 1));
204             }
205             stb.append(" ");
206         }
207         return stb.toString();
208     }
209 
210     @Override
211     public void decode(int[] model, PrintWriter out) {
212         for (int i = 0; i < model.length; i++) {
213             if (model[i] < 0) {
214                 out.print("-");
215                 out.print(decode.get(-model[i] - 1));
216             } else {
217                 out.print(decode.get(model[i] - 1));
218             }
219             out.print(" ");
220         }
221     }
222 }