File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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
Original file line number Diff line number Diff 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 }
Original file line number Diff line number Diff 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
2024end
Original file line number Diff line number Diff line change @@ -47,6 +47,20 @@ def on_solution_callback
4747 end
4848end
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+
5064class 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
You can’t perform that action at this time.
0 commit comments