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
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -279,6 +279,7 @@ graphblas_algorithms.nxapi
│ │ └── single_target_shortest_path_length
│ └── weighted
│ ├── all_pairs_bellman_ford_path_length
│ ├── all_pairs_dijkstra_path_length
│ ├── bellman_ford_path
│ ├── bellman_ford_path_length
│ ├── negative_edge_cycle
Expand Down
1 change: 1 addition & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ def get_info():
"adamic_adar_index",
"adjacency_matrix",
"all_pairs_bellman_ford_path_length",
"all_pairs_dijkstra_path_length",
"all_pairs_shortest_path_length",
"ancestors",
"average_clustering",
Expand Down
103 changes: 98 additions & 5 deletions graphblas_algorithms/algorithms/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
import math
from itertools import pairwise

import numpy as np
from graphblas import Matrix, Vector, binary, indexunary, monoid, replace, select, unary
from graphblas.dtypes import lookup_dtype
from graphblas.semiring import any_pair, min_plus

from .._bfs import _bfs_level, _bfs_levels, _bfs_parent
Expand All @@ -10,6 +14,7 @@
"bellman_ford_path",
"bellman_ford_path_length",
"bellman_ford_path_lengths",
"dijkstra_path_lengths",
"negative_edge_cycle",
"single_source_bellman_ford_path_length",
]
Expand Down Expand Up @@ -53,6 +58,17 @@ def _levels_to_lengths(levels, weight):
return levels


def _iso_walks(G, weight, cutoff):
"""`(weight, levels)`: what each edge of an iso-valued `G` weighs, and its level cutoff.

Where no edge joins two nodes no walk leaves a source, whose length is NetworkX's integer
0 whatever a self-loop weighs, inf included, which integer lengths do not hold.
"""
if G.get_property("offdiag").nvals == 0:
return 1, None
return weight, _level_cutoff(weight, G._A.nrows, cutoff)


def _bellman_ford_path_length(G, source, target=None, *, cutoff=None, name):
# No need for `is_weighted=` keyword, b/c this is assumed to be weighted (I think)
src_id = G._key_to_id[source]
Expand All @@ -66,9 +82,9 @@ def _bellman_ford_path_length(G, source, target=None, *, cutoff=None, name):
is_negative, iso_value = G.get_properties("has_negative_edges+ iso_value")
if not is_negative:
dtype = _length_dtype(G, G.get_property("offdiag"))
cutoff = _level_cutoff(iso_value.get(), G._A.nrows, cutoff)
weight, cutoff = _iso_walks(G, iso_value.get(), cutoff)
d = _bfs_level(G, source, target, cutoff=cutoff, dtype=dtype)
d = _levels_to_lengths(d, iso_value.get())
d = _levels_to_lengths(d, weight)
if dst_id is not None:
d = d.get(dst_id)
if d is None:
Expand Down Expand Up @@ -150,8 +166,8 @@ def bellman_ford_path_length(G, source, target):
return _bellman_ford_path_length(G, source, target, name="bellman_ford_path_length")


def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None):
"""Extra parameters: expand_output, dtype
def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None, cutoff=None):
"""Extra parameters: expand_output, dtype, cutoff

Parameters
----------
Expand All @@ -162,14 +178,19 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None)
The lengths' dtype. By default the values' own, or INT64 for integers, which raises
OverflowError where a length could reach 2**63; a caller whose answer is a float can
pass a floating-point type instead.
cutoff : number, optional
Only lengths at most `cutoff` are kept, as a value of the lengths' dtype; a source's
own 0 always is.
"""
# Same algorithms as in `single_source_bellman_ford_path_length`, but with
# `Cur` as a Matrix with each row corresponding to a source node.
if G.get_property("is_iso"):
is_negative, iso_value = G.get_properties("has_negative_edges+ iso_value")
if not is_negative:
dtype = _length_dtype(G, G.get_property("offdiag"), dtype)
D = _levels_to_lengths(_bfs_levels(G, nodes, dtype=dtype), iso_value.get())
weight, levels = _iso_walks(G, iso_value.get(), cutoff)
D = _bfs_levels(G, nodes, cutoff=levels, dtype=dtype)
D = _levels_to_lengths(D, weight)
if nodes is not None and expand_output and D.ncols != D.nrows:
ids = G.list_to_ids(nodes)
rv = Matrix(D.dtype, D.ncols, D.ncols, name=D.name)
Expand Down Expand Up @@ -209,6 +230,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None)
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
Expand All @@ -217,6 +240,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None)
D(Cur.S) << Cur
else:
Cur << min_plus[dtype](Cur @ A)
if cutoff is not None:
Cur << select.valuele(Cur, cutoff)
Mask << binary.lt(Cur & D)
if Mask.reduce_scalar(monoid.lor):
raise Unbounded("Negative cycle detected.")
Expand Down Expand Up @@ -365,3 +390,71 @@ def negative_edge_cycle(G):
if mask.reduce(monoid.lor):
return True
return False


# Dijkstra
#
# With no negative or NaN weight, adding an edge never shortens a walk, so the length NetworkX's
# Dijkstra gives a node is the least sum over the walks to it: what min-plus finds.

# Rows of lengths found at a time, so that a batch holds about 2**22 entries.
_BATCH_ENTRIES = 2**22


def _dijkstra_cutoff(cutoff, np_type):
"""`cutoff` as a value of the lengths' type that keeps what NetworkX keeps, or None for all.

NetworkX drops a length `x` where `x > cutoff`, so a NaN cutoff drops none. Lengths here
are never negative, so a negative cutoff keeps only the sources.
"""
if cutoff is None or (isinstance(cutoff, float) and math.isnan(cutoff)):
return None
if np_type.kind == "f":
if cutoff == math.inf:
return None
if cutoff == -math.inf:
return -1.0
value = float(cutoff)
if value > cutoff: # an integer that rounds up: the float below it keeps the same
value = math.nextafter(value, -math.inf)
return value
if cutoff < 0:
return -1
if cutoff >= 2**63 - 1:
return None
return int(cutoff) # its floor, as it is not negative


def dijkstra_path_lengths(G, nodes=None, *, cutoff=None):
"""Yield `(source id, ids, lengths)` per source in `nodes`, every node if None.

`ids` lists the nodes the source reaches within `cutoff`: the source, its length the
integer 0, and then the others by increasing length, equal lengths in id order. A
negative or NaN weight is not read as NetworkX's Dijkstra reads it, which follows the
order of its walk; the lengths are then Bellman-Ford's.
"""
if nodes is None:
nodes = list(G)
dtype = _length_dtype(G, G.get_property("offdiag"))
cutoff = _dijkstra_cutoff(cutoff, lookup_dtype(dtype).np_type)
batch = max(1, min(len(nodes), _BATCH_ENTRIES // max(len(G), 1)))
for start in range(0, len(nodes), batch):
keys = nodes[start : start + batch]
ids = G.list_to_ids(keys).astype(np.int64)
D = bellman_ford_path_lengths(G, keys, dtype=dtype, cutoff=cutoff)
rows, cols, vals = D.to_coo() # by row, then by id
rows = rows.astype(np.int64)
rowptr = np.zeros(D.nrows + 1, np.int64)
np.cumsum(np.bincount(rows, minlength=D.nrows), out=rowptr[1:])
# Lengths are not negative, so -1 puts the source first, ahead of any other at 0.
key = np.where(cols == ids[rows], -1, vals)
order = np.empty(rows.size, np.int64)
for lo, hi in pairwise(rowptr.tolist()):
order[lo:hi] = lo + np.argsort(key[lo:hi], kind="stable")
cols = cols[order].tolist()
vals = vals[order].tolist()
for i, src in enumerate(ids.tolist()):
lo, hi = rowptr[i], rowptr[i + 1]
lengths = vals[lo:hi]
lengths[0] = 0 # NetworkX's integer 0 for the source
yield src, cols[lo:hi], lengths
1 change: 1 addition & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,6 +405,7 @@ class Dispatcher:
single_source_shortest_path_length = mod.unweighted.single_source_shortest_path_length
single_target_shortest_path_length = mod.unweighted.single_target_shortest_path_length
all_pairs_bellman_ford_path_length = mod.weighted.all_pairs_bellman_ford_path_length
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
negative_edge_cycle = mod.weighted.negative_edge_cycle
Expand Down
58 changes: 57 additions & 1 deletion graphblas_algorithms/nxapi/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import numpy as np

from graphblas_algorithms import algorithms
from graphblas_algorithms.algorithms.shortest_paths.weighted import _length_dtype
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import normalize_chunksize, partition
from .._utils import can_run, normalize_chunksize, partition
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",
"negative_edge_cycle",
Expand Down Expand Up @@ -106,3 +110,55 @@ def negative_edge_cycle(G, weight="weight", heuristic=True):
# TODO: use a heuristic to try to stop early
G = to_graph(G, weight=weight)
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)
A = G._A
if G.get_property("has_negative_edges+") or (
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.
_length_dtype(G, G.get_property("offdiag"))
return _all_pairs_dijkstra_path_length(G, cutoff)


def _all_pairs_dijkstra_path_length(G, cutoff):
nodes = list(G)
id_to_key = G.id_to_key
keys = [id_to_key[i] for i in range(len(G))]
identity = all(key == i and type(key) is int for i, key in enumerate(keys))
for src, ids, lengths in algorithms.dijkstra_path_lengths(G, nodes, cutoff=cutoff):
if not identity:
ids = map(keys.__getitem__, ids)
yield keys[src], dict(zip(ids, lengths, strict=True))
Loading
Loading