Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
solve_impl.cc
Go to the documentation of this file.
1// Copyright 2010-2024 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
15
16#include <memory>
17#include <optional>
18#include <utility>
19
20#include "absl/functional/any_invocable.h"
21#include "absl/log/check.h"
22#include "absl/memory/memory.h"
23#include "absl/status/status.h"
24#include "absl/status/statusor.h"
25#include "absl/synchronization/mutex.h"
39
41namespace {
42
43absl::StatusOr<SolveResult> CallSolve(
44 BaseSolver& solver, const ModelStorage* const expected_storage,
45 const SolveArguments& arguments, SolveInterrupter& local_canceller) {
46 RETURN_IF_ERROR(arguments.CheckModelStorageAndCallback(expected_storage));
47
48 BaseSolver::Callback cb = nullptr;
49 absl::Mutex mutex;
50 absl::Status cb_status; // Guarded by `mutex`.
51 if (arguments.callback != nullptr) {
52 cb = [&](const CallbackDataProto& callback_data_proto) {
53 const CallbackData data(expected_storage, callback_data_proto);
54 const CallbackResult result = arguments.callback(data);
55 if (const absl::Status status =
56 result.CheckModelStorage(expected_storage);
57 !status.ok()) {
58 // Note that we use util::StatusBuilder() here as util::Annotate() is
59 // not available in open-source code.
61 builder << "invalid CallbackResult returned by user callback";
62
63 { // Limit `lock` scope.
64 const absl::MutexLock lock(&mutex);
65 cb_status.Update(builder);
66 }
67
68 // Trigger subprocess cancellation.
69 local_canceller.Interrupt();
70
71 // Trigger early termination of the solve if cancellation is not
72 // supported (i.e. in in-process solve).
73 CallbackResultProto result_proto;
74 result_proto.set_terminate(true);
75 return result_proto;
76 }
77 return result.Proto();
78 };
79 }
80
81 const absl::StatusOr<SolveResultProto> solve_result_proto = solver.Solve(
82 {.parameters = arguments.parameters.Proto(),
83 .model_parameters = arguments.model_parameters.Proto(),
84 .message_callback = arguments.message_callback,
85 .callback_registration = arguments.callback_registration.Proto(),
86 .user_cb = std::move(cb),
87 .interrupter = arguments.interrupter});
88
89 // solver.Solve() returns an error on cancellation by local_canceller but in
90 // that case we want to ignore this error and return status generated in the
91 // callback instead.
92 { // Limit `lock` scope.
93 const absl::MutexLock lock(&mutex);
94 RETURN_IF_ERROR(cb_status);
95 }
96
97 if (!solve_result_proto.ok()) {
98 return solve_result_proto.status();
99 }
100
101 return SolveResult::FromProto(expected_storage, solve_result_proto.value());
102}
103
104absl::StatusOr<ComputeInfeasibleSubsystemResult> CallComputeInfeasibleSubsystem(
105 BaseSolver& solver, const ModelStorage* const expected_storage,
106 const ComputeInfeasibleSubsystemArguments& arguments,
107 SolveInterrupter& local_canceller) {
109 const ComputeInfeasibleSubsystemResultProto compute_result_proto,
110 solver.ComputeInfeasibleSubsystem(
111 {.parameters = arguments.parameters.Proto(),
112 .message_callback = arguments.message_callback,
113 .interrupter = arguments.interrupter}));
114
115 return ComputeInfeasibleSubsystemResult::FromProto(expected_storage,
116 compute_result_proto);
117}
118
119} // namespace
120
121absl::StatusOr<SolveResult> SolveImpl(
122 const BaseSolverFactory solver_factory, const Model& model,
123 const SolverType solver_type, const SolveArguments& solve_args,
124 const SolveInterrupter* const user_canceller, const bool remove_names) {
125 SolveInterrupter local_canceller;
126 const ScopedSolveInterrupterCallback user_canceller_cb(
127 user_canceller, [&]() { local_canceller.Interrupt(); });
129 const std::unique_ptr<BaseSolver> solver,
130 solver_factory(EnumToProto(solver_type), model.ExportModel(remove_names),
131 &local_canceller));
132 return CallSolve(*solver, model.storage(), solve_args, local_canceller);
133}
134
135absl::StatusOr<ComputeInfeasibleSubsystemResult> ComputeInfeasibleSubsystemImpl(
136 const BaseSolverFactory solver_factory, const Model& model,
137 const SolverType solver_type,
138 const ComputeInfeasibleSubsystemArguments& compute_args,
139 const SolveInterrupter* const user_canceller, const bool remove_names) {
140 SolveInterrupter local_canceller;
141 const ScopedSolveInterrupterCallback user_canceller_cb(
142 user_canceller, [&]() { local_canceller.Interrupt(); });
144 const std::unique_ptr<BaseSolver> subprocess_solver,
145 solver_factory(EnumToProto(solver_type), model.ExportModel(remove_names),
146 &local_canceller));
147 return CallComputeInfeasibleSubsystem(*subprocess_solver, model.storage(),
148 compute_args, local_canceller);
149}
150
151absl::StatusOr<std::unique_ptr<IncrementalSolverImpl>>
153 const SolverType solver_type,
154 const SolveInterrupter* const user_canceller,
155 const bool remove_names) {
156 if (model == nullptr) {
157 return absl::InvalidArgumentError("input model can't be null");
158 }
159 auto local_canceller = std::make_shared<SolveInterrupter>();
160 auto user_canceller_cb =
161 std::make_unique<const ScopedSolveInterrupterCallback>(
162 user_canceller,
163 [local_canceller]() { local_canceller->Interrupt(); });
164 std::unique_ptr<UpdateTracker> update_tracker = model->NewUpdateTracker();
165 ASSIGN_OR_RETURN(ModelProto model_proto,
166 update_tracker->ExportModel(remove_names));
168 std::unique_ptr<BaseSolver> solver,
169 solver_factory(EnumToProto(solver_type), std::move(model_proto),
170 local_canceller.get()));
171 return absl::WrapUnique<IncrementalSolverImpl>(new IncrementalSolverImpl(
172 std::move(solver_factory), solver_type, remove_names,
173 std::move(local_canceller), std::move(user_canceller_cb),
174 model->storage(), std::move(update_tracker), std::move(solver)));
175}
176
177IncrementalSolverImpl::IncrementalSolverImpl(
178 BaseSolverFactory solver_factory, SolverType solver_type,
179 const bool remove_names, std::shared_ptr<SolveInterrupter> local_canceller,
180 std::unique_ptr<const ScopedSolveInterrupterCallback> user_canceller_cb,
181 const ModelStorage* const expected_storage,
182 std::unique_ptr<UpdateTracker> update_tracker,
183 std::unique_ptr<BaseSolver> solver)
184 : solver_factory_(std::move(solver_factory)),
185 solver_type_(solver_type),
186 remove_names_(remove_names),
187 local_canceller_(std::move(local_canceller)),
188 user_canceller_cb_(std::move(user_canceller_cb)),
189 expected_storage_(expected_storage),
190 update_tracker_(std::move(update_tracker)),
191 solver_(std::move(solver)) {}
192
193absl::StatusOr<SolveResult> IncrementalSolverImpl::Solve(
194 const SolveArguments& arguments) {
195 // TODO: b/260337466 - Add permanent errors and concurrency protection.
197 return SolveWithoutUpdate(arguments);
198}
199
200absl::StatusOr<ComputeInfeasibleSubsystemResult>
202 const ComputeInfeasibleSubsystemArguments& arguments) {
203 // TODO: b/260337466 - Add permanent errors and concurrency protection.
206}
207
208absl::StatusOr<UpdateResult> IncrementalSolverImpl::Update() {
209 // TODO: b/260337466 - Add permanent errors and concurrency protection.
210 ASSIGN_OR_RETURN(std::optional<ModelUpdateProto> model_update,
211 update_tracker_->ExportModelUpdate(remove_names_));
212 if (!model_update.has_value()) {
213 return UpdateResult(true);
214 }
215
216 OR_ASSIGN_OR_RETURN3(const bool did_update,
217 solver_->Update(*std::move(model_update)),
218 _ << "update failed");
219 RETURN_IF_ERROR(update_tracker_->AdvanceCheckpoint());
220
221 if (did_update) {
222 return UpdateResult(true);
223 }
224
225 ASSIGN_OR_RETURN(ModelProto model_proto,
226 update_tracker_->ExportModel(remove_names_));
228 solver_,
229 solver_factory_(EnumToProto(solver_type_), std::move(model_proto),
230 local_canceller_.get()),
231 _ << "solver re-creation failed");
232
233 return UpdateResult(false);
234}
235
237 const SolveArguments& arguments) const {
238 // TODO: b/260337466 - Add permanent errors and concurrency protection.
239 return CallSolve(*solver_, expected_storage_, arguments, *local_canceller_);
240}
241
242absl::StatusOr<ComputeInfeasibleSubsystemResult>
244 const ComputeInfeasibleSubsystemArguments& arguments) const {
245 // TODO: b/260337466 - Add permanent errors and concurrency protection.
246 return CallComputeInfeasibleSubsystem(*solver_, expected_storage_, arguments,
247 *local_canceller_);
248}
249
250} // namespace operations_research::math_opt::internal
#define ASSIGN_OR_RETURN(lhs, rexpr)
#define RETURN_IF_ERROR(expr)
std::function< CallbackResultProto(const CallbackDataProto &)> Callback
Callback function type for MIP/LP callbacks.
Definition base_solver.h:54
absl::StatusOr< SolveResult > SolveWithoutUpdate() const
absl::StatusOr< ComputeInfeasibleSubsystemResult > ComputeInfeasibleSubsystemWithoutUpdate() const
absl::StatusOr< ComputeInfeasibleSubsystemResult > ComputeInfeasibleSubsystem()
absl::StatusOr< UpdateResult > Update() override
SolverType solver_type() const override
Returns the underlying solver used.
Definition solve_impl.h:98
static absl::StatusOr< std::unique_ptr< IncrementalSolverImpl > > New(BaseSolverFactory solver_factory, Model *model, SolverType solver_type, const SolveInterrupter *user_canceller, bool remove_names)
absl::Status status
Definition g_gurobi.cc:44
GRBmodel * model
absl::StatusOr< ComputeInfeasibleSubsystemResult > ComputeInfeasibleSubsystemImpl(const BaseSolverFactory solver_factory, const Model &model, const SolverType solver_type, const ComputeInfeasibleSubsystemArguments &compute_args, const SolveInterrupter *const user_canceller, const bool remove_names)
absl::AnyInvocable< absl::StatusOr< std::unique_ptr< BaseSolver > >( SolverTypeProto solver_type, ModelProto model, SolveInterrupter *local_canceller) const > BaseSolverFactory
Definition solve_impl.h:50
absl::StatusOr< SolveResult > SolveImpl(const BaseSolverFactory solver_factory, const Model &model, const SolverType solver_type, const SolveArguments &solve_args, const SolveInterrupter *const user_canceller, const bool remove_names)
SolverType
The solvers supported by MathOpt.
Definition parameters.h:42
Enum< E >::Proto EnumToProto(std::optional< E > value)
Definition enums.h:270
STL namespace.
Arguments passed to ComputeInfeasibleSubsystem() to control the solver.
static absl::StatusOr< ComputeInfeasibleSubsystemResult > FromProto(const ModelStorage *model, const ComputeInfeasibleSubsystemResultProto &result_proto)
Result of the Update() on an incremental solver.
#define OR_ASSIGN_OR_RETURN3(lhs, rexpr, error_expression)