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
13 changes: 12 additions & 1 deletion graphblas_algorithms/algorithms/_bfs.py
Original file line number Diff line number Diff line change
@@ -1,14 +1,25 @@
"""BFS routines used by other algorithms"""

import math

import numpy as np
from graphblas import Matrix, Vector, binary, indexunary, replace, semiring, unary
from graphblas.semiring import any_pair


def _get_cutoff(n, cutoff):
"""One more than the steps a walk takes from its first level, for `range(1, ...)`.

NetworkX steps on while `cutoff > level`: a float such as 2.5 takes ceil(cutoff) steps, and
NaN, 0 or a negative cutoff takes none. A walk never needs more than `n - 1`.
"""
if isinstance(cutoff, np.generic):
cutoff = cutoff.item() # a Python number: numpy warns on casting `n` to a narrow float
if cutoff is None or cutoff >= n:
return n # Everything
return cutoff + 1 # Inclusive
if not cutoff > 0:
return 1 # The first level alone
return math.ceil(cutoff) + 1


def _adjacency(G, transpose=False):
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from math import ceil
import itertools

import numpy as np
from graphblas import Vector, replace
Expand All @@ -21,8 +21,7 @@ def bfs_edges(G, source, *, reverse=False, depth_limit=None):
edges are sorted by parent and then by child, in node order.
"""
id_to_key = G.id_to_key
if depth_limit is not None and depth_limit < len(G):
depth_limit = ceil(depth_limit) # NetworkX walks on while `depth < depth_limit`
# NetworkX walks on while `depth < depth_limit`, the rule `_get_cutoff` reads.
for child_ids, parent_ids in _bfs_parent_levels(
G, source, cutoff=depth_limit, transpose=reverse
):
Expand Down Expand Up @@ -73,13 +72,14 @@ def descendants_at_distance(G, source, distance):
n = A.nrows
q = Vector(bool, size=n, name=f"descendants_at_distance_{distance}")
q[index] = True
# NetworkX gives the layer `i` for which `i == distance`, so none for 2.5, NaN, inf or -1:
# those walk until the layers run out, as NetworkX's do.
if distance == 0:
return q
v = _visited(Vector(bool, size=n, name="bfs_seen"))
any_pair_bool = any_pair[bool]
for _i in range(1, distance + 1):
for i in itertools.count(1):
v(q.S) << True
q(~v.S, replace) << any_pair_bool(q @ A)
if q.nvals == 0:
break
return q
if q.nvals == 0 or i == distance:
return q
24 changes: 24 additions & 0 deletions graphblas_algorithms/nxapi/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,30 @@ def split_evenly(k, L):
yield L[stop:]


# A bound on a walk's levels read here as NetworkX reads it: an int (a bool too), a float no
# wider than a double, or a numpy integer. Others, such as a str, Decimal, Fraction or long
# double, compare by rules of their own, so NetworkX reads them.
_LEVEL_BOUND_TYPES = (int, float, np.integer, np.float16, np.float32)


def level_bound(param):
"""A `can_run` hook that leaves to NetworkX a `param` of a type it reads by other rules."""

def hook(bound):
value = bound.get(param)
if value is None or isinstance(value, _LEVEL_BOUND_TYPES):
return None
return f"a {param} of type {type(value).__name__} is left to networkx"

return hook


def check_level_bound(param, value):
"""Raise what `level_bound(param)` declines; a direct call does not pass through `can_run`."""
if (reason := level_bound(param)({param: value})) is not None:
raise NotImplementedError(reason)


def can_run(hook):
"""Give the decorated wrapper `hook` as its rule in `Dispatcher.can_run`.

Expand Down
35 changes: 33 additions & 2 deletions graphblas_algorithms/nxapi/generators/ego.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,42 @@
import math
import sys

import numpy as np

from graphblas_algorithms import generators
from graphblas_algorithms.classes._utils import PRESERVE
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import check_dijkstra_weights
from .._utils import can_run, check_dijkstra_weights, check_level_bound, level_bound
from ..exception import NodeNotFound

__all__ = ["ego_graph"]


def _radius(radius, distance, is_weighted):
"""`radius` as the walks here read it: a length, a count of edges, or None for no bound.

Without `distance` NetworkX walks while `radius > level`, which the breadth-first walk
reads too. With it, Dijkstra drops a length `> radius`, which keeps every length when
`radius` is NaN; where the edges lack `distance`, each is 1 long, so floor(radius) edges.
"""
if distance is None or radius is None:
return radius
if isinstance(radius, np.generic):
radius = radius.item() # a Python number: numpy warns on casting to a narrow float
# NaN, inf, or an int past every float, which a float conversion would refuse
if (isinstance(radius, float) and math.isnan(radius)) or radius > sys.float_info.max:
return None
if radius < 0:
return -1 # the center alone
return radius if is_weighted else math.floor(radius)


@can_run(level_bound("radius"))
def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
# A subgraph keeps the input's edge data whatever `distance` names. NetworkX reads a
# `distance` the edges do not carry as 1, so the radius is then a hop count.
check_level_bound("radius", radius)
G = to_graph(G, weight=PRESERVE)
if n not in G:
# NetworkX's shortest-path helpers raise these, by whether `distance` is given.
Expand All @@ -22,5 +48,10 @@ def ego_graph(G, n, radius=1, center=True, undirected=False, distance=None):
# NetworkX walks `distance` with Dijkstra.
check_dijkstra_weights(G, "ego_graph")
return generators.ego_graph(
G, n, radius=radius, center=center, undirected=undirected, is_weighted=is_weighted
G,
n,
radius=_radius(radius, distance, is_weighted),
center=center,
undirected=undirected,
is_weighted=is_weighted,
)
8 changes: 7 additions & 1 deletion graphblas_algorithms/nxapi/shortest_paths/unweighted.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import normalize_chunksize, partition
from .._utils import can_run, check_level_bound, level_bound, normalize_chunksize, partition
from ..exception import NodeNotFound

__all__ = [
Expand All @@ -11,23 +11,29 @@
]


@can_run(level_bound("cutoff"))
def single_source_shortest_path_length(G, source, cutoff=None):
check_level_bound("cutoff", cutoff)
G = to_graph(G)
if source not in G:
raise NodeNotFound(f"Source {source} is not in G")
v = algorithms.single_source_shortest_path_length(G, source, cutoff)
return G.vector_to_nodemap(v)


@can_run(level_bound("cutoff"))
def single_target_shortest_path_length(G, target, cutoff=None):
check_level_bound("cutoff", cutoff)
G = to_graph(G)
if target not in G:
raise NodeNotFound(f"Target {target} is not in G")
v = algorithms.single_target_shortest_path_length(G, target, cutoff)
return G.vector_to_nodemap(v)


@can_run(level_bound("cutoff"))
def all_pairs_shortest_path_length(G, cutoff=None, *, chunksize="10 MiB"):
check_level_bound("cutoff", cutoff)
G = to_graph(G)
chunksize = normalize_chunksize(chunksize, len(G) * G._A.dtype.np_type.itemsize, len(G))
if chunksize is None:
Expand Down
75 changes: 75 additions & 0 deletions graphblas_algorithms/nxapi/tests/test_ego.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@
without it, so naming one the graph does not carry makes the radius a hop count.
"""

import math

import networkx as nx
import numpy as np
import pytest

from graphblas_algorithms import DiGraph, Graph, nxapi
Expand Down Expand Up @@ -92,3 +95,75 @@ def test_a_negative_cycle_is_left_to_networkx(cls, edges, radius):
nx.ego_graph(G, 0, radius=radius, distance="weight")
with pytest.raises(NotImplementedError):
nx.ego_graph(G, 0, radius=radius, distance="weight", backend="graphblas")


def branched(directed, costs):
"""A graph whose edges carry "cost" as `costs` says, with graph data and an isolated node.

A rebuilt graph cannot keep node data, so the backend declines a graph that has any.
"""
G = nx.DiGraph() if directed else nx.Graph()
G.graph["name"] = "branched"
pairs = [(0, 1), (1, 2), (2, 3), (3, 4), (1, 5), (5, 0)]
values = {"varied": [1.0, 0.5, 2.0, 1.0, 1.5, 1.0], "equal": [1.0] * 6}.get(costs)
for i, (u, v) in enumerate(pairs):
G.add_edge(u, v, **({} if values is None else {"cost": values[i]}))
G.add_node(6) # reached by nothing
return G


def everything(H):
"""A result's class, graph data, nodes and edges with their data; or its exception."""
if isinstance(H, Exception):
return type(H).__name__, str(H)
H = Dispatcher.convert_to_nx(H)
return (
H.is_directed(),
dict(H.graph),
sorted(H.nodes(data=True)),
sorted((u, v, sorted(d.items())) for u, v, d in H.edges(data=True)),
)


def ego(G, **kwargs):
try:
return nx.ego_graph(G, 0, **kwargs)
except Exception as exc:
return exc


@pytest.mark.parametrize(
"radius",
[2.5, 2.0, 1.5, 0.5, 0.0, -0.5, -1.0, 2, math.inf, -math.inf, math.nan, np.float32(math.nan)],
ids=repr,
)
@DISTANCES
@pytest.mark.parametrize("directed", [False, True], ids=["undirected", "directed"])
@pytest.mark.parametrize("costs", ["varied", "equal", "none"])
@pytest.mark.parametrize("center", [True, False])
@pytest.mark.parametrize("undirected", [False, True], ids=["", "undirected=True"])
def test_a_float_radius_as_networkx(radius, distance, directed, costs, center, undirected):
"""Each answer is NetworkX's: its nodes, edges, their data and the graph data.

Without `distance` NetworkX steps while `radius > level`, so 2.5 reaches 3 edges out and
NaN none. With it, Dijkstra drops a length `> radius`, so 2.5 reaches 2 edges out where
each is 1 long, and NaN reaches every node.
"""
kwargs = {"radius": radius, "center": center, "undirected": undirected}
if distance is not None:
kwargs["distance"] = distance
expected = everything(ego(branched(directed, costs), **kwargs))
assert everything(ego(branched(directed, costs), backend="graphblas", **kwargs)) == expected


@DISTANCES
@pytest.mark.parametrize("costs", ["varied", "none"])
@pytest.mark.parametrize(("radius", "reached"), [(10**400, 6), (-(10**400), 1)], ids=["+", "-"])
def test_an_int_radius_past_every_float(distance, costs, radius, reached):
"""No float holds it, so a conversion to one would raise OverflowError."""
kwargs = {"radius": radius}
if distance is not None:
kwargs["distance"] = distance
expected = everything(ego(branched(False, costs), **kwargs))
assert len(expected[2]) == reached # every node but the isolated one, or the center alone
assert everything(ego(branched(False, costs), backend="graphblas", **kwargs)) == expected
Loading
Loading