Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
min_mean_cycle_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
31
37# include <gtest/gtest.h>
38
39# include <cmath>
40# include <functional>
41# include <limits>
42# include <random>
43# include <tuple>
44# include <vector>
45
46# include <Min_Mean_Cycle.H>
47# include <tpl_agraph.H>
48# include <tpl_graph.H>
49
50using namespace Aleph;
51
52namespace
53{
58 using Node = Graph::Node;
59 using Arc = Graph::Arc;
60 using Edge_Def = std::tuple<size_t, size_t, long long>;
61 using Float_Edge_Def = std::tuple<size_t, size_t, double>;
63
64 template <class GT>
65 struct Built_Graph_T
66 {
67 GT g;
68 std::vector<typename GT::Node *> nodes;
69 std::vector<typename GT::Arc *> arcs;
70 };
71
72 using Built_Graph = Built_Graph_T<Graph>;
73 using Built_Float_Graph = Built_Graph_T<Float_Graph>;
74 using Built_Array_Graph = Built_Graph_T<Array_Graph>;
75
76 template <class GT, typename Weight_Type>
77 Built_Graph_T<GT>
78 build_graph_generic(const size_t n, const std::vector<std::tuple<size_t, size_t, Weight_Type>> & edges)
79 {
80 Built_Graph_T<GT> built;
81 built.nodes.reserve(n);
82 built.arcs.reserve(edges.size());
83
84 for (size_t i = 0; i < n; ++i)
85 built.nodes.push_back(built.g.insert_node(static_cast<int>(i)));
86
87 for (const auto & [u, v, w] : edges)
88 if (u < n and v < n)
89 built.arcs.push_back(built.g.insert_arc(built.nodes[u], built.nodes[v], w));
90
91 return built;
92 }
93
94 Built_Graph build_graph(const size_t n, const std::vector<Edge_Def> & edges)
95 {
96 return build_graph_generic<Graph, long long>(n, edges);
97 }
98
99 Built_Float_Graph build_float_graph(const size_t n, const std::vector<Float_Edge_Def> & edges)
100 {
101 return build_graph_generic<Float_Graph, double>(n, edges);
102 }
103
104 Built_Array_Graph build_array_graph(const size_t n, const std::vector<Edge_Def> & edges)
105 {
106 return build_graph_generic<Array_Graph, long long>(n, edges);
107 }
108
109
110 struct Exact_Oracle_Result
111 {
112 bool has_cycle = false;
113 long double minimum_mean = std::numeric_limits<long double>::infinity();
114 };
115
116
117 Exact_Oracle_Result exact_minimum_mean_cycle(const Built_Graph & built)
118 {
119 const size_t n = built.nodes.size();
120
121 Exact_Oracle_Result oracle;
122 std::vector<bool> visited(n, false);
123
124 std::function<void(size_t, size_t, long long, size_t)> dfs =
125 [&](const size_t start,
126 const size_t u,
127 const long long cost,
128 const size_t len)
129 {
130 for (Node_Arc_Iterator<Graph> it(built.nodes[u]); it.has_curr(); it.next_ne())
131 {
132 Arc * arc = it.get_current_arc_ne();
133 const size_t v = static_cast<size_t>(it.get_tgt_node()->get_info());
134 const long long w = arc->get_info();
135
136 if (v == start)
137 {
138 const size_t cyc_len = len + 1;
139 const long double mean = static_cast<long double>(cost + w)
140 / static_cast<long double>(cyc_len);
141 oracle.has_cycle = true;
142 if (mean < oracle.minimum_mean)
143 oracle.minimum_mean = mean;
144 continue;
145 }
146
147 if (visited[v])
148 continue;
149
150 visited[v] = true;
151 dfs(start, v, cost + w, len + 1);
152 visited[v] = false;
153 }
154 };
155
156 for (size_t s = 0; s < n; ++s)
157 {
158 visited[s] = true;
159 dfs(s, s, 0, 0);
160 visited[s] = false;
161 }
162
163 return oracle;
164 }
165
166
167 bool witness_cycle_is_consistent(const Graph & g, const Result & r)
168 {
169 if (r.cycle_length == 0)
170 return r.cycle_nodes.is_empty() and r.cycle_arcs.is_empty();
171
172 if (r.cycle_nodes.size() != r.cycle_length + 1)
173 return false;
174 if (r.cycle_arcs.size() != r.cycle_length)
175 return false;
176
177 auto node_it = r.cycle_nodes.get_it();
178 if (not node_it.has_curr())
179 return false;
180
181 Node * first = node_it.get_curr();
182 Node * curr = first;
183 node_it.next_ne();
184
185 for (auto arc_it = r.cycle_arcs.get_it(); arc_it.has_curr(); arc_it.next_ne())
186 {
187 if (not node_it.has_curr())
188 return false;
189
190 Arc * arc = arc_it.get_curr();
191 Node * next = node_it.get_curr();
192
193 if (g.get_src_node(arc) != curr or g.get_tgt_node(arc) != next)
194 return false;
195
196 curr = next;
197 node_it.next_ne();
198 }
199
200 return curr == first and not node_it.has_curr();
201 }
202
203
204 struct Hide_Arc
205 {
206 Arc * blocked = nullptr;
207
208 bool operator()(Arc * arc) const noexcept
209 {
210 return arc != blocked;
211 }
212 };
213} // namespace
214
215
216TEST(MinMeanCycleTest, EmptyDigraphReturnsNoCycle)
217{
218 Graph g;
219 const auto r = karp_minimum_mean_cycle(g);
220
221 EXPECT_FALSE(r.has_cycle);
222 EXPECT_EQ(r.cycle_length, 0u);
223 EXPECT_TRUE(r.cycle_nodes.is_empty());
224 EXPECT_TRUE(r.cycle_arcs.is_empty());
225}
226
227
228TEST(MinMeanCycleTest, DagReturnsNoCycle)
229{
230 const std::vector<Edge_Def> edges = {
231 {0, 1, 2}, {1, 2, 3}, {2, 3, 4}, {0, 3, 10}
232 };
233
234 auto built = build_graph(4, edges);
235 const auto r = karp_minimum_mean_cycle(built.g);
236
237 EXPECT_FALSE(r.has_cycle);
238 EXPECT_EQ(r.cycle_length, 0u);
239}
240
241
242TEST(MinMeanCycleTest, SelfLoopCanBeOptimalCycle)
243{
244 const std::vector<Edge_Def> edges = {
245 {0, 1, 8}, {1, 1, 3}, {1, 2, 7}, {2, 0, 9}
246 };
247
248 auto built = build_graph(3, edges);
249 const auto r = karp_minimum_mean_cycle(built.g);
250
251 ASSERT_TRUE(r.has_cycle);
252 EXPECT_NEAR(static_cast<double>(r.minimum_mean), 3.0, 1e-12);
253 EXPECT_EQ(r.cycle_length, 1u);
254 EXPECT_EQ(r.cycle_nodes.size(), 2u);
255 EXPECT_EQ(r.cycle_total_cost, 3);
256 EXPECT_TRUE(witness_cycle_is_consistent(built.g, r));
257}
258
259
260TEST(MinMeanCycleTest, ChoosesMinimumAmongMultipleCycles)
261{
262 const std::vector<Edge_Def> edges = {
263 {0, 1, 3}, {1, 0, 1}, // mean 2
264 {1, 2, 1}, {2, 1, 1}, // mean 1 (optimal)
265 {0, 2, 5}, {2, 0, 5}
266 };
267
268 auto built = build_graph(3, edges);
269 const auto r = karp_minimum_mean_cycle(built.g);
270
271 ASSERT_TRUE(r.has_cycle);
272 EXPECT_NEAR(static_cast<double>(r.minimum_mean), 1.0, 1e-12);
273 EXPECT_TRUE(witness_cycle_is_consistent(built.g, r));
274}
275
276
277TEST(MinMeanCycleTest, SupportsNegativeMeanCycles)
278{
279 const std::vector<Edge_Def> edges = {
280 {0, 1, -5}, {1, 2, 1}, {2, 0, 1}, // mean -1 (optimal)
281 {0, 3, 4}, {3, 0, 4}
282 };
283
284 auto built = build_graph(4, edges);
285 const auto r = karp_minimum_mean_cycle(built.g);
286
287 ASSERT_TRUE(r.has_cycle);
288 EXPECT_NEAR(static_cast<double>(r.minimum_mean), -1.0, 1e-12);
289 EXPECT_TRUE(witness_cycle_is_consistent(built.g, r));
290}
291
292
293TEST(MinMeanCycleTest, ArcFilterChangesResult)
294{
295 const std::vector<Edge_Def> edges = {
296 {0, 1, 1}, {1, 0, 1}, // mean 1 (will be blocked)
297 {2, 3, 3}, {3, 2, 3} // mean 3
298 };
299
300 auto built = build_graph(4, edges);
301
302 const auto full = karp_minimum_mean_cycle(built.g);
303 ASSERT_TRUE(full.has_cycle);
304 EXPECT_NEAR(static_cast<double>(full.minimum_mean), 1.0, 1e-12);
305
306 const Hide_Arc filter{built.arcs[0]};
307 const auto filtered = karp_minimum_mean_cycle<Graph, Dft_Dist<Graph>, Hide_Arc>(
308 built.g, Dft_Dist<Graph>(), filter);
309
310 ASSERT_TRUE(filtered.has_cycle);
311 EXPECT_NEAR(static_cast<double>(filtered.minimum_mean), 3.0, 1e-12);
312 EXPECT_TRUE(witness_cycle_is_consistent(built.g, filtered));
313}
314
315TEST(MinMeanCycleTest, AccessorIsReadOncePerAcceptedArc)
316{
317 // An accessor whose answers may change between calls (live prices, say)
318 // must be read once per arc: the table and the witness cost then come
319 // from the same values.
320 struct Counting_Dist
321 {
322 using Distance_Type = long long;
323 int * calls = nullptr;
324
325 Distance_Type operator()(Arc * arc) const
326 {
327 ++*calls;
328 return arc->get_info();
329 }
330 };
331
332 auto built = build_graph(4, {{0, 1, 1}, {1, 0, 1}, {1, 2, -4}, {2, 1, 1}, {2, 3, 7}});
333 const Hide_Arc filter{built.arcs[4]};
334
335 int calls = 0;
336 const auto full = karp_minimum_mean_cycle<Graph, Counting_Dist, Hide_Arc>(
337 built.g, Counting_Dist{&calls}, filter);
338 ASSERT_TRUE(full.has_cycle);
339 EXPECT_EQ(full.minimum_mean, -1.5L);
340 EXPECT_EQ(full.cycle_total_cost, -3);
341 EXPECT_EQ(calls, 4);
342
343 calls = 0;
344 const auto value = karp_minimum_mean_cycle_value<Graph, Counting_Dist, Hide_Arc>(
345 built.g, Counting_Dist{&calls}, filter);
346 EXPECT_EQ(value.minimum_mean, full.minimum_mean);
347 EXPECT_EQ(calls, 4);
348}
349
350TEST(MinMeanCycleTest, WitnessMeansAreComparedExactly)
351{
352 // The choice among the simple cycles of Karp's walk. In exact arithmetic
353 // they all have the minimum mean, so no graph seen so far depends on it;
354 // it is checked here directly.
356 EXPECT_TRUE(mean_less(-3LL, 2, -2LL, 2));
357 EXPECT_FALSE(mean_less(-3LL, 3, -2LL, 2)); // -1 against -1
358 EXPECT_TRUE(mean_less(-5LL, 3, -3LL, 2)); // -5/3 < -3/2
359 EXPECT_FALSE(mean_less(-3LL, 2, -5LL, 3));
360 EXPECT_TRUE(mean_less(1LL, 3, 1LL, 2));
361 EXPECT_FALSE(mean_less(2LL, 6, 1LL, 3)); // equal, not smaller
362 EXPECT_TRUE(mean_less(-1.5, 1, -1.0, 1));
363# if ALEPH_KARP_INT128
364 // Means 1 apart where long double, whatever its precision (53 bits on
365 // Apple Silicon and MSVC, 64 on x86, 113 on AArch64 Linux), cannot tell
366 // them apart: its unit in the last place there is 4.
367 using min_mean_cycle_detail::karp_int128_t;
368 constexpr int shift = std::numeric_limits<long double>::digits + 2;
369 static_assert(shift <= 124, "3 * 2^shift must fit a 128-bit integer");
370 const karp_int128_t big = static_cast<karp_int128_t>(1) << shift;
371 ASSERT_EQ(static_cast<long double>(big - 1), static_cast<long double>(big));
372 EXPECT_TRUE(mean_less(3 * big - 3, 3, big, 1));
373 EXPECT_FALSE(mean_less(big, 1, 3 * big - 3, 3));
374# endif
375}
376
377TEST(MinMeanCycleTest, TableBytesAreTheBytesArrayReserves)
378{
379 // Audit 2026-10-02, C3: the bytes of Karp's tables, which the memory limit
380 // of Howard's fallback compares. (n + 1) * n entries, rounded up by Array
381 // to a power of two; a sum, plus a predecessor position with the witness.
382 using namespace min_mean_cycle_detail;
383 size_t bytes = 1;
384 ASSERT_TRUE((karp_table_bytes<true, long long>(0, Karp_Sums::Long_Long, bytes)));
385 EXPECT_EQ(bytes, 0u);
386 ASSERT_TRUE((karp_table_bytes<true, long long>(3, Karp_Sums::Long_Long, bytes)));
387 EXPECT_EQ(bytes, 16u * (8 + 8)); // 12 entries -> 16
388 ASSERT_TRUE((karp_table_bytes<false, long long>(3, Karp_Sums::Long_Long, bytes)));
389 EXPECT_EQ(bytes, 16u * 8);
390 ASSERT_TRUE((karp_table_bytes<true, long long>(1000, Karp_Sums::Long_Long, bytes)));
391 EXPECT_EQ(bytes, (size_t{1} << 20) * 16); // 1001000 entries -> 2^20
392 ASSERT_TRUE((karp_table_bytes<true, double>(15, Karp_Sums::Cost_Type_Checked, bytes)));
393 EXPECT_EQ(bytes, 256u * (sizeof(double) + 8)); // 240 entries -> 256
394 ASSERT_TRUE((karp_table_bytes<false, long double>(15, Karp_Sums::Cost_Type_Checked, bytes)));
395 EXPECT_EQ(bytes, 256u * sizeof(long double));
396# if ALEPH_KARP_INT128
397 ASSERT_TRUE((karp_table_bytes<true, long long>(3, Karp_Sums::Int128, bytes)));
398 EXPECT_EQ(bytes, 16u * (16 + 8));
399# endif
400
401 // Counts that do not fit a size_t: the entries themselves, or the bytes
402 // of the power of two that holds them.
403 EXPECT_FALSE((karp_table_bytes<true, long long>(std::numeric_limits<size_t>::max() / 2,
404 Karp_Sums::Long_Long, bytes)));
405 EXPECT_FALSE((karp_table_bytes<false, long long>(size_t{1} << (std::numeric_limits<size_t>::digits / 2 - 1),
406 Karp_Sums::Long_Long, bytes)));
407
408 // How the sums are kept: long long while n * max|w| stays below LLONG_MAX.
409 using In = Incoming_Arc<Graph, long long>;
410 const auto lists = [](const long long w)
411 {
412 Array<Array<In>> incoming;
413 incoming.append(Array<In>());
414 incoming.append(Array<In>());
415 incoming(0).append(In{1, nullptr, w});
416 incoming(1).append(In{0, nullptr, -w});
417 return incoming;
418 };
419 EXPECT_EQ(karp_sums(lists(5)), Karp_Sums::Long_Long);
420 EXPECT_EQ(karp_sums(lists(std::numeric_limits<long long>::max() / 2 - 1)), Karp_Sums::Long_Long);
421# if ALEPH_KARP_INT128
422 EXPECT_EQ(karp_sums(lists(std::numeric_limits<long long>::max() / 2 + 1)), Karp_Sums::Int128);
423# else
424 EXPECT_EQ(karp_sums(lists(std::numeric_limits<long long>::max() / 2 + 1)), Karp_Sums::Long_Long_Checked);
425# endif
427 floating.append(Array<Incoming_Arc<Float_Graph, double>>());
428 EXPECT_EQ(karp_sums(floating), Karp_Sums::Cost_Type_Checked);
429}
430
431TEST(MinMeanCycleTest, WitnessIsASimpleCycle)
432{
433 // Audit 2026-10-02, C4. The witness used to be a closed piece of Karp's
434 // walk, chosen by its rounded mean: with floating-point weights rounding
435 // often favoured a piece that went around a cycle twice (a third of these
436 // graphs). Now it is always a simple cycle, of the reported cost.
437 const auto check = [](const auto & g, const auto & r, const bool exact) -> ::testing::AssertionResult
438 {
439 using GT = std::decay_t<decltype(g)>;
440 if (r.cycle_length == 0 or r.cycle_nodes.size() != r.cycle_length + 1
441 or r.cycle_arcs.size() != r.cycle_length)
442 return ::testing::AssertionFailure() << "sizes";
443 std::vector<typename GT::Node *> nodes;
444 for (auto it = r.cycle_nodes.get_it(); it.has_curr(); it.next_ne())
445 nodes.push_back(it.get_curr());
446 if (nodes.front() != nodes.back())
447 return ::testing::AssertionFailure() << "not closed";
448 for (size_t i = 0; i + 1 < nodes.size(); ++i)
449 for (size_t j = i + 1; j + 1 < nodes.size(); ++j)
450 if (nodes[i] == nodes[j])
451 return ::testing::AssertionFailure() << "node repeated: not a simple cycle";
452 long double sum = 0;
453 size_t i = 0;
454 for (auto it = r.cycle_arcs.get_it(); it.has_curr(); it.next_ne(), ++i)
455 {
456 auto * arc = it.get_curr();
457 if (g.get_src_node(arc) != nodes[i] or g.get_tgt_node(arc) != nodes[i + 1])
458 return ::testing::AssertionFailure() << "arcs do not follow the nodes";
459 sum += static_cast<long double>(arc->get_info());
460 }
461 const long double cost = static_cast<long double>(r.cycle_total_cost);
462 const long double mean = cost / static_cast<long double>(r.cycle_length);
463 const long double tol = exact ? 0.0L : 1e-9L * (1.0L + std::fabs(sum));
464 if (std::fabs(sum - cost) > tol)
465 return ::testing::AssertionFailure() << "cost " << cost << " but arcs add up to " << sum;
466 if (std::fabs(mean - r.minimum_mean) > (exact ? 0.0L : 1e-9L * (1.0L + std::fabs(mean))))
467 return ::testing::AssertionFailure() << "witness mean " << mean << ", reported " << r.minimum_mean;
468 return ::testing::AssertionSuccess();
469 };
470
471 std::mt19937_64 rng(20261002);
472 for (size_t trial = 0; trial < 3000; ++trial)
473 {
474 const size_t n = 1 + rng() % 9;
475 const size_t m = rng() % (3 * n + 1);
476 std::vector<Float_Edge_Def> fedges;
477 std::vector<Edge_Def> iedges;
478 for (size_t i = 0; i < m; ++i)
479 {
480 const size_t u = rng() % n;
481 const size_t v = rng() % n;
482 const double unit = std::uniform_real_distribution<double>(-1.0, 1.0)(rng);
483 const int exponent = static_cast<int>(rng() % 40) - 20;
484 const long long w = static_cast<long long>(rng() % 41) - 20;
485 fedges.emplace_back(u, v, std::ldexp(unit, exponent));
486 iedges.emplace_back(u, v, w);
487 }
488
489 auto fg = build_float_graph(n, fedges);
490 const auto fr = karp_minimum_mean_cycle(fg.g);
491 if (fr.has_cycle)
492 ASSERT_TRUE(check(fg.g, fr, false)) << "double, trial=" << trial;
493
494 auto ig = build_graph(n, iedges);
495 const auto ir = karp_minimum_mean_cycle(ig.g);
496 if (ir.has_cycle)
497 ASSERT_TRUE(check(ig.g, ir, true)) << "long long, trial=" << trial;
498 }
499}
500
501TEST(MinMeanCycleTest, FloatingWeightsAndValueOnlyApiWork)
502{
503 const std::vector<Float_Edge_Def> edges = {
504 {0, 1, 0.5}, {1, 0, 1.0}, // mean 0.75
505 {1, 2, 2.5}, {2, 1, 2.5} // mean 2.5
506 };
507
508 auto built = build_float_graph(3, edges);
509 const auto full = karp_minimum_mean_cycle(built.g);
510 const auto value = karp_minimum_mean_cycle_value(built.g);
511 const auto alias_value = minimum_mean_cycle_value(built.g);
512 const auto value_functor = Karp_Minimum_Mean_Cycle_Value<Float_Graph>()(built.g);
513
514 ASSERT_TRUE(full.has_cycle);
515 EXPECT_NEAR(static_cast<double>(full.minimum_mean), 0.75, 1e-12);
516
517 ASSERT_TRUE(value.has_cycle);
518 EXPECT_NEAR(static_cast<double>(value.minimum_mean), 0.75, 1e-12);
519
520 ASSERT_TRUE(alias_value.has_cycle);
521 EXPECT_NEAR(static_cast<double>(alias_value.minimum_mean), 0.75, 1e-12);
522
523 ASSERT_TRUE(value_functor.has_cycle);
524 EXPECT_NEAR(static_cast<double>(value_functor.minimum_mean), 0.75, 1e-12);
525}
526
527TEST(MinMeanCycleTest, NonFiniteFloatingWeightsThrowDomainError)
528{
529 Float_Graph inf_graph;
530 auto * i0 = inf_graph.insert_node(0);
531 auto * i1 = inf_graph.insert_node(1);
532 inf_graph.insert_arc(i0, i1, std::numeric_limits<double>::infinity());
533 inf_graph.insert_arc(i1, i0, 1.0);
534
535 EXPECT_THROW((karp_minimum_mean_cycle(inf_graph)), std::domain_error);
536 EXPECT_THROW((karp_minimum_mean_cycle_value(inf_graph)), std::domain_error);
537
538 Float_Graph nan_graph;
539 auto * n0 = nan_graph.insert_node(0);
540 auto * n1 = nan_graph.insert_node(1);
541 nan_graph.insert_arc(n0, n1, std::numeric_limits<double>::quiet_NaN());
542 nan_graph.insert_arc(n1, n0, 1.0);
543
544 EXPECT_THROW((karp_minimum_mean_cycle(nan_graph)), std::domain_error);
545 EXPECT_THROW((karp_minimum_mean_cycle_value(nan_graph)), std::domain_error);
546}
547
548TEST(MinMeanCycleTest, IntegerOverflowInAccumulationThrows)
549{
550 // The only cycle costs LLONG_MAX + 1. With 128-bit sums (audit 2026-10-02,
551 // C6) the table holds it: the mean, 2^62, comes out, and only the witness,
552 // whose cost long long cannot hold, throws. Without them every sum is a
553 // checked long long and both throw.
554 const std::vector<Edge_Def> edges = {
555 {0, 1, std::numeric_limits<long long>::max()},
556 {1, 0, 1}
557 };
558
559 auto built = build_graph(2, edges);
560 EXPECT_THROW((karp_minimum_mean_cycle(built.g)), std::overflow_error);
561# if ALEPH_KARP_INT128
562 const auto value = karp_minimum_mean_cycle_value(built.g);
563 ASSERT_TRUE(value.has_cycle);
564 EXPECT_EQ(value.minimum_mean, 0x1p62L);
565# else
566 EXPECT_THROW((karp_minimum_mean_cycle_value(built.g)), std::overflow_error);
567# endif
568}
569
570TEST(MinMeanCycleTest, SumsBeyondTheCostTypeAreExact)
571{
572 // Audit 2026-10-02, C6. A loop of cost LLONG_MAX used to read as the
573 // "unreachable" sentinel and was ignored. And the 2-cycle 0 -> 1 -> 0
574 // costs 2^63, which a long long table could not add up, although the
575 // cheaper loop at 0 is the answer.
576 const long long max = std::numeric_limits<long long>::max();
577 const long long q = 1LL << 62;
578
579 auto loop = build_graph(1, {{0, 0, max}});
580 auto pair = build_graph(3, {{0, 1, q}, {1, 0, q}, {0, 0, q - 1}, {2, 0, -q}, {2, 1, -q}});
581# if ALEPH_KARP_INT128
582 const auto r = karp_minimum_mean_cycle(loop.g);
583 ASSERT_TRUE(r.has_cycle);
584 EXPECT_EQ(r.minimum_mean, static_cast<long double>(max));
585 EXPECT_EQ(r.cycle_total_cost, max);
586 EXPECT_EQ(r.cycle_length, 1u);
587
588 const auto p = karp_minimum_mean_cycle(pair.g);
589 ASSERT_TRUE(p.has_cycle);
590 EXPECT_EQ(p.minimum_mean, static_cast<long double>(q - 1));
591 EXPECT_EQ(p.cycle_total_cost, q - 1);
592 EXPECT_EQ(p.cycle_length, 1u);
593 EXPECT_EQ(karp_minimum_mean_cycle_value(pair.g).minimum_mean, p.minimum_mean);
594# else
595 EXPECT_FALSE(karp_minimum_mean_cycle(loop.g).has_cycle); // the known limit without them
596# endif
597
598 // Narrower integers are added up in long long on every platform.
600 const int imax = std::numeric_limits<int>::max();
601 auto narrow = build_graph_generic<Int_Graph, int>(3, {{0, 1, imax}, {1, 0, imax}, {0, 0, imax - 1}});
602 const auto i = karp_minimum_mean_cycle(narrow.g);
603 ASSERT_TRUE(i.has_cycle);
604 EXPECT_EQ(i.cycle_total_cost, imax - 1);
605 EXPECT_EQ(i.minimum_mean, static_cast<long double>(imax - 1));
606}
607
608TEST(MinMeanCycleTest, BoundedSumsMayReachOneBelowTheSentinel)
609{
610 // Independent audit of stage C, C1. With n * max|w| = 2^63 - 2 the table
611 // stays in long long, and D_2 reaches LLONG_MAX - 1: only LLONG_MAX may
612 // mark an unreachable state.
613 const long long w = (1LL << 62) - 1;
614 auto b = build_graph(2, {{0, 1, w}, {1, 0, w}});
615 const auto r = karp_minimum_mean_cycle(b.g);
616 ASSERT_TRUE(r.has_cycle);
617 EXPECT_EQ(r.minimum_mean, static_cast<long double>(w));
618 EXPECT_EQ(r.cycle_total_cost, 2 * w);
620}
621
622TEST(MinMeanCycleTest, AMinimumMeanCycleWhoseCostFitsIsPreferred)
623{
624 // Independent audit of stage C, T1. The 2-cycle and the loop both have
625 // mean -124, but only the loop's cost fits an int8_t. Karp's vertex 0
626 // ends a walk with just the 2-cycle; another vertex of the same mean
627 // gives the loop, instead of an overflow_error. Equal means are told
628 // apart only where they are compared exactly (128-bit integers).
630# if ALEPH_KARP_INT128
631 auto b = build_graph_generic<Small_Graph, int8_t>(3, {{0, 1, -124}, {1, 0, -124}, {2, 2, -124}});
632 const auto r = karp_minimum_mean_cycle(b.g);
633 ASSERT_TRUE(r.has_cycle);
634 EXPECT_EQ(r.minimum_mean, -124.0L);
635 EXPECT_EQ(r.cycle_length, 1u);
636 EXPECT_EQ(r.cycle_total_cost, -124);
637 EXPECT_EQ(r.witness_node, b.nodes[2]);
638# endif
639
640 // When no minimum-mean cycle fits, the witness cannot be reported.
641 auto alone = build_graph_generic<Small_Graph, int8_t>(2, {{0, 1, -124}, {1, 0, -124}});
642 EXPECT_THROW(karp_minimum_mean_cycle(alone.g), std::overflow_error);
643 EXPECT_EQ(karp_minimum_mean_cycle_value(alone.g).minimum_mean, -124.0L);
644}
645
646# if ALEPH_KARP_INT128
647TEST(MinMeanCycleTest, TheVertexIsChosenWithExactMeans)
648{
649 // Independent audit of stage C, K1. The 5-cycle has mean 2^62 + 1/5 and
650 // the loop 2^62; with 64 bits of long double, or 53, both round to 2^62.
651 // The vertex used to be chosen by those rounded means, the first one on
652 // the 5-cycle, whose cost 5 * 2^62 + 1 does not fit a long long.
653 const long long a = 1LL << 62;
654 auto b = build_graph(6, {{0, 1, a}, {1, 2, a}, {2, 3, a}, {3, 4, a}, {4, 0, a + 1}, {5, 5, a}});
655 const auto r = karp_minimum_mean_cycle(b.g);
656 ASSERT_TRUE(r.has_cycle);
657 EXPECT_EQ(r.minimum_mean, static_cast<long double>(a));
658 EXPECT_EQ(r.cycle_length, 1u);
659 EXPECT_EQ(r.cycle_total_cost, a);
660 EXPECT_EQ(karp_minimum_mean_cycle_value(b.g).minimum_mean, r.minimum_mean);
661}
662# endif
663
664TEST(MinMeanCycleTest, SupportsArrayDigraphBackend)
665{
666 const std::vector<Edge_Def> edges = {
667 {0, 1, 3}, {1, 2, 3}, {2, 0, 0}, // mean 2
668 {0, 3, 5}, {3, 0, 5}
669 };
670
671 auto built = build_array_graph(4, edges);
672 const auto r = karp_minimum_mean_cycle(built.g);
673 const auto v = karp_minimum_mean_cycle_value(built.g);
674
675 ASSERT_TRUE(r.has_cycle);
676 EXPECT_NEAR(static_cast<double>(r.minimum_mean), 2.0, 1e-12);
677 ASSERT_TRUE(v.has_cycle);
678 EXPECT_NEAR(static_cast<double>(v.minimum_mean), 2.0, 1e-12);
679}
680
681
682TEST(MinMeanCycleTest, FunctorAndAliasMatchFreeFunction)
683{
684 const std::vector<Edge_Def> edges = {
685 {0, 1, 2}, {1, 0, 2},
686 {1, 2, 1}, {2, 1, 1}
687 };
688
689 auto built = build_graph(3, edges);
690
691 const auto free_result = karp_minimum_mean_cycle(built.g);
692 const auto alias_result = minimum_mean_cycle(built.g);
693 const auto functor_result = Karp_Minimum_Mean_Cycle<Graph>()(built.g);
694
695 ASSERT_EQ(free_result.has_cycle, alias_result.has_cycle);
696 ASSERT_EQ(free_result.has_cycle, functor_result.has_cycle);
697 if (free_result.has_cycle)
698 {
699 EXPECT_NEAR(static_cast<double>(free_result.minimum_mean),
700 static_cast<double>(alias_result.minimum_mean),
701 1e-12);
702 EXPECT_NEAR(static_cast<double>(free_result.minimum_mean),
703 static_cast<double>(functor_result.minimum_mean),
704 1e-12);
705 }
706}
707
708
709TEST(MinMeanCycleTest, UndirectedGraphThrowsDomainError)
710{
711 UGraph g;
712 auto * n0 = g.insert_node(0);
713 auto * n1 = g.insert_node(1);
714 g.insert_arc(n0, n1, 1);
715
716 EXPECT_THROW((karp_minimum_mean_cycle(g)), std::domain_error);
717}
718
719
720TEST(MinMeanCycleTest, RandomSmallGraphsMatchExactOracle)
721{
722 std::mt19937_64 rng(0xDA7A5EEDULL);
723 std::uniform_int_distribution<int> n_dist(2, 7);
724 std::bernoulli_distribution has_edge(0.36);
725 std::uniform_int_distribution<int> weight_dist(-9, 13);
726
727 for (size_t trial = 0; trial < 90; ++trial)
728 {
729 const size_t n = static_cast<size_t>(n_dist(rng));
730 std::vector<Edge_Def> edges;
731 for (size_t u = 0; u < n; ++u)
732 for (size_t v = 0; v < n; ++v)
733 {
734 if (u == v)
735 {
736 if (std::bernoulli_distribution(0.12)(rng))
737 edges.emplace_back(u, v, static_cast<long long>(weight_dist(rng)));
738 continue;
739 }
740
741 if (has_edge(rng))
742 edges.emplace_back(u, v, static_cast<long long>(weight_dist(rng)));
743 }
744
745 auto built = build_graph(n, edges);
746 const auto exact = exact_minimum_mean_cycle(built);
747 const auto got = karp_minimum_mean_cycle(built.g);
748 const auto value_only = karp_minimum_mean_cycle_value(built.g);
749
750 ASSERT_EQ(got.has_cycle, exact.has_cycle) << "trial=" << trial;
751 ASSERT_EQ(value_only.has_cycle, exact.has_cycle) << "trial=" << trial;
752 if (not got.has_cycle)
753 continue;
754
755 EXPECT_NEAR(static_cast<double>(got.minimum_mean),
756 static_cast<double>(exact.minimum_mean),
757 1e-10)
758 << "trial=" << trial;
759 EXPECT_NEAR(static_cast<double>(value_only.minimum_mean),
760 static_cast<double>(exact.minimum_mean),
761 1e-10)
762 << "trial=" << trial;
763
764 EXPECT_GT(got.cycle_length, 0u) << "trial=" << trial;
765 EXPECT_TRUE(witness_cycle_is_consistent(built.g, got)) << "trial=" << trial;
766
767 const long double witness_mean = static_cast<long double>(got.cycle_total_cost)
768 / static_cast<long double>(got.cycle_length);
769 EXPECT_GE(witness_mean + 1e-12L, got.minimum_mean) << "trial=" << trial;
770 }
771}
Minimum mean cycle in directed graphs (Karp 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
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Functor wrapper for value-only minimum mean cycle.
Functor wrapper for Karp minimum mean cycle.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Node Node
The graph type.
Definition tpl_graph.H:443
Arc Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
static mt19937 rng
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
Min_Mean_Cycle_Value_Result minimum_mean_cycle_value(const GT &g, Distance distance=Distance(), SA sa=SA())
Alias for karp_minimum_mean_cycle_value().
Min_Mean_Cycle_Result< GT, typename Distance::Distance_Type > minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA())
Alias for karp_minimum_mean_cycle().
Min_Mean_Cycle_Value_Result karp_minimum_mean_cycle_value(const GT &g, Distance distance=Distance(), SA sa=SA())
Compute only the minimum mean value (without witness walk).
Min_Mean_Cycle_Result< GT, typename Distance::Distance_Type > karp_minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA())
Compute minimum mean cycle by Karp's algorithm.
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
bool mean_less(const Acc c1, const size_t l1, const Acc c2, const size_t l2)
Whether the mean c1 / l1 is smaller than c2 / l2.
Main namespace for Aleph-w library functions.
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
and
Check uniqueness with explicit hash + equality functors.
auto mean(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute the arithmetic mean.
Definition stat_utils.H:190
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
Definition ahPair.H:89
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
std::tuple< size_t, size_t, long long > Edge_Def
Built_Graph_T< GT > build_graph_generic(const size_t n, const std::vector< std::tuple< size_t, size_t, Weight_Type > > &edges)
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
List_Digraph< Graph_Node< int >, Graph_Arc< double > > Float_Graph
bool has_cycle(const Spec &s)
Whether the multigraph, not directed, has a cycle.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Result of minimum mean cycle computation.
bool has_cycle
True if at least one directed cycle exists.
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
Gsl_Compatible_Rng r
Array-based graph implementation.
Generic graph and digraph implementations.