Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_exhaustive_matching_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
47#include <algorithm>
48#include <limits>
49#include <random>
50#include <set>
51#include <stdexcept>
52#include <string>
53#include <vector>
54
55#include <gtest/gtest.h>
56
57#include <tpl_graph.H>
58#include <Blossom_Weighted.H>
59#include <Min_Cost_Matching.H>
60
62#include "graph_harness.H"
63#include "graph_oracles.H"
64
65using namespace Aleph;
66using namespace graph_harness;
67namespace oracle = graph_oracles;
70
71namespace
72{
77 struct Best
78 {
79 long long max_weight = 0;
80 long long min_cost = 0;
81 size_t max_size = 0;
82 long long max_weight_of_max_size = std::numeric_limits<long long>::lowest();
83 long long min_cost_of_max_size = std::numeric_limits<long long>::max();
84 bool perfect = false;
85 long long min_cost_perfect = std::numeric_limits<long long>::max();
86 };
87
88 Best best_matchings(const Spec & s, unsigned long hidden)
89 {
90 Best b;
91 const size_t m = s.arcs.size();
92 for (unsigned long sub = 0; sub < (1UL << m); ++sub)
93 {
94 if (sub & hidden)
95 continue;
96 std::vector<bool> used(size_t(s.n), false);
97 long long w = 0;
98 size_t size = 0;
99 bool ok = true;
100 for (size_t i = 0; i < m and ok; ++i)
101 if (sub & (1UL << i))
102 {
103 const int u = s.arcs[i][0], v = s.arcs[i][1];
104 ok = u != v and not used[size_t(u)] and not used[size_t(v)];
105 used[size_t(u)] = used[size_t(v)] = true;
106 w += s.w[i];
107 ++size;
108 }
109 if (not ok)
110 continue;
111 b.max_weight = std::max(b.max_weight, w);
112 b.min_cost = std::min(b.min_cost, w);
113 if (size > b.max_size)
114 {
115 b.max_size = size;
116 b.max_weight_of_max_size = w;
117 b.min_cost_of_max_size = w;
118 }
119 else if (size == b.max_size)
120 {
121 b.max_weight_of_max_size = std::max(b.max_weight_of_max_size, w);
122 b.min_cost_of_max_size = std::min(b.min_cost_of_max_size, w);
123 }
124 if (2 * size == size_t(s.n))
125 {
126 b.perfect = true;
127 b.min_cost_perfect = std::min(b.min_cost_perfect, w);
128 }
129 }
130 if (b.max_size == 0)
131 b.max_weight_of_max_size = b.min_cost_of_max_size = 0;
132 return b;
133 }
134
137 template <class GT>
138 std::string matching_error(const Spec & s, const DynDlist<typename GT::Arc *> & l,
139 unsigned long hidden, long long w, size_t k)
140 {
141 std::vector<bool> used(size_t(s.n), false);
142 long long total = 0;
143 size_t size = 0;
144 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
145 {
146 const int i = num(it.get_curr());
147 if (i < 0 or size_t(i) >= s.arcs.size() or not graph_filters::shown(hidden, i))
148 return "a hidden arc, or one that is not of the graph";
149 const int u = s.arcs[size_t(i)][0], v = s.arcs[size_t(i)][1];
150 if (u == v or used[size_t(u)] or used[size_t(v)])
151 return "not a matching";
152 used[size_t(u)] = used[size_t(v)] = true;
153 total += s.w[size_t(i)];
154 ++size;
155 }
156 if (total != w or size != k)
157 return "it reports " + std::to_string(w) + " and " + std::to_string(k)
158 + " arcs for " + std::to_string(total) + " and " + std::to_string(size);
159 return "";
160 }
161
164 template <class F>
165 void for_each_weighting(Spec s, long long lo, long long hi, F && f)
166 {
167 s.w.assign(s.arcs.size(), lo);
168 while (true)
169 {
170 f(static_cast<const Spec &>(s));
171 size_t i = 0;
172 while (i < s.w.size() and s.w[i] == hi)
173 s.w[i++] = lo;
174 if (i == s.w.size())
175 return;
176 ++s.w[i];
177 }
178 }
179
180 struct Matching_Checks
181 {
182 Check max_weight{"compute_maximum_weight_general_matching()"};
183 Check max_weight_card{"compute_maximum_weight_general_matching(), the cardinality first"};
184 Check min_cost{"compute_minimum_cost_general_matching()"};
185 Check min_cost_card{"compute_minimum_cost_general_matching(), the cardinality first"};
186 Check perfect{"compute_minimum_cost_perfect_general_matching()"};
187 Check functors{"the functors and the blossom_ aliases"};
188
189 void expect() const
190 {
191 for (const Check * c : {&max_weight, &max_weight_card, &min_cost, &min_cost_card,
192 &perfect, &functors})
193 c->expect();
194 }
195 };
196
198 template <class GT>
199 void check_matchings(Matching_Checks & c, const Spec & s, unsigned long hidden)
200 {
201 using Dist = Weight_Of<GT, long long>;
202 using Filter = Hide_Mask<GT>;
203 Built<GT> b(s);
204 Dist d;
205 d.weights = &s.w;
206 const Best want = best_matchings(s, hidden);
207 const std::string at = hidden == 0 ? "" : "hiding " + std::to_string(hidden) + ": ";
208
209 auto run = [&] (Check & check, auto && match, long long want_value, size_t want_size,
210 bool any_size)
211 {
212 check.run();
214 const auto [value, size] = match(l);
215 if (auto e = matching_error<GT>(s, l, hidden, value, size); not e.empty())
216 check.fail(s, at + e);
217 else if (value != want_value or (not any_size and size != want_size))
218 check.fail(s, at + "gives " + std::to_string(value) + " with " + std::to_string(size)
219 + " arcs, not " + std::to_string(want_value) + " with "
220 + std::to_string(want_size));
221 };
222
223 run(c.max_weight, [&] (auto & l)
224 {
225 const auto r = compute_maximum_weight_general_matching<GT, Dist, Filter>
226 (b.g, l, d, Filter{hidden});
227 return std::pair(r.total_weight, r.cardinality);
228 }, want.max_weight, 0, true);
229
230 run(c.max_weight_card, [&] (auto & l)
231 {
232 const auto r = compute_maximum_weight_general_matching<GT, Dist, Filter>
233 (b.g, l, d, Filter{hidden}, true);
234 return std::pair(r.total_weight, r.cardinality);
235 }, want.max_weight_of_max_size, want.max_size, false);
236
237 run(c.min_cost, [&] (auto & l)
238 {
239 const auto r = compute_minimum_cost_general_matching<GT, Dist, Filter>
240 (b.g, l, d, Filter{hidden});
241 return std::pair(r.total_cost, r.cardinality);
242 }, want.min_cost, 0, true);
243
244 run(c.min_cost_card, [&] (auto & l)
245 {
246 const auto r = compute_minimum_cost_general_matching<GT, Dist, Filter>
247 (b.g, l, d, Filter{hidden}, true);
248 return std::pair(r.total_cost, r.cardinality);
249 }, want.min_cost_of_max_size, want.max_size, false);
250
251 c.perfect.run();
252 {
254 const auto r = compute_minimum_cost_perfect_general_matching<GT, Dist, Filter>
255 (b.g, l, d, Filter{hidden});
256 if (r.feasible != want.perfect)
257 c.perfect.fail(s, at + (r.feasible ? "finds a perfect matching that is not"
258 : "finds no perfect matching"));
259 else if (not r.feasible and not l.is_empty())
260 c.perfect.fail(s, at + "leaves arcs without a perfect matching");
261 else if (r.feasible)
262 {
263 if (auto e = matching_error<GT>(s, l, hidden, r.total_cost, r.cardinality); not e.empty())
264 c.perfect.fail(s, at + e);
265 else if (r.total_cost != want.min_cost_perfect or 2 * r.cardinality != size_t(s.n))
266 c.perfect.fail(s, at + "costs " + std::to_string(r.total_cost) + ", not "
267 + std::to_string(want.min_cost_perfect));
268 }
269 }
270
271 // The other entry points give the same
272 if (hidden == 0)
273 {
274 c.functors.run();
276 const auto r1 = blossom_maximum_weight_matching<GT, Dist>(b.g, l1, d);
278 const auto r3 = blossom_minimum_cost_matching<GT, Dist>(b.g, l3, d);
279 const auto r4 = Compute_Minimum_Cost_General_Matching<GT, Dist>(d)(b.g, l4);
281 if (r1.total_weight != want.max_weight or r2.total_weight != want.max_weight
282 or r3.total_cost != want.min_cost or r4.total_cost != want.min_cost
283 or r5.feasible != want.perfect
284 or (r5.feasible and r5.total_cost != want.min_cost_perfect))
285 c.functors.fail(s, "an entry point gives another answer");
286 }
287 }
288}
289
290template <class GT>
291class ExhaustiveMatching : public ::testing::Test {};
292
294
295TYPED_TEST(ExhaustiveMatching, EveryWeightingHasItsBestMatchings)
296{
297 Matching_Checks c;
298 for_each_spec(domain(3, 3), false, [&] (const Spec & spec)
299 {
300 for_each_weighting(spec, -1, 1, [&] (const Spec & s)
301 {
302 check_matchings<TypeParam>(c, s, 0);
303 });
304 });
305 c.expect();
306}
307
308TYPED_TEST(ExhaustiveMatching, MatchingsRespectTheFilter)
309{
310 Matching_Checks c;
311 for_each_spec(domain(4, 3), false, [&] (const Spec & spec)
312 {
313 // Distinct weights, against the order of the arcs
314 Spec s = spec;
315 s.w.clear();
316 for (size_t i = 0; i < s.arcs.size(); ++i)
317 s.w.push_back(static_cast<long long>(s.arcs.size() - i) - 1);
318 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
319 check_matchings<TypeParam>(c, s, hidden);
320 });
321 c.expect();
322}
323
324TYPED_TEST(ExhaustiveMatching, RandomGraphsHaveTheirBestMatchings)
325{
326 Matching_Checks c;
327 std::mt19937 rng(seed(734));
328 const int graphs = heavy() ? 2000 : 200;
329 for (int k = 0; k < graphs; ++k)
330 {
331 const int n = 4 + int(rng() % 5);
332 const int m = n - 1 + int(rng() % unsigned(n));
333 Spec s = random_spec(rng, n, std::min(m, 14), false);
334 random_weights(rng, s, -5, 9);
335 check_matchings<TypeParam>(c, s, 0);
336 }
337 c.expect();
338}
339
340template <class GT>
341class ExhaustiveMatchingOnDigraphs : public ::testing::Test {};
342
344
346{
347 using GT = TypeParam;
348 GT g;
349 auto * p = g.insert_node(0);
350 auto * q = g.insert_node(1);
351 g.insert_arc(p, q, 0);
353 EXPECT_THROW(compute_maximum_weight_general_matching(g, l), std::domain_error);
354 EXPECT_THROW(compute_minimum_cost_general_matching(g, l), std::domain_error);
355 EXPECT_THROW(compute_minimum_cost_perfect_general_matching(g, l), std::domain_error);
356}
Maximum-weight matching in general undirected graphs.
Minimum-cost matching in general undirected graphs.
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
Functor wrapper for weighted blossom matching.
Functor wrapper for minimum-cost general matching.
Functor wrapper for minimum-cost perfect general matching.
Dynamic doubly linked list with O(1) size and bidirectional access.
constexpr bool is_empty() const noexcept
Definition htlist.H:434
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
The failures of one property over a domain.
static mt19937 rng
TYPED_TEST(ExhaustiveMatching, EveryWeightingHasItsBestMatchings)
TYPED_TEST_SUITE(ExhaustiveMatching, Undirected_Kinds)
The kinds of arc filter and of distance that the graph algorithms must accept.
Every small multigraph, on every kind of graph, for the tests.
Answers computed from a Spec of graph_harness.H, without Aleph.
Min_Cost_Perfect_Matching_Result< long long > compute_minimum_cost_perfect_general_matching(const GT &g, DynDlist< typename GT::Arc * > &matching, Cost cost=Cost(), SA sa=SA())
Compute minimum-cost perfect matching in a general undirected graph.
Min_Cost_Matching_Result< long long > compute_minimum_cost_general_matching(const GT &g, DynDlist< typename GT::Arc * > &matching, Cost cost=Cost(), SA sa=SA(), const bool max_cardinality=false)
Compute minimum-cost matching in a general undirected graph.
Blossom_Weighted_Result< long long > compute_maximum_weight_general_matching(const GT &g, DynDlist< typename GT::Arc * > &matching, Weight weight=Weight(), SA sa=SA(), const bool max_cardinality=false)
Compute maximum-weight matching in a general undirected graph.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
void expect(std::ifstream &input_stream, const std::string &expected)
Expect and consume a specific string/keyword.
and
Check uniqueness with explicit hash + equality functors.
double sub(double a, double b)
constexpr bool shown(unsigned long hidden, int i) noexcept
Whether the arc number i is shown by the mask hidden.
::testing::Types< Aleph::List_Digraph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SDigraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Digraph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > > > Directed_Kinds
The directed kinds, with int infos.
::testing::Types< Aleph::List_Graph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SGraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Graph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > > > Undirected_Kinds
The kinds of graph that are not directed, with int infos.
size_t for_each_spec(const Domain &d, bool directed, F &&f)
Calls f(spec) with every spec of d, smallest first, and returns how many there were.
Spec random_spec(std::mt19937 &rng, int n, int m, bool directed, bool loops=true, bool parallel=true)
A random spec of n nodes and m arcs, with loops and parallel arcs if asked; parallel is ignored when ...
int num(Node *p)
The number of a node of a built graph.
Domain domain(int max_nodes, int max_arcs)
The domain of max_nodes nodes and max_arcs arcs, of one more of each in heavy mode,...
bool heavy()
Whether the mode is heavy, which asks for the larger domains.
void random_weights(std::mt19937 &rng, Spec &s, long long lo, long long hi)
Gives each arc of s a weight from lo to hi.
Hides the arcs of a mask; copyable, assignable, noexcept.
The weight of an arc, read by its number from a vector.
A graph made from a spec, with its nodes and arcs by number.
A small multigraph: its nodes are 0 .
std::vector< long long > w
size_t num_arcs() const noexcept
std::vector< std::array< int, 2 > > arcs
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
DynList< char > l3
DynList< int > l1
DynList< int > l2
DynSetTree< char > l5
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Generic graph and digraph implementations.
DynList< int > l