Skip to content
Open
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
31 changes: 16 additions & 15 deletions _nx_graphblas/__init__.py

Large diffs are not rendered by default.

49 changes: 32 additions & 17 deletions _nx_graphblas/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,40 +87,54 @@

_ECCENTRICITY_BOUNDS = (
"`usebounds` bounds the eccentricities on an undirected graph whose lengths are integers;\n"
"elsewhere every one is computed. The null graph is left to NetworkX.\n"
+ _NEGATIVE_EDGES
+ "\n"
+ _PATH_OVERFLOW
"elsewhere every one is computed. The null graph gets the installed NetworkX's own answer,\n"
"which differs between its versions.\n" + _NEGATIVE_EDGES + "\n" + _PATH_OVERFLOW
)

_CORE_SUBGRAPH = (
"A precomputed `core_number`, or a `k` that is not a real number, is left to NetworkX."
"A precomputed `core_number` is left to NetworkX. A `k` that is not a real number is\n"
"compared with each core number as NetworkX compares it."
)

# NetworkX takes a node named "weight" for its `weight` argument, a bug that raises TypeError.
_NODE_NAMED_WEIGHT = (
'A graph with a node named "weight" gets the index its degree gives, where NetworkX raises\n'
"TypeError or, if the graph is disconnected, gives inf; a NetworkX graph with such a node is\n"
"left to the next backend or NetworkX.\n"
)

# Prose NetworkX shows under a function's documentation, for behaviour its docstring does not
# describe.
_ADDITIONAL_DOCS = {
"all_pairs_bellman_ford_path_length": _PATH_OVERFLOW,
"average_shortest_path_length": (
'A `method` other than None, "unweighted", "dijkstra" and "bellman-ford" is left to\n'
'NetworkX. Lengths are Bellman-Ford\'s, with `method="dijkstra"` too, so a negative edge\n'
"without a negative cycle is answered where NetworkX's Dijkstra raises\n"
'"Contradictory paths found".'
'Lengths are Bellman-Ford\'s, whatever the `method`: with `method="dijkstra"`, a negative\n'
"edge without a negative cycle is answered where NetworkX's Dijkstra raises\n"
'"Contradictory paths found", and with Floyd-Warshall a negative cycle raises\n'
"NetworkXUnbounded, as NetworkX 3.7 does. NetworkX 3.6's Floyd-Warshall gives a number\n"
"there, so on NetworkX 3.6 a NetworkX graph with a negative weight is left to the next\n"
"backend or NetworkX for Floyd-Warshall."
),
"bellman_ford_path": _PATH_OVERFLOW,
"bellman_ford_path_length": _PATH_OVERFLOW,
"bethe_hessian_matrix": (
"NetworkX reads `weight` here but converts no edge data for it, so a NetworkX graph with\n"
"weights is left to NetworkX. A backend graph's values are read where they are `weight`'s."
),
"betweenness_centrality": (
"Unweighted: a call with `weight`, or with `k` short of every node, is left to NetworkX."
),
"betweenness_centrality_subset": "Unweighted: a call with `weight` is left to NetworkX.",
"bfs_edges": (
"A breadth-first tree that may differ from NetworkX's, as may the order: a node's parent\n"
"is its neighbor on the level above first in node order, and each level comes by parent,\n"
"then child, in node order. `sort_neighbors` is left to NetworkX."
"then child, in node order. With `sort_neighbors`, NetworkX's walk, which hands\n"
"`sort_neighbors` each node's neighbors in node order, not in the order they were added;\n"
"a NetworkX graph is left to the next backend or NetworkX."
),
"bfs_successors": (
"The children in `bfs_edges`'s tree, which may differ from NetworkX's, as may the order.\n"
"`sort_neighbors` is left to NetworkX."
"With `sort_neighbors`, as in `bfs_edges`."
),
"center": _ECCENTRICITY_BOUNDS,
"closeness_centrality": _NEGATIVE_EDGES,
Expand All @@ -129,7 +143,8 @@
),
"cut_size": _SUM_OVERFLOW + ".",
"diameter": _ECCENTRICITY_BOUNDS,
"eccentricity": "A precomputed `sp`, and the null graph, are left to NetworkX.\n"
"eccentricity": "A precomputed `sp` is left to NetworkX. The null graph gets the installed\n"
"NetworkX's own answer, which differs between its versions.\n"
+ _NEGATIVE_EDGES
+ "\n"
+ _PATH_OVERFLOW,
Expand All @@ -152,13 +167,14 @@
"floyd_warshall": _PATH_OVERFLOW,
"floyd_warshall_predecessor_and_distance": _PATH_OVERFLOW,
"group_closeness_centrality": "Unweighted: a call with `weight` is left to NetworkX.",
"gutman_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"gutman_index": _NODE_NAMED_WEIGHT + _LENGTH_SUM_OVERFLOW,
"harmonic_centrality": _NEGATIVE_EDGES,
"harmonic_diameter": "A precomputed `sp` is left to NetworkX.\n" + _NEGATIVE_EDGES,
"hits": (
"A graph with nodes and no edges gets 0.0 for every node, where NetworkX's power\n"
'iteration does not converge. `method="svd"` is left to NetworkX.'
'iteration does not converge. `method="svd"` is computed as NetworkX 3.7 computes it,\n'
"with SciPy's `svds` on this backend's matrix. NetworkX 3.6 has no `method`; there this\n"
'backend takes it as its own keyword, "power_iteration" or "svd".'
),
"hyper_wiener_index": _LENGTH_SUM_OVERFLOW,
"k_core": _CORE_SUBGRAPH,
Expand All @@ -173,8 +189,7 @@
"negative_edge_cycle": _PATH_OVERFLOW,
"periphery": _ECCENTRICITY_BOUNDS,
"radius": _ECCENTRICITY_BOUNDS,
"schultz_index": 'A graph with a node named "weight" is left to NetworkX.\n'
+ _LENGTH_SUM_OVERFLOW,
"schultz_index": _NODE_NAMED_WEIGHT + _LENGTH_SUM_OVERFLOW,
"single_source_bellman_ford_path_length": _PATH_OVERFLOW,
"volume": _SUM_OVERFLOW + ", or to 2**63 over the most times `S` names one node.",
"wiener_index": _NEGATIVE_EDGES + "\n" + _LENGTH_SUM_OVERFLOW,
Expand Down
7 changes: 6 additions & 1 deletion graphblas_algorithms/algorithms/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,9 +140,14 @@ def k_crust(G, k=None, core=None):


def k_corona(G, k, core=None):
"""The nodes of core number k with exactly k neighbors in the k-core; successors if directed."""
"""The nodes of core number k with exactly k neighbors in the k-core; successors if directed.

A `k` of None is the largest core number, as NetworkX takes it.
"""
if core is None:
core = core_number(G)
if k is None:
k = _largest(core)
n = len(G)
numbers = _dense(core, n)
inside = Vector.from_coo(np.flatnonzero(numbers >= k), True, size=n)
Expand Down
2 changes: 2 additions & 0 deletions graphblas_algorithms/classes/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,8 @@ def from_networkx(cls, G, weight=None, dtype=None):
if reason is not None:
raise NotImplementedError(reason)
rv = cls()
# The class NetworkX names in its errors, such as a user's subclass of `nx.Graph`.
rv._networkx_class_name = type(G).__name__
rv._key_to_id = {k: i for i, k in enumerate(G)}
if rv._key_to_id:
rv._A = gb.io.from_networkx(G, nodelist=rv._key_to_id, weight=weight, dtype=dtype)
Expand Down
65 changes: 57 additions & 8 deletions graphblas_algorithms/nxapi/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import numpy as np

from graphblas_algorithms import algorithms
from graphblas_algorithms.algorithms.core import _induced
from graphblas_algorithms.classes._utils import PRESERVE
from graphblas_algorithms.classes.digraph import to_graph
from graphblas_algorithms.classes.graph import to_undirected_graph
Expand Down Expand Up @@ -60,11 +61,51 @@ def _own_core_numbers(bound):
# with its own errors node by node.
if bound.get("core_number") is not None:
return "a precomputed `core_number` is not read here; networkx serves it"
if bound.get("k") is not None and not isinstance(bound["k"], Real):
return "a `k` that is not a real number is left to networkx; networkx serves it"
return None


# NetworkX's test of a node `v`, with core numbers `c` and neighbors `adj[v]`, for each name.
_TESTS = {
"k_core": lambda adj, v, k, c: c[v] >= k,
"k_shell": lambda adj, v, k, c: c[v] == k,
"k_crust": lambda adj, v, k, c: c[v] <= k,
"k_corona": lambda adj, v, k, c: c[v] == k and k == sum(1 for w in adj[v] if c[w] >= k),
}


def _by_networkx_s_test(name, G, k):
"""The subgraph whose nodes pass NetworkX's own test against a `k` that is not a number.

NetworkX compares each core number with `k` in Python, so a `k` such as a string raises
its TypeError, a Decimal compares as a number, and a null graph compares nothing.
"""
core = _by_node(G, algorithms.core_number(G).to_dense(fill_value=0))
test = _TESTS[name]
adj = _Neighbors(G) if name == "k_corona" else None
keep = np.zeros(len(G), bool)
key_to_id = G._key_to_id
for v in core:
if test(adj, v, k, core):
keep[key_to_id[v]] = True
return _induced(G, keep)


class _Neighbors:
"""`G[v]` for NetworkX's k-corona test: the keys of `v`'s successors, by id."""

def __init__(self, G):
self._key_to_id = G._key_to_id
self._id_to_key = G.id_to_key
self._indptr, self._indices, _values = G._A.to_csr()

def __getitem__(self, v):
i = self._key_to_id[v]
return [
self._id_to_key[j]
for j in self._indices[self._indptr[i] : self._indptr[i + 1]].tolist()
]


def _max_of_nothing():
try:
return max(())
Expand All @@ -80,45 +121,53 @@ def _check_subgraph_call(G, k):
raise ValueError(*_max_of_nothing().args)


def _refuse_what_can_run_declines(k, core_number):
def _refuse_what_can_run_declines(core_number):
# A direct call does not pass through `can_run`.
if (reason := _own_core_numbers({"k": k, "core_number": core_number})) is not None:
if (reason := _own_core_numbers({"core_number": core_number})) is not None:
raise NotImplementedError(reason)


@can_run(_own_core_numbers)
@not_implemented_for("multigraph")
def k_core(G, k=None, core_number=None):
_refuse_what_can_run_declines(k, core_number)
_refuse_what_can_run_declines(core_number)
G = to_graph(G, weight=PRESERVE)
_check_subgraph_call(G, k)
if k is not None and not isinstance(k, Real):
return _by_networkx_s_test("k_core", G, k)
return algorithms.k_core(G, k)


@can_run(_own_core_numbers)
@not_implemented_for("multigraph")
def k_shell(G, k=None, core_number=None):
_refuse_what_can_run_declines(k, core_number)
_refuse_what_can_run_declines(core_number)
G = to_graph(G, weight=PRESERVE)
_check_subgraph_call(G, k)
if k is not None and not isinstance(k, Real):
return _by_networkx_s_test("k_shell", G, k)
return algorithms.k_shell(G, k)


@can_run(_own_core_numbers)
@not_implemented_for("multigraph")
def k_crust(G, k=None, core_number=None):
_refuse_what_can_run_declines(k, core_number)
_refuse_what_can_run_declines(core_number)
G = to_graph(G, weight=PRESERVE)
_check_subgraph_call(G, k)
if k is not None and not isinstance(k, Real):
return _by_networkx_s_test("k_crust", G, k)
return algorithms.k_crust(G, k)


@can_run(_own_core_numbers)
@not_implemented_for("multigraph")
def k_corona(G, k, core_number=None):
_refuse_what_can_run_declines(k, core_number)
_refuse_what_can_run_declines(core_number)
G = to_graph(G, weight=PRESERVE)
_check_subgraph_call(G, k)
if k is not None and not isinstance(k, Real):
return _by_networkx_s_test("k_corona", G, k)
return algorithms.k_corona(G, k)


Expand Down
52 changes: 28 additions & 24 deletions graphblas_algorithms/nxapi/distance_measures.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,25 @@
__all__ = ["center", "diameter", "eccentricity", "harmonic_diameter", "periphery", "radius"]


def _with_nodes(bound):
# NetworkX 3.6 answers the null graph with an empty dict or a ValueError, 3.7 with
# NetworkXPointlessConcept, and `usebounds` with a ValueError; each version answers its own.
if len(bound["G"]) == 0:
return "NetworkX's answer for the null graph depends on its version; networkx serves it"
def _without_sp_on_nodes(bound):
# Rebuilding a matrix from the caller's dict would cost more than the walks it saves. The
# null graph's answer is NetworkX's own, whatever `sp` holds.
if bound.get("sp") is not None and len(bound["G"]) > 0:
return "eccentricity does not read a precomputed `sp`; networkx serves it"
return None


def _with_nodes_without_sp(bound):
# Rebuilding a matrix from the caller's dict would cost more than the walks it saves.
if bound.get("sp") is not None:
return "eccentricity does not read a precomputed `sp`; networkx serves it"
return _with_nodes(bound)
def _networkx_on_the_null_graph(name, G, **kwargs):
"""NetworkX's own answer for a null graph like `G`: it differs between NetworkX's versions.

NetworkX 3.6 answers with an empty dict or a ValueError, and later versions with
NetworkXPointlessConcept, except `usebounds` with a ValueError. A null graph holds nothing
to convert or walk, so the installed NetworkX is asked directly.
"""
import networkx as nx

null = nx.DiGraph() if G.is_directed() else nx.Graph()
return getattr(nx, name)(null, backend="networkx", **kwargs)


def _without_sp(bound):
Expand Down Expand Up @@ -57,9 +63,11 @@ def _extreme_nodes(e, pick):
return [v for v in e if e[v] == target]


@can_run(_with_nodes_without_sp)
@can_run(_without_sp_on_nodes)
def eccentricity(G, v=None, sp=None, weight=None):
if (reason := _with_nodes_without_sp({"G": G, "sp": sp})) is not None:
if len(G) == 0:
return _networkx_on_the_null_graph("eccentricity", G, v=v, sp=sp, weight=weight)
if (reason := _without_sp_on_nodes({"G": G, "sp": sp})) is not None:
raise NotImplementedError(reason)
G = to_graph(G, weight=weight)
keys = nbunch_keys(G, v, unique=True)
Expand All @@ -69,40 +77,36 @@ def eccentricity(G, v=None, sp=None, weight=None):
return {key: ecc[key] for key in (G if keys is None else keys)}


@can_run(_with_nodes)
def diameter(G, e=None, usebounds=False, weight=None):
if (reason := _with_nodes({"G": G})) is not None:
raise NotImplementedError(reason)
if len(G) == 0:
return _networkx_on_the_null_graph("diameter", G, e=e, usebounds=usebounds, weight=weight)
if e is not None:
return max(e.values())
G = to_graph(G, weight=weight)
return _answer(G, algorithms.diameter, usebounds=usebounds is True)


@can_run(_with_nodes)
def radius(G, e=None, usebounds=False, weight=None):
if (reason := _with_nodes({"G": G})) is not None:
raise NotImplementedError(reason)
if len(G) == 0:
return _networkx_on_the_null_graph("radius", G, e=e, usebounds=usebounds, weight=weight)
if e is not None:
return min(e.values())
G = to_graph(G, weight=weight)
return _answer(G, algorithms.radius, usebounds=usebounds is True)


@can_run(_with_nodes)
def periphery(G, e=None, usebounds=False, weight=None):
if (reason := _with_nodes({"G": G})) is not None:
raise NotImplementedError(reason)
if len(G) == 0:
return _networkx_on_the_null_graph("periphery", G, e=e, usebounds=usebounds, weight=weight)
if e is not None:
return _extreme_nodes(e, max)
G = to_graph(G, weight=weight)
return _in_node_order(G, _answer(G, algorithms.periphery, usebounds=usebounds is True))


@can_run(_with_nodes)
def center(G, e=None, usebounds=False, weight=None):
if (reason := _with_nodes({"G": G})) is not None:
raise NotImplementedError(reason)
if len(G) == 0:
return _networkx_on_the_null_graph("center", G, e=e, usebounds=usebounds, weight=weight)
if e is not None:
return _extreme_nodes(e, min)
G = to_graph(G, weight=weight)
Expand Down
28 changes: 16 additions & 12 deletions graphblas_algorithms/nxapi/linalg/bethehessianmatrix.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,29 +4,33 @@
from graphblas_algorithms.classes.graph import Graph, to_undirected_graph
from graphblas_algorithms.utils import not_implemented_for

from .._cache import remembered
from .._utils import can_run, check_nodelist

__all__ = ["bethe_hessian_matrix"]


def _unweighted_only(bound):
"""Decline a weighted graph.
def _weights_converted(bound):
"""Decline a NetworkX graph with weights, which NetworkX's conversion would leave behind.

NetworkX reads `weight` here without declaring it, so a NetworkX graph's weights never
reach this backend; a backend graph's values may be another attribute's, so it is
declined whenever it has any.
NetworkX reads `weight` here without declaring it, so its conversion for this name carries
no edge data. A backend graph is served: its values are read where they are `weight`'s,
and otherwise every edge weighs 1, as NetworkX reads the graph.
"""
G = bound["G"]
if isinstance(G, Graph):
weighted = G._weight is not None
else:
weighted = any("weight" in data for _u, _v, data in G.edges(data=True))
if weighted:
return "bethe_hessian_matrix is unweighted here; networkx serves a weighted graph"
if not isinstance(G, Graph) and remembered(G, ("edge attribute", "weight"), _has_weights):
return (
"NetworkX converts no edge data for bethe_hessian_matrix, which reads `weight`; "
"a NetworkX graph with weights is left to the next backend or NetworkX"
)
return None


@can_run(_unweighted_only)
def _has_weights(G):
return any("weight" in data for _u, _v, data in G.edges(data=True))


@can_run(_weights_converted)
@not_implemented_for("directed")
@not_implemented_for("multigraph")
def bethe_hessian_matrix(G, r=None, nodelist=None):
Expand Down
Loading
Loading