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 @@ -283,6 +283,8 @@ graphblas_algorithms.nxapi
│ ├── bellman_ford_path_length
│ ├── negative_edge_cycle
│ └── single_source_bellman_ford_path_length
├── similarity
│ └── simrank_similarity
├── simple_paths
│ └── is_simple_path
├── smetric
Expand Down
2 changes: 2 additions & 0 deletions _nx_graphblas/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@ def get_info():
"s_metric",
"schultz_index",
"score_sequence",
"simrank_similarity",
"single_source_bellman_ford_path_length",
"single_source_shortest_path_length",
"single_target_shortest_path_length",
Expand Down Expand Up @@ -228,6 +229,7 @@ def get_info():
"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.",
"schultz_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.',
"simrank_similarity": 'Left to NetworkX: a graph with an edge "weight" other than 1 (NetworkX reads it, and\nthe dispatcher converts no attribute for this name), more than 5181 nodes (the n by n\nmatrices would pass 2 GiB), an `importance_factor` that is not a float in (-1, 1),\n`max_iterations` that is not an int of at least 1, a `tolerance` that is not a float\nor is negative or NaN, and an unhashable `source` or `target`. A step whose largest\nchange lands within rounding of the convergence threshold is left to NetworkX too, so\nthe step the iteration stops at is always NetworkX\'s.',
"single_source_bellman_ford_path_length": "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.",
"union": "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.",
"volume": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more, or to 2**63 over the most times `S` names one node.",
Expand Down
9 changes: 9 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@
"radius": _ECCENTRICITY_BOUNDS,
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"simrank_similarity": (
'Left to NetworkX: a graph with an edge "weight" other than 1 (NetworkX reads it, and\n'
"the dispatcher converts no attribute for this name), more than 5181 nodes (the n by n\n"
"matrices would pass 2 GiB), an `importance_factor` that is not a float in (-1, 1),\n"
"`max_iterations` that is not an int of at least 1, a `tolerance` that is not a float\n"
"or is negative or NaN, and an unhashable `source` or `target`. A step whose largest\n"
"change lands within rounding of the convergence threshold is left to NetworkX too, so\n"
"the step the iteration stops at is always NetworkX's."
),
"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,
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 @@ -19,6 +19,7 @@
from .reciprocity import *
from .regular import *
from .shortest_paths import *
from .similarity import *
from .simple_paths import *
from .smetric import *
from .structuralholes import *
Expand Down
93 changes: 93 additions & 0 deletions graphblas_algorithms/algorithms/similarity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
from graphblas import Matrix, Vector, agg, binary, monoid, unary
from graphblas.semiring import plus_times

from .exceptions import GraphBlasAlgorithmException

__all__ = ["simrank_similarity"]

# numpy.allclose's relative tolerance, which NetworkX's convergence test leaves at its default.
_RTOL = 1e-5
# A state this full is held as a bitmap or full matrix rather than a sparse one: sparse
# products with that many entries take far more memory and time.
_DENSE_FRACTION = 1 / 32


class AmbiguousConvergence(GraphBlasAlgorithmException):
"""A step lands so near the convergence threshold that rounding could decide it."""


def _dense(M):
M.ss.config["sparsity_control"] = ["bitmap", "full"]
return M


def simrank_similarity(G, importance_factor=0.9, max_iterations=1000, tolerance=1e-4):
"""SimRank by NetworkX's iteration: S = c * P.T @ S @ P with a unit diagonal, from S = I.

P is the adjacency matrix with each column divided by its count (a node's in-degree, a
self-loop included), so a node with no in-edge has 0 for every other node. The iteration
stops at the first step where every entry is within ``tolerance + 1e-5 * |new|`` of the
step before, NetworkX's ``np.allclose(prev, new, atol=tolerance)``. Returns the similarity
matrix, with no entry where it is 0, and the index of the last step taken (NetworkX raises
when that is its last allowed step, even one that converged). `max_iterations` must be at
least 1, ``importance_factor`` in (-1, 1), so that no entry exceeds 1 in size, and
`tolerance` at least 0: np.allclose also takes exactly equal entries as close, which
decides only for a negative or NaN tolerance.

S stays symmetric, so ``P.T @ S @ P`` is ``Y.T @ P`` with ``Y = S @ P``: two products of
the state by the sparse P, and the state stays sparse while few pairs are similar.

The step taken is NetworkX's. Here and in NetworkX each step is within about
``2 * n * 2**-53 / (1 - |c|)`` of the exact iteration (two products whose weights sum to
at most 1, the error of each step shrunk by ``|c|`` in the next), and P is NetworkX's to
the bit. So the convergence test's largest entry here is within four times that of
NetworkX's, and a step whose largest entry lands within ``32 * n * 2**-53 / (1 - |c|)``
of the threshold raises AmbiguousConvergence rather than risk stopping a step apart.
"""
A = G._A
n = A.nrows
identity = Vector.from_scalar(1.0, n, name="ones").diag(name="identity")
if n == 0:
return identity, 0
in_degrees = A.reduce_columnwise(agg.count).new(dtype=float, name="in_degrees")
in_degrees << unary.minv(in_degrees)
P = plus_times(unary.one[float](A) @ in_degrees.diag()).new(name="column_normalized")
c = float(importance_factor)
margin = 32 * n * 2**-53 / (1 - abs(c))
dense = False
new = identity.dup(name="simrank")
for its in range(max_iterations):
prev = new
Y = Matrix(float, n, n, name="half_step")
new = Matrix(float, n, n, name="simrank")
if dense:
_dense(Y)
_dense(new)
Y << plus_times(prev @ P)
new << plus_times(Y.T @ P)
del Y
new *= c
new(identity.S) << identity
if not dense and new.nvals > _DENSE_FRACTION * n * n:
dense = True
_dense(new)
# prev - new, an entry missing from either taken as 0
prev << prev.ewise_union(new, binary.minus, 0.0, 0.0)
largest = max(prev.reduce_scalar(monoid.max).get(), -prev.reduce_scalar(monoid.min).get())
if largest > tolerance + _RTOL + margin:
continue # some entry is off by more than any |new| <= 1 allows
if largest <= tolerance - margin:
break
# Near the threshold: NetworkX's test entry by entry.
prev << unary.abs(prev)
scaled = unary.abs(new).new(name="scaled")
scaled *= _RTOL
prev(binary.minus) << scaled
worst = prev.reduce_scalar(monoid.max).get() - tolerance
if abs(worst) <= margin:
raise AmbiguousConvergence(
f"step {its} is within {margin:.1e} of the convergence threshold"
)
if worst <= 0:
break
return new, its
4 changes: 4 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -410,6 +410,10 @@ class Dispatcher:
negative_edge_cycle = mod.weighted.negative_edge_cycle
single_source_bellman_ford_path_length = mod.weighted.single_source_bellman_ford_path_length

mod = nxapi.similarity
# ====================
simrank_similarity = mod.simrank_similarity

mod = nxapi.simple_paths
# ======================
is_simple_path = mod.is_simple_path
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 @@ -20,6 +20,7 @@
from .reciprocity import *
from .regular import *
from .shortest_paths import *
from .similarity import *
from .simple_paths import *
from .smetric import *
from .structuralholes import *
Expand Down
4 changes: 4 additions & 0 deletions graphblas_algorithms/nxapi/exception.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
import networkx as nx
except ImportError:

class ExceededMaxIterations(Exception):
pass

class NetworkXAlgorithmError(Exception):
pass

Expand Down Expand Up @@ -31,6 +34,7 @@ class PowerIterationFailedConvergence(Exception):

else:
from networkx import (
ExceededMaxIterations,
NetworkXAlgorithmError,
NetworkXError,
NetworkXException,
Expand Down
131 changes: 131 additions & 0 deletions graphblas_algorithms/nxapi/similarity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
import numbers
import operator

import numpy as np
from graphblas import monoid

from graphblas_algorithms import algorithms
from graphblas_algorithms.classes.digraph import to_graph

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

__all__ = ["simrank_similarity"]

# The most bytes the iteration's n by n matrices may take, so 5181 nodes; past it the call is
# declined before anything is converted. Measured on graphs of 3000 to 5792 nodes, dense and
# sparse, they peak at 49 to 70 bytes a pair of nodes, more at some sizes than at larger ones.
_MOST_BYTES = 2 * 2**30
_BYTES_PER_PAIR = 80
# Numbers whose arithmetic with float64 arrays is float64's, as in NetworkX's numpy loop.
_NUMBERS = (int, float, np.integer, np.float16, np.float32, np.float64)


def _number(x):
if not isinstance(x, _NUMBERS):
return None
try:
return float(x)
except OverflowError:
return None


def _weighted(G):
"""Whether `G` has an edge "weight" other than 1, which NetworkX's adjacency matrix reads."""
if hasattr(G, "_adj"):
return any(
not isinstance(w, numbers.Real) or w != 1
for _u, _v, w in G.edges(data="weight", default=1)
)
if getattr(G, "_weight", None) != "weight" or G._A.nvals == 0:
return False
A = G._A
return not (A.reduce_scalar(monoid.min).get() == A.reduce_scalar(monoid.max).get() == 1)


def _rule(bound):
G = bound["G"]
n = len(G)
if n * n * _BYTES_PER_PAIR > _MOST_BYTES:
return (
f"simrank_similarity on {n} nodes would hold more than {_MOST_BYTES / 2**30:g} GiB "
"of n by n matrices; networkx serves it"
)
for name in ("source", "target"):
try:
hash(bound[name])
except TypeError:
# NetworkX looks it up in a list of the nodes.
return f"simrank_similarity with an unhashable {name}; networkx serves it"
try:
max_iterations = operator.index(bound["max_iterations"])
except TypeError:
max_iterations = 0
if max_iterations < 1:
# Below 1 NetworkX's loop does not run and reading its counter raises UnboundLocalError;
# its range() raises TypeError for a number that is not an int.
return "simrank_similarity with max_iterations not an int of at least 1; networkx serves it"
factor = _number(bound["importance_factor"])
if factor is None or not abs(factor) < 1:
return (
"simrank_similarity with an importance_factor that is not a float in (-1, 1); "
"networkx serves it"
)
tolerance = _number(bound["tolerance"])
if tolerance is None:
return "simrank_similarity with a tolerance that is not a float; networkx serves it"
if not tolerance >= 0:
# np.allclose also takes exactly equal entries as close, which decides only when the
# tolerance is negative or NaN; which entries NetworkX finds equal to the bit is its
# own rounding's.
return "simrank_similarity with a negative or NaN tolerance; networkx serves it"
if _weighted(G):
# The dispatcher converts no edge attribute for this name, as NetworkX declares none.
return (
'simrank_similarity on a graph with an edge "weight" other than 1, which NetworkX '
"reads; networkx serves it"
)
return None


@can_run(_rule)
def simrank_similarity(
G, source=None, target=None, importance_factor=0.9, max_iterations=1000, tolerance=1e-4
):
# Again here: a direct call does not pass through `can_run`.
bound = {
"G": G,
"source": source,
"target": target,
"importance_factor": importance_factor,
"max_iterations": max_iterations,
"tolerance": tolerance,
}
if (reason := _rule(bound)) is not None:
raise NotImplementedError(reason)
G = to_graph(G)
key_to_id = G._key_to_id
if source is not None and source not in key_to_id:
raise NodeNotFound(f"Source node {source} not in G")
if target is not None and target not in key_to_id:
raise NodeNotFound(f"Target node {target} not in G")
try:
S, its = algorithms.simrank_similarity(
G, float(importance_factor), operator.index(max_iterations), float(tolerance)
)
except algorithms.exceptions.GraphBlasAlgorithmException as e:
raise NotImplementedError(
f"simrank_similarity where {e.args[0]}, so rounding could decide the step NetworkX "
"stops at; networkx serves it"
) from e
if its + 1 == max_iterations:
# NetworkX raises when its last allowed step is taken, even one that converged.
raise ExceededMaxIterations(f"simrank did not converge after {max_iterations} iterations.")
keys = list(key_to_id)
if source is not None:
row = key_to_id[source]
if target is not None:
return float(S[row, key_to_id[target]].new().get(0.0))
return dict(zip(keys, S[row, :].new().to_dense(fill_value=0.0).tolist(), strict=True))
rows = S.to_dense(fill_value=0.0).tolist()
return {key: dict(zip(keys, row, strict=True)) for key, row in zip(keys, rows, strict=True)}
Loading
Loading