Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
latex_floyd_test.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
45#include <gtest/gtest.h>
46#include <sstream>
47#include <fstream>
48#include <limits>
49#include <cmath>
50#include <filesystem>
51#if defined(_WIN32)
52# include <process.h>
53#else
54# include <unistd.h>
55#endif
56
57#include <tpl_graph.H>
58#include <tpl_sgraph.H>
59#include <tpl_agraph.H>
60#include <tpl_matgraph.H>
61#include <latex_floyd.H>
62// Both headers, on purpose: they defined the same find_min_path()
63// templates, and could not be included together
64#include <mat_path.H>
65
66using namespace std;
67using namespace testing;
68using namespace Aleph;
69
70// ============================================================================
71// Arc type with distance for Floyd-Warshall
72// ============================================================================
73
76{
77 using Distance_Type = double;
78
79 static constexpr Distance_Type Max_Distance = numeric_limits<double>::infinity();
80 static constexpr Distance_Type Zero_Distance = 0.0;
81
83
86
88
89 operator Distance_Type() const { return distance; }
90};
91
94{
95 using Distance_Type = int;
96
97 static constexpr Distance_Type Max_Distance = numeric_limits<int>::max() / 2; // Avoid overflow
98 static constexpr Distance_Type Zero_Distance = 0;
99
101
104
106
107 operator Distance_Type() const { return distance; }
108};
109
110// ============================================================================
111// Test Fixtures
112// ============================================================================
113
116{
117protected:
122
128
129 void SetUp() override
130 {
131 // Create a simple graph:
132 // 1
133 // 0 -----> 1
134 // | |
135 // |4 |2
136 // v v
137 // 3 <----- 2
138 // 1
139 //
140 // Also: direct edge 0->2 with weight 5 (longer than 0->1->2 = 3)
141
142 n0 = g.insert_node(0);
143 n1 = g.insert_node(1);
144 n2 = g.insert_node(2);
145 n3 = g.insert_node(3);
146
147 g.insert_arc(n0, n1, DistanceArc(1.0)); // 0 -> 1: weight 1
148 g.insert_arc(n1, n2, DistanceArc(2.0)); // 1 -> 2: weight 2
149 g.insert_arc(n2, n3, DistanceArc(1.0)); // 2 -> 3: weight 1
150 g.insert_arc(n0, n3, DistanceArc(4.0)); // 0 -> 3: weight 4 (longer than 0->1->2->3 = 4)
151 g.insert_arc(n0, n2, DistanceArc(5.0)); // 0 -> 2: weight 5 (longer than 0->1->2 = 3)
152 }
153
154 // Helper to get node index by node pointer using matrix iteration
155 long get_index(Ady_Mat<Graph, Dist>& mat, Node* node) const
156 {
157 long n = mat.get_num_nodes();
158 for (long i = 0; i < n; ++i)
159 if (mat(i) == node)
160 return i;
161 return -1;
162 }
163};
164
167{
168protected:
173
175 vector<Node*> nodes;
176
177 static long long process_id() noexcept
178 {
179#if defined(_WIN32)
180 return static_cast<long long>(_getpid());
181#else
182 return static_cast<long long>(getpid());
183#endif
184 }
185
186 string latex_temp_filename() const
187 {
188 const auto *test_info = UnitTest::GetInstance()->current_test_info();
189 string base = string("floyd_test_latex_") + test_info->test_suite_name() + "_" +
190 test_info->name() + "_" + to_string(process_id()) + ".tex";
191
192 for (auto &ch : base)
193 if (ch == '/' or ch == '\\' or ch == ' ')
194 ch = '_';
195
196 return (std::filesystem::temp_directory_path() / base).string();
197 }
198
199 void SetUp() override
200 {
201 // Create a 4-node graph with known shortest paths
202 for (int i = 0; i < 4; ++i)
203 nodes.push_back(g.insert_node(i));
204
205 // Edges: forms a square with diagonal
206 // 0 --2-- 1
207 // | / |
208 // 3 1 4
209 // | / |
210 // 2 --5-- 3
211
212 g.insert_arc(nodes[0], nodes[1], IntDistanceArc(2));
213 g.insert_arc(nodes[1], nodes[0], IntDistanceArc(2));
214 g.insert_arc(nodes[0], nodes[2], IntDistanceArc(3));
215 g.insert_arc(nodes[2], nodes[0], IntDistanceArc(3));
216 g.insert_arc(nodes[1], nodes[2], IntDistanceArc(1)); // Diagonal shortcut
217 g.insert_arc(nodes[2], nodes[1], IntDistanceArc(1));
218 g.insert_arc(nodes[1], nodes[3], IntDistanceArc(4));
219 g.insert_arc(nodes[3], nodes[1], IntDistanceArc(4));
220 g.insert_arc(nodes[2], nodes[3], IntDistanceArc(5));
221 g.insert_arc(nodes[3], nodes[2], IntDistanceArc(5));
222 }
223};
224
225// ============================================================================
226// floyd_all_shortest_paths() Tests
227// ============================================================================
228
230{
231 Ady_Mat<Graph, Dist> dist(g);
232 Ady_Mat<Graph, long> path(g);
233
234 floyd_all_shortest_paths(g, dist, path);
235
236 // Diagonal should be zero
237 const long n = g.get_num_nodes();
238 for (long i = 0; i < n; ++i)
239 EXPECT_DOUBLE_EQ(dist(i, i), 0.0) << "Diagonal at " << i << " should be 0";
240}
241
242TEST_F(FloydSimpleGraphTest, DirectEdgeDistance)
243{
244 Ady_Mat<Graph, Dist> dist(g);
245 Ady_Mat<Graph, long> path(g);
246
247 floyd_all_shortest_paths(g, dist, path);
248
249 // Get indices for n0 and n1
250 long idx0 = get_index(dist, n0);
251 long idx1 = get_index(dist, n1);
252
253 // Direct edge 0->1 has weight 1
254 EXPECT_DOUBLE_EQ(dist(idx0, idx1), 1.0);
255}
256
257TEST_F(FloydSimpleGraphTest, ShortestPathOverMultipleEdges)
258{
259 Ady_Mat<Graph, Dist> dist(g);
260 Ady_Mat<Graph, long> path(g);
261
262 floyd_all_shortest_paths(g, dist, path);
263
264 long idx0 = get_index(dist, n0);
265 long idx2 = get_index(dist, n2);
266
267 // 0->2: direct is 5, but 0->1->2 = 1+2 = 3
268 EXPECT_DOUBLE_EQ(dist(idx0, idx2), 3.0);
269}
270
271TEST_F(FloydSimpleGraphTest, ShortestPathToLastNode)
272{
273 Ady_Mat<Graph, Dist> dist(g);
274 Ady_Mat<Graph, long> path(g);
275
276 floyd_all_shortest_paths(g, dist, path);
277
278 long idx0 = get_index(dist, n0);
279 long idx3 = get_index(dist, n3);
280
281 // 0->3: direct is 4, path 0->1->2->3 = 1+2+1 = 4 (same)
282 EXPECT_DOUBLE_EQ(dist(idx0, idx3), 4.0);
283}
284
285TEST_F(FloydSimpleGraphTest, UnreachableNodesHaveInfinity)
286{
287 Ady_Mat<Graph, Dist> dist(g);
288 Ady_Mat<Graph, long> path(g);
289
290 floyd_all_shortest_paths(g, dist, path);
291
292 long idx1 = get_index(dist, n1);
293 long idx0 = get_index(dist, n0);
294
295 // Node 0 is not reachable from node 1 (directed graph)
296 EXPECT_TRUE(isinf(dist(idx1, idx0)));
297}
298
299TEST_F(FloydIntGraphTest, SymmetricGraph)
300{
301 Ady_Mat<Graph, Dist> dist(g);
302 Ady_Mat<Graph, long> path(g);
303
304 floyd_all_shortest_paths(g, dist, path);
305
306 const long n = g.get_num_nodes();
307
308 // For this undirected-like graph, dist(i,j) == dist(j,i)
309 for (long i = 0; i < n; ++i)
310 for (long j = 0; j < n; ++j)
311 EXPECT_EQ(dist(i, j), dist(j, i))
312 << "Distance should be symmetric for i=" << i << ", j=" << j;
313}
314
316{
317 Ady_Mat<Graph, Dist> dist(g);
318 Ady_Mat<Graph, long> path(g);
319
320 floyd_all_shortest_paths(g, dist, path);
321
322 // Find indices - nodes[0] should be at some index
323 long idx0 = -1, idx3 = -1;
324 const long n = g.get_num_nodes();
325 for (long i = 0; i < n; ++i) {
326 if (dist(i)->get_info() == 0) idx0 = i;
327 if (dist(i)->get_info() == 3) idx3 = i;
328 }
329
330 // 0->3: best path is 0->1->3 = 2+4 = 6
331 EXPECT_EQ(dist(idx0, idx3), 6);
332}
333
334// ============================================================================
335// find_min_path() Tests
336// ============================================================================
337
338TEST_F(FloydSimpleGraphTest, PathReconstructionSameNode)
339{
340 Ady_Mat<Graph, Dist> dist(g);
341 Ady_Mat<Graph, long> path(g);
342
343 floyd_all_shortest_paths(g, dist, path);
344
345 Path<Graph> p(g);
346 long idx0 = get_index(dist, n0);
347
348 find_min_path(path, idx0, idx0, p);
349
350 // Path from node to itself should just contain the source
351 EXPECT_EQ(p.size(), 1u);
352}
353
354TEST_F(FloydSimpleGraphTest, PathReconstructionDirectEdge)
355{
356 Ady_Mat<Graph, Dist> dist(g);
357 Ady_Mat<Graph, long> path(g);
358
359 floyd_all_shortest_paths(g, dist, path);
360
361 Path<Graph> p(g);
362 long idx0 = get_index(dist, n0);
363 long idx1 = get_index(dist, n1);
364
365 find_min_path(path, idx0, idx1, p);
366
367 // Path 0->1 should have 2 nodes
368 EXPECT_EQ(p.size(), 2u);
369}
370
371TEST_F(FloydSimpleGraphTest, PathReconstructionMultipleEdges)
372{
373 Ady_Mat<Graph, Dist> dist(g);
374 Ady_Mat<Graph, long> path(g);
375
376 floyd_all_shortest_paths(g, dist, path);
377
378 Path<Graph> p(g);
379 long idx0 = get_index(dist, n0);
380 long idx2 = get_index(dist, n2);
381
382 find_min_path(path, idx0, idx2, p);
383
384 // Shortest path 0->2 goes through 1, so path is 0->1->2 (3 nodes)
385 EXPECT_EQ(p.size(), 3u);
386}
387
388// ============================================================================
389// floyd_all_shortest_paths_latex() Tests
390// ============================================================================
391
392// Formatters for LaTeX output - must match mat_latex.H signatures
393
395template <class Mat>
397{
398 string operator()(Mat& mat, int i) const
399 {
400 return to_string(mat(static_cast<long>(i))->get_info());
401 }
402};
403
405template <class Mat>
407{
408 string operator()(Mat& mat, int i, int j) const
409 {
410 long val = mat(static_cast<long>(i), static_cast<long>(j));
411 return to_string(val);
412 }
413};
414
416template <class Mat>
418{
419 string operator()(Mat& mat, int i, int j) const
420 {
421 auto val = mat(static_cast<long>(i), static_cast<long>(j));
422 if (isinf(static_cast<double>(val)))
423 return "\\infty";
424 return to_string(static_cast<int>(val));
425 }
426};
427
428TEST_F(FloydIntGraphTest, LatexOutputContainsBeginFigure)
429{
430 Ady_Mat<Graph, Dist> dist(g);
431 Ady_Mat<Graph, long> path(g);
432
433 // Create temp file
434 string filename = latex_temp_filename();
435 ofstream output(filename);
436
439 (g, dist, path, output);
440
441 output.close();
442
443 // Read back and check
444 ifstream input(filename);
445 stringstream ss;
446 ss << input.rdbuf();
447 string content = ss.str();
448
449 EXPECT_NE(content.find("\\begin{figure}"), string::npos);
450 EXPECT_NE(content.find("\\end{figure}"), string::npos);
451}
452
453TEST_F(FloydIntGraphTest, LatexOutputContainsMatrices)
454{
455 Ady_Mat<Graph, Dist> dist(g);
456 Ady_Mat<Graph, long> path(g);
457
458 string filename = latex_temp_filename();
459 ofstream output(filename);
460
463 (g, dist, path, output);
464
465 output.close();
466
467 ifstream input(filename);
468 stringstream ss;
469 ss << input.rdbuf();
470 string content = ss.str();
471
472 // Should contain D_0, P_0, D_1, P_1, etc.
473 EXPECT_NE(content.find("D_0"), string::npos);
474 EXPECT_NE(content.find("P_0"), string::npos);
475 EXPECT_NE(content.find("D_1"), string::npos);
476 EXPECT_NE(content.find("P_1"), string::npos);
477}
478
479TEST_F(FloydIntGraphTest, LatexOutputHasCorrectNumberOfIterations)
480{
481 Ady_Mat<Graph, Dist> dist(g);
482 Ady_Mat<Graph, long> path(g);
483
484 string filename = latex_temp_filename();
485 ofstream output(filename);
486
489 (g, dist, path, output);
490
491 output.close();
492
493 ifstream input(filename);
494 stringstream ss;
495 ss << input.rdbuf();
496 string content = ss.str();
497
498 // For n=4 nodes, we should have D_0 through D_4 (5 matrices)
499 // Actually D_0 initial, then D_1 through D_n
500 const long n = g.get_num_nodes();
501 for (long i = 0; i <= n; ++i) {
502 string dmat = "D_" + to_string(i);
503 EXPECT_NE(content.find(dmat), string::npos) << "Missing " << dmat;
504 }
505}
506
507// ============================================================================
508// Edge Cases
509// ============================================================================
510
511TEST(SingleNodeTest, FloydOnSingleNode)
512{
514
515 Graph g;
516 g.insert_node(0);
517
518 Ady_Mat<Graph, int> dist(g);
519 Ady_Mat<Graph, long> path(g);
520
521 floyd_all_shortest_paths(g, dist, path);
522
523 // Single node: distance to itself is 0
524 EXPECT_EQ(dist(0L, 0L), 0);
525}
526
527TEST(TwoNodeTest, FloydOnTwoNodes)
528{
530
531 Graph g;
532 auto* n0 = g.insert_node(0);
533 auto* n1 = g.insert_node(1);
534 g.insert_arc(n0, n1, IntDistanceArc(5));
535
536 Ady_Mat<Graph, int> dist(g);
537 Ady_Mat<Graph, long> path(g);
538
539 floyd_all_shortest_paths(g, dist, path);
540
541 // Find indices for nodes
542 long idx0 = -1, idx1 = -1;
543 for (long i = 0; i < 2; ++i) {
544 if (dist(i)->get_info() == 0) idx0 = i;
545 if (dist(i)->get_info() == 1) idx1 = i;
546 }
547
548 EXPECT_EQ(dist(idx0, idx0), 0);
549 EXPECT_EQ(dist(idx1, idx1), 0);
550 EXPECT_EQ(dist(idx0, idx1), 5);
551 EXPECT_EQ(dist(idx1, idx0), IntDistanceArc::Max_Distance); // Not reachable
552}
553
554TEST(DisconnectedGraphTest, FloydOnDisconnectedGraph)
555{
557
558 Graph g;
559 auto* n0 = g.insert_node(0);
560 auto* n1 = g.insert_node(1);
561 auto* n2 = g.insert_node(2);
562 auto* n3 = g.insert_node(3);
563
564 // Two disconnected components: {0,1} and {2,3}
565 g.insert_arc(n0, n1, IntDistanceArc(1));
566 g.insert_arc(n1, n0, IntDistanceArc(1));
567 g.insert_arc(n2, n3, IntDistanceArc(2));
568 g.insert_arc(n3, n2, IntDistanceArc(2));
569
570 Ady_Mat<Graph, int> dist(g);
571 Ady_Mat<Graph, long> path(g);
572
573 floyd_all_shortest_paths(g, dist, path);
574
575 // Map node info -> matrix index (Ady_Mat sorts nodes by pointer value)
576 vector<long> idx(4, -1);
577 for (long i = 0; i < 4; ++i)
578 idx[dist(i)->get_info()] = i;
579
580 // Within component 1
581 EXPECT_EQ(dist(idx[0], idx[1]), 1);
582 EXPECT_EQ(dist(idx[1], idx[0]), 1);
583
584 // Within component 2
585 EXPECT_EQ(dist(idx[2], idx[3]), 2);
586 EXPECT_EQ(dist(idx[3], idx[2]), 2);
587
588 // Between components (unreachable)
589 EXPECT_EQ(dist(idx[0], idx[2]), IntDistanceArc::Max_Distance);
590 EXPECT_EQ(dist(idx[1], idx[3]), IntDistanceArc::Max_Distance);
591}
592
593TEST(DisconnectedGraphTest, UnreachableStaysInfinityWithNegativeEdges)
594{
596
597 Graph g;
598 auto* n0 = g.insert_node(0);
599 auto* n1 = g.insert_node(1);
600 auto* n2 = g.insert_node(2);
601 auto* n3 = g.insert_node(3);
602
603 // Component 1: negative edge but no negative cycle
604 g.insert_arc(n0, n1, IntDistanceArc(-5));
605 g.insert_arc(n1, n0, IntDistanceArc(6));
606
607 // Component 2: separate disconnected component
608 g.insert_arc(n2, n3, IntDistanceArc(2));
609 g.insert_arc(n3, n2, IntDistanceArc(2));
610
611 Ady_Mat<Graph, int> dist(g);
612 Ady_Mat<Graph, long> path(g);
613
614 floyd_all_shortest_paths(g, dist, path);
615
616 // Map node info -> matrix index
617 vector<long> idx(4, -1);
618 for (long i = 0; i < 4; ++i)
619 idx[dist(i)->get_info()] = i;
620
621 // Within component 1
622 EXPECT_EQ(dist(idx[0], idx[1]), -5);
623 EXPECT_EQ(dist(idx[1], idx[0]), 6);
624
625 // Between components (unreachable) must remain infinity sentinel even with negative weights
626 EXPECT_EQ(dist(idx[0], idx[2]), IntDistanceArc::Max_Distance);
627 EXPECT_EQ(dist(idx[1], idx[3]), IntDistanceArc::Max_Distance);
628 EXPECT_EQ(dist(idx[2], idx[0]), IntDistanceArc::Max_Distance);
629 EXPECT_EQ(dist(idx[3], idx[1]), IntDistanceArc::Max_Distance);
630}
631
632TEST(CompleteGraphTest, FloydOnCompleteGraph)
633{
635
636 const int N = 5;
637 Graph g;
638 vector<Graph::Node*> nodes;
639
640 for (int i = 0; i < N; ++i)
641 nodes.push_back(g.insert_node(i));
642
643 // Complete graph with all edges having weight 1
644 for (int i = 0; i < N; ++i)
645 for (int j = 0; j < N; ++j)
646 if (i != j)
647 g.insert_arc(nodes[i], nodes[j], IntDistanceArc(1));
648
649 Ady_Mat<Graph, int> dist(g);
650 Ady_Mat<Graph, long> path(g);
651
652 floyd_all_shortest_paths(g, dist, path);
653
654 // In complete graph with unit weights, all distances should be 0 or 1
655 for (long i = 0; i < N; ++i) {
656 for (long j = 0; j < N; ++j) {
657 if (i == j)
658 EXPECT_EQ(dist(i, j), 0);
659 else
660 EXPECT_EQ(dist(i, j), 1);
661 }
662 }
663}
664
665// ============================================================================
666// Custom Compare and Plus Tests
667// ============================================================================
668
669// Max-plus semiring: find widest paths (max of min edge weights)
671{
672 bool operator()(int a, int b) const { return a > b; }
673};
674
676{
677 int operator()(int a, int b) const { return min(a, b); }
678};
679
680TEST(CustomSemiringTest, MaxMinSemiring)
681{
683
684 Graph g;
685 auto* n0 = g.insert_node(0);
686 auto* n1 = g.insert_node(1);
687 auto* n2 = g.insert_node(2);
688
689 // Path 0->2 direct: capacity 2
690 // Path 0->1->2: min(5, 3) = 3 (better!)
691 g.insert_arc(n0, n1, IntDistanceArc(5));
692 g.insert_arc(n1, n2, IntDistanceArc(3));
693 g.insert_arc(n0, n2, IntDistanceArc(2));
694
695 Ady_Mat<Graph, int> cap(g);
696 Ady_Mat<Graph, long> path(g);
697
698 // Note: This would need a different initialization for max-min
699 // This test just verifies custom functors compile and run
700 floyd_all_shortest_paths<Graph, MaxCompare, MinPlus>(g, cap, path);
701
702 // The result depends on initialization which assumes min-plus
703 // So we just verify it runs without crashing
704 SUCCEED();
705}
706
707// ============================================================================
708// Stress Test
709// ============================================================================
710
711TEST(StressTest, FloydOnLargerGraph)
712{
714
715 const int N = 20;
716 Graph g;
717 vector<Graph::Node*> nodes;
718
719 for (int i = 0; i < N; ++i)
720 nodes.push_back(g.insert_node(i));
721
722 // Create a chain with some shortcuts
723 for (int i = 0; i < N - 1; ++i)
724 g.insert_arc(nodes[i], nodes[i + 1], IntDistanceArc(1));
725
726 // Add some shortcuts (longer, so they won't be used)
727 for (int i = 0; i < N - 2; i += 2)
728 g.insert_arc(nodes[i], nodes[i + 2], IntDistanceArc(3)); // Longer than 2 hops
729
730 Ady_Mat<Graph, int> dist(g);
731 Ady_Mat<Graph, long> path(g);
732
733 floyd_all_shortest_paths(g, dist, path);
734
735 // Build index mapping from node info to matrix index
736 vector<long> idx(N, -1);
737 for (long m = 0; m < N; ++m) {
738 int info = dist(m)->get_info();
739 idx[info] = m;
740 }
741
742 // Check that chain distances are correct using proper indices
743 for (int i = 0; i < N; ++i)
744 for (int j = i; j < N; ++j)
745 EXPECT_EQ(dist(idx[i], idx[j]), j - i) << "Distance from " << i << " to " << j;
746}
747
748// ============================================================================
749// Matrix Properties Tests
750// ============================================================================
751
752TEST_F(FloydIntGraphTest, PathMatrixPointsToNextHop)
753{
754 Ady_Mat<Graph, Dist> dist(g);
755 Ady_Mat<Graph, long> path(g);
756
757 floyd_all_shortest_paths(g, dist, path);
758
759 const long n = g.get_num_nodes();
760
761 // For reachable nodes, path(i,j) should point to next hop or j itself
762 for (long i = 0; i < n; ++i) {
763 for (long j = 0; j < n; ++j) {
764 if (i == j) {
765 EXPECT_EQ(path(i, j), j) << "Diagonal should point to self";
766 } else if (dist(i, j) < IntDistanceArc::Max_Distance) {
767 long next = path(i, j);
768 EXPECT_GE(next, 0L);
769 EXPECT_LT(next, n);
770 }
771 }
772 }
773}
774
775TEST_F(FloydSimpleGraphTest, DistanceMatrixTriangleInequality)
776{
777 Ady_Mat<Graph, Dist> dist(g);
778 Ady_Mat<Graph, long> path(g);
779
780 floyd_all_shortest_paths(g, dist, path);
781
782 const long n = g.get_num_nodes();
783
784 // Triangle inequality: dist(i,j) <= dist(i,k) + dist(k,j)
785 for (long i = 0; i < n; ++i) {
786 for (long j = 0; j < n; ++j) {
787 for (long k = 0; k < n; ++k) {
788 if (!isinf(dist(i, k)) && !isinf(dist(k, j))) {
789 EXPECT_LE(dist(i, j), dist(i, k) + dist(k, j))
790 << "Triangle inequality violated for i=" << i << ", j=" << j << ", k=" << k;
791 }
792 }
793 }
794 }
795}
796
797// ============================================================================
798// Initialize_Dist Tests (implicitly tested via floyd_all_shortest_paths)
799// ============================================================================
800
801TEST_F(FloydIntGraphTest, InitializationSetsEdgeWeightsCorrectly)
802{
803 Ady_Mat<Graph, Dist> dist(g);
804 Ady_Mat<Graph, long> path(g);
805
806 // Run Floyd-Warshall which internally uses Initialize_Dist
807 floyd_all_shortest_paths(g, dist, path);
808
809 // After running, we should have valid distances
810 const long n = g.get_num_nodes();
811
812 // Check diagonal is zero (set by initialization)
813 for (long i = 0; i < n; ++i)
814 EXPECT_EQ(dist(i, i), 0);
815
816 // Check that at least some edges have finite weights
817 bool found_finite = false;
818 for (long i = 0; i < n; ++i)
819 for (long j = 0; j < n; ++j)
820 if (i != j && dist(i, j) < IntDistanceArc::Max_Distance)
821 found_finite = true;
822
823 EXPECT_TRUE(found_finite);
824}
825
826// ============================================================================
827// Negative Weights (Note: Floyd-Warshall handles them, but not negative cycles)
828// ============================================================================
829
830TEST(NegativeWeightsTest, FloydWithNegativeWeights)
831{
832 // Use double to allow negative values
834
835 Graph g;
836 auto* n0 = g.insert_node(0);
837 auto* n1 = g.insert_node(1);
838 auto* n2 = g.insert_node(2);
839
840 // 0 --1--> 1 ---(-3)---> 2
841 // 0 --2--> 2 (direct, but longer than 0->1->2 = 1 + (-3) = -2)
842 g.insert_arc(n0, n1, DistanceArc(1.0));
843 g.insert_arc(n1, n2, DistanceArc(-3.0)); // Negative weight
844 g.insert_arc(n0, n2, DistanceArc(2.0));
845
847 Ady_Mat<Graph, long> path(g);
848
849 floyd_all_shortest_paths(g, dist, path);
850
851 // Find indices
852 long idx0 = -1, idx2 = -1;
853 for (long i = 0; i < 3; ++i) {
854 if (dist(i)->get_info() == 0) idx0 = i;
855 if (dist(i)->get_info() == 2) idx2 = i;
856 }
857
858 // Shortest 0->2 should be -2 (through 1)
859 EXPECT_DOUBLE_EQ(dist(idx0, idx2), -2.0);
860}
861
862// ============================================================================
863// Large Dense Graph Test
864// ============================================================================
865
866TEST(DenseGraphTest, FloydOnDenseGraph)
867{
869
870 const int N = 10;
871 Graph g;
872 vector<Graph::Node*> nodes;
873
874 for (int i = 0; i < N; ++i)
875 nodes.push_back(g.insert_node(i));
876
877 // Dense graph: edge from i to j with weight (i+j+1) mod N + 1
878 for (int i = 0; i < N; ++i)
879 for (int j = 0; j < N; ++j)
880 if (i != j)
881 g.insert_arc(nodes[i], nodes[j], IntDistanceArc((i + j + 1) % N + 1));
882
883 Ady_Mat<Graph, int> dist(g);
884 Ady_Mat<Graph, long> path(g);
885
886 floyd_all_shortest_paths(g, dist, path);
887
888 // Verify diagonal is zero
889 for (long i = 0; i < N; ++i)
890 EXPECT_EQ(dist(i, i), 0);
891
892 // Verify all pairs are reachable
893 for (long i = 0; i < N; ++i)
894 for (long j = 0; j < N; ++j)
895 EXPECT_LT(dist(i, j), IntDistanceArc::Max_Distance)
896 << "Should be reachable from " << i << " to " << j;
897}
898
899// ============================================================================
900// Parallel arcs, loops and mat_path.H
901// ============================================================================
902
903namespace
904{
906 template <class GT>
907 int path_cost(Path<GT> & p)
908 {
909 int cost = 0;
910 for (typename Path<GT>::Iterator it(p); it.has_current_arc(); it.next_ne())
911 cost += it.get_current_arc_ne()->get_info().get_distance();
912 return cost;
913 }
914
916 template <class Mat>
917 long index_of(Mat & m, int info)
918 {
919 for (long i = 0; i < static_cast<long>(m.get_num_nodes()); ++i)
920 if (m(i)->get_info() == info)
921 return i;
922 return -1;
923 }
924
926 string parallel_arcs_tex_name()
927 {
928 const auto *info = UnitTest::GetInstance()->current_test_info();
929#if defined(_WIN32)
930 const long long pid = _getpid();
931#else
932 const long long pid = getpid();
933#endif
934 string base = string("floyd_parallel_") + info->test_suite_name() + "_" +
935 info->name() + "_" + to_string(pid) + ".tex";
936 for (auto &ch : base)
937 if (ch == '/' or ch == '\\' or ch == ' ')
938 ch = '_';
939 return (std::filesystem::temp_directory_path() / base).string();
940 }
941
947 template <class GT>
948 void build_parallel_arcs(GT & g, bool heavier_first)
949 {
950 auto *n0 = g.insert_node(0);
951 auto *n1 = g.insert_node(1);
952 auto *n2 = g.insert_node(2);
953 auto insert_light = [&] ()
954 {
955 if (g.is_digraph())
956 g.insert_arc(n0, n1, IntDistanceArc(1));
957 else
958 g.insert_arc(n1, n0, IntDistanceArc(1));
959 };
960 if (not heavier_first)
961 insert_light();
962 g.insert_arc(n0, n1, IntDistanceArc(5));
963 if (heavier_first)
964 insert_light();
965 g.insert_arc(n1, n2, IntDistanceArc(1));
966 g.insert_arc(n0, n2, IntDistanceArc(3));
967 }
968} // namespace
969
970template <class GT>
971class ParallelArcsTest : public Test {};
972
974 Types<List_Digraph<Graph_Node<int>, Graph_Arc<IntDistanceArc>>,
980
982
983TYPED_TEST(ParallelArcsTest, TheLightestArcCounts)
984{
985 using GT = TypeParam;
986 for (const bool heavier_first : {true, false})
987 {
988 GT g;
989 build_parallel_arcs(g, heavier_first);
990 Ady_Mat<GT, int> dist(g);
991 Ady_Mat<GT, long> path(g);
992
993 floyd_all_shortest_paths(g, dist, path);
994
995 const long i0 = index_of(dist, 0), i1 = index_of(dist, 1);
996 const long i2 = index_of(dist, 2);
997 EXPECT_EQ(dist(i0, i1), 1) << "heavier first: " << heavier_first;
998 EXPECT_EQ(dist(i0, i2), 2) << "heavier first: " << heavier_first;
999 EXPECT_EQ(path(i0, i2), i1);
1000 EXPECT_EQ(dist(i1, i0),
1002
1003 // The paths take the light arc, and cost their distances
1004 Path<GT> p(g);
1005 find_min_path(path, i0, i1, p);
1006 EXPECT_EQ(p.size(), 2u);
1007 EXPECT_EQ(path_cost(p), 1);
1008
1009 Path<GT> q(g);
1010 find_min_path(path, dist(i0), dist(i2), q);
1011 EXPECT_EQ(q.size(), 3u);
1012 EXPECT_EQ(path_cost(q), 2);
1013 }
1014}
1015
1016TYPED_TEST(ParallelArcsTest, TheLatexVariantCountsTheSameArcs)
1017{
1018 using GT = TypeParam;
1019 for (const bool heavier_first : {true, false})
1020 {
1021 GT g;
1022 build_parallel_arcs(g, heavier_first);
1023 Ady_Mat<GT, int> dist(g);
1024 Ady_Mat<GT, long> path(g);
1025 floyd_all_shortest_paths(g, dist, path);
1026
1027 Ady_Mat<GT, int> latex_dist(g);
1028 Ady_Mat<GT, long> latex_path(g);
1029 const string filename = parallel_arcs_tex_name();
1030 {
1031 ofstream output(filename);
1034 (g, latex_dist, latex_path, output);
1035 }
1036 std::filesystem::remove(filename);
1037
1038 for (long i = 0; i < 3; ++i)
1039 for (long j = 0; j < 3; ++j)
1040 {
1041 EXPECT_EQ(latex_dist(i, j), dist(i, j)) << i << ", " << j;
1042 EXPECT_EQ(latex_path(i, j), path(i, j)) << i << ", " << j;
1043 }
1044 EXPECT_EQ(latex_dist(index_of(dist, 0), index_of(dist, 1)), 1);
1045 }
1046}
1047
1048TYPED_TEST(ParallelArcsTest, InitializeDistTakesTheLightestArc)
1049{
1050 using GT = TypeParam;
1051 using Dist_Mat = Ady_Mat<GT, int>;
1052 for (const bool heavier_first : {true, false})
1053 {
1054 GT g;
1055 build_parallel_arcs(g, heavier_first);
1056 Dist_Mat dist(g);
1057 Ady_Mat<GT, long> path(g);
1058
1059 dist.template operate_all_arcs_matrix<Initialize_Dist<Dist_Mat>>(&path);
1060
1061 const long i0 = index_of(dist, 0), i1 = index_of(dist, 1);
1062 const long i2 = index_of(dist, 2);
1063 for (long i = 0; i < 3; ++i)
1064 {
1065 EXPECT_EQ(dist(i, i), 0);
1066 EXPECT_EQ(path(i, i), i);
1067 }
1068 EXPECT_EQ(dist(i0, i1), 1);
1069 EXPECT_EQ(path(i0, i1), i1);
1070 EXPECT_EQ(dist(i0, i2), 3); // the arc, before any relaxation
1071 EXPECT_EQ(dist(i1, i0),
1073 }
1074}
1075
1077{
1078 using GT = TypeParam;
1079 GT g;
1080 auto *n0 = g.insert_node(0);
1081 auto *n1 = g.insert_node(1);
1082 g.insert_arc(n0, n0, IntDistanceArc(3));
1083 g.insert_arc(n0, n1, IntDistanceArc(2));
1084 g.insert_arc(n1, n1, IntDistanceArc(7));
1085 Ady_Mat<GT, int> dist(g);
1086 Ady_Mat<GT, long> path(g);
1087
1088 floyd_all_shortest_paths(g, dist, path);
1089
1090 const long i0 = index_of(dist, 0), i1 = index_of(dist, 1);
1091 EXPECT_EQ(dist(i0, i0), 0);
1092 EXPECT_EQ(dist(i1, i1), 0);
1093 EXPECT_EQ(path(i0, i0), i0);
1094 EXPECT_EQ(path(i1, i1), i1);
1095 EXPECT_EQ(dist(i0, i1), 2);
1096
1097 Path<GT> p(g);
1098 find_min_path(path, i0, i1, p);
1099 EXPECT_EQ(p.size(), 2u);
1100 EXPECT_EQ(path_cost(p), 2);
1101}
1102
1103TEST(MatPathTest, FindMinPathThrowsWithoutAnArc)
1104{
1106 Graph g;
1107 auto *n0 = g.insert_node(0);
1108 auto *n1 = g.insert_node(1);
1109 g.insert_arc(n1, n0, IntDistanceArc(1));
1110 Ady_Mat<Graph, long> path(g);
1111 const long i0 = index_of(path, 0), i1 = index_of(path, 1);
1112 path(i0, i1) = i1; // no arc goes from 0 to 1
1113
1114 Path<Graph> p(g);
1115 EXPECT_THROW(find_min_path(path, i0, i1, p), std::invalid_argument);
1116}
1117
1118TEST(MatPathTest, FindMinPathWithArcsWithoutDistances)
1119{
1120 // The arcs hold an int, without get_distance(): the path takes the
1121 // first arc between two nodes
1123 Graph g;
1124 auto *n0 = g.insert_node(0);
1125 auto *n1 = g.insert_node(1);
1126 auto *n2 = g.insert_node(2);
1127 g.insert_arc(n0, n1, 10);
1128 g.insert_arc(n1, n2, 20);
1129 Ady_Mat<Graph, long> path(g);
1130 const long i0 = index_of(path, 0), i1 = index_of(path, 1);
1131 const long i2 = index_of(path, 2);
1132 path(i0, i2) = i1;
1133 path(i1, i2) = i2;
1134
1135 Path<Graph> p(g);
1136 find_min_path(path, i0, i2, p);
1137 ASSERT_EQ(p.size(), 3u);
1138 EXPECT_EQ(p.get_first_node(), n0);
1139 EXPECT_EQ(p.get_last_node(), n2);
1140
1141 // The functor gives the same paths, by indices and by nodes
1143 Path<Graph> q(g), r(g);
1144 finder(path, i0, i2, q);
1145 finder(path, n0, n2, r);
1146 EXPECT_EQ(q.size(), 3u);
1147 EXPECT_EQ(r.size(), 3u);
1148}
1149
1150TEST(MatPathTest, FindMinPathTakesTheLightestByItsCompare)
1151{
1152 // With std::greater<>, the lightest arc is the heaviest one
1154 using Mat = Ady_Mat<Graph, long>;
1155 Graph g;
1156 auto *n0 = g.insert_node(0);
1157 auto *n1 = g.insert_node(1);
1158 g.insert_arc(n0, n1, IntDistanceArc(1));
1159 g.insert_arc(n0, n1, IntDistanceArc(5));
1160 g.insert_arc(n0, n1, IntDistanceArc(3));
1161 Mat path(g);
1162 const long i0 = index_of(path, 0), i1 = index_of(path, 1);
1163 path(i0, i1) = i1;
1164
1165 Path<Graph> by_less(g), by_greater(g), by_nodes(g), by_finder(g);
1166 find_min_path(path, i0, i1, by_less);
1167 find_min_path<Mat, std::greater<>>(path, i0, i1, by_greater);
1168 find_min_path<Mat, std::greater<>>(path, n0, n1, by_nodes);
1169 Find_Min_Path<Mat, std::greater<>>()(path, i0, i1, by_finder);
1170
1171 EXPECT_EQ(path_cost(by_less), 1);
1172 EXPECT_EQ(path_cost(by_greater), 5);
1173 EXPECT_EQ(path_cost(by_nodes), 5);
1174 EXPECT_EQ(path_cost(by_finder), 5);
1175}
List_Graph< Node, Arc > Graph
List_Graph< Graph_Node< Node_Info >, Graph_Arc< Arc_Info > > GT
Auxiliary adjacency matrix with custom entry type.
size_t get_num_nodes() const noexcept
Get number of nodes (matrix dimension)
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
Functor wrapper for find_min_path.
Definition mat_path.H:256
Arc for graphs implemented with simple adjacency lists.
Definition tpl_sgraph.H:197
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
Graph class implemented with singly-linked adjacency lists.
Definition tpl_sgraph.H:274
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Iterator on nodes and arcs of a path.
Definition tpl_graph.H:4395
bool has_current_arc() const noexcept
Return true if iterator has current arc.
Definition tpl_graph.H:4506
Path on a graph.
Definition tpl_graph.H:3832
size_t size() const noexcept
Return the path length in nodes.
Definition tpl_graph.H:3987
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
Test fixture with integer weights.
string latex_temp_filename() const
static long long process_id() noexcept
vector< Node * > nodes
IntDistanceArc::Distance_Type Dist
void SetUp() override
Test fixture with a simple weighted graph.
long get_index(Ady_Mat< Graph, Dist > &mat, Node *node) const
DistanceArc::Distance_Type Dist
bool is_digraph() const noexcept
Return true if the graph this is directed.
Definition graph-dry.H:937
#define TEST(name)
#define N
Definition fib.C:294
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_min_function > > min(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4189
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
void floyd_all_shortest_paths_latex(GT &g, Ady_Mat< GT, typename GT::Arc_Type::Distance_Type > &dist, Ady_Mat< GT, long > &path, std::ofstream &output)
Floyd-Warshall algorithm with LaTeX step-by-step output.
void floyd_all_shortest_paths(GT &g, Ady_Mat< GT, typename GT::Arc_Type::Distance_Type > &dist, Ady_Mat< GT, long > &path)
Compute all-pairs shortest paths using Floyd-Warshall algorithm.
void find_min_path(Mat &p, long src_idx, long tgt_idx, Path< typename Mat::Graph_Type > &path)
Build a minimum path from Floyd-Warshall path matrix using indices.
Definition mat_path.H:191
Floyd-Warshall algorithm with LaTeX output generation.
TYPED_TEST_SUITE(ParallelArcsTest, ParallelArcsGraphs)
TYPED_TEST(ParallelArcsTest, TheLightestArcCounts)
TEST_F(FloydSimpleGraphTest, DiagonalIsZero)
Types< List_Digraph< Graph_Node< int >, Graph_Arc< IntDistanceArc > >, List_Graph< Graph_Node< int >, Graph_Arc< IntDistanceArc > >, List_SDigraph< Graph_Snode< int >, Graph_Sarc< IntDistanceArc > >, List_SGraph< Graph_Snode< int >, Graph_Sarc< IntDistanceArc > >, Array_Digraph< Graph_Anode< int >, Graph_Aarc< IntDistanceArc > >, Array_Graph< Graph_Anode< int >, Graph_Aarc< IntDistanceArc > > > ParallelArcsGraphs
Path reconstruction from Floyd-Warshall path matrices.
Main namespace for Aleph-w library functions.
std::string to_string(const time_t t, const std::string &format)
Format a time_t value into a string using format.
Definition ah-date.H:140
void next()
Advance all underlying iterators (bounds-checked).
Definition ah-zip.H:236
STL namespace.
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Arc info type with required Distance_Type and constants.
Distance_Type get_distance() const
Distance_Type distance
static constexpr Distance_Type Zero_Distance
DistanceArc(Distance_Type d)
static constexpr Distance_Type Max_Distance
Integer distance arc type.
Distance_Type get_distance() const
Distance_Type distance
IntDistanceArc(Distance_Type d)
static constexpr Distance_Type Zero_Distance
static constexpr Distance_Type Max_Distance
bool operator()(int a, int b) const
int operator()(int a, int b) const
Distance formatter: takes matrix, i, j indices, returns formatted entry.
string operator()(Mat &mat, int i, int j) const
Index formatter: takes matrix and index, returns string.
string operator()(Mat &mat, int i) const
Path formatter: takes matrix, i, j indices, returns formatted entry.
string operator()(Mat &mat, int i, int j) const
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Dnode< int > Test
Definition testDnode.C:42
static int * k
Gsl_Compatible_Rng r
Array-based graph implementation.
Generic graph and digraph implementations.
Adjacency matrix representations for graphs.
Simple graph implementation with adjacency lists.
ofstream output
Definition writeHeap.C:215