Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_harness.H
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
62#ifndef ALEPH_TESTS_GRAPH_HARNESS_H
63#define ALEPH_TESTS_GRAPH_HARNESS_H
64
65#include <algorithm>
66#include <array>
67#include <cstddef>
68#include <cstdlib>
69#include <iostream>
70#include <random>
71#include <sstream>
72#include <string>
73#include <type_traits>
74#include <utility>
75#include <vector>
76
77#include <gtest/gtest.h>
78
79#include <tpl_graph.H>
80#include <tpl_sgraph.H>
81#include <tpl_agraph.H>
82
84
85#if defined(__unix__) || defined(__APPLE__)
86# include <pthread.h>
87# define ALEPH_GRAPH_HARNESS_HAS_SMALL_STACK 1
88#else
89# define ALEPH_GRAPH_HARNESS_HAS_SMALL_STACK 0
90#endif
91
92// A build with the address, thread or memory sanitizer
93#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
94# define ALEPH_GRAPH_HARNESS_SANITIZED 1
95#elif defined(__has_feature)
96# if __has_feature(address_sanitizer) || __has_feature(thread_sanitizer) || \
97 __has_feature(memory_sanitizer)
98# define ALEPH_GRAPH_HARNESS_SANITIZED 1
99# endif
100#endif
101#ifndef ALEPH_GRAPH_HARNESS_SANITIZED
102# define ALEPH_GRAPH_HARNESS_SANITIZED 0
103#endif
104
106{
110 struct Spec
111 {
112 int n = 0;
113 std::vector<std::array<int, 2>> arcs;
114 std::vector<long long> w;
115
116 [[nodiscard]] size_t num_arcs() const noexcept { return arcs.size(); }
117
118 [[nodiscard]] bool has_loop() const noexcept
119 {
120 for (const auto & a : arcs)
121 if (a[0] == a[1])
122 return true;
123 return false;
124 }
125
127 [[nodiscard]] std::string str() const
128 {
129 std::ostringstream s;
130 s << "n=" << n << " arcs={";
131 for (size_t i = 0; i < arcs.size(); ++i)
132 {
133 s << (i == 0 ? "" : " ") << arcs[i][0] << "->" << arcs[i][1];
134 if (i < w.size())
135 s << ':' << w[i];
136 }
137 s << '}';
138 return s.str();
139 }
140 };
141
143 struct Domain
144 {
145 int max_nodes = 4;
146 int max_arcs = 3;
147 bool loops = true;
148 bool parallel = true;
149 bool directions = true;
150 bool reversed = true;
151 };
152
154 enum class Mode { light, normal, heavy };
155
158 inline Mode mode()
159 {
160 const char * e = std::getenv("ALEPH_GRAPH_HARNESS");
161 const std::string m = e == nullptr ? "" : e;
162 if (m == "heavy")
163 return Mode::heavy;
164 if (m == "normal")
165 return Mode::normal;
166 if (m == "light")
167 return Mode::light;
169 }
170
172 inline bool heavy() { return mode() == Mode::heavy; }
173
176 inline Domain domain(int max_nodes, int max_arcs)
177 {
178 Domain d;
179 d.max_nodes = heavy() ? max_nodes + 1 : max_nodes;
180 d.max_arcs = heavy() ? max_arcs + 1
181 : mode() == Mode::light ? max_arcs - 1 : max_arcs;
182 return d;
183 }
184
186 inline unsigned seed(unsigned seed)
187 {
188 const char * e = std::getenv("ALEPH_GRAPH_HARNESS_SEED");
189 return e == nullptr ? seed : unsigned(std::strtoul(e, nullptr, 10));
190 }
191
193 inline size_t failures_shown()
194 {
195 const char * e = std::getenv("ALEPH_GRAPH_HARNESS_SHOW");
196 return e == nullptr ? 8 : size_t(std::strtoul(e, nullptr, 10));
197 }
198
202 template <class F>
203 size_t for_each_spec(const Domain & d, bool directed, F && f)
204 {
205 size_t count = 0;
206 for (int n = 0; n <= d.max_nodes; ++n)
207 {
208 // The places where an arc can be: one per pair of nodes, or per
209 // ordered pair in a digraph
210 std::vector<std::array<int, 2>> places;
211 for (int u = 0; u < n; ++u)
212 for (int v = directed ? 0 : u; v < n; ++v)
213 if (u != v or d.loops)
214 places.push_back({u, v});
215 const int p = int(places.size());
216
217 for (int m = 0; m <= d.max_arcs; ++m)
218 {
219 if (m > 0 and (p == 0 or (not d.parallel and m > p)))
220 break;
221
222 // Every multiset of m places (a set if no parallel arcs), as a
223 // nondecreasing (or increasing) sequence of place numbers
224 std::vector<int> pick(size_t(m), 0);
225 if (not d.parallel)
226 for (int i = 0; i < m; ++i)
227 pick[size_t(i)] = i;
228
229 while (true)
230 {
231 std::vector<int> flippable;
232 for (int i = 0; i < m; ++i)
233 if (places[size_t(pick[size_t(i)])][0] != places[size_t(pick[size_t(i)])][1])
234 flippable.push_back(i);
235 const unsigned masks =
236 directed or not d.directions ? 1U : 1U << flippable.size();
237
238 for (unsigned mask = 0; mask < masks; ++mask)
239 {
240 Spec s;
241 s.n = n;
242 for (int i = 0; i < m; ++i)
243 s.arcs.push_back(places[size_t(pick[size_t(i)])]);
244 for (size_t k = 0; k < flippable.size(); ++k)
245 if (mask & (1U << k))
246 std::swap(s.arcs[size_t(flippable[k])][0],
247 s.arcs[size_t(flippable[k])][1]);
248 f(static_cast<const Spec &>(s));
249 ++count;
250 if (d.reversed and m > 1)
251 {
252 std::reverse(s.arcs.begin(), s.arcs.end());
253 f(static_cast<const Spec &>(s));
254 ++count;
255 }
256 }
257
258 // The next multiset, in lexicographic order
259 int i = m - 1;
260 if (d.parallel)
261 {
262 while (i >= 0 and pick[size_t(i)] == p - 1)
263 --i;
264 if (i < 0)
265 break;
266 const int x = pick[size_t(i)] + 1;
267 for (int j = i; j < m; ++j)
268 pick[size_t(j)] = x;
269 }
270 else
271 {
272 while (i >= 0 and pick[size_t(i)] == p - m + i)
273 --i;
274 if (i < 0)
275 break;
276 ++pick[size_t(i)];
277 for (int j = i + 1; j < m; ++j)
278 pick[size_t(j)] = pick[size_t(j - 1)] + 1;
279 }
280 }
281 }
282 }
283 return count;
284 }
285
290 template <class F>
291 size_t for_each_simple_graph(int min_nodes, int max_nodes, bool directed, F && f)
292 {
293 size_t count = 0;
294 for (int n = min_nodes; n <= max_nodes; ++n)
295 {
296 std::vector<std::array<int, 2>> pairs;
297 for (int u = 0; u < n; ++u)
298 for (int v = directed ? 0 : u + 1; v < n; ++v)
299 if (u != v)
300 pairs.push_back({u, v});
301 for (unsigned long set = 0; set < (1UL << pairs.size()); ++set, ++count)
302 {
303 Spec s;
304 s.n = n;
305 for (size_t i = 0; i < pairs.size(); ++i)
306 if (set & (1UL << i))
307 s.arcs.push_back(pairs[i]);
308 f(static_cast<const Spec &>(s));
309 }
310 }
311 return count;
312 }
313
316 inline Spec random_spec(std::mt19937 & rng, int n, int m, bool directed,
317 bool loops = true, bool parallel = true)
318 {
319 Spec s;
320 s.n = n;
321 if (n == 0)
322 return s;
323 std::vector<std::array<int, 2>> places;
324 for (int u = 0; u < n; ++u)
325 for (int v = directed ? 0 : u; v < n; ++v)
326 if (u != v or loops)
327 places.push_back({u, v});
328 if (places.empty())
329 return s;
330 if (not parallel and size_t(m) > places.size())
331 parallel = true;
332 std::vector<bool> taken(places.size(), false);
333 std::uniform_int_distribution<size_t> pick(0, places.size() - 1);
334 while (s.arcs.size() < size_t(m))
335 {
336 const size_t k = pick(rng);
337 if (not parallel and taken[k])
338 continue;
339 taken[k] = true;
340 auto a = places[k];
341 if (not directed and rng() % 2 == 1)
342 std::swap(a[0], a[1]);
343 s.arcs.push_back(a);
344 }
345 return s;
346 }
347
349 inline void random_weights(std::mt19937 & rng, Spec & s, long long lo, long long hi)
350 {
351 std::uniform_int_distribution<long long> w(lo, hi);
352 s.w.clear();
353 for (size_t i = 0; i < s.arcs.size(); ++i)
354 s.w.push_back(w(rng));
355 }
356
358 template <class GT>
359 struct Built
360 {
362 std::vector<typename GT::Node *> nodes;
363 std::vector<typename GT::Arc *> arcs;
364
365 explicit Built(const Spec & s)
366 {
367 for (int i = 0; i < s.n; ++i)
368 nodes.push_back(g.insert_node(i));
369 for (size_t i = 0; i < s.arcs.size(); ++i)
370 arcs.push_back(g.insert_arc(nodes[size_t(s.arcs[i][0])],
371 nodes[size_t(s.arcs[i][1])], int(i)));
372 }
373
374 Built(const Built &) = delete;
375 Built & operator = (const Built &) = delete;
376 };
377
379 template <class Node>
380 [[nodiscard]] int num(Node * p) { return p->get_info(); }
381
383 template <class GT>
384 [[nodiscard]] typename GT::Node * node_of(const GT & g, int i)
385 {
386 for (typename GT::Node_Iterator it(g); it.has_curr(); it.next_ne())
387 if (it.get_curr_ne()->get_info() == i)
388 return it.get_curr_ne();
389 return nullptr;
390 }
391
394 ::testing::Types<Aleph::List_Graph<Aleph::Graph_Node<int>, Aleph::Graph_Arc<int>>,
397
400 ::testing::Types<Aleph::List_Digraph<Aleph::Graph_Node<int>, Aleph::Graph_Arc<int>>,
403
405 using All_Kinds =
406 ::testing::Types<Aleph::List_Graph<Aleph::Graph_Node<int>, Aleph::Graph_Arc<int>>,
412
415 template <class F>
416 bool run_with_small_stack(F && f, size_t kb = 256)
417 {
418#if ALEPH_GRAPH_HARNESS_HAS_SMALL_STACK
419 pthread_attr_t attr;
420 if (pthread_attr_init(&attr) != 0)
421 return false;
422 pthread_attr_setstacksize(&attr, kb * 1024);
423 using Fn = std::remove_reference_t<F>;
424 auto start = [] (void * arg) -> void *
425 {
426 (*static_cast<Fn *>(arg))();
427 return nullptr;
428 };
429 pthread_t thread;
430 const int created = pthread_create(&thread, &attr, start, &f);
431 pthread_attr_destroy(&attr);
432 if (created != 0)
433 return false;
434 return pthread_join(thread, nullptr) == 0;
435#else
436 f();
437 return true;
438#endif
439 }
440
449 class Check
450 {
451 std::string name;
453 size_t runs = 0;
454 size_t failures = 0;
455 size_t skipped = 0;
456 std::vector<std::string> first;
457
458 public:
459 explicit Check(std::string what, bool known = false)
460 : name(std::move(what)), known_failure(known) {}
461
463 void run() noexcept { ++runs; }
464
466 void skip() noexcept { ++skipped; }
467
469 void fail(const Spec & s, const std::string & what)
470 {
471 ++failures;
472 if (first.size() < failures_shown())
473 first.push_back(s.str() + ": " + what);
474 }
475
476 [[nodiscard]] size_t num_failures() const noexcept { return failures; }
477
479 void expect() const
480 {
481 std::ostringstream s;
482 for (const auto & f : first)
483 s << "\n " << f;
484 if (known_failure)
485 {
486 EXPECT_GT(failures + skipped, 0U)
487 << name << ": a known failure no longer fails; remove its mark";
488 std::cout << "[ KNOWN ] " << name << ": " << failures << " of " << runs
489 << " runs fail";
490 if (skipped > 0)
491 std::cout << ", " << skipped << " left out";
492 std::cout << s.str() << std::endl;
493 }
494 else
495 EXPECT_EQ(failures + skipped, 0U)
496 << name << ": " << failures << " of " << runs << " runs fail, "
497 << skipped << " left out" << s.str();
498 }
499 };
506 template <class F, class Filt>
507 void with_each_throw(F & f, const Filt & filt, const char * name)
508 {
510 Filter_Throws::throw_at = 0;
511 Filter_Throws::calls = 0;
512 f(filt, name);
513 const long n = Filter_Throws::calls;
514 for (long k = 1; k <= n; ++k)
515 {
516 Filter_Throws::calls = 0;
517 Filter_Throws::throw_at = k;
518 bool out = false;
519 try
520 {
521 f(filt, name);
522 }
523 catch (const graph_filters::Thrown_By_Filter &)
524 {
525 out = true;
526 }
527 Filter_Throws::throw_at = 0;
528 // Another call of f can call the filter fewer times, when the order
529 // of a search depends on the addresses of a graph that f builds:
530 // then the call k did not come, and nothing threw
531 EXPECT_TRUE(out or Filter_Throws::calls < k)
532 << name << ": what the filter threw at its call " << k << " of " << n
533 << " did not come out";
534 }
535 }
536} // namespace graph_harness
537
542#define EXPECT_THROW_OR_FILTER(statement, type) \
543 do \
544 if (::graph_filters::Filter_Throws::throw_at == 0) \
545 EXPECT_THROW(statement, type); \
546 else \
547 try \
548 { \
549 statement; \
550 } \
551 catch (const type &) \
552 { \
553 } \
554 while (false)
555
556#endif // ALEPH_TESTS_GRAPH_HARNESS_H
WeightedDigraph::Node Node
long double w
Definition btreepic.C:153
size_t size_t int32_t * out
Definition ca-c-api.h:120
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Arc for graphs implemented with simple adjacency lists.
Definition tpl_sgraph.H:197
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Graph class implemented with singly-linked adjacency lists.
Definition tpl_sgraph.H:274
The failures of one property over a domain.
void expect() const
Expects what the mark says, and prints the first failures.
size_t num_failures() const noexcept
void skip() noexcept
Counts a run left out because it would end the program.
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.
std::vector< std::string > first
Check(std::string what, bool known=false)
static mt19937 rng
The kinds of arc filter and of distance that the graph algorithms must accept.
#define ALEPH_GRAPH_HARNESS_SANITIZED
and
Check uniqueness with explicit hash + equality functors.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
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...
GT::Node * node_of(const GT &g, int i)
The node of a graph whose number is i.
::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.
size_t failures_shown()
How many failures a check prints: ALEPH_GRAPH_HARNESS_SHOW, or 8.
Mode mode()
ALEPH_GRAPH_HARNESS=light, normal or heavy, or else light in a build with a sanitizer and normal with...
::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.
size_t for_each_spec(const Domain &d, bool directed, F &&f)
Calls f(spec) with every spec of d, smallest first, and returns how many there were.
void with_each_throw(F &f, const Filt &filt, const char *name)
Calls f(filt, name), as the loop over the filters of a test does, and again for each call k of the fi...
Mode
The sizes of the domains.
Spec random_spec(std::mt19937 &rng, int n, int m, bool directed, bool loops=true, bool parallel=true)
A random spec of n nodes and m arcs, with loops and parallel arcs if asked; parallel is ignored when ...
size_t for_each_simple_graph(int min_nodes, int max_nodes, bool directed, F &&f)
Calls f(spec) with every simple graph of n nodes, for n from min_nodes to max_nodes: each set of pair...
int num(Node *p)
The number of a node of a built graph.
Domain domain(int max_nodes, int max_arcs)
The domain of max_nodes nodes and max_arcs arcs, of one more of each in heavy mode,...
bool heavy()
Whether the mode is heavy, which asks for the larger domains.
void random_weights(std::mt19937 &rng, Spec &s, long long lo, long long hi)
Gives each arc of s a weight from lo to hi.
::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.
STL namespace.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
The calls, counted from 1, of the filters whose call is not noexcept, and the one that throws Thrown_...
What a filter whose call is not noexcept throws at the call Filter_Throws::throw_at.
A graph made from a spec, with its nodes and arcs by number.
Built(const Spec &s)
std::vector< typename GT::Node * > nodes
Built(const Built &)=delete
std::vector< typename GT::Arc * > arcs
Built & operator=(const Built &)=delete
Which multigraphs for_each_spec() gives.
bool loops
arcs from a node to itself
bool parallel
several arcs between the same nodes
bool reversed
also the arcs in the reverse order
bool directions
each arc from either end (not directed)
A small multigraph: its nodes are 0 .
std::string str() const
The spec as text, ready to be written back as a test case.
std::vector< long long > w
size_t num_arcs() const noexcept
std::vector< std::array< int, 2 > > arcs
bool has_loop() const noexcept
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Array-based graph implementation.
Generic graph and digraph implementations.
Simple graph implementation with adjacency lists.