From 6ad0db0c59de568594f11f19423e72c2c8bae845 Mon Sep 17 00:00:00 2001 From: Erik Welch Date: Thu, 3 Dec 2026 18:22:19 -0600 Subject: [PATCH] Stop reading no self-loops from a DiGraph's total degrees A DiGraph's has_self_edges, given only "total_degrees+" in the cache, said there were self-loops if those degrees summed to more than twice the number of edges. They never do: a self-loop counts once in its row and once in its column, as any other edge does. So a DiGraph with a self-loop that had been asked for its degree centrality then said it had none, took the matrix itself as its off-diagonal part, and gave a reciprocity of 0.5 where NetworkX gives 1/3. That case now reads the diagonal. The cases for the row and column degrees looked under "row_degrees" and "column_degrees", which are only aliases: the cache keeps them as "count_rowwise" and "count_columnwise", so those cases never ran. They now read the keys the cache holds. --- graphblas_algorithms/classes/digraph.py | 23 +- graphblas_algorithms/tests/test_self_edges.py | 265 ++++++++++++++++++ 2 files changed, 278 insertions(+), 10 deletions(-) create mode 100644 graphblas_algorithms/tests/test_self_edges.py diff --git a/graphblas_algorithms/classes/digraph.py b/graphblas_algorithms/classes/digraph.py index 29def96..3aa3d53 100644 --- a/graphblas_algorithms/classes/digraph.py +++ b/graphblas_algorithms/classes/digraph.py @@ -350,22 +350,25 @@ def has_self_edges(G, mask=None): cache["has_self_edges"] = True elif "total_recip-" in cache and "total_recip+" in cache: cache["has_self_edges"] = cache["total_recip+"] > cache["total_recip-"] - elif "row_degrees-" in cache and "row_degrees+" in cache: - cache["has_self_edges"] = not cache["row_degrees-"].isequal(cache["row_degrees+"]) - elif "column_degrees-" in cache and "column_degrees+" in cache: - cache["has_self_edges"] = not cache["column_degrees-"].isequal(cache["column_degrees+"]) + # The row and column degrees are kept as "count_rowwise" and "count_columnwise". + elif "count_rowwise-" in cache and "count_rowwise+" in cache: + cache["has_self_edges"] = not cache["count_rowwise-"].isequal(cache["count_rowwise+"]) + elif "count_columnwise-" in cache and "count_columnwise+" in cache: + cache["has_self_edges"] = not cache["count_columnwise-"].isequal( + cache["count_columnwise+"] + ) elif "total_degrees-" in cache and "total_degrees+" in cache: cache["has_self_edges"] = not cache["total_degrees-"].isequal(cache["total_degrees+"]) elif "recip_degrees-" in cache and "recip_degrees+" in cache: cache["has_self_edges"] = not cache["recip_degrees-"].isequal(cache["recip_degrees+"]) - elif "row_degrees-" in cache: - cache["has_self_edges"] = cache["row_degrees-"].reduce().get(0) < A.nvals - elif "column_degrees-" in cache: - cache["has_self_edges"] = cache["column_degrees-"].reduce().get(0) < A.nvals + elif "count_rowwise-" in cache: + cache["has_self_edges"] = cache["count_rowwise-"].reduce().get(0) < A.nvals + elif "count_columnwise-" in cache: + cache["has_self_edges"] = cache["count_columnwise-"].reduce().get(0) < A.nvals elif "total_degrees-" in cache: cache["has_self_edges"] = cache["total_degrees-"].reduce().get(0) < 2 * A.nvals - elif "total_degrees+" in cache: - cache["has_self_edges"] = cache["total_degrees+"].reduce().get(0) > 2 * A.nvals + # "total_degrees+" alone says nothing: a self-loop counts once in its row and once in its + # column, as every other edge does, so it sums to 2 * A.nvals with or without one. else: G.get_property("diag") return cache["has_self_edges"] diff --git a/graphblas_algorithms/tests/test_self_edges.py b/graphblas_algorithms/tests/test_self_edges.py new file mode 100644 index 0000000..3c8824d --- /dev/null +++ b/graphblas_algorithms/tests/test_self_edges.py @@ -0,0 +1,265 @@ +"""Whether a graph has self-loops, as read from whatever its cache already holds.""" + +import itertools +import random + +import graphblas as gb +import networkx as nx +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.algorithms.exceptions import EmptyGraphError +from graphblas_algorithms.classes import DiGraph, Graph + +CLASSES = pytest.mark.parametrize("cls", [Graph, DiGraph], ids=["Graph", "DiGraph"]) + +# Edges as (source, target, weight), on `n` nodes. +GRAPHS = { + "a loop in a cycle": (4, [(0, 1, 1), (1, 2, 1), (2, 0, 1), (2, 2, 1), (0, 3, 1), (3, 0, 1)]), + "no loop": (4, [(0, 1, 1), (1, 2, 1), (2, 0, 1), (0, 3, 1), (3, 0, 1)]), + "a node with only a loop": (3, [(0, 1, 1), (1, 0, 1), (2, 2, 1)]), + "a loop alone": (1, [(0, 0, 2)]), + "a negative loop": (2, [(0, 1, 1), (1, 1, -2)]), + "a loop on every node": (2, [(0, 0, 3), (1, 1, 3), (0, 1, 3)]), + "no edges": (3, []), +} + +# Every property `has_self_edges` may read, and a few more, by the names the cache keeps. +EVIDENCE = [ + "offdiag", + "L+", + "L-", + "U+", + "U-", + "has_negative_diagonal", + "count_rowwise+", + "count_rowwise-", + "plus_rowwise-", + "max_element+", + "max_element-", +] +DIRECTED_EVIDENCE = [ + "count_columnwise+", + "count_columnwise-", + "total_degrees+", + "total_degrees-", + "recip_degrees+", + "recip_degrees-", + "total_recip+", + "total_recip-", +] + + +def matrix(cls, n, edges): + cells = {(u, v): w for u, v, w in edges} + if cls is Graph: + cells.update({(v, u): w for (u, v), w in list(cells.items())}) + rows = [u for u, _ in cells] + cols = [v for _, v in cells] + return gb.Matrix.from_coo(rows, cols, list(cells.values()), nrows=n, ncols=n, dtype=float) + + +def sig(value): + """A value as plain data, to compare one from a cache with one from a fresh graph.""" + if isinstance(value, gb.Matrix): + return ("Matrix", value.shape, tuple(tuple(x.tolist()) for x in value.to_coo())) + if isinstance(value, gb.Vector): + return ("Vector", value.size, tuple(tuple(x.tolist()) for x in value.to_coo())) + if isinstance(value, gb.Scalar): + return ("Scalar", value.value) + if isinstance(value, float): + return round(value, 12) + return value + + +def evidence(cls, name): + """The graph's matrix, each property's value, and whether it has a self-loop.""" + n, edges = GRAPHS[name] + A = matrix(cls, n, edges) + keys = EVIDENCE + DIRECTED_EVIDENCE if cls is DiGraph else EVIDENCE + # Each value comes from a graph of its own, so nothing else it caches comes along. + values = {key: cls(A.dup()).get_property(key) for key in keys} + return A, values, any(u == v for u, v, _ in edges) + + +@CLASSES +@pytest.mark.parametrize("name", list(GRAPHS)) +def test_has_self_edges_from_any_one_or_two_cached_properties(cls, name): + A, values, expected = evidence(cls, name) + offdiag = sig(A.select("offdiag").new()) + wrong = [] + for size in (1, 2): + for held in itertools.combinations(values, size): + G = cls(A.dup()) + G._cache.update({key: values[key] for key in held}) + if G.get_property("has_self_edges") != expected: + wrong.append((held, "has_self_edges")) + if sig(G.get_property("offdiag")) != offdiag: + wrong.append((held, "offdiag")) + assert not wrong + + +@CLASSES +@pytest.mark.parametrize("name", list(GRAPHS)) +def test_has_self_edges_as_another_property_is_computed(cls, name): + """A getter may settle `has_self_edges` from what it computes and what the cache holds.""" + A, values, expected = evidence(cls, name) + offdiag = sig(A.select("offdiag").new()) + wrong = [] + for size in (0, 1, 2): + for held in itertools.combinations(values, size): + for asked in values: + if {"L-", "U-"} <= set(held) and asked.endswith("_element-"): + # Read from L- and U- with a `reduce` that a Matrix lacks: a separate failure. + continue + G = cls(A.dup()) + G._cache.update({key: values[key] for key in held}) + if sig(G.get_property(asked)) != sig(values[asked]): + wrong.append((held, asked, asked)) + if G.get_property("has_self_edges") != expected: + wrong.append((held, asked, "has_self_edges")) + if sig(G.get_property("offdiag")) != offdiag: + wrong.append((held, asked, "offdiag")) + assert not wrong + + +@pytest.mark.parametrize( + "held", + [ + ["count_rowwise-"], + ["count_columnwise-"], + ["total_degrees-"], + ["count_rowwise-", "count_rowwise+"], + ["count_columnwise-", "count_columnwise+"], + ["total_degrees-", "total_degrees+"], + ], + ids=" ".join, +) +@pytest.mark.parametrize("name", list(GRAPHS)) +def test_a_digraph_s_degrees_tell_without_the_diagonal(name, held): + A = matrix(DiGraph, *GRAPHS[name]) + G = DiGraph(A.dup()) + G._cache.update({key: DiGraph(A.dup()).get_property(key) for key in held}) + assert G.get_property("has_self_edges") == (A.diag().nvals > 0) + assert "diag" not in G._cache + + +@CLASSES +def test_has_self_edges_after_degree_centrality(cls): + G = cls(matrix(cls, *GRAPHS["a loop in a cycle"])) + ga.degree_centrality(G) # leaves the degrees, loops counted, in the cache + assert G.get_property("has_self_edges") is True + assert G.get_property("offdiag").nvals == G._A.nvals - 1 + + +def test_reciprocity_after_degree_centrality(): + G = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 2), (0, 3), (3, 0)]) + expected = nx.reciprocity(G, backend="networkx") + assert expected == pytest.approx(1 / 3) + H = DiGraph.from_networkx(G) + nxapi.degree_centrality(H) + assert nxapi.reciprocity(H) == pytest.approx(expected) + assert nxapi.overall_reciprocity(H) == pytest.approx(expected) + some = nx.reciprocity(G, [0, 2], backend="networkx") + assert dict(nxapi.reciprocity(H, [0, 2])) == pytest.approx(some) + + +# Properties and algorithms to call in random orders. Each answer must be the fresh graph's. +FILL_KEYS = [ + "A", + "AT", + "L+", + "L-", + "U+", + "U-", + "diag", + "offdiag", + "has_self_edges", + "is_iso", + "has_negative_edges+", + "count_rowwise+", + "count_rowwise-", + "plus_rowwise+", + "plus_rowwise-", + "min_rowwise+", + "max_rowwise-", + "min_element+", + "max_element+", + "plus_element+", + "min_diagonal", + "max_diagonal", +] +FILL_KEYS_UNDIRECTED = ["degrees+", "degrees-"] +FILL_KEYS_DIRECTED = [ + "count_columnwise+", + "count_columnwise-", + "plus_columnwise-", + "row_degrees+", + "row_degrees-", + "column_degrees+", + "column_degrees-", + "total_degrees+", + "total_degrees-", + "recip_degrees+", + "recip_degrees-", + "total_recip+", + "total_recip-", +] +FILL_ALGORITHMS = {"degree_centrality": ga.degree_centrality} +FILL_ALGORITHMS_DIRECTED = { + "in_degree_centrality": ga.in_degree_centrality, + "out_degree_centrality": ga.out_degree_centrality, + "reciprocity": ga.reciprocity, + "overall_reciprocity": ga.overall_reciprocity, +} + + +def random_matrix(rng, cls): + n = rng.randint(1, 6) + p = rng.random() + weights = [rng.choice([-2, 1, 3])] if rng.random() < 0.3 else [-2, -1, 1, 2, 3] + edges = [(u, v, rng.choice(weights)) for u in range(n) for v in range(n) if u != v] + edges = [edge for edge in edges if rng.random() < p and (cls is DiGraph or edge[0] < edge[1])] + if rng.random() < 0.7: + edges += [(u, u, rng.choice(weights)) for u in rng.sample(range(n), rng.randint(0, n))] + return matrix(cls, n, edges) + + +def outcome(call, G): + try: + return sig(call(G)) + except EmptyGraphError: + return "EmptyGraphError" + + +@CLASSES +@pytest.mark.parametrize("seed", range(3)) +def test_random_fill_orders_against_a_fresh_graph(cls, seed): + rng = random.Random(seed) # noqa: S311 (a seeded order, not a secret) + if cls is DiGraph: + keys = FILL_KEYS + FILL_KEYS_DIRECTED + algorithms = {**FILL_ALGORITHMS, **FILL_ALGORITHMS_DIRECTED} + else: + keys = FILL_KEYS + FILL_KEYS_UNDIRECTED + algorithms = FILL_ALGORITHMS + wrong = [] + for _ in range(100): + A = random_matrix(rng, cls) + G = cls(A.dup()) + steps = [] + for _ in range(rng.randint(1, 10)): + x = rng.random() + if x < 0.2: + name = rng.choice(sorted(algorithms)) + call = algorithms[name] + elif x < 0.4: + name = rng.sample(keys, 3) + call = lambda G, name=name: tuple(map(sig, G.get_properties(name))) # noqa: E731 + else: + name = rng.choice(keys) + call = lambda G, name=name: G.get_property(name) # noqa: E731 + steps.append(name) + if outcome(call, G) != outcome(call, cls(A.dup())): + wrong.append((A.to_coo(), list(steps))) + assert not wrong