export pdlp/python
This commit is contained in:
@@ -227,7 +227,7 @@ set(PYTHON_PROJECT_DIR ${PROJECT_BINARY_DIR}/python/${PYTHON_PROJECT})
|
||||
message(STATUS "Python project build path: ${PYTHON_PROJECT_DIR}")
|
||||
|
||||
# Swig wrap all libraries
|
||||
foreach(SUBPROJECT IN ITEMS init algorithms graph linear_solver constraint_solver sat scheduling util)
|
||||
foreach(SUBPROJECT IN ITEMS init algorithms graph linear_solver constraint_solver pdlp sat scheduling util)
|
||||
add_subdirectory(ortools/${SUBPROJECT}/python)
|
||||
endforeach()
|
||||
|
||||
@@ -247,6 +247,7 @@ file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/linear_solver/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/linear_solver/python/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/packing/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/pdlp/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/pdlp/python/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/sat/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/sat/python/__init__.py CONTENT "")
|
||||
file(GENERATE OUTPUT ${PYTHON_PROJECT_DIR}/scheduling/__init__.py CONTENT "")
|
||||
@@ -311,6 +312,7 @@ add_custom_command(
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:pywrapcp> ${PYTHON_PROJECT}/constraint_solver
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:pywraplp> ${PYTHON_PROJECT}/linear_solver
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:pywrap_model_builder_helper> ${PYTHON_PROJECT}/linear_solver/python
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:pywrap_pdlp_pybind11> ${PYTHON_PROJECT}/pdlp/python
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:swig_helper> ${PYTHON_PROJECT}/sat/python
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:pywraprcpsp> ${PYTHON_PROJECT}/scheduling
|
||||
COMMAND ${CMAKE_COMMAND} -E copy $<TARGET_FILE:sorted_interval_list> ${PYTHON_PROJECT}/util/python
|
||||
@@ -331,6 +333,7 @@ add_custom_command(
|
||||
pywrapcp
|
||||
pywraplp
|
||||
pywrap_model_builder_helper
|
||||
pywrap_pdlp_pybind11
|
||||
swig_helper
|
||||
pywraprcpsp
|
||||
sorted_interval_list
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
# limitations under the License.
|
||||
|
||||
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
|
||||
load("@com_google_protobuf//:protobuf.bzl", "py_proto_library")
|
||||
|
||||
package(
|
||||
default_visibility = ["//visibility:public"],
|
||||
@@ -237,6 +238,11 @@ cc_proto_library(
|
||||
deps = [":parameters_proto"],
|
||||
)
|
||||
|
||||
py_proto_library(
|
||||
name = "parameters_py_pb2",
|
||||
srcs = ["parameters.proto"],
|
||||
)
|
||||
|
||||
proto_library(
|
||||
name = "parameters_proto",
|
||||
srcs = ["parameters.proto"],
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
# limitations under the License.
|
||||
|
||||
load("@rules_cc//cc:defs.bzl", "cc_proto_library")
|
||||
load("@com_google_protobuf//:protobuf.bzl", "py_proto_library")
|
||||
|
||||
package(default_visibility = ["//visibility:public"])
|
||||
|
||||
@@ -26,6 +27,12 @@ cc_proto_library(
|
||||
deps = [":solve_log_proto"],
|
||||
)
|
||||
|
||||
py_proto_library(
|
||||
name = "solve_log_py_pb2",
|
||||
srcs = ["solve_log.proto"],
|
||||
deps = [":solvers_py_pb2"],
|
||||
)
|
||||
|
||||
proto_library(
|
||||
name = "solvers_proto",
|
||||
srcs = ["solvers.proto"],
|
||||
@@ -37,6 +44,12 @@ cc_proto_library(
|
||||
deps = [":solvers_proto"],
|
||||
)
|
||||
|
||||
py_proto_library(
|
||||
name = "solvers_py_pb2",
|
||||
srcs = ["solvers.proto"],
|
||||
deps = ["//ortools/glop:parameters_py_pb2"],
|
||||
)
|
||||
|
||||
cc_library(
|
||||
name = "gtest_main",
|
||||
srcs = ["gtest_main.cc"],
|
||||
|
||||
54
ortools/pdlp/python/BUILD.bazel
Normal file
54
ortools/pdlp/python/BUILD.bazel
Normal file
@@ -0,0 +1,54 @@
|
||||
# Copyright 2010-2022 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.
|
||||
|
||||
# Python wrapper for pdlp libraries.
|
||||
|
||||
load("@pybind11_bazel//:build_defs.bzl", "pybind_extension")
|
||||
load("@rules_python//python:defs.bzl", "py_test")
|
||||
load("@ortools_deps//:requirements.bzl", "requirement")
|
||||
|
||||
pybind_extension(
|
||||
name = "pywrap_pdlp",
|
||||
srcs = ["pywrap_pdlp.cc"],
|
||||
visibility = ["//visibility:public"],
|
||||
deps = [
|
||||
"//ortools/linear_solver:linear_solver_cc_proto",
|
||||
"//ortools/pdlp:primal_dual_hybrid_gradient",
|
||||
"//ortools/pdlp:quadratic_program",
|
||||
"//ortools/pdlp:quadratic_program_io",
|
||||
"//ortools/pdlp:solvers_cc_proto",
|
||||
"@com_google_absl//absl/status",
|
||||
"@com_google_absl//absl/status:statusor",
|
||||
"@com_google_absl//absl/strings",
|
||||
"@eigen//:eigen3",
|
||||
],
|
||||
)
|
||||
|
||||
py_test(
|
||||
name = "pywrap_pdlp_test",
|
||||
size = "small",
|
||||
srcs = ["pywrap_pdlp_test.py"],
|
||||
data = [
|
||||
":pywrap_pdlp.so",
|
||||
],
|
||||
python_version = "PY3",
|
||||
srcs_version = "PY3",
|
||||
deps = [
|
||||
requirement("absl-py"),
|
||||
requirement("numpy"),
|
||||
requirement("scipy"),
|
||||
"//ortools/linear_solver:linear_solver_py_pb2",
|
||||
"//ortools/pdlp:solve_log_py_pb2",
|
||||
"//ortools/pdlp:solvers_py_pb2",
|
||||
],
|
||||
)
|
||||
37
ortools/pdlp/python/CMakeLists.txt
Normal file
37
ortools/pdlp/python/CMakeLists.txt
Normal file
@@ -0,0 +1,37 @@
|
||||
# Copyright 2010-2022 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.
|
||||
|
||||
pybind11_add_module(pywrap_pdlp_pybind11 MODULE pywrap_pdlp.cc)
|
||||
# note: macOS is APPLE and also UNIX !
|
||||
set_target_properties(pywrap_pdlp_pybind11 PROPERTIES
|
||||
LIBRARY_OUTPUT_NAME "pywrap_pdlp")
|
||||
if(APPLE)
|
||||
set_target_properties(pywrap_pdlp_pybind11 PROPERTIES
|
||||
SUFFIX ".so"
|
||||
INSTALL_RPATH "@loader_path;@loader_path/../../../${PYTHON_PROJECT}/.libs"
|
||||
LINK_FLAGS "-flat_namespace -undefined suppress"
|
||||
)
|
||||
elseif(UNIX)
|
||||
set_target_properties(pywrap_pdlp_pybind11 PROPERTIES
|
||||
INSTALL_RPATH "$ORIGIN:$ORIGIN/../../../${PYTHON_PROJECT}/.libs"
|
||||
)
|
||||
endif()
|
||||
target_link_libraries(pywrap_pdlp_pybind11 PRIVATE ${PROJECT_NAMESPACE}::ortools)
|
||||
add_library(${PROJECT_NAMESPACE}::pywrap_pdlp_pybind11 ALIAS pywrap_pdlp_pybind11)
|
||||
|
||||
if(BUILD_TESTING)
|
||||
file(GLOB PYTHON_SRCS "*_test.py")
|
||||
foreach(FILE_NAME IN LISTS PYTHON_SRCS)
|
||||
add_python_test(${FILE_NAME})
|
||||
endforeach()
|
||||
endif()
|
||||
181
ortools/pdlp/python/pywrap_pdlp.cc
Normal file
181
ortools/pdlp/python/pywrap_pdlp.cc
Normal file
@@ -0,0 +1,181 @@
|
||||
// Copyright 2010-2022 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.
|
||||
|
||||
// A pybind11 wrapper for pdlp.
|
||||
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
#include "Eigen/Core"
|
||||
#include "Eigen/SparseCore"
|
||||
#include "absl/status/status.h"
|
||||
#include "absl/status/statusor.h"
|
||||
#include "absl/strings/str_cat.h"
|
||||
#include "absl/strings/string_view.h"
|
||||
#include "ortools/linear_solver/linear_solver.pb.h"
|
||||
#include "ortools/pdlp/primal_dual_hybrid_gradient.h"
|
||||
#include "ortools/pdlp/quadratic_program.h"
|
||||
#include "ortools/pdlp/quadratic_program_io.h"
|
||||
#include "ortools/pdlp/solvers.pb.h"
|
||||
#include "pybind11/eigen.h"
|
||||
#include "pybind11/pybind11.h"
|
||||
#include "pybind11/pytypes.h"
|
||||
#include "pybind11/stl.h"
|
||||
|
||||
namespace pdlp = ::operations_research::pdlp;
|
||||
using ::operations_research::MPModelProto;
|
||||
using ::operations_research::pdlp::QuadraticProgram;
|
||||
using ::pybind11::arg;
|
||||
|
||||
// TODO(user): The interface uses serialized protos because of issues building
|
||||
// pybind11_protobuf. See
|
||||
// https://github.com/protocolbuffers/protobuf/issues/9464. After
|
||||
// pybind11_protobuf is working, this workaround can be removed.
|
||||
|
||||
// A mirror of pdlp::SolverResult except with a serialized SolveLog.
|
||||
struct PywrapSolverResult {
|
||||
Eigen::VectorXd primal_solution;
|
||||
Eigen::VectorXd dual_solution;
|
||||
Eigen::VectorXd reduced_costs;
|
||||
pybind11::bytes solve_log_str;
|
||||
};
|
||||
|
||||
PYBIND11_MODULE(pywrap_pdlp, m) {
|
||||
// ---------------------------------------------------------------------------
|
||||
// quadratic_program.h
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// It's ok to read and assign to the fields of QuadraticProgram. Attempts to
|
||||
// mutate the fields will likely fail silently because of the copies back and
|
||||
// forth from Python and C++.
|
||||
pybind11::class_<QuadraticProgram>(m, "QuadraticProgram")
|
||||
.def(pybind11::init<>())
|
||||
.def("resize_and_initialize", &QuadraticProgram::ResizeAndInitialize)
|
||||
.def("apply_objective_scaling_and_offset",
|
||||
&QuadraticProgram::ApplyObjectiveScalingAndOffset)
|
||||
.def_readwrite("objective_vector", &QuadraticProgram::objective_vector)
|
||||
.def_readwrite("constraint_matrix", &QuadraticProgram::constraint_matrix)
|
||||
.def_readwrite("constraint_lower_bounds",
|
||||
&QuadraticProgram::constraint_lower_bounds)
|
||||
.def_readwrite("constraint_upper_bounds",
|
||||
&QuadraticProgram::constraint_upper_bounds)
|
||||
.def_readwrite("variable_lower_bounds",
|
||||
&QuadraticProgram::variable_lower_bounds)
|
||||
.def_readwrite("variable_upper_bounds",
|
||||
&QuadraticProgram::variable_upper_bounds)
|
||||
.def_readwrite("problem_name", &QuadraticProgram::problem_name)
|
||||
.def_readwrite("variable_names", &QuadraticProgram::variable_names)
|
||||
.def_readwrite("constraint_names", &QuadraticProgram::constraint_names)
|
||||
.def_readwrite("objective_offset", &QuadraticProgram::objective_offset)
|
||||
.def_readwrite("objective_scaling_factor",
|
||||
&QuadraticProgram::objective_scaling_factor)
|
||||
// It appears that pybind11/eigen.h provides only a C++ -> Python
|
||||
// converter for DiagonalMatrix, so we can't expose objective_matrix as a
|
||||
// readwrite field. Below are extra methods for setting the objective
|
||||
// matrix.
|
||||
.def_readonly("objective_matrix", &QuadraticProgram::objective_matrix)
|
||||
.def("set_objective_matrix_diagonal",
|
||||
[](QuadraticProgram& qp,
|
||||
const Eigen::VectorXd& objective_matrix_diagonal) {
|
||||
qp.objective_matrix.emplace();
|
||||
qp.objective_matrix->diagonal() = objective_matrix_diagonal;
|
||||
})
|
||||
.def("clear_objective_matrix",
|
||||
[](QuadraticProgram& qp) { qp.objective_matrix.reset(); });
|
||||
|
||||
m.def("validate_quadratic_program_dimensions",
|
||||
[](const QuadraticProgram& qp) {
|
||||
const absl::Status status =
|
||||
pdlp::ValidateQuadraticProgramDimensions(qp);
|
||||
if (status.ok()) {
|
||||
return;
|
||||
} else {
|
||||
throw std::invalid_argument(absl::StrCat(status.message()));
|
||||
}
|
||||
});
|
||||
|
||||
m.def("is_linear_program", &pdlp::IsLinearProgram);
|
||||
|
||||
m.def(
|
||||
"qp_from_mpmodel_proto",
|
||||
[](absl::string_view proto_str, bool relax_integer_variables,
|
||||
bool include_names) {
|
||||
MPModelProto proto;
|
||||
if (!proto.ParseFromString(std::string(proto_str))) {
|
||||
throw std::invalid_argument("Unable to parse input proto");
|
||||
}
|
||||
absl::StatusOr<QuadraticProgram> qp = pdlp::QpFromMpModelProto(
|
||||
proto, relax_integer_variables, include_names);
|
||||
if (qp.ok()) {
|
||||
return *qp;
|
||||
} else {
|
||||
throw std::invalid_argument(absl::StrCat(qp.status().message()));
|
||||
}
|
||||
},
|
||||
arg("proto_str"), arg("relax_integer_variables"),
|
||||
arg("include_names") = false);
|
||||
|
||||
m.def("qp_to_mpmodel_proto", [](const QuadraticProgram& qp) {
|
||||
absl::StatusOr<MPModelProto> proto = pdlp::QpToMpModelProto(qp);
|
||||
if (proto.ok()) {
|
||||
return pybind11::bytes(proto->SerializeAsString());
|
||||
} else {
|
||||
throw std::invalid_argument(absl::StrCat(proto.status().message()));
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// quadratic_program_io.h
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
m.def("read_quadratic_program_or_die", &pdlp::ReadQuadraticProgramOrDie,
|
||||
arg("filename"), arg("include_names") = false);
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// primal_dual_hybrid_gradient.h
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
pybind11::class_<pdlp::PrimalAndDualSolution>(m, "PrimalAndDualSolution")
|
||||
.def(pybind11::init<>())
|
||||
.def_readwrite("primal_solution",
|
||||
&pdlp::PrimalAndDualSolution::primal_solution)
|
||||
.def_readwrite("dual_solution",
|
||||
&pdlp::PrimalAndDualSolution::dual_solution);
|
||||
|
||||
pybind11::class_<PywrapSolverResult>(m, "SolverResult")
|
||||
.def(pybind11::init<>())
|
||||
.def_readwrite("primal_solution", &PywrapSolverResult::primal_solution)
|
||||
.def_readwrite("dual_solution", &PywrapSolverResult::dual_solution)
|
||||
.def_readwrite("reduced_costs", &PywrapSolverResult::reduced_costs)
|
||||
.def_readwrite("solve_log_str", &PywrapSolverResult::solve_log_str);
|
||||
|
||||
// TODO(user): Expose interrupt_solve and iteration_stats_callback.
|
||||
m.def(
|
||||
"primal_dual_hybrid_gradient",
|
||||
[](QuadraticProgram qp, absl::string_view params_str,
|
||||
std::optional<pdlp::PrimalAndDualSolution> initial_solution) {
|
||||
pdlp::PrimalDualHybridGradientParams params;
|
||||
if (!params.ParseFromString(std::string(params_str))) {
|
||||
throw std::invalid_argument("Unable to parse input params");
|
||||
}
|
||||
pdlp::SolverResult result = pdlp::PrimalDualHybridGradient(
|
||||
std::move(qp), params, std::move(initial_solution));
|
||||
return PywrapSolverResult{
|
||||
.primal_solution = std::move(result.primal_solution),
|
||||
.dual_solution = std::move(result.dual_solution),
|
||||
.reduced_costs = std::move(result.reduced_costs),
|
||||
.solve_log_str = result.solve_log.SerializeAsString()};
|
||||
},
|
||||
arg("qp"), arg("params"), arg("initial_solution") = std::nullopt);
|
||||
}
|
||||
257
ortools/pdlp/python/pywrap_pdlp_test.py
Normal file
257
ortools/pdlp/python/pywrap_pdlp_test.py
Normal file
@@ -0,0 +1,257 @@
|
||||
#!/usr/bin/env python3
|
||||
# Copyright 2010-2022 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.
|
||||
"""Tests for ortools.pdlp.python.quadratic_program."""
|
||||
|
||||
import numpy as np
|
||||
import scipy.sparse
|
||||
|
||||
import unittest
|
||||
from absl.testing import absltest
|
||||
from ortools.pdlp import solve_log_pb2
|
||||
from ortools.pdlp import solvers_pb2
|
||||
from ortools.pdlp.python import pywrap_pdlp
|
||||
from ortools.linear_solver import linear_solver_pb2
|
||||
|
||||
|
||||
def small_proto_lp():
|
||||
# min -2y
|
||||
# s.t. x + y <= 1
|
||||
# x, y >= 0
|
||||
return linear_solver_pb2.MPModelProto(
|
||||
# Defaults are specified for the benefit of assertProto2Equal.
|
||||
maximize=False,
|
||||
objective_offset=0.0,
|
||||
variable=[
|
||||
linear_solver_pb2.MPVariableProto(lower_bound=0,
|
||||
upper_bound=np.inf,
|
||||
objective_coefficient=0,
|
||||
name='x'),
|
||||
linear_solver_pb2.MPVariableProto(lower_bound=0,
|
||||
upper_bound=np.inf,
|
||||
objective_coefficient=-2,
|
||||
name='y')
|
||||
],
|
||||
constraint=[
|
||||
linear_solver_pb2.MPConstraintProto(var_index=[0, 1],
|
||||
coefficient=[1, 1],
|
||||
lower_bound=-np.inf,
|
||||
upper_bound=1)
|
||||
])
|
||||
|
||||
|
||||
def small_proto_qp():
|
||||
# min 2 x*x
|
||||
# s.t. x + y <= 1
|
||||
# x, y >= 0
|
||||
return linear_solver_pb2.MPModelProto(
|
||||
# Defaults are specified for the benefit of assertProto2Equal.
|
||||
maximize=False,
|
||||
objective_offset=0.0,
|
||||
variable=[
|
||||
linear_solver_pb2.MPVariableProto(lower_bound=0,
|
||||
upper_bound=np.inf,
|
||||
objective_coefficient=0,
|
||||
name='x'),
|
||||
linear_solver_pb2.MPVariableProto(lower_bound=0,
|
||||
upper_bound=np.inf,
|
||||
objective_coefficient=0,
|
||||
name='y')
|
||||
],
|
||||
constraint=[
|
||||
linear_solver_pb2.MPConstraintProto(var_index=[0, 1],
|
||||
coefficient=[1, 1],
|
||||
lower_bound=-np.inf,
|
||||
upper_bound=1)
|
||||
],
|
||||
quadratic_objective=linear_solver_pb2.MPQuadraticObjective(
|
||||
qvar1_index=[0], qvar2_index=[0], coefficient=[2]))
|
||||
|
||||
|
||||
class QuadraticProgramTest(absltest.TestCase):
|
||||
|
||||
def test_validate_quadratic_program_dimensions_for_empty_qp(self):
|
||||
qp = pywrap_pdlp.QuadraticProgram()
|
||||
qp.resize_and_initialize(3, 2)
|
||||
pywrap_pdlp.validate_quadratic_program_dimensions(qp)
|
||||
self.assertTrue(pywrap_pdlp.is_linear_program(qp))
|
||||
|
||||
def test_converts_from_tiny_mpmodel_lp(self):
|
||||
lp_proto = small_proto_lp()
|
||||
qp = pywrap_pdlp.qp_from_mpmodel_proto(lp_proto.SerializeToString(),
|
||||
relax_integer_variables=False)
|
||||
pywrap_pdlp.validate_quadratic_program_dimensions(qp)
|
||||
self.assertTrue(pywrap_pdlp.is_linear_program(qp))
|
||||
self.assertSameElements(qp.objective_vector, [0, -2])
|
||||
|
||||
def test_converts_from_tiny_mpmodel_qp(self):
|
||||
qp_proto = small_proto_qp()
|
||||
qp = pywrap_pdlp.qp_from_mpmodel_proto(qp_proto.SerializeToString(),
|
||||
relax_integer_variables=False)
|
||||
pywrap_pdlp.validate_quadratic_program_dimensions(qp)
|
||||
self.assertFalse(pywrap_pdlp.is_linear_program(qp))
|
||||
self.assertSameElements(qp.objective_vector, [0, 0])
|
||||
|
||||
def test_build_lp(self):
|
||||
qp = pywrap_pdlp.QuadraticProgram()
|
||||
qp.objective_vector = [0, -2]
|
||||
qp.constraint_matrix = scipy.sparse.csr_matrix(np.array([[1.0, 1.0]]))
|
||||
qp.constraint_lower_bounds = [-np.inf]
|
||||
qp.constraint_upper_bounds = [1.0]
|
||||
qp.variable_lower_bounds = [0.0, 0.0]
|
||||
qp.variable_upper_bounds = [np.inf, np.inf]
|
||||
qp.variable_names = ['x', 'y']
|
||||
self.assertEqual(
|
||||
linear_solver_pb2.MPModelProto.FromString(
|
||||
pywrap_pdlp.qp_to_mpmodel_proto(qp)), small_proto_lp())
|
||||
|
||||
def test_build_qp(self):
|
||||
qp = pywrap_pdlp.QuadraticProgram()
|
||||
qp.objective_vector = [0, 0]
|
||||
qp.constraint_matrix = scipy.sparse.csr_matrix(np.array([[1.0, 1.0]]))
|
||||
qp.set_objective_matrix_diagonal([4.0])
|
||||
qp.constraint_lower_bounds = [-np.inf]
|
||||
qp.constraint_upper_bounds = [1.0]
|
||||
qp.variable_lower_bounds = [0.0, 0.0]
|
||||
qp.variable_upper_bounds = [np.inf, np.inf]
|
||||
qp.variable_names = ['x', 'y']
|
||||
self.assertEqual(
|
||||
linear_solver_pb2.MPModelProto.FromString(
|
||||
pywrap_pdlp.qp_to_mpmodel_proto(qp)), small_proto_qp())
|
||||
|
||||
|
||||
def tiny_lp():
|
||||
"""Returns a small test LP.
|
||||
|
||||
The LP:
|
||||
min 5 x_1 + 2 x_2 + x_3 + x_4 - 14 s.t.
|
||||
2 x_1 + x_2 + x_3 + 2 x_4 = 12
|
||||
x_1 + x_3 >= 7
|
||||
x_3 - x_4 >= 1
|
||||
0 <= x_1 <= 2
|
||||
0 <= x_2 <= 4
|
||||
0 <= x_3 <= 6
|
||||
0 <= x_4 <= 3
|
||||
|
||||
Optimum solutions:
|
||||
Primal: x_1 = 1, x_2 = 0, x_3 = 6, x_4 = 2. Value: 5 + 0 + 6 + 2 - 14 = -1.
|
||||
Dual: [0.5, 4.0, 0.0] Value: 6 + 28 - 3.5*6 - 14 = -1
|
||||
Reduced costs: [0.0, 1.5, -3.5, 0.0]
|
||||
"""
|
||||
qp = pywrap_pdlp.QuadraticProgram()
|
||||
qp.objective_offset = -14
|
||||
qp.objective_vector = [5, 2, 1, 1]
|
||||
qp.constraint_lower_bounds = [12, 7, 1]
|
||||
qp.constraint_upper_bounds = [12, np.inf, np.inf]
|
||||
qp.variable_lower_bounds = np.zeros(4)
|
||||
qp.variable_upper_bounds = [2, 4, 6, 3]
|
||||
constraint_matrix = np.array([[2, 1, 1, 2], [1, 0, 1, 0], [0, 0, 1, -1]])
|
||||
qp.constraint_matrix = scipy.sparse.csr_matrix(constraint_matrix)
|
||||
return qp
|
||||
|
||||
|
||||
def test_lp():
|
||||
"""Returns a small LP with all 4 patterns lower and upper bounds.
|
||||
|
||||
min 5.5 x_0 - 2 x_1 - x_2 + x_3 - 14 s.t.
|
||||
2 x_0 + x_1 + x_2 + 2 x_3 = 12
|
||||
x_0 + x_2 <= 7
|
||||
4 x_0 >= -4
|
||||
-1 <= 1.5 x_2 - x_3 <= 1
|
||||
-infinity <= x_0 <= infinity
|
||||
-2 <= x_1 <= infinity
|
||||
-infinity <= x_2 <= 6
|
||||
2.5 <= x_3 <= 3.5
|
||||
|
||||
Optimal solutions:
|
||||
Primal: [-1, 8, 1, 2.5]
|
||||
Dual: [-2, 0, 2.375, 2.0/3]
|
||||
Value: -5.5 - 16 -1 + 2.5 - 14 = -34
|
||||
"""
|
||||
qp = pywrap_pdlp.QuadraticProgram()
|
||||
qp.objective_offset = -14
|
||||
qp.objective_vector = [5.5, -2, -1, 1]
|
||||
qp.constraint_lower_bounds = [12, -np.inf, -4, -1]
|
||||
qp.constraint_upper_bounds = [12, 7, np.inf, 1]
|
||||
qp.variable_lower_bounds = [-np.inf, -2, -np.inf, 2.5]
|
||||
qp.variable_upper_bounds = [np.inf, np.inf, 6, 3.5]
|
||||
constraint_matrix = np.array([[2, 1, 1, 2], [1, 0, 1, 0], [4, 0, 0, 0],
|
||||
[0, 0, 1.5, -1]])
|
||||
qp.constraint_matrix = scipy.sparse.csr_matrix(constraint_matrix)
|
||||
return qp
|
||||
|
||||
|
||||
class PrimalDualHybridGradientTest(absltest.TestCase):
|
||||
|
||||
def test_iteration_limit(self):
|
||||
params = solvers_pb2.PrimalDualHybridGradientParams()
|
||||
params.termination_criteria.iteration_limit = 1
|
||||
params.termination_check_frequency = 1
|
||||
result = pywrap_pdlp.primal_dual_hybrid_gradient(
|
||||
tiny_lp(), params.SerializeToString())
|
||||
solve_log = solve_log_pb2.SolveLog.FromString(result.solve_log_str)
|
||||
self.assertLessEqual(solve_log.iteration_count, 1)
|
||||
self.assertEqual(solve_log.termination_reason,
|
||||
solve_log_pb2.TERMINATION_REASON_ITERATION_LIMIT)
|
||||
|
||||
def test_solution(self):
|
||||
params = solvers_pb2.PrimalDualHybridGradientParams()
|
||||
opt_criteria = params.termination_criteria.simple_optimality_criteria
|
||||
opt_criteria.eps_optimal_relative = 0.0
|
||||
opt_criteria.eps_optimal_absolute = 1.0e-10
|
||||
result = pywrap_pdlp.primal_dual_hybrid_gradient(
|
||||
tiny_lp(), params.SerializeToString())
|
||||
solve_log = solve_log_pb2.SolveLog.FromString(result.solve_log_str)
|
||||
self.assertEqual(solve_log.termination_reason,
|
||||
solve_log_pb2.TERMINATION_REASON_OPTIMAL)
|
||||
self.assertSequenceAlmostEqual(result.primal_solution,
|
||||
[1.0, 0.0, 6.0, 2.0])
|
||||
self.assertSequenceAlmostEqual(result.dual_solution, [0.5, 4.0, 0.0])
|
||||
self.assertSequenceAlmostEqual(result.reduced_costs,
|
||||
[0.0, 1.5, -3.5, 0.0])
|
||||
|
||||
def test_solution_2(self):
|
||||
params = solvers_pb2.PrimalDualHybridGradientParams()
|
||||
opt_criteria = params.termination_criteria.simple_optimality_criteria
|
||||
opt_criteria.eps_optimal_relative = 0.0
|
||||
opt_criteria.eps_optimal_absolute = 1.0e-10
|
||||
result = pywrap_pdlp.primal_dual_hybrid_gradient(
|
||||
test_lp(), params.SerializeToString())
|
||||
solve_log = solve_log_pb2.SolveLog.FromString(result.solve_log_str)
|
||||
self.assertEqual(solve_log.termination_reason,
|
||||
solve_log_pb2.TERMINATION_REASON_OPTIMAL)
|
||||
self.assertSequenceAlmostEqual(result.primal_solution, [-1, 8, 1, 2.5])
|
||||
self.assertSequenceAlmostEqual(result.dual_solution,
|
||||
[-2, 0, 2.375, 2 / 3])
|
||||
|
||||
def test_starting_point(self):
|
||||
params = solvers_pb2.PrimalDualHybridGradientParams()
|
||||
opt_criteria = params.termination_criteria.simple_optimality_criteria
|
||||
opt_criteria.eps_optimal_relative = 0.0
|
||||
opt_criteria.eps_optimal_absolute = 1.0e-10
|
||||
params.l_inf_ruiz_iterations = 0
|
||||
params.l2_norm_rescaling = False
|
||||
|
||||
start = pywrap_pdlp.PrimalAndDualSolution()
|
||||
start.primal_solution = [1.0, 0.0, 6.0, 2.0]
|
||||
start.dual_solution = [0.5, 4.0, 0.0]
|
||||
result = pywrap_pdlp.primal_dual_hybrid_gradient(
|
||||
tiny_lp(), params.SerializeToString(), initial_solution=start)
|
||||
solve_log = solve_log_pb2.SolveLog.FromString(result.solve_log_str)
|
||||
self.assertEqual(solve_log.termination_reason,
|
||||
solve_log_pb2.TERMINATION_REASON_OPTIMAL)
|
||||
self.assertEqual(solve_log.iteration_count, 0)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
@@ -64,6 +64,7 @@ setup(
|
||||
'@PYTHON_PROJECT@.linear_solver.python':['$<TARGET_FILE_NAME:pywrap_model_builder_helper>', '*.pyi'],
|
||||
'@PYTHON_PROJECT@.packing':['*.pyi'],
|
||||
'@PYTHON_PROJECT@.pdlp':['*.pyi'],
|
||||
'@PYTHON_PROJECT@.pdlp.python':['$<TARGET_FILE_NAME:pywrap_pdlp_pybind11>'],
|
||||
'@PYTHON_PROJECT@.sat':['*.pyi'],
|
||||
'@PYTHON_PROJECT@.sat.python':['$<TARGET_FILE_NAME:swig_helper>', '*.pyi'],
|
||||
'@PYTHON_PROJECT@.scheduling':['$<TARGET_FILE_NAME:pywraprcpsp>', '*.pyi'],
|
||||
|
||||
Reference in New Issue
Block a user