diff --git a/README.md b/README.md index 1bc06b5..8c01878 100644 --- a/README.md +++ b/README.md @@ -127,6 +127,9 @@ graphblas_algorithms.nxapi ├── boundary │ ├── edge_boundary │ └── node_boundary +├── bridges +│ ├── bridges +│ └── has_bridges ├── centrality │ ├── betweenness │ │ ├── betweenness_centrality diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..32e875f 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -45,6 +45,7 @@ def get_info(): "bfs_layers", "bfs_successors", "boundary_expansion", + "bridges", "center", "closeness_centrality", "clustering", @@ -86,6 +87,7 @@ def get_info(): "gutman_index", "harmonic_centrality", "harmonic_diameter", + "has_bridges", "has_path", "hits", "hyper_wiener_index", @@ -198,6 +200,7 @@ def get_info(): "betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.", "bfs_edges": "A breadth-first tree that may differ from NetworkX's, as may the order: a node's parent\nis its neighbor on the level above first in node order, and each level comes by parent,\nthen child, in node order. `sort_neighbors` is left to NetworkX.", "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.", + "bridges": "Each bridge comes once, as `(u, v)` with `u` before `v` in node order, by `u` and then\n`v` in node order, which may differ from the order of `G.edges()`. A NetworkX graph\nthat would have to be converted is left to NetworkX, the faster there, unless it has\n100000 nodes or more and 1.2 edges per node or more; one NetworkX will give a cached\nconversion is served from 10000 nodes.\nWith `root`, NetworkX searches the root's component alone, so a NetworkX graph is served\nonly on a cached conversion, or, unless it is a view, where this backend serves\n`node_connected_component`, which NetworkX's own `bridges` then calls. A backend graph\nis always served; with `root`, the root's component alone is searched where a short walk\nfrom the root finds it.", "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".\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.', "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".', "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", @@ -215,6 +218,7 @@ def get_info(): "gutman_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.', "harmonic_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', "harmonic_diameter": 'A precomputed `sp` 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".', + "has_bridges": "Served wherever `bridges` would serve the call NetworkX's own `has_bridges` makes to\nit, as this backend is then in `bridges`' priority. Elsewhere a NetworkX graph that\nwould have to be converted is left to NetworkX, the faster there (its scan of the edges\nstops at the first bridge), unless it has 200000 nodes or more and 2 edges per node or\nmore, or 300000 nodes and 1.2 edges per node; one NetworkX will give a cached\nconversion is served from 10000 nodes.\nWith `root`, NetworkX searches the root's component alone, so a NetworkX graph is served\nonly on a cached conversion, or, unless it is a view, where this backend serves\n`node_connected_component`, which NetworkX's own `bridges` then calls. A backend graph\nis always served; with `root`, the root's component alone is searched where a short walk\nfrom the root finds it.", "hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.', "hyper_wiener_index": "Raises 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.", "k_core": "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.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..d881728 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -99,6 +99,13 @@ # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. +_BRIDGES_ROOT = ( + "With `root`, NetworkX searches the root's component alone, so a NetworkX graph is served\n" + "only on a cached conversion, or, unless it is a view, where this backend serves\n" + "`node_connected_component`, which NetworkX's own `bridges` then calls. A backend graph\n" + "is always served; with `root`, the root's component alone is searched where a short walk\n" + "from the root finds it." +) _ADDITIONAL_DOCS = { "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, "average_shortest_path_length": ( @@ -122,6 +129,13 @@ "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n" "`sort_neighbors` is left to NetworkX." ), + "bridges": ( + "Each bridge comes once, as `(u, v)` with `u` before `v` in node order, by `u` and then\n" + "`v` in node order, which may differ from the order of `G.edges()`. A NetworkX graph\n" + "that would have to be converted is left to NetworkX, the faster there, unless it has\n" + "100000 nodes or more and 1.2 edges per node or more; one NetworkX will give a cached\n" + "conversion is served from 10000 nodes.\n" + _BRIDGES_ROOT + ), "center": _ECCENTRICITY_BOUNDS, "closeness_centrality": _NEGATIVE_EDGES, "common_neighbor_centrality": ( @@ -155,6 +169,14 @@ "gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, "harmonic_centrality": _NEGATIVE_EDGES, + "has_bridges": ( + "Served wherever `bridges` would serve the call NetworkX's own `has_bridges` makes to\n" + "it, as this backend is then in `bridges`' priority. Elsewhere a NetworkX graph that\n" + "would have to be converted is left to NetworkX, the faster there (its scan of the edges\n" + "stops at the first bridge), unless it has 200000 nodes or more and 2 edges per node or\n" + "more, or 300000 nodes and 1.2 edges per node; one NetworkX will give a cached\n" + "conversion is served from 10000 nodes.\n" + _BRIDGES_ROOT + ), "harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES, "hits": ( "A graph with nodes and no edges gets 0.0 for every node, where NetworkX's power\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..c1b04d7 --- /dev/null +++ b/graphblas_algorithms/algorithms/bridges.py @@ -0,0 +1,245 @@ +"""Bridges by Tarjan and Vishkin's method, with no walk that takes a step per level. + +A spanning forest comes from Boruvka's rounds, and each tree's Euler tour, ranked by pointer +jumping, numbers its nodes in preorder and gives each subtree's size. A subtree is then a run of +preorder numbers, and the tree edge above it is a bridge iff no non-tree edge leaves that run: +the least and greatest numbers its nodes reach by one lie inside it. Every step is a numpy pass, +and how many there are grows with log n, not with how deep the trees are; a breadth-first +search takes a step per level, and a path graph has as many levels as nodes. +""" + +import numpy as np +from graphblas import Vector, replace +from graphblas.semiring import any_pair + +from .components._labels import _keys_by_id + +__all__ = ["bridge_ids", "has_bridges"] + + +def _spanning_forest(n, us, vs): + """Which edges `us[i]`-`vs[i]` make a spanning forest, and each node's tree, named by a node. + + Boruvka's rounds, with an edge's position as its weight: each tree takes the first edge + that leaves it. With weights all different, the edges taken close no cycle, except that two + trees may take the same edge. Each round at least halves the trees that have an edge out. + """ + in_forest = np.zeros(len(us), bool) + label = np.arange(n) + edges = np.arange(len(us)) + lu, lv = us, vs # The trees at each end + while True: + crossing = lu != lv + edges, lu, lv = edges[crossing], lu[crossing], lv[crossing] + k = len(edges) + if k == 0: + return in_forest, label + first = np.full(n, k) + place = np.arange(k) + np.minimum.at(first, lu, place) + np.minimum.at(first, lv, place) + hooked = np.flatnonzero(first < k) + taken = first[hooked] + in_forest[edges[taken]] = True + target = np.where(lu[taken] == hooked, lv[taken], lu[taken]) + parent = np.arange(n) + parent[hooked] = target + # Two trees that took the same edge point at each other; the smaller stays a root. + mutual = (parent[target] == hooked) & (hooked < target) + parent[hooked[mutual]] = hooked[mutual] + while True: + grand = parent[parent] + if np.array_equal(grand, parent): + break + parent = grand + label = parent[label] + lu = parent[lu] + lv = parent[lv] + + +def _euler_tours(n, tu, tv, label): + """The arcs of the forest `tu[i]`-`tv[i]` as `(src, dst, after, twin, roots)`. + + Arc `i` and arc `i + t` are the two ways along forest edge `i`, so `twin` maps each to the + other; `after` counts the arcs that follow each arc in its tree's tour. A tree's tour starts + at its label along its first arc, and `roots` holds those labels in order. + """ + t = len(tu) + src = np.concatenate([tu, tv]) + dst = np.concatenate([tv, tu]) + twin = np.concatenate([np.arange(t, 2 * t), np.arange(t)]) + order = np.argsort(src, kind="stable") + place = np.empty(2 * t, np.intp) + place[order] = np.arange(2 * t) + degree = np.bincount(src, minlength=n) + stop = np.cumsum(degree) + start = stop - degree + # The arc after `u -> v` is the arc out of `v` that follows `v -> u`, round `v`'s arcs. + nxt = place[twin] + 1 + wrap = nxt == stop[dst] + nxt[wrap] = start[dst[wrap]] + succ = np.empty(2 * t + 1, np.intp) + succ[: 2 * t] = order[nxt] + end = 2 * t + succ[end] = end + roots = np.flatnonzero((label == np.arange(n)) & (degree > 0)) + # Cut each tour where it would come back round to its root's first arc. + succ[twin[order[stop[roots] - 1]]] = end + after = (succ != end).astype(np.intp) + while True: + after += after[succ] + succ = succ[succ] + if (succ == end).all(): + return src, dst, after[:-1], twin, roots + + +def _entries_by_row(A): + """`A`'s entries as `(rows, cols)`, each row's entries together, however `A` is stored. + + `to_coo` lists them in the order the matrix keeps them: by row, or by column in a matrix + stored by column, hypersparse, bitmap or not. + """ + rows, cols, _ = A.to_coo(values=False) + rows = rows.astype(np.intp) + cols = cols.astype(np.intp) + if len(rows) > 1 and (rows[1:] < rows[:-1]).any(): + order = np.argsort(rows, kind="stable") + rows = rows[order] + cols = cols[order] + return rows, cols + + +def _bridge_ids(n, rows, cols): + """The bridges as `(parents, children)` of a spanning forest, and each node's tree label. + + The graph has `n` nodes and the edges `rows[i]`-`cols[i]` both ways, no self-loop, with + each row's entries together, as `_entries_by_row` gives them. + """ + upper = rows < cols + us = rows[upper] + vs = cols[upper] + in_forest, label = _spanning_forest(n, us, vs) + src, dst, after, twin, roots = _euler_tours(n, us[in_forest], vs[in_forest], label) + down = after > after[twin] + parent = np.full(n, -1) + parent[dst[down]] = src[down] + size = np.zeros(n, np.intp) + size[dst[down]] = (after[down] - after[twin[down]] + 1) // 2 + # Preorder numbers: trees of two or more nodes in a row, in the order of their roots, and + # a node's number is its tree's first plus the arcs down in the tour up to its own. + tree_size = np.bincount(label, minlength=n)[roots] + arcs_through = np.cumsum(2 * (tree_size - 1)) + tree_of = np.empty(n, np.intp) + tree_of[roots] = np.arange(len(roots)) + arc_tree = tree_of[label[src]] + tour_place = arcs_through[arc_tree] - 1 - after + down_seen = np.zeros(len(src), np.intp) + down_seen[tour_place[down]] = 1 + down_seen = np.cumsum(down_seen) + pre = np.full(n, -1) + pre[roots] = (arcs_through - 2 * (tree_size - 1)) // 2 + np.arange(len(roots)) + pre[dst[down]] = down_seen[tour_place[down]] + arc_tree[down] + # The least and greatest numbers each node reaches by an edge other than its tree edge up. + keep = cols != parent[rows] + rows = rows[keep] + reach = pre[cols[keep]] + # Indexed by preorder number, which runs over the nodes of trees of two or more nodes. + low = np.arange(np.count_nonzero(pre >= 0)) + high = low.copy() + if len(rows) > 0: + firsts = np.flatnonzero(np.r_[True, rows[1:] != rows[:-1]]) + at = pre[rows[firsts]] + low[at] = np.minimum(low[at], np.minimum.reduceat(reach, firsts)) + high[at] = np.maximum(high[at], np.maximum.reduceat(reach, firsts)) + children = dst[down] + first = pre[children] + span = size[children] + least, greatest = _range_min_max(low, high, first, span) + is_bridge = (least >= first) & (greatest < first + span) + return parent[children[is_bridge]], children[is_bridge], label + + +def _range_min_max(low, high, first, span): + """`low[first[i] : first[i] + span[i]].min()` and `high`'s max likewise, for each `i`. + + A sparse table built a level at a time: at level `j`, `low[i]` is the least of the `2**j` + values from `i`, and each run of `2**j` to `2**(j + 1) - 1` values is two such windows. + """ + least = np.empty(len(first), low.dtype) + greatest = np.empty(len(first), high.dtype) + if len(first) == 0: + return least, greatest + level = np.frexp(span)[1] - 1 # floor(log2(span)), exact for spans below 2**53 + order = np.argsort(level, kind="stable") + bounds = np.r_[0, np.cumsum(np.bincount(level))] + for j in range(len(bounds) - 1): + which = order[bounds[j] : bounds[j + 1]] + if len(which) > 0: + left = first[which] + right = left + span[which] - (1 << j) + least[which] = np.minimum(low[left], low[right]) + greatest[which] = np.maximum(high[left], high[right]) + if j + 2 < len(bounds): + step = 1 << j + low = np.minimum(low[:-step], low[step:]) + high = np.maximum(high[:-step], high[step:]) + return least, greatest + + +def _component_ids(A, index, steps): + """The ids of node `index`'s component in order, or None if it reaches over `steps` levels. + + A breadth-first walk takes a step per level, so it ends soon on a component of few levels, + as a small one has, and is cut short on a deep one. + """ + seen = Vector(bool, A.nrows) + front = Vector(bool, A.nrows) + seen[index] = True + front[index] = True + for _ in range(steps + 1): # the last step finds the front empty + front(~seen.S, replace) << any_pair[bool](front @ A) + if front.nvals == 0: + return seen.to_coo(values=False)[0].astype(np.intp) + seen(front.S) << True + return None + + +def bridge_ids(G, root=None): + """The bridges as arrays `(us, vs)` of node ids, sorted by `us` and then `vs` in node order. + + `u` comes before `v` in `G`'s node order, which is id order in a graph converted from + NetworkX but not in every graph an operator builds. With `root`, those of `root`'s + component only: a walk from `root` finds the component, and if it has under half the nodes + only its edges are searched. A walk cut short after about 2 log2(n) levels, or a component + of half the nodes or more, searches the whole graph and keeps the component's bridges. + Self-loops are never bridges. Not named `bridges`, which would hide this module behind the + function in `algorithms`. + """ + n = len(G) + A = G.get_property("offdiag") + ids = None + if root is not None: + index = G._key_to_id[root] + ids = _component_ids(A, index, 2 * n.bit_length()) + if ids is not None and 2 * len(ids) < n: + parents, children, _ = _bridge_ids(len(ids), *_entries_by_row(A[ids, ids].new())) + parents = ids[parents] + children = ids[children] + else: + parents, children, label = _bridge_ids(n, *_entries_by_row(A)) + if root is not None: + keep = label[children] == label[index] + parents = parents[keep] + children = children[keep] + _, places = G._cacheit("keys_by_id", _keys_by_id, G) + at_parent = parents if places is None else places[parents] + at_child = children if places is None else places[children] + swap = at_parent > at_child + us = np.where(swap, children, parents) + vs = np.where(swap, parents, children) + order = np.lexsort((np.maximum(at_parent, at_child), np.minimum(at_parent, at_child))) + return us[order], vs[order] + + +def has_bridges(G, root=None): + return len(bridge_ids(G, root)[0]) > 0 diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index ec5ebed..19f9b69 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -232,6 +232,11 @@ class Dispatcher: edge_boundary = mod.edge_boundary node_boundary = mod.node_boundary + mod = nxapi.bridges + # ================= + bridges = nxapi.bridges + has_bridges = nxapi.has_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..a76d3d7 --- /dev/null +++ b/graphblas_algorithms/nxapi/bridges.py @@ -0,0 +1,128 @@ +import networkx as nx + +from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms.components._labels import _keys_by_id +from graphblas_algorithms.classes.graph import to_undirected_graph +from graphblas_algorithms.utils import not_implemented_for + +from ._cache import has_reusable_conversion +from ._utils import should_run +from .exception import NodeNotFound + +__all__ = ["bridges", "has_bridges"] + + +def _check(G): + # A parallel edge is never a bridge, and a GraphBLAS matrix would merge it into one edge. + # The dispatcher declines a multigraph before the call; a direct call refuses it here. + if G.is_multigraph(): + raise NotImplementedError("graphblas-algorithms does not support multigraphs") + + +def _check_root(G, root): + if root is not None and root not in G: + raise NodeNotFound(f"Root node {root} is not in graph") + + +def _faster_from(name, what, *floors): + """A `should_run` rule for `name`: serve a NetworkX graph past one of `floors`. + + A floor is `(nodes, edges per node)`. NetworkX is the rival, as a decline goes to it; the + cost weighed is the dispatched call's, conversion included. Converting costs about what + NetworkX's whole search does, edge for edge, so a call that must convert wins only on large + graphs with edges to spare, and on a forest (fewer edges than nodes) not at all. A call + NetworkX will give a cached conversion is served from 10000 nodes. With `root`, NetworkX + searches `root`'s component alone, whose size no rule sees before a walk, so such a call is + served on a cached conversion, or where NetworkX's own `bridges` would have the graph + converted all the same: it finds the component with the dispatched + `node_connected_component`, which this backend serves wherever it is in that name's + priority. Not a view there: NetworkX keeps a view's conversion when the graph under it + changes, and takes only the component's nodes from that call, so a stale conversion would + mislead this backend's search alone. Measured on paths, trees, random graphs, grids, + Watts-Strogatz and Barabasi-Albert graphs of 1e3 to 1e6 nodes, with NetworkX's output read + in full. + """ + least = min(nodes for nodes, _ in floors) + + def rule(bound): + G = bound["G"] + if not isinstance(G, nx.Graph): + return None + n = len(G) + converted = has_reusable_conversion(name, bound) + if converted and n >= 10000: + return None + if bound.get("root") is not None: + priority = nx.config.backend_priority + # NetworkX's views hold their graph as `_graph`. + if not hasattr(G, "_graph") and "graphblas" in priority.get( + "node_connected_component", priority.algos + ): + return None + if not converted: + return ( + "networkx searches the root's component alone, which may be small, and " + f"graphblas would first convert all {n} nodes" + ) + if converted: + return ( + f"networkx finds {what} in this graph of {n} nodes sooner than graphblas, " + "even from the conversion networkx holds" + ) + if n >= least: + # Half the neighbors listed (a self-loop counts half): G.number_of_edges() takes 20 + # times as long, about 0.2 s on a graph of 1e6 nodes. + m = sum(map(len, G._adj.values())) / 2 + if any(n >= nodes and m >= per_node * n for nodes, per_node in floors): + return None + return f"networkx finds {what} in this graph of {n} nodes sooner than graphblas converts it" + + return rule + + +_bridges_rule = _faster_from("bridges", "bridges", (100_000, 1.2)) +# NetworkX's has_bridges builds every chain but ends its scan of the edges at the first bridge. +_has_bridges_own_rule = _faster_from("has_bridges", "a bridge", (200_000, 2), (300_000, 1.2)) + + +def _has_bridges_rule(bound): + """Serve `has_bridges` wherever NetworkX's own would have the graph converted all the same. + + NetworkX's `has_bridges` takes the first of the dispatched `bridges`, which this backend + serves by `bridges`' rule wherever it is in `bridges`' priority. Elsewhere `has_bridges` + has floors of its own. + """ + priority = nx.config.backend_priority + if "graphblas" in priority.get("bridges", priority.algos) and _bridges_rule(bound) is None: + return None + return _has_bridges_own_rule(bound) + + +@not_implemented_for("directed") +@should_run(_bridges_rule) +def bridges(G, root=None): + """Yield each bridge once, as `(u, v)` with `u` before `v` in the graph's node order. + + That is NetworkX's orientation without `root`; the bridges come sorted by `u`, then by `v`, + where NetworkX's follow each node's adjacency. A directed graph raises at the call and a + `root` not in `G` at the first `next()`, as NetworkX's generator does. + """ + _check(G) + G = to_undirected_graph(G) + return _bridges(G, root) + + +def _bridges(G, root): + _check_root(G, root) + us, vs = algorithms.bridge_ids(G, root) + keys, _ = G._cacheit("keys_by_id", _keys_by_id, G) + yield from zip(keys[us].tolist(), keys[vs].tolist(), strict=True) + + +@not_implemented_for("directed") +@should_run(_has_bridges_rule) +def has_bridges(G, root=None): + _check(G) + G = to_undirected_graph(G) + _check_root(G, root) + return algorithms.has_bridges(G, root) diff --git a/graphblas_algorithms/nxapi/tests/test_bridge_set.py b/graphblas_algorithms/nxapi/tests/test_bridge_set.py new file mode 100644 index 0000000..725ed6b --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_bridge_set.py @@ -0,0 +1,622 @@ +"""bridges and has_bridges against NetworkX: the same set of edges, each once, in node order.""" + +from contextlib import contextmanager + +import graphblas as gb +import networkx as nx +import numpy as np +import pytest +from networkx.utils.backends import FAILED_TO_CONVERT + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms.bridges import _range_min_max, _spanning_forest +from graphblas_algorithms.interface import Dispatcher +from graphblas_algorithms.nxapi.bridges import _faster_from + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + + +@contextmanager +def graphblas_first(): + """NetworkX's dispatcher with this backend first, falling back to NetworkX on a decline.""" + config = nx.config + saved = list(config.backend_priority.algos), config.fallback_to_nx + config.backend_priority.algos = ["graphblas"] + config.fallback_to_nx = True + try: + yield + finally: + config.backend_priority.algos, config.fallback_to_nx = saved + + +def _with_loops(G, rng, share): + nodes = list(G) + G.add_edges_from((u, u) for u in rng.permutation(nodes)[: int(len(nodes) * share)].tolist()) + return G + + +def _shuffled(G, rng, prefix=None): + """`G` with its nodes added in a random order, and renamed to strings if `prefix`.""" + nodes = list(G) + name = (lambda u: f"{prefix}{u}") if prefix else (lambda u: u) + H = nx.Graph() + H.add_nodes_from(name(nodes[i]) for i in rng.permutation(len(nodes))) + edges = list(G.edges) + H.add_edges_from((name(edges[i][0]), name(edges[i][1])) for i in rng.permutation(len(edges))) + return H + + +def _random_graphs(): + """320 small graphs, seeded: trees, forests, cycles, grids, sparse random, barbells, ...""" + rng = np.random.default_rng(59) + + def randint(a, b): + return int(rng.integers(a, b + 1)) + + graphs = [(f"tree{i}", nx.random_labeled_tree(randint(1, 60), seed=i)) for i in range(40)] + for i in range(20): + G = nx.disjoint_union_all( + [nx.random_labeled_tree(randint(1, 15), seed=100 + 5 * i + j) for j in range(4)] + ) + G.add_nodes_from(range(len(G), len(G) + randint(0, 4))) # isolated nodes + graphs.append((f"forest{i}", _shuffled(G, rng))) + for i in range(20): + G = nx.cycle_graph(randint(3, 40)) + if i % 2: # a tail hanging off the cycle, and a chord + n = len(G) + nx.add_path(G, [0, *range(n, n + randint(1, 6))]) + G.add_edge(1, n // 2 + 1) + graphs.append((f"cycle{i}", G)) + graphs.extend((f"grid{i}", nx.grid_2d_graph(randint(1, 7), randint(1, 7))) for i in range(20)) + for i in range(80): + n = randint(2, 70) + G = nx.gnp_random_graph(n, rng.uniform(0.5, 3.0) / n, seed=1000 + i) + if i % 4 == 0: + G = _with_loops(G, rng, 0.3) + graphs.append((f"sparse{i}", _shuffled(G, rng))) + for i in range(20): + G = nx.barbell_graph(randint(3, 8), randint(0, 6)) + graphs.append((f"barbell{i}", _shuffled(G, rng))) + for i in range(30): + G = nx.gnm_random_graph(randint(1, 40), randint(0, 60), seed=2000 + i) + G = _with_loops(G, rng, [0.1, 0.5, 1.0][i % 3]) + graphs.append((f"loops{i}", G)) + for i in range(30): + n = randint(2, 50) + G = nx.gnp_random_graph(n, rng.uniform(1.0, 2.5) / n, seed=3000 + i) + graphs.append((f"strings{i}", _shuffled(G, rng, prefix=["n", "node ", "x"][i % 3]))) + for i in range(30): + parts = [nx.cycle_graph(randint(3, 6)) for _ in range(randint(1, 4))] + G = nx.disjoint_union_all(parts) + for _ in range(randint(0, 4)): # links, which are bridges until they close a cycle + G.add_edge(randint(0, len(G) - 1), randint(0, len(G) - 1)) + graphs.append((f"rings{i}", _shuffled(G, rng))) + for i in range(30): + n = randint(5, 40) + G = nx.caveman_graph(randint(1, 5), randint(1, 5)) + G = nx.disjoint_union(G, nx.gnp_random_graph(n, 1.5 / n, seed=4000 + i)) + graphs.append((f"mixed{i}", _shuffled(G, rng))) + return graphs + + +GRAPHS = _random_graphs() + + +def _check(G, root=None): + want = list(nx.bridges(G, root=root)) + got = list(nx.bridges(G, root=root, backend="graphblas")) + unordered = {frozenset(edge) for edge in got} + assert unordered == {frozenset(edge) for edge in want} + assert len(unordered) == len(got), "a bridge came twice" + place = {node: i for i, node in enumerate(G)} + keys = [(place[u], place[v]) for u, v in got] + assert all(i < j for i, j in keys), "not in node order" + assert keys == sorted(keys) + if root is None: + # NetworkX's `H.edges()` gives each edge from its end first in node order, too. + assert set(got) == set(want) + for edge in got: # the graph's own node objects, not numpy scalars + for u in edge: + assert type(u) is type(next(n for n in G if n == u)) + has = nx.has_bridges(G, root=root, backend="graphblas") + assert type(has) is bool + assert has == bool(want) == nx.has_bridges(G, root=root) + return want + + +def test_there_are_enough_graphs(): + assert len(GRAPHS) >= 300 + + +@pytest.mark.parametrize(("name", "G"), GRAPHS, ids=[name for name, _ in GRAPHS]) +def test_bridges_match_networkx(name, G): + want = _check(G) + if name.startswith("tree"): + assert len(want) == G.number_of_edges() + elif name.startswith("cycle") and int(name[5:]) % 2 == 0: + assert want == [] + + +@pytest.mark.parametrize(("name", "G"), GRAPHS[::4], ids=[name for name, _ in GRAPHS[::4]]) +def test_bridges_of_the_root_component_match_networkx(name, G): + nodes = list(G) + for i in np.random.default_rng(len(name) + len(G)).permutation(len(nodes))[:3]: + _check(G, nodes[i]) + + +def test_self_loops_are_never_bridges(): + G = nx.Graph([(0, 0), (0, 1), (1, 2), (2, 2), (3, 3)]) + assert list(nx.bridges(G, backend="graphblas")) == [(0, 1), (1, 2)] + G = nx.Graph([(0, 0)]) + assert list(nx.bridges(G, backend="graphblas")) == [] + assert nx.has_bridges(G, backend="graphblas") is False + assert nx.has_bridges(G, root=0, backend="graphblas") is False + + +def test_a_tree_edge_is_kept_by_a_cycle_below_or_beside_it(): + # 0-1 is a bridge; 1-2-3-1 is a cycle; 3-4 a bridge; 4 also closes 4-5-6-4. + G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 1), (3, 4), (4, 5), (5, 6), (6, 4)]) + assert list(nx.bridges(G, backend="graphblas")) == [(0, 1), (3, 4)] + assert list(nx.bridges(G, root=6, backend="graphblas")) == [(0, 1), (3, 4)] + + +def test_the_root_restricts_to_its_component(): + G = nx.Graph([(0, 1), (2, 3), (3, 4), (4, 2), (4, 5)]) + G.add_node(6) + assert list(nx.bridges(G, root=0, backend="graphblas")) == [(0, 1)] + assert list(nx.bridges(G, root=3, backend="graphblas")) == [(4, 5)] + assert list(nx.bridges(G, root=6, backend="graphblas")) == [] + assert nx.has_bridges(G, root=6, backend="graphblas") is False + # A root equal to a node is that node, as in a dict. + assert list(nx.bridges(G, root=0.0, backend="graphblas")) == [(0, 1)] + assert list(nx.bridges(G, root=False, backend="graphblas")) == [(0, 1)] + + +def test_a_root_searches_its_component_alone_where_a_short_walk_finds_it(monkeypatch): + """A small component alone; a deep one, or one of half the nodes, with the whole graph.""" + from graphblas_algorithms.algorithms import bridges as kernel + + searched = [] + search = kernel._bridge_ids + + def spy(n, rows, cols): + searched.append(n) + return search(n, rows, cols) + + monkeypatch.setattr(kernel, "_bridge_ids", spy) + G = nx.disjoint_union(nx.barbell_graph(4, 2), nx.path_graph(1000)) + g = ga.Graph.from_networkx(G) + assert list(nxapi.bridges(g, root=0)) == [(3, 4), (4, 5), (5, 6)] + assert searched == [10] + searched.clear() + assert list(nxapi.bridges(g, root=10)) == [(i, i + 1) for i in range(10, 1009)] + assert searched == [1010] # 999 levels: the walk is cut short + searched.clear() + assert nxapi.has_bridges(g, root=9) is True + assert searched == [10] + G = nx.disjoint_union(nx.complete_graph(30), nx.path_graph(10)) + g = ga.Graph.from_networkx(G) + searched.clear() + assert list(nxapi.bridges(g, root=0)) == [] + assert searched == [40] # 30 of 40 nodes + assert list(nxapi.bridges(g, root=35)) == [(i, i + 1) for i in range(30, 39)] + assert searched == [40, 10] + # The walk takes up to 2 * n.bit_length() levels: 22 for 2023 and 2024 nodes. + for length, want in [(23, 23), (24, 2024)]: + g = ga.Graph.from_networkx(nx.disjoint_union(nx.path_graph(length), nx.path_graph(2000))) + searched.clear() + assert nxapi.has_bridges(g, root=0) is True + assert searched == [want] + + +@pytest.mark.parametrize("n", [1, 2, 3, 200_000]) +def test_a_long_path_is_all_bridges(n): + """Deep trees: Boruvka's rounds and the tour's pointer jumping, not a step per level.""" + G = nx.path_graph(n) + got = list(nx.bridges(G, backend="graphblas")) + assert got == [(i, i + 1) for i in range(n - 1)] + G.add_edge(0, n - 1) + assert list(nx.bridges(G, backend="graphblas")) == ([(0, 1)] if n == 2 else []) + + +def test_a_star_and_its_tours(): + """A hub's arcs wrap round in its tour, here once per leaf.""" + G = nx.star_graph(300) + assert list(nx.bridges(G, backend="graphblas")) == [(0, i) for i in range(1, 301)] + G.add_edges_from((i, i + 1) for i in range(1, 299, 2)) # all but leaves 299 and 300 + assert list(nx.bridges(G, backend="graphblas")) == [(0, 299), (0, 300)] + _check(_shuffled(G, np.random.default_rng(1))) + + +def test_a_larger_sparse_graph(): + G = nx.gnm_random_graph(20_000, 24_000, seed=59) + G.add_edges_from((u, u) for u in range(0, 20_000, 7)) + assert len(_check(G)) > 1000 + _check(G, root=next(iter(nx.node_connected_component(G, 0)))) + + +def test_empty_graphs(): + for G in [nx.Graph(), nx.empty_graph(5)]: + assert list(nx.bridges(G, backend="graphblas")) == [] + assert nx.has_bridges(G, backend="graphblas") is False + + +def test_a_backend_graph_is_served_directly(): + G = nx.barbell_graph(4, 2) + g = ga.Graph.from_networkx(G) + assert list(nxapi.bridges(g)) == list(nx.bridges(G)) + assert nxapi.has_bridges(g) is True + assert list(nxapi.bridges(g, root=0)) == [(3, 4), (4, 5), (5, 6)] + + +def test_node_order_where_ids_do_not_follow_it(): + """The `union` here lists the second graph's nodes first but numbers them last.""" + G = nx.Graph([(0, 1), (1, 2)]) + H = nx.Graph([("a", "b"), ("b", "c"), ("c", "a"), ("c", "d")]) + U = nx.union(G, H, backend="graphblas") + assert list(U) == ["a", "b", "c", "d", 0, 1, 2] + assert U._key_to_id["a"] > U._key_to_id[2] + want = [("c", "d"), (0, 1), (1, 2)] + assert list(nx.bridges(U, backend="graphblas")) == want + assert list(nxapi.bridges(U)) == want + U = nx.union(H, G, backend="graphblas") + assert list(nxapi.bridges(U)) == [(0, 1), (1, 2), ("c", "d")] + + +STORAGE = ["csr", "csc", "hypercsr", "hypercsc", "bitmapr", "bitmapc"] + + +def _stored(G, fmt): + """`G` as this backend's graph, its matrix stored as `fmt`: by row or column, and so on.""" + g = ga.Graph.from_networkx(G) + A = gb.Matrix.ss.import_any(**g._A.ss.export(fmt)) + return ga.Graph(A, key_to_id=dict(g._key_to_id)) + + +@pytest.mark.parametrize("fmt", STORAGE) +def test_the_answer_does_not_depend_on_how_the_matrix_is_stored(fmt): + """`to_coo` lists a matrix's entries in the order the matrix keeps them, by row or column.""" + graphs = [nx.barbell_graph(5, 3), nx.grid_2d_graph(4, 4), nx.ladder_graph(6)] + graphs += [G for _, G in GRAPHS[::10]] + for G in graphs: + g = _stored(G, fmt) + assert g._A.ss.format == fmt + nodes = list(G) + for root in [None, nodes[0], nodes[-1]] if nodes else [None]: + want = {frozenset(edge) for edge in nx.bridges(G, root=root)} + got = list(nxapi.bridges(g, root=root)) + assert {frozenset(edge) for edge in got} == want + assert len(got) == len(want) + assert nxapi.has_bridges(g, root=root) is bool(want) + + +# A backend graph, and NetworkX graphs on the automatic path + + +@pytest.fixture +def conversions(monkeypatch): + """The calls NetworkX makes to convert a graph for this backend.""" + calls = [] + convert = Dispatcher.convert_from_nx + + def spy(*args, **kwargs): + calls.append(args[0]) + return convert(*args, **kwargs) + + monkeypatch.setattr(Dispatcher, "convert_from_nx", staticmethod(spy)) + return calls + + +def _same(got, want): + """The same outcome: an error, a value, or the same bridges in any order.""" + if want[0] == "items" and got[0] == "items": + return len(got[1]) == len(want[1]) and set(got[1]) == set(want[1]) + return got == want + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +def test_a_backend_graph_is_served_through_networkx_without_a_conversion(conversions, name): + G = nx.barbell_graph(4, 2) + G.add_edge(20, 21) + g = ga.Graph.from_networkx(G) + f = getattr(nx, name) + for root in [None, 0, 20]: + want = _outcome(lambda root=root: f(G, root=root, backend="networkx")) + assert _same(_outcome(lambda root=root: f(g, root=root)), want) + with graphblas_first(): + assert _same(_outcome(lambda root=root: f(g, root=root)), want) + assert conversions == [] + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +def test_should_run_leaves_small_or_sparse_networkx_graphs_to_networkx(conversions, name): + f = getattr(nx, name) + for G in [nx.path_graph(1000), nx.complete_graph(100), nx.grid_2d_graph(100, 100)]: + reason = Dispatcher.should_run(name, (G,), {}) + assert isinstance(reason, str) + assert reason.startswith("networkx finds") + with graphblas_first(): + assert _same(_outcome(lambda G=G: f(G)), _outcome(lambda G=G: f(G, backend="networkx"))) + assert conversions == [] + # A backend graph has nothing to convert, so nothing to weigh. + assert Dispatcher.should_run(name, (ga.Graph.from_networkx(nx.path_graph(5)),), {}) is True + + +def test_should_run_serves_a_large_graph_of_edges_to_spare_and_weighs_each_name(): + """A 400 x 400 grid: bridges from 1e5 nodes, has_bridges (which NetworkX ends early) 2e5.""" + G = nx.grid_2d_graph(400, 400) + assert Dispatcher.should_run("bridges", (G,), {}) is True + assert isinstance(Dispatcher.should_run("has_bridges", (G,), {}), str) + G = nx.path_graph(250_000) + for name in ["bridges", "has_bridges"]: + assert isinstance(Dispatcher.should_run(name, (G,), {}), str) + + +def test_should_run_serves_has_bridges_where_networkx_would_convert_for_its_bridges(conversions): + """NetworkX's has_bridges takes the first of the dispatched bridges: declined, it converts.""" + G = _chorded_cycle(150_000, 4) # 1.25 edges per node: bridges' floor, not has_bridges' + assert isinstance(Dispatcher.should_run("has_bridges", (G,), {}), str) + with graphblas_first(): + assert nx.has_bridges(G, backend="networkx") is False + assert len(conversions) == 1 + G = _chorded_cycle(150_000, 4) + with graphblas_first(): + assert Dispatcher.should_run("bridges", (G,), {}) is True + assert Dispatcher.should_run("has_bridges", (G,), {}) is True + assert nx.has_bridges(G) is False + assert len(conversions) == 2 + small = nx.path_graph(1000) + with graphblas_first(): + assert isinstance(Dispatcher.should_run("has_bridges", (small,), {}), str) + assert nx.has_bridges(small) is True + assert len(conversions) == 2 + + +def _chorded_cycle(n, every): + """A cycle of `n` nodes with a chord from every `every`-th node to the next but one.""" + G = nx.cycle_graph(n) + G.add_edges_from((u, (u + 2) % n) for u in range(0, n, every)) + return G + + +def test_should_run_weighs_has_bridges_on_two_floors(): + """has_bridges from 200000 nodes at 2 edges per node, or 300000 at 1.2; bridges from 100000.""" + G = nx.circulant_graph(200_000, [1, 2]) # 2 edges per node + assert Dispatcher.should_run("has_bridges", (G,), {}) is True + G = _chorded_cycle(300_000, 4) # 1.25 edges per node + assert Dispatcher.should_run("has_bridges", (G,), {}) is True + G = _chorded_cycle(250_000, 4) + assert isinstance(Dispatcher.should_run("has_bridges", (G,), {}), str) + assert Dispatcher.should_run("bridges", (G,), {}) is True + G = _chorded_cycle(250_000, 6) # 1.17 edges per node + assert isinstance(Dispatcher.should_run("bridges", (G,), {}), str) + + +def test_should_run_rule_floors(): + rule = _faster_from("bridges", "bridges", (50, 2), (80, 1.5)) + assert rule({"G": nx.path_graph(100)}) is not None # a forest + assert rule({"G": nx.circulant_graph(40, [1, 2])}) is not None # too few nodes + assert rule({"G": nx.circulant_graph(60, [1, 2])}) is None # 2 edges per node from 50 + G = _chorded_cycle(60, 2) # 90 edges, 1.5 per node, which serves from 80 nodes only + assert rule({"G": G}) is not None + G = _chorded_cycle(80, 2) # 120 edges + assert rule({"G": G}) is None + G.remove_edge(0, 2) + assert rule({"G": G}) is not None + G.add_edge(0, 0) # a self-loop is half an edge here, as each end of an edge is + assert rule({"G": G}) is not None + G.add_edge(5, 5) + assert rule({"G": G}) is None + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +def test_should_run_serves_a_graph_networkx_already_converted(conversions, name): + f = getattr(nx, name) + G = nx.path_graph(10_000) + assert isinstance(Dispatcher.should_run(name, (G,), {}), str) + f(G, backend="graphblas") + assert len(conversions) == 1 + assert Dispatcher.should_run(name, (G,), {}) is True + with graphblas_first(): + assert _same(_outcome(lambda: f(G)), _outcome(lambda: f(G, backend="networkx"))) + assert len(conversions) == 1 # served from NetworkX's cache + saved = nx.config.cache_converted_graphs + nx.config.cache_converted_graphs = False + try: + assert isinstance(Dispatcher.should_run(name, (G,), {}), str) + finally: + nx.config.cache_converted_graphs = saved + G.add_edge(0, 9999) # NetworkX drops its conversions of a graph that changes + assert isinstance(Dispatcher.should_run(name, (G,), {}), str) + # A conversion NetworkX could not make is no conversion. + G.__networkx_cache__.setdefault("backends", {})["graphblas"] = { + (False, False): FAILED_TO_CONVERT + } + assert isinstance(Dispatcher.should_run(name, (G,), {}), str) + small = nx.path_graph(1000) # cached or not, NetworkX is the faster below 10000 nodes + assert "converts it" in Dispatcher.should_run(name, (small,), {}) + f(small, backend="graphblas") + assert "conversion networkx holds" in Dispatcher.should_run(name, (small,), {}) + # NetworkX keeps a view's conversions when the graph under it changes, so none is reused. + H = nx.path_graph(20_000) + V = H.subgraph(range(15_000)) + f(V, backend="graphblas") + assert isinstance(Dispatcher.should_run(name, (V,), {}), str) + + +@contextmanager +def graphblas_first_but_for(name): + """`graphblas_first`, with NetworkX alone in `name`'s priority.""" + with graphblas_first(): + nx.config.backend_priority[name] = [] + try: + yield + finally: + del nx.config.backend_priority[name] + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +def test_should_run_serves_a_root_on_a_cached_conversion(conversions, name): + """NetworkX searches the root's component alone, which may be small.""" + f = getattr(nx, name) + G = nx.disjoint_union(nx.grid_2d_graph(400, 400), nx.path_graph(5)) + root = len(G) - 1 + want = _outcome(lambda: f(G, root=root, backend="networkx")) + with graphblas_first_but_for("node_connected_component"): + reason = Dispatcher.should_run(name, (G,), {"root": root}) + assert "the root's component alone" in reason + assert _same(_outcome(lambda: f(G, root=root)), want) + assert conversions == [] + f(G, backend="graphblas") + assert len(conversions) == 1 + with graphblas_first_but_for("node_connected_component"): + assert Dispatcher.should_run(name, (G,), {"root": root}) is True + assert _same(_outcome(lambda: f(G, root=root)), want) + assert len(conversions) == 1 + small = nx.path_graph(1000) + f(small, backend="graphblas") + with graphblas_first_but_for("node_connected_component"): + assert "conversion networkx holds" in Dispatcher.should_run(name, (small,), {"root": 0}) + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +def test_should_run_serves_a_root_where_networkx_would_convert_for_its_component(conversions, name): + """Declined, NetworkX's bridges converts for its dispatched node_connected_component.""" + f = getattr(nx, name) + G = nx.path_graph(1000) + with graphblas_first(): + want = _outcome(lambda: f(G, root=3, backend="networkx")) + assert len(conversions) == 1 + assert getattr(Dispatcher.node_connected_component, "_should_run", None) is None + G = nx.path_graph(1000) + with graphblas_first(): + assert Dispatcher.should_run(name, (G,), {"root": 3}) is True + assert _same(_outcome(lambda: f(G, root=3)), want) + assert len(conversions) == 2 + assert isinstance(Dispatcher.should_run(name, (G,), {"root": 3}), str) # NetworkX's priority + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +def test_should_run_leaves_a_root_on_a_view_to_networkx(name): + """NetworkX keeps a view's conversion when the graph under it changes. + + Its own `bridges` takes only the component's nodes from `node_connected_component`, so a + stale conversion misleads this backend's search alone. + """ + f = getattr(nx, name) + H = nx.disjoint_union(nx.cycle_graph(30), nx.path_graph(5)) + V = H.subgraph(range(32)) # a view: the cycle and two nodes of the path + f(V, backend="graphblas") # NetworkX now holds a conversion of the view + H.remove_edge(0, 29) # the cycle is a path now, every edge a bridge + want = _outcome(lambda: f(V, root=0, backend="networkx")) + stale = _outcome(lambda: f(V, root=0, backend="graphblas")) + assert not _same(stale, want) # the view's conversion is stale + with graphblas_first(): + assert "the root's component alone" in Dispatcher.should_run(name, (V,), {"root": 0}) + assert _same(_outcome(lambda: f(V, root=0)), want) + + +# Errors, at the call or at the first next(), as in NetworkX + + +def _outcome(f): + try: + result = f() + except Exception as exc: + return "call", type(exc), str(exc) + if isinstance(result, bool): + return "value", result + try: + return "items", list(result) + except Exception as exc: + return "next", type(exc), str(exc) + + +@pytest.mark.parametrize("name", ["bridges", "has_bridges"]) +@pytest.mark.parametrize( + "case", + ["directed", "absent root", "unhashable root", "empty with root", "isolated root"], +) +def test_errors_match_networkx(name, case): + G = nx.Graph([(0, 1), (1, 2)]) + root = None + if case == "directed": + G = nx.DiGraph([(0, 1)]) + elif case == "absent root": + root = 9 + elif case == "unhashable root": + root = [9] + elif case == "empty with root": + G, root = nx.Graph(), 0 + else: + G.add_node(5) + root = 5 + f = getattr(nx, name) + want = _outcome(lambda: f(G, root=root)) + assert _outcome(lambda: f(G, root=root, backend="graphblas")) == want + with graphblas_first(): + assert _outcome(lambda: f(G, root=root)) == want + direct = getattr(nxapi, name) + assert _outcome(lambda: direct(G, root=root)) == want + if not G.is_directed(): + g = ga.Graph.from_networkx(G) + else: + g = ga.DiGraph.from_networkx(G) + assert _outcome(lambda: direct(g, root=root)) == want + if case == "directed": + assert want[:2] == ("call", nx.NetworkXNotImplemented) + elif case != "isolated root": + assert want[:2] == (("next" if name == "bridges" else "call"), nx.NodeNotFound) + + +def test_a_multigraph_is_left_to_networkx(): + """A parallel edge is never a bridge; the matrix would merge it, so the backend declines.""" + G = nx.MultiGraph([(0, 1), (0, 1), (1, 2), (2, 2)]) + assert list(nx.bridges(G)) == [(1, 2)] + for name in ["bridges", "has_bridges"]: + f = getattr(nx, name) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + f(G, backend="graphblas") + with graphblas_first(): + assert _outcome(lambda f=f: f(G)) == _outcome(lambda f=f: f(G, backend="networkx")) + # A direct call refuses at the call, as the dispatcher declines before it. + with pytest.raises(NotImplementedError, match="does not support multigraphs"): + getattr(nxapi, name)(G) + + +# The kernel's parts + + +def test_range_min_max_matches_slicing(): + rng = np.random.default_rng(59) + for n in [1, 2, 3, 5, 8, 31, 32, 33, 100, 1000]: + low = rng.integers(-50, 50, n) + high = rng.integers(-50, 50, n) + first = rng.integers(0, n, 300) + span = 1 + (rng.random(300) * (n - first)).astype(int) + span[:4] = n - first[:4] # to the end + least, greatest = _range_min_max(low, high, first, span) + for a, s, lo, hi in zip(first, span, least, greatest, strict=True): + assert lo == low[a : a + s].min() + assert hi == high[a : a + s].max() + empty = np.empty(0, int) + least, greatest = _range_min_max(np.arange(3), np.arange(3), empty, empty) + assert len(least) == len(greatest) == 0 + + +@pytest.mark.parametrize("seed", range(20)) +def test_the_spanning_forest_spans_and_is_a_forest(seed): + G = nx.gnm_random_graph(60, seed * 4, seed=seed) + edges = np.array(list(G.edges), dtype=np.intp).reshape(-1, 2) + us, vs = edges[:, 0], edges[:, 1] + in_forest, label = _spanning_forest(len(G), us, vs) + F = nx.Graph() + F.add_nodes_from(G) + F.add_edges_from(zip(us[in_forest].tolist(), vs[in_forest].tolist(), strict=True)) + assert nx.is_forest(F) + assert nx.number_connected_components(F) == nx.number_connected_components(G) + for component in nx.connected_components(G): + assert len({label[u] for u in component}) == 1 + assert label[next(iter(component))] in component + assert len(set(label.tolist())) == nx.number_connected_components(G) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..36459a4 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -87,6 +87,7 @@ def call_args(kind, args): "bfs_layers": ("undirected", ([0],)), "bfs_successors": ("undirected", (0,)), "boundary_expansion": ("undirected", ([0, 1],)), + "bridges": ("undirected", ()), # The tournament is the kind without an isolated node: eccentricity, and the names read # off it, raise on a graph in pieces. "center": ("tournament", ()), @@ -132,6 +133,7 @@ def call_args(kind, args): "gutman_index": ("undirected", ()), "harmonic_centrality": ("undirected", ()), "harmonic_diameter": ("undirected", ()), + "has_bridges": ("undirected", ()), "has_path": ("undirected", (0, 2)), "hits": ("directed", ()), "hyper_wiener_index": ("undirected", ()), diff --git a/scripts/maketree.py b/scripts/maketree.py index b9b91f7..170ea10 100755 --- a/scripts/maketree.py +++ b/scripts/maketree.py @@ -119,11 +119,18 @@ def splice(path, text, begin, end): path.write_text(old[:start] + text + old[stop:], encoding="utf-8") -# Dispatched functions that are only available from `nxapi` -SHORTPATH = { - "overall_reciprocity", - "reciprocity", -} +def hidden_modules(): + """The `nxapi` modules that a function of the same name hides, such as `reciprocity`. + + Their functions are reached as `nxapi.`, since `nxapi.` is the function. + """ + from graphblas_algorithms import nxapi + + return { + name + for name, val in vars(nxapi).items() + if not inspect.ismodule(val) and f"{nxapi.__name__}.{name}" in sys.modules + } def main( @@ -171,6 +178,7 @@ def addtree(path): text = s.read() splice(readme_path, f"\n```\n{text}```\n\n", README_BEGIN, README_END) # Step 2: add to interface.py + hidden = hidden_modules() lines = [] prev_mod = None for fullname in fullnames: @@ -186,7 +194,7 @@ def addtree(path): name = name.split(")")[0] else: name = subpath.rsplit(".", 1)[-1] - if name in SHORTPATH: + if mod in hidden: subpath = subpath.rsplit(".", 1)[-1] lines.append(f" {name} = nxapi.{subpath}") else: