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
70 changes: 35 additions & 35 deletions _nx_graphblas/__init__.py

Large diffs are not rendered by default.

58 changes: 30 additions & 28 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,14 @@
}

# NetworkX adds integer weights as Python integers; here they are 64-bit (`checked_sum_type`).
# Past these bounds the kernels raise IntegerOverflowError, which NetworkX's dispatcher takes as
# NotImplementedError, so it tries the next backend: NetworkX itself for a NetworkX graph.
_PATH_OVERFLOW = (
"Raises OverflowError rather than add integer weights where the number of nodes times the\n"
"heaviest absolute weight reaches 2**62, as a length could then pass 2**63."
"Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\n"
"weight reaches 2**62, as a length could then pass 2**63."
)
_SUM_OVERFLOW = (
"Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\n"
"or more"
"Integer weights are left to NetworkX where their absolute values sum to 2**63 or more"
)
_NEGATIVE_EDGES = (
"Lengths are Bellman-Ford's, so a negative edge without a negative cycle is answered where\n"
Expand All @@ -80,9 +81,8 @@

# 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"
"heaviest absolute weight reaches 2**62, or where the sum over one node's targets could\n"
"reach 2**63."
"Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\n"
"weight reaches 2**62, or where the sum over one node's targets could reach 2**63."
)

_ECCENTRICITY_BOUNDS = (
Expand All @@ -99,15 +99,14 @@

# The degree assortativity names add weights into weighted degrees.
_DEGREE_OVERFLOW = (
"Raises OverflowError rather than add integer weights where a weighted degree could reach\n"
"2**63: where the absolute values one node adds (a self-loop's twice) sum to that."
"Integer weights are left to NetworkX where a weighted degree could reach 2**63: where the\n"
"absolute values one node adds (a self-loop's twice) sum to that."
)
_NEIGHBOR_DEGREE_WEIGHTS = (
"Complex weights are left to NetworkX. Float weights are added in another order than\n"
"NetworkX's, so a value may differ from NetworkX's in its last bits. Raises OverflowError\n"
"rather than add integer weights where a node's weighted degree, or its sum of each\n"
"weight times the neighbor's degree, could reach 2**63 (by the sum of the absolute values\n"
"it adds)."
"NetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\n"
"left to NetworkX where a node's weighted degree, or its sum of each weight times the\n"
"neighbor's degree, could reach 2**63 (by the sum of the absolute values it adds)."
)
_DEGREES_AS_KEYS = (
'On a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\n'
Expand Down Expand Up @@ -136,7 +135,8 @@
"without a negative cycle is answered where NetworkX's Dijkstra raises\n"
'"Contradictory paths found".'
),
"average_degree_connectivity": _NEIGHBOR_DEGREE_WEIGHTS,
"average_degree_connectivity": _NEIGHBOR_DEGREE_WEIGHTS
+ "\nWith `weight`, an iterator `nodes` is left to NetworkX.",
"average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\n"
+ _NEIGHBOR_DEGREE_WEIGHTS,
"bellman_ford_path": _PATH_OVERFLOW,
Expand All @@ -159,7 +159,7 @@
"common_neighbor_centrality": (
"An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX."
),
"cut_size": _SUM_OVERFLOW + ".",
"cut_size": _SUM_OVERFLOW + ".\nWith `weight`, an iterator `S` or `T` is left to NetworkX.",
"degree_assortativity_coefficient": (
"`nodes` one node, or an iterator, which NetworkX reads twice, is left to NetworkX.\n"
"The coefficient is taken from the counts of degree pairs in closed form, not from\n"
Expand All @@ -182,13 +182,13 @@
"degree_pearson_correlation_coefficient": (
"SciPy's `pearsonr` of the same pairs in another order, so the value may differ from\n"
"NetworkX's in its last bits; past 2**24 stored edges it is taken from the counts of\n"
"degree pairs.\n" + _DEGREES_AS_FLOATS
"degree pairs.\n"
+ _DEGREES_AS_FLOATS
+ "\nWith `weight`, an iterator `nodes` is left to NetworkX."
),
"diameter": _ECCENTRICITY_BOUNDS,
"eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n"
+ _NEGATIVE_EDGES
+ "\n"
+ _PATH_OVERFLOW,
"eccentricity": "A precomputed `sp`, the null graph, and with `weight` an iterator `v`, are\n"
"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"
"The edges come by their first ends in node order, then by their second ends in node\n"
Expand All @@ -201,9 +201,9 @@
),
"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."
'cycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and\n'
"integer weights are left to NetworkX where the number of nodes times the heaviest\n"
"absolute weight reaches 2**62, as a length could then pass 2**63."
),
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
Expand Down Expand Up @@ -238,17 +238,19 @@
"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,
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.",
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.\n"
"With `weight`, an iterator `S` is left to NetworkX.",
"wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW,
}

# A graph these names return is rebuilt from one matrix, which holds its values in one type.
# full_join rebuilds its inputs too, but leaves a weighted graph to NetworkX.
_ONE_WEIGHT_TYPE = (
"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\n"
"numbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\n"
"change a value, such as an int past 2**53 beside a float, is left to NetworkX."
"Edge weights come back in the one type their matrix holds: mixed ints and floats as\n"
"floats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\n"
"scalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\n"
"one beside a float, or that are all ints held as floats, such as `np.uint64` beside a\n"
"signed int, are left to NetworkX."
)
for _name in (
"compose",
Expand Down
9 changes: 6 additions & 3 deletions graphblas_algorithms/algorithms/_helpers.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from graphblas import binary, dtypes, monoid, unary

from .exceptions import IntegerOverflowError

_ADVICE = (
"which 64-bit integers cannot hold; NetworkX computes with Python integers. Convert the "
"weights to float, or call with backend='networkx'."
Expand Down Expand Up @@ -39,7 +41,8 @@ def checked_sum_type(G, kind, *, count=1):

Integers and booleans are added in INT64, where a smaller type would wrap sooner. INT64
still wraps silently at 2**63, and NetworkX's Python integers do not, so this raises
OverflowError when the bound for `kind` reaches it:
IntegerOverflowError, which NetworkX's dispatcher answers itself, when the bound for `kind`
reaches it:
- "path": a length is a walk of at most `n` edges, and two lengths may be added, so `n`
times the heaviest absolute value off the diagonal must stay below 2**62;
- "sum": the absolute values, each counted up to `count` times, must sum to less than 2**63.
Expand All @@ -52,7 +55,7 @@ def checked_sum_type(G, kind, *, count=1):
least, greatest = G.get_properties("min_element- max_element-")
heaviest = max(-least.get(0), greatest.get(0))
if A.nrows * heaviest >= 2**62:
raise OverflowError(
raise IntegerOverflowError(
f"integer edge weights up to {heaviest} on {A.nrows} nodes could make a path "
f"length reach 2**63, {_ADVICE}"
)
Expand All @@ -64,7 +67,7 @@ def checked_sum_type(G, kind, *, count=1):
total = G._cacheit("abs_sum+", _abs_sum, A)
if total * count >= 2**63:
times = f", counted up to {count} times," if count > 1 else ""
raise OverflowError(
raise IntegerOverflowError(
f"integer edge weights whose absolute values sum to {total:.4g}{times} "
f"could make a sum of them reach 2**63, {_ADVICE}"
)
Expand Down
5 changes: 3 additions & 2 deletions graphblas_algorithms/algorithms/assortativity/mixing.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from graphblas.semiring import plus_pair, plus_second

from .._helpers import _ADVICE, undirected_degrees
from ..exceptions import IntegerOverflowError

__all__ = [
"check_int_sums",
Expand Down Expand Up @@ -36,7 +37,7 @@ def _sum_type(G):


def check_int_sums(G, bounds, what):
"""Raise OverflowError unless an integer sum of `G`'s values stays inside INT64.
"""Raise IntegerOverflowError unless an integer sum of `G`'s values stays inside INT64.

`bounds` is a callable giving, from the absolute values of `G`'s matrix in FP64, a Vector
whose entry for each node bounds the absolute value of each partial sum of that node's
Expand All @@ -53,7 +54,7 @@ def check_int_sums(G, bounds, what):
return
largest = bound(unary.abs[dtypes.FP64](A).new()).reduce(monoid.max).get(0.0)
if largest >= _SAFE_BOUND:
raise OverflowError(
raise IntegerOverflowError(
f"integer edge weights give a node {what} of up to {largest:.4g} in absolute "
f"value, so a sum of them could reach 2**63, {_ADVICE}"
)
Expand Down
2 changes: 1 addition & 1 deletion graphblas_algorithms/algorithms/cuts.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ def cut_size(G, S, T=None, *, is_weighted=False, dtype=None):
"""The weight of the edges between S and T (both ways when directed), or their number.

Weights are added in `dtype`, or by default as `checked_sum_type` says: integers in INT64,
raising OverflowError where their sum could reach 2**63.
raising IntegerOverflowError where their sum could reach 2**63.
"""
if is_weighted and dtype is None:
dtype = checked_sum_type(G, "sum")
Expand Down
9 changes: 9 additions & 0 deletions graphblas_algorithms/algorithms/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,12 @@ class NoPath(GraphBlasAlgorithmException):

class Unbounded(GraphBlasAlgorithmException):
pass


class IntegerOverflowError(OverflowError, NotImplementedError):
"""A sum of 64-bit integers could reach 2**63, where it would wrap.

NetworkX adds integer weights as Python integers, which do not wrap. To a direct caller this
is an OverflowError. NetworkX's dispatcher takes it as NotImplementedError and tries the next
backend it is configured to, which answers exactly when it is NetworkX.
"""
2 changes: 1 addition & 1 deletion graphblas_algorithms/algorithms/shortest_paths/dense.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ def floyd_warshall_predecessor_and_distance(
"""The predecessors, or None, and the distances between every pair of nodes.

`dtype` is the distances' dtype: by default the values' own, or INT64 for integers, which
raises OverflowError where a distance could reach 2**63.
raises IntegerOverflowError where a distance could reach 2**63.
"""
# By using `offdiag` instead of `G._A`, we ensure that D will not become dense.
# Dense D may be better at times, but not including the diagonal will result in less work.
Expand Down
8 changes: 4 additions & 4 deletions graphblas_algorithms/algorithms/shortest_paths/weighted.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ def _length_dtype(G, A, dtype=None):
"""`dtype`, or else the lengths' dtype over `A`, which is `G` without self-loops.

A graph with no edge between two nodes has only zero lengths, NetworkX's integer 0. Other
lengths are added as `checked_sum_type` says, which raises OverflowError where integer ones
could reach 2**63.
lengths are added as `checked_sum_type` says, which raises IntegerOverflowError where
integer ones could reach 2**63.
"""
if dtype is not None:
return dtype
Expand Down Expand Up @@ -136,8 +136,8 @@ def bellman_ford_path_lengths(G, nodes=None, *, expand_output=False, dtype=None)
When True, the returned Matrix has the same shape as the input Matrix.
dtype : dtype, optional
The lengths' dtype. By default the values' own, or INT64 for integers, which raises
OverflowError where a length could reach 2**63; a caller whose answer is a float can
pass a floating-point type instead.
IntegerOverflowError where a length could reach 2**63; a caller whose answer is a float
can pass a floating-point type instead.
"""
# Same algorithms as in `single_source_bellman_ford_path_length`, but with
# `Cur` as a Matrix with each row corresponding to a source node.
Expand Down
12 changes: 6 additions & 6 deletions graphblas_algorithms/algorithms/wiener.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from ._bfs import _bfs_plain
from ._helpers import _ADVICE, undirected_degrees
from .exceptions import PointlessConcept
from .exceptions import IntegerOverflowError, PointlessConcept
from .shortest_paths._distance_batches import distance_batches

__all__ = ["gutman_index", "hyper_wiener_index", "schultz_index", "wiener_index"]
Expand All @@ -18,8 +18,8 @@ def wiener_index(G):

Infinite unless every node reaches every node. Integer lengths are summed exactly, as
NetworkX sums its Python integers, so the result is an int on a directed graph and a float
otherwise. Raises OverflowError rather than let a source's sum of integer lengths reach
2**63 in 64 bits.
otherwise. Raises IntegerOverflowError rather than let a source's sum of integer lengths
reach 2**63 in 64 bits.
"""
if not _connected(G):
return math.inf
Expand Down Expand Up @@ -94,8 +94,8 @@ def _total(G, rows):
"""The sum, over the batches of every source, of the per-source values `rows` lists.

`rows(ids, D, check)` gets a batch and `check`, which turns a Vector of per-source sums of
terms in `D` into Python numbers, raising OverflowError first where an integer sum could
have wrapped. Integers are added as Python ints, so the total is exact.
terms in `D` into Python numbers, raising IntegerOverflowError first where an integer sum
could have wrapped. Integers are added as Python ints, so the total is exact.
"""
n = len(G)
total = 0
Expand All @@ -108,7 +108,7 @@ def _total(G, rows):
def check(sums, power, *, scale=1, longest=longest):
# A per-source sum adds up to `n` terms of at most `scale * longest**power`.
if longest is not None and n * scale * longest**power >= 2**63:
raise OverflowError(
raise IntegerOverflowError(
f"integer lengths up to {longest} between {n} nodes could make a sum of "
f"them reach 2**63, {_ADVICE}"
)
Expand Down
Loading
Loading