Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_graph_utils_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
48#include <gtest/gtest.h>
49
50#include <functional>
51#include <queue>
52#include <random>
53#include <set>
54#include <tuple>
55#include <vector>
56
57#include <tpl_dynArray.H>
58#include <tpl_graph.H>
59#include <tpl_graph_utils.H>
60
61using namespace Aleph;
62
63namespace
64{
68
69 std::vector<Graph::Node *> make_nodes(Graph &g, int n)
70 {
71 std::vector<Graph::Node *> nodes;
72 nodes.reserve(n);
73 for (int i = 0; i < n; ++i)
74 nodes.push_back(g.insert_node(i));
75 return nodes;
76 }
77
78 std::vector<TestDigraph::Node *> make_nodes(TestDigraph &g, int n)
79 {
80 std::vector<TestDigraph::Node *> nodes;
81 nodes.reserve(n);
82 for (int i = 0; i < n; ++i)
83 nodes.push_back(g.insert_node(i));
84 return nodes;
85 }
86
87 std::vector<WGraph::Node *> make_nodes(WGraph &g, int n)
88 {
89 std::vector<WGraph::Node *> nodes;
90 nodes.reserve(n);
91 for (int i = 0; i < n; ++i)
92 nodes.push_back(g.insert_node(i));
93 return nodes;
94 }
95
96 // ---------------------------------------------------------------------------
97 // Helpers for function-pointer traversals
98 // ---------------------------------------------------------------------------
99
100 Graph::Node *g_expected_start = nullptr;
101
102 bool check_from_arc_is_null_for_start(const Graph &, Graph::Node *node, Graph::Arc *from)
103 {
104 if (node == g_expected_start)
105 EXPECT_EQ(from, nullptr);
106 else
107 EXPECT_NE(from, nullptr);
108 return false;
109 }
110
111 bool stop_immediately(const Graph &, Graph::Node *, Graph::Arc *)
112 {
113 return true;
114 }
115
116 // ---------------------------------------------------------------------------
117 // Operation & filter helpers for traversal functors
118 // ---------------------------------------------------------------------------
119
120 template <class GT>
121 struct CollectVisitedInfos
122 {
123 std::vector<int> *infos = nullptr;
124
125 bool operator()(const GT &, typename GT::Node *node, typename GT::Arc *)
126 {
127 infos->push_back(node->get_info());
128 return false;
129 }
130 };
131
132 template <class GT>
133 struct EvenArcInfoOnly
134 {
135 bool operator()(typename GT::Arc *a) const noexcept
136 {
137 return (a->get_info() % 2) == 0;
138 }
139 };
140
141 // ---------------------------------------------------------------------------
142 // Reference BFS on adjacency list (undirected) for property tests
143 // ---------------------------------------------------------------------------
144
145 int bfs_distance(const std::vector<std::vector<int>> &adj, int s, int t)
146 {
147 if (s == t)
148 return 0;
149
150 std::vector<int> dist(adj.size(), -1);
151 std::queue<int> q;
152 dist[s] = 0;
153 q.push(s);
154
155 while (!q.empty())
156 {
157 int u = q.front();
158 q.pop();
159 for (int v : adj[u])
160 {
161 if (dist[v] != -1)
162 continue;
163 dist[v] = dist[u] + 1;
164 if (v == t)
165 return dist[v];
166 q.push(v);
167 }
168 }
169
170 return -1;
171 }
172
173 template <class GT>
174 std::vector<typename GT::Node *> path_nodes(const Path<GT> &path)
175 {
176 std::vector<typename GT::Node *> nodes;
177 path.for_each_node([&](auto p) { nodes.push_back(p); });
178 return nodes;
179 }
180
181} // namespace
182
183// =============================================================================
184// Traversals (free functions)
185// =============================================================================
186
187TEST(GraphUtilsTraversal, DepthFirstTraversalCountsReachableNodes)
188{
189 Graph g;
190 auto nodes = make_nodes(g, 5);
191 g.insert_arc(nodes[0], nodes[1], 1);
192 g.insert_arc(nodes[1], nodes[2], 1);
193 g.insert_arc(nodes[2], nodes[3], 1);
194 g.insert_arc(nodes[3], nodes[4], 1);
195
196 const auto no_visit =
197 static_cast<bool (*)(const Graph &, Graph::Node *, Graph::Arc *)>(nullptr);
198 const size_t visited = depth_first_traversal(g, nodes[0], no_visit);
199 EXPECT_EQ(visited, 5U);
200
201 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
202 EXPECT_TRUE(IS_NODE_VISITED(it.get_curr(), Depth_First));
203}
204
205TEST(GraphUtilsTraversal, DepthFirstTraversalProvidesFromArc)
206{
207 Graph g;
208 auto nodes = make_nodes(g, 3);
209 g.insert_arc(nodes[0], nodes[1], 1);
210 g.insert_arc(nodes[1], nodes[2], 1);
211
212 g_expected_start = nodes[0];
213 depth_first_traversal(g, nodes[0], &check_from_arc_is_null_for_start);
214}
215
216TEST(GraphUtilsTraversal, DepthFirstTraversalStopsImmediately)
217{
218 Graph g;
219 auto nodes = make_nodes(g, 3);
220 g.insert_arc(nodes[0], nodes[1], 1);
221 g.insert_arc(nodes[1], nodes[2], 1);
222
223 const size_t visited = depth_first_traversal(g, nodes[0], &stop_immediately);
224 EXPECT_EQ(visited, 1U);
225}
226
227TEST(GraphUtilsTraversal, BreadthFirstTraversalCountsReachableNodes)
228{
229 Graph g;
230 auto nodes = make_nodes(g, 5);
231 g.insert_arc(nodes[0], nodes[1], 1);
232 g.insert_arc(nodes[1], nodes[2], 1);
233 g.insert_arc(nodes[2], nodes[3], 1);
234 g.insert_arc(nodes[3], nodes[4], 1);
235
236 const auto no_visit =
237 static_cast<bool (*)(const Graph &, Graph::Node *, Graph::Arc *)>(nullptr);
238 const size_t visited = breadth_first_traversal(g, nodes[0], no_visit);
239 EXPECT_EQ(visited, 5U);
240
241 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
242 EXPECT_TRUE(IS_NODE_VISITED(it.get_curr(), Breadth_First));
243}
244
245TEST(GraphUtilsTraversal, BreadthFirstTraversalProvidesFromArc)
246{
247 Graph g;
248 auto nodes = make_nodes(g, 3);
249 g.insert_arc(nodes[0], nodes[1], 1);
250 g.insert_arc(nodes[1], nodes[2], 1);
251
252 g_expected_start = nodes[0];
253 breadth_first_traversal(g, nodes[0], &check_from_arc_is_null_for_start);
254}
255
256TEST(GraphUtilsTraversal, BreadthFirstTraversalStopsImmediately)
257{
258 Graph g;
259 auto nodes = make_nodes(g, 3);
260 g.insert_arc(nodes[0], nodes[1], 1);
261 g.insert_arc(nodes[1], nodes[2], 1);
262
263 const size_t visited = breadth_first_traversal(g, nodes[0], &stop_immediately);
264 EXPECT_EQ(visited, 1U);
265}
266
267// =============================================================================
268// Traversal functors (filters + operations)
269// =============================================================================
270
271TEST(GraphUtilsTraversal, DepthFirstTraversalFunctorHonorsArcFilter)
272{
273 Graph g;
274 auto nodes = make_nodes(g, 3);
275 g.insert_arc(nodes[0], nodes[1], 2); // allowed (even)
276 g.insert_arc(nodes[1], nodes[2], 1); // filtered out
277
278 std::vector<int> visited_infos;
279 CollectVisitedInfos<Graph> op{&visited_infos};
280
282 EvenArcInfoOnly<Graph>()};
283
284 const size_t visited = dft(g, nodes[0], op);
285 EXPECT_EQ(visited, 2U);
286
287 std::set<int> s(visited_infos.begin(), visited_infos.end());
288 EXPECT_EQ(s, (std::set<int>{0, 1}));
289}
290
291TEST(GraphUtilsTraversal, BreadthFirstTraversalFunctorHonorsArcFilter)
292{
293 Graph g;
294 auto nodes = make_nodes(g, 3);
295 g.insert_arc(nodes[0], nodes[1], 2); // allowed (even)
296 g.insert_arc(nodes[1], nodes[2], 1); // filtered out
297
298 std::vector<int> visited_infos;
299 CollectVisitedInfos<Graph> op{&visited_infos};
300
302 EvenArcInfoOnly<Graph>()};
303
304 const size_t visited = bft(g, nodes[0], op);
305 EXPECT_EQ(visited, 2U);
306
307 std::set<int> s(visited_infos.begin(), visited_infos.end());
308 EXPECT_EQ(s, (std::set<int>{0, 1}));
309}
310
311// =============================================================================
312// Path search
313// =============================================================================
314
315TEST(GraphUtilsPath, FindPathBreadthFirstStartEqualsEnd)
316{
317 Graph g;
318 auto nodes = make_nodes(g, 3);
319 g.insert_arc(nodes[0], nodes[1], 1);
320 g.insert_arc(nodes[1], nodes[2], 1);
321
322 auto path = find_path_breadth_first(g, nodes[1], nodes[1]);
323 EXPECT_FALSE(path.is_empty());
324 EXPECT_EQ(path.size(), 1U);
325 EXPECT_EQ(path.get_first_node(), nodes[1]);
326 EXPECT_EQ(path.get_last_node(), nodes[1]);
327}
328
329TEST(GraphUtilsPath, FindPathBreadthFirstReturnsEmptyPathWhenUnreachable)
330{
331 Graph g;
332 auto nodes = make_nodes(g, 4);
333 g.insert_arc(nodes[0], nodes[1], 1);
334 g.insert_arc(nodes[2], nodes[3], 1);
335
336 auto path = find_path_breadth_first(g, nodes[0], nodes[3]);
337 EXPECT_TRUE(path.is_empty());
338 EXPECT_TRUE(path.inside_graph(g));
339}
340
341TEST(GraphUtilsPath, FindPathBreadthFirstFindsShortestByEdges)
342{
343 Graph g;
344 auto nodes = make_nodes(g, 4);
345 g.insert_arc(nodes[0], nodes[3], 1); // direct
346 g.insert_arc(nodes[0], nodes[1], 1);
347 g.insert_arc(nodes[1], nodes[2], 1);
348 g.insert_arc(nodes[2], nodes[3], 1); // longer
349
350 auto path = find_path_breadth_first(g, nodes[0], nodes[3]);
351 ASSERT_FALSE(path.is_empty());
352 EXPECT_EQ(path.size(), 2U);
353
354 auto seq = path_nodes(path);
355 ASSERT_EQ(seq.size(), 2U);
356 EXPECT_EQ(seq.front(), nodes[0]);
357 EXPECT_EQ(seq.back(), nodes[3]);
358 EXPECT_NE(search_arc(g, seq[0], seq[1]), nullptr);
359}
360
361TEST(GraphUtilsPath, FindPathBreadthFirstRandomGraphsMatchesReferenceBfs)
362{
363 std::mt19937 rng(123456);
364 std::uniform_int_distribution<int> n_dist(2, 10);
365 std::bernoulli_distribution edge_dist(0.25);
366 std::uniform_int_distribution<int> pick_dist(0, 9);
367
368 for (int iter = 0; iter < 200; ++iter)
369 {
370 const int n = n_dist(rng);
371
372 Graph g;
373 auto nodes = make_nodes(g, n);
374 std::vector<std::vector<int>> adj(n);
375
376 for (int u = 0; u < n; ++u)
377 for (int v = u + 1; v < n; ++v)
378 if (edge_dist(rng))
379 {
380 g.insert_arc(nodes[u], nodes[v], 1);
381 adj[u].push_back(v);
382 adj[v].push_back(u);
383 }
384
385 const int s = pick_dist(rng) % n;
386 const int t = pick_dist(rng) % n;
387
388 const int ref = bfs_distance(adj, s, t);
389 auto path = find_path_breadth_first(g, nodes[s], nodes[t]);
390
391 if (ref < 0)
392 {
393 EXPECT_TRUE(path.is_empty());
394 }
395 else
396 {
397 ASSERT_FALSE(path.is_empty());
398 EXPECT_EQ(path.size(), static_cast<size_t>(ref + 1));
399
400 auto seq = path_nodes(path);
401 ASSERT_EQ(seq.front(), nodes[s]);
402 ASSERT_EQ(seq.back(), nodes[t]);
403 for (size_t i = 0; i + 1 < seq.size(); ++i)
404 EXPECT_NE(search_arc(g, seq[i], seq[i + 1]), nullptr);
405 }
406 }
407}
408
409// =============================================================================
410// Connectivity / cycles / reachability
411// =============================================================================
412
413TEST(GraphUtilsProperties, TestConnectivityBasics)
414{
415 Graph empty;
416 EXPECT_FALSE(test_connectivity(empty));
417
418 Graph single;
419 (void)single.insert_node(1);
420 EXPECT_TRUE(test_connectivity(single));
421
422 Graph g;
423 auto nodes = make_nodes(g, 4);
424 g.insert_arc(nodes[0], nodes[1], 1);
425 g.insert_arc(nodes[1], nodes[2], 1);
426 EXPECT_FALSE(test_connectivity(g)); // node[3] disconnected
427
428 g.insert_arc(nodes[2], nodes[3], 1);
429 EXPECT_TRUE(test_connectivity(g));
430}
431
432TEST(GraphUtilsProperties, TestConnectivityRejectsDigraphs)
433{
434 TestDigraph dg;
435 auto nodes = make_nodes(dg, 2);
436 dg.insert_arc(nodes[0], nodes[1], 1);
437 EXPECT_THROW(test_connectivity(dg), std::domain_error);
438}
439
440TEST(GraphUtilsProperties, TestForCycleBehavior)
441{
442 Graph g;
443 auto nodes = make_nodes(g, 3);
444 g.insert_arc(nodes[0], nodes[1], 1);
445 g.insert_arc(nodes[1], nodes[2], 1);
446 EXPECT_FALSE(test_for_cycle(g, nodes[0]));
447
448 g.insert_arc(nodes[2], nodes[0], 1); // triangle
449 EXPECT_TRUE(test_for_cycle(g, nodes[0]));
450
451 EXPECT_THROW(test_for_cycle(g, nullptr), std::invalid_argument);
452}
453
454TEST(GraphUtilsProperties, AcyclicAndHasCycleAgreement)
455{
456 Graph empty;
457 EXPECT_TRUE(is_graph_acyclique(empty));
458 EXPECT_FALSE(has_cycle(empty));
459
460 Graph tree;
461 auto nodes = make_nodes(tree, 4);
462 tree.insert_arc(nodes[0], nodes[1], 1);
463 tree.insert_arc(nodes[1], nodes[2], 1);
464 tree.insert_arc(nodes[2], nodes[3], 1);
465 EXPECT_TRUE(is_graph_acyclique(tree));
466 EXPECT_FALSE(has_cycle(tree));
467
468 tree.insert_arc(nodes[3], nodes[0], 1);
469 EXPECT_FALSE(is_graph_acyclique(tree));
470 EXPECT_TRUE(has_cycle(tree));
471}
472
473// is_graph_acyclique(g, start_node) is about the component of start_node,
474// but it answered by the arcs and nodes of all g
475TEST(GraphUtilsProperties, AcyclicFromANodeLooksAtItsComponent)
476{
477 Graph g;
478 auto nodes = make_nodes(g, 6);
479 g.insert_arc(nodes[0], nodes[1], 1); // a path
480 for (int i = 2; i < 6; ++i) // and a K4: 6 nodes, 7 arcs
481 for (int j = i + 1; j < 6; ++j)
482 g.insert_arc(nodes[i], nodes[j], 1);
483
484 EXPECT_TRUE(is_graph_acyclique(g, nodes[0]));
485 EXPECT_FALSE(is_graph_acyclique(g, nodes[2]));
486 EXPECT_FALSE(is_graph_acyclique(g));
487}
488
489// A graph of one node was acyclic even with a loop
490TEST(GraphUtilsProperties, AcyclicTakesALoopAsACycle)
491{
492 Graph g;
493 auto nodes = make_nodes(g, 1);
494 EXPECT_TRUE(is_graph_acyclique(g));
495 EXPECT_TRUE(is_graph_acyclique(g, nodes[0]));
496
497 g.insert_arc(nodes[0], nodes[0], 1);
498 EXPECT_FALSE(is_graph_acyclique(g));
499 EXPECT_FALSE(is_graph_acyclique(g, nodes[0]));
500 EXPECT_TRUE(has_cycle(g));
501
502 Graph h; // a loop in a tree, which the count of arcs does not see
503 auto m = make_nodes(h, 3);
504 h.insert_arc(m[0], m[1], 1);
505 h.insert_arc(m[2], m[2], 1);
506 EXPECT_FALSE(is_graph_acyclique(h));
507 EXPECT_FALSE(is_graph_acyclique(h, m[2]));
508 EXPECT_TRUE(is_graph_acyclique(h, m[0]));
509}
510
511TEST(GraphUtilsProperties, AcyclicRejectsDigraphs)
512{
513 TestDigraph dg;
514 auto nodes = make_nodes(dg, 2);
515 dg.insert_arc(nodes[0], nodes[1], 1);
516 EXPECT_THROW(is_graph_acyclique(dg), std::domain_error);
517 EXPECT_THROW(is_graph_acyclique(dg, nodes[0]), std::domain_error);
518 EXPECT_THROW(is_graph_acyclique(dg, nullptr), std::domain_error);
519}
520
521TEST(GraphUtilsProperties, TestForPathBasicAndRegression)
522{
523 Graph g;
524 auto nodes = make_nodes(g, 6);
525
526 // Two disjoint triangles (E == V) => there is no path across components.
527 g.insert_arc(nodes[0], nodes[1], 1);
528 g.insert_arc(nodes[1], nodes[2], 1);
529 g.insert_arc(nodes[2], nodes[0], 1);
530
531 g.insert_arc(nodes[3], nodes[4], 1);
532 g.insert_arc(nodes[4], nodes[5], 1);
533 g.insert_arc(nodes[5], nodes[3], 1);
534
535 EXPECT_FALSE(test_for_path(g, nodes[0], nodes[5]));
536 EXPECT_TRUE(test_for_path(g, nodes[0], nodes[0]));
537
538 EXPECT_THROW(test_for_path(g, nullptr, nodes[0]), std::invalid_argument);
539 EXPECT_THROW(test_for_path(g, nodes[0], nullptr), std::invalid_argument);
540}
541
542// =============================================================================
543// Connected components and subgraph mapping
544// =============================================================================
545
546// On a digraph an arc toward a component built before pointed to a node of
547// its subgraph, as in a -> b, c -> b, with a first; it rejects a digraph, as
548// test_connectivity() does
549TEST(GraphUtilsComponents, InconnectedComponentsRejectsDigraphs)
550{
551 TestDigraph dg;
552 auto nodes = make_nodes(dg, 3);
553 dg.insert_arc(nodes[0], nodes[1], 1);
554 dg.insert_arc(nodes[2], nodes[1], 2);
555 EXPECT_THROW((void) inconnected_components(dg), std::domain_error);
556}
557
558TEST(GraphUtilsComponents, InconnectedComponentsReturnsMappedSubgraphs)
559{
560 Graph g;
561 auto nodes = make_nodes(g, 4);
562 auto a01 = g.insert_arc(nodes[0], nodes[1], 1);
563 auto a12 = g.insert_arc(nodes[1], nodes[2], 1);
564
565 auto comps = inconnected_components(g);
566
567 std::multiset<std::pair<size_t, size_t>> sizes;
568 size_t comp_count = 0;
569 for (auto it = comps.get_it(); it.has_curr(); it.next_ne())
570 {
571 ++comp_count;
572 auto &sg = it.get_curr();
573 sizes.insert({sg.get_num_nodes(), sg.get_num_arcs()});
574 }
575
576 EXPECT_EQ(comp_count, 2U);
577 EXPECT_EQ(sizes, (std::multiset<std::pair<size_t, size_t>>{{3U, 2U}, {1U, 0U}}));
578
579 // Nodes and arcs must be mapped both ways through cookies.
580 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
581 {
582 auto gp = it.get_curr();
583 auto sp = mapped_node<Graph>(gp);
584 ASSERT_NE(sp, nullptr);
585 EXPECT_EQ(sp->get_info(), gp->get_info());
586 EXPECT_EQ(mapped_node<Graph>(sp), gp);
587 }
588
589 ASSERT_NE(mapped_arc<Graph>(a01), nullptr);
590 ASSERT_NE(mapped_arc<Graph>(a12), nullptr);
591 EXPECT_EQ(mapped_arc<Graph>(mapped_arc<Graph>(a01)), a01);
592 EXPECT_EQ(mapped_arc<Graph>(mapped_arc<Graph>(a12)), a12);
593}
594
595TEST(GraphUtilsComponents, BuildSubgraphCopiesReachableComponent)
596{
597 Graph g;
598 auto nodes = make_nodes(g, 4);
599 g.insert_arc(nodes[0], nodes[1], 1);
600 g.insert_arc(nodes[1], nodes[2], 1);
601 // node[3] is isolated
602
603 g.reset_nodes();
604 g.reset_arcs();
605
606 Graph sg;
607 size_t visited = 0;
608 build_subgraph(g, sg, nodes[0], visited);
609
610 EXPECT_EQ(visited, 3U);
611 EXPECT_EQ(sg.get_num_nodes(), 3U);
612 EXPECT_EQ(sg.get_num_arcs(), 2U);
613}
614
615// =============================================================================
616// Spanning trees
617// =============================================================================
618
619TEST(GraphUtilsSpanningTrees, DepthFirstSpanningTreeIsTreeAndMapped)
620{
621 Graph g;
622 auto nodes = make_nodes(g, 5);
623 g.insert_arc(nodes[0], nodes[1], 1);
624 g.insert_arc(nodes[1], nodes[2], 2);
625 g.insert_arc(nodes[2], nodes[3], 3);
626 g.insert_arc(nodes[3], nodes[4], 4);
627 g.insert_arc(nodes[0], nodes[4], 5); // add a cycle in the original graph
628
629 auto tree = find_depth_first_spanning_tree(g, nodes[0]);
630 EXPECT_EQ(tree.get_num_nodes(), g.get_num_nodes());
631 EXPECT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
632 EXPECT_TRUE(is_graph_acyclique(tree));
633
634 auto img = mapped_node<Graph>(nodes[0]);
635 ASSERT_NE(img, nullptr);
636 EXPECT_EQ(mapped_node<Graph>(img), nodes[0]);
637}
638
639TEST(GraphUtilsSpanningTrees, BreadthFirstSpanningTreeIsTreeAndMapped)
640{
641 Graph g;
642 auto nodes = make_nodes(g, 5);
643 g.insert_arc(nodes[0], nodes[1], 1);
644 g.insert_arc(nodes[1], nodes[2], 1);
645 g.insert_arc(nodes[2], nodes[3], 1);
646 g.insert_arc(nodes[3], nodes[4], 1);
647
648 g.reset_nodes();
649 g.reset_arcs();
650
651 auto tree = find_breadth_first_spanning_tree(g, nodes[0]);
652 EXPECT_EQ(tree.get_num_nodes(), g.get_num_nodes());
653 EXPECT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
654 EXPECT_TRUE(is_graph_acyclique(tree));
655}
656
657// =============================================================================
658// Build spanning tree from arcs (DynArray)
659// =============================================================================
660
661TEST(GraphUtilsSpanningTrees, BuildSpanningTreeFromArcsUsesOneWayMapping)
662{
663 Graph g;
664 auto nodes = make_nodes(g, 4);
665 auto a01 = g.insert_arc(nodes[0], nodes[1], 1);
666 auto a12 = g.insert_arc(nodes[1], nodes[2], 2);
667 auto a23 = g.insert_arc(nodes[2], nodes[3], 3);
668 (void)g.insert_arc(nodes[0], nodes[3], 99);
669
670 g.reset_nodes();
671 g.reset_arcs();
672
674 arcs.append(a01);
675 arcs.append(nullptr); // should be ignored
676 arcs.append(a12);
677 arcs.append(a23);
678
679 auto tree = build_spanning_tree<Graph>(arcs);
680 EXPECT_EQ(tree.get_num_nodes(), 4U);
681 EXPECT_EQ(tree.get_num_arcs(), 3U);
682
683 // Mapping is ret -> original via cookies.
684 for (auto it = tree.get_node_it(); it.has_curr(); it.next_ne())
685 {
686 auto tp = it.get_curr();
687 auto gp = static_cast<Graph::Node *>(NODE_COOKIE(tp));
688 ASSERT_NE(gp, nullptr);
689 EXPECT_EQ(gp->get_info(), tp->get_info());
690 }
691
692 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
693 {
694 auto ta = it.get_curr();
695 auto ga = static_cast<Graph::Arc *>(ARC_COOKIE(ta));
696 ASSERT_NE(ga, nullptr);
697 EXPECT_EQ(ta->get_info(), ga->get_info());
698 }
699
700 // Original graph cookies must remain untouched.
701 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
702 EXPECT_EQ(NODE_COOKIE(it.get_curr()), nullptr);
703}
704
705// =============================================================================
706// Cut nodes / painting / cut graph extraction
707// =============================================================================
708
709TEST(GraphUtilsCutNodes, ComputeCutNodesClearsCookiesAndFindsArticulations)
710{
711 Graph g;
712 auto nodes = make_nodes(g, 4);
713 g.insert_arc(nodes[0], nodes[1], 1);
714 g.insert_arc(nodes[1], nodes[2], 1);
715 g.insert_arc(nodes[2], nodes[3], 1);
716
717 auto cut_nodes = compute_cut_nodes(g, nodes[0]);
718
719 std::set<int> infos;
720 for (auto it = cut_nodes.get_it(); it.has_curr(); it.next_ne())
721 infos.insert(it.get_curr()->get_info());
722
723 EXPECT_EQ(infos, (std::set<int>{1, 2}));
724
725 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
726 EXPECT_EQ(NODE_COOKIE(it.get_curr()), nullptr);
727
728 // Digraphs are rejected.
729 TestDigraph dg;
730 auto dn = make_nodes(dg, 2);
731 dg.insert_arc(dn[0], dn[1], 1);
732 EXPECT_THROW(compute_cut_nodes(dg, dn[0]), std::domain_error);
733}
734
735TEST(GraphUtilsCutNodes, PaintAndExtractCutGraphOnChain)
736{
737 Graph g;
738 auto nodes = make_nodes(g, 4);
739 auto a01 = g.insert_arc(nodes[0], nodes[1], 1);
740 auto a12 = g.insert_arc(nodes[1], nodes[2], 1);
741 auto a23 = g.insert_arc(nodes[2], nodes[3], 1);
742
743 auto cut_nodes = compute_cut_nodes(g, nodes[0]);
744 const long colors_end = paint_subgraphs(g, cut_nodes);
745 EXPECT_EQ(colors_end, 3);
746
747 auto [cut_graph, cross_arcs] = map_cut_graph(g, cut_nodes);
748 EXPECT_EQ(cut_graph.get_num_nodes(), 2U);
749 EXPECT_EQ(cut_graph.get_num_arcs(), 1U);
750
751 // Cross arcs are the two edges adjacent to the cut nodes but reaching non-cut nodes.
752 std::set<Graph::Arc *> cross_set;
753 for (auto it = cross_arcs.get_it(); it.has_curr(); it.next_ne())
754 cross_set.insert(it.get_curr());
755
756 EXPECT_EQ(cross_set, (std::set<Graph::Arc *>{a01, a23}));
757
758 (void)a12; // cut arc is between the two cut nodes
759}
760
761TEST(GraphUtilsCutNodes, PaintAndExtractBlocksOnStar)
762{
763 Graph g;
764 auto nodes = make_nodes(g, 6); // 0 center, 1..5 leaves
765
766 for (int i = 1; i < 6; ++i)
767 g.insert_arc(nodes[0], nodes[i], 1);
768
769 auto cut_nodes = compute_cut_nodes(g, nodes[0]);
770 const long colors_end = paint_subgraphs(g, cut_nodes);
771
772 // Each leaf is a separate block => 5 colors: [1..5], so colors_end == 6.
773 EXPECT_EQ(colors_end, 6);
774
775 // Extract each painted block: each should be a single-node graph.
776 for (long c = 1; c < colors_end; ++c)
777 {
778 auto sg = map_subgraph(g, c);
779 EXPECT_EQ(sg.get_num_nodes(), 1U);
780 EXPECT_EQ(sg.get_num_arcs(), 0U);
781 }
782
783 auto [cut_graph, cross_arcs] = map_cut_graph(g, cut_nodes);
784 EXPECT_EQ(cut_graph.get_num_nodes(), 1U);
785 EXPECT_EQ(cut_graph.get_num_arcs(), 0U);
786
787 size_t cross_count = 0;
788 for (auto it = cross_arcs.get_it(); it.has_curr(); it.next_ne())
789 ++cross_count;
790 EXPECT_EQ(cross_count, 5U);
791}
792
793// =============================================================================
794// Digraph inversion (transpose)
795// =============================================================================
796
797TEST(GraphUtilsDigraph, InvertDigraphPreservesIsolatedNodesAndMapsArcs)
798{
799 TestDigraph g;
800 auto nodes = make_nodes(g, 3);
801 auto a01 = g.insert_arc(nodes[0], nodes[1], 42);
802 // nodes[2] is isolated
803
804 auto gi = invert_digraph(g);
805 EXPECT_EQ(gi.get_num_nodes(), 3U);
806 EXPECT_EQ(gi.get_num_arcs(), 1U);
807
808 auto n0i = mapped_node<TestDigraph>(nodes[0]);
809 auto n1i = mapped_node<TestDigraph>(nodes[1]);
810 auto n2i = mapped_node<TestDigraph>(nodes[2]);
811 ASSERT_NE(n0i, nullptr);
812 ASSERT_NE(n1i, nullptr);
813 ASSERT_NE(n2i, nullptr);
814
815 auto inv = search_directed_arc(gi, n1i, n0i);
816 ASSERT_NE(inv, nullptr);
817 EXPECT_EQ(inv->get_info(), 42);
818
819 ASSERT_NE(mapped_arc<TestDigraph>(a01), nullptr);
820 EXPECT_EQ(mapped_arc<TestDigraph>(mapped_arc<TestDigraph>(a01)), a01);
821}
822
823TEST(GraphUtilsDigraph, InvertDigraphRejectsUndirectedGraphs)
824{
825 Graph g;
826 (void)g.insert_node(0);
827 EXPECT_THROW(invert_digraph(g), std::domain_error);
828}
829
830TEST(GraphUtilsDigraph, InvertDigraphFunctorFiltersArcs)
831{
832 struct OnlyTwo
833 {
834 bool operator()(TestDigraph::Arc *a) const noexcept { return a->get_info() == 2; }
835 void set_cookie(void *) noexcept {}
836 };
837
838 TestDigraph g;
839 auto nodes = make_nodes(g, 3);
840 auto a01 = g.insert_arc(nodes[0], nodes[1], 1);
841 auto a12 = g.insert_arc(nodes[1], nodes[2], 2);
842
844 auto gi = inv(g);
845
846 EXPECT_EQ(gi.get_num_nodes(), 3U);
847 EXPECT_EQ(gi.get_num_arcs(), 1U);
848
849 auto n1i = mapped_node<TestDigraph>(nodes[1]);
850 auto n2i = mapped_node<TestDigraph>(nodes[2]);
851 ASSERT_NE(n1i, nullptr);
852 ASSERT_NE(n2i, nullptr);
853
854 EXPECT_NE(search_directed_arc(gi, n2i, n1i), nullptr);
855 EXPECT_EQ(ARC_COOKIE(a01), nullptr);
856 EXPECT_NE(ARC_COOKIE(a12), nullptr);
857}
858
859// =============================================================================
860// Dft_Dist / get_min_path / Total_Cost
861// =============================================================================
862
863TEST(GraphUtilsCosts, DftDistConstants)
864{
865 EXPECT_EQ((Dft_Dist<Graph>::Zero_Distance), 0);
866 EXPECT_EQ((Dft_Dist<Graph>::Max_Distance), std::numeric_limits<int>::max());
867}
868
869TEST(GraphUtilsCosts, GetMinPathReconstructsCookieChainAndComputesCost)
870{
871 WGraph g;
872 auto nodes = make_nodes(g, 3);
873 g.insert_arc(nodes[0], nodes[1], 2.5);
874 g.insert_arc(nodes[1], nodes[2], 3.0);
875
876 g.reset_nodes();
877
878 NODE_COOKIE(nodes[1]) = nodes[0];
879 NODE_COOKIE(nodes[2]) = nodes[1];
880
881 Path<WGraph> path(g);
882 const double dist = get_min_path<WGraph>(nodes[0], nodes[2], path);
883 EXPECT_DOUBLE_EQ(dist, 5.5);
884 EXPECT_EQ(path.size(), 3U);
885
886 auto seq = path_nodes(path);
887 ASSERT_EQ(seq.size(), 3U);
888 EXPECT_EQ(seq.front(), nodes[0]);
889 EXPECT_EQ(seq.back(), nodes[2]);
890
891 // start == end is a valid trivial path.
892 const double dist0 = get_min_path<WGraph>(nodes[1], nodes[1], path);
893 EXPECT_DOUBLE_EQ(dist0, 0.0);
894 EXPECT_EQ(path.size(), 1U);
895
896 // Broken chain (nullptr) must throw.
897 g.reset_nodes();
898 NODE_COOKIE(nodes[2]) = nullptr;
899 EXPECT_THROW(get_min_path<WGraph>(nodes[0], nodes[2], path), std::domain_error);
900}
901
902TEST(GraphUtilsCosts, TotalCostSumsArcsAndAccumulatorWorks)
903{
904 Graph g;
905 auto nodes = make_nodes(g, 4);
906 g.insert_arc(nodes[0], nodes[1], 1);
907 g.insert_arc(nodes[0], nodes[2], 2);
908 g.insert_arc(nodes[0], nodes[3], 3);
909
911 EXPECT_EQ(cost.total_cost(g), 6);
912
913 // Accumulator usage with traverse_arcs(): sum incident arcs to node[0].
914 cost.reset();
915 EXPECT_TRUE((traverse_arcs<Graph, Node_Arc_Iterator<Graph>>(nodes[0], std::ref(cost))));
916 EXPECT_EQ(cost.value(), 6);
917}
long double h
Definition btreepic.C:154
Stateful breadth-first traversal functor.
Stateful depth-first traversal functor.
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Arc Arc
Definition graph-dry.H:4381
T & append()
Allocate a new entry to the end of array.
Functor for computing the transposed digraph, filtering arcs.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Node Node
The graph type.
Definition tpl_graph.H:443
Arc Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Path on a graph.
Definition tpl_graph.H:3832
void for_each_node(Operation op=Operation()) const
Execute an operation on each node of path.
Definition tpl_graph.H:4529
size_t size() const noexcept
Return the path length in nodes.
Definition tpl_graph.H:3987
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4316
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
bool inside_graph(const GT &gr) const noexcept
Return true if this is on graph gr
Definition tpl_graph.H:3927
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4323
Compute the total cost (sum of arc weights) of a graph.
Distance::Distance_Type total_cost(GT &g)
Compute the total cost.
Distance::Distance_Type value() const noexcept
Return the accumulated value (after using operator()(Arc*)).
void reset() noexcept
Reset the internal accumulator used by operator()(Arc*).
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1213
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
Definition graph-dry.H:1206
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
#define TEST(name)
static mt19937 rng
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
size_t depth_first_traversal(const GT &g, typename GT::Node *start_node, bool(*visit)(const GT &g, typename GT::Node *, typename GT::Arc *))
Depth-first traversal starting from a given node.
GT::Arc * search_arc(const GT &g, typename GT::Node *src, typename GT::Node *tgt, SA sa=SA()) noexcept(nothrow_arc_filter_v< GT, SA >)
Arc filtered searching given two nodes.
Definition tpl_graph.H:3574
#define ARC_COOKIE(p)
Return the arc cookie
bool has_cycle(const GT &g)
Return true if an undirected graph has at least one cycle.
DynList< GT > inconnected_components(const GT &g)
Forward declaration for inconnected_components().
bool test_for_cycle(const GT &g, typename GT::Node *src)
Search for a cycle reachable from a given node.
GT find_breadth_first_spanning_tree(GT &g, typename GT::Node *gp)
Build a breadth-first spanning tree (mapped to the original graph).
bool traverse_arcs(typename GT::Node *p, Operation op=Operation())
Generic arcs traverse of a node.
Definition tpl_graph.H:2891
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
GT invert_digraph(const GT &g)
Compute the transpose (arc-reversed) digraph.
GT::Arc * search_directed_arc(const GT &g, typename GT::Node *src, typename GT::Node *tgt, SA sa=SA()) noexcept(nothrow_arc_filter_v< GT, SA >)
Searching of directed arc linking two nodes.
Definition tpl_graph.H:3603
bool test_connectivity(const GT &g)
Connectivity test for undirected graphs.
#define NODE_COOKIE(p)
Return the node cookie
long paint_subgraphs(const GT &g, const DynList< typename GT::Node * > &cut_node_list)
Paint connected blocks around articulation points.
DynList< typename GT::Node * > compute_cut_nodes(const GT &g, typename GT::Node *start)
Compute articulation points (cut vertices) of an undirected graph.
Path< GT > find_path_breadth_first(const GT &g, typename GT::Node *start, typename GT::Node *end)
Breadth-first search of a (shortest-by-edges) path between two nodes.
bool test_for_path(const GT &g, typename GT::Node *start_node, typename GT::Node *end_node)
Return true if there is a path between two nodes.
size_t breadth_first_traversal(const GT &g, typename GT::Node *start, bool(*visit)(const GT &, typename GT::Node *, typename GT::Arc *))
Breadth-first traversal starting from a given node.
void build_subgraph(const GT &g, GT &sg, typename GT::Node *g_src, size_t &node_count)
Forward declaration for build_subgraph().
GT find_depth_first_spanning_tree(const GT &g, typename GT::Node *gnode)
Build a depth-first spanning tree (mapped to the original graph).
bool is_graph_acyclique(const GT &g, typename GT::Node *start_node)
Return true if an undirected graph is acyclic.
std::tuple< GT, DynList< typename GT::Arc * > > map_cut_graph(const GT &g, const DynList< typename GT::Node * > &cut_node_list)
Extract the cut graph and cross-arc list.
GT map_subgraph(const GT &g, const long color)
Extract a mapped subgraph containing a given color.
@ Depth_First
Definition aleph-graph.H:73
@ Breadth_First
Definition aleph-graph.H:74
Main namespace for Aleph-w library functions.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Lazy and scalable dynamic array implementation.
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.