Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 7 additions & 5 deletions docs/tutorial.rst
Original file line numberDiff line numberDiff line change
Expand Up@@ -176,7 +176,7 @@ print some diagnostics, e.g.::
Read-only : False
Compressor : Blosc(cname='zstd', clevel=3, shuffle=BITSHUFFLE,
: blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 3379344 (3.2M)
Storage ratio : 118.4
Expand DownExpand Up@@ -268,7 +268,7 @@ Here is an example using a delta filter with the Blosc compressor::
Read-only : False
Filter [0] : Delta(dtype='<i4')
Compressor : Blosc(cname='zstd', clevel=1, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 1290562 (1.2M)
Storage ratio : 309.9
Expand DownExpand Up@@ -795,8 +795,10 @@ Here is an example using S3Map to read an array created previously::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : fsspec.mapping.FSMap
Store type : zarr.storage.KVStore
No. bytes : 21
No. bytes stored : 382
Storage ratio : 0.1
Chunks initialized : 3/3
>>> z[:]
array([b'H', b'e', b'l', b'l', b'o', b' ', b'f', b'r', b'o', b'm', b' ',
Expand DownExpand Up@@ -1262,7 +1264,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 6696010 (6.4M)
Storage ratio : 59.7
Expand All@@ -1276,7 +1278,7 @@ ratios, depending on the correlation structure within the data. E.g.::
Order : F
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 400000000 (381.5M)
No. bytes stored : 4684636 (4.5M)
Storage ratio : 85.4
Expand Down
2 changes: 1 addition & 1 deletion mypy.ini
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
[mypy]
python_version = 3.6
python_version = 3.8
ignore_missing_imports = True
follow_imports = silent
2 changes: 2 additions & 0 deletions pytest.ini
Original file line numberDiff line numberDiff line change
Expand Up@@ -3,4 +3,6 @@ doctest_optionflags = NORMALIZE_WHITESPACE ELLIPSIS IGNORE_EXCEPTION_DETAIL
addopts = --durations=10
filterwarnings =
error::DeprecationWarning:zarr.*
error::UserWarning:zarr.*
ignore:PY_SSIZE_T_CLEAN will be required.*:DeprecationWarning
ignore:The loop argument is deprecated since Python 3.8.*:DeprecationWarning
71 changes: 38 additions & 33 deletions zarr/convenience.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -12,17 +12,21 @@
from zarr.hierarchy import group as _create_group
from zarr.hierarchy import open_group
from zarr.meta import json_dumps, json_loads
from zarr.storage import contains_array, contains_group
from zarr.storage import contains_array, contains_group, Store
from zarr.util import TreeViewer, buffer_size, normalize_storage_path

from typing import Union

StoreLike = Union[Store, str, None]


# noinspection PyShadowingBuiltins
def open(store=None, mode='a', **kwargs):
def open(store: StoreLike = None, mode: str = "a", **kwargs):
"""Convenience function to open a group or array using file-mode-like semantics.

Parameters
----------
store : MutableMapping or string, optional
store : Store or string, optional
Store or path to directory in file system or name of zip file.
mode : {'r', 'r+', 'a', 'w', 'w-'}, optional
Persistence mode: 'r' means read only (must exist); 'r+' means
Expand DownExpand Up@@ -75,32 +79,33 @@ def open(store=None, mode='a', **kwargs):
clobber = mode == 'w'
# we pass storage options explicitly, since normalize_store_arg might construct
# a store if the input is a fsspec-compatible URL
store = normalize_store_arg(store, clobber=clobber,
storage_options=kwargs.pop("storage_options", {}))
_store: Store = normalize_store_arg(
store, clobber=clobber, storage_options=kwargs.pop("storage_options", {})
)
path = normalize_storage_path(path)

if mode in {'w', 'w-', 'x'}:
if 'shape' in kwargs:
return open_array(store, mode=mode, **kwargs)
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

elif mode == "a":
if "shape" in kwargs or contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
if "shape" in kwargs or contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
else:
return open_group(store, mode=mode, **kwargs)
return open_group(_store, mode=mode, **kwargs)

else:
if contains_array(store, path):
return open_array(store, mode=mode, **kwargs)
elif contains_group(store, path):
return open_group(store, mode=mode, **kwargs)
if contains_array(_store, path):
return open_array(_store, mode=mode, **kwargs)
elif contains_group(_store, path):
return open_group(_store, mode=mode, **kwargs)
else:
raise PathNotFoundError(path)


def save_array(store, arr, **kwargs):
def save_array(store: StoreLike, arr, **kwargs):
"""Convenience function to save a NumPy array to the local file system, following a
similar API to the NumPy save() function.

Expand DownExpand Up@@ -132,16 +137,16 @@ def save_array(store, arr, **kwargs):

"""
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
_create_array(arr, store=store, overwrite=True, **kwargs)
_create_array(arr, store=_store, overwrite=True, **kwargs)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save_group(store, *args, **kwargs):
def save_group(store: StoreLike, *args, **kwargs):
"""Convenience function to save several NumPy arrays to the local file system, following a
similar API to the NumPy savez()/savez_compressed() functions.

Expand DownExpand Up@@ -203,21 +208,21 @@ def save_group(store, *args, **kwargs):
raise ValueError('at least one array must be provided')
# handle polymorphic store arg
may_need_closing = isinstance(store, str)
store = normalize_store_arg(store, clobber=True)
_store: Store = normalize_store_arg(store, clobber=True)
try:
grp = _create_group(store, overwrite=True)
grp = _create_group(_store, overwrite=True)
for i, arr in enumerate(args):
k = 'arr_{}'.format(i)
grp.create_dataset(k, data=arr, overwrite=True)
for k, arr in kwargs.items():
grp.create_dataset(k, data=arr, overwrite=True)
finally:
if may_need_closing and hasattr(store, 'close'):
if may_need_closing:
# needed to ensure zip file records are written
store.close()
_store.close()


def save(store, *args, **kwargs):
def save(store: StoreLike, *args, **kwargs):
"""Convenience function to save an array or group of arrays to the local file system.

Parameters
Expand DownExpand Up@@ -327,7 +332,7 @@ def __repr__(self):
return r


def load(store):
def load(store: StoreLike):
"""Load data from an array or group into memory.

Parameters
Expand All@@ -353,11 +358,11 @@ def load(store):

"""
# handle polymorphic store arg
store = normalize_store_arg(store)
if contains_array(store, path=None):
return Array(store=store, path=None)[...]
elif contains_group(store, path=None):
grp = Group(store=store, path=None)
_store = normalize_store_arg(store)
if contains_array(_store, path=None):
return Array(store=_store, path=None)[...]
elif contains_group(_store, path=None):
grp = Group(store=_store, path=None)
return LazyLoader(grp)


Expand DownExpand Up@@ -1073,7 +1078,7 @@ def copy_all(source, dest, shallow=False, without_attrs=False, log=None,
return n_copied, n_skipped, n_bytes_copied


def consolidate_metadata(store, metadata_key='.zmetadata'):
def consolidate_metadata(store: Store, metadata_key=".zmetadata"):
"""
Consolidate all metadata for groups and arrays within the given store
into a single resource and put it under the given key.
Expand DownExpand Up@@ -1124,7 +1129,7 @@ def is_zarr_key(key):
return open_consolidated(store, metadata_key=metadata_key)


def open_consolidated(store, metadata_key='.zmetadata', mode='r+', **kwargs):
def open_consolidated(store: Store, metadata_key=".zmetadata", mode="r+", **kwargs):
"""Open group using metadata previously consolidated into a single key.

This is an optimised method for opening a Zarr group, where instead of
Expand Down
17 changes: 11 additions & 6 deletions zarr/core.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -9,6 +9,8 @@
import numpy as np
from numcodecs.compat import ensure_bytes, ensure_ndarray

from collections.abc import MutableMapping

from zarr.attrs import Attributes
from zarr.codecs import AsType, get_codec
from zarr.errors import ArrayNotFoundError, ReadOnlyError, ArrayIndexError
Expand All@@ -29,7 +31,7 @@
pop_fields,
)
from zarr.meta import decode_array_metadata, encode_array_metadata
from zarr.storage import array_meta_key, attrs_key, getsize, listdir
from zarr.storage import array_meta_key, attrs_key, getsize, listdir, Store
from zarr.util import (
InfoReporter,
check_array_shape,
Expand DownExpand Up@@ -129,7 +131,7 @@ class Array:

def __init__(
self,
store,
store: Store,
path=None,
read_only=False,
chunk_store=None,
Expand All@@ -141,6 +143,9 @@ def __init__(
# N.B., expect at this point store is fully initialized with all
# configuration metadata fully specified and normalized

store = Store._ensure_store(store)
chunk_store = Store._ensure_store(chunk_store)

self._store = store
self._chunk_store = chunk_store
self._path = normalize_storage_path(path)
Expand DownExpand Up@@ -2009,7 +2014,7 @@ def _encode_chunk(self, chunk):
cdata = chunk

# ensure in-memory data is immutable and easy to compare
if isinstance(self.chunk_store, dict):
if isinstance(self.chunk_store, MutableMapping):
cdata = ensure_bytes(cdata)

return cdata
Expand DownExpand Up@@ -2042,10 +2047,10 @@ def info(self):
Order : C
Read-only : False
Compressor : Blosc(cname='lz4', clevel=5, shuffle=SHUFFLE, blocksize=0)
Store type : builtins.dict
Store type : zarr.storage.KVStore
No. bytes : 4000000 (3.8M)
No. bytes stored : ...
Storage ratio : ...
No. bytes stored : 320
Storage ratio : 12500.0
Chunks initialized : 0/10

"""
Expand Down
22 changes: 17 additions & 5 deletions zarr/creation.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -2,6 +2,7 @@

import numpy as np
from numcodecs.registry import codec_registry
from collections.abc import MutableMapping

from zarr.core import Array
from zarr.errors import (
Expand All@@ -10,9 +11,18 @@
ContainsGroupError,
)
from zarr.n5 import N5Store
from zarr.storage import (DirectoryStore, ZipStore, contains_array,
contains_group, default_compressor, init_array,
normalize_storage_path, FSStore)
from zarr.storage import (
DirectoryStore,
ZipStore,
KVStore,
contains_array,
contains_group,
default_compressor,
init_array,
normalize_storage_path,
FSStore,
Store,
)


def create(shape, chunks=True, dtype=None, compressor='default',
Expand DownExpand Up@@ -129,9 +139,9 @@ def create(shape, chunks=True, dtype=None, compressor='default',
return z


def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
def normalize_store_arg(store, clobber=False, storage_options=None, mode="w") -> Store:
if store is None:
return dict()
return Store._ensure_store(dict())
elif isinstance(store, str):
mode = mode if clobber else "r"
if "://" in store or "::" in store:
Expand All@@ -145,6 +155,8 @@ def normalize_store_arg(store, clobber=False, storage_options=None, mode='w'):
else:
return DirectoryStore(store)
else:
if not isinstance(store, Store) and isinstance(store, MutableMapping):
store = KVStore(store)
return store


Expand Down
Loading