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