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
43 changes: 22 additions & 21 deletions _nx_graphblas/__init__.py

Large diffs are not rendered by default.

96 changes: 74 additions & 22 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,11 +73,6 @@
"Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\n"
"or more"
)
_NEGATIVE_EDGES = (
"Lengths are Bellman-Ford's, so a negative edge without a negative cycle is answered where\n"
'NetworkX\'s Dijkstra raises "Contradictory paths found".'
)

# The Wiener index and its relatives sum lengths, or terms of them, over each node's targets.
_LENGTH_SUM_OVERFLOW = (
"Raises OverflowError rather than add integer weights where the number of nodes times the\n"
Expand All @@ -87,10 +82,7 @@

_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
"elsewhere every one is computed. The null graph is left to NetworkX.\n" + _PATH_OVERFLOW
)

_CORE_SUBGRAPH = (
Expand All @@ -103,9 +95,7 @@
"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".'
"NetworkX."
),
"bellman_ford_path": _PATH_OVERFLOW,
"bellman_ford_path_length": _PATH_OVERFLOW,
Expand All @@ -123,15 +113,12 @@
"`sort_neighbors` is left to NetworkX."
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
"common_neighbor_centrality": (
"An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX."
),
"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,
"edge_betweenness_centrality": (
"Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\n"
Expand All @@ -144,18 +131,16 @@
"of `G.edges()`."
),
"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'
"call raises OverflowError rather than add integer weights where the number of nodes\n"
"times the heaviest absolute weight reaches 2**62, as a length could then pass 2**63."
"With `distance`, the call raises OverflowError rather than add integer weights where the\n"
"number of nodes times the heaviest absolute weight reaches 2**62, as a length could then\n"
"pass 2**63."
),
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
"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,
"harmonic_centrality": _NEGATIVE_EDGES,
"harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES,
"harmonic_diameter": "A precomputed `sp` is left to NetworkX.",
"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.'
Expand All @@ -177,7 +162,7 @@
+ _LENGTH_SUM_OVERFLOW,
"single_source_bellman_ford_path_length": _PATH_OVERFLOW,
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.",
"wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW,
"wiener_index": _LENGTH_SUM_OVERFLOW,
}

# A graph these names return is rebuilt from one matrix, which holds its values in one type.
Expand All @@ -204,6 +189,73 @@
_ADDITIONAL_DOCS[_name] = _ONE_WEIGHT_TYPE if _doc is None else f"{_doc}\n{_ONE_WEIGHT_TYPE}"


# Float weights whose sums may lose one, where NetworkX's walks and the checks here part.
_LOST_WEIGHT = (
"So are float weights with a negative one where n * n times the heaviest, doubled,\n"
"reaches 2**53 times the lightest nonzero one: a sum may lose a weight (1e300 - 1 is\n"
"1e300), and whether NetworkX then finds a negative cycle follows the order it adds."
)

# How the shortest-path names meet weights that are not finite numbers.
_NONFINITE = {
"bellman-ford": (
"An edge of NaN or +inf weight, which NetworkX's Bellman-Ford never relaxes, gives no\n"
"length, as there. A -inf weight is left to NetworkX, as is a self-loop of NaN or\n"
"infinite weight on an undirected graph, which its conversion makes NaN, and float\n"
"weights so heavy that a sum of n * n of them (on n nodes) may pass the largest float.\n"
+ _LOST_WEIGHT
),
"dijkstra": (
"A negative or NaN weight is left to NetworkX. Its Dijkstra meets them in the order it\n"
'pops its heap: whether a negative one raises "Contradictory paths found", and which\n'
"lengths a NaN hides."
),
"floyd-warshall": (
"A NaN or infinite weight is left to NetworkX, as are float weights so heavy that a\n"
"sum of n * n of them (on n nodes) may pass the largest float.\n" + _LOST_WEIGHT
),
}
for _rule, _names in {
"bellman-ford": [
"all_pairs_bellman_ford_path_length",
"bellman_ford_path",
"bellman_ford_path_length",
"negative_edge_cycle",
"single_source_bellman_ford_path_length",
],
"dijkstra": [
"center",
"closeness_centrality",
"diameter",
"eccentricity",
"gutman_index",
"harmonic_centrality",
"harmonic_diameter",
"hyper_wiener_index",
"periphery",
"radius",
"schultz_index",
"wiener_index",
],
"floyd-warshall": [
"floyd_warshall",
"floyd_warshall_numpy",
"floyd_warshall_predecessor_and_distance",
],
}.items():
for _name in _names:
_doc = _ADDITIONAL_DOCS.get(_name)
_note = _NONFINITE[_rule]
_ADDITIONAL_DOCS[_name] = _note if _doc is None else f"{_doc}\n{_note}"
_ADDITIONAL_DOCS["average_shortest_path_length"] += (
'\nWith `method="dijkstra"`, or a weight and no `method`, a negative or NaN weight is left\n'
'to NetworkX; with `method="bellman-ford"`, a NaN or infinite one, or float weights so\n'
"heavy that a sum of n * n of them (on n nodes) may pass the largest float, or, with a\n"
"negative one, so far apart that a sum may lose one."
)
_ADDITIONAL_DOCS["ego_graph"] += "\nWith `distance`, a negative or NaN weight is left to NetworkX."


def get_functions():
from graphblas_algorithms.interface import Dispatcher

Expand Down
3 changes: 3 additions & 0 deletions graphblas_algorithms/algorithms/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,9 @@ def _reconstruct_path_from_parents(G, parents, src, dst, target):
cur = dst
path = [cur]
while cur != src:
if len(path) > len(d):
# Else the walk never ends, and the list grows until memory runs out
raise RuntimeError(f"the parents from {target} come back on themselves")
cur = d[cur]
path.append(cur)
return G.list_to_keys(reversed(path))
Expand Down
10 changes: 7 additions & 3 deletions graphblas_algorithms/classes/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,12 +138,16 @@ def has_negative_diagonal(G, mask=None):
if A.dtype in NONNEGATIVE_DTYPES or A.dtype._is_udt or cache.get("has_self_edges") is False:
cache["has_negative_diagonal"] = False
elif (
# A negative weight, and none off the diagonal; a missing fact tells nothing.
cache.get("has_negative_edges+") is True
and cache.get("has_negative_edges-") is False
or cache.get("has_negative_edges+") is True
and cache.get("min_element-", 0) >= 0
or cache.get("min_element+", 0) < 0
and cache.get("min_element+", 0) < cache.get("min_element-", 0)
and "min_element-" in cache
and cache["min_element-"] >= 0
or "min_element+" in cache
and "min_element-" in cache
and cache["min_element+"] < 0
and cache["min_element+"] < cache["min_element-"]
):
cache["has_negative_diagonal"] = True
else:
Expand Down
148 changes: 147 additions & 1 deletion graphblas_algorithms/nxapi/_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
from math import ceil
from math import ceil, inf
from numbers import Number

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

from .exception import NetworkXError

try:
Expand Down Expand Up @@ -208,3 +211,146 @@ def nbunch_keys(G, nbunch, *, unique=False):
if present:
keys.append(node)
return list(dict.fromkeys(keys)) if unique else keys


def _read_apart(G):
"""`(nan, posinf, neginf)`: whether some weight of `G` is NaN, +inf or -inf; cached on `G`.

NetworkX's shortest-path walks meet these by comparisons that differ from the sums here. The
conversion of an undirected graph adds a self-loop's weight in twice and takes it out once,
so a loop of weight inf or -inf is NaN on the diagonal: such a NaN may be -inf.
"""

def find():
A = G._A
if A.nvals == 0 or A.dtype.np_type.kind != "f":
return False, False, False
_, _, values = A.to_coo(rows=False, columns=False)
nan = bool(np.isnan(values).any())
neginf = bool(np.isneginf(values).any())
if nan and not neginf and not G.is_directed():
_, loops = A.diag().to_coo()
neginf = bool(np.isnan(loops).any())
return nan, bool(np.isposinf(values).any()), neginf

return G._cacheit("read_apart", find)


def _relaxable(G):
A = select.valuelt(G._A, inf).new(name="relaxable")
return type(G)(A, key_to_id=G._key_to_id, weight=G._weight)


def _heaviest_finite(G):
"""The largest absolute value of `G`'s finite float weights, or 0.0; cached on `G`."""

def find():
A = G._A
if A.nvals == 0 or A.dtype.np_type.kind != "f":
return 0.0
if not any(_read_apart(G)):
least = A.reduce_scalar(monoid.min).get(0)
return float(max(-least, A.reduce_scalar(monoid.max).get(0)))
_, _, values = A.to_coo(rows=False, columns=False)
values = np.abs(values[np.isfinite(values)])
return float(values.max()) if values.size else 0.0

return G._cacheit("heaviest_finite", find)


def _lightest_finite(G):
"""The least absolute value of `G`'s nonzero finite float weights, or inf; cached on `G`."""

def find():
A = G._A
if A.nvals == 0 or A.dtype.np_type.kind != "f":
return inf
magnitudes = unary.abs(A).new(name="magnitudes")
# NaN is not greater than zero; inf is the least only where nothing else is left.
magnitudes << select.valuegt(magnitudes, 0)
return float(magnitudes.reduce_scalar(monoid.min).get(inf))

return G._cacheit("lightest_finite", find)


def check_float_sums(G, name):
"""Raise NotImplementedError where a sum of float weights may overflow or lose a weight.

The lengths of Bellman-Ford and Floyd-Warshall are sums of float weights. A length is the
sum of a walk: of at most `n` edges here, and of at most `n * n` in NetworkX's Bellman-Ford,
which queues each node fewer than `n` times before it reports a negative cycle; its
Floyd-Warshall adds two lengths of paths. So no length passes `n * n` times the heaviest
finite weight, doubled; doubling covers the rounding of such sums below 7e7 nodes.

Weights are left to NetworkX where that bound reaches the largest float. A sum past it is
inf or -inf: NetworkX relaxes no edge to a length of inf, which here is a length; and a
length at -inf falls no further, so a negative cycle may go unfound, here as in NetworkX,
where finding it then follows the order it walks (as for a -inf weight).

A sum also loses a weight under half a unit in its last place: 1e300 - 1 is 1e300. NetworkX
relaxes no edge where the length through it does not fall, so its Bellman-Ford finds no
negative cycle whose weight is lost, where the check here reads a negative self-loop from its
weight; and which cycles a walk finds then follows the order it adds, in either algorithm. A
weight of at least 2**-53 times the bound is never lost, so weights with a negative one are
left to NetworkX where the lightest nonzero one is less. Without a negative weight, a lost
weight gives a length within rounding of NetworkX's. Integer weights have their own bound
(`checked_sum_type`). Each fact is cached on `G`.
"""
n = G._A.nrows
# A product past the largest float is inf, which reaches it
bound = _heaviest_finite(G) * n * n * 2
if bound >= np.finfo(float).max:
raise NotImplementedError(
f"{name} with weights whose sums may overflow is left to networkx"
)
if G.get_property("has_negative_edges+") and bound >= _lightest_finite(G) * 2**53:
raise NotImplementedError(
f"{name} with weights so far apart that a sum may lose one is left to networkx"
)


def bellman_ford_graph(G, name):
"""`G` as NetworkX's Bellman-Ford walks it; NotImplementedError where the walks differ.

NetworkX relaxes an edge only where the length through it is less than the length its head
has, or than inf for a head not yet reached. Through a NaN or +inf weight it never is: NaN
compares false, inf is not less than inf, and -inf plus inf is NaN. Such an edge gives no
length and no predecessor, so it is dropped. A -inf weight is left to NetworkX: no length
falls below -inf, so the check here for a negative cycle, lengths that still fall after
`n - 1` rounds, misses cycles NetworkX finds; and whether NetworkX's own checks find one
follows the order it walks, as a node's length stops falling once it is -inf. So is a
self-loop of an undirected graph that may weigh -inf (`_read_apart`), and so are weights
whose sums may pass the largest float or lose a weight (`check_float_sums`).
"""
nan, posinf, neginf = _read_apart(G)
if neginf:
raise NotImplementedError(f"{name} with a -inf weight is left to networkx")
check_float_sums(G, name)
if not (nan or posinf):
return G
return G._cacheit("relaxable", _relaxable, G)


def check_dijkstra_weights(G, name):
"""Raise NotImplementedError where NetworkX's Dijkstra walks `G`'s weights its own way.

NetworkX answers these names with Dijkstra, which takes no weight to be negative. Given a
negative one, whether it raises "Contradictory paths found", and the lengths it gives when
it does not, follow the order it pops its heap; and a NaN length compares false with every
other, so which nodes get one, and which lengths a NaN hides, follow that order too. The
lengths here are least sums over every walk. Both facts are cached on `G`.
"""
if _read_apart(G)[0] or G.get_property("has_negative_edges+"):
raise NotImplementedError(f"{name} with a negative or NaN weight is left to networkx")


def check_finite_weights(G, name):
"""Raise NotImplementedError for a NaN or infinite weight, which NetworkX reads its own way.

Its Floyd-Warshall keeps a NaN entry, since no sum compares less, and gives a predecessor to
an edge of weight inf but to no walk through one; its NumPy version adds -inf to the inf of
a missing edge and so fills NaN. Its `average_shortest_path_length` by Bellman-Ford skips the
pairs that NaN and inf edges leave apart, though its test for a graph in pieces counts them.
"""
if any(_read_apart(G)):
raise NotImplementedError(f"{name} with a NaN or infinite weight is left to networkx")
11 changes: 3 additions & 8 deletions graphblas_algorithms/nxapi/centrality/closeness.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph

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

__all__ = ["closeness_centrality"]
Expand All @@ -19,20 +19,15 @@ def closeness_centrality(G, u=None, distance=None, wf_improved=True, *, sp=None)
if (reason := _without_sp({"sp": sp})) is not None:
raise NotImplementedError(reason)
G = to_graph(G, weight=distance)
check_dijkstra_weights(G, "closeness_centrality")
if u is not None and u not in G:
# NetworkX's answer is its shortest-path function's, which `distance` picks; Dijkstra's
# hashes `u` first, so an unhashable `u` is a TypeError there.
if distance is None:
raise NodeNotFound(f"Source {u} is not in G")
hash(u)
raise NodeNotFound(f"Node {u} not found in graph")
try:
result = algorithms.closeness_centrality(
G, None if u is None else [u], wf_improved=wf_improved
)
except algorithms.exceptions.Unbounded as e:
# What NetworkX's Dijkstra raises on a negative cycle.
raise ValueError("Contradictory paths found:", "negative weights?") from e
result = algorithms.closeness_centrality(G, None if u is None else [u], wf_improved=wf_improved)
if u is not None:
return result.get(G._key_to_id[u], 0.0)
# A dict, which NetworkX's `incremental_closeness_centrality` edits as its `prev_cc`.
Expand Down
Loading
Loading