Skip to content

Commit 08044d3

Browse files
committed
Added stop_search method to CpSolverSolutionCallback - closes #46
1 parent 51e1821 commit 08044d3

4 files changed

Lines changed: 28 additions & 1 deletion

File tree

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
## 0.18.0 (unreleased)
22

3+
- Added `stop_search` method to `CpSolverSolutionCallback`
34
- Fixed error with `apply_locks` and `set_allowed_vehicles_for_index` methods
45
- Dropped support for Ruby < 3.3
56

ext/or-tools/constraint.cpp

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -432,13 +432,17 @@ void init_constraint(Rice::Module& m) {
432432
parameters.set_num_search_workers(1);
433433

434434
m.Add(NewFeasibleSolutionObserver(
435-
[&callback](const CpSolverResponse& r) {
435+
[&](const CpSolverResponse& r) {
436436
if (!ruby_native_thread_p()) {
437437
throw std::runtime_error{"Non-Ruby thread"};
438438
}
439439

440440
callback.call("response=", r);
441441
callback.call("on_solution_callback");
442+
443+
if (callback.attr_get("@stopped")) {
444+
StopSearch(&m);
445+
}
442446
})
443447
);
444448
}

lib/or_tools/cp_solver_solution_callback.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,5 +16,9 @@ def value(expr)
1616
def objective_value
1717
@response&.objective_value
1818
end
19+
20+
def stop_search
21+
@stopped = true
22+
end
1923
end
2024
end

test/constraint_test.rb

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,20 @@ def on_solution_callback
4747
end
4848
end
4949

50+
class StopSearchCallback < ORTools::CpSolverSolutionCallback
51+
attr_reader :solution_count
52+
53+
def initialize
54+
super()
55+
@solution_count = 0
56+
end
57+
58+
def on_solution_callback
59+
@solution_count += 1
60+
stop_search if @solution_count >= 3
61+
end
62+
end
63+
5064
class ConstraintTest < Minitest::Test
5165
# https://developers.google.com/optimization/cp/cp_solver
5266
def test_cp_sat_solver
@@ -156,6 +170,10 @@ def test_cryptoarithmetic
156170
assert_equal 182, solver.num_conflicts
157171
assert_equal 1777, solver.num_branches
158172
assert_equal 72, solution_printer.solution_count
173+
174+
stop_callback = StopSearchCallback.new
175+
status = solver.solve(model, stop_callback)
176+
assert_equal 3, stop_callback.solution_count
159177
end
160178

161179
# https://developers.google.com/optimization/cp/queens

0 commit comments

Comments
 (0)