diff --git a/README.md b/README.md index 1bc06b5..188c941 100644 --- a/README.md +++ b/README.md @@ -265,6 +265,8 @@ graphblas_algorithms.nxapi ├── regular │ ├── is_k_regular │ └── is_regular +├── richclub +│ └── rich_club_coefficient ├── shortest_paths │ ├── dense │ │ ├── floyd_warshall diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..e9ad4dd 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -144,6 +144,7 @@ def get_info(): "reciprocity", "resource_allocation_index", "reverse", + "rich_club_coefficient", "s_metric", "schultz_index", "score_sequence", @@ -227,6 +228,7 @@ def get_info(): "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "rich_club_coefficient": "Only `normalized=False` without a `seed` is answered here. The default,\n`normalized=True`, normalizes by graphs rewired with random double-edge swaps, and is\nleft to NetworkX. So is a `seed`: it changes nothing without normalization, but\nNetworkX 3.7 and later check it, and raise ValueError for one that cannot seed a\ngenerator.", "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.', "single_source_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..fd6f7a3 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -17,6 +17,7 @@ ("adjacency_matrix", "format"), ("closeness_centrality", "sp"), ("hits", "method"), + ("rich_club_coefficient", "n_samples"), } # Dispatched names newer than the oldest supported NetworkX, with the release that added each. @@ -173,6 +174,13 @@ "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, + "rich_club_coefficient": ( + "Only `normalized=False` without a `seed` is answered here. The default,\n" + "`normalized=True`, normalizes by graphs rewired with random double-edge swaps, and is\n" + "left to NetworkX. So is a `seed`: it changes nothing without normalization, but\n" + "NetworkX 3.7 and later check it, and raise ValueError for one that cannot seed a\n" + "generator." + ), "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, "single_source_bellman_ford_path_length": _PATH_OVERFLOW, diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..e845ed9 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -18,6 +18,7 @@ from .operators import * from .reciprocity import * from .regular import * +from .richclub import * from .shortest_paths import * from .simple_paths import * from .smetric import * diff --git a/graphblas_algorithms/algorithms/richclub.py b/graphblas_algorithms/algorithms/richclub.py new file mode 100644 index 0000000..ebc1491 --- /dev/null +++ b/graphblas_algorithms/algorithms/richclub.py @@ -0,0 +1,29 @@ +import numpy as np +from graphblas import agg + +__all__ = ["rich_club_coefficient"] + + +def rich_club_coefficient(G): + """`{k: 2 * E_k / (N_k * (N_k - 1))}` for k = 0, 1, ... while `N_k` is at least 2. + + `N_k` is the number of nodes of degree above k, and `E_k` the number of edges among them: + an edge counts while k is below the lower degree of its two ends. So a histogram of the + degrees and one of each edge's lower end degree give every `N_k` and `E_k` by suffix sums. + `G` is undirected without self-loops; its values are not read. This is NetworkX's + coefficient before its random normalization. + """ + A = G._A + if A.nvals == 0: + return {} + degrees = A.reduce_rowwise(agg.count).new().to_dense(fill_value=0).astype(np.int64) + # `above[k]` is N_k; it does not increase, so the k with N_k >= 2 come first + above = len(G) - np.cumsum(np.bincount(degrees)) + K = int(np.count_nonzero(above >= 2)) + rows, columns, _ = G.get_property("U-").to_coo(values=False) + lower = np.minimum(degrees[rows], degrees[columns]) + among = len(lower) - np.cumsum(np.bincount(lower, minlength=K))[:K] + above = above[:K] + # exact integers up to 2**53, so each value is the correctly rounded quotient, as NetworkX's + rc = 2 * among / (above * (above - 1)) + return dict(zip(range(K), rc.tolist(), strict=True)) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 251f038..e87b65c 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -394,6 +394,10 @@ class Dispatcher: is_k_regular = mod.is_k_regular is_regular = mod.is_regular + mod = nxapi.richclub + # ================== + rich_club_coefficient = mod.rich_club_coefficient + mod = nxapi.shortest_paths # ======================== floyd_warshall = mod.dense.floyd_warshall diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..cde4f75 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -19,6 +19,7 @@ from .operators import * from .reciprocity import * from .regular import * +from .richclub import * from .shortest_paths import * from .simple_paths import * from .smetric import * diff --git a/graphblas_algorithms/nxapi/richclub.py b/graphblas_algorithms/nxapi/richclub.py new file mode 100644 index 0000000..09d2051 --- /dev/null +++ b/graphblas_algorithms/nxapi/richclub.py @@ -0,0 +1,36 @@ +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.graph import to_undirected_graph +from graphblas_algorithms.utils import not_implemented_for + +from ._utils import can_run + +__all__ = ["rich_club_coefficient"] + + +def _unnormalized_without_seed(bound): + # NetworkX normalizes by graphs it rewires with random double-edge swaps. + if bound["normalized"]: + return ( + "rich_club_coefficient with normalized=True is not implemented here; networkx serves it" + ) + # A seed changes nothing without normalization, but NetworkX 3.7 and later check it all + # the same, raising ValueError for one that cannot seed a generator, and 3.6 does not: + # each NetworkX checks its own. + if bound.get("seed") is not None: + return "rich_club_coefficient with a seed is left to networkx, which checks it" + return None + + +@can_run(_unnormalized_without_seed) +@not_implemented_for("directed") +def rich_club_coefficient(G, normalized=True, Q=100, seed=None, *, n_samples=1): + # `Q` and NetworkX 3.7's `n_samples` steer only the normalization. + if (reason := _unnormalized_without_seed({"normalized": normalized, "seed": seed})) is not None: + raise NotImplementedError(reason) + G = to_undirected_graph(G) + if G.get_property("has_self_edges"): + # NetworkX's own exception, a plain Exception + raise Exception( # noqa: TRY002 + "rich_club_coefficient is not implemented for graphs with self loops." + ) + return algorithms.rich_club_coefficient(G) diff --git a/graphblas_algorithms/nxapi/tests/test_richclub.py b/graphblas_algorithms/nxapi/tests/test_richclub.py new file mode 100644 index 0000000..78c375b --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_richclub.py @@ -0,0 +1,274 @@ +"""rich_club_coefficient against NetworkX: normalized=False is answered here, the rest declined.""" + +import inspect +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + + +@contextmanager +def graphblas_first(fallback=True): + """NetworkX's dispatcher with this backend first, as a user who installs it meets it.""" + config = nx.config + saved = list(config.backend_priority.algos), config.fallback_to_nx + config.backend_priority.algos = ["graphblas"] + config.fallback_to_nx = fallback + try: + yield + finally: + config.backend_priority.algos, config.fallback_to_nx = saved + + +def answer(f, *args, **kwargs): + """The result, or the exception's exact type and message.""" + try: + return f(*args, **kwargs) + except Exception as exc: + return type(exc), str(exc) + + +def assert_same(got, want): + """The same degrees as keys, in the same order; each value within 1e-12, a Python float.""" + if isinstance(want, tuple): + assert got == want + return + assert type(got) is dict + assert list(got) == list(want) + assert all(type(k) is int for k in got) + assert all(type(v) is float for v in got.values()) + assert list(got.values()) == pytest.approx(list(want.values()), rel=1e-12, abs=0) + + +def _relabeled(G, seed): + """`G` with string node names, added in a shuffled order, and its edges shuffled too.""" + rng = np.random.default_rng(seed) + nodes = rng.permutation(list(G)).tolist() + edges = [tuple(e) for e in rng.permutation(list(G.edges)).tolist()] + H = nx.Graph() + H.add_nodes_from(f"n{v}" for v in nodes) + H.add_edges_from((f"n{u}", f"n{v}") for u, v in edges) + return H + + +def _with_isolates(G, seed): + G = G.copy() + G.add_nodes_from(range(len(G), len(G) + 1 + seed % 4)) + return G + + +GENERATORS = { + "gnp sparse": lambda s: nx.gnp_random_graph(20 + s % 40, 0.08, seed=s), + "gnp dense": lambda s: nx.gnp_random_graph(5 + s % 25, 0.6, seed=s), + "gnm": lambda s: nx.gnm_random_graph(30 + s, 2 * (30 + s), seed=s), + "barabasi_albert": lambda s: nx.barabasi_albert_graph(40 + 3 * s, 1 + s % 4, seed=s), + "powerlaw_cluster": lambda s: nx.powerlaw_cluster_graph(50 + s, 2, 0.3, seed=s), + "random_regular": lambda s: nx.random_regular_graph(2 + s % 4, 20 + 2 * (s % 10), seed=s), + "with isolated nodes": lambda s: _with_isolates(nx.gnp_random_graph(25, 0.1, seed=s), s), + "relabeled and shuffled": lambda s: _relabeled(nx.gnp_random_graph(30, 0.15, seed=s), s), + "two components": lambda s: nx.disjoint_union( + nx.gnp_random_graph(10 + s % 7, 0.4, seed=s), nx.barabasi_albert_graph(15, 2, seed=s) + ), + "stars and paths": lambda s: nx.disjoint_union( + nx.star_graph(3 + s % 9), nx.path_graph(2 + s % 5) + ), +} + + +@pytest.mark.parametrize("seed", range(32)) +@pytest.mark.parametrize("kind", GENERATORS) +def test_random_graphs_match_networkx(kind, seed): + G = GENERATORS[kind](seed) + want = nx.rich_club_coefficient(G, normalized=False, backend="networkx") + assert_same(nx.rich_club_coefficient(G, normalized=False, backend="graphblas"), want) + + +@pytest.mark.parametrize( + "G", + [ + nx.Graph(), + nx.empty_graph(3), + nx.path_graph(2), + nx.path_graph(3), + nx.path_graph(5), + nx.star_graph(4), + nx.complete_graph(4), + nx.complete_graph(30), + nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)]), + ], + ids=[ + "null graph", + "no edges", + "one edge", + "path 3", + "path 5", + "star", + "K4", + "K30", + "NetworkX's example", + ], +) +def test_small_graphs(G): + """Keys run from 0 while two or more nodes have degree above k, whichever degrees occur.""" + want = nx.rich_club_coefficient(G, normalized=False, backend="networkx") + got = nx.rich_club_coefficient(G, normalized=False, backend="graphblas") + assert_same(got, want) + + +def test_known_values(): + G = nx.Graph([(0, 1), (0, 2), (1, 2), (1, 3), (1, 4), (4, 5)]) + assert nx.rich_club_coefficient(G, normalized=False, backend="graphblas") == { + 0: 0.4, + 1: 2 / 3, + } + # a star: one node of degree above 0 past the leaves, so only k = 0 + assert nx.rich_club_coefficient(nx.star_graph(4), False, backend="graphblas") == {0: 0.4} + + +def test_weights_are_not_read(): + G = nx.gnp_random_graph(40, 0.2, seed=3) + for i, (u, v) in enumerate(G.edges): + G[u][v]["weight"] = [0, -1.5, float("nan"), 7][i % 4] + want = nx.rich_club_coefficient(G, normalized=False, backend="networkx") + assert_same(nx.rich_club_coefficient(G, normalized=False, backend="graphblas"), want) + H = ga.Graph.from_networkx(G, weight="weight") + assert_same(nxapi.rich_club_coefficient(H, normalized=False), want) + + +@pytest.mark.parametrize("normalized", [True, 1, "yes"]) +def test_normalized_is_left_to_networkx(normalized): + """NetworkX normalizes by graphs it rewires with random swaps from `seed`.""" + G = nx.gnp_random_graph(40, 0.2, seed=5) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + nx.rich_club_coefficient(G, normalized, backend="graphblas") + with pytest.raises(NotImplementedError, match="normalized=True"): + nxapi.rich_club_coefficient(ga.Graph.from_networkx(G), normalized) + want = nx.rich_club_coefficient(G, normalized, Q=5, seed=7, backend="networkx") + with graphblas_first(): + assert nx.rich_club_coefficient(G, normalized, Q=5, seed=7) == want + + +def test_default_is_normalized_and_left_to_networkx(): + G = nx.gnp_random_graph(40, 0.2, seed=6) + with pytest.raises(NotImplementedError): + nx.rich_club_coefficient(G, backend="graphblas") + want = answer(nx.rich_club_coefficient, G, seed=3, backend="networkx") + with graphblas_first(): + assert answer(nx.rich_club_coefficient, G, seed=3) == want + + +@pytest.mark.parametrize("normalized", [False, 0, None, ""]) +def test_falsy_normalized_is_served(normalized): + G = nx.gnp_random_graph(40, 0.2, seed=8) + want = nx.rich_club_coefficient(G, normalized, backend="networkx") + assert_same(nx.rich_club_coefficient(G, normalized, backend="graphblas"), want) + + +def test_q_changes_nothing_without_normalization(): + G = nx.gnp_random_graph(40, 0.2, seed=9) + want = nx.rich_club_coefficient(G, normalized=False, backend="networkx") + got = nx.rich_club_coefficient(G, False, 3, backend="graphblas") + assert_same(got, want) + + +@pytest.mark.parametrize( + "seed", + [42, "junk", 1.5, [1], np.random.default_rng(1)], + ids=["int", "str", "float", "list", "Generator"], +) +def test_seed_is_left_to_networkx(seed): + """NetworkX 3.7 and later check a seed even without normalization; 3.6 does not.""" + G = nx.gnp_random_graph(40, 0.2, seed=11) + with pytest.raises(NotImplementedError, match="graphblas"): + nx.rich_club_coefficient(G, normalized=False, seed=seed, backend="graphblas") + want = answer(nx.rich_club_coefficient, G, normalized=False, seed=seed, backend="networkx") + for fallback in [False, True]: + with graphblas_first(fallback): + assert answer(nx.rich_club_coefficient, G, normalized=False, seed=seed) == want + with pytest.raises(NotImplementedError, match="seed"): + nxapi.rich_club_coefficient(ga.Graph.from_networkx(G), normalized=False, seed=seed) + + +@pytest.mark.skipif( + "n_samples" in inspect.signature(nx.rich_club_coefficient).parameters, + reason="NetworkX 3.7 and later take n_samples", +) +def test_n_samples_is_refused_where_networkx_lacks_it(): + """NetworkX 3.6 raises TypeError for `n_samples`; the call is left to it.""" + G = nx.gnp_random_graph(40, 0.2, seed=12) + with pytest.raises(NotImplementedError, match="graphblas"): + nx.rich_club_coefficient(G, normalized=False, n_samples=1, backend="graphblas") + want = answer(nx.rich_club_coefficient, G, normalized=False, n_samples=1, backend="networkx") + assert want[0] is TypeError + for fallback in [False, True]: + with graphblas_first(fallback): + assert answer(nx.rich_club_coefficient, G, normalized=False, n_samples=1) == want + + +@pytest.mark.skipif( + "n_samples" not in inspect.signature(nx.rich_club_coefficient).parameters, + reason="n_samples was added in NetworkX 3.7", +) +@pytest.mark.parametrize("n_samples", [0, 1, 3]) +def test_n_samples_changes_nothing_without_normalization(n_samples): + """NetworkX checks `n_samples` only to normalize, so 0 is accepted here as there.""" + G = nx.gnp_random_graph(40, 0.2, seed=10) + want = nx.rich_club_coefficient(G, normalized=False, n_samples=n_samples, backend="networkx") + got = nx.rich_club_coefficient(G, normalized=False, n_samples=n_samples, backend="graphblas") + assert_same(got, want) + + +def _self_loop_graph(): + G = nx.path_graph(6) + G.add_edge(3, 3) + return G + + +ERRORS = { + "directed": lambda: nx.gnp_random_graph(10, 0.3, seed=1, directed=True), + "multigraph": lambda: nx.MultiGraph([(0, 1), (0, 1), (1, 2)]), + "multidigraph": lambda: nx.MultiDiGraph([(0, 1), (1, 2)]), + "self-loop": _self_loop_graph, +} + + +@pytest.mark.parametrize("normalized", [False, True]) +@pytest.mark.parametrize("kind", ERRORS) +def test_errors_are_networkx_s(kind, normalized): + """The exception's type and message, explicitly and with this backend first.""" + G = ERRORS[kind]() + want = answer(nx.rich_club_coefficient, G, normalized, backend="networkx") + assert isinstance(want, tuple) + for fallback in [False, True]: + with graphblas_first(fallback): + assert answer(nx.rich_club_coefficient, G, normalized) == want + + +def test_self_loop_is_refused_here(): + """Served, not declined: the backend raises NetworkX's own plain Exception.""" + G = _self_loop_graph() + got = answer(nx.rich_club_coefficient, G, normalized=False, backend="graphblas") + assert got == ( + Exception, + "rich_club_coefficient is not implemented for graphs with self loops.", + ) + H = ga.Graph.from_networkx(G) + assert answer(nxapi.rich_club_coefficient, H, normalized=False) == got + + +def test_directed_backend_graph_is_refused(): + G = ga.DiGraph.from_networkx(nx.DiGraph([(0, 1), (1, 2)])) + with pytest.raises(nx.NetworkXNotImplemented, match="not implemented for directed type"): + nxapi.rich_club_coefficient(G, normalized=False) + + +def test_backend_graph_called_directly(): + G = nx.barabasi_albert_graph(60, 3, seed=2) + want = nx.rich_club_coefficient(G, normalized=False, backend="networkx") + assert_same(nxapi.rich_club_coefficient(ga.Graph.from_networkx(G), normalized=False), want) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..ddcc89c 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -190,6 +190,8 @@ def call_args(kind, args): "radius": ("tournament", ()), "reciprocity": ("directed", ()), "resource_allocation_index": ("undirected", ([(0, 1), (0, 4)],)), + # normalized=False: the default normalization draws random swaps, which NetworkX serves. + "rich_club_coefficient": ("undirected", (False,)), # Unweighted: NetworkX 3.6.1 does not ask for `reverse`'s edge data, so a weighted graph # is declined there and answered on 3.7; the version is not what these tests are about. "reverse": ("plain directed", ()), diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 50b54a5..379e531 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -458,6 +458,7 @@ def test_networkx_answers_a_declined_weight_on_the_automatic_path(value, backend ("adjacency_matrix", "format"): {"format": "csr"}, ("closeness_centrality", "sp"): {"sp": None}, ("hits", "method"): {"method": "power_iteration"}, + ("rich_club_coefficient", "n_samples"): {"normalized": False, "n_samples": 5}, }