Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_exhaustive_cut_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 <limits>
49#include <random>
50#include <set>
51#include <stdexcept>
52#include <string>
53#include <vector>
54
55#include <gtest/gtest.h>
56
57#include <tpl_graph.H>
58#include <Stoer_Wagner.H>
59#include <Karger.H>
60
62#include "graph_harness.H"
63#include "graph_oracles.H"
64
65using namespace Aleph;
66using namespace graph_harness;
67namespace oracle = graph_oracles;
69
70namespace
71{
74 long long min_cut(const Spec & s, const std::vector<long long> & w)
75 {
76 if (s.n < 2)
77 return 0;
78 long long best = std::numeric_limits<long long>::max();
79 // Node 0 on the first side; the second side is not empty
80 for (unsigned long side = 0; side < (1UL << (s.n - 1)); ++side)
81 {
82 if (side == (1UL << (s.n - 1)) - 1)
83 continue;
84 auto first = [&] (int x) { return x == 0 or ((side >> (x - 1)) & 1UL) != 0; };
85 long long total = 0;
86 for (size_t i = 0; i < s.arcs.size(); ++i)
87 if (first(s.arcs[i][0]) != first(s.arcs[i][1]))
88 total += w.empty() ? 1 : w[i];
89 best = std::min(best, total);
90 }
91 return best;
92 }
93
97 template <class GT>
98 std::string cut_error(const Spec & s, const std::vector<long long> & w,
101 const DynList<typename GT::Arc *> & cut, long long value)
102 {
103 std::vector<int> side(size_t(s.n), -1);
104 for (int k = 0; k < 2; ++k)
105 for (auto it = (k == 0 ? vs : vt).get_it(); it.has_curr(); it.next_ne())
106 {
107 const int x = num(it.get_curr());
108 if (x < 0 or x >= s.n or side[size_t(x)] != -1)
109 return "a node is in both sides, or twice";
110 side[size_t(x)] = k;
111 }
112 if (std::count(side.begin(), side.end(), -1) > 0 or vs.is_empty() or vt.is_empty())
113 return "the sides do not split the nodes in two";
114 std::multiset<int> want, got;
115 long long total = 0;
116 for (size_t i = 0; i < s.arcs.size(); ++i)
117 if (side[size_t(s.arcs[i][0])] != side[size_t(s.arcs[i][1])])
118 {
119 want.insert(int(i));
120 total += w.empty() ? 1 : w[i];
121 }
122 for (auto it = cut.get_it(); it.has_curr(); it.next_ne())
123 got.insert(num(it.get_curr()));
124 if (got != want)
125 return "the arcs of the cut are not those between the sides";
126 if (total != value)
127 return "it says " + std::to_string(value) + " for a cut of " + std::to_string(total);
128 return "";
129 }
130
133 template <class F>
134 void for_each_weighting(Spec s, long long lo, long long hi, F && f)
135 {
136 s.w.assign(s.arcs.size(), lo);
137 while (true)
138 {
139 f(static_cast<const Spec &>(s));
140 size_t i = 0;
141 while (i < s.w.size() and s.w[i] == hi)
142 s.w[i++] = lo;
143 if (i == s.w.size())
144 return;
145 ++s.w[i];
146 }
147 }
148}
149
150template <class GT>
151class ExhaustiveCut : public ::testing::Test {};
152
154
155TYPED_TEST(ExhaustiveCut, StoerWagnerFindsAMinimumCut)
156{
157 using GT = TypeParam;
158 using Dist = Weight_Of<GT, long long>;
159 Check cut("Stoer_Wagner_Min_Cut");
160 Check weight("Stoer_Wagner_Min_Cut::min_cut_weight()");
161 Check few("Stoer_Wagner_Min_Cut on less than two nodes");
162
163 // Every weighting of the graphs of 3 nodes, and the weights 1 on 4
164 auto run = [&] (const Spec & s)
165 {
166 Built<GT> b(s);
167 Dist d;
168 d.weights = &s.w;
170 const long long want = min_cut(s, s.w);
171
172 if (s.n < 2)
173 {
174 few.run();
177 try
178 {
179 (void) sw(b.g, vs, vt, arcs);
180 few.fail(s, "cuts a graph of less than two nodes");
181 }
182 catch (const std::domain_error &) {}
183 if (sw.min_cut_weight(b.g) != 0)
184 few.fail(s, "min_cut_weight() is not 0");
185 return;
186 }
187
188 cut.run();
191 const long long got = sw(b.g, vs, vt, arcs);
192 if (auto e = cut_error<GT>(s, s.w, vs, vt, arcs, got); not e.empty())
193 cut.fail(s, e);
194 else if (got != want)
195 cut.fail(s, "a cut of " + std::to_string(got) + ", not " + std::to_string(want));
196
197 weight.run();
198 if (const long long w = sw.min_cut_weight(b.g); w != want)
199 weight.fail(s, std::to_string(w) + ", not " + std::to_string(want));
200 };
201 for_each_spec(domain(3, 3), false, [&] (const Spec & spec)
202 {
203 for_each_weighting(spec, 0, 2, run);
204 });
205 for_each_spec(domain(4, 3), false, [&] (const Spec & spec)
206 {
207 for_each_weighting(spec, 1, 1, run);
208 });
209
210 cut.expect();
211 weight.expect();
212 few.expect();
213}
214
215namespace
216{
219 bool karger_takes(const Spec & s)
220 {
221 return s.n >= 2 and not s.arcs.empty() and not s.has_loop()
222 and oracle::components(s) == 1;
223 }
224
225 struct Karger_Checks
226 {
227 Check rejects{"Karger_Min_Cut, what it does not take"};
228 Check plain{"Karger_Min_Cut::operator()"};
229 Check many{"Karger_Min_Cut::operator(), many iterations"};
230 Check size{"Karger_Min_Cut::compute_min_cut_size()"};
231 Check fast{"Karger_Min_Cut::fast()"};
232
233 void expect() const
234 {
235 for (const Check * c : {&rejects, &plain, &many, &size, &fast})
236 c->expect();
237 }
238 };
239
240 template <class GT>
241 void check_karger(Karger_Checks & c, const Spec & s)
242 {
243 using Node = typename GT::Node;
244 using Arc = typename GT::Arc;
245 Built<GT> b(s);
246 Karger_Min_Cut<GT> karger(seed(735));
247 const std::vector<long long> unit;
248
249 if (not karger_takes(s))
250 {
251 c.rejects.run();
252 DynList<Node *> vs, vt;
253 DynList<Arc *> cut;
254 try
255 {
256 (void) karger(b.g, vs, vt, cut);
257 c.rejects.fail(s, "cuts a graph that it does not take");
258 }
259 catch (const std::domain_error &) {}
260 return;
261 }
262
263 const long long want = min_cut(s, unit);
264
265 // Its iterations by default may miss the minimum: the cut must be one
266 c.plain.run();
267 {
268 DynList<Node *> vs, vt;
269 DynList<Arc *> cut;
270 const long long got = static_cast<long long>(karger(b.g, vs, vt, cut));
271 if (auto e = cut_error<GT>(s, unit, vs, vt, cut, got); not e.empty())
272 c.plain.fail(s, e);
273 else if (got < want)
274 c.plain.fail(s, "a cut of " + std::to_string(got) + " under the minimum");
275 }
276
277 // Each iteration finds a given minimum cut with a probability of
278 // 2 / (n (n - 1)) at least, so that 12 n^2 of them miss it with one
279 // under 1e-12 for n <= 8
280 const size_t iterations = 12 * size_t(s.n) * size_t(s.n);
281 c.many.run();
282 {
283 DynList<Node *> vs, vt;
284 DynList<Arc *> cut;
285 const long long got = static_cast<long long>(karger(b.g, vs, vt, cut, iterations));
286 if (auto e = cut_error<GT>(s, unit, vs, vt, cut, got); not e.empty())
287 c.many.fail(s, e);
288 else if (got != want)
289 c.many.fail(s, "a cut of " + std::to_string(got) + ", not " + std::to_string(want));
290 }
291
292 c.size.run();
293 if (const long long got = static_cast<long long>(karger.compute_min_cut_size(b.g, iterations)); got != want)
294 c.size.fail(s, std::to_string(got) + ", not " + std::to_string(want));
295
296 c.fast.run();
297 {
298 DynList<Node *> vs, vt;
299 DynList<Arc *> cut;
300 const long long got = static_cast<long long>(karger.fast(b.g, vs, vt, cut, 40));
301 if (auto e = cut_error<GT>(s, unit, vs, vt, cut, got); not e.empty())
302 c.fast.fail(s, e);
303 else if (got != want)
304 c.fast.fail(s, "a cut of " + std::to_string(got) + ", not " + std::to_string(want));
305 }
306 }
307}
308
309TYPED_TEST(ExhaustiveCut, KargerFindsAMinimumCut)
310{
311 Karger_Checks c;
312 for_each_spec(domain(4, 3), false, [&] (const Spec & s) { check_karger<TypeParam>(c, s); });
313 c.expect();
314}
315
316TYPED_TEST(ExhaustiveCut, KargerFindsAMinimumCutOfRandomGraphs)
317{
318 Karger_Checks c;
319 std::mt19937 rng(seed(736));
320 const int graphs = heavy() ? 1000 : 60;
321 for (int k = 0; k < graphs; ++k)
322 {
323 const int n = 5 + int(rng() % 4);
324 Spec s = random_spec(rng, n, n + int(rng() % unsigned(n)), false, false);
325 check_karger<TypeParam>(c, s);
326 }
327 c.expect();
328}
Karger's randomized min-cut algorithm.
Stoer-Wagner deterministic min-cut algorithm.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
constexpr bool is_empty() const noexcept
Definition htlist.H:434
Karger's randomized minimum cut algorithm.
Definition Karger.H:165
Stoer-Wagner deterministic minimum cut algorithm.
Weight min_cut_weight(GT &g)
Find only the minimum cut weight (faster, no partition info).
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
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.
static mt19937 rng
TYPED_TEST_SUITE(ExhaustiveCut, Undirected_Kinds)
TYPED_TEST(ExhaustiveCut, StoerWagnerFindsAMinimumCut)
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.
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Main namespace for Aleph-w library functions.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
void expect(std::ifstream &input_stream, const std::string &expected)
Expect and consume a specific string/keyword.
and
Check uniqueness with explicit hash + equality functors.
Net::Flow_Type min_cut(Net &net, DynSetTree< typename Net::Node * > &vs, DynSetTree< typename Net::Node * > &vt, DynList< typename Net::Arc * > &cuts, DynList< typename Net::Arc * > &cutt)
Compute max flow and the corresponding minimum cut.
Definition tpl_net.H:2790
::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.
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 ...
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.
int components(const Spec &s, int skip_node=-1, int skip_arc=-1)
The number of components, without the node skip_node and the arc skip_arc.
The weight of an arc, read by its number from a vector.
A graph made from a spec, with its nodes and arcs by number.
A small multigraph: its nodes are 0 .
std::vector< long long > w
std::vector< std::array< int, 2 > > arcs
bool has_loop() const noexcept
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Generic graph and digraph implementations.