Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,10 @@ graphblas_algorithms.nxapi
│ └── volume
├── dag
│ ├── ancestors
│ └── descendants
│ ├── descendants
│ ├── transitive_closure
│ ├── transitive_closure_dag
│ └── transitive_reduction
├── distance_measures
│ ├── center
│ ├── diameter
Expand Down
6 changes: 6 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,9 @@ def get_info():
"square_clustering",
"symmetric_difference",
"tournament_matrix",
"transitive_closure",
"transitive_closure_dag",
"transitive_reduction",
"transitivity",
"triangles",
"union",
Expand Down Expand Up @@ -229,6 +232,9 @@ def get_info():
"reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.",
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.',
"single_source_bellman_ford_path_length": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.",
"transitive_closure": "Each node's neighbors come in node order, which may differ from NetworkX's. A closure\nof more than 2**24 edges, an undirected edge counted both ways, is left to NetworkX, to\nbound the memory of the graph built.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.",
"transitive_closure_dag": "Each node's neighbors come in node order, which may differ from NetworkX's. A closure\nof more than 2**24 edges, an undirected edge counted both ways, is left to NetworkX, to\nbound the memory of the graph built.\nA `topo_order` is served when it is a list or tuple of every node once, each edge's tail\nbefore its head. NetworkX follows any other order as given, so that is left to it.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.",
"transitive_reduction": "Each node's neighbors come in node order, which may differ from NetworkX's.",
"union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.",
"volume": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more, or to 2**63 over the most times `S` names one node.",
"wiener_index": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.',
Expand Down
16 changes: 16 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
# A closure can have about n**2 edges, each with a dict of its own in the graph built.
_CLOSURE = (
"Each node's neighbors come in node order, which may differ from NetworkX's. A closure\n"
"of more than 2**24 edges, an undirected edge counted both ways, is left to NetworkX, to\n"
"bound the memory of the graph built."
)

_ADDITIONAL_DOCS = {
"all_pairs_bellman_ford_path_length": _PATH_OVERFLOW,
"average_shortest_path_length": (
Expand Down Expand Up @@ -176,6 +183,13 @@
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"single_source_bellman_ford_path_length": _PATH_OVERFLOW,
"transitive_closure": _CLOSURE,
"transitive_closure_dag": _CLOSURE + "\n"
"A `topo_order` is served when it is a list or tuple of every node once, each edge's tail\n"
"before its head. NetworkX follows any other order as given, so that is left to it.",
"transitive_reduction": (
"Each node's neighbors come in node order, which may differ from NetworkX's."
),
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.",
"wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW,
}
Expand All @@ -198,6 +212,8 @@
"k_shell",
"k_truss",
"reverse",
"transitive_closure",
"transitive_closure_dag",
"union",
):
_doc = _ADDITIONAL_DOCS.get(_name)
Expand Down
124 changes: 121 additions & 3 deletions graphblas_algorithms/algorithms/dag.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
from graphblas import Vector, replace
import numpy as np
from graphblas import Matrix, Vector, agg, binary, replace, select, unary
from graphblas.semiring import any_pair

from ._bfs import _bfs_plain
from ._bfs import _bfs_plain, _visited
from .components._labels import component_labels

__all__ = ["ancestors", "descendants", "is_acyclic"]
__all__ = ["ancestors", "descendants", "is_acyclic", "transitive_closure", "transitive_reduction"]


def descendants(G, source):
Expand Down Expand Up @@ -44,3 +46,119 @@ def is_acyclic(G):
alive(~peel.S, replace) << alive
cache["is_acyclic"] = True
return True


# The most (source, node) slots one block of a walk from many sources holds; its bitmap is this
# many bytes. A graph of up to 8192 nodes is walked in one block.
_BLOCK_SLOTS = 2**26


def _blocks(A, least):
"""The sources with at least `least` out-edges, in blocks as large as `_BLOCK_SLOTS` allows.

The others have nothing to walk: a node with no out-edge reaches nothing, and the out-edge
of a node with one is the only way to its head, which the reduction keeps.
"""
counts = A.reduce_rowwise(agg.count).new(name="out_degrees")
ids, counts = counts.to_coo()
ids = ids[counts >= least]
size = max(1, _BLOCK_SLOTS // max(A.nrows, 1))
return [ids[start : start + size] for start in range(0, len(ids), size)]


def _out_edges(A, sources):
"""The out-edges of `sources`, one row each, as True."""
return unary.one[bool](A[sources, :].new()).new(name="out_edges")


def _walk(A, frontier, limit=None):
"""Where each row of `frontier` stands and everything it reaches from there.

A breadth-first search from every row at once, one product per level. None once more than
`limit` entries are reached.
"""
reached = _visited(frontier.dup(name="reached"))
any_pair_bool = any_pair[bool]
while frontier.nvals > 0:
frontier(~reached.S, replace) << any_pair_bool(frontier @ A)
reached(frontier.S) << True
if limit is not None and reached.nvals > limit:
return None
return reached


def _stacked(blocks, n):
"""(sources, rows) blocks, in order of their sources, as one n by n matrix of True."""
counts = np.zeros(n, np.int64)
cols = []
for sources, rows in blocks:
exported = rows.ss.export("csr", sort=True, give_ownership=True)
counts[sources] = np.diff(exported["indptr"])
cols.append(exported["col_indices"])
if not cols:
return Matrix(bool, n, n)
indptr = np.concatenate(([0], np.cumsum(counts)))
return Matrix.from_csr(indptr, np.concatenate(cols), True, nrows=n, ncols=n)


def _reachability(A, limit):
"""(i, j) when a path of one or more edges leads from i to j; None past `limit` entries.

So the diagonal holds each node on a cycle, a self-loop included.
"""
blocks = []
total = 0
for sources in _blocks(A, 1):
reached = _walk(A, _out_edges(A, sources), None if limit is None else limit - total)
if reached is None:
return None
total += reached.nvals
blocks.append((sources, reached))
return _stacked(blocks, A.nrows)


def transitive_closure(G, reflexive=False, *, limit=None):
"""The edges of `G`'s transitive closure, as a matrix of True over `G`'s ids.

(i, j) for each path from i to j, and every edge of `G`. `reflexive` True adds a self-loop at
every node, False one at each node on a cycle, and None none: NetworkX's choices. A cycle of
an undirected graph is one that does not walk back along an edge, so there False adds none.
None when the closure would hold more than `limit` pairs, an undirected pair counted both
ways and each node with itself.
"""
A = G._A
n = A.nrows
if G.is_directed():
R = _reachability(A, limit)
if R is None:
return None
if reflexive is False:
return R
else:
labels = component_labels(A)
sizes = np.bincount(labels, minlength=n)
if limit is not None and int(sizes @ sizes) > limit:
return None
# Every pair in one component, each node with itself.
C = Matrix.from_coo(np.arange(n), labels, True, nrows=n, ncols=n)
R = any_pair[bool](C @ C.T).new(name="transitive_closure")
if reflexive is True:
if G.is_directed():
R(binary.any) << Vector.from_scalar(True, n).diag()
return R
# No self-loop but those `G` has.
E = select.offdiag(R).new(name="transitive_closure")
E(binary.any) << unary.one[bool](select.diag(A).new())
return E


def transitive_reduction(G):
"""The edges of acyclic `G` that no path of two or more edges gives, as True over `G`'s ids."""
A = G._A
implied = []
for sources in _blocks(A, 2):
out = _out_edges(A, sources)
further = _walk(A, any_pair[bool](out @ A).new(name="frontier"))
implied.append((sources, out.dup(mask=further.S)))
implied = _stacked(implied, A.nrows)
return unary.one[bool](A).new(mask=~implied.S, name="transitive_reduction")
3 changes: 3 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,9 @@ class Dispatcher:
# =============
ancestors = mod.ancestors
descendants = mod.descendants
transitive_closure = mod.transitive_closure
transitive_closure_dag = mod.transitive_closure_dag
transitive_reduction = mod.transitive_reduction

mod = nxapi.distance_measures
# ===========================
Expand Down
175 changes: 172 additions & 3 deletions graphblas_algorithms/nxapi/dag.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,29 @@
from itertools import repeat, starmap

import numpy as np
from graphblas import Matrix, select

from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph
from graphblas_algorithms.algorithms.components._labels import _keys_by_id
from graphblas_algorithms.classes._utils import PRESERVE
from graphblas_algorithms.classes.digraph import to_directed_graph, to_graph
from graphblas_algorithms.utils import not_implemented_for

from .exception import NetworkXError
from ._utils import can_run
from .exception import NetworkXError, NetworkXUnfeasible

__all__ = ["ancestors", "descendants"]
__all__ = [
"ancestors",
"descendants",
"transitive_closure",
"transitive_closure_dag",
"transitive_reduction",
]

# The most edges a closure is built with, an undirected edge counting twice. Past it the call
# is declined (NotImplementedError) before the NetworkX graph is built. The call peaks at about
# 215 bytes an edge (NetworkX's own loop at about 180 to 205), so about 3.6 GB at the bound.
_MOST_CLOSURE_EDGES = 2**24


def descendants(G, source):
Expand All @@ -24,3 +44,152 @@ def ancestors(G, source):
raise NetworkXError(*e.args) from e
else:
return G.vector_to_nodeset(result)


def _too_many_edges(name):
return NotImplementedError(
f"{name} would have more than {_MOST_CLOSURE_EDGES} edges, past the bound this "
"backend keeps its memory under; networkx serves it"
)


def transitive_closure(G, reflexive=False):
if reflexive not in {None, True, False}:
raise NetworkXError("Incorrect value for the parameter `reflexive`")
G = to_graph(G, weight=PRESERVE)
if reflexive is None or reflexive is True or reflexive is False:
E = algorithms.transitive_closure(G, reflexive, limit=_MOST_CLOSURE_EDGES)
if E is None:
raise _too_many_edges("transitive_closure")
else:
# A value that only equals one of them, such as 1 or numpy's True: NetworkX adds no edge.
E = G._A.dup(dtype=bool)
return _networkx_graph(G, E, weight=G._weight, keep_graph=True)


def _ordered_by(G, topo_order):
"""Whether `topo_order` lists each node of `G` once, every edge's tail before its head."""
key_to_id = G._key_to_id
n = len(key_to_id)
if len(topo_order) != n:
return False
try:
ids = np.fromiter((key_to_id[node] for node in topo_order), np.int64, n)
except (KeyError, TypeError):
return False
place = np.full(n, -1, np.int64)
place[ids] = np.arange(n)
if (place < 0).any():
return False # a node listed twice, so another not at all
rows, cols, _values = G._A.to_coo(values=False)
return bool((place[rows] < place[cols]).all())


def _own_order(bound):
topo_order = bound.get("topo_order")
if topo_order is not None and not isinstance(topo_order, list | tuple):
return (
"transitive_closure_dag reads a `topo_order` other than a list or tuple as "
"NetworkX's loop does; networkx serves it"
)
return None


@can_run(_own_order)
@not_implemented_for("undirected")
def transitive_closure_dag(G, topo_order=None):
G = to_directed_graph(G, weight=PRESERVE)
if topo_order is None:
if not algorithms.is_acyclic(G):
raise NetworkXUnfeasible("Graph contains a cycle or graph changed during iteration")
elif not _ordered_by(G, topo_order):
# NetworkX does not check it: its answer follows the order given.
raise NotImplementedError(
"transitive_closure_dag with a `topo_order` that is not a topological order of "
"every node once is NetworkX's to answer; networkx serves it"
)
E = algorithms.transitive_closure(G, limit=_MOST_CLOSURE_EDGES)
if E is None:
raise _too_many_edges("transitive_closure_dag")
return _networkx_graph(G, E, weight=G._weight, keep_graph=True)


@not_implemented_for("undirected")
def transitive_reduction(G):
G = to_directed_graph(G)
if not algorithms.is_acyclic(G):
raise NetworkXError("Directed Acyclic Graph required for transitive_reduction")
return _networkx_graph(G, algorithms.transitive_reduction(G))


def _networkx_graph(G, E, *, weight=None, keep_graph=False):
"""The NetworkX graph with `G`'s nodes, in order, and the edges `E` holds over `G`'s ids.

An edge of `G` carries its value under `weight`; with None, or for any other edge, an edge
carries no data. A directed edge's data is one dict in both of its adjacencies, and an
undirected edge's in both directions, as NetworkX keeps them. The adjacency is written a row
at a time, several times faster than `add_edges_from`, which checks each edge in Python; a
closure may have millions. `E` is emptied, its arrays taken rather than copied.
"""
import networkx as nx

directed = G.is_directed()
H = nx.DiGraph() if directed else nx.Graph()
if keep_graph:
H.graph.update(G.graph)
H.add_nodes_from(G._key_to_id)
if E.nvals == 0:
return H
n = E.nrows
keys, _places = G._cacheit("keys_by_id", _keys_by_id, G)
if not directed:
E = select.triu(E).new() # each edge once; its two directions share its data
indptr, cols, _values = _csr(E)
count = len(cols)
# A new dict each: faster than a list display, which also leaves a list behind.
data = np.fromiter(starmap(dict, repeat((), count)), object, count)
_fill(H._adj, G._key_to_id, keys, indptr, cols, data)
# Each edge's place in `data`, read from its other end: the predecessors, or the lower
# triangle (a self-loop is written again, with the same dict).
places = Matrix.ss.import_csr(
nrows=n,
ncols=n,
indptr=indptr,
col_indices=cols,
values=np.arange(count, dtype=np.int64),
sorted_cols=True,
take_ownership=True,
)
del indptr, cols
other = places.T.new()
del places
indptr, cols, at = _csr(other)
del other
_fill(H._pred if directed else H._adj, G._key_to_id, keys, indptr, cols, data[at])
if weight is not None:
A = G._A if directed else select.triu(G._A).new()
rows, cols, values = A.to_coo()
adj = H._adj
# `tolist()` gives Python scalars; NetworkX rejects a numpy scalar in a result.
edges = zip(keys[rows].tolist(), keys[cols].tolist(), values.tolist(), strict=True)
for u, v, value in edges:
adj[u][v][weight] = value
return H


def _csr(M):
"""`M`'s CSR arrays, sorted, taken from it."""
exported = M.ss.export("csr", sort=True, give_ownership=True)
return exported["indptr"], exported["col_indices"], exported["values"]


def _fill(adj, key_to_id, keys, indptr, cols, data):
"""Each node's row of `cols` and `data` into its dict in `adj`."""
neighbors = keys[cols]
indptr = indptr.tolist()
for key, i in key_to_id.items():
start, stop = indptr[i], indptr[i + 1]
if start < stop:
adj[key].update(
zip(neighbors[start:stop].tolist(), data[start:stop].tolist(), strict=True)
)
Loading
Loading