Sử dụng bộ sưu tập để sắp xếp ngăn nắp các trang
Lưu và phân loại nội dung dựa trên lựa chọn ưu tiên của bạn.
Ví dụ này cho thấy cách xây dựng, giải quyết và khám phá kết quả của một chương trình tuyến tính (LP) đơn giản bằng cách sử dụng MathOpt. Thông tin về cách cài đặt OR-Tools có trong hướng dẫn cài đặt. Các ghi chú bổ sung về cách tạo và chạy từ nguồn sẽ được trì hoãn đến cuối.
Xây dựng mô hình MathOpt
Trong nguồn của mình, thông thường, bạn chỉ cần thêm một phần phụ thuộc MathOpt:
Bài toán lập trình tuyến tính sau đây được dùng xuyên suốt hướng dẫn này và được giải bằng GLOP.
$$\begin{aligned}
&\max &x + 2 \cdot y\\
&\text{subject to} &x + y &\leq 1.5 \\
&&-1 \leq x &\leq 1.5 \\
&&0 \leq y &\leq 1
\end{aligned}$$
Trước tiên, hãy xây dựng mô hình:
Python
# Build the model.
model = mathopt.Model(name="getting_started_lp")
x = model.add_variable(lb=-1.0, ub=1.5, name="x")
y = model.add_variable(lb=0.0, ub=1.0, name="y")
model.add_linear_constraint(x + y <= 1.5)
model.maximize(x + 2 * y)
C++
// Build the model.
namespace math_opt = ::operations_research::math_opt;
math_opt::Model lp_model("getting_started_lp");
const math_opt::Variable x = lp_model.AddContinuousVariable(-1.0, 1.5, "x");
const math_opt::Variable y = lp_model.AddContinuousVariable(0.0, 1.0, "y");
lp_model.AddLinearConstraint(x + y <= 1.5, "c");
lp_model.Maximize(x + 2 * y);
Giải bài tập và kiểm tra giải pháp
Tiếp theo, hãy đặt các tham số cho phương thức giải. Việc giải quyết các mô hình tối ưu hoá bằng MathOpt có thể định cấu hình cao. Có các tham số độc lập với trình giải (ví dụ: kích hoạt đầu ra), tham số dành riêng cho trình giải toán (ví dụ: GlopParameters.optimization_quy tắc), các tham số phụ thuộc vào thuộc tính của mô hình (ví dụ: mức độ ưu tiên phân nhánh), lệnh gọi lại cho nhật ký trình giải toán và một lệnh gọi lại để theo dõi và kiểm soát quá trình tối ưu hoá. Mã sau đây sẽ bật nhật ký của trình giải.
Python
# Set parameters, e.g. turn on logging.
params = mathopt.SolveParameters(enable_output=True)
C++
// Set parameters, e.g. turn on logging.
math_opt::SolveArguments args;
args.parameters.enable_output = true;
Để giải bài toán này bằng GLOP, trình giải LP dựa trên đơn giản của Google, hãy dùng hàm Solve().
Python
# Solve and ensure an optimal solution was found with no errors.
# (mathopt.solve may raise a RuntimeError on invalid input or internal solver
# errors.)
result = mathopt.solve(model, mathopt.SolverType.GLOP, params=params)
if result.termination.reason != mathopt.TerminationReason.OPTIMAL:
raise RuntimeError(f"model failed to solve: {result.termination}")
C++
// Solve and ensure an optimal solution was found with no errors.
const absl::StatusOr<math_opt::SolveResult> result =
math_opt::Solve(lp_model, math_opt::SolverType::kGlop, args);
CHECK_OK(result.status());
CHECK_OK(result->termination.EnsureIsOptimal());
Cuối cùng, hãy kiểm tra giá trị mục tiêu của giải pháp tối ưu và các giá trị biến tối ưu. Xin lưu ý rằng vì lý do chấm dứt là tối ưu, nên bạn có thể giả định các giá trị này tồn tại, nhưng vì các lý do chấm dứt khác (ví dụ: không khả thi hoặc không bị ràng buộc), lệnh gọi các phương thức này có thể CHECK fail (trong C++) hoặc raise an exception (trong Python).
Python
# Print some information from the result.
print("MathOpt solve succeeded")
print("Objective value:", result.objective_value())
print("x:", result.variable_values()[x])
print("y:", result.variable_values()[y])
C++
// Print some information from the result.
std::cout << "MathOpt solve succeeded" << std::endl;
std::cout << "Objective value: " << result->objective_value() << std::endl;
std::cout << "x: " << result->variable_values().at(x) << std::endl;
std::cout << "y: " << result->variable_values().at(y) << std::endl;
Lưu ý về việc xây dựng và chạy mã bằng Bazel
Nếu bạn đang tạo MathOpt từ nguồn bằng cách sử dụng bazel, thì ví dụ này cần các phần phụ thuộc sau trong mục tiêu bản dựng:
[null,null,["Cập nhật lần gần đây nhất: 2024-08-08 UTC."],[[["\u003cp\u003eThis guide demonstrates how to build, solve, and analyze a simple linear program (LP) using MathOpt, Google's optimization modeling library.\u003c/p\u003e\n"],["\u003cp\u003eThe example uses GLOP, Google's simplex-based LP solver, to find the optimal solution for a given problem with constraints.\u003c/p\u003e\n"],["\u003cp\u003eThe guide provides code snippets in both Python and C++ for model building, parameter setting, solving the LP, and inspecting the results.\u003c/p\u003e\n"],["\u003cp\u003eBuilding MathOpt from source using Bazel requires specific dependencies to be included in the build target for both Python and C++ projects.\u003c/p\u003e\n"],["\u003cp\u003eWhen building with Bazel, ensure the GLOP solver is enabled using build flags, and consider disabling unused solvers for smaller binaries.\u003c/p\u003e\n"]]],["The core process involves building a linear programming (LP) model, solving it, and inspecting the results using MathOpt. First, a model is built by defining variables (x, y) with bounds and adding a linear constraint. Next, solver parameters are set, and the model is solved using GLOP. Finally, the solution's objective value and variable values are retrieved and printed. When using Bazel to build the source code, MathOpt and Glop dependencies must be added to the build target.\n"],null,["# Getting Started\n\nThis example shows how to build, solve, and explore the results of a simple\nlinear program (LP) using MathOpt. Information about installing OR-Tools is\navailable in the [install guide](/optimization/install). Additional notes on how to build and run\nfrom [source](https://github.com/google/or-tools/tree/stable/ortools/math_opt) are deferred to the end.\n\nBuild a MathOpt model\n---------------------\n\nIn your source, you typically *only* need to add a single MathOpt dependency: \n\n### Python\n\n```python\nfrom ortools.math_opt.python import mathopt\n```\n\n### C++\n\n```c++\n#include \u003ciostream\u003e\n#include \u003costream\u003e\n\n#include \"absl/log/check.h\"\n#include \"absl/status/statusor.h\"\n#include \"ortools/base/init_google.h\"\n#include \"ortools/math_opt/cpp/math_opt.h\"\n```\n\nThe following linear programming problem is used throughout this guide, and it\nis solved with GLOP. \n$$\\\\begin{aligned} \\&\\\\max \\&x + 2 \\\\cdot y\\\\\\\\ \\&\\\\text{subject to} \\&x + y \\&\\\\leq 1.5 \\\\\\\\ \\&\\&-1 \\\\leq x \\&\\\\leq 1.5 \\\\\\\\ \\&\\&0 \\\\leq y \\&\\\\leq 1 \\\\end{aligned}$$\n\nFirst, build the model: \n\n### Python\n\n```python\n# Build the model.\nmodel = mathopt.Model(name=\"getting_started_lp\")\nx = model.add_variable(lb=-1.0, ub=1.5, name=\"x\")\ny = model.add_variable(lb=0.0, ub=1.0, name=\"y\")\nmodel.add_linear_constraint(x + y \u003c= 1.5)\nmodel.maximize(x + 2 * y)\n```\n\n### C++\n\n```c++\n// Build the model.\nnamespace math_opt = ::operations_research::math_opt;\nmath_opt::Model lp_model(\"getting_started_lp\");\nconst math_opt::Variable x = lp_model.AddContinuousVariable(-1.0, 1.5, \"x\");\nconst math_opt::Variable y = lp_model.AddContinuousVariable(0.0, 1.0, \"y\");\nlp_model.AddLinearConstraint(x + y \u003c= 1.5, \"c\");\nlp_model.Maximize(x + 2 * y);\n```\n\nSolve and inspect the solution\n------------------------------\n\nNext, set the parameters for the solve. Solving optimization models with MathOpt\nis highly configurable. There are solver-independent parameters (e.g. enable\noutput), solver-specific parameters (e.g. GlopParameters.optimization_rule),\nparameters that depend on properties of the model (e.g. branching priority), a\ncallback for the solver logs, and a callback to monitor and control the\noptimization. The following code turns the solver logs on. \n\n### Python\n\n```python\n# Set parameters, e.g. turn on logging.\nparams = mathopt.SolveParameters(enable_output=True)\n```\n\n### C++\n\n```c++\n// Set parameters, e.g. turn on logging.\nmath_opt::SolveArguments args;\nargs.parameters.enable_output = true;\n```\n\nTo solve the problem using GLOP, Google's simplex-based LP solver, use the\n`Solve()` function. \n\n### Python\n\n```python\n# Solve and ensure an optimal solution was found with no errors.\n# (mathopt.solve may raise a RuntimeError on invalid input or internal solver\n# errors.)\nresult = mathopt.solve(model, mathopt.SolverType.GLOP, params=params)\nif result.termination.reason != mathopt.TerminationReason.OPTIMAL:\n raise RuntimeError(f\"model failed to solve: {result.termination}\")\n```\n\n### C++\n\n```c++\n// Solve and ensure an optimal solution was found with no errors.\nconst absl::StatusOr\u003cmath_opt::SolveResult\u003e result =\n math_opt::Solve(lp_model, math_opt::SolverType::kGlop, args);\nCHECK_OK(result.status());\nCHECK_OK(result-\u003etermination.EnsureIsOptimal());\n```\n\nLast, inspect the objective value of the optimal solution and the optimal\nvariable values. Note that because the termination reason was optimal, it is\nsafe to assume these values exist, but for other termination reasons (for\nexample, infeasible or unbounded) calling these methods can `CHECK fail` (in\nC++) or `raise an exception` (in Python). \n\n### Python\n\n```python\n# Print some information from the result.\nprint(\"MathOpt solve succeeded\")\nprint(\"Objective value:\", result.objective_value())\nprint(\"x:\", result.variable_values()[x])\nprint(\"y:\", result.variable_values()[y])\n```\n\n### C++\n\n```c++\n// Print some information from the result.\nstd::cout \u003c\u003c \"MathOpt solve succeeded\" \u003c\u003c std::endl;\nstd::cout \u003c\u003c \"Objective value: \" \u003c\u003c result-\u003eobjective_value() \u003c\u003c std::endl;\nstd::cout \u003c\u003c \"x: \" \u003c\u003c result-\u003evariable_values().at(x) \u003c\u003c std::endl;\nstd::cout \u003c\u003c \"y: \" \u003c\u003c result-\u003evariable_values().at(y) \u003c\u003c std::endl;\n```\n\nNotes on building and running your code with **Bazel**\n------------------------------------------------------\n\nIf you are building MathOpt from source using\n[bazel](https://bazel.build/), this example needs the following\ndependencies in the build target: \n\n### Python\n\n```python\n\"//util/operations_research/math_opt/python:mathopt\"\n```\n\n### C++\n\n```c++\n\"//util/operations_research/math_opt/cpp:math_opt\"\n\"//util/operations_research/math_opt/solvers:glop_solver\"\n```\n| **Note:** If you are using Python, you need to pass the flag `--with_glop=true` when building your target so that the solver is compiled. By default, many of the solvers in OR-Tools are enabled. We recommend disabling the solvers you are not using to get smaller binaries and avoid unnecessary dependencies. For example, you can also pass the flags `--with_scip=false --with_cp_sat=false\n| --with_glpk=false --with_glop=true`.\n\nTo run your code, the following bazel command builds and runs your target. \n\n### Python\n\n```python\nbazel run path/to/you:target --with_scip=false --with_cp_sat=false\n--with_glpk=false --with_glop=true -- --your_flags\n```\n\n### C++\n\n```c++\nbazel run path/to/you:target -- --your_flags\n```"]]