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
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -294,11 +294,16 @@ graphblas_algorithms.nxapi
│ ├── score_sequence
│ └── tournament_matrix
├── traversal
│ └── breadth_first_search
│ ├── bfs_edges
│ ├── bfs_layers
│ ├── bfs_successors
│ └── descendants_at_distance
│ ├── breadth_first_search
│ │ ├── bfs_edges
│ │ ├── bfs_labeled_edges
│ │ ├── bfs_layers
│ │ ├── bfs_predecessors
│ │ ├── bfs_successors
│ │ ├── bfs_tree
│ │ └── descendants_at_distance
│ └── edgebfs
│ └── edge_bfs
├── tree
│ └── recognition
│ ├── is_arborescence
Expand Down
12 changes: 10 additions & 2 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,11 @@ def get_info():
"betweenness_centrality",
"betweenness_centrality_subset",
"bfs_edges",
"bfs_labeled_edges",
"bfs_layers",
"bfs_predecessors",
"bfs_successors",
"bfs_tree",
"boundary_expansion",
"center",
"closeness_centrality",
Expand All @@ -65,6 +68,7 @@ def get_info():
"eccentricity",
"edge_betweenness_centrality",
"edge_betweenness_centrality_subset",
"edge_bfs",
"edge_boundary",
"edge_expansion",
"efficiency",
Expand Down Expand Up @@ -196,8 +200,11 @@ def get_info():
"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.",
"betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.",
"betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.",
"bfs_edges": "A breadth-first tree with NetworkX's nodes and depths, which may differ from NetworkX's\ntree, as may the order: a node's parent is its neighbor on the level above first in\nnode order, and the edges come level by level, each level by child in node order. A\nparent's children need not come together. `sort_neighbors` is left to NetworkX.",
"bfs_successors": "The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order:\nlevel by level, each level's parents in node order. `sort_neighbors` is left to NetworkX.",
"bfs_edges": 'A breadth-first tree with NetworkX\'s nodes and depths, which may differ from NetworkX\'s\ntree, as may the order: a node\'s parent is its neighbor on the level above first in\nnode order, and the edges come level by level, each level by child in node order. A\nparent\'s children need not come together.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.',
"bfs_labeled_edges": "NetworkX's edges and labels, from `bfs_edges`'s tree, so which edges are tree edges and\nwhich forward edges may differ from NetworkX's, as may the direction of an undirected\nlevel edge and the order: the sources first, then each level in node order, each\nnode's edges by the other end's node order. Served for this backend's graphs; a\nNetworkX graph is left to NetworkX, which is faster than converting it, and faster too\nwhere a caller reads a few edges from many sources, as `girth` does.",
"bfs_predecessors": 'The parents in `bfs_edges`\'s tree, which may differ from NetworkX\'s, in its order, with\nNetworkX\'s DeprecationWarning where NetworkX gives one.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.\nA NetworkX graph is served where it is converted either way: where a conversion of it is\ncached, or where this backend serves `bfs_edges`, which NetworkX\'s own version calls.\nElsewhere it is left to NetworkX, which is faster than converting it.',
"bfs_successors": 'The children in `bfs_edges`\'s tree, which may differ from NetworkX\'s, as may the order:\nlevel by level, each level\'s parents in node order.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.',
"bfs_tree": '`bfs_edges`\'s tree, which may differ from NetworkX\'s: the source, then each level\'s\nnodes in node order. For this backend\'s graph it is this backend\'s DiGraph; for a\nNetworkX graph, NetworkX\'s DiGraph, built as NetworkX builds it.\n`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\nbackend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.\nServed for this backend\'s graphs and with `backend="graphblas"`. On the automatic\npath a NetworkX graph is left to NetworkX, whose own `bfs_tree` walks with the\n`bfs_edges` its priority names, this backend\'s included: building NetworkX\'s DiGraph\ncosts the same either way, and a deep graph\'s walk costs more here.',
"center": '`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.',
"closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".',
"common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.",
Expand All @@ -208,6 +215,7 @@ def get_info():
"eccentricity": 'A precomputed `sp`, and the null graph, are 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.',
"edge_betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\nThe edges come by their first ends in node order, then by their second ends in node\norder, which may differ from the order of `G.edges()`.",
"edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.",
"edge_bfs": 'Each edge NetworkX yields, once, with NetworkX\'s orientation where it is fixed, in a\nbreadth-first order that may differ from NetworkX\'s: the nodes in `source` first, then\neach level by node order, each node\'s edges by the other end\'s node order, out-edges\nbefore in-edges. An undirected edge, or with `orientation="ignore"` a directed one,\ncomes from the end met first, so between two nodes at one depth its direction or label\nmay differ.',
"ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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.',
"floyd_warshall": "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.",
"floyd_warshall_predecessor_and_distance": "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.",
Expand Down
47 changes: 45 additions & 2 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@
"A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX."
)

_CONVERTED_EITHER_WAY = (
"A NetworkX graph is served where it is converted either way: where a conversion of it is\n"
"cached, or where this backend serves `bfs_edges`, which NetworkX's own version calls.\n"
"Elsewhere it is left to NetworkX, which is faster than converting it."
)
_SORT_NEIGHBORS = (
"`sort_neighbors` is left to NetworkX for a NetworkX graph on the automatic path; for this\n"
'backend\'s graph, or with `backend="graphblas"`, it raises NotImplementedError.'
)

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_ADDITIONAL_DOCS = {
Expand All @@ -117,11 +127,36 @@
"A breadth-first tree with NetworkX's nodes and depths, which may differ from NetworkX's\n"
"tree, as may the order: a node's parent is its neighbor on the level above first in\n"
"node order, and the edges come level by level, each level by child in node order. A\n"
"parent's children need not come together. `sort_neighbors` is left to NetworkX."
"parent's children need not come together.\n" + _SORT_NEIGHBORS
),
"bfs_labeled_edges": (
"NetworkX's edges and labels, from `bfs_edges`'s tree, so which edges are tree edges and\n"
"which forward edges may differ from NetworkX's, as may the direction of an undirected\n"
"level edge and the order: the sources first, then each level in node order, each\n"
"node's edges by the other end's node order. Served for this backend's graphs; a\n"
"NetworkX graph is left to NetworkX, which is faster than converting it, and faster too\n"
"where a caller reads a few edges from many sources, as `girth` does."
),
"bfs_predecessors": (
"The parents in `bfs_edges`'s tree, which may differ from NetworkX's, in its order, with\n"
"NetworkX's DeprecationWarning where NetworkX gives one.\n"
+ _SORT_NEIGHBORS
+ "\n"
+ _CONVERTED_EITHER_WAY
),
"bfs_successors": (
"The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order:\n"
"level by level, each level's parents in node order. `sort_neighbors` is left to NetworkX."
"level by level, each level's parents in node order.\n" + _SORT_NEIGHBORS
),
"bfs_tree": (
"`bfs_edges`'s tree, which may differ from NetworkX's: the source, then each level's\n"
"nodes in node order. For this backend's graph it is this backend's DiGraph; for a\n"
"NetworkX graph, NetworkX's DiGraph, built as NetworkX builds it.\n"
+ _SORT_NEIGHBORS
+ '\nServed for this backend\'s graphs and with `backend="graphblas"`. On the automatic\n'
"path a NetworkX graph is left to NetworkX, whose own `bfs_tree` walks with the\n"
"`bfs_edges` its priority names, this backend's included: building NetworkX's DiGraph\n"
"costs the same either way, and a deep graph's walk costs more here."
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
Expand All @@ -144,6 +179,14 @@
"in node order, then by their second ends in node order, which may differ from the order\n"
"of `G.edges()`."
),
"edge_bfs": (
"Each edge NetworkX yields, once, with NetworkX's orientation where it is fixed, in a\n"
"breadth-first order that may differ from NetworkX's: the nodes in `source` first, then\n"
"each level by node order, each node's edges by the other end's node order, out-edges\n"
'before in-edges. An undirected edge, or with `orientation="ignore"` a directed one,\n'
"comes from the end met first, so between two nodes at one depth its direction or label\n"
"may differ."
),
"ego_graph": (
"With `distance`, lengths are Bellman-Ford's, so a negative edge without a negative\n"
'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\n'
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/traversal/__init__.py
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
from .breadth_first_search import *
from .edgebfs import *
148 changes: 146 additions & 2 deletions graphblas_algorithms/algorithms/traversal/breadth_first_search.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,33 @@
from math import ceil

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

from .._bfs import _bfs_parent_levels, _visited
from graphblas_algorithms.classes.digraph import DiGraph

from .._bfs import _adjacency, _bfs_parent_levels, _visited
from ..components._labels import _keys_by_id
from .edgebfs import _csr, _rows

__all__ = [
"bfs_edges",
"bfs_labeled_edges",
"bfs_layers",
"bfs_predecessors",
"bfs_successors",
"bfs_tree",
"descendants_at_distance",
]

# The kinds of edge `bfs_labeled_edges` gives, in the order of NetworkX's names for them.
TREE_EDGE, LEVEL_EDGE, FORWARD_EDGE, REVERSE_EDGE = range(4)


def _levels(G, source, depth_limit, reverse=False):
if depth_limit is not None and not depth_limit >= 0:
# NetworkX walks no level for a limit below 0, -inf or NaN alike.
return iter(())
if depth_limit is not None and depth_limit < len(G):
depth_limit = ceil(depth_limit) # NetworkX walks on while `depth < depth_limit`
return _bfs_parent_levels(G, source, cutoff=depth_limit, transpose=reverse)
Expand Down Expand Up @@ -56,6 +69,137 @@ def bfs_successors(G, source, *, depth_limit=None):
yield source, []


def bfs_predecessors(G, source, *, depth_limit=None):
"""Yield `(child, parent)` for each edge of `bfs_edges`'s tree, in its order.

The source is yielded as given, as NetworkX does.
"""
keys, _places = G._cacheit("keys_by_id", _keys_by_id, G)
first = True
for child_ids, parent_ids in _levels(G, source, depth_limit):
children = keys[child_ids].tolist()
if first:
# Every node of the first level is the source's child.
first = False
yield from zip(children, [source] * len(children), strict=True)
else:
yield from zip(children, keys[parent_ids].tolist(), strict=True)


def bfs_tree(G, source, *, reverse=False, depth_limit=None):
"""`bfs_edges`'s tree as a DiGraph of this backend: an edge from each parent to its child.

Its nodes are the source, as given, then each level's nodes in node order, as `bfs_edges`
yields them; its edges carry no values.
"""
index = G._key_to_id[source]
order = [np.array([index], np.int64)]
parents = [np.empty(0, np.int64)]
for child_ids, parent_ids in _levels(G, source, depth_limit, reverse):
order.append(child_ids.astype(np.int64))
parents.append(parent_ids.astype(np.int64))
order = np.concatenate(order)
k = len(order)
renumber = np.empty(len(G), np.int64)
renumber[order] = np.arange(k)
A = Matrix.from_coo(
renumber[np.concatenate(parents)],
renumber[order[1:]],
True,
dtype=bool,
nrows=k,
ncols=k,
name="bfs_tree",
)
keys, _places = G._cacheit("keys_by_id", _keys_by_id, G)
names = keys[order].tolist()
names[0] = source
return DiGraph(A, key_to_id=dict(zip(names, range(k), strict=True)))


def _parent_levels(G, source_ids):
"""Yield `(child_ids, parent_ids)` for each level below the nodes `source_ids`, nearest first.

`_bfs_parent_levels`'s walk from several sources, each node reached getting the neighbor on
the level above that the walk takes first: a source in the order given, then a node in node
order. So the first level's values are the sources' places in `source_ids`, mapped back.
"""
A = _adjacency(G)
n = A.nrows
seen = _visited(Vector(bool, n, name="seen"))
seen.build(source_ids, np.ones(len(source_ids), bool))
q = Vector.from_coo(source_ids, np.arange(len(source_ids)), size=n, name="q")
min_first = semiring.min_first[int]
own_index = indexunary.index[int]
first = True
while True:
q(~seen.S, replace) << min_first(q @ A)
if q.nvals == 0:
return
seen(q.S) << True
child_ids, parent_ids = q.to_coo()
if first:
first, parent_ids = False, source_ids[parent_ids]
yield child_ids, parent_ids
q << own_index(q)


def bfs_labeled_edges(G, source_ids):
"""Yield `(tails, heads, labels)`, as ids: the edges NetworkX's `bfs_labeled_edges` yields.

`source_ids` are unique ids, in the order given. The walk is `_parent_levels`'s, so the
tree is `bfs_edges`'s for one source. Each node reached, the sources first, then each level
in node order, gives its edges by the node order of their heads: TREE_EDGE to a child,
LEVEL_EDGE within a level, FORWARD_EDGE to the level below otherwise, and REVERSE_EDGE
back up, which an undirected graph leaves out, as it gives a level edge once, from the end
reached first. A self-loop is a level edge.

The walk goes as far as the edges asked for need, as NetworkX's does, so a caller that
stops early, as NetworkX's `girth` does, leaves the rest undone. The first part is the
sources' edges; each later part holds whole levels, about twice as many nodes as the one
before it, and is labelled once the level after it is known.
"""
n = len(G)
csr = _csr(G, False)
depth = np.full(n, -1, np.int64)
parent = np.full(n, -1, np.int64)
position = np.empty(n, np.int64) # in the walk's order, for an undirected level edge
depth[source_ids] = 0
position[source_ids] = np.arange(len(source_ids))
placed = len(source_ids)

def labelled(levels):
tails, heads = _rows(*csr, np.concatenate(levels))
tail_depth, head_depth = depth[tails], depth[heads]
labels = np.where(
tail_depth == head_depth,
LEVEL_EDGE,
np.where(tail_depth < head_depth, FORWARD_EDGE, REVERSE_EDGE),
)
labels[parent[heads] == tails] = TREE_EDGE
if not G.is_directed():
keep = (labels != REVERSE_EDGE) & (
(labels != LEVEL_EDGE) | (position[tails] <= position[heads])
)
tails, heads, labels = tails[keep], heads[keep], labels[keep]
return tails, heads, labels

pending, size, part = [source_ids], len(source_ids), 1
for level, (child_ids, parent_ids) in enumerate(_parent_levels(G, source_ids), 1):
child_ids = child_ids.astype(np.int64)
depth[child_ids] = level
parent[child_ids] = parent_ids
position[child_ids] = np.arange(placed, placed + len(child_ids))
placed += len(child_ids)
# The heads of the pending levels all have their depths now.
if size >= part:
yield labelled(pending)
pending, size, part = [], 0, 2 * size
pending.append(child_ids)
size += len(child_ids)
yield labelled(pending)


def bfs_layers(G, sources):
if sources in G:
sources = [sources]
Expand Down
Loading
Loading