Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
floyd.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
38#include <gtest/gtest.h>
39
40#include <functional>
41#include <limits>
42#include <map>
43#include <random>
44#include <stdexcept>
45#include <thread>
46#include <type_traits>
47#include <utility>
48#include <vector>
49
50#include <tpl_graph_utils.H>
51#include <Floyd_Warshall.H>
52
53using namespace Aleph;
54using namespace std;
55
56// Graph type using proper node/arc wrappers
60
61namespace {
62
63// Helper to insert arc between nodes by value
64void insert_arc_by_value(Grafo& g, int src_val, int tgt_val, int weight)
65{
66 GNode* src = nullptr;
67 GNode* tgt = nullptr;
68
69 for (Grafo::Node_Iterator it(g); it.has_curr(); it.next_ne()) {
70 auto n = it.get_curr();
71 if (n->get_info() == src_val) src = n;
72 if (n->get_info() == tgt_val) tgt = n;
73 }
74
75 if (src && tgt)
76 g.insert_arc(src, tgt, weight);
77}
78
79} // namespace
80
81// Test basic Floyd algorithm on a simple graph
82TEST(FloydBasicGraph, computes_correct_distances)
83{
84 Grafo g;
85 auto n0 = g.insert_node(0);
86 auto n1 = g.insert_node(1);
87 auto n2 = g.insert_node(2);
88
89 // Create edges: 0->1 (weight 1), 1->2 (weight 2), 0->2 (weight 5)
90 insert_arc_by_value(g, 0, 1, 1);
91 insert_arc_by_value(g, 1, 2, 2);
92 insert_arc_by_value(g, 0, 2, 5);
93
95
96 EXPECT_FALSE(floyd.has_negative_cycle());
97
98 const auto& dist = floyd.get_dist_mat();
99
100 const long i0 = floyd.index_node(n0);
101 const long i1 = floyd.index_node(n1);
102 const long i2 = floyd.index_node(n2);
103
104 // Distance from node to itself should be 0
105 EXPECT_EQ(dist(i0, i0), 0);
106 EXPECT_EQ(dist(i1, i1), 0);
107 EXPECT_EQ(dist(i2, i2), 0);
108
109 // Distance 0->1 should be 1 (direct edge)
110 EXPECT_EQ(dist(i0, i1), 1);
111
112 // Distance 0->2 should be 3 (0->1->2, not direct 0->2 with weight 5)
113 EXPECT_EQ(dist(i0, i2), 3);
114
115 // Distance 1->2 should be 2 (direct edge)
116 EXPECT_EQ(dist(i1, i2), 2);
117}
118
119// Test handling of unreachable nodes
120TEST(FloydBasicGraph, handles_unreachable_nodes)
121{
122 Grafo g;
123 auto n0 = g.insert_node(0);
124 auto n1 = g.insert_node(1);
125 // No edges between nodes
126
128
129 const auto& dist = floyd.get_dist_mat();
130 const int Inf = numeric_limits<int>::max();
131
132 const long i0 = floyd.index_node(n0);
133 const long i1 = floyd.index_node(n1);
134
135 // Distances to unreachable nodes should be infinity
136 EXPECT_EQ(dist(i0, i1), Inf);
137 EXPECT_EQ(dist(i1, i0), Inf);
138
139 // Unreachable paths should be reported as empty paths
140 EXPECT_TRUE(floyd.get_min_path(i0, i1).is_empty());
141 EXPECT_TRUE(floyd.get_min_path(i1, i0).is_empty());
142}
143
144// Test negative weights without negative cycles
145TEST(FloydNegativeWeights, handles_negative_weights_without_cycles)
146{
147 Grafo g;
148 auto n0 = g.insert_node(0);
149 auto n1 = g.insert_node(1);
150 auto n2 = g.insert_node(2);
151
152 // 0->1 (weight -1), 1->2 (weight 2), 0->2 (weight 3)
153 g.insert_arc(n0, n1, -1);
154 g.insert_arc(n1, n2, 2);
155 g.insert_arc(n0, n2, 3);
156
158
159 EXPECT_FALSE(floyd.has_negative_cycle());
160
161 // Get actual indices for nodes
162 long i0 = floyd.index_node(n0);
163 long i1 = floyd.index_node(n1);
164 long i2 = floyd.index_node(n2);
165
166 const auto& dist = floyd.get_dist_mat();
167
168 // Distance 0->1 should be -1 (direct negative edge)
169 EXPECT_EQ(dist(i0, i1), -1);
170
171 // Distance 0->2 should be 1 (0->1->2: -1+2=1, better than direct 0->2: 3)
172 EXPECT_EQ(dist(i0, i2), 1);
173}
174
175// Test negative cycle detection
176TEST(FloydNegativeCycle, detects_negative_cycles)
177{
178 Grafo g;
179 g.insert_node(0);
180 g.insert_node(1);
181 g.insert_node(2);
182
183 // Create cycle: 0->1->2->0 with total weight -1
184 insert_arc_by_value(g, 0, 1, 1);
185 insert_arc_by_value(g, 1, 2, -1);
186 insert_arc_by_value(g, 2, 0, -1);
187
189
190 EXPECT_TRUE(floyd.has_negative_cycle());
191}
192
193// Test index_node method
194TEST(FloydIndexNode, finds_correct_indices)
195{
196 Grafo g;
197 g.insert_node(10);
198 g.insert_node(20);
199 g.insert_node(30);
200
201 insert_arc_by_value(g, 10, 20, 1);
202 insert_arc_by_value(g, 20, 30, 1);
203
205
206 const auto nodes = floyd.get_nodes();
207
208 // Test that we can find each node's index
209 for (size_t i = 0; i < nodes.size(); ++i) {
210 auto node = floyd.select_node(i);
211 EXPECT_EQ(floyd.index_node(node), static_cast<long>(i));
212 }
213}
214
215// Test null pointer handling
216TEST(FloydIndexNode, throws_on_null_pointer)
217{
218 Grafo g;
219 g.insert_node(0);
220
222
223 EXPECT_THROW(floyd.index_node(nullptr), std::invalid_argument);
224}
225
226// Test path reconstruction with indices
227TEST(FloydPathReconstruction, throws_on_invalid_indices)
228{
229 Grafo g;
230 g.insert_node(0);
231 g.insert_node(1);
232 insert_arc_by_value(g, 0, 1, 1);
233
235 const long n = g.get_num_nodes();
236
237 EXPECT_THROW(floyd.get_min_path(-1L, 0L), std::out_of_range);
238 EXPECT_THROW(floyd.get_min_path(0L, n), std::out_of_range);
239 EXPECT_THROW(floyd.get_min_path(n, 0L), std::out_of_range);
240}
241
242// Test path reconstruction returns valid path
243TEST(FloydPathReconstruction, returns_valid_path)
244{
245 Grafo g;
246 auto n0 = g.insert_node(0);
247 auto n1 = g.insert_node(1);
248 auto n2 = g.insert_node(2);
249
250 g.insert_arc(n0, n1, 1);
251 g.insert_arc(n1, n2, 2);
252 g.insert_arc(n0, n2, 5);
253
255
256 // Get actual indices
257 long i0 = floyd.index_node(n0);
258 long i2 = floyd.index_node(n2);
259
260 // Get shortest path from n0 to n2
261 auto path = floyd.get_min_path(i0, i2);
262
263 // Path should have at least 2 nodes (start and end)
264 EXPECT_GE(path.size(), 2u);
265
266 // First node should be n0, last should be n2
267 EXPECT_EQ(path.get_first_node(), n0);
268 EXPECT_EQ(path.get_last_node(), n2);
269}
270
271// Test self-path
272TEST(FloydPathReconstruction, handles_self_paths)
273{
274 Grafo g;
275 g.insert_node(0);
276
278
279 auto path = floyd.get_min_path(0L, 0L);
280 EXPECT_EQ(path.size(), 1u);
281}
282
283// Test entry formatting
284TEST(FloydUtility, entry_formats_distances_correctly)
285{
286 Grafo g;
287 g.insert_node(0);
288
290
291 EXPECT_EQ(floyd.entry(42), "42");
292 EXPECT_EQ(floyd.entry(numeric_limits<int>::max()), "Inf");
293 EXPECT_EQ(floyd.entry(-5), "-5");
294}
295
296// Test path matrix structure
297TEST(FloydMatrices, path_matrix_has_correct_structure)
298{
299 Grafo g;
300 g.insert_node(0);
301 g.insert_node(1);
302 g.insert_node(2);
303
304 insert_arc_by_value(g, 0, 1, 1);
305 insert_arc_by_value(g, 1, 2, 1);
306 insert_arc_by_value(g, 0, 2, 5);
307
309
310 const auto& path_mat = floyd.get_path_mat();
311 const auto& dist = floyd.get_dist_mat();
312 const int Inf = numeric_limits<int>::max();
313 const long n = g.get_num_nodes();
314
315 EXPECT_EQ(path_mat.rows(), n);
316 EXPECT_EQ(path_mat.cols(), n);
317
318 // Path matrix entries should be valid node indices
319 for (long i = 0; i < n; ++i) {
320 for (long j = 0; j < n; ++j) {
321 if (dist(i, j) == Inf) {
322 EXPECT_EQ(path_mat(i, j), -1);
323 continue;
324 }
325
326 // Reachable (including i == j): must be a valid index
327 long k = path_mat(i, j);
328 EXPECT_GE(k, 0);
329 EXPECT_LT(k, n);
330 }
331 }
332}
333
334// Test complete graph
335TEST(FloydLargeGraph, handles_complete_graph)
336{
337 const int N = 10;
338 Grafo g;
339 vector<GNode*> nodes;
340
341 for (int i = 0; i < N; ++i)
342 nodes.push_back(g.insert_node(i));
343
344 // Create complete graph
345 for (int i = 0; i < N; ++i)
346 for (int j = 0; j < N; ++j)
347 if (i != j)
348 g.insert_arc(nodes[i], nodes[j], i + j + 1);
349
351
352 EXPECT_FALSE(floyd.has_negative_cycle());
353
354 const auto& dist = floyd.get_dist_mat();
355
356 // All diagonal elements should be 0
357 for (int i = 0; i < N; ++i)
358 EXPECT_EQ(dist(i, i), 0);
359
360 // The direct arc is the shortest path: going through k adds 2k + 1. (The
361 // test compared the distances with the maximum of double, which the
362 // infinity of int is below.)
363 for (int i = 0; i < N; ++i)
364 for (int j = 0; j < N; ++j)
365 if (i != j) {
366 EXPECT_EQ(dist(floyd.index_node(nodes[i]), floyd.index_node(nodes[j])),
367 i + j + 1);
368 }
369}
370
371// Test single node graph
372TEST(FloydStress, handles_single_node_graph)
373{
374 Grafo g;
375 g.insert_node(42);
376
378
379 EXPECT_FALSE(floyd.has_negative_cycle());
380
381 const auto& dist = floyd.get_dist_mat();
382 EXPECT_EQ(dist.rows(), 1);
383 EXPECT_EQ(dist.cols(), 1);
384 EXPECT_EQ(dist(0, 0), 0);
385
386 // Test path reconstruction for single node
387 auto path = floyd.get_min_path(0L, 0L);
388 EXPECT_EQ(path.size(), 1u);
389 EXPECT_EQ(path.get_first_node()->get_info(), 42);
390}
391
392// Test accessors for node array
393TEST(FloydAccessors, node_accessors_behavior)
394{
395 Grafo g;
396 auto* n1 = g.insert_node(1);
397 auto* n2 = g.insert_node(2);
398 auto* n3 = g.insert_node(3);
399
401
402 // 1. Test get_nodes_ref() - should return a reference to internal state
403 const auto& nodes_ref1 = floyd.get_nodes_ref();
404 const auto& nodes_ref2 = floyd.get_nodes_ref();
405 EXPECT_EQ(&nodes_ref1, &nodes_ref2); // Verify they point to the same object
406 EXPECT_EQ(nodes_ref1.size(), 3u);
407
408 // 2. Test get_nodes_copy() - should return an independent copy
409 auto nodes_copy = floyd.get_nodes_copy();
410 EXPECT_EQ(nodes_copy.size(), 3u);
411
412 // 3. Test get_nodes() - should return an independent copy (Snapshot)
413 auto nodes_val = floyd.get_nodes();
414 EXPECT_EQ(nodes_val.size(), 3u);
415
416 // 4. Verify ordering stability across all accessors
417 for (size_t i = 0; i < 3; ++i) {
418 EXPECT_EQ(nodes_ref1(i), nodes_copy(i));
419 EXPECT_EQ(nodes_ref1(i), nodes_val(i));
420 }
421
422 // 5. Verify that mutating a copy doesn't affect the original
423 nodes_copy(0) = nullptr;
424 EXPECT_NE(floyd.get_nodes_ref()(0), nullptr);
425
426 // 6. Verify pointer validity (non-owning) using the solver's own index map.
427 EXPECT_EQ(nodes_ref1(floyd.index_node(n1)), n1);
428 EXPECT_EQ(nodes_ref1(floyd.index_node(n2)), n2);
429 EXPECT_EQ(nodes_ref1(floyd.index_node(n3)), n3);
430}
431
432// ========== Parallel arcs, loops, graphs that are not directed ==========
433
434namespace {
435
437
438template <class GT, class Distance, class SA>
439long dist_of(const Floyd_All_Shortest_Paths<GT, Distance, SA> & floyd,
440 typename GT::Node * s, typename GT::Node * t)
441{
442 return floyd.get_dist_mat()(floyd.index_node(s), floyd.index_node(t));
443}
444
445template <class GT>
446std::vector<typename GT::Arc *> arcs_of(const Path<GT> & path)
447{
448 std::vector<typename GT::Arc *> arcs;
449 path.for_each_arc([&arcs](typename GT::Arc * a) { arcs.push_back(a); });
450 return arcs;
451}
452
453template <class GT>
454long cost_of(const Path<GT> & path)
455{
456 long total = 0;
457 for (auto a : arcs_of(path))
458 total += a->get_info();
459 return total;
460}
461
462// Distances from s by relaxing every arc until nothing changes, apart from
463// the algorithm under test; the nodes that s does not reach are not in it
464template <class GT>
465std::map<typename GT::Node *, long> relaxed_distances(GT & g,
466 typename GT::Node * s)
467{
468 std::map<typename GT::Node *, long> d{{s, 0}};
469 const int directions = g.is_digraph() ? 1 : 2;
470 for (bool changed = true; changed; )
471 {
472 changed = false;
473 for (typename GT::Arc_Iterator it(g); it.has_curr(); it.next_ne())
474 {
475 auto a = it.get_curr();
476 auto u = g.get_src_node(a);
477 auto v = g.get_tgt_node(a);
478 for (int dir = 0; dir < directions; ++dir, std::swap(u, v))
479 if (d.contains(u) and
480 (not d.contains(v) or d[u] + a->get_info() < d[v]))
481 {
482 d[v] = d[u] + a->get_info();
483 changed = true;
484 }
485 }
486 }
487 return d;
488}
489
490// A random graph with parallel arcs and loops, against the relaxation; and
491// the cost of each path against the matrix
492template <class GT>
493void check_against_relaxation(const unsigned seed)
494{
495 std::mt19937 rng(seed);
496 std::uniform_int_distribution<int> pick(0, 7);
497 std::uniform_int_distribution<int> weight(0, 20);
498 GT g;
499 std::vector<typename GT::Node *> nodes;
500 for (int i = 0; i < 8; ++i)
501 nodes.push_back(g.insert_node(i));
502 for (int k = 0; k < 24; ++k)
503 g.insert_arc(nodes[pick(rng)], nodes[pick(rng)], weight(rng));
504
506 ASSERT_FALSE(floyd.has_negative_cycle()) << "seed " << seed;
507 for (auto s : nodes)
508 {
509 auto d = relaxed_distances(g, s);
510 for (auto t : nodes)
511 {
512 if (not d.contains(t))
513 {
514 EXPECT_EQ(dist_of(floyd, s, t), numeric_limits<int>::max())
515 << "seed " << seed;
516 continue;
517 }
518 EXPECT_EQ(dist_of(floyd, s, t), d[t]) << "seed " << seed;
519 auto path = floyd.get_min_path(s, t);
520 EXPECT_EQ(path.get_first_node(), s) << "seed " << seed;
521 EXPECT_EQ(path.get_last_node(), t) << "seed " << seed;
522 EXPECT_EQ(cost_of(path), d[t]) << "seed " << seed;
523 }
524 }
525}
526
527} // namespace
528
529// The matrix took the arc that IndexArc kept for two nodes, the first one
530// inserted, and get_min_path() took the first one it found.
531TEST(FloydParallelArcs, TakesTheLightest)
532{
533 for (const bool heavy_first : {true, false})
534 {
535 Grafo g;
536 auto a = g.insert_node(0);
537 auto b = g.insert_node(1);
538 GArc * light = nullptr;
539 if (heavy_first)
540 {
541 g.insert_arc(a, b, 5);
542 light = g.insert_arc(a, b, 1);
543 }
544 else
545 {
546 light = g.insert_arc(a, b, 1);
547 g.insert_arc(a, b, 5);
548 }
549
551 EXPECT_EQ(dist_of(floyd, a, b), 1) << heavy_first;
552 EXPECT_EQ(arcs_of(floyd.get_min_path(a, b)),
553 std::vector<GArc *>{light}) << heavy_first;
554 }
555}
556
557// get_min_path() looked for each arc in the direction of the path, so in a
558// graph that is not directed it threw when the path went against an arc.
559TEST(FloydUndirected, PathsGoBothWaysAlongTheArcs)
560{
561 UGrafo g;
562 auto a = g.insert_node(0);
563 auto b = g.insert_node(1);
564 auto c = g.insert_node(2);
565 g.insert_arc(a, b, 3);
566 g.insert_arc(c, b, 4);
567 g.insert_arc(b, c, 9); // parallel to the arc of 4
568
570 EXPECT_EQ(dist_of(floyd, a, c), 7);
571 EXPECT_EQ(dist_of(floyd, c, a), 7);
572
573 auto path = floyd.get_min_path(c, a);
574 EXPECT_EQ(path.get_first_node(), c);
575 EXPECT_EQ(path.get_last_node(), a);
576 EXPECT_EQ(cost_of(path), 7);
577}
578
579// In a graph that is not directed, each arc counts both ways, so a negative
580// arc is a negative cycle on its own.
581TEST(FloydUndirected, ANegativeArcIsANegativeCycle)
582{
583 UGrafo g;
584 auto a = g.insert_node(0);
585 auto b = g.insert_node(1);
586 g.insert_arc(a, b, -1);
588 EXPECT_TRUE(floyd.has_negative_cycle());
589 EXPECT_THROW(floyd.get_min_path(a, b), std::domain_error);
590}
591
592// The guard of the sums discarded those below the range of the type, so the
593// cycle of a -> b (lowest) and b -> a (-1) went unseen, and
594// has_negative_cycle() was false.
595TEST(FloydNumeric, ADistanceBelowTheRangeThrows)
596{
597 const int lowest = numeric_limits<int>::lowest();
598
599 Grafo g;
600 auto a = g.insert_node(0);
601 auto b = g.insert_node(1);
602 g.insert_arc(a, b, lowest);
603 g.insert_arc(b, a, -1);
604 EXPECT_THROW(Floyd_All_Shortest_Paths<Grafo>{g}, std::overflow_error);
605
606 // a cycle of three arcs whose sum, and not that of two, is below
607 Grafo h;
608 auto x = h.insert_node(0);
609 auto y = h.insert_node(1);
610 auto z = h.insert_node(2);
611 h.insert_arc(x, y, lowest / 2);
612 h.insert_arc(y, z, lowest / 2);
613 h.insert_arc(z, x, -1);
614 EXPECT_THROW(Floyd_All_Shortest_Paths<Grafo>{h}, std::overflow_error);
615
616 UGrafo u;
617 auto c = u.insert_node(0);
618 auto d = u.insert_node(1);
619 u.insert_arc(c, d, lowest);
620 EXPECT_THROW(Floyd_All_Shortest_Paths<UGrafo>{u}, std::overflow_error);
621}
622
623// A sum that reaches lowest() exactly is a distance like any other.
624TEST(FloydNumeric, ADistanceAtTheBottomOfTheRangeCounts)
625{
626 const int lowest = numeric_limits<int>::lowest();
627 Grafo g;
628 auto a = g.insert_node(0);
629 auto b = g.insert_node(1);
630 auto c = g.insert_node(2);
631 g.insert_arc(a, b, lowest / 2);
632 g.insert_arc(b, c, lowest / 2);
633
635 EXPECT_FALSE(floyd.has_negative_cycle());
636 EXPECT_EQ(dist_of(floyd, a, c), lowest);
637 EXPECT_EQ(cost_of(floyd.get_min_path(a, c)), lowest);
638}
639
640// The diagonal was set to 0 without looking at the loops, so a negative loop
641// was not a negative cycle.
642TEST(FloydLoops, ANegativeLoopIsANegativeCycle)
643{
644 Grafo g;
645 auto a = g.insert_node(0);
646 auto b = g.insert_node(1);
647 g.insert_arc(a, b, 2);
648 g.insert_arc(a, a, -1);
650 EXPECT_TRUE(floyd.has_negative_cycle());
651
652 UGrafo u;
653 auto c = u.insert_node(0);
654 auto d = u.insert_node(1);
655 u.insert_arc(c, d, 2);
656 u.insert_arc(d, d, -1);
658 EXPECT_TRUE(ufloyd.has_negative_cycle());
659}
660
661TEST(FloydLoops, APositiveLoopDoesNotCount)
662{
663 Grafo g;
664 auto a = g.insert_node(0);
665 auto b = g.insert_node(1);
666 g.insert_arc(a, a, 3);
667 g.insert_arc(a, b, 2);
669 EXPECT_FALSE(floyd.has_negative_cycle());
670 EXPECT_EQ(dist_of(floyd, a, a), 0);
671 EXPECT_EQ(cost_of(floyd.get_min_path(a, b)), 2);
672}
673
674// With a negative cycle, rebuilding a path could go around it forever.
675TEST(FloydNegativeCycle, GetMinPathThrows)
676{
677 Grafo g;
678 auto a = g.insert_node(0);
679 auto b = g.insert_node(1);
680 g.insert_arc(a, a, -1);
681 g.insert_arc(a, b, 2);
683 ASSERT_TRUE(floyd.has_negative_cycle());
684 EXPECT_THROW(floyd.get_min_path(a, b), std::domain_error);
685}
686
687// get_min_path() looked for the arcs without the filter, so it could take an
688// arc that the matrix did not see.
689TEST(FloydFilter, PathsUseOnlyTheArcsOfTheFilter)
690{
691 Grafo g;
692 auto a = g.insert_node(0);
693 auto b = g.insert_node(1);
694 GArc * hidden = g.insert_arc(a, b, 1);
695 GArc * shown = g.insert_arc(a, b, 5);
696
697 struct Hide
698 {
699 GArc * hidden = nullptr;
700 bool operator()(GArc * arc) const noexcept { return arc != hidden; }
701 };
702
703 Hide hide{hidden};
705 EXPECT_EQ(floyd.get_dist_mat()(floyd.index_node(a), floyd.index_node(b)), 5);
706 EXPECT_EQ(arcs_of(floyd.get_min_path(a, b)), std::vector<GArc *>{shown});
707
708 // The solver kept a reference to its filter, so a filter passed as a
709 // temporary was gone once the solver was built
711 from_temporary(g, Hide{hidden});
712 EXPECT_EQ(arcs_of(from_temporary.get_min_path(a, b)),
713 std::vector<GArc *>{shown});
714}
715
716TEST(FloydRandom, MatchesRelaxationWithParallelArcsAndLoops)
717{
718 for (unsigned seed = 1; seed <= 30; ++seed)
719 {
720 check_against_relaxation<Grafo>(seed);
721 check_against_relaxation<UGrafo>(seed);
722 }
723}
724
725// ========== A distance given to the constructor ==========
726
727namespace {
728
729// The weight of an arc times a factor; with a negative factor, the heaviest
730// arcs are the lightest
731struct Scaled_Dist
732{
733 using Distance_Type = int;
734 int factor = 1;
735 int operator()(GArc * a) const noexcept { return factor * a->get_info(); }
736};
737
738// The weight of an arc taken from a base, with no default constructor
739struct From_Base_Dist
740{
741 using Distance_Type = int;
742 int base;
743 explicit From_Base_Dist(int b) noexcept : base(b) {}
744 int operator()(GArc * a) const noexcept { return base - a->get_info(); }
745};
746
747// The weight of an arc, with a call operator that is not const
748struct Not_Const_Dist
749{
750 using Distance_Type = int;
751 int operator()(GArc * a) noexcept { return a->get_info(); }
752};
753
754} // namespace
755
756// The solver built its distance with Distance(), so a distance with state
757// could not be given to it. get_min_path() must take, of the parallel arcs,
758// the lightest for that distance.
759TEST(FloydDistance, UsesTheDistanceItWasGiven)
760{
761 Grafo g;
762 auto a = g.insert_node(0);
763 auto b = g.insert_node(1);
764 auto c = g.insert_node(2);
765 g.insert_arc(a, b, 1);
766 GArc * heavy = g.insert_arc(a, b, 5);
767 GArc * bc = g.insert_arc(b, c, 2);
768
769 Floyd_All_Shortest_Paths<Grafo, Scaled_Dist> floyd(g, Scaled_Dist{-1});
770 ASSERT_FALSE(floyd.has_negative_cycle());
771 EXPECT_EQ(dist_of(floyd, a, b), -5);
772 EXPECT_EQ(dist_of(floyd, a, c), -7);
773 EXPECT_EQ(arcs_of(floyd.get_min_path(a, c)),
774 (std::vector<GArc *>{heavy, bc}));
775}
776
777// A distance without a default constructor, alone and with a filter
778TEST(FloydDistance, TakesADistanceWithoutADefaultConstructor)
779{
780 Grafo g;
781 auto a = g.insert_node(0);
782 auto b = g.insert_node(1);
783 GArc * heavy = g.insert_arc(a, b, 9); // the lightest for a base of 10
784 GArc * light = g.insert_arc(a, b, 4);
785
786 Floyd_All_Shortest_Paths<Grafo, From_Base_Dist> floyd(g, From_Base_Dist(10));
787 EXPECT_EQ(dist_of(floyd, a, b), 1);
788 EXPECT_EQ(arcs_of(floyd.get_min_path(a, b)), std::vector<GArc *>{heavy});
789
790 struct Hide
791 {
792 GArc * hidden = nullptr;
793 bool operator()(GArc * arc) const noexcept { return arc != hidden; }
794 };
795
797 filtered(g, From_Base_Dist(10), Hide{heavy});
798 EXPECT_EQ(dist_of(filtered, a, b), 6);
799 EXPECT_EQ(arcs_of(filtered.get_min_path(a, b)), std::vector<GArc *>{light});
800}
801
802// The solver called a distance built for each arc, so its call operator did
803// not have to be const; get_min_path(), which is const, calls a copy of the
804// distance that the solver keeps.
805TEST(FloydDistance, TakesACallOperatorThatIsNotConst)
806{
807 Grafo g;
808 auto a = g.insert_node(0);
809 auto b = g.insert_node(1);
810 g.insert_arc(a, b, 5);
811 GArc * light = g.insert_arc(a, b, 1);
812
814 EXPECT_EQ(dist_of(floyd, a, b), 1);
815 EXPECT_EQ(arcs_of(floyd.get_min_path(a, b)), std::vector<GArc *>{light});
816}
817
818namespace {
819
820// The weight of an arc, with a call operator that is not const and changes
821// the distance
822struct Counting_Dist
823{
824 using Distance_Type = int;
825 long calls = 0;
826 int operator()(GArc * a) noexcept
827 {
828 ++calls;
829 return a->get_info();
830 }
831};
832
833// The weight of an arc, with a call operator that is const if Const; counts
834// the copies of the distance in *copies
835template <bool Const>
836struct Copied_Dist
837{
838 using Distance_Type = int;
839 long * copies;
840
841 explicit Copied_Dist(long * c) noexcept : copies(c) {}
842 Copied_Dist(const Copied_Dist & d) noexcept : copies(d.copies) { ++*copies; }
843 Copied_Dist & operator = (const Copied_Dist &) = default;
844
845 int operator()(GArc * a) const noexcept requires Const
846 {
847 return a->get_info();
848 }
849
850 int operator()(GArc * a) noexcept requires (not Const)
851 {
852 return a->get_info();
853 }
854};
855
856} // namespace
857
858// get_min_path(), which is const, called the distance of the solver, whose
859// call operator may change it, so concurrent calls on the same solver raced
860// (ThreadSanitizer saw it)
861TEST(FloydDistance, ConcurrentPathsDoNotShareTheDistance)
862{
863 Grafo g;
864 auto a = g.insert_node(0);
865 auto b = g.insert_node(1);
866 auto c = g.insert_node(2);
867 GArc * ab = g.insert_arc(a, b, 1);
868 g.insert_arc(a, b, 5);
869 g.insert_arc(b, c, 7);
870 GArc * bc = g.insert_arc(b, c, 2);
871
873 const std::vector<GArc *> expected = {ab, bc};
874 long wrong[2] = {0, 0};
875 auto work = [&floyd, &expected, a, c](long & mistakes)
876 {
877 for (int i = 0; i < 2000; ++i)
878 if (arcs_of(floyd.get_min_path(a, c)) != expected)
879 ++mistakes;
880 };
881 std::thread first(work, std::ref(wrong[0]));
882 std::thread second(work, std::ref(wrong[1]));
883 first.join();
884 second.join();
885 EXPECT_EQ(wrong[0], 0);
886 EXPECT_EQ(wrong[1], 0);
887}
888
889// get_min_path() copies a distance whose call operator is not const, once
890// for each path, and not one whose call operator is const
891TEST(FloydDistance, GetMinPathCopiesOnlyADistanceThatItMayChange)
892{
893 Grafo g;
894 auto a = g.insert_node(0);
895 auto b = g.insert_node(1);
896 g.insert_arc(a, b, 5);
897 GArc * light = g.insert_arc(a, b, 1);
898
899 long copies = 0;
901 with_const(g, Copied_Dist<true>(&copies));
902 long before = copies;
903 EXPECT_EQ(arcs_of(with_const.get_min_path(a, b)), std::vector<GArc *>{light});
904 EXPECT_EQ(copies, before);
905
907 without_const(g, Copied_Dist<false>(&copies));
908 before = copies;
909 EXPECT_EQ(arcs_of(without_const.get_min_path(a, b)),
910 std::vector<GArc *>{light});
911 EXPECT_EQ(copies, before + 1);
912}
913
914// The constructor that takes a distance took it by value, so the braces of
915// (g, {}) could build either it or the filter, and the call was ambiguous
916TEST(FloydDistance, EmptyBracesAreTheFilter)
917{
918 Grafo g;
919 auto a = g.insert_node(0);
920 auto b = g.insert_node(1);
921 g.insert_arc(a, b, 3);
922
924 EXPECT_EQ(dist_of(floyd, a, b), 3);
925
926 Floyd_All_Shortest_Paths<Grafo, Scaled_Dist> scaled(g, {}); // factor 1
927 EXPECT_EQ(dist_of(scaled, a, b), 3);
928}
929
930// The arguments of the class are deduced from a distance, and from a
931// distance and a filter
932TEST(FloydDistance, TheClassIsDeducedFromTheDistance)
933{
934 Grafo g;
935 auto a = g.insert_node(0);
936 auto b = g.insert_node(1);
937 g.insert_arc(a, b, 3);
938
939 Floyd_All_Shortest_Paths floyd(g, Scaled_Dist{2});
940 static_assert(std::is_same_v<decltype(floyd),
942 EXPECT_EQ(dist_of(floyd, a, b), 6);
943
944 Floyd_All_Shortest_Paths both(g, Scaled_Dist{2}, Dft_Show_Arc<Grafo>());
945 static_assert(std::is_same_v<decltype(both),
947 EXPECT_EQ(dist_of(both, a, b), 6);
948
950 Floyd_All_Shortest_Paths filtered(g, sa);
951 static_assert(std::is_same_v<decltype(filtered),
953 EXPECT_EQ(dist_of(filtered, a, b), 3);
954}
955
956// =============================================================================
957// Negative cycles in large graphs
958// =============================================================================
959
960namespace
961{
964
965 template <class G>
966 std::vector<typename G::Node *> insert_nodes(G & g, long n)
967 {
968 std::vector<typename G::Node *> v;
969 for (long i = 0; i < n; ++i)
970 v.push_back(g.insert_node(static_cast<int>(i)));
971 return v;
972 }
973
974 // An arc of -1 from each node to each other one: the graph is the same for
975 // any order of its nodes
976 template <class G>
977 std::vector<typename G::Node *> complete_of_minus_one(G & g, long n)
978 {
979 auto v = insert_nodes(g, n);
980 for (long i = 0; i < n; ++i)
981 for (long j = 0; j < n; ++j)
982 if (i != j)
983 {
984 g.insert_arc(v[i], v[j], typename G::Arc_Type(-1));
985 }
986 return v;
987 }
988
989 // A ring with arcs of 0 both ways, but for one of -1
990 template <class G>
991 std::vector<typename G::Node *> ring_with_one_negative_arc(G & g, long n)
992 {
993 auto v = insert_nodes(g, n);
994 for (long i = 0; i < n; ++i)
995 {
996 g.insert_arc(v[i], v[(i + 1) % n],
997 typename G::Arc_Type(i == 0 ? -1 : 0));
998 g.insert_arc(v[(i + 1) % n], v[i], typename G::Arc_Type(0));
999 }
1000 return v;
1001 }
1002
1003 // A path with arcs of 0, but for the first one, of -1
1004 template <class G>
1005 std::vector<typename G::Node *> path_with_one_negative_arc(G & g, long n)
1006 {
1007 auto v = insert_nodes(g, n);
1008 for (long i = 0; i + 1 < n; ++i)
1009 g.insert_arc(v[i], v[i + 1], typename G::Arc_Type(i == 0 ? -1 : 0));
1010 return v;
1011 }
1012}
1013
1014// The distances that go round a negative cycle doubled at each k, whatever
1015// the cost of the cycle, until a sum went below lowest() and the solver threw
1016// overflow_error instead of finding the cycle. This graph does not depend on
1017// the order of the nodes, which the solver takes from their addresses: with
1018// it, the solver threw for sure, from 32 nodes with int and from 40 with long.
1019TEST(FloydNegativeCycle, ACompleteDigraphOfNegativeArcs)
1020{
1021 Grafo g;
1022 const auto v = complete_of_minus_one(g, 32);
1024 EXPECT_TRUE(floyd.has_negative_cycle());
1025 EXPECT_THROW(floyd.get_min_path(v.front(), v.back()), std::domain_error);
1026
1027 LGrafo h;
1028 complete_of_minus_one(h, 40);
1029 EXPECT_TRUE(Floyd_All_Shortest_Paths<LGrafo>(h).has_negative_cycle());
1030}
1031
1032// The same with one arc of -1: in a ring, and in a path of a graph that is not
1033// directed, where it is a negative cycle. Whether the solver threw depended on
1034// the order of the nodes.
1035TEST(FloydNegativeCycle, OneNegativeArcInALargeGraph)
1036{
1037 for (long n : {64L, 100L, 256L})
1038 {
1039 SCOPED_TRACE(testing::Message() << n << " nodes");
1040 Grafo g;
1041 ring_with_one_negative_arc(g, n);
1042 EXPECT_TRUE(Floyd_All_Shortest_Paths<Grafo>(g).has_negative_cycle());
1043
1044 LGrafo h;
1045 ring_with_one_negative_arc(h, n);
1046 EXPECT_TRUE(Floyd_All_Shortest_Paths<LGrafo>(h).has_negative_cycle());
1047
1048 UGrafo u;
1049 path_with_one_negative_arc(u, n);
1050 EXPECT_TRUE(Floyd_All_Shortest_Paths<UGrafo>(u).has_negative_cycle());
1051
1052 LUGrafo lu;
1053 path_with_one_negative_arc(lu, n);
1054 EXPECT_TRUE(Floyd_All_Shortest_Paths<LUGrafo>(lu).has_negative_cycle());
1055 }
1056}
1057
1058// A negative loop is a negative cycle before the first k: the solver stops
1059// there, without adding the loop to itself, which here would be below
1060// lowest().
1061TEST(FloydLoops, ALoopAtTheBottomOfTheRangeIsANegativeCycle)
1062{
1063 Grafo g;
1064 auto a = g.insert_node(0);
1065 g.insert_arc(a, a, numeric_limits<int>::lowest());
1067 EXPECT_TRUE(floyd.has_negative_cycle());
1068}
Floyd-Warshall algorithm for all-pairs shortest paths.
long double h
Definition btreepic.C:154
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Arc Arc
Definition graph-dry.H:4381
typename BaseGraph::Node Node
Definition graph-dry.H:4380
Compute the all-pairs shortest path distance matrix and the path reconstruction matrix for a graph g ...
DynArray< Node * > get_nodes() const
Get an owning copy of the graph nodes array.
DynArray< Node * > get_nodes_copy() const
Get an owning copy of the graph nodes array.
Path< GT > get_min_path(const long src_idx, const long tgt_idx) const
Reconstruct the shortest path between two nodes by matrix indices.
const DynMatrix< Distance_Type > & get_dist_mat() const noexcept
Get the distance matrix.
Node * select_node(long i) const noexcept
Get the graph node at a given matrix index.
constexpr bool has_negative_cycle() const noexcept
Check if the graph contains a negative cycle.
std::string entry(const Distance_Type &e) const
Convert a distance value to string representation.
const DynArray< Node * > & get_nodes_ref() const noexcept
Get the array of graph nodes as a constant reference.
const DynMatrix< long > & get_path_mat() const noexcept
Get the path reconstruction matrix.
long index_node(Node *p) const
Return the adjacency-matrix index corresponding to node p.
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
typename Arc::Arc_Type Arc_Type
The type of data stored in the arc.
Definition tpl_graph.H:450
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Path on a graph.
Definition tpl_graph.H:3832
Node * get_first_node() const
Return the first node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4316
Node * get_last_node() const
Return the last node of path; throws overflow_error if path is empty.
Definition tpl_graph.H:4323
void for_each_arc(Operation op=Operation()) const
Execute an operation on each arc of path.
Definition tpl_graph.H:4540
Minimal std::expected-style result type for C++20.
ArcInfo & get_info() noexcept
Return a modifiable reference to the arc data.
Definition graph-dry.H:854
Node * get_src_node(Arc *arc) const noexcept
Return the source node of arc (only for directed graphs)
Definition graph-dry.H:1017
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
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
#define N
Definition fib.C:294
Grafo::Arc GArc
Definition floyd.cc:59
Grafo::Node GNode
Definition floyd.cc:58
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynArray< Graph::Arc * > arcs
Definition graphpic.C:408
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
and
Check uniqueness with explicit hash + equality functors.
STL namespace.
Default filter for filtered iterators on arcs.
Definition tpl_graph.H:1024
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
ValueArg< size_t > seed
Definition testHash.C:53
static int * k
Utility algorithms and operations for graphs.