diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..c895807 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -191,43 +191,44 @@ def get_info(): _additional_docs = { # BEGIN: additional_docs "all_pairs_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", - "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".', + "average_shortest_path_length": 'Lengths are Bellman-Ford\'s, whatever the `method`: with `method="dijkstra"`, a negative\nedge without a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found", and with Floyd-Warshall a negative cycle raises\nNetworkXUnbounded, as NetworkX 3.7 does. NetworkX 3.6\'s Floyd-Warshall gives a number\nthere, so on NetworkX 3.6 a NetworkX graph with a negative weight is left to the next\nbackend or NetworkX for Floyd-Warshall.', "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.", + "bethe_hessian_matrix": "NetworkX reads `weight` here but converts no edge data for it, so a NetworkX graph with\nweights is left to NetworkX. A backend graph's values are read where they are `weight`'s.", "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.', + "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. With `sort_neighbors`, NetworkX's walk, which hands\n`sort_neighbors` each node's neighbors in node order, not in the order they were added;\na NetworkX graph is left to the next backend or NetworkX.", + "bfs_successors": "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\nWith `sort_neighbors`, as in `bfs_edges`.", + "center": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph gets the installed NetworkX\'s own answer,\nwhich differs between its versions.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", "compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.", - "diameter": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', + "diameter": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph gets the installed NetworkX\'s own answer,\nwhich differs between its versions.\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.', + "eccentricity": 'A precomputed `sp` is left to NetworkX. The null graph gets the installed\nNetworkX\'s own answer, which differs between its versions.\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.', "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.", "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" gets the index its degree gives, where NetworkX raises\nTypeError or, if the graph is disconnected, gives inf; a NetworkX graph with such a node is\nleft to the next backend or NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', "harmonic_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', "harmonic_diameter": 'A precomputed `sp` is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', - "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.', + "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 computed as NetworkX 3.7 computes it,\nwith SciPy\'s `svds` on this backend\'s matrix. NetworkX 3.6 has no `method`; there this\nbackend takes it as its own keyword, "power_iteration" or "svd".', "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_core": "A precomputed `core_number` is left to NetworkX. A `k` that is not a real number is\ncompared with each core number as NetworkX compares it.\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` is left to NetworkX. A `k` that is not a real number is\ncompared with each core number as NetworkX compares it.\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` is left to NetworkX. A `k` that is not a real number is\ncompared with each core number as NetworkX compares it.\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` is left to NetworkX. A `k` that is not a real number is\ncompared with each core number as NetworkX compares it.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", - "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', - "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', + "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph gets the installed NetworkX\'s own answer,\nwhich differs between its versions.\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 gets the installed NetworkX\'s own answer,\nwhich differs between its versions.\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.', + "schultz_index": 'A graph with a node named "weight" gets the index its degree gives, where NetworkX raises\nTypeError or, if the graph is disconnected, gives inf; a NetworkX graph with such a node is\nleft to the next backend or 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.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..7c33edb 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -87,14 +87,20 @@ _ECCENTRICITY_BOUNDS = ( "`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\n" - "elsewhere every one is computed. The null graph is left to NetworkX.\n" - + _NEGATIVE_EDGES - + "\n" - + _PATH_OVERFLOW + "elsewhere every one is computed. The null graph gets the installed NetworkX's own answer,\n" + "which differs between its versions.\n" + _NEGATIVE_EDGES + "\n" + _PATH_OVERFLOW ) _CORE_SUBGRAPH = ( - "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX." + "A precomputed `core_number` is left to NetworkX. A `k` that is not a real number is\n" + "compared with each core number as NetworkX compares it." +) + +# NetworkX takes a node named "weight" for its `weight` argument, a bug that raises TypeError. +_NODE_NAMED_WEIGHT = ( + 'A graph with a node named "weight" gets the index its degree gives, where NetworkX raises\n' + "TypeError or, if the graph is disconnected, gives inf; a NetworkX graph with such a node is\n" + "left to the next backend or NetworkX.\n" ) # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not @@ -102,13 +108,19 @@ _ADDITIONAL_DOCS = { "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, "average_shortest_path_length": ( - 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n' - 'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n' - "without a negative cycle is answered where NetworkX's Dijkstra raises\n" - '"Contradictory paths found".' + 'Lengths are Bellman-Ford\'s, whatever the `method`: with `method="dijkstra"`, a negative\n' + "edge without a negative cycle is answered where NetworkX's Dijkstra raises\n" + '"Contradictory paths found", and with Floyd-Warshall a negative cycle raises\n' + "NetworkXUnbounded, as NetworkX 3.7 does. NetworkX 3.6's Floyd-Warshall gives a number\n" + "there, so on NetworkX 3.6 a NetworkX graph with a negative weight is left to the next\n" + "backend or NetworkX for Floyd-Warshall." ), "bellman_ford_path": _PATH_OVERFLOW, "bellman_ford_path_length": _PATH_OVERFLOW, + "bethe_hessian_matrix": ( + "NetworkX reads `weight` here but converts no edge data for it, so a NetworkX graph with\n" + "weights is left to NetworkX. A backend graph's values are read where they are `weight`'s." + ), "betweenness_centrality": ( "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX." ), @@ -116,11 +128,13 @@ "bfs_edges": ( "A breadth-first tree that may differ from NetworkX's, as may the order: a node's parent\n" "is its neighbor on the level above first in node order, and each level comes by parent,\n" - "then child, in node order. `sort_neighbors` is left to NetworkX." + "then child, in node order. With `sort_neighbors`, NetworkX's walk, which hands\n" + "`sort_neighbors` each node's neighbors in node order, not in the order they were added;\n" + "a NetworkX graph is left to the next backend or 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." + "With `sort_neighbors`, as in `bfs_edges`." ), "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, @@ -129,7 +143,8 @@ ), "cut_size": _SUM_OVERFLOW + ".", "diameter": _ECCENTRICITY_BOUNDS, - "eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n" + "eccentricity": "A precomputed `sp` is left to NetworkX. The null graph gets the installed\n" + "NetworkX's own answer, which differs between its versions.\n" + _NEGATIVE_EDGES + "\n" + _PATH_OVERFLOW, @@ -152,13 +167,14 @@ "floyd_warshall": _PATH_OVERFLOW, "floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW, "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", - "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n' - + _LENGTH_SUM_OVERFLOW, + "gutman_index": _NODE_NAMED_WEIGHT + _LENGTH_SUM_OVERFLOW, "harmonic_centrality": _NEGATIVE_EDGES, "harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES, "hits": ( "A graph with nodes and no edges gets 0.0 for every node, where NetworkX's power\n" - 'iteration does not converge. `method="svd"` is left to NetworkX.' + 'iteration does not converge. `method="svd"` is computed as NetworkX 3.7 computes it,\n' + "with SciPy's `svds` on this backend's matrix. NetworkX 3.6 has no `method`; there this\n" + 'backend takes it as its own keyword, "power_iteration" or "svd".' ), "hyper_wiener_index": _LENGTH_SUM_OVERFLOW, "k_core": _CORE_SUBGRAPH, @@ -173,8 +189,7 @@ "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, - "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' - + _LENGTH_SUM_OVERFLOW, + "schultz_index": _NODE_NAMED_WEIGHT + _LENGTH_SUM_OVERFLOW, "single_source_bellman_ford_path_length": _PATH_OVERFLOW, "volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.", "wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW, diff --git a/graphblas_algorithms/algorithms/core.py b/graphblas_algorithms/algorithms/core.py index c8310e3..451ebef 100644 --- a/graphblas_algorithms/algorithms/core.py +++ b/graphblas_algorithms/algorithms/core.py @@ -140,9 +140,14 @@ def k_crust(G, k=None, core=None): def k_corona(G, k, core=None): - """The nodes of core number k with exactly k neighbors in the k-core; successors if directed.""" + """The nodes of core number k with exactly k neighbors in the k-core; successors if directed. + + A `k` of None is the largest core number, as NetworkX takes it. + """ if core is None: core = core_number(G) + if k is None: + k = _largest(core) n = len(G) numbers = _dense(core, n) inside = Vector.from_coo(np.flatnonzero(numbers >= k), True, size=n) diff --git a/graphblas_algorithms/classes/_utils.py b/graphblas_algorithms/classes/_utils.py index fa821b1..b7936e8 100644 --- a/graphblas_algorithms/classes/_utils.py +++ b/graphblas_algorithms/classes/_utils.py @@ -78,6 +78,8 @@ def from_networkx(cls, G, weight=None, dtype=None): if reason is not None: raise NotImplementedError(reason) rv = cls() + # The class NetworkX names in its errors, such as a user's subclass of `nx.Graph`. + rv._networkx_class_name = type(G).__name__ rv._key_to_id = {k: i for i, k in enumerate(G)} if rv._key_to_id: rv._A = gb.io.from_networkx(G, nodelist=rv._key_to_id, weight=weight, dtype=dtype) diff --git a/graphblas_algorithms/nxapi/core.py b/graphblas_algorithms/nxapi/core.py index fb8a57d..7902b5c 100644 --- a/graphblas_algorithms/nxapi/core.py +++ b/graphblas_algorithms/nxapi/core.py @@ -3,6 +3,7 @@ import numpy as np from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.core import _induced from graphblas_algorithms.classes._utils import PRESERVE from graphblas_algorithms.classes.digraph import to_graph from graphblas_algorithms.classes.graph import to_undirected_graph @@ -60,11 +61,51 @@ def _own_core_numbers(bound): # with its own errors node by node. if bound.get("core_number") is not None: return "a precomputed `core_number` is not read here; networkx serves it" - if bound.get("k") is not None and not isinstance(bound["k"], Real): - return "a `k` that is not a real number is left to networkx; networkx serves it" return None +# NetworkX's test of a node `v`, with core numbers `c` and neighbors `adj[v]`, for each name. +_TESTS = { + "k_core": lambda adj, v, k, c: c[v] >= k, + "k_shell": lambda adj, v, k, c: c[v] == k, + "k_crust": lambda adj, v, k, c: c[v] <= k, + "k_corona": lambda adj, v, k, c: c[v] == k and k == sum(1 for w in adj[v] if c[w] >= k), +} + + +def _by_networkx_s_test(name, G, k): + """The subgraph whose nodes pass NetworkX's own test against a `k` that is not a number. + + NetworkX compares each core number with `k` in Python, so a `k` such as a string raises + its TypeError, a Decimal compares as a number, and a null graph compares nothing. + """ + core = _by_node(G, algorithms.core_number(G).to_dense(fill_value=0)) + test = _TESTS[name] + adj = _Neighbors(G) if name == "k_corona" else None + keep = np.zeros(len(G), bool) + key_to_id = G._key_to_id + for v in core: + if test(adj, v, k, core): + keep[key_to_id[v]] = True + return _induced(G, keep) + + +class _Neighbors: + """`G[v]` for NetworkX's k-corona test: the keys of `v`'s successors, by id.""" + + def __init__(self, G): + self._key_to_id = G._key_to_id + self._id_to_key = G.id_to_key + self._indptr, self._indices, _values = G._A.to_csr() + + def __getitem__(self, v): + i = self._key_to_id[v] + return [ + self._id_to_key[j] + for j in self._indices[self._indptr[i] : self._indptr[i + 1]].tolist() + ] + + def _max_of_nothing(): try: return max(()) @@ -80,45 +121,53 @@ def _check_subgraph_call(G, k): raise ValueError(*_max_of_nothing().args) -def _refuse_what_can_run_declines(k, core_number): +def _refuse_what_can_run_declines(core_number): # A direct call does not pass through `can_run`. - if (reason := _own_core_numbers({"k": k, "core_number": core_number})) is not None: + if (reason := _own_core_numbers({"core_number": core_number})) is not None: raise NotImplementedError(reason) @can_run(_own_core_numbers) @not_implemented_for("multigraph") def k_core(G, k=None, core_number=None): - _refuse_what_can_run_declines(k, core_number) + _refuse_what_can_run_declines(core_number) G = to_graph(G, weight=PRESERVE) _check_subgraph_call(G, k) + if k is not None and not isinstance(k, Real): + return _by_networkx_s_test("k_core", G, k) return algorithms.k_core(G, k) @can_run(_own_core_numbers) @not_implemented_for("multigraph") def k_shell(G, k=None, core_number=None): - _refuse_what_can_run_declines(k, core_number) + _refuse_what_can_run_declines(core_number) G = to_graph(G, weight=PRESERVE) _check_subgraph_call(G, k) + if k is not None and not isinstance(k, Real): + return _by_networkx_s_test("k_shell", G, k) return algorithms.k_shell(G, k) @can_run(_own_core_numbers) @not_implemented_for("multigraph") def k_crust(G, k=None, core_number=None): - _refuse_what_can_run_declines(k, core_number) + _refuse_what_can_run_declines(core_number) G = to_graph(G, weight=PRESERVE) _check_subgraph_call(G, k) + if k is not None and not isinstance(k, Real): + return _by_networkx_s_test("k_crust", G, k) return algorithms.k_crust(G, k) @can_run(_own_core_numbers) @not_implemented_for("multigraph") def k_corona(G, k, core_number=None): - _refuse_what_can_run_declines(k, core_number) + _refuse_what_can_run_declines(core_number) G = to_graph(G, weight=PRESERVE) _check_subgraph_call(G, k) + if k is not None and not isinstance(k, Real): + return _by_networkx_s_test("k_corona", G, k) return algorithms.k_corona(G, k) diff --git a/graphblas_algorithms/nxapi/distance_measures.py b/graphblas_algorithms/nxapi/distance_measures.py index dc8e353..e228780 100644 --- a/graphblas_algorithms/nxapi/distance_measures.py +++ b/graphblas_algorithms/nxapi/distance_measures.py @@ -7,19 +7,25 @@ __all__ = ["center", "diameter", "eccentricity", "harmonic_diameter", "periphery", "radius"] -def _with_nodes(bound): - # NetworkX 3.6 answers the null graph with an empty dict or a ValueError, 3.7 with - # NetworkXPointlessConcept, and `usebounds` with a ValueError; each version answers its own. - if len(bound["G"]) == 0: - return "NetworkX's answer for the null graph depends on its version; networkx serves it" +def _without_sp_on_nodes(bound): + # Rebuilding a matrix from the caller's dict would cost more than the walks it saves. The + # null graph's answer is NetworkX's own, whatever `sp` holds. + if bound.get("sp") is not None and len(bound["G"]) > 0: + return "eccentricity does not read a precomputed `sp`; networkx serves it" return None -def _with_nodes_without_sp(bound): - # Rebuilding a matrix from the caller's dict would cost more than the walks it saves. - if bound.get("sp") is not None: - return "eccentricity does not read a precomputed `sp`; networkx serves it" - return _with_nodes(bound) +def _networkx_on_the_null_graph(name, G, **kwargs): + """NetworkX's own answer for a null graph like `G`: it differs between NetworkX's versions. + + NetworkX 3.6 answers with an empty dict or a ValueError, and later versions with + NetworkXPointlessConcept, except `usebounds` with a ValueError. A null graph holds nothing + to convert or walk, so the installed NetworkX is asked directly. + """ + import networkx as nx + + null = nx.DiGraph() if G.is_directed() else nx.Graph() + return getattr(nx, name)(null, backend="networkx", **kwargs) def _without_sp(bound): @@ -57,9 +63,11 @@ def _extreme_nodes(e, pick): return [v for v in e if e[v] == target] -@can_run(_with_nodes_without_sp) +@can_run(_without_sp_on_nodes) def eccentricity(G, v=None, sp=None, weight=None): - if (reason := _with_nodes_without_sp({"G": G, "sp": sp})) is not None: + if len(G) == 0: + return _networkx_on_the_null_graph("eccentricity", G, v=v, sp=sp, weight=weight) + if (reason := _without_sp_on_nodes({"G": G, "sp": sp})) is not None: raise NotImplementedError(reason) G = to_graph(G, weight=weight) keys = nbunch_keys(G, v, unique=True) @@ -69,40 +77,36 @@ def eccentricity(G, v=None, sp=None, weight=None): return {key: ecc[key] for key in (G if keys is None else keys)} -@can_run(_with_nodes) def diameter(G, e=None, usebounds=False, weight=None): - if (reason := _with_nodes({"G": G})) is not None: - raise NotImplementedError(reason) + if len(G) == 0: + return _networkx_on_the_null_graph("diameter", G, e=e, usebounds=usebounds, weight=weight) if e is not None: return max(e.values()) G = to_graph(G, weight=weight) return _answer(G, algorithms.diameter, usebounds=usebounds is True) -@can_run(_with_nodes) def radius(G, e=None, usebounds=False, weight=None): - if (reason := _with_nodes({"G": G})) is not None: - raise NotImplementedError(reason) + if len(G) == 0: + return _networkx_on_the_null_graph("radius", G, e=e, usebounds=usebounds, weight=weight) if e is not None: return min(e.values()) G = to_graph(G, weight=weight) return _answer(G, algorithms.radius, usebounds=usebounds is True) -@can_run(_with_nodes) def periphery(G, e=None, usebounds=False, weight=None): - if (reason := _with_nodes({"G": G})) is not None: - raise NotImplementedError(reason) + if len(G) == 0: + return _networkx_on_the_null_graph("periphery", G, e=e, usebounds=usebounds, weight=weight) if e is not None: return _extreme_nodes(e, max) G = to_graph(G, weight=weight) return _in_node_order(G, _answer(G, algorithms.periphery, usebounds=usebounds is True)) -@can_run(_with_nodes) def center(G, e=None, usebounds=False, weight=None): - if (reason := _with_nodes({"G": G})) is not None: - raise NotImplementedError(reason) + if len(G) == 0: + return _networkx_on_the_null_graph("center", G, e=e, usebounds=usebounds, weight=weight) if e is not None: return _extreme_nodes(e, min) G = to_graph(G, weight=weight) diff --git a/graphblas_algorithms/nxapi/linalg/bethehessianmatrix.py b/graphblas_algorithms/nxapi/linalg/bethehessianmatrix.py index 3ec28f2..97186c0 100644 --- a/graphblas_algorithms/nxapi/linalg/bethehessianmatrix.py +++ b/graphblas_algorithms/nxapi/linalg/bethehessianmatrix.py @@ -4,29 +4,33 @@ from graphblas_algorithms.classes.graph import Graph, to_undirected_graph from graphblas_algorithms.utils import not_implemented_for +from .._cache import remembered from .._utils import can_run, check_nodelist __all__ = ["bethe_hessian_matrix"] -def _unweighted_only(bound): - """Decline a weighted graph. +def _weights_converted(bound): + """Decline a NetworkX graph with weights, which NetworkX's conversion would leave behind. - NetworkX reads `weight` here without declaring it, so a NetworkX graph's weights never - reach this backend; a backend graph's values may be another attribute's, so it is - declined whenever it has any. + NetworkX reads `weight` here without declaring it, so its conversion for this name carries + no edge data. A backend graph is served: its values are read where they are `weight`'s, + and otherwise every edge weighs 1, as NetworkX reads the graph. """ G = bound["G"] - if isinstance(G, Graph): - weighted = G._weight is not None - else: - weighted = any("weight" in data for _u, _v, data in G.edges(data=True)) - if weighted: - return "bethe_hessian_matrix is unweighted here; networkx serves a weighted graph" + if not isinstance(G, Graph) and remembered(G, ("edge attribute", "weight"), _has_weights): + return ( + "NetworkX converts no edge data for bethe_hessian_matrix, which reads `weight`; " + "a NetworkX graph with weights is left to the next backend or NetworkX" + ) return None -@can_run(_unweighted_only) +def _has_weights(G): + return any("weight" in data for _u, _v, data in G.edges(data=True)) + + +@can_run(_weights_converted) @not_implemented_for("directed") @not_implemented_for("multigraph") def bethe_hessian_matrix(G, r=None, nodelist=None): diff --git a/graphblas_algorithms/nxapi/link_analysis/hits_alg.py b/graphblas_algorithms/nxapi/link_analysis/hits_alg.py index 7936df0..78aa08c 100644 --- a/graphblas_algorithms/nxapi/link_analysis/hits_alg.py +++ b/graphblas_algorithms/nxapi/link_analysis/hits_alg.py @@ -1,27 +1,53 @@ +from graphblas import io as gb_io + from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run from ..exception import NetworkXError, PowerIterationFailedConvergence __all__ = ["hits"] -def _power_iteration_only(bound): - # NetworkX's two methods can return different vectors for one graph; this backend computes - # the power iteration. - if (method := bound.get("method", "power_iteration")) != "power_iteration": - return f"hits method {method!r} is not implemented here; networkx serves it" - return None +def _by_node(G, values): + """`values`, indexed by id, as a dict of Python floats in `G`'s node order.""" + return dict(zip(G._key_to_id, values[list(G._key_to_id.values())].tolist(), strict=True)) + + +def _hits_svd(G, max_iter, tol, nstart, normalized): + """NetworkX's `method="svd"`, the largest singular vectors of the matrix by SciPy's `svds`. + + The calls are NetworkX's, on this backend's matrix: `nstart` is the start vector in the + order its values come, `max_iter` and `tol` go to ARPACK, and the vectors' sign, which + ARPACK picks, stays unless `normalized` divides it out. + """ + import numpy as np + import scipy as sp + + A = gb_io.to_scipy_sparse(G._A, format="csr") + if nstart is not None: + nstart = np.array(list(nstart.values())) + if max_iter <= 0: + raise PowerIterationFailedConvergence(max_iter) + try: + _, _, vt = sp.sparse.linalg.svds(A, k=1, v0=nstart, maxiter=max_iter, tol=tol) + except sp.sparse.linalg.ArpackNoConvergence as exc: + raise PowerIterationFailedConvergence(max_iter) from exc + a = vt.flatten().real + h = A @ a + if normalized: + h /= h.sum() + a /= a.sum() + return _by_node(G, h), _by_node(G, a) -@can_run(_power_iteration_only) def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True, *, method="power_iteration"): - if (reason := _power_iteration_only({"method": method})) is not None: - raise NotImplementedError(reason) + if method not in ("power_iteration", "svd"): + raise ValueError(f"method not supported: {method}") G = to_graph(G, weight="weight", dtype=float) if len(G) == 0: return {}, {} + if method == "svd": + return _hits_svd(G, max_iter, tol, nstart, normalized) x = None if nstart is not None: if missing := G._key_to_id.keys() - nstart.keys(): diff --git a/graphblas_algorithms/nxapi/reciprocity.py b/graphblas_algorithms/nxapi/reciprocity.py index 3e6685d..06940db 100644 --- a/graphblas_algorithms/nxapi/reciprocity.py +++ b/graphblas_algorithms/nxapi/reciprocity.py @@ -1,25 +1,56 @@ from graphblas_algorithms import algorithms -from graphblas_algorithms.classes.digraph import to_directed_graph +from graphblas_algorithms.classes.digraph import to_directed_graph, to_graph from graphblas_algorithms.utils import not_implemented_for -from ._utils import can_run, nbunch_keys +from ._utils import nbunch_keys from .exception import NetworkXError __all__ = ["overall_reciprocity", "reciprocity"] -def _directed_only(bound): - # The kernel is directed-only, and NetworkX answers an undirected graph. - if not bound["G"].is_directed(): - return "reciprocity is directed-only here; networkx serves the undirected case" - return None +def _class_name(G): + """The name of the class of the caller's graph, which `from_networkx` records.""" + return getattr(G, "_networkx_class_name", None) or type(G).__name__ -# Two decorators: one call with two types refuses only a graph that is both. -@can_run(_directed_only) -@not_implemented_for("undirected") -@not_implemented_for("multigraph") +def _undirected_reciprocity(G, nodes, cls): + """NetworkX's answers for an undirected graph, which its code meets as a directed one. + + The overall reciprocity is 0.0, as no edge is lost making the graph undirected. For nodes, + NetworkX asks the first node it has for its predecessors, which an undirected graph lacks; + its error names the class of the caller's graph, `cls`. + """ + if nodes is None: + if G._A.nvals == 0: + raise NetworkXError("Not defined for empty graphs") + return 0.0 + if nodes in G: + found = True + else: + try: + iterator = iter(nodes) + except TypeError: + raise NetworkXError(f"Node {nodes} is not in the graph.") from None + found = False + for node in iterator: + try: + found = node in G._key_to_id + except TypeError: + raise NetworkXError( + f"Node {node} in sequence nbunch is not a valid node." + ) from None + if found: + break + if found: + raise AttributeError(f"'{cls}' object has no attribute 'predecessors'") + return {} + + +# NetworkX's decorator: one call with two types refuses only a graph that is both. +@not_implemented_for("undirected", "multigraph") def reciprocity(G, nodes=None): + if not G.is_directed(): + return _undirected_reciprocity(to_graph(G, dtype=bool), nodes, _class_name(G)) if nodes is None: return overall_reciprocity(G) G = to_directed_graph(G, dtype=bool) @@ -38,10 +69,10 @@ def reciprocity(G, nodes=None): return {node: rv.get(node) for node in keys} -@can_run(_directed_only) -@not_implemented_for("undirected") -@not_implemented_for("multigraph") +@not_implemented_for("undirected", "multigraph") def overall_reciprocity(G): + if not G.is_directed(): + return _undirected_reciprocity(to_graph(G, dtype=bool), None, _class_name(G)) G = to_directed_graph(G, dtype=bool) try: return algorithms.overall_reciprocity(G) diff --git a/graphblas_algorithms/nxapi/shortest_paths/generic.py b/graphblas_algorithms/nxapi/shortest_paths/generic.py index cdcf0fe..df8258f 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/generic.py +++ b/graphblas_algorithms/nxapi/shortest_paths/generic.py @@ -1,7 +1,10 @@ +import functools + from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run +from .._cache import _in_networkx_test_mode, remembered +from .._utils import should_run from ..exception import NetworkXError, NetworkXPointlessConcept, NetworkXUnbounded, NodeNotFound __all__ = ["average_shortest_path_length", "has_path"] @@ -15,22 +18,87 @@ def has_path(G, source, target): raise NodeNotFound(*e.args) from e -def _single_source(bound): - # Floyd-Warshall answers a negative cycle with a number, where the walk here raises. - if (method := bound.get("method")) not in (None, "unweighted", "dijkstra", "bellman-ford"): +_METHODS = ("unweighted", "dijkstra", "bellman-ford", "floyd-warshall", "floyd-warshall-numpy") + + +@functools.cache +def _networkx_finds_negative_cycles(method): + """Whether the installed NetworkX's Floyd-Warshall for `method` raises on a negative cycle. + + NetworkX 3.7's does, as this backend does; NetworkX 3.6's gives a number. The answer is kept + for the process, so it comes from NetworkX's own code, called without dispatching it and + without writing NetworkX's config, which other threads share. `floyd_warshall` raises only + through `floyd_warshall_predecessor_and_distance`, whose own code calls nothing dispatched, so + that is run for "floyd-warshall". `floyd_warshall_numpy`'s own code calls the dispatched + `to_numpy_array`, which this backend does not implement; NetworkX's test mode hands that call + to the backend under test anyway, where it raises pytest's xfail, so there the numpy method + gets the other method's answer. Any other error counts as no, which leaves a graph with a + negative weight to NetworkX. + """ + import networkx as nx + + if method == "floyd-warshall-numpy" and _in_networkx_test_mode(): + return _networkx_finds_negative_cycles("floyd-warshall") + try: + # In the `try`: under a priority for `classes`, a backend may make this graph, as it likes. + cycle = nx.DiGraph() + cycle.add_edge(0, 1, weight=-2) + cycle.add_edge(1, 0, weight=1) + if method == "floyd-warshall": + nx.floyd_warshall_predecessor_and_distance.orig_func(cycle) + else: + nx.floyd_warshall_numpy.orig_func(cycle) + except nx.NetworkXUnbounded: + return True + except Exception: + return False + return False + + +def _has_negative_weight(G, weight): + """Whether an edge of the NetworkX graph `G` has a `weight` below 0, read once a version.""" + + def scan(G): + try: + return any(value < 0 for _u, _v, value in G.edges(data=weight, default=1)) + except TypeError: + return True # a value that does not compare with 0 may be anything + + return remembered(G, ("negative weight", weight), scan) + + +def _floyd_warshall_as_networkx(bound): + # Without a negative weight there is no negative cycle, and every method gives one mean. + method = bound.get("method") + if ( + method in ("floyd-warshall", "floyd-warshall-numpy") + and (weight := bound.get("weight")) is not None + and not _networkx_finds_negative_cycles(method) + and _has_negative_weight(bound["G"], weight) + ): return ( - "average_shortest_path_length answers the single-source methods; networkx serves " - f"method={method!r}" + f"average_shortest_path_length with method={method!r} on a negative weight: this " + "NetworkX's Floyd-Warshall gives a number for a negative cycle, where this backend " + "raises NetworkXUnbounded; left to the next backend or NetworkX" ) return None -@can_run(_single_source) +@should_run(_floyd_warshall_as_networkx) def average_shortest_path_length(G, weight=None, method=None): - if (reason := _single_source({"method": method})) is not None: - raise NotImplementedError(reason) + """The mean as NetworkX gives it, by any `method`. + + Every method gives one mean, and so does this backend, which finds its lengths alone. On a + negative cycle it raises what NetworkX raises: `NetworkXUnbounded` for Bellman-Ford and, + from NetworkX 3.7, Floyd-Warshall, and for Dijkstra a ValueError. NetworkX 3.6's + Floyd-Warshall gives a number there; this backend raises for a backend graph and for + `backend="graphblas"`, and where NetworkX would convert a graph with a negative weight for + Floyd-Warshall, `should_run` leaves the call to it. + """ if method is None: method = "unweighted" if weight is None else "dijkstra" + if method not in _METHODS: + raise ValueError(f"method not supported: {method}") G = to_graph(G, weight=None if method == "unweighted" else weight) try: return algorithms.average_shortest_path_length(G) @@ -40,7 +108,7 @@ def average_shortest_path_length(G, weight=None, method=None): strongly = "strongly " if G.is_directed() else "" raise NetworkXError(f"Graph is not {strongly}connected.") from e except algorithms.exceptions.Unbounded as e: - if method == "bellman-ford": + if method != "dijkstra": raise NetworkXUnbounded("Negative cycle detected.") from e # What NetworkX's Dijkstra raises on a negative cycle. raise ValueError("Contradictory paths found:", "negative weights?") from e diff --git a/graphblas_algorithms/nxapi/tests/test_core.py b/graphblas_algorithms/nxapi/tests/test_core.py index 0d0f8f3..1b412f6 100644 --- a/graphblas_algorithms/nxapi/tests/test_core.py +++ b/graphblas_algorithms/nxapi/tests/test_core.py @@ -154,11 +154,10 @@ def test_multigraphs_are_refused(name): @pytest.mark.parametrize( - ("args", "kwargs"), - [((), {"core_number": {0: 1, 1: 1, 2: 1}}), ((None, {0: 1}), {}), ((1j,), {}), (("2",), {})], + ("args", "kwargs"), [((), {"core_number": {0: 1, 1: 1, 2: 1}}), ((None, {0: 1}), {})] ) @pytest.mark.parametrize("name", ["k_core", "k_shell", "k_crust", "k_corona"]) -def test_a_precomputed_core_number_or_an_odd_k_is_left_to_networkx(name, args, kwargs): +def test_a_precomputed_core_number_is_left_to_networkx(name, args, kwargs): G = nx.path_graph(3) if name == "k_corona" and not args: args = (1,) diff --git a/graphblas_algorithms/nxapi/tests/test_distance_measures.py b/graphblas_algorithms/nxapi/tests/test_distance_measures.py index de9e088..b5da2fc 100644 --- a/graphblas_algorithms/nxapi/tests/test_distance_measures.py +++ b/graphblas_algorithms/nxapi/tests/test_distance_measures.py @@ -365,20 +365,6 @@ def test_an_empty_e_raises_what_networkx_raises(name): assert raised(name, G, e={}, backend="graphblas") == raised(name, G, e={}) -@pytest.mark.parametrize("name", ECCENTRICITY_NAMES) -@pytest.mark.parametrize("cls", [nx.Graph, nx.DiGraph]) -def test_the_null_graph_is_declined(name, cls): - """NetworkX answers it differently from one release to the next, and with `usebounds`.""" - G = cls() - reason = Dispatcher.can_run(name, (G,), {}) - assert isinstance(reason, str) - assert isinstance(Dispatcher.can_run(name, (ga.Graph.from_networkx(G),), {}), str) - assert Dispatcher.can_run(name, (nx.empty_graph(1, create_using=cls),), {}) is True - with pytest.raises(NotImplementedError, match="null graph") as info: - getattr(nxapi, name)(G) - assert str(info.value) == reason - - def test_eccentricity_declines_a_precomputed_sp(): G = nx.path_graph(4) sp = dict(nx.shortest_path_length(G)) @@ -562,19 +548,6 @@ def G(): assert got == pytest.approx(func(G(), weight="weight"), rel=1e-12) -@pytest.mark.parametrize("method", ["floyd-warshall", "floyd-warshall-numpy", "SPAM"]) -def test_average_leaves_other_methods_to_networkx(method): - G = weighted(nx.path_graph(4)) - reason = Dispatcher.can_run("average_shortest_path_length", (G,), {"method": method}) - assert isinstance(reason, str) - assert reason == Dispatcher.can_run("average_shortest_path_length", (G, "cost", method), {}) - with pytest.raises(NotImplementedError) as info: - nxapi.average_shortest_path_length(G, "cost", method) - assert str(info.value) == reason - for served in [None, "unweighted", "dijkstra", "bellman-ford"]: - assert Dispatcher.can_run("average_shortest_path_length", (G,), {"method": served}) is True - - @pytest.mark.parametrize("name", ["average_shortest_path_length", "harmonic_diameter"]) @WEIGHTS def test_sums_in_batches_of_one_source_give_the_same_answer(name, weight, monkeypatch): diff --git a/graphblas_algorithms/nxapi/tests/test_link_analysis.py b/graphblas_algorithms/nxapi/tests/test_link_analysis.py index 9bd75ee..468c919 100644 --- a/graphblas_algorithms/nxapi/tests/test_link_analysis.py +++ b/graphblas_algorithms/nxapi/tests/test_link_analysis.py @@ -6,7 +6,6 @@ import numpy as np import pytest -from graphblas_algorithms import DiGraph, nxapi from graphblas_algorithms.interface import Dispatcher NX_HITS_TAKES_METHOD = "method" in inspect.signature(nx.hits).parameters @@ -48,21 +47,6 @@ def test_hits_serves_the_power_iteration(): assert Dispatcher.can_run("hits", (G,), {"method": "power_iteration"}) is True -@pytest.mark.skipif(not NX_HITS_TAKES_METHOD, reason="NetworkX has no `method` before 3.7") -@pytest.mark.parametrize("method", ["svd", "spam"]) -def test_hits_declines_any_other_method(method): - """The methods can return different vectors for one graph, so NetworkX answers "svd".""" - G = hits_graph() - reason = Dispatcher.can_run("hits", (G,), {"method": method}) - assert isinstance(reason, str) - assert repr(method) in reason - with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): - nx.hits(G, method=method, backend="graphblas") - with pytest.raises(NotImplementedError) as excinfo: - nxapi.hits(DiGraph.from_networkx(G), method=method) - assert str(excinfo.value) == reason - - @pytest.mark.parametrize( ("n", "cls"), [(1, nx.Graph), (2, nx.Graph), (1, nx.DiGraph)], diff --git a/graphblas_algorithms/nxapi/tests/test_reciprocity.py b/graphblas_algorithms/nxapi/tests/test_reciprocity.py index d91fd0e..e1b9c29 100644 --- a/graphblas_algorithms/nxapi/tests/test_reciprocity.py +++ b/graphblas_algorithms/nxapi/tests/test_reciprocity.py @@ -1,8 +1,6 @@ import networkx as nx import pytest -from graphblas_algorithms import Graph, nxapi - def _outcome(func, *args, **kwargs): """The answer as a plain dict, or the exception's type and message.""" @@ -19,17 +17,6 @@ def _with_isolated_node(): return G -@pytest.mark.parametrize("name", ["reciprocity", "overall_reciprocity"]) -@pytest.mark.parametrize( - "make", - [nx.path_graph, lambda n: Graph.from_networkx(nx.path_graph(n))], - ids=["networkx graph", "backend graph"], -) -def test_reciprocity_refuses_an_undirected_graph(make, name): - with pytest.raises(nx.NetworkXNotImplemented, match="undirected"): - getattr(nxapi, name)(make(3)) - - @pytest.mark.parametrize( "make", [ diff --git a/graphblas_algorithms/nxapi/tests/test_traversal.py b/graphblas_algorithms/nxapi/tests/test_traversal.py index fd83bef..274915b 100644 --- a/graphblas_algorithms/nxapi/tests/test_traversal.py +++ b/graphblas_algorithms/nxapi/tests/test_traversal.py @@ -5,9 +5,6 @@ import networkx as nx import pytest -from graphblas_algorithms import nxapi -from graphblas_algorithms.interface import Dispatcher - pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") CALLS = { @@ -198,26 +195,6 @@ def test_an_absent_source_raises_on_the_first_step_as_networkx_does(name): next(calls) -@pytest.mark.parametrize( - ("name", "args", "kwargs"), - [ - ("bfs_edges", (0,), {"sort_neighbors": sorted}), - ("bfs_edges", (0, False, None, sorted), {}), - ("bfs_successors", (0,), {"sort_neighbors": sorted}), - ("bfs_successors", (0, None, sorted), {}), - ], - ids=["bfs_edges", "bfs_edges by position", "bfs_successors", "bfs_successors by position"], -) -def test_sort_neighbors_is_declined(name, args, kwargs): - G = nx.path_graph(4) - assert Dispatcher.can_run(name, (G, 0), {"sort_neighbors": None}) is True - reason = Dispatcher.can_run(name, (G, *args), kwargs) - assert isinstance(reason, str) - with pytest.raises(NotImplementedError) as direct: - list(getattr(nxapi, name)(G, *args, **kwargs)) - assert str(direct.value) == reason - - @BFS_NAMES def test_the_tree_s_difference_is_in_networkx_s_docs(name): from _nx_graphblas import get_info diff --git a/graphblas_algorithms/nxapi/tests/test_wiener.py b/graphblas_algorithms/nxapi/tests/test_wiener.py index 2bdc3e5..f8935ef 100644 --- a/graphblas_algorithms/nxapi/tests/test_wiener.py +++ b/graphblas_algorithms/nxapi/tests/test_wiener.py @@ -5,9 +5,6 @@ import networkx as nx import pytest -from graphblas_algorithms import nxapi -from graphblas_algorithms.interface import Dispatcher - pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") UNDIRECTED = ["schultz_index", "gutman_index", "hyper_wiener_index"] @@ -119,14 +116,3 @@ def test_a_directed_negative_edge_without_a_negative_cycle_is_answered(): lengths = dict(nx.floyd_warshall(G, weight="weight")) expected = sum(d for row in lengths.values() for d in row.values()) assert nx.wiener_index(G, weight="weight", backend="graphblas") == expected - - -@pytest.mark.parametrize("name", ["schultz_index", "gutman_index"]) -def test_declines_a_node_named_weight(name): - G = nx.Graph([("weight", 1), (1, 2)]) - reason = Dispatcher.can_run(name, (G,), {}) - assert isinstance(reason, str) - with pytest.raises(NotImplementedError) as direct: - getattr(nxapi, name)(G) - assert str(direct.value) == reason - assert Dispatcher.can_run(name, (nx.Graph([(0, 1)]),), {}) is True diff --git a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py index 1c4afc2..d710fc6 100644 --- a/graphblas_algorithms/nxapi/traversal/breadth_first_search.py +++ b/graphblas_algorithms/nxapi/traversal/breadth_first_search.py @@ -1,7 +1,7 @@ from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run +from .._utils import should_run from ..exception import NetworkXError __all__ = [ @@ -13,14 +13,60 @@ def _without_sort_neighbors(bound): - # The order a node's neighbors are walked in picks the tree, and a matrix keeps none. + # NetworkX hands `sort_neighbors` each node's neighbors in the order they were added, which + # a matrix does not keep; and this walk runs in Python, where NetworkX's own walk of its own + # graph is faster. if bound.get("sort_neighbors") is not None: return ( - "a GraphBLAS matrix keeps no neighbor order to sort; networkx serves `sort_neighbors`" + "a walk with `sort_neighbors` hands it each node's neighbors in the order they were " + "added, which a matrix does not keep; left to the next backend or NetworkX" ) return None +def _sorted_bfs_edges(G, source, reverse, depth_limit, sort_neighbors): + """NetworkX's breadth-first walk, asking `sort_neighbors` for each node's neighbors in turn. + + Each node's neighbors come to `sort_neighbors` in the graph's node order. For a function + that sorts by the nodes, such as `sorted`, the tree is NetworkX's. + """ + directed = G.is_directed() + A = G.get_property("AT") if reverse and directed else G._A + indptr, indices, _values = A.to_csr() + key_to_id = G._key_to_id + id_to_key = G.id_to_key + kind = "digraph" if directed else "graph" + + def neighbors(node): + try: + i = key_to_id[node] + except KeyError: + # NetworkX's message is its neighbor iterator's. + raise NetworkXError(f"The node {node} is not in the {kind}.") from None + ids = indices[indptr[i] : indptr[i + 1]].tolist() + return iter(sort_neighbors(id_to_key[j] for j in ids)) + + # NetworkX's `generic_bfs_edges`. + if depth_limit is None: + depth_limit = len(G) + seen = {source} + n = len(G) + depth = 0 + next_parents_children = [(source, neighbors(source))] + while next_parents_children and depth < depth_limit: + this_parents_children = next_parents_children + next_parents_children = [] + for parent, children in this_parents_children: + for child in children: + if child not in seen: + seen.add(child) + next_parents_children.append((child, neighbors(child))) + yield parent, child + if len(seen) == n: + return + depth += 1 + + def _check_source(G, source): # The mapping, not `G`, so that an unhashable source raises TypeError, as in NetworkX. if source not in G._key_to_id: @@ -29,22 +75,37 @@ def _check_source(G, source): raise NetworkXError(f"The node {source} is not in the {kind}.") -@can_run(_without_sort_neighbors) +@should_run(_without_sort_neighbors) def bfs_edges(G, source, reverse=False, depth_limit=None, sort_neighbors=None): - """A breadth-first tree that may differ from NetworkX's (see the backend's notes).""" - if (reason := _without_sort_neighbors({"sort_neighbors": sort_neighbors})) is not None: - raise NotImplementedError(reason) + """A breadth-first tree that may differ from NetworkX's (see the backend's notes). + + With `sort_neighbors`, NetworkX's walk, as `_sorted_bfs_edges` gives it. + """ G = to_graph(G) + if sort_neighbors is not None: + yield from _sorted_bfs_edges(G, source, reverse, depth_limit, sort_neighbors) + return _check_source(G, source) yield from algorithms.bfs_edges(G, source, reverse=reverse, depth_limit=depth_limit) -@can_run(_without_sort_neighbors) +@should_run(_without_sort_neighbors) def bfs_successors(G, source, depth_limit=None, sort_neighbors=None): """The children in `bfs_edges`'s tree, which may differ from NetworkX's.""" - if (reason := _without_sort_neighbors({"sort_neighbors": sort_neighbors})) is not None: - raise NotImplementedError(reason) G = to_graph(G) + if sort_neighbors is not None: + # NetworkX's grouping of its edges by parent. + parent = source + children = [] + for p, c in _sorted_bfs_edges(G, source, False, depth_limit, sort_neighbors): + if p == parent: + children.append(c) + continue + yield (parent, children) + children = [c] + parent = p + yield (parent, children) + return _check_source(G, source) yield from algorithms.bfs_successors(G, source, depth_limit=depth_limit) diff --git a/graphblas_algorithms/nxapi/wiener.py b/graphblas_algorithms/nxapi/wiener.py index add0617..744bb0a 100644 --- a/graphblas_algorithms/nxapi/wiener.py +++ b/graphblas_algorithms/nxapi/wiener.py @@ -2,7 +2,7 @@ from graphblas_algorithms.classes.digraph import to_graph from graphblas_algorithms.utils import not_implemented_for -from ._utils import can_run +from ._utils import should_run from .exception import NetworkXPointlessConcept __all__ = ["gutman_index", "hyper_wiener_index", "schultz_index", "wiener_index"] @@ -22,41 +22,38 @@ def _answer(kernel, G): def _no_node_named_weight(name): def hook(bound): # NetworkX's degrees are `dict(G.degree, weight=weight)`: a node named "weight" gets the - # argument as its degree, and the sum raises TypeError. + # argument as its degree, and the sum raises TypeError, or the graph is disconnected and + # the index is inf. This backend gives the index the node's degree makes. if "weight" in bound["G"]: - return f'{name} on a node named "weight" raises in networkx; networkx serves it' + return ( + f'{name} with a node named "weight": NetworkX takes that node\'s degree from the ' + "`weight` argument, and this backend from its edges; left to the next backend " + "or NetworkX" + ) return None return hook -_schultz_rule = _no_node_named_weight("schultz_index") -_gutman_rule = _no_node_named_weight("gutman_index") - - def wiener_index(G, weight=None): G = to_graph(G, weight=weight) return _answer(algorithms.wiener_index, G) -@can_run(_schultz_rule) +@should_run(_no_node_named_weight("schultz_index")) @not_implemented_for("directed") @not_implemented_for("multigraph") def schultz_index(G, weight=None): - # Again here: a direct call does not pass through `can_run`. - if (reason := _schultz_rule({"G": G, "weight": weight})) is not None: - raise NotImplementedError(reason) + """The index NetworkX gives, here also for a graph with a node named "weight".""" G = to_graph(G, weight=weight) return _answer(algorithms.schultz_index, G) -@can_run(_gutman_rule) +@should_run(_no_node_named_weight("gutman_index")) @not_implemented_for("directed") @not_implemented_for("multigraph") def gutman_index(G, weight=None): - # As in `schultz_index`. - if (reason := _gutman_rule({"G": G, "weight": weight})) is not None: - raise NotImplementedError(reason) + """As `schultz_index`, with a node named "weight" too.""" G = to_graph(G, weight=weight) return _answer(algorithms.gutman_index, G) diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index fd74a43..ca1e1e0 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -411,13 +411,6 @@ def hook(bound): assert seen == [{"G": G, "nodes": [0]}, {"G": G, "nodes": None}, {"G": G, "nodes": None}] -def test_reciprocity_declines_an_undirected_graph_networkx_serves(): - for name in ("overall_reciprocity", "reciprocity"): - assert isinstance(Dispatcher.can_run(name, (nx.path_graph(3),), {}), str) - directed = nx.path_graph(3, create_using=nx.DiGraph) - assert Dispatcher.can_run(name, (directed,), {}) is True - - def test_square_clustering_declines_a_directed_graph(): directed = nx.path_graph(4, create_using=nx.DiGraph) assert isinstance(Dispatcher.can_run("square_clustering", (directed,), {}), str) @@ -432,14 +425,6 @@ def test_bethe_hessian_matrix_declines_a_weighted_graph(): assert Dispatcher.can_run("bethe_hessian_matrix", (nx.path_graph(3),), {}) is True -def test_bethe_hessian_matrix_declines_a_backend_graph_with_values(): - G = nx.Graph([(0, 1), (1, 2)]) - weighted = nx.Graph([(0, 1, {"cost": 2.0}), (1, 2, {"cost": 3.0})]) - assert Dispatcher.can_run("bethe_hessian_matrix", (Graph.from_networkx(G),), {}) is True - backend = Graph.from_networkx(weighted, weight="cost") - assert isinstance(Dispatcher.can_run("bethe_hessian_matrix", (backend,), {}), str) - - # Graphs carrying data a rebuilt graph would have to keep and a matrix cannot hold. def two_edge_attributes(): G = nx.Graph() diff --git a/graphblas_algorithms/tests/test_every_path.py b/graphblas_algorithms/tests/test_every_path.py new file mode 100644 index 0000000..73c9efd --- /dev/null +++ b/graphblas_algorithms/tests/test_every_path.py @@ -0,0 +1,758 @@ +"""Calls this backend once declined, now answered as NetworkX answers them, by each path. + +Each case is called on a backend graph, with `backend="graphblas"` on a NetworkX graph, and with +NetworkX choosing the backend; each gives NetworkX's answer or error, or, where NetworkX has a +bug, the answer documented here, while the call NetworkX dispatches itself gets NetworkX's. +""" + +import inspect +import math +from decimal import Decimal +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest +from networkx.utils import backends + +import graphblas_algorithms as ga +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + + +@pytest.fixture +def conversions(monkeypatch): + """The NetworkX graphs this backend converts, in order.""" + seen = [] + convert = Dispatcher.convert_from_nx + + def spy(G, *args, **kwargs): + seen.append(G) + return convert(G, *args, **kwargs) + + monkeypatch.setattr(Dispatcher, "convert_from_nx", staticmethod(spy)) + return seen + + +def outcome(func, *args, **kwargs): + """What a caller sees: the answer, a generator's items, or the error's type and message.""" + try: + rv = func(*args, **kwargs) + if inspect.isgenerator(rv): + rv = list(rv) + except Exception as exc: + return type(exc), str(exc) + if hasattr(rv, "toarray"): + return rv.toarray().tolist() + if isinstance(rv, (nx.Graph, ga.Graph)): + rv = Dispatcher.convert_to_nx(rv) + edges = {frozenset(e) if not rv.is_directed() else e for e in rv.edges} + return type(rv), list(rv), edges + return rv + + +def native(G, weight="weight"): + return (ga.DiGraph if G.is_directed() else ga.Graph).from_networkx(G, weight=weight) + + +def by_each_path(name, G, *args, backend_priority, conversions, **kwargs): + """NetworkX's outcome, then this backend's: on a backend graph, named, and chosen by NetworkX. + + Also whether NetworkX converted `G` for the call it chose the backend for. + """ + func = getattr(nx, name) + expected = outcome(func, G, *args, backend="networkx", **kwargs) + H = native(G) + with backend_priority(name): + on_native = outcome(func, H, *args, **kwargs) + explicit = outcome(func, G, *args, backend="graphblas", **kwargs) + G.__networkx_cache__.clear() # so that NetworkX converts afresh, or not at all + del conversions[:] + automatic = outcome(func, G, *args, **kwargs) + return expected, on_native, explicit, automatic, any(c is G for c in conversions) + + +@pytest.fixture +def paths(backend_priority, conversions): + def run(name, G, *args, **kwargs): + return by_each_path( + name, G, *args, backend_priority=backend_priority, conversions=conversions, **kwargs + ) + + return run + + +# bethe_hessian_matrix: NetworkX reads `weight` but its conversion carries no edge data. + + +def weighted_triangle_with_a_tail(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 2.0), (1, 2, 3.0), (2, 0, 1.0), (2, 3, 4.0), (3, 3, 0.5)]) + return G + + +@pytest.mark.parametrize("kwargs", [{}, {"r": 2}, {"nodelist": [3, 2, 1]}], ids=repr) +def test_bethe_hessian_matrix_reads_a_backend_graph_s_weights(kwargs, paths): + G = weighted_triangle_with_a_tail() + expected, on_native, explicit, automatic, converted = paths("bethe_hessian_matrix", G, **kwargs) + assert on_native == expected + assert automatic == expected + assert not converted # NetworkX's conversion would leave the weights behind + assert explicit[0] is NotImplementedError + # Values from another attribute are not `weight`'s: every edge weighs 1, as in NetworkX. + for _u, _v, data in G.edges(data=True): + data["cost"] = data.pop("weight") + H = native(G, weight="cost") + assert outcome(nx.bethe_hessian_matrix, H, **kwargs) == outcome( + nx.bethe_hessian_matrix, G, backend="networkx", **kwargs + ) + + +def test_bethe_hessian_matrix_reads_the_weights_once_per_version_of_the_graph(): + G = weighted_triangle_with_a_tail() + assert isinstance(Dispatcher.can_run("bethe_hessian_matrix", (G,), {}), str) + facts = G.__networkx_cache__["graphblas_facts"] + assert facts == {("edge attribute", "weight"): True} + for _u, _v, data in G.edges(data=True): + del data["weight"] # in place: the fact stands until the cache is cleared + assert isinstance(Dispatcher.can_run("bethe_hessian_matrix", (G,), {}), str) + G.__networkx_cache__.clear() + assert Dispatcher.can_run("bethe_hessian_matrix", (G,), {}) is True + + +def test_bethe_hessian_matrix_converts_an_unweighted_graph(paths): + G = nx.Graph([(0, 1), (1, 2), (2, 0), (2, 3)]) + expected, on_native, explicit, automatic, converted = paths("bethe_hessian_matrix", G) + assert on_native == explicit == automatic == expected + assert converted + + +# reciprocity of an undirected graph: NetworkX's code meets it as a directed one. + +UNDIRECTED = { + "a path": lambda: nx.path_graph(4), + "no edges": lambda: nx.empty_graph(3), + "a self-loop": lambda: nx.Graph([(0, 0), (0, 1)]), + "the null graph": nx.Graph, +} + + +@pytest.mark.parametrize("make", UNDIRECTED.values(), ids=UNDIRECTED) +@pytest.mark.parametrize( + "nodes", + [None, 0, [0, 1], [], [99], 99, [[1]], [99, 0], [0, [1]], "ab"], + ids=repr, +) +def test_reciprocity_of_an_undirected_graph(make, nodes, paths): + expected, on_native, explicit, automatic, converted = paths("reciprocity", make(), nodes) + assert on_native == explicit == automatic == expected + assert converted + + +@pytest.mark.parametrize("make", UNDIRECTED.values(), ids=UNDIRECTED) +def test_overall_reciprocity_of_an_undirected_graph(make, paths): + expected, on_native, explicit, automatic, _ = paths("overall_reciprocity", make()) + assert on_native == explicit == automatic == expected + + +class MyGraph(nx.Graph): + """A user's subclass, whose name NetworkX's error gives.""" + + +@pytest.mark.parametrize("nodes", [0, [1, 2]], ids=repr) +def test_reciprocity_s_error_names_the_caller_s_class(nodes, paths): + G = MyGraph(nx.path_graph(3)) + expected, on_native, explicit, automatic, _ = paths("reciprocity", G, nodes) + assert expected == (AttributeError, "'MyGraph' object has no attribute 'predecessors'") + assert on_native == explicit == automatic == expected + + +def test_reciprocity_refuses_an_undirected_multigraph(): + from graphblas_algorithms import nxapi + + G = nx.MultiGraph([(0, 1)]) + for name in ("reciprocity", "overall_reciprocity"): + with pytest.raises(nx.NetworkXNotImplemented, match="undirected multigraph type"): + getattr(nxapi, name)(G) + + +# hits with `method="svd"`: NetworkX's from 3.7, this backend's own keyword on NetworkX 3.6. + +NX_HITS_TAKES_METHOD = "method" in inspect.signature(nx.hits.orig_func).parameters + + +def svd_reference(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True): + """NetworkX 3.7's `_hits_svd`, for a NetworkX without it.""" + import scipy as sp + + if len(G) == 0: + return {}, {} + A = nx.adjacency_matrix(G, nodelist=list(G), dtype=float) + if nstart is not None: + nstart = np.array(list(nstart.values())) + if max_iter <= 0: + raise nx.PowerIterationFailedConvergence(max_iter) + try: + _, _, vt = sp.sparse.linalg.svds(A, k=1, v0=nstart, maxiter=max_iter, tol=tol) + except sp.sparse.linalg.ArpackNoConvergence as exc: + raise nx.PowerIterationFailedConvergence(max_iter) from exc + a = vt.flatten().real + h = A @ a + if normalized: + h /= h.sum() + a /= a.sum() + return dict(zip(G, map(float, h), strict=True)), dict(zip(G, map(float, a), strict=True)) + + +def svd_expected(G, **kwargs): + if NX_HITS_TAKES_METHOD: + return outcome(nx.hits, G, method="svd", backend="networkx", **kwargs) + return outcome(svd_reference, G, **kwargs) + + +def weighted_random(seed, directed): + G = nx.gnp_random_graph(30, 0.15, seed=seed, directed=directed) + rng = np.random.default_rng(seed) + for u, v in G.edges: + G[u][v]["weight"] = float(rng.integers(1, 5)) + return G + + +# None is an undirected bipartite graph: its largest singular value is repeated, so SciPy's +# vector, and NetworkX's own answer, changes from one call to the next. +HITS_GRAPHS = { + "karate club": nx.karate_club_graph, + "NetworkX's test digraph": lambda: nx.DiGraph( + [(1, 3), (1, 5), (2, 1), (3, 5), (5, 4), (5, 3), (6, 5)] + ), + "odd cycle": lambda: nx.cycle_graph(5), + "weighted": lambda: weighted_random(2, False), + "weighted digraph": lambda: weighted_random(3, True), +} + + +def close(left, right): + return all( + x.keys() == y.keys() and all(math.isclose(x[k], y[k], abs_tol=1e-6) for k in x) + for x, y in zip(left, right, strict=True) + ) + + +@pytest.mark.parametrize("make", HITS_GRAPHS.values(), ids=HITS_GRAPHS) +@pytest.mark.parametrize("kwargs", [{}, {"tol": 1e-10}, {"nstart": "ones"}], ids=repr) +def test_hits_svd(make, kwargs, paths): + G = make() + if kwargs.get("nstart"): + kwargs = {"nstart": dict.fromkeys(G, 1.0)} + _, on_native, explicit, automatic, converted = paths("hits", G, method="svd", **kwargs) + expected = svd_expected(G, **kwargs) + for got in (on_native, explicit, automatic): + assert close(got, expected) + assert converted + if NX_HITS_TAKES_METHOD: + assert close(svd_reference(G, **kwargs), expected) + + +@pytest.mark.parametrize("make", HITS_GRAPHS.values(), ids=HITS_GRAPHS) +def test_hits_svd_unnormalized_has_the_sign_scipy_picks(make, paths): + G = make() + _, on_native, explicit, automatic, _ = paths("hits", G, method="svd", normalized=False) + expected = svd_expected(G, normalized=False) + + def magnitudes(vectors): + return [{k: abs(v) for k, v in d.items()} for d in vectors] + + for got in (on_native, explicit, automatic): + assert close(magnitudes(got), magnitudes(expected)) + # One sign for each vector: SciPy's, which NetworkX keeps too. + for d in got: + assert all(v >= -1e-12 for v in d.values()) or all(v <= 1e-12 for v in d.values()) + + +def test_hits_svd_answers_in_node_order(): + """A backend graph whose nodes are not in the order of their rows.""" + K = nx.karate_club_graph() + H0 = native(K) + key_to_id = {key: H0._key_to_id[key] for key in reversed(list(K))} + H = ga.Graph(H0._A, key_to_id=key_to_id, weight=H0._weight) + G = Dispatcher.convert_to_nx(H) + assert list(G) == list(reversed(list(K))) + expected = svd_expected(G) + got = nx.hits(H, method="svd") + assert [list(d) for d in got] == [list(d) for d in expected] + assert close(got, expected) + + +def test_hits_svd_of_a_digraph_follows_its_edges(): + """The hubs point at the authorities: no transpose of the matrix gives the same vectors.""" + G = nx.DiGraph([(0, 1), (0, 2), (3, 1), (3, 2), (4, 2), (1, 2)]) + hubs, authorities = nx.hits(native(G), method="svd") + assert hubs == pytest.approx(svd_expected(G)[0], abs=1e-9) + assert max(authorities, key=authorities.get) == 2 + assert max(hubs, key=hubs.get) in {0, 3} + + +@pytest.mark.parametrize( + ("make", "kwargs"), + [ + (nx.karate_club_graph, {"max_iter": 0}), + (nx.karate_club_graph, {"max_iter": -1}), + (nx.karate_club_graph, {"nstart": {0: 1.0}}), + (lambda: nx.Graph([(0, 0)]), {}), + (nx.Graph, {}), + ], + ids=["max_iter 0", "max_iter -1", "nstart short", "one node", "null graph"], +) +def test_hits_svd_raises_and_answers_as_networkx(make, kwargs, paths): + G = make() + _, on_native, explicit, automatic, _ = paths("hits", G, method="svd", **kwargs) + assert on_native == explicit == automatic == svd_expected(G, **kwargs) + + +@pytest.mark.parametrize("method", ["bogus", None, 3, "SVD"], ids=repr) +def test_hits_refuses_an_unknown_method(method, paths): + expected, on_native, explicit, automatic, _ = paths("hits", nx.path_graph(3), method=method) + refused = (ValueError, f"method not supported: {method}") + assert on_native == explicit == automatic == refused + if NX_HITS_TAKES_METHOD: + assert expected == refused + + +@pytest.mark.skipif(NX_HITS_TAKES_METHOD, reason="NetworkX 3.6 has no `method`") +def test_on_networkx_3_6_method_is_this_backend_s_keyword(paths): + """NetworkX's dispatch passes a keyword it does not declare to the backend; alone it refuses.""" + from _nx_graphblas import get_info + + G = nx.karate_club_graph() + expected, on_native, explicit, automatic, converted = paths("hits", G, method="svd") + assert expected == (TypeError, "hits() got an unexpected keyword argument 'method'") + for got in (on_native, explicit, automatic): + assert close(got, svd_reference(G)) + assert converted + assert "NetworkX 3.6 has no `method`" in get_info()["functions"]["hits"]["additional_docs"] + + +# average_shortest_path_length by Floyd-Warshall, and an unknown method. + +ASPL_GRAPHS = { + "path": (lambda: nx.path_graph(6), None), + "weighted path": (lambda: nx.path_graph(6), "weight"), + "weighted": (weighted_triangle_with_a_tail, "weight"), + "weighted digraph": ( + lambda: nx.DiGraph( + [(0, 1, {"weight": 2.0}), (1, 2, {"weight": 0.5}), (2, 0, {"weight": 1})] + ), + "weight", + ), + "a negative weight": ( + lambda: nx.DiGraph( + [(0, 1, {"weight": -1.0}), (1, 2, {"weight": 2.0}), (2, 0, {"weight": 1})] + ), + "weight", + ), + "one node": (lambda: nx.Graph([(0, 0)]), None), +} + + +# NetworkX 3.7's Floyd-Warshall checks each node's distance to itself; NetworkX 3.6's does not. +NX_FLOYD_WARSHALL_FINDS_NEGATIVE_CYCLES = ( + outcome(nx.floyd_warshall_numpy, nx.DiGraph([(0, 0, {"weight": -1})]), backend="networkx")[0] + is nx.NetworkXUnbounded +) + + +@pytest.mark.parametrize("method", ["floyd-warshall", "floyd-warshall-numpy"]) +@pytest.mark.parametrize("case", ASPL_GRAPHS.values(), ids=ASPL_GRAPHS) +def test_average_shortest_path_length_by_floyd_warshall(case, method, paths): + make, weight = case + name = "average_shortest_path_length" + G = make() + expected, on_native, explicit, automatic, converted = paths( + name, G, weight=weight, method=method + ) + for got in (on_native, explicit, automatic): + assert got == pytest.approx(expected, rel=1e-12) + negative = weight is not None and any(w < 0 for *_, w in G.edges(data=weight, default=1)) + # NetworkX 3.6 answers a negative weight itself, as it would a negative cycle. + assert converted == (not negative or NX_FLOYD_WARSHALL_FINDS_NEGATIVE_CYCLES) + + +# Each with NetworkX 3.6's mean. The second's negative weight lies between -1 and 0. +NEGATIVE_CYCLES = { + "a weight of -3": ([(0, 1, -3.0), (1, 2, 1.0), (2, 0, 1)], -2.0), + "a weight above -1": ([(0, 1, -0.75), (1, 2, 0.25), (2, 0, 0.25)], -0.5), +} + + +@pytest.mark.parametrize("method", ["floyd-warshall", "floyd-warshall-numpy"]) +@pytest.mark.parametrize("cycle", NEGATIVE_CYCLES.values(), ids=NEGATIVE_CYCLES) +def test_average_shortest_path_length_on_a_negative_cycle(cycle, method, paths): + """A backend graph and a named backend raise, as NetworkX 3.7's Floyd-Warshall does. + + NetworkX 3.6's gives a number, which the call NetworkX dispatches itself gets. + """ + edges, networkx_3_6_mean = cycle + G = nx.DiGraph() + G.add_weighted_edges_from(edges) + name = "average_shortest_path_length" + expected, on_native, explicit, automatic, converted = paths( + name, G, weight="weight", method=method + ) + unbounded = (nx.NetworkXUnbounded, "Negative cycle detected.") + assert on_native == explicit == unbounded + assert automatic == expected + if NX_FLOYD_WARSHALL_FINDS_NEGATIVE_CYCLES: + assert expected == unbounded + assert converted + else: + assert expected == networkx_3_6_mean + assert not converted + + +@pytest.mark.parametrize("method", ["floyd-warshall", "floyd-warshall-numpy"]) +def test_the_installed_networkx_is_asked_whether_floyd_warshall_raises(method): + from graphblas_algorithms.nxapi.shortest_paths import generic + + found = generic._networkx_finds_negative_cycles(method) + assert found is NX_FLOYD_WARSHALL_FINDS_NEGATIVE_CYCLES + + +@pytest.fixture +def fresh_probe(): + """The Floyd-Warshall probe with nothing kept, as in a new process; emptied again after.""" + from graphblas_algorithms.nxapi.shortest_paths import generic + + probe = generic._networkx_finds_negative_cycles + probe.cache_clear() + yield probe + probe.cache_clear() + + +# The names NetworkX's two Floyd-Warshall functions call, each dispatched. +_FLOYD_WARSHALL_NAMES = ( + "floyd_warshall", + "floyd_warshall_numpy", + "floyd_warshall_predecessor_and_distance", + "to_numpy_array", +) + + +@pytest.mark.parametrize("method", ["floyd-warshall", "floyd-warshall-numpy"]) +@pytest.mark.parametrize("route", ["algos", "by name", "test mode"]) +def test_the_probe_runs_networkx_s_own_code_whatever_the_priority( + route, method, fresh_probe, conversions, monkeypatch +): + """No call inside the probe goes to this backend, and it writes nothing to NetworkX's config. + + Its answer is kept for the process, so the priority in force when it first runs must not + move a call inside it to this backend, which raises on the cycle where NetworkX 3.6 gives a + number. In NetworkX's test mode every call that names no backend is converted. The config is + one for the process, and a write to it races with any other thread's own `with` on it. + """ + config = nx.config.backend_priority + if route == "by name": + for name in _FLOYD_WARSHALL_NAMES: + monkeypatch.setattr(config, name, ["graphblas"], raising=False) + else: + monkeypatch.setattr(config, "algos", ["graphblas"]) + if route == "test mode": + monkeypatch.setattr(backends._dispatchable, "_is_testing", True) + writes = [] + cls = type(config) + setattr_, delattr_ = cls.__setattr__, cls.__delattr__ + + def spy_set(self, key, value): + writes.append(key) + setattr_(self, key, value) + + def spy_del(self, key): + writes.append(key) + delattr_(self, key) + + monkeypatch.setattr(cls, "__setattr__", spy_set) + monkeypatch.setattr(cls, "__delattr__", spy_del) + try: + found = fresh_probe(method) + except pytest.xfail.Exception as exc: # NetworkX's test mode, for a name this backend lacks + pytest.fail(f"the probe raised {exc!r}") + assert found is NX_FLOYD_WARSHALL_FINDS_NEGATIVE_CYCLES + assert conversions == [] + assert writes == [] + + +@pytest.mark.parametrize( + ("method", "name"), + [ + ("floyd-warshall", "floyd_warshall_predecessor_and_distance"), + ("floyd-warshall-numpy", "floyd_warshall_numpy"), + ], +) +@pytest.mark.parametrize("change", ["its signature", "no orig_func"]) +def test_the_probe_takes_another_error_for_no(change, method, name, fresh_probe, monkeypatch): + """No means a graph with a negative weight goes to NetworkX, which answers it either way.""" + + def changed(G, **kwargs): + raise TypeError("a later NetworkX's signature") + + if change == "its signature": + monkeypatch.setattr(getattr(nx, name), "orig_func", changed) + else: + monkeypatch.setattr(nx, name, changed) + before = dict(nx.config.backend_priority) + assert fresh_probe(method) is False + assert dict(nx.config.backend_priority) == before + + +@pytest.mark.parametrize("method", ["floyd-warshall", "floyd-warshall-numpy"]) +@pytest.mark.parametrize("made", ["raises", "lacks add_edge"]) +def test_the_probe_takes_a_graph_it_cannot_make_for_no(made, method, fresh_probe, monkeypatch): + """Under a priority for `classes`, a backend may make NetworkX's DiGraph, or fail to. + + Nothing of that reaches the caller, whose call is left to NetworkX. + """ + G = nx.DiGraph([(0, 1, {"weight": -1.0}), (1, 0, {"weight": 2.0})]) + + def digraph(*args, **kwargs): + if made == "raises": + raise RuntimeError("no graph made") + return object() # no add_edge + + monkeypatch.setattr(nx, "DiGraph", digraph) + kwargs = {"weight": "weight", "method": method} + reason = Dispatcher.should_run("average_shortest_path_length", (G,), kwargs) + assert "left to the next backend or NetworkX" in reason + assert fresh_probe(method) is False + + +def test_the_negative_weight_is_read_once_per_version_of_the_graph(monkeypatch): + from graphblas_algorithms.nxapi.shortest_paths import generic + + monkeypatch.setattr(generic, "_networkx_finds_negative_cycles", lambda method: False) + G = nx.DiGraph([(0, 1, {"weight": 1.0}), (1, 2, {"weight": 1.0}), (2, 0, {"weight": 1})]) + kwargs = {"weight": "weight", "method": "floyd-warshall"} + name = "average_shortest_path_length" + assert Dispatcher.should_run(name, (G,), kwargs) is True + assert G.__networkx_cache__["graphblas_facts"] == {("negative weight", "weight"): False} + G[0][1]["weight"] = -1.0 # in place: the fact stands until the cache is cleared + assert Dispatcher.should_run(name, (G,), kwargs) is True + G.__networkx_cache__.clear() + assert "left to the next backend or NetworkX" in Dispatcher.should_run(name, (G,), kwargs) + G.add_edge(3, 0, weight=-1.0) # through NetworkX's methods, which empty the cache + G[0][1]["weight"] = 1.0 + assert isinstance(Dispatcher.should_run(name, (G,), kwargs), str) + assert Dispatcher.should_run(name, (G,), {"weight": None, "method": "floyd-warshall"}) + assert Dispatcher.should_run(name, (G,), {"weight": "weight", "method": "dijkstra"}) is True + + +@pytest.mark.parametrize("make", [nx.path_graph, nx.empty_graph, lambda n: nx.Graph()]) +@pytest.mark.parametrize("method", ["bogus", [1]], ids=repr) +def test_average_shortest_path_length_refuses_an_unknown_method(make, method, paths): + name = "average_shortest_path_length" + expected, on_native, explicit, automatic, _ = paths(name, make(3), method=method) + assert expected == (ValueError, f"method not supported: {method}") + assert on_native == explicit == automatic == expected + + +# The eccentricity names on the null graph, whose answer differs between NetworkX's versions. + + +@pytest.mark.parametrize("cls", [nx.Graph, nx.DiGraph]) +@pytest.mark.parametrize( + ("name", "kwargs"), + [ + (name, kwargs) + for name in ("diameter", "radius", "periphery", "center") + for kwargs in ({}, {"weight": "weight"}, {"usebounds": True}, {"e": {}}, {"e": {0: 2}}) + ] + + [ + ("eccentricity", kwargs) + for kwargs in ({}, {"v": 0}, {"v": [0]}, {"sp": {}}, {"weight": "weight"}) + ], + ids=repr, +) +def test_the_null_graph_gets_the_installed_networkx_s_answer(cls, name, kwargs, paths): + expected, on_native, explicit, automatic, _ = paths(name, cls(), **kwargs) + assert on_native == explicit == automatic == expected + + +# k_core, k_shell, k_crust and k_corona with a `k` that is not a real number. + + +def cores_one_to_three(): + G = nx.complete_graph(4) # core 3 + G.add_edges_from([(3, 4), (4, 5), (5, 3)]) # core 2 + G.add_edge(5, 6) # core 1 + return G + + +CORE_GRAPHS = { + "cores 1 to 3": cores_one_to_three, + "the null graph": nx.Graph, + "a digraph": lambda: nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3)]), +} + + +@pytest.mark.parametrize("make", CORE_GRAPHS.values(), ids=CORE_GRAPHS) +@pytest.mark.parametrize( + "k", + ["a", [1], 1j, complex(2, 0), complex(1, 0), Decimal(2), Decimal("1.5"), Fraction(3, 2)], + ids=repr, +) +@pytest.mark.parametrize("name", ["k_core", "k_shell", "k_crust", "k_corona"]) +def test_a_k_that_is_not_a_real_number_is_compared_as_networkx_compares_it(name, k, make, paths): + expected, on_native, explicit, automatic, converted = paths(name, make(), k=k) + assert on_native == explicit == automatic == expected + assert converted + + +@pytest.mark.parametrize( + "make", + [*CORE_GRAPHS.values(), lambda: nx.Graph(nx.karate_club_graph().edges)], + ids=[*CORE_GRAPHS, "karate club"], +) +def test_k_corona_takes_none_as_the_largest_core_number(make, paths): + expected, on_native, explicit, automatic, converted = paths("k_corona", make(), None) + assert on_native == explicit == automatic == expected + assert converted + + +# bfs_edges and bfs_successors with `sort_neighbors`. + + +def added_out_of_node_order(): + """A graph whose nodes' neighbors were added in an order other than the nodes'.""" + G = nx.Graph() + G.add_nodes_from(range(6)) + G.add_edges_from([(0, 4), (0, 2), (0, 1), (2, 5), (1, 5), (4, 3), (5, 3)]) + return G + + +BFS_GRAPHS = { + "karate club": lambda: nx.Graph(nx.karate_club_graph().edges), + "random digraph": lambda: nx.gnp_random_graph(40, 0.1, seed=3, directed=True), + "tree": lambda: nx.balanced_tree(2, 4), + "neighbors out of node order": added_out_of_node_order, +} +SORTS = { + "sorted": sorted, + "reversed": lambda nodes: sorted(nodes, reverse=True), + "by str": lambda nodes: sorted(nodes, key=str), +} + + +@pytest.mark.parametrize("make", BFS_GRAPHS.values(), ids=BFS_GRAPHS) +@pytest.mark.parametrize("sort", SORTS.values(), ids=SORTS) +@pytest.mark.parametrize( + ("name", "kwargs"), + [ + ("bfs_edges", {}), + ("bfs_edges", {"depth_limit": 2}), + ("bfs_edges", {"depth_limit": 0}), + ("bfs_edges", {"reverse": True}), + ("bfs_successors", {}), + ("bfs_successors", {"depth_limit": 2}), + ], + ids=repr, +) +def test_a_walk_with_sort_neighbors_is_networkx_s(name, kwargs, sort, make, paths): + G = make() + expected, on_native, explicit, automatic, converted = paths( + name, G, 0, sort_neighbors=sort, **kwargs + ) + assert on_native == explicit == automatic == expected + assert not converted # NetworkX's walk of its own graph is faster + + +def test_sort_neighbors_is_asked_for_the_same_nodes_in_the_same_order(): + G = added_out_of_node_order() + asked = {"networkx": [], "graphblas": []} + + def sort(into): + def sort_neighbors(nodes): + nodes = sorted(nodes) + into.append(nodes) + return nodes + + return sort_neighbors + + for backend, into in asked.items(): + edges = nx.bfs_edges(G, 0, sort_neighbors=sort(into), backend=backend) + next(edges) # lazily, as NetworkX's walk + assert asked["graphblas"] == asked["networkx"] + assert len(asked["networkx"]) == 2 # the source, then the node of the first edge + for backend, into in asked.items(): + list(nx.bfs_edges(G, 0, sort_neighbors=sort(into), backend=backend)) + assert asked["graphblas"] == asked["networkx"] + + +@pytest.mark.parametrize("make", BFS_GRAPHS.values(), ids=BFS_GRAPHS) +def test_a_walk_reads_each_sorted_neighbor_as_networkx_does(make): + """NetworkX stops reading once every node is seen, and so does the walk here.""" + G = make() + read = {"networkx": [], "graphblas": []} + + def lazily(into): + def sort_neighbors(nodes): + for node in sorted(nodes): + into.append(node) + yield node + + return sort_neighbors + + for backend, into in read.items(): + list(nx.bfs_edges(G, 0, sort_neighbors=lazily(into), backend=backend)) + assert read["graphblas"] == read["networkx"] + + +@pytest.mark.parametrize( + ("source", "sort"), + [("nope", sorted), ([1], sorted), (0, lambda nodes: [*nodes, "x"])], + ids=["a missing source", "an unhashable source", "a stranger sorted in"], +) +def test_a_walk_with_sort_neighbors_raises_as_networkx(source, sort, paths): + for make in (added_out_of_node_order, lambda: nx.DiGraph(added_out_of_node_order())): + expected, on_native, explicit, automatic, _ = paths( + "bfs_edges", make(), source, sort_neighbors=sort + ) + assert on_native == explicit == automatic == expected + + +def test_sort_neighbors_gets_a_backend_graph_s_neighbors_in_node_order(paths): + """The order a backend graph keeps; NetworkX gives them in the order they were added.""" + keep = list # no sorting: the order the walk is handed + expected, on_native, explicit, automatic, _ = paths( + "bfs_edges", added_out_of_node_order(), 0, sort_neighbors=keep + ) + assert expected == [(0, 4), (0, 2), (0, 1), (4, 3), (2, 5)] + assert on_native == explicit == [(0, 1), (0, 2), (0, 4), (1, 5), (4, 3)] + assert automatic == expected + + +# schultz_index and gutman_index with a node named "weight", which NetworkX gives the argument +# as a degree. + + +@pytest.mark.parametrize( + "make", + [nx.path_graph, nx.cycle_graph, lambda n: nx.Graph([(0, 1), (2, 3)])], + ids=["path", "cycle", "disconnected"], +) +@pytest.mark.parametrize("weight", [None, "weight"]) +@pytest.mark.parametrize("name", ["schultz_index", "gutman_index"]) +def test_a_node_named_weight_gets_the_index_its_degree_gives(name, weight, make, paths): + G = nx.relabel_nodes(make(5), {0: "weight"}) + if weight: + for i, (u, v) in enumerate(G.edges): + G[u][v]["weight"] = 1.0 + i + renamed = nx.relabel_nodes(G, {"weight": "w"}) + truth = getattr(nx, name)(renamed, weight=weight, backend="networkx") + expected, on_native, explicit, automatic, converted = paths(name, G, weight=weight) + assert on_native == explicit == pytest.approx(truth, rel=1e-12) + assert automatic == expected + assert not converted + if math.isfinite(truth): + assert expected[0] is TypeError + reason = Dispatcher.should_run(name, (G,), {"weight": weight}) + assert 'node named "weight"' in reason + assert Dispatcher.should_run(name, (renamed,), {"weight": weight}) is True