Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_exhaustive_properties_test.cc
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
47#include <algorithm>
48#include <numeric>
49#include <set>
50#include <stdexcept>
51#include <string>
52#include <vector>
53
54#include <gtest/gtest.h>
55
56#include <tpl_graph.H>
57#include <Graph_Coloring.H>
58#include <hamiltonian.H>
59
61#include "graph_harness.H"
62#include "graph_oracles.H"
63
64using namespace Aleph;
65using namespace graph_harness;
66namespace oracle = graph_oracles;
68
69namespace
70{
74 std::vector<std::vector<bool>> simple_adjacency(const Spec & s, bool directed,
75 unsigned long hidden = 0)
76 {
77 std::vector<std::vector<bool>> adj(size_t(s.n), std::vector<bool>(size_t(s.n), false));
78 for (size_t i = 0; i < s.arcs.size(); ++i)
79 {
80 const int u = s.arcs[i][0], v = s.arcs[i][1];
81 if (u == v or not graph_filters::shown(hidden, int(i)))
82 continue;
83 adj[size_t(u)][size_t(v)] = true;
84 if (not directed)
85 adj[size_t(v)][size_t(u)] = true;
86 }
87 return adj;
88 }
89
92 bool colorable(const std::vector<std::vector<bool>> & adj, int k,
93 std::vector<int> & color, int x = 0)
94 {
95 const int n = int(adj.size());
96 if (x == n)
97 return true;
98 for (int c = 0; c < k; ++c)
99 {
100 bool ok = true;
101 for (int y = 0; y < x and ok; ++y)
102 ok = color[size_t(y)] != c or not (adj[size_t(x)][size_t(y)] or adj[size_t(y)][size_t(x)]);
103 if (not ok)
104 continue;
105 color[size_t(x)] = c;
106 if (colorable(adj, k, color, x + 1))
107 return true;
108 }
109 return false;
110 }
111
113 int chromatic(const std::vector<std::vector<bool>> & adj)
114 {
115 std::vector<int> color(adj.size(), -1);
116 int k = 0;
117 while (not colorable(adj, k, color))
118 ++k;
119 return k;
120 }
121
125 bool hamiltonian(const std::vector<std::vector<bool>> & adj, bool directed)
126 {
127 const int n = int(adj.size());
128 if (n < (directed ? 2 : 3))
129 return false;
130 std::vector<int> order(static_cast<size_t>(n));
131 std::iota(order.begin(), order.end(), 0);
132 do
133 {
134 bool ok = true;
135 for (int i = 0; i < n and ok; ++i)
136 ok = adj[size_t(order[size_t(i)])][size_t(order[size_t((i + 1) % n)])];
137 if (ok)
138 return true;
139 }
140 while (std::next_permutation(order.begin() + 1, order.end()));
141 return false;
142 }
143
146 int simple_degree(const std::vector<std::vector<bool>> & adj, int x, bool out = true)
147 {
148 int d = 0;
149 for (size_t y = 0; y < adj.size(); ++y)
150 d += out ? adj[size_t(x)][y] : adj[y][size_t(x)];
151 return d;
152 }
153
157 bool ore(const std::vector<std::vector<bool>> & adj, bool directed)
158 {
159 const int n = int(adj.size());
160 if (n < 3)
161 return false;
162 for (int u = 0; u < n; ++u)
163 for (int v = directed ? 0 : u + 1; v < n; ++v)
164 if (u != v and not adj[size_t(u)][size_t(v)])
165 if (simple_degree(adj, u) + simple_degree(adj, v, not directed) < n)
166 return false;
167 return true;
168 }
169
172 bool dirac(const std::vector<std::vector<bool>> & adj, bool directed)
173 {
174 const int n = int(adj.size());
175 if (n < 3)
176 return false;
177 for (int x = 0; x < n; ++x)
178 if (2 * simple_degree(adj, x) < n or (directed and 2 * simple_degree(adj, x, false) < n))
179 return false;
180 return true;
181 }
182
185 bool multigraph(const Spec & s, bool directed, unsigned long hidden = 0)
186 {
187 std::set<std::pair<int, int>> seen;
188 for (size_t i = 0; i < s.arcs.size(); ++i)
189 {
190 if (not graph_filters::shown(hidden, int(i)))
191 continue;
192 int u = s.arcs[i][0], v = s.arcs[i][1];
193 if (u == v)
194 return true;
195 if (not directed and u > v)
196 std::swap(u, v);
197 if (not seen.insert({u, v}).second)
198 return true;
199 }
200 return false;
201 }
202
203 template <class GT>
205
208 template <class GT>
209 std::string coloring_error(const Built<GT> & b, const std::vector<std::vector<bool>> & adj,
210 const Colors<GT> & colors, size_t num)
211 {
212 const int n = int(adj.size());
213 std::vector<long> c(size_t(n), -1);
214 for (int x = 0; x < n; ++x)
215 {
216 auto * p = colors.search(b.nodes[size_t(x)]);
217 if (p == nullptr)
218 return "the node " + std::to_string(x) + " has no color";
219 c[size_t(x)] = long(p->second);
220 }
221 std::set<long> used(c.begin(), c.end());
222 if (used.size() != num or (num > 0 and *used.rbegin() != long(num) - 1))
223 return "it says " + std::to_string(num) + " colors, and uses " + std::to_string(used.size());
224 for (int u = 0; u < n; ++u)
225 for (int v = 0; v < n; ++v)
226 if ((adj[size_t(u)][size_t(v)] or adj[size_t(v)][size_t(u)]) and c[size_t(u)] == c[size_t(v)])
227 return "the adjacent " + std::to_string(u) + " and " + std::to_string(v) + " share a color";
228 return "";
229 }
230
233 template <class F>
234 void for_each_test_graph(bool directed, int max_simple, F && f)
235 {
236 for_each_spec(domain(4, 3), directed, f);
237 for_each_simple_graph(1, heavy() ? max_simple + 1 : max_simple, directed, f);
238 }
239}
240
241template <class GT>
242class ExhaustiveProperties : public ::testing::Test {};
243
245
246TYPED_TEST(ExhaustiveProperties, ColoringsAreProperAndTheChromaticNumberExact)
247{
248 using GT = TypeParam;
249 const bool digraph = GT().is_digraph();
250 Check greedy("greedy_coloring()");
251 Check welsh_powell("welsh_powell_coloring()");
252 Check dsatur("dsatur_coloring()");
253 Check exact("chromatic_number()");
254 Check valid("is_valid_coloring()");
255 Check functors("Greedy_Coloring, Welsh_Powell_Coloring and DSatur_Coloring");
256
257 for_each_test_graph(digraph, digraph ? 4 : 5, [&] (const Spec & s)
258 {
259 Built<GT> b(s);
260 const bool loop = s.has_loop();
261 // The colorings take the arcs as not directed
262 const auto adj = simple_adjacency(s, false);
263
264 auto check = [&] (Check & c, auto && color)
265 {
266 c.run();
267 Colors<GT> colors;
268 try
269 {
270 const size_t num = color(colors);
271 if (loop)
272 c.fail(s, "colors a graph with a loop");
273 else if (auto e = coloring_error(b, adj, colors, num); not e.empty())
274 c.fail(s, e);
275 return num;
276 }
277 catch (const std::domain_error &)
278 {
279 if (not loop)
280 c.fail(s, "throws on a graph without loops");
281 }
282 return size_t(0);
283 };
284
285 check(greedy, [&] (Colors<GT> & c) { return greedy_coloring(b.g, c); });
286 check(welsh_powell, [&] (Colors<GT> & c) { return welsh_powell_coloring(b.g, c); });
287 check(dsatur, [&] (Colors<GT> & c) { return dsatur_coloring(b.g, c); });
288 const size_t chi = check(exact, [&] (Colors<GT> & c) { return chromatic_number(b.g, c); });
289 if (not loop and int(chi) != chromatic(adj))
290 exact.fail(s, "gives " + std::to_string(chi) + ", not " + std::to_string(chromatic(adj)));
291
292 check(functors, [&] (Colors<GT> & c) { return Greedy_Coloring<GT>()(b.g, c); });
293 check(functors, [&] (Colors<GT> & c) { return Welsh_Powell_Coloring<GT>()(b.g, c); });
294 check(functors, [&] (Colors<GT> & c) { return DSatur_Coloring<GT>()(b.g, c); });
295
296 if (loop)
297 return;
298
299 // A proper coloring is valid; giving two ends of an arc one color,
300 // or leaving a node without one, makes it invalid
301 valid.run();
302 Colors<GT> colors;
303 (void) greedy_coloring(b.g, colors);
304 if (not is_valid_coloring(b.g, colors))
305 valid.fail(s, "rejects a proper coloring");
306 for (size_t i = 0; i < s.arcs.size(); ++i)
307 {
308 Colors<GT> spoiled = colors;
309 spoiled.find(b.nodes[size_t(s.arcs[i][1])]) = spoiled.find(b.nodes[size_t(s.arcs[i][0])]);
310 if (is_valid_coloring(b.g, spoiled))
311 valid.fail(s, "accepts one color at both ends of the arc " + std::to_string(i));
312 }
313 if (s.n > 0)
314 {
315 Colors<GT> partial = colors;
316 partial.remove(b.nodes[0]);
317 if (is_valid_coloring(b.g, partial))
318 valid.fail(s, "accepts a node without a color");
319 }
320 });
321
322 greedy.expect();
323 welsh_powell.expect();
324 dsatur.expect();
325 exact.expect();
326 valid.expect();
327 functors.expect();
328}
329
330TYPED_TEST(ExhaustiveProperties, HamiltonConditionsAreThoseOfTheirTheorems)
331{
332 using GT = TypeParam;
333 using Filter = Hide_Mask<GT>;
334 const bool digraph = GT().is_digraph();
335 Check ore_simple("Test_Hamiltonian_Sufficiency, simple graphs");
336 Check dirac_simple("Test_Dirac_Condition, simple graphs");
337 Check ore_multi("Test_Hamiltonian_Sufficiency, multigraphs and hidden arcs");
338 Check dirac_multi("Test_Dirac_Condition, multigraphs and hidden arcs");
339 Check sound("a condition that holds has a Hamilton cycle");
340
341 auto run = [&] (const Spec & s, bool masks)
342 {
343 Built<GT> b(s);
344 for (unsigned long hidden = 0; hidden < (1UL << s.num_arcs()); ++hidden)
345 {
346 if (hidden != 0 and (not masks or (s.num_arcs() > 3 and s.n > 3)))
347 break; // the masks, on the graphs of 3 arcs or 3 nodes
348 const auto adj = simple_adjacency(s, digraph, hidden);
349 const bool simple = hidden == 0 and not multigraph(s, digraph);
350 const std::string at = hidden == 0 ? "" : "hiding " + std::to_string(hidden) + ": ";
351
352 const bool got_ore = Test_Hamiltonian_Sufficiency<GT, Dft_Show_Node<GT>, Filter>
353 (Dft_Show_Node<GT>(), Filter{hidden})(b.g);
354 const bool got_dirac = Test_Dirac_Condition<GT, Dft_Show_Node<GT>, Filter>
355 (Dft_Show_Node<GT>(), Filter{hidden})(b.g);
356
357 Check & o = simple ? ore_simple : ore_multi;
358 o.run();
359 if (got_ore != ore(adj, digraph))
360 o.fail(s, at + (got_ore ? "holds" : "does not hold"));
361
362 Check & d = simple ? dirac_simple : dirac_multi;
363 d.run();
364 if (got_dirac != dirac(adj, digraph))
365 d.fail(s, at + (got_dirac ? "holds" : "does not hold"));
366
367 // What the conditions claim, where they are right
368 if (simple)
369 {
370 sound.run();
371 if ((got_ore or got_dirac) and not hamiltonian(adj, digraph))
372 sound.fail(s, "a condition holds on a graph without a Hamilton cycle");
373 }
374 }
375 };
376
377 for_each_test_graph(digraph, digraph ? 4 : 5, [&] (const Spec & s) { run(s, true); });
378
379 // Loops and parallel arcs enough to reach the degrees of the conditions
380 Domain dense;
381 dense.max_nodes = 3;
382 dense.max_arcs = 6;
383 dense.directions = false;
384 dense.reversed = false;
385 for_each_spec(dense, digraph, [&] (const Spec & s) { run(s, false); });
386
387 ore_simple.expect();
388 dirac_simple.expect();
389 ore_multi.expect();
390 dirac_multi.expect();
391 sound.expect();
392}
Graph coloring algorithms and heuristics.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
size_t size_t int32_t * out
Definition ca-c-api.h:120
Functor wrapper for dsatur_coloring.
Generic key-value map implemented on top of a binary search tree.
Functor wrapper for greedy_coloring.
Tests Dirac's sufficient condition for Hamiltonian graphs.
Tests Ore's sufficient condition for Hamiltonian graphs.
Functor wrapper for welsh_powell_coloring.
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
The failures of one property over a domain.
void expect() const
Expects what the mark says, and prints the first failures.
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.
TYPED_TEST_SUITE(ExhaustiveProperties, All_Kinds)
TYPED_TEST(ExhaustiveProperties, ColoringsAreProperAndTheChromaticNumberExact)
The kinds of arc filter and of distance that the graph algorithms must accept.
Every small multigraph, on every kind of graph, for the tests.
Answers computed from a Spec of graph_harness.H, without Aleph.
size_t chromatic_number(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Computes the exact chromatic number of a small graph.
size_t greedy_coloring(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Greedy graph coloring in iteration order.
bool is_valid_coloring(const GT &g, const DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Validates a graph coloring.
size_t dsatur_coloring(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
DSatur graph coloring (saturation-degree heuristic).
size_t welsh_powell_coloring(const GT &g, DynMapTree< typename GT::Node *, size_t > &colors, SA sa=SA())
Welsh-Powell graph coloring.
Hamiltonian sufficiency testing for graphs.
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
static long & color(typename GT::Node *p)
constexpr bool shown(unsigned long hidden, int i) noexcept
Whether the arc number i is shown by the mask hidden.
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.
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.
::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.
Default filter for the graph nodes.
Definition tpl_graph.H:1228
Hides the arcs of a mask; copyable, assignable, noexcept.
A graph made from a spec, with its nodes and arcs by number.
std::vector< typename GT::Node * > nodes
Which multigraphs for_each_spec() gives.
A small multigraph: its nodes are 0 .
size_t num_arcs() const noexcept
std::vector< std::array< int, 2 > > arcs
bool has_loop() const noexcept
bool check(GT &g)
static int * k
Generic graph and digraph implementations.