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
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ dispatch pattern shown above.

```
graphblas_algorithms.nxapi
├── bipartite
│ └── cluster
│ ├── butterflies
│ └── robins_alexander_clustering
├── boundary
│ ├── edge_boundary
│ └── node_boundary
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",
"butterflies",
"center",
"closeness_centrality",
"clustering",
Expand Down Expand Up @@ -144,6 +145,7 @@ def get_info():
"reciprocity",
"resource_allocation_index",
"reverse",
"robins_alexander_clustering",
"s_metric",
"schultz_index",
"score_sequence",
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.",
"butterflies": "A graph with self-loops is left to NetworkX.\nRaises OverflowError rather than count four-cycles and paths of three edges in 64-bit\nintegers where a bound on them, half the sum of the squares of each node's walks of two\nsteps, reaches 2**62.",
"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 Down Expand Up @@ -227,6 +230,7 @@ def get_info():
"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.',
"radius": '`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.',
"reverse": "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.",
"robins_alexander_clustering": "A directed graph or a graph with self-loops is left to NetworkX.\nRaises OverflowError rather than count four-cycles and paths of three edges in 64-bit\nintegers where a bound on them, half the sum of the squares of each node's walks of two\nsteps, reaches 2**62.",
"schultz_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.',
"single_source_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.",
"union": "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.",
Expand Down
10 changes: 10 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
# The generated files list them on every version, so they do not depend on which NetworkX ran
# the generators; an older NetworkX never asks this backend for a name it does not have.
_ADDED_IN = {
"butterflies": "3.7",
"is_cover": "3.7",
"overlapping_modularity": "3.7",
}
Expand Down Expand Up @@ -69,6 +70,11 @@
"Raises OverflowError rather than add integer weights where the number of nodes times the\n"
"heaviest absolute weight reaches 2**62, as a length could then pass 2**63."
)
_COUNT_OVERFLOW = (
"Raises OverflowError rather than count four-cycles and paths of three edges in 64-bit\n"
"integers where a bound on them, half the sum of the squares of each node's walks of two\n"
"steps, reaches 2**62."
)
_SUM_OVERFLOW = (
"Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\n"
"or more"
Expand Down Expand Up @@ -122,6 +128,7 @@
"The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n"
"`sort_neighbors` is left to NetworkX."
),
"butterflies": "A graph with self-loops is left to NetworkX.\n" + _COUNT_OVERFLOW,
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
"common_neighbor_centrality": (
Expand Down Expand Up @@ -173,6 +180,9 @@
"negative_edge_cycle": _PATH_OVERFLOW,
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"robins_alexander_clustering": (
"A directed graph or a graph with self-loops is left to NetworkX.\n" + _COUNT_OVERFLOW
),
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"single_source_bellman_ford_path_length": _PATH_OVERFLOW,
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
from . import exceptions
from .bipartite import *
from .boundary import *
from .centrality import *
from .cluster import *
Expand Down
6 changes: 6 additions & 0 deletions graphblas_algorithms/algorithms/bipartite/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from . import cluster
from .cluster import *

# Only the functions: a bare star import would also hand `cluster`, this package's module, to
# `algorithms`, in place of `algorithms.cluster`.
__all__ = cluster.__all__
147 changes: 147 additions & 0 deletions graphblas_algorithms/algorithms/bipartite/cluster.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
"""Four-cycles ("butterflies") and three-paths, for Robins and Alexander's clustering.

Neither needs the bipartition: NetworkX counts every four-cycle and every path of three edges
whose ends differ, so these do too, and a graph that is not bipartite gets NetworkX's numbers.
The graph must have no self-loops, which NetworkX's loops read as neighbors.
"""

import numpy as np
from graphblas import Matrix, Vector, monoid, select
from graphblas.dtypes import INT64
from graphblas.semiring import plus_pair, plus_second, plus_times

from ..cluster import total_triangles

__all__ = ["butterflies", "robins_alexander_clustering"]

# Counts are added in int64. A node's four-cycles number at most half the square of its walks
# of two steps (`_walks`), so while those halves sum to less than this, no count overflows.
_COUNT_LIMIT = 2**62

# The wedges that one block of rows may walk (`_wedge_blocks`), which bounds the entries of
# its products: a dense graph's would otherwise hold a row for every node at once.
_BLOCK_WEDGES = 2**23


def _degrees(G):
return G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64)


def _walks(G, degrees):
"""Each node's walks of two steps that end at another node.

That is the sum of its neighbors' degrees, less one each.
"""
less_one = Vector.from_dense(degrees - 1)
return plus_second[INT64](G._A @ less_one).new().to_dense(fill_value=0, dtype=np.int64)


def _check_counts(degrees, walks):
"""Raise OverflowError unless every count fits in int64, as NetworkX's Python ints do."""
cycles = float(np.dot(walks.astype(np.float64), walks)) / 2
paths = float(np.dot((degrees - 1).astype(np.float64), walks))
if cycles >= _COUNT_LIMIT or paths >= _COUNT_LIMIT:
raise OverflowError(
"the four-cycles or three-paths here could number 2**62 (a bound from each node's "
"walks of two steps), too near 2**63 for the 64-bit integers they are added in; "
"NetworkX counts with Python integers. Call with backend='networkx'."
)


def _ranked(G, degrees):
"""The adjacency with the nodes numbered by degree, lowest first.

Returns `(ids, B, L)`: `ids` holds the id of each new number, `B` is the adjacency so
numbered, and `L` its edges `u - v` with `v` below `u`.
"""
n = len(G)
ids = np.argsort(degrees, kind="stable")
rank = np.empty(n, np.int64)
rank[ids] = np.arange(n)
rows, cols, _ = G._A.to_coo(values=False)
B = Matrix.from_coo(rank[rows], rank[cols], True, nrows=n, ncols=n)
return ids, B, select.tril(B, -1).new()


def _wedge_blocks(B, L, ranked_degrees):
"""Yield `(start, Lb, W)` over blocks of rows from `start`, with `Lb` those rows of `L`.

`W[i, w]`, for `w` below `u = start + i`, counts the wedges `u - v - w` with `v` below `u`.
A four-cycle has one node `u` above its other three and one node `w` opposite `u`, and its
other two nodes are middles of such wedges, so the `k` wedges from `u` to `w` close C(k, 2)
cycles, each counted once. A hub is never the middle of a wedge from a node of lower degree,
so its neighbors are not walked once for each of them: NetworkX's ordering too. A block
walks about `_BLOCK_WEDGES` wedges, or one row, so a dense graph's products stay small.
"""
n = B.nrows
walked = plus_second[INT64](L @ Vector.from_dense(ranked_degrees)).new()
reach = np.cumsum(walked.to_dense(fill_value=0, dtype=np.int64))
start = 0
while start < n:
before = reach[start - 1] if start else 0
end = int(np.searchsorted(reach, before + _BLOCK_WEDGES, side="right"))
end = min(max(end, start + 1), n)
Lb = L[start:end, :].new()
W = select.tril(plus_pair[INT64](Lb @ B).new(), start - 1).new()
yield start, Lb, W
start = end


def _sums(reduction):
return reduction.new().to_dense(fill_value=0, dtype=np.int64)


def butterflies(G):
"""The four-cycles through each node, an int64 array by node id."""
n = len(G)
degrees = _degrees(G)
if G._A.nvals == 0:
return np.zeros(n, np.int64)
_check_counts(degrees, _walks(G, degrees))
ids, B, L = _ranked(G, degrees)
by_rank = np.zeros(n, np.int64)
for start, Lb, W in _wedge_blocks(B, L, degrees[ids]):
size = W.nrows
rows, cols, counts = W.to_coo()
pairs = Matrix.from_coo(
rows, cols, counts * (counts - 1) // 2, dtype=INT64, nrows=size, ncols=n
)
# A middle of one of the `k` wedges from `u` to `w` is in `k - 1` of their cycles, one
# with each other middle: `X[u, v]` adds those over the `w` that `v` reaches from `u`.
more = counts > 1
less_one = Matrix.from_coo(
rows[more], cols[more], counts[more] - 1, dtype=INT64, nrows=size, ncols=n
)
X = plus_times[INT64](less_one @ B).new(mask=Lb.S)
by_rank[start : start + size] += _sums(pairs.reduce_rowwise(monoid.plus))
by_rank += _sums(pairs.reduce_columnwise(monoid.plus))
by_rank += _sums(X.reduce_columnwise(monoid.plus))
result = np.empty(n, np.int64)
result[ids] = by_rank
return result


def robins_alexander_clustering(G):
"""Four times the four-cycles over the paths of three edges whose ends differ.

Divided as NetworkX divides, so its float to the bit; the integer 0 below four nodes or three
edges, or without such paths, as NetworkX returns it.
"""
if len(G) < 4 or G._A.nvals < 6: # each edge is held both ways
return 0
degrees = _degrees(G)
walks = _walks(G, degrees)
_check_counts(degrees, walks)
# Over each edge `u - w` as the middle, taken both ways as NetworkX takes it: a neighbor of
# `u` but `w` times a neighbor of `w` but `u`, less the pairs that are one node, which make
# a triangle; each triangle is met at its three edges, both ways.
paths = int(np.dot(degrees - 1, walks)) - 6 * int(total_triangles(G))
L_3 = paths / 2
if L_3 == 0:
return 0
ids, B, L = _ranked(G, degrees)
four_cycles = 0
for _, _, W in _wedge_blocks(B, L, degrees[ids]):
counts = W.to_coo(rows=False, columns=False)[2]
four_cycles += int((counts * (counts - 1) // 2).sum())
return 4 * four_cycles / L_3
5 changes: 5 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,11 @@ def _materialize_virtual_adjacency(graph):

class Dispatcher:
# Begin auto-generated code: dispatch
mod = nxapi.bipartite
# ===================
butterflies = mod.cluster.butterflies
robins_alexander_clustering = mod.cluster.robins_alexander_clustering

mod = nxapi.boundary
# ==================
edge_boundary = mod.edge_boundary
Expand Down
2 changes: 2 additions & 0 deletions graphblas_algorithms/nxapi/__init__.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from .bipartite import *
from .boundary import *
from .centrality import *
from .cluster import *
Expand Down Expand Up @@ -29,6 +30,7 @@
from .tournament import is_tournament
from .wiener import *

from . import bipartite
from . import centrality
from . import cluster
from . import community
Expand Down
4 changes: 4 additions & 0 deletions graphblas_algorithms/nxapi/bipartite/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
from .cluster import *

# NetworkX keeps these in `nx.bipartite`, out of its top level.
__all__ = []
42 changes: 42 additions & 0 deletions graphblas_algorithms/nxapi/bipartite/cluster.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.graph import to_undirected_graph
from graphblas_algorithms.utils import not_implemented_for

from .._utils import can_run, nbunch_keys

__all__ = ["butterflies", "robins_alexander_clustering"]


def _undirected(bound):
# NetworkX answers a directed graph from its successors in 3.6.1 and raises from
# `butterflies` in 3.7, after early returns of 0: its answer to give.
if bound["G"].is_directed():
return "robins_alexander_clustering of a directed graph is left to networkx"
return None


def _refuse_self_loops(G, name):
# NetworkX's loops read a self-loop as a neighbor, so its counts with one are its own.
# Raised after the conversion, NetworkX's dispatcher still hands the call to NetworkX.
if G.get_property("has_self_edges"):
raise NotImplementedError(f"{name} of a graph with self-loops is left to networkx")


@can_run(_undirected)
def robins_alexander_clustering(G):
if G.is_directed():
raise NotImplementedError(_undirected({"G": G}))
G = to_undirected_graph(G)
_refuse_self_loops(G, "robins_alexander_clustering")
return algorithms.robins_alexander_clustering(G) # OverflowError where counts could pass int64


@not_implemented_for("directed")
def butterflies(G, nodes=None):
G = to_undirected_graph(G)
_refuse_self_loops(G, "butterflies")
counts = algorithms.butterflies(G).tolist()
key_to_id = G._key_to_id
if nodes is None:
return {key: counts[i] for key, i in key_to_id.items()}
return {key: counts[key_to_id[key]] for key in nbunch_keys(G, nodes)}
Loading
Loading