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 package org.sat4j.pb;
29
30 import java.io.Serializable;
31 import java.math.BigInteger;
32
33 import org.sat4j.core.ReadOnlyVec;
34 import org.sat4j.core.ReadOnlyVecInt;
35 import org.sat4j.specs.ISolver;
36 import org.sat4j.specs.IVec;
37 import org.sat4j.specs.IVecInt;
38
39
40
41
42
43
44
45
46
47 public class ObjectiveFunction implements Serializable {
48
49
50
51
52 private static final long serialVersionUID = 1L;
53
54
55 private final IVec<BigInteger> coeffs;
56
57 private final IVecInt vars;
58
59 private BigInteger correction = BigInteger.ZERO;
60
61 public ObjectiveFunction(IVecInt vars, IVec<BigInteger> coeffs) {
62 this.vars = new ReadOnlyVecInt(vars);
63 this.coeffs = new ReadOnlyVec<BigInteger>(coeffs);
64 }
65
66
67 public BigInteger calculateDegree(ISolver solver) {
68 BigInteger tempDegree = BigInteger.ZERO;
69
70 for (int i = 0; i < vars.size(); i++) {
71 BigInteger coeff = coeffs.get(i);
72 if (varInModel(vars.get(i), solver))
73 tempDegree = tempDegree.add(coeff);
74 else if ((coeff.signum() < 0) && !varInModel(-vars.get(i), solver)) {
75
76
77 tempDegree = tempDegree.add(coeff);
78 }
79 }
80 return tempDegree;
81 }
82
83 private boolean varInModel(int var, ISolver solver) {
84 if (var > 0)
85 return solver.model(var);
86 return !solver.model(-var);
87 }
88
89 public IVec<BigInteger> getCoeffs() {
90 return coeffs;
91 }
92
93 public IVecInt getVars() {
94 return vars;
95 }
96
97 public void setCorrection(BigInteger correction) {
98 this.correction = correction;
99 }
100
101 public BigInteger getCorrection() {
102 return correction;
103 }
104
105 @Override
106 public String toString() {
107 StringBuffer stb = new StringBuffer();
108 IVecInt lits = getVars();
109 IVec<BigInteger> coefs = getCoeffs();
110 BigInteger coef;
111 int lit;
112 for (int i = 0; i < lits.size(); i++) {
113 coef = coefs.get(i);
114 lit = lits.get(i);
115 if (lit < 0) {
116 lit = -lit;
117 coef = coef.negate();
118 }
119 stb.append((coef.signum() < 0 ? "" : "+") + coef + " x" + lit + " ");
120 }
121 return stb.toString();
122 }
123
124 public BigInteger minValue() {
125 BigInteger tempDegree = BigInteger.ZERO;
126 for (int i = 0; i < vars.size(); i++) {
127 BigInteger coeff = coeffs.get(i);
128 if (coeff.signum() < 0) {
129 tempDegree = tempDegree.add(coeff);
130 }
131 }
132 return tempDegree;
133 }
134
135 }