diff --git a/README.md b/README.md index 434b514..867b154 100644 --- a/README.md +++ b/README.md @@ -128,14 +128,19 @@ graphblas_algorithms.nxapi │ ├── connectivity │ │ └── average_degree_connectivity │ ├── correlation +│ │ ├── attribute_assortativity_coefficient │ │ ├── degree_assortativity_coefficient -│ │ └── degree_pearson_correlation_coefficient +│ │ ├── degree_pearson_correlation_coefficient +│ │ └── numeric_assortativity_coefficient │ ├── mixing +│ │ ├── attribute_mixing_dict +│ │ ├── attribute_mixing_matrix │ │ ├── degree_mixing_dict │ │ └── degree_mixing_matrix │ ├── neighbor_degree │ │ └── average_neighbor_degree │ └── pairs +│ ├── node_attribute_xy │ └── node_degree_xy ├── boundary │ ├── edge_boundary diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index be433ea..0588760 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -34,6 +34,9 @@ def get_info(): "all_pairs_bellman_ford_path_length", "all_pairs_shortest_path_length", "ancestors", + "attribute_assortativity_coefficient", + "attribute_mixing_dict", + "attribute_mixing_matrix", "average_clustering", "average_degree_connectivity", "average_neighbor_degree", @@ -130,6 +133,7 @@ def get_info(): "modularity_matrix", "mutual_weight", "negative_edge_cycle", + "node_attribute_xy", "node_boundary", "node_connected_component", "node_degree_xy", @@ -139,6 +143,7 @@ def get_info(): "number_connected_components", "number_of_isolates", "number_weakly_connected_components", + "numeric_assortativity_coefficient", "onion_layers", "out_degree_centrality", "overall_reciprocity", @@ -198,6 +203,9 @@ def get_info(): _additional_docs = { # BEGIN: additional_docs "all_pairs_bellman_ford_path_length": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "attribute_assortativity_coefficient": "Taken from the counted value pairs in float64; within rounding of NetworkX's.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.", + "attribute_mixing_dict": "The keys come in another order than NetworkX's, which follows each node's adjacency.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.", + "attribute_mixing_matrix": "Without `mapping`, NetworkX's numbering of the values is arbitrary; here they are\nnumbered in the order nodes first hold them, None for a missing value last.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.", "average_degree_connectivity": "Complex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).\nWith `weight`, an iterator `nodes` is left to NetworkX.", "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\nComplex weights are left to NetworkX. Float weights are added in another order than\nNetworkX's, so a value may differ from NetworkX's in its last bits. Integer weights are\nleft to NetworkX where a node's weighted degree, or its sum of each weight times the\nneighbor's degree, could reach 2**63 (by the sum of the absolute values it adds).", "average_shortest_path_length": 'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\nNetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\nwithout a negative cycle is answered where NetworkX\'s Dijkstra raises\n"Contradictory paths found".', @@ -237,7 +245,9 @@ def get_info(): "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", "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": "Integer weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.", + "node_attribute_xy": "The pairs come edge by edge as the matrix stores them, not along each node's\nadjacency as in NetworkX.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.", "node_degree_xy": 'The pairs come by edge, both ends in node order, not in NetworkX\'s adjacency order.\nNetworkX\'s own `degree_mixing_dict` takes these degrees as keys.\nA weighted degree is an int where the weights are all integers, and a float where any is\na float; NetworkX adds up an int for a node whose own weights are all integers, or that\nhas none, so there an equal float stands for its int.\nOn a directed graph, an `x` or `y` other than "in" or "out" is left to NetworkX, as are\ncomplex weights and float weights whose sums FP64 could round: the weighted degrees are\nkeys, so the weights must all be multiples of one power of two whose sums stay below\n2**52 of it, so that each weighted degree is NetworkX\'s, bit for bit.\nInteger weights are left to NetworkX where a weighted degree could reach 2**63: where the\nabsolute values one node adds (a self-loop\'s twice) sum to that.', + "numeric_assortativity_coefficient": "The Pearson correlation of the pairs in float64, within rounding of NetworkX's. Where\nNetworkX squares ints past about 3e9 in int64, which wraps, this gives the true\ncoefficient. Values that are not real numbers, an iterator `nodes`, which NetworkX\nreads twice, and a node in `nodes` that is not in the graph are left to NetworkX; a\nnode without the attribute raises KeyError, as there.\nThe values are read from the graph as NetworkX's mixing reads them, a node without the\nattribute as None, and values a dict takes as one key are one value. Left to NetworkX:\na graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\ncallable or unhashable, and values no dict can key.", "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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight 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".\nInteger weights are left to NetworkX where the number of nodes times the heaviest absolute\nweight reaches 2**62, as a length could then pass 2**63.', "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats as\nfloats (1 as 1.0), bools mixed with numbers as numbers (True as 1 or 1.0), and NumPy\nscalars as Python numbers. Weights that would hold an int past 2**53 as a float, such as\none beside a float, or that are all ints held as floats, such as `np.uint64` beside a\nsigned int, are left to NetworkX.", diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index 39a13ca..d4f6126 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -125,6 +125,13 @@ "degree may differ from NetworkX's in its last bits.\n" + _DEGREE_OVERFLOW ) +_NODE_ATTRIBUTE = ( + "The values are read from the graph as NetworkX's mixing reads them, a node without the\n" + "attribute as None, and values a dict takes as one key are one value. Left to NetworkX:\n" + "a graph class with its own `adjacency` or `nodes`, an `attribute` that is None,\n" + "callable or unhashable, and values no dict can key." +) + # Prose NetworkX shows under a function's documentation, for behaviour its docstring does not # describe. _ADDITIONAL_DOCS = { @@ -135,6 +142,19 @@ "without a negative cycle is answered where NetworkX's Dijkstra raises\n" '"Contradictory paths found".' ), + "attribute_assortativity_coefficient": ( + "Taken from the counted value pairs in float64; within rounding of NetworkX's.\n" + + _NODE_ATTRIBUTE + ), + "attribute_mixing_dict": ( + "The keys come in another order than NetworkX's, which follows each node's adjacency.\n" + + _NODE_ATTRIBUTE + ), + "attribute_mixing_matrix": ( + "Without `mapping`, NetworkX's numbering of the values is arbitrary; here they are\n" + "numbered in the order nodes first hold them, None for a missing value last.\n" + + _NODE_ATTRIBUTE + ), "average_degree_connectivity": _NEIGHBOR_DEGREE_WEIGHTS + "\nWith `weight`, an iterator `nodes` is left to NetworkX.", "average_neighbor_degree": "`nodes` one node, which raises in NetworkX, is left to it.\n" @@ -227,12 +247,23 @@ "memory stays bounded." ), "negative_edge_cycle": _PATH_OVERFLOW, + "node_attribute_xy": ( + "The pairs come edge by edge as the matrix stores them, not along each node's\n" + "adjacency as in NetworkX.\n" + _NODE_ATTRIBUTE + ), "node_degree_xy": ( "The pairs come by edge, both ends in node order, not in NetworkX's adjacency order.\n" "NetworkX's own `degree_mixing_dict` takes these degrees as keys.\n" + _DEGREE_TYPES + _DEGREES_AS_KEYS ), + "numeric_assortativity_coefficient": ( + "The Pearson correlation of the pairs in float64, within rounding of NetworkX's. Where\n" + "NetworkX squares ints past about 3e9 in int64, which wraps, this gives the true\n" + "coefficient. Values that are not real numbers, an iterator `nodes`, which NetworkX\n" + "reads twice, and a node in `nodes` that is not in the graph are left to NetworkX; a\n" + "node without the attribute raises KeyError, as there.\n" + _NODE_ATTRIBUTE + ), "periphery": _ECCENTRICITY_BOUNDS, "radius": _ECCENTRICITY_BOUNDS, "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n' diff --git a/graphblas_algorithms/algorithms/assortativity/mixing.py b/graphblas_algorithms/algorithms/assortativity/mixing.py index 5b046e0..e5b7c52 100644 --- a/graphblas_algorithms/algorithms/assortativity/mixing.py +++ b/graphblas_algorithms/algorithms/assortativity/mixing.py @@ -8,6 +8,7 @@ from ..exceptions import IntegerOverflowError __all__ = [ + "attribute_mixing_counts", "check_int_sums", "degree_mixing_counts", "degree_pairs", @@ -163,13 +164,36 @@ def degree_mixing_counts(G, xdeg, ydeg, ids=None): if k == 0: return values, Matrix(dtypes.INT64, 0, 0) xcodes, ycodes = codes[: ids.size], codes[ids.size :] - Px = Matrix.from_coo(ids, xcodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k) - Py = Matrix.from_coo(ids, ycodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k) - # B[u, j]: the neighbors v of u in `ids` whose y-degree is values[j]. The rows of Px are - # the nodes in `ids`, so the second product keeps only edges that start there. + return values, _pair_counts(G, ids, xcodes, ids, ycodes, k) + + +def _pair_counts(G, xids, xcodes, yids, ycodes, k): + """A k x k Matrix counting `(xcodes[u], ycodes[v])` over the stored edges `(u, v)`. + + Only edges from a node in `xids` to a node in `yids` count; the codes are given by + position in those arrays. + """ + n = len(G) + Px = Matrix.from_coo(xids, xcodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k) + Py = Matrix.from_coo(yids, ycodes, 1, dtype=dtypes.INT64, nrows=n, ncols=k) + # B[u, j]: the neighbors v of u in `yids` with code j. The rows of Px are the nodes in + # `xids`, so the second product keeps only edges that start there. B = plus_pair[dtypes.INT64](G._A @ Py).new() - C = plus_second[dtypes.INT64](Px.T @ B).new() - return values, C + return plus_second[dtypes.INT64](Px.T @ B).new() + + +def attribute_mixing_counts(G, codes, k, ids=None): + """Count the pairs `(codes[u], codes[v])` over the stored edges `(u, v)` with `u` in `ids`. + + `codes` gives each node, by id, a code below `k`. Only an edge's first end must be in `ids` + (every node when None), as NetworkX's `node_attribute_xy` keeps them; an undirected edge is + stored both ways and a self-loop once, as it yields them. Returns a k x k Matrix of counts, + the code of the first end by row. + """ + every = np.arange(len(G), dtype=np.int64) + if ids is None: + ids = every + return _pair_counts(G, ids, codes[ids], every, codes, k) def degree_pairs(G, xdeg, ydeg, ids=None): diff --git a/graphblas_algorithms/classes/_node_attributes.py b/graphblas_algorithms/classes/_node_attributes.py new file mode 100644 index 0000000..711b60e --- /dev/null +++ b/graphblas_algorithms/classes/_node_attributes.py @@ -0,0 +1,76 @@ +"""What a graph converted from NetworkX carries for a name that reads a node attribute. + +NetworkX's attribute mixing keys its counts by the values of a node attribute, and which +values are equal decides them. A matrix holds numbers, so a conversion for such a name carries +the values, read once from the NetworkX graph and numbered as a dict keys them. +""" + +from collections import namedtuple +from itertools import chain + +import numpy as np +from graphblas import Matrix, Vector, dtypes + +__all__ = ["NodeAttribute", "from_networkx_adjacency", "read_node_attribute"] + + +class _Missing: + """The value of a node that lacks the attribute.""" + + __slots__ = () + + def __repr__(self): + return "MISSING" + + +MISSING = _Missing() + +# `codes`: a Vector with an entry for each node that has the attribute, the id of its value. +# `values`: the distinct values by id, as the first node in node order holding each holds it; +# two values are one when a dict takes them as one key (1, 1.0 and True; one NaN object). +# `objects`: each node's value as that node holds it, by node id, MISSING where it has none. +# `index`: the id of each value, as a dict looks it up. +NodeAttribute = namedtuple("NodeAttribute", ["codes", "values", "objects", "index"]) + + +def from_networkx_adjacency(graph, key_to_id): + """The structural matrix of `graph`, or None when it has no edges. + + The matrix is the one `from_networkx(graph)` builds, read in one pass over `graph._adj` + rather than through scipy. With no edges, `from_networkx` gives a float matrix of no + entries. + """ + adj = graph._adj + n = len(key_to_id) + if len(adj) != n: + raise ValueError(f"the graph has {n} nodes but {len(adj)} adjacency rows") + dtype = np.int32 if n < 2**31 else np.int64 + nbrs = list(adj.values()) + lengths = np.fromiter(map(len, nbrs), np.int64, n) + count = int(lengths.sum()) + rows = np.fromiter(map(key_to_id.__getitem__, adj), dtype, n) + neighbors = np.fromiter(map(key_to_id.__getitem__, chain.from_iterable(nbrs)), dtype, count) + if count == 0: + return None + return Matrix.from_coo( + np.repeat(rows, lengths), neighbors, 1, dtype=dtypes.INT64, nrows=n, ncols=n + ) + + +def read_node_attribute(graph, attribute, n): + """`attribute` of each node of `graph`, numbered as NetworkX's dicts would key it. + + Raises TypeError for a value no dict can key (a list), as NetworkX's mixing raises. + """ + objects = [datadict.get(attribute, MISSING) for datadict in graph._node.values()] + if len(objects) != n: + raise ValueError(f"the graph has {n} nodes but {len(objects)} node data dicts") + index = {} + codes = np.fromiter( + (-1 if value is MISSING else index.setdefault(value, len(index)) for value in objects), + np.int64, + n, + ) + present = np.flatnonzero(codes >= 0) + vector = Vector.from_coo(present, codes[present], dtype=dtypes.INT64, size=n) + return NodeAttribute(vector, list(index), objects, index) diff --git a/graphblas_algorithms/classes/digraph.py b/graphblas_algorithms/classes/digraph.py index 1211f11..dc021c7 100644 --- a/graphblas_algorithms/classes/digraph.py +++ b/graphblas_algorithms/classes/digraph.py @@ -534,6 +534,8 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a self._key_to_id = key_to_id self._id_to_key = None self._cache = {} + # What a conversion for a name that reads node attributes carries (`interface`). + self._node_attributes = {} # Graphblas-specific methods from_networkx = classmethod(_utils.from_networkx) diff --git a/graphblas_algorithms/classes/graph.py b/graphblas_algorithms/classes/graph.py index 0848c89..e15b3c6 100644 --- a/graphblas_algorithms/classes/graph.py +++ b/graphblas_algorithms/classes/graph.py @@ -384,6 +384,8 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a self._key_to_id = key_to_id self._id_to_key = None self._cache = {} + # What a conversion for a name that reads node attributes carries (`interface`). + self._node_attributes = {} # Graphblas-specific methods from_networkx = classmethod(_utils.from_networkx) diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 01f9b1c..c888f76 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -308,16 +308,65 @@ def _materialize_virtual_adjacency(graph): return H +def _with_node_attribute(cls, graph, node_attrs, name): + """`graph` converted for `name`, carrying the one node attribute in `node_attrs`. + + Only a name whose wrapper reads a node attribute (`nxapi._utils.reads_node_attribute`) + gets it; for any other the conversion is refused, as every one was before such names were + served. + """ + import networkx as nx + + from .classes._node_attributes import from_networkx_adjacency, read_node_attribute + + wrapper = getattr(Dispatcher, name, None) if isinstance(name, str) else None + if not getattr(wrapper, "_reads_node_attribute", False): + raise NotImplementedError( + f"A conversion carries node attributes only for the names that read them here, " + f"not for {name}" + ) + [[attribute, default]] = node_attrs.items() if len(node_attrs) == 1 else [[None, None]] + if attribute is None or default is not None: + raise NotImplementedError(f"{name} reads one node attribute, with no default") + cls_of = type(graph) + if getattr(cls_of, "adjacency", None) is not nx.Graph.adjacency or ( + getattr(cls_of, "nodes", None) is not nx.Graph.nodes + ): + # `can_run` declines these; a direct call is refused here. + raise NotImplementedError( + f"{name} walks the adjacency and nodes {cls_of.__name__} reports, which networkx " + "serves" + ) + key_to_id = {key: i for i, key in enumerate(graph)} + try: + A = from_networkx_adjacency(graph, key_to_id) + record = read_node_attribute(graph, attribute, len(key_to_id)) + except Exception as exc: + # A value no dict can key (NetworkX's mixing raises on it too), or an adjacency whose + # rows are not the graph's nodes: NetworkX answers, with its own error. + raise NotImplementedError( + f"Node attribute {attribute!r} of this graph cannot be read for {name}: {exc}" + ) from exc + G = cls.from_networkx(graph) if A is None else cls(A, key_to_id=key_to_id) + G._node_attributes[attribute] = record + return G + + class Dispatcher: # Begin auto-generated code: dispatch mod = nxapi.assortativity # ======================= average_degree_connectivity = mod.connectivity.average_degree_connectivity + attribute_assortativity_coefficient = mod.correlation.attribute_assortativity_coefficient degree_assortativity_coefficient = mod.correlation.degree_assortativity_coefficient degree_pearson_correlation_coefficient = mod.correlation.degree_pearson_correlation_coefficient + numeric_assortativity_coefficient = mod.correlation.numeric_assortativity_coefficient + attribute_mixing_dict = mod.mixing.attribute_mixing_dict + attribute_mixing_matrix = mod.mixing.attribute_mixing_matrix degree_mixing_dict = mod.mixing.degree_mixing_dict degree_mixing_matrix = mod.mixing.degree_mixing_matrix average_neighbor_degree = mod.neighbor_degree.average_neighbor_degree + node_attribute_xy = mod.pairs.node_attribute_xy node_degree_xy = mod.pairs.node_degree_xy mod = nxapi.boundary @@ -566,10 +615,18 @@ def convert_from_nx( "graphblas-algorithms does not support multigraphs: a GraphBLAS matrix " "holds one value per node pair, so parallel edges would be combined" ) - graph = _materialize_virtual_adjacency(graph) - if node_attrs: - raise NotImplementedError("non-None `node_attrs` is not yet implemented") + if edge_attrs or preserve_edge_attrs: + raise NotImplementedError( + f"{name} reads node attributes with edge data, which no name here does" + ) + G = _with_node_attribute( + DiGraph if graph.is_directed() else Graph, graph, node_attrs, name + ) + if preserve_graph_attrs: + G.graph.update(graph.graph) + return G + graph = _materialize_virtual_adjacency(graph) weight = None if edge_attrs: diff --git a/graphblas_algorithms/nxapi/_utils.py b/graphblas_algorithms/nxapi/_utils.py index 0e990a0..c2f15f7 100644 --- a/graphblas_algorithms/nxapi/_utils.py +++ b/graphblas_algorithms/nxapi/_utils.py @@ -158,6 +158,16 @@ def decorator(func): return decorator +def reads_node_attribute(func): + """Mark the decorated wrapper as one that answers from a node attribute. + + NetworkX asks the conversion for the attribute the call names (`node_attrs`), and the + conversion carries it only for a wrapper marked so (`interface._with_node_attribute`). + """ + func._reads_node_attribute = True + return func + + def iterators_read_before_sums(name, *parameters): """A rule declining a weighted call that passes a one-shot iterator in `parameters`. diff --git a/graphblas_algorithms/nxapi/assortativity/correlation.py b/graphblas_algorithms/nxapi/assortativity/correlation.py index ce3369d..d5bb3ff 100644 --- a/graphblas_algorithms/nxapi/assortativity/correlation.py +++ b/graphblas_algorithms/nxapi/assortativity/correlation.py @@ -1,22 +1,35 @@ +import numbers from collections.abc import Iterator import numpy as np +from graphblas import Matrix from graphblas_algorithms import algorithms +from graphblas_algorithms.classes._node_attributes import MISSING from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run, iterators_read_before_sums, nbunch_keys +from .._utils import can_run, iterators_read_before_sums, nbunch_keys, reads_node_attribute +from .mixing import attribute_mixing_matrix # noqa: F401 (NetworkX's module has it too) from .mixing import degree_mixing_matrix # noqa: F401 (NetworkX's module has it too) from .mixing import ( + attribute_counts, + carrying, check_rule, degree_arrays, + node_attribute, + node_attribute_rule, pair_ids, weighted, xy_rule, ) from .pairs import node_degree_xy # noqa: F401 (NetworkX's module has it too) -__all__ = ["degree_assortativity_coefficient", "degree_pearson_correlation_coefficient"] +__all__ = [ + "attribute_assortativity_coefficient", + "degree_assortativity_coefficient", + "degree_pearson_correlation_coefficient", + "numeric_assortativity_coefficient", +] # A Pearson coefficient over more pairs than this is taken from the counts, not from one # array of the pairs per end. @@ -109,3 +122,84 @@ def degree_pearson_correlation_coefficient(G, x="out", y="in", weight=None, node return _too_few_pairs(xs, ys) rv = algorithms.pearson_from_counts(values, C) return _constant_input() if rv is None else rv + + +_attribute_rule = node_attribute_rule("attribute_assortativity_coefficient") + + +@can_run(_attribute_rule) +@reads_node_attribute +def attribute_assortativity_coefficient(G, attribute, nodes=None): + """NetworkX's coefficient, taken from the counted value pairs in float64. + + With M the pairs' joint distribution, a and b its row and column sums, NetworkX's + `attribute_ac` gives (trace(M) - sum(M @ M)) / (1 - sum(M @ M)), and sum(M @ M) is a . b. + """ + name = "attribute_assortativity_coefficient" + check_rule(_attribute_rule, G=G, attribute=attribute, nodes=nodes) + G = to_graph(carrying(G, attribute, name)) + C, _ = attribute_counts(G, attribute, nodes, name) + rows, cols, counts = C.to_coo() + total = float(counts.sum()) + if total == 0: + return 0.0 # NetworkX's empty matrix: (0 - 0) / (1 - 0) + k = C.nrows + a = np.bincount(rows, counts, k) / total + b = np.bincount(cols, counts, k) / total + trace = counts[rows == cols].sum() / total + s = float(a @ b) + if s == 1: + return float("nan") # one value: NetworkX's 0 / 0 + return float((trace - s) / (1 - s)) + + +# NetworkX reads `nodes` twice, by the set of values and by `node_attribute_xy`. +_numeric_rule = node_attribute_rule("numeric_assortativity_coefficient", nodes_read_twice=True) + + +def _held(G, record, key, attribute, name): + """`G.nodes[key][attribute]` as NetworkX reads it, from the values the conversion carries.""" + try: + i = G._key_to_id[key] + except (KeyError, TypeError): + # NetworkX raises for a key not in the graph, and for a slice, by its own messages. + raise NotImplementedError(f"{name} with {key!r} in `nodes` raises in networkx") from None + value = record.objects[i] + if value is MISSING: + raise KeyError(attribute) + return value + + +@can_run(_numeric_rule) +@reads_node_attribute +def numeric_assortativity_coefficient(G, attribute, nodes=None): + """The Pearson correlation of the value pairs along the edges from `nodes`, in float64. + + As in NetworkX, only pairs whose two values are held by nodes in `nodes` count. NetworkX + squares the values in their own type, so ints past about 3e9 wrap in int64 there; here + they are floats, and the coefficient is the true one. + """ + name = "numeric_assortativity_coefficient" + check_rule(_numeric_rule, G=G, attribute=attribute, nodes=nodes) + G = to_graph(carrying(G, attribute, name)) + record = node_attribute(G, attribute, name) + # The values of `nodes`, read before their pairs, as NetworkX reads them. + if nodes is None: + if record.codes.nvals < len(G): + raise KeyError(attribute) + held = range(len(record.values)) + else: + held = {record.index[_held(G, record, key, attribute, name)] for key in nodes} + C, values = attribute_counts(G, attribute, nodes, name) + if not all(isinstance(values[code], numbers.Real) for code in held): + raise NotImplementedError(f"{name} of values that are not real numbers raises in networkx") + x = np.full(len(values), np.nan) + for code in held: + x[code] = values[code] + rows, cols, counts = C.to_coo() + inside = np.zeros(len(values), bool) + inside[list(held)] = True + keep = inside[rows] & inside[cols] + C = Matrix.from_coo(rows[keep], cols[keep], counts[keep], nrows=C.nrows, ncols=C.ncols) + rv = algorithms.pearson_from_counts(x, C) + return float("nan") if rv is None else rv diff --git a/graphblas_algorithms/nxapi/assortativity/mixing.py b/graphblas_algorithms/nxapi/assortativity/mixing.py index b810da7..8a6389f 100644 --- a/graphblas_algorithms/nxapi/assortativity/mixing.py +++ b/graphblas_algorithms/nxapi/assortativity/mixing.py @@ -1,11 +1,18 @@ +from collections.abc import Iterator + import numpy as np from graphblas_algorithms import algorithms from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run +from .._utils import can_run, reads_node_attribute -__all__ = ["degree_mixing_dict", "degree_mixing_matrix"] +__all__ = [ + "attribute_mixing_dict", + "attribute_mixing_matrix", + "degree_mixing_dict", + "degree_mixing_matrix", +] def _is_degree_kind(value): @@ -78,13 +85,16 @@ def mixing_counts(G, x, y, weight, nodes, name): def _mixing_dict(values, C, normalized=False): - """NetworkX's `mixing_dict` of the counted pairs, its keys in sorted order. + """NetworkX's `mixing_dict` of the counted pairs, its keys in the order of `values`. - As there, each degree met at either end of a pair is a key, with an empty dict if it is - never an x-degree, and `normalized` divides each count by the number of pairs. + As there, each value (a degree or an attribute's value) met at either end of a pair is a + key, with an empty dict if it is never an x-value, and `normalized` divides each count by + the number of pairs. NetworkX's keys come in the order it meets them along each node's + adjacency, which a matrix does not keep; here the degrees come in increasing order, and an + attribute's values by code. """ rows, cols, counts = C.to_coo() - keys = values.tolist() + keys = values.tolist() if isinstance(values, np.ndarray) else values rv = {keys[i]: {} for i in np.union1d(rows, cols).tolist()} total = float(counts.sum()) for i, j, count in zip(rows.tolist(), cols.tolist(), counts.tolist(), strict=True): @@ -145,5 +155,160 @@ def degree_mixing_matrix( return a -# NetworkX's module has it too. Imported last: `pairs` takes the helpers above from here. -from .pairs import node_degree_xy # noqa: E402, F401 isort:skip +def node_attribute_rule(name, *, nodes_read_twice=False): + """The `can_run` rule of the names that mix a node attribute along each edge.""" + + def hook(bound): + import networkx as nx + + attribute = bound["attribute"] + if attribute is None or callable(attribute): + # NetworkX's conversion then carries no attribute, or every one. + return f"{name} with `attribute` {attribute!r} is left to networkx" + try: + hash(attribute) + except TypeError: + return f"{name} with an unhashable `attribute` raises in networkx" + G = bound["G"] + cls = type(G) + if hasattr(G, "_adj") and ( + cls.adjacency is not nx.Graph.adjacency or cls.nodes is not nx.Graph.nodes + ): + return ( + f"{name} walks the adjacency and nodes {cls.__name__} reports; networkx " + "serves it" + ) + if nodes_read_twice and isinstance(bound["nodes"], Iterator): + return f"{name} reads an iterator `nodes` twice in networkx" + return None + + return hook + + +def carrying(G, attribute, name): + """A NetworkX `G` converted with `attribute`, as NetworkX converts it for `name`. + + For a direct call; through the dispatcher NetworkX has converted the graph already, and + any other graph is returned as it is. + """ + if not hasattr(G, "_adj"): + return G + from graphblas_algorithms.interface import Dispatcher + + return Dispatcher.convert_from_nx(G, node_attrs={attribute: None}, name=name) + + +def node_attribute(G, attribute, name): + """The conversion's record of `attribute` (`NodeAttribute`). + + A graph not converted for a name that reads it carries none, such as this backend's own + graph or a conversion cached for a name that asked for every attribute; NetworkX answers. + """ + record = G._node_attributes.get(attribute) + if record is None: + raise NotImplementedError( + f"{name} needs node attribute {attribute!r} from the conversion of a NetworkX " + "graph, and this graph does not carry it; networkx serves it" + ) + return record + + +def stream_codes(record): + """Each node's code as NetworkX's mixing meets it, and the value of each code. + + NetworkX reads a node without the attribute as None, which is then one value with a None + that a node holds. + """ + codes = record.codes.to_dense(fill_value=-1, dtype=np.int64) + values = record.values + missing = codes < 0 + if missing.any(): + none = record.index.get(None) + if none is None: + none = len(values) + values = [*values, None] + codes[missing] = none + return codes, values + + +def attribute_counts(G, attribute, nodes, name): + """The counted value pairs of the converted `G`, the codes' values, and each node's code. + + `C[i, j]` pairs have the values `values[i]` and `values[j]`, along the edges from `nodes`. + """ + record = node_attribute(G, attribute, name) + codes, values = stream_codes(record) + C = algorithms.attribute_mixing_counts(G, codes, len(values), pair_ids(G, nodes)) + return C, values + + +def attribute_mixing(G, attribute, nodes, mapping, normalized, name): + """NetworkX's `attribute_mixing_matrix` of the converted `G`. + + Without `mapping`, NetworkX numbers the values it meets as a set of them iterates, which its + documentation leaves arbitrary; here they are numbered in the order nodes first hold them, + a value no node holds (None, for a node without the attribute) last. + """ + # Before `nodes` is read: an iterator then reaches NetworkX unspent. + try: + len(mapping) if mapping is not None else None + except TypeError: + raise NotImplementedError(f"{name} with this `mapping` raises in networkx") from None + C, values = attribute_counts(G, attribute, nodes, name) + if mapping is None: + rows, cols, _ = C.to_coo(values=False) + met = np.union1d(rows, cols) + index = np.full(len(values), -1, np.int64) + index[met] = np.arange(met.size) + size = met.size + elif _regular(mapping): + index = np.array([mapping.get(value, -1) for value in values], np.int64) + size = len(mapping) + else: + from networkx.utils import dict_to_numpy_array + + a = dict_to_numpy_array(_mixing_dict(values, C), mapping=mapping) + return a / a.sum() if normalized else a + rows, cols, counts = C.to_coo() + i = index[rows] + j = index[cols] + keep = (i >= 0) & (j >= 0) + a = np.zeros((size, size)) + a[i[keep], j[keep]] = counts[keep] + if normalized: + a = a / a.sum() + return a + + +_attribute_mixing_rule = node_attribute_rule("attribute_mixing_matrix") + + +@can_run(_attribute_mixing_rule) +@reads_node_attribute +def attribute_mixing_matrix(G, attribute, nodes=None, mapping=None, normalized=True): + check_rule(_attribute_mixing_rule, G=G, attribute=attribute, nodes=nodes) + G = to_graph(carrying(G, attribute, "attribute_mixing_matrix")) + return attribute_mixing(G, attribute, nodes, mapping, normalized, "attribute_mixing_matrix") + + +_attribute_mixing_dict_rule = node_attribute_rule("attribute_mixing_dict") + + +@can_run(_attribute_mixing_dict_rule) +@reads_node_attribute +def attribute_mixing_dict(G, attribute, nodes=None, normalized=False): + name = "attribute_mixing_dict" + check_rule(_attribute_mixing_dict_rule, G=G, attribute=attribute, nodes=nodes) + G = to_graph(carrying(G, attribute, name)) + C, values = attribute_counts(G, attribute, nodes, name) + rv = _mixing_dict(values, C) + if normalized: + total = float(C.reduce_scalar().get(0)) + for counts in rv.values(): + for key in counts: + counts[key] /= total + return rv + + +# NetworkX's module has them too. Imported last: `pairs` takes the helpers above from here. +from .pairs import node_attribute_xy, node_degree_xy # noqa: E402, F401 isort:skip diff --git a/graphblas_algorithms/nxapi/assortativity/pairs.py b/graphblas_algorithms/nxapi/assortativity/pairs.py index 939c890..aa4e22d 100644 --- a/graphblas_algorithms/nxapi/assortativity/pairs.py +++ b/graphblas_algorithms/nxapi/assortativity/pairs.py @@ -1,10 +1,48 @@ +import numpy as np + from graphblas_algorithms import algorithms +from graphblas_algorithms.classes._node_attributes import MISSING from graphblas_algorithms.classes.digraph import to_graph -from .._utils import can_run -from .mixing import check_rule, degree_arrays, pair_ids, weighted, xy_rule +from .._utils import can_run, reads_node_attribute +from .mixing import ( + carrying, + check_rule, + degree_arrays, + node_attribute, + node_attribute_rule, + pair_ids, + weighted, + xy_rule, +) + +__all__ = ["node_attribute_xy", "node_degree_xy"] + +_node_attribute_xy_rule = node_attribute_rule("node_attribute_xy") + + +@can_run(_node_attribute_xy_rule) +@reads_node_attribute +def node_attribute_xy(G, attribute, nodes=None): + """The value pairs along each edge from `nodes`, edge by edge as the matrix stores them. + + NetworkX yields them along `G.adjacency()`; the pairs are the same, in another order. An + undirected edge gives a pair each way, and a self-loop one. + """ + name = "node_attribute_xy" + check_rule(_node_attribute_xy_rule, G=G, attribute=attribute, nodes=nodes) + G = to_graph(carrying(G, attribute, name)) + record = node_attribute(G, attribute, name) + ids = pair_ids(G, nodes) + rows, cols, _ = G._A.to_coo(values=False) + if ids is not None: + keep = np.zeros(len(G), bool) + keep[ids] = True + keep = keep[rows] + rows, cols = rows[keep], cols[keep] + held = [None if value is MISSING else value for value in record.objects] + return ((held[u], held[v]) for u, v in zip(rows.tolist(), cols.tolist(), strict=True)) -__all__ = ["node_degree_xy"] _pairs_rule = xy_rule("node_degree_xy") diff --git a/graphblas_algorithms/nxapi/tests/test_node_attributes.py b/graphblas_algorithms/nxapi/tests/test_node_attributes.py new file mode 100644 index 0000000..0d39c79 --- /dev/null +++ b/graphblas_algorithms/nxapi/tests/test_node_attributes.py @@ -0,0 +1,544 @@ +"""The node attribute mixing names against NetworkX's own answers. + +Floats agree within rounding, counts and pairs exactly, and orders NetworkX leaves arbitrary +(the matrix's numbering without `mapping`, the dict's keys, the pairs) are checked as sets. +""" + +import math +import numbers +import pickle +from collections import Counter +from collections.abc import Iterator +from fractions import Fraction + +import networkx as nx +import numpy as np +import pytest + +import graphblas_algorithms as ga +from graphblas_algorithms import nxapi +from graphblas_algorithms.interface import Dispatcher + +from .test_assortativity import GRAPHS, automatic + +pytestmark = [ + pytest.mark.filterwarnings("ignore:Note. conversions to backend graphs"), + pytest.mark.filterwarnings("ignore::RuntimeWarning"), # numpy's nan from 0 / 0, as there +] + +NAMES = [ + "attribute_assortativity_coefficient", + "attribute_mixing_dict", + "attribute_mixing_matrix", + "node_attribute_xy", + "numeric_assortativity_coefficient", +] +REL = 1e-12 +NAN = float("nan") +KINDS = { + "strings": ["red", "green", "blue", "cyan", "magenta"], + "ints": [1, 2, 3, 4], + # 5, 13, 21 and 29 want one slot of a small set, so its order is the order of filling. + "ints that want one slot": [5, 13, 21, 29], + "floats": [0.5, 1.5, -2.25, 3.0], + "numbers of several types": [1, 1.0, True, 2.5, np.int64(2), np.float32(0.5), Fraction(1, 2)], + "one nan object": [NAN, 1.0, 2.0], + "nan objects": "nan objects", + "zeros of both signs": [0.0, -0.0, 1.0], + "big ints": [2**70, 3, 2**63, -(2**65)], + "ints past 2**53 beside a float": [2**53 + 1, 0.5, 7], + "ints whose squares wrap int64": [2**40, 3, 2**33], + "strings and ints": ["a", 1, "b", 2], + "tuples": [(1, 2), (3, 4), (5, 6)], + "None held": [None, 1, 2], + "bools": [True, False], + "one value": [5], +} +SWEPT = [ + "null", + "one node", + "one self-loop", + "two isolated", + "star", + "karate", + "self-loops", + "disconnected, isolated", + "mixed keys", + "node order unlike key order", + "null directed", + "directed self-loop", + "D2", + "both ways, isolated", +] + + +def assign(G, kind, *, missing=False, attr="a"): + """Give the nodes values of `kind`, every fourth node none when `missing`.""" + values = KINDS[kind] + for i, node in enumerate(G): + if missing and i % 4 == 1: + continue + if values == "nan objects": + G.nodes[node][attr] = float("nan") if i % 3 else 1.5 # a new NaN object each time + else: + G.nodes[node][attr] = values[(5 * i + 2) % len(values)] + return G + + +def run(func, G, kwargs, backend): + """What a call gives, a generator read out; "automatic" puts graphblas first.""" + try: + if backend == "automatic": + rv = automatic(func.__name__, G, **kwargs) + else: + rv = func(G, backend=backend, **kwargs) + return "value", list(rv) if isinstance(rv, Iterator) else rv + except NotImplementedError: + raise + except Exception as exc: + return "raised", type(exc), str(exc) + + +def _exact(value): + """`value` as a Fraction, or None for nan and the infinities.""" + if isinstance(value, numbers.Integral): + return Fraction(int(value)) + if isinstance(value, Fraction): + return value + value = float(value) + return Fraction(value) if math.isfinite(value) else None + + +def true_numeric(G, attribute, nodes): + """The Pearson correlation of NetworkX's value pairs, from exact sums.""" + nodes = list(G) if nodes is None else list(nodes) + held = {G.nodes[node][attribute] for node in nodes} + pairs = [ + (x, y) + for x, y in nx.node_attribute_xy(G, attribute, nodes, backend="networkx") + if x in held and y in held + ] + pairs = [(_exact(x), _exact(y)) for x, y in pairs] + if not pairs or any(x is None or y is None for x, y in pairs): + return NAN + n = len(pairs) + mx = sum(x for x, _ in pairs) / n + my = sum(y for _, y in pairs) / n + cov = sum((x - mx) * (y - my) for x, y in pairs) + vx = sum((x - mx) ** 2 for x, _ in pairs) + vy = sum((y - my) ** 2 for _, y in pairs) + if vx == 0 or vy == 0: + return NAN + return math.copysign(math.sqrt(cov * cov / (vx * vy)), cov) + + +def numbered(G, attribute, nodes, normalized): + """The mixing matrix numbered in the order nodes first hold the values, None last.""" + d = nx.attribute_mixing_dict(G, attribute, nodes, backend="networkx") + firsts = dict.fromkeys(data[attribute] for _, data in G.nodes(data=True) if attribute in data) + if any(attribute not in data for _, data in G.nodes(data=True)): + firsts.setdefault(None) + met = [value for value in firsts if value in d] + a = np.zeros((len(met), len(met))) + for i, x in enumerate(met): + for j, y in enumerate(met): + a[i, j] = d[x].get(y, 0) + return a / a.sum() if normalized else a + + +def close(got, want): + if isinstance(want, float) and math.isnan(want): + assert math.isnan(got) + else: + assert got == pytest.approx(want, rel=REL, abs=1e-15) + + +def assert_valid(name, G, kwargs, got, want): + """`got` is NetworkX's `want` under the contract: the same error, or the same contents.""" + if want[0] == "raised" or got[0] == "raised": + assert got == want + return + got, want = got[1], want[1] + attribute = kwargs["attribute"] + if name == "node_attribute_xy": + assert Counter(got) == Counter(want) + elif name == "attribute_mixing_dict": + assert got == want # by key, as a dict compares; counts and their shares exact + elif name == "attribute_mixing_matrix": + if kwargs.get("mapping") is None: + nodes = kwargs.get("nodes") + want = numbered(G, attribute, nodes, kwargs.get("normalized", True)) + assert got.shape == want.shape + np.testing.assert_allclose(got, want, rtol=REL, atol=1e-15) + elif name == "attribute_assortativity_coefficient": + close(got, float(want)) + else: + close(got, true_numeric(G, attribute, kwargs.get("nodes"))) + + +def check(name, G, *args, **kwargs): + """True if this backend serves the call, with what NetworkX gives under the contract. + + A call left to NetworkX raises NotImplementedError with `backend="graphblas"`, and NetworkX + answers it under the priority. + """ + func = getattr(nx, name) + if args: + [kwargs["attribute"]] = args + spent = {key: list(val) for key, val in kwargs.items() if isinstance(val, Iterator)} + + def fresh(): + return {**kwargs, **{key: iter(val) for key, val in spent.items()}} + + want = run(func, G, fresh(), "networkx") + plain = {**kwargs, **spent} + automatic_answer = run(func, G, fresh(), "automatic") + try: + got = run(func, G, fresh(), "graphblas") + except NotImplementedError: + assert automatic_answer == want or repr(automatic_answer) == repr(want) + return False + assert_valid(name, G, plain, got, want) + assert_valid(name, G, plain, automatic_answer, want) + return True + + +def served_here(name, G, attribute, kwargs): + """Whether the call is served: all but the numeric name on values not real numbers.""" + if name != "numeric_assortativity_coefficient": + return True + nodes = kwargs.get("nodes") + try: + held = {G.nodes[node][attribute] for node in (G if nodes is None else nodes)} + except (KeyError, TypeError): + return True # raises as NetworkX raises + return all(isinstance(value, numbers.Real) for value in held) + + +def calls(G): + """The calls each graph is checked with: every name, with and without `nodes`.""" + nodes = list(G) + some = nodes[1:4] + held = list(dict.fromkeys(data.get("a") for _, data in G.nodes(data=True))) + yield "attribute_assortativity_coefficient", {} + yield "attribute_assortativity_coefficient", {"nodes": some} + yield "attribute_assortativity_coefficient", {"nodes": iter(some)} + yield "attribute_mixing_matrix", {} + yield "attribute_mixing_matrix", {"normalized": False} + yield "attribute_mixing_matrix", {"nodes": [*some, "not a node"], "normalized": False} + yield "attribute_mixing_matrix", {"mapping": {v: i for i, v in enumerate(reversed(held))}} + yield "attribute_mixing_matrix", {"mapping": {v: len(held) - 1 - i for i, v in enumerate(held)}} + yield "attribute_mixing_matrix", {"mapping": dict.fromkeys(held, 0)} # not one-to-one + yield "attribute_mixing_matrix", {"mapping": list(held)} # raises in NetworkX + yield "attribute_mixing_dict", {} + yield "attribute_mixing_dict", {"nodes": some, "normalized": True} + yield "node_attribute_xy", {} + yield "node_attribute_xy", {"nodes": [*some, "not a node"]} + yield "numeric_assortativity_coefficient", {} + yield "numeric_assortativity_coefficient", {"nodes": some} + + +def _keyable(G): + try: + {data.get("a") for _, data in G.nodes(data=True)} + except TypeError: + return False + return True + + +@pytest.mark.parametrize("missing", [False, True]) +@pytest.mark.parametrize("kind", list(KINDS)) +@pytest.mark.parametrize("graph", SWEPT) +def test_awkward_values(graph, kind, missing): + # NetworkX's answer within rounding, or its error (a missing value is KeyError for the + # numeric name, a None for the others). + G = assign(GRAPHS[graph](), kind, missing=missing) + for name, kwargs in calls(G): + served = served_here(name, G, "a", kwargs) + assert check(name, G, "a", **kwargs) is served, (name, kwargs) + + +@pytest.mark.parametrize("graph", list(GRAPHS)) +def test_every_graph(graph): + for missing in [False, True]: + G = assign(GRAPHS[graph](), "strings", missing=missing) + for name, kwargs in calls(G): + served = served_here(name, G, "a", kwargs) + assert check(name, G, "a", **kwargs) is served, (name, kwargs) + + +def _hub(order): + """Node 0 joins nodes 1, 2 and 3, with values 13, 21 and 29, in `order`; 1 joins 2.""" + G = nx.Graph() + G.add_nodes_from(range(4)) + G.add_edges_from((0, v) for v in order) + G.add_edge(1, 2) + for node, value in zip(range(4), [5, 13, 21, 29], strict=True): + G.nodes[node]["a"] = value + return G + + +def test_values_are_numbered_in_the_order_nodes_hold_them(): + # The same nodes in the same order and the same edges, added in another order. NetworkX + # meets the values along node 0's neighbors in the order they were added, and these all + # want one slot of its set, so its numbering follows that order; here it does not. + G1, G2 = _hub([1, 2, 3]), _hub([3, 1, 2]) + assert sorted(map(sorted, G1.edges)) == sorted(map(sorted, G2.edges)) + M1 = nx.attribute_mixing_matrix(G1, "a", backend="networkx") + M2 = nx.attribute_mixing_matrix(G2, "a", backend="networkx") + assert not np.array_equal(M1, M2) + got = [nx.attribute_mixing_matrix(G, "a", backend="graphblas") for G in [G1, G2]] + np.testing.assert_array_equal(got[0], got[1]) + np.testing.assert_array_equal(got[0], numbered(G1, "a", None, True)) + for G in [G1, G2]: + for name in NAMES: + assert check(name, G, "a") + + +@pytest.mark.parametrize("seed", range(20)) +def test_graphs_built_from_shuffled_edges(seed): + # Each node's neighbors come in the order its edges were added, not in node order; with + # values that want one slot of NetworkX's set, the order it meets them decides the matrix. + rng = np.random.default_rng(seed) + for directed in [False, True]: + H = nx.gnp_random_graph( + int(rng.integers(2, 31)), rng.random() * 0.4, seed, directed=directed + ) + nodes, edges = list(H), list(H.edges) + nodes = [nodes[i] for i in rng.permutation(len(nodes))] + edges = [edges[i] for i in rng.permutation(len(edges))] + for kind in ["ints that want one slot", "strings"]: + # A new graph for each: NetworkX's cached conversion would keep the old values. + G = H.__class__() + G.add_nodes_from(nodes) + G.add_edges_from(edges) + G = assign(G, kind, missing=seed % 2 == 1) + for name, kwargs in calls(G): + served = served_here(name, G, "a", kwargs) + assert check(name, G, "a", **kwargs) is served, (name, kwargs) + + +def test_numeric_is_the_true_coefficient_where_networkx_s_squares_wrap(): + # 2**40 and 2.0**40 are one value; NetworkX's set keeps the one its `nodes` meet first, and + # squares it in int64, where it wraps, or in float64. Here it is a float either way. + G = nx.path_graph(5) + nx.set_node_attributes(G, {0: 2.0**40, 1: 2**40, 2: 3, 3: 2**40, 4: 3}, "a") + with_int = nx.numeric_assortativity_coefficient(G, "a", nodes=[1, 0, 2, 3, 4]) + with_float = nx.numeric_assortativity_coefficient(G, "a", nodes=[0, 1, 2, 3, 4]) + assert with_int != pytest.approx(with_float) + want = true_numeric(G, "a", None) + assert with_float == pytest.approx(want, rel=REL) + for nodes in [None, [1, 0, 2, 3, 4], [0, 1, 2, 3, 4]]: + got = nx.numeric_assortativity_coefficient(G, "a", nodes=nodes, backend="graphblas") + assert got == pytest.approx(want, rel=REL) + + +def test_many_values_are_served(): + G = nx.path_graph(5000) + nx.set_node_attributes(G, {node: (node * 7) % 4999 for node in G}, "a") + for name in NAMES: + if name != "attribute_mixing_matrix": # a dense 5000 x 5000 matrix + assert check(name, G, "a") + mapping = {value: i for i, value in enumerate(range(10))} + assert check("attribute_mixing_matrix", G, "a", mapping=mapping) + + +def test_values_no_dict_can_key_are_left_to_networkx(): + G = nx.path_graph(4) + nx.set_node_attributes(G, {0: [1], 1: [2], 2: [1], 3: [2]}, "a") + for name in NAMES: + assert not check(name, G, "a") + with pytest.raises(NotImplementedError, match="cannot be read"): + getattr(nxapi, name)(G, "a") + + +def test_a_node_without_the_value_raises_keyerror_in_the_numeric_name(): + G = nx.path_graph(4) + nx.set_node_attributes(G, {0: 1, 1: 2, 3: 4}, "a") + for nodes in [None, [0, 1, 2], [2, 99]]: + with pytest.raises(KeyError, match="'a'"): + nx.numeric_assortativity_coefficient(G, "a", nodes=nodes, backend="graphblas") + # The other names read it as None. + assert check("attribute_assortativity_coefficient", G, "a") + assert check("attribute_mixing_matrix", G, "a", mapping={None: 0, 1: 1, 2: 2, 4: 3}) + + +@pytest.mark.parametrize( + ("nodes", "served"), + [([1, 99], False), ([99, 1], False), ([slice(0, 2)], False), ([[1]], False), (7, True)], + ids=repr, +) +def test_numeric_with_nodes_networkx_cannot_look_up(nodes, served): + # NetworkX raises, each by its own message (a view's lookup words it otherwise), so a + # node it cannot look up is left to it. A `nodes` it cannot iterate raises here as there. + G = nx.Graph([(1, 2), ("a", "b"), (1, "b")]) + nx.set_node_attributes(G, 3, "a") + assert check("numeric_assortativity_coefficient", G, "a", nodes=nodes) is served + view = nx.subgraph_view(G, filter_node=lambda node: node != 2) + assert check("numeric_assortativity_coefficient", view, "a", nodes=nodes) is served + + +class OwnNodes(nx.Graph): + """A graph class with its own `nodes`, which NetworkX's mixing reads the values through.""" + + @property + def nodes(self): + return nx.reportviews.NodeView(self) + + +@pytest.mark.parametrize("name", NAMES) +@pytest.mark.parametrize( + "case", + ["attribute None", "callable attribute", "unhashable attribute", "AntiGraph", "own nodes"], +) +def test_declines_what_networkx_reads_another_way(name, case): + from networkx.algorithms.approximation.kcomponents import _AntiGraph + + G = nx.path_graph(5) + attribute = "a" + if case == "attribute None": + attribute = None + elif case == "callable attribute": + attribute = len + elif case == "unhashable attribute": + attribute = ["a"] + elif case == "AntiGraph": + G = _AntiGraph(G) + elif case == "own nodes": + G = OwnNodes(G) + for node in G: + G.nodes[node]["a"] = node % 2 + reason = Dispatcher.can_run(name, (G, attribute), {}) + assert isinstance(reason, str) + with pytest.raises(NotImplementedError) as direct: + getattr(nxapi, name)(G, attribute) + assert str(direct.value) == reason + want = run(getattr(nx, name), G, {"attribute": attribute}, "networkx") + got = run(getattr(nx, name), G, {"attribute": attribute}, "automatic") + assert repr(got) == repr(want) + + +def test_numeric_with_an_iterator_nodes_is_left_to_networkx(): + # NetworkX reads `nodes` twice; the attribute names read it once and are served. + G = assign(nx.karate_club_graph(), "ints") + reason = Dispatcher.can_run("numeric_assortativity_coefficient", (G, "a"), {"nodes": iter([])}) + assert "twice" in reason + want = nx.numeric_assortativity_coefficient(G, "a", nodes=iter([0, 1, 2]), backend="networkx") + got = automatic("numeric_assortativity_coefficient", G, attribute="a", nodes=iter([0, 1, 2])) + assert repr(got) == repr(want) + for name in NAMES[:-1]: + assert Dispatcher.can_run(name, (G, "a"), {"nodes": iter([])}) is True + + +@pytest.mark.parametrize("attribute", [1, ("a", 1), True, 2.5]) +def test_attribute_names_other_than_strings(attribute): + G = nx.karate_club_graph() + for node in G: + G.nodes[node][attribute] = node % 3 + for name in NAMES: + assert check(name, G, attribute) + + +def test_views(): + G = assign(nx.karate_club_graph(), "strings", missing=True) + D = assign(nx.gn_graph(30, seed=2), "ints that want one slot", missing=True) + for view in [ + nx.subgraph_view(G, filter_node=lambda node: node % 3 != 0), + nx.subgraph_view(G, filter_edge=lambda u, v: (u + v) % 4 != 0), + G.subgraph([5, 1, 7, 3, 0, 33, 32]), + D.reverse(copy=False), + nx.subgraph_view(D, filter_node=lambda node: node != 0), + ]: + for name, kwargs in calls(view): + assert check(name, view, "a", **kwargs), (name, kwargs) + + +def test_direct_calls(): + G = assign(nx.karate_club_graph(), "strings", missing=True) + for name in NAMES[:-1]: + want = run(getattr(nx, name), G, {"attribute": "a"}, "networkx") + got = getattr(nxapi, name)(G, "a") + got = ("value", list(got) if isinstance(got, Iterator) else got) + assert_valid(name, G, {"attribute": "a"}, got, want) + G = assign(nx.karate_club_graph(), "floats") + want = nx.numeric_assortativity_coefficient(G, "a", backend="networkx") + assert nxapi.numeric_assortativity_coefficient(G, "a") == pytest.approx(want, rel=REL) + # This backend's own graph carries no node attributes. + for name in NAMES: + with pytest.raises(NotImplementedError, match="does not carry it"): + getattr(nxapi, name)(ga.Graph.from_networkx(G), "a") + + +def convert(G, name="attribute_assortativity_coefficient", attribute="a", **kwargs): + return Dispatcher.convert_from_nx(G, node_attrs={attribute: None}, name=name, **kwargs) + + +@pytest.mark.parametrize("graph", list(GRAPHS)) +def test_the_conversion_holds_the_matrix_from_networkx_does(graph): + # A conversion cached for these names serves the names that read no node attribute. + G = assign(GRAPHS[graph](), "strings", missing=True) + for H in [G, nx.subgraph_view(G, filter_node=lambda node: node != 0)]: + got = convert(H) + want = type(got).from_networkx(H) + assert got._key_to_id == want._key_to_id + assert got._weight is want._weight is None + assert got._A.dtype == want._A.dtype + assert got._A.isequal(want._A, check_dtype=True) + assert got._A.ss.is_iso == want._A.ss.is_iso + + +def test_the_conversion_carries_the_values(): + G = nx.Graph([(3, 1), (1, 0), (0, 2), (1, 2)]) + nx.set_node_attributes(G, {3: "x", 0: 1.0, 2: 1}, "a") + g = convert(G) + record = g._node_attributes["a"] + assert record.values == ["x", 1.0] # 1 is 1.0's key; node 1 holds none + assert type(record.values[1]) is float + assert record.codes.to_dense(fill_value=-1).tolist() == [0, -1, 1, 1] + assert record.objects[3] == 1 + assert type(record.objects[3]) is int + assert pickle.loads(pickle.dumps(g))._node_attributes["a"].values == ["x", 1.0] # noqa: S301 + + +def test_a_conversion_for_these_names_serves_the_others(): + G = assign(nx.karate_club_graph(), "strings", missing=True) + assign(G, "ints", attr="x") + plain = nx.karate_club_graph() + automatic("numeric_assortativity_coefficient", G, attribute="x") + automatic("attribute_assortativity_coefficient", G, attribute="a") + cache = G.__networkx_cache__["backends"]["graphblas"] + assert set(cache) == {(False, frozenset({("x", None)})), (False, frozenset({("a", None)}))} + for name in ["betweenness_centrality", "degree_assortativity_coefficient", "triangles"]: + assert automatic(name, G) == automatic(name, plain) + assert len(cache) == 2 # served from one of the two + + +@pytest.mark.parametrize( + ("node_attrs", "kwargs", "match"), + [ + ({"a": None}, {"name": "pagerank"}, "only for the names that read them here"), + ({"a": None}, {"name": None}, "only for the names that read them here"), + ({"a": None, "b": None}, {}, "one node attribute"), + ({"a": 0}, {}, "with no default"), + ({"a": None}, {"edge_attrs": {"weight": 1}}, "edge data"), + ({"a": None}, {"preserve_edge_attrs": True}, "edge data"), + ], +) +def test_other_conversions_with_node_attributes_are_refused(node_attrs, kwargs, match): + G = assign(nx.path_graph(3), "ints") + kwargs = {"name": "attribute_assortativity_coefficient", **kwargs} + with pytest.raises(NotImplementedError, match=match): + Dispatcher.convert_from_nx(G, node_attrs=node_attrs, **kwargs) + + +def test_every_name_of_the_mixing_modules_that_reads_values_is_marked(): + for name in NAMES: + assert getattr(Dispatcher, name)._reads_node_attribute + for name in [ + "degree_assortativity_coefficient", + "degree_mixing_dict", + "degree_mixing_matrix", + "node_degree_xy", + "pagerank", + ]: + assert not getattr(getattr(Dispatcher, name), "_reads_node_attribute", False) diff --git a/graphblas_algorithms/tests/_dispatched.py b/graphblas_algorithms/tests/_dispatched.py index 3906aaa..49e5cf8 100644 --- a/graphblas_algorithms/tests/_dispatched.py +++ b/graphblas_algorithms/tests/_dispatched.py @@ -27,7 +27,10 @@ def dispatcher_functions(): def make_graph(kind, *, shift=0, drop=0, label="first"): - """A small NetworkX graph of `kind`: weighted unless "plain", directed unless undirected.""" + """A small NetworkX graph of `kind`: weighted unless "plain", directed unless undirected. + + The "attributed" graph's nodes carry a string "colour" and an int "size". + """ import networkx as nx if kind == "tournament": @@ -49,6 +52,9 @@ def make_graph(kind, *, shift=0, drop=0, label="first"): if kind != "tournament": # a tournament has an edge for every pair, so no isolates G.add_node(4 + shift) G.graph.update({"name": label, "extra": [1, 2], label: True}) + if kind == "attributed": + for node in G: + G.nodes[node].update(colour=["red", "blue"][node % 2], size=node % 3) return G @@ -74,6 +80,9 @@ def call_args(kind, args): "all_pairs_bellman_ford_path_length": ("undirected", ()), "all_pairs_shortest_path_length": ("undirected", ()), "ancestors": ("dag", (3,)), + "attribute_assortativity_coefficient": ("attributed", ("colour",)), + "attribute_mixing_dict": ("attributed", ("colour",)), + "attribute_mixing_matrix": ("attributed", ("colour",)), "average_clustering": ("undirected", ()), "average_degree_connectivity": ("undirected", ()), "average_neighbor_degree": ("undirected", ()), @@ -186,6 +195,8 @@ def call_args(kind, args): "number_connected_components": ("undirected", ()), "number_of_isolates": ("undirected", ()), "number_weakly_connected_components": ("directed", ()), + "node_attribute_xy": ("attributed", ("colour",)), + "numeric_assortativity_coefficient": ("attributed", ("size",)), "onion_layers": ("undirected", ()), "out_degree_centrality": ("directed", ()), "overall_reciprocity": ("directed", ()),