diff --git a/README.md b/README.md index 1bc06b5..1bc7147 100644 --- a/README.md +++ b/README.md @@ -149,8 +149,10 @@ graphblas_algorithms.nxapi │ │ └── group_out_degree_centrality │ ├── harmonic │ │ └── harmonic_centrality -│ └── katz -│ └── katz_centrality +│ ├── katz +│ │ └── katz_centrality +│ └── laplacian +│ └── laplacian_centrality ├── cluster │ ├── average_clustering │ ├── clustering diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..3dfeaab 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -116,6 +116,7 @@ def get_info(): "k_shell", "k_truss", "katz_centrality", + "laplacian_centrality", "laplacian_matrix", "local_efficiency", "lowest_common_ancestor", @@ -222,6 +223,7 @@ def get_info(): "k_crust": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge 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.", "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge 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.", "k_truss": "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.", + "laplacian_centrality": "A directed graph is left to NetworkX, whose directed Laplacian is dense and built from\nan eigenvector it finds iteratively. So are a nodelist that is not a list of hashable\nnodes, a graph whose Laplacian energy is not finite, float weights of both signs whose\nsum is so near 0 that NetworkX's order of summation decides whether it raises\nZeroDivisionError, and complex weights.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "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.", "periphery": '`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.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..fe5bf9e 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -165,6 +165,13 @@ "k_corona": _CORE_SUBGRAPH, "k_crust": _CORE_SUBGRAPH, "k_shell": _CORE_SUBGRAPH, + "laplacian_centrality": ( + "A directed graph is left to NetworkX, whose directed Laplacian is dense and built from\n" + "an eigenvector it finds iteratively. So are a nodelist that is not a list of hashable\n" + "nodes, a graph whose Laplacian energy is not finite, float weights of both signs whose\n" + "sum is so near 0 that NetworkX's order of summation decides whether it raises\n" + "ZeroDivisionError, and complex weights." + ), "local_efficiency": ( "The cost is the breadth-first levels times the chunks of walks, so a node whose\n" "neighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\n" diff --git a/graphblas_algorithms/algorithms/centrality/__init__.py b/graphblas_algorithms/algorithms/centrality/__init__.py index 7713385..bf1bac1 100644 --- a/graphblas_algorithms/algorithms/centrality/__init__.py +++ b/graphblas_algorithms/algorithms/centrality/__init__.py @@ -6,3 +6,4 @@ from .group import * from .harmonic import * from .katz import * +from .laplacian import * diff --git a/graphblas_algorithms/algorithms/centrality/laplacian.py b/graphblas_algorithms/algorithms/centrality/laplacian.py new file mode 100644 index 0000000..4ed962a --- /dev/null +++ b/graphblas_algorithms/algorithms/centrality/laplacian.py @@ -0,0 +1,56 @@ +import math + +import numpy as np +from graphblas import Vector, binary, monoid, select, unary +from graphblas.semiring import plus_times + +from ..exceptions import GraphBlasAlgorithmException + +__all__ = ["laplacian_centrality"] + + +def _energy_drops(G): + """Each node's drop in Laplacian energy when it is removed, and the energy: (array, float). + + For an undirected graph's Laplacian L = D - A, with d the diagonal, the energy (the sum of + the squared eigenvalues of the symmetric L) is the sum of the squares of L's entries: + sum(d**2) plus the squares of the edge weights off the diagonal. NetworkX removes node i + by dropping its row and column and taking |L[j, i]| off each other diagonal entry, so the + drop for i is d[i]**2 + 2 * sum_j |A[i, j]| * d[j] + sum_j A[i, j]**2 over j other than i. + A self-loop is in no entry of L: NetworkX's diagonal is the row sum less the self-loop. + """ + A = G._A + d = A.reduce_rowwise(monoid.plus[float]).new(name="d") + d(binary.minus) << A.diag() + off = select.offdiag(A).new(dtype=float, name="off_diagonal") + squares = binary.times(off & off).new(name="squares").reduce_rowwise(monoid.plus) + squares = squares.new(name="squared_weights").to_dense(fill_value=0.0) + if off.nvals > 0 and off.reduce_scalar(monoid.min).get() < 0: + off << unary.abs(off) + across = plus_times(off @ d).new(name="across").to_dense(fill_value=0.0) + d = d.to_dense(fill_value=0.0) + with np.errstate(over="ignore", invalid="ignore"): # a non-finite energy is the caller's + d *= d + energy = float(d.sum() + squares.sum()) + across *= 2 + d += across + d += squares + return d, energy + + +def laplacian_centrality(G, normalized=True, *, name="laplacian_centrality"): + """Each node's drop in Laplacian energy when it is removed, as a fraction of the energy. + + An undirected graph only. NaN for every node when `normalized` and the energy is 0, which + is NetworkX's 0 / 0: only self-loops carry weight. Raises GraphBlasAlgorithmException when + the energy is not finite. + """ + drops, energy = _energy_drops(G) + if not math.isfinite(energy): + raise GraphBlasAlgorithmException(f"the Laplacian energy is {energy}") + if normalized: + if energy == 0: + drops[:] = np.nan + else: + drops /= energy + return Vector.from_dense(drops, name=name) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01b052f..9597b10 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -255,6 +255,7 @@ class Dispatcher: group_out_degree_centrality = mod.group.group_out_degree_centrality harmonic_centrality = mod.harmonic.harmonic_centrality katz_centrality = mod.katz.katz_centrality + laplacian_centrality = mod.laplacian.laplacian_centrality mod = nxapi.cluster # ================= diff --git a/graphblas_algorithms/nxapi/centrality/__init__.py b/graphblas_algorithms/nxapi/centrality/__init__.py index 7713385..bf1bac1 100644 --- a/graphblas_algorithms/nxapi/centrality/__init__.py +++ b/graphblas_algorithms/nxapi/centrality/__init__.py @@ -6,3 +6,4 @@ from .group import * from .harmonic import * from .katz import * +from .laplacian import * diff --git a/graphblas_algorithms/nxapi/centrality/laplacian.py b/graphblas_algorithms/nxapi/centrality/laplacian.py new file mode 100644 index 0000000..4ca9d1c --- /dev/null +++ b/graphblas_algorithms/nxapi/centrality/laplacian.py @@ -0,0 +1,119 @@ +import math + +import numpy as np + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes.digraph import to_graph + +from .._utils import can_run +from ..exception import NetworkXError, NetworkXPointlessConcept + +__all__ = ["laplacian_centrality"] + + +def _rule(bound): + G = bound["G"] + nodelist = bound["nodelist"] + if G.is_directed(): + return ( + "laplacian_centrality of a directed graph is NetworkX's dense directed Laplacian, " + "from an eigenvector it finds iteratively; networkx serves it" + ) + if nodelist is None: + return None + if not isinstance(nodelist, list): + # NetworkX adds a list to it: a tuple raises TypeError, an array broadcasts. + return f"laplacian_centrality with a {type(nodelist).__name__} nodelist; networkx serves it" + for node in nodelist: + try: + hash(node) + except TypeError: + # NetworkX's nbunch_iter words this error. + return "laplacian_centrality with an unhashable node in nodelist; networkx serves it" + return None + + +def _weightless(G): + """Whether NetworkX finds `G.size(weight)` to be 0; None when its order of summation decides. + + NetworkX sums the weighted degrees: each weight twice, a self-loop's too. The order does not + matter for weights of one sign, nor for weights that are multiples of one power of 2 whose + sizes sum to less than 2**52 of it (integers, halves), as every partial sum is then exact. + Otherwise the sum is 0 in no order when its exact value is past the rounding that a sum of + these terms can make. + """ + A = G._A + if A.nvals == 0: + return True + terms = np.concatenate([A.to_coo(rows=False, columns=False)[2], A.diag().to_coo()[1]]) + if terms.dtype == bool: + return not terms.any() + if terms.dtype.kind in "iu": + return sum(terms.tolist()) == 0 + if not np.isfinite(terms).all(): + return False # NaN or infinite: never 0 + if not (terms > 0).any() or not (terms < 0).any(): + return not terms.any() + magnitude = float(np.abs(terms).sum()) + if not math.isfinite(magnitude): + return None # a partial sum may overflow + low = _lowest_bit(terms) + if 52 + low >= 1024 or magnitude < math.ldexp(1.0, 52 + low): + return float(terms.sum()) / 2 == 0 # NetworkX's size halves the sum + exact = math.fsum(terms.tolist()) + if abs(exact) > 2 * terms.size * 2**-53 * magnitude + 2**-1000: + return False + return None + + +def _lowest_bit(values): + """The exponent of the lowest bit set in any of the nonzero float `values`.""" + mantissas, exponents = np.frexp(values[values != 0]) + whole = (mantissas * 2.0**53).astype(np.int64) # exact: a mantissa has 53 bits + lowest = np.frexp((whole & -whole).astype(np.float64))[1] - 1 + return int((exponents - 53 + lowest).min()) + + +@can_run(_rule) +def laplacian_centrality( + G, normalized=True, nodelist=None, weight="weight", walk_type=None, alpha=0.95 +): + # Again here: a direct call does not pass through `can_run`. + if (reason := _rule({"G": G, "nodelist": nodelist})) is not None: + raise NotImplementedError(reason) + G = to_graph(G, weight=weight) + if weight is not None and weight == G._weight and G._A.dtype.np_type.kind == "c": + # The kernel would read only the real parts. Refused by the converted matrix's type, + # which needs no pass over the edges and sees a cached or given graph as well. + raise NotImplementedError( + f"Edge attribute {weight!r} has complex values; networkx serves the call" + ) + if len(G) == 0: + raise NetworkXPointlessConcept("null graph has no centrality defined") + weightless = _weightless(G) + if weightless is None: + raise NotImplementedError( + "laplacian_centrality on edge weights that nearly cancel: whether NetworkX finds " + "their sum to be 0 depends on its order of summation; networkx serves it" + ) + if weightless: + if normalized: + raise ZeroDivisionError("graph with no edges has zero full energy") + return dict.fromkeys(G._key_to_id, 0) + key_to_id = G._key_to_id + if nodelist is not None: + present = {node for node in nodelist if node in key_to_id} + if len(present) != len(nodelist): + raise NetworkXError("nodelist has duplicate nodes or nodes not in G") + try: + result = algorithms.laplacian_centrality(G, normalized) + except algorithms.exceptions.GraphBlasAlgorithmException as e: + raise NotImplementedError( + f"laplacian_centrality where {e.args[0]} (a NaN or infinite weight, or a square " + "past the float range); networkx serves it" + ) from e + result = result.to_dense() + if nodelist is None: + return dict(zip(key_to_id, result.tolist(), strict=True)) + ids = [key_to_id[node] for node in nodelist] + return dict(zip(nodelist, result[ids].tolist(), strict=True)) diff --git a/graphblas_algorithms/nxapi/tests/test_laplacian_centrality.py b/graphblas_algorithms/nxapi/tests/test_laplacian_centrality.py new file mode 100644 index 0000000..d93ab95 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_laplacian_centrality.py @@ -0,0 +1,463 @@ +"""laplacian_centrality against NetworkX. + +The keys, their order, the errors and the value types must be NetworkX's exactly. The values must +be too when the weights are integers (NetworkX's sums are then exact, and so are this backend's +below 2**53); with float weights they agree to within 1e-12 of the graph's Laplacian energy, +since NetworkX subtracts two energies and keeps the rounding of the whole. 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 + +import networkx as nx +import numpy as np +import pytest + +pytestmark = pytest.mark.filterwarnings( + "ignore:Note. conversions to backend graphs", + "ignore:invalid value encountered", + "ignore:overflow encountered", +) + +# A relative tolerance; the absolute one is this times the energy (unnormalized) or this. +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 energy(G, weight="weight"): + """NetworkX's full Laplacian energy of an undirected `G`.""" + return float(np.sum(nx.laplacian_matrix(G, weight=weight, backend="networkx").toarray() ** 2)) + + +def assert_same(got, expected, *, exact, scale): + assert list(got) == list(expected) + assert [type(value) for value in got.values()] == [type(v) for v in expected.values()] + for node, value in expected.items(): + if math.isnan(value): + assert math.isnan(got[node]), node + elif exact: + assert got[node] == value, node + else: + assert got[node] == pytest.approx(value, rel=TOLERANCE, abs=TOLERANCE * scale), node + + +def served(G, *, exact=False, **kwargs): + """laplacian_centrality by this backend, both ways, checked against NetworkX's.""" + expected = nx.laplacian_centrality(G, backend="networkx", **kwargs) + weight = kwargs.get("weight", "weight") + scale = 1.0 if kwargs.get("normalized", True) or len(G) == 0 else max(1.0, energy(G, weight)) + got = nx.laplacian_centrality(G, backend="graphblas", **kwargs) + assert_same(got, expected, exact=exact, scale=scale) + G.__networkx_cache__.clear() + with graphblas_first(): + assert_same(nx.laplacian_centrality(G, **kwargs), expected, exact=exact, scale=scale) + return got, expected + + +def raised(G, error, match=None, **kwargs): + """The error NetworkX raises, raised by this backend too, both ways.""" + with pytest.raises(error, match=match): + nx.laplacian_centrality(G, backend="networkx", **kwargs) + with pytest.raises(error, match=match): + nx.laplacian_centrality(G, backend="graphblas", **kwargs) + G.__networkx_cache__.clear() + with graphblas_first(), pytest.raises(error, match=match): + nx.laplacian_centrality(G, **kwargs) + + +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 + + try: + expected = ("value", nx.laplacian_centrality(G, backend="networkx", **kwargs)) + except Exception as e: + expected = ("error", type(e), str(e)) + declined = Dispatcher.can_run("laplacian_centrality", (G,), kwargs) + if declined is True: # declined once converted + with pytest.raises(NotImplementedError) as info: + nx.laplacian_centrality(G, backend="graphblas", **kwargs) + declined = str(info.value.__cause__) + assert reason in declined + G.__networkx_cache__.clear() + with graphblas_first(): + try: + got = ("value", nx.laplacian_centrality(G, **kwargs)) + except Exception as e: + got = ("error", type(e), str(e)) + if expected[0] == "value" and got[0] == "value": + assert list(got[1]) == list(expected[1]) + assert all( + (math.isnan(a) and math.isnan(b)) or a == b + for a, b in zip(got[1].values(), expected[1].values(), strict=True) + ) + else: + assert got == expected + + +def random_graph(seed): + """A random undirected graph: weights of one of several kinds, self-loops, isolated nodes. + + Kinds by seed: unweighted, small integers of both signs, floats of both signs, positive + floats with some edges missing the attribute, integer-valued floats. + """ + rng = np.random.default_rng(seed) + n = int(rng.integers(1, 41)) + p = float(rng.choice([0.03, 0.1, 0.2, 0.4])) + kind = seed % 5 + G = nx.Graph() + G.add_nodes_from(rng.permutation(n).tolist()) + for u in range(n): + for v in range(u, n): + if rng.random() >= (p / 3 if u == v else p): + continue + if kind == 0: + G.add_edge(u, v) + elif kind == 1: + G.add_edge(u, v, weight=int(rng.integers(-5, 10))) + elif kind == 2: + G.add_edge(u, v, weight=float(rng.normal(1.0, 2.0))) + elif kind == 3: + if rng.random() < 0.2: + G.add_edge(u, v, other=1) + else: + G.add_edge(u, v, weight=float(rng.uniform(0.1, 3.0))) + else: + G.add_edge(u, v, weight=float(rng.integers(-3, 8))) + labels = seed % 3 + if labels == 1: + G = nx.relabel_nodes(G, {node: f"n{node}" for node in G}) + elif labels == 2: + G = nx.relabel_nodes(G, {node: (node % 4, node) for node in G}) + return G, kind + + +def _random_nodelist(G, rng): + nodes = list(G) + count = int(rng.integers(0, len(nodes) + 1)) + return [nodes[i] for i in rng.permutation(len(nodes))[:count].tolist()] + + +def checked(G, *, exact=False, **kwargs): + """`served` where NetworkX answers, `raised` where it raises.""" + try: + nx.laplacian_centrality(G, backend="networkx", **kwargs) + except ZeroDivisionError: + raised(G, ZeroDivisionError, **kwargs) + else: + served(G, exact=exact, **kwargs) + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs(seed): + G, kind = random_graph(seed) + nodelist = _random_nodelist(G, np.random.default_rng(10_000 + seed)) + exact = kind in {0, 1, 4} + for normalized in (True, False): + checked(G, normalized=normalized, exact=exact) + checked(G, normalized=normalized, nodelist=nodelist, exact=exact) + checked(G, weight=None, exact=True) + + +@pytest.mark.parametrize( + "G", + [ + nx.path_graph(200), + nx.star_graph(150), + nx.complete_graph(60), + nx.gnm_random_graph(300, 900, seed=1), + nx.barabasi_albert_graph(300, 3, seed=2), + nx.karate_club_graph(), + ], + ids=["path", "star", "complete", "gnm", "barabasi-albert", "karate"], +) +def test_larger_graphs(G): + for normalized in (True, False): + served(G, normalized=normalized, exact=True, weight=None) + served(G, normalized=normalized) + + +def test_larger_float_weights(): + rng = np.random.default_rng(7) + G = nx.gnm_random_graph(250, 1500, seed=3) + for u, v in G.edges: + G[u][v]["weight"] = float(rng.lognormal(0.0, 1.5)) + G.add_edge(5, 5, weight=40.0) + for normalized in (True, False): + served(G, normalized=normalized) + served(G, normalized=normalized, nodelist=[7, 3, 5, 200]) + + +def test_docstring_example(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 4), (0, 2, 2), (2, 1, 1), (1, 3, 2), (1, 4, 2), (4, 5, 1)]) + got, _ = served(G, exact=True) + assert {v: round(c, 2) for v, c in got.items()} == { + 0: 0.7, + 1: 0.9, + 2: 0.28, + 3: 0.22, + 4: 0.26, + 5: 0.04, + } + got, _ = served(G, normalized=False, exact=True) + assert got == {0: 140.0, 1: 180.0, 2: 56.0, 3: 44.0, 4: 52.0, 5: 8.0} + + +def test_self_loops_change_nothing(): + """NetworkX's Laplacian diagonal is the row sum less the self-loop.""" + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 4), (0, 2, 2), (2, 1, 1), (1, 3, 2), (1, 4, 2), (4, 5, 1)]) + plain, _ = served(G, normalized=False, exact=True) + G.add_edge(1, 1, weight=5) + G.add_edge(5, 5, weight=-3) + G.add_edge(6, 6, weight=2) + looped, _ = served(G, normalized=False, exact=True) + assert looped == {**plain, 6: 0.0} + + +def test_negative_weights_count_by_their_size_off_the_diagonal(): + """NetworkX takes |L[j, i]| off each diagonal entry, whatever the weight's sign.""" + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 3), (1, 2, -2), (2, 3, 0.5)]) + got, _ = served(G, normalized=False, exact=True) + assert got == {0: 24.0, 1: 26.0, 2: 11.0, 3: -1.0} + + +def test_only_self_loops_carry_weight(): + """The energy is 0: NaN for every node normalized (NetworkX's 0 / 0), else 0.0.""" + for G in (nx.Graph([(0, 0)]), nx.Graph([(0, 0), (1, 1), (2, 3)])): + if G.number_of_edges() == 3: + G[2][3]["weight"] = 0 + got, _ = served(G) + assert all(math.isnan(value) for value in got.values()) + got, _ = served(G, normalized=False, exact=True) + assert set(got.values()) == {0.0} + + +def test_isolated_nodes_drop_nothing(): + G = nx.path_graph(4) + G.add_nodes_from(["a", "b"]) + got, _ = served(G, exact=True) + assert got["a"] == got["b"] == 0.0 + + +def test_the_null_graph(): + for normalized in (True, False): + raised(nx.Graph(), nx.NetworkXPointlessConcept, "null graph", normalized=normalized) + + +@pytest.mark.parametrize( + "weights", + [[], [0], [1, -1], [1.0, -1.0], [2.5, -1.5, -1.0], [0.0, -0.0]], + ids=["no edges", "zero", "ints that cancel", "floats that cancel", "halves", "zeros"], +) +def test_weights_that_sum_to_zero(weights): + """ZeroDivisionError normalized; otherwise int 0 for every node of G, nodelist or not.""" + G = nx.Graph() + G.add_nodes_from([3, 0]) + G.add_weighted_edges_from((i, i + 1, w) for i, w in enumerate(weights)) + raised(G, ZeroDivisionError, "zero full energy") + got, _ = served(G, normalized=False, exact=True) + assert got == dict.fromkeys(G, 0) + assert all(type(value) is int for value in got.values()) + got, _ = served(G, normalized=False, nodelist=[9, 9], exact=True) + assert list(got) == list(G) + + +def test_a_self_loop_is_in_the_weight_sum(): + """NetworkX's size is half the weighted degree sum, where a self-loop counts twice.""" + G = nx.Graph() + G.add_weighted_edges_from([(0, 0, 2), (1, 2, -2)]) + raised(G, ZeroDivisionError) + G = nx.Graph() + G.add_weighted_edges_from([(0, 0, 1), (1, 2, -2)]) + served(G, exact=True) + + +def test_weights_that_nearly_cancel_are_left_to_networkx(): + """0.1 + 0.2 - 0.3 is not 0 in floats, and whether a sum is depends on its order.""" + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 0.1), (1, 2, 0.2), (2, 3, -0.3)]) + left_to_networkx(G, "nearly cancel", normalized=False) + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 0.1), (1, 2, 0.2), (2, 3, -0.5)]) + served(G, normalized=False) + + +def test_large_integer_valued_float_weights(): + """Past 2**53 an integer-valued float sum may round, so its order may matter.""" + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 2.0**60), (1, 2, -(2.0**60)), (2, 3, 1.0)]) + left_to_networkx(G, "nearly cancel", normalized=False) + + +@pytest.mark.parametrize( + "weights", + [[2.0**60, -(2.0**60), 2.0**12], [0.375, -0.125, -0.25], [2.0**1000, -(2.0**1000)]], + ids=["large multiples of 2**12", "eighths", "huge"], +) +def test_weights_whose_sum_is_exact_in_any_order(weights): + """Multiples of one power of 2 whose sizes sum to less than 2**52 of it: an exact sum. + + The huge weights sum to 0, which NetworkX finds before their squares overflow. + """ + G = nx.Graph() + G.add_weighted_edges_from((i, i + 1, w) for i, w in enumerate(weights)) + if sum(weights) == 0: + raised(G, ZeroDivisionError) + served(G, normalized=False, exact=True) + else: + served(G, normalized=False) + + +def test_weights_whose_sizes_overflow_are_left_to_networkx(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, 1e308), (1, 2, 1e308), (2, 3, -1e308), (3, 4, -1e308)]) + left_to_networkx(G, "nearly cancel") + + +@pytest.mark.parametrize( + "weight", + [float("nan"), float("inf"), -float("inf"), 1e200], + ids=["nan", "inf", "-inf", "square overflows"], +) +def test_a_non_finite_energy_is_left_to_networkx(weight): + G = nx.Graph() + G.add_weighted_edges_from([(0, 1, weight), (1, 2, 3.0), (3, 4, 1.0)]) + left_to_networkx(G, "Laplacian energy is") + left_to_networkx(G, "Laplacian energy is", normalized=False) + + +def test_a_non_finite_self_loop_is_left_to_networkx(): + G = nx.Graph() + G.add_weighted_edges_from([(0, 0, float("nan")), (1, 2, 3.0)]) + left_to_networkx(G, "Laplacian energy is") + + +@pytest.mark.parametrize( + "nodelist", + [[3, 1], [4, 3, 2, 1, 0], [], [1.0], [2, True]], + ids=["some", "all reversed", "empty", "1.0 for 1", "True for 1"], +) +def test_nodelist(nodelist): + """The keys are nodelist's items, in its order; the values are for the whole graph.""" + G = nx.path_graph(5) + got, _ = served(G, nodelist=nodelist, exact=True) + assert list(got) == nodelist + assert [type(key) for key in got] == [type(node) for node in nodelist] + + +@pytest.mark.parametrize( + "nodelist", + [[1, 9], [1, 1], [1, 1.0], [True, 1], [None]], + ids=["missing", "repeated", "1 and 1.0", "True and 1", "None"], +) +def test_a_bad_nodelist(nodelist): + raised( + nx.path_graph(5), nx.NetworkXError, "duplicate nodes or nodes not in G", nodelist=nodelist + ) + + +@pytest.mark.parametrize( + "nodelist", + [(1, 2), iter([1]), np.array([1, 2]), [1, [2]], "ab"], + ids=["tuple", "iterator", "array", "unhashable", "string"], +) +def test_a_nodelist_that_is_not_a_list_of_nodes_is_left_to_networkx(nodelist): + G = nx.path_graph(5) + G.add_node("ab") + if isinstance(nodelist, list): + left_to_networkx(G, "unhashable", nodelist=nodelist) + else: + reason = "nodelist; networkx serves it" + from graphblas_algorithms.interface import Dispatcher + + assert reason in Dispatcher.can_run("laplacian_centrality", (G,), {"nodelist": nodelist}) + + +def test_an_unhashable_node_is_declined_before_conversion(): + from graphblas_algorithms.interface import Dispatcher + + reason = Dispatcher.can_run("laplacian_centrality", (nx.path_graph(3),), {"nodelist": [[1]]}) + assert "unhashable" in reason + + +def test_a_directed_graph_is_left_to_networkx(): + from graphblas_algorithms.interface import Dispatcher + + G = nx.DiGraph([(0, 1), (1, 2), (2, 0), (2, 3)]) + assert "directed" in Dispatcher.can_run("laplacian_centrality", (G,), {}) + with graphblas_first(): + got = nx.laplacian_centrality(G) + # NetworkX's own answer moves in the last bits from call to call: its directed Laplacian is + # from an eigenvector ARPACK finds from a random start. + assert got == pytest.approx(nx.laplacian_centrality(G, backend="networkx"), rel=1e-9) + from graphblas_algorithms.nxapi import laplacian_centrality + + with pytest.raises(NotImplementedError, match="directed"): + laplacian_centrality(G) + + +def test_walk_type_and_alpha_are_ignored_for_an_undirected_graph(): + G = nx.path_graph(5) + served(G, walk_type="bad", alpha=5, exact=True) + + +def test_weight_names(): + G = nx.Graph() + G.add_edge(0, 1, weight=2, w=5) + G.add_edge(1, 2, w=-1) + for weight in ("weight", "w", "absent", None): + served(G, weight=weight, normalized=False, exact=True) + + +def test_bool_weights(): + G = nx.Graph() + G.add_edge(0, 1, weight=True) + G.add_edge(1, 2, weight=True) + G.add_edge(2, 3, weight=False) + served(G, exact=True) + served(G, normalized=False, exact=True) + + +@pytest.mark.filterwarnings("ignore:Casting complex values to real") +@pytest.mark.parametrize("weight", [1 + 2j, 1 + 0j, np.complex64(2 - 1j)]) +def test_complex_weights_are_left_to_networkx(weight): + import graphblas_algorithms as ga + from graphblas_algorithms import nxapi + + G = nx.path_graph(3) + nx.set_edge_attributes(G, weight, "weight") + reason = "Edge attribute 'weight' has complex values; networkx serves the call" + left_to_networkx(G, reason) + left_to_networkx(G, reason, normalized=False) + G.add_edge(2, 3, weight=4) # one complex weight makes the conversion complex + left_to_networkx(G, reason, nodelist=[3, 1]) + with pytest.raises(NotImplementedError, match="complex values"): + nxapi.laplacian_centrality(ga.Graph.from_networkx(G, weight="weight")) + # A call that reads another attribute, or none, sees no complex value, even when NetworkX + # serves it the complex conversion it cached. + served(G, weight="w", exact=True) + served(G, weight=None, exact=True) + + +def test_a_multigraph_is_left_to_networkx(): + from graphblas_algorithms.interface import Dispatcher + + G = nx.MultiGraph([(0, 1), (0, 1), (1, 2)]) + assert isinstance(Dispatcher.can_run("laplacian_centrality", (G,), {}), str) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 769a039..251b037 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -163,6 +163,7 @@ def call_args(kind, args): "k_shell": ("undirected", ()), "k_truss": ("undirected", (3,)), "katz_centrality": ("undirected", ()), + "laplacian_centrality": ("undirected", ()), "laplacian_matrix": ("undirected", ()), "local_efficiency": ("undirected", ()), "lowest_common_ancestor": ("dag", (1, 2)),