diff --git a/README.md b/README.md index 75a0ddb..42a6920 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,7 @@ graphblas_algorithms.nxapi │ │ └── is_partition │ └── quality │ ├── inter_community_edges +│ ├── inter_community_non_edges │ ├── intra_community_edges │ ├── modularity │ ├── overlapping_modularity @@ -247,6 +248,8 @@ graphblas_algorithms.nxapi │ └── resource_allocation_index ├── lowest_common_ancestors │ └── lowest_common_ancestor +├── moral +│ └── moral_graph ├── operators │ ├── binary │ │ ├── compose diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 509261e..36c1514 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -91,6 +91,7 @@ def get_info(): "hyper_wiener_index", "in_degree_centrality", "inter_community_edges", + "inter_community_non_edges", "intersection", "intra_community_edges", "is_arborescence", @@ -126,6 +127,7 @@ def get_info(): "mixing_expansion", "modularity", "modularity_matrix", + "moral_graph", "mutual_weight", "negative_edge_cycle", "node_boundary", @@ -221,6 +223,8 @@ def get_info(): "harmonic_diameter": 'A precomputed `sp` 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".', "hits": 'A graph with nodes and no edges gets 0.0 for every node, where NetworkX\'s power\niteration does not converge. `method="svd"` is left to NetworkX.', "hyper_wiener_index": "Raises 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.", + "inter_community_edges": "A `partition` given as a function, or as an iterator, is left to NetworkX.", + "inter_community_non_edges": "A `partition` given as a function, or as an iterator, is left to NetworkX.", "k_core": "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_corona": "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_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.", @@ -231,6 +235,7 @@ def get_info(): "maximum_spanning_tree": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nAlso left to NetworkX: a graph whose edges carry more than one attribute, or the weight\non some edges only, and one of fewer than 800000 edges, where NetworkX is faster.', "minimum_spanning_edges": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nThe edges come lightest first (heaviest first for the maximum), and a NaN weight raises\nwhen they are first asked for, naming one NaN edge. With `data=True`, also left to\nNetworkX: a graph whose edges carry more than one attribute, or the weight on some edges\nonly, and one of fewer than 800000 edges (200000 with `data=False`), where NetworkX is\nfaster.', "minimum_spanning_tree": 'Where weights tie, the forest may differ from NetworkX\'s whichever `algorithm` is named;\nits total weight is the same. Equal weights are taken by their ends in node order, on\nevery platform; Kruskal takes them in `G.edges()` order, so its forest is the same where\neach node\'s neighbors were added in node order. Left to NetworkX: an int past 2**53 held\nas a float that ties another weight, complex weights, an infinite weight with Boruvka\n(which leaves such an edge out), and a NaN self-loop with `algorithm="prim"`.\nAlso left to NetworkX: a graph whose edges carry more than one attribute, or the weight\non some edges only, and one of fewer than 800000 edges, where NetworkX is faster.', + "moral_graph": "Built from the NetworkX graph given, as NetworkX builds it, so it keeps that graph's\ndata; most of the time goes to building it. A graph of this backend's own, or a\nconversion that was copied or unpickled, is left to NetworkX, as is a graph with fewer\nthan 5 pairs of parents (two predecessors of one node) for each edge, where NetworkX\nis faster.", "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.', "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.', diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index f83f248..703f9cf 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -118,6 +118,8 @@ "faster." ) +_PARTITION_READ = "A `partition` given as a function, or as an iterator, is left to NetworkX." + # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. _ADDITIONAL_DOCS = { @@ -182,6 +184,8 @@ 'iteration does not converge. `method="svd"` is left to NetworkX.' ), "hyper_wiener_index": _LENGTH_SUM_OVERFLOW, + "inter_community_edges": _PARTITION_READ, + "inter_community_non_edges": _PARTITION_READ, "k_core": _CORE_SUBGRAPH, "k_corona": _CORE_SUBGRAPH, "k_crust": _CORE_SUBGRAPH, @@ -195,6 +199,13 @@ "maximum_spanning_tree": _SPANNING + "\n" + _SPANNING_DATA, "minimum_spanning_edges": _SPANNING + "\n" + _SPANNING_EDGES, "minimum_spanning_tree": _SPANNING + "\n" + _SPANNING_DATA, + "moral_graph": ( + "Built from the NetworkX graph given, as NetworkX builds it, so it keeps that graph's\n" + "data; most of the time goes to building it. A graph of this backend's own, or a\n" + "conversion that was copied or unpickled, is left to NetworkX, as is a graph with fewer\n" + "than 5 pairs of parents (two predecessors of one node) for each edge, where NetworkX\n" + "is faster." + ), "negative_edge_cycle": _PATH_OVERFLOW, "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, diff --git a/graphblas_algorithms/algorithms/__init__.py b/graphblas_algorithms/algorithms/__init__.py index 4fda5b3..aa01888 100644 --- a/graphblas_algorithms/algorithms/__init__.py +++ b/graphblas_algorithms/algorithms/__init__.py @@ -15,6 +15,7 @@ from .link_analysis import * from .link_prediction import * from .lowest_common_ancestors import * +from .moral import * from .operators import * from .reciprocity import * from .regular import * diff --git a/graphblas_algorithms/algorithms/community/quality.py b/graphblas_algorithms/algorithms/community/quality.py index c516a15..de6882b 100644 --- a/graphblas_algorithms/algorithms/community/quality.py +++ b/graphblas_algorithms/algorithms/community/quality.py @@ -5,6 +5,7 @@ __all__ = [ "inter_community_edges", + "inter_community_non_edges", "intra_community_edges", "modularity", "overlapping_modularity", @@ -40,6 +41,28 @@ def inter_community_edges(G, partition): return count +def inter_community_non_edges(G, S): + """The pairs of nodes in different blocks of a partition that `G` does not join. + + `S` is node by block, with a 1 for each node in its block; a node no block holds is not + counted. Ordered pairs in a directed graph, unordered in an undirected one. + """ + A = G._A + sizes = S.reduce_columnwise(monoid.plus).new() + held = int(sizes.reduce(monoid.plus).get(0)) + across = held * held - int(sizes.ewise_mult(sizes, binary.times).reduce(monoid.plus).get(0)) + # Each node's neighbors in each block. A held node's neighbors in other blocks are its + # edges across, and a self-loop is counted in both sums. + T = plus_pair(A @ S).new() + held_nodes = S.reduce_rowwise(monoid.any).new() + reached = int(T.reduce_rowwise(monoid.plus).new(mask=held_nodes.S).reduce(monoid.plus).get(0)) + inside = int(T.dup(mask=S.S).reduce_scalar(monoid.plus).get(0)) + count = across - (reached - inside) + if not G.is_directed(): + count //= 2 # an edge is stored at both ends and a pair counted from both + return count + + def _inside(A, S, weighted): """The values of `A` between members of one community, each weighed by `S` at both ends. diff --git a/graphblas_algorithms/algorithms/moral.py b/graphblas_algorithms/algorithms/moral.py new file mode 100644 index 0000000..9d3c389 --- /dev/null +++ b/graphblas_algorithms/algorithms/moral.py @@ -0,0 +1,36 @@ +from graphblas import Matrix, binary, select +from graphblas.semiring import any_pair + +from graphblas_algorithms import Graph + +__all__ = ["co_parents", "moral_graph"] + + +def co_parents(G): + """The pairs of nodes that share a child and that `G` does not join, either way. + + A Matrix of the node ids, each pair once as `(i, j)` with `i < j`. A child's parents are + its column of `A`, so `A @ A.T` pairs them; the mask leaves out the pairs `A` already + joins, and a node's pair with itself. + """ + A = G._A + AT = G.get_property("AT") + joined = Matrix(bool, A.nrows, A.ncols) + joined(A.S) << True + joined(AT.S) << True + pairs = any_pair[bool](A @ AT).new(mask=~joined.S) + return select.triu(pairs, 1).new() + + +def moral_graph(G): + """`G` without directions, with each pair of nodes that share a child joined. + + An undirected graph of the structure alone: its values are all True, and name no attribute. + """ + A = G._A + pairs = co_parents(G) + M = Matrix(bool, A.nrows, A.ncols) + for edges in (A, G.get_property("AT"), pairs): + M(edges.S) << True + M(binary.any) << pairs.T + return Graph(M, key_to_id=G._key_to_id, weight=None) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index fe24099..a2d4808 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -23,7 +23,7 @@ # Graph-returning names whose result is built from the NetworkX graph a conversion came from, # so that it keeps that graph's own data, nodes' included; the matrix gives only the weights. -_BUILT_FROM_SOURCE = frozenset({"maximum_spanning_tree", "minimum_spanning_tree"}) +_BUILT_FROM_SOURCE = frozenset({"maximum_spanning_tree", "minimum_spanning_tree", "moral_graph"}) @functools.cache @@ -56,7 +56,7 @@ def _declared(name): if name == "ego_graph": # It keeps every edge attribute, so it declares none, yet `distance` names one. attribute_parameters = ("distance",) - elif name in _BUILT_FROM_SOURCE: + elif name in {"maximum_spanning_tree", "minimum_spanning_tree"}: attribute_parameters = ("weight",) # the same: they keep every attribute, read one # NetworkX before 3.7 declares no preserve flags for `reverse`, whose result keeps its data. rebuilds_input = ( @@ -282,6 +282,7 @@ class Dispatcher: is_cover = mod.community_utils.is_cover is_partition = mod.community_utils.is_partition inter_community_edges = mod.quality.inter_community_edges + inter_community_non_edges = mod.quality.inter_community_non_edges intra_community_edges = mod.quality.intra_community_edges modularity = mod.quality.modularity overlapping_modularity = mod.quality.overlapping_modularity @@ -384,6 +385,10 @@ class Dispatcher: # ================================= lowest_common_ancestor = mod.lowest_common_ancestor + mod = nxapi.moral + # =============== + moral_graph = mod.moral_graph + mod = nxapi.operators # =================== compose = mod.binary.compose diff --git a/graphblas_algorithms/nxapi/__init__.py b/graphblas_algorithms/nxapi/__init__.py index 9c65650..f30f9c8 100644 --- a/graphblas_algorithms/nxapi/__init__.py +++ b/graphblas_algorithms/nxapi/__init__.py @@ -16,6 +16,7 @@ from .link_analysis import * from .link_prediction import * from .lowest_common_ancestors import * +from .moral import * from .operators import * from .reciprocity import * from .regular import * diff --git a/graphblas_algorithms/nxapi/community/quality.py b/graphblas_algorithms/nxapi/community/quality.py index 3697df2..61fc3ae 100644 --- a/graphblas_algorithms/nxapi/community/quality.py +++ b/graphblas_algorithms/nxapi/community/quality.py @@ -1,7 +1,10 @@ +from collections.abc import Iterator + from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph from graphblas_algorithms.utils import not_implemented_for +from .._utils import can_run from ..exception import NetworkXError, NetworkXException # is_cover and is_partition are found here too, as in NetworkX @@ -16,20 +19,53 @@ def intra_community_edges(G, partition): return algorithms.intra_community_edges(G, partition) -def inter_community_edges(G, partition): - G = to_graph(G) - # NetworkX counts on the graph restricted to the union of the blocks, which must then be - # split exactly: no node twice, and none the graph does not have +def _blocks_as_read(bound): + """Leave to NetworkX a `partition` that its `quotient_graph` reads as no list of blocks. + + A function is an equivalence relation, whose classes NetworkX finds. An iterator is read + twice there, once to find the nodes and once to check them, so the second reading finds + it empty, and NetworkX raises for nearly any graph. + """ + partition = bound["partition"] + if callable(partition): + return "A `partition` given as a relation is left to NetworkX; networkx serves it" + if isinstance(partition, Iterator): + return "NetworkX reads `partition` twice, and an iterator once; networkx serves it" + return None + + +def _blocks(G, partition): + """The blocks of `partition`, as NetworkX's `quotient_graph` reads them. + + A dict's blocks are its values. NetworkX counts on the graph restricted to the union of + the blocks, which must then be split exactly: no node twice, and none the graph does not + have. Its check is followed step by step, as it reads each block twice and takes the + blocks' lengths last, so a block that is a generator fails where it fails there. + """ + if isinstance(partition, dict): + partition = partition.values() partition = list(partition) covered = set().union(*partition) - if sum(len(block) for block in partition) != len(covered) or any( - node not in G for node in covered - ): + size = len(G) if len(covered) == len(G) else sum(node in G for node in covered) + named = {node for block in partition for node in block if node in G} + if not size == len(named) == sum(len(block) for block in partition): raise NetworkXException("each node must be in exactly one part of `partition`") - partition = [G.set_to_vector(block) for block in partition] + return partition + + +@can_run(_blocks_as_read) +def inter_community_edges(G, partition): + G = to_graph(G) + partition = [G.set_to_vector(block) for block in _blocks(G, partition)] return algorithms.inter_community_edges(G, partition) +@can_run(_blocks_as_read) +def inter_community_non_edges(G, partition): + G = to_graph(G) + return algorithms.inter_community_non_edges(G, _memberships(G, _blocks(G, partition))) + + def _not_a_partition(G, communities): try: from networkx.algorithms.community.quality import NotAPartition diff --git a/graphblas_algorithms/nxapi/moral.py b/graphblas_algorithms/nxapi/moral.py new file mode 100644 index 0000000..30d6c32 --- /dev/null +++ b/graphblas_algorithms/nxapi/moral.py @@ -0,0 +1,85 @@ +import numpy as np + +from graphblas_algorithms import algorithms +from graphblas_algorithms.classes._utils import source_of +from graphblas_algorithms.classes.digraph import to_directed_graph +from graphblas_algorithms.utils import not_implemented_for + +from ._utils import should_run + +__all__ = ["moral_graph"] + +# Below this many pairs of parents (two predecessors of one node) for each edge, NetworkX's loop +# over the pairs costs less than converting the graph does; the two cross between 4 and 5 on +# random graphs of 1e4 to 6e5 edges (Indicative). +_FEWEST_PARENT_PAIRS_PER_EDGE = 5 + + +def _decline(reason): + raise NotImplementedError(f"{reason}; networkx serves it") + + +def _few_parent_pairs(bound): + pred = getattr(bound["G"], "_pred", None) + if pred is None: + return None + # NetworkX's loop takes every pair of each node's predecessors, as here. + indegree = np.fromiter(map(len, pred.values()), np.int64) + pairs = int((indegree * (indegree - 1) // 2).sum()) + if pairs < _FEWEST_PARENT_PAIRS_PER_EDGE * int(indegree.sum()): + return ( + f"networkx is faster below {_FEWEST_PARENT_PAIRS_PER_EDGE} pairs of parents for each " + "edge, with no conversion to pay" + ) + return None + + +def _join(adj, rows, cols, data, id_to_key): + """Give each node `rows[k]` the neighbor `cols[k]` with the data dict `data[k]`. + + `rows` is sorted, so each node's new neighbors go in with one `dict.update`. + """ + nbrs = [id_to_key[col] for col in cols.tolist()] + bounds = np.append(np.flatnonzero(np.diff(rows, prepend=-1)), len(rows)).tolist() + starts = bounds[:-1] + for row, start, stop in zip(rows[starts].tolist(), starts, bounds[1:], strict=True): + adj[id_to_key[row]].update(zip(nbrs[start:stop], data[start:stop], strict=True)) + + +@should_run(_few_parent_pairs) +@not_implemented_for("undirected") +def moral_graph(G): + import networkx as nx + + if G.is_multigraph(): + _decline("graphblas-algorithms does not support multigraphs") + # NetworkX's answer is its graph's `to_undirected()`, which copies the graph's, nodes' and + # edges' data, with the pairs that share a child joined where they were not. The matrix + # holds none of that data, so the answer starts from the NetworkX graph itself: a direct + # call's, or the one the conversion was made from. + source = G if isinstance(G, nx.Graph) else source_of(G) + if source is None: + _decline( + "The moral graph carries the data of the NetworkX graph it is taken from, and this " + "graph was not converted from one that is still alive" + ) + G = to_directed_graph(G) + rows, cols, _ = algorithms.co_parents(G).to_coo(values=False) + H = source.to_undirected() + if type(H) is not nx.Graph: + # A subclass may build its edges its own way, so it is asked to. + id_to_key = G.id_to_key + us = [id_to_key[row] for row in rows.tolist()] + H.add_edges_from(zip(us, [id_to_key[col] for col in cols.tolist()], strict=True)) + return H + # As `add_edges_from` joins them: an empty dict for each new edge, the same in both + # directions. Each node is reached in both passes, as a row in one of them. + data = [{} for _ in range(len(rows))] + order = np.argsort(cols, kind="stable") # by column, and by row within one + try: + _join(H._adj, rows, cols, data, G.id_to_key) + _join(H._adj, cols[order], rows[order], [data[k] for k in order.tolist()], G.id_to_key) + except KeyError: + # A view's conversion is not dropped when a node leaves the graph under it. + _decline("The graph has changed since it was converted") + return H diff --git a/graphblas_algorithms/nxapi/tests/test_community.py b/graphblas_algorithms/nxapi/tests/test_community.py index 04ba284..d104ae0 100644 --- a/graphblas_algorithms/nxapi/tests/test_community.py +++ b/graphblas_algorithms/nxapi/tests/test_community.py @@ -21,10 +21,13 @@ } -@pytest.mark.parametrize("name", ["inter_community_edges", "intra_community_edges"]) +INTER = ["inter_community_edges", "inter_community_non_edges"] + + +@pytest.mark.parametrize("name", [*INTER, "intra_community_edges"]) @pytest.mark.parametrize("make", SHAPES.values(), ids=SHAPES) def test_community_edge_counts_follow_networkx(make, name): - """An undirected edge is counted once, and a self-loop in its block.""" + """An undirected edge or pair is counted once, and a self-loop in its block.""" func = getattr(quality, name) partition = [{0, 1}, {2, 3}] assert func(make(), partition, backend="graphblas") == func(make(), partition) @@ -66,14 +69,108 @@ def _outcome(func, *args, **kwargs): ], ) @pytest.mark.parametrize("make", [nx.Graph, nx.DiGraph]) -def test_inter_community_edges_follows_networkx(make, partition): +@pytest.mark.parametrize("name", INTER) +def test_inter_community_counts_follow_networkx(name, make, partition): """The graph is restricted to the union of the blocks, which must then be a partition.""" - func = quality.inter_community_edges + func = getattr(quality, name) triangle = [(0, 1), (1, 2), (2, 0)] expected = _outcome(func, make(triangle), partition()) assert _outcome(func, make(triangle), partition(), backend="graphblas") == expected +# How NetworkX's `quotient_graph` reads a `partition` that is no list of sets. +PARTITION_SHAPES = { + "a tuple of frozensets": (lambda: (frozenset({0, 1}), frozenset({2, 3, 4})), True), + "lists": (lambda: [[0, 1], [2, 3, 4]], True), + "a dict's values": (lambda: {"a": {0, 1}, "b": {2, 3, 4}}, True), + "a dict naming a node as a block": (lambda: {0: {1, 2}, 3: {0, 4}}, True), + "a dict, its values not a partition": (lambda: {0: {0, 1}, 1: {1, 2, 3, 4}}, True), + "dict values": ({"a": {0, 1}, "b": {2, 3, 4}}.values, True), + "a set of frozensets": (lambda: {frozenset({0, 1}), frozenset({2, 3, 4})}, True), + "strings as blocks": (lambda: ["ab", "cd"], True), + "a generator": (lambda: (block for block in [{0, 1}, {2, 3, 4}]), False), + "an iterator": (lambda: iter([{0, 1}, {2, 3, 4}]), False), + "an iterator of absent nodes": (lambda: iter([{9}]), False), + "an iterator of empty blocks": (lambda: iter([set(), set()]), False), + "a relation": (lambda: lambda u, v: (u in {0, 1, "a", "b"}) == (v in {0, 1, "a", "b"}), False), + "a block of unhashable members": (lambda: [[{0}], [2]], True), + "a block that is not iterable": (lambda: [{0, 1}, 2], True), + "a block without a length": (lambda: [{0, 1}, (n for n in [2, 3, 4])], True), + # NetworkX counts the graph's nodes among the blocks' before it asks for their lengths. + "a block without a length, of an absent node": (lambda: [{0, 1}, (n for n in [9])], True), +} + + +@pytest.mark.parametrize("make", [nx.Graph, nx.DiGraph]) +@pytest.mark.parametrize("shape", PARTITION_SHAPES) +@pytest.mark.parametrize("name", INTER) +def test_a_partition_is_read_as_networkx_reads_it(name, shape, make): + """A dict's blocks are its values. A relation, or an iterator, is left to NetworkX.""" + func = getattr(quality, name) + partition, served = PARTITION_SHAPES[shape] + graph = make([(0, 1), (1, 2), (2, 3), (3, 4), (4, 0), (0, 2), (1, 1)]) + if shape == "strings as blocks": + graph = nx.relabel_nodes(graph, dict(enumerate("abcde"))) + expected = _outcome(func, graph, partition()) + with nx.config(fallback_to_nx=False), nx.config.backend_priority(algos=["graphblas"]): + assert _outcome(func, graph, partition()) == expected + from graphblas_algorithms.interface import Dispatcher + + assert (Dispatcher.can_run(name, (graph, partition()), {}) is True) == served + if served: + assert _outcome(func, graph, partition(), backend="graphblas") == expected + + +def _random_partition_case(seed): + """A graph, with self-loops and isolated nodes, and a partition of some or all its nodes.""" + rng = np.random.default_rng(seed) + n = int(rng.choice([0, 1, 2, 3, 5, 8, 20, 50])) + p = float(rng.choice([0.0, 0.1, 0.3, 0.7, 1.0])) + G = nx.gnp_random_graph(n, p, seed=seed, directed=bool(seed % 2)) + G.add_edges_from((v, v) for v in G if rng.random() < 0.2) + if seed % 3 == 0: + G = nx.relabel_nodes(G, {v: f"n{v}" for v in G if v % 2}) + nodes = list(G) + held = [v for v in nodes if rng.random() < 0.8] if seed % 4 == 0 else nodes + k = int(rng.integers(1, len(held) + 2)) if held else int(rng.integers(0, 2)) + labels = rng.integers(0, k, len(held)) if k else [] + blocks = [{v for v, label in zip(held, labels, strict=True) if label == b} for b in range(k)] + container = seed % 5 + if container == 1: + blocks = [sorted(block, key=str) for block in blocks] + elif container == 2: + blocks = tuple(map(frozenset, blocks)) + elif container == 3: + blocks = {f"b{b}": block for b, block in enumerate(blocks)} + return G, blocks + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs_and_partitions_follow_networkx(seed): + G, partition = _random_partition_case(seed) + for name in INTER: + func = getattr(quality, name) + expected = func(G, partition) + got = func(G, partition, backend="graphblas") + assert type(got) is int + assert got == expected, name + + +@pytest.mark.parametrize("directed", [False, True]) +def test_non_edges_count_every_pair_across(directed): + """No edges: every pair of nodes in different blocks, once a pair or once each way.""" + G = nx.empty_graph(10, create_using=nx.DiGraph if directed else nx.Graph) + partition = [set(range(3)), set(range(3, 7)), {7}, {8, 9}] + pairs = 3 * 4 + 3 * 1 + 3 * 2 + 4 * 1 + 4 * 2 + 1 * 2 + expected = 2 * pairs if directed else pairs + assert quality.inter_community_non_edges(G, partition, backend="graphblas") == expected + assert quality.inter_community_non_edges(G, partition) == expected + G.add_edges_from([(0, 3), (3, 0), (7, 8), (0, 1), (9, 9)]) + expected -= 3 if directed else 2 + assert quality.inter_community_non_edges(G, partition, backend="graphblas") == expected + assert quality.inter_community_non_edges(G, partition) == expected + + def backend(G, **kwargs): return (ga.DiGraph if G.is_directed() else ga.Graph).from_networkx(G, **kwargs) diff --git a/graphblas_algorithms/nxapi/tests/test_moral.py b/graphblas_algorithms/nxapi/tests/test_moral.py new file mode 100644 index 0000000..c2793c3 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_moral.py @@ -0,0 +1,333 @@ +"""`moral_graph` as NetworkX builds it: its graph's data copied, with co-parents joined.""" + +import copy + +import networkx as nx +import numpy as np +import pytest +from graphblas import monoid + +import graphblas_algorithms as ga +from graphblas_algorithms import algorithms, nxapi +from graphblas_algorithms.interface import Dispatcher +from graphblas_algorithms.nxapi import moral + +pytestmark = pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs") + + +@pytest.fixture(autouse=True) +def _any_graph(monkeypatch): + """Serve every graph on the automatic path too, which `should_run` may leave to NetworkX.""" + monkeypatch.setattr(moral, "_FEWEST_PARENT_PAIRS_PER_EDGE", 0) + + +def assert_same(got, expected, G): + """NetworkX's graph, data and class, with copies of `G`'s data as NetworkX makes them.""" + assert type(got) is type(expected) + assert got.graph == expected.graph + assert list(got) == list(expected) + assert got._node == expected._node + assert got._adj == expected._adj + # One dict for each edge, the same in both directions, as `add_edges_from` gives. + seen = {} + for u, nbrs in got._adj.items(): + for v, data in nbrs.items(): + assert type(data) is type(expected._adj[u][v]) + assert got._adj[v][u] is data + assert seen.setdefault(id(data), frozenset((u, v))) == frozenset((u, v)) + # Deep copies: no dict or value of `G`'s is the result's. + assert got.graph is not G.graph + assert "obj" not in got.graph or got.graph["obj"] is not G.graph["obj"] + for node, data in got._node.items(): + assert data is not G._node[node] + assert "obj" not in data or data["obj"] is not G._node[node]["obj"] + for u, v, data in got.edges(data=True): + for a, b in ((u, v), (v, u)): + if b in G._adj.get(a, {}): + assert data is not G._adj[a][b] + assert data.get("obj") is None or data["obj"] is not G._adj[a][b].get("obj") + + +def _pick(rng, items): + """One of `items` itself, not a NumPy copy of it.""" + return items[int(rng.integers(len(items)))] + + +def _keys(rng, n): + kind = _pick(rng, ["int", "str", "tuple", "mixed"]) + if kind == "int": + keys = rng.choice(10 * n + 10, n, replace=False).tolist() + elif kind == "str": + keys = [f"n{i}" for i in range(n)] + elif kind == "tuple": + keys = [(i, i % 3) for i in range(n)] + else: + keys = [i if i % 2 else f"n{i}" for i in range(n)] + return [keys[i] for i in rng.permutation(n).tolist()] + + +def _data(rng, seed): + """Edge or node data: none, a weight, or several values with a list among them.""" + kind = rng.random() + if kind < 0.4: + return {} + if kind < 0.7: + return {"weight": _pick(rng, [1, 2.5, -3, 0.0, True])} + return { + "weight": float(rng.random()), + "obj": [seed, float(rng.random())], + "tag": _pick(rng, "abc"), + } + + +def random_digraph(seed): + """A directed graph with self-loops, isolated nodes, two-way edges and data of each kind.""" + rng = np.random.default_rng(seed) + n = _pick(rng, [0, 1, 2, 3, 5, 8, 13, 21, 34]) + keys = _keys(rng, n) + G = nx.DiGraph() + if rng.random() < 0.5: + G.graph.update(name=f"g{seed}", obj=[seed]) + for key in keys: + G.add_node(key, **_data(rng, seed)) + shape = _pick(rng, ["gnp", "dag", "parents", "two-way"]) + p = _pick(rng, [0.05, 0.15, 0.4, 0.8]) + order = {key: i for i, key in enumerate(keys)} + for u in keys: + for v in keys: + if u == v: + if rng.random() < 0.1: + G.add_edge(u, v, **_data(rng, seed)) + elif (shape == "dag" and order[u] > order[v]) or (shape == "parents" and order[v] >= 3): + continue # acyclic, or few children with many parents + elif rng.random() < p: + G.add_edge(u, v, **_data(rng, seed)) + if shape == "two-way" and rng.random() < 0.5: + G.add_edge(v, u, **_data(rng, seed)) + return G + + +@pytest.mark.parametrize("seed", range(330)) +def test_random_graphs_follow_networkx(seed): + G = random_digraph(seed) + expected = nx.moral_graph(G, backend="networkx") + assert_same(nx.moral_graph(G, backend="graphblas"), expected, G) + # Again, on the conversion NetworkX cached for the first call. + assert_same(nx.moral_graph(G, backend="graphblas"), expected, G) + + +@pytest.mark.parametrize("seed", range(0, 330, 11)) +def test_a_conversion_cached_for_another_name_serves_it(seed): + """The weighted conversion `pagerank` caches is the one the answer is built beside.""" + G = random_digraph(seed) + expected = nx.moral_graph(G, backend="networkx") + try: + nx.pagerank(G, backend="graphblas") # converts, and caches, before it runs + except (nx.PowerIterationFailedConvergence, nx.NetworkXException): + pass + assert len(G) == 0 or G.__networkx_cache__["backends"]["graphblas"] + assert_same(nx.moral_graph(G, backend="graphblas"), expected, G) + + +@pytest.mark.parametrize("seed", range(0, 330, 11)) +def test_served_on_the_automatic_path(seed): + G = random_digraph(seed) + expected = nx.moral_graph(G, backend="networkx") + with nx.config(fallback_to_nx=False), nx.config.backend_priority(generators=["graphblas"]): + got = nx.moral_graph(G) + assert_same(got, expected, G) + + +@pytest.mark.parametrize("seed", range(0, 330, 11)) +def test_a_direct_call_builds_from_the_graph_given(seed): + G = random_digraph(seed) + assert_same(nxapi.moral_graph(G), nx.moral_graph(G, backend="networkx"), G) + + +def test_parents_of_a_child_are_joined_and_the_rest_kept(): + G = nx.DiGraph(name="g") + G.add_node(0, colour="red", obj=[1, 2]) + G.add_edge(1, 0, w=1, a="x") + G.add_edge(0, 1, w=2, b="y") # two-way: the later direction's values win, as NetworkX's + G.add_edge(2, 0, w=3) # 1 and 2 share 0, and are joined already + G.add_edge(1, 2, w=9) + G.add_edges_from([(3, 4), (5, 4), (6, 4)]) # 3, 5 and 6 share 4 + G.add_edge(4, 4, loop=True) # 4 is its own parent, already joined to the others + got = nx.moral_graph(G, backend="graphblas") + assert_same(got, nx.moral_graph(G, backend="networkx"), G) + assert got.edges[0, 1] == {"w": 1, "a": "x", "b": "y"} + assert got.edges[1, 2] == {"w": 9} + assert got.edges[4, 4] == {"loop": True} + assert {frozenset(e) for e in got.edges(3)} == {frozenset(e) for e in [(3, 4), (3, 5), (3, 6)]} + assert got.edges[3, 5] == {} + + +def test_the_new_edges_are_bare_and_their_own(): + G = nx.DiGraph([(0, 9), (1, 9), (2, 9)]) + got = nx.moral_graph(G, backend="graphblas") + new = [got._adj[u][v] for u, v in [(0, 1), (0, 2), (1, 2)]] + assert new == [{}, {}, {}] + assert len({id(data) for data in new}) == 3 + got.edges[0, 1]["x"] = 1 + assert got.edges[1, 0] == {"x": 1} + assert got.edges[0, 2] == {} + + +@pytest.mark.parametrize("make", [nx.Graph, nx.MultiGraph]) +def test_an_undirected_graph_raises_as_in_networkx(make): + G = make([(0, 1)]) + with pytest.raises(nx.NetworkXNotImplemented, match="not implemented for undirected type"): + nx.moral_graph(G, backend="graphblas") + with pytest.raises(nx.NetworkXNotImplemented, match="not implemented for undirected type"): + nxapi.moral_graph(G) + + +def _declined(exc): + """The reason this backend gave, which NetworkX keeps as the cause of its own error.""" + messages = [] + while exc is not None: + messages.append(str(exc)) + exc = exc.__cause__ + return " ".join(messages) + + +def test_a_multigraph_is_left_to_networkx(): + G = nx.MultiDiGraph([(0, 2), (1, 2), (0, 2)]) + assert isinstance(Dispatcher.can_run("moral_graph", (G,), {}), str) + expected = nx.moral_graph(G, backend="networkx") + with nx.config(fallback_to_nx=False), nx.config.backend_priority(generators=["graphblas"]): + got = nx.moral_graph(G) + assert type(got) is nx.MultiGraph + assert nx.utils.edges_equal( + got.edges(keys=True, data=True), expected.edges(keys=True, data=True) + ) + with pytest.raises(NotImplementedError, match="multigraphs"): + nxapi.moral_graph(G) + + +class EdgeData(dict): + pass + + +class SubGraph(nx.Graph): + edge_attr_dict_factory = EdgeData + + +class SubDiGraph(nx.DiGraph): + def to_undirected_class(self): + return SubGraph + + +def test_a_subclass_gets_networkx_s_answer(): + G = SubDiGraph([(0, 2, {"w": 1}), (1, 2)]) + expected = nx.moral_graph(G, backend="networkx") + assert type(expected) is SubGraph + assert type(expected.edges[0, 1]) is EdgeData + with nx.config(fallback_to_nx=False), nx.config.backend_priority(generators=["graphblas"]): + assert_same(nx.moral_graph(G), expected, G) + # Called directly, the subclass is asked to add the edges itself. + assert_same(nxapi.moral_graph(G), expected, G) + + +def test_this_backend_s_own_graph_is_declined(): + """It holds no NetworkX data to copy; NetworkX answers where it may fall back.""" + G = nx.DiGraph([(0, 2, {"weight": 2}), (1, 2)]) + B = ga.DiGraph.from_networkx(G, weight="weight") + with pytest.raises(NotImplementedError, match="not converted from one that is still alive"): + nxapi.moral_graph(B) + with nx.config(fallback_to_nx=False), pytest.raises(NotImplementedError): + nx.moral_graph(B) + with nx.config(fallback_to_nx=True): + got = nx.moral_graph(B) + assert type(got) is nx.Graph + assert got._adj == nx.moral_graph(B.to_networkx(), backend="networkx")._adj + + +def test_a_copied_conversion_is_declined_and_networkx_answers(): + """A copy's cache holds a copy of the conversion, which no NetworkX graph made.""" + G = nx.DiGraph([(0, 2, {"w": 1}), (1, 2), (3, 2)]) + G.add_node(0, colour="red") + nx.moral_graph(G, backend="graphblas") # caches the conversion + C = copy.deepcopy(G) + assert any(C.__networkx_cache__.get("backends", {}).values()) + with pytest.raises(NotImplementedError) as info: + nx.moral_graph(C, backend="graphblas") + assert "not converted from one that is still alive" in _declined(info.value) + with nx.config(fallback_to_nx=False), nx.config.backend_priority(generators=["graphblas"]): + assert_same(nx.moral_graph(C), nx.moral_graph(G, backend="networkx"), C) + + +def test_a_view_whose_graph_lost_a_node_is_declined(): + """NetworkX keeps a view's cached conversion when the graph under it changes.""" + G = nx.DiGraph([(0, 2), (1, 2), (3, 2), (4, 0)]) + view = G.subgraph([0, 1, 2, 3]) + nx.moral_graph(view, backend="graphblas") # caches the view's conversion + G.remove_node(1) # a co-parent + with pytest.raises(NotImplementedError) as info: + nx.moral_graph(view, backend="graphblas") + assert "changed since it was converted" in _declined(info.value) + with nx.config(fallback_to_nx=False), nx.config.backend_priority(generators=["graphblas"]): + got = nx.moral_graph(view) + assert_same(got, nx.moral_graph(view, backend="networkx"), view) + + +def test_views_are_built_from_the_view(): + G = random_digraph(7) + for view in (G.reverse(copy=False), G.subgraph(list(G)[::2])): + assert_same( + nx.moral_graph(view, backend="graphblas"), + nx.moral_graph(view, backend="networkx"), + view, + ) + + +@pytest.mark.parametrize("seed", range(0, 330, 5)) +def test_the_graphblas_moral_graph_is_the_structure(seed): + G = random_digraph(seed) + if not len(G): + return + B = ga.DiGraph.from_networkx(G) + M = algorithms.moral_graph(B) + assert not M.is_directed() + assert M._weight is None + assert M._A.dtype == bool + assert M._A.reduce_scalar(monoid.land).get(True) + expected = nx.moral_graph(G, backend="networkx") + got = M.to_networkx() + assert set(got) == set(expected) + assert {frozenset(e) for e in got.edges} == {frozenset(e) for e in expected.edges} + pairs = algorithms.co_parents(B) + rows, cols, _ = pairs.to_coo() + assert (rows < cols).all() + keys = B.id_to_key + for u, v in zip(rows.tolist(), cols.tolist(), strict=True): + assert not G.has_edge(keys[u], keys[v]) + assert not G.has_edge(keys[v], keys[u]) + assert pairs.nvals == expected.number_of_edges() - G.to_undirected().number_of_edges() + + +def _parents_of_one_child(k): + """`k` parents of one child: k edges and k * (k - 1) / 2 pairs of parents.""" + return nx.DiGraph((parent, "child") for parent in range(k)) + + +def _converted(G): + return bool(G.__networkx_cache__.get("backends", {}).get("graphblas")) + + +def test_should_run_leaves_few_pairs_of_parents_to_networkx(monkeypatch): + monkeypatch.setattr(moral, "_FEWEST_PARENT_PAIRS_PER_EDGE", 5) + few, many = _parents_of_one_child(10), _parents_of_one_child(11) # 4.5 and 5 per edge + assert isinstance(Dispatcher.should_run("moral_graph", (few,), {}), str) + assert Dispatcher.should_run("moral_graph", (many,), {}) is True + # A self-loop makes its node one of its own parents, as in NetworkX's loop. + few.add_edge("child", "child") # 11 edges, 55 pairs + assert Dispatcher.should_run("moral_graph", (few,), {}) is True + assert Dispatcher.should_run("moral_graph", (nx.DiGraph(),), {}) is True + view = many.subgraph([*range(10), "child"]) + assert isinstance(Dispatcher.should_run("moral_graph", (view,), {}), str) + for G, served in [(_parents_of_one_child(10), False), (_parents_of_one_child(11), True)]: + expected = nx.moral_graph(G, backend="networkx") + with nx.config(fallback_to_nx=False), nx.config.backend_priority(generators=["graphblas"]): + assert_same(nx.moral_graph(G), expected, G) + assert _converted(G) == served diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 86559ac..d066185 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -137,6 +137,7 @@ def call_args(kind, args): "hyper_wiener_index": ("undirected", ()), "in_degree_centrality": ("directed", ()), "inter_community_edges": ("undirected", ([{0, 1}, {2, 3, 4}],)), + "inter_community_non_edges": ("undirected", ([{0, 1}, {2, 3, 4}],)), "intersection": ("plain", (SECOND,)), "intra_community_edges": ("undirected", ([{0, 1}, {2, 3, 4}],)), "is_arborescence": ("dag", ()), @@ -172,6 +173,7 @@ def call_args(kind, args): "minimum_spanning_tree": ("undirected", ()), "mixing_expansion": ("undirected", ([0, 1], [2, 3])), "modularity": ("undirected", ([{0, 1}, {2, 3, 4}],)), + "moral_graph": ("directed", ()), "modularity_matrix": ("undirected", ()), "mutual_weight": ("directed", (0, 1)), "negative_edge_cycle": ("undirected", ()), diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 9afd01e..d77b8cb 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -475,7 +475,7 @@ def weighted_digraph(): def operands(name, build): """`name`'s arguments with `build()` as the graph, plus what else the name needs.""" G = build() - if name == "reverse": + if name in {"moral_graph", "reverse"}: return (G.to_directed(),) if name in {"disjoint_union", "full_join", "union"}: return (G, nx.relabel_nodes(build(), lambda node: f"b{node}")) diff --git a/graphblas_algorithms/tests/test_match_nx.py b/graphblas_algorithms/tests/test_match_nx.py index 70507dc..01fa7ad 100644 --- a/graphblas_algorithms/tests/test_match_nx.py +++ b/graphblas_algorithms/tests/test_match_nx.py @@ -582,6 +582,7 @@ def test_signatures_match_nx(): "k_truss", "maximum_spanning_tree", "minimum_spanning_tree", + "moral_graph", "reverse", "symmetric_difference", "union",