Google OR-Tools v9.11
a fast and portable software suite for combinatorial optimization
Loading...
Searching...
No Matches
constraint_solver.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
67
68#ifndef OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
69#define OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
70
71#include <stddef.h>
72#include <stdint.h>
73
74#include <deque>
75#include <functional>
76#include <memory>
77#include <ostream>
78#include <random>
79#include <string>
80#include <utility>
81#include <vector>
82
83#include "absl/base/attributes.h"
84#include "absl/base/log_severity.h"
85#include "absl/container/flat_hash_map.h"
86#include "absl/container/flat_hash_set.h"
87#include "absl/flags/declare.h"
88#include "absl/flags/flag.h"
89#include "absl/log/check.h"
90#include "absl/random/random.h"
91#include "absl/strings/str_format.h"
92#include "absl/strings/string_view.h"
93#include "absl/time/time.h"
94#include "absl/types/span.h"
97#include "ortools/base/timer.h"
98#include "ortools/base/types.h"
99#include "ortools/constraint_solver/search_stats.pb.h"
100#include "ortools/constraint_solver/solver_parameters.pb.h"
105
106#if !defined(SWIG)
107ABSL_DECLARE_FLAG(int64_t, cp_random_seed);
108#endif // !defined(SWIG)
109
110class File;
111
112namespace operations_research {
113
114class Assignment;
115class AssignmentProto;
116class BaseObject;
117class CastConstraint;
118class Constraint;
119class Decision;
120class DecisionBuilder;
121class DecisionVisitor;
122class Demon;
123class DemonProfiler;
124class Dimension;
125class DisjunctiveConstraint;
126class ImprovementSearchLimit;
127class IntExpr;
128class IntVar;
129class IntVarAssignment;
130class IntVarLocalSearchFilter;
131class IntervalVar;
132class IntervalVarAssignment;
133class LocalSearch;
134class LocalSearchFilter;
135class LocalSearchFilterManager;
136class LocalSearchMonitor;
137class LocalSearchOperator;
138class LocalSearchPhaseParameters;
139class LocalSearchProfiler;
140class ModelCache;
141class ModelVisitor;
142class ObjectiveMonitor;
143class OptimizeVar;
144class Pack;
145class ProfiledDecisionBuilder;
146class PropagationBaseObject;
147class PropagationMonitor;
148class Queue;
149class RegularLimit;
150class RegularLimitParameters;
151class RevBitMatrix;
152class Search;
153class SearchLimit;
154class SearchMonitor;
155class SequenceVar;
156class SequenceVarAssignment;
157class SolutionCollector;
158class SolutionPool;
159class SymmetryBreaker;
160struct StateInfo;
161struct Trail;
162template <class T>
163class SimpleRevFIFO;
164template <typename F>
165class LightIntFunctionElementCt;
166template <typename F>
167class LightIntIntFunctionElementCt;
168
169inline int64_t CpRandomSeed() {
170 return absl::GetFlag(FLAGS_cp_random_seed) == -1
171 ? absl::Uniform<int64_t>(absl::BitGen(), 0, kint64max)
172 : absl::GetFlag(FLAGS_cp_random_seed);
173}
174
184 };
185
186 enum ValueSelection {
254class Solver {
255 public:
260 struct IntegerCastInfo {
262 : variable(nullptr), expression(nullptr), maintainer(nullptr) {}
263 IntegerCastInfo(IntVar* const v, IntExpr* const e, Constraint* const c)
264 : variable(v), expression(e), maintainer(c) {}
268 };
269
271 static constexpr int kNumPriorities = 3;
281
286
305
313
321
327
333
343
347
351 };
352 // TODO(user): add HIGHEST_MIN and LOWEST_MAX.
353
356 enum IntValueStrategy {
359
365
402
431 };
445 TWOOPT,
446
461 OROPT,
462
464 RELOCATE,
465
473 EXCHANGE,
484 CROSS,
485
493
500
508
515
535 PATHLNS,
536
540
545
554 INCREMENT,
555
559 DECREMENT,
560
569 };
570
578 LK,
579
587
594 TSPLNS
595 };
596
603 GE,
605 LE,
609 };
610
620 VAR_PRIORITY = 1,
621
623 NORMAL_PRIORITY = 2,
624 };
625
631
634
637
640
657 };
666 ENDS_AT,
667
673
675 STARTS_AT,
684
689 };
690
699 NO_CHANGE,
700
704 KEEP_LEFT,
705
755 kEndFail,
768 kAccept,
769 // Dummy event whose underlying int is the number of MonitorEvent enums.
770 kLast,
771 };
772#endif // SWIG
773
775 typedef std::function<int64_t(int64_t)> IndexEvaluator1;
776 typedef std::function<int64_t(int64_t, int64_t)> IndexEvaluator2;
777 typedef std::function<int64_t(int64_t, int64_t, int64_t)> IndexEvaluator3;
778
779 typedef std::function<bool(int64_t)> IndexFilter1;
780
781 typedef std::function<IntVar*(int64_t)> Int64ToIntVar;
782
783 typedef std::function<int64_t(Solver* solver,
784 const std::vector<IntVar*>& vars,
785 int64_t first_unbound, int64_t last_unbound)>
787
788 typedef std::function<int64_t(const IntVar* v, int64_t id)>
790 typedef std::function<bool(int64_t, int64_t, int64_t)>
792 typedef std::function<DecisionModification()> BranchSelector;
793 // TODO(user): wrap in swig.
794 typedef std::function<void(Solver*)> Action;
795 typedef std::function<void()> Closure;
796
798 explicit Solver(const std::string& name);
799 Solver(const std::string& name, const ConstraintSolverParameters& parameters);
800
801#ifndef SWIG
802 // This type is neither copyable nor movable.
803 Solver(const Solver&) = delete;
804 Solver& operator=(const Solver&) = delete;
805#endif
806
810 ConstraintSolverParameters parameters() const { return parameters_; }
811 // Read-only.
812 const ConstraintSolverParameters& const_parameters() const {
813 return parameters_;
814 }
816 // TODO(user): Move to constraint_solver_parameters.h.
817 static ConstraintSolverParameters DefaultSolverParameters();
818
820
824 template <class T>
825 void SaveValue(T* o) {
826 InternalSaveValue(o);
827 }
828
841 template <typename T>
842 T* RevAlloc(T* object) {
843 return reinterpret_cast<T*>(SafeRevAlloc(object));
844 }
845
852 template <typename T>
853 T* RevAllocArray(T* object) {
854 return reinterpret_cast<T*>(SafeRevAllocArray(object));
855 }
856
890 void AddConstraint(Constraint* c);
894 void AddCastConstraint(CastConstraint* constraint, IntVar* target_var,
895 IntExpr* expr);
896
938 bool Solve(DecisionBuilder* db, const std::vector<SearchMonitor*>& monitors);
939 bool Solve(DecisionBuilder* db);
940 bool Solve(DecisionBuilder* db, SearchMonitor* m1);
941 bool Solve(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2);
942 bool Solve(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2,
943 SearchMonitor* m3);
944 bool Solve(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2,
947
956
957 void NewSearch(DecisionBuilder* db,
958 const std::vector<SearchMonitor*>& monitors);
959 void NewSearch(DecisionBuilder* db);
960 void NewSearch(DecisionBuilder* db, SearchMonitor* m1);
961 void NewSearch(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2);
962 void NewSearch(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2,
963 SearchMonitor* m3);
964 void NewSearch(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2,
966
967 bool NextSolution();
968 void RestartSearch();
969 void EndSearch();
971
980 bool SolveAndCommit(DecisionBuilder* db,
981 const std::vector<SearchMonitor*>& monitors);
982 bool SolveAndCommit(DecisionBuilder* db);
983 bool SolveAndCommit(DecisionBuilder* db, SearchMonitor* m1);
984 bool SolveAndCommit(DecisionBuilder* db, SearchMonitor* m1,
985 SearchMonitor* m2);
986 bool SolveAndCommit(DecisionBuilder* db, SearchMonitor* m1, SearchMonitor* m2,
987 SearchMonitor* m3);
988
990 bool CheckAssignment(Assignment* solution);
991
996
998 SolverState state() const { return state_; }
999
1001 void Fail();
1002
1003#if !defined(SWIG)
1008 void AddBacktrackAction(Action a, bool fast);
1009#endif
1010
1012 std::string DebugString() const;
1013
1015 static int64_t MemoryUsage();
1016
1021 absl::Time Now() const;
1022
1025 int64_t wall_time() const;
1026
1028 int64_t branches() const { return branches_; }
1029
1031 int64_t solutions() const;
1032
1034 int64_t unchecked_solutions() const;
1035
1037 int64_t demon_runs(DemonPriority p) const { return demon_runs_[p]; }
1038
1040 int64_t failures() const { return fails_; }
1041
1043 int64_t neighbors() const { return neighbors_; }
1044
1047 void ClearNeighbors() { neighbors_ = 0; }
1048 void IncrementNeighbors() { ++neighbors_; }
1049
1051 int64_t filtered_neighbors() const { return filtered_neighbors_; }
1052
1054 int64_t accepted_neighbors() const { return accepted_neighbors_; }
1058 uint64_t stamp() const;
1059
1061 uint64_t fail_stamp() const;
1062
1064 void set_context(absl::string_view context) { context_ = context; }
1065
1067 const std::string& context() const { return context_; }
1068
1071 return optimization_direction_;
1072 }
1074 optimization_direction_ = direction;
1076
1077 // All factories (MakeXXX methods) encapsulate creation of objects
1078 // through RevAlloc(). Hence, the Solver used for allocating the
1079 // returned object will retain ownership of the allocated memory.
1080 // Destructors are called upon backtrack, or when the Solver is
1081 // itself destructed.
1082
1083 // ----- Int Variables and Constants -----
1084
1086 IntVar* MakeIntVar(int64_t min, int64_t max, const std::string& name);
1087
1089 IntVar* MakeIntVar(const std::vector<int64_t>& values,
1090 const std::string& name);
1093 IntVar* MakeIntVar(const std::vector<int>& values, const std::string& name);
1096 IntVar* MakeIntVar(int64_t min, int64_t max);
1099 IntVar* MakeIntVar(const std::vector<int64_t>& values);
1102 IntVar* MakeIntVar(const std::vector<int>& values);
1103
1105 IntVar* MakeBoolVar(const std::string& name);
1106
1109
1111 IntVar* MakeIntConst(int64_t val, const std::string& name);
1112
1114 IntVar* MakeIntConst(int64_t val);
1115
1119 void MakeIntVarArray(int var_count, int64_t vmin, int64_t vmax,
1120 const std::string& name, std::vector<IntVar*>* vars);
1123 void MakeIntVarArray(int var_count, int64_t vmin, int64_t vmax,
1124 std::vector<IntVar*>* vars);
1126 IntVar** MakeIntVarArray(int var_count, int64_t vmin, int64_t vmax,
1127 const std::string& name);
1128
1132 void MakeBoolVarArray(int var_count, const std::string& name,
1133 std::vector<IntVar*>* vars);
1136 void MakeBoolVarArray(int var_count, std::vector<IntVar*>* vars);
1138 IntVar** MakeBoolVarArray(int var_count, const std::string& name);
1139
1140 // ----- Integer Expressions -----
1141
1143 IntExpr* MakeSum(IntExpr* left, IntExpr* right);
1145 IntExpr* MakeSum(IntExpr* expr, int64_t value);
1147 IntExpr* MakeSum(const std::vector<IntVar*>& vars);
1148
1150 IntExpr* MakeScalProd(const std::vector<IntVar*>& vars,
1151 const std::vector<int64_t>& coefs);
1153 IntExpr* MakeScalProd(const std::vector<IntVar*>& vars,
1154 const std::vector<int>& coefs);
1155
1157 IntExpr* MakeDifference(IntExpr* left, IntExpr* right);
1159 IntExpr* MakeDifference(int64_t value, IntExpr* expr);
1162
1164 IntExpr* MakeProd(IntExpr* left, IntExpr* right);
1166 IntExpr* MakeProd(IntExpr* expr, int64_t value);
1167
1169 IntExpr* MakeDiv(IntExpr* expr, int64_t value);
1171 IntExpr* MakeDiv(IntExpr* numerator, IntExpr* denominator);
1172
1174 IntExpr* MakeAbs(IntExpr* expr);
1176 IntExpr* MakeSquare(IntExpr* expr);
1178 IntExpr* MakePower(IntExpr* expr, int64_t n);
1179
1181 IntExpr* MakeElement(const std::vector<int64_t>& values, IntVar* index);
1183 IntExpr* MakeElement(const std::vector<int>& values, IntVar* index);
1184
1195 IntExpr* MakeMonotonicElement(IndexEvaluator1 values, bool increasing,
1196 IntVar* index);
1198 IntExpr* MakeElement(IndexEvaluator2 values, IntVar* index1, IntVar* index2);
1199
1201 IntExpr* MakeElement(const std::vector<IntVar*>& vars, IntVar* index);
1202
1203#if !defined(SWIG)
1205 IntExpr* MakeElement(Int64ToIntVar vars, int64_t range_start,
1206 int64_t range_end, IntVar* argument);
1207#endif // SWIG
1208
1213
1220 template <typename F>
1221 Constraint* MakeLightElement(F values, IntVar* const var, IntVar* const index,
1222 std::function<bool()> deep_serialize = nullptr) {
1224 this, var, index, std::move(values), std::move(deep_serialize)));
1225 }
1226
1233 template <typename F>
1234 Constraint* MakeLightElement(F values, IntVar* const var,
1235 IntVar* const index1, IntVar* const index2,
1236 std::function<bool()> deep_serialize = nullptr) {
1238 this, var, index1, index2, std::move(values),
1239 std::move(deep_serialize)));
1240 }
1241
1244 IntExpr* MakeIndexExpression(const std::vector<IntVar*>& vars, int64_t value);
1245
1247 Constraint* MakeIfThenElseCt(IntVar* condition, IntExpr* then_expr,
1248 IntExpr* else_expr, IntVar* target_var);
1249
1251 IntExpr* MakeMin(const std::vector<IntVar*>& vars);
1253 IntExpr* MakeMin(IntExpr* left, IntExpr* right);
1255 IntExpr* MakeMin(IntExpr* expr, int64_t value);
1257 IntExpr* MakeMin(IntExpr* expr, int value);
1258
1260 IntExpr* MakeMax(const std::vector<IntVar*>& vars);
1262 IntExpr* MakeMax(IntExpr* left, IntExpr* right);
1264 IntExpr* MakeMax(IntExpr* expr, int64_t value);
1266 IntExpr* MakeMax(IntExpr* expr, int value);
1267
1269 IntExpr* MakeConvexPiecewiseExpr(IntExpr* expr, int64_t early_cost,
1270 int64_t early_date, int64_t late_date,
1271 int64_t late_cost);
1272
1275 IntExpr* MakeSemiContinuousExpr(IntExpr* expr, int64_t fixed_charge,
1276 int64_t step);
1277
1280 // TODO(user): Investigate if we can merge all three piecewise linear
1282#ifndef SWIG
1284 const PiecewiseLinearFunction& f);
1285#endif
1286
1288 IntExpr* MakeModulo(IntExpr* x, int64_t mod);
1289
1292
1295 int64_t unperformed_value);
1296
1301 Constraint* MakeFalseConstraint(const std::string& explanation);
1302
1304 Constraint* MakeIsEqualCstCt(IntExpr* var, int64_t value, IntVar* boolvar);
1312 Constraint* MakeEquality(IntExpr* left, IntExpr* right);
1314 Constraint* MakeEquality(IntExpr* expr, int64_t value);
1316 Constraint* MakeEquality(IntExpr* expr, int value);
1317
1320 IntVar* boolvar);
1328 Constraint* MakeNonEquality(IntExpr* left, IntExpr* right);
1330 Constraint* MakeNonEquality(IntExpr* expr, int64_t value);
1333
1336 IntVar* boolvar);
1344 Constraint* MakeLessOrEqual(IntExpr* left, IntExpr* right);
1346 Constraint* MakeLessOrEqual(IntExpr* expr, int64_t value);
1349
1352 IntVar* boolvar);
1362 Constraint* MakeGreaterOrEqual(IntExpr* expr, int64_t value);
1365
1367 Constraint* MakeIsGreaterCstCt(IntExpr* v, int64_t c, IntVar* b);
1371 IntVar* MakeIsGreaterVar(IntExpr* left, IntExpr* right);
1375 Constraint* MakeGreater(IntExpr* left, IntExpr* right);
1377 Constraint* MakeGreater(IntExpr* expr, int64_t value);
1379 Constraint* MakeGreater(IntExpr* expr, int value);
1380
1382 Constraint* MakeIsLessCstCt(IntExpr* v, int64_t c, IntVar* b);
1386 IntVar* MakeIsLessVar(IntExpr* left, IntExpr* right);
1388 Constraint* MakeIsLessCt(IntExpr* left, IntExpr* right, IntVar* b);
1390 Constraint* MakeLess(IntExpr* left, IntExpr* right);
1392 Constraint* MakeLess(IntExpr* expr, int64_t value);
1394 Constraint* MakeLess(IntExpr* expr, int value);
1395
1397 Constraint* MakeSumLessOrEqual(const std::vector<IntVar*>& vars, int64_t cst);
1398 Constraint* MakeSumGreaterOrEqual(const std::vector<IntVar*>& vars,
1399 int64_t cst);
1400 Constraint* MakeSumEquality(const std::vector<IntVar*>& vars, int64_t cst);
1401 Constraint* MakeSumEquality(const std::vector<IntVar*>& vars, IntVar* var);
1402 Constraint* MakeScalProdEquality(const std::vector<IntVar*>& vars,
1403 const std::vector<int64_t>& coefficients,
1404 int64_t cst);
1405 Constraint* MakeScalProdEquality(const std::vector<IntVar*>& vars,
1406 const std::vector<int>& coefficients,
1407 int64_t cst);
1408 Constraint* MakeScalProdEquality(const std::vector<IntVar*>& vars,
1409 const std::vector<int64_t>& coefficients,
1410 IntVar* target);
1411 Constraint* MakeScalProdEquality(const std::vector<IntVar*>& vars,
1412 const std::vector<int>& coefficients,
1413 IntVar* target);
1414 Constraint* MakeScalProdGreaterOrEqual(const std::vector<IntVar*>& vars,
1415 const std::vector<int64_t>& coeffs,
1416 int64_t cst);
1417 Constraint* MakeScalProdGreaterOrEqual(const std::vector<IntVar*>& vars,
1418 const std::vector<int>& coeffs,
1419 int64_t cst);
1420 Constraint* MakeScalProdLessOrEqual(const std::vector<IntVar*>& vars,
1421 const std::vector<int64_t>& coefficients,
1422 int64_t cst);
1423 Constraint* MakeScalProdLessOrEqual(const std::vector<IntVar*>& vars,
1424 const std::vector<int>& coefficients,
1425 int64_t cst);
1426
1427 Constraint* MakeMinEquality(const std::vector<IntVar*>& vars,
1428 IntVar* min_var);
1429 Constraint* MakeMaxEquality(const std::vector<IntVar*>& vars,
1430 IntVar* max_var);
1431
1432 Constraint* MakeElementEquality(const std::vector<int64_t>& vals,
1433 IntVar* index, IntVar* target);
1434 Constraint* MakeElementEquality(const std::vector<int>& vals, IntVar* index,
1435 IntVar* target);
1436 Constraint* MakeElementEquality(const std::vector<IntVar*>& vars,
1437 IntVar* index, IntVar* target);
1438 Constraint* MakeElementEquality(const std::vector<IntVar*>& vars,
1439 IntVar* index, int64_t target);
1446 Constraint* MakeIndexOfConstraint(const std::vector<IntVar*>& vars,
1447 IntVar* index, int64_t target);
1448
1456#if !defined(SWIG)
1458 Demon* MakeActionDemon(Action action);
1459#endif
1461 Demon* MakeClosureDemon(Closure closure);
1462
1463 // ----- Between and related constraints -----
1464
1466 Constraint* MakeBetweenCt(IntExpr* expr, int64_t l, int64_t u);
1467
1472 Constraint* MakeNotBetweenCt(IntExpr* expr, int64_t l, int64_t u);
1473
1475 Constraint* MakeIsBetweenCt(IntExpr* expr, int64_t l, int64_t u, IntVar* b);
1476 IntVar* MakeIsBetweenVar(IntExpr* v, int64_t l, int64_t u);
1477
1478 // ----- Member and related constraints -----
1479
1482 Constraint* MakeMemberCt(IntExpr* expr, const std::vector<int64_t>& values);
1483 Constraint* MakeMemberCt(IntExpr* expr, const std::vector<int>& values);
1484
1487 const std::vector<int64_t>& values);
1488 Constraint* MakeNotMemberCt(IntExpr* expr, const std::vector<int>& values);
1489
1491 Constraint* MakeNotMemberCt(IntExpr* expr, std::vector<int64_t> starts,
1492 std::vector<int64_t> ends);
1494 Constraint* MakeNotMemberCt(IntExpr* expr, std::vector<int> starts,
1495 std::vector<int> ends);
1496#if !defined(SWIG)
1499 SortedDisjointIntervalList intervals);
1500#endif // !defined(SWIG)
1501
1503 Constraint* MakeIsMemberCt(IntExpr* expr, const std::vector<int64_t>& values,
1504 IntVar* boolvar);
1505 Constraint* MakeIsMemberCt(IntExpr* expr, const std::vector<int>& values,
1506 IntVar* boolvar);
1507 IntVar* MakeIsMemberVar(IntExpr* expr, const std::vector<int64_t>& values);
1508 IntVar* MakeIsMemberVar(IntExpr* expr, const std::vector<int>& values);
1509
1511 Constraint* MakeAtMost(std::vector<IntVar*> vars, int64_t value,
1512 int64_t max_count);
1514 Constraint* MakeCount(const std::vector<IntVar*>& vars, int64_t value,
1515 int64_t max_count);
1517 Constraint* MakeCount(const std::vector<IntVar*>& vars, int64_t value,
1518 IntVar* max_count);
1519
1521 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1522 const std::vector<int64_t>& values,
1523 const std::vector<IntVar*>& cards);
1525 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1526 const std::vector<int>& values,
1527 const std::vector<IntVar*>& cards);
1529 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1530 const std::vector<IntVar*>& cards);
1533 Constraint* MakeDistribute(const std::vector<IntVar*>& vars, int64_t card_min,
1534 int64_t card_max, int64_t card_size);
1538 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1539 const std::vector<int64_t>& card_min,
1540 const std::vector<int64_t>& card_max);
1544 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1545 const std::vector<int>& card_min,
1546 const std::vector<int>& card_max);
1550 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1551 const std::vector<int64_t>& values,
1552 const std::vector<int64_t>& card_min,
1553 const std::vector<int64_t>& card_max);
1557 Constraint* MakeDistribute(const std::vector<IntVar*>& vars,
1558 const std::vector<int>& values,
1559 const std::vector<int>& card_min,
1560 const std::vector<int>& card_max);
1561
1566 Constraint* MakeDeviation(const std::vector<IntVar*>& vars,
1567 IntVar* deviation_var, int64_t total_sum);
1568
1571 Constraint* MakeAllDifferent(const std::vector<IntVar*>& vars);
1572
1576 Constraint* MakeAllDifferent(const std::vector<IntVar*>& vars,
1577 bool stronger_propagation);
1578
1581 Constraint* MakeAllDifferentExcept(const std::vector<IntVar*>& vars,
1582 int64_t escape_value);
1583 // TODO(user): Do we need a version with an array of escape values.
1584
1600 Constraint* MakeSortingConstraint(const std::vector<IntVar*>& vars,
1601 const std::vector<IntVar*>& sorted);
1602 // TODO(user): Add void MakeSortedArray(
1603 // const std::vector<IntVar*>& vars,
1604 // std::vector<IntVar*>* const sorted);
1605
1608 Constraint* MakeLexicalLess(const std::vector<IntVar*>& left,
1609 const std::vector<IntVar*>& right);
1610
1613 Constraint* MakeLexicalLessOrEqual(const std::vector<IntVar*>& left,
1614 const std::vector<IntVar*>& right);
1615
1620 Constraint* MakeLexicalLessOrEqualWithOffsets(std::vector<IntVar*> left,
1621 std::vector<IntVar*> right,
1622 std::vector<int64_t> offsets);
1623
1624 // Semi-reified version of the above: boolvar -> LexLE(left, right, offsets).
1626 std::vector<IntVar*> left, std::vector<IntVar*> right,
1627 std::vector<int64_t> offsets, IntVar* boolvar);
1628
1634 const std::vector<IntVar*>& left, const std::vector<IntVar*>& right);
1635
1639 IntVar* index, const std::vector<IntVar*>& vars);
1640
1644 IntVar* index, const std::vector<IntVar*>& vars);
1645
1650 Constraint* MakeNullIntersect(const std::vector<IntVar*>& first_vars,
1651 const std::vector<IntVar*>& second_vars);
1652
1658 Constraint* MakeNullIntersectExcept(const std::vector<IntVar*>& first_vars,
1659 const std::vector<IntVar*>& second_vars,
1660 int64_t escape_value);
1661
1662 // TODO(user): Implement MakeAllNullIntersect taking an array of
1663 // variable vectors.
1664
1674 Constraint* MakeNoCycle(const std::vector<IntVar*>& nexts,
1675 const std::vector<IntVar*>& active,
1676 IndexFilter1 sink_handler = nullptr);
1677 Constraint* MakeNoCycle(const std::vector<IntVar*>& nexts,
1678 const std::vector<IntVar*>& active,
1679 IndexFilter1 sink_handler, bool assume_paths);
1680
1682 Constraint* MakeCircuit(const std::vector<IntVar*>& nexts);
1683
1686 Constraint* MakeSubCircuit(const std::vector<IntVar*>& nexts);
1687
1692 Constraint* MakePathCumul(const std::vector<IntVar*>& nexts,
1693 const std::vector<IntVar*>& active,
1694 const std::vector<IntVar*>& cumuls,
1695 const std::vector<IntVar*>& transits);
1698 // TODO(user): Merge with other path-cumuls constraints.
1699 Constraint* MakeDelayedPathCumul(const std::vector<IntVar*>& nexts,
1700 const std::vector<IntVar*>& active,
1701 const std::vector<IntVar*>& cumuls,
1702 const std::vector<IntVar*>& transits);
1709 Constraint* MakePathCumul(const std::vector<IntVar*>& nexts,
1710 const std::vector<IntVar*>& active,
1711 const std::vector<IntVar*>& cumuls,
1712 IndexEvaluator2 transit_evaluator);
1713
1720 Constraint* MakePathCumul(const std::vector<IntVar*>& nexts,
1721 const std::vector<IntVar*>& active,
1722 const std::vector<IntVar*>& cumuls,
1723 const std::vector<IntVar*>& slacks,
1724 IndexEvaluator2 transit_evaluator);
1727 // TODO(user): Only does checking on WhenBound events on next variables.
1729 Constraint* MakePathConnected(std::vector<IntVar*> nexts,
1730 std::vector<int64_t> sources,
1731 std::vector<int64_t> sinks,
1732 std::vector<IntVar*> status);
1733#ifndef SWIG
1736 // TODO(user): This constraint does not make holes in variable domains;
1740 std::vector<IntVar*> nexts,
1741 const std::vector<std::pair<int, int>>& precedences);
1751 std::vector<IntVar*> nexts,
1752 const std::vector<std::pair<int, int>>& precedences,
1753 absl::Span<const int> lifo_path_starts,
1754 absl::Span<const int> fifo_path_starts);
1758 std::vector<IntVar*> nexts, std::vector<IntVar*> transits,
1759 const std::vector<std::pair<int, int>>& precedences);
1775 std::vector<IntVar*> nexts;
1776 std::vector<IntVar*> paths;
1777 std::vector<IntVar*> forces;
1778 std::vector<IntVar*> distances;
1779 std::vector<int64_t> path_unit_costs;
1780 std::vector<bool> path_used_when_empty;
1781 std::vector<int64_t> path_starts;
1782 std::vector<int64_t> path_ends;
1783 std::vector<IntVar*> costs;
1784 };
1786 PathEnergyCostConstraintSpecification specification);
1787#endif // !SWIG
1791 Constraint* MakeMapDomain(IntVar* var, const std::vector<IntVar*>& actives);
1792
1797 Constraint* MakeAllowedAssignments(const std::vector<IntVar*>& vars,
1798 const IntTupleSet& tuples);
1799
1808 const std::vector<IntVar*>& vars, const IntTupleSet& transition_table,
1809 int64_t initial_state, const std::vector<int64_t>& final_states);
1818 Constraint* MakeTransitionConstraint(const std::vector<IntVar*>& vars,
1819 const IntTupleSet& transition_table,
1820 int64_t initial_state,
1821 const std::vector<int>& final_states);
1822
1823#if defined(SWIGPYTHON)
1826 const std::vector<IntVar*>& vars,
1827 const std::vector<std::vector<int64_t> /*keep for swig*/>& raw_tuples) {
1828 IntTupleSet tuples(vars.size());
1829 tuples.InsertAll(raw_tuples);
1830 return MakeAllowedAssignments(vars, tuples);
1831 }
1832
1834 const std::vector<IntVar*>& vars,
1835 const std::vector<std::vector<int64_t> /*keep for swig*/>&
1836 raw_transitions,
1837 int64_t initial_state, const std::vector<int>& final_states) {
1838 IntTupleSet transitions(3);
1839 transitions.InsertAll(raw_transitions);
1840 return MakeTransitionConstraint(vars, transitions, initial_state,
1841 final_states);
1842 }
1843#endif
1844
1854 const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars,
1855 const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size);
1857 const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars,
1858 absl::Span<const int64_t> x_size, absl::Span<const int64_t> y_size);
1860 const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars,
1861 absl::Span<const int> x_size, absl::Span<const int> y_size);
1862
1872 const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars,
1873 const std::vector<IntVar*>& x_size, const std::vector<IntVar*>& y_size);
1875 const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars,
1876 absl::Span<const int64_t> x_size, absl::Span<const int64_t> y_size);
1878 const std::vector<IntVar*>& x_vars, const std::vector<IntVar*>& y_vars,
1879 absl::Span<const int> x_size, absl::Span<const int> y_size);
1880
1886 Pack* MakePack(const std::vector<IntVar*>& vars, int number_of_bins);
1887
1893 int64_t start_max, int64_t duration,
1894 bool optional,
1895 const std::string& name);
1896
1899 void MakeFixedDurationIntervalVarArray(int count, int64_t start_min,
1900 int64_t start_max, int64_t duration,
1901 bool optional, absl::string_view name,
1902 std::vector<IntervalVar*>* array);
1903
1907 int64_t duration,
1908 const std::string& name);
1909
1913 int64_t duration,
1914 IntVar* performed_variable,
1915 const std::string& name);
1916
1920 const std::vector<IntVar*>& start_variables, int64_t duration,
1921 absl::string_view name, std::vector<IntervalVar*>* array);
1922
1926 const std::vector<IntVar*>& start_variables,
1927 absl::Span<const int64_t> durations, absl::string_view name,
1928 std::vector<IntervalVar*>* array);
1932 const std::vector<IntVar*>& start_variables,
1933 absl::Span<const int> durations, absl::string_view name,
1934 std::vector<IntervalVar*>* array);
1935
1939 const std::vector<IntVar*>& start_variables,
1940 absl::Span<const int64_t> durations,
1941 const std::vector<IntVar*>& performed_variables, absl::string_view name,
1942 std::vector<IntervalVar*>* array);
1943
1947 const std::vector<IntVar*>& start_variables,
1948 absl::Span<const int> durations,
1949 const std::vector<IntVar*>& performed_variables, absl::string_view name,
1950 std::vector<IntervalVar*>* array);
1951
1953 IntervalVar* MakeFixedInterval(int64_t start, int64_t duration,
1954 const std::string& name);
1955
1959 int64_t duration_min, int64_t duration_max,
1960 int64_t end_min, int64_t end_max, bool optional,
1961 const std::string& name);
1962
1965 void MakeIntervalVarArray(int count, int64_t start_min, int64_t start_max,
1966 int64_t duration_min, int64_t duration_max,
1967 int64_t end_min, int64_t end_max, bool optional,
1968 absl::string_view name,
1969 std::vector<IntervalVar*>* array);
1970
1974
1980 IntervalVar* interval_var, int64_t duration, int64_t offset);
1981
1987 IntervalVar* interval_var, int64_t duration, int64_t offset);
1988
1994 IntervalVar* interval_var, int64_t duration, int64_t offset);
1995
2001 IntervalVar* interval_var, int64_t duration, int64_t offset);
2002
2021
2040
2044 int64_t d);
2045
2048 IntervalVar* t2);
2049
2056 IntervalVar* t2, int64_t delay);
2057
2062 IntVar* alt);
2063
2067
2071 const std::vector<IntervalVar*>& intervals, const std::string& name);
2072
2077 const std::vector<IntervalVar*>& intervals, const std::string& name);
2078
2088 Constraint* MakeCumulative(const std::vector<IntervalVar*>& intervals,
2089 const std::vector<int64_t>& demands,
2090 int64_t capacity, const std::string& name);
2091
2101 Constraint* MakeCumulative(const std::vector<IntervalVar*>& intervals,
2102 const std::vector<int>& demands, int64_t capacity,
2103 const std::string& name);
2104
2114 Constraint* MakeCumulative(const std::vector<IntervalVar*>& intervals,
2115 const std::vector<int64_t>& demands,
2116 IntVar* capacity, absl::string_view name);
2117
2127 Constraint* MakeCumulative(const std::vector<IntervalVar*>& intervals,
2128 const std::vector<int>& demands, IntVar* capacity,
2129 const std::string& name);
2130
2138 Constraint* MakeCumulative(const std::vector<IntervalVar*>& intervals,
2139 const std::vector<IntVar*>& demands,
2140 int64_t capacity, const std::string& name);
2141
2149 Constraint* MakeCumulative(const std::vector<IntervalVar*>& intervals,
2150 const std::vector<IntVar*>& demands,
2151 IntVar* capacity, const std::string& name);
2152
2158 Constraint* MakeCover(const std::vector<IntervalVar*>& vars,
2159 IntervalVar* target_var);
2160
2163
2166
2169
2175
2181
2187 const Assignment* assignment, bool maximize);
2191 const Assignment* assignment, std::vector<bool> maximize);
2201 std::vector<bool> maximize);
2202
2207 const Assignment* assignment, int solution_count, bool maximize);
2209 bool maximize);
2213 const Assignment* assignment, int solution_count,
2214 std::vector<bool> maximize);
2216 int solution_count, std::vector<bool> maximize);
2217
2223
2225 OptimizeVar* MakeMinimize(IntVar* v, int64_t step);
2226
2228 OptimizeVar* MakeMaximize(IntVar* v, int64_t step);
2229
2231 OptimizeVar* MakeOptimize(bool maximize, IntVar* v, int64_t step);
2232
2235 OptimizeVar* MakeWeightedMinimize(const std::vector<IntVar*>& sub_objectives,
2236 const std::vector<int64_t>& weights,
2237 int64_t step);
2238
2241 OptimizeVar* MakeWeightedMinimize(const std::vector<IntVar*>& sub_objectives,
2242 const std::vector<int>& weights,
2243 int64_t step);
2244
2246 OptimizeVar* MakeWeightedMaximize(const std::vector<IntVar*>& sub_objectives,
2247 const std::vector<int64_t>& weights,
2248 int64_t step);
2249
2251 OptimizeVar* MakeWeightedMaximize(const std::vector<IntVar*>& sub_objectives,
2252 const std::vector<int>& weights,
2253 int64_t step);
2254
2256 OptimizeVar* MakeWeightedOptimize(bool maximize,
2257 const std::vector<IntVar*>& sub_objectives,
2258 const std::vector<int64_t>& weights,
2259 int64_t step);
2260
2262 OptimizeVar* MakeWeightedOptimize(bool maximize,
2263 const std::vector<IntVar*>& sub_objectives,
2264 const std::vector<int>& weights,
2265 int64_t step);
2266
2269 OptimizeVar* MakeLexicographicOptimize(std::vector<bool> maximize,
2270 std::vector<IntVar*> variables,
2271 std::vector<int64_t> steps);
2272
2274
2290
2291 ObjectiveMonitor* MakeTabuSearch(bool maximize, IntVar* objective,
2292 int64_t step,
2293 const std::vector<IntVar*>& vars,
2294 int64_t keep_tenure, int64_t forbid_tenure,
2295 double tabu_factor);
2296
2298 const std::vector<bool>& maximize, std::vector<IntVar*> objectives,
2299 std::vector<int64_t> steps, const std::vector<IntVar*>& vars,
2300 int64_t keep_tenure, int64_t forbid_tenure, double tabu_factor);
2301
2305 int64_t step,
2306 const std::vector<IntVar*>& tabu_vars,
2307 int64_t forbid_tenure);
2308
2310 // TODO(user): document behavior
2312 int64_t step,
2313 int64_t initial_temperature);
2315 const std::vector<bool>& maximize, std::vector<IntVar*> vars,
2316 std::vector<int64_t> steps, std::vector<int64_t> initial_temperatures);
2317
2321 bool maximize, IntVar* objective, IndexEvaluator2 objective_function,
2322 int64_t step, const std::vector<IntVar*>& vars, double penalty_factor,
2323 bool reset_penalties_on_new_best_solution = false);
2325 bool maximize, IntVar* objective, IndexEvaluator3 objective_function,
2326 int64_t step, const std::vector<IntVar*>& vars,
2327 const std::vector<IntVar*>& secondary_vars, double penalty_factor,
2328 bool reset_penalties_on_new_best_solution = false);
2329
2333 SearchMonitor* MakeLubyRestart(int scale_factor);
2334
2337 SearchMonitor* MakeConstantRestart(int frequency);
2338
2340 ABSL_MUST_USE_RESULT RegularLimit* MakeTimeLimit(absl::Duration time);
2341#if !defined(SWIG)
2342 ABSL_DEPRECATED("Use the version taking absl::Duration() as argument")
2343#endif // !defined(SWIG)
2344 ABSL_MUST_USE_RESULT RegularLimit* MakeTimeLimit(int64_t time_in_ms) {
2345 return MakeTimeLimit(time_in_ms == kint64max
2346 ? absl::InfiniteDuration()
2347 : absl::Milliseconds(time_in_ms));
2348 }
2349
2352 ABSL_MUST_USE_RESULT RegularLimit* MakeBranchesLimit(int64_t branches);
2353
2356 ABSL_MUST_USE_RESULT RegularLimit* MakeFailuresLimit(int64_t failures);
2357
2360 ABSL_MUST_USE_RESULT RegularLimit* MakeSolutionsLimit(int64_t solutions);
2361
2364 // timer by estimating the number of remaining calls, and 'cumulative' means
2365 // that the limit applies cumulatively, instead of search-by-search.
2366 ABSL_MUST_USE_RESULT RegularLimit* MakeLimit(absl::Duration time,
2367 int64_t branches,
2368 int64_t failures,
2369 int64_t solutions,
2370 bool smart_time_check = false,
2371 bool cumulative = false);
2373 ABSL_MUST_USE_RESULT RegularLimit* MakeLimit(
2374 const RegularLimitParameters& proto);
2375
2376#if !defined(SWIG)
2377 ABSL_DEPRECATED("Use other MakeLimit() versions")
2378#endif // !defined(SWIG)
2379 ABSL_MUST_USE_RESULT RegularLimit* MakeLimit(int64_t time, int64_t branches,
2380 int64_t failures,
2381 int64_t solutions,
2382 bool smart_time_check = false,
2383 bool cumulative = false);
2384
2386 RegularLimitParameters MakeDefaultRegularLimitParameters() const;
2387
2391 ABSL_MUST_USE_RESULT SearchLimit* MakeLimit(SearchLimit* limit_1,
2392 SearchLimit* limit_2);
2393
2398 ABSL_MUST_USE_RESULT ImprovementSearchLimit* MakeImprovementLimit(
2399 IntVar* objective_var, bool maximize, double objective_scaling_factor,
2400 double objective_offset, double improvement_rate_coefficient,
2401 int improvement_rate_solutions_distance);
2404 ABSL_MUST_USE_RESULT ImprovementSearchLimit*
2406 std::vector<IntVar*> objective_vars, std::vector<bool> maximize,
2407 std::vector<double> objective_scaling_factors,
2408 std::vector<double> objective_offsets,
2409 double improvement_rate_coefficient,
2410 int improvement_rate_solutions_distance);
2411
2414 ABSL_MUST_USE_RESULT SearchLimit* MakeCustomLimit(
2415 std::function<bool()> limiter);
2416
2417 // TODO(user): DEPRECATE API of MakeSearchLog(.., IntVar* var,..).
2418
2421 SearchMonitor* MakeSearchLog(int branch_period);
2422
2424 SearchMonitor* MakeSearchLog(int branch_period, IntVar* var);
2425
2428 SearchMonitor* MakeSearchLog(int branch_period,
2429 std::function<std::string()> display_callback);
2430
2433 SearchMonitor* MakeSearchLog(int branch_period, IntVar* var,
2434 std::function<std::string()> display_callback);
2435
2438 SearchMonitor* MakeSearchLog(int branch_period, std::vector<IntVar*> vars,
2439 std::function<std::string()> display_callback);
2440
2443 SearchMonitor* MakeSearchLog(int branch_period, OptimizeVar* opt_var);
2444
2447 SearchMonitor* MakeSearchLog(int branch_period, OptimizeVar* opt_var,
2448 std::function<std::string()> display_callback);
2449
2451 struct SearchLogParameters {
2454 int branch_period = 1;
2457 OptimizeVar* objective = nullptr;
2458 std::vector<IntVar*> variables;
2462 std::vector<double> scaling_factors;
2463 std::vector<double> offsets;
2467 std::function<std::string()> display_callback;
2471 };
2472 SearchMonitor* MakeSearchLog(SearchLogParameters parameters);
2473
2476 SearchMonitor* MakeSearchTrace(const std::string& prefix);
2477
2479 SearchMonitor* MakeEnterSearchCallback(std::function<void()> callback);
2480 SearchMonitor* MakeExitSearchCallback(std::function<void()> callback);
2481 SearchMonitor* MakeAtSolutionCallback(std::function<void()> callback);
2482
2484 ModelVisitor* MakePrintModelVisitor();
2486 ModelVisitor* MakeStatisticsModelVisitor();
2487#if !defined(SWIG)
2489 ModelVisitor* MakeVariableDegreeVisitor(
2490 absl::flat_hash_map<const IntVar*, int>* map);
2491#endif // !defined(SWIG)
2492
2495 const std::vector<SymmetryBreaker*>& visitors);
2496 SearchMonitor* MakeSymmetryManager(SymmetryBreaker* v1);
2499 SymmetryBreaker* v3);
2502
2508 bool start_with_lower_half);
2511 Decision* MakeAssignVariablesValues(const std::vector<IntVar*>& vars,
2512 const std::vector<int64_t>& values);
2514 const std::vector<IntVar*>& vars, const std::vector<int64_t>& values);
2515 Decision* MakeAssignVariablesValuesOrFail(const std::vector<IntVar*>& vars,
2516 const std::vector<int64_t>& values);
2518 Decision* MakeDecision(Action apply, Action refute);
2519
2530 DecisionBuilder* db3);
2532 DecisionBuilder* db3, DecisionBuilder* db4);
2533 DecisionBuilder* Compose(const std::vector<DecisionBuilder*>& dbs);
2534
2546 // TODO(user): The search tree can be balanced by using binary
2553 DecisionBuilder* db3);
2555 DecisionBuilder* db3, DecisionBuilder* db4);
2556 DecisionBuilder* Try(const std::vector<DecisionBuilder*>& dbs);
2557
2559 // TODO(user): name each of them differently, and document them (and do that
2561 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2562 IntVarStrategy var_str, IntValueStrategy val_str);
2563 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2564 IndexEvaluator1 var_evaluator,
2565 IntValueStrategy val_str);
2566
2567 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2568 IntVarStrategy var_str,
2569 IndexEvaluator2 value_evaluator);
2570
2573 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2574 IntVarStrategy var_str,
2575 VariableValueComparator var_val1_val2_comparator);
2576
2577 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2578 IndexEvaluator1 var_evaluator,
2579 IndexEvaluator2 value_evaluator);
2580
2581 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2582 IntVarStrategy var_str,
2583 IndexEvaluator2 value_evaluator,
2584 IndexEvaluator1 tie_breaker);
2585
2586 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2587 IndexEvaluator1 var_evaluator,
2588 IndexEvaluator2 value_evaluator,
2589 IndexEvaluator1 tie_breaker);
2590
2591 DecisionBuilder* MakeDefaultPhase(const std::vector<IntVar*>& vars);
2592 DecisionBuilder* MakeDefaultPhase(const std::vector<IntVar*>& vars,
2594
2597 IntValueStrategy val_str);
2599 IntValueStrategy val_str);
2601 IntVarStrategy var_str, IntValueStrategy val_str);
2602 DecisionBuilder* MakePhase(IntVar* v0, IntVar* v1, IntVar* v2, IntVar* v3,
2603 IntVarStrategy var_str, IntValueStrategy val_str);
2604
2611 int64_t* marker);
2612
2619 int64_t* marker);
2620
2624
2628
2634 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2636
2644 DecisionBuilder* MakePhase(const std::vector<IntVar*>& vars,
2645 IndexEvaluator2 eval, IndexEvaluator1 tie_breaker,
2646 EvaluatorStrategy str);
2647
2649 DecisionBuilder* MakePhase(const std::vector<IntervalVar*>& intervals,
2650 IntervalStrategy str);
2651
2652 DecisionBuilder* MakePhase(const std::vector<SequenceVar*>& sequences,
2653 SequenceStrategy str);
2654
2658 Assignment* assignment, DecisionBuilder* db,
2659 const std::vector<IntVar*>& vars);
2660
2664
2672 SearchMonitor* monitor2);
2674 SearchMonitor* monitor2,
2675 SearchMonitor* monitor3);
2677 SearchMonitor* monitor2,
2678 SearchMonitor* monitor3,
2679 SearchMonitor* monitor4);
2681 const std::vector<SearchMonitor*>& monitors);
2682
2691 bool maximize, int64_t step);
2693 bool maximize, int64_t step,
2694 SearchMonitor* monitor1);
2696 bool maximize, int64_t step,
2697 SearchMonitor* monitor1,
2698 SearchMonitor* monitor2);
2700 bool maximize, int64_t step,
2701 SearchMonitor* monitor1,
2702 SearchMonitor* monitor2,
2703 SearchMonitor* monitor3);
2705 bool maximize, int64_t step,
2706 SearchMonitor* monitor1,
2707 SearchMonitor* monitor2,
2708 SearchMonitor* monitor3,
2709 SearchMonitor* monitor4);
2711 DecisionBuilder* db, Assignment* solution, bool maximize, int64_t step,
2712 const std::vector<SearchMonitor*>& monitors);
2713
2717
2721
2724 const std::vector<IntVar*>& vars, LocalSearchOperators op,
2725 std::function<const std::vector<int>&(int, int)> get_neighbors = nullptr);
2727 const std::vector<IntVar*>& vars,
2728 const std::vector<IntVar*>& secondary_vars, LocalSearchOperators op,
2729 std::function<const std::vector<int>&(int, int)> get_neighbors = nullptr);
2730 // TODO(user): Make the callback an IndexEvaluator2 when there are no
2731 // secondary variables.
2732 LocalSearchOperator* MakeOperator(const std::vector<IntVar*>& vars,
2733 IndexEvaluator3 evaluator,
2735 LocalSearchOperator* MakeOperator(const std::vector<IntVar*>& vars,
2736 const std::vector<IntVar*>& secondary_vars,
2737 IndexEvaluator3 evaluator,
2739
2747 LocalSearchOperator* MakeRandomLnsOperator(const std::vector<IntVar*>& vars,
2748 int number_of_variables);
2749 LocalSearchOperator* MakeRandomLnsOperator(const std::vector<IntVar*>& vars,
2750 int number_of_variables,
2751 int32_t seed);
2752
2759
2767 const std::vector<IntVar*>& variables,
2768 const std::vector<int64_t>& target_values);
2769
2801 const std::vector<LocalSearchOperator*>& ops);
2803 const std::vector<LocalSearchOperator*>& ops, bool restart);
2805 const std::vector<LocalSearchOperator*>& ops,
2806 std::function<int64_t(int, int)> evaluator);
2810 const std::vector<LocalSearchOperator*>& ops);
2811
2816 const std::vector<LocalSearchOperator*>& ops, int32_t seed);
2817
2826 const std::vector<LocalSearchOperator*>& ops, double memory_coefficient,
2827 double exploration_coefficient, bool maximize);
2828
2835 int64_t limit);
2836
2861 // TODO(user): Make a variant which runs a local search after each
2862 // solution found in a DFS.
2863
2866 DecisionBuilder* MakeLocalSearchPhase(const std::vector<IntVar*>& vars,
2867 DecisionBuilder* first_solution,
2871 const std::vector<IntVar*>& vars, DecisionBuilder* first_solution,
2872 DecisionBuilder* first_solution_sub_decision_builder,
2874 DecisionBuilder* MakeLocalSearchPhase(const std::vector<SequenceVar*>& vars,
2875 DecisionBuilder* first_solution,
2877
2883 const Assignment* initial_solution,
2884 LocalSearchFilterManager* filter_manager,
2885 LocalSearchOperator* ls_operator,
2886 const std::vector<SearchMonitor*>& monitors, RegularLimit* limit,
2887 absl::flat_hash_set<IntVar*>* touched = nullptr);
2888
2891
2894 IntVar* objective, LocalSearchOperator* ls_operator,
2895 DecisionBuilder* sub_decision_builder);
2897 IntVar* objective, LocalSearchOperator* ls_operator,
2898 DecisionBuilder* sub_decision_builder, RegularLimit* limit);
2900 IntVar* objective, LocalSearchOperator* ls_operator,
2901 DecisionBuilder* sub_decision_builder, RegularLimit* limit,
2902 LocalSearchFilterManager* filter_manager);
2903
2905 IntVar* objective, SolutionPool* pool, LocalSearchOperator* ls_operator,
2906 DecisionBuilder* sub_decision_builder);
2908 IntVar* objective, SolutionPool* pool, LocalSearchOperator* ls_operator,
2909 DecisionBuilder* sub_decision_builder, RegularLimit* limit);
2911 IntVar* objective, SolutionPool* pool, LocalSearchOperator* ls_operator,
2912 DecisionBuilder* sub_decision_builder, RegularLimit* limit,
2913 LocalSearchFilterManager* filter_manager);
2914
2920 const std::vector<IntVar*>& vars, IndexEvaluator2 values,
2921 Solver::LocalSearchFilterBound filter_enum);
2923 const std::vector<IntVar*>& vars,
2924 const std::vector<IntVar*>& secondary_vars, IndexEvaluator3 values,
2925 Solver::LocalSearchFilterBound filter_enum);
2926
2929 void TopPeriodicCheck();
2933 int TopProgressPercent();
2934
2938 void PushState();
2939 void PopState();
2940
2943 int SearchDepth() const;
2944
2947 int SearchLeftDepth() const;
2948
2951 int SolveDepth() const;
2952
2955
2958
2960 template <class T>
2961 void SaveAndSetValue(T* adr, T val) {
2962 if (*adr != val) {
2963 InternalSaveValue(adr);
2964 *adr = val;
2965 }
2966 }
2967
2969 template <class T>
2970 void SaveAndAdd(T* adr, T val) {
2971 if (val != 0) {
2972 InternalSaveValue(adr);
2973 (*adr) += val;
2974 }
2975 }
2976
2978 int64_t Rand64(int64_t size) {
2979 DCHECK_GT(size, 0);
2980 return absl::Uniform<int64_t>(random_, 0, size);
2981 }
2982
2984 int32_t Rand32(int32_t size) {
2985 DCHECK_GT(size, 0);
2986 return absl::Uniform<int32_t>(random_, 0, size);
2987 }
2988
2990 void ReSeed(int32_t seed) { random_.seed(seed); }
2991
2995 void ExportProfilingOverview(const std::string& filename);
2996
2998 // TODO(user): Merge demon and local search profiles.
2999 std::string LocalSearchProfile() const;
3000
3001#if !defined(SWIG)
3003 ConstraintSolverStatistics GetConstraintSolverStatistics() const;
3005 LocalSearchStatistics GetLocalSearchStatistics() const;
3006#endif // !defined(SWIG)
3007
3011 bool CurrentlyInSolve() const;
3012
3015 int constraints() const { return constraints_list_.size(); }
3016
3018 void Accept(ModelVisitor* visitor) const;
3019
3020 Decision* balancing_decision() const { return balancing_decision_.get(); }
3021
3023#if !defined(SWIG)
3024 void set_fail_intercept(std::function<void()> fail_intercept) {
3025 fail_intercept_ = std::move(fail_intercept);
3027#endif // !defined(SWIG)
3028 void clear_fail_intercept() { fail_intercept_ = nullptr; }
3030 DemonProfiler* demon_profiler() const { return demon_profiler_; }
3031 // TODO(user): Get rid of the following methods once fast local search is
3034 void SetUseFastLocalSearch(bool use_fast_local_search) {
3035 use_fast_local_search_ = use_fast_local_search;
3036 }
3038 bool UseFastLocalSearch() const { return use_fast_local_search_; }
3040 bool HasName(const PropagationBaseObject* object) const;
3042 Demon* RegisterDemon(Demon* demon);
3050
3052 Search* ActiveSearch() const;
3054 ModelCache* Cache() const;
3056 bool InstrumentsDemons() const;
3058 bool IsProfilingEnabled() const;
3060 bool IsLocalSearchProfilingEnabled() const;
3062 bool InstrumentsVariables() const;
3064 bool NameAllVariables() const;
3066 std::string model_name() const;
3077 void SetSearchContext(Search* search, absl::string_view search_context);
3078 std::string SearchContext() const;
3079 std::string SearchContext(const Search* search) const;
3081 // TODO(user): Investigate if this should be moved to Search.
3084 void ClearLocalSearchState() { local_search_state_.reset(nullptr); }
3085
3090 std::vector<int64_t> tmp_vector_;
3091
3092 friend class BaseIntExpr;
3093 friend class Constraint;
3094 friend class DemonProfiler;
3095 friend class FindOneNeighbor;
3096 friend class IntVar;
3097 friend class PropagationBaseObject;
3098 friend class Queue;
3099 friend class SearchMonitor;
3100 friend class SearchLimit;
3101 friend class RoutingModel;
3102 friend class LocalSearch;
3103 friend class LocalSearchProfiler;
3104
3105#if !defined(SWIG)
3107 template <class>
3108 friend class SimpleRevFIFO;
3109 template <class K, class V>
3110 friend class RevImmutableMultiMap;
3111
3116 bool IsBooleanVar(IntExpr* expr, IntVar** inner_var, bool* is_negated) const;
3117
3122 bool IsProduct(IntExpr* expr, IntExpr** inner_expr, int64_t* coefficient);
3123#endif
3124
3127 IntExpr* CastExpression(const IntVar* var) const;
3128
3130 void FinishCurrentSearch();
3131 void RestartCurrentSearch();
3132
3135 void ShouldFail() { should_fail_ = true; }
3136 void CheckFail() {
3137 if (!should_fail_) return;
3138 should_fail_ = false;
3139 Fail();
3141
3144
3145 private:
3146 void Init();
3147 void PushState(MarkerType t, const StateInfo& info);
3149 void PushSentinel(int magic_code);
3150 void BacktrackToSentinel(int magic_code);
3151 void ProcessConstraints();
3152 bool BacktrackOneLevel(Decision** fail_decision);
3153 void JumpToSentinelWhenNested();
3154 void JumpToSentinel();
3155 void check_alloc_state();
3156 void FreezeQueue();
3157 void EnqueueVar(Demon* d);
3158 void EnqueueDelayedDemon(Demon* d);
3159 void ExecuteAll(const SimpleRevFIFO<Demon*>& demons);
3160 void EnqueueAll(const SimpleRevFIFO<Demon*>& demons);
3161 void UnfreezeQueue();
3162 void reset_action_on_fail();
3163 void set_action_on_fail(Action a);
3164 void set_variable_to_clean_on_fail(IntVar* v);
3165 void IncrementUncheckedSolutionCounter();
3166 bool IsUncheckedSolutionLimitReached();
3167
3168 void InternalSaveValue(int* valptr);
3169 void InternalSaveValue(int64_t* valptr);
3170 void InternalSaveValue(uint64_t* valptr);
3171 void InternalSaveValue(double* valptr);
3172 void InternalSaveValue(bool* valptr);
3173 void InternalSaveValue(void** valptr);
3174 void InternalSaveValue(int64_t** valptr) {
3175 InternalSaveValue(reinterpret_cast<void**>(valptr));
3176 }
3177
3178 BaseObject* SafeRevAlloc(BaseObject* ptr);
3179
3180 int* SafeRevAllocArray(int* ptr);
3181 int64_t* SafeRevAllocArray(int64_t* ptr);
3182 uint64_t* SafeRevAllocArray(uint64_t* ptr);
3183 double* SafeRevAllocArray(double* ptr);
3184 BaseObject** SafeRevAllocArray(BaseObject** ptr);
3185 IntVar** SafeRevAllocArray(IntVar** ptr);
3186 IntExpr** SafeRevAllocArray(IntExpr** ptr);
3187 Constraint** SafeRevAllocArray(Constraint** ptr);
3190 void* UnsafeRevAllocAux(void* ptr);
3191 template <class T>
3192 T* UnsafeRevAlloc(T* ptr) {
3193 return reinterpret_cast<T*>(
3194 UnsafeRevAllocAux(reinterpret_cast<void*>(ptr)));
3195 }
3196 void** UnsafeRevAllocArrayAux(void** ptr);
3197 template <class T>
3198 T** UnsafeRevAllocArray(T** ptr) {
3199 return reinterpret_cast<T**>(
3200 UnsafeRevAllocArrayAux(reinterpret_cast<void**>(ptr)));
3201 }
3202
3203 void InitCachedIntConstants();
3204 void InitCachedConstraint();
3205
3209 Search* TopLevelSearch() const { return searches_.at(1); }
3213 Search* ParentSearch() const {
3214 const size_t search_size = searches_.size();
3215 DCHECK_GT(search_size, 1);
3216 return searches_[search_size - 2];
3217 }
3218
3219 template <bool is_profile_active>
3220 Assignment* RunUncheckedLocalSearchInternal(
3221 const Assignment* initial_solution,
3222 LocalSearchFilterManager* filter_manager,
3223 LocalSearchOperator* ls_operator,
3224 const std::vector<SearchMonitor*>& monitors, RegularLimit* limit,
3225 absl::flat_hash_set<IntVar*>* touched);
3226
3228 std::string GetName(const PropagationBaseObject* object);
3229 void SetName(const PropagationBaseObject* object, absl::string_view name);
3230
3233 int GetNewIntVarIndex() { return num_int_vars_++; }
3234
3236 bool IsADifference(IntExpr* expr, IntExpr** left, IntExpr** right);
3237
3238 const std::string name_;
3239 const ConstraintSolverParameters parameters_;
3240 absl::flat_hash_map<const PropagationBaseObject*, std::string>
3241 propagation_object_names_;
3242 absl::flat_hash_map<const PropagationBaseObject*, IntegerCastInfo>
3243 cast_information_;
3244 absl::flat_hash_set<const Constraint*> cast_constraints_;
3245 const std::string empty_name_;
3246 std::unique_ptr<Queue> queue_;
3247 std::unique_ptr<Trail> trail_;
3248 std::vector<Constraint*> constraints_list_;
3249 std::vector<Constraint*> additional_constraints_list_;
3250 std::vector<int> additional_constraints_parent_list_;
3251 SolverState state_;
3252 int64_t branches_;
3253 int64_t fails_;
3254 int64_t decisions_;
3255 int64_t demon_runs_[kNumPriorities];
3256 int64_t neighbors_;
3257 int64_t filtered_neighbors_;
3258 int64_t accepted_neighbors_;
3259 std::string context_;
3260 OptimizationDirection optimization_direction_;
3261 std::unique_ptr<ClockTimer> timer_;
3262 std::vector<Search*> searches_;
3263 std::mt19937 random_;
3264 uint64_t fail_stamp_;
3265 std::unique_ptr<Decision> balancing_decision_;
3267 std::function<void()> fail_intercept_;
3269 DemonProfiler* const demon_profiler_;
3271 bool use_fast_local_search_;
3273 LocalSearchProfiler* const local_search_profiler_;
3275 std::unique_ptr<Assignment> local_search_state_;
3276
3278 enum { MIN_CACHED_INT_CONST = -8, MAX_CACHED_INT_CONST = 8 };
3279 IntVar* cached_constants_[MAX_CACHED_INT_CONST + 1 - MIN_CACHED_INT_CONST];
3280
3282 Constraint* true_constraint_;
3283 Constraint* false_constraint_;
3284
3285 std::unique_ptr<Decision> fail_decision_;
3286 int constraint_index_;
3287 int additional_constraint_index_;
3288 int num_int_vars_;
3289
3290 std::unique_ptr<ModelCache> model_cache_;
3291 std::unique_ptr<PropagationMonitor> propagation_monitor_;
3292 PropagationMonitor* print_trace_;
3293 std::unique_ptr<LocalSearchMonitor> local_search_monitor_;
3294 int anonymous_variable_index_;
3295 bool should_fail_;
3296};
3297
3298std::ostream& operator<<(std::ostream& out, const Solver* const s);
3299
3303inline int64_t Zero() { return 0; }
3304
3306inline int64_t One() { return 1; }
3307
3311class BaseObject {
3312 public:
3313 BaseObject() {}
3314
3315#ifndef SWIG
3316 // This type is neither copyable nor movable.
3317 BaseObject(const BaseObject&) = delete;
3318 BaseObject& operator=(const BaseObject&) = delete;
3319#endif
3320 virtual ~BaseObject() {}
3321 virtual std::string DebugString() const { return "BaseObject"; }
3322};
3323
3324std::ostream& operator<<(std::ostream& out, const BaseObject* o);
3325
3329class PropagationBaseObject : public BaseObject {
3330 public:
3331 explicit PropagationBaseObject(Solver* const s) : solver_(s) {}
3332
3333#ifndef SWIG
3334 // This type is neither copyable nor movable.
3337#endif
3338 ~PropagationBaseObject() override{};
3339
3340 std::string DebugString() const override {
3341 if (name().empty()) {
3342 return "PropagationBaseObject";
3343 } else {
3344 return absl::StrFormat("PropagationBaseObject: %s", name());
3345 }
3346 }
3347 Solver* solver() const { return solver_; }
3348
3351 void FreezeQueue() { solver_->FreezeQueue(); }
3352
3355 void UnfreezeQueue() { solver_->UnfreezeQueue(); }
3356
3360 void EnqueueDelayedDemon(Demon* const d) { solver_->EnqueueDelayedDemon(d); }
3361 void EnqueueVar(Demon* const d) { solver_->EnqueueVar(d); }
3363 void EnqueueAll(const SimpleRevFIFO<Demon*>& demons);
3364
3365#if !defined(SWIG)
3366 // This method sets a callback that will be called if a failure
3367 // happens during the propagation of the queue.
3369 solver_->set_action_on_fail(std::move(a));
3370 }
3371#endif // !defined(SWIG)
3372
3374 void reset_action_on_fail() { solver_->reset_action_on_fail(); }
3375
3378 solver_->set_variable_to_clean_on_fail(v);
3379 }
3380
3382 virtual std::string name() const;
3383 void set_name(absl::string_view name);
3385 bool HasName() const;
3387 virtual std::string BaseName() const;
3388
3389 private:
3390 Solver* const solver_;
3395class Decision : public BaseObject {
3396 public:
3397 Decision() {}
3398
3399#ifndef SWIG
3400 // This type is neither copyable nor movable.
3401 Decision(const Decision&) = delete;
3402 Decision& operator=(const Decision&) = delete;
3403#endif
3404 ~Decision() override {}
3405
3407 virtual void Apply(Solver* s) = 0;
3408
3410 virtual void Refute(Solver* s) = 0;
3412 std::string DebugString() const override { return "Decision"; }
3414 virtual void Accept(DecisionVisitor* visitor) const;
3415};
3419class DecisionVisitor : public BaseObject {
3420 public:
3421 DecisionVisitor() {}
3422
3423#ifndef SWIG
3424 // This type is neither copyable nor movable.
3425 DecisionVisitor(const DecisionVisitor&) = delete;
3426 DecisionVisitor& operator=(const DecisionVisitor&) = delete;
3427#endif
3428 ~DecisionVisitor() override {}
3429 virtual void VisitSetVariableValue(IntVar* var, int64_t value);
3431 bool start_with_lower_half);
3432 virtual void VisitScheduleOrPostpone(IntervalVar* var, int64_t est);
3433 virtual void VisitScheduleOrExpedite(IntervalVar* var, int64_t est);
3434 virtual void VisitRankFirstInterval(SequenceVar* sequence, int index);
3435 virtual void VisitRankLastInterval(SequenceVar* sequence, int index);
3436 virtual void VisitUnknownDecision();
3437};
3438
3441class DecisionBuilder : public BaseObject {
3442 public:
3443 DecisionBuilder() {}
3444
3445#ifndef SWIG
3446 // This type is neither copyable nor movable.
3447 DecisionBuilder(const DecisionBuilder&) = delete;
3448 DecisionBuilder& operator=(const DecisionBuilder&) = delete;
3449#endif
3450 ~DecisionBuilder() override {}
3455 virtual Decision* Next(Solver* s) = 0;
3456 std::string DebugString() const override;
3457#if !defined(SWIG)
3462 virtual void AppendMonitors(Solver* solver,
3463 std::vector<SearchMonitor*>* extras);
3464 virtual void Accept(ModelVisitor* visitor) const;
3465#endif
3466 void set_name(absl::string_view name) { name_ = name; }
3467 std::string GetName() const;
3469 private:
3470 std::string name_;
3471};
3472
3473#if !defined(SWIG)
3475 public:
3478 const std::string& name() const { return name_; }
3479 double seconds() const { return seconds_; }
3480 Decision* Next(Solver* solver) override;
3481 std::string DebugString() const override;
3483 std::vector<SearchMonitor*>* extras) override;
3484 void Accept(ModelVisitor* visitor) const override;
3485
3486 private:
3487 DecisionBuilder* const db_;
3488 const std::string name_;
3489 SimpleCycleTimer timer_;
3490 double seconds_;
3491};
3492#endif
3493
3503class Demon : public BaseObject {
3504 public:
3507 Demon() : stamp_(uint64_t{0}) {}
3508
3509#ifndef SWIG
3510 // This type is neither copyable nor movable.
3511 Demon(const Demon&) = delete;
3512 Demon& operator=(const Demon&) = delete;
3513#endif
3514 ~Demon() override {}
3515
3517 virtual void Run(Solver* s) = 0;
3518
3523
3524 std::string DebugString() const override;
3525
3528 void inhibit(Solver* s);
3529
3531 void desinhibit(Solver* s);
3532
3533 private:
3534 friend class Queue;
3535 void set_stamp(int64_t stamp) { stamp_ = stamp; }
3536 uint64_t stamp() const { return stamp_; }
3537 uint64_t stamp_;
3538};
3539
3541class ModelVisitor : public BaseObject {
3542 public:
3544 static const char kAbs[];
3545 static const char kAbsEqual[];
3546 static const char kAllDifferent[];
3547 static const char kAllowedAssignments[];
3548 static const char kAtMost[];
3549 static const char kIndexOf[];
3550 static const char kBetween[];
3551 static const char kConditionalExpr[];
3552 static const char kCircuit[];
3553 static const char kConvexPiecewise[];
3554 static const char kCountEqual[];
3555 static const char kCover[];
3556 static const char kCumulative[];
3557 static const char kDeviation[];
3558 static const char kDifference[];
3559 static const char kDisjunctive[];
3560 static const char kDistribute[];
3561 static const char kDivide[];
3562 static const char kDurationExpr[];
3563 static const char kElement[];
3564 static const char kLightElementEqual[];
3565 static const char kElementEqual[];
3566 static const char kEndExpr[];
3567 static const char kEquality[];
3568 static const char kFalseConstraint[];
3569 static const char kGlobalCardinality[];
3570 static const char kGreater[];
3571 static const char kGreaterOrEqual[];
3572 static const char kIntegerVariable[];
3573 static const char kIntervalBinaryRelation[];
3574 static const char kIntervalDisjunction[];
3575 static const char kIntervalUnaryRelation[];
3576 static const char kIntervalVariable[];
3577 static const char kInversePermutation[];
3578 static const char kIsBetween[];
3579 static const char kIsDifferent[];
3580 static const char kIsEqual[];
3581 static const char kIsGreater[];
3582 static const char kIsGreaterOrEqual[];
3583 static const char kIsLess[];
3584 static const char kIsLessOrEqual[];
3585 static const char kIsMember[];
3586 static const char kLess[];
3587 static const char kLessOrEqual[];
3588 static const char kLexLess[];
3589 static const char kLinkExprVar[];
3590 static const char kMapDomain[];
3591 static const char kMax[];
3592 static const char kMaxEqual[];
3593 static const char kMember[];
3594 static const char kMin[];
3595 static const char kMinEqual[];
3596 static const char kModulo[];
3597 static const char kNoCycle[];
3598 static const char kNonEqual[];
3599 static const char kNotBetween[];
3600 static const char kNotMember[];
3601 static const char kNullIntersect[];
3602 static const char kOpposite[];
3603 static const char kPack[];
3604 static const char kPathCumul[];
3605 static const char kDelayedPathCumul[];
3606 static const char kPerformedExpr[];
3607 static const char kPower[];
3608 static const char kProduct[];
3609 static const char kScalProd[];
3610 static const char kScalProdEqual[];
3611 static const char kScalProdGreaterOrEqual[];
3612 static const char kScalProdLessOrEqual[];
3613 static const char kSemiContinuous[];
3614 static const char kSequenceVariable[];
3615 static const char kSortingConstraint[];
3616 static const char kSquare[];
3617 static const char kStartExpr[];
3618 static const char kSum[];
3619 static const char kSumEqual[];
3620 static const char kSumGreaterOrEqual[];
3621 static const char kSumLessOrEqual[];
3622 static const char kTrace[];
3623 static const char kTransition[];
3624 static const char kTrueConstraint[];
3625 static const char kVarBoundWatcher[];
3626 static const char kVarValueWatcher[];
3629 static const char kCountAssignedItemsExtension[];
3630 static const char kCountUsedBinsExtension[];
3631 static const char kInt64ToBoolExtension[];
3632 static const char kInt64ToInt64Extension[];
3633 static const char kObjectiveExtension[];
3634 static const char kSearchLimitExtension[];
3635 static const char kUsageEqualVariableExtension[];
3637 static const char kUsageLessConstantExtension[];
3638 static const char kVariableGroupExtension[];
3643 static const char kActiveArgument[];
3644 static const char kAssumePathsArgument[];
3645 static const char kBranchesLimitArgument[];
3646 static const char kCapacityArgument[];
3647 static const char kCardsArgument[];
3648 static const char kCoefficientsArgument[];
3649 static const char kCountArgument[];
3650 static const char kCumulativeArgument[];
3651 static const char kCumulsArgument[];
3652 static const char kDemandsArgument[];
3653 static const char kDurationMaxArgument[];
3654 static const char kDurationMinArgument[];
3655 static const char kEarlyCostArgument[];
3656 static const char kEarlyDateArgument[];
3657 static const char kEndMaxArgument[];
3658 static const char kEndMinArgument[];
3659 static const char kEndsArgument[];
3660 static const char kExpressionArgument[];
3661 static const char kFailuresLimitArgument[];
3662 static const char kFinalStatesArgument[];
3663 static const char kFixedChargeArgument[];
3664 static const char kIndex2Argument[];
3665 static const char kIndexArgument[];
3666 static const char kInitialState[];
3667 static const char kIntervalArgument[];
3668 static const char kIntervalsArgument[];
3669 static const char kLateCostArgument[];
3670 static const char kLateDateArgument[];
3671 static const char kLeftArgument[];
3672 static const char kMaxArgument[];
3673 static const char kMaximizeArgument[];
3674 static const char kMinArgument[];
3675 static const char kModuloArgument[];
3676 static const char kNextsArgument[];
3677 static const char kOptionalArgument[];
3678 static const char kPartialArgument[];
3679 static const char kPositionXArgument[];
3680 static const char kPositionYArgument[];
3681 static const char kRangeArgument[];
3682 static const char kRelationArgument[];
3683 static const char kRightArgument[];
3684 static const char kSequenceArgument[];
3685 static const char kSequencesArgument[];
3686 static const char kSizeArgument[];
3687 static const char kSizeXArgument[];
3688 static const char kSizeYArgument[];
3689 static const char kSmartTimeCheckArgument[];
3690 static const char kSolutionLimitArgument[];
3691 static const char kStartMaxArgument[];
3692 static const char kStartMinArgument[];
3693 static const char kStartsArgument[];
3694 static const char kStepArgument[];
3695 static const char kTargetArgument[];
3696 static const char kTimeLimitArgument[];
3697 static const char kTransitsArgument[];
3698 static const char kTuplesArgument[];
3699 static const char kValueArgument[];
3700 static const char kValuesArgument[];
3701 static const char kVariableArgument[];
3702 static const char kVarsArgument[];
3703 static const char kEvaluatorArgument[];
3706 static const char kMirrorOperation[];
3707 static const char kRelaxedMaxOperation[];
3708 static const char kRelaxedMinOperation[];
3709 static const char kSumOperation[];
3710 static const char kDifferenceOperation[];
3711 static const char kProductOperation[];
3712 static const char kStartSyncOnStartOperation[];
3713 static const char kStartSyncOnEndOperation[];
3714 static const char kTraceOperation[];
3716 ~ModelVisitor() override;
3721 virtual void BeginVisitModel(const std::string& type_name);
3722 virtual void EndVisitModel(const std::string& type_name);
3723 virtual void BeginVisitConstraint(const std::string& type_name,
3724 const Constraint* constraint);
3725 virtual void EndVisitConstraint(const std::string& type_name,
3726 const Constraint* constraint);
3727 virtual void BeginVisitExtension(const std::string& type);
3728 virtual void EndVisitExtension(const std::string& type);
3729 virtual void BeginVisitIntegerExpression(const std::string& type_name,
3730 const IntExpr* expr);
3731 virtual void EndVisitIntegerExpression(const std::string& type_name,
3732 const IntExpr* expr);
3733 virtual void VisitIntegerVariable(const IntVar* variable, IntExpr* delegate);
3734 virtual void VisitIntegerVariable(const IntVar* variable,
3735 const std::string& operation, int64_t value,
3736 IntVar* delegate);
3737 virtual void VisitIntervalVariable(const IntervalVar* variable,
3738 const std::string& operation,
3739 int64_t value, IntervalVar* delegate);
3740 virtual void VisitSequenceVariable(const SequenceVar* variable);
3743 virtual void VisitIntegerArgument(const std::string& arg_name, int64_t value);
3744 virtual void VisitIntegerArrayArgument(const std::string& arg_name,
3745 const std::vector<int64_t>& values);
3746 virtual void VisitIntegerMatrixArgument(const std::string& arg_name,
3747 const IntTupleSet& tuples);
3750 virtual void VisitIntegerExpressionArgument(const std::string& arg_name,
3751 IntExpr* argument);
3754 const std::string& arg_name, const std::vector<IntVar*>& arguments);
3757 virtual void VisitIntervalArgument(const std::string& arg_name,
3758 IntervalVar* argument);
3760 virtual void VisitIntervalArrayArgument(
3761 const std::string& arg_name, const std::vector<IntervalVar*>& arguments);
3763 virtual void VisitSequenceArgument(const std::string& arg_name,
3764 SequenceVar* argument);
3767 const std::string& arg_name, const std::vector<SequenceVar*>& arguments);
3768#if !defined(SWIG)
3771 const std::string& arg_name, const Solver::Int64ToIntVar& arguments);
3772
3775 void VisitInt64ToBoolExtension(Solver::IndexFilter1 filter, int64_t index_min,
3776 int64_t index_max);
3778 int64_t index_min, int64_t index_max);
3781 const std::string& arg_name, int64_t index_max);
3782#endif // #if !defined(SWIG)
3783};
3784
3791class Constraint : public PropagationBaseObject {
3792 public:
3793 explicit Constraint(Solver* const solver) : PropagationBaseObject(solver) {}
3794
3795#ifndef SWIG
3796 // This type is neither copyable nor movable.
3797 Constraint(const Constraint&) = delete;
3798 Constraint& operator=(const Constraint&) = delete;
3799#endif
3800 ~Constraint() override {}
3801
3804 virtual void Post() = 0;
3805
3808 virtual void InitialPropagate() = 0;
3809 std::string DebugString() const override;
3810
3813 void PostAndPropagate();
3814
3816 virtual void Accept(ModelVisitor* visitor) const;
3817
3819 bool IsCastConstraint() const;
3820
3824 virtual IntVar* Var();
3825};
3826
3830class CastConstraint : public Constraint {
3831 public:
3832 CastConstraint(Solver* const solver, IntVar* const target_var)
3834 CHECK(target_var != nullptr);
3835 }
3836 ~CastConstraint() override {}
3837
3838 IntVar* target_var() const { return target_var_; }
3839
3840 protected:
3841 IntVar* const target_var_;
3842};
3843
3845class SearchMonitor : public BaseObject {
3846 public:
3847 static constexpr int kNoProgress = -1;
3848
3849 explicit SearchMonitor(Solver* const s) : solver_(s) {}
3850
3851#ifndef SWIG
3852 // This type is neither copyable nor movable.
3855#endif
3856 ~SearchMonitor() override {}
3858 virtual void EnterSearch();
3859
3861 virtual void RestartSearch();
3862
3864 virtual void ExitSearch();
3865
3867 virtual void BeginNextDecision(DecisionBuilder* b);
3868
3870 virtual void EndNextDecision(DecisionBuilder* b, Decision* d);
3871
3873 virtual void ApplyDecision(Decision* d);
3874
3876 virtual void RefuteDecision(Decision* d);
3877
3880 virtual void AfterDecision(Decision* d, bool apply);
3881
3883 virtual void BeginFail();
3884
3886 virtual void EndFail();
3887
3889 virtual void BeginInitialPropagation();
3890
3893
3897 virtual bool AcceptSolution();
3898
3902 virtual bool AtSolution();
3905 virtual void NoMoreSolutions();
3906
3909 virtual bool LocalOptimum();
3912 virtual bool AcceptDelta(Assignment* delta, Assignment* deltadelta);
3913
3915 virtual void AcceptNeighbor();
3916
3918 virtual void AcceptUncheckedNeighbor();
3919
3922 virtual bool IsUncheckedSolutionLimitReached() { return false; }
3923
3925 virtual void PeriodicCheck();
3926
3929 virtual int ProgressPercent() { return kNoProgress; }
3930
3932 virtual void Accept(ModelVisitor* visitor) const;
3933
3937 virtual void Install();
3938
3939 Solver* solver() const { return solver_; }
3940
3941 protected:
3943
3944 private:
3945 Solver* const solver_;
3946};
3947
3953template <class T>
3954class Rev {
3955 public:
3956 explicit Rev(const T& val) : stamp_(0), value_(val) {}
3957
3958 const T& Value() const { return value_; }
3959
3960 void SetValue(Solver* const s, const T& val) {
3961 if (val != value_) {
3962 if (stamp_ < s->stamp()) {
3963 s->SaveValue(&value_);
3964 stamp_ = s->stamp();
3965 }
3966 value_ = val;
3967 }
3968 }
3969
3970 private:
3971 uint64_t stamp_;
3972 T value_;
3973};
3974
3976template <class T>
3977class NumericalRev : public Rev<T> {
3978 public:
3979 explicit NumericalRev(const T& val) : Rev<T>(val) {}
3980
3981 void Add(Solver* const s, const T& to_add) {
3982 this->SetValue(s, this->Value() + to_add);
3983 }
3984
3985 void Incr(Solver* const s) { Add(s, 1); }
3987 void Decr(Solver* const s) { Add(s, -1); }
3988};
3989
3995template <class T>
3997 public:
3998 RevArray(int size, const T& val)
3999 : stamps_(new uint64_t[size]), values_(new T[size]), size_(size) {
4000 for (int i = 0; i < size; ++i) {
4001 stamps_[i] = 0;
4002 values_[i] = val;
4003 }
4004 }
4005
4006 ~RevArray() {}
4007
4008 int64_t size() const { return size_; }
4009
4010 const T& Value(int index) const { return values_[index]; }
4012#if !defined(SWIG)
4013 const T& operator[](int index) const { return values_[index]; }
4014#endif
4016 void SetValue(Solver* const s, int index, const T& val) {
4017 DCHECK_LT(index, size_);
4018 if (val != values_[index]) {
4019 if (stamps_[index] < s->stamp()) {
4020 s->SaveValue(&values_[index]);
4021 stamps_[index] = s->stamp();
4022 }
4023 values_[index] = val;
4024 }
4025 }
4026
4027 private:
4028 std::unique_ptr<uint64_t[]> stamps_;
4029 std::unique_ptr<T[]> values_;
4030 const int size_;
4031};
4032
4034template <class T>
4035class NumericalRevArray : public RevArray<T> {
4036 public:
4037 NumericalRevArray(int size, const T& val) : RevArray<T>(size, val) {}
4039 void Add(Solver* const s, int index, const T& to_add) {
4040 this->SetValue(s, index, this->Value(index) + to_add);
4041 }
4043 void Incr(Solver* const s, int index) { Add(s, index, 1); }
4045 void Decr(Solver* const s, int index) { Add(s, index, -1); }
4046};
4047
4056 public:
4057 explicit IntExpr(Solver* const s) : PropagationBaseObject(s) {}
4058
4059#ifndef SWIG
4060 // This type is neither copyable nor movable.
4061 IntExpr(const IntExpr&) = delete;
4062 IntExpr& operator=(const IntExpr&) = delete;
4063#endif
4064 ~IntExpr() override {}
4066 virtual int64_t Min() const = 0;
4067 virtual void SetMin(int64_t m) = 0;
4068 virtual int64_t Max() const = 0;
4069 virtual void SetMax(int64_t m) = 0;
4073 virtual void Range(int64_t* l, int64_t* u) {
4074 *l = Min();
4075 *u = Max();
4076 }
4078 virtual void SetRange(int64_t l, int64_t u) {
4079 SetMin(l);
4080 SetMax(u);
4081 }
4082
4084 virtual void SetValue(int64_t v) { SetRange(v, v); }
4085
4087 virtual bool Bound() const { return (Min() == Max()); }
4088
4090 virtual bool IsVar() const { return false; }
4091
4093 virtual IntVar* Var() = 0;
4099 IntVar* VarWithName(const std::string& name);
4102 virtual void WhenRange(Demon* d) = 0;
4104 void WhenRange(Solver::Closure closure) {
4105 WhenRange(solver()->MakeClosureDemon(std::move(closure)));
4106 }
4107
4108#if !defined(SWIG)
4110 void WhenRange(Solver::Action action) {
4111 WhenRange(solver()->MakeActionDemon(std::move(action)));
4113#endif // SWIG
4116 virtual void Accept(ModelVisitor* visitor) const;
4117};
4129
4136class IntVarIterator : public BaseObject {
4137 public:
4138 ~IntVarIterator() override {}
4139
4141 virtual void Init() = 0;
4142
4144 virtual bool Ok() const = 0;
4145
4147 virtual int64_t Value() const = 0;
4148
4150 virtual void Next() = 0;
4151
4153 std::string DebugString() const override { return "IntVar::Iterator"; }
4154};
4155
4156#ifndef SWIG
4163class InitAndGetValues {
4164 public:
4165 explicit InitAndGetValues(IntVarIterator* it)
4166 : it_(it), begin_was_called_(false) {
4167 it_->Init();
4168 }
4169 struct Iterator;
4170
4171 Iterator begin() {
4172 if (DEBUG_MODE) {
4173 DCHECK(!begin_was_called_);
4174 begin_was_called_ = true;
4175 }
4176 return Iterator::Begin(it_);
4177 }
4178 Iterator end() { return Iterator::End(it_); }
4179
4180 struct Iterator {
4182 static Iterator Begin(IntVarIterator* it) {
4183 return Iterator(it, /*is_end=*/false);
4184 }
4185 static Iterator End(IntVarIterator* it) {
4186 return Iterator(it, /*is_end=*/true);
4187 }
4188
4189 int64_t operator*() const {
4190 DCHECK(it->Ok());
4191 return it->Value();
4192 }
4193 Iterator& operator++() {
4194 DCHECK(it->Ok());
4195 it->Next();
4196 return *this;
4197 }
4198 bool operator!=(const Iterator& other) const {
4199 DCHECK(other.it == it);
4200 DCHECK(other.is_end);
4201 return it->Ok();
4202 }
4203
4204 private:
4205 Iterator(IntVarIterator* it, bool is_end) : it(it), is_end(is_end) {}
4206
4208 const bool is_end;
4209 };
4211 private:
4212 IntVarIterator* const it_;
4213 bool begin_was_called_;
4214};
4215#endif // SWIG
4216
4220class IntVar : public IntExpr {
4221 public:
4222 explicit IntVar(Solver* s);
4223 IntVar(Solver* s, const std::string& name);
4224
4225#ifndef SWIG
4226 // This type is neither copyable nor movable.
4227 IntVar(const IntVar&) = delete;
4228 IntVar& operator=(const IntVar&) = delete;
4229#endif
4230
4231 ~IntVar() override{};
4232
4233 bool IsVar() const override { return true; }
4234 IntVar* Var() override { return this; }
4235
4238 virtual int64_t Value() const = 0;
4239
4241 virtual void RemoveValue(int64_t v) = 0;
4242
4245 virtual void RemoveInterval(int64_t l, int64_t u) = 0;
4246
4248 virtual void RemoveValues(const std::vector<int64_t>& values);
4249
4251 virtual void SetValues(const std::vector<int64_t>& values);
4252
4255 virtual void WhenBound(Demon* d) = 0;
4258 void WhenBound(Solver::Closure closure) {
4259 WhenBound(solver()->MakeClosureDemon(std::move(closure)));
4260 }
4261
4262#if !defined(SWIG)
4265 void WhenBound(Solver::Action action) {
4266 WhenBound(solver()->MakeActionDemon(std::move(action)));
4267 }
4268#endif // SWIG
4269
4272 virtual void WhenDomain(Demon* d) = 0;
4275 void WhenDomain(Solver::Closure closure) {
4276 WhenDomain(solver()->MakeClosureDemon(std::move(closure)));
4277 }
4278#if !defined(SWIG)
4281 void WhenDomain(Solver::Action action) {
4282 WhenDomain(solver()->MakeActionDemon(std::move(action)));
4283 }
4284#endif // SWIG
4287 virtual uint64_t Size() const = 0;
4288
4291 virtual bool Contains(int64_t v) const = 0;
4296 virtual IntVarIterator* MakeHoleIterator(bool reversible) const = 0;
4297
4301 virtual IntVarIterator* MakeDomainIterator(bool reversible) const = 0;
4302
4304 virtual int64_t OldMin() const = 0;
4305
4307 virtual int64_t OldMax() const = 0;
4308
4309 virtual int VarType() const;
4310
4312 void Accept(ModelVisitor* visitor) const override;
4315 virtual IntVar* IsEqual(int64_t constant) = 0;
4316 virtual IntVar* IsDifferent(int64_t constant) = 0;
4317 virtual IntVar* IsGreaterOrEqual(int64_t constant) = 0;
4318 virtual IntVar* IsLessOrEqual(int64_t constant) = 0;
4319
4321 int index() const { return index_; }
4322
4323 private:
4324 const int index_;
4325};
4326
4331 public:
4332 SolutionCollector(Solver* solver, const Assignment* assignment);
4334
4335#ifndef SWIG
4336 // This type is neither copyable nor movable.
4337 SolutionCollector(const SolutionCollector&) = delete;
4339#endif
4340
4341 ~SolutionCollector() override;
4342 void Install() override;
4343 std::string DebugString() const override { return "SolutionCollector"; }
4344
4346 void Add(IntVar* var);
4347 void Add(const std::vector<IntVar*>& vars);
4348 void Add(IntervalVar* var);
4349 void Add(const std::vector<IntervalVar*>& vars);
4350 void Add(SequenceVar* var);
4351 void Add(const std::vector<SequenceVar*>& vars);
4352 void AddObjective(IntVar* objective);
4353 void AddObjectives(const std::vector<IntVar*>& objectives);
4356 void EnterSearch() override;
4357
4359 int solution_count() const;
4360
4362 bool has_solution() const;
4363
4365 Assignment* solution(int n) const;
4366
4369
4371 int64_t wall_time(int n) const;
4372
4374 int64_t branches(int n) const;
4378 int64_t failures(int n) const;
4381 int64_t objective_value(int n) const;
4382
4384 int64_t ObjectiveValueFromIndex(int n, int index) const;
4385
4387 int64_t Value(int n, IntVar* var) const;
4390 int64_t StartValue(int n, IntervalVar* var) const;
4391
4393 int64_t EndValue(int n, IntervalVar* var) const;
4394
4396 int64_t DurationValue(int n, IntervalVar* var) const;
4397
4399 int64_t PerformedValue(int n, IntervalVar* var) const;
4400
4404 const std::vector<int>& ForwardSequence(int n, SequenceVar* var) const;
4408 const std::vector<int>& BackwardSequence(int n, SequenceVar* var) const;
4411 const std::vector<int>& Unperformed(int n, SequenceVar* var) const;
4412
4413 protected:
4414 struct SolutionData {
4416 int64_t time;
4417 int64_t branches;
4418 int64_t failures;
4419 int64_t ObjectiveValue() const;
4420 int64_t ObjectiveValueFromIndex(int index) const;
4421 bool operator<(const SolutionData& other) const;
4422 };
4423
4425 void PushSolution();
4426 void Push(const SolutionData& data) { solution_data_.push_back(data); }
4428 void PopSolution();
4429 SolutionData BuildSolutionDataForCurrentState();
4430 void FreeSolution(Assignment* solution);
4431 void check_index(int n) const;
4432
4433 std::unique_ptr<Assignment> prototype_;
4434 std::vector<SolutionData> solution_data_;
4435 std::vector<Assignment*> recycle_solutions_;
4436#if !defined(SWIG)
4437 std::vector<std::unique_ptr<Assignment>> solution_pool_;
4438#endif // SWIG
4439};
4440
4441// Base objective monitor class. All metaheuristics derive from this.
4442class ObjectiveMonitor : public SearchMonitor {
4443 public:
4444 ObjectiveMonitor(Solver* solver, const std::vector<bool>& maximize,
4445 std::vector<IntVar*> vars, std::vector<int64_t> steps);
4446 ~ObjectiveMonitor() override {}
4447#ifndef SWIG
4448 ObjectiveMonitor(const ObjectiveMonitor&) = delete;
4450#endif // SWIG
4451 IntVar* ObjectiveVar(int index) const { return objective_vars_[index]; }
4452 IntVar* MinimizationVar(int index) const { return minimization_vars_[index]; }
4453 int64_t Step(int index) const { return steps_[index]; }
4454 bool Maximize(int index) const {
4456 }
4457 int64_t BestValue(int index) const {
4460 }
4461 int Size() const { return objective_vars_.size(); }
4462 void EnterSearch() override;
4463 bool AtSolution() override;
4464 bool AcceptDelta(Assignment* delta, Assignment* deltadelta) override;
4465 void Accept(ModelVisitor* visitor) const override;
4466
4467 protected:
4468 const std::vector<IntVar*>& objective_vars() const { return objective_vars_; }
4469 const std::vector<IntVar*>& minimization_vars() const {
4470 return minimization_vars_;
4471 }
4472 int64_t BestInternalValue(int index) const { return best_values_[index]; }
4473 int64_t CurrentInternalValue(int index) const {
4474 return current_values_[index];
4477 current_values_[index] = value;
4478 }
4479 template <typename T>
4481 if (Size() == 1) {
4483 } else {
4484 Solver* const solver = this->solver();
4485 for (int i = 0; i < Size(); ++i) {
4486 upper_bounds_[i] = solver->MakeIntConst(upper_bounds(i));
4487 }
4489 minimization_vars_, upper_bounds_, steps_));
4490 }
4492 template <typename T>
4494 const T& upper_bounds) {
4495 Solver* const solver = this->solver();
4497 if (Size() == 1) {
4500 } else {
4501 for (int i = 0; i < Size(); ++i) {
4502 upper_bounds_[i] = solver->MakeIntConst(upper_bounds(i));
4503 }
4505 minimization_vars_, upper_bounds_, steps_, status));
4507 return status;
4508 }
4513 private:
4514 friend class Solver;
4515 const std::vector<IntVar*> objective_vars_;
4516 std::vector<IntVar*> minimization_vars_;
4517 std::vector<IntVar*> upper_bounds_;
4518 std::vector<int64_t> steps_;
4519 std::vector<int64_t> best_values_;
4520 std::vector<int64_t> current_values_;
4521};
4522
4527 public:
4528 OptimizeVar(Solver* solver, bool maximize, IntVar* var, int64_t step);
4529 // Specifies a lexicographic objective. Each objective is specified in
4530 // decreasing order with the corresponding direction and step.
4531 OptimizeVar(Solver* solver, const std::vector<bool>& maximize,
4532 std::vector<IntVar*> vars, std::vector<int64_t> steps);
4533#ifndef SWIG
4534 ~OptimizeVar() override {}
4535#endif // SIWG
4536
4538 int64_t best() const { return BestValue(0); }
4539
4541 IntVar* var() const { return Size() == 0 ? nullptr : ObjectiveVar(0); }
4542
4544 void BeginNextDecision(DecisionBuilder* db) override;
4545 void RefuteDecision(Decision* d) override;
4546 bool AtSolution() override;
4547 bool AcceptSolution() override;
4548 virtual std::string Name() const;
4549 std::string DebugString() const override;
4550
4552};
4553
4555class SearchLimit : public SearchMonitor {
4556 public:
4557 explicit SearchLimit(Solver* const s) : SearchMonitor(s), crossed_(false) {}
4558
4559#ifndef SWIG
4560 // This type is neither copyable nor movable.
4561 SearchLimit(const SearchLimit&) = delete;
4562 SearchLimit& operator=(const SearchLimit&) = delete;
4563#endif
4564 ~SearchLimit() override;
4565
4567 bool crossed() const { return crossed_; }
4568
4573 bool Check() { return CheckWithOffset(absl::ZeroDuration()); }
4576 virtual bool CheckWithOffset(absl::Duration offset) = 0;
4577
4579 virtual void Init() = 0;
4580
4583 virtual void Copy(const SearchLimit* limit) = 0;
4586 virtual SearchLimit* MakeClone() const = 0;
4587
4589 void EnterSearch() override;
4590 void BeginNextDecision(DecisionBuilder* b) override;
4591 void PeriodicCheck() override;
4592 void RefuteDecision(Decision* d) override;
4593 std::string DebugString() const override {
4594 return absl::StrFormat("SearchLimit(crossed = %i)", crossed_);
4595 }
4596 void Install() override;
4597
4598 private:
4599 void TopPeriodicCheck();
4600
4601 bool crossed_;
4602};
4603
4606class RegularLimit : public SearchLimit {
4607 public:
4608 RegularLimit(Solver* s, absl::Duration time, int64_t branches,
4609 int64_t failures, int64_t solutions, bool smart_time_check,
4610 bool cumulative);
4611 ~RegularLimit() override;
4612 void Copy(const SearchLimit* limit) override;
4613 SearchLimit* MakeClone() const override;
4615 bool CheckWithOffset(absl::Duration offset) override;
4616 void Init() override;
4617 void ExitSearch() override;
4618 void UpdateLimits(absl::Duration time, int64_t branches, int64_t failures,
4619 int64_t solutions);
4620 absl::Duration duration_limit() const { return duration_limit_; }
4621 int64_t wall_time() const {
4622 return duration_limit_ == absl::InfiniteDuration()
4623 ? kint64max
4624 : absl::ToInt64Milliseconds(duration_limit());
4626 int64_t branches() const { return branches_; }
4627 int64_t failures() const { return failures_; }
4628 int64_t solutions() const { return solutions_; }
4629 bool IsUncheckedSolutionLimitReached() override;
4630 int ProgressPercent() override;
4631 std::string DebugString() const override;
4632 void Install() override;
4633
4634 absl::Time AbsoluteSolverDeadline() const {
4635 return solver_time_at_limit_start_ + duration_limit_;
4636 }
4638 void Accept(ModelVisitor* visitor) const override;
4639
4640 private:
4641 bool CheckTime(absl::Duration offset);
4642 absl::Duration TimeElapsed();
4643 static int64_t GetPercent(int64_t value, int64_t offset, int64_t total) {
4644 return (total > 0 && total < kint64max) ? 100 * (value - offset) / total
4645 : -1;
4646 }
4647
4648 absl::Duration duration_limit_;
4649 absl::Time solver_time_at_limit_start_;
4650 absl::Duration last_time_elapsed_;
4651 int64_t check_count_;
4652 int64_t next_check_;
4653 bool smart_time_check_;
4654 int64_t branches_;
4655 int64_t branches_offset_;
4656 int64_t failures_;
4657 int64_t failures_offset_;
4658 int64_t solutions_;
4659 int64_t solutions_offset_;
4667 bool cumulative_;
4668};
4669
4670// Limit based on the improvement rate of 'objective_var' or a lexicographic
4671// objective composed of 'objective_vars'.
4672// This limit proceeds in two stages:
4673// 1) During the phase of the search in which the objective is strictly
4674// improving, a threshold value is computed as the minimum improvement rate of
4675// the objective, based on the 'improvement_rate_coefficient' and
4676// 'improvement_rate_solutions_distance' parameters.
4677// 2) Then, if the search continues beyond this phase of strict improvement, the
4678// limit stops the search when the improvement rate of the objective gets below
4679// this threshold value.
4680class ImprovementSearchLimit : public SearchLimit {
4681 public:
4682 ImprovementSearchLimit(Solver* solver, IntVar* objective_var, bool maximize,
4683 double objective_scaling_factor,
4684 double objective_offset,
4685 double improvement_rate_coefficient,
4686 int improvement_rate_solutions_distance);
4687 ImprovementSearchLimit(Solver* solver, std::vector<IntVar*> objective_vars,
4688 std::vector<bool> maximize,
4689 std::vector<double> objective_scaling_factors,
4690 std::vector<double> objective_offsets,
4691 double improvement_rate_coefficient,
4692 int improvement_rate_solutions_distance);
4693 ~ImprovementSearchLimit() override;
4694 void Copy(const SearchLimit* limit) override;
4695 SearchLimit* MakeClone() const override;
4696 bool CheckWithOffset(absl::Duration offset) override;
4697 bool AtSolution() override;
4698 void Init() override;
4699 void Install() override;
4700
4701 private:
4702 std::vector<IntVar*> objective_vars_;
4703 std::vector<bool> maximize_;
4704 std::vector<double> objective_scaling_factors_;
4705 std::vector<double> objective_offsets_;
4706 double improvement_rate_coefficient_;
4707 int improvement_rate_solutions_distance_;
4708
4709 std::vector<double> best_objectives_;
4710 // clang-format off
4711 std::vector<std::deque<std::pair<double, int64_t> > > improvements_;
4712 // clang-format on
4713 std::vector<double> thresholds_;
4714 bool objective_updated_;
4715 bool gradient_stage_;
4716};
4717
4728class IntervalVar : public PropagationBaseObject {
4729 public:
4731 static const int64_t kMinValidValue;
4733 static const int64_t kMaxValidValue;
4734 IntervalVar(Solver* const solver, const std::string& name)
4736 set_name(name);
4737 }
4739#ifndef SWIG
4740 // This type is neither copyable nor movable.
4741 IntervalVar(const IntervalVar&) = delete;
4742 IntervalVar& operator=(const IntervalVar&) = delete;
4743#endif
4744 ~IntervalVar() override {}
4745
4748 virtual int64_t StartMin() const = 0;
4749 virtual int64_t StartMax() const = 0;
4750 virtual void SetStartMin(int64_t m) = 0;
4751 virtual void SetStartMax(int64_t m) = 0;
4752 virtual void SetStartRange(int64_t mi, int64_t ma) = 0;
4753 virtual int64_t OldStartMin() const = 0;
4754 virtual int64_t OldStartMax() const = 0;
4755 virtual void WhenStartRange(Demon* d) = 0;
4756 void WhenStartRange(Solver::Closure closure) {
4757 WhenStartRange(solver()->MakeClosureDemon(std::move(closure)));
4758 }
4759#if !defined(SWIG)
4760 void WhenStartRange(Solver::Action action) {
4761 WhenStartRange(solver()->MakeActionDemon(std::move(action)));
4762 }
4763#endif // SWIG
4764 virtual void WhenStartBound(Demon* d) = 0;
4765 void WhenStartBound(Solver::Closure closure) {
4766 WhenStartBound(solver()->MakeClosureDemon(std::move(closure)));
4767 }
4768#if !defined(SWIG)
4769 void WhenStartBound(Solver::Action action) {
4770 WhenStartBound(solver()->MakeActionDemon(std::move(action)));
4771 }
4772#endif // SWIG
4773
4775 virtual int64_t DurationMin() const = 0;
4776 virtual int64_t DurationMax() const = 0;
4777 virtual void SetDurationMin(int64_t m) = 0;
4778 virtual void SetDurationMax(int64_t m) = 0;
4779 virtual void SetDurationRange(int64_t mi, int64_t ma) = 0;
4780 virtual int64_t OldDurationMin() const = 0;
4781 virtual int64_t OldDurationMax() const = 0;
4782 virtual void WhenDurationRange(Demon* d) = 0;
4783 void WhenDurationRange(Solver::Closure closure) {
4784 WhenDurationRange(solver()->MakeClosureDemon(std::move(closure)));
4785 }
4786#if !defined(SWIG)
4788 WhenDurationRange(solver()->MakeActionDemon(std::move(action)));
4789 }
4790#endif // SWIG
4791 virtual void WhenDurationBound(Demon* d) = 0;
4793 WhenDurationBound(solver()->MakeClosureDemon(std::move(closure)));
4794 }
4795#if !defined(SWIG)
4796 void WhenDurationBound(Solver::Action action) {
4797 WhenDurationBound(solver()->MakeActionDemon(std::move(action)));
4798 }
4799#endif // SWIG
4802 virtual int64_t EndMin() const = 0;
4803 virtual int64_t EndMax() const = 0;
4804 virtual void SetEndMin(int64_t m) = 0;
4805 virtual void SetEndMax(int64_t m) = 0;
4806 virtual void SetEndRange(int64_t mi, int64_t ma) = 0;
4807 virtual int64_t OldEndMin() const = 0;
4808 virtual int64_t OldEndMax() const = 0;
4809 virtual void WhenEndRange(Demon* d) = 0;
4811 WhenEndRange(solver()->MakeClosureDemon(std::move(closure)));
4813#if !defined(SWIG)
4815 WhenEndRange(solver()->MakeActionDemon(std::move(action)));
4816 }
4817#endif // SWIG
4818 virtual void WhenEndBound(Demon* d) = 0;
4820 WhenEndBound(solver()->MakeClosureDemon(std::move(closure)));
4821 }
4822#if !defined(SWIG)
4824 WhenEndBound(solver()->MakeActionDemon(std::move(action)));
4825 }
4826#endif // SWIG
4827
4830 virtual bool MustBePerformed() const = 0;
4831 virtual bool MayBePerformed() const = 0;
4832 bool CannotBePerformed() const { return !MayBePerformed(); }
4833 bool IsPerformedBound() const {
4836 virtual void SetPerformed(bool val) = 0;
4837 virtual bool WasPerformedBound() const = 0;
4838 virtual void WhenPerformedBound(Demon* d) = 0;
4840 WhenPerformedBound(solver()->MakeClosureDemon(std::move(closure)));
4842#if !defined(SWIG)
4843 void WhenPerformedBound(Solver::Action action) {
4844 WhenPerformedBound(solver()->MakeActionDemon(std::move(action)));
4845 }
4846#endif // SWIG
4847
4849 void WhenAnything(Demon* d);
4852 WhenAnything(solver()->MakeClosureDemon(std::move(closure)));
4853 }
4854#if !defined(SWIG)
4856 void WhenAnything(Solver::Action action) {
4857 WhenAnything(solver()->MakeActionDemon(std::move(action)));
4858 }
4859#endif // SWIG
4860
4864 virtual IntExpr* StartExpr() = 0;
4865 virtual IntExpr* DurationExpr() = 0;
4866 virtual IntExpr* EndExpr() = 0;
4867 virtual IntExpr* PerformedExpr() = 0;
4871 virtual IntExpr* SafeStartExpr(int64_t unperformed_value) = 0;
4872 virtual IntExpr* SafeDurationExpr(int64_t unperformed_value) = 0;
4873 virtual IntExpr* SafeEndExpr(int64_t unperformed_value) = 0;
4874
4876 virtual void Accept(ModelVisitor* visitor) const = 0;
4885class SequenceVar : public PropagationBaseObject {
4886 public:
4887 SequenceVar(Solver* s, const std::vector<IntervalVar*>& intervals,
4888 const std::vector<IntVar*>& nexts, const std::string& name);
4890 ~SequenceVar() override;
4892 std::string DebugString() const override;
4893
4894#if !defined(SWIG)
4897 void DurationRange(int64_t* dmin, int64_t* dmax) const;
4901 void HorizonRange(int64_t* hmin, int64_t* hmax) const;
4905 void ActiveHorizonRange(int64_t* hmin, int64_t* hmax) const;
4906
4908 void ComputeStatistics(int* ranked, int* not_ranked, int* unperformed) const;
4909#endif // !defined(SWIG)
4913 void RankFirst(int index);
4914
4917 void RankNotFirst(int index);
4918
4921 void RankLast(int index);
4922
4929 void ComputePossibleFirstsAndLasts(std::vector<int>* possible_firsts,
4930 std::vector<int>* possible_lasts);
4937 void RankSequence(const std::vector<int>& rank_first,
4938 const std::vector<int>& rank_last,
4939 const std::vector<int>& unperformed);
4940
4949 void FillSequence(std::vector<int>* rank_first, std::vector<int>* rank_last,
4950 std::vector<int>* unperformed) const;
4951
4953 IntervalVar* Interval(int index) const;
4954
4956 IntVar* Next(int index) const;
4957
4959 int64_t size() const { return intervals_.size(); }
4960
4962 virtual void Accept(ModelVisitor* visitor) const;
4963
4964 private:
4965 int ComputeForwardFrontier();
4966 int ComputeBackwardFrontier();
4967 void UpdatePrevious() const;
4968
4969 const std::vector<IntervalVar*> intervals_;
4970 const std::vector<IntVar*> nexts_;
4971 mutable std::vector<int> previous_;
4972};
4973
4974class AssignmentElement {
4975 public:
4976 AssignmentElement() : activated_(true) {}
4977
4978 void Activate() { activated_ = true; }
4979 void Deactivate() { activated_ = false; }
4980 bool Activated() const { return activated_; }
4981
4982 private:
4983 bool activated_;
4984};
4985
4986class IntVarElement : public AssignmentElement {
4987 public:
4988 IntVarElement();
4989 explicit IntVarElement(IntVar* var);
4990 void Reset(IntVar* var);
4992 void Copy(const IntVarElement& element);
4993 IntVar* Var() const { return var_; }
4994 void Store() {
4995 min_ = var_->Min();
4996 max_ = var_->Max();
4997 }
4998 void Restore() {
4999 if (var_ != nullptr) {
5000 var_->SetRange(min_, max_);
5001 }
5002 }
5003 void LoadFromProto(const IntVarAssignment& int_var_assignment_proto);
5004 void WriteToProto(IntVarAssignment* int_var_assignment_proto) const;
5005
5006 int64_t Min() const { return min_; }
5007 void SetMin(int64_t m) { min_ = m; }
5008 int64_t Max() const { return max_; }
5009 void SetMax(int64_t m) { max_ = m; }
5010 int64_t Value() const {
5011 DCHECK_EQ(min_, max_);
5012 // Get the value from an unbound int var assignment element.
5013 return min_;
5014 }
5015 bool Bound() const { return (max_ == min_); }
5016 void SetRange(int64_t l, int64_t u) {
5017 min_ = l;
5018 max_ = u;
5019 }
5020 void SetValue(int64_t v) {
5021 min_ = v;
5022 max_ = v;
5023 }
5024 std::string DebugString() const;
5025
5026 bool operator==(const IntVarElement& element) const;
5027 bool operator!=(const IntVarElement& element) const {
5028 return !(*this == element);
5029 }
5030
5031 private:
5032 IntVar* var_;
5033 int64_t min_;
5034 int64_t max_;
5036
5038 public:
5041 void Reset(IntervalVar* var);
5043 void Copy(const IntervalVarElement& element);
5044 IntervalVar* Var() const { return var_; }
5045 void Store();
5046 void Restore();
5047 void LoadFromProto(
5048 const IntervalVarAssignment& interval_var_assignment_proto);
5049 void WriteToProto(IntervalVarAssignment* interval_var_assignment_proto) const;
5050
5051 int64_t StartMin() const { return start_min_; }
5052 int64_t StartMax() const { return start_max_; }
5053 int64_t StartValue() const {
5054 CHECK_EQ(start_max_, start_min_);
5055 return start_max_;
5056 }
5057 int64_t DurationMin() const { return duration_min_; }
5058 int64_t DurationMax() const { return duration_max_; }
5059 int64_t DurationValue() const {
5060 CHECK_EQ(duration_max_, duration_min_);
5061 return duration_max_;
5062 }
5063 int64_t EndMin() const { return end_min_; }
5064 int64_t EndMax() const { return end_max_; }
5065 int64_t EndValue() const {
5066 CHECK_EQ(end_max_, end_min_);
5067 return end_max_;
5069 int64_t PerformedMin() const { return performed_min_; }
5070 int64_t PerformedMax() const { return performed_max_; }
5071 int64_t PerformedValue() const {
5072 CHECK_EQ(performed_max_, performed_min_);
5073 return performed_max_;
5075 void SetStartMin(int64_t m) { start_min_ = m; }
5076 void SetStartMax(int64_t m) { start_max_ = m; }
5077 void SetStartRange(int64_t mi, int64_t ma) {
5078 start_min_ = mi;
5079 start_max_ = ma;
5080 }
5081 void SetStartValue(int64_t v) {
5082 start_min_ = v;
5083 start_max_ = v;
5084 }
5085 void SetDurationMin(int64_t m) { duration_min_ = m; }
5086 void SetDurationMax(int64_t m) { duration_max_ = m; }
5087 void SetDurationRange(int64_t mi, int64_t ma) {
5088 duration_min_ = mi;
5089 duration_max_ = ma;
5090 }
5091 void SetDurationValue(int64_t v) {
5092 duration_min_ = v;
5093 duration_max_ = v;
5094 }
5095 void SetEndMin(int64_t m) { end_min_ = m; }
5096 void SetEndMax(int64_t m) { end_max_ = m; }
5097 void SetEndRange(int64_t mi, int64_t ma) {
5098 end_min_ = mi;
5099 end_max_ = ma;
5100 }
5101 void SetEndValue(int64_t v) {
5102 end_min_ = v;
5103 end_max_ = v;
5104 }
5105 void SetPerformedMin(int64_t m) { performed_min_ = m; }
5106 void SetPerformedMax(int64_t m) { performed_max_ = m; }
5107 void SetPerformedRange(int64_t mi, int64_t ma) {
5108 performed_min_ = mi;
5109 performed_max_ = ma;
5111 void SetPerformedValue(int64_t v) {
5112 performed_min_ = v;
5113 performed_max_ = v;
5114 }
5115 bool Bound() const {
5116 return (start_min_ == start_max_ && duration_min_ == duration_max_ &&
5117 end_min_ == end_max_ && performed_min_ == performed_max_);
5119 std::string DebugString() const;
5120 bool operator==(const IntervalVarElement& element) const;
5121 bool operator!=(const IntervalVarElement& element) const {
5122 return !(*this == element);
5125 private:
5126 int64_t start_min_;
5127 int64_t start_max_;
5128 int64_t duration_min_;
5129 int64_t duration_max_;
5130 int64_t end_min_;
5131 int64_t end_max_;
5132 int64_t performed_min_;
5133 int64_t performed_max_;
5151 public:
5156 void Copy(const SequenceVarElement& element);
5157 SequenceVar* Var() const { return var_; }
5158 void Store();
5159 void Restore();
5161 const SequenceVarAssignment& sequence_var_assignment_proto);
5162 void WriteToProto(SequenceVarAssignment* sequence_var_assignment_proto) const;
5163
5164 const std::vector<int>& ForwardSequence() const;
5165 const std::vector<int>& BackwardSequence() const;
5166 const std::vector<int>& Unperformed() const;
5167 void SetSequence(const std::vector<int>& forward_sequence,
5168 const std::vector<int>& backward_sequence,
5169 const std::vector<int>& unperformed);
5170 void SetForwardSequence(const std::vector<int>& forward_sequence);
5171 void SetBackwardSequence(const std::vector<int>& backward_sequence);
5172 void SetUnperformed(const std::vector<int>& unperformed);
5173 bool Bound() const {
5174 return forward_sequence_.size() + unperformed_.size() == var_->size();
5175 }
5176
5177 std::string DebugString() const;
5178
5179 bool operator==(const SequenceVarElement& element) const;
5180 bool operator!=(const SequenceVarElement& element) const {
5181 return !(*this == element);
5182 }
5183
5184 private:
5185 bool CheckClassInvariants();
5186
5187 SequenceVar* var_;
5188 std::vector<int> forward_sequence_;
5189 std::vector<int> backward_sequence_;
5190 std::vector<int> unperformed_;
5191};
5192
5193template <class V, class E>
5194class AssignmentContainer {
5195 public:
5197 E* Add(V* var) {
5198 CHECK(var != nullptr);
5199 int index = -1;
5200 if (!Find(var, &index)) {
5201 return FastAdd(var);
5202 } else {
5203 return &elements_[index];
5204 }
5205 }
5207 E* FastAdd(V* var) {
5208 DCHECK(var != nullptr);
5209 elements_.emplace_back(var);
5210 return &elements_.back();
5211 }
5214 E* AddAtPosition(V* var, int position) {
5215 elements_[position].Reset(var);
5216 return &elements_[position];
5217 }
5218 void Clear() {
5219 elements_.clear();
5220 if (!elements_map_.empty()) {
5221 elements_map_.clear();
5222 }
5223 }
5226 void Resize(size_t size) { elements_.resize(size); }
5227 bool Empty() const { return elements_.empty(); }
5230 void CopyIntersection(const AssignmentContainer<V, E>& container) {
5231 for (int i = 0; i < container.elements_.size(); ++i) {
5232 const E& element = container.elements_[i];
5233 const V* const var = element.Var();
5234 int index = -1;
5235 if (i < elements_.size() && elements_[i].Var() == var) {
5236 index = i;
5237 } else if (!Find(var, &index)) {
5238 continue;
5240 DCHECK_GE(index, 0);
5241 E* const local_element = &elements_[index];
5242 local_element->Copy(element);
5243 if (element.Activated()) {
5244 local_element->Activate();
5245 } else {
5246 local_element->Deactivate();
5247 }
5248 }
5249 }
5252 void Copy(const AssignmentContainer<V, E>& container) {
5254 for (int i = 0; i < container.elements_.size(); ++i) {
5255 const E& element = container.elements_[i];
5256 FastAdd(element.Var())->Copy(element);
5257 }
5258 }
5259 bool Contains(const V* const var) const {
5260 int index;
5261 return Find(var, &index);
5262 }
5263 E* MutableElement(const V* const var) {
5264 E* const element = MutableElementOrNull(var);
5265 DCHECK(element != nullptr)
5266 << "Unknown variable " << var->DebugString() << " in solution";
5267 return element;
5268 }
5269 E* MutableElementOrNull(const V* const var) {
5270 int index = -1;
5271 if (Find(var, &index)) {
5272 return MutableElement(index);
5274 return nullptr;
5275 }
5276 const E& Element(const V* const var) const {
5277 const E* const element = ElementPtrOrNull(var);
5278 DCHECK(element != nullptr)
5279 << "Unknown variable " << var->DebugString() << " in solution";
5280 return *element;
5281 }
5282 const E* ElementPtrOrNull(const V* const var) const {
5283 int index = -1;
5284 if (Find(var, &index)) {
5285 return &Element(index);
5287 return nullptr;
5288 }
5289 const std::vector<E>& elements() const { return elements_; }
5290 E* MutableElement(int index) { return &elements_[index]; }
5291 const E& Element(int index) const { return elements_[index]; }
5292 int Size() const { return elements_.size(); }
5293 void Store() {
5294 for (E& element : elements_) {
5295 element.Store();
5296 }
5297 }
5298 void Restore() {
5299 for (E& element : elements_) {
5300 if (element.Activated()) {
5301 element.Restore();
5302 }
5303 }
5304 }
5305 bool AreAllElementsBound() const {
5306 for (const E& element : elements_) {
5307 if (!element.Bound()) return false;
5308 }
5309 return true;
5310 }
5315 bool operator==(const AssignmentContainer<V, E>& container) const {
5317 if (Size() != container.Size()) {
5318 return false;
5319 }
5321 EnsureMapIsUpToDate();
5325 for (const E& element : container.elements_) {
5326 const int position =
5327 gtl::FindWithDefault(elements_map_, element.Var(), -1);
5328 if (position < 0 || elements_[position] != element) {
5329 return false;
5330 }
5331 }
5332 return true;
5333 }
5334 bool operator!=(const AssignmentContainer<V, E>& container) const {
5335 return !(*this == container);
5336 }
5337
5338 private:
5339 void EnsureMapIsUpToDate() const {
5340 absl::flat_hash_map<const V*, int>* map =
5341 const_cast<absl::flat_hash_map<const V*, int>*>(&elements_map_);
5342 for (int i = map->size(); i < elements_.size(); ++i) {
5343 (*map)[elements_[i].Var()] = i;
5344 }
5345 }
5346 bool Find(const V* const var, int* index) const {
5348 const size_t kMaxSizeForLinearAccess = 11;
5349 if (Size() <= kMaxSizeForLinearAccess) {
5353 for (int i = 0; i < elements_.size(); ++i) {
5354 if (var == elements_[i].Var()) {
5355 *index = i;
5356 return true;
5358 }
5359 return false;
5360 } else {
5361 EnsureMapIsUpToDate();
5362 DCHECK_EQ(elements_map_.size(), elements_.size());
5363 return gtl::FindCopy(elements_map_, var, index);
5365 }
5366
5367 std::vector<E> elements_;
5368 absl::flat_hash_map<const V*, int> elements_map_;
5369};
5370
5373class Assignment : public PropagationBaseObject {
5374 public:
5380
5381 explicit Assignment(Solver* solver);
5382 explicit Assignment(const Assignment* copy);
5383
5384#ifndef SWIG
5385 // This type is neither copyable nor movable.
5386 Assignment(const Assignment&) = delete;
5387 Assignment& operator=(const Assignment&) = delete;
5388#endif
5389
5390 ~Assignment() override;
5391
5392 void Clear();
5393 bool Empty() const {
5394 return int_var_container_.Empty() && interval_var_container_.Empty() &&
5395 sequence_var_container_.Empty();
5396 }
5397 int Size() const {
5399 }
5400 int NumIntVars() const { return int_var_container_.Size(); }
5401 int NumIntervalVars() const { return interval_var_container_.Size(); }
5402 int NumSequenceVars() const { return sequence_var_container_.Size(); }
5403 void Store();
5404 void Restore();
5405
5408 bool Load(const std::string& filename);
5409#if !defined(SWIG)
5410 bool Load(File* file);
5411#endif
5412 void Load(const AssignmentProto& assignment_proto);
5414 bool Save(const std::string& filename) const;
5415#if !defined(SWIG)
5416 bool Save(File* file) const;
5417#endif // #if !defined(SWIG)
5418 void Save(AssignmentProto* assignment_proto) const;
5419
5420 void AddObjective(IntVar* const v) { AddObjectives({v}); }
5421 void AddObjectives(const std::vector<IntVar*>& vars) {
5422 // Objective can only set once.
5423 DCHECK(!HasObjective());
5424 objective_elements_.reserve(vars.size());
5425 for (IntVar* const var : vars) {
5426 if (var != nullptr) {
5427 objective_elements_.emplace_back(var);
5428 }
5429 }
5430 }
5431 void ClearObjective() { objective_elements_.clear(); }
5432 int NumObjectives() const { return objective_elements_.size(); }
5433 IntVar* Objective() const { return ObjectiveFromIndex(0); }
5435 return HasObjectiveFromIndex(index) ? objective_elements_[index].Var()
5436 : nullptr;
5437 }
5438 bool HasObjective() const { return !objective_elements_.empty(); }
5439 bool HasObjectiveFromIndex(int index) const {
5440 return index < objective_elements_.size();
5441 }
5442 int64_t ObjectiveMin() const { return ObjectiveMinFromIndex(0); }
5443 int64_t ObjectiveMax() const { return ObjectiveMaxFromIndex(0); }
5444 int64_t ObjectiveValue() const { return ObjectiveValueFromIndex(0); }
5445 bool ObjectiveBound() const { return ObjectiveBoundFromIndex(0); }
5447 void SetObjectiveMax(int64_t m) { SetObjectiveMaxFromIndex(0, m); }
5448 void SetObjectiveValue(int64_t value) {
5450 }
5451 void SetObjectiveRange(int64_t l, int64_t u) {
5453 }
5454 int64_t ObjectiveMinFromIndex(int index) const {
5455 return HasObjectiveFromIndex(index) ? objective_elements_[index].Min() : 0;
5457 int64_t ObjectiveMaxFromIndex(int index) const {
5458 return HasObjectiveFromIndex(index) ? objective_elements_[index].Max() : 0;
5460 int64_t ObjectiveValueFromIndex(int index) const {
5461 return HasObjectiveFromIndex(index) ? objective_elements_[index].Value()
5462 : 0;
5463 }
5464 bool ObjectiveBoundFromIndex(int index) const {
5465 return HasObjectiveFromIndex(index) ? objective_elements_[index].Bound()
5466 : true;
5467 }
5468 void SetObjectiveMinFromIndex(int index, int64_t m) {
5470 objective_elements_[index].SetMin(m);
5471 }
5472 }
5473 void SetObjectiveMaxFromIndex(int index, int64_t m) {
5475 objective_elements_[index].SetMax(m);
5476 }
5477 }
5478 void SetObjectiveValueFromIndex(int index, int64_t value) {
5480 objective_elements_[index].SetValue(value);
5481 }
5482 }
5483 void SetObjectiveRangeFromIndex(int index, int64_t l, int64_t u) {
5485 objective_elements_[index].SetRange(l, u);
5486 }
5487 }
5488
5489 IntVarElement* Add(IntVar* var);
5490 void Add(const std::vector<IntVar*>& vars);
5493 int64_t Min(const IntVar* var) const;
5494 int64_t Max(const IntVar* var) const;
5495 int64_t Value(const IntVar* var) const;
5496 bool Bound(const IntVar* var) const;
5497 void SetMin(const IntVar* var, int64_t m);
5498 void SetMax(const IntVar* var, int64_t m);
5499 void SetRange(const IntVar* var, int64_t l, int64_t u);
5500 void SetValue(const IntVar* var, int64_t value);
5503 void Add(const std::vector<IntervalVar*>& vars);
5506 int64_t StartMin(const IntervalVar* var) const;
5507 int64_t StartMax(const IntervalVar* var) const;
5508 int64_t StartValue(const IntervalVar* var) const;
5509 int64_t DurationMin(const IntervalVar* var) const;
5510 int64_t DurationMax(const IntervalVar* var) const;
5511 int64_t DurationValue(const IntervalVar* var) const;
5512 int64_t EndMin(const IntervalVar* var) const;
5513 int64_t EndMax(const IntervalVar* var) const;
5514 int64_t EndValue(const IntervalVar* var) const;
5515 int64_t PerformedMin(const IntervalVar* var) const;
5516 int64_t PerformedMax(const IntervalVar* var) const;
5517 int64_t PerformedValue(const IntervalVar* var) const;
5518 void SetStartMin(const IntervalVar* var, int64_t m);
5519 void SetStartMax(const IntervalVar* var, int64_t m);
5520 void SetStartRange(const IntervalVar* var, int64_t mi, int64_t ma);
5521 void SetStartValue(const IntervalVar* var, int64_t value);
5522 void SetDurationMin(const IntervalVar* var, int64_t m);
5523 void SetDurationMax(const IntervalVar* var, int64_t m);
5524 void SetDurationRange(const IntervalVar* var, int64_t mi, int64_t ma);
5525 void SetDurationValue(const IntervalVar* var, int64_t value);
5526 void SetEndMin(const IntervalVar* var, int64_t m);
5527 void SetEndMax(const IntervalVar* var, int64_t m);
5528 void SetEndRange(const IntervalVar* var, int64_t mi, int64_t ma);
5529 void SetEndValue(const IntervalVar* var, int64_t value);
5530 void SetPerformedMin(const IntervalVar* var, int64_t m);
5531 void SetPerformedMax(const IntervalVar* var, int64_t m);
5532 void SetPerformedRange(const IntervalVar* var, int64_t mi, int64_t ma);
5533 void SetPerformedValue(const IntervalVar* var, int64_t value);
5534
5536 void Add(const std::vector<SequenceVar*>& vars);
5539 const std::vector<int>& ForwardSequence(const SequenceVar* var) const;
5540 const std::vector<int>& BackwardSequence(const SequenceVar* var) const;
5541 const std::vector<int>& Unperformed(const SequenceVar* var) const;
5543 const std::vector<int>& forward_sequence,
5544 const std::vector<int>& backward_sequence,
5545 const std::vector<int>& unperformed);
5547 const std::vector<int>& forward_sequence);
5549 const std::vector<int>& backward_sequence);
5550 void SetUnperformed(const SequenceVar* var,
5551 const std::vector<int>& unperformed);
5552
5553 void Activate(const IntVar* var);
5554 void Deactivate(const IntVar* var);
5555 bool Activated(const IntVar* var) const;
5556
5557 void Activate(const IntervalVar* var);
5558 void Deactivate(const IntervalVar* var);
5559 bool Activated(const IntervalVar* var) const;
5560
5561 void Activate(const SequenceVar* var);
5562 void Deactivate(const SequenceVar* var);
5563 bool Activated(const SequenceVar* var) const;
5564
5567 bool ActivatedObjective() const { return ActivatedObjectiveFromIndex(0); }
5570 objective_elements_[index].Activate();
5571 }
5572 }
5575 objective_elements_[index].Deactivate();
5576 }
5577 }
5578 bool ActivatedObjectiveFromIndex(int index) const {
5579 return HasObjectiveFromIndex(index) ? objective_elements_[index].Activated()
5580 : true;
5581 }
5582
5583 std::string DebugString() const override;
5584
5585 bool AreAllElementsBound() const {
5586 return int_var_container_.AreAllElementsBound() &&
5587 interval_var_container_.AreAllElementsBound() &&
5588 sequence_var_container_.AreAllElementsBound();
5589 }
5590
5591 bool Contains(const IntVar* var) const;
5592 bool Contains(const IntervalVar* var) const;
5593 bool Contains(const SequenceVar* var) const;
5596 void CopyIntersection(const Assignment* assignment);
5599 void Copy(const Assignment* assignment);
5600
5601 // TODO(user): Add element iterators to avoid exposing container class.
5602 const IntContainer& IntVarContainer() const { return int_var_container_; }
5603 IntContainer* MutableIntVarContainer() { return &int_var_container_; }
5605 return interval_var_container_;
5606 }
5608 return &interval_var_container_;
5609 }
5611 return sequence_var_container_;
5612 }
5614 return &sequence_var_container_;
5615 }
5616 bool operator==(const Assignment& assignment) const {
5617 return int_var_container_ == assignment.int_var_container_ &&
5618 interval_var_container_ == assignment.interval_var_container_ &&
5619 sequence_var_container_ == assignment.sequence_var_container_ &&
5620 objective_elements_ == assignment.objective_elements_;
5621 }
5622 bool operator!=(const Assignment& assignment) const {
5623 return !(*this == assignment);
5626 private:
5627 IntContainer int_var_container_;
5628 IntervalContainer interval_var_container_;
5629 SequenceContainer sequence_var_container_;
5630 std::vector<IntVarElement> objective_elements_;
5631};
5633std::ostream& operator<<(std::ostream& out,
5634 const Assignment& assignment);
5635
5641void SetAssignmentFromAssignment(Assignment* target_assignment,
5642 const std::vector<IntVar*>& target_vars,
5643 const Assignment* source_assignment,
5644 const std::vector<IntVar*>& source_vars);
5645
5646class Pack : public Constraint {
5647 public:
5648 Pack(Solver* s, const std::vector<IntVar*>& vars, int number_of_bins);
5649
5650 ~Pack() override;
5651
5656
5661 const std::vector<int64_t>& weights, const std::vector<int64_t>& bounds);
5668 Solver::IndexEvaluator1 weights, const std::vector<int64_t>& bounds);
5675 Solver::IndexEvaluator2 weights, const std::vector<int64_t>& bounds);
5676
5679 void AddWeightedSumEqualVarDimension(const std::vector<int64_t>& weights,
5680 const std::vector<IntVar*>& loads);
5686 const std::vector<IntVar*>& loads);
5687
5698 const std::vector<IntVar*>& usage, const std::vector<int64_t>& capacity);
5699
5702 void AddWeightedSumOfAssignedDimension(const std::vector<int64_t>& weights,
5703 IntVar* cost_var);
5704
5707 void AddCountUsedBinDimension(IntVar* count_var);
5708
5711 void AddCountAssignedItemsDimension(IntVar* count_var);
5712
5713 void Post() override;
5714 void ClearAll();
5715 void PropagateDelayed();
5716 void InitialPropagate() override;
5717 void Propagate();
5718 void OneDomain(int var_index);
5719 std::string DebugString() const override;
5720 bool IsUndecided(int var_index, int bin_index) const;
5721 void SetImpossible(int var_index, int bin_index);
5722 void Assign(int var_index, int bin_index);
5723 bool IsAssignedStatusKnown(int var_index) const;
5724 bool IsPossible(int var_index, int bin_index) const;
5725 IntVar* AssignVar(int var_index, int bin_index) const;
5726 void SetAssigned(int var_index);
5727 void SetUnassigned(int var_index);
5728 void RemoveAllPossibleFromBin(int bin_index);
5729 void AssignAllPossibleToBin(int bin_index);
5730 void AssignFirstPossibleToBin(int bin_index);
5733 void Accept(ModelVisitor* visitor) const override;
5734
5735 private:
5736 bool IsInProcess() const;
5737 const std::vector<IntVar*> vars_;
5738 const int bins_;
5739 std::vector<Dimension*> dims_;
5740 std::unique_ptr<RevBitMatrix> unprocessed_;
5741 std::vector<std::vector<int>> forced_;
5742 std::vector<std::vector<int>> removed_;
5743 std::vector<IntVarIterator*> holes_;
5744 uint64_t stamp_;
5745 Demon* demon_;
5746 std::vector<std::pair<int, int>> to_set_;
5747 std::vector<std::pair<int, int>> to_unset_;
5748 bool in_process_;
5749};
5750
5751class DisjunctiveConstraint : public Constraint {
5752 public:
5753 DisjunctiveConstraint(Solver* s, const std::vector<IntervalVar*>& intervals,
5754 const std::string& name);
5755
5756#ifndef SWIG
5757 // This type is neither copyable nor movable.
5760#endif
5761
5762 ~DisjunctiveConstraint() override;
5763
5765 virtual SequenceVar* MakeSequenceVar() = 0;
5766
5771 void SetTransitionTime(Solver::IndexEvaluator2 transition_time);
5772
5773 int64_t TransitionTime(int before_index, int after_index) {
5774 DCHECK(transition_time_);
5775 return transition_time_(before_index, after_index);
5776 }
5777
5778#if !defined(SWIG)
5779 virtual const std::vector<IntVar*>& nexts() const = 0;
5780 virtual const std::vector<IntVar*>& actives() const = 0;
5781 virtual const std::vector<IntVar*>& time_cumuls() const = 0;
5782 virtual const std::vector<IntVar*>& time_slacks() const = 0;
5783#endif // !defined(SWIG)
5784
5785 protected:
5786 const std::vector<IntervalVar*> intervals_;
5788};
5789
5792class SolutionPool : public BaseObject {
5793 public:
5794 SolutionPool() {}
5795 ~SolutionPool() override {}
5796
5799 virtual void Initialize(Assignment* assignment) = 0;
5800
5803 virtual void RegisterNewSolution(Assignment* assignment) = 0;
5804
5807 virtual void GetNextSolution(Assignment* assignment) = 0;
5808
5811 virtual bool SyncNeeded(Assignment* local_assignment) = 0;
5812};
5813} // namespace operations_research
5814
5815#endif // OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
IntegerValue size
int64_t max
int64_t min
Definition file.h:30
const E & Element(const V *const var) const
E * FastAdd(V *var)
Adds element without checking its presence in the container.
void Copy(const AssignmentContainer< V, E > &container)
bool operator!=(const AssignmentContainer< V, E > &container) const
bool operator==(const AssignmentContainer< V, E > &container) const
void CopyIntersection(const AssignmentContainer< V, E > &container)
const std::vector< E > & elements() const
bool Contains(const V *const var) const
const E * ElementPtrOrNull(const V *const var) const
void Activate(const IntVar *var)
AssignmentContainer< IntVar, IntVarElement > IntContainer
void SetPerformedRange(const IntervalVar *var, int64_t mi, int64_t ma)
int64_t Value(const IntVar *var) const
AssignmentContainer< IntervalVar, IntervalVarElement > IntervalContainer
void SetStartMax(const IntervalVar *var, int64_t m)
void SetMax(const IntVar *var, int64_t m)
void SetForwardSequence(const SequenceVar *var, const std::vector< int > &forward_sequence)
int64_t EndMin(const IntervalVar *var) const
bool Activated(const IntVar *var) const
AssignmentContainer< SequenceVar, SequenceVarElement > SequenceContainer
int64_t ObjectiveValueFromIndex(int index) const
int64_t DurationMax(const IntervalVar *var) const
int64_t PerformedMin(const IntervalVar *var) const
int64_t Max(const IntVar *var) const
void SetBackwardSequence(const SequenceVar *var, const std::vector< int > &backward_sequence)
int64_t Min(const IntVar *var) const
void SetEndValue(const IntervalVar *var, int64_t value)
bool Contains(const IntVar *var) const
void SetValue(const IntVar *var, int64_t value)
bool ObjectiveBoundFromIndex(int index) const
void SetEndMin(const IntervalVar *var, int64_t m)
void AddObjectives(const std::vector< IntVar * > &vars)
bool Load(const std::string &filename)
int64_t EndValue(const IntervalVar *var) const
void SetMin(const IntVar *var, int64_t m)
bool operator==(const Assignment &assignment) const
const std::vector< int > & Unperformed(const SequenceVar *var) const
void SetPerformedValue(const IntervalVar *var, int64_t value)
int64_t PerformedValue(const IntervalVar *var) const
IntervalContainer * MutableIntervalVarContainer()
int64_t StartValue(const IntervalVar *var) const
void SetObjectiveRange(int64_t l, int64_t u)
IntVarElement * Add(IntVar *var)
const IntervalContainer & IntervalVarContainer() const
const SequenceContainer & SequenceVarContainer() const
void SetPerformedMax(const IntervalVar *var, int64_t m)
int64_t ObjectiveMinFromIndex(int index) const
void SetObjectiveMinFromIndex(int index, int64_t m)
std::string DebugString() const override
int64_t EndMax(const IntervalVar *var) const
int64_t StartMin(const IntervalVar *var) const
IntVarElement * FastAdd(IntVar *var)
Adds without checking if variable has been previously added.
void Deactivate(const IntVar *var)
void Copy(const Assignment *assignment)
const std::vector< int > & ForwardSequence(const SequenceVar *var) const
void SetRange(const IntVar *var, int64_t l, int64_t u)
int64_t ObjectiveMaxFromIndex(int index) const
bool ActivatedObjectiveFromIndex(int index) const
int64_t DurationMin(const IntervalVar *var) const
const IntContainer & IntVarContainer() const
void SetObjectiveMaxFromIndex(int index, int64_t m)
bool Bound(const IntVar *var) const
int64_t DurationValue(const IntervalVar *var) const
void SetSequence(const SequenceVar *var, const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
void SetStartMin(const IntervalVar *var, int64_t m)
void SetDurationMin(const IntervalVar *var, int64_t m)
void SetStartValue(const IntervalVar *var, int64_t value)
void SetDurationMax(const IntervalVar *var, int64_t m)
Assignment & operator=(const Assignment &)=delete
void SetEndMax(const IntervalVar *var, int64_t m)
void SetStartRange(const IntervalVar *var, int64_t mi, int64_t ma)
void SetDurationValue(const IntervalVar *var, int64_t value)
void CopyIntersection(const Assignment *assignment)
void SetEndRange(const IntervalVar *var, int64_t mi, int64_t ma)
void SetDurationRange(const IntervalVar *var, int64_t mi, int64_t ma)
bool operator!=(const Assignment &assignment) const
SequenceContainer * MutableSequenceVarContainer()
bool HasObjectiveFromIndex(int index) const
int64_t StartMax(const IntervalVar *var) const
IntVar * ObjectiveFromIndex(int index) const
void SetObjectiveValueFromIndex(int index, int64_t value)
bool Save(const std::string &filename) const
Saves the assignment to a file.
const std::vector< int > & BackwardSequence(const SequenceVar *var) const
void SetPerformedMin(const IntervalVar *var, int64_t m)
void SetObjectiveRangeFromIndex(int index, int64_t l, int64_t u)
void SetUnperformed(const SequenceVar *var, const std::vector< int > &unperformed)
int64_t PerformedMax(const IntervalVar *var) const
BaseObject & operator=(const BaseObject &)=delete
virtual std::string DebugString() const
CastConstraint(Solver *const solver, IntVar *const target_var)
Constraint & operator=(const Constraint &)=delete
std::string DebugString() const override
--------------— Constraint class ----------------—
virtual void InitialPropagate()=0
bool IsCastConstraint() const
Is the constraint created by a cast from expression to integer variable?
virtual void Accept(ModelVisitor *visitor) const
Accepts the given visitor.
DecisionBuilder & operator=(const DecisionBuilder &)=delete
void set_name(absl::string_view name)
virtual void Accept(ModelVisitor *visitor) const
virtual void AppendMonitors(Solver *solver, std::vector< SearchMonitor * > *extras)
std::string DebugString() const override
-------— Decision Builder -------—
virtual void VisitRankFirstInterval(SequenceVar *sequence, int index)
virtual void VisitSetVariableValue(IntVar *var, int64_t value)
virtual void VisitScheduleOrPostpone(IntervalVar *var, int64_t est)
virtual void VisitRankLastInterval(SequenceVar *sequence, int index)
virtual void VisitScheduleOrExpedite(IntervalVar *var, int64_t est)
DecisionVisitor & operator=(const DecisionVisitor &)=delete
virtual void VisitSplitVariableDomain(IntVar *var, int64_t value, bool start_with_lower_half)
virtual void Refute(Solver *s)=0
Refute will be called after a backtrack.
std::string DebugString() const override
virtual void Apply(Solver *s)=0
Apply will be called first when the decision is executed.
Decision & operator=(const Decision &)=delete
virtual void Accept(DecisionVisitor *visitor) const
Accepts the given visitor.
Demon & operator=(const Demon &)=delete
virtual void Run(Solver *s)=0
This is the main callback of the demon.
virtual Solver::DemonPriority priority() const
---------------— Demon class -------------—
std::string DebugString() const override
void desinhibit(Solver *s)
This method un-inhibits the demon that was previously inhibited.
virtual const std::vector< IntVar * > & time_slacks() const =0
virtual SequenceVar * MakeSequenceVar()=0
Creates a sequence variable from the constraint.
DisjunctiveConstraint(Solver *s, const std::vector< IntervalVar * > &intervals, const std::string &name)
Sequence Constraint.
Definition resource.cc:2585
virtual const std::vector< IntVar * > & time_cumuls() const =0
virtual const std::vector< IntVar * > & actives() const =0
int64_t TransitionTime(int before_index, int after_index)
DisjunctiveConstraint & operator=(const DisjunctiveConstraint &)=delete
const std::vector< IntervalVar * > intervals_
virtual const std::vector< IntVar * > & nexts() const =0
void SetTransitionTime(Solver::IndexEvaluator2 transition_time)
Definition resource.cc:2597
--— Finds a neighbor of the assignment passed --—
bool CheckWithOffset(absl::Duration offset) override
Definition search.cc:4636
ImprovementSearchLimit(Solver *solver, IntVar *objective_var, bool maximize, double objective_scaling_factor, double objective_offset, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
--— Improvement Search Limit --—
Definition search.cc:4564
void Init() override
This method is called when the search limit is initialized.
Definition search.cc:4602
void Install() override
A search monitors adds itself on the active search.
Definition search.cc:4597
void Copy(const SearchLimit *limit) override
Definition search.cc:4612
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
Definition search.cc:4629
virtual void SetValue(int64_t v)
This method sets the value of the expression.
virtual bool Bound() const
Returns true if the min and the max of the expression are equal.
virtual void SetMax(int64_t m)=0
virtual bool IsVar() const
Returns true if the expression is indeed a variable.
virtual void SetRange(int64_t l, int64_t u)
This method sets both the min and the max of the expression.
virtual int64_t Min() const =0
IntExpr & operator=(const IntExpr &)=delete
virtual void SetMin(int64_t m)=0
virtual void WhenRange(Demon *d)=0
Attach a demon that will watch the min or the max of the expression.
virtual void Range(int64_t *l, int64_t *u)
IntVar * VarWithName(const std::string &name)
-------— IntExpr -------—
virtual IntVar * Var()=0
Creates a variable from the expression.
virtual int64_t Max() const =0
virtual void Accept(ModelVisitor *visitor) const
Accepts the given visitor.
--— Main IntTupleSet class --—
Definition tuple_set.h:47
bool operator==(const IntVarElement &element) const
Definition assignment.cc:77
void SetRange(int64_t l, int64_t u)
bool operator!=(const IntVarElement &element) const
IntVarElement()
--------------— Solutions ---------------------—
Definition assignment.cc:40
void Copy(const IntVarElement &element)
Definition assignment.cc:56
void WriteToProto(IntVarAssignment *int_var_assignment_proto) const
Definition assignment.cc:92
void LoadFromProto(const IntVarAssignment &int_var_assignment_proto)
Definition assignment.cc:66
virtual bool Ok() const =0
This method indicates if we can call Value() or not.
virtual int64_t Value() const =0
This method returns the current value of the iterator.
virtual void Next()=0
This method moves the iterator to the next value.
virtual void Init()=0
This method must be called before each loop.
std::string DebugString() const override
Pretty Print.
virtual void WhenBound(Demon *d)=0
virtual void WhenDomain(Demon *d)=0
bool IsVar() const override
Returns true if the expression is indeed a variable.
virtual void SetValues(const std::vector< int64_t > &values)
This method intersects the current domain with the values in the array.
void Accept(ModelVisitor *visitor) const override
Accepts the given visitor.
virtual IntVar * IsDifferent(int64_t constant)=0
int index() const
Returns the index of the variable.
IntVar(Solver *s)
-------— IntVar -------—
virtual IntVarIterator * MakeDomainIterator(bool reversible) const =0
virtual int64_t OldMax() const =0
Returns the previous max.
IntVar * Var() override
Creates a variable from the expression.
virtual IntVar * IsLessOrEqual(int64_t constant)=0
IntVar & operator=(const IntVar &)=delete
virtual bool Contains(int64_t v) const =0
virtual int64_t Value() const =0
virtual int VarType() const
------— IntVar ------—
virtual void RemoveValue(int64_t v)=0
This method removes the value 'v' from the domain of the variable.
virtual uint64_t Size() const =0
This method returns the number of values in the domain of the variable.
virtual IntVarIterator * MakeHoleIterator(bool reversible) const =0
virtual IntVar * IsGreaterOrEqual(int64_t constant)=0
virtual IntVar * IsEqual(int64_t constant)=0
IsEqual.
virtual void RemoveInterval(int64_t l, int64_t u)=0
virtual int64_t OldMin() const =0
Returns the previous min.
virtual void RemoveValues(const std::vector< int64_t > &values)
This method remove the values from the domain of the variable.
void SetDurationRange(int64_t mi, int64_t ma)
void WriteToProto(IntervalVarAssignment *interval_var_assignment_proto) const
bool operator!=(const IntervalVarElement &element) const
void Copy(const IntervalVarElement &element)
void SetEndRange(int64_t mi, int64_t ma)
IntervalVarElement()
--— IntervalVarElement --—
bool operator==(const IntervalVarElement &element) const
void SetStartRange(int64_t mi, int64_t ma)
void SetPerformedRange(int64_t mi, int64_t ma)
void LoadFromProto(const IntervalVarAssignment &interval_var_assignment_proto)
virtual IntExpr * PerformedExpr()=0
virtual int64_t DurationMax() const =0
virtual bool WasPerformedBound() const =0
virtual void WhenEndRange(Demon *d)=0
virtual void SetEndRange(int64_t mi, int64_t ma)=0
virtual int64_t OldEndMax() const =0
virtual int64_t OldDurationMin() const =0
virtual int64_t EndMax() const =0
virtual IntExpr * StartExpr()=0
virtual int64_t EndMin() const =0
These methods query, set, and watch the end position of the interval var.
virtual int64_t OldStartMax() const =0
virtual void SetEndMax(int64_t m)=0
virtual void SetPerformed(bool val)=0
virtual void SetDurationMax(int64_t m)=0
virtual void SetStartRange(int64_t mi, int64_t ma)=0
virtual int64_t OldDurationMax() const =0
virtual void SetStartMax(int64_t m)=0
static const int64_t kMaxValidValue
The largest acceptable value to be returned by EndMax()
virtual void WhenStartRange(Demon *d)=0
void WhenAnything(Demon *d)
Attaches a demon awakened when anything about this interval changes.
Definition interval.cc:2272
virtual int64_t OldEndMin() const =0
virtual int64_t StartMax() const =0
virtual bool MayBePerformed() const =0
virtual void SetDurationMin(int64_t m)=0
virtual void WhenDurationBound(Demon *d)=0
virtual IntExpr * SafeStartExpr(int64_t unperformed_value)=0
static const int64_t kMinValidValue
The smallest acceptable value to be returned by StartMin()
virtual void WhenStartBound(Demon *d)=0
virtual IntExpr * SafeDurationExpr(int64_t unperformed_value)=0
IntervalVar & operator=(const IntervalVar &)=delete
virtual IntExpr * SafeEndExpr(int64_t unperformed_value)=0
virtual IntExpr * DurationExpr()=0
virtual void WhenDurationRange(Demon *d)=0
virtual void WhenEndBound(Demon *d)=0
virtual int64_t DurationMin() const =0
These methods query, set, and watch the duration of the interval var.
virtual void SetEndMin(int64_t m)=0
virtual IntExpr * EndExpr()=0
virtual void SetStartMin(int64_t m)=0
virtual void Accept(ModelVisitor *visitor) const =0
Accepts the given visitor.
virtual void WhenPerformedBound(Demon *d)=0
virtual void SetDurationRange(int64_t mi, int64_t ma)=0
virtual int64_t OldStartMin() const =0
IntervalVar(Solver *const solver, const std::string &name)
virtual int64_t StartMin() const =0
virtual bool MustBePerformed() const =0
--— LightIntFunctionElementCt --—
--— LightIntIntFunctionElementCt --—
-------— Local Search Phase Parameters -------—
--— LocalSearchProfiler --—
--— Local search decision builder --—
virtual void VisitSequenceVariable(const SequenceVar *variable)
virtual void VisitIntervalArrayArgument(const std::string &arg_name, const std::vector< IntervalVar * > &arguments)
virtual void VisitIntervalArgument(const std::string &arg_name, IntervalVar *argument)
Visit interval argument.
static const char kVariableUsageLessConstantExtension[]
void VisitInt64ToBoolExtension(Solver::IndexFilter1 filter, int64_t index_min, int64_t index_max)
--— Helpers --—
void VisitInt64ToInt64AsArray(const Solver::IndexEvaluator1 &eval, const std::string &arg_name, int64_t index_max)
Expands function as array when index min is 0.
static const char kMirrorOperation[]
Operations.
static const char kActiveArgument[]
argument names:
virtual void BeginVisitModel(const std::string &type_name)
--— Virtual methods for visitors --—
virtual void BeginVisitIntegerExpression(const std::string &type_name, const IntExpr *expr)
virtual void VisitIntegerArgument(const std::string &arg_name, int64_t value)
Visit integer arguments.
virtual void VisitIntegerVariable(const IntVar *variable, IntExpr *delegate)
virtual void VisitSequenceArrayArgument(const std::string &arg_name, const std::vector< SequenceVar * > &arguments)
virtual void VisitIntegerMatrixArgument(const std::string &arg_name, const IntTupleSet &tuples)
virtual void VisitIntegerVariableEvaluatorArgument(const std::string &arg_name, const Solver::Int64ToIntVar &arguments)
Helpers.
static const char kStartSyncOnStartOperation[]
virtual void EndVisitModel(const std::string &type_name)
virtual void VisitIntegerExpressionArgument(const std::string &arg_name, IntExpr *argument)
Visit integer expression argument.
virtual void VisitIntegerVariableArrayArgument(const std::string &arg_name, const std::vector< IntVar * > &arguments)
virtual void VisitIntegerArrayArgument(const std::string &arg_name, const std::vector< int64_t > &values)
static const char kUsageLessConstantExtension[]
virtual void BeginVisitConstraint(const std::string &type_name, const Constraint *constraint)
virtual void EndVisitExtension(const std::string &type)
static const char kUsageEqualVariableExtension[]
static const char kCountAssignedItemsExtension[]
Extension names:
virtual void VisitIntervalVariable(const IntervalVar *variable, const std::string &operation, int64_t value, IntervalVar *delegate)
void VisitInt64ToInt64Extension(const Solver::IndexEvaluator1 &eval, int64_t index_min, int64_t index_max)
virtual void BeginVisitExtension(const std::string &type)
static const char kWeightedSumOfAssignedEqualVariableExtension[]
virtual void VisitSequenceArgument(const std::string &arg_name, SequenceVar *argument)
Visit sequence argument.
virtual void EndVisitIntegerExpression(const std::string &type_name, const IntExpr *expr)
static const char kAbs[]
Constraint and Expression types.
virtual void EndVisitConstraint(const std::string &type_name, const Constraint *constraint)
Subclass of RevArray<T> which adds numerical operations.
void Decr(Solver *const s, int index)
void Add(Solver *const s, int index, const T &to_add)
void Incr(Solver *const s, int index)
void Add(Solver *const s, const T &to_add)
Base objective monitor class. All metaheuristics derive from this.
bool CurrentInternalValuesAreConstraining() const
Definition search.cc:3055
const std::vector< IntVar * > & minimization_vars() const
IntVar * MinimizationVar(int index) const
const std::vector< IntVar * > & objective_vars() const
void SetCurrentInternalValue(int index, int64_t value)
void MakeMinimizationVarsLessOrEqualWithSteps(const T &upper_bounds)
int64_t CurrentInternalValue(int index) const
bool AcceptDelta(Assignment *delta, Assignment *deltadelta) override
Definition search.cc:3005
void Accept(ModelVisitor *visitor) const override
Accepts the given model visitor.
Definition search.cc:3045
ObjectiveMonitor(Solver *solver, const std::vector< bool > &maximize, std::vector< IntVar * > vars, std::vector< int64_t > steps)
-------— Objective Management -------—
Definition search.cc:2948
IntVar * MakeMinimizationVarsLessOrEqualWithStepsStatus(const T &upper_bounds)
void EnterSearch() override
Beginning of the search.
Definition search.cc:2982
ObjectiveMonitor & operator=(const ObjectiveMonitor &)=delete
void BeginNextDecision(DecisionBuilder *db) override
Internal methods.
Definition search.cc:3077
int64_t best() const
Returns the best value found during search.
void RefuteDecision(Decision *d) override
Before refuting the decision.
Definition search.cc:3090
IntVar * var() const
Returns the variable that is optimized.
OptimizeVar(Solver *solver, bool maximize, IntVar *var, int64_t step)
Definition search.cc:3068
std::string DebugString() const override
Definition search.cc:3119
virtual std::string Name() const
Definition search.cc:3117
void SetUnassigned(int var_index)
Definition pack.cc:444
void SetAssigned(int var_index)
Definition pack.cc:436
void Assign(int var_index, int bin_index)
Definition pack.cc:416
bool IsPossible(int var_index, int bin_index) const
Definition pack.cc:428
void Post() override
Definition pack.cc:127
void AddCountUsedBinDimension(IntVar *count_var)
Definition pack.cc:1598
Pack(Solver *s, const std::vector< IntVar * > &vars, int number_of_bins)
--— Pack --—
Definition pack.cc:108
void AddWeightedSumLessOrEqualConstantDimension(const std::vector< int64_t > &weights, const std::vector< int64_t > &bounds)
-------— API -------—
Definition pack.cc:1529
void AddSumVariableWeightsLessOrEqualConstantDimension(const std::vector< IntVar * > &usage, const std::vector< int64_t > &capacity)
Definition pack.cc:1588
void AddCountAssignedItemsDimension(IntVar *count_var)
Definition pack.cc:1605
void UnassignAllRemainingItems()
Definition pack.cc:493
void AssignAllRemainingItems()
Definition pack.cc:483
std::string DebugString() const override
--------------— Constraint class ----------------—
Definition pack.cc:380
void AssignAllPossibleToBin(int bin_index)
Definition pack.cc:466
void Accept(ModelVisitor *visitor) const override
Accepts the given visitor.
Definition pack.cc:393
IntVar * AssignVar(int var_index, int bin_index) const
Definition pack.cc:432
bool IsAssignedStatusKnown(int var_index) const
Definition pack.cc:424
void AssignFirstPossibleToBin(int bin_index)
Definition pack.cc:476
void AddWeightedSumEqualVarDimension(const std::vector< int64_t > &weights, const std::vector< IntVar * > &loads)
Definition pack.cc:1559
void RemoveAllPossibleFromBin(int bin_index)
Definition pack.cc:456
void AddWeightedSumOfAssignedDimension(const std::vector< int64_t > &weights, IntVar *cost_var)
Definition pack.cc:1579
void InitialPropagate() override
Definition pack.cc:190
void SetImpossible(int var_index, int bin_index)
Definition pack.cc:408
void OneDomain(int var_index)
Definition pack.cc:334
bool IsUndecided(int var_index, int bin_index) const
Definition pack.cc:404
ProfiledDecisionBuilder(DecisionBuilder *db)
--------------— ProfiledDecisionBuilder ---------—
std::string DebugString() const override
-------— Decision Builder -------—
void Accept(ModelVisitor *visitor) const override
void AppendMonitors(Solver *solver, std::vector< SearchMonitor * > *extras) override
PropagationBaseObject & operator=(const PropagationBaseObject &)=delete
void ExecuteAll(const SimpleRevFIFO< Demon * > &demons)
virtual std::string name() const
Object naming.
void set_variable_to_clean_on_fail(IntVar *v)
Shortcut for variable cleaner.
void EnqueueAll(const SimpleRevFIFO< Demon * > &demons)
virtual std::string BaseName() const
Returns a base name for automatic naming.
void reset_action_on_fail()
This method clears the failure callback.
bool HasName() const
Returns whether the object has been named or not.
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
Definition search.cc:4388
bool IsUncheckedSolutionLimitReached() override
Definition search.cc:4448
void Install() override
A search monitors adds itself on the active search.
Definition search.cc:4369
bool CheckWithOffset(absl::Duration offset) override
Definition search.cc:4396
void Init() override
This method is called when the search limit is initialized.
Definition search.cc:4417
std::string DebugString() const override
Definition search.cc:4454
void Accept(ModelVisitor *visitor) const override
Accepts the given model visitor.
Definition search.cc:4462
void ExitSearch() override
End of the search.
Definition search.cc:4428
RegularLimit(Solver *s, absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check, bool cumulative)
--— Regular Limit --—
Definition search.cc:4348
void Copy(const SearchLimit *limit) override
Definition search.cc:4377
void UpdateLimits(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions)
Definition search.cc:4439
RegularLimit * MakeIdenticalClone() const
Definition search.cc:4390
const T & Value(int index) const
RevArray(int size, const T &val)
void SetValue(Solver *const s, int index, const T &val)
const T & operator[](int index) const
void SetValue(Solver *const s, const T &val)
Base class of all search limits.
~SearchLimit() override
-------— Search Limits -------—
Definition search.cc:4309
std::string DebugString() const override
void BeginNextDecision(DecisionBuilder *b) override
Before calling DecisionBuilder::Next.
Definition search.cc:4323
void PeriodicCheck() override
Periodic call to check limits in long running methods.
Definition search.cc:4333
bool crossed() const
Returns true if the limit has been crossed.
virtual void Copy(const SearchLimit *limit)=0
void EnterSearch() override
Internal methods.
Definition search.cc:4318
virtual void Init()=0
This method is called when the search limit is initialized.
void Install() override
A search monitors adds itself on the active search.
Definition search.cc:4311
SearchLimit & operator=(const SearchLimit &)=delete
virtual bool CheckWithOffset(absl::Duration offset)=0
void RefuteDecision(Decision *d) override
Before refuting the decision.
Definition search.cc:4328
virtual SearchLimit * MakeClone() const =0
Allocates a clone of the limit.
A search monitor is a simple set of callbacks to monitor all search events.
virtual void Install()
A search monitors adds itself on the active search.
virtual void BeginInitialPropagation()
Before the initial propagation.
virtual void EndFail()
After completing the backtrack.
virtual void RestartSearch()
Restart the search.
virtual void EndInitialPropagation()
After the initial propagation.
virtual bool AcceptDelta(Assignment *delta, Assignment *deltadelta)
virtual void BeginNextDecision(DecisionBuilder *b)
Before calling DecisionBuilder::Next.
virtual void RefuteDecision(Decision *d)
Before refuting the decision.
virtual void EndNextDecision(DecisionBuilder *b, Decision *d)
After calling DecisionBuilder::Next, along with the returned decision.
virtual void ApplyDecision(Decision *d)
Before applying the decision.
virtual void Accept(ModelVisitor *visitor) const
Accepts the given model visitor.
virtual void ExitSearch()
End of the search.
virtual void PeriodicCheck()
Periodic call to check limits in long running methods.
virtual void NoMoreSolutions()
When the search tree is finished.
void ListenToEvent(Solver::MonitorEvent event)
virtual void BeginFail()
Just when the failure occurs.
virtual void EnterSearch()
Beginning of the search.
virtual void AfterDecision(Decision *d, bool apply)
virtual void AcceptNeighbor()
After accepting a neighbor during local search.
virtual void AcceptUncheckedNeighbor()
After accepting an unchecked neighbor during local search.
---------------— Search class --------------—
void WriteToProto(SequenceVarAssignment *sequence_var_assignment_proto) const
bool operator==(const SequenceVarElement &element) const
SequenceVarElement()
--— SequenceVarElement --—
void SetUnperformed(const std::vector< int > &unperformed)
const std::vector< int > & ForwardSequence() const
void Copy(const SequenceVarElement &element)
void SetBackwardSequence(const std::vector< int > &backward_sequence)
const std::vector< int > & BackwardSequence() const
void SetSequence(const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
void SetForwardSequence(const std::vector< int > &forward_sequence)
void LoadFromProto(const SequenceVarAssignment &sequence_var_assignment_proto)
const std::vector< int > & Unperformed() const
void HorizonRange(int64_t *hmin, int64_t *hmax) const
virtual void Accept(ModelVisitor *visitor) const
Accepts the given visitor.
void RankSequence(const std::vector< int > &rank_first, const std::vector< int > &rank_last, const std::vector< int > &unperformed)
IntervalVar * Interval(int index) const
Returns the index_th interval of the sequence.
void ComputePossibleFirstsAndLasts(std::vector< int > *possible_firsts, std::vector< int > *possible_lasts)
int64_t size() const
Returns the number of interval vars in the sequence.
SequenceVar(Solver *s, const std::vector< IntervalVar * > &intervals, const std::vector< IntVar * > &nexts, const std::string &name)
--— SequenceVar --—
void ComputeStatistics(int *ranked, int *not_ranked, int *unperformed) const
Compute statistics on the sequence.
void FillSequence(std::vector< int > *rank_first, std::vector< int > *rank_last, std::vector< int > *unperformed) const
std::string DebugString() const override
void ActiveHorizonRange(int64_t *hmin, int64_t *hmax) const
void DurationRange(int64_t *dmin, int64_t *dmax) const
std::string DebugString() const override
int64_t branches(int n) const
Returns the number of branches when the nth solution was found.
Definition search.cc:2470
SolutionData BuildSolutionDataForCurrentState()
Definition search.cc:2420
void AddObjectives(const std::vector< IntVar * > &objectives)
Definition search.cc:2397
const std::vector< int > & ForwardSequence(int n, SequenceVar *var) const
Definition search.cc:2510
void Add(IntVar *var)
Add API.
Definition search.cc:2355
SolutionCollector & operator=(const SolutionCollector &)=delete
std::vector< std::unique_ptr< Assignment > > solution_pool_
int64_t PerformedValue(int n, IntervalVar *var) const
This is a shortcut to get the PerformedValue of 'var' in the nth solution.
Definition search.cc:2506
void EnterSearch() override
Beginning of the search.
Definition search.cc:2403
void FreeSolution(Assignment *solution)
Definition search.cc:2441
void Push(const SolutionData &data)
void PopSolution()
Remove and delete the last popped solution.
Definition search.cc:2412
const std::vector< int > & Unperformed(int n, SequenceVar *var) const
Definition search.cc:2520
void AddObjective(IntVar *objective)
Definition search.cc:2391
bool has_solution() const
Returns whether any solutions were stored during the search.
Definition search.cc:2463
int solution_count() const
Returns how many solutions were stored during the search.
Definition search.cc:2461
void Install() override
A search monitors adds itself on the active search.
Definition search.cc:2351
int64_t wall_time(int n) const
Returns the wall time in ms for the nth solution.
Definition search.cc:2465
void PushSolution()
Push the current state as a new solution.
Definition search.cc:2408
int64_t DurationValue(int n, IntervalVar *var) const
This is a shortcut to get the DurationValue of 'var' in the nth solution.
Definition search.cc:2498
int64_t ObjectiveValueFromIndex(int n, int index) const
Returns the value of the index-th objective of the nth solution.
Definition search.cc:2485
const std::vector< int > & BackwardSequence(int n, SequenceVar *var) const
Definition search.cc:2515
int64_t StartValue(int n, IntervalVar *var) const
This is a shortcut to get the StartValue of 'var' in the nth solution.
Definition search.cc:2494
SolutionCollector(Solver *solver, const Assignment *assignment)
-------— Solution Collectors --------—
Definition search.cc:2313
int64_t Value(int n, IntVar *var) const
This is a shortcut to get the Value of 'var' in the nth solution.
Definition search.cc:2490
std::vector< Assignment * > recycle_solutions_
std::vector< SolutionData > solution_data_
std::unique_ptr< Assignment > prototype_
Assignment * last_solution_or_null() const
Returns the last solution if there are any, nullptr otherwise.
Definition search.cc:2457
int64_t EndValue(int n, IntervalVar *var) const
This is a shortcut to get the EndValue of 'var' in the nth solution.
Definition search.cc:2502
virtual bool SyncNeeded(Assignment *local_assignment)=0
virtual void Initialize(Assignment *assignment)=0
virtual void RegisterNewSolution(Assignment *assignment)=0
virtual void GetNextSolution(Assignment *assignment)=0
For the time being, Solver is neither MT_SAFE nor MT_HOT.
Constraint * MakeIsLexicalLessOrEqualWithOffsetsCt(std::vector< IntVar * > left, std::vector< IntVar * > right, std::vector< int64_t > offsets, IntVar *boolvar)
Semi-reified version of the above: boolvar -> LexLE(left, right, offsets).
static ConstraintSolverParameters DefaultSolverParameters()
--— ConstraintSolverParameters --—
Constraint * MakeDistribute(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values, const std::vector< IntVar * > &cards)
Aggregated version of count: |{i | v[i] == values[j]}| == cards[j].
Definition count_cst.cc:966
void SetBranchSelector(BranchSelector bs)
Sets the given branch selector on the current active search.
IntervalVar * MakeMirrorInterval(IntervalVar *interval_var)
--— API --—
Definition interval.cc:2249
IntExpr * MakeElement(const std::vector< int64_t > &values, IntVar *index)
values[index]
Definition element.cc:658
OptimizationDirection optimization_direction() const
The direction of optimization, getter and setter.
Constraint * MakePathConnected(std::vector< IntVar * > nexts, std::vector< int64_t > sources, std::vector< int64_t > sinks, std::vector< IntVar * > status)
std::function< int64_t(const IntVar *v, int64_t id)> VariableValueSelector
Constraint * MakeIsLessOrEqualCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left <= right)
Definition range_cst.cc:736
Decision * MakeAssignVariablesValuesOrDoNothing(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
Definition search.cc:1854
Demon * RegisterDemon(Demon *demon)
Adds a new demon and wraps it inside a DemonProfiler if necessary.
Search * ActiveSearch() const
Returns the active search, nullptr outside search.
Constraint * MakeScalProdLessOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
Constraint * MakeIsEqualCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var == value)
Definition expr_cst.cc:493
Demon * MakeClosureDemon(Closure closure)
Creates a demon from a closure.
IntExpr * MakeScalProd(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefs)
scalar product
IntVar * MakeIsGreaterOrEqualVar(IntExpr *left, IntExpr *right)
status var of (left >= right)
Definition range_cst.cc:791
IntExpr * MakeDiv(IntExpr *expr, int64_t value)
expr / value (integer division)
Constraint * MakeSortingConstraint(const std::vector< IntVar * > &vars, const std::vector< IntVar * > &sorted)
bool IsLocalSearchProfilingEnabled() const
Returns whether we are profiling local search.
void ExportProfilingOverview(const std::string &filename)
Constraint * MakeLexicalLess(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
bool NextSolution()
Search for the next solution in the search tree.
Constraint * MakeSumEquality(const std::vector< IntVar * > &vars, int64_t cst)
DecisionBuilder * MakeSolveOnce(DecisionBuilder *db)
Definition search.cc:4887
IntVar * MakeBoolVar(const std::string &name)
MakeBoolVar will create a variable with a {0, 1} domain.
uint64_t fail_stamp() const
The fail_stamp() is incremented after each backtrack.
int64_t accepted_neighbors() const
The number of accepted neighbors.
DecisionBuilder * MakeApplyBranchSelector(BranchSelector bs)
Creates a decision builder that will set the branch selector.
Constraint * MakeNotMemberCt(IntExpr *expr, const std::vector< int64_t > &values)
expr not in set.
Definition expr_cst.cc:1239
void set_fail_intercept(std::function< void()> fail_intercept)
Internal.
Constraint * MakeIsGreaterCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left > right)
Definition range_cst.cc:806
DecisionBuilder * MakeRestoreAssignment(Assignment *assignment)
Constraint * MakeIsGreaterOrEqualCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left >= right)
Definition range_cst.cc:796
SearchMonitor * MakeEnterSearchCallback(std::function< void()> callback)
--— Callback-based search monitors --—
Definition search.cc:490
LocalSearchOperator * MakeMoveTowardTargetOperator(const Assignment &target)
Constraint * MakeIsEqualCt(IntExpr *v1, IntExpr *v2, IntVar *b)
b == (v1 == v2)
Definition range_cst.cc:628
IntVar * MakeIsMemberVar(IntExpr *expr, const std::vector< int64_t > &values)
Definition expr_cst.cc:1501
Decision * MakeAssignVariableValueOrFail(IntVar *var, int64_t value)
Definition search.cc:1654
Constraint * MakeNonEquality(IntExpr *left, IntExpr *right)
left != right
Definition range_cst.cc:570
IntVar * MakeIsEqualCstVar(IntExpr *var, int64_t value)
status var of (var == value)
Definition expr_cst.cc:468
Constraint * MakeSubCircuit(const std::vector< IntVar * > &nexts)
Decision * MakeVariableLessOrEqualValue(IntVar *var, int64_t value)
Definition search.cc:1742
IntExpr * MakeMax(const std::vector< IntVar * > &vars)
std::max(vars)
SearchMonitor * MakeLubyRestart(int scale_factor)
Definition search.cc:5119
int64_t branches() const
The number of branches explored since the creation of the solver.
OptimizeVar * MakeWeightedOptimize(bool maximize, const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a weighted objective with a given sense (true = maximization).
Definition search.cc:3174
IntervalVar * MakeFixedDurationStartSyncedOnEndIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Definition interval.cc:2450
LocalSearchOperator * ConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
std::function< DecisionModification()> BranchSelector
IntExpr * MakeDifference(IntExpr *left, IntExpr *right)
left - right
SearchMonitor * MakeConstantRestart(int frequency)
Definition search.cc:5154
int64_t solutions() const
The number of solutions found since the start of the search.
LocalSearchFilter * MakeVariableDomainFilter()
bool NameAllVariables() const
Returns whether all variables should be named.
DecisionBuilder * MakeNestedOptimize(DecisionBuilder *db, Assignment *solution, bool maximize, int64_t step)
Definition search.cc:5006
Constraint * MakeMemberCt(IntExpr *expr, const std::vector< int64_t > &values)
--— Member and related constraints --—
Definition expr_cst.cc:1169
ABSL_MUST_USE_RESULT RegularLimit * MakeSolutionsLimit(int64_t solutions)
Definition search.cc:4522
Constraint * MakeGreaterOrEqual(IntExpr *left, IntExpr *right)
left >= right
Definition range_cst.cc:548
void AddPropagationMonitor(PropagationMonitor *monitor)
Decision * MakeRankLastInterval(SequenceVar *sequence, int index)
IntVar * MakeBoolVar()
MakeBoolVar will create a variable with a {0, 1} domain.
LocalSearchPhaseParameters * MakeLocalSearchPhaseParameters(IntVar *objective, LocalSearchOperator *ls_operator, DecisionBuilder *sub_decision_builder)
Local Search Phase Parameters.
void MakeIntervalVarArray(int count, int64_t start_min, int64_t start_max, int64_t duration_min, int64_t duration_max, int64_t end_min, int64_t end_max, bool optional, absl::string_view name, std::vector< IntervalVar * > *array)
Definition interval.cc:2425
SolutionCollector * MakeBestValueSolutionCollector(const Assignment *assignment, bool maximize)
Definition search.cc:2732
IntVar * MakeIsLessOrEqualCstVar(IntExpr *var, int64_t value)
status var of (var <= value)
Definition expr_cst.cc:785
Constraint * MakeIfThenElseCt(IntVar *condition, IntExpr *then_expr, IntExpr *else_expr, IntVar *target_var)
Special cases with arrays of size two.
Definition element.cc:1609
Solver & operator=(const Solver &)=delete
IntExpr * MakeSum(IntExpr *left, IntExpr *right)
--— Integer Expressions --—
Constraint * MakeCumulative(const std::vector< IntervalVar * > &intervals, const std::vector< int64_t > &demands, int64_t capacity, const std::string &name)
Demands are constant.
Definition resource.cc:2620
ABSL_MUST_USE_RESULT SearchLimit * MakeCustomLimit(std::function< bool()> limiter)
Definition search.cc:4844
Constraint * MakeScalProdEquality(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
Constraint * MakeIsMemberCt(IntExpr *expr, const std::vector< int64_t > &values, IntVar *boolvar)
boolvar == (expr in set)
Definition expr_cst.cc:1489
static constexpr int kNumPriorities
Number of priorities for demons.
IntExpr * MakeMin(const std::vector< IntVar * > &vars)
std::min(vars)
void Fail()
Abandon the current branch in the search tree. A backtrack will follow.
Constraint * MakePathCumul(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, const std::vector< IntVar * > &cumuls, const std::vector< IntVar * > &transits)
const ConstraintSolverParameters & const_parameters() const
Read-only.
IntVar * MakeIsDifferentVar(IntExpr *v1, IntExpr *v2)
status var of (v1 != v2)
Definition range_cst.cc:647
IntervalVar * MakeIntervalVar(int64_t start_min, int64_t start_max, int64_t duration_min, int64_t duration_max, int64_t end_min, int64_t end_max, bool optional, const std::string &name)
Variable Duration Interval Var.
Definition interval.cc:2416
ABSL_MUST_USE_RESULT RegularLimit * MakeFailuresLimit(int64_t failures)
Definition search.cc:4515
Decision * balancing_decision() const
int64_t demon_runs(DemonPriority p) const
The number of demons executed during search for a given priority.
@ NORMAL_PRIORITY
NORMAL_PRIORITY is the highest priority: Demons will be processed first.
@ VAR_PRIORITY
VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.
std::function< void(Solver *)> Action
OptimizeVar * MakeWeightedMinimize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Definition search.cc:3181
void NewSearch(DecisionBuilder *db, const std::vector< SearchMonitor * > &monitors)
Opens a new top level search.
std::function< bool(int64_t)> IndexFilter1
IntVarLocalSearchFilter * MakeSumObjectiveFilter(const std::vector< IntVar * > &vars, IndexEvaluator2 values, Solver::LocalSearchFilterBound filter_enum)
Constraint * MakeNonOverlappingNonStrictBoxesConstraint(const std::vector< IntVar * > &x_vars, const std::vector< IntVar * > &y_vars, const std::vector< IntVar * > &x_size, const std::vector< IntVar * > &y_size)
Definition diffn.cc:330
DecisionBuilder * MakeProfiledDecisionBuilderWrapper(DecisionBuilder *db)
Activates profiling on a decision builder.
bool UseFastLocalSearch() const
Returns true if fast local search is enabled.
IntVar * MakeIsGreaterVar(IntExpr *left, IntExpr *right)
status var of (left > right)
Definition range_cst.cc:802
Decision * MakeVariableGreaterOrEqualValue(IntVar *var, int64_t value)
Definition search.cc:1747
LocalSearchMonitor * GetLocalSearchMonitor() const
Returns the local search monitor.
Assignment * RunUncheckedLocalSearch(const Assignment *initial_solution, LocalSearchFilterManager *filter_manager, LocalSearchOperator *ls_operator, const std::vector< SearchMonitor * > &monitors, RegularLimit *limit, absl::flat_hash_set< IntVar * > *touched=nullptr)
IntVar * MakeIsLessVar(IntExpr *left, IntExpr *right)
status var of (left < right)
Definition range_cst.cc:748
ABSL_MUST_USE_RESULT RegularLimit * MakeTimeLimit(absl::Duration time)
Creates a search limit that constrains the running time.
Definition search.cc:4501
const std::string & context() const
Gets the current context of the search.
Constraint * MakeCircuit(const std::vector< IntVar * > &nexts)
Force the "nexts" variable to create a complete Hamiltonian path.
Constraint * MakeDeviation(const std::vector< IntVar * > &vars, IntVar *deviation_var, int64_t total_sum)
Definition deviation.cc:414
SolverState
This enum represents the state of the solver w.r.t. the search.
@ IN_SEARCH
Executing the search code.
@ IN_ROOT_NODE
Executing the root node.
@ PROBLEM_INFEASIBLE
After search, the model is infeasible.
@ NO_MORE_SOLUTIONS
After failed NextSolution and before EndSearch.
@ OUTSIDE_SEARCH
Before search, after search.
@ AT_SOLUTION
After successful NextSolution and before EndSearch.
void set_context(absl::string_view context)
Sets the current context of the search.
DisjunctiveConstraint * MakeDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
-------— Factory methods -------—
Definition resource.cc:2608
LocalSearchStatistics GetLocalSearchStatistics() const
Returns detailed local search statistics.
void SaveAndAdd(T *adr, T val)
All-in-one SaveAndAdd_value.
IntVar * RegisterIntVar(IntVar *var)
Registers a new IntVar and wraps it inside a TraceIntVar if necessary.
Definition trace.cc:860
Constraint * MakeIsGreaterCstCt(IntExpr *v, int64_t c, IntVar *b)
b == (v > c)
Definition expr_cst.cc:722
DecisionBuilder * Compose(DecisionBuilder *db1, DecisionBuilder *db2)
Definition search.cc:609
ObjectiveMonitor * MakeTabuSearch(bool maximize, IntVar *objective, int64_t step, const std::vector< IntVar * > &vars, int64_t keep_tenure, int64_t forbid_tenure, double tabu_factor)
MetaHeuristics which try to get the search out of local optima.
Definition search.cc:3530
std::string LocalSearchProfile() const
IntervalVar * MakeFixedDurationEndSyncedOnStartIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Definition interval.cc:2457
Constraint * MakeAllDifferentExcept(const std::vector< IntVar * > &vars, int64_t escape_value)
DecisionBuilder * MakePhase(const std::vector< IntVar * > &vars, IntVarStrategy var_str, IntValueStrategy val_str)
Definition search.cc:2116
IntVar * MakeIsGreaterCstVar(IntExpr *var, int64_t value)
status var of (var > value)
Definition expr_cst.cc:702
bool CheckAssignment(Assignment *solution)
Checks whether the given assignment satisfies all relevant constraints.
LocalSearchOperator * RandomConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
bool IsBooleanVar(IntExpr *expr, IntVar **inner_var, bool *is_negated) const
void AddBacktrackAction(Action a, bool fast)
void MakeFixedDurationIntervalVarArray(int count, int64_t start_min, int64_t start_max, int64_t duration, bool optional, absl::string_view name, std::vector< IntervalVar * > *array)
Definition interval.cc:2299
Decision * MakeAssignVariableValue(IntVar *var, int64_t val)
Decisions.
Definition search.cc:1616
void SaveAndSetValue(T *adr, T val)
All-in-one SaveAndSetValue.
std::string model_name() const
Returns the name of the model.
LocalSearchFilter * MakeAcceptFilter()
Local Search Filters.
IntExpr * MakeMonotonicElement(IndexEvaluator1 values, bool increasing, IntVar *index)
Definition element.cc:869
Decision * MakeAssignVariablesValuesOrFail(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
Definition search.cc:1861
Decision * MakeScheduleOrExpedite(IntervalVar *var, int64_t est, int64_t *marker)
Constraint * MakeSumLessOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
Variation on arrays.
Constraint * MakeIsLessCstCt(IntExpr *v, int64_t c, IntVar *b)
b == (v < c)
Definition expr_cst.cc:822
SolutionPool * MakeDefaultSolutionPool()
Solution Pool.
Constraint * MakeNonOverlappingBoxesConstraint(const std::vector< IntVar * > &x_vars, const std::vector< IntVar * > &y_vars, const std::vector< IntVar * > &x_size, const std::vector< IntVar * > &y_size)
Definition diffn.cc:300
LocalSearchOperator * MakeNeighborhoodLimit(LocalSearchOperator *op, int64_t limit)
ConstraintSolverStatistics GetConstraintSolverStatistics() const
Returns detailed cp search statistics.
Constraint * MakePathEnergyCostConstraint(PathEnergyCostConstraintSpecification specification)
Decision * MakeSplitVariableDomain(IntVar *var, int64_t val, bool start_with_lower_half)
Definition search.cc:1737
Constraint * MakeSumGreaterOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
Constraint * MakeTemporalDisjunction(IntervalVar *t1, IntervalVar *t2, IntVar *alt)
Constraint * MakeAllowedAssignments(const std::vector< IntVar * > &vars, const IntTupleSet &tuples)
------— API -------—
Definition table.cc:1259
Constraint * MakePathPrecedenceConstraint(std::vector< IntVar * > nexts, const std::vector< std::pair< int, int > > &precedences)
IntervalVar * MakeFixedDurationIntervalVar(int64_t start_min, int64_t start_max, int64_t duration, bool optional, const std::string &name)
Definition interval.cc:2284
DecisionBuilder * MakeLocalSearchPhase(Assignment *assignment, LocalSearchPhaseParameters *parameters)
Constraint * MakeLightElement(F values, IntVar *const var, IntVar *const index, std::function< bool()> deep_serialize=nullptr)
Constraint * MakeLess(IntExpr *left, IntExpr *right)
left < right
Definition range_cst.cc:552
IntExpr * CastExpression(const IntVar *var) const
!defined(SWIG)
ModelCache * Cache() const
Returns the cache of the model.
IntExpr * MakeOpposite(IntExpr *expr)
-expr
Constraint * MakeAtMost(std::vector< IntVar * > vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| <= max_count
Definition count_cst.cc:957
ABSL_MUST_USE_RESULT ImprovementSearchLimit * MakeLexicographicImprovementLimit(std::vector< IntVar * > objective_vars, std::vector< bool > maximize, std::vector< double > objective_scaling_factors, std::vector< double > objective_offsets, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
Definition search.cc:4730
Constraint * MakeAbsEquality(IntVar *var, IntVar *abs_var)
Creates the constraint abs(var) == abs_var.
OptimizeVar * MakeOptimize(bool maximize, IntVar *v, int64_t step)
Creates a objective with a given sense (true = maximization).
Definition search.cc:3138
void MakeBoolVarArray(int var_count, const std::string &name, std::vector< IntVar * > *vars)
DecisionBuilder * MakeConstraintAdder(Constraint *ct)
@ STARTS_BEFORE
t starts before d, i.e. Start(t) <= d.
@ ENDS_AT
t ends at d, i.e. End(t) == d.
@ STARTS_AFTER
t starts after d, i.e. Start(t) >= d.
@ ENDS_BEFORE
t ends before d, i.e. End(t) <= d.
@ STARTS_AT
t starts at d, i.e. Start(t) == d.
@ ENDS_AFTER
t ends after d, i.e. End(t) >= d.
IntExpr * MakePiecewiseLinearExpr(IntExpr *expr, const PiecewiseLinearFunction &f)
IntExpr * RegisterIntExpr(IntExpr *expr)
Registers a new IntExpr and wraps it inside a TraceIntExpr if necessary.
Definition trace.cc:848
int64_t neighbors() const
The number of neighbors created.
Constraint * MakeIsDifferentCt(IntExpr *v1, IntExpr *v2, IntVar *b)
b == (v1 != v2)
Definition range_cst.cc:692
Constraint * MakeNullIntersectExcept(const std::vector< IntVar * > &first_vars, const std::vector< IntVar * > &second_vars, int64_t escape_value)
IntExpr * MakeModulo(IntExpr *x, int64_t mod)
Modulo expression x % mod (with the python convention for modulo).
Constraint * MakeGreater(IntExpr *left, IntExpr *right)
left > right
Definition range_cst.cc:566
DisjunctiveConstraint * MakeStrictDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
Definition resource.cc:2613
Constraint * MakeLexicalLessOrEqual(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
OptimizationDirection
Optimization directions.
IntVar * MakeIsEqualVar(IntExpr *v1, IntExpr *v2)
status var of (v1 == v2)
Definition range_cst.cc:583
IntVar * MakeIsDifferentCstVar(IntExpr *var, int64_t value)
status var of (var != value)
Definition expr_cst.cc:586
SearchMonitor * MakeAtSolutionCallback(std::function< void()> callback)
Definition search.cc:465
Constraint * MakeCount(const std::vector< IntVar * > &vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| == max_count
Definition count_cst.cc:33
@ CHOOSE_RANDOM
Randomly select one of the remaining unbound variables.
@ INT_VAR_DEFAULT
The default behavior is CHOOSE_FIRST_UNBOUND.
@ INT_VAR_SIMPLE
The simple selection is CHOOSE_FIRST_UNBOUND.
IntVar * MakeIsBetweenVar(IntExpr *v, int64_t l, int64_t u)
Definition expr_cst.cc:1093
Constraint * MakeElementEquality(const std::vector< int64_t > &vals, IntVar *index, IntVar *target)
Definition element.cc:1681
IntervalVar * MakeFixedInterval(int64_t start, int64_t duration, const std::string &name)
Creates a fixed and performed interval.
Definition interval.cc:2279
Pack * MakePack(const std::vector< IntVar * > &vars, int number_of_bins)
Definition pack.cc:1612
@ LE
Move is accepted when the current objective value <= objective.Max.
@ GE
Move is accepted when the current objective value >= objective.Min.
DecisionBuilder * Try(DecisionBuilder *db1, DecisionBuilder *db2)
Definition search.cc:757
SolutionCollector * MakeAllSolutionCollector()
Definition search.cc:2942
DecisionBuilder * MakeDefaultPhase(const std::vector< IntVar * > &vars)
SequenceStrategy
Used for scheduling. Not yet implemented.
LocalSearchFilter * MakeRejectFilter()
IntervalVar * RegisterIntervalVar(IntervalVar *var)
Definition trace.cc:869
int64_t unchecked_solutions() const
The number of unchecked solutions found by local search.
IntVar * MakeIsGreaterOrEqualCstVar(IntExpr *var, int64_t value)
status var of (var >= value)
Definition expr_cst.cc:685
Constraint * MakeMinEquality(const std::vector< IntVar * > &vars, IntVar *min_var)
Decision * MakeDecision(Action apply, Action refute)
Definition search.cc:667
Constraint * MakeIsLessCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left < right)
Definition range_cst.cc:779
ObjectiveMonitor * MakeLexicographicSimulatedAnnealing(const std::vector< bool > &maximize, std::vector< IntVar * > vars, std::vector< int64_t > steps, std::vector< int64_t > initial_temperatures)
Definition search.cc:3652
SolutionCollector * MakeFirstSolutionCollector()
Definition search.cc:2584
Constraint * MakeIndexOfConstraint(const std::vector< IntVar * > &vars, IntVar *index, int64_t target)
Definition element.cc:1744
int32_t Rand32(int32_t size)
Returns a random value between 0 and 'size' - 1;.
void FinishCurrentSearch()
Tells the solver to kill or restart the current search.
Constraint * MakeDelayedPathCumul(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, const std::vector< IntVar * > &cumuls, const std::vector< IntVar * > &transits)
void Accept(ModelVisitor *visitor) const
Accepts the given model visitor.
Constraint * MakeIndexOfFirstMinValueConstraint(IntVar *index, const std::vector< IntVar * > &vars)
IntExpr * MakeAbs(IntExpr *expr)
expr
Decision * MakeRankFirstInterval(SequenceVar *sequence, int index)
IntExpr * MakeSquare(IntExpr *expr)
expr * expr
std::vector< int64_t > tmp_vector_
SolutionCollector * MakeLastSolutionCollector()
Definition search.cc:2636
ModelVisitor * MakeVariableDegreeVisitor(absl::flat_hash_map< const IntVar *, int > *map)
Compute the number of constraints a variable is attached to.
Definition utilities.cc:822
Constraint * MakeNoCycle(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, IndexFilter1 sink_handler=nullptr)
bool IsProfilingEnabled() const
Returns whether we are profiling the solver.
MonitorEvent
Search monitor events.
@ kLast
Dummy event whose underlying int is the number of MonitorEvent enums.
std::function< int64_t(int64_t, int64_t, int64_t)> IndexEvaluator3
Constraint * MakeIndexOfFirstMaxValueConstraint(IntVar *index, const std::vector< IntVar * > &vars)
DecisionBuilder * MakeStoreAssignment(Assignment *assignment)
ObjectiveMonitor * MakeGuidedLocalSearch(bool maximize, IntVar *objective, IndexEvaluator2 objective_function, int64_t step, const std::vector< IntVar * > &vars, double penalty_factor, bool reset_penalties_on_new_best_solution=false)
Definition search.cc:4269
Constraint * MakeScalProdGreaterOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coeffs, int64_t cst)
IntExpr * MakeIndexExpression(const std::vector< IntVar * > &vars, int64_t value)
Definition element.cc:1759
@ STARTS_AT_START
t1 starts at t2 start, i.e. Start(t1) == Start(t2) + delay.
@ ENDS_AFTER_END
t1 ends after t2 end, i.e. End(t1) >= End(t2) + delay.
@ ENDS_AFTER_START
t1 ends after t2 start, i.e. End(t1) >= Start(t2) + delay.
@ ENDS_AT_END
t1 ends at t2 end, i.e. End(t1) == End(t2) + delay.
@ ENDS_AT_START
t1 ends at t2 start, i.e. End(t1) == Start(t2) + delay.
@ STARTS_AFTER_END
t1 starts after t2 end, i.e. Start(t1) >= End(t2) + delay.
@ STARTS_AFTER_START
t1 starts after t2 start, i.e. Start(t1) >= Start(t2) + delay.
@ STARTS_AT_END
t1 starts at t2 end, i.e. Start(t1) == End(t2) + delay.
SolutionCollector * MakeBestLexicographicValueSolutionCollector(const Assignment *assignment, std::vector< bool > maximize)
Definition search.cc:2737
SearchMonitor * MakeExitSearchCallback(std::function< void()> callback)
Definition search.cc:515
LocalSearchOperator * MultiArmedBanditConcatenateOperators(const std::vector< LocalSearchOperator * > &ops, double memory_coefficient, double exploration_coefficient, bool maximize)
SearchMonitor * MakeSearchTrace(const std::string &prefix)
Definition search.cc:436
Decision * MakeAssignVariablesValues(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
Definition search.cc:1846
SolutionCollector * MakeNBestValueSolutionCollector(const Assignment *assignment, int solution_count, bool maximize)
Definition search.cc:2858
Constraint * MakeMaxEquality(const std::vector< IntVar * > &vars, IntVar *max_var)
void ClearLocalSearchState()
Clears the local search state.
std::function< void()> Closure
Constraint * MakeEquality(IntExpr *left, IntExpr *right)
left == right
Definition range_cst.cc:518
IntervalVar * MakeIntervalRelaxedMax(IntervalVar *interval_var)
Definition interval.cc:2254
IntVar * MakeIsLessOrEqualVar(IntExpr *left, IntExpr *right)
status var of (left <= right)
Definition range_cst.cc:704
LocalSearchOperator * MakeOperator(const std::vector< IntVar * > &vars, LocalSearchOperators op, std::function< const std::vector< int > &(int, int)> get_neighbors=nullptr)
Local Search Operators.
ObjectiveMonitor * MakeLexicographicTabuSearch(const std::vector< bool > &maximize, std::vector< IntVar * > objectives, std::vector< int64_t > steps, const std::vector< IntVar * > &vars, int64_t keep_tenure, int64_t forbid_tenure, double tabu_factor)
Definition search.cc:3540
Assignment * MakeAssignment()
This method creates an empty assignment.
DecisionBuilder * MakeDecisionBuilderFromAssignment(Assignment *assignment, DecisionBuilder *db, const std::vector< IntVar * > &vars)
Definition search.cc:2303
ABSL_MUST_USE_RESULT RegularLimit * MakeBranchesLimit(int64_t branches)
Definition search.cc:4508
@ RELOCATE
Relocate neighborhood with length of 1 (see OROPT comment).
Constraint * MakeTrueConstraint()
This constraint always succeeds.
Decision * MakeScheduleOrPostpone(IntervalVar *var, int64_t est, int64_t *marker)
Demon * MakeDelayedConstraintInitialPropagateCallback(Constraint *ct)
SearchMonitor * MakeSearchLog(int branch_period)
Definition search.cc:309
std::function< IntVar *(int64_t)> Int64ToIntVar
ObjectiveMonitor * MakeSimulatedAnnealing(bool maximize, IntVar *v, int64_t step, int64_t initial_temperature)
Definition search.cc:3645
Constraint * MakeLessOrEqual(IntExpr *left, IntExpr *right)
left <= right
Definition range_cst.cc:532
bool HasName(const PropagationBaseObject *object) const
Returns whether the object has been named or not.
Constraint * MakeIsGreaterOrEqualCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var >= value)
Definition expr_cst.cc:706
OptimizeVar * MakeMinimize(IntVar *v, int64_t step)
Creates a minimization objective.
Definition search.cc:3130
void SetSearchContext(Search *search, absl::string_view search_context)
IntervalVar * MakeFixedDurationEndSyncedOnEndIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Definition interval.cc:2464
Constraint * MakeLexicalLessOrEqualWithOffsets(std::vector< IntVar * > left, std::vector< IntVar * > right, std::vector< int64_t > offsets)
std::string DebugString() const
!defined(SWIG)
Constraint * MakeBetweenCt(IntExpr *expr, int64_t l, int64_t u)
--— Between and related constraints --—
Definition expr_cst.cc:929
DemonProfiler * demon_profiler() const
Access to demon profiler.
Demon * MakeConstraintInitialPropagateCallback(Constraint *ct)
void MakeIntVarArray(int var_count, int64_t vmin, int64_t vmax, const std::string &name, std::vector< IntVar * > *vars)
ABSL_MUST_USE_RESULT RegularLimit * MakeLimit(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check=false, bool cumulative=false)
Definition search.cc:4536
OptimizeVar * MakeWeightedMaximize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a maximization weigthed objective.
Definition search.cc:3188
int64_t filtered_neighbors() const
The number of filtered neighbors (neighbors accepted by filters).
Decision * MakeAssignVariableValueOrDoNothing(IntVar *var, int64_t value)
Definition search.cc:1683
SolverState state() const
State of the solver.
SolutionCollector * MakeNBestLexicographicValueSolutionCollector(const Assignment *assignment, int solution_count, std::vector< bool > maximize)
Definition search.cc:2876
int64_t Rand64(int64_t size)
Returns a random value between 0 and 'size' - 1;.
IntVar * MakeIntVar(int64_t min, int64_t max, const std::string &name)
--— Int Variables and Constants --—
std::function< bool(int64_t, int64_t, int64_t)> VariableValueComparator
ConstraintSolverParameters parameters() const
Stored Parameters.
Constraint * MakeAllDifferent(const std::vector< IntVar * > &vars)
Constraint * MakeIntervalVarRelationWithDelay(IntervalVar *t1, BinaryIntervalRelation r, IntervalVar *t2, int64_t delay)
bool Solve(DecisionBuilder *db, const std::vector< SearchMonitor * > &monitors)
ModelVisitor * MakePrintModelVisitor()
Prints the model.
Definition utilities.cc:814
void SaveValue(T *o)
reversibility
Constraint * MakeFalseConstraint()
This constraint always fails.
friend void InternalSaveBooleanVarValue(Solver *, IntVar *)
ObjectiveMonitor * MakeGenericTabuSearch(bool maximize, IntVar *v, int64_t step, const std::vector< IntVar * > &tabu_vars, int64_t forbid_tenure)
Definition search.cc:3549
void ReSeed(int32_t seed)
Reseed the solver random generator.
@ INTERVAL_DEFAULT
The default is INTERVAL_SET_TIMES_FORWARD.
@ INTERVAL_SIMPLE
The simple is INTERVAL_SET_TIMES_FORWARD.
bool IsProduct(IntExpr *expr, IntExpr **inner_expr, int64_t *coefficient)
IntExpr * MakeConvexPiecewiseExpr(IntExpr *expr, int64_t early_cost, int64_t early_date, int64_t late_date, int64_t late_cost)
Convex piecewise function.
std::function< int64_t(Solver *solver, const std::vector< IntVar * > &vars, int64_t first_unbound, int64_t last_unbound)> VariableIndexSelector
IntervalVar * MakeFixedDurationStartSyncedOnStartIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Synced Interval Vars.
Definition interval.cc:2443
void set_optimization_direction(OptimizationDirection direction)
IntExpr * MakePower(IntExpr *expr, int64_t n)
expr ^ n (n > 0)
IntExpr * MakeConditionalExpression(IntVar *condition, IntExpr *expr, int64_t unperformed_value)
Conditional Expr condition ? expr : unperformed_value.
@ ASSIGN_MAX_VALUE
Selects the max value of the selected variable.
@ INT_VALUE_DEFAULT
The default behavior is ASSIGN_MIN_VALUE.
@ INT_VALUE_SIMPLE
The simple selection is ASSIGN_MIN_VALUE.
@ ASSIGN_MIN_VALUE
Selects the min value of the selected variable.
@ ASSIGN_RANDOM_VALUE
Selects randomly one of the possible values of the selected variable.
OptimizeVar * MakeLexicographicOptimize(std::vector< bool > maximize, std::vector< IntVar * > variables, std::vector< int64_t > steps)
Definition search.cc:3143
std::function< int64_t(int64_t)> IndexEvaluator1
Callback typedefs.
SearchMonitor * MakeSymmetryManager(const std::vector< SymmetryBreaker * > &visitors)
Symmetry Breaking.
Definition search.cc:5293
IntVar * MakeIsLessCstVar(IntExpr *var, int64_t value)
status var of (var < value)
Definition expr_cst.cc:802
IntervalVar * MakeIntervalRelaxedMin(IntervalVar *interval_var)
Definition interval.cc:2263
int64_t failures() const
The number of failures encountered since the creation of the solver.
bool CheckConstraint(Constraint *ct)
RegularLimitParameters MakeDefaultRegularLimitParameters() const
Creates a regular limit proto containing default values.
Definition search.cc:4551
std::function< int64_t(int64_t, int64_t)> IndexEvaluator2
bool InstrumentsDemons() const
Returns whether we are instrumenting demons.
Constraint * MakeIsBetweenCt(IntExpr *expr, int64_t l, int64_t u, IntVar *b)
b == (l <= expr <= u)
Definition expr_cst.cc:1057
Constraint * MakeIsLessOrEqualCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var <= value)
Definition expr_cst.cc:806
PropagationMonitor * GetPropagationMonitor() const
Returns the propagation monitor.
Constraint * MakeTransitionConstraint(const std::vector< IntVar * > &vars, const IntTupleSet &transition_table, int64_t initial_state, const std::vector< int64_t > &final_states)
Definition table.cc:1272
IntExpr * MakeProd(IntExpr *left, IntExpr *right)
left * right
IntVar * MakeIntConst(int64_t val, const std::string &name)
IntConst will create a constant expression.
Constraint * MakeIntervalVarRelation(IntervalVar *t, UnaryIntervalRelation r, int64_t d)
Demon * MakeActionDemon(Action action)
Creates a demon from a callback.
Constraint * MakeNullIntersect(const std::vector< IntVar * > &first_vars, const std::vector< IntVar * > &second_vars)
Solver(const std::string &name)
Solver API.
bool InstrumentsVariables() const
Returns whether we are tracing variables.
Constraint * MakeNotBetweenCt(IntExpr *expr, int64_t l, int64_t u)
Definition expr_cst.cc:962
void AddLocalSearchMonitor(LocalSearchMonitor *monitor)
Constraint * MakePathTransitPrecedenceConstraint(std::vector< IntVar * > nexts, std::vector< IntVar * > transits, const std::vector< std::pair< int, int > > &precedences)
static int64_t MemoryUsage()
Current memory usage in bytes.
Constraint * MakeCover(const std::vector< IntervalVar * > &vars, IntervalVar *target_var)
LocalSearchOperator * MakeRandomLnsOperator(const std::vector< IntVar * > &vars, int number_of_variables)
Constraint * MakeInversePermutationConstraint(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
void SetUseFastLocalSearch(bool use_fast_local_search)
OptimizeVar * MakeMaximize(IntVar *v, int64_t step)
Creates a maximization objective.
Definition search.cc:3134
Constraint * MakeIsDifferentCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var != value)
Definition expr_cst.cc:595
IntExpr * MakeSemiContinuousExpr(IntExpr *expr, int64_t fixed_charge, int64_t step)
ABSL_MUST_USE_RESULT ImprovementSearchLimit * MakeImprovementLimit(IntVar *objective_var, bool maximize, double objective_scaling_factor, double objective_offset, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
Definition search.cc:4721
ModelVisitor * MakeStatisticsModelVisitor()
Displays some nice statistics on the model.
Definition utilities.cc:818
bool SolveAndCommit(DecisionBuilder *db, const std::vector< SearchMonitor * > &monitors)
void AddCastConstraint(CastConstraint *constraint, IntVar *target_var, IntExpr *expr)
int64_t b
Definition table.cc:45
int64_t a
Definition table.cc:44
ABSL_DECLARE_FLAG(int64_t, cp_random_seed)
CpModelProto proto
The output proto.
const std::string name
A name for logging purposes.
const Constraint * ct
int64_t value
IntVar * var
absl::Status status
Definition g_gurobi.cc:44
absl::Span< const double > coefficients
MPCallback * callback
int index
const bool DEBUG_MODE
Definition macros.h:24
double solution
Definition file.cc:169
bool FindCopy(const Collection &collection, const Key &key, Value *const value)
Definition map_util.h:190
const MapUtilMappedT< Collection > & FindWithDefault(const Collection &collection, const KeyType &key, const MapUtilMappedT< Collection > &value)
Definition map_util.h:36
In SWIG mode, we don't want anything besides these top-level includes.
int64_t CapSub(int64_t x, int64_t y)
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
int64_t One()
This method returns 1.
void SetAssignmentFromAssignment(Assignment *target_assignment, const std::vector< IntVar * > &target_vars, const Assignment *source_assignment, const std::vector< IntVar * > &source_vars)
NOLINT.
int64_t CapOpp(int64_t v)
Note(user): -kint64min != kint64max, but kint64max == ~kint64min.
bool Next()
const Variable x
Definition qp_tests.cc:127
int64_t time
Definition resource.cc:1708
int64_t delta
Definition resource.cc:1709
int64_t coefficient
std::vector< double > upper_bounds
Definition lp_utils.cc:747
Rev< int64_t > start_max
Rev< int64_t > end_max
Rev< int64_t > start_min
Rev< int64_t > end_min
int64_t stamp
Definition search.cc:3270
int var_index
Definition search.cc:3268
int64_t start
bool use_last_conflict
Should we use last conflict method. The default is false.
DecisionBuilder * decision_builder
When defined, this overrides the default impact based decision builder.
int heuristic_num_failures_limit
The failure limit for each heuristic that we run.
ValueSelection value_selection_schema
This parameter describes which value to select for a given var.
int random_seed
Seed used to initialize the random part in some heuristics.
static Iterator Begin(IntVarIterator *it)
These are the only way to construct an Iterator.
bool operator<(const SolutionData &other) const
Definition search.cc:2333
---------------— StateMarker / StateInfo struct --------—
double objective_value
The value objective_vector^T * (solution - center_point).
static const int64_t kint64max
Definition types.h:32