From e30c96cee6e8ff34a26fa19d4168803f304a5fba Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Wed, 2 Dec 2026 20:27:14 -0600 Subject: [PATCH] Add simrank_similarity NetworkX iterates S = c * P.T @ S @ P from the identity and sets the diagonal back to 1 at each step, where P is the adjacency matrix with each column divided by its count (the in-degree, a self-loop included), so a node with no in-edge is 0 to every other node. It takes dense n by n products; here P stays sparse, and so does S while few pairs are similar, as on a tree. S stays symmetric, so the step is two products by P: Y = S @ P, then Y.T @ P. The iteration stops where NetworkX's does: at the first step where every entry is within tolerance + 1e-5 * |new| of the step before, its np.allclose test. ExceededMaxIterations is raised when that step is the last one allowed, as NetworkX raises it, even after converging there. Each step here and in NetworkX is within rounding of the exact one, so the largest change is checked against the threshold with a margin for that rounding, and a step inside the margin is left to NetworkX. Left to NetworkX: an edge "weight" other than 1, which NetworkX's adjacency matrix reads but the dispatcher does not convert for this name; more than 5181 nodes, past which the n by n matrices would pass 2 GiB; an importance_factor that is not a float in (-1, 1); max_iterations that is not an int of at least 1, where NetworkX raises UnboundLocalError or TypeError; a tolerance that is not a float, or is negative or NaN, where np.allclose's taking exactly equal entries as close decides; and an unhashable source or target, which NetworkX looks up in a list. --- README.md | 2 + _nx_graphblas/__init__.py | 2 + _nx_graphblas/core.py | 9 + graphblas_algorithms/algorithms/__init__.py | 1 + graphblas_algorithms/algorithms/similarity.py | 93 ++++ graphblas_algorithms/interface.py | 4 + graphblas_algorithms/nxapi/__init__.py | 1 + graphblas_algorithms/nxapi/exception.py | 4 + graphblas_algorithms/nxapi/similarity.py | 131 ++++++ .../nxapi/tests/test_simrank.py | 442 ++++++++++++++++++ graphblas_algorithms/tests/_dispatched.py | 1 + 11 files changed, 690 insertions(+) create mode 100644 graphblas_algorithms/algorithms/similarity.py create mode 100644 graphblas_algorithms/nxapi/similarity.py create mode 100644 graphblas_algorithms/nxapi/tests/test_simrank.py diff --git a/README.md b/README.md index 1bc06b5..abab1ce 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..70e1dc7 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -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", @@ -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.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..df8c5f5 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -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, diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..0c027ac 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -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 * diff --git a/graphblas_algorithms/algorithms/similarity.py b/graphblas_algorithms/algorithms/similarity.py new file mode 100644 index 0000000..6ce4b80 --- /dev/null +++ b/graphblas_algorithms/algorithms/similarity.py @@ -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 diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..90a861a 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -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 diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..abf3bcc 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -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 * diff --git a/graphblas_algorithms/nxapi/exception.py b/graphblas_algorithms/nxapi/exception.py index f4a05df..e8f1a0c 100644 --- a/graphblas_algorithms/nxapi/exception.py +++ b/graphblas_algorithms/nxapi/exception.py @@ -2,6 +2,9 @@ import networkx as nx except ImportError: + class ExceededMaxIterations(Exception): + pass + class NetworkXAlgorithmError(Exception): pass @@ -31,6 +34,7 @@ class PowerIterationFailedConvergence(Exception): else: from networkx import ( + ExceededMaxIterations, NetworkXAlgorithmError, NetworkXError, NetworkXException, diff --git a/graphblas_algorithms/nxapi/similarity.py b/graphblas_algorithms/nxapi/similarity.py new file mode 100644 index 0000000..e4247d9 --- /dev/null +++ b/graphblas_algorithms/nxapi/similarity.py @@ -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)} diff --git a/graphblas_algorithms/nxapi/tests/test_simrank.py b/graphblas_algorithms/nxapi/tests/test_simrank.py new file mode 100644 index 0000000..bd2b67b --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_simrank.py @@ -0,0 +1,442 @@ +"""simrank_similarity against NetworkX. + +The keys and their order, the value types, the errors and their messages, and the step the +iteration stops at must be NetworkX's exactly. The values agree within 1e-12: every entry is at +most 1, and each implementation is within ``2 * n * 2**-53 / (1 - |c|)`` of the exact iteration +(about 2e-13 for the 40 nodes and factor 0.95 of the random graphs here). The step is pinned by +NetworkX's own rule: it raises ExceededMaxIterations when the step it stops at is its last +allowed one, so with `k` the step NetworkX stops at, ``max_iterations=k + 1`` raises and +``k + 2`` returns, and the same must hold here. Each call is made by name with +``backend="graphblas"`` and with this backend first in NetworkX's priority, where a decline must +reach NetworkX's own answer. +""" + +import math +from contextlib import contextmanager +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga + +pytestmark = pytest.mark.filterwarnings( + "ignore:Note. conversions to backend graphs", + "ignore:One of rtol or atol is not valid", + "ignore:invalid value encountered", +) + +TOLERANCE = 1e-12 + + +@contextmanager +def graphblas_first(): + """Put this backend first for algorithms; a decline goes to NetworkX.""" + config = nx.config + saved = list(config.backend_priority.algos), config.fallback_to_nx + config.backend_priority.algos = ["graphblas"] + config.fallback_to_nx = False + try: + yield + finally: + config.backend_priority.algos, config.fallback_to_nx = saved + + +def call(G, backend=None, **kwargs): + """The answer of one call: ("value", result) or ("error", type, message).""" + if backend is not None: + kwargs["backend"] = backend + try: + return ("value", nx.simrank_similarity(G, **kwargs)) + except Exception as e: + return ("error", type(e), str(e)) + + +def assert_close(got, expected): + assert type(got) is type(expected) + if isinstance(expected, dict): + assert list(got) == list(expected) + for key, value in expected.items(): + assert_close(got[key], value) + else: + assert got == pytest.approx(expected, rel=0, abs=TOLERANCE) + + +def assert_same(got, expected): + if expected[0] == "value" and got[0] == "value": + assert_close(got[1], expected[1]) + else: + assert got == expected + + +def check(G, **kwargs): + """Served by this backend, with NetworkX's answer or error, both ways.""" + expected = call(G, "networkx", **kwargs) + got = call(G, "graphblas", **kwargs) + if got[0] == "error": + assert got[1] is not NotImplementedError, got + assert_same(got, expected) + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same(call(G, **kwargs), expected) + return expected + + +def left_to_networkx(G, reason, **kwargs): + """Declined: the backend says why, and NetworkX's answer (or error) comes back.""" + from graphblas_algorithms.interface import Dispatcher + + expected = call(G, "networkx", **kwargs) + declined = Dispatcher.can_run("simrank_similarity", (G,), kwargs) + if declined is True: # declined once converted + with pytest.raises(NotImplementedError) as info: + nx.simrank_similarity(G, backend="graphblas", **kwargs) + declined = str(info.value.__cause__) + assert reason in declined + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same(call(G, **kwargs), expected) + return expected + + +def stop_step(G, **kwargs): + """The step NetworkX's iteration stops at, from where its ExceededMaxIterations begins.""" + if call(G, "networkx", max_iterations=1000, **kwargs)[0] == "error": + return None + lo, hi = 1, 1000 # raises at lo, returns at hi; lo is k + 1 once they meet + if call(G, "networkx", max_iterations=lo, **kwargs)[0] == "value": + return -1 + while hi - lo > 1: + mid = (lo + hi) // 2 + if call(G, "networkx", max_iterations=mid, **kwargs)[0] == "error": + lo = mid + else: + hi = mid + return lo - 1 + + +def check_stop_step(G, **kwargs): + """The backend stops at NetworkX's step: it raises at ``k + 1`` and returns at ``k + 2``.""" + k = stop_step(G, **kwargs) + assert k is not None + assert k >= 0 + raised = check(G, max_iterations=k + 1, **kwargs) + assert raised == ( + "error", + nx.ExceededMaxIterations, + f"simrank did not converge after {k + 1} iterations.", + ) + assert check(G, max_iterations=k + 2, **kwargs)[0] == "value" + return k + + +def random_case(seed): + """A random graph and the keywords of one call. + + Directed on odd seeds. Labels by seed: shuffled ints, strings or tuples. Edges carry no + data, a "weight" of 1, 1.0 or True, or another attribute, which NetworkX does not read. + Some nodes are isolated, some edges are self-loops, and a directed graph has nodes with no + in-edge. The call asks for every pair, one source, one pair, or a target alone (which + NetworkX checks and then ignores), sometimes of a node not in the graph, with an + importance factor and a tolerance from a spread of values. + """ + rng = np.random.default_rng(seed) + directed = seed % 2 == 1 + n = int(rng.integers(1, 41)) + p = float(rng.choice([0.02, 0.05, 0.1, 0.2, 0.4])) + labels = [ + list(rng.permutation(n).tolist()), + [f"n{i}" for i in rng.permutation(n).tolist()], + [(i % 3, f"x{i}") for i in rng.permutation(n).tolist()], + ][seed // 2 % 3] + G = nx.DiGraph() if directed else nx.Graph() + G.add_nodes_from(labels) + data = seed // 6 % 3 + for i, u in enumerate(labels): + for j, v in enumerate(labels): + if not directed and j < i: + continue + if rng.random() >= (p / 4 if i == j else p): + continue + if data == 0: + G.add_edge(u, v) + elif data == 1: + G.add_edge(u, v, weight=[1, 1.0, True][int(rng.integers(3))]) + else: + G.add_edge(u, v, w=float(rng.uniform(0, 5))) + kwargs = { + "importance_factor": [0.9, 0.9, 0.5, 0.8, -0.5, 0.95, 0.3, 0.0][int(rng.integers(8))], + "tolerance": [1e-4, 1e-4, 1e-2, 1e-6, 0.05][int(rng.integers(5))], + } + form = ["all", "source", "pair", "target"][int(rng.integers(4))] + missing = "missing" if rng.random() < 0.08 else None + + def node(): + return missing if missing is not None else labels[int(rng.integers(n))] + + if form in ("source", "pair"): + kwargs["source"] = node() + if form in ("pair", "target"): + kwargs["target"] = node() + return G, kwargs + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs(seed): + G, kwargs = random_case(seed) + expected = check(G, **kwargs) + if expected[0] == "error": + assert expected[1] is nx.NodeNotFound + return + factors = {key: kwargs[key] for key in ("importance_factor", "tolerance")} + check_stop_step(G, **factors) + + +@pytest.mark.parametrize( + "G", + [ + nx.convert_node_labels_to_integers(nx.grid_2d_graph(15, 15)), + nx.bfs_tree(nx.random_labeled_tree(300, seed=3), 0), + nx.gnm_random_graph(300, 1200, seed=4), + nx.gnm_random_graph(250, 600, seed=5, directed=True), + nx.gnm_random_graph(400, 300, seed=6), + nx.les_miserables_graph().to_directed(as_view=False), + ], + ids=["grid", "tree", "gnm", "directed", "sparse", "les_miserables"], +) +def test_larger_graphs(G): + if nx.get_edge_attributes(G, "weight"): + H = G.__class__() + H.add_nodes_from(G) + H.add_edges_from(G.edges) + G = H + k = check_stop_step(G) + assert k > 2 + check(G) + node = next(iter(G)) + check(G, source=node) + check(G, source=node, target=list(G)[-1]) + + +def test_docstring_examples(): + G = nx.cycle_graph(2) + assert check(G) == ("value", {0: {0: 1.0, 1: 0.0}, 1: {0: 0.0, 1: 1.0}}) + assert check(G, source=0) == ("value", {0: 1.0, 1: 0.0}) + assert check(G, source=0, target=0) == ("value", 1.0) + + +def test_directed_in_neighbors(): + # 4 has no in-edge, so it is 0 to every other node; 1 and 2 share their in-neighbor 0. + G = nx.DiGraph([(0, 1), (0, 2), (1, 3), (2, 3), (4, 0)]) + status, S = check(G) + assert status == "value" + assert all(S[4][v] == 0 for v in G if v != 4) + assert S[1][2] == pytest.approx(0.9) + check_stop_step(G) + check_stop_step(G.reverse()) + + +def test_self_loops_count_as_in_edges(): + G = nx.Graph([(0, 0), (0, 1), (1, 2), (2, 2), (3, 3)]) + status, S = check(G) + assert S[0][2] != nx.simrank_similarity(nx.Graph([(0, 1), (1, 2)]), backend="networkx")[0][2] + check_stop_step(G) + check_stop_step(nx.DiGraph([(0, 0), (0, 1), (1, 1), (1, 2)])) + + +def test_isolated_nodes(): + G = nx.empty_graph(5) + assert check(G) == ("value", {u: {v: float(u == v) for v in G} for u in G}) + assert check(G, max_iterations=1)[1] is nx.ExceededMaxIterations + assert check(G, max_iterations=2)[0] == "value" + + +def test_null_graph(): + G = nx.Graph() + assert check(G) == ("value", {}) + assert check(G, max_iterations=1) == ( + "error", + nx.ExceededMaxIterations, + "simrank did not converge after 1 iterations.", + ) + assert check(G, source=0) == ("error", nx.NodeNotFound, "Source node 0 not in G") + assert check(nx.DiGraph(), target=0)[1] is nx.NodeNotFound + + +def test_nodes_not_in_graph(): + G = nx.path_graph(4) + assert check(G, source=9) == ("error", nx.NodeNotFound, "Source node 9 not in G") + assert check(G, source=0, target=9) == ("error", nx.NodeNotFound, "Target node 9 not in G") + assert check(G, target=9) == ("error", nx.NodeNotFound, "Target node 9 not in G") + assert check(G, source=9, target=9)[2] == "Source node 9 not in G" + assert check(G, source="0")[2] == "Source node 0 not in G" + # NetworkX checks the nodes first, whatever else is asked + assert check(G, source=9, tolerance=0.0, max_iterations=3)[1] is nx.NodeNotFound + + +def test_equal_node_keys(): + # NetworkX finds a node by equality, as a dict does. + G = nx.path_graph(4) + for source in (1.0, True, np.int64(1), np.float64(1.0)): + assert check(G, source=source)[1] == check(G, source=1)[1] + assert check(G, source=0, target=source)[0] == "value" + + +def test_iteration_limit(): + G = nx.cycle_graph(5) + for m in (1, 2, 3): + assert check(G, max_iterations=m) == ( + "error", + nx.ExceededMaxIterations, + f"simrank did not converge after {m} iterations.", + ) + assert check(G, tolerance=0.0, max_iterations=50)[1] is nx.ExceededMaxIterations + assert check(G, tolerance=float("inf"))[0] == "value" + check_stop_step(G, tolerance=0.0) + check_stop_step(nx.path_graph(4), tolerance=0.0) + assert check(G, max_iterations=np.int64(40))[0] == "value" + assert check(G, max_iterations=True)[1] is nx.ExceededMaxIterations + for kwargs in ({}, {"importance_factor": 0.5}, {"tolerance": 1e-8}, {"tolerance": 0.3}): + check_stop_step(G, **kwargs) + + +def test_factors(): + G = nx.Graph([(0, 1), (0, 2), (1, 3), (2, 3), (3, 4), (5, 5)]) + for c in (0.0, 0.1, 0.5, 0.99, -0.5, -0.9, np.float32(0.6), 1 // 2): + check_stop_step(G, importance_factor=c) + check(G, importance_factor=0.999, max_iterations=10000) + check_stop_step(G, tolerance=np.float32(1e-3)) + check_stop_step(G, tolerance=1) + + +@pytest.mark.parametrize("weight", [1, 1.0, True, np.float64(1.0), np.int8(1), Fraction(1)]) +def test_unit_weights_served(weight): + G = nx.Graph([(0, 1), (1, 2), (2, 3)]) + nx.set_edge_attributes(G, weight, "weight") + check_stop_step(G) + + +@pytest.mark.parametrize("weight", [2, 0.5, 0, -1, float("nan"), float("inf"), "x", None]) +def test_weights_left_to_networkx(weight): + G = nx.Graph([(0, 1), (1, 2), (2, 3)]) + G.edges[1, 2]["weight"] = weight + left_to_networkx(G, 'an edge "weight" other than 1') + left_to_networkx(G.to_directed(), 'an edge "weight" other than 1', source=0) + + +def test_other_attributes_ignored(): + G = nx.Graph([(0, 1, {"w": 5}), (1, 2, {"length": 0}), (2, 3)]) + check_stop_step(G) + + +@pytest.mark.parametrize( + ("kwargs", "reason"), + [ + ({"max_iterations": 0}, "max_iterations not an int of at least 1"), + ({"max_iterations": -1}, "max_iterations not an int of at least 1"), + ({"max_iterations": 1.5}, "max_iterations not an int of at least 1"), + ({"max_iterations": "3"}, "max_iterations not an int of at least 1"), + ({"importance_factor": 1}, "not a float in (-1, 1)"), + ({"importance_factor": 1.5, "max_iterations": 20}, "not a float in (-1, 1)"), + ({"importance_factor": -1.0, "max_iterations": 20}, "not a float in (-1, 1)"), + ({"importance_factor": float("nan"), "max_iterations": 5}, "not a float in (-1, 1)"), + ({"importance_factor": Fraction(1, 2)}, "not a float in (-1, 1)"), + ({"importance_factor": np.longdouble(0.9)}, "not a float in (-1, 1)"), + ({"tolerance": "x"}, "a tolerance that is not a float"), + ({"tolerance": 10**400}, "a tolerance that is not a float"), + ({"tolerance": np.longdouble(1e-4)}, "a tolerance that is not a float"), + ({"tolerance": -1.0}, "a negative or NaN tolerance"), + ({"tolerance": -1e-6}, "a negative or NaN tolerance"), + ({"tolerance": float("nan")}, "a negative or NaN tolerance"), + ({"tolerance": -float("inf")}, "a negative or NaN tolerance"), + ({"tolerance": np.float32("nan")}, "a negative or NaN tolerance"), + ({"tolerance": -1, "max_iterations": 7}, "a negative or NaN tolerance"), + ({"source": [1]}, "an unhashable source"), + ({"source": np.array([1])}, "an unhashable source"), + ({"source": 0, "target": [9]}, "an unhashable target"), + ], +) +def test_left_to_networkx(kwargs, reason): + left_to_networkx(nx.path_graph(4), reason, **kwargs) + + +def test_memory_bound(): + from graphblas_algorithms.interface import Dispatcher + from graphblas_algorithms.nxapi import similarity + + assert Dispatcher.can_run("simrank_similarity", (nx.empty_graph(5181),), {}) is True + G = nx.empty_graph(5182) + declined = Dispatcher.can_run("simrank_similarity", (G,), {}) + assert "on 5182 nodes would hold more than 2 GiB" in declined + with pytest.raises(NotImplementedError, match="on 5182 nodes"): + similarity.simrank_similarity(G) + assert similarity._MOST_BYTES // similarity._BYTES_PER_PAIR < 5182**2 + + +def test_multigraph_left_to_networkx(): + G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)]) + left_to_networkx(G, "multigraph") + + +def test_near_threshold_left_to_networkx(): + """A step whose largest change is the tolerance, to the bit, is left to NetworkX.""" + G = nx.karate_club_graph() + G = nx.Graph(G.edges) + A = nx.to_numpy_array(G) + s = A.sum(axis=0) + s[s == 0] = 1 + A /= s + prev = np.eye(len(G)) + for _ in range(5): + new = 0.9 * ((A.T @ prev) @ A) + np.fill_diagonal(new, 1.0) + worst = float(np.max(np.abs(prev - new) - 1e-5 * np.abs(new))) + prev = new + # The margin for rounding is 32 * n * 2**-53 / (1 - c), about 1.2e-12 here. + for tolerance in (worst, worst + 1e-13, worst - 1e-13): + expected = left_to_networkx(G, "within", tolerance=tolerance) + assert expected[0] == "value" + # Just off the threshold either way, the step is clear and this backend serves it. + check_stop_step(G, tolerance=worst * (1 + 1e-6)) + check_stop_step(G, tolerance=worst * (1 - 1e-6)) + + +def test_backend_graphs(): + from graphblas_algorithms import nxapi + + G = nx.Graph([(0, 1), (1, 2), (2, 3), (3, 3)]) + expected = nx.simrank_similarity(G, backend="networkx") + for H in (ga.Graph.from_networkx(G), ga.Graph.from_networkx(G, weight="weight")): + assert_close(nxapi.simrank_similarity(H), expected) + nx.set_edge_attributes(G, 1, "weight") + assert_close(nxapi.simrank_similarity(ga.Graph.from_networkx(G, weight="weight")), expected) + G.edges[1, 2]["weight"] = 2 + with pytest.raises(NotImplementedError, match='an edge "weight" other than 1'): + nxapi.simrank_similarity(ga.Graph.from_networkx(G, weight="weight")) + # A conversion whose values came from another attribute holds no "weight": each edge is 1. + assert_close(nxapi.simrank_similarity(ga.Graph.from_networkx(G, weight="other")), expected) + + +def test_values_exact_types(): + G = nx.Graph([("a", "b"), ("b", "c")]) + status, S = check(G) + assert all(type(v) is float for row in S.values() for v in row.values()) + assert type(check(G, source="a", target="c")[1]) is float + assert math.isclose(S["a"]["c"], 0.9) + + +def test_negative_or_nan_tolerance_left_to_networkx(): + """np.allclose takes exactly equal entries as close whatever the tolerance. + + With a negative or NaN tolerance only they can be, so NetworkX stops where its iteration + reaches a fixed point to the bit, as on a path, and otherwise runs out of iterations. + """ + reason = "a negative or NaN tolerance" + for tolerance in (-1.0, float("nan"), -float("inf")): + assert left_to_networkx(nx.path_graph(4), reason, tolerance=tolerance)[0] == "value" + expected = left_to_networkx( + nx.cycle_graph(5), reason, tolerance=tolerance, max_iterations=7 + ) + assert expected[1] is nx.ExceededMaxIterations + left_to_networkx(nx.path_graph(4), reason, tolerance=-1e-6, source=0, target=2) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..4b77c83 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -196,6 +196,7 @@ def call_args(kind, args): "s_metric": ("undirected", ()), "schultz_index": ("undirected", ()), "score_sequence": ("tournament", ()), + "simrank_similarity": ("plain", ()), "single_source_bellman_ford_path_length": ("undirected", (0,)), "single_source_shortest_path_length": ("undirected", (0,)), "single_target_shortest_path_length": ("undirected", (0,)),