Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
graph_exhaustive_negative_cycles_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
71#include <algorithm>
72#include <array>
73#include <cmath>
74#include <functional>
75#include <iterator>
76#include <limits>
77#include <map>
78#include <memory>
79#include <optional>
80#include <random>
81#include <set>
82#include <sstream>
83#include <stdexcept>
84#include <string>
85#include <tuple>
86#include <type_traits>
87#include <utility>
88#include <vector>
89
90#include <gtest/gtest.h>
91
92#include <tpl_graph.H>
93#include <Bellman_Ford.H>
94#include <Negative_Cycles.H>
95#include <Min_Mean_Cycle.H>
97#include <Floyd_Warshall.H>
98#include <Johnson.H>
99
100#include "graph_filter_catalog.H"
101#include "graph_harness.H"
102#include "graph_oracles.H"
103
104using namespace Aleph;
105using namespace graph_harness;
106namespace oracle = graph_oracles;
108
109namespace
110{
112 template <typename T>
113 std::string text_of(const T & x)
114 {
115 std::ostringstream s;
116 s << x;
117 return s.str();
118 }
119
122 template <class GT, typename T>
123 struct Spec_Weight
124 {
125 using Distance_Type = T;
126
127 const std::vector<T> * weights = nullptr;
128
129 T operator () (typename GT::Arc * a) const
130 {
131 return (*weights)[size_t(a->get_info())];
132 }
133
134 T operator () (typename GT::Arc * a, typename GT::Node *) const
135 {
136 return (*this)(a);
137 }
138 };
139
141 template <class GT>
142 struct Show_Mask
143 {
144 unsigned long shown = 0;
145
146 bool operator () (typename GT::Arc * a) const noexcept
147 {
148 return a->get_info() >= 0 and ((shown >> a->get_info()) & 1UL) != 0;
149 }
150 };
151
154 template <class GT>
155 struct Show_Arcs
156 {
157 const std::set<typename GT::Arc *> * arcs = nullptr;
158
159 bool operator () (typename GT::Arc * a) const
160 {
161 return arcs->count(a) != 0;
162 }
163 };
164
166 std::vector<bool> shown_but(const Spec & s, unsigned long hidden)
167 {
168 std::vector<bool> r(s.num_arcs());
169 for (size_t i = 0; i < r.size(); ++i)
170 r[i] = graph_filters::shown(hidden, int(i));
171 return r;
172 }
173
175 std::vector<bool> shown_only(const Spec & s, unsigned long shown)
176 {
177 std::vector<bool> r(s.num_arcs());
178 for (size_t i = 0; i < r.size(); ++i)
179 r[i] = ((shown >> i) & 1UL) != 0;
180 return r;
181 }
182
184 const std::vector<long long> Small_Weights = {-2, -1, 0, 1, 2};
185
188 const std::vector<long long> Sign_Weights = {-2, 1};
189
192 const std::vector<long long> Unit_Weights = {-1, 0, 1};
193
196 Domain small_weights_domain()
197 {
198 Domain d;
199 d.max_nodes = heavy() ? 3 : 2;
200 d.max_arcs = 3;
201 return d;
202 }
203
206 Domain sign_domain()
207 {
208 return domain(3, 3);
209 }
210
213 template <class F>
214 void for_each_weighting(const Spec & s, const std::vector<long long> & values, F && f)
215 {
216 Spec t = s;
217 t.w.assign(s.num_arcs(), values[0]);
218 std::vector<size_t> k(s.num_arcs(), 0);
219 while (true)
220 {
221 f(static_cast<const Spec &>(t));
222 size_t i = 0;
223 for (; i < k.size(); ++i)
224 {
225 if (++k[i] < values.size())
226 {
227 t.w[i] = values[k[i]];
228 break;
229 }
230 k[i] = 0;
231 t.w[i] = values[0];
232 }
233 if (i == k.size())
234 return;
235 }
236 }
237
242 template <class F>
243 void for_each_weighted_spec(F && f, const std::vector<long long> & small_weights = Small_Weights)
244 {
245 const Domain small = small_weights_domain();
246 for_each_spec(small, true, [&] (const Spec & s)
247 {
248 for_each_weighting(s, small_weights, f);
249 });
250 for_each_spec(sign_domain(), true, [&] (const Spec & s)
251 {
252 if (s.n > small.max_nodes or int(s.num_arcs()) > small.max_arcs)
253 for_each_weighting(s, Sign_Weights, f);
254 });
255 }
256
258 struct Walk
259 {
260 std::vector<int> nodes;
261 std::vector<int> arcs;
262
263 [[nodiscard]] std::string str() const
264 {
265 std::string r = "[";
266 for (size_t i = 0; i < nodes.size(); ++i)
267 {
268 r += std::to_string(nodes[i]);
269 if (i < arcs.size())
270 r += " -" + std::to_string(arcs[i]) + "-> ";
271 }
272 return r + "]";
273 }
274 };
275
277 template <class GT, class Number>
278 Walk walk_of(const Path<GT> & p, Number && number)
279 {
280 Walk w;
281 for (typename Path<GT>::Iterator it(p); it.has_current_node(); it.next_ne())
282 {
283 w.nodes.push_back(num(it.get_current_node_ne()));
284 if (it.has_current_arc())
285 w.arcs.push_back(number(it.get_current_arc_ne()));
286 }
287 return w;
288 }
289
291 template <class GT>
292 Walk walk_of(const Path<GT> & p)
293 {
294 return walk_of(p, [] (typename GT::Arc * a) { return num(a); });
295 }
296
298 template <class Nodes, class Arcs>
299 Walk walk_of(const Nodes & nodes, const Arcs & arcs)
300 {
301 Walk w;
302 for (auto it = nodes.get_it(); it.has_curr(); it.next_ne())
303 w.nodes.push_back(num(it.get_curr()));
304 for (auto it = arcs.get_it(); it.has_curr(); it.next_ne())
305 w.arcs.push_back(num(it.get_curr()));
306 return w;
307 }
308
312 std::string walk_error(const Spec & s, const Walk & w, const std::vector<bool> & show)
313 {
314 if (w.nodes.empty() or w.nodes.size() != w.arcs.size() + 1)
315 return "the walk " + w.str() + " is empty or lacks arcs";
316 for (size_t i = 0; i < w.arcs.size(); ++i)
317 {
318 const int a = w.arcs[i];
319 if (a < 0 or size_t(a) >= s.arcs.size())
320 return "the walk " + w.str() + " has an arc that is not of the graph";
321 if (s.arcs[size_t(a)][0] != w.nodes[i] or s.arcs[size_t(a)][1] != w.nodes[i + 1])
322 return "the walk " + w.str() + " does not follow the arc " + std::to_string(a);
323 if (not show[size_t(a)])
324 return "the walk " + w.str() + " takes the hidden arc " + std::to_string(a);
325 }
326 return "";
327 }
328
332 std::string closed_walk_error(const Spec & s, const Walk & w,
333 const std::vector<bool> & show, bool simple)
334 {
335 if (auto e = walk_error(s, w, show); not e.empty())
336 return e;
337 if (w.arcs.empty() or w.nodes.front() != w.nodes.back())
338 return "the walk " + w.str() + " is not a closed one";
339 if (simple and std::set<int>(w.nodes.begin() + 1, w.nodes.end()).size() != w.arcs.size())
340 return "the cycle " + w.str() + " repeats a node";
341 return "";
342 }
343
345 long long cost_of(const Spec & s, const Walk & w)
346 {
347 long long c = 0;
348 for (int a : w.arcs)
349 c += s.w[size_t(a)];
350 return c;
351 }
352
355 struct Cycle
356 {
357 std::vector<int> arcs;
358 long long cost = 0;
359 };
360
364 std::vector<Cycle> simple_cycles(const Spec & s, const std::vector<bool> & show)
365 {
366 std::vector<Cycle> r;
367 std::vector<bool> on(size_t(s.n), false);
368 std::vector<int> arcs;
369 // Extends the path in arcs, from root to x at cost c, by each arc out
370 // of x: to root, which closes a cycle, or to a node above root that is
371 // not on the path
372 auto extend = [&] (auto & self, int root, int x, long long c) -> void
373 {
374 for (size_t i = 0; i < s.arcs.size(); ++i)
375 {
376 if (not show[i] or s.arcs[i][0] != x)
377 continue;
378 const int y = s.arcs[i][1];
379 arcs.push_back(int(i));
380 if (y == root)
381 r.push_back({arcs, c + s.w[i]});
382 else if (y > root and not on[size_t(y)])
383 {
384 on[size_t(y)] = true;
385 self(self, root, y, c + s.w[i]);
386 on[size_t(y)] = false;
387 }
388 arcs.pop_back();
389 }
390 };
391 for (int root = 0; root < s.n; ++root)
392 extend(extend, root, root, 0);
393 return r;
394 }
395
397 bool has_negative_cycle(const Spec & s, const std::vector<bool> & show)
398 {
399 for (const auto & c : simple_cycles(s, show))
400 if (c.cost < 0)
401 return true;
402 return false;
403 }
404
406 Spec shown_spec(const Spec & s, const std::vector<bool> & show)
407 {
408 unsigned long hidden = 0;
409 for (size_t i = 0; i < show.size(); ++i)
410 if (not show[i])
411 hidden |= 1UL << i;
412 std::vector<int> orig;
413 return oracle::without(s, hidden, orig);
414 }
415
418 struct Truth
419 {
420 std::vector<bool> show;
421 std::vector<Cycle> cycles;
422 std::vector<std::vector<bool>> reach;
423 std::vector<std::vector<long long>> dist;
424 bool negative = false;
425 std::vector<bool> negative_from;
426
427 Truth(const Spec & s, std::vector<bool> shown) : show(std::move(shown))
428 {
429 cycles = simple_cycles(s, show);
430 const Spec t = shown_spec(s, show);
431 reach = oracle::closure(t, true);
432 bool neg = false;
433 dist = oracle::shortest_distances(t, true, neg);
434 negative_from.assign(size_t(s.n), false);
435 for (const auto & c : cycles)
436 if (c.cost < 0)
437 {
438 negative = true;
439 const int x = s.arcs[size_t(c.arcs[0])][0];
440 for (int u = 0; u < s.n; ++u)
441 if (oracle::reaches(reach, u, x))
442 negative_from[size_t(u)] = true;
443 }
444 }
445
446 [[nodiscard]] bool reaches(int u, int v) const { return oracle::reaches(reach, u, v); }
447 };
448
452 std::vector<long long> potentials(const Truth & t, int n)
453 {
454 std::vector<long long> h(size_t(n), 0);
455 for (int u = 0; u < n; ++u)
456 for (int v = 0; v < n; ++v)
457 if (t.dist[size_t(u)][size_t(v)] != oracle::Inf)
458 h[size_t(v)] = std::min(h[size_t(v)], t.dist[size_t(u)][size_t(v)]);
459 return h;
460 }
461
464 bool least_mean(const Truth & t, long long & num, long long & den)
465 {
466 bool found = false;
467 for (const auto & c : t.cycles)
468 {
469 const long long len = (long long) c.arcs.size();
470 if (not found or c.cost * den < num * len)
471 {
472 num = c.cost;
473 den = len;
474 found = true;
475 }
476 }
477 return found;
478 }
479
482 bool least_cost(const Truth & t, size_t len, long long & cost, size_t & arcs)
483 {
484 bool found = false;
485 for (const auto & c : t.cycles)
486 if (c.arcs.size() <= len and
487 (not found or c.cost < cost or (c.cost == cost and c.arcs.size() < arcs)))
488 {
489 cost = c.cost;
490 arcs = c.arcs.size();
491 found = true;
492 }
493 return found;
494 }
495
500 bool least_closed_walk(const Spec & s, const std::vector<bool> & show, size_t len,
501 long long & cost)
502 {
503 bool found = false;
504 const size_t n = size_t(s.n);
505 for (int v = 0; v < s.n; ++v)
506 {
507 // cur[u]: the least cost of such a walk of k arcs from v to u
508 std::vector<long long> cur(n, oracle::Inf);
509 for (size_t i = 0; i < s.arcs.size(); ++i)
510 if (show[i] and s.arcs[i][0] == v)
511 cur[size_t(s.arcs[i][1])] = std::min(cur[size_t(s.arcs[i][1])], s.w[i]);
512 for (size_t k = 1; k <= len; ++k)
513 {
514 if (cur[size_t(v)] != oracle::Inf and (not found or cur[size_t(v)] < cost))
515 {
516 cost = cur[size_t(v)];
517 found = true;
518 }
519 std::vector<long long> next(n, oracle::Inf);
520 for (size_t i = 0; i < s.arcs.size(); ++i)
521 {
522 const int x = s.arcs[i][0], y = s.arcs[i][1];
523 if (show[i] and x != v and cur[size_t(x)] != oracle::Inf)
524 next[size_t(y)] = std::min(next[size_t(y)], cur[size_t(x)] + s.w[i]);
525 }
526 cur = std::move(next);
527 }
528 }
529 return found;
530 }
531
542 bool sums_may_overflow(const Spec & s, const std::vector<bool> & show,
543 long long lo, long long hi)
544 {
545 const size_t n = size_t(s.n), m = s.num_arcs();
546 long long most = 0;
547 std::vector<bool> on(n, false);
548 auto extend = [&] (auto & self, int x, long long c) -> void
549 {
550 most = std::max(most, c);
551 for (size_t i = 0; i < m; ++i)
552 if (show[i] and s.arcs[i][0] == x)
553 {
554 const int y = s.arcs[i][1];
555 most = std::max(most, c + s.w[i]);
556 if (not on[size_t(y)])
557 {
558 on[size_t(y)] = true;
559 self(self, y, c + s.w[i]);
560 on[size_t(y)] = false;
561 }
562 }
563 };
564 for (int x = 0; x < s.n; ++x)
565 {
566 on[size_t(x)] = true;
567 extend(extend, x, 0);
568 on[size_t(x)] = false;
569 }
570
571 const size_t k = (n + 4) * (m + n) + 1;
572 long long least = 0;
573 std::vector<long long> cur(n, 0);
574 for (size_t step = 0; step < k; ++step)
575 {
576 std::vector<long long> next(n, oracle::Inf);
577 for (size_t i = 0; i < m; ++i)
578 if (show[i] and cur[size_t(s.arcs[i][0])] != oracle::Inf)
579 next[size_t(s.arcs[i][1])] = std::min(next[size_t(s.arcs[i][1])],
580 cur[size_t(s.arcs[i][0])] + s.w[i]);
581 for (long long x : next)
582 if (x != oracle::Inf)
583 least = std::min(least, x);
584 cur = std::move(next);
585 }
586 return most > hi or least < lo;
587 }
588
593 bool walks_may_overflow(const Spec & s, const std::vector<bool> & show, size_t len,
594 long long lo, long long hi)
595 {
596 const size_t n = size_t(s.n);
597 // The costliest and the cheapest walk of k arcs that ends at each node
598 std::vector<long long> most(n, 0), least(n, 0);
599 std::vector<bool> ends(n, true);
600 for (size_t k = 1; k <= len; ++k)
601 {
602 std::vector<long long> next_most(n, std::numeric_limits<long long>::lowest());
603 std::vector<long long> next_least(n, std::numeric_limits<long long>::max());
604 std::vector<bool> next_ends(n, false);
605 for (size_t i = 0; i < s.num_arcs(); ++i)
606 {
607 const size_t x = size_t(s.arcs[i][0]), y = size_t(s.arcs[i][1]);
608 if (not show[i] or not ends[x])
609 continue;
610 next_ends[y] = true;
611 next_most[y] = std::max(next_most[y], most[x] + s.w[i]);
612 next_least[y] = std::min(next_least[y], least[x] + s.w[i]);
613 }
614 for (size_t v = 0; v < n; ++v)
615 if (next_ends[v] and (next_most[v] > hi or next_least[v] < lo))
616 return true;
617 most = std::move(next_most);
618 least = std::move(next_least);
619 ends = std::move(next_ends);
620 }
621 return false;
622 }
623
626 template <class GT, typename T>
627 struct Case
628 {
629 const Spec & s;
630 Built<GT> b;
631 std::vector<T> w;
632 Spec_Weight<GT, T> d;
633 Truth t;
636 std::string label;
639 bool may_overflow = false;
642 bool may_reject = false;
645 std::vector<bool> filtered;
648 std::optional<Truth> signs;
649
650 Case(const Spec & spec, std::vector<bool> show)
651 : s(spec), b(spec), w(spec.w.begin(), spec.w.end()), t(spec, std::move(show)),
652 filtered(t.show)
653 {
654 d.weights = &w;
655 }
656
657 Case(const Case &) = delete;
658 Case & operator = (const Case &) = delete;
659
660 [[nodiscard]] const std::vector<bool> & show() const noexcept { return t.show; }
661 };
662
663 template <class GT, typename T, class SA = Dft_Show_Arc<GT>>
665
668 template <class GT>
669 bool intact(const Built<GT> & b, const Spec & s)
670 {
671 if (b.g.get_num_nodes() != size_t(s.n) or b.g.get_num_arcs() != s.num_arcs())
672 return false;
673 for (size_t i = 0; i < b.arcs.size(); ++i)
674 if (num(b.arcs[i]) != int(i))
675 return false;
676 return true;
677 }
678
680 Spec with_signs(const Spec & s)
681 {
682 Spec t = s;
683 for (auto & w : t.w)
684 w = w < 0 ? -1 : w > 0 ? 1 : 0;
685 return t;
686 }
687
691 template <class GT, typename T>
692 std::string data_error(const Case<GT, T> & c)
693 {
694 for (auto * p : c.b.nodes)
695 if (NODE_COOKIE(p) != nullptr or IS_NODE_VISITED(p, Aleph::Depth_First)
697 return "the node " + std::to_string(num(p)) + " keeps its data or a bit";
698 for (auto * a : c.b.arcs)
700 return "the arc " + std::to_string(num(a)) + " keeps its bit";
701 return "";
702 }
703
706 template <class GT, typename T, class SA>
707 std::string state_error(const BF<GT, T, SA> & bf, const Case<GT, T> & c)
708 {
709 if (bf.has_computation() or bf.is_painted())
710 return "the object keeps a computation";
711 return data_error(c);
712 }
713
717 template <class GT, typename T, class SA>
718 std::string after_throw_error(BF<GT, T, SA> & bf, Case<GT, T> & c)
719 {
720 if (auto e = state_error(bf, c); not e.empty() or c.s.n == 0)
721 return e;
722 const Spec t = with_signs(c.s);
723 if (not c.signs)
724 c.signs.emplace(t, c.filtered);
725 const std::vector<T> weights = c.w;
726 for (size_t i = 0; i < c.w.size(); ++i)
727 c.w[i] = T(t.w[i]);
728 const bool negative = bf.paint_spanning_tree(c.b.nodes[0]);
729 c.w = weights;
730 return negative == c.signs->negative_from[0] ? "" : "it does not run again";
731 }
732
738 template <class GT, typename T, class SA, class Call>
739 bool returns(Check & k, BF<GT, T, SA> & bf, Case<GT, T> & c, const std::string & where,
740 Call && call)
741 {
742 try
743 {
744 call();
745 return true;
746 }
747 catch (const std::overflow_error & e)
748 {
749 k.run();
750 if (not c.may_overflow)
751 k.fail(c.s, c.label + where + "throws " + e.what());
752 else if (auto err = after_throw_error(bf, c); not err.empty())
753 k.fail(c.s, c.label + where + "after overflow_error, " + err);
754 return false;
755 }
756 catch (const std::domain_error &)
757 {
758 if (not c.may_reject)
759 throw;
760 k.run();
761 if (auto err = after_throw_error(bf, c); not err.empty())
762 k.fail(c.s, c.label + where + "after domain_error, " + err);
763 return false;
764 }
765 }
766
767 const char * says(bool found)
768 {
769 return found ? "finds a negative cycle where there is none" : "finds no negative cycle";
770 }
771
772 std::string from_text(int u)
773 {
774 return "from " + std::to_string(u) + ": ";
775 }
776
778 struct Detection_Checks
779 {
780 Check paint;
781 Check faster;
782 Check from;
783 Check global;
784 Check weights;
785 size_t turn = 0;
786
787 explicit Detection_Checks(const std::string & how = "")
788 : paint("Bellman_Ford::paint_spanning_tree()" + how),
789 faster("Bellman_Ford::faster_paint_spanning_tree()" + how),
790 from("Bellman_Ford::has_negative_cycle(start)" + how),
791 global("Bellman_Ford::has_negative_cycle()" + how),
792 weights("Bellman_Ford::compute_nodes_weights()" + how)
793 {}
794
795 void expect() const
796 {
797 for (const Check * c : {&paint, &faster, &from, &global, &weights})
798 c->expect();
799 }
800 };
801
804 template <class GT, typename T, class Map>
805 std::string potentials_error(const Case<GT, T> & c, const Map & m)
806 {
807 const auto h = potentials(c.t, c.s.n);
808 if (m.size() != size_t(c.s.n))
809 return "gives " + std::to_string(m.size()) + " potentials";
810 for (int v = 0; v < c.s.n; ++v)
811 {
812 const auto * p = m.search(c.b.nodes[size_t(v)]);
813 if (p == nullptr)
814 return "gives no potential to " + std::to_string(v);
815 if ((long double) p->second != (long double) h[size_t(v)])
816 return "gives " + std::to_string((long double) p->second) + " to "
817 + std::to_string(v) + ", not " + std::to_string(h[size_t(v)]);
818 }
819 return "";
820 }
821
825 template <class GT, typename T, class SA>
826 void run_detection(Detection_Checks & k, Case<GT, T> & c, const SA & sa)
827 {
828 const Spec & s = c.s;
829 const bool faster = k.turn++ % 2 == 1;
830 Check & paint = faster ? k.faster : k.paint;
831 for (int u = 0; u < s.n; ++u)
832 {
833 auto * p = c.b.nodes[size_t(u)];
834 const bool want = c.t.negative_from[size_t(u)];
835 const std::string from = from_text(u);
836 {
837 BF<GT, T, SA> bf(c.b.g, c.d, sa);
838 returns(paint, bf, c, from, [&]
839 {
840 const bool got = faster ? bf.faster_paint_spanning_tree(p)
841 : bf.paint_spanning_tree(p);
842 paint.run();
843 if (got != want)
844 paint.fail(s, c.label + from + says(got));
845 });
846 }
847 BF<GT, T, SA> bf(c.b.g, c.d, sa);
848 returns(k.from, bf, c, from, [&]
849 {
850 const bool got = bf.has_negative_cycle(p);
851 k.from.run();
852 if (got != want)
853 k.from.fail(s, c.label + from + says(got));
854 });
855 }
856
857 {
858 BF<GT, T, SA> bf(c.b.g, c.d, sa);
859 returns(k.global, bf, c, "", [&]
860 {
861 const bool got = bf.has_negative_cycle();
862 k.global.run();
863 if (got != c.t.negative)
864 k.global.fail(s, c.label + says(got));
865 else if (not intact(c.b, s))
866 k.global.fail(s, c.label + "leaves the graph changed");
867 });
868 }
869
870 BF<GT, T, SA> bf(c.b.g, c.d, sa);
871 returns(k.weights, bf, c, "", [&]
872 {
873 try
874 {
875 const auto m = bf.compute_nodes_weights();
876 k.weights.run();
877 if (c.t.negative)
878 k.weights.fail(s, c.label + "does not throw on a negative cycle");
879 else if (auto e = potentials_error(c, m); not e.empty())
880 k.weights.fail(s, c.label + e);
881 }
882 catch (const std::domain_error &)
883 {
884 k.weights.run();
885 if (not c.t.negative and not c.may_reject)
886 k.weights.fail(s, c.label + "throws domain_error without a negative cycle");
887 else if (auto e = state_error(bf, c); not e.empty())
888 k.weights.fail(s, c.label + "after domain_error, " + e);
889 }
890 });
891 if (not intact(c.b, s))
892 k.weights.fail(s, c.label + "leaves the graph changed");
893 }
894
900 template <class GT, typename T>
901 void check_witness(Check & k, const Case<GT, T> & c, const Path<GT> & path, bool want,
902 const std::string & where, const bool * found = nullptr)
903 {
904 k.run();
905 if (found != nullptr and *found == path.is_empty())
906 {
907 k.fail(c.s, c.label + where + "returns " + (*found ? "true" : "false") + " with a path of "
908 + std::to_string(path.size()) + " nodes");
909 return;
910 }
911 if (path.is_empty())
912 {
913 if (want)
914 k.fail(c.s, c.label + where + "finds no negative cycle");
915 return;
916 }
917 const Walk w = walk_of(path);
918 if (auto e = closed_walk_error(c.s, w, c.show(), true); not e.empty())
919 k.fail(c.s, c.label + where + e);
920 else if (const long long cost = cost_of(c.s, w); cost >= 0)
921 k.fail(c.s, c.label + where + "the cycle " + w.str() + " costs " + std::to_string(cost));
922 else if (not want)
923 k.fail(c.s, c.label + where + "finds the negative cycle " + w.str()
924 + ", that the oracle lacks");
925 }
926
930 const std::pair<double, size_t> Steps[] = {{0.0, 1}, {0.5, 1}, {1.0, 2}, {4.0, 1}};
931
934 struct Witness_Checks
935 {
936 Check test;
937 Check test_path;
939 Check steps;
940 size_t turn = 0;
941
942 Witness_Checks(bool global, const std::string & how)
943 : test(std::string("Bellman_Ford::test_negative_cycle(")
944 + (global ? "" : "start") + ")" + how),
945 test_path(std::string("Bellman_Ford::test_negative_cycle(")
946 + (global ? "path" : "start, path") + ")" + how),
947 search(std::string("Bellman_Ford::search_negative_cycle(")
948 + (global ? "" : "start") + ")" + how),
949 steps(std::string("Bellman_Ford::search_negative_cycle(")
950 + (global ? "" : "start, ") + "it_factor, step)" + how)
951 {}
952
953 void expect() const
954 {
955 for (const Check * c : {&test, &test_path, &search, &steps})
956 c->expect();
957 }
958 };
959
965 template <class GT, typename T, class SA>
966 void run_witnesses(Witness_Checks & k, Case<GT, T> & c, const SA & sa, bool global)
967 {
968 const size_t turn = k.turn++;
969 // Not a structured binding, which Clang 14 does not capture in a lambda
970 const double factor = Steps[(turn / 4) % std::size(Steps)].first;
971 const size_t step = Steps[(turn / 4) % std::size(Steps)].second;
972 const bool with_path = turn % 2 == 1;
973 const bool with_steps = (turn / 2) % 2 == 1;
974 const std::string with = "with " + text_of(factor) + " and " + text_of(step) + ": ";
975
976 // The searches from u, or from no start if u is -1
977 auto searches = [&] (int u)
978 {
979 typename GT::Node * p = u < 0 ? nullptr : c.b.nodes[size_t(u)];
980 const bool want = u < 0 ? c.t.negative : c.t.negative_from[size_t(u)];
981 const std::string from = u < 0 ? std::string() : from_text(u);
982 {
983 Check & test = with_path ? k.test_path : k.test;
984 BF<GT, T, SA> bf(c.b.g, c.d, sa);
985 returns(test, bf, c, from, [&]
986 {
987 if (not with_path)
988 check_witness(test, c, u < 0 ? bf.test_negative_cycle() : bf.test_negative_cycle(p),
989 want, from);
990 else
991 {
992 Path<GT> path(c.b.g);
993 const bool found = u < 0 ? bf.test_negative_cycle(path)
994 : bf.test_negative_cycle(p, path);
995 check_witness(test, c, path, want, from, &found);
996 }
997 });
998 }
999 Check & search = with_steps ? k.steps : k.search;
1000 BF<GT, T, SA> bf(c.b.g, c.d, sa);
1001 returns(search, bf, c, from, [&]
1002 {
1003 if (not with_steps)
1004 check_witness(search, c,
1005 u < 0 ? bf.search_negative_cycle() : bf.search_negative_cycle(p),
1006 want, from);
1007 else
1008 check_witness(search, c,
1009 std::get<0>(u < 0 ? bf.search_negative_cycle(factor, step)
1010 : bf.search_negative_cycle(p, factor, step)),
1011 want, from + with);
1012 });
1013 };
1014
1015 if (not global)
1016 for (int u = 0; u < c.s.n; ++u)
1017 searches(u);
1018 else
1019 {
1020 searches(-1);
1021 if (not intact(c.b, c.s))
1022 k.test.fail(c.s, c.label + "a search leaves the graph changed");
1023 }
1024 }
1025
1028 struct Functor_Checks
1029 {
1030 Check path;
1031 Check start_path;
1032 Check start;
1033 Check graph;
1034 size_t turn = 0;
1035
1036 explicit Functor_Checks(const std::string & how)
1037 : path("Bellman_Ford_Negative_Cycle(g, path, d, sa)" + how),
1038 start_path("Bellman_Ford_Negative_Cycle(g, start, path, d, sa)" + how),
1039 start("Bellman_Ford_Negative_Cycle(g, start, d, sa)" + how),
1040 graph("Bellman_Ford_Negative_Cycle(g, d, sa)" + how)
1041 {}
1042
1043 void expect() const
1044 {
1045 for (const Check * c : {&path, &start_path, &start, &graph})
1046 c->expect();
1047 }
1048 };
1049
1052 std::vector<int> ends_of(const Spec & s)
1053 {
1054 if (s.n == 0)
1055 return {};
1056 if (s.n == 1)
1057 return {0};
1058 return {0, s.n - 1};
1059 }
1060
1065 template <template <class, class> class NAit, class GT, typename T, class SA>
1066 void run_functors(Functor_Checks & k, Case<GT, T> & c, const SA & sa)
1067 {
1068 using D = Spec_Weight<GT, T>;
1070 const size_t turn = k.turn++;
1071 const bool lvalues = turn % 2 == 0;
1072 const bool with_path = (turn / 2) % 2 == 0;
1073 const std::string how = lvalues ? "lvalues: " : "rvalues: ";
1074 D d = c.d;
1075 SA a = sa;
1076 // A call that throws fails its check, and the others still run
1077 auto guarded = [&] (Check & k, const std::string & where, auto && call)
1078 {
1079 try
1080 {
1081 call();
1082 }
1083 catch (const std::exception & e)
1084 {
1085 k.run();
1086 k.fail(c.s, c.label + where + "throws " + e.what());
1087 }
1088 };
1089 {
1090 const bool want = c.t.negative;
1091 if (with_path)
1092 guarded(k.path, how, [&]
1093 {
1094 Path<GT> path(c.b.g);
1095 const bool found = lvalues ? F()(c.b.g, path, d, a) : F()(c.b.g, path, D(d), SA(a));
1096 check_witness(k.path, c, path, want, how, &found);
1097 });
1098 else
1099 guarded(k.graph, how, [&]
1100 {
1101 check_witness(k.graph, c, lvalues ? F()(c.b.g, d, a) : F()(c.b.g, D(d), SA(a)), want,
1102 how);
1103 });
1104 if (not intact(c.b, c.s))
1105 k.graph.fail(c.s, c.label + "a search leaves the graph changed");
1106 }
1107 for (int u : ends_of(c.s))
1108 {
1109 auto * p = c.b.nodes[size_t(u)];
1110 const bool want = c.t.negative_from[size_t(u)];
1111 const std::string where = how + from_text(u);
1112 if (with_path)
1113 guarded(k.start_path, where, [&]
1114 {
1115 Path<GT> path(c.b.g);
1116 const bool found = lvalues ? F()(c.b.g, p, path, d, a)
1117 : F()(c.b.g, p, path, D(d), SA(a));
1118 check_witness(k.start_path, c, path, want, where, &found);
1119 });
1120 else
1121 guarded(k.start, where, [&]
1122 {
1123 check_witness(k.start, c,
1124 lvalues ? F()(c.b.g, p, d, a) : F()(c.b.g, p, D(d), SA(a)), want,
1125 where);
1126 });
1127 }
1128 }
1129
1131 template <class GT>
1132 std::set<int> painted_arcs(const Built<GT> & b)
1133 {
1134 std::set<int> r;
1135 for (size_t i = 0; i < b.arcs.size(); ++i)
1137 r.insert(int(i));
1138 return r;
1139 }
1140
1145 template <class GT, typename T>
1146 std::string painting_error(const Case<GT, T> & c, int u, const std::set<int> & painted)
1147 {
1148 const Spec & s = c.s;
1149 std::vector<int> into(size_t(s.n), 0);
1150 for (int i : painted)
1151 {
1152 const int x = s.arcs[size_t(i)][0], y = s.arcs[size_t(i)][1];
1153 if (not c.show()[size_t(i)])
1154 return "paints the hidden arc " + std::to_string(i);
1155 if (not c.t.reaches(u, x) or y == u)
1156 return "paints the arc " + std::to_string(i) + ", out of the tree";
1157 if (c.t.dist[size_t(u)][size_t(x)] + s.w[size_t(i)] != c.t.dist[size_t(u)][size_t(y)])
1158 return "paints the arc " + std::to_string(i) + ", which is not on a shortest path";
1159 ++into[size_t(y)];
1160 }
1161 for (int v = 0; v < s.n; ++v)
1162 {
1163 if (IS_NODE_VISITED(c.b.nodes[size_t(v)], Aleph::Spanning_Tree) != c.t.reaches(u, v))
1164 return "paints the node " + std::to_string(v) + " wrongly";
1165 if (v != u and c.t.reaches(u, v) and into[size_t(v)] != 1)
1166 return "paints " + std::to_string(into[size_t(v)]) + " arcs into " + std::to_string(v);
1167 }
1168 return "";
1169 }
1170
1175 template <class GT, typename T, class SA>
1176 std::string distances_error(BF<GT, T, SA> & bf, const Case<GT, T> & c, int u,
1177 bool domain_error_is_right = false)
1178 {
1179 for (int v = 0; v < c.s.n; ++v)
1180 {
1181 const bool reached = c.t.reaches(u, v);
1182 try
1183 {
1184 const T got = bf.get_distance(c.b.nodes[size_t(v)]);
1185 if (not reached)
1186 return "gives a distance to " + std::to_string(v) + ", which is not reached";
1187 if ((long double) got != (long double) c.t.dist[size_t(u)][size_t(v)])
1188 return "gives " + text_of(got) + " to " + std::to_string(v) + ", not "
1189 + std::to_string(c.t.dist[size_t(u)][size_t(v)]);
1190 }
1191 catch (const std::domain_error &)
1192 {
1193 if (reached and not domain_error_is_right)
1194 return "throws domain_error for " + std::to_string(v) + ", which is reached";
1195 }
1196 }
1197 return "";
1198 }
1199
1203 template <class GT, typename T>
1204 std::string min_path_error(const Case<GT, T> & c, const Path<GT> & path, int u, int v, T got)
1205 {
1206 const Walk w = walk_of(path);
1207 if (auto e = walk_error(c.s, w, c.show()); not e.empty())
1208 return e;
1209 if (w.nodes.front() != u or w.nodes.back() != v)
1210 return "the path " + w.str() + " does not go from " + std::to_string(u) + " to "
1211 + std::to_string(v);
1212 if (std::set<int>(w.nodes.begin(), w.nodes.end()).size() != w.nodes.size())
1213 return "the path " + w.str() + " repeats a node";
1214 const long long want = c.t.dist[size_t(u)][size_t(v)];
1215 if (cost_of(c.s, w) != want or (long double) got != (long double) want)
1216 return "the path " + w.str() + " costs " + std::to_string(cost_of(c.s, w)) + " and "
1217 + text_of(got) + " is returned, not " + std::to_string(want);
1218 return "";
1219 }
1220
1224 template <class GT, typename T, class SA>
1225 std::string min_paths_error(BF<GT, T, SA> & bf, const Case<GT, T> & c, int u,
1226 bool domain_error_is_right = false)
1227 {
1228 for (int v = 0; v < c.s.n; ++v)
1229 {
1230 const bool reached = c.t.reaches(u, v);
1231 try
1232 {
1233 Path<GT> path(c.b.g);
1234 const T got = bf.get_min_path(c.b.nodes[size_t(v)], path);
1235 if (not reached)
1236 return "gives a path to " + std::to_string(v) + ", which is not reached";
1237 if (auto e = min_path_error(c, path, u, v, got); not e.empty())
1238 return e;
1239 }
1240 catch (const std::domain_error &)
1241 {
1242 if (reached and not domain_error_is_right)
1243 return "throws domain_error for " + std::to_string(v) + ", which is reached";
1244 }
1245 }
1246 return "";
1247 }
1248
1253 template <class GT>
1254 std::string tree_error(const Spec & s, const GT & tree, const std::set<int> & painted)
1255 {
1256 std::multiset<int> nodes, want_nodes;
1257 for (auto it = tree.get_node_it(); it.has_curr(); it.next_ne())
1258 nodes.insert(num(it.get_curr()));
1259 for (int v = 0; v < s.n; ++v)
1260 want_nodes.insert(v);
1261 if (nodes != want_nodes)
1262 return "the tree has " + std::to_string(nodes.size()) + " nodes, not those of the graph";
1263 std::multiset<std::array<int, 3>> arcs, want_arcs;
1264 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
1265 {
1266 auto * a = it.get_curr();
1267 arcs.insert({num(a), num(tree.get_src_node(a)), num(tree.get_tgt_node(a))});
1268 }
1269 for (int i : painted)
1270 want_arcs.insert({i, s.arcs[size_t(i)][0], s.arcs[size_t(i)][1]});
1271 if (arcs != want_arcs)
1272 return "the tree has " + std::to_string(arcs.size()) + " arcs, not the "
1273 + std::to_string(painted.size()) + " painted ones";
1274 return "";
1275 }
1276
1280 template <class GT>
1281 std::string mapping_error(const Built<GT> & b, const GT & tree, const std::set<int> & painted)
1282 {
1283 std::set<typename GT::Node *> nodes;
1284 for (auto it = tree.get_node_it(); it.has_curr(); it.next_ne())
1285 nodes.insert(it.get_curr());
1286 std::set<typename GT::Arc *> arcs;
1287 for (auto it = tree.get_arc_it(); it.has_curr(); it.next_ne())
1288 arcs.insert(it.get_curr());
1289 for (size_t v = 0; v < b.nodes.size(); ++v)
1290 {
1291 auto * p = b.nodes[v];
1292 auto * q = static_cast<typename GT::Node *>(NODE_COOKIE(p));
1293 if (nodes.count(q) == 0 or num(q) != int(v) or NODE_COOKIE(q) != p)
1294 return "the node " + std::to_string(v) + " is not mapped to its image";
1295 }
1296 for (int i : painted)
1297 {
1298 auto * a = b.arcs[size_t(i)];
1299 auto * q = static_cast<typename GT::Arc *>(ARC_COOKIE(a));
1300 if (arcs.count(q) == 0 or num(q) != i or ARC_COOKIE(q) != a)
1301 return "the arc " + std::to_string(i) + " is not mapped to its image";
1302 }
1303 return "";
1304 }
1305
1308 struct Tree_Checks
1309 {
1310 Check painted;
1311 Check state;
1312 Check distance;
1313 Check path;
1314 Check extract;
1315 Check tree;
1316 Check mapped;
1317 Check mapped_path;
1318 Check mapped_distance;
1319 Check mapped_build;
1320 Check unpainted;
1321 Check unpainted_build;
1322 size_t turn = 0;
1323
1324 explicit Tree_Checks(const std::string & how = "")
1325 : painted("Bellman_Ford, the painted tree" + how),
1326 state("Bellman_Ford, the state after painting" + how),
1327 distance("Bellman_Ford::get_distance()" + how),
1328 path("Bellman_Ford::get_min_path()" + how),
1329 extract("Bellman_Ford::extract_min_spanning_tree()" + how),
1330 tree("Bellman_Ford::build_tree(tree, false)" + how),
1331 mapped("Bellman_Ford::build_tree(tree)" + how),
1332 mapped_path("Bellman_Ford::get_min_path(), after build_tree(tree)" + how),
1333 mapped_distance("Bellman_Ford::get_distance(), after build_tree(tree)" + how),
1334 mapped_build("Bellman_Ford::build_tree(tree), after build_tree(tree)" + how),
1335 unpainted("Bellman_Ford, the queries without a painted tree" + how),
1336 unpainted_build("Bellman_Ford::build_tree(tree, false), without a painted tree" + how)
1337 {}
1338
1339 void expect() const
1340 {
1341 for (const Check * c : {&painted, &state, &distance, &path, &extract, &tree, &mapped,
1342 &mapped_path, &mapped_distance, &mapped_build, &unpainted,
1343 &unpainted_build})
1344 c->expect();
1345 }
1346 };
1347
1350 template <class GT, typename T, class SA>
1351 void check_unpainted_build(Check & k, BF<GT, T, SA> & bf, const Spec & s,
1352 const std::string & where)
1353 {
1354 k.run();
1355 try
1356 {
1357 GT tree;
1358 bf.build_tree(tree, false);
1359 k.fail(s, where + "builds a tree of " + std::to_string(tree.get_num_arcs()) + " arcs");
1360 }
1361 catch (const std::domain_error &)
1362 {
1363 // there is no painted tree
1364 }
1365 catch (const std::exception & e)
1366 {
1367 k.fail(s, where + "throws " + e.what());
1368 }
1369 }
1370
1373 template <class GT, typename T, class SA>
1374 void check_unpainted(Tree_Checks & k, BF<GT, T, SA> & bf, const Case<GT, T> & c, int u,
1375 const std::string & where)
1376 {
1377 auto * p = c.b.nodes[size_t(u)];
1378 k.unpainted.run();
1379 int thrown = 0;
1380 auto count = [&] (auto && call)
1381 {
1382 try
1383 {
1384 call();
1385 }
1386 catch (const std::domain_error &)
1387 {
1388 ++thrown;
1389 }
1390 };
1391 count([&] { bf.get_distance(p); });
1392 count([&] { Path<GT> path(c.b.g); bf.get_min_path(p, path); });
1393 count([&] { bf.extract_min_spanning_tree(); });
1394 count([&] { GT tree; bf.build_tree(tree); });
1395 if (bf.is_painted() or thrown != 4)
1396 k.unpainted.fail(c.s, c.label + where + std::to_string(4 - thrown)
1397 + " of 4 queries do not throw domain_error");
1398 check_unpainted_build(k.unpainted_build, bf, c.s, c.label + where);
1399 }
1400
1406 template <class GT, typename T, class SA>
1407 void run_tree(Tree_Checks & k, Case<GT, T> & c, const SA & sa)
1408 {
1409 const Spec & s = c.s;
1410 if (s.n == 0)
1411 return;
1412 const size_t turn = k.turn++;
1413 const bool faster = turn % 2 == 1;
1414 const int u = (turn / 2) % 2 == 0 ? 0 : s.n - 1;
1415 const std::string where = from_text(u) + (faster ? "SPFA: " : "");
1416 auto * p = c.b.nodes[size_t(u)];
1417 BF<GT, T, SA> bf(c.b.g, c.d, sa);
1418 bool negative = false;
1419 if (not returns(k.painted, bf, c, where, [&]
1420 {
1421 negative = faster ? bf.faster_paint_spanning_tree(p) : bf.paint_spanning_tree(p);
1422 k.painted.run();
1423 }))
1424 return;
1425 if (negative != c.t.negative_from[size_t(u)])
1426 {
1427 k.painted.fail(s, c.label + where + says(negative));
1428 return;
1429 }
1430 if (negative)
1431 {
1432 check_unpainted(k, bf, c, u, where);
1433 return;
1434 }
1435
1436 const auto painted = painted_arcs(c.b);
1437 if (auto e = painting_error(c, u, painted); not e.empty())
1438 k.painted.fail(s, c.label + where + e);
1439
1440 k.state.run();
1441 if (not bf.is_painted() or not bf.has_computation() or bf.get_start_node() != p
1442 or &bf.get_graph() != &c.b.g)
1443 k.state.fail(s, c.label + where + "the getters do not tell the painting");
1444
1445 k.distance.run();
1446 if (auto e = distances_error(bf, c, u); not e.empty())
1447 k.distance.fail(s, c.label + where + e);
1448
1449 k.path.run();
1450 if (auto e = min_paths_error(bf, c, u); not e.empty())
1451 k.path.fail(s, c.label + where + e);
1452
1453 k.extract.run();
1454 {
1455 const auto arcs = bf.extract_min_spanning_tree();
1456 std::set<int> got;
1457 for (size_t i = 0; i < arcs.size(); ++i)
1458 if (arcs(i) != nullptr)
1459 got.insert(num(arcs(i)));
1460 if (got != painted)
1461 k.extract.fail(s, c.label + where + "gives " + std::to_string(got.size())
1462 + " arcs, not the " + std::to_string(painted.size()) + " painted ones");
1463 }
1464
1465 // Without the mapping, the cookies keep the parents
1466 k.tree.run();
1467 {
1468 GT tree;
1469 bf.build_tree(tree, false);
1470 if (auto e = tree_error(s, tree, painted); not e.empty())
1471 k.tree.fail(s, c.label + where + e);
1472 else if (auto e2 = distances_error(bf, c, u); not e2.empty())
1473 k.tree.fail(s, c.label + where + "after it, get_distance() " + e2);
1474 }
1475
1476 k.mapped.run();
1477 GT tree;
1478 bf.build_tree(tree);
1479 if (auto e = tree_error(s, tree, painted); not e.empty())
1480 k.mapped.fail(s, c.label + where + e);
1481 else if (auto e2 = mapping_error(c.b, tree, painted); not e2.empty())
1482 k.mapped.fail(s, c.label + where + e2);
1483
1484 // Once the cookies map the tree, the queries that read the parents
1485 // may give the right answer or throw domain_error
1486 k.mapped_path.run();
1487 if (auto e = min_paths_error(bf, c, u, true); not e.empty())
1488 k.mapped_path.fail(s, c.label + where + e);
1489
1490 k.mapped_distance.run();
1491 if (auto e = distances_error(bf, c, u, true); not e.empty())
1492 k.mapped_distance.fail(s, c.label + where + e);
1493
1494 k.mapped_build.run();
1495 try
1496 {
1497 GT again;
1498 bf.build_tree(again);
1499 if (auto e = tree_error(s, again, painted); not e.empty())
1500 k.mapped_build.fail(s, c.label + where + e);
1501 }
1502 catch (const std::domain_error &)
1503 {
1504 // it may refuse to read the parents
1505 }
1506 catch (const std::exception & e)
1507 {
1508 k.mapped_build.fail(s, c.label + where + "throws " + e.what());
1509 }
1510 }
1511
1513 struct Search_Checks
1514 {
1515 Check disjoint;
1516 Check disjoint_all;
1517 Check disjoint_none;
1518 Check bounded;
1519 Check bounded_none;
1520 Check short_cycle;
1521 Check short_bounds;
1522
1523 explicit Search_Checks(const std::string & how = "")
1524 : disjoint("find_disjoint_negative_cycles(), Min_Weight_Arc" + how),
1525 disjoint_all("find_disjoint_negative_cycles(), All_Arcs" + how),
1526 disjoint_none("find_disjoint_negative_cycles(), max_cycles 0" + how),
1527 bounded("most_negative_cycle_bounded()" + how),
1528 bounded_none("most_negative_cycle_bounded(), max_length 0" + how),
1529 short_cycle("most_negative_cycle_up_to_3()" + how),
1530 short_bounds("most_negative_cycle_up_to_3(), max_length 0 and 4" + how)
1531 {}
1532
1533 void expect() const
1534 {
1535 for (const Check * c : {&disjoint, &disjoint_all, &disjoint_none, &bounded, &bounded_none,
1536 &short_cycle, &short_bounds})
1537 c->expect();
1538 }
1539 };
1540
1548 template <class GT, typename T, class Items>
1549 std::string disjoint_error(const Case<GT, T> & c, const Items & items, size_t max_cycles,
1550 Negative_Cycle_Exclusion exclusion)
1551 {
1552 const Spec & s = c.s;
1553 std::vector<std::vector<int>> cycles;
1554 std::vector<bool> left = c.show();
1555 for (auto it = items.get_it(); it.has_curr(); it.next_ne())
1556 {
1557 const auto & item = it.get_curr();
1558 const Walk w = walk_of(item.cycle);
1559 if (auto e = closed_walk_error(s, w, c.show(), true); not e.empty())
1560 return e;
1561 if (not item.cycle.is_cycle() or item.length != w.arcs.size())
1562 return "the cycle " + w.str() + " has the length " + std::to_string(item.length);
1563 const long long cost = cost_of(s, w);
1564 if (cost >= 0 or (long double) item.total_cost != (long double) cost)
1565 return "the cycle " + w.str() + " costs " + std::to_string(cost) + ", and "
1566 + text_of(item.total_cost) + " is given";
1567 std::vector<int> arcs = w.arcs;
1568 std::sort(arcs.begin(), arcs.end());
1569 for (const auto & other : cycles)
1570 {
1571 if (other == arcs)
1572 return "the cycle " + w.str() + " is given twice";
1573 if (exclusion == Negative_Cycle_Exclusion::All_Arcs)
1574 for (int a : arcs)
1575 if (std::binary_search(other.begin(), other.end(), a))
1576 return "the cycle " + w.str() + " shares the arc " + std::to_string(a);
1577 }
1578 cycles.push_back(arcs);
1579
1580 // The arcs that the exclusion may have taken: all, or those of
1581 // least weight
1582 long long least = s.w[size_t(arcs[0])];
1583 for (int a : arcs)
1584 least = std::min(least, s.w[size_t(a)]);
1585 for (int a : arcs)
1586 if (exclusion == Negative_Cycle_Exclusion::All_Arcs or s.w[size_t(a)] == least)
1587 left[size_t(a)] = false;
1588 }
1589 if (cycles.size() > max_cycles)
1590 return "gives " + std::to_string(cycles.size()) + " cycles";
1591 if (cycles.empty() != not c.t.negative)
1592 return cycles.empty() ? "finds no negative cycle" : "finds a negative cycle";
1593 if (cycles.size() < max_cycles and has_negative_cycle(s, left))
1594 return "stops after " + std::to_string(cycles.size()) + " cycles, with a negative one left";
1595 return "";
1596 }
1597
1603 template <class GT, typename T, class Result>
1604 std::string bounded_error(const Case<GT, T> & c, const Result & r, size_t len)
1605 {
1606 const Spec & s = c.s;
1607 const size_t bound = std::min(len, size_t(s.n));
1608 long long least = 0;
1609 size_t fewest = 0;
1610 const bool has = least_cost(c.t, bound, least, fewest);
1611 if (r.has_cycle != has)
1612 return has ? "finds no cycle" : "finds a cycle where there is none";
1613 if (not has)
1614 return r.is_negative() ? "is negative without a cycle" : "";
1615 const Walk w = walk_of(r.cycle_nodes, r.cycle_arcs);
1616 if (auto e = closed_walk_error(s, w, c.show(), true); not e.empty())
1617 return e;
1618 const long long cost = cost_of(s, w);
1619 if (w.arcs.size() > bound or r.length != w.arcs.size())
1620 return "the cycle " + w.str() + " has the length " + std::to_string(r.length);
1621 if ((long double) r.total_cost != (long double) cost)
1622 return "the cycle " + w.str() + " costs " + std::to_string(cost) + ", and "
1623 + text_of(r.total_cost) + " is given";
1624 if (r.is_negative() != (least < 0))
1625 return "is_negative() is wrong: the least cost is " + std::to_string(least);
1626 const long double gap = (long double) r.optimality_gap;
1627 if (gap < 0 or r.is_exact != (gap == 0) or (long double) cost - gap > (long double) least
1628 or (r.is_exact and cost != least))
1629 return "the cycle costs " + std::to_string(cost) + " with the gap "
1630 + text_of(r.optimality_gap) + (r.is_exact ? ", exact" : "") + ", and the least cost is "
1631 + std::to_string(least);
1632 if constexpr (std::is_integral_v<T>)
1633 {
1634 long long relaxed = 0;
1635 least_closed_walk(s, c.show(), bound, relaxed);
1636 // The gap saturates at max() if it overflows
1637 const long long gap_want =
1638 std::min<long long>(cost - relaxed, std::numeric_limits<T>::max());
1639 if (r.numeric_quality != Cycle_Numeric_Quality::Exact
1640 or r.matches_relaxed_bound != r.is_exact or (long long) r.optimality_gap != gap_want)
1641 return "the gap " + text_of(r.optimality_gap) + " is not the distance from "
1642 + std::to_string(cost) + " to the relaxed bound " + std::to_string(relaxed);
1643 }
1644 return "";
1645 }
1646
1650 template <class GT, typename T, class Result>
1651 std::string short_error(const Case<GT, T> & c, const Result & r, size_t len)
1652 {
1653 const Spec & s = c.s;
1654 long long least = 0;
1655 size_t fewest = 0;
1656 const bool has = least_cost(c.t, len, least, fewest);
1657 if (r.has_cycle != has)
1658 return has ? "finds no cycle" : "finds a cycle where there is none";
1659 if (not has)
1660 return r.is_negative() or not r.cycle_arcs.is_empty() ? "gives a cycle" : "";
1661 const Walk w = walk_of(r.cycle_nodes, r.cycle_arcs);
1662 if (auto e = closed_walk_error(s, w, c.show(), true); not e.empty())
1663 return e;
1664 const long long cost = cost_of(s, w);
1665 if (cost != least or (long double) r.total_cost != (long double) least)
1666 return "the cycle " + w.str() + " costs " + std::to_string(cost) + ", and "
1667 + text_of(r.total_cost) + " is given, not " + std::to_string(least);
1668 if (r.length != w.arcs.size() or r.length != fewest)
1669 return "the cycle " + w.str() + " has the length " + std::to_string(r.length) + ", not "
1670 + std::to_string(fewest);
1671 if (r.is_negative() != (least < 0))
1672 return "is_negative() is wrong";
1673 return "";
1674 }
1675
1678 template <class GT, typename T, class SA>
1679 void run_searches(Search_Checks & k, Case<GT, T> & c, const SA & sa)
1680 {
1681 const GT & g = c.b.g;
1682 const Spec & s = c.s;
1683 for (auto exclusion : {Negative_Cycle_Exclusion::Min_Weight_Arc,
1684 Negative_Cycle_Exclusion::All_Arcs})
1685 for (size_t max_cycles : {size_t(1), size_t(64)})
1686 {
1687 Check & check = exclusion == Negative_Cycle_Exclusion::All_Arcs ? k.disjoint_all
1688 : k.disjoint;
1689 check.run();
1690 const auto items = find_disjoint_negative_cycles(g, max_cycles, exclusion, c.d, sa);
1691 if (auto e = disjoint_error(c, items, max_cycles, exclusion); not e.empty())
1692 check.fail(s, c.label + "up to " + std::to_string(max_cycles) + ": " + e);
1693 }
1694
1695 k.disjoint_none.run();
1696 if (not find_disjoint_negative_cycles(g, 0, Negative_Cycle_Exclusion::Min_Weight_Arc, c.d, sa)
1697 .is_empty())
1698 k.disjoint_none.fail(s, c.label + "gives cycles");
1699
1700 // A bound of n + 1 is cut to n, which for 3 nodes is 3
1701 for (size_t len : {size_t(1), size_t(2), size_t(s.n + 1)})
1702 {
1703 k.bounded.run();
1704 const auto r = most_negative_cycle_bounded(g, len, c.d, sa);
1705 if (auto e = bounded_error(c, r, len); not e.empty())
1706 k.bounded.fail(s, c.label + "up to " + std::to_string(len) + " arcs: " + e);
1707 }
1708
1709 k.bounded_none.run();
1710 if (const auto r = most_negative_cycle_bounded(g, 0, c.d, sa);
1711 r.has_cycle or r.is_negative() or not r.cycle_arcs.is_empty())
1712 k.bounded_none.fail(s, c.label + "gives a cycle");
1713
1714 for (size_t len : {size_t(1), size_t(2), size_t(3)})
1715 {
1716 k.short_cycle.run();
1717 const auto r = most_negative_cycle_up_to_3(g, len, c.d, sa);
1718 if (auto e = short_error(c, r, len); not e.empty())
1719 k.short_cycle.fail(s, c.label + "up to " + std::to_string(len) + " arcs: " + e);
1720 }
1721
1722 k.short_bounds.run();
1723 if (const auto r = most_negative_cycle_up_to_3(g, 0, c.d, sa); r.has_cycle)
1724 k.short_bounds.fail(s, c.label + "gives a cycle of no arc");
1725 try
1726 {
1727 most_negative_cycle_up_to_3(g, 4, c.d, sa);
1728 k.short_bounds.fail(s, c.label + "takes 4 arcs");
1729 }
1730 catch (const std::invalid_argument &)
1731 {
1732 // what the documentation says
1733 }
1734 }
1735
1737 struct Mean_Checks
1738 {
1739 Check karp;
1740 Check karp_value;
1741 Check aliases;
1742 Check functors;
1743 Check howard;
1744 Check howard_value;
1745 Check howard_limit;
1746 Check fallback;
1747 Check fallback_limit;
1748 size_t turn = 0;
1749
1750 explicit Mean_Checks(const std::string & how = "")
1751 : karp("karp_minimum_mean_cycle()" + how),
1752 karp_value("karp_minimum_mean_cycle_value()" + how),
1753 aliases("minimum_mean_cycle() and minimum_mean_cycle_value()" + how),
1754 functors("Karp_Minimum_Mean_Cycle and Karp_Minimum_Mean_Cycle_Value" + how),
1755 howard("howard_minimum_mean_cycle()" + how),
1756 howard_value("howard_minimum_mean_cycle_value()" + how),
1757 howard_limit("howard_minimum_mean_cycle() and its value, without bytes" + how),
1758 fallback("howard_detail::minimum_mean_cycle(), without iterations" + how),
1759 fallback_limit("howard_detail::minimum_mean_cycle(), without iterations nor bytes" + how)
1760 {}
1761
1762 void expect() const
1763 {
1764 for (const Check * c : {&karp, &karp_value, &aliases, &functors, &howard, &howard_value,
1765 &howard_limit, &fallback, &fallback_limit})
1766 c->expect();
1767 }
1768 };
1769
1773 template <class GT, typename T>
1774 long double least_mean_value(const Case<GT, T> & c, bool & has, long long & num,
1775 long long & den)
1776 {
1777 num = 0;
1778 den = 1;
1779 has = least_mean(c.t, num, den);
1780 return has ? (long double) num / (long double) den
1781 : std::numeric_limits<long double>::infinity();
1782 }
1783
1788 template <class GT, typename T, class Result>
1789 std::string mean_error(const Case<GT, T> & c, const Result & r)
1790 {
1791 bool has = false;
1792 long long num = 0, den = 1;
1793 const long double mean = least_mean_value(c, has, num, den);
1794 if (r.has_cycle != has)
1795 return has ? "finds no cycle" : "finds a cycle where there is none";
1796 if (r.minimum_mean != mean)
1797 return "gives the mean " + text_of(r.minimum_mean) + ", not " + std::to_string(num) + "/"
1798 + std::to_string(den);
1799 if (not has)
1800 return r.cycle_arcs.is_empty() and r.cycle_length == 0 ? "" : "gives a cycle";
1801 const Walk w = walk_of(r.cycle_nodes, r.cycle_arcs);
1802 if (auto e = closed_walk_error(c.s, w, c.show(), true); not e.empty())
1803 return e;
1804 const long long cost = cost_of(c.s, w);
1805 if (r.cycle_length != w.arcs.size() or (long double) r.cycle_total_cost != (long double) cost)
1806 return "the cycle " + w.str() + " has the length " + std::to_string(r.cycle_length)
1807 + " and the cost " + text_of(r.cycle_total_cost);
1808 if (cost * den != num * (long long) w.arcs.size())
1809 return "the cycle " + w.str() + " has not the least mean " + std::to_string(num) + "/"
1810 + std::to_string(den);
1811 if (r.witness_node == nullptr)
1812 return "gives no witness node";
1813 return "";
1814 }
1815
1819 template <class Result>
1820 std::string howard_error(const Result & r)
1821 {
1822 if (r.has_cycle and r.witness_node != r.cycle_nodes.get_first())
1823 return "the witness node does not start the cycle";
1824 if (r.used_karp != (r.fallback_reason != Howard_Fallback_Reason::None))
1825 return "used_karp and fallback_reason disagree";
1826 if (r.has_cycle and (r.numeric_quality == Cycle_Numeric_Quality::Exact) == r.used_karp)
1827 return std::string("the quality is ")
1828 + (r.numeric_quality == Cycle_Numeric_Quality::Exact ? "Exact" : "Rounded")
1829 + (r.used_karp ? " after" : " without") + " the fallback";
1830 return "";
1831 }
1832
1835 template <class Result>
1836 bool same_cycle(const Result & a, const Result & b)
1837 {
1838 if (a.has_cycle != b.has_cycle or a.minimum_mean != b.minimum_mean
1839 or a.cycle_length != b.cycle_length or a.cycle_total_cost != b.cycle_total_cost)
1840 return false;
1841 auto i = a.cycle_arcs.get_it();
1842 auto j = b.cycle_arcs.get_it();
1843 for (; i.has_curr() and j.has_curr(); i.next_ne(), j.next_ne())
1844 if (i.get_curr() != j.get_curr())
1845 return false;
1846 return not i.has_curr() and not j.has_curr();
1847 }
1848
1851 template <class GT, typename T, class SA>
1852 void run_means(Mean_Checks & k, Case<GT, T> & c, const SA & sa)
1853 {
1854 using D = Spec_Weight<GT, T>;
1855 const GT & g = c.b.g;
1856 const Spec & s = c.s;
1857
1858 k.karp.run();
1859 const auto r = karp_minimum_mean_cycle(g, c.d, sa);
1860 if (auto e = mean_error(c, r); not e.empty())
1861 k.karp.fail(s, c.label + e);
1862
1863 k.karp_value.run();
1864 const auto v = karp_minimum_mean_cycle_value(g, c.d, sa);
1865 if (v.has_cycle != r.has_cycle or v.minimum_mean != r.minimum_mean)
1866 k.karp_value.fail(s, c.label + "gives " + text_of(v.minimum_mean) + ", and the witness "
1867 + text_of(r.minimum_mean));
1868
1869 // The aliases and the functors, which wrap the functions, in turn
1870 if (k.turn++ % 2 == 0)
1871 {
1872 k.aliases.run();
1873 const auto a = minimum_mean_cycle(g, c.d, sa);
1874 const auto b = minimum_mean_cycle_value(g, c.d, sa);
1875 if (not same_cycle(a, r) or b.has_cycle != v.has_cycle or b.minimum_mean != v.minimum_mean)
1876 k.aliases.fail(s, c.label + "they do not give what karp_minimum_mean_cycle() gives");
1877 }
1878 else
1879 {
1880 // A functor gives the same twice
1881 k.functors.run();
1882 const Karp_Minimum_Mean_Cycle<GT, D, SA> f(c.d, sa);
1884 const auto a = f(g), b = f(g);
1885 const auto x = fv(g), y = fv(g);
1886 if (not same_cycle(a, r) or not same_cycle(b, r) or x.has_cycle != v.has_cycle
1887 or x.minimum_mean != v.minimum_mean or y.minimum_mean != v.minimum_mean)
1888 k.functors.fail(s, c.label + "they do not give what the functions give");
1889 }
1890
1891 k.howard.run();
1892 const auto h = howard_minimum_mean_cycle(g, c.d, sa);
1893 if (auto e = mean_error(c, h); not e.empty())
1894 k.howard.fail(s, c.label + e);
1895 else if (auto e2 = howard_error(h); not e2.empty())
1896 k.howard.fail(s, c.label + e2);
1897
1898 k.howard_value.run();
1899 if (const auto hv = howard_minimum_mean_cycle_value(g, c.d, sa);
1900 hv.has_cycle != h.has_cycle or hv.minimum_mean != h.minimum_mean)
1901 k.howard_value.fail(s, c.label + "gives " + text_of(hv.minimum_mean) + ", and the witness "
1902 + text_of(h.minimum_mean));
1903
1904 // Without bytes for the fallback, the same unless Karp has to answer
1905 k.howard_limit.run();
1906 try
1907 {
1908 const auto z = howard_minimum_mean_cycle(g, c.d, sa, 0);
1909 const auto zv = howard_minimum_mean_cycle_value(g, c.d, sa, 0);
1910 if (h.used_karp)
1911 k.howard_limit.fail(s, c.label + "does not throw length_error");
1912 else if (not same_cycle(z, h) or zv.minimum_mean != h.minimum_mean)
1913 k.howard_limit.fail(s, c.label + "gives another answer");
1914 }
1915 catch (const std::length_error &)
1916 {
1917 if (not h.used_karp)
1918 k.howard_limit.fail(s, c.label + "throws length_error without the fallback");
1919 }
1920
1921 // Without iterations, Karp answers unless the first policy is optimal
1922 k.fallback.run();
1923 const auto f = howard_detail::minimum_mean_cycle<GT, D, SA>(g, c.d, sa, 0);
1924 if (auto e = mean_error(c, f); not e.empty())
1925 k.fallback.fail(s, c.label + e);
1926 else if (auto e2 = howard_error(f); not e2.empty())
1927 k.fallback.fail(s, c.label + e2);
1928 else if (f.used_karp and f.fallback_reason != Howard_Fallback_Reason::Iteration_Limit)
1929 k.fallback.fail(s, c.label + "the reason of the fallback is not the iteration limit");
1930 else if (const auto fv = howard_detail::minimum_mean_cycle<GT, D, SA, false>(g, c.d, sa, 0);
1931 fv.has_cycle != f.has_cycle or fv.minimum_mean != f.minimum_mean)
1932 k.fallback.fail(s, c.label + "without the witness it gives " + text_of(fv.minimum_mean));
1933
1934 // Without bytes either, the fallback throws length_error
1935 k.fallback_limit.run();
1936 try
1937 {
1938 const auto z = howard_detail::minimum_mean_cycle<GT, D, SA>(g, c.d, sa, 0, 0);
1939 if (f.used_karp)
1940 k.fallback_limit.fail(s, c.label + "does not throw length_error");
1941 else if (not same_cycle(z, f))
1942 k.fallback_limit.fail(s, c.label + "gives another cycle");
1943 }
1944 catch (const std::length_error &)
1945 {
1946 if (not f.used_karp)
1947 k.fallback_limit.fail(s, c.label + "throws length_error without the fallback");
1948 }
1949 }
1950
1953 struct All_Pairs_Checks
1954 {
1955 Check floyd;
1956 Check johnson;
1957
1958 explicit All_Pairs_Checks(const std::string & how = "")
1959 : floyd("Floyd_All_Shortest_Paths::has_negative_cycle()" + how),
1960 johnson("Johnson, its constructor" + how)
1961 {}
1962
1963 void expect() const
1964 {
1965 floyd.expect();
1966 johnson.expect();
1967 }
1968 };
1969
1974 template <class GT, typename T, class SA>
1975 void run_floyd(Check & k, Case<GT, T> & c, const SA & sa)
1976 {
1977 using D = Spec_Weight<GT, T>;
1978 const Spec & s = c.s;
1979 bool negative = c.t.negative;
1980 if (not c.b.g.is_digraph())
1981 oracle::shortest_distances(shown_spec(s, c.show()), false, negative);
1982 k.run();
1983 try
1984 {
1985 const Floyd_All_Shortest_Paths<GT, D, SA> f(c.b.g, c.d, sa);
1986 if (s.n == 0)
1987 k.fail(s, c.label + "takes a graph without nodes");
1988 else if (f.has_negative_cycle() != negative)
1989 k.fail(s, c.label + says(f.has_negative_cycle()));
1990 else if (negative)
1991 try
1992 {
1993 const long zero = 0;
1994 f.get_min_path(zero, zero);
1995 k.fail(s, c.label + "get_min_path() gives a path with a negative cycle");
1996 }
1997 catch (const std::domain_error &)
1998 {
1999 // there are no shortest paths
2000 }
2001 }
2002 catch (const std::invalid_argument &)
2003 {
2004 if (s.n != 0)
2005 k.fail(s, c.label + "throws invalid_argument");
2006 }
2007 }
2008
2012 template <class GT, typename T, class SA>
2013 void run_johnson(Check & k, Case<GT, T> & c, const SA & sa)
2014 {
2015 using D = Spec_Weight<GT, T>;
2016 k.run();
2017 try
2018 {
2020 if (c.t.negative)
2021 k.fail(c.s, c.label + "does not throw on a negative cycle");
2022 else if (not j.is_initialized())
2023 k.fail(c.s, c.label + "is not initialized");
2024 }
2025 catch (const std::domain_error &)
2026 {
2027 if (not c.t.negative)
2028 k.fail(c.s, c.label + "throws domain_error without a negative cycle");
2029 }
2030 catch (const std::overflow_error & e)
2031 {
2032 if (not c.may_overflow)
2033 k.fail(c.s, c.label + std::string("throws ") + e.what());
2034 }
2035 catch (const std::exception & e)
2036 {
2037 k.fail(c.s, c.label + std::string("throws ") + e.what());
2038 }
2039 }
2040
2043 const std::vector<long long> Limit_Weights = {std::numeric_limits<int>::lowest() / 2, -1,
2044 std::numeric_limits<int>::max() / 2 - 1,
2045 std::numeric_limits<int>::max() - 5};
2046
2049 const std::vector<long long> Johnson_Limit_Weights = {std::numeric_limits<int>::lowest() / 2,
2050 -10, 1,
2051 std::numeric_limits<int>::max() - 5};
2052
2056 const std::vector<long long> Johnson_Query_Weights = {std::numeric_limits<int>::lowest() / 2,
2057 -10,
2058 std::numeric_limits<int>::max() - 5};
2059
2063 constexpr long long Minus_Infinity = -(1LL << 56);
2064 constexpr long long Not_A_Number = 1LL << 56;
2065
2067 const std::vector<long long> Infinite_Weights = {Minus_Infinity, Not_A_Number, -1, 1};
2068
2070 unsigned long not_finite(const Spec & s)
2071 {
2072 unsigned long mask = 0;
2073 for (size_t i = 0; i < s.num_arcs(); ++i)
2074 if (s.w[i] == Minus_Infinity or s.w[i] == Not_A_Number)
2075 mask |= 1UL << i;
2076 return mask;
2077 }
2078
2080 unsigned long not_a_number(const Spec & s)
2081 {
2082 unsigned long mask = 0;
2083 for (size_t i = 0; i < s.num_arcs(); ++i)
2084 if (s.w[i] == Not_A_Number)
2085 mask |= 1UL << i;
2086 return mask;
2087 }
2088
2092 template <class GT, typename T>
2093 bool reweighting_overflows(const Case<GT, T> & c)
2094 {
2095 const auto h = potentials(c.t, c.s.n);
2096 constexpr long long lo = std::numeric_limits<int>::lowest();
2097 constexpr long long hi = std::numeric_limits<int>::max();
2098 for (size_t i = 0; i < c.s.num_arcs(); ++i)
2099 {
2100 if (not c.show()[i])
2101 continue;
2102 const long long first = c.s.w[i] + h[size_t(c.s.arcs[i][0])];
2103 const long long last = first - h[size_t(c.s.arcs[i][1])];
2104 if (first < lo or first > hi or last < lo or last > hi)
2105 return true;
2106 }
2107 return false;
2108 }
2109
2112 template <class GT>
2113 std::map<typename GT::Arc *, int> weights_as_infos(Built<GT> & b, const Spec & s)
2114 {
2115 std::map<typename GT::Arc *, int> numbers;
2116 for (size_t i = 0; i < b.arcs.size(); ++i)
2117 {
2118 b.arcs[i]->get_info() = int(s.w[i]);
2119 numbers[b.arcs[i]] = int(i);
2120 }
2121 return numbers;
2122 }
2123} // namespace
2124
2125template <class GT>
2126class ExhaustiveBellmanFord : public ::testing::Test {};
2127
2129
2130TYPED_TEST(ExhaustiveBellmanFord, DetectionMatchesTheOracle)
2131{
2132 using GT = TypeParam;
2133 Detection_Checks k;
2134 Check null_start("Bellman_Ford, the searches from a null start");
2135
2136 for_each_weighted_spec([&] (const Spec & s)
2137 {
2138 Case<GT, int> c(s, shown_but(s, 0));
2139 run_detection(k, c, Dft_Show_Arc<GT>());
2140 });
2141
2142 // Every search from a start rejects a null one
2143 for_each_spec(small_weights_domain(), true, [&] (const Spec & s)
2144 {
2145 Spec t = s;
2146 t.w.assign(s.num_arcs(), -1);
2147 Case<GT, int> c(t, shown_but(t, 0));
2148 BF<GT, int> bf(c.b.g, c.d);
2149 int thrown = 0;
2150 auto count = [&] (auto && call)
2151 {
2152 try
2153 {
2154 call();
2155 }
2156 catch (const std::domain_error &)
2157 {
2158 ++thrown;
2159 }
2160 };
2161 null_start.run();
2162 count([&] { bf.paint_spanning_tree(nullptr); });
2163 count([&] { bf.faster_paint_spanning_tree(nullptr); });
2164 count([&] { bf.has_negative_cycle(nullptr); });
2165 count([&] { bf.test_negative_cycle(nullptr); });
2166 count([&] { bf.search_negative_cycle(nullptr); });
2167 count([&] { bf.search_negative_cycle(nullptr, 0.5, 1); });
2168 count([&] { bf.get_distance(nullptr); });
2169 if (thrown != 7)
2170 null_start.fail(t, std::to_string(7 - thrown) + " of 7 do not throw domain_error");
2171 });
2172
2173 k.expect();
2174 null_start.expect();
2175}
2176
2177TYPED_TEST(ExhaustiveBellmanFord, WitnessesFromAStartAreNegativeCycles)
2178{
2179 using GT = TypeParam;
2180 Witness_Checks k(false, "");
2181
2182 for_each_weighted_spec([&] (const Spec & s)
2183 {
2184 Case<GT, int> c(s, shown_but(s, 0));
2185 run_witnesses(k, c, Dft_Show_Arc<GT>(), false);
2186 });
2187
2188 k.expect();
2189}
2190
2191TYPED_TEST(ExhaustiveBellmanFord, WitnessesInTheWholeGraphAreNegativeCycles)
2192{
2193 using GT = TypeParam;
2194 Witness_Checks k(true, "");
2195
2196 for_each_weighted_spec([&] (const Spec & s)
2197 {
2198 Case<GT, int> c(s, shown_but(s, 0));
2199 run_witnesses(k, c, Dft_Show_Arc<GT>(), true);
2200 });
2201
2202 k.expect();
2203}
2204
2205TYPED_TEST(ExhaustiveBellmanFord, FunctorsMatchTheOracle)
2206{
2207 using GT = TypeParam;
2208 Functor_Checks k("");
2209
2210 for_each_weighted_spec([&] (const Spec & s)
2211 {
2212 Case<GT, int> c(s, shown_but(s, 0));
2213 run_functors<Node_Arc_Iterator>(k, c, Dft_Show_Arc<GT>());
2214 });
2215
2216 k.expect();
2217}
2218
2219TYPED_TEST(ExhaustiveBellmanFord, TheTreeOfTheShortestPathsMatchesTheOracle)
2220{
2221 using GT = TypeParam;
2222 Tree_Checks k;
2223
2224 for_each_weighted_spec([&] (const Spec & s)
2225 {
2226 Case<GT, int> c(s, shown_but(s, 0));
2228 });
2229
2230 k.expect();
2231}
2232
2233TYPED_TEST(ExhaustiveBellmanFord, SequencesOfCallsOnOneObjectMatchTheOracle)
2234{
2235 using GT = TypeParam;
2236 Check repaint("Bellman_Ford, a painting after another, from another start");
2237 Check after_search("Bellman_Ford, a painting after each search");
2238 Check after_tree("Bellman_Ford, a painting after build_tree(tree)");
2239 Check after_clear("Bellman_Ford::clear()");
2240 Check fresh_build("Bellman_Ford::build_tree(tree, false), on a new object");
2241 Check bits("Bellman_Ford, the bits Depth_First that a search leaves");
2242 Check cookies("Bellman_Ford, the cookies that a search leaves");
2243 size_t turn = 0;
2244
2245 for_each_spec(sign_domain(), true, [&] (const Spec & shape)
2246 {
2247 if (shape.n == 0)
2248 return;
2249 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2250 {
2251 Case<GT, int> c(s, shown_but(s, 0));
2252 BF<GT, int> bf(c.b.g, c.d);
2253 const int first = 0, last = s.n - 1;
2254
2255 check_unpainted_build(fresh_build, bf, s, "");
2256
2257 // Paints from u and compares with the oracle
2258 auto painting = [&] (int u, bool faster) -> std::string
2259 {
2260 auto * p = c.b.nodes[size_t(u)];
2261 const bool negative =
2262 faster ? bf.faster_paint_spanning_tree(p) : bf.paint_spanning_tree(p);
2263 if (negative != c.t.negative_from[size_t(u)])
2264 return from_text(u) + says(negative);
2265 if (negative)
2266 return bf.is_painted() ? from_text(u) + "is painted" : "";
2267 if (bf.get_start_node() != p)
2268 return from_text(u) + "has another start";
2269 if (auto e = distances_error(bf, c, u); not e.empty())
2270 return from_text(u) + e;
2271 return "";
2272 };
2273
2274 repaint.run();
2275 for (auto [u, faster] : {std::pair{first, false}, {last, true}, {first, true},
2276 {last, false}})
2277 if (auto e = painting(u, faster); not e.empty())
2278 {
2279 repaint.fail(s, e);
2280 break;
2281 }
2282
2283 // A search, the next one of the list at each spec, and then a
2284 // painting
2285 after_search.run();
2286 auto * p = c.b.nodes[size_t(first)];
2287 struct Search
2288 {
2289 const char * name;
2290 std::function<void()> call;
2291 };
2292 const Search searches[] = {
2293 {"has_negative_cycle(start)", [&] { bf.has_negative_cycle(p); }},
2294 {"test_negative_cycle(start)", [&] { bf.test_negative_cycle(p); }},
2295 {"search_negative_cycle(start)", [&] { bf.search_negative_cycle(p); }},
2296 {"search_negative_cycle(start, 0.5, 1)", [&] { bf.search_negative_cycle(p, 0.5, 1); }},
2297 {"has_negative_cycle()", [&] { bf.has_negative_cycle(); }},
2298 {"test_negative_cycle()", [&] { bf.test_negative_cycle(); }},
2299 {"search_negative_cycle()", [&] { bf.search_negative_cycle(); }},
2300 {"search_negative_cycle(0.5, 1)", [&] { bf.search_negative_cycle(0.5, 1); }},
2301 {"compute_nodes_weights()", [&]
2302 {
2303 try
2304 {
2305 bf.compute_nodes_weights();
2306 }
2307 catch (const std::domain_error &)
2308 {
2309 // a negative cycle
2310 }
2311 }}};
2312 {
2313 const Search & search = searches[turn++ % std::size(searches)];
2314 search.call();
2315 const std::set<void *> nodes(c.b.nodes.begin(), c.b.nodes.end());
2316 bool marked = false, outside = false;
2317 for (auto * q : c.b.nodes)
2318 {
2319 marked = marked or IS_NODE_VISITED(q, Aleph::Depth_First);
2320 outside = outside
2321 or (NODE_COOKIE(q) != nullptr and nodes.count(NODE_COOKIE(q)) == 0);
2322 }
2323 bits.run();
2324 if (marked)
2325 bits.fail(s, std::string("after ") + search.name + ", a node keeps the bit");
2326 cookies.run();
2327 if (outside)
2328 cookies.fail(s, std::string("after ") + search.name
2329 + ", a cookie points out of the graph");
2330 if (auto e = painting(last, false); not e.empty())
2331 after_search.fail(s, std::string("after ") + search.name + ", " + e);
2332 }
2333
2334 // A painting after build_tree(tree), and build_tree(tree, false)
2335 // after it
2336 after_tree.run();
2337 if (not c.t.negative_from[size_t(first)] and not c.t.negative_from[size_t(last)])
2338 {
2339 bf.paint_spanning_tree(p);
2340 GT tree;
2341 bf.build_tree(tree);
2342 if (auto e = painting(last, false); not e.empty())
2343 after_tree.fail(s, e);
2344 else
2345 {
2346 GT again;
2347 bf.build_tree(again, false);
2348 if (auto e2 = tree_error(s, again, painted_arcs(c.b)); not e2.empty())
2349 after_tree.fail(s, "build_tree(tree, false): " + e2);
2350 }
2351 }
2352
2353 // clear() forgets the painting and takes the bits off
2354 after_clear.run();
2355 bf.paint_spanning_tree(p);
2356 bf.clear();
2357 bool painted = false;
2358 for (auto * q : c.b.nodes)
2359 painted = painted or IS_NODE_VISITED(q, Aleph::Spanning_Tree);
2360 for (auto * a : c.b.arcs)
2361 painted = painted or IS_ARC_VISITED(a, Aleph::Spanning_Tree);
2362 int thrown = 0;
2363 try
2364 {
2365 bf.extract_min_spanning_tree();
2366 }
2367 catch (const std::domain_error &)
2368 {
2369 ++thrown;
2370 }
2371 try
2372 {
2373 bf.get_distance(p);
2374 }
2375 catch (const std::domain_error &)
2376 {
2377 ++thrown;
2378 }
2379 if (painted or bf.is_painted() or bf.has_computation()
2380 or bf.get_start_node() != nullptr or thrown != 2)
2381 after_clear.fail(s, "keeps some of the painting");
2382 });
2383 });
2384
2385 repaint.expect();
2386 after_search.expect();
2387 after_tree.expect();
2388 after_clear.expect();
2389 fresh_build.expect();
2390 bits.expect();
2391 cookies.expect();
2392}
2393
2394TYPED_TEST(ExhaustiveBellmanFord, DetectionRespectsTheFilter)
2395{
2396 using GT = TypeParam;
2397 Detection_Checks k(", hiding arcs");
2398
2399 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2400 {
2401 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2402 {
2403 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
2404 {
2405 Case<GT, int> c(s, shown_but(s, hidden));
2406 c.label = "hiding " + std::to_string(hidden) + ": ";
2407 run_detection(k, c, Hide_Mask<GT>{hidden});
2408 }
2409 });
2410 });
2411
2412 k.expect();
2413}
2414
2415TYPED_TEST(ExhaustiveBellmanFord, WitnessesRespectTheFilter)
2416{
2417 using GT = TypeParam;
2418 Witness_Checks from(false, ", hiding arcs");
2419 Witness_Checks global(true, ", hiding arcs");
2420
2421 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2422 {
2423 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2424 {
2425 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
2426 {
2427 Case<GT, int> c(s, shown_but(s, hidden));
2428 c.label = "hiding " + std::to_string(hidden) + ": ";
2429 run_witnesses(from, c, Hide_Mask<GT>{hidden}, false);
2430 run_witnesses(global, c, Hide_Mask<GT>{hidden}, true);
2431 }
2432 });
2433 });
2434
2435 from.expect();
2436 global.expect();
2437}
2438
2439TYPED_TEST(ExhaustiveBellmanFord, WhitelistsOfNumbersMatchTheOracle)
2440{
2441 using GT = TypeParam;
2442 const std::string how = ", with a whitelist of numbers";
2443 Detection_Checks k(how);
2444 Witness_Checks from(false, how);
2445 Witness_Checks global(true, how);
2446
2447 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2448 {
2449 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2450 {
2451 for (unsigned long shown = 0; shown < (1UL << s.num_arcs()); ++shown)
2452 {
2453 Case<GT, int> c(s, shown_only(s, shown));
2454 c.label = "showing " + std::to_string(shown) + ": ";
2455 const Show_Mask<GT> sa{shown};
2456 run_detection(k, c, sa);
2457 run_witnesses(from, c, sa, false);
2458 run_witnesses(global, c, sa, true);
2459 }
2460 });
2461 });
2462
2463 k.expect();
2464 from.expect();
2465 global.expect();
2466}
2467
2468TYPED_TEST(ExhaustiveBellmanFord, WhitelistsOfPointersMatchTheOracle)
2469{
2470 using GT = TypeParam;
2471 const std::string how = ", with a whitelist of pointers";
2472 Detection_Checks k(how);
2473 Witness_Checks from(false, how);
2474 Witness_Checks global(true, how);
2475
2476 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2477 {
2478 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2479 {
2480 for (unsigned long shown = 0; shown < (1UL << s.num_arcs()); ++shown)
2481 {
2482 Case<GT, int> c(s, shown_only(s, shown));
2483 c.label = "showing " + std::to_string(shown) + ": ";
2484 std::set<typename GT::Arc *> arcs;
2485 for (size_t i = 0; i < s.num_arcs(); ++i)
2486 if (c.show()[i])
2487 arcs.insert(c.b.arcs[i]);
2488 const Show_Arcs<GT> sa{&arcs};
2489 run_detection(k, c, sa);
2490 run_witnesses(from, c, sa, false);
2491 run_witnesses(global, c, sa, true);
2492 }
2493 });
2494 });
2495
2496 k.expect();
2497 from.expect();
2498 global.expect();
2499}
2500
2501TYPED_TEST(ExhaustiveBellmanFord, DoubleDistancesMatchTheOracle)
2502{
2503 using GT = TypeParam;
2504 const std::string how = ", with double distances";
2505 Detection_Checks k(how);
2506 Witness_Checks from(false, how);
2507 Witness_Checks global(true, how);
2508 Tree_Checks tree(how);
2509
2510 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2511 {
2512 for_each_weighting(shape, Unit_Weights, [&] (const Spec & s)
2513 {
2514 Case<GT, double> c(s, shown_but(s, 0));
2515 run_detection(k, c, Dft_Show_Arc<GT>());
2516 run_witnesses(from, c, Dft_Show_Arc<GT>(), false);
2517 run_witnesses(global, c, Dft_Show_Arc<GT>(), true);
2518 run_tree(tree, c, Dft_Show_Arc<GT>());
2519 });
2520 });
2521
2522 k.expect();
2523 from.expect();
2524 global.expect();
2525 tree.expect();
2526}
2527
2528namespace
2529{
2534 template <class F>
2535 void for_each_spec_near_the_limits(F && f)
2536 {
2537 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2538 {
2539 for_each_weighting(shape, Limit_Weights, [&] (const Spec & s)
2540 {
2541 f(s, sums_may_overflow(s, shown_but(s, 0), std::numeric_limits<int>::lowest(),
2542 std::numeric_limits<int>::max() - 1));
2543 });
2544 });
2545 }
2546}
2547
2548TYPED_TEST(ExhaustiveBellmanFord, IntegersNearTheLimitsMatchTheOracle)
2549{
2550 using GT = TypeParam;
2551 const std::string how = ", near the limits of int";
2552 Detection_Checks k(how);
2553 Witness_Checks from(false, how);
2554 Witness_Checks global(true, how);
2555
2556 // Where a sum may leave int, overflow_error is also right
2557 for_each_spec_near_the_limits([&] (const Spec & s, bool overflow)
2558 {
2559 Case<GT, int> c(s, shown_but(s, 0));
2560 c.may_overflow = overflow;
2561 run_detection(k, c, Dft_Show_Arc<GT>());
2562 run_witnesses(from, c, Dft_Show_Arc<GT>(), false);
2563 run_witnesses(global, c, Dft_Show_Arc<GT>(), true);
2564 });
2565
2566 k.expect();
2567 from.expect();
2568 global.expect();
2569}
2570
2571TYPED_TEST(ExhaustiveBellmanFord, TheTreeNearTheLimitsMatchesTheOracle)
2572{
2573 using GT = TypeParam;
2574 Tree_Checks k(", near the limits of int");
2575
2576 // Where a sum may leave int, the painting may throw overflow_error
2577 for_each_spec_near_the_limits([&] (const Spec & s, bool overflow)
2578 {
2579 Case<GT, int> c(s, shown_but(s, 0));
2580 c.may_overflow = overflow;
2582 });
2583
2584 k.expect();
2585}
2586
2587TYPED_TEST(ExhaustiveBellmanFord, TheQueriesOnPathsNearTheLimitsOfInt)
2588{
2589 using GT = TypeParam;
2590 const std::string how = ", on a path near the limits of int";
2591 Check painted("Bellman_Ford::paint_spanning_tree()" + how);
2592 // A sum of the weights from the end of the path may leave int although
2593 // the distance fits; get_distance() and get_min_path() add them from the
2594 // start, so that each sum is the distance of a node of the path
2595 Check distance("Bellman_Ford::get_distance()" + how);
2596 Check path("Bellman_Ford::get_min_path()" + how);
2597 size_t sums_from_the_end_leave_int = 0;
2598 constexpr long long lo = std::numeric_limits<int>::lowest();
2599 constexpr long long hi = std::numeric_limits<int>::max();
2600
2601 // The path 0 -> 1 -> 2 -> 3, with its arcs inserted in both orders
2602 for (bool reversed : {false, true})
2603 {
2604 Spec shape;
2605 shape.n = 4;
2606 shape.arcs = {{0, 1}, {1, 2}, {2, 3}};
2607 if (reversed)
2608 std::reverse(shape.arcs.begin(), shape.arcs.end());
2609 for_each_weighting(shape, Limit_Weights, [&] (const Spec & s)
2610 {
2611 // A distance may leave int, and then the painting throws
2612 Case<GT, int> c(s, shown_but(s, 0));
2613 c.may_overflow = true;
2614 BF<GT, int> bf(c.b.g, c.d);
2615 bool negative = false;
2616 if (not returns(painted, bf, c, "", [&]
2617 {
2618 negative = bf.paint_spanning_tree(c.b.nodes[0]);
2619 painted.run();
2620 }))
2621 return;
2622 if (negative)
2623 {
2624 painted.fail(s, "finds a negative cycle");
2625 return;
2626 }
2627
2628 // The weight of the arc from v - 1 to v
2629 auto weight = [&] (int v)
2630 {
2631 for (size_t i = 0; i < s.num_arcs(); ++i)
2632 if (s.arcs[i][1] == v)
2633 return s.w[i];
2634 return 0LL;
2635 };
2636 for (int v = 1; v < s.n; ++v)
2637 {
2638 // Whether a sum of the weights from v back to 0 leaves int
2639 bool back = false;
2640 long long sum = 0;
2641 for (int x = v; x > 0; --x)
2642 {
2643 sum += weight(x);
2644 back = back or sum < lo or sum > hi;
2645 }
2646 const long long want = c.t.dist[0][size_t(v)];
2647 sums_from_the_end_leave_int += back;
2648 distance.run();
2649 try
2650 {
2651 if (const int got = bf.get_distance(c.b.nodes[size_t(v)]); got != want)
2652 distance.fail(s, "gives " + std::to_string(got) + " to " + std::to_string(v)
2653 + ", not " + std::to_string(want));
2654 }
2655 catch (const std::overflow_error & e)
2656 {
2657 distance.fail(s, "to " + std::to_string(v) + ": throws " + e.what());
2658 }
2659 path.run();
2660 Path<GT> p(c.b.g);
2661 const int got = bf.get_min_path(c.b.nodes[size_t(v)], p);
2662 if (auto e = min_path_error(c, p, 0, v, got); not e.empty())
2663 path.fail(s, e);
2664 }
2665 });
2666 }
2667
2668 painted.expect();
2669 distance.expect();
2670 path.expect();
2671 EXPECT_GT(sums_from_the_end_leave_int, 0u);
2672}
2673
2674namespace
2675{
2680 template <class GT, class Show, class F>
2681 void for_each_infinite_case(Show && show, F && f)
2682 {
2683 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2684 {
2685 for_each_weighting(shape, Infinite_Weights, [&] (const Spec & s)
2686 {
2687 Case<GT, double> c(s, show(s));
2688 for (size_t i = 0; i < s.num_arcs(); ++i)
2689 if (s.w[i] == Minus_Infinity)
2690 c.w[i] = -std::numeric_limits<double>::infinity();
2691 else if (s.w[i] == Not_A_Number)
2692 c.w[i] = std::numeric_limits<double>::quiet_NaN();
2693 f(s, c);
2694 });
2695 });
2696 }
2697}
2698
2699TYPED_TEST(ExhaustiveBellmanFord, WeightsThatAreNotFiniteAreRejectedOrCounted)
2700{
2701 using GT = TypeParam;
2702 const std::string how = ", with weights of minus infinity or NaN";
2703 Detection_Checks k(how);
2704 Witness_Checks from(false, how);
2705 Witness_Checks global(true, how);
2706 Tree_Checks tree(how);
2707
2708 // An operation whose last pass meets a sum of minus infinity or NaN
2709 // throws domain_error; another one, that stops before, gives the answer
2710 // of the oracle, where minus infinity is below any finite cost and an arc
2711 // of NaN, which never relaxes, does not count
2712 for_each_infinite_case<GT>([] (const Spec & s) { return shown_but(s, not_a_number(s)); },
2713 [&] (const Spec & s, Case<GT, double> & c)
2714 {
2715 c.may_reject = not_finite(s) != 0;
2716 c.filtered = shown_but(s, 0);
2717 run_detection(k, c, Dft_Show_Arc<GT>());
2718 run_witnesses(from, c, Dft_Show_Arc<GT>(), false);
2719 run_witnesses(global, c, Dft_Show_Arc<GT>(), true);
2720 run_tree(tree, c, Dft_Show_Arc<GT>());
2721 });
2722
2723 k.expect();
2724 from.expect();
2725 global.expect();
2726 tree.expect();
2727}
2728
2729TYPED_TEST(ExhaustiveBellmanFord, WeightsThatAreNotFiniteDoNotCountWhenHidden)
2730{
2731 using GT = TypeParam;
2732 const std::string how = ", with weights of minus infinity or NaN hidden by the filter";
2733 Detection_Checks k(how);
2734 Witness_Checks from(false, how);
2735 Witness_Checks global(true, how);
2736
2737 for_each_infinite_case<GT>([] (const Spec & s) { return shown_but(s, not_finite(s)); },
2738 [&] (const Spec & s, Case<GT, double> & c)
2739 {
2740 const unsigned long bad = not_finite(s);
2741 if (bad == 0)
2742 return;
2743 c.label = "hiding " + std::to_string(bad) + ": ";
2744 const Hide_Mask<GT> sa{bad};
2745 run_detection(k, c, sa);
2746 run_witnesses(from, c, sa, false);
2747 run_witnesses(global, c, sa, true);
2748 });
2749
2750 k.expect();
2751 from.expect();
2752 global.expect();
2753}
2754
2755TYPED_TEST(ExhaustiveBellmanFord, RandomDigraphsMatchTheOracle)
2756{
2757 using GT = TypeParam;
2758 const std::string how = ", on random digraphs";
2759 Detection_Checks k(how);
2760 Witness_Checks from(false, how);
2761 Witness_Checks global(true, how);
2762 Tree_Checks tree(how);
2763
2764 std::mt19937 rng(seed(73));
2765 for (int round = 0; round < (heavy() ? 400 : 40); ++round)
2766 {
2767 const int n = 6 + int(rng() % 3);
2768 Spec s = random_spec(rng, n, n + int(rng() % size_t(n + 1)), true);
2769 random_weights(rng, s, -1 - (long long) (rng() % 4), 6);
2770 Case<GT, int> c(s, shown_but(s, 0));
2771 run_detection(k, c, Dft_Show_Arc<GT>());
2772 run_tree(tree, c, Dft_Show_Arc<GT>());
2773 run_witnesses(from, c, Dft_Show_Arc<GT>(), false);
2774 run_witnesses(global, c, Dft_Show_Arc<GT>(), true);
2775 }
2776
2777 k.expect();
2778 from.expect();
2779 global.expect();
2780 tree.expect();
2781}
2782
2783template <class GT>
2784class ExhaustiveNegativeCycleSearches : public ::testing::Test {};
2785
2787
2789{
2790 using GT = TypeParam;
2791 Search_Checks k;
2792
2793 for_each_weighted_spec([&] (const Spec & s)
2794 {
2795 Case<GT, int> c(s, shown_but(s, 0));
2796 run_searches(k, c, Dft_Show_Arc<GT>());
2797 });
2798
2799 k.expect();
2800}
2801
2803{
2804 using GT = TypeParam;
2805 Search_Checks k(", hiding arcs");
2806
2807 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2808 {
2809 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2810 {
2811 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
2812 {
2813 Case<GT, int> c(s, shown_but(s, hidden));
2814 c.label = "hiding " + std::to_string(hidden) + ": ";
2815 run_searches(k, c, Hide_Mask<GT>{hidden});
2816 }
2817 });
2818 });
2819
2820 k.expect();
2821}
2822
2823TYPED_TEST(ExhaustiveNegativeCycleSearches, SearchesWithDoubleCostsMatchTheOracle)
2824{
2825 using GT = TypeParam;
2826 Search_Checks k(", with double costs");
2827
2828 for_each_weighted_spec([&] (const Spec & s)
2829 {
2830 Case<GT, double> c(s, shown_but(s, 0));
2831 run_searches(k, c, Dft_Show_Arc<GT>());
2832 }, Unit_Weights);
2833
2834 k.expect();
2835}
2836
2838{
2839 using GT = TypeParam;
2840 Mean_Checks k;
2841
2842 for_each_weighted_spec([&] (const Spec & s)
2843 {
2844 Case<GT, int> c(s, shown_but(s, 0));
2845 run_means(k, c, Dft_Show_Arc<GT>());
2846 });
2847
2848 k.expect();
2849}
2850
2852{
2853 using GT = TypeParam;
2854 Mean_Checks k(", hiding arcs");
2855
2856 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2857 {
2858 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2859 {
2860 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
2861 {
2862 Case<GT, int> c(s, shown_but(s, hidden));
2863 c.label = "hiding " + std::to_string(hidden) + ": ";
2864 run_means(k, c, Hide_Mask<GT>{hidden});
2865 }
2866 });
2867 });
2868
2869 k.expect();
2870}
2871
2872TYPED_TEST(ExhaustiveNegativeCycleSearches, MeansWithDoubleCostsMatchTheOracle)
2873{
2874 using GT = TypeParam;
2875 Mean_Checks k(", with double costs");
2876
2877 for_each_weighted_spec([&] (const Spec & s)
2878 {
2879 Case<GT, double> c(s, shown_but(s, 0));
2880 run_means(k, c, Dft_Show_Arc<GT>());
2881 }, Unit_Weights);
2882
2883 k.expect();
2884}
2885
2886namespace
2887{
2891 template <class GT, class Run>
2892 void check_all_pairs_detection(Check & ints, Check & doubles, Check & hiding, Run && run)
2893 {
2894 for_each_weighted_spec([&] (const Spec & s)
2895 {
2896 Case<GT, int> c(s, shown_but(s, 0));
2897 run(ints, c, Dft_Show_Arc<GT>());
2898 });
2899
2900 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2901 {
2902 for_each_weighting(shape, Unit_Weights, [&] (const Spec & s)
2903 {
2904 Case<GT, double> c(s, shown_but(s, 0));
2905 run(doubles, c, Dft_Show_Arc<GT>());
2906 });
2907 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2908 {
2909 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
2910 {
2911 Case<GT, int> c(s, shown_but(s, hidden));
2912 c.label = "hiding " + std::to_string(hidden) + ": ";
2913 run(hiding, c, Hide_Mask<GT>{hidden});
2914 }
2915 });
2916 });
2917 }
2918}
2919
2920TYPED_TEST(ExhaustiveNegativeCycleSearches, FloydDetectsTheNegativeCycles)
2921{
2922 using GT = TypeParam;
2923 const std::string name = "Floyd_All_Shortest_Paths::has_negative_cycle()";
2924 Check ints(name);
2925 Check doubles(name + ", with double costs");
2926 Check hiding(name + ", hiding arcs");
2927
2928 check_all_pairs_detection<GT>(ints, doubles, hiding, [] (Check & k, auto & c, const auto & sa)
2929 {
2930 run_floyd(k, c, sa);
2931 });
2932
2933 ints.expect();
2934 doubles.expect();
2935 hiding.expect();
2936}
2937
2938TYPED_TEST(ExhaustiveNegativeCycleSearches, JohnsonDetectsTheNegativeCycles)
2939{
2940 using GT = TypeParam;
2941 const std::string name = "Johnson, its constructor";
2942 Check ints(name);
2943 Check doubles(name + ", with double costs");
2944 Check hiding(name + ", hiding arcs");
2945
2946 check_all_pairs_detection<GT>(ints, doubles, hiding, [] (Check & k, auto & c, const auto & sa)
2947 {
2948 run_johnson(k, c, sa);
2949 });
2950
2951 ints.expect();
2952 doubles.expect();
2953 hiding.expect();
2954}
2955
2956TYPED_TEST(ExhaustiveNegativeCycleSearches, FloydAndJohnsonWithAWhitelistMatchTheOracle)
2957{
2958 using GT = TypeParam;
2959 const std::string how = ", with a whitelist of numbers";
2960 Check floyd("Floyd_All_Shortest_Paths::has_negative_cycle()" + how);
2961 Check johnson("Johnson, its constructor" + how);
2962
2963 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
2964 {
2965 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
2966 {
2967 for (unsigned long shown = 0; shown < (1UL << s.num_arcs()); ++shown)
2968 {
2969 Case<GT, int> c(s, shown_only(s, shown));
2970 c.label = "showing " + std::to_string(shown) + ": ";
2971 const Show_Mask<GT> sa{shown};
2972 run_floyd(floyd, c, sa);
2973 run_johnson(johnson, c, sa);
2974 }
2975 });
2976 });
2977
2978 floyd.expect();
2979 johnson.expect();
2980}
2981
2982namespace
2983{
2986 template <class GT, typename T>
2987 bool least_means_fit(const Case<GT, T> & c)
2988 {
2989 long long num = 0, den = 1;
2990 if (not least_mean(c.t, num, den))
2991 return true;
2992 for (const auto & cy : c.t.cycles)
2993 if (cy.cost * den == num * (long long) cy.arcs.size()
2994 and (cy.cost < std::numeric_limits<int>::lowest()
2995 or cy.cost > std::numeric_limits<int>::max()))
2996 return false;
2997 return true;
2998 }
2999
3002 template <class F>
3003 void unless_it_overflows(Check & k, const Spec & s, bool allowed, const std::string & what,
3004 F && f)
3005 {
3006 try
3007 {
3008 f();
3009 }
3010 catch (const std::overflow_error & e)
3011 {
3012 if (not allowed)
3013 k.fail(s, what + ": throws " + e.what());
3014 }
3015 }
3016}
3017
3018TYPED_TEST(ExhaustiveNegativeCycleSearches, SearchesAndMeansNearTheLimitsOfInt)
3019{
3020 using GT = TypeParam;
3021 const std::string how = ", near the limits of int";
3022 Check disjoint("find_disjoint_negative_cycles()" + how);
3023 Check bounded("most_negative_cycle_bounded()" + how);
3024 Check short_cycle("most_negative_cycle_up_to_3()" + how);
3025 Check karp("karp_minimum_mean_cycle() and its value" + how);
3026 Check howard("howard_minimum_mean_cycle() and its value" + how);
3027
3028 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3029 {
3030 for_each_weighting(shape, Johnson_Limit_Weights, [&] (const Spec & s)
3031 {
3032 Case<GT, int> c(s, shown_but(s, 0));
3033 const GT & g = c.b.g;
3034 // The sums of the relaxations may leave int, which they say with
3035 // overflow_error
3036 const bool may_overflow = sums_may_overflow(s, c.show(),
3037 std::numeric_limits<int>::lowest(),
3038 std::numeric_limits<int>::max());
3039 unless_it_overflows(disjoint, s, may_overflow, "up to 64", [&]
3040 {
3041 disjoint.run();
3042 const auto items =
3043 find_disjoint_negative_cycles(g, 64, Negative_Cycle_Exclusion::Min_Weight_Arc, c.d);
3044 if (auto e = disjoint_error(c, items, 64, Negative_Cycle_Exclusion::Min_Weight_Arc);
3045 not e.empty())
3046 disjoint.fail(s, e);
3047 });
3048
3049 for (size_t len : {size_t(1), size_t(2), size_t(3)})
3050 {
3051 const std::string up_to = "up to " + std::to_string(len) + " arcs";
3052 const bool walks_overflow =
3053 walks_may_overflow(s, c.show(), len, std::numeric_limits<int>::lowest(),
3054 std::numeric_limits<int>::max());
3055 unless_it_overflows(bounded, s, walks_overflow, up_to, [&]
3056 {
3057 bounded.run();
3058 if (auto e = bounded_error(c, most_negative_cycle_bounded(g, len, c.d), len);
3059 not e.empty())
3060 bounded.fail(s, up_to + ": " + e);
3061 });
3062
3063 // Only the total of the best cycle has to fit
3064 long long least = 0;
3065 size_t fewest = 0;
3066 const bool has = least_cost(c.t, len, least, fewest);
3067 const bool out = has and (least < std::numeric_limits<int>::lowest()
3068 or least > std::numeric_limits<int>::max());
3069 unless_it_overflows(short_cycle, s, out, up_to, [&]
3070 {
3071 short_cycle.run();
3072 const auto r = most_negative_cycle_up_to_3(g, len, c.d);
3073 if (out)
3074 short_cycle.fail(s, up_to + ": gives a total out of int");
3075 else if (auto e = short_error(c, r, len); not e.empty())
3076 short_cycle.fail(s, up_to + ": " + e);
3077 });
3078 }
3079
3080 // A witness has to fit, and the values never overflow
3081 const bool fit = least_means_fit(c);
3082 unless_it_overflows(karp, s, not fit, "karp_minimum_mean_cycle()", [&]
3083 {
3084 karp.run();
3085 if (auto e = mean_error(c, karp_minimum_mean_cycle(g, c.d)); not e.empty())
3086 karp.fail(s, e);
3087 });
3088 unless_it_overflows(karp, s, false, "karp_minimum_mean_cycle_value()", [&]
3089 {
3090 karp.run();
3091 const auto r = karp_minimum_mean_cycle_value(g, c.d);
3092 bool has = false;
3093 long long num = 0, den = 1;
3094 const long double mean = least_mean_value(c, has, num, den);
3095 if (r.has_cycle != has or r.minimum_mean != mean)
3096 karp.fail(s, "the value gives " + text_of(r.minimum_mean));
3097 });
3098 unless_it_overflows(howard, s, not fit, "howard_minimum_mean_cycle()", [&]
3099 {
3100 howard.run();
3101 const auto r = howard_minimum_mean_cycle(g, c.d);
3102 if (auto e = mean_error(c, r); not e.empty())
3103 howard.fail(s, e);
3104 else if (auto e2 = howard_error(r); not e2.empty())
3105 howard.fail(s, e2);
3106 });
3107 unless_it_overflows(howard, s, false, "howard_minimum_mean_cycle_value()", [&]
3108 {
3109 howard.run();
3110 const auto r = howard_minimum_mean_cycle_value(g, c.d);
3111 bool has = false;
3112 long long num = 0, den = 1;
3113 const long double mean = least_mean_value(c, has, num, den);
3114 if (r.has_cycle != has or r.minimum_mean != mean)
3115 howard.fail(s, "the value gives " + text_of(r.minimum_mean));
3116 });
3117 });
3118 });
3119
3120 disjoint.expect();
3121 bounded.expect();
3122 short_cycle.expect();
3123 karp.expect();
3124 howard.expect();
3125}
3126
3127namespace
3128{
3132 struct Johnson_Answer_Checks
3133 {
3134 Check build;
3135 Check distance;
3136 Check path;
3137 Check all_pairs;
3138 Check potential;
3139 Check copy;
3140 Check graph;
3141
3142 explicit Johnson_Answer_Checks(const std::string & how)
3143 : build("Johnson, its constructor" + how),
3144 distance("Johnson::get_distance()" + how),
3145 path("Johnson::find_path()" + how),
3146 all_pairs("Johnson::compute_all_pairs_distances()" + how),
3147 potential("Johnson::get_potential()" + how),
3148 copy("Johnson::get_reweighted_graph() and get_copy_node()" + how),
3149 graph("Johnson, the graph that it takes" + how)
3150 {}
3151
3152 void expect() const
3153 {
3154 for (const Check * k : {&build, &distance, &path, &all_pairs, &potential, &copy, &graph})
3155 k->expect();
3156 }
3157 };
3158
3161 template <class GT>
3162 struct Attributes
3163 {
3164 using Of = std::tuple<int, std::vector<bool>, long, void *>;
3165
3166 std::vector<Of> nodes;
3167 std::vector<Of> arcs;
3168
3169 explicit Attributes(const Built<GT> & b)
3170 {
3171 auto bits = [] (const Bit_Fields & f)
3172 {
3173 std::vector<bool> r;
3174 for (int i = 0; i < Num_Bits_Graph; ++i)
3175 r.push_back(f.get_bit(i));
3176 return r;
3177 };
3178 for (auto * p : b.nodes)
3179 nodes.emplace_back(num(p), bits(NODE_BITS(p)), NODE_COUNTER(p), NODE_COOKIE(p));
3180 for (auto * a : b.arcs)
3181 arcs.emplace_back(num(a), bits(ARC_BITS(a)), ARC_COUNTER(a), ARC_COOKIE(a));
3182 }
3183
3184 bool operator == (const Attributes &) const = default;
3185 };
3186
3188 template <typename T>
3189 T unreached_by_johnson()
3190 {
3191 if constexpr (std::numeric_limits<T>::has_infinity)
3192 return std::numeric_limits<T>::infinity();
3193 else
3194 return std::numeric_limits<T>::max();
3195 }
3196
3200 template <class GT, typename T>
3201 std::string johnson_path_error(const Case<GT, T> & c, const Path<GT> & path, int u, int v)
3202 {
3203 const Walk w = walk_of(path);
3204 if (auto e = walk_error(c.s, w, c.show()); not e.empty())
3205 return e;
3206 if (w.nodes.front() != u or w.nodes.back() != v)
3207 return "the path " + w.str() + " does not go from " + std::to_string(u) + " to "
3208 + std::to_string(v);
3209 if (const long long want = c.t.dist[size_t(u)][size_t(v)]; cost_of(c.s, w) != want)
3210 return "the path " + w.str() + " costs " + std::to_string(cost_of(c.s, w)) + ", not "
3211 + std::to_string(want);
3212 return "";
3213 }
3214
3217 template <class F>
3218 void guarded_query(Check & k, const Spec & s, const std::string & where, F && f)
3219 {
3220 k.run();
3221 try
3222 {
3223 if (const std::string e = f(); not e.empty())
3224 k.fail(s, where + e);
3225 }
3226 catch (const std::exception & e)
3227 {
3228 k.fail(s, where + "throws " + e.what());
3229 }
3230 }
3231
3236 template <class GT, typename T, class SA>
3237 void check_johnson_answers(Johnson_Answer_Checks & k, Case<GT, T> & c, const SA & sa,
3238 T scale = T(1))
3239 {
3241 const Spec & s = c.s;
3242 const Attributes<GT> before(c.b);
3243 auto want = [&] (int u, int v)
3244 {
3245 const long long x = c.t.dist[size_t(u)][size_t(v)];
3246 return x == oracle::Inf ? unreached_by_johnson<T>() : T(x) * scale;
3247 };
3248
3249 k.build.run();
3250 std::unique_ptr<Solver> j;
3251 try
3252 {
3253 j = std::make_unique<Solver>(c.b.g, c.d, sa);
3254 }
3255 catch (const std::exception & e)
3256 {
3257 k.build.fail(s, c.label + "throws " + e.what());
3258 return;
3259 }
3260
3261 for (int u = 0; u < s.n; ++u)
3262 for (int v = 0; v < s.n; ++v)
3263 {
3264 auto * p = c.b.nodes[size_t(u)];
3265 auto * q = c.b.nodes[size_t(v)];
3266 const std::string where = c.label + "from " + std::to_string(u) + " to "
3267 + std::to_string(v) + ": ";
3268 guarded_query(k.distance, s, where, [&]
3269 {
3270 const T got = j->get_distance(p, q);
3271 return got == want(u, v) ? std::string()
3272 : "gives " + text_of(got) + ", not " + text_of(want(u, v));
3273 });
3274 guarded_query(k.path, s, where, [&]
3275 {
3276 const Path<GT> path = j->find_path(p, q);
3277 if (c.t.dist[size_t(u)][size_t(v)] != oracle::Inf)
3278 return johnson_path_error(c, path, u, v);
3279 return path.is_empty() ? std::string() : std::string("gives a path to a node not reached");
3280 });
3281 }
3282
3283 guarded_query(k.all_pairs, s, c.label, [&]
3284 {
3285 const auto all = j->compute_all_pairs_distances();
3286 if (all.size() != size_t(s.n) * size_t(s.n))
3287 return std::string("lacks pairs");
3288 for (int u = 0; u < s.n; ++u)
3289 for (int v = 0; v < s.n; ++v)
3290 {
3291 const auto * x = all.search({c.b.nodes[size_t(u)], c.b.nodes[size_t(v)]});
3292 if (x == nullptr or x->second != want(u, v))
3293 return "from " + std::to_string(u) + " to " + std::to_string(v) + " gives "
3294 + (x == nullptr ? std::string("nothing") : text_of(x->second));
3295 }
3296 return std::string();
3297 });
3298
3299 const auto h = potentials(c.t, s.n);
3300 guarded_query(k.potential, s, c.label, [&]
3301 {
3302 for (int v = 0; v < s.n; ++v)
3303 if (const T got = j->get_potential(c.b.nodes[size_t(v)]);
3304 got != T(h[size_t(v)]) * scale)
3305 return "of " + std::to_string(v) + " gives " + text_of(got);
3306 return std::string();
3307 });
3308
3309 // Every arc is copied: one that the filter shows with its new weight,
3310 // converted to the type of the info, and one that it hides with its
3311 // number
3312 guarded_query(k.copy, s, c.label, [&]
3313 {
3314 const GT & r = std::as_const(*j).get_reweighted_graph();
3315 std::multiset<std::tuple<int, int, int>> wanted, got;
3316 for (size_t i = 0; i < s.num_arcs(); ++i)
3317 {
3318 const int x = s.arcs[i][0], y = s.arcs[i][1];
3319 const T w = (T(s.w[i]) + T(h[size_t(x)]) - T(h[size_t(y)])) * scale;
3320 wanted.insert({x, y, c.show()[i] ? static_cast<int>(w) : int(i)});
3321 }
3322 for (auto it = r.get_arc_it(); it.has_curr(); it.next_ne())
3323 {
3324 auto * a = it.get_curr_ne();
3325 got.insert({num(r.get_src_node(a)), num(r.get_tgt_node(a)), a->get_info()});
3326 }
3327 if (j->get_reweighted_graph().get_num_nodes() != size_t(s.n) or got != wanted)
3328 return std::string("the copy is not the graph with the new weights");
3329 for (int v = 0; v < s.n; ++v)
3330 if (auto * p = j->get_copy_node(c.b.nodes[size_t(v)]); p == nullptr or num(p) != v)
3331 return "the copy of " + std::to_string(v) + " is another node";
3332 return std::string();
3333 });
3334
3335 k.graph.run();
3336 if (not (Attributes<GT>(c.b) == before))
3337 k.graph.fail(s, c.label + "the graph changed");
3338 }
3339
3343 struct Johnson_Limit_Checks
3344 {
3345 Check distance;
3346 Check path;
3347 Check all_pairs;
3348 Check copy;
3349 size_t saturated = 0;
3350
3351 explicit Johnson_Limit_Checks(const std::string & how)
3352 : distance("Johnson::get_distance()" + how),
3353 path("Johnson::find_path()" + how),
3354 all_pairs("Johnson::compute_all_pairs_distances()" + how),
3355 copy("Johnson::get_reweighted_graph()" + how)
3356 {}
3357
3358 void expect() const
3359 {
3360 distance.expect();
3361 path.expect();
3362 all_pairs.expect();
3363 copy.expect();
3364 }
3365 };
3366
3372 template <class GT>
3373 bool check_johnson_queries_near_the_limits(Johnson_Limit_Checks & k, Case<GT, int> & c)
3374 {
3375 using Solver = Johnson<GT, Spec_Weight<GT, int>>;
3376 constexpr long long lo = std::numeric_limits<int>::lowest();
3377 constexpr long long hi = std::numeric_limits<int>::max();
3378 const Spec & s = c.s;
3379 std::unique_ptr<Solver> j;
3380 try
3381 {
3382 j = std::make_unique<Solver>(c.b.g, c.d);
3383 }
3384 catch (const std::overflow_error &)
3385 {
3386 return false;
3387 }
3388
3389 auto fits = [&] (int u, int v)
3390 {
3391 const long long d = c.t.dist[size_t(u)][size_t(v)];
3392 return d == oracle::Inf or (d >= lo and d <= hi);
3393 };
3394 auto want = [&] (int u, int v)
3395 {
3396 const long long d = c.t.dist[size_t(u)][size_t(v)];
3397 return d == oracle::Inf ? std::numeric_limits<int>::max() : int(d);
3398 };
3399
3400 bool all_fit = true;
3401 for (int u = 0; u < s.n; ++u)
3402 for (int v = 0; v < s.n; ++v)
3403 {
3404 all_fit = all_fit and fits(u, v);
3405 auto * p = c.b.nodes[size_t(u)];
3406 auto * q = c.b.nodes[size_t(v)];
3407 const std::string where = "from " + std::to_string(u) + " to " + std::to_string(v)
3408 + ": ";
3409 k.distance.run();
3410 try
3411 {
3412 const int got = j->get_distance(p, q);
3413 if (not fits(u, v) or got != want(u, v))
3414 k.distance.fail(s, where + "gives " + std::to_string(got));
3415 }
3416 catch (const std::overflow_error & e)
3417 {
3418 if (fits(u, v))
3419 k.distance.fail(s, where + "throws " + e.what());
3420 }
3421
3422 k.path.run();
3423 try
3424 {
3425 const Path<GT> path = j->find_path(p, q);
3426 if (not fits(u, v))
3427 k.path.fail(s, where + "gives a path of a distance beyond int");
3428 else if (c.t.dist[size_t(u)][size_t(v)] == oracle::Inf)
3429 {
3430 if (not path.is_empty())
3431 k.path.fail(s, where + "gives a path to a node not reached");
3432 }
3433 else if (auto e = johnson_path_error(c, path, u, v); not e.empty())
3434 k.path.fail(s, where + e);
3435 }
3436 catch (const std::overflow_error & e)
3437 {
3438 if (fits(u, v))
3439 k.path.fail(s, where + "throws " + e.what());
3440 }
3441 }
3442
3443 k.all_pairs.run();
3444 try
3445 {
3446 const auto all = j->compute_all_pairs_distances();
3447 if (not all_fit)
3448 k.all_pairs.fail(s, "gives distances beyond int");
3449 else
3450 for (int u = 0; u < s.n; ++u)
3451 for (int v = 0; v < s.n; ++v)
3452 if (const auto * x = all.search({c.b.nodes[size_t(u)], c.b.nodes[size_t(v)]});
3453 x == nullptr or x->second != want(u, v))
3454 k.all_pairs.fail(s, "from " + std::to_string(u) + " to " + std::to_string(v)
3455 + ": a wrong distance");
3456 }
3457 catch (const std::overflow_error & e)
3458 {
3459 if (all_fit)
3460 k.all_pairs.fail(s, std::string("throws ") + e.what());
3461 }
3462
3463 k.copy.run();
3464 const auto h = potentials(c.t, s.n);
3465 std::multiset<std::tuple<int, int, long long>> wanted, got;
3466 bool saturated = false;
3467 for (size_t i = 0; i < s.num_arcs(); ++i)
3468 {
3469 const int x = s.arcs[i][0], y = s.arcs[i][1];
3470 const long long w = s.w[i] + h[size_t(x)] - h[size_t(y)];
3471 saturated = saturated or w > hi;
3472 wanted.insert({x, y, std::min(w, hi)});
3473 }
3474 k.saturated += saturated;
3475 const GT & r = j->get_reweighted_graph();
3476 for (auto it = r.get_arc_it(); it.has_curr(); it.next_ne())
3477 {
3478 auto * a = it.get_curr_ne();
3479 got.insert({num(r.get_src_node(a)), num(r.get_tgt_node(a)), (long long) a->get_info()});
3480 }
3481 if (got != wanted)
3482 k.copy.fail(s, "the copy is not the graph with the new weights");
3483
3484 return not all_fit;
3485 }
3486} // namespace
3487
3488TYPED_TEST(ExhaustiveNegativeCycleSearches, FloydAndJohnsonNearTheLimitsOfInt)
3489{
3490 using GT = TypeParam;
3491 const std::string how = ", near the limits of int";
3492 Check floyd("Floyd_All_Shortest_Paths::has_negative_cycle()" + how);
3493 Check johnson("Johnson, its constructor" + how);
3494 // A class of its own, which the harness found: a new weight w + h(u) -
3495 // h(v), or the sum w + h(u) on the way, out of the range of int although
3496 // every distance fits, which threw overflow_error while Johnson kept
3497 // them in int
3498 Check reweighting("Johnson, its constructor" + how + ", reweighting beyond int");
3499 size_t reweighted_beyond = 0;
3500
3501 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3502 {
3503 for_each_weighting(shape, Johnson_Limit_Weights, [&] (const Spec & s)
3504 {
3505 Case<GT, int> c(s, shown_but(s, 0));
3506
3507 // Floyd may throw overflow_error only with a weight below
3508 // lowest() / (2 (n - 1)), as it documents
3509 try
3510 {
3511 run_floyd(floyd, c, Dft_Show_Arc<GT>());
3512 }
3513 catch (const std::overflow_error &)
3514 {
3515 const long long least = *std::min_element(s.w.begin(), s.w.end());
3516 if (s.n < 2 or least >= std::numeric_limits<int>::lowest() / (2 * (s.n - 1)))
3517 floyd.fail(s, "throws overflow_error");
3518 }
3519
3520 // Where a sum of Bellman-Ford may leave int, overflow_error is
3521 // right too
3522 c.may_overflow = sums_may_overflow(s, c.show(), std::numeric_limits<int>::lowest(),
3523 std::numeric_limits<int>::max() - 1);
3524 const bool reweighted = not c.may_overflow and not c.t.negative
3525 and reweighting_overflows(c);
3526 reweighted_beyond += reweighted;
3527 run_johnson(reweighted ? reweighting : johnson, c, Dft_Show_Arc<GT>());
3528 });
3529 });
3530
3531 floyd.expect();
3532 johnson.expect();
3533 reweighting.expect();
3534 EXPECT_GT(reweighted_beyond, 0U);
3535}
3536
3537TYPED_TEST(ExhaustiveNegativeCycleSearches, JohnsonQueriesNearTheLimitsOfInt)
3538{
3539 using GT = TypeParam;
3540 // Two classes of their own, which the harness found: a distance beyond
3541 // max(), which made every query from its source throw while Johnson
3542 // painted its whole tree in int; and a sum of Dijkstra beyond max() on
3543 // the way to a node whose distance fits
3544 Johnson_Limit_Checks queries(", near the limits of int");
3545 size_t beyond = 0;
3546
3547 for_each_spec(sign_domain(), true, [&] (const Spec & shape)
3548 {
3549 for_each_weighting(shape, Johnson_Query_Weights, [&] (const Spec & s)
3550 {
3551 Case<GT, int> c(s, shown_but(s, 0));
3552 if (not c.t.negative and check_johnson_queries_near_the_limits(queries, c))
3553 ++beyond;
3554 });
3555 });
3556
3557 queries.expect();
3558 EXPECT_GT(beyond, 0U);
3559 EXPECT_GT(queries.saturated, 0U);
3560}
3561
3562TYPED_TEST(ExhaustiveNegativeCycleSearches, JohnsonAnswersOnTheArcsThatTheFilterShows)
3563{
3564 using GT = TypeParam;
3565 // Two classes of their own, which the harness found: a filter that
3566 // reads the numbers in the infos of the arcs, which once read the new
3567 // weights in the infos of the copies of the arcs, and a filter of
3568 // pointers to the arcs, which once got the copies; and parallel arcs,
3569 // one hidden, whose copies were paired with the arcs by their ends, so
3570 // that in List_SDigraph, whose arcs go in the order of their addresses,
3571 // the shown one could take the weight of the hidden one
3572 Johnson_Answer_Checks numbers(", with a whitelist of numbers");
3573 Johnson_Answer_Checks pointers(", with a whitelist of pointers");
3574
3575 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3576 {
3577 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
3578 {
3579 for (unsigned long shown = 0; shown < (1UL << s.num_arcs()); ++shown)
3580 {
3581 Case<GT, int> c(s, shown_only(s, shown));
3582 if (c.t.negative)
3583 continue;
3584 c.label = "showing " + std::to_string(shown) + ": ";
3585 check_johnson_answers(numbers, c, Show_Mask<GT>{shown});
3586 std::set<typename GT::Arc *> arcs;
3587 for (size_t i = 0; i < s.num_arcs(); ++i)
3588 if (c.show()[i])
3589 arcs.insert(c.b.arcs[i]);
3590 check_johnson_answers(pointers, c, Show_Arcs<GT>{&arcs});
3591 }
3592 });
3593 });
3594
3595 numbers.expect();
3596 pointers.expect();
3597}
3598
3599TYPED_TEST(ExhaustiveNegativeCycleSearches, JohnsonAnswersWithCostsThatHaveFractions)
3600{
3601 using GT = TypeParam;
3602 // A class of its own, which the harness found: double costs, the halves
3603 // of the weights, whose potentials and new weights have fractions, which
3604 // the answers once lost in the infos of the copies of the arcs, of type
3605 // int; the infos of the copy still lose them, as documented
3606 Johnson_Answer_Checks halves(", with the halves of the weights as double costs");
3607
3608 for_each_weighted_spec([&] (const Spec & s)
3609 {
3610 Case<GT, double> c(s, shown_but(s, 0));
3611 if (c.t.negative)
3612 return;
3613 for (double & x : c.w)
3614 x /= 2;
3615 check_johnson_answers(halves, c, Dft_Show_Arc<GT>(), 0.5);
3616 });
3617
3618 halves.expect();
3619}
3620
3621TYPED_TEST(ExhaustiveNegativeCycleSearches, RandomDigraphsMatchTheOracle)
3622{
3623 using GT = TypeParam;
3624 const std::string how = ", on random digraphs";
3625 Search_Checks searches(how);
3626 Mean_Checks means(how);
3627 All_Pairs_Checks all_pairs(how);
3628
3629 std::mt19937 rng(seed(79));
3630 for (int round = 0; round < (heavy() ? 1000 : 100); ++round)
3631 {
3632 const int n = 6 + int(rng() % 3);
3633 Spec s = random_spec(rng, n, n + int(rng() % size_t(n + 1)), true);
3634 random_weights(rng, s, -1 - (long long) (rng() % 4), 6);
3635 Case<GT, int> c(s, shown_but(s, 0));
3636 run_searches(searches, c, Dft_Show_Arc<GT>());
3637 run_means(means, c, Dft_Show_Arc<GT>());
3638 run_floyd(all_pairs.floyd, c, Dft_Show_Arc<GT>());
3639 run_johnson(all_pairs.johnson, c, Dft_Show_Arc<GT>());
3640 }
3641
3642 searches.expect();
3643 means.expect();
3644 all_pairs.expect();
3645}
3646
3647TYPED_TEST(ExhaustiveNegativeCycleSearches, DefaultArgumentsReadTheInfoOfTheArcs)
3648{
3649 using GT = TypeParam;
3650 Check bf("Bellman_Ford<GT>");
3651 Check others("the searches with Dft_Dist and Dft_Show_Arc");
3652
3653 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3654 {
3655 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
3656 {
3657 Case<GT, int> c(s, shown_but(s, 0));
3658 const auto numbers = weights_as_infos(c.b, s);
3659 auto number = [&] (typename GT::Arc * a)
3660 {
3661 const auto it = numbers.find(a);
3662 return it == numbers.end() ? -1 : it->second;
3663 };
3664 // The cycle of a path, a negative closed walk if want
3665 auto right = [&] (const Path<GT> & path, bool want)
3666 {
3667 if (path.is_empty())
3668 return not want;
3669 const Walk w = walk_of(path, number);
3670 return want and closed_walk_error(s, w, c.show(), true).empty()
3671 and cost_of(s, w) < 0;
3672 };
3673
3674 Check & k = bf;
3675 k.run();
3676 for (int u = 0; u < s.n; ++u)
3677 {
3678 auto * p = c.b.nodes[size_t(u)];
3679 const bool want = c.t.negative_from[size_t(u)];
3680 Path<GT> path(c.b.g);
3681 if (Bellman_Ford<GT>(c.b.g).has_negative_cycle(p) != want
3682 or Bellman_Ford<GT>(c.b.g).paint_spanning_tree(p) != want
3683 or not right(Bellman_Ford<GT>(c.b.g).test_negative_cycle(p), want)
3684 or not right(Bellman_Ford_Negative_Cycle<GT>()(c.b.g, p), want)
3685 or Bellman_Ford_Negative_Cycle<GT>()(c.b.g, p, path) != want
3686 or not right(path, want))
3687 k.fail(s, from_text(u) + "a wrong answer");
3688 }
3689 {
3690 Path<GT> path(c.b.g);
3691 if (Bellman_Ford<GT>(c.b.g).has_negative_cycle() != c.t.negative
3692 or not right(Bellman_Ford<GT>(c.b.g).search_negative_cycle(), c.t.negative)
3693 or not right(Bellman_Ford_Negative_Cycle<GT>()(c.b.g), c.t.negative)
3694 or Bellman_Ford_Negative_Cycle<GT>()(c.b.g, path) != c.t.negative
3695 or not right(path, c.t.negative))
3696 k.fail(s, "a wrong answer in the whole graph");
3697 }
3698
3699 // The answers that do not depend on the cycle that is chosen
3700 others.run();
3701 bool has_mean = false;
3702 long long num = 0, den = 1;
3703 const long double mean = least_mean_value(c, has_mean, num, den);
3704 long long least = 0;
3705 size_t fewest = 0;
3706 const bool has_short = least_cost(c.t, 3, least, fewest);
3707 const auto karp = karp_minimum_mean_cycle(c.b.g);
3708 const auto howard = howard_minimum_mean_cycle(c.b.g);
3709 const auto three = most_negative_cycle_up_to_3(c.b.g);
3710 const bool negative_bounded = most_negative_cycle_bounded(c.b.g, 3).is_negative();
3711 bool johnson_throws = false;
3712 try
3713 {
3714 Johnson<GT> j(c.b.g);
3715 }
3716 catch (const std::domain_error &)
3717 {
3718 johnson_throws = true;
3719 }
3720 if (karp.has_cycle != has_mean or karp.minimum_mean != mean
3721 or howard.has_cycle != has_mean or howard.minimum_mean != mean
3722 or three.has_cycle != has_short or (has_short and three.total_cost != least)
3723 or negative_bounded != (has_short and least < 0)
3724 or find_disjoint_negative_cycles(c.b.g, 8).is_empty() == c.t.negative
3726 != c.t.negative)
3727 or johnson_throws != c.t.negative)
3728 others.fail(s, "a wrong answer");
3729 });
3730 });
3731
3732 bf.expect();
3733 others.expect();
3734}
3735
3736template <class GT>
3737class ExhaustiveNegativeCyclesNotDirected : public ::testing::Test {};
3738
3740
3741TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, DetectionReadsEachArcFromItsSource)
3742{
3743 using GT = TypeParam;
3744 Detection_Checks k(", not directed");
3745
3746 for_each_weighted_spec([&] (const Spec & s)
3747 {
3748 Case<GT, int> c(s, shown_but(s, 0));
3749 run_detection(k, c, Dft_Show_Arc<GT>());
3750 });
3751
3752 k.expect();
3753}
3754
3755TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, WitnessesFromAStartReadEachArcFromItsSource)
3756{
3757 using GT = TypeParam;
3758 Witness_Checks k(false, ", not directed");
3759
3760 for_each_weighted_spec([&] (const Spec & s)
3761 {
3762 Case<GT, int> c(s, shown_but(s, 0));
3763 run_witnesses(k, c, Dft_Show_Arc<GT>(), false);
3764 });
3765
3766 k.expect();
3767}
3768
3769TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, WitnessesInTheWholeGraphReadEachArcFromItsSource)
3770{
3771 using GT = TypeParam;
3772 Witness_Checks k(true, ", not directed");
3773
3774 for_each_weighted_spec([&] (const Spec & s)
3775 {
3776 Case<GT, int> c(s, shown_but(s, 0));
3777 run_witnesses(k, c, Dft_Show_Arc<GT>(), true);
3778 });
3779
3780 k.expect();
3781}
3782
3783TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, TheTreeReadsEachArcFromItsSource)
3784{
3785 using GT = TypeParam;
3786 Tree_Checks k(", not directed");
3787
3788 for_each_weighted_spec([&] (const Spec & s)
3789 {
3790 Case<GT, int> c(s, shown_but(s, 0));
3792 });
3793
3794 k.expect();
3795}
3796
3797TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, FunctorsWithOutIteratorReadEachArcFromItsSource)
3798{
3799 using GT = TypeParam;
3800 Functor_Checks k(", not directed, with Out_Iterator");
3801
3802 for_each_weighted_spec([&] (const Spec & s)
3803 {
3804 Case<GT, int> c(s, shown_but(s, 0));
3805 run_functors<Out_Iterator>(k, c, Dft_Show_Arc<GT>());
3806 });
3807
3808 k.expect();
3809}
3810
3811TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, FunctorsWithTheirDefaultIteratorReadEachArc)
3812{
3813 using GT = TypeParam;
3814 Functor_Checks k(", not directed");
3815
3816 for_each_weighted_spec([&] (const Spec & s)
3817 {
3818 Case<GT, int> c(s, shown_but(s, 0));
3819 run_functors<Node_Arc_Iterator>(k, c, Dft_Show_Arc<GT>());
3820 });
3821
3822 k.expect();
3823}
3824
3825TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, TheOtherSearchesRejectTheGraph)
3826{
3827 using GT = TypeParam;
3828 Check rejected("Negative_Cycles.H, Karp and Howard, on a graph that is not directed");
3829 Check empty("Negative_Cycles.H, with max_cycles or max_length 0,"
3830 " on a graph that is not directed");
3831
3832 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3833 {
3834 Spec s = shape;
3835 s.w.assign(s.num_arcs(), -1);
3836 Case<GT, int> c(s, shown_but(s, 0));
3837 const GT & g = c.b.g;
3838 int thrown = 0;
3839 auto count = [&] (auto && call)
3840 {
3841 try
3842 {
3843 call();
3844 }
3845 catch (const std::domain_error &)
3846 {
3847 ++thrown;
3848 }
3849 };
3850 rejected.run();
3851 count([&] { find_disjoint_negative_cycles(g, 1, Negative_Cycle_Exclusion::All_Arcs, c.d); });
3852 count([&] { most_negative_cycle_bounded(g, 2, c.d); });
3853 count([&] { most_negative_cycle_up_to_3(g, 2, c.d); });
3854 count([&] { karp_minimum_mean_cycle(g, c.d); });
3855 count([&] { karp_minimum_mean_cycle_value(g, c.d); });
3856 count([&] { howard_minimum_mean_cycle(g, c.d); });
3857 count([&] { howard_minimum_mean_cycle_value(g, c.d); });
3858 if (thrown != 7)
3859 rejected.fail(s, std::to_string(7 - thrown) + " of 7 do not throw domain_error");
3860
3861 // With nothing to search, the graph is not looked at
3862 empty.run();
3863 if (not find_disjoint_negative_cycles(g, 0, Negative_Cycle_Exclusion::All_Arcs, c.d)
3864 .is_empty()
3865 or most_negative_cycle_bounded(g, 0, c.d).has_cycle
3866 or most_negative_cycle_up_to_3(g, 0, c.d).has_cycle)
3867 empty.fail(s, "a cycle");
3868 });
3869
3870 rejected.expect();
3871 empty.expect();
3872}
3873
3874namespace
3875{
3879 template <class GT>
3880 std::string undirected_path_error(const Case<GT, int> & c, const Path<GT> & path, int u,
3881 int v, long long want)
3882 {
3883 const Walk w = walk_of(path);
3884 if (w.nodes.empty() or w.nodes.size() != w.arcs.size() + 1)
3885 return "the path " + w.str() + " is empty or lacks arcs";
3886 if (w.nodes.front() != u or w.nodes.back() != v)
3887 return "the path " + w.str() + " does not go from " + std::to_string(u) + " to "
3888 + std::to_string(v);
3889 long long cost = 0;
3890 for (size_t i = 0; i < w.arcs.size(); ++i)
3891 {
3892 const auto & ends = c.s.arcs[size_t(w.arcs[i])];
3893 const std::set<int> joined = {ends[0], ends[1]}, walked = {w.nodes[i], w.nodes[i + 1]};
3894 if (joined != walked)
3895 return "the path " + w.str() + " does not follow the arc " + std::to_string(w.arcs[i]);
3896 if (not c.show()[size_t(w.arcs[i])])
3897 return "the path " + w.str() + " takes a hidden arc";
3898 cost += c.s.w[size_t(w.arcs[i])];
3899 }
3900 return cost == want ? "" : "the path " + w.str() + " costs " + std::to_string(cost);
3901 }
3902
3907 template <class GT, class SA>
3908 void run_johnson_not_directed(Check & k, Case<GT, int> & c, const SA & sa)
3909 {
3910 bool negative = false;
3911 const auto d = oracle::shortest_distances(shown_spec(c.s, c.show()), false, negative);
3912 k.run();
3913 try
3914 {
3916 if (negative)
3917 {
3918 k.fail(c.s, c.label + "does not throw on a negative cycle");
3919 return;
3920 }
3921 for (int u = 0; u < c.s.n; ++u)
3922 for (int v = 0; v < c.s.n; ++v)
3923 {
3924 const long long want = d[size_t(u)][size_t(v)];
3925 auto * p = c.b.nodes[size_t(u)];
3926 auto * q = c.b.nodes[size_t(v)];
3927 const std::string where = c.label + "from " + std::to_string(u) + " to "
3928 + std::to_string(v) + ": ";
3929 const int got = j.get_distance(p, q);
3930 if (got != (want == oracle::Inf ? std::numeric_limits<int>::max() : int(want)))
3931 k.fail(c.s, where + "gives " + std::to_string(got));
3932 const Path<GT> path = j.find_path(p, q);
3933 if (want == oracle::Inf ? not path.is_empty()
3934 : not undirected_path_error(c, path, u, v, want).empty())
3935 k.fail(c.s, where + "a wrong path");
3936 }
3937 }
3938 catch (const std::domain_error &)
3939 {
3940 if (not negative)
3941 k.fail(c.s, c.label + "throws domain_error without a negative cycle");
3942 }
3943 }
3944}
3945
3946TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, JohnsonTakesEachArcInBothDirections)
3947{
3948 using GT = TypeParam;
3949 Check k("Johnson, not directed");
3950 Check hiding("Johnson, not directed, hiding arcs");
3951
3952 for_each_weighted_spec([&] (const Spec & s)
3953 {
3954 Case<GT, int> c(s, shown_but(s, 0));
3955 run_johnson_not_directed(k, c, Dft_Show_Arc<GT>());
3956 });
3957
3958 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3959 {
3960 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
3961 {
3962 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
3963 {
3964 Case<GT, int> c(s, shown_but(s, hidden));
3965 c.label = "hiding " + std::to_string(hidden) + ": ";
3966 run_johnson_not_directed(hiding, c, Hide_Mask<GT>{hidden});
3967 }
3968 });
3969 });
3970
3971 k.expect();
3972 hiding.expect();
3973}
3974
3975TYPED_TEST(ExhaustiveNegativeCyclesNotDirected, FloydTakesEachArcInBothDirections)
3976{
3977 using GT = TypeParam;
3978 Check k("Floyd_All_Shortest_Paths::has_negative_cycle(), not directed");
3979 Check hiding("Floyd_All_Shortest_Paths::has_negative_cycle(), not directed, hiding arcs");
3980
3981 for_each_weighted_spec([&] (const Spec & s)
3982 {
3983 Case<GT, int> c(s, shown_but(s, 0));
3984 run_floyd(k, c, Dft_Show_Arc<GT>());
3985 });
3986
3987 for_each_spec(small_weights_domain(), true, [&] (const Spec & shape)
3988 {
3989 for_each_weighting(shape, Sign_Weights, [&] (const Spec & s)
3990 {
3991 for (unsigned long hidden = 1; hidden < (1UL << s.num_arcs()); ++hidden)
3992 {
3993 Case<GT, int> c(s, shown_but(s, hidden));
3994 c.label = "hiding " + std::to_string(hidden) + ": ";
3995 run_floyd(hiding, c, Hide_Mask<GT>{hidden});
3996 }
3997 });
3998 });
3999
4000 k.expect();
4001 hiding.expect();
4002}
Bellman-Ford algorithm for single-source shortest paths.
Floyd-Warshall algorithm for all-pairs shortest paths.
Minimum mean cycle by Howard's policy iteration.
Johnson's algorithm for all-pairs shortest paths.
Minimum mean cycle in directed graphs (Karp algorithm).
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t steps
Definition ca-c-api.h:126
size_t size_t int32_t * out
Definition ca-c-api.h:120
Bellman-Ford algorithm for shortest paths with negative weights.
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
std::tuple< Path< GT >, size_t > search_negative_cycle(Node *start, double it_factor, const size_t step)
Searches a negative cycle using the faster version of Bellman-Ford algorithm and iteratively searchin...
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
Path< GT > test_negative_cycle(Node *start)
Search a negative cycle on all possible paths starting from start node.
Bit fields for nodes and arcs used for marking visit state during processing.
Compute the all-pairs shortest path distance matrix and the path reconstruction matrix for a graph g ...
constexpr bool has_negative_cycle() const noexcept
Check if the graph contains a negative cycle.
Johnson's algorithm for all-pairs shortest paths.
Definition Johnson.H:216
Functor wrapper for value-only minimum mean cycle.
Functor wrapper for Karp minimum mean cycle.
Key * search(const Key &key) noexcept
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition tpl_odhash.H:657
Filtered iterator for outcoming arcs of a node.
Definition tpl_graph.H:1942
Iterator on nodes and arcs of a path.
Definition tpl_graph.H:4395
bool has_current_node() const noexcept
Return true if the iterator has a current node.
Definition tpl_graph.H:4512
Path on a graph.
Definition tpl_graph.H:3832
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
auto get_arc_it() const noexcept
Obtains an iterator to the arc of graph.
Definition graph-dry.H:3144
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Definition graph-dry.H:3122
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
The failures of one property over a domain.
void expect() const
Expects what the mark says, and prints the first failures.
void fail(const Spec &s, const std::string &what)
Counts a failure on spec, with what went wrong.
void run() noexcept
Counts a run of the property.
static mt19937 rng
__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
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
TYPED_TEST_SUITE(ExhaustiveBellmanFord, Directed_Kinds)
TYPED_TEST(ExhaustiveBellmanFord, DetectionMatchesTheOracle)
The kinds of arc filter and of distance that the graph algorithms must accept.
Every small multigraph, on every kind of graph, for the tests.
Answers computed from a Spec of graph_harness.H, without Aleph.
DynArray< Graph::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().
DynList< Negative_Cycle_Item< GT, typename Distance::Distance_Type > > find_disjoint_negative_cycles(const GT &g, const size_t max_cycles, const Negative_Cycle_Exclusion exclusion=Negative_Cycle_Exclusion::Min_Weight_Arc, Distance distance=Distance(), SA sa=SA())
Find up to max_cycles negative cycles, excluding arcs of each cycle found before searching for the ne...
#define ARC_COOKIE(p)
Return the arc cookie
Bounded_Cycle_Result< GT, typename Distance::Distance_Type > most_negative_cycle_bounded(const GT &g, const size_t max_length, Distance distance=Distance(), SA sa=SA())
Most negative simple cycle of at most max_length arcs, ranked by total cost (not by mean cost as Karp...
#define NODE_COUNTER(p)
Get the counter of a node.
#define ARC_COUNTER(p)
Return the counter of arc p.
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).
#define IS_NODE_VISITED(p, bit)
Determine whether the control bit is set or not to one.
#define ARC_BITS(p)
Return the control bits of arc p.
#define NODE_COOKIE(p)
Return the node cookie
Negative_Cycle_Exclusion
Which arcs of a found negative cycle are excluded before searching for the next one in find_disjoint_...
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.
Short_Cycle_Result< GT, typename Distance::Distance_Type > most_negative_cycle_up_to_3(const GT &g, const size_t max_length=3, Distance distance=Distance(), SA sa=SA())
Minimum-total-cost simple cycle with at most one, two or three arcs.
#define IS_ARC_VISITED(p, bit)
Determine whether the bit field is or not set to one.
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.
#define NODE_BITS(p)
Get the control bits of a node.
@ Depth_First
Definition aleph-graph.H:73
@ Num_Bits_Graph
Definition aleph-graph.H:85
@ Spanning_Tree
Definition aleph-graph.H:79
@ All_Arcs
Exclude every arc of the cycle.
static mpfr_t y
Definition mpfr_mul_d.c:3
User-facing facade exported by the umbrella search header.
void build(Tree_Node< Key > *troot, Convert &&convert, typename GT::Node *groot, Args &&... args)
constexpr Word bounded(Next &&next, const Word n) noexcept(noexcept(next()))
An integer in [0, n), each with the same probability, from numbers of the bits of Word: the method of...
Definition ah-random.H:773
Main namespace for Aleph-w library functions.
@ Run
Execute the lowered HIR module with Interpreter_Runtime.
@ Call
dst <- callee(args...)
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
constexpr Bit_Column bits(const unsigned n)
Column of n bits without sign: the integers of [0, 2^n - 1].
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
void expect(std::ifstream &input_stream, const std::string &expected)
Expect and consume a specific string/keyword.
@ Cycle
Graph has an Eulerian cycle.
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
Itor1 search(Itor1 beg, const Itor1 &end, Itor2 searchBeg, const Itor2 &searchEnd, BinaryPredicate op=BinaryPredicate())
Search for a subrange within a range.
Definition ahAlgo.H:309
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
bool binary_search(Itor beg, Itor end, const T &value)
Binary search for a value.
Definition ahAlgo.H:1284
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
constexpr bool shown(unsigned long hidden, int i) noexcept
Whether the arc number i is shown by the mask hidden.
::testing::Types< Aleph::List_Digraph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SDigraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Digraph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > > > Directed_Kinds
The directed kinds, with int infos.
::testing::Types< Aleph::List_Graph< Aleph::Graph_Node< int >, Aleph::Graph_Arc< int > >, Aleph::List_SGraph< Aleph::Graph_Snode< int >, Aleph::Graph_Sarc< int > >, Aleph::Array_Graph< Aleph::Graph_Anode< int >, Aleph::Graph_Aarc< int > > > Undirected_Kinds
The kinds of graph that are not directed, with int infos.
size_t for_each_spec(const Domain &d, bool directed, F &&f)
Calls f(spec) with every spec of d, smallest first, and returns how many there were.
Spec random_spec(std::mt19937 &rng, int n, int m, bool directed, bool loops=true, bool parallel=true)
A random spec of n nodes and m arcs, with loops and parallel arcs if asked; parallel is ignored when ...
int num(Node *p)
The number of a node of a built graph.
Domain domain(int max_nodes, int max_arcs)
The domain of max_nodes nodes and max_arcs arcs, of one more of each in heavy mode,...
bool heavy()
Whether the mode is heavy, which asks for the larger domains.
void random_weights(std::mt19937 &rng, Spec &s, long long lo, long long hi)
Gives each arc of s a weight from lo to hi.
constexpr long long Inf
No distance, in the matrices of the oracles.
std::vector< std::vector< long long > > shortest_distances(const Spec &s, bool directed, bool &neg)
Floyd on a matrix of long long: the shortest distances, Inf where there is no path,...
std::vector< std::vector< bool > > closure(const Spec &s, bool directed)
reach[u][v]: v is reached from u by a directed path of one arc or more (in a graph that is not direct...
bool reaches(const std::vector< std::vector< bool > > &r, int u, int v)
Whether there is a path, of zero arcs or more, from u to v.
Spec without(const Spec &s, unsigned long hidden, std::vector< int > &orig)
The spec without the arcs whose numbers are set in hidden, with orig[i] the number in s of its i-th a...
STL namespace.
#define LL
Definition ran_array.c:24
Filtered iterator on all the arcs of a graph.
Definition tpl_graph.H:1200
Detects if a negative cycle exists and eventually computes it.
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Hides the arcs of a mask; copyable, assignable, noexcept.
A graph made from a spec, with its nodes and arcs by number.
std::vector< typename GT::Node * > nodes
std::vector< typename GT::Arc * > arcs
Which multigraphs for_each_spec() gives.
A small multigraph: its nodes are 0 .
std::vector< long long > w
size_t num_arcs() const noexcept
std::vector< std::array< int, 2 > > arcs
void test()
Definition test-comb.C:40
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
bool check(GT &g)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
void run_tree(unsigned long n, Gsl_Compatible_Rng &r)
Generic graph and digraph implementations.