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 @@ -307,6 +307,8 @@ graphblas_algorithms.nxapi
│ └── is_tree
├── triads
│ └── is_triad
├── walks
│ └── number_of_walks
└── wiener
├── gutman_index
├── hyper_wiener_index
Expand Down
2 changes: 2 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,7 @@ def get_info():
"normalized_laplacian_matrix",
"number_connected_components",
"number_of_isolates",
"number_of_walks",
"number_weakly_connected_components",
"onion_layers",
"out_degree_centrality",
Expand Down Expand Up @@ -224,6 +225,7 @@ def get_info():
"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.",
"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.",
"number_of_walks": "Counts from 2**63, where NetworkX's int64 wraps (to negative counts), are exact here up\nto 2**64; OverflowError is raised where a count could reach 2**64. A `walk_length` that\nis not an int is left to NetworkX.",
"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.",
Expand Down
5 changes: 5 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@
"memory stays bounded."
),
"negative_edge_cycle": _PATH_OVERFLOW,
"number_of_walks": (
"Counts from 2**63, where NetworkX's int64 wraps (to negative counts), are exact here up\n"
"to 2**64; OverflowError is raised where a count could reach 2**64. A `walk_length` that\n"
"is not an int is left to NetworkX."
),
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
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 @@ -26,4 +26,5 @@
from .traversal import *
from .tree import *
from .triads import *
from .walks import *
from .wiener import *
102 changes: 102 additions & 0 deletions graphblas_algorithms/algorithms/walks.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
import math

import numpy as np
from graphblas import Matrix, agg, dtypes, monoid, semiring, unary

__all__ = ["number_of_walks"]

# Integers below this, and sums of them that stay below it, are exact in FP64.
_EXACT = 2**53
_UNIT_ROUNDOFF = 2.0**-53


def number_of_walks(G, walk_length, *, method=None):
"""The number of walks of `walk_length` edges from each node to each, as a dense array.

Rows and columns are in node id order. Each edge counts once whatever its value, and so
does a self-loop. The counts are exact integers, in int64 below 2**53 and in uint64 above,
and OverflowError is raised where one could reach 2**64. On a graph with no edges they are
floats, as NetworkX's adjacency matrix of such a graph is float64.
"""
A = G._A
n = A.nrows
if A.nvals == 0:
return np.eye(n) if walk_length == 0 else np.zeros((n, n))
X, exact = _power(A, walk_length, dtypes.FP64, method)
if exact:
return X.to_dense(fill_value=0).astype(np.int64)
# A count passed 2**53, so these are estimates.
largest = X.reduce_scalar(monoid.max).get(0)
if not _largest_count_bound(largest, n, walk_length) < 2**64:
raise OverflowError(
f"the number of walks of length {walk_length} could reach 2**64 (the largest is "
f"about {largest:.4g}), which 64-bit integers cannot hold"
)
# uint64 arithmetic wraps modulo 2**64 even where a product on the way does not fit, so
# every count below 2**64 comes out exact.
X, _ = _power(A, walk_length, dtypes.UINT64, method)
return X.to_dense(fill_value=0)


def _largest_count_bound(largest, n, walk_length):
"""An upper bound on the largest count, from the largest float estimate of the counts.

Every term is positive, so each dot product of at most n terms is within a factor
1 + gamma of its exact value, and a count made of `walk_length` products in a row within
(1 + gamma)**walk_length. That error is clipped at e - 1, which says nothing anyway, so a
huge length cannot overflow it. Past 1/3 the bound is inf: below, it is within a factor
of 2, so a count below 2**63 (which NetworkX's int64 holds) is never taken for 2**64.
"""
gamma = n * _UNIT_ROUNDOFF / (1 - n * _UNIT_ROUNDOFF)
error = math.expm1(min(1.0, min(walk_length, 2**53) * math.log1p(gamma)))
return largest / (1 - error) if error < 1 / 3 else math.inf


def _power(A, k, dtype, method=None):
"""`A**k` in `dtype`, each of `A`'s entries taken as 1, and whether it is exact in FP64.

Exact means no entry of any product on the way reached 2**53. The power is built up
through the leading bits of `k`: from `A**j` to `A**(k >> s)`, by one squaring (and a
step) or by single-edge steps, whichever needs fewer multiplications. A squaring costs
the sum over nodes of (entries in its column) times (entries in its row), a step the
same with A's row instead: squaring wins on a cycle or a path, where the counts stay
sparse, and steps win once the counts fill in. `method` forces "squares" or "edges".
"""
n = A.nrows
if k == 0:
ids = np.arange(n)
return Matrix.from_coo(ids, ids, 1, dtype=dtype, nrows=n, ncols=n), True
X = unary.one[dtype](A).new()
times_A = semiring.plus_first[dtype] # A's values are not read
square = semiring.plus_times[dtype]
rows_A = _entries(A, rows=True)
exact = True
j = 1
for shift in range(k.bit_length() - 2, -1, -1):
target = k >> shift
if X.nvals == 0:
break # no walk of this length, so none longer
# Capped: no squaring costs as much as 2**53 steps, and a huge length is past floats.
steps = min(target - j, 2**53)
if method == "squares" or (
method is None
and (cols := _entries(X, rows=False)) @ _entries(X, rows=True)
<= steps * (cols @ rows_A)
):
X = X.mxm(X, square).new()
j *= 2
exact = exact and _below_exact(X, dtype)
while j < target and X.nvals:
X = X.mxm(A, times_A).new()
j += 1
exact = exact and _below_exact(X, dtype)
return X, exact


def _entries(X, *, rows):
counts = X.reduce_rowwise(agg.count) if rows else X.reduce_columnwise(agg.count)
return counts.new().to_dense(fill_value=0).astype(np.float64)


def _below_exact(X, dtype):
return dtype != dtypes.FP64 or X.reduce_scalar(monoid.max).get(0) < _EXACT
4 changes: 4 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,10 @@ class Dispatcher:
# ================
is_triad = mod.is_triad

mod = nxapi.walks
# ===============
number_of_walks = mod.number_of_walks

mod = nxapi.wiener
# ================
gutman_index = mod.gutman_index
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 @@ -27,6 +27,7 @@
from .tree import *
from .triads import *
from .tournament import is_tournament
from .walks import *
from .wiener import *

from . import centrality
Expand Down
Loading
Loading