48#include <gtest/gtest.h>
69 std::vector<Graph::Node *> make_nodes(
Graph &g,
int n)
71 std::vector<Graph::Node *>
nodes;
73 for (
int i = 0; i < n; ++i)
78 std::vector<TestDigraph::Node *> make_nodes(
TestDigraph &g,
int n)
80 std::vector<TestDigraph::Node *>
nodes;
82 for (
int i = 0; i < n; ++i)
83 nodes.push_back(g.insert_node(i));
87 std::vector<WGraph::Node *> make_nodes(WGraph &g,
int n)
89 std::vector<WGraph::Node *>
nodes;
91 for (
int i = 0; i < n; ++i)
92 nodes.push_back(g.insert_node(i));
104 if (node == g_expected_start)
105 EXPECT_EQ(from,
nullptr);
107 EXPECT_NE(from,
nullptr);
121 struct CollectVisitedInfos
123 std::vector<int> *infos =
nullptr;
133 struct EvenArcInfoOnly
135 bool operator()(
typename GT::Arc *a)
const noexcept
137 return (a->get_info() % 2) == 0;
145 int bfs_distance(
const std::vector<std::vector<int>> &adj,
int s,
int t)
150 std::vector<int> dist(adj.size(), -1);
163 dist[v] = dist[u] + 1;
174 std::vector<typename GT::Node *> path_nodes(
const Path<GT> &path)
176 std::vector<typename GT::Node *>
nodes;
187TEST(GraphUtilsTraversal, DepthFirstTraversalCountsReachableNodes)
190 auto nodes = make_nodes(g, 5);
196 const auto no_visit =
199 EXPECT_EQ(visited, 5U);
201 for (
auto it = g.
get_node_it(); it.has_curr(); it.next_ne())
205TEST(GraphUtilsTraversal, DepthFirstTraversalProvidesFromArc)
208 auto nodes = make_nodes(g, 3);
212 g_expected_start =
nodes[0];
216TEST(GraphUtilsTraversal, DepthFirstTraversalStopsImmediately)
219 auto nodes = make_nodes(g, 3);
224 EXPECT_EQ(visited, 1U);
227TEST(GraphUtilsTraversal, BreadthFirstTraversalCountsReachableNodes)
230 auto nodes = make_nodes(g, 5);
236 const auto no_visit =
239 EXPECT_EQ(visited, 5U);
241 for (
auto it = g.
get_node_it(); it.has_curr(); it.next_ne())
245TEST(GraphUtilsTraversal, BreadthFirstTraversalProvidesFromArc)
248 auto nodes = make_nodes(g, 3);
252 g_expected_start =
nodes[0];
256TEST(GraphUtilsTraversal, BreadthFirstTraversalStopsImmediately)
259 auto nodes = make_nodes(g, 3);
264 EXPECT_EQ(visited, 1U);
271TEST(GraphUtilsTraversal, DepthFirstTraversalFunctorHonorsArcFilter)
274 auto nodes = make_nodes(g, 3);
278 std::vector<int> visited_infos;
279 CollectVisitedInfos<Graph> op{&visited_infos};
282 EvenArcInfoOnly<Graph>()};
284 const size_t visited = dft(g,
nodes[0], op);
285 EXPECT_EQ(visited, 2U);
287 std::set<int> s(visited_infos.begin(), visited_infos.end());
288 EXPECT_EQ(s, (std::set<int>{0, 1}));
291TEST(GraphUtilsTraversal, BreadthFirstTraversalFunctorHonorsArcFilter)
294 auto nodes = make_nodes(g, 3);
298 std::vector<int> visited_infos;
299 CollectVisitedInfos<Graph> op{&visited_infos};
302 EvenArcInfoOnly<Graph>()};
304 const size_t visited = bft(g,
nodes[0], op);
305 EXPECT_EQ(visited, 2U);
307 std::set<int> s(visited_infos.begin(), visited_infos.end());
308 EXPECT_EQ(s, (std::set<int>{0, 1}));
315TEST(GraphUtilsPath, FindPathBreadthFirstStartEqualsEnd)
318 auto nodes = make_nodes(g, 3);
324 EXPECT_EQ(path.
size(), 1U);
329TEST(GraphUtilsPath, FindPathBreadthFirstReturnsEmptyPathWhenUnreachable)
332 auto nodes = make_nodes(g, 4);
341TEST(GraphUtilsPath, FindPathBreadthFirstFindsShortestByEdges)
344 auto nodes = make_nodes(g, 4);
352 EXPECT_EQ(path.
size(), 2U);
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);
361TEST(GraphUtilsPath, FindPathBreadthFirstRandomGraphsMatchesReferenceBfs)
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);
368 for (
int iter = 0; iter < 200; ++iter)
370 const int n = n_dist(
rng);
373 auto nodes = make_nodes(g, n);
374 std::vector<std::vector<int>> adj(n);
376 for (
int u = 0; u < n; ++u)
377 for (
int v = u + 1; v < n; ++v)
385 const int s = pick_dist(
rng) % n;
386 const int t = pick_dist(
rng) % n;
388 const int ref = bfs_distance(adj, s, t);
398 EXPECT_EQ(path.
size(),
static_cast<size_t>(ref + 1));
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);
413TEST(GraphUtilsProperties, TestConnectivityBasics)
423 auto nodes = make_nodes(g, 4);
432TEST(GraphUtilsProperties, TestConnectivityRejectsDigraphs)
435 auto nodes = make_nodes(dg, 2);
440TEST(GraphUtilsProperties, TestForCycleBehavior)
443 auto nodes = make_nodes(g, 3);
454TEST(GraphUtilsProperties, AcyclicAndHasCycleAgreement)
461 auto nodes = make_nodes(tree, 4);
475TEST(GraphUtilsProperties, AcyclicFromANodeLooksAtItsComponent)
478 auto nodes = make_nodes(g, 6);
480 for (
int i = 2; i < 6; ++i)
481 for (
int j = i + 1; j < 6; ++j)
490TEST(GraphUtilsProperties, AcyclicTakesALoopAsACycle)
493 auto nodes = make_nodes(g, 1);
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);
511TEST(GraphUtilsProperties, AcyclicRejectsDigraphs)
514 auto nodes = make_nodes(dg, 2);
521TEST(GraphUtilsProperties, TestForPathBasicAndRegression)
524 auto nodes = make_nodes(g, 6);
549TEST(GraphUtilsComponents, InconnectedComponentsRejectsDigraphs)
552 auto nodes = make_nodes(dg, 3);
558TEST(GraphUtilsComponents, InconnectedComponentsReturnsMappedSubgraphs)
561 auto nodes = make_nodes(g, 4);
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())
572 auto &sg = it.get_curr();
573 sizes.insert({sg.get_num_nodes(), sg.get_num_arcs()});
576 EXPECT_EQ(comp_count, 2U);
577 EXPECT_EQ(sizes, (std::multiset<std::pair<size_t, size_t>>{{3U, 2U}, {1U, 0U}}));
580 for (
auto it = g.
get_node_it(); it.has_curr(); it.next_ne())
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);
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);
595TEST(GraphUtilsComponents, BuildSubgraphCopiesReachableComponent)
598 auto nodes = make_nodes(g, 4);
610 EXPECT_EQ(visited, 3U);
619TEST(GraphUtilsSpanningTrees, DepthFirstSpanningTreeIsTreeAndMapped)
622 auto nodes = make_nodes(g, 5);
634 auto img = mapped_node<Graph>(
nodes[0]);
635 ASSERT_NE(img,
nullptr);
636 EXPECT_EQ(mapped_node<Graph>(img),
nodes[0]);
639TEST(GraphUtilsSpanningTrees, BreadthFirstSpanningTreeIsTreeAndMapped)
642 auto nodes = make_nodes(g, 5);
661TEST(GraphUtilsSpanningTrees, BuildSpanningTreeFromArcsUsesOneWayMapping)
664 auto nodes = make_nodes(g, 4);
675 arcs.append(
nullptr);
679 auto tree = build_spanning_tree<Graph>(
arcs);
680 EXPECT_EQ(tree.get_num_nodes(), 4U);
681 EXPECT_EQ(tree.get_num_arcs(), 3U);
684 for (
auto it = tree.get_node_it(); it.has_curr(); it.next_ne())
686 auto tp = it.get_curr();
688 ASSERT_NE(gp,
nullptr);
689 EXPECT_EQ(gp->get_info(), tp->get_info());
692 for (
auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
694 auto ta = it.get_curr();
696 ASSERT_NE(ga,
nullptr);
697 EXPECT_EQ(ta->get_info(), ga->get_info());
701 for (
auto it = g.
get_node_it(); it.has_curr(); it.next_ne())
709TEST(GraphUtilsCutNodes, ComputeCutNodesClearsCookiesAndFindsArticulations)
712 auto nodes = make_nodes(g, 4);
720 for (
auto it = cut_nodes.get_it(); it.has_curr(); it.next_ne())
721 infos.insert(it.get_curr()->get_info());
723 EXPECT_EQ(infos, (std::set<int>{1, 2}));
725 for (
auto it = g.
get_node_it(); it.has_curr(); it.next_ne())
730 auto dn = make_nodes(dg, 2);
731 dg.insert_arc(dn[0], dn[1], 1);
735TEST(GraphUtilsCutNodes, PaintAndExtractCutGraphOnChain)
738 auto nodes = make_nodes(g, 4);
745 EXPECT_EQ(colors_end, 3);
748 EXPECT_EQ(cut_graph.get_num_nodes(), 2U);
749 EXPECT_EQ(cut_graph.get_num_arcs(), 1U);
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());
756 EXPECT_EQ(cross_set, (std::set<Graph::Arc *>{a01, a23}));
761TEST(GraphUtilsCutNodes, PaintAndExtractBlocksOnStar)
764 auto nodes = make_nodes(g, 6);
766 for (
int i = 1; i < 6; ++i)
773 EXPECT_EQ(colors_end, 6);
776 for (
long c = 1; c < colors_end; ++c)
779 EXPECT_EQ(sg.get_num_nodes(), 1U);
780 EXPECT_EQ(sg.get_num_arcs(), 0U);
784 EXPECT_EQ(cut_graph.get_num_nodes(), 1U);
785 EXPECT_EQ(cut_graph.get_num_arcs(), 0U);
787 size_t cross_count = 0;
788 for (
auto it = cross_arcs.get_it(); it.has_curr(); it.next_ne())
790 EXPECT_EQ(cross_count, 5U);
797TEST(GraphUtilsDigraph, InvertDigraphPreservesIsolatedNodesAndMapsArcs)
800 auto nodes = make_nodes(g, 3);
801 auto a01 = g.insert_arc(
nodes[0],
nodes[1], 42);
805 EXPECT_EQ(gi.get_num_nodes(), 3U);
806 EXPECT_EQ(gi.get_num_arcs(), 1U);
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);
816 ASSERT_NE(inv,
nullptr);
817 EXPECT_EQ(inv->get_info(), 42);
819 ASSERT_NE(mapped_arc<TestDigraph>(a01),
nullptr);
820 EXPECT_EQ(mapped_arc<TestDigraph>(mapped_arc<TestDigraph>(a01)), a01);
823TEST(GraphUtilsDigraph, InvertDigraphRejectsUndirectedGraphs)
830TEST(GraphUtilsDigraph, InvertDigraphFunctorFiltersArcs)
834 bool operator()(
TestDigraph::Arc *a)
const noexcept {
return a->get_info() == 2; }
835 void set_cookie(
void *)
noexcept {}
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);
846 EXPECT_EQ(gi.get_num_nodes(), 3U);
847 EXPECT_EQ(gi.get_num_arcs(), 1U);
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);
863TEST(GraphUtilsCosts, DftDistConstants)
869TEST(GraphUtilsCosts, GetMinPathReconstructsCookieChainAndComputesCost)
872 auto nodes = make_nodes(g, 3);
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);
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]);
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);
899 EXPECT_THROW(get_min_path<WGraph>(
nodes[0],
nodes[2], path), std::domain_error);
902TEST(GraphUtilsCosts, TotalCostSumsArcsAndAccumulatorWorks)
905 auto nodes = make_nodes(g, 4);
916 EXPECT_EQ(cost.
value(), 6);
Stateful breadth-first traversal functor.
Stateful depth-first traversal functor.
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
typename BaseGraph::Arc Arc
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.
Arc Arc
The node class type.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
void for_each_node(Operation op=Operation()) const
Execute an operation on each node of path.
size_t size() const noexcept
Return the path length in nodes.
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
bool is_empty() const noexcept
Return true if the path is empty.
bool inside_graph(const GT &gr) const noexcept
Return true if this is on graph gr
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
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.
void reset_arcs() const
Reset all the arcs of graph (the control bits, the state, the counter and the cookie)
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
void reset_nodes() const
Reset all the nodes of graph (the control bits, the state, the counter and the cookie)
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
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.
#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.
#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.
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.
Main namespace for Aleph-w library functions.
Arc of graph implemented with double-linked adjacency lists.
Filtered iterator of adjacent arcs of a node.
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.