mostly reformat

This commit is contained in:
Laurent Perron
2024-04-08 11:34:45 +02:00
parent e1c19b6c94
commit 622483b682
20 changed files with 56 additions and 41 deletions

View File

@@ -22,6 +22,7 @@ from ortools.algorithms.python import knapsack_solver
class PyWrapAlgorithmsKnapsackSolverTest(absltest.TestCase):
def RealSolve(self, profits, weights, capacities, solver_type, use_reduction):
solver = knapsack_solver.KnapsackSolver(solver_type, "solver")
solver.set_use_reduction(use_reduction)

View File

@@ -15,7 +15,6 @@
#include <string>
#include <vector>
#include "absl/flags/flag.h"
#include "absl/log/check.h"
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
@@ -122,26 +121,26 @@ const char data_dir[] =
#define ORLIB_TEST(name, best_objective, expected_objective, size, function) \
TEST(OrlibTest, APPEND_AND_EVAL(TestOnLine, __LINE__)) { \
auto filespec = file::JoinPathRespectAbsolute( \
absl::GetFlag(FLAGS_test_srcdir), data_dir, name); \
auto filespec = \
file::JoinPathRespectAbsolute(::testing::SrcDir(), data_dir, name); \
LOG(INFO) << "Reading " << name; \
operations_research::SetCoverModel model = function(filespec); \
double cost = RunSolver(name, &model); \
(void)cost; \
}
#define ORLIB_UNICOST_TEST(name, best_objective, expected_objective, size, \
function) \
TEST(OrlibUnicostTest, APPEND_AND_EVAL(TestOnLine, __LINE__)) { \
auto filespec = file::JoinPathRespectAbsolute( \
absl::GetFlag(FLAGS_test_srcdir), data_dir, name); \
LOG(INFO) << "Reading " << name; \
operations_research::SetCoverModel model = function(filespec); \
for (int i = 0; i < model.num_subsets(); ++i) { \
model.SetSubsetCost(i, 1.0); \
} \
double cost = RunSolver(absl::StrCat(name, "_unicost"), &model); \
(void)cost; \
#define ORLIB_UNICOST_TEST(name, best_objective, expected_objective, size, \
function) \
TEST(OrlibUnicostTest, APPEND_AND_EVAL(TestOnLine, __LINE__)) { \
auto filespec = \
file::JoinPathRespectAbsolute(::testing::SrcDir(), data_dir, name); \
LOG(INFO) << "Reading " << name; \
operations_research::SetCoverModel model = function(filespec); \
for (int i = 0; i < model.num_subsets(); ++i) { \
model.SetSubsetCost(i, 1.0); \
} \
double cost = RunSolver(absl::StrCat(name, "_unicost"), &model); \
(void)cost; \
}
#define SCP_TEST(name, best_objective, expected_objective, size) \

View File

@@ -72,6 +72,7 @@ def main():
for arc in range(smcf.num_arcs()):
# Can ignore arcs leading out of source or into sink.
if smcf.tail(arc) != source and smcf.head(arc) != sink:
# Arcs in the solution have a flow value of 1. Their start and end nodes
# give an assignment of worker to task.
if smcf.flow(arc) > 0:

View File

@@ -103,6 +103,7 @@ def main():
and smcf.tail(arc) != 12
and smcf.head(arc) != sink
):
# Arcs in the solution will have a flow value of 1.
# There start and end nodes give an assignment of worker to task.
if smcf.flow(arc) > 0:

View File

@@ -19,6 +19,7 @@ from ortools.init.python import init
class InitTest(absltest.TestCase):
def test_logging(self):
print("test_logging")
init.CppBridge.init_logging("pywrapinit_test.py")

View File

@@ -932,12 +932,10 @@ class Model:
return clone
@typing.overload
def _get_linear_constraints(self, constraints: Optional[pd.Index]) -> pd.Index:
...
def _get_linear_constraints(self, constraints: Optional[pd.Index]) -> pd.Index: ...
@typing.overload
def _get_linear_constraints(self, constraints: pd.Series) -> pd.Series:
...
def _get_linear_constraints(self, constraints: pd.Series) -> pd.Series: ...
def _get_linear_constraints(
self, constraints: Optional[_IndexOrSeries] = None
@@ -947,12 +945,10 @@ class Model:
return constraints
@typing.overload
def _get_variables(self, variables: Optional[pd.Index]) -> pd.Index:
...
def _get_variables(self, variables: Optional[pd.Index]) -> pd.Index: ...
@typing.overload
def _get_variables(self, variables: pd.Series) -> pd.Series:
...
def _get_variables(self, variables: pd.Series) -> pd.Series: ...
def _get_variables(
self, variables: Optional[_IndexOrSeries] = None

View File

@@ -27,6 +27,7 @@ from ortools.linear_solver.python import model_builder_helper
class PywrapModelBuilderHelperTest(absltest.TestCase):
def test_export_model_proto_to_mps_string(self):
model = model_builder_helper.ModelBuilderHelper()
model.set_name("testmodel")

View File

@@ -420,6 +420,7 @@ ENDATA
class InternalHelperTest(absltest.TestCase):
def test_anonymous_variables(self):
helper = mb.Model().helper
index = helper.add_var()
@@ -434,6 +435,7 @@ class InternalHelperTest(absltest.TestCase):
class LinearBaseTest(parameterized.TestCase):
def setUp(self):
super().setUp()
simple_model = mb.Model()
@@ -614,6 +616,7 @@ class LinearBaseTest(parameterized.TestCase):
class LinearBaseErrorsTest(absltest.TestCase):
def test_unknown_linear_type(self):
with self.assertRaisesRegex(TypeError, r"Unrecognized linear expression"):
@@ -636,6 +639,7 @@ class LinearBaseErrorsTest(absltest.TestCase):
class BoundedLinearBaseTest(parameterized.TestCase):
def setUp(self):
super().setUp()
simple_model = mb.Model()
@@ -729,6 +733,7 @@ class BoundedLinearBaseTest(parameterized.TestCase):
class BoundedLinearBaseErrorsTest(absltest.TestCase):
def test_bounded_linear_expression_as_bool(self):
with self.assertRaisesRegex(NotImplementedError, "Boolean value"):
model = mb.Model()
@@ -737,6 +742,7 @@ class BoundedLinearBaseErrorsTest(absltest.TestCase):
class ModelBuilderErrorsTest(absltest.TestCase):
def test_new_var_series_errors(self):
with self.assertRaisesRegex(TypeError, r"Non-index object"):
model = mb.Model()
@@ -1565,6 +1571,7 @@ class ModelBuilderObjectiveTest(parameterized.TestCase):
class ModelBuilderProtoTest(absltest.TestCase):
def test_export_to_proto(self):
expected = linear_solver_pb2.MPModelProto()
text_format.Parse(

View File

@@ -42,6 +42,7 @@ constraint {
class PyWrapLp(unittest.TestCase):
def test_proto(self):
input_proto = linear_solver_pb2.MPModelProto()
text_format.Merge(TEXT_MODEL, input_proto)

View File

@@ -65,12 +65,12 @@ def main():
# [START print_solution]
print(f"Status: {result_status}")
if result_status != pywraplp.Solver.OPTIMAL:
print("The problem does not have an optimal solution!")
if result_status == pywraplp.Solver.FEASIBLE:
print("A potentially suboptimal solution was found")
else:
print("The solver could not solve the problem.")
return
print("The problem does not have an optimal solution!")
if result_status == pywraplp.Solver.FEASIBLE:
print("A potentially suboptimal solution was found")
else:
print("The solver could not solve the problem.")
return
print("Solution:")
print("Objective value =", objective.Value())

View File

@@ -676,7 +676,7 @@ class LinearExpr:
class _Sum(LinearExpr):
"""Represents the sum of two LinearExprs."""
def __init__(self, left, right):
def __init__(self, left, right) -> None:
for x in [left, right]:
if not isinstance(x, (NumberTypes, LinearExpr)):
raise TypeError("not an linear expression: " + str(x))
@@ -699,7 +699,7 @@ class _Sum(LinearExpr):
class _ProductCst(LinearExpr):
"""Represents the product of a LinearExpr by a constant."""
def __init__(self, expr, coeff):
def __init__(self, expr, coeff) -> None:
coeff = cmh.assert_is_a_number(coeff)
if isinstance(expr, _ProductCst):
self.__expr = expr.expression()
@@ -727,7 +727,7 @@ class _ProductCst(LinearExpr):
class _SumArray(LinearExpr):
"""Represents the sum of a list of LinearExpr and a constant."""
def __init__(self, expressions, constant=0):
def __init__(self, expressions, constant=0) -> None:
self.__expressions = []
self.__constant = constant
for x in expressions:
@@ -764,7 +764,7 @@ class _SumArray(LinearExpr):
class _WeightedSum(LinearExpr):
"""Represents sum(ai * xi) + b."""
def __init__(self, expressions, coefficients, constant=0):
def __init__(self, expressions, coefficients, constant=0) -> None:
self.__expressions = []
self.__coefficients = []
self.__constant = constant
@@ -948,7 +948,7 @@ class IntVar(LinearExpr):
class _NotBooleanVariable(LinearExpr):
"""Negation of a boolean variable."""
def __init__(self, boolvar: IntVar):
def __init__(self, boolvar: IntVar) -> None:
self.__boolvar: IntVar = boolvar
@property

View File

@@ -20,6 +20,7 @@ from ortools.sat.python import cp_model_helper
class CpModelHelperTest(absltest.TestCase):
def test_is_boolean(self):
print("test_is_boolean")
self.assertTrue(cp_model_helper.is_boolean(True))
@@ -34,9 +35,7 @@ class CpModelHelperTest(absltest.TestCase):
self.assertRaises(TypeError, cp_model_helper.assert_is_int64, "Hello")
self.assertRaises(TypeError, cp_model_helper.assert_is_int64, 1.2)
self.assertRaises(OverflowError, cp_model_helper.assert_is_int64, 2**63)
self.assertRaises(
OverflowError, cp_model_helper.assert_is_int64, -(2**63) - 1
)
self.assertRaises(OverflowError, cp_model_helper.assert_is_int64, -(2**63) - 1)
cp_model_helper.assert_is_int64(123)
cp_model_helper.assert_is_int64(2**63 - 1)
cp_model_helper.assert_is_int64(-(2**63))

View File

@@ -111,6 +111,7 @@ class LogToString:
class CpModelTest(absltest.TestCase):
def testCreateIntegerVariable(self):
print("testCreateIntegerVariable")
model = cp_model.CpModel()

View File

@@ -22,6 +22,7 @@ from ortools.sat.python import swig_helper
class Callback(swig_helper.SolutionCallback):
def __init__(self):
swig_helper.SolutionCallback.__init__(self)
self.__solution_count = 0
@@ -35,6 +36,7 @@ class Callback(swig_helper.SolutionCallback):
class SwigHelperTest(absltest.TestCase):
def testVariableDomain(self):
model_string = """
variables { domain: [ -10, 10 ] }

View File

@@ -57,7 +57,7 @@ void JsspParser::SetMachines(int machine_count) {
}
}
bool JsspParser::ParseFile(const std::string& filename) {
bool JsspParser::ParseFile(absl::string_view filename) {
problem_.Clear();
// Try to detect the type of the data file.
// - fjs suffix -> Flexible Jobshop

View File

@@ -59,7 +59,7 @@ class JsspParser {
// Parses a file to load a jobshop problem.
// Tries to auto detect the file format.
bool ParseFile(const std::string& filename);
bool ParseFile(absl::string_view filename);
// Returns the loaded problem.
const JsspInputProblem& problem() const { return problem_; }

View File

@@ -23,6 +23,7 @@ FLAGS = flags.FLAGS
class RcpspTest(absltest.TestCase):
def testParseAndAccess(self):
parser = rcpsp.RcpspParser()
data = "ortools/scheduling/testdata/j301_1.sm"

View File

@@ -19,6 +19,7 @@ from ortools.util.python import sorted_interval_list
class SortedIntervalListTest(absltest.TestCase):
def testCtorAndGetter(self):
bool_domain = sorted_interval_list.Domain(0, 1)
self.assertEqual(2, bool_domain.size())

View File

@@ -20,13 +20,14 @@
#include "absl/log/check.h"
#include "absl/strings/numbers.h"
#include "absl/strings/str_split.h"
#include "absl/strings/string_view.h"
#include "ortools/util/filelineiter.h"
namespace operations_research {
// TODO(user): Unit test cases when the function dies, or return
// (and test) a status instead.
QapProblem ReadQapProblemOrDie(const std::string& filepath) {
QapProblem ReadQapProblemOrDie(absl::string_view filepath) {
QapProblem qap_problem;
int n = 0;

View File

@@ -18,6 +18,8 @@
#include <string>
#include <vector>
#include "absl/strings/string_view.h"
namespace operations_research {
// Quadratic assignment problem (QAP) is a classical combinatorial optimization
@@ -63,7 +65,7 @@ struct QapProblem {
// supply flowing from factory 0 to factory 1, and 3 units of supply flowing
// from factory 1 to 0. The distance from location 0 to location 1 is equal
// to 2, and the distance from location 1 to 0 is equal to 1.
QapProblem ReadQapProblemOrDie(const std::string& filepath);
QapProblem ReadQapProblemOrDie(absl::string_view filepath);
} // namespace operations_research