[CP-SAT] add StopSearch C++ function.

This commit is contained in:
Laurent Perron
2025-03-24 04:55:15 -07:00
parent 35c27ab31f
commit 8dd492498f
9 changed files with 41 additions and 37 deletions

View File

@@ -403,9 +403,6 @@ class NetworkRoutingSolver {
cp_model.AddAllDifferent(node_vars);
Model model;
// Create an atomic Boolean that will be periodically checked by the limit.
std::atomic<bool> stopped(false);
model.GetOrCreate<TimeLimit>()->RegisterExternalBooleanAsLimit(&stopped);
model.Add(NewFeasibleSolutionObserver([&](const CpSolverResponse& r) {
const int path_id = all_paths_[demand_index].size();
@@ -415,7 +412,7 @@ class NetworkRoutingSolver {
all_paths_[demand_index].back().insert(arc);
}
if (all_paths_[demand_index].size() >= max_paths) {
stopped = true;
StopSearch(&model);
}
}));

View File

@@ -182,10 +182,14 @@ void CheckNumberOfSolutions(int size, int num_solutions) {
if (absl::GetFlag(FLAGS_use_symmetry)) {
if (size - 1 < kKnownUniqueSolutions) {
CHECK_EQ(num_solutions, kNumUniqueSolutions[size - 1]);
} else if (!absl::GetFlag(FLAGS_cp_disable_solve)) {
CHECK_GT(num_solutions, 0);
}
} else {
if (size - 1 < kKnownSolutions) {
CHECK_EQ(num_solutions, kNumSolutions[size - 1]);
} else if (!absl::GetFlag(FLAGS_cp_disable_solve)) {
CHECK_GT(num_solutions, 0);
}
}
}

View File

@@ -53,10 +53,6 @@ void Solve() {
parameters.set_enumerate_all_solutions(true);
model.Add(NewSatParameters(parameters));
// Create an atomic Boolean that will be periodically checked by the limit.
std::atomic<bool> stopped(false);
model.GetOrCreate<TimeLimit>()->RegisterExternalBooleanAsLimit(&stopped);
const int kSolutionLimit = 100;
int num_solutions = 0;
model.Add(NewFeasibleSolutionObserver([&](const CpSolverResponse& r) {
@@ -68,7 +64,7 @@ void Solve() {
LOG(INFO) << " start_ins = " << SolutionIntegerValue(r, start_ins);
num_solutions++;
if (num_solutions >= kSolutionLimit) {
stopped = true;
StopSearch(&model);
LOG(INFO) << "Stop search after " << kSolutionLimit << " solutions.";
}
}));