Files
ortools-clone/examples/tests/ConstraintSolverTest.java

429 lines
14 KiB
Java
Raw Normal View History

2021-04-02 10:08:51 +02:00
// Copyright 2010-2021 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.
2020-09-14 23:49:23 +02:00
package com.google.ortools;
2020-09-14 23:49:23 +02:00
import com.google.ortools.Loader;
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.LocalSearchFilterManager;
2020-09-23 12:10:52 +02:00
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;
2019-03-29 17:35:04 +01:00
import java.lang.ref.WeakReference;
2019-02-08 13:08:37 +01:00
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.logging.Logger;
2020-09-14 23:49:23 +02:00
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
/** Tests the Constraint solver java interface. */
2020-09-14 23:49:23 +02:00
public class ConstraintSolverTest {
2019-03-29 17:35:04 +01:00
private static void gc() {
Object obj = new Object();
WeakReference ref = new WeakReference<Object>(obj);
obj = null;
2020-09-23 12:10:52 +02:00
while (ref.get() != null) {
2019-03-29 17:35:04 +01:00
System.gc();
}
}
2020-09-14 23:49:23 +02:00
private static final Logger logger = Logger.getLogger(ConstraintSolverTest.class.getName());
2020-09-14 23:49:23 +02:00
@Test
public void testSolverCtor() throws Exception {
Loader.loadNativeLibraries();
logger.info("testSolverCtor...");
Solver solver = new Solver("TestSolver");
2020-09-23 12:10:52 +02:00
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");
}
2020-09-14 23:49:23 +02:00
@Test
public void testIntVar() throws Exception {
Loader.loadNativeLibraries();
logger.info("testIntVar...");
Solver solver = new Solver("Solver");
IntVar var = solver.makeIntVar(3, 11, "IntVar");
2020-09-23 12:10:52 +02:00
if (var.min() != 3) {
throw new AssertionError("IntVar Min wrong");
}
if (var.max() != 11) {
throw new AssertionError("IntVar Max wrong");
}
logger.info("testIntVar...DONE");
}
2020-09-14 23:49:23 +02:00
@Test
private static void testIntVarArray() throws Exception {
Loader.loadNativeLibraries();
logger.info("testIntVarArray...");
Solver solver = new Solver("Solver");
IntVar[] vars = solver.makeIntVarArray(7, 3, 5, "vars");
2020-09-23 12:10:52 +02:00
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");
}
2020-09-14 23:49:23 +02:00
private 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;
}
2020-09-14 23:49:23 +02:00
@Test
public void testSolver() throws Exception {
Loader.loadNativeLibraries();
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);
2020-09-23 12:10:52 +02:00
LocalSearchPhaseParameters lsParams =
solver.makeLocalSearchPhaseParameters(sumVar, 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));
}
2020-09-14 23:49:23 +02:00
private 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
2019-08-06 15:57:08 -07:00
public boolean accept(Assignment delta, Assignment unusedDeltadelta, long unusedObjectiveMin,
2020-09-23 12:10:52 +02:00
long unusedObjectiveMax) {
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;
}
2020-09-14 23:49:23 +02:00
@Test
public void testSolverWithFilter() throws Exception {
Loader.loadNativeLibraries();
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;
LocalSearchFilterManager filter_manager = new LocalSearchFilterManager(filters);
LocalSearchPhaseParameters lsParams =
solver.makeLocalSearchPhaseParameters(sumVar, moveOneVar, db, null, filter_manager);
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));
}
2020-09-14 23:49:23 +02:00
private 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_;
}
2020-09-14 23:49:23 +02:00
@Test
public void testSolverLns() throws Exception {
Loader.loadNativeLibraries();
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);
2019-08-06 15:57:08 -07:00
LocalSearchPhaseParameters lsParams =
2020-09-23 12:10:52 +02:00
solver.makeLocalSearchPhaseParameters(sumVar, 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...
2020-09-14 23:49:23 +02:00
@Test
public void testSearchLog() throws Exception {
Loader.loadNativeLibraries();
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");
}
2020-09-14 23:49:23 +02:00
private static class SearchCount implements Supplier<String> {
2019-02-08 13:08:37 +01:00
public SearchCount(AtomicInteger count_) {
count = count_;
}
@Override
2019-02-08 13:08:37 +01:00
public String get() {
count.addAndGet(1);
return "display callback called...";
}
2019-02-08 13:08:37 +01:00
private AtomicInteger count;
}
2020-09-14 23:49:23 +02:00
@ParameterizedTest
2020-09-23 12:10:52 +02:00
@ValueSource(booleans = {false, true})
2020-09-14 23:49:23 +02:00
public void testSearchLogWithCallback(boolean enableGC) throws Exception {
Loader.loadNativeLibraries();
logger.info("testSearchLogWithCallback (enable gc:" + enableGC + ")...");
Solver solver = new Solver("TestSearchLog");
IntVar var = solver.makeIntVar(1, 1, "Variable");
OptimizeVar objective = solver.makeMinimize(var, 1);
2019-02-08 13:08:37 +01:00
AtomicInteger count = new AtomicInteger(0);
2020-09-23 12:10:52 +02:00
SearchMonitor searchlog = solver.makeSearchLog(0, // branch period
new SearchCount(count));
if (enableGC) {
2019-03-29 17:35:04 +01:00
gc();
}
runSearchLog(searchlog);
2019-02-08 13:08:37 +01:00
logger.info("count:" + count.intValue());
2020-09-23 12:10:52 +02:00
if (count.intValue() != 1)
throw new AssertionError("count != 1");
;
logger.info("testSearchLogWithCallback (enable gc:" + enableGC + ")...DONE");
}
2020-09-14 23:49:23 +02:00
@ParameterizedTest
2020-09-23 12:10:52 +02:00
@ValueSource(booleans = {false, true})
2020-09-14 23:49:23 +02:00
public void testSearchLogWithIntVarCallback(boolean enableGC) throws Exception {
Loader.loadNativeLibraries();
2019-02-08 13:08:37 +01:00
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);
2020-09-23 12:10:52 +02:00
SearchMonitor searchlog = solver.makeSearchLog(0, // branch period
2019-02-08 13:08:37 +01:00
var, // IntVar to monitor
new SearchCount(count));
if (enableGC) {
2019-03-29 17:35:04 +01:00
gc();
2019-02-08 13:08:37 +01:00
}
runSearchLog(searchlog);
2020-09-23 12:10:52 +02:00
if (count.intValue() != 1)
throw new AssertionError("count != 1");
;
2019-02-08 13:08:37 +01:00
logger.info("testSearchLogWithIntVarCallback (enable gc:" + enableGC + ")...DONE");
}
2020-09-14 23:49:23 +02:00
@ParameterizedTest
2020-09-23 12:10:52 +02:00
@ValueSource(booleans = {false, true})
2020-09-14 23:49:23 +02:00
public void testSearchLogWithObjectiveCallback(boolean enableGC) throws Exception {
Loader.loadNativeLibraries();
2019-02-08 13:08:37 +01:00
logger.info("testSearchLogWithObjectiveCallback (enable gc:" + enableGC + ")...");
Solver solver = new Solver("TestSearchLog");
IntVar var = solver.makeIntVar(1, 1, "Variable");
OptimizeVar objective = solver.makeMinimize(var, 1);
2019-02-08 13:08:37 +01:00
AtomicInteger count = new AtomicInteger(0);
2020-09-23 12:10:52 +02:00
SearchMonitor searchlog = solver.makeSearchLog(0, // branch period
objective, // objective var to monitor
new SearchCount(count));
if (enableGC) {
2019-03-29 17:35:04 +01:00
gc();
}
runSearchLog(searchlog);
2020-09-23 12:10:52 +02:00
if (count.intValue() != 1)
throw new AssertionError("count != 1");
;
2019-02-08 13:08:37 +01:00
logger.info("testSearchLogWithObjectiveCallback (enable gc:" + enableGC + ")...DONE");
}
2020-09-14 23:49:23 +02:00
private static class StringProperty {
2019-02-08 13:08:37 +01:00
public StringProperty(String value) {
value_ = value;
}
public void setValue(String value) {
2020-09-23 12:10:52 +02:00
value_ = value;
;
2019-02-08 13:08:37 +01:00
}
public String toString() {
return value_;
}
private String value_;
}
2020-09-14 23:49:23 +02:00
@ParameterizedTest
2020-09-23 12:10:52 +02:00
@ValueSource(booleans = {false, true})
2020-09-14 23:49:23 +02:00
public void testClosureDecision(boolean enableGC) throws Exception {
Loader.loadNativeLibraries();
2019-02-08 13:08:37 +01:00
logger.info("testClosureDecision (enable gc:" + enableGC + ")...");
final StringProperty call = new StringProperty("");
Solver solver = new Solver("ClosureDecisionTest");
Decision decision = solver.makeDecision(
2020-09-23 12:10:52 +02:00
(Solver s) -> { call.setValue("Apply"); }, (Solver s) -> { call.setValue("Refute"); });
2019-02-08 13:08:37 +01:00
if (enableGC) {
2019-03-29 17:35:04 +01:00
gc();
2019-02-08 13:08:37 +01:00
}
decision.apply(solver);
2020-09-23 12:10:52 +02:00
if (!call.toString().equals("Apply")) {
throw new AssertionError("Apply action not called");
}
2019-02-08 13:08:37 +01:00
decision.refute(solver);
2020-09-23 12:10:52 +02:00
if (!call.toString().equals("Refute")) {
throw new AssertionError("Refute action not called");
}
2019-02-08 13:08:37 +01:00
logger.info("testClosureDecision (enable gc:" + enableGC + ")...DONE");
}
2020-09-14 23:49:23 +02:00
@ParameterizedTest
2020-09-23 12:10:52 +02:00
@ValueSource(booleans = {false, true})
2020-09-14 23:49:23 +02:00
public void testSolverInClosureDecision(boolean enableGC) throws Exception {
Loader.loadNativeLibraries();
2019-02-08 13:08:37 +01:00
logger.info("testSolverInClosureDecision (enable gc:" + enableGC + ")...");
Solver solver = new Solver("SolverTestName");
String model_name = solver.model_name();
Decision decision = solver.makeDecision(
2020-09-23 12:10:52 +02:00
(Solver s)
-> {
if (!s.model_name().equals(model_name)) {
throw new AssertionError("Solver ill formed");
}
2019-02-08 13:08:37 +01:00
},
(Solver s) -> {
2020-09-23 12:10:52 +02:00
if (!s.model_name().equals(model_name)) {
throw new AssertionError("Solver ill formed");
}
2019-02-08 13:08:37 +01:00
});
if (enableGC) {
2019-03-29 17:35:04 +01:00
gc(); // verify SearchCount is kept alive
2019-02-08 13:08:37 +01:00
}
decision.apply(solver);
decision.refute(solver);
logger.info("testSolverInClosureDecision (enable gc:" + enableGC + ")...DONE");
}
}