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
34 changes: 22 additions & 12 deletions graphblas_algorithms/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from collections import namedtuple

from . import nxapi
from .nxapi._cache import remembered

#######
# NOTE: Remember to run `python scripts/maketree.py` when adding or removing algorithms
Expand Down Expand Up @@ -190,20 +191,13 @@ def _unrebuildable(graph, weight, preserve_edge_attrs, *, keeps_node_data=True):


def _rebuild_refusal(graph, preserve_edge_attrs):
"""`_unrebuildable`'s reason for `graph`, remembered in the graph's `__networkx_cache__`.
"""`_unrebuildable`'s reason for `graph`, read once per version of the graph."""
preserve = bool(preserve_edge_attrs)

The memo follows NetworkX's own cached conversions: NetworkX empties that cache whenever the
graph is mutated, and with `cache_converted_graphs` off, or no cache, it scans each time.
"""
import networkx as nx
def reason(graph):
return _unrebuildable(_materialize_virtual_adjacency(graph), None, preserve)[1]

cache = getattr(graph, "__networkx_cache__", None) if nx.config.cache_converted_graphs else None
memo = {} if cache is None else cache.setdefault("graphblas_rebuild", {})
key = bool(preserve_edge_attrs)
if key not in memo:
graph = _materialize_virtual_adjacency(graph)
memo[key] = _unrebuildable(graph, None, preserve_edge_attrs)[1]
return memo[key]
return remembered(graph, ("rebuild", preserve), reason)


def _materialize_virtual_adjacency(graph):
Expand Down Expand Up @@ -591,6 +585,22 @@ def can_run(name, args, kwargs):
return reason
return True

@staticmethod
def should_run(name, args, kwargs):
"""True if serving `name` here should be faster than NetworkX, else the reason not.

NetworkX asks only where it would convert a graph to call this backend, after `can_run`
said yes. A wrapper's own rule is its `_should_run` attribute, set with
`nxapi._utils.should_run`.
"""
hook = getattr(getattr(Dispatcher, name, None), "_should_run", None)
if hook is None:
return True
bound = _bound_args(name, args, kwargs)
if bound is None or (reason := hook(bound)) is None:
return True
return reason

@staticmethod
def on_start_tests(items):
"""Mark the tests in NetworkX's suite that this backend cannot pass; the table is empty.
Expand Down
118 changes: 118 additions & 0 deletions graphblas_algorithms/nxapi/_cache.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
"""What this backend keeps in a NetworkX graph's `__networkx_cache__`, and reads from it.

NetworkX owns that cache. It keeps its conversions there and empties it when the graph changes
through its methods; after an edit to the data in place, the caller clears it. A fact kept here
lives and dies with those conversions.
"""


def _in_networkx_test_mode():
"""True in NetworkX's test mode, and where this NetworkX no longer says: the safe answer.

That mode converts afresh for every call that names no backend, so a test may edit a graph's
data in place between calls without clearing its cache.
"""
try:
from networkx.utils.backends import _dispatchable

return bool(_dispatchable._is_testing)
except Exception:
return True


def remembered(graph, key, compute):
"""`compute(graph)`, kept in the graph's `__networkx_cache__` until NetworkX empties it.

For a rule that reads a fact from a NetworkX graph before every call, so that it reads the
graph once per version. Nothing is kept while `cache_converted_graphs` is off, when an edit
in place needs no clearing; in NetworkX's test mode, for the same reason; for a graph without
a cache; or for a view, since NetworkX does not empty a view's cache when the graph under it
changes.
"""
import networkx as nx

cache = getattr(graph, "__networkx_cache__", None) if nx.config.cache_converted_graphs else None
# NetworkX's views hold their graph as `_graph`.
if cache is None or hasattr(graph, "_graph") or _in_networkx_test_mode():
return compute(graph)
memo = cache.setdefault("graphblas_facts", {})
if key not in memo:
memo[key] = compute(graph)
return memo[key]


# What NetworkX's `_convert_graph` builds its cache key from.
_KEY_ARGUMENTS = (
"edge_attrs",
"node_attrs",
"preserve_edge_attrs",
"preserve_node_attrs",
"preserve_graph_attrs",
)


class _CacheKeys:
"""A stand-in for a dispatched function that records the cache key of each graph converted.

NetworkX's `_convert_arguments` reads the call's arguments into what each graph's conversion
must carry; run on this, it records the key of each graph argument where NetworkX would
convert it, by the argument's name.
"""

def __init__(self, func):
self._func = func
self.recorded = {}

def __getattr__(self, attr):
return getattr(self._func, attr)

def _convert_graph(self, backend_name, graph, **kwargs):
from networkx.utils.backends import _get_cache_key

key = _get_cache_key(**{name: kwargs[name] for name in _KEY_ARGUMENTS})
self.recorded[kwargs["graph_name"]] = key
return graph


def has_reusable_conversion(name, bound, graph_name="G"):
"""True if NetworkX will give this call of `name` a cached conversion of `bound[graph_name]`.

`bound` holds the call's arguments by name, as a `can_run` or `should_run` hook gets them.
The key is the one NetworkX's own code makes for this call, and the search is its own, so
a conversion cached for other attributes counts only where NetworkX would use it. False
where it cannot be sure: for a view, whose cached conversions NetworkX keeps when the graph
under it changes, so that one may be stale; in NetworkX's test mode, which converts afresh
for a call that names no backend; or if NetworkX's private names used here have changed.
"""
import networkx as nx

graph = bound.get(graph_name)
cache = getattr(graph, "__networkx_cache__", None)
if not cache or not nx.config.cache_converted_graphs or _in_networkx_test_mode():
return False
try:
# NetworkX's views hold their graph as `_graph`.
if hasattr(graph, "_graph"):
return False
return _cached_for(name, bound, graph_name, cache)
except Exception:
return False


def _cached_for(name, bound, graph_name, cache):
"""`has_reusable_conversion`'s search, through NetworkX's private names."""
from networkx.utils import backends

# The registry holds a function wrapping the dispatchable object.
func = backends._registered_algorithms[name].__wrapped__
if not isinstance(func, backends._dispatchable):
return False
keys = _CacheKeys(func)
backends._dispatchable._convert_arguments(
keys, "graphblas", (), dict(bound), use_cache=True, mutations=None
)
if graph_name not in keys.recorded:
return False # not converted: a backend graph already
converted = dict(cache.get("backends", {}).get("graphblas", {})) # the search may write to it
_key, found = backends._get_from_cache(converted, keys.recorded[graph_name])
return found is not None and found != backends.FAILED_TO_CONVERT
14 changes: 14 additions & 0 deletions graphblas_algorithms/nxapi/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,20 @@ def decorator(func):
return decorator


def should_run(hook):
"""Give the decorated wrapper `hook` as its rule in `Dispatcher.should_run`.

`hook(bound)` gets the arguments as `can_run`'s hook does, and returns the reason NetworkX
should serve the call itself, as the faster of the two, or None to serve it here.
"""

def decorator(func):
func._should_run = hook
return func

return decorator


def check_nodelist(G, nodelist, *, null_graph=True):
"""Refuse what NetworkX's `to_scipy_sparse_array` refuses, in the order it checks.

Expand Down
2 changes: 1 addition & 1 deletion graphblas_algorithms/tests/test_dispatch.py
Original file line number Diff line number Diff line change
Expand Up @@ -647,4 +647,4 @@ def test_the_rebuild_verdict_is_not_kept_while_networkx_caches_no_conversions(mo
monkeypatch.setattr(nx.config, "cache_converted_graphs", False)
G = two_edge_attributes()
assert isinstance(Dispatcher.can_run("k_truss", (G, 2), {}), str)
assert "graphblas_rebuild" not in G.__networkx_cache__
assert "graphblas_facts" not in G.__networkx_cache__
Loading
Loading