35#include <gtest/gtest.h>
59struct ArtificialMaxDomain
61 using State = ArtificialState;
62 using Move = ArtificialMove;
63 using Objective = int;
65 bool is_complete(
const State &state)
const
67 return state.depth == 2;
70 Objective objective_value(
const State &state)
const
75 Objective bound(
const State &state)
const
82 default:
return state.value;
86 void apply(State &state,
const Move &move)
const
88 state.code = move.target_code;
89 state.value += move.delta;
93 void undo(State &state,
const Move &move)
const
96 state.value -= move.delta;
100 template <
typename Visitor>
101 bool for_each_successor(
const State &state, Visitor visit)
const
103 if (state.depth >= 2)
109 if (not visit(Move{2, 0,
'L'}))
111 return visit(Move{3, 0,
'R'});
114 if (not visit(Move{4, 7,
'L'}))
116 return visit(Move{5, 9,
'R'});
119 if (not visit(Move{6, 5,
'L'}))
121 return visit(Move{7, 4,
'R'});
129struct ArtificialMaxBadOrderDomain
131 using State = ArtificialState;
132 using Move = ArtificialMove;
133 using Objective = int;
135 bool is_complete(
const State &state)
const
137 return state.depth == 2;
140 Objective objective_value(
const State &state)
const
145 Objective bound(
const State &state)
const
152 default:
return state.value;
156 void apply(State &state,
const Move &move)
const
158 state.code = move.target_code;
159 state.value += move.delta;
163 void undo(State &state,
const Move &move)
const
166 state.value -= move.delta;
170 template <
typename Visitor>
171 bool for_each_successor(
const State &state, Visitor visit)
const
173 if (state.depth >= 2)
179 if (not visit(Move{3, 0,
'R'}))
181 return visit(Move{2, 0,
'L'});
184 if (not visit(Move{4, 7,
'L'}))
186 return visit(Move{5, 9,
'R'});
189 if (not visit(Move{6, 5,
'L'}))
191 return visit(Move{7, 4,
'R'});
199struct ArtificialMaxVisitedDomain : ArtificialMaxDomain
201 using State_Key = int;
203 [[nodiscard]] State_Key state_key(
const State &state)
const noexcept
209struct ArtificialMinDomain
211 using State = ArtificialState;
212 using Move = ArtificialMove;
213 using Objective = int;
215 bool is_complete(
const State &state)
const
217 return state.depth == 2;
220 Objective objective_value(
const State &state)
const
225 Objective bound(
const State &state)
const
232 default:
return state.value;
236 void apply(State &state,
const Move &move)
const
238 state.code = move.target_code;
239 state.value += move.delta;
243 void undo(State &state,
const Move &move)
const
246 state.value -= move.delta;
250 template <
typename Visitor>
251 bool for_each_successor(
const State &state, Visitor visit)
const
253 if (state.depth >= 2)
259 if (not visit(Move{2, 0,
'L'}))
261 return visit(Move{3, 0,
'R'});
264 if (not visit(Move{4, 8,
'L'}))
266 return visit(Move{5, 6,
'R'});
269 if (not visit(Move{6, 7,
'L'}))
271 return visit(Move{7, 9,
'R'});
287 : index(0), weight(0),
value(0), chosen(n, 0)
293class KnapsackBBDomain
303 using Objective = double;
307 const bool fractional_bound)
309 suffix_values_(items.
size() + 1, 0.0),
311 use_fractional_bound_(fractional_bound)
313 for (
size_t i = items_.size(); i > 0; --i)
314 suffix_values_[i - 1] = suffix_values_[i] + items_[i - 1].
value;
317 bool is_complete(
const State &state)
const
319 return state.index == items_.size();
322 Objective objective_value(
const State &state)
const
327 Objective bound(
const State &state)
const
329 if (not use_fractional_bound_)
330 return state.value + suffix_values_[state.index];
332 Objective optimistic = state.value;
333 int remaining = capacity_ - state.weight;
335 for (
size_t i = state.index; i < items_.size()
and remaining > 0; ++i)
336 if (items_[i].weight <= remaining)
338 optimistic += items_[i].value;
339 remaining -= items_[i].weight;
343 optimistic += items_[i].value * (
static_cast<Objective
>(remaining)/
344 static_cast<Objective
>(items_[i].weight));
351 void apply(State &state,
const Move &move)
const
355 state.weight += items_[state.index].weight;
356 state.value += items_[state.index].value;
357 state.chosen[state.index] = 1;
360 state.chosen[state.index] = 0;
365 void undo(State &state,
const Move &move)
const
370 state.weight -= items_[state.index].weight;
371 state.value -= items_[state.index].value;
374 state.chosen[state.index] = 0;
377 template <
typename Visitor>
378 bool for_each_successor(
const State &state, Visitor visit)
const
380 if (state.index >= items_.size())
383 if (state.weight + items_[state.index].weight <= capacity_)
384 if (not visit(Move{
true}))
387 return visit(Move{
false});
394 bool use_fractional_bound_ =
true;
397struct AssignmentState
404 explicit AssignmentState(
const size_t n = 0)
405 :
row(0), total_cost(0), used_columns(n, 0), assigned_column(n, -1)
411class AssignmentBBDomain
419 using State = AssignmentState;
420 using Objective = int;
428 bool is_complete(
const State &state)
const
430 return state.row == costs_.size();
433 Objective objective_value(
const State &state)
const
435 return state.total_cost;
438 Objective bound(
const State &state)
const
440 Objective optimistic = state.total_cost;
442 for (
size_t row = state.row;
row < costs_.size(); ++
row)
446 if (not state.used_columns[
col]
and (best < 0 or costs_[
row][
col] < best))
455 void apply(State &state,
const Move &move)
const
457 state.total_cost += costs_[state.row][move.col];
458 state.used_columns[move.col] = 1;
459 state.assigned_column[state.row] =
static_cast<int>(move.col);
463 void undo(State &state,
const Move &move)
const
466 state.total_cost -= costs_[state.row][move.col];
467 state.used_columns[move.col] = 0;
468 state.assigned_column[state.row] = -1;
471 template <
typename Visitor>
472 bool for_each_successor(
const State &state, Visitor visit)
const
474 if (state.row >= costs_.size())
477 for (
size_t col = 0;
col < costs_[state.row].size(); ++
col)
478 if (not state.used_columns[
col]
and not visit(Move{
col}))
488struct ThrowingApplyState
490 std::shared_ptr<bool> undo_called;
494struct ThrowingApplyMove
499struct ThrowingApplyBBDomain
501 using State = ThrowingApplyState;
502 using Move = ThrowingApplyMove;
503 using Objective = int;
505 bool is_complete(
const State &state)
const
507 return state.node == 1;
510 Objective objective_value(
const State &)
const
515 Objective bound(
const State &)
const
520 void apply(State &state,
const Move &move)
const
528 void undo(State &state,
const Move &)
const
530 *state.undo_called =
true;
534 template <
typename Visitor>
535 bool for_each_successor(
const State &state, Visitor visit)
const
540 return visit(Move{
true});
544struct ThrowingApplyVisitedBBDomain : ThrowingApplyBBDomain
546 using State_Key = size_t;
548 [[nodiscard]] State_Key state_key(
const State &state)
const noexcept
554static_assert(BranchAndBoundDomain<ArtificialMaxDomain>);
555static_assert(SearchStateKeyProvider<ArtificialMaxVisitedDomain>);
556static_assert(BranchAndBoundDomain<ArtificialMinDomain>);
557static_assert(BranchAndBoundDomain<KnapsackBBDomain>);
558static_assert(BranchAndBoundDomain<AssignmentBBDomain>);
559static_assert(BranchAndBoundDomain<ThrowingApplyBBDomain>);
560static_assert(SearchStateKeyProvider<ThrowingApplyVisitedBBDomain>);
561static_assert(BranchAndBoundObjectivePolicy<Maximize_Objective<int>,
int>);
562static_assert(BranchAndBoundObjectivePolicy<Minimize_Objective<int>,
int>);
566struct NoDefaultBBState
569 explicit NoDefaultBBState(
const size_t d) : depth(d) {}
572struct NoDefaultStateBBDomain
574 using State = NoDefaultBBState;
575 using Move = ArtificialMove;
576 using Objective = int;
578 bool is_complete(
const State &state)
const {
return state.depth == 1; }
579 Objective objective_value(
const State &)
const {
return 0; }
580 Objective bound(
const State &)
const {
return 0; }
581 void apply(State &state,
const Move &)
const { ++state.depth; }
582 void undo(State &state,
const Move &)
const { --state.depth; }
584 template <
typename Visitor>
585 bool for_each_successor(
const State &, Visitor)
const {
return true; }
588static_assert(SuccessorGenerator<NoDefaultStateBBDomain>);
589static_assert(CompleteSolutionPredicate<NoDefaultStateBBDomain>);
590static_assert(OptimizationEvaluator<NoDefaultStateBBDomain>);
591static_assert(not BranchAndBoundDomain<NoDefaultStateBBDomain>);
596 for (
const auto &move : path)
597 out.push_back(move.label);
605 if (
row == costs.size())
613 const int candidate = costs[
row][
col] + brute_assignment_cost(costs,
row + 1, used);
615 if (best < 0 or candidate < best)
627struct IncrementalBoundDomain
629 using State = ArtificialState;
630 using Move = ArtificialMove;
631 using Objective = int;
633 mutable size_t bound_after_calls = 0;
634 mutable size_t apply_calls = 0;
636 bool is_complete(
const State &state)
const
638 return state.depth == 2;
641 Objective objective_value(
const State &state)
const
646 Objective bound(
const State &state)
const
653 default:
return state.value;
657 Objective bound_after(
const State &,
const Move &move)
const
661 switch (move.target_code)
665 default:
return move.delta;
669 void apply(State &state,
const Move &move)
const
672 state.code = move.target_code;
673 state.value += move.delta;
677 void undo(State &state,
const Move &move)
const
680 state.value -= move.delta;
684 template <
typename Visitor>
685 bool for_each_successor(
const State &state, Visitor visit)
const
687 if (state.depth >= 2)
693 if (not visit(Move{2, 0,
'L'}))
695 return visit(Move{3, 0,
'R'});
698 if (not visit(Move{4, 7,
'L'}))
700 return visit(Move{5, 9,
'R'});
703 if (not visit(Move{6, 5,
'L'}))
705 return visit(Move{7, 4,
'R'});
715TEST(BranchAndBoundFramework, ObjectivePoliciesAndIncumbentConstruct)
720 EXPECT_FALSE(incumbent.has_value());
721 EXPECT_TRUE(incumbent.can_improve(10));
724 first.objective_value = 5;
725 EXPECT_TRUE(incumbent.consider(first));
726 EXPECT_TRUE(incumbent.has_value());
727 EXPECT_EQ(incumbent.best_value(), 5);
728 EXPECT_FALSE(incumbent.can_improve(5));
729 EXPECT_TRUE(incumbent.can_improve(6));
732TEST(BranchAndBoundFramework, ArtificialMaximizationPrunesByBound)
734 ArtificialMaxDomain domain;
739 ASSERT_TRUE(result.found_solution());
740 EXPECT_TRUE(result.exhausted());
741 EXPECT_EQ(result.incumbent.best_value(), 9);
742 EXPECT_EQ(artificial_signature(result.incumbent.get().path),
"LR");
743 EXPECT_EQ(result.stats.solutions_found, 2u);
744 EXPECT_EQ(result.stats.pruned_by_bound, 1u);
745 EXPECT_EQ(result.stats.incumbent_updates, 2u);
746 EXPECT_EQ(collector.
size(), 2u);
749TEST(BranchAndBoundFramework, VisitedMapSearchKeepsRecordedBoundsOnSuccess)
751 ArtificialMaxVisitedDomain domain;
755 auto result =
engine.search(ArtificialState{}, visited);
757 ASSERT_TRUE(result.found_solution());
758 EXPECT_NE(visited.search(1),
nullptr);
759 EXPECT_NE(visited.search(2),
nullptr);
762TEST(BranchAndBoundFramework, ArtificialMinimizationWorksWithBestFirst)
764 ArtificialMinDomain domain;
767 policy.
strategy = ExplorationPolicy::Strategy::Best_First;
770 auto result =
engine.search(ArtificialState{});
772 ASSERT_TRUE(result.found_solution());
773 EXPECT_TRUE(result.exhausted());
774 EXPECT_EQ(result.incumbent.best_value(), 6);
775 EXPECT_EQ(artificial_signature(result.incumbent.get().path),
"LR");
776 EXPECT_GT(result.stats.pruned_by_bound, 0u);
779TEST(BranchAndBoundFramework, BoundOrderedDepthFirstAndBestFirstBeatPlainBadOrder)
781 ArtificialMaxBadOrderDomain domain;
786 ordered_policy.move_ordering = MoveOrderingMode::Estimated_Bound;
790 best_policy.strategy = ExplorationPolicy::Strategy::Best_First;
793 ASSERT_TRUE(plain_result.found_solution());
794 ASSERT_TRUE(ordered_result.found_solution());
795 ASSERT_TRUE(best_result.found_solution());
796 EXPECT_EQ(plain_result.incumbent.best_value(), 9);
797 EXPECT_EQ(ordered_result.incumbent.best_value(), plain_result.incumbent.best_value());
798 EXPECT_EQ(best_result.incumbent.best_value(), plain_result.incumbent.best_value());
799 EXPECT_EQ(artificial_signature(ordered_result.incumbent.get().path),
"LR");
800 EXPECT_LT(ordered_result.stats.visited_states, plain_result.stats.visited_states);
801 EXPECT_GT(ordered_result.stats.move_ordering.ordered_batches, 0u);
802 EXPECT_GT(ordered_result.stats.move_ordering.priority_estimates, 0u);
803 EXPECT_LT(best_result.stats.visited_states, plain_result.stats.visited_states);
806TEST(BranchAndBoundFramework, ApplyExceptionDuringMoveOrderingDoesNotCallUndo)
808 auto undo_called = std::make_shared<bool>(
false);
809 ThrowingApplyBBDomain domain;
815 EXPECT_THROW((
void)
engine.search(ThrowingApplyState{undo_called, 0}), std::runtime_error);
816 EXPECT_FALSE(*undo_called);
819TEST(BranchAndBoundFramework, ApplyExceptionDuringDepthFirstExpansionDoesNotCallUndo)
821 auto undo_called = std::make_shared<bool>(
false);
822 ThrowingApplyBBDomain domain;
825 EXPECT_THROW((
void)
engine.search(ThrowingApplyState{undo_called, 0}), std::runtime_error);
826 EXPECT_FALSE(*undo_called);
829TEST(BranchAndBoundFramework, ApplyExceptionDuringVisitedDepthFirstDoesNotCallUndo)
831 auto undo_called = std::make_shared<bool>(
false);
832 ThrowingApplyVisitedBBDomain domain;
836 EXPECT_THROW((
void)
engine.search(ThrowingApplyState{undo_called, 0}, visited),
838 EXPECT_FALSE(*undo_called);
848 void apply(State &state,
const Move &move)
const
854 Objective
bound(
const State &state)
const
862TEST(BranchAndBoundFramework, PostApplyExceptionCallsUndo)
864 auto undo_called = std::make_shared<bool>(
false);
868 EXPECT_THROW((
void)
engine.search(ThrowingApplyState{undo_called, 0}), std::runtime_error);
869 EXPECT_TRUE(*undo_called);
881TEST(BranchAndBoundFramework, PostApplyExceptionDuringVisitedDepthFirstCallsUndo)
883 auto undo_called = std::make_shared<bool>(
false);
889 EXPECT_THROW((
void)
engine.search(ThrowingApplyState{undo_called, 0}, visited), std::runtime_error);
890 EXPECT_TRUE(*undo_called);
891 EXPECT_FALSE(visited.contains(0));
894 *undo_called =
false;
895 EXPECT_THROW((
void)
engine.search(ThrowingApplyState{undo_called, 0}, visited), std::runtime_error);
896 EXPECT_TRUE(*undo_called);
897 EXPECT_FALSE(visited.contains(0));
900TEST(BranchAndBoundFramework, StopAtFirstSolutionUsesCommonExplorationPolicy)
902 ArtificialMaxDomain domain;
908 ASSERT_TRUE(result.found_solution());
909 EXPECT_TRUE(result.stopped_on_solution());
910 EXPECT_EQ(result.stats.solutions_found, 1u);
911 EXPECT_EQ(result.incumbent.best_value(), 7);
912 EXPECT_EQ(artificial_signature(result.incumbent.get().path),
"LL");
915TEST(BranchAndBoundFramework, KnapsackFractionalBoundFindsOptimal)
918 {2, 40.0}, {5, 30.0}, {10, 50.0}, {5, 10.0}
920 constexpr int capacity = 16;
922 KnapsackBBDomain domain(items, capacity,
true);
924 const double optimum = knapsack_01_value<double, int>(items, capacity);
926 ASSERT_TRUE(result.found_solution());
927 EXPECT_DOUBLE_EQ(result.incumbent.best_value(), 90.0);
928 EXPECT_DOUBLE_EQ(result.incumbent.best_value(), optimum);
931TEST(BranchAndBoundFramework, KnapsackBestFirstMatchesDepthFirst)
934 {2, 40.0}, {5, 30.0}, {10, 50.0}, {5, 10.0}
936 constexpr int capacity = 16;
938 KnapsackBBDomain domain(items, capacity,
true);
942 policy.
strategy = ExplorationPolicy::Strategy::Best_First;
946 EXPECT_DOUBLE_EQ(depth_result.incumbent.best_value(), best_result.incumbent.best_value());
947 EXPECT_GT(best_result.stats.pruned_by_bound, 0u);
950TEST(BranchAndBoundFramework, KnapsackFractionalBoundPrunesMoreThanWeakBound)
953 {10, 100.0}, {9, 80.0}, {9, 80.0}, {9, 80.0}
955 constexpr int capacity = 10;
962 EXPECT_DOUBLE_EQ(tight_result.incumbent.best_value(), weak_result.incumbent.best_value());
963 EXPECT_GT(tight_result.stats.pruned_by_bound, 0u);
964 EXPECT_LT(tight_result.stats.visited_states, weak_result.stats.visited_states);
965 EXPECT_LT(tight_result.stats.expanded_states, weak_result.stats.expanded_states);
968TEST(BranchAndBoundFramework, AssignmentMinimizationFindsExpectedOptimum)
977 AssignmentBBDomain domain(costs);
987 const int brute = brute_assignment_cost(costs, 0, used);
989 ASSERT_TRUE(result.found_solution());
990 EXPECT_EQ(result.incumbent.best_value(), brute);
991 EXPECT_EQ(result.incumbent.best_value(), 13);
994TEST(BranchAndBoundFramework, AssignmentBestFirstMatchesDepthFirst)
1003 AssignmentBBDomain domain(costs);
1009 auto depth_result = depth_engine.
search(AssignmentState(costs.
size()));
1013 policy.
strategy = ExplorationPolicy::Strategy::Best_First;
1016 auto best_result = best_engine.
search(AssignmentState(costs.
size()));
1018 EXPECT_EQ(depth_result.incumbent.best_value(), best_result.incumbent.best_value());
1019 EXPECT_GE(best_result.stats.pruned_by_bound, 0u);
1029TEST(BranchAndBoundFramework, MaxDepthOnePreventsCompleteSolution)
1031 ArtificialMaxDomain domain;
1039 auto result =
engine.search(ArtificialState{});
1041 EXPECT_FALSE(result.found_solution());
1042 EXPECT_GT(result.stats.pruned_by_depth, 0u);
1047TEST(BranchAndBoundFramework, MaxExpansionsOnePreventsCompleteSolution)
1049 ArtificialMaxDomain domain;
1057 auto result =
engine.search(ArtificialState{});
1059 EXPECT_TRUE(result.limit_reached());
1060 EXPECT_EQ(result.stats.expanded_states, 1u);
1061 EXPECT_FALSE(result.found_solution());
1066TEST(BranchAndBoundFramework, KnapsackCapacityZeroReturnsEmptySolution)
1069 {2, 40.0}, {5, 30.0}, {10, 50.0}
1071 constexpr int capacity = 0;
1073 KnapsackBBDomain domain(items, capacity,
true);
1076 ASSERT_TRUE(result.found_solution());
1077 EXPECT_DOUBLE_EQ(result.incumbent.best_value(), 0.0);
1084TEST(BranchAndBoundFramework, IncrementalBoundProviderUsedForOrdering)
1086 IncrementalBoundDomain domain;
1092 auto result =
engine.search(ArtificialState{});
1095 ASSERT_TRUE(result.found_solution());
1096 EXPECT_EQ(result.incumbent.best_value(), 9);
1099 EXPECT_GT(
engine.domain().bound_after_calls, 0u);
1102 EXPECT_GT(result.stats.move_ordering.priority_estimates, 0u);
Classical knapsack problem variants (0/1, unbounded, bounded).
Umbrella header for the implicit state-space search framework.
#define ah_runtime_error()
Throws std::runtime_error unconditionally.
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Reusable branch-and-bound engine over implicit state spaces.
static ExplorationPolicy default_policy() noexcept
Return the default branch-and-bound exploration policy.
Result search(State initial_state)
Execute branch and bound and keep only the incumbent.
Global incumbent manager for branch and bound.
Collector that stores accepted solutions in an Aleph list.
size_t size() const noexcept
Number of collected solutions.
constexpr std::uint32_t delta
File contains only the cells that changed relative to a baseline.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::string code(Node *root)
Compute a string with the Lukasiewicz`s word of a tree.
and
Check uniqueness with explicit hash + equality functors.
auto branch_and_bound_search(Domain domain, typename Domain::State initial_state, ExplorationPolicy policy=Branch_And_Bound< Domain, ObjectivePolicy >::default_policy(), SearchLimits limits={}, ObjectivePolicy objective={})
Convenience wrapper for one-shot branch and bound.
Exploration controls shared across engines.
bool stop_at_first_solution
Stop when the first goal is found.
Strategy strategy
Traversal strategy.
MoveOrderingMode move_ordering
Successor-ordering mode.
An item for knapsack problems.
Objective policy for maximization problems.
Objective policy for minimization problems.
Snapshot of a complete optimization solution.
Hard bounds applied by the search engine.
size_t max_expansions
Maximum expanded states.
size_t max_depth
Maximum expansion depth.
void apply(State &state, const Move &move) const
bool is_complete(const State &) const
Objective bound(const State &state) const
State_Key state_key(const State &state) const noexcept