Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
howard_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
38// Self-containment check: must stay the first include.
40
41# include <gtest/gtest.h>
42
43# include <cmath>
44# include <functional>
45# include <limits>
46# include <random>
47# include <set>
48# include <thread>
49# include <tuple>
50# include <vector>
51
52# include <Min_Mean_Cycle.H>
53# include <tpl_agraph.H>
54# include <tpl_graph.H>
55
57
58using namespace Aleph;
59using namespace Negative_Cycles_Test_Support;
60
61namespace
62{
64
68 template <typename Acc>
69 struct Basic_Mean
70 {
71 bool exists = false;
72 Acc total = 0;
73 long long length = 1;
74
76 bool less_than(const Acc t, const long long l) const
77 {
78 return total * l < t * length;
79 }
80 };
81
82 using Mean = Basic_Mean<long long>;
83
85 template <typename Acc = long long, class Built>
86 Basic_Mean<Acc> exact_minimum_mean(const Built & built)
87 {
88 using GT = decltype(built.g);
89 const size_t n = built.nodes.size();
90 std::vector<bool> visited(n, false);
91 Basic_Mean<Acc> best;
92
93 std::function<void(size_t, size_t, Acc, long long)> dfs =
94 [&](const size_t start, const size_t u, const Acc total, const long long len)
95 {
96 for (Node_Arc_Iterator<std::remove_cv_t<std::remove_reference_t<GT>>> it(built.nodes[u]);
97 it.has_curr(); it.next_ne())
98 {
99 const size_t v = static_cast<size_t>(it.get_tgt_node()->get_info());
100 const Acc w = it.get_current_arc_ne()->get_info();
101 if (v == start)
102 {
103 if (not best.exists or (total + w) * best.length < best.total * (len + 1))
104 best = Basic_Mean<Acc>{true, total + w, len + 1};
105 continue;
106 }
107 if (v < start or visited[v])
108 continue;
109 visited[v] = true;
110 dfs(start, v, total + w, len + 1);
111 visited[v] = false;
112 }
113 };
114
115 for (size_t s = 0; s < n; ++s)
116 {
117 visited[s] = true;
118 dfs(s, s, 0, 0);
119 visited[s] = false;
120 }
121 return best;
122 }
123
124 // The witness must be a simple cycle of consecutive graph arcs whose total,
125 // length and mean agree with the result. The agreement is checked with a
126 // plain sum, which adversarial weights defeat; tests built on them pass
127 // `check_values = false` and compare the cost with its known exact value.
128 template <class GT, typename Cost>
130 const bool check_values = true)
131 {
132 if (not r.has_cycle)
133 return r.cycle_length == 0 and r.cycle_nodes.is_empty() and r.cycle_arcs.is_empty();
134
135 if (r.cycle_length == 0 or r.cycle_nodes.size() != r.cycle_length + 1
136 or r.cycle_arcs.size() != r.cycle_length)
137 return false;
138
139 std::set<typename GT::Node *> seen;
140 auto node_it = r.cycle_nodes.get_it();
141 typename GT::Node * first = node_it.get_curr();
142 typename GT::Node * curr = first;
143 node_it.next_ne();
144
145 long double sum = 0.0L;
146 for (auto arc_it = r.cycle_arcs.get_it(); arc_it.has_curr(); arc_it.next_ne())
147 {
148 typename GT::Arc * arc = arc_it.get_curr();
149 if (not node_it.has_curr() or g.get_src_node(arc) != curr
150 or g.get_tgt_node(arc) != node_it.get_curr() or not seen.insert(curr).second)
151 return false;
152 sum += static_cast<long double>(arc->get_info());
153 curr = node_it.get_curr();
154 node_it.next_ne();
155 }
156
157 if (curr != first or node_it.has_curr() or r.witness_node != first)
158 return false;
159 if (not check_values)
160 return true;
161 const long double mean = sum / static_cast<long double>(r.cycle_length);
162 if constexpr (std::is_floating_point_v<Cost>)
163 return std::fabs(mean - r.minimum_mean) <= 1e-9L * (1.0L + std::fabs(mean))
164 and std::fabs(sum - static_cast<long double>(r.cycle_total_cost))
165 <= 1e-9L * (1.0L + std::fabs(sum));
166 else
167 return mean == r.minimum_mean and sum == static_cast<long double>(r.cycle_total_cost);
168 }
169} // namespace
170
171
172// ---------------------------------------------------------------------------
173// The cases of min_mean_cycle_test.cc, run against Howard.
174// ---------------------------------------------------------------------------
175
177{
178 Graph g;
179 const auto r = howard_minimum_mean_cycle(g);
180 EXPECT_FALSE(r.has_cycle);
181 EXPECT_FALSE(r.used_karp);
182 EXPECT_EQ(r.cycle_length, 0u);
184}
185
186
188{
189 auto built = build_graph(4, {{0, 1, -5}, {1, 2, -5}, {0, 2, -9}, {2, 3, -1}});
190 const auto r = howard_minimum_mean_cycle(built.g);
191 EXPECT_FALSE(r.has_cycle);
193}
194
195
197{
198 auto built = build_graph(3, {{0, 0, -2}, {0, 1, 4}, {1, 2, 4}, {2, 0, 4}});
199 const auto r = howard_minimum_mean_cycle(built.g);
200 ASSERT_TRUE(r.has_cycle);
201 EXPECT_EQ(r.cycle_length, 1u);
202 EXPECT_EQ(r.cycle_total_cost, -2);
203 EXPECT_EQ(r.minimum_mean, -2.0L);
204 EXPECT_EQ(r.witness_node, built.nodes[0]);
205 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Exact);
207}
208
209
211{
212 // Means: 0-1-0 is 1.5, 2-3-4-2 is 1, 5-6-5 is 2.
213 auto built = build_graph(7, {{0, 1, 1}, {1, 0, 2},
214 {2, 3, 1}, {3, 4, 1}, {4, 2, 1},
215 {5, 6, 2}, {6, 5, 2}, {1, 2, 9}});
216 const auto r = howard_minimum_mean_cycle(built.g);
217 ASSERT_TRUE(r.has_cycle);
218 EXPECT_EQ(r.minimum_mean, 1.0L);
219 EXPECT_EQ(r.cycle_length, 3u);
221}
222
223
225{
226 auto built = build_graph(3, {{0, 1, 2}, {1, 2, -7}, {2, 0, 1}});
227 const auto r = howard_minimum_mean_cycle(built.g);
228 ASSERT_TRUE(r.has_cycle);
229 EXPECT_EQ(r.cycle_total_cost, -4);
230 EXPECT_EQ(r.cycle_length, 3u);
231 EXPECT_NEAR(static_cast<double>(r.minimum_mean), -4.0 / 3.0, 1e-15);
233}
234
235
237{
238 auto built = build_graph(4, {{0, 1, -4}, {1, 0, 1}, {2, 3, -2}, {3, 2, -2}});
239
240 const auto full = howard_minimum_mean_cycle(built.g);
241 ASSERT_TRUE(full.has_cycle);
242 EXPECT_EQ(full.minimum_mean, -2.0L);
243
244 const Hide_Arc filter{built.arcs[2]}; // 2 -> 3: no cycle remains there
246 built.g, Dft_Dist<Graph>(), filter);
247 ASSERT_TRUE(filtered.has_cycle);
248 EXPECT_EQ(filtered.minimum_mean, -1.5L);
249 EXPECT_EQ(filtered.cycle_length, 2u);
250}
251
252
254{
256 3, {{0, 1, 0.5}, {1, 2, -1.25}, {2, 0, 0.25}, {2, 2, 0.1}});
257
258 const auto r = howard_minimum_mean_cycle(built.g);
259 ASSERT_TRUE(r.has_cycle);
260 EXPECT_NEAR(static_cast<double>(r.minimum_mean), -0.5 / 3.0, 1e-12);
261 EXPECT_NEAR(r.cycle_total_cost, -0.5, 1e-12);
262 EXPECT_EQ(r.cycle_length, 3u);
263 // Found with long double arithmetic, then verified with the weights scaled
264 // to 64-bit integers: exact.
265 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Exact);
267
268 const auto value = howard_minimum_mean_cycle_value(built.g);
269 ASSERT_TRUE(value.has_cycle);
270 EXPECT_EQ(value.minimum_mean, r.minimum_mean);
271}
272
273
275{
277 auto * a = inf_graph.insert_node(0);
278 auto * b = inf_graph.insert_node(1);
279 inf_graph.insert_arc(a, b, std::numeric_limits<double>::infinity());
280 inf_graph.insert_arc(b, a, 1.0);
281 EXPECT_THROW((howard_minimum_mean_cycle(inf_graph)), std::domain_error);
282
284 auto * c = nan_graph.insert_node(0);
285 nan_graph.insert_arc(c, c, std::numeric_limits<double>::quiet_NaN());
286 EXPECT_THROW((howard_minimum_mean_cycle(nan_graph)), std::domain_error);
287
288 // A non-finite weight the filter hides is ignored.
291 EXPECT_FALSE(r.has_cycle);
292}
293
294
296{
297 // The only cycle costs max + 1: its total cannot be represented, Howard
298 // hands the problem to Karp, and Karp's answer (an overflow) comes out.
299 const long long M = std::numeric_limits<long long>::max();
300 auto built = build_graph(2, {{0, 1, M - 1}, {1, 0, 2}});
301 EXPECT_THROW((karp_minimum_mean_cycle(built.g)), std::overflow_error);
302 EXPECT_THROW((howard_minimum_mean_cycle(built.g)), std::overflow_error);
303}
304
305
307{
309 3, {{0, 1, 3}, {1, 2, -5}, {2, 0, 1}, {1, 1, 4}});
310 const auto r = howard_minimum_mean_cycle(built.g);
311 ASSERT_TRUE(r.has_cycle);
312 EXPECT_EQ(r.cycle_total_cost, -1);
313 EXPECT_EQ(r.cycle_length, 3u);
315}
316
317
319{
320 UGraph undirected;
321 auto * u0 = undirected.insert_node(0);
322 auto * u1 = undirected.insert_node(1);
323 undirected.insert_arc(u0, u1, 1);
324 EXPECT_THROW((howard_minimum_mean_cycle(undirected)), std::domain_error);
325 EXPECT_THROW((howard_minimum_mean_cycle_value(undirected)), std::domain_error);
326}
327
328
329// ---------------------------------------------------------------------------
330// What differs from Karp.
331// ---------------------------------------------------------------------------
332
333namespace
334{
335 // Accepts the result of either algorithm: they share their fields.
336 template <class Result>
337 long double mean_of(const Result & r)
338 {
339 return r.has_cycle ? r.minimum_mean : std::numeric_limits<long double>::infinity();
340 }
341}
342
343
345{
346 auto built = build_graph(3, {{0, 1, 2}, {1, 2, -7}, {2, 0, 1}});
347 const auto howard = howard_minimum_mean_cycle(built.g);
348 const auto karp = karp_minimum_mean_cycle(built.g);
349 EXPECT_EQ(mean_of(howard), mean_of(karp));
350
351 const Min_Mean_Cycle_Result<Graph, long long> as_karp = howard; // slicing keeps the fields
352 EXPECT_EQ(as_karp.minimum_mean, howard.minimum_mean);
353 EXPECT_EQ(as_karp.cycle_total_cost, howard.cycle_total_cost);
354}
355
356
358{
359 // A negative triangle among isolated vertices: Karp's witness is an n-step
360 // closed walk that goes around the triangle many times.
361 std::vector<Edge_Def> edges = {{0, 1, -1}, {1, 2, -1}, {2, 0, -1}};
362 auto built = build_graph(60, edges);
363
364 const auto howard = howard_minimum_mean_cycle(built.g);
365 ASSERT_TRUE(howard.has_cycle);
366 EXPECT_EQ(howard.cycle_length, 3u);
367 EXPECT_EQ(howard.cycle_total_cost, -3);
368 EXPECT_EQ(howard.minimum_mean, -1.0L);
369 EXPECT_TRUE(witness_is_simple_cycle(built.g, howard));
370
371 const auto karp = karp_minimum_mean_cycle(built.g);
372 ASSERT_TRUE(karp.has_cycle);
373 EXPECT_EQ(karp.minimum_mean, howard.minimum_mean); // same value, possibly another witness
374}
375
376
378{
379 // numeric_limits::max() is not reserved as "unreachable" (Karp reserves it).
380 const long long M = std::numeric_limits<long long>::max();
381 auto built = build_graph(1, {{0, 0, M}});
382 const auto r = howard_minimum_mean_cycle(built.g);
383 ASSERT_TRUE(r.has_cycle);
384 EXPECT_EQ(r.cycle_total_cost, M);
385 EXPECT_EQ(r.cycle_length, 1u);
386 EXPECT_FALSE(r.used_karp);
387
388 const long long lowest = std::numeric_limits<long long>::min();
389 auto low = build_graph(1, {{0, 0, lowest}});
390 const auto r_low = howard_minimum_mean_cycle(low.g);
391 ASSERT_TRUE(r_low.has_cycle);
392 EXPECT_EQ(r_low.cycle_total_cost, lowest);
393 EXPECT_EQ(r_low.cycle_length, 1u);
394 EXPECT_FALSE(r_low.used_karp);
395}
396
397
399{
400 // int costs near the limits of the type: Karp adds up to n of them in its
401 // table, which overflowed int even where the cycle is a loop; Howard needs
402 // only the cycle it reports. Since the audit's C6 Karp adds them up in
403 // long long and answers too.
406 4, {{2, 2, 653666155}, {2, 2, 585777688}, {1, 3, 641209630}, {3, 0, 491799673},
407 {3, 3, -1900485882}});
408
409 const auto r = howard_minimum_mean_cycle(built.g);
410 ASSERT_TRUE(r.has_cycle);
411 EXPECT_EQ(r.cycle_total_cost, -1900485882);
412 EXPECT_EQ(r.cycle_length, 1u);
413 EXPECT_FALSE(r.used_karp);
414
415 const auto karp = karp_minimum_mean_cycle(built.g);
416 ASSERT_TRUE(karp.has_cycle);
417 EXPECT_EQ(karp.cycle_total_cost, -1900485882);
418 EXPECT_EQ(karp.minimum_mean, r.minimum_mean);
419
420 // An acyclic graph with large weights has no cycle: no overflow either.
422 4, {{0, 1, 2000000000}, {1, 2, 2000000000}, {2, 3, -2000000000}});
423 EXPECT_FALSE(howard_minimum_mean_cycle(dag.g).has_cycle);
424}
425
426
428{
429 auto built = build_graph(3, {{0, 1, 1}, {1, 2, -3}, {2, 0, 1}, {0, 2, 7}, {2, 2, 4}});
430 int dist_calls = 0;
431 int filter_calls = 0;
432
434 built.g, Counting_Dist{&dist_calls}, Counting_Filter{&filter_calls, built.arcs[3]});
435
436 ASSERT_TRUE(r.has_cycle);
437 EXPECT_FALSE(r.used_karp);
440}
441
442
444{
445 auto built = build_graph(4, {{0, 1, 1}, {1, 2, -3}, {2, 0, 1}, {2, 3, -2}, {3, 2, 1}});
447 planted.plant(built);
448 ASSERT_TRUE(planted.intact(built));
449
450 const auto r = howard_minimum_mean_cycle(built.g);
451 ASSERT_TRUE(r.has_cycle);
452 EXPECT_TRUE(planted.intact(built));
453}
454
455
456// ---------------------------------------------------------------------------
457// Agreement with Karp and with an exhaustive oracle.
458// ---------------------------------------------------------------------------
459
461{
462 std::mt19937_64 rng(0x4F5741524431ULL);
463 std::uniform_int_distribution<int> n_dist(1, 7);
464 std::bernoulli_distribution has_edge(0.4);
465 std::bernoulli_distribution has_loop(0.12);
466 std::uniform_int_distribution<int> weight_dist(-6, 9);
467
468 size_t with_cycle = 0;
469 for (size_t trial = 0; trial < 400; ++trial)
470 {
471 const size_t n = static_cast<size_t>(n_dist(rng));
472 std::vector<Edge_Def> edges;
473 for (size_t u = 0; u < n; ++u)
474 for (size_t v = 0; v < n; ++v)
475 if ((u == v) ? has_loop(rng) : has_edge(rng))
476 {
477 edges.emplace_back(u, v, static_cast<long long>(weight_dist(rng)));
478 if (rng() % 7 == 0) // a parallel arc
479 edges.emplace_back(u, v, static_cast<long long>(weight_dist(rng)));
480 }
481
482 auto built = build_graph(n, edges);
483 const Mean oracle = exact_minimum_mean(built);
484 const auto howard = howard_minimum_mean_cycle(built.g);
485 const auto karp = karp_minimum_mean_cycle(built.g);
486
487 ASSERT_EQ(howard.has_cycle, oracle.exists) << "trial=" << trial;
488 ASSERT_EQ(howard.has_cycle, karp.has_cycle) << "trial=" << trial;
489 ASSERT_FALSE(howard.used_karp) << "trial=" << trial;
490 ASSERT_TRUE(witness_is_simple_cycle(built.g, howard)) << "trial=" << trial;
491 if (not howard.has_cycle)
492 continue;
493
494 ++with_cycle;
495 // Exactly the oracle's rational mean: total / length cross-multiplied.
496 ASSERT_EQ(howard.cycle_total_cost * oracle.length, oracle.total * static_cast<long long>(howard.cycle_length))
497 << "trial=" << trial;
498 ASSERT_EQ(howard.minimum_mean, karp.minimum_mean) << "trial=" << trial;
499 }
500 EXPECT_GT(with_cycle, 150u);
501}
502
503
505{
506 std::mt19937_64 rng(0xB16B00B5ULL);
507 std::uniform_int_distribution<int> n_dist(8, 60);
508 std::uniform_int_distribution<int> weight_dist(-40, 90);
509
510 for (size_t trial = 0; trial < 120; ++trial)
511 {
512 const size_t n = static_cast<size_t>(n_dist(rng));
513 const size_t m = n + static_cast<size_t>(rng() % (4 * n));
514 std::vector<Edge_Def> edges;
515 for (size_t i = 0; i < m; ++i)
516 {
517 const size_t u = rng() % n;
518 const size_t v = rng() % n;
519 edges.emplace_back(u, v, static_cast<long long>(weight_dist(rng)));
520 }
521
522 auto built = build_graph(n, edges);
523 const auto howard = howard_minimum_mean_cycle(built.g);
524 const auto karp = karp_minimum_mean_cycle(built.g);
525
526 ASSERT_EQ(howard.has_cycle, karp.has_cycle) << "trial=" << trial;
527 ASSERT_FALSE(howard.used_karp) << "trial=" << trial;
528 if (not howard.has_cycle)
529 continue;
530 ASSERT_EQ(howard.minimum_mean, karp.minimum_mean) << "trial=" << trial;
531 ASSERT_TRUE(witness_is_simple_cycle(built.g, howard)) << "trial=" << trial;
532 }
533}
534
535
537{
538 std::mt19937_64 rng(0xF10A7ULL);
539 std::uniform_int_distribution<int> n_dist(2, 40);
540 std::uniform_real_distribution<double> weight_dist(-1.0, 2.0);
541
542 for (size_t trial = 0; trial < 150; ++trial)
543 {
544 const size_t n = static_cast<size_t>(n_dist(rng));
545 const size_t m = n + static_cast<size_t>(rng() % (3 * n));
546 std::vector<std::tuple<size_t, size_t, double>> edges;
547 for (size_t i = 0; i < m; ++i)
548 {
549 const size_t u = rng() % n;
550 const size_t v = rng() % n;
551 edges.emplace_back(u, v, weight_dist(rng));
552 }
553
554 auto built = build_graph_generic<Float_Graph, double>(n, edges);
555 const auto howard = howard_minimum_mean_cycle(built.g);
556 const auto karp = karp_minimum_mean_cycle(built.g);
557
558 ASSERT_EQ(howard.has_cycle, karp.has_cycle) << "trial=" << trial;
559 ASSERT_FALSE(howard.used_karp) << "trial=" << trial; // no oscillation from rounding noise
560 if (not howard.has_cycle)
561 continue;
562 ASSERT_NEAR(static_cast<double>(howard.minimum_mean), static_cast<double>(karp.minimum_mean), 1e-12)
563 << "trial=" << trial;
564 ASSERT_TRUE(witness_is_simple_cycle(built.g, howard)) << "trial=" << trial;
565 }
566}
567
568
569// The tolerance of the floating-point bias comparison has two ways to be
570// wrong, and each has its own test: too large and the iteration stops before
571// the policy is optimal; too small and rounding noise looks like an
572// improvement, so the policy oscillates until Karp takes over.
574{
575 std::mt19937_64 rng(0x5A11A11ULL);
576 std::uniform_real_distribution<double> weight(-0.001, 0.003);
577
578 for (size_t trial = 0; trial < 1500; ++trial)
579 {
580 const size_t n = 3 + rng() % 28;
581 const size_t m = n + rng() % (3 * n);
582 std::vector<std::tuple<size_t, size_t, double>> edges;
583 for (size_t i = 0; i < m; ++i)
584 {
585 const size_t u = rng() % n;
586 const size_t v = rng() % n;
587 edges.emplace_back(u, v, weight(rng));
588 }
589
590 auto built = build_graph_generic<Float_Graph, double>(n, edges);
591 const auto howard = howard_minimum_mean_cycle(built.g);
592 const auto karp = karp_minimum_mean_cycle(built.g);
593
594 ASSERT_EQ(howard.has_cycle, karp.has_cycle) << "trial=" << trial;
595 if (not howard.has_cycle)
596 continue;
597 ASSERT_NEAR(static_cast<double>(howard.minimum_mean), static_cast<double>(karp.minimum_mean), 1e-12)
598 << "trial=" << trial;
599 }
600}
601
602
604{
605 // 0.1, 0.2, 0.3... are not representable: cycles of equal mean differ by
606 // rounding noise.
607 std::mt19937_64 rng(0xDEC1A1ULL);
608 const double menu[] = {0.1, 0.2, 0.3, 0.7, -0.1, 0.4};
609
610 for (size_t trial = 0; trial < 12000; ++trial)
611 {
612 const size_t n = 3 + rng() % 12;
613 const size_t m = n + rng() % (3 * n);
614 std::vector<std::tuple<size_t, size_t, double>> edges;
615 for (size_t i = 0; i < m; ++i)
616 {
617 const size_t u = rng() % n;
618 const size_t v = rng() % n;
619 edges.emplace_back(u, v, menu[rng() % 6]);
620 }
621
622 auto built = build_graph_generic<Float_Graph, double>(n, edges);
623 const auto howard = howard_minimum_mean_cycle(built.g);
624 ASSERT_FALSE(howard.used_karp) << "trial=" << trial;
625 const auto karp = karp_minimum_mean_cycle(built.g);
626 ASSERT_EQ(howard.has_cycle, karp.has_cycle) << "trial=" << trial;
627 if (howard.has_cycle)
628 ASSERT_NEAR(static_cast<double>(howard.minimum_mean), static_cast<double>(karp.minimum_mean), 1e-12)
629 << "trial=" << trial;
630 }
631}
632
633
635{
636 // Two strongly connected components joined one way, plus an isolated node.
637 // Means: {0,1,2} is 3 / 3 = 1, {3,4} is (-1 + 1) / 2 = 0, the bridge is on no cycle.
638 auto built = build_graph(6, {{0, 1, 1}, {1, 2, 1}, {2, 0, 1},
639 {3, 4, -1}, {4, 3, 1},
640 {2, 3, -100}});
641 const auto r = howard_minimum_mean_cycle(built.g);
642 ASSERT_TRUE(r.has_cycle);
643 EXPECT_EQ(r.minimum_mean, 0.0L);
644 EXPECT_EQ(r.cycle_length, 2u);
646}
647
648
649// ---------------------------------------------------------------------------
650// The two ways out to Karp, and the oscillation that used to need them.
651// ---------------------------------------------------------------------------
652
654{
655 // With the reference of the biases taken as the first node of a cycle that
656 // the walk met, the second phase of the improvement switched node 0 back and
657 // forth between two components of equal mean forever (72 iterations, then
658 // Karp). The reference is now the smallest node of the cycle.
659 auto built = build_graph(8, {{5, 0, -4}, {4, 7, 7}, {0, 1, 2}, {1, 2, 3}, {0, 7, 3}, {7, 2, 1},
660 {7, 5, 4}, {3, 7, 1}, {1, 1, 0}, {7, 3, -5}, {2, 0, 5}, {1, 2, 5},
661 {7, 0, -3}, {7, 7, 4}, {0, 4, 2}, {5, 5, 5}, {1, 0, -3}, {7, 2, 7},
662 {4, 4, -2}, {0, 4, 6}, {0, 3, 3}});
663
664 const auto r = howard_minimum_mean_cycle(built.g);
665 ASSERT_TRUE(r.has_cycle);
666 EXPECT_FALSE(r.used_karp);
667 EXPECT_LT(r.iterations, 20u);
668 EXPECT_EQ(r.minimum_mean, karp_minimum_mean_cycle(built.g).minimum_mean);
669 EXPECT_EQ(r.minimum_mean, -2.0L);
670}
671
672
674{
675 // The cycle 2 -> 3 -> 4 -> 1 -> 2 has the weights 0, -1e20, 1e20, 3. Added
676 // from node 1 their `long double` sum is 0 (the 3 is lost next to 1e20) and
677 // added from node 2 it is 3, so while the total was summed from wherever the
678 // walk entered the cycle, its mean was 0 or 3/4 from one iteration to the
679 // next. Against the cycle 2 -> 3 -> 0 -> 2 (mean 1/3) it kept winning and
680 // losing: 70 iterations, then Karp. The total is now summed from the smallest
681 // node of the cycle.
682 //
683 // The weights span more than the 64 bits of a `long double`, so the value is
684 // the minimum only up to that rounding (see the file documentation); what is
685 // checked is that the iteration converges by itself.
687 5, {{2, 3, 0.0}, {3, 4, -1e20}, {3, 0, 1.0}, {0, 2, 0.0}, {1, 2, 3.0}, {4, 1, 1e20}});
688
689 const auto r = howard_minimum_mean_cycle(built.g);
690 ASSERT_TRUE(r.has_cycle);
691 EXPECT_FALSE(r.used_karp);
692 EXPECT_LT(r.iterations, 5u);
694}
695
696
698{
699 // A graph whose initial policy (cheapest arc out of each node) is not optimal.
700 auto built = build_graph(4, {{0, 1, 1}, {1, 0, 1}, {0, 2, 2}, {2, 3, -9}, {3, 0, 2}, {1, 2, 5}});
701
702 const auto normal = howard_minimum_mean_cycle(built.g);
703 ASSERT_TRUE(normal.has_cycle);
704 EXPECT_FALSE(normal.used_karp);
705 ASSERT_GT(normal.iterations, 0u); // the initial policy had to be improved
706
707 // With no iterations allowed Karp answers, and the value is the same.
708 const auto forced = howard_detail::minimum_mean_cycle<Graph, Dft_Dist<Graph>, Dft_Show_Arc<Graph>>(
709 built.g, Dft_Dist<Graph>(), Dft_Show_Arc<Graph>(), 0);
710 ASSERT_TRUE(forced.has_cycle);
711 EXPECT_TRUE(forced.used_karp);
712 EXPECT_EQ(forced.minimum_mean, normal.minimum_mean);
713 EXPECT_EQ(normal.numeric_quality, Cycle_Numeric_Quality::Exact);
714 EXPECT_EQ(forced.numeric_quality, Cycle_Numeric_Quality::Rounded); // Karp compares long doubles
715
716 // A limit as large as the work needed does not fall back.
717 const auto enough = howard_detail::minimum_mean_cycle<Graph, Dft_Dist<Graph>, Dft_Show_Arc<Graph>>(
718 built.g, Dft_Dist<Graph>(), Dft_Show_Arc<Graph>(), normal.iterations);
719 EXPECT_FALSE(enough.used_karp);
720}
721
722
724{
725 // The cycle 0 -> 1 -> 2 -> 0 costs 2e17 (mean 2e17 / 3), and every partial
726 // sum stays within 3.1e18, so Karp copes. Howard scales the bias by the
727 // denominator of the mean, 3, and 3 * (-3.1e18) leaves the range of long
728 // long: Karp's answer must come out.
729 const long long big = 3100000000000000000LL;
730 auto built = build_graph(3, {{0, 1, big}, {1, 2, -big}, {2, 0, 200000000000000000LL}});
731
732 const auto howard = howard_minimum_mean_cycle(built.g);
733 const auto karp = karp_minimum_mean_cycle(built.g);
734 ASSERT_TRUE(howard.has_cycle);
735 EXPECT_TRUE(howard.used_karp);
736 EXPECT_EQ(howard.minimum_mean, karp.minimum_mean);
737 EXPECT_EQ(howard.minimum_mean, 200000000000000000.0L / 3.0L);
738}
739
740
741// Audit 2026-10-02, H5 and stage C1: the fallback runs Karp on the snapshot
742// Howard already took, one strongly connected component at a time.
743
745{
746 // The graph of IterationLimitFallsBackToKarp; its last arc is hidden.
747 auto built = build_graph(4, {{0, 1, 1}, {1, 0, 1}, {0, 2, 2}, {2, 3, -9}, {3, 0, 2}, {1, 2, 5}});
748
749 int dist_calls = 0;
750 int filter_calls = 0;
751 const auto r = howard_detail::minimum_mean_cycle<Graph, Counting_Dist, Counting_Filter>(
752 built.g, Counting_Dist{&dist_calls}, Counting_Filter{&filter_calls, built.arcs[5]}, 0);
753
754 ASSERT_TRUE(r.has_cycle);
755 EXPECT_TRUE(r.used_karp);
756 EXPECT_EQ(r.minimum_mean, -5.0L / 3.0L);
758 EXPECT_EQ(filter_calls, 6); // once per arc
759 EXPECT_EQ(dist_calls, 5); // once per accepted arc, fallback included
760}
761
762
763// Audit 2026-10-02, C2: the value-only function builds no witness and its
764// fallback keeps no table of predecessors, and still answers the same.
765
767{
769 const auto same = [](const auto & full, const auto & value) -> ::testing::AssertionResult
770 {
771 if (full.has_cycle != value.has_cycle)
772 return ::testing::AssertionFailure() << "has_cycle";
773 if (not full.has_cycle)
774 return ::testing::AssertionSuccess();
775 if (full.minimum_mean != value.minimum_mean
776 or std::signbit(full.minimum_mean) != std::signbit(value.minimum_mean))
777 return ::testing::AssertionFailure()
778 << "minimum_mean " << full.minimum_mean << " against " << value.minimum_mean;
779 if (full.iterations != value.iterations or full.used_karp != value.used_karp
780 or full.fallback_reason != value.fallback_reason
781 or full.numeric_quality != value.numeric_quality)
782 return ::testing::AssertionFailure() << "how the answer was obtained";
783 if (full.used_karp != (full.fallback_reason != Howard_Fallback_Reason::None))
784 return ::testing::AssertionFailure() << "used_karp disagrees with fallback_reason";
785 if (not value.cycle_nodes.is_empty() or not value.cycle_arcs.is_empty()
786 or value.witness_node != nullptr)
787 return ::testing::AssertionFailure() << "the value-only result built a witness";
788 return ::testing::AssertionSuccess();
789 };
790
791 std::mt19937_64 rng(0xC2);
792 size_t fallbacks = 0;
793 size_t compared = 0;
794 for (size_t trial = 0; trial < 3000; ++trial)
795 {
796 const size_t n = 2 + rng() % 8;
797 const size_t m = n + rng() % (2 * n);
798 std::vector<Edge_Def> iedges;
799 std::vector<Edge_Def> bedges; // weights of about 2^61: Karp's sums need 128 bits
800 std::vector<std::tuple<size_t, size_t, double>> fedges;
801 for (size_t i = 0; i < m; ++i)
802 {
803 const size_t u = rng() % n;
804 const size_t v = rng() % n;
805 const long long w = static_cast<long long>(rng() % 41) - 20;
806 const long long big = (1LL << 60) + static_cast<long long>(rng() % (1ULL << 61));
807 const double unit = std::uniform_real_distribution<double>(-1.0, 1.0)(rng);
808 const int exponent = static_cast<int>(rng() % 40) - 20;
809 iedges.emplace_back(u, v, w);
810 bedges.emplace_back(u, v, rng() % 2 ? big : -big);
811 fedges.emplace_back(u, v, std::ldexp(unit, exponent));
812 }
813
814 auto ib = build_graph(n, iedges);
815 auto bb = build_graph(n, bedges);
817 for (const size_t limit : {howard_detail::default_iterations, size_t{0}})
818 {
819 using D = Dft_Dist<Graph>;
820 using S = Dft_Show_Arc<Graph>;
821 for (auto * built : {&ib, &bb})
822 {
823 Full_Int full;
824 try { full = howard_detail::minimum_mean_cycle<Graph, D, S>(built->g, D(), S(), limit); }
825 catch (const std::overflow_error &) { continue; } // only the full one can refuse
826 const auto value = howard_detail::minimum_mean_cycle<Graph, D, S, false>(
827 built->g, D(), S(), limit);
828 ASSERT_TRUE(same(full, value)) << "long long, trial=" << trial << " limit=" << limit;
829 ++compared;
830 fallbacks += full.used_karp;
831 }
832
835 const auto ffull = howard_detail::minimum_mean_cycle<Float_Graph, FD, FS>(fb.g, FD(), FS(), limit);
836 const auto fvalue =
837 howard_detail::minimum_mean_cycle<Float_Graph, FD, FS, false>(fb.g, FD(), FS(), limit);
838 ASSERT_TRUE(same(ffull, fvalue)) << "double, trial=" << trial << " limit=" << limit;
839 ++compared;
840 fallbacks += ffull.used_karp;
841 }
842
843 // The public function, with the default limit.
844 const auto full = howard_minimum_mean_cycle(fb.g);
846 ASSERT_EQ(full.has_cycle, value.has_cycle) << "trial=" << trial;
847 if (full.has_cycle)
848 ASSERT_EQ(full.minimum_mean, value.minimum_mean) << "trial=" << trial;
849 }
850 EXPECT_GT(compared, 15000u);
851 EXPECT_GT(fallbacks, 1000u); // limit 0 sends most of them to Karp
852}
853
854
856{
857 auto built = build_graph(4, {{0, 1, 1}, {1, 0, 1}, {0, 2, 2}, {2, 3, -9}, {3, 0, 2}, {1, 2, 5}});
858
859 for (const size_t limit : {howard_detail::default_iterations, size_t{0}})
860 {
861 int dist_calls = 0;
862 int filter_calls = 0;
863 const auto r = howard_detail::minimum_mean_cycle<Graph, Counting_Dist, Counting_Filter, false>(
864 built.g, Counting_Dist{&dist_calls}, Counting_Filter{&filter_calls, built.arcs[5]}, limit);
865 ASSERT_TRUE(r.has_cycle);
866 EXPECT_EQ(r.used_karp, limit == 0);
867 EXPECT_EQ(r.minimum_mean, -5.0L / 3.0L);
868 EXPECT_EQ(filter_calls, 6) << "limit=" << limit;
869 EXPECT_EQ(dist_calls, 5) << "limit=" << limit;
870 }
871}
872
873
875{
876 // The only cycle costs LLONG_MAX + 1, which long long cannot report. The
877 // function with the witness has to report it and throws; the value-only
878 // one needs only the mean, 2^62, and answers, as
879 // karp_minimum_mean_cycle_value() does (the 128-bit sums of Karp's table
880 // hold it). Without 128-bit integers Karp's table cannot hold it either.
881 const long long max = std::numeric_limits<long long>::max();
882 auto built = build_graph(2, {{0, 1, max}, {1, 0, 1}});
883
884 EXPECT_THROW((howard_minimum_mean_cycle(built.g)), std::overflow_error);
885# if ALEPH_KARP_INT128
886 const auto value = howard_minimum_mean_cycle_value(built.g);
887 ASSERT_TRUE(value.has_cycle);
888 EXPECT_EQ(value.minimum_mean, 0x1p62L);
890# else
891 EXPECT_THROW((howard_minimum_mean_cycle_value(built.g)), std::overflow_error);
892# endif
893}
894
895
896// Audit 2026-10-02, C5: why Karp's algorithm answered.
897
899{
900 using D = Dft_Dist<Graph>;
901 using S = Dft_Show_Arc<Graph>;
902
903 // Howard answers: no reason.
904 auto limit_graph = build_graph(4, {{0, 1, 1}, {1, 0, 1}, {0, 2, 2}, {2, 3, -9}, {3, 0, 2}, {1, 2, 5}});
905 const auto normal = howard_minimum_mean_cycle(limit_graph.g);
906 EXPECT_FALSE(normal.used_karp);
907 EXPECT_EQ(normal.fallback_reason, Howard_Fallback_Reason::None);
908
909 // The policy needs improvements that the limit does not allow.
910 const auto limited = howard_detail::minimum_mean_cycle<Graph, D, S>(limit_graph.g, D(), S(), 0);
911 EXPECT_TRUE(limited.used_karp);
912 EXPECT_EQ(limited.fallback_reason, Howard_Fallback_Reason::Iteration_Limit);
913
914 // The scaled bias of ScaledBiasOverflowFallsBackToKarp leaves long long.
915 const long long big = 3100000000000000000LL;
916 auto bias_graph = build_graph(3, {{0, 1, big}, {1, 2, -big}, {2, 0, 200000000000000000LL}});
917 const auto overflowed = howard_minimum_mean_cycle(bias_graph.g);
918 EXPECT_TRUE(overflowed.used_karp);
919 EXPECT_EQ(overflowed.fallback_reason, Howard_Fallback_Reason::Arithmetic_Overflow);
920
921 // The only cycle costs INT_MAX + 1, which int cannot hold although Howard's
922 // long long arithmetic computes it. The function with the witness has to
923 // report that cost and throws, after Karp finds the same cycle; the
924 // value-only one falls back for the same reason and answers.
926 using ID = Dft_Dist<Int_Graph>;
928 const int imax = std::numeric_limits<int>::max();
929 auto int_graph = build_graph_generic<Int_Graph, int>(2, {{0, 1, imax}, {1, 0, 1}});
930 EXPECT_THROW((howard_minimum_mean_cycle(int_graph.g)), std::overflow_error);
931 const auto value = howard_detail::minimum_mean_cycle<Int_Graph, ID, IS, false>(
933 ASSERT_TRUE(value.has_cycle);
934 EXPECT_TRUE(value.used_karp);
935 EXPECT_EQ(value.fallback_reason, Howard_Fallback_Reason::Cost_Out_Of_Range);
936 EXPECT_EQ(value.minimum_mean, 0x1p30L);
938}
939
940
942{
943 // Found by a directed search (audit 2026-10-02, C5). The cost of the
944 // optimal cycle, -4626910599202282041, fits a long long, but summed from
945 // the node where the witness starts a partial sum leaves the type; the
946 // function then fell back to Karp, as if the cost did not fit. Summed from
947 // the smallest node, as the policy evaluation did without overflowing, it
948 // fits all along.
949 auto built = build_graph(7, {{6, 1, 5062036987607531343LL}, {4, 3, -3695868834463239656LL},
950 {4, 1, -3661910840776953621LL}, {2, 6, 5139072827235855353LL},
951 {6, 2, -2377556606531334447LL}, {1, 6, -3191812457526854301LL},
952 {6, 5, -2872654956802585972LL}, {0, 4, -4120068231194526993LL},
953 {5, 2, -6893328469635551422LL}, {1, 5, -3920853593594695630LL},
954 {0, 2, -5174462936561685175LL}, {6, 1, 5725667193745753167LL},
955 {5, 6, 4628323756336527655LL}, {3, 5, 5325742771487410443LL}});
956
957 const auto r = howard_minimum_mean_cycle(built.g);
958 ASSERT_TRUE(r.has_cycle);
959 EXPECT_FALSE(r.used_karp);
960 EXPECT_EQ(r.fallback_reason, Howard_Fallback_Reason::None);
961 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Exact);
962 EXPECT_EQ(r.cycle_total_cost, -4626910599202282041LL);
963 EXPECT_EQ(r.cycle_length, 3u);
964 EXPECT_TRUE(witness_is_simple_cycle(built.g, r, false)); // sums beyond long double's mantissa
965# if ALEPH_KARP_INT128
966 EXPECT_EQ(r.minimum_mean, karp_minimum_mean_cycle(built.g).minimum_mean);
967# else
968 // Without 128-bit integers Karp's checked long long sums overflow here:
969 // the fallback the summation order used to cause would have thrown.
970 EXPECT_THROW((karp_minimum_mean_cycle(built.g)), std::overflow_error);
971# endif
972}
973
974
975// Audit 2026-10-02, C3: a limit on the memory of the fallback.
976
977namespace
978{
979 // The family of audit H5: two components of three nodes, the first one
980 // with weights whose scaled bias overflows, and `isolated` nodes that lie
981 // on no cycle. Howard falls back to Karp (arithmetic overflow).
982 Built_Graph_T<Graph> h5_graph(const size_t isolated)
983 {
984 const long long big = 3100000000000000000LL;
985 return build_graph(6 + isolated,
986 {{0, 1, big}, {1, 2, -big}, {2, 0, 1}, {3, 4, -1}, {4, 5, -1}, {5, 3, -2}});
987 }
988
989 // Bytes of Karp's tables for that family: for each component of 3 nodes,
990 // (3 + 1) * 3 = 12 entries, of which Array reserves 16. The sums of the
991 // first one need 128 bits (3 * 3.1e18 > LLONG_MAX), 8 bytes without them;
992 // the predecessor positions take 8 more.
993# if ALEPH_KARP_INT128
994 constexpr size_t h5_witness_bytes = 16 * (16 + 8);
995 constexpr size_t h5_value_bytes = 16 * 16;
996# else
997 constexpr size_t h5_witness_bytes = 16 * (8 + 8);
998 constexpr size_t h5_value_bytes = 16 * 8;
999# endif
1000} // namespace
1001
1002
1004{
1005 using D = Dft_Dist<Graph>;
1006 using S = Dft_Show_Arc<Graph>;
1007
1008 // With 3000 isolated nodes a table over the whole graph would take some
1009 // 3003^2 entries, hundreds of MiB; the fallback needs the tables of two
1010 // components of three nodes, a few hundred bytes.
1011 auto built = h5_graph(3000);
1012 const auto unlimited = howard_minimum_mean_cycle(built.g);
1013 ASSERT_TRUE(unlimited.used_karp);
1014 ASSERT_EQ(unlimited.fallback_reason, Howard_Fallback_Reason::Arithmetic_Overflow);
1015
1016 for (const size_t limit : {h5_witness_bytes, size_t{1024}})
1017 {
1018 const auto limited = howard_minimum_mean_cycle(built.g, D(), S(), limit);
1019 ASSERT_TRUE(limited.has_cycle) << "limit=" << limit;
1020 EXPECT_EQ(limited.fallback_reason, Howard_Fallback_Reason::Arithmetic_Overflow);
1021 EXPECT_EQ(limited.minimum_mean, unlimited.minimum_mean);
1022 EXPECT_EQ(limited.cycle_total_cost, unlimited.cycle_total_cost);
1023 EXPECT_EQ(limited.cycle_length, unlimited.cycle_length);
1025 }
1026
1027 // The value-only function needs no predecessors: a smaller table.
1028 for (const size_t limit : {h5_value_bytes, size_t{1024}})
1029 EXPECT_EQ(howard_minimum_mean_cycle_value(built.g, D(), S(), limit).minimum_mean,
1030 unlimited.minimum_mean) << "limit=" << limit;
1031}
1032
1033
1035{
1036 using D = Dft_Dist<Graph>;
1037 using S = Dft_Show_Arc<Graph>;
1038 auto built = h5_graph(10);
1039
1040 // One byte below what the tables need.
1042 std::length_error);
1044 std::length_error);
1045
1046 // The message gives the bytes, the component and the reason.
1047 try
1048 {
1049 (void) howard_minimum_mean_cycle(built.g, D(), S(), 100);
1050 FAIL() << "the limit was ignored";
1051 }
1052 catch (const std::length_error & e)
1053 {
1054 const std::string what = e.what();
1055 EXPECT_NE(what.find("arithmetic overflow"), std::string::npos) << what;
1056 EXPECT_NE(what.find(std::to_string(h5_witness_bytes) + " bytes"), std::string::npos) << what;
1057 EXPECT_NE(what.find("component of 3 nodes"), std::string::npos) << what;
1058 EXPECT_NE(what.find("limit of 100 bytes"), std::string::npos) << what;
1059 }
1060
1061 // A limit of 0 refuses any fallback, and only a fallback: where Howard
1062 // answers by itself it does not matter.
1063 auto plain = build_graph(4, {{0, 1, 1}, {1, 0, 1}, {0, 2, 2}, {2, 3, -9}, {3, 0, 2}, {1, 2, 5}});
1064 const auto r = howard_minimum_mean_cycle(plain.g, D(), S(), 0);
1065 ASSERT_TRUE(r.has_cycle);
1066 EXPECT_FALSE(r.used_karp);
1067 EXPECT_EQ(r.minimum_mean, -5.0L / 3.0L);
1068 try
1069 {
1070 (void) howard_detail::minimum_mean_cycle<Graph, D, S>(plain.g, D(), S(), 0, 0);
1071 FAIL() << "a limit of 0 let the fallback run";
1072 }
1073 catch (const std::length_error & e)
1074 {
1075 EXPECT_NE(std::string(e.what()).find("iteration limit"), std::string::npos) << e.what();
1076 }
1077}
1078
1080{
1081 // Independent audit of stage C, C2. The first component (3 nodes, whose
1082 // scaled bias overflows and sends Howard to Karp) needs small tables; the
1083 // second, a ring of 40 nodes, needs 32768 bytes. A limit that only the
1084 // first component meets has to be refused.
1085 using D = Dft_Dist<Graph>;
1086 using S = Dft_Show_Arc<Graph>;
1087 const long long big = 3100000000000000000LL;
1088 std::vector<std::tuple<size_t, size_t, long long>> edges = {{0, 1, big}, {1, 2, -big}, {2, 0, 1}};
1089 for (size_t i = 0; i < 40; ++i)
1090 edges.emplace_back(3 + i, 3 + (i + 1) % 40, static_cast<long long>(i) - 20);
1091 auto built = build_graph_generic<Graph, long long>(43, edges);
1092 const auto unlimited = howard_minimum_mean_cycle(built.g);
1093 ASSERT_TRUE(unlimited.used_karp);
1094 EXPECT_THROW((howard_minimum_mean_cycle(built.g, D(), S(), 32767)), std::length_error);
1095 EXPECT_NO_THROW((howard_minimum_mean_cycle(built.g, D(), S(), 32768)));
1096}
1097
1098# if ALEPH_KARP_INT128
1100{
1101 // Independent audit of stage C, H1. The 2-cycle costs LLONG_MAX + 1, so
1102 // Howard falls back to Karp, component by component. The loop of the
1103 // other component wins; the witness of the 2-cycle, which does not fit a
1104 // long long, used to be extracted all the same and threw.
1105 const long long max = std::numeric_limits<long long>::max();
1106 auto built = build_graph(3, {{0, 1, max}, {1, 0, 1}, {2, 2, -1}});
1107 const auto r = howard_minimum_mean_cycle(built.g);
1108 ASSERT_TRUE(r.has_cycle);
1109 EXPECT_TRUE(r.used_karp);
1110 EXPECT_EQ(r.fallback_reason, Howard_Fallback_Reason::Arithmetic_Overflow);
1111 EXPECT_EQ(r.minimum_mean, -1.0L);
1112 EXPECT_EQ(r.cycle_total_cost, -1);
1113 EXPECT_EQ(r.witness_node, built.nodes[2]);
1115}
1116
1118{
1119 // Independent audit of stage C, U1. Weights near 2^64 do not fit the
1120 // long long of the exact arithmetic, and unsigned long long used to be
1121 // iterated in long double: its bias tolerance hid the improvement, and it
1122 // reported the loop 3 -> 3 of mean 7 instead of 4 -> 1 -> 5 -> 4 of 11/3.
1123 using U = unsigned long long;
1125 const U m = std::numeric_limits<U>::max();
1127 6, {{4, 2, 6}, {1, 5, 7}, {3, 4, 0}, {5, 0, 7}, {5, 4, 3}, {5, 0, 1}, {2, 3, m - 2},
1128 {4, 1, 1}, {3, 2, m}, {3, 3, 7}, {0, 5, m - 2}, {3, 4, 6}, {4, 2, 1}});
1129 const auto r = howard_minimum_mean_cycle(built.g);
1130 ASSERT_TRUE(r.has_cycle);
1131 EXPECT_FALSE(r.used_karp);
1132 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Exact);
1133 EXPECT_EQ(r.cycle_total_cost, 11u);
1134 EXPECT_EQ(r.cycle_length, 3u);
1135 EXPECT_EQ(r.minimum_mean, 11.0L / 3.0L);
1137
1138 // The 2-cycle totals 2^65 - 2, beyond the cost type; its mean is still
1139 // compared exactly, in 128 bits, and the loop of mean m - 1 wins.
1140 auto large = build_graph_generic<U_Graph, U>(3, {{0, 1, m}, {1, 0, m}, {2, 2, m - 1}});
1141 const auto l = howard_minimum_mean_cycle(large.g);
1142 ASSERT_TRUE(l.has_cycle);
1143 EXPECT_FALSE(l.used_karp);
1144 EXPECT_EQ(l.cycle_total_cost, m - 1);
1145 EXPECT_EQ(l.cycle_length, 1u);
1146}
1147
1149{
1150 // Independent audit of stage C, T1. The loop at 3 and the 2-cycle 1 <-> 2
1151 // have the same mean, -32764, but only the loop's cost fits an int16_t.
1152 // Howard's policy reaches the 2-cycle (Cost_Out_Of_Range), and Karp's
1153 // fallback reports the loop instead of throwing.
1156 5, {{2, 1, -32767}, {4, 3, 32761}, {1, 2, -32761}, {2, 4, -32768},
1157 {3, 2, -32768}, {3, 3, -32764}, {4, 1, 32760}});
1158 const auto r = howard_minimum_mean_cycle(built.g);
1159 ASSERT_TRUE(r.has_cycle);
1160 EXPECT_EQ(r.minimum_mean, -32764.0L);
1161 EXPECT_EQ(r.cycle_length, 1u);
1162 EXPECT_EQ(r.cycle_total_cost, -32764);
1163 EXPECT_EQ(r.fallback_reason, Howard_Fallback_Reason::Cost_Out_Of_Range);
1164}
1165
1167{
1168 // Final independent review of the branch, mutation M37: comparing the
1169 // means in long double went unnoticed. The means 2^60 + 1/6 (a 6-cycle)
1170 // and 2^60 + 1/7 (a 7-cycle in another component) round to the same long
1171 // double; the 7-cycle is the optimum, whichever component comes first.
1172 const long long a = 1LL << 60;
1173 for (const bool seven_first : {false, true})
1174 {
1175 std::vector<Edge_Def> six, seven;
1176 for (size_t i = 0; i < 6; ++i)
1177 six.emplace_back(i, (i + 1) % 6, i == 5 ? a + 1 : a);
1178 for (size_t i = 0; i < 7; ++i)
1179 seven.emplace_back(6 + i, 6 + (i + 1) % 7, i == 6 ? a + 1 : a);
1180 std::vector<Edge_Def> edges = seven_first ? seven : six;
1181 const std::vector<Edge_Def> & rest = seven_first ? six : seven;
1182 edges.insert(edges.end(), rest.begin(), rest.end());
1183 auto built = build_graph(13, edges);
1184
1185 const auto h = howard_minimum_mean_cycle(built.g);
1186 ASSERT_TRUE(h.has_cycle);
1187 EXPECT_EQ(h.cycle_length, 7u) << "seven_first = " << seven_first;
1188 EXPECT_EQ(h.cycle_total_cost, 7 * a + 1) << "seven_first = " << seven_first;
1189
1190 const auto k = karp_minimum_mean_cycle(built.g);
1191 ASSERT_TRUE(k.has_cycle);
1192 EXPECT_EQ(k.cycle_length, 7u) << "seven_first = " << seven_first;
1193 EXPECT_EQ(k.cycle_total_cost, 7 * a + 1) << "seven_first = " << seven_first;
1194 }
1195}
1196# endif
1197
1198
1200{
1201 // Two copies of the graph above (nodes 0-3 and 4-7, same mean -5/3), a
1202 // component of mean -1 (nodes 8-9), arcs between components, which lie on
1203 // no cycle, and many isolated nodes. Only the cyclic core reaches Karp.
1204 const size_t isolated = 2000;
1205 std::vector<Edge_Def> edges;
1206 for (size_t base : {0u, 4u})
1207 for (const auto &[u, v, w] : std::vector<Edge_Def>{{0, 1, 1}, {1, 0, 1}, {0, 2, 2},
1208 {2, 3, -9}, {3, 0, 2}, {1, 2, 5}})
1209 edges.emplace_back(base + u, base + v, w);
1210 edges.emplace_back(8, 9, -1);
1211 edges.emplace_back(9, 8, -1);
1212 edges.emplace_back(9, 0, -100); // between components
1213 edges.emplace_back(3, 4, -100);
1214 edges.emplace_back(10, 8, -100); // from an isolated node
1215 auto built = build_graph(10 + isolated, edges);
1216
1217 const auto r = howard_detail::minimum_mean_cycle<Graph, Dft_Dist<Graph>, Dft_Show_Arc<Graph>>(
1218 built.g, Dft_Dist<Graph>(), Dft_Show_Arc<Graph>(), 0);
1219 ASSERT_TRUE(r.has_cycle);
1220 ASSERT_TRUE(r.used_karp);
1221 EXPECT_EQ(r.minimum_mean, -5.0L / 3.0L);
1223
1224 // The tie between the two copies goes to the one that comes first, as in
1225 // a single table over the whole graph.
1226 for (auto it = r.cycle_nodes.get_it(); it.has_curr(); it.next_ne())
1227 EXPECT_LT(it.get_curr()->get_info(), 4);
1228 EXPECT_LT(r.witness_node->get_info(), 4);
1229
1230 // The same value as Karp on the whole graph, which agrees exactly here:
1231 // integral costs make both round the exact minimum mean once.
1232 EXPECT_EQ(r.minimum_mean, karp_minimum_mean_cycle(built.g).minimum_mean);
1233}
1234
1235
1237{
1238 // Audit 2026-10-02, C4: after the fallback the witness is a simple cycle,
1239 // `witness_node` is its first node and its cost is that of its arcs, as in
1240 // Howard's own answer. Before, it was Karp's closed walk, not simple in a
1241 // third of the floating-point cases.
1242 std::mt19937_64 rng(0xC4);
1243 size_t fallbacks = 0;
1244 for (size_t trial = 0; trial < 3000; ++trial)
1245 {
1246 const size_t n = 2 + rng() % 8;
1247 const size_t m = n + rng() % (2 * n);
1248 std::vector<Edge_Def> iedges;
1249 std::vector<std::tuple<size_t, size_t, double>> fedges;
1250 for (size_t i = 0; i < m; ++i)
1251 {
1252 const size_t u = rng() % n;
1253 const size_t v = rng() % n;
1254 const long long w = static_cast<long long>(rng() % 41) - 20;
1255 const double unit = std::uniform_real_distribution<double>(-1.0, 1.0)(rng);
1256 const int exponent = static_cast<int>(rng() % 40) - 20;
1257 iedges.emplace_back(u, v, w);
1258 fedges.emplace_back(u, v, std::ldexp(unit, exponent));
1259 }
1260
1261 auto ib = build_graph(n, iedges);
1262 const auto ir = howard_detail::minimum_mean_cycle<Graph, Dft_Dist<Graph>, Dft_Show_Arc<Graph>>(
1264 ASSERT_EQ(ir.used_karp, ir.fallback_reason != Howard_Fallback_Reason::None) << "trial=" << trial;
1265 if (ir.used_karp)
1266 {
1267 ++fallbacks;
1268 ASSERT_EQ(ir.fallback_reason, Howard_Fallback_Reason::Iteration_Limit) << "trial=" << trial;
1269 ASSERT_TRUE(witness_is_simple_cycle(ib.g, ir)) << "long long, trial=" << trial;
1270 ASSERT_EQ(ir.minimum_mean, howard_minimum_mean_cycle(ib.g).minimum_mean) << "trial=" << trial;
1271 }
1272
1274 const auto fr =
1275 howard_detail::minimum_mean_cycle<Float_Graph, Dft_Dist<Float_Graph>, Dft_Show_Arc<Float_Graph>>(
1277 ASSERT_EQ(fr.used_karp, fr.fallback_reason != Howard_Fallback_Reason::None) << "trial=" << trial;
1278 if (fr.used_karp)
1279 {
1280 ++fallbacks;
1281 ASSERT_EQ(fr.fallback_reason, Howard_Fallback_Reason::Iteration_Limit) << "trial=" << trial;
1282 ASSERT_TRUE(witness_is_simple_cycle(fb.g, fr)) << "double, trial=" << trial;
1283 ASSERT_EQ(fr.numeric_quality, Cycle_Numeric_Quality::Rounded);
1284 }
1285 }
1286 EXPECT_GT(fallbacks, 1000u); // the iteration limit 0 forces most of them
1287}
1288
1289
1291{
1292 // Found by a directed search (audit 2026-10-02, C1 and C6). Inside the
1293 // component {1, ..., 5} every walk is costly and the long long sums of a
1294 // per-component table overflow; on the whole graph the arc 0 -> 1, from
1295 // outside, kept them low. The per-component fallback then threw where the
1296 // old whole-graph one answered. 128-bit sums remove that.
1297 auto built = build_graph(6, {{3, 4, 2412223573619837724LL}, {2, 3, 2422047310724953863LL},
1298 {1, 2, 3179646298365416052LL}, {0, 1, -3127445719569793886LL},
1299 {1, 2, 3008898773151771847LL}, {4, 4, 3004633816298768677LL},
1300 {0, 5, 2726043725430506698LL}, {3, 5, 1938808504231304943LL},
1301 {4, 1, 3287975327571625454LL}, {1, 2, 2527433209753059253LL},
1302 {1, 1, 1921533484238488548LL}, {5, 3, 1325352911222347034LL},
1303 {2, 3, 2519116059040766616LL}, {2, 2, 1472205099507841752LL},
1304 {2, 2, 3345130543762169200LL}, {1, 4, 1779708353840524248LL},
1305 {1, 5, 3214578466714837685LL}});
1306
1307 const auto exact = howard_minimum_mean_cycle(built.g);
1308 ASSERT_TRUE(exact.has_cycle);
1309 ASSERT_FALSE(exact.used_karp);
1310# if ALEPH_KARP_INT128
1311 const auto forced = howard_detail::minimum_mean_cycle<Graph, Dft_Dist<Graph>, Dft_Show_Arc<Graph>>(
1312 built.g, Dft_Dist<Graph>(), Dft_Show_Arc<Graph>(), 0);
1313 ASSERT_TRUE(forced.has_cycle);
1314 ASSERT_TRUE(forced.used_karp);
1315 EXPECT_TRUE(witness_is_simple_cycle(built.g, forced, false)); // sums beyond long double's mantissa
1316 EXPECT_EQ(forced.minimum_mean, exact.minimum_mean);
1317 EXPECT_EQ(forced.minimum_mean, karp_minimum_mean_cycle(built.g).minimum_mean);
1318# endif
1319}
1320
1321
1322// ---------------------------------------------------------------------------
1323// Audit 2026-10-02, H2-H4, fixed in its stage B. Every weight below is a
1324// binary fraction represented exactly, and the exact answer follows from
1325// identities between powers of two, not from another algorithm. The policy
1326// is found with long double arithmetic and then re-solved exactly with the
1327// weights scaled to 64- or 128-bit integers when they fit; when they do not,
1328// the choice among the cycles of the policy is still made with exact sums.
1329// ---------------------------------------------------------------------------
1330
1332{
1333 // Ring 0 -> 1 -> 2 -> 3 -> 0 with weights 2^e, 1, -2^e, -2: exact mean -1/4.
1334 // Self-loop of node 4: -0.375, the exact optimum. For e = 100 and e = 200
1335 // the plain sum of the policy evaluation loses the 1 and the ring looks like
1336 // mean -1/2; it used to be returned. With e = 200 the weights span 204 bits,
1337 // too many for the exact verification: the policy stays the rounded one, and
1338 // only the exact choice among its cycles picks the loop.
1339 for (const int e : {50, 100, 200})
1340 {
1341 const double big = std::ldexp(1.0, e);
1343 5, {{0, 1, big}, {1, 2, 1.0}, {2, 3, -big}, {3, 0, -2.0}, {4, 4, -0.375}});
1344
1345 const auto r = howard_minimum_mean_cycle(built.g);
1346 ASSERT_TRUE(r.has_cycle) << "e=" << e;
1347 EXPECT_FALSE(r.used_karp) << "e=" << e;
1348 EXPECT_TRUE(witness_is_simple_cycle(built.g, r)) << "e=" << e;
1349 EXPECT_EQ(r.minimum_mean, -0.375L) << "e=" << e;
1350 EXPECT_EQ(r.cycle_total_cost, -0.375) << "e=" << e;
1351 EXPECT_EQ(r.cycle_length, 1u) << "e=" << e;
1352
1353 // The scaled weights need 54 bits for e = 50, 104 for e = 100 and 204
1354 // for e = 200.
1355# if ALEPH_HOWARD_INT128
1356 const bool verified = e <= 100;
1357# else
1358 const bool verified = e == 50;
1359# endif
1360 EXPECT_EQ(r.numeric_quality, verified ? Cycle_Numeric_Quality::Exact
1361 : Cycle_Numeric_Quality::Rounded) << "e=" << e;
1362 }
1363}
1364
1365
1367{
1368 // Ring 0 -> 1 -> 2 -> 3 -> 0 with weights 2^122, 1, -2^122, -1.875 (exact mean
1369 // -0.21875) and a self-loop of -0.375, the optimum. The rounded iteration
1370 // loses the 1 and prefers the ring. Scaled to integers the weights need 126
1371 // bits, so the 128-bit verification is tried, but the ring's mean has
1372 // denominator 4 and 4 * 2^125 overflows it: the verification must notice and
1373 // give up, leaving the exact choice among the cycles to pick the loop.
1374 const double big = std::ldexp(1.0, 122);
1376 5, {{0, 1, big}, {1, 2, 1.0}, {2, 3, -big}, {3, 0, -1.875}, {4, 4, -0.375}});
1377
1378 const auto r = howard_minimum_mean_cycle(built.g);
1379 ASSERT_TRUE(r.has_cycle);
1380 EXPECT_FALSE(r.used_karp);
1381 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Rounded);
1382 EXPECT_EQ(r.minimum_mean, -0.375L);
1383 EXPECT_EQ(r.cycle_length, 1u);
1384 EXPECT_TRUE(witness_is_simple_cycle(built.g, r, false));
1385}
1386
1387
1389{
1390 // Loops of weight 0 on nodes 0 and 1, and the cycle 0 -> 1 -> 0 with weights
1391 // d and -2d: mean -d/2, the optimum. With d = 2^-60 the improvement is below
1392 // the absolute floor of the bias tolerance (64 epsilon of a long double), so
1393 // the long double iteration stops at a loop of mean 0; the exact one, which
1394 // starts from that policy, finds the cycle.
1395 for (const int exponent : {-60, 0})
1396 {
1397 const double d = std::ldexp(1.0, exponent);
1399 2, {{0, 0, 0.0}, {1, 1, 0.0}, {0, 1, d}, {1, 0, -2 * d}});
1400
1401 const auto r = howard_minimum_mean_cycle(built.g);
1402 ASSERT_TRUE(r.has_cycle) << "exponent=" << exponent;
1403 EXPECT_FALSE(r.used_karp) << "exponent=" << exponent;
1404 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Exact) << "exponent=" << exponent;
1405 EXPECT_TRUE(witness_is_simple_cycle(built.g, r)) << "exponent=" << exponent;
1406 EXPECT_EQ(r.minimum_mean, -static_cast<long double>(d) / 2) << "exponent=" << exponent;
1407 EXPECT_EQ(r.cycle_total_cost, -d) << "exponent=" << exponent;
1408 EXPECT_EQ(r.cycle_length, 2u) << "exponent=" << exponent;
1409 }
1410}
1411
1412
1414{
1415 // Six-arc ring whose weights 2^100, 1, 2^-100, -1, -2^100, -2^-100 (in some
1416 // rotation) sum exactly to zero. Its published cost used to be a
1417 // compensated sum, -2^-100 for some rotations; it is now the exact sum. The
1418 // weights span 201 binary orders of magnitude, too many for the exact
1419 // verification, so the result stays Rounded.
1420 const double big = std::ldexp(1.0, 100);
1421 const double tiny = std::ldexp(1.0, -100);
1422 const std::vector<double> ring = {big, 1.0, tiny, -1.0, -big, -tiny};
1423
1424 for (size_t rotation = 0; rotation < ring.size(); ++rotation)
1425 {
1426 std::vector<std::tuple<size_t, size_t, double>> edges;
1427 for (size_t i = 0; i < ring.size(); ++i)
1428 edges.emplace_back(i, (i + 1) % ring.size(), ring[(i + rotation) % ring.size()]);
1429 auto built = build_graph_generic<Float_Graph, double>(ring.size(), edges);
1430
1431 const auto r = howard_minimum_mean_cycle(built.g);
1432 ASSERT_TRUE(r.has_cycle) << "rotation=" << rotation;
1433 EXPECT_FALSE(r.used_karp) << "rotation=" << rotation;
1434 EXPECT_EQ(r.cycle_length, ring.size()) << "rotation=" << rotation;
1435 EXPECT_EQ(r.numeric_quality, Cycle_Numeric_Quality::Rounded) << "rotation=" << rotation;
1436 EXPECT_TRUE(witness_is_simple_cycle(built.g, r, false)) << "rotation=" << rotation;
1437 EXPECT_EQ(r.cycle_total_cost, 0.0) << "rotation=" << rotation;
1438 EXPECT_EQ(r.minimum_mean, 0.0L) << "rotation=" << rotation;
1439 }
1440}
1441
1442
1444{
1445 // Whenever Karp can answer, Howard (directly or through the fallback) gives
1446 // the same value; Howard may also answer where Karp's sums overflow.
1447 //
1448 // The mean is a `long double`. With a 64-bit mantissa (x86) converting a sum
1449 // of up to ~1e19 is exact and both algorithms round the same quotient once,
1450 // so they agree bit for bit. With a 53-bit one (`long double` is a `double`
1451 // on Apple Silicon and MSVC) every conversion of such a sum rounds, and
1452 // Karp's subtract-then-divide drifts from the exact mean by a few rounding
1453 // errors *of the sums*, which are large next to a small mean. So Howard's
1454 // cycle is checked exactly against a 128-bit exhaustive oracle on every
1455 // platform, and Karp's value with a tolerance that is zero where
1456 // `long double` is wide enough to make the two bit-identical.
1457 using Mean_Limits = std::numeric_limits<long double>;
1458 std::mt19937_64 rng(0x0F3EF10ULL);
1459 for (size_t trial = 0; trial < 1500; ++trial)
1460 {
1461 const size_t n = 2 + rng() % 5;
1462 const long long big = (trial % 2 == 0) ? 1000000000000000000LL : 2000000000000000000LL;
1463 std::vector<Edge_Def> edges;
1464 const size_t m = n + rng() % (2 * n);
1465 for (size_t i = 0; i < m; ++i)
1466 {
1467 const size_t u = rng() % n;
1468 const size_t v = rng() % n;
1469 const long long w = static_cast<long long>(rng() % static_cast<unsigned long long>(2 * big)) - big;
1470 edges.emplace_back(u, v, w);
1471 }
1472
1473 auto built = build_graph(n, edges);
1476 bool karp_threw = false;
1477 try { karp = karp_minimum_mean_cycle(built.g); } catch (const std::overflow_error &) { karp_threw = true; }
1478 try { howard = howard_minimum_mean_cycle(built.g); }
1479 catch (const std::overflow_error &)
1480 {
1481 // Only an answer that Karp could not give either may be refused.
1482 ASSERT_TRUE(karp_threw) << "trial=" << trial;
1483 continue;
1484 }
1485
1486# if ALEPH_HOWARD_INT128
1487 // Howard's own answer, also where Karp threw: exactly the oracle's
1488 // rational mean, `total / length` cross-multiplied in 128 bits. (After
1489 // the fallback the witness is Karp's closed walk: nothing to compare.)
1490 // Without a 128-bit integer (MSVC) only the comparison with Karp below
1491 // remains.
1492 const auto oracle = exact_minimum_mean<__int128>(built);
1493 ASSERT_EQ(howard.has_cycle, oracle.exists) << "trial=" << trial;
1494 if (howard.has_cycle and not howard.used_karp)
1495 ASSERT_TRUE(static_cast<__int128>(howard.cycle_total_cost) * oracle.length
1496 == oracle.total * static_cast<__int128>(howard.cycle_length))
1497 << "trial=" << trial;
1498# endif
1499
1500 if (karp_threw)
1501 continue;
1502 ASSERT_EQ(howard.has_cycle, karp.has_cycle) << "trial=" << trial;
1503 if (not howard.has_cycle)
1504 continue;
1505
1506 // Karp rounds the conversions of its sums (each below n * big in
1507 // absolute value) and their difference: a few of their rounding errors,
1508 // `epsilon * n * big`, bound the drift. That holds after the fallback
1509 // too, which runs Karp's table on each component, not on the whole
1510 // graph: other sums, the same exact mean.
1511 const long double tolerance =
1512 Mean_Limits::digits >= 64
1513 ? 0.0L
1514 : 8.0L * Mean_Limits::epsilon() * static_cast<long double>(n)
1515 * static_cast<long double>(big);
1516 ASSERT_LE(std::fabs(howard.minimum_mean - karp.minimum_mean), tolerance)
1517 << "trial=" << trial;
1518 }
1519}
1520
1521
1522// ---------------------------------------------------------------------------
1523// The exact arithmetic.
1524// ---------------------------------------------------------------------------
1525
1527{
1528 const long long hi = std::numeric_limits<long long>::max();
1529 const long long lo = std::numeric_limits<long long>::min();
1530
1531 EXPECT_EQ(Arith::compare_fractions(1, 3, 2, 6), 0);
1532 EXPECT_EQ(Arith::compare_fractions(-1, 3, 1, 3), -1);
1533 EXPECT_EQ(Arith::compare_fractions(7, 2, 10, 3), 1); // 3.5 > 3.33..
1534 EXPECT_EQ(Arith::compare_fractions(hi, 1, hi - 1, 1), 1);
1535 EXPECT_EQ(Arith::compare_fractions(lo, 1, lo + 1, 1), -1);
1536 EXPECT_EQ(Arith::compare_fractions(lo, 3, lo, 2), 1); // -x/3 > -x/2
1537 EXPECT_EQ(Arith::compare_fractions(hi, hi, 1, 1), 0);
1538 EXPECT_EQ(Arith::compare_fractions(hi - 1, hi, hi - 2, hi - 1), 1); // 1 - 1/hi vs 1 - 1/(hi-1)
1539
1540# if ALEPH_HOWARD_INT128
1541 std::mt19937_64 rng(0xC0FFEE);
1542 for (size_t i = 0; i < 200000; ++i)
1543 {
1544 auto draw = [&]
1545 {
1546 const unsigned long long r = rng();
1547 switch (rng() % 4)
1548 {
1549 case 0: return static_cast<long long>(r);
1550 case 1: return static_cast<long long>(r % 2000) - 1000;
1551 case 2: return static_cast<long long>(r >> (rng() % 63)) * (rng() % 2 ? 1 : -1);
1552 default: return (rng() % 2) ? hi - static_cast<long long>(r % 5) : lo + static_cast<long long>(r % 5);
1553 }
1554 };
1555 auto positive = [&]
1556 {
1557 long long b = draw();
1558 if (b == lo)
1559 b = hi;
1560 return b < 0 ? -b : (b == 0 ? 1 : b);
1561 };
1562 const long long a1 = draw(), a2 = draw(), b1 = positive(), b2 = positive();
1563 const __int128 lhs = static_cast<__int128>(a1) * b2;
1564 const __int128 rhs = static_cast<__int128>(a2) * b1;
1565 const int expected = lhs < rhs ? -1 : (lhs > rhs ? 1 : 0);
1566 ASSERT_EQ(Arith::compare_fractions(a1, b1, a2, b2), expected)
1567 << a1 << "/" << b1 << " vs " << a2 << "/" << b2;
1568 }
1569# endif
1570}
1571
1572
1574{
1575 const auto e = Arith::make_eta(-6, 4);
1576 EXPECT_EQ(e.num, -3);
1577 EXPECT_EQ(e.den, 2);
1578 EXPECT_TRUE(Arith::equal(Arith::make_eta(2, 4), Arith::make_eta(1, 2)));
1579 EXPECT_FALSE(Arith::equal(Arith::make_eta(1, 3), Arith::make_eta(1, 2)));
1580 EXPECT_TRUE(Arith::less(Arith::make_eta(1, 3), Arith::make_eta(1, 2)));
1581 EXPECT_FALSE(Arith::less(Arith::make_eta(1, 2), Arith::make_eta(1, 2)));
1582 const auto zero = Arith::make_eta(0, 7);
1583 EXPECT_EQ(zero.num, 0);
1584 EXPECT_EQ(zero.den, 1);
1585 const auto extreme = Arith::make_eta(std::numeric_limits<long long>::min(), 2);
1586 EXPECT_EQ(extreme.den, 1);
1587 EXPECT_EQ(extreme.num, std::numeric_limits<long long>::min() / 2);
1588
1589 long long out = 0;
1590 EXPECT_TRUE(Arith::step(5, Arith::Eta{3, 2}, 10, out)); // 2 * 5 - 3 + 10
1591 EXPECT_EQ(out, 17);
1592 const long long hi = std::numeric_limits<long long>::max();
1593 EXPECT_FALSE(Arith::step(hi, Arith::Eta{0, 2}, 0, out)); // 2 * max overflows
1594 EXPECT_FALSE(Arith::step(0, Arith::Eta{std::numeric_limits<long long>::min(), 1}, 0, out)); // 0 - min
1595 EXPECT_FALSE(Arith::step(0, Arith::Eta{0, 1}, hi, out) and Arith::step(1, Arith::Eta{0, 1}, hi, out));
1596}
1597
1598
1599# if ALEPH_HOWARD_INT128
1601{
1602 // The 128-bit arithmetic of the exact verification: products whose factors
1603 // fit 64 bits take a fast path, the others the portable test.
1604 using Wide = howard_detail::int128_t;
1606 const Wide two_125 = Wide(1) << 125;
1608
1609 Wide out = 0;
1610 EXPECT_TRUE(Ar::step(Wide(5), Ar::Eta{3, 2}, Wide(10), out)); // 2 * 5 - 3 + 10, fast path
1611 EXPECT_EQ(out, Wide(17));
1612 EXPECT_TRUE(Ar::step(two_125, Ar::Eta{0, 3}, Wide(0), out)); // 3 * 2^125 < 2^127
1613 EXPECT_EQ(out, 3 * two_125);
1614 EXPECT_FALSE(Ar::step(two_125, Ar::Eta{0, 4}, Wide(0), out)); // 4 * 2^125 = 2^127 overflows
1615 EXPECT_FALSE(Ar::step(-two_125, Ar::Eta{0, 5}, Wide(0), out)); // -5 * 2^125 overflows
1616 EXPECT_FALSE(Ar::step(max, Ar::Eta{0, 2}, Wide(0), out));
1617 EXPECT_FALSE(Ar::step(Wide(0), Ar::Eta{0, 1}, max, out) and Ar::step(Wide(1), Ar::Eta{0, 1}, max, out));
1618
1619 const auto e = Ar::make_eta(-(Wide(3) << 100), 6); // -3 * 2^100 / 6 = -2^99 / 1
1620 EXPECT_EQ(e.den, Wide(1));
1621 EXPECT_EQ(e.num, -(Wide(1) << 99));
1622}
1623# endif
1624
1625
1626// ---------------------------------------------------------------------------
1627// The file documentation promises that several threads may search one graph.
1628// ---------------------------------------------------------------------------
1629
1631{
1632 std::vector<Edge_Def> edges;
1633 for (size_t u = 0; u < 40; ++u)
1634 {
1635 edges.emplace_back(u, (u + 1) % 40, 1 + static_cast<long long>(u % 5));
1636 edges.emplace_back(u, (u * 7 + 3) % 40, 2 - static_cast<long long>(u % 3));
1637 }
1638 auto built = build_graph(40, edges);
1639 const auto reference = howard_minimum_mean_cycle(built.g);
1640 ASSERT_TRUE(reference.has_cycle);
1641
1642 constexpr size_t threads = 8;
1643 std::vector<int> failures(threads, 0);
1644 std::vector<std::thread> pool;
1645 for (size_t t = 0; t < threads; ++t)
1646 pool.emplace_back([&, t]
1647 {
1648 for (size_t i = 0; i < 40; ++i)
1649 {
1650 const auto r = howard_minimum_mean_cycle(built.g);
1651 if (r.minimum_mean != reference.minimum_mean or r.cycle_arcs != reference.cycle_arcs
1652 or r.iterations != reference.iterations)
1653 ++failures[t];
1654 }
1655 });
1656 for (auto & th : pool)
1657 th.join();
1658 for (size_t t = 0; t < threads; ++t)
1659 EXPECT_EQ(failures[t], 0) << "thread " << t;
1660}
Minimum mean cycle by Howard's policy iteration.
Minimum mean cycle in directed graphs (Karp algorithm).
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
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.
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
Minimal std::expected-style result type for C++20.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
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
Container< Node * > nodes() const
Return a container with all the nodes of the graph.
Definition graph-dry.H:3062
#define FAIL(msg)
#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
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.
Howard_Mean_Cycle_Result< GT, typename Distance::Distance_Type > howard_minimum_mean_cycle(const GT &g, Distance distance=Distance(), SA sa=SA(), const size_t max_fallback_bytes=std::numeric_limits< size_t >::max())
Minimum mean cycle by Howard's policy iteration.
Min_Mean_Cycle_Value_Result howard_minimum_mean_cycle_value(const GT &g, Distance distance=Distance(), SA sa=SA(), const size_t max_fallback_bytes=std::numeric_limits< size_t >::max())
Minimum mean cycle value by Howard's policy iteration, without the witness.
constexpr size_t default_iterations
Value of max_iterations that selects the default limit, V + 64.
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.
Main namespace for Aleph-w library functions.
bool less_than(const T &op1, const T &op2, Compare &cmp)
Determines if op1 is less than op2 using a comparison operator.
Definition ahFunction.H:991
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
bool exists(Container &container, Operation &operation)
Return true if at least one element satisfies a predicate.
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::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
Graph types and probe helpers shared by negative_cycles_test.cc and bounded_negative_cycle_test....
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Result of howard_minimum_mean_cycle().
bool used_karp
True if Karp's algorithm produced the answer: fallback_reason is not None.
Result of minimum mean cycle computation.
size_t cycle_length
Number of arcs in witness cycle.
Cost_Type cycle_total_cost
Weight sum of witness cycle.
bool has_cycle
True if at least one directed cycle exists.
bool has_cycle
True if at least one directed cycle exists.
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Arithmetic of the policy evaluation, specialised by exactness.
Integer type, and its limits, of the exact arithmetic for Cost_Type: long long, or int128_t for unsig...
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
Array-based graph implementation.
Generic graph and digraph implementations.
DynList< int > l