spacetimer 0.1.0__tar.gz → 0.2.0__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: spacetimer
3
- Version: 0.1.0
3
+ Version: 0.2.0
4
4
  Summary: Chunk, shard, and codec recommendations for Zarr, by use case
5
5
  Author: norlandrhagen
6
6
  Author-email: norlandrhagen <norlandrhagen@gmail.com>
@@ -8,7 +8,7 @@ License-Expression: MIT
8
8
  License-File: LICENSE
9
9
  Requires-Dist: numpy
10
10
  Requires-Dist: xarray>=2025.9.0
11
- Requires-Dist: zarr>=3.2.1
11
+ Requires-Dist: zarr>=3.3
12
12
  Requires-Python: >=3.12
13
13
  Project-URL: Documentation, https://norlandrhagen.github.io/spacetimer/
14
14
  Project-URL: Repository, https://github.com/norlandrhagen/spacetimer
@@ -17,7 +17,7 @@ Description-Content-Type: text/markdown
17
17
 
18
18
  # spacetimer
19
19
 
20
- Chunk and shard recommendations for Zarr, based on how people will read your data: time series, maps, a mix of both, or web tiles. It reads only metadata and returns an `encoding` dict for `to_zarr`.
20
+ Don't want to think about your Zarr chunking scheme? `spacetimer` gives you _geospatial-focused_ chunk and shard recommendations for Zarr (or Icechunk) stores, based on how people will read your data: time series, maps, a mix of both, or web tiles. It reads only metadata and returns an `encoding` dict for `to_zarr`.
21
21
 
22
22
  ## Install
23
23
 
@@ -31,7 +31,9 @@ Or with pip: `pip install spacetimer`.
31
31
 
32
32
  ```python
33
33
  import spacetimer
34
+ import xarray as xr
34
35
 
36
+ ds = xr.open_zarr("in.zarr")
35
37
  encoding = spacetimer.recommend(ds, "time") # or "space", "balanced", "web"
36
38
  spacetimer.report(ds, encoding) # chunks read per map and per time series
37
39
  ds.to_zarr("out.zarr", encoding=encoding)
@@ -39,6 +41,10 @@ ds.to_zarr("out.zarr", encoding=encoding)
39
41
 
40
42
  See the [docs](https://norlandrhagen.github.io/spacetimer/) for options, bitrounding, and how to read the report.
41
43
 
44
+ ## Credits
45
+
46
+ spacetimer builds on the chunking, sharding, and bitrounding work in [dynamical.org's reformatters](https://github.com/dynamical-org/reformatters). Thanks to the dynamical.org team for sharing it openly.
47
+
42
48
  ## License
43
49
 
44
50
  [MIT](https://github.com/norlandrhagen/spacetimer/blob/main/LICENSE)
@@ -0,0 +1,33 @@
1
+ # spacetimer
2
+
3
+ Don't want to think about your Zarr chunking scheme? `spacetimer` gives you _geospatial-focused_ chunk and shard recommendations for Zarr (or Icechunk) stores, based on how people will read your data: time series, maps, a mix of both, or web tiles. It reads only metadata and returns an `encoding` dict for `to_zarr`.
4
+
5
+ ## Install
6
+
7
+ ```bash
8
+ uv add spacetimer
9
+ ```
10
+
11
+ Or with pip: `pip install spacetimer`.
12
+
13
+ ## Usage
14
+
15
+ ```python
16
+ import spacetimer
17
+ import xarray as xr
18
+
19
+ ds = xr.open_zarr("in.zarr")
20
+ encoding = spacetimer.recommend(ds, "time") # or "space", "balanced", "web"
21
+ spacetimer.report(ds, encoding) # chunks read per map and per time series
22
+ ds.to_zarr("out.zarr", encoding=encoding)
23
+ ```
24
+
25
+ See the [docs](https://norlandrhagen.github.io/spacetimer/) for options, bitrounding, and how to read the report.
26
+
27
+ ## Credits
28
+
29
+ spacetimer builds on the chunking, sharding, and bitrounding work in [dynamical.org's reformatters](https://github.com/dynamical-org/reformatters). Thanks to the dynamical.org team for sharing it openly.
30
+
31
+ ## License
32
+
33
+ [MIT](https://github.com/norlandrhagen/spacetimer/blob/main/LICENSE)
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "spacetimer"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Chunk, shard, and codec recommendations for Zarr, by use case"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -9,7 +9,7 @@ requires-python = ">=3.12"
9
9
  dependencies = [
10
10
  "numpy",
11
11
  "xarray>=2025.9.0",
12
- "zarr>=3.2.1",
12
+ "zarr>=3.3",
13
13
  ]
14
14
 
15
15
  [[project.authors]]
@@ -29,8 +29,10 @@ build-backend = "uv_build"
29
29
  bench = [
30
30
  "coiled>=1.135.6",
31
31
  "obstore>=0.12.1",
32
+ "zarrs>=0.2.3",
32
33
  ]
33
34
  dev = [
35
+ { include-group = "bench" },
34
36
  "dask>=2025.1.0",
35
37
  "hypothesis>=6.150.0",
36
38
  "icechunk>=1.1.19",
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "spacetimer"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "Chunk, shard, and codec recommendations for Zarr, by use case"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -12,7 +12,7 @@ requires-python = ">=3.12"
12
12
  dependencies = [
13
13
  "numpy",
14
14
  "xarray>=2025.9.0",
15
- "zarr>=3.2.1",
15
+ "zarr>=3.3",
16
16
  ]
17
17
 
18
18
  [project.urls]
@@ -28,8 +28,11 @@ build-backend = "uv_build"
28
28
  bench = [
29
29
  "coiled>=1.135.6",
30
30
  "obstore>=0.12.1",
31
+ "zarrs>=0.2.3",
31
32
  ]
32
33
  dev = [
34
+ # coiled run installs only dev, so bench rides along
35
+ { include-group = "bench" },
33
36
  "dask>=2025.1.0",
34
37
  "hypothesis>=6.150.0",
35
38
  "icechunk>=1.1.19",
@@ -28,6 +28,12 @@ YEAR_RULE = (
28
28
  "cb7d15bfe5dfba501ed383041d141444d6ee7009/src/scripts/chunk_shard_size.py#L330-L339"
29
29
  )
30
30
  SPATIAL_DIMS = frozenset({"x", "y", "lat", "lon", "latitude", "longitude"})
31
+ # forecasts follow dynamical: one init_time per chunk, all members together, series along lead
32
+ LEAD_DIMS = frozenset({"lead_time", "step", "forecast_period"})
33
+ ENSEMBLE_DIMS = frozenset(
34
+ {"ensemble_member", "member", "member_id", "realization", "number"}
35
+ )
36
+ DEFAULT_RATIO = 0.2
31
37
  # CF coordinate metadata that marks a coordinate's dims as spatial
32
38
  CF_SPATIAL_NAMES = frozenset(
33
39
  {
@@ -78,21 +84,24 @@ class Preset:
78
84
  chunk_bytes: int
79
85
  """Target chunk size, measured as ``basis`` says."""
80
86
  basis: SizeBasis
81
- spatial_edge: int | Literal["auto"] | None
87
+ spatial_edge: int | Literal["auto", "full"] | None
82
88
  """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."""
89
+ where one map and one time series read the same number of chunks. ``"full"``:
90
+ the largest map tile that fits, time takes what is left. ``None``: one time
91
+ step per chunk."""
85
92
  chunks_per_shard: int
86
93
  """Default chunks per shard along each spatial dim."""
87
94
 
88
95
 
89
96
  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),
97
+ # dynamical.org reformatters, analysis mode: ~3.5 MiB compressed, 32x32 tiles.
98
+ # 4 chunks per shard, not dynamical's 8: zarr-python reads a fully touched shard
99
+ # in one GET, so on S3 a map read over 6 big shards took 2.4 s, over 15 0.9 s
100
+ UseCase.TIME: Preset(int(3.5 * MiB), SizeBasis.COMPRESSED, 32, 4),
101
+ # same byte target: the largest map tile that fits, time takes the rest
102
+ UseCase.SPACE: Preset(int(3.5 * MiB), SizeBasis.COMPRESSED, "full", 4),
94
103
  # 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),
104
+ UseCase.BALANCED: Preset(int(3.5 * MiB), SizeBasis.COMPRESSED, "auto", 4),
96
105
  # topozarr: 512 KiB raw tiles, 4x4 chunks per shard
97
106
  UseCase.WEB: Preset(512 * 1024, SizeBasis.RAW, None, 4),
98
107
  }
@@ -162,7 +171,7 @@ def recommend(
162
171
  *,
163
172
  chunks_per_shard: int | None = None,
164
173
  sharding: bool = True,
165
- compression_ratio: float = 0.2,
174
+ compression_ratio: float | Mapping[str, float] = DEFAULT_RATIO,
166
175
  raw_chunk_bytes: int | None = None,
167
176
  spatial_dims: Collection[str] = SPATIAL_DIMS,
168
177
  time_dim: str | None = None,
@@ -175,35 +184,31 @@ def recommend(
175
184
  uncompressed size. Chunks never exceed the current shape, so for a dataset
176
185
  you will append to, pass ``VarSpec``s with the final shape. ``compressors``
177
186
  replaces the default codec and does not change chunk sizes; pass a matching
178
- ``compression_ratio`` if yours compresses differently.
187
+ ``compression_ratio`` if yours compresses differently; a ``{var: ratio}``
188
+ mapping sets it per variable, and others use 0.2.
179
189
  """
180
190
  use_case = UseCase(use_case)
181
191
  preset = PRESETS[use_case]
182
- _check_ratio(compression_ratio)
183
192
  if not sharding and chunks_per_shard is not None:
184
193
  raise ValueError("chunks_per_shard has no effect with sharding=False")
185
194
  if chunks_per_shard is not None and chunks_per_shard < 1:
186
195
  raise ValueError(f"chunks_per_shard must be >= 1, got {chunks_per_shard}")
187
196
  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
197
 
195
198
  spatial_dims, cf_time = _roles(data, spatial_dims)
196
199
  steps = _time_steps(data)
197
200
  encoding: dict[str, Encoding] = {}
198
201
  skipped: list[str] = []
199
- for spec in _specs(data):
202
+ all_specs = _specs(data)
203
+ _check_ratio(compression_ratio, [s.name for s in all_specs])
204
+ for spec in all_specs:
200
205
  spatial = [i for i, d in enumerate(spec.dims) if d in spatial_dims]
201
206
  if not spatial:
202
207
  skipped.append(spec.name)
203
208
  continue
204
209
  t = _time_axis(spec, spatial, time_dim, cf_time)
205
210
  if (
206
- preset.spatial_edge is not None
211
+ preset.spatial_edge not in (None, "full")
207
212
  and t is None
208
213
  and len(spatial) < len(spec.dims)
209
214
  ):
@@ -221,7 +226,13 @@ def recommend(
221
226
  f"to keep a shard at or under {MAX_INNER_CHUNKS} chunks",
222
227
  skip_file_prefixes=_PKG,
223
228
  )
224
- chunks, shards = _layout(spec, preset, raw_chunk_bytes, cps, spatial, t)
229
+ if (target := raw_chunk_bytes) is None:
230
+ target = (
231
+ preset.chunk_bytes
232
+ if preset.basis is SizeBasis.RAW
233
+ else int(preset.chunk_bytes / _ratio(compression_ratio, spec.name))
234
+ )
235
+ chunks, shards = _layout(spec, preset, target, cps, spatial, t)
225
236
  if (
226
237
  t is not None
227
238
  and (step := steps.get(spec.dims[t])) is not None
@@ -270,7 +281,7 @@ class Report:
270
281
 
271
282
  costs: dict[str, Costs]
272
283
  encoding: Mapping[str, Mapping[str, Any]]
273
- compression_ratio: float
284
+ compression_ratio: float | Mapping[str, float]
274
285
  specs: Mapping[str, VarSpec]
275
286
 
276
287
  def _rows(self) -> list[tuple[str, ...]]:
@@ -323,7 +334,7 @@ class Report:
323
334
  self.specs[name],
324
335
  self.encoding[name],
325
336
  c,
326
- ratio=self.compression_ratio,
337
+ ratio=_ratio(self.compression_ratio, name),
327
338
  opened=i == 0,
328
339
  )
329
340
  for i, (name, c) in enumerate(self.costs.items())
@@ -335,7 +346,7 @@ def report(
335
346
  data: Data,
336
347
  encoding: Mapping[str, Mapping[str, Any]] | None = None,
337
348
  *,
338
- compression_ratio: float = 0.2,
349
+ compression_ratio: float | Mapping[str, float] = DEFAULT_RATIO,
339
350
  spatial_dims: Collection[str] = SPATIAL_DIMS,
340
351
  time_dim: str | None = None,
341
352
  ) -> Report:
@@ -346,9 +357,9 @@ def report(
346
357
  reports the layout already stored in a ``zarr.Group``, or in a Dataset
347
358
  opened from Zarr.
348
359
  """
349
- _check_ratio(compression_ratio)
350
360
  spatial_dims, cf_time = _roles(data, spatial_dims)
351
361
  all_specs = _specs(data)
362
+ _check_ratio(compression_ratio, [s.name for s in all_specs])
352
363
  if encoding is None:
353
364
  encoding = _stored_encoding(data, [s.name for s in all_specs])
354
365
  out: dict[str, Costs] = {}
@@ -377,7 +388,12 @@ def report(
377
388
  spatial = [i for i, d in enumerate(spec.dims) if d in spatial_dims]
378
389
  t = _time_axis(spec, spatial, time_dim, cf_time)
379
390
  out[spec.name] = _costs(
380
- spec, enc["chunks"], enc.get("shards"), spatial, t, compression_ratio
391
+ spec,
392
+ enc["chunks"],
393
+ enc.get("shards"),
394
+ spatial,
395
+ t,
396
+ _ratio(compression_ratio, spec.name),
381
397
  )
382
398
  specs[spec.name] = spec
383
399
  if missing := sorted(set(encoding) - set(out)):
@@ -413,9 +429,19 @@ def _stored_encoding(data: Data, names: list[str]) -> dict[str, dict[str, Any]]:
413
429
  raise TypeError("encoding=None needs a zarr.Group or a Dataset opened from Zarr")
414
430
 
415
431
 
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}")
432
+ def _check_ratio(ratio: float | Mapping[str, float], names: list[str]) -> None:
433
+ for r in ratio.values() if isinstance(ratio, Mapping) else [ratio]:
434
+ if not 0 < r <= 1:
435
+ raise ValueError(f"compression_ratio must be in (0, 1], got {r}")
436
+ if isinstance(ratio, Mapping) and (missing := sorted(set(ratio) - set(names))):
437
+ warnings.warn(
438
+ f"compression_ratio names {missing}, not found in data",
439
+ skip_file_prefixes=_PKG,
440
+ )
441
+
442
+
443
+ def _ratio(ratio: float | Mapping[str, float], name: str) -> float:
444
+ return ratio.get(name, DEFAULT_RATIO) if isinstance(ratio, Mapping) else ratio
419
445
 
420
446
 
421
447
  def _specs(obj: Data) -> list[VarSpec]:
@@ -533,9 +559,11 @@ def _time_axis(
533
559
  if time_dim is not None:
534
560
  return spec.dims.index(time_dim) if time_dim in spec.dims else None
535
561
  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
562
+ # forecasts read series along lead time; then CF metadata, then names
563
+ lead = [i for i in other if spec.dims[i] in LEAD_DIMS]
537
564
  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)
565
+ by_name = [i for i in other if "time" in spec.dims[i]]
566
+ return next(iter(lead + by_cf + by_name), None)
539
567
 
540
568
 
541
569
  def _iroot(x: int, n: int) -> int:
@@ -599,6 +627,17 @@ def _layout(
599
627
  other = [i for i in range(ndim) if i not in spatial]
600
628
  chunks = [1] * ndim
601
629
  budget = max(1, raw_chunk_bytes // spec.dtype.itemsize) # elements per chunk
630
+ growable = other
631
+ if t is not None and spec.dims[t] in LEAD_DIMS:
632
+ # forecast: all members in one chunk, so one read serves the ensemble;
633
+ # map reads (space, web) usually want one member, so their chunks hold one
634
+ whole = preset.basis is not SizeBasis.RAW and preset.spatial_edge != "full"
635
+ for i in other:
636
+ if spec.dims[i] in ENSEMBLE_DIMS and whole:
637
+ chunks[i] = min(spec.shape[i], budget)
638
+ budget = max(1, budget // chunks[i])
639
+ # init_time and the like stay 1 per shard, so a new run writes new shards
640
+ growable = [i for i in other if i == t or spec.dims[i] in ENSEMBLE_DIMS]
602
641
 
603
642
  edge = preset.spatial_edge
604
643
  if edge == "auto" and t is not None:
@@ -612,6 +651,9 @@ def _layout(
612
651
  budget = max(budget // chunks[t], min(budget, fixed))
613
652
  for i, c in _fill_spatial(spec.shape, spatial, budget).items():
614
653
  chunks[i] = c
654
+ if edge == "full" and t is not None: # maps first, time fills what is left
655
+ tile = math.prod(chunks[i] for i in spatial)
656
+ chunks[t] = min(spec.shape[t], max(1, budget // tile))
615
657
 
616
658
  if chunks_per_shard is None:
617
659
  return tuple(chunks), None
@@ -626,7 +668,7 @@ def _layout(
626
668
  target = raw_chunk_bytes * k ** len(spatial) // spec.dtype.itemsize
627
669
  inner = math.prod(s // c for s, c in zip(shards, chunks))
628
670
  headroom = min(target // math.prod(shards), MAX_INNER_CHUNKS // inner)
629
- for i in reversed(other):
671
+ for i in reversed(growable):
630
672
  if headroom <= 1:
631
673
  break
632
674
  mult = min(headroom, -(-spec.shape[i] // chunks[i]))
@@ -679,7 +721,7 @@ class SpacetimerAccessor:
679
721
  *,
680
722
  chunks_per_shard: int | None = None,
681
723
  sharding: bool = True,
682
- compression_ratio: float = 0.2,
724
+ compression_ratio: float | Mapping[str, float] = DEFAULT_RATIO,
683
725
  raw_chunk_bytes: int | None = None,
684
726
  spatial_dims: Collection[str] = SPATIAL_DIMS,
685
727
  time_dim: str | None = None,
@@ -710,7 +752,7 @@ class SpacetimerAccessor:
710
752
  self,
711
753
  encoding: Mapping[str, Mapping[str, Any]] | None = None,
712
754
  *,
713
- compression_ratio: float = 0.2,
755
+ compression_ratio: float | Mapping[str, float] = DEFAULT_RATIO,
714
756
  spatial_dims: Collection[str] = SPATIAL_DIMS,
715
757
  time_dim: str | None = None,
716
758
  ) -> Report:
@@ -1,27 +0,0 @@
1
- # spacetimer
2
-
3
- Chunk and shard recommendations for Zarr, based on how people will read your data: time series, maps, a mix of both, or web tiles. It reads only metadata and returns an `encoding` dict for `to_zarr`.
4
-
5
- ## Install
6
-
7
- ```bash
8
- uv add spacetimer
9
- ```
10
-
11
- Or with pip: `pip install spacetimer`.
12
-
13
- ## Usage
14
-
15
- ```python
16
- import spacetimer
17
-
18
- encoding = spacetimer.recommend(ds, "time") # or "space", "balanced", "web"
19
- spacetimer.report(ds, encoding) # chunks read per map and per time series
20
- ds.to_zarr("out.zarr", encoding=encoding)
21
- ```
22
-
23
- See the [docs](https://norlandrhagen.github.io/spacetimer/) for options, bitrounding, and how to read the report.
24
-
25
- ## License
26
-
27
- [MIT](https://github.com/norlandrhagen/spacetimer/blob/main/LICENSE)
File without changes