19#if !defined(__PORTABLE_PLATFORM__)
24#include "absl/container/flat_hash_set.h"
25#include "absl/random/random.h"
38 "DEBUG ONLY. If true, all the intermediate solution will be dumped "
39 "under '\"FLAGS_cp_model_dump_prefix\" + \"solution_xxx.pb.txt\"'.");
42 std::string, cp_model_load_debug_solution,
"",
43 "DEBUG ONLY. When this is set to a non-empty file name, "
44 "we will interpret this as an internal solution which can be used for "
45 "debugging. For instance we use it to identify wrong cuts/reasons.");
54 if (
response.solution().empty())
return;
58 solution.variable_values.assign(
response.solution().begin(),
65 solution.rank = -
response.best_objective_bound();
71 std::vector<double> lp_solution) {
72 if (lp_solution.empty())
return;
76 solution.variable_values = std::move(lp_solution);
79 absl::MutexLock mutex_lock(&
mutex_);
80 solution.rank = -num_synchronization_;
85 absl::MutexLock mutex_lock(&mutex_);
86 return !solutions_.empty();
90 absl::MutexLock mutex_lock(&mutex_);
91 std::vector<double> solution;
92 if (solutions_.empty())
return solution;
94 solution = std::move(solutions_.back());
95 solutions_.pop_back();
100 const std::vector<double>& lp_solution) {
101 absl::MutexLock mutex_lock(&mutex_);
102 solutions_.push_back(lp_solution);
109 solutions_(parameters_.solution_pool_size()),
114std::string ProgressMessage(
const std::string& event_or_solution_count,
115 double time_in_seconds,
double obj_best,
116 double obj_lb,
double obj_ub,
117 const std::string& solution_info) {
118 const std::string obj_next =
119 absl::StrFormat(
"next:[%.9g,%.9g]", obj_lb, obj_ub);
120 return absl::StrFormat(
"#%-5s %6.2fs best:%-5.9g %-15s %s",
121 event_or_solution_count, time_in_seconds, obj_best,
122 obj_next, solution_info);
125std::string SatProgressMessage(
const std::string& event_or_solution_count,
126 double time_in_seconds,
127 const std::string& solution_info) {
128 return absl::StrFormat(
"#%-5s %6.2fs %s", event_or_solution_count,
129 time_in_seconds, solution_info);
135 absl::MutexLock mutex_lock(&mutex_);
137 absl::StrFormat(
"#Model %6.2fs %s", wall_timer_.
Get(),
message));
142 objective_or_null_ = &cp_model.
objective();
146 IntegerValue(domain.
Max()));
149 objective_or_null_ =
nullptr;
154 absl::MutexLock mutex_lock(&mutex_);
155 update_integral_on_each_change_ = set;
159 absl::MutexLock mutex_lock(&mutex_);
160 UpdateGapIntegralInternal();
163void SharedResponseManager::UpdateGapIntegralInternal() {
164 if (objective_or_null_ ==
nullptr)
return;
167 const double time_delta = current_time - last_gap_integral_time_stamp_;
175 const double factor =
177 const double bounds_delta = std::log(1 + factor * last_absolute_gap_);
178 gap_integral_ += time_delta * bounds_delta;
181 last_gap_integral_time_stamp_ = current_time;
183 std::max(0.0,
static_cast<double>(inner_objective_upper_bound_) -
184 static_cast<double>(inner_objective_lower_bound_));
189 absl::MutexLock mutex_lock(&mutex_);
190 if (objective_or_null_ ==
nullptr)
return;
191 absolute_gap_limit_ =
parameters.absolute_gap_limit();
192 relative_gap_limit_ =
parameters.relative_gap_limit();
195void SharedResponseManager::TestGapLimitsIfNeeded() {
199 if (update_integral_on_each_change_) UpdateGapIntegralInternal();
201 if (absolute_gap_limit_ == 0 && relative_gap_limit_ == 0)
return;
206 const double user_best =
208 const double user_bound =
210 const double gap = std::abs(user_best - user_bound);
211 if (gap <= absolute_gap_limit_) {
212 SOLVER_LOG(logger_,
"Absolute gap limit of ", absolute_gap_limit_,
219 shared_time_limit_->
Stop();
221 if (gap /
std::max(1.0, std::abs(user_best)) < relative_gap_limit_) {
222 SOLVER_LOG(logger_,
"Relative gap limit of ", relative_gap_limit_,
227 shared_time_limit_->
Stop();
232 const std::string& update_info, IntegerValue lb, IntegerValue ub) {
233 absl::MutexLock mutex_lock(&mutex_);
234 CHECK(objective_or_null_ !=
nullptr);
241 if (inner_objective_lower_bound_ > inner_objective_upper_bound_) {
246 (lb > inner_objective_lower_bound_ || ub < inner_objective_upper_bound_);
247 if (lb > inner_objective_lower_bound_) {
252 DCHECK_LE(inner_objective_upper_bound_, best_solution_objective_value_);
253 inner_objective_lower_bound_ =
254 std::min(best_solution_objective_value_, lb.value());
256 if (ub < inner_objective_upper_bound_) {
257 inner_objective_upper_bound_ = ub.value();
259 if (inner_objective_lower_bound_ > inner_objective_upper_bound_) {
266 if (update_integral_on_each_change_) UpdateGapIntegralInternal();
268 SatProgressMessage(
"Done", wall_timer_.
Get(), update_info));
280 RegisterObjectiveBoundImprovement(update_info);
281 SOLVER_LOG(logger_, ProgressMessage(
"Bound", wall_timer_.
Get(), best,
282 new_lb, new_ub, update_info));
284 if (change) TestGapLimitsIfNeeded();
291 const std::string& worker_info) {
292 absl::MutexLock mutex_lock(&mutex_);
301 inner_objective_lower_bound_ = best_solution_objective_value_;
302 if (update_integral_on_each_change_) UpdateGapIntegralInternal();
308 SatProgressMessage(
"Done", wall_timer_.
Get(), worker_info));
312 absl::MutexLock mutex_lock(&mutex_);
313 best_response_.clear_sufficient_assumptions_for_infeasibility();
314 for (
const int ref : core) {
315 best_response_.add_sufficient_assumptions_for_infeasibility(ref);
320 absl::MutexLock mutex_lock(&mutex_);
321 return IntegerValue(inner_objective_lower_bound_);
325 absl::MutexLock mutex_lock(&mutex_);
326 return IntegerValue(inner_objective_upper_bound_);
330 absl::MutexLock mutex_lock(&mutex_);
331 synchronized_inner_objective_lower_bound_ =
332 IntegerValue(inner_objective_lower_bound_);
333 synchronized_inner_objective_upper_bound_ =
334 IntegerValue(inner_objective_upper_bound_);
338 absl::MutexLock mutex_lock(&mutex_);
339 return synchronized_inner_objective_lower_bound_;
343 absl::MutexLock mutex_lock(&mutex_);
344 return synchronized_inner_objective_upper_bound_;
348 absl::MutexLock mutex_lock(&mutex_);
349 return IntegerValue(best_solution_objective_value_);
353 absl::MutexLock mutex_lock(&mutex_);
354 return gap_integral_;
358 std::function<
void(std::vector<int64_t>*)> postprocessor) {
359 absl::MutexLock mutex_lock(&mutex_);
360 solution_postprocessors_.push_back(postprocessor);
365 absl::MutexLock mutex_lock(&mutex_);
366 postprocessors_.push_back(postprocessor);
371 absl::MutexLock mutex_lock(&mutex_);
372 final_postprocessors_.push_back(postprocessor);
377 absl::MutexLock mutex_lock(&mutex_);
378 const int id = next_callback_id_++;
379 callbacks_.emplace_back(
id, std::move(
callback));
384 absl::MutexLock mutex_lock(&mutex_);
385 for (
int i = 0; i < callbacks_.size(); ++i) {
386 if (callbacks_[i].first == callback_id) {
387 callbacks_.erase(callbacks_.begin() + i);
391 LOG(DFATAL) <<
"Callback id " << callback_id <<
" not registered.";
395 FillObjectiveValuesInBestResponse();
401 std::vector<int64_t> solution(result.
solution().begin(),
403 for (
int i = solution_postprocessors_.size(); --i >= 0;) {
404 solution_postprocessors_[i](&solution);
408 for (
int i = postprocessors_.size(); --i >= 0;) {
409 postprocessors_[i](&result);
415 absl::MutexLock mutex_lock(&mutex_);
420 std::vector<int64_t> temp;
421 for (
int i = 0; i < solutions_.NumSolutions(); ++i) {
422 temp = solutions_.GetSolution(i).variable_values;
423 for (
int i = solution_postprocessors_.size(); --i >= 0;) {
424 solution_postprocessors_[i](&temp);
427 temp.begin(), temp.end());
430 for (
int i = final_postprocessors_.size(); --i >= 0;) {
431 final_postprocessors_[i](&result);
437void SharedResponseManager::FillObjectiveValuesInBestResponse() {
438 if (objective_or_null_ ==
nullptr)
return;
442 best_response_.clear_objective_value();
443 best_response_.clear_best_objective_bound();
444 best_response_.clear_inner_objective_lower_bound();
451 best_response_.set_objective_value(
454 best_response_.set_objective_value(
459 best_response_.set_inner_objective_lower_bound(
461 best_response_.set_best_objective_bound(
465 best_response_.set_gap_integral(gap_integral_);
470 absl::MutexLock mutex_lock(&mutex_);
476 solution.variable_values.assign(
response.solution().begin(),
478 solutions_.
Add(solution);
481 if (objective_or_null_ !=
nullptr) {
482 const int64_t objective_value =
488 solution.variable_values.assign(
response.solution().begin(),
490 solution.rank = objective_value;
491 solutions_.
Add(solution);
495 if (objective_value > inner_objective_upper_bound_)
return;
501 DCHECK_GE(objective_value, inner_objective_lower_bound_);
503 DCHECK_LT(objective_value, best_solution_objective_value_);
504 best_solution_objective_value_ = objective_value;
507 inner_objective_upper_bound_ = objective_value - 1;
513 if (update_integral_on_each_change_) {
514 solutions_.Synchronize();
525 best_response_.set_solution_info(
response.solution_info());
526 *best_response_.mutable_solution() =
response.solution();
529 if (objective_or_null_ !=
nullptr &&
530 inner_objective_lower_bound_ > inner_objective_upper_bound_) {
537 std::string solution_info =
response.solution_info();
538 if (
model !=
nullptr) {
540 const int64_t num_fixed =
model->Get<
SatSolver>()->NumFixedVariables();
541 absl::StrAppend(&solution_info,
" fixed_bools:", num_fixed,
"/",
545 if (objective_or_null_ !=
nullptr) {
554 RegisterSolutionFound(solution_info);
555 SOLVER_LOG(logger_, ProgressMessage(absl::StrCat(num_solutions_),
556 wall_timer_.
Get(), best, lb, ub,
559 SOLVER_LOG(logger_, SatProgressMessage(absl::StrCat(num_solutions_),
560 wall_timer_.
Get(), solution_info));
566 TestGapLimitsIfNeeded();
567 if (!callbacks_.empty()) {
568 SetStatsFromModelInternal(
model);
570 for (
const auto& pair : callbacks_) {
575#if !defined(__PORTABLE_PLATFORM__)
578 if (absl::GetFlag(FLAGS_cp_model_dump_solutions)) {
579 const std::string
file =
580 absl::StrCat(dump_prefix_,
"solution_", num_solutions_,
".pb.txt");
581 LOG(
INFO) <<
"Dumping solution to '" <<
file <<
"'.";
588#if !defined(__PORTABLE_PLATFORM__)
589 if (absl::GetFlag(FLAGS_cp_model_load_debug_solution).empty())
return;
593 LOG(
INFO) <<
"Reading solution from '"
594 << absl::GetFlag(FLAGS_cp_model_load_debug_solution) <<
"'.";
600 debug_solution.resize(
602 for (
int i = 0; i <
response.solution().size(); ++i) {
603 if (!mapping.IsInteger(i))
continue;
604 const IntegerVariable
var = mapping.Integer(i);
612 if (objective_def ==
nullptr)
return;
614 const IntegerVariable objective_var = objective_def->
objective_var;
615 const int64_t objective_value =
617 debug_solution[objective_var] = objective_value;
618 debug_solution[
NegationOf(objective_var)] = -objective_value;
623 absl::MutexLock mutex_lock(&mutex_);
624 SetStatsFromModelInternal(
model);
627void SharedResponseManager::SetStatsFromModelInternal(
Model*
model) {
628 if (
model ==
nullptr)
return;
631 best_response_.set_num_booleans(sat_solver->NumVariables());
632 best_response_.set_num_branches(sat_solver->num_branches());
633 best_response_.set_num_conflicts(sat_solver->num_failures());
634 best_response_.set_num_binary_propagations(sat_solver->num_propagations());
635 best_response_.set_num_restarts(sat_solver->num_restarts());
636 best_response_.set_num_integer_propagations(
637 integer_trail ==
nullptr ? 0 : integer_trail->num_enqueues());
639 best_response_.set_wall_time(
time_limit->GetElapsedTime());
640 best_response_.set_deterministic_time(
643 int64_t num_lp_iters = 0;
646 num_lp_iters += lp->total_num_simplex_iterations();
648 best_response_.set_num_lp_iterations(num_lp_iters);
652 absl::MutexLock mutex_lock(&mutex_);
658 if (improvement_info.empty())
return "";
661 for (
int i = 0; i < improvement_info.size(); ++i) {
662 if (!std::isalnum(improvement_info[i]) && improvement_info[i] !=
'_') {
663 return improvement_info.substr(0, i);
667 return improvement_info;
670void SharedResponseManager::RegisterSolutionFound(
671 const std::string& improvement_info) {
672 if (improvement_info.empty())
return;
676void SharedResponseManager::RegisterObjectiveBoundImprovement(
677 const std::string& improvement_info) {
678 if (improvement_info.empty() || improvement_info ==
"initial domain")
return;
683 absl::MutexLock mutex_lock(&mutex_);
684 if (!primal_improvements_count_.empty()) {
685 SOLVER_LOG(logger_,
"Solutions found per subsolver:");
686 for (
const auto& entry : primal_improvements_count_) {
687 SOLVER_LOG(logger_,
" '", entry.first,
"': ", entry.second);
690 if (!dual_improvements_count_.empty()) {
692 SOLVER_LOG(logger_,
"Objective bounds found per subsolver:");
693 for (
const auto& entry : dual_improvements_count_) {
694 SOLVER_LOG(logger_,
" '", entry.first,
"': ", entry.second);
702 lower_bounds_(num_variables_,
std::numeric_limits<int64_t>::
min()),
703 upper_bounds_(num_variables_,
std::numeric_limits<int64_t>::
max()),
704 synchronized_lower_bounds_(num_variables_,
705 std::numeric_limits<int64_t>::
min()),
706 synchronized_upper_bounds_(num_variables_,
707 std::numeric_limits<int64_t>::
max()) {
708 changed_variables_since_last_synchronize_.ClearAndResize(num_variables_);
709 for (
int i = 0; i < num_variables_; ++i) {
710 lower_bounds_[i] =
model_proto.variables(i).domain(0);
711 const int domain_size =
model_proto.variables(i).domain_size();
712 upper_bounds_[i] =
model_proto.variables(i).domain(domain_size - 1);
713 synchronized_lower_bounds_[i] = lower_bounds_[i];
714 synchronized_upper_bounds_[i] = upper_bounds_[i];
720 const std::vector<int>& variables,
721 const std::vector<int64_t>& new_lower_bounds,
722 const std::vector<int64_t>& new_upper_bounds) {
723 CHECK_EQ(variables.size(), new_lower_bounds.size());
724 CHECK_EQ(variables.size(), new_upper_bounds.size());
725 int num_improvements = 0;
727 absl::MutexLock mutex_lock(&mutex_);
728 for (
int i = 0; i < variables.size(); ++i) {
729 const int var = variables[i];
730 if (
var >= num_variables_)
continue;
731 const int64_t old_lb = lower_bounds_[
var];
732 const int64_t old_ub = upper_bounds_[
var];
733 const int64_t new_lb = new_lower_bounds[i];
734 const int64_t new_ub = new_upper_bounds[i];
735 const bool changed_lb = new_lb > old_lb;
736 const bool changed_ub = new_ub < old_ub;
738 if (!changed_lb && !changed_ub)
continue;
741 lower_bounds_[
var] = new_lb;
744 upper_bounds_[
var] = new_ub;
746 changed_variables_since_last_synchronize_.Set(
var);
751 if (num_improvements > 0) {
752 VLOG(2) << worker_name <<
" exports " << num_improvements
761 const std::vector<int64_t>& solution,
762 const std::vector<int>& variables_to_fix) {
763 absl::MutexLock mutex_lock(&mutex_);
769 for (
const int var : variables_to_fix) {
770 const int64_t
value = solution[
var];
772 VLOG(1) <<
"Incompatibility in FixVariablesFromPartialSolution() "
773 <<
"var: " <<
var <<
" value: " <<
value <<
" bounds: ["
774 << lower_bounds_[
var] <<
"," << upper_bounds_[
var] <<
"]";
780 for (
const int var : variables_to_fix) {
781 const int64_t old_lb = lower_bounds_[
var];
782 const int64_t old_ub = upper_bounds_[
var];
783 const bool changed_lb = solution[
var] > old_lb;
784 const bool changed_ub = solution[
var] < old_ub;
785 if (!changed_lb && !changed_ub)
continue;
787 lower_bounds_[
var] = solution[
var];
788 upper_bounds_[
var] = solution[
var];
789 changed_variables_since_last_synchronize_.Set(
var);
794 absl::MutexLock mutex_lock(&mutex_);
796 changed_variables_since_last_synchronize_.PositionsSetAtLeastOnce()) {
797 synchronized_lower_bounds_[
var] = lower_bounds_[
var];
798 synchronized_upper_bounds_[
var] = upper_bounds_[
var];
799 for (
int j = 0; j < id_to_changed_variables_.size(); ++j) {
800 id_to_changed_variables_[j].Set(
var);
803 changed_variables_since_last_synchronize_.ClearAll();
807 absl::MutexLock mutex_lock(&mutex_);
808 const int id = id_to_changed_variables_.size();
809 id_to_changed_variables_.resize(
id + 1);
810 id_to_changed_variables_[id].ClearAndResize(num_variables_);
811 for (
int var = 0;
var < num_variables_; ++
var) {
815 if (lb != synchronized_lower_bounds_[
var] ||
816 ub != synchronized_upper_bounds_[
var]) {
817 id_to_changed_variables_[id].Set(
var);
824 int id, std::vector<int>* variables, std::vector<int64_t>* new_lower_bounds,
825 std::vector<int64_t>* new_upper_bounds) {
827 new_lower_bounds->clear();
828 new_upper_bounds->clear();
830 absl::MutexLock mutex_lock(&mutex_);
831 for (
const int var : id_to_changed_variables_[
id].PositionsSetAtLeastOnce()) {
832 variables->push_back(
var);
833 new_lower_bounds->push_back(synchronized_lower_bounds_[
var]);
834 new_upper_bounds->push_back(synchronized_upper_bounds_[
var]);
836 id_to_changed_variables_[id].ClearAll();
#define DCHECK_LE(val1, val2)
#define CHECK_EQ(val1, val2)
#define CHECK_GE(val1, val2)
#define DCHECK_GE(val1, val2)
#define DCHECK_LT(val1, val2)
#define VLOG(verboselevel)
We call domain any subset of Int64 = [kint64min, kint64max].
int64_t Min() const
Returns the min value of the domain.
bool IsEmpty() const
Returns true if this is the empty set.
int64_t Max() const
Returns the max value of the domain.
double GetElapsedDeterministicTime() const
bool LoggingIsEnabled() const
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
const ::operations_research::sat::CpObjectiveProto & objective() const
const ::operations_research::sat::IntegerVariableProto & variables(int index) const
bool has_objective() const
double scaling_factor() const
int64_t solution(int index) const
::operations_research::sat::CpSolverStatus status() const
::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > * mutable_solution()
::operations_research::sat::CpSolverSolution * add_additional_solutions()
::PROTOBUF_NAMESPACE_ID::RepeatedField< int64_t > * mutable_values()
IntegerVariable NumIntegerVariables() const
int64_t domain(int index) const
Class that owns everything related to a particular optimization model.
bool enumerate_all_solutions() const
bool fill_additional_solutions_in_response() const
SharedBoundsManager(const CpModelProto &model_proto)
void ReportPotentialNewBounds(const CpModelProto &model_proto, const std::string &worker_name, const std::vector< int > &variables, const std::vector< int64_t > &new_lower_bounds, const std::vector< int64_t > &new_upper_bounds)
void FixVariablesFromPartialSolution(const std::vector< int64_t > &solution, const std::vector< int > &variables_to_fix)
void GetChangedBounds(int id, std::vector< int > *variables, std::vector< int64_t > *new_lower_bounds, std::vector< int64_t > *new_upper_bounds)
void AddNewSolution(const std::vector< double > &lp_solution)
std::vector< double > GetNewSolution()
bool HasNewSolution() const
void NewLPSolution(std::vector< double > lp_solution)
void NewRelaxationSolution(const CpSolverResponse &response)
bool ProblemIsSolved() const
void InitializeObjective(const CpModelProto &cp_model)
void SetStatsFromModel(Model *model)
CpSolverResponse GetResponse(bool full_response=true)
void AddSolutionPostprocessor(std::function< void(std::vector< int64_t > *)> postprocessor)
void AddFinalResponsePostprocessor(std::function< void(CpSolverResponse *)> postprocessor)
IntegerValue GetInnerObjectiveUpperBound()
IntegerValue SynchronizedInnerObjectiveUpperBound()
IntegerValue SynchronizedInnerObjectiveLowerBound()
void NewSolution(const CpSolverResponse &response, Model *model)
void DisplayImprovementStatistics()
double GapIntegral() const
void NotifyThatImprovingProblemIsInfeasible(const std::string &worker_info)
void SetUpdateGapIntegralOnEachChange(bool set)
IntegerValue BestSolutionInnerObjectiveValue()
void AddUnsatCore(const std::vector< int > &core)
void SetGapLimitsFromParameters(const SatParameters ¶meters)
void LogMessage(std::string message)
void AddResponsePostprocessor(std::function< void(CpSolverResponse *)> postprocessor)
int AddSolutionCallback(std::function< void(const CpSolverResponse &)> callback)
void LoadDebugSolution(Model *)
IntegerValue GetInnerObjectiveLowerBound()
void UnregisterCallback(int callback_id)
SharedResponseManager(Model *model)
void UpdateInnerObjectiveBounds(const std::string &update_info, IntegerValue lb, IntegerValue ub)
void Add(const Solution &solution)
void AddInternal(const Solution &solution) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_)
CpModelProto const * model_proto
SharedResponseManager * response
ModelSharedTimeLimit * time_limit
absl::Status GetTextProto(const absl::string_view &filename, google::protobuf::Message *proto, int flags)
absl::Status SetTextProto(const absl::string_view &filename, const google::protobuf::Message &proto, int flags)
int NumVariables(const VariablesProto &variables)
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
int64_t ComputeInnerObjective(const CpObjectiveProto &objective, const CpSolverResponse &response)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
double ScaleObjectiveValue(const CpObjectiveProto &proto, int64_t value)
std::string ExtractSubSolverName(const std::string &improvement_info)
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
int64_t ScaleInnerObjectiveValue(const CpObjectiveProto &proto, int64_t value)
Collection of objects used to extend the Constraint Solver library.
IntegerVariable objective_var
ABSL_FLAG(bool, cp_model_dump_solutions, false, "DEBUG ONLY. If true, all the intermediate solution will be dumped " "under '\"FLAGS_cp_model_dump_prefix\" + \"solution_xxx.pb.txt\"'.")
#define SOLVER_LOG(logger,...)