spacetimer 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- spacetimer/__init__.py +36 -0
- spacetimer/_html.py +172 -0
- spacetimer/_svg.py +196 -0
- spacetimer/bitround.py +184 -0
- spacetimer/core.py +724 -0
- spacetimer/icons/space.png +0 -0
- spacetimer/icons/time.png +0 -0
- spacetimer/py.typed +0 -0
- spacetimer-0.1.0.dist-info/METADATA +44 -0
- spacetimer-0.1.0.dist-info/RECORD +12 -0
- spacetimer-0.1.0.dist-info/WHEEL +4 -0
- spacetimer-0.1.0.dist-info/licenses/LICENSE +21 -0
spacetimer/core.py
ADDED
|
@@ -0,0 +1,724 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import math
|
|
4
|
+
import warnings
|
|
5
|
+
from collections.abc import Collection, Iterable, Mapping, Sequence
|
|
6
|
+
from dataclasses import asdict, dataclass, field
|
|
7
|
+
from enum import StrEnum
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Literal, NotRequired, TypedDict
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import xarray as xr
|
|
13
|
+
import zarr
|
|
14
|
+
from zarr.abc.codec import BytesBytesCodec
|
|
15
|
+
from zarr.codecs import BloscCodec
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
import pandas as pd
|
|
19
|
+
|
|
20
|
+
MiB = 1024 * 1024
|
|
21
|
+
# caps shard size in chunks; the zarr v3 shard index is 16 B per chunk, so 8 KiB.
|
|
22
|
+
# dynamical's worked example (1440x32x32 in 2880x384x384) holds 288
|
|
23
|
+
MAX_INNER_CHUNKS = 512
|
|
24
|
+
MIN_EDGE = 32 # the time preset's tile, so balanced never reads more per map
|
|
25
|
+
YEAR = np.timedelta64(365, "D")
|
|
26
|
+
YEAR_RULE = (
|
|
27
|
+
"https://github.com/dynamical-org/reformatters/blob/"
|
|
28
|
+
"cb7d15bfe5dfba501ed383041d141444d6ee7009/src/scripts/chunk_shard_size.py#L330-L339"
|
|
29
|
+
)
|
|
30
|
+
SPATIAL_DIMS = frozenset({"x", "y", "lat", "lon", "latitude", "longitude"})
|
|
31
|
+
# CF coordinate metadata that marks a coordinate's dims as spatial
|
|
32
|
+
CF_SPATIAL_NAMES = frozenset(
|
|
33
|
+
{
|
|
34
|
+
"latitude",
|
|
35
|
+
"longitude",
|
|
36
|
+
"grid_latitude",
|
|
37
|
+
"grid_longitude",
|
|
38
|
+
"projection_x_coordinate",
|
|
39
|
+
"projection_y_coordinate",
|
|
40
|
+
}
|
|
41
|
+
)
|
|
42
|
+
CF_DEGREES = frozenset(
|
|
43
|
+
f"{deg}{sep}{d}"
|
|
44
|
+
for deg in ("degree", "degrees")
|
|
45
|
+
for sep in ("_", "")
|
|
46
|
+
for d in ("north", "east", "N", "E")
|
|
47
|
+
)
|
|
48
|
+
# warnings skip our frames so they point at the caller, accessor included
|
|
49
|
+
_PKG = (str(Path(__file__).parent),)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class UseCase(StrEnum):
|
|
53
|
+
"""The access pattern readers will use most. Plain strings work too."""
|
|
54
|
+
|
|
55
|
+
TIME = "time"
|
|
56
|
+
"""Time series at a point."""
|
|
57
|
+
SPACE = "space"
|
|
58
|
+
"""Full maps at one time step."""
|
|
59
|
+
BALANCED = "balanced"
|
|
60
|
+
"""A mix of maps and time series."""
|
|
61
|
+
WEB = "web"
|
|
62
|
+
"""Map tiles in a browser."""
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
class SizeBasis(StrEnum):
|
|
66
|
+
"""What a preset's ``chunk_bytes`` measures."""
|
|
67
|
+
|
|
68
|
+
RAW = "raw"
|
|
69
|
+
"""Uncompressed bytes (web tiles are sized by extent)."""
|
|
70
|
+
COMPRESSED = "compressed"
|
|
71
|
+
"""Compressed bytes, converted to raw with ``compression_ratio``."""
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
@dataclass(frozen=True)
|
|
75
|
+
class Preset:
|
|
76
|
+
"""Chunk and shard targets for one use case; see ``PRESETS``."""
|
|
77
|
+
|
|
78
|
+
chunk_bytes: int
|
|
79
|
+
"""Target chunk size, measured as ``basis`` says."""
|
|
80
|
+
basis: SizeBasis
|
|
81
|
+
spatial_edge: int | Literal["auto"] | None
|
|
82
|
+
"""Spatial tile edge; time takes the rest of the budget. ``"auto"``: the edge
|
|
83
|
+
where one map and one time series read the same number of chunks. ``None``:
|
|
84
|
+
one time step per chunk."""
|
|
85
|
+
chunks_per_shard: int
|
|
86
|
+
"""Default chunks per shard along each spatial dim."""
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
PRESETS: dict[UseCase, Preset] = {
|
|
90
|
+
# dynamical.org reformatters, analysis mode: ~3.5 MiB compressed, 32x32 tiles
|
|
91
|
+
UseCase.TIME: Preset(int(3.5 * MiB), SizeBasis.COMPRESSED, 32, 8),
|
|
92
|
+
# same byte target, spent on one time step of the largest tile that fits
|
|
93
|
+
UseCase.SPACE: Preset(int(3.5 * MiB), SizeBasis.COMPRESSED, None, 8),
|
|
94
|
+
# same byte target; tile edge picked per variable, at least the time preset's 32
|
|
95
|
+
UseCase.BALANCED: Preset(int(3.5 * MiB), SizeBasis.COMPRESSED, "auto", 8),
|
|
96
|
+
# topozarr: 512 KiB raw tiles, 4x4 chunks per shard
|
|
97
|
+
UseCase.WEB: Preset(512 * 1024, SizeBasis.RAW, None, 4),
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class VarSpec:
|
|
103
|
+
"""One variable's metadata, to plan a layout before the data exists."""
|
|
104
|
+
|
|
105
|
+
name: str
|
|
106
|
+
dims: tuple[str, ...]
|
|
107
|
+
shape: tuple[int, ...]
|
|
108
|
+
"""Final shape; chunks never exceed it."""
|
|
109
|
+
dtype: np.dtype
|
|
110
|
+
"""Anything ``np.dtype`` accepts, e.g. ``"f4"``."""
|
|
111
|
+
attrs: Mapping[str, Any] = field(default_factory=dict)
|
|
112
|
+
"""CF attributes; ``convention_keepbits`` reads ``standard_name``,
|
|
113
|
+
``long_name``, and ``units``."""
|
|
114
|
+
|
|
115
|
+
def __post_init__(self) -> None:
|
|
116
|
+
object.__setattr__(self, "dtype", np.dtype(self.dtype))
|
|
117
|
+
if len(self.dims) != len(self.shape) or any(n < 1 for n in self.shape):
|
|
118
|
+
raise ValueError(
|
|
119
|
+
f"{self.name!r}: dims {self.dims} and shape {self.shape} must "
|
|
120
|
+
"have the same length, and every size must be >= 1"
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
Data = xr.Dataset | zarr.Group | Iterable[VarSpec]
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
class Encoding(TypedDict):
|
|
128
|
+
"""One variable's entry in the ``to_zarr`` encoding ``recommend`` returns."""
|
|
129
|
+
|
|
130
|
+
chunks: tuple[int, ...]
|
|
131
|
+
shards: NotRequired[tuple[int, ...]]
|
|
132
|
+
"""Absent with ``sharding=False``."""
|
|
133
|
+
compressors: tuple[BytesBytesCodec, ...]
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
@dataclass(frozen=True)
|
|
137
|
+
class Costs:
|
|
138
|
+
"""Estimates; MiB are compressed at the given compression_ratio."""
|
|
139
|
+
|
|
140
|
+
chunk_mib: float
|
|
141
|
+
shard_mib: float | None
|
|
142
|
+
"""``None`` when unsharded."""
|
|
143
|
+
objects: int
|
|
144
|
+
"""Stored objects: shards, or chunks when unsharded."""
|
|
145
|
+
slice_chunks: int
|
|
146
|
+
"""Chunks read for one full spatial slice (one map)."""
|
|
147
|
+
slice_mib: float
|
|
148
|
+
series_chunks: int
|
|
149
|
+
"""Chunks read for one point's full time series."""
|
|
150
|
+
series_mib: float
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
# dynamical.org's production codec
|
|
154
|
+
DEFAULT_COMPRESSORS: tuple[BytesBytesCodec, ...] = (
|
|
155
|
+
BloscCodec(cname="zstd", clevel=3, shuffle="shuffle"),
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def recommend(
|
|
160
|
+
data: Data,
|
|
161
|
+
use_case: UseCase,
|
|
162
|
+
*,
|
|
163
|
+
chunks_per_shard: int | None = None,
|
|
164
|
+
sharding: bool = True,
|
|
165
|
+
compression_ratio: float = 0.2,
|
|
166
|
+
raw_chunk_bytes: int | None = None,
|
|
167
|
+
spatial_dims: Collection[str] = SPATIAL_DIMS,
|
|
168
|
+
time_dim: str | None = None,
|
|
169
|
+
compressors: Sequence[BytesBytesCodec] = DEFAULT_COMPRESSORS,
|
|
170
|
+
) -> dict[str, Encoding]:
|
|
171
|
+
"""Return a ``to_zarr`` encoding for every variable with a spatial dim.
|
|
172
|
+
|
|
173
|
+
Reads metadata only. ``chunks_per_shard`` is per spatial dim; ``None`` uses
|
|
174
|
+
the preset's value. ``raw_chunk_bytes`` overrides the preset's target with an
|
|
175
|
+
uncompressed size. Chunks never exceed the current shape, so for a dataset
|
|
176
|
+
you will append to, pass ``VarSpec``s with the final shape. ``compressors``
|
|
177
|
+
replaces the default codec and does not change chunk sizes; pass a matching
|
|
178
|
+
``compression_ratio`` if yours compresses differently.
|
|
179
|
+
"""
|
|
180
|
+
use_case = UseCase(use_case)
|
|
181
|
+
preset = PRESETS[use_case]
|
|
182
|
+
_check_ratio(compression_ratio)
|
|
183
|
+
if not sharding and chunks_per_shard is not None:
|
|
184
|
+
raise ValueError("chunks_per_shard has no effect with sharding=False")
|
|
185
|
+
if chunks_per_shard is not None and chunks_per_shard < 1:
|
|
186
|
+
raise ValueError(f"chunks_per_shard must be >= 1, got {chunks_per_shard}")
|
|
187
|
+
cps = (chunks_per_shard or preset.chunks_per_shard) if sharding else None
|
|
188
|
+
if raw_chunk_bytes is None:
|
|
189
|
+
raw_chunk_bytes = (
|
|
190
|
+
preset.chunk_bytes
|
|
191
|
+
if preset.basis is SizeBasis.RAW
|
|
192
|
+
else int(preset.chunk_bytes / compression_ratio)
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
spatial_dims, cf_time = _roles(data, spatial_dims)
|
|
196
|
+
steps = _time_steps(data)
|
|
197
|
+
encoding: dict[str, Encoding] = {}
|
|
198
|
+
skipped: list[str] = []
|
|
199
|
+
for spec in _specs(data):
|
|
200
|
+
spatial = [i for i, d in enumerate(spec.dims) if d in spatial_dims]
|
|
201
|
+
if not spatial:
|
|
202
|
+
skipped.append(spec.name)
|
|
203
|
+
continue
|
|
204
|
+
t = _time_axis(spec, spatial, time_dim, cf_time)
|
|
205
|
+
if (
|
|
206
|
+
preset.spatial_edge is not None
|
|
207
|
+
and t is None
|
|
208
|
+
and len(spatial) < len(spec.dims)
|
|
209
|
+
):
|
|
210
|
+
warnings.warn(
|
|
211
|
+
f"{spec.name!r}: no time dim found in {spec.dims}, so the "
|
|
212
|
+
f"{use_case.value!r} layout falls back to spatial tiles; pass time_dim=",
|
|
213
|
+
skip_file_prefixes=_PKG,
|
|
214
|
+
)
|
|
215
|
+
if (
|
|
216
|
+
chunks_per_shard
|
|
217
|
+
and (k := _per_dim(chunks_per_shard, len(spatial))) < chunks_per_shard
|
|
218
|
+
):
|
|
219
|
+
warnings.warn(
|
|
220
|
+
f"{spec.name!r}: chunks_per_shard={chunks_per_shard} reduced to {k} "
|
|
221
|
+
f"to keep a shard at or under {MAX_INNER_CHUNKS} chunks",
|
|
222
|
+
skip_file_prefixes=_PKG,
|
|
223
|
+
)
|
|
224
|
+
chunks, shards = _layout(spec, preset, raw_chunk_bytes, cps, spatial, t)
|
|
225
|
+
if (
|
|
226
|
+
t is not None
|
|
227
|
+
and (step := steps.get(spec.dims[t])) is not None
|
|
228
|
+
and chunks[t] * step > YEAR
|
|
229
|
+
):
|
|
230
|
+
warnings.warn(
|
|
231
|
+
f"{spec.name!r}: a time chunk spans {chunks[t] * step / np.timedelta64(1, 'D'):,.0f} "
|
|
232
|
+
f"days; dynamical.org keeps them to a year or less ({YEAR_RULE}). "
|
|
233
|
+
"Pass a smaller raw_chunk_bytes to shorten them",
|
|
234
|
+
skip_file_prefixes=_PKG,
|
|
235
|
+
)
|
|
236
|
+
enc = Encoding(
|
|
237
|
+
chunks=chunks,
|
|
238
|
+
compressors=tuple(compressors),
|
|
239
|
+
)
|
|
240
|
+
if shards is not None:
|
|
241
|
+
enc["shards"] = shards
|
|
242
|
+
encoding[spec.name] = enc
|
|
243
|
+
if skipped:
|
|
244
|
+
warnings.warn(
|
|
245
|
+
f"no spatial dim in {skipped}, left to Xarray defaults; "
|
|
246
|
+
"pass spatial_dims= if their dims have other names",
|
|
247
|
+
skip_file_prefixes=_PKG,
|
|
248
|
+
)
|
|
249
|
+
return encoding
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
REPORT_HEAD = (
|
|
253
|
+
"var",
|
|
254
|
+
"chunks",
|
|
255
|
+
"shards",
|
|
256
|
+
"objects",
|
|
257
|
+
"slice chunks",
|
|
258
|
+
"series chunks",
|
|
259
|
+
)
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
@dataclass(frozen=True)
|
|
263
|
+
class Report:
|
|
264
|
+
"""Per-variable ``Costs``.
|
|
265
|
+
|
|
266
|
+
A notebook shows one expandable view per variable (chunk-grid cube, sizes,
|
|
267
|
+
read costs, encoding); a terminal shows a Markdown table. The numbers are in
|
|
268
|
+
``costs`` and ``to_pandas()``.
|
|
269
|
+
"""
|
|
270
|
+
|
|
271
|
+
costs: dict[str, Costs]
|
|
272
|
+
encoding: Mapping[str, Mapping[str, Any]]
|
|
273
|
+
compression_ratio: float
|
|
274
|
+
specs: Mapping[str, VarSpec]
|
|
275
|
+
|
|
276
|
+
def _rows(self) -> list[tuple[str, ...]]:
|
|
277
|
+
rows = []
|
|
278
|
+
for name, c in self.costs.items():
|
|
279
|
+
shards = self.encoding[name].get("shards")
|
|
280
|
+
rows.append(
|
|
281
|
+
(
|
|
282
|
+
name,
|
|
283
|
+
"x".join(map(str, self.encoding[name]["chunks"])),
|
|
284
|
+
"x".join(map(str, shards)) if shards else "-",
|
|
285
|
+
f"{c.objects:,}",
|
|
286
|
+
f"{c.slice_chunks:,}",
|
|
287
|
+
f"{c.series_chunks:,}",
|
|
288
|
+
)
|
|
289
|
+
)
|
|
290
|
+
return rows
|
|
291
|
+
|
|
292
|
+
def __repr__(self) -> str:
|
|
293
|
+
"""A Markdown table, readable in a terminal and pasteable into GitHub."""
|
|
294
|
+
rows = [REPORT_HEAD, *self._rows()]
|
|
295
|
+
widths = [max(len(r[i]) for r in rows) for i in range(len(REPORT_HEAD))]
|
|
296
|
+
rows.insert(1, tuple("-" * w for w in widths))
|
|
297
|
+
lines = [
|
|
298
|
+
"| " + " | ".join(v.ljust(w) for v, w in zip(r, widths)) + " |"
|
|
299
|
+
for r in rows
|
|
300
|
+
]
|
|
301
|
+
return "\n".join(lines)
|
|
302
|
+
|
|
303
|
+
def to_pandas(self) -> pd.DataFrame:
|
|
304
|
+
"""One row per variable, unformatted numbers."""
|
|
305
|
+
import pandas as pd
|
|
306
|
+
|
|
307
|
+
rows = {
|
|
308
|
+
name: {
|
|
309
|
+
"chunks": self.encoding[name]["chunks"],
|
|
310
|
+
"shards": self.encoding[name].get("shards"),
|
|
311
|
+
**asdict(c),
|
|
312
|
+
}
|
|
313
|
+
for name, c in self.costs.items()
|
|
314
|
+
}
|
|
315
|
+
return pd.DataFrame.from_dict(rows, orient="index").rename_axis("var")
|
|
316
|
+
|
|
317
|
+
def _repr_html_(self) -> str:
|
|
318
|
+
"""One collapsible row per variable, like the Xarray repr."""
|
|
319
|
+
from spacetimer._html import REPORT_CSS, _var_html # lazy: _html imports core
|
|
320
|
+
|
|
321
|
+
rows = "".join(
|
|
322
|
+
_var_html(
|
|
323
|
+
self.specs[name],
|
|
324
|
+
self.encoding[name],
|
|
325
|
+
c,
|
|
326
|
+
ratio=self.compression_ratio,
|
|
327
|
+
opened=i == 0,
|
|
328
|
+
)
|
|
329
|
+
for i, (name, c) in enumerate(self.costs.items())
|
|
330
|
+
)
|
|
331
|
+
return f'<div class="st-report">{REPORT_CSS}{rows}</div>'
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def report(
|
|
335
|
+
data: Data,
|
|
336
|
+
encoding: Mapping[str, Mapping[str, Any]] | None = None,
|
|
337
|
+
*,
|
|
338
|
+
compression_ratio: float = 0.2,
|
|
339
|
+
spatial_dims: Collection[str] = SPATIAL_DIMS,
|
|
340
|
+
time_dim: str | None = None,
|
|
341
|
+
) -> Report:
|
|
342
|
+
"""Estimate read and storage costs of ``encoding`` (any, not only ours).
|
|
343
|
+
|
|
344
|
+
Each entry needs ``chunks``; ``shards`` and ``compressors`` are optional, so
|
|
345
|
+
a hand-written dict or an array's ``.encoding`` works. ``encoding=None``
|
|
346
|
+
reports the layout already stored in a ``zarr.Group``, or in a Dataset
|
|
347
|
+
opened from Zarr.
|
|
348
|
+
"""
|
|
349
|
+
_check_ratio(compression_ratio)
|
|
350
|
+
spatial_dims, cf_time = _roles(data, spatial_dims)
|
|
351
|
+
all_specs = _specs(data)
|
|
352
|
+
if encoding is None:
|
|
353
|
+
encoding = _stored_encoding(data, [s.name for s in all_specs])
|
|
354
|
+
out: dict[str, Costs] = {}
|
|
355
|
+
specs: dict[str, VarSpec] = {}
|
|
356
|
+
for spec in all_specs:
|
|
357
|
+
if spec.name not in encoding:
|
|
358
|
+
continue
|
|
359
|
+
enc = encoding[spec.name]
|
|
360
|
+
if "chunks" not in enc:
|
|
361
|
+
raise ValueError(f"{spec.name!r}: encoding has no chunks")
|
|
362
|
+
for key in ("chunks", "shards"):
|
|
363
|
+
if (grid := enc.get(key)) is None:
|
|
364
|
+
continue
|
|
365
|
+
if isinstance(grid, Mapping) or any(
|
|
366
|
+
not isinstance(n, int) or n < 1 for n in grid
|
|
367
|
+
):
|
|
368
|
+
raise ValueError(
|
|
369
|
+
f"{spec.name!r}: {key} must be a tuple of positive ints, one per "
|
|
370
|
+
f"dim of {spec.dims}; got {grid!r}"
|
|
371
|
+
)
|
|
372
|
+
if len(grid) != len(spec.shape):
|
|
373
|
+
raise ValueError(
|
|
374
|
+
f"{spec.name!r}: {key} {tuple(grid)} has {len(grid)} dims, "
|
|
375
|
+
f"data has {len(spec.shape)} {spec.dims}"
|
|
376
|
+
)
|
|
377
|
+
spatial = [i for i, d in enumerate(spec.dims) if d in spatial_dims]
|
|
378
|
+
t = _time_axis(spec, spatial, time_dim, cf_time)
|
|
379
|
+
out[spec.name] = _costs(
|
|
380
|
+
spec, enc["chunks"], enc.get("shards"), spatial, t, compression_ratio
|
|
381
|
+
)
|
|
382
|
+
specs[spec.name] = spec
|
|
383
|
+
if missing := sorted(set(encoding) - set(out)):
|
|
384
|
+
warnings.warn(
|
|
385
|
+
f"encoding names {missing}, not found in data", skip_file_prefixes=_PKG
|
|
386
|
+
)
|
|
387
|
+
return Report(out, encoding, compression_ratio, specs)
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
def _stored_encoding(data: Data, names: list[str]) -> dict[str, dict[str, Any]]:
|
|
391
|
+
"""Each variable's stored layout: Zarr array metadata, or Xarray's ``.encoding``."""
|
|
392
|
+
if isinstance(data, zarr.Group):
|
|
393
|
+
out: dict[str, dict[str, Any]] = {}
|
|
394
|
+
for name in names:
|
|
395
|
+
arr = data[name]
|
|
396
|
+
assert isinstance(arr, zarr.Array)
|
|
397
|
+
out[name] = {"chunks": arr.chunks, "compressors": tuple(arr.compressors)}
|
|
398
|
+
if arr.shards is not None:
|
|
399
|
+
out[name]["shards"] = arr.shards
|
|
400
|
+
return out
|
|
401
|
+
if isinstance(data, xr.Dataset):
|
|
402
|
+
keys = ("chunks", "shards", "compressors")
|
|
403
|
+
out = {
|
|
404
|
+
n: {k: v for k in keys if (v := data[n].encoding.get(k)) is not None}
|
|
405
|
+
for n in names
|
|
406
|
+
}
|
|
407
|
+
if missing := [n for n, e in out.items() if "chunks" not in e]:
|
|
408
|
+
raise ValueError(
|
|
409
|
+
f"no stored chunks for {missing}; open the data from Zarr or pass "
|
|
410
|
+
"an encoding"
|
|
411
|
+
)
|
|
412
|
+
return out
|
|
413
|
+
raise TypeError("encoding=None needs a zarr.Group or a Dataset opened from Zarr")
|
|
414
|
+
|
|
415
|
+
|
|
416
|
+
def _check_ratio(ratio: float) -> None:
|
|
417
|
+
if not 0 < ratio <= 1:
|
|
418
|
+
raise ValueError(f"compression_ratio must be in (0, 1], got {ratio}")
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
def _specs(obj: Data) -> list[VarSpec]:
|
|
422
|
+
if isinstance(obj, xr.Dataset):
|
|
423
|
+
return [
|
|
424
|
+
VarSpec(str(n), tuple(map(str, v.dims)), v.shape, v.dtype, dict(v.attrs))
|
|
425
|
+
for n, v in obj.data_vars.items()
|
|
426
|
+
]
|
|
427
|
+
if isinstance(obj, zarr.Group):
|
|
428
|
+
arrays = dict(obj.arrays())
|
|
429
|
+
coords = _coord_names(obj, arrays)
|
|
430
|
+
specs, unnamed = [], []
|
|
431
|
+
for name, arr in arrays.items():
|
|
432
|
+
if (dims := _dims(arr)) is None:
|
|
433
|
+
unnamed.append(name)
|
|
434
|
+
continue
|
|
435
|
+
if dims and dims != (name,) and name not in coords:
|
|
436
|
+
specs.append(VarSpec(name, dims, arr.shape, arr.dtype, dict(arr.attrs)))
|
|
437
|
+
if unnamed:
|
|
438
|
+
warnings.warn(
|
|
439
|
+
f"no dimension names on {unnamed}, skipped", skip_file_prefixes=_PKG
|
|
440
|
+
)
|
|
441
|
+
return specs
|
|
442
|
+
if isinstance(obj, xr.DataArray): # iterating one would yield its slices
|
|
443
|
+
raise TypeError("pass a Dataset (da.to_dataset()), zarr.Group, or VarSpecs")
|
|
444
|
+
return list(obj)
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
def _dims(arr: zarr.Array) -> tuple[str, ...] | None:
|
|
448
|
+
"""Dimension names from v3 metadata or the v2 ``_ARRAY_DIMENSIONS`` attr."""
|
|
449
|
+
if arr.ndim == 0: # zarr stores no names for scalars like spatial_ref
|
|
450
|
+
return ()
|
|
451
|
+
names = getattr(arr.metadata, "dimension_names", None) or arr.attrs.get(
|
|
452
|
+
"_ARRAY_DIMENSIONS"
|
|
453
|
+
)
|
|
454
|
+
return tuple(map(str, names)) if isinstance(names, (list, tuple)) else None
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _coord_names(group: zarr.Group, arrays: Mapping[str, zarr.Array]) -> set[str]:
|
|
458
|
+
"""Non-dimension coords (e.g. 2-D lat/lon), as Xarray records them."""
|
|
459
|
+
return {
|
|
460
|
+
c
|
|
461
|
+
for attrs in (group.attrs, *(a.attrs for a in arrays.values()))
|
|
462
|
+
for c in str(attrs.get("coordinates", "")).split()
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
|
|
466
|
+
def _coords(obj: Data) -> list[tuple[str, tuple[str, ...], np.dtype, Mapping]]:
|
|
467
|
+
"""(name, dims, dtype, attrs) of each coordinate; none for ``VarSpec``s."""
|
|
468
|
+
if isinstance(obj, xr.Dataset):
|
|
469
|
+
return [
|
|
470
|
+
(str(n), tuple(map(str, c.dims)), c.dtype, c.attrs)
|
|
471
|
+
for n, c in obj.coords.items()
|
|
472
|
+
]
|
|
473
|
+
if isinstance(obj, zarr.Group):
|
|
474
|
+
arrays = dict(obj.arrays())
|
|
475
|
+
named = _coord_names(obj, arrays)
|
|
476
|
+
return [
|
|
477
|
+
(name, dims, arr.dtype, arr.attrs)
|
|
478
|
+
for name, arr in arrays.items()
|
|
479
|
+
if (dims := _dims(arr)) is not None and (dims == (name,) or name in named)
|
|
480
|
+
]
|
|
481
|
+
return []
|
|
482
|
+
|
|
483
|
+
|
|
484
|
+
def _roles(
|
|
485
|
+
data: Data, spatial_dims: Collection[str]
|
|
486
|
+
) -> tuple[Collection[str], set[str]]:
|
|
487
|
+
"""Add CF-marked spatial dims to the default names, and find CF time dims.
|
|
488
|
+
|
|
489
|
+
A coordinate is spatial by ``axis`` X/Y, a lat/lon/projection
|
|
490
|
+
``standard_name``, or degrees north/east ``units``; time by ``axis`` T,
|
|
491
|
+
``standard_name`` time, "since" ``units``, or a datetime dtype. Bounds
|
|
492
|
+
coordinates are skipped. Explicit ``spatial_dims`` are used as given.
|
|
493
|
+
"""
|
|
494
|
+
coords = _coords(data)
|
|
495
|
+
bounds = {str(a["bounds"]) for *_, a in coords if "bounds" in a}
|
|
496
|
+
spatial: set[str] = set()
|
|
497
|
+
time: set[str] = set()
|
|
498
|
+
for name, dims, dtype, attrs in coords:
|
|
499
|
+
if name in bounds:
|
|
500
|
+
continue
|
|
501
|
+
axis, sn, units = (
|
|
502
|
+
str(attrs.get(k, "")) for k in ("axis", "standard_name", "units")
|
|
503
|
+
)
|
|
504
|
+
if axis in ("X", "Y") or sn in CF_SPATIAL_NAMES or units in CF_DEGREES:
|
|
505
|
+
spatial.update(dims)
|
|
506
|
+
elif len(dims) == 1 and (
|
|
507
|
+
axis == "T"
|
|
508
|
+
or sn == "time"
|
|
509
|
+
or " since " in units
|
|
510
|
+
or np.issubdtype(dtype, np.datetime64)
|
|
511
|
+
):
|
|
512
|
+
time.update(dims)
|
|
513
|
+
if spatial_dims is SPATIAL_DIMS: # the default: names plus coordinate metadata
|
|
514
|
+
spatial_dims = SPATIAL_DIMS | spatial
|
|
515
|
+
return spatial_dims, time - set(spatial_dims)
|
|
516
|
+
|
|
517
|
+
|
|
518
|
+
def _time_steps(data: Data) -> dict[str, np.timedelta64]:
|
|
519
|
+
"""Spacing of each datetime index. A Dataset holds its indexes in memory; a
|
|
520
|
+
Group would need a data read, so it gets none."""
|
|
521
|
+
if not isinstance(data, xr.Dataset):
|
|
522
|
+
return {}
|
|
523
|
+
return {
|
|
524
|
+
str(d): v[1] - v[0]
|
|
525
|
+
for d, idx in data.indexes.items()
|
|
526
|
+
if len(v := np.asarray(idx)) > 1 and np.issubdtype(v.dtype, np.datetime64)
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
|
|
530
|
+
def _time_axis(
|
|
531
|
+
spec: VarSpec, spatial: list[int], time_dim: str | None, cf_time: Collection[str]
|
|
532
|
+
) -> int | None:
|
|
533
|
+
if time_dim is not None:
|
|
534
|
+
return spec.dims.index(time_dim) if time_dim in spec.dims else None
|
|
535
|
+
other = [i for i in range(len(spec.dims)) if i not in spatial]
|
|
536
|
+
# CF metadata first, then names; forecast (init_time x lead_time) takes init_time
|
|
537
|
+
by_cf = [i for i in other if spec.dims[i] in cf_time]
|
|
538
|
+
return next(iter(by_cf + [i for i in other if "time" in spec.dims[i]]), None)
|
|
539
|
+
|
|
540
|
+
|
|
541
|
+
def _iroot(x: int, n: int) -> int:
|
|
542
|
+
"""Floor of the nth root; the float root alone gives 32768 ** (1 / 3) == 31.99."""
|
|
543
|
+
r = round(x ** (1 / n))
|
|
544
|
+
return r if r**n <= x else r - 1
|
|
545
|
+
|
|
546
|
+
|
|
547
|
+
def _per_dim(chunks_per_shard: int, n_spatial: int) -> int:
|
|
548
|
+
k = chunks_per_shard
|
|
549
|
+
while k > 1 and k**n_spatial > MAX_INNER_CHUNKS:
|
|
550
|
+
k -= 1
|
|
551
|
+
return k
|
|
552
|
+
|
|
553
|
+
|
|
554
|
+
def _balanced(dim: int, ideal: int) -> int:
|
|
555
|
+
"""Chunk near ``ideal`` that splits ``dim`` evenly (topozarr calculate_chunk_size)."""
|
|
556
|
+
return dim if dim <= ideal else math.ceil(dim / math.ceil(dim / ideal))
|
|
557
|
+
|
|
558
|
+
|
|
559
|
+
def _fill_spatial(
|
|
560
|
+
shape: tuple[int, ...], spatial: list[int], budget: int
|
|
561
|
+
) -> dict[int, int]:
|
|
562
|
+
"""Square tiles of ``budget`` elements; dims smaller than the tile edge are
|
|
563
|
+
taken whole and their unused budget goes to the remaining dims."""
|
|
564
|
+
out: dict[int, int] = {}
|
|
565
|
+
todo = sorted(spatial, key=lambda i: shape[i])
|
|
566
|
+
while todo:
|
|
567
|
+
edge = _iroot(budget, len(todo))
|
|
568
|
+
if shape[todo[0]] > edge:
|
|
569
|
+
out.update({i: _balanced(shape[i], edge) for i in todo})
|
|
570
|
+
break
|
|
571
|
+
i = todo.pop(0)
|
|
572
|
+
out[i] = shape[i]
|
|
573
|
+
budget = max(1, budget // shape[i])
|
|
574
|
+
return out
|
|
575
|
+
|
|
576
|
+
|
|
577
|
+
def _balanced_edge(
|
|
578
|
+
shape: tuple[int, ...], spatial: list[int], t: int, budget: int
|
|
579
|
+
) -> int:
|
|
580
|
+
"""Edge where map reads (prod(S) / e^n) equal series reads (T e^n / budget).
|
|
581
|
+
|
|
582
|
+
Their product prod(S) T / budget is fixed by the chunk size, so equal is
|
|
583
|
+
also the smallest worst case.
|
|
584
|
+
"""
|
|
585
|
+
n = len(spatial)
|
|
586
|
+
maps = math.prod(shape[i] for i in spatial)
|
|
587
|
+
return max(MIN_EDGE, _iroot(maps * budget // shape[t], 2 * n))
|
|
588
|
+
|
|
589
|
+
|
|
590
|
+
def _layout(
|
|
591
|
+
spec: VarSpec,
|
|
592
|
+
preset: Preset,
|
|
593
|
+
raw_chunk_bytes: int,
|
|
594
|
+
chunks_per_shard: int | None,
|
|
595
|
+
spatial: list[int],
|
|
596
|
+
t: int | None,
|
|
597
|
+
) -> tuple[tuple[int, ...], tuple[int, ...] | None]:
|
|
598
|
+
ndim = len(spec.shape)
|
|
599
|
+
other = [i for i in range(ndim) if i not in spatial]
|
|
600
|
+
chunks = [1] * ndim
|
|
601
|
+
budget = max(1, raw_chunk_bytes // spec.dtype.itemsize) # elements per chunk
|
|
602
|
+
|
|
603
|
+
edge = preset.spatial_edge
|
|
604
|
+
if edge == "auto" and t is not None:
|
|
605
|
+
edge = _balanced_edge(spec.shape, spatial, t, budget)
|
|
606
|
+
if isinstance(edge, int) and t is not None:
|
|
607
|
+
# fixed-edge tiles first, then time takes what they leave
|
|
608
|
+
fixed = edge ** len(spatial)
|
|
609
|
+
tile = _fill_spatial(spec.shape, spatial, fixed)
|
|
610
|
+
chunks[t] = min(spec.shape[t], max(1, budget // math.prod(tile.values())))
|
|
611
|
+
# keep those tiles; they only grow when time is too short to use the budget
|
|
612
|
+
budget = max(budget // chunks[t], min(budget, fixed))
|
|
613
|
+
for i, c in _fill_spatial(spec.shape, spatial, budget).items():
|
|
614
|
+
chunks[i] = c
|
|
615
|
+
|
|
616
|
+
if chunks_per_shard is None:
|
|
617
|
+
return tuple(chunks), None
|
|
618
|
+
|
|
619
|
+
k = _per_dim(chunks_per_shard, len(spatial))
|
|
620
|
+
shards = list(chunks)
|
|
621
|
+
for i in spatial: # ceil: the last shard may overhang the array, as dynamical's do
|
|
622
|
+
shards[i] = chunks[i] * min(k, -(-spec.shape[i] // chunks[i]))
|
|
623
|
+
|
|
624
|
+
# spend leftover shard budget on non-spatial dims, innermost first (topozarr)
|
|
625
|
+
if k > 1:
|
|
626
|
+
target = raw_chunk_bytes * k ** len(spatial) // spec.dtype.itemsize
|
|
627
|
+
inner = math.prod(s // c for s, c in zip(shards, chunks))
|
|
628
|
+
headroom = min(target // math.prod(shards), MAX_INNER_CHUNKS // inner)
|
|
629
|
+
for i in reversed(other):
|
|
630
|
+
if headroom <= 1:
|
|
631
|
+
break
|
|
632
|
+
mult = min(headroom, -(-spec.shape[i] // chunks[i]))
|
|
633
|
+
shards[i] = chunks[i] * mult
|
|
634
|
+
headroom //= mult
|
|
635
|
+
return tuple(chunks), tuple(shards)
|
|
636
|
+
|
|
637
|
+
|
|
638
|
+
def _costs(
|
|
639
|
+
spec: VarSpec,
|
|
640
|
+
chunks: tuple[int, ...],
|
|
641
|
+
shards: tuple[int, ...] | None,
|
|
642
|
+
spatial: list[int],
|
|
643
|
+
t: int | None,
|
|
644
|
+
ratio: float,
|
|
645
|
+
) -> Costs:
|
|
646
|
+
def count(axes: Iterable[int], grid: tuple[int, ...]) -> int:
|
|
647
|
+
return math.prod(math.ceil(spec.shape[i] / grid[i]) for i in axes)
|
|
648
|
+
|
|
649
|
+
chunk_mib = math.prod(chunks) * spec.dtype.itemsize * ratio / MiB
|
|
650
|
+
slice_chunks = count(spatial, chunks)
|
|
651
|
+
series_chunks = count([t], chunks) if t is not None else 1
|
|
652
|
+
return Costs(
|
|
653
|
+
chunk_mib=chunk_mib,
|
|
654
|
+
shard_mib=chunk_mib * (math.prod(shards) / math.prod(chunks))
|
|
655
|
+
if shards
|
|
656
|
+
else None,
|
|
657
|
+
objects=count(range(len(spec.shape)), shards or chunks),
|
|
658
|
+
slice_chunks=slice_chunks,
|
|
659
|
+
slice_mib=slice_chunks * chunk_mib,
|
|
660
|
+
series_chunks=series_chunks,
|
|
661
|
+
series_mib=series_chunks * chunk_mib,
|
|
662
|
+
)
|
|
663
|
+
|
|
664
|
+
|
|
665
|
+
@xr.register_dataset_accessor("spacetimer")
|
|
666
|
+
class SpacetimerAccessor:
|
|
667
|
+
"""``ds.spacetimer.recommend("time")``.
|
|
668
|
+
|
|
669
|
+
Signatures are copied from the functions so editors can autocomplete them;
|
|
670
|
+
``test_accessor_signatures_match`` fails if they drift.
|
|
671
|
+
"""
|
|
672
|
+
|
|
673
|
+
def __init__(self, ds: xr.Dataset) -> None:
|
|
674
|
+
self._ds = ds
|
|
675
|
+
|
|
676
|
+
def recommend(
|
|
677
|
+
self,
|
|
678
|
+
use_case: UseCase,
|
|
679
|
+
*,
|
|
680
|
+
chunks_per_shard: int | None = None,
|
|
681
|
+
sharding: bool = True,
|
|
682
|
+
compression_ratio: float = 0.2,
|
|
683
|
+
raw_chunk_bytes: int | None = None,
|
|
684
|
+
spatial_dims: Collection[str] = SPATIAL_DIMS,
|
|
685
|
+
time_dim: str | None = None,
|
|
686
|
+
compressors: Sequence[BytesBytesCodec] = DEFAULT_COMPRESSORS,
|
|
687
|
+
) -> dict[str, Encoding]:
|
|
688
|
+
"""See ``spacetimer.recommend``."""
|
|
689
|
+
return recommend(
|
|
690
|
+
self._ds,
|
|
691
|
+
use_case,
|
|
692
|
+
chunks_per_shard=chunks_per_shard,
|
|
693
|
+
sharding=sharding,
|
|
694
|
+
compression_ratio=compression_ratio,
|
|
695
|
+
raw_chunk_bytes=raw_chunk_bytes,
|
|
696
|
+
spatial_dims=spatial_dims,
|
|
697
|
+
time_dim=time_dim,
|
|
698
|
+
compressors=compressors,
|
|
699
|
+
)
|
|
700
|
+
|
|
701
|
+
def bitround(self, *, keepbits: Mapping[str, int] | None = None) -> xr.Dataset:
|
|
702
|
+
"""``apply_keepbits``; ``keepbits=None`` uses ``convention_keepbits``."""
|
|
703
|
+
from spacetimer.bitround import apply_keepbits, convention_keepbits
|
|
704
|
+
|
|
705
|
+
if keepbits is None:
|
|
706
|
+
keepbits = convention_keepbits(self._ds)
|
|
707
|
+
return apply_keepbits(self._ds, keepbits=keepbits)
|
|
708
|
+
|
|
709
|
+
def report(
|
|
710
|
+
self,
|
|
711
|
+
encoding: Mapping[str, Mapping[str, Any]] | None = None,
|
|
712
|
+
*,
|
|
713
|
+
compression_ratio: float = 0.2,
|
|
714
|
+
spatial_dims: Collection[str] = SPATIAL_DIMS,
|
|
715
|
+
time_dim: str | None = None,
|
|
716
|
+
) -> Report:
|
|
717
|
+
"""See ``spacetimer.report``."""
|
|
718
|
+
return report(
|
|
719
|
+
self._ds,
|
|
720
|
+
encoding,
|
|
721
|
+
compression_ratio=compression_ratio,
|
|
722
|
+
spatial_dims=spatial_dims,
|
|
723
|
+
time_dim=time_dim,
|
|
724
|
+
)
|