-
Notifications
You must be signed in to change notification settings - Fork 0
/
memcached_array_writer.py
169 lines (140 loc) · 5.14 KB
/
memcached_array_writer.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
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2020 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ############################################################################*/
"""Script filling memcached with a 3D stack chunk by chunk
memcached --listen=127.0.0.1 --memory-limit=65000 --max-item-size=17m --slab-min-size=16m
"""
import json
import io
import itertools
import math
import h5py
import numpy
import bloscpack
from pymemcache.client.base import Client
import silx.io
class NumpySerde(object):
"""Numpy array serializer"""
def serialize(key, value):
if isinstance(value, numpy.ndarray):
with io.BytesIO() as buffer:
numpy.save(buffer, value)
return buffer.getvalue(), 2
else:
return value, 1
def deserialize(key, value, flags):
if flags == 1:
return value
elif flags == 2:
with io.BytesIO(value) as buffer:
return numpy.load(buffer)
else:
raise RuntimeException("Unsupported serialization flags")
class NumpyBloscpackSerde(object):
"""Numpy array serializer"""
def serialize(key, value):
if isinstance(value, numpy.ndarray):
with io.BytesIO() as buffer:
numpy.save(buffer, value)
return buffer.getvalue(), 2
else:
return value, 1
def deserialize(key, value, flags):
if flags == 1:
return value
elif flags == 2:
with io.BytesIO(value) as buffer:
return numpy.load(buffer)
else:
raise RuntimeException("Unsupported serialization flags")
def slice_sender(client, dset):
"""Send slice from dataset to client
:param Client client:
:param dset: Array-like of data
"""
ndigits = math.floor(math.log10(len(dset))) + 1
template = "slice%%0%dd" % ndigits
for index, slice_ in enumerate(dset):
key = template % index
client.set(key, slice_)
yield key
def _flatten_slices(slices):
"""Returns a flattened tuple of slices start and stop
:param List[slice] slices:
"""
result = []
for s in slices:
result.append(s.start)
result.append(s.stop)
return tuple(result)
def chunk_sender(client, dset, uid="data", chunks=None):
"""Send chunks from dataset to client
:param Client client:
:param dset: Array-like of data (with slicing and a shape attribute)
:param str uid: Unique ID of the dataset
:param Union[List[int],None] chunks:
List of size of the chunk in each dimension.
As many dimension as the dataset.
If None, a single chunk is used.
"""
template = uid + "[" + ",".join(["%d:%d"] * len(dset.shape)) + "]"
if chunks is None:
chunks = dset.shape
# Write header
client.set(
uid,
json.dumps(
{
"version": 1,
"shape": dset.shape,
"dtype": dset.dtype.str,
"chunks": chunks,
}
),
)
nchunks = numpy.ceil(numpy.array(dset.shape) / numpy.array(chunks)).astype(
numpy.int
)
for index in range(numpy.prod(nchunks)):
slices = []
for nchunk_dim, chunk_size, dset_size in zip(
reversed(nchunks), reversed(chunks), reversed(dset.shape)
):
start = (index % nchunk_dim) * chunk_size
stop = min(start + chunk_size, dset_size)
slices.insert(0, slice(start, stop))
index = index // nchunk_dim
key = template % tuple(
itertools.chain.from_iterable((s.start, s.stop) for s in slices)
)
client.set(key, dset[tuple(slices)])
yield key
if __name__ == "__main__":
import sys
SERVER = "localhost", 11211
client = Client(SERVER, serde=NumpySerde)
url = silx.io.url.DataUrl(sys.argv[1])
with silx.io.open(url.path()) as dset:
# for key in slice_sender(client, dset):
for key in chunk_sender(client, dset, chunks=[1, 512, 512]):
print("loaded", key)