OR-Tools  9.6
basic_example_mo.cc
Go to the documentation of this file.
1 // Copyright 2010-2022 Google LLC
2 // Licensed under the Apache License, Version 2.0 (the "License");
3 // you may not use this file except in compliance with the License.
4 // You may obtain a copy of the License at
5 //
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13 
14 // Testing correctness of the code snippets in the comments of math_opt.h.
15 
16 #include <iostream>
17 #include <limits>
18 
19 #include "absl/status/status.h"
20 #include "absl/status/statusor.h"
22 #include "ortools/base/logging.h"
26 
27 namespace {
28 
29 namespace math_opt = ::operations_research::math_opt;
30 
31 // Model the problem:
32 // max 2.0 * x + y
33 // s.t. x + y <= 1.5
34 // x in {0.0, 1.0}
35 // y in [0.0, 2.5]
36 //
37 absl::Status Main() {
38  math_opt::Model model("my_model");
39  const math_opt::Variable x = model.AddBinaryVariable("x");
40  const math_opt::Variable y = model.AddContinuousVariable(0.0, 2.5, "y");
41  // We can directly use linear combinations of variables ...
42  model.AddLinearConstraint(x + y <= 1.5, "c");
43  // ... or build them incrementally.
44  math_opt::LinearExpression objective_expression;
45  objective_expression += 2 * x;
46  objective_expression += y;
47  model.Maximize(objective_expression);
49  Solve(model, math_opt::SolverType::kGscip));
50  switch (result.termination.reason) {
51  case math_opt::TerminationReason::kOptimal:
52  case math_opt::TerminationReason::kFeasible:
53  std::cout << "Objective value: " << result.objective_value() << std::endl
54  << "Value for variable x: " << result.variable_values().at(x)
55  << std::endl;
56  return absl::OkStatus();
57  default:
59  << "model failed to solve: " << result.termination;
60  }
61 }
62 } // namespace
63 
64 int main(int argc, char** argv) {
65  InitGoogle(argv[0], &argc, &argv, true);
66  const absl::Status status = Main();
67  if (!status.ok()) {
68  LOG(QFATAL) << status;
69  }
70  return 0;
71 }
#define ASSIGN_OR_RETURN(lhs, rexpr)
int main(int argc, char **argv)
absl::Status status
Definition: g_gurobi.cc:41
GRBmodel * model
void InitGoogle(const char *usage, int *argc, char ***argv, bool deprecated)
Definition: init_google.h:34
absl::StatusOr< SolveResult > Solve(const Model &model, const SolverType solver_type, const SolveArguments &solve_args, const SolverInitArguments &init_args)
StatusBuilder InternalErrorBuilder()
const VariableMap< double > & variable_values() const