Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_contract_matrix_paths_all_pairs_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
51#include <set>
52#include <stdexcept>
53#include <string>
54#include <type_traits>
55#include <utility>
56
57#include <gtest/gtest.h>
58
59#include <tpl_graph.H>
60#include <Floyd_Warshall.H>
61#include <Johnson.H>
62#include <K_Shortest_Paths.H>
63#include <Kruskal.H>
64#include <Prim.H>
65
66#include "graph_harness.H"
69
70using namespace Aleph;
71using namespace graph_harness;
72using namespace graph_contract_matrix;
73
74namespace
75{
77 template <class List>
78 std::set<int> arc_numbers(const List & l)
79 {
80 std::set<int> r;
81 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
82 r.insert(it.get_curr()->get_info());
83 return r;
84 }
85} // namespace
86
87namespace
88{
93 Spec ladder()
94 {
95 Spec s;
96 s.n = 4;
97 s.arcs = {{0, 1}, {2, 3}, {1, 2}, {1, 2}};
98 return s;
99 }
100
103 template <class GT, class SA>
104 constexpr int ladder_cost = hides<GT, SA> ? 4 : 3;
105
108 template <class GT, class SA>
109 std::set<int> ladder_arcs()
110 {
111 return hides<GT, SA> ? std::set<int>{0, 1, 3} : std::set<int>{0, 1, 2};
112 }
113
115 template <class GT>
116 std::set<int> path_arcs(const Path<GT> & p)
117 {
118 std::set<int> r;
119 p.for_each_arc([&r] (typename GT::Arc * a) { r.insert(a->get_info()); });
120 return r;
121 }
122
125 template <class GT>
126 std::set<int> graph_arcs(const GT & g)
127 {
128 std::set<int> r;
129 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
130 r.insert(it.get_curr_ne()->get_info());
131 return r;
132 }
133
135 template <class GT>
136 std::set<int> painted_arcs(const GT & g)
137 {
138 std::set<int> r;
139 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
140 if (IS_ARC_VISITED(it.get_curr_ne(), Aleph::Spanning_Tree))
141 r.insert(it.get_curr_ne()->get_info());
142 return r;
143 }
144
149 Spec diamond()
150 {
151 Spec s;
152 s.n = 4;
153 s.arcs = {{0, 1}, {2, 3}, {1, 2}, {3, 0}, {1, 3}};
154 return s;
155 }
156
158 template <class List>
159 bool some_path_has_hidden(const List & l)
160 {
161 for (auto it = l.get_it(); it.has_curr(); it.next_ne())
162 {
163 bool has = false;
164 it.get_curr().path.for_each_arc([&has] (auto a) { has = has or a->get_info() == Hidden; });
165 if (has)
166 return true;
167 }
168 return false;
169 }
170} // namespace
171
172// On the six kinds
173
174template <class GT>
175class ContractPathsAllPairs : public ::testing::Test {};
176
178
179TYPED_TEST(ContractPathsAllPairs, FloydAllShortestPaths)
180{
181 using GT = TypeParam;
182
183 for_each_filter<GT>([&] (auto sa, const char * name)
184 {
185 using SA = decltype(sa);
187 Built<GT> b(ladder());
188 auto * s = b.nodes[0];
189 auto * t = b.nodes[3];
190 SCOPED_TRACE(name);
191 const int cost = ladder_cost<GT, SA>;
192 const auto arcs = ladder_arcs<GT, SA>();
193 for_each_constness(b.g, [&] (auto & g)
194 {
195 // The filter as an lvalue and as an rvalue, with a distance, and
196 // deduced from them
197 Floyd x(g, sa);
198 SA moved = sa;
199 Floyd y(g, std::move(moved));
200 Floyd z(g, Dft_Dist<GT>(), sa);
201 Floyd_All_Shortest_Paths w(g, Dft_Dist<GT>(), sa);
202 static_assert(std::is_same_v<decltype(w), Floyd>);
203 for (const Floyd * f : {&x, &y, &z, &w})
204 {
205 EXPECT_FALSE(f->has_negative_cycle());
206 const long i = f->index_node(s);
207 const long j = f->index_node(t);
208 EXPECT_EQ(f->select_node(i), s);
209 EXPECT_EQ(f->get_dist_mat()(i, j), cost);
210 EXPECT_EQ(path_arcs(f->get_min_path(s, t)), arcs);
211 EXPECT_EQ(path_arcs(f->get_min_path(i, j)), arcs);
212 }
213 EXPECT_EQ(x.get_nodes().size(), 4U);
214 EXPECT_EQ(x.get_nodes_ref().size(), 4U);
215 EXPECT_EQ(x.get_nodes_copy().size(), 4U);
216 EXPECT_EQ(x.get_path_mat()(x.index_node(s), x.index_node(s)), x.index_node(s));
217 EXPECT_EQ(x.entry(cost), std::to_string(cost));
218 testing::internal::CaptureStdout();
219 x.print(x.get_dist_mat());
220 EXPECT_NE(testing::internal::GetCapturedStdout().find(std::to_string(cost)),
221 std::string::npos);
222 });
223 });
224}
225
227{
228 using GT = TypeParam;
229
230 for_each_filter<GT>([&] (auto sa, const char * name)
231 {
232 using SA = decltype(sa);
233 Built<GT> b(ladder());
234 auto * s = b.nodes[0];
235 auto * t = b.nodes[3];
236 SCOPED_TRACE(name);
237 constexpr bool hidden = hides<GT, SA>;
238 const int cost = ladder_cost<GT, SA>;
239 const auto arcs = ladder_arcs<GT, SA>();
240 for_each_constness(b.g, [&] (auto & g)
241 {
242 const auto explicit_args =
243 yen_k_shortest_paths<GT, Dft_Dist<GT>, SA>(g, s, t, 2, Dft_Dist<GT>(), sa);
244 const auto deduced = yen_k_shortest_paths(g, s, t, 2, Dft_Dist<GT>(), sa);
245 const Yen_K_Shortest_Paths<GT, Dft_Dist<GT>, SA> yen(Dft_Dist<GT>(), sa);
246 const auto by_object = yen(g, s, t, 2);
247 for (const auto * l : {&explicit_args, &deduced, &by_object})
248 {
249 // Two simple paths, of costs 3 and 4, or the one without the
250 // hidden arc
251 ASSERT_EQ(l->size(), hidden ? 1U : 2U);
252 EXPECT_EQ(l->get_first().total_cost, cost);
253 EXPECT_EQ(path_arcs(l->get_first().path), arcs);
254 EXPECT_EQ(some_path_has_hidden(*l), not hidden);
255 }
256 });
257 });
258}
259
260TYPED_TEST(ContractPathsAllPairs, EppsteinKShortestPaths)
261{
262 using GT = TypeParam;
263
264 for_each_filter<GT>([&] (auto sa, const char * name)
265 {
266 using SA = decltype(sa);
267 Built<GT> b(ladder());
268 auto * s = b.nodes[0];
269 auto * t = b.nodes[3];
270 SCOPED_TRACE(name);
271 const int cost = ladder_cost<GT, SA>;
272 const auto arcs = ladder_arcs<GT, SA>();
273 for_each_constness(b.g, [&] (auto & g)
274 {
275 const auto explicit_args =
276 eppstein_k_shortest_paths<GT, Dft_Dist<GT>, SA>(g, s, t, 2, Dft_Dist<GT>(), sa);
277 const auto deduced = eppstein_k_shortest_paths(g, s, t, 2, Dft_Dist<GT>(), sa);
278 const Eppstein_K_Shortest_Paths<GT, Dft_Dist<GT>, SA> eppstein(Dft_Dist<GT>(), sa);
279 const auto by_object = eppstein(g, s, t, 2);
280 for (const auto * l : {&explicit_args, &deduced, &by_object})
281 {
282 // The paths may repeat nodes, through the arc of weight 0
283 ASSERT_FALSE(l->is_empty());
284 EXPECT_EQ(l->get_first().total_cost, cost);
285 EXPECT_EQ(path_arcs(l->get_first().path), arcs);
286 if (hides<GT, SA>)
287 {
288 EXPECT_FALSE(some_path_has_hidden(*l));
289 }
290 }
291 });
292 });
293}
294
295// Johnson, on the digraphs
296
297template <class GT>
298class ContractPathsJohnson : public ::testing::Test {};
299
301
303{
304 using GT = TypeParam;
305
306 for_each_filter<GT>([&] (auto sa, const char * name)
307 {
308 using SA = decltype(sa);
309 Built<GT> b(diamond());
310 auto * s = b.nodes[0];
311 auto * t = b.nodes[3];
312 SCOPED_TRACE(name);
313 const int cost = hides<GT, SA> ? 4 : 3;
314 const auto arcs = hides<GT, SA> ? std::set<int>{0, 4} : std::set<int>{0, 1, 2};
315 for_each_constness(b.g, [&] (auto & g)
316 {
317 Johnson<GT, Dft_Dist<GT>, Arc_Iterator, Node_Arc_Iterator, SA> x(g, Dft_Dist<GT>(), sa);
318 EXPECT_TRUE(x.is_initialized());
319 EXPECT_EQ(x.get_distance(s, t), cost);
320 EXPECT_EQ(path_arcs(x.find_path(s, t)), arcs);
321 const auto all = x.compute_all_pairs_distances();
322 EXPECT_EQ(all.find(std::make_pair(s, t)), cost);
323 EXPECT_EQ(x.get_potential(s), 0);
324 EXPECT_EQ(x.get_reweighted_graph().get_num_nodes(), 4U);
325 EXPECT_EQ(std::as_const(x).get_reweighted_graph().get_num_arcs(), 5U);
326 EXPECT_NE(x.get_copy_node(s), nullptr);
327 });
328 });
329}
330
331TYPED_TEST(ContractPathsJohnson, JohnsonFiltersTheArcsOfTheGraph)
332{
333 using GT = TypeParam;
334
335 // 0 -> 1 (weight -1), 1 -> 2 (5), the hidden 0 -> 2 (2), 2 -> 3 (0) and
336 // 1 -> 3 (3): without the hidden arc the shortest path from 0 to 3 is
337 // 0 -> 1 -> 3, of cost 2. The weights are written in the infos; only
338 // the hidden arc has the info 2.
339 Spec spec;
340 spec.n = 4;
341 spec.arcs = {{0, 1}, {1, 2}, {0, 2}, {2, 3}, {1, 3}};
342 Built<GT> b(spec);
343 const int weight[] = {-1, 5, 2, 0, 3};
344 for (size_t i = 0; i < b.arcs.size(); ++i)
345 b.arcs[i]->get_info() = weight[i];
346
347 // A case of its own, which the matrix found: Johnson gave the filter the
348 // arcs of its copy of the graph, whose infos it had overwritten with the
349 // reweighted weights, so that the filter read 2 in the copy of 1 -> 3
350 // (3 + h(1) - h(3) = 3 - 1 - 0) and hid it
351 Check johnson("Johnson with a filter that reads the infos of the arcs");
352 Check bellman_ford("Bellman_Ford on the same graph and filter");
353
354 for_each_filter<GT>([&] (auto sa, const char * name)
355 {
356 using SA = decltype(sa);
357 if constexpr (hides<GT, SA>)
358 {
359 johnson.run();
361 const int d = x.get_distance(b.nodes[0], b.nodes[3]);
362 if (d != 2)
363 johnson.fail(spec, std::string(name) + ": distance " + std::to_string(d) + ", not 2");
364
365 bellman_ford.run();
367 y.paint_spanning_tree(b.nodes[0]);
368 const int e = y.get_distance(b.nodes[3]);
369 if (e != 2)
370 bellman_ford.fail(spec, std::string(name) + ": distance " + std::to_string(e) + ", not 2");
371 }
372 });
373
374 johnson.expect();
375 bellman_ford.expect();
376}
377
378// The minimum spanning trees, on the kinds that are not directed
379
380template <class GT>
381class ContractPathsSpanningTree : public ::testing::Test {};
382
384
385TYPED_TEST(ContractPathsSpanningTree, KruskalMinSpanningTree)
386{
387 using GT = TypeParam;
388
389 for_each_filter<GT>([&] (auto sa, const char * name)
390 {
391 using SA = decltype(sa);
392 Built<GT> b(ladder());
393 SCOPED_TRACE(name);
394 const auto arcs = ladder_arcs<GT, SA>();
395 for_each_constness(b.g, [&] (auto & g)
396 {
397 Kruskal_Min_Spanning_Tree<GT, Dft_Dist<GT>, SA> x(Dft_Dist<GT>(), sa);
398 x.paint_min_spanning_tree(g);
399 EXPECT_TRUE(x.is_painted());
400 EXPECT_EQ(painted_arcs(g), arcs);
401 GT tree;
402 x.paint_min_spanning_tree(g, tree);
403 EXPECT_EQ(graph_arcs(tree), arcs);
404 x(g, tree);
405 EXPECT_EQ(graph_arcs(tree), arcs);
406 x(g);
407 EXPECT_EQ(painted_arcs(g), arcs);
408 });
409 });
410}
411
413{
414 using GT = TypeParam;
415
416 for_each_filter<GT>([&] (auto sa, const char * name)
417 {
418 using SA = decltype(sa);
419 Built<GT> b(ladder());
420 SCOPED_TRACE(name);
421 const auto arcs = ladder_arcs<GT, SA>();
422 for_each_constness(b.g, [&] (auto & g)
423 {
424 Prim_Min_Spanning_Tree<GT, Dft_Dist<GT>, SA> x(Dft_Dist<GT>(), sa);
425 GT tree;
426 x(g, tree);
427 EXPECT_EQ(graph_arcs(tree), arcs);
428 x(g, b.nodes[3], tree);
429 EXPECT_EQ(graph_arcs(tree), arcs);
430 x(g);
431 EXPECT_EQ(painted_arcs(g), arcs);
432 x(g, b.nodes[3]);
433 EXPECT_EQ(painted_arcs(g), arcs);
434 });
435 });
436}
Floyd-Warshall algorithm for all-pairs shortest paths.
Johnson's algorithm for all-pairs shortest paths.
K-shortest path algorithms (Yen and Eppstein-style API).
Kruskal's minimum spanning tree algorithm.
Prim's algorithm for minimum spanning trees.
Bellman-Ford algorithm for shortest paths with negative weights.
Default distance accessor for arc weights.
Node belonging to a double circular linked list with header node.
Definition tpl_dnode.H:106
T & get_first()
Return the first item of the list.
Definition htlist.H:1548
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Compute the all-pairs shortest path distance matrix and the path reconstruction matrix for a graph g ...
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Johnson's algorithm for all-pairs shortest paths.
Definition Johnson.H:216
Distance_Type get_distance(Node *src, Node *tgt)
Get the shortest distance from source to target.
Definition Johnson.H:885
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Path on a graph.
Definition tpl_graph.H:3832
void for_each_arc(Operation op=Operation()) const
Execute an operation on each arc of path.
Definition tpl_graph.H:4540
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
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.
void expect() const
Expects what the mark says, and prints the first failures.
void fail(const Spec &s, const std::string &what)
Counts a failure on spec, with what went wrong.
void run() noexcept
Counts a run of the property.
What the files of the contract matrix of the graph templates, graph_contract_matrix_*_test....
TYPED_TEST(ContractPathsAllPairs, FloydAllShortestPaths)
TYPED_TEST_SUITE(ContractPathsAllPairs, All_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.
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
@ Spanning_Tree
Definition aleph-graph.H:79
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
Itor find(const Itor &beg, const Itor &end, const T &value)
Find the first element equal to a value.
Definition ahAlgo.H:230
void for_each_constness(GT &g, F &&f)
Calls f(g) with g as it is and as a const graph.
constexpr int Hidden
The number of the arc that the filters hide.
::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.
::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 > >, 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 > > > All_Kinds
The six kinds, with int infos.
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
A graph made from a spec, with its nodes and arcs by number.
std::vector< typename GT::Node * > nodes
std::vector< typename GT::Arc * > arcs
A small multigraph: its nodes are 0 .
std::vector< std::array< int, 2 > > arcs
Gsl_Compatible_Rng r
Generic graph and digraph implementations.
DynList< int > l