68 #ifndef OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
69 #define OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
83 #include "absl/base/log_severity.h"
84 #include "absl/container/flat_hash_map.h"
85 #include "absl/container/flat_hash_set.h"
86 #include "absl/flags/declare.h"
87 #include "absl/flags/flag.h"
88 #include "absl/random/random.h"
89 #include "absl/strings/str_format.h"
90 #include "absl/time/time.h"
111 class AssignmentProto;
113 class CastConstraint;
116 class DecisionBuilder;
117 class DecisionVisitor;
121 class DisjunctiveConstraint;
122 class ImprovementSearchLimit;
125 class IntVarAssignment;
126 class IntVarLocalSearchFilter;
128 class IntervalVarAssignment;
129 class LocalSearchFilter;
130 class LocalSearchFilterManager;
131 class LocalSearchMonitor;
132 class LocalSearchOperator;
133 class LocalSearchPhaseParameters;
134 class LocalSearchProfiler;
139 class PropagationBaseObject;
140 class PropagationMonitor;
143 class RegularLimitParameters;
149 class SequenceVarAssignment;
150 class SolutionCollector;
152 class SymmetryBreaker;
159 return absl::GetFlag(FLAGS_cp_random_seed) == -1
160 ? absl::Uniform<int64_t>(absl::BitGen(), 0,
kint64max)
161 : absl::GetFlag(FLAGS_cp_random_seed);
741 typedef std::function<int64_t(
Solver* solver,
742 const std::vector<IntVar*>& vars,
743 int64_t first_unbound, int64_t last_unbound)>
746 typedef std::function<int64_t(
const IntVar* v, int64_t
id)>
748 typedef std::function<bool(int64_t, int64_t, int64_t)>
761 ConstraintSolverParameters
parameters()
const {
return parameters_; }
773 InternalSaveValue(o);
788 template <
typename T>
790 return reinterpret_cast<T*
>(SafeRevAlloc(
object));
799 template <
typename T>
801 return reinterpret_cast<T*
>(SafeRevAllocArray(
object));
886 const std::vector<SearchMonitor*>& monitors);
908 const std::vector<SearchMonitor*>& monitors);
933 const std::vector<SearchMonitor*>& monitors);
973 absl::Time
Now()
const;
1005 uint64_t
stamp()
const;
1012 return optimization_direction_;
1015 optimization_direction_ = direction;
1031 const std::string&
name);
1061 const std::string&
name, std::vector<IntVar*>* vars);
1065 std::vector<IntVar*>* vars);
1068 const std::string&
name);
1074 std::vector<IntVar*>* vars);
1092 const std::vector<int64_t>& coefs);
1095 const std::vector<int>& coefs);
1148 int64_t range_end,
IntVar* argument);
1159 IntVar*
const target_var);
1181 int64_t early_date, int64_t late_date,
1207 int64_t unperformed_value);
1334 const std::vector<int64_t>& coeffs,
1337 const std::vector<int>& coeffs,
1403 const std::vector<int64_t>& values);
1408 const std::vector<int64_t>& values);
1410 const std::vector<int>& values);
1414 std::vector<int64_t> ends);
1417 std::vector<int> ends);
1426 const std::vector<int64_t>& values,
1429 const std::vector<int>& values,
1432 const std::vector<int64_t>& values);
1443 IntVar*
const max_count);
1447 const std::vector<int64_t>& values,
1448 const std::vector<IntVar*>& cards);
1451 const std::vector<int>& values,
1452 const std::vector<IntVar*>& cards);
1455 const std::vector<IntVar*>& cards);
1459 int64_t card_max, int64_t card_size);
1464 const std::vector<int64_t>& card_min,
1465 const std::vector<int64_t>& card_max);
1470 const std::vector<int>& card_min,
1471 const std::vector<int>& card_max);
1476 const std::vector<int64_t>& values,
1477 const std::vector<int64_t>& card_min,
1478 const std::vector<int64_t>& card_max);
1483 const std::vector<int>& values,
1484 const std::vector<int>& card_min,
1485 const std::vector<int>& card_max);
1492 IntVar*
const deviation_var, int64_t total_sum);
1502 bool stronger_propagation);
1507 int64_t escape_value);
1526 const std::vector<IntVar*>& sorted);
1534 const std::vector<IntVar*>& right);
1539 const std::vector<IntVar*>& right);
1546 const std::vector<IntVar*>& left,
const std::vector<IntVar*>& right);
1563 const std::vector<IntVar*>& second_vars);
1571 const std::vector<IntVar*>& second_vars,
1572 int64_t escape_value);
1587 const std::vector<IntVar*>& active,
1590 const std::vector<IntVar*>& active,
1605 const std::vector<IntVar*>& active,
1606 const std::vector<IntVar*>& cumuls,
1607 const std::vector<IntVar*>& transits);
1612 const std::vector<IntVar*>& active,
1613 const std::vector<IntVar*>& cumuls,
1614 const std::vector<IntVar*>& transits);
1622 const std::vector<IntVar*>& active,
1623 const std::vector<IntVar*>& cumuls,
1633 const std::vector<IntVar*>& active,
1634 const std::vector<IntVar*>& cumuls,
1635 const std::vector<IntVar*>& slacks,
1642 std::vector<int64_t> sources,
1643 std::vector<int64_t> sinks,
1644 std::vector<IntVar*> status);
1652 std::vector<IntVar*> nexts,
1653 const std::vector<std::pair<int, int>>& precedences);
1663 std::vector<IntVar*> nexts,
1664 const std::vector<std::pair<int, int>>& precedences,
1665 const std::vector<int>& lifo_path_starts,
1666 const std::vector<int>& fifo_path_starts);
1670 std::vector<IntVar*> nexts, std::vector<IntVar*> transits,
1671 const std::vector<std::pair<int, int>>& precedences);
1676 Constraint* MakeMapDomain(IntVar* const var,
1677 const std::vector<IntVar*>& actives);
1694 const std::vector<IntVar*>& vars,
const IntTupleSet& transition_table,
1695 int64_t initial_state,
const std::vector<int64_t>& final_states);
1706 int64_t initial_state,
1707 const std::vector<int>& final_states);
1709 #if defined(SWIGPYTHON)
1712 const std::vector<IntVar*>& vars,
1713 const std::vector<std::vector<int64_t> >& raw_tuples) {
1715 tuples.InsertAll(raw_tuples);
1720 const std::vector<IntVar*>& vars,
1721 const std::vector<std::vector<int64_t> >&
1723 int64_t initial_state,
const std::vector<int>& final_states) {
1724 IntTupleSet transitions(3);
1725 transitions.InsertAll(raw_transitions);
1740 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1741 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1743 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1744 const std::vector<int64_t>& x_size,
const std::vector<int64_t>& y_size);
1746 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1747 const std::vector<int>& x_size,
const std::vector<int>& y_size);
1758 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1759 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1761 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1762 const std::vector<int64_t>& x_size,
const std::vector<int64_t>& y_size);
1764 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1765 const std::vector<int>& x_size,
const std::vector<int>& y_size);
1772 Pack*
MakePack(
const std::vector<IntVar*>& vars,
int number_of_bins);
1781 const std::string&
name);
1787 bool optional,
const std::string&
name,
1788 std::vector<IntervalVar*>*
const array);
1794 const std::string&
name);
1800 IntVar*
const performed_variable,
1801 const std::string&
name);
1806 const std::vector<IntVar*>& start_variables, int64_t duration,
1807 const std::string&
name, std::vector<IntervalVar*>*
const array);
1812 const std::vector<IntVar*>& start_variables,
1813 const std::vector<int64_t>& durations,
const std::string&
name,
1814 std::vector<IntervalVar*>*
const array);
1818 const std::vector<IntVar*>& start_variables,
1819 const std::vector<int>& durations,
const std::string&
name,
1820 std::vector<IntervalVar*>*
const array);
1825 const std::vector<IntVar*>& start_variables,
1826 const std::vector<int64_t>& durations,
1827 const std::vector<IntVar*>& performed_variables,
const std::string&
name,
1828 std::vector<IntervalVar*>*
const array);
1833 const std::vector<IntVar*>& start_variables,
1834 const std::vector<int>& durations,
1835 const std::vector<IntVar*>& performed_variables,
const std::string&
name,
1836 std::vector<IntervalVar*>*
const array);
1840 const std::string&
name);
1845 int64_t duration_min, int64_t duration_max,
1847 const std::string&
name);
1852 int64_t duration_min, int64_t duration_max,
1854 const std::string&
name,
1855 std::vector<IntervalVar*>*
const array);
1866 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1873 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1880 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1887 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1935 IntervalVar*
const t2);
1943 IntervalVar*
const t2,
1950 IntervalVar*
const t2,
IntVar*
const alt);
1955 IntervalVar*
const t2);
1960 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
1966 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
1978 const std::vector<int64_t>& demands,
1991 const std::vector<int>& demands, int64_t
capacity,
1992 const std::string&
name);
2004 const std::vector<int64_t>& demands,
2017 const std::vector<int>& demands,
2028 const std::vector<IntVar*>& demands,
2039 const std::vector<IntVar*>& demands,
2048 IntervalVar*
const target_var);
2061 const Assignment*
const assignment);
2068 const Assignment*
const assignment);
2078 const Assignment*
const assignment,
bool maximize);
2090 const Assignment*
const assignment,
int solution_count,
bool maximize);
2096 const Assignment*
const assignment);
2113 const std::vector<int64_t>& weights,
2119 const std::vector<int>& weights,
2124 const std::vector<int64_t>& weights,
2129 const std::vector<int>& weights,
2134 const std::vector<IntVar*>& sub_objectives,
2135 const std::vector<int64_t>& weights,
2140 const std::vector<IntVar*>& sub_objectives,
2141 const std::vector<int>& weights,
2163 const std::vector<IntVar*>& vars,
2164 int64_t keep_tenure, int64_t forbid_tenure,
2165 double tabu_factor);
2171 const std::vector<IntVar*>& tabu_vars,
2172 int64_t forbid_tenure);
2178 int64_t initial_temperature);
2185 const std::vector<IntVar*>& vars,
2186 double penalty_factor);
2188 bool maximize,
IntVar*
const objective,
2190 const std::vector<IntVar*>& vars,
2191 const std::vector<IntVar*>& secondary_vars,
double penalty_factor);
2205 ABSL_DEPRECATED(
"Use the version taking absl::Duration() as argument")
2209 ? absl::InfiniteDuration()
2210 : absl::Milliseconds(time_in_ms));
2231 bool smart_time_check =
false,
2232 bool cumulative =
false);
2237 ABSL_DEPRECATED(
"Use other MakeLimit() versions")
2240 int64_t
solutions,
bool smart_time_check =
false,
2241 bool cumulative =
false);
2257 IntVar* objective_var,
bool maximize,
double objective_scaling_factor,
2258 double objective_offset,
double improvement_rate_coefficient,
2259 int improvement_rate_solutions_distance);
2277 std::function<std::string()> display_callback);
2282 std::function<std::string()> display_callback);
2291 std::function<std::string()> display_callback);
2333 absl::flat_hash_map<const IntVar*, int>*
const map);
2338 const std::vector<SymmetryBreaker*>& visitors);
2355 bool start_with_lower_half);
2360 const std::vector<int64_t>& values);
2461 int64_t*
const marker);
2469 int64_t*
const marker);
2509 const std::vector<IntVar*>& vars);
2535 const std::vector<SearchMonitor*>& monitors);
2571 int64_t step,
const std::vector<SearchMonitor*>& monitors);
2585 const std::vector<IntVar*>& secondary_vars,
2593 const std::vector<IntVar*>& secondary_vars,
2605 int number_of_variables);
2607 int number_of_variables,
2624 const std::vector<IntVar*>& variables,
2625 const std::vector<int64_t>& target_values);
2658 const std::vector<LocalSearchOperator*>& ops);
2660 const std::vector<LocalSearchOperator*>& ops,
bool restart);
2662 const std::vector<LocalSearchOperator*>& ops,
2663 std::function<int64_t(
int,
int)> evaluator);
2667 const std::vector<LocalSearchOperator*>& ops);
2673 const std::vector<LocalSearchOperator*>& ops, int32_t seed);
2683 const std::vector<LocalSearchOperator*>& ops,
double memory_coefficient,
2684 double exploration_coefficient,
bool maximize);
2725 const std::vector<IntVar*>& vars,
DecisionBuilder*
const first_solution,
2729 const std::vector<IntVar*>& vars,
DecisionBuilder*
const first_solution,
2733 const std::vector<SequenceVar*>& vars,
2774 const std::vector<IntVar*>& vars,
2814 InternalSaveValue(adr);
2823 InternalSaveValue(adr);
2831 return absl::Uniform<int64_t>(random_, 0, size);
2837 return absl::Uniform<int32_t>(random_, 0, size);
2841 void ReSeed(int32_t seed) { random_.seed(seed); }
2876 fail_intercept_ = std::move(fail_intercept);
2886 use_fast_local_search_ = use_fast_local_search;
2959 template <
class K,
class V>
2967 bool* is_negated)
const;
2989 if (!should_fail_)
return;
2990 should_fail_ =
false;
2998 void PushSentinel(
int magic_code);
2999 void BacktrackToSentinel(
int magic_code);
3000 void ProcessConstraints();
3001 bool BacktrackOneLevel(
Decision** fail_decision);
3002 void JumpToSentinelWhenNested();
3003 void JumpToSentinel();
3004 void check_alloc_state();
3006 void EnqueueVar(
Demon*
const d);
3007 void EnqueueDelayedDemon(
Demon*
const d);
3010 void UnfreezeQueue();
3011 void reset_action_on_fail();
3012 void set_action_on_fail(
Action a);
3013 void set_variable_to_clean_on_fail(
IntVar* v);
3014 void IncrementUncheckedSolutionCounter();
3015 bool IsUncheckedSolutionLimitReached();
3017 void InternalSaveValue(
int* valptr);
3018 void InternalSaveValue(int64_t* valptr);
3019 void InternalSaveValue(uint64_t* valptr);
3020 void InternalSaveValue(
double* valptr);
3021 void InternalSaveValue(
bool* valptr);
3022 void InternalSaveValue(
void** valptr);
3023 void InternalSaveValue(int64_t** valptr) {
3024 InternalSaveValue(
reinterpret_cast<void**
>(valptr));
3027 BaseObject* SafeRevAlloc(BaseObject* ptr);
3029 int* SafeRevAllocArray(
int* ptr);
3030 int64_t* SafeRevAllocArray(int64_t* ptr);
3031 uint64_t* SafeRevAllocArray(uint64_t* ptr);
3032 double* SafeRevAllocArray(
double* ptr);
3033 BaseObject** SafeRevAllocArray(BaseObject** ptr);
3035 IntExpr** SafeRevAllocArray(IntExpr** ptr);
3039 void* UnsafeRevAllocAux(
void* ptr);
3041 T* UnsafeRevAlloc(T* ptr) {
3042 return reinterpret_cast<T*
>(
3043 UnsafeRevAllocAux(
reinterpret_cast<void*
>(ptr)));
3045 void** UnsafeRevAllocArrayAux(
void** ptr);
3047 T** UnsafeRevAllocArray(T** ptr) {
3048 return reinterpret_cast<T**
>(
3049 UnsafeRevAllocArrayAux(
reinterpret_cast<void**
>(ptr)));
3052 void InitCachedIntConstants();
3053 void InitCachedConstraint();
3058 Search* TopLevelSearch()
const {
return searches_.at(1); }
3062 Search* ParentSearch()
const {
3063 const size_t search_size = searches_.size();
3065 return searches_[search_size - 2];
3074 int GetNewIntVarIndex() {
return num_int_vars_++; }
3077 bool IsADifference(IntExpr* expr, IntExpr**
const left,
3078 IntExpr**
const right);
3080 const std::string name_;
3081 const ConstraintSolverParameters parameters_;
3082 absl::flat_hash_map<const PropagationBaseObject*, std::string>
3083 propagation_object_names_;
3084 absl::flat_hash_map<const PropagationBaseObject*, IntegerCastInfo>
3086 absl::flat_hash_set<const Constraint*> cast_constraints_;
3087 const std::string empty_name_;
3088 std::unique_ptr<Queue> queue_;
3089 std::unique_ptr<Trail> trail_;
3090 std::vector<Constraint*> constraints_list_;
3091 std::vector<Constraint*> additional_constraints_list_;
3092 std::vector<int> additional_constraints_parent_list_;
3099 int64_t filtered_neighbors_;
3100 int64_t accepted_neighbors_;
3102 std::unique_ptr<ClockTimer> timer_;
3103 std::vector<Search*> searches_;
3104 std::mt19937 random_;
3105 uint64_t fail_stamp_;
3106 std::unique_ptr<Decision> balancing_decision_;
3108 std::function<void()> fail_intercept_;
3112 bool use_fast_local_search_;
3116 std::unique_ptr<Assignment> local_search_state_;
3119 enum { MIN_CACHED_INT_CONST = -8, MAX_CACHED_INT_CONST = 8 };
3120 IntVar* cached_constants_[MAX_CACHED_INT_CONST + 1 - MIN_CACHED_INT_CONST];
3126 std::unique_ptr<Decision> fail_decision_;
3127 int constraint_index_;
3128 int additional_constraint_index_;
3131 std::unique_ptr<ModelCache> model_cache_;
3132 std::unique_ptr<PropagationMonitor> propagation_monitor_;
3133 PropagationMonitor* print_trace_;
3134 std::unique_ptr<LocalSearchMonitor> local_search_monitor_;
3135 int anonymous_variable_index_;
3141 std::ostream&
operator<<(std::ostream& out,
const Solver*
const s);
3146 inline int64_t
Zero() {
return 0; }
3149 inline int64_t
One() {
return 1; }
3164 std::ostream&
operator<<(std::ostream& out,
const BaseObject* o);
3175 if (
name().empty()) {
3176 return "PropagationBaseObject";
3178 return absl::StrFormat(
"PropagationBaseObject: %s",
name());
3203 solver_->set_action_on_fail(std::move(
a));
3212 solver_->set_variable_to_clean_on_fail(v);
3216 virtual std::string
name()
const;
3221 virtual std::string
BaseName()
const;
3246 DISALLOW_COPY_AND_ASSIGN(
Decision);
3257 bool start_with_lower_half);
3286 std::vector<SearchMonitor*>*
const extras);
3329 void set_stamp(int64_t stamp) {
stamp_ = stamp; }
3330 uint64_t stamp()
const {
return stamp_; }
3530 const std::string& operation, int64_t
value,
3533 const std::string& operation,
3541 const std::vector<int64_t>& values);
3550 const std::string& arg_name,
const std::vector<IntVar*>& arguments);
3557 const std::string& arg_name,
const std::vector<IntervalVar*>& arguments);
3563 const std::string& arg_name,
const std::vector<SequenceVar*>& arguments);
3574 int64_t index_min, int64_t index_max);
3577 const std::string& arg_name, int64_t index_max);
3740 explicit Rev(
const T& val) : stamp_(0), value_(val) {}
3742 const T&
Value()
const {
return value_; }
3745 if (val != value_) {
3746 if (stamp_ < s->stamp()) {
3748 stamp_ = s->
stamp();
3783 : stamps_(new uint64_t[
size]), values_(new T[
size]), size_(
size) {
3784 for (
int i = 0; i <
size; ++i) {
3792 int64_t
size()
const {
return size_; }
3802 if (val != values_[
index]) {
3807 values_[
index] = val;
3812 std::unique_ptr<uint64_t[]> stamps_;
3813 std::unique_ptr<T[]> values_;
3844 virtual int64_t
Min()
const = 0;
3846 virtual int64_t
Max()
const = 0;
3851 virtual void Range(int64_t* l, int64_t* u) {
3868 virtual bool IsVar()
const {
return false; }
3897 DISALLOW_COPY_AND_ASSIGN(
IntExpr);
3925 virtual bool Ok()
const = 0;
3934 std::string
DebugString()
const override {
return "IntVar::Iterator"; }
3947 : it_(it), begin_was_called_(false) {
3954 DCHECK(!begin_was_called_);
3955 begin_was_called_ =
true;
3972 return it_->
Value();
3980 DCHECK(other.it_ == it_);
3993 IntVarIterator*
const it_;
3994 bool begin_was_called_;
4007 bool IsVar()
const override {
return true; }
4022 virtual void RemoveValues(
const std::vector<int64_t>& values);
4025 virtual void SetValues(
const std::vector<int64_t>& values);
4099 DISALLOW_COPY_AND_ASSIGN(
IntVar);
4110 std::string
DebugString()
const override {
return "SolutionCollector"; }
4114 void Add(
const std::vector<IntVar*>& vars);
4116 void Add(
const std::vector<IntervalVar*>& vars);
4118 void Add(
const std::vector<SequenceVar*>& vars);
4225 virtual std::string
Print()
const;
4273 return absl::StrFormat(
"SearchLimit(crossed = %i)", crossed_);
4277 void TopPeriodicCheck();
4294 bool Check()
override;
4295 void Init()
override;
4301 return duration_limit_ == absl::InfiniteDuration()
4313 return solver_time_at_limit_start_ + duration_limit_;
4320 absl::Duration TimeElapsed();
4321 static int64_t GetPercent(int64_t
value, int64_t offset, int64_t total) {
4322 return (total > 0 && total <
kint64max) ? 100 * (
value - offset) / total
4326 absl::Duration duration_limit_;
4327 absl::Time solver_time_at_limit_start_;
4328 absl::Duration last_time_elapsed_;
4329 int64_t check_count_;
4330 int64_t next_check_;
4331 bool smart_time_check_;
4333 int64_t branches_offset_;
4335 int64_t failures_offset_;
4337 int64_t solutions_offset_;
4360 double objective_scaling_factor,
4361 double objective_offset,
4362 double improvement_rate_coefficient,
4363 int improvement_rate_solutions_distance);
4367 bool Check()
override;
4369 void Init()
override;
4374 double objective_scaling_factor_;
4375 double objective_offset_;
4376 double improvement_rate_coefficient_;
4377 int improvement_rate_solutions_distance_;
4379 double best_objective_;
4381 std::deque<std::pair<double, int64_t> > improvements_;
4384 bool objective_updated_;
4385 bool gradient_stage_;
4555 const std::vector<IntVar*>& nexts,
const std::string&
name);
4564 void DurationRange(int64_t*
const dmin, int64_t*
const dmax)
const;
4568 void HorizonRange(int64_t*
const hmin, int64_t*
const hmax)
const;
4576 int*
const unperformed)
const;
4598 std::vector<int>*
const possible_lasts);
4606 const std::vector<int>& rank_last,
4607 const std::vector<int>& unperformed);
4618 std::vector<int>*
const rank_last,
4619 std::vector<int>*
const unperformed)
const;
4628 int64_t
size()
const {
return intervals_.size(); }
4634 int ComputeForwardFrontier();
4635 int ComputeBackwardFrontier();
4636 void UpdatePrevious()
const;
4638 const std::vector<IntervalVar*> intervals_;
4639 const std::vector<IntVar*> nexts_;
4640 mutable std::vector<int> previous_;
4668 if (var_ !=
nullptr) {
4672 void LoadFromProto(
const IntVarAssignment& int_var_assignment_proto);
4673 void WriteToProto(IntVarAssignment* int_var_assignment_proto)
const;
4675 int64_t
Min()
const {
return min_; }
4677 int64_t
Max()
const {
return max_; }
4684 bool Bound()
const {
return (max_ == min_); }
4697 return !(*
this == element);
4717 const IntervalVarAssignment& interval_var_assignment_proto);
4718 void WriteToProto(IntervalVarAssignment* interval_var_assignment_proto)
const;
4729 CHECK_EQ(duration_max_, duration_min_);
4730 return duration_max_;
4741 CHECK_EQ(performed_max_, performed_min_);
4742 return performed_max_;
4777 performed_min_ = mi;
4778 performed_max_ = ma;
4785 return (start_min_ == start_max_ && duration_min_ == duration_max_ &&
4786 end_min_ == end_max_ && performed_min_ == performed_max_);
4791 return !(*
this == element);
4797 int64_t duration_min_;
4798 int64_t duration_max_;
4801 int64_t performed_min_;
4802 int64_t performed_max_;
4830 const SequenceVarAssignment& sequence_var_assignment_proto);
4831 void WriteToProto(SequenceVarAssignment* sequence_var_assignment_proto)
const;
4836 void SetSequence(
const std::vector<int>& forward_sequence,
4837 const std::vector<int>& backward_sequence,
4838 const std::vector<int>& unperformed);
4843 return forward_sequence_.size() + unperformed_.size() == var_->
size();
4850 return !(*
this == element);
4854 bool CheckClassInvariants();
4857 std::vector<int> forward_sequence_;
4858 std::vector<int> backward_sequence_;
4859 std::vector<int> unperformed_;
4862 template <
class V,
class E>
4872 return &elements_[
index];
4878 elements_.emplace_back(
var);
4879 return &elements_.back();
4884 elements_[position].Reset(
var);
4885 return &elements_[position];
4889 if (!elements_map_.empty()) {
4890 elements_map_.clear();
4895 void Resize(
size_t size) { elements_.resize(size); }
4896 bool Empty()
const {
return elements_.empty(); }
4900 for (
int i = 0; i < container.elements_.size(); ++i) {
4901 const E& element = container.elements_[i];
4902 const V*
const var = element.Var();
4904 if (i < elements_.size() && elements_[i].Var() ==
var) {
4910 E*
const local_element = &elements_[
index];
4911 local_element->Copy(element);
4912 if (element.Activated()) {
4913 local_element->Activate();
4915 local_element->Deactivate();
4923 for (
int i = 0; i < container.elements_.size(); ++i) {
4924 const E& element = container.elements_[i];
4925 FastAdd(element.Var())->Copy(element);
4934 DCHECK(element !=
nullptr)
4935 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
4947 DCHECK(element !=
nullptr)
4948 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
4958 const std::vector<E>&
elements()
const {
return elements_; }
4961 int Size()
const {
return elements_.size(); }
4963 for (E& element : elements_) {
4968 for (E& element : elements_) {
4969 if (element.Activated()) {
4975 for (
const E& element : elements_) {
4976 if (!element.Bound())
return false;
4990 EnsureMapIsUpToDate();
4994 for (
const E& element : container.elements_) {
4995 const int position =
4997 if (position < 0 || elements_[position] != element) {
5004 return !(*
this == container);
5008 void EnsureMapIsUpToDate()
const {
5009 absl::flat_hash_map<const V*, int>* map =
5010 const_cast<absl::flat_hash_map<const V*, int>*
>(&elements_map_);
5011 for (
int i = map->size(); i < elements_.size(); ++i) {
5012 (*map)[elements_[i].Var()] = i;
5015 bool Find(
const V*
const var,
int*
index)
const {
5017 const size_t kMaxSizeForLinearAccess = 11;
5018 if (
Size() <= kMaxSizeForLinearAccess) {
5022 for (
int i = 0; i < elements_.size(); ++i) {
5023 if (
var == elements_[i].Var()) {
5030 EnsureMapIsUpToDate();
5031 DCHECK_EQ(elements_map_.size(), elements_.size());
5036 std::vector<E> elements_;
5037 absl::flat_hash_map<const V*, int> elements_map_;
5056 return int_var_container_.
Empty() && interval_var_container_.
Empty() &&
5057 sequence_var_container_.
Empty();
5070 bool Load(
const std::string& filename);
5074 void Load(
const AssignmentProto& assignment_proto);
5076 bool Save(
const std::string& filename)
const;
5080 void Save(AssignmentProto*
const assignment_proto)
const;
5096 void Add(
const std::vector<IntVar*>& vars);
5109 void Add(
const std::vector<IntervalVar*>& vars);
5142 void Add(
const std::vector<SequenceVar*>& vars);
5149 const std::vector<int>& forward_sequence,
5150 const std::vector<int>& backward_sequence,
5151 const std::vector<int>& unperformed);
5153 const std::vector<int>& forward_sequence);
5155 const std::vector<int>& backward_sequence);
5157 const std::vector<int>& unperformed);
5196 return interval_var_container_;
5199 return &interval_var_container_;
5202 return sequence_var_container_;
5205 return &sequence_var_container_;
5208 return int_var_container_ == assignment.int_var_container_ &&
5209 interval_var_container_ == assignment.interval_var_container_ &&
5210 sequence_var_container_ == assignment.sequence_var_container_ &&
5211 objective_element_ == assignment.objective_element_;
5214 return !(*
this == assignment);
5226 const Assignment& assignment);
5234 const std::vector<IntVar*>& target_vars,
5235 const Assignment* source_assignment,
5236 const std::vector<IntVar*>& source_vars);
5240 Pack(
Solver*
const s,
const std::vector<IntVar*>& vars,
int number_of_bins);
5253 const std::vector<int64_t>& weights,
const std::vector<int64_t>&
bounds);
5272 const std::vector<IntVar*>& loads);
5278 const std::vector<IntVar*>& loads);
5290 const std::vector<IntVar*>& usage,
const std::vector<int64_t>&
capacity);
5305 void Post()
override;
5312 bool IsUndecided(
int var_index,
int bin_index)
const;
5314 void Assign(
int var_index,
int bin_index);
5316 bool IsPossible(
int var_index,
int bin_index)
const;
5328 bool IsInProcess()
const;
5329 const std::vector<IntVar*> vars_;
5331 std::vector<Dimension*> dims_;
5332 std::unique_ptr<RevBitMatrix> unprocessed_;
5333 std::vector<std::vector<int>> forced_;
5334 std::vector<std::vector<int>> removed_;
5335 std::vector<IntVarIterator*> holes_;
5338 std::vector<std::pair<int, int>> to_set_;
5339 std::vector<std::pair<int, int>> to_unset_;
5346 const std::vector<IntervalVar*>& intervals,
5347 const std::string&
name);
5365 virtual const std::vector<IntVar*>&
nexts()
const = 0;
5366 virtual const std::vector<IntVar*>&
actives()
const = 0;
#define CHECK_EQ(val1, val2)
#define DCHECK_GE(val1, val2)
#define DCHECK_GT(val1, val2)
#define DCHECK_LT(val1, val2)
#define DCHECK(condition)
#define DCHECK_EQ(val1, val2)
bool AreAllElementsBound() const
E * MutableElement(const V *const var)
E * MutableElementOrNull(const V *const var)
bool operator==(const AssignmentContainer< V, E > &container) const
Returns true if this and 'container' both represent the same V* -> E map.
const E * ElementPtrOrNull(const V *const var) const
const std::vector< E > & elements() const
bool Contains(const V *const var) const
E * AddAtPosition(V *var, int position)
Advanced usage: Adds element at a given position; position has to have been allocated with Assignment...
const E & Element(int index) const
void Copy(const AssignmentContainer< V, E > &container)
Copies all the elements of 'container' to this container, clearing its previous content.
bool operator!=(const AssignmentContainer< V, E > &container) const
E * MutableElement(int index)
const E & Element(const V *const var) const
void CopyIntersection(const AssignmentContainer< V, E > &container)
Copies the elements of 'container' which are already in the calling container.
void Resize(size_t size)
Advanced usage: Resizes the container, potentially adding elements with null variables.
E * FastAdd(V *var)
Adds element without checking its presence in the container.
An Assignment is a variable -> domains mapping, used to report solutions to the user.
bool ActivatedObjective() const
const std::vector< int > & Unperformed(const SequenceVar *const var) const
void SetForwardSequence(const SequenceVar *const var, const std::vector< int > &forward_sequence)
void SetStartRange(const IntervalVar *const var, int64_t mi, int64_t ma)
void Deactivate(const IntVar *const var)
IntContainer * MutableIntVarContainer()
int64_t EndMin(const IntervalVar *const var) const
int64_t PerformedMin(const IntervalVar *const var) const
int64_t EndMax(const IntervalVar *const var) const
void SetBackwardSequence(const SequenceVar *const var, const std::vector< int > &backward_sequence)
int64_t StartMax(const IntervalVar *const var) const
const IntContainer & IntVarContainer() const
const std::vector< int > & BackwardSequence(const SequenceVar *const var) const
bool AreAllElementsBound() const
void SetStartMin(const IntervalVar *const var, int64_t m)
int64_t DurationMin(const IntervalVar *const var) const
int64_t EndValue(const IntervalVar *const var) const
int64_t ObjectiveMax() const
Assignment(Solver *const s)
void SetRange(const IntVar *const var, int64_t l, int64_t u)
const SequenceContainer & SequenceVarContainer() const
AssignmentContainer< SequenceVar, SequenceVarElement > SequenceContainer
int NumSequenceVars() const
int64_t StartValue(const IntervalVar *const var) const
void SetObjectiveValue(int64_t value)
IntVar * Objective() const
void SetObjectiveMax(int64_t m)
bool Load(const std::string &filename)
Loads an assignment from a file; does not add variables to the assignment (only the variables contain...
void SetMax(const IntVar *const var, int64_t m)
void SetDurationMin(const IntervalVar *const var, int64_t m)
int64_t PerformedValue(const IntervalVar *const var) const
int64_t DurationMax(const IntervalVar *const var) const
bool Contains(const IntVar *const var) const
void SetEndRange(const IntervalVar *const var, int64_t mi, int64_t ma)
int64_t ObjectiveValue() const
bool Activated(const IntVar *const var) const
bool Save(const std::string &filename) const
Saves the assignment to a file.
void SetPerformedRange(const IntervalVar *const var, int64_t mi, int64_t ma)
int64_t DurationValue(const IntervalVar *const var) const
const std::vector< int > & ForwardSequence(const SequenceVar *const var) const
bool HasObjective() const
void SetDurationRange(const IntervalVar *const var, int64_t mi, int64_t ma)
void AddObjective(IntVar *const v)
void SetEndMin(const IntervalVar *const var, int64_t m)
void SetValue(const IntVar *const var, int64_t value)
void Activate(const IntVar *const var)
void DeactivateObjective()
int64_t ObjectiveMin() const
void SetDurationMax(const IntervalVar *const var, int64_t m)
SequenceContainer * MutableSequenceVarContainer()
int64_t Max(const IntVar *const var) const
int64_t Value(const IntVar *const var) const
void SetStartMax(const IntervalVar *const var, int64_t m)
void SetPerformedMax(const IntervalVar *const var, int64_t m)
IntervalContainer * MutableIntervalVarContainer()
void SetUnperformed(const SequenceVar *const var, const std::vector< int > &unperformed)
void SetObjectiveRange(int64_t l, int64_t u)
void SetMin(const IntVar *const var, int64_t m)
int64_t PerformedMax(const IntervalVar *const var) const
void SetObjectiveMin(int64_t m)
bool operator==(const Assignment &assignment) const
void SetDurationValue(const IntervalVar *const var, int64_t value)
void CopyIntersection(const Assignment *assignment)
Copies the intersection of the two assignments to the current assignment.
int NumIntervalVars() const
void SetEndValue(const IntervalVar *const var, int64_t value)
bool ObjectiveBound() const
AssignmentContainer< IntervalVar, IntervalVarElement > IntervalContainer
void SetStartValue(const IntervalVar *const var, int64_t value)
void SetEndMax(const IntervalVar *const var, int64_t m)
void SetPerformedValue(const IntervalVar *const var, int64_t value)
void SetPerformedMin(const IntervalVar *const var, int64_t m)
void Copy(const Assignment *assignment)
Copies 'assignment' to the current assignment, clearing its previous content.
AssignmentContainer< IntVar, IntVarElement > IntContainer
void SetSequence(const SequenceVar *const var, const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
IntVarElement * Add(IntVar *const var)
const IntervalContainer & IntervalVarContainer() const
bool Bound(const IntVar *const var) const
std::string DebugString() const override
int64_t Min(const IntVar *const var) const
IntVarElement * FastAdd(IntVar *const var)
Adds without checking if variable has been previously added.
int64_t StartMin(const IntervalVar *const var) const
bool operator!=(const Assignment &assignment) const
A BaseObject is the root of all reversibly allocated objects.
virtual std::string DebugString() const
Cast constraints are special channeling constraints designed to keep a variable in sync with an expre...
IntVar * target_var() const
~CastConstraint() override
IntVar *const target_var_
CastConstraint(Solver *const solver, IntVar *const target_var)
A constraint is the main modeling object.
void PostAndPropagate()
Calls Post and then Propagate to initialize the constraints.
bool IsCastConstraint() const
Is the constraint created by a cast from expression to integer variable?
virtual void InitialPropagate()=0
This method performs the initial propagation of the constraint.
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given visitor.
virtual IntVar * Var()
Creates a Boolean variable representing the status of the constraint (false = constraint is violated,...
Constraint(Solver *const solver)
std::string DebugString() const override
virtual void Post()=0
This method is called when the constraint is processed by the solver.
A DecisionBuilder is responsible for creating the search tree.
virtual Decision * Next(Solver *const s)=0
This is the main method of the decision builder class.
virtual void Accept(ModelVisitor *const visitor) const
virtual void AppendMonitors(Solver *const solver, std::vector< SearchMonitor * > *const extras)
This method will be called at the start of the search.
~DecisionBuilder() override
std::string DebugString() const override
A Decision represents a choice point in the search tree.
virtual void Accept(DecisionVisitor *const visitor) const
Accepts the given visitor.
virtual void Apply(Solver *const s)=0
Apply will be called first when the decision is executed.
virtual void Refute(Solver *const s)=0
Refute will be called after a backtrack.
std::string DebugString() const override
A DecisionVisitor is used to inspect a decision.
virtual void VisitSetVariableValue(IntVar *const var, int64_t value)
~DecisionVisitor() override
virtual void VisitSplitVariableDomain(IntVar *const var, int64_t value, bool start_with_lower_half)
virtual void VisitRankFirstInterval(SequenceVar *const sequence, int index)
virtual void VisitUnknownDecision()
virtual void VisitRankLastInterval(SequenceVar *const sequence, int index)
virtual void VisitScheduleOrPostpone(IntervalVar *const var, int64_t est)
virtual void VisitScheduleOrExpedite(IntervalVar *const var, int64_t est)
A Demon is the base element of a propagation queue.
void inhibit(Solver *const s)
This method inhibits the demon in the search tree below the current position.
Demon()
This indicates the priority of a demon.
void desinhibit(Solver *const s)
This method un-inhibits the demon that was previously inhibited.
virtual Solver::DemonPriority priority() const
This method returns the priority of the demon.
std::string DebugString() const override
virtual void Run(Solver *const s)=0
This is the main callback of the demon.
const std::vector< IntervalVar * > intervals_
virtual const std::vector< IntVar * > & time_cumuls() const =0
int64_t TransitionTime(int before_index, int after_index)
virtual const std::vector< IntVar * > & actives() const =0
virtual SequenceVar * MakeSequenceVar()=0
Creates a sequence variable from the constraint.
~DisjunctiveConstraint() override
virtual const std::vector< IntVar * > & nexts() const =0
DisjunctiveConstraint(Solver *const s, const std::vector< IntervalVar * > &intervals, const std::string &name)
void SetTransitionTime(Solver::IndexEvaluator2 transition_time)
Add a transition time between intervals.
virtual const std::vector< IntVar * > & time_slacks() const =0
Solver::IndexEvaluator2 transition_time_
bool Check() override
This method is called to check the status of the limit.
void Init() override
This method is called when the search limit is initialized.
~ImprovementSearchLimit() override
void Copy(const SearchLimit *const limit) override
Copy a limit.
bool AtSolution() override
This method is called when a valid solution is found.
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)
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
Utility class to encapsulate an IntVarIterator and use it in a range-based loop.
InitAndGetValues(IntVarIterator *it)
The class IntExpr is the base of all integer expressions in constraint programming.
virtual IntVar * Var()=0
Creates a variable from the expression.
virtual void SetRange(int64_t l, int64_t u)
This method sets both the min and the max of the expression.
void WhenRange(Solver::Closure closure)
Attach a demon that will watch the min or the max of the expression.
virtual bool Bound() const
Returns true if the min and the max of the expression are equal.
virtual void SetValue(int64_t v)
This method sets the value of the expression.
virtual bool IsVar() const
Returns true if the expression is indeed a variable.
virtual int64_t Min() const =0
virtual void SetMax(int64_t m)=0
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given visitor.
virtual void SetMin(int64_t m)=0
IntVar * VarWithName(const std::string &name)
Creates a variable from the expression and set the name of the resulting var.
virtual int64_t Max() const =0
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.
virtual void WhenRange(Demon *d)=0
Attach a demon that will watch the min or the max of the expression.
void WhenRange(Solver::Action action)
Attach a demon that will watch the min or the max of the expression.
void Copy(const IntVarElement &element)
bool operator!=(const IntVarElement &element) const
void Reset(IntVar *const var)
bool operator==(const IntVarElement &element) const
std::string DebugString() const
void WriteToProto(IntVarAssignment *int_var_assignment_proto) const
void LoadFromProto(const IntVarAssignment &int_var_assignment_proto)
void SetRange(int64_t l, int64_t u)
The class IntVar is a subset of IntExpr.
virtual bool Contains(int64_t v) const =0
This method returns whether the value 'v' is in the domain of the variable.
virtual IntVar * IsDifferent(int64_t constant)=0
virtual int64_t OldMax() const =0
Returns the previous max.
IntVar * Var() override
Creates a variable from the expression.
virtual IntVar * IsGreaterOrEqual(int64_t constant)=0
virtual void RemoveValue(int64_t v)=0
This method removes the value 'v' from the domain of the variable.
void WhenBound(Solver::Closure closure)
This method attaches a closure that will be awakened when the variable is bound.
virtual void WhenBound(Demon *d)=0
This method attaches a demon that will be awakened when the variable is bound.
void WhenDomain(Solver::Closure closure)
This method attaches a closure that will watch any domain modification of the domain of the variable.
virtual IntVarIterator * MakeHoleIterator(bool reversible) const =0
Creates a hole iterator.
virtual IntVar * IsLessOrEqual(int64_t constant)=0
void WhenDomain(Solver::Action action)
This method attaches an action that will watch any domain modification of the domain of the variable.
void Accept(ModelVisitor *const visitor) const override
Accepts the given visitor.
virtual void SetValues(const std::vector< int64_t > &values)
This method intersects the current domain with the values in the array.
virtual IntVarIterator * MakeDomainIterator(bool reversible) const =0
Creates a domain iterator.
virtual void RemoveInterval(int64_t l, int64_t u)=0
This method removes the interval 'l' .
virtual IntVar * IsEqual(int64_t constant)=0
IsEqual.
virtual void WhenDomain(Demon *d)=0
This method attaches a demon that will watch any domain modification of the domain of the variable.
virtual void RemoveValues(const std::vector< int64_t > &values)
This method remove the values from the domain of the variable.
virtual int64_t Value() const =0
This method returns the value of the variable.
int index() const
Returns the index of the variable.
void WhenBound(Solver::Action action)
This method attaches an action that will be awakened when the variable is bound.
virtual int64_t OldMin() const =0
Returns the previous min.
bool IsVar() const override
Returns true if the expression is indeed a variable.
virtual uint64_t Size() const =0
This method returns the number of values in the domain of the variable.
virtual int VarType() const
The class Iterator has two direct subclasses.
virtual void Init()=0
This method must be called before each loop.
virtual void Next()=0
This method moves the iterator to the next value.
virtual int64_t Value() const =0
This method returns the current value of the iterator.
~IntVarIterator() override
std::string DebugString() const override
Pretty Print.
virtual bool Ok() const =0
This method indicates if we can call Value() or not.
IntervalVarElement * Clone()
void LoadFromProto(const IntervalVarAssignment &interval_var_assignment_proto)
int64_t StartValue() const
void SetDurationRange(int64_t mi, int64_t ma)
bool operator!=(const IntervalVarElement &element) const
void Reset(IntervalVar *const var)
int64_t PerformedMax() const
int64_t DurationMax() const
void SetPerformedRange(int64_t mi, int64_t ma)
int64_t DurationMin() const
void SetEndRange(int64_t mi, int64_t ma)
void SetEndValue(int64_t v)
void SetEndMin(int64_t m)
void SetDurationValue(int64_t v)
void SetPerformedMin(int64_t m)
void SetStartRange(int64_t mi, int64_t ma)
void SetDurationMin(int64_t m)
void SetEndMax(int64_t m)
std::string DebugString() const
void SetStartMin(int64_t m)
void SetStartMax(int64_t m)
int64_t PerformedMin() const
void SetPerformedValue(int64_t v)
int64_t PerformedValue() const
bool operator==(const IntervalVarElement &element) const
void Copy(const IntervalVarElement &element)
void WriteToProto(IntervalVarAssignment *interval_var_assignment_proto) const
void SetPerformedMax(int64_t m)
void SetDurationMax(int64_t m)
void SetStartValue(int64_t v)
int64_t DurationValue() const
IntervalVar * Var() const
Interval variables are often used in scheduling.
virtual void SetDurationMin(int64_t m)=0
void WhenDurationRange(Solver::Closure closure)
virtual IntExpr * SafeStartExpr(int64_t unperformed_value)=0
These methods create expressions encapsulating the start, end and duration of the interval var.
void WhenAnything(Solver::Closure closure)
Attaches a closure awakened when anything about this interval changes.
void WhenStartBound(Solver::Closure closure)
virtual int64_t DurationMax() const =0
virtual void WhenStartBound(Demon *const d)=0
virtual void SetEndMax(int64_t m)=0
void WhenEndRange(Solver::Closure closure)
void WhenAnything(Demon *const d)
Attaches a demon awakened when anything about this interval changes.
virtual int64_t DurationMin() const =0
These methods query, set, and watch the duration of the interval var.
virtual void SetPerformed(bool val)=0
virtual void SetDurationMax(int64_t m)=0
void WhenEndBound(Solver::Action action)
virtual void WhenEndRange(Demon *const d)=0
virtual int64_t OldEndMax() const =0
virtual void WhenDurationBound(Demon *const d)=0
virtual bool WasPerformedBound() const =0
virtual void SetStartMax(int64_t m)=0
void WhenStartRange(Solver::Action action)
static const int64_t kMinValidValue
The smallest acceptable value to be returned by StartMin()
virtual void SetStartRange(int64_t mi, int64_t ma)=0
virtual void WhenDurationRange(Demon *const d)=0
virtual IntExpr * SafeEndExpr(int64_t unperformed_value)=0
virtual int64_t OldStartMax() const =0
virtual int64_t OldDurationMin() const =0
static const int64_t kMaxValidValue
The largest acceptable value to be returned by EndMax()
virtual int64_t OldEndMin() const =0
virtual void WhenEndBound(Demon *const d)=0
virtual int64_t OldDurationMax() const =0
virtual void Accept(ModelVisitor *const visitor) const =0
Accepts the given visitor.
void WhenDurationBound(Solver::Action action)
virtual bool MustBePerformed() const =0
These methods query, set, and watch the performed status of the interval var.
IntervalVar(Solver *const solver, const std::string &name)
virtual void WhenPerformedBound(Demon *const d)=0
virtual IntExpr * EndExpr()=0
void WhenStartBound(Solver::Action action)
virtual void SetEndMin(int64_t m)=0
virtual int64_t EndMin() const =0
These methods query, set, and watch the end position of the interval var.
void WhenAnything(Solver::Action action)
Attaches an action awakened when anything about this interval changes.
virtual IntExpr * PerformedExpr()=0
virtual int64_t StartMin() const =0
These methods query, set, and watch the start position of the interval var.
virtual IntExpr * DurationExpr()=0
void WhenEndRange(Solver::Action action)
void WhenStartRange(Solver::Closure closure)
virtual void WhenStartRange(Demon *const d)=0
virtual IntExpr * StartExpr()=0
These methods create expressions encapsulating the start, end and duration of the interval var.
bool IsPerformedBound() const
virtual void SetDurationRange(int64_t mi, int64_t ma)=0
void WhenPerformedBound(Solver::Action action)
virtual int64_t EndMax() const =0
void WhenPerformedBound(Solver::Closure closure)
void WhenEndBound(Solver::Closure closure)
virtual void SetStartMin(int64_t m)=0
virtual bool MayBePerformed() const =0
void WhenDurationRange(Solver::Action action)
bool CannotBePerformed() const
virtual void SetEndRange(int64_t mi, int64_t ma)=0
virtual int64_t OldStartMin() const =0
virtual int64_t StartMax() const =0
virtual IntExpr * SafeDurationExpr(int64_t unperformed_value)=0
void WhenDurationBound(Solver::Closure closure)
Local Search Filters are used for fast neighbor pruning.
Filter manager: when a move is made, filters are executed to decide whether the solution is feasible ...
The base class for all local search operators.
Implements a complete cache for model elements: expressions and constraints.
static const char kDurationMinArgument[]
static const char kIntervalArgument[]
static const char kSolutionLimitArgument[]
static const char kSizeArgument[]
static const char kIsMember[]
static const char kCountUsedBinsExtension[]
static const char kIntervalVariable[]
static const char kObjectiveExtension[]
static const char kPower[]
static const char kEarlyDateArgument[]
static const char kMaximizeArgument[]
static const char kLateDateArgument[]
static const char kFinalStatesArgument[]
static const char kIndex2Argument[]
static const char kStartExpr[]
static const char kMinArgument[]
static const char kEndsArgument[]
virtual void VisitIntegerArgument(const std::string &arg_name, int64_t value)
Visit integer arguments.
static const char kSequenceVariable[]
static const char kDeviation[]
static const char kMirrorOperation[]
Operations.
static const char kAbs[]
Constraint and Expression types.
static const char kMember[]
static const char kDelayedPathCumul[]
virtual void VisitSequenceVariable(const SequenceVar *const variable)
static const char kVariableUsageLessConstantExtension[]
virtual void VisitIntegerVariable(const IntVar *const variable, IntExpr *const delegate)
static const char kSumEqual[]
static const char kSortingConstraint[]
static const char kElementEqual[]
void VisitInt64ToInt64AsArray(const Solver::IndexEvaluator1 &eval, const std::string &arg_name, int64_t index_max)
Expands function as array when index min is 0.
static const char kPack[]
static const char kIsBetween[]
static const char kRangeArgument[]
static const char kLess[]
virtual void VisitIntervalVariable(const IntervalVar *const variable, const std::string &operation, int64_t value, IntervalVar *const delegate)
static const char kAtMost[]
static const char kDisjunctive[]
void VisitInt64ToInt64Extension(const Solver::IndexEvaluator1 &eval, int64_t index_min, int64_t index_max)
static const char kTargetArgument[]
static const char kActiveArgument[]
argument names:
static const char kRelaxedMaxOperation[]
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.
static const char kSequenceArgument[]
static const char kAbsEqual[]
static const char kTimeLimitArgument[]
static const char kIntegerVariable[]
virtual void VisitIntegerArrayArgument(const std::string &arg_name, const std::vector< int64_t > &values)
static const char kNullIntersect[]
virtual void VisitIntervalArgument(const std::string &arg_name, IntervalVar *const argument)
Visit interval argument.
static const char kConvexPiecewise[]
static const char kBranchesLimitArgument[]
static const char kMaxArgument[]
static const char kModulo[]
static const char kCapacityArgument[]
static const char kProductOperation[]
static const char kBetween[]
static const char kIntervalsArgument[]
static const char kIntervalUnaryRelation[]
static const char kScalProd[]
static const char kTrueConstraint[]
static const char kOpposite[]
virtual void BeginVisitIntegerExpression(const std::string &type_name, const IntExpr *const expr)
virtual void EndVisitIntegerExpression(const std::string &type_name, const IntExpr *const expr)
static const char kEvaluatorArgument[]
static const char kPositionXArgument[]
static const char kCumulsArgument[]
static const char kCircuit[]
static const char kWeightedSumOfAssignedEqualVariableExtension[]
virtual void VisitIntegerVariableEvaluatorArgument(const std::string &arg_name, const Solver::Int64ToIntVar &arguments)
Helpers.
static const char kRelaxedMinOperation[]
static const char kMapDomain[]
static const char kLessOrEqual[]
static const char kSizeXArgument[]
static const char kModuloArgument[]
static const char kEndMaxArgument[]
static const char kSmartTimeCheckArgument[]
static const char kValueArgument[]
static const char kIntervalDisjunction[]
static const char kDemandsArgument[]
static const char kTraceOperation[]
static const char kSemiContinuous[]
static const char kIsGreater[]
virtual void EndVisitConstraint(const std::string &type_name, const Constraint *const constraint)
static const char kRelationArgument[]
static const char kEarlyCostArgument[]
static const char kVarValueWatcher[]
static const char kDurationExpr[]
static const char kIsDifferent[]
static const char kGreaterOrEqual[]
static const char kLeftArgument[]
static const char kGlobalCardinality[]
static const char kLexLess[]
virtual void BeginVisitExtension(const std::string &type)
static const char kNextsArgument[]
static const char kTransitsArgument[]
static const char kTransition[]
static const char kStartSyncOnStartOperation[]
static const char kStartMinArgument[]
static const char kUsageLessConstantExtension[]
virtual void EndVisitExtension(const std::string &type)
static const char kCumulativeArgument[]
static const char kStepArgument[]
static const char kLateCostArgument[]
static const char kMaxEqual[]
static const char kSumLessOrEqual[]
static const char kTuplesArgument[]
static const char kCountArgument[]
static const char kUsageEqualVariableExtension[]
static const char kStartMaxArgument[]
static const char kAllowedAssignments[]
virtual void EndVisitModel(const std::string &type_name)
static const char kIsGreaterOrEqual[]
static const char kPathCumul[]
static const char kDifferenceOperation[]
static const char kVarsArgument[]
static const char kSumOperation[]
virtual void VisitIntegerVariableArrayArgument(const std::string &arg_name, const std::vector< IntVar * > &arguments)
static const char kTrace[]
static const char kRightArgument[]
static const char kIsLess[]
static const char kIsLessOrEqual[]
static const char kVariableGroupExtension[]
static const char kIndexOf[]
static const char kEndExpr[]
static const char kNotMember[]
static const char kStartsArgument[]
static const char kElement[]
static const char kSizeYArgument[]
static const char kCountEqual[]
static const char kPartialArgument[]
static const char kExpressionArgument[]
static const char kDistribute[]
static const char kFailuresLimitArgument[]
static const char kScalProdGreaterOrEqual[]
static const char kPositionYArgument[]
static const char kVarBoundWatcher[]
virtual void VisitIntervalArrayArgument(const std::string &arg_name, const std::vector< IntervalVar * > &arguments)
static const char kDivide[]
static const char kInt64ToBoolExtension[]
static const char kIntervalBinaryRelation[]
virtual void VisitIntegerMatrixArgument(const std::string &arg_name, const IntTupleSet &tuples)
static const char kCardsArgument[]
virtual void VisitIntegerExpressionArgument(const std::string &arg_name, IntExpr *const argument)
Visit integer expression argument.
static const char kNoCycle[]
static const char kGreater[]
virtual void VisitSequenceArrayArgument(const std::string &arg_name, const std::vector< SequenceVar * > &arguments)
static const char kCover[]
static const char kNotBetween[]
static const char kCoefficientsArgument[]
static const char kScalProdLessOrEqual[]
static const char kEndMinArgument[]
static const char kVariableArgument[]
static const char kValuesArgument[]
static const char kMinEqual[]
static const char kEquality[]
static const char kInt64ToInt64Extension[]
static const char kSequencesArgument[]
static const char kSumGreaterOrEqual[]
static const char kFixedChargeArgument[]
static const char kDurationMaxArgument[]
static const char kLinkExprVar[]
static const char kScalProdEqual[]
static const char kProduct[]
static const char kDifference[]
static const char kCumulative[]
static const char kAllDifferent[]
static const char kSquare[]
static const char kAssumePathsArgument[]
static const char kInitialState[]
static const char kNonEqual[]
static const char kConditionalExpr[]
static const char kIsEqual[]
static const char kStartSyncOnEndOperation[]
static const char kOptionalArgument[]
static const char kIndexArgument[]
static const char kFalseConstraint[]
static const char kPerformedExpr[]
virtual void VisitSequenceArgument(const std::string &arg_name, SequenceVar *const argument)
Visit sequence argument.
static const char kSearchLimitExtension[]
virtual void BeginVisitModel(const std::string &type_name)
--— Virtual methods for visitors --—
virtual void BeginVisitConstraint(const std::string &type_name, const Constraint *const constraint)
static const char kInversePermutation[]
static const char kCountAssignedItemsExtension[]
Extension names:
Subclass of RevArray<T> which adds numerical operations.
void Decr(Solver *const s, int index)
NumericalRevArray(int size, const T &val)
void Add(Solver *const s, int index, const T &to_add)
void Incr(Solver *const s, int index)
Subclass of Rev<T> which adds numerical operations.
NumericalRev(const T &val)
void Decr(Solver *const s)
void Incr(Solver *const s)
void Add(Solver *const s, const T &to_add)
This class encapsulates an objective.
void EnterSearch() override
Beginning of the search.
void BeginNextDecision(DecisionBuilder *const db) override
Before calling DecisionBuilder::Next.
OptimizeVar(Solver *const s, bool maximize, IntVar *const a, int64_t step)
int64_t best() const
Returns the best value found during search.
bool found_initial_solution_
IntVar * Var() const
Returns the variable that is optimized.
void Accept(ModelVisitor *const visitor) const override
Accepts the given model visitor.
bool AcceptSolution() override
This method is called when a solution is found.
virtual std::string Print() const
bool AtSolution() override
This method is called when a valid solution is found.
void RefuteDecision(Decision *const d) override
Before refuting the decision.
bool AcceptDelta(Assignment *delta, Assignment *deltadelta) override
Internal methods.
std::string DebugString() const override
bool IsAssignedStatusKnown(int var_index) const
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...
void Post() override
This method is called when the constraint is processed by the solver.
void AddCountAssignedItemsDimension(IntVar *const count_var)
This dimension links 'count_var' to the actual number of items assigned to a bin in the pack.
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,...
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.
void InitialPropagate() override
This method performs the initial propagation of the constraint.
Pack(Solver *const s, const std::vector< IntVar * > &vars, int number_of_bins)
void SetImpossible(int var_index, int bin_index)
void SetAssigned(int var_index)
bool IsUndecided(int var_index, int bin_index) const
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.
bool IsPossible(int var_index, int bin_index) const
void AssignFirstPossibleToBin(int bin_index)
void AddCountUsedBinDimension(IntVar *const count_var)
This dimension links 'count_var' to the actual number of bins used in the pack.
void OneDomain(int var_index)
void SetUnassigned(int var_index)
void Accept(ModelVisitor *const visitor) const override
Accepts the given visitor.
void AssignAllPossibleToBin(int bin_index)
void Assign(int var_index, int bin_index)
void UnassignAllRemainingItems()
std::string DebugString() const override
void AssignAllRemainingItems()
IntVar * AssignVar(int var_index, int bin_index) const
void RemoveAllPossibleFromBin(int bin_index)
void EnqueueDelayedDemon(Demon *const d)
This method pushes the demon onto the propagation queue.
virtual std::string name() const
Object naming.
void reset_action_on_fail()
This method clears the failure callback.
bool HasName() const
Returns whether the object has been named or not.
void set_action_on_fail(Solver::Action a)
void ExecuteAll(const SimpleRevFIFO< Demon * > &demons)
void EnqueueVar(Demon *const d)
void FreezeQueue()
This method freezes the propagation queue.
void EnqueueAll(const SimpleRevFIFO< Demon * > &demons)
virtual std::string BaseName() const
Returns a base name for automatic naming.
~PropagationBaseObject() override
void set_variable_to_clean_on_fail(IntVar *v)
Shortcut for variable cleaner.
PropagationBaseObject(Solver *const s)
void set_name(const std::string &name)
void UnfreezeQueue()
This method unfreezes the propagation queue.
std::string DebugString() const override
Usual limit based on wall_time, number of explored branches and number of failures in the search tree...
bool Check() override
This method is called to check the status of the limit.
absl::Duration duration_limit() const
bool IsUncheckedSolutionLimitReached() override
Returns true if the limit of solutions has been reached including unchecked solutions.
void UpdateLimits(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions)
void Init() override
This method is called when the search limit is initialized.
void ExitSearch() override
End of the search.
int64_t wall_time() const
int ProgressPercent() override
Returns a percentage representing the propress of the search before reaching limits.
absl::Time AbsoluteSolverDeadline() const
void Accept(ModelVisitor *const visitor) const override
Accepts the given model visitor.
void Copy(const SearchLimit *const limit) override
Copy a limit.
RegularLimit(Solver *const s, absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check, bool cumulative)
RegularLimit * MakeIdenticalClone() const
std::string DebugString() const override
int64_t solutions() const
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
Reversible array of POD types.
const T & Value(int index) const
RevArray(int size, const T &val)
void SetValue(Solver *const s, int index, const T &val)
const T & operator[](int index) const
This class adds reversibility to a POD type.
void SetValue(Solver *const s, const T &val)
Reversible Immutable MultiMap class.
Base class of all search limits.
void EnterSearch() override
Internal methods.
SearchLimit(Solver *const s)
void PeriodicCheck() override
Periodic call to check limits in long running methods.
virtual void Init()=0
This method is called when the search limit is initialized.
void BeginNextDecision(DecisionBuilder *const b) override
Before calling DecisionBuilder::Next.
virtual void Copy(const SearchLimit *const limit)=0
Copy a limit.
virtual SearchLimit * MakeClone() const =0
Allocates a clone of the limit.
void RefuteDecision(Decision *const d) override
Before refuting the decision.
bool crossed() const
Returns true if the limit has been crossed.
std::string DebugString() const override
virtual bool Check()=0
This method is called to check the status of the limit.
A search monitor is a simple set of callbacks to monitor all search events.
virtual void RefuteDecision(Decision *const d)
Before refuting the decision.
SearchMonitor(Solver *const s)
virtual void ApplyDecision(Decision *const d)
Before applying the decision.
virtual void RestartSearch()
Restart the search.
virtual void ExitSearch()
End of the search.
virtual bool IsUncheckedSolutionLimitReached()
Returns true if the limit of solutions has been reached including unchecked solutions.
virtual bool LocalOptimum()
When a local optimum is reached.
virtual int ProgressPercent()
Returns a percentage representing the propress of the search before reaching limits.
virtual void NoMoreSolutions()
When the search tree is finished.
virtual void BeginFail()
Just when the failure occurs.
virtual void AfterDecision(Decision *const d, bool apply)
Just after refuting or applying the decision, apply is true after Apply.
virtual void BeginInitialPropagation()
Before the initial propagation.
virtual void BeginNextDecision(DecisionBuilder *const b)
Before calling DecisionBuilder::Next.
virtual void PeriodicCheck()
Periodic call to check limits in long running methods.
virtual void EnterSearch()
Beginning of the search.
~SearchMonitor() override
virtual void EndNextDecision(DecisionBuilder *const b, Decision *const d)
After calling DecisionBuilder::Next, along with the returned decision.
virtual void EndFail()
After completing the backtrack.
virtual void EndInitialPropagation()
After the initial propagation.
static constexpr int kNoProgress
virtual void AcceptUncheckedNeighbor()
After accepting an unchecked neighbor during local search.
virtual bool AcceptDelta(Assignment *delta, Assignment *deltadelta)
virtual bool AtSolution()
This method is called when a valid solution is found.
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given model visitor.
virtual void AcceptNeighbor()
After accepting a neighbor during local search.
virtual void Install()
Registers itself on the solver such that it gets notified of the search and propagation events.
virtual bool AcceptSolution()
This method is called when a solution is found.
The SequenceVarElement stores a partial representation of ranked interval variables in the underlying...
void SetSequence(const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
void Reset(SequenceVar *const var)
bool operator==(const SequenceVarElement &element) const
const std::vector< int > & BackwardSequence() const
bool operator!=(const SequenceVarElement &element) const
void SetBackwardSequence(const std::vector< int > &backward_sequence)
const std::vector< int > & Unperformed() const
void SetUnperformed(const std::vector< int > &unperformed)
std::string DebugString() const
SequenceVarElement * Clone()
SequenceVar * Var() const
const std::vector< int > & ForwardSequence() const
void Copy(const SequenceVarElement &element)
void LoadFromProto(const SequenceVarAssignment &sequence_var_assignment_proto)
void WriteToProto(SequenceVarAssignment *sequence_var_assignment_proto) const
void SetForwardSequence(const std::vector< int > &forward_sequence)
A sequence variable is a variable whose domain is a set of possible orderings of the interval variabl...
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...
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.
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 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.
void ComputeStatistics(int *const ranked, int *const not_ranked, int *const unperformed) const
Compute statistics on the sequence.
void DurationRange(int64_t *const dmin, int64_t *const dmax) const
Returns the minimum and maximum duration of combined interval vars in the sequence.
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.
IntVar * Next(int index) const
Returns the next of the index_th interval of the sequence.
IntervalVar * Interval(int index) const
Returns the index_th interval of the sequence.
int64_t size() const
Returns the number of interval vars in the sequence.
void RankLast(int index)
Ranks the index_th interval var first of all unranked interval vars.
virtual void Accept(ModelVisitor *const visitor) const
Accepts the given visitor.
void RankFirst(int index)
Ranks the index_th interval var first of all unranked interval vars.
void RankNotLast(int index)
Indicates that the index_th interval var will not be ranked first of all currently unranked interval ...
void RankNotFirst(int index)
Indicates that the index_th interval var will not be ranked first of all currently unranked interval ...
SequenceVar(Solver *const s, const std::vector< IntervalVar * > &intervals, const std::vector< IntVar * > &nexts, const std::string &name)
std::string DebugString() const override
This class represent a reversible FIFO structure.
This class is the root class of all solution collectors.
void check_index(int n) const
void EnterSearch() override
Beginning of the search.
~SolutionCollector() override
void Push(const SolutionData &data)
void PushSolution()
Push the current state as a new solution.
void AddObjective(IntVar *const objective)
std::vector< Assignment * > recycle_solutions_
std::vector< SolutionData > solution_data_
void Add(IntVar *const var)
Add API.
int solution_count() const
Returns how many solutions were stored during the search.
int64_t Value(int n, IntVar *const var) const
This is a shortcut to get the Value of 'var' in the nth solution.
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.
SolutionData BuildSolutionDataForCurrentState()
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 StartValue(int n, IntervalVar *const var) const
This is a shortcut to get the StartValue of 'var' in the nth solution.
Assignment * solution(int n) const
Returns the nth solution.
int64_t EndValue(int n, IntervalVar *const var) const
This is a shortcut to get the EndValue of 'var' in the nth solution.
int64_t objective_value(int n) const
Returns the objective value of the nth solution.
int64_t wall_time(int n) const
Returns the wall time in ms for the nth solution.
int64_t branches(int n) const
Returns the number of branches when the nth solution was found.
int64_t PerformedValue(int n, IntervalVar *const var) const
This is a shortcut to get the PerformedValue of 'var' in the nth solution.
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.
void FreeSolution(Assignment *solution)
int64_t failures(int n) const
Returns the number of failures encountered at the time of the nth solution.
std::unique_ptr< Assignment > prototype_
SolutionCollector(Solver *const solver, const Assignment *assignment)
void PopSolution()
Remove and delete the last popped solution.
std::string DebugString() const override
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.
This class is used to manage a pool of solutions.
virtual bool SyncNeeded(Assignment *const local_assignment)=0
This method checks if the local solution needs to be updated with an external one.
virtual void RegisterNewSolution(Assignment *const assignment)=0
This method is called when a new solution has been accepted by the local search.
virtual void GetNextSolution(Assignment *const assignment)=0
This method is called when the local search starts a new neighborhood to initialize the default assig...
virtual void Initialize(Assignment *const assignment)=0
This method is called to initialize the solution pool with the assignment from the local search.
SolverState state() const
State of the solver.
Constraint * MakeBetweenCt(IntExpr *const expr, int64_t l, int64_t u)
(l <= expr <= u)
Decision * MakeDecision(Action apply, Action refute)
int64_t neighbors() const
The number of neighbors created.
RegularLimit * MakeTimeLimit(int64_t time_in_ms)
SearchMonitor * MakeLubyRestart(int scale_factor)
This search monitor will restart the search periodically.
void SaveValue(T *o)
reversibility
SolutionCollector * MakeAllSolutionCollector()
Collect all solutions of the search.
Constraint * MakeCount(const std::vector< IntVar * > &vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| == max_count
DecisionModification
The Solver is responsible for creating the search tree.
@ NO_CHANGE
Keeps the default behavior, i.e.
@ SWITCH_BRANCHES
Applies right branch first.
@ KEEP_RIGHT
Left branches are ignored.
@ KEEP_LEFT
Right branches are ignored.
@ KILL_BOTH
Backtracks to the previous decisions, i.e.
bool IsBooleanVar(IntExpr *const expr, IntVar **inner_var, bool *is_negated) const
Returns true if expr represents either boolean_var or 1 - boolean_var.
RegularLimit * MakeSolutionsLimit(int64_t solutions)
Creates a search limit that constrains the number of solutions found during the search.
OptimizeVar * MakeWeightedMinimize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a minimization weighted objective.
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...
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...
LocalSearchFilter * MakeVariableDomainFilter()
bool HasName(const PropagationBaseObject *object) const
Returns whether the object has been named or not.
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...
void ClearLocalSearchState()
Clears the local search state.
DemonProfiler * demon_profiler() const
Access to demon profiler.
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...
SolutionCollector * MakeLastSolutionCollector()
Collect the last solution of the search.
Decision * MakeAssignVariableValueOrDoNothing(IntVar *const var, int64_t value)
Constraint * MakeIsLessCstCt(IntExpr *const v, int64_t c, IntVar *const b)
b == (v < c)
SearchMonitor * MakeAtSolutionCallback(std::function< void()> callback)
IntVar * MakeIsGreaterCstVar(IntExpr *const var, int64_t value)
status var of (var > value)
IntExpr * MakeIndexExpression(const std::vector< IntVar * > &vars, int64_t value)
Returns the expression expr such that vars[expr] == value.
int64_t branches() const
The number of branches explored since the creation of the solver.
IntExpr * RegisterIntExpr(IntExpr *const expr)
Registers a new IntExpr and wraps it inside a TraceIntExpr if necessary.
void RestartCurrentSearch()
SearchLimit * MakeCustomLimit(std::function< bool()> limiter)
Callback-based search limit.
friend class DemonProfiler
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...
Constraint * MakeLess(IntExpr *const left, IntExpr *const right)
left < right
friend void InternalSaveBooleanVarValue(Solver *const, IntVar *const)
LocalSearchOperator * MakeMoveTowardTargetOperator(const Assignment &target)
Creates a local search operator that tries to move the assignment of some variables toward a target.
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...
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.
Constraint * MakeSumEquality(const std::vector< IntVar * > &vars, int64_t cst)
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.
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.
IntExpr * MakeAbs(IntExpr *const expr)
|expr|
Constraint * MakeFalseConstraint()
This constraint always fails.
Constraint * MakeEquality(IntExpr *const left, IntExpr *const right)
left == right
Constraint * MakeIsDifferentCt(IntExpr *const v1, IntExpr *const v2, IntVar *const b)
b == (v1 != v2)
OptimizeVar * MakeOptimize(bool maximize, IntVar *const v, int64_t step)
Creates a objective with a given sense (true = maximization).
Constraint * MakeIntervalVarRelationWithDelay(IntervalVar *const t1, BinaryIntervalRelation r, IntervalVar *const t2, int64_t delay)
This method creates a relation between two interval vars.
Constraint * MakeLessOrEqual(IntExpr *const left, IntExpr *const right)
left <= right
IntExpr * MakePiecewiseLinearExpr(IntExpr *expr, const PiecewiseLinearFunction &f)
General piecewise-linear function expression, built from f(x) where f is piecewise-linear.
ConstraintSolverStatistics GetConstraintSolverStatistics() const
Returns detailed cp search statistics.
IntVar * MakeIsGreaterOrEqualCstVar(IntExpr *const var, int64_t value)
status var of (var >= value)
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...
Constraint * MakeIsLessOrEqualCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var <= value)
DisjunctiveConstraint * MakeStrictDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
This constraint forces all interval vars into an non-overlapping sequence.
IntVar * MakeIsGreaterVar(IntExpr *const left, IntExpr *const right)
status var of (left > right)
LocalSearchStatistics GetLocalSearchStatistics() const
Returns detailed local search statistics.
IntExpr * MakeMin(const std::vector< IntVar * > &vars)
std::min(vars)
static constexpr int kNumPriorities
Number of priorities for demons.
DemonPriority
This enum represents the three possible priorities for a demon in the Solver queue.
@ VAR_PRIORITY
VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.
@ DELAYED_PRIORITY
DELAYED_PRIORITY is the lowest priority: Demons will be processed after VAR_PRIORITY and NORMAL_PRIOR...
@ NORMAL_PRIORITY
NORMAL_PRIORITY is the highest priority: Demons will be processed first.
ConstraintSolverParameters parameters() const
Stored Parameters.
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...
SearchMonitor * MakeSymmetryManager(const std::vector< SymmetryBreaker * > &visitors)
Symmetry Breaking.
Constraint * MakeNotMemberCt(IntExpr *const expr, const std::vector< int64_t > &values)
expr not in set.
int64_t filtered_neighbors() const
The number of filtered neighbors (neighbors accepted by filters).
SolverState
This enum represents the state of the solver w.r.t. the search.
@ AT_SOLUTION
After successful NextSolution and before EndSearch.
@ PROBLEM_INFEASIBLE
After search, the model is infeasible.
@ OUTSIDE_SEARCH
Before search, after search.
@ IN_ROOT_NODE
Executing the root node.
@ NO_MORE_SOLUTIONS
After failed NextSolution and before EndSearch.
@ IN_SEARCH
Executing the search code.
Constraint * MakeAbsEquality(IntVar *const var, IntVar *const abs_var)
Creates the constraint abs(var) == abs_var.
std::string SearchContext() const
RegularLimit * MakeFailuresLimit(int64_t failures)
Creates a search limit that constrains the number of failures that can happen when exploring the sear...
bool CheckAssignment(Assignment *const solution)
Checks whether the given assignment satisfies all relevant constraints.
bool IsProduct(IntExpr *const expr, IntExpr **inner_expr, int64_t *coefficient)
Returns true if expr represents a product of a expr and a constant.
IntVar * RegisterIntVar(IntVar *const var)
Registers a new IntVar and wraps it inside a TraceIntVar if necessary.
absl::Time Now() const
The 'absolute time' as seen by the solver.
IntVar * MakeIsDifferentVar(IntExpr *const v1, IntExpr *const v2)
status var of (v1 != v2)
IntVar * MakeIsEqualVar(IntExpr *const v1, IntExpr *v2)
status var of (v1 == v2)
DecisionBuilder * MakeConstraintAdder(Constraint *const ct)
Returns a decision builder that will add the given constraint to the model.
Constraint * MakeCircuit(const std::vector< IntVar * > &nexts)
Force the "nexts" variable to create a complete Hamiltonian path.
OptimizationDirection
Optimization directions.
IntervalStrategy
This enum describes the straregy used to select the next interval variable and its value to be fixed.
@ INTERVAL_SET_TIMES_FORWARD
Selects the variable with the lowest starting time of all variables, and fixes its starting time to t...
@ INTERVAL_SIMPLE
The simple is INTERVAL_SET_TIMES_FORWARD.
@ INTERVAL_SET_TIMES_BACKWARD
Selects the variable with the highest ending time of all variables, and fixes the ending time to this...
@ INTERVAL_DEFAULT
The default is INTERVAL_SET_TIMES_FORWARD.
Constraint * MakeGreater(IntExpr *const left, IntExpr *const right)
left > right
Pack * MakePack(const std::vector< IntVar * > &vars, int number_of_bins)
This constraint packs all variables onto 'number_of_bins' variables.
std::function< int64_t(int64_t, int64_t, int64_t)> IndexEvaluator3
Assignment * GetOrCreateLocalSearchState()
Returns (or creates) an assignment representing the state of local search.
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.
bool IsProfilingEnabled() const
Returns whether we are profiling the solver.
Demon * MakeActionDemon(Action action)
Creates a demon from a callback.
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...
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...
Constraint * MakeLexicalLess(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
Creates a constraint that enforces that left is lexicographically less than right.
RegularLimit * MakeBranchesLimit(int64_t branches)
Creates a search limit that constrains the number of branches explored in the search tree.
int64_t demon_runs(DemonPriority p) const
The number of demons executed during search for a given priority.
void AddPropagationMonitor(PropagationMonitor *const monitor)
Adds the propagation monitor to the solver.
Constraint * MakeElementEquality(const std::vector< int64_t > &vals, IntVar *const index, IntVar *const target)
IntVar * MakeIsLessCstVar(IntExpr *const var, int64_t value)
status var of (var < value)
OptimizeVar * MakeMaximize(IntVar *const v, int64_t step)
Creates a maximization objective.
SearchMonitor * MakeSearchLog(int branch_period)
The SearchMonitors below will display a periodic search log on LOG(INFO) every branch_period branches...
IntValueStrategy
This enum describes the strategy used to select the next variable value to set.
@ INT_VALUE_SIMPLE
The simple selection is ASSIGN_MIN_VALUE.
@ ASSIGN_CENTER_VALUE
Selects the first possible value which is the closest to the center of the domain of the selected var...
@ SPLIT_UPPER_HALF
Split the domain in two around the center, and choose the lower part first.
@ ASSIGN_MIN_VALUE
Selects the min value of the selected variable.
@ ASSIGN_RANDOM_VALUE
Selects randomly one of the possible values of the selected variable.
@ INT_VALUE_DEFAULT
The default behavior is ASSIGN_MIN_VALUE.
@ ASSIGN_MAX_VALUE
Selects the max value of the selected variable.
@ SPLIT_LOWER_HALF
Split the domain in two around the center, and choose the lower part first.
UnaryIntervalRelation
This enum is used in Solver::MakeIntervalVarRelation to specify the temporal relation between an inte...
@ ENDS_BEFORE
t ends before d, i.e. End(t) <= d.
@ AVOID_DATE
STARTS_AFTER or ENDS_BEFORE, i.e.
@ ENDS_AFTER
t ends after d, i.e. End(t) >= d.
@ STARTS_BEFORE
t starts before d, i.e. Start(t) <= d.
@ STARTS_AT
t starts at d, i.e. Start(t) == d.
@ ENDS_AT
t ends at d, i.e. End(t) == d.
@ STARTS_AFTER
t starts after d, i.e. Start(t) >= d.
@ CROSS_DATE
STARTS_BEFORE and ENDS_AFTER at the same time, i.e.
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...
bool CheckConstraint(Constraint *const ct)
Checks whether adding this constraint will lead to an immediate failure.
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.
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.
void SetSearchContext(Search *search, const std::string &search_context)
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.
std::function< int64_t(Solver *solver, const std::vector< IntVar * > &vars, int64_t first_unbound, int64_t last_unbound)> VariableIndexSelector
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...
Constraint * MakeMemberCt(IntExpr *const expr, const std::vector< int64_t > &values)
expr in set.
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 TopPeriodicCheck()
Performs PeriodicCheck on the top-level search; for instance, can be called from a nested solve to ch...
int64_t Rand64(int64_t size)
Returns a random value between 0 and 'size' - 1;.
DecisionBuilder * MakeApplyBranchSelector(BranchSelector bs)
Creates a decision builder that will set the branch selector.
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.
std::function< int64_t(int64_t, int64_t)> IndexEvaluator2
void SetUseFastLocalSearch(bool use_fast_local_search)
enabled for metaheuristics.
Decision * MakeAssignVariableValue(IntVar *const var, int64_t val)
Decisions.
IntervalVar * MakeIntervalRelaxedMin(IntervalVar *const interval_var)
Creates and returns an interval variable that wraps around the given one, relaxing the min start and ...
OptimizeVar * MakeMinimize(IntVar *const v, int64_t step)
Creates a minimization objective.
Demon * MakeClosureDemon(Closure closure)
!defined(SWIG)
void AddConstraint(Constraint *const c)
Adds the constraint 'c' to the model.
Decision * MakeAssignVariablesValues(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
DecisionBuilder * MakeSolveOnce(DecisionBuilder *const db)
SolveOnce will collapse a search tree described by a decision builder 'db' and a set of monitors and ...
LocalSearchOperator * ConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
Creates a local search operator which concatenates a vector of operators.
LocalSearchFilter * MakeRejectFilter()
Constraint * MakeIsEqualCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var == value)
LocalSearchFilter * MakeAcceptFilter()
Local Search Filters.
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.
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 ...
int64_t wall_time() const
DEPRECATED: Use Now() instead.
std::function< bool(int64_t)> IndexFilter1
friend class LocalSearchProfiler
Constraint * MakeIsLessCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left < right)
DisjunctiveConstraint * MakeDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
This constraint forces all interval vars into an non-overlapping sequence.
OptimizeVar * MakeWeightedMaximize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a maximization weigthed objective.
void ShouldFail()
These methods are only useful for the SWIG wrappers, which need a way to externally cause the Solver ...
int SearchDepth() const
Gets the search depth of the current active search.
Constraint * MakeSumGreaterOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
int64_t unchecked_solutions() const
The number of unchecked solutions found by local search.
void SaveAndSetValue(T *adr, T val)
All-in-one SaveAndSetValue.
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.
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].
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...
void AddLocalSearchMonitor(LocalSearchMonitor *monitor)
Adds the local search monitor to the solver.
LocalSearchOperator * RandomConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
Randomized version of local search concatenator; calls a random operator at each call to MakeNextNeig...
BinaryIntervalRelation
This enum is used in Solver::MakeIntervalVarRelation to specify the temporal relation between the two...
@ ENDS_AFTER_END
t1 ends after t2 end, i.e. End(t1) >= End(t2) + delay.
@ ENDS_AFTER_START
t1 ends after t2 start, i.e. End(t1) >= Start(t2) + delay.
@ STAYS_IN_SYNC
STARTS_AT_START and ENDS_AT_END at the same time.
@ ENDS_AT_END
t1 ends at t2 end, i.e. End(t1) == End(t2) + delay.
@ STARTS_AT_END
t1 starts at t2 end, i.e. Start(t1) == End(t2) + delay.
@ ENDS_AT_START
t1 ends at t2 start, i.e. End(t1) == Start(t2) + delay.
@ STARTS_AFTER_END
t1 starts after t2 end, i.e. Start(t1) >= End(t2) + delay.
@ STARTS_AFTER_START
t1 starts after t2 start, i.e. Start(t1) >= Start(t2) + delay.
@ STARTS_AT_START
t1 starts at t2 start, i.e. Start(t1) == Start(t2) + delay.
Constraint * MakeMaxEquality(const std::vector< IntVar * > &vars, IntVar *const max_var)
LocalSearchOperators
This enum is used in Solver::MakeOperator to specify the neighborhood to create.
@ EXCHANGE
Operator which exchanges the positions of two nodes.
@ MAKEINACTIVE
Operator which makes path nodes inactive.
@ RELOCATE
Relocate neighborhood with length of 1 (see OROPT comment).
@ SWAPACTIVE
Operator which replaces an active node by an inactive one.
@ SIMPLELNS
Operator which defines one neighbor per variable.
@ INCREMENT
Operator which defines one neighbor per variable.
@ MAKECHAININACTIVE
Operator which makes a "chain" of path nodes inactive.
@ TWOOPT
Operator which reverses a sub-chain of a path.
@ FULLPATHLNS
Operator which relaxes one entire path and all inactive nodes, thus defining num_paths neighbors.
@ EXTENDEDSWAPACTIVE
Operator which makes an inactive node active and an active one inactive.
@ OROPT
Relocate: OROPT and RELOCATE.
@ PATHLNS
Operator which relaxes two sub-chains of three consecutive arcs each.
@ UNACTIVELNS
Operator which relaxes all inactive nodes and one sub-chain of six consecutive arcs.
@ MAKEACTIVE
Operator which inserts an inactive node into a path.
@ DECREMENT
Operator which defines a neighborhood to decrement values.
@ CROSS
Operator which cross exchanges the starting chains of 2 paths, including exchanging the whole paths.
Constraint * MakeIsEqualCt(IntExpr *const v1, IntExpr *v2, IntVar *const b)
b == (v1 == v2)
LocalSearchPhaseParameters * MakeLocalSearchPhaseParameters(IntVar *objective, LocalSearchOperator *const ls_operator, DecisionBuilder *const sub_decision_builder)
Local Search Phase Parameters.
IntExpr * MakeOpposite(IntExpr *const expr)
-expr
void PushState()
The PushState and PopState methods manipulates the states of the reversible objects.
bool IsLocalSearchProfilingEnabled() const
Returns whether we are profiling local search.
Constraint * MakeScalProdLessOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
IntVarLocalSearchFilter * MakeSumObjectiveFilter(const std::vector< IntVar * > &vars, IndexEvaluator2 values, Solver::LocalSearchFilterBound filter_enum)
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 ReSeed(int32_t seed)
Reseed the solver random generator.
Demon * MakeConstraintInitialPropagateCallback(Constraint *const ct)
This method is a specialized case of the MakeConstraintDemon method to call the InitiatePropagate of ...
std::string DebugString() const
!defined(SWIG)
Constraint * MakeTrueConstraint()
This constraint always succeeds.
Demon * RegisterDemon(Demon *const demon)
Adds a new demon and wraps it inside a DemonProfiler if necessary.
Search * ActiveSearch() const
Returns the active search, nullptr outside search.
Constraint * MakeAllDifferentExcept(const std::vector< IntVar * > &vars, int64_t escape_value)
All variables are pairwise different, unless they are assigned to the escape value.
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...
int64_t failures() const
The number of failures encountered since the creation of the solver.
IntervalVar * MakeIntervalRelaxedMax(IntervalVar *const interval_var)
Creates and returns an interval variable that wraps around the given one, relaxing the max start and ...
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.
IntervalVar * MakeFixedInterval(int64_t start, int64_t duration, const std::string &name)
Creates a fixed and performed interval.
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,...
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'.
ModelVisitor * MakeVariableDegreeVisitor(absl::flat_hash_map< const IntVar *, int > *const map)
Compute the number of constraints a variable is attached to.
SearchMonitor * MakeConstantRestart(int frequency)
This search monitor will restart the search periodically after 'frequency' failures.
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...
LocalSearchMonitor * GetLocalSearchMonitor() const
Returns the local search monitor.
int constraints() const
Counts the number of constraints that have been added to the solver before the search.
IntVar * MakeIsBetweenVar(IntExpr *const v, int64_t l, int64_t u)
IntExpr * MakeElement(const std::vector< int64_t > &values, IntVar *const index)
values[index]
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.
EvaluatorStrategy
This enum is used by Solver::MakePhase to specify how to select variables and values during the searc...
@ CHOOSE_STATIC_GLOBAL_BEST
Pairs are compared at the first call of the selector, and results are cached.
@ CHOOSE_DYNAMIC_GLOBAL_BEST
Pairs are compared each time a variable is selected.
static int64_t MemoryUsage()
Current memory usage in bytes.
void set_optimization_direction(OptimizationDirection direction)
int SolveDepth() const
Gets the number of nested searches.
IntVar * MakeIsMemberVar(IntExpr *const expr, const std::vector< int64_t > &values)
IntVar * MakeIsLessOrEqualCstVar(IntExpr *const var, int64_t value)
status var of (var <= value)
SearchMonitor * MakeSimulatedAnnealing(bool maximize, IntVar *const v, int64_t step, int64_t initial_temperature)
Creates a Simulated Annealing monitor.
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.
PropagationMonitor * GetPropagationMonitor() const
Returns the propagation monitor.
Decision * MakeRankFirstInterval(SequenceVar *const sequence, int index)
Returns a decision that tries to rank first the ith interval var in the sequence variable.
IntExpr * MakeMax(const std::vector< IntVar * > &vars)
std::max(vars)
Constraint * MakeIsLessOrEqualCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left <= right)
bool Solve(DecisionBuilder *const db, const std::vector< SearchMonitor * > &monitors)
SolutionPool * MakeDefaultSolutionPool()
Solution Pool.
void clear_fail_intercept()
IntExpr * MakeDifference(IntExpr *const left, IntExpr *const right)
left - right
Constraint * MakeIsDifferentCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var != value)
std::string model_name() const
Returns the name of the model.
RegularLimitParameters MakeDefaultRegularLimitParameters() const
Creates a regular limit proto containing default values.
RegularLimit * MakeTimeLimit(absl::Duration time)
Creates a search limit that constrains the running time.
IntExpr * MakeConvexPiecewiseExpr(IntExpr *expr, int64_t early_cost, int64_t early_date, int64_t late_date, int64_t late_cost)
Convex piecewise function.
IntExpr * MakePower(IntExpr *const expr, int64_t n)
expr ^ n (n > 0)
IntVar * MakeBoolVar()
MakeBoolVar will create a variable with a {0, 1} domain.
bool UseFastLocalSearch() const
Returns true if fast local search is enabled.
bool InstrumentsVariables() const
Returns whether we are tracing variables.
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|.
IntVar * MakeIsDifferentCstVar(IntExpr *const var, int64_t value)
status var of (var != value)
SearchMonitor * MakeSearchTrace(const std::string &prefix)
Creates a search monitor that will trace precisely the behavior of the search.
int64_t accepted_neighbors() const
The number of accepted neighbors.
Constraint * MakeNonEquality(IntExpr *const left, IntExpr *const right)
left != right
static ConstraintSolverParameters DefaultSolverParameters()
Create a ConstraintSolverParameters proto with all the default values.
IntVar * MakeIsLessVar(IntExpr *const left, IntExpr *const right)
status var of (left < right)
LocalSearchOperator * MakeOperator(const std::vector< IntVar * > &vars, LocalSearchOperators op)
Local Search Operators.
friend class SearchMonitor
std::string LocalSearchProfile() const
Returns local search profiling information in a human readable format.
void Accept(ModelVisitor *const visitor) const
Accepts the given model visitor.
int SearchLeftDepth() const
Gets the search left depth of the current active search.
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...
Constraint * MakeTemporalDisjunction(IntervalVar *const t1, IntervalVar *const t2, IntVar *const alt)
This constraint implements a temporal disjunction between two interval vars t1 and t2.
int TopProgressPercent()
Returns a percentage representing the propress of the search before reaching the limits of the top-le...
bool CurrentlyInSolve() const
Returns true whether the current search has been created using a Solve() call instead of a NewSearch ...
Constraint * MakeIsGreaterOrEqualCstCt(IntExpr *const var, int64_t value, IntVar *const boolvar)
boolvar == (var >= value)
T * RevAlloc(T *object)
Registers the given object as being reversible.
IntVarStrategy
This enum describes the strategy used to select the next branching variable at each node during the s...
@ CHOOSE_RANDOM
Randomly select one of the remaining unbound variables.
@ CHOOSE_MIN_SIZE
Among unbound variables, select the variable with the smallest size.
@ CHOOSE_FIRST_UNBOUND
Select the first unbound variable.
@ CHOOSE_PATH
Selects the next unbound variable on a path, the path being defined by the variables: var[i] correspo...
@ CHOOSE_HIGHEST_MAX
Among unbound variables, select the variable with the highest maximal value.
@ CHOOSE_MIN_SIZE_LOWEST_MIN
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
@ INT_VAR_DEFAULT
The default behavior is CHOOSE_FIRST_UNBOUND.
@ CHOOSE_MIN_SIZE_HIGHEST_MAX
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
@ CHOOSE_MAX_REGRET_ON_MIN
Among unbound variables, select the variable with the largest gap between the first and the second va...
@ CHOOSE_MIN_SIZE_HIGHEST_MIN
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
@ CHOOSE_MAX_SIZE
Among unbound variables, select the variable with the highest size.
@ INT_VAR_SIMPLE
The simple selection is CHOOSE_FIRST_UNBOUND.
@ CHOOSE_MIN_SIZE_LOWEST_MAX
Among unbound variables, select the variable with the smallest size, i.e., the smallest number of pos...
@ CHOOSE_LOWEST_MIN
Among unbound variables, select the variable with the smallest minimal value.
DecisionBuilder * MakePhase(const std::vector< IntVar * > &vars, IntVarStrategy var_str, IntValueStrategy val_str)
Phases on IntVar arrays.
IntExpr * MakeScalProd(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefs)
scalar product
SequenceStrategy
Used for scheduling. Not yet implemented.
@ CHOOSE_MIN_SLACK_RANK_FORWARD
@ CHOOSE_RANDOM_RANK_FORWARD
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.
Solver(const std::string &name)
Solver API.
uint64_t stamp() const
The stamp indicates how many moves in the search tree we have performed.
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....
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.
ModelCache * Cache() const
Returns the cache of the model.
Decision * MakeRankLastInterval(SequenceVar *const sequence, int index)
Returns a decision that tries to rank last the ith interval var in the sequence variable.
Constraint * MakeAllDifferent(const std::vector< IntVar * > &vars)
All variables are pairwise different.
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...
IntExpr * MakeDiv(IntExpr *const expr, int64_t value)
expr / value (integer division)
std::function< int64_t(const IntVar *v, int64_t id)> VariableValueSelector
Constraint * MakeIsBetweenCt(IntExpr *const expr, int64_t l, int64_t u, IntVar *const b)
b == (l <= expr <= u)
DecisionBuilder * MakeLocalSearchPhase(Assignment *const assignment, LocalSearchPhaseParameters *const parameters)
Local Search decision builders factories.
Constraint * MakeScalProdGreaterOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coeffs, int64_t cst)
Demon * MakeDelayedConstraintInitialPropagateCallback(Constraint *const ct)
This method is a specialized case of the MakeConstraintDemon method to call the InitiatePropagate of ...
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.
bool NameAllVariables() const
Returns whether all variables should be named.
T * RevAllocArray(T *object)
Like RevAlloc() above, but for an array of objects: the array must have been allocated with the new[]...
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...
IntExpr * MakeSum(IntExpr *const left, IntExpr *const right)
left + right.
IntExpr * CastExpression(const IntVar *const var) const
!defined(SWIG)
SearchMonitor * MakeEnterSearchCallback(std::function< void()> callback)
--— Callback-based search monitors --—
uint64_t fail_stamp() const
The fail_stamp() is incremented after each backtrack.
void SetBranchSelector(BranchSelector bs)
Sets the given branch selector on the current active search.
friend class PropagationBaseObject
IntExpr * MakeSquare(IntExpr *const expr)
expr * expr
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...
IntExpr * MakeConditionalExpression(IntVar *const condition, IntExpr *const expr, int64_t unperformed_value)
Conditional Expr condition ? expr : unperformed_value.
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.
std::vector< int64_t > tmp_vector_
Unsafe temporary vector.
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...
Constraint * MakeIsGreaterCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left > right)
Assignment * MakeAssignment()
This method creates an empty assignment.
ModelVisitor * MakePrintModelVisitor()
Prints the model.
std::function< void()> Closure
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...
std::function< void(Solver *)> Action
SolutionCollector * MakeFirstSolutionCollector()
Collect the first solution of the search.
void ExportProfilingOverview(const std::string &filename)
Exports the profiling information in a human readable overview.
DecisionBuilder * Compose(DecisionBuilder *const db1, DecisionBuilder *const db2)
Creates a decision builder which sequentially composes decision builders.
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...
MarkerType
This enum is used internally in private methods Solver::PushState and Solver::PopState to tag states ...
SolutionCollector * MakeBestValueSolutionCollector(const Assignment *const assignment, bool maximize)
Collect the solution corresponding to the optimal value of the objective of 'assignment'; if 'assignm...
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...
Constraint * MakeMinEquality(const std::vector< IntVar * > &vars, IntVar *const min_var)
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).
Constraint * MakeIsGreaterCstCt(IntExpr *const v, int64_t c, IntVar *const b)
b == (v > c)
Constraint * MakeSumLessOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
Variation on arrays.
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...
std::function< int64_t(int64_t)> IndexEvaluator1
Callback typedefs.
int32_t Rand32(int32_t size)
Returns a random value between 0 and 'size' - 1;.
DecisionBuilder * MakeStoreAssignment(Assignment *assignment)
Returns a DecisionBuilder which stores an Assignment (calls void Assignment::Store())
Constraint * MakePathPrecedenceConstraint(std::vector< IntVar * > nexts, const std::vector< std::pair< int, int >> &precedences)
Contraint enforcing, for each pair (i,j) in precedences, i to be before j in paths defined by next va...
std::function< DecisionModification()> BranchSelector
bool InstrumentsDemons() const
Returns whether we are instrumenting demons.
Constraint * MakeIntervalVarRelation(IntervalVar *const t, UnaryIntervalRelation r, int64_t d)
This method creates a relation between an interval var and a date.
SearchMonitor * MakeExitSearchCallback(std::function< void()> callback)
Decision * MakeSplitVariableDomain(IntVar *const var, int64_t val, bool start_with_lower_half)
DecisionBuilder * MakeDefaultPhase(const std::vector< IntVar * > &vars)
IntExpr * MakeProd(IntExpr *const left, IntExpr *const right)
left * right
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,...
IntVar * MakeIntConst(int64_t val, const std::string &name)
IntConst will create a constant expression.
Decision * MakeVariableLessOrEqualValue(IntVar *const var, int64_t value)
void set_fail_intercept(std::function< void()> fail_intercept)
Internal.
DecisionBuilder * MakeRestoreAssignment(Assignment *assignment)
Returns a DecisionBuilder which restores an Assignment (calls void Assignment::Restore())
Decision * MakeFailDecision()
void Fail()
Abandon the current branch in the search tree. A backtrack will follow.
IntExpr * MakeModulo(IntExpr *const x, int64_t mod)
Modulo expression x % mod (with the python convention for modulo).
Constraint * MakeGreaterOrEqual(IntExpr *const left, IntExpr *const right)
left >= right
IntVar * MakeIsEqualCstVar(IntExpr *const var, int64_t value)
status var of (var == value)
Constraint * MakeIsMemberCt(IntExpr *const expr, const std::vector< int64_t > &values, IntVar *const boolvar)
boolvar == (expr in set)
int64_t solutions() const
The number of solutions found since the start of the search.
IntVar * MakeIsGreaterOrEqualVar(IntExpr *const left, IntExpr *const right)
status var of (left >= right)
Constraint * MakeIsGreaterOrEqualCt(IntExpr *const left, IntExpr *const right, IntVar *const b)
b == (left >= right)
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...
std::function< IntVar *(int64_t)> Int64ToIntVar
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...
std::function< bool(int64_t, int64_t, int64_t)> VariableValueComparator
Constraint * MakeAtMost(std::vector< IntVar * > vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| <= max_count
void FinishCurrentSearch()
Tells the solver to kill or restart the current search.
Decision * MakeAssignVariableValueOrFail(IntVar *const var, int64_t value)
void NewSearch(DecisionBuilder *const db, const std::vector< SearchMonitor * > &monitors)
Constraint * MakeScalProdEquality(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
IntExpr * MakeMonotonicElement(IndexEvaluator1 values, bool increasing, IntVar *const index)
Function based element.
Constraint * MakeNoCycle(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, IndexFilter1 sink_handler=nullptr)
Prevent cycles.
SolutionCollector * MakeNBestValueSolutionCollector(const Assignment *const assignment, int solution_count, bool maximize)
Same as MakeBestValueSolutionCollector but collects the best solution_count solutions.
ModelVisitor * MakeStatisticsModelVisitor()
Displays some nice statistics on the model.
Decision * balancing_decision() const
IntVar * MakeIsLessOrEqualVar(IntExpr *const left, IntExpr *const right)
status var of (left <= right)
IntervalVar * RegisterIntervalVar(IntervalVar *const var)
Registers a new IntervalVar and wraps it inside a TraceIntervalVar if necessary.
EvaluatorLocalSearchOperators
This enum is used in Solver::MakeOperator associated with an evaluator to specify the neighborhood to...
@ TSPOPT
Sliding TSP operator.
@ LK
Lin-Kernighan local search.
LocalSearchFilterBound
This enum is used in Solver::MakeLocalSearchObjectiveFilter.
@ GE
Move is accepted when the current objective value >= objective.Min.
@ LE
Move is accepted when the current objective value <= objective.Max.
@ EQ
Move is accepted when the current objective value is in the interval objective.Min .
Decision * MakeVariableGreaterOrEqualValue(IntVar *const var, int64_t value)
OptimizationDirection optimization_direction() const
The direction of optimization, getter and setter.
void SaveAndAdd(T *adr, T val)
All-in-one SaveAndAdd_value.
This class represents a sorted list of disjoint, closed intervals.
A symmetry breaker is an object that will visit a decision and create the 'symmetrical' decision in r...
ABSL_DECLARE_FLAG(int64_t, cp_random_seed)
Declaration of the core objects for the constraint solver.
SharedBoundsManager * bounds
absl::Span< const double > coefficients
static const int64_t kint64max
#define DISALLOW_COPY_AND_ASSIGN(TypeName)
bool FindCopy(const Collection &collection, const Key &key, Value *const value)
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)
Collection of objects used to extend the Constraint Solver library.
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
void SetAssignmentFromAssignment(Assignment *target_assignment, const std::vector< IntVar * > &target_vars, const Assignment *source_assignment, const std::vector< IntVar * > &source_vars)
NOLINT.
int64_t One()
This method returns 1.
This struct holds all parameters for the default search.
int heuristic_num_failures_limit
The failure limit for each heuristic that we run.
int initialization_splits
Maximum number of intervals that the initialization of impacts will scan per variable.
DecisionBuilder * decision_builder
When defined, this overrides the default impact based decision builder.
DisplayLevel display_level
This represents the amount of information displayed by the default search.
ValueSelection value_selection_schema
This parameter describes which value to select for a given var.
@ CHOOSE_MAX_VALUE_IMPACT
@ CHOOSE_MAX_AVERAGE_IMPACT
VariableSelection var_selection_schema
This parameter describes how the next variable to instantiate will be chosen.
bool persistent_impact
Whether to keep the impact from the first search for other searches, or to recompute the impact for e...
bool use_last_conflict
Should we use last conflict method. The default is false.
int heuristic_period
The distance in nodes between each run of the heuristics.
int random_seed
Seed used to initialize the random part in some heuristics.
bool run_all_heuristics
The default phase will run heuristics periodically.
static Iterator Begin(IntVarIterator *it)
These are the only way to construct an Iterator.
bool operator!=(const Iterator &other) const
int64_t operator*() const
static Iterator End(IntVarIterator *it)
bool operator<(const SolutionData &other) const
Holds semantic information stating that the 'expression' has been cast into 'variable' using the Var(...
IntegerCastInfo(IntVar *const v, IntExpr *const e, Constraint *const c)
Creates a search monitor from logging parameters.
int branch_period
SearchMonitors will display a periodic search log every branch_period branches explored.
OptimizeVar * objective
SearchMonitors will display values of objective or variable (both cannot be used together).
std::function< std::string()> display_callback
SearchMonitors will display the result of display_callback at each new solution found and when the se...
double scaling_factor
When displayed, objective or var values will be scaled and offset by the given values in the followin...
bool display_on_new_solutions_only
To be used to protect from cases where display_callback assumes variables are instantiated,...