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
8 changes: 8 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,13 @@ graphblas_algorithms.nxapi
├── dag
│ ├── ancestors
│ └── descendants
├── distance_measures
│ ├── center
│ ├── diameter
│ ├── eccentricity
│ ├── harmonic_diameter
│ ├── periphery
│ └── radius
├── dominating
│ └── is_dominating_set
├── efficiency_measures
Expand Down Expand Up @@ -235,6 +242,7 @@ graphblas_algorithms.nxapi
│ │ ├── floyd_warshall_numpy
│ │ └── floyd_warshall_predecessor_and_distance
│ ├── generic
│ │ ├── average_shortest_path_length
│ │ └── has_path
│ ├── unweighted
│ │ ├── all_pairs_shortest_path_length
Expand Down
14 changes: 14 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ def get_info():
"all_pairs_shortest_path_length",
"ancestors",
"average_clustering",
"average_shortest_path_length",
"bellman_ford_path",
"bellman_ford_path_length",
"bethe_hessian_matrix",
Expand All @@ -42,6 +43,7 @@ def get_info():
"bfs_layers",
"bfs_successors",
"boundary_expansion",
"center",
"closeness_centrality",
"clustering",
"complement",
Expand All @@ -52,9 +54,11 @@ def get_info():
"degree_centrality",
"descendants",
"descendants_at_distance",
"diameter",
"difference",
"directed_modularity_matrix",
"disjoint_union",
"eccentricity",
"edge_boundary",
"edge_expansion",
"efficiency",
Expand All @@ -69,6 +73,7 @@ def get_info():
"generalized_degree",
"google_matrix",
"harmonic_centrality",
"harmonic_diameter",
"has_path",
"hits",
"in_degree_centrality",
Expand Down Expand Up @@ -104,6 +109,8 @@ def get_info():
"out_degree_centrality",
"overall_reciprocity",
"pagerank",
"periphery",
"radius",
"reciprocity",
"reverse",
"s_metric",
Expand Down Expand Up @@ -142,22 +149,29 @@ def get_info():
_additional_docs = {
# BEGIN: additional_docs
"all_pairs_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.",
"average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".',
"bellman_ford_path": "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.",
"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.",
"betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, 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.",
"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".',
"compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0, and an int past 2**53 rounded), bools mixed with numbers as numbers\n(True as 1 or 1.0), and NumPy scalars as Python numbers.",
"cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.",
"diameter": '`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.',
"disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0, and an int past 2**53 rounded), bools mixed with numbers as numbers\n(True as 1 or 1.0), and NumPy scalars as Python numbers.",
"eccentricity": 'A precomputed `sp`, and the null graph, are 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.',
"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 as\nfloats (1 as 1.0, and an int past 2**53 rounded), bools mixed with numbers as numbers\n(True as 1 or 1.0), and NumPy scalars as Python numbers.',
"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.",
"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".',
"harmonic_diameter": 'A precomputed `sp` 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".',
"hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.',
"k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0, and an int past 2**53 rounded), bools mixed with numbers as numbers\n(True as 1 or 1.0), and NumPy scalars as Python numbers.",
"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.',
"reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0, and an int past 2**53 rounded), bools mixed with numbers as numbers\n(True as 1 or 1.0), and NumPy scalars as Python numbers.",
"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 as\nfloats (1 as 1.0, and an int past 2**53 rounded), bools mixed with numbers as numbers\n(True as 1 or 1.0), and NumPy scalars as Python numbers.",
Expand Down
23 changes: 23 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,24 @@
'NetworkX\'s Dijkstra raises "Contradictory paths found".'
)

_ECCENTRICITY_BOUNDS = (
"`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\n"
"elsewhere every one is computed. The null graph is left to NetworkX.\n"
+ _NEGATIVE_EDGES
+ "\n"
+ _PATH_OVERFLOW
)

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_ADDITIONAL_DOCS = {
"all_pairs_bellman_ford_path_length": _PATH_OVERFLOW,
"average_shortest_path_length": (
'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n'
'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n'
"without a negative cycle is answered where NetworkX's Dijkstra raises\n"
'"Contradictory paths found".'
),
"bellman_ford_path": _PATH_OVERFLOW,
"bellman_ford_path_length": _PATH_OVERFLOW,
"betweenness_centrality": (
Expand All @@ -67,8 +81,14 @@
"The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n"
"`sort_neighbors` is left to NetworkX."
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
"cut_size": _SUM_OVERFLOW + ".",
"diameter": _ECCENTRICITY_BOUNDS,
"eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n"
+ _NEGATIVE_EDGES
+ "\n"
+ _PATH_OVERFLOW,
"ego_graph": (
"With `distance`, lengths are Bellman-Ford's, so a negative edge without a negative\n"
'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\n'
Expand All @@ -78,11 +98,14 @@
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
"harmonic_centrality": _NEGATIVE_EDGES,
"harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES,
"hits": (
"A graph with nodes and no edges gets 0.0 for every node, where NetworkX's power\n"
'iteration does not converge. `method="svd"` is left to NetworkX.'
),
"negative_edge_cycle": _PATH_OVERFLOW,
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"single_source_bellman_ford_path_length": _PATH_OVERFLOW,
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.",
}
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 @@ -7,6 +7,7 @@
from .core import *
from .cuts import *
from .dag import *
from .distance_measures import *
from .dominating import *
from .efficiency_measures import *
from .isolate import *
Expand Down
156 changes: 156 additions & 0 deletions graphblas_algorithms/algorithms/distance_measures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
import math

import numpy as np
from graphblas import Vector, monoid, select

from .centrality.harmonic import harmonic_centrality
from .exceptions import NoPath, PointlessConcept, Unbounded
from .shortest_paths._distance_batches import _batch_size, distance_batches

__all__ = [
"center",
"diameter",
"eccentricity",
"harmonic_diameter",
"periphery",
"radius",
]


def eccentricity(G, nodes=None, *, first=None):
"""The greatest length from each node of `nodes` to any node, by node id.

`nodes` is a list of distinct node keys, or None for every node. Raises NoPath when one of
them does not reach every node, so that its greatest length is infinite, or Unbounded on a
negative cycle: whichever a walk from one node at a time in that order meets first, or a
walk from `first` alone when it is given.
"""
n = len(G)
if n == 0:
raise PointlessConcept("Cannot compute eccentricity of a null graph.")
result = None
try:
for ids, D in distance_batches(G, nodes):
# A row holds `n` entries when its source reaches every node.
if D.nvals != D.nrows * n:
raise NoPath("Found infinite path length")
if result is None:
result = Vector(D.dtype, n, name="eccentricity")
result[ids] << D.reduce_rowwise(monoid.max)
except Unbounded:
# A batch raises for a cycle any of its sources reaches; NetworkX walks one source at a
# time and raises at the first that misses a node or meets the cycle.
for source in [first] if first is not None else (G if nodes is None else nodes):
[(_ids, D)] = distance_batches(G, [source])
if D.nvals != n:
raise NoPath("Found infinite path length") from None
raise
return Vector(int, n, name="eccentricity") if result is None else result


def _bounded_eccentricity(G, *, greatest, ties):
"""The eccentricities of enough nodes of an undirected `G` to hold every extreme one.

A walk from `s` bounds the eccentricity of each node `i` at length `d` from it:
`max(d, ecc(s) - d) <= ecc(i) <= ecc(s) + d` (Takes and Kosters). Nodes are walked from, in
batches that double, until no other node's bounds allow an eccentricity beyond the greatest
(or least) one found, or with `ties`, equal to it. Exact when the lengths are integers.
"""
n = len(G)
if n == 0:
raise PointlessConcept("Cannot compute eccentricity of a null graph.")
lower = np.zeros(n, np.int64)
upper = np.full(n, np.iinfo(np.int64).max)
ecc = np.zeros(n, np.int64)
known = np.zeros(n, bool)
degrees = G.get_property("degrees+").to_dense(fill_value=0)
size = 1
while True:
open_ = ~known
if known.any() and greatest:
extreme = ecc[known].max()
open_ &= upper >= extreme if ties else upper > extreme
elif known.any():
extreme = ecc[known].min()
open_ &= lower <= extreme if ties else lower < extreme
if not open_.any():
break
# Half from the least lower bounds (central nodes, which bring the upper bounds down),
# the rest from the greatest upper bounds (outlying ones, which bring the lower bounds
# up); the higher degree first among equals.
candidates = np.flatnonzero(open_)
by_lower = candidates[np.lexsort((-degrees[candidates], lower[candidates]))]
by_upper = candidates[np.lexsort((-degrees[candidates], -upper[candidates]))]
picks = np.concatenate([by_lower[: (size + 1) // 2], by_upper[:size]])
_, first = np.unique(picks, return_index=True)
for ids, D in distance_batches(G, G.list_to_keys(picks[np.sort(first)][:size])):
if D.nvals != D.nrows * n:
raise NoPath("Found infinite path length")
dtype = D.dtype
d = D.to_dense().astype(np.int64, copy=False)
e = d.max(axis=1)
ecc[ids] = e
known[ids] = True
# One scratch array for both bounds, and the batch let go before the next is walked.
t = np.subtract(e[:, None], d)
np.maximum(lower, np.maximum(t, d, out=t).max(axis=0), out=lower)
np.minimum(upper, np.add(e[:, None], d, out=t).min(axis=0), out=upper)
del t, d, D
size = min(2 * size, _batch_size(n))
ids = np.flatnonzero(known)
return Vector.from_coo(ids, ecc[ids], dtype=dtype, size=n, name="eccentricity")


def _eccentricities(G, usebounds, *, greatest, ties):
"""Every eccentricity, or with `usebounds` where the bounds hold, enough of them."""
if not usebounds or G.is_directed():
return eccentricity(G)
if G._A.dtype.np_type.kind in "biu":
return _bounded_eccentricity(G, greatest=greatest, ties=ties)
# NetworkX's bounded search walks first from a node of greatest degree, so that walk decides
# what a graph in pieces with a negative cycle raises.
degrees = G.get_property("degrees+").to_dense(fill_value=0)
return eccentricity(G, first=G.id_to_key[int(degrees.argmax())])


def diameter(G, *, usebounds=False):
"""The greatest eccentricity.

With `usebounds`, an undirected graph whose lengths are integers is walked from as few
nodes as the bounds allow; otherwise from every node.
"""
return _eccentricities(G, usebounds, greatest=True, ties=False).reduce(monoid.max).get()


def radius(G, *, usebounds=False):
"""The least eccentricity; `usebounds` as for `diameter`."""
return _eccentricities(G, usebounds, greatest=False, ties=False).reduce(monoid.min).get()


def periphery(G, *, usebounds=False):
"""The eccentricity of each node whose eccentricity is the diameter, by node id.

`usebounds` as for `diameter`.
"""
ecc = _eccentricities(G, usebounds, greatest=True, ties=True)
return select.valueeq(ecc, ecc.reduce(monoid.max).get()).new(name="periphery")


def center(G, *, usebounds=False):
"""The eccentricity of each node whose eccentricity is the radius, by node id.

`usebounds` as for `diameter`.
"""
ecc = _eccentricities(G, usebounds, greatest=False, ties=True)
return select.valueeq(ecc, ecc.reduce(monoid.min).get()).new(name="center")


def harmonic_diameter(G):
"""`n (n - 1)` over the sum of `1 / d` for the lengths `d` between nodes, except a `d` of 0.

Infinite when there is no such length, NaN for a graph of fewer than two nodes.
"""
n = len(G)
if (total := harmonic_centrality(G).reduce(monoid.plus).get(0)) != 0:
return n * (n - 1) / total
return math.inf if n > 1 else math.nan
31 changes: 29 additions & 2 deletions graphblas_algorithms/algorithms/shortest_paths/generic.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
from ..exceptions import NoPath
from graphblas import monoid

from .._bfs import _bfs_plain
from ..exceptions import NoPath, PointlessConcept
from ._distance_batches import distance_batches
from .unweighted import bidirectional_shortest_path_length

__all__ = ["has_path"]
__all__ = ["average_shortest_path_length", "has_path"]


def has_path(G, source, target):
Expand All @@ -10,3 +14,26 @@ def has_path(G, source, target):
except NoPath:
return False
return True


def average_shortest_path_length(G):
"""The mean length over ordered pairs of distinct nodes; 0 for one node.

Raises NoPath, before any length is found, unless every node reaches every node.
"""
n = len(G)
if n == 0:
raise PointlessConcept(
"the null graph has no paths, thus there is no average shortest path length"
)
if n == 1:
return 0
# Every node reaches every node when one node reaches all and all reach it.
source = next(iter(G))
directions = (False, True) if G.is_directed() else (False,)
if any(_bfs_plain(G, source, transpose=t).nvals < n for t in directions):
raise NoPath("Graph is not connected.")
# Lengths in floats, as the mean is: integer lengths, and their sum, can pass 2**63.
batches = distance_batches(G, dtype=float)
total = sum(D.reduce_scalar(monoid.plus).get(0) for _ids, D in batches)
return total / (n * (n - 1))
Loading
Loading