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
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,8 @@ graphblas_algorithms.nxapi
├── boundary
│ ├── edge_boundary
│ └── node_boundary
├── bridges
│ └── local_bridges
├── centrality
│ ├── betweenness
│ │ ├── betweenness_centrality
Expand Down
2 changes: 2 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,7 @@ def get_info():
"k_truss",
"katz_centrality",
"laplacian_matrix",
"local_bridges",
"local_efficiency",
"lowest_common_ancestor",
"mixing_expansion",
Expand Down Expand Up @@ -222,6 +223,7 @@ def get_info():
"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.",
"k_shell": "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_truss": "Edge 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.",
"local_bridges": "Edges come by their first end and then by their second, both in node order. NetworkX\ngoes by each node's adjacency order, so the order can differ; the pairs, each with its\nend first in node order first, and the spans are NetworkX's. Spans over a `weight` are\nserved for Python ints or floats that are at least 0 and finite, ints while the number\nof nodes times the largest stays below 2**62; other weights are left to NetworkX. With\nints mixed with floats, a span is a float where NetworkX's can be an int (3.0 for 3).\nThe graph is read at the call, not as the generator is read.",
"local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.",
"negative_edge_cycle": "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.",
"periphery": '`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.',
Expand Down
9 changes: 9 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,15 @@
"k_corona": _CORE_SUBGRAPH,
"k_crust": _CORE_SUBGRAPH,
"k_shell": _CORE_SUBGRAPH,
"local_bridges": (
"Edges come by their first end and then by their second, both in node order. NetworkX\n"
"goes by each node's adjacency order, so the order can differ; the pairs, each with its\n"
"end first in node order first, and the spans are NetworkX's. Spans over a `weight` are\n"
"served for Python ints or floats that are at least 0 and finite, ints while the number\n"
"of nodes times the largest stays below 2**62; other weights are left to NetworkX. With\n"
"ints mixed with floats, a span is a float where NetworkX's can be an int (3.0 for 3).\n"
"The graph is read at the call, not as the generator is read."
),
"local_efficiency": (
"The cost is the breadth-first levels times the chunks of walks, so a node whose\n"
"neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\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
166 changes: 166 additions & 0 deletions graphblas_algorithms/algorithms/bridges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
import math

import numpy as np
from graphblas import Matrix, Vector, binary, monoid, replace, unary
from graphblas.semiring import any_first, any_pair, any_second, min_plus

__all__ = ["local_bridges"]

# The memory a batch of span rows may take, and the bytes a row may take per node of the graph
# at a batch's peak. Measured on 20000 nodes (a random tree, where a row searches a whole side,
# and random bipartite graphs, whose frontiers are wide): up to about 9 bytes for the
# breadth-first rows and 45 for the Bellman-Ford rows, with rows reaching half the nodes.
# A row can reach all of them, so these are those figures doubled or more.
_BATCH_BUDGET = 2**30
_HOP_BYTES = 32
_WEIGHTED_BYTES = 96


def _batch_rows(n, bytes_per_node):
"""How many span rows a batch holds on `n` nodes."""
return max(1, _BATCH_BUDGET // (bytes_per_node * n))


def local_bridge_ids(G):
"""The ids `(u, v)` of the edges whose ends share no neighbor, with `u < v`, sorted.

A self-loop makes a node its own neighbor, so no edge at a node with a self-loop is a
local bridge, nor is a self-loop itself, as where NetworkX intersects neighbor sets.
"""
U = G.get_property("U-")
if U.nvals == 0:
empty = np.empty(0, np.uint64)
return empty, empty
A = G._A
shared = any_pair[bool](A @ A).new(mask=U.S)
bridges = U.dup(mask=~shared.S)
rows, columns, _ = bridges.to_coo(values=False)
order = np.lexsort((columns, rows))
return rows[order], columns[order]


def _start(A, sources, targets):
"""Each source's neighbors but its target, a row per source; and the sources and targets.

Walking on from these rows, with each row's source taken as reached at 0, never crosses
the edge from the source to its target: the source is left only through these neighbors.
"""
b = len(sources)
rows = np.arange(b, dtype=np.uint64)
T = Matrix.from_coo(rows, targets, True, nrows=b, ncols=A.ncols)
S = Matrix.from_coo(rows, sources, True, nrows=b, ncols=A.ncols)
return A[sources, :].new(mask=~T.S), S, T


def _prefer_bitmap(M):
"""Hold `M` as a bitmap once more than 1% of it is filled, rather than sparse.

The rows filled so far grow as a search goes, a whole side of the graph on a tree. Held
sparse, each update made a new copy, and a batch's peak ran to hundreds of bytes an entry;
a bitmap, a byte or so a row and node, is updated in place. Below 1% a row's few entries
stay sparse, so a batch of short searches does not pay for a whole bitmap.
"""
M.ss.config["bitmap_switch"] = 0.01


def _hop_spans(G, sources, targets):
"""The fewest edges from each source to its target without the edge between them.

A breadth-first search a row per pair; a row stops at its target. `inf` where the target
is not reached.
"""
A = G._A
b = len(sources)
F, S, T = _start(A, sources, targets)
F = unary.one[bool](F).new()
seen = binary.lor(F | S).new()
_prefer_bitmap(F)
_prefer_bitmap(seen)
spans = np.full(b, -1, np.int64)
active = np.ones(b, bool)
depth = 1
while F.nvals > 0:
depth += 1
F(~seen.S, replace) << any_pair[bool](F @ A)
reached = F.dup(mask=T.S)
if reached.nvals > 0:
rows, _, _ = reached.to_coo(values=False)
spans[rows] = depth
active[rows] = False
keep = Vector.from_coo(np.flatnonzero(active), True, size=b)
F << any_second[bool](keep.diag() @ F)
seen(F.S) << True
return [span if span >= 0 else math.inf for span in spans.tolist()]


def _weighted_spans(G, sources, targets):
"""The least sum of weights from each source to its target without the edge between them.

Bellman-Ford a row per pair. A row walks on only from lengths that changed and that are
below its target's length so far, which no longer path can lower as weights are at least 0.
`inf` where the target is not reached.
"""
A = G._A
dtype = A.dtype
b = len(sources)
F, S, T = _start(A, sources, targets)
D = F.dup()
D(S.S) << 0
Mask = Matrix(bool, b, A.ncols)
for M in [F, D, Mask]:
_prefer_bitmap(M)
one = unary.one[bool]
while F.nvals > 0:
F << min_plus[dtype](F @ A)
Mask << one(F)
Mask(binary.second) << binary.lt(F & D)
F(Mask.V, replace) << F
D(F.S) << F
bound = D.dup(mask=T.S).reduce_rowwise(monoid.min).new()
if bound.nvals > 0 and F.nvals > 0:
Mask << one(F)
Mask(binary.second) << binary.lt(F & any_first[dtype](bound.diag() @ F))
F(Mask.V, replace) << F
lengths = D.dup(mask=T.S).reduce_rowwise(monoid.min).new()
ids, values = lengths.to_coo()
spans = [math.inf] * b
for i, value in zip(ids.tolist(), values.tolist(), strict=True):
spans[i] = value
return spans


def _unit_weights(G):
"""Whether every edge but a self-loop weighs the integer 1, so a span is a hop count."""
if G._A.dtype.np_type.kind not in "iu":
return False
least, greatest = G.get_properties("min_element- max_element-")
return least.get(0) == 1 and greatest.get(0) == 1


def local_bridges(G, *, with_span=True, weighted=False):
"""Yield `(u, v)`, or `(u, v, span)`, for each edge whose ends share no neighbor.

`u` is the end first in node order, as in NetworkX's `G.edges`; edges come by `u` and then
by `v`, both in node order. A span is the least length from `u` to `v` without their edge:
the fewest edges, or with `weighted` the least sum of `G`'s values, which must be at least
0 and, if integers, small enough that no length reaches 2**63. `inf` where there is none.
Spans are computed a batch of edges at a time, as they are read.
"""
id_to_key = G.id_to_key
rows, columns = local_bridge_ids(G)
if not with_span:
for u, v in zip(rows.tolist(), columns.tolist(), strict=True):
yield id_to_key[u], id_to_key[v]
return
if len(rows) == 0:
return
if weighted and not _unit_weights(G):
spans_of, size = _weighted_spans, _batch_rows(len(G), _WEIGHTED_BYTES)
else:
spans_of, size = _hop_spans, _batch_rows(len(G), _HOP_BYTES)
for start in range(0, len(rows), size):
sources = rows[start : start + size]
targets = columns[start : start + size]
spans = spans_of(G, sources, targets)
for u, v, span in zip(sources.tolist(), targets.tolist(), spans, strict=True):
yield id_to_key[u], id_to_key[v], span
4 changes: 4 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,10 @@ class Dispatcher:
edge_boundary = mod.edge_boundary
node_boundary = mod.node_boundary

mod = nxapi.bridges
# =================
local_bridges = mod.local_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
50 changes: 50 additions & 0 deletions graphblas_algorithms/nxapi/bridges.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import numpy as np
from graphblas import dtypes

from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.graph import to_undirected_graph
from graphblas_algorithms.utils import not_implemented_for

__all__ = ["local_bridges"]


def _unserved_weights(G):
"""Why the spans over `G`'s weights are left to NetworkX, or None.

NetworkX's Dijkstra raises or can stop early on a negative weight, and NaN compares false,
so weights are served when at least 0 and finite. Integers are added in 64 bits here, so
they are served while no length can reach 2**63. Other dtypes, such as NumPy's narrow
floats or bools, are added in other types by NetworkX, and are left to it as well.
"""
A = G._A
if A.dtype not in {dtypes.INT64, dtypes.FP64}:
return f"local_bridges spans over {A.dtype} weights are not implemented here"
least, greatest = G.get_properties("min_element+ max_element+")
if least.get(0) < 0:
return "local_bridges spans over negative weights are not implemented here"
if A.dtype == dtypes.FP64:
if not np.isfinite(A.to_coo(rows=False, columns=False)[2]).all():
return "local_bridges spans over NaN or infinite weights are not implemented here"
elif A.nrows * greatest.get(0) >= 2**62:
return "local_bridges spans over integer weights this large are not implemented here"
return None


@not_implemented_for("directed")
@not_implemented_for("multigraph")
def local_bridges(G, with_span=True, weight=None):
# Not a generator function: a decline must come at the call, where NetworkX's dispatcher
# can still hand the call to NetworkX. The returned generator reads spans as it goes.
# NetworkX computes spans for `with_span is True` only, so not for 1 or `np.True_`.
with_span = with_span is True
if callable(weight):
# The dispatcher declines a weight function for every name (`Dispatcher.can_run`);
# this is for a direct call.
raise NotImplementedError(
"local_bridges with a weight function is not implemented here; networkx serves it"
)
weighted = with_span and weight is not None
G = to_undirected_graph(G, weight=weight if weighted else None)
if weighted and (reason := _unserved_weights(G)) is not None:
raise NotImplementedError(f"{reason}; networkx serves it")
return algorithms.local_bridges(G, with_span=with_span, weighted=weighted)
Loading
Loading