math_opt: format python files

This commit is contained in:
Corentin Le Molgat
2024-04-12 11:36:36 +02:00
parent be220948a3
commit 03a06c9e97
26 changed files with 70 additions and 0 deletions

View File

@@ -27,6 +27,7 @@ class CppExampleTest(
log_scraping.LogScraping,
absltest.TestCase,
):
def test_regression(self):
result = self.assert_binary_succeeds("ortools/math_opt/core/c_api/cpp_example")
is_optimal = self.assert_has_line_with_prefixed_number(

View File

@@ -96,6 +96,7 @@ def _expected_iis_success() -> (
class PybindComputeInfeasibleSubsystemTest(
compare_proto.MathOptProtoAssertions, absltest.TestCase
):
def test_compute_infeasible_subsystem_infeasible(self) -> None:
iis_result = solver.compute_infeasible_subsystem(
_simple_infeasible_model(),

View File

@@ -84,6 +84,7 @@ def _solve_model(
class PybindSolverTest(parameterized.TestCase):
def tearDown(self):
super().tearDown()
self.assertEqual(solver.debug_num_solver(), 0)
@@ -261,6 +262,7 @@ class PybindSolverTest(parameterized.TestCase):
class PybindSolveInterrupterTest(parameterized.TestCase):
def test_solve_interrupter_is_interrupted(self) -> None:
interrupter = solver.SolveInterrupter()
self.assertFalse(interrupter.is_interrupted())

View File

@@ -25,6 +25,7 @@ from ortools.math_opt.python.testing import compare_proto
class CallbackDataTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_parse_callback_data_no_solution(self) -> None:
mod = model.Model(name="test_model")
cb_data_proto = callback_pb2.CallbackDataProto(
@@ -86,6 +87,7 @@ class CallbackDataTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
class CallbackRegistrationTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def testToProto(self) -> None:
mod = model.Model(name="test_model")
x = mod.add_binary_variable(name="x")
@@ -123,6 +125,7 @@ class CallbackRegistrationTest(compare_proto.MathOptProtoAssertions, absltest.Te
class GeneratedLinearConstraintTest(
compare_proto.MathOptProtoAssertions, absltest.TestCase
):
def testToProto(self) -> None:
mod = model.Model(name="test_model")
x = mod.add_binary_variable(name="x")
@@ -148,6 +151,7 @@ class GeneratedLinearConstraintTest(
class CallbackResultTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def testToProto(self) -> None:
mod = model.Model(name="test_model")
x = mod.add_binary_variable(name="x")

View File

@@ -29,6 +29,7 @@ _ComputeInfeasibleSubsystemResult = (
class ModelSubsetBoundsTest(absltest.TestCase, compare_proto.MathOptProtoAssertions):
def test_empty(self) -> None:
self.assertTrue(_ModelSubsetBounds().empty())
self.assertFalse(_ModelSubsetBounds(lower=True).empty())
@@ -61,6 +62,7 @@ class ModelSubsetBoundsTest(absltest.TestCase, compare_proto.MathOptProtoAsserti
class ModelSubsetTest(absltest.TestCase, compare_proto.MathOptProtoAssertions):
def test_empty(self) -> None:
m = model.Model()
x = m.add_binary_variable()
@@ -168,6 +170,7 @@ class ModelSubsetTest(absltest.TestCase, compare_proto.MathOptProtoAssertions):
class ComputeInfeasibleSubsystemResultTest(absltest.TestCase):
def test_to_proto_round_trip(self) -> None:
m = model.Model()
x = m.add_binary_variable()

View File

@@ -23,6 +23,7 @@ def _type_check_linear_sum(x: model.LinearSum) -> None:
class FastSumTest(absltest.TestCase):
def test_variables(self) -> None:
mod = model.Model()
x = mod.add_binary_variable()
@@ -79,6 +80,7 @@ class FastSumTest(absltest.TestCase):
class EvaluateExpressionTest(absltest.TestCase):
def test_scalar_expression(self) -> None:
mod = model.Model()
x = mod.add_binary_variable()

View File

@@ -19,6 +19,7 @@ from ortools.math_opt.python import hash_model_storage
class HashModelStorageTest(absltest.TestCase):
def test_quadratic_term_storage(self):
storage = hash_model_storage._QuadraticTermStorage()
storage.set_coefficient(0, 1, 1.0)

View File

@@ -45,6 +45,7 @@ def _simple_request() -> rpc_pb2.SolveRequest:
class ProtoConverterTest(absltest.TestCase, compare.Proto2Assertions):
def test_convert_request(self):
request = _simple_request()
expected = optimization_pb2.SolveMathOptModelRequest(

View File

@@ -77,6 +77,7 @@ def _simple_model() -> tuple[mathopt.Model, mathopt.Variable, mathopt.Variable]:
class RemoteHttpSolveTest(absltest.TestCase):
def test_session_headers(self):
deadline = 1.0
server_deadline = deadline * (1 - remote_http_solve._RELATIVE_TIME_BUFFER)

View File

@@ -37,6 +37,7 @@ _QUADRATIC_TYPES = (
class BoundedExprTest(absltest.TestCase):
def test_eq_float(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -334,6 +335,7 @@ class BoundedExprTest(absltest.TestCase):
class BoundedExprErrorTest(absltest.TestCase):
def test_ne(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -589,6 +591,7 @@ class BoundedExprErrorTest(absltest.TestCase):
class BoundedExprStrAndReprTest(absltest.TestCase):
def test_upper_bounded_expr(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -628,6 +631,7 @@ class BoundedExprStrAndReprTest(absltest.TestCase):
# TODO(b/216492143): change __str__ to match C++ implementation in cl/421649402.
class LinearStrAndReprTest(parameterized.TestCase):
def test_sorting_ok(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -720,6 +724,7 @@ class LinearStrAndReprTest(parameterized.TestCase):
# TODO(b/216492143): change __str__ to match C++ implementation in cl/421649402.
class QuadraticStrAndReprTest(parameterized.TestCase):
def test_sorting_ok(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -858,6 +863,7 @@ def all_linear_number_op_parameters() -> List[LinearNumberOpTestsParameters]:
# Test all operations (including inplace) between a number and a Linear object
class LinearNumberOpTests(parameterized.TestCase):
@parameterized.named_parameters(
(p.test_suffix(), p.linear_type, p.constant, p.linear_first)
for p in all_linear_number_op_parameters()
@@ -1087,6 +1093,7 @@ class LinearNumberOpTests(parameterized.TestCase):
class QuadraticTermKey(absltest.TestCase):
# Mock QuadraticTermKey.__hash__ to have a collision in the dictionary lookup
# so that a correct behavior of term1 == term2 is needed to recover the
# values. For instance, if QuadraticTermKey.__eq__ only compared equality of
@@ -1141,6 +1148,7 @@ def all_quadratic_number_op_parameters() -> List[QuadraticNumberOpTestsParameter
for p in all_quadratic_number_op_parameters()
)
class QuadraticNumberOpTests(parameterized.TestCase):
def test_mult(
self,
quadratic_type: str,
@@ -1436,6 +1444,7 @@ def all_linear_linear_add_sub_params() -> List[LinearLinearAddSubTestParams]:
# Test add/sub operations (including inplace) between two Linear objects.
class LinearLinearAddSubTest(parameterized.TestCase):
@parameterized.named_parameters(
(p.test_suffix(), p.lhs_type, p.rhs_type, p.subtract)
for p in all_linear_linear_add_sub_params()
@@ -1543,6 +1552,7 @@ def all_linear_quadratic_add_sub_params() -> List[LinearQuadraticAddSubTestParam
# objects. Also re-checks the operations for the pure Linear check when the
# result is intereted as a QuadraticExpression.
class LinearQuadraticAddSubTest(parameterized.TestCase):
def assertDictEqualWithZeroDefault(
self, dict1: dict[Any, float], dict2: dict[Any, float]
) -> None:
@@ -1710,6 +1720,7 @@ class LinearQuadraticAddSubTest(parameterized.TestCase):
# Test multiplication of two Linear objects.
class LinearLinearMulTest(parameterized.TestCase):
def assertDictEqualWithZeroDefault(
self, dict1: dict[Any, float], dict2: dict[Any, float]
) -> None:
@@ -2038,6 +2049,7 @@ class LinearLinearMulTest(parameterized.TestCase):
# Test negate on Linear and Quadratic objects.
class NegateTest(parameterized.TestCase):
def test_negate_var(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -2230,6 +2242,7 @@ def get_linear_or_quadratic_for_unsupported_operand_test(
class UnsupportedProductOperandTest(parameterized.TestCase):
@parameterized.named_parameters(
(p.test_suffix(), p.lhs_type, p.rhs_type)
for p in all_unsupported_product_operand_params()
@@ -2308,6 +2321,7 @@ def all_unsupported_addition_operand_params() -> (
for p in all_unsupported_addition_operand_params()
)
class UnsupportedAdditionOperandTest(parameterized.TestCase):
def test_add(
self, linear_or_quadratic_type: str, linear_or_quadratic_first: bool
) -> None:
@@ -2382,6 +2396,7 @@ class UnsupportedAdditionOperandTest(parameterized.TestCase):
class UnsupportedInitializationTest(parameterized.TestCase):
def test_linear_sum_not_tuple(self):
# pytype: disable=wrong-arg-types
with self.assertRaisesRegex(TypeError, "object is not iterable"):
@@ -2469,6 +2484,7 @@ class UnsupportedInitializationTest(parameterized.TestCase):
@parameterized.named_parameters(("_python_sum", True), ("LinearSum", False))
class SumTest(parameterized.TestCase):
def test_sum_vars(self, python_sum: bool) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")
@@ -2637,6 +2653,7 @@ class SumTest(parameterized.TestCase):
class AstTest(parameterized.TestCase):
def assertDictEqualWithZeroDefault(
self, dict1: dict[Any, float], dict2: dict[Any, float]
) -> None:
@@ -2739,6 +2756,7 @@ class AstTest(parameterized.TestCase):
# Test behavior of LinearExpression and as_flat_linear_expression that is
# not covered by other tests.
class LinearExpressionTest(absltest.TestCase):
def test_init_to_zero(self) -> None:
expression = model.LinearExpression()
self.assertEqual(expression.offset, 0.0)
@@ -2775,6 +2793,7 @@ class LinearExpressionTest(absltest.TestCase):
# Test behavior of QuadraticExpression and as_flat_quadratic_expression that is
# not covered by other tests.
class QuadraticExpressionTest(absltest.TestCase):
def test_terms_read_only(self) -> None:
mod = model.Model()
x = mod.add_binary_variable(name="x")

View File

@@ -84,6 +84,7 @@ def _get_public_api(module: types.ModuleType) -> List[Tuple[str, Any]]:
class MathoptTest(absltest.TestCase):
def test_imports(self) -> None:
missing_imports: List[str] = []
for module in _MODULES_TO_CHECK:

View File

@@ -24,8 +24,10 @@ from ortools.math_opt.python import message_callback
class PrinterMessageCallbackTest(absltest.TestCase):
def test_no_prefix(self):
class FlushCountingStringIO(io.StringIO):
def __init__(self):
super().__init__()
self.num_flushes: int = 0
@@ -54,6 +56,7 @@ class PrinterMessageCallbackTest(absltest.TestCase):
class LogMessagesTest(absltest.TestCase):
def test_defaults(self):
with self.assertLogs(logger="absl", level="INFO") as logs:
message_callback.log_messages(["line 1", "line 2"])
@@ -111,6 +114,7 @@ class VLogMessagesTest(absltest.TestCase):
class ListMessageCallbackTest(absltest.TestCase):
def test_empty(self):
msgs = []
cb = message_callback.list_message_callback(msgs)

View File

@@ -24,6 +24,7 @@ from ortools.math_opt.python.testing import compare_proto
class ModelParametersTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_solution_hint_round_trip(self) -> None:
mod = model.Model(name="test_model")
x = mod.add_binary_variable(name="x")

View File

@@ -117,6 +117,7 @@ class StorageUpdateTracker(abc.ABC):
class UsedUpdateTrackerAfterRemovalError(RuntimeError):
def __init__(self):
super().__init__(
"Attempted to use update tracker after removing it from model storage."

View File

@@ -30,6 +30,7 @@ _ObjEntry = model_storage.LinearObjectiveEntry
@parameterized.parameters((hash_model_storage.HashModelStorage,))
class ModelStorageTest(compare_proto.MathOptProtoAssertions, parameterized.TestCase):
def test_add_and_read_variables(self, storage_class: _StorageClass) -> None:
storage = storage_class("test_model")
self.assertEqual(0, storage.next_variable_id())

View File

@@ -36,6 +36,7 @@ _ObjectiveUpdatesProto = model_update_pb2.ObjectiveUpdatesProto
@parameterized.parameters((hash_model_storage.HashModelStorage,))
class ModelStorageTest(compare_proto.MathOptProtoAssertions, parameterized.TestCase):
def test_simple_delete_var(self, storage_class: _StorageClass) -> None:
storage = storage_class("test_model")
tracker = storage.add_update_tracker()

View File

@@ -32,6 +32,7 @@ _ObjEntry = model_storage.LinearObjectiveEntry
@parameterized.parameters((hash_model_storage.HashModelStorage,))
class ModelTest(compare_proto.MathOptProtoAssertions, parameterized.TestCase):
def test_name(self, storage_class: StorageClass) -> None:
mod = model.Model(name="test_model", storage_class=storage_class)
self.assertEqual("test_model", mod.name)

View File

@@ -26,6 +26,7 @@ from ortools.math_opt.python import normalize
class MathOptProtoAssertionsTest(absltest.TestCase, compare.Proto2Assertions):
def test_removes_empty_message(self) -> None:
model_with_empty_vars = model_pb2.ModelProto()
model_with_empty_vars.variables.SetInParent()

View File

@@ -31,6 +31,7 @@ from ortools.sat import sat_parameters_pb2
class GurobiParameters(absltest.TestCase):
def test_to_proto(self) -> None:
gurobi_proto = parameters.GurobiParameters(
param_values={"x": "dog", "ab": "7"}
@@ -45,6 +46,7 @@ class GurobiParameters(absltest.TestCase):
class GlpkParameters(absltest.TestCase):
def test_to_proto(self) -> None:
# Test with `optional bool` set to true.
glpk_proto = parameters.GlpkParameters(
@@ -71,6 +73,7 @@ class GlpkParameters(absltest.TestCase):
class ProtoRoundTrip(absltest.TestCase):
def test_solver_type_round_trip(self) -> None:
for solver_type in parameters.SolverType:
self.assertEqual(

View File

@@ -26,6 +26,7 @@ from ortools.math_opt.python.testing import compare_proto
class ParseTerminationReason(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_termination_unspecified(self) -> None:
termination_proto = result_pb2.TerminationProto(
reason=result_pb2.TERMINATION_REASON_UNSPECIFIED
@@ -86,6 +87,7 @@ class ParseTerminationReason(compare_proto.MathOptProtoAssertions, absltest.Test
class ParseProblemStatus(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_problem_status_round_trip(self) -> None:
problem_status = result.ProblemStatus(
primal_status=result.FeasibilityStatus.FEASIBLE,
@@ -124,6 +126,7 @@ class ParseProblemStatus(compare_proto.MathOptProtoAssertions, absltest.TestCase
class ParseObjectiveBounds(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_objective_bounds_round_trip(self) -> None:
objective_bounds = result.ObjectiveBounds(primal_bound=10, dual_bound=20)
objective_bounds_proto = objective_bounds.to_proto()
@@ -136,6 +139,7 @@ class ParseObjectiveBounds(compare_proto.MathOptProtoAssertions, absltest.TestCa
class ParseSolveStats(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_problem_status_round_trip(self) -> None:
solve_stats = result.SolveStats(
solve_time=datetime.timedelta(seconds=10),
@@ -157,6 +161,7 @@ class ParseSolveStats(compare_proto.MathOptProtoAssertions, absltest.TestCase):
class SolveResultAuxiliaryFunctionsTest(absltest.TestCase):
def test_solve_time(self) -> None:
res = result.SolveResult(
solve_stats=result.SolveStats(solve_time=datetime.timedelta(seconds=10))
@@ -638,6 +643,7 @@ def _make_undetermined_result_proto() -> result_pb2.SolveResultProto:
class SolveResultTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_solve_result_gscip_output(self) -> None:
mod = model.Model(name="test_model")
mod.add_binary_variable()

View File

@@ -20,6 +20,7 @@ from ortools.math_opt.python.testing import compare_proto
class ParsePrimalSolutionTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_empty_primal_solution_proto_round_trip(self) -> None:
mod = model.Model(name="test_model")
empty_solution = solution.PrimalSolution(
@@ -64,6 +65,7 @@ class ParsePrimalSolutionTest(compare_proto.MathOptProtoAssertions, absltest.Tes
class ParsePrimalRayTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_parse(self) -> None:
mod = model.Model(name="test_model")
x = mod.add_binary_variable(name="x")
@@ -76,6 +78,7 @@ class ParsePrimalRayTest(compare_proto.MathOptProtoAssertions, absltest.TestCase
class ParseDualSolutionTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_empty_primal_solution_proto_round_trip(self) -> None:
mod = model.Model(name="test_model")
empty_solution = solution.DualSolution(
@@ -137,6 +140,7 @@ class ParseDualSolutionTest(compare_proto.MathOptProtoAssertions, absltest.TestC
class ParseDualRayTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_parse(self) -> None:
mod = model.Model(name="test_model")
x = mod.add_binary_variable(name="x")
@@ -154,6 +158,7 @@ class ParseDualRayTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
class BasisTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_empty_basis_proto_round_trip(self) -> None:
mod = model.Model(name="test_model")
empty_basis = solution.Basis()
@@ -268,6 +273,7 @@ class BasisTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
class ParseSolutionTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_solution_proto_round_trip(self) -> None:
mod = model.Model(name="test_model")
mod.add_variable()

View File

@@ -31,6 +31,7 @@ _Bounds = compute_infeasible_subsystem_result.ModelSubsetBounds
class SolveTest(absltest.TestCase):
def test_callback(self) -> None:
mod = model.Model(name="test_model")
# Solve the problem:

View File

@@ -46,6 +46,7 @@ def _list_is_near(v1: List[float], v2: List[float], tolerance: float = 1e-5) ->
class SolveTest(absltest.TestCase):
def _assert_dict_almost_equal(
self, expected: VarOrConstraintDict, actual: VarOrConstraintDict, places=5
):

View File

@@ -21,6 +21,7 @@ from ortools.math_opt.python.testing import compare_proto
class SolverResourcesTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_to_proto_empty(self):
self.assert_protos_equiv(
solver_resources.SolverResources().to_proto(),

View File

@@ -20,6 +20,7 @@ from ortools.math_opt.python.testing import compare_proto
class SparseDoubleVectorTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_to_proto_empty(self) -> None:
actual = sparse_containers.to_sparse_double_vector_proto({})
self.assert_protos_equiv(
@@ -97,6 +98,7 @@ class SparseDoubleVectorTest(compare_proto.MathOptProtoAssertions, absltest.Test
class SparseInt32VectorTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_to_proto_empty(self) -> None:
self.assert_protos_equiv(
sparse_containers.to_sparse_int32_vector_proto({}),
@@ -124,6 +126,7 @@ class SparseInt32VectorTest(compare_proto.MathOptProtoAssertions, absltest.TestC
class SparseVectorFilterTest(compare_proto.MathOptProtoAssertions, absltest.TestCase):
def test_is_none(self) -> None:
f = sparse_containers.SparseVectorFilter(skip_zero_values=True)
self.assertTrue(f.skip_zero_values)

View File

@@ -22,6 +22,7 @@ from ortools.math_opt.python import statistics
class RangeTest(absltest.TestCase):
def test_merge_optional_ranges(self) -> None:
self.assertIsNone(statistics.merge_optional_ranges(None, None))
r = statistics.Range(1.0, 3.0)
@@ -52,6 +53,7 @@ class RangeTest(absltest.TestCase):
class ModelRangesTest(absltest.TestCase):
def test_printing(self) -> None:
self.assertMultiLineEqual(
str(
@@ -130,6 +132,7 @@ class ModelRangesTest(absltest.TestCase):
class ComputeModelRangesTest(absltest.TestCase):
def test_empty(self) -> None:
mdl = model.Model(name="model")
self.assertEqual(