Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
gscip.h
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
14// Simplified bindings for the SCIP solver. This is not designed to be used
15// directly by users, the API is not friendly to a modeler. For most common
16// cases, use MathOpt instead.
17//
18// Notable differences between gSCIP and SCIP:
19// * Unless callbacks are used, gSCIP only exposes the SCIP stage PROBLEM to
20// the user through public APIs.
21// * Instead of the stateful SCIP parameters API, parameters are passed in at
22// Solve() time and cleared at the end of solve. Parameters that effect
23// problem creation are thus not supported.
24// * gSCIP uses std::numeric_limits<double>::infinity(), rather than SCIPs
25// infinity (a default value of 1e20). Doubles with absolute value >= 1e20
26// but < inf result in an error. Changing the underlying SCIP's infinity is
27// not supported.
28// * absl::Status and absl::StatusOr are used to propagate SCIP errors (and on
29// a best effort basis, also filter out bad input to gSCIP functions). In
30// constraint handlers, we also use absl::Status and absl::StatusOr for
31// error propagation and not SCIP_RETCODE.
32// * Interruption: SCIP interruption (via SCIPinterruptSolve()) is not
33// threadsafe and can only be safely used from a callback (and only in some
34// stages). For GScip, users can optionally provide a GScip::Interrupter as
35// part of the Solve() API. (Behind the scenes we call SCIPinterruptSolve()
36// on the correct thread for the user. Users who know what they are doing
37// can invoke SCIPinterruptSolve() directly, but using a GScip::Interrupter
38// is recommended.
39//
40// A note on error propagation and reliability:
41// Many methods on SCIP return an error code. Errors can be triggered by
42// both invalid input and bugs in SCIP. We propagate these errors back to the
43// user through gSCIP through Status and StatusOr. If you are solving a single
44// MIP and you have previously successfully solved similar MIPs, it is unlikely
45// gSCIP would return any status errors. Depending on your application, CHECK
46// failing on these errors may be appropriate (e.g. a benchmark that is run by
47// hand). If you are solving a very large number of MIPs (e.g. in a flume job),
48// your instances are numerically challenging, or the model/data are drawn from
49// an unreliable source, or you are running a server that cannot crash, you may
50// want to try and process these errors instead. Note that on bad instances,
51// SCIP may still crash, so highly reliable systems should run SCIP in a
52// separate process.
53//
54// NOTE(user): much of the API uses const std::string& instead of
55// absl::string_view because the underlying SCIP API needs a null terminated
56// char*.
57#ifndef OR_TOOLS_GSCIP_GSCIP_H_
58#define OR_TOOLS_GSCIP_GSCIP_H_
59
60#include <atomic>
61#include <cstdint>
62#include <functional>
63#include <limits>
64#include <memory>
65#include <string>
66#include <vector>
67
68#include "absl/base/thread_annotations.h"
69#include "absl/container/flat_hash_map.h"
70#include "absl/container/flat_hash_set.h"
71#include "absl/status/status.h"
72#include "absl/status/statusor.h"
73#include "absl/strings/string_view.h"
74#include "absl/synchronization/mutex.h"
75#include "absl/types/span.h"
77#include "ortools/gscip/gscip.pb.h"
79#include "ortools/gscip/gscip_message_handler.h" // IWYU pragma: export
81#include "scip/scip.h"
82#include "scip/scip_prob.h"
83#include "scip/type_cons.h"
84#include "scip/type_scip.h"
85#include "scip/type_var.h"
86
87namespace operations_research {
88
89using GScipSolution = absl::flat_hash_map<SCIP_VAR*, double>;
90
91// The result of GScip::Solve(). Contains the solve status, statistics, and the
92// solutions found.
93struct GScipResult {
94 GScipOutput gscip_output;
95 // The number of solutions returned is at most GScipParameters::num_solutions.
96 // They are ordered from best objective value to worst. When
97 // gscip_output.status() is optimal, solutions will have at least one element.
98 std::vector<GScipSolution> solutions;
99 // Of the same size as solutions.
100 std::vector<double> objective_values;
101 // Advanced use below
102
103 // If the problem was unbounded, a primal ray in the unbounded direction of
104 // the LP relaxation should be produced.
105 absl::flat_hash_map<SCIP_VAR*, double> primal_ray;
106};
107
108// Models the constraint lb <= a*x <= ub. Members variables and coefficients
109// must have the same size.
110struct GScipLinearRange {
111 double lower_bound = -std::numeric_limits<double>::infinity();
112 std::vector<SCIP_VAR*> variables;
113 std::vector<double> coefficients;
114 double upper_bound = std::numeric_limits<double>::infinity();
115};
116
117// A variable is implied integer if the integrality constraint is not required
118// for the model to be valid, but the variable takes an integer value in any
119// optimal solution to the problem.
120enum class GScipVarType { kContinuous, kBinary, kInteger, kImpliedInteger };
121
122struct GScipIndicatorConstraint;
123struct GScipLogicalConstraintData;
124// Some advanced features, defined at the end of the header file.
125struct GScipQuadraticRange;
126struct GScipSOSData;
127struct GScipVariableOptions;
128
129const GScipVariableOptions& DefaultGScipVariableOptions();
130struct GScipConstraintOptions;
131
132const GScipConstraintOptions& DefaultGScipConstraintOptions();
133using GScipBranchingPriority = absl::flat_hash_map<SCIP_VAR*, int>;
134enum class GScipHintResult;
135
136// A thin wrapper around the SCIP solver that provides C++ bindings that are
137// idiomatic for Google. Unless callbacks are used, the SCIP stage is always
138// PROBLEM. If any GScip function returns an absl::Status error, then the GScip
139// object should be considered to be in an error state.
140class GScip {
141 public:
142 // Used to notify GScip that a call to Solve() should terminate early.
143 //
144 // Begins in the uninterrupted state, and irreversibly moves to the
145 // interrupted state after a call to `interrupt()`.
146 //
147 // This class is threadsafe.
148 class Interrupter {
149 public:
150 Interrupter() = default;
151 Interrupter(const Interrupter&) = delete;
152 Interrupter& operator=(const Interrupter&) = delete;
153
154 // Triggers the interrupter. Informs calls to GScip::Solve() which took
155 // this Interrupter as an argument to stop as soon as possible. Note that
156 // this function does not block and GScip::Solve() does not stop
157 // immediately. Calling this function more than once has no further effect.
158 //
159 // This function is threadsafe and nonblocking.
160 void Interrupt() { interrupted_ = true; }
161
162 // Returns true if we are in the interrupted state (i.e. `interrupt() was
163 // called).
164 //
165 // This function is threadsafe, non-blocking, and fast (time to read an
166 // atomic).
167 bool is_interrupted() const { return interrupted_.load(); }
168
169 private:
170 std::atomic<bool> interrupted_{false};
171 };
172
173 // Create a new GScip (the constructor is private). The default objective
174 // direction is minimization.
175 static absl::StatusOr<std::unique_ptr<GScip>> Create(
176 const std::string& problem_name);
177 ~GScip();
178 static std::string ScipVersion();
179
180 // After Solve() the parameters are reset and SCIP stage is restored to
181 // PROBLEM. "legacy_params" are in the format of legacy_scip_params.h and are
182 // applied after "params". Use of "legacy_params" is discouraged.
183 //
184 // The returned StatusOr will contain an error only if an:
185 // * An underlying function from SCIP fails.
186 // * There is an I/O error with managing SCIP output.
187 // * A user-defined callback function fails.
188 // The above cases are not mutually exclusive. If the problem is infeasible,
189 // this will be reflected in the value of GScipResult::gscip_output::status.
190 //
191 // No reference is held to message_handler or interrupter after Solve()
192 // returns.
193 absl::StatusOr<GScipResult> Solve(
194 const GScipParameters& params = GScipParameters(),
195 absl::string_view legacy_params = "",
196 GScipMessageHandler message_handler = nullptr,
197 const Interrupter* interrupter = nullptr);
198
199 // ///////////////////////////////////////////////////////////////////////////
200 // Basic Model Construction
201 // ///////////////////////////////////////////////////////////////////////////
202
203 // Use true for maximization, false for minimization.
204 absl::Status SetMaximize(bool is_maximize);
205 absl::Status SetObjectiveOffset(double offset);
206
207 // The returned SCIP_VAR is owned by GScip. With default options, the
208 // returned variable will have the same lifetime as GScip (if instead,
209 // GScipVariableOptions::keep_alive is false, SCIP may free the variable at
210 // any time, see GScipVariableOptions::keep_alive for details).
211 //
212 // Note that SCIP will internally convert a variable of type `kInteger` with
213 // bounds of [0, 1] to a variable of type `kBinary`.
214 absl::StatusOr<SCIP_VAR*> AddVariable(
215 double lb, double ub, double obj_coef, GScipVarType var_type,
216 const std::string& var_name = "",
217 const GScipVariableOptions& options = DefaultGScipVariableOptions());
218
219 // The returned SCIP_CONS is owned by GScip. With default options, the
220 // returned variable will have the same lifetime as GScip (if instead,
221 // GScipConstraintOptions::keep_alive is false, SCIP may free the constraint
222 // at any time, see GScipConstraintOptions::keep_alive for details).
223 //
224 // Can be called while creating the model or in a callback (e.g. in a
225 // GScipConstraintHandler).
226 absl::StatusOr<SCIP_CONS*> AddLinearConstraint(
227 const GScipLinearRange& range, const std::string& name = "",
228 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
229
230 // ///////////////////////////////////////////////////////////////////////////
231 // Model Queries
232 // ///////////////////////////////////////////////////////////////////////////
233
234 bool ObjectiveIsMaximize();
235 double ObjectiveOffset();
236
237 double Lb(SCIP_VAR* var);
238 double Ub(SCIP_VAR* var);
239 double ObjCoef(SCIP_VAR* var);
240 // NOTE: The returned type may differ from the type passed to `AddVariable()`.
241 GScipVarType VarType(SCIP_VAR* var);
242 absl::string_view Name(SCIP_VAR* var);
243 const absl::flat_hash_set<SCIP_VAR*>& variables() { return variables_; }
244
245 // These methods works on all constraint types.
246 absl::string_view Name(SCIP_CONS* constraint);
247 bool IsConstraintLinear(SCIP_CONS* constraint);
248 const absl::flat_hash_set<SCIP_CONS*>& constraints() { return constraints_; }
249
250 // These methods will CHECK fail if constraint is not a linear constraint.
251 absl::Span<const double> LinearConstraintCoefficients(SCIP_CONS* constraint);
252 absl::Span<SCIP_VAR* const> LinearConstraintVariables(SCIP_CONS* constraint);
253 double LinearConstraintLb(SCIP_CONS* constraint);
254 double LinearConstraintUb(SCIP_CONS* constraint);
255
256 // ///////////////////////////////////////////////////////////////////////////
257 // Model Updates (needed for incrementalism)
258 // ///////////////////////////////////////////////////////////////////////////
259 // TODO(b/246342145): A crash may occur if you attempt to set a lb <= -1.0 on
260 // a binary variable. SCIP can also silently change the vartype of a variable
261 // after construction, so you should check it via `VarType()`.
262 absl::Status SetLb(SCIP_VAR* var, double lb);
263 // TODO(b/246342145): A crash may occur if you attempt to set an ub >= 2.0 on
264 // a binary variable. SCIP can also silently change the vartype of a variable
265 // after construction, so you should check it via `VarType()`.
266 absl::Status SetUb(SCIP_VAR* var, double ub);
267 absl::Status SetObjCoef(SCIP_VAR* var, double obj_coef);
268 absl::Status SetVarType(SCIP_VAR* var, GScipVarType var_type);
269
270 // Warning: you need to ensure that no constraint has a reference to this
271 // variable before deleting it, or undefined behavior will occur. For linear
272 // constraints, you can set the coefficient of this variable to zero to remove
273 // the variable from the constraint.
274 absl::Status DeleteVariable(SCIP_VAR* var);
275
276 // Checks if SafeBulkDelete will succeed for vars, and returns a description
277 // the problematic variables/constraints on a failure (the returned status
278 // will not contain a propagated SCIP error). Will not modify the underlying
279 // SCIP, it is safe to continue using this if an error is returned.
280 absl::Status CanSafeBulkDelete(const absl::flat_hash_set<SCIP_VAR*>& vars);
281
282 // Attempts to remove vars from all constraints and then remove vars from
283 // the model. As of August 7, 2020, will fail if the model contains any
284 // constraints that are not linear.
285 //
286 // Will call CanSafeBulkDelete above, but can also return an error Status
287 // propagated from SCIP. Do not assume SCIP is in a valid state if this fails.
288 absl::Status SafeBulkDelete(const absl::flat_hash_set<SCIP_VAR*>& vars);
289
290 // These methods will CHECK fail if constraint is not a linear constraint.
291 absl::Status SetLinearConstraintLb(SCIP_CONS* constraint, double lb);
292 absl::Status SetLinearConstraintUb(SCIP_CONS* constraint, double ub);
293 absl::Status SetLinearConstraintCoef(SCIP_CONS* constraint, SCIP_VAR* var,
294 double value);
295 absl::Status AddLinearConstraintCoef(SCIP_CONS* constraint, SCIP_VAR* var,
296 double value);
297
298 // Works on all constraint types. Unlike DeleteVariable, no special action is
299 // required before deleting a constraint.
300 absl::Status DeleteConstraint(SCIP_CONS* constraint);
301
302 // ///////////////////////////////////////////////////////////////////////////
303 // Nonlinear constraint types.
304 // For now, only basic support (adding to the model) is provided. Reading and
305 // updating support may be added in the future.
306 // ///////////////////////////////////////////////////////////////////////////
307
308 // Adds a constraint of the form:
309 // if z then a * x <= b
310 // where z is a binary variable, x is a vector of decision variables, a is
311 // vector of constants, and b is a constant. z can be negated.
312 //
313 // NOTE(user): options.modifiable is ignored.
314 absl::StatusOr<SCIP_CONS*> AddIndicatorConstraint(
315 const GScipIndicatorConstraint& indicator_constraint,
316 const std::string& name = "",
317 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
318
319 // Adds a constraint of form lb <= x * Q * x + a * x <= ub.
320 //
321 // NOTE(user): options.modifiable and options.sticking_at_node are ignored.
322 absl::StatusOr<SCIP_CONS*> AddQuadraticConstraint(
323 const GScipQuadraticRange& range, const std::string& name = "",
324 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
325
326 // Adds the constraint:
327 // logical_data.resultant = AND_i logical_data.operators[i],
328 // where logical_data.resultant and logical_data.operators[i] are all binary
329 // variables.
330 absl::StatusOr<SCIP_CONS*> AddAndConstraint(
331 const GScipLogicalConstraintData& logical_data,
332 const std::string& name = "",
333 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
334
335 // Adds the constraint:
336 // logical_data.resultant = OR_i logical_data.operators[i],
337 // where logical_data.resultant and logical_data.operators[i] must be binary
338 // variables.
339 absl::StatusOr<SCIP_CONS*> AddOrConstraint(
340 const GScipLogicalConstraintData& logical_data,
341 const std::string& name = "",
342 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
343
344 // Adds the constraint that at most one of the variables in sos_data can be
345 // nonzero. The variables can be integer or continuous. See GScipSOSData for
346 // details.
347 //
348 // NOTE(user): options.modifiable is ignored (these constraints are not
349 // modifiable).
350 absl::StatusOr<SCIP_CONS*> AddSOS1Constraint(
351 const GScipSOSData& sos_data, const std::string& name = "",
352 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
353
354 // Adds the constraint that at most two of the variables in sos_data can be
355 // nonzero, and they must be adjacent under the ordering for sos_data. See
356 // GScipSOSData for details.
357 //
358 // NOTE(user): options.modifiable is ignored (these constraints are not
359 // modifiable).
360 absl::StatusOr<SCIP_CONS*> AddSOS2Constraint(
361 const GScipSOSData& sos_data, const std::string& name = "",
362 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
363
364 // ///////////////////////////////////////////////////////////////////////////
365 // Advanced use
366 // ///////////////////////////////////////////////////////////////////////////
367
368 // Returns the name of the constraint handler for this constraint.
369 absl::string_view ConstraintType(SCIP_CONS* constraint);
370
371 // The proposed solution can be partial (only specify some of the variables)
372 // or complete. Complete solutions will be checked for feasibility and
373 // objective quality, and might be unused for these reasons. Partial solutions
374 // will always be accepted.
375 absl::StatusOr<GScipHintResult> SuggestHint(
376 const GScipSolution& partial_solution);
377
378 // All variables have a default branching priority of zero. Variables are
379 // partitioned by their branching priority, and a fractional variable from the
380 // highest partition will always be branched on.
381 //
382 // TODO(user): Add support for BranchingFactor as well, this is typically
383 // more useful.
384 absl::Status SetBranchingPriority(SCIP_VAR* var, int priority);
385
386 // Doubles with absolute value of at least this value are invalid and result
387 // in errors. Floating point actual infinities are replaced by this value in
388 // SCIP calls. SCIP considers values at least this large to be infinite. When
389 // querying gSCIP, if an absolute value exceeds ScipInf, it is replaced by
390 // std::numeric_limits<double>::infinity().
391 double ScipInf();
392 static constexpr double kDefaultScipInf = 1e20;
393
394 // These should typically not be needed.
395 SCIP* scip() { return scip_; }
396
397 absl::StatusOr<bool> DefaultBoolParamValue(const std::string& parameter_name);
398 absl::StatusOr<int> DefaultIntParamValue(const std::string& parameter_name);
399 absl::StatusOr<int64_t> DefaultLongParamValue(
400 const std::string& parameter_name);
401 absl::StatusOr<double> DefaultRealParamValue(
402 const std::string& parameter_name);
403 absl::StatusOr<char> DefaultCharParamValue(const std::string& parameter_name);
404 absl::StatusOr<std::string> DefaultStringParamValue(
405 const std::string& parameter_name);
406
407 // Returns true if GScip is in an error state. Currently only checks if a
408 // callback has failed, but in the future it may check for other failures.
409 bool InErrorState();
410
411 // Internal use. Used by constraint handlers to propagate user-returned Status
412 // errors to GSCIP. Interrupts a solve and passes an error status that
413 // GScip::Solve() must return after SCIP finishes interrupting the solve. Does
414 // not do anything if previously called with a (non-OK) status (i.e. the first
415 // status error is returned by SCIP).
416 //
417 // CHECK fails if status is OK.
418 void InterruptSolveFromCallbackOnCallbackError(absl::Status error_status);
419
420 // Internal use only. Users should instead call
421 // GScipConstraintHandler::AddCallbackConstraint().
422 template <typename ConsHandler, typename ConsData>
423 inline absl::StatusOr<SCIP_CONS*> AddConstraintForHandler(
424 ConsHandler* handler, ConsData* data, const std::string& name = "",
425 const GScipConstraintOptions& options = DefaultGScipConstraintOptions());
426
427 // Internal use only.
428 //
429 // Replaces +/- inf by +/- ScipInf(), fails when |d| is in [ScipInf(), inf).
430 absl::StatusOr<double> ScipInfClamp(double d);
431
432 // Internal use only.
433 //
434 // Returns +/- inf if |d| >= ScipInf(), otherwise returns d.
435 double ScipInfUnclamp(double d);
436
437 private:
438 // Event handler that it used to call SCIPinterruptSolve() is a safe manner.
439 //
440 // At the start of SCIPsolve(), SCIP resets `SCIP_Stat::userinterrupt` to
441 // false. It does the same in SCIPpresolve(), which is called at the beginning
442 // of SCIPsolve() but also at the beginning of each restart. The
443 // `userinterrupt` can also be reset when the transformed problem is freed
444 // when the parameter "misc/resetstat" is used. On top of that, it is not
445 // possible to call SCIPinterruptSolve() in SCIP_STAGE_INITSOLVE stage; which
446 // occurs in the middle of the solve and at restarts.
447 //
448 // If this was no enough, SCIPinterruptSolve() calls SCIPcheckStage() which is
449 // not thread-safe.
450 //
451 // As a consequence, there is no safe way to call SCIPinterruptSolve() from
452 // another thread. Here we take a safer approach: we call it only from the
453 // Exec() of an event handler. This solves all thread safety issues and, if we
454 // have been careful, also ensures we don't call it in the wrong stage. This
455 // also solves the issue the multiple resets of the `userinterrupt` flag since
456 // each time we are called after the interrupter has been triggered, we simply
457 // call SCIPinterruptSolve() until SCIP finally listens.
458 class InterruptEventHandler : public GScipEventHandler {
459 public:
460 InterruptEventHandler();
461
462 SCIP_RETCODE Init(GScip* gscip) override;
463 SCIP_RETCODE Execute(GScipEventHandlerContext) override;
464
465 // Calls SCIPinterruptSolve() if the interrupter is set and triggered and
466 // SCIP is in a valid stage for that.
467 SCIP_RETCODE TryCallInterruptIfNeeded(GScip* gscip);
468
469 // Sets the interrupter, or clears it when `interrupter == nullptr`.
470 void set_interrupter(const Interrupter* interrupter);
471
472 private:
473 // This is set at the start of each call to GScip::Solve() and cleared
474 // before the function returns. It may be null when the user does not
475 // provide an interrupter; in that case we don't register any event.
476 const Interrupter* interrupter_ = nullptr;
477 };
478
479 explicit GScip(SCIP* scip);
480 // Releases SCIP memory.
481 absl::Status CleanUp();
482
483 absl::Status SetParams(const GScipParameters& params,
484 absl::string_view legacy_params);
485 absl::Status FreeTransform();
486
487 // Returns an error if |d| >= ScipInf().
488 absl::Status CheckScipFinite(double d);
489
490 absl::Status MaybeKeepConstraintAlive(SCIP_CONS* constraint,
491 const GScipConstraintOptions& options);
492
493 SCIP* scip_;
494 InterruptEventHandler interrupt_event_handler_;
495 absl::flat_hash_set<SCIP_VAR*> variables_;
496 absl::flat_hash_set<SCIP_CONS*> constraints_;
497 absl::Mutex callback_status_mutex_;
498 absl::Status callback_status_ ABSL_GUARDED_BY(callback_status_mutex_);
499};
500
501// Advanced features below
502
503// Models the constraint
504// lb <= x * Q * x + a * x <= ub
505struct GScipQuadraticRange {
506 // Models lb above.
507 double lower_bound = -std::numeric_limits<double>::infinity();
508
509 // Models a * x above. linear_variables and linear_coefficients must have the
510 // same size.
511 std::vector<SCIP_Var*> linear_variables;
512 std::vector<double> linear_coefficients;
513
514 // These three vectors must have the same size. Models x * Q * x as
515 // sum_i quadratic_coefficients[i] * quadratic_variables1[i]
516 // * quadratic_variables2[i]
517 //
518 // Duplicate quadratic terms (e.g. i=3 encodes 4*x1*x3 and i=4 encodes
519 // 8*x3*x1) are added (as if you added a single entry 12*x1*x3).
520 //
521 // TODO(user): investigate, the documentation seems to suggest that when
522 // linear_variables[i] == quadratic_variables1[i] == quadratic_variables2[i]
523 // there is some advantage.
524 std::vector<SCIP_Var*> quadratic_variables1;
525 std::vector<SCIP_Var*> quadratic_variables2;
526 std::vector<double> quadratic_coefficients;
527
528 // Models ub above.
529 double upper_bound = std::numeric_limits<double>::infinity();
530};
531
532// Models special ordered set constraints (SOS1 and SOS2 constraints). Each
533// contains a list of variables that are implicitly ordered by the provided
534// weights, which must be distinct.
535// SOS1: At most one of the variables can be nonzero.
536// SOS2: At most two of the variables can be nonzero, and they must be
537// consecutive.
538//
539// The weights are optional, and if not provided, the ordering in "variables" is
540// used.
541struct GScipSOSData {
542 // The list of variables where all but one or two must be zero. Can be integer
543 // or continuous variables, typically their domain will contain zero. Cannot
544 // be empty in a valid SOS constraint.
545 std::vector<SCIP_VAR*> variables;
546
547 // Optional, can be empty. Otherwise, must have size equal to variables, and
548 // values must be distinct. Determines an "ordering" over the variables
549 // (smallest weight to largest). Additionally, the numeric values of
550 // the weights are used to make branching decisions in a solver specific way,
551 // for details, see:
552 // * https://scip.zib.de/doc/html/cons__sos1_8c.php
553 // * https://scip.zib.de/doc/html/cons__sos2_8c.php.
554 std::vector<double> weights;
555};
556
557// Models the constraint z = 1 => a * x <= b
558// If negate_indicator, then instead: z = 0 => a * x <= b
559struct GScipIndicatorConstraint {
560 // The z variable above. The vartype must be kBinary.
561 SCIP_VAR* indicator_variable = nullptr;
562 bool negate_indicator = false;
563 // The x variable above.
564 std::vector<SCIP_Var*> variables;
565 // a above. Must have the same size as x.
566 std::vector<double> coefficients;
567 // b above.
568 double upper_bound = std::numeric_limits<double>::infinity();
569};
570
571// Data for constraint of the form resultant = f(operators), e.g.:
572// resultant = AND_i operators[i]
573// For existing constraints (e.g. AND, OR) resultant and operators[i] should all
574// be binary variables, this my change. See use in GScip for details.
575struct GScipLogicalConstraintData {
576 SCIP_VAR* resultant = nullptr;
577 std::vector<SCIP_VAR*> operators;
578};
579
580enum class GScipHintResult {
581 // Hint was not feasible.
583 // Hint was not good enough to keep.
584 kRejected,
585 // Hint was kept. Partial solutions are not checked for feasibility, they
586 // are always accepted.
587 kAccepted
588};
589
590// Advanced use. Options to use when creating a variable.
591struct GScipVariableOptions {
592 // ///////////////////////////////////////////////////////////////////////////
593 // SCIP options. Descriptions are from the SCIP documentation, e.g.
594 // SCIPcreateVar:
595 // https://scip.zib.de/doc/html/group__PublicVariableMethods.php#ga7a37fe4dc702dadecc4186b9624e93fc
596 // ///////////////////////////////////////////////////////////////////////////
597
598 // Should var's column be present in the initial root LP?
599 bool initial = true;
600
601 // Is var's column removable from the LP (due to aging or cleanup)?
602 bool removable = false;
603
604 // ///////////////////////////////////////////////////////////////////////////
605 // gSCIP options.
606 // ///////////////////////////////////////////////////////////////////////////
607
608 // If keep_alive=true, the returned variable will not to be freed until after
609 // ~GScip() is called. Otherwise, the returned variable could be freed
610 // internally by SCIP at any point, and it is not safe to hold a reference to
611 // the returned variable.
612 //
613 // The primary reason to set keep_alive=false is if you are adding many
614 // variables in a callback (in branch and price), and you expect that most of
615 // them will be deleted.
616 bool keep_alive = true;
617};
618
619// Advanced use. Options to use when creating a constraint.
620struct GScipConstraintOptions {
621 // ///////////////////////////////////////////////////////////////////////////
622 // SCIP options. Descriptions are from the SCIP documentation, e.g.
623 // SCIPcreateConsLinear:
624 // https://scip.zib.de/doc/html/group__CONSHDLRS.php#gaea3b4db21fe214be5db047e08b46b50e
625 // ///////////////////////////////////////////////////////////////////////////
626
627 // Should the LP relaxation of constraint be in the initial LP? False for lazy
628 // constraints (true in callbacks).
629 bool initial = true;
630 // Should the constraint be separated during LP processing?
631 bool separate = true;
632 // Should the constraint be enforced during node processing? True for model
633 // constraints, false for redundant constraints.
634 bool enforce = true;
635 // Should the constraint be checked for feasibility? True for model
636 // constraints, false for redundant constraints.
637 bool check = true;
638 // Should the constraint be propagated during node processing?
639 bool propagate = true;
640 // Is constraint only valid locally? Must be true for branching constraints.
641 bool local = false;
642 // Is constraint modifiable (subject to column generation)? In column
643 // generation applications, set to true if pricing adds coefficients to this
644 // constraint.
645 bool modifiable = false;
646 // Is constraint subject to aging? Set to true for own cuts which are
647 // separated as constraints
648 bool dynamic = false;
649 // Should the relaxation be removed from the LP due to aging or cleanup? Set
650 // to true for 'lazy constraints' and 'user cuts'.
651 bool removable = false;
652 // Should the constraint always be kept at the node where it was added, even
653 // if it may be moved to a more global node? Usually set to false. Set to true
654 // for constraints that represent node data.
655 bool sticking_at_node = false;
656
657 // ///////////////////////////////////////////////////////////////////////////
658 // gSCIP options.
659 // ///////////////////////////////////////////////////////////////////////////
660
661 // If keep_alive=true, the returned constraint will not to be freed until
662 // after ~GScip() is called. Otherwise, the returned constraint could be freed
663 // internally by SCIP at any point, and it is not safe to hold a reference to
664 // the returned constraint.
665 //
666 // The primary reason to set keep_alive=false is if you are adding many
667 // constraints in a callback, and you expect that most of them will be
668 // deleted.
669 bool keep_alive = true;
670};
671
673// Template function implementations
675
676template <typename ConsHandler, typename ConsData>
677absl::StatusOr<SCIP_CONS*> GScip::AddConstraintForHandler(
678 ConsHandler* handler, ConsData* data, const std::string& name,
679 const GScipConstraintOptions& options) {
680 SCIP_CONS* constraint = nullptr;
681 RETURN_IF_SCIP_ERROR(SCIPcreateCons(
682 scip_, &constraint, name.data(), handler, data, options.initial,
683 options.separate, options.enforce, options.check, options.propagate,
684 options.local, options.modifiable, options.dynamic, options.removable,
685 options.sticking_at_node));
686 if (constraint == nullptr) {
687 return absl::InternalError("SCIP failed to create constraint");
688 }
689 RETURN_IF_SCIP_ERROR(SCIPaddCons(scip_, constraint));
690 RETURN_IF_ERROR(MaybeKeepConstraintAlive(constraint, options));
691 return constraint;
692}
693
694} // namespace operations_research
695
696#endif // OR_TOOLS_GSCIP_GSCIP_H_
#define RETURN_IF_ERROR(expr)
const std::string name
A name for logging purposes.
int64_t value
IntVar * var
double upper_bound
double lower_bound
absl::Span< const double > coefficients
absl::StatusOr< SolveResult > Solve(const Model &model, const SolverType solver_type, const SolveArguments &solve_args, const SolverInitArguments &init_args)
Definition solve.cc:62
In SWIG mode, we don't want anything besides these top-level includes.
const GScipConstraintOptions & DefaultGScipConstraintOptions()
Definition gscip.cc:292
const GScipVariableOptions & DefaultGScipVariableOptions()
Definition gscip.cc:287
#define RETURN_IF_SCIP_ERROR(x)
const std::optional< Range > & range
Definition statistics.cc:37