Files
ortools-clone/ortools/math_opt/samples/cpp/basic_example.cc

65 lines
2.1 KiB
C++
Raw Permalink Normal View History

2025-01-10 11:35:44 +01:00
// Copyright 2010-2025 Google LLC
2021-04-11 12:05:38 +02:00
// 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.
// Testing correctness of the code snippets in the comments of math_opt.h.
#include <iostream>
#include <limits>
2023-07-13 20:22:58 +02:00
#include <ostream>
2021-04-11 12:05:38 +02:00
2022-03-02 22:10:23 +01:00
#include "absl/status/status.h"
2022-01-31 18:44:25 +01:00
#include "ortools/base/init_google.h"
2021-05-22 19:00:14 +02:00
#include "ortools/base/logging.h"
2022-03-02 22:10:23 +01:00
#include "ortools/base/status_macros.h"
2021-04-11 12:05:38 +02:00
#include "ortools/math_opt/cpp/math_opt.h"
namespace {
2022-03-02 22:10:23 +01:00
namespace math_opt = ::operations_research::math_opt;
2021-04-11 12:05:38 +02:00
// Model the problem:
// max 2.0 * x + y
// s.t. x + y <= 1.5
// x in {0.0, 1.0}
// y in [0.0, 2.5]
//
2022-03-02 22:10:23 +01:00
absl::Status Main() {
math_opt::Model model("my_model");
const math_opt::Variable x = model.AddBinaryVariable("x");
const math_opt::Variable y = model.AddContinuousVariable(0.0, 2.5, "y");
2021-04-11 12:05:38 +02:00
// We can directly use linear combinations of variables ...
2022-01-12 16:01:42 +01:00
model.AddLinearConstraint(x + y <= 1.5, "c");
2021-04-11 12:05:38 +02:00
// ... or build them incrementally.
2022-03-02 22:10:23 +01:00
math_opt::LinearExpression objective_expression;
2021-04-11 12:05:38 +02:00
objective_expression += 2 * x;
objective_expression += y;
2022-01-12 16:01:42 +01:00
model.Maximize(objective_expression);
2022-03-02 22:10:23 +01:00
ASSIGN_OR_RETURN(const math_opt::SolveResult result,
Solve(model, math_opt::SolverType::kGscip));
RETURN_IF_ERROR(result.termination.EnsureIsOptimalOrFeasible());
2023-07-13 20:22:58 +02:00
std::cout << "Objective value: " << result.objective_value() << std::endl
<< "Value for variable x: " << result.variable_values().at(x)
<< std::endl;
return absl::OkStatus();
2021-04-11 12:05:38 +02:00
}
} // namespace
int main(int argc, char** argv) {
2022-01-31 18:44:25 +01:00
InitGoogle(argv[0], &argc, &argv, true);
2022-03-02 22:10:23 +01:00
const absl::Status status = Main();
if (!status.ok()) {
LOG(QFATAL) << status;
}
2021-04-11 12:05:38 +02:00
return 0;
}