-
Notifications
You must be signed in to change notification settings - Fork 78
/
Copy pathcache.py
236 lines (190 loc) · 7.33 KB
/
cache.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# BSD 3-Clause License; see https://github.com/scikit-hep/uproot5/blob/main/LICENSE
"""
This module defines simple, thread-safe cache classes satisfying the
``MutableMapping`` protocol.
The :doc:`uproot.cache.LRUCache` implements a least-recently used eviction
policy that limits the number of items in the cache (used as an
``object_cache``).
The :doc:`uproot.cache.LRUArrayCache` implements the same policy, limiting the
total number of bytes, as reported by ``nbytes``.
"""
from __future__ import annotations
import threading
from collections.abc import MutableMapping
import uproot
class LRUCache(MutableMapping):
"""
Args:
limit (None or int): Number of objects to allow in the cache before
evicting the least-recently used. If None, this cache never evicts.
LRUCache is a ``MutableMapping`` that evicts the least-recently used
objects when the ``current`` number of objects exceeds the ``limit``.
Get and set (or explicitly remove) items with ``MutableMapping`` syntax:
square bracket subscripting.
LRUCache is thread-safe for all options: getting, setting, deleting,
iterating, listing keys, values, and items.
This cache is insensitive to the size of the objects it stores, and hence
is a better ``object_cache`` than an ``array_cache``.
"""
@classmethod
def sizeof(cls, obj):
"""
The "size of" an object in this cache is always exactly 1.
"""
return 1
def __init__(self, limit):
self._limit = limit
self._current = 0
self._order = []
self._data = {}
self._lock = threading.Lock()
def __getstate__(self):
return {
"_limit": self._limit,
}
def __setstate__(self, state):
self._limit = state["_limit"]
self._current = 0
self._order = []
self._data = {}
self._lock = threading.Lock()
def __repr__(self):
if self._limit is None:
limit = "(no limit)"
else:
limit = f"({self._current}/{self._limit} full)"
return f"<LRUCache {limit} at 0x{id(self):012x}>"
@property
def limit(self):
"""
Number of objects to allow in the cache before evicting the
least-recently used. If None, this cache never evicts.
"""
return self._limit
@property
def current(self):
"""
Current number of items in the cache.
"""
return self._current
def keys(self):
"""
Returns a copy of the keys currently in the cache, in least-recently
used order.
The list ascends from least-recently used to most-recently used: index
``0`` is the least-recently used and index ``-1`` is the most-recently
used.
(Calling this method does not change the order.)
"""
with self._lock:
return list(self._order)
def values(self):
"""
Returns a copy of the values currently in the cache, in least-recently
used order.
The list ascends from least-recently used to most-recently used: index
``0`` is the least-recently used and index ``-1`` is the most-recently
used.
(Calling this method does not change the order.)
"""
with self._lock:
return [self._data[where] for where in self._order]
def items(self):
"""
Returns a copy of the items currently in the cache, in least-recently
used order.
The list ascends from least-recently used to most-recently used: index
``0`` is the least-recently used and index ``-1`` is the most-recently
used.
(Calling this method does not change the order.)
"""
with self._lock:
return [(where, self._data[where]) for where in self._order]
def __getitem__(self, where):
with self._lock:
out = self._data[where]
self._order.remove(where)
self._order.append(where)
return out
def __setitem__(self, where, what):
with self._lock:
if where in self._data:
self._order.remove(where)
self._order.append(where)
self._data[where] = what
self._current += self.sizeof(what)
if self._limit is not None:
while self._current > self._limit and len(self._order) > 0:
key = self._order.pop(0)
self._current -= self.sizeof(self._data[key])
del self._data[key]
def __delitem__(self, where):
with self._lock:
self._current -= self.sizeof(self._data[where])
del self._data[where]
self._order.remove(where)
def __iter__(self):
with self._lock:
order = list(self._order)
yield from order
def __len__(self):
with self._lock:
return len(self._order)
class LRUArrayCache(LRUCache):
"""
Args:
limit_bytes (None, int, or str): Amount of data to allow in the cache
before evicting the least-recently used. An integer is interpreted
as a number of bytes and a string must be a number followed by a
unit, such as "100 MB". If None, this cache never evicts.
LRUArrayCache is a ``MutableMapping`` that evicts the least-recently used
objects when the ``current`` number of bytes exceeds the ``limit``. The
size of an object is taken from its ``nbytes`` attribute. If it does not
have an ``nbytes``, it is presumed to have ``default_nbytes``.
Get and set (or explicitly remove) items with ``MutableMapping`` syntax:
square bracket subscripting.
LRUArrayCache is thread-safe for all options: getting, setting, deleting,
iterating, listing keys, values, and items.
This cache is sensitive to the size of the objects it stores, but only if
those objects have meaningful ``nbytes``. It is therefore a better
``array_cache`` than an ``array_cache``.
"""
default_nbytes = 1024
@classmethod
def sizeof(cls, what):
"""
The "size of" an object in this cache is its
- ``nbytes`` attribute/property if it has one (NumPy and Awkward Arrays,
Pandas Series),
- ``memory_usage().sum()`` if it exists (Pandas DataFrames),
- ``default_nbytes`` otherwise.
"""
if hasattr(what, "nbytes"):
return what.nbytes
if hasattr(what, "memory_usage") and callable(what.memory_usage):
tmp = what.memory_usage()
if hasattr(tmp, "sum") and callable(tmp.sum):
return tmp.sum()
return cls.default_nbytes
def __init__(self, limit_bytes):
limit = None if limit_bytes is None else uproot._util.memory_size(limit_bytes)
super().__init__(limit)
def __repr__(self):
if self._limit is None:
limit = "(no limit)"
else:
limit = f"({self._current}/{self._limit} bytes full)"
return f"<LRUArrayCache {limit} at 0x{id(self):012x}>"
@property
def limit(self):
"""
Number of bytes to allow in the cache before evicting the
least-recently used. If None, this cache never evicts.
"""
return self._limit
@property
def current(self):
"""
Current number of bytes in the cache.
"""
return self._current