diff --git a/README.md b/README.md index 8c01878..25590d1 100644 --- a/README.md +++ b/README.md @@ -172,6 +172,11 @@ graphblas_algorithms.nxapi │ ├── overlapping_modularity │ └── partition_quality ├── components +│ ├── biconnected +│ │ ├── articulation_points +│ │ ├── biconnected_component_edges +│ │ ├── biconnected_components +│ │ └── is_biconnected │ ├── connected │ │ ├── connected_components │ │ ├── is_connected diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 32e875f..881c629 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -34,6 +34,7 @@ def get_info(): "all_pairs_bellman_ford_path_length", "all_pairs_shortest_path_length", "ancestors", + "articulation_points", "average_clustering", "average_shortest_path_length", "bellman_ford_path", @@ -44,6 +45,8 @@ def get_info(): "bfs_edges", "bfs_layers", "bfs_successors", + "biconnected_component_edges", + "biconnected_components", "boundary_expansion", "bridges", "center", @@ -96,6 +99,7 @@ def get_info(): "intersection", "intra_community_edges", "is_arborescence", + "is_biconnected", "is_branching", "is_connected", "is_cover", @@ -193,6 +197,7 @@ def get_info(): _additional_docs = { # BEGIN: additional_docs "all_pairs_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", + "articulation_points": "Each cut node once, in node order, where NetworkX's follow its search.\nA NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.", "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".', "bellman_ford_path": "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.", "bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", @@ -200,6 +205,8 @@ 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.", + "biconnected_component_edges": "Each block's edges come in an order and an orientation of their own, and a self-loop\nin one block of its node, where NetworkX lists it in the block its search meets it by,\nor not at all at a node its search starts from, so on the automatic path a NetworkX\ngraph with a self-loop is left to NetworkX.\nA NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.", + "biconnected_components": "The blocks come in an order of their own.\nA NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.", "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".', @@ -221,6 +228,7 @@ def get_info(): "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.", + "is_biconnected": "A NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.", "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.", "k_corona": "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_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.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index d881728..eee96be 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -93,6 +93,12 @@ + _PATH_OVERFLOW ) +_BLOCKS_AUTO = ( + "A NetworkX graph that would have to be converted is left to NetworkX: with the conversion\n" + "counted the wins were small, and no floor of nodes and edges per node kept out the losses\n" + "on more than one kind of graph. One NetworkX has converted already is served from 10000\n" + "nodes. A backend graph is always served." +) _CORE_SUBGRAPH = ( "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX." ) @@ -108,6 +114,9 @@ ) _ADDITIONAL_DOCS = { "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, + "articulation_points": ( + "Each cut node once, in node order, where NetworkX's follow its search.\n" + _BLOCKS_AUTO + ), "average_shortest_path_length": ( 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n' 'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n' @@ -129,6 +138,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." ), + "biconnected_component_edges": ( + "Each block's edges come in an order and an orientation of their own, and a self-loop\n" + "in one block of its node, where NetworkX lists it in the block its search meets it by,\n" + "or not at all at a node its search starts from, so on the automatic path a NetworkX\n" + "graph with a self-loop is left to NetworkX.\n" + _BLOCKS_AUTO + ), + "biconnected_components": "The blocks come in an order of their own.\n" + _BLOCKS_AUTO, "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" @@ -183,6 +199,7 @@ 'iteration does not converge. `method="svd"` is left to NetworkX.' ), "hyper_wiener_index": _LENGTH_SUM_OVERFLOW, + "is_biconnected": _BLOCKS_AUTO, "k_core": _CORE_SUBGRAPH, "k_corona": _CORE_SUBGRAPH, "k_crust": _CORE_SUBGRAPH, diff --git a/graphblas_algorithms/algorithms/bridges.py b/graphblas_algorithms/algorithms/bridges.py index c1b04d7..4359802 100644 --- a/graphblas_algorithms/algorithms/bridges.py +++ b/graphblas_algorithms/algorithms/bridges.py @@ -8,6 +8,8 @@ search takes a step per level, and a path graph has as many levels as nodes. """ +from collections import namedtuple + import numpy as np from graphblas import Vector, replace from graphblas.semiring import any_pair @@ -109,11 +111,19 @@ def _entries_by_row(A): return rows, cols -def _bridge_ids(n, rows, cols): - """The bridges as `(parents, children)` of a spanning forest, and each node's tree label. +_Forest = namedtuple("_Forest", "label parent pre size children least greatest off_u off_v") + + +def _forest_numbers(n, rows, cols): + """A spanning forest in preorder, and what each subtree reaches. 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. + each row's entries together, as `_entries_by_row` gives them. By node id: `label`, the + node's tree; `parent`, -1 at a root; `pre`, the preorder number, -1 in a tree of one node; + and `size`, the number of nodes in the subtree. `children` are the nodes below the forest's + edges, and `least` and `greatest`, by child, the least and greatest numbers that the + child's subtree reaches by an edge other than the child's edge up. `off_u` and `off_v` are + the edges off the forest, with `off_u < off_v`. """ upper = rows < cols us = rows[upper] @@ -128,6 +138,7 @@ def _bridge_ids(n, rows, cols): # 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] + size[roots] = tree_size arcs_through = np.cumsum(2 * (tree_size - 1)) tree_of = np.empty(n, np.intp) tree_of[roots] = np.arange(len(roots)) @@ -155,8 +166,20 @@ def _bridge_ids(n, rows, cols): 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 + return _Forest( + label, parent, pre, size, children, least, greatest, us[~in_forest], vs[~in_forest] + ) + + +def _bridge_ids(n, rows, cols): + """The bridges as `(parents, children)` of a spanning forest, and each node's tree label. + + The graph is as `_forest_numbers` takes it. + """ + f = _forest_numbers(n, rows, cols) + first = f.pre[f.children] + is_bridge = (f.least >= first) & (f.greatest < first + f.size[f.children]) + return f.parent[f.children[is_bridge]], f.children[is_bridge], f.label def _range_min_max(low, high, first, span): diff --git a/graphblas_algorithms/algorithms/components/__init__.py b/graphblas_algorithms/algorithms/components/__init__.py index bb0aea6..1b28e83 100644 --- a/graphblas_algorithms/algorithms/components/__init__.py +++ b/graphblas_algorithms/algorithms/components/__init__.py @@ -1,2 +1,3 @@ +from .biconnected import * from .connected import * from .weakly_connected import * diff --git a/graphblas_algorithms/algorithms/components/biconnected.py b/graphblas_algorithms/algorithms/components/biconnected.py new file mode 100644 index 0000000..9de1ce0 --- /dev/null +++ b/graphblas_algorithms/algorithms/components/biconnected.py @@ -0,0 +1,133 @@ +"""Blocks (biconnected components) and cut nodes by Tarjan and Vishkin's method. + +With a spanning forest numbered in preorder, as `bridges` numbers it, the blocks are the +connected components of a graph on the forest's edges, each named by its lower end, that joins +1. the edges above `a` and `b`, for each edge `a`-`b` off the forest whose ends are not one the + other's ancestor; and +2. the edges above `v` and above its child `w`, when `w`'s subtree reaches a node outside `v`'s + by an edge other than its own forest edges (`v` not a tree's root). +An edge off the forest lies in the block of the forest edge above its end later in preorder, and +a node is a cut node iff its forest edges lie in two blocks or more. Every step is a numpy pass, +and how many there are grows with log n, as for `bridges`. +""" + +import numpy as np +from graphblas import Matrix + +__all__ = ["articulation_ids", "block_edge_ids", "block_node_ids", "is_biconnected"] + + +def _forest(G): + # `bridges` imports this package, so its forest is imported when first needed. + from ..bridges import _entries_by_row, _forest_numbers + + return _forest_numbers(len(G), *_entries_by_row(G.get_property("offdiag"))) + + +def _blocks(G, f=None): + """`(f, block, later)`: the forest's numbers, and blocks named by node. + + `block[w]` is the block of the forest edge above `w`, and an edge off the forest lies in the + block of the forest edge above its end `later`. + """ + from ..bridges import _spanning_forest + + if f is None: + f = _forest(G) + pre, size, parent, children = f.pre, f.size, f.parent, f.children + v = parent[children] + inner = parent[v] >= 0 + w2 = children[inner] + v2 = v[inner] + out = (f.least[inner] < pre[v2]) | (f.greatest[inner] >= pre[v2] + size[v2]) + a, b = f.off_u, f.off_v + a_later = pre[a] > pre[b] + later = np.where(a_later, a, b) + earlier = np.where(a_later, b, a) + unrelated = pre[earlier] + size[earlier] <= pre[later] + _, block = _spanning_forest( + len(parent), + np.concatenate([w2[out], earlier[unrelated]]), + np.concatenate([v2[out], later[unrelated]]), + ) + return f, block, later + + +def articulation_ids(G): + """The cut nodes' ids, in id order.""" + f, block, _ = _blocks(G) + children = f.children + p = f.parent[children] + nonroot = f.parent[p] >= 0 + cut = np.zeros(len(f.parent), bool) + cut[p[nonroot & (block[children] != block[p])]] = True + # A root is a cut node when its children's edges lie in two blocks or more: when one of + # them is not in the block of the child written last. + roots = p[~nonroot] + child_blocks = block[children[~nonroot]] + some = np.empty(len(cut), block.dtype) + some[roots] = child_blocks + cut[roots[child_blocks != some[roots]]] = True + return np.flatnonzero(cut) + + +def _grouped(rows, cols, nrows, ncols): + """`cols` grouped by `rows`, each group once and in order, and where each group starts. + + A pair given twice is kept once. GraphBLAS groups them as it builds a matrix, far faster + than numpy sorts them (0.39 s by `np.unique` against 0.02 s on a random tree of 1e6 nodes). + """ + M = Matrix.from_coo(rows, cols, True, nrows=nrows, ncols=ncols) + indptr, cols, _ = M.to_csr() + indptr = indptr.astype(np.intp) + starts = indptr[:-1][indptr[1:] > indptr[:-1]] + return cols.astype(np.intp), np.r_[starts, indptr[-1]] + + +def block_node_ids(G): + """`(nodes, starts)`: block `i` is `nodes[starts[i]:starts[i + 1]]`, each id once.""" + f, block, _ = _blocks(G) + children = f.children + n = len(f.parent) + b = block[children] + # A block's nodes are the ends of its forest edges: their lower ends, and the top one's parent. + return _grouped(np.r_[b, b], np.r_[children, f.parent[children]], n, n) + + +def block_edge_ids(G): + """`(us, vs, starts)`: block `i`'s edges are the pairs `us[s:e]`, `vs[s:e]` of its run `s:e`. + + The forest's edges, those off it, and each self-loop once, in a block of its node: the block + of its forest edge up, or at a root, of one of its forest edges down. A self-loop at a node + with no other edge is in no block. + """ + f, block, later = _blocks(G) + children = f.children + parent = f.parent + loops = G.get_property("diag").to_coo(values=False)[0].astype(np.intp) + root_block = np.full(len(parent), -1) + root_block[parent[children]] = block[children] + loop_block = np.where(parent[loops] >= 0, block[loops], root_block[loops]) + kept = loop_block >= 0 + loops = loops[kept] + us = np.concatenate([parent[children], f.off_u, loops]) + vs = np.concatenate([children, f.off_v, loops]) + b = np.concatenate([block[children], block[later], loop_block[kept]]) + edges, starts = _grouped(b, np.arange(len(b)), len(parent), len(b)) + return us[edges], vs[edges], starts + + +def is_biconnected(G): + """Whether `G` has two nodes or more, all in one block, as NetworkX defines it.""" + n = len(G) + if n < 2: + return False + degrees = G.get_property("degrees-") + # A node of no edge, or among three nodes or more of one edge, leaves it in two blocks or none. + if degrees.nvals < n or (n > 2 and degrees.reduce("min").get() < 2): + return False + f = _forest(G) + if len(f.children) < n - 1: # not connected + return False + _, block, _ = _blocks(G, f) + return bool((block[f.children] == block[f.children[0]]).all()) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 19f9b69..94c7589 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -276,6 +276,10 @@ class Dispatcher: mod = nxapi.components # ==================== + articulation_points = mod.biconnected.articulation_points + biconnected_component_edges = mod.biconnected.biconnected_component_edges + biconnected_components = mod.biconnected.biconnected_components + is_biconnected = mod.biconnected.is_biconnected connected_components = mod.connected.connected_components is_connected = mod.connected.is_connected node_connected_component = mod.connected.node_connected_component diff --git a/graphblas_algorithms/nxapi/bridges.py b/graphblas_algorithms/nxapi/bridges.py index a76d3d7..ced6583 100644 --- a/graphblas_algorithms/nxapi/bridges.py +++ b/graphblas_algorithms/nxapi/bridges.py @@ -24,27 +24,36 @@ def _check_root(G, root): raise NodeNotFound(f"Root node {root} is not in graph") -def _faster_from(name, what, *floors): +def _faster_from(name, what, *floors, unless=None): """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 + graphs with edges to spare, and on a forest (fewer edges than nodes) not at all; with no + floors, never. A call NetworkX will give a cached conversion is served from 10000 nodes. + `unless(G)`, if given, is the reason to leave a NetworkX graph the rule would serve to + NetworkX all the same, or None. 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. + mislead this backend's search alone. Measured for each name on paths, trees, random graphs, + grids, Watts-Strogatz and Barabasi-Albert graphs of 1e3 to 1e6 nodes (for the blocks, also + cycles, barbells and a dense random graph), with NetworkX's output read in full. """ - least = min(nodes for nodes, _ in floors) + least = min((nodes for nodes, _ in floors), default=None) def rule(bound): + reason = weigh(bound) + G = bound["G"] + if reason is None and unless is not None and isinstance(G, nx.Graph): + return unless(G) + return reason + + def weigh(bound): G = bound["G"] if not isinstance(G, nx.Graph): return None @@ -69,7 +78,7 @@ def rule(bound): f"networkx finds {what} in this graph of {n} nodes sooner than graphblas, " "even from the conversion networkx holds" ) - if n >= least: + if least is not None and 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 diff --git a/graphblas_algorithms/nxapi/components/__init__.py b/graphblas_algorithms/nxapi/components/__init__.py index bb0aea6..1b28e83 100644 --- a/graphblas_algorithms/nxapi/components/__init__.py +++ b/graphblas_algorithms/nxapi/components/__init__.py @@ -1,2 +1,3 @@ +from .biconnected import * from .connected import * from .weakly_connected import * diff --git a/graphblas_algorithms/nxapi/components/biconnected.py b/graphblas_algorithms/nxapi/components/biconnected.py new file mode 100644 index 0000000..a92968e --- /dev/null +++ b/graphblas_algorithms/nxapi/components/biconnected.py @@ -0,0 +1,105 @@ +"""Blocks and cut nodes, as NetworkX's generators give them. + +On the automatic path each name is left to NetworkX wherever a NetworkX graph would have to be +converted: with the conversion counted the wins were small, and no floor of nodes and edges per +node kept out the losses on more than one kind of graph (Watts-Strogatz graphs lost where grids +of their size won). A call NetworkX will give a cached conversion is served from 10000 nodes, +as `_faster_from` serves any name. +""" + +from itertools import pairwise + +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 remembered +from .._utils import should_run +from ..bridges import _check, _faster_from + +__all__ = [ + "articulation_points", + "biconnected_component_edges", + "biconnected_components", + "is_biconnected", +] + + +def _a_self_loop(G): + """The reason to leave a NetworkX graph with a self-loop to NetworkX, or None. + + NetworkX lists a self-loop where its search meets it, and this backend in a block of its own + choosing: both valid, but on the automatic path a call gets NetworkX's. The scan reads every + node of a graph without one, so it is read once per version of the graph. + """ + if remembered(G, "a self-loop", _has_a_self_loop): + return "networkx lists a self-loop in a block of its search's choosing" + return None + + +def _has_a_self_loop(G): + return any(u in nbrs for u, nbrs in G._adj.items()) + + +@not_implemented_for("directed") +@should_run(_faster_from("is_biconnected", "whether it is biconnected")) +def is_biconnected(G): + _check(G) + return algorithms.is_biconnected(to_undirected_graph(G)) + + +@not_implemented_for("directed") +@should_run(_faster_from("biconnected_component_edges", "the blocks' edges", unless=_a_self_loop)) +def biconnected_component_edges(G): + """Yield each block's edges as a list of pairs, a self-loop in one block of its node. + + NetworkX lists a self-loop in the block of its node's edge up in its search, or not at all + at a node its search starts from. A directed graph raises at the call, and the graph is read + at the first `next()`, as in NetworkX's generators. + """ + _check(G) + + def block_edges(): + H = to_undirected_graph(G) + us, vs, starts = algorithms.block_edge_ids(H) + keys, _ = H._cacheit("keys_by_id", _keys_by_id, H) + edges = list(zip(keys[us].tolist(), keys[vs].tolist(), strict=True)) + for start, end in pairwise(starts.tolist()): + yield edges[start:end] + + return block_edges() + + +@not_implemented_for("directed") +@should_run(_faster_from("biconnected_components", "the blocks")) +def biconnected_components(G): + """Yield each block's nodes as a set.""" + _check(G) + + def blocks(): + H = to_undirected_graph(G) + nodes, starts = algorithms.block_node_ids(H) + keys, _ = H._cacheit("keys_by_id", _keys_by_id, H) + nodes = keys[nodes].tolist() + for start, end in pairwise(starts.tolist()): + yield set(nodes[start:end]) + + return blocks() + + +@not_implemented_for("directed") +@should_run(_faster_from("articulation_points", "the cut nodes")) +def articulation_points(G): + """Yield each cut node once, in the graph's node order, where NetworkX's follow its search.""" + _check(G) + + def cut_nodes(): + H = to_undirected_graph(G) + ids = algorithms.articulation_ids(H) + keys, places = H._cacheit("keys_by_id", _keys_by_id, H) + if places is not None: + ids = ids[places[ids].argsort(kind="stable")] + yield from keys[ids].tolist() + + return cut_nodes() diff --git a/graphblas_algorithms/nxapi/tests/test_biconnected.py b/graphblas_algorithms/nxapi/tests/test_biconnected.py new file mode 100644 index 0000000..e072590 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_biconnected.py @@ -0,0 +1,384 @@ +"""Blocks and cut nodes against NetworkX: the same sets, as NetworkX's own tests compare them.""" + +from itertools import pairwise + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.interface import Dispatcher + +from ..components.biconnected import _a_self_loop +from .test_bridge_set import GRAPHS, STORAGE, _outcome, _shuffled, _stored, graphblas_first + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +NAMES = [ + "articulation_points", + "biconnected_component_edges", + "biconnected_components", + "is_biconnected", +] + + +def _node_type(G, u): + return type(next(v for v in G if v == u)) + + +def _edge_sets(components): + return {frozenset(frozenset(edge) for edge in block) for block in components} + + +def _without_loops(components): + return [[edge for edge in block if edge[0] != edge[1]] for block in components] + + +def _check(G): + place = {node: i for i, node in enumerate(G)} + # Cut nodes: NetworkX's set, each once, in node order, as the graph's own objects. + want = list(nx.articulation_points(G)) + got = list(nx.articulation_points(G, backend="graphblas")) + assert set(got) == set(want) + assert len(got) == len(set(got)) == len(want) + assert [place[u] for u in got] == sorted(place[u] for u in got) + assert all(type(u) is _node_type(G, u) for u in got) + # Blocks as sets of nodes, each block once. + want = list(nx.biconnected_components(G)) + got = list(nx.biconnected_components(G, backend="graphblas")) + assert all(type(block) is set for block in got) + assert {frozenset(block) for block in got} == {frozenset(block) for block in want} + assert len(got) == len(want) + assert all(type(u) is _node_type(G, u) for block in got for u in block) + # Blocks as lists of edges: every edge of the graph once, a self-loop at a node with other + # edges in one block of its node, where NetworkX's placing follows its search. + want = list(nx.biconnected_component_edges(G)) + got = list(nx.biconnected_component_edges(G, backend="graphblas")) + assert all(type(block) is list for block in got) + assert _edge_sets(_without_loops(got)) == _edge_sets(_without_loops(want)) + edges = [frozenset(edge) for block in got for edge in block] + assert len(edges) == len(set(edges)) + loops = {u for u, v in G.edges if u == v and len(G[u]) > 1} + assert {frozenset(edge) for edge in G.edges if edge[0] != edge[1] or edge[0] in loops} == set( + edges + ) + for block in got: + nodes = {u for edge in block if edge[0] != edge[1] for u in edge} + assert all(u in nodes for u, v in block if u == v) + if not loops: + assert _edge_sets(got) == _edge_sets(want) + # One block of every node. + result = nx.is_biconnected(G, backend="graphblas") + assert type(result) is bool + assert result == nx.is_biconnected(G) + + +@pytest.mark.parametrize(("name", "G"), GRAPHS, ids=[name for name, _ in GRAPHS]) +def test_blocks_match_networkx(name, G): + _check(G) + + +@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 + got = list(nxapi.articulation_points(g)) + assert set(got) == set(nx.articulation_points(G)) + assert len(got) == len(set(got)) + want = {frozenset(block) for block in nx.biconnected_components(G)} + assert {frozenset(block) for block in nxapi.biconnected_components(g)} == want + got = _without_loops(nxapi.biconnected_component_edges(g)) + assert _edge_sets(got) == _edge_sets(_without_loops(nx.biconnected_component_edges(G))) + assert nxapi.is_biconnected(g) is nx.is_biconnected(G) + + +def _small_graphs(): + """Every graph of up to 7 nodes, up to isomorphism, and some joined at a node or an edge.""" + graphs = list(nx.graph_atlas_g()) + rng = np.random.default_rng(74) + for i in range(60): + parts = [graphs[int(rng.integers(len(graphs)))] for _ in range(int(rng.integers(2, 4)))] + G = nx.disjoint_union_all(parts) + for _ in range(int(rng.integers(0, 4))): + if len(G) > 1: + u, v = rng.choice(list(G), 2, replace=False).tolist() + if i % 2: + G = nx.contracted_nodes(G, u, v, self_loops=False) + else: + G.add_edge(u, v) + graphs.append(_shuffled(G, rng)) + return graphs + + +def test_every_small_graph_and_some_joined(): + for G in _small_graphs(): + _check(G) + + +@pytest.mark.parametrize( + "G", + [ + nx.Graph(), + nx.empty_graph(1), + nx.empty_graph(2), + nx.path_graph(2), + nx.path_graph(3), + nx.cycle_graph(3), + nx.complete_graph(5), + nx.star_graph(4), + nx.Graph([(0, 0)]), + nx.Graph([(0, 0), (0, 1)]), + nx.Graph([(0, 1), (1, 1)]), + nx.Graph([(0, 1), (1, 2), (2, 0), (0, 0), (3, 3)]), + nx.disjoint_union(nx.cycle_graph(4), nx.cycle_graph(3)), + nx.disjoint_union(nx.path_graph(2), nx.empty_graph(1)), + nx.barbell_graph(4, 0), + nx.barbell_graph(4, 3), + nx.grid_2d_graph(4, 5), + nx.wheel_graph(6), + nx.complete_bipartite_graph(2, 5), + ], + ids=lambda G: f"{len(G)}-{G.number_of_edges()}", +) +def test_edge_cases(G): + _check(G) + + +@pytest.mark.parametrize("n", [3, 1000, 200_000]) +def test_a_long_path_and_cycle(n): + G = nx.path_graph(n) + assert list(nx.articulation_points(G, backend="graphblas")) == list(range(1, n - 1)) + assert len(list(nx.biconnected_components(G, backend="graphblas"))) == n - 1 + assert nx.is_biconnected(G, backend="graphblas") is (n == 2) + G.add_edge(0, n - 1) + assert list(nx.articulation_points(G, backend="graphblas")) == [] + assert list(nx.biconnected_components(G, backend="graphblas")) == [set(range(n))] + assert nx.is_biconnected(G, backend="graphblas") is True + + +def test_is_biconnected_where_it_ends_early(): + """No edge at a node, one edge at a node of three or more, or two components: no search.""" + cases = { + "isolated": nx.disjoint_union(nx.cycle_graph(5), nx.empty_graph(1)), + "leaf": nx.lollipop_graph(4, 1), + "two cycles": nx.disjoint_union(nx.cycle_graph(5), nx.cycle_graph(4)), + "one edge": nx.path_graph(2), + "one edge and a node": nx.disjoint_union(nx.path_graph(2), nx.empty_graph(1)), + "two cycles at a node": nx.Graph([(0, 1), (1, 2), (2, 0), (0, 3), (3, 4), (4, 0)]), + "a cycle with a loop": nx.Graph([(0, 1), (1, 2), (2, 0), (1, 1)]), + } + for G in cases.values(): + assert nx.is_biconnected(G, backend="graphblas") is nx.is_biconnected(G) + + +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] + assert list(nx.articulation_points(U, backend="graphblas")) == ["c", 1] + assert list(nxapi.articulation_points(U)) == ["c", 1] + blocks = {frozenset(block) for block in nxapi.biconnected_components(U)} + assert blocks == {frozenset("abc"), frozenset("cd"), frozenset({0, 1}), frozenset({1, 2})} + edges = _edge_sets(nxapi.biconnected_component_edges(U)) + assert edges == _edge_sets(nx.biconnected_component_edges(nx.union(G, H))) + + +def test_blocks_from_a_forest_with_edges_off_it_at_its_root(monkeypatch): + """Blocks from any spanning forest, here a search's: edges off it at its root, in two subtrees. + + The forest `_spanning_forest` builds kept every edge at a root on each graph tried, so this + one is given by hand. + """ + from graphblas_algorithms.algorithms import bridges + from graphblas_algorithms.algorithms.components import biconnected + + G = ga.Graph.from_networkx(nx.Graph([(0, 1), (1, 2), (2, 0), (0, 3), (3, 4), (4, 0)])) + tree = {(0, 1), (1, 2), (0, 3), (3, 4)} + spanning_forest = bridges._spanning_forest + + def search_forest(n, us, vs): + if len(us) != 6: # the blocks' own graph + return spanning_forest(n, us, vs) + in_forest = np.array([edge in tree for edge in zip(us.tolist(), vs.tolist(), strict=True)]) + return in_forest, np.zeros(n, np.intp) + + monkeypatch.setattr(bridges, "_spanning_forest", search_forest) + f = bridges._forest_numbers(len(G), *bridges._entries_by_row(G.get_property("offdiag"))) + assert set(zip(f.off_u.tolist(), f.off_v.tolist(), strict=True)) == {(0, 2), (0, 4)} + assert f.parent.tolist() == [-1, 0, 1, 0, 3] + assert biconnected.articulation_ids(G).tolist() == [0] + nodes, starts = biconnected.block_node_ids(G) + blocks = {frozenset(nodes[a:b].tolist()) for a, b in pairwise(starts.tolist())} + assert blocks == {frozenset({0, 1, 2}), frozenset({0, 3, 4})} + us, vs, starts = biconnected.block_edge_ids(G) + edges = { + frozenset(map(frozenset, zip(us[a:b].tolist(), vs[a:b].tolist(), strict=True))) + for a, b in pairwise(starts.tolist()) + } + assert edges == { + frozenset(map(frozenset, [(0, 1), (1, 2), (0, 2)])), + frozenset(map(frozenset, [(0, 3), (3, 4), (0, 4)])), + } + assert biconnected.is_biconnected(G) is False + + +# A backend graph, through NetworkX and directly + + +@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 _as_sets(name, outcome): + if outcome[0] != "items": + return outcome + if name == "biconnected_component_edges": + return "items", _edge_sets(outcome[1]) + if name == "biconnected_components": + return "items", {frozenset(block) for block in outcome[1]} + return "items", set(outcome[1]) + + +@pytest.mark.parametrize("name", NAMES) +def test_a_backend_graph_is_served_through_networkx_without_a_conversion(conversions, name): + G = nx.barbell_graph(4, 2) + G.add_edges_from([(20, 21), (21, 22), (22, 20), (22, 23)]) + g = ga.Graph.from_networkx(G) + f = getattr(nx, name) + want = _as_sets(name, _outcome(lambda: f(G, backend="networkx"))) + assert _as_sets(name, _outcome(lambda: f(g))) == want + with graphblas_first(): + assert _as_sets(name, _outcome(lambda: f(g))) == want + assert _as_sets(name, _outcome(lambda: getattr(nxapi, name)(g))) == want + assert conversions == [] + + +@pytest.mark.parametrize("name", NAMES[:3]) +def test_a_direct_call_reads_the_graph_at_the_first_next(name): + """As NetworkX's generators do: a change made after the call and before `next()` is seen.""" + results = [] + for f in [getattr(nx, name), getattr(nxapi, name)]: + G = nx.path_graph(5) + blocks = f(G) + G.add_edge(0, 4) + results.append(_as_sets(name, _outcome(lambda blocks=blocks: blocks))) + assert results[0] == results[1] + assert results[0] != _as_sets(name, _outcome(lambda: f(nx.path_graph(5)))) + + +# The automatic path: should_run + + +def _reason(name, G): + return Dispatcher.should_run(name, (G,), {}) + + +@pytest.mark.parametrize("name", NAMES) +def test_should_run_leaves_small_networkx_graphs_to_networkx(conversions, name): + f = getattr(nx, name) + for G in [nx.cycle_graph(1000), nx.grid_2d_graph(100, 100), nx.barbell_graph(50, 10)]: + assert isinstance(_reason(name, G), str) + with graphblas_first(): + assert _as_sets(name, _outcome(lambda G=G: f(G))) == _as_sets( + name, _outcome(lambda G=G: f(G, backend="networkx")) + ) + assert conversions == [] + # A backend graph has nothing to convert, so nothing to weigh. + assert _reason(name, ga.Graph.from_networkx(nx.path_graph(5))) is True + + +def test_should_run_leaves_every_graph_that_must_be_converted(): + """With the conversion counted, no floor of nodes and edges per node kept out the losses.""" + G = nx.circulant_graph(300_000, [1, 2]) + assert all(isinstance(_reason(name, G), str) for name in NAMES) + + +def test_should_run_leaves_a_self_loop_to_networkx(): + assert _a_self_loop(nx.cycle_graph(5)) is None + G = nx.cycle_graph(5) + G.add_edge(3, 3) + assert isinstance(_a_self_loop(G), str) + + +def test_should_run_serves_a_graph_networkx_already_converted(conversions): + G = nx.cycle_graph(10_000) + G.add_edge(0, 0) + reasons = [_reason(name, G) for name in NAMES] + assert all(isinstance(reason, str) for reason in reasons) + nx.is_biconnected(G, backend="graphblas") + assert len(conversions) == 1 + assert [_reason(name, G) is True for name in NAMES] == [True, False, True, True] + assert isinstance(_reason("biconnected_component_edges", G), str) # its self-loop + assert G.__networkx_cache__["graphblas_facts"]["a self-loop"] is True # read once a version + with graphblas_first(): + for name in NAMES: + f = getattr(nx, name) + assert _as_sets(name, _outcome(lambda f=f: f(G))) == _as_sets( + name, _outcome(lambda f=f: f(G, backend="networkx")) + ) + assert len(conversions) == 1 # served from NetworkX's cache, or left to NetworkX + G.remove_edge(0, 0) # NetworkX drops its conversions of a graph that changes + assert all(isinstance(_reason(name, G), str) for name in NAMES) + nx.is_biconnected(G, backend="graphblas") + assert all(_reason(name, G) is True for name in NAMES) + G = nx.path_graph(10_000) + nx.is_biconnected(G, backend="graphblas") + assert all(_reason(name, G) is True for name in NAMES) + G = nx.cycle_graph(9_999) # under 10000 nodes, cached or not: the floor `_faster_from` sets + assert all("converts it" in _reason(name, G) for name in NAMES) + nx.is_biconnected(G, backend="graphblas") + assert all("conversion networkx holds" in _reason(name, G) for name in NAMES) + # NetworkX keeps a view's conversions when the graph under it changes, so none is reused. + V = nx.cycle_graph(20_000).subgraph(range(15_000)) + nx.is_biconnected(V, backend="graphblas") + assert all(isinstance(_reason(name, V), str) for name in NAMES) + + +# Errors, at the call, as in NetworkX + + +@pytest.mark.parametrize("name", NAMES) +def test_a_directed_graph_raises_at_the_call(name): + G = nx.DiGraph([(0, 1), (1, 2), (2, 0)]) + f = getattr(nx, name) + want = _outcome(lambda: f(G)) + assert want[:2] == ("call", nx.NetworkXNotImplemented) + assert _outcome(lambda: f(G, backend="graphblas")) == want + with graphblas_first(): + assert _outcome(lambda: f(G)) == want + direct = getattr(nxapi, name) + assert _outcome(lambda: direct(G)) == want + assert _outcome(lambda: direct(ga.DiGraph.from_networkx(G))) == want + + +@pytest.mark.parametrize("name", NAMES) +def test_a_multigraph_is_left_to_networkx(name): + """The matrix would merge parallel edges, which make a block of their own, so it declines.""" + G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)]) + f = getattr(nx, name) + with pytest.raises(NotImplementedError, match="not implemented by 'graphblas'"): + f(G, backend="graphblas") + with graphblas_first(): + assert _as_sets(name, _outcome(lambda: f(G))) == _as_sets( + name, _outcome(lambda: f(G, backend="networkx")) + ) + with pytest.raises(NotImplementedError, match="does not support multigraphs"): + getattr(nxapi, name)(G) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 36459a4..f8dffd6 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -74,6 +74,7 @@ def call_args(kind, args): "all_pairs_bellman_ford_path_length": ("undirected", ()), "all_pairs_shortest_path_length": ("undirected", ()), "ancestors": ("dag", (3,)), + "articulation_points": ("undirected", ()), "average_clustering": ("undirected", ()), # Raises on a graph in pieces, as `center` and its kin below do. "average_shortest_path_length": ("tournament", ()), @@ -86,6 +87,8 @@ def call_args(kind, args): "bfs_edges": ("undirected", (0,)), "bfs_layers": ("undirected", ([0],)), "bfs_successors": ("undirected", (0,)), + "biconnected_component_edges": ("undirected", ()), + "biconnected_components": ("undirected", ()), "boundary_expansion": ("undirected", ([0, 1],)), "bridges": ("undirected", ()), # The tournament is the kind without an isolated node: eccentricity, and the names read @@ -142,6 +145,7 @@ def call_args(kind, args): "intersection": ("plain", (SECOND,)), "intra_community_edges": ("undirected", ([{0, 1}, {2, 3, 4}],)), "is_arborescence": ("dag", ()), + "is_biconnected": ("undirected", ()), "is_branching": ("dag", ()), "is_connected": ("undirected", ()), "is_cover": ("undirected", ([{0, 1, 2}, {2, 3, 4}],)),