53#include <gtest/gtest.h>
92 return arc->get_info();
97 arc->get_info() = 0.0;
129 for (
int i = 0; i < n; ++i)
130 nodes.push_back(
g.insert_node(i));
132 for (
int i = 0; i < n - 1; ++i)
140 std::mt19937 gen(
seed);
141 std::uniform_real_distribution<double> dist(minWeight, maxWeight);
144 for (
int i = 0; i < n; ++i)
145 nodes.push_back(
g.insert_node(i));
147 for (
int i = 0; i < n; ++i)
148 for (
int j = 0; j < n; ++j)
164 nodes.push_back(
g.insert_node(0));
165 nodes.push_back(
g.insert_node(1));
166 nodes.push_back(
g.insert_node(2));
167 nodes.push_back(
g.insert_node(3));
179 nodes.push_back(
g.insert_node(0));
180 nodes.push_back(
g.insert_node(1));
181 nodes.push_back(
g.insert_node(2));
190 double minWeight = 1.0,
double maxWeight = 10.0,
193 std::mt19937 gen(
seed);
194 std::uniform_real_distribution<double> weightDist(minWeight, maxWeight);
195 std::uniform_real_distribution<double> probDist(0.0, 1.0);
198 for (
int i = 0; i < n; ++i)
199 nodes.push_back(
g.insert_node(i));
201 for (
int i = 0; i < n; ++i)
202 for (
int j = 0; j < n; ++j)
203 if (i != j && probDist(gen) < edgeProbability)
210 const double INF = std::numeric_limits<double>::infinity();
211 int n =
nodes.size();
214 std::vector<std::vector<double>> dist(n, std::vector<double>(n, INF));
216 for (
int i = 0; i < n; ++i)
222 auto arc = it.get_curr();
223 auto src =
g.get_src_node(arc);
224 auto tgt =
g.get_tgt_node(arc);
225 int i = src->get_info();
226 int j = tgt->get_info();
227 double w = arc->get_info();
233 for (
int k = 0;
k < n; ++
k)
234 for (
int i = 0; i < n; ++i)
235 for (
int j = 0; j < n; ++j)
236 if (dist[i][
k] != INF && dist[
k][j] != INF)
237 if (dist[i][
k] + dist[
k][j] < dist[i][j])
238 dist[i][j] = dist[i][
k] + dist[
k][j];
241 std::map<std::pair<int, int>,
double> result;
242 for (
int i = 0; i < n; ++i)
243 for (
int j = 0; j < n; ++j)
244 if (dist[i][j] != INF)
245 result[{i, j}] = dist[i][j];
256 createPathGraph(3, 2.0);
261 EXPECT_FALSE(hasNegCycle);
267 createNegativeWeightGraph();
272 EXPECT_FALSE(hasNegCycle) <<
"Graph has negative weights but no negative cycles";
277 createNegativeCycleGraph();
282 EXPECT_TRUE(hasNegCycle) <<
"Graph should have a negative cycle";
287 createNegativeWeightGraph();
295 EXPECT_EQ(weights.size(),
nodes.size());
298 for (
auto node :
nodes)
300 auto* weightPtr = weights.search(node);
301 ASSERT_NE(weightPtr,
nullptr) <<
"Node should have a weight";
302 EXPECT_TRUE(std::isfinite(weightPtr->second));
308 createNegativeCycleGraph();
320 createPathGraph(4, 1.0);
327 EXPECT_DOUBLE_EQ(dist, 3.0);
331 EXPECT_DOUBLE_EQ(dist, 1.0);
335 EXPECT_DOUBLE_EQ(dist, 0.0);
340 createNegativeWeightGraph();
377 createNegativeCycleGraph();
381 EXPECT_THROW(JohnsonType johnson(g), std::domain_error);
386 createNegativeWeightGraph();
395 auto checkFiniteDist = [&](
int i,
int j,
double expected) {
396 auto* entry = allPairs.search(std::make_pair(
nodes[i],
nodes[j]));
397 ASSERT_NE(entry,
nullptr) <<
"Missing entry for (" << i <<
", " << j <<
")";
398 EXPECT_NEAR(entry->second,
expected, 1e-9)
399 <<
"Distance mismatch for (" << i <<
", " << j <<
")";
406 checkFiniteDist(0, 0, 0.0);
407 checkFiniteDist(0, 1, -2.0);
408 checkFiniteDist(0, 2, -1.0);
409 checkFiniteDist(0, 3, 1.0);
412 checkFiniteDist(1, 1, 0.0);
413 checkFiniteDist(1, 2, 1.0);
416 checkFiniteDist(2, 2, 0.0);
419 checkFiniteDist(3, 1, -3.0);
420 checkFiniteDist(3, 2, -2.0);
421 checkFiniteDist(3, 3, 0.0);
433 createNegativeWeightGraph();
441 auto arc = it.get_curr();
442 auto u = g.get_src_node(arc);
443 auto v = g.get_tgt_node(arc);
444 double w = arc->get_info();
446 auto* hu_ptr = weights.search(u);
447 auto* hv_ptr = weights.search(v);
448 ASSERT_NE(hu_ptr,
nullptr);
449 ASSERT_NE(hv_ptr,
nullptr);
451 double hu = hu_ptr->second;
452 double hv = hv_ptr->second;
453 double w_prime =
w + hu - hv;
455 EXPECT_GE(w_prime, 0.0)
456 <<
"Reweighted edge should be non-negative: w=" <<
w
457 <<
", h(u)=" << hu <<
", h(v)=" << hv
458 <<
", w'=" << w_prime;
466 createNegativeWeightGraph();
477 for (
auto it = g.get_node_it(); it.has_curr(); it.next())
479 auto orig = it.get_curr();
480 auto copy = reweighted.insert_node(orig->get_info());
487 auto arc = it.get_curr();
488 auto u = g.get_src_node(arc);
489 auto v = g.get_tgt_node(arc);
490 double w = arc->get_info();
492 double hu = weights.find(u);
493 double hv = weights.find(v);
494 double w_prime =
w + hu - hv;
496 auto* uCopy = nodeMap.
search(u);
497 auto* vCopy = nodeMap.
search(v);
498 reweighted.insert_arc(uCopy->second, vCopy->second, w_prime);
504 ASSERT_NE(srcPtr,
nullptr);
516 createCompleteGraph(5, 1.0, 10.0);
518 auto floydResults = computeFloydWarshall();
521 EXPECT_FALSE(floydResults.empty());
524 int n =
nodes.size();
525 for (
int i = 0; i < n; ++i)
526 for (
int j = 0; j < n; ++j)
527 EXPECT_NE(floydResults.find({i, j}), floydResults.end())
528 <<
"Path from " << i <<
" to " << j <<
" should exist";
534 createSparseGraph(10, 0.3, 1.0, 10.0);
536 auto floydResults = computeFloydWarshall();
539 for (
int i = 0; i < (int)
nodes.size(); ++i)
541 auto it = floydResults.find({i, i});
542 ASSERT_NE(it, floydResults.end());
543 EXPECT_DOUBLE_EQ(it->second, 0.0);
551 nodes.push_back(g.insert_node(0));
556 EXPECT_FALSE(hasNegCycle);
561 nodes.push_back(g.insert_node(0));
562 nodes.push_back(g.insert_node(1));
567 EXPECT_FALSE(hasNegCycle);
572 nodes.push_back(g.insert_node(0));
573 nodes.push_back(g.insert_node(1));
579 EXPECT_FALSE(hasNegCycle);
585 nodes.push_back(g.insert_node(0));
591 EXPECT_FALSE(hasNegCycle);
596 nodes.push_back(g.insert_node(0));
602 EXPECT_TRUE(hasNegCycle);
607 nodes.push_back(g.insert_node(0));
608 nodes.push_back(g.insert_node(1));
616 EXPECT_FALSE(hasNegCycle);
623 createCompleteGraph(20, 1.0, 100.0);
629 EXPECT_FALSE(hasNegCycle);
632 for (
size_t i = 1; i <
nodes.size(); ++i)
636 EXPECT_FALSE(path.
is_empty()) <<
"Path to node " << i <<
" should exist";
643 createCompleteGraph(100, 1.0, 100.0);
648 auto start = std::chrono::high_resolution_clock::now();
654 auto mid = std::chrono::high_resolution_clock::now();
659 auto end = std::chrono::high_resolution_clock::now();
661 auto bfTime = std::chrono::duration_cast<std::chrono::milliseconds>(mid - start);
662 auto totalTime = std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
664 std::cout <<
"Bellman-Ford time: " << bfTime.count() <<
" ms\n";
665 std::cout <<
"Total time: " << totalTime.count() <<
" ms\n";
673 nodes.push_back(g.insert_node(0));
674 nodes.push_back(g.insert_node(1));
675 nodes.push_back(g.insert_node(2));
676 nodes.push_back(g.insert_node(3));
684 auto floydResults = computeFloydWarshall();
693 auto d00 = floydResults[std::make_pair(0, 0)];
694 auto d01 = floydResults[std::make_pair(0, 1)];
695 auto d02 = floydResults[std::make_pair(0, 2)];
696 auto d03 = floydResults[std::make_pair(0, 3)];
698 EXPECT_DOUBLE_EQ(d00, 0.0);
699 EXPECT_DOUBLE_EQ(d01, 3.0);
700 EXPECT_DOUBLE_EQ(d02, 1.0);
701 EXPECT_DOUBLE_EQ(d03, 3.0);
712 EXPECT_DOUBLE_EQ(
dist2, 1.0) <<
"Distance 0->2 should be 1.0";
717 EXPECT_DOUBLE_EQ(dist3, 3.0) <<
"Distance 0->3 should be 3.0";
724 createNegativeWeightGraph();
734 EXPECT_EQ(hasNeg1, hasNeg2);
737 EXPECT_FALSE(hasNeg1);
738 EXPECT_FALSE(hasNeg2);
745 createNegativeCycleGraph();
752 if (!cycle.is_empty())
756 EXPECT_GE(cycle.size(), 2) <<
"Cycle should have at least 2 nodes";
763 nodes.push_back(g.insert_node(0));
764 nodes.push_back(g.insert_node(1));
765 nodes.push_back(g.insert_node(2));
775 EXPECT_FALSE(hasNegFromNode0) <<
"Negative cycle not reachable from node 0";
780 EXPECT_TRUE(hasNegGlobal) <<
"Global check should find unreachable negative cycle";
790 createNegativeWeightGraph();
801 catch (
const std::domain_error&)
803 FAIL() <<
"Unexpected negative cycle in test graph";
807 std::map<Arc*, double> originalWeights;
808 std::map<Arc*, double> reweightedWeights;
812 auto arc = it.get_curr();
813 auto u = g.get_src_node(arc);
814 auto v = g.get_tgt_node(arc);
815 double w = arc->get_info();
817 originalWeights[arc] =
w;
819 double hu =
h.find(u);
820 double hv =
h.find(v);
821 double w_prime =
w + hu - hv;
823 EXPECT_GE(w_prime, -1e-9) <<
"Reweighted edge should be non-negative";
825 reweightedWeights[arc] = w_prime;
826 arc->get_info() = w_prime;
830 std::map<std::pair<int, int>,
double> johnsonDistances;
832 for (
size_t i = 0; i <
nodes.size(); ++i)
837 for (
size_t j = 0; j <
nodes.size(); ++j)
841 johnsonDistances[{(int)i, (
int)j}] = 0.0;
851 double hu =
h.find(
nodes[i]);
852 double hv =
h.find(
nodes[j]);
853 double d = d_prime - hu + hv;
855 johnsonDistances[{(int)i, (
int)j}] = d;
867 auto arc = it.get_curr();
868 arc->get_info() = originalWeights[arc];
872 auto floydDistances = computeFloydWarshall();
874 for (
const auto& [
pair, dist] : johnsonDistances)
876 auto it = floydDistances.find(
pair);
877 if (it != floydDistances.end())
879 EXPECT_NEAR(dist, it->second, 1e-9)
880 <<
"Distance mismatch for pair (" <<
pair.first <<
", " <<
pair.second <<
"): "
881 <<
"Johnson=" << dist <<
", Floyd=" << it->second;
895TEST(JohnsonIntegers, AnUnreachableNodeIsAtMax)
898 auto a = g.insert_node(0);
899 auto b = g.insert_node(1);
900 auto c = g.insert_node(2);
901 g.insert_arc(a, b, 5);
902 g.insert_arc(b, a, -2);
905 constexpr int unreachable = std::numeric_limits<int>::max();
912 EXPECT_EQ(
all.find(std::make_pair(a, b)), 5);
913 EXPECT_EQ(
all.find(std::make_pair(b, a)), -2);
914 EXPECT_EQ(
all.find(std::make_pair(a, c)), unreachable);
915 EXPECT_EQ(
all.find(std::make_pair(c, b)), unreachable);
919TEST(JohnsonIntegers, AnUnreachableNodeIsAtInfinityWithDoubles)
922 auto a = g.insert_node(0);
923 auto b = g.insert_node(1);
924 g.insert_arc(a, b, 1.5);
929 std::numeric_limits<double>::infinity());
935TEST(JohnsonIntegers, ADistanceNearMaxDoesNotOverflowOnTheWayBack)
937 constexpr int max = std::numeric_limits<int>::max();
939 auto s = g.insert_node(0);
940 auto t = g.insert_node(1);
941 auto u = g.insert_node(2);
942 auto v = g.insert_node(3);
943 g.insert_arc(u, s, -10);
944 g.insert_arc(v, t, -8);
945 g.insert_arc(s, t,
max - 5);
955 auto x =
h.insert_node(0);
956 auto y =
h.insert_node(1);
957 auto z =
h.insert_node(2);
958 h.insert_arc(x,
y,
max - 10);
959 h.insert_arc(
y, z, 20);
961 EXPECT_THROW(above.
get_distance(x, z), std::overflow_error);
970 template <
typename T>
971 void check_a_potential_below_lowest()
974 constexpr T max = std::numeric_limits<T>::max();
975 constexpr int factor[] = {-1, -1, 1, 1};
978 std::vector<typename G::Node *> v;
979 for (
int i = 0; i < 5; ++i)
981 for (
int i = 0; i < 4; ++i)
988 for (
int round = 0; round < 2; ++round)
989 for (
int i = 0; i < 5; ++i)
990 for (
int k = 0;
k < 5; ++
k)
992 const int s = round == 0 ? i : 4 - i;
993 SCOPED_TRACE(
"from " + std::to_string(s) +
" to " + std::to_string(
k));
994 auto * src = v[size_t(s)];
995 auto * tgt = v[size_t(
k)];
998 EXPECT_EQ(johnson.get_distance(src, tgt), s ==
k ?
T(0) :
max);
999 EXPECT_EQ(johnson.find_path(src, tgt).size(), s ==
k ? 1u : 0u);
1004 for (
int x = s; x <
k; ++x)
1006 if (sum < -1 or sum > 1)
1008 EXPECT_THROW(johnson.get_distance(src, tgt), std::overflow_error);
1009 EXPECT_THROW(johnson.find_path(src, tgt), std::overflow_error);
1013 EXPECT_EQ(johnson.get_distance(src, tgt),
T(sum *
max));
1014 const auto path = johnson.find_path(src, tgt);
1015 EXPECT_EQ(path.size(),
size_t(
k - s + 1));
1016 EXPECT_EQ(path.get_first_node(), src);
1017 EXPECT_EQ(path.get_last_node(), tgt);
1020 EXPECT_THROW(johnson.compute_all_pairs_distances(), std::overflow_error);
1022 EXPECT_EQ(johnson.get_potential(v[0]),
T(0));
1023 EXPECT_EQ(johnson.get_potential(v[1]),
T(-
max));
1024 EXPECT_THROW(johnson.get_potential(v[2]), std::overflow_error);
1025 EXPECT_EQ(johnson.get_potential(v[3]),
T(-
max));
1026 EXPECT_EQ(johnson.get_potential(v[4]),
T(0));
1029 const G &
copy = johnson.get_reweighted_graph();
1030 EXPECT_EQ(
copy.get_num_arcs(), 4u);
1031 for (
auto it =
copy.get_arc_it(); it.has_curr(); it.next_ne())
1032 EXPECT_EQ(it.get_curr()->get_info(),
T(0));
1036 EXPECT_EQ(moved.get_distance(v[0], v[4]),
T(0));
1037 EXPECT_EQ(moved.get_distance(v[1], v[4]),
max);
1038 EXPECT_THROW(moved.get_distance(v[2], v[4]), std::overflow_error);
1045TEST(JohnsonIntegers, APotentialBelowLowestThrowsOnlyForTheDistancesThatDoNotFit)
1047 check_a_potential_below_lowest<short>();
1048 check_a_potential_below_lowest<int>();
1049 check_a_potential_below_lowest<long long>();
1055TEST(JohnsonIntegers, ANegativeCycleOfLargeWeightsThrowsDomainError)
1057 constexpr int max = std::numeric_limits<int>::max();
1059 auto a = g.insert_node(0);
1060 auto b = g.insert_node(1);
1061 auto c = g.insert_node(2);
1062 g.insert_arc(a, b, -
max);
1063 g.insert_arc(b, c, -
max);
1064 g.insert_arc(c, a,
max);
1068 constexpr long long lmax = std::numeric_limits<long long>::max();
1070 auto x =
h.insert_node(0);
1071 auto y =
h.insert_node(1);
1072 h.insert_arc(x,
y, -lmax);
1073 h.insert_arc(
y, x, -lmax);
1082 ::testing::InitGoogleTest(&argc, argv);
1083 return RUN_ALL_TESTS();
1089TEST(JohnsonIntegers, TheTreeOfTheLastSourceIsReused)
1092 std::vector<IntDigraph::Node *> v;
1093 std::mt19937 gen(11);
1094 for (
int i = 0; i < 12; ++i)
1095 v.push_back(g.insert_node(i));
1096 for (
int k = 0;
k < 40; ++
k)
1098 const auto i = gen() % 12, j = gen() % 12;
1100 g.insert_arc(v[std::min(i, j)], v[std::max(i, j)],
int(gen() % 21) - 8);
1107 return s == t ? 0 :
all.find(std::make_pair(s, t));
1110 for (
int round = 0; round < 3; ++round)
1111 for (
size_t i = 0; i < v.size(); ++i)
1112 for (
size_t j = 0; j < v.size(); ++j)
1115 const auto s = v[(i + round * j) % v.size()];
Bellman-Ford algorithm for single-source shortest paths.
Dijkstra's shortest path algorithm.
Johnson's algorithm for all-pairs shortest paths.
WeightedDigraph::Node Node
Bellman-Ford algorithm for shortest paths with negative weights.
bool faster_paint_spanning_tree(Node *start)
Faster shortest paths tree painting from a start node.
DynMapTree< Node *, Distance_Type > compute_nodes_weights()
Returns a mapping with the shortest distances to each node obtained after executing the Bellman-Ford ...
bool paint_spanning_tree(Node *start)
Paint the shortest paths tree from a start node.
bool is_painted() const noexcept
Check if a shortest-path tree has been painted.
bool has_negative_cycle(Node *start)
Test if a negative cycle exists starting from a specific node.
Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extract the shortest path to a node from a previously painted tree.
Path< GT > test_negative_cycle(Node *start)
Search a negative cycle on all possible paths starting from start node.
Generic directed graph (digraph) wrapper template.
typename BaseGraph::Arc Arc
typename BaseGraph::Node Node
Spanning tree calculation of all shortest paths from a given node according to Dijkstra's algorithm.
Distance::Distance_Type get_min_path(typename GT::Node *end, Path< GT > &path)
Extracts a shortest path to end from a previously painted graph.
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.
bool is_painted() const noexcept
Check if the graph has been painted.
Generic key-value map implemented on top of a binary search tree.
Pair * search(const Key &key) noexcept(nothrow_search)
Collect all keys.
Pair * insert(const Key &key, const Data &data)
Insert a key-value pair.
void next()
Advances the iterator to the next filtered element.
Johnson's algorithm for all-pairs shortest paths.
Path< GT > find_path(Node *src, Node *tgt)
Find the shortest path from source to target.
bool is_initialized() const noexcept
Check if the algorithm has been initialized.
DynMapTree< std::pair< Node *, Node * >, Distance_Type > compute_all_pairs_distances()
Compute the shortest distance for all pairs.
Distance_Type get_potential(Node *node) const
Get the node potential (h value) for a node.
Distance_Type get_distance(Node *src, Node *tgt)
Get the shortest distance from source to target.
Graph implemented with double-linked adjacency lists.
virtual Node * insert_node(Node *node) noexcept
Insertion of a node already allocated.
Arc * insert_arc(Node *src_node, Node *tgt_node, void *a)
bool is_empty() const noexcept
Return true if the path is empty.
Minimal std::expected-style result type for C++20.
void createSparseGraph(int n, double edgeProbability=0.2, double minWeight=1.0, double maxWeight=10.0, unsigned seed=42)
std::map< std::pair< int, int >, double > computeFloydWarshall()
std::vector< Node * > nodes
void createPathGraph(int n, double weight=1.0)
void createNegativeWeightGraph()
void createNegativeCycleGraph()
void createCompleteGraph(int n, double minWeight=1.0, double maxWeight=10.0, unsigned seed=42)
static Geom_Number dist2(const Point &a, const Point &b)
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
DynArray< Graph::Node * > nodes
TEST_F(JohnsonTest, BellmanFordBasic)
Main namespace for Aleph-w library functions.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
bool all(Container &container, Operation &operation)
Return true if all elements satisfy a predicate.
std::decay_t< typename HeadC::Item_Type > T
std::pair< First, Second > pair
Alias to std::pair kept for backwards compatibility.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
Filtered iterator on all the arcs of a graph.
Arc of graph implemented with double-linked adjacency lists.
Node belonging to a graph implemented with a double linked adjacency list.
Distance_Type operator()(Arc *arc) const
static void set_zero(Arc *arc)
void set_weight(Arc *arc, Distance_Type w)
Generic graph and digraph implementations.
Utility algorithms and operations for graphs.