68#ifndef OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
69#define OR_TOOLS_CONSTRAINT_SOLVER_CONSTRAINT_SOLVER_H_
83#include "absl/base/attributes.h"
84#include "absl/base/log_severity.h"
85#include "absl/container/flat_hash_map.h"
86#include "absl/container/flat_hash_set.h"
87#include "absl/flags/declare.h"
88#include "absl/flags/flag.h"
89#include "absl/random/random.h"
90#include "absl/strings/str_format.h"
91#include "absl/time/time.h"
97#include "ortools/constraint_solver/search_stats.pb.h"
98#include "ortools/constraint_solver/solver_parameters.pb.h"
112class AssignmentProto;
117class DecisionBuilder;
118class DecisionVisitor;
122class DisjunctiveConstraint;
123class ImprovementSearchLimit;
126class IntVarAssignment;
127class IntVarLocalSearchFilter;
129class IntervalVarAssignment;
130class LocalSearchFilter;
131class LocalSearchFilterManager;
132class LocalSearchMonitor;
133class LocalSearchOperator;
134class LocalSearchPhaseParameters;
135class LocalSearchProfiler;
140class ProfiledDecisionBuilder;
141class PropagationBaseObject;
142class PropagationMonitor;
145class RegularLimitParameters;
151class SequenceVarAssignment;
152class SolutionCollector;
154class SymmetryBreaker;
161 return absl::GetFlag(FLAGS_cp_random_seed) == -1
162 ? absl::Uniform<int64_t>(absl::BitGen(), 0,
kint64max)
163 : absl::GetFlag(FLAGS_cp_random_seed);
743 typedef std::function<int64_t(
Solver* solver,
744 const std::vector<IntVar*>& vars,
745 int64_t first_unbound, int64_t last_unbound)>
748 typedef std::function<int64_t(
const IntVar* v, int64_t
id)>
750 typedef std::function<bool(int64_t, int64_t, int64_t)>
763 ConstraintSolverParameters
parameters()
const {
return parameters_; }
775 InternalSaveValue(o);
790 template <
typename T>
792 return reinterpret_cast<T*
>(SafeRevAlloc(
object));
801 template <
typename T>
803 return reinterpret_cast<T*
>(SafeRevAllocArray(
object));
888 const std::vector<SearchMonitor*>& monitors);
910 const std::vector<SearchMonitor*>& monitors);
935 const std::vector<SearchMonitor*>& monitors);
975 absl::Time
Now()
const;
1007 uint64_t
stamp()
const;
1014 return optimization_direction_;
1017 optimization_direction_ = direction;
1033 const std::string&
name);
1063 const std::string&
name, std::vector<IntVar*>* vars);
1067 std::vector<IntVar*>* vars);
1070 const std::string&
name);
1076 std::vector<IntVar*>* vars);
1094 const std::vector<int64_t>& coefs);
1097 const std::vector<int>& coefs);
1150 int64_t range_end,
IntVar* argument);
1161 IntVar*
const target_var);
1183 int64_t early_date, int64_t late_date,
1209 int64_t unperformed_value);
1336 const std::vector<int64_t>& coeffs,
1339 const std::vector<int>& coeffs,
1405 const std::vector<int64_t>& values);
1410 const std::vector<int64_t>& values);
1412 const std::vector<int>& values);
1416 std::vector<int64_t> ends);
1419 std::vector<int> ends);
1428 const std::vector<int64_t>& values,
1431 const std::vector<int>& values,
1434 const std::vector<int64_t>& values);
1445 IntVar*
const max_count);
1449 const std::vector<int64_t>& values,
1450 const std::vector<IntVar*>& cards);
1453 const std::vector<int>& values,
1454 const std::vector<IntVar*>& cards);
1457 const std::vector<IntVar*>& cards);
1461 int64_t card_max, int64_t card_size);
1466 const std::vector<int64_t>& card_min,
1467 const std::vector<int64_t>& card_max);
1472 const std::vector<int>& card_min,
1473 const std::vector<int>& card_max);
1478 const std::vector<int64_t>& values,
1479 const std::vector<int64_t>& card_min,
1480 const std::vector<int64_t>& card_max);
1485 const std::vector<int>& values,
1486 const std::vector<int>& card_min,
1487 const std::vector<int>& card_max);
1494 IntVar*
const deviation_var, int64_t total_sum);
1504 bool stronger_propagation);
1509 int64_t escape_value);
1528 const std::vector<IntVar*>& sorted);
1536 const std::vector<IntVar*>& right);
1541 const std::vector<IntVar*>& right);
1548 const std::vector<IntVar*>& left,
const std::vector<IntVar*>& right);
1565 const std::vector<IntVar*>& second_vars);
1573 const std::vector<IntVar*>& second_vars,
1574 int64_t escape_value);
1589 const std::vector<IntVar*>& active,
1592 const std::vector<IntVar*>& active,
1607 const std::vector<IntVar*>& active,
1608 const std::vector<IntVar*>& cumuls,
1609 const std::vector<IntVar*>& transits);
1614 const std::vector<IntVar*>& active,
1615 const std::vector<IntVar*>& cumuls,
1616 const std::vector<IntVar*>& transits);
1624 const std::vector<IntVar*>& active,
1625 const std::vector<IntVar*>& cumuls,
1635 const std::vector<IntVar*>& active,
1636 const std::vector<IntVar*>& cumuls,
1637 const std::vector<IntVar*>& slacks,
1644 std::vector<int64_t> sources,
1645 std::vector<int64_t> sinks,
1646 std::vector<IntVar*>
status);
1654 std::vector<IntVar*> nexts,
1655 const std::vector<std::pair<int, int>>& precedences);
1665 std::vector<IntVar*> nexts,
1666 const std::vector<std::pair<int, int>>& precedences,
1667 const std::vector<int>& lifo_path_starts,
1668 const std::vector<int>& fifo_path_starts);
1672 std::vector<IntVar*> nexts, std::vector<IntVar*> transits,
1673 const std::vector<std::pair<int, int>>& precedences);
1678 Constraint* MakeMapDomain(IntVar* const var,
1679 const std::vector<IntVar*>& actives);
1696 const std::vector<IntVar*>& vars,
const IntTupleSet& transition_table,
1697 int64_t initial_state,
const std::vector<int64_t>& final_states);
1708 int64_t initial_state,
1709 const std::vector<int>& final_states);
1711#if defined(SWIGPYTHON)
1714 const std::vector<IntVar*>& vars,
1715 const std::vector<std::vector<int64_t> >& raw_tuples) {
1717 tuples.InsertAll(raw_tuples);
1722 const std::vector<IntVar*>& vars,
1723 const std::vector<std::vector<int64_t> >&
1725 int64_t initial_state,
const std::vector<int>& final_states) {
1726 IntTupleSet transitions(3);
1727 transitions.InsertAll(raw_transitions);
1742 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1743 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1745 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1746 const std::vector<int64_t>& x_size,
const std::vector<int64_t>& y_size);
1748 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1749 const std::vector<int>& x_size,
const std::vector<int>& y_size);
1760 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1761 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1763 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1764 const std::vector<int64_t>& x_size,
const std::vector<int64_t>& y_size);
1766 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1767 const std::vector<int>& x_size,
const std::vector<int>& y_size);
1774 Pack*
MakePack(
const std::vector<IntVar*>& vars,
int number_of_bins);
1783 const std::string&
name);
1789 bool optional,
const std::string&
name,
1790 std::vector<IntervalVar*>*
const array);
1796 const std::string&
name);
1802 IntVar*
const performed_variable,
1803 const std::string&
name);
1808 const std::vector<IntVar*>& start_variables, int64_t duration,
1809 const std::string&
name, std::vector<IntervalVar*>*
const array);
1814 const std::vector<IntVar*>& start_variables,
1815 const std::vector<int64_t>& durations,
const std::string&
name,
1816 std::vector<IntervalVar*>*
const array);
1820 const std::vector<IntVar*>& start_variables,
1821 const std::vector<int>& durations,
const std::string&
name,
1822 std::vector<IntervalVar*>*
const array);
1827 const std::vector<IntVar*>& start_variables,
1828 const std::vector<int64_t>& durations,
1829 const std::vector<IntVar*>& performed_variables,
const std::string&
name,
1830 std::vector<IntervalVar*>*
const array);
1835 const std::vector<IntVar*>& start_variables,
1836 const std::vector<int>& durations,
1837 const std::vector<IntVar*>& performed_variables,
const std::string&
name,
1838 std::vector<IntervalVar*>*
const array);
1842 const std::string&
name);
1847 int64_t duration_min, int64_t duration_max,
1849 const std::string&
name);
1854 int64_t duration_min, int64_t duration_max,
1856 const std::string&
name,
1857 std::vector<IntervalVar*>*
const array);
1868 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1875 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1882 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1889 IntervalVar*
const interval_var, int64_t duration, int64_t offset);
1937 IntervalVar*
const t2);
1945 IntervalVar*
const t2,
1952 IntervalVar*
const t2,
IntVar*
const alt);
1957 IntervalVar*
const t2);
1962 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
1968 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
1980 const std::vector<int64_t>& demands,
1993 const std::vector<int>& demands, int64_t
capacity,
1994 const std::string&
name);
2006 const std::vector<int64_t>& demands,
2019 const std::vector<int>& demands,
2030 const std::vector<IntVar*>& demands,
2041 const std::vector<IntVar*>& demands,
2050 IntervalVar*
const target_var);
2063 const Assignment*
const assignment);
2070 const Assignment*
const assignment);
2080 const Assignment*
const assignment,
bool maximize);
2092 const Assignment*
const assignment,
int solution_count,
bool maximize);
2098 const Assignment*
const assignment);
2115 const std::vector<int64_t>& weights,
2121 const std::vector<int>& weights,
2126 const std::vector<int64_t>& weights,
2131 const std::vector<int>& weights,
2136 const std::vector<IntVar*>& sub_objectives,
2137 const std::vector<int64_t>& weights,
2142 const std::vector<IntVar*>& sub_objectives,
2143 const std::vector<int>& weights,
2165 const std::vector<IntVar*>& vars,
2166 int64_t keep_tenure, int64_t forbid_tenure,
2167 double tabu_factor);
2173 const std::vector<IntVar*>& tabu_vars,
2174 int64_t forbid_tenure);
2180 int64_t initial_temperature);
2187 const std::vector<IntVar*>& vars,
2188 double penalty_factor);
2190 bool maximize,
IntVar*
const objective,
2192 const std::vector<IntVar*>& vars,
2193 const std::vector<IntVar*>& secondary_vars,
double penalty_factor);
2207 ABSL_DEPRECATED(
"Use the version taking absl::Duration() as argument")
2211 ? absl::InfiniteDuration()
2212 : absl::Milliseconds(time_in_ms));
2235 bool smart_time_check =
false,
2236 bool cumulative =
false);
2239 const RegularLimitParameters&
proto);
2247 bool smart_time_check =
false,
2248 bool cumulative =
false);
2264 IntVar* objective_var,
bool maximize,
double objective_scaling_factor,
2265 double objective_offset,
double improvement_rate_coefficient,
2266 int improvement_rate_solutions_distance);
2271 std::function<
bool()> limiter);
2285 std::function<std::string()> display_callback);
2290 std::function<std::string()> display_callback);
2299 std::function<std::string()> display_callback);
2341 absl::flat_hash_map<const IntVar*, int>*
const map);
2346 const std::vector<SymmetryBreaker*>& visitors);
2363 bool start_with_lower_half);
2368 const std::vector<int64_t>& values);
2370 const std::vector<IntVar*>& vars,
const std::vector<int64_t>& values);
2372 const std::vector<int64_t>& values);
2473 int64_t*
const marker);
2481 int64_t*
const marker);
2521 const std::vector<IntVar*>& vars);
2547 const std::vector<SearchMonitor*>& monitors);
2583 int64_t step,
const std::vector<SearchMonitor*>& monitors);
2597 const std::vector<IntVar*>& secondary_vars,
2605 const std::vector<IntVar*>& secondary_vars,
2617 int number_of_variables);
2619 int number_of_variables,
2636 const std::vector<IntVar*>& variables,
2637 const std::vector<int64_t>& target_values);
2670 const std::vector<LocalSearchOperator*>& ops);
2672 const std::vector<LocalSearchOperator*>& ops,
bool restart);
2674 const std::vector<LocalSearchOperator*>& ops,
2675 std::function<int64_t(
int,
int)> evaluator);
2679 const std::vector<LocalSearchOperator*>& ops);
2685 const std::vector<LocalSearchOperator*>& ops, int32_t seed);
2695 const std::vector<LocalSearchOperator*>& ops,
double memory_coefficient,
2696 double exploration_coefficient,
bool maximize);
2737 const std::vector<IntVar*>& vars,
DecisionBuilder*
const first_solution,
2741 const std::vector<IntVar*>& vars,
DecisionBuilder*
const first_solution,
2745 const std::vector<SequenceVar*>& vars,
2786 const std::vector<IntVar*>& vars,
2826 InternalSaveValue(adr);
2835 InternalSaveValue(adr);
2843 return absl::Uniform<int64_t>(random_, 0, size);
2849 return absl::Uniform<int32_t>(random_, 0, size);
2853 void ReSeed(int32_t seed) { random_.seed(seed); }
2888 fail_intercept_ = std::move(fail_intercept);
2898 use_fast_local_search_ = use_fast_local_search;
2971 template <
class K,
class V>
2979 bool* is_negated)
const;
3001 if (!should_fail_)
return;
3002 should_fail_ =
false;
3013 void PushSentinel(
int magic_code);
3014 void BacktrackToSentinel(
int magic_code);
3015 void ProcessConstraints();
3016 bool BacktrackOneLevel(
Decision** fail_decision);
3017 void JumpToSentinelWhenNested();
3018 void JumpToSentinel();
3019 void check_alloc_state();
3021 void EnqueueVar(
Demon*
const d);
3022 void EnqueueDelayedDemon(
Demon*
const d);
3025 void UnfreezeQueue();
3026 void reset_action_on_fail();
3027 void set_action_on_fail(
Action a);
3028 void set_variable_to_clean_on_fail(
IntVar* v);
3029 void IncrementUncheckedSolutionCounter();
3030 bool IsUncheckedSolutionLimitReached();
3032 void InternalSaveValue(
int* valptr);
3033 void InternalSaveValue(int64_t* valptr);
3034 void InternalSaveValue(uint64_t* valptr);
3035 void InternalSaveValue(
double* valptr);
3036 void InternalSaveValue(
bool* valptr);
3037 void InternalSaveValue(
void** valptr);
3038 void InternalSaveValue(int64_t** valptr) {
3039 InternalSaveValue(
reinterpret_cast<void**
>(valptr));
3042 BaseObject* SafeRevAlloc(BaseObject* ptr);
3044 int* SafeRevAllocArray(
int* ptr);
3045 int64_t* SafeRevAllocArray(int64_t* ptr);
3046 uint64_t* SafeRevAllocArray(uint64_t* ptr);
3047 double* SafeRevAllocArray(
double* ptr);
3048 BaseObject** SafeRevAllocArray(BaseObject** ptr);
3050 IntExpr** SafeRevAllocArray(IntExpr** ptr);
3054 void* UnsafeRevAllocAux(
void* ptr);
3056 T* UnsafeRevAlloc(T* ptr) {
3057 return reinterpret_cast<T*
>(
3058 UnsafeRevAllocAux(
reinterpret_cast<void*
>(ptr)));
3060 void** UnsafeRevAllocArrayAux(
void** ptr);
3062 T** UnsafeRevAllocArray(T** ptr) {
3063 return reinterpret_cast<T**
>(
3064 UnsafeRevAllocArrayAux(
reinterpret_cast<void**
>(ptr)));
3067 void InitCachedIntConstants();
3068 void InitCachedConstraint();
3073 Search* TopLevelSearch()
const {
return searches_.at(1); }
3077 Search* ParentSearch()
const {
3078 const size_t search_size = searches_.size();
3080 return searches_[search_size - 2];
3089 int GetNewIntVarIndex() {
return num_int_vars_++; }
3092 bool IsADifference(IntExpr* expr, IntExpr**
const left,
3093 IntExpr**
const right);
3095 const std::string name_;
3096 const ConstraintSolverParameters parameters_;
3097 absl::flat_hash_map<const PropagationBaseObject*, std::string>
3098 propagation_object_names_;
3099 absl::flat_hash_map<const PropagationBaseObject*, IntegerCastInfo>
3101 absl::flat_hash_set<const Constraint*> cast_constraints_;
3102 const std::string empty_name_;
3103 std::unique_ptr<Queue> queue_;
3104 std::unique_ptr<Trail> trail_;
3105 std::vector<Constraint*> constraints_list_;
3106 std::vector<Constraint*> additional_constraints_list_;
3107 std::vector<int> additional_constraints_parent_list_;
3114 int64_t filtered_neighbors_;
3115 int64_t accepted_neighbors_;
3117 std::unique_ptr<ClockTimer> timer_;
3118 std::vector<Search*> searches_;
3119 std::mt19937 random_;
3120 uint64_t fail_stamp_;
3121 std::unique_ptr<Decision> balancing_decision_;
3123 std::function<void()> fail_intercept_;
3127 bool use_fast_local_search_;
3131 std::unique_ptr<Assignment> local_search_state_;
3134 enum { MIN_CACHED_INT_CONST = -8, MAX_CACHED_INT_CONST = 8 };
3135 IntVar* cached_constants_[MAX_CACHED_INT_CONST + 1 - MIN_CACHED_INT_CONST];
3141 std::unique_ptr<Decision> fail_decision_;
3142 int constraint_index_;
3143 int additional_constraint_index_;
3146 std::unique_ptr<ModelCache> model_cache_;
3147 std::unique_ptr<PropagationMonitor> propagation_monitor_;
3148 PropagationMonitor* print_trace_;
3149 std::unique_ptr<LocalSearchMonitor> local_search_monitor_;
3150 int anonymous_variable_index_;
3156std::ostream&
operator<<(std::ostream& out,
const Solver*
const s);
3164inline int64_t
One() {
return 1; }
3179std::ostream&
operator<<(std::ostream& out,
const BaseObject* o);
3190 if (
name().empty()) {
3191 return "PropagationBaseObject";
3193 return absl::StrFormat(
"PropagationBaseObject: %s",
name());
3218 solver_->set_action_on_fail(std::move(
a));
3227 solver_->set_variable_to_clean_on_fail(v);
3231 virtual std::string
name()
const;
3236 virtual std::string
BaseName()
const;
3261 DISALLOW_COPY_AND_ASSIGN(
Decision);
3272 bool start_with_lower_half);
3301 std::vector<SearchMonitor*>*
const extras);
3317 const std::string&
name()
const {
return name_; }
3322 std::vector<SearchMonitor*>*
const extras)
override;
3327 const std::string name_;
3368 void set_stamp(int64_t stamp) {
stamp_ = stamp; }
3369 uint64_t stamp()
const {
return stamp_; }
3569 const std::string& operation, int64_t
value,
3572 const std::string& operation,
3580 const std::vector<int64_t>& values);
3589 const std::string& arg_name,
const std::vector<IntVar*>& arguments);
3596 const std::string& arg_name,
const std::vector<IntervalVar*>& arguments);
3602 const std::string& arg_name,
const std::vector<SequenceVar*>& arguments);
3613 int64_t index_min, int64_t index_max);
3616 const std::string& arg_name, int64_t index_max);
3779 explicit Rev(
const T& val) : stamp_(0), value_(val) {}
3781 const T&
Value()
const {
return value_; }
3784 if (val != value_) {
3785 if (stamp_ < s->stamp()) {
3787 stamp_ = s->
stamp();
3822 : stamps_(new uint64_t[
size]), values_(new T[
size]), size_(
size) {
3823 for (
int i = 0; i <
size; ++i) {
3831 int64_t
size()
const {
return size_; }
3841 if (val != values_[
index]) {
3846 values_[
index] = val;
3851 std::unique_ptr<uint64_t[]> stamps_;
3852 std::unique_ptr<T[]> values_;
3883 virtual int64_t
Min()
const = 0;
3885 virtual int64_t
Max()
const = 0;
3890 virtual void Range(int64_t* l, int64_t* u) {
3907 virtual bool IsVar()
const {
return false; }
3936 DISALLOW_COPY_AND_ASSIGN(
IntExpr);
3964 virtual bool Ok()
const = 0;
3973 std::string
DebugString()
const override {
return "IntVar::Iterator"; }
3986 : it_(it), begin_was_called_(false) {
3993 DCHECK(!begin_was_called_);
3994 begin_was_called_ =
true;
4011 return it_->
Value();
4019 DCHECK(other.it_ == it_);
4032 IntVarIterator*
const it_;
4033 bool begin_was_called_;
4046 bool IsVar()
const override {
return true; }
4061 virtual void RemoveValues(
const std::vector<int64_t>& values);
4064 virtual void SetValues(
const std::vector<int64_t>& values);
4138 DISALLOW_COPY_AND_ASSIGN(
IntVar);
4149 std::string
DebugString()
const override {
return "SolutionCollector"; }
4153 void Add(
const std::vector<IntVar*>& vars);
4155 void Add(
const std::vector<IntervalVar*>& vars);
4157 void Add(
const std::vector<SequenceVar*>& vars);
4264 virtual std::string
Print()
const;
4312 return absl::StrFormat(
"SearchLimit(crossed = %i)", crossed_);
4316 void TopPeriodicCheck();
4333 bool Check()
override;
4334 void Init()
override;
4340 return duration_limit_ == absl::InfiniteDuration()
4352 return solver_time_at_limit_start_ + duration_limit_;
4359 absl::Duration TimeElapsed();
4360 static int64_t GetPercent(int64_t
value, int64_t offset, int64_t total) {
4361 return (total > 0 && total <
kint64max) ? 100 * (
value - offset) / total
4365 absl::Duration duration_limit_;
4366 absl::Time solver_time_at_limit_start_;
4367 absl::Duration last_time_elapsed_;
4368 int64_t check_count_;
4369 int64_t next_check_;
4370 bool smart_time_check_;
4372 int64_t branches_offset_;
4374 int64_t failures_offset_;
4376 int64_t solutions_offset_;
4399 double objective_scaling_factor,
4400 double objective_offset,
4401 double improvement_rate_coefficient,
4402 int improvement_rate_solutions_distance);
4406 bool Check()
override;
4408 void Init()
override;
4413 double objective_scaling_factor_;
4414 double objective_offset_;
4415 double improvement_rate_coefficient_;
4416 int improvement_rate_solutions_distance_;
4418 double best_objective_;
4420 std::deque<std::pair<double, int64_t> > improvements_;
4423 bool objective_updated_;
4424 bool gradient_stage_;
4594 const std::vector<IntVar*>& nexts,
const std::string&
name);
4603 void DurationRange(int64_t*
const dmin, int64_t*
const dmax)
const;
4607 void HorizonRange(int64_t*
const hmin, int64_t*
const hmax)
const;
4615 int*
const unperformed)
const;
4637 std::vector<int>*
const possible_lasts);
4645 const std::vector<int>& rank_last,
4646 const std::vector<int>& unperformed);
4657 std::vector<int>*
const rank_last,
4658 std::vector<int>*
const unperformed)
const;
4667 int64_t
size()
const {
return intervals_.size(); }
4673 int ComputeForwardFrontier();
4674 int ComputeBackwardFrontier();
4675 void UpdatePrevious()
const;
4677 const std::vector<IntervalVar*> intervals_;
4678 const std::vector<IntVar*> nexts_;
4679 mutable std::vector<int> previous_;
4707 if (var_ !=
nullptr) {
4711 void LoadFromProto(
const IntVarAssignment& int_var_assignment_proto);
4712 void WriteToProto(IntVarAssignment* int_var_assignment_proto)
const;
4714 int64_t
Min()
const {
return min_; }
4716 int64_t
Max()
const {
return max_; }
4723 bool Bound()
const {
return (max_ == min_); }
4736 return !(*
this == element);
4756 const IntervalVarAssignment& interval_var_assignment_proto);
4757 void WriteToProto(IntervalVarAssignment* interval_var_assignment_proto)
const;
4768 CHECK_EQ(duration_max_, duration_min_);
4769 return duration_max_;
4780 CHECK_EQ(performed_max_, performed_min_);
4781 return performed_max_;
4816 performed_min_ = mi;
4817 performed_max_ = ma;
4824 return (start_min_ == start_max_ && duration_min_ == duration_max_ &&
4825 end_min_ == end_max_ && performed_min_ == performed_max_);
4830 return !(*
this == element);
4836 int64_t duration_min_;
4837 int64_t duration_max_;
4840 int64_t performed_min_;
4841 int64_t performed_max_;
4869 const SequenceVarAssignment& sequence_var_assignment_proto);
4870 void WriteToProto(SequenceVarAssignment* sequence_var_assignment_proto)
const;
4875 void SetSequence(
const std::vector<int>& forward_sequence,
4876 const std::vector<int>& backward_sequence,
4877 const std::vector<int>& unperformed);
4882 return forward_sequence_.size() + unperformed_.size() == var_->
size();
4889 return !(*
this == element);
4893 bool CheckClassInvariants();
4896 std::vector<int> forward_sequence_;
4897 std::vector<int> backward_sequence_;
4898 std::vector<int> unperformed_;
4901template <
class V,
class E>
4911 return &elements_[
index];
4917 elements_.emplace_back(
var);
4918 return &elements_.back();
4923 elements_[position].Reset(
var);
4924 return &elements_[position];
4928 if (!elements_map_.empty()) {
4929 elements_map_.clear();
4934 void Resize(
size_t size) { elements_.resize(size); }
4935 bool Empty()
const {
return elements_.empty(); }
4939 for (
int i = 0; i < container.elements_.size(); ++i) {
4940 const E& element = container.elements_[i];
4941 const V*
const var = element.Var();
4943 if (i < elements_.size() && elements_[i].Var() ==
var) {
4949 E*
const local_element = &elements_[
index];
4950 local_element->Copy(element);
4951 if (element.Activated()) {
4952 local_element->Activate();
4954 local_element->Deactivate();
4962 for (
int i = 0; i < container.elements_.size(); ++i) {
4963 const E& element = container.elements_[i];
4964 FastAdd(element.Var())->Copy(element);
4973 DCHECK(element !=
nullptr)
4974 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
4986 DCHECK(element !=
nullptr)
4987 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
4997 const std::vector<E>&
elements()
const {
return elements_; }
5000 int Size()
const {
return elements_.size(); }
5002 for (E& element : elements_) {
5007 for (E& element : elements_) {
5008 if (element.Activated()) {
5014 for (
const E& element : elements_) {
5015 if (!element.Bound())
return false;
5029 EnsureMapIsUpToDate();
5033 for (
const E& element : container.elements_) {
5034 const int position =
5036 if (position < 0 || elements_[position] != element) {
5043 return !(*
this == container);
5047 void EnsureMapIsUpToDate()
const {
5048 absl::flat_hash_map<const V*, int>* map =
5049 const_cast<absl::flat_hash_map<const V*, int>*
>(&elements_map_);
5050 for (
int i = map->size(); i < elements_.size(); ++i) {
5051 (*map)[elements_[i].Var()] = i;
5054 bool Find(
const V*
const var,
int*
index)
const {
5056 const size_t kMaxSizeForLinearAccess = 11;
5057 if (
Size() <= kMaxSizeForLinearAccess) {
5061 for (
int i = 0; i < elements_.size(); ++i) {
5062 if (
var == elements_[i].Var()) {
5069 EnsureMapIsUpToDate();
5070 DCHECK_EQ(elements_map_.size(), elements_.size());
5075 std::vector<E> elements_;
5076 absl::flat_hash_map<const V*, int> elements_map_;
5095 return int_var_container_.
Empty() && interval_var_container_.
Empty() &&
5096 sequence_var_container_.
Empty();
5109 bool Load(
const std::string& filename);
5113 void Load(
const AssignmentProto& assignment_proto);
5115 bool Save(
const std::string& filename)
const;
5119 void Save(AssignmentProto*
const assignment_proto)
const;
5135 void Add(
const std::vector<IntVar*>& vars);
5148 void Add(
const std::vector<IntervalVar*>& vars);
5181 void Add(
const std::vector<SequenceVar*>& vars);
5188 const std::vector<int>& forward_sequence,
5189 const std::vector<int>& backward_sequence,
5190 const std::vector<int>& unperformed);
5192 const std::vector<int>& forward_sequence);
5194 const std::vector<int>& backward_sequence);
5196 const std::vector<int>& unperformed);
5235 return interval_var_container_;
5238 return &interval_var_container_;
5241 return sequence_var_container_;
5244 return &sequence_var_container_;
5247 return int_var_container_ == assignment.int_var_container_ &&
5248 interval_var_container_ == assignment.interval_var_container_ &&
5249 sequence_var_container_ == assignment.sequence_var_container_ &&
5250 objective_element_ == assignment.objective_element_;
5253 return !(*
this == assignment);
5265 const Assignment& assignment);
5273 const std::vector<IntVar*>& target_vars,
5274 const Assignment* source_assignment,
5275 const std::vector<IntVar*>& source_vars);
5279 Pack(
Solver*
const s,
const std::vector<IntVar*>& vars,
int number_of_bins);
5292 const std::vector<int64_t>& weights,
const std::vector<int64_t>&
bounds);
5311 const std::vector<IntVar*>& loads);
5317 const std::vector<IntVar*>& loads);
5329 const std::vector<IntVar*>& usage,
const std::vector<int64_t>&
capacity);
5344 void Post()
override;
5351 bool IsUndecided(
int var_index,
int bin_index)
const;
5353 void Assign(
int var_index,
int bin_index);
5355 bool IsPossible(
int var_index,
int bin_index)
const;
5367 bool IsInProcess()
const;
5368 const std::vector<IntVar*> vars_;
5370 std::vector<Dimension*> dims_;
5371 std::unique_ptr<RevBitMatrix> unprocessed_;
5372 std::vector<std::vector<int>> forced_;
5373 std::vector<std::vector<int>> removed_;
5374 std::vector<IntVarIterator*> holes_;
5377 std::vector<std::pair<int, int>> to_set_;
5378 std::vector<std::pair<int, int>> to_unset_;
5385 const std::vector<IntervalVar*>& intervals,
5386 const std::string&
name);
5404 virtual const std::vector<IntVar*>&
nexts()
const = 0;
5405 virtual const std::vector<IntVar*>&
actives()
const = 0;
#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
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
E * MutableElementOrNull(const V *const var)
bool Contains(const V *const var) const
const E & Element(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...
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(const V *const var)
void CopyIntersection(const AssignmentContainer< V, E > &container)
Copies the elements of 'container' which are already in the calling container.
const E & Element(int index) const
E * FastAdd(V *var)
Adds element without checking its presence in the container.
const std::vector< E > & elements() const
void Resize(size_t size)
Advanced usage: Resizes the container, potentially adding elements with null variables.
E * MutableElement(int index)
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)
int64_t EndMin(const IntervalVar *const var) const
int64_t PerformedMin(const IntervalVar *const var) const
int64_t EndMax(const IntervalVar *const var) const
SequenceContainer * MutableSequenceVarContainer()
void SetBackwardSequence(const SequenceVar *const var, const std::vector< int > &backward_sequence)
int64_t StartMax(const IntervalVar *const var) 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 IntervalContainer & IntervalVarContainer() 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)
IntervalContainer * MutableIntervalVarContainer()
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)
const SequenceContainer & SequenceVarContainer() const
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)
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)
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)
IntContainer * MutableIntVarContainer()
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)
bool Bound(const IntVar *const var) const
std::string DebugString() const override
const IntContainer & IntVarContainer() const
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...
~CastConstraint() override
IntVar *const target_var_
IntVar * target_var() const
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.
std::string GetName() const
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
void set_name(const std::string &name)
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_slacks() const =0
virtual SequenceVar * MakeSequenceVar()=0
Creates a sequence variable from the constraint.
virtual const std::vector< IntVar * > & actives() const =0
int64_t TransitionTime(int before_index, int after_index)
virtual const std::vector< IntVar * > & nexts() const =0
virtual const std::vector< IntVar * > & time_cumuls() const =0
~DisjunctiveConstraint() override
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.
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 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 IntVar * Var()=0
Creates a variable from the expression.
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.
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 IntVarIterator * MakeHoleIterator(bool reversible) const =0
Creates a hole iterator.
virtual IntVar * IsEqual(int64_t constant)=0
IsEqual.
virtual void WhenBound(Demon *d)=0
This method attaches a demon that will be awakened when the variable is bound.
virtual IntVar * IsLessOrEqual(int64_t constant)=0
void WhenDomain(Solver::Closure closure)
This method attaches a closure that will watch any domain modification of the domain of the variable.
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.
IntVar * Var() override
Creates a variable from the expression.
virtual void RemoveInterval(int64_t l, int64_t u)=0
This method removes the interval 'l' .
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 IntVarIterator * MakeDomainIterator(bool reversible) const =0
Creates a domain iterator.
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 * DurationExpr()=0
virtual IntExpr * PerformedExpr()=0
void WhenAnything(Solver::Closure closure)
Attaches a closure awakened when anything about this interval changes.
void WhenStartBound(Solver::Closure closure)
virtual IntExpr * SafeDurationExpr(int64_t unperformed_value)=0
virtual IntExpr * SafeStartExpr(int64_t unperformed_value)=0
These methods create expressions encapsulating the start, end and duration of the interval var.
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 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
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 int64_t StartMin() const =0
These methods query, set, and watch the start position of the interval var.
void WhenEndRange(Solver::Action action)
void WhenStartRange(Solver::Closure closure)
virtual IntExpr * EndExpr()=0
virtual IntExpr * SafeEndExpr(int64_t unperformed_value)=0
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
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_
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.
IntVar * Var() const
Returns the variable that is optimized.
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)
ProfiledDecisionBuilder(DecisionBuilder *db)
const std::string & name() const
void AppendMonitors(Solver *const solver, std::vector< SearchMonitor * > *const extras) override
This method will be called at the start of the search.
~ProfiledDecisionBuilder() override
void Accept(ModelVisitor *const visitor) const override
Decision * Next(Solver *const solver) override
This is the main method of the decision builder class.
std::string DebugString() const override
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 & operator[](int index) const
const T & Value(int index) const
RevArray(int size, const T &val)
void SetValue(Solver *const s, int index, const T &val)
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.
virtual SearchLimit * MakeClone() const =0
Allocates a clone of the limit.
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.
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()
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)
SequenceVar * Var() const
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.
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.
DecisionBuilder * MakeProfiledDecisionBuilderWrapper(DecisionBuilder *db)
Activates profiling on a decision builder.
ABSL_MUST_USE_RESULT 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.
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()
ABSL_MUST_USE_RESULT 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)
Decision * MakeAssignVariablesValuesOrFail(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
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
DemonProfiler * demon_profiler() const
Access to demon profiler.
ABSL_MUST_USE_RESULT RegularLimit * MakeFailuresLimit(int64_t failures)
Creates a search limit that constrains the number of failures that can happen when exploring the sear...
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.
ABSL_MUST_USE_RESULT RegularLimit * MakeBranchesLimit(int64_t branches)
Creates a search limit that constrains the number of branches explored in the search tree.
ABSL_MUST_USE_RESULT RegularLimit * MakeTimeLimit(int64_t time_in_ms)
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)
ABSL_MUST_USE_RESULT RegularLimit * MakeLimit(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check=false, bool cumulative=false)
Limits the search with the 'time', 'branches', 'failures' and 'solutions' limits.
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
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...
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.
Decision * MakeAssignVariablesValuesOrDoNothing(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
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,...
ABSL_MUST_USE_RESULT ImprovementSearchLimit * MakeImprovementLimit(IntVar *objective_var, bool maximize, double objective_scaling_factor, double objective_offset, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
Limits the search based on the improvements of 'objective_var'.
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.
ABSL_MUST_USE_RESULT 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)
Decision * balancing_decision() const
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.
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.
T * RevAllocArray(T *object)
Like RevAlloc() above, but for an array of objects: the array must have been allocated with the new[]...
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)
Constraint * MakePathPrecedenceConstraint(std::vector< IntVar * > nexts, const std::vector< std::pair< int, int > > &precedences)
Constraint enforcing, for each pair (i,j) in precedences, i to be before j in paths defined by next v...
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())
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
T * RevAlloc(T *object)
Registers the given object as being reversible.
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.
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)
class ABSL_DEPRECATED("Use the direct methods instead") MPSReader
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,...