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 _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ def get_info():
"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, 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.',
"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.",
"google_matrix": "Keys of `personalization` and `dangling` that are not nodes are left out, as NetworkX\nleaves them. NetworkX divides each by its sum: where `personalization` sums to 0, inf\nor NaN, or `dangling` does and a node dangles, the call is left to NetworkX.",
"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.\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, or where the sum over one node\'s targets could\nreach 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".',
Expand All @@ -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.",
"pagerank": "Keys of `nstart`, `personalization` and `dangling` that are not nodes are left out, as\nNetworkX leaves them. NetworkX divides each by its sum, `dangling` even where no node\ndangles: where one sums to 0, inf or NaN, the call is left to NetworkX.\nWhere values of both signs nearly cancel, so that dividing by their sum magnifies its\nrounding, rounding may decide whether NetworkX's iteration stops, and its ranks: such a\ncall is left to NetworkX. The sums are each node's out-weights and those of `nstart`,\n`personalization` and `dangling`; the magnifications, the sum of the values' sizes over\nthe size of their sum, are multiplied, and the call is left to NetworkX past\n`sqrt(tol / 2**-52) / 100` (671 for the default `tol`). A node with three or more\nout-weights of both signs is left to NetworkX in any case.",
"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
17 changes: 17 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,11 @@
),
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
"google_matrix": (
"Keys of `personalization` and `dangling` that are not nodes are left out, as NetworkX\n"
"leaves them. NetworkX divides each by its sum: where `personalization` sums to 0, inf\n"
"or NaN, or `dangling` does and a node dangles, the call is left to NetworkX."
),
"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,
Expand All @@ -171,6 +176,18 @@
"memory stays bounded."
),
"negative_edge_cycle": _PATH_OVERFLOW,
"pagerank": (
"Keys of `nstart`, `personalization` and `dangling` that are not nodes are left out, as\n"
"NetworkX leaves them. NetworkX divides each by its sum, `dangling` even where no node\n"
"dangles: where one sums to 0, inf or NaN, the call is left to NetworkX.\n"
"Where values of both signs nearly cancel, so that dividing by their sum magnifies its\n"
"rounding, rounding may decide whether NetworkX's iteration stops, and its ranks: such a\n"
"call is left to NetworkX. The sums are each node's out-weights and those of `nstart`,\n"
"`personalization` and `dangling`; the magnifications, the sum of the values' sizes over\n"
"the size of their sum, are multiplied, and the call is left to NetworkX past\n"
"`sqrt(tol / 2**-52) / 100` (671 for the default `tol`). A node with three or more\n"
"out-weights of both signs is left to NetworkX in any case."
),
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
Expand Down
30 changes: 20 additions & 10 deletions graphblas_algorithms/algorithms/link_analysis/pagerank_alg.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

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

from graphblas_algorithms import Graph

Expand Down Expand Up @@ -65,7 +65,10 @@ def pagerank(
# Fold alpha constant into S
if row_degrees is None:
row_degrees = nonzero_out_weight_sums(A)
S = (alpha / row_degrees).new(name="S")
# 1 / sum first, as NetworkX takes it: below about 5.6e-309 it passes the largest float,
# where alpha / sum may not, and NetworkX's ranks turn inf or NaN.
S = (1.0 / row_degrees).new(name="S")
S *= alpha

if (iso_value := G.get_property("iso_value")) is not None:
# Fold iso-value of A into S
Expand All @@ -82,9 +85,12 @@ def pagerank(
dangling_mask(mask=~S.S) << 1.0
# Fold alpha constant into dangling_weights (or dangling_mask)
if dangling is not None:
dangling_weights = (alpha / dangling.reduce().get(0) * dangling).new(
name="dangling_weights"
)
denom = dangling.reduce().get(0)
if denom == 0:
raise ZeroDivisionError("dangling sums to 0")
# Divided first, as in NetworkX: alpha over a tiny sum can pass the largest float
dangling_weights = (dangling / denom).new(name="dangling_weights")
dangling_weights *= alpha
elif personalization is None:
# Fast case (and common case); is iso-valued
dangling_mask(mask=dangling_mask.S) << alpha * p
Expand Down Expand Up @@ -156,19 +162,23 @@ def google_matrix(
if dangling is not None:
if ids is not None:
dangling = dangling[ids].new(name="dangling")
dangling_weights = (1.0 / dangling.reduce().get(0) * dangling).new(
mask=dangling.V, name="dangling_weights"
)
denom = dangling.reduce().get(0)
if denom == 0:
raise ZeroDivisionError("dangling sums to 0")
# Divided, as in NetworkX: 1 over a tiny sum can pass the largest float
dangling_weights = (dangling / denom).new(mask=dangling.V, name="dangling_weights")
A << binary.first(empty_rows.outer(dangling_weights) | A)
elif personalization is None:
A << binary.first((p * empty_rows) | A)
else:
A << binary.first(empty_rows.outer(p) | A)

# Each row divided by its sum, as in NetworkX: 1 or alpha over a tiny sum can pass the
# largest float, and the row would turn inf
scale = A.reduce_rowwise(monoid.plus).new(float)
rows, sums = scale.to_coo()
scale << alpha / scale
A << scale * A
A << any_rdiv(scale.diag() @ A)
A *= alpha
p *= 1 - alpha
if personalization is None:
# Add a scalar everywhere, which makes A dense
Expand Down
99 changes: 90 additions & 9 deletions graphblas_algorithms/nxapi/link_analysis/pagerank_alg.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import math
from math import inf

import numpy as np
from graphblas import agg, binary
from graphblas import Vector, agg, binary, monoid, unary

from graphblas_algorithms import algorithms
from graphblas_algorithms.algorithms.link_analysis.pagerank_alg import nonzero_out_weight_sums
Expand Down Expand Up @@ -44,12 +45,20 @@ def pagerank(
"is left to networkx"
)
# We'll normalize initial, personalization, and dangling vectors later
x = G.dict_to_vector(nstart, dtype=float, name="nstart")
p = G.dict_to_vector(personalization, dtype=float, name="personalization")
if dangling is not None and row_sums.nvals < N:
dangling_weights = G.dict_to_vector(dangling, dtype=float, name="dangling")
else:
dangling_weights = None
x = _values_at_nodes(G, nstart, "nstart")
p = _values_at_nodes(G, personalization, "personalization")
d = _values_at_nodes(G, dangling, "dangling")
# NetworkX divides the dangling values by their sum even where no node dangles, and then
# fails to converge where that sum is 0, inf or NaN: 0 times NaN is NaN
_check_sums("pagerank", nstart=x, personalization=p, dangling=d)
dangling_weights = d if d is not None and row_sums.nvals < N else None
# Dividing by a sum magnifies its rounding where its values cancel, which NetworkX's own
# rounding then decides: whether it stops, and with which ranks.
magnified = _magnification(G._A, x, p, dangling_weights)
if magnified > 1 and magnified > _magnification_allowed(tol):
raise NotImplementedError(
"pagerank where values of both signs nearly cancel is left to networkx"
)
try:
result = algorithms.pagerank(
G,
Expand Down Expand Up @@ -85,18 +94,90 @@ def find():
return G._cacheit("out_weights_cancel_by_order", find)


def _values_at_nodes(G, values, name):
"""A dict's values at `G`'s nodes, as a vector; other keys are left out, as NetworkX does."""
if values is None:
return None
key_to_id = G._key_to_id
pairs = [(key_to_id[key], value) for key, value in values.items() if key in key_to_id]
ids, at_nodes = zip(*pairs, strict=True) if pairs else ((), ())
return Vector.from_coo(ids, at_nodes, size=len(G), dtype=float, name=name)


def _check_sums(name, **vectors):
"""Leave to NetworkX a call where one of `vectors` sums to 0, or to inf or NaN.

NetworkX divides each by its sum: 0 makes NaN, so its iteration fails to converge (for
`personalization` it raises ZeroDivisionError), and so does a value of inf or NaN, which
makes NaN in `google_matrix`. Finite values whose sum only overflows give zeros there;
such a call goes to NetworkX as well.
"""
for key, v in vectors.items():
if v is not None:
total = v.reduce().get(0)
if total == 0 or not math.isfinite(total):
raise NotImplementedError(f"{name} where {key} sums to {total} is left to networkx")


def _magnification_allowed(tol):
"""The most rounding may be magnified, for NetworkX's answer to stay the same here.

Rounding to within `eps` (2**-52), magnified `m` times in the ranks and `m` times again in
the change between rounds, which stops the iteration at `N * tol`: this keeps `eps * m**2`
at least 10**4 times below `tol`. NetworkX first gave another answer at 7 to 9 times
`sqrt(N * tol / eps)`, 1100 to 1600 times this, on a node whose out-weights nearly cancel and
whose two heads lead back to it, where their huge ranks cancel again.
"""
if not tol > 0: # NetworkX never stops: its change between rounds is never below 0
return 0.0
return math.sqrt(tol / np.finfo(float).eps) / 100


def _magnification(A, *vectors):
"""How much dividing by sums that cancel may magnify their rounding, at most.

For values of both signs, the sum of their sizes over the size of their sum: in each node's
out-weights, and in each of `vectors` given. The product of these, as a path in the graph
may pass through every such node. 1 where nothing cancels. A row that sums to 0 dangles,
and is not counted: the caller has left out-weights of both signs, three or more of them,
to NetworkX (`_out_weights_cancel_by_order`), and two add to 0 in either order. It has also
left a vector that sums to 0 to NetworkX (`_check_sums`).
"""

def product(logs):
return math.exp(logs) if logs < 700 else math.inf

logs = 0.0
for v in vectors:
if v is not None and v.reduce(monoid.min).get(0) < 0 < v.reduce(monoid.max).get(0):
total = v.reduce().get(0)
logs += math.log(unary.abs(v).reduce().get(0) / abs(total))
if A.nvals == 0 or A.reduce_scalar(monoid.min).get(0) >= 0:
return product(logs)
low = A.reduce_rowwise(monoid.min).new().select("<", 0).new()
high = A.reduce_rowwise(monoid.max).new().select(">", 0).new()
mixed = binary.pair(low & high).new()
if mixed.nvals == 0:
return product(logs)
sums = A.reduce_rowwise().new(mask=mixed.S)
sizes = unary.abs(A).reduce_rowwise().new(mask=sums.select("!=", 0).new().S)
_, ratios = binary.truediv(sizes & unary.abs(sums)).new().to_coo()
return product(logs + float(np.log(ratios).sum()))


def google_matrix(
G, alpha=0.85, personalization=None, nodelist=None, weight="weight", dangling=None
):
G = to_graph(G, weight=weight, dtype=float)
check_dense_nodelist(G, nodelist)
if weight is not None and _signs(G)[1]:
return _google_matrix_as_networkx(G, alpha, personalization, nodelist, dangling)
p = G.dict_to_vector(personalization, dtype=float, name="personalization")
p = _values_at_nodes(G, personalization, "personalization")
if dangling is not None and nonzero_out_weight_sums(G._A).nvals < len(G):
dangling_weights = G.dict_to_vector(dangling, dtype=float, name="dangling")
dangling_weights = _values_at_nodes(G, dangling, "dangling")
else:
dangling_weights = None
_check_sums("google_matrix", personalization=p, dangling=dangling_weights)
rv = algorithms.google_matrix(
G,
alpha=alpha,
Expand Down
Loading
Loading