From 663d3c0e4529d4a49db57e9939f44a63831bad49 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 19:40:19 -0600 Subject: [PATCH] Add local_bridges A local bridge is an edge whose two ends share no neighbor. They are the edges of the strict upper triangle where a masked A @ A has no entry; A keeps its self-loops, so a node with one is its own neighbor, as in NetworkX. Each pair comes with its end first in node order first, as G.edges gives it, and the pairs come in node order of both ends. A span is the shortest length between the two ends without their edge. Spans are computed for a batch of edges at a time as the generator is read, a row per edge, each row started from the first end's other neighbors with that end taken as reached. Without a weight this is a breadth-first search that stops at the other end. With a weight it is Bellman-Ford over lengths that changed and are still below the other end's length so far. Weights are served when they are Python ints or floats, at least 0 and finite, and ints while no length can reach 2**63; other weights, and weight functions, are left to NetworkX. A batch holds as many rows as its memory allows, at the bytes a row takes per node at a batch's peak, measured for each kind of row. The rows filled so far are held as a bitmap once more than 1% full: held sparse, they were copied at each update, and a random tree of 20000 nodes, where each row searches a whole side, peaked at 1.7 GiB without weights and 3.3 GiB with them. It now peaks at 0.2 and 0.3 GiB. Values a matrix cannot hold, such as strings, are declined at the conversion, so NetworkX answers without spans, as it reads no weight then, and with spans raises as its generator is read. --- README.md | 2 + _nx_graphblas/__init__.py | 2 + _nx_graphblas/core.py | 9 + graphblas_algorithms/algorithms/__init__.py | 1 + graphblas_algorithms/algorithms/bridges.py | 166 +++++++++ graphblas_algorithms/interface.py | 4 + graphblas_algorithms/nxapi/__init__.py | 1 + graphblas_algorithms/nxapi/bridges.py | 50 +++ .../nxapi/tests/test_bridges.py | 331 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 1 + 10 files changed, 567 insertions(+) create mode 100644 graphblas_algorithms/algorithms/bridges.py create mode 100644 graphblas_algorithms/nxapi/bridges.py create mode 100644 graphblas_algorithms/nxapi/tests/test_bridges.py diff --git a/README.md b/README.md index 1bc06b5..723562c 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,8 @@ graphblas_algorithms.nxapi ├── boundary │ ├── edge_boundary │ └── node_boundary +├── bridges +│ └── local_bridges ├── centrality │ ├── betweenness │ │ ├── betweenness_centrality diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..43defe3 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -117,6 +117,7 @@ def get_info(): "k_truss", "katz_centrality", "laplacian_matrix", + "local_bridges", "local_efficiency", "lowest_common_ancestor", "mixing_expansion", @@ -222,6 +223,7 @@ def get_info(): "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, 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.", "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, 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.", "k_truss": "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.", + "local_bridges": "Edges come by their first end and then by their second, both in node order. NetworkX\ngoes by each node's adjacency order, so the order can differ; the pairs, each with its\nend first in node order first, and the spans are NetworkX's. Spans over a `weight` are\nserved for Python ints or floats that are at least 0 and finite, ints while the number\nof nodes times the largest stays below 2**62; other weights are left to NetworkX. With\nints mixed with floats, a span is a float where NetworkX's can be an int (3.0 for 3).\nThe graph is read at the call, not as the generator is read.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "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.", "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.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..fecb6d6 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -165,6 +165,15 @@ "k_corona": _CORE_SUBGRAPH, "k_crust": _CORE_SUBGRAPH, "k_shell": _CORE_SUBGRAPH, + "local_bridges": ( + "Edges come by their first end and then by their second, both in node order. NetworkX\n" + "goes by each node's adjacency order, so the order can differ; the pairs, each with its\n" + "end first in node order first, and the spans are NetworkX's. Spans over a `weight` are\n" + "served for Python ints or floats that are at least 0 and finite, ints while the number\n" + "of nodes times the largest stays below 2**62; other weights are left to NetworkX. With\n" + "ints mixed with floats, a span is a float where NetworkX's can be an int (3.0 for 3).\n" + "The graph is read at the call, not as the generator is read." + ), "local_efficiency": ( "The cost is the breadth-first levels times the chunks of walks, so a node whose\n" "neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n" diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..a26f1f2 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -1,5 +1,6 @@ from . import exceptions from .boundary import * +from .bridges import * from .centrality import * from .cluster import * from .community import * diff --git a/graphblas_algorithms/algorithms/bridges.py b/graphblas_algorithms/algorithms/bridges.py new file mode 100644 index 0000000..a2004b2 --- /dev/null +++ b/graphblas_algorithms/algorithms/bridges.py @@ -0,0 +1,166 @@ +import math + +import numpy as np +from graphblas import Matrix, Vector, binary, monoid, replace, unary +from graphblas.semiring import any_first, any_pair, any_second, min_plus + +__all__ = ["local_bridges"] + +# The memory a batch of span rows may take, and the bytes a row may take per node of the graph +# at a batch's peak. Measured on 20000 nodes (a random tree, where a row searches a whole side, +# and random bipartite graphs, whose frontiers are wide): up to about 9 bytes for the +# breadth-first rows and 45 for the Bellman-Ford rows, with rows reaching half the nodes. +# A row can reach all of them, so these are those figures doubled or more. +_BATCH_BUDGET = 2**30 +_HOP_BYTES = 32 +_WEIGHTED_BYTES = 96 + + +def _batch_rows(n, bytes_per_node): + """How many span rows a batch holds on `n` nodes.""" + return max(1, _BATCH_BUDGET // (bytes_per_node * n)) + + +def local_bridge_ids(G): + """The ids `(u, v)` of the edges whose ends share no neighbor, with `u < v`, sorted. + + A self-loop makes a node its own neighbor, so no edge at a node with a self-loop is a + local bridge, nor is a self-loop itself, as where NetworkX intersects neighbor sets. + """ + U = G.get_property("U-") + if U.nvals == 0: + empty = np.empty(0, np.uint64) + return empty, empty + A = G._A + shared = any_pair[bool](A @ A).new(mask=U.S) + bridges = U.dup(mask=~shared.S) + rows, columns, _ = bridges.to_coo(values=False) + order = np.lexsort((columns, rows)) + return rows[order], columns[order] + + +def _start(A, sources, targets): + """Each source's neighbors but its target, a row per source; and the sources and targets. + + Walking on from these rows, with each row's source taken as reached at 0, never crosses + the edge from the source to its target: the source is left only through these neighbors. + """ + b = len(sources) + rows = np.arange(b, dtype=np.uint64) + T = Matrix.from_coo(rows, targets, True, nrows=b, ncols=A.ncols) + S = Matrix.from_coo(rows, sources, True, nrows=b, ncols=A.ncols) + return A[sources, :].new(mask=~T.S), S, T + + +def _prefer_bitmap(M): + """Hold `M` as a bitmap once more than 1% of it is filled, rather than sparse. + + The rows filled so far grow as a search goes, a whole side of the graph on a tree. Held + sparse, each update made a new copy, and a batch's peak ran to hundreds of bytes an entry; + a bitmap, a byte or so a row and node, is updated in place. Below 1% a row's few entries + stay sparse, so a batch of short searches does not pay for a whole bitmap. + """ + M.ss.config["bitmap_switch"] = 0.01 + + +def _hop_spans(G, sources, targets): + """The fewest edges from each source to its target without the edge between them. + + A breadth-first search a row per pair; a row stops at its target. `inf` where the target + is not reached. + """ + A = G._A + b = len(sources) + F, S, T = _start(A, sources, targets) + F = unary.one[bool](F).new() + seen = binary.lor(F | S).new() + _prefer_bitmap(F) + _prefer_bitmap(seen) + spans = np.full(b, -1, np.int64) + active = np.ones(b, bool) + depth = 1 + while F.nvals > 0: + depth += 1 + F(~seen.S, replace) << any_pair[bool](F @ A) + reached = F.dup(mask=T.S) + if reached.nvals > 0: + rows, _, _ = reached.to_coo(values=False) + spans[rows] = depth + active[rows] = False + keep = Vector.from_coo(np.flatnonzero(active), True, size=b) + F << any_second[bool](keep.diag() @ F) + seen(F.S) << True + return [span if span >= 0 else math.inf for span in spans.tolist()] + + +def _weighted_spans(G, sources, targets): + """The least sum of weights from each source to its target without the edge between them. + + Bellman-Ford a row per pair. A row walks on only from lengths that changed and that are + below its target's length so far, which no longer path can lower as weights are at least 0. + `inf` where the target is not reached. + """ + A = G._A + dtype = A.dtype + b = len(sources) + F, S, T = _start(A, sources, targets) + D = F.dup() + D(S.S) << 0 + Mask = Matrix(bool, b, A.ncols) + for M in [F, D, Mask]: + _prefer_bitmap(M) + one = unary.one[bool] + while F.nvals > 0: + F << min_plus[dtype](F @ A) + Mask << one(F) + Mask(binary.second) << binary.lt(F & D) + F(Mask.V, replace) << F + D(F.S) << F + bound = D.dup(mask=T.S).reduce_rowwise(monoid.min).new() + if bound.nvals > 0 and F.nvals > 0: + Mask << one(F) + Mask(binary.second) << binary.lt(F & any_first[dtype](bound.diag() @ F)) + F(Mask.V, replace) << F + lengths = D.dup(mask=T.S).reduce_rowwise(monoid.min).new() + ids, values = lengths.to_coo() + spans = [math.inf] * b + for i, value in zip(ids.tolist(), values.tolist(), strict=True): + spans[i] = value + return spans + + +def _unit_weights(G): + """Whether every edge but a self-loop weighs the integer 1, so a span is a hop count.""" + if G._A.dtype.np_type.kind not in "iu": + return False + least, greatest = G.get_properties("min_element- max_element-") + return least.get(0) == 1 and greatest.get(0) == 1 + + +def local_bridges(G, *, with_span=True, weighted=False): + """Yield `(u, v)`, or `(u, v, span)`, for each edge whose ends share no neighbor. + + `u` is the end first in node order, as in NetworkX's `G.edges`; edges come by `u` and then + by `v`, both in node order. A span is the least length from `u` to `v` without their edge: + the fewest edges, or with `weighted` the least sum of `G`'s values, which must be at least + 0 and, if integers, small enough that no length reaches 2**63. `inf` where there is none. + Spans are computed a batch of edges at a time, as they are read. + """ + id_to_key = G.id_to_key + rows, columns = local_bridge_ids(G) + if not with_span: + for u, v in zip(rows.tolist(), columns.tolist(), strict=True): + yield id_to_key[u], id_to_key[v] + return + if len(rows) == 0: + return + if weighted and not _unit_weights(G): + spans_of, size = _weighted_spans, _batch_rows(len(G), _WEIGHTED_BYTES) + else: + spans_of, size = _hop_spans, _batch_rows(len(G), _HOP_BYTES) + for start in range(0, len(rows), size): + sources = rows[start : start + size] + targets = columns[start : start + size] + spans = spans_of(G, sources, targets) + for u, v, span in zip(sources.tolist(), targets.tolist(), spans, strict=True): + yield id_to_key[u], id_to_key[v], span diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 251f038..576fff0 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -238,6 +238,10 @@ class Dispatcher: edge_boundary = mod.edge_boundary node_boundary = mod.node_boundary + mod = nxapi.bridges + # ================= + local_bridges = mod.local_bridges + mod = nxapi.centrality # ==================== betweenness_centrality = mod.betweenness.betweenness_centrality diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..a09def3 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -1,4 +1,5 @@ from .boundary import * +from .bridges import * from .centrality import * from .cluster import * from .community import * diff --git a/graphblas_algorithms/nxapi/bridges.py b/graphblas_algorithms/nxapi/bridges.py new file mode 100644 index 0000000..041f223 --- /dev/null +++ b/graphblas_algorithms/nxapi/bridges.py @@ -0,0 +1,50 @@ +import numpy as np +from graphblas import dtypes + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.graph import to_undirected_graph +from graphblas_algorithms.utils import not_implemented_for + +__all__ = ["local_bridges"] + + +def _unserved_weights(G): + """Why the spans over `G`'s weights are left to NetworkX, or None. + + NetworkX's Dijkstra raises or can stop early on a negative weight, and NaN compares false, + so weights are served when at least 0 and finite. Integers are added in 64 bits here, so + they are served while no length can reach 2**63. Other dtypes, such as NumPy's narrow + floats or bools, are added in other types by NetworkX, and are left to it as well. + """ + A = G._A + if A.dtype not in {dtypes.INT64, dtypes.FP64}: + return f"local_bridges spans over {A.dtype} weights are not implemented here" + least, greatest = G.get_properties("min_element+ max_element+") + if least.get(0) < 0: + return "local_bridges spans over negative weights are not implemented here" + if A.dtype == dtypes.FP64: + if not np.isfinite(A.to_coo(rows=False, columns=False)[2]).all(): + return "local_bridges spans over NaN or infinite weights are not implemented here" + elif A.nrows * greatest.get(0) >= 2**62: + return "local_bridges spans over integer weights this large are not implemented here" + return None + + +@not_implemented_for("directed") +@not_implemented_for("multigraph") +def local_bridges(G, with_span=True, weight=None): + # Not a generator function: a decline must come at the call, where NetworkX's dispatcher + # can still hand the call to NetworkX. The returned generator reads spans as it goes. + # NetworkX computes spans for `with_span is True` only, so not for 1 or `np.True_`. + with_span = with_span is True + if callable(weight): + # The dispatcher declines a weight function for every name (`Dispatcher.can_run`); + # this is for a direct call. + raise NotImplementedError( + "local_bridges with a weight function is not implemented here; networkx serves it" + ) + weighted = with_span and weight is not None + G = to_undirected_graph(G, weight=weight if weighted else None) + if weighted and (reason := _unserved_weights(G)) is not None: + raise NotImplementedError(f"{reason}; networkx serves it") + return algorithms.local_bridges(G, with_span=with_span, weighted=weighted) diff --git a/graphblas_algorithms/nxapi/tests/test_bridges.py b/graphblas_algorithms/nxapi/tests/test_bridges.py new file mode 100644 index 0000000..b5ebdcf --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_bridges.py @@ -0,0 +1,331 @@ +"""local_bridges against NetworkX: the same pairs and spans, in node order.""" + +import inspect +import math +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms import bridges + +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 items, or the exception's exact type and message, at the call or at a next().""" + try: + return list(f(*args, **kwargs)) + except Exception as exc: + return type(exc), str(exc) + + +def assert_same(G, got, want): + """The same items, each yielded once, each span of NetworkX's type; in node order here.""" + assert inspect.isgenerator(got) + got = list(got) + assert len(got) == len(want) + assert set(got) == set(want) + types = {item[:2]: type(item[2]) for item in want if len(item) == 3} + assert all(type(item[2]) is types[item[:2]] for item in got if len(item) == 3) + position = {node: i for i, node in enumerate(G)} + assert got == sorted(got, key=lambda item: (position[item[0]], position[item[1]])) + + +def weigh(G, seed, kind): + rng = np.random.default_rng(seed) + for u, v in G.edges: + if kind == "int": + G[u][v]["weight"] = int(rng.integers(0, 10)) + elif kind == "float": + G[u][v]["weight"] = float(rng.choice([0.0, 0.1, 0.2, 0.3, 0.7, 1.5, 2.25])) + elif kind == "some missing" and rng.random() < 0.7: + G[u][v]["weight"] = int(rng.choice([1, 3])) + return G + + +def with_self_loops(G, seed): + rng = np.random.default_rng(seed) + G.add_edges_from((v, v) for v in rng.choice(len(G), size=max(1, len(G) // 8)).tolist()) + return G + + +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) + H = nx.Graph() + H.add_nodes_from(f"n{v}" for v in rng.permutation(list(G)).tolist()) + H.add_edges_from((f"n{u}", f"n{v}") for u, v in rng.permutation(list(G.edges)).tolist()) + return H + + +def tree(n, seed): + if hasattr(nx, "random_labeled_tree"): + return nx.random_labeled_tree(n, seed=seed) + return nx.random_tree(n, seed=seed) + + +GENERATORS = { + "sparse gnm": lambda s: nx.gnm_random_graph(10 + 3 * s, 12 + 4 * s, seed=s), + "dense gnp": lambda s: nx.gnp_random_graph(6 + s % 15, 0.5, seed=s), + "tree": lambda s: tree(4 + 2 * s, s), + "cycle with chords": lambda s: nx.Graph( + [*nx.cycle_graph(8 + s).edges, (0, 4 + s % 4), (1, 6 + s % 2)] + ), + "watts_strogatz": lambda s: nx.watts_strogatz_graph(20 + s, 4, 0.2, seed=s), + "barabasi_albert": lambda s: nx.barabasi_albert_graph(20 + 2 * s, 1 + s % 3, seed=s), + "self-loops": lambda s: with_self_loops(nx.gnm_random_graph(20 + s, 28 + s, seed=s), s), + "isolated nodes": lambda s: nx.disjoint_union( + nx.gnm_random_graph(15, 18, seed=s), nx.empty_graph(1 + s % 4) + ), + "string labels": lambda s: relabeled(nx.gnm_random_graph(25, 32, seed=s), s), + "grid": lambda s: nx.grid_2d_graph(2 + s % 5, 2 + s % 4), +} +MODES = { + "spans": ({}, None), + "pairs": ({"with_span": False}, None), + "int weights": ({"weight": "weight"}, "int"), + "float weights": ({"weight": "weight"}, "float"), + "weights some missing": ({"weight": "weight"}, "some missing"), +} + + +@pytest.mark.parametrize("seed", range(8)) +@pytest.mark.parametrize("mode", MODES) +@pytest.mark.parametrize("kind", GENERATORS) +def test_random_graphs_match_networkx(kind, mode, seed): + kwargs, weights = MODES[mode] + G = GENERATORS[kind](seed) + if weights is not None: + weigh(G, seed, weights) + want = list(nx.local_bridges(G, backend="networkx", **kwargs)) + assert_same(G, nx.local_bridges(G, backend="graphblas", **kwargs), want) + + +@pytest.mark.parametrize("size", [1, 2, 5]) +def test_spans_in_small_batches(monkeypatch, size): + """Spans a few edges at a time, as on a graph too large for one batch.""" + monkeypatch.setattr(bridges, "_batch_rows", lambda n, bytes_per_node: size) + for seed in range(3): + G = nx.gnm_random_graph(40, 55, seed=seed) + want = list(nx.local_bridges(G, backend="networkx")) + assert_same(G, nx.local_bridges(G, backend="graphblas"), want) + weigh(G, seed, "float") + want = list(nx.local_bridges(G, weight="weight", backend="networkx")) + assert_same(G, nx.local_bridges(G, weight="weight", backend="graphblas"), want) + + +@pytest.mark.parametrize( + ("G", "want"), + [ + (nx.Graph(), []), + (nx.empty_graph(3), []), + (nx.complete_graph(4), []), + (nx.path_graph(3), [(0, 1, math.inf), (1, 2, math.inf)]), + (nx.cycle_graph(5), [(0, 1, 4), (0, 4, 4), (1, 2, 4), (2, 3, 4), (3, 4, 4)]), + (nx.Graph([(0, 1), (1, 2), (2, 0), (2, 3)]), [(2, 3, math.inf)]), + ], + ids=["null graph", "no edges", "K4", "path", "cycle", "triangle with a tail"], +) +def test_known_answers(G, want): + assert list(nx.local_bridges(G, backend="graphblas")) == want + assert list(nx.local_bridges(G, backend="networkx")) == want + + +def test_self_loops(): + """A self-loop makes its node its own neighbor: no edge there is a local bridge.""" + G = nx.cycle_graph(5) + G.add_edge(0, 0) + want = [(1, 2, 4), (2, 3, 4), (3, 4, 4)] + assert list(nx.local_bridges(G, backend="graphblas")) == want + assert list(nx.local_bridges(G, backend="networkx")) == want + G = nx.path_graph(3) + G.add_edge(1, 1) + assert list(nx.local_bridges(G, backend="graphblas")) == [] + + +def test_order_and_ends_follow_node_order(): + """Each pair's first end comes first in node order, as in NetworkX's `G.edges`.""" + G = nx.Graph() + G.add_nodes_from([3, 1, 0, 2, 4]) + G.add_edges_from([(4, 3), (2, 0), (0, 1), (2, 4), (1, 3)]) + got = list(nx.local_bridges(G, with_span=False, backend="graphblas")) + assert got == [(3, 1), (3, 4), (1, 0), (0, 2), (2, 4)] + # NetworkX goes by each node's adjacency order, where 4 comes before 1 + want = list(nx.local_bridges(G, with_span=False, backend="networkx")) + assert want == [(3, 4), (3, 1), (1, 0), (0, 2), (2, 4)] + + +@pytest.mark.parametrize("with_span", [1, "yes", np.True_, None, 0, False]) +def test_spans_only_for_true(with_span): + """NetworkX computes spans for `with_span is True` only.""" + G = nx.cycle_graph(6) + want = list(nx.local_bridges(G, with_span, backend="networkx")) + assert all(len(item) == 2 for item in want) + assert list(nx.local_bridges(G, with_span, backend="graphblas")) == want + + +def test_weights_are_not_read_without_spans(): + G = nx.cycle_graph(6) + nx.set_edge_attributes(G, -1.5, "weight") + G[0][1]["weight"] = float("nan") + want = list(nx.local_bridges(G, False, "weight", backend="networkx")) + assert list(nx.local_bridges(G, False, "weight", backend="graphblas")) == want + + +def test_weighted_spans(): + G = nx.cycle_graph(4) + nx.set_edge_attributes(G, {(0, 1): 2.5, (1, 2): 1, (2, 3): 0.5, (3, 0): 4}, "weight") + got = list(nx.local_bridges(G, weight="weight", backend="graphblas")) + assert got == [(0, 1, 5.5), (0, 3, 4.0), (1, 2, 7.0), (2, 3, 7.5)] + # a missing weight is 1, as in NetworkX: ints + got = list(nx.local_bridges(G, weight="missing", backend="graphblas")) + assert got == [(0, 1, 3), (0, 3, 3), (1, 2, 3), (2, 3, 3)] + assert all(type(span) is int for _, _, span in got) + + +@pytest.mark.parametrize("one", [1, 1.0]) +def test_unit_weights(one): + """Weights of int 1 give int spans, of 1.0 float ones, as NetworkX's sums do.""" + G = nx.gnm_random_graph(30, 40, seed=5) + nx.set_edge_attributes(G, one, "weight") + G.add_edge(29, 29, weight=7) # a self-loop's weight changes no span + want = list(nx.local_bridges(G, weight="weight", backend="networkx")) + assert_same(G, nx.local_bridges(G, weight="weight", backend="graphblas"), want) + assert {type(span) for _, _, span in want if span != math.inf} == {type(one)} + + +def test_zero_weights(): + G = nx.cycle_graph(7) + nx.set_edge_attributes(G, 0, "weight") + G[3][4]["weight"] = 5 + want = list(nx.local_bridges(G, weight="weight", backend="networkx")) + assert_same(G, nx.local_bridges(G, weight="weight", backend="graphblas"), want) + + +def test_mixed_int_and_float_weights_give_floats(): + """A matrix holds one type: a span over ints only is 3.0 here and 3 in NetworkX.""" + G = nx.cycle_graph(4) + nx.set_edge_attributes(G, {(0, 1): 0.5, (1, 2): 1, (2, 3): 1, (3, 0): 1}, "weight") + want = list(nx.local_bridges(G, weight="weight", backend="networkx")) + got = list(nx.local_bridges(G, weight="weight", backend="graphblas")) + assert got == want + assert (0, 1, 3) in want + assert all(type(span) is float for _, _, span in got) + + +def _weights(values): + G = nx.cycle_graph(5) + for (u, v), value in zip(G.edges, values, strict=False): + G[u][v]["weight"] = value + return G + + +DECLINED = { + "negative": _weights([1, -1, 1, 1, 1]), + "negative self-loop": nx.Graph([(0, 1), (1, 2), (2, 3), (3, 0), (4, 4, {"weight": -1})]), + "nan": _weights([1.0, float("nan"), 1.0, 1.0, 1.0]), + "inf": _weights([1.0, float("inf"), 1.0, 1.0, 1.0]), + "-inf": _weights([1.0, -float("inf"), 1.0, 1.0, 1.0]), + "float32": _weights([np.float32(0.1)] * 5), + "bool": _weights([True, False, True, True, True]), + "huge int": _weights([1, 2**61, 1, 1, 1]), +} + + +@pytest.mark.parametrize("kind", DECLINED) +def test_weights_left_to_networkx(kind): + G = DECLINED[kind] + with pytest.raises(NotImplementedError, match="'graphblas' backend"): + nx.local_bridges(G, weight="weight", backend="graphblas") + want = answer(nx.local_bridges, G, weight="weight", backend="networkx") + with graphblas_first(): + # by repr, where NaN spans are the same + assert repr(answer(nx.local_bridges, G, weight="weight")) == repr(want) + with pytest.raises(NotImplementedError, match="networkx serves it"): + nxapi.local_bridges(ga.Graph.from_networkx(G, weight="weight"), weight="weight") + + +@pytest.mark.parametrize("with_span", [False, 1, "yes", None, True]) +@pytest.mark.parametrize("self_loop", [False, True]) +def test_string_weights_left_to_networkx(self_loop, with_span): + """A matrix holds no strings, so the conversion is declined, at the call. + + NetworkX reads no weight unless `with_span is True`, and answers; with spans it raises + TypeError as its generator is read. NetworkX's conversion negates a self-loop's weight, + which raises TypeError rather than scipy's ValueError: both are declined. + """ + G = nx.cycle_graph(5) + nx.set_edge_attributes(G, "a", "weight") + if self_loop: + G.add_edge(2, 2, weight="b") + want = answer(nx.local_bridges, G, with_span, "weight", backend="networkx") + for fallback in [False, True]: + with graphblas_first(fallback): + items = nx.local_bridges(G, with_span, "weight") # nothing raised at the call + assert answer(iter, items) == want + if with_span is True: + assert want == (TypeError, "unsupported operand type(s) for +: 'int' and 'str'") + else: + assert want == list(nx.local_bridges(G, with_span, backend="networkx")) + + +def test_weight_function_left_to_networkx(): + G = nx.cycle_graph(5) + weight = lambda u, v, d: 2 # noqa: E731 + want = list(nx.local_bridges(G, weight=weight, backend="networkx")) + with graphblas_first(): + assert list(nx.local_bridges(G, weight=weight)) == want + with pytest.raises(NotImplementedError, match="weight function"): + nxapi.local_bridges(ga.Graph.from_networkx(G), weight=weight) + + +ERRORS = { + "directed": lambda: nx.DiGraph([(0, 1), (1, 2)]), + "multigraph": lambda: nx.MultiGraph([(0, 1), (0, 1), (1, 2)]), + "multidigraph": lambda: nx.MultiDiGraph([(0, 1), (1, 2)]), +} + + +@pytest.mark.parametrize("with_span", [True, False]) +@pytest.mark.parametrize("kind", ERRORS) +def test_errors_are_networkx_s(kind, with_span): + """Raised at the call, as NetworkX raises them, with this backend first.""" + G = ERRORS[kind]() + with pytest.raises(nx.NetworkXNotImplemented) as want: + nx.local_bridges(G, with_span, backend="networkx") + for fallback in [False, True]: + with graphblas_first(fallback), pytest.raises(nx.NetworkXNotImplemented) as got: + nx.local_bridges(G, with_span) + assert str(got.value) == str(want.value) + + +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.local_bridges(G) + + +def test_backend_graph_called_directly(): + G = nx.barabasi_albert_graph(60, 2, seed=2) + weigh(G, 2, "float") + H = ga.Graph.from_networkx(G, weight="weight") + for kwargs in [{}, {"with_span": False}, {"weight": "weight"}]: + want = list(nx.local_bridges(G, backend="networkx", **kwargs)) + assert_same(G, nxapi.local_bridges(H, **kwargs), want) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..b940d20 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -164,6 +164,7 @@ def call_args(kind, args): "k_truss": ("undirected", (3,)), "katz_centrality": ("undirected", ()), "laplacian_matrix": ("undirected", ()), + "local_bridges": ("undirected", ()), "local_efficiency": ("undirected", ()), "lowest_common_ancestor": ("dag", (1, 2)), "mixing_expansion": ("undirected", ([0, 1], [2, 3])),