| 1 |
""" |
| 2 |
Module to support caching of function results to memory (used to cache results |
| 3 |
of parsing, generation of state update code, etc.). Provides the `cached` |
| 4 |
decorator. |
| 5 |
""" |
| 6 |
|
| 7 |
import collections |
| 8 |
import functools |
| 9 |
from collections.abc import Mapping |
| 10 |
|
| 11 |
|
| 12 |
class CacheKey: |
| 13 |
""" |
| 14 |
Mixin class for objects that will be used as keys for caching (e.g. |
| 15 |
`Variable` objects) and have to define a certain "identity" with respect |
| 16 |
to caching. This "identity" is different from standard Python hashing and |
| 17 |
equality checking: a `Variable` for example would be considered "identical" |
| 18 |
for caching purposes regardless which object (e.g. `NeuronGroup`) it belongs |
| 19 |
to (because this does not matter for parsing, creating abstract code, etc.) |
| 20 |
but this of course matters for the values it refers to and therefore for |
| 21 |
comparison of equality to other variables. |
| 22 |
|
| 23 |
Classes that mix in the `CacheKey` class should re-define the |
| 24 |
``_cache_irrelevant_attributes`` attribute to note all the attributes that |
| 25 |
should be ignored. The property ``_state_tuple`` will refer to a tuple of |
| 26 |
all attributes that were not excluded in such a way; this tuple will be used |
| 27 |
as the key for caching purposes. |
| 28 |
""" |
| 29 |
|
| 30 |
#: Set of attributes that should not be considered for caching of state |
| 31 |
#: update code, etc. |
| 32 |
_cache_irrelevant_attributes = set() |
| 33 |
|
| 34 |
@property |
| 35 |
def _state_tuple(self): |
| 36 |
"""A tuple with this object's attribute values, defining its identity |
| 37 |
for caching purposes. See `CacheKey` for details.""" |
| 38 |
return tuple( |
| 39 |
value |
| 40 |
for key, value in sorted(self.__dict__.items()) |
| 41 |
if key not in self._cache_irrelevant_attributes |
| 42 |
) |
| 43 |
|
| 44 |
|
| 45 |
class _CacheStatistics: |
| 46 |
""" |
| 47 |
Helper class to store cache statistics |
| 48 |
""" |
| 49 |
|
| 50 |
def __init__(self): |
| 51 |
self.hits = 0 |
| 52 |
self.misses = 0 |
| 53 |
|
| 54 |
def __repr__(self): |
| 55 |
return f"<Cache statistics: {int(self.hits)} hits, {int(self.misses)} misses>" |
| 56 |
|
| 57 |
|
| 58 |
def cached(func): |
| 59 |
""" |
| 60 |
Decorator to cache a function so that it will not be re-evaluated when |
| 61 |
called with the same arguments. Uses the `_hashable` function to make |
| 62 |
arguments usable as a dictionary key even though they mutable (lists, |
| 63 |
dictionaries, etc.). |
| 64 |
|
| 65 |
Notes |
| 66 |
----- |
| 67 |
This is *not* a general-purpose caching decorator in any way comparable to |
| 68 |
``functools.lru_cache`` or joblib's caching functions. It is very simplistic |
| 69 |
(no maximum cache size, no normalization of calls, e.g. ``foo(3)`` and |
| 70 |
``foo(x=3)`` are not considered equivalent function calls) and makes very |
| 71 |
specific assumptions for our use case. Most importantly, `Variable` objects |
| 72 |
are considered to be identical when they refer to the same object, even |
| 73 |
though the actually stored values might have changed. |
| 74 |
|
| 75 |
Parameters |
| 76 |
---------- |
| 77 |
func : function |
| 78 |
The function to decorate. |
| 79 |
|
| 80 |
Returns |
| 81 |
------- |
| 82 |
decorated : function |
| 83 |
The decorated function. |
| 84 |
""" |
| 85 |
# For simplicity, we store the cache in the function itself |
| 86 |
func._cache = {} |
| 87 |
func._cache_statistics = _CacheStatistics() |
| 88 |
|
| 89 |
@functools.wraps(func) |
| 90 |
def cached_func(*args, **kwds): |
| 91 |
try: |
| 92 |
cache_key = tuple( |
| 93 |
[_hashable(arg) for arg in args] |
| 94 |
+ [(key, _hashable(value)) for key, value in sorted(kwds.items())] |
| 95 |
) |
| 96 |
except TypeError: |
| 97 |
# If we cannot handle a type here, that most likely means that the |
| 98 |
# user provided an argument of a type we don't handle. This will |
| 99 |
# lead to an error message later that is most likely more meaningful |
| 100 |
# to the user than an error message by the caching system |
| 101 |
# complaining about an unsupported type. |
| 102 |
return func(*args, **kwds) |
| 103 |
if cache_key in func._cache: |
| 104 |
func._cache_statistics.hits += 1 |
| 105 |
else: |
| 106 |
func._cache_statistics.misses += 1 |
| 107 |
func._cache[cache_key] = func(*args, **kwds) |
| 108 |
return func._cache[cache_key] |
| 109 |
|
| 110 |
return cached_func |
| 111 |
|
| 112 |
|
| 113 |
_of_type_cache = collections.defaultdict(set) |
| 114 |
|
| 115 |
|
| 116 |
def _of_type(obj_type, check_type): |
| 117 |
if (obj_type, check_type) not in _of_type_cache: |
| 118 |
_of_type_cache[(obj_type, check_type)] = issubclass(obj_type, check_type) |
| 119 |
return _of_type_cache[(obj_type, check_type)] |
| 120 |
|
| 121 |
|
| 122 |
def _hashable(obj): |
| 123 |
"""Helper function to make a few data structures hashable (e.g. a |
| 124 |
dictionary gets converted to a frozenset). The function is specifically |
| 125 |
tailored to our use case and not meant to be generally useful.""" |
| 126 |
if hasattr(obj, "_state_tuple"): |
| 127 |
return _hashable(obj._state_tuple) |
| 128 |
obj_type = type(obj) |
| 129 |
if _of_type(obj_type, Mapping): |
| 130 |
return frozenset( |
| 131 |
(_hashable(key), _hashable(value)) for key, value in obj.items() |
| 132 |
) |
| 133 |
elif _of_type(obj_type, set): |
| 134 |
return frozenset(_hashable(el) for el in obj) |
| 135 |
elif _of_type(obj_type, tuple) or _of_type(obj_type, list): |
| 136 |
return tuple(_hashable(el) for el in obj) |
| 137 |
if hasattr(obj, "dim") and getattr(obj, "shape", None) == (): |
| 138 |
# Scalar Quantity object |
| 139 |
return float(obj), obj.dim |
| 140 |
else: |
| 141 |
try: |
| 142 |
# Make sure that the object is hashable |
| 143 |
hash(obj) |
| 144 |
return obj |
| 145 |
except TypeError as ex: |
| 146 |
raise TypeError( |
| 147 |
f"Do not know how to handle object of type {type(obj)}" |
| 148 |
) from ex |