1 /*
2 * SAT4J: a SATisfiability library for Java Copyright (C) 2004-2006 Daniel Le Berre
3 *
4 * Based on the original minisat specification from:
5 *
6 * An extensible SAT solver. Niklas E?n and Niklas S?rensson. Proceedings of the
7 * Sixth International Conference on Theory and Applications of Satisfiability
8 * Testing, LNCS 2919, pp 502-518, 2003.
9 *
10 * This library is free software; you can redistribute it and/or modify it under
11 * the terms of the GNU Lesser General Public License as published by the Free
12 * Software Foundation; either version 2.1 of the License, or (at your option)
13 * any later version.
14 *
15 * This library is distributed in the hope that it will be useful, but WITHOUT
16 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
17 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
18 * details.
19 *
20 * You should have received a copy of the GNU Lesser General Public License
21 * along with this library; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23 *
24 */
25 package org.sat4j.opt;
26
27 import org.sat4j.core.VecInt;
28 import org.sat4j.specs.ContradictionException;
29 import org.sat4j.specs.IOptimizationProblem;
30 import org.sat4j.specs.ISolver;
31 import org.sat4j.specs.IVecInt;
32 import org.sat4j.specs.TimeoutException;
33 import org.sat4j.tools.SolverDecorator;
34
35 /**
36 * Computes a solution with the smallest number of satisfied literals.
37 *
38 * Please make sure that newVar(howmany) is called first to setup the decorator.
39 *
40 * @author leberre
41 */
42 public class MinOneDecorator extends SolverDecorator implements
43 IOptimizationProblem {
44
45 /**
46 *
47 */
48 private static final long serialVersionUID = 1L;
49
50 private int[] prevmodel;
51
52 public MinOneDecorator(ISolver solver) {
53 super(solver);
54 }
55
56 public boolean admitABetterSolution() throws TimeoutException {
57 boolean result = isSatisfiable();
58 if (result) {
59 prevmodel = super.model();
60 }
61 return result;
62 }
63
64 public boolean hasNoObjectiveFunction() {
65 return false;
66 }
67
68 public boolean nonOptimalMeansSatisfiable() {
69 return true;
70 }
71
72 private int counter;
73
74 public Number calculateObjective() {
75 counter = 0;
76 for (int p : prevmodel) {
77 if (p > 0) {
78 counter++;
79 }
80 }
81 return counter;
82 }
83
84 private final IVecInt literals = new VecInt();
85
86 public void discard() throws ContradictionException {
87 if (literals.isEmpty()) {
88 for (int i = 1; i <= nVars(); i++) {
89 literals.push(i);
90 }
91 }
92 addAtMost(literals, counter - 1);
93 }
94
95 @Override
96 public int[] model() {
97 // DLB findbugs ok
98 return prevmodel;
99 }
100
101 @Override
102 public void reset() {
103 literals.clear();
104 super.reset();
105 }
106
107 }