diff --git a/_nx_graphblas/__init__.py b/_nx_graphblas/__init__.py index 3cab89e..eae8c9f 100644 --- a/_nx_graphblas/__init__.py +++ b/_nx_graphblas/__init__.py @@ -201,14 +201,14 @@ def get_info(): "center": '`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.', "closeness_centrality": 'Lengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".', "common_neighbor_centrality": "An `alpha` other than a Python int or float, unless it equals 1, is left to NetworkX.", - "compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "compose": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", "cut_size": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more.", "diameter": '`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.', - "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "disjoint_union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", "eccentricity": 'A precomputed `sp`, and the null graph, are 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.', "edge_betweenness_centrality": "Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX.\nThe edges come by their first ends in node order, then by their second ends in node\norder, which may differ from the order of `G.edges()`.", "edge_betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX. The edges come by their first ends\nin node order, then by their second ends in node order, which may differ from the order\nof `G.edges()`.", - "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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.', + "ego_graph": 'With `distance`, lengths are Bellman-Ford\'s, so a negative edge without a negative\ncycle is answered where NetworkX\'s Dijkstra raises "Contradictory paths found", and the\ncall raises OverflowError rather than add integer weights where the number of nodes\ntimes the heaviest absolute weight reaches 2**62, as a length could then pass 2**63.\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), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.', "floyd_warshall": "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.", "floyd_warshall_predecessor_and_distance": "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.", "group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.", @@ -217,19 +217,19 @@ 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.", - "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.", - "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", - "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "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), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", + "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), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", + "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), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", + "k_shell": "A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX.\nEdge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", + "k_truss": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", "local_efficiency": "The cost is the breadth-first levels times the chunks of walks, so a node whose\nneighbors induce long paths (the hub of a wheel) is no faster than in NetworkX; the\nmemory stays bounded.", "negative_edge_cycle": "Raises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.", "periphery": '`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\nelsewhere every one is computed. The null graph is left to NetworkX.\nLengths are Bellman-Ford\'s, so a negative edge without a negative cycle is answered where\nNetworkX\'s Dijkstra raises "Contradictory paths found".\nRaises OverflowError rather than add integer weights where the number of nodes times the\nheaviest absolute weight reaches 2**62, as a length could then pass 2**63.', "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.', - "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "reverse": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", "schultz_index": 'A graph with a node named "weight" is left to NetworkX.\nRaises 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.', "single_source_bellman_ford_path_length": "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.", - "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\nnumbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\nchange a value, such as an int past 2**53 beside a float, is left to NetworkX.", + "union": "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\nnumbers. A mix that would change a value, such as an int past 2**53 beside a float, is\nleft to NetworkX, and so is any bool weight, as for every name.", "volume": "Raises OverflowError rather than add integer weights whose absolute values sum to 2**63\nor more, or to 2**63 over the most times `S` names one node.", "wiener_index": 'Lengths 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, or where the sum over one node\'s targets could\nreach 2**63.', # END: additional_docs diff --git a/_nx_graphblas/core.py b/_nx_graphblas/core.py index eee5c0d..ea12978 100644 --- a/_nx_graphblas/core.py +++ b/_nx_graphblas/core.py @@ -184,9 +184,9 @@ # full_join rebuilds its inputs too, but leaves a weighted graph to NetworkX. _ONE_WEIGHT_TYPE = ( "Edge weights come back in the one type their matrix holds: mixed ints and floats, or\n" - "`np.uint64` beside signed ints, as floats (1 as 1.0), bools mixed with numbers as\n" - "numbers (True as 1 or 1.0), and NumPy scalars as Python numbers. A mix that would\n" - "change a value, such as an int past 2**53 beside a float, is left to NetworkX." + "`np.uint64` beside signed ints, as floats (1 as 1.0), and NumPy scalars as Python\n" + "numbers. A mix that would change a value, such as an int past 2**53 beside a float, is\n" + "left to NetworkX, and so is any bool weight, as for every name." ) for _name in ( "compose", diff --git a/graphblas_algorithms/interface.py b/graphblas_algorithms/interface.py index 251f038..83c9c64 100644 --- a/graphblas_algorithms/interface.py +++ b/graphblas_algorithms/interface.py @@ -100,7 +100,8 @@ def _edge_value_problem(graph, attr): numpy infers for them all, so where that is a float or complex, an int past 2**53 can come back as another number (2**53 + 1 beside a float as 9007199254740992.0, a large `np.uint64` beside a negative int the same way): refused as well. A change of type alone - is not refused: 1.0 for 1 beside a float, 1 for True beside an int. A numpy time and a + is not refused: 1.0 for 1 beside a float. A bool is refused once the graph is converted, + whatever it sits beside (`_has_bool_values`). A numpy time and a long double are refused whatever they sit beside: GraphBLAS has neither type, and `int()` of a `timedelta64`, which subclasses `np.integer`, raises TypeError. """ @@ -147,6 +148,49 @@ def _edge_value_problem(graph, attr): return None +def _has_bool_values(graph, attr, G): + """Whether some edge's `attr` is a bool, Python's or NumPy's; `G` is the converted graph. + + NetworkX adds Python's bools as the ints 1 and 0 and NumPy's two at a time as a logical or + (`np.True_ + np.True_` is True, where `mutual_weight` adds two), and some of its answers + hold a weight as it was given (`floyd_warshall`'s distance along one edge, `ego_graph`'s + edges, `adjacency_matrix`). A matrix of bools has no plus, and one of ints or floats has + lost which values were bools, so a bool anywhere is left to NetworkX. + + A matrix of bools says so at once. In any other, a bool is held as 1 or 0 (1.0 or 0.0 + beside floats, and an undirected self-loop's True as 1 once NetworkX's conversion has + negated and added it), so only those entries are looked up in `graph`: one at a time when + they are few, as most weights from data are not exactly 1 or 0, and else all the values + at once, their types gathered at C speed. + """ + import itertools + import operator + + import numpy as np + from graphblas import binary, dtypes, select + + A = G._A + if A.dtype == dtypes.BOOL: + return True + bools = (bool, np.bool_) + ones_and_zeros = binary.any(select.valueeq(A, 1).new() | select.valueeq(A, 0).new()).new() + if ones_and_zeros.nvals == 0: + return False + if 4 * ones_and_zeros.nvals < A.nvals: + keys = list(G._key_to_id) # by id + adj = graph._adj + rows, cols, _values = ones_and_zeros.to_coo(values=False) + return any( + type(adj[keys[row]][keys[col]].get(attr)) in bools + for row, col in zip(rows.tolist(), cols.tolist(), strict=True) + ) + datadicts = itertools.chain.from_iterable( + map(operator.methodcaller("values"), graph._adj.values()) + ) + types = set(map(type, map(operator.methodcaller("get", attr), datadicts))) + return not types.isdisjoint(bools) + + def _unrebuildable(graph, weight, preserve_edge_attrs, *, keeps_node_data=True): """Why a graph rebuilt from `graph` would not carry what NetworkX's own result does. @@ -522,6 +566,11 @@ def convert_from_nx( raise NotImplementedError( f"Edge attribute {weight!r} has values a GraphBLAS matrix cannot hold: {exc}" ) from exc + if weight is not None and _has_bool_values(graph, weight, G): + raise NotImplementedError( + f"Edge attribute {weight!r} has bool values, which NetworkX adds as ints (two " + "of NumPy's as a logical or) and returns as bools; networkx serves the call" + ) # A rebuilt graph keeps the graph attributes too, which NetworkX before 3.7 does not # ask for on `reverse` when its conversion cache is off. if preserve_graph_attrs or declared.rebuilds_input: diff --git a/graphblas_algorithms/nxapi/tests/test_community.py b/graphblas_algorithms/nxapi/tests/test_community.py index 04ba284..52b4b00 100644 --- a/graphblas_algorithms/nxapi/tests/test_community.py +++ b/graphblas_algorithms/nxapi/tests/test_community.py @@ -157,6 +157,12 @@ def test_modularity_follows_networkx(name, weight, resolution): G, partition = _partitioned()[name] expected = quality.modularity(G, partition, weight=weight, resolution=resolution) for H in (G, backend(G, weight="weight")): + if H is G and name == "boolean weights" and weight == "weight": + # NetworkX's bools are left to NetworkX as they are converted (test_bool_weights.py); + # a backend graph that holds bools already is served, adding them as numbers. + with pytest.raises(NotImplementedError): + quality.modularity(H, partition, weight, resolution, backend="graphblas") + continue rv = quality.modularity(H, partition, weight, resolution, backend="graphblas") assert rv == pytest.approx(expected, rel=1e-12, abs=1e-15) diff --git a/graphblas_algorithms/tests/test_bool_weights.py b/graphblas_algorithms/tests/test_bool_weights.py new file mode 100644 index 0000000..7f551b4 --- /dev/null +++ b/graphblas_algorithms/tests/test_bool_weights.py @@ -0,0 +1,267 @@ +"""Bool edge weights are left to NetworkX, which adds Python's as ints and returns them as bools. + +NetworkX adds `True` as 1 and NumPy's `np.True_ + np.True_` as a logical or, and some of its +answers hold a weight as it was given: `floyd_warshall_predecessor_and_distance`'s distance +along one edge, `ego_graph`'s edges, `adjacency_matrix`. A matrix of bools has no plus, and +one of ints or floats has lost which values were bools, so the conversion refuses a bool +anywhere among the values it reads, and NetworkX answers. +""" + +import math +import numbers + +import networkx as nx +import numpy as np +import pytest +from networkx.utils.backends import _registered_algorithms + +from graphblas_algorithms.interface import Dispatcher, _declared +from graphblas_algorithms.tests._dispatched import dispatcher_functions + +pytestmark = pytest.mark.filterwarnings( + "ignore:Note. conversions to backend graphs", "ignore::RuntimeWarning" +) + +# Each kind of bool weight, by edge index: all bools, Python's or NumPy's, or bools beside ints +# or floats. Each has a twin: its values with each bool an int. +BOOLS = { + "bool": lambda i: i % 3 != 2, + "all True": lambda i: True, + "all False": lambda i: False, + "np.bool_": lambda i: np.bool_(i % 3 != 2), + "bool+int": lambda i: True if i % 2 else i + 2, + "np.bool_+int": lambda i: np.True_ if i % 2 else i + 2, + "bool+float": lambda i: True if i % 2 else i + 0.5, + "False+float": lambda i: False if i % 2 else i + 0.5, + "np.bool_+float": lambda i: np.True_ if i % 2 else i + 0.5, +} +EDGES = [(0, 1), (1, 2), (2, 3), (3, 0), (0, 2), (3, 4)] + + +def twin(make): + def made(i): + value = make(i) + return int(value) if isinstance(value, bool | np.bool_) else value + + return made + + +def graph(directed, loop, make, attr="weight"): + G = nx.DiGraph() if directed else nx.Graph() + for i, (u, v) in enumerate(EDGES + [(2, 2)] * loop): + G.add_edge(u, v, **{attr: make(i)}) + return G + + +@pytest.mark.parametrize("loop", [False, True], ids=["", "self-loop"]) +@pytest.mark.parametrize("directed", [False, True], ids=["undirected", "directed"]) +@pytest.mark.parametrize("name", ["pagerank", "ego_graph"]) +@pytest.mark.parametrize("kind", BOOLS) +def test_a_bool_weight_is_refused_at_conversion(kind, name, directed, loop): + """Whatever the bools sit beside, and whatever dtype the matrix takes; their twins convert. + + `ego_graph` rebuilds its input from the matrix, so its conversion reads every value first. + """ + make = BOOLS[kind] + G = graph(directed, loop, make, attr="cost") + if kind == "np.bool_" and loop and not directed: + # NetworkX negates an undirected self-loop's value as it converts, which NumPy refuses + # for a bool; that TypeError is refused before the values are read. + reason = "cannot hold" + else: + reason = "Edge attribute 'cost' has bool values" + with pytest.raises(NotImplementedError, match=reason): + Dispatcher.convert_from_nx(G, edge_attrs={"cost": 1}, name=name) + H = Dispatcher.convert_from_nx( + graph(directed, loop, twin(make), "cost"), {"cost": 1}, name=name + ) + assert H._A.dtype.np_type.kind in "if" + + +@pytest.mark.parametrize("where", ["edge", "self-loop"]) +@pytest.mark.parametrize("beside", [5, 5.5]) +@pytest.mark.parametrize("directed", [False, True], ids=["undirected", "directed"]) +@pytest.mark.parametrize("value", [True, False, np.True_, np.False_], ids=repr) +def test_a_lone_bool_among_many_numbers_is_found(value, directed, beside, where): + """A bool is held as 1 or 0; with few of those, each is looked up in the graph by itself.""" + G = nx.cycle_graph(20, create_using=nx.DiGraph if directed else nx.Graph) + nx.set_edge_attributes(G, beside, "cost") + u, v = (7, 8) if where == "edge" else (3, 3) + G.add_edge(u, v, cost=value) + if isinstance(value, np.bool_) and where == "self-loop" and not directed: + reason = "cannot hold" # NetworkX's conversion negates it, which NumPy refuses + else: + reason = "Edge attribute 'cost' has bool values" + with pytest.raises(NotImplementedError, match=reason): + Dispatcher.convert_from_nx(G, edge_attrs={"cost": 1}, name="pagerank") + G.add_edge(u, v, cost=int(value)) # its twin: a lone 1 or 0 + A = Dispatcher.convert_from_nx(G, edge_attrs={"cost": 1}, name="pagerank")._A + assert A[u, v].value == int(value) + + +def test_a_bool_in_an_attribute_not_read_is_no_matter(): + G = graph(True, True, lambda i: i + 1) + nx.set_edge_attributes(G, True, "flag") + A = Dispatcher.convert_from_nx(G, edge_attrs={"weight": 1}, name="pagerank")._A + assert A.dtype.np_type.kind == "i" + A = Dispatcher.convert_from_nx(G, edge_attrs=None, name="pagerank")._A + assert A.nvals == len(EDGES) + 1 + # An attribute no edge has is no weight: the unweighted graph. + A = Dispatcher.convert_from_nx(G, edge_attrs={"absent": 1}, name="pagerank")._A + assert A.nvals == len(EDGES) + 1 + + +# Names that rebuild their input from its matrix, each with its arguments after the graph. +REBUILDS = {"reverse": (), "k_truss": (2,), "k_core": (), "ego_graph": (0,)} + + +@pytest.mark.parametrize("kind", ["bool", "bool+int", "bool+float", "np.bool_+float"]) +@pytest.mark.parametrize("name", REBUILDS) +def test_networkx_rebuilds_a_graph_with_bool_weights(name, kind, backend_priority): + """NetworkX's graph, its bools as they were given.""" + directed = name == "reverse" + func = _registered_algorithms[name] + expected = outcome( + func, (graph(directed, False, BOOLS[kind]), *REBUILDS[name]), {"backend": "networkx"} + ) + assert expected[0] == "answer" + with backend_priority("generators"): + got = outcome(func, (graph(directed, False, BOOLS[kind]), *REBUILDS[name]), {}) + assert agree(got, expected) + _graph, _directed, _nodes, edges = expected[1] + kinds = {scalar[1] for _edge, (_map, items) in edges for _key, scalar in items} + assert "bool" in kinds + + +def _kind(x): + if isinstance(x, bool | np.bool_): + return "bool" + if isinstance(x, numbers.Integral): + return "int" + if isinstance(x, numbers.Real): + return "float" + if isinstance(x, numbers.Complex): + return "complex" + return None + + +def settle(value, depth=0): + """`value` as plain data, each scalar with its kind: bool, int, float or complex.""" + if depth > 6: + return ("repr", repr(value)) + value = Dispatcher.convert_to_nx(value) + if isinstance(value, nx.Graph): + edges = ( + (repr((u, v) if value.is_directed() else tuple(sorted((u, v)))), settle(d, depth + 1)) + for u, v, d in value.edges(data=True) + ) + return ("graph", value.is_directed(), sorted(map(repr, value.nodes)), sorted(edges)) + if type(value).__module__.startswith("scipy.sparse"): + return ("matrix", value.dtype.kind, settle(value.toarray().tolist(), depth + 1)) + if type(value).__module__.split(".")[0] == "graphblas": # a Matrix or Vector + dense = value.to_dense(fill_value=0) + return ("matrix", dense.dtype.kind, settle(dense.tolist(), depth + 1)) + if isinstance(value, np.ndarray): + return ("array", value.dtype.kind, settle(value.tolist(), depth + 1)) + if (kind := _kind(value)) is not None: + return ("scalar", kind, complex(value) if kind == "complex" else float(value)) + if hasattr(value, "items") and not isinstance(value, str | bytes): + return ("map", sorted((repr(k), settle(v, depth + 1)) for k, v in value.items())) + if isinstance(value, str | bytes) or value is None: + return ("plain", repr(value)) + if isinstance(value, set | frozenset): + return ("set", sorted(map(repr, value))) + if hasattr(value, "__iter__"): + return ("list", [settle(v, depth + 1) for v in value]) + return ("repr", repr(value)) + + +def same(a, b): + """Whether settled `a` and `b` agree: floats within rel 1e-9, the rest and kinds exactly.""" + if type(a) is not type(b): + return False + if isinstance(a, tuple) and len(a) == 3 and a[0] == "scalar" == b[0]: + if a[1] != b[1]: + return False + x, y = a[2], b[2] + if isinstance(x, complex): + return x == y + if math.isnan(x) or math.isnan(y): + return math.isnan(x) and math.isnan(y) + return x == y or abs(x - y) <= max(1e-12, 1e-9 * max(abs(x), abs(y))) + if isinstance(a, tuple | list): + return len(a) == len(b) and all(map(same, a, b)) + return a == b + + +def outcome(func, args, kwargs): + try: + result = func(*args, **kwargs) + except Exception as exc: + return ("error", type(exc).__name__, str(exc)) + try: + return ("answer", settle(result)) + except Exception as exc: + return ("error as read", type(exc).__name__, str(exc)) + + +def agree(got, expected): + if got[0] == expected[0] == "answer": + return same(got[1], expected[1]) + return got == expected + + +RECIPES = [(), (0,), (0, 3), ([0, 1],), ([0, 1], [2, 3]), ([{0, 1, 2}, {3, 4}],)] + + +def _weighted_names(): + functions = dispatcher_functions() + return sorted( + name + for name in functions + if name in _registered_algorithms and _declared(name).attribute_parameters + ) + + +WEIGHTED = _weighted_names() + + +def test_the_weighted_names_are_listed(): + """A guard on the listing: the names whose answers hold a weight as given are among them.""" + assert len(WEIGHTED) >= 40 + holders = {"floyd_warshall_predecessor_and_distance", "ego_graph", "adjacency_matrix"} + assert holders | {"mutual_weight", "pagerank"} <= set(WEIGHTED) + + +@pytest.mark.parametrize("name", WEIGHTED) +def test_networkx_answers_every_weighted_name_with_bool_weights(name, backend_priority): + """The answer, or error, NetworkX gives, with this backend first in NetworkX's priority.""" + func = _registered_algorithms[name] + parameter = _declared(name).attribute_parameters[0] + kwargs = {parameter: "weight"} + wrong = [] + calls = 0 + for directed in (False, True): + numeric = graph(directed, True, lambda i: i + 1) + recipe = next( + ( + args + for args in RECIPES + if outcome(func, (numeric, *args), {**kwargs, "backend": "networkx"})[0] == "answer" + ), + None, + ) + if recipe is None: + continue + for kind, make in BOOLS.items(): + for loop in (False, True): + expected = outcome( + func, (graph(directed, loop, make), *recipe), {**kwargs, "backend": "networkx"} + ) + with backend_priority("algos"), backend_priority("generators"): + got = outcome(func, (graph(directed, loop, make), *recipe), kwargs) + calls += 1 + if not agree(got, expected): + wrong.append(f"{kind} directed={directed} loop={loop}: {got} vs {expected}") + assert not wrong, "\n".join(wrong) + assert calls >= 2 * len(BOOLS) # some names NetworkX takes in one direction only diff --git a/graphblas_algorithms/tests/test_dispatch.py b/graphblas_algorithms/tests/test_dispatch.py index 50b54a5..fb3d691 100644 --- a/graphblas_algorithms/tests/test_dispatch.py +++ b/graphblas_algorithms/tests/test_dispatch.py @@ -43,18 +43,15 @@ def test_multigraph_conversion_is_refused_rather_than_collapsed(): [ 3, 2.5, - True, 1 + 2j, np.int64(3), np.int32(3), np.uint8(3), np.float64(2.5), np.float32(2.5), - np.bool_(True), np.complex128(1 + 2j), 0, 0.0, - False, 2**63 - 1, -(2**63), ], @@ -63,7 +60,8 @@ def test_every_value_a_matrix_can_hold_still_converts(value): """The refusal must not turn away a value the conversion handles. numpy integers are the case that matters: `np.int64` does not subclass `int`, and they - are what `from_pandas_edgelist` produces, so a graph built that way must convert. + are what `from_pandas_edgelist` produces, so a graph built that way must convert. A bool + converts too, but is then refused (test_bool_weights.py). """ G = nx.Graph([(0, 1, {"cost": value})]) converted = Dispatcher.convert_from_nx(G, preserve_edge_attrs=True) @@ -121,7 +119,6 @@ def test_networkx_answers_a_rebuild_of_an_int_outside_int64(name, value, backend # Pairs whose values come back equal, if not of the same type. CHANGES_TYPE_ONLY = { "int beside a float": (1, 1.5), - "True beside an int": (True, 2), "2**53 beside a float": (2**53, 1.5), "int past 2**53 beside an int": (2**53 + 1, 2), "np.uint64 at 2**63 beside an int": (np.uint64(2**63), 2), diff --git a/graphblas_algorithms/tests/test_roundtrip.py b/graphblas_algorithms/tests/test_roundtrip.py index 5b57698..8fbc620 100644 --- a/graphblas_algorithms/tests/test_roundtrip.py +++ b/graphblas_algorithms/tests/test_roundtrip.py @@ -331,22 +331,16 @@ def test_mixed_int_and_float_weights_come_back_as_floats(name): [ ([1, 2], [1, 2]), ([1.0, 2.5], [1.0, 2.5]), - ([True, False], [True, False]), ([1, 2.5], [1.0, 2.5]), ([2**62 + 1, 2], [2**62 + 1, 2]), - ([True, 2], [1, 2]), - ([True, 2.5], [1.0, 2.5]), ([np.int32(1), 2], [1, 2]), ([np.float32(1.5), np.float32(2.5)], [1.5, 2.5]), ], ids=[ "int", "float", - "bool", "int and float", "a big int and an int", - "bool and int", - "bool and float", "numpy int", "numpy float", ], @@ -408,7 +402,7 @@ def test_the_iso_value_cache_entry_is_written_not_read(): assert g.get_property("iso_value") is None -@pytest.mark.parametrize("value", [None, 2.5, 3, True, np.int64(3), np.float32(0.5)]) +@pytest.mark.parametrize("value", [None, 2.5, 3, np.int64(3), np.float32(0.5)]) @pytest.mark.parametrize("attr", ["weight", "cost"]) def test_our_own_output_converts_back(value, attr): """What `to_networkx` emits, `from_networkx` accepts.