Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
generate_df_tree_test.cc
Go to the documentation of this file.
1
6#include <gtest/gtest.h>
7
8#include <algorithm>
9#include <functional>
10#include <memory>
11#include <random>
12#include <set>
13#include <sstream>
14#include <stdexcept>
15#include <string>
16#include <utility>
17#include <vector>
18
19#if defined(__unix__) || defined(__APPLE__)
20#include <pthread.h>
21#endif
22
23#include <generate_df_tree.H>
24#include <tpl_cut_nodes.H>
25#include <tpl_graph_utils.H>
26
27using namespace Aleph;
28
29namespace
30{
32 using Node = Graph::Node;
33 using Arc = Graph::Arc;
34
35 // Owner of a tree returned by build_df_low_tree()
36 using Tree_Ptr = std::unique_ptr<Df_Low_Tree_Node, void (*)(Df_Low_Tree_Node *)>;
37
38 Tree_Ptr own(Df_Low_Tree_Node * root)
39 {
40 return Tree_Ptr(root, [] (Df_Low_Tree_Node * p) { destroy_tree(p); });
41 }
42
43 // Two triangles, 0-1-2 and 1-3-4, and the arc 4-5: the cut nodes are 1
44 // and 4, and the only bridge is 4-5. The info of an arc u-v is 10 u + v.
45 struct Two_Triangles
46 {
47 Graph g;
48 std::vector<Node *> n;
49
50 Two_Triangles()
51 {
52 for (int i = 0; i < 6; ++i)
53 n.push_back(g.insert_node(i));
54
55 const int arcs[][2] = {{0, 1}, {1, 2}, {2, 0}, {1, 3}, {3, 4}, {4, 1}, {4, 5}};
56 for (const auto & a : arcs)
57 g.insert_arc(n[a[0]], n[a[1]], 10 * a[0] + a[1]);
58 }
59 };
60
61 // The arcs are traversed in the order of insertion, so from 0 the tree is
62 // 0 - 1 - {2, 3 - 4 - 5}, and the other arcs are 2-0 and 4-1
63 const std::string two_triangles_low =
64 "Root \"0,0,-\" \n"
65 "Node 0 \"1,1,0\" \n"
66 "Node 0.0 \"2,2,0\" \n"
67 "Node 0.0 \"3,3,1\" \n"
68 "Node 0.0.1 \"4,4,1\" \n"
69 "Node 0.0.1.0 \"5,5,5\" \n"
70 "Dashed-Connexion 0.0.0 0 L\n"
71 "Dashed-Connexion 0.0.1.0 0.0 R\n";
72
73 // Hides the arc whose info is info
74 struct Hide_Arc
75 {
76 int info = -1;
77
78 bool operator () (Arc * a) const noexcept
79 {
80 return a->get_info() != info;
81 }
82 };
83
84 // Tree nodes of a tree in preorder
85 std::vector<Df_Low_Tree_Node *> preorder(Df_Low_Tree_Node * root)
86 {
87 std::vector<Df_Low_Tree_Node *> nodes;
88 std::function<void(Df_Low_Tree_Node *)> visit = [&] (Df_Low_Tree_Node * p)
89 {
90 nodes.push_back(p);
91 for (auto c = p->get_left_child(); c != nullptr; c = c->get_right_sibling())
92 visit(c);
93 };
94 visit(root);
95 return nodes;
96 }
97
98 Df_Low_Tree_Node * find_label(Df_Low_Tree_Node * root, const std::string & label)
99 {
100 for (auto p : preorder(root))
101 if (p->get_key().label == label)
102 return p;
103 return nullptr;
104 }
105
106 std::pair<std::string, std::string> labels(const Df_Low_Non_Tree_Arc & a)
107 {
108 return {a.first->get_key().label, a.second->get_key().label};
109 }
110
111 std::vector<std::pair<std::string, std::string>>
112 labels(const DynList<Df_Low_Non_Tree_Arc> & arcs)
113 {
114 std::vector<std::pair<std::string, std::string>> ret;
115 arcs.for_each([&ret] (const Df_Low_Non_Tree_Arc & a) { ret.push_back(labels(a)); });
116 return ret;
117 }
118
119 using Label_Pairs = std::vector<std::pair<std::string, std::string>>;
120}
121
122TEST(Df_Low_Tree, writes_the_tree_with_df_low_and_the_other_arcs)
123{
124 Two_Triangles t;
125 std::ostringstream out;
126 write_df_low_tree(t.g, t.n[0], out);
127 EXPECT_EQ(out.str(), two_triangles_low);
128}
129
130TEST(Df_Low_Tree, writes_the_labels_that_the_writer_chooses)
131{
132 Two_Triangles t;
133
134 std::ostringstream df;
135 write_df_low_tree<Write_Df_Tree_Df>(t.g, t.n[0], df);
136 EXPECT_EQ(df.str(),
137 "Root \"(0,0)\" \n"
138 "Node 0 \"(1,1)\" \n"
139 "Node 0.0 \"(2,2)\" \n"
140 "Node 0.0 \"(3,3)\" \n"
141 "Node 0.0.1 \"(4,4)\" \n"
142 "Node 0.0.1.0 \"(5,5)\" \n"
143 "Dashed-Connexion 0.0.0 0 L\n"
144 "Dashed-Connexion 0.0.1.0 0.0 R\n");
145
146 std::ostringstream label;
147 write_df_low_tree<Write_Df_Tree_Label>
148 (t.g, t.n[0], label,
149 [] (Node * p) { return std::string(1, char('A' + p->get_info())); });
150 EXPECT_EQ(label.str(),
151 "Root \"A\" \n"
152 "Node 0 \"B\" \n"
153 "Node 0.0 \"C\" \n"
154 "Node 0.0 \"D\" \n"
155 "Node 0.0.1 \"E\" \n"
156 "Node 0.0.1.0 \"F\" \n"
157 "Dashed-Connexion 0.0.0 0 L\n"
158 "Dashed-Connexion 0.0.1.0 0.0 R\n");
159}
160
161TEST(Df_Low_Tree, builds_the_tree_and_the_other_arcs)
162{
163 Two_Triangles t;
165 auto tree = own(build_df_low_tree(t.g, t.n[0], others));
166
167 std::vector<std::string> keys;
168 for (auto p : preorder(tree.get()))
169 {
170 const Df_Low_Key & k = p->get_key();
171 keys.push_back(k.label + ":" + std::to_string(k.df) + ":" + std::to_string(k.low));
172 }
173 EXPECT_EQ(keys, (std::vector<std::string>{"0:0:-1", "1:1:0", "2:2:0", "3:3:1",
174 "4:4:1", "5:5:5"}));
175 EXPECT_EQ(labels(others), (Label_Pairs{{"2", "0"}, {"4", "1"}}));
176}
177
178TEST(Df_Low_Tree, the_tree_depends_on_the_start_node)
179{
180 Two_Triangles t;
181 std::ostringstream out;
182 write_df_low_tree(t.g, t.n[5], out);
183 EXPECT_EQ(out.str(),
184 "Root \"5,0,-\" \n"
185 "Node 0 \"4,1,1\" \n"
186 "Node 0.0 \"3,2,1\" \n"
187 "Node 0.0.0 \"1,3,1\" \n"
188 "Node 0.0.0.0 \"0,4,3\" \n"
189 "Node 0.0.0.0.0 \"2,5,3\" \n"
190 "Dashed-Connexion 0.0.0.0.0.0 0.0.0.0 L\n"
191 "Dashed-Connexion 0.0.0.0 0.0 R\n");
192}
193
194TEST(Df_Low_Tree, a_single_node_is_only_a_root)
195{
196 Graph g;
197 Node * p = g.insert_node(7);
198 std::ostringstream out;
199 write_df_low_tree(g, p, out);
200 EXPECT_EQ(out.str(), "Root \"7,0,-\" \n");
201}
202
203TEST(Df_Low_Tree, the_default_label_writes_the_node_info)
204{
206 auto a = g.insert_node("a");
207 auto b = g.insert_node("b");
208 g.insert_arc(a, b, 0);
209
210 std::ostringstream out;
211 write_df_low_tree(g, a, out);
212 EXPECT_EQ(out.str(), "Root \"a,0,-\" \nNode 0 \"b,1,1\" \n");
213}
214
215TEST(Df_Low_Tree, a_parallel_arc_is_another_arc)
216{
217 Two_Triangles t;
218 t.g.insert_arc(t.n[4], t.n[5], 45);
219
221 auto tree = own(build_df_low_tree(t.g, t.n[0], others));
222 EXPECT_EQ(labels(others), (Label_Pairs{{"2", "0"}, {"4", "1"}, {"5", "4"}}));
223 EXPECT_EQ(find_label(tree.get(), "5")->get_key().low, 4); // 4-5 is no bridge
224}
225
226TEST(Df_Low_Tree, an_arc_from_a_node_to_itself_is_left_out)
227{
228 Two_Triangles t;
229 t.g.insert_arc(t.n[3], t.n[3], 33);
230
231 std::ostringstream out;
232 write_df_low_tree(t.g, t.n[0], out);
233 EXPECT_EQ(out.str(), two_triangles_low);
234}
235
236TEST(Df_Low_Tree, only_the_arcs_that_the_filter_shows_count)
237{
238 Two_Triangles t;
240 auto tree = own(build_df_low_tree(t.g, t.n[0], others,
241 Dft_Df_Tree_Label<Graph>(), Hide_Arc{20}));
242
243 EXPECT_EQ(labels(others), (Label_Pairs{{"4", "1"}}));
244 EXPECT_EQ(find_label(tree.get(), "2")->get_key().low, 2);
245 EXPECT_EQ(find_label(tree.get(), "1")->get_key().low, 1);
246}
247
248TEST(Df_Low_Tree, only_the_nodes_that_the_start_node_reaches_are_in_the_tree)
249{
250 Two_Triangles t;
251 Node * x = t.g.insert_node(10);
252 Node * y = t.g.insert_node(11);
253 t.g.insert_arc(x, y, 1011);
254 t.g.insert_arc(y, x, 1110);
255
257 auto tree = own(build_df_low_tree(t.g, t.n[0], others));
258 EXPECT_EQ(preorder(tree.get()).size(), 6U);
259 EXPECT_EQ(labels(others), (Label_Pairs{{"2", "0"}, {"4", "1"}}));
260
261 auto other = own(build_df_low_tree(t.g, x, others));
262 EXPECT_EQ(preorder(other.get()).size(), 2U);
263 EXPECT_EQ(labels(others), (Label_Pairs{{"11", "10"}}));
264}
265
266TEST(Df_Low_Tree, does_not_modify_the_graph)
267{
268 Two_Triangles t;
269 for (auto p : t.n)
270 {
271 NODE_COOKIE(p) = p;
272 NODE_COUNTER(p) = 100 + p->get_info();
273 }
274 for (auto it = t.g.get_arc_it(); it.has_curr(); it.next_ne())
275 ARC_COOKIE(it.get_curr()) = it.get_curr();
276
277 std::ostringstream out;
278 write_df_low_tree(t.g, t.n[0], out);
280 auto tree = own(build_df_low_tree(t.g, t.n[0], others));
281
282 for (auto p : t.n)
283 {
284 EXPECT_EQ(NODE_COOKIE(p), p);
285 EXPECT_EQ(NODE_COUNTER(p), 100 + p->get_info());
286 }
287 for (auto it = t.g.get_arc_it(); it.has_curr(); it.next_ne())
288 EXPECT_EQ(ARC_COOKIE(it.get_curr()), it.get_curr());
289}
290
291TEST(Df_Low_Tree, rejects_a_digraph_and_a_null_start_node)
292{
294 auto a = dg.insert_node(0);
295 dg.insert_arc(a, dg.insert_node(1), 0);
296
298 std::ostringstream out;
299 EXPECT_THROW((void) build_df_low_tree(dg, a, others), std::domain_error);
300 EXPECT_THROW(write_df_low_tree(dg, a, out), std::domain_error);
301
302 Two_Triangles t;
303 EXPECT_THROW((void) build_df_low_tree(t.g, nullptr, others), std::invalid_argument);
304 EXPECT_THROW(write_df_low_tree(t.g, nullptr, out), std::invalid_argument);
305 EXPECT_TRUE(out.str().empty());
306}
307
308TEST(Df_Low_Tree, an_exception_leaves_nothing_behind)
309{
310 Two_Triangles t;
311 int calls = 0;
312 auto label = [&calls] (Node * p)
313 {
314 if (++calls == 4) // node 3, after the arc 2-0 was found
315 throw std::runtime_error("label");
316 return std::to_string(p->get_info());
317 };
318
320 EXPECT_THROW((void) build_df_low_tree(t.g, t.n[0], others, label), std::runtime_error);
321 EXPECT_TRUE(others.is_empty());
322
323 calls = 0;
324 std::ostringstream out;
325 EXPECT_THROW(write_df_low_tree(t.g, t.n[0], out, label), std::runtime_error);
326 EXPECT_TRUE(out.str().empty());
327}
328
329// write_df_low_tree() refused the trees of more levels than generate_tree()
330// wrote, Max_Tree_Node_Depth
331TEST(Df_Low_Tree, a_tree_of_any_depth_is_written)
332{
333 for (const size_t n : {Max_Tree_Node_Depth, Max_Tree_Node_Depth + 1, size_t(3000)})
334 {
335 Graph g; // a path of n nodes, a tree of n levels
336 Node * first = g.insert_node(0);
337 Node * last = first;
338 for (size_t i = 1; i < n; ++i)
339 {
340 Node * p = g.insert_node(int(i));
341 g.insert_arc(last, p, 0);
342 last = p;
343 }
344
345 std::ostringstream out;
346 EXPECT_NO_THROW(write_df_low_tree(g, first, out));
347
348 // the root and a node for each other one
349 const std::string s = out.str();
350 size_t nodes = 0;
351 for (size_t pos = s.find("Node "); pos != std::string::npos; pos = s.find("Node ", pos + 1))
352 ++nodes;
353 EXPECT_EQ(s.rfind("Root ", 0), 0u);
354 EXPECT_EQ(nodes, n - 1);
355 }
356}
357
358namespace
359{
360 // Runs f, which must not throw, in a thread with a stack of 256 KiB, which
361 // a recursion as deep as the trees of these tests are high overflows.
362 // Without POSIX threads, it runs f in this thread.
363 template <class F>
364 void run_with_small_stack(F f)
365 {
366#if defined(__unix__) || defined(__APPLE__)
367 pthread_attr_t attr;
368 ASSERT_EQ(pthread_attr_init(&attr), 0);
369 ASSERT_EQ(pthread_attr_setstacksize(&attr, 256 * 1024), 0);
370 auto start = [](void *arg) -> void *
371 {
372 (*static_cast<F *>(arg))();
373 return nullptr;
374 };
375 pthread_t thread;
376 const int created = pthread_create(&thread, &attr, start, &f);
377 pthread_attr_destroy(&attr);
378 ASSERT_EQ(created, 0);
379 ASSERT_EQ(pthread_join(thread, nullptr), 0);
380#else
381 f();
382#endif
383 }
384} // namespace
385
386// write_df_low_tree() gave the Dewey numbers with a recursion, one call
387// for each level, which did not fit in a small stack; it also kept the
388// number of every node, although only those of the ends of the other arcs
389// are written
390TEST(Df_Low_Tree, a_deep_tree_is_written_on_a_small_stack)
391{
392 constexpr size_t n = 3000;
393 Graph g; // a cycle of n nodes: a tree of n levels and an arc to the root
394 Node * first = g.insert_node(0);
395 Node * last = first;
396 for (size_t i = 1; i < n; ++i)
397 {
398 Node * p = g.insert_node(int(i));
399 g.insert_arc(last, p, 0);
400 last = p;
401 }
402 g.insert_arc(last, first, 0);
403
404 std::string s;
405 bool threw = false;
406 run_with_small_stack([&]
407 {
408 try
409 {
410 std::ostringstream out;
411 write_df_low_tree(g, first, out);
412 s = out.str();
413 }
414 catch (...)
415 {
416 threw = true;
417 }
418 });
419 ASSERT_FALSE(threw);
420
421 size_t nodes = 0;
422 for (size_t pos = s.find("Node "); pos != std::string::npos; pos = s.find("Node ", pos + 1))
423 ++nodes;
424 EXPECT_EQ(s.rfind("Root ", 0), 0u);
425 EXPECT_EQ(nodes, n - 1);
426
427 std::string deepest = "0"; // the Dewey number of the last node
428 for (size_t i = 1; i < n; ++i)
429 deepest += ".0";
430 EXPECT_NE(s.find("Dashed-Connexion " + deepest + " 0 "), std::string::npos);
431}
432
433// The df and low numbers give the same cut nodes and bridges as
434// compute_cut_nodes() and find_bridges(), on random connected graphs with
435// cycles and parallel arcs
436TEST(Df_Low_Tree, agrees_with_cut_nodes_and_bridges)
437{
438 std::mt19937 rng(20261020);
439 for (int round = 0; round < 200; ++round)
440 {
441 Graph g;
442 const int num_nodes = 1 + int(rng() % 40);
443 std::vector<Node *> n;
444 for (int i = 0; i < num_nodes; ++i)
445 n.push_back(g.insert_node(i));
446 for (int i = 1; i < num_nodes; ++i) // a spanning tree
447 g.insert_arc(n[i], n[rng() % i], 0);
448 for (int k = int(rng() % (num_nodes + 1)); k > 0; --k)
449 if (int u = int(rng() % num_nodes), v = int(rng() % num_nodes); u != v)
450 g.insert_arc(n[u], n[v], 0);
451
452 Node * src = n[rng() % num_nodes];
454 auto tree = own(build_df_low_tree(g, src, others));
455
456 const auto nodes = preorder(tree.get());
457 ASSERT_EQ(nodes.size(), size_t(num_nodes));
458 ASSERT_EQ(others.size(), g.get_num_arcs() - (num_nodes - 1));
459
460 std::set<std::string> cuts;
461 std::set<std::pair<std::string, std::string>> bridges;
462 for (size_t i = 0; i < nodes.size(); ++i)
463 {
464 Df_Low_Tree_Node * p = nodes[i];
465 const Df_Low_Key & k = p->get_key();
466 ASSERT_EQ(k.df, long(i)); // preorder
467 ASSERT_EQ(k.low >= 0, p != tree.get());
468
469 size_t children = 0;
470 bool cut = false;
471 for (auto c = p->get_left_child(); c != nullptr; c = c->get_right_sibling())
472 {
473 ++children;
474 cut = cut or c->get_key().low >= k.df;
475 if (c->get_key().low > k.df)
476 bridges.insert(std::minmax(k.label, c->get_key().label));
477 }
478 if (p == tree.get() ? children > 1 : cut)
479 cuts.insert(k.label);
480 }
481
482 others.for_each([] (const Df_Low_Non_Tree_Arc & a)
483 { // from a descendant to its ancestor
484 bool ancestor = false;
485 for (auto q = a.first->get_parent(); q != nullptr and not ancestor; q = q->get_parent())
486 ancestor = q == a.second;
487 EXPECT_TRUE(ancestor) << a.first->get_key().label << " " << a.second->get_key().label;
488 });
489
490 std::set<std::string> expected_cuts;
491 compute_cut_nodes(g, src).for_each([&] (Node * p)
492 {
493 expected_cuts.insert(std::to_string(p->get_info()));
494 });
495 std::set<std::pair<std::string, std::string>> expected_bridges;
496 find_bridges(g, src).for_each([&] (Arc * a)
497 {
498 expected_bridges.insert(std::minmax(std::to_string(g.get_src_node(a)->get_info()),
499 std::to_string(g.get_tgt_node(a)->get_info())));
500 });
501
502 EXPECT_EQ(cuts, expected_cuts) << "round " << round;
503 EXPECT_EQ(bridges, expected_bridges) << "round " << round;
504 }
505}
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int num_nodes
Definition btreepic.C:410
size_t size_t int32_t * out
Definition ca-c-api.h:120
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
size_t size() const noexcept
Return the current dimension of array.
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
const Type * first() const
Get the first element.
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
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
Forward declaration used by CRTP helpers before the full node definition.
Tree_Node * get_left_child() const noexcept
Returns the leftmost child of this.
T & get_key() noexcept
Returns a modifiable reference to the node contents.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
static mt19937 rng
Pictures of depth-first trees with their df and low numbers.
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
#define ARC_COOKIE(p)
Return the arc cookie
#define NODE_COUNTER(p)
Get the counter of a node.
Df_Low_Tree_Node * build_df_low_tree(const GT &g, typename GT::Node *src, DynList< Df_Low_Non_Tree_Arc > &non_tree_arcs, Node_Label node_label=Node_Label(), SA sa=SA())
Build the depth-first spanning tree of an undirected graph, with the df and low numbers of its nodes.
#define NODE_COOKIE(p)
Return the node cookie
DynList< typename GT::Node * > compute_cut_nodes(const GT &g, typename GT::Node *start)
Compute articulation points (cut vertices) of an undirected graph.
void write_df_low_tree(const GT &g, typename GT::Node *src, std::ostream &out, Node_Label node_label=Node_Label(), SA sa=SA())
Write, for ntreepic, the depth-first spanning tree of an undirected graph with the df and low numbers...
DynList< typename GT::Arc * > find_bridges(const GT &g, typename GT::Node *start, SA sa=SA())
Find all bridge edges in a connected undirected graph.
void destroy_tree(Node *root)
Destroys (frees memory) the tree whose root is root.
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
constexpr size_t Max_Tree_Node_Depth
The depth of the trees that generate_tree() wrote before 7.3.2; it writes trees of any depth now.
Tree_Node< Df_Low_Key > Df_Low_Tree_Node
Node of the depth-first tree that build_df_low_tree() returns.
std::pair< Df_Low_Tree_Node *, Df_Low_Tree_Node * > Df_Low_Non_Tree_Arc
Arc of the graph that is not in the depth-first tree.
and
Check uniqueness with explicit hash + equality functors.
static long & df(typename GT::Node *p)
Internal helper: DFS discovery time stored in NODE_COUNTER(p).
bool run_with_small_stack(F &&f, size_t kb=256)
Runs f in a thread whose stack has kb KiB, and returns false if the thread could not run; without POS...
Key of a node of a depth-first tree with df and low numbers.
Default label of a graph node: its information, written with operator <<.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
int keys[]
DynArray< int > preorder
static int * k
Articulation points (cut nodes), bridges, and biconnected components.
Utility algorithms and operations for graphs.