From 0c0a53258d0f47c41f215e653f73585318c1a131 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 20:34:14 -0600 Subject: [PATCH] Serve the community link prediction names from a carried attribute cn_soundarajan_hopcroft, ra_index_soundarajan_hopcroft and within_inter_cluster read each node's community, and the conversion refused node attributes for them, so they always fell back. It now carries the community for them as it does for the attribute mixing names. The scores come from products masked to the pairs: the common neighbors over the adjacency, and those in the pair's community over the edges within communities, weighted by 1 / degree for the resource allocation index. The counts, and within_inter_cluster's ratios, are NetworkX's exactly; the resource allocation sums are added in another order, so within rounding. The triples come in NetworkX's order, and a node without the community raises NetworkXAlgorithmError when the pair that looks it up is reached, as there. Where two or more common neighbors of that pair lack it, NetworkX names the first in its sets' order, which a matrix does not keep, so such a call is left to it; so are community values other than plain Python ones, whose `==` may not be a dict's. --- README.md | 5 +- _nx_graphblas/__init__.py | 6 + _nx_graphblas/core.py | 20 + .../algorithms/link_prediction.py | 103 +++- graphblas_algorithms/interface.py | 3 + .../nxapi/assortativity/mixing.py | 10 +- graphblas_algorithms/nxapi/link_prediction.py | 220 +++++++- .../tests/test_community_link_prediction.py | 522 ++++++++++++++++++ .../nxapi/tests/test_link_prediction.py | 15 - graphblas_algorithms/tests/_dispatched.py | 3 + 10 files changed, 882 insertions(+), 25 deletions(-) create mode 100644 graphblas_algorithms/nxapi/tests/test_community_link_prediction.py diff --git a/README.md b/README.md index 867b154..7767e4a 100644 --- a/README.md +++ b/README.md @@ -259,10 +259,13 @@ graphblas_algorithms.nxapi │ └── pagerank ├── link_prediction │ ├── adamic_adar_index +│ ├── cn_soundarajan_hopcroft │ ├── common_neighbor_centrality │ ├── jaccard_coefficient │ ├── preferential_attachment -│ └── resource_allocation_index +│ ├── ra_index_soundarajan_hopcroft +│ ├── resource_allocation_index +│ └── within_inter_cluster ├── lowest_common_ancestors │ └── lowest_common_ancestor ├── operators diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 0588760..375e6d4 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -53,6 +53,7 @@ def get_info(): "center", "closeness_centrality", "clustering", + "cn_soundarajan_hopcroft", "common_neighbor_centrality", "complement", "compose", @@ -152,6 +153,7 @@ def get_info(): "partition_quality", "periphery", "preferential_attachment", + "ra_index_soundarajan_hopcroft", "radius", "reciprocity", "resource_allocation_index", @@ -171,6 +173,7 @@ def get_info(): "volume", "weakly_connected_components", "wiener_index", + "within_inter_cluster", # END: functions ) @@ -217,6 +220,7 @@ def get_info(): "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".', + "cn_soundarajan_hopcroft": "The triples come in NetworkX's order. A node without the community raises\nNetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\nNetworkX: a `community` that is None, callable or unhashable; communities other than\nints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\nnumpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\nfirst failing pair with two or more common neighbors without the community, of which\nNetworkX names the first in its sets' order (with every non-edge, a node with a community\nand two or more neighbors without one).", "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.", @@ -249,6 +253,7 @@ def get_info(): "node_degree_xy": 'The pairs come by edge, both ends in node order, not in NetworkX\'s adjacency order.\nNetworkX\'s own `degree_mixing_dict` takes these degrees as keys.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', "numeric_assortativity_coefficient": "The Pearson correlation of the pairs in float64, within rounding of NetworkX's. Where\nNetworkX squares ints past about 3e9 in int64, which wraps, this gives the true\ncoefficient. Values that are not real numbers, an iterator `nodes`, which NetworkX\nreads twice, and a node in `nodes` that is not in the graph are left to NetworkX; a\nnode without the attribute raises KeyError, as there.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.", "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.', + "ra_index_soundarajan_hopcroft": "The sums are added in another order than NetworkX's, so a score may differ from\nNetworkX's in its last bits.\nThe triples come in NetworkX's order. A node without the community raises\nNetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\nNetworkX: a `community` that is None, callable or unhashable; communities other than\nints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\nnumpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\nfirst failing pair with two or more common neighbors without the community, of which\nNetworkX names the first in its sets' order (with every non-edge, a node with a community\nand two or more neighbors without one).", "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.', @@ -256,6 +261,7 @@ def get_info(): "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.', + "within_inter_cluster": "The ratios are NetworkX's to the last bit. A `delta` other than a Python float or an\nint below 2**52 is left to NetworkX.\nThe triples come in NetworkX's order. A node without the community raises\nNetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\nNetworkX: a `community` that is None, callable or unhashable; communities other than\nints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\nnumpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\nfirst failing pair with two or more common neighbors without the community, of which\nNetworkX names the first in its sets' order (with every non-edge, a node with a community\nand two or more neighbors without one).", # END: additional_docs } # fmt: on diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index d4f6126..18894f4 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -132,6 +132,17 @@ "callable or unhashable, and values no dict can key." ) +_COMMUNITY = ( + "The triples come in NetworkX's order. A node without the community raises\n" + "NetworkXAlgorithmError when the pair that looks it up is reached, as there. Left to\n" + "NetworkX: a `community` that is None, callable or unhashable; communities other than\n" + "ints, floats, complex numbers, strings, bytes, None and tuples or frozensets of them,\n" + "numpy's values among them; a graph class with its own `adjacency` or `nodes`; and a\n" + "first failing pair with two or more common neighbors without the community, of which\n" + "NetworkX names the first in its sets' order (with every non-edge, a node with a community\n" + "and two or more neighbors without one)." +) + # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. _ADDITIONAL_DOCS = { @@ -176,6 +187,7 @@ ), "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, + "cn_soundarajan_hopcroft": _COMMUNITY, "common_neighbor_centrality": ( "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX." ), @@ -265,6 +277,10 @@ "node without the attribute raises KeyError, as there.\n" + _NODE_ATTRIBUTE ), "periphery": _ECCENTRICITY_BOUNDS, + "ra_index_soundarajan_hopcroft": ( + "The sums are added in another order than NetworkX's, so a score may differ from\n" + "NetworkX's in its last bits.\n" + _COMMUNITY + ), "radius": _ECCENTRICITY_BOUNDS, "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, @@ -272,6 +288,10 @@ "volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.\n" "With `weight`, an iterator `S` is left to NetworkX.", "wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW, + "within_inter_cluster": ( + "The ratios are NetworkX's to the last bit. A `delta` other than a Python float or an\n" + "int below 2**52 is left to NetworkX.\n" + _COMMUNITY + ), } # A graph these names return is rebuilt from one matrix, which holds its values in one type. diff --git a/graphblas_algorithms/algorithms/link_prediction.py b/graphblas_algorithms/algorithms/link_prediction.py index 63aca60..cf0aa8b 100644 --- a/graphblas_algorithms/algorithms/link_prediction.py +++ b/graphblas_algorithms/algorithms/link_prediction.py @@ -1,18 +1,28 @@ +from collections import namedtuple from math import inf, log import numpy as np -from graphblas import Matrix, Vector, binary +from graphblas import Matrix, Vector, binary, dtypes from graphblas.semiring import any_second, plus_first, plus_pair from ._bfs import _bfs_level from .shortest_paths._distance_batches import distance_batches __all__ = [ + "Communities", "adamic_adar_index", + "cn_soundarajan_hopcroft", "common_neighbor_centrality", + "communities", + "community_misses", "jaccard_coefficient", + "missing_common_neighbor", + "missing_neighbors", "preferential_attachment", + "ra_index_soundarajan_hopcroft", "resource_allocation_index", + "same_community", + "within_inter_cluster", ] # Each function scores node pairs given by id: `u` and `v` are arrays of one length, or `u` is @@ -67,7 +77,9 @@ def _pair_sums(G, u, v, weights=None, *, A=None): """For each pair, the common neighbors of its nodes: how many, or their total weight. The pair's own nodes are not common neighbors unless `A`, an adjacency with the self-loops - on its diagonal, is given in place of the one without them. A pair with none scores 0. + on its diagonal, is given in place of the one without them; another symmetric `A`, such as + the edges within communities, counts the neighbors common along its edges. A pair with + none scores 0. """ if A is None: A = G.get_property("offdiag") @@ -180,3 +192,90 @@ def common_neighbor_centrality(G, u, v, alpha=0.8): # NetworkX's order of operations, so that the result matches it to the last bit. with np.errstate(divide="ignore", invalid="ignore"): return alpha * shared + (1 - alpha) * len(G) / distances + + +# `codes`: each node's community by id, as a number: two nodes have equal numbers >= 0 when +# NetworkX takes their values as equal, -1 marks a node without the attribute, and -2 a value +# equal to nothing, itself included (NaN). +# `same`: the edges, self-loops left out, whose two ends have one community. +# `missing`: a Vector of 1.0 at each node without the attribute, or None when every node has it. +Communities = namedtuple("Communities", ["codes", "same", "missing"]) + + +def communities(G, codes): + """The `Communities` of the undirected `G` whose nodes have the community `codes`.""" + n = len(G) + rows, cols, _ = G.get_property("offdiag").to_coo(values=False) + held = codes[rows] + keep = (held == codes[cols]) & (held >= 0) + same = Matrix.from_coo(rows[keep], cols[keep], 1, dtype=dtypes.INT64, nrows=n, ncols=n) + ids = np.flatnonzero(codes == -1) + missing = Vector.from_coo(ids, 1.0, size=n) if ids.size else None + return Communities(codes, same, missing) + + +def cn_soundarajan_hopcroft(G, u, v, communities): + """The common neighbors, those in the pair's community counted twice.""" + return _pair_sums(G, u, v) + _pair_sums(G, u, v, A=communities.same) + + +def ra_index_soundarajan_hopcroft(G, u, v, communities): + """The sum of 1 / degree over the common neighbors in the pair's community; 0 for none. + + A pair of two communities has no common neighbor in both. + """ + return _pair_sums(G, u, v, _neighbor_weights(G, "resource_allocation"), A=communities.same) + + +def within_inter_cluster(G, u, v, communities, delta): + """Common neighbors in the pair's community over those outside it plus `delta`. + + The counts are exact, and one addition and one division in float64 are NetworkX's, so the + ratio is NetworkX's to the last bit; where the pair's nodes are not of one community, + NetworkX gives 0 instead. + """ + within = _pair_sums(G, u, v, A=communities.same) + inter = _pair_sums(G, u, v) - within + with np.errstate(divide="ignore", invalid="ignore", over="ignore"): + return within / (inter + delta) + + +def same_community(communities, u, v): + """Whether NetworkX takes the communities of each pair's nodes as equal.""" + codes = communities.codes + held = codes[u] + return (held == codes[v]) & (held >= 0) + + +def community_misses(G, u, v, communities): + """Where scoring each pair meets a node without a community, which NetworkX raises on. + + 0 where it meets none, -1 where `u` has none, -2 where `v` has none and `u` has one, and + otherwise, for a pair of one community, the number of its common neighbors without one, + each of which NetworkX looks up. None when every node has a community. + """ + if communities.missing is None: + return None + codes = communities.codes + shared = _pair_sums(G, u, v, communities.missing).astype(np.int64) + misses = np.where(same_community(communities, u, v), shared, 0) + misses = np.where(codes[v] == -1, -2, misses) + return np.where(codes[u] == -1, -1, misses) + + +def missing_neighbors(G, communities): + """How many neighbors without a community each node with one has, by id.""" + rv = np.zeros(len(G), np.int64) + if communities.missing is not None: + ids, counts = plus_pair(G.get_property("offdiag") @ communities.missing).new().to_coo() + rv[ids] = counts + rv[communities.codes < 0] = 0 + return rv + + +def missing_common_neighbor(G, u, v, communities): + """The id of the one common neighbor of `u` and `v`, not `u` or `v`, without a community.""" + A = G.get_property("offdiag") + row = binary.first(A[int(u), :].new() & A[int(v), :].new()).new() + [rv] = binary.first(row & communities.missing).new().to_coo(values=False)[0].tolist() + return rv diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index c888f76..b3d5a9e 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -499,10 +499,13 @@ class Dispatcher: mod = nxapi.link_prediction # ========================= adamic_adar_index = mod.adamic_adar_index + cn_soundarajan_hopcroft = mod.cn_soundarajan_hopcroft common_neighbor_centrality = mod.common_neighbor_centrality jaccard_coefficient = mod.jaccard_coefficient preferential_attachment = mod.preferential_attachment + ra_index_soundarajan_hopcroft = mod.ra_index_soundarajan_hopcroft resource_allocation_index = mod.resource_allocation_index + within_inter_cluster = mod.within_inter_cluster mod = nxapi.lowest_common_ancestors # ================================= diff --git a/graphblas_algorithms/nxapi/assortativity/mixing.py b/graphblas_algorithms/nxapi/assortativity/mixing.py index 8a6389f..c72e16d 100644 --- a/graphblas_algorithms/nxapi/assortativity/mixing.py +++ b/graphblas_algorithms/nxapi/assortativity/mixing.py @@ -155,20 +155,20 @@ def degree_mixing_matrix( return a -def node_attribute_rule(name, *, nodes_read_twice=False): - """The `can_run` rule of the names that mix a node attribute along each edge.""" +def node_attribute_rule(name, *, nodes_read_twice=False, param="attribute"): + """The `can_run` rule of the names that read the node attribute their `param` names.""" def hook(bound): import networkx as nx - attribute = bound["attribute"] + attribute = bound[param] if attribute is None or callable(attribute): # NetworkX's conversion then carries no attribute, or every one. - return f"{name} with `attribute` {attribute!r} is left to networkx" + return f"{name} with `{param}` {attribute!r} is left to networkx" try: hash(attribute) except TypeError: - return f"{name} with an unhashable `attribute` raises in networkx" + return f"{name} with an unhashable `{param}` raises in networkx" G = bound["G"] cls = type(G) if hasattr(G, "_adj") and ( diff --git a/graphblas_algorithms/nxapi/link_prediction.py b/graphblas_algorithms/nxapi/link_prediction.py index 1736cf8..c8d6355 100644 --- a/graphblas_algorithms/nxapi/link_prediction.py +++ b/graphblas_algorithms/nxapi/link_prediction.py @@ -1,21 +1,27 @@ from itertools import islice, repeat from math import log +from operator import eq import numpy as np from graphblas_algorithms import algorithms +from graphblas_algorithms.classes._node_attributes import MISSING from graphblas_algorithms.classes.graph import to_undirected_graph from graphblas_algorithms.utils import not_implemented_for -from ._utils import can_run +from ._utils import can_run, reads_node_attribute +from .assortativity.mixing import carrying, check_rule, node_attribute, node_attribute_rule from .exception import NetworkXAlgorithmError, NodeNotFound __all__ = [ "adamic_adar_index", + "cn_soundarajan_hopcroft", "common_neighbor_centrality", "jaccard_coefficient", "preferential_attachment", + "ra_index_soundarajan_hopcroft", "resource_allocation_index", + "within_inter_cluster", ] # Each function returns a generator of `(u, v, score)`, as NetworkX's do: `ebunch` is checked @@ -38,12 +44,16 @@ def _nothing(): yield from () -def _predict(G, ebunch, score, triples): +def _predict(G, ebunch, score, triples, check=None): """The triples for the pairs of `ebunch`, or of every non-edge when it is None. `score` is the kernel, over node ids; `triples` turns its scores into what NetworkX yields. + `check(G, uids, vids)`, given, is called on the call with the pairs' ids, or with None for + every non-edge, to raise NotImplementedError for pairs left to NetworkX. """ if ebunch is None: + if check is not None: + check(G, None, None) return _non_edges(G, score, triples) if iter(ebunch) is ebunch: # NetworkX reads `ebunch` twice, to check it and then to score it, so an iterator that @@ -59,6 +69,8 @@ def _predict(G, ebunch, score, triples): except Exception as exc: error = exc else: + if check is not None: + check(G, uids, vids) return _pairs(G, us, vs, uids, vids, score, triples) _check(G, ebunch) # raises what NetworkX raises first raise error @@ -198,3 +210,207 @@ def score(G, u, v): def preferential_attachment(G, ebunch=None): G = to_undirected_graph(G) return _predict(G, ebunch, algorithms.preferential_attachment, _products) + + +# The community names read a node attribute, which the conversion carries (`reads_node_attribute`). +# NetworkX looks up the community of `u`, then of `v`, and only where the two are equal those of +# the common neighbors; a node without the attribute raises NetworkXAlgorithmError there, when +# the generator reaches the pair. + +# Types whose `==` is a dict's equality of keys, as the conversion numbers the values, and never +# raises. NumPy's values are not among them: `np.bool_(True) == 2**70` raises OverflowError. +_PLAIN = frozenset({int, bool, float, complex, str, bytes, type(None)}) + + +def _plain(value): + cls = type(value) + if cls in _PLAIN: + return True + if cls is tuple or cls is frozenset: + return all(map(_plain, value)) + return False + + +def _communities(G, community, name): + """Each node's community as NetworkX compares them (`algorithms.Communities`). + + NetworkX compares two communities with `==`. For the plain types above that is the + equality by which the conversion numbered the values, but for a value not equal to itself + (NaN), which NetworkX finds equal to nothing. Other values are left to NetworkX. + """ + record = node_attribute(G, community, name) + + def compute(): + # The types in the order nodes first hold them, so that the same one is named each time. + for cls in dict.fromkeys(map(type, record.objects)): + if cls is type(MISSING) or cls in _PLAIN: + continue + held = (value for value in record.objects if type(value) is cls) + if cls in {tuple, frozenset} and all(map(_plain, held)): + continue + raise NotImplementedError( + f"{name} compares communities such as {cls.__name__} values with `==`, which " + "may differ from how a dict compares keys, or raise; networkx serves it" + ) + codes = record.codes.to_dense(fill_value=-1, dtype=np.int64) + # NaN: NetworkX's `==` finds it equal to nothing, itself included. + unequal = [code for code, value in enumerate(record.values) if not eq(value, value)] + if unequal: + codes[np.isin(codes, unequal)] = -2 + return algorithms.communities(G, codes) + + return G._cacheit(("communities", community), compute) + + +def _no_community(node, community): + """NetworkX's error for `node` without the attribute, raised from its KeyError.""" + error = NetworkXAlgorithmError(f"No community information available for Node {node}") + error.__cause__ = KeyError(community) + return error + + +def _one_missing_named(communities, community, name): + """The `check` of `_predict`: which node NetworkX names must follow from the pairs. + + Where two or more common neighbors of a pair lack the attribute, NetworkX names the first + in the order of a set it builds from its adjacency, which a matrix does not keep; such a + pair, if it is the first that raises, is left to NetworkX. With every non-edge, so is any + node with a community and two or more neighbors without one, which such a pair needs. + """ + reason = ( + f"{name} may meet two nodes without community {community!r} in one pair, and which " + "NetworkX names follows the order of its sets; networkx serves it" + ) + + def check(G, uids, vids): + if communities.missing is None: + return + if uids is None: + if algorithms.missing_neighbors(G, communities).max(initial=0) > 1: + raise NotImplementedError(reason) + return + misses = algorithms.community_misses(G, uids, vids, communities) + stop = _first(misses != 0) + if stop is not None and misses[stop] > 1: + raise NotImplementedError(reason) + + return check + + +def _community_triples(G, communities, community, convert): + """The `triples` of a community name, stopped where NetworkX raises for a missing value. + + `convert(values, uids, vids)` gives the Python numbers NetworkX yields from the scores. + """ + + def triples(us, vs, values, uids, vids): + misses = algorithms.community_misses(G, uids, vids, communities) + stop = None if misses is None else _first(misses != 0) + if stop is None: + return zip(us, vs, convert(values, uids, vids), strict=True) + us = list(us) + vs = list(vs) + if misses[stop] == -1: + node = us[stop] + elif misses[stop] == -2: + node = vs[stop] + else: + uid = uids if np.ndim(uids) == 0 else uids[stop] + wid = algorithms.missing_common_neighbor(G, uid, vids[stop], communities) + node = G.id_to_key[wid] + error = _no_community(node, community) + return _until(us, vs, convert(values, uids, vids), stop, error) + + return triples + + +def _community_predict(name, G, ebunch, community, kernel, convert): + """The triples of a community name for the converted `G`.""" + communities = _communities(G, community, name) + + def score(G, u, v): + return kernel(G, u, v, communities) + + def numbers(values, uids, vids): + return convert(communities, values, uids, vids) + + triples = _community_triples(G, communities, community, numbers) + return _predict(G, ebunch, score, triples, _one_missing_named(communities, community, name)) + + +def _counts(communities, values, uids, vids): + return values.tolist() + + +def _community_sums(communities, values, uids, vids): + # An empty sum, or a pair of two communities, is NetworkX's int 0. + return _python(values, values == 0) + + +def _cluster_ratios(communities, values, uids, vids): + # A pair of two communities is NetworkX's int 0; else a float, 0.0 included. + return _python(values, ~algorithms.same_community(communities, uids, vids)) + + +_cn_rule = node_attribute_rule("cn_soundarajan_hopcroft", param="community") + + +@can_run(_cn_rule) +@reads_node_attribute +@not_implemented_for("directed") +@not_implemented_for("multigraph") +def cn_soundarajan_hopcroft(G, ebunch=None, community="community"): + name = "cn_soundarajan_hopcroft" + check_rule(_cn_rule, G=G, community=community) + G = to_undirected_graph(carrying(G, community, name)) + kernel = algorithms.cn_soundarajan_hopcroft + return _community_predict(name, G, ebunch, community, kernel, _counts) + + +_ra_rule = node_attribute_rule("ra_index_soundarajan_hopcroft", param="community") + + +@can_run(_ra_rule) +@reads_node_attribute +@not_implemented_for("directed") +@not_implemented_for("multigraph") +def ra_index_soundarajan_hopcroft(G, ebunch=None, community="community"): + name = "ra_index_soundarajan_hopcroft" + check_rule(_ra_rule, G=G, community=community) + G = to_undirected_graph(carrying(G, community, name)) + kernel = algorithms.ra_index_soundarajan_hopcroft + return _community_predict(name, G, ebunch, community, kernel, _community_sums) + + +def _plain_delta(bound): + # NetworkX adds `delta` to a count and divides by the sum: in float64 for a float, and + # exactly for an int, which float64 matches below 2**52. Another type of number gives + # another type of answer. + delta = bound["delta"] + if type(delta) in {float, bool} or type(delta) is int and delta < 2**52: + return None + return ( + "within_inter_cluster computes with a float `delta`, or an int below 2**52; networkx " + "serves it" + ) + + +_within_rule = node_attribute_rule("within_inter_cluster", param="community") + + +@can_run(_within_rule, _plain_delta) +@reads_node_attribute +@not_implemented_for("directed") +@not_implemented_for("multigraph") +def within_inter_cluster(G, ebunch=None, delta=0.001, community="community"): + name = "within_inter_cluster" + check_rule(_within_rule, G=G, community=community) + check_rule(_plain_delta, delta=delta) + if delta <= 0: + raise NetworkXAlgorithmError("Delta must be greater than zero") + G = to_undirected_graph(carrying(G, community, name)) + + def kernel(G, u, v, communities): + return algorithms.within_inter_cluster(G, u, v, communities, delta) + + return _community_predict(name, G, ebunch, community, kernel, _cluster_ratios) diff --git a/graphblas_algorithms/nxapi/tests/test_community_link_prediction.py b/graphblas_algorithms/nxapi/tests/test_community_link_prediction.py new file mode 100644 index 0000000..cd6f524 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_community_link_prediction.py @@ -0,0 +1,522 @@ +"""The community link prediction names against NetworkX's own answers. + +Counts, and within_inter_cluster's ratios, are NetworkX's exactly; the sums of +ra_index_soundarajan_hopcroft are added in another order, so within REL. The triples come in +NetworkX's order, and a node without the attribute raises where NetworkX raises, after the same +triples, with the same error. +""" + +import itertools +import math +import types +from decimal import Decimal +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.interface import Dispatcher + +from .test_assortativity import automatic +from .test_link_prediction import _CONTAINERS, _INVALID + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +NAMES = ["cn_soundarajan_hopcroft", "ra_index_soundarajan_hopcroft", "within_inter_cluster"] +REL = 1e-12 +NAN = float("nan") + + +def _cause(exc): + cause = exc.__cause__ + return None if cause is None else (type(cause), cause.args) + + +def run(name, G, backend, **kwargs): + """What a caller sees: each triple with its score's type, and an error with where it came. + + A call this backend leaves to NetworkX raises NotImplementedError with + `backend="graphblas"`; "automatic" puts this backend first in NetworkX's priority. + """ + try: + if backend == "automatic": + triples = automatic(name, G, **kwargs) + else: + triples = getattr(nx, name)(G, backend=backend, **kwargs) + except NotImplementedError: + raise + except Exception as exc: + return "on the call", type(exc), str(exc), _cause(exc) + assert isinstance(triples, types.GeneratorType) + seen = [] + try: + for u, v, p in triples: + seen.append((u, v, type(p), p)) + except Exception as exc: + return seen, type(exc), str(exc), _cause(exc) + return seen + + +def _same_number(got, want, *, close): + if isinstance(want, float) and math.isnan(want): + return isinstance(got, float) and math.isnan(got) + if close and type(want) is float: + return got == pytest.approx(want, rel=REL, abs=0) + return got == want + + +def assert_same(name, got, want): + """`got` is `want`, but for the last bits of the resource allocation sums.""" + close = name == "ra_index_soundarajan_hopcroft" + if isinstance(want, tuple): # an error, after some triples or on the call + assert isinstance(got, tuple) + assert got[1:] == want[1:] + if want[0] == "on the call": + assert got[0] == want[0] + return + got, want = got[0], want[0] + assert isinstance(got, list) + assert [t[:3] for t in got] == [t[:3] for t in want] + for g, w in zip(got, want, strict=True): + assert _same_number(g[3], w[3], close=close), (g, w) + + +def check(name, G, **kwargs): + """True if this backend serves the call, with NetworkX's answer; NetworkX's either way. + + A callable `ebunch` makes a fresh one for each call. + """ + ebunch = kwargs.pop("ebunch") + + def fresh(): + return ebunch() if callable(ebunch) else ebunch + + want = run(name, G, "networkx", ebunch=fresh(), **kwargs) + assert_same(name, run(name, G, "automatic", ebunch=fresh(), **kwargs), want) + try: + got = run(name, G, "graphblas", ebunch=fresh(), **kwargs) + except NotImplementedError: + return False + assert_same(name, got, want) + return True + + +def declined(name, G, **kwargs): + """Why this backend leaves the call to NetworkX, from its rule or its wrapper.""" + with pytest.raises(NotImplementedError) as info: + run(name, G, "graphblas", **kwargs) + cause = info.value.__cause__ + return str(info.value) if cause is None else str(cause) + + +def path(**changes): + """The path 0-1-2-3-4, nodes 0 to 2 of community 0 and 3, 4 of community 1. + + `n3=None` takes node 3's community away, and `n3=value` gives it `value`; a node past 4 is + added, isolated. + """ + G = nx.path_graph(5) + nx.set_node_attributes(G, {0: 0, 1: 0, 2: 0, 3: 1, 4: 1}, "community") + for node, value in changes.items(): + node = int(node[1:]) + if node not in G: + G.add_node(node) + if value is not None: + G.nodes[node]["community"] = value + elif value is None: + del G.nodes[node]["community"] + else: + G.nodes[node]["community"] = value + return G + + +# Random graphs: community values of several kinds, some nodes without one, self-loops, and +# node keys that are not 0 to n - 1 in order. +KINDS = { + "ints": [0, 1, 2], + "strings": ["red", "green", "blue", "cyan"], + "one value": [7], + "equal numbers of several types": [1, 1.0, True, 1 + 0j, 2, 2.0, 3], + "strings and ints": ["1", 1, "a", None], + "tuples": [(1, "x"), (2, "y"), (1, "x")], + "nan objects": "nan objects", +} +SEEDS = range(330) + + +def random_case(seed): + """A graph, its pairs, and `delta` for seed `seed`; every kind and node key layout in turn.""" + rng = np.random.default_rng(seed) + n = int(rng.integers(0, 28)) + G = nx.gnp_random_graph(n, float(rng.choice([0.05, 0.15, 0.3, 0.6, 0.9])), seed=seed) + if n and rng.random() < 0.3: + G.add_edges_from((u, u) for u in rng.choice(n, min(n, 3), replace=False).tolist()) + layout = seed % 3 + if layout == 1: + G = nx.relabel_nodes(G, {i: f"n{(7 * i) % 31}" for i in range(n)}) + elif layout == 2: + H = nx.Graph() + H.add_nodes_from(rng.permutation(n).tolist()) + H.add_edges_from(G.edges) + G = H + nodes = list(G) + kind = list(KINDS)[seed % len(KINDS)] + for i, node in enumerate(nodes): + if kind == "nan objects": + G.nodes[node]["community"] = float("nan") if i % 3 == 0 else i % 2 + else: + G.nodes[node]["community"] = KINDS[kind][int(rng.integers(len(KINDS[kind])))] + missing = int(rng.choice([0, 0, 0, 1, 1, 2, 4])) + for node in rng.permutation(n)[:missing].tolist(): + del G.nodes[nodes[node]]["community"] + pairs = [] + if n: + ids = rng.integers(n, size=(int(rng.integers(0, 3 * n + 1)), 2)).tolist() + pairs = [(nodes[i], nodes[j]) for i, j in ids] + delta = [0.001, 0.5, 1, 3, 1e-300, math.inf, NAN, True][seed % 8] + return G, pairs, delta + + +def _kwargs(name, ebunch, delta): + if name == "within_inter_cluster": + return {"ebunch": ebunch, "delta": delta} + return {"ebunch": ebunch} + + +@pytest.mark.parametrize("seed", SEEDS) +def test_random_graphs(seed): + G, pairs, delta = random_case(seed) + for name in NAMES: + for ebunch in (pairs, None): + check(name, G, **_kwargs(name, ebunch, delta)) + + +def test_random_graphs_are_mostly_served(): + """Only the pairs that may name one of several nodes without a community are declined.""" + served = declined = 0 + for seed in SEEDS[:60]: + G, pairs, delta = random_case(seed) + for name in NAMES: + for ebunch in (pairs, None): + if check(name, G, **_kwargs(name, ebunch, delta)): + served += 1 + else: + declined += 1 + assert served > 4 * declined > 0 + + +# A node without the attribute: NetworkX raises when its generator reaches a pair that looks it +# up: as `u`, as `v`, or as a common neighbor of two nodes of one community. +_MISSING = { + "u, third pair": (path(n3=None), [(0, 2), (1, 4), (3, 0)]), + "v, second pair": (path(n3=None), [(0, 2), (0, 3)]), + "u before v": (path(n3=None, n0=None), [(1, 2), (3, 0)]), + "u as the caller's object": (path(n3=None), [(0, 2), (3.0, 1)]), + "v as the caller's object": (path(n3=None), [(0, 2), (1, True), (2, 3.0)]), + "common neighbor of one community": (path(n1=None), [(2, 4), (0, 2)]), + "common neighbor of two communities": (path(n1=None, n2=1), [(0, 2)]), + "common neighbor of a self-pair": (path(n1=None), [(4, 4), (2, 2)]), + "common neighbor of a NaN pair": (path(n1=None, n0=NAN), [(0, 2), (0, 0)]), + "common neighbor of a self-pair, NaN": (path(n1=None, n2=NAN), [(2, 2), (0, 0)]), + "every non-edge": (path(n3=None), None), + "every non-edge, a common neighbor": (path(n2=None), None), + "every pair has the attribute": (path(n5=None), [(0, 2), (1, 3)]), + "no node has it": (nx.complete_graph(4), [(0, 1)]), + "no node has it, every non-edge": (nx.empty_graph(4), None), + "a pair of nodes without it first": (path(n0=None, n2=None), [(0, 2), (1, 3)]), +} + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize("case", _MISSING) +def test_a_missing_community_raises_where_networkx_raises(name, case): + G, ebunch = _MISSING[case] + want = run(name, G, "networkx", ebunch=ebunch) + assert check(name, G, ebunch=ebunch) + if case not in { + "common neighbor of two communities", + "common neighbor of a NaN pair", + "every pair has the attribute", + }: + assert isinstance(want, tuple) + assert want[0] != "on the call" + assert want[1] is nx.NetworkXAlgorithmError + assert want[3] == (KeyError, ("community",)) + + +def _k6(*missing): + G = nx.complete_graph(6) + nx.set_node_attributes(G, 0, "community") + for node in missing: + del G.nodes[node]["community"] + return G + + +@pytest.mark.parametrize("name", NAMES) +def test_which_of_several_missing_common_neighbors_networkx_names_is_left_to_it(name): + G = _k6(2, 3, 4) + for ebunch in ([(0, 1)], [(0, 5), (1, 1)], [(5, 5)], None): + assert "may meet two nodes without community" in declined(name, G, ebunch=ebunch) + assert not check(name, G, ebunch=ebunch) + # Where NetworkX raises earlier, on a node it names first, the pair is never reached. + for ebunch in ([(2, 0), (0, 1)], [(0, 3), (0, 1)], [(0, 1, 2)], [(0, 9), (0, 1)]): + assert check(name, G, ebunch=ebunch) + assert check(name, _k6(2), ebunch=None) + + +@pytest.mark.parametrize("name", NAMES) +def test_every_non_edge_with_no_pair_meeting_two_nodes_without_a_community(name): + """Nodes without a community, or with NaN, may have many neighbors without one.""" + G = nx.path_graph(7) + G.add_edges_from([(1, 3), (4, 1), (4, 5)]) + H = G.copy() + nx.set_node_attributes(G, {0: 0, 4: NAN, 6: 0}, "community") + assert check(name, G, ebunch=None) + nx.set_node_attributes(H, {0: 0, 2: 0, 4: NAN, 6: 0}, "community") # 2 meets 1 and 3 + assert "may meet two nodes" in declined(name, H, ebunch=None) + + +@pytest.mark.parametrize("name", NAMES) +def test_values_networkx_takes_as_equal(name): + G = nx.complete_graph(6) + G.add_edge(6, 0) + values = [1, 1.0, True, complex(1, 0), b"1", (1,), "1"] + nx.set_node_attributes(G, dict(enumerate(values)), "community") + ebunch = list(itertools.product(G, repeat=2)) + assert check(name, G, ebunch=ebunch) + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize( + "values", + [ + [NAN, NAN, 0.0, -0.0, 0, None, NAN], # one NaN object, equal to nothing + [float("nan") for _ in range(7)], + [complex(NAN, 0), 0j, 0, (0, NAN), (0, NAN), frozenset([1, 2]), frozenset([2, 1])], + [None] * 7, + [b"a", "a", b"a", 2**70, float(2**70), True, 1], + ], +) +def test_awkward_values(name, values): + G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, 6), (6, 0), (0, 3), (1, 5)]) + G.add_edge(2, 2) + nx.set_node_attributes(G, dict(enumerate(values)), "community") + ebunch = list(itertools.product(G, repeat=2)) + assert check(name, G, ebunch=ebunch) + assert check(name, G, ebunch=None) + + +class Loud: + """Equal to every other Loud, but hashed by identity.""" + + def __eq__(self, other): + return isinstance(other, Loud) + + __hash__ = object.__hash__ + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize( + ("values", "match"), + [ + ([Fraction(1, 2), 0.5, Decimal(1), 1], "compares communities such as Fraction"), + ([1, np.int64(1), 2, 2], "compares communities such as int64"), + ([np.bool_(True), 2**70, 2, 2], "compares communities such as bool"), + ([np.str_("a"), "a", 2, 2], "compares communities such as str_"), + ([(1, np.float64(2)), (1, 2.0), 2, 2], "compares communities such as tuple"), + ([Loud(), Loud(), 1, 1], "compares communities such as Loud"), + ([(1, Loud()), (1, Loud()), 1, 1], "compares communities such as tuple"), + ([[1], [1], 2, 2], "cannot be read"), + ], +) +def test_values_whose_equality_a_dict_may_not_share_are_left_to_networkx(name, values, match): + G = nx.cycle_graph(4) + nx.set_node_attributes(G, dict(enumerate(values)), "community") + assert match in declined(name, G, ebunch=[(0, 2)]) + assert not check(name, G, ebunch=[(0, 2), (1, 3)]) + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize("community", [0, ("c", 1), True, 2.5, "two words"]) +def test_attribute_names_other_than_community(name, community): + G = path() + for node in G: + G.nodes[node][community] = G.nodes[node].pop("community") + G.nodes[1][1] = "other" # True looks up 1 + assert check(name, G, ebunch=[(0, 2), (1, 3), (2, 4)], community=community) + assert check(name, G, ebunch=None, community=community) + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize("community", [None, len, [1], {"a": 1}]) +def test_attribute_names_networkx_reads_otherwise_are_left_to_it(name, community): + G = path() + assert isinstance(Dispatcher.can_run(name, (G, [(0, 2)], community), {}), str) + with pytest.raises(NotImplementedError): + run(name, G, "graphblas", ebunch=[(0, 2)], community=community) + assert not check(name, G, ebunch=[(0, 2)], community=community) + + +@pytest.mark.parametrize( + ("delta", "served"), + [ + (0, True), + (-1, True), + (0.0, True), + (-0.0, True), + (False, True), + (-math.inf, True), + (-(10**400), True), + (NAN, True), + (math.inf, True), + (5e-324, True), + (1e-300, True), + (1, True), + (True, True), + (0.25, True), + (2**52 - 1, True), + (2**52, False), + (10**400, False), + (np.float64(0.5), False), + (np.int64(1), False), + (Fraction(1, 2), False), + ("x", False), + (None, False), + ], +) +def test_delta(delta, served): + """Raises on the call for delta <= 0; other types of number are left to NetworkX.""" + G = path() + G.add_edge(0, 2) + ebunch = [(0, 2), (0, 1), (0, 4), (1, 3), (0, 0), (2, 2), (3, 3)] + assert check("within_inter_cluster", G, ebunch=ebunch, delta=delta) is served + assert check("within_inter_cluster", G, ebunch=None, delta=delta) is served + + +def test_delta_is_checked_before_the_pairs(): + G = path(n3=None) + want = run("within_inter_cluster", G, "networkx", ebunch=[(0, 9)], delta=0) + assert want[:2] == ("on the call", nx.NetworkXAlgorithmError) + assert run("within_inter_cluster", G, "graphblas", ebunch=[(0, 9)], delta=0) == want + with pytest.raises(nx.NetworkXAlgorithmError, match="Delta"): + nxapi.within_inter_cluster(G, [(0, 9)], delta=-1) + + +def test_ratios_are_networkx_s_to_the_last_bit(): + G = nx.complete_graph(12) + nx.set_node_attributes(G, {i: i % 3 for i in G}, "community") + for delta in (0.001, 0.1, 0.3, 1e-300, 7, 1 / 3): + want = run("within_inter_cluster", G, "networkx", ebunch=None, delta=delta) + assert run("within_inter_cluster", G, "graphblas", ebunch=None, delta=delta) == want + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize("cls", [nx.DiGraph, nx.MultiGraph, nx.MultiDiGraph]) +def test_directed_and_multigraphs_raise_on_the_call(name, cls): + G = cls(path()) + want = run(name, G, "networkx", ebunch=[(0, 9)]) + assert want[:2] == ("on the call", nx.NetworkXNotImplemented) + assert run(name, G, "graphblas", ebunch=[(0, 9)]) == want + with pytest.raises(nx.NetworkXNotImplemented): + getattr(nxapi, name)(G, [(0, 2)]) + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize("which", _INVALID) +def test_ebunch_is_checked_on_the_call(name, which): + G = path(n2=None) + want = run(name, G, "networkx", ebunch=_INVALID[which]) + assert want[0] == "on the call" + assert run(name, G, "graphblas", ebunch=_INVALID[which]) == want + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize("which", _CONTAINERS) +def test_ebunch_containers(name, which): + """An iterator is used up by NetworkX's check, and nothing is scored or raised.""" + for G in (path(), path(n2=None)): + assert check(name, G, ebunch=_CONTAINERS[which]) + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize( + "G", + [nx.Graph(), nx.empty_graph(1), nx.empty_graph(4), nx.Graph([(0, 0)])], + ids=["null", "one node", "edgeless", "one self-loop"], +) +def test_small_graphs(name, G): + for missing in (False, True): + G = G.copy() + if not missing: + nx.set_node_attributes(G, 0, "community") + for ebunch in (None, [], list(itertools.product(G, repeat=2))): + assert check(name, G, ebunch=ebunch) + + +@pytest.mark.parametrize("labels", ["str", "tuple", "shuffled"]) +def test_every_non_edge_comes_in_networkx_order(labels): + G = nx.gnp_random_graph(40, 0.1, seed=3) + order = np.random.default_rng(3).permutation(40).tolist() + mapping = { + "str": {i: f"n{j}" for i, j in enumerate(order)}, + "tuple": {i: (j % 3, str(j)) for i, j in enumerate(order)}, + "shuffled": {i: 1000 + 7 * j for i, j in enumerate(order)}, + }[labels] + H = nx.Graph() + H.add_nodes_from((mapping[i], {"community": i % 4}) for i in order) + H.add_edges_from(nx.relabel_nodes(G, mapping).edges) + for name in NAMES: + want = run(name, H, "networkx", ebunch=None) + assert [t[:2] for t in run(name, H, "graphblas", ebunch=None)] == [t[:2] for t in want] + + +@pytest.mark.parametrize("name", NAMES) +def test_views(name): + G = path(n3=None, n6=1) + G.add_edges_from([(4, 6), (2, 6), (0, 6)]) + views = { + "subgraph": G.subgraph([0, 1, 2, 4, 6]), + "restricted": nx.restricted_view(G, [3], [(0, 1)]), + "edge subgraph": G.edge_subgraph([(0, 1), (1, 2), (2, 6), (4, 6)]), + } + for view in views.values(): + for ebunch in (None, list(itertools.product(view, repeat=2))): + assert check(name, view, ebunch=ebunch) + + +def test_one_conversion_serves_every_name_and_attribute(): + G = path(n4=2) + nx.set_node_attributes(G, {i: i // 2 for i in G}, "other") + with nx.config(cache_converted_graphs=True): + for _ in range(2): + for name, community in itertools.product(NAMES, ["community", "other"]): + assert check(name, G, ebunch=None, community=community) + nx.attribute_assortativity_coefficient(G, "community", backend="graphblas") + for name in NAMES: + assert check(name, G, ebunch=[(0, 2), (1, 3)]) + + +def test_direct_calls(): + G = path(n3=None) + for name in NAMES: + func = getattr(nxapi, name) + want = run(name, G, "networkx", ebunch=[(0, 2), (2, 4), (0, 3)]) + triples = func(G, [(0, 2), (2, 4), (0, 3)]) + assert next(triples)[:2] == (0, 2) + assert next(triples)[:2] == (2, 4) + with pytest.raises(nx.NetworkXAlgorithmError, match=r"Node 3$") as info: + next(triples) + assert _cause(info.value) == want[3] + with pytest.raises(NotImplementedError, match="does not carry it"): + func(ga.Graph.from_networkx(G), [(0, 2)]) + + +def test_every_name_is_dispatched_and_reads_the_attribute(): + from _nx_graphblas import get_info + + for name in NAMES: + assert name in get_info()["functions"] + assert getattr(Dispatcher, name)._reads_node_attribute diff --git a/graphblas_algorithms/nxapi/tests/test_link_prediction.py b/graphblas_algorithms/nxapi/tests/test_link_prediction.py index b5f810c..8f3ee3a 100644 --- a/graphblas_algorithms/nxapi/tests/test_link_prediction.py +++ b/graphblas_algorithms/nxapi/tests/test_link_prediction.py @@ -294,18 +294,3 @@ def test_a_weighted_conversion_in_the_cache_is_read_for_its_structure(call): with nx.config(cache_converted_graphs=True): nx.pagerank(G, backend="graphblas") # converts and caches with the weights assert _run(call, G, [(0, 3), (1, 3), (0, 1)], backend="graphblas") == expected - - -@pytest.mark.parametrize( - "name", ["cn_soundarajan_hopcroft", "ra_index_soundarajan_hopcroft", "within_inter_cluster"] -) -def test_the_community_attribute_names_are_left_to_networkx(name): - """They read a node attribute, which a backend graph does not hold.""" - from _nx_graphblas import get_info - - assert name not in get_info()["functions"] - assert not hasattr(ga.interface.Dispatcher, name) - G = nx.path_graph(4) - nx.set_node_attributes(G, {0: 0, 1: 0, 2: 1, 3: 1}, "community") - with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): - getattr(nx, name)(G, [(0, 2)], backend="graphblas") diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 49e5cf8..8ed9f6c 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -103,6 +103,7 @@ def call_args(kind, args): "center": ("tournament", ()), "closeness_centrality": ("undirected", ()), "clustering": ("undirected", ()), + "cn_soundarajan_hopcroft": ("attributed", ([(0, 1), (0, 2), (1, 3)], "colour")), "common_neighbor_centrality": ("undirected", ([(0, 1), (0, 4)],)), # Unweighted: the complement's new edges would have no weight to carry. "complement": ("plain", ()), @@ -205,6 +206,7 @@ def call_args(kind, args): "partition_quality": ("undirected", ([{0, 1}, {2, 3, 4}],)), "periphery": ("tournament", ()), "preferential_attachment": ("undirected", ([(0, 1), (0, 4)],)), + "ra_index_soundarajan_hopcroft": ("attributed", ([(0, 1), (0, 2), (1, 3)], "colour")), "radius": ("tournament", ()), "reciprocity": ("directed", ()), "resource_allocation_index": ("undirected", ([(0, 1), (0, 4)],)), @@ -226,4 +228,5 @@ def call_args(kind, args): "volume": ("undirected", ([0, 1],)), "weakly_connected_components": ("directed", ()), "wiener_index": ("tournament", ()), + "within_inter_cluster": ("attributed", ([(0, 1), (0, 2), (1, 3)], 0.001, "colour")), }