forked from google/or-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TestConstraintSolver.java
390 lines (350 loc) · 13.8 KB
/
TestConstraintSolver.java
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// Copyright 2010-2018 Google LLC
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import com.google.ortools.constraintsolver.Assignment;
import com.google.ortools.constraintsolver.AssignmentIntContainer;
import com.google.ortools.constraintsolver.BaseLns;
import com.google.ortools.constraintsolver.Decision;
import com.google.ortools.constraintsolver.DecisionBuilder;
import com.google.ortools.constraintsolver.IntVar;
import com.google.ortools.constraintsolver.IntVarLocalSearchFilter;
import com.google.ortools.constraintsolver.IntVarLocalSearchOperator;
import com.google.ortools.constraintsolver.LocalSearchPhaseParameters;
import com.google.ortools.constraintsolver.OptimizeVar;
import com.google.ortools.constraintsolver.SearchLog;
import com.google.ortools.constraintsolver.SearchMonitor;
import com.google.ortools.constraintsolver.SolutionCollector;
import com.google.ortools.constraintsolver.Solver;
import com.google.ortools.constraintsolver.main;
import java.lang.ref.WeakReference;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Logger;
/** Tests the Constraint solver java interface. */
public class TestConstraintSolver {
static {
System.loadLibrary("jniortools");
}
private static void gc() {
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
obj = null;
while(ref.get() != null) {
System.gc();
}
}
private static final Logger logger = Logger.getLogger(TestConstraintSolver.class.getName());
static void testSolverCtor() throws Exception {
logger.info("testSolverCtor...");
Solver solver = new Solver("TestSolver");
if (!solver.model_name().equals("TestSolver")) {throw new AssertionError("Solver ill formed");}
if (solver.toString().length() < 0) {throw new AssertionError("Solver ill formed");}
logger.info("testSolverCtor...DONE");
}
static void testIntVar() throws Exception {
logger.info("testIntVar...");
Solver solver = new Solver("Solver");
IntVar var = solver.makeIntVar(3, 11, "IntVar");
if (var.min() != 3) {throw new AssertionError("IntVar Min wrong");}
if (var.max() != 11) {throw new AssertionError("IntVar Max wrong");}
logger.info("testIntVar...DONE");
}
static void testIntVarArray() throws Exception {
logger.info("testIntVarArray...");
Solver solver = new Solver("Solver");
IntVar[] vars = solver.makeIntVarArray(7, 3, 5, "vars");
if (vars.length != 7) {throw new AssertionError("Vars length wrong");}
for(IntVar var: vars) {
if (var.min() != 3) {throw new AssertionError("IntVar Min wrong");}
if (var.max() != 5) {throw new AssertionError("IntVar Max wrong");}
}
logger.info("testIntVarArray...DONE");
}
static class MoveOneVar extends IntVarLocalSearchOperator {
public MoveOneVar(IntVar[] variables) {
super(variables);
variableIndex = 0;
moveUp = false;
}
@Override
protected boolean oneNeighbor() {
long currentValue = oldValue(variableIndex);
if (moveUp) {
setValue(variableIndex, currentValue + 1);
variableIndex = (variableIndex + 1) % size();
} else {
setValue(variableIndex, currentValue - 1);
}
moveUp = !moveUp;
return true;
}
@Override
public void onStart() {}
// Index of the next variable to try to restore
private long variableIndex;
// Direction of the modification.
private boolean moveUp;
}
static void testSolver() throws Exception {
Solver solver = new Solver("Solver");
IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars");
IntVar sumVar = solver.makeSum(vars).var();
OptimizeVar obj = solver.makeMinimize(sumVar, 1);
DecisionBuilder db =
solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE);
MoveOneVar moveOneVar = new MoveOneVar(vars);
LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(moveOneVar, db);
DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams);
SolutionCollector collector = solver.makeLastSolutionCollector();
collector.addObjective(sumVar);
SearchMonitor log = solver.makeSearchLog(1000, obj);
solver.solve(ls, collector, obj, log);
logger.info("Objective value = " + collector.objectiveValue(0));
}
static class SumFilter extends IntVarLocalSearchFilter {
public SumFilter(IntVar[] vars) {
super(vars);
sum = 0;
}
@Override
protected void onSynchronize(Assignment unusedDelta) {
sum = 0;
for (int index = 0; index < size(); ++index) {
sum += value(index);
}
}
@Override
public boolean accept(Assignment delta, Assignment unusedDeltadelta) {
AssignmentIntContainer solutionDelta = delta.intVarContainer();
int solutionDeltaSize = solutionDelta.size();
for (int i = 0; i < solutionDeltaSize; ++i) {
if (!solutionDelta.element(i).activated()) {
return true;
}
}
long newSum = sum;
for (int index = 0; index < solutionDeltaSize; ++index) {
int touchedVar = index(solutionDelta.element(index).var());
long oldValue = value(touchedVar);
long newValue = solutionDelta.element(index).value();
newSum += newValue - oldValue;
}
return newSum < sum;
}
private long sum;
}
static void testSolverWithFilter() throws Exception {
Solver solver = new Solver("Solver");
IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars");
IntVar sumVar = solver.makeSum(vars).var();
OptimizeVar obj = solver.makeMinimize(sumVar, 1);
DecisionBuilder db =
solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE);
MoveOneVar moveOneVar = new MoveOneVar(vars);
SumFilter filter = new SumFilter(vars);
IntVarLocalSearchFilter[] filters = new IntVarLocalSearchFilter[1];
filters[0] = filter;
LocalSearchPhaseParameters lsParams =
solver.makeLocalSearchPhaseParameters(moveOneVar, db, null, filters);
DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams);
SolutionCollector collector = solver.makeLastSolutionCollector();
collector.addObjective(sumVar);
SearchMonitor log = solver.makeSearchLog(1000, obj);
solver.solve(ls, collector, obj, log);
logger.info("Objective value = " + collector.objectiveValue(0));
}
static class OneVarLns extends BaseLns {
public OneVarLns(IntVar[] vars) {
super(vars);
}
@Override
public void initFragments() {
index_ = 0;
}
@Override
public boolean nextFragment() {
int size = size();
if (index_ < size) {
appendToFragment(index_);
++index_;
return true;
} else {
return false;
}
}
private int index_;
}
static void testSolverLns() throws Exception {
Solver solver = new Solver("Solver");
IntVar[] vars = solver.makeIntVarArray(4, 0, 4, "vars");
IntVar sumVar = solver.makeSum(vars).var();
OptimizeVar obj = solver.makeMinimize(sumVar, 1);
DecisionBuilder db =
solver.makePhase(vars, Solver.CHOOSE_FIRST_UNBOUND, Solver.ASSIGN_MAX_VALUE);
OneVarLns oneVarLns = new OneVarLns(vars);
LocalSearchPhaseParameters lsParams = solver.makeLocalSearchPhaseParameters(oneVarLns, db);
DecisionBuilder ls = solver.makeLocalSearchPhase(vars, db, lsParams);
SolutionCollector collector = solver.makeLastSolutionCollector();
collector.addObjective(sumVar);
SearchMonitor log = solver.makeSearchLog(1000, obj);
solver.solve(ls, collector, obj, log);
logger.info("Objective value = " + collector.objectiveValue(0));
}
private static void runSearchLog(SearchMonitor searchlog) {
searchlog.enterSearch();
searchlog.exitSearch();
searchlog.acceptSolution();
searchlog.atSolution();
searchlog.beginFail();
searchlog.noMoreSolutions();
searchlog.beginInitialPropagation();
searchlog.endInitialPropagation();
}
// Simple Coverage test...
static void testSearchLog() throws Exception {
logger.info("testSearchLog...");
Solver solver = new Solver("TestSearchLog");
IntVar var = solver.makeIntVar(1, 1, "Variable");
OptimizeVar objective = solver.makeMinimize(var, 1);
SearchMonitor searchlog = solver.makeSearchLog(0);
runSearchLog(searchlog);
logger.info("testSearchLog...DONE");
}
static class SearchCount implements Supplier<String> {
public SearchCount(AtomicInteger count_) {
count = count_;
}
@Override
public String get() {
count.addAndGet(1);
return "display callback called...";
}
private AtomicInteger count;
}
static void testSearchLogWithCallback(boolean enableGC) throws Exception {
logger.info("testSearchLogWithCallback (enable gc:" + enableGC + ")...");
Solver solver = new Solver("TestSearchLog");
IntVar var = solver.makeIntVar(1, 1, "Variable");
OptimizeVar objective = solver.makeMinimize(var, 1);
AtomicInteger count = new AtomicInteger(0);
SearchMonitor searchlog = solver.makeSearchLog(
0, // branch period
new SearchCount(count));
if (enableGC) {
gc();
}
runSearchLog(searchlog);
logger.info("count:" + count.intValue());
if (count.intValue() != 1) throw new AssertionError("count != 1"); ;
logger.info("testSearchLogWithCallback (enable gc:" + enableGC + ")...DONE");
}
static void testSearchLogWithIntVarCallback(boolean enableGC) throws Exception {
logger.info("testSearchLogWithIntVarCallback (enable gc:" + enableGC + ")...");
Solver solver = new Solver("TestSearchLog");
IntVar var = solver.makeIntVar(1, 1, "Variable");
OptimizeVar objective = solver.makeMinimize(var, 1);
AtomicInteger count = new AtomicInteger(0);
SearchMonitor searchlog = solver.makeSearchLog(
0, // branch period
var, // IntVar to monitor
new SearchCount(count));
if (enableGC) {
gc();
}
runSearchLog(searchlog);
if (count.intValue() != 1) throw new AssertionError("count != 1"); ;
logger.info("testSearchLogWithIntVarCallback (enable gc:" + enableGC + ")...DONE");
}
static void testSearchLogWithObjectiveCallback(boolean enableGC) throws Exception {
logger.info("testSearchLogWithObjectiveCallback (enable gc:" + enableGC + ")...");
Solver solver = new Solver("TestSearchLog");
IntVar var = solver.makeIntVar(1, 1, "Variable");
OptimizeVar objective = solver.makeMinimize(var, 1);
AtomicInteger count = new AtomicInteger(0);
SearchMonitor searchlog = solver.makeSearchLog(
0, // branch period
objective, // objective var to monitor
new SearchCount(count));
if (enableGC) {
gc();
}
runSearchLog(searchlog);
if (count.intValue() != 1) throw new AssertionError("count != 1"); ;
logger.info("testSearchLogWithObjectiveCallback (enable gc:" + enableGC + ")...DONE");
}
static class StringProperty {
public StringProperty(String value) {
value_ = value;
}
public void setValue(String value) {
value_ = value;;
}
public String toString() {
return value_;
}
private String value_;
}
static void testClosureDecision(boolean enableGC) throws Exception {
logger.info("testClosureDecision (enable gc:" + enableGC + ")...");
final StringProperty call = new StringProperty("");
Solver solver = new Solver("ClosureDecisionTest");
Decision decision = solver.makeDecision(
(Solver s) -> { call.setValue("Apply"); },
(Solver s) -> { call.setValue("Refute"); });
if (enableGC) {
gc();
}
decision.apply(solver);
if (!call.toString().equals("Apply")) {throw new AssertionError("Apply action not called");}
decision.refute(solver);
if (!call.toString().equals("Refute")) {throw new AssertionError("Refute action not called");}
logger.info("testClosureDecision (enable gc:" + enableGC + ")...DONE");
}
static void testSolverInClosureDecision(boolean enableGC) throws Exception {
logger.info("testSolverInClosureDecision (enable gc:" + enableGC + ")...");
Solver solver = new Solver("SolverTestName");
String model_name = solver.model_name();
Decision decision = solver.makeDecision(
(Solver s) -> {
if (!s.model_name().equals(model_name)) {throw new AssertionError("Solver ill formed");}
},
(Solver s) -> {
if (!s.model_name().equals(model_name)) {throw new AssertionError("Solver ill formed");}
});
if (enableGC) {
gc(); // verify SearchCount is kept alive
}
decision.apply(solver);
decision.refute(solver);
logger.info("testSolverInClosureDecision (enable gc:" + enableGC + ")...DONE");
}
public static void main(String[] args) throws Exception {
testSolverCtor();
testIntVar();
testIntVarArray();
testSolver();
testSolverWithFilter();
testSolverLns();
testSearchLog();
testSearchLogWithCallback(/*enableGC=*/false);
testSearchLogWithCallback(/*enableGC=*/true);
testSearchLogWithIntVarCallback(/*enableGC=*/false);
testSearchLogWithIntVarCallback(/*enableGC=*/true);
testSearchLogWithObjectiveCallback(/*enableGC=*/false);
testSearchLogWithObjectiveCallback(/*enableGC=*/true);
testClosureDecision(/*enableGC=*/false);
testClosureDecision(/*enableGC=*/true);
testSolverInClosureDecision(/*enableGC=*/false);
testSolverInClosureDecision(/*enableGC=*/true);
}
}