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
18 changes: 18 additions & 0 deletions graphblas_algorithms/classes/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,12 +81,30 @@ def from_networkx(cls, G, weight=None, dtype=None):
rv._key_to_id = {k: i for i, k in enumerate(G)}
if rv._key_to_id:
rv._A = gb.io.from_networkx(G, nodelist=rv._key_to_id, weight=weight, dtype=dtype)
if weight is not None and not G.is_directed():
_put_self_loop_weights(rv._A, G, rv._key_to_id, weight)
else:
rv._A = Matrix(dtype if dtype is not None else float)
rv._weight = weight
return rv


def _put_self_loop_weights(A, G, key_to_id, weight):
"""Store each self-loop's own weight in `A`, the matrix of the undirected graph `G`.

NetworkX's `to_scipy_sparse_array` adds each edge in both directions and then each
self-loop's weight negated, so a self-loop's entry is `w + w - w`: NaN for inf or -inf,
and inf where `w + w` overflows.
"""
import networkx as nx

loops = [(key_to_id[u], w) for u, _, w in nx.selfloop_edges(G, data=weight, default=1)]
if loops:
ids, weights = zip(*loops, strict=True)
D = Matrix.from_coo(ids, ids, weights, dtype=A.dtype, nrows=A.nrows, ncols=A.ncols)
A(D.S) << D


##############
# Properties #
##############
Expand Down
86 changes: 86 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,82 @@ def _is_graph(obj):
)


# NetworkX builds these names' answers from `to_scipy_sparse_array`, whose entry for an
# undirected self-loop weighing `w` is `w + w - w`, where a conversion here stores `w`.
_READS_SUMMED_SELF_LOOPS = frozenset(
{
"adjacency_matrix",
"hits",
"laplacian_matrix",
"modularity_matrix",
"normalized_laplacian_matrix",
"pagerank",
}
)


def _summed_self_loop(graph, weight, dtype=None):
"""A self-loop weight `w` of the undirected NetworkX `graph` for which `w + w - w` is not `w`.

That is inf or -inf, which give NaN, or a float past half the largest of the type NetworkX
sums in, `dtype` if given, which gives inf. None if there is no such weight. A conversion
cached for `weight` holds each self-loop's own weight on its diagonal, so it answers, and
keeps the answer for as long as it is the cached conversion; else the graph is read.
"""
import numpy as np

from .classes import Graph

if weight is None or graph.is_directed() or not hasattr(graph, "_adj"):
return None
try:
sums_in = None if dtype is None else np.dtype(dtype)
except TypeError:
sums_in = None
if sums_in is not None and sums_in.kind != "f":
sums_in = None
cache = getattr(graph, "__networkx_cache__", None)
converted = cache.get("backends", {}).get("graphblas", {}) if isinstance(cache, dict) else {}
for H in converted.values():
if isinstance(H, Graph) and not H.is_directed() and H._weight == weight:
memo = H.__dict__.setdefault("_summed_self_loops", {})
key = None if sums_in is None else sums_in.str
if key not in memo:
memo[key] = _summed_on_diagonal(H._A, sums_in)
return memo[key]
return _summed_in_loops(graph, weight, sums_in)


def _summed_on_diagonal(A, sums_in):
"""A value on `A`'s diagonal for which `w + w - w` is not `w` in `sums_in`, or `A`'s type."""
import numpy as np

kind = sums_in if sums_in is not None else A.dtype.np_type
if kind.kind != "f":
return None
_, values = A.diag().to_coo()
bad = np.isinf(values) | (np.abs(values) > np.finfo(kind).max / 2)
return values[bad][0].item() if bad.any() else None


def _summed_in_loops(graph, weight, sums_in):
"""As `_summed_on_diagonal`, from `graph`'s self-loops, each in `sums_in` or its own type."""
import math

import networkx as nx
import numpy as np

halves = {} # half the largest value of each float type met
for _, _, w in nx.selfloop_edges(graph, data=weight, default=1):
if isinstance(w, float | np.floating):
kind = sums_in or type(w)
if kind not in halves:
halves[kind] = np.finfo(kind).max / 2
if math.isinf(w) or abs(w) > halves[kind]:
return w
return None


def _edge_value_problem(graph, attr):
"""Why the values of `attr` would not come back from a matrix as they were given, or None.

Expand Down Expand Up @@ -574,6 +650,16 @@ def can_run(name, args, kwargs):
return f"{reason}; networkx serves it"

bound = _bound_args(name, args, kwargs)
if name in _READS_SUMMED_SELF_LOOPS:
# `hits` takes no weight and reads "weight".
weight = "weight" if bound is None else bound.get("weight", "weight")
dtype = None if bound is None else bound.get("dtype")
for graph in graphs:
if (w := _summed_self_loop(graph, weight, dtype)) is not None:
return (
f"NetworkX's {name} reads a self-loop weighing {w} as "
f"{w} + {w} - {w}; networkx serves it"
)
if bound is None:
return True
for parameter in declared.attribute_parameters:
Expand Down
246 changes: 246 additions & 0 deletions graphblas_algorithms/tests/test_self_loops.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,246 @@
"""An undirected self-loop's weight, as NetworkX reads it, in the conversion and the answers."""

import math

import networkx as nx
import numpy as np
import pytest

from graphblas_algorithms import Graph
from graphblas_algorithms.interface import Dispatcher

_NX_VERSION = tuple(int(x) for x in nx.__version__.split(".")[:2])

# NetworkX's `to_scipy_sparse_array` stores an undirected self-loop weighing `w` as
# `w + w - w`, which is not `w` for these, while NetworkX's loops read `w` itself.
SUMMED = [math.inf, -math.inf, 1e308, np.float32(3e38)]
WEIGHTS = [*SUMMED, math.nan, 0.1, 2.0]


def square(w):
"""Four nodes, each pair joined, an isolated node, and a self-loop on 0 weighing `w`."""
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (1, 3)]
G = nx.Graph()
G.add_weighted_edges_from((u, v, type(w)(i + 2)) for i, (u, v) in enumerate(edges))
G.add_node(4)
G.add_edge(0, 0, weight=w)
return G


VIEWS = {
"graph": lambda G: G,
"subgraph view": lambda G: G.subgraph(list(G)),
"to_undirected view": lambda G: nx.DiGraph(G).to_undirected(as_view=True),
}


def ids(value):
return f"{type(value).__name__}({value})"


@pytest.mark.parametrize("w", WEIGHTS, ids=ids)
@pytest.mark.parametrize("view", sorted(VIEWS))
def test_a_conversion_holds_each_self_loops_own_weight(w, view):
G = square(w)
if type(w) is float:
G.add_edge(2, 2) # no weight: NetworkX reads 1
A = Graph.from_networkx(VIEWS[view](G), weight="weight")._A
[value, *one] = A.diag().to_coo()[1].tolist()
assert value == w or (math.isnan(value) and math.isnan(w))
assert one == ([1] if type(w) is float else [])
assert A.dtype.np_type == np.asarray(w).dtype


def plain(x):
"""A result as nested lists of numbers and keys, to compare with `same`."""
if hasattr(x, "to_networkx") and not isinstance(x, nx.Graph):
x = x.to_networkx()
if isinstance(x, nx.Graph):
return [sorted(x), sorted((u, v, plain(d)) for u, v, d in x.edges(data=True))]
if hasattr(x, "toarray"):
x = x.toarray()
if isinstance(x, np.ndarray):
return x.tolist()
if hasattr(x, "items"):
return sorted((k, plain(v)) for k, v in x.items())
if isinstance(x, tuple | list):
return [plain(v) for v in x]
if hasattr(x, "__next__"):
return plain(list(x))
return x


def same(a, b):
if isinstance(a, list) and isinstance(b, list):
return len(a) == len(b) and all(same(x, y) for x, y in zip(a, b, strict=True))
if isinstance(a, tuple) and isinstance(b, tuple):
return same(list(a), list(b))
if isinstance(a, float | np.floating | int) and isinstance(b, float | np.floating | int):
# Weights scaled by 1e308 meet the subnormals, where NetworkX's clustering gives 0.
close = math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-300)
return close or a == b or (math.isnan(a) and math.isnan(b))
return a == b


# Names that read the self-loop's weight: NetworkX's loops read it as it is, and the names whose
# NetworkX answer is built from `to_scipy_sparse_array` are declined.
CALLS = {
"adjacency_matrix": nx.adjacency_matrix,
"all_pairs_bellman_ford_path_length": nx.all_pairs_bellman_ford_path_length,
"closeness_centrality": lambda G: nx.closeness_centrality(G, distance="weight"),
"clustering": lambda G: nx.clustering(G, weight="weight"),
"compose": lambda G: nx.compose(G, nx.Graph([(5, 6)])),
"disjoint_union": lambda G: nx.disjoint_union(G, nx.Graph([(5, 6)])),
"ego_graph": lambda G: nx.ego_graph(G, 0),
"floyd_warshall": nx.floyd_warshall,
"floyd_warshall_numpy": nx.floyd_warshall_numpy,
"google_matrix": nx.google_matrix,
"laplacian_matrix": nx.laplacian_matrix,
"modularity_matrix": lambda G: nx.modularity_matrix(G, weight="weight"),
"negative_edge_cycle": nx.negative_edge_cycle,
"normalized_laplacian_matrix": nx.normalized_laplacian_matrix,
"pagerank": nx.pagerank,
"normalized_cut_size": lambda G: nx.normalized_cut_size(G, [0, 1], weight="weight"),
"union": lambda G: nx.union(G, nx.Graph([(5, 6)])),
"volume": lambda G: nx.volume(G, [0, 1], weight="weight"),
}
# Differences in the kernels, whatever a self-loop weighs: left to separate changes. NetworkX's
# negative_edge_cycle adds a node, which a view refuses.
# With a NaN weight, NetworkX's weighted clustering scales by a maximum that depends on the
# order it reads the edges in.
KERNELS = {("google_matrix", "nan"), ("modularity_matrix", "nan"), ("clustering", "nan")}
KERNELS |= {("negative_edge_cycle", view) for view in VIEWS if view != "graph"}
DECLINED = {
"adjacency_matrix",
"hits",
"laplacian_matrix",
"modularity_matrix",
"normalized_laplacian_matrix",
"pagerank",
}


def answer(f, G):
try:
return plain(f(G))
except Exception as exc:
return type(exc).__name__


@pytest.mark.parametrize("w", [*SUMMED[:3], math.nan, 0.1], ids=ids)
@pytest.mark.parametrize("view", sorted(VIEWS))
@pytest.mark.parametrize("name", sorted(CALLS))
def test_names_answer_as_networkx_reads_a_self_loop(name, view, w):
if (name, str(w)) in KERNELS or (name, view) in KERNELS:
pytest.skip("a difference in the kernel")
if name.startswith("floyd_warshall") and _NX_VERSION < (3, 7) and (w < 0 or math.isnan(w)):
pytest.skip("NetworkX 3.6.1's Floyd-Warshall reads self-loops otherwise, directed too")
G = VIEWS[view](square(w))
want = answer(CALLS[name], G)
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
got = answer(CALLS[name], VIEWS[view](square(w)))
assert same(want, got), (want, got)
served = Dispatcher.can_run(name, (G,), {"weight": "weight"})
assert (served is True) == (name not in DECLINED or w not in SUMMED), served


@pytest.mark.parametrize("w", WEIGHTS, ids=ids)
@pytest.mark.parametrize("name", sorted(DECLINED))
def test_names_built_from_networkx_summed_matrix_are_declined(name, w):
"""Where NetworkX's matrix holds another value than the self-loop's own weight."""
kwargs = {} if name == "hits" else {"weight": "weight"}
served = Dispatcher.can_run(name, (square(w),), kwargs)
assert (served is True) == (w not in SUMMED), served
D = nx.DiGraph(square(w))
assert Dispatcher.can_run(name, (D,), kwargs) is True # a directed graph is not summed


def test_the_check_is_kept_with_the_cached_conversion():
G = square(2.0)
assert Dispatcher.can_run("pagerank", (G,), {}) is True # no conversion yet: G is read
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
nx.pagerank(G)
[H] = G.__networkx_cache__["backends"]["graphblas"].values()
assert Dispatcher.can_run("pagerank", (G,), {}) is True
assert H._summed_self_loops == {None: None}
G.add_edge(1, 1, weight=math.inf) # NetworkX empties the cache
assert isinstance(Dispatcher.can_run("pagerank", (G,), {}), str)


@pytest.mark.parametrize("view", ["subgraph view", "to_undirected view"])
def test_a_view_is_checked_against_its_own_conversion(view):
"""A view's cache outlives a change to its graph: the check follows the conversion."""
G = square(2.0)
root = G if view == "subgraph view" else nx.DiGraph(G)
V = G.subgraph(list(G)) if view == "subgraph view" else root.to_undirected(as_view=True)
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
nx.adjacency_matrix(V)
root.add_edge(1, 1, weight=math.inf)
want = nx.adjacency_matrix(V, backend="networkx").toarray().tolist()
got = nx.adjacency_matrix(V).toarray().tolist()
# Dropped where stale conversions are, and then declined; else possibly stale.
cached = V.__networkx_cache__.get("backends", {}).get("graphblas", {}).values()
if any(H._A.diag().get(H._key_to_id[1]) is None for H in cached):
pytest.skip("the view's conversion is stale, as without dropping stale conversions")
assert same(want, got)


@pytest.mark.parametrize("w", [2e38, 1e300, 1e38], ids=ids)
def test_a_requested_dtype_is_the_one_networkx_sums_in(w):
"""2e38 fits in float32, and twice it does not."""
G = square(2.0)
G.add_edge(1, 1, weight=w)
served = Dispatcher.can_run("adjacency_matrix", (G,), {"dtype": np.float32})
assert (served is True) == (w == 1e38), served
want = nx.adjacency_matrix(G, dtype=np.float32).toarray()
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
got = nx.adjacency_matrix(G, dtype=np.float32).toarray()
assert same(want.tolist(), got.tolist())


def test_each_dtype_is_checked_on_the_same_graph():
"""The answer for one dtype is not the answer for another."""
G = square(2.0)
G.add_edge(1, 1, weight=2e38) # fits in float32; twice it does not
for _ in range(2): # before the conversion is cached, then from it
assert Dispatcher.can_run("adjacency_matrix", (G,), {}) is True
f32 = Dispatcher.can_run("adjacency_matrix", (G,), {"dtype": np.float32})
assert isinstance(f32, str)
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
nx.adjacency_matrix(G)


def cache_a_conversion(name, G, *args, **kwargs):
"""Leave the conversion that `name` makes in `G`'s cache."""
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
result = getattr(nx, name)(G, *args, **kwargs)
if hasattr(result, "__next__"):
list(result)
return list(G.__networkx_cache__["backends"]["graphblas"].values())


def test_a_conversion_without_the_weight_does_not_answer():
G = square(2.0)
G.add_edge(1, 1, weight=math.inf)
[H] = cache_a_conversion("bfs_edges", G, 0)
assert H._weight is None
assert isinstance(Dispatcher.can_run("pagerank", (G,), {}), str)


def test_an_integer_conversion_is_served():
G = square(5)
[H] = cache_a_conversion("volume", G, [0, 1], weight="weight")
assert H._A.dtype.np_type.kind == "i"
assert Dispatcher.can_run("adjacency_matrix", (G,), {}) is True
want = nx.adjacency_matrix(G, backend="networkx").toarray().tolist()
with nx.config(backend_priority=["graphblas"], warnings_to_ignore={"cache"}):
got = nx.adjacency_matrix(G).toarray().tolist()
assert want == got


def test_a_float32_conversion_is_read_in_float32():
"""3e38 fits in float32, and twice it does not; in float64 it would."""
G = square(np.float32(3e38))
[H] = cache_a_conversion("volume", G, [0, 1], weight="weight")
assert H._A.dtype.np_type == np.float32
assert isinstance(Dispatcher.can_run("adjacency_matrix", (G,), {}), str)
Loading