25#include "absl/base/attributes.h"
26#include "absl/cleanup/cleanup.h"
27#include "absl/log/check.h"
28#include "absl/status/status.h"
29#include "absl/status/statusor.h"
30#include "absl/strings/str_cat.h"
31#include "absl/strings/str_format.h"
32#include "absl/strings/str_join.h"
33#include "absl/strings/str_split.h"
34#include "absl/strings/string_view.h"
35#include "absl/time/clock.h"
36#include "absl/time/time.h"
37#include "absl/types/optional.h"
42#include "ortools/linear_solver/linear_solver.pb.h"
49constexpr int GRB_OK = 0;
51inline absl::Status GurobiCodeToUtilStatus(
int error_code,
52 const char* source_file,
54 const char* statement,
56 if (error_code == GRB_OK)
return absl::OkStatus();
57 return absl::InvalidArgumentError(absl::StrFormat(
58 "Gurobi error code %d (file '%s', line %d) on '%s': %s", error_code,
62int AddIndicatorConstraint(
const MPGeneralConstraintProto& gen_cst,
64 std::vector<int>* tmp_variables,
65 std::vector<double>* tmp_coefficients) {
66 CHECK(gurobi_model !=
nullptr);
67 CHECK(tmp_variables !=
nullptr);
68 CHECK(tmp_coefficients !=
nullptr);
70 const auto& ind_cst = gen_cst.indicator_constraint();
71 MPConstraintProto cst = ind_cst.constraint();
72 if (cst.lower_bound() > -std::numeric_limits<double>::infinity()) {
74 gurobi_model, gen_cst.name().c_str(), ind_cst.var_index(),
75 ind_cst.var_value(), cst.var_index_size(),
76 cst.mutable_var_index()->mutable_data(),
77 cst.mutable_coefficient()->mutable_data(),
82 if (cst.upper_bound() < std::numeric_limits<double>::infinity() &&
83 cst.lower_bound() != cst.upper_bound()) {
85 ind_cst.var_index(), ind_cst.var_value(),
87 cst.mutable_var_index()->mutable_data(),
88 cst.mutable_coefficient()->mutable_data(),
95int AddSosConstraint(
const MPSosConstraint& sos_cst,
GRBmodel* gurobi_model,
96 std::vector<int>* tmp_variables,
97 std::vector<double>* tmp_weights) {
98 CHECK(gurobi_model !=
nullptr);
99 CHECK(tmp_variables !=
nullptr);
100 CHECK(tmp_weights !=
nullptr);
102 tmp_variables->resize(sos_cst.var_index_size(), 0);
103 for (
int v = 0; v < sos_cst.var_index_size(); ++v) {
104 (*tmp_variables)[v] = sos_cst.var_index(v);
106 tmp_weights->resize(sos_cst.var_index_size(), 0);
107 if (sos_cst.weight_size() == sos_cst.var_index_size()) {
108 for (
int w = 0;
w < sos_cst.weight_size(); ++
w) {
109 (*tmp_weights)[
w] = sos_cst.weight(
w);
112 DCHECK_EQ(sos_cst.weight_size(), 0);
114 std::iota(tmp_weights->begin(), tmp_weights->end(), 1);
117 std::vector<int> types = {sos_cst.type() == MPSosConstraint::SOS1_DEFAULT
120 std::vector<int> begins = {0};
122 sos_cst.var_index_size(),
124 begins.data(), tmp_variables->data(),
125 tmp_weights->data());
128int AddQuadraticConstraint(
const MPGeneralConstraintProto& gen_cst,
130 CHECK(gurobi_model !=
nullptr);
131 constexpr double kInfinity = std::numeric_limits<double>::infinity();
133 CHECK(gen_cst.has_quadratic_constraint());
134 const MPQuadraticConstraint& quad_cst = gen_cst.quadratic_constraint();
136 auto addqconstr = [](
GRBmodel* gurobi_model, MPQuadraticConstraint quad_cst,
137 char sense,
double rhs,
const std::string&
name) {
140 quad_cst.var_index_size(),
141 quad_cst.mutable_var_index()->mutable_data(),
142 quad_cst.mutable_coefficient()->mutable_data(),
143 quad_cst.qvar1_index_size(),
144 quad_cst.mutable_qvar1_index()->mutable_data(),
145 quad_cst.mutable_qvar2_index()->mutable_data(),
146 quad_cst.mutable_qcoefficient()->mutable_data(),
152 if (quad_cst.has_lower_bound() && quad_cst.lower_bound() > -kInfinity) {
153 const int grb_status =
154 addqconstr(gurobi_model, gen_cst.quadratic_constraint(),
156 gen_cst.has_name() ? gen_cst.name() +
"_lb" :
"");
157 if (grb_status != GRB_OK)
return grb_status;
159 if (quad_cst.has_upper_bound() && quad_cst.upper_bound() < kInfinity) {
160 const int grb_status =
161 addqconstr(gurobi_model, gen_cst.quadratic_constraint(),
GRB_LESS_EQUAL,
162 quad_cst.upper_bound(),
163 gen_cst.has_name() ? gen_cst.name() +
"_ub" :
"");
164 if (grb_status != GRB_OK)
return grb_status;
170int AddAndConstraint(
const MPGeneralConstraintProto& gen_cst,
171 GRBmodel* gurobi_model, std::vector<int>* tmp_variables) {
172 CHECK(gurobi_model !=
nullptr);
173 CHECK(tmp_variables !=
nullptr);
175 auto and_cst = gen_cst.and_constraint();
178 gen_cst.name().c_str(),
179 and_cst.resultant_var_index(),
180 and_cst.var_index_size(),
181 and_cst.mutable_var_index()->mutable_data());
184int AddOrConstraint(
const MPGeneralConstraintProto& gen_cst,
185 GRBmodel* gurobi_model, std::vector<int>* tmp_variables) {
186 CHECK(gurobi_model !=
nullptr);
187 CHECK(tmp_variables !=
nullptr);
189 auto or_cst = gen_cst.or_constraint();
191 gen_cst.name().c_str(),
192 or_cst.resultant_var_index(),
193 or_cst.var_index_size(),
194 or_cst.mutable_var_index()->mutable_data());
197int AddMinConstraint(
const MPGeneralConstraintProto& gen_cst,
198 GRBmodel* gurobi_model, std::vector<int>* tmp_variables) {
199 CHECK(gurobi_model !=
nullptr);
200 CHECK(tmp_variables !=
nullptr);
202 auto min_cst = gen_cst.min_constraint();
205 gen_cst.name().c_str(),
206 min_cst.resultant_var_index(),
207 min_cst.var_index_size(),
208 min_cst.mutable_var_index()->mutable_data(),
209 min_cst.has_constant()
211 : std::numeric_limits<double>::infinity());
214int AddMaxConstraint(
const MPGeneralConstraintProto& gen_cst,
215 GRBmodel* gurobi_model, std::vector<int>* tmp_variables) {
216 CHECK(gurobi_model !=
nullptr);
217 CHECK(tmp_variables !=
nullptr);
219 auto max_cst = gen_cst.max_constraint();
222 gen_cst.name().c_str(),
223 max_cst.resultant_var_index(),
224 max_cst.var_index_size(),
225 max_cst.mutable_var_index()->mutable_data(),
226 max_cst.has_constant()
228 : -std::numeric_limits<double>::infinity());
234 if (
parameters.empty())
return absl::OkStatus();
235 std::vector<std::string> error_messages;
238 if (
line.empty())
continue;
241 if (
line[0] ==
'#')
continue;
242 for (absl::string_view token :
243 absl::StrSplit(
line,
',', absl::SkipWhitespace())) {
244 if (token.empty())
continue;
245 std::vector<std::string> key_value =
246 absl::StrSplit(token, absl::ByAnyChar(
" ="), absl::SkipWhitespace());
248 if (key_value.size() != 2) {
249 const std::string current_message =
250 absl::StrCat(
"Cannot parse parameter '", token,
251 "'. Expected format is 'ParameterName value' or "
252 "'ParameterName=value'");
253 error_messages.push_back(current_message);
256 const int gurobi_code =
258 if (gurobi_code != GRB_OK) {
259 const std::string current_message = absl::StrCat(
260 "Error setting parameter '", key_value[0],
"' to value '",
262 error_messages.push_back(current_message);
265 VLOG(2) << absl::StrCat(
"Set parameter '", key_value[0],
"' to value '",
270 if (error_messages.empty())
return absl::OkStatus();
271 return absl::InvalidArgumentError(absl::StrJoin(error_messages,
"\n"));
276 MPSolutionResponse response;
277 const absl::optional<LazyMutableCopy<MPModelProto>> optional_model =
279 if (!optional_model)
return response;
280 const MPModelProto&
model = **optional_model;
285 bool gurobi_env_was_created =
false;
286 auto gurobi_env_deleter = absl::MakeCleanup([&]() {
287 if (gurobi_env_was_created && gurobi_env !=
nullptr) {
291 if (gurobi_env ==
nullptr) {
293 gurobi_env_was_created =
true;
297 auto gurobi_model_deleter = absl::MakeCleanup([&]() {
299 LOG_IF(DFATAL, error_code != GRB_OK)
300 <<
"GRBfreemodel failed with error " << error_code <<
": "
305#define RETURN_IF_GUROBI_ERROR(x) \
307 GurobiCodeToUtilStatus(x, __FILE__, __LINE__, #x, gurobi_env));
310 model.name().c_str(),
321 request->enable_internal_solver_output()));
322 if (request->has_solver_specific_parameters()) {
324 request->solver_specific_parameters(), model_env);
325 if (!parameters_status.ok()) {
326 response.set_status(MPSOLVER_MODEL_INVALID_SOLVER_PARAMETERS);
327 response.set_status_str(
328 std::string(parameters_status.message()));
332 if (request->solver_time_limit_seconds() > 0) {
335 request->solver_time_limit_seconds()));
338 const int variable_size =
model.variable_size();
339 bool has_integer_variables =
false;
341 std::vector<double> obj_coeffs(variable_size, 0);
342 std::vector<double> lb(variable_size);
343 std::vector<double> ub(variable_size);
344 std::vector<char> ctype(variable_size);
345 std::vector<const char*> varnames(variable_size);
346 for (
int v = 0; v < variable_size; ++v) {
347 const MPVariableProto& variable =
model.variable(v);
348 obj_coeffs[v] = variable.objective_coefficient();
349 lb[v] = variable.lower_bound();
350 ub[v] = variable.upper_bound();
351 ctype[v] = variable.is_integer() &&
352 request->solver_type() ==
353 MPModelRequest::GUROBI_MIXED_INTEGER_PROGRAMMING
356 if (variable.is_integer()) has_integer_variables =
true;
357 if (!variable.name().empty()) varnames[v] = variable.name().c_str();
361 GRBaddvars(gurobi_model, variable_size, 0,
nullptr,
nullptr,
nullptr,
363 lb.data(), ub.data(), ctype.data(),
364 const_cast<char**
>(varnames.data())));
367 for (
int i = 0; i <
model.solution_hint().var_index_size(); ++i) {
370 model.solution_hint().var_value(i)));
375 std::vector<int> ct_variables;
376 std::vector<double> ct_coefficients;
377 for (
int c = 0; c <
model.constraint_size(); ++c) {
378 const MPConstraintProto& constraint =
model.constraint(c);
379 const int size = constraint.var_index_size();
380 ct_variables.resize(
size, 0);
381 ct_coefficients.resize(
size, 0);
382 for (
int i = 0; i <
size; ++i) {
383 ct_variables[i] = constraint.var_index(i);
384 ct_coefficients[i] = constraint.coefficient(i);
388 if (constraint.lower_bound() == constraint.upper_bound()) {
390 gurobi_model,
size, ct_variables.data(),
391 ct_coefficients.data(),
393 constraint.name().c_str()));
394 }
else if (constraint.lower_bound() ==
395 -std::numeric_limits<double>::infinity()) {
397 gurobi_model,
size, ct_variables.data(),
398 ct_coefficients.data(),
400 constraint.name().c_str()));
401 }
else if (constraint.upper_bound() ==
402 std::numeric_limits<double>::infinity()) {
404 gurobi_model,
size, ct_variables.data(),
405 ct_coefficients.data(),
407 constraint.name().c_str()));
410 gurobi_model,
size, ct_variables.data(),
411 ct_coefficients.data(),
412 constraint.lower_bound(),
413 constraint.upper_bound(),
414 constraint.name().c_str()));
418 for (
const auto& gen_cst :
model.general_constraint()) {
419 switch (gen_cst.general_constraint_case()) {
420 case MPGeneralConstraintProto::kIndicatorConstraint: {
422 gen_cst, gurobi_model, &ct_variables, &ct_coefficients));
425 case MPGeneralConstraintProto::kSosConstraint: {
427 gurobi_model, &ct_variables,
431 case MPGeneralConstraintProto::kQuadraticConstraint: {
435 case MPGeneralConstraintProto::kAbsConstraint: {
438 gen_cst.name().c_str(),
439 gen_cst.abs_constraint().resultant_var_index(),
440 gen_cst.abs_constraint().var_index()));
443 case MPGeneralConstraintProto::kAndConstraint: {
445 AddAndConstraint(gen_cst, gurobi_model, &ct_variables));
448 case MPGeneralConstraintProto::kOrConstraint: {
450 AddOrConstraint(gen_cst, gurobi_model, &ct_variables));
453 case MPGeneralConstraintProto::kMinConstraint: {
455 AddMinConstraint(gen_cst, gurobi_model, &ct_variables));
458 case MPGeneralConstraintProto::kMaxConstraint: {
460 AddMaxConstraint(gen_cst, gurobi_model, &ct_variables));
464 return absl::UnimplementedError(
465 absl::StrFormat(
"General constraints of type %i not supported.",
466 gen_cst.general_constraint_case()));
472 model.maximize() ? -1 : 1));
474 model.objective_offset()));
475 if (
model.has_quadratic_objective()) {
476 MPQuadraticObjective qobj =
model.quadratic_objective();
477 if (qobj.coefficient_size() > 0) {
480 qobj.mutable_qvar1_index()->mutable_data(),
481 qobj.mutable_qvar2_index()->mutable_data(),
482 qobj.mutable_coefficient()->mutable_data()));
488 const absl::Time time_before = absl::Now();
494 const absl::Duration solving_duration = absl::Now() - time_before;
496 VLOG(1) <<
"Finished solving in GurobiSolveProto(), walltime = "
497 << solving_duration <<
", usertime = " << user_timer.
GetDuration();
498 response.mutable_solve_info()->set_solve_wall_time_seconds(
499 absl::ToDoubleSeconds(solving_duration));
500 response.mutable_solve_info()->set_solve_user_time_seconds(
503 int optimization_status = 0;
506 int solution_count = 0;
509 switch (optimization_status) {
511 response.set_status(MPSOLVER_OPTIMAL);
514 DLOG(INFO) <<
"Gurobi solve returned GRB_INF_OR_UNBD, which we treat as "
515 "INFEASIBLE even though it may mean UNBOUNDED.";
516 response.set_status_str(
517 "The model may actually be unbounded: Gurobi returned "
519 ABSL_FALLTHROUGH_INTENDED;
521 response.set_status(MPSOLVER_INFEASIBLE);
524 response.set_status(MPSOLVER_UNBOUNDED);
527 if (solution_count > 0) {
528 response.set_status(MPSOLVER_FEASIBLE);
530 response.set_status(MPSOLVER_NOT_SOLVED);
531 response.set_status_str(
532 absl::StrFormat(
"Gurobi status code %d", optimization_status));
538 if (solution_count > 0 && (response.status() == MPSOLVER_FEASIBLE ||
539 response.status() == MPSOLVER_OPTIMAL)) {
544 double best_objective_bound = 0;
546 &best_objective_bound);
547 if (response.status() == MPSOLVER_OPTIMAL &&
553 response.set_best_objective_bound(best_objective_bound);
556 response.mutable_variable_value()->Resize(variable_size, 0);
559 response.mutable_variable_value()->mutable_data()));
563 auto round_values_of_integer_variables_fn =
564 [&](google::protobuf::RepeatedField<double>* values) {
565 for (
int v = 0; v < variable_size; ++v) {
566 if (
model.variable(v).is_integer()) {
567 (*values)[v] = std::round((*values)[v]);
571 round_values_of_integer_variables_fn(response.mutable_variable_value());
572 if (!has_integer_variables &&
model.general_constraint_size() == 0) {
573 response.mutable_dual_value()->Resize(
model.constraint_size(), 0);
576 response.mutable_dual_value()->mutable_data()));
578 const int additional_solutions = std::min(
579 solution_count, std::min(request->populate_additional_solutions_up_to(),
580 std::numeric_limits<int32_t>::max() - 1) +
582 for (
int i = 1; i < additional_solutions; ++i) {
585 MPSolution*
solution = response.add_additional_solutions();
586 solution->mutable_variable_value()->Resize(variable_size, 0);
593 solution->mutable_variable_value()->mutable_data()));
594 round_values_of_integer_variables_fn(
solution->mutable_variable_value());
597#undef RETURN_IF_GUROBI_ERROR
#define ASSIGN_OR_RETURN(lhs, rexpr)
absl::Duration GetDuration() const
void Start()
When Start() is called multiple times, only the most recent is used.
const std::string name
A name for logging purposes.
#define GRB_DBL_ATTR_START
#define GRB_ERROR_DATA_NOT_AVAILABLE
#define GRB_INT_ATTR_MODELSENSE
#define GRB_GREATER_EQUAL
#define GRB_DBL_ATTR_OBJVAL
struct _GRBmodel GRBmodel
#define GRB_DBL_ATTR_OBJCON
#define GRB_INT_ATTR_STATUS
#define GRB_DBL_ATTR_POOLOBJVAL
#define GRB_INT_PAR_SOLUTIONNUMBER
#define GRB_INT_ATTR_SOLCOUNT
#define GRB_INT_PAR_OUTPUTFLAG
#define GRB_DBL_PAR_TIMELIMIT
#define GRB_DBL_ATTR_OBJBOUND
#define RETURN_IF_GUROBI_ERROR(x)
In SWIG mode, we don't want anything besides these top-level includes.
std::function< int(GRBmodel *model, int numnz, int *cind, double *cval, char sense, double rhs, const char *constrname)> GRBaddconstr
std::function< void(GRBenv *env)> GRBfreeenv
std::function< int(GRBmodel *model, const char *attrname, double *valueP)> GRBgetdblattr
std::function< int(GRBmodel *model, const char *attrname, int first, int len, double *values)> GRBgetdblattrarray
std::function< int(GRBmodel *model, const char *attrname, double newvalue)> GRBsetdblattr
std::function< int(GRBmodel *model, int numvars, int numnz, int *vbeg, int *vind, double *vval, double *obj, double *lb, double *ub, char *vtype, char **varnames)> GRBaddvars
std::function< int(GRBmodel *model, int numlnz, int *lind, double *lval, int numqnz, int *qrow, int *qcol, double *qval, char sense, double rhs, const char *QCname)> GRBaddqconstr
std::function< int(GRBmodel *model, const char *attrname, int newvalue)> GRBsetintattr
std::function< int(GRBenv *env, const char *paramname, const char *value)> GRBsetparam
std::function< int(GRBenv *env, GRBmodel **modelP, const char *Pname, int numvars, double *obj, double *lb, double *ub, char *vtype, char **varnames)> GRBnewmodel
std::function< int(GRBmodel *model)> GRBupdatemodel
std::function< GRBenv *(GRBmodel *model)> GRBgetenv
std::function< int(GRBmodel *model)> GRBfreemodel
std::function< int(GRBenv *env, const char *paramname, int value)> GRBsetintparam
std::function< int(GRBmodel *model, const char *name, int resvar, int nvars, const int *vars, double constant)> GRBaddgenconstrMin
std::function< int(GRBmodel *model, int numnz, int *cind, double *cval, double lower, double upper, const char *constrname)> GRBaddrangeconstr
absl::StatusOr< MPSolutionResponse > GurobiSolveProto(LazyMutableCopy< MPModelRequest > request, GRBenv *gurobi_env)
std::function< int(GRBmodel *model, const char *name, int binvar, int binval, int nvars, const int *vars, const double *vals, char sense, double rhs)> GRBaddgenconstrIndicator
std::optional< LazyMutableCopy< MPModelProto > > GetMPModelOrPopulateResponse(LazyMutableCopy< MPModelRequest > &request, MPSolutionResponse *response)
std::function< int(GRBmodel *model)> GRBoptimize
std::function< int(GRBmodel *model, int numqnz, int *qrow, int *qcol, double *qval)> GRBaddqpterms
std::function< int(GRBmodel *model, const char *name, int resvar, int argvar)> GRBaddgenconstrAbs
std::function< int(GRBmodel *model, const char *attrname, int *valueP)> GRBgetintattr
std::function< const char *(GRBenv *env)> GRBgeterrormsg
absl::StatusOr< GRBenv * > GetGurobiEnv()
std::function< int(GRBmodel *model, const char *name, int resvar, int nvars, const int *vars)> GRBaddgenconstrAnd
std::function< int(GRBmodel *model, const char *name, int resvar, int nvars, const int *vars)> GRBaddgenconstrOr
std::function< int(GRBmodel *model, const char *name, int resvar, int nvars, const int *vars, double constant)> GRBaddgenconstrMax
std::function< int(GRBmodel *model, int numsos, int nummembers, int *types, int *beg, int *ind, double *weight)> GRBaddsos
absl::Status SetSolverSpecificParameters(absl::string_view parameters, GRBenv *gurobi)
std::function< int(GRBenv *env, const char *paramname, double value)> GRBsetdblparam
std::function< int(GRBmodel *model, const char *attrname, int element, double newvalue)> GRBsetdblattrelement
trees with all degrees equal w the current value of w
double objective_value
The value objective_vector^T * (solution - center_point).