From be2dec2113be6ce1b04d293dfafaf320802dd66f Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 21:03:23 -0600 Subject: [PATCH] Add is_aperiodic, flow_hierarchy and kosaraju components is_aperiodic: in a strongly connected graph every walk from node 0 to a node v has the same length modulo the period, the gcd of the cycle lengths. With level[v] the depth of v in a breadth-first walk from node 0, the period is the gcd of level[u] + 1 - level[v] over the edges (u, v): one NumPy reduction over the edge list, where a self-loop gives 1. The walk takes a GraphBLAS round a level; a long thin one, as around a cycle, goes to a queue in Python, priced as is_strongly_connected's walks are. The errors are NetworkX's: NetworkXPointlessConcept for a graph without nodes, NetworkXError for one that is not strongly connected, and NetworkX 3.6.1's NetworkXError for an undirected graph (later versions refuse one before dispatching). flow_hierarchy: an edge lies on a cycle exactly when its ends share a strongly connected component, as a self-loop's do, so the answer is 1 less the weight of those edges over all the weight, read off the component labels. Without weights, or with integer ones, both sums are exact, and the value is NetworkX's while its sums stay below 2**53. Float weights of one sign agree within the rounding of the sums, and a NaN weight gives NaN, as in NetworkX. Left to NetworkX: weights that sum to 0, where NetworkX raises ZeroDivisionError for Python numbers and gives NaN for NumPy ones, which a conversion does not tell apart; float weights of both signs, whose sums can cancel to what the order of summation decides; float weights whose sum passes half the float range, where NetworkX's sum of degrees overflows; and complex weights. kosaraju_strongly_connected_components yields the components from the same labels as strongly_connected_components, in an order that may differ from NetworkX's. A source is left to NetworkX: NetworkX dev keeps its walk to the nodes that reach the source and yields their components, while 3.7 and earlier step past them, so the sets differ. --- README.md | 6 +- _nx_graphblas/__init__.py | 5 + _nx_graphblas/core.py | 9 + graphblas_algorithms/algorithms/__init__.py | 1 + graphblas_algorithms/algorithms/dag.py | 63 ++- graphblas_algorithms/algorithms/hierarchy.py | 14 + graphblas_algorithms/interface.py | 8 + graphblas_algorithms/nxapi/__init__.py | 1 + .../nxapi/components/strongly_connected.py | 21 + graphblas_algorithms/nxapi/dag.py | 18 +- graphblas_algorithms/nxapi/hierarchy.py | 77 +++ .../nxapi/tests/test_aperiodic_flow.py | 463 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 3 + 13 files changed, 683 insertions(+), 6 deletions(-) create mode 100644 graphblas_algorithms/algorithms/hierarchy.py create mode 100644 graphblas_algorithms/nxapi/hierarchy.py create mode 100644 graphblas_algorithms/nxapi/tests/test_aperiodic_flow.py diff --git a/README.md b/README.md index 8651a2e..6ae4dad 100644 --- a/README.md +++ b/README.md @@ -183,6 +183,7 @@ graphblas_algorithms.nxapi │ ├── strongly_connected │ │ ├── condensation │ │ ├── is_strongly_connected +│ │ ├── kosaraju_strongly_connected_components │ │ ├── number_strongly_connected_components │ │ └── strongly_connected_components │ └── weakly_connected @@ -208,7 +209,8 @@ graphblas_algorithms.nxapi │ └── volume ├── dag │ ├── ancestors -│ └── descendants +│ ├── descendants +│ └── is_aperiodic ├── distance_measures │ ├── center │ ├── diameter @@ -225,6 +227,8 @@ graphblas_algorithms.nxapi ├── generators │ └── ego │ └── ego_graph +├── hierarchy +│ └── flow_hierarchy ├── isolate │ ├── is_isolate │ ├── isolates diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index fcc51cf..1978f1f 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -74,6 +74,7 @@ def get_info(): "eigenvector_centrality", "fast_could_be_isomorphic", "faster_could_be_isomorphic", + "flow_hierarchy", "floyd_warshall", "floyd_warshall_numpy", "floyd_warshall_predecessor_and_distance", @@ -95,6 +96,7 @@ def get_info(): "inter_community_edges", "intersection", "intra_community_edges", + "is_aperiodic", "is_arborescence", "is_attracting_component", "is_branching", @@ -121,6 +123,7 @@ def get_info(): "k_shell", "k_truss", "katz_centrality", + "kosaraju_strongly_connected_components", "laplacian_matrix", "local_efficiency", "lowest_common_ancestor", @@ -219,6 +222,7 @@ def get_info(): "edge_betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\nThe edges come by their first ends in node order, then by their second ends in node\norder, which may differ from the order of `G.edges()`.", "edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.", "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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.', + "flow_hierarchy": "Integer weights, or none, give NetworkX's value exactly; float weights of one sign agree\nto within the rounding of their sums. Left to NetworkX: float weights of both signs,\nwhose sums can cancel; weights that sum to 0, where NetworkX raises ZeroDivisionError\nfor Python numbers and gives NaN for NumPy ones; float weights whose sum is past half\nthe float range; and complex weights.", "floyd_warshall": "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.", "floyd_warshall_predecessor_and_distance": "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.", "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", @@ -232,6 +236,7 @@ def get_info(): "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "kosaraju_strongly_connected_components": "The components come by their first node, an order that may differ from NetworkX's. A `source` is left to NetworkX, whose versions differ on it.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index d2ff12d..f8d8468 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -159,6 +159,13 @@ "call raises OverflowError rather than add integer weights where the number of nodes\n" "times the heaviest absolute weight reaches 2**62, as a length could then pass 2**63." ), + "flow_hierarchy": ( + "Integer weights, or none, give NetworkX's value exactly; float weights of one sign agree\n" + "to within the rounding of their sums. Left to NetworkX: float weights of both signs,\n" + "whose sums can cancel; weights that sum to 0, where NetworkX raises ZeroDivisionError\n" + "for Python numbers and gives NaN for NumPy ones; float weights whose sum is past half\n" + "the float range; and complex weights." + ), "floyd_warshall": _PATH_OVERFLOW, "floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW, "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", @@ -175,6 +182,8 @@ "k_corona": _CORE_SUBGRAPH, "k_crust": _CORE_SUBGRAPH, "k_shell": _CORE_SUBGRAPH, + "kosaraju_strongly_connected_components": _COMPONENT_ORDER + + " A `source` is left to NetworkX, whose versions differ on it.", "local_efficiency": ( "The cost is the breadth-first levels times the chunks of walks, so a node whose\n" "neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n" diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..9b87c4e 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -10,6 +10,7 @@ from .distance_measures import * from .dominating import * from .efficiency_measures import * +from .hierarchy import * from .isolate import * from .isomorphism import * from .link_analysis import * diff --git a/graphblas_algorithms/algorithms/dag.py b/graphblas_algorithms/algorithms/dag.py index 9483e70..94451ab 100644 --- a/graphblas_algorithms/algorithms/dag.py +++ b/graphblas_algorithms/algorithms/dag.py @@ -1,9 +1,11 @@ +import numpy as np from graphblas import Vector, replace from graphblas.semiring import any_pair -from ._bfs import _bfs_plain +from ._bfs import _adjacency, _bfs_plain, _visited +from .components.strongly_connected import _WALK_ROUND, _Budget -__all__ = ["ancestors", "descendants", "is_acyclic"] +__all__ = ["ancestors", "descendants", "is_acyclic", "is_aperiodic"] def descendants(G, source): @@ -44,3 +46,60 @@ def is_acyclic(G): alive(~peel.S, replace) << alive cache["is_acyclic"] = True return True + + +def is_aperiodic(G): + """Whether the lengths of the cycles of a strongly connected `G` have no common factor above 1. + + In a strongly connected graph every walk from node 0 to a node `v` has the same length + modulo the period (the greatest common divisor of the cycle lengths), so with `level[v]` + the length of any one of them, the period divides `level[u] + 1 - level[v]` for every edge + `(u, v)`. And the gcd of that over the edges divides every cycle's length, the sum of it + around the cycle. So that gcd is the period; the edges of the walk's own tree give 0, and a + self-loop 1. `G` must be strongly connected and have a node. + """ + level = _levels(G) + rows, cols, _values = G._A.to_coo(values=False) + return int(np.gcd.reduce(level[rows] + 1 - level[cols])) == 1 + + +def _levels(G): + """Each node's depth in a breadth-first walk from node 0, which must reach every node. + + A GraphBLAS round a level; a long thin walk, as around a cycle, goes to a walk in Python + instead, priced as `is_strongly_connected`'s walks are. + """ + A = _adjacency(G) + n = A.nrows + budget = _Budget(n + A.nvals) + level = _visited(Vector(np.int64, n, name="level")) + q = Vector(bool, n, name="q") + level[0] = 0 + q[0] = True + depth = 0 + budget.start() + while True: + q(~level.S, replace) << any_pair(q @ A) + if q.nvals == 0: + return level.to_dense() + if not budget.spend(_WALK_ROUND, q.nvals): + return _sequential_levels(A) + depth += 1 + level(q.S) << depth + + +def _sequential_levels(A): + """`_levels` by a queue in Python, for walks with many thin levels.""" + indptr, indices, _values = A.to_csr() + indptr = indptr.tolist() + indices = indices.tolist() + level = [-1] * A.nrows + level[0] = 0 + queue = [0] + for u in queue: # the queue grows as it is read + depth = level[u] + 1 + for w in indices[indptr[u] : indptr[u + 1]]: + if level[w] < 0: + level[w] = depth + queue.append(w) + return np.array(level, np.int64) diff --git a/graphblas_algorithms/algorithms/hierarchy.py b/graphblas_algorithms/algorithms/hierarchy.py new file mode 100644 index 0000000..c3c4f38 --- /dev/null +++ b/graphblas_algorithms/algorithms/hierarchy.py @@ -0,0 +1,14 @@ +from .components.strongly_connected import component_labels + +__all__ = ["flow_hierarchy"] + + +def flow_hierarchy(G): + """The values of `G`'s edges, as an array, and whether each lies on a cycle. + + An edge lies on a cycle exactly when its ends are in one strongly connected component, as + a self-loop's are. + """ + labels = component_labels(G) + rows, cols, values = G._A.to_coo() + return values, labels[rows] == labels[cols] diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 04a8d43..ad7b93f 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -287,6 +287,9 @@ class Dispatcher: is_semiconnected = mod.semiconnected.is_semiconnected condensation = mod.strongly_connected.condensation is_strongly_connected = mod.strongly_connected.is_strongly_connected + kosaraju_strongly_connected_components = ( + mod.strongly_connected.kosaraju_strongly_connected_components + ) number_strongly_connected_components = ( mod.strongly_connected.number_strongly_connected_components ) @@ -320,6 +323,7 @@ class Dispatcher: # ============= ancestors = mod.ancestors descendants = mod.descendants + is_aperiodic = mod.is_aperiodic mod = nxapi.distance_measures # =========================== @@ -344,6 +348,10 @@ class Dispatcher: # ==================== ego_graph = mod.ego.ego_graph + mod = nxapi.hierarchy + # =================== + flow_hierarchy = mod.flow_hierarchy + mod = nxapi.isolate # ================= is_isolate = mod.is_isolate diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..0d71f4e 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -10,6 +10,7 @@ from .dominating import * from .efficiency_measures import * from .generators import * +from .hierarchy import * from .isolate import * from .isomorphism import fast_could_be_isomorphic, faster_could_be_isomorphic from .linalg import * diff --git a/graphblas_algorithms/nxapi/components/strongly_connected.py b/graphblas_algorithms/nxapi/components/strongly_connected.py index 42469f4..486a22d 100644 --- a/graphblas_algorithms/nxapi/components/strongly_connected.py +++ b/graphblas_algorithms/nxapi/components/strongly_connected.py @@ -12,6 +12,7 @@ __all__ = [ "condensation", "is_strongly_connected", + "kosaraju_strongly_connected_components", "number_strongly_connected_components", "strongly_connected_components", ] @@ -38,6 +39,26 @@ def strongly_connected_components(G): yield from algorithms.strongly_connected_components(G) +def _no_source(bound): + if bound.get("source") is not None: + # NetworkX dev keeps the walk to the nodes that reach `source`; 3.7 and earlier step + # past them, so their sets depend on the order of the walk. + return ( + "kosaraju_strongly_connected_components from a source differs between NetworkX " + "versions; networkx serves it" + ) + return None + + +@can_run(_no_source) +@not_implemented_for("undirected") +def kosaraju_strongly_connected_components(G, source=None): + if (reason := _no_source({"source": source})) is not None: + raise NotImplementedError(reason) + G = to_directed_graph(G) + yield from algorithms.strongly_connected_components(G) + + def _no_scc(bound): if bound.get("scc") is not None: return "condensation numbers its own components; networkx serves a given `scc`" diff --git a/graphblas_algorithms/nxapi/dag.py b/graphblas_algorithms/nxapi/dag.py index d00734f..52ab43a 100644 --- a/graphblas_algorithms/nxapi/dag.py +++ b/graphblas_algorithms/nxapi/dag.py @@ -1,9 +1,9 @@ from graphblas_algorithms import algorithms -from graphblas_algorithms.classes.digraph import to_graph +from graphblas_algorithms.classes.digraph import to_directed_graph, to_graph -from .exception import NetworkXError +from .exception import NetworkXError, NetworkXPointlessConcept -__all__ = ["ancestors", "descendants"] +__all__ = ["ancestors", "descendants", "is_aperiodic"] def descendants(G, source): @@ -24,3 +24,15 @@ def ancestors(G, source): raise NetworkXError(*e.args) from e else: return G.vector_to_nodeset(result) + + +def is_aperiodic(G): + if not G.is_directed(): + # NetworkX 3.6.1's words. Later versions refuse an undirected graph before dispatching. + raise NetworkXError("is_aperiodic not defined for undirected graphs") + G = to_directed_graph(G) + if len(G) == 0: + raise NetworkXPointlessConcept("Graph has no nodes.") + if not algorithms.is_strongly_connected(G): + raise NetworkXError("Graph is not strongly connected.") + return algorithms.is_aperiodic(G) diff --git a/graphblas_algorithms/nxapi/hierarchy.py b/graphblas_algorithms/nxapi/hierarchy.py new file mode 100644 index 0000000..6f3e234 --- /dev/null +++ b/graphblas_algorithms/nxapi/hierarchy.py @@ -0,0 +1,77 @@ +import math + +import numpy as np + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.digraph import to_graph + +from .exception import NetworkXError + +__all__ = ["flow_hierarchy"] + + +def flow_hierarchy(G, weight=None): + """1 less the share of the edges' weight that lies on cycles, as NetworkX finds it. + + NetworkX sums each strongly connected component's subgraph size and divides by the graph's. + Integer weights, or none, give its value exactly: both sums are exact here, and so are + NetworkX's while they stay below 2**53, so both divide the same integers. Float weights of + one sign agree to within about `4 * m * 2**-53`, for `m` edges, the rounding of the sums. + """ + G = to_graph(G, weight=weight) + if G._A.nvals == 0: + raise NetworkXError("flow_hierarchy not applicable to empty graphs") + if not G.is_directed(): + raise NetworkXError("G must be a digraph in flow_hierarchy") + reads_values = weight is not None and weight == G._weight + if reads_values and G._A.dtype.np_type.kind == "c": + raise NotImplementedError( + f"Edge attribute {weight!r} has complex values; networkx serves the call" + ) + values, on_cycle = algorithms.flow_hierarchy(G) + if not reads_values: + # NetworkX's sizes are then ints, and so is its division's numerator. + return 1 - int(on_cycle.sum()) / len(values) + if values.dtype.kind == "f": + return _float_hierarchy(values, on_cycle) + total = _exact_sum(values) + if total == 0: + raise NotImplementedError(_ZERO) + return 1 - _exact_sum(values[on_cycle]) / total + + +_ZERO = ( + "flow_hierarchy where the weights sum to 0: NetworkX raises ZeroDivisionError for Python " + "numbers and gives NaN for NumPy ones, which a conversion does not tell apart; networkx " + "serves it" +) + + +def _exact_sum(values): + """The sum of integer (or bool) `values` as a Python int.""" + if values.size == 0: + return 0 + largest = max(abs(int(values.min())), abs(int(values.max()))) + if largest * values.size < 2**63: + return int(values.sum(dtype=np.int64)) + return sum(values.tolist()) + + +def _float_hierarchy(values, on_cycle): + if np.isnan(values).any(): + return math.nan # NetworkX's sums are NaN, and so is what it divides + if (values < 0).any() and (values > 0).any(): + raise NotImplementedError( + "flow_hierarchy on float weights of both signs, whose sums can cancel to what " + "NetworkX's order of summation decides; networkx serves it" + ) + finite = values[np.isfinite(values)] + if not float(np.abs(finite).sum()) < 2.0**1023: + # NetworkX sums each edge twice (once each way) before halving, and would overflow. + raise NotImplementedError( + "flow_hierarchy on weights whose sum is past half the float range; networkx serves it" + ) + total = float(values.sum()) + if total == 0: + raise NotImplementedError(_ZERO) + return 1 - float(values[on_cycle].sum()) / total diff --git a/graphblas_algorithms/nxapi/tests/test_aperiodic_flow.py b/graphblas_algorithms/nxapi/tests/test_aperiodic_flow.py new file mode 100644 index 0000000..a1149e0 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_aperiodic_flow.py @@ -0,0 +1,463 @@ +"""is_aperiodic, flow_hierarchy and kosaraju_strongly_connected_components against NetworkX. + +is_aperiodic's answer and errors must be NetworkX's exactly. So must flow_hierarchy's with +integer weights or none (both sides divide the same integers); with float weights of one sign +it agrees within ``4 * m * 2**-53`` for `m` edges, the rounding of its sums. The components +from kosaraju_strongly_connected_components must be NetworkX's as a partition, in any order. +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. +""" + +import math +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga + +pytestmark = pytest.mark.filterwarnings( + "ignore:Note. conversions to backend graphs", + "ignore:invalid value encountered", + "ignore:overflow encountered", +) + + +@contextmanager +def graphblas_first(): + """Put this backend first for algorithms; a decline goes to NetworkX.""" + config = nx.config + saved = list(config.backend_priority.algos), config.fallback_to_nx + config.backend_priority.algos = ["graphblas"] + config.fallback_to_nx = False + try: + yield + finally: + config.backend_priority.algos, config.fallback_to_nx = saved + + +def call(name, G, backend=None, **kwargs): + """The answer of one call: ("value", result) or ("error", type, message).""" + if backend is not None: + kwargs["backend"] = backend + try: + result = getattr(nx, name)(G, **kwargs) + if name == "kosaraju_strongly_connected_components": + assert type(result).__name__ == "generator" + result = list(result) + assert all(type(c) is set for c in result) + result = sorted(map(sorted, result), key=repr) + except Exception as e: + return ("error", type(e), str(e)) + else: + return ("value", result) + + +def approx(x): + return pytest.approx(x, rel=1e-12) + + +def assert_same(got, expected, tolerance=0.0): + if expected[0] == "value" and got[0] == "value": + a, b = got[1], expected[1] + if isinstance(b, float): + assert isinstance(a, float) + if math.isnan(b): + assert math.isnan(a) + elif tolerance: + assert a == pytest.approx(b, rel=0, abs=tolerance) + else: + # Not `==`: NetworkX's own answer on the priority path, after a decline, has + # differed from its direct one in the last bit (NetworkX 3.6.1, Python 3.11). + assert a == approx(b) + else: + assert type(a) is type(b) + assert a == b + else: + assert got == expected + + +def check(name, G, tolerance=0.0, **kwargs): + """Served by this backend, with NetworkX's answer or error, both ways.""" + expected = call(name, G, "networkx", **kwargs) + got = call(name, G, "graphblas", **kwargs) + if got[0] == "error": + assert got[1] is not NotImplementedError, got + assert_same(got, expected, tolerance) + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same(call(name, G, **kwargs), expected, tolerance) + return expected + + +def left_to_networkx(name, G, reason, **kwargs): + """Declined: the backend says why, and NetworkX's answer (or error) comes back.""" + from graphblas_algorithms.interface import Dispatcher + + expected = call(name, G, "networkx", **kwargs) + declined = Dispatcher.can_run(name, (G,), kwargs) + if declined is True: # declined once converted + with pytest.raises(NotImplementedError) as info: + getattr(nx, name)(G, backend="graphblas", **kwargs) + declined = str(info.value.__cause__ or info.value) + assert reason in declined + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same(call(name, G, **kwargs), expected) + return expected + + +def float_tolerance(G): + return 4 * max(G.number_of_edges(), 1) * 2**-53 + + +def random_digraph(seed): + """A random digraph, its labels and the kind of its weights. + + Shapes by seed: a random digraph (rarely strongly connected); a cycle through every node + with chords (strongly connected, usually aperiodic); a cycle through `k` classes of nodes + with chords only from one class to the next (strongly connected with period a multiple of + `k`), sometimes with one chord more; a few cycles joined by one-way edges. Some graphs have + self-loops, and the random and joined shapes may have isolated nodes. Labels by seed: + shuffled ints, strings or tuples. Weights by seed: none, ints from 0, ints of both signs, + positive floats, floats of both signs (declined), bools. + """ + rng = np.random.default_rng(seed) + shape = seed % 4 + k = int(rng.integers(2, 5)) + n = k * int(rng.integers(1, 11)) if shape == 2 else int(rng.integers(1, 41)) + order = rng.permutation(n).tolist() + G = nx.DiGraph() + G.add_nodes_from(order) + if shape == 0: + p = float(rng.choice([0.02, 0.05, 0.1, 0.2])) + G.add_edges_from((u, v) for u in range(n) for v in range(n) if u != v and rng.random() < p) + elif shape == 1: + if n > 1: + nx.add_cycle(G, order) + for _ in range(int(rng.integers(0, n + 1))): + G.add_edge(*map(int, rng.integers(n, size=2))) + elif shape == 2: + if n > 1: + nx.add_cycle(G, order) + place = {v: i for i, v in enumerate(order)} + for _ in range(int(rng.integers(0, 2 * n + 1))): + u, v = map(int, rng.integers(n, size=2)) + if (place[v] - place[u] - 1) % k == 0: + G.add_edge(u, v) + if rng.random() < 0.3: + G.add_edge(*map(int, rng.integers(n, size=2))) # may break the period, or change it + else: + start = 0 + while start < n: + size = int(rng.integers(1, 6)) + if size > 1: + nx.add_cycle(G, order[start : start + size]) + if start and rng.random() < 0.8: + G.add_edge(order[int(rng.integers(start))], order[start]) + start += size + if rng.random() < 0.3: + for v in range(n): + if rng.random() < 0.1: + G.add_edge(v, v) + weights = seed // 12 % 6 + for u, v in G.edges: + if weights == 1: + G.edges[u, v]["weight"] = int(rng.integers(0, 5)) + elif weights == 2: + G.edges[u, v]["weight"] = int(rng.integers(-3, 6)) + elif weights == 3: + G.edges[u, v]["weight"] = float(rng.uniform(0.1, 3.0)) + elif weights == 4: + G.edges[u, v]["weight"] = float(rng.normal(1.0, 2.0)) + elif weights == 5: + G.edges[u, v]["weight"] = rng.random() < 0.7 + labels = seed // 4 % 3 + if labels == 1: + G = nx.relabel_nodes(G, {v: f"n{v}" for v in G}) + elif labels == 2: + G = nx.relabel_nodes(G, {v: (v % 3, f"x{v}") for v in G}) + return G, weights + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_digraphs(seed): + G, weights = random_digraph(seed) + check("is_aperiodic", G) + check("flow_hierarchy", G) + check("kosaraju_strongly_connected_components", G) + values = [w for _u, _v, w in G.edges(data="weight", default=1)] + if weights == 4 and min(values) < 0 < max(values): + left_to_networkx("flow_hierarchy", G, "float weights of both signs", weight="weight") + elif sum(values) == 0 and values: + left_to_networkx("flow_hierarchy", G, "the weights sum to 0", weight="weight") + else: + tolerance = float_tolerance(G) if weights in (3, 4) else 0.0 + check("flow_hierarchy", G, tolerance, weight="weight") + if len(G): + source = next(iter(G)) + left_to_networkx( + "kosaraju_strongly_connected_components", G, "differs between NetworkX", source=source + ) + + +@pytest.mark.parametrize( + ("edges", "expected"), + [ + ([(1, 2), (2, 1)], False), + ([(1, 2), (2, 3), (3, 1), (1, 4), (4, 1)], True), + ([(1, 2), (2, 3), (3, 1), (2, 1), (1, 4), (4, 2)], True), + ([(0, 0)], True), + ([(0, 1), (1, 2), (2, 0), (0, 3), (3, 4), (4, 5), (5, 0)], True), + ([(0, 1), (1, 2), (2, 3), (3, 0), (0, 4), (4, 5), (5, 6), (6, 7), (7, 8), (8, 0)], False), + ], +) +def test_aperiodic_examples(edges, expected): + assert check("is_aperiodic", nx.DiGraph(edges)) == ("value", expected) + + +def test_aperiodic_one_node(): + G = nx.empty_graph(1, create_using=nx.DiGraph) + assert check("is_aperiodic", G) == ("value", False) + G.add_edge(0, 0) + assert check("is_aperiodic", G) == ("value", True) + + +def test_aperiodic_errors(): + assert check("is_aperiodic", nx.DiGraph()) == ( + "error", + nx.NetworkXPointlessConcept, + "Graph has no nodes.", + ) + not_strongly = ("error", nx.NetworkXError, "Graph is not strongly connected.") + assert check("is_aperiodic", nx.DiGraph([(0, 1), (1, 0), (1, 2)])) == not_strongly + assert check("is_aperiodic", nx.empty_graph(2, create_using=nx.DiGraph)) == not_strongly + G = nx.DiGraph([(0, 1), (1, 0)]) + G.add_node(2) + assert check("is_aperiodic", G) == not_strongly + # NetworkX 3.7 and later refuse these before dispatching; 3.6.1 hands them to the backend. + assert check("is_aperiodic", nx.path_graph(3))[1] in ( + nx.NetworkXNotImplemented, + nx.NetworkXError, + ) + assert check("is_aperiodic", nx.Graph())[0] == "error" + from graphblas_algorithms import nxapi + + with pytest.raises(nx.NetworkXError, match="is_aperiodic not defined for undirected graphs"): + nxapi.is_aperiodic(ga.Graph.from_networkx(nx.cycle_graph(3))) + + +@pytest.mark.parametrize("n", [500, 3000]) +def test_aperiodic_long_cycles(n): + # Thousands of thin levels: the walk goes to the queue in Python, and the answer is the same. + G = nx.cycle_graph(n, create_using=nx.DiGraph) + assert check("is_aperiodic", G) == ("value", False) + G.add_edge(n // 2, 0) # a cycle of n // 2 + 1 beside one of n + expected = math.gcd(n, n // 2 + 1) == 1 + assert check("is_aperiodic", G) == ("value", expected) + G.add_edge(1, 1) + assert check("is_aperiodic", G) == ("value", True) + + +def test_long_thin_walks_go_to_the_queue(monkeypatch): + from graphblas_algorithms.algorithms import dag + + calls = [] + sequential = dag._sequential_levels + + def counted(A): + calls.append(A.nrows) + return sequential(A) + + monkeypatch.setattr(dag, "_sequential_levels", counted) + H = ga.DiGraph.from_networkx(nx.cycle_graph(3000, create_using=nx.DiGraph)) + assert dag._levels(H).tolist() == list(range(3000)) + assert calls == [3000] + calls.clear() + G = nx.gnp_random_graph(2000, 0.005, seed=3, directed=True) + nx.add_cycle(G, range(2000)) + H = ga.DiGraph.from_networkx(G) + assert dict(enumerate(dag._levels(H).tolist())) == nx.single_source_shortest_path_length(G, 0) + assert calls == [] + + +def test_levels_by_queue_match_the_walk(): + from graphblas_algorithms.algorithms._bfs import _adjacency + from graphblas_algorithms.algorithms.dag import _levels, _sequential_levels + + for seed in range(40): + G = nx.gnp_random_graph(60, 0.08, seed=seed, directed=True) + nx.add_cycle(G, range(60)) + H = ga.DiGraph.from_networkx(G) + expected = nx.single_source_shortest_path_length(G, 0) + levels = _levels(H) + assert dict(enumerate(levels.tolist())) == expected + assert (_sequential_levels(_adjacency(H)) == levels).all() + + +@pytest.mark.parametrize( + "G", + [ + nx.gnp_random_graph(800, 0.01, seed=1, directed=True), + nx.DiGraph(nx.complete_bipartite_graph(30, 40)), + nx.grid_2d_graph(20, 20, periodic=True, create_using=nx.DiGraph), + nx.DiGraph(nx.grid_2d_graph(15, 15, periodic=True)), + nx.scale_free_graph(1000, seed=2), + ], + ids=["gnp", "bipartite", "torus_one_way", "torus_both_ways", "scale_free"], +) +def test_larger_graphs(G): + if G.is_multigraph(): + G = nx.DiGraph(G) + check("is_aperiodic", G) + check("flow_hierarchy", G) + check("kosaraju_strongly_connected_components", G) + if nx.is_strongly_connected(G): + sub = G + else: + sub = G.subgraph(max(nx.strongly_connected_components(G), key=len)).copy() + check("is_aperiodic", sub) + + +def test_flow_hierarchy_errors(): + empty = ("error", nx.NetworkXError, "flow_hierarchy not applicable to empty graphs") + assert check("flow_hierarchy", nx.DiGraph()) == empty + assert check("flow_hierarchy", nx.empty_graph(3, create_using=nx.DiGraph)) == empty + # NetworkX looks for edges before it looks at the direction. + assert check("flow_hierarchy", nx.empty_graph(3)) == empty + assert check("flow_hierarchy", nx.path_graph(3)) == ( + "error", + nx.NetworkXError, + "G must be a digraph in flow_hierarchy", + ) + assert check("flow_hierarchy", nx.Graph([(0, 0)]))[2] == "G must be a digraph in flow_hierarchy" + + +def test_flow_hierarchy_values(): + assert check("flow_hierarchy", nx.DiGraph([(0, 1), (1, 2)])) == ("value", approx(1.0)) + assert check("flow_hierarchy", nx.cycle_graph(4, create_using=nx.DiGraph)) == ( + "value", + approx(0.0), + ) + assert check("flow_hierarchy", nx.DiGraph([(0, 0), (0, 1)])) == ("value", approx(0.5)) + G = nx.DiGraph([(0, 1, {"weight": 2}), (1, 0, {"weight": 3}), (1, 2, {"weight": 5})]) + assert check("flow_hierarchy", G, weight="weight") == ("value", approx(0.5)) + assert check("flow_hierarchy", G) == ("value", approx(1 - 2 / 3)) + assert check("flow_hierarchy", G, weight="absent") == ("value", approx(1 - 2 / 3)) + G.add_edge(2, 2, other=7) + check("flow_hierarchy", G, weight="weight") + check("flow_hierarchy", G, weight="other") + + +@pytest.mark.parametrize( + "weights", + [ + [True, True, False, True], + [2**62, 2**62, 2**62, 1], + [-1, -2, -3, -4], + [-1.5, -0.25, -3.0, -4.0], + [0.0, 1e-300, 2.5, 1e300], + [3, -1, 4, -1], + [np.float64(0.5), np.float64(2), np.float64(1), np.float64(3)], + [np.int64(5), np.int64(1), np.int64(2), np.int64(3)], + ], +) +def test_flow_hierarchy_weights(weights): + G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 3)]) + for (u, v), w in zip(G.edges, weights, strict=True): + G.edges[u, v]["weight"] = w + expected = call("flow_hierarchy", G, "networkx", weight="weight") + got = call("flow_hierarchy", G, "graphblas", weight="weight") + assert got[0] == expected[0] == "value" + assert type(got[1]) is float # NetworkX gives np.float64 for NumPy weights + assert got[1] == pytest.approx(expected[1], rel=0, abs=float_tolerance(G)) + check("flow_hierarchy", G, float_tolerance(G), weight="weight") + + +@pytest.mark.parametrize( + ("weights", "expected"), + [ + ([1.0, float("nan"), 1.0, 1.0], "nan"), + ([float("nan"), -1.0, 2.0, 1.0], "nan"), # NaN before the signs are looked at + ([1.0, 1.0, 1.0, float("nan")], "nan"), + ([float("inf"), 1.0, 1.0, 1.0], "nan"), + ([1.0, 1.0, 1.0, float("inf")], 1.0), + ([-float("inf"), -1.0, -1.0, -1.0], "nan"), + ([1e300, 1e300, 1e300, float("inf")], 1.0), + ], +) +def test_flow_hierarchy_non_finite(weights, expected): + G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 3)]) + for (u, v), w in zip(G.edges, weights, strict=True): + G.edges[u, v]["weight"] = w + status, value = check("flow_hierarchy", G, weight="weight") + assert math.isnan(value) if expected == "nan" else value == approx(expected) + + +@pytest.mark.parametrize( + ("weights", "reason"), + [ + ([0, 0, 0, 0], "the weights sum to 0"), + ([1, -1, 0, 0], "the weights sum to 0"), + ([0.0, 0.0, 0.0, 0.0], "the weights sum to 0"), + ([False, False, False, False], "the weights sum to 0"), + ([np.float64(0)] * 4, "the weights sum to 0"), + ([0.1, 0.2, -0.3, 1.0], "float weights of both signs"), + ([1.5, -1.5, 2.0, 1.0], "float weights of both signs"), + ([1e308, 1e308, 1.0, 1.0], "past half the float range"), + ([5e307, 5e307, 1.0, 1.0], "past half the float range"), + ([1 + 2j, 1.0, 1.0, 1.0], "Edge attribute 'weight' has complex values"), + ], +) +def test_flow_hierarchy_left_to_networkx(weights, reason): + G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 3)]) + for (u, v), w in zip(G.edges, weights, strict=True): + G.edges[u, v]["weight"] = w + left_to_networkx("flow_hierarchy", G, reason, weight="weight") + + +def test_flow_hierarchy_backend_graphs(): + from graphblas_algorithms import nxapi + + G = nx.DiGraph([(0, 1, {"weight": 2}), (1, 0, {"weight": 3}), (1, 2, {"weight": 5})]) + H = ga.DiGraph.from_networkx(G, weight="weight") + assert nxapi.flow_hierarchy(H, weight="weight") == approx(0.5) + assert nxapi.flow_hierarchy(H) == approx(1 - 2 / 3) # the values are not read + assert nxapi.flow_hierarchy(ga.DiGraph.from_networkx(G), weight="weight") == approx(1 - 2 / 3) + nx.set_edge_attributes(G, 1j, "weight") + with pytest.raises(NotImplementedError, match="complex values"): + nxapi.flow_hierarchy(ga.DiGraph.from_networkx(G, weight="weight"), weight="weight") + + +def test_kosaraju(): + G = nx.DiGraph([(0, 1), (1, 0), (1, 2), (2, 3), (3, 2), (4, 1), (2, 5), (6, 6)]) + G.add_node(7) + check("kosaraju_strongly_connected_components", G) + assert check("kosaraju_strongly_connected_components", nx.DiGraph()) == ("value", []) + for source in G: + left_to_networkx( + "kosaraju_strongly_connected_components", G, "differs between NetworkX", source=source + ) + left_to_networkx( + "kosaraju_strongly_connected_components", G, "differs between NetworkX", source=9 + ) + # NetworkX refuses an undirected graph before dispatching, when the generator is made. + with pytest.raises(nx.NetworkXNotImplemented): + nx.kosaraju_strongly_connected_components(nx.path_graph(3), backend="graphblas") + from graphblas_algorithms import nxapi + + gen = nxapi.kosaraju_strongly_connected_components(ga.DiGraph.from_networkx(G), source=0) + with pytest.raises(NotImplementedError, match="differs between NetworkX"): + next(gen) + + +def test_multigraphs_left_to_networkx(): + from graphblas_algorithms.interface import Dispatcher + + G = nx.MultiDiGraph([(0, 1), (1, 0), (0, 1), (1, 2)]) + for name in ("is_aperiodic", "flow_hierarchy", "kosaraju_strongly_connected_components"): + assert isinstance(Dispatcher.can_run(name, (G,), {}), str) + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same(call(name, G), call(name, G, "networkx")) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 3a012a3..6993271 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -119,6 +119,7 @@ def call_args(kind, args): "eigenvector_centrality": ("undirected", ()), "fast_could_be_isomorphic": ("undirected", (SECOND,)), "faster_could_be_isomorphic": ("undirected", (SECOND,)), + "flow_hierarchy": ("directed", ("weight",)), "floyd_warshall": ("undirected", ()), "floyd_warshall_numpy": ("undirected", ()), "floyd_warshall_predecessor_and_distance": ("undirected", ()), @@ -141,6 +142,7 @@ def call_args(kind, args): "inter_community_edges": ("undirected", ([{0, 1}, {2, 3, 4}],)), "intersection": ("plain", (SECOND,)), "intra_community_edges": ("undirected", ([{0, 1}, {2, 3, 4}],)), + "is_aperiodic": ("tournament", ()), "is_arborescence": ("dag", ()), "is_attracting_component": ("directed", ()), "is_branching": ("dag", ()), @@ -168,6 +170,7 @@ def call_args(kind, args): "k_shell": ("undirected", ()), "k_truss": ("undirected", (3,)), "katz_centrality": ("undirected", ()), + "kosaraju_strongly_connected_components": ("dag", ()), "laplacian_matrix": ("undirected", ()), "local_efficiency": ("undirected", ()), "lowest_common_ancestor": ("dag", (1, 2)),