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 @@ -282,8 +282,11 @@ graphblas_algorithms.nxapi
│ ├── all_pairs_dijkstra_path_length
│ ├── bellman_ford_path
│ ├── bellman_ford_path_length
│ ├── dijkstra_path_length
│ ├── multi_source_dijkstra_path_length
│ ├── negative_edge_cycle
│ └── single_source_bellman_ford_path_length
│ ├── single_source_bellman_ford_path_length
│ └── single_source_dijkstra_path_length
├── simple_paths
│ └── is_simple_path
├── smetric
Expand Down
3 changes: 3 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ def get_info():
"descendants_at_distance",
"diameter",
"difference",
"dijkstra_path_length",
"directed_modularity_matrix",
"disjoint_union",
"eccentricity",
Expand Down Expand Up @@ -123,6 +124,7 @@ def get_info():
"mixing_expansion",
"modularity",
"modularity_matrix",
"multi_source_dijkstra_path_length",
"mutual_weight",
"negative_edge_cycle",
"node_boundary",
Expand All @@ -149,6 +151,7 @@ def get_info():
"schultz_index",
"score_sequence",
"single_source_bellman_ford_path_length",
"single_source_dijkstra_path_length",
"single_source_shortest_path_length",
"single_target_shortest_path_length",
"square_clustering",
Expand Down
52 changes: 52 additions & 0 deletions graphblas_algorithms/algorithms/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
"bellman_ford_path",
"bellman_ford_path_length",
"bellman_ford_path_lengths",
"dijkstra_path_length",
"dijkstra_path_lengths",
"multi_source_dijkstra_path_length",
"negative_edge_cycle",
"single_source_bellman_ford_path_length",
]
Expand Down Expand Up @@ -458,3 +460,53 @@ def dijkstra_path_lengths(G, nodes=None, *, cutoff=None):
lengths = vals[lo:hi]
lengths[0] = 0 # NetworkX's integer 0 for the source
yield src, cols[lo:hi], lengths


def _dijkstra_vector(G, ids, *, cutoff=None, dst_id=None):
"""The least length from any node in `ids` to each node it reaches within `cutoff`.

A walk is relaxed one edge a round from the nodes whose length improved in the last one,
as in `bellman_ford_path_lengths`, but from all of `ids` at once. With `dst_id`, a walk
longer than the length found to it is dropped, so only its length is then the least.
"""
A = G.get_property("offdiag")
dtype = _length_dtype(G, A)
cutoff = _dijkstra_cutoff(cutoff, lookup_dtype(dtype).np_type)
n = A.nrows
d = Vector.from_coo(np.unique(ids), 0, dtype, size=n, name="dijkstra_path_length")
cur = d.dup(name="cur")
mask = Vector(bool, n, name="mask")
one = unary.one[bool]
for _i in range(n - 1):
cur << min_plus[dtype](cur @ A)
if cutoff is not None:
cur << select.valuele(cur, cutoff)
mask << one(cur)
mask(binary.second) << binary.lt(cur & d)
cur(mask.V, replace) << cur
if cur.nvals == 0:
break
d(cur.S) << cur
if dst_id is not None:
# Weights are not negative, so no walk past this length makes a shorter one.
cutoff = cur.get(dst_id, cutoff)
return d


def multi_source_dijkstra_path_length(G, sources, *, cutoff=None):
"""A Vector of the least length from any of `sources` to each node within `cutoff`.

Each source is at 0, whatever `cutoff` is. Where no weight is negative or NaN these are the
lengths NetworkX's Dijkstra gives; elsewhere its lengths follow the order of its walk.
"""
return _dijkstra_vector(G, G.list_to_ids(sources), cutoff=cutoff)


def dijkstra_path_length(G, source, target):
"""The least length from `source` to `target`, as `multi_source_dijkstra_path_length`."""
src_id = G._key_to_id[source]
dst_id = G._key_to_id[target]
d = _dijkstra_vector(G, [src_id], dst_id=dst_id).get(dst_id)
if d is None:
raise NoPath(f"node {target} not reachable from {source}")
return d
19 changes: 19 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -408,8 +408,11 @@ class Dispatcher:
all_pairs_dijkstra_path_length = mod.weighted.all_pairs_dijkstra_path_length
bellman_ford_path = mod.weighted.bellman_ford_path
bellman_ford_path_length = mod.weighted.bellman_ford_path_length
dijkstra_path_length = mod.weighted.dijkstra_path_length
multi_source_dijkstra_path_length = mod.weighted.multi_source_dijkstra_path_length
negative_edge_cycle = mod.weighted.negative_edge_cycle
single_source_bellman_ford_path_length = mod.weighted.single_source_bellman_ford_path_length
single_source_dijkstra_path_length = mod.weighted.single_source_dijkstra_path_length

mod = nxapi.simple_paths
# ======================
Expand Down Expand Up @@ -592,6 +595,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
165 changes: 132 additions & 33 deletions graphblas_algorithms/nxapi/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,23 @@
import numpy as np

from graphblas_algorithms import algorithms
from graphblas_algorithms.algorithms.components._labels import _keys_by_id
from graphblas_algorithms.algorithms.shortest_paths.weighted import _length_dtype
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import can_run, normalize_chunksize, partition
from .._utils import can_run, normalize_chunksize, partition, should_run
from ..exception import NetworkXNoPath, NetworkXUnbounded, NodeNotFound

__all__ = [
"all_pairs_bellman_ford_path_length",
"all_pairs_dijkstra_path_length",
"bellman_ford_path",
"bellman_ford_path_length",
"dijkstra_path_length",
"multi_source_dijkstra_path_length",
"negative_edge_cycle",
"single_source_bellman_ford_path_length",
"single_source_dijkstra_path_length",
]


Expand Down Expand Up @@ -112,44 +116,68 @@ def negative_edge_cycle(G, weight="weight", heuristic=True):
return algorithms.negative_edge_cycle(G)


_NAME = "all_pairs_dijkstra_path_length"
_CUTOFF_TYPES = (int, float, np.integer, np.float64)


def _dijkstra_can_run(bound):
G = bound["G"]
cutoff = bound["cutoff"]
if cutoff is not None and (
not isinstance(cutoff, _CUTOFF_TYPES)
or (isinstance(cutoff, (int, np.integer)) and abs(int(cutoff)) >= 2**53)
):
# NetworkX compares each length with `cutoff` as Python does, which for other types,
# or integers beyond float precision, need not be as a matrix of lengths compares.
return f"{_NAME} compares lengths with a cutoff of {type(cutoff).__name__} as networkx does"
if not hasattr(G, "_adj"):
return None # this backend's graph
import networkx as nx

if getattr(type(G), "adjacency", None) is not nx.Graph.adjacency:
# NetworkX's Dijkstra walks `G._adj`, and a conversion reads the adjacency this class
# reports instead, as `_AntiGraph`'s complement.
return f"{_NAME} walks `G._adj`, which this graph does not report as its adjacency"
return None


@can_run(_dijkstra_can_run)
def all_pairs_dijkstra_path_length(G, cutoff=None, weight="weight"):
G = to_graph(G, weight=weight)
def _dijkstra_rule(name):
"""The `can_run` rule of the Dijkstra length name `name`."""

def rule(bound):
G = bound["G"]
cutoff = bound.get("cutoff")
if cutoff is not None and (
not isinstance(cutoff, _CUTOFF_TYPES)
or (isinstance(cutoff, (int, np.integer)) and abs(int(cutoff)) >= 2**53)
):
# NetworkX compares each length with `cutoff` as Python does, which for other
# types, or integers beyond float precision, need not be as a matrix compares.
kind = type(cutoff).__name__
return f"{name} compares lengths with a cutoff of {kind} as networkx does"
if "target" in bound:
try:
hash(bound["target"])
except TypeError:
# NetworkX compares each node it reaches with the target, and then looks it up.
return f"{name} meets a target that is not hashable as networkx does"
if not hasattr(G, "_adj"):
return None # this backend's graph
import networkx as nx

if getattr(type(G), "adjacency", None) is not nx.Graph.adjacency:
# NetworkX's Dijkstra walks `G._adj`, and a conversion reads the adjacency this
# class reports instead, as `_AntiGraph`'s complement.
return f"{name} walks `G._adj`, which this graph does not report as its adjacency"
return None

return rule


def _negative_or_nan(G):
A = G._A
if G.get_property("has_negative_edges+") or (
return bool(G.get_property("has_negative_edges+")) or bool(
A.dtype.np_type.kind == "f" and np.isnan(A.to_coo(rows=False, columns=False)[2]).any()
):
# NetworkX's Dijkstra gives what its walk meets: which nodes a NaN length hides, which
# lengths a negative weight changes, and the item that raises "Contradictory paths".
raise NotImplementedError(f"{_NAME} with a negative or NaN weight is left to networkx")
# Bound integer sums now, when called, rather than at the first item: an error raised
# then reaches the caller after NetworkX's dispatcher has returned.
)


def _check_walk(G, name):
"""Raise where NetworkX's Dijkstra on `G` gives what its walk meets, not the least lengths.

That is which nodes a NaN length hides, which lengths a negative weight changes, and where
it raises "Contradictory paths"; NetworkX answers these. Integer weights whose sums could
reach 2**63 raise OverflowError. The check is kept with `G`, since NetworkX's own loops,
such as its `all_pairs_dijkstra_path_length`, ask for one source at a time.
"""
if G._cacheit("negative_or_nan", _negative_or_nan, G):
raise NotImplementedError(f"{name} with a negative or NaN weight is left to networkx")
_length_dtype(G, G.get_property("offdiag"))


@can_run(_dijkstra_rule("all_pairs_dijkstra_path_length"))
def all_pairs_dijkstra_path_length(G, cutoff=None, weight="weight"):
G = to_graph(G, weight=weight)
# Checked now, when called, rather than at the first item: an error raised then reaches
# the caller after NetworkX's dispatcher has returned.
_check_walk(G, "all_pairs_dijkstra_path_length")
return _all_pairs_dijkstra_path_length(G, cutoff)


Expand All @@ -162,3 +190,74 @@ def _all_pairs_dijkstra_path_length(G, cutoff):
if not identity:
ids = map(keys.__getitem__, ids)
yield keys[src], dict(zip(ids, lengths, strict=True))


def _lengths_from(G, sources, d):
"""`d`, the lengths from `sources`, as a dict of NetworkX's keys and order up to ties.

Each source comes first, as given, at the integer 0, and then the other nodes by increasing
length, equal lengths in id order.
"""
ids, lengths = d.to_coo()
is_source = np.zeros(len(G), bool)
is_source[G.list_to_ids(sources)] = True
others = ~is_source[ids]
order = np.argsort(lengths[others], kind="stable")
keys, _ = G._cacheit("keys_by_id", _keys_by_id, G)
rv = dict.fromkeys(sources, 0)
rv.update(zip(keys[ids[others][order]].tolist(), lengths[others][order].tolist(), strict=True))
return rv


def _one_walk(bound):
# NetworkX's Dijkstra from one source, or from several at once, reads each edge about once,
# as converting the graph does. Measured with the conversion counted, NetworkX was the
# faster on graphs of 1e5 edges, and of 1e6 but for random float weights on a random graph.
# With the conversion cached the backend was faster on random graphs and slower on grids,
# where it takes a round per edge of the longest path.
return "networkx walks from a few sources sooner than this backend converts the graph"


def _multi_source(G, sources, cutoff, name):
# NetworkX's checks, in its order; a generator is spent by the second and gives {}.
if not sources:
raise ValueError("sources must not be empty")
for s in sources:
if s not in G:
raise NodeNotFound(f"Node {s} not found in graph")
_check_walk(G, name)
sources = list(sources)
d = algorithms.multi_source_dijkstra_path_length(G, sources, cutoff=cutoff)
return _lengths_from(G, sources, d)


@can_run(_dijkstra_rule("multi_source_dijkstra_path_length"))
@should_run(_one_walk)
def multi_source_dijkstra_path_length(G, sources, cutoff=None, weight="weight"):
G = to_graph(G, weight=weight)
return _multi_source(G, sources, cutoff, "multi_source_dijkstra_path_length")


@can_run(_dijkstra_rule("single_source_dijkstra_path_length"))
@should_run(_one_walk)
def single_source_dijkstra_path_length(G, source, cutoff=None, weight="weight"):
G = to_graph(G, weight=weight)
# NetworkX passes `{source}`, whose TypeError an unhashable source raises here too.
return _multi_source(G, {source}, cutoff, "single_source_dijkstra_path_length")


@can_run(_dijkstra_rule("dijkstra_path_length"))
@should_run(_one_walk)
def dijkstra_path_length(G, source, target, weight="weight"):
G = to_graph(G, weight=weight)
if source not in G:
raise NodeNotFound(f"Node {source} not found in graph")
if source == target:
return 0
_check_walk(G, "dijkstra_path_length")
if target not in G:
raise NetworkXNoPath(f"Node {target} not reachable from {source}")
try:
return algorithms.dijkstra_path_length(G, source, target)
except algorithms.exceptions.NoPath as e:
raise NetworkXNoPath(f"Node {target} not reachable from {source}") from e
Loading
Loading