diff --git a/graphblas_algorithms/classes/_utils.py b/graphblas_algorithms/classes/_utils.py index fa821b1..491f40c 100644 --- a/graphblas_algorithms/classes/_utils.py +++ b/graphblas_algorithms/classes/_utils.py @@ -55,8 +55,22 @@ def drop_unrequested_values(G, weight): NetworkX reads a missing attribute. NetworkX's conversion cache is one way a graph with other values arrives: it serves a conversion to a later call that asks for less. `PRESERVE` is for the wrappers that rebuild their input and so want whatever values it holds. + + A call that reads complex values is refused, with NotImplementedError, so that NetworkX + answers it or raises its own error. NetworkX compares weights, or makes floats of them, and + so raises TypeError on most complex ones; GraphBLAS has no complex `min` or `max`, nor the + `min_plus` semiring of shortest paths, and its complex arithmetic elsewhere would answer + where NetworkX raises, or answer otherwise. Every wrapper that reads its weights asks here + first, on any graph: a conversion made for this call, one NetworkX cached for another, or + one given directly. """ - if weight is PRESERVE or (weight is not None and weight == G._weight): + if weight is PRESERVE: + return G + if weight is not None and weight == G._weight: + if G._A.dtype.np_type.kind == "c": + raise NotImplementedError( + f"Edge attribute {weight!r} has complex values; networkx serves the call" + ) return G if _has_no_values_to_drop(G): return G # the usual unweighted conversion is not copied diff --git a/graphblas_algorithms/nxapi/boundary.py b/graphblas_algorithms/nxapi/boundary.py index 3d5d4f2..1e81cf0 100644 --- a/graphblas_algorithms/nxapi/boundary.py +++ b/graphblas_algorithms/nxapi/boundary.py @@ -22,6 +22,10 @@ def edge_boundary(G, nbunch1, nbunch2=None, data=False, keys=False, default=None # A graph with no values has none to yield: `data=True` gives an empty mapping per edge # and a named attribute the caller's default, as in NetworkX. reads_values = bool(is_multigraph or (data and G._weight is not None)) + if data is True and G._weight is not None: + # The values are yielded from the matrix, so complex ones are refused, as for a call + # that names their attribute: NetworkX's own answer keeps each value's type. + G = to_graph(G, weight=G._weight) v1 = G.set_to_vector(nbunch1, ignore_extra=True) v2 = G.set_to_vector(nbunch2, ignore_extra=True) result = algorithms.edge_boundary(G, v1, v2, is_weighted=reads_values) diff --git a/graphblas_algorithms/nxapi/generators/ego.py b/graphblas_algorithms/nxapi/generators/ego.py index 32d562e..6c4806b 100644 --- a/graphblas_algorithms/nxapi/generators/ego.py +++ b/graphblas_algorithms/nxapi/generators/ego.py @@ -11,6 +11,10 @@ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None): # A subgraph keeps the input's edge data whatever `distance` names. NetworkX reads a # `distance` the edges do not carry as 1, so the radius is then a hop count. G = to_graph(G, weight=PRESERVE) + is_weighted = distance is not None and G._weight == distance + if is_weighted: + # The lengths are read, and complex ones refused, as for a call that names them. + G = to_graph(G, weight=distance) if n not in G: # NetworkX's shortest-path helpers raise these, by whether `distance` is given. if distance is None: @@ -23,7 +27,7 @@ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None): radius=radius, center=center, undirected=undirected, - is_weighted=distance is not None and G._weight == distance, + is_weighted=is_weighted, ) except algorithms.exceptions.Unbounded as e: # What NetworkX's Dijkstra raises on a negative cycle. diff --git a/graphblas_algorithms/nxapi/shortest_paths/weighted.py b/graphblas_algorithms/nxapi/shortest_paths/weighted.py index 2f2a016..5f057d8 100644 --- a/graphblas_algorithms/nxapi/shortest_paths/weighted.py +++ b/graphblas_algorithms/nxapi/shortest_paths/weighted.py @@ -14,11 +14,17 @@ def all_pairs_bellman_ford_path_length(G, weight="weight", *, chunksize="10 MiB"): + G = to_graph(G, weight=weight) + # Read on the call, so that a refusal (complex weights) reaches NetworkX's dispatcher, + # which can still answer instead, rather than the caller reading the generator. + return _all_pairs_bellman_ford_path_length(G, chunksize) + + +def _all_pairs_bellman_ford_path_length(G, chunksize): # Larger chunksize offers more parallelism, but uses more memory. # Chunksize indicates for how many source nodes to compute at one time. # The default is to choose the number of rows so the result, if dense, # will be about 10MB. - G = to_graph(G, weight=weight) chunksize = normalize_chunksize(chunksize, len(G) * G._A.dtype.np_type.itemsize, len(G)) if chunksize is None: # All at once diff --git a/graphblas_algorithms/nxapi/tests/test_community.py b/graphblas_algorithms/nxapi/tests/test_community.py index 04ba284..78facdc 100644 --- a/graphblas_algorithms/nxapi/tests/test_community.py +++ b/graphblas_algorithms/nxapi/tests/test_community.py @@ -157,6 +157,11 @@ def test_modularity_follows_networkx(name, weight, resolution): G, partition = _partitioned()[name] expected = quality.modularity(G, partition, weight=weight, resolution=resolution) for H in (G, backend(G, weight="weight")): + if name == "complex weights" and weight == "weight": + # Complex weights are left to NetworkX: tests/test_complex_weights.py. + with pytest.raises(NotImplementedError): + quality.modularity(H, partition, weight, resolution, backend="graphblas") + continue rv = quality.modularity(H, partition, weight, resolution, backend="graphblas") assert rv == pytest.approx(expected, rel=1e-12, abs=1e-15) diff --git a/graphblas_algorithms/tests/test_complex_weights.py b/graphblas_algorithms/tests/test_complex_weights.py new file mode 100644 index 0000000..e1b4377 --- /dev/null +++ b/graphblas_algorithms/tests/test_complex_weights.py @@ -0,0 +1,362 @@ +"""Complex edge weights are left to NetworkX, which answers them or raises its own error. + +NetworkX compares weights, or makes floats of them, so it raises TypeError on most complex +weights, and on some numpy ones answers in complex numbers. GraphBLAS has no complex `min` or +`max`, nor the `min_plus` semiring, so the backend raised KeyError for shortest paths, and +elsewhere answered with complex arithmetic where NetworkX raises. A call that reads complex +values now declines, and NetworkX answers it; a call that reads no values, or carries them +into a graph it rebuilds, is served. +""" + +import math +import sys +from collections.abc import Iterator, Mapping + +import networkx as nx +import numpy as np +import pytest +from networkx.utils.backends import _registered_algorithms + +from graphblas_algorithms import Graph, nxapi +from graphblas_algorithms.interface import Dispatcher + +pytestmark = pytest.mark.filterwarnings("ignore") + +S, T = set(range(10)), set(range(10, 30)) + + +def _other(G, shift): + return nx.relabel_nodes(G, {u: u + shift for u in G}) + + +# Each name that reads an edge attribute's values, called with the attribute `w`, or with None +# for an unweighted call where the name has one; and the kinds of graph it takes. +READERS = { + "adjacency_matrix": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "all_pairs_bellman_ford_path_length": (lambda f, G, w, **k: dict(f(G, weight=w, **k)), "UD"), + "average_clustering": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "average_shortest_path_length": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "bellman_ford_path": (lambda f, G, w, **k: f(G, 0, 7, weight=w, **k), "UD"), + "bellman_ford_path_length": (lambda f, G, w, **k: f(G, 0, 7, weight=w, **k), "UD"), + "betweenness_centrality": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "betweenness_centrality_subset": ( + lambda f, G, w, **k: f(G, [0, 1, 2], [5, 6, 7], weight=w, **k), + "UD", + ), + "center": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "closeness_centrality": (lambda f, G, w, **k: f(G, distance=w, **k), "UD"), + "clustering": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "conductance": (lambda f, G, w, **k: f(G, S, T, weight=w, **k), "UD"), + "cut_size": (lambda f, G, w, **k: f(G, S, T, weight=w, **k), "UD"), + "diameter": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "directed_modularity_matrix": (lambda f, G, w, **k: f(G, weight=w, **k), "D"), + "eccentricity": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "edge_betweenness_centrality": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "edge_betweenness_centrality_subset": ( + lambda f, G, w, **k: f(G, [0, 1, 2], [5, 6, 7], weight=w, **k), + "UD", + ), + "edge_boundary": (lambda f, G, w, **k: f(G, range(10), data=w or False, **k), "UD"), + "edge_expansion": (lambda f, G, w, **k: f(G, S, T, weight=w, **k), "UD"), + "ego_graph": (lambda f, G, w, **k: f(G, 0, radius=2, distance=w, **k), "UD"), + "eigenvector_centrality": (lambda f, G, w, **k: f(G, weight=w, max_iter=1000, **k), "UD"), + "floyd_warshall": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "floyd_warshall_numpy": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "floyd_warshall_predecessor_and_distance": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "google_matrix": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "group_closeness_centrality": (lambda f, G, w, **k: f(G, [0, 1], weight=w, **k), "UD"), + "gutman_index": (lambda f, G, w, **k: f(G, weight=w, **k), "U"), + "harmonic_centrality": (lambda f, G, w, **k: f(G, distance=w, **k), "UD"), + "harmonic_diameter": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "hyper_wiener_index": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "katz_centrality": (lambda f, G, w, **k: f(G, alpha=0.01, weight=w, **k), "UD"), + "laplacian_matrix": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "mixing_expansion": (lambda f, G, w, **k: f(G, S, T, weight=w, **k), "UD"), + "modularity": (lambda f, G, w, **k: f(G, [S, T], weight=w, **k), "UD"), + "modularity_matrix": (lambda f, G, w, **k: f(G, weight=w, **k), "U"), + "mutual_weight": (lambda f, G, w, **k: f(G, 0, 1, weight=w, **k), "UD"), + "negative_edge_cycle": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "normalized_cut_size": (lambda f, G, w, **k: f(G, S, T, weight=w, **k), "UD"), + "normalized_laplacian_matrix": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "overlapping_modularity": (lambda f, G, w, **k: f(G, [S, T], weight=w, **k), "U"), + "pagerank": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "periphery": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "radius": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + "schultz_index": (lambda f, G, w, **k: f(G, weight=w, **k), "U"), + "single_source_bellman_ford_path_length": ( + lambda f, G, w, **k: f(G, 0, weight=w, **k), + "UD", + ), + "volume": (lambda f, G, w, **k: f(G, S, weight=w, **k), "UD"), + "wiener_index": (lambda f, G, w, **k: f(G, weight=w, **k), "UD"), + # These read "weight" whatever they are given, or yield the edge data. + "hits": (lambda f, G, w, **k: f(G, max_iter=1000, **k), "UD"), + "tournament_matrix": (lambda f, G, w, **k: f(G, **k), "T"), + "edge_boundary, data=True": (lambda f, G, w, **k: f(G, range(10), data=True, **k), "UD"), +} +# The names that carry the values into a graph they rebuild, without computing with them. +CARRIERS = { + "compose": (lambda f, G, **k: f(G, _other(G, 5), **k), "UD"), + "disjoint_union": (lambda f, G, **k: f(G, G, **k), "UD"), + "union": (lambda f, G, **k: f(G, _other(G, 100), **k), "UD"), + "reverse": (lambda f, G, **k: f(G, **k), "D"), + "k_core": (lambda f, G, **k: f(G, **k), "UD"), + "k_corona": (lambda f, G, **k: f(G, 2, **k), "UD"), + "k_crust": (lambda f, G, **k: f(G, **k), "UD"), + "k_shell": (lambda f, G, **k: f(G, **k), "UD"), + "k_truss": (lambda f, G, **k: f(G, 3, **k), "U"), +} +# A carrier the backend declines for any weighted graph, complex or not. +NOT_SERVED = {"full_join"} +FLOATS = lambda k, rng: float(rng.uniform(0.05, 3.0)) # noqa: E731 +PATTERNS = { + "python complex": lambda k, rng: complex(float(rng.uniform(0.05, 3.0)), 0.5), + "np.complex64": lambda k, rng: np.complex64(complex(float(rng.uniform(0.05, 3.0)), 0.5)), + "one complex with no imaginary part among floats": lambda k, rng: ( + complex(1.5, 0.0) if k == 3 else float(rng.uniform(0.05, 3.0)) + ), +} + + +def _graph(value, kind, seed=1, n=30): + """A connected random graph whose every edge carries `value(k, rng)` as "weight".""" + rng = np.random.default_rng(seed) + if kind == "T": # a tournament + G = nx.DiGraph() + G.add_nodes_from(range(8)) + G.add_edges_from( + (u, v) if rng.random() < 0.5 else (v, u) for u in range(8) for v in range(u + 1, 8) + ) + else: + G = nx.DiGraph() if kind == "D" 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 kind == "D": + pairs += [(v, u) for u, v in pairs[::4]] + G.add_edges_from(dict.fromkeys(pairs)) + for k, (u, v) in enumerate(G.edges): + G[u][v]["weight"] = value(k, rng) + return G + + +def _public(name): + """The function a user calls; a decorator around NetworkX's dispatchable may refuse first.""" + func = _registered_algorithms[name] + return getattr(sys.modules[func.__module__], name, func) + + +def _form(x): + """A comparable form: graphs by nodes and edge data, containers by contents. + + Each number keeps its type; a graph of this backend is first converted to NetworkX's. + """ + if getattr(x, "__networkx_backend__", None) == "graphblas": + x = Dispatcher.convert_to_nx(x) + if isinstance(x, nx.Graph): + edges = sorted(((repr(u), repr(v), _form(d)) for u, v, d in x.edges(data=True)), key=repr) + return ("graph", type(x).__name__, sorted(map(repr, x)), edges) + if isinstance(x, Mapping): + return ("map", sorted(((repr(k), _form(v)) for k, v in x.items()), key=repr)) + if hasattr(x, "toarray"): + x = x.toarray() + if isinstance(x, np.ndarray): + return ("array", str(x.dtype), x.shape, [_form(v) for v in x.ravel().tolist()]) + if isinstance(x, set | frozenset): + return ("set", sorted(map(repr, x))) + if isinstance(x, list | tuple | Iterator): + return ("seq", [_form(v) for v in x]) + if isinstance(x, float | complex | np.floating | np.complexfloating): + return ("number", type(x).__name__, complex(x)) + return (type(x).__name__, repr(x)) + + +def _same(a, b, typed=True): + """Equal forms, each float or complex number of one type and within a relative 1e-12. + + `typed=False` for a graph the backend rebuilds: its matrix holds the values in one dtype, + and a change of type alone is let through (as 1.0 for 1 beside a float), so a float + beside a complex comes back complex, and an np.complex64 as a Python complex. + """ + if isinstance(a, tuple) and len(a) == 3 and a[0] == "number": + if not (isinstance(b, tuple) and len(b) == 3 and b[0] == "number"): + return False + if typed and a[1] != b[1]: + return False + x, y = a[2], b[2] + nan = any(math.isnan(v) for v in (x.real, x.imag, y.real, y.imag)) + return x == y or (not nan and abs(x - y) <= 1e-12 * max(abs(x), abs(y))) + if isinstance(a, tuple | list): + return ( + isinstance(b, type(a)) + and len(a) == len(b) + and all(_same(x, y, typed) for x, y in zip(a, b, strict=True)) + ) + return a == b + + +def _answer(name, call, G, *args, backend): + """("value", form) or (exception type, message). + + `backend="first"` puts graphblas first in NetworkX's priority, with fallback on, as a user + meets it; the names that return a graph (`ego_graph`, the carriers) follow `generators`. + """ + func = _public(name.split(",")[0]) + config = nx.config + priority = config.backend_priority + saved = list(priority.algos), list(priority.generators), config.fallback_to_nx + kwargs = {} + if backend == "first": + priority.algos = priority.generators = ["graphblas"] + config.fallback_to_nx = True + else: + kwargs["backend"] = backend + try: + rv = call(func, G.copy(), *args, **kwargs) + if name.startswith("edge_boundary"): + return "value", ("multiset", sorted((_form(e) for e in rv), key=repr)) + return "value", _form(rv) + except Exception as exc: + return type(exc), str(exc) + finally: + priority.algos, priority.generators, config.fallback_to_nx = saved + + +def _cases(table, patterns=PATTERNS): + return [ + pytest.param(name, pattern, kind, id=f"{name}-{pattern}-{kind}") + for name, (_, kinds) in table.items() + for pattern in patterns + for kind in kinds + ] + + +def _known(name): + if name.split(",")[0] not in _registered_algorithms: + pytest.skip(f"{name} is not dispatched by this NetworkX") + + +def test_every_name_that_reads_or_carries_edge_values_is_here(): + """A new name declaring edge attributes must be added to READERS or CARRIERS.""" + names = {name.split(",")[0] for name in (*READERS, *CARRIERS, *NOT_SERVED)} + declared = { + name + for name, func in _registered_algorithms.items() + if hasattr(Dispatcher, name) and (func.edge_attrs or func.preserve_edge_attrs) + } + assert declared <= names + + +@pytest.mark.parametrize(("name", "pattern", "kind"), _cases(READERS)) +def test_a_call_reading_complex_values_is_left_to_networkx(name, pattern, kind): + _known(name) + call = READERS[name][0] + G = _graph(PATTERNS[pattern], kind) + want = _answer(name, call, G, "weight", backend="networkx") + got = _answer(name, call, G, "weight", backend="first") + assert got[0] == want[0] + assert _same(got[1], want[1]) if got[0] == "value" else got[1] == want[1] + # Declined when asked of this backend by name, unless NetworkX refuses before dispatching. + explicit = _answer(name, call, G, "weight", backend="graphblas") + assert explicit[0] is NotImplementedError or explicit == want + + +@pytest.mark.parametrize(("name", "pattern", "kind"), _cases(CARRIERS)) +def test_a_graph_carrying_complex_values_is_rebuilt_and_served(name, pattern, kind): + _known(name) + call = CARRIERS[name][0] + G = _graph(PATTERNS[pattern], kind) + if _answer(name, call, _graph(FLOATS, kind), backend="graphblas")[0] is NotImplementedError: + pytest.skip(f"{name} is declined for float weights too, by this NetworkX") + want = _answer(name, call, G, backend="networkx") + for backend in ["graphblas", "first"]: + got = _answer(name, call, G, backend=backend) + assert got[0] == "value" + assert _same(got[1], want[1], typed=False) + + +UNWEIGHTED = { + name: entry + for name, entry in READERS.items() + if name not in {"hits", "tournament_matrix", "edge_boundary, data=True"} +} + + +@pytest.mark.parametrize(("name", "pattern", "kind"), _cases(UNWEIGHTED, ["python complex"])) +def test_an_unweighted_call_on_a_graph_with_complex_values_is_served(name, pattern, kind): + _known(name) + call = UNWEIGHTED[name][0] + G = _graph(PATTERNS[pattern], kind) + got = _answer(name, call, G, None, backend="graphblas") + assert got[0] is not NotImplementedError + if name == "ego_graph": # without `distance`, a carrier of the values + want = _answer(name, call, G, None, backend="networkx") + assert got[0] == want[0] == "value" + assert _same(got[1], want[1], typed=False) + return + # The answer for the same edges carrying floats: the complex values are not read. + # (Whether that answer is NetworkX's is for the tests of each name.) + want = _answer(name, call, _graph(FLOATS, kind), None, backend="graphblas") + assert got[0] == want[0] + assert _same(got[1], want[1]) if got[0] == "value" else got[1] == want[1] + + +# The first cases found: a 6-cycle of edges weighing 1.5 + 0.5j. +PROBE = { + "closeness_centrality": lambda G, **k: nx.closeness_centrality(G, distance="weight", **k), + "harmonic_centrality": lambda G, **k: nx.harmonic_centrality(G, distance="weight", **k), + "average_shortest_path_length": lambda G, **k: nx.average_shortest_path_length( + G, weight="weight", **k + ), + "pagerank": lambda G, **k: nx.pagerank(G, weight="weight", **k), + "single_source_bellman_ford_path_length": lambda G, **k: ( + nx.single_source_bellman_ford_path_length(G, 0, weight="weight", **k) + ), +} + + +@pytest.mark.parametrize("make", [complex, np.complex64], ids=["python complex", "np.complex64"]) +@pytest.mark.parametrize("name", PROBE) +def test_the_cycle_of_complex_weights(name, make): + G = nx.cycle_graph(6) + nx.set_edge_attributes(G, make(1.5 + 0.5j), "weight") + + def call(func, G, **kwargs): + return PROBE[name](G, **kwargs) + + want = _answer(name, call, G, backend="networkx") + assert _answer(name, call, G, backend="first") == want + assert _answer(name, call, G, backend="graphblas")[0] is NotImplementedError + + +def test_a_conversion_cached_for_a_rebuild_is_not_read_for_complex_values(): + """A conversion that holds complex values for a rebuild declines a later weighted call. + + `k_core` keeps every attribute, so its conversion holds the complex values; NetworkX + serves it to `pagerank`, which is to read them. + """ + G = _graph(PATTERNS["python complex"], "U") + nx.k_core(G, backend="graphblas") + [[key]] = [G.__networkx_cache__["backends"]["graphblas"].keys()] + assert key[0] is True # every edge attribute + with pytest.raises(NotImplementedError): + nx.pagerank(G, weight="weight", backend="graphblas") + assert len(G.__networkx_cache__["backends"]["graphblas"]) == 1 # it was reused + # unweighted, the same conversion serves + nx.pagerank(G, weight=None, backend="graphblas") + + +def test_a_backend_graph_holding_complex_values_declines_a_weighted_call(): + H = nx.cycle_graph(4) + nx.set_edge_attributes(H, 1 + 1j, "weight") + G = Graph.from_networkx(H, weight="weight") + with pytest.raises(NotImplementedError, match="complex values"): + nxapi.pagerank(G, weight="weight") + assert nxapi.pagerank(G, weight=None) == pytest.approx(nx.pagerank(H, weight=None)) + + +def test_all_pairs_bellman_ford_declines_on_the_call(): + """Not when its generator is read, where NetworkX could no longer answer instead.""" + G = _graph(PATTERNS["python complex"], "U") + with pytest.raises(NotImplementedError): + nx.all_pairs_bellman_ford_path_length(G, weight="weight", backend="graphblas")