Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
ah_graph_concepts_test.cc
Go to the documentation of this file.
1// Self-containment check: must stay the first include (aleph-concepts.md ยง4.6).
2#include <ah-graph-concepts.H>
3
4#include <gtest/gtest.h>
5
6#include <stdexcept>
7#include <utility>
8
9#include <Dijkstra.H>
10#include <Johnson.H>
11#include <K_Shortest_Paths.H>
12#include <io_graph.H>
13#include <Kruskal.H>
14#include <tpl_agraph.H>
15#include <tpl_graph.H>
16#include <tpl_indexGraph.H>
17#include <tpl_maxflow.H>
18#include <tpl_net.H>
19#include <tpl_sgraph.H>
20
21// Positive/negative checks for the graph concepts of Phase 3 of
22// aleph-concepts-plan.md, and for the algorithms they now constrain.
23
24using namespace Aleph;
25
26namespace
27{
35
36 struct NotAGraph
37 {
38 using Node = int;
39 };
40
41 // A distance without Distance_Type: fine for Kruskal (it only compares
42 // dist(a) < dist(b)) but not an ArcDistance.
43 struct PlainWeight
44 {
45 int operator()(LG::Arc * a) const { return a->get_info(); }
46 };
47
48 // A filter that can be moved and not copied, which no algorithm can
49 // take: each iterator, and each frame of a search, keeps a copy of it
50 struct Move_Only_Filter
51 {
52 Move_Only_Filter() = default;
53 Move_Only_Filter(Move_Only_Filter &&) = default;
54 Move_Only_Filter(const Move_Only_Filter &) = delete;
55 bool operator()(LG::Arc *) const { return true; }
56 };
57
58 // A filter that can be copied, and neither assigned nor built by default
59 struct Reference_Filter
60 {
61 const int & limit;
62 bool operator()(LG::Arc * a) const { return a->get_info() < limit; }
63 };
64
65 struct NonArithmeticCost
66 {
67 struct Cost
68 {
69 int v = 0;
70 };
71 using Distance_Type = Cost;
72 Cost operator()(LG::Arc *) const { return {}; }
73 };
74} // namespace
75
76// --- Concepts over the library graph types ---------------------------------
77
78static_assert(AlephGraph<LG> and AlephGraph<LD> and AlephGraph<AG> and AlephGraph<AD>);
79static_assert(AlephGraph<SG> and AlephGraph<SD> and AlephGraph<NG>);
80static_assert(AlephGraph<const LG &>);
81
82// _In_Iterator walks the list of a node, which holds the arcs into the
83// node only on a graph that is not directed and on the networks: it does
84// not exist for a digraph type, whose list holds only the arcs that leave
85template <class G>
86constexpr bool has_basic_in_iterator = requires { typename _In_Iterator<G>; };
87
88static_assert(has_basic_in_iterator<LG> and has_basic_in_iterator<AG> and
89 has_basic_in_iterator<SG> and has_basic_in_iterator<NG>);
90static_assert(not has_basic_in_iterator<LD> and not has_basic_in_iterator<AD> and
91 not has_basic_in_iterator<SD>);
92static_assert(not AlephGraph<NotAGraph> and not AlephGraph<DynList<int>> and not AlephGraph<int>);
93
94static_assert(ArcFilter<Dft_Show_Arc<LG>, LG>);
95static_assert(NodeFilter<Dft_Show_Node<LG>, LG>);
96static_assert(not ArcFilter<Dft_Show_Node<LG>, LG>);
97static_assert(not NodeFilter<Dft_Show_Arc<LG>, LG>);
98// An arc filter must be copied, and need not be assigned or built by default
99static_assert(not ArcFilter<Move_Only_Filter, LG>);
100static_assert(ArcFilter<Reference_Filter, LG>);
101
102static_assert(ArcDistance<Dft_Dist<LG>, LG>);
103static_assert(not ArcDistance<PlainWeight, LG>);
104
105static_assert(FlowNetwork<NG>);
106static_assert(not FlowNetwork<LG>);
107
108// --- Constrained algorithms --------------------------------------------------
109
110template <class G>
111concept can_dijkstra = requires { typename Dijkstra_Min_Paths<G>; };
112template <class D>
113concept can_dijkstra_with = requires { typename Dijkstra_Min_Paths<LG, D>; };
114template <class D>
115concept can_kruskal_with = requires { typename Kruskal_Min_Spanning_Tree<LG, D>; };
116template <class N>
117concept can_max_flow = requires(N & net) { dinic_maximum_flow(net); };
118template <class D>
119concept can_yen = requires(const LG & g, LG::Node * n, D d) {
120 yen_k_shortest_paths<LG, D>(g, n, n, 1, d);
121};
122
124static_assert(not can_dijkstra<NotAGraph>);
126// Kruskal keeps accepting distances without Distance_Type, as it always has.
127static_assert(can_kruskal_with<PlainWeight>);
128static_assert(can_max_flow<NG> and not can_max_flow<LG>);
129// Former static_assert, now a constraint on the entry point.
131
132// --- Constrained utilities of tpl_graph.H ------------------------------------
133
134template <class G>
135concept can_copy_graph = requires(G & t, const G & s) { copy_graph(t, s); };
136template <class G>
137concept can_clear_graph = requires(G & g) { clear_graph(g); };
138template <class G>
139concept can_compare_graphs = requires(const G & g) { are_equal(g, g); };
140template <class G>
141concept can_for_each_node = requires(const G & g) { for_each_node(g, [](auto *) {}); };
142template <class SA>
143concept can_filter_arcs_with = requires(const LG & g) { for_each_arc(g, [](LG::Arc *) {}, SA()); };
144template <class G>
145concept can_out_nodes = requires(typename G::Node * p) { out_nodes<G>(p); };
146
151// Filters are checked at the call: a node filter is not an arc filter.
154
155// Graph I/O: the graph and the node/arc filters are checked when naming IO_Graph.
156template <class G>
157concept can_io_graph = requires { typename IO_Graph<G>; };
158template <class NF>
162
167
168TEST(AhGraphConceptsTest, InOutArcHelpersCompileAndAgree)
169{
170 // These helpers never compiled: they called traverse_*_arcs and
171 // for_each_*_arc without <GT>, which cannot be deduced from a Node *.
172 LG g;
173 auto * a = g.insert_node(1);
174 auto * b = g.insert_node(2);
175 g.insert_arc(a, b, 4);
176 g.insert_arc(a, b, 7);
177 auto even = [](LG::Arc * arc) { return arc->get_info() % 2 == 0; };
178
179 EXPECT_FALSE(all_out_arc<LG>(a, even));
180 EXPECT_TRUE(exists_out_arc<LG>(a, even));
181 EXPECT_EQ(search_in_arc<LG>(b, even)->get_info(), 4);
182 EXPECT_EQ(filter_in_arcs<LG>(b, even).size(), 1u);
183 EXPECT_EQ((map_out_arcs<LG, int>(a, [](LG::Arc * arc) { return arc->get_info(); }).size()), 2u);
184 EXPECT_EQ((foldl_in_arcs<LG, int>(b, 0, [](const int & s, LG::Arc * arc)
185 { return s + arc->get_info(); })), 11);
186
187 // The one-argument form used to be ambiguous (two viable overloads).
188 EXPECT_EQ(out_degree<LG>(a), 2u);
189 EXPECT_EQ(in_degree<LG>(b), 2u);
190 EXPECT_EQ(in_degree<LG>(a), 0u);
191}
192
193// On a graph that is not directed and on a network, _In_Iterator sees the
194// arcs into the node, as In_Iterator(g, p)
195TEST(AhGraphConceptsTest, BasicInIteratorSeesTheArcsIntoTheNode)
196{
197 LG g;
198 auto * a = g.insert_node(1);
199 auto * b = g.insert_node(2);
200 auto * c = g.insert_node(3);
201 g.insert_arc(a, b, 4);
202 g.insert_arc(c, b, 5);
203 g.insert_arc(b, c, 6);
204 int sum = 0, sum_of_g = 0;
205 size_t n = 0, n_of_g = 0;
206 for (_In_Iterator<LG> it(b); it.has_curr(); it.next_ne(), ++n)
207 sum += it.get_curr()->get_info();
208 for (In_Iterator<LG> it(g, b); it.has_curr(); it.next_ne(), ++n_of_g)
209 sum_of_g += it.get_curr()->get_info();
210 EXPECT_EQ(n, 2u); // the arcs whose target is b: a -> b and c -> b
211 EXPECT_EQ(sum, 9);
212 EXPECT_EQ(n_of_g, n);
213 EXPECT_EQ(sum_of_g, sum);
214
215 NG net;
216 auto * s = net.insert_node();
217 auto * m = net.insert_node();
218 auto * t = net.insert_node();
219 net.insert_arc(s, m, 2);
220 net.insert_arc(m, t, 3);
221 net.insert_arc(s, t, 4);
222 size_t into_t = 0;
223 for (_In_Iterator<NG> it(t); it.has_curr(); it.next_ne())
224 {
225 EXPECT_EQ(net.get_tgt_node(it.get_curr()), t);
226 ++into_t;
227 }
228 EXPECT_EQ(into_t, 2u);
229 EXPECT_EQ(into_t, net.get_in_degree(t));
230}
231
232TEST(AhGraphConceptsTest, ConstrainedAlgorithmsStillRun)
233{
234 LG g;
235 auto * a = g.insert_node(1);
236 auto * b = g.insert_node(2);
237 auto * c = g.insert_node(3);
238 g.insert_arc(a, b, 2);
239 g.insert_arc(b, c, 3);
240 g.insert_arc(a, c, 9);
241
242 Path<LG> path(g);
243 const auto d = Dijkstra_Min_Paths<LG>().find_min_path(g, a, c, path);
244 EXPECT_EQ(d, 5);
245
246 LG tree;
248 EXPECT_EQ(tree.get_num_arcs(), 2u);
249
250 const auto paths = yen_k_shortest_paths<LG>(g, a, c, 2);
251 EXPECT_EQ(paths.size(), 2u);
252}
253
254namespace
255{
256 // A filter whose call may throw
257 template <class GT>
258 struct May_Throw_Filter
259 {
260 bool operator()(typename GT::Arc *) const { return true; }
261 };
262
263 // A filter whose call throws while *armed
264 template <class GT>
265 struct Armed_Filter
266 {
267 const bool * armed = nullptr;
268
269 bool operator()(typename GT::Arc *) const
270 {
271 if (*armed)
272 throw std::runtime_error("Armed_Filter");
273 return true;
274 }
275 };
276} // namespace
277
278// The searches of an arc, the moves of the iterators of digraphs and the
279// steps of the depth-first searches were noexcept whatever their filter,
280// and a filter that threw ended the program: they are noexcept as the
281// filter, and what it throws comes out
282TEST(AhGraphConceptsTest, WhatCallsTheFilterIsNoexceptAsTheFilter)
283{
284 static_assert(nothrow_arc_filter_v<LG, Dft_Show_Arc<LG>>);
285 static_assert(not nothrow_arc_filter_v<LG, May_Throw_Filter<LG>>);
286 static_assert(not nothrow_arc_filter_v<LG, Reference_Filter>);
287
288 static_assert(noexcept(search_arc<LG>(std::declval<const LG &>(), nullptr, nullptr)));
289 static_assert(not noexcept(search_arc<LG, May_Throw_Filter<LG>>(std::declval<const LG &>(),
290 nullptr, nullptr)));
291 static_assert(noexcept(search_directed_arc<LD>(std::declval<const LD &>(), nullptr, nullptr)));
292 static_assert(not noexcept(search_directed_arc<LD, May_Throw_Filter<LD>>(
293 std::declval<const LD &>(), nullptr, nullptr)));
294 static_assert(noexcept(search_spanning_tree_arc<LG>(std::declval<const LG &>(), nullptr,
295 nullptr)));
296 static_assert(not noexcept(search_spanning_tree_arc<LG, May_Throw_Filter<LG>>(
297 std::declval<const LG &>(), nullptr, nullptr)));
298
299 static_assert(noexcept(std::declval<Out_Iterator<LD> &>().next_ne()));
300 static_assert(not noexcept(std::declval<Out_Iterator<LD, May_Throw_Filter<LD>> &>().next_ne()));
301 static_assert(noexcept(std::declval<In_Iterator<LG> &>().next_ne()));
302 static_assert(not noexcept(std::declval<In_Iterator<LG, May_Throw_Filter<LG>> &>().next_ne()));
303 static_assert(noexcept(std::declval<In_Iterator<AD> &>().next_ne()));
304 static_assert(not noexcept(std::declval<In_Iterator<AD, May_Throw_Filter<AD>> &>().next_ne()));
305
308 static_assert(noexcept(std::declval<Frame &>().next_arc()));
309 static_assert(noexcept(std::declval<Frame &>().template next_target<Aleph::Depth_First>()));
310 static_assert(not noexcept(std::declval<May_Throw_Frame &>().next_arc()));
311 static_assert(not noexcept(std::declval<May_Throw_Frame &>()
312 .template next_target<Aleph::Depth_First>()));
313
314 LG g;
315 auto * a = g.insert_node(1);
316 auto * b = g.insert_node(2);
317 auto * c = g.insert_node(3);
318 auto * ab = g.insert_arc(a, b, 1);
319 g.insert_arc(a, c, 2);
320
321 bool armed = false;
322 const Armed_Filter<LG> filter{&armed};
323 EXPECT_EQ((search_arc<LG, Armed_Filter<LG>>(g, a, b, filter)), ab);
324 armed = true;
325 EXPECT_THROW((search_arc<LG, Armed_Filter<LG>>(g, a, b, filter)), std::runtime_error);
326 EXPECT_THROW((search_spanning_tree_arc<LG, Armed_Filter<LG>>(g, a, b, filter)),
327 std::runtime_error);
328
329 // On the second arc of the node, after next_ne()
330 armed = false;
332 ASSERT_TRUE(it.has_curr());
333 armed = true;
334 EXPECT_THROW(it.next_ne(), std::runtime_error);
335}
Dijkstra's shortest path algorithm.
Johnson's algorithm for all-pairs shortest paths.
K-shortest path algorithms (Yen and Eppstein-style API).
Kruskal's minimum spanning tree algorithm.
C++20 concepts for the protocol shared by graph algorithms.
constexpr bool has_basic_in_iterator
WeightedDigraph::Node Node
bool has_curr() const noexcept
Return true the iterator has an current arc.
Definition tpl_graph.H:1822
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Spanning tree calculation of all shortest paths from a given node according to Dijkstra's algorithm.
Definition Dijkstra.H:117
Distance::Distance_Type find_min_path(const GT &g, typename GT::Node *start, typename GT::Node *end, Path< GT > &min_path)
Computes the shortest path between start and end by painting the graph.
Definition Dijkstra.H:536
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Arc for graphs implemented with simple adjacency lists.
Definition tpl_sgraph.H:197
Graph serialization and deserialization class.
Definition io_graph.H:344
Filtered iterator for incoming arcs of a node.
Definition tpl_graph.H:2045
Computes the minimum spanning tree of a graph using Kruskal's algorithm.
Definition Kruskal.H:94
Graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:439
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
_Graph_Node Node
The graph type.
Definition tpl_graph.H:443
Graph class implemented with singly-linked adjacency lists.
Definition tpl_sgraph.H:274
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Path on a graph.
Definition tpl_graph.H:3832
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
#define TEST(name)
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
void for_each_node(const GT &g, Op operation, SN sn=SN())
Traverse all the nodes of graph filtering some ones according to a condition and executing an operati...
Definition tpl_graph.H:1320
void for_each_arc(const GT &g, Op operation, SA sa=SA())
Traverse all the arcs of graph filtering some ones according to a condition and executing an operatio...
Definition tpl_graph.H:1339
void clear_graph(GT &g)
Clean a graph: all its nodes and arcs are removed and freed.
Definition tpl_graph.H:4776
void copy_graph(GT &gtgt, const GT &gsrc, bool cookie_map=false)
Explicit copy of graph.
Definition tpl_graph.H:4794
Graph serialization and deserialization utilities.
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
Net::Flow_Type dinic_maximum_flow(Net &net)
Compute maximum flow using Dinic's algorithm.
and
Check uniqueness with explicit hash + equality functors.
bool are_equal(const GT &g1, const GT &g2)
Fast graph comparison.
GT::Arc * search_spanning_tree_arc(const GT &g, typename GT::Node *src, typename GT::Node *tgt, SA sa=SA()) noexcept(nothrow_arc_filter_v< GT, SA >)
Helper to find the spanning tree arc between two nodes in a multigraph.
void next_ne() noexcept(noexcept(std::declval< Aleph::const_iterator_t< HeadC > & >().next_ne()) and noexcept(std::declval< ZipIterator< TailC... > & >().next_ne()))
Advance all underlying iterators (unchecked variant).
Definition ah-zip.H:252
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
The next arc of a node to look at, for a depth-first search that keeps only that in a frame.
Default arc loading functor for binary and text modes.
Definition io_graph.H:279
Default arc storage functor for binary and text modes.
Definition io_graph.H:203
Default node storage functor for binary and text modes.
Definition io_graph.H:165
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Arc of a flow network implemented with adjacency lists.
Definition tpl_net.H:160
Flow network implemented with adjacency lists.
Definition tpl_net.H:311
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Array-based graph implementation.
Generic graph and digraph implementations.
Graph indexing utilities for O(log n) node/arc lookup.
Advanced maximum flow algorithms.
Network flow graph structures.
Simple graph implementation with adjacency lists.