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 ExitCode exitCode = getExitCode();
68 out.println(ANSWER_PREFIX + exitCode);
69 if (exitCode == ExitCode.SATISFIABLE
70 || exitCode == ExitCode.OPTIMUM_FOUND) {
71 out.print(SOLUTION_PREFIX);
72 getReader().decode(solver.model(), out);
73 out.println();
74 IOptimizationProblem optproblem = (IOptimizationProblem) solver;
75 if (!optproblem.hasNoObjectiveFunction()) {
76 log("objective function=" + optproblem.calculateObjective());
77 }
78 }
79 }
80
81 @Override
82 protected void solve(IProblem problem) throws TimeoutException {
83 boolean isSatisfiable = false;
84
85 IOptimizationProblem optproblem = (IOptimizationProblem) problem;
86
87 try {
88 while (optproblem.admitABetterSolution()) {
89 if (!isSatisfiable) {
90 if (optproblem.nonOptimalMeansSatisfiable()) {
91 setExitCode(ExitCode.SATISFIABLE);
92 if (optproblem.hasNoObjectiveFunction()) {
93 return;
94 }
95 log("SATISFIABLE");
96 }
97 isSatisfiable = true;
98 log("OPTIMIZING...");
99 }
100 log("Got one! Elapsed wall clock time (in seconds):"
101 + (System.currentTimeMillis() - getBeginTime())
102 / 1000.0);
103 getLogWriter().println(
104 CURRENT_OPTIMUM_VALUE_PREFIX
105 + optproblem.calculateObjective());
106 optproblem.discard();
107 }
108 if (isSatisfiable) {
109 setExitCode(ExitCode.OPTIMUM_FOUND);
110 } else {
111 setExitCode(ExitCode.UNSATISFIABLE);
112 }
113 } catch (ContradictionException ex) {
114 assert isSatisfiable;
115 setExitCode(ExitCode.OPTIMUM_FOUND);
116 }
117 }
118
119 }