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 graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
from math import nan

import numpy as np
from graphblas import Matrix, Vector, binary, monoid
from graphblas.semiring import plus_first, plus_times

Expand Down Expand Up @@ -163,6 +166,7 @@ def google_matrix(
A << binary.first(empty_rows.outer(p) | A)

scale = A.reduce_rowwise(monoid.plus).new(float)
rows, sums = scale.to_coo()
scale << alpha / scale
A << scale * A
p *= 1 - alpha
Expand All @@ -171,4 +175,8 @@ def google_matrix(
A(binary.plus)[:, :] = p
else:
A << A + p
# NetworkX divides the whole dense row by its sum, so a NaN sum makes every entry NaN,
# where this scales only the row's entries.
if nan_rows := rows[np.isnan(sums)].tolist():
A[nan_rows, :] = nan
return A
12 changes: 9 additions & 3 deletions graphblas_algorithms/linalg/laplacianmatrix.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from graphblas import monoid, unary
from graphblas import binary, monoid, unary

__all__ = [
"laplacian_matrix",
Expand Down Expand Up @@ -36,9 +36,12 @@ def normalized_laplacian_matrix(
):
d, A = _laplacian_helper(G, nodelist, is_weighted)
# A node whose weights sum to zero is left out of the scaling, which zeroes its row and
# column; NetworkX takes its 1 / sqrt(0) as 0.
# column; NetworkX takes its 1 / sqrt(0) as 0. So is a node whose weights sum to +inf,
# whose 1 / sqrt(inf) is 0: NetworkX's sparse diagonal drops the zero, and with it the
# node's row and column. A sum that is NaN or below zero gives NaN, which stays.
d_invsqrt = unary.sqrt(d.select("!=", 0).new()).new(name="d_invsqrt")
d_invsqrt << unary.minv(d_invsqrt)
d_invsqrt = d_invsqrt.select("!=", 0).new(name="d_invsqrt")

# Calculate: A_weighted = D_invsqrt @ A @ D_invsqrt
A_weighted = d_invsqrt.outer(d_invsqrt).new(mask=A.S, name=name)
Expand All @@ -48,7 +51,10 @@ def normalized_laplacian_matrix(
# A_weighted = (D_invsqrt @ A).new(name=name)
# A_weighted @= D_invsqrt

d_invsqrt << unary.one(d_invsqrt)
# NetworkX's diagonal is d_invsqrt * d * d_invsqrt, which is 1 here, or NaN with a NaN
# d_invsqrt even where the node has no self-loop.
d_invsqrt << binary.times(d_invsqrt, 0.0)
d_invsqrt << binary.plus(d_invsqrt, 1.0)
D = d_invsqrt.diag(name="D")
A_weighted << D - A_weighted
return A_weighted
39 changes: 39 additions & 0 deletions graphblas_algorithms/nxapi/_utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from math import ceil
from numbers import Number

import numpy as np

from .exception import NetworkXError

try:
Expand Down Expand Up @@ -208,3 +210,40 @@ 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 value of `G` is NaN, +inf or -inf; cached on `G`.

NetworkX meets these values with arithmetic and comparisons that can differ from the
matrix operations here.
"""

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)
return (
bool(np.isnan(values).any()),
bool(np.isposinf(values).any()),
bool(np.isneginf(values).any()),
)

return G._cacheit("read_apart", find)


def _signs(G):
"""`(largest, negative)`: the largest value of `G`, and whether some value is below zero.

NetworkX divides by the largest weight (clustering) and by sums of weights (the modularity
matrices, google_matrix, pagerank), and takes square roots of sums
(normalized_laplacian_matrix). So a largest weight of 0 can make it divide by zero, and a
negative weight can make a sum 0 or below 0, or make it cancel, so that its rounding follows
the order NetworkX adds in. Both are read off the minimum and maximum cached on `G`'s
conversion, which pass over NaN. A graph with no values gives None and False.
"""
if G._A.nvals == 0:
return None, False
smallest = G.get_property("min_element+").get()
return G.get_property("max_element+").get(), smallest is not None and smallest < 0
25 changes: 24 additions & 1 deletion graphblas_algorithms/nxapi/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from graphblas_algorithms.classes.nodemap import VectorMap
from graphblas_algorithms.utils import not_implemented_for

from ._utils import can_run, nbunch_keys, normalize_chunksize, partition
from ._utils import _read_apart, _signs, can_run, nbunch_keys, normalize_chunksize, partition

__all__ = [
"average_clustering",
Expand Down Expand Up @@ -42,8 +42,30 @@ def transitivity(G):
return G._cacheit("transitivity", func, G)


def _check_weights(G, weight, name):
"""Raise NotImplementedError for a NaN weight, or a largest weight of 0.

NetworkX scales the weights by `max(d.get(weight, 1) for u, v, d in G.edges(data=True))`.
Python's `max` keeps a NaN it starts with and passes over a NaN met later, so a NaN on the
first edge makes every scaled weight NaN, and one elsewhere only its own triangles. A
matrix keeps no edge order. An infinite weight gives the same maximum in any order.

A largest weight of 0 (every weight 0 or less) makes NetworkX divide by zero: it raises
ZeroDivisionError for Python numbers and gives NaN or infinities for NumPy ones, and only
at the nodes it reaches. A largest weight below 0 scales every weight to a positive one,
as here.
"""
if weight is None:
return
if _read_apart(G)[0]:
raise NotImplementedError(f"{name} with a NaN weight is left to networkx")
if _signs(G)[0] == 0:
raise NotImplementedError(f"{name} with a largest weight of 0 is left to networkx")


def clustering(G, nodes=None, weight=None):
G = to_graph(G, weight=weight) # to directed or undirected
_check_weights(G, weight, "clustering") # before `nodes`, which may be read only once
weighted = weight is not None
if nodes in G:
if G.is_directed():
Expand All @@ -62,6 +84,7 @@ def clustering(G, nodes=None, weight=None):

def average_clustering(G, nodes=None, weight=None, count_zeros=True):
G = to_graph(G, weight=weight) # to directed or undirected
_check_weights(G, weight, "average_clustering")
keys = nbunch_keys(G, nodes)
if len(G) == 0:
raise ZeroDivisionError("division by zero")
Expand Down
32 changes: 31 additions & 1 deletion graphblas_algorithms/nxapi/linalg/laplacianmatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
from graphblas_algorithms import linalg
from graphblas_algorithms.classes.digraph import to_graph

from .._utils import check_nodelist
from .._utils import _read_apart, _signs, check_nodelist

__all__ = ["laplacian_matrix", "normalized_laplacian_matrix"]

Expand All @@ -18,5 +18,35 @@ def laplacian_matrix(G, nodelist=None, weight="weight"):
def normalized_laplacian_matrix(G, nodelist=None, weight="weight"):
G = to_graph(G, weight=weight)
check_nodelist(G, nodelist)
if weight is not None and (_read_apart(G)[0] or _signs(G)[1]):
return _normalized_laplacian_as_networkx(G, nodelist)
rv = linalg.normalized_laplacian_matrix(G, nodelist, is_weighted=weight is not None)
return gb_io.to_scipy_sparse(rv)


def _normalized_laplacian_as_networkx(G, nodelist):
"""NetworkX's own arithmetic on the same SciPy array, for a NaN or a negative weight.

Such a weight can make a node's weight sum NaN or negative, so that 1 / sqrt(sum) is NaN,
and NetworkX's sparse products then put NaN only where `L = D - A` has an entry: SciPy
drops a zero there, as at an edge of weight 0, or at a node whose other weights sum to 0.
The sign of a sum that cancels follows the order of addition, which is SciPy's here too.
"""
import numpy as np
import scipy as sp

if nodelist is None:
A = G._A
else:
ids = G.list_to_ids(nodelist)
A = G._A[ids, ids].new()
A = sp.sparse.csr_array(gb_io.to_scipy_sparse(A, format="csr"))
n, _ = A.shape
diags = A.sum(axis=1)
D = sp.sparse.dia_array((diags, 0), shape=(n, n)).tocsr()
L = D - A
with np.errstate(divide="ignore"):
diags_sqrt = 1.0 / np.sqrt(diags)
diags_sqrt[np.isinf(diags_sqrt)] = 0
DH = sp.sparse.dia_array((diags_sqrt, 0), shape=(n, n)).tocsr()
return DH @ (L @ DH)
46 changes: 45 additions & 1 deletion graphblas_algorithms/nxapi/linalg/modularitymatrix.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
import numpy as np
from graphblas import io as gb_io

from graphblas_algorithms import linalg
from graphblas_algorithms.classes.digraph import to_directed_graph
from graphblas_algorithms.classes.graph import to_undirected_graph
from graphblas_algorithms.utils import not_implemented_for

from .._utils import check_nodelist
from .._utils import _read_apart, _signs, check_nodelist

__all__ = ["directed_modularity_matrix", "modularity_matrix"]

Expand All @@ -23,13 +24,49 @@ def _all_nan_if_no_edges(G, nodelist):
return np.full((n, n), np.nan) if nvals == 0 else None


def _for_networkx_arithmetic(G, nodelist, weight):
"""The weights `nodelist` selects as NetworkX holds them, if NetworkX's arithmetic decides.

A NaN or infinite value makes `m` NaN or infinite, and NetworkX's
`A - outer(k, k) / (2 * m)` then gives NaN in every row and column whose `k` is not finite,
and in a zero row or column beside one (0 times inf), where the sparse product here has no
entry. Every other entry is `A` less a zero, as a finite product over an infinite `m` is
zero. Weights that are all 0 make `m` 0, and NetworkX divides by it; weights of both signs
can make `m` cancel, to 0 or to a small number, by the order NetworkX adds in. So these are
computed with NetworkX's own arithmetic on the same SciPy array. Otherwise None.
"""
if weight is None:
return None
largest, negative = _signs(G)
positive = largest is not None and largest > 0
if positive and nodelist is None and not negative and not any(_read_apart(G)):
return None
if nodelist is None:
A = G._A
else:
ids = G.list_to_ids(nodelist)
A = G._A[ids, ids].new()
import scipy as sp

A = sp.sparse.csr_array(gb_io.to_scipy_sparse(A, format="csr"))
if np.isfinite(A.data).all() and (A.data >= 0).all() and (A.data > 0).any():
return None
return A


@not_implemented_for("directed")
@not_implemented_for("multigraph")
def modularity_matrix(G, nodelist=None, weight=None):
G = to_undirected_graph(G, weight=weight)
check_nodelist(G, nodelist)
if (all_nan := _all_nan_if_no_edges(G, nodelist)) is not None:
return all_nan
if (A := _for_networkx_arithmetic(G, nodelist, weight)) is not None:
k = A.sum(axis=1)
m = k.sum() * 0.5
with np.errstate(invalid="ignore", divide="ignore"):
X = np.outer(k, k) / (2 * m)
return A - X
rv = linalg.modularity_matrix(G, nodelist, is_weighted=weight is not None)
return rv.to_dense(fill_value=0)

Expand All @@ -41,5 +78,12 @@ def directed_modularity_matrix(G, nodelist=None, weight=None):
check_nodelist(G, nodelist)
if (all_nan := _all_nan_if_no_edges(G, nodelist)) is not None:
return all_nan
if (A := _for_networkx_arithmetic(G, nodelist, weight)) is not None:
k_in = A.sum(axis=0)
k_out = A.sum(axis=1)
m = k_in.sum()
with np.errstate(invalid="ignore", divide="ignore"):
X = np.outer(k_out, k_in) / m
return A - X
rv = linalg.directed_modularity_matrix(G, nodelist, is_weighted=weight is not None)
return rv.to_dense(fill_value=0)
17 changes: 16 additions & 1 deletion graphblas_algorithms/nxapi/link_analysis/hits_alg.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 _read_apart, _signs, can_run
from ..exception import NetworkXError, PowerIterationFailedConvergence

__all__ = ["hits"]
Expand All @@ -20,8 +20,23 @@ def hits(G, max_iter=100, tol=1.0e-8, nstart=None, normalized=True, *, method="p
if (reason := _power_iteration_only({"method": method})) is not None:
raise NotImplementedError(reason)
G = to_graph(G, weight="weight", dtype=float)
if any(_read_apart(G)):
# NetworkX 3.6 computes hits with ARPACK, which raises its own error on these values;
# later versions fail to converge, as the power iteration here does.
raise NotImplementedError("hits with a NaN or infinite weight is left to networkx")
if len(G) == 0:
return {}, {}
largest, negative = _signs(G)
if negative or largest == 0:
# Each step divides the hub values by their largest. NetworkX takes it over every node,
# 0 for a node with no hub value, and this power iteration over the values it holds.
# With every weight 0 the largest is 0: NetworkX does not converge (in 3.6 its ARPACK
# raises), and here the division is skipped. With a negative weight, hub values can all
# be below 0, so that NetworkX divides by 0 and this iteration does not. A graph with
# no edges is answered here, as the backend's notes say.
raise NotImplementedError(
"hits with a negative weight, or with every weight 0, is left to networkx"
)
x = None
if nstart is not None:
if missing := G._key_to_id.keys() - nstart.keys():
Expand Down
Loading
Loading