diff --git a/README.md b/README.md index 0579784..d5f6f5d 100644 --- a/README.md +++ b/README.md @@ -197,6 +197,7 @@ graphblas_algorithms.nxapi │ └── volume ├── dag │ ├── ancestors +│ ├── dag_longest_path │ ├── dag_longest_path_length │ ├── descendants │ ├── has_cycle diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 2c5f861..c6d373d 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -55,6 +55,7 @@ def get_info(): "connected_components", "core_number", "cut_size", + "dag_longest_path", "dag_longest_path_length", "degree_centrality", "descendants", @@ -208,7 +209,8 @@ def get_info(): "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", "compose": "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.", "cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.", - "dag_longest_path_length": "A graph whose class has its own `neighbors`, `successors`, `predecessors`, `in_degree`,\n`adjacency` or `__getitem__` is left to NetworkX, which reads its edges through them.", + "dag_longest_path": "Where several paths are longest, the one given may differ from NetworkX's. Given a\n`topo_order` that is a topological order of every node once, it is NetworkX's; any\nother `topo_order`, or one that can be read only once, is left to NetworkX, as are NaN\nor infinite weights and float weights of 2**53 or more.\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.\nA graph whose class has its own `neighbors`, `successors`, `predecessors`, `in_degree`,\n`adjacency` or `__getitem__` is left to NetworkX, which reads its edges through them.", + "dag_longest_path_length": "Where several paths are longest and the weights are ints on some edges and floats on\nothers (a float `default_weight` counts), the length is that of the path this backend\nfinds, so it may be an int where NetworkX's is a float of the same value, or the\nreverse. NaN or infinite weights, and float weights of 2**53 or more, are left to\nNetworkX.\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.\nA graph whose class has its own `neighbors`, `successors`, `predecessors`, `in_degree`,\n`adjacency` or `__getitem__` is left to NetworkX, which reads its edges through them.", "diameter": '`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.', "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", "eccentricity": 'A precomputed `sp`, and the null graph, are 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 40fe889..8debfe7 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -132,7 +132,22 @@ "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX." ), "cut_size": _SUM_OVERFLOW + ".", - "dag_longest_path_length": _OWN_EDGE_READERS, + "dag_longest_path": ( + "Where several paths are longest, the one given may differ from NetworkX's. Given a\n" + "`topo_order` that is a topological order of every node once, it is NetworkX's; any\n" + "other `topo_order`, or one that can be read only once, is left to NetworkX, as are NaN\n" + "or infinite weights and float weights of 2**53 or more.\n" + + _PATH_OVERFLOW + + "\n" + + _OWN_EDGE_READERS + ), + "dag_longest_path_length": ( + "Where several paths are longest and the weights are ints on some edges and floats on\n" + "others (a float `default_weight` counts), the length is that of the path this backend\n" + "finds, so it may be an int where NetworkX's is a float of the same value, or the\n" + "reverse. NaN or infinite weights, and float weights of 2**53 or more, are left to\n" + "NetworkX.\n" + _PATH_OVERFLOW + "\n" + _OWN_EDGE_READERS + ), "diameter": _ECCENTRICITY_BOUNDS, "eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n" + _NEGATIVE_EDGES diff --git a/graphblas_algorithms/algorithms/dag.py b/graphblas_algorithms/algorithms/dag.py index add6bda..d5248d3 100644 --- a/graphblas_algorithms/algorithms/dag.py +++ b/graphblas_algorithms/algorithms/dag.py @@ -9,7 +9,10 @@ "ancestors", "dag_longest_path_length", "descendants", + "generations", "is_acyclic", + "longest_path", + "longest_path_lengths", ] @@ -106,11 +109,12 @@ def run(self): count += self._python_rounds() return count - def _python_rounds(self): + def _python_rounds(self, walked=None): """Python rounds from `current` while the frontier stays small; the number of rounds. One loop for every round, as `advance` would run them one call at a time: a path of n - nodes is n rounds, and a call per round costs more than the round. + nodes is n rounds, and a call per round costs more than the round. Each round's list + is appended to `walked` when it is given. """ indptr, indices, indegree, out = self._lists back = max(_FEW_EDGES, self._n // 16) @@ -119,6 +123,8 @@ def _python_rounds(self): while this and sum(map(out.__getitem__, this)) < back: count += 1 self.peeled += len(this) + if walked is not None: + walked.append(this) nxt = [] for u in this: for v in indices[indptr[u] : indptr[u + 1]]: @@ -174,3 +180,113 @@ def dag_longest_path_length(G): if peel.peeled < len(G): return None return max(count - 1, 0) + + +def generations(G): + """Every generation's ids, first to last, or None if `G` has a cycle. + + A generation is an array, or a list where it was walked in Python. The answer to + `is_acyclic` is cached on the way. + """ + peel = Generations(G) + rv = [] + while len(peel.current): + rv.append(peel.advance()) + if peel._python: + peel._python_rounds(rv) + G._cache["is_acyclic"] = acyclic = peel.peeled == len(G) + return rv if acyclic else None + + +def longest_path_lengths(G, generations, np_type, uniform=None): + """Each node's length in NetworkX's `dag_longest_path`, and `G`'s in-edges it was found from. + + NetworkX gives a node the heaviest of its predecessors' lengths plus the edge's weight, or + 0 when it has no predecessor or that is negative: the path starts there. A node's + predecessors are all in earlier generations, so each generation takes the most of its + in-edges' sums at once. The weights are `G`'s values as `np_type` (int64 or float64), or + `uniform` on every edge. The value, never the order, of a sum is NetworkX's: each is one + addition of two numbers it also adds, and the most of equal numbers is that number. + + A generation with few in-edges runs in Python on lists, as `Generations` walks its small + rounds, so a deep graph costs a few hundred nanoseconds a node, not a NumPy call or more. + Returns the lengths and the in-edges (`indptr`, `sources`, `weights`, by target). + """ + A = G._A + n = A.nrows + indptr, sources, weights = A.to_csc() + indptr = indptr.astype(np.int64) + sources = sources.astype(np.int64) + if uniform is None: + weights = weights.astype(np_type) + else: + weights = np.full(len(sources), uniform, np_type) + indegree = np.diff(indptr) + dist = np.zeros(n, np_type) + zero = np_type(0).item() + back = max(_FEW_EDGES, n // 16) + lists = d = None + python = False + for this in generations[1:]: # the first are the sources, of length 0 + if python: + if not isinstance(this, list): + this = this.tolist() + edges = sum(map(lists[3].__getitem__, this)) + if edges >= back: + dist = np.array(d, np_type) + python = False + this = np.array(this, np.int64) + else: + this = np.asarray(this, np.int64) + edges = int(indegree[this].sum()) + if edges < _FEW_EDGES: + if lists is None: + lists = (indptr.tolist(), sources.tolist(), weights.tolist(), indegree.tolist()) + d = dist.tolist() + python = True + this = this.tolist() + if python: + ptr, src, wts, _ = lists + for v in this: + a, b = ptr[v], ptr[v + 1] + if b - a == 1: # most nodes of a deep graph: no list to build + best = d[src[a]] + wts[a] + else: + best = max([d[u] + w for u, w in zip(src[a:b], wts[a:b], strict=True)]) + d[v] = best if best >= 0 else zero + else: + # Every node after the first generation has an in-edge, so no segment is empty. + counts = indegree[this] + offsets = np.cumsum(counts) - counts + at = np.arange(edges) + np.repeat(indptr[this] - offsets, counts) + best = np.maximum.reduceat(dist[sources[at]] + weights[at], offsets) + best[best < 0] = 0 + dist[this] = best + if python: + dist = np.array(d, np_type) + return dist, (indptr, sources, weights) + + +def longest_path(dist, in_edges): + """The ids of a longest path, first to last, from `longest_path_lengths`'s answer. + + It ends at the first node of the greatest length and steps back along an in-edge whose sum + is the node's length, until a node of length 0, where it starts. Its weights then add up, + in order, to the greatest length; where several paths do, which one is this backend's own. + """ + end = int(np.argmax(dist)) + if not dist[end]: + return [end] + indptr, sources, weights = in_edges + targets = np.repeat(np.arange(len(dist)), np.diff(indptr)) + length = dist[targets] + tight = (dist[sources] + weights == length) & (length != 0) + pred = np.full(len(dist), -1, np.int64) + pred[targets[tight]] = sources[tight] + path = [end] + v = end + while dist[v]: + v = int(pred[v]) + path.append(v) + path.reverse() + return path diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 0a52bd1..762815f 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -340,6 +340,7 @@ class Dispatcher: mod = nxapi.dag # ============= ancestors = mod.ancestors + dag_longest_path = mod.dag_longest_path dag_longest_path_length = mod.dag_longest_path_length descendants = mod.descendants has_cycle = mod.has_cycle diff --git a/graphblas_algorithms/nxapi/dag.py b/graphblas_algorithms/nxapi/dag.py index d6503a6..452d48e 100644 --- a/graphblas_algorithms/nxapi/dag.py +++ b/graphblas_algorithms/nxapi/dag.py @@ -1,6 +1,10 @@ +import itertools +import math + import numpy as np from graphblas_algorithms import algorithms +from graphblas_algorithms.algorithms._helpers import checked_sum_type from graphblas_algorithms.algorithms.components._labels import _keys_by_id from graphblas_algorithms.classes.digraph import to_graph from graphblas_algorithms.utils import not_implemented_for @@ -11,6 +15,7 @@ # `has_cycle` too, which NetworkX keeps out of its own namespace. __all__ = [ "ancestors", + "dag_longest_path", "dag_longest_path_length", "descendants", "is_directed_acyclic_graph", @@ -225,46 +230,196 @@ def topological_sort(G): return _sort(_generations(G, graph, changed)) -def _unit_weights(bound): - # Only the unweighted length falls out of the generations. - default = bound["default_weight"] - if type(default) not in {int, bool} or default != 1: - return ( - "dag_longest_path_length serves edges that weigh the int 1; networkx serves " - f"default_weight={default!r}" +def _real(x): + return type(x) in {int, bool, float} and math.isfinite(x) + + +def _longest(name): + def hook(bound): + G = bound["G"] + if bound["weight"] is None and not _real(bound["default_weight"]): + return ( + f"{name} weighs every edge {bound['default_weight']!r} here, which is not a " + "finite Python int or float; networkx serves it" + ) + if (order := bound.get("topo_order")) is not None: + try: + once = iter(order) is order + except TypeError: + return f"{name}: networkx says what a `topo_order` that is not iterable does" + if once: + # Read here, an iterator would reach NetworkX empty if the order is declined. + return f"{name} reads a `topo_order` it can read twice; networkx serves an iterator" + if not hasattr(G, "_adj"): + return None + if (reason := edges_read_its_own_way(name, G)) is not None: + return reason # NetworkX answers through topological_sort and G.pred + _drop_stale_conversions(G) + return None + + return hook + + +def _lengths(G, weight, default_weight): + """The longest-path lengths as NetworkX finds them, in its order of errors. + + A cycle raises first, as NetworkX's topological sort does whatever the weights. A weight + that is NaN or infinite, or a float of 2**53 or more (where float64 may hold an int + NetworkX adds exactly) is left to NetworkX; an int one raises OverflowError where a sum + could pass int64. + """ + name = "dag_longest_path" + A = G._A + if weight is None or weight != G._weight: + # No value is named, so each edge weighs the default, as NetworkX reads a missing one. + uniform = int(default_weight) if type(default_weight) is bool else default_weight + if not _real(uniform): + raise NotImplementedError( + f"{name} weighs every edge {default_weight!r}; networkx serves it" + ) + np_type = np.float64 if isinstance(uniform, float) else np.int64 + else: + uniform = None + kind = A.dtype.np_type.kind + if kind not in "biuf": + raise NotImplementedError(f"{name} of {A.dtype} weights is left to networkx") + np_type = np.float64 if kind == "f" else np.int64 + layers = algorithms.generations(G) + if layers is None: + raise NetworkXUnfeasible(_CYCLE) + if np_type is np.float64: + values = ( + np.array([uniform]) if uniform is not None else A.to_coo(rows=False, columns=False)[2] ) - weight = bound["weight"] - G = bound["G"] - if (reason := edges_read_its_own_way("dag_longest_path_length", G)) is not None: - return reason # NetworkX answers through topological_sort - if weight is not None and hasattr(G, "_adj"): - import networkx as nx + if len(values) and not np.isfinite(values).all(): + raise NotImplementedError(f"{name} with NaN or infinite weights is left to networkx") + if len(values) and np.abs(values).max() >= 2**53: + raise NotImplementedError( + f"{name} with float weights of 2**53 or more is left to networkx, which may " + "hold them as ints" + ) + elif uniform is None: + checked_sum_type(G, "path") + elif len(G) * abs(uniform) >= 2**62: + raise OverflowError( + f"every edge weighing {uniform} on {len(G)} nodes could make a path length reach " + "2**63, which 64-bit integers cannot hold; NetworkX computes with Python integers. " + "Call with backend='networkx'." + ) + return algorithms.longest_path_lengths(G, layers, np_type, uniform) - from ..interface import _root - root = _root(G) - cache = ( - getattr(root, "__networkx_cache__", None) if nx.config.cache_converted_graphs else None +def _in_order(G, topo_order): + """`topo_order` as ids, if it is a topological order of every node once; otherwise None.""" + key_to_id = G._key_to_id + try: + ids = np.array([key_to_id[v] for v in topo_order], np.int64) + except (KeyError, TypeError): + return None + n = len(G) + if len(ids) != n: + return None + position = np.full(n, -1, np.int64) + position[ids] = np.arange(n) + if (position < 0).any(): + return None # a node twice, so another not at all + rows, cols, _ = G._A.to_coo(values=False) + if (position[rows] >= position[cols]).any(): + return None + return ids + + +def _networkx_path(graph, G, dist, ids, weight, default_weight): + """NetworkX's own path for its topological order `ids`. + + It ends at the first node in that order of the greatest length, and each step back takes + the first predecessor, in `graph.pred`'s order, of the greatest sum, while that sum is not + negative. + """ + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + key_to_id = G._key_to_id + d = dist.tolist() + v = keys[ids[int(np.argmax(dist[ids]))]] + path = [v] + while True: + best = None + for u, data in graph.pred[v].items(): + total = d[key_to_id[u]] + data.get(weight, default_weight) + if best is None or total > best[0]: + best = (total, u) + if best is None or not best[0] >= 0: + break + v = best[1] + path.append(v) + path.reverse() + return path + + +@can_run(_longest("dag_longest_path")) +@not_implemented_for("undirected") +def dag_longest_path(G, weight="weight", default_weight=1, topo_order=None): + graph, _changed = _watch(G) # before `to_graph`, which may give a copy without values + G = to_graph(G, weight=weight) + if len(G) == 0: + return [] + if topo_order is None: + dist, in_edges = _lengths(G, weight, default_weight) + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + return keys[algorithms.longest_path(dist, in_edges)].tolist() + # A caller picks among equal paths with the order, so the path is NetworkX's for it. Its + # ties go to the first node of the order and the first predecessor in `graph.pred`, and + # the lengths compared are NetworkX's, so the ties are too. + if graph is None: + raise NotImplementedError( + "dag_longest_path with `topo_order` reads the NetworkX graph's order of " + "predecessors, and this graph has none; networkx serves it" ) - memo = cache.setdefault("graphblas_weighted", {}) if root is G and cache is not None else {} - if weight not in memo: - memo[weight] = any(weight in datadict for _u, _v, datadict in G.edges(data=True)) - if memo[weight]: - return f"dag_longest_path_length serves unweighted graphs; networkx reads {weight!r}" - elif weight is not None and G._weight == weight: - return f"dag_longest_path_length serves unweighted graphs; networkx reads {weight!r}" - if hasattr(G, "_adj"): - _drop_stale_conversions(G) - return None + ids = _in_order(G, topo_order) + if ids is None: + raise NotImplementedError( + "dag_longest_path serves a `topo_order` that is a topological order of every " + "node once; networkx says what this one gives" + ) + dist, _in_edges = _lengths(G, weight, default_weight) # an order of every node: no cycle + return _networkx_path(graph, G, dist, ids, weight, default_weight) + +def _unit(G, weight, default_weight): + """Whether every edge weighs the int 1, so the length is the number of generations less one.""" + if type(default_weight) not in {int, bool} or default_weight != 1: + return False # where NetworkX adds a default of 1.0, its length is a float + A = G._A + if weight is None or weight != G._weight or A.nvals == 0: + return True + if A.dtype.np_type.kind not in "biu": + return False + # Off the diagonal: a self-loop is a cycle, which the generations find. + least, greatest = G.get_properties("min_element- max_element-") + return least.get(1) == greatest.get(1) == 1 -@can_run(_unit_weights) + +@can_run(_longest("dag_longest_path_length")) @not_implemented_for("undirected") def dag_longest_path_length(G, weight="weight", default_weight=1): - if reason := _unit_weights({"G": G, "weight": weight, "default_weight": default_weight}): - raise NotImplementedError(reason) - G = to_graph(G) - rv = algorithms.dag_longest_path_length(G) - if rv is None: - raise NetworkXUnfeasible(_CYCLE) - return rv + graph, _changed = _watch(G) # before `to_graph`, which may give a copy without values + G = to_graph(G, weight=weight) + if len(G) == 0: + return 0 + if _unit(G, weight, default_weight): + rv = algorithms.dag_longest_path_length(G) + if rv is None: + raise NetworkXUnfeasible(_CYCLE) + return rv + dist, in_edges = _lengths(G, weight, default_weight) + ids = algorithms.longest_path(dist, in_edges) + if len(ids) < 2: + return 0 + if graph is None: + return dist[ids[-1]].item() + # NetworkX's sum, of its own numbers, along this path: the same total, of its types. + keys, _places = G._cacheit("keys_by_id", _keys_by_id, G) + path = keys[ids].tolist() + total = 0 + for u, v in itertools.pairwise(path): + total += graph[u][v].get(weight, default_weight) + return total diff --git a/graphblas_algorithms/nxapi/tests/test_dag.py b/graphblas_algorithms/nxapi/tests/test_dag.py index 548cf7b..8931bf9 100644 --- a/graphblas_algorithms/nxapi/tests/test_dag.py +++ b/graphblas_algorithms/nxapi/tests/test_dag.py @@ -264,7 +264,7 @@ def test_a_dag_in_any_order_is_served(name, shape): # Every DAG name: NetworkX answers each through topological_sort or its generations. -EVERY_NAME = [*NAMES, "dag_longest_path_length"] +EVERY_NAME = [*NAMES, "dag_longest_path", "dag_longest_path_length"] @pytest.mark.parametrize("attr", EDGE_READERS) @@ -280,8 +280,8 @@ def test_a_class_that_reads_its_edges_its_own_way_is_declined(name, attr): def test_networkx_answers_a_class_whose_neighbors_hide_an_edge(name): """NetworkX finds a cycle where the stored edges, which a conversion reads, are a DAG. - It never walks 0 -> 1, so node 1 keeps an in-degree: the topological names and - dag_longest_path_length raise, and the others say there is a cycle. + It never walks 0 -> 1, so node 1 keeps an in-degree: the topological names and the longest + paths raise, and the others say there is a cycle. """ G = _subclassed(_HidesAnEdge)() expected = _outcome(lambda: _func(name)(G, backend="networkx")) @@ -416,7 +416,7 @@ def test_a_change_before_the_first_next_is_seen(): @pytest.mark.parametrize("read_the_graph", [False, True]) @pytest.mark.parametrize("mutation", _UNDER_A_VIEW) @pytest.mark.parametrize("view", _VIEWS) -@pytest.mark.parametrize("name", [*NAMES, "dag_longest_path_length"]) +@pytest.mark.parametrize("name", EVERY_NAME) def test_a_view_is_not_answered_from_a_conversion_made_before_its_graph_changed( name, view, mutation, read_the_graph ): @@ -442,7 +442,7 @@ def test_a_current_conversion_is_kept(view): V = G if view is None else _VIEWS[view](G) def read(): - for name in [*NAMES, "dag_longest_path_length"]: + for name in EVERY_NAME: _outcome(lambda name=name: _func(name)(V, backend="graphblas")) return list(V.__networkx_cache__["backends"]["graphblas"].values()) @@ -529,32 +529,30 @@ def test_a_backend_graph_is_read_as_it_was_converted(): @pytest.mark.parametrize( - ("kwargs", "served"), + "kwargs", [ - ({}, True), # no edge carries "weight" - ({"weight": None}, True), - ({"default_weight": 1.0}, False), # NetworkX answers a float - ({"default_weight": 2}, False), - ({"weight": None, "default_weight": 2}, False), # NetworkX reads the default + {}, # no edge carries "weight" + {"weight": None}, + {"default_weight": 1.0}, # NetworkX answers a float + {"weight": None, "default_weight": 2}, # NetworkX reads the default ], ) -def test_dag_longest_path_length_serves_unit_weights(kwargs, served): +def test_dag_longest_path_length_of_unit_weights(kwargs): G = nx.DiGraph([(0, 1), (1, 2), (0, 2)]) - assert (Dispatcher.can_run("dag_longest_path_length", (G,), kwargs) is True) is served - if served: - expected = nx.dag_longest_path_length(G, **kwargs) - got = nx.dag_longest_path_length(G, backend="graphblas", **kwargs) - assert (type(got), got) == (type(expected), expected) + assert Dispatcher.can_run("dag_longest_path_length", (G,), kwargs) is True + expected = nx.dag_longest_path_length(G, **kwargs) + got = nx.dag_longest_path_length(G, backend="graphblas", **kwargs) + assert (type(got), got) == (type(expected), expected) -def test_dag_longest_path_length_declines_a_weighted_graph(): +def test_dag_longest_path_length_of_a_weighted_graph(): G = nx.DiGraph([(0, 1), (1, 2)]) G.add_edge(0, 2, weight=5) - assert "unweighted" in Dispatcher.can_run("dag_longest_path_length", (G,), {}) - assert Dispatcher.can_run("dag_longest_path_length", (G,), {"weight": "cost"}) is True + assert Dispatcher.can_run("dag_longest_path_length", (G,), {}) is True + assert nx.dag_longest_path_length(G, backend="graphblas") == 5 + assert nx.dag_longest_path_length(G, weight="cost", backend="graphblas") == 2 H = ga.DiGraph.from_networkx(G, weight="weight") - with pytest.raises(NotImplementedError, match="unweighted"): - nxapi.dag_longest_path_length(H) + assert nxapi.dag_longest_path_length(H) == 5 assert nxapi.dag_longest_path_length(H, weight=None) == 2 diff --git a/graphblas_algorithms/nxapi/tests/test_dag_longest_path.py b/graphblas_algorithms/nxapi/tests/test_dag_longest_path.py new file mode 100644 index 0000000..ebde966 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_dag_longest_path.py @@ -0,0 +1,434 @@ +"""dag_longest_path and the weighted dag_longest_path_length against NetworkX. + +Where several paths are longest, NetworkX's pick follows its order of nodes and predecessors, +and this backend's need not: a path is checked to be a path of the graph whose weights add up, +as NetworkX adds them, to NetworkX's length. Given `topo_order`, the path must be NetworkX's. +""" + +import itertools +import zlib +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms import dag as dag_kernel +from graphblas_algorithms.interface import Dispatcher + +# The graphs are shared, so a call may meet a conversion an earlier one cached. +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + +NAMES = ["dag_longest_path", "dag_longest_path_length"] + + +def _outcome(call): + try: + return "answer", call() + except Exception as exc: + return type(exc), str(exc) + + +def _three_ways(name, G, **kwargs): + """NetworkX's outcome, graphblas's by name, and NetworkX's with graphblas first.""" + func = getattr(nx, name) + want = _outcome(lambda: func(G, backend="networkx", **kwargs)) + got = _outcome(lambda: func(G, backend="graphblas", **kwargs)) + config = nx.config.backend_priority + before, fallback = list(config.algos), nx.config.fallback_to_nx + config.algos, nx.config.fallback_to_nx = ["graphblas"], False + try: + first = _outcome(lambda: func(G, **kwargs)) + finally: + config.algos, nx.config.fallback_to_nx = before, fallback + return want, got, first + + +def _fold(G, path, weight="weight", default_weight=1): + total = 0 + for u, v in itertools.pairwise(path): + total += default_weight if weight is None else G[u][v].get(weight, default_weight) + return total + + +def _assert_a_longest_path(G, got, want, weight="weight", default_weight=1): + assert len(set(got)) == len(got) + assert all(G.has_edge(u, v) for u, v in itertools.pairwise(got)) + assert bool(got) == bool(want) + length, expected = _fold(G, got, weight, default_weight), _fold(G, want, weight, default_weight) + if isinstance(expected, float) or isinstance(length, float): + assert length == pytest.approx(expected, rel=1e-12) + else: + assert length == expected + + +def _pick(rng, values): + return values[int(rng.integers(len(values)))] # a Python value, as a graph's user writes + + +def _weight(rng, kind): + """An edge's data for `kind`: its weight, or none (`kind` "missing" half the time).""" + if kind == "int": + return {"weight": int(rng.integers(-5, 21))} + if kind == "tied int": + return {"weight": _pick(rng, [1, 2])} + if kind == "float": + return {"weight": float(rng.uniform(-2, 5))} + if kind == "tied float": + return {"weight": _pick(rng, [0.1, 0.2, 0.3])} + if kind == "negative": + if rng.random() < 0.8: + return {"weight": int(rng.integers(-9, 0))} + return {"weight": float(rng.uniform(-3, 1))} + if kind == "missing" and rng.random() < 0.5: + return {"weight": _pick(rng, [2, 3, 0.5])} + if kind == "zero": + return {"weight": _pick(rng, [0, 0.0, -0.0])} + if kind == "mixed": + return {"weight": _pick(rng, [1, 2, 1.0, 2.0])} + return {} + + +def _dag(rng, n, p, kind, labels=False, isolated=0): + """A random DAG on `n` nodes, added and ranked in two random orders, and `isolated` more.""" + rank = rng.permutation(n).tolist() + G = nx.DiGraph() + G.add_nodes_from(rng.permutation(n).tolist()) + G.add_nodes_from(range(n, n + isolated)) + for a in range(n): + for b in range(a + 1, n): + if rng.random() < p: + G.add_edge(rank[a], rank[b], **_weight(rng, kind)) + if labels: + G = nx.relabel_nodes(G, {v: f"v{v}" for v in G}) + return G + + +KINDS = ["int", "tied int", "float", "tied float", "negative", "missing", "zero", "mixed", "none"] + + +def _graphs(): + rng = np.random.default_rng(69) + graphs = {} + for i in range(264): + kind = KINDS[i % len(KINDS)] + n = _pick(rng, [2, 3, 5, 8, 13, 21, 40, 90]) + p = _pick(rng, [0.05, 0.15, 0.35, 0.8]) + graphs[f"random {i} {kind}"] = _dag(rng, n, p, kind, labels=i % 5 == 0, isolated=i % 3) + for i, kind in enumerate(KINDS * 3): + G = nx.DiGraph() + width, depth = _pick(rng, [1, 2, 5]), _pick(rng, [10, 60]) + for k in range(depth - 1): + for j in range(width): + for _ in range(2): + G.add_edge((k, j), (k + 1, int(rng.integers(width))), **_weight(rng, kind)) + graphs[f"layered {i} {kind}"] = G + for n in [1, 2, 10, 600]: + graphs[f"path {n}"] = nx.path_graph(n, create_using=nx.DiGraph) + graphs["empty"] = nx.DiGraph() + graphs["isolated nodes"] = nx.empty_graph(4, create_using=nx.DiGraph) + graphs["string node"] = nx.DiGraph() + graphs["string node"].add_node("a") + for i in range(10): + graphs[f"tree {i}"] = nx.bfs_tree(nx.random_labeled_tree(30, seed=i), 0) + return graphs + + +GRAPHS = _graphs() + + +def test_there_are_enough_graphs(): + assert len(GRAPHS) >= 300 + + +def _kwargs(key): + if key.endswith("none"): + return [{"weight": None}, {"weight": None, "default_weight": 3}] + if key.endswith("missing"): + return [{}, {"default_weight": 1.0}, {"weight": "absent"}] + return [{}] + + +CASES = [(key, i) for key in GRAPHS for i in range(len(_kwargs(key)))] + + +@pytest.mark.parametrize(("key", "i"), CASES) +def test_a_longest_path(key, i): + G, kwargs = GRAPHS[key], _kwargs(key)[i] + want = nx.dag_longest_path(G, backend="networkx", **kwargs) + got = nx.dag_longest_path(G, backend="graphblas", **kwargs) + _assert_a_longest_path( + G, got, want, kwargs.get("weight", "weight"), kwargs.get("default_weight", 1) + ) + + +def _mixed(G, kwargs): + """Whether the weights NetworkX adds are ints on some edges and floats on others.""" + weight, default = kwargs.get("weight", "weight"), kwargs.get("default_weight", 1) + if weight is None: + return False + return len({isinstance(d.get(weight, default), float) for *_, d in G.edges(data=True)}) == 2 + + +@pytest.mark.parametrize(("key", "i"), CASES) +def test_the_length_as_networkx(key, i): + G, kwargs = GRAPHS[key], _kwargs(key)[i] + want = nx.dag_longest_path_length(G, backend="networkx", **kwargs) + got = nx.dag_longest_path_length(G, backend="graphblas", **kwargs) + if isinstance(want, float) and isinstance(got, float): + assert got == pytest.approx(want, rel=1e-12) + elif _mixed(G, kwargs): + # NetworkX's int or float follows its path, which may cross a float (a float default + # counts) where an equal path here does not, or the reverse: the same number, of the + # type of the path found here. + assert got == want + path = nx.dag_longest_path(G, backend="graphblas", **kwargs) + weight, default = kwargs.get("weight", "weight"), kwargs.get("default_weight", 1) + assert type(got) is type(_fold(G, path, weight, default)) + else: + assert (type(got), got) == (type(want), want) + + +def test_the_length_s_type_follows_the_path(): + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, 1), (1, 3, 1), (0, 2, 1.0), (2, 3, 1)]) + for name in NAMES: + want, got, first = _three_ways(name, G) + assert want[0] == got[0] == first[0] == "answer" + path = nx.dag_longest_path(G, backend="graphblas") + length = nx.dag_longest_path_length(G, backend="graphblas") + assert (type(length), length) == (type(_fold(G, path)), 2) + assert nx.dag_longest_path_length(G, backend="networkx") == 2 + # One longest path, of ints, in a graph of floats too: NetworkX's int. + G.add_edge(0, 3, weight=0.5) + G[0][2]["weight"] = 0.5 + for name in NAMES: + want, got, first = _three_ways(name, G) + assert (type(got[1]), got[1]) == (type(want[1]), want[1]) + assert first == want + + +def _orders(G, rng): + yield list(nx.topological_sort(G, backend="networkx")) + generations = [list(g) for g in nx.topological_generations(G, backend="networkx")] + for g in generations: + rng.shuffle(g) + yield [v for g in generations for v in g] + yield tuple(reversed(list(nx.topological_sort(G.reverse(), backend="networkx")))) + + +@pytest.mark.parametrize("key", [key for key in GRAPHS if len(GRAPHS[key])]) +def test_a_topological_order_gives_networkx_s_path(key): + G = GRAPHS[key] + rng = np.random.default_rng(zlib.crc32(key.encode())) + for kwargs in _kwargs(key): + for order in _orders(G, rng): + want = nx.dag_longest_path(G, topo_order=order, backend="networkx", **kwargs) + got = nx.dag_longest_path(G, topo_order=order, backend="graphblas", **kwargs) + assert got == want + + +def test_networkx_s_example_of_a_topological_order(): + G = nx.DiGraph([(0, 1), (0, 2)]) + assert nx.dag_longest_path(G, topo_order=[0, 1, 2], backend="graphblas") == [0, 1] + assert nx.dag_longest_path(G, topo_order=[0, 2, 1], backend="graphblas") == [0, 2] + + +def test_networkx_s_weighted_example(): + G = nx.DiGraph([(0, 1, {"cost": 1}), (1, 2, {"cost": 1}), (0, 2, {"cost": 42})]) + assert nx.dag_longest_path(G, backend="graphblas") == [0, 1, 2] + assert nx.dag_longest_path(G, weight="cost", backend="graphblas") == [0, 2] + assert nx.dag_longest_path_length(G, weight="cost", backend="graphblas") == 42 + + +def _cycle(): + return nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3)]) + + +def _with_weights(*weights): + G = nx.DiGraph() + G.add_weighted_edges_from((i, i + 1, w) for i, w in enumerate(weights)) + return G + + +# Each graph and arguments, and whether graphblas answers (True) or leaves it to NetworkX. +ERRORS_AND_DECLINES = { + "a cycle": (_cycle, {}, True), + "a self-loop": (lambda: nx.DiGraph([(0, 1), (1, 1)]), {}, True), + "a cycle and NaN": (lambda: nx.DiGraph([(0, 1, {"weight": float("nan")}), (1, 0)]), {}, True), + "NaN": (lambda: _with_weights(float("nan"), 1.0), {}, False), + "NaN later": (lambda: _with_weights(1.0, float("nan"), 5.0), {}, False), + "inf": (lambda: _with_weights(float("inf"), 1.0), {}, False), + "-inf": (lambda: _with_weights(1.0, float("-inf")), {}, False), + "a float of 2**53": (lambda: _with_weights(2.0**53, 1.0), {}, False), + "an int past int64": (lambda: _with_weights(2**64, 1), {}, False), + "complex": (lambda: _with_weights(1j, 1), {}, False), + "weight None, a NaN default": (_cycle, {"weight": None, "default_weight": float("nan")}, False), + "weight None, a Fraction default": ( + lambda: _with_weights(1, 2), + {"weight": None, "default_weight": Fraction(1, 3)}, + False, + ), + "a default of 3": ( + lambda: nx.DiGraph([(0, 1, {"weight": 2}), (1, 2)]), + {"default_weight": 3}, + False, + ), + "a multigraph": (lambda: nx.MultiDiGraph([(0, 1), (0, 1), (1, 2)]), {}, False), + "bool weights": (lambda: _with_weights(True, True, False), {}, True), + "weight None, a negative default": ( + lambda: _with_weights(1, 2), + {"weight": None, "default_weight": -1}, + True, + ), + "weight None, a zero default": ( + lambda: _with_weights(1, 2), + {"weight": None, "default_weight": 0}, + True, + ), + "weight None, a float default": ( + lambda: _with_weights(1, 2), + {"weight": None, "default_weight": 2.5}, + True, + ), +} + + +@pytest.mark.parametrize("case", sorted(ERRORS_AND_DECLINES)) +@pytest.mark.parametrize("name", NAMES) +def test_errors_and_declines_as_networkx(name, case): + make, kwargs, served = ERRORS_AND_DECLINES[case] + want, got, first = _three_ways(name, make(), **kwargs) + assert first == want + if served: + assert got == want + else: + assert got[0] is NotImplementedError + + +@pytest.mark.parametrize("name", NAMES) +def test_an_undirected_graph_raises(name): + want, got, first = _three_ways(name, nx.Graph([(0, 1)])) + assert want[0] is nx.NetworkXNotImplemented + assert got == first == want + with pytest.raises(nx.NetworkXNotImplemented): + getattr(nxapi, name)(ga.Graph.from_networkx(nx.Graph([(0, 1)]))) + + +@pytest.mark.parametrize("name", NAMES) +def test_an_int_sum_that_could_pass_int64_raises_overflow_error(name): + G = _with_weights(2**61, 2**61, 2**61) + with pytest.raises(OverflowError, match="2\\*\\*63"): + getattr(nx, name)(G, backend="graphblas") + G = _with_weights(1, 2) + with pytest.raises(OverflowError, match="2\\*\\*63"): + getattr(nx, name)(G, weight=None, default_weight=2**61, backend="graphblas") + # A cycle is told first, as NetworkX's topological sort tells it whatever the weights. + G = _with_weights(2**61, 2**61, 2**61) + G.add_edge(3, 0, weight=1) + with pytest.raises(nx.NetworkXUnfeasible): + getattr(nx, name)(G, backend="graphblas") + + +TOPO_ORDERS = { + "not topological": [3, 2, 1, 0], + "a closed subset": [0, 1], + "an open subset": [1, 3], + "an absent node": [0, 1, 2, 3, 9], + "a node twice": [0, 1, 1, 2, 3], + "a node twice, for a source": [1, 1, 2, 3], # every edge forward, but 0 is never read + "empty": [], + "an unhashable node": [0, [1], 2, 3], + "a set": {0, 1, 2, 3}, +} + + +@pytest.mark.parametrize("case", sorted(TOPO_ORDERS)) +def test_a_topo_order_as_networkx(case): + G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)]) + order = TOPO_ORDERS[case] + want, _got, first = _three_ways("dag_longest_path", G, topo_order=order) + assert first == want + + +def test_a_topo_order_on_a_cycle_is_networkx_s(): + want, got, first = _three_ways("dag_longest_path", _cycle(), topo_order=[0, 1, 2, 3]) + assert want[0] is KeyError + assert got[0] is NotImplementedError + assert first == want + + +def test_a_one_pass_topo_order_is_left_to_networkx(): + G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3)]) + reason = Dispatcher.can_run("dag_longest_path", (G,), {"topo_order": iter([0, 2, 1, 3])}) + assert "iterator" in reason + want = nx.dag_longest_path(G, topo_order=iter([0, 2, 1, 3]), backend="networkx") + config = nx.config.backend_priority + before = list(config.algos) + config.algos = ["graphblas"] + try: + assert nx.dag_longest_path(G, topo_order=(v for v in [0, 2, 1, 3])) == want + finally: + config.algos = before + assert "iterable" in Dispatcher.can_run("dag_longest_path", (G,), {"topo_order": 5}) + + +def test_a_topo_order_on_a_graph_built_here_is_left_to_networkx(): + H = ga.DiGraph.from_networkx(nx.DiGraph([(0, 1), (0, 2)])) + with pytest.raises(NotImplementedError, match="order of predecessors"): + nxapi.dag_longest_path(H, topo_order=[0, 1, 2]) + assert nxapi.dag_longest_path(H) in ([0, 1], [0, 2]) + + +def test_an_empty_graph_reads_no_topo_order(): + assert nx.dag_longest_path(nx.DiGraph(), topo_order=[5], backend="graphblas") == [] + assert nx.dag_longest_path_length(nx.DiGraph(), backend="graphblas") == 0 + + +@pytest.mark.parametrize("weight", ["weight", None, "absent"]) +def test_a_graph_built_here(weight): + G = _dag(np.random.default_rng(3), 40, 0.2, "float") + H = ga.DiGraph.from_networkx(G, weight="weight") + got = nxapi.dag_longest_path(H, weight=weight) + want = nx.dag_longest_path(G, weight=weight, backend="networkx") + _assert_a_longest_path(G, got, want, weight) + length = nxapi.dag_longest_path_length(H, weight=weight) + assert length == pytest.approx(nx.dag_longest_path_length(G, weight=weight), rel=1e-12) + + +@pytest.mark.parametrize("few", [0, 3, 10**9]) +@pytest.mark.parametrize("seed", range(8)) +def test_python_and_numpy_generations_agree(monkeypatch, few, seed): + """Small generations run in Python and large ones in NumPy; any split gives the same.""" + monkeypatch.setattr(dag_kernel, "_FEW_EDGES", few) + rng = np.random.default_rng(seed) + G = _dag(rng, 120, _pick(rng, [0.03, 0.1, 0.3]), _pick(rng, ["int", "float", "tied int"])) + want = nx.dag_longest_path(G, backend="networkx") + _assert_a_longest_path(G, nx.dag_longest_path(G, backend="graphblas"), want) + length = nx.dag_longest_path_length(G, backend="graphblas") + assert length == pytest.approx(nx.dag_longest_path_length(G, backend="networkx"), rel=1e-12) + + +def test_a_wide_generation_after_narrow_ones_goes_back_to_numpy(monkeypatch): + monkeypatch.setattr(dag_kernel, "_FEW_EDGES", 4) + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, 2), (1, 2, 3)]) + G.add_weighted_edges_from((2, 10 + i, i) for i in range(30)) + G.add_weighted_edges_from((10 + i, 100, 30 - i) for i in range(30)) + G.add_weighted_edges_from([(100, 101, -1), (101, 102, 4)]) + # The 30 paths through the wide generation tie, each 30 long. + _assert_a_longest_path( + G, nx.dag_longest_path(G, backend="graphblas"), [0, 1, 2, 10, 100, 101, 102] + ) + assert nx.dag_longest_path_length(G, backend="graphblas") == 38 + + +def test_the_lengths_are_networkx_s_to_the_bit(): + """Each length is one sum NetworkX also makes, so the float is the same float.""" + rng = np.random.default_rng(5) + for _ in range(20): + G = _dag(rng, 60, 0.2, "float") + want = nx.dag_longest_path_length(G, backend="networkx") + assert nx.dag_longest_path_length(G, backend="graphblas").hex() == want.hex() diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 0f93dc2..57e87ed 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -18,8 +18,8 @@ def dispatcher_functions(): # tournament an isolated node: neither is visible in a graph that is only its edges. _SQUARE = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (1, 3)] _DAG = [(0, 1), (0, 2), (1, 3), (2, 3)] -_DIRECTED_KINDS = {"directed", "plain directed", "tournament", "dag", "plain dag"} -_UNWEIGHTED_KINDS = {"plain", "plain directed", "plain dag"} +_DIRECTED_KINDS = {"directed", "plain directed", "tournament", "dag"} +_UNWEIGHTED_KINDS = {"plain", "plain directed"} # Placeholders for the second graph a binary operator takes, replaced when the call is made. SECOND = "" @@ -32,7 +32,7 @@ def make_graph(kind, *, shift=0, drop=0, label="first"): if kind == "tournament": edges = _SQUARE # exactly one edge per pair, which is what a tournament is - elif kind in {"dag", "plain dag"}: + elif kind == "dag": edges = _DAG elif kind in _DIRECTED_KINDS: edges = _SQUARE + [(v, u) for u, v in _SQUARE] @@ -101,7 +101,8 @@ def call_args(kind, args): "core_number": ("undirected", ()), "cut_size": ("undirected", ([0, 1], [2, 3])), # Unweighted: the backend declines a weighted graph here (see its `can_run` hook). - "dag_longest_path_length": ("plain dag", ()), + "dag_longest_path": ("dag", ()), + "dag_longest_path_length": ("dag", ()), "degree_centrality": ("undirected", ()), "descendants": ("dag", (0,)), "descendants_at_distance": ("dag", (0, 1)),