add tests for model builder

This commit is contained in:
Laurent Perron
2022-04-04 15:08:29 +02:00
parent 3ee27d3354
commit fb6e4c8eeb
8 changed files with 208 additions and 45 deletions

View File

@@ -519,10 +519,8 @@ public final class CpModelTest {
final IntVar y = model.newIntVar(0, 10, "y");
List<Constraint> constraints = new ArrayList<>();
for (int i = 0; i < 10; ++i) {
Constraint ct =
model.addLinearExpressionInDomain(
LinearExpr.newBuilder().add(x).add(y),
Domain.fromFlatIntervals(new long[] {6 + i, 92 - i}));
Constraint ct = model.addLinearExpressionInDomain(LinearExpr.newBuilder().add(x).add(y),
Domain.fromFlatIntervals(new long[] {6 + i, 92 - i}));
constraints.add(ct);
}
@@ -548,4 +546,49 @@ public final class CpModelTest {
}
}
@Test
public void testCpModel_minimize() throws Exception {
final CpModel model = new CpModel();
assertNotNull(model);
final IntVar x1 = model.newIntVar(0, 5, "x1");
final IntVar x2 = model.newIntVar(0, 5, "x2");
final IntVar x3 = model.newIntVar(0, 5, "x3");
model.minimize(LinearExpr.sum(new IntVar[] {x1, x2}));
assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(2);
assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse();
model.minimize(x3);
assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(1);
assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse();
model.minimize(LinearExpr.sum(new IntVar[] {x1, x2}));
assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(2);
assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse();
model.minimize(DoubleLinearExpr.weightedSum(new IntVar[] {x1, x2}, new double[] {2.5, 3.5}));
assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(2);
assertThat(model.getBuilder().hasObjective()).isFalse();
model.minimize(DoubleLinearExpr.affine(x3, 1.4, 1.2));
assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(1);
assertThat(model.getBuilder().hasObjective()).isFalse();
model.maximize(LinearExpr.sum(new IntVar[] {x1, x2}));
assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(2);
assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse();
model.maximize(x3);
assertThat(model.getBuilder().getObjectiveBuilder().getVarsCount()).isEqualTo(1);
assertThat(model.getBuilder().hasFloatingPointObjective()).isFalse();
model.maximize(DoubleLinearExpr.weightedSum(new IntVar[] {x1, x2}, new double[] {2.5, 3.5}));
assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(2);
assertThat(model.getBuilder().hasObjective()).isFalse();
model.maximize(DoubleLinearExpr.affine(x3, 1.4, 1.2));
assertThat(model.getBuilder().getFloatingPointObjectiveBuilder().getVarsCount()).isEqualTo(1);
assertThat(model.getBuilder().hasObjective()).isFalse();
}
}

View File

@@ -20,10 +20,12 @@ import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.ortools.Loader;
import com.google.ortools.linearsolver.MPConstraint;
import com.google.ortools.linearsolver.MPObjective;
import com.google.ortools.linearsolver.MPSolver;
import com.google.ortools.linearsolver.MPVariable;
import com.google.ortools.linearsolver.MPModelProto;
import com.google.ortools.linearsolver.MPModelRequest;
import com.google.ortools.linearsolver.MPSolutionResponse;
import com.google.ortools.linearsolver.MPSolverResponseStatus;
import com.google.ortools.linearsolver.MPVariableProto;
import com.google.ortools.linearsolver.PartialVariableAssignment;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

View File

@@ -0,0 +1,88 @@
// 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.
package com.google.ortools.modelbuilder;
import static com.google.common.truth.Truth.assertThat;
import com.google.ortools.Loader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public final class ModelBuilderTest {
@BeforeEach
public void setUp() {
Loader.loadNativeLibraries();
}
@Test
public void runMinimalLinearExample_ok() {
ModelBuilder model = new ModelBuilder();
model.setName("minimal_linear_example");
double infinity = java.lang.Double.POSITIVE_INFINITY;
Variable x1 = model.newNumVar(0.0, infinity, "x1");
Variable x2 = model.newNumVar(0.0, infinity, "x2");
Variable x3 = model.newNumVar(0.0, infinity, "x3");
assertThat(model.numVariables()).isEqualTo(3);
assertThat(x1.getIntegrality()).isFalse();
assertThat(x1.getLowerBound()).isEqualTo(0.0);
assertThat(x2.getUpperBound()).isEqualTo(infinity);
x1.setLowerBound(1.0);
assertThat(x1.getLowerBound()).isEqualTo(1.0);
LinearConstraint c0 = model.addLessOrEqual(LinearExpr.sum(new Variable[] {x1, x2, x3}), 100.0);
assertThat(c0.getUpperBound()).isEqualTo(100.0);
LinearConstraint c1 =
model
.addLessOrEqual(
LinearExpr.newBuilder().addTerm(x1, 10.0).addTerm(x2, 4.0).addTerm(x3, 5.0), 600.0)
.withName("c1");
assertThat(c1.getName()).isEqualTo("c1");
LinearConstraint c2 = model.addLessOrEqual(
LinearExpr.newBuilder().addTerm(x1, 2.0).addTerm(x2, 2.0).addTerm(x3, 6.0), 300.0);
assertThat(c2.getUpperBound()).isEqualTo(300.0);
model.maximize(
LinearExpr.weightedSum(new Variable[] {x1, x2, x3}, new double[] {10.0, 6, 4.0}));
assertThat(x3.getObjectiveCoefficient()).isEqualTo(4.0);
assertThat(model.getObjectiveOffset()).isEqualTo(0.0);
model.setObjectiveOffset(-5.5);
assertThat(model.getObjectiveOffset()).isEqualTo(-5.5);
ModelSolver solver = new ModelSolver("glop");
assertThat(solver.solverIsSupported()).isTrue();
assertThat(solver.solve(model)).isEqualTo(SolveStatus.OPTIMAL);
assertThat(solver.getObjectiveValue())
.isWithin(1e-5)
.of(733.333333 + model.getObjectiveOffset());
assertThat(solver.getValue(x1)).isWithin(1e-5).of(33.333333);
assertThat(solver.getValue(x2)).isWithin(1e-5).of(66.6666673);
assertThat(solver.getValue(x3)).isWithin(1e-5).of(0.0);
double dualObjectiveValue = solver.getDualValue(c0) * c0.getUpperBound()
+ solver.getDualValue(c1) * c1.getUpperBound()
+ solver.getDualValue(c2) * c2.getUpperBound() + model.getObjectiveOffset();
assertThat(solver.getObjectiveValue()).isWithin(1e-5).of(dualObjectiveValue);
assertThat(solver.getReducedCost(x1)).isWithin(1e-5).of(0.0);
assertThat(solver.getReducedCost(x2)).isWithin(1e-5).of(0.0);
assertThat(solver.getReducedCost(x3))
.isWithin(1e-5)
.of(4.0 - 1.0 * solver.getDualValue(c0) - 5.0 * solver.getDualValue(c1));
assertThat(model.exportToLpString(false)).contains("minimal_linear_example");
assertThat(model.exportToMpsString(false)).contains("minimal_linear_example");
}
}

View File

@@ -20,10 +20,6 @@ import static org.junit.jupiter.api.Assertions.assertTrue;
import com.google.auto.value.AutoValue;
import com.google.ortools.Loader;
import com.google.ortools.constraintsolver.Assignment;
import com.google.ortools.constraintsolver.FirstSolutionStrategy;
import com.google.ortools.constraintsolver.RoutingIndexManager;
import com.google.ortools.constraintsolver.RoutingModel;
import com.google.ortools.constraintsolver.RoutingModelParameters;
import com.google.ortools.constraintsolver.RoutingSearchParameters;
import com.google.protobuf.Duration;
@@ -360,9 +356,8 @@ public final class RoutingSolverTest {
dimension.setSpanCostCoefficientForAllVehicles(2);
RoutingSearchParameters searchParameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(main.defaultRoutingSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
main.defaultRoutingSearchParameters()
.toBuilder()
.setTimeLimit(Duration.newBuilder().setSeconds(10))
.build();
@@ -388,9 +383,8 @@ public final class RoutingSolverTest {
model.setArcCostEvaluatorOfAllVehicles(pair.getFirst());
RoutingSearchParameters searchParameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(main.defaultRoutingSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
main.defaultRoutingSearchParameters()
.toBuilder()
.setTimeLimit(Duration.newBuilder().setSeconds(10))
.build();
@@ -422,9 +416,8 @@ public final class RoutingSolverTest {
model.setArcCostEvaluatorOfAllVehicles(pair.getFirst());
final RoutingSearchParameters searchParameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(main.defaultRoutingSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
main.defaultRoutingSearchParameters()
.toBuilder()
.setTimeLimit(Duration.newBuilder().setSeconds(10))
.build();
@@ -470,9 +463,8 @@ public final class RoutingSolverTest {
}
RoutingSearchParameters searchParameters =
RoutingSearchParameters.newBuilder()
.mergeFrom(main.defaultRoutingSearchParameters())
.setFirstSolutionStrategy(FirstSolutionStrategy.Value.PATH_CHEAPEST_ARC)
main.defaultRoutingSearchParameters()
.toBuilder()
.setTimeLimit(Duration.newBuilder().setSeconds(10))
.build();

View File

@@ -20,8 +20,6 @@ namespace Google.OrTools.Tests
{
public class SatSolverTest
{
private const int LargeCount = 100000;
static IntegerVariableProto NewIntegerVariable(long lb, long ub)
{
IntegerVariableProto var = new IntegerVariableProto();
@@ -296,11 +294,10 @@ public class SatSolverTest
public void LargeWeightedSumLong()
{
CpModel model = new CpModel();
model.Model.Variables.Capacity = LargeCount;
List<IntVar> vars = new List<IntVar>(LargeCount);
List<long> coeffs = new List<long>(LargeCount);
List<IntVar> vars = new List<IntVar>();
List<long> coeffs = new List<long>();
for (int i = 0; i < LargeCount; ++i)
for (int i = 0; i < 100000; ++i)
{
vars.Add(model.NewBoolVar(""));
coeffs.Add(i + 1);
@@ -317,11 +314,10 @@ public class SatSolverTest
public void LargeWeightedSumInt()
{
CpModel model = new CpModel();
model.Model.Variables.Capacity = LargeCount;
List<IntVar> vars = new List<IntVar>(LargeCount);
List<int> coeffs = new List<int>(LargeCount);
List<IntVar> vars = new List<IntVar>();
List<int> coeffs = new List<int>();
for (int i = 0; i < LargeCount; ++i)
for (int i = 0; i < 100000; ++i)
{
vars.Add(model.NewBoolVar(""));
coeffs.Add(i);
@@ -338,10 +334,9 @@ public class SatSolverTest
public void LargeWeightedSumExpr()
{
CpModel model = new CpModel();
model.Model.Variables.Capacity = LargeCount;
List<LinearExpr> exprs = new List<LinearExpr>(LargeCount);
List<LinearExpr> exprs = new List<LinearExpr>();
for (int i = 0; i < LargeCount; ++i)
for (int i = 0; i < 100000; ++i)
{
exprs.Add(model.NewBoolVar("") * i);
}
@@ -357,11 +352,10 @@ public class SatSolverTest
public void LargeWeightedSumBuilder()
{
CpModel model = new CpModel();
model.Model.Variables.Capacity = LargeCount;
List<IntVar> vars = new List<IntVar>(LargeCount);
List<long> coeffs = new List<long>(LargeCount);
List<IntVar> vars = new List<IntVar>();
List<long> coeffs = new List<long>();
for (int i = 0; i < LargeCount; ++i)
for (int i = 0; i < 100000; ++i)
{
vars.Add(model.NewBoolVar(""));
coeffs.Add(i + 1);
@@ -369,7 +363,7 @@ public class SatSolverTest
var watch = System.Diagnostics.Stopwatch.StartNew();
LinearExprBuilder obj = LinearExpr.NewBuilder();
for (int i = 0; i < LargeCount; ++i)
for (int i = 0; i < 100000; ++i)
{
obj.AddTerm(vars[i], coeffs[i]);
}

View File

@@ -53,7 +53,7 @@ class ModelBuilderTest(unittest.TestCase):
self.assertEqual(-math.inf, c2.lower_bound)
solver = model_builder.ModelSolver(solver_name)
self.assertEqual(model_builder.OPTIMAL, solver.solve(model))
self.assertEqual(model_builder.SolveStatus.OPTIMAL, solver.solve(model))
# The problem has an optimal solution.
self.assertAlmostEqual(733.333333 + model.objective_offset,
@@ -122,6 +122,13 @@ ENDATA
self.assertTrue(model.import_from_mps_string(mps_data))
self.assertEqual(model.name, 'SupportedMaximizationProblem')
def test_import_from_mps_file(self):
mps_path = resources.GetResourceFilename('ortools.linear_solver/'
'testdata/maximization.mps')
model = model_builder.ModelBuilder()
self.assertTrue(model.import_from_mps_file(mps_path))
self.assertEqual(model.name, 'SupportedMaximizationProblem')
def test_import_from_lp_string(self):
lp_data = """
min: x + y;
@@ -139,6 +146,43 @@ ENDATA
self.assertEqual(42, model.var_from_index(0).upper_bound)
self.assertEqual('x', model.var_from_index(0).name)
def test_import_from_lp_file(self):
lp_path = resources.GetResourceFilename('testdata/small_model.lp')
model = model_builder.ModelBuilder()
self.assertTrue(model.import_from_lp_file(lp_path))
self.assertEqual(6, model.num_variables)
self.assertEqual(3, model.num_constraints)
self.assertEqual(1, model.var_from_index(0).lower_bound)
self.assertEqual(42, model.var_from_index(0).upper_bound)
self.assertEqual('x', model.var_from_index(0).name)
def test_variables(self):
model = model_builder.ModelBuilder()
x = model.new_int_var(0.0, 4.0, 'x')
self.assertEqual(0, x.index)
self.assertEqual(0.0, x.lower_bound)
self.assertEqual(4.0, x.upper_bound)
self.assertEqual('x', x.name)
x.lower_bound = 1.0
x.upper_bound = 3.0
self.assertEqual(1.0, x.lower_bound)
self.assertEqual(3.0, x.upper_bound)
self.assertTrue(x.is_integral)
# Tests the equality operator.
y = model.new_int_var(0.0, 4.0, 'y')
x_copy = model.var_from_index(0)
self.assertEqual(x, x)
self.assertEqual(x, x_copy)
self.assertNotEqual(x, y)
# Tests the hash method.
var_set = set()
var_set.add(x)
self.assertIn(x, var_set)
self.assertIn(x_copy, var_set)
self.assertNotIn(y, var_set)
if __name__ == '__main__':
unittest.main()

View File

@@ -11,7 +11,7 @@
# 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.
"""Tests for ortools.util.sorted_interval_list."""
"""Tests for ortools.util.python.sorted_interval_list."""
import unittest

View File

@@ -312,7 +312,6 @@ check_java: \
test_java_linear_solver_samples \
test_java_model_builder_samples \
test_java_sat_samples \
\
rjava_LinearProgramming \
rjava_IntegerProgramming
@@ -327,6 +326,7 @@ test_java_tests: \
rjava_CpModelTest \
rjava_CpSolverTest \
rjava_SatSolverTest \
rjava_ModelBuilderTest
.PHONY: test_java_contrib # Build and Run all Java Contrib (located in examples/contrib)
test_java_contrib: \