diff --git a/graphblas_algorithms/algorithms/_helpers.py b/graphblas_algorithms/algorithms/_helpers.py index 3eddc1b..93de72e 100644 --- a/graphblas_algorithms/algorithms/_helpers.py +++ b/graphblas_algorithms/algorithms/_helpers.py @@ -1,5 +1,7 @@ from graphblas import binary, dtypes, monoid, unary +from ..classes._utils import current_snapshot + _ADVICE = ( "which 64-bit integers cannot hold; NetworkX computes with Python integers. Convert the " "weights to float, or call with backend='networkx'." @@ -45,6 +47,8 @@ def checked_sum_type(G, kind, *, count=1): - "sum": the absolute values, each counted up to `count` times, must sum to less than 2**63. Other values are added in their own type, and never raise. """ + # One snapshot throughout: the matrix, its properties and the sum cached for it agree + G = current_snapshot(G) A = G._A if A.dtype.np_type.kind not in "biu": return A.dtype @@ -61,7 +65,9 @@ def checked_sum_type(G, kind, *, count=1): heaviest = max(-least.get(0), greatest.get(0)) # The cheap bound first: the absolute sum is needed only when it fails. if A.nvals * heaviest * count >= 2**63: - total = G._cacheit("abs_sum+", _abs_sum, A) + cache = G._properties + if (total := cache.get("abs_sum+")) is None: + total = cache["abs_sum+"] = _abs_sum(A) if total * count >= 2**63: times = f", counted up to {count} times," if count > 1 else "" raise OverflowError( diff --git a/graphblas_algorithms/algorithms/dag.py b/graphblas_algorithms/algorithms/dag.py index 9483e70..58522fd 100644 --- a/graphblas_algorithms/algorithms/dag.py +++ b/graphblas_algorithms/algorithms/dag.py @@ -1,6 +1,7 @@ from graphblas import Vector, replace from graphblas.semiring import any_pair +from ..classes._utils import current_snapshot from ._bfs import _bfs_plain __all__ = ["ancestors", "descendants", "is_acyclic"] @@ -27,10 +28,10 @@ def is_acyclic(G): whatever survives when nothing can be peeled is on a cycle. One vector-matrix product per round, as many rounds as the longest path, so the answer is cached on the graph. """ - cache = G._cache + snapshot = current_snapshot(G) # the matrix and the cache the answer is kept in + cache, A = snapshot._properties, snapshot._A if (cached := cache.get("is_acyclic")) is not None: return cached - A = G._A alive = Vector(bool, size=A.nrows, name="alive") alive << True while alive.nvals > 0: diff --git a/graphblas_algorithms/classes/_caching.py b/graphblas_algorithms/classes/_caching.py index 6e2a8e4..46c4469 100644 --- a/graphblas_algorithms/classes/_caching.py +++ b/graphblas_algorithms/classes/_caching.py @@ -11,7 +11,7 @@ def get_reduce_to_vector(key, opname, methodname): if key[-1] == "-": def get_reduction(G, mask=None): - cache = G._cache + cache = G._properties if mask is not None: if key in cache: return cache[key].dup(mask=mask) @@ -66,7 +66,7 @@ def get_reduction(G, mask=None): def get_reduction(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if mask is not None: if key in cache: return cache[key].dup(mask=mask) @@ -103,7 +103,7 @@ def get_reduce_to_scalar(key, opname): if key[-1] == "-": def get_reduction(G, mask=None): - cache = G._cache + cache = G._properties if key not in cache: if cache.get("has_self_edges") is False and f"{keybase}+" in cache: cache[key] = cache[f"{keybase}+"] @@ -144,7 +144,7 @@ def get_reduction(G, mask=None): def get_reduction(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if key not in cache: if cache.get("has_self_edges") is False and f"{keybase}-" in cache: cache[key] = cache[f"{keybase}-"] @@ -172,7 +172,7 @@ def get_reduction(G, mask=None): def get_reduction(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if key not in cache: if not G.get_property("has_self_edges"): cache[key] = Scalar(op_[A.dtype].return_type, name=key) diff --git a/graphblas_algorithms/classes/_utils.py b/graphblas_algorithms/classes/_utils.py index fa821b1..cf49d5d 100644 --- a/graphblas_algorithms/classes/_utils.py +++ b/graphblas_algorithms/classes/_utils.py @@ -3,7 +3,8 @@ import graphblas as gb import numpy as np -from graphblas import Matrix, Vector, binary, dtypes, unary +from graphblas import Matrix, Scalar, Vector, binary, dtypes, unary +from graphblas.core import ffi, lib from graphblas.core.matrix import TransposedMatrix @@ -84,6 +85,7 @@ def from_networkx(cls, G, weight=None, dtype=None): else: rv._A = Matrix(dtype if dtype is not None else float) rv._weight = weight + rv.clear_cache() return rv @@ -104,22 +106,28 @@ def id_to_key(self): def get_property(self, name, *, mask=None): - return self._get_property[self._cache_aliases.get(name, name)](self, mask) + return self._get_property[self._cache_aliases.get(name, name)](current_snapshot(self), mask) def get_properties(self, names, *, mask=None): + return _get_properties(self, None, names, mask) + + +def _get_properties(G, snapshot, names, mask): + # `G` is the graph or its class: the property tables. A graph's own call takes its current + # snapshot; a getter's call (through `_Snapshot.get_properties`) stays on its own. if isinstance(names, str): # Separated by commas and/or spaces names = [ - self._cache_aliases.get(name, name) - for name in names.replace(" ", ",").split(",") - if name + G._cache_aliases.get(name, name) for name in names.replace(" ", ",").split(",") if name ] else: - names = [self._cache_aliases.get(name, name) for name in names] + names = [G._cache_aliases.get(name, name) for name in names] + if snapshot is None: + snapshot = current_snapshot(G) results = { - name: self._get_property[name](self, mask) - for name in sorted(names, key=self._property_priority.__getitem__) + name: G._get_property[name](snapshot, mask) + for name in sorted(names, key=G._property_priority.__getitem__) } return [results[name] for name in names] @@ -337,9 +345,167 @@ def to_networkx(self, edge_attribute=PRESERVE): def _cacheit(self, key, func, *args, **kwargs): - if key not in self._cache: - self._cache[key] = func(*args, **kwargs) - return self._cache[key] + snapshot = current_snapshot(self) + cache = snapshot._properties + if key in cache: + return cache[key] + value = func(*args, **kwargs) + # `func` reads the graph itself, so its value is kept only if the matrix is still the one + # stamped (one replaced and then put back during `func` is not seen) + if current_snapshot(self) is snapshot: + cache[key] = value + return value + + +######### +# Cache # +######### +# A graph's cache is one `_Snapshot`: its matrix, read once, that matrix's GraphBLAS handle and +# number of entries (the stamp), and the properties computed from it. `get_property`, +# `get_properties`, `_cacheit`, `_cache` and `cache_info` take the graph's current snapshot, +# making a new one when `_A` was replaced or gained or lost entries, and put it in place with one +# store. A getter is given the snapshot in place of the graph: it reads `_A` and `_properties` +# from it and asks it for the properties it needs, so a value lands only in the dict of the +# matrix it was computed from, whatever other threads do to the graph meanwhile. A snapshot +# another thread has replaced serves its call to the end and is then dropped. Code that reads +# the matrix and caches from it outside a getter (`checked_sum_type`, `is_acyclic`) takes one +# snapshot with `current_snapshot` and reads both from it. +# +# Readers that share a snapshot fill one dict, and each store can give the GIL to another +# thread, so a reader can find any part of what another call stores. A getter reads only keys +# it has found or stored itself, never one it leaves to a nested call to store. +# +# The snapshot holds the matrix, so its handle is not freed and given to another matrix while it +# is compared; a handle keeps its dtype for its life. The count is read by one C call into a +# buffer the snapshot holds, half the cost of `A._nvals` and a sixth of `A.nvals`; threads +# sharing a snapshot write the same matrix's count into it. + +_MISSING = object() + + +class _PropertyCache(dict): + """A graph's cached properties. + + A GraphBLAS value is finished (`wait`) as it is stored, so that threads sharing the graph + only ever read it. The getters store a value again on every call (filling one key from + another); a value the key already holds is left as it is, without a second `wait`. + """ + + __slots__ = () + + def __setitem__(self, key, value): + if dict.get(self, key, _MISSING) is value: + return + if isinstance(value, (Matrix, Vector, Scalar)): + value.wait() # a cached graph (`structure`) finished its matrix as it was made + dict.__setitem__(self, key, value) + + +class _Snapshot: + """A graph's matrix as one stamp saw it, with the properties computed from that matrix.""" + + __slots__ = ("_A", "_buffer", "_graph_type", "_handle", "_nvals", "_properties") + + def __init__(self, graph_type, A): + # Once per stamp: an unfinished matrix is written to by the reads of later checks + A.wait() + self._A = A + self._handle = A.gb_obj[0] + self._nvals = A._nvals + self._buffer = ffi.new("GrB_Index*") + self._properties = _PropertyCache() + self._graph_type = graph_type + + def get_property(self, name, *, mask=None): + G = self._graph_type + return G._get_property[G._cache_aliases.get(name, name)](self, mask) + + def get_properties(self, names, *, mask=None): + return _get_properties(self._graph_type, self, names, mask) + + +_matrix_nvals = lib.GrB_Matrix_nvals + + +def current_snapshot(self): + """The graph's snapshot, made anew if `_A` was replaced or gained or lost entries.""" + snapshot = self._snapshot + A = self._A + handle = A.gb_obj[0] + # A failed call (a freed handle) makes a new snapshot too, whose `_nvals` raises the error + if ( + snapshot._handle != handle + or _matrix_nvals(snapshot._buffer, handle) + or snapshot._buffer[0] != snapshot._nvals + ): + snapshot = self._snapshot = _Snapshot(type(self), A) + return snapshot + + +def cache(self): + return current_snapshot(self)._properties + + +def clear_cache(self): + """Forget the cached properties; the next call computes what it needs again. + + This happens by itself when the matrix is replaced or gains or loses entries. Call it after + a change that keeps the number of entries: new values, `A << B` with as many entries, one + entry added and another removed, a resize. + """ + self._snapshot = _Snapshot(type(self), self._A) + + +def cache_info(self): + """The bytes each cached property holds, by key. + + GraphBLAS objects and numpy arrays are counted. Memory counted already (the matrix itself, + or a value stored under two keys) counts 0, and a cached graph counts its matrix and its + own cache. + """ + snapshot = current_snapshot(self) + seen = {id(snapshot._A)} + # a copy of the items: a reader sharing the graph may store a property meanwhile + return {key: _nbytes(value, seen) for key, value in list(snapshot._properties.items())} + + +def _nbytes(value, seen): + if id(value) in seen: + return 0 + if isinstance(value, (tuple, list)): + return sum(_nbytes(item, seen) for item in value) + seen.add(id(value)) + if isinstance(value, (Matrix, Vector)): + return value.ss.nbytes + if isinstance(value, Scalar): # what GraphBLAS holds, as `ss.nbytes` counts it + return value.__sizeof__() - object.__sizeof__(value) + if isinstance(value, np.ndarray): + return value.nbytes + if isinstance(getattr(value, "_A", None), Matrix): + items = list(value._cache.values()) + return _nbytes(value._A, seen) + sum(_nbytes(item, seen) for item in items) + return 0 + + +def getstate(self): + # A snapshot's handle and buffer do not pickle: a copy carries its matrix and properties, + # both from one snapshot, and is stamped afresh in `setstate` + snapshot = current_snapshot(self) + state = self.__dict__.copy() + state["_A"] = snapshot._A + state["_snapshot"] = dict(snapshot._properties) + return state + + +def setstate(self, state): + state = dict(state) + # A graph pickled before snapshots, by any earlier release, holds its properties in `_cache` + properties = state.pop("_snapshot", None) or state.pop("_cache", {}) + self.__dict__.update(state) + self.clear_cache() + cache = self._snapshot._properties + for key, value in properties.items(): + cache[key] = value def renumber_key_to_id(self, indices): diff --git a/graphblas_algorithms/classes/digraph.py b/graphblas_algorithms/classes/digraph.py index 1211f11..412a9d2 100644 --- a/graphblas_algorithms/classes/digraph.py +++ b/graphblas_algorithms/classes/digraph.py @@ -24,7 +24,7 @@ def get_AT(G, mask=None): """A.T""" A = G._A - cache = G._cache + cache = G._properties if "AT" not in cache: cache["AT"] = A.T.new() return cache["AT"] @@ -33,7 +33,7 @@ def get_AT(G, mask=None): def get_Up(G, mask=None): """select.triu(A)""" A = G._A - cache = G._cache + cache = G._properties if "U+" not in cache: if "U-" in cache and not G.get_property("has_self_edges"): cache["U+"] = cache["U-"] @@ -52,7 +52,7 @@ def get_Up(G, mask=None): def get_Lp(G, mask=None): """select.tril(A)""" A = G._A - cache = G._cache + cache = G._properties if "L+" not in cache: if "L-" in cache and not G.get_property("has_self_edges"): cache["L+"] = cache["L-"] @@ -71,7 +71,7 @@ def get_Lp(G, mask=None): def get_Um(G, mask=None): """select.triu(A, 1)""" A = G._A - cache = G._cache + cache = G._properties if "U-" not in cache: if "U+" in cache: if cache.get("has_self_edges") is False: @@ -95,7 +95,7 @@ def get_Um(G, mask=None): def get_Lm(G, mask=None): """select.tril(A, -1)""" A = G._A - cache = G._cache + cache = G._properties if "L-" not in cache: if "L+" in cache: if cache.get("has_self_edges") is False: @@ -119,7 +119,7 @@ def get_Lm(G, mask=None): def get_recip_degreesp(G, mask=None): """pair(A & A.T).reduce_rowwise()""" A = G._A - cache = G._cache + cache = G._properties AT = cache.get("AT", A.T) if mask is not None: if "recip_degrees+" in cache: @@ -161,7 +161,7 @@ def get_recip_degreesp(G, mask=None): def get_recip_degreesm(G, mask=None): """C = select.offdiag(A) ; pair(C & C.T).reduce_rowwise()""" A = G._A - cache = G._cache + cache = G._properties if "AT" in cache: AT = cache["AT"] elif "offdiag" in cache: @@ -237,7 +237,7 @@ def get_recip_degreesm(G, mask=None): def get_total_degreesp(G, mask=None): """A.reduce_rowwise(agg.count) + A.reduce_columnwise(agg.count)""" - cache = G._cache + cache = G._properties if mask is not None: if "total_degrees+" in cache: return cache["total_degrees+"].dup(mask=mask) @@ -267,7 +267,7 @@ def get_total_degreesp(G, mask=None): def get_total_degreesm(G, mask=None): """C = select.offdiag(A) ; C.reduce_rowwise(agg.count) + C.reduce_columnwise(agg.count)""" - cache = G._cache + cache = G._properties if mask is not None: if "total_degrees-" in cache: return cache["total_degrees-"].dup(mask=mask) @@ -298,7 +298,7 @@ def get_total_degreesm(G, mask=None): def get_total_recipp(G, mask=None): """pair(A & A.T).reduce_scalar()""" A = G._A - cache = G._cache + cache = G._properties if "total_recip+" not in cache: if "total_recip-" in cache and cache.get("has_self_edges") is False: cache["total_recip+"] = cache["total_recip-"] @@ -316,7 +316,7 @@ def get_total_recipp(G, mask=None): def get_total_recipm(G, mask=None): """C = select.offdiag(A) ; pair(C & C.T).reduce_scalar()""" - cache = G._cache + cache = G._properties if "total_recip-" not in cache: if "total_recip+" in cache and cache.get("has_self_edges") is False: cache["total_recip-"] = cache["total_recip+"] @@ -332,7 +332,7 @@ def get_total_recipm(G, mask=None): def has_self_edges(G, mask=None): """A.diag().nvals > 0""" A = G._A - cache = G._cache + cache = G._properties if "has_self_edges" not in cache: if "offdiag" in cache: cache["has_self_edges"] = A.nvals > cache["offdiag"].nvals @@ -367,7 +367,7 @@ def has_self_edges(G, mask=None): elif "total_degrees+" in cache: cache["has_self_edges"] = cache["total_degrees+"].reduce().get(0) > 2 * A.nvals else: - G.get_property("diag") + cache["has_self_edges"] = G.get_property("diag").nvals > 0 return cache["has_self_edges"] @@ -514,7 +514,14 @@ class DiGraph(Graph): graph_attr_dict_factory = dict def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **attr): - """`weight`: the edge attribute the values came from, or None for structural values.""" + """`incoming_graph_data`: the adjacency, used as it is when it is a Matrix (not copied). + + The cached properties are dropped when the matrix is replaced or gains or loses entries. + A change that keeps the number of entries is not seen: call `clear_cache` after one. + Finish the matrix (`A.wait()`) before threads share the graph. + + `weight`: the edge attribute the values came from, or None for structural values. + """ if incoming_graph_data is not None: # Does not copy if A is a Matrix! A = gb.core.utils.ensure_type(incoming_graph_data, Matrix) @@ -533,7 +540,7 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a key_to_id = {i: i for i in range(A.nrows)} self._key_to_id = key_to_id self._id_to_key = None - self._cache = {} + self.clear_cache() # Graphblas-specific methods from_networkx = classmethod(_utils.from_networkx) @@ -556,6 +563,11 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a vector_to_nodeset = _utils.vector_to_nodeset vector_to_set = _utils.vector_to_set _cacheit = _utils._cacheit + _cache = property(_utils.cache) + clear_cache = _utils.clear_cache + cache_info = _utils.cache_info + __getstate__ = _utils.getstate + __setstate__ = _utils.setstate renumber_key_to_id = _utils.renumber_key_to_id # NetworkX methods diff --git a/graphblas_algorithms/classes/graph.py b/graphblas_algorithms/classes/graph.py index 0848c89..05342fa 100644 --- a/graphblas_algorithms/classes/graph.py +++ b/graphblas_algorithms/classes/graph.py @@ -17,14 +17,14 @@ def get_A(G, mask=None): def get_AT(G, mask=None): """A.T""" A = G._A - G._cache["AT"] = A + G._properties["AT"] = A return A def get_offdiag(G, mask=None): """select.offdiag(A)""" A = G._A - cache = G._cache + cache = G._properties if "offdiag" not in cache: if cache.get("has_self_edges") is False: cache["offdiag"] = A @@ -40,7 +40,7 @@ def get_offdiag(G, mask=None): def get_Up(G, mask=None): """select.triu(A)""" A = G._A - cache = G._cache + cache = G._properties if "U+" not in cache: if "U-" in cache and not G.get_property("has_self_edges"): cache["U+"] = cache["U-"] @@ -56,7 +56,7 @@ def get_Up(G, mask=None): def get_Lp(G, mask=None): """select.tril(A)""" A = G._A - cache = G._cache + cache = G._properties if "L+" not in cache: if "L-" in cache and not G.get_property("has_self_edges"): cache["L+"] = cache["L-"] @@ -72,7 +72,7 @@ def get_Lp(G, mask=None): def get_Um(G, mask=None): """select.triu(A, 1)""" A = G._A - cache = G._cache + cache = G._properties if "U-" not in cache: if "U+" in cache: if G.get_property("has_self_edges"): @@ -93,7 +93,7 @@ def get_Um(G, mask=None): def get_Lm(G, mask=None): """select.tril(A, -1)""" A = G._A - cache = G._cache + cache = G._properties if "L-" not in cache: if "L+" in cache: if G.get_property("has_self_edges"): @@ -114,7 +114,7 @@ def get_Lm(G, mask=None): def get_diag(G, mask=None): """A.diag()""" A = G._A - cache = G._cache + cache = G._properties if "diag" not in cache: if cache.get("has_self_edges") is False: cache["diag"] = Vector(A.dtype, size=A.nrows, name="diag") @@ -133,7 +133,7 @@ def get_diag(G, mask=None): def has_negative_diagonal(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if "has_negative_diagonal" not in cache: if A.dtype in NONNEGATIVE_DTYPES or A.dtype._is_udt or cache.get("has_self_edges") is False: cache["has_negative_diagonal"] = False @@ -153,7 +153,7 @@ def has_negative_diagonal(G, mask=None): def has_negative_edgesp(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if "has_negative_edges+" not in cache: if A.dtype in NONNEGATIVE_DTYPES or A.dtype._is_udt: cache["has_negative_edges+"] = False @@ -176,7 +176,7 @@ def has_negative_edgesp(G, mask=None): def has_negative_edgesm(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if "has_negative_edges-" not in cache: if A.dtype in NONNEGATIVE_DTYPES or A.dtype._is_udt: cache["has_negative_edges-"] = False @@ -195,8 +195,9 @@ def has_negative_edgesm(G, mask=None): def has_self_edges(G, mask=None): """A.diag().nvals > 0""" A = G._A - cache = G._cache + cache = G._properties if "has_self_edges" not in cache: + # A triangle's size tells, as A is symmetric: (A.nvals - diagonal) / 2 entries off it if "L+" in cache: cache["has_self_edges"] = 2 * cache["L+"].nvals > A.nvals elif "L-" in cache: @@ -210,14 +211,15 @@ def has_self_edges(G, mask=None): elif cache.get("has_negative_diagonal") is True: cache["has_self_edges"] = True else: - G.get_property("diag") + cache["has_self_edges"] = G.get_property("diag").nvals > 0 return cache["has_self_edges"] def is_iso(G, mask=None): - cache = G._cache + cache = G._properties if "is_iso" not in cache: - get_iso_value(G) + # Its own store: a reader sharing the cache may be between get_iso_value's two stores + cache["is_iso"] = get_iso_value(G) is not None return cache["is_iso"] @@ -236,7 +238,7 @@ def _uniform_value(G): def get_iso_value(G, mask=None): A = G._A - cache = G._cache + cache = G._properties if "iso_value" not in cache: if not A.nvals: # An edgeless result of an operator can be stored iso, with no value to read. @@ -281,8 +283,10 @@ def __missing__(self, key): opname = keybase[: -len("_rowwise")] methodname = "reduce_rowwise" elif keybase.endswith("_columnwise"): - opname = keybase[: -len("_columnwise")] - methodname = "reduce_rowwise" + # A symmetric A's columns are its rows: one getter, cached under the row key + get_reduction = self[f"{keybase[: -len('_columnwise')]}_rowwise{key[-1]}"] + self[key] = get_reduction + return get_reduction elif keybase.endswith("_element"): opname = keybase[: -len("_element")] methodname = "reduce_scalar" @@ -292,7 +296,6 @@ def __missing__(self, key): get_reduction = get_reduce_to_scalar(key, opname) else: get_reduction = get_reduce_to_vector(key, opname, methodname) - self[f"{opname}_columnwise{key[-1]}"] = get_reduction elif key.endswith("_diagonal"): # e.g., min_diagonal opname = key[: -len("_diagonal")] @@ -364,7 +367,16 @@ class Graph: graph_attr_dict_factory = dict def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **attr): - """`weight`: the edge attribute the values came from, or None for structural values.""" + """`incoming_graph_data`: the adjacency, holding each edge in both directions. + + A Matrix is used as it is, not copied. It must be symmetric, which is not checked: the + cached properties assume it (`has_self_edges`, for one, is read from triangle sizes). + They are dropped when the matrix is replaced or gains or loses entries. A change that + keeps the number of entries is not seen: call `clear_cache` after one. Finish the + matrix (`A.wait()`) before threads share the graph. + + `weight`: the edge attribute the values came from, or None for structural values. + """ if incoming_graph_data is not None: # Does not copy if A is a Matrix! A = gb.core.utils.ensure_type(incoming_graph_data, Matrix) @@ -383,7 +395,7 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a key_to_id = {i: i for i in range(A.nrows)} self._key_to_id = key_to_id self._id_to_key = None - self._cache = {} + self.clear_cache() # Graphblas-specific methods from_networkx = classmethod(_utils.from_networkx) @@ -406,6 +418,11 @@ def __init__(self, incoming_graph_data=None, *, key_to_id=None, weight=None, **a vector_to_nodeset = _utils.vector_to_nodeset vector_to_set = _utils.vector_to_set _cacheit = _utils._cacheit + _cache = property(_utils.cache) + clear_cache = _utils.clear_cache + cache_info = _utils.cache_info + __getstate__ = _utils.getstate + __setstate__ = _utils.setstate renumber_key_to_id = _utils.renumber_key_to_id # NetworkX methods diff --git a/graphblas_algorithms/tests/test_cache.py b/graphblas_algorithms/tests/test_cache.py new file mode 100644 index 0000000..c5c3350 --- /dev/null +++ b/graphblas_algorithms/tests/test_cache.py @@ -0,0 +1,671 @@ +"""A graph's cached properties follow its matrix, which `Graph(A)` uses without copying.""" + +import base64 +import copy +import pickle +import warnings + +import networkx as nx +import pytest +from graphblas import Matrix, Scalar, Vector, agg +from graphblas.core import ffi, lib + +from graphblas_algorithms.algorithms import dag +from graphblas_algorithms.algorithms._helpers import checked_sum_type +from graphblas_algorithms.classes import DiGraph, Graph, _utils +from graphblas_algorithms.classes._utils import drop_unrequested_values +from graphblas_algorithms.classes.graph import AutoDict + +GRAPH_PROPERTIES = [ + "degrees+", + "degrees-", + "has_self_edges", + "offdiag", + "diag", + "L-", + "U+", + "plus_rowwise+", +] +DIGRAPH_PROPERTIES = [ + "AT", + "row_degrees+", + "column_degrees-", + "has_self_edges", + "offdiag", + "diag", + "L-", + "U+", + "plus_columnwise+", +] + + +def path(directed): + """0 - 1 - 2, and 3 alone.""" + if directed: + return Matrix.from_coo([0, 1], [1, 2], 1, nrows=4, ncols=4) + return Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], 1, nrows=4, ncols=4) + + +def add_edge(A, directed): + A[2, 3] = 1 + if not directed: + A[3, 2] = 1 + + +def add_self_loop(A, directed): + A[1, 1] = 1 + + +def remove_edge(A, directed): + del A[0, 1] + if not directed: + del A[1, 0] + + +CHANGES = [add_edge, add_self_loop, remove_edge] + + +def same(x, y): + if isinstance(x, (Matrix, Vector, Scalar)): + return type(x) is type(y) and x.isequal(y, check_dtype=True) + return type(x) is type(y) and x == y + + +@pytest.mark.parametrize("read", ["get_property", "get_properties"]) +@pytest.mark.parametrize("change", CHANGES) +@pytest.mark.parametrize("cls", [Graph, DiGraph], ids=["Graph", "DiGraph"]) +def test_the_properties_follow_a_change_to_the_matrix(cls, change, read): + directed = cls is DiGraph + names = DIGRAPH_PROPERTIES if directed else GRAPH_PROPERTIES + A = path(directed) + G = cls(A) + G.get_properties(names) + change(A, directed) + if read == "get_property": + values = [G.get_property(name) for name in names] + else: + values = G.get_properties(names) + expected = cls(A.dup()).get_properties(names) + for name, value, fresh in zip(names, values, expected, strict=True): + assert same(value, fresh), name + + +@pytest.mark.parametrize("change", CHANGES) +def test_degree_centrality_follows_a_change_to_the_matrix(change): + A = path(False) + G = Graph(A) + nx.degree_centrality(G) + change(A, False) + assert nx.degree_centrality(G) == nx.degree_centrality(Graph(A.dup())) + + +@pytest.mark.parametrize("change", CHANGES) +def test_ancestors_follow_a_change_to_the_matrix(change): + A = path(True) + G = DiGraph(A) + for node in G: + nx.ancestors(G, node) + assert "AT" in G._cache + change(A, True) + fresh = DiGraph(A.dup()) + assert [nx.ancestors(G, node) for node in G] == [nx.ancestors(fresh, node) for node in fresh] + + +def test_the_cache_read_directly_is_emptied_by_a_change(): + A = path(False) + G = Graph(A) + G.get_property("degrees-") + assert "count_rowwise-" in G._cache + add_edge(A, False) + assert "count_rowwise-" not in G._cache + G.get_property("degrees-") + assert "count_rowwise-" in G._cache + + +def test_a_property_is_computed_once_while_the_matrix_is_unchanged(): + G = Graph(path(False)) + degrees = G.get_property("degrees+") + assert G.get_properties("degrees+ L-")[0] is degrees + assert G.get_property("degrees+") is degrees + + +def test_a_property_whose_value_is_none_is_kept(): + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.0, 1.0, 2.0, 2.0], nrows=3, ncols=3) + G = Graph(A, weight="weight") + assert G.get_property("iso_value") is None + assert G.get_property("is_iso") is False + assert G._cache["iso_value"] is None + + +class _OtherThreads: + """Other threads' work, done as the cache holding this is dropped. + + That is where a check replacing the cache can give the GIL to other threads. + """ + + def __init__(self, work): + self.work = work + + def __del__(self): + self.work() + + +def test_a_matrix_replaced_while_the_cache_is_replaced(): + A0 = path(False) + A1 = path(False) + add_edge(A1, False) + A2 = A1.dup() + add_self_loop(A2, False) + G = Graph(A0) + G.get_property("degrees+") + + def other_threads(): + G.get_properties("degrees+ has_self_edges") # a reader finds A1 and caches from it + G._A = A2 # a writer replaces the matrix + + G._cache["other threads"] = _OtherThreads(other_threads) + G._A = A1 + G.get_property("degrees+") # this reader finds A1 too and drops the cache + assert G._A is A2 + # A lost update is fine, but each value the cache holds now must be the current matrix's + fresh = Graph(A2.dup()) + for key, value in G._cache.items(): + assert same(value, fresh.get_property(key)), key + assert G.get_property("has_self_edges") is True + assert G.get_property("degrees+").isequal(fresh.get_property("degrees+")) + + +def test_a_getter_keeps_to_the_matrix_its_call_found(monkeypatch): + A1 = path(False) + A2 = path(False) + add_self_loop(A2, False) + G = Graph(A1) + getters = AutoDict(Graph._get_property) + real_has_self_edges = getters["has_self_edges"] + + def has_self_edges(snapshot, mask=None): + # Other threads, after this call's check and before its getter asks for "diag": a writer + # replaces the matrix, and a reader's call caches from the new one + G._A = A2 + G.get_property("degrees+") + return real_has_self_edges(snapshot, mask) + + getters["has_self_edges"] = has_self_edges + monkeypatch.setattr(Graph, "_get_property", getters) + assert G.get_property("has_self_edges") is False # the matrix this call found + assert G.get_property("has_self_edges") is True + + +def test_a_value_computed_while_the_matrix_was_replaced_is_not_kept(): + A1 = path(False) + A2 = A1.dup() + add_edge(A2, False) + G = Graph(A1) + + def entries_while_replaced(): + G._A = A2 # another thread replaces the matrix while this is computed + return G._A.nvals + + assert G._cacheit("entries", entries_while_replaced) == A2.nvals + G._A = A1 # and puts the first one back + assert G._cacheit("entries", lambda: G._A.nvals) == A1.nvals + + +SHARED_PROPERTIES = [ + "A", + "AT", + "offdiag", + "U+", + "U-", + "L+", + "L-", + "diag", + "has_self_edges", + "is_iso", + "iso_value", + "has_negative_diagonal", + "has_negative_edges+", + "has_negative_edges-", + "row_degrees+", + "row_degrees-", + "column_degrees+", + "column_degrees-", + "plus_rowwise+", + "plus_columnwise-", + "min_element+", + "max_element-", + "plus_element+", + "min_diagonal", +] +DIGRAPH_ONLY = [ + "recip_degrees+", + "recip_degrees-", + "total_degrees+", + "total_degrees-", + "total_recip+", + "total_recip-", +] + + +def _shared_graphs(): + """Integer values, as `same` compares dtypes; ones (stored iso) and not; loops or not.""" + for cls in (Graph, DiGraph): + rows, cols = ([0, 1], [1, 2]) if cls is DiGraph else ([0, 1, 1, 2], [1, 0, 2, 1]) + for values, loop in [(1, True), ("varied", True), ("varied", False)]: + r, c = rows + [1] * loop, cols + [1] * loop + v = 1 if values == 1 else list(range(2, len(r) + 2)) + if cls is Graph and values != 1: + v = [2, 2, 3, 3, 4][: len(r)] # symmetric + yield cls, values, loop, Matrix.from_coo(r, c, v, nrows=4, ncols=4) + + +@pytest.mark.parametrize( + ("cls", "values", "loop", "A"), + list(_shared_graphs()), + ids=lambda x: getattr(x, "__name__", None) if isinstance(x, type) else None, +) +def test_a_reader_between_another_readers_stores_gets_its_answer(cls, values, loop, A, monkeypatch): + # Readers share a graph's cache: one can find it holding any part of what another call + # stores, in the order that call stores it. Each such state, for each property asked first, + # must answer every property, never raising. (A DiGraph with a loop can still infer + # `has_self_edges` wrongly from `total_degrees+`, a fault of its own; values not compared.) + names = SHARED_PROPERTIES + (DIGRAPH_ONLY if cls is DiGraph else []) + fresh = {name: cls(A).get_property(name) for name in names} + check_values = cls is Graph or not loop + real = _utils._PropertyCache.__setitem__ + for first in names: + stores = [] + + def record(cache, key, value, stores=stores): + stores.append((key, value)) + real(cache, key, value) + + with monkeypatch.context() as m: + m.setattr(_utils._PropertyCache, "__setitem__", record) + cls(A).get_property(first) + for i in range(len(stores)): + for name in names: + G = cls(A) + for key, value in stores[:i]: + G._cache[key] = value + answer = G.get_property(name) + if check_values: + assert same(answer, fresh[name]), (first, stores[:i], name) + + +def _weights(heavy, light): + """Symmetric INT64 weights: `heavy` edges of 2**60 in a chain, then `light` edges of 1.""" + rows, cols, values = [], [], [] + for i in range(heavy + light): + rows += [i, i + 1] + cols += [i + 1, i] + values += [2**60 if i < heavy else 1] * 2 + return Matrix.from_coo(rows, cols, values, nrows=heavy + light + 1, ncols=heavy + light + 1) + + +def test_a_sum_checked_while_the_matrix_is_replaced_keeps_to_one_matrix(monkeypatch): + A1 = _weights(4, 1) # 10 entries summing to 2**63 + 2: too much for INT64 + A2 = _weights(2, 3) # 10 entries summing to 2**62 + 6 + G = Graph(A1) + getters = AutoDict(Graph._get_property) + real_min_element = getters["min_element+"] + replaced = [] + + def min_element(snapshot, mask=None): + if not replaced: # another thread replaces the matrix while this call reads properties + G._A = A2 + replaced.append(True) + return real_min_element(snapshot, mask) + + getters["min_element+"] = min_element + monkeypatch.setattr(Graph, "_get_property", getters) + with pytest.raises(OverflowError): + checked_sum_type(G, "sum") # the matrix this call found + assert replaced + assert checked_sum_type(G, "sum") is checked_sum_type(Graph(A2.dup()), "sum") + assert G._cache["abs_sum+"] == 2**62 + 6 + + +def test_is_acyclic_keeps_to_one_matrix(monkeypatch): + A_dag = path(True) + A_cycle = A_dag.dup() + A_cycle[2, 0] = 1 + G = DiGraph(A_dag) + real_get, real_vector = _utils._PropertyCache.get, dag.Vector + + def get(cache, key, default=None): + if key == "is_acyclic": # another thread replaces the matrix as the cache is read... + G._A = A_cycle + return real_get(cache, key, default) + + def vector(*args, **kwargs): + G._A = A_dag # ...and puts it back before the answer is stored + return real_vector(*args, **kwargs) + + monkeypatch.setattr(_utils._PropertyCache, "get", get) + monkeypatch.setattr(dag, "Vector", vector) + assert dag.is_acyclic(G) is True + monkeypatch.undo() + assert G._A is A_dag + assert dag.is_acyclic(G) is True + + +def test_a_replaced_matrix_empties_the_cache(): + G = Graph(path(False)) + G.get_property("degrees+") + B = Matrix.from_coo([0, 1, 2, 3], [1, 0, 3, 2], 1, nrows=4, ncols=4) # as many entries + G._A = B + assert G.get_property("degrees+").isequal(B.reduce_rowwise(agg.count).new()) + + +def test_a_matrix_where_a_freed_one_was_empties_the_cache(): + # The allocator gives a freed handle to the next matrix: the stamp keeps the old one alive + G = Graph(path(False)) + G.get_property("degrees+") + G._A = None + B = Matrix.from_coo([0, 1, 2, 3], [1, 0, 3, 2], 1, nrows=4, ncols=4) # as many entries + G._A = B + assert G.get_property("degrees+").isequal(B.reduce_rowwise(agg.count).new()) + + +def test_a_new_handle_behind_the_same_matrix_empties_the_cache(): + A = path(False) + B = Matrix.from_coo([0, 1, 2, 3], [1, 0, 3, 2], 1, nrows=4, ncols=4) + G = Graph(A) + G.get_property("degrees+") + A.gb_obj[0], B.gb_obj[0] = B.gb_obj[0], A.gb_obj[0] + assert G.get_property("degrees+").isequal(A.reduce_rowwise(agg.count).new()) + + +def test_clear_cache_after_new_values_for_the_same_entries(): + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.0, 1.0, 2.0, 2.0], nrows=3, ncols=3) + G = Graph(A, weight="weight") + G.get_property("plus_rowwise+") + A[0, 1] = 5.0 + A[1, 0] = 5.0 + G.clear_cache() + assert G.cache_info() == {} + assert G.get_property("plus_rowwise+").isequal(A.reduce_rowwise().new()) + + +def test_the_structure_graph_follows_a_change_to_the_matrix(): + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.5, 1.5, 2.5, 2.5], nrows=4, ncols=4) + G = Graph(A, weight="weight") + assert drop_unrequested_values(G, None) is drop_unrequested_values(G, None) + A[2, 3] = 4.5 + A[3, 2] = 4.5 + assert drop_unrequested_values(G, None)._A.nvals == 6 + + +def test_cache_info_counts_each_object_once(): + G = Graph(path(False)) # no self-edges: "offdiag" is the matrix and "U-" is "U+" + assert G.cache_info() == {} + G.get_properties("offdiag degrees+ U+ U-") + cache = G._cache + info = G.cache_info() + assert set(info) == set(cache) + assert cache["offdiag"] is G._A + assert info["offdiag"] == 0 + assert info["count_rowwise+"] == cache["count_rowwise+"].ss.nbytes > 0 + assert cache["U-"] is cache["U+"] + assert sorted([info["U+"], info["U-"]]) == [0, cache["U+"].ss.nbytes] + + +def test_cache_info_follows_a_change_to_the_matrix(): + A = path(False) + G = Graph(A) + G.get_property("degrees+") + add_edge(A, False) + assert G.cache_info() == {} + + +def test_cache_info_counts_a_scalar_as_graphblas_holds_it(): + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.5, 1.5, 2.5, 2.5], nrows=3, ncols=3) + G = Graph(A, weight="weight") + value = G.get_property("min_element+") + assert isinstance(value, Scalar) + size = ffi.new("size_t*") + assert lib.GxB_Scalar_memoryUsage(size, value.gb_obj[0]) == 0 + assert G.cache_info()["min_element+"] == size[0] > 0 + + +def test_cache_info_counts_a_cached_graph(): + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.5, 1.5, 2.5, 2.5], nrows=3, ncols=3) + G = Graph(A, weight="weight") + twin = drop_unrequested_values(G, None) + twin.get_property("degrees+") + expected = twin._A.ss.nbytes + twin._cache["count_rowwise+"].ss.nbytes + assert G.cache_info() == {"structure": expected} + + +@pytest.mark.parametrize("target", ["graph", "cached graph"]) +def test_cache_info_while_a_reader_stores_a_property(target, monkeypatch): + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.5, 1.5, 2.5, 2.5], nrows=3, ncols=3) + G = Graph(A, weight="weight") + G.get_property("degrees+") + twin = drop_unrequested_values(G, None) + twin.get_property("degrees+") + other = G if target == "graph" else twin + real = _utils._nbytes + stored = [] + + def nbytes(value, seen): + # another reader stores a property while cache_info counts this graph's or the twin's + if not stored and (other is G or id(twin._A) in seen): + stored.append(other.get_property("diag")) + return real(value, seen) + + monkeypatch.setattr(_utils, "_nbytes", nbytes) + info = G.cache_info() + assert stored + assert set(info) <= set(G._cache) + + +def test_a_stored_value_is_finished(monkeypatch): + waited = [] + for cls in (Matrix, Vector, Scalar): + + def wait(self, how="materialize", *, real=cls.wait): + waited.append(self) + return real(self, how) + + monkeypatch.setattr(cls, "wait", wait) + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.5, 1.5, 2.5, 2.5], nrows=3, ncols=3) + G = Graph(A, weight="weight") + G.get_properties("L- degrees+ plus_rowwise+ min_element+") + twin = drop_unrequested_values(G, None) + stored = [value for value in G._cache.values() if isinstance(value, (Matrix, Vector, Scalar))] + stored.append(twin._A) + assert any(isinstance(value, Scalar) for value in stored) + assert len(stored) >= 5 + for value in stored: + assert any(value is w for w in waited), value.name + # A warm call stores values again (one key filled from another) but waits for none + count = len(waited) + G.get_properties("L- degrees+ degrees- plus_rowwise+ min_element+") + assert len(waited) == count + + +def test_the_matrix_is_finished_once_a_snapshot(monkeypatch): + waited = [] + real = Matrix.wait + + def wait(self, how="materialize"): + waited.append(self) + return real(self, how) + + monkeypatch.setattr(Matrix, "wait", wait) + A = path(False) + G = Graph(A) + assert sum(w is A for w in waited) == 1 + G.get_property("degrees+") + G.get_property("degrees+") + assert sum(w is A for w in waited) == 1 + add_edge(A, False) + G.get_property("degrees+") + assert sum(w is A for w in waited) == 2 + + +@pytest.mark.parametrize("cls", [Graph, DiGraph]) +def test_a_converted_graph_holds_a_finished_matrix(cls, monkeypatch): + waited = [] + real = Matrix.wait + + def wait(self, how="materialize"): + waited.append(self) + return real(self, how) + + monkeypatch.setattr(Matrix, "wait", wait) + G = cls.from_networkx(nx.path_graph(4, create_using=nx.DiGraph if cls is DiGraph else nx.Graph)) + assert any(w is G._A for w in waited) + + +def test_the_columns_of_a_graph_are_its_rows(monkeypatch): + # Getters made by earlier tests would hide which key asked first + fresh = AutoDict({k: v for k, v in Graph._get_property.items() if "wise" not in k}) + monkeypatch.setattr(Graph, "_get_property", fresh) + A = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [1.0, 1.0, 2.0, 2.0], nrows=3, ncols=3) + G = Graph(A, weight="weight") + columns = G.get_property("plus_columnwise+") + assert G.get_property("plus_rowwise+") is columns + assert list(G._cache) == ["plus_rowwise+"] + + +def test_the_columns_of_a_digraph_are_its_own(): + A = Matrix.from_coo([0, 1], [1, 2], [1.0, 2.0], nrows=3, ncols=3) + G = DiGraph(A, weight="weight") + assert G.get_property("plus_columnwise+").isequal(A.reduce_columnwise().new()) + assert G.get_property("plus_rowwise+").isequal(A.reduce_rowwise().new()) + + +# Pickled before a graph's cache was a snapshot (a plain `_cache` dict, no pickling hooks, as in +# every earlier release): a Graph of the path 0 - 1 - 2 weighted 2 and 3, with node 3 alone, +# holding cached properties, and a NetworkX graph holding a cached conversion to one. +OLD_GRAPH = ( + "gASVQQUAAAAAAACMImdyYXBoYmxhc19hbGdvcml0aG1zLmNsYXNzZXMuZ3JhcGiUjAVHcmFwaJSTlCmBlH2UKIwX" + "Z3JhcGhfYXR0cl9kaWN0X2ZhY3RvcnmUjAhidWlsdGluc5SMBGRpY3SUk5SMBWdyYXBolH2UjAJfQZSMFWdyYXBo" + "Ymxhcy5jb3JlLm1hdHJpeJSME01hdHJpeC5fZGVzZXJpYWxpemWUk5R9lCiMBmJpdG1hcJSMFm51bXB5Ll9jb3Jl" + "Lm11bHRpYXJyYXmUjAxfcmVjb25zdHJ1Y3SUk5SMBW51bXB5lIwHbmRhcnJheZSTlEsAhZRDAWKUh5RSlChLAUsQ" + "hZRoFIwFZHR5cGWUk5SMAmIxlImIh5RSlChLA4wBfJROTk5K/////0r/////SwB0lGKJQxAAAQAAAQABAAABAAAA" + "AAAAlHSUYowFbnZhbHOUSwSMBW5yb3dzlEsEjAVuY29sc5RLBIwGaXNfaXNvlImMBmZvcm1hdJSMB2JpdG1hcHKU" + "jAZ2YWx1ZXOUaBNoFksAhZRoGIeUUpQoSwFLEIWUaB2MAmk4lImIh5RSlChLA4wBPJROTk5K/////0r/////SwB0" + "lGKJQ4AAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAAAAAAAADAAAAAAAAAAAAAAAA" + "AAAAAAAAAAAAAAADAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" + "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+ + +def test_a_graph_pickled_by_an_earlier_release_loads(): + G = pickle.loads(base64.b64decode(OLD_GRAPH)) # noqa: S301 (made here, by this package) + weighted = Matrix.from_coo([0, 1, 1, 2], [1, 0, 2, 1], [2, 2, 3, 3], nrows=4, ncols=4) + assert G._A.isequal(weighted, check_dtype=True) + assert {"count_rowwise+", "offdiag", "plus_rowwise+", "has_self_edges", "U-"} <= set(G._cache) + assert "_cache" not in G.__dict__ + fresh = Graph(G._A.dup()) + for key in G._cache: + assert same(G.get_property(key), fresh.get_property(key)), key + add_edge(G._A, False) + assert G.get_property("degrees+").isequal(Graph(G._A.dup()).get_property("degrees+")) + + +def test_a_networkx_graph_pickled_with_a_conversion_by_an_earlier_release_loads(): + H = pickle.loads(base64.b64decode(OLD_NX_GRAPH)) # noqa: S301 (made here, by this package) + assert H.__networkx_cache__["backends"]["graphblas"] + with warnings.catch_warnings(): # NetworkX notes that it uses the cached conversion + warnings.filterwarnings("ignore", message="Note: conversions to backend graphs") + result = nx.degree_centrality(H, backend="graphblas") + assert result == nx.degree_centrality(H, backend="networkx") + + +@pytest.mark.parametrize("when", ["before", "after"]) +def test_a_copy_takes_its_matrix_and_properties_from_one_snapshot(when, monkeypatch): + A1 = path(False) + A2 = A1.dup() + add_edge(A2, False) + G = Graph(A2) + G.get_property("degrees+") + if when == "before": + G._A = A1 # replaced, with no call since + real = _utils.current_snapshot + replaced = [] + + def current_snapshot(graph): + # another thread puts the matrix back just before the copy's check, or replaces it + # just after + if graph is G and not replaced: + replaced.append(True) + if when == "before": + G._A = A2 + return real(graph) + snapshot = real(graph) + G._A = A1 + return snapshot + return real(graph) + + monkeypatch.setattr(_utils, "current_snapshot", current_snapshot) + H = roundtrip(G) + assert replaced + monkeypatch.undo() + assert H.get_property("degrees+").isequal(Graph(H._A.dup()).get_property("degrees+")) + + +def roundtrip(G): + return pickle.loads(pickle.dumps(G)) # noqa: S301 (its own bytes) + + +@pytest.mark.parametrize("duplicate", [roundtrip, copy.deepcopy], ids=["pickle", "deepcopy"]) +def test_a_copy_keeps_its_properties_and_follows_its_own_matrix(duplicate): + G = Graph(path(False)) + G.get_property("degrees+") + H = duplicate(G) + assert "count_rowwise+" in H._cache + add_edge(H._A, False) + assert H.get_property("degrees+").isequal(Graph(H._A.dup()).get_property("degrees+")) + assert "count_rowwise+" in G._cache + + +@pytest.mark.parametrize("duplicate", [roundtrip, copy.deepcopy], ids=["pickle", "deepcopy"]) +def test_a_copy_made_after_a_change_is_not_stale(duplicate): + A = path(False) + G = Graph(A) + G.get_property("degrees+") + add_edge(A, False) + H = duplicate(G) + assert H.get_property("degrees+").isequal(Graph(A.dup()).get_property("degrees+"))