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 @@ -265,6 +265,8 @@ graphblas_algorithms.nxapi
├── regular
│ ├── is_k_regular
│ └── is_regular
├── richclub
│ └── rich_club_coefficient
├── shortest_paths
│ ├── dense
│ │ ├── floyd_warshall
Expand Down
2 changes: 2 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,7 @@ def get_info():
"reciprocity",
"resource_allocation_index",
"reverse",
"rich_club_coefficient",
"s_metric",
"schultz_index",
"score_sequence",
Expand Down Expand Up @@ -227,6 +228,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.",
"rich_club_coefficient": "Only `normalized=False` without a `seed` is answered here. The default,\n`normalized=True`, normalizes by graphs rewired with random double-edge swaps, and is\nleft to NetworkX. So is a `seed`: it changes nothing without normalization, but\nNetworkX 3.7 and later check it, and raise ValueError for one that cannot seed a\ngenerator.",
"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
8 changes: 8 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
("adjacency_matrix", "format"),
("closeness_centrality", "sp"),
("hits", "method"),
("rich_club_coefficient", "n_samples"),
}

# Dispatched names newer than the oldest supported NetworkX, with the release that added each.
Expand Down Expand Up @@ -173,6 +174,13 @@
"negative_edge_cycle": _PATH_OVERFLOW,
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"rich_club_coefficient": (
"Only `normalized=False` without a `seed` is answered here. The default,\n"
"`normalized=True`, normalizes by graphs rewired with random double-edge swaps, and is\n"
"left to NetworkX. So is a `seed`: it changes nothing without normalization, but\n"
"NetworkX 3.7 and later check it, and raise ValueError for one that cannot seed a\n"
"generator."
),
"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
Expand Up @@ -18,6 +18,7 @@
from .operators import *
from .reciprocity import *
from .regular import *
from .richclub import *
from .shortest_paths import *
from .simple_paths import *
from .smetric import *
Expand Down
29 changes: 29 additions & 0 deletions graphblas_algorithms/algorithms/richclub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import numpy as np
from graphblas import agg

__all__ = ["rich_club_coefficient"]


def rich_club_coefficient(G):
"""`{k: 2 * E_k / (N_k * (N_k - 1))}` for k = 0, 1, ... while `N_k` is at least 2.

`N_k` is the number of nodes of degree above k, and `E_k` the number of edges among them:
an edge counts while k is below the lower degree of its two ends. So a histogram of the
degrees and one of each edge's lower end degree give every `N_k` and `E_k` by suffix sums.
`G` is undirected without self-loops; its values are not read. This is NetworkX's
coefficient before its random normalization.
"""
A = G._A
if A.nvals == 0:
return {}
degrees = A.reduce_rowwise(agg.count).new().to_dense(fill_value=0).astype(np.int64)
# `above[k]` is N_k; it does not increase, so the k with N_k >= 2 come first
above = len(G) - np.cumsum(np.bincount(degrees))
K = int(np.count_nonzero(above >= 2))
rows, columns, _ = G.get_property("U-").to_coo(values=False)
lower = np.minimum(degrees[rows], degrees[columns])
among = len(lower) - np.cumsum(np.bincount(lower, minlength=K))[:K]
above = above[:K]
# exact integers up to 2**53, so each value is the correctly rounded quotient, as NetworkX's
rc = 2 * among / (above * (above - 1))
return dict(zip(range(K), rc.tolist(), strict=True))
4 changes: 4 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,10 @@ class Dispatcher:
is_k_regular = mod.is_k_regular
is_regular = mod.is_regular

mod = nxapi.richclub
# ==================
rich_club_coefficient = mod.rich_club_coefficient

mod = nxapi.shortest_paths
# ========================
floyd_warshall = mod.dense.floyd_warshall
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/nxapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from .operators import *
from .reciprocity import *
from .regular import *
from .richclub import *
from .shortest_paths import *
from .simple_paths import *
from .smetric import *
Expand Down
36 changes: 36 additions & 0 deletions graphblas_algorithms/nxapi/richclub.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
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

__all__ = ["rich_club_coefficient"]


def _unnormalized_without_seed(bound):
# NetworkX normalizes by graphs it rewires with random double-edge swaps.
if bound["normalized"]:
return (
"rich_club_coefficient with normalized=True is not implemented here; networkx serves it"
)
# A seed changes nothing without normalization, but NetworkX 3.7 and later check it all
# the same, raising ValueError for one that cannot seed a generator, and 3.6 does not:
# each NetworkX checks its own.
if bound.get("seed") is not None:
return "rich_club_coefficient with a seed is left to networkx, which checks it"
return None


@can_run(_unnormalized_without_seed)
@not_implemented_for("directed")
def rich_club_coefficient(G, normalized=True, Q=100, seed=None, *, n_samples=1):
# `Q` and NetworkX 3.7's `n_samples` steer only the normalization.
if (reason := _unnormalized_without_seed({"normalized": normalized, "seed": seed})) is not None:
raise NotImplementedError(reason)
G = to_undirected_graph(G)
if G.get_property("has_self_edges"):
# NetworkX's own exception, a plain Exception
raise Exception( # noqa: TRY002
"rich_club_coefficient is not implemented for graphs with self loops."
)
return algorithms.rich_club_coefficient(G)
Loading
Loading