Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
negative_cycles_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
37// Self-containment check: must stay the first include.
38# include <Negative_Cycles.H>
39
40# include <gtest/gtest.h>
41
42# include <cmath>
43# include <functional>
44# include <limits>
45# include <random>
46# include <set>
47# include <thread>
48# include <tuple>
49# include <type_traits>
50# include <vector>
51
52# include <Bellman_Ford.H>
53# include <tpl_agraph.H>
54# include <tpl_graph.H>
55
57
58using namespace Aleph;
59using namespace Negative_Cycles_Test_Support;
60
61namespace
62{
64
65 // A reported item must be a closed path over consecutive graph arcs that
66 // visits no node twice, whose arc weights sum to total_cost, negative.
67 template <class GT, typename Cost>
69 {
70 if (item.cycle.is_empty() or not item.cycle.is_cycle() or not item.cycle.inside_graph(g))
71 return false;
72
73 const auto arcs = item.cycle.arcs();
74 if (arcs.size() != item.length or item.length == 0)
75 return false;
76
77 std::set<typename GT::Node *> seen;
78 typename GT::Node * first = item.cycle.get_first_node();
79 typename GT::Node * curr = first;
80 Cost sum = Cost{0};
81 long double abs_sum = 0.0L;
82 for (auto it = arcs.get_it(); it.has_curr(); it.next_ne())
83 {
84 typename GT::Arc * arc = it.get_curr();
85 if (g.get_src_node(arc) != curr or not seen.insert(curr).second)
86 return false;
87 sum += arc->get_info();
88 abs_sum += std::fabs(static_cast<long double>(arc->get_info()));
89 curr = g.get_tgt_node(arc);
90 }
91
92 if (curr != first)
93 return false;
94 if constexpr (std::is_floating_point_v<Cost>)
95 // total_cost is a compensated sum: it may differ from the plain sum above by
96 // the rounding error of plain summation, at most (terms + 1) * eps * sum of |w|
97 return std::fabs(static_cast<long double>(sum) - static_cast<long double>(item.total_cost))
98 <= (item.length + 1) * static_cast<long double>(std::numeric_limits<Cost>::epsilon()) * abs_sum
99 and item.total_cost < Cost{0};
100 else
101 return sum == item.total_cost and sum < Cost{0};
102 }
103
104 template <class GT, typename Cost>
105 std::set<typename GT::Arc *> arc_set(const Negative_Cycle_Item<GT, Cost> & item)
106 {
107 std::set<typename GT::Arc *> s;
108 item.cycle.for_each_arc([&s](typename GT::Arc * a) { s.insert(a); });
109 return s;
110 }
111
112 template <class GT, typename Cost>
114 const bool require_disjoint)
115 {
116 std::vector<std::set<typename GT::Arc *>> sets;
117 for (auto it = items.get_it(); it.has_curr(); it.next_ne())
118 sets.push_back(arc_set(it.get_curr()));
119
120 for (size_t i = 0; i < sets.size(); ++i)
121 for (size_t j = i + 1; j < sets.size(); ++j)
122 {
123 if (sets[i] == sets[j])
124 return false;
126 for (auto * a : sets[i])
127 if (sets[j].count(a) != 0)
129 }
130 return true;
131 }
132
133 // Exhaustive oracle: does the graph have a simple cycle of negative total
134 // weight among the arcs accepted by `allow`?
136 const std::function<bool(Arc *)> & allow)
137 {
138 const size_t n = built.nodes.size();
139 std::vector<bool> visited(n, false);
140 bool found = false;
141
142 std::function<void(size_t, size_t, long long)> dfs =
143 [&](const size_t start, const size_t u, const long long cost)
144 {
145 if (found)
146 return;
147 for (Node_Arc_Iterator<Graph> it(built.nodes[u]); it.has_curr(); it.next_ne())
148 {
149 Arc * arc = it.get_current_arc_ne();
150 if (not allow(arc))
151 continue;
152 const size_t v = static_cast<size_t>(it.get_tgt_node()->get_info());
153 const long long w = arc->get_info();
154 if (v == start)
155 {
156 if (cost + w < 0)
157 found = true;
158 continue;
159 }
160 if (v < start or visited[v]) // canonical start: the minimum node of the cycle
161 continue;
162 visited[v] = true;
163 dfs(start, v, cost + w);
164 visited[v] = false;
165 }
166 };
167
168 for (size_t s = 0; s < n and not found; ++s)
169 {
170 visited[s] = true;
171 dfs(s, s, 0);
172 visited[s] = false;
173 }
174 return found;
175 }
176
177
178 // The same triangle of total cost -1 for every cost type.
179 template <typename W>
181 {
183 auto built = build_graph_generic<G, W>(
184 3, {{0, 1, W(1)}, {1, 2, W(-3)}, {2, 0, W(1)}});
185
186 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
187 ASSERT_EQ(cycles.size(), 1u);
188 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, cycles.get_first()));
189 EXPECT_EQ(cycles.get_first().total_cost, W(-1));
190 EXPECT_EQ(cycles.get_first().length, 3u);
191 }
192} // namespace
193
194
196{
197 // 0 -> 1 -> 2 -> 0 costs -1 (3 arcs); 3 -> 4 -> 3 costs -1 (2 arcs).
198 const std::vector<Edge_Def> edges = {
199 {0, 1, 1}, {1, 2, -3}, {2, 0, 1},
200 {2, 3, 5},
201 {3, 4, -2}, {4, 3, 1}
202 };
203 auto built = build_graph(5, edges);
204
205 for (const auto policy : {Negative_Cycle_Exclusion::Min_Weight_Arc,
206 Negative_Cycle_Exclusion::All_Arcs})
207 {
208 const auto cycles = find_disjoint_negative_cycles(built.g, 10, policy);
209 ASSERT_EQ(cycles.size(), 2u);
210
211 std::multiset<size_t> lengths;
212 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
213 {
214 const Item & item = it.get_curr();
216 EXPECT_EQ(item.total_cost, -1);
217 lengths.insert(item.length);
218 }
219 EXPECT_EQ(lengths, (std::multiset<size_t>{2, 3}));
221 }
222}
223
224
226{
227 const std::vector<Edge_Def> edges = {
228 {0, 1, 2}, {1, 2, -5}, {2, 0, 1}, // -2
229 {2, 3, 1}, {3, 0, 4} // 0 -> 1 -> 2 -> 3 -> 0 costs 2
230 };
231 auto built = build_graph(4, edges);
232
233 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
234 ASSERT_EQ(cycles.size(), 1u);
235 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, cycles.get_first()));
236 EXPECT_EQ(cycles.get_first().total_cost, -2);
237 EXPECT_EQ(cycles.get_first().length, 3u);
238}
239
240
242{
243 const std::vector<Edge_Def> positive = {
244 {0, 1, 1}, {1, 2, 1}, {2, 0, 1}, {1, 0, 3}
245 };
246 auto cyc = build_graph(3, positive);
248
249 const std::vector<Edge_Def> dag = {
250 {0, 1, -4}, {1, 2, -4}, {0, 2, -9}
251 };
252 auto acyclic = build_graph(3, dag);
254
255 Graph empty;
256 EXPECT_TRUE(find_disjoint_negative_cycles(empty, 5).is_empty());
257}
258
259
261{
262 const std::vector<Edge_Def> edges = {{0, 1, -1}, {1, 0, -1}};
263 auto built = build_graph(2, edges);
264
265 EXPECT_TRUE(find_disjoint_negative_cycles(built.g, 0).is_empty());
266 EXPECT_EQ(find_disjoint_negative_cycles(built.g, 1).size(), 1u);
267}
268
269
270// max_cycles == 0 must not snapshot nor validate the graph: no exception for
271// an undirected graph and no call to the distance accessor.
273{
274 UGraph undirected;
275 auto * u0 = undirected.insert_node(0);
276 auto * u1 = undirected.insert_node(1);
277 undirected.insert_arc(u0, u1, -1);
278 EXPECT_NO_THROW({ EXPECT_TRUE(find_disjoint_negative_cycles(undirected, 0).is_empty()); });
279
280 struct Counting_Dist
281 {
282 using Distance_Type = long long;
283 int * calls;
284 Distance_Type operator()(Arc * a) const { ++*calls; return a->get_info(); }
285 };
286 auto built = build_graph(2, {{0, 1, -1}, {1, 0, -1}});
287 int calls = 0;
289 built.g, 0, Negative_Cycle_Exclusion::Min_Weight_Arc, Counting_Dist{&calls})).is_empty());
290 EXPECT_EQ(calls, 0);
291}
292
293
295{
296 // Three arc-disjoint negative 2-cycles.
297 const std::vector<Edge_Def> edges = {
298 {0, 1, -1}, {1, 0, 0},
299 {2, 3, -1}, {3, 2, 0},
300 {4, 5, -1}, {5, 4, 0},
301 {1, 2, 7}, {3, 4, 7}
302 };
303 auto built = build_graph(6, edges);
304
305 EXPECT_EQ(find_disjoint_negative_cycles(built.g, 2).size(), 2u);
306 EXPECT_EQ(find_disjoint_negative_cycles(built.g, 3).size(), 3u);
307 EXPECT_EQ(find_disjoint_negative_cycles(built.g, 100).size(), 3u);
308}
309
310
312{
313 // Two 2-cycles hanging from node 0.
314 const std::vector<Edge_Def> edges = {
315 {0, 1, -2}, {1, 0, 1}, // -1
316 {0, 2, -3}, {2, 0, 1} // -2
317 };
318 auto built = build_graph(3, edges);
319
320 for (const auto policy : {Negative_Cycle_Exclusion::Min_Weight_Arc,
321 Negative_Cycle_Exclusion::All_Arcs})
322 {
323 const auto cycles = find_disjoint_negative_cycles(built.g, 10, policy);
324 ASSERT_EQ(cycles.size(), 2u);
325 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
326 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, it.get_curr()));
328 }
329}
330
331
333{
334 // A: 0 -> 1 -> 2 -> 0 costs -3; B: 0 -> 1 -> 3 -> 0 costs -2. They share
335 // arc 0 -> 1, which is the minimum-weight arc of neither cycle.
336 const std::vector<Edge_Def> edges = {
337 {0, 1, 1},
338 {1, 2, -5}, {2, 0, 1},
339 {1, 3, -2}, {3, 0, -1}
340 };
341 auto built = build_graph(4, edges);
342
343 const auto min_arc = find_disjoint_negative_cycles(
344 built.g, 10, Negative_Cycle_Exclusion::Min_Weight_Arc);
345 ASSERT_EQ(min_arc.size(), 2u);
346 for (auto it = min_arc.get_it(); it.has_curr(); it.next_ne())
347 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, it.get_curr()));
349
350 const auto all_arcs = find_disjoint_negative_cycles(
351 built.g, 10, Negative_Cycle_Exclusion::All_Arcs);
352 ASSERT_EQ(all_arcs.size(), 1u);
353 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, all_arcs.get_first()));
354}
355
356
358{
359 // Two arcs 0 -> 1 (weights 5 and -4) and one arc 1 -> 0 (weight 1): the
360 // only negative cycle uses the -4 arc, which must be the one reported.
361 auto built = build_graph(2, {{0, 1, 5}, {0, 1, -4}, {1, 0, 1}});
362
363 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
364 ASSERT_EQ(cycles.size(), 1u);
365 const Item & item = cycles.get_first();
367 EXPECT_EQ(item.total_cost, -3);
368 EXPECT_TRUE(item.cycle.contains_arc(built.arcs[1]));
369 EXPECT_FALSE(item.cycle.contains_arc(built.arcs[0]));
370}
371
372
374{
375 auto built = build_graph(3, {{0, 1, 1}, {1, 2, -3}, {2, 0, 1}});
376
377 ASSERT_EQ(find_disjoint_negative_cycles(built.g, 5).size(), 1u);
378
379 const Hide_Arc filter{built.arcs[1]};
381 built.g, 5, Negative_Cycle_Exclusion::Min_Weight_Arc, Dft_Dist<Graph>(), filter);
382 EXPECT_TRUE(hidden.is_empty());
383}
384
385
387{
389 3, {{0, 1, -0.75}, {1, 2, 0.25}, {2, 0, 0.25}, {2, 1, 0.5}});
390
391 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
392 ASSERT_EQ(cycles.size(), 1u);
393 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, cycles.get_first()));
394 EXPECT_NEAR(cycles.get_first().total_cost, -0.25, 1e-12);
395}
396
397
399{
401 3, {{0, 1, -4}, {1, 0, 1}, {1, 2, 3}, {2, 1, 3}});
402
403 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
404 ASSERT_EQ(cycles.size(), 1u);
405 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, cycles.get_first()));
406 EXPECT_EQ(cycles.get_first().total_cost, -3);
407}
408
409
411{
412 UGraph undirected;
413 auto * u0 = undirected.insert_node(0);
414 auto * u1 = undirected.insert_node(1);
415 undirected.insert_arc(u0, u1, -1);
416 EXPECT_THROW((find_disjoint_negative_cycles(undirected, 1)), std::domain_error);
417
419 auto * i0 = inf_graph.insert_node(0);
420 auto * i1 = inf_graph.insert_node(1);
421 inf_graph.insert_arc(i0, i1, -std::numeric_limits<double>::infinity());
422 inf_graph.insert_arc(i1, i0, 1.0);
423 EXPECT_THROW((find_disjoint_negative_cycles(inf_graph, 1)), std::domain_error);
424
426 auto * n0 = nan_graph.insert_node(0);
427 auto * n1 = nan_graph.insert_node(1);
428 nan_graph.insert_arc(n0, n1, std::numeric_limits<double>::quiet_NaN());
429 nan_graph.insert_arc(n1, n0, 1.0);
430 EXPECT_THROW((find_disjoint_negative_cycles(nan_graph, 1)), std::domain_error);
431
432 // dist[1] becomes -5, then -5 + min overflows.
433 auto overflow = build_graph(2, {{0, 1, -5}, {1, 0, std::numeric_limits<long long>::min()}});
434 EXPECT_THROW((find_disjoint_negative_cycles(overflow.g, 1)), std::overflow_error);
435}
436
437
439{
440 auto built = build_graph(3, {{0, 1, 1}, {1, 2, -3}, {2, 0, 1}});
441 const size_t nodes = built.g.get_num_nodes();
442 const size_t arcs = built.g.get_num_arcs();
443
444 const Graph & cg = built.g; // the function takes a const graph
445 const auto cycles = find_disjoint_negative_cycles(cg, 5);
446 ASSERT_EQ(cycles.size(), 1u);
447
448 EXPECT_EQ(built.g.get_num_nodes(), nodes);
449 EXPECT_EQ(built.g.get_num_arcs(), arcs);
450 for (auto * a : built.arcs)
451 EXPECT_EQ(ARC_COOKIE(a), nullptr);
452 for (auto * p : built.nodes)
453 EXPECT_EQ(NODE_COOKIE(p), nullptr);
454}
455
456
457// ---------------------------------------------------------------------------
458// Known numeric limitation (F2 of auditoria-rama-arbitrage-performance-bugs.md,
459// delimited in stage B of auditoria-profunda-arbitraje-2026-10-02.md).
460//
461// The loop 1 -> 1 of weight -1 is exactly representable and is a negative
462// cycle, but the incoming arc of weight -1e16 puts dist[1] at -1e16, where
463// adding -1 is absorbed: dist[1] never improves, the loop never enters the
464// predecessor graph and no cycle is extracted. most_negative_cycle_bounded()
465// keeps per-layer costs and does find the loop. Running the enumeration on
466// the cyclic core would remove that arc (it joins two components), but it was
467// measured to cost 1.3 to 2.3 times as much in every benchmark family without
468// saving anything, and it cannot help inside a component (next test): the
469// limitation is documented instead, and pinned here.
470// ---------------------------------------------------------------------------
472{
473 // Same arcs in both insertion orders: the outcome does not depend on it.
474 for (const bool incoming_first : {true, false})
475 {
476 Float_Graph g;
477 auto * s = g.insert_node(0);
478 auto * v = g.insert_node(1);
479 if (incoming_first)
480 {
481 g.insert_arc(s, v, -1e16);
482 g.insert_arc(v, v, -1.0);
483 }
484 else
485 {
486 g.insert_arc(v, v, -1.0);
487 g.insert_arc(s, v, -1e16);
488 }
489
490 const auto cycles = find_disjoint_negative_cycles(g, 1);
491 EXPECT_TRUE(cycles.is_empty()) << "incoming_first=" << incoming_first; // known limitation
492
493 const auto bounded = most_negative_cycle_bounded(g, 1);
494 ASSERT_TRUE(bounded.has_cycle) << "incoming_first=" << incoming_first;
495 EXPECT_EQ(bounded.total_cost, -1.0);
496 EXPECT_EQ(bounded.length, 1u);
497 }
498}
499
500
501// KNOWN LIMITATION: the same absorption with the huge arc inside a strongly
502// connected component: 0 -> 1 of -1e16, 1 -> 0 of +1e16 and the loop of -1 on
503// node 1. Restricting the search to the cyclic core would not help here
504// either: with floating-point costs an empty result is not a proof that no
505// negative cycle exists.
507{
508 Float_Graph g;
509 auto * s = g.insert_node(0);
510 auto * v = g.insert_node(1);
511 g.insert_arc(s, v, -1e16);
512 g.insert_arc(v, s, 1e16);
513 g.insert_arc(v, v, -1.0);
514
515 EXPECT_TRUE(find_disjoint_negative_cycles(g, 1).is_empty()); // known limitation
516
517 const auto bounded = most_negative_cycle_bounded(g, 1);
518 ASSERT_TRUE(bounded.has_cycle);
519 EXPECT_EQ(bounded.total_cost, -1.0);
520 EXPECT_EQ(bounded.length, 1u);
521}
522
523
524// ---------------------------------------------------------------------------
525// F1 of auditoria-rama-arbitrage-performance-bugs.md for the enumeration.
526//
527// Each ring below has an exact total of zero (checked with integers) but its
528// plain double sum rounds to -1, because the huge weights swallow the small
529// ones, and the predecessor graph does contain it. It used to be reported as
530// a negative cycle of cost -1. The reported cost is now recomputed with
531// compensated summation, so no cycle is reported.
532// ---------------------------------------------------------------------------
534{
535 const std::vector<std::vector<double>> rings = {
536 {-7.0, -1e16, 1e16, 7.0},
537 {-1e16, -7.0, 1e16, 7.0},
538 {-1e16, -3.0, 1e16, 3.0},
539 {-3.0, -1e16, 5e15, 3.0, 5e15},
540 {-1e16, 4.0, -7.0, 1e16, 3.0}
541 };
542
543 for (const auto & weights : rings)
544 {
545 long long exact_sum = 0; // independent oracle: integer arithmetic, exact here
546 for (const double w : weights)
547 exact_sum += static_cast<long long>(w);
549
550 Float_Graph g;
551 std::vector<Float_Graph::Node *> nodes;
552 for (size_t i = 0; i < weights.size(); ++i)
553 nodes.push_back(g.insert_node(static_cast<int>(i)));
554 for (size_t i = 0; i < weights.size(); ++i)
555 g.insert_arc(nodes[i], nodes[(i + 1) % weights.size()], weights[i]);
556
557 for (const auto policy : {Negative_Cycle_Exclusion::Min_Weight_Arc,
558 Negative_Cycle_Exclusion::All_Arcs})
559 EXPECT_TRUE(find_disjoint_negative_cycles(g, 3, policy).is_empty());
560 }
561}
562
563
565{
566 // 5 arcs, one of them hidden by the filter: the filter is asked about all
567 // of them exactly once and the distance accessor only about accepted ones.
568 auto built = build_graph(3, {{0, 1, 1}, {1, 2, -3}, {2, 0, 1}, {0, 2, 7}, {2, 2, 4}});
569 int dist_calls = 0;
570 int filter_calls = 0;
571
573 built.g, 4, Negative_Cycle_Exclusion::All_Arcs, Counting_Dist{&dist_calls},
574 Counting_Filter{&filter_calls, built.arcs[3]});
575
576 ASSERT_EQ(cycles.size(), 1u);
579}
580
581
583{
584 Float_Graph g;
585 auto * a = g.insert_node(0);
586 auto * b = g.insert_node(1);
587 auto * c = g.insert_node(2);
588 g.insert_arc(a, b, -2.0);
589 g.insert_arc(b, a, 1.0); // cycle of cost -1
590 g.insert_arc(b, c, std::numeric_limits<double>::infinity());
591 g.insert_arc(c, a, std::numeric_limits<double>::quiet_NaN());
592
593 // Without the filter the non-finite weights are rejected...
594 EXPECT_THROW((find_disjoint_negative_cycles(g, 5)), std::domain_error);
595
596 // ...and with a filter that hides exactly those arcs they are never read.
598 g, 5, Negative_Cycle_Exclusion::Min_Weight_Arc, Dft_Dist<Float_Graph>(), Finite_Arcs());
599 ASSERT_EQ(cycles.size(), 1u);
600 EXPECT_NEAR(cycles.get_first().total_cost, -1.0, 1e-12);
601}
602
603
605{
606 auto built = build_graph(4, {{0, 1, 1}, {1, 2, -3}, {2, 0, 1}, {2, 3, -2}, {3, 2, 1}});
608 planted.plant(built);
609 ASSERT_TRUE(planted.intact(built));
610
611 for (const auto policy : {Negative_Cycle_Exclusion::Min_Weight_Arc,
612 Negative_Cycle_Exclusion::All_Arcs})
613 {
614 const auto cycles = find_disjoint_negative_cycles(built.g, 5, policy);
615 EXPECT_EQ(cycles.size(), 2u);
616 EXPECT_TRUE(planted.intact(built));
617 }
618}
619
620
622{
623 auto negative = build_graph(1, {{0, 0, -3}});
624 const auto found = find_disjoint_negative_cycles(negative.g, 5);
625 ASSERT_EQ(found.size(), 1u);
626 EXPECT_TRUE(is_valid_negative_simple_cycle(negative.g, found.get_first()));
627 EXPECT_EQ(found.get_first().total_cost, -3);
628 EXPECT_EQ(found.get_first().length, 1u);
629
630 for (const long long w : {0LL, 3LL})
631 {
632 auto not_negative = build_graph(1, {{0, 0, w}});
633 EXPECT_TRUE(find_disjoint_negative_cycles(not_negative.g, 5).is_empty()) << "w=" << w;
634 }
635
639}
640
641
643{
644 // 0 <-> 1 positive, 2 isolated, 3 <-> 4 negative, 5 -> 6 acyclic.
645 auto built = build_graph(7, {{0, 1, 2}, {1, 0, 2}, {3, 4, -2}, {4, 3, 1}, {5, 6, -9}});
646
647 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
648 ASSERT_EQ(cycles.size(), 1u);
649 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, cycles.get_first()));
650 EXPECT_EQ(cycles.get_first().total_cost, -1);
651 EXPECT_TRUE(cycles.get_first().cycle.contains_node(built.nodes[3]));
652 EXPECT_TRUE(cycles.get_first().cycle.contains_node(built.nodes[4]));
653}
654
655
660
661
666
667
669{
672 const int int_min = std::numeric_limits<int>::min();
673 const int int_max = std::numeric_limits<int>::max();
674 const long double ld_lowest = std::numeric_limits<long double>::lowest();
675 const long double ld_max = std::numeric_limits<long double>::max();
676
677 // A loop of the lowest value is a legitimate negative cycle...
680 ASSERT_EQ(int_found.size(), 1u);
681 EXPECT_EQ(int_found.get_first().total_cost, int_min);
682
685 ASSERT_EQ(ld_found.size(), 1u);
686 EXPECT_EQ(ld_found.get_first().total_cost, ld_lowest);
687
688 // ...the largest value is simply not negative...
693
694 // ...and sums that leave the type throw: overflow for integers, a
695 // non-finite accumulation for floating point.
696 auto int_two = build_graph_generic<IntGraph, int>(2, {{0, 1, int_min}, {1, 0, int_min}});
697 EXPECT_THROW((find_disjoint_negative_cycles(int_two.g, 1)), std::overflow_error);
699 EXPECT_THROW((find_disjoint_negative_cycles(ld_two.g, 1)), std::domain_error);
700}
701
702
704{
705 std::mt19937_64 rng(0x5EED0C1CULL);
706 std::uniform_int_distribution<int> n_dist(2, 7);
707 std::bernoulli_distribution has_edge(0.4);
708 std::bernoulli_distribution has_loop(0.1);
709 std::uniform_int_distribution<int> weight_dist(-9, 13);
710
711 size_t graphs_with_cycles = 0;
712 for (size_t trial = 0; trial < 150; ++trial)
713 {
714 const size_t n = static_cast<size_t>(n_dist(rng));
715 std::vector<Edge_Def> edges;
716 for (size_t u = 0; u < n; ++u)
717 for (size_t v = 0; v < n; ++v)
718 {
719 const bool keep = (u == v) ? has_loop(rng) : has_edge(rng);
720 if (keep)
721 edges.emplace_back(u, v, static_cast<long long>(weight_dist(rng)));
722 }
723
724 auto built = build_graph(n, edges);
725 const bool expected = has_negative_simple_cycle(built, [](Arc *) { return true; });
728
729 for (const auto policy : {Negative_Cycle_Exclusion::Min_Weight_Arc,
730 Negative_Cycle_Exclusion::All_Arcs})
731 {
732 const auto cycles = find_disjoint_negative_cycles(built.g, 10, policy);
733 ASSERT_EQ(not cycles.is_empty(), expected) << "trial=" << trial;
734 ASSERT_LE(cycles.size(), 10u);
735 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
736 ASSERT_TRUE(is_valid_negative_simple_cycle(built.g, it.get_curr())) << "trial=" << trial;
738 cycles, policy == Negative_Cycle_Exclusion::All_Arcs)) << "trial=" << trial;
739
740 // After excluding every reported arc there is no negative cycle left
741 // among the rest, otherwise the search stopped too early.
742 if (policy == Negative_Cycle_Exclusion::All_Arcs and cycles.size() < 10)
743 {
744 std::set<Arc *> used;
745 for (auto it = cycles.get_it(); it.has_curr(); it.next_ne())
746 for (auto * a : arc_set(it.get_curr()))
747 used.insert(a);
749 built, [&used](Arc * a) { return used.count(a) == 0; })) << "trial=" << trial;
750 }
751 }
752 }
753 EXPECT_GT(graphs_with_cycles, 20u); // the sample exercises both outcomes
754}
755
756
757// ---------------------------------------------------------------------------
758// Node index of the snapshot (open addressing over node pointers).
759// ---------------------------------------------------------------------------
760
762{
763 // A ring of many nodes whose total is -1 and a loop among a crowd of
764 // isolated nodes: every node must be found by its pointer.
765 constexpr size_t ring = 5000;
766 std::vector<Edge_Def> edges;
767 for (size_t i = 0; i < ring; ++i)
768 edges.emplace_back(i, (i + 1) % ring, i == 0 ? -static_cast<long long>(ring) : 1);
769 auto built = build_graph(ring, edges);
770
771 const auto cycles = find_disjoint_negative_cycles(built.g, 3);
772 ASSERT_EQ(cycles.size(), 1u);
773 EXPECT_EQ(cycles.get_first().length, ring);
774 EXPECT_EQ(cycles.get_first().total_cost, -1);
775 EXPECT_TRUE(is_valid_negative_simple_cycle(built.g, cycles.get_first()));
776
777 constexpr size_t crowd = 20000;
778 auto sparse = build_graph(crowd, {{12345, 12345, -2}});
779 const auto loops = find_disjoint_negative_cycles(sparse.g, 3);
780 ASSERT_EQ(loops.size(), 1u);
781 EXPECT_EQ(loops.get_first().length, 1u);
782 EXPECT_EQ(loops.get_first().cycle.get_first_node(), sparse.nodes[12345]);
783}
784
785
787{
788 Graph empty;
789 EXPECT_TRUE(find_disjoint_negative_cycles(empty, 3).is_empty());
790
791 auto one = build_graph(1, {{0, 0, -1}});
792 const auto cycles = find_disjoint_negative_cycles(one.g, 3);
793 ASSERT_EQ(cycles.size(), 1u);
794 EXPECT_EQ(cycles.get_first().total_cost, -1);
795}
796
797
798// The index of the snapshot answers with the position of every node it was
799// given, and refuses what it was not given: a null pointer must not match a
800// free slot, and an unknown node must not loop or answer with a position.
802{
803 auto built = build_graph(300, {});
804 auto stranger = build_graph(1, {});
805
807 for (size_t i = 0; i < built.nodes.size(); ++i)
808 index.insert(built.nodes[i], 1000 + i);
809
810 for (size_t i = 0; i < built.nodes.size(); ++i)
811 EXPECT_EQ(index.find(built.nodes[i]), 1000 + i);
812
813 EXPECT_THROW((void) index.find(nullptr), std::domain_error);
814 EXPECT_THROW((void) index.find(stranger.nodes[0]), std::domain_error);
815 EXPECT_THROW(index.insert(nullptr, 0), std::domain_error);
816
817 // A table that is exactly as full as it will ever be still answers.
819 single.insert(built.nodes[7], 42);
820 EXPECT_EQ(single.find(built.nodes[7]), 42u);
821 EXPECT_THROW((void) single.find(built.nodes[8]), std::domain_error);
822}
823
824
825// The file documentation promises that several threads may search the same
826// graph while nobody modifies it: the functions take a `const GT &` and keep
827// all their state local. Every thread must get exactly the single-threaded
828// answer.
830{
831 // Two negative triangles and some positive clutter, with ties.
832 std::vector<Edge_Def> edges = {{0, 1, 2}, {1, 2, -5}, {2, 0, 2},
833 {3, 4, 1}, {4, 5, -4}, {5, 3, 2},
834 {2, 3, 1}, {5, 0, 1}, {1, 4, 3}, {4, 1, 3}};
835 for (size_t u = 6; u < 40; ++u)
836 {
837 edges.emplace_back(u, (u + 1) % 40, 1);
838 edges.emplace_back(u, (u * 7 + 3) % 40, 2);
839 }
840 auto built = build_graph(40, edges);
841
842 const auto cycles_ref = find_disjoint_negative_cycles(built.g, 5);
843 const auto bounded_ref = most_negative_cycle_bounded(built.g, 6);
844 ASSERT_GE(cycles_ref.size(), 2u);
845 ASSERT_TRUE(bounded_ref.has_cycle);
846
847 auto same_cycles = [&](const decltype(cycles_ref) & a)
848 {
849 if (a.size() != cycles_ref.size())
850 return false;
851 auto ia = a.get_it();
852 auto ir = cycles_ref.get_it();
853 for (; ia.has_curr(); ia.next_ne(), ir.next_ne())
854 if (ia.get_curr().total_cost != ir.get_curr().total_cost
855 or ia.get_curr().cycle.arcs() != ir.get_curr().cycle.arcs())
856 return false;
857 return true;
858 };
859
860 constexpr size_t threads = 8;
861 constexpr size_t rounds = 25;
862 std::vector<int> failures(threads, 0);
863 std::vector<std::thread> pool;
864 for (size_t t = 0; t < threads; ++t)
865 pool.emplace_back([&, t]
866 {
867 for (size_t i = 0; i < rounds; ++i)
868 {
869 const auto cycles = find_disjoint_negative_cycles(built.g, 5);
870 const auto bounded = most_negative_cycle_bounded(built.g, 6);
871 if (not same_cycles(cycles) or bounded.total_cost != bounded_ref.total_cost
872 or bounded.length != bounded_ref.length
873 or bounded.is_exact != bounded_ref.is_exact
874 or bounded.cycle_arcs != bounded_ref.cycle_arcs)
875 ++failures[t];
876 }
877 });
878 for (auto & th : pool)
879 th.join();
880
881 for (size_t t = 0; t < threads; ++t)
882 EXPECT_EQ(failures[t], 0) << "thread " << t;
883}
Bellman-Ford algorithm for single-source shortest paths.
Enumeration of negative cycles and bounded-length most negative cycle in directed graphs.
WeightedDigraph::Arc Arc
long double w
Definition btreepic.C:153
Bellman-Ford algorithm for shortest paths with negative weights.
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
Doubly-linked list (defined in tpl_dynList.H).
Definition htlist.H:1231
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Definition tpl_graph.H:535
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
Definition tpl_graph.H:618
Minimal std::expected-style result type for C++20.
Map from node pointers to their positions, built once and never modified afterwards.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
Node * get_tgt_node(Arc *arc) const noexcept
Return the target node of arc (only for directed graphs)
Definition graph-dry.H:1023
#define TEST(name)
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...
#define ARC_COOKIE(p)
Return the arc cookie
Bounded_Cycle_Result< GT, typename Distance::Distance_Type > most_negative_cycle_bounded(const GT &g, const size_t max_length, Distance distance=Distance(), SA sa=SA())
Most negative simple cycle of at most max_length arcs, ranked by total cost (not by mean cost as Karp...
#define NODE_COOKIE(p)
Return the node cookie
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
Main namespace for Aleph-w library functions.
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
and
Check uniqueness with explicit hash + equality functors.
std::ostream & join(const C &c, const std::string &sep, std::ostream &out)
Join elements of an Aleph-style container into a stream.
Itor::difference_type count(const Itor &beg, const Itor &end, const T &value)
Count elements equal to a value.
Definition ahAlgo.H:127
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
Graph types and probe helpers shared by negative_cycles_test.cc and bounded_negative_cycle_test....
#define LL
Definition ran_array.c:24
One negative cycle reported by find_disjoint_negative_cycles().
Path< GT > cycle
Closed path: is_cycle() holds, every arc is a graph arc.
Cost_Type total_cost
Sum of the arc weights, negative; for floating-point costs the exact sum, rounded once.
size_t length
Number of arcs.
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Array-based graph implementation.
Generic graph and digraph implementations.