|
| 1 | +from typing import Any |
| 2 | + |
| 3 | +import hypothesis.extra.numpy as npst |
| 4 | +import hypothesis.strategies as st |
| 5 | +import numpy as np |
| 6 | +from hypothesis import given, settings # noqa |
| 7 | + |
| 8 | +from .array import Array |
| 9 | +from .group import Group |
| 10 | +from .store import MemoryStore, StoreLike |
| 11 | + |
| 12 | +# Copied from Xarray |
| 13 | +_attr_keys = st.text(st.characters(), min_size=1) |
| 14 | +_attr_values = st.recursive( |
| 15 | + st.none() | st.booleans() | st.text(st.characters(), max_size=5), |
| 16 | + lambda children: st.lists(children) | st.dictionaries(_attr_keys, children), |
| 17 | + max_leaves=3, |
| 18 | +) |
| 19 | + |
| 20 | +# From https://zarr-specs.readthedocs.io/en/latest/v3/core/v3.0.html#node-names |
| 21 | +# 1. must not be the empty string ("") |
| 22 | +# 2. must not include the character "/" |
| 23 | +# 3. must not be a string composed only of period characters, e.g. "." or ".." |
| 24 | +# 4. must not start with the reserved prefix "__" |
| 25 | +zarr_key_chars = st.sampled_from( |
| 26 | + ".-0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz" |
| 27 | +) |
| 28 | +node_names = st.text(zarr_key_chars, min_size=1).filter( |
| 29 | + lambda t: t not in (".", "..") and not t.startswith("__") |
| 30 | +) |
| 31 | +array_names = node_names |
| 32 | +attrs = st.none() | st.dictionaries(_attr_keys, _attr_values) |
| 33 | +paths = st.lists(node_names, min_size=1).map(lambda x: "/".join(x)) | st.just("/") |
| 34 | +np_arrays = npst.arrays( |
| 35 | + # TODO: re-enable timedeltas once they are supported |
| 36 | + dtype=npst.scalar_dtypes().filter(lambda x: x.kind != "m"), |
| 37 | + shape=npst.array_shapes(max_dims=4), |
| 38 | +) |
| 39 | +stores = st.builds(MemoryStore, st.just({}), mode=st.just("w")) |
| 40 | +compressors = st.sampled_from([None, "default"]) |
| 41 | + |
| 42 | + |
| 43 | +@st.composite # type: ignore[misc] |
| 44 | +def np_array_and_chunks( |
| 45 | + draw: st.DrawFn, *, arrays: st.SearchStrategy[np.ndarray] = np_arrays |
| 46 | +) -> tuple[np.ndarray, tuple[int]]: # type: ignore[type-arg] |
| 47 | + """A hypothesis strategy to generate small sized random arrays. |
| 48 | +
|
| 49 | + Returns: a tuple of the array and a suitable random chunking for it. |
| 50 | + """ |
| 51 | + array = draw(arrays) |
| 52 | + # We want this strategy to shrink towards arrays with smaller number of chunks |
| 53 | + # 1. st.integers() shrinks towards smaller values. So we use that to generate number of chunks |
| 54 | + numchunks = draw(st.tuples(*[st.integers(min_value=1, max_value=size) for size in array.shape])) |
| 55 | + # 2. and now generate the chunks tuple |
| 56 | + chunks = tuple(size // nchunks for size, nchunks in zip(array.shape, numchunks, strict=True)) |
| 57 | + return (array, chunks) |
| 58 | + |
| 59 | + |
| 60 | +@st.composite # type: ignore[misc] |
| 61 | +def arrays( |
| 62 | + draw: st.DrawFn, |
| 63 | + *, |
| 64 | + compressors: st.SearchStrategy = compressors, |
| 65 | + stores: st.SearchStrategy[StoreLike] = stores, |
| 66 | + arrays: st.SearchStrategy[np.ndarray] = np_arrays, |
| 67 | + paths: st.SearchStrategy[None | str] = paths, |
| 68 | + array_names: st.SearchStrategy = array_names, |
| 69 | + attrs: st.SearchStrategy = attrs, |
| 70 | +) -> Array: |
| 71 | + store = draw(stores) |
| 72 | + nparray, chunks = draw(np_array_and_chunks(arrays=arrays)) |
| 73 | + path = draw(paths) |
| 74 | + name = draw(array_names) |
| 75 | + attributes = draw(attrs) |
| 76 | + # compressor = draw(compressors) |
| 77 | + |
| 78 | + # TODO: clean this up |
| 79 | + # if path is None and name is None: |
| 80 | + # array_path = None |
| 81 | + # array_name = None |
| 82 | + # elif path is None and name is not None: |
| 83 | + # array_path = f"{name}" |
| 84 | + # array_name = f"/{name}" |
| 85 | + # elif path is not None and name is None: |
| 86 | + # array_path = path |
| 87 | + # array_name = None |
| 88 | + # elif path == "/": |
| 89 | + # assert name is not None |
| 90 | + # array_path = name |
| 91 | + # array_name = "/" + name |
| 92 | + # else: |
| 93 | + # assert name is not None |
| 94 | + # array_path = f"{path}/{name}" |
| 95 | + # array_name = "/" + array_path |
| 96 | + |
| 97 | + expected_attrs = {} if attributes is None else attributes |
| 98 | + |
| 99 | + array_path = path + ("/" if not path.endswith("/") else "") + name |
| 100 | + root = Group.create(store) |
| 101 | + fill_value_args: tuple[Any, ...] = tuple() |
| 102 | + if nparray.dtype.kind == "M": |
| 103 | + fill_value_args = ("ns",) |
| 104 | + |
| 105 | + a = root.create_array( |
| 106 | + array_path, |
| 107 | + shape=nparray.shape, |
| 108 | + chunks=chunks, |
| 109 | + dtype=nparray.dtype.str, |
| 110 | + attributes=attributes, |
| 111 | + # compressor=compressor, # TODO: FIXME |
| 112 | + fill_value=nparray.dtype.type(0, *fill_value_args), |
| 113 | + ) |
| 114 | + |
| 115 | + assert isinstance(a, Array) |
| 116 | + assert nparray.shape == a.shape |
| 117 | + assert chunks == a.chunks |
| 118 | + assert array_path == a.path, (path, name, array_path, a.name, a.path) |
| 119 | + # assert array_path == a.name, (path, name, array_path, a.name, a.path) |
| 120 | + # assert a.basename is None # TODO |
| 121 | + # assert a.store == normalize_store_arg(store) |
| 122 | + assert dict(a.attrs) == expected_attrs |
| 123 | + |
| 124 | + a[:] = nparray |
| 125 | + |
| 126 | + return a |
| 127 | + |
| 128 | + |
| 129 | +def is_negative_slice(idx: Any) -> bool: |
| 130 | + return isinstance(idx, slice) and idx.step is not None and idx.step < 0 |
| 131 | + |
| 132 | + |
| 133 | +@st.composite # type: ignore[misc] |
| 134 | +def basic_indices(draw: st.DrawFn, *, shape: tuple[int], **kwargs): # type: ignore[no-untyped-def] |
| 135 | + """Basic indices without unsupported negative slices.""" |
| 136 | + return draw( |
| 137 | + npst.basic_indices(shape=shape, **kwargs).filter( |
| 138 | + lambda idxr: ( |
| 139 | + not ( |
| 140 | + is_negative_slice(idxr) |
| 141 | + or (isinstance(idxr, tuple) and any(is_negative_slice(idx) for idx in idxr)) |
| 142 | + ) |
| 143 | + ) |
| 144 | + ) |
| 145 | + ) |
0 commit comments