OR-Tools  9.2
callback_validator.cc
Go to the documentation of this file.
1// Copyright 2010-2021 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 <algorithm>
17#include <limits>
18#include <string>
19#include <vector>
20
22#include "google/protobuf/duration.pb.h"
23#include "absl/container/flat_hash_set.h"
24#include "absl/status/status.h"
25#include "absl/strings/str_cat.h"
26#include "absl/strings/str_join.h"
27#include "ortools/math_opt/callback.pb.h"
31#include "ortools/math_opt/solution.pb.h"
32#include "ortools/math_opt/sparse_containers.pb.h"
39#include "absl/status/status.h"
41
42namespace operations_research {
43namespace math_opt {
44namespace {
45
46constexpr double kInf = std::numeric_limits<double>::infinity();
47
48absl::Status IsEventRegistered(
49 const CallbackEventProto event,
50 const CallbackRegistrationProto& callback_registration) {
51 // Unfortunatelly the range iterator return ints and not CallbackEventProtos.
52 const int num_events = callback_registration.request_registration_size();
53 for (int k = 0; k < num_events; ++k) {
54 if (callback_registration.request_registration(k) == event) {
55 return absl::OkStatus();
56 }
57 }
58 return absl::InvalidArgumentError(absl::StrCat(
59 "event ", ProtoEnumToString(event),
60 " not part of the registered_events in callback_registration"));
61}
62
63absl::Status ValidateGeneratedLinearConstraint(
64 const CallbackResultProto::GeneratedLinearConstraint& linear_constraint,
65 const bool add_cuts, const bool add_lazy_constraints,
66 const ModelSummary& model_summary) {
67 const auto coefficients = MakeView(linear_constraint.linear_expression());
70 {.allow_positive_infinity = false, .allow_negative_infinity = false}))
71 << "invalid linear_constraint coefficients";
72 RETURN_IF_ERROR(CheckIdsSubset(coefficients.ids(), model_summary.variables,
73 "cut variables", "model IDs"));
74 RETURN_IF_ERROR(CheckScalar(linear_constraint.lower_bound(),
75 {.allow_positive_infinity = false}))
76 << "for GeneratedLinearConstraint.lower_bound";
77 RETURN_IF_ERROR(CheckScalar(linear_constraint.upper_bound(),
78 {.allow_negative_infinity = false}))
79 << "for GeneratedLinearConstraint.upper_bound";
80 if (linear_constraint.lower_bound() == -kInf &&
81 linear_constraint.upper_bound() == kInf) {
82 return absl::InvalidArgumentError(
83 "invalid GeneratedLinearConstraint, bounds [-inf,inf]");
84 }
85 if (linear_constraint.is_lazy() && !add_lazy_constraints) {
86 return absl::InvalidArgumentError(
87 "invalid GeneratedLinearConstraint with lazy attribute set to true, "
88 "adding lazy constraints requires "
89 "CallbackRegistrationProto.add_lazy_constraints=true");
90 }
91 if (!linear_constraint.is_lazy() && !add_cuts) {
92 return absl::InvalidArgumentError(
93 "invalid GeneratedLinearConstraint with lazy attribute set to false, "
94 "adding cuts requires CallbackRegistrationProto.add_cuts=true");
95 }
96 return absl::OkStatus();
97}
98
99template <typename T>
100struct ProtoEnumFormatter {
101 void operator()(std::string* const out, const T value) {
102 out->append(ProtoEnumToString(value));
103 }
104};
105
106} // namespace
107
109 const CallbackRegistrationProto& callback_registration,
110 const ModelSummary& model_summary) {
112 callback_registration.mip_solution_filter(), model_summary.variables))
113 << "invalid CallbackRegistrationProto.mip_solution_filter";
115 callback_registration.mip_node_filter(), model_summary.variables))
116 << "invalid CallbackRegistrationProto.mip_node_filter";
117 // Unfortunatelly the range iterator return ints and not CallbackEventProtos.
118 const int num_events = callback_registration.request_registration_size();
119 bool can_add_lazy_constraints = false;
120 bool can_add_cuts = false;
121 for (int k = 0; k < num_events; ++k) {
122 const CallbackEventProto requested_event =
123 callback_registration.request_registration(k);
124 if (requested_event == CALLBACK_EVENT_UNSPECIFIED ||
125 !CallbackEventProto_IsValid(requested_event)) {
126 return absl::InvalidArgumentError(absl::StrCat(
127 "invalid event ", requested_event, " can not be registered"));
128 }
129 if (requested_event == CALLBACK_EVENT_MIP_NODE) {
130 can_add_lazy_constraints = true;
131 can_add_cuts = true;
132 }
133 if (requested_event == CALLBACK_EVENT_MIP_SOLUTION) {
134 can_add_lazy_constraints = true;
135 }
136 }
137 if (callback_registration.add_cuts() && !can_add_cuts) {
138 return absl::InvalidArgumentError(
139 "can only add cuts at event CALLBACK_EVENT_MIP_NODE but this event was "
140 "not requested");
141 }
142 if (callback_registration.add_lazy_constraints() &&
143 !can_add_lazy_constraints) {
144 return absl::InvalidArgumentError(
145 "can only add lazy constraints at events CALLBACK_EVENT_MIP_NODE and "
146 "CALLBACK_EVENT_MIP_SOLUTION but neither of these events were "
147 "requested");
148 }
149
150 return absl::OkStatus();
151}
152
154 const CallbackDataProto& cb_data,
155 const CallbackRegistrationProto& callback_registration,
156 const ModelSummary& model_summary) {
157 const CallbackEventProto event = cb_data.event();
158 RETURN_IF_ERROR(IsEventRegistered(event, callback_registration))
159 << "invalid CallbackDataProto.event for given CallbackRegistrationProto";
160
161 const bool has_primal_solution = cb_data.has_primal_solution_vector();
162 if (has_primal_solution && event != CALLBACK_EVENT_MIP_SOLUTION &&
163 event != CALLBACK_EVENT_MIP_NODE) {
164 return absl::InvalidArgumentError(
165 absl::StrCat("can't provide primal_solution_vector for event ", event,
166 " (", ProtoEnumToString(event), ")"));
167 }
168
169#ifdef RETURN_IF_SCALAR
170#error Collision in macro definition RETURN_IF_SCALAR
171#endif
172#define RETURN_IF_SCALAR(stat, value, option) \
173 do { \
174 if (stat.has_##value()) { \
175 RETURN_IF_ERROR(CheckScalar(static_cast<double>(stat.value()), option)) \
176 << "Invalid CallbackDataProto." << #stat << "." << #value; \
177 } \
178 } while (false)
179 const DoubleOptions nonan;
180 const DoubleOptions finite = {.allow_positive_infinity = false,
181 .allow_negative_infinity = false};
182 const DoubleOptions noneg = {.allow_positive_infinity = false,
183 .allow_negative = false};
184 // Check PresolveStats.
185 const auto& presolve_stats = cb_data.presolve_stats();
186 RETURN_IF_SCALAR(presolve_stats, bound_changes, noneg);
187 RETURN_IF_SCALAR(presolve_stats, coefficient_changes, noneg);
188
189 // Check SimplexStats.
190 const auto& simplex_stats = cb_data.simplex_stats();
191 RETURN_IF_SCALAR(simplex_stats, iteration_count, noneg);
192 RETURN_IF_SCALAR(simplex_stats, objective_value, finite);
193 RETURN_IF_SCALAR(simplex_stats, primal_infeasibility, noneg);
194 RETURN_IF_SCALAR(simplex_stats, dual_infeasibility, noneg);
195
196 // Check BarrierStats.
197 const auto& barrier_stats = cb_data.barrier_stats();
198 RETURN_IF_SCALAR(barrier_stats, iteration_count, noneg);
199 RETURN_IF_SCALAR(barrier_stats, primal_objective, finite);
200 RETURN_IF_SCALAR(barrier_stats, dual_objective, finite);
201 RETURN_IF_SCALAR(barrier_stats, complementarity, finite);
202 RETURN_IF_SCALAR(barrier_stats, primal_infeasibility, noneg);
203 RETURN_IF_SCALAR(barrier_stats, dual_infeasibility, noneg);
204
205 // Check MipStats.
206 const auto& mip_stats = cb_data.mip_stats();
207 RETURN_IF_SCALAR(mip_stats, primal_bound, nonan);
208 RETURN_IF_SCALAR(mip_stats, dual_bound, nonan);
209 RETURN_IF_SCALAR(mip_stats, explored_nodes, noneg);
210 RETURN_IF_SCALAR(mip_stats, open_nodes, noneg);
211 RETURN_IF_SCALAR(mip_stats, simplex_iterations, noneg);
212 RETURN_IF_SCALAR(mip_stats, number_of_solutions_found, noneg);
213 RETURN_IF_SCALAR(mip_stats, cutting_planes_in_lp, noneg);
214
215 // Check runtime.
216 RETURN_IF_ERROR(CheckScalar(cb_data.runtime().seconds(), noneg))
217 << "Invalid CallbackDataProto.runtime.seconds";
218 RETURN_IF_ERROR(CheckScalar(cb_data.runtime().nanos(), noneg))
219 << "Invalid CallbackDataProto.runtime.nanos";
220#undef RETURN_IF_SCALAR
221
222 // Ensure required fields are available depending on event.
223 switch (event) {
224 case CALLBACK_EVENT_MIP_NODE:
225 case CALLBACK_EVENT_MIP_SOLUTION: {
226 if (has_primal_solution) {
227 const SparseVectorFilterProto& filter =
228 event == CALLBACK_EVENT_MIP_NODE
229 ? callback_registration.mip_node_filter()
230 : callback_registration.mip_solution_filter();
232 cb_data.primal_solution_vector(), filter, model_summary))
233 << "invalid CallbackDataProto.primal_solution_vector";
234 } else if (event == CALLBACK_EVENT_MIP_SOLUTION) {
235 return absl::InvalidArgumentError(
236 absl::StrCat("must provide primal_solution_vector for event ",
237 event, " (", ProtoEnumToString(event), ")"));
238 }
239 break;
240 }
241
242 case CALLBACK_EVENT_UNSPECIFIED:
243 // This can not happen as a valid callback_registration can not register
244 // a CALLBACK_EVENT_UNSPECIFIED.
245 LOG(FATAL)
246 << "CALLBACK_EVENT_UNSPECIFIED can not be a registered event, this "
247 "points to either an invalid CallbackRegistrationProto (which "
248 "violates "
249 "one of the assumptions of this function), or memory corruption";
250 default:
251 // The remaining events are just for information collection. No further
252 // test required.
253 break;
254 }
255
256 return absl::OkStatus();
257}
258
260 const CallbackResultProto& callback_result,
261 const CallbackEventProto callback_event,
262 const CallbackRegistrationProto& callback_registration,
263 const ModelSummary& model_summary) {
264 // We assume that all arguments but the first are valid and concordant with
265 // each other. Otherwise this is an internal implementation error.
266 CHECK_OK(IsEventRegistered(callback_event, callback_registration));
267
268 if (!callback_result.cuts().empty()) {
269 if (callback_event != CALLBACK_EVENT_MIP_NODE &&
270 callback_event != CALLBACK_EVENT_MIP_SOLUTION) {
271 return absl::InvalidArgumentError(absl::StrCat(
272 "invalid CallbackResultProto, can't return cuts for callback_event ",
273 callback_event, "(", ProtoEnumToString(callback_event), ")"));
274 }
275 for (const CallbackResultProto::GeneratedLinearConstraint& cut :
276 callback_result.cuts()) {
277 RETURN_IF_ERROR(ValidateGeneratedLinearConstraint(
278 cut, callback_registration.add_cuts(),
279 callback_registration.add_lazy_constraints(), model_summary));
280 }
281 }
282 if (!callback_result.suggested_solutions().empty()) {
283 if (callback_event != CALLBACK_EVENT_MIP_NODE) {
284 return absl::InvalidArgumentError(absl::StrCat(
285 "invalid CallbackResultProto, can't return suggested solutions for "
286 "callback_event ",
287 callback_event, "(", ProtoEnumToString(callback_event), ")"));
288 }
289 for (const SparseDoubleVectorProto& primal_solution_vector :
290 callback_result.suggested_solutions()) {
292 primal_solution_vector, SparseVectorFilterProto(), model_summary))
293 << "invalid CallbackResultProto.suggested_solutions";
294 }
295 }
296
297 return absl::OkStatus();
298}
299
301 const CallbackRegistrationProto& registration,
302 const absl::flat_hash_set<CallbackEventProto>& supported_events) {
303 std::vector<CallbackEventProto> unsupported_events;
304 for (const CallbackEventProto event : EventSet(registration)) {
305 if (!supported_events.contains(event)) {
306 unsupported_events.push_back(event);
307 }
308 }
309
310 if (unsupported_events.empty()) {
311 return absl::OkStatus();
312 }
313
314 std::sort(unsupported_events.begin(), unsupported_events.end());
315
316 const bool plural = unsupported_events.size() >= 2;
317 return absl::InvalidArgumentError(
318 absl::StrCat("event", (plural ? "s { " : " "),
319 absl::StrJoin(unsupported_events, ", ",
320 ProtoEnumFormatter<CallbackEventProto>()),
321 (plural ? " } are" : " is"), " not supported"));
322}
323
324} // namespace math_opt
325} // namespace operations_research
#define CHECK_OK(x)
Definition: base/logging.h:44
#define LOG(severity)
Definition: base/logging.h:420
#define RETURN_IF_SCALAR(stat, value, option)
int64_t value
absl::Span< const double > coefficients
const int FATAL
Definition: log_severity.h:32
absl::Status CheckRegisteredCallbackEvents(const CallbackRegistrationProto &registration, const absl::flat_hash_set< CallbackEventProto > &supported_events)
absl::Status CheckScalar(const double value, const DoubleOptions &options)
absl::Status ValidateCallbackResultProto(const CallbackResultProto &callback_result, const CallbackEventProto callback_event, const CallbackRegistrationProto &callback_registration, const ModelSummary &model_summary)
absl::Status ValidatePrimalSolutionVector(const SparseDoubleVectorProto &vector, const SparseVectorFilterProto &filter, const ModelSummary &model_summary)
absl::Status ValidateCallbackDataProto(const CallbackDataProto &cb_data, const CallbackRegistrationProto &callback_registration, const ModelSummary &model_summary)
absl::Status ValidateCallbackRegistration(const CallbackRegistrationProto &callback_registration, const ModelSummary &model_summary)
SparseVectorView< T > MakeView(absl::Span< const int64_t > ids, const Collection &values)
absl::Status CheckIdsAndValues(const SparseVectorView< T > &vector_view, absl::string_view value_name="values")
absl::Status ValidateSparseVectorFilter(const SparseVectorFilterProto &v, const IdNameBiMap &valid_ids)
absl::Status CheckIdsSubset(absl::Span< const int64_t > ids, const IdNameBiMap &universe, absl::string_view ids_description, absl::string_view universe_description)
absl::flat_hash_set< CallbackEventProto > EventSet(const CallbackRegistrationProto &callback_registration)
Collection of objects used to extend the Constraint Solver library.
std::string ProtoEnumToString(ProtoEnumType enum_value)
#define RETURN_IF_ERROR(expr)
Definition: status_macros.h:29