From 4dca4dc58afd08ff5fbec7174e620269b3f12fbf Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Tue, 1 Dec 2026 21:08:02 -0600 Subject: [PATCH] Let NetworkX answer where integer weight sums would not be exact NetworkX adds integer weights as Python ints, exactly. Here they are added in 64 bits, which wrap past 2**63, and a matrix holds every weight in the one dtype numpy infers for them all, so an int past 2**53 beside a float, or an np.uint64 beside a signed int, is held as a float and rounds: 2**53 - 1 and np.uint64(4) add to 2**53 + 4. Where a sum could reach 2**63 the kernels raise IntegerOverflowError, an OverflowError that is also a NotImplementedError, so NetworkX's dispatcher tries the next backend: under backend_priority NetworkX answers for a NetworkX graph, and for one of this backend's graphs when fallback_to_nx is on. With backend="graphblas" NetworkX raises its own NotImplementedError from it, and a direct call gets an OverflowError. NetworkX answers with the arguments it was given, so a one-shot iterator of nodes, read before the sums are bounded, would reach it spent: cut_size, volume, average_degree_connectivity, degree_pearson_correlation_coefficient and eccentricity leave a weighted call with one to NetworkX. all_pairs_bellman_ford_path_length and node_degree_xy bound their sums when called, while NetworkX can still answer, rather than when the first item is read. A conversion that holds ints as floats is kept and marked. The names that add the weights as exact ints, compare them, or give them back decline at their call, on that conversion or one NetworkX serves from its cache, and NetworkX answers; a name NetworkX declares as reading weights is one of them unless it is listed with a float answer. Those names, such as pagerank, NetworkX computes in floats too, or from exact sums that a float sum of weights of one sign matches to a few parts in 2**53. They are served unless the weights can cancel in a float sum: ints held as floats of both signs, or ints of both signs large enough that their sums pass 2**53, which they add as floats too. The conversion records which, so a call reads one attribute. An int below 2**53 beside a float is served, as NetworkX adds it in floats too. The additional_docs notes say which weights are left to NetworkX. --- _nx_graphblas/__init__.py | 70 +-- _nx_graphblas/core.py | 58 +-- graphblas_algorithms/algorithms/_helpers.py | 9 +- .../algorithms/assortativity/mixing.py | 5 +- graphblas_algorithms/algorithms/cuts.py | 2 +- graphblas_algorithms/algorithms/exceptions.py | 9 + .../algorithms/shortest_paths/dense.py | 2 +- .../algorithms/shortest_paths/weighted.py | 8 +- graphblas_algorithms/algorithms/wiener.py | 12 +- graphblas_algorithms/interface.py | 202 +++++++- graphblas_algorithms/nxapi/_utils.py | 44 +- .../nxapi/assortativity/connectivity.py | 3 +- .../nxapi/assortativity/correlation.py | 6 +- .../nxapi/assortativity/pairs.py | 8 +- graphblas_algorithms/nxapi/cuts.py | 4 +- .../nxapi/distance_measures.py | 4 +- .../nxapi/shortest_paths/weighted.py | 10 +- graphblas_algorithms/nxapi/tests/_overflow.py | 44 ++ .../nxapi/tests/test_assortativity.py | 36 +- graphblas_algorithms/nxapi/tests/test_cuts.py | 16 +- .../nxapi/tests/test_overflow.py | 185 +++++-- .../nxapi/tests/test_wiener.py | 19 +- graphblas_algorithms/tests/test_dispatch.py | 475 +++++++++++++++++- graphblas_algorithms/tests/test_roundtrip.py | 2 +- 24 files changed, 1053 insertions(+), 180 deletions(-) create mode 100644 graphblas_algorithms/nxapi/tests/_overflow.py diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 32ee9eb..be433ea 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -197,55 +197,55 @@ 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_degree_connectivity": "Complex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Raises OverflowError\nrather than add integer weights where a node's weighted degree, or its sum of each\nweight times the neighbor's degree, could reach 2**63 (by the sum of the absolute values\nit adds).", - "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\nComplex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Raises OverflowError\nrather than add integer weights where a node's weighted degree, or its sum of each\nweight times the neighbor's degree, could reach 2**63 (by the sum of the absolute values\nit adds).", + "all_pairs_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "average_degree_connectivity": "Complex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).\nWith `weight`, an iterator `nodes` is left to NetworkX.", + "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\nComplex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).", "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.", + "bellman_ford_path": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", "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.', + "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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight 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".', "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.", - "degree_assortativity_coefficient": '`nodes` one node, or an iterator, which NetworkX reads twice, is left to NetworkX.\nThe coefficient is taken from the counts of degree pairs in closed form, not from\nNetworkX\'s dense matrix, so it may differ from NetworkX\'s in its last bits. Where every\nx-degree, or every y-degree, is the same it is nan, where NetworkX\'s 0 / 0 may round to\nan infinity; where integer weighted degrees pass 2**31, NetworkX squares them in 64-bit\nintegers, which wrap, and here it is Pearson\'s r of the pairs, as\n`degree_pearson_correlation_coefficient` gives.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights. Float weights are added in another order than NetworkX\'s, so a weighted\ndegree may differ from NetworkX\'s in its last bits.\nRaises OverflowError rather than add integer weights where a weighted degree could reach\n2**63: where the absolute values one node adds (a self-loop\'s twice) sum to that.', - "degree_mixing_dict": 'The keys come in increasing order of degree, not in the order NetworkX meets them.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nRaises OverflowError rather than add integer weights where a weighted degree could reach\n2**63: where the absolute values one node adds (a self-loop\'s twice) sum to that.', - "degree_mixing_matrix": 'Without `mapping`, the degrees are numbered in increasing order; NetworkX numbers\nthem in the order a Python set of them iterates, which it documents as arbitrary.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nRaises OverflowError rather than add integer weights where a weighted degree could reach\n2**63: where the absolute values one node adds (a self-loop\'s twice) sum to that.', - "degree_pearson_correlation_coefficient": 'SciPy\'s `pearsonr` of the same pairs in another order, so the value may differ from\nNetworkX\'s in its last bits; past 2**24 stored edges it is taken from the counts of\ndegree pairs.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights. Float weights are added in another order than NetworkX\'s, so a weighted\ndegree may differ from NetworkX\'s in its last bits.\nRaises OverflowError rather than add integer weights where a weighted degree could reach\n2**63: where the absolute values one node adds (a self-loop\'s twice) sum to that.', - "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.', - "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.', + "compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", + "cut_size": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more.\nWith `weight`, an iterator `S` or `T` is left to NetworkX.", + "degree_assortativity_coefficient": '`nodes` one node, or an iterator, which NetworkX reads twice, is left to NetworkX.\nThe coefficient is taken from the counts of degree pairs in closed form, not from\nNetworkX\'s dense matrix, so it may differ from NetworkX\'s in its last bits. Where every\nx-degree, or every y-degree, is the same it is nan, where NetworkX\'s 0 / 0 may round to\nan infinity; where integer weighted degrees pass 2**31, NetworkX squares them in 64-bit\nintegers, which wrap, and here it is Pearson\'s r of the pairs, as\n`degree_pearson_correlation_coefficient` gives.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights. Float weights are added in another order than NetworkX\'s, so a weighted\ndegree may differ from NetworkX\'s in its last bits.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', + "degree_mixing_dict": 'The keys come in increasing order of degree, not in the order NetworkX meets them.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', + "degree_mixing_matrix": 'Without `mapping`, the degrees are numbered in increasing order; NetworkX numbers\nthem in the order a Python set of them iterates, which it documents as arbitrary.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', + "degree_pearson_correlation_coefficient": 'SciPy\'s `pearsonr` of the same pairs in another order, so the value may differ from\nNetworkX\'s in its last bits; past 2**24 stored edges it is taken from the counts of\ndegree pairs.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights. Float weights are added in another order than NetworkX\'s, so a weighted\ndegree may differ from NetworkX\'s in its last bits.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.\nWith `weight`, an iterator `nodes` is left to NetworkX.', + "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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', + "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", + "eccentricity": 'A precomputed `sp`, the null graph, and with `weight` an iterator `v`, are\nleft 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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', "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`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and\ninteger weights are left to NetworkX where the number of nodes times the heaviest\nabsolute 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 as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.', + "floyd_warshall": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "floyd_warshall_predecessor_and_distance": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", "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.', + "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 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".', "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.", - "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.", + "hyper_wiener_index": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node's targets could reach 2**63.", + "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 as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are 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 as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are 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 as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are 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 as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", + "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are 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.", - "node_degree_xy": 'The pairs come by edge, both ends in node order, not in NetworkX\'s adjacency order.\nNetworkX\'s own `degree_mixing_dict` takes these degrees as keys.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nRaises OverflowError rather than add integer weights where a weighted degree could reach\n2**63: where the absolute values one node adds (a self-loop\'s twice) sum to that.', - "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.', - "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.", - "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.', + "negative_edge_cycle": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "node_degree_xy": 'The pairs come by edge, both ends in node order, not in NetworkX\'s adjacency order.\nNetworkX\'s own `degree_mixing_dict` takes these degrees as keys.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', + "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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight 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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', + "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", + "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.', + "single_source_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", + "volume": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more, or to 2**63 over the most times `S` names one node.\nWith `weight`, an iterator `S` is left to NetworkX.", + "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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.', # END: additional_docs } # fmt: on diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index 317e9e2..39a13ca 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -65,13 +65,14 @@ } # NetworkX adds integer weights as Python integers; here they are 64-bit (`checked_sum_type`). +# Past these bounds the kernels raise IntegerOverflowError, which NetworkX's dispatcher takes as +# NotImplementedError, so it tries the next backend: NetworkX itself for a NetworkX graph. _PATH_OVERFLOW = ( - "Raises OverflowError rather than add integer weights where the number of nodes times the\n" - "heaviest absolute weight reaches 2**62, as a length could then pass 2**63." + "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\n" + "weight reaches 2**62, as a length could then pass 2**63." ) _SUM_OVERFLOW = ( - "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\n" - "or more" + "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more" ) _NEGATIVE_EDGES = ( "Lengths are Bellman-Ford's, so a negative edge without a negative cycle is answered where\n" @@ -80,9 +81,8 @@ # 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" - "heaviest absolute weight reaches 2**62, or where the sum over one node's targets could\n" - "reach 2**63." + "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\n" + "weight reaches 2**62, or where the sum over one node's targets could reach 2**63." ) _ECCENTRICITY_BOUNDS = ( @@ -99,15 +99,14 @@ # The degree assortativity names add weights into weighted degrees. _DEGREE_OVERFLOW = ( - "Raises OverflowError rather than add integer weights where a weighted degree could reach\n" - "2**63: where the absolute values one node adds (a self-loop's twice) sum to that." + "Integer weights are left to NetworkX where a weighted degree could reach 2**63: where the\n" + "absolute values one node adds (a self-loop's twice) sum to that." ) _NEIGHBOR_DEGREE_WEIGHTS = ( "Complex weights are left to NetworkX. Float weights are added in another order than\n" - "NetworkX's, so a value may differ from NetworkX's in its last bits. Raises OverflowError\n" - "rather than add integer weights where a node's weighted degree, or its sum of each\n" - "weight times the neighbor's degree, could reach 2**63 (by the sum of the absolute values\n" - "it adds)." + "NetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\n" + "left to NetworkX where a node's weighted degree, or its sum of each weight times the\n" + "neighbor's degree, could reach 2**63 (by the sum of the absolute values it adds)." ) _DEGREES_AS_KEYS = ( 'On a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\n' @@ -136,7 +135,8 @@ "without a negative cycle is answered where NetworkX's Dijkstra raises\n" '"Contradictory paths found".' ), - "average_degree_connectivity": _NEIGHBOR_DEGREE_WEIGHTS, + "average_degree_connectivity": _NEIGHBOR_DEGREE_WEIGHTS + + "\nWith `weight`, an iterator `nodes` is left to NetworkX.", "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\n" + _NEIGHBOR_DEGREE_WEIGHTS, "bellman_ford_path": _PATH_OVERFLOW, @@ -159,7 +159,7 @@ "common_neighbor_centrality": ( "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX." ), - "cut_size": _SUM_OVERFLOW + ".", + "cut_size": _SUM_OVERFLOW + ".\nWith `weight`, an iterator `S` or `T` is left to NetworkX.", "degree_assortativity_coefficient": ( "`nodes` one node, or an iterator, which NetworkX reads twice, is left to NetworkX.\n" "The coefficient is taken from the counts of degree pairs in closed form, not from\n" @@ -182,13 +182,13 @@ "degree_pearson_correlation_coefficient": ( "SciPy's `pearsonr` of the same pairs in another order, so the value may differ from\n" "NetworkX's in its last bits; past 2**24 stored edges it is taken from the counts of\n" - "degree pairs.\n" + _DEGREES_AS_FLOATS + "degree pairs.\n" + + _DEGREES_AS_FLOATS + + "\nWith `weight`, an iterator `nodes` is left to NetworkX." ), "diameter": _ECCENTRICITY_BOUNDS, - "eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n" - + _NEGATIVE_EDGES - + "\n" - + _PATH_OVERFLOW, + "eccentricity": "A precomputed `sp`, the null graph, and with `weight` an iterator `v`, are\n" + "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" "The edges come by their first ends in node order, then by their second ends in node\n" @@ -201,9 +201,9 @@ ), "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." + 'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and\n' + "integer weights are left to NetworkX where the number of nodes times the heaviest\n" + "absolute weight reaches 2**62, as a length could then pass 2**63." ), "floyd_warshall": _PATH_OVERFLOW, "floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW, @@ -238,17 +238,19 @@ "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _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.", + "volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.\n" + "With `weight`, an iterator `S` is left to NetworkX.", "wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW, } # A graph these names return is rebuilt from one matrix, which holds its values in one type. # full_join rebuilds its inputs too, but leaves a weighted graph to NetworkX. _ONE_WEIGHT_TYPE = ( - "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\n" - "numbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\n" - "change a value, such as an int past 2**53 beside a float, is left to NetworkX." + "Edge weights come back in the one type their matrix holds: mixed ints and floats as\n" + "floats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\n" + "scalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\n" + "one beside a float, or that are all ints held as floats, such as `np.uint64` beside a\n" + "signed int, are left to NetworkX." ) for _name in ( "compose", diff --git a/graphblas_algorithms/algorithms/_helpers.py b/graphblas_algorithms/algorithms/_helpers.py index 3eddc1b..58ad43e 100644 --- a/graphblas_algorithms/algorithms/_helpers.py +++ b/graphblas_algorithms/algorithms/_helpers.py @@ -1,5 +1,7 @@ from graphblas import binary, dtypes, monoid, unary +from .exceptions import IntegerOverflowError + _ADVICE = ( "which 64-bit integers cannot hold; NetworkX computes with Python integers. Convert the " "weights to float, or call with backend='networkx'." @@ -39,7 +41,8 @@ def checked_sum_type(G, kind, *, count=1): Integers and booleans are added in INT64, where a smaller type would wrap sooner. INT64 still wraps silently at 2**63, and NetworkX's Python integers do not, so this raises - OverflowError when the bound for `kind` reaches it: + IntegerOverflowError, which NetworkX's dispatcher answers itself, when the bound for `kind` + reaches it: - "path": a length is a walk of at most `n` edges, and two lengths may be added, so `n` times the heaviest absolute value off the diagonal must stay below 2**62; - "sum": the absolute values, each counted up to `count` times, must sum to less than 2**63. @@ -52,7 +55,7 @@ def checked_sum_type(G, kind, *, count=1): least, greatest = G.get_properties("min_element- max_element-") heaviest = max(-least.get(0), greatest.get(0)) if A.nrows * heaviest >= 2**62: - raise OverflowError( + raise IntegerOverflowError( f"integer edge weights up to {heaviest} on {A.nrows} nodes could make a path " f"length reach 2**63, {_ADVICE}" ) @@ -64,7 +67,7 @@ def checked_sum_type(G, kind, *, count=1): total = G._cacheit("abs_sum+", _abs_sum, A) if total * count >= 2**63: times = f", counted up to {count} times," if count > 1 else "" - raise OverflowError( + raise IntegerOverflowError( f"integer edge weights whose absolute values sum to {total:.4g}{times} " f"could make a sum of them reach 2**63, {_ADVICE}" ) diff --git a/graphblas_algorithms/algorithms/assortativity/mixing.py b/graphblas_algorithms/algorithms/assortativity/mixing.py index 8b9ee30..5b046e0 100644 --- a/graphblas_algorithms/algorithms/assortativity/mixing.py +++ b/graphblas_algorithms/algorithms/assortativity/mixing.py @@ -5,6 +5,7 @@ from graphblas.semiring import plus_pair, plus_second from .._helpers import _ADVICE, undirected_degrees +from ..exceptions import IntegerOverflowError __all__ = [ "check_int_sums", @@ -36,7 +37,7 @@ def _sum_type(G): def check_int_sums(G, bounds, what): - """Raise OverflowError unless an integer sum of `G`'s values stays inside INT64. + """Raise IntegerOverflowError unless an integer sum of `G`'s values stays inside INT64. `bounds` is a callable giving, from the absolute values of `G`'s matrix in FP64, a Vector whose entry for each node bounds the absolute value of each partial sum of that node's @@ -53,7 +54,7 @@ def check_int_sums(G, bounds, what): return largest = bound(unary.abs[dtypes.FP64](A).new()).reduce(monoid.max).get(0.0) if largest >= _SAFE_BOUND: - raise OverflowError( + raise IntegerOverflowError( f"integer edge weights give a node {what} of up to {largest:.4g} in absolute " f"value, so a sum of them could reach 2**63, {_ADVICE}" ) diff --git a/graphblas_algorithms/algorithms/cuts.py b/graphblas_algorithms/algorithms/cuts.py index aa54667..35566e0 100644 --- a/graphblas_algorithms/algorithms/cuts.py +++ b/graphblas_algorithms/algorithms/cuts.py @@ -20,7 +20,7 @@ def cut_size(G, S, T=None, *, is_weighted=False, dtype=None): """The weight of the edges between S and T (both ways when directed), or their number. Weights are added in `dtype`, or by default as `checked_sum_type` says: integers in INT64, - raising OverflowError where their sum could reach 2**63. + raising IntegerOverflowError where their sum could reach 2**63. """ if is_weighted and dtype is None: dtype = checked_sum_type(G, "sum") diff --git a/graphblas_algorithms/algorithms/exceptions.py b/graphblas_algorithms/algorithms/exceptions.py index 7c911c9..ecc21d4 100644 --- a/graphblas_algorithms/algorithms/exceptions.py +++ b/graphblas_algorithms/algorithms/exceptions.py @@ -20,3 +20,12 @@ class NoPath(GraphBlasAlgorithmException): class Unbounded(GraphBlasAlgorithmException): pass + + +class IntegerOverflowError(OverflowError, NotImplementedError): + """A sum of 64-bit integers could reach 2**63, where it would wrap. + + NetworkX adds integer weights as Python integers, which do not wrap. To a direct caller this + is an OverflowError. NetworkX's dispatcher takes it as NotImplementedError and tries the next + backend it is configured to, which answers exactly when it is NetworkX. + """ diff --git a/graphblas_algorithms/algorithms/shortest_paths/dense.py b/graphblas_algorithms/algorithms/shortest_paths/dense.py index 97eed59..99ad0e6 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/dense.py +++ b/graphblas_algorithms/algorithms/shortest_paths/dense.py @@ -17,7 +17,7 @@ def floyd_warshall_predecessor_and_distance( """The predecessors, or None, and the distances between every pair of nodes. `dtype` is the distances' dtype: by default the values' own, or INT64 for integers, which - raises OverflowError where a distance could reach 2**63. + raises IntegerOverflowError where a distance could reach 2**63. """ # By using `offdiag` instead of `G._A`, we ensure that D will not become dense. # Dense D may be better at times, but not including the diagonal will result in less work. diff --git a/graphblas_algorithms/algorithms/shortest_paths/weighted.py b/graphblas_algorithms/algorithms/shortest_paths/weighted.py index c0e5913..e6863f1 100644 --- a/graphblas_algorithms/algorithms/shortest_paths/weighted.py +++ b/graphblas_algorithms/algorithms/shortest_paths/weighted.py @@ -19,8 +19,8 @@ def _length_dtype(G, A, dtype=None): """`dtype`, or else the lengths' dtype over `A`, which is `G` without self-loops. A graph with no edge between two nodes has only zero lengths, NetworkX's integer 0. Other - lengths are added as `checked_sum_type` says, which raises OverflowError where integer ones - could reach 2**63. + lengths are added as `checked_sum_type` says, which raises IntegerOverflowError where + integer ones could reach 2**63. """ if dtype is not None: return dtype @@ -136,8 +136,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None) When True, the returned Matrix has the same shape as the input Matrix. dtype : dtype, optional The lengths' dtype. By default the values' own, or INT64 for integers, which raises - OverflowError where a length could reach 2**63; a caller whose answer is a float can - pass a floating-point type instead. + IntegerOverflowError where a length could reach 2**63; a caller whose answer is a float + can pass a floating-point type instead. """ # Same algorithms as in `single_source_bellman_ford_path_length`, but with # `Cur` as a Matrix with each row corresponding to a source node. diff --git a/graphblas_algorithms/algorithms/wiener.py b/graphblas_algorithms/algorithms/wiener.py index 138e9d1..63e39e2 100644 --- a/graphblas_algorithms/algorithms/wiener.py +++ b/graphblas_algorithms/algorithms/wiener.py @@ -7,7 +7,7 @@ from ._bfs import _bfs_plain from ._helpers import _ADVICE, undirected_degrees -from .exceptions import PointlessConcept +from .exceptions import IntegerOverflowError, PointlessConcept from .shortest_paths._distance_batches import distance_batches __all__ = ["gutman_index", "hyper_wiener_index", "schultz_index", "wiener_index"] @@ -18,8 +18,8 @@ def wiener_index(G): Infinite unless every node reaches every node. Integer lengths are summed exactly, as NetworkX sums its Python integers, so the result is an int on a directed graph and a float - otherwise. Raises OverflowError rather than let a source's sum of integer lengths reach - 2**63 in 64 bits. + otherwise. Raises IntegerOverflowError rather than let a source's sum of integer lengths + reach 2**63 in 64 bits. """ if not _connected(G): return math.inf @@ -94,8 +94,8 @@ def _total(G, rows): """The sum, over the batches of every source, of the per-source values `rows` lists. `rows(ids, D, check)` gets a batch and `check`, which turns a Vector of per-source sums of - terms in `D` into Python numbers, raising OverflowError first where an integer sum could - have wrapped. Integers are added as Python ints, so the total is exact. + terms in `D` into Python numbers, raising IntegerOverflowError first where an integer sum + could have wrapped. Integers are added as Python ints, so the total is exact. """ n = len(G) total = 0 @@ -108,7 +108,7 @@ def _total(G, rows): def check(sums, power, *, scale=1, longest=longest): # A per-source sum adds up to `n` terms of at most `scale * longest**power`. if longest is not None and n * scale * longest**power >= 2**63: - raise OverflowError( + raise IntegerOverflowError( f"integer lengths up to {longest} between {n} nodes could make a sum of " f"them reach 2**63, {_ADVICE}" ) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 4498fb5..01f9b1c 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -97,12 +97,12 @@ def _edge_value_problem(graph, attr): Anything else reaches scipy as an object or string dtype and raises ValueError, which NetworkX does not fall back on; an int from 2**63 up to 2**64 converts, but to a float beside a smaller int, so it is refused too. The matrix holds every value in the one dtype - numpy infers for them all, so where that is a float or complex, an int past 2**53 can - come back as another number (2**53 + 1 beside a float as 9007199254740992.0, a large - `np.uint64` beside a negative int the same way): refused as well. A change of type alone - is not refused: 1.0 for 1 beside a float, 1 for True beside an int. A numpy time and a - long double are refused whatever they sit beside: GraphBLAS has neither type, and - `int()` of a `timedelta64`, which subclasses `np.integer`, raises TypeError. + numpy infers for them all, so where that is a float or complex, an int past 2**53 is + refused as well, and so are values that are all ints (`_ints_held_as_floats` says why). + A change of type alone is not refused: 1.0 for 1 beside a float, 1 for True beside an + int. A numpy time and a long double are refused whatever they sit beside: GraphBLAS has + neither type, and `int()` of a `timedelta64`, which subclasses `np.integer`, raises + TypeError. """ import numpy as np @@ -118,6 +118,8 @@ def _edge_value_problem(graph, attr): "a GraphBLAS matrix" ) big_int = False # an int that a float64 might not hold exactly + unsigned = False # an np.uint64 beside a signed int makes ints floats + real = False # a float or complex: ints beside one are floats in NetworkX's sums too for _u, _v, datadict in graph.edges(data=True): if attr not in datadict: continue @@ -130,23 +132,98 @@ def _edge_value_problem(graph, attr): return unholdable elif isinstance(value, np.integer): big_int = big_int or abs(int(value)) > 2**53 + unsigned = unsigned or isinstance(value, np.unsignedinteger) elif not isinstance(value, holdable): return unholdable - if not big_int: + elif not isinstance(value, np.bool_): + real = True + if not (big_int or (unsigned and not real)): return None values = [datadict[attr] for _u, _v, datadict in graph.edges(data=True) if attr in datadict] held = np.array(values) # the dtype the conversion gives the matrix if held.dtype.kind in "fc": - for given, back in zip(values, held.tolist(), strict=True): - # Python compares an int with a float or complex exactly. - if isinstance(given, int | np.integer) and int(given) != back: - return ( - f"mixes ints past 2**53 with values that make its matrix {held.dtype}, " - "which would change those ints" - ) + return (_HELD_AS_FLOATS if real else _ALL_INTS_AS_FLOATS).format(held.dtype) return None +_HELD_AS_FLOATS = ( + "mixes ints past 2**53 with values that make its matrix {}, which would hold those ints as " + "floats" +) +_ALL_INTS_AS_FLOATS = "has only ints, which its matrix would hold as floats ({})" + + +def _ints_held_as_floats(graph, attr, G): + """Why `G`'s matrix, converted from `graph`'s `attr`, holds as floats ints NetworkX keeps. + + The matrix holds every value in the one dtype numpy infers for them all, and NetworkX adds + and compares ints as Python ints, exactly, where a sum of floats rounds past 2**53. Two + cases are marked on the conversion, and the names that add or compare the weights exactly + decline them (`_ints_as_floats_guard`): + - every value an int (a bool counts as one), held as floats all the same: an `np.uint64` + beside a signed int, or an int from 2**63 up beside a smaller one. Small ones then add in + floats too: 2**52 + 1 twice and np.uint64(5) do not sum exactly; + - an int past 2**53 beside a float. It may come back as another number (2**53 + 1 as + 9007199254740992.0), and where it does not, it adds in floats (2**63 and 1 to 2**63). + An int below 2**53 beside a float is not marked: NetworkX adds it in floats there too. + The matrix's values pick what to read of the graph: every value whole, for the first case, + read until a value given as a float; finite values of magnitude 2**53 or more, for the + second, read at those entries only. + """ + import numpy as np + + A = G._A + if A.dtype.np_type.kind not in "fc" or A.nvals == 0: + return None + rows, cols, values = A.to_coo(sort=False) + finite = np.isfinite(values) + if values.dtype.kind == "f" and finite.all() and (values == np.trunc(values)).all(): + # NetworkX reads a missing attribute as the int 1. + for _u, _v, value in graph.edges(data=attr, default=1): + if not isinstance(value, int | np.integer | np.bool_): + break + else: + return _ALL_INTS_AS_FLOATS.format(A.dtype.np_type) + big = finite & (np.abs(values.real) >= 2**53) + if big.any(): + id_to_key = G.id_to_key + for i, j in zip(rows[big].tolist(), cols[big].tolist(), strict=True): + value = graph.adj[id_to_key[i]][id_to_key[j]].get(attr, 1) + if isinstance(value, bool | np.bool_ | np.timedelta64): + continue + if isinstance(value, int | np.integer) and abs(int(value)) > 2**53: + return _HELD_AS_FLOATS.format(A.dtype.np_type) + return None + + +_BIG_INTS = "has ints whose absolute values sum past 2**52, which it adds as floats" + + +def _float_sums_cancel(G, marked): + """Whether float sums of `G`'s weights can cancel where NetworkX's exact int sums do not. + + The names in `_FLOAT_ANSWERS` add the weights as floats, where NetworkX adds ints exactly. + A sum of floats of one sign, zeros either way, rounds by a few parts in 2**53 of its exact + value; terms of both signs can cancel, and their sum rounds to anything, 0 included. These + are weights of both signs, then: ints held as floats (`marked`), and ints whose absolute + values, each counted twice, sum past 2**53. A sum of degrees counts a value at most twice, + in and out or at both ends of a self-loop, and a sum of ints within that bound is exact as + floats in any order. One int past 2**52 passes it, and so do many smaller ones: 2**52 + 1 + added three times as floats is 3 * 2**52 + 4. A complex value has no sign. + """ + from .algorithms._helpers import _abs_sum + + A = G._A + kind = A.dtype.np_type.kind + if marked and kind == "c": + return True + if not marked and kind != "i": + return False + # A matrix with weights has values: one with no edges converts without them. + lo, hi = (bound.get() for bound in G.get_properties("min_element+ max_element+")) + return lo < 0 < hi and (marked or G._cacheit("abs_sum+", _abs_sum, A) > 2**52) + + def _unrebuildable(graph, weight, preserve_edge_attrs, *, keeps_node_data=True): """Why a graph rebuilt from `graph` would not carry what NetworkX's own result does. @@ -530,6 +607,16 @@ def convert_from_nx( raise NotImplementedError( f"Edge attribute {weight!r} has values a GraphBLAS matrix cannot hold: {exc}" ) from exc + # Kept and marked, so that NetworkX caches a conversion the names with float answers + # can use; a refusal here would leave NetworkX's failed mark for every name. The names + # that add or compare the weights exactly decline at their call, before reading any + # argument, on this conversion or a cached one. The names with float answers decline + # weights whose float sums can cancel, which is recorded here too. + if weight is not None: + if problem := _ints_held_as_floats(graph, weight, G): + G._ints_as_floats = problem = f"edge attribute {weight!r} {problem}" + if _float_sums_cancel(G, marked=problem is not None): + G._float_sums_cancel = problem or f"edge attribute {weight!r} {_BIG_INTS}" # A rebuilt graph keeps the graph attributes too, which NetworkX before 3.7 does not # ask for on `reverse` when its conversion cache is off. if preserve_graph_attrs or declared.rebuilds_input: @@ -628,3 +715,90 @@ def key(testpath): for (test_name, keywords), reason in xfail.items(): if base_name == test_name and keywords.issubset(kset): item.add_marker(pytest.mark.xfail(reason=reason)) + + +# The names that read weights and answer in floats that NetworkX computes from them in floats +# too, or from exact sums whose rounding as floats stays within a float's: a few parts in +# 2**53 for each weight, where the weights are of one sign and so cannot cancel. They are served +# on ints held as floats too, and decline weights whose float sums can cancel: ints held as +# floats of both signs, or ints of both signs large enough to sum past 2**53 +# (`_float_sums_cancel`). The other names that read weights or carry edge data answer with +# integer sums, compare weights, or give the weights back, and decline ints held as floats +# whatever their signs (`_ints_as_floats_guard`). +_FLOAT_ANSWERS = frozenset( + { + "adjacency_matrix", + "average_clustering", + "average_neighbor_degree", + "average_shortest_path_length", + "closeness_centrality", + "clustering", + "conductance", + "degree_assortativity_coefficient", + "degree_pearson_correlation_coefficient", + "directed_modularity_matrix", + "edge_expansion", + "eigenvector_centrality", + "google_matrix", + "group_closeness_centrality", + "harmonic_centrality", + "harmonic_diameter", + "hits", + "katz_centrality", + "laplacian_matrix", + "mixing_expansion", + "modularity", + "modularity_matrix", + "normalized_cut_size", + "normalized_laplacian_matrix", + "overlapping_modularity", + "pagerank", + "tournament_matrix", + } +) + + +def _ints_as_floats_guard(name, func, *, float_answer=False): + """`func`, declining a graph whose matrix holds as floats ints NetworkX keeps exact. + + The conversion keeps such a graph and marks it (`_ints_held_as_floats`), so that NetworkX's + cache holds one for the names in `_FLOAT_ANSWERS`. This declines each call given one: the + call that made it, a later one NetworkX serves from its cache, or a call on a graph of this + backend's that came from one. With `float_answer`, the graph declined is instead one whose + float sums of its weights can cancel, as the conversion recorded (`_float_sums_cancel`): + ints held as floats of both signs, or ints of both signs large enough to sum past 2**53. + """ + if float_answer: + attr, does = "_float_sums_cancel", "adds weights of both signs, which can cancel" + else: + attr, does = "_ints_as_floats", "adds or compares weights as NetworkX's exact ints" + + @functools.wraps(func) + def call(*args, **kwargs): + for arg in (*args, *kwargs.values()): + if (problem := getattr(arg, attr, None)) is not None: + raise NotImplementedError(f"{name} {does}, and the {problem}; networkx serves it") + return func(*args, **kwargs) + + return call + + +def _guard_exact_names(): + """Guard every name that reads weights or gives edge data back; `_FLOAT_ANSWERS` by sign. + + What a name reads is what the running NetworkX declares for it, so a name added later is + guarded unless it is listed. A rebuilt graph is declined before conversion + (`_rebuild_refusal`). + """ + for name, func in list(vars(Dispatcher).items()): + if not callable(func): + continue + if name in _FLOAT_ANSWERS: + setattr(Dispatcher, name, _ints_as_floats_guard(name, func, float_answer=True)) + continue + declared = _declared(name) + if declared.attribute_parameters or declared.preserves_edge_attrs: + setattr(Dispatcher, name, _ints_as_floats_guard(name, func)) + + +_guard_exact_names() diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 72f728b..0e990a0 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -1,3 +1,4 @@ +from collections.abc import Iterator from math import ceil from numbers import Number @@ -132,13 +133,23 @@ def split_evenly(k, L): yield L[stop:] -def can_run(hook): - """Give the decorated wrapper `hook` as its rule in `Dispatcher.can_run`. +def can_run(*hooks): + """Give the decorated wrapper `hooks` as its rule in `Dispatcher.can_run`. - `hook(bound)` gets the call's arguments by NetworkX's parameter names, defaults applied, - before anything is converted, so a graph may be a NetworkX graph or one of this - backend's. It returns the reason to decline the call, or None to serve it. + Each `hook(bound)` gets the call's arguments by NetworkX's parameter names, defaults + applied, before anything is converted, so a graph may be a NetworkX graph or one of this + backend's. It returns the reason to decline the call, or None to serve it; the first + reason declines. """ + if len(hooks) == 1: + [hook] = hooks + else: + + def hook(bound): + for rule in hooks: + if (reason := rule(bound)) is not None: + return reason + return None def decorator(func): func._can_run = hook @@ -147,6 +158,29 @@ def decorator(func): return decorator +def iterators_read_before_sums(name, *parameters): + """A rule declining a weighted call that passes a one-shot iterator in `parameters`. + + The wrapper reads these node arguments before its kernel can find that 64-bit sums of + integer weights could overflow and raise IntegerOverflowError. NetworkX then answers with + the arguments it was given, and would get such an iterator already spent: a wrong answer, + with no error. Unweighted sums count edges or nodes, which cannot reach 2**63. + """ + + def rule(bound): + if bound.get("weight") is None: + return None + for parameter in parameters: + if isinstance(bound.get(parameter), Iterator): + return ( + f"{name} with `weight` reads an iterator `{parameter}` before it can find that " + "a sum would overflow, and NetworkX would then get it spent; networkx serves it" + ) + return None + + return rule + + def check_nodelist(G, nodelist, *, null_graph=True): """Refuse what NetworkX's `to_scipy_sparse_array` refuses, in the order it checks. diff --git a/graphblas_algorithms/nxapi/assortativity/connectivity.py b/graphblas_algorithms/nxapi/assortativity/connectivity.py index 741e94c..2f900ca 100644 --- a/graphblas_algorithms/nxapi/assortativity/connectivity.py +++ b/graphblas_algorithms/nxapi/assortativity/connectivity.py @@ -3,7 +3,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import nbunch_keys +from .._utils import can_run, iterators_read_before_sums, nbunch_keys from ..exception import NetworkXError from .mixing import weighted @@ -40,6 +40,7 @@ def _group_sums(values, groups, size): return rv +@can_run(iterators_read_before_sums("average_degree_connectivity", "nodes")) def average_degree_connectivity(G, source="in+out", target="in+out", nodes=None, weight=None): if G.is_directed(): if source not in _KINDS: diff --git a/graphblas_algorithms/nxapi/assortativity/correlation.py b/graphblas_algorithms/nxapi/assortativity/correlation.py index 88e95b7..ce3369d 100644 --- a/graphblas_algorithms/nxapi/assortativity/correlation.py +++ b/graphblas_algorithms/nxapi/assortativity/correlation.py @@ -5,7 +5,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, iterators_read_before_sums, nbunch_keys from .mixing import degree_mixing_matrix # noqa: F401 (NetworkX's module has it too) from .mixing import ( check_rule, @@ -86,7 +86,9 @@ def _constant_input(): return float("nan") -@can_run(_pearson_rule) +@can_run( + _pearson_rule, iterators_read_before_sums("degree_pearson_correlation_coefficient", "nodes") +) def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, nodes=None): check_rule(_pearson_rule, G=G, x=x, y=y) import scipy as sp diff --git a/graphblas_algorithms/nxapi/assortativity/pairs.py b/graphblas_algorithms/nxapi/assortativity/pairs.py index aa9cd07..939c890 100644 --- a/graphblas_algorithms/nxapi/assortativity/pairs.py +++ b/graphblas_algorithms/nxapi/assortativity/pairs.py @@ -17,15 +17,17 @@ def node_degree_xy(G, x="out", y="in", weight=None, nodes=None): pairs are made, and `nodes` read, when the first is asked for. NetworkX's `mixing_dict` takes these degrees as keys, and its `degree_mixing_dict` and `degree_mixing_matrix` call this name; so float weights must add as NetworkX adds them, or be left to it, as there. + The degrees are added at the call, so that one that could reach 2**63 raises + IntegerOverflowError while NetworkX's dispatcher can still answer instead. """ check_rule(_pairs_rule, G=G, x=x, y=y) G = to_graph(G, weight=weight) is_weighted = weighted(G, weight, "node_degree_xy", exact=True) - return _pairs(G, x, y, is_weighted, nodes) + xdeg, ydeg = degree_arrays(G, x, y, is_weighted) + return _pairs(G, xdeg, ydeg, nodes) -def _pairs(G, x, y, is_weighted, nodes): +def _pairs(G, xdeg, ydeg, nodes): ids = pair_ids(G, nodes) - xdeg, ydeg = degree_arrays(G, x, y, is_weighted) xs, ys = algorithms.degree_pairs(G, xdeg, ydeg, ids) yield from zip(xs.tolist(), ys.tolist(), strict=True) diff --git a/graphblas_algorithms/nxapi/cuts.py b/graphblas_algorithms/nxapi/cuts.py index 2ffd378..2f26f14 100644 --- a/graphblas_algorithms/nxapi/cuts.py +++ b/graphblas_algorithms/nxapi/cuts.py @@ -3,7 +3,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from ._utils import nbunch_keys +from ._utils import can_run, iterators_read_before_sums, nbunch_keys from .exception import NetworkXError __all__ = [ @@ -18,6 +18,7 @@ ] +@can_run(iterators_read_before_sums("cut_size", "S", "T")) def cut_size(G, S, T=None, weight=None): is_multigraph = G.is_multigraph() G = to_graph(G, weight=weight) @@ -35,6 +36,7 @@ def _counts(G, nbunch): return Vector.from_coo(ids, [1] * len(ids), dtype=int, size=len(G), dup_op=binary.plus) +@can_run(iterators_read_before_sums("volume", "S")) def volume(G, S, weight=None): is_multigraph = G.is_multigraph() G = to_graph(G, weight=weight) diff --git a/graphblas_algorithms/nxapi/distance_measures.py b/graphblas_algorithms/nxapi/distance_measures.py index dc8e353..9c9a928 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, iterators_read_before_sums, nbunch_keys from .exception import NetworkXError __all__ = ["center", "diameter", "eccentricity", "harmonic_diameter", "periphery", "radius"] @@ -57,7 +57,7 @@ def _extreme_nodes(e, pick): return [v for v in e if e[v] == target] -@can_run(_with_nodes_without_sp) +@can_run(_with_nodes_without_sp, iterators_read_before_sums("eccentricity", "v")) 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) diff --git a/graphblas_algorithms/nxapi/shortest_paths/weighted.py b/graphblas_algorithms/nxapi/shortest_paths/weighted.py index 2f2a016..7f91281 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/weighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/weighted.py @@ -1,4 +1,5 @@ from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.shortest_paths.weighted import _length_dtype from graphblas_algorithms.classes.digraph import to_graph from .._utils import normalize_chunksize, partition @@ -14,11 +15,18 @@ def all_pairs_bellman_ford_path_length(G, weight="weight", *, chunksize="10 MiB"): + G = to_graph(G, weight=weight) + # Raise IntegerOverflowError now, while NetworkX's dispatcher can still answer instead, + # rather than when the first length is asked for. + _length_dtype(G, G.get_property("offdiag")) + return _all_pairs_bellman_ford_path_length(G, chunksize) + + +def _all_pairs_bellman_ford_path_length(G, chunksize): # Larger chunksize offers more parallelism, but uses more memory. # 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) chunksize = normalize_chunksize(chunksize, len(G) * G._A.dtype.np_type.itemsize, len(G)) if chunksize is None: # All at once diff --git a/graphblas_algorithms/nxapi/tests/_overflow.py b/graphblas_algorithms/nxapi/tests/_overflow.py new file mode 100644 index 0000000..e7b1ff2 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/_overflow.py @@ -0,0 +1,44 @@ +"""How a call whose integer sums could pass 2**63 ends, by the way it reaches this backend. + +The kernels raise IntegerOverflowError, an OverflowError that is also a NotImplementedError. +Under `backend_priority` NetworkX takes it as a decline and answers itself, exactly, for a +NetworkX graph, and for this backend's graphs when `fallback_to_nx` is on. Called with +`backend="graphblas"`, NetworkX tries nothing else and raises its own NotImplementedError from +it. Called directly, the kernels raise it as it is. +""" + +import re +from contextlib import contextmanager + +import networkx as nx +import pytest + +from graphblas_algorithms.algorithms.exceptions import IntegerOverflowError + + +@contextmanager +def declined(match=None): + """The block calls with `backend="graphblas"`: NetworkX raises from this backend's error.""" + with pytest.raises(NotImplementedError) as info: + yield + assert type(info.value) is NotImplementedError + assert isinstance(info.value.__cause__, IntegerOverflowError) + if match is not None: + assert re.search(match, str(info.value.__cause__)) + + +@contextmanager +def graphblas_first(kind="algos", *, fallback_to_nx=False): + """NetworkX tries this backend first in its `kind` priority list ("algos" or "generators"). + + Only around the call under test: NetworkX's own algorithms call others, which would come here. + """ + config = nx.config + saved = list(getattr(config.backend_priority, kind)), config.fallback_to_nx + setattr(config.backend_priority, kind, ["graphblas"]) + config.fallback_to_nx = fallback_to_nx + try: + yield + finally: + setattr(config.backend_priority, kind, saved[0]) + config.fallback_to_nx = saved[1] diff --git a/graphblas_algorithms/nxapi/tests/test_assortativity.py b/graphblas_algorithms/nxapi/tests/test_assortativity.py index 0eb7d47..69f61c8 100644 --- a/graphblas_algorithms/nxapi/tests/test_assortativity.py +++ b/graphblas_algorithms/nxapi/tests/test_assortativity.py @@ -19,6 +19,8 @@ from graphblas_algorithms import nxapi from graphblas_algorithms.interface import Dispatcher +from ._overflow import declined + pytestmark = [ pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs"), pytest.mark.filterwarnings("ignore::RuntimeWarning"), # numpy's nan from 0 / 0, as there @@ -175,6 +177,19 @@ def automatic(name, G, **kwargs): config.algos = before +def left_to_networkx(name, G, **kwargs): + """A call whose 64-bit sums could wrap: NetworkX answers it under the priority. + + With `backend="graphblas"` NetworkX raises from this backend's IntegerOverflowError. + """ + func = getattr(nx, name) + want = outcome(func, G, kwargs, "networkx") + assert want[0] == "value" + assert_same(outcome(func, G, kwargs, "automatic"), want) + with declined("2\\*\\*63"): + func(G, backend="graphblas", **kwargs) + + def same_as_networkx(name, G, rel=REL, types=True, **kwargs): func = getattr(nx, name) want = outcome(func, G, kwargs, "networkx") @@ -509,11 +524,10 @@ def test_big_integer_weights(): # NetworkX squares these degrees in int64 for this one, so it is checked against the pairs. coefficient_as_networkx("degree_assortativity_coefficient", G, weight="weight") coefficient_as_networkx("degree_pearson_correlation_coefficient", G, weight="weight") - # Rather than let a 64-bit sum wrap. + # Left to NetworkX rather than let a 64-bit sum wrap. G = weighted(nx.path_graph(5), [2**62]) - for name in ["average_neighbor_degree", "degree_mixing_matrix"]: - with pytest.raises(OverflowError, match="2\\*\\*63"): - getattr(nx, name)(G, weight="weight", backend="graphblas") + for name in ["average_neighbor_degree", "degree_mixing_matrix", "node_degree_xy"]: + left_to_networkx(name, G, weight="weight") def _every_name(G, **kwargs): @@ -557,16 +571,15 @@ def test_integer_weights_are_bounded_node_by_node(directed): (weighted(nx.star_graph(4), [2**61 - 1]), ["average_degree_connectivity"]), ], ) -def test_a_sum_that_could_reach_2_63_raises(graph, names): +def test_a_sum_that_could_reach_2_63_is_left_to_networkx(graph, names): for name in names: - with pytest.raises(OverflowError, match="2\\*\\*63"): - getattr(nx, name)(graph, weight="weight", backend="graphblas") + left_to_networkx(name, graph, weight="weight") # On a directed graph a self-loop is one out-edge: 2**62 + 1. if graph.number_of_edges() == 2: D = weighted(nx.DiGraph([(0, 0), (0, 1)]), [2**62, 1]) same_as_networkx("average_neighbor_degree", D, weight="weight", target="in") - with pytest.raises(OverflowError, match="2\\*\\*63"): # 2**62 times out-degree 2 - nx.average_neighbor_degree(D, weight="weight", backend="graphblas") + # 2**62 times out-degree 2 + left_to_networkx("average_neighbor_degree", D, weight="weight") def test_in_and_out_neighbors_are_bounded_together(): @@ -576,10 +589,7 @@ def test_in_and_out_neighbors_are_bounded_together(): D.add_edge(2, 0, weight=2**60) D.add_edge(0, 1, weight=2**60) D.add_weighted_edges_from([(1, leaf, 1) for leaf in "abcd"] + [(2, leaf, 1) for leaf in "xyz"]) - with pytest.raises(OverflowError, match="2\\*\\*63"): - nx.average_neighbor_degree( - D, source="in+out", target="out", weight="weight", backend="graphblas" - ) + left_to_networkx("average_neighbor_degree", D, source="in+out", target="out", weight="weight") same_as_networkx("average_neighbor_degree", D, source="out", target="out", weight="weight") diff --git a/graphblas_algorithms/nxapi/tests/test_cuts.py b/graphblas_algorithms/nxapi/tests/test_cuts.py index 61e12a9..bd0f1c4 100644 --- a/graphblas_algorithms/nxapi/tests/test_cuts.py +++ b/graphblas_algorithms/nxapi/tests/test_cuts.py @@ -1,6 +1,12 @@ +from collections.abc import Iterator + import networkx as nx import pytest +from graphblas_algorithms.interface import Dispatcher + +from ._overflow import graphblas_first + SHAPES = { "a self-loop": lambda: nx.Graph([(0, 0), (0, 1), (1, 2), (2, 3)]), "directed": lambda: nx.path_graph(4, create_using=nx.DiGraph), @@ -148,7 +154,15 @@ def test_expansions_divide_by_the_set_sizes_as_given(name, args): def test_volume_nbunch_follows_networkx(make, weight, nodes): """A degree view over the nbunch skips an absent member and counts a repeat each time.""" expected = _outcome(nx.volume, make(), nodes(), weight=weight) - got = _outcome(nx.volume, make(), nodes(), weight=weight, backend="graphblas") + if weight is not None and isinstance(nodes(), Iterator): + # Read before the sums are bounded, so left to NetworkX (see test_overflow.py). + assert "an iterator `S`" in Dispatcher.can_run( + "volume", (make(), nodes()), {"weight": weight} + ) + with graphblas_first(): + got = _outcome(nx.volume, make(), nodes(), weight=weight) + else: + got = _outcome(nx.volume, make(), nodes(), weight=weight, backend="graphblas") assert got == pytest.approx(expected) diff --git a/graphblas_algorithms/nxapi/tests/test_overflow.py b/graphblas_algorithms/nxapi/tests/test_overflow.py index db54b5c..f2cab38 100644 --- a/graphblas_algorithms/nxapi/tests/test_overflow.py +++ b/graphblas_algorithms/nxapi/tests/test_overflow.py @@ -1,12 +1,11 @@ -"""Integer weights large enough that a result could pass 2**63 raise OverflowError. +"""Integer weights large enough that a result could pass 2**63 are left to NetworkX. NetworkX adds integer weights as Python integers, which never overflow; this backend adds them as -64-bit integers, which wrap silently. Just below each bound the backend answers as NetworkX does; -at the bound it raises, through the dispatcher, under `backend_priority`, and called directly. +64-bit integers, which wrap silently. Just below each bound the backend answers as NetworkX does. +At the bound its kernels raise IntegerOverflowError: under `backend_priority` NetworkX answers +instead, with `backend="graphblas"` NetworkX raises from it, and a direct call raises it. """ -from contextlib import contextmanager - import networkx as nx import numpy as np import pytest @@ -15,6 +14,8 @@ import graphblas_algorithms as ga from graphblas_algorithms import DiGraph, Graph +from ._overflow import declined, graphblas_first + def path(n, weights, create_using=nx.Graph): """A path whose edges weigh `weights` in turn.""" @@ -53,22 +54,6 @@ def plain(result, typed=True): return (result, type(result)) if typed else result -@contextmanager -def graphblas_first(): - """NetworkX tries this backend first, and would answer itself after NotImplementedError. - - Only around the call under test: NetworkX's own algorithms call others, which would come here. - """ - config = nx.config - saved = list(config.backend_priority.algos), config.fallback_to_nx - config.backend_priority.algos = ["graphblas"] - config.fallback_to_nx = True - try: - yield - finally: - config.backend_priority.algos, config.fallback_to_nx = saved - - # Each name: how NetworkX is called, and the kernel a direct call reaches. PATHS = { "single_source_bellman_ford_path_length": ( @@ -125,15 +110,30 @@ def test_path_lengths_just_below_the_bound_are_networkx_s(name): @pytest.mark.parametrize("name", sorted(PATHS)) @pytest.mark.parametrize("graph", sorted(AT)) -def test_path_lengths_at_the_bound_raise(name, graph): - with pytest.raises(OverflowError, match="could make a path length reach 2\\*\\*63"): +def test_path_lengths_at_the_bound_are_left_to_networkx(name, graph): + want = call(name, AT[graph](), backend="networkx") + for fallback_to_nx in (False, True): # a NetworkX graph needs no fallback + with graphblas_first(fallback_to_nx=fallback_to_nx): + assert call(name, AT[graph]()) == want + with declined("could make a path length reach 2\\*\\*63"): call(name, AT[graph](), backend="graphblas") - with graphblas_first(), pytest.raises(OverflowError): - call(name, AT[graph]()) # NetworkX does not swallow it, nor answer instead - with pytest.raises(OverflowError): + with pytest.raises(OverflowError, match="could make a path length reach 2\\*\\*63"): PATHS[name][1](convert(AT[graph]())) +@pytest.mark.parametrize("name", sorted(PATHS)) +def test_a_backend_graph_at_the_bound_is_left_to_networkx_with_fallback(name): + """NetworkX converts this backend's graph back only with `fallback_to_nx` on. + + Without it NetworkX has no other backend to try, and raises its own NotImplementedError. + """ + want = call(name, AT["at the bound"](), backend="networkx") + with graphblas_first(fallback_to_nx=True): + assert call(name, convert(AT["at the bound"]())) == want + with graphblas_first(), pytest.raises(NotImplementedError, match="not implemented by"): + call(name, convert(AT["at the bound"]())) + + @pytest.mark.parametrize("name", sorted(PATHS)) @pytest.mark.parametrize("value", [2**61, 2**61 + 1]) def test_lengths_that_fit_but_whose_sums_would_wrap_raise(name, value): @@ -147,8 +147,11 @@ def test_lengths_that_fit_but_whose_sums_would_wrap_raise(name, value): want = call(name, path(4, [2**61]), backend="networkx") assert call(name, path(4, [2**61]), backend="graphblas") == want return - with pytest.raises(OverflowError): + with declined(): call(name, path(4, [2**61, value]), backend="graphblas") + want = call(name, path(4, [2**61, value]), backend="networkx") + with graphblas_first(): + assert call(name, path(4, [2**61, value])) == want @pytest.mark.parametrize( @@ -165,10 +168,10 @@ def G(): assert nx.negative_edge_cycle(G()) is False assert ga.negative_edge_cycle(convert(G())) is False return - with pytest.raises(OverflowError): + with declined(): nx.negative_edge_cycle(G(), backend="graphblas") - with graphblas_first(), pytest.raises(OverflowError): - nx.negative_edge_cycle(G()) + with graphblas_first(): + assert nx.negative_edge_cycle(G()) is nx.negative_edge_cycle(G(), backend="networkx") with pytest.raises(OverflowError): ga.negative_edge_cycle(convert(G())) @@ -179,8 +182,13 @@ def test_ego_graph_with_a_distance_at_the_bound(): want = nx.ego_graph(below(), 0, radius, distance="weight", backend="networkx") got = nx.ego_graph(below(), 0, radius, distance="weight", backend="graphblas") assert sorted(got) == sorted(want) == [0, 1, 2] - with pytest.raises(OverflowError): + with declined(): nx.ego_graph(AT["at the bound"](), 0, radius, distance="weight", backend="graphblas") + want = nx.ego_graph(AT["at the bound"](), 0, radius, distance="weight", backend="networkx") + with graphblas_first("generators"): + got = nx.ego_graph(AT["at the bound"](), 0, radius, distance="weight") + assert type(got) is nx.Graph + assert sorted(got.edges(data=True)) == sorted(want.edges(data=True)) def test_negative_edge_cycle_answers_without_adding_when_no_weight_is_negative(): @@ -237,7 +245,11 @@ def test_negative_edge_cycle_adds_small_types_in_64_bits(): def test_uint64_weights_from_2_63_raise(): G = path(3, [2**63, 1]) with pytest.raises(OverflowError, match="could make a path length reach 2\\*\\*63"): - call("single_source_bellman_ford_path_length", from_matrix(G, dtypes.UINT64)) + ga.single_source_bellman_ford_path_length(from_matrix(G, dtypes.UINT64), 0) + # Converted back, they are NetworkX's Python integers. + with graphblas_first(fallback_to_nx=True): + got = call("single_source_bellman_ford_path_length", from_matrix(G, dtypes.UINT64)) + assert got == call("single_source_bellman_ford_path_length", G, backend="networkx") # Sums of weights: cut_size and volume. Their bound is on the absolute values of every weight the @@ -287,13 +299,16 @@ def test_sums_just_below_the_bound_are_networkx_s(name, graph): @pytest.mark.parametrize("name", sorted(SUMS)) @pytest.mark.parametrize("graph", sorted(AT_SUMS)) -def test_sums_at_the_bound_raise(name, graph): +def test_sums_at_the_bound_are_left_to_networkx(name, graph): """Every absolute value counts, so a negative weight cannot cancel a positive one.""" - with pytest.raises(OverflowError, match="could make a sum of them reach 2\\*\\*63"): + want = sum_of(name, AT_SUMS[graph](), backend="networkx") + with graphblas_first(): + assert sum_of(name, AT_SUMS[graph]()) == want + with graphblas_first(fallback_to_nx=True): + assert sum_of(name, convert(AT_SUMS[graph]())) == want + with declined("could make a sum of them reach 2\\*\\*63"): sum_of(name, AT_SUMS[graph](), backend="graphblas") - with graphblas_first(), pytest.raises(OverflowError): - sum_of(name, AT_SUMS[graph]()) - with pytest.raises(OverflowError): + with pytest.raises(OverflowError, match="could make a sum of them reach 2\\*\\*63"): SUMS[name][1](convert(AT_SUMS[graph]())) @@ -305,8 +320,11 @@ def test_volume_counts_a_repeated_node_in_its_bound(times): want = nx.volume(star([2**62 - 1]), [0] * times, weight="weight", backend="networkx") assert nx.volume(G, [0] * times, weight="weight", backend="graphblas") == want else: - with pytest.raises(OverflowError, match="counted up to 3 times"): + with declined("counted up to 3 times"): nx.volume(G, [0] * times, weight="weight", backend="graphblas") + want = nx.volume(star([2**62 - 1]), [0] * times, weight="weight", backend="networkx") + with graphblas_first(): + assert nx.volume(star([2**62 - 1]), [0] * times, weight="weight") == want @pytest.mark.parametrize( @@ -345,7 +363,7 @@ def test_sums_of_smaller_integer_types_are_added_in_64_bits(name, dtype): @pytest.mark.parametrize("name", sorted(SUMS)) def test_uint64_weights_from_2_63_raise_in_sums(name): with pytest.raises(OverflowError): - sum_of(name, from_matrix(star([2**63, 1]), dtypes.UINT64)) + SUMS[name][1](from_matrix(star([2**63, 1]), dtypes.UINT64)) # The eccentricity names: lengths as the bellman_ford names find them, and `usebounds` adds two. @@ -376,12 +394,13 @@ def test_eccentricities_just_below_the_bound_are_networkx_s(name): @pytest.mark.parametrize("name", sorted(ECCENTRICITY)) @pytest.mark.parametrize("value", [2**60, 2**61, 2**61 + 1]) -def test_eccentricities_at_the_bound_raise(name, value): +def test_eccentricities_at_the_bound_are_left_to_networkx(name, value): """At 2**61 every length fits, but the bounds add two of them: `periphery` answered [0].""" - with pytest.raises(OverflowError, match="could make a path length reach 2\\*\\*63"): + with declined("could make a path length reach 2\\*\\*63"): eccentricity_call(name, path(4, [2**61, value]), backend="graphblas") - with graphblas_first(), pytest.raises(OverflowError): - eccentricity_call(name, path(4, [2**61, value])) + want = eccentricity_call(name, path(4, [2**61, value]), backend="networkx") + with graphblas_first(): + assert eccentricity_call(name, path(4, [2**61, value])) == want def test_eccentricity_called_directly_raises(): @@ -399,3 +418,83 @@ def test_eccentricities_of_smaller_integer_types_are_added_in_64_bits(name, dtyp assert eccentricity_call(name, from_matrix(G, kind)) == eccentricity_call( name, G, backend="networkx" ) + + +# Node arguments as one-shot iterators. NetworkX answers with the arguments it was given, so a +# wrapper that read an iterator before its kernel raised would leave NetworkX one already spent, +# and NetworkX would answer, wrongly and without an error, as if given no nodes. +ITERATED = { + "cut_size": ( + lambda: path(4, [2**61, 2**61 + 7]), + lambda f, G, nodes, **kw: f(G, nodes([0, 1]), nodes([2, 3]), weight="weight", **kw), + ), + "volume": ( + lambda: path(4, [2**61, 2**61 + 7]), + lambda f, G, nodes, **kw: f(G, nodes([1, 2, 1, 2]), weight="weight", **kw), + ), + "average_degree_connectivity": ( + lambda: path(5, [2**62]), + lambda f, G, nodes, **kw: f(G, nodes=nodes([1, 2]), weight="weight", **kw), + ), + "average_neighbor_degree": ( + lambda: path(5, [2**62]), + lambda f, G, nodes, **kw: f(G, nodes=nodes([1, 2]), weight="weight", **kw), + ), + "degree_mixing_matrix": ( + lambda: path(5, [2**62]), + lambda f, G, nodes, **kw: f( + G, nodes=nodes([1, 2]), weight="weight", mapping={2**62: 0, 2**63: 1}, **kw + ).tolist(), + ), + "degree_pearson_correlation_coefficient": ( + lambda: path(5, [2**62, 2**62 + 1]), + lambda f, G, nodes, **kw: f(G, nodes=nodes([0, 1, 2, 3]), weight="weight", **kw), + ), + "degree_assortativity_coefficient": ( + lambda: path(5, [2**62, 2**62 + 1]), + lambda f, G, nodes, **kw: f(G, nodes=nodes([0, 1, 2, 3]), weight="weight", **kw), + ), + "eccentricity": ( + lambda: path(4, [2**61, 2**61 + 1]), + lambda f, G, nodes, **kw: f(G, v=nodes([0, 1]), weight="weight", **kw), + ), +} +ONE_SHOT = {"iterator": iter, "generator": lambda nodes: (node for node in nodes)} + + +@pytest.mark.parametrize("name", sorted(ITERATED)) +@pytest.mark.parametrize("kind", sorted(ONE_SHOT)) +def test_a_one_shot_iterator_of_nodes_at_the_bound_gets_networkx_s_answer(name, kind): + build, call = ITERATED[name] + func = getattr(nx, name) + with declined(): # given a list, the kernel finds the bound + call(func, build(), list, backend="graphblas") + want = call(func, build(), ONE_SHOT[kind], backend="networkx") + for fallback_to_nx in (False, True): + with graphblas_first(fallback_to_nx=fallback_to_nx): + got = call(func, build(), ONE_SHOT[kind]) + assert repr(got) == repr(want) # repr: NetworkX's own answer may be nan + + +@pytest.mark.parametrize( + ("name", "parameters"), + [ + ("cut_size", ["S", "T"]), + ("volume", ["S"]), + ("average_degree_connectivity", ["nodes"]), + ("degree_pearson_correlation_coefficient", ["nodes"]), + ("eccentricity", ["v"]), + ], +) +def test_only_a_weighted_call_with_an_iterator_of_nodes_is_declined(name, parameters): + """Unweighted sums count edges or nodes, which cannot reach 2**63.""" + from graphblas_algorithms.interface import Dispatcher + + G = path(4, [1, 2]) + for parameter in parameters: + nodes = {p: [0, 1] for p in parameters} | {parameter: iter([0, 1])} + reason = Dispatcher.can_run(name, (G,), {**nodes, "weight": "weight"}) + assert f"reads an iterator `{parameter}`" in reason + assert Dispatcher.can_run(name, (G,), {**nodes, "weight": None}) is True + lists = {p: [0, 1] for p in parameters} + assert Dispatcher.can_run(name, (G,), {**lists, "weight": "weight"}) is True diff --git a/graphblas_algorithms/nxapi/tests/test_wiener.py b/graphblas_algorithms/nxapi/tests/test_wiener.py index 2bdc3e5..eed9f23 100644 --- a/graphblas_algorithms/nxapi/tests/test_wiener.py +++ b/graphblas_algorithms/nxapi/tests/test_wiener.py @@ -8,6 +8,8 @@ from graphblas_algorithms import nxapi from graphblas_algorithms.interface import Dispatcher +from ._overflow import declined, graphblas_first + pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") UNDIRECTED = ["schultz_index", "gutman_index", "hyper_wiener_index"] @@ -90,10 +92,21 @@ def test_integer_lengths_are_summed_exactly(name): @pytest.mark.parametrize("name", WEIGHTED) -def test_raises_rather_than_wrap(name): - G = weighted(nx.path_graph(40), [2**53] * 39) +def test_a_sum_that_could_wrap_is_left_to_networkx(name): + """Every length fits in 64 bits, but a sum over one node's targets might not.""" + + def G(): + return weighted(nx.path_graph(40), [2**53] * 39) + + want = getattr(nx, name)(G(), weight="weight", backend="networkx") + with graphblas_first(): + got = getattr(nx, name)(G(), weight="weight") + assert type(got) is type(want) + assert got == want + with declined("lengths up to .* could make a sum of them reach 2\\*\\*63"): + getattr(nx, name)(G(), weight="weight", backend="graphblas") with pytest.raises(OverflowError, match="2\\*\\*63"): - getattr(nx, name)(G, weight="weight", backend="graphblas") + getattr(nxapi, name)(G(), weight="weight") @pytest.mark.parametrize("name", WEIGHTED) diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 1765e78..276b3b1 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -1,5 +1,6 @@ """Tests for the NetworkX backend protocol methods in `graphblas_algorithms.interface`.""" +import re import warnings from decimal import Decimal from fractions import Fraction @@ -105,9 +106,10 @@ def test_networkx_answers_a_rebuild_of_an_int_outside_int64(name, value, backend assert sorted(map(repr, got.edges(data=True))) == sorted(map(repr, expected.edges(data=True))) -# Pairs of weights whose one matrix dtype (what numpy infers for them all) is a float or -# complex that cannot hold one of the ints exactly. -CHANGES_VALUE = { +# Pairs of weights whose one matrix dtype (what numpy infers for them all) is a float or complex +# that would hold ints NetworkX keeps exact: an int past 2**53 beside a float, some coming back +# as other numbers and some equal but as floats, or values that are all ints. +HELD_AS_FLOATS = { "int past 2**53 beside a float": (2**53 + 1, 1.5), "negative int past 2**53 beside a float": (-(2**53) - 1, 1.5), "int past 2**53 beside a complex": (2**53 + 1, 1j), @@ -117,14 +119,18 @@ def test_networkx_answers_a_rebuild_of_an_int_outside_int64(name, value, backend "np.uint64 beside a negative np.int64": (np.uint64(2**53 + 1), np.int64(-1)), "int past 2**53 beside np.uint64": (2**62 + 1, np.uint64(5)), "int past 2**53 beside nan": (2**53 + 1, float("nan")), + "np.uint64 at 2**63 beside an int": (np.uint64(2**63), 2), + "int past 2**53, exact as a float, beside a float": (2**62, 0.5), + "small np.uint64 beside an int": (np.uint64(5), -2), } +# Both refusals: an int past 2**53 beside a float, and values that are all ints. +AS_FLOATS = r"would hold (those ints )?as floats" # Pairs whose values come back equal, if not of the same type. CHANGES_TYPE_ONLY = { "int beside a float": (1, 1.5), "True beside an int": (True, 2), "2**53 beside a float": (2**53, 1.5), "int past 2**53 beside an int": (2**53 + 1, 2), - "np.uint64 at 2**63 beside an int": (np.uint64(2**63), 2), "np.uint64 beside np.uint64": (np.uint64(2**64 - 1), np.uint64(5)), } @@ -135,16 +141,16 @@ def weighted_triangle_of(pair): ) -@pytest.mark.parametrize("pair", CHANGES_VALUE.values(), ids=CHANGES_VALUE) -def test_a_rebuild_whose_one_dtype_would_change_a_value_is_declined(pair): +@pytest.mark.parametrize("pair", HELD_AS_FLOATS.values(), ids=HELD_AS_FLOATS) +def test_a_rebuild_that_would_hold_ints_as_floats_is_declined(pair): G = weighted_triangle_of(pair) - with pytest.raises(NotImplementedError, match="would change those ints"): + with pytest.raises(NotImplementedError, match=AS_FLOATS): Dispatcher.convert_from_nx(G, preserve_edge_attrs=True, name="k_truss") - assert "would change those ints" in Dispatcher.can_run("k_truss", (G, 2), {}) + assert re.search(AS_FLOATS, Dispatcher.can_run("k_truss", (G, 2), {})) -@pytest.mark.parametrize("pair", CHANGES_VALUE.values(), ids=CHANGES_VALUE) -def test_networkx_answers_a_rebuild_whose_one_dtype_would_change_a_value(pair, backend_priority): +@pytest.mark.parametrize("pair", HELD_AS_FLOATS.values(), ids=HELD_AS_FLOATS) +def test_networkx_answers_a_rebuild_that_would_hold_ints_as_floats(pair, backend_priority): G = weighted_triangle_of(pair) expected = nx.k_truss(G, 2, backend="networkx") with backend_priority("generators"): @@ -164,6 +170,455 @@ def test_a_rebuild_that_changes_only_a_value_s_type_is_served(pair): assert got[u][v]["weight"] == given # Python compares an int and a float exactly +# A call that only reads the weights: NetworkX adds and compares ints as Python ints, exactly, +# where a float matrix rounds. Each reader below answers a + b for the pair (a, b). +READ_AS_FLOATS = { + "uint64-range int beside a negative int": (2**63 + 1, -1), + "2**63 beside 1": (2**63, 1), + "int past 2**53 beside a float": (2**53 + 1, 0.5), + "np.uint64 at 2**63 beside an int": (np.uint64(2**63), 2), + "int below 2**53 beside an np.uint64": (2**53 - 1, np.uint64(4)), +} +READ_SERVED = { + "int beside a float": (1, 1.5), + "2**53 beside a float": (2**53, 1.5), + "True beside an int": (True, 2), + "int past 2**53 beside an int": (2**53 + 1, 2), +} +READERS = { + "cut_size": lambda f, G, **kw: f(G, [0], [1, 3], weight="weight", **kw), + "volume": lambda f, G, **kw: f(G, [0], weight="weight", **kw), + "bellman_ford_path_length": lambda f, G, **kw: f(G, 0, 2, weight="weight", **kw), +} + + +# Names whose answers are floats: served on these weights, within a float's rounding. +FLOAT_READERS = { + "pagerank": lambda f, G, **kw: f(G, weight="weight", **kw), + "closeness_centrality": lambda f, G, **kw: f(G, distance="weight", **kw), + "conductance": lambda f, G, **kw: f(G, [0], [1, 3], weight="weight", **kw), +} + + +def read_graph_of(pair): + a, b = pair + return nx.DiGraph([(0, 1, {"weight": a}), (1, 2, {"weight": b}), (0, 3, {"weight": b})]) + + +@pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") +@pytest.mark.parametrize("pair", READ_AS_FLOATS.values(), ids=READ_AS_FLOATS) +@pytest.mark.parametrize("name", sorted(READERS)) +def test_a_read_that_would_hold_ints_as_floats_is_left_to_networkx(name, pair, backend_priority): + """The conversion is kept and marked, and the call declines before it reads an argument.""" + G = Dispatcher.convert_from_nx(read_graph_of(pair), edge_attrs={"weight": 1}, name=name) + assert re.search(AS_FLOATS, G._ints_as_floats) + with pytest.raises(NotImplementedError, match=AS_FLOATS): + READERS[name](getattr(Dispatcher, name), G) + func = getattr(nx, name) + want = READERS[name](func, read_graph_of(pair), backend="networkx") + G = read_graph_of(pair) + with backend_priority("algos"): + assert repr(READERS[name](func, G)) == repr(want) # NetworkX's, exact + # A second call is given NetworkX's cached conversion, declines again, and NetworkX + # answers again. + assert repr(READERS[name](func, G)) == repr(want) + + +@pytest.mark.parametrize("pair", [(2**53 + 1, 1j), (np.int64(2**53 + 1), np.complex64(1j))]) +def test_a_read_that_would_hold_an_int_past_2_53_as_a_complex_is_declined(pair): + G = Dispatcher.convert_from_nx(read_graph_of(pair), edge_attrs={"weight": 1}, name="volume") + with pytest.raises(NotImplementedError, match=AS_FLOATS): + Dispatcher.volume(G, [0], weight="weight") + + +@pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") +@pytest.mark.parametrize("pair", READ_AS_FLOATS.values(), ids=READ_AS_FLOATS) +def test_edge_data_given_back_from_ints_held_as_floats_is_left_to_networkx(pair, backend_priority): + want = list(nx.edge_boundary(read_graph_of(pair), [0], data="weight", backend="networkx")) + with pytest.raises(NotImplementedError): + list(nx.edge_boundary(read_graph_of(pair), [0], data="weight", backend="graphblas")) + with backend_priority("algos"): + got = list(nx.edge_boundary(read_graph_of(pair), [0], data="weight")) + assert repr(got) == repr(want) + + +# Of one sign, so that their sums, rounded, do not cancel. +READ_AS_FLOATS_OF_ONE_SIGN = { + key: pair for key, pair in READ_AS_FLOATS.items() if min(pair) >= 0 or max(pair) <= 0 +} + + +@pytest.mark.parametrize( + "pair", READ_AS_FLOATS_OF_ONE_SIGN.values(), ids=READ_AS_FLOATS_OF_ONE_SIGN +) +@pytest.mark.parametrize("name", sorted(FLOAT_READERS)) +def test_a_float_answer_is_served_on_ints_held_as_floats(name, pair): + func = getattr(nx, name) + want = FLOAT_READERS[name](func, read_graph_of(pair), backend="networkx") + got = FLOAT_READERS[name](func, read_graph_of(pair), backend="graphblas") + if isinstance(want, dict): + assert got.keys() == want.keys() + assert got == pytest.approx(want, rel=1e-12) + + +@pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") +@pytest.mark.parametrize("first", ["exact", "float"]) +def test_names_share_the_cached_conversion_of_ints_held_as_floats(first, backend_priority): + """Either name may come first: the exact one declines on the cache, the float one is served.""" + pair = READ_AS_FLOATS["int past 2**53 beside a float"] + G = read_graph_of(pair) + exact = READERS["bellman_ford_path_length"] + floats = FLOAT_READERS["pagerank"] + want_exact = exact(nx.bellman_ford_path_length, read_graph_of(pair), backend="networkx") + want_float = floats(nx.pagerank, read_graph_of(pair), backend="networkx") + calls = [ + lambda: exact(nx.bellman_ford_path_length, G) == want_exact, + lambda: floats(nx.pagerank, G, backend="graphblas") == pytest.approx(want_float), + ] + with backend_priority("algos"): + for call in calls if first == "exact" else calls[::-1]: + assert call() + assert calls[0]() + + +S, T = [0, 1, 2], [3, 4, 5, 6] +# Every name in `_FLOAT_ANSWERS`, called on the graphs below. +FLOAT_ANSWERS = { + "adjacency_matrix": lambda G, **kw: nx.adjacency_matrix(G, **kw).toarray(), + "average_clustering": lambda G, **kw: nx.average_clustering(G, weight="weight", **kw), + "average_neighbor_degree": lambda G, **kw: nx.average_neighbor_degree(G, weight="weight", **kw), + "average_shortest_path_length": lambda G, **kw: nx.average_shortest_path_length( + G, weight="weight", method="bellman-ford", **kw + ), + "closeness_centrality": lambda G, **kw: nx.closeness_centrality(G, distance="weight", **kw), + "clustering": lambda G, **kw: nx.clustering(G, weight="weight", **kw), + "conductance": lambda G, **kw: nx.conductance(G, S, T, weight="weight", **kw), + "degree_assortativity_coefficient": lambda G, **kw: nx.degree_assortativity_coefficient( + G, weight="weight", **kw + ), + "degree_pearson_correlation_coefficient": ( + lambda G, **kw: nx.degree_pearson_correlation_coefficient(G, weight="weight", **kw) + ), + "directed_modularity_matrix": lambda G, **kw: nx.directed_modularity_matrix( + G, weight="weight", **kw + ), + "edge_expansion": lambda G, **kw: nx.edge_expansion(G, S, T, weight="weight", **kw), + "eigenvector_centrality": lambda G, **kw: nx.eigenvector_centrality( + G, weight="weight", max_iter=5000, tol=1e-13, **kw + ), + "google_matrix": lambda G, **kw: nx.google_matrix(G, weight="weight", **kw), + "group_closeness_centrality": lambda G, **kw: nx.group_closeness_centrality( + G, S, weight="weight", **kw + ), + "harmonic_centrality": lambda G, **kw: nx.harmonic_centrality(G, distance="weight", **kw), + "harmonic_diameter": lambda G, **kw: nx.harmonic_diameter(G, weight="weight", **kw), + "hits": lambda G, **kw: nx.hits(G, max_iter=5000, tol=1e-13, **kw), + "katz_centrality": lambda G, **kw: nx.katz_centrality( + G, alpha=1e-20, weight="weight", max_iter=5000, **kw + ), + "laplacian_matrix": lambda G, **kw: nx.laplacian_matrix(G, weight="weight", **kw).toarray(), + "mixing_expansion": lambda G, **kw: nx.mixing_expansion(G, S, T, weight="weight", **kw), + "modularity": lambda G, **kw: nx.community.modularity(G, [S, T], weight="weight", **kw), + "modularity_matrix": lambda G, **kw: nx.modularity_matrix(G, weight="weight", **kw), + "normalized_cut_size": lambda G, **kw: nx.normalized_cut_size(G, S, T, weight="weight", **kw), + "normalized_laplacian_matrix": lambda G, **kw: nx.normalized_laplacian_matrix( + G, weight="weight", **kw + ).toarray(), + "overlapping_modularity": lambda G, **kw: nx.community.overlapping_modularity( + G, [S, [*T, 0]], weight="weight", **kw + ), + "pagerank": lambda G, **kw: nx.pagerank(G, weight="weight", tol=1e-14, max_iter=5000, **kw), + "tournament_matrix": lambda G, **kw: nx.tournament.tournament_matrix(G, **kw).toarray(), +} +# Names that leave weighted calls to NetworkX for reasons of their own, in `can_run`, before the +# sign is asked. +CAN_RUN_DECLINES = {"group_closeness_centrality": "unweighted here"} +# NetworkX's degree_assortativity_coefficient squares integer degrees in int64, which wraps past +# 2**31, as these are; here it is Pearson's r of the degree pairs, as NetworkX's +# degree_pearson_correlation_coefficient gives it. +SAME_ANSWER_AS = {"degree_assortativity_coefficient": "degree_pearson_correlation_coefficient"} +# Declined, NetworkX's degree_pearson_correlation_coefficient reads this backend's node_degree_xy, +# whose pairs come in another order, so its pearsonr may differ in the last bits. +PAIRS_IN_ANOTHER_ORDER = {"degree_pearson_correlation_coefficient"} +# Where negative weights mean something to NetworkX other than a shortest path or a degree's +# square root: sums and the matrices. +NEGATIVE_WEIGHTS_READ_AS_SUMS = { + "adjacency_matrix", + "average_neighbor_degree", + "conductance", + "directed_modularity_matrix", + "edge_expansion", + "laplacian_matrix", + "mixing_expansion", + "modularity", + "modularity_matrix", + "normalized_cut_size", + "overlapping_modularity", + "tournament_matrix", +} + + +def weighted_cycle(weights, *, directed): + """A 7-cycle with two chords, weighed in turn by `weights`.""" + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(7)) + pairs = [(i, (i + 1) % 7) for i in range(7)] + [(0, 3), (2, 5), (4, 1)] + for k, (u, v) in enumerate(pairs): + G.add_edge(u, v, weight=weights[k % len(weights)]) + return G + + +def cancelling(*, directed, kind): + """Ints of both signs whose float sums cancel where NetworkX's exact sums do not. + + "held as floats" and "ints": the cut from S to T weighs exactly 4, from 2**60 + 4, which a + float holds as 2**60, and -2**60, so a float sum makes it 0. Two other weights are floats + in the first, so that the matrix holds the ints as floats; in the second it holds ints, + which the names with float answers add as floats. "small ints": every weight is within + 2**53, but the degrees of 3 and 4 sum to 2**53 + 5, which a float holds as 2**53 + 4. + """ + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(7)) + if kind == "small ints": + G.add_edges_from([(0, 1), (1, 2), (3, 4), (4, 5), (5, 6)], weight=1) + big, cancel = 2**52 + 1, -(2**52) + G.add_weighted_edges_from( + [(0, 3, big), (1, 4, big), (2, 5, big), (0, 6, cancel), (1, 6, cancel), (2, 6, cancel)] + ) + return G + ints = kind == "ints" + G.add_weighted_edges_from( + [ + (0, 1, 1 if ints else 0.5), + (1, 2, 3), + (2, 3, 2**60 + 4), + (1, 4, -(2**60)), + (3, 4, 5 if ints else 1.5), + (4, 5, 2**60 + 1), + (5, 6, -(2**60)), + (6, 3, 2), + (2, 0, -1), + ] + ) + return G + + +CANCELLING = ["held as floats", "ints", "small ints"] +# Weights whose float sums cannot cancel, so that the names with float answers serve them. +SERVED = { + "positive held as floats": [2**53 + 1, 1.5, 2**60 + 3, 2.5, 7, 2**55 + 1, 3.0], + "negative held as floats": [-(2**53) - 1, -1.5, -(2**60) - 3, -2.5, 0, -(2**55) - 1, -3.0], + "positive ints": [2**53 + 1, 3, 2**60 + 3, 5, 7, 2**55 + 1, 2], + "negative ints": [-(2**53) - 1, -3, -(2**60) - 3, -5, 0, -(2**55) - 1, -2], + "small ints of both signs": [2**40 + 1, -3, 5, -(2**40), 7, 1, -2], +} + + +def outcome(call): + """A comparable record of what `call()` gives: its value with full precision, or its error.""" + try: + value = call() + except NotImplementedError: + raise + except Exception as exc: + return "raised", type(exc), str(exc) + if isinstance(value, np.ndarray): + value = value.tolist() + elif isinstance(value, tuple): + value = [dict(part) for part in value] + return "value", repr(value) + + +def answer(call): + """`call()`'s value, or the error it raises but NotImplementedError.""" + try: + return call() + except NotImplementedError: + raise + except Exception as exc: + return exc + + +def known(name, G): + if name not in _registered_algorithms: + pytest.skip(f"{name} is not dispatched by this NetworkX") + want = outcome(lambda: FLOAT_ANSWERS[name](G, backend="networkx")) + if want[0] == "raised" and want[1] is nx.NetworkXNotImplemented: + pytest.skip(f"{name} is not for this kind of graph") + return want + + +def causes(exc): + while exc is not None: + yield str(exc) + exc = exc.__cause__ or exc.__context__ + + +def assert_declined(name, G, reason): + """The call declines: in `can_run` for the names that decline weights there, else at call.""" + if name in CAN_RUN_DECLINES: + call = FLOAT_ANSWERS[name] + assert CAN_RUN_DECLINES[name] in Dispatcher.can_run(name, (G, S), {"weight": "weight"}) + with pytest.raises(NotImplementedError): + call(G, backend="graphblas") + return + with pytest.raises(NotImplementedError) as declined: + FLOAT_ANSWERS[name](G, backend="graphblas") + assert any(reason in message for message in causes(declined.value)) + + +def exact_copy(G): + """`G` with every weight a Fraction, so that NetworkX's sums and comparisons are exact.""" + H = G.__class__() + H.add_nodes_from(G) + H.add_weighted_edges_from((u, v, Fraction(w)) for u, v, w in G.edges(data="weight")) + return H + + +@pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") +@pytest.mark.parametrize("kind", CANCELLING) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", sorted(FLOAT_ANSWERS)) +def test_a_float_answer_on_weights_whose_float_sums_cancel_is_left_to_networkx( + name, directed, kind, backend_priority +): + """Their float sums cancel to anything, so the call declines and NetworkX answers, exactly.""" + G = cancelling(directed=directed, kind=kind) + want = known(name, G) + H = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name=name) + held_as_floats = kind == "held as floats" + assert re.search(AS_FLOATS if held_as_floats else "sum past 2[*][*]52", H._float_sums_cancel) + assert hasattr(H, "_ints_as_floats") is held_as_floats + assert_declined(name, G, "weights of both signs") + if outcome(lambda: FLOAT_ANSWERS[name](G, backend="networkx")) != want: + pytest.skip(f"NetworkX's {name} gives another answer each call (scipy's svds before 3.7)") + with backend_priority("algos"): + for _ in range(2): # the second from the cached conversion + got = outcome(lambda: FLOAT_ANSWERS[name](G)) + if name in PAIRS_IN_ANOTHER_ORDER and got[0] == want[0] == "value": + assert float(got[1]) == pytest.approx(float(want[1]), rel=1e-12) + else: + assert got == want + + +@pytest.mark.parametrize("kind", ["held as floats", "ints"]) +def test_cancelling_weights_change_the_answer(kind): + """Why: NetworkX's exact sums against float sums of the same weights.""" + G = cancelling(directed=False, kind=kind) + assert nx.cut_size(G, S, T, weight="weight", backend="networkx") == 4 + assert nx.edge_expansion(G, S, T, weight="weight", backend="networkx") == 4 / 3 + F = nx.Graph() + F.add_weighted_edges_from((u, v, float(w)) for u, v, w in G.edges(data="weight")) + assert nx.edge_expansion(F, S, T, weight="weight", backend="networkx") == 0.0 + + +def close(got, want, rel): + """`got` within `rel` of `want`, relative to the largest of `want`'s values.""" + if isinstance(want, dict): + assert got.keys() == want.keys() + got, want = list(got.values()), list(want.values()) + elif isinstance(want, tuple): + for g, w in zip(got, want, strict=True): + close(g, w, rel) + return + got, want = np.asarray(got, dtype=float), np.asarray(want, dtype=float) + assert got.shape == want.shape + scale = np.max(np.abs(want), initial=0.0) or 1.0 + np.testing.assert_allclose(got, want, rtol=0, atol=rel * scale) + + +@pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") +@pytest.mark.parametrize("weights", SERVED.values(), ids=SERVED) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", sorted(FLOAT_ANSWERS)) +def test_a_float_answer_on_weights_whose_float_sums_cannot_cancel_is_served( + name, directed, weights +): + """Their sums round by a few parts in 2**53: within 1e-9, `hits` iterating to a tolerance.""" + if min(weights) < 0 and name not in NEGATIVE_WEIGHTS_READ_AS_SUMS: + pytest.skip("a negative length or degree is another matter") + G = weighted_cycle(weights, directed=directed) + known(name, G) + H = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name=name) + held_as_floats = any(isinstance(w, float) for w in weights) + if held_as_floats: + assert re.search(AS_FLOATS, H._ints_as_floats) + else: + assert not hasattr(H, "_ints_as_floats") + assert not hasattr(H, "_float_sums_cancel") + if name in CAN_RUN_DECLINES: + assert_declined(name, G, None) + return + reference = FLOAT_ANSWERS[SAME_ANSWER_AS.get(name, name)] + want = answer(lambda: reference(G, backend="networkx")) + if isinstance(want, Exception): + # NetworkX's Bellman-Ford and Dijkstra can fail on ints past 2**53 beside floats, which + # they add and compare as both; with every weight a Fraction they do not. + want = answer(lambda: reference(exact_copy(G), backend="networkx")) + again = answer(lambda: reference(G, backend="networkx")) + if not isinstance(want, Exception) and not isinstance(again, Exception): + try: + close(again, want, 1e-9) + except AssertionError: + pytest.skip( + f"NetworkX's {name} gives another answer each call (scipy's svds before 3.7)" + ) + got = answer(lambda: FLOAT_ANSWERS[name](G, backend="graphblas")) + if isinstance(want, Exception): + # The power iterations do not converge on these, here or in NetworkX. + assert type(got).__name__ == type(want).__name__ + else: + close(got, want, 1e-9) + + +def weighted_path(weights, *, directed): + G = nx.DiGraph() if directed else nx.Graph() + G.add_weighted_edges_from((i, i + 1, w) for i, w in enumerate(weights)) + return G + + +RECORDED = { + "held-as-floats-nonnegative": ([2**60, 0.5, 0], True, False), + "held-as-floats-nonpositive": ([-(2**60), -0.5, 0], True, False), + "held-as-floats-both-signs": ([2**60, -0.5], True, True), + "small-held-as-floats-both-signs": ([np.uint64(3), -2], True, True), + "held-as-complex": ([2**60, 1j], True, True), # a complex value has no sign + "floats-past-2-53-both-signs": ([2.0**60, -0.5], True, False), # NetworkX adds floats + "ints-nonnegative": ([2**60, 1, 0], True, False), + "ints-nonpositive": ([-(2**60), -1, 0], True, False), + "one-int-past-2-53": ([2**53 + 1, -1], True, True), + "one-int-below-minus-2-53": ([1, -(2**53) - 1], True, True), + "ints-summing-to-2-52": ([2**51, -(2**51)], True, False), + "ints-summing-past-2-52": ([2**51 + 1, -(2**51)], True, True), + "undirected-each-edge-held-twice": ([2**50 + 1, -(2**50)], False, True), + "many-small-ints": ([2**52 + 1] * 3 + [-(2**52)] * 3, True, True), +} + + +@pytest.mark.parametrize(("weights", "directed", "cancel"), RECORDED.values(), ids=RECORDED) +def test_the_conversion_records_whether_float_sums_of_the_weights_can_cancel( + weights, directed, cancel +): + """Ints held as floats of both signs, or ints of both signs whose sizes sum past 2**52.""" + import pickle + + G = weighted_path(weights, directed=directed) + H = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="pagerank") + assert hasattr(H, "_float_sums_cancel") is cancel + assert hasattr(pickle.loads(pickle.dumps(H)), "_float_sums_cancel") is cancel # noqa: S301 + + +@pytest.mark.parametrize("pair", READ_SERVED.values(), ids=READ_SERVED) +@pytest.mark.parametrize("name", sorted(READERS)) +def test_a_read_whose_ints_stay_exact_is_served(name, pair): + """Ints that fit 53 bits are exact as floats; ints beside ints stay ints.""" + func = getattr(nx, name) + want = READERS[name](func, read_graph_of(pair), backend="networkx") + got = READERS[name](func, read_graph_of(pair), backend="graphblas") + assert type(got) is type(want) + assert got == want + + # GraphBLAS has no type for these; a long double that is a double on this platform is not one. FOREIGN = {"timedelta64": np.timedelta64(5, "s"), "datetime64": np.datetime64("2020-01-01")} FOREIGN.update( diff --git a/graphblas_algorithms/tests/test_roundtrip.py b/graphblas_algorithms/tests/test_roundtrip.py index 5b57698..58982c3 100644 --- a/graphblas_algorithms/tests/test_roundtrip.py +++ b/graphblas_algorithms/tests/test_roundtrip.py @@ -364,7 +364,7 @@ def test_a_big_int_beside_a_float_is_left_to_networkx(): """One type for both would be a float, which cannot hold 2**62 + 1, as the note says.""" G = nx.DiGraph() G.add_weighted_edges_from([(0, 1, 2**62 + 1), (1, 2, 1.5)]) - with pytest.raises(NotImplementedError, match="would change those ints"): + with pytest.raises(NotImplementedError, match="would hold those ints as floats"): convert(G, preserve_edge_attrs=True, name="reverse")