19 #if !defined(__PORTABLE_PLATFORM__) 22 #endif // __PORTABLE_PLATFORM__ 24 #include "absl/container/flat_hash_set.h" 25 #include "absl/random/random.h" 37 ABSL_FLAG(
bool, cp_model_dump_solutions,
false,
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);
106 : enumerate_all_solutions_(
115 std::string ProgressMessage(
const std::string& event_or_solution_count,
116 double time_in_seconds,
double obj_best,
117 double obj_lb,
double obj_ub,
118 const std::string& solution_info) {
119 const std::string obj_next =
120 absl::StrFormat(
"next:[%.9g,%.9g]", obj_lb, obj_ub);
121 return absl::StrFormat(
"#%-5s %6.2fs best:%-5.9g %-15s %s",
122 event_or_solution_count, time_in_seconds, obj_best,
123 obj_next, solution_info);
126 std::string SatProgressMessage(
const std::string& event_or_solution_count,
127 double time_in_seconds,
128 const std::string& solution_info) {
129 return absl::StrFormat(
"#%-5s %6.2fs %s", event_or_solution_count,
130 time_in_seconds, solution_info);
137 objective_or_null_ = &cp_model.
objective();
141 IntegerValue(domain.
Max()));
144 objective_or_null_ =
nullptr;
149 absl::MutexLock mutex_lock(&mutex_);
150 update_integral_on_each_change_ = set;
154 absl::MutexLock mutex_lock(&mutex_);
155 UpdatePrimalIntegralInternal();
158 void SharedResponseManager::UpdatePrimalIntegralInternal() {
159 if (objective_or_null_ ==
nullptr)
return;
162 const double time_delta = current_time - last_primal_integral_time_stamp_;
170 const double factor =
172 const double bounds_delta = std::log(1 + factor * last_absolute_gap_);
173 primal_integral_ += time_delta * bounds_delta;
176 last_primal_integral_time_stamp_ = current_time;
178 std::max(0.0, static_cast<double>(inner_objective_upper_bound_) -
179 static_cast<double>(inner_objective_lower_bound_));
184 absl::MutexLock mutex_lock(&mutex_);
185 if (objective_or_null_ ==
nullptr)
return;
186 absolute_gap_limit_ =
parameters.absolute_gap_limit();
187 relative_gap_limit_ =
parameters.relative_gap_limit();
190 void SharedResponseManager::TestGapLimitsIfNeeded() {
194 if (update_integral_on_each_change_) UpdatePrimalIntegralInternal();
196 if (absolute_gap_limit_ == 0 && relative_gap_limit_ == 0)
return;
201 const double user_best =
203 const double user_bound =
205 const double gap = std::abs(user_best - user_bound);
206 if (gap <= absolute_gap_limit_) {
207 SOLVER_LOG(logger_,
"Absolute gap limit of ", absolute_gap_limit_,
214 shared_time_limit_->
Stop();
216 if (gap /
std::max(1.0, std::abs(user_best)) < relative_gap_limit_) {
217 SOLVER_LOG(logger_,
"Relative gap limit of ", relative_gap_limit_,
222 shared_time_limit_->
Stop();
227 const std::string& update_info, IntegerValue lb, IntegerValue ub) {
228 absl::MutexLock mutex_lock(&mutex_);
229 CHECK(objective_or_null_ !=
nullptr);
236 if (inner_objective_lower_bound_ > inner_objective_upper_bound_) {
241 (lb > inner_objective_lower_bound_ || ub < inner_objective_upper_bound_);
242 if (lb > inner_objective_lower_bound_) {
247 DCHECK_LE(inner_objective_upper_bound_, best_solution_objective_value_);
248 inner_objective_lower_bound_ =
249 std::min(best_solution_objective_value_, lb.value());
251 if (ub < inner_objective_upper_bound_) {
252 inner_objective_upper_bound_ = ub.value();
254 if (inner_objective_lower_bound_ > inner_objective_upper_bound_) {
261 if (update_integral_on_each_change_) UpdatePrimalIntegralInternal();
263 SatProgressMessage(
"Done", wall_timer_.
Get(), update_info));
275 RegisterObjectiveBoundImprovement(update_info);
276 SOLVER_LOG(logger_, ProgressMessage(
"Bound", wall_timer_.
Get(), best,
277 new_lb, new_ub, update_info));
279 if (change) TestGapLimitsIfNeeded();
286 const std::string& worker_info) {
287 absl::MutexLock mutex_lock(&mutex_);
293 if (objective_or_null_ ==
nullptr) {
294 best_response_.set_all_solutions_were_found(
true);
299 inner_objective_lower_bound_ = best_solution_objective_value_;
300 if (update_integral_on_each_change_) UpdatePrimalIntegralInternal();
306 SatProgressMessage(
"Done", wall_timer_.
Get(), worker_info));
310 absl::MutexLock mutex_lock(&mutex_);
311 best_response_.clear_sufficient_assumptions_for_infeasibility();
312 for (
const int ref : core) {
313 best_response_.add_sufficient_assumptions_for_infeasibility(ref);
318 absl::MutexLock mutex_lock(&mutex_);
319 return IntegerValue(inner_objective_lower_bound_);
323 absl::MutexLock mutex_lock(&mutex_);
324 return IntegerValue(inner_objective_upper_bound_);
328 absl::MutexLock mutex_lock(&mutex_);
329 synchronized_inner_objective_lower_bound_ =
330 IntegerValue(inner_objective_lower_bound_);
331 synchronized_inner_objective_upper_bound_ =
332 IntegerValue(inner_objective_upper_bound_);
336 absl::MutexLock mutex_lock(&mutex_);
337 return synchronized_inner_objective_lower_bound_;
341 absl::MutexLock mutex_lock(&mutex_);
342 return synchronized_inner_objective_upper_bound_;
346 absl::MutexLock mutex_lock(&mutex_);
347 return IntegerValue(best_solution_objective_value_);
351 absl::MutexLock mutex_lock(&mutex_);
352 return primal_integral_;
357 absl::MutexLock mutex_lock(&mutex_);
358 postprocessors_.push_back(postprocessor);
363 absl::MutexLock mutex_lock(&mutex_);
364 final_postprocessors_.push_back(postprocessor);
369 absl::MutexLock mutex_lock(&mutex_);
370 const int id = next_callback_id_++;
371 callbacks_.emplace_back(
id, std::move(
callback));
376 absl::MutexLock mutex_lock(&mutex_);
377 for (
int i = 0; i < callbacks_.size(); ++i) {
378 if (callbacks_[i].first == callback_id) {
379 callbacks_.erase(callbacks_.begin() + i);
383 LOG(DFATAL) <<
"Callback id " << callback_id <<
" not registered.";
387 absl::MutexLock mutex_lock(&mutex_);
388 FillObjectiveValuesInBestResponse();
392 for (
int i = postprocessors_.size(); --i >= 0;) {
393 postprocessors_[i](&result);
396 for (
int i = final_postprocessors_.size(); --i >= 0;) {
397 final_postprocessors_[i](&result);
403 void SharedResponseManager::FillObjectiveValuesInBestResponse() {
404 if (objective_or_null_ ==
nullptr)
return;
408 best_response_.clear_objective_value();
409 best_response_.clear_best_objective_bound();
416 best_response_.set_objective_value(
419 best_response_.set_objective_value(
424 best_response_.set_best_objective_bound(
428 best_response_.set_primal_integral(primal_integral_);
433 absl::MutexLock mutex_lock(&mutex_);
435 if (objective_or_null_ !=
nullptr) {
436 const int64_t objective_value =
442 solution.variable_values.assign(
response.solution().begin(),
444 solution.rank = objective_value;
445 solutions_.
Add(solution);
449 if (objective_value > inner_objective_upper_bound_)
return;
455 DCHECK_GE(objective_value, inner_objective_lower_bound_);
457 DCHECK_LT(objective_value, best_solution_objective_value_);
458 best_solution_objective_value_ = objective_value;
461 inner_objective_upper_bound_ = objective_value - 1;
466 if (objective_or_null_ ==
nullptr && !enumerate_all_solutions_) {
472 best_response_.set_solution_info(
response.solution_info());
473 *best_response_.mutable_solution() =
response.solution();
474 *best_response_.mutable_solution_lower_bounds() =
476 *best_response_.mutable_solution_upper_bounds() =
480 if (objective_or_null_ !=
nullptr &&
481 inner_objective_lower_bound_ > inner_objective_upper_bound_) {
488 std::string solution_info =
response.solution_info();
489 if (
model !=
nullptr) {
491 const int64_t num_fixed =
model->Get<
SatSolver>()->NumFixedVariables();
492 absl::StrAppend(&solution_info,
" fixed_bools:", num_fixed,
"/",
496 if (objective_or_null_ !=
nullptr) {
505 RegisterSolutionFound(solution_info);
506 SOLVER_LOG(logger_, ProgressMessage(absl::StrCat(num_solutions_),
507 wall_timer_.
Get(), best, lb, ub,
510 SOLVER_LOG(logger_, SatProgressMessage(absl::StrCat(num_solutions_),
511 wall_timer_.
Get(), solution_info));
517 TestGapLimitsIfNeeded();
518 if (!callbacks_.empty()) {
519 FillObjectiveValuesInBestResponse();
520 SetStatsFromModelInternal(
model);
524 for (
int i = postprocessors_.size(); --i >= 0;) {
525 postprocessors_[i](©);
527 for (
const auto& pair : callbacks_) {
532 #if !defined(__PORTABLE_PLATFORM__) 535 if (absl::GetFlag(FLAGS_cp_model_dump_solutions)) {
536 const std::string
file =
537 absl::StrCat(dump_prefix_,
"solution_", num_solutions_,
".pbtxt");
538 LOG(
INFO) <<
"Dumping solution to '" <<
file <<
"'.";
541 #endif // __PORTABLE_PLATFORM__ 545 #if !defined(__PORTABLE_PLATFORM__) 546 if (absl::GetFlag(FLAGS_cp_model_load_debug_solution).empty())
return;
550 LOG(
INFO) <<
"Reading solution from '" 551 << absl::GetFlag(FLAGS_cp_model_load_debug_solution) <<
"'.";
557 debug_solution.resize(
559 for (
int i = 0; i <
response.solution().size(); ++i) {
560 if (!mapping.IsInteger(i))
continue;
561 const IntegerVariable
var = mapping.Integer(i);
569 if (objective_def ==
nullptr)
return;
571 const IntegerVariable objective_var = objective_def->
objective_var;
572 const int64_t objective_value =
574 debug_solution[objective_var] = objective_value;
575 debug_solution[
NegationOf(objective_var)] = -objective_value;
576 #endif // __PORTABLE_PLATFORM__ 580 absl::MutexLock mutex_lock(&mutex_);
581 SetStatsFromModelInternal(
model);
584 void SharedResponseManager::SetStatsFromModelInternal(
Model*
model) {
585 if (
model ==
nullptr)
return;
588 best_response_.set_num_booleans(sat_solver->NumVariables());
589 best_response_.set_num_branches(sat_solver->num_branches());
590 best_response_.set_num_conflicts(sat_solver->num_failures());
591 best_response_.set_num_binary_propagations(sat_solver->num_propagations());
592 best_response_.set_num_restarts(sat_solver->num_restarts());
593 best_response_.set_num_integer_propagations(
594 integer_trail ==
nullptr ? 0 : integer_trail->num_enqueues());
596 best_response_.set_wall_time(
time_limit->GetElapsedTime());
597 best_response_.set_deterministic_time(
600 int64_t num_lp_iters = 0;
603 num_lp_iters += lp->total_num_simplex_iterations();
605 best_response_.set_num_lp_iterations(num_lp_iters);
609 absl::MutexLock mutex_lock(&mutex_);
615 if (improvement_info.empty())
return "";
618 for (
int i = 0; i < improvement_info.size(); ++i) {
619 if (!std::isalnum(improvement_info[i]) && improvement_info[i] !=
'_') {
620 return improvement_info.substr(0, i);
624 return improvement_info;
627 void SharedResponseManager::RegisterSolutionFound(
628 const std::string& improvement_info) {
629 if (improvement_info.empty())
return;
633 void SharedResponseManager::RegisterObjectiveBoundImprovement(
634 const std::string& improvement_info) {
635 if (improvement_info.empty() || improvement_info ==
"initial domain")
return;
640 absl::MutexLock mutex_lock(&mutex_);
641 if (!primal_improvements_count_.empty()) {
642 SOLVER_LOG(logger_,
"Solutions found per subsolver:");
643 for (
const auto& entry : primal_improvements_count_) {
644 SOLVER_LOG(logger_,
" '", entry.first,
"': ", entry.second);
647 if (!dual_improvements_count_.empty()) {
649 SOLVER_LOG(logger_,
"Objective bounds found per subsolver:");
650 for (
const auto& entry : dual_improvements_count_) {
651 SOLVER_LOG(logger_,
" '", entry.first,
"': ", entry.second);
659 lower_bounds_(num_variables_, std::numeric_limits<int64_t>::
min()),
660 upper_bounds_(num_variables_, std::numeric_limits<int64_t>::
max()),
661 synchronized_lower_bounds_(num_variables_,
662 std::numeric_limits<int64_t>::
min()),
663 synchronized_upper_bounds_(num_variables_,
664 std::numeric_limits<int64_t>::
max()) {
665 changed_variables_since_last_synchronize_.ClearAndResize(num_variables_);
666 for (
int i = 0; i < num_variables_; ++i) {
667 lower_bounds_[i] =
model_proto.variables(i).domain(0);
668 const int domain_size =
model_proto.variables(i).domain_size();
669 upper_bounds_[i] =
model_proto.variables(i).domain(domain_size - 1);
670 synchronized_lower_bounds_[i] = lower_bounds_[i];
671 synchronized_upper_bounds_[i] = upper_bounds_[i];
677 const std::vector<int>& variables,
678 const std::vector<int64_t>& new_lower_bounds,
679 const std::vector<int64_t>& new_upper_bounds) {
680 CHECK_EQ(variables.size(), new_lower_bounds.size());
681 CHECK_EQ(variables.size(), new_upper_bounds.size());
682 int num_improvements = 0;
684 absl::MutexLock mutex_lock(&mutex_);
685 for (
int i = 0; i < variables.size(); ++i) {
686 const int var = variables[i];
687 if (
var >= num_variables_)
continue;
688 const int64_t old_lb = lower_bounds_[
var];
689 const int64_t old_ub = upper_bounds_[
var];
690 const int64_t new_lb = new_lower_bounds[i];
691 const int64_t new_ub = new_upper_bounds[i];
692 const bool changed_lb = new_lb > old_lb;
693 const bool changed_ub = new_ub < old_ub;
695 if (!changed_lb && !changed_ub)
continue;
698 lower_bounds_[
var] = new_lb;
701 upper_bounds_[
var] = new_ub;
703 changed_variables_since_last_synchronize_.Set(
var);
708 if (num_improvements > 0) {
709 VLOG(2) << worker_name <<
" exports " << num_improvements
715 absl::MutexLock mutex_lock(&mutex_);
717 changed_variables_since_last_synchronize_.PositionsSetAtLeastOnce()) {
718 synchronized_lower_bounds_[
var] = lower_bounds_[
var];
719 synchronized_upper_bounds_[
var] = upper_bounds_[
var];
720 for (
int j = 0; j < id_to_changed_variables_.size(); ++j) {
721 id_to_changed_variables_[j].Set(
var);
724 changed_variables_since_last_synchronize_.ClearAll();
728 absl::MutexLock mutex_lock(&mutex_);
729 const int id = id_to_changed_variables_.size();
730 id_to_changed_variables_.resize(
id + 1);
731 id_to_changed_variables_[id].ClearAndResize(num_variables_);
732 for (
int var = 0;
var < num_variables_; ++
var) {
736 if (lb != synchronized_lower_bounds_[
var] ||
737 ub != synchronized_upper_bounds_[
var]) {
738 id_to_changed_variables_[id].Set(
var);
745 int id, std::vector<int>* variables, std::vector<int64_t>* new_lower_bounds,
746 std::vector<int64_t>* new_upper_bounds) {
748 new_lower_bounds->clear();
749 new_upper_bounds->clear();
751 absl::MutexLock mutex_lock(&mutex_);
752 for (
const int var : id_to_changed_variables_[
id].PositionsSetAtLeastOnce()) {
753 variables->push_back(
var);
754 new_lower_bounds->push_back(synchronized_lower_bounds_[
var]);
755 new_upper_bounds->push_back(synchronized_upper_bounds_[
var]);
757 id_to_changed_variables_[id].ClearAll();
IntegerValue GetInnerObjectiveUpperBound()
A simple class to enforce both an elapsed time limit and a deterministic time limit in the same threa...
void SetStatsFromModel(Model *model)
#define SOLVER_LOG(logger,...)
#define CHECK_GE(val1, val2)
Class that owns everything related to a particular optimization model.
void AddNewSolution(const std::vector< double > &lp_solution)
IntegerVariable NumIntegerVariables() const
ModelSharedTimeLimit * time_limit
constexpr IntegerValue kMinIntegerValue(-kMaxIntegerValue)
IntegerValue GetInnerObjectiveLowerBound()
absl::Status SetTextProto(const absl::string_view &filename, const google::protobuf::Message &proto, int flags)
#define VLOG(verboselevel)
void UnregisterCallback(int callback_id)
void AddFinalSolutionPostprocessor(std::function< void(CpSolverResponse *)> postprocessor)
void swap(IdMap< K, V > &a, IdMap< K, V > &b)
void NewSolution(const CpSolverResponse &response, Model *model)
void NewLPSolution(std::vector< double > lp_solution)
SharedResponseManager(Model *model)
constexpr IntegerValue kMaxIntegerValue(std::numeric_limits< IntegerValue::ValueType >::max() - 1)
int64_t Max() const
Returns the max value of the domain.
int NumVariables(const VariablesProto &variables)
double PrimalIntegral() const
void AddUnsatCore(const std::vector< int > &core)
void UpdateInnerObjectiveBounds(const std::string &update_info, IntegerValue lb, IntegerValue ub)
std::string ExtractSubSolverName(const std::string &improvement_info)
void DisplayImprovementStatistics()
const ::operations_research::sat::IntegerVariableProto & variables(int index) const
int64_t Min() const
Returns the min value of the domain.
CpSolverResponse GetResponse(bool full_response=true)
IntegerValue BestSolutionInnerObjectiveValue()
double ScaleObjectiveValue(const CpObjectiveProto &proto, int64_t value)
void Add(const Solution &solution)
int AddSolutionCallback(std::function< void(const CpSolverResponse &)> callback)
bool ProblemIsSolved() const
void SetUpdatePrimalIntegralOnEachChange(bool set)
void InitializeObjective(const CpModelProto &cp_model)
SharedBoundsManager(const CpModelProto &model_proto)
void AddSolutionPostprocessor(std::function< void(CpSolverResponse *)> postprocessor)
const ::operations_research::sat::CpObjectiveProto & objective() const
IntegerVariable objective_var
void AddInternal(const Solution &solution) ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_)
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 DCHECK_GE(val1, val2)
SharedResponseManager * response
#define CHECK_EQ(val1, val2)
bool has_objective() const
CpModelProto const * model_proto
std::vector< IntegerVariable > NegationOf(const std::vector< IntegerVariable > &vars)
We call domain any subset of Int64 = [kint64min, kint64max].
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 NotifyThatImprovingProblemIsInfeasible(const std::string &worker_info)
IntegerValue SynchronizedInnerObjectiveUpperBound()
bool LoggingIsEnabled() const
absl::Status GetTextProto(const absl::string_view &filename, google::protobuf::Message *proto, int flags)
bool HasNewSolution() const
#define DCHECK_LE(val1, val2)
void UpdatePrimalIntegral()
void GetChangedBounds(int id, std::vector< int > *variables, std::vector< int64_t > *new_lower_bounds, std::vector< int64_t > *new_upper_bounds)
Collection of objects used to extend the Constraint Solver library.
int64_t ComputeInnerObjective(const CpObjectiveProto &objective, const CpSolverResponse &response)
IntegerValue SynchronizedInnerObjectiveLowerBound()
double GetElapsedDeterministicTime() const
::PROTOBUF_NAMESPACE_ID::int64 domain(int index) const
std::vector< double > GetNewSolution()
void SetGapLimitsFromParameters(const SatParameters ¶meters)
double scaling_factor() const
Domain ReadDomainFromProto(const ProtoWithDomain &proto)
bool IsEmpty() const
Returns true if this is the empty set.
#define DCHECK_LT(val1, val2)
void LoadDebugSolution(Model *)
void NewRelaxationSolution(const CpSolverResponse &response)