diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 4ab61f3..6ac7794 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -195,53 +195,75 @@ def get_info(): _additional_docs = { # BEGIN: additional_docs - "all_pairs_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", - "average_degree_connectivity": "Complex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).\nWith `weight`, an iterator `nodes` is left to NetworkX.", - "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\nComplex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).", - "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".', - "bellman_ford_path": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", - "bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "adjacency_matrix": "Weights that are all `np.float32` give NetworkX's answer. Beside other numbers, or with\nNumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights.", + "all_pairs_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.", + "average_clustering": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "average_degree_connectivity": "Complex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).\nWith `weight`, an iterator `nodes` is left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\nComplex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "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".\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "bellman_ford_path": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights that are all `np.float32` give NetworkX's answer. Beside other numbers, or with\nNumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights.", + "bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.", "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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', - "closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', + "center": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights that are all `np.float32` give NetworkX\'s answer. Beside other numbers, or with\nNumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights.', + "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".\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "clustering": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", "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 as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "cut_size": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more.\nWith `weight`, an iterator `S` or `T` is left to NetworkX.", - "degree_assortativity_coefficient": '`nodes` one node, or an iterator, which NetworkX reads twice, is left to NetworkX.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weights must all be\nmultiples of one power of two whose sums stay below 2**52 of it, so that each weighted\ndegree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.\nPast 2048 distinct degrees the coefficient is taken from the counts of degree pairs,\nnot from NetworkX\'s dense matrix, so it may differ in its last bits.', - "degree_mixing_matrix": 'Without `mapping`, NetworkX numbers the degrees in the order a Python set of them\niterates, which can depend on the order it met them along each node\'s adjacency;\nwhere it can, the call is left to NetworkX (called with `backend="graphblas"`, it\nraises NotImplementedError).\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weights must all be\nmultiples of one power of two whose sums stay below 2**52 of it, so that each weighted\ndegree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', - "degree_pearson_correlation_coefficient": 'SciPy\'s `pearsonr` of the same pairs in another order, so the value may differ from\nNetworkX\'s in its last bits; past 2**24 stored edges it is taken from the counts of\ndegree pairs.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weights must all be\nmultiples of one power of two whose sums stay below 2**52 of it, so that each weighted\ndegree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.\nWith `weight`, an iterator `nodes` is left to NetworkX.', - "diameter": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', - "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "eccentricity": 'A precomputed `sp`, the null graph, and with `weight` an iterator `v`, are\nleft to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', + "compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "conductance": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "cut_size": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more.\nWith `weight`, an iterator `S` or `T` is left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "degree_assortativity_coefficient": '`nodes` one node, or an iterator, which NetworkX reads twice, is left to NetworkX.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weights must all be\nmultiples of one power of two whose sums stay below 2**52 of it, so that each weighted\ndegree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.\nPast 2048 distinct degrees the coefficient is taken from the counts of degree pairs,\nnot from NetworkX\'s dense matrix, so it may differ in its last bits.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "degree_mixing_matrix": 'Without `mapping`, NetworkX numbers the degrees in the order a Python set of them\niterates, which can depend on the order it met them along each node\'s adjacency;\nwhere it can, the call is left to NetworkX (called with `backend="graphblas"`, it\nraises NotImplementedError).\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weights must all be\nmultiples of one power of two whose sums stay below 2**52 of it, so that each weighted\ndegree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "degree_pearson_correlation_coefficient": 'SciPy\'s `pearsonr` of the same pairs in another order, so the value may differ from\nNetworkX\'s in its last bits; past 2**24 stored edges it is taken from the counts of\ndegree pairs.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weights must all be\nmultiples of one power of two whose sums stay below 2**52 of it, so that each weighted\ndegree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.\nWith `weight`, an iterator `nodes` is left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "diameter": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.', + "directed_modularity_matrix": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "eccentricity": 'A precomputed `sp`, the null graph, and with `weight` an iterator `v`, are\nleft to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.', "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\ninteger weights are left to NetworkX where the number of nodes times the heaviest\nabsolute weight reaches 2**62, as a length could then pass 2**63.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.', - "floyd_warshall": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", - "floyd_warshall_predecessor_and_distance": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "edge_boundary": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "edge_expansion": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and\ninteger weights are left to NetworkX where the number of nodes times the heaviest\nabsolute weight reaches 2**62, as a length could then pass 2**63.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "eigenvector_centrality": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "floyd_warshall": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.", + "floyd_warshall_numpy": "Weights that are all `np.float32` give NetworkX's answer. Beside other numbers, or with\nNumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights.", + "floyd_warshall_predecessor_and_distance": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.", + "full_join": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "google_matrix": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", "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.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.', - "harmonic_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', - "harmonic_diameter": 'A precomputed `sp` is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', - "hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.', - "hyper_wiener_index": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node's targets could reach 2**63.", - "k_core": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "k_corona": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", + "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "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".\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "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".\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare 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 left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "hyper_wiener_index": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node's targets could reach 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "k_core": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "k_corona": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "katz_centrality": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "laplacian_matrix": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare 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": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", - "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', - "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', - "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.', - "single_source_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", - "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", - "volume": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more, or to 2**63 over the most times `S` names one node.\nWith `weight`, an iterator `S` is left to NetworkX.", - "wiener_index": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.', + "mixing_expansion": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "modularity": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "modularity_matrix": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "mutual_weight": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "negative_edge_cycle": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights that are all `np.float32` give NetworkX's answer. Beside other numbers, or with\nNumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights.", + "normalized_cut_size": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "normalized_laplacian_matrix": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "overlapping_modularity": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "pagerank": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights that are all `np.float32` give NetworkX\'s answer. Beside other numbers, or with\nNumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights.', + "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.', + "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', + "single_source_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\nare then sums in that type, which its callers go on adding in it; a result here holds\nPython floats.", + "tournament_matrix": "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "volume": "Integer weights are left to NetworkX where their absolute values sum to 2**63 or more, or to 2**63 over the most times `S` names one node.\nWith `weight`, an iterator `S` is left to NetworkX.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.", + "wiener_index": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, or where the sum over one node\'s targets could reach 2**63.\nWeights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\nare left to NetworkX.', # END: additional_docs } # fmt: on diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index da07d7b..decf15a 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -245,6 +245,100 @@ _ADDITIONAL_DOCS[_name] = _ONE_WEIGHT_TYPE if _doc is None else f"{_doc}\n{_ONE_WEIGHT_TYPE}" +# Weights of a narrow NumPy type, which NetworkX adds in that type (NumPy 2's rule, NEP 50), +# where a matrix holds every value in one dtype. `graphblas_algorithms.interface` has the rule. +_NARROW_LEFT = ( + "Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\n" + "are left to NetworkX." +) +_NARROW_LENGTHS_LEFT = ( + "Weights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\n" + "are then sums in that type, which its callers go on adding in it; a result here holds\n" + "Python floats." +) +_FLOAT32_SERVED = ( + "Weights that are all `np.float32` give NetworkX's answer. Beside other numbers, or with\n" + "NumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights." +) +# `interface._FLOAT32_EXACT`; a test keeps the two the same. +FLOAT32_SERVED = ( + "adjacency_matrix", + "bellman_ford_path", + "center", + "floyd_warshall_numpy", + "negative_edge_cycle", + "periphery", +) +NARROW_LENGTHS_LEFT = ( + "all_pairs_bellman_ford_path_length", + "bellman_ford_path_length", + "diameter", + "eccentricity", + "floyd_warshall", + "floyd_warshall_predecessor_and_distance", + "radius", + "single_source_bellman_ford_path_length", +) +# The other names that read weights or carry edge data; a test checks that none is missing. +# The unweighted names, which leave any weight to NetworkX, are not here. +NARROW_LEFT = ( + "average_clustering", + "average_degree_connectivity", + "average_neighbor_degree", + "average_shortest_path_length", + "closeness_centrality", + "clustering", + "compose", + "conductance", + "cut_size", + "degree_assortativity_coefficient", + "degree_mixing_matrix", + "degree_pearson_correlation_coefficient", + "directed_modularity_matrix", + "disjoint_union", + "edge_boundary", + "edge_expansion", + "ego_graph", + "eigenvector_centrality", + "full_join", + "google_matrix", + "gutman_index", + "harmonic_centrality", + "harmonic_diameter", + "hits", + "hyper_wiener_index", + "k_core", + "k_corona", + "k_crust", + "k_shell", + "k_truss", + "katz_centrality", + "laplacian_matrix", + "mixing_expansion", + "modularity", + "modularity_matrix", + "mutual_weight", + "normalized_cut_size", + "normalized_laplacian_matrix", + "overlapping_modularity", + "pagerank", + "reverse", + "schultz_index", + "tournament_matrix", + "union", + "volume", + "wiener_index", +) +for _names, _note in ( + (FLOAT32_SERVED, _FLOAT32_SERVED), + (NARROW_LENGTHS_LEFT, _NARROW_LENGTHS_LEFT), + (NARROW_LEFT, _NARROW_LEFT), +): + for _name in _names: + _doc = _ADDITIONAL_DOCS.get(_name) + _ADDITIONAL_DOCS[_name] = _note if _doc is None else f"{_doc}\n{_note}" + + def get_functions(): from graphblas_algorithms.interface import Dispatcher diff --git a/graphblas_algorithms/classes/_utils.py b/graphblas_algorithms/classes/_utils.py index fa821b1..f25439a 100644 --- a/graphblas_algorithms/classes/_utils.py +++ b/graphblas_algorithms/classes/_utils.py @@ -79,7 +79,9 @@ def from_networkx(cls, G, weight=None, dtype=None): raise NotImplementedError(reason) rv = cls() rv._key_to_id = {k: i for i, k in enumerate(G)} - if rv._key_to_id: + if rv._key_to_id and weight is not None and not G.is_multigraph(): + rv._A, rv._weight_types = _weighted_matrix(G, rv._key_to_id, weight, dtype) + elif rv._key_to_id: rv._A = gb.io.from_networkx(G, nodelist=rv._key_to_id, weight=weight, dtype=dtype) else: rv._A = Matrix(dtype if dtype is not None else float) @@ -87,6 +89,42 @@ def from_networkx(cls, G, weight=None, dtype=None): return rv +def _weighted_matrix(G, index, weight, dtype): + """The matrix `gb.io.from_networkx` builds, and the types of the weights it read. + + The same steps as NetworkX's `to_scipy_sparse_array` (one body from 3.6 through 3.7), so + that the one walk of the edges that reads each weight (a missing one as the int 1) also + gives their types, which `interface._narrow_weights` asks for. + """ + import networkx as nx + import scipy as sp + + if dtype is not None: + dtype = dtypes.lookup_dtype(dtype).np_type + n = len(index) + coefficients = zip( + *((index[u], index[v], wt) for u, v, wt in G.edges(data=weight, default=1)), strict=True + ) + try: + row, col, data = coefficients + except ValueError: + row, col, data = [], [], [] + types = frozenset(map(type, data)) + if G.is_directed(): + A = sp.sparse.coo_array((data, (row, col)), shape=(n, n), dtype=dtype) + else: + # Each edge both ways; a self-loop's second entry is taken back off the diagonal. + d, r, c = data + data, row + col, col + row + selfloops = list(nx.selfloop_edges(G, data=weight, default=1)) + if selfloops: + diag_index, diag_data = zip(*((index[u], -wt) for u, v, wt in selfloops), strict=True) + d += diag_data + r += diag_index + c += diag_index + A = sp.sparse.coo_array((d, (r, c)), shape=(n, n), dtype=dtype) + return gb.io.from_scipy_sparse(A.asformat("csr")), types + + ############## # Properties # ############## diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 41dfe17..cf8dd4b 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -195,6 +195,90 @@ def _ints_held_as_floats(graph, attr, G): return None +# The names whose answer for weights that are all `np.float32` is NetworkX's exactly. NumPy +# (NEP 50) adds a float32 and a Python number in float32, so NetworkX's lengths are float32 sums +# from the first weight on. These names add each path's weights edge by edge in float32, as +# NetworkX does, and only compare the sums: Bellman-Ford's path and its negative-cycle test, and +# center and periphery. floyd_warshall_numpy widens to float64 first, as NetworkX's array does, +# and adjacency_matrix adds nothing. A name that returns the lengths is left to NetworkX: its +# lengths are `np.float32`, which a caller (NetworkX's own average_shortest_path_length among +# them) adds in float32, where a result here holds Python floats, as NetworkX's test mode asks +# of a backend. The other names sum or compare in another order or type, and a rebuild would +# carry the weights as Python floats, which NetworkX's own code then adds in float64 (cut_size +# adds the weights edge_boundary gives). +_FLOAT32_EXACT = frozenset( + { + "adjacency_matrix", + "bellman_ford_path", + "center", + "floyd_warshall_numpy", + "negative_edge_cycle", + "periphery", + } +) + + +@functools.cache +def _float32_sums_stay_float32(): + """True where NumPy adds a float32 and a Python number in float32 (NEP 50, NumPy 2). + + NetworkX's sums start from the int 0. Under the older rule they are float64 from the first + weight on, and no float32 matrix adds as they do. + """ + import numpy as np + + return type(np.float32(1) + 0) is np.float32 and type(np.float32(1) + 0.5) is np.float32 + + +def _adds_narrow_as_networkx(name, narrow): + """True if `name` answers as NetworkX does for weights that are all of the type `narrow`.""" + import numpy as np + + return narrow is np.float32 and name in _FLOAT32_EXACT and _float32_sums_stay_float32() + + +def _narrow_weights(graph, attr, G): + """The narrow type of `graph`'s `attr` values, if all are one, or why they cannot be held. + + NumPy (NEP 50) adds an `np.float16`, `np.float32` or `np.complex64` and a Python number, or + the same type, in that narrow type, and a wider NumPy type in the wider one. So NetworkX's + sums change type along a path wherever the weights do, while a matrix holds every value in + the one dtype numpy infers for them all and adds in that. Such a mix is refused, for every + name. A missing attribute counts as NetworkX reads it, the int 1. Weights that are all one + narrow type give that type, and their matrix holds them in it; they are served only by the + names in `_FLOAT32_EXACT`. + + The types come from the conversion's own walk of the edges (`from_networkx`), so no second + walk is made; a graph built another way has its edges read here. + """ + import numpy as np + + A = G._A + dtype = A.dtype.np_type + types = G.__dict__.pop("_weight_types", None) + if A.nvals == 0 or dtype.kind not in "fc": + return None + if types is None: + types = { + type(datadict.get(attr, 1)) + for nbrs in graph._adj.values() + for datadict in nbrs.values() + } + narrow = sorted( + (t for t in types if issubclass(t, np.float16 | np.float32 | np.complex64)), + key=lambda t: t.__name__, + ) + if not narrow: + return None + if len(types) == 1: + return narrow[0] + names = " and ".join(f"np.{t.__name__}" for t in narrow) + return ( + f"mixes {names} with other numbers, which NetworkX adds in the narrow type from the " + f"first such weight on, where its matrix holds them all as {dtype}" + ) + + def _unrebuildable(graph, weight, preserve_edge_attrs, *, keeps_node_data=True): """Why a graph rebuilt from `graph` would not carry what NetworkX's own result does. @@ -580,6 +664,13 @@ def convert_from_nx( # with the arguments as given. A refused conversion is not cached for another name. if weight is not None and (problem := _ints_held_as_floats(graph, weight, G)): raise NotImplementedError(f"Edge attribute {weight!r} {problem}") + if weight is not None and (narrow := _narrow_weights(graph, weight, G)) is not None: + if isinstance(narrow, str): + raise NotImplementedError(f"Edge attribute {weight!r} {narrow}") + # Kept and marked, so that NetworkX caches a conversion the names that add these + # weights as it does (`_FLOAT32_EXACT`) can use. The others decline at their call + # (`_narrow_guard`), on this conversion or a cached one. + G._narrow_weights = narrow # A rebuilt graph keeps the graph attributes too, which NetworkX before 3.7 does not # ask for on `reverse` when its conversion cache is off. if preserve_graph_attrs or declared.rebuilds_input: @@ -678,3 +769,39 @@ def key(testpath): for (test_name, keywords), reason in xfail.items(): if base_name == test_name and keywords.issubset(kset): item.add_marker(pytest.mark.xfail(reason=reason)) + + +def _narrow_guard(name, func): + """`func`, declining weights all of one narrow type unless `name` adds them as NetworkX. + + The conversion keeps such a graph, so that NetworkX's cache holds a good one for the next + name; a refusal there would leave NetworkX's failed mark for every name instead. This + declines each call given one: the call that made it, a later one NetworkX serves from its + cache, or a call on a graph of this backend's that came from one. + """ + + @functools.wraps(func) + def call(*args, **kwargs): + for arg in (*args, *kwargs.values()): + narrow = getattr(arg, "_narrow_weights", None) + if narrow is not None and not _adds_narrow_as_networkx(name, narrow): + raise NotImplementedError( + f"{name} on weights that are all np.{narrow.__name__}, which NetworkX adds " + "in that type, is not answered as NetworkX answers it; networkx serves it" + ) + return func(*args, **kwargs) + + return call + + +def _guard_narrow_names(): + # Every name that reads weights or carries edge data (a test keeps the lists whole). + from _nx_graphblas import core + + for name in (*core.FLOAT32_SERVED, *core.NARROW_LENGTHS_LEFT, *core.NARROW_LEFT): + func = getattr(Dispatcher, name, None) + if func is not None: + setattr(Dispatcher, name, _narrow_guard(name, func)) + + +_guard_narrow_names() diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index cea3af8..f2e9ab5 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -50,7 +50,7 @@ def test_multigraph_conversion_is_refused_rather_than_collapsed(): np.int32(3), np.uint8(3), np.float64(2.5), - np.float32(2.5), + # np.float32, which NetworkX adds in float32, is left to it (test_narrow_weights.py). np.bool_(True), np.complex128(1 + 2j), 0, diff --git a/graphblas_algorithms/tests/test_narrow_weights.py b/graphblas_algorithms/tests/test_narrow_weights.py new file mode 100644 index 0000000..cea96a2 --- /dev/null +++ b/graphblas_algorithms/tests/test_narrow_weights.py @@ -0,0 +1,455 @@ +"""Weights of np.float32, np.float16 or np.complex64, which NetworkX adds in their own type. + +NumPy (NEP 50, NumPy 2) adds such a value and a Python number, or one of its own type, in that +narrow type, so NetworkX's sums change type along a path wherever its weights do. A GraphBLAS +matrix holds every value in the one dtype numpy infers for them all. A narrow type beside other +numbers is left to NetworkX, for every name. Weights that are all np.float32 are served where +the answer is NetworkX's exactly, and left to NetworkX elsewhere. Each case is checked three +ways: NetworkX itself, graphblas called by name, and NetworkX with graphblas first in its +priority (`backend_priority`, with `fallback_to_nx` off). +""" + +from collections.abc import Iterator + +import networkx as nx +import numpy as np +import pytest +from networkx.utils.backends import _registered_algorithms + +from graphblas_algorithms import interface +from graphblas_algorithms.interface import Dispatcher + +f32 = np.float32 + +# How each name is called; G first, then `backend=` when given. +CALLS = { + "bellman_ford_path": lambda f, G, **kw: f(G, 0, 7, weight="weight", **kw), + "negative_edge_cycle": lambda f, G, **kw: f(G, weight="weight", **kw), + "center": lambda f, G, **kw: f(G, weight="weight", **kw), + "periphery": lambda f, G, **kw: f(G, weight="weight", **kw), + "floyd_warshall_numpy": lambda f, G, **kw: f(G, weight="weight", **kw), + "adjacency_matrix": lambda f, G, **kw: f(G, weight="weight", **kw), + # Left to NetworkX for weights all np.float32. The lengths first: NetworkX's are np.float32. + "single_source_bellman_ford_path_length": lambda f, G, **kw: f(G, 0, weight="weight", **kw), + "bellman_ford_path_length": lambda f, G, **kw: f(G, 0, 7, weight="weight", **kw), + "all_pairs_bellman_ford_path_length": lambda f, G, **kw: f(G, weight="weight", **kw), + "eccentricity": lambda f, G, **kw: f(G, weight="weight", **kw), + "diameter": lambda f, G, **kw: f(G, weight="weight", **kw), + "radius": lambda f, G, **kw: f(G, weight="weight", **kw), + "floyd_warshall": lambda f, G, **kw: f(G, weight="weight", **kw), + "floyd_warshall_predecessor_and_distance": lambda f, G, **kw: f(G, weight="weight", **kw), + "closeness_centrality": lambda f, G, **kw: f(G, distance="weight", **kw), + "harmonic_centrality": lambda f, G, **kw: f(G, distance="weight", **kw), + "wiener_index": lambda f, G, **kw: f(G, weight="weight", **kw), + "average_shortest_path_length": lambda f, G, **kw: f(G, weight="weight", **kw), + "cut_size": lambda f, G, **kw: f(G, set(range(10)), weight="weight", **kw), + "volume": lambda f, G, **kw: f(G, set(range(10)), weight="weight", **kw), + "mutual_weight": lambda f, G, **kw: f(G, 0, 1, weight="weight", **kw), + "laplacian_matrix": lambda f, G, **kw: f(G, weight="weight", **kw), + "pagerank": lambda f, G, **kw: f(G, weight="weight", **kw), + "clustering": lambda f, G, **kw: f(G, weight="weight", **kw), + "ego_graph": lambda f, G, **kw: f(G, 0, radius=1.3, distance="weight", **kw), +} +EXACT = sorted(interface._FLOAT32_EXACT) +LEFT = sorted(CALLS.keys() - interface._FLOAT32_EXACT) + + +def plain(value): + """A result as dicts, lists and Python numbers, to compare exactly. + + A narrow NumPy scalar keeps its type beside its value as a Python number: NumPy compares + np.float32 with a Python float in float32, and a caller adds it in float32. + """ + value = Dispatcher.convert_to_nx(value) + if isinstance(value, Iterator): + value = list(value) + if isinstance(value, nx.Graph): + edges = [ + ((u, v) if value.is_directed() else tuple(sorted((u, v))), plain(d)) + for u, v, d in value.edges(data=True) + ] + return sorted(value.nodes), sorted(edges, key=repr) + if hasattr(value, "toarray"): + value = value.toarray() + if isinstance(value, np.ndarray): + return str(value.dtype), value.tolist() + if isinstance(value, dict): + return {key: plain(val) for key, val in value.items()} + if isinstance(value, list | tuple): + return [plain(item) for item in value] + if isinstance(value, np.float16 | np.float32 | np.complex64): + return f"np.{type(value).__name__}", value.item() + if isinstance(value, np.generic): + return value.item() + return value + + +def outcome(name, G, mode, backend_priority=None): + """("value", result) or ("raised", exception type), on a copy of `G`. + + ("declined", None) where graphblas, called by name, raises NotImplementedError. + """ + G = G.copy() + func = _registered_algorithms[name] + try: + if mode == "automatic": + with backend_priority("generators" if name == "ego_graph" else "algos"): + return "value", plain(CALLS[name](func, G)) + return "value", plain(CALLS[name](func, G, backend=mode)) + except NotImplementedError: + if mode == "graphblas": + return "declined", None + raise + except Exception as exc: + return "raised", type(exc).__name__ + + +def weighted(value, *, directed=False, seed=0, n=30): + """A connected random graph; `value(k, rng)` weighs its k-th edge, or None for no weight.""" + rng = np.random.default_rng(seed) + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(n)) + pairs = [(i, (i + 1) % n) for i in range(n)] + pairs += [(int(u), int(v)) for u, v in rng.integers(0, n, (3 * n, 2)) if u != v] + if directed: + pairs += [(v, u) for u, v in pairs[::4]] # some both ways, as mutual_weight reads + for k, (u, v) in enumerate(dict.fromkeys(pairs)): + w = value(k, rng) + G.add_edge(u, v) if w is None else G.add_edge(u, v, weight=w) + return G + + +def tenth(rng): + return float(rng.choice([0.1, 0.2, 0.3, 0.7, 1.1, 2.6])) + + +def all_f32(k, rng): + return f32(tenth(rng)) + + +MIXES = { + "np.float32 beside floats": lambda k, rng: f32(tenth(rng)) if k % 2 else tenth(rng), + "one np.float32 among floats": lambda k, rng: f32(tenth(rng)) if k == 3 else tenth(rng), + "np.float32 beside np.float64": lambda k, rng: ( + f32(tenth(rng)) if k % 2 else np.float64(tenth(rng)) + ), + "np.float32 beside ints": lambda k, rng: f32(tenth(rng)) if k % 2 else int(rng.integers(1, 4)), + "np.float32 beside bools": lambda k, rng: f32(tenth(rng)) if k % 3 else True, + "np.float32 beside no weight": lambda k, rng: f32(tenth(rng)) if k % 2 else None, + "np.float16 beside floats": lambda k, rng: np.float16(tenth(rng)) if k % 2 else tenth(rng), + "np.float16 beside np.float32": lambda k, rng: ( + np.float16(tenth(rng)) if k % 2 else f32(tenth(rng)) + ), + "np.float16 only": lambda k, rng: np.float16(tenth(rng)), +} + + +def known(name): + if name not in _registered_algorithms: + pytest.skip(f"{name} is not dispatched by this NetworkX") + + +@pytest.mark.skipif(not interface._float32_sums_stay_float32(), reason="needs NEP 50 (NumPy 2)") +def test_networkx_adds_float32_weights_in_float32(): + """The premise: NetworkX's lengths differ for the same values as Python floats.""" + G = nx.Graph([(0, 1, {"weight": f32(0.1)}), (1, 2, {"weight": f32(0.2)})]) + H = nx.Graph([(0, 1, {"weight": float(f32(0.1))}), (1, 2, {"weight": float(f32(0.2))})]) + lengths = nx.single_source_bellman_ford_path_length(G, 0) + assert type(lengths[2]) is f32 + # Compared as Python floats: NumPy compares np.float32 with a Python float in float32. + assert float(lengths[2]) == float(f32(0.1) + f32(0.2)) != float(f32(0.1)) + float(f32(0.2)) + assert float(lengths[2]) != nx.single_source_bellman_ford_path_length(H, 0)[2] + + +@pytest.mark.skipif(not interface._float32_sums_stay_float32(), reason="needs NEP 50 (NumPy 2)") +@pytest.mark.parametrize("seed", range(3)) +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", EXACT) +def test_float32_weights_are_added_as_networkx_adds_them(name, directed, seed, backend_priority): + known(name) + G = weighted(all_f32, directed=directed, seed=seed) + expected = outcome(name, G, "networkx") + assert outcome(name, G, "graphblas") == expected # served, with NetworkX's answer + assert outcome(name, G, "automatic", backend_priority) == expected + + +@pytest.mark.parametrize("directed", [False, True]) +@pytest.mark.parametrize("name", LEFT) +def test_float32_weights_are_left_to_networkx_where_it_adds_otherwise( + name, directed, backend_priority +): + known(name) + G = weighted(all_f32, directed=directed) + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +@pytest.mark.parametrize("mix", sorted(MIXES)) +@pytest.mark.parametrize("name", sorted(CALLS)) +def test_a_narrow_type_beside_other_numbers_is_left_to_networkx(name, mix, backend_priority): + known(name) + G = weighted(MIXES[mix], directed=name == "mutual_weight") + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +@pytest.mark.parametrize("name", LEFT) +def test_a_cached_float32_conversion_is_not_read_where_it_adds_otherwise(name, backend_priority): + """A conversion made for a name served on these weights is cached for the next name.""" + known(name) + G = weighted(all_f32, directed=name == "mutual_weight") + nx.bellman_ford_path(G, 0, 7, backend="graphblas") + nx.floyd_warshall_numpy(G, backend="graphblas") # its conversion, too, may serve the next + assert G.__networkx_cache__["backends"]["graphblas"] + assert outcome(name, G, "graphblas") == ("declined", None) + expected = outcome(name, G, "networkx") + with backend_priority("generators" if name == "ego_graph" else "algos"): + got = "value", plain(CALLS[name](_registered_algorithms[name], G)) + assert got == expected + + +@pytest.mark.skipif(not interface._float32_sums_stay_float32(), reason="needs NEP 50 (NumPy 2)") +@pytest.mark.parametrize( + "method", ["dijkstra", "bellman-ford", "floyd-warshall", "floyd-warshall-numpy"] +) +def test_networkx_s_own_sums_of_float32_lengths_stay_its_own(method, backend_priority): + """average_shortest_path_length, left to NetworkX, adds what the lengths' names give it. + + Lengths served as Python floats would make that sum float64 under the priority. + """ + G = weighted(all_f32) + expected = nx.average_shortest_path_length(G.copy(), weight="weight", method=method) + assert type(expected) is (float if method == "floyd-warshall-numpy" else f32) + for name in ["single_source_bellman_ford_path_length", "floyd_warshall"]: + assert outcome(name, G, "graphblas") == ("declined", None) + with backend_priority("algos"): + got = nx.average_shortest_path_length(G.copy(), weight="weight", method=method) + assert type(got) is type(expected) + assert got == expected + + +@pytest.mark.parametrize("radius", [0.2, 0.3, 0.30000001192092896]) +def test_ego_graph_compares_float32_lengths_with_its_radius_in_networkx( + radius, graphblas_generators +): + """NetworkX compares np.float32(0.1) * 3, summed, with 0.3 in float32, where they are equal.""" + G = nx.path_graph(6) + nx.set_edge_attributes(G, f32(0.1), "weight") + expected = sorted(nx.ego_graph(G, 0, radius=radius, distance="weight", backend="networkx")) + assert sorted(nx.ego_graph(G, 0, radius=radius, distance="weight")) == expected + with pytest.raises(NotImplementedError): + nx.ego_graph(G, 0, radius=radius, distance="weight", backend="graphblas") + + +@pytest.mark.parametrize("name", ["reverse", "edge_boundary", "ego_graph"]) +def test_a_rebuild_of_float32_weights_is_left_to_networkx(name, backend_priority): + """It would carry them as Python floats, which NetworkX's own code then adds in float64.""" + calls = { + "reverse": nx.reverse, + "edge_boundary": lambda G, **kw: list(nx.edge_boundary(G, range(10), data="weight", **kw)), + "ego_graph": lambda G, **kw: nx.ego_graph(G, 0, radius=2, **kw), + } + G = weighted(all_f32, directed=True) + expected = calls[name](G.copy(), backend="networkx") + with pytest.raises(NotImplementedError): + calls[name](G.copy(), backend="graphblas") + with backend_priority("generators" if name != "edge_boundary" else "algos"): + got = calls[name](G.copy()) + assert plain(got) == plain(expected) + if name == "edge_boundary": + weights = [w for *_, w in got] + else: + weights = [d["weight"] for *_, d in got.edges(data=True)] + assert weights + assert all(type(w) is f32 for w in weights) + + +def test_without_nep_50_float32_weights_are_left_to_networkx(monkeypatch, backend_priority): + """With NumPy's older rule NetworkX's sums are float64 from the first weight on.""" + G = weighted(all_f32) + assert outcome("bellman_ford_path", G, "graphblas")[0] == "value" + monkeypatch.setattr(interface, "_float32_sums_stay_float32", lambda: False) + for name in EXACT: + assert outcome(name, G, "graphblas") == ("declined", None) + assert outcome(name, G, "automatic", backend_priority) == outcome(name, G, "networkx") + + +@pytest.mark.parametrize("mix", sorted(MIXES)) +def test_the_conversion_refuses_a_mix_for_every_name(mix): + G = weighted(MIXES[mix]) + for kwargs in [ + {"edge_attrs": {"weight": 1}, "name": "pagerank"}, + {"preserve_edge_attrs": True, "name": "reverse"}, + ]: + if mix == "np.float32 beside no weight" and "preserve_edge_attrs" in kwargs: + continue # refused for the edges without data, as before + with pytest.raises(NotImplementedError, match=r"np\.float16|np\.float32|float16"): + Dispatcher.convert_from_nx(G, **kwargs) + + +@pytest.mark.parametrize( + ("kwargs", "call"), + [ + ({"edge_attrs": {"weight": 1}, "name": "center"}, None), + ( + {"edge_attrs": {"weight": 1}, "name": "closeness_centrality"}, + lambda H: Dispatcher.closeness_centrality(H, distance="weight"), + ), + ({"preserve_edge_attrs": True, "name": "reverse"}, Dispatcher.reverse), + ], +) +def test_the_conversion_keeps_float32_and_marks_it(kwargs, call): + """Kept, so NetworkX's cache holds a good conversion; a name that adds otherwise declines.""" + G = weighted(all_f32, directed=True) + H = Dispatcher.convert_from_nx(G, **kwargs) + assert H._A.dtype == "FP32" + assert H._narrow_weights is f32 + if call is not None: + with pytest.raises(NotImplementedError, match=r"all np\.float32"): + call(H) + + +@pytest.mark.skipif(not interface._float32_sums_stay_float32(), reason="needs NEP 50 (NumPy 2)") +@pytest.mark.parametrize( + "first", ["single_source_bellman_ford_path_length", "closeness_centrality"] +) +def test_a_name_left_to_networkx_leaves_the_cache_to_the_names_served(first): + """NetworkX marks a conversion that raises as failed, for every later name on the graph.""" + G = weighted(all_f32) + with pytest.raises(NotImplementedError): + CALLS[first](_registered_algorithms[first], G, backend="graphblas") + expected = nx.center(G.copy(), weight="weight", backend="networkx") + assert nx.center(G, weight="weight", backend="graphblas") == expected + + +def test_complex64_weights_are_left_to_networkx(): + G = weighted(lambda k, rng: np.complex64(tenth(rng) + 1j)) + H = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="adjacency_matrix") + assert H._narrow_weights is np.complex64 + with pytest.raises(NotImplementedError, match="complex64"): + Dispatcher.adjacency_matrix(H, weight="weight") + with pytest.raises(NotImplementedError): + nx.adjacency_matrix(G, weight="weight", backend="graphblas") + G = weighted(lambda k, rng: np.complex64(1j) if k % 2 else complex(tenth(rng), 1)) + with pytest.raises(NotImplementedError, match=r"np\.complex64"): + Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="adjacency_matrix") + + +@pytest.mark.parametrize( + "value", + [ + lambda k, rng: rng.uniform(0.1, 3), + lambda k, rng: float(k % 5 + 1), + lambda k, rng: 0.1 * (k % 7), + ], +) +def test_other_floats_are_not_narrow(value): + """Floats none of which round-trip through float32 are not read; whole ones are, and pass.""" + G = weighted(value) + H = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="closeness_centrality") + assert interface._narrow_weights(G, "weight", H) is None + assert getattr(H, "_narrow_weights", None) is None + + +def test_a_graph_of_this_backends_is_read_as_its_matrix_holds_it(): + """A graph built here from float32 values is this backend's own, read as it is held. + + One converted for a NetworkX call keeps that call's rule. + """ + import graphblas_algorithms as ga + + G = weighted(all_f32) + built = ga.Graph.from_networkx(G, weight="weight") + nx.closeness_centrality(built, distance="weight", backend="graphblas") + converted = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="center") + with pytest.raises(NotImplementedError): + nx.closeness_centrality(converted, distance="weight", backend="graphblas") + + +def test_every_name_that_reads_weights_has_a_note_on_narrow_ones(): + from _nx_graphblas import core + + from ._dispatched import dispatcher_functions + + assert set(core.FLOAT32_SERVED) == interface._FLOAT32_EXACT + noted = core.FLOAT32_SERVED + core.NARROW_LENGTHS_LEFT + core.NARROW_LEFT + assert len(set(noted)) == len(noted) + assert core.get_functions().keys() >= interface._FLOAT32_EXACT + # These leave any weight to NetworkX (their notes say so). + unweighted = { + "betweenness_centrality", + "betweenness_centrality_subset", + "edge_betweenness_centrality", + "edge_betweenness_centrality_subset", + "group_closeness_centrality", + } + for name in dispatcher_functions().keys() - unweighted: + declared = interface._declared(name) + if declared.attribute_parameters or declared.preserves_edge_attrs: + assert name in noted, name + + +class _CountedReads(dict): + """Edge data that counts the looks for a key: NetworkX's edge views ask `in`, then index.""" + + reads = 0 + + def get(self, key, default=None): + type(self).reads += 1 + return super().get(key, default) + + def __contains__(self, key): + type(self).reads += 1 + return super().__contains__(key) + + +@pytest.mark.parametrize("directed", [False, True]) +def test_the_weights_types_come_from_the_conversion_s_own_walk(directed): + """Plain float weights cost no second walk of the edges, even where they fit a float32.""" + + class Counted(nx.DiGraph if directed else nx.Graph): + edge_attr_dict_factory = _CountedReads + + G = Counted() + G.add_weighted_edges_from((i, (i * 7 + 1) % 50, 0.5 + i % 3) for i in range(50)) + _CountedReads.reads = 0 + H = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="pagerank") + # One walk, plus a look or so elsewhere; a second walk would read every edge again. + assert G.number_of_edges() <= _CountedReads.reads < 2 * G.number_of_edges() + assert not hasattr(H, "_weight_types") + assert getattr(H, "_narrow_weights", None) is None + + +@pytest.mark.parametrize( + "values", + [ + [1.0, 0.5], + [1, 2], + [True, False], + [1, 2.5], + [np.int64(3), 2], + [np.float32(0.5), np.float32(1.5)], + [np.float32(0.5), 1.5], + [1 + 2j, 3.0], + [np.complex64(1 + 2j), np.complex64(1)], + [None, 2.5], + [-1.5, 2**53], + ], +) +@pytest.mark.parametrize("directed", [False, True]) +def test_the_conversion_s_matrix_is_networkx_s_scipy_array(values, directed): + """`from_networkx` builds what `gb.io.from_networkx` builds, self-loops included.""" + import graphblas as gb + + from graphblas_algorithms.classes._utils import _weighted_matrix + + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(range(6)) + for k, (u, v) in enumerate([(0, 1), (1, 2), (2, 2), (3, 1), (4, 4), (5, 0)]): + value = values[k % len(values)] + G.add_edge(u, v) if value is None else G.add_edge(u, v, weight=value) + index = {node: i for i, node in enumerate(G)} + expected = gb.io.from_networkx(G, nodelist=index, weight="weight") + got, types = _weighted_matrix(G, index, "weight", None) + assert got.isequal(expected, check_dtype=True) + assert types == {int if v is None else type(v) for v in values} diff --git a/graphblas_algorithms/tests/test_roundtrip.py b/graphblas_algorithms/tests/test_roundtrip.py index 58982c3..5d5688b 100644 --- a/graphblas_algorithms/tests/test_roundtrip.py +++ b/graphblas_algorithms/tests/test_roundtrip.py @@ -337,7 +337,8 @@ def test_mixed_int_and_float_weights_come_back_as_floats(name): ([True, 2], [1, 2]), ([True, 2.5], [1.0, 2.5]), ([np.int32(1), 2], [1, 2]), - ([np.float32(1.5), np.float32(2.5)], [1.5, 2.5]), + # np.float32, which NetworkX adds in float32, is left to it (test_narrow_weights.py). + ([np.float64(1.5), np.float64(2.5)], [1.5, 2.5]), ], ids=[ "int", @@ -408,7 +409,7 @@ def test_the_iso_value_cache_entry_is_written_not_read(): assert g.get_property("iso_value") is None -@pytest.mark.parametrize("value", [None, 2.5, 3, True, np.int64(3), np.float32(0.5)]) +@pytest.mark.parametrize("value", [None, 2.5, 3, True, np.int64(3), np.float64(0.5)]) @pytest.mark.parametrize("attr", ["weight", "cost"]) def test_our_own_output_converts_back(value, attr): """What `to_networkx` emits, `from_networkx` accepts.