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: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
8 changes: 8 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down Expand Up @@ -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.',
Expand Down
25 changes: 25 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 = {
Expand Down Expand Up @@ -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,
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/tree/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .mst import *
from .recognition import *
90 changes: 90 additions & 0 deletions graphblas_algorithms/algorithms/tree/mst.py
Original file line number Diff line number Diff line change
@@ -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)
16 changes: 16 additions & 0 deletions graphblas_algorithms/classes/_utils.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import weakref
from collections.abc import Mapping
from itertools import islice

Expand All @@ -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.
Expand Down
41 changes: 39 additions & 2 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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"):
Expand All @@ -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:
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down
14 changes: 14 additions & 0 deletions graphblas_algorithms/nxapi/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
Loading
Loading