Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
astar_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 <tpl_graph.H>
47#include <AStar.H>
48#include <Dijkstra.H>
49#include <tpl_graph_utils.H>
50#include <random>
51#include <cmath>
52#include <functional>
53#include <stdexcept>
54#include <vector>
55
56using namespace Aleph;
57
58// ==================== Heap Type Tags ====================
59
61{
62 template <class G, class D, class A>
64};
65
67{
68 template <class G, class D, class A>
70};
71
72// ==================== Type definitions ====================
73
74// Simple weighted graph
75struct SimpleNode : public Graph_Node<int>
76{
77 using Graph_Node<int>::Graph_Node;
78};
79
80struct SimpleArc : public Graph_Arc<double>
81{
82 using Graph_Arc<double>::Graph_Arc;
83};
84
86
87// Grid-based node with coordinates
88struct GridNode : public Graph_Node<int>
89{
90 int x = 0;
91 int y = 0;
92
93 GridNode() = default;
94 GridNode(int id) : Graph_Node<int>(id), x(0), y(0) {}
95 GridNode(int id, int _x, int _y) : Graph_Node<int>(id), x(_x), y(_y) {}
96};
97
98struct GridArc : public Graph_Arc<double>
99{
100 using Graph_Arc<double>::Graph_Arc;
101};
102
104
105// Distance accessor for double weights
107{
108 using Distance_Type = double;
109
111 {
112 return arc->get_info();
113 }
114
116 {
117 return arc->get_info();
118 }
119
120 static void set_zero(SimpleGraph::Arc* arc)
121 {
122 arc->get_info() = 0.0;
123 }
124};
125
126// Euclidean heuristic for GridGraph
128{
129 using Distance_Type = double;
130
132 {
133 double dx = from->x - to->x;
134 double dy = from->y - to->y;
135 return std::sqrt(dx*dx + dy*dy);
136 }
137};
138
139// Manhattan heuristic for GridGraph
141{
142 using Distance_Type = double;
143
145 {
146 return std::abs(from->x - to->x) + std::abs(from->y - to->y);
147 }
148};
149
150// ==================== Test Fixtures ====================
151
152class AStarBasicTest : public ::testing::Test
153{
154protected:
156 std::vector<SimpleGraph::Node*> nodes;
157
158 void SetUp() override
159 {
160 // Create a simple graph:
161 // 1
162 // 0 ----> 1
163 // | |
164 // 4 | | 2
165 // v v
166 // 3 ----> 2
167 // 1
168 for (int i = 0; i < 4; ++i)
169 nodes.push_back(g.insert_node(i));
170
171 g.insert_arc(nodes[0], nodes[1], 1.0);
172 g.insert_arc(nodes[1], nodes[2], 2.0);
173 g.insert_arc(nodes[0], nodes[3], 4.0);
174 g.insert_arc(nodes[3], nodes[2], 1.0);
175 }
176};
177
178class AStarGridTest : public ::testing::Test
179{
180protected:
182 std::vector<GridGraph::Node*> nodes;
183 static constexpr int GRID_SIZE = 5;
184
185 void SetUp() override
186 {
187 // Create a 5x5 grid graph
188 nodes.resize(GRID_SIZE * GRID_SIZE);
189
190 for (int y = 0; y < GRID_SIZE; ++y)
191 for (int x = 0; x < GRID_SIZE; ++x)
192 {
193 int idx = y * GRID_SIZE + x;
194 GridNode node(idx, x, y); // Stack-allocated, no leak
195 nodes[idx] = g.insert_node(node.get_info());
196 nodes[idx]->x = x;
197 nodes[idx]->y = y;
198 }
199
200 // Connect adjacent cells (4-connected grid)
201 for (int y = 0; y < GRID_SIZE; ++y)
202 for (int x = 0; x < GRID_SIZE; ++x)
203 {
204 int idx = y * GRID_SIZE + x;
205
206 // Right neighbor
207 if (x + 1 < GRID_SIZE)
208 {
209 int right = y * GRID_SIZE + (x + 1);
210 g.insert_arc(nodes[idx], nodes[right], 1.0);
211 g.insert_arc(nodes[right], nodes[idx], 1.0);
212 }
213
214 // Down neighbor
215 if (y + 1 < GRID_SIZE)
216 {
217 int down = (y + 1) * GRID_SIZE + x;
218 g.insert_arc(nodes[idx], nodes[down], 1.0);
219 g.insert_arc(nodes[down], nodes[idx], 1.0);
220 }
221 }
222 }
223
225 {
226 return nodes[y * GRID_SIZE + x];
227 }
228};
229
230// ==================== Tests ====================
231
232// Test basic path finding with zero heuristic (should match Dijkstra)
233TEST_F(AStarBasicTest, ZeroHeuristicMatchesDijkstra)
234{
235 Path<SimpleGraph> astar_path(g);
236 Path<SimpleGraph> dijkstra_path(g);
237
240
241 auto astar_cost = astar.find_path(g, nodes[0], nodes[2], astar_path);
242 auto dijkstra_cost = dijkstra.find_min_path(g, nodes[0], nodes[2], dijkstra_path);
243
244 EXPECT_DOUBLE_EQ(astar_cost, dijkstra_cost);
245 EXPECT_EQ(astar_path.size(), dijkstra_path.size());
246}
247
248// Test finding shortest path
249TEST_F(AStarBasicTest, FindsShortestPath)
250{
251 Path<SimpleGraph> path(g);
253
254 auto cost = astar.find_path(g, nodes[0], nodes[2], path);
255
256 // Shortest path: 0 -> 1 -> 2 with cost 3
257 EXPECT_DOUBLE_EQ(cost, 3.0);
258 EXPECT_EQ(path.size(), 3);
259}
260
261// Test paint_path version
262TEST_F(AStarBasicTest, PaintPathWorks)
263{
265
266 bool found = astar.paint_path(g, nodes[0], nodes[2]);
267 EXPECT_TRUE(found);
268 EXPECT_TRUE(astar.is_painted());
269
270 Path<SimpleGraph> path(g);
271 auto cost = astar.get_min_path(nodes[2], path);
272 EXPECT_DOUBLE_EQ(cost, 3.0);
273}
274
275// Test compute_path (tree building version)
276TEST_F(AStarBasicTest, ComputePathBuildsTree)
277{
278 SimpleGraph tree;
280
281 auto end_tree_node = astar.compute_path(g, nodes[0], nodes[2], tree);
282
283 EXPECT_NE(end_tree_node, nullptr);
284 EXPECT_GE(tree.get_num_nodes(), 2u);
285}
286
287// Test no path exists
288TEST_F(AStarBasicTest, NoPathReturnsMax)
289{
290 // Add isolated node
291 auto isolated = g.insert_node(99);
292
293 Path<SimpleGraph> path(g);
295
296 auto cost = astar.find_path(g, nodes[0], isolated, path);
297
298 EXPECT_EQ(cost, std::numeric_limits<double>::max());
299 EXPECT_TRUE(path.is_empty());
300}
301
302// Test start equals end
303TEST_F(AStarBasicTest, StartEqualsEnd)
304{
305 Path<SimpleGraph> path(g);
307
308 // When start == end, paint_path should find it immediately
309 bool found = astar.paint_path(g, nodes[0], nodes[0]);
310 EXPECT_TRUE(found);
311}
312
313// Test grid with Euclidean heuristic
314TEST_F(AStarGridTest, EuclideanHeuristicFindsShortest)
315{
316 Path<GridGraph> path(g);
318
319 auto start = get_node(0, 0);
320 auto end = get_node(GRID_SIZE-1, GRID_SIZE-1);
321
322 auto cost = astar.find_path(g, start, end, path);
323
324 // Manhattan distance in 4-connected grid
325 double expected = (GRID_SIZE-1) + (GRID_SIZE-1);
326 EXPECT_DOUBLE_EQ(cost, expected);
327}
328
329// Test grid with Manhattan heuristic
330TEST_F(AStarGridTest, ManhattanHeuristicFindsShortest)
331{
332 Path<GridGraph> path(g);
334
335 auto start = get_node(0, 0);
336 auto end = get_node(GRID_SIZE-1, GRID_SIZE-1);
337
338 auto cost = astar.find_path(g, start, end, path);
339
340 double expected = (GRID_SIZE-1) + (GRID_SIZE-1);
341 EXPECT_DOUBLE_EQ(cost, expected);
342}
343
344// Test that A* with good heuristic explores fewer nodes than Dijkstra
345TEST_F(AStarGridTest, GoodHeuristicReducesExploration)
346{
347 // This is a qualitative test - A* should find the path
348 Path<GridGraph> path(g);
350
351 auto start = get_node(0, 0);
352 auto end = get_node(4, 4);
353
354 auto cost = astar.find_path(g, start, end, path);
355
356 EXPECT_FALSE(path.is_empty());
357 EXPECT_EQ(cost, 8.0); // Manhattan distance in grid
358}
359
360// Test operator() interface
361TEST_F(AStarBasicTest, OperatorInterface)
362{
363 Path<SimpleGraph> path(g);
365
366 auto cost = astar(g, nodes[0], nodes[2], path);
367
368 EXPECT_DOUBLE_EQ(cost, 3.0);
369}
370
371// Test single node graph
372TEST(AStarEdgeCases, SingleNodeGraph)
373{
374 SimpleGraph g;
375 auto node = g.insert_node(0);
376
377 Path<SimpleGraph> path(g);
379
380 bool found = astar.paint_path(g, node, node);
381 EXPECT_TRUE(found);
382}
383
384// Test null parameters throw
385TEST(AStarEdgeCases, NullParametersThrow)
386{
387 SimpleGraph g;
388 auto node = g.insert_node(0);
389
390 Path<SimpleGraph> path(g);
392
393 EXPECT_THROW(astar.find_path(g, nullptr, node, path), std::domain_error);
394 EXPECT_THROW(astar.find_path(g, node, nullptr, path), std::domain_error);
395}
396
397// Test empty graph throws
398TEST(AStarEdgeCases, EmptyGraphThrows)
399{
400 SimpleGraph empty_g;
401 SimpleGraph g;
402 auto node = g.insert_node(0);
403
404 Path<SimpleGraph> path(empty_g);
406
407 EXPECT_THROW(astar.find_path(empty_g, node, node, path), std::domain_error);
408}
409
410// Test comparison: A* vs Dijkstra on random graph
411TEST(AStarComparison, RandomGraphMatchesDijkstra)
412{
413 SimpleGraph g;
414 std::vector<SimpleGraph::Node*> nodes;
415 std::mt19937 rng(42);
416 std::uniform_real_distribution<double> weight_dist(0.1, 10.0);
417
418 // Create 20 nodes
419 for (int i = 0; i < 20; ++i)
420 nodes.push_back(g.insert_node(i));
421
422 // Create random edges
423 for (size_t i = 0; i < nodes.size(); ++i)
424 for (size_t j = i + 1; j < nodes.size(); ++j)
425 if (rng() % 3 == 0)
426 {
427 double w = weight_dist(rng);
428 g.insert_arc(nodes[i], nodes[j], w);
429 g.insert_arc(nodes[j], nodes[i], w);
430 }
431
432 // Compare paths for multiple pairs
435
436 for (int i = 0; i < 5; ++i)
437 {
438 auto start = nodes[rng() % nodes.size()];
439 auto end = nodes[rng() % nodes.size()];
440
441 if (start == end)
442 continue;
443
444 Path<SimpleGraph> astar_path(g);
445 Path<SimpleGraph> dijkstra_path(g);
446
447 auto astar_cost = astar.find_path(g, start, end, astar_path);
448 auto dijkstra_cost = dijkstra.find_min_path(g, start, end, dijkstra_path);
449
450 // Costs should match (both should be optimal)
451 EXPECT_NEAR(astar_cost, dijkstra_cost, 1e-9)
452 << "Mismatch for start=" << start->get_info()
453 << " end=" << end->get_info();
454 }
455}
456
457// ==================== Tests for New Dijkstra-Compatible Methods ====================
458
459class AStarDijkstraModeTest : public ::testing::Test
460{
461protected:
463 std::vector<SimpleGraph::Node*> nodes;
464
465 void SetUp() override
466 {
467 // Create a larger graph for testing complete tree
468 // 1 2
469 // 0 ----> 1 ----> 2
470 // \ | ^
471 // \5 |3 |1
472 // \ v |
473 // --> 3 ------+
474 for (int i = 0; i < 4; ++i)
475 nodes.push_back(g.insert_node(i));
476
477 g.insert_arc(nodes[0], nodes[1], 1.0);
478 g.insert_arc(nodes[1], nodes[2], 2.0);
479 g.insert_arc(nodes[0], nodes[3], 5.0);
480 g.insert_arc(nodes[1], nodes[3], 3.0);
481 g.insert_arc(nodes[3], nodes[2], 1.0);
482 }
483};
484
485// Test compute_min_paths_tree (Dijkstra mode - complete tree)
486TEST_F(AStarDijkstraModeTest, ComputeMinPathsTreeBuildsCompleteTree)
487{
488 SimpleGraph tree;
490
491 auto root = astar.compute_min_paths_tree(g, nodes[0], tree);
492
493 ASSERT_NE(root, nullptr);
494 // Tree should have all reachable nodes
495 EXPECT_EQ(tree.get_num_nodes(), g.get_num_nodes());
496 // Tree should have n-1 arcs for n nodes (spanning tree)
497 EXPECT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
498}
499
500// Test paint_min_paths_tree (Dijkstra mode - complete)
501TEST_F(AStarDijkstraModeTest, PaintMinPathsTreePaintsAll)
502{
504
505 astar.paint_min_paths_tree(g, nodes[0]);
506
507 EXPECT_TRUE(astar.is_painted());
508 EXPECT_TRUE(astar.has_computation());
509 EXPECT_EQ(astar.get_start_node(), nodes[0]);
510
511 // All nodes should be reachable
512 for (auto node : nodes)
513 {
514 Path<SimpleGraph> path(g);
515 auto dist = astar.get_min_path(node, path);
516 EXPECT_LT(dist, std::numeric_limits<double>::max());
517 }
518}
519
520// Test find_min_path (Dijkstra mode - no heuristic)
521TEST_F(AStarDijkstraModeTest, FindMinPathMatchesDijkstra)
522{
525
526 Path<SimpleGraph> astar_path(g);
527 Path<SimpleGraph> dijkstra_path(g);
528
529 auto astar_cost = astar.find_min_path(g, nodes[0], nodes[2], astar_path);
530 auto dijkstra_cost = dijkstra.find_min_path(g, nodes[0], nodes[2], dijkstra_path);
531
532 EXPECT_DOUBLE_EQ(astar_cost, dijkstra_cost);
533 EXPECT_EQ(astar_path.size(), dijkstra_path.size());
534}
535
536// Test compute_partial_min_paths_tree (without heuristic)
537TEST_F(AStarDijkstraModeTest, ComputePartialMinPathsTree)
538{
539 SimpleGraph tree;
541
542 astar.compute_partial_min_paths_tree(g, nodes[0], nodes[2], tree);
543
544 // Tree should contain at least the path nodes
545 EXPECT_GE(tree.get_num_nodes(), 2u);
546 // But may not contain all nodes (partial)
547 EXPECT_LE(tree.get_num_nodes(), g.get_num_nodes());
548}
549
550// Test paint_partial_min_paths_tree (without heuristic)
551TEST_F(AStarDijkstraModeTest, PaintPartialMinPathsTree)
552{
554
555 bool found = astar.paint_partial_min_paths_tree(g, nodes[0], nodes[2]);
556
557 EXPECT_TRUE(found);
558 EXPECT_TRUE(astar.is_painted());
559
560 // Can extract path
561 Path<SimpleGraph> path(g);
562 auto cost = astar.get_min_path(nodes[2], path);
563 EXPECT_EQ(cost, 3.0); // 0->1->2
564}
565
566// Test get_distance after painting
567TEST_F(AStarDijkstraModeTest, GetDistanceAfterPainting)
568{
570
571 astar.paint_min_paths_tree(g, nodes[0]);
572
573 // Distance to node 0 (start) should be 0
574 EXPECT_DOUBLE_EQ(astar.get_distance(nodes[0]), 0.0);
575
576 // Distance to node 1 should be 1
577 EXPECT_DOUBLE_EQ(astar.get_distance(nodes[1]), 1.0);
578
579 // Distance to node 2 should be 3 (0->1->2)
580 EXPECT_DOUBLE_EQ(astar.get_distance(nodes[2]), 3.0);
581
582 // Distance to node 3 should be 4 (0->1->3)
583 EXPECT_DOUBLE_EQ(astar.get_distance(nodes[3]), 4.0);
584}
585
586// Test copy_painted_min_paths_tree
587TEST_F(AStarDijkstraModeTest, CopyPaintedMinPathsTree)
588{
590
591 astar.paint_min_paths_tree(g, nodes[0]);
592
593 SimpleGraph tree;
594 auto total_dist = astar.copy_painted_min_paths_tree(g, tree);
595 (void)total_dist; // May be 0 depending on Paint_Filt implementation
596
597 // Tree should have all nodes
598 EXPECT_EQ(tree.get_num_nodes(), g.get_num_nodes());
599 // Tree should have n-1 arcs
600 EXPECT_EQ(tree.get_num_arcs(), g.get_num_nodes() - 1);
601}
602
603// Test operator() for Dijkstra mode (tree version)
604TEST_F(AStarDijkstraModeTest, OperatorTreeVersion)
605{
606 SimpleGraph tree;
608
609 astar(g, nodes[0], tree);
610
611 EXPECT_EQ(tree.get_num_nodes(), g.get_num_nodes());
612}
613
614// Test get_distance throws if not painted
615TEST(AStarErrorCases, GetDistanceThrowsIfNotPainted)
616{
617 SimpleGraph g;
618 auto node = g.insert_node(0);
619
621
622 EXPECT_THROW(astar.get_distance(node), std::domain_error);
623}
624
625// Test copy_painted throws if not painted
626TEST(AStarErrorCases, CopyPaintedThrowsIfNotPainted)
627{
628 SimpleGraph g;
629 g.insert_node(0);
630
631 SimpleGraph tree;
633
634 EXPECT_THROW(astar.copy_painted_min_paths_tree(g, tree), std::domain_error);
635}
636
637// Compare A* Dijkstra mode trees with actual Dijkstra trees
638TEST_F(AStarDijkstraModeTest, TreesMatchDijkstra)
639{
640 SimpleGraph astar_tree, dijkstra_tree;
641
644
645 astar.compute_min_paths_tree(g, nodes[0], astar_tree);
646 dijkstra.compute_min_paths_tree(g, nodes[0], dijkstra_tree);
647
648 // Same number of nodes and arcs
649 EXPECT_EQ(astar_tree.get_num_nodes(), dijkstra_tree.get_num_nodes());
650 EXPECT_EQ(astar_tree.get_num_arcs(), dijkstra_tree.get_num_arcs());
651}
652
653// Test disconnected graph
654TEST(AStarDijkstraMode, DisconnectedGraph)
655{
656 SimpleGraph g;
657 auto n0 = g.insert_node(0);
658 auto n1 = g.insert_node(1);
659 (void)g.insert_node(2); // n2 is intentionally disconnected
660
661 g.insert_arc(n0, n1, 1.0);
662
663 SimpleGraph tree;
665
666 astar.compute_min_paths_tree(g, n0, tree);
667
668 // Tree should only contain connected component
669 EXPECT_EQ(tree.get_num_nodes(), 2u);
670}
671
672// Test state getters
674{
676
677 // Before computation
678 EXPECT_FALSE(astar.has_computation());
679 EXPECT_FALSE(astar.is_painted());
680 EXPECT_EQ(astar.get_start_node(), nullptr);
681 EXPECT_EQ(astar.get_graph(), nullptr);
682
683 astar.paint_min_paths_tree(g, nodes[0]);
684
685 // After computation
686 EXPECT_TRUE(astar.has_computation());
687 EXPECT_TRUE(astar.is_painted());
688 EXPECT_EQ(astar.get_start_node(), nodes[0]);
689 EXPECT_EQ(astar.get_graph(), &g);
690}
691
692// ==================== Typed Tests for Both Heap Types ====================
693
694template <typename HeapTag>
695class AStarHeapTest : public ::testing::Test
696{
697protected:
699 std::vector<SimpleGraph::Node*> nodes;
700
701 void SetUp() override
702 {
703 for (int i = 0; i < 5; ++i)
704 nodes.push_back(g.insert_node(i));
705
706 // Create graph: 0 -> 1 -> 2 -> 3 -> 4
707 // \---------^
708 g.insert_arc(nodes[0], nodes[1], 1.0);
709 g.insert_arc(nodes[1], nodes[2], 2.0);
710 g.insert_arc(nodes[2], nodes[3], 3.0);
711 g.insert_arc(nodes[3], nodes[4], 4.0);
712 g.insert_arc(nodes[0], nodes[2], 10.0); // Long path
713 }
714};
715
716using HeapTypes = ::testing::Types<BinHeapTag, FibHeapTag>;
718
719// Test A* with both heap types - find_path (with heuristic)
720TYPED_TEST(AStarHeapTest, FindPathWithHeuristic)
721{
725 TypeParam::template Heap>;
726 AStar astar;
727 Path<SimpleGraph> path(this->g);
728
729 auto cost = astar.find_path(this->g, this->nodes[0], this->nodes[4], path);
730
731 EXPECT_EQ(cost, 10.0); // 1+2+3+4
732 EXPECT_FALSE(path.is_empty());
733}
734
735// Test A* with both heap types - compute_min_paths_tree (Dijkstra mode)
736TYPED_TEST(AStarHeapTest, ComputeMinPathsTree)
737{
741 TypeParam::template Heap>;
742 AStar astar;
743 SimpleGraph tree;
744
745 auto root = astar.compute_min_paths_tree(this->g, this->nodes[0], tree);
746
747 EXPECT_NE(root, nullptr);
748 EXPECT_EQ(tree.get_num_nodes(), 5u);
749 EXPECT_EQ(tree.get_num_arcs(), 4u);
750}
751
752// Test A* with both heap types - paint and get_distance
753TYPED_TEST(AStarHeapTest, PaintAndGetDistance)
754{
758 TypeParam::template Heap>;
759 AStar astar;
760
761 astar.paint_min_paths_tree(this->g, this->nodes[0]);
762
763 EXPECT_EQ(astar.get_distance(this->nodes[0]), 0.0);
764 EXPECT_EQ(astar.get_distance(this->nodes[1]), 1.0);
765 EXPECT_EQ(astar.get_distance(this->nodes[2]), 3.0); // 1+2
766 EXPECT_EQ(astar.get_distance(this->nodes[3]), 6.0); // 1+2+3
767 EXPECT_EQ(astar.get_distance(this->nodes[4]), 10.0); // 1+2+3+4
768}
769
770// Test A* vs Dijkstra with both heap types
771TYPED_TEST(AStarHeapTest, MatchesDijkstra)
772{
776 TypeParam::template Heap>;
779 TypeParam::template Heap>;
780
781 AStar astar;
782 Dijkstra dijkstra;
783
784 Path<SimpleGraph> astar_path(this->g);
785 Path<SimpleGraph> dijkstra_path(this->g);
786
787 auto astar_cost = astar.find_min_path(this->g, this->nodes[0], this->nodes[4], astar_path);
788 auto dijkstra_cost = dijkstra.find_min_path(this->g, this->nodes[0], this->nodes[4], dijkstra_path);
789
790 EXPECT_DOUBLE_EQ(astar_cost, dijkstra_cost);
791 EXPECT_EQ(astar_path.size(), dijkstra_path.size());
792}
793
794// ==================== Additional Edge Case Tests ====================
795
796// Test with self-loop (arc from node to itself)
797TEST(AStarEdgeCaseTest, SelfLoop)
798{
799 SimpleGraph g;
800 auto n1 = g.insert_node(1);
801 auto n2 = g.insert_node(2);
802
803 g.insert_arc(n1, n2, 5.0);
804 g.insert_arc(n2, n2, 1.0); // Self-loop
805
807 AStar astar;
808 Path<SimpleGraph> path(g);
809
810 auto cost = astar.find_min_path(g, n1, n2, path);
811
812 EXPECT_DOUBLE_EQ(cost, 5.0);
813 EXPECT_EQ(path.size(), 2u);
814}
815
816// Test with multiple arcs between same nodes
817TEST(AStarEdgeCaseTest, MultipleArcsBetweenNodes)
818{
819 SimpleGraph g;
820 auto n1 = g.insert_node(1);
821 auto n2 = g.insert_node(2);
822
823 g.insert_arc(n1, n2, 10.0);
824 g.insert_arc(n1, n2, 5.0); // Better path
825 g.insert_arc(n1, n2, 15.0);
826
828 AStar astar;
829 Path<SimpleGraph> path(g);
830
831 auto cost = astar.find_min_path(g, n1, n2, path);
832
833 EXPECT_DOUBLE_EQ(cost, 5.0); // Should find shortest
834}
835
836// Test with all arcs having same weight
837TEST(AStarEdgeCaseTest, UniformWeights)
838{
839 SimpleGraph g;
840 std::vector<SimpleGraph::Node*> nodes;
841
842 for (int i = 0; i < 4; ++i)
843 nodes.push_back(g.insert_node(i));
844
845 // Create square graph with all edges weight 1.0
846 g.insert_arc(nodes[0], nodes[1], 1.0);
847 g.insert_arc(nodes[1], nodes[2], 1.0);
848 g.insert_arc(nodes[2], nodes[3], 1.0);
849 g.insert_arc(nodes[0], nodes[3], 1.0);
850
852 AStar astar;
853 Path<SimpleGraph> path(g);
854
855 auto cost = astar.find_min_path(g, nodes[0], nodes[3], path);
856
857 EXPECT_DOUBLE_EQ(cost, 1.0); // Direct path
858 EXPECT_EQ(path.size(), 2u);
859}
860
861// Test with very large weights (close to overflow)
862TEST(AStarEdgeCaseTest, LargeWeights)
863{
864 SimpleGraph g;
865 auto n1 = g.insert_node(1);
866 auto n2 = g.insert_node(2);
867 auto n3 = g.insert_node(3);
868
869 double large = 1e100;
870 g.insert_arc(n1, n2, large);
871 g.insert_arc(n2, n3, large);
872
874 AStar astar;
875 Path<SimpleGraph> path(g);
876
877 auto cost = astar.find_min_path(g, n1, n3, path);
878
879 EXPECT_GT(cost, large); // Should handle large values
880 EXPECT_FALSE(path.is_empty());
881}
882
883// Test reusability: multiple searches on same object
884TEST(AStarEdgeCaseTest, Reusability)
885{
886 SimpleGraph g;
887 std::vector<SimpleGraph::Node*> nodes;
888
889 for (int i = 0; i < 5; ++i)
890 nodes.push_back(g.insert_node(i));
891
892 g.insert_arc(nodes[0], nodes[1], 1.0);
893 g.insert_arc(nodes[1], nodes[2], 2.0);
894 g.insert_arc(nodes[2], nodes[3], 3.0);
895 g.insert_arc(nodes[3], nodes[4], 4.0);
896
898 AStar astar; // Single instance
899
900 // First search
901 {
902 Path<SimpleGraph> path1(g);
903 auto cost1 = astar.find_min_path(g, nodes[0], nodes[2], path1);
904 EXPECT_DOUBLE_EQ(cost1, 3.0);
905 }
906
907 // Second search (should reset state correctly)
908 {
909 Path<SimpleGraph> path2(g);
910 auto cost2 = astar.find_min_path(g, nodes[1], nodes[4], path2);
911 EXPECT_DOUBLE_EQ(cost2, 9.0);
912 }
913
914 // Third search with different graph structure
915 {
916 Path<SimpleGraph> path3(g);
917 auto cost3 = astar.find_min_path(g, nodes[0], nodes[4], path3);
918 EXPECT_DOUBLE_EQ(cost3, 10.0);
919 }
920}
921
922// Test with zero-weight arcs
923TEST(AStarEdgeCaseTest, ZeroWeightArcs)
924{
925 SimpleGraph g;
926 auto n1 = g.insert_node(1);
927 auto n2 = g.insert_node(2);
928 auto n3 = g.insert_node(3);
929
930 g.insert_arc(n1, n2, 0.0); // Zero weight
931 g.insert_arc(n2, n3, 5.0);
932
934 AStar astar;
935 Path<SimpleGraph> path(g);
936
937 auto cost = astar.find_min_path(g, n1, n3, path);
938
939 EXPECT_DOUBLE_EQ(cost, 5.0);
940 EXPECT_EQ(path.size(), 3u);
941}
942
943// Test with inadmissible heuristic (should still find a path, but may be suboptimal)
944TEST(AStarEdgeCaseTest, InadmissibleHeuristic)
945{
946 GridGraph g;
947 auto n1 = g.insert_node(1);
948 n1->x = 0; n1->y = 0;
949
950 auto n2 = g.insert_node(2);
951 n2->x = 1; n2->y = 0;
952
953 auto n3 = g.insert_node(3);
954 n3->x = 2; n3->y = 0;
955
956 g.insert_arc(n1, n2, 1.0);
957 g.insert_arc(n2, n3, 1.0);
958 g.insert_arc(n1, n3, 10.0); // Suboptimal direct path
959
960 // Inadmissible heuristic that overestimates
961 struct BadHeuristic
962 {
963 using Distance_Type = double;
964 Distance_Type operator()(GridGraph::Node* from, GridGraph::Node* to) const
965 {
966 double dx = from->x - to->x;
967 double dy = from->y - to->y;
968 return 100.0 * std::sqrt(dx*dx + dy*dy); // Massively overestimate
969 }
970 };
971
973 AStar astar;
974 Path<GridGraph> path(g);
975
976 auto cost = astar.find_path(g, n1, n3, path);
977
978 // With inadmissible heuristic, may get suboptimal result
979 // But should still find SOME path
980 EXPECT_GT(cost, 0.0);
981 EXPECT_FALSE(path.is_empty());
982}
983
984// ==================== Distance policies and exceptions ====================
985
987
988// The policy of the report on 7.0.0: the weight of an arc times a factor.
990{
991 using Distance_Type = int;
992
993 int factor = 1;
994
995 int operator()(IntGraph::Arc * a) const { return factor * a->get_info(); }
996};
997
998// Every method used a default-constructed distance instead of the one
999// given to the constructor, so a factor of 3 was ignored.
1000TEST(AStarPolicyTest, UsesTheDistanceItWasGiven)
1001{
1002 IntGraph g;
1003 auto a = g.insert_node(0);
1004 auto b = g.insert_node(1);
1005 auto c = g.insert_node(2);
1006 g.insert_arc(a, b, 3);
1007 g.insert_arc(b, c, 4);
1008 g.insert_arc(a, c, 20);
1009
1011 Path<IntGraph> path(g);
1012 IntGraph tree;
1013
1014 EXPECT_EQ(astar.find_path(g, a, c, path), 21);
1015 EXPECT_EQ(astar.find_min_path(g, a, c, path), 21);
1016
1017 ASSERT_TRUE(astar.paint_partial_path(g, a, c));
1018 EXPECT_EQ(astar.get_min_path(c, path), 21);
1019
1020 ASSERT_TRUE(astar.paint_partial_min_paths_tree(g, a, c));
1021 EXPECT_EQ(astar.get_min_path(c, path), 21);
1022
1023 astar.paint_min_paths_tree(g, a);
1024 EXPECT_EQ(astar.get_distance(c), 21);
1025 IntGraph painted;
1026 EXPECT_EQ(astar.copy_painted_min_paths_tree(g, painted), 21);
1027
1028 ASSERT_NE(astar.compute_partial_path(g, a, c, tree), nullptr);
1029 EXPECT_EQ(astar.get_min_path(tree, c, path), 21);
1030
1031 astar.compute_min_paths_tree(g, a, tree);
1032 EXPECT_EQ(astar.get_min_path(tree, c, path), 21);
1033
1034 astar.compute_partial_min_paths_tree(g, a, c, tree);
1035 EXPECT_EQ(astar.get_min_path(tree, c, path), 21);
1036}
1037
1039
1040// A heuristic that reads h(v) from an array, by the info of v.
1042{
1043 using Distance_Type = int;
1044
1045 const int * h = nullptr;
1046
1048 {
1049 return h[from->get_info()];
1050 }
1051};
1052
1053// A sum g + h beyond max() gave the arc the priority max(), the priority of
1054// s->a, whose g + h is max(): the heap could keep b->a, after which a->t did
1055// not fit, and the methods threw overflow_error, though s->a->t costs max().
1056// The heuristic is the distance to t, which does not overestimate.
1057TEST(AStarPolicyTest, FindsAPathOfMaxThroughAPriorityThatDoesNotFit)
1058{
1059 constexpr int M = std::numeric_limits<int>::max();
1060 IntDigraph g;
1061 auto s = g.insert_node(0);
1062 auto a = g.insert_node(1);
1063 auto b = g.insert_node(2);
1064 auto t = g.insert_node(3);
1065 g.insert_arc(s, b, 2);
1066 g.insert_arc(s, a, 1);
1067 g.insert_arc(b, a, 0);
1068 g.insert_arc(a, t, M - 1);
1069 const int h[] = {M, M - 1, M - 1, 0};
1070
1073 Path<IntDigraph> path(g);
1074 EXPECT_EQ(astar.find_path(g, s, t, path), M);
1075 EXPECT_EQ(path.size(), 3u);
1076
1077 ASSERT_TRUE(astar.paint_partial_path(g, s, t));
1078 EXPECT_EQ(astar.get_min_path(t, path), M);
1079
1080 IntDigraph tree;
1081 ASSERT_NE(astar.compute_partial_path(g, s, t, tree), nullptr);
1082 EXPECT_EQ(astar.get_min_path(tree, t, path), M);
1083}
1084
1085// The weight of an arc times a factor, with no default constructor.
1087{
1088 using Distance_Type = int;
1089
1091
1092 explicit Factor_Only_Distance(int f) noexcept : factor(f) {}
1093
1094 int operator()(IntGraph::Arc * a) const { return factor * a->get_info(); }
1095};
1096
1097// ArcHeap built its comparator by default, so such a distance did not
1098// compile with it.
1099TEST(AStarPolicyTest, TakesADistanceWithoutADefaultConstructor)
1100{
1101 IntGraph g;
1102 auto a = g.insert_node(0);
1103 auto b = g.insert_node(1);
1104 auto c = g.insert_node(2);
1105 g.insert_arc(a, b, 3);
1106 g.insert_arc(b, c, 4);
1107 g.insert_arc(a, c, 20);
1108
1110 Path<IntGraph> path(g);
1111 IntGraph tree;
1112
1113 EXPECT_EQ(astar.find_path(g, a, c, path), 21);
1114 EXPECT_EQ(astar.find_min_path(g, a, c, path), 21);
1115
1116 astar.paint_min_paths_tree(g, a);
1117 EXPECT_EQ(astar.get_distance(c), 21);
1118 IntGraph painted;
1119 EXPECT_EQ(astar.copy_painted_min_paths_tree(g, painted), 21);
1120
1121 ASSERT_NE(astar.compute_partial_path(g, a, c, tree), nullptr);
1122 EXPECT_EQ(astar.get_min_path(tree, c, path), 21);
1123
1124 astar.compute_min_paths_tree(g, a, tree);
1125 EXPECT_EQ(astar.get_min_path(tree, c, path), 21);
1126}
1127
1128// Counts the calls of a distance or a heuristic and makes one of them throw.
1130{
1131 long calls = 0;
1132 long fail_at = 0; // number of the call that throws; 0 for none
1133
1134 void count()
1135 {
1136 if (++calls == fail_at)
1137 throw std::runtime_error("policy failed");
1138 }
1139};
1140
1142{
1143 using Distance_Type = int;
1144
1146
1148 {
1149 if (failure != nullptr)
1150 failure->count();
1151 return a->get_info();
1152 }
1153};
1154
1156{
1157 using Distance_Type = int;
1158
1160
1162 {
1163 if (failure != nullptr)
1164 failure->count();
1165 return 0;
1166 }
1167};
1168
1169// The cookies were allocated at the start and freed at the end, but not
1170// when the algorithm threw: a distance or a heuristic that failed leaked
1171// them. Each call fails in turn; the same object, on the same graph, must
1172// then give the right costs. LeakSanitizer reports any cookie left.
1173TEST(AStarPolicyTest, DistanceOrHeuristicThatThrowsLeavesTheGraphReusable)
1174{
1175 // a 3 x 4 grid with weights from 1 to 9
1176 IntGraph g;
1177 std::vector<IntGraph::Node *> n;
1178 for (int i = 0; i < 12; ++i)
1179 n.push_back(g.insert_node(i));
1180 for (int r = 0; r < 3; ++r)
1181 for (int c = 0; c < 4; ++c)
1182 {
1183 const int i = 4 * r + c;
1184 if (c < 3)
1185 g.insert_arc(n[i], n[i + 1], 1 + (7 * i) % 9);
1186 if (r < 2)
1187 g.insert_arc(n[i], n[i + 4], 1 + (5 * i + 3) % 9);
1188 }
1189
1190 const auto start = n[0];
1191 const auto end = n[11];
1193 Path<IntGraph> expected_path(g);
1194 const int expected = dijkstra.find_min_path(g, start, end, expected_path);
1195 ASSERT_GT(expected, 0);
1196
1197 Call_Failure distance_failure;
1198 Call_Failure heuristic_failure;
1200 astar(Failing_Distance{&distance_failure},
1201 Failing_Heuristic{&heuristic_failure});
1202 IntGraph tree;
1203
1204 const std::vector<std::function<void()>> methods = {
1205 [&] {
1206 Path<IntGraph> path(g);
1207 EXPECT_EQ(astar.find_path(g, start, end, path), expected);
1208 },
1209 [&] {
1210 ASSERT_NE(astar.compute_partial_path(g, start, end, tree), nullptr);
1211 Path<IntGraph> path(g);
1212 EXPECT_EQ(astar.get_min_path(tree, end, path), expected);
1213 },
1214 [&] {
1215 Path<IntGraph> path(g);
1216 EXPECT_EQ(astar.find_min_path(g, start, end, path), expected);
1217 },
1218 [&] {
1219 astar.paint_min_paths_tree(g, start);
1220 EXPECT_EQ(astar.get_distance(end), expected);
1221 },
1222 [&] {
1223 astar.compute_min_paths_tree(g, start, tree);
1224 Path<IntGraph> path(g);
1225 EXPECT_EQ(astar.get_min_path(tree, end, path), expected);
1226 },
1227 [&] {
1228 astar.compute_partial_min_paths_tree(g, start, end, tree);
1229 Path<IntGraph> path(g);
1230 EXPECT_EQ(astar.get_min_path(tree, end, path), expected);
1231 }
1232 };
1233
1234 for (auto * failure : {&heuristic_failure, &distance_failure})
1235 for (size_t m = 0; m < methods.size(); ++m)
1236 {
1237 distance_failure = heuristic_failure = Call_Failure();
1238 methods[m]();
1239 const long calls = failure->calls;
1240 if (failure == &distance_failure)
1241 ASSERT_GT(calls, 0) << "method " << m;
1242
1243 for (long k = 1; k <= calls; ++k)
1244 {
1245 distance_failure = heuristic_failure = Call_Failure();
1246 failure->fail_at = k;
1247 EXPECT_THROW(methods[m](), std::runtime_error)
1248 << "method " << m << ", call " << k;
1249
1250 failure->fail_at = 0;
1251 methods[m]();
1252 }
1253 }
1254}
1255
1256int main(int argc, char **argv)
1257{
1258 ::testing::InitGoogleTest(&argc, argv);
1259 return RUN_ALL_TESTS();
1260}
A* shortest path algorithm.
Dijkstra's shortest path algorithm.
TYPED_TEST(AStarHeapTest, FindPathWithHeuristic)
List_Graph< SimpleNode, SimpleArc > SimpleGraph
Definition astar_test.cc:85
TEST_F(AStarBasicTest, ZeroHeuristicMatchesDijkstra)
::testing::Types< BinHeapTag, FibHeapTag > HeapTypes
TYPED_TEST_SUITE(AStarHeapTest, HeapTypes)
int main()
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
void SetUp() override
std::vector< SimpleGraph::Node * > nodes
SimpleGraph g
void SetUp() override
std::vector< SimpleGraph::Node * > nodes
std::vector< GridGraph::Node * > nodes
GridGraph::Node * get_node(int x, int y)
void SetUp() override
static constexpr int GRID_SIZE
GridGraph g
void SetUp() override
SimpleGraph g
std::vector< SimpleGraph::Node * > nodes
A* algorithm for finding the shortest path between two nodes.
Definition AStar.H:176
Distance::Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extracts a shortest path to end from a previously painted graph.
Distance::Distance_Type find_min_path(const GT &g, typename GT::Node *start, typename GT::Node *end, Path< GT > &min_path)
Computes shortest path by painting the graph (without heuristic).
Definition AStar.H:924
GT::Node * compute_min_paths_tree(const GT &g, typename GT::Node *start, GT &tree)
Computes the spanning tree of ALL shortest paths from the start node.
Definition AStar.H:556
GT::Node * compute_path(const GT &g, typename GT::Node *start, typename GT::Node *end, GT &tree)
Alias for compute_partial_path (backward compatibility).
Definition AStar.H:523
Distance::Distance_Type copy_painted_min_paths_tree(GT &g, GT &tree)
Extracts the painted shortest paths tree and puts it in tree.
bool is_painted() const noexcept
Check if the graph has been painted.
void compute_partial_min_paths_tree(const GT &g, typename GT::Node *start, typename GT::Node *end, GT &tree)
Computes the partial spanning tree from start to end (without a heuristic).
Definition AStar.H:643
bool has_computation() const noexcept
Check if a computation has been performed.
GT::Node * compute_partial_path(const GT &g, typename GT::Node *start, typename GT::Node *end, GT &tree)
Computes the shortest path from start to end using A*.
Definition AStar.H:280
GT * get_graph() const noexcept
Get the graph of the last computation.
Distance::Distance_Type get_distance(typename GT::Node *node)
Gets the accumulated distance to a node after painting.
bool paint_partial_min_paths_tree(const GT &g, typename GT::Node *start, typename GT::Node *end)
Paints on graph g the partial shortest paths tree (without heuristic).
Definition AStar.H:744
GT::Node * get_start_node() const noexcept
Get the start node of the last computation.
bool paint_path(const GT &g, typename GT::Node *start, typename GT::Node *end)
Alias for paint_partial_path (backward compatibility).
Definition AStar.H:530
Distance::Distance_Type find_path(const GT &g, typename GT::Node *start, typename GT::Node *end, Path< GT > &path)
Finds the shortest path from start to end using A*.
Definition AStar.H:505
void paint_min_paths_tree(const GT &g, typename GT::Node *start)
Paints on graph g the spanning tree of ALL shortest paths starting from start (without heuristic).
Definition AStar.H:844
Default distance accessor for arc weights.
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
typename BaseGraph::Node Node
Definition graph-dry.H:4380
Spanning tree calculation of all shortest paths from a given node according to Dijkstra's algorithm.
Definition Dijkstra.H:117
Distance::Distance_Type find_min_path(const GT &g, typename GT::Node *start, typename GT::Node *end, Path< GT > &min_path)
Computes the shortest path between start and end by painting the graph.
Definition Dijkstra.H:536
GT::Node * compute_min_paths_tree(const GT &g, typename GT::Node *start, GT &tree)
Computes the spanning tree of all shortest paths from the start node.
Definition Dijkstra.H:185
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
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
bool is_empty() const noexcept
Return true if the path is empty.
Definition tpl_graph.H:3993
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
NodeInfo & get_info() noexcept
Return a modifiable reference to the data contained in the node.
Definition graph-dry.H:753
constexpr size_t get_num_nodes() const noexcept
Return the total of nodes of graph.
Definition graph-dry.H:975
constexpr size_t get_num_arcs() const noexcept
Return the number of arcs of the graph.
Definition graph-dry.H:1064
constexpr size_t size() const noexcept
Returns the number of entries in the table.
Definition hashDry.H:954
#define TEST(name)
static mt19937 rng
__gmp_expr< T, __gmp_binary_expr< __gmp_expr< T, U >, unsigned long int, __gmp_root_function > > root(const __gmp_expr< T, U > &expr, unsigned long int l)
Definition gmpfrxx.h:4138
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
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
Node belonging to a graph implemented with a double linked adjacency list.
Definition tpl_graph.H:126
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Default heuristic for A* (zero heuristic, degrades to Dijkstra).
Definition AStar.H:79
const int * h
int operator()(IntDigraph::Node *from, IntDigraph::Node *) const
Distance_Type operator()(GridGraph::Arc *arc) const
Distance_Type operator()(SimpleGraph::Arc *arc) const
static void set_zero(SimpleGraph::Arc *arc)
double Distance_Type
int operator()(IntGraph::Arc *a) const
Factor_Only_Distance(int f) noexcept
Call_Failure * failure
int operator()(IntGraph::Arc *a) const
int operator()(IntGraph::Node *, IntGraph::Node *) const
Call_Failure * failure
Distance_Type operator()(GridGraph::Node *from, GridGraph::Node *to) const
Distance_Type operator()(GridGraph::Node *from, GridGraph::Node *to) const
GridNode(int id, int _x, int _y)
Definition astar_test.cc:95
GridNode()=default
GridNode(int id)
Definition astar_test.cc:94
int operator()(IntGraph::Arc *a) const
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.