Repository navigation
Expand file tree
/
Copy path_base.py
More file actions
225 lines (193 loc) · 7.76 KB
/
Copy path_base.py
File metadata and controls
225 lines (193 loc) · 7.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
"""Base class and helpers for the cast_value zarr codec (v1 API)."""
from __future__ import annotations
from dataclasses import dataclass, replace
from typing import TYPE_CHECKING, cast
import numpy as np
from zarr.abc.codec import ArrayArrayCodec
from zarr.core.common import JSON, parse_named_configuration
from zarr.core.dtype import get_data_type_from_json
from cast_value.zarr_compat._parsing import (
extract_raw_map,
parse_map_entries,
parse_scalar_map,
)
if TYPE_CHECKING:
from collections.abc import Iterable
from typing import Self
from zarr.core.array_spec import ArraySpec
from zarr.core.buffer import NDBuffer
from zarr.core.chunk_grids import ChunkGrid
from zarr.core.dtype.wrapper import TBaseDType, TBaseScalar, ZDType
from cast_value.types import (
OutOfRangeMode,
RoundingMode,
ScalarMapEntry,
ScalarMapJSON,
ScalarMapLike,
)
@dataclass(frozen=True)
class _CastValueBaseV1(ArrayArrayCodec):
"""Base class for cast-value array-to-array codecs.
Subclasses must implement ``_cast_array`` to provide the actual
array casting logic. Everything else — metadata handling, validation,
serialization — is shared.
Parameters
----------
data_type : str
Target zarr v3 data type name (e.g. "uint8", "float32").
rounding : RoundingMode
How to round when exact representation is impossible. Default is "nearest-even".
out_of_range : OutOfRangeMode or None
What to do when a value is outside the target's range.
None means error. "clamp" clips to range. "wrap" uses modular arithmetic
(only valid for integer types).
scalar_map : dict or None
Explicit value overrides. Each of the optional "encode"/"decode" keys
accepts either a mapping of source -> target or an iterable of
(source, target) pairs; both are normalized to the spec's
list-of-pairs form: {"encode": [[src, tgt], ...], "decode": [[src, tgt], ...]}.
"""
is_fixed_size = True
dtype: ZDType[TBaseDType, TBaseScalar]
rounding: RoundingMode
out_of_range: OutOfRangeMode | None
scalar_map: ScalarMapJSON | None
def __init__(
self,
*,
data_type: str | ZDType[TBaseDType, TBaseScalar],
rounding: RoundingMode = "nearest-even",
out_of_range: OutOfRangeMode | None = None,
scalar_map: ScalarMapJSON | ScalarMapLike | None = None,
) -> None:
if isinstance(data_type, str):
dtype = get_data_type_from_json(data_type, zarr_format=3)
else:
dtype = data_type
object.__setattr__(self, "dtype", dtype)
object.__setattr__(self, "rounding", rounding)
object.__setattr__(self, "out_of_range", out_of_range)
object.__setattr__(self, "scalar_map", parse_scalar_map(scalar_map))
@classmethod
def from_dict(cls, data: dict[str, JSON]) -> Self:
_, configuration_parsed = parse_named_configuration(
data, "cast_value", require_configuration=True
)
return cls(**configuration_parsed) # type: ignore[arg-type] # ty: ignore[invalid-argument-type]
def to_dict(self) -> dict[str, JSON]:
config: dict[str, JSON] = {
"data_type": cast("JSON", self.dtype.to_json(zarr_format=3))
}
if self.rounding != "nearest-even":
config["rounding"] = self.rounding
if self.out_of_range is not None:
config["out_of_range"] = self.out_of_range
if self.scalar_map is not None:
config["scalar_map"] = cast("JSON", self.scalar_map)
return {"name": "cast_value", "configuration": config}
def validate(
self,
*,
shape: tuple[int, ...], # noqa: ARG002
dtype: ZDType[TBaseDType, TBaseScalar],
chunk_grid: ChunkGrid, # noqa: ARG002
) -> None:
source_native = dtype.to_native_dtype()
target_native = self.dtype.to_native_dtype()
for label, dt in [("source", source_native), ("target", target_native)]:
if not np.issubdtype(dt, np.integer) and not np.issubdtype(dt, np.floating):
msg = (
f"cast_value codec only supports integer and floating-point data types. "
f"Got {label} dtype {dt}."
)
raise ValueError(msg)
if self.out_of_range == "wrap" and not np.issubdtype(target_native, np.integer):
msg = "out_of_range='wrap' is only valid for integer target types."
raise ValueError(msg)
def _cast_array(
self,
arr: np.ndarray,
*,
target_dtype: np.dtype,
scalar_map_entries: Iterable[ScalarMapEntry] | None,
) -> np.ndarray:
"""Cast *arr* to *target_dtype*. Subclasses must override this."""
raise NotImplementedError
def resolve_metadata(self, chunk_spec: ArraySpec) -> ArraySpec:
target_zdtype = self.dtype
target_native = target_zdtype.to_native_dtype()
source_native = chunk_spec.dtype.to_native_dtype()
fill = chunk_spec.fill_value
fill_arr = np.array([fill], dtype=source_native)
encode_raw = extract_raw_map(self.scalar_map, "encode")
encode_entries = (
parse_map_entries(encode_raw, chunk_spec.dtype, self.dtype)
if encode_raw
else None
)
new_fill_arr = self._cast_array(
fill_arr,
target_dtype=target_native,
scalar_map_entries=encode_entries,
)
new_fill = target_native.type(new_fill_arr[0])
return replace(chunk_spec, dtype=target_zdtype, fill_value=new_fill)
def _encode_sync(
self,
chunk_array: NDBuffer,
_chunk_spec: ArraySpec,
) -> NDBuffer | None:
arr = chunk_array.as_ndarray_like()
target_native = self.dtype.to_native_dtype()
encode_raw = extract_raw_map(self.scalar_map, "encode")
encode_entries = (
parse_map_entries(encode_raw, _chunk_spec.dtype, self.dtype)
if encode_raw
else None
)
result = self._cast_array(
np.asarray(arr),
target_dtype=target_native,
scalar_map_entries=encode_entries,
)
return chunk_array.__class__.from_ndarray_like(result) # ty: ignore[invalid-argument-type]
async def _encode_single(
self,
chunk_data: NDBuffer,
chunk_spec: ArraySpec,
) -> NDBuffer | None:
return self._encode_sync(chunk_data, chunk_spec)
def _decode_sync(
self,
chunk_array: NDBuffer,
chunk_spec: ArraySpec,
) -> NDBuffer:
arr = chunk_array.as_ndarray_like()
target_native = chunk_spec.dtype.to_native_dtype()
decode_raw = extract_raw_map(self.scalar_map, "decode")
decode_entries = (
parse_map_entries(decode_raw, self.dtype, chunk_spec.dtype)
if decode_raw
else None
)
result = self._cast_array(
np.asarray(arr),
target_dtype=target_native,
scalar_map_entries=decode_entries,
)
return chunk_array.__class__.from_ndarray_like(result) # ty: ignore[invalid-argument-type]
async def _decode_single(
self,
chunk_data: NDBuffer,
chunk_spec: ArraySpec,
) -> NDBuffer:
return self._decode_sync(chunk_data, chunk_spec)
def compute_encoded_size(
self, input_byte_length: int, chunk_spec: ArraySpec
) -> int:
source_itemsize = chunk_spec.dtype.to_native_dtype().itemsize
target_itemsize = self.dtype.to_native_dtype().itemsize
if source_itemsize == 0: # pragma: no cover
return 0
num_elements = input_byte_length // source_itemsize
return num_elements * target_itemsize