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
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,9 @@ graphblas_algorithms.nxapi
├── boundary
│ ├── edge_boundary
│ └── node_boundary
├── bridges
│ ├── bridges
│ └── has_bridges
├── centrality
│ ├── betweenness
│ │ ├── betweenness_centrality
Expand Down
4 changes: 4 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ def get_info():
"bfs_layers",
"bfs_successors",
"boundary_expansion",
"bridges",
"center",
"closeness_centrality",
"clustering",
Expand Down Expand Up @@ -86,6 +87,7 @@ def get_info():
"gutman_index",
"harmonic_centrality",
"harmonic_diameter",
"has_bridges",
"has_path",
"hits",
"hyper_wiener_index",
Expand Down Expand Up @@ -198,6 +200,7 @@ def get_info():
"betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.",
"bfs_edges": "A breadth-first tree that may differ from NetworkX's, as may the order: a node's parent\nis its neighbor on the level above first in node order, and each level comes by parent,\nthen child, in node order. `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.\n`sort_neighbors` is left to NetworkX.",
"bridges": "Each bridge comes once, as `(u, v)` with `u` before `v` in node order, by `u` and then\n`v` in node order, which may differ from the order of `G.edges()`. A NetworkX graph\nthat would have to be converted is left to NetworkX, the faster there, unless it has\n100000 nodes or more and 1.2 edges per node or more; one NetworkX will give a cached\nconversion is served from 10000 nodes.\nWith `root`, NetworkX searches the root's component alone, so a NetworkX graph is served\nonly on a cached conversion, or, unless it is a view, where this backend serves\n`node_connected_component`, which NetworkX's own `bridges` then calls. A backend graph\nis always served; with `root`, the root's component alone is searched where a short walk\nfrom the root finds it.",
"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 @@ -215,6 +218,7 @@ def get_info():
"gutman_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 2**63.',
"harmonic_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".',
"harmonic_diameter": 'A precomputed `sp` 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".',
"has_bridges": "Served wherever `bridges` would serve the call NetworkX's own `has_bridges` makes to\nit, as this backend is then in `bridges`' priority. Elsewhere a NetworkX graph that\nwould have to be converted is left to NetworkX, the faster there (its scan of the edges\nstops at the first bridge), unless it has 200000 nodes or more and 2 edges per node or\nmore, or 300000 nodes and 1.2 edges per node; one NetworkX will give a cached\nconversion is served from 10000 nodes.\nWith `root`, NetworkX searches the root's component alone, so a NetworkX graph is served\nonly on a cached conversion, or, unless it is a view, where this backend serves\n`node_connected_component`, which NetworkX's own `bridges` then calls. A backend graph\nis always served; with `root`, the root's component alone is searched where a short walk\nfrom the root finds it.",
"hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.',
"hyper_wiener_index": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node's targets could\nreach 2**63.",
"k_core": "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.",
Expand Down
22 changes: 22 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_BRIDGES_ROOT = (
"With `root`, NetworkX searches the root's component alone, so a NetworkX graph is served\n"
"only on a cached conversion, or, unless it is a view, where this backend serves\n"
"`node_connected_component`, which NetworkX's own `bridges` then calls. A backend graph\n"
"is always served; with `root`, the root's component alone is searched where a short walk\n"
"from the root finds it."
)
_ADDITIONAL_DOCS = {
"all_pairs_bellman_ford_path_length": _PATH_OVERFLOW,
"average_shortest_path_length": (
Expand All @@ -122,6 +129,13 @@
"The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n"
"`sort_neighbors` is left to NetworkX."
),
"bridges": (
"Each bridge comes once, as `(u, v)` with `u` before `v` in node order, by `u` and then\n"
"`v` in node order, which may differ from the order of `G.edges()`. A NetworkX graph\n"
"that would have to be converted is left to NetworkX, the faster there, unless it has\n"
"100000 nodes or more and 1.2 edges per node or more; one NetworkX will give a cached\n"
"conversion is served from 10000 nodes.\n" + _BRIDGES_ROOT
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
"common_neighbor_centrality": (
Expand Down Expand Up @@ -155,6 +169,14 @@
"gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"harmonic_centrality": _NEGATIVE_EDGES,
"has_bridges": (
"Served wherever `bridges` would serve the call NetworkX's own `has_bridges` makes to\n"
"it, as this backend is then in `bridges`' priority. Elsewhere a NetworkX graph that\n"
"would have to be converted is left to NetworkX, the faster there (its scan of the edges\n"
"stops at the first bridge), unless it has 200000 nodes or more and 2 edges per node or\n"
"more, or 300000 nodes and 1.2 edges per node; one NetworkX will give a cached\n"
"conversion is served from 10000 nodes.\n" + _BRIDGES_ROOT
),
"harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES,
"hits": (
"A graph with nodes and no edges gets 0.0 for every node, where NetworkX's power\n"
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from . import exceptions
from .boundary import *
from .bridges import *
from .centrality import *
from .cluster import *
from .community import *
Expand Down
245 changes: 245 additions & 0 deletions graphblas_algorithms/algorithms/bridges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,245 @@
"""Bridges by Tarjan and Vishkin's method, with no walk that takes a step per level.

A spanning forest comes from Boruvka's rounds, and each tree's Euler tour, ranked by pointer
jumping, numbers its nodes in preorder and gives each subtree's size. A subtree is then a run of
preorder numbers, and the tree edge above it is a bridge iff no non-tree edge leaves that run:
the least and greatest numbers its nodes reach by one lie inside it. Every step is a numpy pass,
and how many there are grows with log n, not with how deep the trees are; a breadth-first
search takes a step per level, and a path graph has as many levels as nodes.
"""

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

from .components._labels import _keys_by_id

__all__ = ["bridge_ids", "has_bridges"]


def _spanning_forest(n, us, vs):
"""Which edges `us[i]`-`vs[i]` make a spanning forest, and each node's tree, named by a node.

Boruvka's rounds, with an edge's position as its weight: each tree takes the first edge
that leaves it. With weights all different, the edges taken close no cycle, except that two
trees may take the same edge. Each round at least halves the trees that have an edge out.
"""
in_forest = np.zeros(len(us), bool)
label = np.arange(n)
edges = np.arange(len(us))
lu, lv = us, vs # The trees at each end
while True:
crossing = lu != lv
edges, lu, lv = edges[crossing], lu[crossing], lv[crossing]
k = len(edges)
if k == 0:
return in_forest, label
first = np.full(n, k)
place = np.arange(k)
np.minimum.at(first, lu, place)
np.minimum.at(first, lv, place)
hooked = np.flatnonzero(first < k)
taken = first[hooked]
in_forest[edges[taken]] = True
target = np.where(lu[taken] == hooked, lv[taken], lu[taken])
parent = np.arange(n)
parent[hooked] = target
# Two trees that took the same edge point at each other; the smaller stays a root.
mutual = (parent[target] == hooked) & (hooked < target)
parent[hooked[mutual]] = hooked[mutual]
while True:
grand = parent[parent]
if np.array_equal(grand, parent):
break
parent = grand
label = parent[label]
lu = parent[lu]
lv = parent[lv]


def _euler_tours(n, tu, tv, label):
"""The arcs of the forest `tu[i]`-`tv[i]` as `(src, dst, after, twin, roots)`.

Arc `i` and arc `i + t` are the two ways along forest edge `i`, so `twin` maps each to the
other; `after` counts the arcs that follow each arc in its tree's tour. A tree's tour starts
at its label along its first arc, and `roots` holds those labels in order.
"""
t = len(tu)
src = np.concatenate([tu, tv])
dst = np.concatenate([tv, tu])
twin = np.concatenate([np.arange(t, 2 * t), np.arange(t)])
order = np.argsort(src, kind="stable")
place = np.empty(2 * t, np.intp)
place[order] = np.arange(2 * t)
degree = np.bincount(src, minlength=n)
stop = np.cumsum(degree)
start = stop - degree
# The arc after `u -> v` is the arc out of `v` that follows `v -> u`, round `v`'s arcs.
nxt = place[twin] + 1
wrap = nxt == stop[dst]
nxt[wrap] = start[dst[wrap]]
succ = np.empty(2 * t + 1, np.intp)
succ[: 2 * t] = order[nxt]
end = 2 * t
succ[end] = end
roots = np.flatnonzero((label == np.arange(n)) & (degree > 0))
# Cut each tour where it would come back round to its root's first arc.
succ[twin[order[stop[roots] - 1]]] = end
after = (succ != end).astype(np.intp)
while True:
after += after[succ]
succ = succ[succ]
if (succ == end).all():
return src, dst, after[:-1], twin, roots


def _entries_by_row(A):
"""`A`'s entries as `(rows, cols)`, each row's entries together, however `A` is stored.

`to_coo` lists them in the order the matrix keeps them: by row, or by column in a matrix
stored by column, hypersparse, bitmap or not.
"""
rows, cols, _ = A.to_coo(values=False)
rows = rows.astype(np.intp)
cols = cols.astype(np.intp)
if len(rows) > 1 and (rows[1:] < rows[:-1]).any():
order = np.argsort(rows, kind="stable")
rows = rows[order]
cols = cols[order]
return rows, cols


def _bridge_ids(n, rows, cols):
"""The bridges as `(parents, children)` of a spanning forest, and each node's tree label.

The graph has `n` nodes and the edges `rows[i]`-`cols[i]` both ways, no self-loop, with
each row's entries together, as `_entries_by_row` gives them.
"""
upper = rows < cols
us = rows[upper]
vs = cols[upper]
in_forest, label = _spanning_forest(n, us, vs)
src, dst, after, twin, roots = _euler_tours(n, us[in_forest], vs[in_forest], label)
down = after > after[twin]
parent = np.full(n, -1)
parent[dst[down]] = src[down]
size = np.zeros(n, np.intp)
size[dst[down]] = (after[down] - after[twin[down]] + 1) // 2
# Preorder numbers: trees of two or more nodes in a row, in the order of their roots, and
# a node's number is its tree's first plus the arcs down in the tour up to its own.
tree_size = np.bincount(label, minlength=n)[roots]
arcs_through = np.cumsum(2 * (tree_size - 1))
tree_of = np.empty(n, np.intp)
tree_of[roots] = np.arange(len(roots))
arc_tree = tree_of[label[src]]
tour_place = arcs_through[arc_tree] - 1 - after
down_seen = np.zeros(len(src), np.intp)
down_seen[tour_place[down]] = 1
down_seen = np.cumsum(down_seen)
pre = np.full(n, -1)
pre[roots] = (arcs_through - 2 * (tree_size - 1)) // 2 + np.arange(len(roots))
pre[dst[down]] = down_seen[tour_place[down]] + arc_tree[down]
# The least and greatest numbers each node reaches by an edge other than its tree edge up.
keep = cols != parent[rows]
rows = rows[keep]
reach = pre[cols[keep]]
# Indexed by preorder number, which runs over the nodes of trees of two or more nodes.
low = np.arange(np.count_nonzero(pre >= 0))
high = low.copy()
if len(rows) > 0:
firsts = np.flatnonzero(np.r_[True, rows[1:] != rows[:-1]])
at = pre[rows[firsts]]
low[at] = np.minimum(low[at], np.minimum.reduceat(reach, firsts))
high[at] = np.maximum(high[at], np.maximum.reduceat(reach, firsts))
children = dst[down]
first = pre[children]
span = size[children]
least, greatest = _range_min_max(low, high, first, span)
is_bridge = (least >= first) & (greatest < first + span)
return parent[children[is_bridge]], children[is_bridge], label


def _range_min_max(low, high, first, span):
"""`low[first[i] : first[i] + span[i]].min()` and `high`'s max likewise, for each `i`.

A sparse table built a level at a time: at level `j`, `low[i]` is the least of the `2**j`
values from `i`, and each run of `2**j` to `2**(j + 1) - 1` values is two such windows.
"""
least = np.empty(len(first), low.dtype)
greatest = np.empty(len(first), high.dtype)
if len(first) == 0:
return least, greatest
level = np.frexp(span)[1] - 1 # floor(log2(span)), exact for spans below 2**53
order = np.argsort(level, kind="stable")
bounds = np.r_[0, np.cumsum(np.bincount(level))]
for j in range(len(bounds) - 1):
which = order[bounds[j] : bounds[j + 1]]
if len(which) > 0:
left = first[which]
right = left + span[which] - (1 << j)
least[which] = np.minimum(low[left], low[right])
greatest[which] = np.maximum(high[left], high[right])
if j + 2 < len(bounds):
step = 1 << j
low = np.minimum(low[:-step], low[step:])
high = np.maximum(high[:-step], high[step:])
return least, greatest


def _component_ids(A, index, steps):
"""The ids of node `index`'s component in order, or None if it reaches over `steps` levels.

A breadth-first walk takes a step per level, so it ends soon on a component of few levels,
as a small one has, and is cut short on a deep one.
"""
seen = Vector(bool, A.nrows)
front = Vector(bool, A.nrows)
seen[index] = True
front[index] = True
for _ in range(steps + 1): # the last step finds the front empty
front(~seen.S, replace) << any_pair[bool](front @ A)
if front.nvals == 0:
return seen.to_coo(values=False)[0].astype(np.intp)
seen(front.S) << True
return None


def bridge_ids(G, root=None):
"""The bridges as arrays `(us, vs)` of node ids, sorted by `us` and then `vs` in node order.

`u` comes before `v` in `G`'s node order, which is id order in a graph converted from
NetworkX but not in every graph an operator builds. With `root`, those of `root`'s
component only: a walk from `root` finds the component, and if it has under half the nodes
only its edges are searched. A walk cut short after about 2 log2(n) levels, or a component
of half the nodes or more, searches the whole graph and keeps the component's bridges.
Self-loops are never bridges. Not named `bridges`, which would hide this module behind the
function in `algorithms`.
"""
n = len(G)
A = G.get_property("offdiag")
ids = None
if root is not None:
index = G._key_to_id[root]
ids = _component_ids(A, index, 2 * n.bit_length())
if ids is not None and 2 * len(ids) < n:
parents, children, _ = _bridge_ids(len(ids), *_entries_by_row(A[ids, ids].new()))
parents = ids[parents]
children = ids[children]
else:
parents, children, label = _bridge_ids(n, *_entries_by_row(A))
if root is not None:
keep = label[children] == label[index]
parents = parents[keep]
children = children[keep]
_, places = G._cacheit("keys_by_id", _keys_by_id, G)
at_parent = parents if places is None else places[parents]
at_child = children if places is None else places[children]
swap = at_parent > at_child
us = np.where(swap, children, parents)
vs = np.where(swap, parents, children)
order = np.lexsort((np.maximum(at_parent, at_child), np.minimum(at_parent, at_child)))
return us[order], vs[order]


def has_bridges(G, root=None):
return len(bridge_ids(G, root)[0]) > 0
5 changes: 5 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,11 @@ class Dispatcher:
edge_boundary = mod.edge_boundary
node_boundary = mod.node_boundary

mod = nxapi.bridges
# =================
bridges = nxapi.bridges
has_bridges = nxapi.has_bridges

mod = nxapi.centrality
# ====================
betweenness_centrality = mod.betweenness.betweenness_centrality
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/nxapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from .boundary import *
from .bridges import *
from .centrality import *
from .cluster import *
from .community import *
Expand Down
Loading
Loading