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
10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,9 +125,13 @@ dispatch pattern shown above.
```
graphblas_algorithms.nxapi
├── bipartite
│ └── cluster
│ ├── butterflies
│ └── robins_alexander_clustering
│ ├── cluster
│ │ ├── average_clustering (bipartite_average_clustering)
│ │ ├── butterflies
│ │ ├── latapy_clustering
│ │ └── robins_alexander_clustering
│ └── redundancy
│ └── node_redundancy
├── boundary
│ ├── edge_boundary
│ └── node_boundary
Expand Down
6 changes: 6 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ def get_info():
"bfs_edges",
"bfs_layers",
"bfs_successors",
"bipartite_average_clustering",
"boundary_expansion",
"butterflies",
"center",
Expand Down Expand Up @@ -118,6 +119,7 @@ def get_info():
"k_truss",
"katz_centrality",
"laplacian_matrix",
"latapy_clustering",
"local_efficiency",
"lowest_common_ancestor",
"mixing_expansion",
Expand All @@ -128,6 +130,7 @@ def get_info():
"node_boundary",
"node_connected_component",
"node_expansion",
"node_redundancy",
"normalized_cut_size",
"normalized_laplacian_matrix",
"number_connected_components",
Expand Down Expand Up @@ -200,6 +203,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.",
"bipartite_average_clustering": "A directed graph is left to NetworkX. The average is NetworkX's sum over the nodes, of\nvalues within a relative 1e-12 of NetworkX's (see `latapy_clustering`).",
"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".',
Expand All @@ -225,8 +229,10 @@ 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.",
"latapy_clustering": "A directed graph is left to NetworkX. A node's terms are added in the order of the\nnodes' ids, not in NetworkX's set order, so a value can differ from NetworkX's in its\nlast bits.",
"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.",
"node_redundancy": "A directed graph, or a graph with self-loops, is left to NetworkX.",
"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.",
Expand Down
10 changes: 10 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@
"The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n"
"`sort_neighbors` is left to NetworkX."
),
"bipartite_average_clustering": (
"A directed graph is left to NetworkX. The average is NetworkX's sum over the nodes, of\n"
"values within a relative 1e-12 of NetworkX's (see `latapy_clustering`)."
),
"butterflies": "A graph with self-loops is left to NetworkX.\n" + _COUNT_OVERFLOW,
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
Expand Down Expand Up @@ -172,12 +176,18 @@
"k_corona": _CORE_SUBGRAPH,
"k_crust": _CORE_SUBGRAPH,
"k_shell": _CORE_SUBGRAPH,
"latapy_clustering": (
"A directed graph is left to NetworkX. A node's terms are added in the order of the\n"
"nodes' ids, not in NetworkX's set order, so a value can differ from NetworkX's in its\n"
"last bits."
),
"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"
"memory stays bounded."
),
"negative_edge_cycle": _PATH_OVERFLOW,
"node_redundancy": "A directed graph, or a graph with self-loops, is left to NetworkX.",
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"robins_alexander_clustering": (
Expand Down
11 changes: 7 additions & 4 deletions graphblas_algorithms/algorithms/bipartite/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from . import cluster
from . import basic, cluster, latapy, redundancy
from .basic import *
from .cluster import *
from .latapy import *
from .redundancy 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__
# Only the functions: a bare star import would also hand this package's modules to
# `algorithms`, among them `cluster` in place of `algorithms.cluster`.
__all__ = basic.__all__ + cluster.__all__ + latapy.__all__ + redundancy.__all__
51 changes: 51 additions & 0 deletions graphblas_algorithms/algorithms/bipartite/basic.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
"""Whether a graph is bipartite, and the blocks of rows the bipartite kernels walk."""

import numpy as np
from graphblas import Matrix, Vector
from graphblas.dtypes import INT64
from graphblas.semiring import plus_second

from ..components._labels import component_labels

__all__ = ["is_bipartite"]

# The paths of two steps that one block of rows may walk, which bounds the entries of its
# products: a dense graph's would otherwise hold a row for every node at once.
_BLOCK_WALKS = 2**22


def is_bipartite(G):
"""Whether `G` has no cycle of odd length, a self-loop being one, as NetworkX answers.

In the double cover each node `v` is two, `v` and `v'`, and each edge `u - v` joins `u` to
`v'` and `u'` to `v`. A walk there from `v` to `v'` is a walk of odd length from `v` back to
`v` in `G`, so `G` is bipartite exactly when no `v` shares a component with its `v'`.
"""
n = len(G)
rows, cols, _ = G._A.to_coo(values=False)
cover = Matrix.from_coo(
np.concatenate([rows, rows + n]),
np.concatenate([cols + n, cols]),
True,
nrows=2 * n,
ncols=2 * n,
)
labels = component_labels(cover)
return not np.any(labels[:n] == labels[n:])


def row_blocks(G, ids, degrees):
"""Split `ids` into runs, in order, that walk about `_BLOCK_WALKS` paths of two steps each.

A node's paths of two steps number its neighbors' degrees added up; a run holds one node
at least.
"""
walks = plus_second[INT64](G._A @ Vector.from_dense(degrees)).new()
reach = np.cumsum(walks.to_dense(fill_value=0, dtype=np.int64)[ids])
start = 0
while start < len(ids):
before = reach[start - 1] if start else 0
end = int(np.searchsorted(reach, before + _BLOCK_WALKS, side="right"))
end = min(max(end, start + 1), len(ids))
yield ids[start:end]
start = end
42 changes: 42 additions & 0 deletions graphblas_algorithms/algorithms/bipartite/latapy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Latapy's bipartite clustering: each node's overlaps with the nodes two steps away."""

import numpy as np
from graphblas.dtypes import INT64
from graphblas.semiring import plus_pair

from .basic import row_blocks

__all__ = ["latapy_clustering"]


def latapy_clustering(G, ids, mode):
"""The clustering of each node in `ids`, which holds no node twice, as a float64 array.

`G` must be bipartite, so the nodes two steps from `v` are the nodes other than `v` that
share a neighbor with it. Each such `u` adds the neighbors they share over the size of the
union of their neighbors ("dot"), the smaller of their degrees ("min") or the larger
("max"): one division each, as NetworkX's. The terms are added in the order of `u`'s id,
and their sum is divided by their number.
"""
A = G._A
degrees = G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64)
result = np.zeros(len(ids), np.float64)
done = 0
for block in row_blocks(G, ids, degrees):
size = len(block)
shared = plus_pair[INT64](A[block, :].new() @ A).new()
rows, cols, common = shared.to_coo()
others = cols != block[rows] # each node shares its whole neighborhood with itself
rows, cols, common = rows[others], cols[others], common[others]
mine, theirs = degrees[block[rows]], degrees[cols]
if mode == "dot":
sizes = mine + theirs - common
elif mode == "min":
sizes = np.minimum(mine, theirs)
else:
sizes = np.maximum(mine, theirs)
sums = np.bincount(rows, weights=common / sizes, minlength=size)
counts = np.bincount(rows, minlength=size)
np.divide(sums, counts, out=result[done : done + size], where=counts > 0)
done += size
return result
36 changes: 36 additions & 0 deletions graphblas_algorithms/algorithms/bipartite/redundancy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""Latapy's node redundancy: the share of a node's pairs of neighbors that meet elsewhere too."""

import numpy as np
from graphblas import Matrix, monoid
from graphblas.dtypes import INT64
from graphblas.semiring import plus_pair

from .basic import row_blocks

__all__ = ["node_redundancy"]


def node_redundancy(G, ids):
"""The redundancy of each node in `ids`, which holds no node twice, as a float64 array.

Each node in `ids` needs two neighbors at least, and `G` no self-loops. Two neighbors `u`
and `w` of `v` meet at a node other than `v` when they share two neighbors or more, so
`M[u, w]` marks the pairs of nodes that share two, and `P[u, v]` counts, for a neighbor
`u` of `v`, the other neighbors of `v` that `u` meets so. Its column sums count each pair
of `v`'s neighbors twice, and they are divided by `d (d - 1)`, as NetworkX divides.
"""
A = G._A
n = len(G)
degrees = G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64)
asked = A[:, ids].new()
neighbors = np.unique(asked.to_coo(values=False)[0])
twice = np.zeros(len(ids), np.int64)
for block in row_blocks(G, neighbors, degrees):
shared = plus_pair[INT64](A[block, :].new() @ A).new()
rows, cols, common = shared.to_coo()
meet = (common >= 2) & (cols != block[rows])
M = Matrix.from_coo(rows[meet], cols[meet], True, nrows=len(block), ncols=n)
P = plus_pair[INT64](M @ asked).new(mask=asked[block, :].new().S)
twice += P.reduce_columnwise(monoid.plus).new().to_dense(fill_value=0, dtype=np.int64)
pairs = degrees[ids] * (degrees[ids] - 1)
return twice / pairs
3 changes: 3 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,8 +235,11 @@ class Dispatcher:
# Begin auto-generated code: dispatch
mod = nxapi.bipartite
# ===================
bipartite_average_clustering = mod.cluster.average_clustering
butterflies = mod.cluster.butterflies
latapy_clustering = mod.cluster.latapy_clustering
robins_alexander_clustering = mod.cluster.robins_alexander_clustering
node_redundancy = mod.redundancy.node_redundancy

mod = nxapi.boundary
# ==================
Expand Down
4 changes: 3 additions & 1 deletion graphblas_algorithms/nxapi/bipartite/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
from .cluster import *
from .redundancy import *

# NetworkX keeps these in `nx.bipartite`, out of its top level.
# NetworkX keeps these in `nx.bipartite`, out of its top level, where `clustering` and
# `average_clustering` name other functions.
__all__ = []
69 changes: 68 additions & 1 deletion graphblas_algorithms/nxapi/bipartite/cluster.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,21 @@
import numpy as np
from networkx import NetworkXError

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"]
# Where two names are one function, the later is the one listed: `latapy_clustering`, after
# its alias `clustering`, as in NetworkX.
__all__ = [
"average_clustering",
"butterflies",
"clustering",
"latapy_clustering",
"robins_alexander_clustering",
]


def _undirected(bound):
Expand Down Expand Up @@ -40,3 +51,59 @@ def butterflies(G, nodes=None):
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)}


# NetworkX's `modes`, looked up the same way, so a bad mode raises what NetworkX raises.
_MODES = {"dot": "dot", "min": "min", "max": "max"}


def _left_if_directed(bound):
# NetworkX reads a directed graph's successors as its neighbors: its answer to give.
if bound["G"].is_directed():
return "a directed graph is left to networkx"
return None


def _refuse_directed(G):
if G.is_directed():
raise NotImplementedError(_left_if_directed({"G": G}))


def _clustering(G, nodes, mode):
"""NetworkX's checks in NetworkX's order, then a dict of the nodes in `nodes`'s order."""
if not G._cacheit("is_bipartite", algorithms.is_bipartite, G):
raise NetworkXError("Graph is not bipartite")
try:
mode = _MODES[mode]
except KeyError as err:
raise NetworkXError("Mode for bipartite clustering must be: dot, min or max") from err
if nodes is None:
nodes = G
key_to_id = G._key_to_id
# Each lookup as NetworkX's `G[v]`: KeyError for a node not in the graph, TypeError for
# one that cannot be.
ids = {}
for v in nodes:
ids.setdefault(v, key_to_id[v])
values = algorithms.latapy_clustering(G, np.fromiter(ids.values(), np.int64), mode)
return dict(zip(ids, values.tolist(), strict=True))


@can_run(_left_if_directed)
def latapy_clustering(G, nodes=None, mode="dot"):
_refuse_directed(G)
G = to_undirected_graph(G)
return _clustering(G, nodes, mode)


clustering = latapy_clustering


@can_run(_left_if_directed)
def average_clustering(G, nodes=None, mode="dot"):
_refuse_directed(G)
G = to_undirected_graph(G)
if nodes is None:
nodes = G
ccs = _clustering(G, nodes, mode)
return sum(ccs[v] for v in nodes) / len(nodes)
33 changes: 33 additions & 0 deletions graphblas_algorithms/nxapi/bipartite/redundancy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import numpy as np
from networkx import NetworkXError

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

from .._utils import can_run
from .cluster import _left_if_directed, _refuse_directed, _refuse_self_loops

__all__ = ["node_redundancy"]


@can_run(_left_if_directed)
def node_redundancy(G, nodes=None):
_refuse_directed(G)
G = to_undirected_graph(G)
# NetworkX counts a self-loop as a neighbor, and a node as a neighbor two of its neighbors
# meet at. Raised before `nodes` is read, NetworkX's dispatcher hands it the call intact.
_refuse_self_loops(G, "node_redundancy")
if nodes is None:
nodes = G
key_to_id = G._key_to_id
degrees = G.get_property("degrees-").to_dense(fill_value=0, dtype=np.int64)
# As NetworkX: `nodes` is read once for the check and again for the answer.
if any(degrees[key_to_id[v]] < 2 for v in nodes):
raise NetworkXError(
"Cannot compute redundancy coefficient for a node that has fewer than two neighbors."
)
ids = {}
for v in nodes:
ids.setdefault(v, key_to_id[v])
values = algorithms.node_redundancy(G, np.fromiter(ids.values(), np.int64))
return dict(zip(ids, values.tolist(), strict=True))
Loading
Loading