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;
29
30 import java.io.PrintWriter;
31
32 import org.sat4j.specs.ContradictionException;
33 import org.sat4j.specs.IOptimizationProblem;
34 import org.sat4j.specs.IProblem;
35 import org.sat4j.specs.TimeoutException;
36
37
38
39
40
41
42
43
44
45 public abstract class AbstractOptimizationLauncher extends AbstractLauncher {
46
47
48
49
50 private static final long serialVersionUID = 1L;
51
52 private static final String CURRENT_OPTIMUM_VALUE_PREFIX = "o ";
53
54 @Override
55 protected void displayResult() {
56 displayAnswer();
57
58 log("Total wall clock time (in seconds): "
59 + (System.currentTimeMillis() - getBeginTime()) / 1000.0);
60 }
61
62 protected void displayAnswer() {
63 if (solver == null)
64 return;
65 PrintWriter out = getLogWriter();
66 solver.printStat(out, COMMENT_PREFIX);
67 solver.printInfos(out, COMMENT_PREFIX);
68 ExitCode exitCode = getExitCode();
69 out.println(ANSWER_PREFIX + exitCode);
70 if (exitCode == ExitCode.SATISFIABLE
71 || exitCode == ExitCode.OPTIMUM_FOUND) {
72 out.print(SOLUTION_PREFIX);
73 getReader().decode(solver.model(), out);
74 out.println();
75 IOptimizationProblem optproblem = (IOptimizationProblem) solver;
76 if (!optproblem.hasNoObjectiveFunction()) {
77 log("objective function=" + optproblem.getObjectiveValue());
78 }
79 }
80 }
81
82 @Override
83 protected void solve(IProblem problem) throws TimeoutException {
84 boolean isSatisfiable = false;
85
86 IOptimizationProblem optproblem = (IOptimizationProblem) problem;
87
88 try {
89 while (optproblem.admitABetterSolution()) {
90 if (!isSatisfiable) {
91 if (optproblem.nonOptimalMeansSatisfiable()) {
92 setExitCode(ExitCode.SATISFIABLE);
93 if (optproblem.hasNoObjectiveFunction()) {
94 return;
95 }
96 log("SATISFIABLE");
97 }
98 isSatisfiable = true;
99 log("OPTIMIZING...");
100 }
101 log("Got one! Elapsed wall clock time (in seconds):"
102 + (System.currentTimeMillis() - getBeginTime())
103 / 1000.0);
104 getLogWriter().println(
105 CURRENT_OPTIMUM_VALUE_PREFIX
106 + optproblem.getObjectiveValue());
107 optproblem.discardCurrentSolution();
108 }
109 if (isSatisfiable) {
110 setExitCode(ExitCode.OPTIMUM_FOUND);
111 } else {
112 setExitCode(ExitCode.UNSATISFIABLE);
113 }
114 } catch (ContradictionException ex) {
115 assert isSatisfiable;
116 setExitCode(ExitCode.OPTIMUM_FOUND);
117 }
118 }
119
120 }