Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
bench_negative_cycles.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 https://github.com/lrleon/Aleph-w
6
7 This file is part of Aleph-w library
8
9 Copyright (c) 2002-2026 Leandro Rabindranath Leon
10*/
11
132#include <algorithm>
133#include <charconv>
134#include <chrono>
135#include <cmath>
136#include <cstdint>
137#include <cstdio>
138#include <cstdlib>
139#include <cstring>
140#include <functional>
141#include <memory>
142#include <new>
143#include <random>
144#include <string>
145#include <system_error>
146#include <tuple>
147#include <vector>
148
149#include <Bellman_Ford.H>
151#include <Min_Mean_Cycle.H>
152#include <Negative_Cycles.H>
153#include <tpl_array.H>
154#include <tpl_dynList.H>
155#include <tpl_dynMapTree.H>
156#include <tpl_dynSetTree.H>
157#include <tpl_graph.H>
158
159#include "../ca/bench_support.H"
160
161using namespace Aleph;
162
163// ---------------------------------------------------------------------------
164// Allocation probe: counts calls to the global operator new while `active`.
165// ---------------------------------------------------------------------------
166
167namespace
168{
169struct Alloc_Probe
170{
171 bool active = false;
172 size_t calls = 0;
173 size_t bytes = 0;
174};
175
176Alloc_Probe alloc_probe;
177} // namespace
178
179// The replacement functions are not inlined: GCC cannot then pair a malloc
180// behind `operator new` with a free behind `operator delete` and warn about a
181// mismatch (-Wmismatched-new-delete), and the probe costs the same everywhere.
182#if defined(__GNUC__)
183#define BENCH_NOINLINE __attribute__((noinline))
184#else
185#define BENCH_NOINLINE
186#endif
187
188BENCH_NOINLINE void * operator new(const std::size_t size)
189{
190 if (alloc_probe.active)
191 {
192 ++alloc_probe.calls;
193 alloc_probe.bytes += size;
194 }
195 if (void * p = std::malloc(size == 0 ? 1 : size))
196 return p;
197 std::fputs("bench_negative_cycles: out of memory\n", stderr);
198 std::abort();
199}
200
201BENCH_NOINLINE void * operator new[](const std::size_t size) { return operator new(size); }
202BENCH_NOINLINE void operator delete(void * p) noexcept { std::free(p); }
203BENCH_NOINLINE void operator delete[](void * p) noexcept { std::free(p); }
204BENCH_NOINLINE void operator delete(void * p, std::size_t) noexcept { std::free(p); }
205BENCH_NOINLINE void operator delete[](void * p, std::size_t) noexcept { std::free(p); }
206
207namespace
208{
209
211using Node = Graph::Node;
212using Arc = Graph::Arc;
216using Exclusion = Negative_Cycle_Exclusion;
217
218volatile long sink = 0; // keeps results observable for the optimizer
219
220// `sink += v` on a volatile is deprecated in C++20.
221void keep(const long v) { sink = sink + v; }
222
223constexpr size_t num_hubs = 4;
224constexpr double fee = 0.001; // 0.1 % per trade
225constexpr size_t seeded_triangles = 5;
226constexpr double triangle_profit = 0.012; // -log of the gain of one triangle
227constexpr size_t min_assets = num_hubs + 3 * seeded_triangles;
228constexpr size_t max_assets = 20000;
229constexpr size_t max_samples = 100000;
230constexpr size_t min_regression_samples = 30;
231constexpr size_t bounded_max_nodes = 1000; // bounded variants are skipped above this
232constexpr size_t dense_max_nodes = 120;
233constexpr size_t reweight_rounds = 8;
234constexpr size_t component_size = 12;
235constexpr size_t loop_isolated_factor = 50; // isolated vertices per asset
236constexpr size_t loop_isolated_max = 20000;
237constexpr size_t scc_pair_isolated_factor = 10; // vertices per asset
238constexpr size_t scc_pair_isolated_max = 4000;
239constexpr size_t scc_pairs_max = 300; // vertices of `scc-pairs`
240constexpr size_t long_bound_max_nodes = 400; // `components` runs L = V up to here
241constexpr size_t warmup_min_runs = 2;
242constexpr size_t warmup_max_runs = 200;
243constexpr double warmup_ms = 30.0;
244
245// ---------------------------------------------------------------------------
246// Argument parsing
247// ---------------------------------------------------------------------------
248
249// Parses the whole of `text` as a decimal unsigned integer in [lo, hi].
250// No sign, blank, prefix or trailing character is accepted.
251bool parse_uint(const char * text, const unsigned long long lo,
252 const unsigned long long hi, unsigned long long & out)
253{
254 if (text == nullptr or *text == '\0')
255 return false;
256 const char * end = text + std::strlen(text);
257 unsigned long long value = 0;
258 const auto [ptr, ec] = std::from_chars(text, end, value);
259 if (ec != std::errc() or ptr != end or value < lo or value > hi)
260 return false;
261 out = value;
262 return true;
263}
264
265struct Options
266{
267 size_t assets = 300;
268 size_t samples = 31;
269 unsigned seed = 42;
270 bool check_only = false;
271 std::string only;
272};
273
274void usage(std::FILE * out)
275{
276 std::fprintf(out,
277 "usage: bench_negative_cycles [num_assets] [samples] [seed] [--check-only] [--only=<text>]\n"
278 " num_assets integer in [%zu, %zu] (default 300)\n"
279 " samples integer in [1, %zu] (default 31; < %zu is exploratory)\n"
280 " seed integer in [0, 4294967295] (default 42)\n"
281 " --check-only validate the results, do not time anything\n"
282 " --only=<text> keep the graph families whose name contains <text>\n",
283 min_assets, max_assets, max_samples, min_regression_samples);
284}
285
286// Returns true if the command line is valid; otherwise prints why.
287bool parse_args(const int argc, char * argv[], Options & opt)
288{
289 struct Positional
290 {
291 const char * name;
292 unsigned long long lo;
293 unsigned long long hi;
294 };
295 const Positional positional[] =
296 {{"num_assets", min_assets, max_assets},
297 {"samples", 1, max_samples},
298 {"seed", 0, 4294967295ULL}};
299
300 size_t next = 0;
301 for (int i = 1; i < argc; ++i)
302 {
303 const char * arg = argv[i];
304 if (std::strcmp(arg, "--check-only") == 0)
305 opt.check_only = true;
306 else if (std::strncmp(arg, "--only=", 7) == 0)
307 opt.only = arg + 7;
308 else if (std::strcmp(arg, "--help") == 0 or std::strcmp(arg, "-h") == 0)
309 {
310 usage(stdout);
311 std::exit(0);
312 }
313 else if (std::strncmp(arg, "--", 2) == 0)
314 {
315 std::fprintf(stderr, "unknown option '%s'\n", arg);
316 return false;
317 }
318 else if (next >= 3)
319 {
320 std::fprintf(stderr, "unexpected argument '%s'\n", arg);
321 return false;
322 }
323 else
324 {
325 const Positional & p = positional[next];
326 unsigned long long value = 0;
327 if (not parse_uint(arg, p.lo, p.hi, value))
328 {
329 std::fprintf(stderr,
330 "%s must be a decimal integer in [%llu, %llu], got '%s'\n",
331 p.name, p.lo, p.hi, arg);
332 return false;
333 }
334 if (next == 0)
335 opt.assets = static_cast<size_t>(value);
336 else if (next == 1)
337 opt.samples = static_cast<size_t>(value);
338 else
339 opt.seed = static_cast<unsigned>(value);
340 ++next;
341 }
342 }
343 return true;
344}
345
346// ---------------------------------------------------------------------------
347// Graph specifications and instances
348// ---------------------------------------------------------------------------
349
350struct Arc_Spec
351{
352 size_t u;
353 size_t v;
354 double w;
355 bool cut; // seeded-triangle arc (market weights only)
356};
357
358struct Spec
359{
360 size_t nodes = 0;
361 size_t isolated = 0; // extra vertices without arcs
362 Array<double> lp; // log-price per node (market families)
363 Array<Arc_Spec> arcs; // in insertion order
364 size_t seeded = 0; // arc-disjoint negative cycles planted
365 bool negative = false; // ground truth: a negative cycle exists
366};
367
368double fee_term() { return -std::log(1.0 - fee); }
369
370double market_weight(const Spec & s, const Arc_Spec & a)
371{
372 const double w = s.lp(a.v) - s.lp(a.u) + fee_term();
373 return a.cut ? w - (fee_term() + triangle_profit / 3.0) : w;
374}
375
376void draw_prices(Spec & s, std::mt19937 & rng)
377{
378 std::uniform_real_distribution<double> log_price(-3.0, 3.0);
379 for (size_t i = 0; i < s.nodes; ++i)
380 s.lp(i) = log_price(rng);
381}
382
383void both_ways(Spec & s, const size_t u, const size_t v)
384{
385 s.arcs.append(Arc_Spec{u, v, market_weight(s, {u, v, 0, false}), false});
386 s.arcs.append(Arc_Spec{v, u, market_weight(s, {v, u, 0, false}), false});
387}
388
389void plant_triangles(Spec & s)
390{
391 for (size_t t = 0; t < seeded_triangles; ++t)
392 {
393 const size_t a = num_hubs + 3 * t;
394 const size_t b = a + 1;
395 const size_t c = a + 2;
396 if (c >= s.nodes)
397 break;
398 for (const auto & uv : {std::pair<size_t, size_t>{a, b}, {b, c}, {c, a}})
399 {
400 Arc_Spec arc{uv.first, uv.second, 0, true};
401 arc.w = market_weight(s, arc);
402 s.arcs.append(arc);
403 }
404 ++s.seeded;
405 }
406 s.negative = s.seeded > 0;
407}
408
409// The market of the original benchmark; the random draws keep their order so
410// that a given (n, seed) is the same multigraph as before.
411Spec market_spec(const size_t n, const bool arbitrage, const unsigned seed)
412{
413 std::mt19937 rng(seed);
414 std::uniform_real_distribution<double> log_price(-3.0, 3.0);
415
416 Spec s;
417 s.nodes = n;
418 for (size_t i = 0; i < n; ++i)
419 s.lp.append(log_price(rng));
420
421 for (size_t h = 0; h < num_hubs; ++h)
422 for (size_t v = h + 1; v < n; ++v)
423 both_ways(s, h, v);
424
425 std::uniform_int_distribution<size_t> pick(num_hubs, n - 1);
426 for (size_t k = 0; k < n; ++k)
427 {
428 const size_t u = pick(rng);
429 const size_t v = pick(rng);
430 if (u != v)
431 both_ways(s, u, v);
432 }
433
434 if (arbitrage)
435 plant_triangles(s);
436 return s;
437}
438
439// Complete digraph with consistent prices and one planted triangle.
440Spec dense_spec(const size_t n, const unsigned seed)
441{
442 std::mt19937 rng(seed + 1);
443 Spec s;
444 s.nodes = n;
445 for (size_t i = 0; i < n; ++i)
446 s.lp.append(0.0);
447 draw_prices(s, rng);
448 for (size_t u = 0; u < n; ++u)
449 for (size_t v = 0; v < n; ++v)
450 if (u != v)
451 s.arcs.append(Arc_Spec{u, v, market_weight(s, {u, v, 0, false}), false});
452 for (const auto & uv : {std::pair<size_t, size_t>{0, 1}, {1, 2}, {2, 0}})
453 {
454 Arc_Spec arc{uv.first, uv.second, 0, true};
455 arc.w = market_weight(s, arc);
456 s.arcs.append(arc);
457 }
458 s.seeded = 1;
459 s.negative = true;
460 return s;
461}
462
463// Forward arcs only, weights in [-1, 1]: negative arcs but no cycle at all.
464Spec dag_spec(const size_t n, const unsigned seed)
465{
466 std::mt19937 rng(seed + 2);
467 std::uniform_real_distribution<double> weight(-1.0, 1.0);
468 Spec s;
469 s.nodes = n;
470 for (size_t i = 0; i + 1 < n; ++i)
471 {
472 std::uniform_int_distribution<size_t> pick(i + 1, n - 1);
473 for (size_t k = 0; k < 4; ++k)
474 s.arcs.append(Arc_Spec{i, pick(rng), weight(rng), false});
475 }
476 return s;
477}
478
479// Disjoint strongly connected components of `component_size` nodes with
480// positive weights; one in three gets a negative triangle on its first three
481// ring nodes (closing arc c -> a makes the triangle cost -0.01).
482Spec components_spec(const size_t n, const unsigned seed)
483{
484 std::mt19937 rng(seed + 3);
485 std::uniform_real_distribution<double> weight(0.5, 1.5);
486 const size_t comps = std::max<size_t>(1, n / component_size);
487
488 Spec s;
489 s.nodes = comps * component_size;
490 for (size_t c = 0; c < comps; ++c)
491 {
492 const size_t base = c * component_size;
493 Array<double> ring;
494 for (size_t i = 0; i < component_size; ++i)
495 {
496 ring.append(weight(rng));
497 s.arcs.append(Arc_Spec{base + i, base + (i + 1) % component_size, ring(i), false});
498 }
499 std::uniform_int_distribution<size_t> pick(0, component_size - 1);
500 for (size_t k = 0; k < component_size; ++k)
501 {
502 const size_t u = pick(rng);
503 const size_t v = pick(rng);
504 if (u != v)
505 s.arcs.append(Arc_Spec{base + u, base + v, weight(rng), false});
506 }
507 if (c % 3 == 0)
508 {
509 s.arcs.append(Arc_Spec{base + 2, base, -(ring(0) + ring(1)) - 0.01, false});
510 ++s.seeded;
511 }
512 }
513 s.negative = s.seeded > 0;
514 return s;
515}
516
517// One negative self-loop and nothing else but isolated vertices: the search
518// has to cope with a graph that is almost all dead weight.
519Spec loop_isolated_spec(const size_t n)
520{
521 Spec s;
522 s.nodes = std::min(loop_isolated_factor * n, loop_isolated_max);
523 s.arcs.append(Arc_Spec{0, 0, -1.0, false});
524 s.seeded = 1;
525 s.negative = true;
526 return s;
527}
528
529// Appends the pair of audit H6 on nodes a and b: a -> b -> a costs 0, and b
530// has a self-loop of -1. Closed walks of every length start at both nodes.
531void scc_pair(Spec & s, const size_t a, const size_t b)
532{
533 s.arcs.append(Arc_Spec{a, b, 0.0, false});
534 s.arcs.append(Arc_Spec{b, b, -1.0, false});
535 s.arcs.append(Arc_Spec{b, a, 0.0, false});
536 ++s.seeded;
537 s.negative = true;
538}
539
540// Audit H6: one such pair among isolated vertices. Its cyclic core has two
541// nodes, but the bounded search with L = V does about L^2 work on it.
542Spec scc_pair_isolated_spec(const size_t n)
543{
544 Spec s;
545 s.nodes = std::min(scc_pair_isolated_factor * n, scc_pair_isolated_max);
546 scc_pair(s, 0, 1);
547 return s;
548}
549
550// Disjoint pairs and nothing else: every node is in a component, so with
551// L = V the search does about V^3 work.
552Spec scc_pairs_spec(const size_t n)
553{
554 Spec s;
555 const size_t pairs = std::max<size_t>(1, std::min(n, scc_pairs_max) / 2);
556 s.nodes = 2 * pairs;
557 for (size_t p = 0; p < pairs; ++p)
558 scc_pair(s, 2 * p, 2 * p + 1);
559 return s;
560}
561
562// A graph plus the data the harness needs to run and judge variants on it.
563struct Instance
564{
565 std::string name;
566 Spec spec;
567 bool bounded_is_cheap = false; // run the bounded variants whatever the size
568 bool long_bound = false; // run the bounded search with L = V too
569 Graph g;
570 Array<Arc *> arcs; // arcs[i] is the graph arc of spec.arcs(i)
571 Array<Array<double>> round_weights; // empty for static instances
572 size_t rounds = 1;
573
575 void apply_round(const size_t r)
576 {
577 if (round_weights.is_empty())
578 return;
579 const Array<double> & w = round_weights(r % rounds);
580 for (size_t i = 0; i < arcs.size(); ++i)
581 arcs(i)->get_info() = w(i);
582 }
583};
584
585std::unique_ptr<Instance> make_instance(std::string name, Spec spec,
586 const bool reversed = false)
587{
588 auto inst = std::make_unique<Instance>();
589 inst->name = std::move(name);
590 inst->spec = std::move(spec);
591 const Spec & s = inst->spec;
592
594 const size_t total = s.nodes + s.isolated;
595 nodes.reserve(total);
596 for (size_t i = 0; i < total; ++i)
597 nodes.append(inst->g.insert_node(static_cast<int>(i)));
598
599 const size_t m = s.arcs.size();
600 inst->arcs.reserve(m);
601 for (size_t i = 0; i < m; ++i)
602 inst->arcs.append(nullptr);
603 for (size_t k = 0; k < m; ++k)
604 {
605 const size_t i = reversed ? m - 1 - k : k;
606 const Arc_Spec & a = s.arcs(i);
607 inst->arcs(i) = inst->g.insert_arc(nodes(a.u), nodes(a.v), a.w);
608 }
609 return inst;
610}
611
612// Market with a fixed topology and `reweight_rounds` price sets.
613std::unique_ptr<Instance> make_reweighted(const size_t n, const unsigned seed)
614{
615 auto inst = make_instance("market-reweighted", market_spec(n, true, seed));
616 Spec work = inst->spec;
617 std::mt19937 rng(seed + 4);
618 for (size_t r = 0; r < reweight_rounds; ++r)
619 {
620 draw_prices(work, rng);
622 w.reserve(work.arcs.size());
623 for (size_t i = 0; i < work.arcs.size(); ++i)
624 w.append(market_weight(work, work.arcs(i)));
625 inst->round_weights.append(std::move(w));
626 }
627 inst->rounds = reweight_rounds;
628 inst->apply_round(0);
629 return inst;
630}
631
632// ---------------------------------------------------------------------------
633// Results and validation
634// ---------------------------------------------------------------------------
635
636enum class Verdict { None, Detected, Valid, Invalid };
637enum class Group { Detect, Witness, Bounded, Mean, Reference };
638
639struct Outcome
640{
641 Verdict verdict = Verdict::None;
642 size_t count = 0; // cycles reported
643 double cost = 0.0; // cost of the first (or only) cycle
644 size_t length = 0; // arcs of that cycle
645 char cert[16] = "-"; // bounded search: "exact" / "bound" / "no-cert"; Howard: "it=7" or "karp"
646 char why[128] = ""; // reason when Invalid
647 size_t allocs = 0; // operator new calls of one run
648 size_t bytes = 0;
649};
650
651const char * verdict_name(const Verdict v)
652{
653 switch (v)
654 {
655 case Verdict::None: return "none";
656 case Verdict::Detected: return "detected";
657 case Verdict::Valid: return "valid";
658 case Verdict::Invalid: return "INVALID";
659 }
660 return "?";
661}
662
663struct Limits
664{
665 size_t max_len = SIZE_MAX; // arcs per cycle
666 size_t max_count = SIZE_MAX; // cycles requested
667 bool disjoint = false; // pairwise arc-disjoint (All_Arcs)
668};
669
670void invalid(Outcome & o, const char * why)
671{
672 o.verdict = Verdict::Invalid;
673 std::snprintf(o.why, sizeof(o.why), "%s", why);
674}
675
676template <class T>
677Array<T> to_array(const DynList<T> & list)
678{
679 Array<T> ret;
680 list.for_each([&](const T & x) { ret.append(x); });
681 return ret;
682}
683
684// Checks that `nodes`/`arcs` describe a closed cycle of `g` (simple, unless
685// `simple` is false: a closed walk may repeat nodes). On success returns
686// nullptr and sets `cost` to the arc sum.
687const char * check_cycle(const Graph & g, const Array<Node *> & nodes,
688 const Array<Arc *> & arcs, long double & cost,
689 const bool simple = true)
690{
691 if (arcs.size() == 0)
692 return "empty cycle";
693 if (nodes.size() != arcs.size() + 1)
694 return "node and arc counts do not match";
695 if (nodes(0) != nodes(nodes.size() - 1))
696 return "path is not closed";
698 cost = 0;
699 for (size_t i = 0; i < arcs.size(); ++i)
700 {
701 if (g.get_src_node(arcs(i)) != nodes(i) or g.get_tgt_node(arcs(i)) != nodes(i + 1))
702 return "arc does not join consecutive nodes";
703 if (simple and seen.insert(nodes(i)) == nullptr)
704 return "node repeated: not a simple cycle";
705 cost += arcs(i)->get_info();
706 }
707 return nullptr;
708}
709
710Outcome check_result(const Graph &, const bool detected, const Limits &)
711{
712 Outcome o;
713 o.verdict = detected ? Verdict::Detected : Verdict::None;
714 return o;
715}
716
717// The snapshot is a reference measurement, not a detector: nothing to check.
718Outcome check_result(const Graph &, const Indexed &, const Limits &)
719{
720 return Outcome{};
721}
722
725long double cheapest_arcs_cost(const Graph & g, const Array<Node *> & nodes)
726{
727 long double cost = 0;
728 for (size_t i = 0; i + 1 < nodes.size(); ++i)
729 {
730 double best = std::numeric_limits<double>::infinity();
731 for (Node_Arc_Iterator<Graph> it(nodes(i)); it.has_curr(); it.next_ne())
732 if (g.get_tgt_node(it.get_curr()) == nodes(i + 1) and it.get_curr()->get_info() < best)
733 best = it.get_curr()->get_info();
734 cost += best;
735 }
736 return cost;
737}
738
739Outcome check_result(const Graph & g, const Path<Graph> & p, const Limits &)
740{
741 Outcome o;
742 if (p.is_empty())
743 return o;
744 o.count = 1;
745 const auto nodes = to_array(p.nodes());
746 const auto arcs = to_array(p.arcs());
747 long double cost = 0;
748 if (const char * why = check_cycle(g, nodes, arcs, cost))
749 {
750 invalid(o, why);
751 return o;
752 }
753 o.cost = static_cast<double>(cost);
754 o.length = arcs.size();
755 if (not (cost < 0))
756 {
757 const long double cheapest = cheapest_arcs_cost(g, nodes);
758 if (cheapest < 0)
759 {
760 std::snprintf(o.why, sizeof(o.why),
761 "witness cost is not negative: a costlier parallel arc was picked "
762 "(the cheapest ones cost %.6Lg)", cheapest);
763 o.verdict = Verdict::Invalid;
764 }
765 else
766 invalid(o, "witness cost is not negative");
767 return o;
768 }
769 o.verdict = Verdict::Valid;
770 return o;
771}
772
773Outcome check_result(const Graph & g, const std::tuple<Path<Graph>, size_t> & r,
774 const Limits & lim)
775{
776 return check_result(g, std::get<0>(r), lim);
777}
778
780template <typename Result>
781Outcome check_total_cycle(const Graph & g, const Result & r, const Limits & lim)
782{
783 Outcome o;
784 if (not r.has_cycle)
785 return o;
786 o.count = 1;
787 o.cost = r.total_cost;
788 o.length = r.length;
789 const auto nodes = to_array(r.cycle_nodes);
790 const auto arcs = to_array(r.cycle_arcs);
791 long double cost = 0;
792 if (const char * why = check_cycle(g, nodes, arcs, cost))
793 invalid(o, why);
794 else if (arcs.size() != r.length)
795 invalid(o, "length field differs from the arc count");
796 else if (arcs.size() > lim.max_len)
797 invalid(o, "cycle longer than max_length");
798 else if (std::fabs(cost - static_cast<long double>(r.total_cost)) > 1e-9L)
799 invalid(o, "total_cost differs from the arc sum");
800 else if ((cost < 0) != r.is_negative())
801 invalid(o, "is_negative() disagrees with the arc sum");
802 else
803 o.verdict = cost < 0 ? Verdict::Valid : Verdict::None;
804 return o;
805}
806
807Outcome check_result(const Graph & g, const Bounded & r, const Limits & lim)
808{
809 Outcome o = check_total_cycle(g, r, lim);
810 if (r.has_cycle)
811 // A rounded relaxed bound alone proves no optimality.
812 std::snprintf(o.cert, sizeof(o.cert), "%s",
813 r.is_exact ? "exact" : r.matches_relaxed_bound ? "bound" : "no-cert");
814 return o;
815}
816
833const char * check_short_optimum(const Graph & g, const Short_Cycle_Result<Graph, double> & r)
834{
835 long double witness = 0, witness_abs = 0;
836 for (auto it = r.cycle_arcs.get_it(); it.has_curr(); it.next_ne())
837 {
838 witness += it.get_curr()->get_info();
839 witness_abs += std::fabs(static_cast<long double>(it.get_curr()->get_info()));
840 }
841
842 // Positions of the nodes, and out- and in-adjacency in compressed rows.
844 size_t n = 0;
845 for (auto it = g.get_node_it(); it.has_curr(); it.next_ne())
846 index.insert(it.get_curr(), n++);
847 Array<size_t> out_start(n + 1, 0), in_start(n + 1, 0);
848 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
849 {
850 ++out_start(index.find(g.get_src_node(it.get_curr())) + 1);
851 ++in_start(index.find(g.get_tgt_node(it.get_curr())) + 1);
852 }
853 for (size_t u = 0; u < n; ++u)
854 {
855 out_start(u + 1) += out_start(u);
856 in_start(u + 1) += in_start(u);
857 }
858 const size_t m = out_start(n);
859 Array<size_t> out_tgt(m, 0), in_src(m, 0), out_fill(n, 0), in_fill(n, 0);
860 Array<double> out_w(m, 0.0), in_w(m, 0.0);
861 for (auto it = g.get_arc_it(); it.has_curr(); it.next_ne())
862 {
863 const size_t s = index.find(g.get_src_node(it.get_curr()));
864 const size_t d = index.find(g.get_tgt_node(it.get_curr()));
865 const double w = it.get_curr()->get_info();
866 const size_t po = out_start(s) + out_fill(s)++;
867 out_tgt(po) = d;
868 out_w(po) = w;
869 const size_t pi = in_start(d) + in_fill(d)++;
870 in_src(pi) = s;
871 in_w(pi) = w;
872 }
873
874 constexpr long double eps = std::numeric_limits<long double>::epsilon();
875 bool any = false;
876 const char * cheaper = nullptr;
877 const auto candidate = [&](const long double total, const long double abs_total)
878 {
879 any = true;
880 if (r.has_cycle and witness > total + 8 * eps * (witness_abs + abs_total))
881 cheaper = "a cheaper cycle of at most three arcs exists";
882 };
883
884 constexpr double unset = std::numeric_limits<double>::infinity();
885 Array<double> closing(n, unset); // cheapest arc x -> u, for the current u
886 for (size_t u = 0; u < n and cheaper == nullptr; ++u)
887 {
888 for (size_t p = in_start(u); p < in_start(u + 1); ++p)
889 if (in_w(p) < closing(in_src(p)))
890 closing(in_src(p)) = in_w(p);
891 if (closing(u) != unset)
892 candidate(closing(u), std::fabs(static_cast<long double>(closing(u)))); // loop
893 for (size_t p = out_start(u); p < out_start(u + 1); ++p)
894 {
895 const size_t v = out_tgt(p);
896 if (v == u)
897 continue;
898 const long double a = out_w(p);
899 if (closing(v) != unset) // u -> v -> u
900 candidate(a + closing(v), std::fabs(a) + std::fabs(static_cast<long double>(closing(v))));
901 for (size_t q = out_start(v); q < out_start(v + 1); ++q)
902 {
903 const size_t x = out_tgt(q);
904 if (x == u or x == v or closing(x) == unset)
905 continue;
906 const long double b = out_w(q); // u -> v -> x -> u
907 candidate(a + b + closing(x),
908 std::fabs(a) + std::fabs(b) + std::fabs(static_cast<long double>(closing(x))));
909 }
910 }
911 for (size_t p = in_start(u); p < in_start(u + 1); ++p)
912 closing(in_src(p)) = unset;
913 }
914
915 if (cheaper != nullptr)
916 return cheaper;
917 if (any != r.has_cycle)
918 return r.has_cycle ? "reported a cycle where none of at most three arcs exists"
919 : "missed a cycle of at most three arcs";
920 return nullptr;
921}
922
926Outcome check_result(const Graph & g, const Short_Cycle_Result<Graph, double> & r,
927 const Limits & lim)
928{
929 Outcome o = check_total_cycle(g, r, lim);
930 if (o.verdict == Verdict::Invalid)
931 return o;
932 if (const char * why = check_short_optimum(g, r))
933 invalid(o, why);
934 else if (r.has_cycle)
935 std::snprintf(o.cert, sizeof(o.cert), "exact");
936 return o;
937}
938
939// Karp's minimum mean cycle: the witness is a simple cycle (see
940// Min_Mean_Cycle.H) of consecutive arcs of the graph, whose total, length and
941// mean agree with the result.
942Outcome check_result(const Graph & g, const Min_Mean_Cycle_Result<Graph, double> & r,
943 const Limits &)
944{
945 Outcome o;
946 if (not r.has_cycle)
947 return o;
948 o.count = 1;
949 o.cost = r.cycle_total_cost;
950 o.length = r.cycle_length;
951 const auto nodes = to_array(r.cycle_nodes);
952 const auto arcs = to_array(r.cycle_arcs);
953 long double cost = 0;
954 if (const char * why = check_cycle(g, nodes, arcs, cost))
955 invalid(o, why);
956 else if (arcs.size() != r.cycle_length)
957 invalid(o, "cycle_length differs from the arc count");
958 else if (std::fabs(cost - static_cast<long double>(r.cycle_total_cost)) > 1e-9L)
959 invalid(o, "cycle_total_cost differs from the arc sum");
960 else if (std::fabs(cost / static_cast<long double>(arcs.size()) - r.minimum_mean) > 1e-9L)
961 invalid(o, "the witness mean differs from minimum_mean");
962 else
963 o.verdict = cost < 0 ? Verdict::Valid : Verdict::None;
964 return o;
965}
966
967// Howard's minimum mean cycle: the witness is a *simple* cycle whose total,
968// length and mean agree with the result, and where Karp fits in memory the mean
969// must be Karp's.
970Outcome check_result(const Graph & g, const Howard_Mean_Cycle_Result<Graph, double> & r,
971 const Limits &)
972{
973 Outcome o;
974 if (not r.has_cycle)
975 return o;
976 o.count = 1;
977 o.cost = r.cycle_total_cost;
978 o.length = r.cycle_length;
979 if (r.used_karp)
980 std::snprintf(o.cert, sizeof(o.cert), "karp");
981 else
982 std::snprintf(o.cert, sizeof(o.cert), "it=%zu", r.iterations);
983 const auto nodes = to_array(r.cycle_nodes);
984 const auto arcs = to_array(r.cycle_arcs);
985 long double cost = 0;
986 if (const char * why = check_cycle(g, nodes, arcs, cost))
987 invalid(o, why);
988 else if (arcs.size() != r.cycle_length)
989 invalid(o, "cycle_length differs from the arc count");
990 else if (std::fabs(cost - static_cast<long double>(r.cycle_total_cost)) > 1e-9L)
991 invalid(o, "cycle_total_cost differs from the arc sum");
992 else if (std::fabs(cost / static_cast<long double>(arcs.size()) - r.minimum_mean) > 1e-9L)
993 invalid(o, "the witness mean differs from minimum_mean");
994 else if (g.get_num_nodes() <= bounded_max_nodes
995 and std::fabs(karp_minimum_mean_cycle_value(g).minimum_mean - r.minimum_mean) > 1e-9L)
996 invalid(o, "the mean differs from Karp's");
997 else
998 o.verdict = cost < 0 ? Verdict::Valid : Verdict::None;
999 return o;
1000}
1001
1002Outcome check_result(const Graph &, const Min_Mean_Cycle_Value_Result & r, const Limits &)
1003{
1004 Outcome o;
1005 o.verdict = r.has_cycle and r.minimum_mean < 0 ? Verdict::Detected : Verdict::None;
1006 return o;
1007}
1008
1009Outcome check_result(const Graph & g, const Cycles & items, const Limits & lim)
1010{
1011 Outcome o;
1012 o.count = items.size();
1013 if (items.is_empty())
1014 return o;
1015 if (items.size() > lim.max_count)
1016 {
1017 invalid(o, "more cycles than requested");
1018 return o;
1019 }
1020
1022 for (auto it = items.get_it(); it.has_curr(); it.next_ne())
1023 {
1024 const auto & item = it.get_curr();
1025 const auto nodes = to_array(item.cycle.nodes());
1026 const auto arcs = to_array(item.cycle.arcs());
1027 long double cost = 0;
1028 if (const char * why = check_cycle(g, nodes, arcs, cost))
1029 {
1030 invalid(o, why);
1031 return o;
1032 }
1033 if (all.is_empty())
1034 {
1035 o.cost = item.total_cost;
1036 o.length = item.length;
1037 }
1038 if (arcs.size() != item.length)
1039 invalid(o, "length field differs from the arc count");
1040 else if (not (cost < 0))
1041 invalid(o, "cycle cost is not negative");
1042 else if (std::fabs(cost - static_cast<long double>(item.total_cost)) > 1e-9L)
1043 invalid(o, "total_cost differs from the arc sum");
1044 if (o.verdict == Verdict::Invalid)
1045 return o;
1046 all.append(arcs);
1047 }
1048
1049 if (lim.disjoint)
1050 {
1051 DynSetTree<Arc *> used;
1052 for (size_t i = 0; i < all.size(); ++i)
1053 for (size_t k = 0; k < all(i).size(); ++k)
1054 if (used.insert(all(i)(k)) == nullptr)
1055 {
1056 invalid(o, "two cycles share an arc under All_Arcs");
1057 return o;
1058 }
1059 }
1060 else
1061 for (size_t i = 0; i < all.size(); ++i)
1062 for (size_t j = i + 1; j < all.size(); ++j)
1063 {
1064 if (all(i).size() != all(j).size())
1065 continue;
1066 bool same = true;
1067 for (size_t k = 0; same and k < all(i).size(); ++k)
1068 {
1069 bool found = false;
1070 for (size_t l = 0; not found and l < all(j).size(); ++l)
1071 found = all(i)(k) == all(j)(l);
1072 same = found;
1073 }
1074 if (same)
1075 {
1076 invalid(o, "the same cycle was reported twice");
1077 return o;
1078 }
1079 }
1080
1081 o.verdict = Verdict::Valid;
1082 return o;
1083}
1084
1085long weigh(const bool b) { return b; }
1086long weigh(const Path<Graph> & p) { return p.is_empty() ? 0 : static_cast<long>(p.size()); }
1087long weigh(const std::tuple<Path<Graph>, size_t> & r)
1088{
1089 return weigh(std::get<0>(r)) + static_cast<long>(std::get<1>(r));
1090}
1091long weigh(const Bounded & r) { return static_cast<long>(r.length); }
1093long weigh(const Short_Cycle_Result<Graph, double> & r) { return static_cast<long>(r.length); }
1094long weigh(const Min_Mean_Cycle_Result<Graph, double> & r)
1095{
1096 return static_cast<long>(r.cycle_length);
1097}
1098long weigh(const Min_Mean_Cycle_Value_Result & r) { return r.has_cycle ? 1 : 0; }
1099long weigh(const Cycles & c) { return static_cast<long>(c.size()); }
1100long weigh(const Indexed & ig) { return static_cast<long>(ig.arcs.size()); }
1101
1102// ---------------------------------------------------------------------------
1103// Variants
1104// ---------------------------------------------------------------------------
1105
1106struct Variant
1107{
1108 std::string name;
1109 Group group;
1110 size_t bound; // L of the bounded search, else 0
1111 bool small_only = false; // cost grows too fast to run on huge graphs
1112 bool long_bound = false; // only on instances with `long_bound`
1113 std::function<long(Graph &)> run; // the bare call, for timing
1114 std::function<Outcome(Graph &)> inspect; // the call plus its validation
1115};
1116
1117template <class Call>
1118Variant make_variant(std::string name, const Group group, const size_t bound,
1119 const Limits lim, Call call)
1120{
1121 Variant v;
1122 v.name = std::move(name);
1123 v.group = group;
1124 v.bound = bound;
1125 v.small_only = group == Group::Bounded or group == Group::Mean;
1126 v.run = [call](Graph & g) { return weigh(call(g)); };
1127 v.inspect = [call, lim](Graph & g)
1128 {
1129 alloc_probe.calls = 0;
1130 alloc_probe.bytes = 0;
1131 alloc_probe.active = true;
1132 const auto result = call(g);
1133 alloc_probe.active = false;
1134 const size_t calls = alloc_probe.calls;
1135 const size_t bytes = alloc_probe.bytes;
1136 Outcome o = check_result(g, result, lim);
1137 o.allocs = calls;
1138 o.bytes = bytes;
1139 return o;
1140 };
1141 return v;
1142}
1143
1144DynList<Variant> make_variants()
1145{
1146 constexpr size_t K = seeded_triangles;
1148
1149 vs.append(make_variant("BF::has_negative_cycle() [classic]", Group::Detect,
1150 0, Limits{},
1151 [](Graph & g) { return Bellman_Ford<Graph>(g).has_negative_cycle(); }));
1152
1153 vs.append(make_variant("BF::test_negative_cycle() [classic]", Group::Witness,
1154 0, Limits{},
1155 [](Graph & g) { return Bellman_Ford<Graph>(g).test_negative_cycle(); }));
1156 vs.append(make_variant("BF::search_negative_cycle() [SPFA]", Group::Witness,
1157 0, Limits{},
1158 [](Graph & g) { return Bellman_Ford<Graph>(g).search_negative_cycle(); }));
1159 vs.append(make_variant("BF::search_negative_cycle(0.1, 1) [SPFA+early]", Group::Witness,
1160 0, Limits{},
1161 [](Graph & g) { return Bellman_Ford<Graph>(g).search_negative_cycle(0.1, 1); }));
1162
1163 vs.append(make_variant("find_disjoint(g, 1)", Group::Witness,
1164 0, Limits{SIZE_MAX, 1, false},
1165 [](Graph & g) { return find_disjoint_negative_cycles(g, 1); }));
1166 vs.append(make_variant("find_disjoint(g, 5, Min_Weight_Arc)", Group::Witness,
1167 0, Limits{SIZE_MAX, K, false},
1168 [](Graph & g)
1169 { return find_disjoint_negative_cycles(g, K, Exclusion::Min_Weight_Arc); }));
1170 vs.append(make_variant("find_disjoint(g, 5, All_Arcs)", Group::Witness,
1171 0, Limits{SIZE_MAX, K, true},
1172 [](Graph & g)
1173 { return find_disjoint_negative_cycles(g, K, Exclusion::All_Arcs); }));
1174
1175 for (const size_t L : {3, 6, 12})
1176 {
1177 char label[48];
1178 std::snprintf(label, sizeof(label), "most_negative_cycle_bounded(g, %zu)", L);
1179 vs.append(make_variant(label, Group::Bounded, L, Limits{L, SIZE_MAX, false},
1180 [L](Graph & g) { return most_negative_cycle_bounded(g, L); }));
1181 }
1182
1183 vs.append(make_variant("most_negative_cycle_up_to_3(g, 3)", Group::Bounded,
1184 3, Limits{3, SIZE_MAX, false},
1185 [](Graph & g) { return most_negative_cycle_up_to_3(g, 3); }));
1186
1187 // L = V, as long as any simple cycle: only where the components are small
1188 // (see "Long walks in small components" above).
1189 auto whole = make_variant("most_negative_cycle_bounded(g, V)", Group::Bounded, 0,
1190 Limits{},
1191 [](Graph & g) { return most_negative_cycle_bounded(g, g.get_num_nodes()); });
1192 whole.long_bound = true;
1193 vs.append(std::move(whole));
1194
1195 vs.append(make_variant("karp_minimum_mean_cycle_value(g)", Group::Mean,
1196 0, Limits{},
1197 [](Graph & g) { return karp_minimum_mean_cycle_value(g); }));
1198 vs.append(make_variant("karp_minimum_mean_cycle(g)", Group::Mean,
1199 0, Limits{},
1200 [](Graph & g) { return karp_minimum_mean_cycle(g); }));
1201
1202 // Howard's algorithm needs O(V + E) memory, so it runs on every size.
1203 auto howard_value = make_variant("howard_minimum_mean_cycle_value(g)", Group::Mean,
1204 0, Limits{},
1205 [](Graph & g) { return howard_minimum_mean_cycle_value(g); });
1206 howard_value.small_only = false;
1207 vs.append(std::move(howard_value));
1208 auto howard_witness = make_variant("howard_minimum_mean_cycle(g)", Group::Mean,
1209 0, Limits{},
1210 [](Graph & g) { return howard_minimum_mean_cycle(g); });
1211 howard_witness.small_only = false;
1212 vs.append(std::move(howard_witness));
1213
1214 vs.append(make_variant("snapshot only (index_graph)", Group::Reference,
1215 0, Limits{},
1216 [](Graph & g)
1217 {
1218 Dft_Dist<Graph> distance;
1220 return negative_cycles_detail::index_graph(g, distance, show, "bench");
1221 }));
1222
1223 return vs;
1224}
1225
1226enum class Judgment { Ok, Unexpected };
1227
1228// Compares an outcome with the ground truth of the instance.
1229Judgment judge(const Instance & inst, const Variant & v, const Outcome & o,
1230 const char *& reason)
1231{
1232 if (v.group == Group::Reference)
1233 return Judgment::Ok;
1234
1235 if (not inst.spec.negative)
1236 {
1237 if (o.verdict == Verdict::None)
1238 return Judgment::Ok;
1239 reason = o.verdict == Verdict::Invalid ? o.why
1240 : "reported a negative cycle where none exists";
1241 return Judgment::Unexpected;
1242 }
1243
1244 if (o.verdict == Verdict::Invalid)
1245 {
1246 reason = o.why; // an invalid witness, of Bellman_Ford or not, is an error
1247 return Judgment::Unexpected;
1248 }
1249
1250 const bool detector = v.group == Group::Detect or v.name.find("_value(") != std::string::npos;
1251 const Verdict need = detector ? Verdict::Detected : Verdict::Valid;
1252 if (o.verdict == need)
1253 return Judgment::Ok;
1254 reason = "missed the negative cycle planted in the graph";
1255 return Judgment::Unexpected;
1256}
1257
1269size_t validator_self_test()
1270{
1271 size_t misjudged = 0;
1272
1273 const double gap = std::max(64.0 * static_cast<double>(std::numeric_limits<long double>::epsilon()),
1274 std::ldexp(1.0, -52));
1275 Graph g;
1276 Node * u = g.insert_node(0);
1277 Node * v = g.insert_node(1);
1278 Arc * cheap = g.insert_arc(u, u, -1.0);
1279 Arc * costly = g.insert_arc(v, v, -1.0 + gap);
1281 r.has_cycle = true;
1282 r.length = 1;
1283 r.cycle_arcs.append(cheap);
1284 r.total_cost = -1.0;
1285 if (check_short_optimum(g, r) != nullptr)
1286 ++misjudged; // the true optimum must pass
1287 r.cycle_arcs.empty();
1288 r.cycle_arcs.append(costly);
1289 r.total_cost = -1.0 + gap;
1290 if (check_short_optimum(g, r) == nullptr)
1291 ++misjudged;
1292
1293 Instance inst; // judge() reads only the ground truth
1294 inst.spec.negative = true;
1295 Variant bf;
1296 bf.group = Group::Witness;
1297 bf.bound = 0;
1298 Outcome o;
1299 invalid(o, "self-test");
1300 const char * reason = "";
1301 if (judge(inst, bf, o, reason) != Judgment::Unexpected)
1302 ++misjudged; // an invalid witness is an error
1303 return misjudged;
1304}
1305
1306// ---------------------------------------------------------------------------
1307// Timing
1308// ---------------------------------------------------------------------------
1309
1310struct Timing
1311{
1312 double median = 0.0;
1313 double p90 = 0.0;
1314 double best = 0.0;
1315};
1316
1317// Runs `run()` under the timing protocol; `prepare(i)` runs before each run,
1318// outside the timed region. `run` returns a value that is fed to `keep`.
1319template <class Prepare, class Run>
1320Timing time_runs(const size_t samples, Prepare prepare, Run run)
1321{
1322 // Untimed warmup: at least `warmup_min_runs`, then until `warmup_ms` have
1323 // elapsed (at most `warmup_max_runs`), so that short variants also reach a
1324 // steady state (caches, branch predictors, clock frequency).
1325 double warmed = 0.0;
1326 for (size_t w = 0; w < warmup_min_runs or (warmed < warmup_ms and w < warmup_max_runs); ++w)
1327 {
1328 prepare(w);
1329 const auto t0 = std::chrono::steady_clock::now();
1330 keep(run());
1331 warmed += std::chrono::duration<double, std::milli>(
1332 std::chrono::steady_clock::now() - t0).count();
1333 }
1334
1335 std::vector<double> ms;
1336 ms.reserve(samples);
1337 for (size_t i = 0; i < samples; ++i)
1338 {
1339 prepare(i);
1340 const auto t0 = std::chrono::steady_clock::now();
1341 const long r = run();
1342 const auto t1 = std::chrono::steady_clock::now();
1343 keep(r);
1344 ms.push_back(std::chrono::duration<double, std::milli>(t1 - t0).count());
1345 }
1346 std::sort(ms.begin(), ms.end());
1347
1348 Timing t;
1349 t.median = ms[ms.size() / 2];
1350 t.best = ms.front();
1351 const size_t rank = static_cast<size_t>(std::ceil(0.9 * static_cast<double>(ms.size())));
1352 t.p90 = ms[std::max<size_t>(rank, 1) - 1];
1353 return t;
1354}
1355
1356Timing time_variant(Instance & inst, const Variant & v, const size_t samples)
1357{
1358 return time_runs(samples,
1359 [&inst](const size_t i) { inst.apply_round(i); },
1360 [&inst, &v] { return v.run(inst.g); });
1361}
1362
1363// ---------------------------------------------------------------------------
1364// Reporting
1365// ---------------------------------------------------------------------------
1366
1367struct Tally
1368{
1369 size_t unexpected = 0;
1370};
1371
1372const char * group_title(const Group g)
1373{
1374 switch (g)
1375 {
1376 case Group::Detect: return "detection only";
1377 case Group::Witness: return "with a witness cycle";
1378 case Group::Bounded: return "bounded search";
1379 case Group::Mean: return "minimum mean cycle (Karp: O(V^2) memory; Howard: O(V + E))";
1380 case Group::Reference: return "reference";
1381 }
1382 return "";
1383}
1384
1385void print_header()
1386{
1387 std::printf(" %-47s %9s %9s %9s %-8s %5s %12s %4s %-7s %7s %9s\n",
1388 "variant", "median ms", "p90 ms", "best ms", "verdict", "found",
1389 "cost", "len", "cert", "allocs", "KiB");
1390}
1391
1392void print_row(const Variant & v, const Outcome & o, const Timing * t, const Judgment j)
1393{
1394 char times[96];
1395 if (t != nullptr)
1396 std::snprintf(times, sizeof(times), "%9.3f %9.3f %9.3f", t->median, t->p90, t->best);
1397 else
1398 std::snprintf(times, sizeof(times), "%9s %9s %9s", "-", "-", "-");
1399
1400 char cost[24] = "-";
1401 if (o.count > 0)
1402 std::snprintf(cost, sizeof(cost), "%+.6g", o.cost);
1403 char len[16] = "-";
1404 if (o.count > 0)
1405 std::snprintf(len, sizeof(len), "%zu", o.length);
1406 // Detectors report no cycle and the snapshot is not a detector at all.
1407 const bool counts_cycles = v.group == Group::Witness or v.group == Group::Bounded
1408 or (v.group == Group::Mean and v.name.find("_value(") == std::string::npos);
1409 char found[16] = "-";
1410 if (counts_cycles)
1411 std::snprintf(found, sizeof(found), "%zu", o.count);
1412
1413 std::printf(" %-47s %s %-8s %5s %12s %4s %-7s %7zu %9.1f%s\n", v.name.c_str(), times,
1414 v.group == Group::Reference ? "-" : verdict_name(o.verdict), found, cost, len,
1415 o.cert, o.allocs,
1416 static_cast<double>(o.bytes) / 1024.0,
1417 j == Judgment::Unexpected ? " <- UNEXPECTED" : "");
1418}
1419
1420// ---------------------------------------------------------------------------
1421// Reusable topology: what a snapshot kept between calls would save
1422// ---------------------------------------------------------------------------
1423
1424// Re-reads the weight of every arc of `ig` through `distance`. A reusable
1425// topology would do this for each new weight set instead of building a new
1426// snapshot. Returns the sum of the weights so the loop cannot be optimized
1427// away.
1428double refresh_weights(Indexed & ig, Dft_Dist<Graph> & distance)
1429{
1430 double total = 0.0;
1431 for (size_t i = 0; i < ig.arcs.size(); ++i)
1432 {
1433 auto & rec = ig.arcs(i);
1434 rec.weight = distance(rec.arc);
1435 negative_cycles_detail::check_finite(rec.weight, "bench: non-finite arc weight");
1436 total += rec.weight;
1437 }
1438 return total;
1439}
1440
1441// A snapshot refreshed after every weight change must hold exactly what a new
1442// snapshot holds (same arcs, same order, same weights); otherwise the refresh
1443// loop above would not be measuring the work a reusable topology has to do.
1444bool refreshed_snapshot_matches(Instance & inst)
1445{
1446 Dft_Dist<Graph> distance;
1448 inst.apply_round(0);
1449 Indexed kept = negative_cycles_detail::index_graph(inst.g, distance, show, "bench");
1450 for (size_t r = 0; r < inst.rounds; ++r)
1451 {
1452 inst.apply_round(r);
1453 keep(std::signbit(refresh_weights(kept, distance)) ? 1 : 2);
1454 const Indexed fresh = negative_cycles_detail::index_graph(inst.g, distance, show, "bench");
1455 if (fresh.nodes.size() != kept.nodes.size() or fresh.arcs.size() != kept.arcs.size())
1456 return false;
1457 for (size_t i = 0; i < fresh.arcs.size(); ++i)
1458 if (fresh.arcs(i).arc != kept.arcs(i).arc
1459 or fresh.arcs(i).src != kept.arcs(i).src
1460 or fresh.arcs(i).tgt != kept.arcs(i).tgt
1461 or fresh.arcs(i).weight != kept.arcs(i).weight)
1462 return false;
1463 }
1464 return true;
1465}
1466
1467void print_timing_row(const char * name, const Timing & t)
1468{
1469 std::printf(" %-47s %9.3f %9.3f %9.3f\n", name, t.median, t.p90, t.best);
1470}
1471
1472// Times `find_disjoint(g, 1)`, its snapshot and the weight refresh of a kept
1473// snapshot, and prints the estimate (call - snapshot + refresh). Nothing here
1474// is a library API: the enumeration is not callable on an existing snapshot.
1475void report_reusable_topology(Instance & inst, const size_t samples, Tally & tally)
1476{
1477 if (not refreshed_snapshot_matches(inst))
1478 {
1479 ++tally.unexpected;
1480 std::printf(" -- reusable topology\n UNEXPECTED: a refreshed snapshot differs from a "
1481 "new one\n");
1482 return;
1483 }
1484 if (samples == 0)
1485 return;
1486
1487 Dft_Dist<Graph> distance;
1489 inst.apply_round(0);
1490 Indexed kept = negative_cycles_detail::index_graph(inst.g, distance, show, "bench");
1491
1492 const auto prepare = [&inst](const size_t i) { inst.apply_round(i); };
1493 const Timing call = time_runs(samples, prepare,
1494 [&inst] { return weigh(find_disjoint_negative_cycles(inst.g, 1)); });
1495 const Timing snapshot = time_runs(samples, prepare,
1496 [&inst, &distance, &show]
1497 { return weigh(negative_cycles_detail::index_graph(inst.g, distance, show, "bench")); });
1498 const Timing refresh = time_runs(samples, prepare,
1499 [&kept, &distance]
1500 { return std::signbit(refresh_weights(kept, distance)) ? 1L : 2L; });
1501
1502 std::printf(" -- reusable topology (estimate: call - snapshot + refresh; not a library API)\n");
1503 print_timing_row("find_disjoint(g, 1), as today", call);
1504 print_timing_row(" of which the snapshot (index_graph)", snapshot);
1505 print_timing_row(" weight refresh of a kept snapshot", refresh);
1506 const double estimate = call.median - snapshot.median + refresh.median;
1507 if (call.median > snapshot.median and estimate > 0.0)
1508 std::printf(" %-47s %9.3f %9s %9s est. x%.1f\n",
1509 "find_disjoint(g, 1) with a kept snapshot", estimate, "-", "-",
1510 call.median / estimate);
1511 else
1512 std::printf(" %-47s %9s (the call is not slower than its snapshot: no estimate)\n",
1513 "find_disjoint(g, 1) with a kept snapshot", "n/a");
1514}
1515
1516// Validates every variant on `inst` (all its weight sets) and, if `samples`
1517// is positive, times it. Updates `tally`.
1518void report_instance(Instance & inst, const DynList<Variant> & variants,
1519 const size_t samples, Tally & tally)
1520{
1521 std::printf("\n== %s: %zu vertices, %zu arcs, %s ==\n", inst.name.c_str(),
1522 inst.g.get_num_nodes(), inst.g.get_num_arcs(),
1523 inst.spec.negative ? "negative cycle planted" : "no negative cycle");
1524 print_header();
1525
1526 Group last = Group::Reference;
1527 bool first = true;
1528 bool skipped_bounded = false;
1529 for (auto it = variants.get_it(); it.has_curr(); it.next_ne())
1530 {
1531 const Variant & v = it.get_curr();
1532 if (v.long_bound and not inst.long_bound)
1533 continue;
1534 if (v.small_only and inst.g.get_num_nodes() > bounded_max_nodes
1535 and not (v.group == Group::Bounded and inst.bounded_is_cheap))
1536 {
1537 skipped_bounded = true;
1538 continue;
1539 }
1540 if (first or v.group != last)
1541 std::printf(" -- %s\n", group_title(v.group));
1542 first = false;
1543 last = v.group;
1544
1545 Outcome shown;
1546 Judgment worst = Judgment::Ok;
1547 std::string reason; // a copy: `why` may point into a dead Outcome
1548 for (size_t r = 0; r < inst.rounds; ++r)
1549 {
1550 inst.apply_round(r);
1551 const Outcome o = v.inspect(inst.g);
1552 const char * why = "";
1553 const Judgment j = judge(inst, v, o, why);
1554 if (r == 0 or (j > worst))
1555 {
1556 shown = o;
1557 if (j > worst)
1558 {
1559 worst = j;
1560 reason = why;
1561 }
1562 }
1563 }
1564
1565 if (worst == Judgment::Unexpected)
1566 ++tally.unexpected;
1567
1568 if (samples > 0)
1569 {
1570 const Timing t = time_variant(inst, v, samples);
1571 print_row(v, shown, &t, worst);
1572 }
1573 else
1574 print_row(v, shown, nullptr, worst);
1575 if (worst != Judgment::Ok)
1576 std::printf(" UNEXPECTED: %s\n", reason.c_str());
1577 }
1578 if (skipped_bounded)
1579 std::printf(" (%s variants skipped: more than %zu vertices)\n",
1580 inst.bounded_is_cheap ? "Karp" : "bounded and Karp", bounded_max_nodes);
1581 report_reusable_topology(inst, samples, tally);
1582}
1583
1584void print_environment(const Options & opt)
1585{
1586 std::printf("Negative cycle benchmark\n");
1587 std::printf(" compiler : %s\n", Aleph::CA::Bench::compiler_string().c_str());
1588 std::printf(" cpu : %s\n", Aleph::CA::Bench::cpu_string().c_str());
1589#ifdef BENCH_BUILD_TYPE
1590 std::printf(" build : %s\n", BENCH_BUILD_TYPE);
1591#endif
1592#ifdef BENCH_CXX_FLAGS
1593 std::printf(" flags : %s\n", BENCH_CXX_FLAGS);
1594#endif
1595#if defined(__OPTIMIZE__)
1596 std::printf(" optimized: yes\n");
1597#else
1598 std::printf(" optimized: NO (timings are not meaningful)\n");
1599#endif
1600#if defined(NDEBUG)
1601 std::printf(" asserts : off\n");
1602#else
1603 std::printf(" asserts : ON (timings are not meaningful)\n");
1604#endif
1605 std::printf(" assets=%zu seed=%u samples=%zu%s\n", opt.assets, opt.seed, opt.samples,
1606 opt.check_only ? " (--check-only: nothing is timed)" : "");
1607 if (not opt.check_only)
1608 {
1609 std::printf(" protocol : untimed warmup (>= %zu runs, until %.0f ms, <= %zu runs), then "
1610 "%zu timed runs; median, p90 (nearest rank), best\n",
1611 warmup_min_runs, warmup_ms, warmup_max_runs, opt.samples);
1612 if (opt.samples < min_regression_samples)
1613 std::printf(" note : fewer than %zu samples: exploratory only\n",
1614 min_regression_samples);
1615 }
1616}
1617
1618
1619// The graph families of the requested instances, in report order.
1620struct Family
1621{
1622 const char * name;
1623 std::unique_ptr<Instance> (*build)(const Options &);
1624};
1625
1626const Family families[] =
1627 {
1628 {"market-arbitrage",
1629 [](const Options & o) { return make_instance("market-arbitrage", market_spec(o.assets, true, o.seed)); }},
1630 {"market-clean",
1631 [](const Options & o) { return make_instance("market-clean", market_spec(o.assets, false, o.seed)); }},
1632 {"market-arbitrage-reversed",
1633 [](const Options & o)
1634 { return make_instance("market-arbitrage-reversed", market_spec(o.assets, true, o.seed), true); }},
1635 {"market-isolated-nodes",
1636 [](const Options & o)
1637 {
1638 Spec s = market_spec(o.assets, true, o.seed);
1639 s.isolated = o.assets;
1640 return make_instance("market-isolated-nodes", std::move(s));
1641 }},
1642 {"dag", [](const Options & o) { return make_instance("dag", dag_spec(o.assets, o.seed)); }},
1643 {"components",
1644 [](const Options & o)
1645 {
1646 auto inst = make_instance("components", components_spec(o.assets, o.seed));
1647 inst->long_bound = inst->g.get_num_nodes() <= long_bound_max_nodes;
1648 return inst;
1649 }},
1650 {"dense",
1651 [](const Options & o)
1652 { return make_instance("dense", dense_spec(std::min(o.assets, dense_max_nodes), o.seed)); }},
1653 {"market-reweighted", [](const Options & o) { return make_reweighted(o.assets, o.seed); }},
1654 {"loop-isolated",
1655 [](const Options & o)
1656 {
1657 auto inst = make_instance("loop-isolated", loop_isolated_spec(o.assets));
1658 inst->bounded_is_cheap = true;
1659 return inst;
1660 }},
1661 {"scc-pair-isolated",
1662 [](const Options & o)
1663 {
1664 auto inst = make_instance("scc-pair-isolated", scc_pair_isolated_spec(o.assets));
1665 inst->bounded_is_cheap = true;
1666 inst->long_bound = true;
1667 return inst;
1668 }},
1669 {"scc-pairs",
1670 [](const Options & o)
1671 {
1672 auto inst = make_instance("scc-pairs", scc_pairs_spec(o.assets));
1673 inst->long_bound = true;
1674 return inst;
1675 }},
1676 };
1677
1678} // namespace
1679
1680int main(const int argc, char * argv[])
1681{
1682 Options opt;
1683 if (not parse_args(argc, argv, opt))
1684 {
1685 usage(stderr);
1686 return 2;
1687 }
1688
1689 if (not opt.only.empty())
1690 {
1691 bool any = false;
1692 for (const Family & f : families)
1693 any = any or std::strstr(f.name, opt.only.c_str()) != nullptr;
1694 if (not any)
1695 {
1696 std::fprintf(stderr, "no graph family matches --only=%s\n", opt.only.c_str());
1697 return 2;
1698 }
1699 }
1700
1701 print_environment(opt);
1702 const DynList<Variant> variants = make_variants();
1703 Tally tally;
1704
1705 const size_t misjudged = validator_self_test();
1706 std::printf("\nValidator self-test: %s\n", misjudged == 0 ? "ok" : "FAILED");
1707 if (misjudged > 0)
1708 {
1709 std::fprintf(stderr, "bench_negative_cycles: the validators misjudged %zu known result(s)\n",
1710 misjudged);
1711 tally.unexpected += misjudged;
1712 }
1713
1714 // Multigraph regressions of the old Bellman-Ford extractor: validation only.
1715 std::printf("\n#### regression inputs (n = 19; validation only)");
1716 for (const unsigned seed : {19u, 42u})
1717 {
1718 auto inst = make_instance("market-arbitrage n=19 seed=" + std::to_string(seed),
1719 market_spec(19, true, seed));
1720 report_instance(*inst, variants, 0, tally);
1721 }
1722
1723 std::printf("\n#### requested instances");
1724 for (const Family & f : families)
1725 {
1726 if (not opt.only.empty() and std::strstr(f.name, opt.only.c_str()) == nullptr)
1727 continue;
1728 auto inst = f.build(opt);
1729 report_instance(*inst, variants, opt.check_only ? 0 : opt.samples, tally);
1730 }
1731
1732 std::printf("\nSummary: %zu unexpected result(s)\n", tally.unexpected);
1733 if (tally.unexpected > 0)
1734 {
1735 std::fprintf(stderr, "bench_negative_cycles: %zu unexpected result(s)\n", tally.unexpected);
1736 return 1;
1737 }
1738 return sink == -1 ? 1 : 0;
1739}
Bellman-Ford algorithm for single-source shortest paths.
Minimum mean cycle by Howard's policy iteration.
Minimum mean cycle in directed graphs (Karp algorithm).
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
int main()
#define BENCH_NOINLINE
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Bellman-Ford algorithm for shortest paths with negative weights.
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.
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
T & append(const T &item)
Definition htlist.H:1362
size_t size() const noexcept
Return the number of items of the list, in constant time.
Definition htlist.H:1264
Generic key-value map implemented on top of a binary search tree.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
Data & find(const Key &key)
Find the value associated with key.
Dynamic set backed by balanced binary search trees with automatic memory management.
Key * insert(const Key &key)
Inserts a key into the dynamic set.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Node Node
The graph type.
Definition tpl_graph.H:443
Arc Arc
The node class type.
Definition tpl_graph.H:444
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Path on a graph.
Definition tpl_graph.H:3832
DynList< Arc * > arcs() const
Return a list with the arcs of a path (order, according to the path)
Definition tpl_graph.H:4576
size_t size() const noexcept
Return the path length in nodes.
Definition tpl_graph.H:3987
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
DynList< Node * > nodes() const
Return a list with the nodes of path (order according to the path)
Definition tpl_graph.H:4565
Wrapper for the error value used to initialize an expected.
void for_each(Operation &operation) const
Traverse all the container and performs an operation on each element.
Definition ah-dry.H:1475
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
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
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
static mt19937 rng
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
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...
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...
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).
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.
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.
std::string cpu_string()
Read the CPU model name advertised by the host.
std::string compiler_string()
Describe the compiler that produced the running binary.
Indexed_Graph< GT, typename Distance::Distance_Type > index_graph(const GT &g, Distance &distance, SA &sa, const char *fn)
Snapshot the graph: index its nodes and the arcs accepted by sa, reading each weight once.
void check_finite(const Cost_Type &value, const char *context)
Main namespace for Aleph-w library functions.
Array< typename C::Item_Type > to_array(const C &c)
Convenience wrapper identical to to_Array (copy contents).
Definition ah-convert.H:181
@ Run
Execute the lowered HIR module with Interpreter_Runtime.
@ Call
dst <- callee(args...)
@ Invalid
Uninitialized register/slot or explicit invalid placeholder.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
const T * median(const T &a, const T &b, const T &c, const Compare &cmp=Compare())
Return a pointer to the median value among three elements.
Definition ahUtils.H:85
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
@ Ok
The result is in value.
and
Check uniqueness with explicit hash + equality functors.
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
Snapshot snapshot(const Aleph::Adaptive_Huffman_Encoder &encoder)
Reconstruct and validate the tree using public encoder operations.
constexpr bool shown(unsigned long hidden, int i) noexcept
Whether the arc number i is shown by the mask hidden.
Spec reversed(const Spec &s)
The spec with each arc reversed; the arcs keep their numbers.
void print_header()
Result of most_negative_cycle_bounded().
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Result of howard_minimum_mean_cycle().
Result of minimum mean cycle computation.
Lightweight minimum-mean-cycle value result.
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Represents a missing value.
Exact optimum returned by most_negative_cycle_up_to_3().
Positional snapshot of a graph: nodes by position and the arcs accepted by the arc filter,...
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
void usage()
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Dynamic array container with automatic resizing.
Alias for htlist.H (DynList implementation).
Dynamic key-value map based on balanced binary search trees.
Dynamic set implementations based on balanced binary search trees.
Generic graph and digraph implementations.
DynList< int > l