45#include <gtest/gtest.h>
54#include <unordered_map>
55#include <unordered_set>
68 using Weighted_Edge = std::tuple<size_t, size_t, long long>;
71 using SGraph_Backend =
73 using AGraph_Backend =
78 size_t cardinality = 0;
79 long long total_weight = 0;
81 bool operator==(
const Objective & other)
const noexcept
83 return cardinality == other.cardinality
84 and total_weight == other.total_weight;
90 GT build_graph(
size_t n,
const std::vector<Weighted_Edge> & edges)
93 std::vector<typename GT::Node *>
nodes;
96 for (
size_t i = 0; i < n; ++i)
99 for (
const auto & [u, v,
w] : edges)
101 if (u >= n or v >= n)
114 std::unordered_set<typename GT::Arc *> arcs_in_graph;
115 for (
typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
116 arcs_in_graph.insert(it.get_curr());
118 std::unordered_set<typename GT::Node *> used_nodes;
119 for (
auto it = matching.
get_it(); it.has_curr(); it.next_ne())
121 auto * arc = it.get_curr();
125 if (arcs_in_graph.find(arc) == arcs_in_graph.end())
130 if (src ==
nullptr or tgt ==
nullptr or src == tgt)
133 if (not used_nodes.insert(src).second)
136 if (not used_nodes.insert(tgt).second)
144 bool better(
const Objective & lhs,
145 const Objective & rhs,
146 bool max_cardinality)
noexcept
150 if (lhs.cardinality != rhs.cardinality)
151 return lhs.cardinality > rhs.cardinality;
152 return lhs.total_weight > rhs.total_weight;
155 if (lhs.total_weight != rhs.total_weight)
156 return lhs.total_weight > rhs.total_weight;
158 return lhs.cardinality > rhs.cardinality;
162 std::vector<Weighted_Edge>
163 normalize_simple_edges(
size_t n,
const std::vector<Weighted_Edge> & edges)
165 using Pair = std::pair<size_t, size_t>;
168 size_t operator()(
const Pair & p)
const noexcept
170 const size_t h1 = std::hash<size_t>{}(p.first);
171 const size_t h2 = std::hash<size_t>{}(p.second);
172 return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2));
176 std::unordered_map<Pair, long long, Pair_Hash> best;
177 best.reserve(edges.size() * 2 + 1);
179 for (
auto [u, v,
w] : edges)
181 if (u >= n or v >= n or u == v)
187 const Pair key{u, v};
188 const auto it = best.find(key);
189 if (it == best.end() or
w > it->second)
193 std::vector<Weighted_Edge> result;
194 result.reserve(best.size());
195 for (
const auto & kv : best)
196 result.emplace_back(kv.first.first, kv.first.second, kv.second);
198 std::sort(result.begin(), result.end(),
199 [](
const Weighted_Edge & a,
const Weighted_Edge & b)
201 if (std::get<0>(a) != std::get<0>(b))
202 return std::get<0>(a) < std::get<0>(b);
203 if (std::get<1>(a) != std::get<1>(b))
204 return std::get<1>(a) < std::get<1>(b);
205 return std::get<2>(a) < std::get<2>(b);
212 Objective exact_weighted_matching_optimum(
size_t n,
213 const std::vector<Weighted_Edge> & edges,
214 bool max_cardinality)
217 return Objective{0, 0};
221 <<
"exact_weighted_matching_optimum supports n <= 24";
223 constexpr long long NO_EDGE = std::numeric_limits<long long>::min() / 4;
224 std::vector<std::vector<long long>>
w(n, std::vector<long long>(n, NO_EDGE));
226 for (
auto [u, v, wt] : normalize_simple_edges(n, edges))
232 const uint64_t full_mask = (n == 64)
233 ? std::numeric_limits<uint64_t>::max()
234 : ((uint64_t{1} << n) - 1);
236 const size_t state_count =
static_cast<size_t>(full_mask + 1);
237 std::vector<Objective> memo(state_count);
238 std::vector<char> seen(state_count, 0);
240 std::function<Objective(uint64_t)> solve = [&](uint64_t mask) -> Objective
243 return Objective{0, 0};
245 const size_t pos =
static_cast<size_t>(mask);
249 const size_t i =
static_cast<size_t>(__builtin_ctzll(mask));
250 const uint64_t rest = mask & ~(uint64_t{1} << i);
252 Objective best = solve(rest);
257 const size_t j =
static_cast<size_t>(__builtin_ctzll(
options));
260 if (
w[i][j] == NO_EDGE)
263 Objective candidate = solve(rest & ~(uint64_t{1} << j));
264 ++candidate.cardinality;
265 candidate.total_weight +=
w[i][j];
267 if (better(candidate, best, max_cardinality))
276 return solve(full_mask);
285 for (
auto it = matching.
get_it(); it.has_curr(); it.next_ne())
287 auto * arc = it.get_curr();
288 obj.total_weight +=
static_cast<long long>(arc->get_info());
297 Objective solve_weighted(
const GT & g,
299 bool max_cardinality)
301 const auto res = blossom_maximum_weight_matching<GT>(
308 EXPECT_EQ(res.cardinality, matching.
size());
309 const Objective obj = compute_objective_from_matching<GT>(matching);
310 EXPECT_EQ(res.cardinality, obj.cardinality);
311 EXPECT_EQ(res.total_weight, obj.total_weight);
318 std::vector<std::pair<size_t, size_t>>
319 canonical_matching_pairs(
const GT & g,
322 std::vector<std::pair<size_t, size_t>> pairs;
323 pairs.reserve(matching.
size());
325 for (
auto it = matching.
get_it(); it.has_curr(); it.next_ne())
327 auto * arc = it.get_curr();
328 size_t u =
static_cast<size_t>(g.
get_src_node(arc)->get_info());
329 size_t v =
static_cast<size_t>(g.
get_tgt_node(arc)->get_info());
332 pairs.emplace_back(u, v);
335 std::sort(pairs.begin(), pairs.end());
340 struct Solve_Snapshot
343 std::vector<std::pair<size_t, size_t>> pairs;
348 Solve_Snapshot solve_backend(
size_t n,
349 const std::vector<Weighted_Edge> & edges,
350 bool max_cardinality)
352 GT g = build_graph<GT>(n, edges);
355 const Objective
objective = solve_weighted(g, matching, max_cardinality);
359 return Solve_Snapshot{
361 canonical_matching_pairs(g, matching)};
366 void assert_matches_exact(
size_t n,
367 const std::vector<Weighted_Edge> & edges,
368 bool max_cardinality)
370 GT g = build_graph<GT>(n, edges);
373 const Objective got = solve_weighted(g, matching, max_cardinality);
377 const Objective
expected = exact_weighted_matching_optimum(
378 n, edges, max_cardinality);
385 class WeightedBlossomTypedTest :
public ::testing::Test
389 using GraphBackends = ::testing::Types<
401 using Graph = TypeParam;
406 const auto result = blossom_maximum_weight_matching<Graph>(g, matching);
408 EXPECT_EQ(result.cardinality, 0u);
409 EXPECT_EQ(result.total_weight, 0);
416 using Graph = TypeParam;
418 assert_matches_exact<Graph>(2, {{0, 1, 7}},
false);
424 using Graph = TypeParam;
426 const std::vector<Weighted_Edge> edges = {
434 assert_matches_exact<Graph>(4, edges,
false);
435 assert_matches_exact<Graph>(4, edges,
true);
439TYPED_TEST(WeightedBlossomTypedTest, NegativeWeightsDefaultAndMaxCardinality)
441 using Graph = TypeParam;
443 const std::vector<Weighted_Edge> edges = {
450 assert_matches_exact<Graph>(4, edges,
false);
451 assert_matches_exact<Graph>(4, edges,
true);
455TYPED_TEST(WeightedBlossomTypedTest, WeightedBlossomRegressionCases)
457 using Graph = TypeParam;
460 const std::vector<std::pair<size_t, std::vector<Weighted_Edge>>> cases = {
461 {4, {{1, 2, 8}, {1, 3, 9}, {2, 3, 10}, {3, 4, 7}}},
462 {6, {{1, 2, 9}, {1, 3, 8}, {2, 3, 10}, {1, 4, 5}, {4, 5, 4}, {1, 6, 3}}},
464 {{1, 2, 23}, {1, 5, 22}, {1, 6, 15}, {2, 3, 25},
465 {3, 4, 22}, {4, 5, 25}, {4, 8, 14}, {5, 7, 13}}},
467 {{1, 2, 45}, {1, 5, 45}, {2, 3, 50}, {3, 4, 45}, {4, 5, 50},
468 {1, 6, 30}, {3, 9, 35}, {4, 8, 28}, {5, 7, 26}, {9, 10, 5}}},
470 {{1, 2, 40}, {1, 3, 40}, {2, 3, 60}, {2, 4, 55}, {3, 5, 55},
471 {4, 5, 50}, {1, 8, 15}, {5, 7, 30}, {7, 6, 10}, {8, 10, 10}, {4, 9, 30}}}
474 for (
const auto & [n, edges_one_based] : cases)
476 std::vector<Weighted_Edge> edges_zero_based;
477 edges_zero_based.reserve(edges_one_based.size());
479 for (
const auto & [u, v,
w] : edges_one_based)
480 edges_zero_based.emplace_back(u - 1, v - 1,
w);
482 assert_matches_exact<Graph>(n, edges_zero_based,
false);
483 assert_matches_exact<Graph>(n, edges_zero_based,
true);
488TYPED_TEST(WeightedBlossomTypedTest, RandomSmallGraphsAgainstExactDP)
490 using Graph = TypeParam;
492 std::mt19937_64
rng(0xC0FFEE1234ULL);
493 std::uniform_int_distribution<int> n_dist(1, 11);
494 std::uniform_real_distribution<double> p_dist(0.0, 1.0);
495 std::uniform_int_distribution<int> w_dist(-10, 24);
497 for (
size_t iter = 0; iter < 180; ++iter)
499 const size_t n =
static_cast<size_t>(n_dist(
rng));
500 std::vector<Weighted_Edge> edges;
502 for (
size_t u = 0; u < n; ++u)
503 for (
size_t v = u + 1; v < n; ++v)
505 if (p_dist(
rng) < 0.45)
507 edges.emplace_back(u, v,
static_cast<long long>(w_dist(
rng)));
510 if (p_dist(
rng) < 0.18)
511 edges.emplace_back(u, v,
static_cast<long long>(w_dist(
rng)));
516 if (n > 0
and p_dist(
rng) < 0.2)
517 edges.emplace_back(
static_cast<size_t>(
rng() % n),
518 static_cast<size_t>(
rng() % n),
519 static_cast<long long>(w_dist(
rng)));
521 assert_matches_exact<Graph>(n, edges,
false);
522 assert_matches_exact<Graph>(n, edges,
true);
527TEST(WeightedBlossomStandaloneTest, CrossBackendUniqueOptimumConsistency)
529 const std::vector<Weighted_Edge> edges = {
542 for (
bool max_cardinality : {
false,
true})
544 const Solve_Snapshot list_res = solve_backend<List_Backend>(
545 7, edges, max_cardinality);
546 const Solve_Snapshot sgraph_res = solve_backend<SGraph_Backend>(
547 7, edges, max_cardinality);
548 const Solve_Snapshot agraph_res = solve_backend<AGraph_Backend>(
549 7, edges, max_cardinality);
551 const Objective
expected = exact_weighted_matching_optimum(
552 7, edges, max_cardinality);
554 EXPECT_EQ(list_res.objective,
expected);
555 EXPECT_EQ(sgraph_res.objective,
expected);
556 EXPECT_EQ(agraph_res.objective,
expected);
558 EXPECT_EQ(list_res.pairs, sgraph_res.pairs);
559 EXPECT_EQ(list_res.pairs, agraph_res.pairs);
564TEST(WeightedBlossomStandaloneTest, CrossBackendRandomObjectiveConsistency)
566 std::mt19937_64
rng(0xB10550ULL);
567 std::uniform_int_distribution<int> n_dist(1, 10);
568 std::uniform_real_distribution<double> p_dist(0.0, 1.0);
569 std::uniform_int_distribution<int> w_dist(-12, 25);
571 for (
size_t iter = 0; iter < 140; ++iter)
573 const size_t n =
static_cast<size_t>(n_dist(
rng));
574 std::vector<Weighted_Edge> edges;
576 for (
size_t u = 0; u < n; ++u)
577 for (
size_t v = u + 1; v < n; ++v)
579 if (p_dist(
rng) < 0.42)
581 edges.emplace_back(u, v,
static_cast<long long>(w_dist(
rng)));
582 if (p_dist(
rng) < 0.2)
583 edges.emplace_back(u, v,
static_cast<long long>(w_dist(
rng)));
587 if (n > 0
and p_dist(
rng) < 0.3)
588 edges.emplace_back(
static_cast<size_t>(
rng() % n),
589 static_cast<size_t>(
rng() % n),
590 static_cast<long long>(w_dist(
rng)));
592 for (
bool max_cardinality : {
false,
true})
594 const Solve_Snapshot list_res = solve_backend<List_Backend>(
595 n, edges, max_cardinality);
596 const Solve_Snapshot sgraph_res = solve_backend<SGraph_Backend>(
597 n, edges, max_cardinality);
598 const Solve_Snapshot agraph_res = solve_backend<AGraph_Backend>(
599 n, edges, max_cardinality);
601 const Objective
expected = exact_weighted_matching_optimum(
602 n, edges, max_cardinality);
604 EXPECT_EQ(list_res.objective,
expected);
605 EXPECT_EQ(sgraph_res.objective,
expected);
606 EXPECT_EQ(agraph_res.objective,
expected);
607 EXPECT_EQ(list_res.objective, sgraph_res.objective);
608 EXPECT_EQ(list_res.objective, agraph_res.objective);
616 struct Positive_Arc_Filter
619 bool operator()(
Arc * arc)
const noexcept
621 return arc->get_info() > 0;
627TEST(WeightedBlossomStandaloneTest, ArcFilterIsRespected)
646 Positive_Arc_Filter>(g,
649 Positive_Arc_Filter(),
652 EXPECT_EQ(result.cardinality, 2u);
653 EXPECT_EQ(result.total_weight, 11);
658TEST(WeightedBlossomStandaloneTest, DigraphThrowsDomainError)
663 auto * n0 = g.insert_node(0);
664 auto * n1 = g.insert_node(1);
665 g.insert_arc(n0, n1, 42);
669 EXPECT_THROW(blossom_maximum_weight_matching<Digraph>(g, matching),
674TEST(WeightedBlossomStandaloneTest, MaxCardinalityCanBeatPureWeightCardinality)
678 const std::vector<Weighted_Edge> edges = {
689 Graph g = build_graph<Graph>(6, edges);
692 const Objective pure_weight = solve_weighted(g, weight_matching,
false);
695 const Objective max_card = solve_weighted(g, card_matching,
true);
700 EXPECT_GE(max_card.cardinality, pure_weight.cardinality);
702 const Objective exact_weight = exact_weighted_matching_optimum(6, edges,
false);
703 const Objective exact_card = exact_weighted_matching_optimum(6, edges,
true);
705 EXPECT_EQ(pure_weight, exact_weight);
706 EXPECT_EQ(max_card, exact_card);
710TEST(WeightedBlossomMwMatchingStandaloneTest, FloatingWeightsAndFiniteValidation)
712 namespace mw = blossom_weighted_detail::mwmatching;
716 edges.
append(mw::Edge<double>(0, 1, 1.5));
717 edges.
append(mw::Edge<double>(1, 2, 2.0));
718 edges.
append(mw::Edge<double>(0, 2, 1.0));
721 ASSERT_EQ(sol.
size(), 1u);
722 const auto [u, v] = sol[0];
723 EXPECT_TRUE((u == 1
and v == 2) or (u == 2
and v == 1));
727 mw::Edge<double>(0, 1, std::numeric_limits<double>::quiet_NaN()));
728 EXPECT_THROW((mw::maximum_weight_matching(nan_edges)),
729 std::invalid_argument);
730 EXPECT_THROW((mw::adjust_weights_for_maximum_cardinality_matching(nan_edges)),
731 std::invalid_argument);
735 mw::Edge<double>(0, 1, std::numeric_limits<double>::infinity()));
736 EXPECT_THROW((mw::maximum_weight_matching(inf_edges)),
737 std::invalid_argument);
741TEST(WeightedBlossomMwMatchingStandaloneTest, RejectsSelfLoopsAndDuplicateEdges)
743 namespace mw = blossom_weighted_detail::mwmatching;
746 self_loop.
append(mw::Edge<long long>(0, 0, 7));
747 EXPECT_THROW((mw::maximum_weight_matching(self_loop)),
748 std::invalid_argument);
751 duplicate.
append(mw::Edge<long long>(0, 1, 8));
752 duplicate.
append(mw::Edge<long long>(1, 0, 9));
753 EXPECT_THROW((mw::maximum_weight_matching(duplicate)),
754 std::invalid_argument);
758TEST(WeightedBlossomMwMatchingStandaloneTest, RejectsUnsafeIntegerRanges)
760 namespace mw = blossom_weighted_detail::mwmatching;
762 const long long max_safe = std::numeric_limits<long long>::max() / 4;
763 const long long min_safe = std::numeric_limits<long long>::min() / 4;
766 too_large_weight.
append(mw::Edge<long long>(0, 1, max_safe + 1));
767 EXPECT_THROW((mw::maximum_weight_matching(too_large_weight)),
768 std::invalid_argument);
771 too_small_weight.
append(mw::Edge<long long>(0, 1, min_safe - 1));
772 EXPECT_THROW((mw::adjust_weights_for_maximum_cardinality_matching(
774 std::invalid_argument);
777 huge_range.
append(mw::Edge<long long>(0, 1, 0));
778 huge_range.
append(mw::Edge<long long>(0, 2, max_safe));
779 EXPECT_THROW((mw::adjust_weights_for_maximum_cardinality_matching(huge_range)),
780 std::invalid_argument);
784TEST(WeightedBlossomStandaloneTest, ToLlCheckedRejectsOverflow)
787 (blossom_weighted_detail::to_ll_checked<unsigned long long>(
788 std::numeric_limits<unsigned long long>::max())),
789 std::overflow_error);
792 (blossom_weighted_detail::to_ll_checked<long long>(
793 std::numeric_limits<long long>::max())));
796 (blossom_weighted_detail::to_ll_checked<long long>(
797 std::numeric_limits<long long>::min())));
800 (blossom_weighted_detail::to_ll_checked<unsigned long long>(
801 static_cast<unsigned long long>(
802 std::numeric_limits<long long>::max()))));
805 (blossom_weighted_detail::to_ll_checked<long long>(0
LL)));
809TEST(WeightedBlossomStandaloneTest, StressLargeRandomGraphsCrossBackendConsistency)
811 std::mt19937_64
rng(0x5EED5EED1234ULL);
812 std::uniform_int_distribution<int> n_dist(45, 85);
813 std::uniform_real_distribution<double> p_dist(0.0, 1.0);
814 std::uniform_int_distribution<int> w_dist(-40, 120);
816 for (
size_t iter = 0; iter < 8; ++iter)
818 const size_t n =
static_cast<size_t>(n_dist(
rng));
819 std::vector<Weighted_Edge> edges;
820 edges.reserve((n * n) / 5);
822 for (
size_t u = 0; u < n; ++u)
823 for (
size_t v = u + 1; v < n; ++v)
825 if (p_dist(
rng) < 0.14)
827 edges.emplace_back(u, v,
static_cast<long long>(w_dist(
rng)));
828 if (p_dist(
rng) < 0.05)
829 edges.emplace_back(u, v,
static_cast<long long>(w_dist(
rng)));
833 const Solve_Snapshot list_weight = solve_backend<List_Backend>(
835 const Solve_Snapshot sgraph_weight = solve_backend<SGraph_Backend>(
837 const Solve_Snapshot agraph_weight = solve_backend<AGraph_Backend>(
840 EXPECT_EQ(list_weight.objective, sgraph_weight.objective);
841 EXPECT_EQ(list_weight.objective, agraph_weight.objective);
842 EXPECT_LE(list_weight.objective.cardinality, n / 2);
846 const Solve_Snapshot list_card = solve_backend<List_Backend>(
848 const Solve_Snapshot sgraph_card = solve_backend<SGraph_Backend>(
850 const Solve_Snapshot agraph_card = solve_backend<AGraph_Backend>(
853 EXPECT_EQ(list_card.objective, sgraph_card.objective);
854 EXPECT_EQ(list_card.objective, agraph_card.objective);
855 EXPECT_LE(list_card.objective.cardinality, n / 2);
Maximum-weight matching in general undirected graphs.
#define ah_runtime_error_if(C)
Throws std::runtime_error if condition holds.
TYPED_TEST_SUITE(ArcHeapLifecycle, ArcHeapKinds)
List_Graph< Node, Arc > Graph
bool verify_matching(const Graph &g, const DynDlist< Graph::Arc * > &matching)
Verifies that a matching is valid:
Simple dynamic array with automatic resizing and functional operations.
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
constexpr bool is_empty() const noexcept
Return true if this (as header node) is empty.
Dynamic doubly linked list with O(1) size and bidirectional access.
const size_t & size() const noexcept
Return the number of elements (constant time)
Arc for graphs implemented with simple adjacency lists.
Graph implemented with double-linked adjacency lists.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Graph class implemented with singly-linked adjacency lists.
Minimal std::expected-style result type for C++20.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
DynArray< Graph::Node * > nodes
Blossom_Weighted_Result< long long > blossom_maximum_weight_matching(const GT &g, DynDlist< typename GT::Arc * > &matching, Weight weight=Weight(), SA sa=SA(), const bool max_cardinality=false)
Alias for compute_maximum_weight_general_matching().
static Geom_Number objective(const Point &p)
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
and
Check uniqueness with explicit hash + equality functors.
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
static struct argp_option options[]
Default filter for filtered iterators on arcs.
Arc of graph implemented with double-linked adjacency lists.
Array-based graph implementation.
Generic graph and digraph implementations.
Simple graph implementation with adjacency lists.
TYPED_TEST(WeightedBlossomTypedTest, EmptyGraph)