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/log/check.h"
90#include "absl/random/random.h"
91#include "absl/strings/str_format.h"
92#include "absl/strings/string_view.h"
93#include "absl/time/time.h"
94#include "absl/types/span.h"
99#include "ortools/constraint_solver/search_stats.pb.h"
100#include "ortools/constraint_solver/solver_parameters.pb.h"
115class AssignmentProto;
120class DecisionBuilder;
121class DecisionVisitor;
125class DisjunctiveConstraint;
126class ImprovementSearchLimit;
129class IntVarAssignment;
130class IntVarLocalSearchFilter;
132class IntervalVarAssignment;
134class LocalSearchFilter;
135class LocalSearchFilterManager;
136class LocalSearchMonitor;
137class LocalSearchOperator;
138class LocalSearchPhaseParameters;
139class LocalSearchProfiler;
142class ObjectiveMonitor;
145class ProfiledDecisionBuilder;
146class PropagationBaseObject;
147class PropagationMonitor;
150class RegularLimitParameters;
156class SequenceVarAssignment;
157class SolutionCollector;
159class SymmetryBreaker;
165class LightIntFunctionElementCt;
167class LightIntIntFunctionElementCt;
170 return absl::GetFlag(FLAGS_cp_random_seed) == -1
171 ? absl::Uniform<int64_t>(absl::BitGen(), 0,
kint64max)
172 :
absl::GetFlag(FLAGS_cp_random_seed);
260 struct IntegerCastInfo {
777 typedef std::function<int64_t(int64_t, int64_t, int64_t)>
IndexEvaluator3;
783 typedef std::function<int64_t(
Solver* solver,
784 const std::vector<IntVar*>& vars,
785 int64_t first_unbound, int64_t last_unbound)>
788 typedef std::function<int64_t(
const IntVar* v, int64_t
id)>
790 typedef std::function<bool(int64_t, int64_t, int64_t)>
795 typedef std::function<void()>
Closure;
810 ConstraintSolverParameters
parameters()
const {
return parameters_; }
826 InternalSaveValue(o);
841 template <
typename T>
843 return reinterpret_cast<T*
>(SafeRevAlloc(
object));
852 template <
typename T>
854 return reinterpret_cast<T*
>(SafeRevAllocArray(
object));
938 bool Solve(DecisionBuilder* db,
const std::vector<SearchMonitor*>& monitors);
939 bool Solve(DecisionBuilder* db);
958 const std::vector<SearchMonitor*>& monitors);
981 const std::vector<SearchMonitor*>& monitors);
1021 absl::Time
Now()
const;
1028 int64_t
branches()
const {
return branches_; }
1040 int64_t
failures()
const {
return fails_; }
1043 int64_t
neighbors()
const {
return neighbors_; }
1058 uint64_t
stamp()
const;
1067 const std::string&
context()
const {
return context_; }
1071 return optimization_direction_;
1074 optimization_direction_ = direction;
1090 const std::string&
name);
1120 const std::string&
name, std::vector<IntVar*>* vars);
1124 std::vector<IntVar*>* vars);
1127 const std::string&
name);
1133 std::vector<IntVar*>* vars);
1151 const std::vector<int64_t>& coefs);
1154 const std::vector<int>& coefs);
1206 int64_t range_end,
IntVar* argument);
1220 template <
typename F>
1222 std::function<
bool()> deep_serialize =
nullptr) {
1224 this,
var,
index, std::move(values), std::move(deep_serialize)));
1233 template <
typename F>
1236 std::function<
bool()> deep_serialize =
nullptr) {
1238 this,
var, index1, index2, std::move(values),
1239 std::move(deep_serialize)));
1270 int64_t early_date, int64_t late_date,
1295 int64_t unperformed_value);
1415 const std::vector<int64_t>& coeffs,
1418 const std::vector<int>& coeffs,
1487 const std::vector<int64_t>& values);
1492 std::vector<int64_t> ends);
1495 std::vector<int> ends);
1522 const std::vector<int64_t>& values,
1523 const std::vector<IntVar*>& cards);
1526 const std::vector<int>& values,
1527 const std::vector<IntVar*>& cards);
1530 const std::vector<IntVar*>& cards);
1534 int64_t card_max, int64_t card_size);
1539 const std::vector<int64_t>& card_min,
1540 const std::vector<int64_t>& card_max);
1545 const std::vector<int>& card_min,
1546 const std::vector<int>& card_max);
1551 const std::vector<int64_t>& values,
1552 const std::vector<int64_t>& card_min,
1553 const std::vector<int64_t>& card_max);
1558 const std::vector<int>& values,
1559 const std::vector<int>& card_min,
1560 const std::vector<int>& card_max);
1567 IntVar* deviation_var, int64_t total_sum);
1577 bool stronger_propagation);
1582 int64_t escape_value);
1601 const std::vector<IntVar*>& sorted);
1609 const std::vector<IntVar*>& right);
1614 const std::vector<IntVar*>& right);
1621 std::vector<IntVar*> right,
1622 std::vector<int64_t> offsets);
1626 std::vector<IntVar*> left, std::vector<IntVar*> right,
1627 std::vector<int64_t> offsets,
IntVar* boolvar);
1634 const std::vector<IntVar*>& left,
const std::vector<IntVar*>& right);
1651 const std::vector<IntVar*>& second_vars);
1659 const std::vector<IntVar*>& second_vars,
1660 int64_t escape_value);
1675 const std::vector<IntVar*>& active,
1678 const std::vector<IntVar*>& active,
1693 const std::vector<IntVar*>& active,
1694 const std::vector<IntVar*>& cumuls,
1695 const std::vector<IntVar*>& transits);
1700 const std::vector<IntVar*>& active,
1701 const std::vector<IntVar*>& cumuls,
1702 const std::vector<IntVar*>& transits);
1710 const std::vector<IntVar*>& active,
1711 const std::vector<IntVar*>& cumuls,
1721 const std::vector<IntVar*>& active,
1722 const std::vector<IntVar*>& cumuls,
1723 const std::vector<IntVar*>& slacks,
1730 std::vector<int64_t> sources,
1731 std::vector<int64_t> sinks,
1732 std::vector<IntVar*>
status);
1740 std::vector<IntVar*> nexts,
1741 const std::vector<std::pair<int, int>>& precedences);
1751 std::vector<IntVar*> nexts,
1752 const std::vector<std::pair<int, int>>& precedences,
1753 absl::Span<const int> lifo_path_starts,
1754 absl::Span<const int> fifo_path_starts);
1758 std::vector<IntVar*> nexts, std::vector<IntVar*> transits,
1759 const std::vector<std::pair<int, int>>& precedences);
1775 std::vector<IntVar*>
nexts;
1776 std::vector<IntVar*>
paths;
1777 std::vector<IntVar*>
forces;
1783 std::vector<IntVar*>
costs;
1786 PathEnergyCostConstraintSpecification specification);
1791 Constraint* MakeMapDomain(IntVar* var, const std::vector<IntVar*>& actives);
1808 const std::vector<IntVar*>& vars,
const IntTupleSet& transition_table,
1809 int64_t initial_state,
const std::vector<int64_t>& final_states);
1820 int64_t initial_state,
1821 const std::vector<int>& final_states);
1823#if defined(SWIGPYTHON)
1826 const std::vector<IntVar*>& vars,
1827 const std::vector<std::vector<int64_t> >& raw_tuples) {
1829 tuples.InsertAll(raw_tuples);
1834 const std::vector<IntVar*>& vars,
1835 const std::vector<std::vector<int64_t> >&
1837 int64_t initial_state,
const std::vector<int>& final_states) {
1839 transitions.InsertAll(raw_transitions);
1854 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1855 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1857 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1858 absl::Span<const int64_t> x_size, absl::Span<const int64_t> y_size);
1860 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1861 absl::Span<const int> x_size, absl::Span<const int> y_size);
1872 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1873 const std::vector<IntVar*>& x_size,
const std::vector<IntVar*>& y_size);
1875 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1876 absl::Span<const int64_t> x_size, absl::Span<const int64_t> y_size);
1878 const std::vector<IntVar*>& x_vars,
const std::vector<IntVar*>& y_vars,
1879 absl::Span<const int> x_size, absl::Span<const int> y_size);
1886 Pack*
MakePack(
const std::vector<IntVar*>& vars,
int number_of_bins);
1895 const std::string&
name);
1902 std::vector<IntervalVar*>* array);
1908 const std::string&
name);
1914 IntVar* performed_variable,
1915 const std::string&
name);
1920 const std::vector<IntVar*>& start_variables, int64_t duration,
1921 absl::string_view
name, std::vector<IntervalVar*>* array);
1926 const std::vector<IntVar*>& start_variables,
1927 absl::Span<const int64_t> durations, absl::string_view
name,
1928 std::vector<IntervalVar*>* array);
1932 const std::vector<IntVar*>& start_variables,
1933 absl::Span<const int> durations, absl::string_view
name,
1934 std::vector<IntervalVar*>* array);
1939 const std::vector<IntVar*>& start_variables,
1940 absl::Span<const int64_t> durations,
1941 const std::vector<IntVar*>& performed_variables, absl::string_view
name,
1942 std::vector<IntervalVar*>* array);
1947 const std::vector<IntVar*>& start_variables,
1948 absl::Span<const int> durations,
1949 const std::vector<IntVar*>& performed_variables, absl::string_view
name,
1950 std::vector<IntervalVar*>* array);
1954 const std::string&
name);
1959 int64_t duration_min, int64_t duration_max,
1961 const std::string&
name);
1966 int64_t duration_min, int64_t duration_max,
1968 absl::string_view
name,
1969 std::vector<IntervalVar*>* array);
1980 IntervalVar* interval_var, int64_t duration, int64_t offset);
1987 IntervalVar* interval_var, int64_t duration, int64_t offset);
1994 IntervalVar* interval_var, int64_t duration, int64_t offset);
2001 IntervalVar* interval_var, int64_t duration, int64_t offset);
2071 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
2077 const std::vector<IntervalVar*>& intervals,
const std::string&
name);
2089 const std::vector<int64_t>& demands,
2090 int64_t capacity,
const std::string&
name);
2102 const std::vector<int>& demands, int64_t capacity,
2103 const std::string&
name);
2115 const std::vector<int64_t>& demands,
2128 const std::vector<int>& demands,
IntVar* capacity,
2129 const std::string&
name);
2139 const std::vector<IntVar*>& demands,
2140 int64_t capacity,
const std::string&
name);
2150 const std::vector<IntVar*>& demands,
2187 const Assignment* assignment,
bool maximize);
2191 const Assignment* assignment, std::vector<bool> maximize);
2201 std::vector<bool> maximize);
2207 const Assignment* assignment,
int solution_count,
bool maximize);
2213 const Assignment* assignment,
int solution_count,
2214 std::vector<bool> maximize);
2216 int solution_count, std::vector<bool> maximize);
2236 const std::vector<int64_t>& weights,
2242 const std::vector<int>& weights,
2247 const std::vector<int64_t>& weights,
2252 const std::vector<int>& weights,
2257 const std::vector<IntVar*>& sub_objectives,
2258 const std::vector<int64_t>& weights,
2263 const std::vector<IntVar*>& sub_objectives,
2264 const std::vector<int>& weights,
2270 std::vector<IntVar*> variables,
2271 std::vector<int64_t> steps);
2293 const std::vector<IntVar*>& vars,
2294 int64_t keep_tenure, int64_t forbid_tenure,
2295 double tabu_factor);
2298 const std::vector<bool>& maximize, std::vector<IntVar*> objectives,
2299 std::vector<int64_t> steps,
const std::vector<IntVar*>& vars,
2300 int64_t keep_tenure, int64_t forbid_tenure,
double tabu_factor);
2306 const std::vector<IntVar*>& tabu_vars,
2307 int64_t forbid_tenure);
2313 int64_t initial_temperature);
2315 const std::vector<bool>& maximize, std::vector<IntVar*> vars,
2316 std::vector<int64_t> steps, std::vector<int64_t> initial_temperatures);
2322 int64_t step,
const std::vector<IntVar*>& vars,
double penalty_factor,
2323 bool reset_penalties_on_new_best_solution =
false);
2326 int64_t step,
const std::vector<IntVar*>& vars,
2327 const std::vector<IntVar*>& secondary_vars,
double penalty_factor,
2328 bool reset_penalties_on_new_best_solution =
false);
2342 ABSL_DEPRECATED(
"Use the version taking absl::Duration() as argument")
2346 ? absl::InfiniteDuration()
2347 : absl::Milliseconds(time_in_ms));
2366 ABSL_MUST_USE_RESULT RegularLimit*
MakeLimit(absl::Duration
time,
2370 bool smart_time_check =
false,
2371 bool cumulative =
false);
2373 ABSL_MUST_USE_RESULT RegularLimit*
MakeLimit(
2374 const RegularLimitParameters&
proto);
2377 ABSL_DEPRECATED(
"Use other MakeLimit() versions")
2382 bool smart_time_check =
false,
2383 bool cumulative =
false);
2399 IntVar* objective_var,
bool maximize,
double objective_scaling_factor,
2400 double objective_offset,
double improvement_rate_coefficient,
2401 int improvement_rate_solutions_distance);
2404 ABSL_MUST_USE_RESULT ImprovementSearchLimit*
2406 std::vector<IntVar*> objective_vars, std::vector<bool> maximize,
2407 std::vector<double> objective_scaling_factors,
2408 std::vector<double> objective_offsets,
2409 double improvement_rate_coefficient,
2410 int improvement_rate_solutions_distance);
2415 std::function<
bool()> limiter);
2429 std::function<std::string()> display_callback);
2434 std::function<std::string()> display_callback);
2439 std::function<std::string()> display_callback);
2448 std::function<std::string()> display_callback);
2451 struct SearchLogParameters {
2490 absl::flat_hash_map<const IntVar*, int>* map);
2495 const std::vector<SymmetryBreaker*>& visitors);
2508 bool start_with_lower_half);
2512 const std::vector<int64_t>& values);
2514 const std::vector<IntVar*>& vars,
const std::vector<int64_t>& values);
2516 const std::vector<int64_t>& values);
2659 const std::vector<IntVar*>& vars);
2681 const std::vector<SearchMonitor*>& monitors);
2691 bool maximize, int64_t step);
2693 bool maximize, int64_t step,
2696 bool maximize, int64_t step,
2700 bool maximize, int64_t step,
2705 bool maximize, int64_t step,
2712 const std::vector<SearchMonitor*>& monitors);
2725 std::function<
const std::vector<int>&(
int,
int)> get_neighbors =
nullptr);
2727 const std::vector<IntVar*>& vars,
2729 std::function<
const std::vector<int>&(
int,
int)> get_neighbors =
nullptr);
2736 const std::vector<IntVar*>& secondary_vars,
2748 int number_of_variables);
2750 int number_of_variables,
2767 const std::vector<IntVar*>& variables,
2768 const std::vector<int64_t>& target_values);
2801 const std::vector<LocalSearchOperator*>& ops);
2803 const std::vector<LocalSearchOperator*>& ops,
bool restart);
2805 const std::vector<LocalSearchOperator*>& ops,
2806 std::function<int64_t(
int,
int)> evaluator);
2810 const std::vector<LocalSearchOperator*>& ops);
2816 const std::vector<LocalSearchOperator*>& ops, int32_t seed);
2826 const std::vector<LocalSearchOperator*>& ops,
double memory_coefficient,
2827 double exploration_coefficient,
bool maximize);
2886 const std::vector<SearchMonitor*>& monitors,
RegularLimit* limit,
2887 absl::flat_hash_set<IntVar*>* touched =
nullptr);
2923 const std::vector<IntVar*>& vars,
2963 InternalSaveValue(adr);
2972 InternalSaveValue(adr);
2980 return absl::Uniform<int64_t>(random_, 0,
size);
2986 return absl::Uniform<int32_t>(random_, 0,
size);
2990 void ReSeed(int32_t seed) { random_.seed(seed); }
3015 int constraints()
const {
return constraints_list_.size(); }
3018 void Accept(ModelVisitor* visitor)
const;
3025 fail_intercept_ = std::move(fail_intercept);
3035 use_fast_local_search_ = use_fast_local_search;
3109 template <
class K,
class V>
3137 if (!should_fail_)
return;
3138 should_fail_ =
false;
3149 void PushSentinel(
int magic_code);
3150 void BacktrackToSentinel(
int magic_code);
3151 void ProcessConstraints();
3153 void JumpToSentinelWhenNested();
3154 void JumpToSentinel();
3155 void check_alloc_state();
3161 void UnfreezeQueue();
3162 void reset_action_on_fail();
3163 void set_action_on_fail(
Action a);
3164 void set_variable_to_clean_on_fail(
IntVar* v);
3165 void IncrementUncheckedSolutionCounter();
3166 bool IsUncheckedSolutionLimitReached();
3168 void InternalSaveValue(
int* valptr);
3169 void InternalSaveValue(int64_t* valptr);
3170 void InternalSaveValue(uint64_t* valptr);
3171 void InternalSaveValue(
double* valptr);
3172 void InternalSaveValue(
bool* valptr);
3173 void InternalSaveValue(
void** valptr);
3174 void InternalSaveValue(int64_t** valptr) {
3175 InternalSaveValue(
reinterpret_cast<void**
>(valptr));
3180 int* SafeRevAllocArray(
int* ptr);
3181 int64_t* SafeRevAllocArray(int64_t* ptr);
3182 uint64_t* SafeRevAllocArray(uint64_t* ptr);
3183 double* SafeRevAllocArray(
double* ptr);
3190 void* UnsafeRevAllocAux(
void* ptr);
3192 T* UnsafeRevAlloc(T* ptr) {
3193 return reinterpret_cast<T*
>(
3194 UnsafeRevAllocAux(
reinterpret_cast<void*
>(ptr)));
3196 void** UnsafeRevAllocArrayAux(
void** ptr);
3198 T** UnsafeRevAllocArray(T** ptr) {
3199 return reinterpret_cast<T**
>(
3200 UnsafeRevAllocArrayAux(
reinterpret_cast<void**
>(ptr)));
3203 void InitCachedIntConstants();
3204 void InitCachedConstraint();
3209 Search* TopLevelSearch()
const {
return searches_.at(1); }
3213 Search* ParentSearch()
const {
3214 const size_t search_size = searches_.size();
3215 DCHECK_GT(search_size, 1);
3216 return searches_[search_size - 2];
3219 template <
bool is_profile_active>
3220 Assignment* RunUncheckedLocalSearchInternal(
3221 const Assignment* initial_solution,
3222 LocalSearchFilterManager* filter_manager,
3223 LocalSearchOperator* ls_operator,
3224 const std::vector<SearchMonitor*>& monitors, RegularLimit* limit,
3225 absl::flat_hash_set<IntVar*>* touched);
3233 int GetNewIntVarIndex() {
return num_int_vars_++; }
3236 bool IsADifference(IntExpr* expr, IntExpr** left, IntExpr** right);
3238 const std::string name_;
3239 const ConstraintSolverParameters parameters_;
3240 absl::flat_hash_map<const PropagationBaseObject*, std::string>
3241 propagation_object_names_;
3242 absl::flat_hash_map<const PropagationBaseObject*, IntegerCastInfo>
3244 absl::flat_hash_set<const Constraint*> cast_constraints_;
3245 const std::string empty_name_;
3246 std::unique_ptr<Queue> queue_;
3247 std::unique_ptr<Trail> trail_;
3248 std::vector<Constraint*> constraints_list_;
3249 std::vector<Constraint*> additional_constraints_list_;
3250 std::vector<int> additional_constraints_parent_list_;
3257 int64_t filtered_neighbors_;
3258 int64_t accepted_neighbors_;
3259 std::string context_;
3261 std::unique_ptr<ClockTimer> timer_;
3262 std::vector<Search*> searches_;
3263 std::mt19937 random_;
3264 uint64_t fail_stamp_;
3265 std::unique_ptr<Decision> balancing_decision_;
3267 std::function<void()> fail_intercept_;
3271 bool use_fast_local_search_;
3275 std::unique_ptr<Assignment> local_search_state_;
3278 enum { MIN_CACHED_INT_CONST = -8, MAX_CACHED_INT_CONST = 8 };
3279 IntVar* cached_constants_[MAX_CACHED_INT_CONST + 1 - MIN_CACHED_INT_CONST];
3285 std::unique_ptr<Decision> fail_decision_;
3286 int constraint_index_;
3287 int additional_constraint_index_;
3290 std::unique_ptr<ModelCache> model_cache_;
3291 std::unique_ptr<PropagationMonitor> propagation_monitor_;
3292 PropagationMonitor* print_trace_;
3293 std::unique_ptr<LocalSearchMonitor> local_search_monitor_;
3294 int anonymous_variable_index_;
3298std::ostream&
operator<<(std::ostream& out,
const Solver*
const s);
3303inline int64_t
Zero() {
return 0; }
3306inline int64_t
One() {
return 1; }
3321 virtual std::string
DebugString()
const {
return "BaseObject"; }
3324std::ostream&
operator<<(std::ostream& out,
const BaseObject* o);
3329class PropagationBaseObject :
public BaseObject {
3341 if (
name().empty()) {
3342 return "PropagationBaseObject";
3344 return absl::StrFormat(
"PropagationBaseObject: %s",
name());
3347 Solver*
solver()
const {
return solver_; }
3361 void EnqueueVar(Demon*
const d) { solver_->EnqueueVar(d); }
3369 solver_->set_action_on_fail(std::move(
a));
3378 solver_->set_variable_to_clean_on_fail(v);
3382 virtual std::string
name()
const;
3412 std::string
DebugString()
const override {
return "Decision"; }
3431 bool start_with_lower_half);
3455 virtual Decision*
Next(Solver* s) = 0;
3463 std::vector<SearchMonitor*>* extras);
3478 const std::string&
name()
const {
return name_; }
3479 double seconds()
const {
return seconds_; }
3480 Decision*
Next(Solver* solver)
override;
3483 std::vector<SearchMonitor*>* extras)
override;
3488 const std::string name_;
3507 Demon() : stamp_(uint64_t{0}) {}
3536 uint64_t
stamp()
const {
return stamp_; }
3541class ModelVisitor :
public BaseObject {
3544 static const char kAbs[];
3555 static const char kCover[];
3586 static const char kLess[];
3591 static const char kMax[];
3594 static const char kMin[];
3735 const std::string& operation, int64_t
value,
3738 const std::string& operation,
3745 const std::vector<int64_t>& values);
3754 const std::string& arg_name,
const std::vector<IntVar*>& arguments);
3761 const std::string& arg_name,
const std::vector<IntervalVar*>& arguments);
3767 const std::string& arg_name,
const std::vector<SequenceVar*>& arguments);
3778 int64_t index_min, int64_t index_max);
3781 const std::string& arg_name, int64_t index_max);
3804 virtual void Post() = 0;
3816 virtual void Accept(ModelVisitor* visitor)
const;
3824 virtual IntVar*
Var();
3830class CastConstraint :
public Constraint {
3845class SearchMonitor :
public BaseObject {
3932 virtual void Accept(ModelVisitor* visitor)
const;
3939 Solver*
solver()
const {
return solver_; }
3945 Solver*
const solver_;
3956 explicit Rev(
const T& val) : stamp_(0), value_(val) {}
3958 const T&
Value()
const {
return value_; }
3960 void SetValue(Solver*
const s,
const T& val) {
3961 if (val != value_) {
3962 if (stamp_ < s->
stamp()) {
3963 s->SaveValue(&value_);
3964 stamp_ = s->stamp();
3977class NumericalRev :
public Rev<T> {
3981 void Add(
Solver*
const s,
const T& to_add) {
3985 void Incr(Solver*
const s) {
Add(s, 1); }
3999 : stamps_(
new uint64_t[
size]), values_(
new T[
size]), size_(
size) {
4000 for (
int i = 0; i <
size; ++i) {
4008 int64_t
size()
const {
return size_; }
4018 if (val != values_[
index]) {
4023 values_[
index] = val;
4028 std::unique_ptr<uint64_t[]> stamps_;
4029 std::unique_ptr<T[]> values_;
4066 virtual int64_t
Min()
const = 0;
4068 virtual int64_t
Max()
const = 0;
4069 virtual void SetMax(int64_t m) = 0;
4073 virtual void Range(int64_t* l, int64_t* u) {
4078 virtual void SetRange(int64_t l, int64_t u) {
4087 virtual bool Bound()
const {
return (
Min() ==
Max()); }
4090 virtual bool IsVar()
const {
return false; }
4093 virtual IntVar*
Var() = 0;
4144 virtual bool Ok()
const = 0;
4153 std::string
DebugString()
const override {
return "IntVar::Iterator"; }
4163class InitAndGetValues {
4166 : it_(it), begin_was_called_(false) {
4173 DCHECK(!begin_was_called_);
4174 begin_was_called_ =
true;
4182 static Iterator
Begin(IntVarIterator* it) {
4183 return Iterator(it,
false);
4185 static Iterator
End(IntVarIterator* it) {
4186 return Iterator(it,
true);
4199 DCHECK(other.it == it);
4200 DCHECK(other.is_end);
4205 Iterator(
IntVarIterator* it,
bool is_end) : it(it), is_end(is_end) {}
4213 bool begin_was_called_;
4233 bool IsVar()
const override {
return true; }
4248 virtual void RemoveValues(
const std::vector<int64_t>& values);
4287 virtual uint64_t
Size()
const = 0;
4304 virtual int64_t
OldMin()
const = 0;
4307 virtual int64_t
OldMax()
const = 0;
4321 int index()
const {
return index_; }
4343 std::string
DebugString()
const override {
return "SolutionCollector"; }
4347 void Add(
const std::vector<IntVar*>& vars);
4349 void Add(
const std::vector<IntervalVar*>& vars);
4351 void Add(
const std::vector<SequenceVar*>& vars);
4442class ObjectiveMonitor :
public SearchMonitor {
4445 std::vector<IntVar*> vars, std::vector<int64_t> steps);
4461 int Size()
const {
return objective_vars_.size(); }
4465 void Accept(ModelVisitor* visitor)
const override;
4468 const std::vector<IntVar*>&
objective_vars()
const {
return objective_vars_; }
4470 return minimization_vars_;
4479 template <
typename T>
4485 for (
int i = 0; i <
Size(); ++i) {
4489 minimization_vars_, upper_bounds_, steps_));
4492 template <
typename T>
4501 for (
int i = 0; i <
Size(); ++i) {
4505 minimization_vars_, upper_bounds_, steps_,
status));
4515 const std::vector<IntVar*> objective_vars_;
4516 std::vector<IntVar*> minimization_vars_;
4517 std::vector<IntVar*> upper_bounds_;
4518 std::vector<int64_t> steps_;
4519 std::vector<int64_t> best_values_;
4520 std::vector<int64_t> current_values_;
4532 std::vector<IntVar*> vars, std::vector<int64_t> steps);
4548 virtual std::string
Name()
const;
4567 bool crossed()
const {
return crossed_; }
4579 virtual void Init() = 0;
4594 return absl::StrFormat(
"SearchLimit(crossed = %i)", crossed_);
4599 void TopPeriodicCheck();
4616 void Init()
override;
4622 return duration_limit_ == absl::InfiniteDuration()
4626 int64_t
branches()
const {
return branches_; }
4627 int64_t
failures()
const {
return failures_; }
4628 int64_t
solutions()
const {
return solutions_; }
4635 return solver_time_at_limit_start_ + duration_limit_;
4641 bool CheckTime(absl::Duration offset);
4642 absl::Duration TimeElapsed();
4643 static int64_t GetPercent(int64_t
value, int64_t offset, int64_t total) {
4648 absl::Duration duration_limit_;
4649 absl::Time solver_time_at_limit_start_;
4650 absl::Duration last_time_elapsed_;
4651 int64_t check_count_;
4652 int64_t next_check_;
4653 bool smart_time_check_;
4655 int64_t branches_offset_;
4657 int64_t failures_offset_;
4659 int64_t solutions_offset_;
4683 double objective_scaling_factor,
4684 double objective_offset,
4685 double improvement_rate_coefficient,
4686 int improvement_rate_solutions_distance);
4688 std::vector<bool> maximize,
4689 std::vector<double> objective_scaling_factors,
4690 std::vector<double> objective_offsets,
4691 double improvement_rate_coefficient,
4692 int improvement_rate_solutions_distance);
4698 void Init()
override;
4702 std::vector<IntVar*> objective_vars_;
4703 std::vector<bool> maximize_;
4704 std::vector<double> objective_scaling_factors_;
4705 std::vector<double> objective_offsets_;
4706 double improvement_rate_coefficient_;
4707 int improvement_rate_solutions_distance_;
4709 std::vector<double> best_objectives_;
4711 std::vector<std::deque<std::pair<double, int64_t> > > improvements_;
4713 std::vector<double> thresholds_;
4714 bool objective_updated_;
4715 bool gradient_stage_;
4748 virtual int64_t
StartMin()
const = 0;
4749 virtual int64_t
StartMax()
const = 0;
4802 virtual int64_t
EndMin()
const = 0;
4806 virtual void SetEndRange(int64_t mi, int64_t ma) = 0;
4888 const std::vector<IntVar*>& nexts,
const std::string&
name);
4930 std::vector<int>* possible_lasts);
4938 const std::vector<int>& rank_last,
4939 const std::vector<int>& unperformed);
4949 void FillSequence(std::vector<int>* rank_first, std::vector<int>* rank_last,
4950 std::vector<int>* unperformed)
const;
4959 int64_t
size()
const {
return intervals_.size(); }
4965 int ComputeForwardFrontier();
4966 int ComputeBackwardFrontier();
4967 void UpdatePrevious()
const;
4969 const std::vector<IntervalVar*> intervals_;
4970 const std::vector<IntVar*> nexts_;
4971 mutable std::vector<int> previous_;
4974class AssignmentElement {
4978 void Activate() { activated_ =
true; }
4980 bool Activated()
const {
return activated_; }
4986class IntVarElement :
public AssignmentElement {
4993 IntVar*
Var()
const {
return var_; }
4999 if (var_ !=
nullptr) {
5003 void LoadFromProto(
const IntVarAssignment& int_var_assignment_proto);
5004 void WriteToProto(IntVarAssignment* int_var_assignment_proto)
const;
5006 int64_t
Min()
const {
return min_; }
5007 void SetMin(int64_t m) { min_ = m; }
5008 int64_t
Max()
const {
return max_; }
5009 void SetMax(int64_t m) { max_ = m; }
5010 int64_t
Value()
const {
5011 DCHECK_EQ(min_, max_);
5015 bool Bound()
const {
return (max_ == min_); }
5016 void SetRange(int64_t l, int64_t u) {
5028 return !(*
this == element);
5048 const IntervalVarAssignment& interval_var_assignment_proto);
5049 void WriteToProto(IntervalVarAssignment* interval_var_assignment_proto)
const;
5051 int64_t
StartMin()
const {
return start_min_; }
5054 CHECK_EQ(start_max_, start_min_);
5058 int64_t
DurationMax()
const {
return duration_max_; }
5060 CHECK_EQ(duration_max_, duration_min_);
5061 return duration_max_;
5063 int64_t
EndMin()
const {
return end_min_; }
5064 int64_t
EndMax()
const {
return end_max_; }
5066 CHECK_EQ(end_max_, end_min_);
5070 int64_t
PerformedMax()
const {
return performed_max_; }
5072 CHECK_EQ(performed_max_, performed_min_);
5073 return performed_max_;
5095 void SetEndMin(int64_t m) { end_min_ = m; }
5108 performed_min_ = mi;
5109 performed_max_ = ma;
5115 bool Bound()
const {
5116 return (start_min_ == start_max_ && duration_min_ == duration_max_ &&
5117 end_min_ == end_max_ && performed_min_ == performed_max_);
5122 return !(*
this == element);
5128 int64_t duration_min_;
5129 int64_t duration_max_;
5132 int64_t performed_min_;
5133 int64_t performed_max_;
5161 const SequenceVarAssignment& sequence_var_assignment_proto);
5162 void WriteToProto(SequenceVarAssignment* sequence_var_assignment_proto)
const;
5167 void SetSequence(
const std::vector<int>& forward_sequence,
5168 const std::vector<int>& backward_sequence,
5169 const std::vector<int>& unperformed);
5173 bool Bound()
const {
5174 return forward_sequence_.size() + unperformed_.size() == var_->
size();
5181 return !(*
this == element);
5185 bool CheckClassInvariants();
5188 std::vector<int> forward_sequence_;
5189 std::vector<int> backward_sequence_;
5190 std::vector<int> unperformed_;
5193template <
class V,
class E>
5194class AssignmentContainer {
5198 CHECK(
var !=
nullptr);
5203 return &elements_[
index];
5208 DCHECK(
var !=
nullptr);
5210 return &elements_.back();
5215 elements_[position].Reset(
var);
5216 return &elements_[position];
5220 if (!elements_map_.empty()) {
5221 elements_map_.clear();
5227 bool Empty()
const {
return elements_.empty(); }
5231 for (
int i = 0;
i < container.elements_.size(); ++
i) {
5232 const E& element = container.elements_[i];
5233 const V*
const var = element.Var();
5235 if (i < elements_.size() && elements_[i].Var() ==
var) {
5240 DCHECK_GE(
index, 0);
5241 E*
const local_element = &elements_[
index];
5242 local_element->Copy(element);
5243 if (element.Activated()) {
5244 local_element->Activate();
5246 local_element->Deactivate();
5254 for (
int i = 0; i < container.elements_.size(); ++i) {
5255 const E& element = container.elements_[i];
5265 DCHECK(element !=
nullptr)
5266 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
5278 DCHECK(element !=
nullptr)
5279 <<
"Unknown variable " <<
var->DebugString() <<
" in solution";
5289 const std::vector<E>&
elements()
const {
return elements_; }
5292 int Size()
const {
return elements_.size(); }
5294 for (E& element : elements_) {
5299 for (E& element : elements_) {
5300 if (element.Activated()) {
5306 for (
const E& element : elements_) {
5307 if (!element.Bound())
return false;
5317 if (
Size() != container.Size()) {
5321 EnsureMapIsUpToDate();
5325 for (
const E& element : container.elements_) {
5326 const int position =
5328 if (position < 0 || elements_[position] != element) {
5335 return !(*
this == container);
5339 void EnsureMapIsUpToDate()
const {
5340 absl::flat_hash_map<const V*, int>* map =
5341 const_cast<absl::flat_hash_map<const V*, int>*
>(&elements_map_);
5342 for (
int i = map->size(); i < elements_.size(); ++i) {
5343 (*map)[elements_[i].Var()] = i;
5346 bool Find(
const V*
const var,
int*
index)
const {
5348 const size_t kMaxSizeForLinearAccess = 11;
5349 if (
Size() <= kMaxSizeForLinearAccess) {
5353 for (
int i = 0; i < elements_.size(); ++i) {
5354 if (
var == elements_[i].Var()) {
5361 EnsureMapIsUpToDate();
5362 DCHECK_EQ(elements_map_.size(), elements_.size());
5367 std::vector<E> elements_;
5368 absl::flat_hash_map<const V*, int> elements_map_;
5373class Assignment :
public PropagationBaseObject {
5394 return int_var_container_.
Empty() && interval_var_container_.
Empty() &&
5395 sequence_var_container_.
Empty();
5408 bool Load(
const std::string& filename);
5412 void Load(
const AssignmentProto& assignment_proto);
5414 bool Save(
const std::string& filename)
const;
5418 void Save(AssignmentProto* assignment_proto)
const;
5424 objective_elements_.reserve(vars.size());
5425 for (IntVar*
const var : vars) {
5426 if (
var !=
nullptr) {
5427 objective_elements_.emplace_back(
var);
5440 return index < objective_elements_.size();
5470 objective_elements_[
index].SetMin(m);
5475 objective_elements_[
index].SetMax(m);
5485 objective_elements_[
index].SetRange(l, u);
5489 IntVarElement*
Add(IntVar*
var);
5490 void Add(
const std::vector<IntVar*>& vars);
5503 void Add(
const std::vector<IntervalVar*>& vars);
5536 void Add(
const std::vector<SequenceVar*>& vars);
5543 const std::vector<int>& forward_sequence,
5544 const std::vector<int>& backward_sequence,
5545 const std::vector<int>& unperformed);
5547 const std::vector<int>& forward_sequence);
5549 const std::vector<int>& backward_sequence);
5551 const std::vector<int>& unperformed);
5570 objective_elements_[
index].Activate();
5575 objective_elements_[
index].Deactivate();
5605 return interval_var_container_;
5608 return &interval_var_container_;
5611 return sequence_var_container_;
5614 return &sequence_var_container_;
5617 return int_var_container_ == assignment.int_var_container_ &&
5618 interval_var_container_ == assignment.interval_var_container_ &&
5619 sequence_var_container_ == assignment.sequence_var_container_ &&
5620 objective_elements_ == assignment.objective_elements_;
5623 return !(*
this == assignment);
5630 std::vector<IntVarElement> objective_elements_;
5642 const std::vector<IntVar*>& target_vars,
5644 const std::vector<IntVar*>& source_vars);
5648 Pack(
Solver* s,
const std::vector<IntVar*>& vars,
int number_of_bins);
5661 const std::vector<int64_t>& weights,
const std::vector<int64_t>& bounds);
5680 const std::vector<IntVar*>& loads);
5686 const std::vector<IntVar*>& loads);
5698 const std::vector<IntVar*>& usage,
const std::vector<int64_t>& capacity);
5713 void Post()
override;
5736 bool IsInProcess()
const;
5737 const std::vector<IntVar*> vars_;
5739 std::vector<Dimension*> dims_;
5740 std::unique_ptr<RevBitMatrix> unprocessed_;
5741 std::vector<std::vector<int>> forced_;
5742 std::vector<std::vector<int>> removed_;
5743 std::vector<IntVarIterator*> holes_;
5746 std::vector<std::pair<int, int>> to_set_;
5747 std::vector<std::pair<int, int>> to_unset_;
5754 const std::string&
name);
5779 virtual const std::vector<IntVar*>&
nexts()
const = 0;
5780 virtual const std::vector<IntVar*>&
actives()
const = 0;
5781 virtual const std::vector<IntVar*>&
time_cumuls()
const = 0;
5782 virtual const std::vector<IntVar*>&
time_slacks()
const = 0;
5792class SolutionPool :
public BaseObject {
5799 virtual void Initialize(Assignment* assignment) = 0;
const E & Element(const V *const var) const
E * FastAdd(V *var)
Adds element without checking its presence in the container.
bool AreAllElementsBound() const
void Copy(const AssignmentContainer< V, E > &container)
bool operator!=(const AssignmentContainer< V, E > &container) const
E * MutableElementOrNull(const V *const var)
E * MutableElement(const V *const var)
E * AddAtPosition(V *var, int position)
bool operator==(const AssignmentContainer< V, E > &container) const
void CopyIntersection(const AssignmentContainer< V, E > &container)
const std::vector< E > & elements() const
bool Contains(const V *const var) const
const E * ElementPtrOrNull(const V *const var) const
void Activate(const IntVar *var)
AssignmentContainer< IntVar, IntVarElement > IntContainer
Assignment(Solver *solver)
void SetPerformedRange(const IntervalVar *var, int64_t mi, int64_t ma)
int64_t Value(const IntVar *var) const
AssignmentContainer< IntervalVar, IntervalVarElement > IntervalContainer
void SetStartMax(const IntervalVar *var, int64_t m)
void SetMax(const IntVar *var, int64_t m)
void SetForwardSequence(const SequenceVar *var, const std::vector< int > &forward_sequence)
int64_t EndMin(const IntervalVar *var) const
bool Activated(const IntVar *var) const
IntContainer * MutableIntVarContainer()
AssignmentContainer< SequenceVar, SequenceVarElement > SequenceContainer
int64_t ObjectiveValueFromIndex(int index) const
int64_t DurationMax(const IntervalVar *var) const
void SetObjectiveMax(int64_t m)
int64_t PerformedMin(const IntervalVar *var) const
int64_t Max(const IntVar *var) const
void SetBackwardSequence(const SequenceVar *var, const std::vector< int > &backward_sequence)
int64_t Min(const IntVar *var) const
void SetEndValue(const IntervalVar *var, int64_t value)
bool Contains(const IntVar *var) const
bool HasObjective() const
void SetValue(const IntVar *var, int64_t value)
bool ObjectiveBoundFromIndex(int index) const
void SetEndMin(const IntervalVar *var, int64_t m)
void AddObjectives(const std::vector< IntVar * > &vars)
bool Load(const std::string &filename)
int64_t EndValue(const IntervalVar *var) const
void SetMin(const IntVar *var, int64_t m)
bool operator==(const Assignment &assignment) const
void DeactivateObjectiveFromIndex(int index)
const std::vector< int > & Unperformed(const SequenceVar *var) const
void SetPerformedValue(const IntervalVar *var, int64_t value)
int64_t PerformedValue(const IntervalVar *var) const
IntervalContainer * MutableIntervalVarContainer()
int64_t StartValue(const IntervalVar *var) const
bool ObjectiveBound() const
void SetObjectiveRange(int64_t l, int64_t u)
void SetObjectiveValue(int64_t value)
IntVarElement * Add(IntVar *var)
const IntervalContainer & IntervalVarContainer() const
const SequenceContainer & SequenceVarContainer() const
void SetPerformedMax(const IntervalVar *var, int64_t m)
void ActivateObjectiveFromIndex(int index)
int64_t ObjectiveMinFromIndex(int index) const
void SetObjectiveMinFromIndex(int index, int64_t m)
std::string DebugString() const override
bool AreAllElementsBound() const
int64_t EndMax(const IntervalVar *var) const
int64_t StartMin(const IntervalVar *var) const
IntVarElement * FastAdd(IntVar *var)
Adds without checking if variable has been previously added.
bool ActivatedObjective() const
void Deactivate(const IntVar *var)
int NumIntervalVars() const
void Copy(const Assignment *assignment)
int64_t ObjectiveMin() const
const std::vector< int > & ForwardSequence(const SequenceVar *var) const
IntVar * Objective() const
void SetRange(const IntVar *var, int64_t l, int64_t u)
int64_t ObjectiveMaxFromIndex(int index) const
int64_t ObjectiveMax() const
bool ActivatedObjectiveFromIndex(int index) const
int64_t DurationMin(const IntervalVar *var) const
int NumObjectives() const
const IntContainer & IntVarContainer() const
void SetObjectiveMaxFromIndex(int index, int64_t m)
bool Bound(const IntVar *var) const
void DeactivateObjective()
int64_t DurationValue(const IntervalVar *var) const
void SetSequence(const SequenceVar *var, const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
int NumSequenceVars() const
void SetStartMin(const IntervalVar *var, int64_t m)
void SetDurationMin(const IntervalVar *var, int64_t m)
void SetStartValue(const IntervalVar *var, int64_t value)
void SetDurationMax(const IntervalVar *var, int64_t m)
Assignment & operator=(const Assignment &)=delete
void SetEndMax(const IntervalVar *var, int64_t m)
int64_t ObjectiveValue() const
void SetStartRange(const IntervalVar *var, int64_t mi, int64_t ma)
void SetDurationValue(const IntervalVar *var, int64_t value)
void CopyIntersection(const Assignment *assignment)
void SetEndRange(const IntervalVar *var, int64_t mi, int64_t ma)
void AddObjective(IntVar *const v)
void SetDurationRange(const IntervalVar *var, int64_t mi, int64_t ma)
bool operator!=(const Assignment &assignment) const
SequenceContainer * MutableSequenceVarContainer()
bool HasObjectiveFromIndex(int index) const
int64_t StartMax(const IntervalVar *var) const
IntVar * ObjectiveFromIndex(int index) const
void SetObjectiveValueFromIndex(int index, int64_t value)
bool Save(const std::string &filename) const
Saves the assignment to a file.
const std::vector< int > & BackwardSequence(const SequenceVar *var) const
void SetPerformedMin(const IntervalVar *var, int64_t m)
void SetObjectiveRangeFromIndex(int index, int64_t l, int64_t u)
void SetObjectiveMin(int64_t m)
void SetUnperformed(const SequenceVar *var, const std::vector< int > &unperformed)
int64_t PerformedMax(const IntervalVar *var) const
BaseObject & operator=(const BaseObject &)=delete
virtual std::string DebugString() const
IntVar * target_var() const
CastConstraint(Solver *const solver, IntVar *const target_var)
~CastConstraint() override
IntVar *const target_var_
Constraint & operator=(const Constraint &)=delete
std::string DebugString() const override
--------------— Constraint class ----------------—
virtual void InitialPropagate()=0
bool IsCastConstraint() const
Is the constraint created by a cast from expression to integer variable?
Constraint(Solver *const solver)
virtual void Accept(ModelVisitor *visitor) const
Accepts the given visitor.
DecisionBuilder & operator=(const DecisionBuilder &)=delete
void set_name(absl::string_view name)
virtual void Accept(ModelVisitor *visitor) const
virtual void AppendMonitors(Solver *solver, std::vector< SearchMonitor * > *extras)
std::string GetName() const
std::string DebugString() const override
-------— Decision Builder -------—
~DecisionBuilder() override
virtual void VisitRankFirstInterval(SequenceVar *sequence, int index)
virtual void VisitSetVariableValue(IntVar *var, int64_t value)
virtual void VisitScheduleOrPostpone(IntervalVar *var, int64_t est)
~DecisionVisitor() override
virtual void VisitRankLastInterval(SequenceVar *sequence, int index)
virtual void VisitUnknownDecision()
virtual void VisitScheduleOrExpedite(IntervalVar *var, int64_t est)
DecisionVisitor & operator=(const DecisionVisitor &)=delete
virtual void VisitSplitVariableDomain(IntVar *var, int64_t value, bool start_with_lower_half)
virtual void Refute(Solver *s)=0
Refute will be called after a backtrack.
std::string DebugString() const override
virtual void Apply(Solver *s)=0
Apply will be called first when the decision is executed.
Decision & operator=(const Decision &)=delete
virtual void Accept(DecisionVisitor *visitor) const
Accepts the given visitor.
Demon & operator=(const Demon &)=delete
virtual void Run(Solver *s)=0
This is the main callback of the demon.
virtual Solver::DemonPriority priority() const
---------------— Demon class -------------—
std::string DebugString() const override
void desinhibit(Solver *s)
This method un-inhibits the demon that was previously inhibited.
virtual const std::vector< IntVar * > & time_slacks() const =0
virtual SequenceVar * MakeSequenceVar()=0
Creates a sequence variable from the constraint.
DisjunctiveConstraint(Solver *s, const std::vector< IntervalVar * > &intervals, const std::string &name)
Sequence Constraint.
virtual const std::vector< IntVar * > & time_cumuls() const =0
Solver::IndexEvaluator2 transition_time_
virtual const std::vector< IntVar * > & actives() const =0
int64_t TransitionTime(int before_index, int after_index)
DisjunctiveConstraint & operator=(const DisjunctiveConstraint &)=delete
const std::vector< IntervalVar * > intervals_
virtual const std::vector< IntVar * > & nexts() const =0
~DisjunctiveConstraint() override
void SetTransitionTime(Solver::IndexEvaluator2 transition_time)
--— Finds a neighbor of the assignment passed --—
bool CheckWithOffset(absl::Duration offset) override
~ImprovementSearchLimit() override
ImprovementSearchLimit(Solver *solver, IntVar *objective_var, bool maximize, double objective_scaling_factor, double objective_offset, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
--— Improvement Search Limit --—
void Init() override
This method is called when the search limit is initialized.
void Install() override
A search monitors adds itself on the active search.
void Copy(const SearchLimit *limit) override
bool AtSolution() override
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
InitAndGetValues(IntVarIterator *it)
virtual void SetValue(int64_t v)
This method sets the value of the expression.
virtual bool Bound() const
Returns true if the min and the max of the expression are equal.
virtual void SetMax(int64_t m)=0
virtual bool IsVar() const
Returns true if the expression is indeed a variable.
virtual void SetRange(int64_t l, int64_t u)
This method sets both the min and the max of the expression.
virtual int64_t Min() const =0
IntExpr & operator=(const IntExpr &)=delete
virtual void SetMin(int64_t m)=0
virtual void WhenRange(Demon *d)=0
Attach a demon that will watch the min or the max of the expression.
virtual void Range(int64_t *l, int64_t *u)
IntVar * VarWithName(const std::string &name)
-------— IntExpr -------—
virtual IntVar * Var()=0
Creates a variable from the expression.
virtual int64_t Max() const =0
virtual void Accept(ModelVisitor *visitor) const
Accepts the given visitor.
--— Main IntTupleSet class --—
bool operator==(const IntVarElement &element) const
void SetRange(int64_t l, int64_t u)
bool operator!=(const IntVarElement &element) const
IntVarElement()
--------------— Solutions ---------------------—
std::string DebugString() const
void Copy(const IntVarElement &element)
void WriteToProto(IntVarAssignment *int_var_assignment_proto) const
void LoadFromProto(const IntVarAssignment &int_var_assignment_proto)
virtual bool Ok() const =0
This method indicates if we can call Value() or not.
virtual int64_t Value() const =0
This method returns the current value of the iterator.
virtual void Next()=0
This method moves the iterator to the next value.
~IntVarIterator() override
virtual void Init()=0
This method must be called before each loop.
std::string DebugString() const override
Pretty Print.
virtual void WhenBound(Demon *d)=0
virtual void WhenDomain(Demon *d)=0
bool IsVar() const override
Returns true if the expression is indeed a variable.
virtual void SetValues(const std::vector< int64_t > &values)
This method intersects the current domain with the values in the array.
void Accept(ModelVisitor *visitor) const override
Accepts the given visitor.
virtual IntVar * IsDifferent(int64_t constant)=0
int index() const
Returns the index of the variable.
IntVar(Solver *s)
-------— IntVar -------—
virtual IntVarIterator * MakeDomainIterator(bool reversible) const =0
virtual int64_t OldMax() const =0
Returns the previous max.
IntVar * Var() override
Creates a variable from the expression.
virtual IntVar * IsLessOrEqual(int64_t constant)=0
IntVar & operator=(const IntVar &)=delete
virtual bool Contains(int64_t v) const =0
virtual int64_t Value() const =0
virtual int VarType() const
------— IntVar ------—
virtual void RemoveValue(int64_t v)=0
This method removes the value 'v' from the domain of the variable.
virtual uint64_t Size() const =0
This method returns the number of values in the domain of the variable.
virtual IntVarIterator * MakeHoleIterator(bool reversible) const =0
virtual IntVar * IsGreaterOrEqual(int64_t constant)=0
virtual IntVar * IsEqual(int64_t constant)=0
IsEqual.
virtual void RemoveInterval(int64_t l, int64_t u)=0
virtual int64_t OldMin() const =0
Returns the previous min.
virtual void RemoveValues(const std::vector< int64_t > &values)
This method remove the values from the domain of the variable.
void SetStartValue(int64_t v)
void SetDurationValue(int64_t v)
int64_t PerformedValue() const
IntervalVar * Var() const
void SetEndMin(int64_t m)
void SetDurationRange(int64_t mi, int64_t ma)
void SetStartMax(int64_t m)
void SetPerformedMin(int64_t m)
IntervalVarElement * Clone()
void SetStartMin(int64_t m)
std::string DebugString() const
void WriteToProto(IntervalVarAssignment *interval_var_assignment_proto) const
void SetPerformedMax(int64_t m)
void SetPerformedValue(int64_t v)
void SetEndMax(int64_t m)
bool operator!=(const IntervalVarElement &element) const
void Reset(IntervalVar *var)
void Copy(const IntervalVarElement &element)
int64_t DurationMax() const
void SetEndRange(int64_t mi, int64_t ma)
void SetDurationMax(int64_t m)
IntervalVarElement()
--— IntervalVarElement --—
int64_t PerformedMin() const
bool operator==(const IntervalVarElement &element) const
void SetStartRange(int64_t mi, int64_t ma)
int64_t DurationMin() const
void SetPerformedRange(int64_t mi, int64_t ma)
void LoadFromProto(const IntervalVarAssignment &interval_var_assignment_proto)
int64_t PerformedMax() const
int64_t DurationValue() const
void SetEndValue(int64_t v)
void SetDurationMin(int64_t m)
int64_t StartValue() const
virtual IntExpr * PerformedExpr()=0
bool IsPerformedBound() const
virtual int64_t DurationMax() const =0
virtual bool WasPerformedBound() const =0
virtual void WhenEndRange(Demon *d)=0
virtual void SetEndRange(int64_t mi, int64_t ma)=0
virtual int64_t OldEndMax() const =0
virtual int64_t OldDurationMin() const =0
virtual int64_t EndMax() const =0
virtual IntExpr * StartExpr()=0
virtual int64_t EndMin() const =0
These methods query, set, and watch the end position of the interval var.
virtual int64_t OldStartMax() const =0
virtual void SetEndMax(int64_t m)=0
virtual void SetPerformed(bool val)=0
virtual void SetDurationMax(int64_t m)=0
virtual void SetStartRange(int64_t mi, int64_t ma)=0
virtual int64_t OldDurationMax() const =0
virtual void SetStartMax(int64_t m)=0
static const int64_t kMaxValidValue
The largest acceptable value to be returned by EndMax()
virtual void WhenStartRange(Demon *d)=0
bool CannotBePerformed() const
void WhenAnything(Demon *d)
Attaches a demon awakened when anything about this interval changes.
virtual int64_t OldEndMin() const =0
virtual int64_t StartMax() const =0
virtual bool MayBePerformed() const =0
virtual void SetDurationMin(int64_t m)=0
virtual void WhenDurationBound(Demon *d)=0
virtual IntExpr * SafeStartExpr(int64_t unperformed_value)=0
static const int64_t kMinValidValue
The smallest acceptable value to be returned by StartMin()
virtual void WhenStartBound(Demon *d)=0
virtual IntExpr * SafeDurationExpr(int64_t unperformed_value)=0
IntervalVar & operator=(const IntervalVar &)=delete
virtual IntExpr * SafeEndExpr(int64_t unperformed_value)=0
virtual IntExpr * DurationExpr()=0
virtual void WhenDurationRange(Demon *d)=0
virtual void WhenEndBound(Demon *d)=0
virtual int64_t DurationMin() const =0
These methods query, set, and watch the duration of the interval var.
virtual void SetEndMin(int64_t m)=0
virtual IntExpr * EndExpr()=0
virtual void SetStartMin(int64_t m)=0
virtual void Accept(ModelVisitor *visitor) const =0
Accepts the given visitor.
virtual void WhenPerformedBound(Demon *d)=0
virtual void SetDurationRange(int64_t mi, int64_t ma)=0
virtual int64_t OldStartMin() const =0
IntervalVar(Solver *const solver, const std::string &name)
virtual int64_t StartMin() const =0
virtual bool MustBePerformed() const =0
--— LightIntFunctionElementCt --—
--— LightIntIntFunctionElementCt --—
-------— Local Search Phase Parameters -------—
--— LocalSearchProfiler --—
--— Local search decision builder --—
static const char kCumulsArgument[]
static const char kStartMaxArgument[]
static const char kVarValueWatcher[]
static const char kConvexPiecewise[]
static const char kScalProdGreaterOrEqual[]
static const char kStepArgument[]
static const char kLexLess[]
virtual void VisitSequenceVariable(const SequenceVar *variable)
static const char kGreaterOrEqual[]
static const char kSolutionLimitArgument[]
static const char kAbsEqual[]
static const char kNullIntersect[]
static const char kStartExpr[]
virtual void VisitIntervalArrayArgument(const std::string &arg_name, const std::vector< IntervalVar * > &arguments)
virtual void VisitIntervalArgument(const std::string &arg_name, IntervalVar *argument)
Visit interval argument.
static const char kIndexOf[]
static const char kVariableUsageLessConstantExtension[]
static const char kDeviation[]
static const char kSequenceArgument[]
static const char kAssumePathsArgument[]
void VisitInt64ToBoolExtension(Solver::IndexFilter1 filter, int64_t index_min, int64_t index_max)
--— Helpers --—
static const char kIntervalBinaryRelation[]
static const char kIntegerVariable[]
static const char kDifferenceOperation[]
static const char kInitialState[]
static const char kIsMember[]
static const char kTraceOperation[]
static const char kSearchLimitExtension[]
static const char kEndsArgument[]
static const char kRelaxedMinOperation[]
static const char kFalseConstraint[]
static const char kFixedChargeArgument[]
static const char kDurationMaxArgument[]
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 kSumOperation[]
static const char kIntervalVariable[]
static const char kFinalStatesArgument[]
static const char kNoCycle[]
static const char kElement[]
static const char kSequenceVariable[]
static const char kTuplesArgument[]
static const char kFailuresLimitArgument[]
static const char kMirrorOperation[]
Operations.
static const char kMinEqual[]
static const char kEarlyCostArgument[]
static const char kInt64ToInt64Extension[]
static const char kNotBetween[]
static const char kDistribute[]
static const char kOpposite[]
static const char kTransition[]
static const char kActiveArgument[]
argument names:
static const char kObjectiveExtension[]
static const char kIsGreater[]
virtual void BeginVisitModel(const std::string &type_name)
--— Virtual methods for visitors --—
static const char kDifference[]
static const char kDurationMinArgument[]
virtual void BeginVisitIntegerExpression(const std::string &type_name, const IntExpr *expr)
static const char kNextsArgument[]
static const char kProduct[]
virtual void VisitIntegerArgument(const std::string &arg_name, int64_t value)
Visit integer arguments.
static const char kRangeArgument[]
static const char kCircuit[]
static const char kLateCostArgument[]
static const char kEndMinArgument[]
static const char kMinArgument[]
virtual void VisitIntegerVariable(const IntVar *variable, IntExpr *delegate)
virtual void VisitSequenceArrayArgument(const std::string &arg_name, const std::vector< SequenceVar * > &arguments)
static const char kCoefficientsArgument[]
virtual void VisitIntegerMatrixArgument(const std::string &arg_name, const IntTupleSet &tuples)
static const char kExpressionArgument[]
static const char kTrace[]
virtual void VisitIntegerVariableEvaluatorArgument(const std::string &arg_name, const Solver::Int64ToIntVar &arguments)
Helpers.
static const char kTargetArgument[]
~ModelVisitor() override
Methods.
static const char kMapDomain[]
static const char kStartsArgument[]
static const char kIntervalDisjunction[]
static const char kPositionXArgument[]
static const char kStartSyncOnStartOperation[]
static const char kRelationArgument[]
static const char kIsDifferent[]
static const char kSortingConstraint[]
static const char kSizeArgument[]
static const char kMember[]
static const char kModulo[]
static const char kSumGreaterOrEqual[]
static const char kIntervalUnaryRelation[]
static const char kMaxArgument[]
virtual void EndVisitModel(const std::string &type_name)
static const char kProductOperation[]
static const char kTransitsArgument[]
static const char kPerformedExpr[]
virtual void VisitIntegerExpressionArgument(const std::string &arg_name, IntExpr *argument)
Visit integer expression argument.
static const char kNotMember[]
static const char kValueArgument[]
static const char kEndExpr[]
static const char kLessOrEqual[]
static const char kMaxEqual[]
static const char kLateDateArgument[]
static const char kRightArgument[]
static const char kEarlyDateArgument[]
static const char kScalProdLessOrEqual[]
static const char kIsGreaterOrEqual[]
virtual void VisitIntegerVariableArrayArgument(const std::string &arg_name, const std::vector< IntVar * > &arguments)
static const char kCapacityArgument[]
static const char kSumLessOrEqual[]
static const char kModuloArgument[]
static const char kVarBoundWatcher[]
static const char kIsEqual[]
static const char kCumulative[]
static const char kScalProdEqual[]
static const char kSizeYArgument[]
static const char kSequencesArgument[]
static const char kEndMaxArgument[]
static const char kDurationExpr[]
static const char kVariableGroupExtension[]
virtual void VisitIntegerArrayArgument(const std::string &arg_name, const std::vector< int64_t > &values)
static const char kAllDifferent[]
static const char kValuesArgument[]
static const char kIsLess[]
static const char kIndexArgument[]
static const char kPack[]
static const char kPathCumul[]
static const char kRelaxedMaxOperation[]
static const char kScalProd[]
static const char kAtMost[]
static const char kStartSyncOnEndOperation[]
static const char kUsageLessConstantExtension[]
static const char kMaximizeArgument[]
static const char kLightElementEqual[]
static const char kElementEqual[]
static const char kCumulativeArgument[]
static const char kSquare[]
static const char kIntervalArgument[]
static const char kPositionYArgument[]
static const char kIsBetween[]
static const char kVarsArgument[]
virtual void BeginVisitConstraint(const std::string &type_name, const Constraint *constraint)
static const char kVariableArgument[]
static const char kLinkExprVar[]
static const char kBranchesLimitArgument[]
static const char kIndex2Argument[]
static const char kSumEqual[]
virtual void EndVisitExtension(const std::string &type)
static const char kUsageEqualVariableExtension[]
static const char kSemiContinuous[]
static const char kDemandsArgument[]
static const char kDisjunctive[]
static const char kNonEqual[]
static const char kCountEqual[]
static const char kSizeXArgument[]
static const char kGreater[]
static const char kEquality[]
static const char kLeftArgument[]
static const char kGlobalCardinality[]
static const char kInversePermutation[]
static const char kCountAssignedItemsExtension[]
Extension names:
virtual void VisitIntervalVariable(const IntervalVar *variable, const std::string &operation, int64_t value, IntervalVar *delegate)
static const char kCountUsedBinsExtension[]
static const char kStartMinArgument[]
static const char kOptionalArgument[]
static const char kCountArgument[]
static const char kConditionalExpr[]
void VisitInt64ToInt64Extension(const Solver::IndexEvaluator1 &eval, int64_t index_min, int64_t index_max)
static const char kTrueConstraint[]
static const char kPartialArgument[]
static const char kDelayedPathCumul[]
virtual void BeginVisitExtension(const std::string &type)
static const char kWeightedSumOfAssignedEqualVariableExtension[]
static const char kInt64ToBoolExtension[]
virtual void VisitSequenceArgument(const std::string &arg_name, SequenceVar *argument)
Visit sequence argument.
static const char kEvaluatorArgument[]
static const char kCover[]
virtual void EndVisitIntegerExpression(const std::string &type_name, const IntExpr *expr)
static const char kAbs[]
Constraint and Expression types.
static const char kSmartTimeCheckArgument[]
static const char kCardsArgument[]
static const char kBetween[]
static const char kDivide[]
static const char kAllowedAssignments[]
static const char kTimeLimitArgument[]
static const char kPower[]
static const char kIsLessOrEqual[]
static const char kLess[]
static const char kIntervalsArgument[]
virtual void EndVisitConstraint(const std::string &type_name, const Constraint *constraint)
Subclass of RevArray<T> which adds numerical operations.
void Decr(Solver *const s, int index)
NumericalRevArray(int size, const T &val)
void Add(Solver *const s, int index, const T &to_add)
void Incr(Solver *const s, int index)
NumericalRev(const T &val)
void Incr(Solver *const s)
void Decr(Solver *const s)
void Add(Solver *const s, const T &to_add)
Base objective monitor class. All metaheuristics derive from this.
bool CurrentInternalValuesAreConstraining() const
const std::vector< IntVar * > & minimization_vars() const
IntVar * MinimizationVar(int index) const
const std::vector< IntVar * > & objective_vars() const
~ObjectiveMonitor() override
void SetCurrentInternalValue(int index, int64_t value)
void MakeMinimizationVarsLessOrEqualWithSteps(const T &upper_bounds)
int64_t BestInternalValue(int index) const
bool found_initial_solution_
int64_t CurrentInternalValue(int index) const
bool AcceptDelta(Assignment *delta, Assignment *deltadelta) override
IntVar * ObjectiveVar(int index) const
void Accept(ModelVisitor *visitor) const override
Accepts the given model visitor.
int64_t BestValue(int index) const
bool AtSolution() override
int64_t Step(int index) const
ObjectiveMonitor(Solver *solver, const std::vector< bool > &maximize, std::vector< IntVar * > vars, std::vector< int64_t > steps)
-------— Objective Management -------—
bool Maximize(int index) const
IntVar * MakeMinimizationVarsLessOrEqualWithStepsStatus(const T &upper_bounds)
void EnterSearch() override
Beginning of the search.
ObjectiveMonitor & operator=(const ObjectiveMonitor &)=delete
void BeginNextDecision(DecisionBuilder *db) override
Internal methods.
int64_t best() const
Returns the best value found during search.
void RefuteDecision(Decision *d) override
Before refuting the decision.
bool AtSolution() override
IntVar * var() const
Returns the variable that is optimized.
OptimizeVar(Solver *solver, bool maximize, IntVar *var, int64_t step)
std::string DebugString() const override
bool AcceptSolution() override
virtual std::string Name() const
void SetUnassigned(int var_index)
void SetAssigned(int var_index)
void Assign(int var_index, int bin_index)
bool IsPossible(int var_index, int bin_index) const
void AddCountUsedBinDimension(IntVar *count_var)
Pack(Solver *s, const std::vector< IntVar * > &vars, int number_of_bins)
--— Pack --—
void AddWeightedSumLessOrEqualConstantDimension(const std::vector< int64_t > &weights, const std::vector< int64_t > &bounds)
-------— API -------—
void AddSumVariableWeightsLessOrEqualConstantDimension(const std::vector< IntVar * > &usage, const std::vector< int64_t > &capacity)
void AddCountAssignedItemsDimension(IntVar *count_var)
void UnassignAllRemainingItems()
void AssignAllRemainingItems()
std::string DebugString() const override
--------------— Constraint class ----------------—
void AssignAllPossibleToBin(int bin_index)
void Accept(ModelVisitor *visitor) const override
Accepts the given visitor.
IntVar * AssignVar(int var_index, int bin_index) const
bool IsAssignedStatusKnown(int var_index) const
void AssignFirstPossibleToBin(int bin_index)
void AddWeightedSumEqualVarDimension(const std::vector< int64_t > &weights, const std::vector< IntVar * > &loads)
void RemoveAllPossibleFromBin(int bin_index)
void AddWeightedSumOfAssignedDimension(const std::vector< int64_t > &weights, IntVar *cost_var)
void InitialPropagate() override
void SetImpossible(int var_index, int bin_index)
void OneDomain(int var_index)
bool IsUndecided(int var_index, int bin_index) const
ProfiledDecisionBuilder(DecisionBuilder *db)
--------------— ProfiledDecisionBuilder ---------—
std::string DebugString() const override
-------— Decision Builder -------—
void Accept(ModelVisitor *visitor) const override
const std::string & name() const
void AppendMonitors(Solver *solver, std::vector< SearchMonitor * > *extras) override
~ProfiledDecisionBuilder() override
PropagationBaseObject & operator=(const PropagationBaseObject &)=delete
void EnqueueVar(Demon *const d)
void ExecuteAll(const SimpleRevFIFO< Demon * > &demons)
virtual std::string name() const
Object naming.
void set_variable_to_clean_on_fail(IntVar *v)
Shortcut for variable cleaner.
void EnqueueAll(const SimpleRevFIFO< Demon * > &demons)
void set_action_on_fail(Solver::Action a)
void EnqueueDelayedDemon(Demon *const d)
~PropagationBaseObject() override
virtual std::string BaseName() const
Returns a base name for automatic naming.
void set_name(absl::string_view name)
void reset_action_on_fail()
This method clears the failure callback.
std::string DebugString() const override
bool HasName() const
Returns whether the object has been named or not.
PropagationBaseObject(Solver *const s)
absl::Duration duration_limit() const
SearchLimit * MakeClone() const override
Allocates a clone of the limit.
bool IsUncheckedSolutionLimitReached() override
void Install() override
A search monitors adds itself on the active search.
bool CheckWithOffset(absl::Duration offset) override
int64_t wall_time() const
void Init() override
This method is called when the search limit is initialized.
int64_t solutions() const
int ProgressPercent() override
std::string DebugString() const override
void Accept(ModelVisitor *visitor) const override
Accepts the given model visitor.
void ExitSearch() override
End of the search.
absl::Time AbsoluteSolverDeadline() const
RegularLimit(Solver *s, absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check, bool cumulative)
--— Regular Limit --—
void Copy(const SearchLimit *limit) override
void UpdateLimits(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions)
RegularLimit * MakeIdenticalClone() const
const T & Value(int index) const
RevArray(int size, const T &val)
void SetValue(Solver *const s, int index, const T &val)
const T & operator[](int index) const
void SetValue(Solver *const s, const T &val)
Base class of all search limits.
~SearchLimit() override
-------— Search Limits -------—
std::string DebugString() const override
void BeginNextDecision(DecisionBuilder *b) override
Before calling DecisionBuilder::Next.
void PeriodicCheck() override
Periodic call to check limits in long running methods.
bool crossed() const
Returns true if the limit has been crossed.
virtual void Copy(const SearchLimit *limit)=0
void EnterSearch() override
Internal methods.
virtual void Init()=0
This method is called when the search limit is initialized.
void Install() override
A search monitors adds itself on the active search.
SearchLimit & operator=(const SearchLimit &)=delete
virtual bool CheckWithOffset(absl::Duration offset)=0
SearchLimit(Solver *const s)
void RefuteDecision(Decision *d) override
Before refuting the decision.
virtual SearchLimit * MakeClone() const =0
Allocates a clone of the limit.
A search monitor is a simple set of callbacks to monitor all search events.
static constexpr int kNoProgress
virtual void Install()
A search monitors adds itself on the active search.
~SearchMonitor() override
virtual bool AtSolution()
virtual void BeginInitialPropagation()
Before the initial propagation.
virtual void EndFail()
After completing the backtrack.
virtual void RestartSearch()
Restart the search.
virtual void EndInitialPropagation()
After the initial propagation.
virtual bool AcceptDelta(Assignment *delta, Assignment *deltadelta)
virtual void BeginNextDecision(DecisionBuilder *b)
Before calling DecisionBuilder::Next.
virtual void RefuteDecision(Decision *d)
Before refuting the decision.
virtual int ProgressPercent()
virtual void EndNextDecision(DecisionBuilder *b, Decision *d)
After calling DecisionBuilder::Next, along with the returned decision.
virtual void ApplyDecision(Decision *d)
Before applying the decision.
virtual void Accept(ModelVisitor *visitor) const
Accepts the given model visitor.
virtual bool IsUncheckedSolutionLimitReached()
virtual void ExitSearch()
End of the search.
virtual bool LocalOptimum()
SearchMonitor(Solver *const s)
virtual void PeriodicCheck()
Periodic call to check limits in long running methods.
virtual void NoMoreSolutions()
When the search tree is finished.
void ListenToEvent(Solver::MonitorEvent event)
virtual void BeginFail()
Just when the failure occurs.
virtual bool AcceptSolution()
virtual void EnterSearch()
Beginning of the search.
virtual void AfterDecision(Decision *d, bool apply)
virtual void AcceptNeighbor()
After accepting a neighbor during local search.
virtual void AcceptUncheckedNeighbor()
After accepting an unchecked neighbor during local search.
---------------— Search class --------------—
void Reset(SequenceVar *var)
void WriteToProto(SequenceVarAssignment *sequence_var_assignment_proto) const
bool operator==(const SequenceVarElement &element) const
std::string DebugString() const
SequenceVarElement * Clone()
SequenceVarElement()
--— SequenceVarElement --—
void SetUnperformed(const std::vector< int > &unperformed)
const std::vector< int > & ForwardSequence() const
void Copy(const SequenceVarElement &element)
void SetBackwardSequence(const std::vector< int > &backward_sequence)
const std::vector< int > & BackwardSequence() const
void SetSequence(const std::vector< int > &forward_sequence, const std::vector< int > &backward_sequence, const std::vector< int > &unperformed)
void SetForwardSequence(const std::vector< int > &forward_sequence)
SequenceVar * Var() const
void LoadFromProto(const SequenceVarAssignment &sequence_var_assignment_proto)
const std::vector< int > & Unperformed() const
void RankNotFirst(int index)
void HorizonRange(int64_t *hmin, int64_t *hmax) const
virtual void Accept(ModelVisitor *visitor) const
Accepts the given visitor.
void RankNotLast(int index)
void RankSequence(const std::vector< int > &rank_first, const std::vector< int > &rank_last, const std::vector< int > &unperformed)
IntervalVar * Interval(int index) const
Returns the index_th interval of the sequence.
void ComputePossibleFirstsAndLasts(std::vector< int > *possible_firsts, std::vector< int > *possible_lasts)
int64_t size() const
Returns the number of interval vars in the sequence.
SequenceVar(Solver *s, const std::vector< IntervalVar * > &intervals, const std::vector< IntVar * > &nexts, const std::string &name)
--— SequenceVar --—
void RankFirst(int index)
void ComputeStatistics(int *ranked, int *not_ranked, int *unperformed) const
Compute statistics on the sequence.
void FillSequence(std::vector< int > *rank_first, std::vector< int > *rank_last, std::vector< int > *unperformed) const
std::string DebugString() const override
void ActiveHorizonRange(int64_t *hmin, int64_t *hmax) const
void DurationRange(int64_t *dmin, int64_t *dmax) const
std::string DebugString() const override
int64_t branches(int n) const
Returns the number of branches when the nth solution was found.
SolutionData BuildSolutionDataForCurrentState()
void AddObjectives(const std::vector< IntVar * > &objectives)
const std::vector< int > & ForwardSequence(int n, SequenceVar *var) const
~SolutionCollector() override
void Add(IntVar *var)
Add API.
SolutionCollector & operator=(const SolutionCollector &)=delete
std::vector< std::unique_ptr< Assignment > > solution_pool_
int64_t PerformedValue(int n, IntervalVar *var) const
This is a shortcut to get the PerformedValue of 'var' in the nth solution.
void EnterSearch() override
Beginning of the search.
void FreeSolution(Assignment *solution)
void Push(const SolutionData &data)
void PopSolution()
Remove and delete the last popped solution.
const std::vector< int > & Unperformed(int n, SequenceVar *var) const
void AddObjective(IntVar *objective)
bool has_solution() const
Returns whether any solutions were stored during the search.
void check_index(int n) const
int solution_count() const
Returns how many solutions were stored during the search.
void Install() override
A search monitors adds itself on the active search.
int64_t wall_time(int n) const
Returns the wall time in ms for the nth solution.
void PushSolution()
Push the current state as a new solution.
int64_t DurationValue(int n, IntervalVar *var) const
This is a shortcut to get the DurationValue of 'var' in the nth solution.
int64_t ObjectiveValueFromIndex(int n, int index) const
Returns the value of the index-th objective of the nth solution.
int64_t failures(int n) const
const std::vector< int > & BackwardSequence(int n, SequenceVar *var) const
int64_t StartValue(int n, IntervalVar *var) const
This is a shortcut to get the StartValue of 'var' in the nth solution.
SolutionCollector(Solver *solver, const Assignment *assignment)
-------— Solution Collectors --------—
int64_t Value(int n, IntVar *var) const
This is a shortcut to get the Value of 'var' in the nth solution.
std::vector< Assignment * > recycle_solutions_
std::vector< SolutionData > solution_data_
std::unique_ptr< Assignment > prototype_
Assignment * last_solution_or_null() const
Returns the last solution if there are any, nullptr otherwise.
int64_t EndValue(int n, IntervalVar *var) const
This is a shortcut to get the EndValue of 'var' in the nth solution.
virtual bool SyncNeeded(Assignment *local_assignment)=0
virtual void Initialize(Assignment *assignment)=0
virtual void RegisterNewSolution(Assignment *assignment)=0
virtual void GetNextSolution(Assignment *assignment)=0
For the time being, Solver is neither MT_SAFE nor MT_HOT.
Constraint * MakeIsLexicalLessOrEqualWithOffsetsCt(std::vector< IntVar * > left, std::vector< IntVar * > right, std::vector< int64_t > offsets, IntVar *boolvar)
Semi-reified version of the above: boolvar -> LexLE(left, right, offsets).
static ConstraintSolverParameters DefaultSolverParameters()
--— ConstraintSolverParameters --—
Constraint * MakeDistribute(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values, const std::vector< IntVar * > &cards)
Aggregated version of count: |{i | v[i] == values[j]}| == cards[j].
void SetBranchSelector(BranchSelector bs)
Sets the given branch selector on the current active search.
IntervalVar * MakeMirrorInterval(IntervalVar *interval_var)
--— API --—
IntExpr * MakeElement(const std::vector< int64_t > &values, IntVar *index)
values[index]
OptimizationDirection optimization_direction() const
The direction of optimization, getter and setter.
Constraint * MakePathConnected(std::vector< IntVar * > nexts, std::vector< int64_t > sources, std::vector< int64_t > sinks, std::vector< IntVar * > status)
bool CurrentlyInSolve() const
std::function< int64_t(const IntVar *v, int64_t id)> VariableValueSelector
Constraint * MakeIsLessOrEqualCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left <= right)
Decision * MakeAssignVariablesValuesOrDoNothing(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
Demon * RegisterDemon(Demon *demon)
Adds a new demon and wraps it inside a DemonProfiler if necessary.
Search * ActiveSearch() const
Returns the active search, nullptr outside search.
Constraint * MakeScalProdLessOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
Constraint * MakeIsEqualCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var == value)
Demon * MakeClosureDemon(Closure closure)
Creates a demon from a closure.
IntExpr * MakeScalProd(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefs)
scalar product
IntVar * MakeIsGreaterOrEqualVar(IntExpr *left, IntExpr *right)
status var of (left >= right)
IntExpr * MakeDiv(IntExpr *expr, int64_t value)
expr / value (integer division)
Constraint * MakeSortingConstraint(const std::vector< IntVar * > &vars, const std::vector< IntVar * > &sorted)
bool IsLocalSearchProfilingEnabled() const
Returns whether we are profiling local search.
void ExportProfilingOverview(const std::string &filename)
Constraint * MakeLexicalLess(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
bool NextSolution()
Search for the next solution in the search tree.
Constraint * MakeSumEquality(const std::vector< IntVar * > &vars, int64_t cst)
DecisionBuilder * MakeSolveOnce(DecisionBuilder *db)
IntVar * MakeBoolVar(const std::string &name)
MakeBoolVar will create a variable with a {0, 1} domain.
uint64_t fail_stamp() const
The fail_stamp() is incremented after each backtrack.
int64_t accepted_neighbors() const
The number of accepted neighbors.
DecisionBuilder * MakeApplyBranchSelector(BranchSelector bs)
Creates a decision builder that will set the branch selector.
Constraint * MakeNotMemberCt(IntExpr *expr, const std::vector< int64_t > &values)
expr not in set.
void set_fail_intercept(std::function< void()> fail_intercept)
Internal.
friend class DemonProfiler
Constraint * MakeIsGreaterCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left > right)
DecisionBuilder * MakeRestoreAssignment(Assignment *assignment)
Constraint * MakeIsGreaterOrEqualCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left >= right)
SearchMonitor * MakeEnterSearchCallback(std::function< void()> callback)
--— Callback-based search monitors --—
LocalSearchOperator * MakeMoveTowardTargetOperator(const Assignment &target)
void IncrementNeighbors()
Constraint * MakeIsEqualCt(IntExpr *v1, IntExpr *v2, IntVar *b)
b == (v1 == v2)
IntVar * MakeIsMemberVar(IntExpr *expr, const std::vector< int64_t > &values)
Decision * MakeAssignVariableValueOrFail(IntVar *var, int64_t value)
Constraint * MakeNonEquality(IntExpr *left, IntExpr *right)
left != right
IntVar * MakeIsEqualCstVar(IntExpr *var, int64_t value)
status var of (var == value)
Constraint * MakeSubCircuit(const std::vector< IntVar * > &nexts)
Decision * MakeVariableLessOrEqualValue(IntVar *var, int64_t value)
IntExpr * MakeMax(const std::vector< IntVar * > &vars)
std::max(vars)
SearchMonitor * MakeLubyRestart(int scale_factor)
int64_t branches() const
The number of branches explored since the creation of the solver.
OptimizeVar * MakeWeightedOptimize(bool maximize, const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a weighted objective with a given sense (true = maximization).
IntervalVar * MakeFixedDurationStartSyncedOnEndIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
LocalSearchOperator * ConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
std::function< DecisionModification()> BranchSelector
IntExpr * MakeDifference(IntExpr *left, IntExpr *right)
left - right
SearchMonitor * MakeConstantRestart(int frequency)
int64_t solutions() const
The number of solutions found since the start of the search.
LocalSearchFilter * MakeVariableDomainFilter()
bool NameAllVariables() const
Returns whether all variables should be named.
DecisionBuilder * MakeNestedOptimize(DecisionBuilder *db, Assignment *solution, bool maximize, int64_t step)
Constraint * MakeMemberCt(IntExpr *expr, const std::vector< int64_t > &values)
--— Member and related constraints --—
ABSL_MUST_USE_RESULT RegularLimit * MakeSolutionsLimit(int64_t solutions)
Constraint * MakeGreaterOrEqual(IntExpr *left, IntExpr *right)
left >= right
void AddPropagationMonitor(PropagationMonitor *monitor)
Decision * MakeRankLastInterval(SequenceVar *sequence, int index)
IntVar * MakeBoolVar()
MakeBoolVar will create a variable with a {0, 1} domain.
LocalSearchPhaseParameters * MakeLocalSearchPhaseParameters(IntVar *objective, LocalSearchOperator *ls_operator, DecisionBuilder *sub_decision_builder)
Local Search Phase Parameters.
void MakeIntervalVarArray(int count, int64_t start_min, int64_t start_max, int64_t duration_min, int64_t duration_max, int64_t end_min, int64_t end_max, bool optional, absl::string_view name, std::vector< IntervalVar * > *array)
SolutionCollector * MakeBestValueSolutionCollector(const Assignment *assignment, bool maximize)
IntVar * MakeIsLessOrEqualCstVar(IntExpr *var, int64_t value)
status var of (var <= value)
Constraint * MakeIfThenElseCt(IntVar *condition, IntExpr *then_expr, IntExpr *else_expr, IntVar *target_var)
Special cases with arrays of size two.
Solver & operator=(const Solver &)=delete
IntExpr * MakeSum(IntExpr *left, IntExpr *right)
--— Integer Expressions --—
Constraint * MakeCumulative(const std::vector< IntervalVar * > &intervals, const std::vector< int64_t > &demands, int64_t capacity, const std::string &name)
Demands are constant.
ABSL_MUST_USE_RESULT SearchLimit * MakeCustomLimit(std::function< bool()> limiter)
Constraint * MakeScalProdEquality(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coefficients, int64_t cst)
Constraint * MakeIsMemberCt(IntExpr *expr, const std::vector< int64_t > &values, IntVar *boolvar)
boolvar == (expr in set)
static constexpr int kNumPriorities
Number of priorities for demons.
IntExpr * MakeMin(const std::vector< IntVar * > &vars)
std::min(vars)
void Fail()
Abandon the current branch in the search tree. A backtrack will follow.
Constraint * MakePathCumul(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, const std::vector< IntVar * > &cumuls, const std::vector< IntVar * > &transits)
const ConstraintSolverParameters & const_parameters() const
Read-only.
IntVar * MakeIsDifferentVar(IntExpr *v1, IntExpr *v2)
status var of (v1 != v2)
IntervalVar * MakeIntervalVar(int64_t start_min, int64_t start_max, int64_t duration_min, int64_t duration_max, int64_t end_min, int64_t end_max, bool optional, const std::string &name)
Variable Duration Interval Var.
ABSL_MUST_USE_RESULT RegularLimit * MakeFailuresLimit(int64_t failures)
Decision * balancing_decision() const
int64_t demon_runs(DemonPriority p) const
The number of demons executed during search for a given priority.
@ NORMAL_PRIORITY
NORMAL_PRIORITY is the highest priority: Demons will be processed first.
@ VAR_PRIORITY
VAR_PRIORITY is between DELAYED_PRIORITY and NORMAL_PRIORITY.
std::function< void(Solver *)> Action
OptimizeVar * MakeWeightedMinimize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
void NewSearch(DecisionBuilder *db, const std::vector< SearchMonitor * > &monitors)
Opens a new top level search.
std::function< bool(int64_t)> IndexFilter1
IntVarLocalSearchFilter * MakeSumObjectiveFilter(const std::vector< IntVar * > &vars, IndexEvaluator2 values, Solver::LocalSearchFilterBound filter_enum)
Constraint * MakeNonOverlappingNonStrictBoxesConstraint(const std::vector< IntVar * > &x_vars, const std::vector< IntVar * > &y_vars, const std::vector< IntVar * > &x_size, const std::vector< IntVar * > &y_size)
DecisionBuilder * MakeProfiledDecisionBuilderWrapper(DecisionBuilder *db)
Activates profiling on a decision builder.
bool UseFastLocalSearch() const
Returns true if fast local search is enabled.
IntVar * MakeIsGreaterVar(IntExpr *left, IntExpr *right)
status var of (left > right)
Decision * MakeVariableGreaterOrEqualValue(IntVar *var, int64_t value)
LocalSearchMonitor * GetLocalSearchMonitor() const
Returns the local search monitor.
Assignment * RunUncheckedLocalSearch(const Assignment *initial_solution, LocalSearchFilterManager *filter_manager, LocalSearchOperator *ls_operator, const std::vector< SearchMonitor * > &monitors, RegularLimit *limit, absl::flat_hash_set< IntVar * > *touched=nullptr)
IntVar * MakeIsLessVar(IntExpr *left, IntExpr *right)
status var of (left < right)
ABSL_MUST_USE_RESULT RegularLimit * MakeTimeLimit(absl::Duration time)
Creates a search limit that constrains the running time.
void clear_fail_intercept()
const std::string & context() const
Gets the current context of the search.
Constraint * MakeCircuit(const std::vector< IntVar * > &nexts)
Force the "nexts" variable to create a complete Hamiltonian path.
Constraint * MakeDeviation(const std::vector< IntVar * > &vars, IntVar *deviation_var, int64_t total_sum)
int SearchLeftDepth() const
SolverState
This enum represents the state of the solver w.r.t. the search.
@ IN_SEARCH
Executing the search code.
@ IN_ROOT_NODE
Executing the root node.
@ PROBLEM_INFEASIBLE
After search, the model is infeasible.
@ NO_MORE_SOLUTIONS
After failed NextSolution and before EndSearch.
@ OUTSIDE_SEARCH
Before search, after search.
@ AT_SOLUTION
After successful NextSolution and before EndSearch.
void set_context(absl::string_view context)
Sets the current context of the search.
DisjunctiveConstraint * MakeDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
-------— Factory methods -------—
friend class LocalSearchProfiler
LocalSearchStatistics GetLocalSearchStatistics() const
Returns detailed local search statistics.
void SaveAndAdd(T *adr, T val)
All-in-one SaveAndAdd_value.
IntVar * RegisterIntVar(IntVar *var)
Registers a new IntVar and wraps it inside a TraceIntVar if necessary.
Constraint * MakeIsGreaterCstCt(IntExpr *v, int64_t c, IntVar *b)
b == (v > c)
DecisionBuilder * Compose(DecisionBuilder *db1, DecisionBuilder *db2)
ObjectiveMonitor * MakeTabuSearch(bool maximize, IntVar *objective, int64_t step, const std::vector< IntVar * > &vars, int64_t keep_tenure, int64_t forbid_tenure, double tabu_factor)
MetaHeuristics which try to get the search out of local optima.
std::string LocalSearchProfile() const
IntervalVar * MakeFixedDurationEndSyncedOnStartIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Constraint * MakeAllDifferentExcept(const std::vector< IntVar * > &vars, int64_t escape_value)
DecisionBuilder * MakePhase(const std::vector< IntVar * > &vars, IntVarStrategy var_str, IntValueStrategy val_str)
IntVar * MakeIsGreaterCstVar(IntExpr *var, int64_t value)
status var of (var > value)
bool CheckAssignment(Assignment *solution)
Checks whether the given assignment satisfies all relevant constraints.
LocalSearchOperator * RandomConcatenateOperators(const std::vector< LocalSearchOperator * > &ops)
bool IsBooleanVar(IntExpr *expr, IntVar **inner_var, bool *is_negated) const
void AddBacktrackAction(Action a, bool fast)
void MakeFixedDurationIntervalVarArray(int count, int64_t start_min, int64_t start_max, int64_t duration, bool optional, absl::string_view name, std::vector< IntervalVar * > *array)
Decision * MakeAssignVariableValue(IntVar *var, int64_t val)
Decisions.
void SaveAndSetValue(T *adr, T val)
All-in-one SaveAndSetValue.
std::string model_name() const
Returns the name of the model.
LocalSearchFilter * MakeAcceptFilter()
Local Search Filters.
IntExpr * MakeMonotonicElement(IndexEvaluator1 values, bool increasing, IntVar *index)
Decision * MakeAssignVariablesValuesOrFail(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
Decision * MakeScheduleOrExpedite(IntervalVar *var, int64_t est, int64_t *marker)
Constraint * MakeSumLessOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
Variation on arrays.
Constraint * MakeIsLessCstCt(IntExpr *v, int64_t c, IntVar *b)
b == (v < c)
SolutionPool * MakeDefaultSolutionPool()
Solution Pool.
Constraint * MakeNonOverlappingBoxesConstraint(const std::vector< IntVar * > &x_vars, const std::vector< IntVar * > &y_vars, const std::vector< IntVar * > &x_size, const std::vector< IntVar * > &y_size)
LocalSearchOperator * MakeNeighborhoodLimit(LocalSearchOperator *op, int64_t limit)
ConstraintSolverStatistics GetConstraintSolverStatistics() const
Returns detailed cp search statistics.
Constraint * MakePathEnergyCostConstraint(PathEnergyCostConstraintSpecification specification)
Decision * MakeSplitVariableDomain(IntVar *var, int64_t val, bool start_with_lower_half)
Constraint * MakeSumGreaterOrEqual(const std::vector< IntVar * > &vars, int64_t cst)
Constraint * MakeTemporalDisjunction(IntervalVar *t1, IntervalVar *t2, IntVar *alt)
Constraint * MakeAllowedAssignments(const std::vector< IntVar * > &vars, const IntTupleSet &tuples)
------— API -------—
Constraint * MakePathPrecedenceConstraint(std::vector< IntVar * > nexts, const std::vector< std::pair< int, int > > &precedences)
IntervalVar * MakeFixedDurationIntervalVar(int64_t start_min, int64_t start_max, int64_t duration, bool optional, const std::string &name)
DecisionBuilder * MakeLocalSearchPhase(Assignment *assignment, LocalSearchPhaseParameters *parameters)
Constraint * MakeLightElement(F values, IntVar *const var, IntVar *const index, std::function< bool()> deep_serialize=nullptr)
Constraint * MakeLess(IntExpr *left, IntExpr *right)
left < right
IntExpr * CastExpression(const IntVar *var) const
!defined(SWIG)
ModelCache * Cache() const
Returns the cache of the model.
IntExpr * MakeOpposite(IntExpr *expr)
-expr
Constraint * MakeAtMost(std::vector< IntVar * > vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| <= max_count
ABSL_MUST_USE_RESULT ImprovementSearchLimit * MakeLexicographicImprovementLimit(std::vector< IntVar * > objective_vars, std::vector< bool > maximize, std::vector< double > objective_scaling_factors, std::vector< double > objective_offsets, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
Constraint * MakeAbsEquality(IntVar *var, IntVar *abs_var)
Creates the constraint abs(var) == abs_var.
OptimizeVar * MakeOptimize(bool maximize, IntVar *v, int64_t step)
Creates a objective with a given sense (true = maximization).
void MakeBoolVarArray(int var_count, const std::string &name, std::vector< IntVar * > *vars)
DecisionBuilder * MakeConstraintAdder(Constraint *ct)
@ STARTS_BEFORE
t starts before d, i.e. Start(t) <= d.
@ ENDS_AT
t ends at d, i.e. End(t) == d.
@ STARTS_AFTER
t starts after d, i.e. Start(t) >= d.
@ ENDS_BEFORE
t ends before d, i.e. End(t) <= d.
@ STARTS_AT
t starts at d, i.e. Start(t) == d.
@ ENDS_AFTER
t ends after d, i.e. End(t) >= d.
IntExpr * MakePiecewiseLinearExpr(IntExpr *expr, const PiecewiseLinearFunction &f)
IntExpr * RegisterIntExpr(IntExpr *expr)
Registers a new IntExpr and wraps it inside a TraceIntExpr if necessary.
int64_t neighbors() const
The number of neighbors created.
Constraint * MakeIsDifferentCt(IntExpr *v1, IntExpr *v2, IntVar *b)
b == (v1 != v2)
Constraint * MakeNullIntersectExcept(const std::vector< IntVar * > &first_vars, const std::vector< IntVar * > &second_vars, int64_t escape_value)
IntExpr * MakeModulo(IntExpr *x, int64_t mod)
Modulo expression x % mod (with the python convention for modulo).
Constraint * MakeGreater(IntExpr *left, IntExpr *right)
left > right
DisjunctiveConstraint * MakeStrictDisjunctiveConstraint(const std::vector< IntervalVar * > &intervals, const std::string &name)
Constraint * MakeLexicalLessOrEqual(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
OptimizationDirection
Optimization directions.
IntVar * MakeIsEqualVar(IntExpr *v1, IntExpr *v2)
status var of (v1 == v2)
IntVar * MakeIsDifferentCstVar(IntExpr *var, int64_t value)
status var of (var != value)
SearchMonitor * MakeAtSolutionCallback(std::function< void()> callback)
Constraint * MakeCount(const std::vector< IntVar * > &vars, int64_t value, int64_t max_count)
|{i | vars[i] == value}| == max_count
@ CHOOSE_MIN_SIZE_LOWEST_MIN
@ CHOOSE_RANDOM
Randomly select one of the remaining unbound variables.
@ CHOOSE_MIN_SIZE_LOWEST_MAX
@ INT_VAR_DEFAULT
The default behavior is CHOOSE_FIRST_UNBOUND.
@ INT_VAR_SIMPLE
The simple selection is CHOOSE_FIRST_UNBOUND.
@ CHOOSE_MIN_SIZE_HIGHEST_MAX
@ CHOOSE_MAX_REGRET_ON_MIN
@ CHOOSE_MIN_SIZE_HIGHEST_MIN
IntVar * MakeIsBetweenVar(IntExpr *v, int64_t l, int64_t u)
Constraint * MakeElementEquality(const std::vector< int64_t > &vals, IntVar *index, IntVar *target)
IntervalVar * MakeFixedInterval(int64_t start, int64_t duration, const std::string &name)
Creates a fixed and performed interval.
Pack * MakePack(const std::vector< IntVar * > &vars, int number_of_bins)
@ LE
Move is accepted when the current objective value <= objective.Max.
@ GE
Move is accepted when the current objective value >= objective.Min.
DecisionBuilder * Try(DecisionBuilder *db1, DecisionBuilder *db2)
T * RevAllocArray(T *object)
SolutionCollector * MakeAllSolutionCollector()
DecisionBuilder * MakeDefaultPhase(const std::vector< IntVar * > &vars)
SequenceStrategy
Used for scheduling. Not yet implemented.
@ CHOOSE_RANDOM_RANK_FORWARD
@ CHOOSE_MIN_SLACK_RANK_FORWARD
LocalSearchFilter * MakeRejectFilter()
IntervalVar * RegisterIntervalVar(IntervalVar *var)
int64_t unchecked_solutions() const
The number of unchecked solutions found by local search.
IntVar * MakeIsGreaterOrEqualCstVar(IntExpr *var, int64_t value)
status var of (var >= value)
Constraint * MakeMinEquality(const std::vector< IntVar * > &vars, IntVar *min_var)
Decision * MakeDecision(Action apply, Action refute)
Constraint * MakeIsLessCt(IntExpr *left, IntExpr *right, IntVar *b)
b == (left < right)
ObjectiveMonitor * MakeLexicographicSimulatedAnnealing(const std::vector< bool > &maximize, std::vector< IntVar * > vars, std::vector< int64_t > steps, std::vector< int64_t > initial_temperatures)
SolutionCollector * MakeFirstSolutionCollector()
Constraint * MakeIndexOfConstraint(const std::vector< IntVar * > &vars, IntVar *index, int64_t target)
int32_t Rand32(int32_t size)
Returns a random value between 0 and 'size' - 1;.
void FinishCurrentSearch()
Tells the solver to kill or restart the current search.
Constraint * MakeDelayedPathCumul(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, const std::vector< IntVar * > &cumuls, const std::vector< IntVar * > &transits)
void Accept(ModelVisitor *visitor) const
Accepts the given model visitor.
Constraint * MakeIndexOfFirstMinValueConstraint(IntVar *index, const std::vector< IntVar * > &vars)
IntExpr * MakeAbs(IntExpr *expr)
expr
Decision * MakeRankFirstInterval(SequenceVar *sequence, int index)
IntExpr * MakeSquare(IntExpr *expr)
expr * expr
std::vector< int64_t > tmp_vector_
SolutionCollector * MakeLastSolutionCollector()
ModelVisitor * MakeVariableDegreeVisitor(absl::flat_hash_map< const IntVar *, int > *map)
Compute the number of constraints a variable is attached to.
Constraint * MakeNoCycle(const std::vector< IntVar * > &nexts, const std::vector< IntVar * > &active, IndexFilter1 sink_handler=nullptr)
bool IsProfilingEnabled() const
Returns whether we are profiling the solver.
MonitorEvent
Search monitor events.
@ kIsUncheckedSolutionLimitReached
@ kAcceptUncheckedNeighbor
@ kLast
Dummy event whose underlying int is the number of MonitorEvent enums.
@ kBeginInitialPropagation
friend class SearchMonitor
std::function< int64_t(int64_t, int64_t, int64_t)> IndexEvaluator3
Constraint * MakeIndexOfFirstMaxValueConstraint(IntVar *index, const std::vector< IntVar * > &vars)
DecisionBuilder * MakeStoreAssignment(Assignment *assignment)
ObjectiveMonitor * MakeGuidedLocalSearch(bool maximize, IntVar *objective, IndexEvaluator2 objective_function, int64_t step, const std::vector< IntVar * > &vars, double penalty_factor, bool reset_penalties_on_new_best_solution=false)
Constraint * MakeScalProdGreaterOrEqual(const std::vector< IntVar * > &vars, const std::vector< int64_t > &coeffs, int64_t cst)
IntExpr * MakeIndexExpression(const std::vector< IntVar * > &vars, int64_t value)
std::string SearchContext() const
@ STARTS_AT_START
t1 starts at t2 start, i.e. Start(t1) == Start(t2) + delay.
@ ENDS_AFTER_END
t1 ends after t2 end, i.e. End(t1) >= End(t2) + delay.
@ ENDS_AFTER_START
t1 ends after t2 start, i.e. End(t1) >= Start(t2) + delay.
@ ENDS_AT_END
t1 ends at t2 end, i.e. End(t1) == End(t2) + delay.
@ ENDS_AT_START
t1 ends at t2 start, i.e. End(t1) == Start(t2) + delay.
@ STARTS_AFTER_END
t1 starts after t2 end, i.e. Start(t1) >= End(t2) + delay.
@ STARTS_AFTER_START
t1 starts after t2 start, i.e. Start(t1) >= Start(t2) + delay.
@ STARTS_AT_END
t1 starts at t2 end, i.e. Start(t1) == End(t2) + delay.
friend class RoutingModel
SolutionCollector * MakeBestLexicographicValueSolutionCollector(const Assignment *assignment, std::vector< bool > maximize)
SearchMonitor * MakeExitSearchCallback(std::function< void()> callback)
LocalSearchOperator * MultiArmedBanditConcatenateOperators(const std::vector< LocalSearchOperator * > &ops, double memory_coefficient, double exploration_coefficient, bool maximize)
SearchMonitor * MakeSearchTrace(const std::string &prefix)
Decision * MakeAssignVariablesValues(const std::vector< IntVar * > &vars, const std::vector< int64_t > &values)
SolutionCollector * MakeNBestValueSolutionCollector(const Assignment *assignment, int solution_count, bool maximize)
Constraint * MakeMaxEquality(const std::vector< IntVar * > &vars, IntVar *max_var)
void ClearLocalSearchState()
Clears the local search state.
std::function< void()> Closure
Constraint * MakeEquality(IntExpr *left, IntExpr *right)
left == right
IntervalVar * MakeIntervalRelaxedMax(IntervalVar *interval_var)
IntVar * MakeIsLessOrEqualVar(IntExpr *left, IntExpr *right)
status var of (left <= right)
LocalSearchOperator * MakeOperator(const std::vector< IntVar * > &vars, LocalSearchOperators op, std::function< const std::vector< int > &(int, int)> get_neighbors=nullptr)
Local Search Operators.
ObjectiveMonitor * MakeLexicographicTabuSearch(const std::vector< bool > &maximize, std::vector< IntVar * > objectives, std::vector< int64_t > steps, const std::vector< IntVar * > &vars, int64_t keep_tenure, int64_t forbid_tenure, double tabu_factor)
Assignment * MakeAssignment()
This method creates an empty assignment.
DecisionBuilder * MakeDecisionBuilderFromAssignment(Assignment *assignment, DecisionBuilder *db, const std::vector< IntVar * > &vars)
EvaluatorLocalSearchOperators
int64_t wall_time() const
ABSL_MUST_USE_RESULT RegularLimit * MakeBranchesLimit(int64_t branches)
@ RELOCATE
Relocate neighborhood with length of 1 (see OROPT comment).
Constraint * MakeTrueConstraint()
This constraint always succeeds.
Decision * MakeScheduleOrPostpone(IntervalVar *var, int64_t est, int64_t *marker)
Demon * MakeDelayedConstraintInitialPropagateCallback(Constraint *ct)
SearchMonitor * MakeSearchLog(int branch_period)
std::function< IntVar *(int64_t)> Int64ToIntVar
friend class PropagationBaseObject
ObjectiveMonitor * MakeSimulatedAnnealing(bool maximize, IntVar *v, int64_t step, int64_t initial_temperature)
Constraint * MakeLessOrEqual(IntExpr *left, IntExpr *right)
left <= right
bool HasName(const PropagationBaseObject *object) const
Returns whether the object has been named or not.
Constraint * MakeIsGreaterOrEqualCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var >= value)
OptimizeVar * MakeMinimize(IntVar *v, int64_t step)
Creates a minimization objective.
void SetSearchContext(Search *search, absl::string_view search_context)
void RestartCurrentSearch()
IntervalVar * MakeFixedDurationEndSyncedOnEndIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Constraint * MakeLexicalLessOrEqualWithOffsets(std::vector< IntVar * > left, std::vector< IntVar * > right, std::vector< int64_t > offsets)
std::string DebugString() const
!defined(SWIG)
Constraint * MakeBetweenCt(IntExpr *expr, int64_t l, int64_t u)
--— Between and related constraints --—
DemonProfiler * demon_profiler() const
Access to demon profiler.
Demon * MakeConstraintInitialPropagateCallback(Constraint *ct)
void MakeIntVarArray(int var_count, int64_t vmin, int64_t vmax, const std::string &name, std::vector< IntVar * > *vars)
ABSL_MUST_USE_RESULT RegularLimit * MakeLimit(absl::Duration time, int64_t branches, int64_t failures, int64_t solutions, bool smart_time_check=false, bool cumulative=false)
OptimizeVar * MakeWeightedMaximize(const std::vector< IntVar * > &sub_objectives, const std::vector< int64_t > &weights, int64_t step)
Creates a maximization weigthed objective.
int64_t filtered_neighbors() const
The number of filtered neighbors (neighbors accepted by filters).
Decision * MakeAssignVariableValueOrDoNothing(IntVar *var, int64_t value)
SolverState state() const
State of the solver.
SolutionCollector * MakeNBestLexicographicValueSolutionCollector(const Assignment *assignment, int solution_count, std::vector< bool > maximize)
int64_t Rand64(int64_t size)
Returns a random value between 0 and 'size' - 1;.
IntVar * MakeIntVar(int64_t min, int64_t max, const std::string &name)
--— Int Variables and Constants --—
std::function< bool(int64_t, int64_t, int64_t)> VariableValueComparator
ConstraintSolverParameters parameters() const
Stored Parameters.
Constraint * MakeAllDifferent(const std::vector< IntVar * > &vars)
Constraint * MakeIntervalVarRelationWithDelay(IntervalVar *t1, BinaryIntervalRelation r, IntervalVar *t2, int64_t delay)
bool Solve(DecisionBuilder *db, const std::vector< SearchMonitor * > &monitors)
ModelVisitor * MakePrintModelVisitor()
Prints the model.
void SaveValue(T *o)
reversibility
Constraint * MakeFalseConstraint()
This constraint always fails.
friend void InternalSaveBooleanVarValue(Solver *, IntVar *)
ObjectiveMonitor * MakeGenericTabuSearch(bool maximize, IntVar *v, int64_t step, const std::vector< IntVar * > &tabu_vars, int64_t forbid_tenure)
void ReSeed(int32_t seed)
Reseed the solver random generator.
@ INTERVAL_SET_TIMES_FORWARD
@ INTERVAL_DEFAULT
The default is INTERVAL_SET_TIMES_FORWARD.
@ INTERVAL_SET_TIMES_BACKWARD
@ INTERVAL_SIMPLE
The simple is INTERVAL_SET_TIMES_FORWARD.
bool IsProduct(IntExpr *expr, IntExpr **inner_expr, int64_t *coefficient)
IntExpr * MakeConvexPiecewiseExpr(IntExpr *expr, int64_t early_cost, int64_t early_date, int64_t late_date, int64_t late_cost)
Convex piecewise function.
Assignment * GetOrCreateLocalSearchState()
std::function< int64_t(Solver *solver, const std::vector< IntVar * > &vars, int64_t first_unbound, int64_t last_unbound)> VariableIndexSelector
IntervalVar * MakeFixedDurationStartSyncedOnStartIntervalVar(IntervalVar *interval_var, int64_t duration, int64_t offset)
Synced Interval Vars.
void set_optimization_direction(OptimizationDirection direction)
IntExpr * MakePower(IntExpr *expr, int64_t n)
expr ^ n (n > 0)
IntExpr * MakeConditionalExpression(IntVar *condition, IntExpr *expr, int64_t unperformed_value)
Conditional Expr condition ? expr : unperformed_value.
@ ASSIGN_MAX_VALUE
Selects the max value of the selected variable.
@ INT_VALUE_DEFAULT
The default behavior is ASSIGN_MIN_VALUE.
@ INT_VALUE_SIMPLE
The simple selection is ASSIGN_MIN_VALUE.
@ ASSIGN_MIN_VALUE
Selects the min value of the selected variable.
@ ASSIGN_RANDOM_VALUE
Selects randomly one of the possible values of the selected variable.
OptimizeVar * MakeLexicographicOptimize(std::vector< bool > maximize, std::vector< IntVar * > variables, std::vector< int64_t > steps)
std::function< int64_t(int64_t)> IndexEvaluator1
Callback typedefs.
SearchMonitor * MakeSymmetryManager(const std::vector< SymmetryBreaker * > &visitors)
Symmetry Breaking.
IntVar * MakeIsLessCstVar(IntExpr *var, int64_t value)
status var of (var < value)
IntervalVar * MakeIntervalRelaxedMin(IntervalVar *interval_var)
int64_t failures() const
The number of failures encountered since the creation of the solver.
bool CheckConstraint(Constraint *ct)
RegularLimitParameters MakeDefaultRegularLimitParameters() const
Creates a regular limit proto containing default values.
std::function< int64_t(int64_t, int64_t)> IndexEvaluator2
bool InstrumentsDemons() const
Returns whether we are instrumenting demons.
Constraint * MakeIsBetweenCt(IntExpr *expr, int64_t l, int64_t u, IntVar *b)
b == (l <= expr <= u)
Constraint * MakeIsLessOrEqualCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var <= value)
PropagationMonitor * GetPropagationMonitor() const
Returns the propagation monitor.
Constraint * MakeTransitionConstraint(const std::vector< IntVar * > &vars, const IntTupleSet &transition_table, int64_t initial_state, const std::vector< int64_t > &final_states)
Decision * MakeFailDecision()
IntExpr * MakeProd(IntExpr *left, IntExpr *right)
left * right
IntVar * MakeIntConst(int64_t val, const std::string &name)
IntConst will create a constant expression.
Constraint * MakeIntervalVarRelation(IntervalVar *t, UnaryIntervalRelation r, int64_t d)
Demon * MakeActionDemon(Action action)
Creates a demon from a callback.
Constraint * MakeNullIntersect(const std::vector< IntVar * > &first_vars, const std::vector< IntVar * > &second_vars)
Solver(const std::string &name)
Solver API.
bool InstrumentsVariables() const
Returns whether we are tracing variables.
Constraint * MakeNotBetweenCt(IntExpr *expr, int64_t l, int64_t u)
void AddLocalSearchMonitor(LocalSearchMonitor *monitor)
Constraint * MakePathTransitPrecedenceConstraint(std::vector< IntVar * > nexts, std::vector< IntVar * > transits, const std::vector< std::pair< int, int > > &precedences)
static int64_t MemoryUsage()
Current memory usage in bytes.
Constraint * MakeCover(const std::vector< IntervalVar * > &vars, IntervalVar *target_var)
void AddConstraint(Constraint *c)
LocalSearchOperator * MakeRandomLnsOperator(const std::vector< IntVar * > &vars, int number_of_variables)
Constraint * MakeInversePermutationConstraint(const std::vector< IntVar * > &left, const std::vector< IntVar * > &right)
void SetUseFastLocalSearch(bool use_fast_local_search)
OptimizeVar * MakeMaximize(IntVar *v, int64_t step)
Creates a maximization objective.
@ CHOOSE_DYNAMIC_GLOBAL_BEST
@ CHOOSE_STATIC_GLOBAL_BEST
Constraint * MakeIsDifferentCstCt(IntExpr *var, int64_t value, IntVar *boolvar)
boolvar == (var != value)
IntExpr * MakeSemiContinuousExpr(IntExpr *expr, int64_t fixed_charge, int64_t step)
ABSL_MUST_USE_RESULT ImprovementSearchLimit * MakeImprovementLimit(IntVar *objective_var, bool maximize, double objective_scaling_factor, double objective_offset, double improvement_rate_coefficient, int improvement_rate_solutions_distance)
ModelVisitor * MakeStatisticsModelVisitor()
Displays some nice statistics on the model.
bool SolveAndCommit(DecisionBuilder *db, const std::vector< SearchMonitor * > &monitors)
void AddCastConstraint(CastConstraint *constraint, IntVar *target_var, IntExpr *expr)
ABSL_DECLARE_FLAG(int64_t, cp_random_seed)
CpModelProto proto
The output proto.
const std::string name
A name for logging purposes.
absl::Span< const double > coefficients
bool FindCopy(const Collection &collection, const Key &key, Value *const value)
const MapUtilMappedT< Collection > & FindWithDefault(const Collection &collection, const KeyType &key, const MapUtilMappedT< Collection > &value)
In SWIG mode, we don't want anything besides these top-level includes.
int64_t CapSub(int64_t x, int64_t y)
std::ostream & operator<<(std::ostream &out, const Assignment &assignment)
int64_t One()
This method returns 1.
void SetAssignmentFromAssignment(Assignment *target_assignment, const std::vector< IntVar * > &target_vars, const Assignment *source_assignment, const std::vector< IntVar * > &source_vars)
NOLINT.
int64_t CapOpp(int64_t v)
Note(user): -kint64min != kint64max, but kint64max == ~kint64min.
std::vector< double > upper_bounds
bool use_last_conflict
Should we use last conflict method. The default is false.
DecisionBuilder * decision_builder
When defined, this overrides the default impact based decision builder.
int initialization_splits
int heuristic_num_failures_limit
The failure limit for each heuristic that we run.
DisplayLevel display_level
@ CHOOSE_MAX_VALUE_IMPACT
@ CHOOSE_MAX_AVERAGE_IMPACT
ValueSelection value_selection_schema
This parameter describes which value to select for a given var.
int random_seed
Seed used to initialize the random part in some heuristics.
VariableSelection var_selection_schema
static Iterator End(IntVarIterator *it)
bool operator!=(const Iterator &other) const
static Iterator Begin(IntVarIterator *it)
These are the only way to construct an Iterator.
int64_t operator*() const
int64_t ObjectiveValue() const
bool operator<(const SolutionData &other) const
int64_t ObjectiveValueFromIndex(int index) const
std::vector< IntVar * > paths
std::vector< IntVar * > nexts
std::vector< int64_t > path_unit_costs
std::vector< bool > path_used_when_empty
std::vector< IntVar * > forces
std::vector< int64_t > path_starts
std::vector< IntVar * > costs
std::vector< int64_t > path_ends
std::vector< IntVar * > distances
std::vector< double > scaling_factors
std::vector< double > offsets
std::function< std::string()> display_callback
bool display_on_new_solutions_only
std::vector< IntVar * > variables
---------------— StateMarker / StateInfo struct --------—
double objective_value
The value objective_vector^T * (solution - center_point).
static const int64_t kint64max