68 #ifndef OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_ 69 #define OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_ 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/random/random.h" 90 #include "absl/strings/str_format.h" 91 #include "absl/time/time.h" 105 #endif // !defined(SWIG) 112 class AssignmentProto;
114 class CastConstraint;
117 class DecisionBuilder;
118 class DecisionVisitor;
122 class DisjunctiveConstraint;
123 class ImprovementSearchLimit;
126 class IntVarAssignment;
127 class IntVarLocalSearchFilter;
129 class IntervalVarAssignment;
130 class LocalSearchFilter;
131 class LocalSearchFilterManager;
132 class LocalSearchMonitor;
133 class LocalSearchOperator;
134 class LocalSearchPhaseParameters;
135 class LocalSearchProfiler;
140 class ProfiledDecisionBuilder;
141 class PropagationBaseObject;
142 class PropagationMonitor;
145 class RegularLimitParameters;
151 class SequenceVarAssignment;
152 class SolutionCollector;
154 class SymmetryBreaker;
161 return absl::GetFlag(FLAGS_cp_random_seed) == -1
162 ? absl::Uniform<int64_t>(absl::BitGen(), 0,
kint64max)
163 : absl::GetFlag(FLAGS_cp_random_seed);
743 typedef std::function<int64_t(
Solver* solver,
744 const std::vector<IntVar*>& vars,
745 int64_t first_unbound, int64_t last_unbound)>
748 typedef std::function<int64_t(
const IntVar* v, int64_t
id)>
750 typedef std::function<bool(int64_t, int64_t, int64_t)>
775 InternalSaveValue(o);
790 template <
typename T>
792 return reinterpret_cast<T*>(SafeRevAlloc(
object));
801 template <
typename T>
803 return reinterpret_cast<T*>(SafeRevAllocArray(
object));
888 const std::vector<SearchMonitor*>& monitors);
910 const std::vector<SearchMonitor*>& monitors);
935 const std::vector<SearchMonitor*>& monitors);
975 absl::Time
Now()
const;
1007 uint64_t
stamp()
const;
1014 return optimization_direction_;
1017 optimization_direction_ = direction;
1033 const std::string&
name);
1063 const std::string&
name, std::vector<IntVar*>* vars);
1067 std::vector<IntVar*>* vars);
1070 const std::string&
name);
1076 std::vector<IntVar*>* vars);
1094 const std::vector<int64_t>& coefs);
1097 const std::vector<int>& coefs);
1150 int64_t range_end,
IntVar* argument);
1161 IntVar*
const target_var);
1183 int64_t early_date, int64_t late_date,
1209 int64_t unperformed_value);
1336 const std::vector<int64_t>& coeffs,
1339 const std::vector<int>& coeffs,
1381 Demon* MakeClosureDemon(Closure closure); 1405 const std::vector<int64_t>& values);
1410 const std::vector<int64_t>& values);
1412 const std::vector<int>& values);
1416 std::vector<int64_t> ends);
1419 std::vector<int> ends);
1424 #endif // !defined(SWIG) 1428 const std::vector<int64_t>& values,
1431 const std::vector<int>& values,
1434 const std::vector<int64_t>& values);
1445 IntVar*
const max_count);
1449 const std::vector<int64_t>& values,
1450 const std::vector<IntVar*>& cards);
1453 const std::vector<int>& values,
1454 const std::vector<IntVar*>& cards);
1457 const std::vector<IntVar*>& cards);
1461 int64_t card_max, int64_t card_size);
1466 const std::vector<int64_t>& card_min,
1467 const std::vector<int64_t>& card_max);
1472 const std::vector<int>& card_min,
1473 const std::vector<int>& card_max);
1478 const std::vector<int64_t>& values,
1479 const std::vector<int64_t>& card_min,
1480 const std::vector<int64_t>& card_max);
1485 const std::vector<int>& values,
1486 const std::vector<int>& card_min,
1487 const std::vector<int>& card_max);
1494 IntVar*
const deviation_var, int64_t total_sum);
1504 bool stronger_propagation);
1509 int64_t escape_value);
1528 const std::vector<IntVar*>& sorted);
1536 const std::vector<IntVar*>& right);
1541 const std::vector<IntVar*>& right);
1548 const std::vector<IntVar*>& left,
const std::vector<IntVar*>& right);
1565 const std::vector<IntVar*>& second_vars);
1573 const std::vector<IntVar*>& second_vars,
1574 int64_t escape_value);
1589 const std::vector<IntVar*>& active,
1592 const std::vector<IntVar*>& active,
1607 const std::vector<IntVar*>& active,
1608 const std::vector<IntVar*>& cumuls,
1609 const std::vector<IntVar*>& transits);
1614 const std::vector<IntVar*>& active,
1615 const std::vector<IntVar*>& cumuls,
1616 const std::vector<IntVar*>& transits);
1624 const std::vector<IntVar*>& active,
1625 const std::vector<IntVar*>& cumuls,
1635 const std::vector<IntVar*>& active,
1636 const std::vector<IntVar*>& cumuls,
1637 const std::vector<IntVar*>& slacks,
1644 std::vector<int64_t> sources,
1645 std::vector<int64_t> sinks,
1646 std::vector<IntVar*> status);
1654 std::vector<IntVar*> nexts,
1655 const std::vector<std::pair<int, int>>& precedences);
1665 std::vector<IntVar*> nexts,
1666 const std::vector<std::pair<int, int>>& precedences,
1667 const std::vector<int>& lifo_path_starts,
1668 const std::vector<int>& fifo_path_starts);
1672 std::vector<IntVar*> nexts, std::vector<IntVar*> transits,
1673 const std::vector<std::pair<int, int>>& precedences);
1679 const std::vector<IntVar*>& actives);
1696 const std::vector<IntVar*>& vars,
const IntTupleSet& transition_table,
1697 int64_t initial_state,
const std::vector<int64_t>& final_states);
1708 int64_t initial_state,
1709 const std::vector<int>& final_states);
1711 #if defined(SWIGPYTHON) 1714 const std::vector<IntVar*>& vars,
1715 const std::vector<std::vector<int64_t> >& raw_tuples) {
1722 const std::vector<IntVar*>& vars,
1723 const std::vector<std::vector<int64_t> >&
1725 int64_t initial_state,
const std::vector<int>& final_states) {
1726 IntTupleSet transitions(3);
1727 transitions.InsertAll(raw_transitions);
1742 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1743 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1745 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1746 const std::vector<int64_t>& x_size,
const std::vector<int64_t>& y_size);
1748 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1749 const std::vector<int>& x_size,
const std::vector<int>& y_size);
1760 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1761 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1763 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1764 const std::vector<int64_t>& x_size,
const std::vector<int64_t>& y_size);
1766 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1767 const std::vector<int>& x_size,
const std::vector<int>& y_size);
1774 Pack*
MakePack(
const std::vector<IntVar*>& vars,
int number_of_bins);
1783 const std::string&
name);
1789 bool optional,
const std::string&
name,
1790 std::vector<IntervalVar*>*
const array);
1796 const std::string&
name);
1802 IntVar*
const performed_variable,
1803 const std::string&
name);
1808 const std::vector<IntVar*>& start_variables, int64_t duration,
1809 const std::string&
name, std::vector<IntervalVar*>*
const array);
1814 const std::vector<IntVar*>& start_variables,
1815 const std::vector<int64_t>& durations,
const std::string&
name,
1816 std::vector<IntervalVar*>*
const array);
1820 const std::vector<IntVar*>& start_variables,
1821 const std::vector<int>& durations,
const std::string&
name,
1822 std::vector<IntervalVar*>*
const array);
1827 const std::vector<IntVar*>& start_variables,
1828 const std::vector<int64_t>& durations,
1829 const std::vector<IntVar*>& performed_variables,
const std::string&
name,
1830 std::vector<IntervalVar*>*
const array);
1835 const std::vector<IntVar*>& start_variables,
1836 const std::vector<int>& durations,
1837 const std::vector<IntVar*>& performed_variables,
const std::string&
name,
1838 std::vector<IntervalVar*>*
const array);
1842 const std::string&
name);
1847 int64_t duration_min, int64_t duration_max,
1849 const std::string&
name);
1854 int64_t duration_min, int64_t duration_max,
1856 const std::string&
name,
1857 std::vector<IntervalVar*>*
const array);
1868 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1875 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1882 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1889 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1937 IntervalVar*
const t2);
1945 IntervalVar*
const t2,
1952 IntervalVar*
const t2,
IntVar*
const alt);
1957 IntervalVar*
const t2);
1962 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
1968 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
1980 const std::vector<int64_t>& demands,
1993 const std::vector<int>& demands, int64_t
capacity,
1994 const std::string&
name);
2006 const std::vector<int64_t>& demands,
2019 const std::vector<int>& demands,
2030 const std::vector<IntVar*>& demands,
2041 const std::vector<IntVar*>& demands,
2050 IntervalVar*
const target_var);
2063 const Assignment*
const assignment);
2070 const Assignment*
const assignment);
2080 const Assignment*
const assignment,
bool maximize);
2092 const Assignment*
const assignment,
int solution_count,
bool maximize);
2098 const Assignment*
const assignment);
2115 const std::vector<int64_t>& weights,
2121 const std::vector<int>& weights,
2126 const std::vector<int64_t>& weights,
2131 const std::vector<int>& weights,
2136 const std::vector<IntVar*>& sub_objectives,
2137 const std::vector<int64_t>& weights,
2142 const std::vector<IntVar*>& sub_objectives,
2143 const std::vector<int>& weights,
2165 const std::vector<IntVar*>& vars,
2166 int64_t keep_tenure, int64_t forbid_tenure,
2167 double tabu_factor);
2173 const std::vector<IntVar*>& tabu_vars,
2174 int64_t forbid_tenure);
2180 int64_t initial_temperature);
2187 const std::vector<IntVar*>& vars,
2188 double penalty_factor);
2190 bool maximize,
IntVar*
const objective,
2192 const std::vector<IntVar*>& vars,
2193 const std::vector<IntVar*>& secondary_vars,
double penalty_factor);
2207 ABSL_DEPRECATED(
"Use the version taking absl::Duration() as argument")
2208 #endif // !defined(SWIG) 2211 ? absl::InfiniteDuration()
2212 : absl::Milliseconds(time_in_ms));
2235 bool smart_time_check =
false,
2236 bool cumulative =
false);
2242 ABSL_DEPRECATED(
"Use other MakeLimit() versions")
2243 #endif // !defined(SWIG) 2247 bool smart_time_check =
false,
2248 bool cumulative =
false);
2264 IntVar* objective_var,
bool maximize,
double objective_scaling_factor,
2265 double objective_offset,
double improvement_rate_coefficient,
2266 int improvement_rate_solutions_distance);
2271 std::function<
bool()> limiter);
2285 std::function<std::string()> display_callback);
2290 std::function<std::string()> display_callback);
2299 std::function<std::string()> display_callback);
2341 absl::flat_hash_map<const IntVar*, int>*
const map);
2342 #endif // !defined(SWIG) 2346 const std::vector<SymmetryBreaker*>& visitors);
2363 bool start_with_lower_half);
2368 const std::vector<int64_t>& values);
2370 const std::vector<IntVar*>& vars,
const std::vector<int64_t>& values);
2372 const std::vector<int64_t>& values);
2473 int64_t*
const marker);
2481 int64_t*
const marker);
2521 const std::vector<IntVar*>& vars);
2547 const std::vector<SearchMonitor*>& monitors);
2583 int64_t step,
const std::vector<SearchMonitor*>& monitors);
2597 const std::vector<IntVar*>& secondary_vars,
2605 const std::vector<IntVar*>& secondary_vars,
2617 int number_of_variables);
2619 int number_of_variables,
2636 const std::vector<IntVar*>& variables,
2637 const std::vector<int64_t>& target_values);
2670 const std::vector<LocalSearchOperator*>& ops);
2672 const std::vector<LocalSearchOperator*>& ops,
bool restart);
2674 const std::vector<LocalSearchOperator*>& ops,
2675 std::function<int64_t(
int,
int)> evaluator);
2679 const std::vector<LocalSearchOperator*>& ops);
2685 const std::vector<LocalSearchOperator*>& ops, int32_t seed);
2695 const std::vector<LocalSearchOperator*>& ops,
double memory_coefficient,
2696 double exploration_coefficient,
bool maximize);
2737 const std::vector<IntVar*>& vars,
DecisionBuilder*
const first_solution,
2741 const std::vector<IntVar*>& vars,
DecisionBuilder*
const first_solution,
2745 const std::vector<SequenceVar*>& vars,
2786 const std::vector<IntVar*>& vars,
2826 InternalSaveValue(adr);
2835 InternalSaveValue(adr);
2843 return absl::Uniform<int64_t>(random_, 0, size);
2849 return absl::Uniform<int32_t>(random_, 0, size);
2853 void ReSeed(int32_t seed) { random_.seed(seed); }
2869 #endif // !defined(SWIG) 2888 fail_intercept_ = std::move(fail_intercept);
2890 #endif // !defined(SWIG) 2898 use_fast_local_search_ = use_fast_local_search;
2971 template <
class K,
class V>
2979 bool* is_negated)
const;
3001 if (!should_fail_)
return;
3002 should_fail_ =
false;
3013 void PushSentinel(
int magic_code);
3014 void BacktrackToSentinel(
int magic_code);
3015 void ProcessConstraints();
3016 bool BacktrackOneLevel(
Decision** fail_decision);
3017 void JumpToSentinelWhenNested();
3018 void JumpToSentinel();
3019 void check_alloc_state();
3021 void EnqueueVar(
Demon*
const d);
3022 void EnqueueDelayedDemon(
Demon*
const d);
3025 void UnfreezeQueue();
3026 void reset_action_on_fail();
3027 void set_action_on_fail(
Action a);
3028 void set_variable_to_clean_on_fail(
IntVar* v);
3029 void IncrementUncheckedSolutionCounter();
3030 bool IsUncheckedSolutionLimitReached();
3032 void InternalSaveValue(
int* valptr);
3033 void InternalSaveValue(int64_t* valptr);
3034 void InternalSaveValue(uint64_t* valptr);
3035 void InternalSaveValue(
double* valptr);
3036 void InternalSaveValue(
bool* valptr);
3037 void InternalSaveValue(
void** valptr);
3038 void InternalSaveValue(int64_t** valptr) {
3039 InternalSaveValue(reinterpret_cast<void**>(valptr));
3042 BaseObject* SafeRevAlloc(BaseObject* ptr);
3044 int* SafeRevAllocArray(
int* ptr);
3045 int64_t* SafeRevAllocArray(int64_t* ptr);
3046 uint64_t* SafeRevAllocArray(uint64_t* ptr);
3047 double* SafeRevAllocArray(
double* ptr);
3048 BaseObject** SafeRevAllocArray(BaseObject** ptr);
3050 IntExpr** SafeRevAllocArray(IntExpr** ptr);
3054 void* UnsafeRevAllocAux(
void* ptr);
3056 T* UnsafeRevAlloc(T* ptr) {
3057 return reinterpret_cast<T*>(
3058 UnsafeRevAllocAux(reinterpret_cast<void*>(ptr)));
3060 void** UnsafeRevAllocArrayAux(
void** ptr);
3062 T** UnsafeRevAllocArray(T** ptr) {
3063 return reinterpret_cast<T**>(
3064 UnsafeRevAllocArrayAux(reinterpret_cast<void**>(ptr)));
3067 void InitCachedIntConstants();
3068 void InitCachedConstraint();
3073 Search* TopLevelSearch()
const {
return searches_.at(1); }
3077 Search* ParentSearch()
const {
3078 const size_t search_size = searches_.size();
3080 return searches_[search_size - 2];
3089 int GetNewIntVarIndex() {
return num_int_vars_++; }
3092 bool IsADifference(IntExpr* expr, IntExpr**
const left,
3093 IntExpr**
const right);
3095 const std::string name_;
3096 const ConstraintSolverParameters parameters_;
3097 absl::flat_hash_map<const PropagationBaseObject*, std::string>
3098 propagation_object_names_;
3099 absl::flat_hash_map<const PropagationBaseObject*, IntegerCastInfo>
3101 absl::flat_hash_set<const Constraint*> cast_constraints_;
3102 const std::string empty_name_;
3103 std::unique_ptr<Queue> queue_;
3104 std::unique_ptr<Trail> trail_;
3105 std::vector<Constraint*> constraints_list_;
3106 std::vector<Constraint*> additional_constraints_list_;
3107 std::vector<int> additional_constraints_parent_list_;
3114 int64_t filtered_neighbors_;
3115 int64_t accepted_neighbors_;
3117 std::unique_ptr<ClockTimer> timer_;
3118 std::vector<Search*> searches_;
3119 std::mt19937 random_;
3120 uint64_t fail_stamp_;
3121 std::unique_ptr<Decision> balancing_decision_;
3123 std::function<void()> fail_intercept_;
3127 bool use_fast_local_search_;
3131 std::unique_ptr<Assignment> local_search_state_;
3134 enum { MIN_CACHED_INT_CONST = -8, MAX_CACHED_INT_CONST = 8 };
3135 IntVar* cached_constants_[MAX_CACHED_INT_CONST + 1 - MIN_CACHED_INT_CONST];
3141 std::unique_ptr<Decision> fail_decision_;
3142 int constraint_index_;
3143 int additional_constraint_index_;
3146 std::unique_ptr<ModelCache> model_cache_;
3147 std::unique_ptr<PropagationMonitor> propagation_monitor_;
3148 PropagationMonitor* print_trace_;
3149 std::unique_ptr<LocalSearchMonitor> local_search_monitor_;
3150 int anonymous_variable_index_;
3156 std::ostream&
operator<<(std::ostream& out,
const Solver*
const s);
3161 inline int64_t
Zero() {
return 0; }
3164 inline int64_t
One() {
return 1; }
3179 std::ostream&
operator<<(std::ostream& out,
const BaseObject* o);
3190 if (
name().empty()) {
3191 return "PropagationBaseObject";
3193 return absl::StrFormat(
"PropagationBaseObject: %s",
name());
3218 solver_->set_action_on_fail(std::move(
a));
3220 #endif // !defined(SWIG) 3227 solver_->set_variable_to_clean_on_fail(v);
3231 virtual std::string
name()
const;
3236 virtual std::string
BaseName()
const;
3261 DISALLOW_COPY_AND_ASSIGN(
Decision);
3272 bool start_with_lower_half);
3301 std::vector<SearchMonitor*>*
const extras);
3317 const std::string&
name()
const {
return name_; }
3322 std::vector<SearchMonitor*>*
const extras)
override;
3327 const std::string name_;
3368 void set_stamp(int64_t stamp) {
stamp_ = stamp; }
3369 uint64_t stamp()
const {
return stamp_; }
3569 const std::string& operation, int64_t
value,
3572 const std::string& operation,
3580 const std::vector<int64_t>& values);
3589 const std::string& arg_name,
const std::vector<IntVar*>& arguments);
3596 const std::string& arg_name,
const std::vector<IntervalVar*>& arguments);
3602 const std::string& arg_name,
const std::vector<SequenceVar*>& arguments);
3613 int64_t index_min, int64_t index_max);
3616 const std::string& arg_name, int64_t index_max);
3617 #endif // #if !defined(SWIG) 3633 virtual void Post() = 0;
3779 explicit Rev(
const T& val) : stamp_(0), value_(val) {}
3781 const T&
Value()
const {
return value_; }
3784 if (val != value_) {
3785 if (stamp_ < s->stamp()) {
3787 stamp_ = s->
stamp();
3822 : stamps_(new uint64_t[
size]), values_(new T[
size]), size_(
size) {
3823 for (
int i = 0; i <
size; ++i) {
3831 int64_t
size()
const {
return size_; }
3841 if (val != values_[
index]) {
3846 values_[
index] = val;
3851 std::unique_ptr<uint64_t[]> stamps_;
3852 std::unique_ptr<T[]> values_;
3883 virtual int64_t
Min()
const = 0;
3884 virtual void SetMin(int64_t m) = 0;
3885 virtual int64_t
Max()
const = 0;
3886 virtual void SetMax(int64_t m) = 0;
3890 virtual void Range(int64_t* l, int64_t* u) {
3907 virtual bool IsVar()
const {
return false; }
3933 virtual void Accept(ModelVisitor*
const visitor)
const;
3936 DISALLOW_COPY_AND_ASSIGN(
IntExpr);
3961 virtual void Init() = 0;
3964 virtual bool Ok()
const = 0;
3967 virtual int64_t
Value()
const = 0;
3970 virtual void Next() = 0;
3973 std::string
DebugString()
const override {
return "IntVar::Iterator"; }
3977 class InitAndGetValues {
3986 : it_(it), begin_was_called_(false) {
3993 DCHECK(!begin_was_called_);
3994 begin_was_called_ =
true;
4011 return it_->
Value();
4019 DCHECK(other.it_ == it_);
4032 IntVarIterator*
const it_;
4033 bool begin_was_called_;
4046 bool IsVar()
const override {
return true; }
4051 virtual int64_t
Value()
const = 0;
4061 virtual void RemoveValues(
const std::vector<int64_t>& values);
4064 virtual void SetValues(
const std::vector<int64_t>& values);
4100 virtual uint64_t
Size()
const = 0;
4104 virtual bool Contains(int64_t v)
const = 0;
4117 virtual int64_t
OldMin()
const = 0;
4120 virtual int64_t
OldMax()
const = 0;
4125 void Accept(ModelVisitor*
const visitor)
const override;
4138 DISALLOW_COPY_AND_ASSIGN(
IntVar);
4149 std::string
DebugString()
const override {
return "SolutionCollector"; }
4153 void Add(
const std::vector<IntVar*>& vars);
4155 void Add(
const std::vector<IntervalVar*>& vars);
4157 void Add(
const std::vector<SequenceVar*>& vars);
4264 virtual std::string
Print()
const;
4294 virtual bool Check() = 0;
4297 virtual void Init() = 0;
4312 return absl::StrFormat(
"SearchLimit(crossed = %i)", crossed_);
4316 void TopPeriodicCheck();
4333 bool Check()
override;
4334 void Init()
override;
4340 return duration_limit_ == absl::InfiniteDuration()
4352 return solver_time_at_limit_start_ + duration_limit_;
4359 absl::Duration TimeElapsed();
4360 static int64_t GetPercent(int64_t
value, int64_t offset, int64_t total) {
4361 return (total > 0 && total <
kint64max) ? 100 * (
value - offset) / total
4365 absl::Duration duration_limit_;
4366 absl::Time solver_time_at_limit_start_;
4367 absl::Duration last_time_elapsed_;
4368 int64_t check_count_;
4369 int64_t next_check_;
4370 bool smart_time_check_;
4372 int64_t branches_offset_;
4374 int64_t failures_offset_;
4376 int64_t solutions_offset_;
4399 double objective_scaling_factor,
4400 double objective_offset,
4401 double improvement_rate_coefficient,
4402 int improvement_rate_solutions_distance);
4406 bool Check()
override;
4408 void Init()
override;
4413 double objective_scaling_factor_;
4414 double objective_offset_;
4415 double improvement_rate_coefficient_;
4416 int improvement_rate_solutions_distance_;
4418 double best_objective_;
4420 std::deque<std::pair<double, int64_t> > improvements_;
4423 bool objective_updated_;
4424 bool gradient_stage_;
4451 virtual int64_t
StartMin()
const = 0;
4452 virtual int64_t
StartMax()
const = 0;
4505 virtual int64_t
EndMin()
const = 0;
4506 virtual int64_t
EndMax()
const = 0;
4509 virtual void SetEndRange(int64_t mi, int64_t ma) = 0;
4569 virtual IntExpr*
EndExpr() = 0;
4574 virtual IntExpr*
SafeStartExpr(int64_t unperformed_value) = 0;
4576 virtual IntExpr*
SafeEndExpr(int64_t unperformed_value) = 0;
4579 virtual void Accept(ModelVisitor*
const visitor)
const = 0;
4594 const std::vector<IntVar*>& nexts,
const std::string&
name);
4601 void DurationRange(int64_t*
const dmin, int64_t*
const dmax)
const;
4607 void HorizonRange(int64_t*
const hmin, int64_t*
const hmax)
const;
4615 int*
const unperformed)
const;
4616 #endif // !defined(SWIG) 4637 std::vector<int>*
const possible_lasts);
4645 const std::vector<int>& rank_last,
4646 const std::vector<int>& unperformed);
4657 std::vector<int>*
const rank_last,
4658 std::vector<int>*
const unperformed)
const;
4667 int64_t
size()
const {
return intervals_.size(); }
4673 int ComputeForwardFrontier();
4674 int ComputeBackwardFrontier();
4675 void UpdatePrevious()
const;
4677 const std::vector<IntervalVar*> intervals_;
4678 const std::vector<IntVar*> nexts_;
4679 mutable std::vector<int> previous_;
4707 if (var_ !=
nullptr) {
4714 int64_t
Min()
const {
return min_; }
4716 int64_t
Max()
const {
return max_; }
4723 bool Bound()
const {
return (max_ == min_); }
4736 return !(*
this == element);
4768 CHECK_EQ(duration_max_, duration_min_);
4769 return duration_max_;
4780 CHECK_EQ(performed_max_, performed_min_);
4781 return performed_max_;
4816 performed_min_ = mi;
4817 performed_max_ = ma;
4824 return (start_min_ == start_max_ && duration_min_ == duration_max_ &&
4825 end_min_ == end_max_ && performed_min_ == performed_max_);
4830 return !(*
this == element);
4836 int64_t duration_min_;
4837 int64_t duration_max_;
4840 int64_t performed_min_;
4841 int64_t performed_max_;
4875 void SetSequence(
const std::vector<int>& forward_sequence,
4876 const std::vector<int>& backward_sequence,
4877 const std::vector<int>& unperformed);
4882 return forward_sequence_.size() + unperformed_.size() == var_->
size();
4889 return !(*
this == element);
4893 bool CheckClassInvariants();
4896 std::vector<int> forward_sequence_;
4897 std::vector<int> backward_sequence_;
4898 std::vector<int> unperformed_;
4901 template <
class V,
class E>
4911 return &elements_[
index];
4917 elements_.emplace_back(
var);
4918 return &elements_.back();
4923 elements_[position].Reset(
var);
4924 return &elements_[position];
4928 if (!elements_map_.empty()) {
4929 elements_map_.clear();
4934 void Resize(
size_t size) { elements_.resize(size); }
4935 bool Empty()
const {
return elements_.empty(); }
4939 for (
int i = 0; i < container.elements_.size(); ++i) {
4940 const E& element = container.elements_[i];
4941 const V*
const var = element.Var();
4943 if (i < elements_.size() && elements_[i].Var() ==
var) {
4949 E*
const local_element = &elements_[
index];
4950 local_element->Copy(element);
4951 if (element.Activated()) {
4952 local_element->Activate();
4954 local_element->Deactivate();
4962 for (
int i = 0; i < container.elements_.size(); ++i) {
4963 const E& element = container.elements_[i];
4973 DCHECK(element !=
nullptr)
4974 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
4986 DCHECK(element !=
nullptr)
4987 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
4997 const std::vector<E>&
elements()
const {
return elements_; }
5000 int Size()
const {
return elements_.size(); }
5002 for (E& element : elements_) {
5007 for (E& element : elements_) {
5008 if (element.Activated()) {
5014 for (
const E& element : elements_) {
5015 if (!element.Bound())
return false;
5029 EnsureMapIsUpToDate();
5033 for (
const E& element : container.elements_) {
5034 const int position =
5036 if (position < 0 || elements_[position] != element) {
5043 return !(*
this == container);
5047 void EnsureMapIsUpToDate()
const {
5048 absl::flat_hash_map<const V*, int>* map =
5049 const_cast<absl::flat_hash_map<const V*, int>*
>(&elements_map_);
5050 for (
int i = map->size(); i < elements_.size(); ++i) {
5051 (*map)[elements_[i].Var()] = i;
5054 bool Find(
const V*
const var,
int*
index)
const {
5056 const size_t kMaxSizeForLinearAccess = 11;
5057 if (
Size() <= kMaxSizeForLinearAccess) {
5061 for (
int i = 0; i < elements_.size(); ++i) {
5062 if (
var == elements_[i].Var()) {
5069 EnsureMapIsUpToDate();
5070 DCHECK_EQ(elements_map_.size(), elements_.size());
5075 std::vector<E> elements_;
5076 absl::flat_hash_map<const V*, int> elements_map_;
5095 return int_var_container_.
Empty() && interval_var_container_.
Empty() &&
5096 sequence_var_container_.
Empty();
5109 bool Load(
const std::string& filename);
5113 void Load(const AssignmentProto& assignment_proto); 5114 bool Save(
const std::string& filename)
const;
5118 #endif // #if !defined(SWIG) 5135 void Add(
const std::vector<IntVar*>& vars);
5148 void Add(
const std::vector<IntervalVar*>& vars);
5181 void Add(
const std::vector<SequenceVar*>& vars);
5188 const std::vector<int>& forward_sequence,
5189 const std::vector<int>& backward_sequence,
5190 const std::vector<int>& unperformed);
5192 const std::vector<int>& forward_sequence);
5194 const std::vector<int>& backward_sequence);
5196 const std::vector<int>& unperformed);
5235 return interval_var_container_;
5238 return &interval_var_container_;
5241 return sequence_var_container_;
5244 return &sequence_var_container_;
5247 return int_var_container_ == assignment.int_var_container_ &&
5248 interval_var_container_ == assignment.interval_var_container_ &&
5249 sequence_var_container_ == assignment.sequence_var_container_ &&
5250 objective_element_ == assignment.objective_element_;
5253 return !(*
this == assignment);
5265 const Assignment& assignment);
5273 const std::vector<IntVar*>& target_vars,
5274 const Assignment* source_assignment,
5275 const std::vector<IntVar*>& source_vars);
5279 Pack(
Solver*
const s,
const std::vector<IntVar*>& vars,
int number_of_bins);
5292 const std::vector<int64_t>& weights,
const std::vector<int64_t>&
bounds);
5311 const std::vector<IntVar*>& loads);
5317 const std::vector<IntVar*>& loads);
5329 const std::vector<IntVar*>& usage,
const std::vector<int64_t>&
capacity);
5344 void Post()
override;
5351 bool IsUndecided(
int var_index,
int bin_index)
const;
5353 void Assign(
int var_index,
int bin_index);
5355 bool IsPossible(
int var_index,
int bin_index)
const;
5367 bool IsInProcess()
const;
5368 const std::vector<IntVar*> vars_;
5370 std::vector<Dimension*> dims_;
5371 std::unique_ptr<RevBitMatrix> unprocessed_;
5372 std::vector<std::vector<int>> forced_;
5373 std::vector<std::vector<int>> removed_;
5374 std::vector<IntVarIterator*> holes_;
5377 std::vector<std::pair<int, int>> to_set_;
5378 std::vector<std::pair<int, int>> to_unset_;
5385 const std::vector<IntervalVar*>& intervals,
5386 const std::string&
name);
5404 virtual const std::vector<IntVar*>&
nexts()
const = 0;
5405 virtual const std::vector<IntVar*>&
actives()
const = 0;
5406 virtual const std::vector<IntVar*>&
time_cumuls()
const = 0;
5407 virtual const std::vector<IntVar*>&
time_slacks()
const = 0;
5408 #endif // !defined(SWIG) 5443 #endif // OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_ Right branches are ignored.
const std::vector< int > & Unperformed(int n, SequenceVar *const var) const
This is a shortcut to get the list of unperformed of 'var' in the nth solution.
Constraint * MakeFalseConstraint()
This constraint always fails.
Constraint * MakePathConnected(std::vector< IntVar * > nexts, std::vector< int64_t > sources, std::vector< int64_t > sinks, std::vector< IntVar * > status)
Constraint enforcing that status[i] is true iff there's a path defined on next variables from sources...
IntVar * MakeIsGreaterVar(IntExpr *const left, IntExpr *const right)
status var of (left > right)
Constraint * MakeMapDomain(IntVar *const var, const std::vector< IntVar * > &actives)
This constraint maps the domain of 'var' onto the array of variables 'actives'.
int64_t filtered_neighbors() const
The number of filtered neighbors (neighbors accepted by filters).
Decision * MakeScheduleOrExpedite(IntervalVar *const var, int64_t est, int64_t *const marker)
Returns a decision that tries to schedule a task at a given time.
Constraint * MakeCount(const std::vector< IntVar * > &vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| == max_count
static const char kProduct[]
virtual int64_t OldStartMax() const =0
absl::Time AbsoluteSolverDeadline() const
Constraint * MakeScalProdLessOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
Cast constraints are special channeling constraints designed to keep a variable in sync with an expre...
Constraint * MakeGreater(IntExpr *const left, IntExpr *const right)
left > right
void ClearLocalSearchState()
Clears the local search state.
int64_t size() const
Returns the number of interval vars in the sequence.
static const char kDivide[]
void RankNotFirst(int index)
Indicates that the index_th interval var will not be ranked first of all currently unranked interval ...
OptimizeVar * MakeOptimize(bool maximize, IntVar *const v, int64_t step)
Creates a objective with a given sense (true = maximization).
bool CannotBePerformed() const
IntVar * MakeIsGreaterOrEqualCstVar(IntExpr *const var, int64_t value)
status var of (var >= value)
IntVar * MakeIsEqualCstVar(IntExpr *const var, int64_t value)
status var of (var == value)
ABSL_MUST_USE_RESULT RegularLimit * MakeBranchesLimit(int64_t branches)
Creates a search limit that constrains the number of branches explored in the search tree.
void Assign(int var_index, int bin_index)
virtual void Post()=0
This method is called when the constraint is processed by the solver.
DemonProfiler * demon_profiler() const
Access to demon profiler.
bool run_all_heuristics
The default phase will run heuristics periodically.
IntVar * Var() const
Returns the variable that is optimized.
SearchMonitor * MakeSearchLog(int branch_period)
The SearchMonitors below will display a periodic search log on LOG(INFO) every branch_period branches...
static const char kCumulsArgument[]
Creates a search monitor from logging parameters.
Selects the min value of the selected variable.
static const char kTrace[]
static const char kPartialArgument[]
int64_t objective_value(int n) const
Returns the objective value of the nth solution.
static const char kVarBoundWatcher[]
SequenceContainer * MutableSequenceVarContainer()
SolutionData BuildSolutionDataForCurrentState()
SolutionCollector * MakeNBestValueSolutionCollector(const Assignment *const assignment, int solution_count, bool maximize)
Same as MakeBestValueSolutionCollector but collects the best solution_count solutions.
void reset_action_on_fail()
This method clears the failure callback.
Selects the first possible value which is the closest to the center of the domain of the selected var...
static const char kIndexOf[]
static const char kPathCumul[]
const E * ElementPtrOrNull(const V *const var) const
Pairs are compared at the first call of the selector, and results are cached.
void WhenEndBound(Solver::Action action)
static const char kModuloArgument[]
Constraint * MakeIsDifferentCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var != value)
std::function< bool(int64_t, int64_t, int64_t)> VariableValueComparator
virtual std::string Print() const
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
int SearchDepth() const
Gets the search depth of the current active search.
virtual void VisitIntervalArrayArgument(const std::string &arg_name, const std::vector< IntervalVar * > &arguments)
static const char kSearchLimitExtension[]
DecisionModification
The Solver is responsible for creating the search tree.
void AddLocalSearchMonitor(LocalSearchMonitor *monitor)
Adds the local search monitor to the solver.
void SetTransitionTime(Solver::IndexEvaluator2 transition_time)
Add a transition time between intervals.
AssignmentContainer< IntVar, IntVarElement > IntContainer
int branch_period
SearchMonitors will display a periodic search log every branch_period branches explored.
void Copy(const SequenceVarElement &element)
int64_t Value(const IntVar *const var) const
void SetBackwardSequence(const std::vector< int > &backward_sequence)
virtual bool IsUncheckedSolutionLimitReached()
Returns true if the limit of solutions has been reached including unchecked solutions.
IntervalVar * RegisterIntervalVar(IntervalVar *const var)
Registers a new IntervalVar and wraps it inside a TraceIntervalVar if necessary.
std::string DebugString() const override
int64_t DurationValue() const
virtual void Init()=0
This method must be called before each loop.
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)
Limits the search with the 'time', 'branches', 'failures' and 'solutions' limits.
After successful NextSolution and before EndSearch.
std::function< int64_t(const IntVar *v, int64_t id)> VariableValueSelector
virtual void EnterSearch()
Beginning of the search.
void Activate(const IntVar *const var)
Constraint * MakeNotMemberCt(IntExpr *const expr, const std::vector< int64_t > &values)
expr not in set.
IntExpr * MakeProd(IntExpr *const left, IntExpr *const right)
left * right
std::unique_ptr< Assignment > prototype_
void Init() override
This method is called when the search limit is initialized.
static const char kCountEqual[]
The base class for all local search operators.
void VisitInt64ToInt64AsArray(const Solver::IndexEvaluator1 &eval, const std::string &arg_name, int64_t index_max)
Expands function as array when index min is 0.
std::vector< SolutionData > solution_data_
Assignment(Solver *const s)
const SequenceContainer & SequenceVarContainer() const
void WhenDurationRange(Solver::Closure closure)
AssignmentContainer< SequenceVar, SequenceVarElement > SequenceContainer
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
Demon * MakeDelayedConstraintInitialPropagateCallback(Constraint *const ct)
This method is a specialized case of the MakeConstraintDemon method to call the InitiatePropagate of ...
The simple selection is ASSIGN_MIN_VALUE.
bool IsProduct(IntExpr *const expr, IntExpr **inner_expr, int64_t *coefficient)
Returns true if expr represents a product of a expr and a constant.
ModelVisitor * MakeVariableDegreeVisitor(absl::flat_hash_map< const IntVar *, int > *const map)
Compute the number of constraints a variable is attached to.
Constraint * MakeIsGreaterCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left > right)
virtual void WhenBound(Demon *d)=0
This method attaches a demon that will be awakened when the variable is bound.
int64_t solutions() const
The number of solutions found since the start of the search.
int64_t PerformedMin() const
void NewSearch(DecisionBuilder *const db, const std::vector< SearchMonitor * > &monitors)
virtual IntExpr * DurationExpr()=0
void Reset(IntVar *const var)
Solver(const std::string &name)
Solver API.
void AddWeightedSumOfAssignedDimension(const std::vector< int64_t > &weights, IntVar *const cost_var)
This dimension enforces that cost_var == sum of weights[i] for all objects 'i' assigned to a bin.
RegularLimit * MakeIdenticalClone() const
bool CurrentlyInSolve() const
Returns true whether the current search has been created using a Solve() call instead of a NewSearch ...
int64_t One()
This method returns 1.
const std::vector< int > & ForwardSequence() const
virtual void VisitUnknownDecision()
int NumIntervalVars() const
IntervalVar * MakeFixedInterval(int64_t start, int64_t duration, const std::string &name)
Creates a fixed and performed interval.
void RemoveAllPossibleFromBin(int bin_index)
static const char kPower[]
virtual bool Check()=0
This method is called to check the status of the limit.
int ProgressPercent() override
Returns a percentage representing the propress of the search before reaching limits.
ABSL_MUST_USE_RESULT SearchLimit * MakeCustomLimit(std::function< bool()> limiter)
Callback-based search limit.
IntVar * Var() override
Creates a variable from the expression.
virtual IntExpr * PerformedExpr()=0
void Reset(IntervalVar *const var)
bool display_on_new_solutions_only
To be used to protect from cases where display_callback assumes variables are instantiated,...
void EnterSearch() override
Beginning of the search.
Among unbound variables, select the variable with the smallest minimal value.
void ComputeStatistics(int *const ranked, int *const not_ranked, int *const unperformed) const
Compute statistics on the sequence.
static const char kDifferenceOperation[]
void RestartCurrentSearch()
Constraint * MakeAbsEquality(IntVar *const var, IntVar *const abs_var)
Creates the constraint abs(var) == abs_var.
virtual void BeginVisitIntegerExpression(const std::string &type_name, const IntExpr *const expr)
void TopPeriodicCheck()
Performs PeriodicCheck on the top-level search; for instance, can be called from a nested solve to ch...
MarkerType
This enum is used internally in private methods Solver::PushState and Solver::PopState to tag states ...
IntervalVar(Solver *const solver, const std::string &name)
virtual void RemoveValue(int64_t v)=0
This method removes the value 'v' from the domain of the variable.
IntVarElement * FastAdd(IntVar *const var)
Adds without checking if variable has been previously added.
Lin-Kernighan local search.
int64_t DurationMin() const
ABSL_DECLARE_FLAG(int64_t, cp_random_seed)
Declaration of the core objects for the constraint solver.
virtual SequenceVar * MakeSequenceVar()=0
Creates a sequence variable from the constraint.
Constraint * MakeIsLessOrEqualCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left <= right)
After search, the model is infeasible.
void RankLast(int index)
Ranks the index_th interval var first of all unranked interval vars.
IntVar * MakeIsLessCstVar(IntExpr *const var, int64_t value)
status var of (var < value)
virtual void VisitRankFirstInterval(SequenceVar *const sequence, int index)
t ends after d, i.e. End(t) >= d.
Operator which defines a neighborhood to decrement values.
static const char kCumulative[]
std::string GetName() const
virtual int64_t Value() const =0
This method returns the value of the variable.
~CastConstraint() override
virtual void VisitIntegerVariableArrayArgument(const std::string &arg_name, const std::vector< IntVar * > &arguments)
LocalSearchFilter * MakeRejectFilter()
void RefuteDecision(Decision *const d) override
Before refuting the decision.
static const char kEarlyCostArgument[]
ABSL_MUST_USE_RESULT RegularLimit * MakeTimeLimit(absl::Duration time)
Creates a search limit that constrains the running time.
int64_t StartValue(int n, IntervalVar *const var) const
This is a shortcut to get the StartValue of 'var' in the nth solution.
const std::vector< E > & elements() const
static int64_t MemoryUsage()
Current memory usage in bytes.
LocalSearchOperator * MakeNeighborhoodLimit(LocalSearchOperator *const op, int64_t limit)
Creates a local search operator that wraps another local search operator and limits the number of nei...
std::function< int64_t(int64_t)> IndexEvaluator1
Callback typedefs.
void SetBranchSelector(BranchSelector bs)
Sets the given branch selector on the current active search.
static const char kAllDifferent[]
IntExpr * MakePower(IntExpr *const expr, int64_t n)
expr ^ n (n > 0)
virtual void InitialPropagate()=0
This method performs the initial propagation of the constraint.
static const char kOptionalArgument[]
ABSL_MUST_USE_RESULT RegularLimit * MakeTimeLimit(int64_t time_in_ms)
void SetValue(const IntVar *const var, int64_t value)
virtual void BeginFail()
Just when the failure occurs.
This class adds reversibility to a POD type.
static const char kIntervalUnaryRelation[]
IntVar * RegisterIntVar(IntVar *const var)
Registers a new IntVar and wraps it inside a TraceIntVar if necessary.
int64_t wall_time() const
static const char kTuplesArgument[]
Operator which exchanges the positions of two nodes.
bool AreAllElementsBound() const
virtual void EndFail()
After completing the backtrack.
Constraint * MakeAllDifferentExcept(const std::vector< IntVar * > &vars, int64_t escape_value)
All variables are pairwise different, unless they are assigned to the escape value.
void WhenEndRange(Solver::Closure closure)
The default is INTERVAL_SET_TIMES_FORWARD.
ABSL_MUST_USE_RESULT RegularLimit * MakeSolutionsLimit(int64_t solutions)
Creates a search limit that constrains the number of solutions found during the search.
static const char kMember[]
SearchMonitor * MakeConstantRestart(int frequency)
This search monitor will restart the search periodically after 'frequency' failures.
std::string DebugString() const override
int64_t EndValue(const IntervalVar *const var) const
virtual void BeginVisitConstraint(const std::string &type_name, const Constraint *const constraint)
Decision * MakeVariableGreaterOrEqualValue(IntVar *const var, int64_t value)
void SetStartMax(const IntervalVar *const var, int64_t m)
void Push(const SolutionData &data)
bool FindCopy(const Collection &collection, const Key &key, Value *const value)
IntVar * MakeIsGreaterCstVar(IntExpr *const var, int64_t value)
status var of (var > value)
void SetStartRange(const IntervalVar *const var, int64_t mi, int64_t ma)
RevArray(int size, const T &val)
SequenceVar(Solver *const s, const std::vector< IntervalVar * > &intervals, const std::vector< IntVar * > &nexts, const std::string &name)
void SaveAndSetValue(T *adr, T val)
All-in-one SaveAndSetValue.
bool SolveAndCommit(DecisionBuilder *const db, const std::vector< SearchMonitor * > &monitors)
SolveAndCommit using a decision builder and up to three search monitors, usually one for the objectiv...
t1 ends at t2 end, i.e. End(t1) == End(t2) + delay.
void SetStartMin(int64_t m)
bool Activated(const IntVar *const var) const
int64_t ObjectiveMin() const
virtual int VarType() const
int heuristic_num_failures_limit
The failure limit for each heuristic that we run.
bool IsPerformedBound() const
static const char kMaxArgument[]
IntervalVar * MakeFixedDurationEndSyncedOnEndIntervalVar(IntervalVar *const interval_var, int64_t duration, int64_t offset)
Creates an interval var with a fixed duration whose end is synchronized with the end of another inter...
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)
This constraint states that all the boxes must not overlap.
static const char kEquality[]
void SetUnperformed(const SequenceVar *const var, const std::vector< int > &unperformed)
Decision * MakeAssignVariablesValuesOrDoNothing(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
IntVar * VarWithName(const std::string &name)
Creates a variable from the expression and set the name of the resulting var.
static const char kSequenceVariable[]
LocalSearchOperator * MultiArmedBanditConcatenateOperators(const std::vector< LocalSearchOperator * > &ops, double memory_coefficient, double exploration_coefficient, bool maximize)
Creates a local search operator which concatenates a vector of operators.
void ActiveHorizonRange(int64_t *const hmin, int64_t *const hmax) const
Returns the minimum start min and the maximum end max of all unranked interval vars in the sequence.
The simple selection is CHOOSE_FIRST_UNBOUND.
int64_t Max(const IntVar *const var) const
After failed NextSolution and before EndSearch.
virtual bool Contains(int64_t v) const =0
This method returns whether the value 'v' is in the domain of the variable.
void AssignAllRemainingItems()
void Copy(const SearchLimit *const limit) override
Copy a limit.
void SetEndRange(int64_t mi, int64_t ma)
void UpdateLimits(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions)
Constraint * MakeInversePermutationConstraint(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
Creates a constraint that enforces that 'left' and 'right' both represent permutations of [0....
IntVarElement * Add(IntVar *const var)
static const char kObjectiveExtension[]
virtual void RefuteDecision(Decision *const d)
Before refuting the decision.
std::function< IntVar *(int64_t)> Int64ToIntVar
BinaryIntervalRelation
This enum is used in Solver::MakeIntervalVarRelation to specify the temporal relation between the two...
virtual void VisitScheduleOrPostpone(IntervalVar *const var, int64_t est)
Backtracks to the previous decisions, i.e.
static const char kGreater[]
Constraint * MakeScalProdEquality(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
void AddSumVariableWeightsLessOrEqualConstantDimension(const std::vector< IntVar * > &usage, const std::vector< int64_t > &capacity)
This dimension imposes: forall b in bins, sum (i in items: usage[i] * is_assigned(i,...
Constraint * MakeElementEquality(const std::vector< int64_t > &vals, IntVar *const index, IntVar *const target)
Constraint * MakeIsLessCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left < right)
void WhenStartRange(Solver::Closure closure)
void WhenEndRange(Solver::Action action)
bool operator!=(const Iterator &other) const
A Demon is the base element of a propagation queue.
virtual IntVarIterator * MakeHoleIterator(bool reversible) const =0
Creates a hole iterator.
void DeactivateObjective()
void MakeBoolVarArray(int var_count, const std::string &name, std::vector< IntVar * > *vars)
This method will append the vector vars with 'var_count' boolean variables having name "name<i>" wher...
void OneDomain(int var_index)
static const char kLinkExprVar[]
Constraint * MakeNullIntersect(const std::vector< IntVar * > &first_vars, const std::vector< IntVar * > &second_vars)
Creates a constraint that states that all variables in the first vector are different from all variab...
static const char kSizeXArgument[]
void DurationRange(int64_t *const dmin, int64_t *const dmax) const
Returns the minimum and maximum duration of combined interval vars in the sequence.
static const char kElementEqual[]
A DecisionVisitor is used to inspect a decision.
virtual int64_t OldStartMin() const =0
~ImprovementSearchLimit() override
~SolutionCollector() override
t ends before d, i.e. End(t) <= d.
virtual int64_t OldMax() const =0
Returns the previous max.
bool operator==(const Assignment &assignment) const
Constraint(Solver *const solver)
void SetPerformedRange(const IntervalVar *const var, int64_t mi, int64_t ma)
virtual const std::vector< IntVar * > & actives() const =0
SolutionCollector * MakeBestValueSolutionCollector(const Assignment *const assignment, bool maximize)
Collect the solution corresponding to the optimal value of the objective of 'assignment'; if 'assignm...
int64_t failures() const
The number of failures encountered since the creation of the solver.
static const char kVariableArgument[]
void PushSolution()
Push the current state as a new solution.
virtual std::string name() const
Object naming.
static const char kIndex2Argument[]
void MakeIntVarArray(int var_count, int64_t vmin, int64_t vmax, const std::string &name, std::vector< IntVar * > *vars)
This method will append the vector vars with 'var_count' variables having bounds vmin and vmax and ha...
void WhenRange(Solver::Closure closure)
Attach a demon that will watch the min or the max of the expression.
static const char kCountArgument[]
int64_t wall_time(int n) const
Returns the wall time in ms for the nth solution.
static const char kEndsArgument[]
void RankSequence(const std::vector< int > &rank_first, const std::vector< int > &rank_last, const std::vector< int > &unperformed)
Applies the following sequence of ranks, ranks first, then rank last.
OptimizeVar * MakeMaximize(IntVar *const v, int64_t step)
Creates a maximization objective.
void PeriodicCheck() override
Periodic call to check limits in long running methods.
Constraint * MakeIntervalVarRelationWithDelay(IntervalVar *const t1, BinaryIntervalRelation r, IntervalVar *const t2, int64_t delay)
This method creates a relation between two interval vars.
static const char kDisjunctive[]
DisjunctiveConstraint * MakeDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
This constraint forces all interval vars into an non-overlapping sequence.
Constraint * MakeMemberCt(IntExpr *const expr, const std::vector< int64_t > &values)
expr in set.
E * MutableElementOrNull(const V *const var)
DecisionBuilder * MakeDecisionBuilderFromAssignment(Assignment *const assignment, DecisionBuilder *const db, const std::vector< IntVar * > &vars)
Returns a decision builder for which the left-most leaf corresponds to assignment,...
static const char kAbsEqual[]
virtual IntVar * Var()
Creates a Boolean variable representing the status of the constraint (false = constraint is violated,...
Constraint * MakeScalProdGreaterOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coeffs, int64_t cst)
static ConstraintSolverParameters DefaultSolverParameters()
Create a ConstraintSolverParameters proto with all the default values.
Demon()
This indicates the priority of a demon.
void VisitInt64ToInt64Extension(const Solver::IndexEvaluator1 &eval, int64_t index_min, int64_t index_max)
void InsertAll(const std::vector< std::vector< int64_t > > &tuples)
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, const std::string &name, std::vector< IntervalVar * > *const array)
This method fills the vector with 'count' interval var built with the corresponding parameters.
Operator which makes path nodes inactive.
void AddWeightedSumLessOrEqualConstantDimension(const std::vector< int64_t > &weights, const std::vector< int64_t > &bounds)
Dimensions are additional constraints than can restrict what is possible with the pack constraint.
bool found_initial_solution_
virtual int64_t Min() const =0
Randomly select one of the remaining unbound variables.
bool Load(const std::string &filename)
Loads an assignment from a file; does not add variables to the assignment (only the variables contain...
int32_t Rand32(int32_t size)
Returns a random value between 0 and 'size' - 1;.
virtual void Init()=0
This method is called when the search limit is initialized.
void SetStartValue(const IntervalVar *const var, int64_t value)
static Iterator Begin(IntVarIterator *it)
These are the only way to construct an Iterator.
virtual void BeginNextDecision(DecisionBuilder *const b)
Before calling DecisionBuilder::Next.
bool InstrumentsVariables() const
Returns whether we are tracing variables.
void AssignFirstPossibleToBin(int bin_index)
virtual void VisitSequenceArgument(const std::string &arg_name, SequenceVar *const argument)
Visit sequence argument.
bool AtSolution() override
This method is called when a valid solution is found.
void WhenBound(Solver::Closure closure)
This method attaches a closure that will be awakened when the variable is bound.
IntVar * MakeIsEqualVar(IntExpr *const v1, IntExpr *v2)
status var of (v1 == v2)
A constraint is the main modeling object.
int64_t neighbors() const
The number of neighbors created.
virtual void SetEndRange(int64_t mi, int64_t ma)=0
E * AddAtPosition(V *var, int position)
Advanced usage: Adds element at a given position; position has to have been allocated with Assignment...
Assignment * solution(int n) const
Returns the nth solution.
IntExpr * RegisterIntExpr(IntExpr *const expr)
Registers a new IntExpr and wraps it inside a TraceIntExpr if necessary.
InitAndGetValues(IntVarIterator *it)
virtual void RestartSearch()
Restart the search.
void AddConstraint(Constraint *const c)
Adds the constraint 'c' to the model.
SolutionCollector(Solver *const solver, const Assignment *assignment)
int64_t ObjectiveValue() const
bool operator==(const IntVarElement &element) const
SolverState state() const
State of the solver.
bool IsVar() const override
Returns true if the expression is indeed a variable.
#define DCHECK_GT(val1, val2)
virtual void Apply(Solver *const s)=0
Apply will be called first when the decision is executed.
Constraint * MakeNullIntersectExcept(const std::vector< IntVar * > &first_vars, const std::vector< IntVar * > &second_vars, int64_t escape_value)
Creates a constraint that states that all variables in the first vector are different from all variab...
static const char kCapacityArgument[]
IntVar * MakeIsGreaterOrEqualVar(IntExpr *const left, IntExpr *const right)
status var of (left >= right)
int random_seed
Seed used to initialize the random part in some heuristics.
int64_t StartValue(const IntervalVar *const var) const
Usual limit based on wall_time, number of explored branches and number of failures in the search tree...
Constraint * MakeSumEquality(const std::vector< IntVar * > &vars, int64_t cst)
virtual void VisitScheduleOrExpedite(IntervalVar *const var, int64_t est)
IntervalVar * Var() const
t1 ends at t2 start, i.e. End(t1) == Start(t2) + delay.
void SetSequence(const SequenceVar *const var, const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
static const char kStartSyncOnStartOperation[]
const E & Element(const V *const var) const
void WhenAnything(Demon *const d)
Attaches a demon awakened when anything about this interval changes.
virtual IntExpr * StartExpr()=0
These methods create expressions encapsulating the start, end and duration of the interval var.
void SetStartRange(int64_t mi, int64_t ma)
bool IsUncheckedSolutionLimitReached() override
Returns true if the limit of solutions has been reached including unchecked solutions.
static const char kNoCycle[]
virtual void ExitSearch()
End of the search.
static const char kStartsArgument[]
void SetImpossible(int var_index, int bin_index)
void AddCountAssignedItemsDimension(IntVar *const count_var)
This dimension links 'count_var' to the actual number of items assigned to a bin in the pack.
virtual void WhenEndBound(Demon *const d)=0
bool IsCastConstraint() const
Is the constraint created by a cast from expression to integer variable?
const T & Value(int index) const
static const char kDemandsArgument[]
int64_t branches() const
The number of branches explored since the creation of the solver.
friend class PropagationBaseObject
void SetEndMax(const IntervalVar *const var, int64_t m)
virtual void Accept(DecisionVisitor *const visitor) const
Accepts the given visitor.
static const char kIsLessOrEqual[]
static const char kEndMaxArgument[]
Constraint * MakeSortingConstraint(const std::vector< IntVar * > &vars, const std::vector< IntVar * > &sorted)
Creates a constraint binding the arrays of variables "vars" and "sorted_vars": sorted_vars[0] must be...
void Add(IntVar *const var)
Add API.
bool operator!=(const IntervalVarElement &element) const
void Deactivate(const IntVar *const var)
const std::vector< int > & BackwardSequence(int n, SequenceVar *const var) const
This is a shortcut to get the BackwardSequence of 'var' in the nth solution.
Constraint * MakeCircuit(const std::vector< IntVar * > &nexts)
Force the "nexts" variable to create a complete Hamiltonian path.
void SetObjectiveRange(int64_t l, int64_t u)
A DecisionBuilder is responsible for creating the search tree.
virtual void EndVisitModel(const std::string &type_name)
void SetForwardSequence(const SequenceVar *const var, const std::vector< int > &forward_sequence)
SearchMonitor * MakeTabuSearch(bool maximize, IntVar *const v, 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.
static const char kPack[]
void PopSolution()
Remove and delete the last popped solution.
static const char kStartExpr[]
t ends at d, i.e. End(t) == d.
bool InstrumentsDemons() const
Returns whether we are instrumenting demons.
int64_t unchecked_solutions() const
The number of unchecked solutions found by local search.
void VisitInt64ToBoolExtension(Solver::IndexFilter1 filter, int64_t index_min, int64_t index_max)
Using SWIG on callbacks is troublesome, so we hide these methods during the wrapping.
void Accept(ModelVisitor *const visitor) const override
Accepts the given visitor.
virtual Solver::DemonPriority priority() const
This method returns the priority of the demon.
void SetForwardSequence(const std::vector< int > &forward_sequence)
static const char kDistribute[]
virtual void SetStartMin(int64_t m)=0
friend class LocalSearchProfiler
std::string DebugString() const override
virtual const std::vector< IntVar * > & time_cumuls() const =0
std::string DebugString() const
const std::vector< int > & BackwardSequence() const
virtual void WhenEndRange(Demon *const d)=0
const IntervalContainer & IntervalVarContainer() const
bool Contains(const IntVar *const var) const
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
const std::vector< int > & ForwardSequence(int n, SequenceVar *const var) const
This is a shortcut to get the ForwardSequence of 'var' in the nth solution.
Constraint * MakeIsDifferentCt(IntExpr *const v1, IntExpr *const v2, IntVar *const b)
b == (v1 != v2)
virtual int64_t DurationMax() const =0
static const char kFailuresLimitArgument[]
The default behavior is ASSIGN_MIN_VALUE.
static const char kSizeYArgument[]
t1 starts at t2 start, i.e. Start(t1) == Start(t2) + delay.
static const char kTrueConstraint[]
static const char kRelationArgument[]
virtual void BeginInitialPropagation()
Before the initial propagation.
ConstraintSolverParameters parameters() const
Stored Parameters.
t starts at d, i.e. Start(t) == d.
virtual bool Bound() const
Returns true if the min and the max of the expression are equal.
virtual void Run(Solver *const s)=0
This is the main callback of the demon.
virtual IntVar * Var()=0
Creates a variable from the expression.
DisjunctiveConstraint * MakeStrictDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
This constraint forces all interval vars into an non-overlapping sequence.
LocalSearchPhaseParameters * MakeLocalSearchPhaseParameters(IntVar *objective, LocalSearchOperator *const ls_operator, DecisionBuilder *const sub_decision_builder)
Local Search Phase Parameters.
virtual void VisitIntervalVariable(const IntervalVar *const variable, const std::string &operation, int64_t value, IntervalVar *const delegate)
bool CheckAssignment(Assignment *const solution)
Checks whether the given assignment satisfies all relevant constraints.
OptimizeVar * MakeWeightedMaximize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a maximization weigthed objective.
Interval variables are often used in scheduling.
Constraint * MakeSubCircuit(const std::vector< IntVar * > &nexts)
Force the "nexts" variable to create a complete Hamiltonian path for those that do not loop upon them...
void LoadFromProto(const IntVarAssignment &int_var_assignment_proto)
static const char kSumOperation[]
Constraint * MakeAtMost(std::vector< IntVar * > vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| <= max_count
Demon * MakeConstraintInitialPropagateCallback(Constraint *const ct)
This method is a specialized case of the MakeConstraintDemon method to call the InitiatePropagate of ...
void desinhibit(Solver *const s)
This method un-inhibits the demon that was previously inhibited.
~IntVarIterator() override
static const char kMinEqual[]
SearchMonitor * MakeAtSolutionCallback(std::function< void()> callback)
virtual void VisitRankLastInterval(SequenceVar *const sequence, int index)
int64_t PerformedValue() const
virtual void SetDurationRange(int64_t mi, int64_t ma)=0
IntervalContainer * MutableIntervalVarContainer()
void ExportProfilingOverview(const std::string &filename)
Exports the profiling information in a human readable overview.
Executing the search code.
std::function< DecisionModification()> BranchSelector
absl::Time Now() const
The 'absolute time' as seen by the solver.
Decision * MakeRankFirstInterval(SequenceVar *const sequence, int index)
Returns a decision that tries to rank first the ith interval var in the sequence variable.
The simple is INTERVAL_SET_TIMES_FORWARD.
static const char kIsEqual[]
void AddCastConstraint(CastConstraint *const constraint, IntVar *const target_var, IntExpr *const expr)
Adds 'constraint' to the solver and marks it as a cast constraint, that is, a constraint created call...
t1 ends after t2 end, i.e. End(t1) >= End(t2) + delay.
virtual int64_t StartMax() const =0
SearchMonitor * MakeGenericTabuSearch(bool maximize, IntVar *const v, int64_t step, const std::vector< IntVar * > &tabu_vars, int64_t forbid_tenure)
Creates a Tabu Search based on the vars |vars|.
virtual void SetValues(const std::vector< int64_t > &values)
This method intersects the current domain with the values in the array.
static const char kIntegerVariable[]
PropagationMonitor * GetPropagationMonitor() const
Returns the propagation monitor.
virtual void WhenPerformedBound(Demon *const d)=0
Constraint * MakeTemporalDisjunction(IntervalVar *const t1, IntervalVar *const t2, IntVar *const alt)
This constraint implements a temporal disjunction between two interval vars t1 and t2.
virtual IntVar * IsDifferent(int64_t constant)=0
void Decr(Solver *const s, int index)
Reversible array of POD types.
int NumSequenceVars() const
Decision * MakeAssignVariableValue(IntVar *const var, int64_t val)
Decisions.
void SaveValue(T *o)
reversibility
bool Contains(const V *const var) const
virtual void WhenStartBound(Demon *const d)=0
DecisionBuilder * MakeProfiledDecisionBuilderWrapper(DecisionBuilder *db)
Activates profiling on a decision builder.
virtual const std::vector< IntVar * > & nexts() const =0
bool operator==(const AssignmentContainer< V, E > &container) const
Returns true if this and 'container' both represent the same V* -> E map.
static const char kProductOperation[]
Operator which relaxes all inactive nodes and one sub-chain of six consecutive arcs.
~ProfiledDecisionBuilder() override
virtual void SetMax(int64_t m)=0
virtual int64_t OldEndMax() const =0
static const int64_t kMinValidValue
The smallest acceptable value to be returned by StartMin()
Relocate neighborhood with length of 1 (see OROPT comment).
Constraint * MakeSumLessOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
Variation on arrays.
std::string DebugString() const
virtual void BeginVisitModel(const std::string &type_name)
--— Virtual methods for visitors --—
IntExpr * MakeScalProd(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefs)
scalar product
virtual void VisitSequenceArrayArgument(const std::string &arg_name, const std::vector< SequenceVar * > &arguments)
bool IsUndecided(int var_index, int bin_index) const
bool NameAllVariables() const
Returns whether all variables should be named.
Move is accepted when the current objective value <= objective.Max.
int64_t PerformedMin(const IntervalVar *const var) const
IntervalVar * MakeFixedDurationStartSyncedOnStartIntervalVar(IntervalVar *const interval_var, int64_t duration, int64_t offset)
Creates an interval var with a fixed duration whose start is synchronized with the start of another i...
static const char kCountUsedBinsExtension[]
void AppendMonitors(Solver *const solver, std::vector< SearchMonitor * > *const extras) override
This method will be called at the start of the search.
VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.
void SetPerformedMax(int64_t m)
virtual void VisitIntervalArgument(const std::string &arg_name, IntervalVar *const argument)
Visit interval argument.
void FreeSolution(Assignment *solution)
Operator which defines one neighbor per variable.
void WriteToProto(IntervalVarAssignment *interval_var_assignment_proto) const
static const char kEvaluatorArgument[]
void set_optimization_direction(OptimizationDirection direction)
SolutionCollector * MakeLastSolutionCollector()
Collect the last solution of the search.
static const char kCircuit[]
static const char kIsLess[]
Implements a complete cache for model elements: expressions and constraints.
static const char kElement[]
IntExpr * MakeMin(const std::vector< IntVar * > &vars)
std::min(vars)
ValueSelection value_selection_schema
This parameter describes which value to select for a given var.
int64_t DurationMax() const
Selects the variable with the lowest starting time of all variables, and fixes its starting time to t...
Operator which cross exchanges the starting chains of 2 paths, including exchanging the whole paths.
Decision * MakeRankLastInterval(SequenceVar *const sequence, int index)
Returns a decision that tries to rank last the ith interval var in the sequence variable.
void EnqueueVar(Demon *const d)
void SetDurationRange(const IntervalVar *const var, int64_t mi, int64_t ma)
LocalSearchFilterBound
This enum is used in Solver::MakeLocalSearchObjectiveFilter.
Constraint * MakeIsLessOrEqualCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var <= value)
virtual int64_t OldDurationMin() const =0
int64_t DurationMin(const IntervalVar *const var) const
Constraint * MakeAllDifferent(const std::vector< IntVar * > &vars)
All variables are pairwise different.
static const char kVarValueWatcher[]
void SetAssignmentFromAssignment(Assignment *target_assignment, const std::vector< IntVar * > &target_vars, const Assignment *source_assignment, const std::vector< IntVar * > &source_vars)
NOLINT.
bool AcceptSolution() override
This method is called when a solution is found.
int64_t failures(int n) const
Returns the number of failures encountered at the time of the nth solution.
bool HasObjective() const
DecisionBuilder * decision_builder
When defined, this overrides the default impact based decision builder.
int solution_count() const
Returns how many solutions were stored during the search.
bool operator!=(const SequenceVarElement &element) const
NORMAL_PRIORITY is the highest priority: Demons will be processed first.
Filter manager: when a move is made, filters are executed to decide whether the solution is feasible ...
static const int64_t kint64max
virtual bool MayBePerformed() const =0
Reversible Immutable MultiMap class.
std::string DebugString() const override
virtual void Copy(const SearchLimit *const limit)=0
Copy a limit.
virtual bool AcceptSolution()
This method is called when a solution is found.
This class encapsulates an objective.
IntervalVar * MakeFixedDurationStartSyncedOnEndIntervalVar(IntervalVar *const interval_var, int64_t duration, int64_t offset)
Creates an interval var with a fixed duration whose start is synchronized with the end of another int...
static const char kMinArgument[]
int64_t PerformedValue(int n, IntervalVar *const var) const
This is a shortcut to get the PerformedValue of 'var' in the nth solution.
void AddWeightedSumEqualVarDimension(const std::vector< int64_t > &weights, const std::vector< IntVar * > &loads)
This dimension imposes that for all bins b, the weighted sum (weights[i]) of all objects i assigned t...
int64_t DurationValue(const IntervalVar *const var) const
void WhenDurationRange(Solver::Action action)
virtual int64_t EndMax() const =0
DecisionBuilder * MakeStoreAssignment(Assignment *assignment)
Returns a DecisionBuilder which stores an Assignment (calls void Assignment::Store())
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
OptimizationDirection optimization_direction() const
The direction of optimization, getter and setter.
LocalSearchFilter * MakeVariableDomainFilter()
AssignmentContainer< IntervalVar, IntervalVarElement > IntervalContainer
void Reset(SequenceVar *const var)
void ReSeed(int32_t seed)
Reseed the solver random generator.
void SetObjectiveMin(int64_t m)
int SolveDepth() const
Gets the number of nested searches.
Constraint * MakeNoCycle(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, IndexFilter1 sink_handler=nullptr)
Prevent cycles.
static const char kGreaterOrEqual[]
virtual void RemoveValues(const std::vector< int64_t > &values)
This method remove the values from the domain of the variable.
Constraint * MakeIsGreaterOrEqualCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var >= value)
static const char kDifference[]
Decision * MakeDecision(Action apply, Action refute)
void SetDurationMax(int64_t m)
virtual void VisitSplitVariableDomain(IntVar *const var, int64_t value, bool start_with_lower_half)
bool use_last_conflict
Should we use last conflict method. The default is false.
SolutionCollector * MakeFirstSolutionCollector()
Collect the first solution of the search.
void Accept(ModelVisitor *const visitor) const
Accepts the given model visitor.
IntegerCastInfo(IntVar *const v, IntExpr *const e, Constraint *const c)
virtual int64_t Value() const =0
This method returns the current value of the iterator.
std::string DebugString() const override
IntExpr * MakeAbs(IntExpr *const expr)
|expr|
void SetEndMin(int64_t m)
The class Iterator has two direct subclasses.
virtual std::string BaseName() const
Returns a base name for automatic naming.
UnaryIntervalRelation
This enum is used in Solver::MakeIntervalVarRelation to specify the temporal relation between an inte...
void BeginNextDecision(DecisionBuilder *const b) override
Before calling DecisionBuilder::Next.
Constraint * MakeIsLessCstCt(IntExpr *const v, int64_t c, IntVar *const b)
b == (v < c)
static const char kCover[]
static const char kPerformedExpr[]
Constraint * MakeIsEqualCt(IntExpr *const v1, IntExpr *v2, IntVar *const b)
b == (v1 == v2)
IntVar * MakeIsLessVar(IntExpr *const left, IntExpr *const right)
status var of (left < right)
void LoadFromProto(const SequenceVarAssignment &sequence_var_assignment_proto)
void WhenAnything(Solver::Closure closure)
Attaches a closure awakened when anything about this interval changes.
bool IsProfilingEnabled() const
Returns whether we are profiling the solver.
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
void Copy(const IntervalVarElement &element)
Holds semantic information stating that the 'expression' has been cast into 'variable' using the Var(...
SearchMonitor * MakeSearchTrace(const std::string &prefix)
Creates a search monitor that will trace precisely the behavior of the search.
bool Check() override
This method is called to check the status of the limit.
static const char kLessOrEqual[]
ConstraintSolverStatistics GetConstraintSolverStatistics() const
Returns detailed cp search statistics.
SearchMonitor * MakeLubyRestart(int scale_factor)
This search monitor will restart the search periodically.
static const char kVariableGroupExtension[]
bool UseFastLocalSearch() const
Returns true if fast local search is enabled.
Operator which makes a "chain" of path nodes inactive.
static const char kBranchesLimitArgument[]
static const char kLateDateArgument[]
int64_t Rand64(int64_t size)
Returns a random value between 0 and 'size' - 1;.
IntExpr * MakeMax(const std::vector< IntVar * > &vars)
std::max(vars)
void WhenPerformedBound(Solver::Action action)
t1 starts at t2 end, i.e. Start(t1) == End(t2) + delay.
void MakeFixedDurationIntervalVarArray(int count, int64_t start_min, int64_t start_max, int64_t duration, bool optional, const std::string &name, std::vector< IntervalVar * > *const array)
This method fills the vector with 'count' interval variables built with the corresponding parameters.
void Copy(const IntVarElement &element)
Constraint * MakeAllowedAssignments(const std::vector< IntVar * > &vars, const IntTupleSet &tuples)
This method creates a constraint where the graph of the relation between the variables is given in ex...
This class represents a sorted list of disjoint, closed intervals.
LocalSearchOperators
This enum is used in Solver::MakeOperator to specify the neighborhood to create.
Decision * MakeAssignVariableValueOrFail(IntVar *const var, int64_t value)
virtual void NoMoreSolutions()
When the search tree is finished.
virtual bool AcceptDelta(Assignment *delta, Assignment *deltadelta)
IntExpr * CastExpression(const IntVar *const var) const
!defined(SWIG)
Selects the variable with the highest ending time of all variables, and fixes the ending time to this...
int64_t Min(const IntVar *const var) const
Pack(Solver *const s, const std::vector< IntVar * > &vars, int number_of_bins)
RegularLimit(Solver *const s, absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check, bool cumulative)
void SetEndMin(const IntervalVar *const var, int64_t m)
int constraints() const
Counts the number of constraints that have been added to the solver before the search.
static const char kUsageLessConstantExtension[]
Pack * MakePack(const std::vector< IntVar * > &vars, int number_of_bins)
This constraint packs all variables onto 'number_of_bins' variables.
DecisionBuilder * MakeDefaultPhase(const std::vector< IntVar * > &vars)
Constraint * MakeDelayedPathCumul(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, const std::vector< IntVar * > &cumuls, const std::vector< IntVar * > &transits)
Delayed version of the same constraint: propagation on the nexts variables is delayed until all const...
void SetPerformedMax(const IntervalVar *const var, int64_t m)
PropagationBaseObject(Solver *const s)
virtual void SetMin(int64_t m)=0
static const char kCountAssignedItemsExtension[]
Extension names:
virtual void RegisterNewSolution(Assignment *const assignment)=0
This method is called when a new solution has been accepted by the local search.
void WriteToProto(SequenceVarAssignment *sequence_var_assignment_proto) const
Demon * RegisterDemon(Demon *const demon)
Adds a new demon and wraps it inside a DemonProfiler if necessary.
IntExpr * MakeDifference(IntExpr *const left, IntExpr *const right)
left - right
void SetPerformedValue(const IntervalVar *const var, int64_t value)
IntContainer * MutableIntVarContainer()
static const char kStartSyncOnEndOperation[]
void Accept(ModelVisitor *const visitor) const override
Accepts the given model visitor.
void AddPropagationMonitor(PropagationMonitor *const monitor)
Adds the propagation monitor to the solver.
Constraint * MakeDeviation(const std::vector< IntVar * > &vars, IntVar *const deviation_var, int64_t total_sum)
Deviation constraint: sum_i |n * vars[i] - total_sum| <= deviation_var and sum_i vars[i] == total_sum...
LocalSearchOperator * MakeRandomLnsOperator(const std::vector< IntVar * > &vars, int number_of_variables)
Creates a large neighborhood search operator which creates fragments (set of relaxed variables) with ...
ProfiledDecisionBuilder(DecisionBuilder *db)
static const char kDelayedPathCumul[]
void clear_fail_intercept()
static const char kIsBetween[]
bool AcceptDelta(Assignment *delta, Assignment *deltadelta) override
Internal methods.
void SetUnassigned(int var_index)
void RankFirst(int index)
Ranks the index_th interval var first of all unranked interval vars.
IntVar * Next(int index) const
Returns the next of the index_th interval of the sequence.
The SequenceVarElement stores a partial representation of ranked interval variables in the underlying...
void AddCountUsedBinDimension(IntVar *const count_var)
This dimension links 'count_var' to the actual number of bins used in the pack.
IntVar * MakeIsMemberVar(IntExpr *const expr, const std::vector< int64_t > &values)
void SetDurationValue(int64_t v)
static const int64_t kMaxValidValue
The largest acceptable value to be returned by EndMax()
void SaveAndAdd(T *adr, T val)
All-in-one SaveAndAdd_value.
uint64_t stamp() const
The stamp indicates how many moves in the search tree we have performed.
void SetEndValue(const IntervalVar *const var, int64_t value)
static const char kIntervalVariable[]
bool operator!=(const IntVarElement &element) const
int64_t ObjectiveMax() const
void set_variable_to_clean_on_fail(IntVar *v)
Shortcut for variable cleaner.
t1 starts after t2 end, i.e. Start(t1) >= End(t2) + delay.
bool operator!=(const AssignmentContainer< V, E > &container) const
static const char kTransitsArgument[]
DisjunctiveConstraint(Solver *const s, const std::vector< IntervalVar * > &intervals, const std::string &name)
virtual IntExpr * SafeDurationExpr(int64_t unperformed_value)=0
Among unbound variables, select the variable with the largest gap between the first and the second va...
void SetStartValue(int64_t v)
void WhenStartBound(Solver::Action action)
std::function< int64_t(int64_t, int64_t, int64_t)> IndexEvaluator3
void UnfreezeQueue()
This method unfreezes the propagation queue.
std::string DebugString() const override
std::function< void(Solver *)> Action
void set_name(const std::string &name)
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given model visitor.
static constexpr int kNumPriorities
Number of priorities for demons.
static const char kFinalStatesArgument[]
Constraint * MakeIntervalVarRelation(IntervalVar *const t, UnaryIntervalRelation r, int64_t d)
This method creates a relation between an interval var and a date.
void UnassignAllRemainingItems()
bool IsPossible(int var_index, int bin_index) const
void SetStartMin(const IntervalVar *const var, int64_t m)
Selects the max value of the selected variable.
SearchMonitor(Solver *const s)
Constraint * MakeIsEqualCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var == value)
virtual void EndVisitIntegerExpression(const std::string &type_name, const IntExpr *const expr)
void SetAssigned(int var_index)
virtual void AppendMonitors(Solver *const solver, std::vector< SearchMonitor * > *const extras)
This method will be called at the start of the search.
virtual void Install()
Registers itself on the solver such that it gets notified of the search and propagation events.
int64_t wall_time() const
DEPRECATED: Use Now() instead.
virtual void PeriodicCheck()
Periodic call to check limits in long running methods.
Constraint * MakeLess(IntExpr *const left, IntExpr *const right)
left < right
Left branches are ignored.
SequenceVar * Var() const
static const char kUsageEqualVariableExtension[]
int TopProgressPercent()
Returns a percentage representing the propress of the search before reaching the limits of the top-le...
void AddBacktrackAction(Action a, bool fast)
When SaveValue() is not the best way to go, one can create a reversible action that will be called up...
An Assignment is a variable -> domains mapping, used to report solutions to the user.
virtual uint64_t Size() const =0
This method returns the number of values in the domain of the variable.
Decision * MakeAssignVariablesValuesOrFail(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
~DisjunctiveConstraint() override
const std::vector< int > & BackwardSequence(const SequenceVar *const var) const
IntExpr * MakeSquare(IntExpr *const expr)
expr * expr
LocalSearchStatistics GetLocalSearchStatistics() const
Returns detailed local search statistics.
void Accept(ModelVisitor *const visitor) const override
Accepts the given model visitor.
void CopyIntersection(const Assignment *assignment)
Copies the intersection of the two assignments to the current assignment.
Constraint * MakeLexicalLessOrEqual(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
Creates a constraint that enforces that left is lexicographically less than or equal to right.
friend class DemonProfiler
LocalSearchMonitor * GetLocalSearchMonitor() const
Returns the local search monitor.
void ExecuteAll(const SimpleRevFIFO< Demon * > &demons)
int heuristic_period
The distance in nodes between each run of the heuristics.
~SearchMonitor() override
static const char kSmartTimeCheckArgument[]
A BaseObject is the root of all reversibly allocated objects.
Constraint * MakeIndexOfFirstMaxValueConstraint(IntVar *index, const std::vector< IntVar * > &vars)
Creates a constraint that binds the index variable to the index of the first variable with the maximu...
IntervalVarElement * Clone()
The class IntVar is a subset of IntExpr.
virtual Decision * Next(Solver *const s)=0
This is the main method of the decision builder class.
void WhenDurationBound(Solver::Action action)
#define DCHECK_GE(val1, val2)
void FinishCurrentSearch()
Tells the solver to kill or restart the current search.
t1 ends after t2 start, i.e. End(t1) >= Start(t2) + delay.
virtual void VisitIntegerMatrixArgument(const std::string &arg_name, const IntTupleSet &tuples)
Constraint * MakeCover(const std::vector< IntervalVar * > &vars, IntervalVar *const target_var)
This constraint states that the target_var is the convex hull of the intervals.
IntervalVar * MakeMirrorInterval(IntervalVar *const interval_var)
Creates an interval var that is the mirror image of the given one, that is, the interval var obtained...
SearchMonitor * MakeSimulatedAnnealing(bool maximize, IntVar *const v, int64_t step, int64_t initial_temperature)
Creates a Simulated Annealing monitor.
The class IntExpr is the base of all integer expressions in constraint programming.
void SetDurationMin(int64_t m)
static const char kIntervalBinaryRelation[]
Constraint * MakeIsBetweenCt(IntExpr *const expr, int64_t l, int64_t u, IntVar *const b)
b == (l <= expr <= u)
virtual void VisitSetVariableValue(IntVar *const var, int64_t value)
Among unbound variables, select the variable with the highest maximal value.
static const char kBetween[]
Constraint * MakeIsGreaterOrEqualCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left >= right)
IntValueStrategy
This enum describes the strategy used to select the next variable value to set.
T * RevAllocArray(T *object)
Like RevAlloc() above, but for an array of objects: the array must have been allocated with the new[]...
virtual bool LocalOptimum()
When a local optimum is reached.
static const char kTimeLimitArgument[]
static Iterator End(IntVarIterator *it)
void SetValue(Solver *const s, int index, const T &val)
std::string DebugString() const
!defined(SWIG)
Constraint * MakeLessOrEqual(IntExpr *const left, IntExpr *const right)
left <= right
STARTS_AT_START and ENDS_AT_END at the same time.
IntVar * target_var() const
void ShouldFail()
These methods are only useful for the SWIG wrappers, which need a way to externally cause the Solver ...
STARTS_BEFORE and ENDS_AFTER at the same time, i.e.
IntExpr * MakeMonotonicElement(IndexEvaluator1 values, bool increasing, IntVar *const index)
Function based element.
#define CHECK_EQ(val1, val2)
void Incr(Solver *const s)
void WhenStartRange(Solver::Action action)
static const char kVarsArgument[]
Relocate: OROPT and RELOCATE.
Move is accepted when the current objective value >= objective.Min.
virtual void EndNextDecision(DecisionBuilder *const b, Decision *const d)
After calling DecisionBuilder::Next, along with the returned decision.
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given visitor.
IntExpr * MakeElement(const std::vector< int64_t > &values, IntVar *const index)
values[index]
void AddObjective(IntVar *const v)
virtual IntVar * IsGreaterOrEqual(int64_t constant)=0
int64_t PerformedValue(const IntervalVar *const var) const
ABSL_MUST_USE_RESULT RegularLimit * MakeFailuresLimit(int64_t failures)
Creates a search limit that constrains the number of failures that can happen when exploring the sear...
Constraint * MakeSumGreaterOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
static const char kIntervalDisjunction[]
IntExpr * MakeIndexExpression(const std::vector< IntVar * > &vars, int64_t value)
Returns the expression expr such that vars[expr] == value.
IntVarStrategy
This enum describes the strategy used to select the next branching variable at each node during the s...
OptimizeVar * MakeWeightedMinimize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a minimization weighted objective.
virtual void SetValue(int64_t v)
This method sets the value of the expression.
E * MutableElement(const V *const var)
static const char kSumGreaterOrEqual[]
Constraint * MakeIsMemberCt(IntExpr *const expr, const std::vector< int64_t > &values, IntVar *const boolvar)
boolvar == (expr in set)
virtual int64_t OldEndMin() const =0
static const char kSequencesArgument[]
void SetMax(const IntVar *const var, int64_t m)
Constraint * MakeIndexOfFirstMinValueConstraint(IntVar *index, const std::vector< IntVar * > &vars)
Creates a constraint that binds the index variable to the index of the first variable with the minimu...
std::string DebugString() const override
virtual void VisitIntegerArgument(const std::string &arg_name, int64_t value)
Visit integer arguments.
ImprovementSearchLimit(Solver *const s, IntVar *objective_var, bool maximize, double objective_scaling_factor, double objective_offset, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
std::function< int64_t(int64_t, int64_t)> IndexEvaluator2
static const char kIndexArgument[]
static const char kAbs[]
Constraint and Expression types.
Assignment * GetOrCreateLocalSearchState()
Returns (or creates) an assignment representing the state of local search.
IntVar * MakeIntVar(int64_t min, int64_t max, const std::string &name)
MakeIntVar will create the best range based int var for the bounds given.
void PostAndPropagate()
Calls Post and then Propagate to initialize the constraints.
This class represent a reversible FIFO structure.
Before search, after search.
virtual int64_t DurationMin() const =0
These methods query, set, and watch the duration of the interval var.
int64_t demon_runs(DemonPriority p) const
The number of demons executed during search for a given priority.
T * RevAlloc(T *object)
Registers the given object as being reversible.
bool crossed() const
Returns true if the limit has been crossed.
Constraint * MakeIfThenElseCt(IntVar *const condition, IntExpr *const then_expr, IntExpr *const else_expr, IntVar *const target_var)
Special cases with arrays of size two.
void SetPerformedMin(const IntervalVar *const var, int64_t m)
IntVar *const target_var_
Decision * Next(Solver *const solver) override
This is the main method of the decision builder class.
bool AreAllElementsBound() const
VariableSelection var_selection_schema
This parameter describes how the next variable to instantiate will be chosen.
bool ObjectiveBound() const
void SetRange(int64_t l, int64_t u)
void Copy(const SearchLimit *const limit) override
Copy a limit.
Constraint * MakeLexicalLess(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
Creates a constraint that enforces that left is lexicographically less than right.
static const char kWeightedSumOfAssignedEqualVariableExtension[]
IntVar * MakeIsBetweenVar(IntExpr *const v, int64_t l, int64_t u)
DecisionBuilder * MakeApplyBranchSelector(BranchSelector bs)
Creates a decision builder that will set the branch selector.
static const char kValuesArgument[]
bool persistent_impact
Whether to keep the impact from the first search for other searches, or to recompute the impact for e...
void EnterSearch() override
Internal methods.
void Accept(ModelVisitor *const visitor) const override
int64_t DurationValue(int n, IntervalVar *const var) const
This is a shortcut to get the DurationValue of 'var' in the nth solution.
int64_t solutions() const
Among unbound variables, select the variable with the smallest size.
void CopyIntersection(const AssignmentContainer< V, E > &container)
Copies the elements of 'container' which are already in the calling container.
static const char kInitialState[]
Solver::IndexEvaluator2 transition_time_
std::string DebugString() const override
bool operator!=(const Assignment &assignment) const
virtual int64_t EndMin() const =0
These methods query, set, and watch the end position of the interval var.
#define DCHECK(condition)
Keeps the default behavior, i.e.
static const char kAllowedAssignments[]
Search * ActiveSearch() const
Returns the active search, nullptr outside search.
const Collection::value_type::second_type & FindWithDefault(const Collection &collection, const typename Collection::value_type::first_type &key, const typename Collection::value_type::second_type &value)
A sequence variable is a variable whose domain is a set of possible orderings of the interval variabl...
Operator which replaces an active node by an inactive one.
Constraint * MakeBetweenCt(IntExpr *const expr, int64_t l, int64_t u)
(l <= expr <= u)
static const char kMaxEqual[]
Select the first unbound variable.
DecisionBuilder * MakeConstraintAdder(Constraint *const ct)
Returns a decision builder that will add the given constraint to the model.
Assignment * MakeAssignment()
This method creates an empty assignment.
Operator which reverses a sub-chain of a path.
ModelCache * Cache() const
Returns the cache of the model.
const std::vector< int > & Unperformed() const
STARTS_AFTER or ENDS_BEFORE, i.e.
void Post() override
This method is called when the constraint is processed by the solver.
Constraint * MakeGreaterOrEqual(IntExpr *const left, IntExpr *const right)
left >= right
virtual void VisitIntegerVariable(const IntVar *const variable, IntExpr *const delegate)
virtual void AcceptNeighbor()
After accepting a neighbor during local search.
SearchLimit(Solver *const s)
static const char kConditionalExpr[]
virtual void VisitIntegerArrayArgument(const std::string &arg_name, const std::vector< int64_t > &values)
IntVar * MakeIsLessOrEqualVar(IntExpr *const left, IntExpr *const right)
status var of (left <= right)
virtual void Next()=0
This method moves the iterator to the next value.
static const char kSquare[]
virtual std::string DebugString() const
virtual void SetEndMin(int64_t m)=0
This class is used to manage a pool of solutions.
IntVar * MakeIntConst(int64_t val, const std::string &name)
IntConst will create a constant expression.
std::function< bool(int64_t)> IndexFilter1
void Init() override
This method is called when the search limit is initialized.
absl::Duration duration_limit() const
std::function< int64_t(Solver *solver, const std::vector< IntVar * > &vars, int64_t first_unbound, int64_t last_unbound)> VariableIndexSelector
void Copy(const AssignmentContainer< V, E > &container)
Copies all the elements of 'container' to this container, clearing its previous content.
static const char kLeftArgument[]
static const char kDurationMaxArgument[]
virtual int ProgressPercent()
Returns a percentage representing the propress of the search before reaching limits.
virtual void AcceptUncheckedNeighbor()
After accepting an unchecked neighbor during local search.
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)
Creates an interval var by specifying the bounds on start, duration, and end.
Operator which defines one neighbor per variable.
OptimizeVar * objective
SearchMonitors will display values of objective or variable (both cannot be used together).
static const char kTransition[]
LocalSearchFilter * MakeAcceptFilter()
Local Search Filters.
void Fail()
Abandon the current branch in the search tree. A backtrack will follow.
#define DCHECK_EQ(val1, val2)
static const char kSemiContinuous[]
virtual void WhenDurationRange(Demon *const d)=0
static const char kNotBetween[]
Constraint * MakeCumulative(const std::vector< IntervalVar * > &intervals, const std::vector< int64_t > &demands, int64_t capacity, const std::string &name)
This constraint forces that, for any integer t, the sum of the demands corresponding to an interval c...
void SetPerformedValue(int64_t v)
virtual int64_t OldMin() const =0
Returns the previous min.
void SetUnperformed(const std::vector< int > &unperformed)
SequenceStrategy
Used for scheduling. Not yet implemented.
static const char kMirrorOperation[]
Operations.
void SetPerformedRange(int64_t mi, int64_t ma)
void InitialPropagate() override
This method performs the initial propagation of the constraint.
Constraint * MakeTransitionConstraint(const std::vector< IntVar * > &vars, const IntTupleSet &transition_table, int64_t initial_state, const std::vector< int64_t > &final_states)
This constraint create a finite automaton that will check the sequence of variables vars.
SearchMonitor * MakeGuidedLocalSearch(bool maximize, IntVar *const objective, IndexEvaluator2 objective_function, int64_t step, const std::vector< IntVar * > &vars, double penalty_factor)
Creates a Guided Local Search monitor.
int64_t EndMin(const IntervalVar *const var) const
static const char kScalProdEqual[]
const std::string & name() const
static const char kCumulativeArgument[]
virtual void EndVisitExtension(const std::string &type)
void SetObjectiveValue(int64_t value)
friend void InternalSaveBooleanVarValue(Solver *const, IntVar *const)
void SetSearchContext(Search *search, const std::string &search_context)
int64_t PerformedMax(const IntervalVar *const var) const
Constraint * MakePathTransitPrecedenceConstraint(std::vector< IntVar * > nexts, std::vector< IntVar * > transits, const std::vector< std::pair< int, int >> &precedences)
Same as MakePathPrecedenceConstraint but will force i to be before j if the sum of transits on the pa...
virtual void SetDurationMax(int64_t m)=0
static const char kSequenceArgument[]
void WhenDurationBound(Solver::Closure closure)
void SetValue(Solver *const s, const T &val)
DemonPriority
This enum represents the three possible priorities for a demon in the Solver queue.
static const char kRelaxedMaxOperation[]
A Decision represents a choice point in the search tree.
Constraint * MakeNotBetweenCt(IntExpr *const expr, int64_t l, int64_t u)
(expr < l || expr > u) This constraint is lazy as it will not make holes in the domain of variables.
int64_t DurationMax(const IntervalVar *const var) const
Decision * MakeVariableLessOrEqualValue(IntVar *const var, int64_t value)
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given visitor.
int64_t Value(int n, IntVar *const var) const
This is a shortcut to get the Value of 'var' in the nth solution.
int64_t branches(int n) const
Returns the number of branches when the nth solution was found.
static const char kIsDifferent[]
Pairs are compared each time a variable is selected.
virtual void SetStartMax(int64_t m)=0
virtual void WhenStartRange(Demon *const d)=0
Constraint * MakeTrueConstraint()
This constraint always succeeds.
IntVar * MakeIsDifferentCstVar(IntExpr *const var, int64_t value)
status var of (var != value)
LocalSearchOperator * ConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
Creates a local search operator which concatenates a vector of operators.
void SetEndValue(int64_t v)
OptimizeVar(Solver *const s, bool maximize, IntVar *const a, int64_t step)
static const char kModulo[]
static const char kDeviation[]
void ExitSearch() override
End of the search.
void check_index(int n) const
static const char kSortingConstraint[]
uint64_t fail_stamp() const
The fail_stamp() is incremented after each backtrack.
static const char kScalProd[]
bool IsLocalSearchProfilingEnabled() const
Returns whether we are profiling local search.
static const char kScalProdGreaterOrEqual[]
A search monitor is a simple set of callbacks to monitor all search events.
virtual void AfterDecision(Decision *const d, bool apply)
Just after refuting or applying the decision, apply is true after Apply.
std::string DebugString() const override
std::function< std::string()> display_callback
SearchMonitors will display the result of display_callback at each new solution found and when the se...
DecisionBuilder * MakePhase(const std::vector< IntVar * > &vars, IntVarStrategy var_str, IntValueStrategy val_str)
Phases on IntVar arrays.
std::vector< int64_t > tmp_vector_
Unsafe temporary vector.
virtual int64_t OldDurationMax() const =0
IntervalStrategy
This enum describes the straregy used to select the next interval variable and its value to be fixed.
static const char kLateCostArgument[]
virtual IntExpr * SafeEndExpr(int64_t unperformed_value)=0
void set_name(const std::string &name)
void FillSequence(std::vector< int > *const rank_first, std::vector< int > *const rank_last, std::vector< int > *const unperformed) const
Clears 'rank_first' and 'rank_last', and fills them with the intervals in the order of the ranks.
void PushState()
The PushState and PopState methods manipulates the states of the reversible objects.
virtual void WhenDomain(Demon *d)=0
This method attaches a demon that will watch any domain modification of the domain of the variable.
IntervalVar * MakeFixedDurationIntervalVar(int64_t start_min, int64_t start_max, int64_t duration, bool optional, const std::string &name)
Creates an interval var with a fixed duration.
void Copy(const Assignment *assignment)
Copies 'assignment' to the current assignment, clearing its previous content.
virtual void VisitIntegerVariableEvaluatorArgument(const std::string &arg_name, const Solver::Int64ToIntVar &arguments)
Helpers.
static const char kRangeArgument[]
static const char kInversePermutation[]
std::string DebugString() const override
static const char kAtMost[]
SharedBoundsManager * bounds
void WhenStartBound(Solver::Closure closure)
bool HasName(const PropagationBaseObject *object) const
Returns whether the object has been named or not.
std::string DebugString() const override
virtual IntVar * IsEqual(int64_t constant)=0
IsEqual.
static const char kNullIntersect[]
static const char kSumEqual[]
Collection of objects used to extend the Constraint Solver library.
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
bool Check() override
This method is called to check the status of the limit.
virtual void ApplyDecision(Decision *const d)
Before applying the decision.
int initialization_splits
Maximum number of intervals that the initialization of impacts will scan per variable.
Constraint * MakeMaxEquality(const std::vector< IntVar * > &vars, IntVar *const max_var)
virtual IntExpr * EndExpr()=0
virtual void VisitSequenceVariable(const SequenceVar *const variable)
bool IsBooleanVar(IntExpr *const expr, IntVar **inner_var, bool *is_negated) const
Returns true if expr represents either boolean_var or 1 - boolean_var.
const std::vector< IntervalVar * > intervals_
DecisionBuilder * MakeNestedOptimize(DecisionBuilder *const db, Assignment *const solution, bool maximize, int64_t step)
NestedOptimize will collapse a search tree described by a decision builder 'db' and a set of monitors...
virtual void EndVisitConstraint(const std::string &type_name, const Constraint *const constraint)
void SetDurationMax(const IntervalVar *const var, int64_t m)
double scaling_factor
When displayed, objective or var values will be scaled and offset by the given values in the followin...
int64_t accepted_neighbors() const
The number of accepted neighbors.
virtual void BeginVisitExtension(const std::string &type)
bool operator==(const IntervalVarElement &element) const
virtual void Refute(Solver *const s)=0
Refute will be called after a backtrack.
virtual IntVar * IsLessOrEqual(int64_t constant)=0
void Decr(Solver *const s)
static const char kFalseConstraint[]
static const char kFixedChargeArgument[]
IntExpr * MakeConditionalExpression(IntVar *const condition, IntExpr *const expr, int64_t unperformed_value)
Conditional Expr condition ? expr : unperformed_value.
virtual void SetStartRange(int64_t mi, int64_t ma)=0
A symmetry breaker is an object that will visit a decision and create the 'symmetrical' decision in r...
DisplayLevel display_level
This represents the amount of information displayed by the default search.
bool ActivatedObjective() const
static const char kIsGreater[]
~PropagationBaseObject() override
friend class SearchMonitor
IntervalVar * MakeFixedDurationEndSyncedOnStartIntervalVar(IntervalVar *const interval_var, int64_t duration, int64_t offset)
Creates an interval var with a fixed duration whose end is synchronized with the start of another int...
std::string DebugString() const override
Constraint * MakeEquality(IntExpr *const left, IntExpr *const right)
left == right
void EnqueueAll(const SimpleRevFIFO< Demon * > &demons)
NumericalRevArray(int size, const T &val)
void HorizonRange(int64_t *const hmin, int64_t *const hmax) const
Returns the minimum start min and the maximum end max of all interval vars in the sequence.
virtual void SetDurationMin(int64_t m)=0
static const char kStepArgument[]
IntVar * AssignVar(int var_index, int bin_index) const
absl::Span< const double > coefficients
Operator which makes an inactive node active and an active one inactive.
Selects the next unbound variable on a path, the path being defined by the variables: var[i] correspo...
Operator which relaxes one entire path and all inactive nodes, thus defining num_paths neighbors.
static const char kExpressionArgument[]
virtual SearchLimit * MakeClone() const =0
Allocates a clone of the limit.
Selects randomly one of the possible values of the selected variable.
bool AtSolution() override
This method is called when a valid solution is found.
virtual void Accept(ModelVisitor *const visitor) const
virtual void Range(int64_t *l, int64_t *u)
By default calls Min() and Max(), but can be redefined when Min and Max code can be factorized.
static const char kLexLess[]
IntVar * MakeIsDifferentVar(IntExpr *const v1, IntExpr *const v2)
status var of (v1 != v2)
static const char kIsGreaterOrEqual[]
virtual void Initialize(Assignment *const assignment)=0
This method is called to initialize the solution pool with the assignment from the local search.
static const char kValueArgument[]
virtual void WhenRange(Demon *d)=0
Attach a demon that will watch the min or the max of the expression.
static const char kOpposite[]
Constraint * MakeIsGreaterCstCt(IntExpr *const v, int64_t c, IntVar *const b)
b == (v > c)
Constraint * MakeMinEquality(const std::vector< IntVar * > &vars, IntVar *const min_var)
Decision * MakeScheduleOrPostpone(IntervalVar *const var, int64_t est, int64_t *const marker)
Returns a decision that tries to schedule a task at a given time.
static const char kSumLessOrEqual[]
void SetDurationMin(const IntervalVar *const var, int64_t m)
void inhibit(Solver *const s)
This method inhibits the demon in the search tree below the current position.
virtual bool AtSolution()
This method is called when a valid solution is found.
void RefuteDecision(Decision *const d) override
Before refuting the decision.
~DecisionBuilder() override
int64_t operator *() const
static const char kActiveArgument[]
argument names:
void ComputePossibleFirstsAndLasts(std::vector< int > *const possible_firsts, std::vector< int > *const possible_lasts)
Computes the set of indices of interval variables that can be ranked first in the set of unranked act...
IntExpr * MakeSemiContinuousExpr(IntExpr *const expr, int64_t fixed_charge, int64_t step)
Semi continuous Expression (x <= 0 -> f(x) = 0; x > 0 -> f(x) = ax + b) a >= 0 and b >= 0.
std::string DebugString() const
const T & operator[](int index) const
std::string DebugString() const override
IntVar * MakeIsLessOrEqualCstVar(IntExpr *const var, int64_t value)
status var of (var <= value)
DecisionBuilder * Try(DecisionBuilder *const db1, DecisionBuilder *const db2)
Creates a decision builder which will create a search tree where each decision builder is called from...
void Add(Solver *const s, const T &to_add)
Decision * MakeAssignVariableValueOrDoNothing(IntVar *const var, int64_t value)
t starts before d, i.e. Start(t) <= d.
DecisionBuilder * MakeLocalSearchPhase(Assignment *const assignment, LocalSearchPhaseParameters *const parameters)
Local Search decision builders factories.
IntervalVar * MakeIntervalRelaxedMin(IntervalVar *const interval_var)
Creates and returns an interval variable that wraps around the given one, relaxing the min start and ...
EvaluatorLocalSearchOperators
This enum is used in Solver::MakeOperator associated with an evaluator to specify the neighborhood to...
ModelVisitor * MakePrintModelVisitor()
Prints the model.
virtual const std::vector< IntVar * > & time_slacks() const =0
LocalSearchOperator * MakeMoveTowardTargetOperator(const Assignment &target)
Creates a local search operator that tries to move the assignment of some variables toward a target.
Among unbound variables, select the variable with the highest size.
static constexpr int kNoProgress
DecisionBuilder * MakeRestoreAssignment(Assignment *assignment)
Returns a DecisionBuilder which restores an Assignment (calls void Assignment::Restore())
int64_t TransitionTime(int before_index, int after_index)
static const char kNextsArgument[]
IntExpr * MakeDiv(IntExpr *const expr, int64_t value)
expr / value (integer division)
void WhenEndBound(Solver::Closure closure)
ModelVisitor * MakeStatisticsModelVisitor()
Displays some nice statistics on the model.
virtual bool MustBePerformed() const =0
These methods query, set, and watch the performed status of the interval var.
IntervalVar * Interval(int index) const
Returns the index_th interval of the sequence.
void EnqueueDelayedDemon(Demon *const d)
This method pushes the demon onto the propagation queue.
E * MutableElement(int index)
const E & Element(int index) const
Constraint * MakeNonEquality(IntExpr *const left, IntExpr *const right)
left != right
static const char kTargetArgument[]
Subclass of Rev<T> which adds numerical operations.
void BeginNextDecision(DecisionBuilder *const db) override
Before calling DecisionBuilder::Next.
void Accept(ModelVisitor *const visitor) const override
Accepts the given visitor.
void SetObjectiveMax(int64_t m)
bool Save(const std::string &filename) const
Saves the assignment to a file.
Move is accepted when the current objective value is in the interval objective.Min .
SearchMonitor * MakeSymmetryManager(const std::vector< SymmetryBreaker * > &visitors)
Symmetry Breaking.
IntExpr * MakeModulo(IntExpr *const x, int64_t mod)
Modulo expression x % mod (with the python convention for modulo).
Decision * MakeAssignVariablesValues(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
static const char kStartMinArgument[]
void set_action_on_fail(Solver::Action a)
Subclass of RevArray<T> which adds numerical operations.
void SetDurationValue(const IntervalVar *const var, int64_t value)
int64_t StartMax(const IntervalVar *const var) const
IntExpr * MakePiecewiseLinearExpr(IntExpr *expr, const PiecewiseLinearFunction &f)
General piecewise-linear function expression, built from f(x) where f is piecewise-linear.
Constraint * MakePathCumul(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, const std::vector< IntVar * > &cumuls, const std::vector< IntVar * > &transits)
Creates a constraint which accumulates values along a path such that: cumuls[next[i]] = cumuls[i] + t...
const std::vector< int > & ForwardSequence(const SequenceVar *const var) const
virtual void SetEndMax(int64_t m)=0
LocalSearchOperator * RandomConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
Randomized version of local search concatenator; calls a random operator at each call to MakeNextNeig...
Applies right branch first.
void WriteToProto(IntVarAssignment *int_var_assignment_proto) const
IntExpr * MakeOpposite(IntExpr *const expr)
-expr
static const char kNonEqual[]
void SetRange(const IntVar *const var, int64_t l, int64_t u)
bool Solve(DecisionBuilder *const db, const std::vector< SearchMonitor * > &monitors)
std::string SearchContext() const
virtual bool Ok() const =0
This method indicates if we can call Value() or not.
t1 starts after t2 start, i.e. Start(t1) >= Start(t2) + delay.
static const char kTraceOperation[]
std::string model_name() const
Returns the name of the model.
OptimizeVar * MakeMinimize(IntVar *const v, int64_t step)
Creates a minimization objective.
static const char kCoefficientsArgument[]
virtual void SetRange(int64_t l, int64_t u)
This method sets both the min and the max of the expression.
virtual void Accept(ModelVisitor *const visitor) const =0
Accepts the given visitor.
static const char kRightArgument[]
static const char kSizeArgument[]
virtual bool WasPerformedBound() const =0
SequenceVarElement * Clone()
static const char kEndExpr[]
static const char kStartMaxArgument[]
Demon * MakeActionDemon(Action action)
Creates a demon from a callback.
void SetSequence(const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
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)
This constraint states that all the boxes must not overlap.
void FreezeQueue()
This method freezes the propagation queue.
static const char kIntervalsArgument[]
static const char kEndMinArgument[]
Base class of all search limits.
int64_t StartMin(const IntervalVar *const var) const
static const char kAssumePathsArgument[]
NumericalRev(const T &val)
Split the domain in two around the center, and choose the lower part first.
void SetMin(const IntVar *const var, int64_t m)
void Resize(size_t size)
Advanced usage: Resizes the container, potentially adding elements with null variables.
bool HasName() const
Returns whether the object has been named or not.
void SetUseFastLocalSearch(bool use_fast_local_search)
enabled for metaheuristics.
const IntContainer & IntVarContainer() const
void SetStartMax(int64_t m)
void EnterSearch() override
Beginning of the search.
void SetEndRange(const IntervalVar *const var, int64_t mi, int64_t ma)
static const char kDurationExpr[]
static const char kEarlyDateArgument[]
void AssignAllPossibleToBin(int bin_index)
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
Split the domain in two around the center, and choose the lower part first.
IntExpr * MakeConvexPiecewiseExpr(IntExpr *expr, int64_t early_cost, int64_t early_date, int64_t late_date, int64_t late_cost)
Convex piecewise function.
Constraint * MakePathPrecedenceConstraint(std::vector< IntVar * > nexts, const std::vector< std::pair< int, int >> &precedences)
Constraint enforcing, for each pair (i,j) in precedences, i to be before j in paths defined by next v...
void Add(Solver *const s, int index, const T &to_add)
virtual void WhenDurationBound(Demon *const d)=0
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)
Limits the search based on the improvements of 'objective_var'.
SearchMonitor * MakeEnterSearchCallback(std::function< void()> callback)
--— Callback-based search monitors --—
int64_t EndValue(int n, IntervalVar *const var) const
This is a shortcut to get the EndValue of 'var' in the nth solution.
const std::vector< int > & Unperformed(const SequenceVar *const var) const
void RankNotLast(int index)
Indicates that the index_th interval var will not be ranked first of all currently unranked interval ...
Local Search Filters are used for fast neighbor pruning.
Operator which relaxes two sub-chains of three consecutive arcs each.
void SetDurationRange(int64_t mi, int64_t ma)
bool CheckConstraint(Constraint *const ct)
Checks whether adding this constraint will lead to an immediate failure.
int SearchLeftDepth() const
Gets the search left depth of the current active search.
static const char kCardsArgument[]
virtual IntVarIterator * MakeDomainIterator(bool reversible) const =0
Creates a domain iterator.
static const char kGlobalCardinality[]
int64_t PerformedMax() const
void WhenPerformedBound(Solver::Closure closure)
bool IsAssignedStatusKnown(int var_index) const
static const char kIntervalArgument[]
virtual void GetNextSolution(Assignment *const assignment)=0
This method is called when the local search starts a new neighborhood to initialize the default assig...
OptimizationDirection
Optimization directions.
Decision * MakeFailDecision()
virtual void SetPerformed(bool val)=0
DecisionBuilder * Compose(DecisionBuilder *const db1, DecisionBuilder *const db2)
Creates a decision builder which sequentially composes decision builders.
SolutionCollector * MakeAllSolutionCollector()
Collect all solutions of the search.
static const char kInt64ToBoolExtension[]
DELAYED_PRIORITY is the lowest priority: Demons will be processed after VAR_PRIORITY and NORMAL_PRIOR...
static const char kIsMember[]
static const char kNotMember[]
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].
IntExpr * MakeSum(IntExpr *const left, IntExpr *const right)
left + right.
int64_t EndMax(const IntervalVar *const var) const
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).
void set_fail_intercept(std::function< void()> fail_intercept)
Internal.
bool operator==(const SequenceVarElement &element) const
virtual bool IsVar() const
Returns true if the expression is indeed a variable.
CastConstraint(Solver *const solver, IntVar *const target_var)
The default behavior is CHOOSE_FIRST_UNBOUND.
static const char kConvexPiecewise[]
t starts after d, i.e. Start(t) >= d.
void WhenDomain(Solver::Closure closure)
This method attaches a closure that will watch any domain modification of the domain of the variable.
SolverState
This enum represents the state of the solver w.r.t. the search.
RegularLimitParameters MakeDefaultRegularLimitParameters() const
Creates a regular limit proto containing default values.
virtual void EndInitialPropagation()
After the initial propagation.
std::string LocalSearchProfile() const
Returns local search profiling information in a human readable format.
virtual int64_t Max() const =0
bool operator<(const SolutionData &other) const
Operator which inserts an inactive node into a path.
void AddObjective(IntVar *const objective)
LocalSearchOperator * MakeOperator(const std::vector< IntVar * > &vars, LocalSearchOperators op)
Local Search Operators.
IntVarLocalSearchFilter * MakeSumObjectiveFilter(const std::vector< IntVar * > &vars, IndexEvaluator2 values, Solver::LocalSearchFilterBound filter_enum)
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given visitor.
static const char kLess[]
virtual int64_t StartMin() const =0
These methods query, set, and watch the start position of the interval var.
static const char kMapDomain[]
int index() const
Returns the index of the variable.
#define DCHECK_LT(val1, val2)
static const char kRelaxedMinOperation[]
void Incr(Solver *const s, int index)
void SetBackwardSequence(const SequenceVar *const var, const std::vector< int > &backward_sequence)
~DecisionVisitor() override
bool Bound(const IntVar *const var) const
void SetPerformedMin(int64_t m)
virtual void RemoveInterval(int64_t l, int64_t u)=0
This method removes the interval 'l' .
static const char kMaximizeArgument[]
E * FastAdd(V *var)
Adds element without checking its presence in the container.
int64_t best() const
Returns the best value found during search.
static const char kPositionXArgument[]
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
EvaluatorStrategy
This enum is used by Solver::MakePhase to specify how to select variables and values during the searc...
Constraint * MakeIndexOfConstraint(const std::vector< IntVar * > &vars, IntVar *const index, int64_t target)
This constraint is a special case of the element constraint with an array of integer variables,...
IntVar * Objective() const
std::vector< Assignment * > recycle_solutions_
IntVar * MakeBoolVar()
MakeBoolVar will create a variable with a {0, 1} domain.
DecisionBuilder * MakeSolveOnce(DecisionBuilder *const db)
SolveOnce will collapse a search tree described by a decision builder 'db' and a set of monitors and ...
SolutionPool * MakeDefaultSolutionPool()
Solution Pool.
This struct holds all parameters for the default search.
SearchMonitor * MakeExitSearchCallback(std::function< void()> callback)
int64_t StartValue() const
static const char kDurationMinArgument[]
This class is the root class of all solution collectors.
static const char kPositionYArgument[]
virtual void VisitIntegerExpressionArgument(const std::string &arg_name, IntExpr *const argument)
Visit integer expression argument.
std::string DebugString() const override
Pretty Print.
Decision * MakeSplitVariableDomain(IntVar *const var, int64_t val, bool start_with_lower_half)
IntervalVar * MakeIntervalRelaxedMax(IntervalVar *const interval_var)
Creates and returns an interval variable that wraps around the given one, relaxing the max start and ...
void SetEndMax(int64_t m)
void LoadFromProto(const IntervalVarAssignment &interval_var_assignment_proto)
Decision * balancing_decision() const
virtual IntExpr * SafeStartExpr(int64_t unperformed_value)=0
These methods create expressions encapsulating the start, end and duration of the interval var.
static const char kInt64ToInt64Extension[]
std::function< void()> Closure
static const char kScalProdLessOrEqual[]
static const char kSolutionLimitArgument[]
static const char kVariableUsageLessConstantExtension[]
virtual bool SyncNeeded(Assignment *const local_assignment)=0
This method checks if the local solution needs to be updated with an external one.