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 package org.sat4j.opt;
27
28 import java.math.BigInteger;
29
30 import org.sat4j.core.Vec;
31 import org.sat4j.core.VecInt;
32 import org.sat4j.specs.ContradictionException;
33 import org.sat4j.specs.IConstr;
34 import org.sat4j.specs.IOptimizationProblem;
35 import org.sat4j.specs.ISolver;
36 import org.sat4j.specs.IVec;
37 import org.sat4j.specs.IVecInt;
38
39 public class WeightedMaxSatDecorator extends AbstractSelectorVariablesDecorator
40 implements IOptimizationProblem {
41
42
43
44
45 private static final long serialVersionUID = 1L;
46
47 private final IVec<BigInteger> coefs = new Vec<BigInteger>();
48
49 public WeightedMaxSatDecorator(ISolver solver) {
50 super(solver);
51 }
52
53
54 protected int top = -1;
55
56 public void setTopWeight(int top) {
57 this.top = top;
58 }
59
60 @Override
61 public IConstr addClause(IVecInt literals) throws ContradictionException {
62 int weight = literals.get(0);
63 if (weight<top) {
64 coefs.push(BigInteger.valueOf(weight));
65 literals.set(0, nborigvars + ++nbnewvar);
66 } else {
67 literals.delete(0);
68 }
69 return super.addClause(literals);
70 }
71
72 @Override
73 public void reset() {
74 coefs.clear();
75 vec.clear();
76 super.reset();
77 }
78
79 public boolean hasNoObjectiveFunction() {
80 return false;
81 }
82
83 public boolean nonOptimalMeansSatisfiable() {
84 return false;
85 }
86
87 private BigInteger counter;
88
89 public Number calculateObjective() {
90 counter = BigInteger.ZERO;
91 for (int q : prevfullmodel) {
92 if (q > nborigvars) {
93 counter = counter.add(coefs.get(q - nborigvars - 1));
94 }
95 }
96 return counter;
97 }
98
99 private final IVecInt vec = new VecInt();
100
101
102
103 public void discard() throws ContradictionException {
104 if (vec.isEmpty()) {
105 for (int i = 1; i <= nbnewvar; i++) {
106 vec.push(nborigvars+i);
107 }
108 }
109
110
111
112
113 super.addPseudoBoolean(vec, coefs, false, counter
114 .subtract(BigInteger.ONE));
115 }
116
117 }