Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
negative_cycles_numeric_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
45# include <gtest/gtest.h>
46# include <gmp.h>
47
48# include <algorithm>
49# include <cmath>
50# include <functional>
51# include <limits>
52# include <random>
53# include <set>
54# include <tuple>
55# include <vector>
56
58# include <Negative_Cycles.H>
59# include <tpl_graph.H>
60
61using namespace Aleph;
62
63namespace
64{
65 // ------------------------------------------------------------------------
66 // Exact rationals over the GMP C interface.
67 // ------------------------------------------------------------------------
68 class Rational
69 {
70 mpq_t q_;
71
72 public:
73 Rational() { mpq_init(q_); }
74 Rational(const Rational & other) { mpq_init(q_); mpq_set(q_, other.q_); }
75 Rational & operator=(const Rational & other) { mpq_set(q_, other.q_); return *this; }
76 ~Rational() { mpq_clear(q_); }
77
78 // The exact value of a finite floating-point number: its integer
79 // mantissa, built 32 bits at a time, times a power of two.
80 template <typename T>
81 static Rational of(const T x)
82 {
83 Rational r;
84 if (x == T(0))
85 return r;
86 int e = 0;
87 const T f = std::frexp(std::fabs(x), &e);
88 constexpr int digits = std::numeric_limits<T>::digits;
89 T m = std::ldexp(f, digits);
90 std::vector<unsigned long> chunks;
91 const T base = T(4294967296.0);
92 while (m != T(0))
93 {
94 const T low = std::fmod(m, base);
95 chunks.push_back(static_cast<unsigned long>(low));
96 m = (m - low) / base;
97 }
98 mpz_t z;
99 mpz_init(z);
100 for (size_t i = chunks.size(); i-- > 0; )
101 {
102 mpz_mul_2exp(z, z, 32);
103 mpz_add_ui(z, z, chunks[i]);
104 }
105 if (x < T(0))
106 mpz_neg(z, z);
107 mpq_set_z(r.q_, z);
108 mpz_clear(z);
109 const int exponent = e - digits;
110 if (exponent >= 0)
111 mpq_mul_2exp(r.q_, r.q_, static_cast<mp_bitcnt_t>(exponent));
112 else
113 mpq_div_2exp(r.q_, r.q_, static_cast<mp_bitcnt_t>(-exponent));
114 return r;
115 }
116
117 Rational & operator+=(const Rational & other) { mpq_add(q_, q_, other.q_); return *this; }
118
119 friend Rational operator-(const Rational & a, const Rational & b)
120 {
121 Rational r;
122 mpq_sub(r.q_, a.q_, b.q_);
123 return r;
124 }
125
126 Rational times(const size_t factor) const
127 {
128 Rational f;
129 mpq_set_ui(f.q_, static_cast<unsigned long>(factor), 1);
130 Rational r;
131 mpq_mul(r.q_, q_, f.q_);
132 return r;
133 }
134
135 friend int compare(const Rational & a, const Rational & b) { return mpq_cmp(a.q_, b.q_); }
136 int sign() const { return mpq_sgn(q_); }
137 };
138
139 // a / la < b / lb, with positive lengths.
140 bool mean_less(const Rational & a, const size_t la, const Rational & b, const size_t lb)
141 {
142 return compare(a.times(lb), b.times(la)) < 0;
143 }
144
145 bool mean_equal(const Rational & a, const size_t la, const Rational & b, const size_t lb)
146 {
147 return compare(a.times(lb), b.times(la)) == 0;
148 }
149
150 // True if `computed` is within one unit in the last place of `exact`, with
151 // the same sign (zero only for zero).
152 template <typename T>
153 bool within_one_ulp(const T computed, const Rational & exact)
154 {
155 if (computed == T(0))
156 return exact.sign() == 0;
157 if ((computed < T(0) ? -1 : 1) != exact.sign())
158 return false;
159 const T up = std::nextafter(computed, std::numeric_limits<T>::infinity());
160 const T down = std::nextafter(computed, -std::numeric_limits<T>::infinity());
161 return compare(Rational::of(down), exact) <= 0 and compare(exact, Rational::of(up)) <= 0;
162 }
163
164 // ------------------------------------------------------------------------
165 // Instances.
166 // ------------------------------------------------------------------------
167 template <typename T>
168 struct Instance
169 {
170 size_t n = 0;
171 std::vector<std::tuple<size_t, size_t, T>> edges;
172 std::vector<bool> hidden; // aligned with edges
173 };
174
175 enum class Family { Moderate, Ties, Subnormal, Three_Scales, Market };
176
177 template <typename T>
178 T draw_weight(const Family family, std::mt19937_64 & rng)
179 {
180 const auto small = [&rng](const int range) { return static_cast<int>(rng() % (2 * range + 1)) - range; };
181 switch (family)
182 {
183 case Family::Moderate:
184 return std::ldexp(static_cast<T>(small(50)), small(8));
185 case Family::Ties:
186 return static_cast<T>(small(3));
187 case Family::Subnormal:
188 return static_cast<T>(small(50)) * std::numeric_limits<T>::denorm_min()
189 * static_cast<T>(1 << (rng() % 8));
190 case Family::Three_Scales:
191 {
192 // Far enough apart that a plain sum loses the smaller scales.
193 constexpr int gap = std::numeric_limits<T>::digits + 6;
194 const int scale = static_cast<int>(rng() % 3) - 1; // -1, 0, 1
195 return std::ldexp(static_cast<T>(small(7)), scale * gap);
196 }
197 case Family::Market:
198 {
199 // -log of a rate between assets of random log-prices, with a fee.
200 std::uniform_real_distribution<double> lp(-3.0, 3.0);
201 return static_cast<T>(lp(rng) - lp(rng) - std::log(1.0 - 0.001));
202 }
203 }
204 return T(0);
205 }
206
207 template <typename T>
208 Instance<T> make_instance(const Family family, std::mt19937_64 & rng)
209 {
210 Instance<T> inst;
211 inst.n = 1 + rng() % 6;
212 const size_t m = rng() % (inst.n * inst.n + 3);
213 const bool split = inst.n >= 4 and rng() % 3 == 0; // two blocks joined one way only
214 const bool filter = rng() % 3 == 0;
215 for (size_t i = 0; i < m; ++i)
216 {
217 size_t u = rng() % inst.n;
218 size_t v = rng() % inst.n;
219 if (split and (u < inst.n / 2) != (v < inst.n / 2) and u > v)
220 std::swap(u, v); // only from the first block to the second
221 inst.edges.emplace_back(u, v, draw_weight<T>(family, rng));
222 inst.hidden.push_back(filter and rng() % 4 == 0);
223 }
224 if (family == Family::Three_Scales and inst.n >= 4 and rng() % 2 == 0)
225 {
226 // A ring whose exact total is zero, big, unit, -big, -unit, whose plain
227 // sum loses the unit and comes out as -unit.
228 constexpr int gap = std::numeric_limits<T>::digits + 6;
229 const T big = std::ldexp(T(1), gap);
230 const T unit = T(1 + rng() % 5);
231 inst.edges.emplace_back(0, 1, big);
232 inst.edges.emplace_back(1, 2, unit);
233 inst.edges.emplace_back(2, 3, -big);
234 inst.edges.emplace_back(3, 0, -unit);
235 for (int k = 0; k < 4; ++k)
236 inst.hidden.push_back(false);
237 }
238 return inst;
239 }
240
241 template <typename T>
243
244 template <typename T>
245 struct Built
246 {
247 Graph_T<T> g;
248 std::vector<typename Graph_T<T>::Node *> nodes;
249 std::vector<typename Graph_T<T>::Arc *> arcs;
250 std::set<typename Graph_T<T>::Arc *> hidden;
251 };
252
253 // Nodes are inserted in the order `node_order`, arcs in `arc_order`, and
254 // every weight is multiplied by 2^scale (exactly, for the instances used).
255 template <typename T>
256 void build(const Instance<T> & inst, Built<T> & b, const std::vector<size_t> & node_order,
257 const std::vector<size_t> & arc_order, const int scale = 0)
258 {
259 b.nodes.assign(inst.n, nullptr);
260 for (const size_t i : node_order)
261 b.nodes[i] = b.g.insert_node(static_cast<int>(i));
262 b.arcs.assign(inst.edges.size(), nullptr);
263 for (const size_t k : arc_order)
264 {
265 const auto & [u, v, w] = inst.edges[k];
266 b.arcs[k] = b.g.insert_arc(b.nodes[u], b.nodes[v], std::ldexp(w, scale));
267 if (inst.hidden[k])
268 b.hidden.insert(b.arcs[k]);
269 }
270 }
271
272 template <typename T>
273 void build(const Instance<T> & inst, Built<T> & b)
274 {
275 std::vector<size_t> nodes(inst.n);
276 std::vector<size_t> arcs(inst.edges.size());
277 for (size_t i = 0; i < nodes.size(); ++i)
278 nodes[i] = i;
279 for (size_t i = 0; i < arcs.size(); ++i)
280 arcs[i] = i;
281 build(inst, b, nodes, arcs);
282 }
283
284 template <typename T>
285 struct Hide_Set
286 {
287 const std::set<typename Graph_T<T>::Arc *> * hidden = nullptr;
288
289 bool operator()(typename Graph_T<T>::Arc * arc) const
290 {
291 return hidden == nullptr or hidden->count(arc) == 0;
292 }
293 };
294
295 // ------------------------------------------------------------------------
296 // Exhaustive oracle over the simple cycles of the visible arcs.
297 // ------------------------------------------------------------------------
298 struct Oracle
299 {
300 bool any_cycle = false;
301 bool any_bounded = false; // a cycle of at most `bound` arcs
302 Rational best_total; // minimum total over cycles of at most `bound` arcs
303 size_t best_total_length = 0; // shortest among exact total-cost minimizers
304 Rational best_mean_total; // the minimum mean is best_mean_total / best_mean_length
305 size_t best_mean_length = 1;
306 };
307
308 template <typename T>
309 Oracle oracle(const Instance<T> & inst, const size_t bound)
310 {
311 Oracle o;
312 std::vector<bool> on_path(inst.n, false);
313 std::vector<Rational> weights;
314 for (const auto & e : inst.edges)
315 weights.push_back(Rational::of(std::get<2>(e)));
316
317 std::function<void(size_t, size_t, const Rational &, size_t)> dfs =
318 [&](const size_t start, const size_t u, const Rational & total, const size_t length)
319 {
320 for (size_t k = 0; k < inst.edges.size(); ++k)
321 {
322 const auto & [a, b, w] = inst.edges[k];
323 if (a != u or inst.hidden[k])
324 continue;
325 Rational t = total;
326 t += weights[k];
327 if (b == start)
328 {
329 const size_t len = length + 1;
330 if (not o.any_cycle or mean_less(t, len, o.best_mean_total, o.best_mean_length))
331 {
332 o.best_mean_total = t;
333 o.best_mean_length = len;
334 }
335 o.any_cycle = true;
336 if (len <= bound and (not o.any_bounded or compare(t, o.best_total) < 0
337 or (compare(t, o.best_total) == 0 and len < o.best_total_length)))
338 {
339 o.best_total = t;
340 o.best_total_length = len;
341 o.any_bounded = true;
342 }
343 continue;
344 }
345 if (b < start or on_path[b])
346 continue;
347 on_path[b] = true;
348 dfs(start, b, t, length + 1);
349 on_path[b] = false;
350 }
351 };
352 for (size_t s = 0; s < inst.n; ++s)
353 {
354 on_path[s] = true;
355 dfs(s, s, Rational(), 0);
356 on_path[s] = false;
357 }
358 return o;
359 }
360
361 // The exact total of a witness given as a list of arcs, which must be
362 // consecutive, visible, simple and closed.
363 template <typename T>
364 bool exact_witness(const Built<T> & b, const DynList<typename Graph_T<T>::Arc *> & arcs,
365 Rational & total, size_t & length)
366 {
367 std::set<typename Graph_T<T>::Node *> seen;
368 typename Graph_T<T>::Node * first = nullptr;
369 typename Graph_T<T>::Node * current = nullptr;
370 length = 0;
371 total = Rational();
372 for (auto it = arcs.get_it(); it.has_curr(); it.next_ne())
373 {
374 auto * arc = it.get_curr();
375 if (b.hidden.count(arc) != 0)
376 return false;
377 auto * src = b.g.get_src_node(arc);
378 if (first == nullptr)
379 first = current = src;
380 if (src != current or not seen.insert(src).second)
381 return false;
382 current = b.g.get_tgt_node(arc);
383 total += Rational::of(arc->get_info());
384 ++length;
385 }
386 return length > 0 and current == first;
387 }
388
389 // ------------------------------------------------------------------------
390 // The checks, for one instance.
391 // ------------------------------------------------------------------------
393 template <typename T>
394 void check_short(const Instance<T> & inst, const Built<T> & b, const size_t bound)
395 {
396 using G = Graph_T<T>;
397 const Oracle o = oracle(inst, bound);
398 const auto r = most_negative_cycle_up_to_3<G, Dft_Dist<G>, Hide_Set<T>>(
399 b.g, bound, Dft_Dist<G>(), Hide_Set<T>{&b.hidden});
400 ASSERT_EQ(r.has_cycle, o.any_bounded);
401 if (not r.has_cycle)
402 return;
403
404 Rational total;
405 size_t length = 0;
406 ASSERT_TRUE(exact_witness(b, r.cycle_arcs, total, length));
407 ASSERT_EQ(length, r.length);
408 ASSERT_EQ(length, o.best_total_length);
409 ASSERT_EQ(compare(total, o.best_total), 0);
410 ASSERT_TRUE(within_one_ulp(r.total_cost, total));
411 ASSERT_EQ(r.is_negative(), total.sign() < 0);
412 }
413
414 template <typename T>
415 void check_bounded(const Instance<T> & inst, const Built<T> & b, const size_t bound,
416 const char * family, const size_t trial)
417 {
418 using G = Graph_T<T>;
419 const Oracle o = oracle(inst, bound);
420 const auto r = most_negative_cycle_bounded<G, Dft_Dist<G>, Hide_Set<T>>(
421 b.g, bound, Dft_Dist<G>(), Hide_Set<T>{&b.hidden});
422 ASSERT_EQ(r.has_cycle, o.any_bounded) << family << " trial=" << trial << " L=" << bound;
423 if (not r.has_cycle)
424 return;
425
426 Rational total;
427 size_t length = 0;
428 ASSERT_TRUE(exact_witness(b, r.cycle_arcs, total, length)) << family << " trial=" << trial;
429 ASSERT_EQ(length, r.length) << family << " trial=" << trial;
430 ASSERT_LE(length, bound) << family << " trial=" << trial;
431 ASSERT_TRUE(within_one_ulp(r.total_cost, total)) << family << " trial=" << trial;
432 ASSERT_EQ(r.is_negative(), total.sign() < 0) << family << " trial=" << trial;
433
434 // The gap is rigorous: the optimum is no cheaper than total - gap.
435 ASSERT_GE(r.optimality_gap, T(0)) << family << " trial=" << trial;
436 ASSERT_LE(compare(total - o.best_total, Rational::of(r.optimality_gap)), 0)
437 << family << " trial=" << trial << " L=" << bound;
438 ASSERT_EQ(r.is_exact, r.optimality_gap == T(0)) << family << " trial=" << trial;
439 if (r.is_exact)
440 ASSERT_EQ(compare(total, o.best_total), 0) << family << " trial=" << trial;
441 }
442
443 template <typename T>
444 void check_howard(const Instance<T> & inst, const Built<T> & b, const char * family,
445 const size_t trial)
446 {
447 using G = Graph_T<T>;
448 const Oracle o = oracle(inst, inst.n);
449 const auto h = howard_minimum_mean_cycle<G, Dft_Dist<G>, Hide_Set<T>>(
450 b.g, Dft_Dist<G>(), Hide_Set<T>{&b.hidden});
451 ASSERT_EQ(h.has_cycle, o.any_cycle) << family << " trial=" << trial;
452 if (not h.has_cycle or h.used_karp)
453 return;
454
455 Rational total;
456 size_t length = 0;
457 ASSERT_TRUE(exact_witness(b, h.cycle_arcs, total, length)) << family << " trial=" << trial;
458 ASSERT_EQ(length, h.cycle_length) << family << " trial=" << trial;
459 ASSERT_TRUE(within_one_ulp(h.cycle_total_cost, total)) << family << " trial=" << trial;
460 if (h.numeric_quality == Cycle_Numeric_Quality::Exact)
461 ASSERT_TRUE(mean_equal(total, length, o.best_mean_total, o.best_mean_length))
462 << family << " trial=" << trial;
463 }
464
465 template <typename T>
466 void check_enumeration(const Instance<T> & inst, const Built<T> & b, const char * family,
467 const size_t trial)
468 {
469 using G = Graph_T<T>;
470 const Oracle o = oracle(inst, inst.n);
471 const auto cycles = find_disjoint_negative_cycles<G, Dft_Dist<G>, Hide_Set<T>>(
472 b.g, 3, Negative_Cycle_Exclusion::All_Arcs, Dft_Dist<G>(), Hide_Set<T>{&b.hidden});
473 std::set<typename G::Arc *> used;
474 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
475 {
476 const auto & item = it.get_curr();
477 const auto arcs = item.cycle.arcs(); // a list by value: keep it alive while iterating
478 Rational total;
479 size_t length = 0;
480 ASSERT_TRUE(exact_witness(b, arcs, total, length)) << family << " trial=" << trial;
481 ASSERT_EQ(length, item.length) << family << " trial=" << trial;
482 ASSERT_LT(total.sign(), 0) << family << " trial=" << trial; // exactly negative
483 ASSERT_TRUE(within_one_ulp(item.total_cost, total)) << family << " trial=" << trial;
484 for (auto ai = arcs.get_it(); ai.has_curr(); ai.next_ne())
485 ASSERT_TRUE(used.insert(ai.get_curr()).second) << family << " trial=" << trial;
486 }
487 // A cycle of negative exact mean is a negative cycle: when the oracle
488 // says there is none, nothing is reported.
489 if (not o.any_cycle or o.best_mean_total.sign() >= 0)
490 ASSERT_TRUE(cycles.is_empty()) << family << " trial=" << trial;
491 }
492
493 const std::pair<Family, const char *> families[] = {
494 {Family::Moderate, "moderate"},
495 {Family::Ties, "ties"},
496 {Family::Subnormal, "subnormal"},
497 {Family::Three_Scales, "three-scales"},
498 {Family::Market, "market"},
499 };
500
501 template <typename T>
502 void run_differential(const unsigned long long seed, const size_t trials)
503 {
504 std::mt19937_64 rng(seed);
505 for (const auto & [family, name] : families)
506 for (size_t trial = 0; trial < trials; ++trial)
507 {
508 const Instance<T> inst = make_instance<T>(family, rng);
509 Built<T> b;
510 build(inst, b);
511 for (const size_t bound : {size_t(1), size_t(2), size_t(3), inst.n})
512 check_bounded(inst, b, bound, name, trial);
513 check_howard(inst, b, name, trial);
514 check_enumeration(inst, b, name, trial);
515 if (::testing::Test::HasFatalFailure())
516 return;
517 }
518 }
519
521 template <typename T>
522 void run_short_differential(const unsigned long long seed)
523 {
524 std::mt19937_64 rng(seed);
525 for (const auto & [family, name] : families)
526 for (size_t trial = 0; trial < 200; ++trial)
527 {
528 SCOPED_TRACE(::testing::Message() << name << " trial=" << trial);
529 const Instance<T> inst = make_instance<T>(family, rng);
530 Built<T> b;
531 build(inst, b);
532 for (size_t bound = 1; bound <= 3; ++bound)
533 {
534 SCOPED_TRACE(::testing::Message() << "L=" << bound);
535 check_short(inst, b, bound);
536 if (::testing::Test::HasFatalFailure())
537 return;
538 }
539 }
540 }
541} // namespace
542
543
544// ---------------------------------------------------------------------------
545// Differential checks against the exact oracle.
546// ---------------------------------------------------------------------------
547
548TEST(NegativeCyclesNumericTest, DoubleWeightsAgreeWithTheExactOracle)
549{
550 run_differential<double>(0x5EED0001ULL, 400);
551}
552
553
554TEST(NegativeCyclesNumericTest, FloatWeightsAgreeWithTheExactOracle)
555{
556 run_differential<float>(0x5EED0002ULL, 300);
557}
558
559
560TEST(NegativeCyclesNumericTest, LongDoubleWeightsAgreeWithTheExactOracle)
561{
562 run_differential<long double>(0x5EED0003ULL, 300);
563}
564
565
566TEST(NegativeCyclesNumericTest, ShortDoubleCyclesAgreeWithTheExactOracle)
567{
568 run_short_differential<double>(0xD40001ULL);
569}
570
571
572TEST(NegativeCyclesNumericTest, ShortFloatCyclesAgreeWithTheExactOracle)
573{
574 run_short_differential<float>(0xD40002ULL);
575}
576
577
578TEST(NegativeCyclesNumericTest, ShortLongDoubleCyclesAgreeWithTheExactOracle)
579{
580 run_short_differential<long double>(0xD40003ULL);
581}
582
583
584TEST(NegativeCyclesNumericTest, ShortOptimaSurvivePermutationAndExactScaling)
585{
586 std::mt19937_64 rng(0xD45CA1E);
587 for (const auto family : {Family::Moderate, Family::Ties, Family::Three_Scales, Family::Market})
588 for (size_t trial = 0; trial < 200; ++trial)
589 {
590 SCOPED_TRACE(::testing::Message() << "family=" << int(family) << " trial=" << trial);
591 const Instance<double> inst = make_instance<double>(family, rng);
592 std::vector<size_t> nodes(inst.n), arcs(inst.edges.size());
593 for (size_t i = 0; i < nodes.size(); ++i)
594 nodes[i] = i;
595 for (size_t i = 0; i < arcs.size(); ++i)
596 arcs[i] = i;
597 for (const int scale : {-7, 0, 9})
598 {
599 std::shuffle(nodes.begin(), nodes.end(), rng);
600 std::shuffle(arcs.begin(), arcs.end(), rng);
601 auto scaled = inst;
602 for (auto & edge : scaled.edges)
603 std::get<2>(edge) = std::ldexp(std::get<2>(edge), scale);
604 Built<double> b;
605 build(scaled, b, nodes, arcs);
606 for (size_t bound = 1; bound <= 3; ++bound)
607 {
608 SCOPED_TRACE(::testing::Message() << "scale=" << scale << " L=" << bound);
609 check_short(scaled, b, bound);
610 if (::testing::Test::HasFatalFailure())
611 return;
612 }
613 }
614 }
615}
616
617
618// ---------------------------------------------------------------------------
619// Invariance (stage B6 of auditoria-profunda-arbitraje-2026-10-02.md).
620// ---------------------------------------------------------------------------
621
622// Multiplying every weight by a power of two is exact (no overflow and no
623// subnormal results for these families), and rounding commutes with it, so
624// the bounded search must take the same decisions: the same cycle, with its
625// cost and gap scaled exactly.
626TEST(NegativeCyclesNumericTest, BoundedSearchIsInvariantUnderScalingByPowersOfTwo)
627{
628 std::mt19937_64 rng(0x5CA1E);
629 for (const auto family : {Family::Moderate, Family::Ties, Family::Three_Scales, Family::Market})
630 for (size_t trial = 0; trial < 300; ++trial)
631 {
632 const Instance<double> inst = make_instance<double>(family, rng);
633 std::vector<size_t> nodes(inst.n);
634 std::vector<size_t> arcs(inst.edges.size());
635 for (size_t i = 0; i < nodes.size(); ++i)
636 nodes[i] = i;
637 for (size_t i = 0; i < arcs.size(); ++i)
638 arcs[i] = i;
639 for (const int scale : {-7, 9})
640 {
641 Built<double> plain;
642 Built<double> scaled;
643 build(inst, plain, nodes, arcs, 0);
644 build(inst, scaled, nodes, arcs, scale);
645 using G = Graph_T<double>;
646 const size_t bound = std::max<size_t>(1, inst.n);
647 const auto a = most_negative_cycle_bounded<G, Dft_Dist<G>, Hide_Set<double>>(
648 plain.g, bound, Dft_Dist<G>(), Hide_Set<double>{&plain.hidden});
649 const auto b = most_negative_cycle_bounded<G, Dft_Dist<G>, Hide_Set<double>>(
650 scaled.g, bound, Dft_Dist<G>(), Hide_Set<double>{&scaled.hidden});
651 ASSERT_EQ(a.has_cycle, b.has_cycle) << "trial=" << trial;
652 if (not a.has_cycle)
653 continue;
654 ASSERT_EQ(b.total_cost, std::ldexp(a.total_cost, scale)) << "trial=" << trial;
655 ASSERT_EQ(b.optimality_gap, std::ldexp(a.optimality_gap, scale)) << "trial=" << trial;
656 ASSERT_EQ(a.is_exact, b.is_exact) << "trial=" << trial;
657 ASSERT_EQ(a.matches_relaxed_bound, b.matches_relaxed_bound) << "trial=" << trial;
658 ASSERT_EQ(a.length, b.length) << "trial=" << trial;
659 }
660 }
661}
662
663
664// The order in which arcs and nodes are inserted changes how ties are broken
665// and the order of the sums, but not the exact optimum: whenever a result is
666// certified (bounded search) or verified exactly (Howard), its value is the
667// oracle's, whatever the order.
668TEST(NegativeCyclesNumericTest, CertifiedResultsDoNotDependOnArcOrNodeOrder)
669{
670 std::mt19937_64 rng(0x0D3E5);
671 for (const auto family : {Family::Moderate, Family::Ties, Family::Three_Scales, Family::Market})
672 for (size_t trial = 0; trial < 200; ++trial)
673 {
674 const Instance<double> inst = make_instance<double>(family, rng);
675 const Oracle o = oracle(inst, inst.n);
676 std::vector<size_t> nodes(inst.n);
677 std::vector<size_t> arcs(inst.edges.size());
678 for (size_t i = 0; i < nodes.size(); ++i)
679 nodes[i] = i;
680 for (size_t i = 0; i < arcs.size(); ++i)
681 arcs[i] = i;
682 for (int shuffle = 0; shuffle < 4; ++shuffle)
683 {
684 std::shuffle(nodes.begin(), nodes.end(), rng);
685 std::shuffle(arcs.begin(), arcs.end(), rng);
686 Built<double> b;
687 build(inst, b, nodes, arcs);
688 using G = Graph_T<double>;
689
690 const auto r = most_negative_cycle_bounded<G, Dft_Dist<G>, Hide_Set<double>>(
691 b.g, std::max<size_t>(1, inst.n), Dft_Dist<G>(), Hide_Set<double>{&b.hidden});
692 if (r.is_exact)
693 {
694 Rational total;
695 size_t length = 0;
696 ASSERT_TRUE(exact_witness(b, r.cycle_arcs, total, length));
697 ASSERT_EQ(compare(total, o.best_total), 0) << "trial=" << trial;
698 }
699
700 const auto h = howard_minimum_mean_cycle<G, Dft_Dist<G>, Hide_Set<double>>(
701 b.g, Dft_Dist<G>(), Hide_Set<double>{&b.hidden});
702 if (h.has_cycle and not h.used_karp and h.numeric_quality == Cycle_Numeric_Quality::Exact)
703 {
704 Rational total;
705 size_t length = 0;
706 ASSERT_TRUE(exact_witness(b, h.cycle_arcs, total, length));
707 ASSERT_TRUE(mean_equal(total, length, o.best_mean_total, o.best_mean_length))
708 << "trial=" << trial;
709 }
710 }
711 }
712}
713
714
715TEST(NegativeCyclesNumericTest, ExactUpperBoundBeyondTheRangeIsInfinity)
716{
717 // CodeRabbit, PR #103: upper() stepped its bound with nextafter() until it
718 // was not below the exact value. Above DBL_MAX the step reaches infinity,
719 // whose negation the exact check cannot add, and it looped forever.
721 const double max = std::numeric_limits<double>::max();
722
723 Exact_Sum<double> above;
724 ASSERT_TRUE(above.add(max));
725 ASSERT_TRUE(above.add(1.0)); // DBL_MAX + 1, an expansion of finite components
726 EXPECT_EQ(above.upper(), std::numeric_limits<double>::infinity());
727
728 // Finite bounds are unchanged: the value itself when representable, the
729 // next number up otherwise, also at the edge of the range.
730 Exact_Sum<double> at;
731 ASSERT_TRUE(at.add(max));
732 EXPECT_EQ(at.upper(), max);
733
734 Exact_Sum<double> just_above_one;
735 ASSERT_TRUE(just_above_one.add(1.0));
736 ASSERT_TRUE(just_above_one.add(0x1p-60));
737 EXPECT_EQ(just_above_one.upper(), std::nextafter(1.0, 2.0));
738
739 Exact_Sum<double> below_minus_max; // -DBL_MAX - 1: the bound -DBL_MAX is finite
740 ASSERT_TRUE(below_minus_max.add(-max));
741 ASSERT_TRUE(below_minus_max.add(-1.0));
742 EXPECT_EQ(below_minus_max.upper(), -max);
743
744 // Independent audit of stage C, E1. After an add() that overflowed, a
745 // component is -inf and the value is meaningless; upper() stepped up from
746 // -DBL_MAX one ulp at a time and never ended. It is now infinity. The
747 // overflow uses the largest component, which is a long double where
748 // FLT_EVAL_METHOD is not 0: there twice -DBL_MAX does not overflow.
749 using Component = Exact_Sum<double>::Component;
750 const Component component_max = std::numeric_limits<Component>::max();
751 Exact_Sum<double> broken;
752 ASSERT_TRUE(broken.add(-component_max));
753 ASSERT_FALSE(broken.add(-component_max));
754 EXPECT_EQ(broken.upper(), std::numeric_limits<double>::infinity());
755}
756
757
758TEST(NegativeCyclesNumericTest, ExactSumsNearTheLargestFiniteValueStayExact)
759{
760 // Final independent review of the branch, F1. TwoSum computes s - a, which
761 // overflows when an operand is DBL_MAX although s does not: add() returned
762 // true with a NaN component, and the triangle below, of finite weights
763 // whose total fits, got a NaN cost, was not negative, or was not reported.
764 // A sibling case: a partial sum inside Grow-Expansion overflowed although
765 // the value fitted, and add() returned false for a total near 2^1023.
767 const double max = std::numeric_limits<double>::max();
768 const double a = 0x1p968;
769 const double c = -(0x1p1022 - 0x1p970); // a + max + c = 3 * 2^1022 - 3 * 2^968
770
771 Exact_Sum<double> s;
772 ASSERT_TRUE(s.add(a));
773 ASSERT_TRUE(s.add(max));
774 ASSERT_TRUE(s.add(c));
775 EXPECT_EQ(s.sign(), 1);
776 EXPECT_EQ(s.rounded(), 0x1.8p1023);
777
778 Exact_Sum<double> t; // -2^1023 - 3 * 2^970 + max = 2^1023 - 5 * 2^970
779 ASSERT_TRUE(t.add(-0x1p1023));
780 ASSERT_TRUE(t.add(-0x3p970));
781 ASSERT_TRUE(t.add(max));
782 EXPECT_EQ(t.sign(), 1);
783 EXPECT_EQ(t.rounded(), 0x1.ffffffffffffbp1022);
784
785 Exact_Sum<float> f; // the triangle in float: 2^101 + FLT_MAX - (2^126 - 2^102)
786 ASSERT_TRUE(f.add(0x1p101f));
787 ASSERT_TRUE(f.add(std::numeric_limits<float>::max()));
788 ASSERT_TRUE(f.add(-(0x1p126f - 0x1p102f)));
789 EXPECT_EQ(f.sign(), 1);
790 EXPECT_EQ(f.rounded(), 0x1.7ffffep127f);
791
792 // Through the searches, the negated triangle is clearly negative.
793 using G = Graph_T<double>;
794 G g;
795 auto n0 = g.insert_node(0);
796 auto n1 = g.insert_node(1);
797 auto n2 = g.insert_node(2);
798 g.insert_arc(n0, n1, -a);
799 g.insert_arc(n1, n2, -max);
800 g.insert_arc(n2, n0, -c);
801
802 const auto u3 = most_negative_cycle_up_to_3(g, 3);
803 ASSERT_TRUE(u3.has_cycle);
804 EXPECT_TRUE(u3.is_negative());
805 EXPECT_EQ(u3.total_cost, -0x1.8p1023);
806
807 const auto bounded = most_negative_cycle_bounded(g, 3);
808 ASSERT_TRUE(bounded.has_cycle);
809 EXPECT_EQ(bounded.total_cost, -0x1.8p1023);
810
811 const auto found = find_disjoint_negative_cycles(g, 3);
812 ASSERT_EQ(found.size(), 1u);
813 EXPECT_EQ(found.get_first().total_cost, -0x1.8p1023);
814
815 const auto h = howard_minimum_mean_cycle(g);
816 ASSERT_TRUE(h.has_cycle);
817 EXPECT_EQ(h.cycle_total_cost, -0x1.8p1023);
818 EXPECT_LT(h.minimum_mean, 0.0L);
819}
820
821
822TEST(NegativeCyclesNumericTest, TotalsBeyondTheRangeThrowWhateverTheEvaluationMethod)
823{
824 // Final independent review of the branch, F3. Where FLT_EVAL_METHOD is not
825 // 0 the exact sums of doubles are kept in long double, which does not
826 // overflow at DBL_MAX: the total -(DBL_MAX + 2^970) of this triangle was
827 // published as -infinity instead of throwing, as it does elsewhere.
828 using G = Graph_T<double>;
829 const double max = std::numeric_limits<double>::max();
830 G g;
831 auto n0 = g.insert_node(0);
832 auto n1 = g.insert_node(1);
833 auto n2 = g.insert_node(2);
834 g.insert_arc(n0, n1, -max);
835 g.insert_arc(n1, n2, -0x1p969);
836 g.insert_arc(n2, n0, -0x1p969);
837
838 EXPECT_THROW(find_disjoint_negative_cycles(g, 3), std::domain_error);
839 EXPECT_THROW(most_negative_cycle_up_to_3(g, 3), std::domain_error);
840}
Minimum mean cycle by Howard's policy iteration.
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
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
Graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:439
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Exact sum of floating-point numbers.
#define TEST(name)
static mt19937 rng
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
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...
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.
decltype(auto) current(It &it) noexcept(current_is_noexcept< It >)
Current item of an iterator that is positioned on one.
Definition ah-dry.H:233
void build(Tree_Node< Key > *troot, Convert &&convert, typename GT::Node *groot, Args &&... args)
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
bool mean_less(const Acc c1, const size_t l1, const Acc c2, const size_t l2)
Whether the mean c1 / l1 is smaller than c2 / l2.
Main namespace for Aleph-w library functions.
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
static long & low(typename GT::Node *p)
Internal helper: low-link value stored directly in NODE_COOKIE(p).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
Gen_MultiPolynomial< C, M > operator-(const C &s, const Gen_MultiPolynomial< C, M > &p)
Scalar - polynomial.
and
Check uniqueness with explicit hash + equality functors.
auto shuffle(const C< T > &c)
Randomly shuffle a sequence.
std::vector< std::string > & split(const std::string &s, const char delim, std::vector< std::string > &elems)
Split a std::string by a single delimiter character.
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
STL namespace.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Gsl_Compatible_Rng r
Generic graph and digraph implementations.