diff --git a/README.md b/README.md index 1bc06b5..75a0ddb 100644 --- a/README.md +++ b/README.md @@ -300,6 +300,11 @@ graphblas_algorithms.nxapi │ ├── bfs_successors │ └── descendants_at_distance ├── tree +│ ├── mst +│ │ ├── maximum_spanning_edges +│ │ ├── maximum_spanning_tree +│ │ ├── minimum_spanning_edges +│ │ └── minimum_spanning_tree │ └── recognition │ ├── is_arborescence │ ├── is_branching diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..509261e 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -119,6 +119,10 @@ def get_info(): "laplacian_matrix", "local_efficiency", "lowest_common_ancestor", + "maximum_spanning_edges", + "maximum_spanning_tree", + "minimum_spanning_edges", + "minimum_spanning_tree", "mixing_expansion", "modularity", "modularity_matrix", @@ -223,6 +227,10 @@ def get_info(): "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "local_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.", + "maximum_spanning_edges": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nThe edges come lightest first (heaviest first for the maximum), and a NaN weight raises\nwhen they are first asked for, naming one NaN edge. With `data=True`, also left to\nNetworkX: a graph whose edges carry more than one attribute, or the weight on some edges\nonly, and one of fewer than 800000 edges (200000 with `data=False`), where NetworkX is\nfaster.', + "maximum_spanning_tree": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nAlso left to NetworkX: a graph whose edges carry more than one attribute, or the weight\non some edges only, and one of fewer than 800000 edges, where NetworkX is faster.', + "minimum_spanning_edges": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nThe edges come lightest first (heaviest first for the maximum), and a NaN weight raises\nwhen they are first asked for, naming one NaN edge. With `data=True`, also left to\nNetworkX: a graph whose edges carry more than one attribute, or the weight on some edges\nonly, and one of fewer than 800000 edges (200000 with `data=False`), where NetworkX is\nfaster.', + "minimum_spanning_tree": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nAlso left to NetworkX: a graph whose edges carry more than one attribute, or the weight\non some edges only, and one of fewer than 800000 edges, where NetworkX is faster.', "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.', "radius": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..f83f248 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -97,6 +97,27 @@ "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX." ) +# The spanning-tree names: what may differ from NetworkX, and what is left to it. +_SPANNING = ( + "Where weights tie, the forest may differ from NetworkX's whichever `algorithm` is named;\n" + "its total weight is the same. Equal weights are taken by their ends in node order, on\n" + "every platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\n" + "each node's neighbors were added in node order. Left to NetworkX: an int past 2**53 held\n" + "as a float that ties another weight, complex weights, an infinite weight with Boruvka\n" + '(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.' +) +_SPANNING_DATA = ( + "Also left to NetworkX: a graph whose edges carry more than one attribute, or the weight\n" + "on some edges only, and one of fewer than 800000 edges, where NetworkX is faster." +) +_SPANNING_EDGES = ( + "The edges come lightest first (heaviest first for the maximum), and a NaN weight raises\n" + "when they are first asked for, naming one NaN edge. With `data=True`, also left to\n" + "NetworkX: a graph whose edges carry more than one attribute, or the weight on some edges\n" + "only, and one of fewer than 800000 edges (200000 with `data=False`), where NetworkX is\n" + "faster." +) + # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. _ADDITIONAL_DOCS = { @@ -170,6 +191,10 @@ "neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n" "memory stays bounded." ), + "maximum_spanning_edges": _SPANNING + "\n" + _SPANNING_EDGES, + "maximum_spanning_tree": _SPANNING + "\n" + _SPANNING_DATA, + "minimum_spanning_edges": _SPANNING + "\n" + _SPANNING_EDGES, + "minimum_spanning_tree": _SPANNING + "\n" + _SPANNING_DATA, "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, diff --git a/graphblas_algorithms/algorithms/tree/__init__.py b/graphblas_algorithms/algorithms/tree/__init__.py index 7b8f387..aa613a4 100644 --- a/graphblas_algorithms/algorithms/tree/__init__.py +++ b/graphblas_algorithms/algorithms/tree/__init__.py @@ -1 +1,2 @@ +from .mst import * from .recognition import * diff --git a/graphblas_algorithms/algorithms/tree/mst.py b/graphblas_algorithms/algorithms/tree/mst.py new file mode 100644 index 0000000..ad99a55 --- /dev/null +++ b/graphblas_algorithms/algorithms/tree/mst.py @@ -0,0 +1,90 @@ +import numpy as np +from graphblas import select + +__all__ = ["maximum_spanning_edges", "minimum_spanning_edges"] + + +def _forest(rows, cols, n): + """The ranks of the minimum spanning forest of edges listed from lightest to heaviest. + + Edge `r` joins nodes `rows[r]` and `cols[r]`. No two edges share a rank, so the forest is + unique and Boruvka's rounds find it: each component takes the lightest edge leaving it, + and those edges join components without making a cycle. Each component points at the one + its edge reaches; only two components that took the same edge point at each other, so + once the lower of each such pair points at itself, every chain of pointers ends there. + """ + nodes = np.arange(n) + label = nodes # each node's component, named by one of its nodes + live = np.arange(len(rows)) # the edges that may still join two components + none = np.iinfo(np.int64).max + chosen = [] + while True: + a = label[rows[live]] + b = label[cols[live]] + crossing = a != b + live, a, b = live[crossing], a[crossing], b[crossing] + if live.size == 0: + break + lightest = np.full(n, none) + np.minimum.at(lightest, a, live) + np.minimum.at(lightest, b, live) + comps = np.flatnonzero(lightest != none) + edges = lightest[comps] + ends = label[rows[edges]] + other = np.where(ends == comps, label[cols[edges]], ends) + parent = nodes.copy() + parent[comps] = other + pair = (parent[other] == comps) & (comps < other) + parent[comps[pair]] = comps[pair] + chosen.append(edges[~pair]) + while not np.array_equal(grand := parent[parent], parent): + parent = grand + label = parent[label] + if not chosen: + return np.empty(0, np.int64) + return np.sort(np.concatenate(chosen)) + + +def _spanning_edges(G, *, maximum, ignore_nan): + A = G._A + if A.dtype.np_type.kind == "c": + raise TypeError("Complex edge weights have no order") + # A self-loop's weight is read like any other's; it never joins two components. + rows, cols, vals = select.triu(A).new().to_coo() + if vals.dtype.kind == "f" and np.isnan(vals).any(): + if not ignore_nan: + raise ValueError("NaN found as an edge weight") + keep = ~np.isnan(vals) + rows, cols, vals = rows[keep], cols[keep], vals[keep] + # A stable sort, so equal weights stay in the order `to_coo` gives, by their ends in node + # order, and the forest is the same on every platform: NumPy's default sort orders equal + # values one way on one CPU and another way on the next. Kruskal's sort keeps `G.edges()` + # order, which is this one where each node's neighbors were added in node order. + if maximum: + # Heaviest first, equal weights still in that order, as Kruskal sorts negated weights. + order = len(vals) - 1 - np.argsort(vals[::-1], kind="stable")[::-1] + else: + order = np.argsort(vals, kind="stable") + rows = rows[order] + cols = cols[order] + tree = _forest(rows, cols, A.nrows) + return rows[tree], cols[tree] + + +def minimum_spanning_edges(G, *, ignore_nan=False): + """The edges of a minimum spanning forest of undirected `G`, lightest first. + + Returns the two ends of each edge as arrays of node ids, the lower id first. Among edges + of equal weight the one whose lower id is lower, then whose higher id is lower, comes + first. A NaN weight raises ValueError, unless `ignore_nan`, which leaves those edges out. + """ + return _spanning_edges(G, maximum=False, ignore_nan=ignore_nan) + + +def maximum_spanning_edges(G, *, ignore_nan=False): + """The edges of a maximum spanning forest of undirected `G`, heaviest first. + + As `minimum_spanning_edges`, with the order of the weights reversed and equal weights + still in the same order. + """ + return _spanning_edges(G, maximum=True, ignore_nan=ignore_nan) diff --git a/graphblas_algorithms/classes/_utils.py b/graphblas_algorithms/classes/_utils.py index fa821b1..6bb3993 100644 --- a/graphblas_algorithms/classes/_utils.py +++ b/graphblas_algorithms/classes/_utils.py @@ -1,3 +1,4 @@ +import weakref from collections.abc import Mapping from itertools import islice @@ -21,6 +22,21 @@ def __repr__(self): PRESERVE = _Preserve() +# The NetworkX graph each conversion was made from, held weakly: NetworkX's cache keeps a +# conversion as long as its graph, and a pickled or copied conversion is not the one made. +_SOURCES = weakref.WeakKeyDictionary() + + +def remember_source(G, graph): + """Record that backend graph `G` was converted from NetworkX graph `graph`.""" + _SOURCES[G] = weakref.ref(graph) + + +def source_of(G): + """The NetworkX graph `G` was converted from, or None if it is unknown or gone.""" + ref = _SOURCES.get(G) + return None if ref is None else ref() + def _structure_of(G): """`G` with its values replaced by integer ones, and a cache of its own. diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..fe24099 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -21,13 +21,19 @@ ) +# Graph-returning names whose result is built from the NetworkX graph a conversion came from, +# so that it keeps that graph's own data, nodes' included; the matrix gives only the weights. +_BUILT_FROM_SOURCE = frozenset({"maximum_spanning_tree", "minimum_spanning_tree"}) + + @functools.cache def _declared(name): """What the running NetworkX declares for `name`, read once from its dispatch registry. - `signature`: of the function NetworkX dispatches, to read a call's arguments by name. - `attribute_parameters`: the parameters that name an edge attribute to read. - - `rebuilds_input`: the result is a graph that keeps its input's data. + - `rebuilds_input`: the result is a graph that keeps its input's data, rebuilt from the + matrix (not so for `_BUILT_FROM_SOURCE`). - `preserves_edge_attrs`: NetworkX asks the conversion to carry the input's edge data. - `returns_graph`: the result is a graph. @@ -50,8 +56,14 @@ def _declared(name): if name == "ego_graph": # It keeps every edge attribute, so it declares none, yet `distance` names one. attribute_parameters = ("distance",) + elif name in _BUILT_FROM_SOURCE: + attribute_parameters = ("weight",) # the same: they keep every attribute, read one # NetworkX before 3.7 declares no preserve flags for `reverse`, whose result keeps its data. - rebuilds_input = func._returns_graph and (bool(preserve) or name == "reverse") + rebuilds_input = ( + func._returns_graph + and (bool(preserve) or name == "reverse") + and name not in _BUILT_FROM_SOURCE + ) return _Declared( inspect.signature(func.orig_func), attribute_parameters, @@ -437,6 +449,10 @@ class Dispatcher: mod = nxapi.tree # ============== + maximum_spanning_edges = mod.mst.maximum_spanning_edges + maximum_spanning_tree = mod.mst.maximum_spanning_tree + minimum_spanning_edges = mod.mst.minimum_spanning_edges + minimum_spanning_tree = mod.mst.minimum_spanning_tree is_arborescence = mod.recognition.is_arborescence is_branching = mod.recognition.is_branching is_forest = mod.recognition.is_forest @@ -468,6 +484,7 @@ def convert_from_nx( graph_name=None, ): from .classes import DiGraph, Graph + from .classes._utils import remember_source # Each refusal is a NotImplementedError, the one exception NetworkX falls back on here. if not hasattr(graph, "is_directed") or not hasattr(graph, "adj"): @@ -479,6 +496,7 @@ def convert_from_nx( "graphblas-algorithms does not support multigraphs: a GraphBLAS matrix " "holds one value per node pair, so parallel edges would be combined" ) + source = graph graph = _materialize_virtual_adjacency(graph) if node_attrs: @@ -524,6 +542,9 @@ def convert_from_nx( # ask for on `reverse` when its conversion cache is off. if preserve_graph_attrs or declared.rebuilds_input: G.graph.update(graph.graph) + if graph is source: + # A snapshot's data dicts are not the caller's, so only a graph read as it is counts. + remember_source(G, graph) return G @staticmethod @@ -591,6 +612,22 @@ def can_run(name, args, kwargs): return reason return True + @staticmethod + def should_run(name, args, kwargs): + """True if serving `name` here should be faster than NetworkX, else the reason not. + + NetworkX asks only where it would convert a graph to call this backend, after `can_run` + said yes. A wrapper's own rule is its `_should_run` attribute, set with + `nxapi._utils.should_run`. + """ + hook = getattr(getattr(Dispatcher, name, None), "_should_run", None) + if hook is None: + return True + bound = _bound_args(name, args, kwargs) + if bound is None or (reason := hook(bound)) is None: + return True + return reason + @staticmethod def on_start_tests(items): """Mark the tests in NetworkX's suite that this backend cannot pass; the table is empty. diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 72f728b..b3fe7a9 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -147,6 +147,20 @@ def decorator(func): return decorator +def should_run(hook): + """Give the decorated wrapper `hook` as its rule in `Dispatcher.should_run`. + + `hook(bound)` gets the arguments as `can_run`'s hook does, and returns the reason NetworkX + should serve the call itself, as the faster of the two, or None to serve it here. + """ + + def decorator(func): + func._should_run = hook + return func + + return decorator + + def check_nodelist(G, nodelist, *, null_graph=True): """Refuse what NetworkX's `to_scipy_sparse_array` refuses, in the order it checks. diff --git a/graphblas_algorithms/nxapi/tests/test_mst.py b/graphblas_algorithms/nxapi/tests/test_mst.py new file mode 100644 index 0000000..1cf42f7 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_mst.py @@ -0,0 +1,596 @@ +"""Minimum and maximum spanning trees and their edges, against NetworkX. + +Where weights tie there are several valid forests, and this backend's may differ from +NetworkX's. So every answer is checked as a spanning forest with NetworkX's total weight +(exact for ints), and as NetworkX's own edges where the weights are distinct. The data an +answer carries is the graph's own, as NetworkX's is: the graph's dicts, never values read back +from a matrix. +""" + +import copy +import math +import pickle +from contextlib import contextmanager + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import algorithms +from graphblas_algorithms.interface import Dispatcher +from graphblas_algorithms.nxapi.tree import mst + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +TREES = ["minimum_spanning_tree", "maximum_spanning_tree"] +EDGES = ["minimum_spanning_edges", "maximum_spanning_edges"] +NAMES = TREES + EDGES +ALGORITHMS = ["kruskal", "prim", "boruvka", "bor\u016fvka"] + + +@pytest.fixture(autouse=True) +def _any_size(monkeypatch): + """Serve small graphs on the automatic path too, which `should_run` leaves to NetworkX.""" + monkeypatch.setattr(mst, "_FEWEST_EDGES", 0) + monkeypatch.setattr(mst, "_FEWEST_EDGES_WITH_DATA", 0) + + +@contextmanager +def _automatic(): + """Put this backend first, with NetworkX answering what it declines.""" + priority = nx.config.backend_priority + saved = list(priority.algos), list(priority.generators) + priority.algos = priority.generators = ["graphblas"] + try: + yield + finally: + priority.algos, priority.generators = saved + + +def _call(name, G, backend=None, **kwargs): + """The answer as a graph or a list of the edges yielded.""" + rv = getattr(nx, name)(G, backend=backend, **kwargs) + return rv if isinstance(rv, nx.Graph) else list(rv) + + +def _outcome(name, G, backend=None, **kwargs): + try: + return _call(name, G, backend, **kwargs) + except Exception as exc: + return type(exc), str(exc) + + +def _triples(result): + """`(u, v, datadict)` for each edge of a tree, or of the edges a generator yielded.""" + return list(result.edges(data=True)) if isinstance(result, nx.Graph) else result + + +def _edge_set(result): + return {frozenset((u, v)) for u, v, *_ in _triples(result)} + + +def _total(result, weight="weight"): + return sum(datadict.get(weight, 1) for _u, _v, datadict in _triples(result)) + + +def _check_forest(G, result): + """`result` is a spanning forest of `G`: G's edges, no cycle, one tree per component.""" + edges = _triples(result) + F = nx.Graph() + F.add_nodes_from(G) + F.add_edges_from((u, v) for u, v, _datadict in edges) + assert len(edges) == F.number_of_edges(), "an edge given twice" + assert all(G.has_edge(u, v) and u != v for u, v, _datadict in edges) + if len(G): + assert nx.is_forest(F) + assert nx.number_connected_components(F) == nx.number_connected_components(G) + if isinstance(result, nx.Graph): + assert list(result) == list(G) + + +def _graph(seed, weights, n=30, m=45): + """A random graph of several components, with isolated nodes and self-loops.""" + rng = np.random.default_rng(seed) + G = nx.gnm_random_graph(n, m, seed=seed) + G.add_edges_from([(0, 0), (n - 1, n - 1)]) + G.add_nodes_from([n, n + 1]) + values = { + "distinct floats": lambda: rng.normal(size=G.number_of_edges()).tolist(), + "tied ints": lambda: rng.integers(0, 3, G.number_of_edges()).tolist(), + "tied floats": lambda: [x / 4 for x in rng.integers(-2, 2, G.number_of_edges()).tolist()], + "big ints": lambda: rng.integers(-(2**62), 2**62, G.number_of_edges()).tolist(), + "tied big ints": lambda: [2**62 + int(x) for x in rng.integers(0, 3, G.number_of_edges())], + }[weights]() + for (u, v), w in zip(G.edges, values, strict=True): + G[u][v]["weight"] = w + return G + + +WEIGHTS = ["distinct floats", "tied ints", "tied floats", "big ints", "tied big ints"] + + +@pytest.mark.parametrize("seed", range(4)) +@pytest.mark.parametrize("weights", WEIGHTS) +@pytest.mark.parametrize("algorithm", ALGORITHMS) +@pytest.mark.parametrize("name", NAMES) +def test_a_spanning_forest_of_networkx_s_total_weight(name, algorithm, weights, seed): + G = _graph(seed, weights) + expected = _call(name, G, "networkx", algorithm=algorithm) + result = _call(name, G, "graphblas", algorithm=algorithm) + _check_forest(G, result) + if weights.endswith("ints"): + assert _total(result) == _total(expected) # Python ints, exact + else: + assert _total(result) == pytest.approx(_total(expected), rel=1e-12) + + +@pytest.mark.parametrize("seed", range(4)) +@pytest.mark.parametrize("weights", ["distinct floats", "big ints"]) +@pytest.mark.parametrize("algorithm", ALGORITHMS) +@pytest.mark.parametrize("name", NAMES) +def test_the_forest_is_networkx_s_where_the_weights_are_distinct(name, algorithm, weights, seed): + G = _graph(seed, weights, n=60, m=200) + expected = _call(name, G, "networkx", algorithm=algorithm) + assert _edge_set(_call(name, G, "graphblas", algorithm=algorithm)) == _edge_set(expected) + + +def _in_node_order(G): + """`G` rebuilt with each node's neighbors added in node order. + + Then `G.edges()` lists the edges by their ends in node order, the order in which Kruskal's + stable sort keeps equal weights. + """ + H = nx.Graph() + H.add_nodes_from(G.nodes(data=True)) + order = {node: i for i, node in enumerate(G)} + H.add_edges_from(sorted(G.edges(data=True), key=lambda e: sorted((order[e[0]], order[e[1]])))) + return H + + +@pytest.mark.parametrize("seed", range(4)) +@pytest.mark.parametrize("weights", ["tied ints", "tied floats", "tied big ints"]) +@pytest.mark.parametrize("name", NAMES) +def test_ties_go_as_kruskal_s_where_neighbors_were_added_in_node_order(name, weights, seed): + """Equal weights are taken by their ends in node order, as Kruskal takes `G.edges()`.""" + G = _in_node_order(_graph(seed, weights, n=60, m=200)) + expected = _call(name, G, "networkx") + assert _edge_set(_call(name, G, "graphblas")) == _edge_set(expected) + + +@pytest.mark.parametrize("name", NAMES) +def test_one_weight_on_every_edge_gives_kruskal_s_forest(name): + """Every edge ties, where a sort that is not stable would order them by the platform.""" + G = _in_node_order(nx.grid_2d_graph(8, 8)) + nx.set_edge_attributes(G, 1, "weight") + expected = _call(name, G, "networkx") + assert _edge_set(_call(name, G, "graphblas")) == _edge_set(expected) + + +def test_networkx_s_steiner_tree_tests_get_its_trees(monkeypatch): + """Mehlhorn's Steiner tree is built from two spanning forests, so it follows their ties. + + NetworkX's test lists the trees it accepts for its graphs; on G3 a forest of the same + weight with other ties gives a tree of the same weight that is not one of them. + """ + from networkx.algorithms.approximation.tests.test_steinertree import TestSteinerTree + + from graphblas_algorithms.algorithms.tree import mst as kernel + + served = [] + spanning_edges = kernel._spanning_edges + + def spy(*args, **kwargs): + served.append(True) + return spanning_edges(*args, **kwargs) + + monkeypatch.setattr(kernel, "_spanning_edges", spy) + T = TestSteinerTree + T.setup_class() + for G, terminals in [(T.G1, T.G1_term_nodes), (T.G2, T.G2_term_nodes), (T.G3, T.G3_term_nodes)]: + expected = nx.approximation.steiner_tree(G, terminals, method="mehlhorn") + with _automatic(): + result = nx.approximation.steiner_tree(G, terminals, method="mehlhorn") + assert _edge_set(result) == _edge_set(expected) + assert len(served) == 6 # two forests for each graph + + +@pytest.mark.parametrize("name", EDGES) +def test_the_edges_come_lightest_first_or_heaviest_first(name): + G = _graph(0, "tied ints", n=60, m=200) + weights = [d["weight"] for _u, _v, d in _call(name, G, "graphblas")] + assert weights == sorted(weights, reverse=name.startswith("maximum")) + + +def _rich_graph(): + """Graph, node and edge data: the weights as Python ints and floats and NumPy scalars.""" + G = nx.Graph(name="rich", tags=["a"]) + weights = [1, 2.5, np.float32(0.5), np.int16(4), 3, np.float64(7.25), True, 6] + G.add_weighted_edges_from( + (u, v, w) for (u, v), w in zip(nx.cycle_graph(8).edges, weights, strict=True) + ) + G.add_edge(0, 4, weight=10) + G.add_node(8, colour="red") + G.nodes[0]["label"] = {"nested": [1]} + return G + + +@pytest.mark.parametrize("name", TREES) +def test_the_tree_carries_the_graph_s_data_as_networkx_s_does(name): + G = _rich_graph() + expected = _call(name, G, "networkx") + result = _call(name, G, "graphblas") + assert type(result) is type(expected) + assert result.graph == expected.graph + assert result.graph is not G.graph + assert list(result.nodes(data=True)) == list(expected.nodes(data=True)) + assert result._adj == expected._adj + for u, v, datadict in result.edges(data=True): + # A copy of the graph's own dict, its values the graph's objects (no float for a + # NumPy scalar, no 1 for True), as NetworkX's `add_edges_from` makes it. + assert datadict is not G[u][v] + assert all(value is G[u][v][key] for key, value in datadict.items()) + for node, datadict in result.nodes(data=True): + assert datadict is not G.nodes[node] + assert all(value is G.nodes[node][key] for key, value in datadict.items()) + + +@pytest.mark.parametrize("keys", [True, False]) +@pytest.mark.parametrize("name", EDGES) +def test_the_edges_carry_the_graph_s_own_dicts(name, keys): + G = _rich_graph() + expected = _call(name, G, "networkx", keys=keys) + result = _call(name, G, "graphblas", keys=keys) + assert all(datadict is G[u][v] for u, v, datadict in result) + assert _edge_set(result) == _edge_set(expected) + bare = _call(name, G, "graphblas", keys=keys, data=False) + assert all(len(edge) == 2 for edge in bare) + assert {frozenset(edge) for edge in bare} == _edge_set(expected) + + +@pytest.mark.parametrize("name", EDGES) +def test_edges_with_several_attributes_are_served_without_their_data(name): + """`data=False` converts only the weight, so the other attributes are no obstacle.""" + G = _graph(1, "distinct floats") + for u, v in G.edges: + G[u][v]["colour"] = "red" + expected = _call(name, G, "networkx", data=False) + with _automatic(): + assert Dispatcher.can_run(name, (G,), {"data": False}) is True + result = _call(name, G, "graphblas", data=False) + assert {frozenset(e) for e in result} == {frozenset(e) for e in expected} + + +@pytest.mark.parametrize("name", NAMES) +def test_a_graph_whose_edges_carry_several_attributes_is_left_to_networkx(name): + """A conversion that carries the edge data holds one attribute; NetworkX's has them all.""" + G = _graph(1, "distinct floats") + for u, v in G.edges: + G[u][v]["colour"] = f"c{u}" + expected = _call(name, G, "networkx") + with pytest.raises(NotImplementedError): + _call(name, G, "graphblas") + with _automatic(): + result = _call(name, G) + assert _triples(result) == _triples(expected) + + +@pytest.mark.parametrize("name", TREES) +def test_node_data_is_carried_not_refused(name): + G = _graph(2, "distinct floats") + for node in G: + G.nodes[node]["colour"] = f"c{node}" + assert Dispatcher.can_run(name, (G,), {}) is True + result = _call(name, G, "graphblas") + assert dict(result.nodes(data=True)) == dict(G.nodes(data=True)) + + +def test_a_rebuild_is_still_refused_on_a_conversion_a_tree_left_in_the_cache(): + """A tree's conversion of a graph with node data is cached where `k_core`'s would be.""" + G = _graph(2, "distinct floats") + G.remove_edges_from(nx.selfloop_edges(G)) + G.nodes[0]["colour"] = "red" + nx.minimum_spanning_tree(G, backend="graphblas") + assert isinstance(Dispatcher.can_run("k_core", (G,), {}), str) + expected = nx.k_core(G, backend="networkx") + with _automatic(): + result = nx.k_core(G) + assert dict(result.nodes(data=True)) == dict(expected.nodes(data=True)) + + +@pytest.mark.parametrize("name", NAMES) +def test_a_directed_graph_raises_as_in_networkx(name): + D = nx.DiGraph([(0, 1, {"weight": 1})]) + with pytest.raises(nx.NetworkXNotImplemented, match="not implemented for directed type"): + _call(name, D, "networkx") + with pytest.raises(nx.NetworkXNotImplemented, match="not implemented for directed type"): + getattr(ga.nxapi, name)(D) # NetworkX raises before dispatching the edges names + with pytest.raises(nx.NetworkXNotImplemented, match="not implemented for directed type"): + getattr(Dispatcher, name)(Dispatcher.convert_from_nx(D, edge_attrs={"weight": 1})) + + +@pytest.mark.parametrize("name", NAMES) +def test_an_unknown_algorithm_raises_when_called(name): + G = _graph(0, "tied ints") + for backend in ("networkx", "graphblas"): + # Not when iterated: the generators raise before they are returned. + with pytest.raises(ValueError, match=r"^random is not a valid choice for an algorithm\.$"): + getattr(nx, name)(G, algorithm="random", backend=backend) + with pytest.raises(TypeError, match="unhashable"): + getattr(nx, name)(G, algorithm=["kruskal"], backend=backend) + + +def _nan_graph(where): + G = _graph(3, "distinct floats") + if where == "between": + G.add_edge(2, 31, weight=math.nan) + else: + G.add_edge(31, 31, weight=math.nan) + return G + + +@pytest.mark.parametrize("algorithm", ALGORITHMS) +@pytest.mark.parametrize("name", NAMES) +def test_a_nan_weight_between_two_nodes_raises_valueerror(name, algorithm): + G = _nan_graph("between") + if name in EDGES: + # When the edges are asked for, as NetworkX's generators raise. + edges = getattr(nx, name)(G, algorithm=algorithm, backend="graphblas") + with pytest.raises(ValueError, match=r"^NaN found as an edge weight. Edge \(2, 31, \{"): + next(edges) + with pytest.raises(ValueError, match=r"^NaN found as an edge weight. Edge \(2, 31, \{"): + _call(name, G, "graphblas", algorithm=algorithm) + with pytest.raises(ValueError, match=r"^NaN found as an edge weight\. Edge "): + _call(name, G, "networkx", algorithm=algorithm) + + +@pytest.mark.parametrize("where", ["between", "self-loop"]) +@pytest.mark.parametrize("algorithm", ALGORITHMS) +@pytest.mark.parametrize("name", NAMES) +def test_ignore_nan_leaves_those_edges_out(name, algorithm, where): + G = _nan_graph(where) + expected = _call(name, G, "networkx", algorithm=algorithm, ignore_nan=True) + result = _call(name, G, "graphblas", algorithm=algorithm, ignore_nan=True) + assert _edge_set(result) == _edge_set(expected) + + +@pytest.mark.parametrize("name", NAMES) +def test_a_nan_self_loop_is_read_as_each_networkx_algorithm_reads_it(name): + """Kruskal reads its weight and raises; Boruvka never reads it; Prim only at a start.""" + G = _nan_graph("self-loop") + with pytest.raises(ValueError, match=r"^NaN found as an edge weight. Edge \(31, 31, \{"): + _call(name, G, "graphblas", algorithm="kruskal") + for algorithm in ("boruvka", "bor\u016fvka"): + expected = _call(name, G, "networkx", algorithm=algorithm) + assert _edge_set(_call(name, G, "graphblas", algorithm=algorithm)) == _edge_set(expected) + with pytest.raises(NotImplementedError): + _call(name, G, "graphblas", algorithm="prim") + with _automatic(): + assert _outcome(name, G, algorithm="prim") == _outcome( + name, G, "networkx", algorithm="prim" + ) + + +# A self-loop's weight goes into the matrix's diagonal twice and comes out once, so there inf and +# -inf are NaN, and a weight past half the largest float is infinite. +LOOPS = {"nan": math.nan, "inf": math.inf, "-inf": -math.inf, "1e308": 1e308, "-1e308": -1e308} + + +def _same(G, got, want): + """`got` is `want`'s error, or a spanning forest of `G` with `want`'s edges.""" + if isinstance(want, tuple): + assert got == want + else: + _check_forest(G, got) + assert _edge_set(got) == _edge_set(want) + + +@pytest.mark.parametrize("ignore_nan", [False, True]) +@pytest.mark.parametrize("value", LOOPS) +@pytest.mark.parametrize("algorithm", ALGORITHMS) +@pytest.mark.parametrize("name", NAMES) +def test_a_self_loop_s_weight_is_the_graph_s_not_the_diagonal_s(name, algorithm, value, ignore_nan): + """Only a self-loop whose weight in the graph is NaN raises, where NetworkX reads it. + + Kruskal reads every self-loop's weight, Boruvka none, and Prim one at a node it starts a + tree from, which it picks from a set, so that is declined. + """ + G = _graph(3, "distinct floats") + for u in (0, 29, 31): # 29 has a loop already, 31 no other edge + G.add_edge(u, u, weight=LOOPS[value]) + kwargs = {"algorithm": algorithm, "ignore_nan": ignore_nan} + want = _outcome(name, G, "networkx", **kwargs) + if value == "nan" and not ignore_nan and algorithm == "kruskal": + assert want == (ValueError, "NaN found as an edge weight. Edge (0, 0, {'weight': nan})") + if value == "nan" and not ignore_nan and algorithm == "prim": + with pytest.raises(NotImplementedError) as declined: + _call(name, G, "graphblas", **kwargs) + exc = declined.value + while "starts a tree" not in str(exc): # NetworkX may raise its own, from this one + exc = exc.__cause__ or exc.__context__ + else: + _same(G, _outcome(name, G, "graphblas", **kwargs), want) + with _automatic(): + _same(G, _outcome(name, G, **kwargs), want) + + +def _infinite_graph(sign): + """A path whose middle edge, the only one joining its halves, weighs `sign` * inf.""" + G = nx.path_graph(4) + nx.set_edge_attributes(G, {(0, 1): 1.0, (1, 2): sign * math.inf, (2, 3): 2.0}, "weight") + return G + + +@pytest.mark.parametrize("name", NAMES) +def test_networkx_s_boruvka_leaves_out_an_infinite_edge_so_it_serves_that(name): + sign = -1 if name.startswith("maximum") else 1 + G = _infinite_graph(sign) + expected = _call(name, G, "networkx", algorithm="boruvka") + assert _edge_set(expected) == {frozenset((0, 1)), frozenset((2, 3))} + with pytest.raises(NotImplementedError): + _call(name, G, "graphblas", algorithm="boruvka") + with _automatic(): + assert _edge_set(_call(name, G, algorithm="boruvka")) == _edge_set(expected) + for algorithm in ("kruskal", "prim"): # these take it, and so does this backend + expected = _call(name, G, "networkx", algorithm=algorithm) + assert _edge_set(_call(name, G, "graphblas", algorithm=algorithm)) == _edge_set(expected) + # An infinite edge the other way round is one Boruvka takes. + G = _infinite_graph(-sign) + expected = _call(name, G, "networkx", algorithm="boruvka") + assert _edge_set(_call(name, G, "graphblas", algorithm="boruvka")) == _edge_set(expected) + + +@pytest.mark.parametrize("name", NAMES) +def test_complex_weights_are_left_to_networkx(name): + G = nx.path_graph(3) + nx.set_edge_attributes(G, {(0, 1): 1 + 1j, (1, 2): 2.0}, "weight") + with pytest.raises(NotImplementedError): + _call(name, G, "graphblas") + with _automatic(): + assert _outcome(name, G) == _outcome(name, G, "networkx") + + +@pytest.mark.parametrize("data", [False, True]) +@pytest.mark.parametrize("name", EDGES) +def test_ints_past_2_53_held_as_floats_are_left_to_networkx(name, data): + """2**53 + 1 beside a float becomes 2**53, tied with a weight it is greater than.""" + G = nx.Graph() + G.add_edge(0, 1, weight=2**53 + 1) + G.add_edge(1, 2, weight=2.0**53) + G.add_edge(0, 2, weight=2**53 + 2) + expected = _call(name, G, "networkx", data=data) + with pytest.raises(NotImplementedError): + _call(name, G, "graphblas", data=data) + with _automatic(): + assert _edge_set(_call(name, G, data=data)) == _edge_set(expected) + + +@pytest.mark.parametrize("name", NAMES) +def test_an_unhashable_weight_is_left_to_networkx(name): + G = _graph(0, "tied ints") + assert isinstance(Dispatcher.can_run(name, (G,), {"weight": ["weight"]}), str) + + +@pytest.mark.parametrize("weight", ["cost", None]) +@pytest.mark.parametrize("algorithm", ALGORITHMS) +@pytest.mark.parametrize("name", NAMES) +def test_a_weight_no_edge_has_is_1_for_every_edge(name, algorithm, weight): + G = _graph(5, "distinct floats") + expected = _call(name, G, "networkx", algorithm=algorithm, weight=weight) + result = _call(name, G, "graphblas", algorithm=algorithm, weight=weight) + _check_forest(G, result) + assert len(_triples(result)) == len(_triples(expected)) + + +@pytest.mark.parametrize("name", NAMES) +def test_another_attribute_is_the_weight_when_named(name): + G = _graph(6, "distinct floats") + for _u, _v, datadict in G.edges(data=True): + datadict["cost"] = -datadict.pop("weight") + expected = _call(name, G, "networkx", weight="cost") + result = _call(name, G, "graphblas", weight="cost") + assert _edge_set(result) == _edge_set(expected) + + +@pytest.mark.parametrize("name", NAMES) +def test_the_null_graph_and_a_graph_with_no_edges(name): + for G in (nx.Graph(), nx.empty_graph(3)): + expected = _call(name, G, "networkx") + result = _call(name, G, "graphblas") + assert _triples(result) == _triples(expected) + if name in TREES: + assert list(result) == list(expected) + + +@pytest.mark.parametrize("name", NAMES) +def test_a_conversion_without_its_networkx_graph_is_declined(name): + """The data comes from the graph converted, which a conversion made otherwise lacks.""" + G = _graph(0, "tied ints") + with pytest.raises(NotImplementedError, match="not converted from one that is still alive"): + getattr(Dispatcher, name)(ga.Graph.from_networkx(G, weight="weight")) + + +@pytest.mark.parametrize("name", EDGES) +def test_a_copied_graph_s_cached_conversion_does_not_give_the_original_s_data(name): + G = _graph(0, "distinct floats") + _call(name, G, "graphblas") # caches the conversion in G + unpickled = pickle.loads(pickle.dumps(G)) # noqa: S301 (bytes it made itself) + for H in (copy.deepcopy(G), unpickled): + with _automatic(): + result = _call(name, H) + assert all(datadict is H[u][v] for u, v, datadict in result) + assert _edge_set(result) == _edge_set(_call(name, G, "networkx")) + + +@pytest.mark.parametrize("name", NAMES) +def test_a_view_is_served_with_its_own_data(name): + G = _graph(7, "distinct floats") + view = G.subgraph(range(20)) + expected = _call(name, view, "networkx") + result = _call(name, view, "graphblas") + assert _edge_set(result) == _edge_set(expected) + if name in EDGES: + assert all(datadict is view[u][v] for u, v, datadict in result) + # An undirected view of a directed graph reads each edge's dict as NetworkX does. + D = nx.DiGraph() + D.add_edge(0, 1, weight=1.0) + D.add_edge(1, 0, weight=5.0) + D.add_edge(1, 2, weight=2.0) + D.add_edge(2, 0, weight=3.0) + U = D.to_undirected(as_view=True) + result, expected = _call(name, U, "graphblas"), _call(name, U, "networkx") + by_edge = {frozenset((u, v)): datadict for u, v, datadict in _triples(result)} + assert by_edge == {frozenset((u, v)): datadict for u, v, datadict in _triples(expected)} + if name in EDGES: + assert {id(datadict) for datadict in by_edge.values()} == {id(d) for *_e, d in expected} + + +@pytest.mark.parametrize("name", NAMES) +def test_a_stale_view_conversion_is_left_to_networkx(name): + """NetworkX keeps a view's cached conversion when the graph under it changes.""" + G = nx.cycle_graph(6) + nx.set_edge_attributes(G, {e: float(i) for i, e in enumerate(G.edges)}, "weight") + view = G.subgraph(range(6)) + _call(name, view, "graphblas") # caches the conversion in the view + G.remove_edge(0, 1) # its lightest edge, in every tree + with _automatic(): + assert _edge_set(_call(name, view)) == _edge_set(_call(name, view, "networkx")) + + +@pytest.mark.parametrize("name", NAMES) +def test_should_run_leaves_a_small_graph_to_networkx(name, monkeypatch): + monkeypatch.setattr(mst, "_FEWEST_EDGES", 10) + monkeypatch.setattr(mst, "_FEWEST_EDGES_WITH_DATA", 20) + small, large = nx.path_graph(15), nx.path_graph(30) # 14 and 29 edges + assert isinstance(Dispatcher.should_run(name, (small,), {}), str) + assert Dispatcher.should_run(name, (large,), {}) is True + if name in EDGES: + assert Dispatcher.should_run(name, (small,), {"data": False}) is True + assert isinstance(Dispatcher.should_run(name, (nx.path_graph(10),), {"data": False}), str) + assert Dispatcher.should_run("pagerank", (small,), {}) is True + + +def test_the_kernel_gives_ids_of_a_forest_in_weight_order(): + G = _graph(8, "distinct floats") + B = ga.Graph.from_networkx(G, weight="weight") + expected = nx.minimum_spanning_tree(G, backend="networkx") + for kernel, reverse in [ + (algorithms.minimum_spanning_edges, False), + (algorithms.maximum_spanning_edges, True), + ]: + rows, cols = kernel(B) + assert (rows < cols).all() + weights = [G[int(u)][int(v)]["weight"] for u, v in zip(rows, cols, strict=True)] + assert weights == sorted(weights, reverse=reverse) + rows, cols = algorithms.minimum_spanning_edges(B) + assert {frozenset((int(u), int(v))) for u, v in zip(rows, cols, strict=True)} == _edge_set( + expected + ) + G.add_edge(3, 3, weight=math.nan) + B = ga.Graph.from_networkx(G, weight="weight") + with pytest.raises(ValueError, match="NaN found as an edge weight"): + algorithms.minimum_spanning_edges(B) + assert len(algorithms.minimum_spanning_edges(B, ignore_nan=True)[0]) == len(expected.edges) + C = ga.Graph.from_networkx(nx.Graph([(0, 1, {"weight": 1j})]), weight="weight") + with pytest.raises(TypeError, match="Complex"): + algorithms.minimum_spanning_edges(C) diff --git a/graphblas_algorithms/nxapi/tree/__init__.py b/graphblas_algorithms/nxapi/tree/__init__.py index 7b8f387..aa613a4 100644 --- a/graphblas_algorithms/nxapi/tree/__init__.py +++ b/graphblas_algorithms/nxapi/tree/__init__.py @@ -1 +1,2 @@ +from .mst import * from .recognition import * diff --git a/graphblas_algorithms/nxapi/tree/mst.py b/graphblas_algorithms/nxapi/tree/mst.py new file mode 100644 index 0000000..b059f73 --- /dev/null +++ b/graphblas_algorithms/nxapi/tree/mst.py @@ -0,0 +1,211 @@ +from math import isnan + +import numpy as np +from graphblas import monoid, select, unary + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes._utils import source_of +from graphblas_algorithms.classes.graph import to_undirected_graph +from graphblas_algorithms.utils import not_implemented_for + +from .._utils import can_run, should_run + +__all__ = [ + "maximum_spanning_edges", + "maximum_spanning_tree", + "minimum_spanning_edges", + "minimum_spanning_tree", +] + +# NetworkX's choices. Each gives a spanning forest; where weights tie they may give different +# ones, and this backend gives its own whichever is named. It takes equal weights by their ends +# in node order, as Kruskal takes them in `G.edges()` order, so the two forests are the same +# where each node's neighbors were added in node order. +_ALGORITHMS = frozenset({"boruvka", "bor\u016fvka", "kruskal", "prim"}) +_BORUVKA = frozenset({"boruvka", "bor\u016fvka"}) + +# Below these many edges NetworkX's Kruskal is faster than converting the graph (Indicative). +# A conversion that carries the edge data, as the trees' and `data=True`'s do, costs more. +_FEWEST_EDGES = 200_000 +_FEWEST_EDGES_WITH_DATA = 800_000 + + +def _unhashable_weight(bound): + # NetworkX looks the weight up in each edge's dict, which raises on an unhashable name. + try: + hash(bound["weight"]) + except TypeError: + return "an unhashable `weight` is left to networkx, which raises on it" + return None + + +def _few_edges(bound): + adj = getattr(bound["G"], "_adj", None) + if adj is None: + return None + fewest = _FEWEST_EDGES_WITH_DATA if bound.get("data", True) else _FEWEST_EDGES + if sum(map(len, adj.values())) < 2 * fewest: # each edge is in two nodes' adjacencies + return f"networkx is faster below {fewest} edges, with no conversion to pay" + return None + + +def _decline(reason): + raise NotImplementedError(f"{reason}; networkx serves it") + + +def _source(G, algorithm): + """The NetworkX graph whose data the answer carries, once the call is known to be served.""" + import networkx as nx + + if algorithm not in _ALGORITHMS: + raise ValueError(f"{algorithm} is not a valid choice for an algorithm.") + if G.is_multigraph(): + _decline("graphblas-algorithms does not support multigraphs") + if isinstance(G, nx.Graph): + return G # a direct call + if (source := source_of(G)) is None: + _decline( + "A spanning tree carries the edge data of the NetworkX graph it is taken from, " + "and this graph was not converted from one that is still alive" + ) + return source + + +def _with_data(adj, pairs): + """Each edge `(u, v)` with the data dict the NetworkX graph holds for it.""" + try: + return [(u, v, adj[u][v]) for u, v in pairs] + except KeyError: + # A view's conversion is not dropped when the graph under it changes. + _decline("The graph has changed since it was converted") + + +def _nan_self_loops(adj, nodes, weight): + """The nodes among `nodes` whose self-loop weighs NaN in the NetworkX graph. + + The conversion counts a self-loop's weight in twice and out once, so on the matrix's + diagonal a loop of weight inf or -inf is NaN too (inf + inf - inf). The graph's own weight, + read as NetworkX reads it, tells the two apart. + """ + try: + return [u for u in nodes if isnan(adj[u][u].get(weight, 1))] + except KeyError: + _decline("The graph has changed since it was converted") + + +def _forest(source, B, algorithm, ignore_nan, maximum, weight): + """The forest's edges with the data dicts `source` holds, or the error to raise for a NaN. + + `B` is the graph with the weights the call reads. The edges are `(u, v, datadict)`, + lightest first (heaviest for `maximum`). Where NetworkX raises on a NaN weight, the edges + are None and the error is NetworkX's ValueError, raised when the edges are first asked + for, as NetworkX's is. + """ + A = B._A + kind = A.dtype.np_type.kind + if kind == "c": + _decline("Complex weights have no order, and NetworkX raises TypeError on them") + id_to_key = B.id_to_key + adj = source._adj + if kind == "f": + nans = unary.isnan(select.triu(A)).new() + nans = nans.select(select.valueeq, True).new() + if nans.nvals and not ignore_nan: + rows, cols, _ = nans.to_coo(values=False) + between = np.flatnonzero(rows != cols) + # Every algorithm reads the weight of each edge between two nodes, and Kruskal each + # self-loop's too. NetworkX names the first NaN it meets; any one is named here. + if between.size: + pair = (id_to_key[int(rows[between[0]])], id_to_key[int(cols[between[0]])]) + elif loops := _nan_self_loops(adj, [id_to_key[i] for i in rows.tolist()], weight): + if algorithm == "prim": + _decline( + "NetworkX's Prim reads a self-loop's weight only at a node it starts a " + "tree from, so whether a NaN there raises depends on that choice" + ) + # Boruvka reads no self-loop's weight. + pair = (loops[0], loops[0]) if algorithm == "kruskal" else None + else: + pair = None # self-loops of weight inf or -inf, which no algorithm raises on + if pair is not None: + [edge] = _with_data(adj, [pair]) + return None, ValueError(f"NaN found as an edge weight. Edge {edge}") + between = select.triu(A, 1).new() + if algorithm in _BORUVKA: + # Boruvka takes an edge lighter than infinity, so an infinite one never joins two + # components (a minus-infinite one for a maximum tree). + worst = between.reduce_scalar(monoid.min if maximum else monoid.max).new().value + if worst is not None and worst == (-np.inf if maximum else np.inf): + _decline("NetworkX's Boruvka leaves out an edge of infinite weight") + # An int past 2**53 held as a float can tie with another value it is not equal to. + big = between.select(select.valuege, 2.0**53).new().to_coo()[2] + neg = between.select(select.valuele, -(2.0**53)).new().to_coo()[2] + held = np.concatenate([big, neg]) + if np.unique(held).size < held.size: + _decline("Weights of 2**53 or more that are equal as floats may be ints that differ") + kernel = algorithms.maximum_spanning_edges if maximum else algorithms.minimum_spanning_edges + rows, cols = kernel(B, ignore_nan=True) + us = [id_to_key[i] for i in rows.tolist()] + vs = [id_to_key[i] for i in cols.tolist()] + return _with_data(adj, zip(us, vs, strict=True)), None + + +def _edges(edges, error, data): + if error is not None: + raise error + if data: + yield from edges + else: + for u, v, _datadict in edges: + yield u, v + + +def _tree(source, edges, error): + if error is not None: + raise error + # As NetworkX builds it: the same class, and copies of the graph's, nodes' and edges' dicts. + T = source.__class__() + T.graph.update(source.graph) + T.add_nodes_from(source.nodes.items()) + T.add_edges_from(edges) + return T + + +@can_run(_unhashable_weight) +@should_run(_few_edges) +@not_implemented_for("directed") +def minimum_spanning_edges( + G, algorithm="kruskal", weight="weight", keys=True, data=True, ignore_nan=False +): + source = _source(G, algorithm) + B = to_undirected_graph(G, weight=weight) # values only where `weight` names them + return _edges(*_forest(source, B, algorithm, ignore_nan, maximum=False, weight=weight), data) + + +@can_run(_unhashable_weight) +@should_run(_few_edges) +@not_implemented_for("directed") +def maximum_spanning_edges( + G, algorithm="kruskal", weight="weight", keys=True, data=True, ignore_nan=False +): + source = _source(G, algorithm) + B = to_undirected_graph(G, weight=weight) + return _edges(*_forest(source, B, algorithm, ignore_nan, maximum=True, weight=weight), data) + + +@can_run(_unhashable_weight) +@should_run(_few_edges) +@not_implemented_for("directed") +def minimum_spanning_tree(G, weight="weight", algorithm="kruskal", ignore_nan=False): + source = _source(G, algorithm) + B = to_undirected_graph(G, weight=weight) + return _tree(source, *_forest(source, B, algorithm, ignore_nan, maximum=False, weight=weight)) + + +@can_run(_unhashable_weight) +@should_run(_few_edges) +@not_implemented_for("directed") +def maximum_spanning_tree(G, weight="weight", algorithm="kruskal", ignore_nan=False): + source = _source(G, algorithm) + B = to_undirected_graph(G, weight=weight) + return _tree(source, *_forest(source, B, algorithm, ignore_nan, maximum=True, weight=weight)) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..86559ac 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -166,6 +166,10 @@ def call_args(kind, args): "laplacian_matrix": ("undirected", ()), "local_efficiency": ("undirected", ()), "lowest_common_ancestor": ("dag", (1, 2)), + "maximum_spanning_edges": ("undirected", ()), + "maximum_spanning_tree": ("undirected", ()), + "minimum_spanning_edges": ("undirected", ()), + "minimum_spanning_tree": ("undirected", ()), "mixing_expansion": ("undirected", ([0, 1], [2, 3])), "modularity": ("undirected", ([{0, 1}, {2, 3, 4}],)), "modularity_matrix": ("undirected", ()), diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 1765e78..9afd01e 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -10,7 +10,12 @@ from networkx.utils.backends import _registered_algorithms from graphblas_algorithms.classes import DiGraph, Graph -from graphblas_algorithms.interface import Dispatcher, _declared, _materialize_virtual_adjacency +from graphblas_algorithms.interface import ( + _BUILT_FROM_SOURCE, + Dispatcher, + _declared, + _materialize_virtual_adjacency, +) from graphblas_algorithms.tests._dispatched import dispatcher_functions @@ -489,19 +494,27 @@ def operands(name, build): name for name in sorted(dispatcher_functions()) if _registered_algorithms[name]._returns_graph ) REBUILDS_ITS_INPUT = tuple(name for name in GRAPH_RETURNING if _declared(name).rebuilds_input) -KEEPS_NO_DATA = tuple(name for name in GRAPH_RETURNING if not _declared(name).rebuilds_input) +KEEPS_NO_DATA = tuple( + name + for name in GRAPH_RETURNING + if not _declared(name).rebuilds_input and name not in _BUILT_FROM_SOURCE +) @pytest.mark.parametrize("name", GRAPH_RETURNING) def test_a_name_rebuilds_its_input_exactly_when_networkx_keeps_its_data(name): - """The split the rebuild refusal rests on, put to NetworkX for every graph-returning name.""" + """The split the rebuild refusal rests on, put to NetworkX for every graph-returning name. + + A name built from the NetworkX graph itself keeps its data without a rebuild. + """ result = _registered_algorithms[name](*operands(name, every_kind_of_data), backend="networkx") keeps = ( any(data for *_edge, data in result.edges(data=True)) or any(data for _node, data in result.nodes(data=True)) or bool(result.graph) ) - assert _declared(name).rebuilds_input == keeps + assert (_declared(name).rebuilds_input or name in _BUILT_FROM_SOURCE) == keeps + assert not (_declared(name).rebuilds_input and name in _BUILT_FROM_SOURCE) @pytest.mark.parametrize("build", [two_edge_attributes, node_attributes], ids=["edge", "node"]) diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py index 4bf5d09..70507dc 100644 --- a/graphblas_algorithms/tests/test_match_nx.py +++ b/graphblas_algorithms/tests/test_match_nx.py @@ -580,6 +580,8 @@ def test_signatures_match_nx(): "k_crust", "k_shell", "k_truss", + "maximum_spanning_tree", + "minimum_spanning_tree", "reverse", "symmetric_difference", "union", @@ -635,14 +637,29 @@ def _graph_call(name, weighted, backend): return _registered_algorithms[name](G, *built, backend=backend) +# Names whose graph is one of several valid ones where weights tie, as all do unweighted. +_TIES = {"maximum_spanning_tree", "minimum_spanning_tree"} + + @pytest.mark.parametrize("name", _RETURNS_GRAPH) def test_an_unweighted_graph_returning_call_keeps_what_networkx_keeps(name): """Graph attributes are NetworkX's to decide: some of these names carry them, some not.""" expected = _graph_call(name, False, "networkx") result = _graph_call(name, False, "graphblas") - assert result._weight is None, f"{name} invented a weight for an unweighted graph" - back = _as_networkx(result) + if isinstance(result, nx.Graph): + back = result # built from the NetworkX graph itself (`_BUILT_FROM_SOURCE`) + else: + assert result._weight is None, f"{name} invented a weight for an unweighted graph" + back = _as_networkx(result) assert dict(back.graph) == dict(expected.graph) + if name in _TIES: + # Another spanning forest of the same graph, its edges carrying the same data. + G, _built = _graph_call_args(name, False) + assert set(back) == set(expected) + assert nx.is_forest(back) + assert back.number_of_edges() == expected.number_of_edges() + assert all(data == G.edges[u, v] for u, v, data in back.edges(data=True)) + return assert _edges(back) == _edges(expected) @@ -669,10 +686,11 @@ def test_a_weighted_graph_returning_call_carries_the_weight_or_says_it_cannot(na # The set operators and `complement` build their results with none of the input's data, # so a weight there would be one this backend invented. belongs = "weight" if any(data for _u, _v, data in expected.edges(data=True)) else None - assert ( - result._weight == belongs - ), f"{name} carries {result._weight!r} where networkx carries {belongs!r}" - result = _as_networkx(result) + if not isinstance(result, nx.Graph): # a graph built from the NetworkX graph carries all + assert ( + result._weight == belongs + ), f"{name} carries {result._weight!r} where networkx carries {belongs!r}" + result = _as_networkx(result) assert dict(result.graph) == dict(expected.graph) # Edge by edge: `full_join` adds edges that NetworkX leaves bare. assert _edges(result) == _edges(expected), f"{name} did not carry the weight networkx does"