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
7 changes: 5 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -149,8 +149,11 @@ graphblas_algorithms.nxapi
│ │ └── group_out_degree_centrality
│ ├── harmonic
│ │ └── harmonic_centrality
│ └── katz
│ └── katz_centrality
│ ├── katz
│ │ └── katz_centrality
│ └── reaching
│ ├── global_reaching_centrality
│ └── local_reaching_centrality
├── cluster
│ ├── average_clustering
│ ├── clustering
Expand Down
4 changes: 4 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ def get_info():
"full_join",
"generalized_degree",
"global_efficiency",
"global_reaching_centrality",
"google_matrix",
"group_closeness_centrality",
"group_degree_centrality",
Expand Down Expand Up @@ -118,6 +119,7 @@ def get_info():
"katz_centrality",
"laplacian_matrix",
"local_efficiency",
"local_reaching_centrality",
"lowest_common_ancestor",
"mixing_expansion",
"modularity",
Expand Down Expand Up @@ -211,6 +213,7 @@ def get_info():
"ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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.',
"floyd_warshall": "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.",
"floyd_warshall_predecessor_and_distance": "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.",
"global_reaching_centrality": "Unweighted: a call with `weight` is left to NetworkX, which averages the weights along\nthe path its Dijkstra picks among paths of equal length.",
"group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.",
"gutman_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.',
"harmonic_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 @@ -223,6 +226,7 @@ def get_info():
"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_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.",
"local_reaching_centrality": "Unweighted: a call with `weight` is left to NetworkX, which averages the weights along\nthe path its Dijkstra picks among paths of equal length. So are given `paths`.",
"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.',
"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.',
Expand Down
9 changes: 9 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,13 @@

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
# NetworkX averages the weights along the path its Dijkstra picks, and paths of equal length
# can average differently.
_REACHING_WEIGHTED = (
"Unweighted: a call with `weight` is left to NetworkX, which averages the weights along\n"
"the path its Dijkstra picks among paths of equal length."
)

_ADDITIONAL_DOCS = {
"all_pairs_bellman_ford_path_length": _PATH_OVERFLOW,
"average_shortest_path_length": (
Expand Down Expand Up @@ -151,6 +158,7 @@
),
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
"global_reaching_centrality": _REACHING_WEIGHTED,
"group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.",
"gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
Expand All @@ -170,6 +178,7 @@
"neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n"
"memory stays bounded."
),
"local_reaching_centrality": _REACHING_WEIGHTED + " So are given `paths`.",
"negative_edge_cycle": _PATH_OVERFLOW,
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/algorithms/centrality/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .group import *
from .harmonic import *
from .katz import *
from .reaching import *
72 changes: 72 additions & 0 deletions graphblas_algorithms/algorithms/centrality/reaching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import itertools

import numpy as np
from graphblas import Matrix, agg, replace
from graphblas.semiring import any_pair

from .._bfs import _adjacency, _bfs_level, _bfs_plain, _visited

__all__ = ["global_reaching_centrality", "local_reaching_centrality"]

# The most (source, node) slots one block of walks holds; its bitmap is this many bytes. A
# graph of up to 8192 nodes is walked in one block.
_BLOCK_SLOTS = 2**26


def _reaching(G, ids):
"""The local reaching centrality of each node of `ids`, by one walk from all of them at once.

A breadth-first search from every source of the block, one product per level. On a
directed graph a node's value is the share of the other nodes it reaches. On an undirected
one it is the sum of `1 / d` over the nodes at length `d`, as a share of the other nodes:
each level adds its count over its length, so the sum depends only on how many nodes each
level holds.
"""
A = _adjacency(G)
n = A.nrows
frontier = Matrix.from_coo(np.arange(len(ids)), ids, True, nrows=len(ids), ncols=n)
seen = _visited(frontier.dup(name="seen"))
sums = np.zeros(len(ids))
any_pair_bool = any_pair[bool]
for length in itertools.count(1):
frontier(~seen.S, replace) << any_pair_bool(frontier @ A)
if frontier.nvals == 0:
break
seen(frontier.S) << True
if not G.is_directed():
rows, counts = frontier.reduce_rowwise(agg.count).new().to_coo()
sums[rows] += counts / length
if G.is_directed():
rows, counts = seen.reduce_rowwise(agg.count).new().to_coo()
sums[rows] = counts - 1
return sums / (n - 1)


def global_reaching_centrality(G):
"""The mean, over the nodes, of how far each falls short of the most any node reaches.

NetworkX's local values in id order, which is node order for a converted graph, summed by
Python's `sum` as NetworkX sums them.
"""
n = len(G)
size = max(1, _BLOCK_SLOTS // n)
local = np.empty(n)
for start in range(0, n, size):
ids = np.arange(start, min(start + size, n), dtype=np.uint64)
local[ids] = _reaching(G, ids)
return sum((local.max() - local).tolist()) / (n - 1)


def local_reaching_centrality(G, v):
"""The share of the other nodes `v` reaches; undirected, each counts `1 / d` at length `d`.

The undirected terms are NetworkX's, nearest first, summed by Python's `sum` as NetworkX
sums them.
"""
n = len(G)
if G.is_directed():
return (_bfs_plain(G, v).nvals - 1) / (n - 1)
_, levels = _bfs_level(G, v).to_coo()
per_level = np.bincount(levels)[1:]
terms = np.repeat(1 / np.arange(1, len(per_level) + 1), per_level)
return sum(terms.tolist()) / (n - 1)
2 changes: 2 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,8 @@ class Dispatcher:
group_out_degree_centrality = mod.group.group_out_degree_centrality
harmonic_centrality = mod.harmonic.harmonic_centrality
katz_centrality = mod.katz.katz_centrality
global_reaching_centrality = mod.reaching.global_reaching_centrality
local_reaching_centrality = mod.reaching.local_reaching_centrality

mod = nxapi.cluster
# =================
Expand Down
1 change: 1 addition & 0 deletions graphblas_algorithms/nxapi/centrality/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@
from .group import *
from .harmonic import *
from .katz import *
from .reaching import *
50 changes: 50 additions & 0 deletions graphblas_algorithms/nxapi/centrality/reaching.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import can_run
from ..exception import NetworkXError, NodeNotFound

__all__ = ["global_reaching_centrality", "local_reaching_centrality"]


def _unweighted_without_paths(bound):
# With a weight NetworkX averages the weights along the path its Dijkstra picks among
# paths of equal length, so the answer turns on its tie-breaks.
if bound["weight"] is not None:
return "a weighted reaching centrality is left to networkx, as its ties pick the answer"
if bound.get("paths") is not None:
return "given `paths` are read by networkx"
# NetworkX's `shortest_path` reads a `v` of None as every source, and the lengths it then
# takes of the generator raise TypeError (directed) or AttributeError: its errors to give.
if "v" in bound and bound["v"] is None:
return "a `v` of None is left to networkx"
return None


def _check(G, name, bound):
# A direct call does not pass through `can_run`.
if (reason := _unweighted_without_paths(bound)) is not None:
raise NotImplementedError(f"{name}: {reason}")
# NetworkX's checks, in its order; `G.size()` counts a self-loop.
if G._A.nvals > 0 and len(G) == 1:
raise NetworkXError(
"local_reaching_centrality of a single node with self-loop not well-defined"
)
if G._A.nvals == 0:
raise NetworkXError("Size of G must be positive")


@can_run(_unweighted_without_paths)
def global_reaching_centrality(G, weight=None, normalized=True):
G = to_graph(G)
_check(G, "global_reaching_centrality", {"weight": weight})
return algorithms.global_reaching_centrality(G)


@can_run(_unweighted_without_paths)
def local_reaching_centrality(G, v, paths=None, weight=None, normalized=True):
G = to_graph(G)
_check(G, "local_reaching_centrality", {"weight": weight, "paths": paths, "v": v})
if v not in G:
raise NodeNotFound(f"Source {v} not in G")
return algorithms.local_reaching_centrality(G, v)
Loading
Loading