From 661d89565942521c948f6df40282c6689f57adaa Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 17:31:44 -0600 Subject: [PATCH] Add transitive_closure, transitive_closure_dag and transitive_reduction A directed graph's closure is a breadth-first search from every node with an out-edge at once, in blocks of sources whose bitmap stays under 64 MB. Its diagonal holds the nodes on a cycle, the self-loops reflexive=False adds; reflexive=True adds one at every node and None adds none but the graph's own. An undirected graph's closure joins each node to the rest of its component, read off the component labels, and as in NetworkX it gains no self-loop there unless reflexive is True. The reduction keeps each edge whose head no walk of two or more edges from its tail reaches, walking only from nodes with two out-edges or more. The results are NetworkX graphs written a row at a time rather than through add_edges_from. As NetworkX's copy does, a closure keeps the graph attributes and each edge's weight, its new edges carry no data, and an edge's data dict is the one both its adjacencies hold; the reduction keeps the nodes and nothing else. A reflexive that only equals a bool, such as 1, adds no edge, as in NetworkX. A cycle raises NetworkXUnfeasible in transitive_closure_dag and NetworkXError in transitive_reduction, as NetworkX's do. A closure of more than 2**24 edges is left to NetworkX, to bound the memory of the graph built. So is a topo_order that is not a list or tuple of every node once in a topological order, since NetworkX does not check it and its answer follows the order given. --- README.md | 5 +- _nx_graphblas/__init__.py | 6 + _nx_graphblas/core.py | 16 + graphblas_algorithms/algorithms/dag.py | 124 ++++- graphblas_algorithms/interface.py | 3 + graphblas_algorithms/nxapi/dag.py | 175 ++++++- graphblas_algorithms/nxapi/exception.py | 4 + .../nxapi/tests/test_transitive_closure.py | 434 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 4 + graphblas_algorithms/tests/test_dispatch.py | 11 + graphblas_algorithms/tests/test_match_nx.py | 7 +- 11 files changed, 781 insertions(+), 8 deletions(-) create mode 100644 graphblas_algorithms/nxapi/tests/test_transitive_closure.py diff --git a/README.md b/README.md index 1bc06b5..67cff60 100644 --- a/README.md +++ b/README.md @@ -197,7 +197,10 @@ graphblas_algorithms.nxapi │ └── volume ├── dag │ ├── ancestors -│ └── descendants +│ ├── descendants +│ ├── transitive_closure +│ ├── transitive_closure_dag +│ └── transitive_reduction ├── distance_measures │ ├── center │ ├── diameter diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..4519faa 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -153,6 +153,9 @@ def get_info(): "square_clustering", "symmetric_difference", "tournament_matrix", + "transitive_closure", + "transitive_closure_dag", + "transitive_reduction", "transitivity", "triangles", "union", @@ -229,6 +232,9 @@ def get_info(): "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "schultz_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.', "single_source_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.", + "transitive_closure": "Each node's neighbors come in node order, which may differ from NetworkX's. A closure\nof more than 2**24 edges, an undirected edge counted both ways, is left to NetworkX, to\nbound the memory of the graph built.\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.", + "transitive_closure_dag": "Each node's neighbors come in node order, which may differ from NetworkX's. A closure\nof more than 2**24 edges, an undirected edge counted both ways, is left to NetworkX, to\nbound the memory of the graph built.\nA `topo_order` is served when it is a list or tuple of every node once, each edge's tail\nbefore its head. NetworkX follows any other order as given, so that is left to it.\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.", + "transitive_reduction": "Each node's neighbors come in node order, which may differ from NetworkX's.", "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "volume": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more, or to 2**63 over the most times `S` names one node.", "wiener_index": 'Lengths 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, or where the sum over one node\'s targets could\nreach 2**63.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..3f3f32d 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. +# A closure can have about n**2 edges, each with a dict of its own in the graph built. +_CLOSURE = ( + "Each node's neighbors come in node order, which may differ from NetworkX's. A closure\n" + "of more than 2**24 edges, an undirected edge counted both ways, is left to NetworkX, to\n" + "bound the memory of the graph built." +) + _ADDITIONAL_DOCS = { "all_pairs_bellman_ford_path_length": _PATH_OVERFLOW, "average_shortest_path_length": ( @@ -176,6 +183,13 @@ "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' + _LENGTH_SUM_OVERFLOW, "single_source_bellman_ford_path_length": _PATH_OVERFLOW, + "transitive_closure": _CLOSURE, + "transitive_closure_dag": _CLOSURE + "\n" + "A `topo_order` is served when it is a list or tuple of every node once, each edge's tail\n" + "before its head. NetworkX follows any other order as given, so that is left to it.", + "transitive_reduction": ( + "Each node's neighbors come in node order, which may differ from NetworkX's." + ), "volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.", "wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW, } @@ -198,6 +212,8 @@ "k_shell", "k_truss", "reverse", + "transitive_closure", + "transitive_closure_dag", "union", ): _doc = _ADDITIONAL_DOCS.get(_name) diff --git a/graphblas_algorithms/algorithms/dag.py b/graphblas_algorithms/algorithms/dag.py index 9483e70..ed19e86 100644 --- a/graphblas_algorithms/algorithms/dag.py +++ b/graphblas_algorithms/algorithms/dag.py @@ -1,9 +1,11 @@ -from graphblas import Vector, replace +import numpy as np +from graphblas import Matrix, Vector, agg, binary, replace, select, unary from graphblas.semiring import any_pair -from ._bfs import _bfs_plain +from ._bfs import _bfs_plain, _visited +from .components._labels import component_labels -__all__ = ["ancestors", "descendants", "is_acyclic"] +__all__ = ["ancestors", "descendants", "is_acyclic", "transitive_closure", "transitive_reduction"] def descendants(G, source): @@ -44,3 +46,119 @@ def is_acyclic(G): alive(~peel.S, replace) << alive cache["is_acyclic"] = True return True + + +# The most (source, node) slots one block of a walk from many sources holds; its bitmap is this +# many bytes. A graph of up to 8192 nodes is walked in one block. +_BLOCK_SLOTS = 2**26 + + +def _blocks(A, least): + """The sources with at least `least` out-edges, in blocks as large as `_BLOCK_SLOTS` allows. + + The others have nothing to walk: a node with no out-edge reaches nothing, and the out-edge + of a node with one is the only way to its head, which the reduction keeps. + """ + counts = A.reduce_rowwise(agg.count).new(name="out_degrees") + ids, counts = counts.to_coo() + ids = ids[counts >= least] + size = max(1, _BLOCK_SLOTS // max(A.nrows, 1)) + return [ids[start : start + size] for start in range(0, len(ids), size)] + + +def _out_edges(A, sources): + """The out-edges of `sources`, one row each, as True.""" + return unary.one[bool](A[sources, :].new()).new(name="out_edges") + + +def _walk(A, frontier, limit=None): + """Where each row of `frontier` stands and everything it reaches from there. + + A breadth-first search from every row at once, one product per level. None once more than + `limit` entries are reached. + """ + reached = _visited(frontier.dup(name="reached")) + any_pair_bool = any_pair[bool] + while frontier.nvals > 0: + frontier(~reached.S, replace) << any_pair_bool(frontier @ A) + reached(frontier.S) << True + if limit is not None and reached.nvals > limit: + return None + return reached + + +def _stacked(blocks, n): + """(sources, rows) blocks, in order of their sources, as one n by n matrix of True.""" + counts = np.zeros(n, np.int64) + cols = [] + for sources, rows in blocks: + exported = rows.ss.export("csr", sort=True, give_ownership=True) + counts[sources] = np.diff(exported["indptr"]) + cols.append(exported["col_indices"]) + if not cols: + return Matrix(bool, n, n) + indptr = np.concatenate(([0], np.cumsum(counts))) + return Matrix.from_csr(indptr, np.concatenate(cols), True, nrows=n, ncols=n) + + +def _reachability(A, limit): + """(i, j) when a path of one or more edges leads from i to j; None past `limit` entries. + + So the diagonal holds each node on a cycle, a self-loop included. + """ + blocks = [] + total = 0 + for sources in _blocks(A, 1): + reached = _walk(A, _out_edges(A, sources), None if limit is None else limit - total) + if reached is None: + return None + total += reached.nvals + blocks.append((sources, reached)) + return _stacked(blocks, A.nrows) + + +def transitive_closure(G, reflexive=False, *, limit=None): + """The edges of `G`'s transitive closure, as a matrix of True over `G`'s ids. + + (i, j) for each path from i to j, and every edge of `G`. `reflexive` True adds a self-loop at + every node, False one at each node on a cycle, and None none: NetworkX's choices. A cycle of + an undirected graph is one that does not walk back along an edge, so there False adds none. + None when the closure would hold more than `limit` pairs, an undirected pair counted both + ways and each node with itself. + """ + A = G._A + n = A.nrows + if G.is_directed(): + R = _reachability(A, limit) + if R is None: + return None + if reflexive is False: + return R + else: + labels = component_labels(A) + sizes = np.bincount(labels, minlength=n) + if limit is not None and int(sizes @ sizes) > limit: + return None + # Every pair in one component, each node with itself. + C = Matrix.from_coo(np.arange(n), labels, True, nrows=n, ncols=n) + R = any_pair[bool](C @ C.T).new(name="transitive_closure") + if reflexive is True: + if G.is_directed(): + R(binary.any) << Vector.from_scalar(True, n).diag() + return R + # No self-loop but those `G` has. + E = select.offdiag(R).new(name="transitive_closure") + E(binary.any) << unary.one[bool](select.diag(A).new()) + return E + + +def transitive_reduction(G): + """The edges of acyclic `G` that no path of two or more edges gives, as True over `G`'s ids.""" + A = G._A + implied = [] + for sources in _blocks(A, 2): + out = _out_edges(A, sources) + further = _walk(A, any_pair[bool](out @ A).new(name="frontier")) + implied.append((sources, out.dup(mask=further.S))) + implied = _stacked(implied, A.nrows) + return unary.one[bool](A).new(mask=~implied.S, name="transitive_reduction") diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..d6d0b04 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -310,6 +310,9 @@ class Dispatcher: # ============= ancestors = mod.ancestors descendants = mod.descendants + transitive_closure = mod.transitive_closure + transitive_closure_dag = mod.transitive_closure_dag + transitive_reduction = mod.transitive_reduction mod = nxapi.distance_measures # =========================== diff --git a/graphblas_algorithms/nxapi/dag.py b/graphblas_algorithms/nxapi/dag.py index d00734f..abdc704 100644 --- a/graphblas_algorithms/nxapi/dag.py +++ b/graphblas_algorithms/nxapi/dag.py @@ -1,9 +1,29 @@ +from itertools import repeat, starmap + +import numpy as np +from graphblas import Matrix, select + from graphblas_algorithms import algorithms -from graphblas_algorithms.classes.digraph import to_graph +from graphblas_algorithms.algorithms.components._labels import _keys_by_id +from graphblas_algorithms.classes._utils import PRESERVE +from graphblas_algorithms.classes.digraph import to_directed_graph, to_graph +from graphblas_algorithms.utils import not_implemented_for -from .exception import NetworkXError +from ._utils import can_run +from .exception import NetworkXError, NetworkXUnfeasible -__all__ = ["ancestors", "descendants"] +__all__ = [ + "ancestors", + "descendants", + "transitive_closure", + "transitive_closure_dag", + "transitive_reduction", +] + +# The most edges a closure is built with, an undirected edge counting twice. Past it the call +# is declined (NotImplementedError) before the NetworkX graph is built. The call peaks at about +# 215 bytes an edge (NetworkX's own loop at about 180 to 205), so about 3.6 GB at the bound. +_MOST_CLOSURE_EDGES = 2**24 def descendants(G, source): @@ -24,3 +44,152 @@ def ancestors(G, source): raise NetworkXError(*e.args) from e else: return G.vector_to_nodeset(result) + + +def _too_many_edges(name): + return NotImplementedError( + f"{name} would have more than {_MOST_CLOSURE_EDGES} edges, past the bound this " + "backend keeps its memory under; networkx serves it" + ) + + +def transitive_closure(G, reflexive=False): + if reflexive not in {None, True, False}: + raise NetworkXError("Incorrect value for the parameter `reflexive`") + G = to_graph(G, weight=PRESERVE) + if reflexive is None or reflexive is True or reflexive is False: + E = algorithms.transitive_closure(G, reflexive, limit=_MOST_CLOSURE_EDGES) + if E is None: + raise _too_many_edges("transitive_closure") + else: + # A value that only equals one of them, such as 1 or numpy's True: NetworkX adds no edge. + E = G._A.dup(dtype=bool) + return _networkx_graph(G, E, weight=G._weight, keep_graph=True) + + +def _ordered_by(G, topo_order): + """Whether `topo_order` lists each node of `G` once, every edge's tail before its head.""" + key_to_id = G._key_to_id + n = len(key_to_id) + if len(topo_order) != n: + return False + try: + ids = np.fromiter((key_to_id[node] for node in topo_order), np.int64, n) + except (KeyError, TypeError): + return False + place = np.full(n, -1, np.int64) + place[ids] = np.arange(n) + if (place < 0).any(): + return False # a node listed twice, so another not at all + rows, cols, _values = G._A.to_coo(values=False) + return bool((place[rows] < place[cols]).all()) + + +def _own_order(bound): + topo_order = bound.get("topo_order") + if topo_order is not None and not isinstance(topo_order, list | tuple): + return ( + "transitive_closure_dag reads a `topo_order` other than a list or tuple as " + "NetworkX's loop does; networkx serves it" + ) + return None + + +@can_run(_own_order) +@not_implemented_for("undirected") +def transitive_closure_dag(G, topo_order=None): + G = to_directed_graph(G, weight=PRESERVE) + if topo_order is None: + if not algorithms.is_acyclic(G): + raise NetworkXUnfeasible("Graph contains a cycle or graph changed during iteration") + elif not _ordered_by(G, topo_order): + # NetworkX does not check it: its answer follows the order given. + raise NotImplementedError( + "transitive_closure_dag with a `topo_order` that is not a topological order of " + "every node once is NetworkX's to answer; networkx serves it" + ) + E = algorithms.transitive_closure(G, limit=_MOST_CLOSURE_EDGES) + if E is None: + raise _too_many_edges("transitive_closure_dag") + return _networkx_graph(G, E, weight=G._weight, keep_graph=True) + + +@not_implemented_for("undirected") +def transitive_reduction(G): + G = to_directed_graph(G) + if not algorithms.is_acyclic(G): + raise NetworkXError("Directed Acyclic Graph required for transitive_reduction") + return _networkx_graph(G, algorithms.transitive_reduction(G)) + + +def _networkx_graph(G, E, *, weight=None, keep_graph=False): + """The NetworkX graph with `G`'s nodes, in order, and the edges `E` holds over `G`'s ids. + + An edge of `G` carries its value under `weight`; with None, or for any other edge, an edge + carries no data. A directed edge's data is one dict in both of its adjacencies, and an + undirected edge's in both directions, as NetworkX keeps them. The adjacency is written a row + at a time, several times faster than `add_edges_from`, which checks each edge in Python; a + closure may have millions. `E` is emptied, its arrays taken rather than copied. + """ + import networkx as nx + + directed = G.is_directed() + H = nx.DiGraph() if directed else nx.Graph() + if keep_graph: + H.graph.update(G.graph) + H.add_nodes_from(G._key_to_id) + if E.nvals == 0: + return H + n = E.nrows + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + if not directed: + E = select.triu(E).new() # each edge once; its two directions share its data + indptr, cols, _values = _csr(E) + count = len(cols) + # A new dict each: faster than a list display, which also leaves a list behind. + data = np.fromiter(starmap(dict, repeat((), count)), object, count) + _fill(H._adj, G._key_to_id, keys, indptr, cols, data) + # Each edge's place in `data`, read from its other end: the predecessors, or the lower + # triangle (a self-loop is written again, with the same dict). + places = Matrix.ss.import_csr( + nrows=n, + ncols=n, + indptr=indptr, + col_indices=cols, + values=np.arange(count, dtype=np.int64), + sorted_cols=True, + take_ownership=True, + ) + del indptr, cols + other = places.T.new() + del places + indptr, cols, at = _csr(other) + del other + _fill(H._pred if directed else H._adj, G._key_to_id, keys, indptr, cols, data[at]) + if weight is not None: + A = G._A if directed else select.triu(G._A).new() + rows, cols, values = A.to_coo() + adj = H._adj + # `tolist()` gives Python scalars; NetworkX rejects a numpy scalar in a result. + edges = zip(keys[rows].tolist(), keys[cols].tolist(), values.tolist(), strict=True) + for u, v, value in edges: + adj[u][v][weight] = value + return H + + +def _csr(M): + """`M`'s CSR arrays, sorted, taken from it.""" + exported = M.ss.export("csr", sort=True, give_ownership=True) + return exported["indptr"], exported["col_indices"], exported["values"] + + +def _fill(adj, key_to_id, keys, indptr, cols, data): + """Each node's row of `cols` and `data` into its dict in `adj`.""" + neighbors = keys[cols] + indptr = indptr.tolist() + for key, i in key_to_id.items(): + start, stop = indptr[i], indptr[i + 1] + if start < stop: + adj[key].update( + zip(neighbors[start:stop].tolist(), data[start:stop].tolist(), strict=True) + ) diff --git a/graphblas_algorithms/nxapi/exception.py b/graphblas_algorithms/nxapi/exception.py index f4a05df..2ed6785 100644 --- a/graphblas_algorithms/nxapi/exception.py +++ b/graphblas_algorithms/nxapi/exception.py @@ -23,6 +23,9 @@ class NetworkXPointlessConcept(Exception): class NetworkXUnbounded(Exception): pass + class NetworkXUnfeasible(Exception): + pass + class NodeNotFound(Exception): pass @@ -38,6 +41,7 @@ class PowerIterationFailedConvergence(Exception): NetworkXNotImplemented, NetworkXPointlessConcept, NetworkXUnbounded, + NetworkXUnfeasible, NodeNotFound, PowerIterationFailedConvergence, ) diff --git a/graphblas_algorithms/nxapi/tests/test_transitive_closure.py b/graphblas_algorithms/nxapi/tests/test_transitive_closure.py new file mode 100644 index 0000000..dc2e01a --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_transitive_closure.py @@ -0,0 +1,434 @@ +"""transitive_closure, transitive_closure_dag and transitive_reduction against NetworkX. + +The edges, their data and the nodes must be NetworkX's exactly; only the order of each node's +neighbors may differ. Each call is made by name with `backend="graphblas"` and with this backend +first in NetworkX's priority, where a decline must reach NetworkX's own answer. +""" + +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest + +from graphblas_algorithms.interface import Dispatcher +from graphblas_algorithms.nxapi import dag + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +NAMES = ["transitive_closure", "transitive_closure_dag", "transitive_reduction"] +REFLEXIVE = [False, True, None] + + +@contextmanager +def graphblas_first(): + """Put this backend first for graph-returning names; a decline goes to NetworkX.""" + config = nx.config + saved = list(config.backend_priority.generators), config.fallback_to_nx + config.backend_priority.generators = ["graphblas"] + config.fallback_to_nx = False + try: + yield + finally: + config.backend_priority.generators, config.fallback_to_nx = saved + + +def assert_same_graph(got, expected): + """The same class, nodes in the same order, and the same data everywhere.""" + assert type(got) is type(expected) + assert list(got) == list(expected) + assert got.graph == expected.graph + assert got._node == expected._node + assert got._adj == expected._adj + if expected.is_directed(): + assert got._pred == expected._pred + assert all(got._succ[u][v] is got._pred[v][u] for u, v in got.edges) + else: + assert all(got._adj[u][v] is got._adj[v][u] for u, v in got.edges) + + +def served(name, G, *args, **kwargs): + """`name` by this backend, both ways, checked to agree; NetworkX's answer last.""" + func = getattr(nx, name) + expected = func(G, *args, **kwargs) + got = func(G, *args, backend="graphblas", **kwargs) + assert_same_graph(got, expected) + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same_graph(func(G, *args, **kwargs), expected) + return got, expected + + +def _relabeled(G, rng, labels): + nodes = rng.permutation(len(G)).tolist() + if labels == "str": + mapping = {node: f"n{node}" for node in nodes} + elif labels == "tuple": + mapping = {node: (node % 3, node) for node in nodes} + else: + mapping = {node: node for node in nodes} + # Nodes first, in a shuffled order, then the edges in a shuffled order of their own. + H = G.__class__() + H.graph.update(G.graph) + H.add_nodes_from(mapping[node] for node in nodes) + edges = list(G.edges(data=True)) + H.add_edges_from( + (mapping[u], mapping[v], data) + for u, v, data in (edges[i] for i in rng.permutation(len(edges)).tolist()) + ) + return H + + +def random_graph(seed, *, directed, acyclic=False): + """A small random graph: sparse or dense, maybe weighted, with self-loops unless acyclic.""" + rng = np.random.default_rng(seed) + n = int(rng.integers(0, 25)) + p = float(rng.choice([0.03, 0.08, 0.15, 0.3])) + G = nx.gnp_random_graph(n, p, seed=seed, directed=directed and not acyclic) + if acyclic: + G = nx.DiGraph(G.edges) # an undirected gnp edge has u < v + G.add_nodes_from(range(n)) + elif n and rng.random() < 0.5: + loops = rng.choice(n, size=int(rng.integers(1, max(1, n // 4) + 1)), replace=False) + G.add_edges_from((v, v) for v in loops.tolist()) + weights = rng.choice(["none", "int", "float"]) + for _u, _v, data in G.edges(data=True): + if weights == "int": + data["weight"] = int(rng.integers(-5, 10)) + elif weights == "float": + data["weight"] = float(rng.uniform(-1, 3)) + if rng.random() < 0.5: + G.graph["name"] = f"g{seed}" + return _relabeled(G, rng, rng.choice(["int", "str", "tuple"])) + + +@pytest.mark.parametrize("seed", range(110)) +@pytest.mark.parametrize("directed", [True, False], ids=["directed", "undirected"]) +def test_transitive_closure_of_a_random_graph(seed, directed): + G = random_graph(seed, directed=directed) + for reflexive in REFLEXIVE: + served("transitive_closure", G, reflexive=reflexive) + + +@pytest.mark.parametrize("seed", range(110)) +def test_the_closure_and_reduction_of_a_random_dag(seed): + G = random_graph(1000 + seed, directed=True, acyclic=True) + served("transitive_closure_dag", G) + served("transitive_closure_dag", G, list(nx.topological_sort(G))) + served("transitive_closure_dag", G, topo_order=tuple(nx.topological_sort(G))) + served("transitive_reduction", G) + for reflexive in REFLEXIVE: + served("transitive_closure", G, reflexive=reflexive) + + +@pytest.mark.parametrize( + "build", + [ + lambda: nx.path_graph(300, create_using=nx.DiGraph), + lambda: nx.balanced_tree(3, 5, create_using=nx.DiGraph), + lambda: nx.gn_graph(400, seed=1), + lambda: nx.DiGraph(nx.complete_graph(30)), + lambda: nx.cycle_graph(50, create_using=nx.DiGraph), + lambda: nx.path_graph(200), + lambda: nx.disjoint_union(nx.complete_graph(20), nx.cycle_graph(30)), + ], + ids=["path", "tree", "gn", "complete", "cycle", "undirected path", "undirected pieces"], +) +def test_transitive_closure_of_a_larger_graph(build): + G = build() + for reflexive in REFLEXIVE: + served("transitive_closure", G, reflexive=reflexive) + if G.is_directed() and nx.is_directed_acyclic_graph(G): + served("transitive_closure_dag", G) + served("transitive_reduction", G) + + +@pytest.mark.parametrize( + "G", + [ + nx.DiGraph([(0, 1)]), + nx.Graph([(0, 1)]), + nx.DiGraph([(0, 0)]), + nx.Graph([(0, 0)]), + nx.empty_graph(3, create_using=nx.DiGraph), + nx.empty_graph(3), + ], + ids=["edge", "undirected edge", "self-loop", "undirected self-loop", "no edges", "undirected"], +) +def test_a_tiny_graph(G): + for reflexive in REFLEXIVE: + served("transitive_closure", G, reflexive=reflexive) + if G.is_directed() and nx.is_directed_acyclic_graph(G): + served("transitive_closure_dag", G) + served("transitive_reduction", G) + + +def test_a_cycle_gives_each_node_on_it_a_self_loop(): + G = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3), (4, 4)]) + G.add_node(5) + got, _ = served("transitive_closure", G) + assert sorted(v for v in got if got.has_edge(v, v)) == [0, 1, 2, 4] + got, _ = served("transitive_closure", G, reflexive=None) + assert sorted(v for v in got if got.has_edge(v, v)) == [4] # the graph's own + got, _ = served("transitive_closure", G, reflexive=True) + assert all(got.has_edge(v, v) for v in got) + + +def test_an_undirected_graph_gains_no_self_loop_but_its_own_unless_reflexive(): + G = nx.Graph([(0, 1), (1, 2), (3, 3)]) + G.add_node(4) + for reflexive in [False, None]: + got, _ = served("transitive_closure", G, reflexive=reflexive) + assert [v for v in got if got.has_edge(v, v)] == [3] + got, _ = served("transitive_closure", G, reflexive=True) + assert all(got.has_edge(v, v) for v in got) + + +def test_the_edges_a_graph_has_keep_their_data_and_the_new_ones_have_none(): + G = nx.DiGraph() + G.add_edge(0, 1, weight=7) + G.add_edge(1, 2, weight=2.5) + G.add_edge(2, 2, weight=-1) + G.graph.update({"name": "g", "extra": [1, 2]}) + for name in ["transitive_closure", "transitive_closure_dag"]: + if name == "transitive_closure_dag": + G.remove_edge(2, 2) + got, _ = served(name, G) + assert got[0][1] == {"weight": 7.0} + assert got[0][2] == {} + assert got.graph == {"name": "g", "extra": [1, 2]} + assert got.graph["extra"] is G.graph["extra"] # copied as NetworkX copies it: shallow + + +@pytest.mark.parametrize( + ("weights", "expected"), + [ + ([1, 2], [1, 2]), + ([1.0, 2.5], [1.0, 2.5]), + ([True, False], [True, False]), + ([1, 2.5], [1.0, 2.5]), + ], + ids=["int", "float", "bool", "int and float"], +) +def test_the_weights_come_back_in_the_one_type_their_matrix_holds(weights, expected): + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, weights[0]), (1, 2, weights[1])]) + H = nx.transitive_closure(G, backend="graphblas") + got = [H[u][v]["weight"] for u, v in [(0, 1), (1, 2)]] + assert got == expected + assert [type(w) for w in got] == [type(w) for w in expected] + assert H[0][2] == {} + + +def test_the_reduction_keeps_the_nodes_and_none_of_the_data(): + G = nx.DiGraph([(0, 1, {"weight": 3}), (1, 2, {"weight": 4}), (0, 2, {"weight": 5})]) + G.add_node(3, colour="red") + G.graph["name"] = "g" + got, _ = served("transitive_reduction", G) + assert type(got) is nx.DiGraph + assert list(got.nodes(data=True)) == [(0, {}), (1, {}), (2, {}), (3, {})] + assert sorted(got.edges(data=True)) == [(0, 1, {}), (1, 2, {})] + assert got.graph == {} + + +@pytest.mark.parametrize("name", ["transitive_closure", "transitive_closure_dag"]) +@pytest.mark.parametrize("data", ["node", "two edge attributes", "bare and weighted"]) +def test_data_a_closure_cannot_carry_is_left_to_networkx(name, data): + G = nx.DiGraph([(0, 1, {"weight": 1.5}), (1, 2, {"weight": 2.5})]) + if data == "node": + G.nodes[0]["colour"] = "red" + elif data == "two edge attributes": + G[0][1]["colour"] = "red" + else: + G.add_edge(2, 3) + assert isinstance(Dispatcher.can_run(name, (G,), {}), str) + expected = getattr(nx, name)(G) + with graphblas_first(): + got = getattr(nx, name)(G) + assert_same_graph(got, expected) + + +@pytest.mark.parametrize("value", [1, 0, 1.0, np.True_, np.False_]) +def test_a_reflexive_that_only_equals_a_bool_adds_no_edge(value): + """NetworkX accepts it, as it is in {None, True, False}, and then matches no branch.""" + G = nx.DiGraph([(0, 1), (1, 2), (2, 0)]) + got, expected = served("transitive_closure", G, reflexive=value) + assert sorted(got.edges) == sorted(G.edges) + + +@pytest.mark.parametrize("value", ["yes", 2, (True,)]) +def test_a_reflexive_of_another_value_raises_as_in_networkx(value): + G = nx.DiGraph([(0, 1)]) + for backend in ["networkx", "graphblas"]: + with pytest.raises(nx.NetworkXError, match="Incorrect value for the parameter"): + nx.transitive_closure(G, reflexive=value, backend=backend) + + +def test_an_unhashable_reflexive_raises_type_error_as_in_networkx(): + G = nx.DiGraph([(0, 1)]) + for backend in ["networkx", "graphblas"]: + with pytest.raises(TypeError): + nx.transitive_closure(G, reflexive=[True], backend=backend) + + +@pytest.mark.parametrize( + "G", + [nx.DiGraph([(0, 1), (1, 2), (2, 0)]), nx.DiGraph([(0, 1), (1, 1)])], + ids=["cycle", "self-loop"], +) +def test_the_dag_names_raise_on_a_cycle_as_networkx_does(G): + for backend in ["networkx", "graphblas"]: + with pytest.raises(nx.NetworkXUnfeasible, match="Graph contains a cycle"): + nx.transitive_closure_dag(G, backend=backend) + with pytest.raises(nx.NetworkXError, match="Directed Acyclic Graph required"): + nx.transitive_reduction(G, backend=backend) + with pytest.raises(nx.NetworkXUnfeasible, match="Graph contains a cycle"): + dag.transitive_closure_dag(G) + with pytest.raises(nx.NetworkXError, match="Directed Acyclic Graph required"): + dag.transitive_reduction(G) + + +@pytest.mark.parametrize("name", ["transitive_closure_dag", "transitive_reduction"]) +def test_the_dag_names_refuse_an_undirected_graph(name): + G = nx.path_graph(3) + for backend in ["networkx", "graphblas"]: + with pytest.raises(nx.NetworkXNotImplemented): + getattr(nx, name)(G, backend=backend) + with pytest.raises(nx.NetworkXNotImplemented): + getattr(dag, name)(G) + + +def test_the_null_graph(): + for G in [nx.Graph(), nx.DiGraph()]: + for reflexive in REFLEXIVE: + served("transitive_closure", G, reflexive=reflexive) + served("transitive_closure_dag", nx.DiGraph()) + served("transitive_reduction", nx.DiGraph()) + + +# Orders NetworkX follows as given, with an answer that is not the closure, or an error. +OTHER_ORDERS = { + "reversed": lambda order: order[::-1], + "partial": lambda order: order[:2], + "empty": lambda order: [], + "repeated": lambda order: [*order, order[0]], + "a node in place of another": lambda order: [order[1], *order[1:]], + "a node not in the graph": lambda order: [*order, "missing"], + "an unhashable node": lambda order: [*order[:-1], [order[-1]]], + "an iterator": iter, +} + + +@pytest.mark.parametrize("other", OTHER_ORDERS) +def test_a_topo_order_that_is_not_one_is_left_to_networkx(other): + G = nx.DiGraph([(0, 1), (1, 2), (2, 3), (0, 4)]) + order = list(nx.topological_sort(G)) + try: + expected = nx.transitive_closure_dag(G, OTHER_ORDERS[other](order)) + except Exception as exc: + expected = exc + with pytest.raises(NotImplementedError): + nx.transitive_closure_dag(G, OTHER_ORDERS[other](order), backend="graphblas") + with graphblas_first(): + if isinstance(expected, Exception): + with pytest.raises(type(expected)): + nx.transitive_closure_dag(G, OTHER_ORDERS[other](order)) + else: + assert_same_graph(nx.transitive_closure_dag(G, OTHER_ORDERS[other](order)), expected) + + +def test_networkx_does_not_check_a_given_topo_order_for_a_cycle(): + """With an order given NetworkX answers a graph with a cycle; no order of it is valid.""" + G = nx.DiGraph([(0, 1), (1, 2), (2, 0)]) + expected = nx.transitive_closure_dag(G, [0, 1, 2]) + with pytest.raises(NotImplementedError): + nx.transitive_closure_dag(G, [0, 1, 2], backend="graphblas") + with graphblas_first(): + assert_same_graph(nx.transitive_closure_dag(G, [0, 1, 2]), expected) + + +def test_a_topo_order_other_than_a_list_or_tuple_is_declined_before_converting(): + G = nx.DiGraph([(0, 1)]) + assert isinstance(Dispatcher.can_run("transitive_closure_dag", (G, iter([0, 1])), {}), str) + assert Dispatcher.can_run("transitive_closure_dag", (G, [0, 1]), {}) is True + assert Dispatcher.can_run("transitive_closure_dag", (G,), {"topo_order": (0, 1)}) is True + + +@pytest.mark.parametrize( + ("name", "G", "pairs"), + [ + ("transitive_closure", nx.path_graph(4, create_using=nx.DiGraph), 6), + ("transitive_closure_dag", nx.path_graph(4, create_using=nx.DiGraph), 6), + # Undirected: each pair counts both ways, and each node with itself. + ("transitive_closure", nx.path_graph(4), 16), + ], + ids=["directed", "dag", "undirected"], +) +def test_a_closure_past_the_bound_is_left_to_networkx(monkeypatch, name, G, pairs): + func = getattr(nx, name) + expected = func(G) + monkeypatch.setattr(dag, "_MOST_CLOSURE_EDGES", pairs) + assert_same_graph(func(G, backend="graphblas"), expected) + monkeypatch.setattr(dag, "_MOST_CLOSURE_EDGES", pairs - 1) + with pytest.raises(NotImplementedError) as info: + func(G, backend="graphblas") + assert "past the bound" in str(info.value.__cause__) + with graphblas_first(): + assert_same_graph(func(G), expected) + + +@pytest.mark.parametrize("blocks", [1, 5]) +def test_the_bound_counts_each_pair_reached(monkeypatch, blocks): + """A complete digraph reaches every pair, each node itself included, over all the blocks.""" + from graphblas_algorithms.algorithms import dag as kernels + from graphblas_algorithms.classes import DiGraph + + monkeypatch.setattr(kernels, "_BLOCK_SLOTS", 50 * 50 // blocks) + G = DiGraph.from_networkx(nx.complete_graph(50, create_using=nx.DiGraph)) + assert len(kernels._blocks(G._A, 1)) == blocks + assert kernels.transitive_closure(G, limit=50 * 50 - 1) is None + assert kernels.transitive_closure(G, limit=50 * 50).nvals == 50 * 50 + + +def test_a_walk_in_several_blocks(monkeypatch): + """More sources than one block holds; each block's rows land in their own place.""" + from graphblas_algorithms.algorithms import dag as kernels + from graphblas_algorithms.classes import DiGraph + + monkeypatch.setattr(kernels, "_BLOCK_SLOTS", 7 * 60) + G = nx.gn_graph(60, seed=3) + G.add_edges_from([(0, 59), (59, 30)]) # a cycle through the root + assert len(kernels._blocks(DiGraph.from_networkx(G)._A, 1)) == 9 + for reflexive in REFLEXIVE: + served("transitive_closure", G, reflexive=reflexive) + D = nx.DiGraph(nx.gnp_random_graph(60, 0.1, seed=4).edges) + D.add_nodes_from(range(60)) + assert len(kernels._blocks(DiGraph.from_networkx(D)._A, 2)) > 2 + served("transitive_closure_dag", D) + served("transitive_reduction", D) + + +def test_a_node_with_one_out_edge_is_not_walked_from_for_the_reduction(): + """Its edge is the only way to its head, so it stays; a tree is its own reduction.""" + from graphblas_algorithms.algorithms import dag as kernels + from graphblas_algorithms.classes import DiGraph + + G = nx.gn_graph(200, seed=5) + assert kernels._blocks(DiGraph.from_networkx(G)._A, 2) == [] + got, _ = served("transitive_reduction", G) + assert sorted(got.edges) == sorted(G.edges) + + +def test_the_result_is_an_ordinary_networkx_graph(): + G = nx.DiGraph([(0, 1), (1, 2)]) + got = nx.transitive_closure(G, backend="graphblas") + got.add_edge(2, 3) + got.remove_edge(0, 2) + got[0][1]["colour"] = "red" + assert got.pred[1][0] == {"colour": "red"} + assert sorted(got.edges) == [(0, 1), (1, 2), (2, 3)] + assert sorted(got.in_degree) == [(0, 0), (1, 1), (2, 1), (3, 1)] + assert nx.utils.graphs_equal(got.copy(), got) + U = nx.transitive_closure(nx.path_graph(3), backend="graphblas") + U[0][2]["colour"] = "blue" + assert U[2][0] == {"colour": "blue"} diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..5129a75 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -202,6 +202,10 @@ def call_args(kind, args): "square_clustering": ("undirected", ()), "symmetric_difference": ("plain", (SECOND,)), "tournament_matrix": ("tournament", ()), + # The directed square has a cycle through every node, so the closure gains self-loops. + "transitive_closure": ("directed", ()), + "transitive_closure_dag": ("dag", ()), + "transitive_reduction": ("dag", ()), "transitivity": ("undirected", ()), "triangles": ("undirected", ()), "union": ("undirected", (SECOND_DISJOINT,)), diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 1765e78..0abfd79 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -467,11 +467,22 @@ def weighted_digraph(): return nx.DiGraph([(0, 1, {"weight": 2.0}), (1, 2, {"weight": 3.0})]) +def _acyclic(G): + """`G` with each edge pointed from its smaller node to its larger, and all its data.""" + D = nx.DiGraph() + D.graph.update(G.graph) + D.add_nodes_from(G.nodes(data=True)) + D.add_edges_from((min(u, v), max(u, v), data) for u, v, data in G.edges(data=True)) + return D + + def operands(name, build): """`name`'s arguments with `build()` as the graph, plus what else the name needs.""" G = build() if name == "reverse": return (G.to_directed(),) + if name in {"transitive_closure_dag", "transitive_reduction"}: + return (_acyclic(G),) if name in {"disjoint_union", "full_join", "union"}: return (G, nx.relabel_nodes(build(), lambda node: f"b{node}")) if name in {"compose", "difference", "intersection", "symmetric_difference"}: diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py index 4bf5d09..f992531 100644 --- a/graphblas_algorithms/tests/test_match_nx.py +++ b/graphblas_algorithms/tests/test_match_nx.py @@ -586,6 +586,11 @@ def test_signatures_match_nx(): ] +# Their results are NetworkX graphs, built here: test_transitive_closure checks them against +# NetworkX's. +_RETURNS_A_NETWORKX_GRAPH = ["transitive_closure", "transitive_closure_dag", "transitive_reduction"] + + def test_the_graph_returning_names_are_the_ones_networkx_says(): from networkx.utils.backends import _registered_algorithms @@ -594,7 +599,7 @@ def test_the_graph_returning_names_are_the_ones_networkx_says(): for name in dispatcher_functions() if getattr(_registered_algorithms.get(name), "_returns_graph", False) } - assert returns_graph == set(_RETURNS_GRAPH) + assert returns_graph == set(_RETURNS_GRAPH) | set(_RETURNS_A_NETWORKX_GRAPH) def _edges(G):