|
1 | 1 | from __future__ import annotations |
2 | 2 |
|
3 | 3 | import warnings |
| 4 | +from collections.abc import Mapping, Sequence |
4 | 5 | from dataclasses import dataclass |
5 | | -from typing import ClassVar, Final, Literal |
| 6 | +from typing import ( |
| 7 | + ClassVar, |
| 8 | + Final, |
| 9 | + Generic, |
| 10 | + Literal, |
| 11 | + TypedDict, |
| 12 | + TypeGuard, |
| 13 | + TypeVar, |
| 14 | +) |
| 15 | + |
| 16 | +from zarr.core.common import NamedConfig |
6 | 17 |
|
7 | 18 | EndiannessStr = Literal["little", "big"] |
8 | 19 | ENDIANNESS_STR: Final = "little", "big" |
| 20 | + |
9 | 21 | SpecialFloatStrings = Literal["NaN", "Infinity", "-Infinity"] |
10 | 22 | SPECIAL_FLOAT_STRINGS: Final = ("NaN", "Infinity", "-Infinity") |
| 23 | + |
11 | 24 | JSONFloatV2 = float | SpecialFloatStrings |
12 | 25 | JSONFloatV3 = float | SpecialFloatStrings | str |
13 | 26 |
|
| 27 | +ObjectCodecID = Literal["vlen-utf8", "vlen-bytes", "vlen-array", "pickle", "json2", "msgpack2"] |
| 28 | +# These are the ids of the known object codecs for zarr v2. |
| 29 | +OBJECT_CODEC_IDS: Final = ("vlen-utf8", "vlen-bytes", "vlen-array", "pickle", "json2", "msgpack2") |
| 30 | + |
| 31 | +# This is a wider type than our standard JSON type because we need |
| 32 | +# to work with typeddict objects which are assignable to Mapping[str, object] |
| 33 | +DTypeJSON = str | int | float | Sequence["DTypeJSON"] | None | Mapping[str, object] |
| 34 | + |
| 35 | +# The DTypeJSON_V2 type exists because ZDType.from_json takes a single argument, which must contain |
| 36 | +# all the information necessary to decode the data type. Zarr v2 supports multiple distinct |
| 37 | +# data types that all used the "|O" data type identifier. These data types can only be |
| 38 | +# discriminated on the basis of their "object codec", i.e. a special data type specific |
| 39 | +# compressor or filter. So to figure out what data type a zarr v2 array has, we need the |
| 40 | +# data type identifier from metadata, as well as an object codec id if the data type identifier |
| 41 | +# is "|O". |
| 42 | +# So we will pack the name of the dtype alongside the name of the object codec id, if applicable, |
| 43 | +# in a single dict, and pass that to the data type inference logic. |
| 44 | +# These type variables have a very wide bound because the individual zdtype |
| 45 | +# classes can perform a very specific type check. |
| 46 | + |
| 47 | +# This is the JSON representation of a structured dtype in zarr v2 |
| 48 | +StructuredName_V2 = Sequence["str | StructuredName_V2"] |
| 49 | + |
| 50 | +# This models the type of the name a dtype might have in zarr v2 array metadata |
| 51 | +DTypeName_V2 = StructuredName_V2 | str |
| 52 | + |
| 53 | +TDTypeNameV2_co = TypeVar("TDTypeNameV2_co", bound=DTypeName_V2, covariant=True) |
| 54 | +TObjectCodecID_co = TypeVar("TObjectCodecID_co", bound=None | str, covariant=True) |
| 55 | + |
| 56 | + |
| 57 | +class DTypeConfig_V2(TypedDict, Generic[TDTypeNameV2_co, TObjectCodecID_co]): |
| 58 | + name: TDTypeNameV2_co |
| 59 | + object_codec_id: TObjectCodecID_co |
| 60 | + |
| 61 | + |
| 62 | +DTypeSpec_V2 = DTypeConfig_V2[DTypeName_V2, None | str] |
| 63 | + |
| 64 | + |
| 65 | +def check_structured_dtype_v2_inner(data: object) -> TypeGuard[StructuredName_V2]: |
| 66 | + """ |
| 67 | + A type guard for the inner elements of a structured dtype. This is a recursive check because |
| 68 | + the type is itself recursive. |
| 69 | +
|
| 70 | + This check ensures that all the elements are 2-element sequences beginning with a string |
| 71 | + and ending with either another string or another 2-element sequence beginning with a string and |
| 72 | + ending with another instance of that type. |
| 73 | + """ |
| 74 | + if isinstance(data, (str, Mapping)): |
| 75 | + return False |
| 76 | + if not isinstance(data, Sequence): |
| 77 | + return False |
| 78 | + if len(data) != 2: |
| 79 | + return False |
| 80 | + if not (isinstance(data[0], str)): |
| 81 | + return False |
| 82 | + if isinstance(data[-1], str): |
| 83 | + return True |
| 84 | + elif isinstance(data[-1], Sequence): |
| 85 | + return check_structured_dtype_v2_inner(data[-1]) |
| 86 | + return False |
| 87 | + |
| 88 | + |
| 89 | +def check_structured_dtype_name_v2(data: Sequence[object]) -> TypeGuard[StructuredName_V2]: |
| 90 | + return all(check_structured_dtype_v2_inner(d) for d in data) |
| 91 | + |
| 92 | + |
| 93 | +def check_dtype_name_v2(data: object) -> TypeGuard[DTypeName_V2]: |
| 94 | + """ |
| 95 | + Type guard for narrowing the type of a python object to an valid zarr v2 dtype name. |
| 96 | + """ |
| 97 | + if isinstance(data, str): |
| 98 | + return True |
| 99 | + elif isinstance(data, Sequence): |
| 100 | + return check_structured_dtype_name_v2(data) |
| 101 | + return False |
| 102 | + |
| 103 | + |
| 104 | +def check_dtype_spec_v2(data: object) -> TypeGuard[DTypeSpec_V2]: |
| 105 | + """ |
| 106 | + Type guard for narrowing a python object to an instance of DTypeSpec_V2 |
| 107 | + """ |
| 108 | + if not isinstance(data, Mapping): |
| 109 | + return False |
| 110 | + if set(data.keys()) != {"name", "object_codec_id"}: |
| 111 | + return False |
| 112 | + if not check_dtype_name_v2(data["name"]): |
| 113 | + return False |
| 114 | + return isinstance(data["object_codec_id"], str | None) |
| 115 | + |
| 116 | + |
| 117 | +# By comparison, The JSON representation of a dtype in zarr v3 is much simpler. |
| 118 | +# It's either a string, or a structured dict |
| 119 | +DTypeSpec_V3 = str | NamedConfig[str, Mapping[str, object]] |
| 120 | + |
| 121 | + |
| 122 | +def check_dtype_spec_v3(data: object) -> TypeGuard[DTypeSpec_V3]: |
| 123 | + """ |
| 124 | + Type guard for narrowing the type of a python object to an instance of |
| 125 | + DTypeSpec_V3, i.e either a string or a dict with a "name" field that's a string and a |
| 126 | + "configuration" field that's a mapping with string keys. |
| 127 | + """ |
| 128 | + if isinstance(data, str) or ( # noqa: SIM103 |
| 129 | + isinstance(data, Mapping) |
| 130 | + and set(data.keys()) == {"name", "configuration"} |
| 131 | + and isinstance(data["configuration"], Mapping) |
| 132 | + and all(isinstance(k, str) for k in data["configuration"]) |
| 133 | + ): |
| 134 | + return True |
| 135 | + return False |
| 136 | + |
| 137 | + |
| 138 | +def unpack_dtype_json(data: DTypeSpec_V2 | DTypeSpec_V3) -> DTypeJSON: |
| 139 | + """ |
| 140 | + Return the array metadata form of the dtype JSON representation. For the Zarr V3 form of dtype |
| 141 | + metadata, this is a no-op. For the Zarr V2 form of dtype metadata, this unpacks the dtype name. |
| 142 | + """ |
| 143 | + if isinstance(data, Mapping) and set(data.keys()) == {"name", "object_codec_id"}: |
| 144 | + return data["name"] |
| 145 | + return data |
| 146 | + |
14 | 147 |
|
15 | 148 | class DataTypeValidationError(ValueError): ... |
16 | 149 |
|
|
0 commit comments