From f9c1c17e875727b91bb2ad106ad5eae0d3d0370c Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Tue, 1 Dec 2026 21:41:17 -0600 Subject: [PATCH] Follow NetworkX on NaN, infinite and negative path weights NetworkX's Bellman-Ford relaxes an edge only where the length through it is less than the length its head has, which through a NaN or +inf weight it never is, so such an edge reaches nothing. Here it was summed, and every node past it got a NaN or inf length. The Bellman-Ford names now drop those edges. They, and the average length by Bellman-Ford, still serve negative weights. NetworkX's Dijkstra, behind eccentricity and its kin, closeness, harmonic, the Wiener indices, ego_graph with a distance and the average length by Dijkstra, meets a NaN in the order it pops its heap, and it takes no weight to be negative: given one, whether it raises "Contradictory paths found", and the lengths it gives when it does not, follow that order too. Those names gave Bellman-Ford's lengths for a negative weight, so a call that fails in NetworkX was answered. They now leave NaN and negative weights to NetworkX, by facts cached on the conversion, and the handlers that gave a negative cycle NetworkX's Dijkstra error are removed, as nothing reaches them. Floyd-Warshall keeps NaN entries, so its calls with a NaN go to NetworkX too, as does any call here with a -inf weight, where the check for a negative cycle misses cycles NetworkX finds. On an undirected graph the conversion adds a self-loop's weight in twice and takes it out once, so a loop of -inf or +inf holds NaN, as a NaN loop does. Such a NaN on the diagonal counts as -inf there, and the call goes to NetworkX. Float weights so heavy that a sum may pass the largest float go to NetworkX too: at -inf the lengths stop falling before the check for a negative cycle, and the walk back along the parents could run without end; at inf a node NetworkX leaves unreached got a length. The walk now stops after as many steps as there are nodes. A negative weight off the diagonal no longer counts as a negative self-loop, as it did once the sign of the weights was cached. The Floyd-Warshall names take the same bound, and where a weight is negative, the Bellman-Ford and Floyd-Warshall names also go to NetworkX when that bound reaches 2**53 times the lightest nonzero weight, as a sum that large can lose a weight and with it a negative cycle that NetworkX's rounding hides. --- _nx_graphblas/__init__.py | 43 +- _nx_graphblas/core.py | 96 ++- .../algorithms/shortest_paths/weighted.py | 3 + graphblas_algorithms/classes/graph.py | 10 +- graphblas_algorithms/nxapi/_utils.py | 148 +++- .../nxapi/centrality/closeness.py | 11 +- .../nxapi/centrality/harmonic.py | 9 +- .../nxapi/distance_measures.py | 13 +- graphblas_algorithms/nxapi/generators/ego.py | 22 +- .../nxapi/shortest_paths/dense.py | 8 +- .../nxapi/shortest_paths/generic.py | 20 +- .../nxapi/shortest_paths/weighted.py | 18 +- .../nxapi/tests/test_distance_centrality.py | 22 +- .../nxapi/tests/test_distance_measures.py | 46 +- graphblas_algorithms/nxapi/tests/test_ego.py | 7 +- .../nxapi/tests/test_nonfinite_weights.py | 657 ++++++++++++++++++ .../nxapi/tests/test_wiener.py | 12 +- graphblas_algorithms/nxapi/wiener.py | 11 +- graphblas_algorithms/tests/test_properties.py | 51 +- 19 files changed, 1078 insertions(+), 129 deletions(-) create mode 100644 graphblas_algorithms/nxapi/tests/test_nonfinite_weights.py diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..17e795a 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -190,48 +190,49 @@ def get_info(): _additional_docs = { # BEGIN: additional_docs - "all_pairs_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", - "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".', - "bellman_ford_path": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", - "bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "all_pairs_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nAn edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\nlength, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\ninfinite weight on an undirected graph, which its conversion makes NaN, and float\nweights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", + "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX.\nWith `method="dijkstra"`, or a weight and no `method`, a negative or NaN weight is left\nto NetworkX; with `method="bellman-ford"`, a NaN or infinite one, or float weights so\nheavy that a sum of n * n of them (on n nodes) may pass the largest float, or, with a\nnegative one, so far apart that a sum may lose one.', + "bellman_ford_path": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nAn edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\nlength, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\ninfinite weight on an undirected graph, which its conversion makes NaN, and float\nweights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", + "bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nAn edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\nlength, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\ninfinite weight on an undirected graph, which its conversion makes NaN, and float\nweights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", "betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.", "betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.", "bfs_edges": "A breadth-first tree that may differ from NetworkX's, as may the order: a node's parent\nis its neighbor on the level above first in node order, and each level comes by parent,\nthen child, in node order. `sort_neighbors` is left to NetworkX.", "bfs_successors": "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n`sort_neighbors` is left to NetworkX.", - "center": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', - "closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', + "center": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', + "closeness_centrality": 'A negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", "compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.", - "diameter": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', + "diameter": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", - "eccentricity": 'A precomputed `sp`, and the null graph, are left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', + "eccentricity": 'A precomputed `sp`, and the null graph, are left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', "edge_betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\nThe edges come by their first ends in node order, then by their second ends in node\norder, which may differ from the order of `G.edges()`.", "edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.", - "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.', - "floyd_warshall": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", - "floyd_warshall_predecessor_and_distance": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "ego_graph": "With `distance`, the call raises OverflowError rather than add integer weights where the\nnumber of nodes times the heaviest absolute weight reaches 2**62, as a length could then\npass 2**63.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.\nWith `distance`, a negative or NaN weight is left to NetworkX.", + "floyd_warshall": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA NaN or infinite weight is left to NetworkX, as are float weights so heavy that a\nsum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", + "floyd_warshall_numpy": "A NaN or infinite weight is left to NetworkX, as are float weights so heavy that a\nsum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", + "floyd_warshall_predecessor_and_distance": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA NaN or infinite weight is left to NetworkX, as are float weights so heavy that a\nsum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", - "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', - "harmonic_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', - "harmonic_diameter": 'A precomputed `sp` is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', + "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', + "harmonic_centrality": 'A negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', + "harmonic_diameter": 'A precomputed `sp` is left to NetworkX.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', "hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.', - "hyper_wiener_index": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node's targets could\nreach 2**63.", + "hyper_wiener_index": 'Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', "k_core": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_corona": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", - "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", - "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', - "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', + "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nAn edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\nlength, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\ninfinite weight on an undirected graph, which its conversion makes NaN, and float\nweights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", + "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', + "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", - "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', - "single_source_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', + "single_source_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.\nAn edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\nlength, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\ninfinite weight on an undirected graph, which its conversion makes NaN, and float\nweights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\nSo are float weights with a negative one where n * n times the heaviest, doubled,\nreaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n1e300), and whether NetworkX then finds a negative cycle follows the order it adds.", "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "volume": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more, or to 2**63 over the most times `S` names one node.", - "wiener_index": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', + "wiener_index": 'Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.\nA negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\npops its heap: whether a negative one raises "Contradictory paths found", and which\nlengths a NaN hides.', # END: additional_docs } # fmt: on diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..133c74c 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -73,11 +73,6 @@ "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\n" "or more" ) -_NEGATIVE_EDGES = ( - "Lengths are Bellman-Ford's, so a negative edge without a negative cycle is answered where\n" - 'NetworkX\'s Dijkstra raises "Contradictory paths found".' -) - # The Wiener index and its relatives sum lengths, or terms of them, over each node's targets. _LENGTH_SUM_OVERFLOW = ( "Raises OverflowError rather than add integer weights where the number of nodes times the\n" @@ -87,10 +82,7 @@ _ECCENTRICITY_BOUNDS = ( "`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\n" - "elsewhere every one is computed. The null graph is left to NetworkX.\n" - + _NEGATIVE_EDGES - + "\n" - + _PATH_OVERFLOW + "elsewhere every one is computed. The null graph is left to NetworkX.\n" + _PATH_OVERFLOW ) _CORE_SUBGRAPH = ( @@ -103,9 +95,7 @@ "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, "average_shortest_path_length": ( 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n' - 'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n' - "without a negative cycle is answered where NetworkX's Dijkstra raises\n" - '"Contradictory paths found".' + "NetworkX." ), "bellman_ford_path": _PATH_OVERFLOW, "bellman_ford_path_length": _PATH_OVERFLOW, @@ -123,15 +113,12 @@ "`sort_neighbors` is left to NetworkX." ), "center": _ECCENTRICITY_BOUNDS, - "closeness_centrality": _NEGATIVE_EDGES, "common_neighbor_centrality": ( "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX." ), "cut_size": _SUM_OVERFLOW + ".", "diameter": _ECCENTRICITY_BOUNDS, "eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n" - + _NEGATIVE_EDGES - + "\n" + _PATH_OVERFLOW, "edge_betweenness_centrality": ( "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\n" @@ -144,18 +131,16 @@ "of `G.edges()`." ), "ego_graph": ( - "With `distance`, lengths are Bellman-Ford's, so a negative edge without a negative\n" - 'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\n' - "call raises OverflowError rather than add integer weights where the number of nodes\n" - "times the heaviest absolute weight reaches 2**62, as a length could then pass 2**63." + "With `distance`, the call raises OverflowError rather than add integer weights where the\n" + "number of nodes times the heaviest absolute weight reaches 2**62, as a length could then\n" + "pass 2**63." ), "floyd_warshall": _PATH_OVERFLOW, "floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW, "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, - "harmonic_centrality": _NEGATIVE_EDGES, - "harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES, + "harmonic_diameter": "A precomputed `sp` is left to NetworkX.", "hits": ( "A graph with nodes and no edges gets 0.0 for every node, where NetworkX's power\n" 'iteration does not converge. `method="svd"` is left to NetworkX.' @@ -177,7 +162,7 @@ + _LENGTH_SUM_OVERFLOW, "single_source_bellman_ford_path_length": _PATH_OVERFLOW, "volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.", - "wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW, + "wiener_index": _LENGTH_SUM_OVERFLOW, } # A graph these names return is rebuilt from one matrix, which holds its values in one type. @@ -204,6 +189,73 @@ _ADDITIONAL_DOCS[_name] = _ONE_WEIGHT_TYPE if _doc is None else f"{_doc}\n{_ONE_WEIGHT_TYPE}" +# Float weights whose sums may lose one, where NetworkX's walks and the checks here part. +_LOST_WEIGHT = ( + "So are float weights with a negative one where n * n times the heaviest, doubled,\n" + "reaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n" + "1e300), and whether NetworkX then finds a negative cycle follows the order it adds." +) + +# How the shortest-path names meet weights that are not finite numbers. +_NONFINITE = { + "bellman-ford": ( + "An edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\n" + "length, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\n" + "infinite weight on an undirected graph, which its conversion makes NaN, and float\n" + "weights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\n" + + _LOST_WEIGHT + ), + "dijkstra": ( + "A negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\n" + 'pops its heap: whether a negative one raises "Contradictory paths found", and which\n' + "lengths a NaN hides." + ), + "floyd-warshall": ( + "A NaN or infinite weight is left to NetworkX, as are float weights so heavy that a\n" + "sum of n * n of them (on n nodes) may pass the largest float.\n" + _LOST_WEIGHT + ), +} +for _rule, _names in { + "bellman-ford": [ + "all_pairs_bellman_ford_path_length", + "bellman_ford_path", + "bellman_ford_path_length", + "negative_edge_cycle", + "single_source_bellman_ford_path_length", + ], + "dijkstra": [ + "center", + "closeness_centrality", + "diameter", + "eccentricity", + "gutman_index", + "harmonic_centrality", + "harmonic_diameter", + "hyper_wiener_index", + "periphery", + "radius", + "schultz_index", + "wiener_index", + ], + "floyd-warshall": [ + "floyd_warshall", + "floyd_warshall_numpy", + "floyd_warshall_predecessor_and_distance", + ], +}.items(): + for _name in _names: + _doc = _ADDITIONAL_DOCS.get(_name) + _note = _NONFINITE[_rule] + _ADDITIONAL_DOCS[_name] = _note if _doc is None else f"{_doc}\n{_note}" +_ADDITIONAL_DOCS["average_shortest_path_length"] += ( + '\nWith `method="dijkstra"`, or a weight and no `method`, a negative or NaN weight is left\n' + 'to NetworkX; with `method="bellman-ford"`, a NaN or infinite one, or float weights so\n' + "heavy that a sum of n * n of them (on n nodes) may pass the largest float, or, with a\n" + "negative one, so far apart that a sum may lose one." +) +_ADDITIONAL_DOCS["ego_graph"] += "\nWith `distance`, a negative or NaN weight is left to NetworkX." + + def get_functions(): from graphblas_algorithms.interface import Dispatcher diff --git a/graphblas_algorithms/algorithms/shortest_paths/weighted.py b/graphblas_algorithms/algorithms/shortest_paths/weighted.py index 1fd9bf8..3f659c6 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/weighted.py +++ b/graphblas_algorithms/algorithms/shortest_paths/weighted.py @@ -240,6 +240,9 @@ def _reconstruct_path_from_parents(G, parents, src, dst, target): cur = dst path = [cur] while cur != src: + if len(path) > len(d): + # Else the walk never ends, and the list grows until memory runs out + raise RuntimeError(f"the parents from {target} come back on themselves") cur = d[cur] path.append(cur) return G.list_to_keys(reversed(path)) diff --git a/graphblas_algorithms/classes/graph.py b/graphblas_algorithms/classes/graph.py index 0848c89..53cdb54 100644 --- a/graphblas_algorithms/classes/graph.py +++ b/graphblas_algorithms/classes/graph.py @@ -138,12 +138,16 @@ def has_negative_diagonal(G, mask=None): if A.dtype in NONNEGATIVE_DTYPES or A.dtype._is_udt or cache.get("has_self_edges") is False: cache["has_negative_diagonal"] = False elif ( + # A negative weight, and none off the diagonal; a missing fact tells nothing. cache.get("has_negative_edges+") is True and cache.get("has_negative_edges-") is False or cache.get("has_negative_edges+") is True - and cache.get("min_element-", 0) >= 0 - or cache.get("min_element+", 0) < 0 - and cache.get("min_element+", 0) < cache.get("min_element-", 0) + and "min_element-" in cache + and cache["min_element-"] >= 0 + or "min_element+" in cache + and "min_element-" in cache + and cache["min_element+"] < 0 + and cache["min_element+"] < cache["min_element-"] ): cache["has_negative_diagonal"] = True else: diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 72f728b..fd84fbd 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -1,6 +1,9 @@ -from math import ceil +from math import ceil, inf from numbers import Number +import numpy as np +from graphblas import monoid, select, unary + from .exception import NetworkXError try: @@ -208,3 +211,146 @@ def nbunch_keys(G, nbunch, *, unique=False): if present: keys.append(node) return list(dict.fromkeys(keys)) if unique else keys + + +def _read_apart(G): + """`(nan, posinf, neginf)`: whether some weight of `G` is NaN, +inf or -inf; cached on `G`. + + NetworkX's shortest-path walks meet these by comparisons that differ from the sums here. The + conversion of an undirected graph adds a self-loop's weight in twice and takes it out once, + so a loop of weight inf or -inf is NaN on the diagonal: such a NaN may be -inf. + """ + + def find(): + A = G._A + if A.nvals == 0 or A.dtype.np_type.kind != "f": + return False, False, False + _, _, values = A.to_coo(rows=False, columns=False) + nan = bool(np.isnan(values).any()) + neginf = bool(np.isneginf(values).any()) + if nan and not neginf and not G.is_directed(): + _, loops = A.diag().to_coo() + neginf = bool(np.isnan(loops).any()) + return nan, bool(np.isposinf(values).any()), neginf + + return G._cacheit("read_apart", find) + + +def _relaxable(G): + A = select.valuelt(G._A, inf).new(name="relaxable") + return type(G)(A, key_to_id=G._key_to_id, weight=G._weight) + + +def _heaviest_finite(G): + """The largest absolute value of `G`'s finite float weights, or 0.0; cached on `G`.""" + + def find(): + A = G._A + if A.nvals == 0 or A.dtype.np_type.kind != "f": + return 0.0 + if not any(_read_apart(G)): + least = A.reduce_scalar(monoid.min).get(0) + return float(max(-least, A.reduce_scalar(monoid.max).get(0))) + _, _, values = A.to_coo(rows=False, columns=False) + values = np.abs(values[np.isfinite(values)]) + return float(values.max()) if values.size else 0.0 + + return G._cacheit("heaviest_finite", find) + + +def _lightest_finite(G): + """The least absolute value of `G`'s nonzero finite float weights, or inf; cached on `G`.""" + + def find(): + A = G._A + if A.nvals == 0 or A.dtype.np_type.kind != "f": + return inf + magnitudes = unary.abs(A).new(name="magnitudes") + # NaN is not greater than zero; inf is the least only where nothing else is left. + magnitudes << select.valuegt(magnitudes, 0) + return float(magnitudes.reduce_scalar(monoid.min).get(inf)) + + return G._cacheit("lightest_finite", find) + + +def check_float_sums(G, name): + """Raise NotImplementedError where a sum of float weights may overflow or lose a weight. + + The lengths of Bellman-Ford and Floyd-Warshall are sums of float weights. A length is the + sum of a walk: of at most `n` edges here, and of at most `n * n` in NetworkX's Bellman-Ford, + which queues each node fewer than `n` times before it reports a negative cycle; its + Floyd-Warshall adds two lengths of paths. So no length passes `n * n` times the heaviest + finite weight, doubled; doubling covers the rounding of such sums below 7e7 nodes. + + Weights are left to NetworkX where that bound reaches the largest float. A sum past it is + inf or -inf: NetworkX relaxes no edge to a length of inf, which here is a length; and a + length at -inf falls no further, so a negative cycle may go unfound, here as in NetworkX, + where finding it then follows the order it walks (as for a -inf weight). + + A sum also loses a weight under half a unit in its last place: 1e300 - 1 is 1e300. NetworkX + relaxes no edge where the length through it does not fall, so its Bellman-Ford finds no + negative cycle whose weight is lost, where the check here reads a negative self-loop from its + weight; and which cycles a walk finds then follows the order it adds, in either algorithm. A + weight of at least 2**-53 times the bound is never lost, so weights with a negative one are + left to NetworkX where the lightest nonzero one is less. Without a negative weight, a lost + weight gives a length within rounding of NetworkX's. Integer weights have their own bound + (`checked_sum_type`). Each fact is cached on `G`. + """ + n = G._A.nrows + # A product past the largest float is inf, which reaches it + bound = _heaviest_finite(G) * n * n * 2 + if bound >= np.finfo(float).max: + raise NotImplementedError( + f"{name} with weights whose sums may overflow is left to networkx" + ) + if G.get_property("has_negative_edges+") and bound >= _lightest_finite(G) * 2**53: + raise NotImplementedError( + f"{name} with weights so far apart that a sum may lose one is left to networkx" + ) + + +def bellman_ford_graph(G, name): + """`G` as NetworkX's Bellman-Ford walks it; NotImplementedError where the walks differ. + + NetworkX relaxes an edge only where the length through it is less than the length its head + has, or than inf for a head not yet reached. Through a NaN or +inf weight it never is: NaN + compares false, inf is not less than inf, and -inf plus inf is NaN. Such an edge gives no + length and no predecessor, so it is dropped. A -inf weight is left to NetworkX: no length + falls below -inf, so the check here for a negative cycle, lengths that still fall after + `n - 1` rounds, misses cycles NetworkX finds; and whether NetworkX's own checks find one + follows the order it walks, as a node's length stops falling once it is -inf. So is a + self-loop of an undirected graph that may weigh -inf (`_read_apart`), and so are weights + whose sums may pass the largest float or lose a weight (`check_float_sums`). + """ + nan, posinf, neginf = _read_apart(G) + if neginf: + raise NotImplementedError(f"{name} with a -inf weight is left to networkx") + check_float_sums(G, name) + if not (nan or posinf): + return G + return G._cacheit("relaxable", _relaxable, G) + + +def check_dijkstra_weights(G, name): + """Raise NotImplementedError where NetworkX's Dijkstra walks `G`'s weights its own way. + + NetworkX answers these names with Dijkstra, which takes no weight to be negative. Given a + negative one, whether it raises "Contradictory paths found", and the lengths it gives when + it does not, follow the order it pops its heap; and a NaN length compares false with every + other, so which nodes get one, and which lengths a NaN hides, follow that order too. The + lengths here are least sums over every walk. Both facts are cached on `G`. + """ + if _read_apart(G)[0] or G.get_property("has_negative_edges+"): + raise NotImplementedError(f"{name} with a negative or NaN weight is left to networkx") + + +def check_finite_weights(G, name): + """Raise NotImplementedError for a NaN or infinite weight, which NetworkX reads its own way. + + Its Floyd-Warshall keeps a NaN entry, since no sum compares less, and gives a predecessor to + an edge of weight inf but to no walk through one; its NumPy version adds -inf to the inf of + a missing edge and so fills NaN. Its `average_shortest_path_length` by Bellman-Ford skips the + pairs that NaN and inf edges leave apart, though its test for a graph in pieces counts them. + """ + if any(_read_apart(G)): + raise NotImplementedError(f"{name} with a NaN or infinite weight is left to networkx") diff --git a/graphblas_algorithms/nxapi/centrality/closeness.py b/graphblas_algorithms/nxapi/centrality/closeness.py index 8f4dd21..0ef718c 100644 --- a/graphblas_algorithms/nxapi/centrality/closeness.py +++ b/graphblas_algorithms/nxapi/centrality/closeness.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run +from .._utils import can_run, check_dijkstra_weights from ..exception import NodeNotFound __all__ = ["closeness_centrality"] @@ -19,6 +19,7 @@ def closeness_centrality(G, u=None, distance=None, wf_improved=True, *, sp=None) if (reason := _without_sp({"sp": sp})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight=distance) + check_dijkstra_weights(G, "closeness_centrality") if u is not None and u not in G: # NetworkX's answer is its shortest-path function's, which `distance` picks; Dijkstra's # hashes `u` first, so an unhashable `u` is a TypeError there. @@ -26,13 +27,7 @@ def closeness_centrality(G, u=None, distance=None, wf_improved=True, *, sp=None) raise NodeNotFound(f"Source {u} is not in G") hash(u) raise NodeNotFound(f"Node {u} not found in graph") - try: - result = algorithms.closeness_centrality( - G, None if u is None else [u], wf_improved=wf_improved - ) - except algorithms.exceptions.Unbounded as e: - # What NetworkX's Dijkstra raises on a negative cycle. - raise ValueError("Contradictory paths found:", "negative weights?") from e + result = algorithms.closeness_centrality(G, None if u is None else [u], wf_improved=wf_improved) if u is not None: return result.get(G._key_to_id[u], 0.0) # A dict, which NetworkX's `incremental_closeness_centrality` edits as its `prev_cc`. diff --git a/graphblas_algorithms/nxapi/centrality/harmonic.py b/graphblas_algorithms/nxapi/centrality/harmonic.py index 4d7401a..acf0e2c 100644 --- a/graphblas_algorithms/nxapi/centrality/harmonic.py +++ b/graphblas_algorithms/nxapi/centrality/harmonic.py @@ -1,20 +1,17 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import nbunch_keys +from .._utils import check_dijkstra_weights, nbunch_keys __all__ = ["harmonic_centrality"] def harmonic_centrality(G, nbunch=None, distance=None, sources=None): G = to_graph(G, weight=distance) + check_dijkstra_weights(G, "harmonic_centrality") keys = nbunch_keys(G, nbunch, unique=True) sources = nbunch_keys(G, sources, unique=True) - try: - result = algorithms.harmonic_centrality(G, keys, sources) - except algorithms.exceptions.Unbounded as e: - # What NetworkX's Dijkstra raises on a negative cycle. - raise ValueError("Contradictory paths found:", "negative weights?") from e + result = algorithms.harmonic_centrality(G, keys, sources) scores = G.vector_to_dict(result) # A dict over `nbunch` alone, with NetworkX's integer 0 for a node no source reaches. return {key: scores.get(key, 0) for key in (G if keys is None else keys)} diff --git a/graphblas_algorithms/nxapi/distance_measures.py b/graphblas_algorithms/nxapi/distance_measures.py index dc8e353..4b3c5aa 100644 --- a/graphblas_algorithms/nxapi/distance_measures.py +++ b/graphblas_algorithms/nxapi/distance_measures.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from ._utils import can_run, nbunch_keys +from ._utils import can_run, check_dijkstra_weights, nbunch_keys from .exception import NetworkXError __all__ = ["center", "diameter", "eccentricity", "harmonic_diameter", "periphery", "radius"] @@ -30,7 +30,7 @@ def _without_sp(bound): def _answer(G, kernel, *args, **kwargs): - """`kernel(G, ...)`, raising what NetworkX raises where a length is infinite or unbounded.""" + """`kernel(G, ...)`, raising what NetworkX raises where a length is infinite.""" try: return kernel(G, *args, **kwargs) except algorithms.exceptions.NoPath as e: @@ -42,9 +42,6 @@ def _answer(G, kernel, *args, **kwargs): else: message = "Found infinite path length because the graph is not connected" raise NetworkXError(message) from e - except algorithms.exceptions.Unbounded as e: - # What NetworkX's Dijkstra raises on a negative cycle. - raise ValueError("Contradictory paths found:", "negative weights?") from e def _in_node_order(G, v): @@ -62,6 +59,7 @@ def eccentricity(G, v=None, sp=None, weight=None): if (reason := _with_nodes_without_sp({"G": G, "sp": sp})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "eccentricity") keys = nbunch_keys(G, v, unique=True) ecc = G.vector_to_dict(_answer(G, algorithms.eccentricity, keys)) if v in G: @@ -76,6 +74,7 @@ def diameter(G, e=None, usebounds=False, weight=None): if e is not None: return max(e.values()) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "diameter") return _answer(G, algorithms.diameter, usebounds=usebounds is True) @@ -86,6 +85,7 @@ def radius(G, e=None, usebounds=False, weight=None): if e is not None: return min(e.values()) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "radius") return _answer(G, algorithms.radius, usebounds=usebounds is True) @@ -96,6 +96,7 @@ def periphery(G, e=None, usebounds=False, weight=None): if e is not None: return _extreme_nodes(e, max) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "periphery") return _in_node_order(G, _answer(G, algorithms.periphery, usebounds=usebounds is True)) @@ -106,6 +107,7 @@ def center(G, e=None, usebounds=False, weight=None): if e is not None: return _extreme_nodes(e, min) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "center") return _in_node_order(G, _answer(G, algorithms.center, usebounds=usebounds is True)) @@ -114,4 +116,5 @@ def harmonic_diameter(G, sp=None, *, weight=None): if (reason := _without_sp({"sp": sp})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "harmonic_diameter") return _answer(G, algorithms.harmonic_diameter) diff --git a/graphblas_algorithms/nxapi/generators/ego.py b/graphblas_algorithms/nxapi/generators/ego.py index 32d562e..c1c904e 100644 --- a/graphblas_algorithms/nxapi/generators/ego.py +++ b/graphblas_algorithms/nxapi/generators/ego.py @@ -1,7 +1,8 @@ -from graphblas_algorithms import algorithms, generators +from graphblas_algorithms import generators from graphblas_algorithms.classes._utils import PRESERVE from graphblas_algorithms.classes.digraph import to_graph +from .._utils import check_dijkstra_weights from ..exception import NodeNotFound __all__ = ["ego_graph"] @@ -16,15 +17,10 @@ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None): if distance is None: raise NodeNotFound(f"Source {n} is not in G") raise NodeNotFound(f"Node {n} not found in graph") - try: - return generators.ego_graph( - G, - n, - radius=radius, - center=center, - undirected=undirected, - is_weighted=distance is not None and G._weight == distance, - ) - except algorithms.exceptions.Unbounded as e: - # What NetworkX's Dijkstra raises on a negative cycle. - raise ValueError("Contradictory paths found:", "negative weights?") from e + is_weighted = distance is not None and G._weight == distance + if is_weighted: + # NetworkX walks `distance` with Dijkstra. + check_dijkstra_weights(G, "ego_graph") + return generators.ego_graph( + G, n, radius=radius, center=center, undirected=undirected, is_weighted=is_weighted + ) diff --git a/graphblas_algorithms/nxapi/shortest_paths/dense.py b/graphblas_algorithms/nxapi/shortest_paths/dense.py index 8434f3c..174a96f 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/dense.py +++ b/graphblas_algorithms/nxapi/shortest_paths/dense.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import check_dense_nodelist +from .._utils import check_dense_nodelist, check_finite_weights, check_float_sums from ..exception import NetworkXError, NetworkXUnbounded __all__ = ["floyd_warshall", "floyd_warshall_numpy", "floyd_warshall_predecessor_and_distance"] @@ -9,6 +9,8 @@ def floyd_warshall(G, weight="weight"): G = to_graph(G, weight=weight) + check_finite_weights(G, "floyd_warshall") + check_float_sums(G, "floyd_warshall") try: D = algorithms.floyd_warshall(G, is_weighted=weight is not None) except algorithms.exceptions.Unbounded as e: @@ -19,6 +21,8 @@ def floyd_warshall(G, weight="weight"): def floyd_warshall_predecessor_and_distance(G, weight="weight"): G = to_graph(G, weight=weight) + check_finite_weights(G, "floyd_warshall_predecessor_and_distance") + check_float_sums(G, "floyd_warshall_predecessor_and_distance") try: P, D = algorithms.floyd_warshall_predecessor_and_distance(G, is_weighted=weight is not None) except algorithms.exceptions.Unbounded as e: @@ -31,6 +35,8 @@ def floyd_warshall_predecessor_and_distance(G, weight="weight"): def floyd_warshall_numpy(G, nodelist=None, weight="weight"): G = to_graph(G, weight=weight) + check_finite_weights(G, "floyd_warshall_numpy") + check_float_sums(G, "floyd_warshall_numpy") if nodelist is not None: if not (len(nodelist) == len(G) == len(set(nodelist))): raise NetworkXError("nodelist must contain every node in G with no repeats.") diff --git a/graphblas_algorithms/nxapi/shortest_paths/generic.py b/graphblas_algorithms/nxapi/shortest_paths/generic.py index cdcf0fe..9b1ed59 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/generic.py +++ b/graphblas_algorithms/nxapi/shortest_paths/generic.py @@ -1,7 +1,12 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run +from .._utils import ( + can_run, + check_dijkstra_weights, + check_finite_weights, + check_float_sums, +) from ..exception import NetworkXError, NetworkXPointlessConcept, NetworkXUnbounded, NodeNotFound __all__ = ["average_shortest_path_length", "has_path"] @@ -32,6 +37,13 @@ def average_shortest_path_length(G, weight=None, method=None): if method is None: method = "unweighted" if weight is None else "dijkstra" G = to_graph(G, weight=None if method == "unweighted" else weight) + if method == "dijkstra": + check_dijkstra_weights(G, "average_shortest_path_length") + elif method == "bellman-ford": + # NetworkX's Bellman-Ford drops an edge of NaN or +inf weight (`bellman_ford_graph`), + # but its test for a graph in pieces counts it, and its sum skips the pairs it leaves. + check_finite_weights(G, "average_shortest_path_length") + check_float_sums(G, "average_shortest_path_length") try: return algorithms.average_shortest_path_length(G) except algorithms.exceptions.PointlessConcept as e: @@ -40,7 +52,5 @@ def average_shortest_path_length(G, weight=None, method=None): strongly = "strongly " if G.is_directed() else "" raise NetworkXError(f"Graph is not {strongly}connected.") from e except algorithms.exceptions.Unbounded as e: - if method == "bellman-ford": - raise NetworkXUnbounded("Negative cycle detected.") from e - # What NetworkX's Dijkstra raises on a negative cycle. - raise ValueError("Contradictory paths found:", "negative weights?") from e + # Only Bellman-Ford serves negative weights. + raise NetworkXUnbounded("Negative cycle detected.") from e diff --git a/graphblas_algorithms/nxapi/shortest_paths/weighted.py b/graphblas_algorithms/nxapi/shortest_paths/weighted.py index 2f2a016..7bd68df 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/weighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/weighted.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import normalize_chunksize, partition +from .._utils import bellman_ford_graph, normalize_chunksize, partition from ..exception import NetworkXNoPath, NetworkXUnbounded, NodeNotFound __all__ = [ @@ -18,8 +18,14 @@ def all_pairs_bellman_ford_path_length(G, weight="weight", *, chunksize="10 MiB" # Chunksize indicates for how many source nodes to compute at one time. # The default is to choose the number of rows so the result, if dense, # will be about 10MB. - G = to_graph(G, weight=weight) + G = bellman_ford_graph(to_graph(G, weight=weight), "all_pairs_bellman_ford_path_length") chunksize = normalize_chunksize(chunksize, len(G) * G._A.dtype.np_type.itemsize, len(G)) + # Not a generator itself: a weight left to NetworkX is refused here, when called, where + # NetworkX's dispatcher can still answer the call. + return _all_pairs_bellman_ford_path_length(G, chunksize) + + +def _all_pairs_bellman_ford_path_length(G, chunksize): if chunksize is None: # All at once try: @@ -53,7 +59,7 @@ def _check_source(G, source): def single_source_bellman_ford_path_length(G, source, weight="weight"): # TODO: what if weight is a function? - G = to_graph(G, weight=weight) + G = bellman_ford_graph(to_graph(G, weight=weight), "single_source_bellman_ford_path_length") _check_source(G, source) try: d = algorithms.single_source_bellman_ford_path_length(G, source) @@ -64,7 +70,7 @@ def single_source_bellman_ford_path_length(G, source, weight="weight"): def bellman_ford_path(G, source, target, weight="weight"): # TODO: what if weight is a function? - G = to_graph(G, weight=weight) + G = bellman_ford_graph(to_graph(G, weight=weight), "bellman_ford_path") if source == target: if source not in G: raise NodeNotFound(f"Node {source} is not found in the graph") @@ -83,7 +89,7 @@ def bellman_ford_path(G, source, target, weight="weight"): def bellman_ford_path_length(G, source, target, weight="weight"): - G = to_graph(G, weight=weight) + G = bellman_ford_graph(to_graph(G, weight=weight), "bellman_ford_path_length") if source == target: if source not in G: raise NodeNotFound(f"Node {source} not found in graph") @@ -104,5 +110,5 @@ def bellman_ford_path_length(G, source, target, weight="weight"): def negative_edge_cycle(G, weight="weight", heuristic=True): # TODO: what if weight is a function? # TODO: use a heuristic to try to stop early - G = to_graph(G, weight=weight) + G = bellman_ford_graph(to_graph(G, weight=weight), "negative_edge_cycle") return algorithms.negative_edge_cycle(G) diff --git a/graphblas_algorithms/nxapi/tests/test_distance_centrality.py b/graphblas_algorithms/nxapi/tests/test_distance_centrality.py index 8866a02..c28e153 100644 --- a/graphblas_algorithms/nxapi/tests/test_distance_centrality.py +++ b/graphblas_algorithms/nxapi/tests/test_distance_centrality.py @@ -183,14 +183,13 @@ def test_a_distance_that_is_not_an_attribute_name_is_declined(name, distance): @pytest.mark.parametrize("name", sorted(NAMES)) @pytest.mark.parametrize("cls", [nx.DiGraph, nx.Graph], ids=["directed cycle", "undirected edge"]) -def test_a_negative_cycle_raises_what_networkx_raises(name, cls): +def test_a_negative_cycle_is_left_to_networkx(name, cls): edges = [(0, 1, {"cost": 1.0}), (1, 2, {"cost": -3.0}), (2, 0, {"cost": 1.0})] G = cls(edges if cls is nx.DiGraph else edges[:2]) - with pytest.raises(ValueError, match="negative weights") as theirs: + with pytest.raises(ValueError, match="negative weights"): NAMES[name](G, distance="cost") - with pytest.raises(ValueError, match="negative weights") as ours: + with pytest.raises(NotImplementedError): NAMES[name](G, distance="cost", backend="graphblas") - assert (type(ours.value), str(ours.value)) == (type(theirs.value), str(theirs.value)) @pytest.mark.parametrize("name", sorted(NAMES)) @@ -277,6 +276,10 @@ def spy(G, nodes=None, **kwargs): def test_harmonic_skips_only_a_length_of_zero(cost): """NetworkX skips `d == 0`, a source's own and one across a zero-weight edge.""" G = nx.DiGraph([(0, 1, {"cost": cost}), (1, 2, {"cost": 2.0})]) + if cost < 0: + with pytest.raises(NotImplementedError): + nx.harmonic_centrality(G, distance="cost", backend="graphblas") + return got = nx.harmonic_centrality(G, distance="cost", backend="graphblas") assert_matches(got, nx.harmonic_centrality(G, distance="cost")) assert (got[1] == 0) is (cost == 0) @@ -380,13 +383,12 @@ def G(): assert got == pytest.approx(want, rel=1e-12, abs=0) -def test_closeness_scores_a_negative_total_zero(): - """NetworkX divides only where the lengths sum above 0; node 2 is the control.""" +def test_closeness_with_a_negative_weight_is_left_to_networkx(): + """NetworkX scores 0 where the lengths sum to 0 or less, as node 1's do here.""" G = nx.DiGraph([(0, 1, {"cost": -1.0}), (1, 2, {"cost": 2.0})]) - got = nx.closeness_centrality(G, distance="cost", wf_improved=False, backend="graphblas") - assert got[1] == 0.0 - assert got[2] == pytest.approx(2 / 3) - assert_matches(got, nx.closeness_centrality(G, distance="cost", wf_improved=False)) + assert nx.closeness_centrality(G, distance="cost", wf_improved=False)[1] == 0.0 + with pytest.raises(NotImplementedError): + nx.closeness_centrality(G, distance="cost", wf_improved=False, backend="graphblas") @pytest.mark.skipif( diff --git a/graphblas_algorithms/nxapi/tests/test_distance_measures.py b/graphblas_algorithms/nxapi/tests/test_distance_measures.py index de9e088..19e09d1 100644 --- a/graphblas_algorithms/nxapi/tests/test_distance_measures.py +++ b/graphblas_algorithms/nxapi/tests/test_distance_measures.py @@ -40,6 +40,13 @@ def raised(name, G, **kwargs): return type(info.value), str(info.value) +def declined(name, G, **kwargs): + """graphblas, called by name, leaves the call to NetworkX: here, a negative weight.""" + with pytest.raises(NotImplementedError): + answer(name, G, backend="graphblas", **kwargs) + return True + + def weighted(G, weights=(1.0, 2.0, 3.5, 0.5)): H = G.copy() for i, (_u, _v, data) in enumerate(H.edges(data=True)): @@ -128,13 +135,12 @@ def test_an_attribute_no_edge_carries_is_the_unweighted_graph(name): @pytest.mark.parametrize("name", ECCENTRICITY_NAMES) @pytest.mark.parametrize("shape", sorted(NEGATIVE_CYCLES)) -def test_a_negative_cycle_raises_what_networkx_raises(name, shape): +def test_a_negative_cycle_is_left_to_networkx(name, shape): cls, edges = NEGATIVE_CYCLES[shape] G = cls() G.add_weighted_edges_from(edges, weight="cost") - expected = raised(name, G, weight="cost") - assert expected[0] is ValueError - assert raised(name, G, weight="cost", backend="graphblas") == expected + assert raised(name, G, weight="cost")[0] is ValueError + assert declined(name, G, weight="cost") def with_isolated_node(): @@ -168,7 +174,7 @@ def test_a_graph_in_pieces_raises_what_networkx_raises(name, shape, usebounds): ) @pytest.mark.parametrize("cls", [nx.Graph, nx.DiGraph]) @pytest.mark.parametrize("cost", [1.0, 1], ids=["float", "integer"]) -def test_a_negative_cycle_in_a_later_piece_raises_what_networkx_raises(name, usebounds, cls, cost): +def test_a_negative_cycle_in_a_later_piece_is_left_to_networkx(name, usebounds, cls, cost): """NetworkX walks from one node at a time, so its first walk decides which error comes first. Its bounded search (`usebounds is True`, undirected) walks first from a node of greatest @@ -179,7 +185,8 @@ def test_a_negative_cycle_in_a_later_piece_raises_what_networkx_raises(name, use if cls is nx.DiGraph: G.add_edge(3, 2, cost=-cost) kwargs = {"weight": "cost"} if usebounds is None else {"weight": "cost", "usebounds": usebounds} - assert raised(name, G, backend="graphblas", **kwargs) == raised(name, G, **kwargs) + assert raised(name, G, **kwargs) + assert declined(name, G, **kwargs) @pytest.mark.parametrize("name", FROM_ECCENTRICITY) @@ -429,17 +436,20 @@ def test_harmonic_diameter_matches_networkx(shape, weight): @pytest.mark.parametrize("cost", [-1.0, 0.0], ids=["negative", "zero"]) def test_harmonic_diameter_skips_only_a_length_of_zero(cost): G = nx.DiGraph([(0, 1, {"cost": cost}), (1, 2, {"cost": 2.0}), (2, 0, {"cost": 1.0})]) + if cost < 0: + assert declined("harmonic_diameter", G, weight="cost") + return expected = nx.harmonic_diameter(G, weight="cost") assert_close(nx.harmonic_diameter(G, weight="cost", backend="graphblas"), expected) @pytest.mark.parametrize("shape", sorted(NEGATIVE_CYCLES)) -def test_harmonic_diameter_on_a_negative_cycle_raises_what_networkx_raises(shape): +def test_harmonic_diameter_on_a_negative_cycle_is_left_to_networkx(shape): cls, edges = NEGATIVE_CYCLES[shape] G = cls() G.add_weighted_edges_from(edges, weight="cost") - expected = raised("harmonic_diameter", G, weight="cost") - assert raised("harmonic_diameter", G, weight="cost", backend="graphblas") == expected + assert raised("harmonic_diameter", G, weight="cost") + assert declined("harmonic_diameter", G, weight="cost") def test_harmonic_diameter_declines_a_precomputed_sp(): @@ -488,21 +498,28 @@ def test_average_with_unweighted_method_ignores_the_weight(): def test_average_of_a_negative_edge_without_a_negative_cycle(): + """Served by Bellman-Ford; left to NetworkX by Dijkstra.""" G = nx.DiGraph([(0, 1, {"cost": -1.0}), (1, 2, {"cost": 3.0}), (2, 0, {"cost": 1.0})]) - for method in ["dijkstra", "bellman-ford"]: - expected = nx.average_shortest_path_length(G, weight="cost", method=method) - got = nx.average_shortest_path_length(G, weight="cost", method=method, backend="graphblas") - assert_close(got, expected) + method = "bellman-ford" + expected = nx.average_shortest_path_length(G, weight="cost", method=method) + got = nx.average_shortest_path_length(G, weight="cost", method=method, backend="graphblas") + assert_close(got, expected) + for method in [None, "dijkstra"]: + assert declined("average_shortest_path_length", G, weight="cost", method=method) @pytest.mark.parametrize("shape", sorted(NEGATIVE_CYCLES)) @pytest.mark.parametrize("method", [None, "dijkstra", "bellman-ford"]) def test_average_on_a_negative_cycle_raises_what_networkx_raises(shape, method): + """Served by Bellman-Ford; left to NetworkX by Dijkstra.""" cls, edges = NEGATIVE_CYCLES[shape] G = cls() G.add_weighted_edges_from(edges, weight="cost") kwargs = {"weight": "cost", "method": method} expected = raised("average_shortest_path_length", G, **kwargs) + if method != "bellman-ford": + assert declined("average_shortest_path_length", G, **kwargs) + return assert raised("average_shortest_path_length", G, backend="graphblas", **kwargs) == expected @@ -518,6 +535,9 @@ def test_average_in_pieces_raises_what_networkx_raises(shape): G.add_node(9) expected = raised("average_shortest_path_length", G, weight="cost") assert expected[0] is nx.NetworkXError + if shape not in DISCONNECTED: + assert declined("average_shortest_path_length", G, weight="cost") + return assert raised("average_shortest_path_length", G, weight="cost", backend="graphblas") == expected diff --git a/graphblas_algorithms/nxapi/tests/test_ego.py b/graphblas_algorithms/nxapi/tests/test_ego.py index 496d9de..f7897af 100644 --- a/graphblas_algorithms/nxapi/tests/test_ego.py +++ b/graphblas_algorithms/nxapi/tests/test_ego.py @@ -84,12 +84,11 @@ def test_an_absent_source_raises_node_not_found(distance): ids=["undirected", "undirected-int", "uniform", "directed", "self-loop", "far-self-loop"], ) @pytest.mark.parametrize("radius", [1.0, 100.0]) -def test_a_negative_cycle_raises_what_networkx_raises(cls, edges, radius): +def test_a_negative_cycle_is_left_to_networkx(cls, edges, radius): """NetworkX's Dijkstra meets the cycle as a contradiction and raises ValueError.""" G = cls() G.add_weighted_edges_from(edges) - with pytest.raises(ValueError, match="Contradictory paths") as theirs: + with pytest.raises(ValueError, match="Contradictory paths"): nx.ego_graph(G, 0, radius=radius, distance="weight") - with pytest.raises(ValueError, match="Contradictory paths") as ours: + with pytest.raises(NotImplementedError): nx.ego_graph(G, 0, radius=radius, distance="weight", backend="graphblas") - assert ours.value.args == theirs.value.args diff --git a/graphblas_algorithms/nxapi/tests/test_nonfinite_weights.py b/graphblas_algorithms/nxapi/tests/test_nonfinite_weights.py new file mode 100644 index 0000000..e39544a --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_nonfinite_weights.py @@ -0,0 +1,657 @@ +"""NaN, infinite and negative weights in the shortest-path names, as NetworkX walks them. + +NetworkX's Bellman-Ford relaxes an edge only where the length through it is less than the length +its head has, which through a NaN or +inf weight it never is: such edges add nothing, and the +names here drop them. Its Dijkstra, behind eccentricity and the names like it, reads a NaN or a +negative weight in the order it pops its heap: those calls are left to NetworkX, as are +Floyd-Warshall's with a NaN or an infinite weight, and any with a -inf weight, as is a loop of +an undirected graph that may weigh -inf, as its conversion holds NaN for one. So are +Bellman-Ford's and Floyd-Warshall's with weights heavy enough that a sum of them may pass the +largest float, or, with a negative one, so far apart that a sum may lose one. Each case is +checked three ways: NetworkX itself, graphblas called by name, and NetworkX with +graphblas first in its priority. +""" + +import math +from collections.abc import Iterator +from contextlib import contextmanager +from itertools import pairwise + +import networkx as nx +import numpy as np +import pytest +from networkx.utils.backends import _registered_algorithms + +from graphblas_algorithms.interface import Dispatcher + +NAN, INF = float("nan"), float("inf") + + +@contextmanager +def _first(kind): + """Put graphblas first in NetworkX's `kind` priority, with `fallback_to_nx` off. + + NetworkX answers a call declined here on its own graphs all the same. + """ + config = nx.config.backend_priority + before = list(getattr(config, kind)) if kind in config else None + fallback = nx.config.fallback_to_nx + setattr(config, kind, ["graphblas"]) + nx.config.fallback_to_nx = False + try: + yield + finally: + if before is None: + delattr(config, kind) + else: + setattr(config, kind, before) + nx.config.fallback_to_nx = fallback + + +@pytest.fixture +def backend_priority(): + return _first + + +BELLMAN_FORD = [ + "single_source_bellman_ford_path_length", + "all_pairs_bellman_ford_path_length", + "bellman_ford_path_length", + "bellman_ford_path", + "negative_edge_cycle", +] +DIJKSTRA = [ + "eccentricity", + "diameter", + "radius", + "center", + "periphery", + "harmonic_diameter", + "closeness_centrality", + "harmonic_centrality", + "wiener_index", + "schultz_index", + "gutman_index", + "hyper_wiener_index", + "average_shortest_path_length", + "ego_graph", +] +FLOYD_WARSHALL = [ + "floyd_warshall", + "floyd_warshall_predecessor_and_distance", + "floyd_warshall_numpy", +] +UNDIRECTED_ONLY = {"schultz_index", "gutman_index", "hyper_wiener_index"} + + +def call(name, G, backend=None): + """`name` on `G` as a test calls it, with `weight` (or `distance`) naming "weight".""" + kwargs = {} if backend is None else {"backend": backend} + if name == "average_shortest_path_length bellman-ford": + return _registered_algorithms["average_shortest_path_length"]( + G, weight="weight", method="bellman-ford", **kwargs + ) + func = _registered_algorithms[name] + last = list(G)[-1] + if name == "single_source_bellman_ford_path_length": + return func(G, 0, weight="weight", **kwargs) + if name in {"bellman_ford_path_length", "bellman_ford_path"}: + return func(G, 0, last, weight="weight", **kwargs) + if name in {"closeness_centrality", "harmonic_centrality"}: + return func(G, distance="weight", **kwargs) + if name == "ego_graph": + return func(G, 0, radius=2.5, distance="weight", **kwargs) + return func(G, weight="weight", **kwargs) + + +def plain(value): + """A result as dicts, lists and numbers, NaN as the string "nan" so that it equals itself.""" + value = Dispatcher.convert_to_nx(value) + if isinstance(value, Iterator): + value = list(value) + if isinstance(value, nx.Graph): + edges = [(u, v) if value.is_directed() else tuple(sorted((u, v))) for u, v in value.edges] + return sorted(value.nodes), sorted(edges), sorted(map(repr, value.edges(data=True))) + if isinstance(value, np.ndarray): + return plain(value.tolist()) + if hasattr(value, "items"): + return {key: plain(val) for key, val in value.items()} + if isinstance(value, list | tuple): + return [plain(item) for item in value] + if isinstance(value, float) and math.isnan(value): + return "nan" + return value + + +def outcome(name, G, mode, backend_priority=None, *, message=False): + """("value", result) or ("raised", exception type), on a copy of `G`. + + ("declined", None) when graphblas, called by name, raises NotImplementedError. With + `message`, a raised exception is ("raised", type, its str). + """ + G = G.copy() + try: + if mode == "automatic": + kind = "generators" if name == "ego_graph" else "algos" + with backend_priority(kind): + return "value", plain(call(name, G)) + return "value", plain(call(name, G, mode)) + except NotImplementedError: + if mode == "graphblas": + return "declined", None + raise + except Exception as exc: + if message: + return "raised", type(exc).__name__, str(exc) + return "raised", type(exc).__name__ + + +def weighted(edges, weights, directed=False): + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(1 + max(max(edge) for edge in edges))) + for (u, v), w in zip(edges, weights, strict=True): + G.add_edge(u, v, weight=w) + return G + + +def random_weighted(seed, directed, values): + """A sparse random graph with edges weighing `values` at random, on a cycle through all.""" + rng = np.random.default_rng(seed) + n = 12 + pairs = [(u, v) for u in range(n) for v in range(n) if u != v and (directed or u < v)] + edges = [pair for pair in pairs if rng.random() < 0.22] + cycle = [(i, (i + 1) % n) for i in range(n)] # connected, as the Dijkstra names need + edges = list(dict.fromkeys(cycle + edges)) + weights = [values[int(k)] for k in rng.integers(0, len(values), len(edges))] + return weighted(edges, weights, directed) + + +PATH = [(0, 1), (1, 2), (2, 3), (3, 4), (0, 4)] + + +def graphs(special): + """Graphs where some edges weigh `special`, each by a label.""" + out = {} + for directed in [False, True]: + d = "directed" if directed else "undirected" + # The middle edge of a path, with a long way round: a node beyond it is reached the + # other way, or not at all when directed. + out[f"{d} path"] = weighted(PATH, [1.0, special, 2.0, 1.5, 10.0], directed) + out[f"{d} every edge"] = weighted(PATH, [special] * len(PATH), directed) + for seed in range(3): + out[f"{d} random {seed}"] = random_weighted(seed, directed, [special, 1.0, 2.5, 0.5]) + return out + + +NAN_GRAPHS = graphs(NAN) +INF_GRAPHS = graphs(INF) +MINUS_INF_GRAPHS = graphs(-INF) +NEGATIVE_GRAPHS = graphs(-1.0) +FINITE_GRAPHS = graphs(3.0) + + +def applies(name, G): + return not (name in UNDIRECTED_ONLY and G.is_directed()) + + +def path_length(G, path): + """The length of `path` in `G`, or None where it is not a path of finite weights.""" + total = 0 + for u, v in pairwise(path): + if v not in G[u] or not math.isfinite(w := G[u][v].get("weight", 1)): + return None + total += w + return total + + +def assert_as_networkx(name, G, got, expected): + """The same outcome, with float lengths within rounding and a path valid and as short.""" + if name == "bellman_ford_path" and expected[0] == "value": + path = got[1] + assert got[0] == "value" + assert (path[0], path[-1]) == (expected[1][0], expected[1][-1]) + length = path_length(G, path) + assert length is not None + assert length == pytest.approx(path_length(G, expected[1]), rel=1e-12) + else: + assert got == expected or _close(got, expected) + + +@pytest.mark.parametrize("label", sorted(NAN_GRAPHS)) +@pytest.mark.parametrize("name", BELLMAN_FORD) +def test_bellman_ford_drops_the_edges_networkx_never_relaxes(name, label, backend_priority): + for G in [NAN_GRAPHS[label], INF_GRAPHS[label]]: + expected = outcome(name, G, "networkx") + assert_as_networkx(name, G, outcome(name, G, "graphblas"), expected) # served + assert_as_networkx(name, G, outcome(name, G, "automatic", backend_priority), expected) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_a_node_beyond_a_nan_edge_has_no_length(directed): + G = weighted(PATH, [1.0, NAN, 2.0, 1.5, 10.0], directed) + got = nx.single_source_bellman_ford_path_length(G, 0, weight="weight", backend="graphblas") + expected = ( + {0: 0, 1: 1.0, 4: 10.0, 3: 11.5, 2: 13.5} if not directed else {0: 0, 1: 1.0, 4: 10.0} + ) + assert dict(got) == expected + assert dict(got) == nx.single_source_bellman_ford_path_length(G, 0, weight="weight") + + +def test_a_graph_of_nan_edges_reaches_only_the_source(): + G = weighted(PATH, [NAN] * len(PATH)) + got = nx.single_source_bellman_ford_path_length(G, 0, weight="weight", backend="graphblas") + assert dict(got) == {0: 0} + assert type(got[0]) is int # as NetworkX's 0 + + +@pytest.mark.parametrize("label", sorted(MINUS_INF_GRAPHS)) +@pytest.mark.parametrize("name", [*BELLMAN_FORD, *DIJKSTRA]) +def test_minus_inf_is_left_to_networkx(name, label, backend_priority): + if name not in _registered_algorithms or not applies(name, MINUS_INF_GRAPHS[label]): + pytest.skip("not in this NetworkX, or not for this graph") + G = MINUS_INF_GRAPHS[label] + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +def looped(special, directed, at, negative): + """PATH (with -1.0 for its third edge if `negative`) and a self-loop of `special` at `at`. + + Node 5 is reached from no other node. + """ + weights = [1.0, 2.0, -1.0 if negative else 2.0, 1.5, 10.0] + G = weighted(PATH, weights, directed) + G.add_edge(at, at, weight=special) + return G + + +LOOPED = { + f"{'directed' if directed else 'undirected'} {special} at {at}{' negative' * negative}": ( + looped(special, directed, at, negative) + ) + for directed in [False, True] + for special in [-INF, INF, NAN, -1.0, 2.0, -1e308, 1e308] + for at in [0, 2, 5] + for negative in [False, True] +} + + +def may_weigh_minus_inf(G): + """A -inf weight, or a self-loop of an undirected graph that its conversion makes NaN or -inf. + + The conversion adds an undirected loop's weight in twice and takes it out once: inf and -inf + give NaN, -1e308 gives -inf and 1e308 gives inf. + """ + for u, v, w in G.edges(data="weight"): + if u == v and not G.is_directed(): + held = w + w - w + if math.isnan(held) or held == -INF: + return True + elif w == -INF: + return True + return False + + +def may_overflow(G): + """Whether `n * n` times `G`'s heaviest finite weight, doubled, reaches the largest float.""" + weights = [abs(w) for *_, w in G.edges(data="weight") if math.isfinite(w)] + return max(weights, default=0.0) * len(G) ** 2 * 2 >= np.finfo(float).max + + +@pytest.mark.parametrize("label", sorted(LOOPED)) +@pytest.mark.parametrize("name", BELLMAN_FORD) +def test_self_loops_as_networkx(name, label, backend_priority): + """A loop that may weigh -inf, or of +-1e308 on a directed graph, is left to NetworkX. + + Any other is served, as NetworkX. Sums of +-1e308 may overflow; an undirected graph's + conversion makes a loop of 1e308 inf, which is dropped. + """ + G = LOOPED[label] + expected = outcome(name, G, "networkx", message=True) + got = outcome(name, G, "graphblas", message=True) + if may_weigh_minus_inf(G) or (may_overflow(G) and G.is_directed()): + assert got == ("declined", None) + else: + assert_as_networkx(name, G, got, expected) + assert_as_networkx( + name, G, outcome(name, G, "automatic", backend_priority, message=True), expected + ) + + +@pytest.mark.parametrize("at", [0, 2]) +def test_an_undirected_minus_inf_loop_is_left_to_networkx(at, backend_priority): + """From the loop NetworkX gives -inf lengths; from another node it finds the -1.0 edge's cycle. + + Which it gives follows the order it walks. The conversion holds NaN for the loop, which + alone does not tell it from a NaN or inf loop. + """ + from graphblas_algorithms import Graph, nxapi + + G = looped(-INF, False, at, True) + assert Graph.from_networkx(G, weight="weight")._A.diag().to_dict() == { + at: pytest.approx(NAN, nan_ok=True) + } + expected = dict.fromkeys(range(5), -INF) + other = at + 1 + assert nx.single_source_bellman_ford_path_length(G, at) == expected + with pytest.raises(nx.NetworkXUnbounded): + nx.single_source_bellman_ford_path_length(G, other) + with backend_priority("algos"): + assert nx.single_source_bellman_ford_path_length(G, at) == expected + assert nx.bellman_ford_path_length(G, at, other) == -INF + with pytest.raises(nx.NetworkXUnbounded): + nx.single_source_bellman_ford_path_length(G, other) + with pytest.raises(NotImplementedError, match="-inf"): + nxapi.single_source_bellman_ford_path_length(G, at) + H = looped(-INF, False, at, False) + with backend_priority("algos"): + assert nx.negative_edge_cycle(H) == nx.negative_edge_cycle(H, backend="networkx") + + +@pytest.mark.parametrize("special", [NAN, INF]) +def test_a_directed_nan_or_inf_loop_is_still_served(special): + G = looped(special, True, 2, False) + got = nx.single_source_bellman_ford_path_length(G, 0, backend="graphblas") + assert dict(got) == nx.single_source_bellman_ford_path_length(G, 0) + + +def overflowing(): + """Graphs of finite weights whose sums pass the largest float, each by a label.""" + out = {} + # -1e308 + -1e308 is -inf, and lengths stop falling before the cycle is found; with + # isolated nodes the rounds left over make the parents of 1 and 2 point at each other. + G = weighted([(0, 1), (1, 2), (2, 3), (3, 4)], [1.0, -1e308, -1.0, 1.0]) + G.add_nodes_from([5, 6]) + out["undirected -1e308 edge and isolated nodes"] = G + out["undirected -1e308 on the path"] = weighted(PATH, [1.0, -1e308, 2.0, 1.5, 10.0]) + out["directed -1e308 twice"] = weighted(PATH, [-1e308, -1e308, 2.0, 1.5, 10.0], True) + # A NaN as well: the heaviest weight is read past it + out["directed -1e308 twice, NaN"] = weighted(PATH, [-1e308, -1e308, NAN, 1.5, 10.0], True) + # NetworkX does not relax an edge to a length of inf: node 2 is not reached + out["directed 1e308 twice"] = weighted(PATH, [1e308, 1e308, 2.0, 1.5, 10.0], True) + G = weighted([(0, 1), (1, 2), (2, 3), (3, 4), (2, 1)], [1.0, -1e307, -1.0, 1.0, -1e307], True) + G.add_nodes_from(range(40)) + out["directed -1e307 cycle on 40 nodes"] = G + return out + + +OVERFLOWING = overflowing() + + +SUMMED = [*BELLMAN_FORD, "average_shortest_path_length bellman-ford", *FLOYD_WARSHALL] + + +@pytest.mark.parametrize("label", sorted(OVERFLOWING)) +@pytest.mark.parametrize("name", SUMMED) +def test_weights_whose_sums_may_overflow_are_left_to_networkx(name, label, backend_priority): + G = OVERFLOWING[label] + assert outcome(name, G, "graphblas") == ("declined", None) + expected = outcome(name, G, "networkx", message=True) + assert outcome(name, G, "automatic", backend_priority, message=True) == expected + + +@pytest.mark.parametrize("name", ["single_source_bellman_ford_path_length", "floyd_warshall_numpy"]) +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_the_overflow_bound(name, sign): + """Declined where 5 * 5 times the heaviest weight, doubled, reaches the largest float. + + The other weights are near it, so that none is lost from a sum. + """ + limit = np.finfo(float).max / (2 * 5 * 5) + for w, declined in [(limit * 0.999, False), (limit * 1.001, True)]: + G = weighted(PATH, [w / 2, w / 3, sign * w, w / 4, w / 5], directed=True) + got = outcome(name, G, "graphblas") + if declined: + assert got == ("declined", None) + else: + assert_as_networkx(name, G, got, outcome(name, G, "networkx")) + + +def losing(): + """Graphs with a negative weight that a length may lose, each by a label.""" + cycle = [(0, 1), (1, 2), (2, 1)] + return { + # 1e300 - 1 is 1e300: NetworkX's loop never shortens the length of 1 + "directed loop lost to 1e300": weighted([(0, 1), (1, 1)], [1e300, -1.0], True), + # 3 * 2**52 - 1 rounds to 3 * 2**52: lost to a sum of three weights, where no weight is + # 2**53 times another + "directed loop lost to three of 2**52": weighted( + [(0, 1), (1, 2), (2, 3), (3, 3)], [2.0**52] * 3 + [-1.0], True + ), + "directed cycle lost to 1e300": weighted(cycle, [1e300, -1.0, 0.5], True), + "undirected -1 beside 1e300": weighted(PATH, [1e300, -1.0, 2.0, 1.5, 10.0]), + "directed -1 beside 1e300, no cycle": weighted(PATH, [1e300, -1.0, 2.0, 1.5, 10.0], True), + } + + +LOSING = losing() + + +@pytest.mark.parametrize("label", sorted(LOSING)) +@pytest.mark.parametrize("name", SUMMED) +def test_weights_so_far_apart_that_a_sum_may_lose_one_are_left_to_networkx( + name, label, backend_priority +): + G = LOSING[label] + assert outcome(name, G, "graphblas") == ("declined", None) + expected = outcome(name, G, "networkx", message=True) + assert outcome(name, G, "automatic", backend_priority, message=True) == expected + + +def test_a_loop_whose_weight_is_lost_gives_networkx_lengths(backend_priority): + """From 0 the loop is lost; `negative_edge_cycle` walks from a node of its own, and finds it.""" + G = LOSING["directed loop lost to 1e300"] + assert nx.single_source_bellman_ford_path_length(G, 0) == {0: 0, 1: 1e300} + assert nx.negative_edge_cycle(G) + with backend_priority("algos"): + assert nx.single_source_bellman_ford_path_length(G, 0) == {0: 0, 1: 1e300} + assert nx.negative_edge_cycle(G) + + +@pytest.mark.parametrize("name", ["single_source_bellman_ford_path_length", "floyd_warshall"]) +def test_the_lost_weight_bound(name): + """Declined where 5 * 5 times the heaviest weight, doubled, reaches 2**53 times the lightest. + + The lightest nonzero weight is 0.5; a zero weight and a NaN one are passed over. + """ + limit = 0.5 * 2**53 / (2 * 5 * 5) + for w, declined in [(limit * 0.999, False), (limit * 1.001, True)]: + G = weighted(PATH, [w, 0.0, -0.5, 1.5, 10.0], directed=True) + G.add_edge(4, 4, weight=NAN) + if name.startswith("floyd"): + G.remove_edge(4, 4) + got = outcome(name, G, "graphblas") + if declined: + assert got == ("declined", None) + else: + assert_as_networkx(name, G, got, outcome(name, G, "networkx")) + + +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", SUMMED) +def test_weights_far_apart_with_none_negative_are_served(name, directed): + """A lost positive weight leaves a length within rounding of NetworkX's.""" + G = weighted(PATH, [1e300, 1e-300, 2.0, 1.5, 10.0], directed) + got = outcome(name, G, "graphblas") + assert got[0] != "declined" + assert_as_networkx(name, G, got, outcome(name, G, "networkx")) + + +@pytest.mark.parametrize("name", SUMMED) +def test_integer_weights_far_apart_are_served(name): + """Integer sums lose nothing; their own bound is far off here.""" + G = weighted(PATH, [10**15, -1, 2, 1, 10], directed=True) + got = outcome(name, G, "graphblas") + assert got[0] != "declined" + assert_as_networkx(name, G, got, outcome(name, G, "networkx")) + + +def test_the_lightest_weight_is_read_once_and_only_beside_a_negative_one(): + from graphblas_algorithms import DiGraph + from graphblas_algorithms.nxapi import floyd_warshall, single_source_bellman_ford_path_length + + G = DiGraph.from_networkx(FINITE_GRAPHS["directed path"], weight="weight") + single_source_bellman_ford_path_length(G, 0) + floyd_warshall(G) + assert "lightest_finite" not in G._cache + H = weighted(PATH, [0.0, -0.25, 2.0, 1.5, 10.0], directed=True) + H.add_edge(4, 4, weight=NAN) + G = DiGraph.from_networkx(H, weight="weight") + single_source_bellman_ford_path_length(G, 0) + assert G._cache["lightest_finite"] == 0.25 + G._cache["lightest_finite"] = 1e-300 + with pytest.raises(NotImplementedError, match="lose"): + single_source_bellman_ford_path_length(G, 0) + + +def test_a_walk_of_parents_that_comes_back_on_itself_raises(): + """It would otherwise never end, and its list would grow until memory ran out.""" + from graphblas import Vector + + from graphblas_algorithms import Graph + from graphblas_algorithms.algorithms.shortest_paths.weighted import ( + _reconstruct_path_from_parents as walk, + ) + + G = Graph.from_networkx(FINITE_GRAPHS["undirected path"], weight="weight") + parents = Vector.from_coo([0, 1, 2, 3, 4], [0, 0, 1, 2, 3]) + assert walk(G, parents, 0, 4, 4) == [0, 1, 2, 3, 4] + parents[1] = 2 + with pytest.raises(RuntimeError, match="come back"): + walk(G, parents, 0, 4, 4) + + +@pytest.mark.parametrize("label", sorted(NEGATIVE_GRAPHS)) +@pytest.mark.parametrize("name", DIJKSTRA) +def test_a_negative_weight_is_left_to_networkx_dijkstra(name, label, backend_priority): + """NetworkX's answer, or its exception with its message, whichever its walk meets.""" + if name not in _registered_algorithms or not applies(name, NEGATIVE_GRAPHS[label]): + pytest.skip("not in this NetworkX, or not for this graph") + G = NEGATIVE_GRAPHS[label] + assert outcome(name, G, "graphblas") == ("declined", None) + expected = outcome(name, G, "networkx", message=True) + assert outcome(name, G, "automatic", backend_priority, message=True) == expected + + +@pytest.mark.parametrize("label", sorted(NEGATIVE_GRAPHS)) +@pytest.mark.parametrize("name", [*BELLMAN_FORD, "average_shortest_path_length bellman-ford"]) +def test_a_negative_weight_is_served_by_bellman_ford(name, label, backend_priority): + G = NEGATIVE_GRAPHS[label] + expected = outcome(name, G, "networkx", message=True) + assert_as_networkx(name, G, outcome(name, G, "graphblas", message=True), expected) + assert_as_networkx( + name, G, outcome(name, G, "automatic", backend_priority, message=True), expected + ) + + +def test_the_negative_weight_check_reads_the_conversion_once(): + from graphblas_algorithms import Graph + from graphblas_algorithms.nxapi import eccentricity + + G = Graph.from_networkx(FINITE_GRAPHS["undirected random 0"], weight="weight") + eccentricity(G, weight="weight") + assert G._cache["has_negative_edges+"] is False + assert G._cache["read_apart"] == (False, False, False) + + +@pytest.mark.parametrize("first", ["eccentricity", "single_source_bellman_ford_path_length"]) +def test_negative_edge_cycle_after_another_name_on_the_same_graph(first, backend_priority): + """The sign of the weights another name read once made a self-loop of 2.0 count as negative. + + The calls share NetworkX's cached conversion, which keeps what each name learned of it. + """ + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 0, 2.0), (0, 1, 2.0), (1, 2, -1.0), (2, 3, 1.0), (3, 0, 5.0)]) + assert nx.negative_edge_cycle(G, backend="networkx") is False + with backend_priority("algos"): + if first == "eccentricity": + nx.eccentricity(G, weight="weight") # left to NetworkX for the negative weight + else: + nx.single_source_bellman_ford_path_length(G, 0) + assert nx.negative_edge_cycle(G) is False + + +@pytest.mark.parametrize("label", sorted(NAN_GRAPHS)) +@pytest.mark.parametrize("name", [*DIJKSTRA, *FLOYD_WARSHALL]) +def test_nan_is_left_to_networkx_where_it_walks_its_own_way(name, label, backend_priority): + if name not in _registered_algorithms or not applies(name, NAN_GRAPHS[label]): + pytest.skip("not in this NetworkX, or not for this graph") + G = NAN_GRAPHS[label] + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +@pytest.mark.parametrize("label", sorted(INF_GRAPHS)) +@pytest.mark.parametrize("name", DIJKSTRA) +def test_plus_inf_is_served_where_dijkstra_adds_it(name, label, backend_priority): + if name not in _registered_algorithms or not applies(name, INF_GRAPHS[label]): + pytest.skip("not in this NetworkX, or not for this graph") + G = INF_GRAPHS[label] + expected = outcome(name, G, "networkx") + got = outcome(name, G, "graphblas") + assert got[0] != "declined" + assert got == expected or _close(got, expected) + assert outcome(name, G, "automatic", backend_priority) == got + + +@pytest.mark.parametrize("special", [INF, -INF]) +@pytest.mark.parametrize("name", [*FLOYD_WARSHALL, "average_shortest_path_length bellman-ford"]) +def test_infinite_weights_are_left_to_networkx_here(name, special, backend_priority): + for G in graphs(special).values(): + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +@pytest.mark.parametrize("label", sorted(NAN_GRAPHS)) +def test_average_by_bellman_ford_leaves_nan_to_networkx(label, backend_priority): + name = "average_shortest_path_length bellman-ford" + G = NAN_GRAPHS[label] + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +@pytest.mark.parametrize("name", [*BELLMAN_FORD, *DIJKSTRA, *FLOYD_WARSHALL]) +def test_finite_weights_are_still_served(name): + if name not in _registered_algorithms: + pytest.skip("not in this NetworkX") + for G in FINITE_GRAPHS.values(): + if applies(name, G): + assert outcome(name, G, "graphblas")[0] != "declined" + + +def test_a_nan_in_another_attribute_does_not_stop_ego_graph(backend_priority): + # The edges' "weight" holds NaN, but the radius is walked by "cost", which none carries. + G = NAN_GRAPHS["undirected path"] + expected = nx.ego_graph(G, 0, radius=2, distance="cost") + got = nx.ego_graph(G.copy(), 0, radius=2, distance="cost", backend="graphblas") + assert plain(got) == plain(expected) + + +def test_the_graph_without_the_dropped_edges_is_made_once(): + from graphblas_algorithms import Graph + from graphblas_algorithms.nxapi import single_source_bellman_ford_path_length + + G = Graph.from_networkx(NAN_GRAPHS["undirected random 0"], weight="weight") + single_source_bellman_ford_path_length(G, 0) + H = G._cache["relaxable"] + single_source_bellman_ford_path_length(G, 1) + assert G._cache["relaxable"] is H + assert H._A.nvals < G._A.nvals + assert not np.isnan(H._A.to_coo()[2]).any() + + +def _close(got, expected): + """Equal but for float sums added in another order, as with finite weights.""" + if got[0] != expected[0]: + return False + + def walk(a, b): + if isinstance(a, dict) and isinstance(b, dict): + return a.keys() == b.keys() and all(walk(a[k], b[k]) for k in a) + if isinstance(a, list) and isinstance(b, list): + return len(a) == len(b) and all(walk(x, y) for x, y in zip(a, b, strict=True)) + if isinstance(a, float) and isinstance(b, float) and math.isfinite(a): + return a == pytest.approx(b, rel=1e-12) + return a == b + + return walk(got[1], expected[1]) diff --git a/graphblas_algorithms/nxapi/tests/test_wiener.py b/graphblas_algorithms/nxapi/tests/test_wiener.py index 2bdc3e5..8968b0b 100644 --- a/graphblas_algorithms/nxapi/tests/test_wiener.py +++ b/graphblas_algorithms/nxapi/tests/test_wiener.py @@ -107,18 +107,20 @@ def test_the_null_graph(name, directed): @pytest.mark.parametrize("name", WEIGHTED) -def test_a_negative_cycle_raises_as_networkxs_dijkstra_does(name): +def test_a_negative_cycle_is_left_to_networkx(name): G = weighted(nx.path_graph(4), [1, -1, 2]) with pytest.raises(ValueError, match="Contradictory paths found"): + getattr(nx, name)(G, weight="weight") + with pytest.raises(NotImplementedError): getattr(nx, name)(G, weight="weight", backend="graphblas") -def test_a_directed_negative_edge_without_a_negative_cycle_is_answered(): +def test_a_directed_negative_edge_without_a_negative_cycle_is_left_to_networkx(): + """NetworkX's Dijkstra may answer or raise here, by the order it walks.""" G = nx.DiGraph() G.add_weighted_edges_from([(0, 1, 4), (1, 2, -2), (2, 0, 5), (0, 2, 1)]) - lengths = dict(nx.floyd_warshall(G, weight="weight")) - expected = sum(d for row in lengths.values() for d in row.values()) - assert nx.wiener_index(G, weight="weight", backend="graphblas") == expected + with pytest.raises(NotImplementedError): + nx.wiener_index(G, weight="weight", backend="graphblas") @pytest.mark.parametrize("name", ["schultz_index", "gutman_index"]) diff --git a/graphblas_algorithms/nxapi/wiener.py b/graphblas_algorithms/nxapi/wiener.py index add0617..8d2d409 100644 --- a/graphblas_algorithms/nxapi/wiener.py +++ b/graphblas_algorithms/nxapi/wiener.py @@ -2,21 +2,18 @@ from graphblas_algorithms.classes.digraph import to_graph from graphblas_algorithms.utils import not_implemented_for -from ._utils import can_run +from ._utils import can_run, check_dijkstra_weights from .exception import NetworkXPointlessConcept __all__ = ["gutman_index", "hyper_wiener_index", "schultz_index", "wiener_index"] def _answer(kernel, G): - """`kernel(G)`, raising what NetworkX raises for the null graph and a negative cycle.""" + """`kernel(G)`, raising what NetworkX raises for the null graph.""" try: return kernel(G) except algorithms.exceptions.PointlessConcept as e: raise NetworkXPointlessConcept(*e.args) from e - except algorithms.exceptions.Unbounded as e: - # What NetworkX's Dijkstra raises on a negative cycle. - raise ValueError("Contradictory paths found:", "negative weights?") from e def _no_node_named_weight(name): @@ -36,6 +33,7 @@ def hook(bound): def wiener_index(G, weight=None): G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "wiener_index") return _answer(algorithms.wiener_index, G) @@ -47,6 +45,7 @@ def schultz_index(G, weight=None): if (reason := _schultz_rule({"G": G, "weight": weight})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "schultz_index") return _answer(algorithms.schultz_index, G) @@ -58,6 +57,7 @@ def gutman_index(G, weight=None): if (reason := _gutman_rule({"G": G, "weight": weight})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "gutman_index") return _answer(algorithms.gutman_index, G) @@ -65,4 +65,5 @@ def gutman_index(G, weight=None): @not_implemented_for("multigraph") def hyper_wiener_index(G, weight=None): G = to_graph(G, weight=weight) + check_dijkstra_weights(G, "hyper_wiener_index") return _answer(algorithms.hyper_wiener_index, G) diff --git a/graphblas_algorithms/tests/test_properties.py b/graphblas_algorithms/tests/test_properties.py index 09cddf6..32a8b43 100644 --- a/graphblas_algorithms/tests/test_properties.py +++ b/graphblas_algorithms/tests/test_properties.py @@ -1,4 +1,6 @@ -"""An off-diagonal reduction read from the triangle matrices the cache already holds.""" +"""Properties read from what the cache already holds.""" + +from itertools import permutations import networkx as nx import pytest @@ -22,3 +24,50 @@ def test_a_reduction_over_the_off_diagonal_after_the_triangle_matrices(cls, key) off_diagonal = G._A.select("offdiag").new() expected = off_diagonal.reduce_scalar("max" if key.startswith("max") else "min").new() assert G.get_property(key).value == expected.value + + +SIGN_FACTS = [ + "has_negative_diagonal", + "has_negative_edges+", + "has_negative_edges-", + "has_self_edges", +] +READ_FIRST = [ + None, + "min_element+", + "max_element+", + "min_element-", + "max_element-", + "min_diagonal", + "is_iso", + "offdiag", +] + + +@pytest.mark.parametrize("loop", [None, -2.0, 0.0, 2.0]) +@pytest.mark.parametrize("edge", [-1.0, 1.0]) +@pytest.mark.parametrize("cls", [Graph, DiGraph], ids=["Graph", "DiGraph"]) +def test_the_sign_facts_do_not_depend_on_what_was_read_before(cls, edge, loop): + """Each fact the cache infers from others is the same in whatever order they are read. + + A negative weight off the diagonal once made a cached `min_element+` or + `has_negative_edges+` stand for a negative self-loop. + """ + G = nx.DiGraph() if cls is DiGraph else nx.Graph() + G.add_weighted_edges_from([(0, 1, 1.0), (1, 2, edge), (2, 3, 3.0)]) + if loop is not None: + G.add_edge(0, 0, weight=loop) + negative_loop = loop is not None and loop < 0 + expected = { + "has_negative_diagonal": negative_loop, + "has_negative_edges+": edge < 0 or negative_loop, + "has_negative_edges-": edge < 0, + "has_self_edges": loop is not None, + } + for first in READ_FIRST: + for order in permutations(SIGN_FACTS): + H = cls.from_networkx(G, weight="weight") + if first is not None: + H.get_property(first) + got = {fact: H.get_property(fact) for fact in order} + assert got == expected, (first, order)