From 83d8c57ca818dff4157e24c79b8edd324f0ae9f2 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 19:40:10 -0600 Subject: [PATCH] Leave newer keywords and unconvertible weights to NetworkX Two declines that apply to every dispatched name. A keyword NetworkX added after its oldest supported release is now declined where the installed NetworkX lacks it: hits's method, closeness_centrality's sp and adjacency_matrix's format on 3.6. Such a NetworkX passes the keyword on, and the backend, whose wrappers take it, answered where NetworkX's own function raises TypeError for it. The backend's own keywords, such as chunksize, are taken on any NetworkX. A TypeError from converting an edge attribute's values is now a decline, as scipy's ValueError already was, so NetworkX answers or raises its own error. NetworkX's to_scipy_sparse_array negates the value of an undirected self-loop before scipy sees it, which raises TypeError for a string, bytes, None, a list or an object without arithmetic. A weighted call on such a graph raised that error at the call, where NetworkX often answers, raises a different error, or raises only as its generator is read. --- graphblas_algorithms/interface.py | 15 ++- .../nxapi/tests/test_link_analysis.py | 9 +- graphblas_algorithms/tests/test_dispatch.py | 109 ++++++++++++++++++ 3 files changed, 130 insertions(+), 3 deletions(-) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..251f038 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -512,9 +512,11 @@ def convert_from_nx( cls = DiGraph if graph.is_directed() else Graph try: G = cls.from_networkx(graph, weight=weight) - except ValueError as exc: + except (TypeError, ValueError) as exc: # scipy refuses the values' dtype: a string, None, an int beyond int64 and uint64. - # A rebuild was scanned for these above; a call that only reads the values is not. + # NetworkX's `to_scipy_sparse_array` negates a self-loop's value first, and that + # raises TypeError for a string. A rebuild was scanned for these above; a call that + # only reads the values is not. if weight is None: raise raise NotImplementedError( @@ -573,6 +575,15 @@ def can_run(name, args, kwargs): if reason is not None: return f"{reason}; networkx serves it" + if declared.signature is not None: + from _nx_graphblas.core import _NOT_EXTRA + + # A keyword NetworkX added after its oldest supported release, given to a NetworkX + # that predates it: there NetworkX's own function raises TypeError for it. + for key in kwargs: + if (name, key) in _NOT_EXTRA and key not in declared.signature.parameters: + return f"{name} takes no `{key}` in this NetworkX; networkx raises for it" + bound = _bound_args(name, args, kwargs) if bound is None: return True diff --git a/graphblas_algorithms/nxapi/tests/test_link_analysis.py b/graphblas_algorithms/nxapi/tests/test_link_analysis.py index 9bd75ee..7bb38ae 100644 --- a/graphblas_algorithms/nxapi/tests/test_link_analysis.py +++ b/graphblas_algorithms/nxapi/tests/test_link_analysis.py @@ -45,7 +45,14 @@ def test_hits_refuses_the_nstart_networkx_refuses(nstart, message): def test_hits_serves_the_power_iteration(): G = hits_graph() assert Dispatcher.can_run("hits", (G,), {}) is True - assert Dispatcher.can_run("hits", (G,), {"method": "power_iteration"}) is True + reason = Dispatcher.can_run("hits", (G,), {"method": "power_iteration"}) + if NX_HITS_TAKES_METHOD: + assert reason is True + else: + # A NetworkX without `method` raises TypeError for it, so the call is left to it. + assert "`method`" in reason + with pytest.raises(TypeError, match="method"): + nx.hits(G, method="power_iteration", backend="networkx") @pytest.mark.skipif(not NX_HITS_TAKES_METHOD, reason="NetworkX has no `method` before 3.7") diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 1765e78..50b54a5 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -205,6 +205,63 @@ def test_a_weight_the_conversion_cannot_hold_is_refused_for_any_name(value): Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="pagerank") +class NoArithmetic: + """An edge value with no arithmetic and no order.""" + + def __repr__(self): + return "NoArithmetic()" + + +# Values whose negation raises TypeError: NetworkX's `to_scipy_sparse_array` negates the value +# of an undirected self-loop before scipy sees it. +CANNOT_NEGATE = {"str": "red", "bytes": b"x", "None": None, "list": [1], "object": NoArithmetic()} + + +@pytest.mark.parametrize("value", CANNOT_NEGATE.values(), ids=CANNOT_NEGATE) +def test_a_self_loop_value_the_conversion_cannot_negate_is_refused(value): + """The conversion's TypeError, like scipy's ValueError, is a NotImplementedError.""" + G = nx.Graph([(0, 1, {"weight": value}), (1, 1, {"weight": value})]) + with pytest.raises(NotImplementedError, match="cannot hold"): + Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="pagerank") + + +# A name and its arguments after the graph, for a few of each kind of weighted name. +WEIGHTED_CALLS = { + "pagerank": (), + "clustering": (), + "volume": ([0, 1],), + "katz_centrality": (), + "google_matrix": (), + "closeness_centrality": (), + "eccentricity": (), + "single_source_bellman_ford_path_length": (0,), + "wiener_index": (), +} + + +@pytest.mark.parametrize("value", CANNOT_NEGATE.values(), ids=CANNOT_NEGATE) +@pytest.mark.parametrize("name", WEIGHTED_CALLS) +def test_networkx_answers_a_self_loop_value_the_conversion_cannot_negate( + name, value, backend_priority +): + """NetworkX's own answer or error, rather than the conversion's TypeError at the call.""" + func = _registered_algorithms[name] + [parameter] = _declared(name).attribute_parameters + + def outcome(**extra): + G = nx.cycle_graph(4) + nx.set_edge_attributes(G, value, "weight") + G.add_edge(2, 2, weight=value) + try: + return repr(func(G, *WEIGHTED_CALLS[name], **{parameter: "weight"}, **extra)) + except Exception as exc: + return type(exc), str(exc) + + expected = outcome(backend="networkx") + with backend_priority("algos"): + assert outcome() == expected + + @pytest.mark.parametrize("value", [-(2**63) - 1, 2**64]) def test_networkx_answers_a_weight_the_conversion_cannot_hold(value, backend_priority): G = nx.DiGraph([(0, 1, {"weight": value}), (1, 2, {"weight": 1}), (2, 0, {"weight": 1})]) @@ -395,6 +452,58 @@ def test_networkx_answers_a_declined_weight_on_the_automatic_path(value, backend assert got == pytest.approx(expected) +# NetworkX's own keywords newer than its oldest supported release (`_NOT_EXTRA`), each in a +# call this backend serves where the installed NetworkX has the keyword. +NEWER_KEYWORDS = { + ("adjacency_matrix", "format"): {"format": "csr"}, + ("closeness_centrality", "sp"): {"sp": None}, + ("hits", "method"): {"method": "power_iteration"}, +} + + +def test_every_newer_keyword_is_tested_here(): + from _nx_graphblas.core import _NOT_EXTRA + + functions = dispatcher_functions() + assert {pair for pair in _NOT_EXTRA if pair[0] in functions} == NEWER_KEYWORDS.keys() + + +def _same_answer(got, expected): + if hasattr(expected, "toarray"): + return got.format == expected.format and np.array_equal(got.toarray(), expected.toarray()) + if isinstance(expected, tuple): + return all(map(_same_answer, got, expected)) + return got == pytest.approx(expected) + + +@pytest.mark.parametrize(("name", "key"), NEWER_KEYWORDS, ids="-".join) +def test_a_newer_keyword_is_left_to_a_networkx_that_lacks_it(name, key, backend_priority): + """There NetworkX raises TypeError for it; where NetworkX has it, it is served.""" + import inspect + + G = nx.cycle_graph(4) + func = _registered_algorithms[name] + kwargs = NEWER_KEYWORDS[name, key] + reason = Dispatcher.can_run(name, (G,), kwargs) + if key in inspect.signature(func.orig_func).parameters: + assert reason is True + expected = func(G, **kwargs, backend="networkx") + assert _same_answer(func(G, **kwargs, backend="graphblas"), expected) + else: + assert f"`{key}`" in reason + with pytest.raises(TypeError, match=key) as expected: + func(G, **kwargs, backend="networkx") + with backend_priority("algos"), pytest.raises(TypeError) as got: + func(G, **kwargs) + assert str(got.value) == str(expected.value) + + +def test_a_keyword_of_this_backend_s_own_is_served_on_any_networkx(): + """`chunksize` is in no NetworkX; NetworkX passes it to the backend that takes it.""" + G = nx.cycle_graph(4) + assert Dispatcher.can_run("betweenness_centrality", (G,), {"chunksize": 2}) is True + + def test_a_hook_gets_the_arguments_by_name_with_defaults(monkeypatch): seen = []