-
-
Notifications
You must be signed in to change notification settings - Fork 258
/
array.py
548 lines (473 loc) · 17.8 KB
/
array.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
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
# Notes on what I've changed here:
# 1. Split Array into AsyncArray and Array
# 3. Added .size and .attrs methods
# 4. Temporarily disabled the creation of ArrayV2
# 5. Added from_dict to AsyncArray
# Questions to consider:
# 1. Was splitting the array into two classes really necessary?
# 2. Do we really need runtime_configuration? Specifically, the asyncio_loop seems problematic
from __future__ import annotations
from dataclasses import dataclass, replace
import json
from typing import Any, Dict, Iterable, Literal, Optional, Tuple, Union
import numpy as np
from zarr.v3.abc.codec import Codec
# from zarr.v3.array_v2 import ArrayV2
from zarr.v3.codecs import BytesCodec
from zarr.v3.common import (
ZARR_JSON,
ArraySpec,
ChunkCoords,
Selection,
SliceSelection,
concurrent_map,
)
from zarr.v3.config import RuntimeConfiguration
from zarr.v3.indexing import BasicIndexer, all_chunk_coords, is_total_slice
from zarr.v3.chunk_grids import RegularChunkGrid
from zarr.v3.chunk_key_encodings import DefaultChunkKeyEncoding, V2ChunkKeyEncoding
from zarr.v3.metadata import ArrayMetadata
from zarr.v3.store import StoreLike, StorePath, make_store_path
from zarr.v3.sync import sync
def parse_array_metadata(data: Any):
if isinstance(data, ArrayMetadata):
return data
elif isinstance(data, dict):
return ArrayMetadata.from_dict(data)
else:
raise TypeError
@dataclass(frozen=True)
class AsyncArray:
metadata: ArrayMetadata
store_path: StorePath
runtime_configuration: RuntimeConfiguration
@property
def codecs(self):
return self.metadata.codecs
def __init__(
self,
metadata: ArrayMetadata,
store_path: StorePath,
runtime_configuration: RuntimeConfiguration,
):
metadata_parsed = parse_array_metadata(metadata)
object.__setattr__(self, "metadata", metadata_parsed)
object.__setattr__(self, "store_path", store_path)
object.__setattr__(self, "runtime_configuration", runtime_configuration)
@classmethod
async def create(
cls,
store: StoreLike,
*,
shape: ChunkCoords,
dtype: Union[str, np.dtype],
chunk_shape: ChunkCoords,
fill_value: Optional[Any] = None,
chunk_key_encoding: Union[
Tuple[Literal["default"], Literal[".", "/"]],
Tuple[Literal["v2"], Literal[".", "/"]],
] = ("default", "/"),
codecs: Optional[Iterable[Union[Codec, Dict[str, Any]]]] = None,
dimension_names: Optional[Iterable[str]] = None,
attributes: Optional[Dict[str, Any]] = None,
runtime_configuration: RuntimeConfiguration = RuntimeConfiguration(),
exists_ok: bool = False,
) -> AsyncArray:
store_path = make_store_path(store)
if not exists_ok:
assert not await (store_path / ZARR_JSON).exists()
codecs = list(codecs) if codecs is not None else [BytesCodec()]
if fill_value is None:
if dtype == np.dtype("bool"):
fill_value = False
else:
fill_value = 0
metadata = ArrayMetadata(
shape=shape,
data_type=dtype,
chunk_grid=RegularChunkGrid(chunk_shape=chunk_shape),
chunk_key_encoding=(
V2ChunkKeyEncoding(separator=chunk_key_encoding[1])
if chunk_key_encoding[0] == "v2"
else DefaultChunkKeyEncoding(separator=chunk_key_encoding[1])
),
fill_value=fill_value,
codecs=codecs,
dimension_names=tuple(dimension_names) if dimension_names else None,
attributes=attributes or {},
)
runtime_configuration = runtime_configuration or RuntimeConfiguration()
array = cls(
metadata=metadata,
store_path=store_path,
runtime_configuration=runtime_configuration,
)
await array._save_metadata()
return array
@classmethod
def from_dict(
cls,
store_path: StorePath,
data: Dict[str, Any],
runtime_configuration: RuntimeConfiguration,
) -> AsyncArray:
metadata = ArrayMetadata.from_dict(data)
async_array = cls(
metadata=metadata, store_path=store_path, runtime_configuration=runtime_configuration
)
return async_array
@classmethod
async def open(
cls,
store: StoreLike,
runtime_configuration: RuntimeConfiguration = RuntimeConfiguration(),
) -> AsyncArray:
store_path = make_store_path(store)
zarr_json_bytes = await (store_path / ZARR_JSON).get()
assert zarr_json_bytes is not None
return cls.from_dict(
store_path,
json.loads(zarr_json_bytes),
runtime_configuration=runtime_configuration,
)
@classmethod
async def open_auto(
cls,
store: StoreLike,
runtime_configuration: RuntimeConfiguration = RuntimeConfiguration(),
) -> AsyncArray: # TODO: Union[AsyncArray, ArrayV2]
store_path = make_store_path(store)
v3_metadata_bytes = await (store_path / ZARR_JSON).get()
if v3_metadata_bytes is not None:
return cls.from_dict(
store_path,
json.loads(v3_metadata_bytes),
runtime_configuration=runtime_configuration or RuntimeConfiguration(),
)
else:
raise ValueError("no v2 support yet")
# return await ArrayV2.open(store_path)
@property
def ndim(self) -> int:
return len(self.metadata.shape)
@property
def shape(self) -> ChunkCoords:
return self.metadata.shape
@property
def size(self) -> int:
return np.prod(self.metadata.shape).item()
@property
def dtype(self) -> np.dtype:
return self.metadata.dtype
@property
def attrs(self) -> dict:
return self.metadata.attributes
async def getitem(self, selection: Selection):
assert isinstance(self.metadata.chunk_grid, RegularChunkGrid)
indexer = BasicIndexer(
selection,
shape=self.metadata.shape,
chunk_shape=self.metadata.chunk_grid.chunk_shape,
)
# setup output array
out = np.zeros(
indexer.shape,
dtype=self.metadata.dtype,
order=self.runtime_configuration.order,
)
# reading chunks and decoding them
await concurrent_map(
[
(chunk_coords, chunk_selection, out_selection, out)
for chunk_coords, chunk_selection, out_selection in indexer
],
self._read_chunk,
self.runtime_configuration.concurrency,
)
if out.shape:
return out
else:
return out[()]
async def _save_metadata(self) -> None:
await (self.store_path / ZARR_JSON).set(self.metadata.to_bytes())
async def _read_chunk(
self,
chunk_coords: ChunkCoords,
chunk_selection: SliceSelection,
out_selection: SliceSelection,
out: np.ndarray,
):
chunk_spec = self.metadata.get_chunk_spec(chunk_coords)
chunk_key_encoding = self.metadata.chunk_key_encoding
chunk_key = chunk_key_encoding.encode_chunk_key(chunk_coords)
store_path = self.store_path / chunk_key
if self.codecs.supports_partial_decode:
chunk_array = await self.codecs.decode_partial(
store_path, chunk_selection, chunk_spec, self.runtime_configuration
)
if chunk_array is not None:
out[out_selection] = chunk_array
else:
out[out_selection] = self.metadata.fill_value
else:
chunk_bytes = await store_path.get()
if chunk_bytes is not None:
chunk_array = await self.codecs.decode(
chunk_bytes, chunk_spec, self.runtime_configuration
)
tmp = chunk_array[chunk_selection]
out[out_selection] = tmp
else:
out[out_selection] = self.metadata.fill_value
async def setitem(self, selection: Selection, value: np.ndarray) -> None:
assert isinstance(self.metadata.chunk_grid, RegularChunkGrid)
chunk_shape = self.metadata.chunk_grid.chunk_shape
indexer = BasicIndexer(
selection,
shape=self.metadata.shape,
chunk_shape=chunk_shape,
)
sel_shape = indexer.shape
# check value shape
if np.isscalar(value):
# setting a scalar value
pass
else:
if not hasattr(value, "shape"):
value = np.asarray(value, self.metadata.dtype)
assert value.shape == sel_shape
if value.dtype.name != self.metadata.dtype.name:
value = value.astype(self.metadata.dtype, order="A")
# merging with existing data and encoding chunks
await concurrent_map(
[
(
value,
chunk_shape,
chunk_coords,
chunk_selection,
out_selection,
)
for chunk_coords, chunk_selection, out_selection in indexer
],
self._write_chunk,
self.runtime_configuration.concurrency,
)
async def _write_chunk(
self,
value: np.ndarray,
chunk_shape: ChunkCoords,
chunk_coords: ChunkCoords,
chunk_selection: SliceSelection,
out_selection: SliceSelection,
):
chunk_spec = self.metadata.get_chunk_spec(chunk_coords)
chunk_key_encoding = self.metadata.chunk_key_encoding
chunk_key = chunk_key_encoding.encode_chunk_key(chunk_coords)
store_path = self.store_path / chunk_key
if is_total_slice(chunk_selection, chunk_shape):
# write entire chunks
if np.isscalar(value):
chunk_array = np.empty(
chunk_shape,
dtype=self.metadata.dtype,
)
chunk_array.fill(value)
else:
chunk_array = value[out_selection]
await self._write_chunk_to_store(store_path, chunk_array, chunk_spec)
elif self.codecs.supports_partial_encode:
# print("encode_partial", chunk_coords, chunk_selection, repr(self))
await self.codecs.encode_partial(
store_path,
value[out_selection],
chunk_selection,
chunk_spec,
self.runtime_configuration,
)
else:
# writing partial chunks
# read chunk first
chunk_bytes = await store_path.get()
# merge new value
if chunk_bytes is None:
chunk_array = np.empty(
chunk_shape,
dtype=self.metadata.dtype,
)
chunk_array.fill(self.metadata.fill_value)
else:
chunk_array = (
await self.codecs.decode(chunk_bytes, chunk_spec, self.runtime_configuration)
).copy() # make a writable copy
chunk_array[chunk_selection] = value[out_selection]
await self._write_chunk_to_store(store_path, chunk_array, chunk_spec)
async def _write_chunk_to_store(
self, store_path: StorePath, chunk_array: np.ndarray, chunk_spec: ArraySpec
):
if np.all(chunk_array == self.metadata.fill_value):
# chunks that only contain fill_value will be removed
await store_path.delete()
else:
chunk_bytes = await self.codecs.encode(
chunk_array, chunk_spec, self.runtime_configuration
)
if chunk_bytes is None:
await store_path.delete()
else:
await store_path.set(chunk_bytes)
async def resize(self, new_shape: ChunkCoords) -> AsyncArray:
if len(new_shape) != len(self.metadata.shape):
raise ValueError(
"The new shape must have the same number of dimensions "
+ f"(={len(self.metadata.shape)})."
)
new_metadata = replace(self.metadata, shape=new_shape)
# Remove all chunks outside of the new shape
assert isinstance(self.metadata.chunk_grid, RegularChunkGrid)
chunk_shape = self.metadata.chunk_grid.chunk_shape
chunk_key_encoding = self.metadata.chunk_key_encoding
old_chunk_coords = set(all_chunk_coords(self.metadata.shape, chunk_shape))
new_chunk_coords = set(all_chunk_coords(new_shape, chunk_shape))
async def _delete_key(key: str) -> None:
await (self.store_path / key).delete()
await concurrent_map(
[
(chunk_key_encoding.encode_chunk_key(chunk_coords),)
for chunk_coords in old_chunk_coords.difference(new_chunk_coords)
],
_delete_key,
self.runtime_configuration.concurrency,
)
# Write new metadata
await (self.store_path / ZARR_JSON).set(new_metadata.to_bytes())
return replace(self, metadata=new_metadata)
async def update_attributes(self, new_attributes: Dict[str, Any]) -> AsyncArray:
new_metadata = replace(self.metadata, attributes=new_attributes)
# Write new metadata
await (self.store_path / ZARR_JSON).set(new_metadata.to_bytes())
return replace(self, metadata=new_metadata)
def __repr__(self):
return f"<AsyncArray {self.store_path} shape={self.shape} dtype={self.dtype}>"
async def info(self):
return NotImplemented
@dataclass(frozen=True)
class Array:
_async_array: AsyncArray
@classmethod
def create(
cls,
store: StoreLike,
*,
shape: ChunkCoords,
dtype: Union[str, np.dtype],
chunk_shape: ChunkCoords,
fill_value: Optional[Any] = None,
chunk_key_encoding: Union[
Tuple[Literal["default"], Literal[".", "/"]],
Tuple[Literal["v2"], Literal[".", "/"]],
] = ("default", "/"),
codecs: Optional[Iterable[Union[Codec, Dict[str, Any]]]] = None,
dimension_names: Optional[Iterable[str]] = None,
attributes: Optional[Dict[str, Any]] = None,
runtime_configuration: RuntimeConfiguration = RuntimeConfiguration(),
exists_ok: bool = False,
) -> Array:
async_array = sync(
AsyncArray.create(
store=store,
shape=shape,
dtype=dtype,
chunk_shape=chunk_shape,
fill_value=fill_value,
chunk_key_encoding=chunk_key_encoding,
codecs=codecs,
dimension_names=dimension_names,
attributes=attributes,
runtime_configuration=runtime_configuration,
exists_ok=exists_ok,
),
runtime_configuration.asyncio_loop,
)
return cls(async_array)
@classmethod
def from_dict(
cls,
store_path: StorePath,
data: Dict[str, Any],
runtime_configuration: RuntimeConfiguration,
) -> Array:
async_array = AsyncArray.from_dict(
store_path=store_path, data=data, runtime_configuration=runtime_configuration
)
return cls(async_array)
@classmethod
def open(
cls,
store: StoreLike,
runtime_configuration: RuntimeConfiguration = RuntimeConfiguration(),
) -> Array:
async_array = sync(
AsyncArray.open(store, runtime_configuration=runtime_configuration),
runtime_configuration.asyncio_loop,
)
return cls(async_array)
@classmethod
def open_auto(
cls,
store: StoreLike,
runtime_configuration: RuntimeConfiguration = RuntimeConfiguration(),
) -> Array: # TODO: Union[Array, ArrayV2]:
async_array = sync(
AsyncArray.open_auto(store, runtime_configuration),
runtime_configuration.asyncio_loop,
)
return cls(async_array)
@property
def ndim(self) -> int:
return self._async_array.ndim
@property
def shape(self) -> ChunkCoords:
return self._async_array.shape
@property
def size(self) -> int:
return self._async_array.size
@property
def dtype(self) -> np.dtype:
return self._async_array.dtype
@property
def attrs(self) -> dict:
return self._async_array.attrs
@property
def metadata(self) -> ArrayMetadata:
return self._async_array.metadata
@property
def store_path(self) -> StorePath:
return self._async_array.store_path
def __getitem__(self, selection: Selection):
return sync(
self._async_array.getitem(selection),
self._async_array.runtime_configuration.asyncio_loop,
)
def __setitem__(self, selection: Selection, value: np.ndarray) -> None:
sync(
self._async_array.setitem(selection, value),
self._async_array.runtime_configuration.asyncio_loop,
)
def resize(self, new_shape: ChunkCoords) -> Array:
return sync(
self._async_array.resize(new_shape),
self._async_array.runtime_configuration.asyncio_loop,
)
def update_attributes(self, new_attributes: Dict[str, Any]) -> Array:
return sync(
self._async_array.update_attributes(new_attributes),
self._async_array.runtime_configuration.asyncio_loop,
)
def __repr__(self):
return f"<Array {self.store_path} shape={self.shape} dtype={self.dtype}>"
def info(self):
return sync(
self._async_array.info(),
self._async_array.runtime_configuration.asyncio_loop,
)