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: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@ graphblas_algorithms.nxapi
│ ├── overlapping_modularity
│ └── partition_quality
├── components
│ ├── biconnected
│ │ ├── articulation_points
│ │ ├── biconnected_component_edges
│ │ ├── biconnected_components
│ │ └── is_biconnected
│ ├── connected
│ │ ├── connected_components
│ │ ├── is_connected
Expand Down
8 changes: 8 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def get_info():
"all_pairs_bellman_ford_path_length",
"all_pairs_shortest_path_length",
"ancestors",
"articulation_points",
"average_clustering",
"average_shortest_path_length",
"bellman_ford_path",
Expand All @@ -44,6 +45,8 @@ def get_info():
"bfs_edges",
"bfs_layers",
"bfs_successors",
"biconnected_component_edges",
"biconnected_components",
"boundary_expansion",
"bridges",
"center",
Expand Down Expand Up @@ -96,6 +99,7 @@ def get_info():
"intersection",
"intra_community_edges",
"is_arborescence",
"is_biconnected",
"is_branching",
"is_connected",
"is_cover",
Expand Down Expand Up @@ -193,13 +197,16 @@ def get_info():
_additional_docs = {
# BEGIN: additional_docs
"all_pairs_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.",
"articulation_points": "Each cut node once, in node order, where NetworkX's follow its search.\nA NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.",
"average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".',
"bellman_ford_path": "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.",
"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 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.",
"biconnected_component_edges": "Each block's edges come in an order and an orientation of their own, and a self-loop\nin one block of its node, where NetworkX lists it in the block its search meets it by,\nor not at all at a node its search starts from, so on the automatic path a NetworkX\ngraph with a self-loop is left to NetworkX.\nA NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.",
"biconnected_components": "The blocks come in an order of their own.\nA NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.",
"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".',
Expand All @@ -221,6 +228,7 @@ def get_info():
"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.",
"is_biconnected": "A NetworkX graph that would have to be converted is left to NetworkX: with the conversion\ncounted the wins were small, and no floor of nodes and edges per node kept out the losses\non more than one kind of graph. One NetworkX has converted already is served from 10000\nnodes. A backend graph is always served.",
"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.",
"k_corona": "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.",
"k_crust": "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
17 changes: 17 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,12 @@
+ _PATH_OVERFLOW
)

_BLOCKS_AUTO = (
"A NetworkX graph that would have to be converted is left to NetworkX: with the conversion\n"
"counted the wins were small, and no floor of nodes and edges per node kept out the losses\n"
"on more than one kind of graph. One NetworkX has converted already is served from 10000\n"
"nodes. A backend graph is always served."
)
_CORE_SUBGRAPH = (
"A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX."
)
Expand All @@ -108,6 +114,9 @@
)
_ADDITIONAL_DOCS = {
"all_pairs_bellman_ford_path_length": _PATH_OVERFLOW,
"articulation_points": (
"Each cut node once, in node order, where NetworkX's follow its search.\n" + _BLOCKS_AUTO
),
"average_shortest_path_length": (
'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n'
'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n'
Expand All @@ -129,6 +138,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."
),
"biconnected_component_edges": (
"Each block's edges come in an order and an orientation of their own, and a self-loop\n"
"in one block of its node, where NetworkX lists it in the block its search meets it by,\n"
"or not at all at a node its search starts from, so on the automatic path a NetworkX\n"
"graph with a self-loop is left to NetworkX.\n" + _BLOCKS_AUTO
),
"biconnected_components": "The blocks come in an order of their own.\n" + _BLOCKS_AUTO,
"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"
Expand Down Expand Up @@ -183,6 +199,7 @@
'iteration does not converge. `method="svd"` is left to NetworkX.'
),
"hyper_wiener_index": _LENGTH_SUM_OVERFLOW,
"is_biconnected": _BLOCKS_AUTO,
"k_core": _CORE_SUBGRAPH,
"k_corona": _CORE_SUBGRAPH,
"k_crust": _CORE_SUBGRAPH,
Expand Down
33 changes: 28 additions & 5 deletions graphblas_algorithms/algorithms/bridges.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
search takes a step per level, and a path graph has as many levels as nodes.
"""

from collections import namedtuple

import numpy as np
from graphblas import Vector, replace
from graphblas.semiring import any_pair
Expand Down Expand Up @@ -109,11 +111,19 @@ def _entries_by_row(A):
return rows, cols


def _bridge_ids(n, rows, cols):
"""The bridges as `(parents, children)` of a spanning forest, and each node's tree label.
_Forest = namedtuple("_Forest", "label parent pre size children least greatest off_u off_v")


def _forest_numbers(n, rows, cols):
"""A spanning forest in preorder, and what each subtree reaches.

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.
each row's entries together, as `_entries_by_row` gives them. By node id: `label`, the
node's tree; `parent`, -1 at a root; `pre`, the preorder number, -1 in a tree of one node;
and `size`, the number of nodes in the subtree. `children` are the nodes below the forest's
edges, and `least` and `greatest`, by child, the least and greatest numbers that the
child's subtree reaches by an edge other than the child's edge up. `off_u` and `off_v` are
the edges off the forest, with `off_u < off_v`.
"""
upper = rows < cols
us = rows[upper]
Expand All @@ -128,6 +138,7 @@ def _bridge_ids(n, rows, cols):
# 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]
size[roots] = tree_size
arcs_through = np.cumsum(2 * (tree_size - 1))
tree_of = np.empty(n, np.intp)
tree_of[roots] = np.arange(len(roots))
Expand Down Expand Up @@ -155,8 +166,20 @@ def _bridge_ids(n, rows, cols):
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
return _Forest(
label, parent, pre, size, children, least, greatest, us[~in_forest], vs[~in_forest]
)


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

The graph is as `_forest_numbers` takes it.
"""
f = _forest_numbers(n, rows, cols)
first = f.pre[f.children]
is_bridge = (f.least >= first) & (f.greatest < first + f.size[f.children])
return f.parent[f.children[is_bridge]], f.children[is_bridge], f.label


def _range_min_max(low, high, first, span):
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/components/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
from .biconnected import *
from .connected import *
from .weakly_connected import *
133 changes: 133 additions & 0 deletions graphblas_algorithms/algorithms/components/biconnected.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
"""Blocks (biconnected components) and cut nodes by Tarjan and Vishkin's method.

With a spanning forest numbered in preorder, as `bridges` numbers it, the blocks are the
connected components of a graph on the forest's edges, each named by its lower end, that joins
1. the edges above `a` and `b`, for each edge `a`-`b` off the forest whose ends are not one the
other's ancestor; and
2. the edges above `v` and above its child `w`, when `w`'s subtree reaches a node outside `v`'s
by an edge other than its own forest edges (`v` not a tree's root).
An edge off the forest lies in the block of the forest edge above its end later in preorder, and
a node is a cut node iff its forest edges lie in two blocks or more. Every step is a numpy pass,
and how many there are grows with log n, as for `bridges`.
"""

import numpy as np
from graphblas import Matrix

__all__ = ["articulation_ids", "block_edge_ids", "block_node_ids", "is_biconnected"]


def _forest(G):
# `bridges` imports this package, so its forest is imported when first needed.
from ..bridges import _entries_by_row, _forest_numbers

return _forest_numbers(len(G), *_entries_by_row(G.get_property("offdiag")))


def _blocks(G, f=None):
"""`(f, block, later)`: the forest's numbers, and blocks named by node.

`block[w]` is the block of the forest edge above `w`, and an edge off the forest lies in the
block of the forest edge above its end `later`.
"""
from ..bridges import _spanning_forest

if f is None:
f = _forest(G)
pre, size, parent, children = f.pre, f.size, f.parent, f.children
v = parent[children]
inner = parent[v] >= 0
w2 = children[inner]
v2 = v[inner]
out = (f.least[inner] < pre[v2]) | (f.greatest[inner] >= pre[v2] + size[v2])
a, b = f.off_u, f.off_v
a_later = pre[a] > pre[b]
later = np.where(a_later, a, b)
earlier = np.where(a_later, b, a)
unrelated = pre[earlier] + size[earlier] <= pre[later]
_, block = _spanning_forest(
len(parent),
np.concatenate([w2[out], earlier[unrelated]]),
np.concatenate([v2[out], later[unrelated]]),
)
return f, block, later


def articulation_ids(G):
"""The cut nodes' ids, in id order."""
f, block, _ = _blocks(G)
children = f.children
p = f.parent[children]
nonroot = f.parent[p] >= 0
cut = np.zeros(len(f.parent), bool)
cut[p[nonroot & (block[children] != block[p])]] = True
# A root is a cut node when its children's edges lie in two blocks or more: when one of
# them is not in the block of the child written last.
roots = p[~nonroot]
child_blocks = block[children[~nonroot]]
some = np.empty(len(cut), block.dtype)
some[roots] = child_blocks
cut[roots[child_blocks != some[roots]]] = True
return np.flatnonzero(cut)


def _grouped(rows, cols, nrows, ncols):
"""`cols` grouped by `rows`, each group once and in order, and where each group starts.

A pair given twice is kept once. GraphBLAS groups them as it builds a matrix, far faster
than numpy sorts them (0.39 s by `np.unique` against 0.02 s on a random tree of 1e6 nodes).
"""
M = Matrix.from_coo(rows, cols, True, nrows=nrows, ncols=ncols)
indptr, cols, _ = M.to_csr()
indptr = indptr.astype(np.intp)
starts = indptr[:-1][indptr[1:] > indptr[:-1]]
return cols.astype(np.intp), np.r_[starts, indptr[-1]]


def block_node_ids(G):
"""`(nodes, starts)`: block `i` is `nodes[starts[i]:starts[i + 1]]`, each id once."""
f, block, _ = _blocks(G)
children = f.children
n = len(f.parent)
b = block[children]
# A block's nodes are the ends of its forest edges: their lower ends, and the top one's parent.
return _grouped(np.r_[b, b], np.r_[children, f.parent[children]], n, n)


def block_edge_ids(G):
"""`(us, vs, starts)`: block `i`'s edges are the pairs `us[s:e]`, `vs[s:e]` of its run `s:e`.

The forest's edges, those off it, and each self-loop once, in a block of its node: the block
of its forest edge up, or at a root, of one of its forest edges down. A self-loop at a node
with no other edge is in no block.
"""
f, block, later = _blocks(G)
children = f.children
parent = f.parent
loops = G.get_property("diag").to_coo(values=False)[0].astype(np.intp)
root_block = np.full(len(parent), -1)
root_block[parent[children]] = block[children]
loop_block = np.where(parent[loops] >= 0, block[loops], root_block[loops])
kept = loop_block >= 0
loops = loops[kept]
us = np.concatenate([parent[children], f.off_u, loops])
vs = np.concatenate([children, f.off_v, loops])
b = np.concatenate([block[children], block[later], loop_block[kept]])
edges, starts = _grouped(b, np.arange(len(b)), len(parent), len(b))
return us[edges], vs[edges], starts


def is_biconnected(G):
"""Whether `G` has two nodes or more, all in one block, as NetworkX defines it."""
n = len(G)
if n < 2:
return False
degrees = G.get_property("degrees-")
# A node of no edge, or among three nodes or more of one edge, leaves it in two blocks or none.
if degrees.nvals < n or (n > 2 and degrees.reduce("min").get() < 2):
return False
f = _forest(G)
if len(f.children) < n - 1: # not connected
return False
_, block, _ = _blocks(G, f)
return bool((block[f.children] == block[f.children[0]]).all())
4 changes: 4 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,10 @@ class Dispatcher:

mod = nxapi.components
# ====================
articulation_points = mod.biconnected.articulation_points
biconnected_component_edges = mod.biconnected.biconnected_component_edges
biconnected_components = mod.biconnected.biconnected_components
is_biconnected = mod.biconnected.is_biconnected
connected_components = mod.connected.connected_components
is_connected = mod.connected.is_connected
node_connected_component = mod.connected.node_connected_component
Expand Down
Loading
Loading