diff --git a/graphblas_algorithms/algorithms/cluster.py b/graphblas_algorithms/algorithms/cluster.py index f84a219..6ec70f1 100644 --- a/graphblas_algorithms/algorithms/cluster.py +++ b/graphblas_algorithms/algorithms/cluster.py @@ -132,9 +132,10 @@ def single_clustering(G, node, *, weighted=False): return 0 index = G._key_to_id[node] # TODO: it would be nice if we could clean this up, but still be fast - if "degrees-" in G._cache: + # The cache keeps the degrees under the names their aliases resolve to. + if G._cache_aliases.get("degrees-", "degrees-") in G._cache: degrees = G.get_property("degrees-").get(index) - elif "degrees+" in G._cache: + elif G._cache_aliases.get("degrees+", "degrees+") in G._cache: degrees = G.get_property("degrees+").get(index) if G.get_property("has_self_edges") and G._A.get(index, index) is not None: degrees -= 1 diff --git a/graphblas_algorithms/classes/_caching.py b/graphblas_algorithms/classes/_caching.py index 3074bed..a9d2019 100644 --- a/graphblas_algorithms/classes/_caching.py +++ b/graphblas_algorithms/classes/_caching.py @@ -1,4 +1,4 @@ -from graphblas import Scalar, dtypes, op +from graphblas import Scalar, dtypes, monoid, op from graphblas.core import operator NONNEGATIVE_DTYPES = {dtypes.BOOL, dtypes.UINT8, dtypes.UINT16, dtypes.UINT32, dtypes.UINT64} @@ -99,6 +99,8 @@ def get_reduction(G, mask=None): def get_reduce_to_scalar(key, opname): op_ = op.from_string(opname) op_, opclass = operator.find_opclass(op_) + # The reduction of the whole from those of the rows (or columns): counts add up. + parts_op = monoid.plus if opname == "count" else op_ keybase = key[:-1] if key[-1] == "-": @@ -108,13 +110,13 @@ def get_reduction(G, mask=None): if cache.get("has_self_edges") is False and f"{keybase}+" in cache: cache[key] = cache[f"{keybase}+"] elif f"{opname}_rowwise-" in cache: - cache[key] = cache[f"{opname}_rowwise-"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_rowwise-"].reduce(parts_op).new(name=key) elif f"{opname}_columnwise-" in cache: - cache[key] = cache[f"{opname}_columnwise-"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_columnwise-"].reduce(parts_op).new(name=key) elif cache.get("has_self_edges") is False and f"{opname}_rowwise+" in cache: - cache[key] = cache[f"{opname}_rowwise+"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_rowwise+"].reduce(parts_op).new(name=key) elif cache.get("has_self_edges") is False and f"{opname}_columnwise+" in cache: - cache[key] = cache[f"{opname}_columnwise+"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_columnwise+"].reduce(parts_op).new(name=key) elif "offdiag" in cache: cache[key] = cache["offdiag"].reduce_scalar(op_).new(name=key) elif ( @@ -124,8 +126,8 @@ def get_reduction(G, mask=None): and G.get_property("has_self_edges") ): return op_( - cache["L-"].reduce(op_)._as_vector() | cache["U-"].reduce(op_)._as_vector() - )[0].new(name=key) + cache["L-"].reduce_scalar(op_).new() | cache["U-"].reduce_scalar(op_).new() + ).new(name=key) elif not G.get_property("has_self_edges"): cache[key] = G.get_property(f"{keybase}+") else: @@ -149,13 +151,13 @@ def get_reduction(G, mask=None): if cache.get("has_self_edges") is False and f"{keybase}-" in cache: cache[key] = cache[f"{keybase}-"] elif f"{opname}_rowwise+" in cache: - cache[key] = cache[f"{opname}_rowwise+"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_rowwise+"].reduce(parts_op).new(name=key) elif f"{opname}_columnwise+" in cache: - cache[key] = cache[f"{opname}_columnwise+"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_columnwise+"].reduce(parts_op).new(name=key) elif cache.get("has_self_edges") is False and f"{opname}_rowwise-" in cache: - cache[key] = cache[f"{opname}_rowwise-"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_rowwise-"].reduce(parts_op).new(name=key) elif cache.get("has_self_edges") is False and f"{opname}_columnwise-" in cache: - cache[key] = cache[f"{opname}_columnwise-"].reduce(op_).new(name=key) + cache[key] = cache[f"{opname}_columnwise-"].reduce(parts_op).new(name=key) else: cache[key] = A.reduce_scalar(op_).new(name=key) if ( diff --git a/graphblas_algorithms/classes/digraph.py b/graphblas_algorithms/classes/digraph.py index 3aa3d53..2e971e9 100644 --- a/graphblas_algorithms/classes/digraph.py +++ b/graphblas_algorithms/classes/digraph.py @@ -128,7 +128,7 @@ def get_recip_degreesp(G, mask=None): cache["recip_degrees+"] = cache["recip_degrees-"] return cache["recip_degrees-"].dup(mask=mask) if "recip_degrees-" in cache and "diag" in cache: - return (unary.one(cache["diag"]) + cache["recip_degrees-"]).new( + return (unary.one[int](cache["diag"]) + cache["recip_degrees-"]).new( mask=mask, name="recip_degrees+" ) if "recip_degrees-" in cache and not G.get_property("has_self_edges"): @@ -138,7 +138,7 @@ def get_recip_degreesp(G, mask=None): if cache.get("has_self_edges") is False and "recip_degrees-" in cache: cache["recip_degrees+"] = cache["recip_degrees-"] elif "recip_degrees-" in cache and "diag" in cache: - cache["recip_degrees+"] = (unary.one(cache["diag"]) + cache["recip_degrees-"]).new( + cache["recip_degrees+"] = (unary.one[int](cache["diag"]) + cache["recip_degrees-"]).new( name="recip_degrees+" ) elif "recip_degrees-" in cache and not G.get_property("has_self_edges"): @@ -175,7 +175,7 @@ def get_recip_degreesm(G, mask=None): cache["recip_degrees-"] = cache["recip_degrees+"] return cache["recip_degrees-"].dup(mask=mask) if "recip_degrees+" in cache and "diag" in cache: - rv = binary.minus(cache["recip_degrees+"] | unary.one(cache["diag"])).new( + rv = binary.minus(cache["recip_degrees+"] | unary.one[int](cache["diag"])).new( mask=mask, name="recip_degrees-" ) rv(rv.V, replace) << rv # drop 0s @@ -195,14 +195,14 @@ def get_recip_degreesm(G, mask=None): ).new(name="recip_degrees-") diag = G.get_property("diag", mask=mask) overlap = binary.pair(A & AT).reduce_rowwise().new(mask=mask) - rv = binary.minus(overlap | unary.one(diag)).new(name="recip_degrees-") + rv = binary.minus(overlap | unary.one[int](diag)).new(name="recip_degrees-") rv(rv.V, replace) << rv # drop 0s return rv if "recip_degrees-" not in cache: if cache.get("has_self_edges") is False and "recip_degrees+" in cache: cache["recip_degrees-"] = cache["recip_degrees+"] elif "recip_degrees+" in cache and "diag" in cache: - rv = binary.minus(cache["recip_degrees+"] | unary.one(cache["diag"])).new( + rv = binary.minus(cache["recip_degrees+"] | unary.one[int](cache["diag"])).new( name="recip_degrees-" ) rv(rv.V, replace) << rv # drop 0s @@ -221,7 +221,7 @@ def get_recip_degreesm(G, mask=None): else: diag = G.get_property("diag") overlap = binary.pair(A & AT).reduce_rowwise().new() - rv = binary.minus(overlap | unary.one(diag)).new(name="recip_degrees-") + rv = binary.minus(overlap | unary.one[int](diag)).new(name="recip_degrees-") rv(rv.V, replace) << rv # drop 0s cache["recip_degrees-"] = rv if ( diff --git a/graphblas_algorithms/classes/graph.py b/graphblas_algorithms/classes/graph.py index 1f156a9..2d0847d 100644 --- a/graphblas_algorithms/classes/graph.py +++ b/graphblas_algorithms/classes/graph.py @@ -138,12 +138,16 @@ def has_negative_diagonal(G, mask=None): if A.dtype in NONNEGATIVE_DTYPES or A.dtype._is_udt or cache.get("has_self_edges") is False: cache["has_negative_diagonal"] = False elif ( + # A negative weight, and none off the diagonal; a missing fact tells nothing. cache.get("has_negative_edges+") is True and cache.get("has_negative_edges-") is False or cache.get("has_negative_edges+") is True - and cache.get("min_element-", 0) >= 0 - or cache.get("min_element+", 0) < 0 - and cache.get("min_element+", 0) < cache.get("min_element-", 0) + and "min_element-" in cache + and cache["min_element-"] >= 0 + or "min_element+" in cache + and "min_element-" in cache + and cache["min_element+"] < 0 + and cache["min_element+"] < cache["min_element-"] ): cache["has_negative_diagonal"] = True else: diff --git a/graphblas_algorithms/tests/test_cache_inference.py b/graphblas_algorithms/tests/test_cache_inference.py new file mode 100644 index 0000000..915192e --- /dev/null +++ b/graphblas_algorithms/tests/test_cache_inference.py @@ -0,0 +1,257 @@ +"""What a graph infers from the properties it has cached, against what a fresh graph computes.""" + +import random +import re + +import graphblas as gb +import networkx as nx +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms.classes import DiGraph, Graph + +# The reductions to ask for: monoids, and an aggregator, whose results combine differently; +# not "any", whose answer may differ with the order it reads values in. +OPS = ["plus", "min", "max", "times", "count"] +REDUCTION = re.compile(r"[a-z]+_(rowwise|columnwise|element)[+-]$|[a-z]+_diagonal$") + + +def property_names(cls): + # The class's reductions grow as they are asked for, so take its others and add our own. + names = {name for name in cls._get_property if not REDUCTION.match(name)} + names |= set(cls._cache_aliases) + # `iso_value` raises KeyError after `is_iso` is cached as False; #121 rewrites both. + names.discard("iso_value") + for op in OPS: + for sign in "+-": + names |= {f"{op}_rowwise{sign}", f"{op}_columnwise{sign}", f"{op}_element{sign}"} + names.add(f"{op}_diagonal") + return sorted(names) + + +def vector_names(cls): + """The names whose values are Vectors, which may also be asked for under a mask.""" + names = [name for name in property_names(cls) if "_rowwise" in name or "_columnwise" in name] + names += [name for name in cls._cache_aliases if name.endswith(("degrees+", "degrees-"))] + names += ["diag"] + if cls is DiGraph: + names += ["recip_degrees+", "recip_degrees-", "total_degrees+", "total_degrees-"] + return sorted(set(names)) + + +def algorithms(cls): + rv = {"degree_centrality": ga.degree_centrality} + if cls is DiGraph: + rv.update( + in_degree_centrality=ga.in_degree_centrality, + out_degree_centrality=ga.out_degree_centrality, + reciprocity=ga.reciprocity, + overall_reciprocity=ga.overall_reciprocity, + ) + return rv + + +def random_matrix(rng, cls): + """Up to 6 nodes, any density, loops on some nodes or none, one value or several.""" + # At least one: python-graphblas 2026.11 counts the entries of a 0 by 0 matrix as 1. + n = rng.randint(1, 6) + dtype = rng.choice(["FP64", "INT64", "BOOL"]) + p = rng.random() + weights = [rng.choice([-2, 1, 3])] if rng.random() < 0.3 else [-2, -1, 1, 2, 3] + cells = {} + for u in range(n): + for v in range(u + 1 if cls is Graph else 0, n): + if u != v and rng.random() < p: + cells[u, v] = rng.choice(weights) + if rng.random() < 0.7: + for u in rng.sample(range(n), rng.randint(0, n)): + cells[u, u] = rng.choice(weights) + if cls is Graph: + cells.update({(v, u): w for (u, v), w in list(cells.items())}) + values = [True] * len(cells) if dtype == "BOOL" else list(cells.values()) + rows = [u for u, _ in cells] + cols = [v for _, v in cells] + return gb.Matrix.from_coo(rows, cols, values, nrows=n, ncols=n, dtype=dtype) + + +def sig(value): + """A value as plain data, with its dtype, to compare one from a cache with a fresh one.""" + if isinstance(value, (gb.Matrix, gb.Vector)): + entries = tuple(tuple(x.tolist()) for x in value.to_coo()) + return (type(value).__name__, str(value.dtype), value.shape, entries) + if isinstance(value, gb.Scalar): + return ("Scalar", str(value.dtype), value.value) + if isinstance(value, float): + return round(value, 12) + return value + + +def outcome(call, G): + try: + return sig(call(G)) + except Exception as exc: # The same error as a fresh graph's is the same answer. + return ("raised", type(exc).__name__) + + +def mismatches(cls, seed, trials): + """The steps of random fill orders whose answer is not a fresh graph's.""" + rng = random.Random(seed) # noqa: S311 (a seeded order, not a secret) + names = property_names(cls) + vectors = vector_names(cls) + algos = algorithms(cls) + wrong = [] + for _ in range(trials): + A = random_matrix(rng, cls) + G = cls(A.dup()) + steps = [] + for _ in range(rng.randint(1, 10)): + x = rng.random() + fresh = None + if x < 0.15: + label = rng.choice(sorted(algos)) + call = algos[label] + elif x < 0.35: + label = rng.sample(names, 3) + call = lambda G, label=label: tuple(map(sig, G.get_properties(label))) # noqa: E731 + # Each from a fresh graph of its own, as the others may be asked first. + fresh = lambda G, label=label: tuple( # noqa: E731 + sig(type(G)(G._A.dup()).get_property(name)) for name in label + ) + elif x < 0.5: + name = rng.choice(vectors) + ids = sorted(rng.sample(range(A.nrows), rng.randint(0, A.nrows))) + label = (name, ids) + mask = gb.Vector.from_coo(ids, True, size=A.nrows, dtype=bool).S + call = lambda G, name=name, mask=mask: G.get_property(name, mask=mask) # noqa: E731 + else: + label = rng.choice(names) + call = lambda G, label=label: G.get_property(label) # noqa: E731 + fresh = fresh or call + steps.append(label) + got = outcome(call, G) + expected = outcome(fresh, cls(A.dup())) + if got != expected: + wrong.append((A.to_coo(), str(A.dtype), list(steps), got, expected)) + return wrong + + +@pytest.mark.parametrize("cls", [Graph, DiGraph], ids=["Graph", "DiGraph"]) +@pytest.mark.parametrize("seed", range(4)) +def test_random_fill_orders_against_a_fresh_graph(cls, seed): + assert not mismatches(cls, seed, 100) + + +def directed_or_not(cls, edges, n): + rows = [u for u, _, _ in edges] + cols = [v for _, v, _ in edges] + A = gb.Matrix.from_coo(rows, cols, [w for _, _, w in edges], nrows=n, ncols=n) + if cls is Graph: + A = gb.binary.first(A | A.T).new() + return A + + +@pytest.mark.parametrize("cls", [Graph, DiGraph], ids=["Graph", "DiGraph"]) +@pytest.mark.parametrize("loop", [True, False], ids=["a loop", "no loop"]) +@pytest.mark.parametrize( + "first", + [ + [counts, "has_self_edges"] if before is None else [before, counts, "has_self_edges"] + for counts in ["count_rowwise+", "count_rowwise-", "count_columnwise+", "count_columnwise-"] + for before in [None, "offdiag"] + ], + ids=" ".join, +) +@pytest.mark.parametrize("asked", ["count_element+", "count_element-"]) +def test_count_element_from_the_counts_of_rows_or_columns(cls, loop, first, asked): + edges = [(0, 1, 1.0), (0, 2, 1.0), (1, 2, 1.0)] + ([(2, 2, 1.0)] if loop else []) + A = directed_or_not(cls, edges, 3) + G = cls(A.dup()) + for name in first: + G.get_property(name) + expected = A.nvals if asked.endswith("+") else A.select("offdiag").new().nvals + assert G.get_property(asked).value == expected + + +# Edges on 3 nodes, and whether a weight on the diagonal is negative. +NEGATIVE_DIAGONAL = { + "a loop of 1, -2 off it": ([(0, 1, -2.0), (1, 2, 3.0), (2, 2, 1.0)], False), + "a loop of 1, 3 and 4 off it": ([(0, 1, 3.0), (1, 2, 4.0), (2, 2, 1.0)], False), + "a loop of -1, 3 and 4 off it": ([(0, 1, 3.0), (1, 2, 4.0), (2, 2, -1.0)], True), + "a loop of -3, -2 off it": ([(0, 1, -2.0), (2, 2, -3.0)], True), + "a loop of -2, -3 off it": ([(0, 1, -3.0), (2, 2, -2.0)], True), +} + + +@pytest.mark.parametrize("cls", [Graph, DiGraph], ids=["Graph", "DiGraph"]) +@pytest.mark.parametrize( + "cached", + [ + ["min_element+"], + ["has_negative_edges+"], + ["min_element+", "min_element-"], + ["has_negative_edges+", "min_element-"], + ["has_negative_edges+", "has_negative_edges-"], + ], + ids=" ".join, +) +@pytest.mark.parametrize("name", list(NEGATIVE_DIAGONAL)) +def test_negative_diagonal_from_what_is_cached(cls, name, cached): + edges, expected = NEGATIVE_DIAGONAL[name] + G = cls(directed_or_not(cls, edges, 3)) + for key in cached: + G.get_property(key) + assert G.get_property("has_negative_diagonal") == expected + + +def test_negative_edge_cycle_after_the_least_weight_is_cached(): + G = nx.DiGraph() + G.add_weighted_edges_from([(0, 1, -2.0), (1, 2, 3.0), (2, 2, 1.0)]) # no negative cycle + H = DiGraph.from_networkx(G, weight="weight") + H.get_property("min_element+") + assert nx.negative_edge_cycle(H) is nx.negative_edge_cycle(G, backend="networkx") is False + + +@pytest.mark.parametrize("dtype", ["FP64", "INT64", "BOOL"]) +@pytest.mark.parametrize( + "first", + [ + [], + ["diag", "recip_degrees-"], + ["diag", "recip_degrees+"], + ["has_self_edges", "recip_degrees+"], + ["offdiag", "recip_degrees-"], + ["L-", "U-", "has_self_edges", "recip_degrees-"], + ], + ids=lambda first: " ".join(first) or "fresh", +) +def test_reciprocal_degrees_are_counts_in_any_fill_order(first, dtype): + # Node 1 has a loop and two reciprocated edges; node 2, a loop alone. + A = gb.Matrix.from_coo([0, 1, 1, 1, 2, 2], [1, 0, 1, 3, 2, 3], 2, nrows=4, ncols=4, dtype=dtype) + G = DiGraph(A.dup()) + G.get_properties(first) + mask = gb.Vector.from_coo([1, 2], True, size=4).S + for name in ["recip_degrees+", "recip_degrees-"]: + fresh = DiGraph(A.dup()).get_property(name) + assert fresh.dtype == "INT64" + assert G.get_property(name, mask=mask).isequal(fresh.dup(mask=mask), check_dtype=True) + assert G.get_property(name).isequal(fresh, check_dtype=True) + + +def test_clustering_of_one_node_reads_the_cached_degrees(monkeypatch): + G = nx.Graph([(0, 1), (1, 2), (2, 0), (2, 3), (2, 2)]) + expected = [nx.clustering(G, node, backend="networkx") for node in G] + extract = gb.Matrix.__getitem__ + for name in ["degrees-", "degrees+"]: + H = Graph.from_networkx(G) + H.get_property(name) + rows = [] + + def spy(A, index, rows=rows): + rows.append(index) + return extract(A, index) + + monkeypatch.setattr(gb.Matrix, "__getitem__", spy) + assert [nx.clustering(H, node) for node in G] == pytest.approx(expected) + monkeypatch.undo() + # A row of each node for its triangles, and none more for its degree. + assert len(rows) == len(G)