|
| 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 | +// Minimal example for Getting Started. |
| 15 | +// [START imports] |
| 16 | +#include <iostream> |
| 17 | +#include <ostream> |
| 18 | + |
| 19 | +#include "absl/log/check.h" |
| 20 | +#include "absl/status/statusor.h" |
| 21 | +#include "ortools/base/init_google.h" |
| 22 | +#include "ortools/math_opt/cpp/math_opt.h" |
| 23 | +// [END imports] |
| 24 | + |
| 25 | +int main(int argc, char** argv) { |
| 26 | + InitGoogle(argv[0], &argc, &argv, true); |
| 27 | + |
| 28 | + // [START build_model] |
| 29 | + // Build the model. |
| 30 | + namespace math_opt = ::operations_research::math_opt; |
| 31 | + math_opt::Model lp_model("getting_started_lp"); |
| 32 | + const math_opt::Variable x = lp_model.AddContinuousVariable(-1.0, 1.5, "x"); |
| 33 | + const math_opt::Variable y = lp_model.AddContinuousVariable(0.0, 1.0, "y"); |
| 34 | + lp_model.AddLinearConstraint(x + y <= 1.5, "c"); |
| 35 | + lp_model.Maximize(x + 2 * y); |
| 36 | + // [END build_model] |
| 37 | + |
| 38 | + // [START solve_args] |
| 39 | + // Set parameters, e.g. turn on logging. |
| 40 | + math_opt::SolveArguments args; |
| 41 | + args.parameters.enable_output = true; |
| 42 | + // [END solve_args] |
| 43 | + |
| 44 | + // [START solve] |
| 45 | + // Solve and ensure an optimal solution was found with no errors. |
| 46 | + const absl::StatusOr<math_opt::SolveResult> result = |
| 47 | + math_opt::Solve(lp_model, math_opt::SolverType::kGlop, args); |
| 48 | + CHECK_OK(result.status()); |
| 49 | + CHECK_OK(result->termination.EnsureIsOptimal()); |
| 50 | + // [END solve] |
| 51 | + |
| 52 | + // [START print_result] |
| 53 | + // Print some information from the result. |
| 54 | + std::cout << "MathOpt solve succeeded" << std::endl; |
| 55 | + std::cout << "Objective value: " << result->objective_value() << std::endl; |
| 56 | + std::cout << "x: " << result->variable_values().at(x) << std::endl; |
| 57 | + std::cout << "y: " << result->variable_values().at(y) << std::endl; |
| 58 | + // [END print_result] |
| 59 | + |
| 60 | + return 0; |
| 61 | +} |
0 commit comments