Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
k_shortest_paths_test.cc
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
31
37# include <gtest/gtest.h>
38
39# include <algorithm>
40# include <chrono>
41# include <cstdlib>
42# include <functional>
43# include <limits>
44# include <random>
45# include <stdexcept>
46# include <string>
47# include <tuple>
48# include <utility>
49
50# include <K_Shortest_Paths.H>
51# include <tpl_array.H>
52# include <tpl_dynArray.H>
53# include <tpl_graph.H>
54# include <tpl_olhash.H>
55
56using namespace Aleph;
57
58namespace
59{
61 using Node = Graph::Node;
62 using Arc = Graph::Arc;
63 using Edge_Def = std::tuple<size_t, size_t, long long>;
64
65 struct Canonical_Path
66 {
67 long long cost = 0;
69
70 bool operator==(const Canonical_Path & other) const noexcept
71 {
72 if (cost != other.cost or nodes.size() != other.nodes.size())
73 return false;
74
75 for (size_t i = 0; i < nodes.size(); ++i)
76 if (nodes(i) != other.nodes(i))
77 return false;
78
79 return true;
80 }
81 };
82
83
84 bool same_node_sequence(const DynArray<int> & a, const DynArray<int> & b)
85 {
86 if (a.size() != b.size())
87 return false;
88
89 for (size_t i = 0; i < a.size(); ++i)
90 if (a(i) != b(i))
91 return false;
92
93 return true;
94 }
95
96
97 bool node_sequence_less(const DynArray<int> & a, const DynArray<int> & b)
98 {
99 const size_t min_size = std::min(a.size(), b.size());
100 for (size_t i = 0; i < min_size; ++i)
101 {
102 if (a(i) < b(i))
103 return true;
104 if (a(i) > b(i))
105 return false;
106 }
107
108 return a.size() < b.size();
109 }
110
111
112 bool canonical_less(const Canonical_Path & a, const Canonical_Path & b)
113 {
114 if (a.cost != b.cost)
115 return a.cost < b.cost;
116 return node_sequence_less(a.nodes, b.nodes);
117 }
118
119
120 void sort_canonical_paths(Array<Canonical_Path> & paths)
121 {
122 for (size_t i = 1; i < paths.size(); ++i)
123 {
124 Canonical_Path key = paths[i];
125 size_t j = i;
126 while (j > 0 and canonical_less(key, paths[j - 1]))
127 {
128 paths[j] = paths[j - 1];
129 --j;
130 }
131 paths[j] = key;
132 }
133 }
134
135
136 bool contains_canonical_path(const Array<Canonical_Path> & paths,
137 const Canonical_Path & needle)
138 {
139 for (size_t i = 0; i < paths.size(); ++i)
140 if (paths[i] == needle)
141 return true;
142 return false;
143 }
144
145
146 Array<Edge_Def> make_edges(std::initializer_list<Edge_Def> init)
147 {
148 Array<Edge_Def> edges;
149 edges.reserve(init.size());
150 for (const auto & e : init)
151 edges.append(e);
152 return edges;
153 }
154
155
156 struct Built_Graph
157 {
158 Graph g;
160 };
161
162
163 Built_Graph build_graph(const size_t n, const Array<Edge_Def> & edges)
164 {
165 Built_Graph built;
166 built.nodes.reserve(n);
167 for (size_t i = 0; i < n; ++i)
168 built.nodes.append(built.g.insert_node(static_cast<int>(i)));
169
170 for (auto it = edges.get_it(); it.has_curr(); it.next_ne())
171 {
172 const auto & [u, v, w] = it.get_curr();
173 if (u < n and v < n)
174 built.g.insert_arc(built.nodes[u], built.nodes[v], w);
175 }
176
177 return built;
178 }
179
180
181 DynArray<int> extract_node_ids(const Path<Graph> & path)
182 {
183 DynArray<int> ids;
184 for (Path<Graph>::Iterator it(path); it.has_current_node(); it.next_ne())
185 ids.append(it.get_current_node_ne()->get_info());
186 return ids;
187 }
188
189
190 bool is_simple_path(const Path<Graph> & path)
191 {
193 for (Path<Graph>::Iterator it(path); it.has_current_node(); it.next_ne())
194 {
195 Node * node = it.get_current_node_ne();
196 if (seen.contains(node))
197 return false;
198 seen.insert(node);
199 }
200 return true;
201 }
202
203
204 template <class Result_List>
205 Array<Canonical_Path> normalize_results(const Result_List & results)
206 {
208 for (auto it = results.get_it(); it.has_curr(); it.next_ne())
209 {
210 const auto & item = it.get_curr();
211 out.append(Canonical_Path{
212 item.total_cost,
213 extract_node_ids(item.path)});
214 }
215
216 sort_canonical_paths(out);
217 return out;
218 }
219
220
222 exact_k_shortest_simple_paths(Node * source,
223 Node * target,
224 const size_t k)
225 {
226 if (k == 0)
227 return Array<Canonical_Path>();
228
229 if (source == target)
230 {
231 Canonical_Path p;
232 p.cost = 0;
233 p.nodes.append(source->get_info());
235 out.append(p);
236 return out;
237 }
238
240 OLhashTable<Node *> visited;
241 DynArray<int> stack;
242
243 std::function<void(Node *, long long)> dfs =
244 [&](Node * u, const long long cost)
245 {
246 if (u == target)
247 {
248 Canonical_Path p;
249 p.cost = cost;
250 for (size_t i = 0; i < stack.size(); ++i)
251 p.nodes.append(stack(i));
252 all.append(p);
253 return;
254 }
255
256 for (Node_Arc_Iterator<Graph> it(u); it.has_curr(); it.next_ne())
257 {
258 Arc * arc = it.get_current_arc_ne();
259 Node * v = it.get_tgt_node();
260 if (visited.contains(v))
261 continue;
262
263 visited.insert(v);
264 stack.append(v->get_info());
265 dfs(v, cost + arc->get_info());
266 (void) stack.pop();
267 visited.remove(v);
268 }
269 };
270
271 visited.insert(source);
272 stack.append(source->get_info());
273 dfs(source, 0);
274
275 sort_canonical_paths(all);
276
277 if (all.size() > k)
278 while (all.size() > k)
279 (void) all.remove_last();
280 return all;
281 }
282
283
284 Array<Edge_Def> random_graph_edges(std::mt19937_64 & rng,
285 const size_t n)
286 {
287 std::bernoulli_distribution has_edge(0.36);
288 std::uniform_int_distribution<int> base_w(1, 40);
289
290 Array<Edge_Def> edges;
291 size_t edge_id = 0;
292 for (size_t u = 0; u < n; ++u)
293 for (size_t v = 0; v < n; ++v)
294 {
295 if (u == v or not has_edge(rng))
296 continue;
297 const long long w = static_cast<long long>(base_w(rng))
298 + static_cast<long long>(edge_id * 101);
299 edges.append(Edge_Def{u, v, w});
300 ++edge_id;
301 }
302 return edges;
303 }
304} // namespace
305
306
307TEST(KShortestPathsTest, YenKnownGraphProducesExpectedCosts)
308{
309 const auto edges = make_edges({
310 {0, 1, 1}, {0, 2, 1}, {1, 3, 1}, {2, 3, 1},
311 {1, 2, 1}, {2, 1, 1}, {0, 3, 5}
312 });
313 auto built = build_graph(4, edges);
314
315 const auto got = yen_k_shortest_paths<Graph>(
316 built.g, built.nodes[0], built.nodes[3], 5);
317 auto normalized = normalize_results(got);
318
319 ASSERT_EQ(normalized.size(), 5u);
320 EXPECT_EQ(normalized[0].cost, 2);
321 EXPECT_EQ(normalized[1].cost, 2);
322 EXPECT_EQ(normalized[2].cost, 3);
323 EXPECT_EQ(normalized[3].cost, 3);
324 EXPECT_EQ(normalized[4].cost, 5);
325}
326
327
328TEST(KShortestPathsTest, EppsteinApiMatchesYenOnKnownGraph)
329{
330 const auto edges = make_edges({
331 {0, 1, 1}, {0, 2, 1}, {1, 3, 1}, {2, 3, 1},
332 {1, 2, 2}, {0, 3, 7}
333 });
334 auto built = build_graph(4, edges);
335
336 const auto yen = normalize_results(
337 yen_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[3], 6));
338 const auto epp = normalize_results(
339 eppstein_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[3], 6));
340
341 ASSERT_GE(epp.size(), yen.size());
342
343 for (size_t i = 0; i < yen.size(); ++i)
344 {
345 EXPECT_TRUE(contains_canonical_path(epp, yen[i]));
346 }
347}
348
349
350TEST(KShortestPathsTest, EppsteinCanReturnCyclicAlternatives)
351{
352 const auto edges = make_edges({
353 {0, 1, 1}, {1, 2, 1}, {2, 3, 1},
354 {2, 4, 1}, {4, 2, 1}
355 });
356 auto built = build_graph(5, edges);
357
358 const auto yen = normalize_results(
359 yen_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[3], 4));
360 const auto epp = normalize_results(
361 eppstein_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[3], 4));
362
363 ASSERT_EQ(yen.size(), 1u);
364 ASSERT_EQ(epp.size(), 4u);
365
366 EXPECT_EQ(epp[0].cost, 3);
367 EXPECT_EQ(epp[1].cost, 5);
368 EXPECT_EQ(epp[2].cost, 7);
369 EXPECT_EQ(epp[3].cost, 9);
370
371 EXPECT_FALSE(same_node_sequence(epp[1].nodes, yen[0].nodes));
372}
373
374
375TEST(KShortestPathsTest, SourceEqualsTargetReturnsTrivialPath)
376{
377 const auto edges = make_edges({
378 {0, 1, 2}, {1, 2, 2}, {2, 0, 2}
379 });
380 auto built = build_graph(3, edges);
381
382 const auto got = yen_k_shortest_paths<Graph>(
383 built.g, built.nodes[1], built.nodes[1], 10);
384
385 ASSERT_EQ(got.size(), 1u);
386 const auto normalized = normalize_results(got);
387 ASSERT_EQ(normalized.size(), 1u);
388 EXPECT_EQ(normalized[0].cost, 0);
389 ASSERT_EQ(normalized[0].nodes.size(), 1u);
390 EXPECT_EQ(normalized[0].nodes(0), 1);
391}
392
393
394TEST(KShortestPathsTest, UnreachableReturnsEmpty)
395{
396 const auto edges = make_edges({
397 {0, 1, 1}, {1, 0, 1}, {2, 3, 1}
398 });
399 auto built = build_graph(4, edges);
400
401 const auto got = yen_k_shortest_paths<Graph>(
402 built.g, built.nodes[0], built.nodes[3], 4);
403 EXPECT_TRUE(got.is_empty());
404}
405
406
407TEST(KShortestPathsTest, NegativeWeightsThrowDomainError)
408{
409 const auto edges = make_edges({
410 {0, 1, 2}, {1, 2, -5}, {0, 2, 9}
411 });
412 auto built = build_graph(3, edges);
413
414 EXPECT_THROW(
415 (yen_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[2], 3)),
416 std::domain_error);
417 EXPECT_THROW(
418 (eppstein_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[2], 3)),
419 std::domain_error);
420}
421
422
423TEST(KShortestPathsTest, RandomSmallGraphsMatchExactOracle)
424{
425 std::mt19937_64 rng(0xBADC0FFEEULL);
426 std::uniform_int_distribution<int> n_dist(3, 8);
427
428 for (size_t trial = 0; trial < 80; ++trial)
429 {
430 const size_t n = static_cast<size_t>(n_dist(rng));
431 auto built = build_graph(n, random_graph_edges(rng, n));
432 Node * source = built.nodes[0];
433 Node * target = built.nodes[n - 1];
434 constexpr size_t K = 7;
435
436 const auto expected = exact_k_shortest_simple_paths(
437 source, target, K);
438
439 const auto yen = normalize_results(
440 yen_k_shortest_paths<Graph>(built.g, source, target, K));
441 const auto epp = normalize_results(
442 eppstein_k_shortest_paths<Graph>(built.g, source, target, K));
443
444 ASSERT_EQ(yen.size(), expected.size()) << "trial=" << trial;
445 ASSERT_GE(epp.size(), expected.size()) << "trial=" << trial;
446 ASSERT_LE(epp.size(), K) << "trial=" << trial;
447
448 for (size_t i = 0; i < expected.size(); ++i)
449 {
450 EXPECT_EQ(yen[i].cost, expected[i].cost)
451 << "trial=" << trial << ", i=" << i;
452 EXPECT_TRUE(same_node_sequence(yen[i].nodes, expected[i].nodes))
453 << "trial=" << trial << ", i=" << i;
454 }
455
456 if (expected.size() > 0)
457 EXPECT_EQ(epp[0].cost, expected[0].cost)
458 << "trial=" << trial;
459
460 for (size_t i = 1; i < epp.size(); ++i)
461 {
462 EXPECT_GE(epp[i].cost, epp[i - 1].cost)
463 << "trial=" << trial << ", i=" << i;
464 }
465 }
466}
467
468
469TEST(KShortestPathsTest, ReturnedPathsAreSimpleAndNonDecreasingCost)
470{
471 const auto edges = make_edges({
472 {0, 1, 1}, {0, 2, 4}, {1, 2, 1}, {1, 3, 2},
473 {2, 3, 1}, {2, 4, 3}, {3, 4, 1}
474 });
475 auto built = build_graph(5, edges);
476
477 const auto got = yen_k_shortest_paths<Graph>(
478 built.g, built.nodes[0], built.nodes[4], 10);
479
480 long long prev = std::numeric_limits<long long>::min();
481 for (auto it = got.get_it(); it.has_curr(); it.next_ne())
482 {
483 const auto & item = it.get_curr();
484 EXPECT_TRUE(is_simple_path(item.path));
485 EXPECT_GE(item.total_cost, prev);
486 prev = item.total_cost;
487 }
488}
489
490
491TEST(KShortestPathsTest, EppsteinResultsAreNonDecreasingCost)
492{
493 const auto edges = make_edges({
494 {0, 1, 1}, {1, 2, 1}, {2, 3, 1},
495 {2, 4, 1}, {4, 2, 1}
496 });
497 auto built = build_graph(5, edges);
498
499 const auto got = eppstein_k_shortest_paths<Graph>(
500 built.g, built.nodes[0], built.nodes[3], 8);
501
502 long long prev = std::numeric_limits<long long>::min();
503 for (auto it = got.get_it(); it.has_curr(); it.next_ne())
504 {
505 const auto & item = it.get_curr();
506 EXPECT_GE(item.total_cost, prev);
507 prev = item.total_cost;
508 }
509}
510
511
512TEST(KShortestPathsTest, SelfLoopAndParallelArcs)
513{
514 // Graph with:
515 // - Node 0 -> 1: Two parallel arcs with weights 10 and 20.
516 // - Node 1 -> 1: Self-loop with weight 5.
517 // - Node 1 -> 2: Arc with weight 5.
518 //
519 // Shortest paths from 0 to 2:
520 // 1. 0->1(cost=10)->2(cost=5) = 15
521 // 2. 0->1(cost=20)->2(cost=5) = 25
522 //
523 // The self-loop 1->1 should be ignored by Yen's (simple paths only).
524 // Eppstein's API is general (non-loopless), so a cheaper loopy path may
525 // appear before the second simple alternative.
526
527 const auto edges = make_edges({
528 {0, 1, 10}, // parallel arc 1
529 {0, 1, 20}, // parallel arc 2
530 {1, 1, 5}, // self-loop on spur node
531 {1, 2, 5}
532 });
533 auto built = build_graph(3, edges);
534
535 const size_t K = 2;
536 const auto yen_results = normalize_results(
537 yen_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[2], K));
538 const auto epp_results = normalize_results(
539 eppstein_k_shortest_paths<Graph>(built.g, built.nodes[0], built.nodes[2], K));
540
541 ASSERT_EQ(yen_results.size(), 2u);
542 ASSERT_EQ(epp_results.size(), 2u);
543
544 // Check path 1: Cost 15, nodes [0, 1, 2]
545 EXPECT_EQ(yen_results[0].cost, 15);
546 EXPECT_EQ(yen_results[0].nodes.size(), 3u);
547 EXPECT_EQ(yen_results[0].nodes(0), 0);
548 EXPECT_EQ(yen_results[0].nodes(1), 1);
549 EXPECT_EQ(yen_results[0].nodes(2), 2);
550
551 // Check path 2: Cost 25, nodes [0, 1, 2]
552 EXPECT_EQ(yen_results[1].cost, 25);
553 EXPECT_EQ(yen_results[1].nodes.size(), 3u);
554 EXPECT_EQ(yen_results[1].nodes(0), 0);
555 EXPECT_EQ(yen_results[1].nodes(1), 1);
556 EXPECT_EQ(yen_results[1].nodes(2), 2);
557
558 // Eppstein: first path matches Yen's best simple path.
559 EXPECT_EQ(epp_results[0], yen_results[0]);
560
561 // Eppstein can use the self-loop:
562 // 0->1(cost=10)->1(cost=5)->2(cost=5) = 20
563 EXPECT_EQ(epp_results[1].cost, 20);
564 EXPECT_EQ(epp_results[1].nodes.size(), 4u);
565 EXPECT_EQ(epp_results[1].nodes(0), 0);
566 EXPECT_EQ(epp_results[1].nodes(1), 1);
567 EXPECT_EQ(epp_results[1].nodes(2), 1);
568 EXPECT_EQ(epp_results[1].nodes(3), 2);
569}
570
571
572// Eppstein made the deviations of a walk also after the last one that was
573// asked, and threw when the cost of one did not fit: with a loop of max() at
574// the target, a query of one walk threw. A walk whose cost does not fit is
575// left out, and overflow_error comes only when one of the first k does not
576// fit.
577TEST(KShortestPathsTest, EppsteinLeavesOutTheWalksWhoseCostDoesNotFit)
578{
580 constexpr int M = std::numeric_limits<int>::max();
581
582 Int_Graph g;
583 auto * s = g.insert_node(0);
584 auto * t = g.insert_node(1);
585 g.insert_arc(s, t, 1);
586 g.insert_arc(t, t, M);
587
588 const auto one = eppstein_k_shortest_paths<Int_Graph>(g, s, t, 1);
589 ASSERT_EQ(one.size(), 1u);
590 EXPECT_EQ(one.get_first().total_cost, 1);
591 // The second walk, s->t->t, costs M + 1
592 EXPECT_THROW(eppstein_k_shortest_paths<Int_Graph>(g, s, t, 2), std::overflow_error);
593
594 // A second walk that fits comes before the one that does not
595 g.insert_arc(s, t, 5);
596 const auto two = eppstein_k_shortest_paths<Int_Graph>(g, s, t, 2);
597 ASSERT_EQ(two.size(), 2u);
598 EXPECT_EQ(two.get_first().total_cost, 1);
599 EXPECT_EQ(two.get_last().total_cost, 5);
600 EXPECT_THROW(eppstein_k_shortest_paths<Int_Graph>(g, s, t, 3), std::overflow_error);
601
602 // A deviation at the source whose cost does not fit
603 Int_Graph h;
604 auto * a = h.insert_node(0);
605 auto * b = h.insert_node(1);
606 auto * x = h.insert_node(2);
607 h.insert_arc(a, b, 1);
608 h.insert_arc(a, x, M);
609 h.insert_arc(x, b, 1);
610 EXPECT_EQ(eppstein_k_shortest_paths<Int_Graph>(h, a, b, 1).size(), 1u);
611 EXPECT_THROW(eppstein_k_shortest_paths<Int_Graph>(h, a, b, 2), std::overflow_error);
612}
613
614
615// max() marked a node that does not reach the target, and Yen took a
616// spur path of that cost for none: a path of exactly max() was not given.
617TEST(KShortestPathsTest, APathOfExactlyMaxIsGiven)
618{
620 constexpr int M = std::numeric_limits<int>::max();
621
622 Int_Graph g;
623 auto * a = g.insert_node(0);
624 auto * b = g.insert_node(1);
625 auto * c = g.insert_node(2);
626 g.insert_arc(a, b, M - 1);
627 g.insert_arc(b, c, 1);
628
629 for (bool by_yen : {true, false})
630 {
631 SCOPED_TRACE(by_yen ? "Yen" : "Eppstein");
632 const auto one = by_yen ? yen_k_shortest_paths<Int_Graph>(g, a, c, 2)
633 : eppstein_k_shortest_paths<Int_Graph>(g, a, c, 2);
634 ASSERT_EQ(one.size(), 1u);
635 EXPECT_EQ(one.get_first().total_cost, M);
636 }
637
638 // After a cheaper path
639 g.insert_arc(a, b, M / 2);
640 for (bool by_yen : {true, false})
641 {
642 SCOPED_TRACE(by_yen ? "Yen" : "Eppstein");
643 const auto two = by_yen ? yen_k_shortest_paths<Int_Graph>(g, a, c, 2)
644 : eppstein_k_shortest_paths<Int_Graph>(g, a, c, 2);
645 ASSERT_EQ(two.size(), 2u);
646 EXPECT_EQ(two.get_first().total_cost, M / 2 + 1);
647 EXPECT_EQ(two.get_last().total_cost, M);
648 }
649}
650
651// The search of Yen from each spur node is a Dijkstra, which threw when
652// the target was reached only beyond max(): the next path, from another
653// spur node, was lost.
654TEST(KShortestPathsTest, YenGoesOnPastASpurNodeBeyondMax)
655{
657 constexpr int M = std::numeric_limits<int>::max();
658
659 Int_Graph g;
660 auto * s = g.insert_node(0);
661 auto * a = g.insert_node(1);
662 auto * c = g.insert_node(2);
663 auto * d = g.insert_node(3);
664 auto * t = g.insert_node(4);
665 g.insert_arc(s, a, 1);
666 g.insert_arc(a, t, 1);
667 g.insert_arc(a, c, 1);
668 g.insert_arc(c, t, 1);
669 g.insert_arc(s, d, M - 1); // from s, without s->a, only beyond max()
670 g.insert_arc(d, t, M - 1);
671
672 const auto two = yen_k_shortest_paths<Int_Graph>(g, s, t, 2);
673 ASSERT_EQ(two.size(), 2u);
674 EXPECT_EQ(two.get_first().total_cost, 2);
675 EXPECT_EQ(two.get_last().total_cost, 3);
676 // The third path, s->d->t, costs 2 M - 2
677 EXPECT_THROW(yen_k_shortest_paths<Int_Graph>(g, s, t, 3), std::overflow_error);
678}
679
680// Eppstein chose the arc of its tree among the parallel arcs to the parent
681// by a checked sum, which threw on a heavy one.
682TEST(KShortestPathsTest, EppsteinTakesAHeavyParallelArcOfTheTree)
683{
685 using Int_Undigraph = List_Graph<Graph_Node<int>, Graph_Arc<int>>;
686 constexpr int M = std::numeric_limits<int>::max();
687
688 Int_Graph g;
689 auto * s = g.insert_node(0);
690 auto * a = g.insert_node(1);
691 auto * t = g.insert_node(2);
692 g.insert_arc(s, a, 1);
693 g.insert_arc(s, a, M); // M + d(a, t) does not fit
694 g.insert_arc(a, t, 1);
695 const auto walks = eppstein_k_shortest_paths<Int_Graph>(g, s, t, 1);
696 ASSERT_EQ(walks.size(), 1u);
697 EXPECT_EQ(walks.get_first().total_cost, 2);
698
699 Int_Undigraph u;
700 auto * us = u.insert_node(0);
701 auto * ua = u.insert_node(1);
702 auto * ut = u.insert_node(2);
703 u.insert_arc(us, ua, 1);
704 u.insert_arc(us, ua, M);
705 u.insert_arc(ua, ut, 1);
706 const auto uwalks = eppstein_k_shortest_paths<Int_Undigraph>(u, us, ut, 1);
707 ASSERT_EQ(uwalks.size(), 1u);
708 EXPECT_EQ(uwalks.get_first().total_cost, 2);
709}
710
711
712// The index of the suffixes of Eppstein, a painting of Dijkstra from the
713// target, threw when the distance to the target of a node did not fit,
714// though no walk that is asked goes through it. It leaves out such a node,
715// and a walk through it that is asked throws, as its cost does not fit.
716TEST(KShortestPathsTest, EppsteinLeavesOutOfItsIndexANodeBeyondMax)
717{
719 using Int_Undigraph = List_Graph<Graph_Node<int>, Graph_Arc<int>>;
720 constexpr int M = std::numeric_limits<int>::max();
721
722 // x reaches t only through y, at 2 M - 2, and no walk from s goes
723 // through x
724 Int_Graph g;
725 auto * s = g.insert_node(0);
726 auto * t = g.insert_node(1);
727 auto * x = g.insert_node(2);
728 auto * y = g.insert_node(3);
729 g.insert_arc(s, t, 1);
730 g.insert_arc(x, y, M - 1);
731 g.insert_arc(y, t, M - 1);
732
733 const auto walks = eppstein_k_shortest_paths<Int_Graph>(g, s, t, 2);
734 ASSERT_EQ(walks.size(), 1u);
735 EXPECT_EQ(walks.get_first().total_cost, 1);
736 const auto from_y = eppstein_k_shortest_paths<Int_Graph>(g, y, t, 1);
737 ASSERT_EQ(from_y.size(), 1u);
738 EXPECT_EQ(from_y.get_first().total_cost, M - 1);
739 // From x, the first walk does not fit
740 EXPECT_THROW(eppstein_k_shortest_paths<Int_Graph>(g, x, t, 1), std::overflow_error);
741
742 // The second walk, s->x->y->t, goes through x, and does not fit
743 g.insert_arc(s, x, 1);
744 const auto one = eppstein_k_shortest_paths<Int_Graph>(g, s, t, 1);
745 ASSERT_EQ(one.size(), 1u);
746 EXPECT_EQ(one.get_first().total_cost, 1);
747 EXPECT_THROW(eppstein_k_shortest_paths<Int_Graph>(g, s, t, 2), std::overflow_error);
748
749 // Not directed: the second walk is s-t-s-t, and s-t-y-t does not fit
750 Int_Undigraph u;
751 auto * us = u.insert_node(0);
752 auto * ut = u.insert_node(1);
753 auto * ux = u.insert_node(2);
754 auto * uy = u.insert_node(3);
755 u.insert_arc(us, ut, 1);
756 u.insert_arc(ux, uy, M - 1);
757 u.insert_arc(uy, ut, M - 1);
758 const auto uwalks = eppstein_k_shortest_paths<Int_Undigraph>(u, us, ut, 2);
759 ASSERT_EQ(uwalks.size(), 2u);
760 EXPECT_EQ(uwalks.get_first().total_cost, 1);
761 EXPECT_EQ(uwalks.get_last().total_cost, 3);
762 EXPECT_THROW(eppstein_k_shortest_paths<Int_Undigraph>(u, ux, ut, 1), std::overflow_error);
763}
764
765
766// The search of Yen from each spur node takes a target that it reaches
767// only beyond max() for no path, but an overflow_error that the distance or
768// the filter throws, at whatever call, passes on, as in Eppstein.
769TEST(KShortestPathsTest, AnOverflowErrorOfTheDistanceOrOfTheFilterPassesOn)
770{
772 using Arc = Int_Graph::Arc;
773 constexpr int M = std::numeric_limits<int>::max();
774
775 // As in YenGoesOnPastASpurNodeBeyondMax: from s, without s->a, the target
776 // is reached only beyond max()
777 Int_Graph g;
778 auto * s = g.insert_node(0);
779 auto * a = g.insert_node(1);
780 auto * c = g.insert_node(2);
781 auto * d = g.insert_node(3);
782 auto * t = g.insert_node(4);
783 g.insert_arc(s, a, 1);
784 g.insert_arc(a, t, 1);
785 g.insert_arc(a, c, 1);
786 g.insert_arc(c, t, 1);
787 g.insert_arc(s, d, M - 1);
788 g.insert_arc(d, t, M - 1);
789
790 // Each throws at its call number at; with at == 0, never
791 struct Distance
792 {
793 using Distance_Type = int;
794 size_t * calls;
795 size_t at;
796 int operator()(Arc * arc) const
797 {
798 if (++*calls == at)
799 throw std::overflow_error("thrown by the distance");
800 return arc->get_info();
801 }
802 };
803 struct Filter
804 {
805 size_t * calls;
806 size_t at;
807 bool operator()(Arc *) const
808 {
809 if (++*calls == at)
810 throw std::overflow_error("thrown by the filter");
811 return true;
812 }
813 };
814
815 size_t distance_calls = 0, filter_calls = 0;
816 for (bool by_yen : {true, false})
817 for (bool by_distance : {true, false})
818 {
819 SCOPED_TRACE(std::string(by_yen ? "Yen" : "Eppstein")
820 + (by_distance ? ", the distance" : ", the filter"));
821 const size_t & calls = by_distance ? distance_calls : filter_calls;
822 const char * what =
823 by_distance ? "thrown by the distance" : "thrown by the filter";
824 auto run = [&] (size_t at)
825 {
826 distance_calls = filter_calls = 0;
827 const Distance distance{&distance_calls, by_distance ? at : 0};
828 const Filter filter{&filter_calls, by_distance ? 0 : at};
829 if (by_yen)
830 return yen_k_shortest_paths(g, s, t, 2, distance, filter).size();
831 return eppstein_k_shortest_paths(g, s, t, 2, distance, filter).size();
832 };
833
834 ASSERT_EQ(run(0), 2u);
835 const size_t total = calls;
836 ASSERT_GT(total, 0u);
837 for (size_t at = 1; at <= total; ++at)
838 {
839 bool threw = false;
840 try
841 {
842 (void) run(at);
843 }
844 catch (const std::overflow_error & e)
845 {
846 threw = true;
847 EXPECT_STREQ(e.what(), what) << "at the call " << at;
848 }
849 // A run may make fewer calls
850 EXPECT_TRUE(threw or calls < at)
851 << "the call " << at << " threw nothing out";
852 }
853 }
854}
855
856
857// ============================================================================
858// Opt-in deterministic performance regression test.
859//
860// Activate with: PERF_TESTS_ENABLED=1 ./build/Tests/k_shortest_paths_test
861//
862// Parameters (pinned for reproducibility; update the comment if you change them):
863// MASTER_SEED 0xDEADBEEFCAFEBABEULL — drives all graph generation
864// N 40 nodes per graph (vs. 3–8 in RandomSmallGraphsMatchExactOracle)
865// K 25 shortest paths requested
866// TRIALS 3 independent random graphs drawn from the same RNG stream
867// Edge model random_graph_edges(): Bernoulli p=0.36, weight = base ∈ [1,40]
868// + 101*edge_index (unique, non-negative)
869// Budget 1000 ms per algorithm invocation (wall-clock via steady_clock)
870//
871// When a machine-specific baseline is established, record it here and tighten
872// the budget accordingly.
873// ============================================================================
874
875TEST(KShortestPathsTest, PerfRegression)
876{
877 const char * env = std::getenv("PERF_TESTS_ENABLED");
878 if (env == nullptr or std::string(env) != "1")
879 GTEST_SKIP() << "Skipped: set PERF_TESTS_ENABLED=1 to run";
880
881 constexpr size_t N = 40;
882 constexpr size_t K = 25;
883 constexpr int TRIALS = 3;
884 constexpr long long BUDGET_MS = 1000; // milliseconds per algorithm call
885 constexpr uint64_t MASTER_SEED = 0xDEADBEEFCAFEBABEULL;
886
887 std::mt19937_64 rng(MASTER_SEED);
888
889 for (int trial = 0; trial < TRIALS; ++trial)
890 {
891 auto built = build_graph(N, random_graph_edges(rng, N));
892 Node * src = built.nodes[0];
893 Node * tgt = built.nodes[N - 1];
894
895 // --- Yen k-shortest (simple) paths ---
896 {
897 const auto t0 = std::chrono::steady_clock::now();
898 const auto result = yen_k_shortest_paths<Graph>(built.g, src, tgt, K);
899 const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
900 std::chrono::steady_clock::now() - t0).count();
901
902 EXPECT_LE(elapsed, BUDGET_MS)
903 << "yen_k_shortest_paths exceeded budget on trial " << trial
904 << ": " << elapsed << " ms (budget " << BUDGET_MS << " ms,"
905 << " N=" << N << ", K=" << K << ", seed=" << MASTER_SEED << ")";
906
907 EXPECT_LE(result.size(), K) << "trial=" << trial;
908
909 // Non-decreasing cost sanity check
910 long long prev = std::numeric_limits<long long>::min();
911 for (auto it = result.get_it(); it.has_curr(); it.next_ne())
912 {
913 EXPECT_GE(it.get_curr().total_cost, prev) << "trial=" << trial;
914 prev = it.get_curr().total_cost;
915 }
916 }
917
918 // --- Eppstein k-shortest (possibly non-simple) paths ---
919 {
920 const auto t0 = std::chrono::steady_clock::now();
921 const auto result = eppstein_k_shortest_paths<Graph>(built.g, src, tgt, K);
922 const auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
923 std::chrono::steady_clock::now() - t0).count();
924
925 EXPECT_LE(elapsed, BUDGET_MS)
926 << "eppstein_k_shortest_paths exceeded budget on trial " << trial
927 << ": " << elapsed << " ms (budget " << BUDGET_MS << " ms,"
928 << " N=" << N << ", K=" << K << ", seed=" << MASTER_SEED << ")";
929
930 EXPECT_LE(result.size(), K) << "trial=" << trial;
931
932 long long prev = std::numeric_limits<long long>::min();
933 for (auto it = result.get_it(); it.has_curr(); it.next_ne())
934 {
935 EXPECT_GE(it.get_curr().total_cost, prev) << "trial=" << trial;
936 prev = it.get_curr().total_cost;
937 }
938 }
939 }
940}
K-shortest path algorithms (Yen and Eppstein-style API).
WeightedDigraph::Node Node
WeightedDigraph::Arc Arc
long double h
Definition btreepic.C:154
long double w
Definition btreepic.C:153
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
Generic directed graph (digraph) wrapper template.
Definition graph-dry.H:4377
size_t size() const noexcept
Return the current dimension of array.
T pop()
Remove the last item of array (as if this was a stack)
T & append()
Allocate a new entry to the end of array.
void next_ne() noexcept(shows_ne)
Advances the iterator to the next filtered element, as next() does.
Node Node
The graph type.
Definition tpl_graph.H:443
Arc Arc
The node class type.
Definition tpl_graph.H:444
Number Theoretic Transform over Z / MOD Z.
Definition ntt.H:115
Open addressing hash table with linear probing collision resolution.
Definition tpl_olhash.H:175
constexpr bool contains(const Key &key) const noexcept
Alias for has().
Definition hashDry.H:769
void remove(const Key &key)
Remove the key referenced by key.
Definition tpl_olhash.H:672
Iterator on nodes and arcs of a path.
Definition tpl_graph.H:4395
bool has_current_node() const noexcept
Return true if the iterator has a current node.
Definition tpl_graph.H:4512
Path on a graph.
Definition tpl_graph.H:3832
Minimal std::expected-style result type for C++20.
auto get_it()
Return a properly initialized iterator positioned at the first item on the container.
Definition ah-dry.H:663
Key * insert(const Key &key)
Inserts a key into the hash table (copy version).
Definition hashDry.H:507
#define TEST(name)
static mt19937 rng
DynArray< Graph::Node * > nodes
Definition graphpic.C:406
DynList< K_Shortest_Path_Item< GT, typename Distance::Distance_Type > > yen_k_shortest_paths(const GT &g, typename GT::Node *source, typename GT::Node *target, const size_t k, Distance distance=Distance(), SA sa=SA())
Compute k shortest loopless paths using Yen's algorithm.
DynList< K_Shortest_Path_Item< GT, typename Distance::Distance_Type > > eppstein_k_shortest_paths(const GT &g, typename GT::Node *source, typename GT::Node *target, const size_t k, Distance distance=Distance(), SA sa=SA())
Compute k shortest general (loopy) paths.
static mpfr_t y
Definition mpfr_mul_d.c:3
DFSResult< typename Domain::Distance > dfs(Domain &domain, typename Domain::State &state, SearchPath< typename Domain::Move > &path, const typename Domain::Distance g, const typename Domain::Distance threshold, const size_t depth, IDAStarResult< Solution, typename Domain::Distance > &result, OnSolution &on_solution)
Core recursive DFS used by IDA* for a single threshold pass.
Main namespace for Aleph-w library functions.
bool operator==(const DynList< T > &l1, const DynList< T > &l2)
Equality operator for DynList.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
Container2< typename Container1::Item_Type > filter(Container1 &container, Operation &operation)
Filter elements that satisfy operation.
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
and
Check uniqueness with explicit hash + equality functors.
static std::atomic< bool > init
Definition hash-fct.C:54
std::tuple< size_t, size_t, long long > Edge_Def
Built_Graph_T< Graph > build_graph(const size_t n, const std::vector< Edge_Def > &edges)
Arc of graph implemented with double-linked adjacency lists.
Definition tpl_graph.H:231
Filtered iterator of adjacent arcs of a node.
Definition tpl_graph.H:1155
Distance accessor.
Distance_Type operator()(Arc *a) const
static int * k
Dynamic array container with automatic resizing.
Lazy and scalable dynamic array implementation.
Generic graph and digraph implementations.
Open addressing hash table with linear probing.