Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 60 additions & 38 deletions _nx_graphblas/__init__.py

Large diffs are not rendered by default.

94 changes: 94 additions & 0 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,6 +245,100 @@
_ADDITIONAL_DOCS[_name] = _ONE_WEIGHT_TYPE if _doc is None else f"{_doc}\n{_ONE_WEIGHT_TYPE}"


# Weights of a narrow NumPy type, which NetworkX adds in that type (NumPy 2's rule, NEP 50),
# where a matrix holds every value in one dtype. `graphblas_algorithms.interface` has the rule.
_NARROW_LEFT = (
"Weights of `np.float16`, `np.float32` or `np.complex64`, which NetworkX adds in that type,\n"
"are left to NetworkX."
)
_NARROW_LENGTHS_LEFT = (
"Weights of `np.float16`, `np.float32` or `np.complex64` are left to NetworkX, whose lengths\n"
"are then sums in that type, which its callers go on adding in it; a result here holds\n"
"Python floats."
)
_FLOAT32_SERVED = (
"Weights that are all `np.float32` give NetworkX's answer. Beside other numbers, or with\n"
"NumPy before 2, they are left to NetworkX, as are `np.float16` and `np.complex64` weights."
)
# `interface._FLOAT32_EXACT`; a test keeps the two the same.
FLOAT32_SERVED = (
"adjacency_matrix",
"bellman_ford_path",
"center",
"floyd_warshall_numpy",
"negative_edge_cycle",
"periphery",
)
NARROW_LENGTHS_LEFT = (
"all_pairs_bellman_ford_path_length",
"bellman_ford_path_length",
"diameter",
"eccentricity",
"floyd_warshall",
"floyd_warshall_predecessor_and_distance",
"radius",
"single_source_bellman_ford_path_length",
)
# The other names that read weights or carry edge data; a test checks that none is missing.
# The unweighted names, which leave any weight to NetworkX, are not here.
NARROW_LEFT = (
"average_clustering",
"average_degree_connectivity",
"average_neighbor_degree",
"average_shortest_path_length",
"closeness_centrality",
"clustering",
"compose",
"conductance",
"cut_size",
"degree_assortativity_coefficient",
"degree_mixing_matrix",
"degree_pearson_correlation_coefficient",
"directed_modularity_matrix",
"disjoint_union",
"edge_boundary",
"edge_expansion",
"ego_graph",
"eigenvector_centrality",
"full_join",
"google_matrix",
"gutman_index",
"harmonic_centrality",
"harmonic_diameter",
"hits",
"hyper_wiener_index",
"k_core",
"k_corona",
"k_crust",
"k_shell",
"k_truss",
"katz_centrality",
"laplacian_matrix",
"mixing_expansion",
"modularity",
"modularity_matrix",
"mutual_weight",
"normalized_cut_size",
"normalized_laplacian_matrix",
"overlapping_modularity",
"pagerank",
"reverse",
"schultz_index",
"tournament_matrix",
"union",
"volume",
"wiener_index",
)
for _names, _note in (
(FLOAT32_SERVED, _FLOAT32_SERVED),
(NARROW_LENGTHS_LEFT, _NARROW_LENGTHS_LEFT),
(NARROW_LEFT, _NARROW_LEFT),
):
for _name in _names:
_doc = _ADDITIONAL_DOCS.get(_name)
_ADDITIONAL_DOCS[_name] = _note if _doc is None else f"{_doc}\n{_note}"


def get_functions():
from graphblas_algorithms.interface import Dispatcher

Expand Down
40 changes: 39 additions & 1 deletion graphblas_algorithms/classes/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,14 +79,52 @@ def from_networkx(cls, G, weight=None, dtype=None):
raise NotImplementedError(reason)
rv = cls()
rv._key_to_id = {k: i for i, k in enumerate(G)}
if rv._key_to_id:
if rv._key_to_id and weight is not None and not G.is_multigraph():
rv._A, rv._weight_types = _weighted_matrix(G, rv._key_to_id, weight, dtype)
elif rv._key_to_id:
rv._A = gb.io.from_networkx(G, nodelist=rv._key_to_id, weight=weight, dtype=dtype)
else:
rv._A = Matrix(dtype if dtype is not None else float)
rv._weight = weight
return rv


def _weighted_matrix(G, index, weight, dtype):
"""The matrix `gb.io.from_networkx` builds, and the types of the weights it read.

The same steps as NetworkX's `to_scipy_sparse_array` (one body from 3.6 through 3.7), so
that the one walk of the edges that reads each weight (a missing one as the int 1) also
gives their types, which `interface._narrow_weights` asks for.
"""
import networkx as nx
import scipy as sp

if dtype is not None:
dtype = dtypes.lookup_dtype(dtype).np_type
n = len(index)
coefficients = zip(
*((index[u], index[v], wt) for u, v, wt in G.edges(data=weight, default=1)), strict=True
)
try:
row, col, data = coefficients
except ValueError:
row, col, data = [], [], []
types = frozenset(map(type, data))
if G.is_directed():
A = sp.sparse.coo_array((data, (row, col)), shape=(n, n), dtype=dtype)
else:
# Each edge both ways; a self-loop's second entry is taken back off the diagonal.
d, r, c = data + data, row + col, col + row
selfloops = list(nx.selfloop_edges(G, data=weight, default=1))
if selfloops:
diag_index, diag_data = zip(*((index[u], -wt) for u, v, wt in selfloops), strict=True)
d += diag_data
r += diag_index
c += diag_index
A = sp.sparse.coo_array((d, (r, c)), shape=(n, n), dtype=dtype)
return gb.io.from_scipy_sparse(A.asformat("csr")), types


##############
# Properties #
##############
Expand Down
127 changes: 127 additions & 0 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,90 @@ def _ints_held_as_floats(graph, attr, G):
return None


# The names whose answer for weights that are all `np.float32` is NetworkX's exactly. NumPy
# (NEP 50) adds a float32 and a Python number in float32, so NetworkX's lengths are float32 sums
# from the first weight on. These names add each path's weights edge by edge in float32, as
# NetworkX does, and only compare the sums: Bellman-Ford's path and its negative-cycle test, and
# center and periphery. floyd_warshall_numpy widens to float64 first, as NetworkX's array does,
# and adjacency_matrix adds nothing. A name that returns the lengths is left to NetworkX: its
# lengths are `np.float32`, which a caller (NetworkX's own average_shortest_path_length among
# them) adds in float32, where a result here holds Python floats, as NetworkX's test mode asks
# of a backend. The other names sum or compare in another order or type, and a rebuild would
# carry the weights as Python floats, which NetworkX's own code then adds in float64 (cut_size
# adds the weights edge_boundary gives).
_FLOAT32_EXACT = frozenset(
{
"adjacency_matrix",
"bellman_ford_path",
"center",
"floyd_warshall_numpy",
"negative_edge_cycle",
"periphery",
}
)


@functools.cache
def _float32_sums_stay_float32():
"""True where NumPy adds a float32 and a Python number in float32 (NEP 50, NumPy 2).

NetworkX's sums start from the int 0. Under the older rule they are float64 from the first
weight on, and no float32 matrix adds as they do.
"""
import numpy as np

return type(np.float32(1) + 0) is np.float32 and type(np.float32(1) + 0.5) is np.float32


def _adds_narrow_as_networkx(name, narrow):
"""True if `name` answers as NetworkX does for weights that are all of the type `narrow`."""
import numpy as np

return narrow is np.float32 and name in _FLOAT32_EXACT and _float32_sums_stay_float32()


def _narrow_weights(graph, attr, G):
"""The narrow type of `graph`'s `attr` values, if all are one, or why they cannot be held.

NumPy (NEP 50) adds an `np.float16`, `np.float32` or `np.complex64` and a Python number, or
the same type, in that narrow type, and a wider NumPy type in the wider one. So NetworkX's
sums change type along a path wherever the weights do, while a matrix holds every value in
the one dtype numpy infers for them all and adds in that. Such a mix is refused, for every
name. A missing attribute counts as NetworkX reads it, the int 1. Weights that are all one
narrow type give that type, and their matrix holds them in it; they are served only by the
names in `_FLOAT32_EXACT`.

The types come from the conversion's own walk of the edges (`from_networkx`), so no second
walk is made; a graph built another way has its edges read here.
"""
import numpy as np

A = G._A
dtype = A.dtype.np_type
types = G.__dict__.pop("_weight_types", None)
if A.nvals == 0 or dtype.kind not in "fc":
return None
if types is None:
types = {
type(datadict.get(attr, 1))
for nbrs in graph._adj.values()
for datadict in nbrs.values()
}
narrow = sorted(
(t for t in types if issubclass(t, np.float16 | np.float32 | np.complex64)),
key=lambda t: t.__name__,
)
if not narrow:
return None
if len(types) == 1:
return narrow[0]
names = " and ".join(f"np.{t.__name__}" for t in narrow)
return (
f"mixes {names} with other numbers, which NetworkX adds in the narrow type from the "
f"first such weight on, where its matrix holds them all as {dtype}"
)


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.

Expand Down Expand Up @@ -580,6 +664,13 @@ def convert_from_nx(
# with the arguments as given. A refused conversion is not cached for another name.
if weight is not None and (problem := _ints_held_as_floats(graph, weight, G)):
raise NotImplementedError(f"Edge attribute {weight!r} {problem}")
if weight is not None and (narrow := _narrow_weights(graph, weight, G)) is not None:
if isinstance(narrow, str):
raise NotImplementedError(f"Edge attribute {weight!r} {narrow}")
# Kept and marked, so that NetworkX caches a conversion the names that add these
# weights as it does (`_FLOAT32_EXACT`) can use. The others decline at their call
# (`_narrow_guard`), on this conversion or a cached one.
G._narrow_weights = narrow
# 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:
Expand Down Expand Up @@ -678,3 +769,39 @@ def key(testpath):
for (test_name, keywords), reason in xfail.items():
if base_name == test_name and keywords.issubset(kset):
item.add_marker(pytest.mark.xfail(reason=reason))


def _narrow_guard(name, func):
"""`func`, declining weights all of one narrow type unless `name` adds them as NetworkX.

The conversion keeps such a graph, so that NetworkX's cache holds a good one for the next
name; a refusal there would leave NetworkX's failed mark for every name instead. This
declines each call given one: the call that made it, a later one NetworkX serves from its
cache, or a call on a graph of this backend's that came from one.
"""

@functools.wraps(func)
def call(*args, **kwargs):
for arg in (*args, *kwargs.values()):
narrow = getattr(arg, "_narrow_weights", None)
if narrow is not None and not _adds_narrow_as_networkx(name, narrow):
raise NotImplementedError(
f"{name} on weights that are all np.{narrow.__name__}, which NetworkX adds "
"in that type, is not answered as NetworkX answers it; networkx serves it"
)
return func(*args, **kwargs)

return call


def _guard_narrow_names():
# Every name that reads weights or carries edge data (a test keeps the lists whole).
from _nx_graphblas import core

for name in (*core.FLOAT32_SERVED, *core.NARROW_LENGTHS_LEFT, *core.NARROW_LEFT):
func = getattr(Dispatcher, name, None)
if func is not None:
setattr(Dispatcher, name, _narrow_guard(name, func))


_guard_narrow_names()
2 changes: 1 addition & 1 deletion graphblas_algorithms/tests/test_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def test_multigraph_conversion_is_refused_rather_than_collapsed():
np.int32(3),
np.uint8(3),
np.float64(2.5),
np.float32(2.5),
# np.float32, which NetworkX adds in float32, is left to it (test_narrow_weights.py).
np.bool_(True),
np.complex128(1 + 2j),
0,
Expand Down
Loading
Loading