145#include <system_error>
159#include "../ca/bench_support.H"
161using namespace Aleph;
176Alloc_Probe alloc_probe;
183#define BENCH_NOINLINE __attribute__((noinline))
185#define BENCH_NOINLINE
190 if (alloc_probe.active)
193 alloc_probe.bytes +=
size;
195 if (
void * p = std::malloc(
size == 0 ? 1 :
size))
197 std::fputs(
"bench_negative_cycles: out of memory\n", stderr);
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); }
218volatile long sink = 0;
221void keep(
const long v) { sink = sink + v; }
223constexpr size_t num_hubs = 4;
224constexpr double fee = 0.001;
225constexpr size_t seeded_triangles = 5;
226constexpr double triangle_profit = 0.012;
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;
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;
236constexpr size_t loop_isolated_max = 20000;
237constexpr size_t scc_pair_isolated_factor = 10;
238constexpr size_t scc_pair_isolated_max = 4000;
239constexpr size_t scc_pairs_max = 300;
240constexpr size_t long_bound_max_nodes = 400;
241constexpr size_t warmup_min_runs = 2;
242constexpr size_t warmup_max_runs = 200;
243constexpr double warmup_ms = 30.0;
251bool parse_uint(
const char * text,
const unsigned long long lo,
252 const unsigned long long hi,
unsigned long long &
out)
254 if (text ==
nullptr or *text ==
'\0')
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)
270 bool check_only =
false;
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);
287bool parse_args(
const int argc,
char * argv[], Options & opt)
292 unsigned long long lo;
293 unsigned long long hi;
295 const Positional positional[] =
296 {{
"num_assets", min_assets, max_assets},
297 {
"samples", 1, max_samples},
298 {
"seed", 0, 4294967295ULL}};
301 for (
int i = 1; i < argc; ++i)
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)
308 else if (std::strcmp(arg,
"--help") == 0 or std::strcmp(arg,
"-h") == 0)
313 else if (std::strncmp(arg,
"--", 2) == 0)
315 std::fprintf(stderr,
"unknown option '%s'\n", arg);
320 std::fprintf(stderr,
"unexpected argument '%s'\n", arg);
325 const Positional & p = positional[
next];
326 unsigned long long value = 0;
327 if (not parse_uint(arg, p.lo, p.hi,
value))
330 "%s must be a decimal integer in [%llu, %llu], got '%s'\n",
331 p.name, p.lo, p.hi, arg);
335 opt.assets =
static_cast<size_t>(
value);
337 opt.samples =
static_cast<size_t>(
value);
339 opt.seed =
static_cast<unsigned>(
value);
365 bool negative =
false;
368double fee_term() {
return -std::log(1.0 - fee); }
370double market_weight(
const Spec & s,
const Arc_Spec & a)
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;
376void draw_prices(Spec & s, std::mt19937 &
rng)
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);
383void both_ways(Spec & s,
const size_t u,
const size_t v)
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});
389void plant_triangles(Spec & s)
391 for (
size_t t = 0; t < seeded_triangles; ++t)
393 const size_t a = num_hubs + 3 * t;
394 const size_t b = a + 1;
395 const size_t c = a + 2;
398 for (
const auto & uv : {std::pair<size_t, size_t>{a, b}, {b, c}, {c, a}})
400 Arc_Spec arc{uv.first, uv.second, 0,
true};
401 arc.w = market_weight(s, arc);
406 s.negative = s.seeded > 0;
411Spec market_spec(
const size_t n,
const bool arbitrage,
const unsigned seed)
414 std::uniform_real_distribution<double> log_price(-3.0, 3.0);
418 for (
size_t i = 0; i < n; ++i)
419 s.lp.append(log_price(
rng));
421 for (
size_t h = 0;
h < num_hubs; ++
h)
422 for (
size_t v =
h + 1; v < n; ++v)
425 std::uniform_int_distribution<size_t> pick(num_hubs, n - 1);
426 for (
size_t k = 0;
k < n; ++
k)
428 const size_t u = pick(
rng);
429 const size_t v = pick(
rng);
440Spec dense_spec(
const size_t n,
const unsigned seed)
445 for (
size_t i = 0; i < n; ++i)
448 for (
size_t u = 0; u < n; ++u)
449 for (
size_t v = 0; v < n; ++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}})
454 Arc_Spec arc{uv.first, uv.second, 0,
true};
455 arc.w = market_weight(s, arc);
464Spec dag_spec(
const size_t n,
const unsigned seed)
467 std::uniform_real_distribution<double> weight(-1.0, 1.0);
470 for (
size_t i = 0; i + 1 < n; ++i)
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});
482Spec components_spec(
const size_t n,
const unsigned seed)
485 std::uniform_real_distribution<double> weight(0.5, 1.5);
486 const size_t comps = std::max<size_t>(1, n / component_size);
489 s.nodes = comps * component_size;
490 for (
size_t c = 0; c < comps; ++c)
492 const size_t base = c * component_size;
494 for (
size_t i = 0; i < component_size; ++i)
497 s.arcs.append(Arc_Spec{base + i, base + (i + 1) % component_size, ring(i),
false});
499 std::uniform_int_distribution<size_t> pick(0, component_size - 1);
500 for (
size_t k = 0;
k < component_size; ++
k)
502 const size_t u = pick(
rng);
503 const size_t v = pick(
rng);
505 s.arcs.append(Arc_Spec{base + u, base + v, weight(
rng),
false});
509 s.arcs.append(Arc_Spec{base + 2, base, -(ring(0) + ring(1)) - 0.01,
false});
513 s.negative = s.seeded > 0;
519Spec loop_isolated_spec(
const size_t n)
522 s.nodes = std::min(loop_isolated_factor * n, loop_isolated_max);
523 s.arcs.append(Arc_Spec{0, 0, -1.0,
false});
531void scc_pair(Spec & s,
const size_t a,
const size_t b)
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});
542Spec scc_pair_isolated_spec(
const size_t n)
545 s.nodes = std::min(scc_pair_isolated_factor * n, scc_pair_isolated_max);
552Spec scc_pairs_spec(
const size_t n)
555 const size_t pairs = std::max<size_t>(1, std::min(n, scc_pairs_max) / 2);
557 for (
size_t p = 0; p < pairs; ++p)
558 scc_pair(s, 2 * p, 2 * p + 1);
567 bool bounded_is_cheap =
false;
568 bool long_bound =
false;
575 void apply_round(
const size_t r)
580 for (
size_t i = 0; i <
arcs.size(); ++i)
581 arcs(i)->get_info() =
w(i);
585std::unique_ptr<Instance> make_instance(std::string name, Spec spec,
586 const bool reversed =
false)
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;
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)));
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)
606 const Arc_Spec & a = s.arcs(i);
607 inst->arcs(i) = inst->g.insert_arc(
nodes(a.u),
nodes(a.v), a.w);
613std::unique_ptr<Instance> make_reweighted(
const size_t n,
const unsigned seed)
615 auto inst = make_instance(
"market-reweighted", market_spec(n,
true,
seed));
616 Spec work = inst->spec;
618 for (
size_t r = 0;
r < reweight_rounds; ++
r)
620 draw_prices(work,
rng);
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));
627 inst->rounds = reweight_rounds;
628 inst->apply_round(0);
636enum class Verdict {
None, Detected, Valid,
Invalid };
637enum class Group { Detect, Witness, Bounded, Mean, Reference };
641 Verdict verdict = Verdict::None;
651const char * verdict_name(
const Verdict v)
655 case Verdict::None:
return "none";
656 case Verdict::Detected:
return "detected";
657 case Verdict::Valid:
return "valid";
658 case Verdict::Invalid:
return "INVALID";
665 size_t max_len = SIZE_MAX;
666 size_t max_count = SIZE_MAX;
667 bool disjoint =
false;
670void invalid(Outcome & o,
const char * why)
672 o.verdict = Verdict::Invalid;
673 std::snprintf(o.why,
sizeof(o.why),
"%s", why);
689 const bool simple =
true)
691 if (
arcs.size() == 0)
692 return "empty cycle";
694 return "node and arc counts do not match";
696 return "path is not closed";
699 for (
size_t i = 0; i <
arcs.size(); ++i)
702 return "arc does not join consecutive nodes";
704 return "node repeated: not a simple cycle";
705 cost +=
arcs(i)->get_info();
710Outcome check_result(
const Graph &,
const bool detected,
const Limits &)
713 o.verdict = detected ? Verdict::Detected : Verdict::None;
718Outcome check_result(
const Graph &,
const Indexed &,
const Limits &)
727 long double cost = 0;
728 for (
size_t i = 0; i + 1 <
nodes.size(); ++i)
730 double best = std::numeric_limits<double>::infinity();
733 best = it.get_curr()->get_info();
747 long double cost = 0;
748 if (
const char * why = check_cycle(g,
nodes,
arcs, cost))
753 o.cost =
static_cast<double>(cost);
754 o.length =
arcs.size();
757 const long double cheapest = cheapest_arcs_cost(g,
nodes);
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;
766 invalid(o,
"witness cost is not negative");
769 o.verdict = Verdict::Valid;
776 return check_result(g, std::get<0>(
r), lim);
780template <
typename Result>
781Outcome check_total_cycle(
const Graph & g,
const Result &
r,
const Limits & lim)
787 o.cost =
r.total_cost;
791 long double cost = 0;
792 if (
const char * why = check_cycle(g,
nodes,
arcs, cost))
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");
803 o.verdict = cost < 0 ? Verdict::Valid : Verdict::None;
807Outcome check_result(
const Graph & g,
const Bounded &
r,
const Limits & lim)
809 Outcome o = check_total_cycle(g,
r, lim);
812 std::snprintf(o.cert,
sizeof(o.cert),
"%s",
813 r.is_exact ?
"exact" :
r.matches_relaxed_bound ?
"bound" :
"no-cert");
835 long double witness = 0, witness_abs = 0;
836 for (
auto it =
r.cycle_arcs.get_it(); it.has_curr(); it.next_ne())
838 witness += it.get_curr()->get_info();
839 witness_abs += std::fabs(
static_cast<long double>(it.get_curr()->get_info()));
845 for (
auto it = g.
get_node_it(); it.has_curr(); it.next_ne())
846 index.
insert(it.get_curr(), n++);
848 for (
auto it = g.
get_arc_it(); it.has_curr(); it.next_ne())
853 for (
size_t u = 0; u < n; ++u)
855 out_start(u + 1) += out_start(u);
856 in_start(u + 1) += in_start(u);
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);
861 for (
auto it = g.
get_arc_it(); it.has_curr(); it.next_ne())
865 const double w = it.get_curr()->get_info();
866 const size_t po = out_start(s) + out_fill(s)++;
869 const size_t pi = in_start(d) + in_fill(d)++;
874 constexpr long double eps = std::numeric_limits<long double>::epsilon();
876 const char * cheaper =
nullptr;
877 const auto candidate = [&](
const long double total,
const long double abs_total)
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";
884 constexpr double unset = std::numeric_limits<double>::infinity();
886 for (
size_t u = 0; u < n
and cheaper ==
nullptr; ++u)
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))));
893 for (
size_t p = out_start(u); p < out_start(u + 1); ++p)
895 const size_t v = out_tgt(p);
898 const long double a = out_w(p);
899 if (closing(v) != unset)
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)
903 const size_t x = out_tgt(q);
904 if (x == u or x == v or closing(x) == unset)
906 const long double b = out_w(q);
907 candidate(a + b + closing(x),
908 std::fabs(a) + std::fabs(b) + std::fabs(
static_cast<long double>(closing(x))));
911 for (
size_t p = in_start(u); p < in_start(u + 1); ++p)
912 closing(in_src(p)) = unset;
915 if (cheaper !=
nullptr)
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";
929 Outcome o = check_total_cycle(g,
r, lim);
930 if (o.verdict == Verdict::Invalid)
932 if (
const char * why = check_short_optimum(g,
r))
934 else if (
r.has_cycle)
935 std::snprintf(o.cert,
sizeof(o.cert),
"exact");
949 o.cost =
r.cycle_total_cost;
950 o.length =
r.cycle_length;
953 long double cost = 0;
954 if (
const char * why = check_cycle(g,
nodes,
arcs, cost))
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");
963 o.verdict = cost < 0 ? Verdict::Valid : Verdict::None;
977 o.cost =
r.cycle_total_cost;
978 o.length =
r.cycle_length;
980 std::snprintf(o.cert,
sizeof(o.cert),
"karp");
982 std::snprintf(o.cert,
sizeof(o.cert),
"it=%zu",
r.iterations);
985 long double cost = 0;
986 if (
const char * why = check_cycle(g,
nodes,
arcs, cost))
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");
996 invalid(o,
"the mean differs from Karp's");
998 o.verdict = cost < 0 ? Verdict::Valid : Verdict::None;
1005 o.verdict =
r.has_cycle
and r.minimum_mean < 0 ? Verdict::Detected : Verdict::None;
1009Outcome check_result(
const Graph & g,
const Cycles & items,
const Limits & lim)
1012 o.count = items.size();
1013 if (items.is_empty())
1015 if (items.size() > lim.max_count)
1017 invalid(o,
"more cycles than requested");
1022 for (
auto it = items.get_it(); it.has_curr(); it.next_ne())
1024 const auto & item = it.get_curr();
1027 long double cost = 0;
1028 if (
const char * why = check_cycle(g,
nodes,
arcs, cost))
1035 o.cost = item.total_cost;
1036 o.length = item.length;
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)
1052 for (
size_t i = 0; i <
all.size(); ++i)
1053 for (
size_t k = 0;
k <
all(i).size(); ++
k)
1056 invalid(o,
"two cycles share an arc under All_Arcs");
1061 for (
size_t i = 0; i <
all.size(); ++i)
1062 for (
size_t j = i + 1; j <
all.size(); ++j)
1067 for (
size_t k = 0; same
and k <
all(i).size(); ++
k)
1076 invalid(o,
"the same cycle was reported twice");
1081 o.verdict = Verdict::Valid;
1085long weigh(
const bool b) {
return b; }
1089 return weigh(std::get<0>(
r)) +
static_cast<long>(std::get<1>(
r));
1091long weigh(
const Bounded &
r) {
return static_cast<long>(
r.length); }
1096 return static_cast<long>(
r.cycle_length);
1099long weigh(
const Cycles & c) {
return static_cast<long>(c.size()); }
1100long weigh(
const Indexed & ig) {
return static_cast<long>(ig.arcs.size()); }
1111 bool small_only =
false;
1112 bool long_bound =
false;
1113 std::function<long(
Graph &)> run;
1114 std::function<Outcome(
Graph &)> inspect;
1117template <
class Call>
1118Variant make_variant(std::string name,
const Group group,
const size_t bound,
1119 const Limits lim,
Call call)
1122 v.name = std::move(name);
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)
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);
1146 constexpr size_t K = seeded_triangles;
1149 vs.
append(make_variant(
"BF::has_negative_cycle() [classic]", Group::Detect,
1153 vs.
append(make_variant(
"BF::test_negative_cycle() [classic]", Group::Witness,
1156 vs.
append(make_variant(
"BF::search_negative_cycle() [SPFA]", Group::Witness,
1159 vs.
append(make_variant(
"BF::search_negative_cycle(0.1, 1) [SPFA+early]", Group::Witness,
1163 vs.
append(make_variant(
"find_disjoint(g, 1)", Group::Witness,
1164 0, Limits{SIZE_MAX, 1,
false},
1166 vs.
append(make_variant(
"find_disjoint(g, 5, Min_Weight_Arc)", Group::Witness,
1167 0, Limits{SIZE_MAX, K,
false},
1170 vs.
append(make_variant(
"find_disjoint(g, 5, All_Arcs)", Group::Witness,
1171 0, Limits{SIZE_MAX, K,
true},
1175 for (
const size_t L : {3, 6, 12})
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},
1183 vs.
append(make_variant(
"most_negative_cycle_up_to_3(g, 3)", Group::Bounded,
1184 3, Limits{3, SIZE_MAX,
false},
1189 auto whole = make_variant(
"most_negative_cycle_bounded(g, V)", Group::Bounded, 0,
1192 whole.long_bound =
true;
1193 vs.
append(std::move(whole));
1195 vs.
append(make_variant(
"karp_minimum_mean_cycle_value(g)", Group::Mean,
1198 vs.
append(make_variant(
"karp_minimum_mean_cycle(g)", Group::Mean,
1203 auto howard_value = make_variant(
"howard_minimum_mean_cycle_value(g)", Group::Mean,
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,
1211 howard_witness.small_only =
false;
1212 vs.
append(std::move(howard_witness));
1214 vs.
append(make_variant(
"snapshot only (index_graph)", Group::Reference,
1226enum class Judgment {
Ok, Unexpected };
1229Judgment judge(
const Instance & inst,
const Variant & v,
const Outcome & o,
1230 const char *& reason)
1232 if (v.group == Group::Reference)
1233 return Judgment::Ok;
1235 if (not inst.spec.negative)
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;
1244 if (o.verdict == Verdict::Invalid)
1247 return Judgment::Unexpected;
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;
1269size_t validator_self_test()
1271 size_t misjudged = 0;
1273 const double gap = std::max(64.0 *
static_cast<double>(std::numeric_limits<long double>::epsilon()),
1274 std::ldexp(1.0, -52));
1283 r.cycle_arcs.append(cheap);
1284 r.total_cost = -1.0;
1285 if (check_short_optimum(g,
r) !=
nullptr)
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)
1294 inst.spec.negative =
true;
1296 bf.group = Group::Witness;
1299 invalid(o,
"self-test");
1300 const char * reason =
"";
1301 if (judge(inst, bf, o, reason) != Judgment::Unexpected)
1319template <
class Prepare,
class Run>
1320Timing time_runs(
const size_t samples, Prepare prepare,
Run run)
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)
1329 const auto t0 = std::chrono::steady_clock::now();
1331 warmed += std::chrono::duration<double, std::milli>(
1332 std::chrono::steady_clock::now() - t0).count();
1335 std::vector<double> ms;
1336 ms.reserve(samples);
1337 for (
size_t i = 0; i < samples; ++i)
1340 const auto t0 = std::chrono::steady_clock::now();
1341 const long r = run();
1342 const auto t1 = std::chrono::steady_clock::now();
1344 ms.push_back(std::chrono::duration<double, std::milli>(t1 - t0).
count());
1346 std::sort(ms.begin(), ms.end());
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];
1356Timing time_variant(Instance & inst,
const Variant & v,
const size_t samples)
1358 return time_runs(samples,
1359 [&inst](
const size_t i) { inst.apply_round(i); },
1360 [&inst, &v] {
return v.run(inst.g); });
1372const char * group_title(
const Group g)
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";
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");
1392void print_row(
const Variant & v,
const Outcome & o,
const Timing * t,
const Judgment j)
1396 std::snprintf(times,
sizeof(times),
"%9.3f %9.3f %9.3f", t->median, t->p90, t->best);
1398 std::snprintf(times,
sizeof(times),
"%9s %9s %9s",
"-",
"-",
"-");
1400 char cost[24] =
"-";
1402 std::snprintf(cost,
sizeof(cost),
"%+.6g", o.cost);
1405 std::snprintf(len,
sizeof(len),
"%zu", o.length);
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] =
"-";
1411 std::snprintf(found,
sizeof(found),
"%zu", o.count);
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,
1416 static_cast<double>(o.bytes) / 1024.0,
1417 j == Judgment::Unexpected ?
" <- UNEXPECTED" :
"");
1431 for (
size_t i = 0; i < ig.arcs.size(); ++i)
1433 auto & rec = ig.arcs(i);
1434 rec.weight = distance(rec.arc);
1436 total += rec.weight;
1444bool refreshed_snapshot_matches(Instance & inst)
1448 inst.apply_round(0);
1450 for (
size_t r = 0;
r < inst.rounds; ++
r)
1452 inst.apply_round(
r);
1453 keep(std::signbit(refresh_weights(kept, distance)) ? 1 : 2);
1455 if (fresh.nodes.size() != kept.nodes.size() or fresh.arcs.size() != kept.arcs.size())
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)
1467void print_timing_row(
const char * name,
const Timing & t)
1469 std::printf(
" %-47s %9.3f %9.3f %9.3f\n", name, t.median, t.p90, t.best);
1475void report_reusable_topology(Instance & inst,
const size_t samples, Tally & tally)
1477 if (not refreshed_snapshot_matches(inst))
1480 std::printf(
" -- reusable topology\n UNEXPECTED: a refreshed snapshot differs from a "
1489 inst.apply_round(0);
1492 const auto prepare = [&inst](
const size_t i) { inst.apply_round(i); };
1493 const Timing call = time_runs(samples, prepare,
1495 const Timing
snapshot = time_runs(samples, prepare,
1496 [&inst, &distance, &show]
1498 const Timing refresh = time_runs(samples, prepare,
1500 {
return std::signbit(refresh_weights(kept, distance)) ? 1L : 2L; });
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);
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");
1519 const size_t samples, Tally & tally)
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");
1526 Group last = Group::Reference;
1528 bool skipped_bounded =
false;
1529 for (
auto it = variants.
get_it(); it.has_curr(); it.next_ne())
1531 const Variant & v = it.get_curr();
1532 if (v.long_bound
and not inst.long_bound)
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))
1537 skipped_bounded =
true;
1540 if (first or v.group != last)
1541 std::printf(
" -- %s\n", group_title(v.group));
1546 Judgment worst = Judgment::Ok;
1548 for (
size_t r = 0;
r < inst.rounds; ++
r)
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))
1565 if (worst == Judgment::Unexpected)
1570 const Timing t = time_variant(inst, v, samples);
1571 print_row(v, shown, &t, worst);
1574 print_row(v, shown,
nullptr, worst);
1575 if (worst != Judgment::Ok)
1576 std::printf(
" UNEXPECTED: %s\n", reason.c_str());
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);
1584void print_environment(
const Options & opt)
1586 std::printf(
"Negative cycle benchmark\n");
1589#ifdef BENCH_BUILD_TYPE
1590 std::printf(
" build : %s\n", BENCH_BUILD_TYPE);
1592#ifdef BENCH_CXX_FLAGS
1593 std::printf(
" flags : %s\n", BENCH_CXX_FLAGS);
1595#if defined(__OPTIMIZE__)
1596 std::printf(
" optimized: yes\n");
1598 std::printf(
" optimized: NO (timings are not meaningful)\n");
1601 std::printf(
" asserts : off\n");
1603 std::printf(
" asserts : ON (timings are not meaningful)\n");
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)
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);
1623 std::unique_ptr<Instance> (*build)(
const Options &);
1626const Family families[] =
1628 {
"market-arbitrage",
1629 [](
const Options & o) {
return make_instance(
"market-arbitrage", market_spec(o.assets,
true, o.seed)); }},
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)
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));
1642 {
"dag", [](
const Options & o) {
return make_instance(
"dag", dag_spec(o.assets, o.seed)); }},
1644 [](
const Options & o)
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;
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); }},
1655 [](
const Options & o)
1657 auto inst = make_instance(
"loop-isolated", loop_isolated_spec(o.assets));
1658 inst->bounded_is_cheap =
true;
1661 {
"scc-pair-isolated",
1662 [](
const Options & o)
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;
1670 [](
const Options & o)
1672 auto inst = make_instance(
"scc-pairs", scc_pairs_spec(o.assets));
1673 inst->long_bound =
true;
1680int main(
const int argc,
char * argv[])
1683 if (not parse_args(argc, argv, opt))
1689 if (not opt.only.empty())
1692 for (
const Family & f : families)
1693 any = any or std::strstr(f.name, opt.only.c_str()) !=
nullptr;
1696 std::fprintf(stderr,
"no graph family matches --only=%s\n", opt.only.c_str());
1701 print_environment(opt);
1705 const size_t misjudged = validator_self_test();
1706 std::printf(
"\nValidator self-test: %s\n", misjudged == 0 ?
"ok" :
"FAILED");
1709 std::fprintf(stderr,
"bench_negative_cycles: the validators misjudged %zu known result(s)\n",
1711 tally.unexpected += misjudged;
1715 std::printf(
"\n#### regression inputs (n = 19; validation only)");
1716 for (
const unsigned seed : {19u, 42u})
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);
1723 std::printf(
"\n#### requested instances");
1724 for (
const Family & f : families)
1726 if (not opt.only.empty()
and std::strstr(f.name, opt.only.c_str()) ==
nullptr)
1728 auto inst = f.build(opt);
1729 report_instance(*inst, variants, opt.check_only ? 0 : opt.samples, tally);
1732 std::printf(
"\nSummary: %zu unexpected result(s)\n", tally.unexpected);
1733 if (tally.unexpected > 0)
1735 std::fprintf(stderr,
"bench_negative_cycles: %zu unexpected result(s)\n", tally.unexpected);
1738 return sink == -1 ? 1 : 0;
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
size_t size_t int32_t value
size_t size_t int32_t * out
Simple dynamic array with automatic resizing and functional operations.
constexpr bool is_empty() const noexcept
Checks if the container is empty.
T & append(const T &data)
Append a copy of data
void reserve(size_t cap)
Reserves cap cells into the array.
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.
Doubly-linked list (defined in tpl_dynList.H).
T & append(const T &item)
size_t size() const noexcept
Return the number of items of the list, in constant time.
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.
Arc Arc
The node class type.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
DynList< Arc * > arcs() const
Return a list with the arcs of a path (order, according to the path)
size_t size() const noexcept
Return the path length in nodes.
bool is_empty() const noexcept
Return true if the path is empty.
DynList< Node * > nodes() const
Return a list with the nodes of path (order according to the path)
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.
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
auto get_arc_it() const noexcept
Obtains an iterator to the arc of graph.
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
auto get_node_it() const noexcept
Obtains an iterator to the nodes of graph.
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
DynArray< Graph::Node * > nodes
DynArray< Graph::Arc * > arcs
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).
@ 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.
std::decay_t< typename HeadC::Item_Type > T
@ Ok
The result is in value.
and
Check uniqueness with explicit hash + equality functors.
void next()
Advance all underlying iterators (bounds-checked).
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
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.
Result of most_negative_cycle_bounded().
Default filter for filtered iterators on arcs.
Arc of graph implemented with double-linked adjacency lists.
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.
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)
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.