58#include "absl/flags/declare.h"
59#include "absl/flags/flag.h"
60#include "absl/status/status.h"
61#include "absl/status/statusor.h"
62#include "absl/strings/match.h"
63#include "absl/strings/str_cat.h"
64#include "absl/strings/str_format.h"
65#include "absl/time/time.h"
72#include "ortools/linear_solver/linear_solver.pb.h"
77#include "ortools/sat/cp_model.pb.h"
84 "Input file name with solution in .sol format.");
85ABSL_FLAG(std::optional<std::string>, solver, std::nullopt,
86 "The solver to use: bop, cbc, clp, glop, glpk_lp, glpk_mip, "
87 "gurobi_lp, gurobi_mip, pdlp, scip, knapsack, sat. If unspecified "
88 "either use MPModelRequest.solver_type if the --input is an "
89 "MPModelRequest and the field is set or use glop.");
91 "Number of threads to use by the underlying solver.");
93 "Solver specific parameters file. "
94 "If this flag is set, the --params flag is ignored.");
95ABSL_FLAG(std::string, params,
"",
"Solver specific parameters");
97 "It specifies a limit on the solving time. The duration must be must "
98 "be positive. It default to an infinite duration meaning that no "
99 "time limit will be imposed.");
101 "If non-empty, write the returned solution in csv format with "
102 "each line formed by a variable name and its value.");
105 "Format in which to dump protos (if flags --dump_model, "
106 "--dump_request, or --dump_response are used). Possible values: "
107 "'text', 'binary', 'json' which correspond to text proto format "
108 "binary proto format, and json. If 'binary' or 'json' are used, "
109 "we append '.bin' and '.json' to file names.");
111 "Whether to gzip dumped protos. Appends .gz to their name.");
113 "If non-empty, dumps MPModelProto there.");
115 "If non-empty, dumps MPModelRequest there.");
117 "If non-empty, dumps MPSolutionResponse there.");
119 "If non-empty, output the best solution in Miplib .sol format.");
121 "If non-empty, dumps the model in mps format there.");
125 log_verification_errors);
128 linear_solver_enable_verbose_output);
131 "Run MPSolver on the given input file. Many formats are supported: \n"
132 " - a .mps or .mps.gz file,\n"
133 " - an MPModelProto (binary or text, possibly gzipped),\n"
134 " - an MPModelRequest (binary or text, possibly gzipped).";
139MPModelRequest ReadMipModel(
const std::string&
input) {
140 MPModelRequest request_proto;
141 MPModelProto model_proto;
142 if (absl::EndsWith(
input,
".lp")) {
143#if defined(USE_LP_PARSER)
146 absl::StatusOr<MPModelProto> result = ModelProtoFromLpFormat(data);
148 model_proto = std::move(result).value();
150 LOG(FATAL) <<
"Support for parsing LP format is not compiled in.";
152 }
else if (absl::EndsWith(
input,
".mps") ||
153 absl::EndsWith(
input,
".mps.gz")) {
154 QCHECK_OK(glop::MPSReader().ParseFile(
input, &model_proto))
155 <<
"Error while parsing the mps file '" <<
input <<
"'.";
163 const bool is_model_proto = model_proto.variable_size() > 0;
164 const bool is_request_proto =
165 request_proto.model().variable_size() > 0 ||
166 !request_proto.model_delta().baseline_model_file_path().empty();
167 if (!is_model_proto && !is_request_proto) {
168 LOG(FATAL) <<
"Failed to parse '" <<
input
169 <<
"' as an MPModelProto or an MPModelRequest.";
171 CHECK(!(is_model_proto && is_request_proto));
173 if (is_request_proto) {
174 LOG(INFO) <<
"Read input proto as an MPModelRequest.";
176 LOG(INFO) <<
"Read input proto as an MPModelProto.";
177 model_proto.Swap(request_proto.mutable_model());
179 return request_proto;
182MPSolutionResponse LocalSolve(
const MPModelRequest& request_proto) {
186 MPSolver solver(request_proto.model().name(),
188 request_proto.solver_type()));
189 const absl::Status set_num_threads_status =
190 solver.SetNumThreads(absl::GetFlag(FLAGS_num_threads));
191 if (set_num_threads_status.ok()) {
192 LOG(INFO) <<
"Set number of threads to " << absl::GetFlag(FLAGS_num_threads)
194 }
else if (absl::GetFlag(FLAGS_num_threads) != 1) {
195 LOG(ERROR) <<
"Failed to set number of threads due to: "
196 << set_num_threads_status.message() <<
". Using 1 as default.";
198 solver.EnableOutput();
200 if (request_proto.has_solver_specific_parameters()) {
201 CHECK(solver.SetSolverSpecificParametersAsString(
202 request_proto.solver_specific_parameters()))
203 <<
"Wrong solver_specific_parameters (bad --params or --params_file ?)";
206 MPSolutionResponse response;
210 std::string error_message;
211 const MPSolverResponseStatus
status =
212 solver.LoadModelFromProtoWithUniqueNamesOrDie(request_proto.model(),
215 if (
status != MPSOLVER_MODEL_IS_VALID) {
218 if (request_proto.solver_type() ==
219 MPModelRequest::SAT_INTEGER_PROGRAMMING) {
220 sat::CpSolverResponse sat_response;
221 sat_response.set_status(sat::CpSolverStatus::MODEL_INVALID);
225 response.set_status(
status);
226 response.set_status_str(error_message);
230 if (request_proto.has_solver_time_limit_seconds()) {
232 absl::Seconds(request_proto.solver_time_limit_seconds()));
239 SigintHandler handler;
240 handler.Register([&solver] { solver.InterruptSolve(); });
248 !absl::GetFlag(FLAGS_verify_solution)) {
249 const bool verified =
250 solver.VerifySolution(MPSolverParameters().GetDoubleParam(
252 absl::GetFlag(FLAGS_log_verification_errors));
253 LOG(INFO) <<
"The solution "
254 << (verified ?
"was verified." :
"didn't pass verification.");
261 absl::PrintF(
"%-12s: %d\n",
"Nodes", solver.nodes());
265 solver.FillSolutionResponseProto(&response);
270 QCHECK(!absl::GetFlag(FLAGS_input).empty()) <<
"--input is required";
271 QCHECK_GE(absl::GetFlag(FLAGS_time_limit), absl::ZeroDuration())
272 <<
"--time_limit must be given a positive duration";
275 std::optional<MPSolver::OptimizationProblemType> type;
276 if (
const std::optional<std::string> type_flag = absl::GetFlag(FLAGS_solver);
277 type_flag.has_value()) {
280 <<
"Unsupported --solver: " << type_flag.value();
284 MPModelRequest request_proto = ReadMipModel(absl::GetFlag(FLAGS_input));
286 if (!absl::GetFlag(FLAGS_sol_hint).empty()) {
287 const auto read_sol =
288 ParseSolFile(absl::GetFlag(FLAGS_sol_hint), request_proto.model());
289 CHECK_OK(read_sol.status());
290 const MPSolutionResponse& sol = read_sol.value();
291 if (request_proto.model().has_solution_hint()) {
292 LOG(WARNING) <<
"Overwriting solution hint found in the request with "
293 <<
"solution from " << absl::GetFlag(FLAGS_sol_hint);
295 request_proto.mutable_model()->clear_solution_hint();
296 for (
int i = 0; i < sol.variable_value_size(); ++i) {
297 request_proto.mutable_model()->mutable_solution_hint()->add_var_index(i);
298 request_proto.mutable_model()->mutable_solution_hint()->add_var_value(
299 sol.variable_value(i));
303 printf(
"%-12s: '%s'\n",
"File", absl::GetFlag(FLAGS_input).c_str());
307 if (absl::GetFlag(FLAGS_dump_format) ==
"text") {
309 }
else if (absl::GetFlag(FLAGS_dump_format) ==
"binary") {
311 }
else if (absl::GetFlag(FLAGS_dump_format) ==
"json") {
314 LOG(FATAL) <<
"Unsupported --dump_format: "
315 << absl::GetFlag(FLAGS_dump_format);
318 if (!absl::GetFlag(FLAGS_dump_mps).empty()) {
320 request_proto.model()));
324 if (type.has_value() || !request_proto.has_solver_type()) {
325 request_proto.set_solver_type(
static_cast<MPModelRequest::SolverType
>(
328 if (absl::GetFlag(FLAGS_time_limit) != absl::InfiniteDuration()) {
329 LOG(INFO) <<
"Setting a time limit of " << absl::GetFlag(FLAGS_time_limit);
330 request_proto.set_solver_time_limit_seconds(
331 absl::ToDoubleSeconds(absl::GetFlag(FLAGS_time_limit)));
333 if (absl::GetFlag(FLAGS_linear_solver_enable_verbose_output)) {
334 request_proto.set_enable_internal_solver_output(
true);
336 if (!absl::GetFlag(FLAGS_params_file).empty()) {
337 CHECK(absl::GetFlag(FLAGS_params).empty())
338 <<
"--params and --params_file are incompatible";
339 std::string file_contents;
342 <<
"Could not read parameters file.";
343 request_proto.set_solver_specific_parameters(file_contents);
345 if (!absl::GetFlag(FLAGS_params).empty()) {
346 request_proto.set_solver_specific_parameters(absl::GetFlag(FLAGS_params));
350 if (!absl::GetFlag(FLAGS_dump_model).empty()) {
352 request_proto.model(), write_format,
353 absl::GetFlag(FLAGS_dump_gzip)));
355 if (!absl::GetFlag(FLAGS_dump_request).empty()) {
357 write_format, absl::GetFlag(FLAGS_dump_gzip)));
361 "%-12s: %s\n",
"Solver",
362 MPModelRequest::SolverType_Name(request_proto.solver_type()).c_str());
363 absl::PrintF(
"%-12s: %s\n",
"Parameters", absl::GetFlag(FLAGS_params));
364 absl::PrintF(
"%-12s: %d x %d\n",
"Dimension",
365 request_proto.model().constraint_size(),
366 request_proto.model().variable_size());
368 const absl::Time solve_start_time = absl::Now();
370 const MPSolutionResponse response = LocalSolve(request_proto);
372 const absl::Duration solving_time = absl::Now() - solve_start_time;
373 const bool has_solution = response.status() == MPSOLVER_OPTIMAL ||
374 response.status() == MPSOLVER_FEASIBLE;
375 absl::PrintF(
"%-12s: %s\n",
"Status",
376 MPSolverResponseStatus_Name(
377 static_cast<MPSolverResponseStatus
>(response.status()))
379 absl::PrintF(
"%-12s: %15.15e\n",
"Objective",
380 has_solution ? response.objective_value() : 0.0);
381 absl::PrintF(
"%-12s: %15.15e\n",
"BestBound",
382 has_solution ? response.best_objective_bound() : 0.0);
383 absl::PrintF(
"%-12s: %s\n",
"StatusString", response.status_str());
384 absl::PrintF(
"%-12s: %-6.4g s\n",
"Time",
385 absl::ToDoubleSeconds(solving_time));
389 if (!absl::GetFlag(FLAGS_sol_file).empty() && has_solution) {
390 std::string sol_string;
391 absl::StrAppend(&sol_string,
"=obj= ", response.objective_value(),
"\n");
392 for (
int i = 0; i < response.variable_value().
size(); ++i) {
393 absl::StrAppend(&sol_string, request_proto.model().variable(i).name(),
394 " ", response.variable_value(i),
"\n");
396 LOG(INFO) <<
"Writing .sol solution to '" << absl::GetFlag(FLAGS_sol_file)
401 if (!absl::GetFlag(FLAGS_dump_response).empty() && has_solution) {
403 write_format, absl::GetFlag(FLAGS_dump_gzip)));
405 if (!absl::GetFlag(FLAGS_output_csv).empty() && has_solution) {
406 std::string csv_file;
407 for (
int i = 0; i < response.variable_value_size(); ++i) {
409 absl::StrFormat(
"%s,%e\n", request_proto.model().variable(i).name(),
410 response.variable_value(i));
420int main(
int argc,
char** argv) {
422 operations_research::Run();
@ FEASIBLE
feasible, or stopped by limit.
@ GLOP_LINEAR_PROGRAMMING
static bool ParseSolverType(absl::string_view solver_id, OptimizationProblemType *type)
static
void InitGoogle(const char *usage, int *argc, char ***argv, bool deprecated)
ABSL_FLAG(std::string, sol_hint, "", "Input file name with solution in .sol format.")
int main(int argc, char **argv)
static const char kUsageStr[]
ABSL_DECLARE_FLAG(bool, verify_solution)
absl::StatusOr< std::string > GetContents(absl::string_view path, Options options)
absl::Status SetContents(absl::string_view filename, absl::string_view contents, Options options)
std::string CpSolverResponseStats(const CpSolverResponse &response, bool has_objective)
In SWIG mode, we don't want anything besides these top-level includes.
absl::Status WriteModelToMpsFile(absl::string_view filename, const MPModelProto &model, const MPModelExportOptions &options)
absl::StatusOr< glop::DenseRow > ParseSolFile(absl::string_view file_name, const glop::LinearProgram &model)
Parse a solution to model from a file.
bool SolverTypeIsMip(MPModelRequest::SolverType solver_type)
There is a homonymous version taking a MPSolver::OptimizationProblemType.
absl::Status WriteProtoToFile(absl::string_view filename, const google::protobuf::Message &proto, ProtoWriteFormat proto_write_format, bool gzipped, bool append_extension_to_file_name)
absl::Status ReadFileToProto(absl::string_view filename, google::protobuf::Message *proto, bool allow_partial)
static int input(yyscan_t yyscanner)